diff --git a/Digital Assignment 1/assets/Banana.jpg b/Digital Assignment 1/assets/Banana.jpg new file mode 100644 index 000000000..d234c3299 Binary files /dev/null and b/Digital Assignment 1/assets/Banana.jpg differ diff --git a/Digital Assignment 1/assets/Black.jpg b/Digital Assignment 1/assets/Black.jpg new file mode 100644 index 000000000..d2fcf8540 Binary files /dev/null and b/Digital Assignment 1/assets/Black.jpg differ diff --git a/Digital Assignment 1/assets/Blue.jpg b/Digital Assignment 1/assets/Blue.jpg new file mode 100644 index 000000000..2e62a38d1 Binary files /dev/null and b/Digital Assignment 1/assets/Blue.jpg differ diff --git a/Digital Assignment 1/assets/BlueGray.jpg b/Digital Assignment 1/assets/BlueGray.jpg new file mode 100644 index 000000000..d8644bf23 Binary files /dev/null and b/Digital Assignment 1/assets/BlueGray.jpg differ diff --git a/Digital Assignment 1/assets/Brown.jpg b/Digital Assignment 1/assets/Brown.jpg new file mode 100644 index 000000000..052a34d74 Binary files /dev/null and b/Digital Assignment 1/assets/Brown.jpg differ diff --git a/Digital Assignment 1/assets/Cyan.jpg b/Digital Assignment 1/assets/Cyan.jpg new file mode 100644 index 000000000..340f379eb Binary files /dev/null and b/Digital Assignment 1/assets/Cyan.jpg differ diff --git a/Digital Assignment 1/assets/DarkGreen.jpg b/Digital Assignment 1/assets/DarkGreen.jpg new file mode 100644 index 000000000..2a21b842a Binary files /dev/null and b/Digital Assignment 1/assets/DarkGreen.jpg differ diff --git a/Digital Assignment 1/assets/Gray.jpg b/Digital Assignment 1/assets/Gray.jpg new file mode 100644 index 000000000..d2c66d4ef Binary files /dev/null and b/Digital Assignment 1/assets/Gray.jpg differ diff --git a/Digital Assignment 1/assets/Green.jpg b/Digital Assignment 1/assets/Green.jpg new file mode 100644 index 000000000..4f3747f0e Binary files /dev/null and b/Digital Assignment 1/assets/Green.jpg differ diff --git a/Digital Assignment 1/assets/HotPink.jpg b/Digital Assignment 1/assets/HotPink.jpg new file mode 100644 index 000000000..9241f074d Binary files /dev/null and b/Digital Assignment 1/assets/HotPink.jpg differ diff --git a/Digital Assignment 1/assets/Kargo.jpg b/Digital Assignment 1/assets/Kargo.jpg new file mode 100644 index 000000000..8c893958a Binary files /dev/null and b/Digital Assignment 1/assets/Kargo.jpg differ diff --git a/Digital Assignment 1/assets/Lips.jpg b/Digital Assignment 1/assets/Lips.jpg new file mode 100644 index 000000000..74c60637b Binary files /dev/null and b/Digital Assignment 1/assets/Lips.jpg differ diff --git a/Digital Assignment 1/assets/Maroon.jpg b/Digital Assignment 1/assets/Maroon.jpg new file mode 100644 index 000000000..23c20ffee Binary files /dev/null and b/Digital Assignment 1/assets/Maroon.jpg differ diff --git a/Digital Assignment 1/assets/OJ.jpg b/Digital Assignment 1/assets/OJ.jpg new file mode 100644 index 000000000..1bcc15cd9 Binary files /dev/null and b/Digital Assignment 1/assets/OJ.jpg differ diff --git a/Digital Assignment 1/assets/Pink.jpg b/Digital Assignment 1/assets/Pink.jpg new file mode 100644 index 000000000..1615844af Binary files /dev/null and b/Digital Assignment 1/assets/Pink.jpg differ diff --git a/Digital Assignment 1/assets/Purple.jpg b/Digital Assignment 1/assets/Purple.jpg new file mode 100644 index 000000000..344f55459 Binary files /dev/null and b/Digital Assignment 1/assets/Purple.jpg differ diff --git a/Digital Assignment 1/assets/Red.jpg b/Digital Assignment 1/assets/Red.jpg new file mode 100644 index 000000000..8945b8ea5 Binary files /dev/null and b/Digital Assignment 1/assets/Red.jpg differ diff --git a/Digital Assignment 1/assets/Sky.jpg b/Digital Assignment 1/assets/Sky.jpg new file mode 100644 index 000000000..85558e512 Binary files /dev/null and b/Digital Assignment 1/assets/Sky.jpg differ diff --git a/Digital Assignment 1/assets/Yellow.jpg b/Digital Assignment 1/assets/Yellow.jpg new file mode 100644 index 000000000..8e4957a46 Binary files /dev/null and b/Digital Assignment 1/assets/Yellow.jpg differ diff --git a/Digital Assignment 1/assets/phaser.png b/Digital Assignment 1/assets/phaser.png new file mode 100644 index 000000000..a37a23af6 Binary files /dev/null and b/Digital Assignment 1/assets/phaser.png differ diff --git a/Digital Assignment 1/assets/phaser_tiles.json b/Digital Assignment 1/assets/phaser_tiles.json new file mode 100644 index 000000000..523e0c8e4 --- /dev/null +++ b/Digital Assignment 1/assets/phaser_tiles.json @@ -0,0 +1,39 @@ +{ "height":6, + "layers":[ + { + "data":[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], + "height":6, + "name":"Ground", + "opacity":1, + "type":"tilelayer", + "visible":true, + "width":6, + "x":0, + "y":0 + }], + "orientation":"orthogonal", + "properties": + { + + }, + "tileheight":100, + "tilesets":[ + { + "firstgid":1, + "image":"C:\/Program Files (x86)\/Tiled\/examples\/tmw_desert_spacing.png", + "imageheight":607, + "imagewidth":607, + "margin":1, + "name":"Desert", + "properties": + { + + }, + "spacing":1, + "tileheight":100, + "tilewidth":100 + }], + "tilewidth":100, + "version":1, + "width":6 +} \ No newline at end of file diff --git a/Digital Assignment 1/assets/phaser_tiles.png b/Digital Assignment 1/assets/phaser_tiles.png new file mode 100644 index 000000000..9bea28f71 Binary files /dev/null and b/Digital Assignment 1/assets/phaser_tiles.png differ diff --git a/Digital Assignment 1/index.html b/Digital Assignment 1/index.html new file mode 100644 index 000000000..79d178a0a --- /dev/null +++ b/Digital Assignment 1/index.html @@ -0,0 +1,142 @@ + + + + + Memories of Kisses + + + + + + + +
+
+

Memories of Kisses

+ +
+ + diff --git a/Digital Assignment 1/js/main.js b/Digital Assignment 1/js/main.js new file mode 100644 index 000000000..2f51df6b1 --- /dev/null +++ b/Digital Assignment 1/js/main.js @@ -0,0 +1,302 @@ +//"use strict"; + +window.onload = function() { + // You can copy-and-paste the code from any of the examples at http://examples.phaser.io here. + // You will need to change the fourth parameter to "new Phaser.Game()" from + // 'phaser-example' to 'game', which is the id of the HTML element where we + // want the game to go. + // The assets (and code) can be found at: https://github.com/photonstorm/phaser/tree/master/examples/assets + // You will need to change the paths you pass to "game.load.image()" or any other + // loading functions to reflect where you are putting the assets. + // All loading functions will typically all be found inside "preload()". + + // mods by Patrick OReilly + // twitter: @pato_reilly + + var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'game', { preload: preload, create: create, update: update, render: render }); + + function preload() { + + game.load.tilemap('matching', 'assets/phaser_tiles.json', null, Phaser.Tilemap.TILED_JSON); + game.load.image('tiles', 'assets/phaser_tiles.png');//, 100, 100, -1, 1, 1); + } + + var timeCheck = 0; + var flipFlag = false; + + var startList = new Array(); + var squareList = new Array(); + + var masterCounter = 0; + var squareCounter = 0; + var attempt = 20; + var square1Num; + var square2Num; + var savedSquareX1; + var savedSquareY1; + var savedSquareX2; + var savedSquareY2; + + var map; + var tileset; + var layer; + + var marker; + var currentTile; + var currentTilePosition; + + var tileBack = 25; + var timesUp = '+'; + var tryAgain = '-'; + var youWin = '+'; + + var myCountdownSeconds; + + function create() { + + map = game.add.tilemap('matching'); + + map.addTilesetImage('Desert', 'tiles'); + //tileset = game.add.tileset('tiles') + + //layer = game.add.tilemapLayer(0, 0, 600, 600, tileset, map, 0); + layer = map.createLayer('Ground');//.tilemapLayer(0, 0, 600, 600, tileset, map, 0); + + //layer.resizeWorld(); + + marker = game.add.graphics(); + marker.lineStyle(2, 0x00FF00, 1); + marker.drawRect(0, 0, 100, 100); + + randomizeTiles(); + + } + + function update() { + + countDownTimer(); + + if (layer.getTileX(game.input.activePointer.worldX) <= 5) // to prevent the marker from going out of bounds + { + marker.x = layer.getTileX(game.input.activePointer.worldX) * 100; + marker.y = layer.getTileY(game.input.activePointer.worldY) * 100; + } + + if (flipFlag == true) + { + if (game.time.now - timeCheck > 500) + { + flipBack(); + flipFlag = false; + } + } + else + { + processClick(); + } + + if (attempt == 0 || myCountdownSeconds <= 0) + { + tryAgain = 'TRY AGAIN'; + game.paused = true; + } + } + + + function countDownTimer() { + + var timeLimit = 180 + + myTime = game.time.now; + mySeconds = parseInt(myTime/1000); + myCountdownSeconds = timeLimit - mySeconds; + + if (myCountdownSeconds <= 0) + { + // time is up + timesUp = 'Time is up!'; + myCountdownSeconds = 0; + + } + } + + function processClick() { + + currentTile = map.getTile(layer.getTileX(marker.x), layer.getTileY(marker.y)); + currentTilePosition = ((layer.getTileY(game.input.activePointer.worldY)+1)*6)-(6-(layer.getTileX(game.input.activePointer.worldX)+1)); + + if (game.input.mousePointer.isDown && (currentTile.index == tileBack)) + { + // check to make sure the tile is not already flipped + if (currentTile.index == tileBack) + { + // get the corresponding item out of squareList + currentNum = squareList[currentTilePosition-1]; + flipOver(); + squareCounter++; + + if (squareCounter == 1) + { + square1Num = currentNum; + savedSquareX1 = layer.getTileX(marker.x); + savedSquareY1 = layer.getTileY(marker.y); + } + + // is the second tile of pair flipped? + if (squareCounter == 2) + { + // reset squareCounter + squareCounter = 0; + square2Num = currentNum; + // check for match + if (square1Num == square2Num) + { + masterCounter++; + + if (masterCounter == 18) + { + // go "win" + youWin = 'Got them all!'; + } + else + { + savedSquareX2 = layer.getTileX(marker.x); + savedSquareY2 = layer.getTileY(marker.y); + } + } + else + { + flipFlag = true; + timeCheck = game.time.now; + savedSquareX2 = layer.getTileX(marker.x); + savedSquareY2 = layer.getTileY(marker.y); + attempt--; + } + + } + } + } + } + + function flipOver() { + + map.putTile(currentNum, layer.getTileX(marker.x), layer.getTileY(marker.y)); + } + + function flipBack() { + + map.putTile(tileBack, savedSquareX1, savedSquareY1); + map.putTile(tileBack, savedSquareX2, savedSquareY2); + + } + + function randomizeTiles() { + + for (num = 1; num <= 18; num++) + { + startList.push(num); + } + for (num = 1; num <= 18; num++) + { + startList.push(num); + } + + // for debugging + myString1 = startList.toString(); + + // randomize squareList + for (i = 1; i <=36; i++) + { + var randomPosition = game.rnd.integerInRange(0,startList.length-1); + var thisNumber = startList[ randomPosition ]; + + squareList.push(thisNumber); + var a = startList.indexOf(thisNumber); + + startList.splice(a, 1); + + } + + // for debugging + myString2 = squareList.toString(); + + for (col = 0; col < 6; col++) + { + for (row = 0; row < 6; row++) + { + map.putTile(tileBack, col, row); + } + } + } + + function getHiddenTile() { + + thisTile = squareList[currentTilePosition-1]; + return thisTile; + } + + function render() { + + game.debug.text(timesUp, 620, 208, 'rgb(0,255,0)'); + game.debug.text(youWin, 620, 240, 'rgb(0,255,0)'); + + game.debug.text('Time: ' + myCountdownSeconds, 620, 15, 'rgb(0,255,0)'); + + //game.debug.text('squareCounter: ' + squareCounter, 620, 272, 'rgb(0,0,255)'); + game.debug.text('Matched Pairs ' + masterCounter, 620, 304, 'rgb(255,255,255)'); + game.debug.text('Remaining Tries ' + attempt, 620, 320, 'rgb(255,255,0)'); + game.debug.text(tryAgain, 620, 350, 'rgb(255,0,0)'); + + + //game.debug.text('startList: ' + myString1, 620, 208, 'rgb(255,0,0)'); + //game.debug.text('squareList: ' + myString2, 620, 240, 'rgb(255,0,0)'); + + + // game.debug.text('Tile: ' + map.getTile(layer.getTileX(marker.x), layer.getTileY(marker.y)), 620, 48, 'rgb(255,0,0)'); + + game.debug.text('LayerX: ' + layer.getTileX(marker.x), 620, 80, 'rgb(255,0,0)'); + game.debug.text('LayerY: ' + layer.getTileY(marker.y), 620, 112, 'rgb(255,0,0)'); + + // game.debug.text('Tile Position: ' + currentTilePosition, 620, 144, 'rgb(255,0,0)'); + game.debug.text('Hidden Tile: ' + getHiddenTile(), 620, 176, 'rgb(255,0,0)'); + } + +/* + var game = new Phaser.Game( 800, 600, Phaser.AUTO, 'game', { preload: preload, create: create, update: update } ); + + function preload() { + // Load an image and call it 'logo'. + game.load.image( 'logo', 'assets/phaser.png' ); + } + + var bouncy; + + function create() { + // Create a sprite at the center of the screen using the 'logo' image. + bouncy = game.add.sprite( game.world.centerX, game.world.centerY, 'logo' ); + // Anchor the sprite at its center, as opposed to its top-left corner. + // so it will be truly centered. + bouncy.anchor.setTo( 0.5, 0.5 ); + + // Turn on the arcade physics engine for this sprite. + game.physics.enable( bouncy, Phaser.Physics.ARCADE ); + // Make it bounce off of the world bounds. + bouncy.body.collideWorldBounds = true; + + // Add some text using a CSS style. + // Center it in X, and position its top 15 pixels from the top of the world. + var style = { font: "25px Verdana", fill: "#9999ff", align: "center" }; + var text = game.add.text( game.world.centerX, 15, "Build something amazing.", style ); + text.anchor.setTo( 0.5, 0.0 ); + } + + function update() { + // Accelerate the 'logo' sprite towards the cursor, + // accelerating at 500 pixels/second and moving no faster than 500 pixels/second + // in X or Y. + // This function returns the rotation angle that makes it visually match its + // new trajectory. + bouncy.rotation = game.physics.arcade.accelerateToPointer( bouncy, game.input.activePointer, 500, 500, 500 ); + } +*/ +}; diff --git a/Digital Assignment 1/js/phaser.js b/Digital Assignment 1/js/phaser.js new file mode 100644 index 000000000..3bac171a7 --- /dev/null +++ b/Digital Assignment 1/js/phaser.js @@ -0,0 +1,107825 @@ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +* +* @overview +* +* Phaser - http://phaser.io +* +* v2.10.0 "2018-01-18" - Built: Thu Jan 18 2018 16:35:03 +* +* By Richard Davey http://www.photonstorm.com @photonstorm +* +* Phaser is a fun, free and fast 2D game framework for making HTML5 games +* for desktop and mobile web browsers, supporting Canvas and WebGL rendering. +* +* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23 +* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe +* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com +* +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate. +* +* Follow development at http://phaser.io and on our forum +* +* "If you want your children to be intelligent, read them fairy tales." +* "If you want them to be more intelligent, read them more fairy tales." +* -- Albert Einstein +*/ + +/** + * The MIT License (MIT) + * + * Copyright (c) 2015 p2.js authors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=0 && s<=1 && t>=0 && t<=1); +}; + + +},{"./Scalar":4}],2:[function(_dereq_,module,exports){ +module.exports = Point; + +/** + * Point related functions + * @class Point + */ +function Point(){}; + +/** + * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. + * @static + * @method area + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +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 = []; + +/** + * Check if three points are collinear + * @method collinear + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. + * @return {Boolean} + */ +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 angle < thresholdAngle; + } +}; + +Point.sqdist = function(a,b){ + var dx = b[0] - a[0]; + var dy = b[1] - a[1]; + return dx * dx + dy * dy; +}; + +},{}],3:[function(_dereq_,module,exports){ +var Line = _dereq_("./Line") +, Point = _dereq_("./Point") +, Scalar = _dereq_("./Scalar") + +module.exports = Polygon; + +/** + * Polygon class. + * @class Polygon + * @constructor + */ +function Polygon(){ + + /** + * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] + * @property vertices + * @type {Array} + */ + this.vertices = []; +} + +/** + * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. + * @method at + * @param {Number} i + * @return {Array} + */ +Polygon.prototype.at = function(i){ + var v = this.vertices, + s = v.length; + return v[i < 0 ? i % s + s : i % s]; +}; + +/** + * Get first vertex + * @method first + * @return {Array} + */ +Polygon.prototype.first = function(){ + return this.vertices[0]; +}; + +/** + * Get last vertex + * @method last + * @return {Array} + */ +Polygon.prototype.last = function(){ + return this.vertices[this.vertices.length-1]; +}; + +/** + * Clear the polygon data + * @method clear + * @return {Array} + */ +Polygon.prototype.clear = function(){ + this.vertices.length = 0; +}; + +/** + * Append points "from" to "to"-1 from an other polygon "poly" onto this one. + * @method append + * @param {Polygon} poly The polygon to get points from. + * @param {Number} from The vertex index in "poly". + * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. + * @return {Array} + */ +Polygon.prototype.append = function(poly,from,to){ + if(typeof(from) == "undefined") throw new Error("From is not given!"); + if(typeof(to) == "undefined") throw new Error("To is not given!"); + + if(to-1 < from) throw new Error("lol1"); + if(to > poly.vertices.length) throw new Error("lol2"); + if(from < 0) throw new Error("lol3"); + + for(var i=from; i v[br][0])) { + br = i; + } + } + + // reverse poly if clockwise + if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { + this.reverse(); + } +}; + +/** + * Reverse the vertices in the polygon + * @method 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; +}; + +/** + * Check if a point in the polygon is a reflex point + * @method isReflex + * @param {Number} i + * @return {Boolean} + */ +Polygon.prototype.isReflex = function(i){ + return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); +}; + +var tmpLine1=[], + tmpLine2=[]; + +/** + * Check if two vertices in the polygon can see each other + * @method canSee + * @param {Number} a Vertex index 1 + * @param {Number} b Vertex index 2 + * @return {Boolean} + */ +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) { // for each edge + if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges + 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))) { // if diag intersects an edge + 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) < dist) { // if edge is blocking visibility to b + return false; + } + } + } + + return true; +}; + +/** + * Copy the polygon from vertex i to vertex j. + * @method copy + * @param {Number} i + * @param {Number} j + * @param {Polygon} [targetPoly] Optional target polygon to save in. + * @return {Polygon} The resulting copy. + */ +Polygon.prototype.copy = function(i,j,targetPoly){ + var p = targetPoly || new Polygon(); + p.clear(); + if (i < j) { + // Insert all vertices from i to j + for(var k=i; k<=j; k++) + p.vertices.push(this.vertices[k]); + + } else { + + // Insert vertices 0 to j + for(var k=0; k<=j; k++) + p.vertices.push(this.vertices[k]); + + // Insert vertices i to end + for(var k=i; k 0) + return this.slice(edges); + else + return [this]; +}; + +/** + * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. + * @method slice + * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() + * @return {Array} + */ +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; i maxlevel){ + console.warn("quickDecomp: max level ("+maxlevel+") reached."); + return result; + } + + for (var i = 0; i < this.vertices.length; ++i) { + if (poly.isReflex(i)) { + reflexVertices.push(poly.vertices[i]); + upperDist = lowerDist = Number.MAX_VALUE; + + + for (var j = 0; j < this.vertices.length; ++j) { + if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge + p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection + if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly + d = Point.sqdist(poly.vertices[i], p); + if (d < lowerDist) { // keep only the closest intersection + lowerDist = d; + lowerInt = p; + lowerIndex = j; + } + } + } + if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); + if (Point.left(poly.at(i - 1), poly.at(i), p)) { + d = Point.sqdist(poly.vertices[i], p); + if (d < upperDist) { + upperDist = d; + upperInt = p; + upperIndex = j; + } + } + } + } + + // if there are no vertices to connect to, choose a point in the middle + if (lowerIndex == (upperIndex + 1) % this.vertices.length) { + //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); + p[0] = (lowerInt[0] + upperInt[0]) / 2; + p[1] = (lowerInt[1] + upperInt[1]) / 2; + steinerPoints.push(p); + + if (i < upperIndex) { + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); + lowerPoly.append(poly, i, upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + if (lowerIndex != 0){ + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); + upperPoly.append(poly,lowerIndex,poly.vertices.length); + } + //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); + lowerPoly.append(poly,i,poly.vertices.length); + } + //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); + lowerPoly.append(poly,0,upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); + upperPoly.append(poly,lowerIndex,i+1); + } + } else { + // connect to the closest point within the triangle + //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); + + if (lowerIndex > upperIndex) { + upperIndex += this.vertices.length; + } + closestDist = Number.MAX_VALUE; + + if(upperIndex < lowerIndex){ + return result; + } + + for (var j = lowerIndex; j <= upperIndex; ++j) { + if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + d = Point.sqdist(poly.at(i), poly.at(j)); + if (d < closestDist) { + closestDist = d; + closestIndex = j % this.vertices.length; + } + } + } + + if (i < closestIndex) { + lowerPoly.append(poly,i,closestIndex+1); + if (closestIndex != 0){ + upperPoly.append(poly,closestIndex,v.length); + } + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + lowerPoly.append(poly,i,v.length); + } + lowerPoly.append(poly,0,closestIndex+1); + upperPoly.append(poly,closestIndex,i+1); + } + } + + // solve smallest poly first + if (lowerPoly.vertices.length < upperPoly.vertices.length) { + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } else { + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } + + return result; + } + } + result.push(this); + + return result; +}; + +/** + * Remove collinear points in the polygon. + * @method removeCollinearPoints + * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. + * @return {Number} The number of points removed + */ +Polygon.prototype.removeCollinearPoints = function(precision){ + var num = 0; + for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ + if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ + // Remove the middle point + this.vertices.splice(i%this.vertices.length,1); + i--; // Jump one point forward. Otherwise we may get a chain removal + num++; + } + } + return num; +}; + +},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){ +module.exports = Scalar; + +/** + * Scalar functions + * @class Scalar + */ +function Scalar(){} + +/** + * Check if two scalars are equal + * @static + * @method eq + * @param {Number} a + * @param {Number} b + * @param {Number} [precision] + * @return {Boolean} + */ +Scalar.eq = function(a,b,precision){ + precision = precision || 0; + return Math.abs(a-b) < precision; +}; + +},{}],5:[function(_dereq_,module,exports){ +module.exports = { + Polygon : _dereq_("./Polygon"), + Point : _dereq_("./Point"), +}; + +},{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){ +module.exports={ + "name": "p2", + "version": "0.7.1", + "description": "A JavaScript 2D physics engine.", + "author": "Stefan Hedman (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.5", + "grunt-contrib-jshint": "^0.11.2", + "grunt-contrib-nodeunit": "^0.4.1", + "grunt-contrib-uglify": "~0.4.0", + "grunt-contrib-watch": "~0.5.0", + "grunt-browserify": "~2.0.1", + "grunt-contrib-concat": "^0.4.0" + }, + "dependencies": { + "poly-decomp": "0.1.1" + } +} + +},{}],7:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = AABB; + +/** + * Axis aligned bounding box class. + * @class AABB + * @constructor + * @param {Object} [options] + * @param {Array} [options.upperBound] + * @param {Array} [options.lowerBound] + */ +function AABB(options){ + + /** + * The lower bound of the bounding box. + * @property lowerBound + * @type {Array} + */ + this.lowerBound = vec2.create(); + if(options && options.lowerBound){ + vec2.copy(this.lowerBound, options.lowerBound); + } + + /** + * The upper bound of the bounding box. + * @property upperBound + * @type {Array} + */ + this.upperBound = vec2.create(); + if(options && options.upperBound){ + vec2.copy(this.upperBound, options.upperBound); + } +} + +var tmp = vec2.create(); + +/** + * Set the AABB bounds from a set of points, transformed by the given position and angle. + * @method setFromPoints + * @param {Array} points An array of vec2's. + * @param {Array} position + * @param {number} angle + * @param {number} skinSize Some margin to be added to the AABB. + */ +AABB.prototype.setFromPoints = function(points, position, angle, skinSize){ + var l = this.lowerBound, + u = this.upperBound; + + if(typeof(angle) !== "number"){ + angle = 0; + } + + // Set to the first point + if(angle !== 0){ + vec2.rotate(l, points[0], angle); + } else { + vec2.copy(l, points[0]); + } + vec2.copy(u, l); + + // Compute cosines and sines just once + var cosAngle = Math.cos(angle), + sinAngle = Math.sin(angle); + for(var i = 1; i u[j]){ + u[j] = p[j]; + } + if(p[j] < l[j]){ + l[j] = p[j]; + } + } + } + + // Add offset + if(position){ + vec2.add(this.lowerBound, this.lowerBound, position); + vec2.add(this.upperBound, this.upperBound, position); + } + + if(skinSize){ + this.lowerBound[0] -= skinSize; + this.lowerBound[1] -= skinSize; + this.upperBound[0] += skinSize; + this.upperBound[1] += skinSize; + } +}; + +/** + * Copy bounds from an AABB to this AABB + * @method copy + * @param {AABB} aabb + */ +AABB.prototype.copy = function(aabb){ + vec2.copy(this.lowerBound, aabb.lowerBound); + vec2.copy(this.upperBound, aabb.upperBound); +}; + +/** + * Extend this AABB so that it covers the given AABB too. + * @method extend + * @param {AABB} aabb + */ +AABB.prototype.extend = function(aabb){ + // Loop over x and y + var i = 2; + while(i--){ + // Extend lower bound + var l = aabb.lowerBound[i]; + if(this.lowerBound[i] > l){ + this.lowerBound[i] = l; + } + + // Upper + var u = aabb.upperBound[i]; + if(this.upperBound[i] < u){ + this.upperBound[i] = u; + } + } +}; + +/** + * Returns true if the given AABB overlaps this AABB. + * @method overlaps + * @param {AABB} aabb + * @return {Boolean} + */ +AABB.prototype.overlaps = function(aabb){ + var l1 = this.lowerBound, + u1 = this.upperBound, + l2 = aabb.lowerBound, + u2 = aabb.upperBound; + + // l2 u2 + // |---------| + // |--------| + // l1 u1 + + 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])); +}; + +/** + * @method containsPoint + * @param {Array} point + * @return {boolean} + */ +AABB.prototype.containsPoint = function(point){ + var l = this.lowerBound, + u = this.upperBound; + return l[0] <= point[0] && point[0] <= u[0] && l[1] <= point[1] && point[1] <= u[1]; +}; + +/** + * Check if the AABB is hit by a ray. + * @method overlapsRay + * @param {Ray} ray + * @return {number} -1 if no hit, a number between 0 and 1 if hit. + */ +AABB.prototype.overlapsRay = function(ray){ + var t = 0; + + // ray.direction is unit direction vector of ray + var dirFracX = 1 / ray.direction[0]; + var dirFracY = 1 / ray.direction[1]; + + // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner + var t1 = (this.lowerBound[0] - ray.from[0]) * dirFracX; + var t2 = (this.upperBound[0] - ray.from[0]) * dirFracX; + var t3 = (this.lowerBound[1] - ray.from[1]) * dirFracY; + var t4 = (this.upperBound[1] - ray.from[1]) * dirFracY; + + var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4))); + var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4))); + + // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us + if (tmax < 0){ + //t = tmax; + return -1; + } + + // if tmin > tmax, ray doesn't intersect AABB + if (tmin > tmax){ + //t = tmax; + return -1; + } + + return tmin; +}; +},{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Body = _dereq_('../objects/Body'); + +module.exports = Broadphase; + +/** + * Base class for broadphase implementations. + * @class Broadphase + * @constructor + */ +function Broadphase(type){ + + this.type = type; + + /** + * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). + * @property result + * @type {Array} + */ + this.result = []; + + /** + * The world to search for collision pairs in. To change it, use .setWorld() + * @property world + * @type {World} + * @readOnly + */ + this.world = null; + + /** + * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE. + * @property {Number} boundingVolumeType + */ + this.boundingVolumeType = Broadphase.AABB; +} + +/** + * Axis aligned bounding box type. + * @static + * @property {Number} AABB + */ +Broadphase.AABB = 1; + +/** + * Bounding circle type. + * @static + * @property {Number} BOUNDING_CIRCLE + */ +Broadphase.BOUNDING_CIRCLE = 2; + +/** + * Set the world that we are searching for collision pairs in. + * @method setWorld + * @param {World} world + */ +Broadphase.prototype.setWorld = function(world){ + this.world = world; +}; + +/** + * Get all potential intersecting body pairs. + * @method getCollisionPairs + * @param {World} world The world to search in. + * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). + */ +Broadphase.prototype.getCollisionPairs = function(world){}; + +var dist = vec2.create(); + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.aabbCheck = function(bodyA, bodyB){ + return bodyA.getAABB().overlaps(bodyB.getAABB()); +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether two bodies are allowed to collide at all. + * @method canCollide + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.canCollide = function(bodyA, bodyB){ + var KINEMATIC = Body.KINEMATIC; + var STATIC = Body.STATIC; + + // Cannot collide static bodies + if(bodyA.type === STATIC && bodyB.type === STATIC){ + return false; + } + + // Cannot collide static vs kinematic bodies + if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) || + (bodyA.type === STATIC && bodyB.type === KINEMATIC)){ + return false; + } + + // Cannot collide kinematic vs kinematic + if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){ + return false; + } + + // Cannot collide both sleeping bodies + if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ + return false; + } + + // Cannot collide if one is static and the other is sleeping + if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === STATIC) || + (bodyB.sleepState === Body.SLEEPING && bodyA.type === STATIC)){ + return false; + } + + return true; +}; + +Broadphase.NAIVE = 1; +Broadphase.SAP = 2; + +},{"../math/vec2":30,"../objects/Body":31}],9:[function(_dereq_,module,exports){ +var Circle = _dereq_('../shapes/Circle'), + Plane = _dereq_('../shapes/Plane'), + Shape = _dereq_('../shapes/Shape'), + Particle = _dereq_('../shapes/Particle'), + Broadphase = _dereq_('../collision/Broadphase'), + vec2 = _dereq_('../math/vec2'); + +module.exports = NaiveBroadphase; + +/** + * Naive broadphase implementation. Does N^2 tests. + * + * @class NaiveBroadphase + * @constructor + * @extends Broadphase + */ +function NaiveBroadphase(){ + Broadphase.call(this, Broadphase.NAIVE); +} +NaiveBroadphase.prototype = new Broadphase(); +NaiveBroadphase.prototype.constructor = NaiveBroadphase; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +NaiveBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = world.bodies, + result = this.result; + + result.length = 0; + + for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ + var bi = bodies[i]; + + for(var j=0; j pos0 && pos < pos1){ + // We got contact! + + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape); + + vec2.scale(c.normalA, orthoDist, -1); + vec2.normalize(c.normalA, c.normalA); + + vec2.scale( c.contactPointA, c.normalA, circleRadius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + sub(c.contactPointB, projectedPoint, lineOffset); + add(c.contactPointB, c.contactPointB, lineOffset); + sub(c.contactPointB, c.contactPointB, lineBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; + } + } + + // Add corner + verts[0] = worldVertex0; + verts[1] = worldVertex1; + + for(var i=0; i 0){ + for(var i=0; i Math.pow(r,2)){ + return 0; + } + + if(justTest){ + return true; + } + + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + 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; +}; + +/** + * Plane/Convex Narrowphase + * @method planeConvex + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} convexBody + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = +Narrowphase.prototype[Shape.PLANE | Shape.BOX] = +Narrowphase.prototype.planeConvex = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + convexBody, + convexShape, + convexOffset, + convexAngle, + justTest +){ + var worldVertex = tmp1, + worldNormal = tmp2, + dist = tmp3; + + var numReported = 0; + vec2.rotate(worldNormal, yAxis, planeAngle); + + for(var i=0; i!==convexShape.vertices.length; i++){ + var v = convexShape.vertices[i]; + vec2.rotate(worldVertex, v, convexAngle); + add(worldVertex, worldVertex, convexOffset); + + sub(dist, worldVertex, planeOffset); + + if(dot(dist,worldNormal) <= 0){ + + if(justTest){ + return true; + } + + // Found vertex + numReported++; + + var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); + + sub(dist, worldVertex, planeOffset); + + vec2.copy(c.normalA, worldNormal); + + var d = dot(dist, c.normalA); + vec2.scale(dist, c.normalA, d); + + // rj is from convex center to contact + sub(c.contactPointB, worldVertex, convexBody.position); + + + // ri is from plane center to contact + sub( c.contactPointA, worldVertex, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + this.contactEquations.push(c); + + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numReported){ + this.frictionEquations.push(this.createFrictionFromAverage(numReported)); + } + } + + return numReported; +}; + +/** + * Narrowphase for particle vs plane + * @method particlePlane + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = +Narrowphase.prototype.particlePlane = function( + particleBody, + particleShape, + particleOffset, + particleAngle, + planeBody, + planeShape, + planeOffset, + planeAngle, + justTest +){ + var dist = tmp1, + worldNormal = tmp2; + + planeAngle = planeAngle || 0; + + sub(dist, particleOffset, planeOffset); + vec2.rotate(worldNormal, yAxis, planeAngle); + + var d = dot(dist, worldNormal); + + if(d > 0){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape); + + vec2.copy(c.normalA, worldNormal); + vec2.scale( dist, c.normalA, d ); + // dist is now the distance vector in the normal direction + + // ri is the particle position projected down onto the plane, from the plane center + sub( c.contactPointA, particleOffset, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + // rj is from the body center to the particle center + sub( c.contactPointB, particleOffset, particleBody.position ); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + return 1; +}; + +/** + * Circle/Particle Narrowphase + * @method circleParticle + * @param {Body} circleBody + * @param {Circle} circleShape + * @param {Array} circleOffset + * @param {Number} circleAngle + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = +Narrowphase.prototype.circleParticle = function( + circleBody, + circleShape, + circleOffset, + circleAngle, + particleBody, + particleShape, + particleOffset, + particleAngle, + justTest +){ + var dist = tmp1; + + sub(dist, particleOffset, circleOffset); + if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape); + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + // Vector from circle to contact point is the normal times the circle radius + vec2.scale(c.contactPointA, c.normalA, circleShape.radius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + // Vector from particle center to contact point is zero + sub(c.contactPointB, particleOffset, particleBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; +}; + +var planeCapsule_tmpCircle = new Circle({ radius: 1 }), + planeCapsule_tmp1 = vec2.create(), + planeCapsule_tmp2 = vec2.create(), + planeCapsule_tmp3 = vec2.create(); + +/** + * @method planeCapsule + * @param {Body} planeBody + * @param {Circle} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} capsuleBody + * @param {Particle} capsuleShape + * @param {Array} capsuleOffset + * @param {Number} capsuleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = +Narrowphase.prototype.planeCapsule = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + capsuleBody, + capsuleShape, + capsuleOffset, + capsuleAngle, + justTest +){ + var end1 = planeCapsule_tmp1, + end2 = planeCapsule_tmp2, + circle = planeCapsule_tmpCircle, + dst = planeCapsule_tmp3; + + // Compute world end positions + vec2.set(end1, -capsuleShape.length/2, 0); + vec2.rotate(end1,end1,capsuleAngle); + add(end1,end1,capsuleOffset); + + vec2.set(end2, capsuleShape.length/2, 0); + vec2.rotate(end2,end2,capsuleAngle); + add(end2,end2,capsuleOffset); + + circle.radius = capsuleShape.radius; + + var enableFrictionBefore; + + // Temporarily turn off friction + if(this.enableFrictionReduction){ + enableFrictionBefore = this.enableFriction; + this.enableFriction = false; + } + + // Do Narrowphase as two circles + var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest), + numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest); + + // Restore friction + if(this.enableFrictionReduction){ + this.enableFriction = enableFrictionBefore; + } + + if(justTest){ + return numContacts1 || numContacts2; + } else { + var numTotal = numContacts1 + numContacts2; + if(this.enableFrictionReduction){ + if(numTotal){ + this.frictionEquations.push(this.createFrictionFromAverage(numTotal)); + } + } + return numTotal; + } +}; + +/** + * Creates ContactEquations and FrictionEquations for a collision. + * @method circlePlane + * @param {Body} bi The first body that should be connected to the equations. + * @param {Circle} si The circle shape participating in the collision. + * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. + * @param {Body} bj The second body that should be connected to the equations. + * @param {Plane} sj The Plane shape that is participating + * @param {Array} xj Extra offset for the plane shape. + * @param {Number} aj Extra angle to apply to the plane + */ +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, // Offset from body center, rotated! + planeBody = bj, + shapeB = sj, + planeOffset = xj, + planeAngle = aj; + + planeAngle = planeAngle || 0; + + // Vector from plane to circle + var planeToCircle = tmp1, + worldNormal = tmp2, + temp = tmp3; + + sub(planeToCircle, circleOffset, planeOffset); + + // World plane normal + vec2.rotate(worldNormal, yAxis, planeAngle); + + // Normal direction distance + var d = dot(worldNormal, planeToCircle); + + if(d > circleShape.radius){ + return 0; // No overlap. Abort. + } + + if(justTest){ + return true; + } + + // Create contact + var contact = this.createContactEquation(planeBody,circleBody,sj,si); + + // ni is the plane world normal + vec2.copy(contact.normalA, worldNormal); + + // rj is the vector from circle center to the contact point + vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); + add(contact.contactPointB, contact.contactPointB, circleOffset); + sub(contact.contactPointB, contact.contactPointB, circleBody.position); + + // ri is the distance from plane center to contact. + vec2.scale(temp, contact.normalA, d); + sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector + 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; +}; + +/** + * Convex/convex Narrowphase.See this article for more info. + * @method convexConvex + * @param {Body} bi + * @param {Convex} si + * @param {Array} xi + * @param {Number} ai + * @param {Body} bj + * @param {Convex} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CONVEX] = +Narrowphase.prototype[Shape.CONVEX | Shape.BOX] = +Narrowphase.prototype[Shape.BOX] = +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 = typeof(precision) === 'number' ? precision : 0; + + var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); + if(!found){ + return 0; + } + + // Make sure the separating axis is directed from shape i to shape j + sub(dist,xj,xi); + if(dot(sepAxis,dist) > 0){ + vec2.scale(sepAxis,sepAxis,-1); + } + + // Find edges with normals closest to the separating axis + var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis + closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); + + if(closestEdge1 === -1 || closestEdge2 === -1){ + return 0; + } + + // Loop over the shapes + 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){ + // Swap! + 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; + } + + // Loop over 2 points in convex B + for(var j=closestEdgeB; j= 3){ + + if(justTest){ + return true; + } + + // worldPoint was on the "inside" side of each of the 3 checked edges. + // Project it to the center edge and use the projection direction as normal + + // Create contact + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + numContacts++; + + // Get center edge from body A + var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], + v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; + + // Construct the edge + 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); // Normal points out of convex A + vec2.normalize(c.normalA,c.normalA); + + sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point + var d = dot(c.normalA,dist); // Penetration + vec2.scale(penetrationVec, c.normalA, d); // Vector penetration + + 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); + + // Todo reduce to 1 friction equation if we have 2 contact points + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numContacts){ + this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); + } + } + + return numContacts; +}; + +// .projectConvex is called by other functions, need local tmp vectors +var pcoa_tmp1 = vec2.fromValues(0,0); + +/** + * Project a Convex onto a world-oriented axis + * @method projectConvexOntoAxis + * @static + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Array} worldAxis + * @param {Array} result + */ +Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = pcoa_tmp1; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, worldAxis, -convexAngle); + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + // Project the position of the body onto the axis - need to add this to the result + var offset = dot(convexOffset, worldAxis); + + vec2.set( result, min + offset, max + offset); +}; + +// .findSeparatingAxis is called by other functions, need local tmp vectors +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); + +/** + * Find a separating axis between the shapes, that maximizes the separating distance between them. + * @method findSeparatingAxis + * @static + * @param {Convex} c1 + * @param {Array} offset1 + * @param {Number} angle1 + * @param {Convex} c2 + * @param {Array} offset2 + * @param {Number} angle2 + * @param {Array} sepAxis The resulting axis + * @return {Boolean} Whether the axis could be found. + */ +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; + + if(c1 instanceof Box && c2 instanceof Box){ + + for(var j=0; j!==2; j++){ + var c = c1, + angle = angle1; + if(j===1){ + c = c2; + angle = angle2; + } + + for(var i=0; i!==2; i++){ + + // Get the world edge + if(i === 0){ + vec2.set(normal, 0, 1); + } else if(i === 1) { + vec2.set(normal, 1, 0); + } + if(angle !== 0){ + vec2.rotate(normal, normal, angle); + } + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + + } else { + + 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++){ + // Get the world edge + vec2.rotate(worldPoint0, c.vertices[i], angle); + vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); + + sub(edge, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, edge); + vec2.normalize(normal,normal); + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + } + + + /* + // Needs to be tested some more + 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.axes.length; i++){ + + var normal = c.axes[i]; + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1); + Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + 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; +}; + +// .getClosestEdge is called by other functions, need local tmp vectors +var gce_tmp1 = vec2.fromValues(0,0) +, gce_tmp2 = vec2.fromValues(0,0) +, gce_tmp3 = vec2.fromValues(0,0); + +/** + * Get the edge that has a normal closest to an axis. + * @method getClosestEdge + * @static + * @param {Convex} c + * @param {Number} angle + * @param {Array} axis + * @param {Boolean} flip + * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. + */ +Narrowphase.getClosestEdge = function(c,angle,axis,flip){ + var localAxis = gce_tmp1, + edge = gce_tmp2, + normal = gce_tmp3; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, axis, -angle); + if(flip){ + vec2.scale(localAxis,localAxis,-1); + } + + var closestEdge = -1, + N = c.vertices.length, + maxDot = -1; + for(var i=0; i!==N; i++){ + // Get the edge + sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + 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(); + +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = +Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, + hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ + var data = hfShape.heights, + 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; + + // Get the index of the points to test against + var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), + idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); + + /*if(idxB < 0 || idxA >= data.length) + return justTest ? false : 0;*/ + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(circlePos[1]-radius > max){ + return justTest ? false : 0; + } + + /* + if(circlePos[1]+radius < min){ + // Below the minimum point... We can just guess. + // TODO + } + */ + + // 1. Check so center of circle is not inside the field. If it is, this wont work... + // 2. For each edge + // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) + // 2. 2. Check if point is inside. + + var found = false; + + // Check all edges first + for(var i=idxA; i= v0[0] && candidate[0] < v1[0] && d <= 0){ + + if(justTest){ + return true; + } + + found = true; + + // Store the candidate point, projected to the edge + vec2.scale(dist,worldNormal,-d); + vec2.add(minCandidate,candidate,dist); + vec2.copy(minCandidateNormal,worldNormal); + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Normal is out of the heightfield + vec2.copy(c.normalA, minCandidateNormal); + + // Vector from circle to heightfield + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + vec2.copy(c.contactPointA, minCandidate); + vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push( this.createFrictionFromContact(c) ); + } + } + } + + // Check all vertices + found = false; + if(radius > 0){ + for(var i=idxA; i<=idxB; i++){ + + // Get point + vec2.set(v0, i*w, data[i]); + vec2.add(v0,v0,hfPos); + + vec2.sub(dist, circlePos, v0); + + if(vec2.squaredLength(dist) < Math.pow(radius, 2)){ + + if(justTest){ + return true; + } + + found = true; + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Construct normal - out of heightfield + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + sub(c.contactPointA, v0, hfPos); + add(c.contactPointA, c.contactPointA, hfPos); + sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(found){ + return 1; + } + + return 0; + +}; + +var convexHeightfield_v0 = vec2.create(), + convexHeightfield_v1 = vec2.create(), + convexHeightfield_tilePos = vec2.create(), + convexHeightfield_tempConvexShape = new Convex({ vertices: [vec2.create(),vec2.create(),vec2.create(),vec2.create()] }); +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.BOX | Shape.HEIGHTFIELD] = +Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = +Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, + hfBody,hfShape,hfPos,hfAngle, justTest ){ + var data = hfShape.heights, + w = hfShape.elementWidth, + v0 = convexHeightfield_v0, + v1 = convexHeightfield_v1, + tilePos = convexHeightfield_tilePos, + tileConvex = convexHeightfield_tempConvexShape; + + // Get the index of the points to test against + var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), + idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(convexBody.aabb.lowerBound[1] > max){ + return justTest ? false : 0; + } + + var found = false; + var numContacts = 0; + + // Loop over all edges + // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape) + for(var i=idxA; i= 0 || aabb.containsPoint(this.from)){ + this.intersectBody(result, body); + } + } +}; + +var intersectBody_worldPosition = vec2.create(); + +/** + * Shoot a ray at a body, get back information about the hit. + * @method intersectBody + * @private + * @param {Body} body + */ +Ray.prototype.intersectBody = function (result, body) { + var checkCollisionResponse = this.checkCollisionResponse; + + if(checkCollisionResponse && !body.collisionResponse){ + return; + } + + var worldPosition = intersectBody_worldPosition; + + for (var i = 0, N = body.shapes.length; i < N; i++) { + var shape = body.shapes[i]; + + if(checkCollisionResponse && !shape.collisionResponse){ + continue; // Skip + } + + if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){ + continue; + } + + // Get world angle and position of the shape + vec2.rotate(worldPosition, shape.position, body.angle); + vec2.add(worldPosition, worldPosition, body.position); + var worldAngle = shape.angle + body.angle; + + this.intersectShape( + result, + shape, + worldAngle, + worldPosition, + body + ); + + if(result.shouldStop(this)){ + break; + } + } +}; + +/** + * @method intersectShape + * @private + * @param {Shape} shape + * @param {number} angle + * @param {array} position + * @param {Body} body + */ +Ray.prototype.intersectShape = function(result, shape, angle, position, body){ + var from = this.from; + + // Checking radius + var distance = distanceFromIntersectionSquared(from, this.direction, position); + if (distance > shape.boundingRadius * shape.boundingRadius) { + return; + } + + this._currentBody = body; + this._currentShape = shape; + + shape.raycast(result, this, position, angle); + + this._currentBody = this._currentShape = null; +}; + +/** + * Get the AABB of the ray. + * @method getAABB + * @param {AABB} aabb + */ +Ray.prototype.getAABB = function(result){ + var to = this.to; + var from = this.from; + vec2.set( + result.lowerBound, + Math.min(to[0], from[0]), + Math.min(to[1], from[1]) + ); + vec2.set( + result.upperBound, + Math.max(to[0], from[0]), + Math.max(to[1], from[1]) + ); +}; + +var hitPointWorld = vec2.create(); + +/** + * @method reportIntersection + * @private + * @param {number} fraction + * @param {array} normal + * @param {number} [faceIndex=-1] + * @return {boolean} True if the intersections should continue + */ +Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){ + var from = this.from; + var to = this.to; + var shape = this._currentShape; + var body = this._currentBody; + + // Skip back faces? + if(this.skipBackfaces && vec2.dot(normal, this.direction) > 0){ + return; + } + + switch(this.mode){ + + case Ray.ALL: + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + this.callback(result); + break; + + case Ray.CLOSEST: + + // Store if closer than current closest + if(fraction < result.fraction || !result.hasHit()){ + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + } + break; + + case Ray.ANY: + + // Report and stop. + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + break; + } +}; + +var v0 = vec2.create(), + intersect = vec2.create(); +function distanceFromIntersectionSquared(from, direction, position) { + + // v0 is vector from from to position + vec2.sub(v0, position, from); + var dot = vec2.dot(v0, direction); + + // intersect = direction * dot + from + vec2.scale(intersect, direction, dot); + vec2.add(intersect, intersect, from); + + return vec2.squaredDistance(position, intersect); +} + + +},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Ray = _dereq_('../collision/Ray'); + +module.exports = RaycastResult; + +/** + * Storage for Ray casting hit data. + * @class RaycastResult + * @constructor + */ +function RaycastResult(){ + + /** + * The normal of the hit, oriented in world space. + * @property {array} normal + */ + this.normal = vec2.create(); + + /** + * The hit shape, or null. + * @property {Shape} shape + */ + this.shape = null; + + /** + * The hit body, or null. + * @property {Body} body + */ + this.body = null; + + /** + * The index of the hit triangle, if the hit shape was indexable. + * @property {number} faceIndex + * @default -1 + */ + this.faceIndex = -1; + + /** + * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet. + * @property {number} fraction + * @default -1 + */ + this.fraction = -1; + + /** + * If the ray should stop traversing. + * @readonly + * @property {Boolean} isStopped + */ + this.isStopped = false; +} + +/** + * Reset all result data. Must be done before re-using the result object. + * @method reset + */ +RaycastResult.prototype.reset = function () { + vec2.set(this.normal, 0, 0); + this.shape = null; + this.body = null; + this.faceIndex = -1; + this.fraction = -1; + this.isStopped = false; +}; + +/** + * Get the distance to the hit point. + * @method getHitDistance + * @param {Ray} ray + */ +RaycastResult.prototype.getHitDistance = function (ray) { + return vec2.distance(ray.from, ray.to) * this.fraction; +}; + +/** + * Returns true if the ray hit something since the last reset(). + * @method hasHit + */ +RaycastResult.prototype.hasHit = function () { + return this.fraction !== -1; +}; + +/** + * Get world hit point. + * @method getHitPoint + * @param {array} out + * @param {Ray} ray + */ +RaycastResult.prototype.getHitPoint = function (out, ray) { + vec2.lerp(out, ray.from, ray.to, this.fraction); +}; + +/** + * Can be called while iterating over hits to stop searching for hit points. + * @method stop + */ +RaycastResult.prototype.stop = function(){ + this.isStopped = true; +}; + +/** + * @method shouldStop + * @private + * @param {Ray} ray + * @return {boolean} + */ +RaycastResult.prototype.shouldStop = function(ray){ + return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY); +}; + +/** + * @method set + * @private + * @param {array} normal + * @param {Shape} shape + * @param {Body} body + * @param {number} fraction + */ +RaycastResult.prototype.set = function( + normal, + shape, + body, + fraction, + faceIndex +){ + vec2.copy(this.normal, normal); + this.shape = shape; + this.body = body; + this.fraction = fraction; + this.faceIndex = faceIndex; +}; +},{"../collision/Ray":11,"../math/vec2":30}],13:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, Broadphase = _dereq_('../collision/Broadphase'); + +module.exports = SAPBroadphase; + +/** + * Sweep and prune broadphase along one axis. + * + * @class SAPBroadphase + * @constructor + * @extends Broadphase + */ +function SAPBroadphase(){ + Broadphase.call(this,Broadphase.SAP); + + /** + * List of bodies currently in the broadphase. + * @property axisList + * @type {Array} + */ + this.axisList = []; + + /** + * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance. + * @property axisIndex + * @type {Number} + */ + this.axisIndex = 0; + + var that = this; + this._addBodyHandler = function(e){ + that.axisList.push(e.body); + }; + + this._removeBodyHandler = function(e){ + // Remove from list + var idx = that.axisList.indexOf(e.body); + if(idx !== -1){ + that.axisList.splice(idx,1); + } + }; +} +SAPBroadphase.prototype = new Broadphase(); +SAPBroadphase.prototype.constructor = SAPBroadphase; + +/** + * Change the world + * @method setWorld + * @param {World} world + */ +SAPBroadphase.prototype.setWorld = function(world){ + // Clear the old axis array + this.axisList.length = 0; + + // Add all bodies from the new world + Utils.appendArray(this.axisList, world.bodies); + + // Remove old handlers, if any + world + .off("addBody",this._addBodyHandler) + .off("removeBody",this._removeBodyHandler); + + // Add handlers to update the list of bodies. + world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); + + this.world = world; +}; + +/** + * Sorts bodies along an axis. + * @method sortAxisList + * @param {Array} a + * @param {number} axisIndex + * @return {Array} + */ +SAPBroadphase.sortAxisList = function(a, axisIndex){ + axisIndex = axisIndex|0; + for(var i=1,l=a.length; 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.sortList = function(){ + var bodies = this.axisList, + axisIndex = this.axisIndex; + + // Sort the lists + SAPBroadphase.sortAxisList(bodies, axisIndex); +}; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +SAPBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = this.axisList, + result = this.result, + axisIndex = this.axisIndex; + + result.length = 0; + + // Update all AABBs if needed + var l = bodies.length; + while(l--){ + var b = bodies[l]; + if(b.aabbNeedsUpdate){ + b.updateAABB(); + } + } + + // Sort the lists + this.sortList(); + + // Look through the X list + for(var i=0, N=bodies.length|0; i!==N; i++){ + var bi = bodies[i]; + + for(var j=i+1; j G = [-n -rixn n rjxn] + + var r = vec2.create(); + var ri = vec2.create(); // worldAnchorA + var rj = vec2.create(); // worldAnchorB + var that = this; + normal.computeGq = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + xi = bodyA.position, + xj = bodyB.position; + + // Transform local anchors to world + vec2.rotate(ri, localAnchorA, bodyA.angle); + vec2.rotate(rj, localAnchorB, bodyB.angle); + + vec2.add(r, xj, rj); + vec2.sub(r, r, ri); + vec2.sub(r, r, xi); + + //vec2.sub(r, bodyB.position, bodyA.position); + return vec2.length(r) - that.distance; + }; + + // Make the contact constraint bilateral + this.setMaxForce(maxForce); + + /** + * If the upper limit is enabled or not. + * @property {Boolean} upperLimitEnabled + */ + this.upperLimitEnabled = false; + + /** + * The upper constraint limit. + * @property {number} upperLimit + */ + this.upperLimit = 1; + + /** + * If the lower limit is enabled or not. + * @property {Boolean} lowerLimitEnabled + */ + this.lowerLimitEnabled = false; + + /** + * The lower constraint limit. + * @property {number} lowerLimit + */ + this.lowerLimit = 0; + + /** + * Current constraint position. This is equal to the current distance between the world anchor points. + * @property {number} position + */ + this.position = 0; +} +DistanceConstraint.prototype = new Constraint(); +DistanceConstraint.prototype.constructor = DistanceConstraint; + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +var n = vec2.create(); +var ri = vec2.create(); // worldAnchorA +var rj = vec2.create(); // worldAnchorB +DistanceConstraint.prototype.update = function(){ + var normal = this.equations[0], + bodyA = this.bodyA, + bodyB = this.bodyB, + distance = this.distance, + xi = bodyA.position, + xj = bodyB.position, + normalEquation = this.equations[0], + G = normal.G; + + // Transform local anchors to world + vec2.rotate(ri, this.localAnchorA, bodyA.angle); + vec2.rotate(rj, this.localAnchorB, bodyB.angle); + + // Get world anchor points and normal + vec2.add(n, xj, rj); + vec2.sub(n, n, ri); + vec2.sub(n, n, xi); + this.position = vec2.length(n); + + var violating = false; + if(this.upperLimitEnabled){ + if(this.position > this.upperLimit){ + normalEquation.maxForce = 0; + normalEquation.minForce = -this.maxForce; + this.distance = this.upperLimit; + violating = true; + } + } + + if(this.lowerLimitEnabled){ + if(this.position < this.lowerLimit){ + normalEquation.maxForce = this.maxForce; + normalEquation.minForce = 0; + this.distance = this.lowerLimit; + violating = true; + } + } + + if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){ + // No constraint needed. + normalEquation.enabled = false; + return; + } + + normalEquation.enabled = true; + + vec2.normalize(n,n); + + // Caluclate cross products + var rixn = vec2.crossLength(ri, n), + rjxn = vec2.crossLength(rj, n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; +}; + +/** + * Set the max force to be used + * @method setMaxForce + * @param {Number} maxForce + */ +DistanceConstraint.prototype.setMaxForce = function(maxForce){ + var normal = this.equations[0]; + normal.minForce = -maxForce; + normal.maxForce = maxForce; +}; + +/** + * Get the max force + * @method getMaxForce + * @return {Number} + */ +DistanceConstraint.prototype.getMaxForce = function(){ + var normal = this.equations[0]; + return normal.maxForce; +}; + +},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, AngleLockEquation = _dereq_('../equations/AngleLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = GearConstraint; + +/** + * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB. + * @class GearConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for). + * @param {Number} [options.ratio=1] Gear ratio. + * @param {Number} [options.maxTorque] Maximum torque to apply. + * @extends Constraint + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB, { + * ratio: 2, + * maxTorque: 1000 + * }); + * world.addConstraint(constraint); + */ +function GearConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); + + /** + * The gear ratio. + * @property ratio + * @type {Number} + */ + this.ratio = options.ratio !== undefined ? options.ratio : 1; + + /** + * The relative angle + * @property angle + * @type {Number} + */ + this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle; + + // Send same parameters to the equation + options.angle = this.angle; + options.ratio = this.ratio; + + this.equations = [ + new AngleLockEquation(bodyA,bodyB,options), + ]; + + // Set max torque + if(options.maxTorque !== undefined){ + this.setMaxTorque(options.maxTorque); + } +} +GearConstraint.prototype = new Constraint(); +GearConstraint.prototype.constructor = GearConstraint; + +GearConstraint.prototype.update = function(){ + var eq = this.equations[0]; + if(eq.ratio !== this.ratio){ + eq.setRatio(this.ratio); + } + eq.angle = this.angle; +}; + +/** + * Set the max torque for the constraint. + * @method setMaxTorque + * @param {Number} torque + */ +GearConstraint.prototype.setMaxTorque = function(torque){ + this.equations[0].setMaxTorque(torque); +}; + +/** + * Get the max torque for the constraint. + * @method getMaxTorque + * @return {Number} + */ +GearConstraint.prototype.getMaxTorque = function(torque){ + return this.equations[0].maxForce; +}; +},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('../equations/Equation'); + +module.exports = LockConstraint; + +/** + * Locks the relative position and rotation between two bodies. + * + * @class LockConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions. + * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles. + * @param {number} [options.maxForce] + * @extends Constraint + * + * @example + * // Locks the relative position and rotation between bodyA and bodyB + * var constraint = new LockConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + */ +function LockConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); + + var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); + + var localAngleB = options.localAngleB || 0; + + // Use 3 equations: + // gx = (xj - xi - l) * xhat = 0 + // gy = (xj - xi - l) * yhat = 0 + // gr = (xi - xj + r) * that = 0 + // + // ...where: + // l is the localOffsetB vector rotated to world in bodyA frame + // r is the same vector but reversed and rotated from bodyB frame + // xhat, yhat are world axis vectors + // that is the tangent of r + // + // For the first two constraints, we get + // G*W = (vj - vi - ldot ) * xhat + // = (vj - vi - wi x l) * xhat + // + // Since (wi x l) * xhat = (l x xhat) * wi, we get + // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] + // + // The last constraint gives + // GW = (vi - vj + wj x r) * that + // = [ that 0 -that (r x t) ] + + var x = new Equation(bodyA,bodyB,-maxForce,maxForce), + y = new Equation(bodyA,bodyB,-maxForce,maxForce), + rot = new Equation(bodyA,bodyB,-maxForce,maxForce); + + var l = vec2.create(), + g = vec2.create(), + that = this; + x.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[0]; + }; + y.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[1]; + }; + var r = vec2.create(), + t = vec2.create(); + rot.computeGq = function(){ + vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); + vec2.scale(r,r,-1); + vec2.sub(g,bodyA.position,bodyB.position); + vec2.add(g,g,r); + vec2.rotate(t,r,-Math.PI/2); + vec2.normalize(t,t); + return vec2.dot(g,t); + }; + + /** + * The offset of bodyB in bodyA's frame. + * @property {Array} localOffsetB + */ + this.localOffsetB = vec2.create(); + if(options.localOffsetB){ + vec2.copy(this.localOffsetB, options.localOffsetB); + } else { + // Construct from current positions + vec2.sub(this.localOffsetB, bodyB.position, bodyA.position); + vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle); + } + + /** + * The offset angle of bodyB in bodyA's frame. + * @property {Number} localAngleB + */ + this.localAngleB = 0; + if(typeof(options.localAngleB) === 'number'){ + this.localAngleB = options.localAngleB; + } else { + // Construct + this.localAngleB = bodyB.angle - bodyA.angle; + } + + this.equations.push(x, y, rot); + this.setMaxForce(maxForce); +} +LockConstraint.prototype = new Constraint(); +LockConstraint.prototype.constructor = LockConstraint; + +/** + * Set the maximum force to be applied. + * @method setMaxForce + * @param {Number} force + */ +LockConstraint.prototype.setMaxForce = function(force){ + var eqs = this.equations; + for(var i=0; ithis tutorial. Also called "slider constraint". + * + * @class PrismaticConstraint + * @constructor + * @extends Constraint + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.maxForce] Max force to be applied by the constraint + * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. + * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. + * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. + * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. + * @param {Number} [options.upperLimit] + * @param {Number} [options.lowerLimit] + * @todo Ability to create using only a point and a worldAxis + */ +function PrismaticConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); + + // Get anchors + var localAnchorA = vec2.fromValues(0,0), + localAxisA = vec2.fromValues(1,0), + localAnchorB = vec2.fromValues(0,0); + if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); } + if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); } + if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); } + + /** + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = localAnchorA; + + /** + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = localAnchorB; + + /** + * @property localAxisA + * @type {Array} + */ + this.localAxisA = localAxisA; + + /* + + The constraint violation for the common axis point is + + g = ( xj + rj - xi - ri ) * t := gg*t + + where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. + + gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) + + Note the use of the chain rule. Now we identify the jacobian + + G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] + + The rotational part is just a rotation lock. + + */ + + var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE; + + // Translational part + var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); + var ri = new vec2.create(), + rj = new vec2.create(), + gg = new vec2.create(), + t = new vec2.create(); + trans.computeGq = function(){ + // g = ( xj + rj - xi - ri ) * t + return vec2.dot(gg,t); + }; + trans.updateJacobian = function(){ + var G = this.G, + xi = bodyA.position, + xj = bodyB.position; + vec2.rotate(ri,localAnchorA,bodyA.angle); + vec2.rotate(rj,localAnchorB,bodyB.angle); + vec2.add(gg,xj,rj); + vec2.sub(gg,gg,xi); + vec2.sub(gg,gg,ri); + vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); + + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + }; + this.equations.push(trans); + + // Rotational part + if(!options.disableRotationalLock){ + var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); + this.equations.push(rot); + } + + /** + * The position of anchor A relative to anchor B, along the constraint axis. + * @property position + * @type {Number} + */ + this.position = 0; + + // Is this one used at all? + this.velocity = 0; + + /** + * Set to true to enable lower limit. + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; + + /** + * Set to true to enable upper limit. + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; + + /** + * Lower constraint limit. The constraint position is forced to be larger than this value. + * @property lowerLimit + * @type {Number} + */ + this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; + + /** + * Upper constraint limit. The constraint position is forced to be smaller than this value. + * @property upperLimit + * @type {Number} + */ + this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; + + // Equations used for limits + this.upperLimitEquation = new ContactEquation(bodyA,bodyB); + this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); + + // Set max/min forces + this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; + this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; + + /** + * Equation used for the motor. + * @property motorEquation + * @type {Equation} + */ + this.motorEquation = new Equation(bodyA,bodyB); + + /** + * The current motor state. Enable or disable the motor using .enableMotor + * @property motorEnabled + * @type {Boolean} + */ + this.motorEnabled = false; + + /** + * Set the target speed for the motor. + * @property motorSpeed + * @type {Number} + */ + this.motorSpeed = 0; + + var that = this; + var motorEquation = this.motorEquation; + var old = motorEquation.computeGW; + motorEquation.computeGq = function(){ return 0; }; + motorEquation.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed; + }; +} + +PrismaticConstraint.prototype = new Constraint(); +PrismaticConstraint.prototype.constructor = PrismaticConstraint; + +var worldAxisA = vec2.create(), + worldAnchorA = vec2.create(), + worldAnchorB = vec2.create(), + orientedAnchorA = vec2.create(), + orientedAnchorB = vec2.create(), + tmp = vec2.create(); + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +PrismaticConstraint.prototype.update = function(){ + var eqs = this.equations, + trans = eqs[0], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation, + bodyA = this.bodyA, + bodyB = this.bodyB, + localAxisA = this.localAxisA, + localAnchorA = this.localAnchorA, + localAnchorB = this.localAnchorB; + + trans.updateJacobian(); + + // Transform local things to world + vec2.rotate(worldAxisA, localAxisA, bodyA.angle); + vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); + vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); + vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); + vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); + + var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); + + // Motor + if(this.motorEnabled){ + // G = [ a a x ri -a -a x rj ] + var G = this.motorEquation.G; + G[0] = worldAxisA[0]; + G[1] = worldAxisA[1]; + G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); + G[3] = -worldAxisA[0]; + G[4] = -worldAxisA[1]; + G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); + } + + /* + Limits strategy: + Add contact equation, with normal along the constraint axis. + min/maxForce is set so the constraint is repulsive in the correct direction. + Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. + + ^ + | + upperLimit x + | ------ + anchorB x<---| B | + | | | + ------ | ------ + | | | + | A |-->x anchorA + ------ | + x lowerLimit + | + axis + */ + + + if(this.upperLimitEnabled && relPosition > upperLimit){ + // Update contact constraint normal, etc + 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 && relPosition < lowerLimit){ + // Update contact constraint normal, etc + vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); + vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); + vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); + vec2.scale(tmp,worldAxisA,lowerLimit); + vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } +}; + +/** + * Enable the motor + * @method enableMotor + */ +PrismaticConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +PrismaticConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the constraint limits. + * @method setLimits + * @param {number} lower Lower limit. + * @param {number} upper Upper limit. + */ +PrismaticConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + + +},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation') +, RotationalLockEquation = _dereq_('../equations/RotationalLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = RevoluteConstraint; + +var worldPivotA = vec2.create(), + worldPivotB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1), + g = vec2.create(); + +/** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * @class RevoluteConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to. + * @param {Array} [options.localPivotB] See localPivotA. + * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. + * @extends Constraint + * + * @example + * // This will create a revolute constraint between two bodies with pivot point in between them. + * var bodyA = new Body({ mass: 1, position: [-1, 0] }); + * var bodyB = new Body({ mass: 1, position: [1, 0] }); + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * worldPivot: [0, 0] + * }); + * world.addConstraint(constraint); + * + * // Using body-local pivot points, the constraint could have been constructed like this: + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * localPivotA: [1, 0], + * localPivotB: [-1, 0] + * }); + */ +function RevoluteConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); + + var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; + + /** + * @property {Array} pivotA + */ + this.pivotA = vec2.create(); + + /** + * @property {Array} pivotB + */ + this.pivotB = vec2.create(); + + if(options.worldPivot){ + // Compute pivotA and pivotB + vec2.sub(this.pivotA, options.worldPivot, bodyA.position); + vec2.sub(this.pivotB, options.worldPivot, bodyB.position); + // Rotate to local coordinate system + vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle); + vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle); + } else { + // Get pivotA and pivotB + vec2.copy(this.pivotA, options.localPivotA); + vec2.copy(this.pivotB, options.localPivotB); + } + + // Equations to be fed to the solver + var eqs = this.equations = [ + new Equation(bodyA,bodyB,-maxForce,maxForce), + new Equation(bodyA,bodyB,-maxForce,maxForce), + ]; + + var x = eqs[0]; + var y = eqs[1]; + var that = this; + + x.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,xAxis); + }; + + y.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,yAxis); + }; + + y.minForce = x.minForce = -maxForce; + y.maxForce = x.maxForce = maxForce; + + this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); + + /** + * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. + * @property {Boolean} motorEnabled + * @readOnly + */ + this.motorEnabled = false; + + /** + * The constraint position. + * @property angle + * @type {Number} + * @readOnly + */ + this.angle = 0; + + /** + * Set to true to enable lower limit + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = false; + + /** + * Set to true to enable upper limit + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = false; + + /** + * The lower limit on the constraint angle. + * @property lowerLimit + * @type {Boolean} + */ + this.lowerLimit = 0; + + /** + * The upper limit on the constraint angle. + * @property upperLimit + * @type {Boolean} + */ + this.upperLimit = 0; + + this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.upperLimitEquation.minForce = 0; + this.lowerLimitEquation.maxForce = 0; +} +RevoluteConstraint.prototype = new Constraint(); +RevoluteConstraint.prototype.constructor = RevoluteConstraint; + +/** + * Set the constraint angle limits. + * @method setLimits + * @param {number} lower Lower angle limit. + * @param {number} upper Upper angle limit. + */ +RevoluteConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + +RevoluteConstraint.prototype.update = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + pivotA = this.pivotA, + pivotB = this.pivotB, + eqs = this.equations, + normal = eqs[0], + tangent= eqs[1], + x = eqs[0], + y = eqs[1], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation; + + var relAngle = this.angle = bodyB.angle - bodyA.angle; + + if(this.upperLimitEnabled && relAngle > upperLimit){ + 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 < lowerLimit){ + lowerLimitEquation.angle = lowerLimit; + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } + + /* + + The constraint violation is + + g = xj + rj - xi - ri + + ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: + + gdot = vj + wj x rj - vi - wi x ri + + We split this into x and y directions. (let x and y be unit vectors along the respective axes) + + gdot * x = ( vj + wj x rj - vi - wi x ri ) * x + = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x + = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi + = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] + = G*W + + ...and similar for y. We have then identified the jacobian entries for x and y directions: + + Gx = [ x (rj x x) -x -(ri x x)] + Gy = [ y (rj x y) -y -(ri x y)] + + */ + + vec2.rotate(worldPivotA, pivotA, bodyA.angle); + vec2.rotate(worldPivotB, pivotB, bodyB.angle); + + // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc + + x.G[0] = -1; + x.G[1] = 0; + x.G[2] = -vec2.crossLength(worldPivotA,xAxis); + x.G[3] = 1; + x.G[4] = 0; + x.G[5] = vec2.crossLength(worldPivotB,xAxis); + + y.G[0] = 0; + y.G[1] = -1; + y.G[2] = -vec2.crossLength(worldPivotA,yAxis); + y.G[3] = 0; + y.G[4] = 1; + y.G[5] = vec2.crossLength(worldPivotB,yAxis); +}; + +/** + * Enable the rotational motor + * @method enableMotor + */ +RevoluteConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +RevoluteConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the speed of the rotational constraint motor + * @method setMotorSpeed + * @param {Number} speed + */ +RevoluteConstraint.prototype.setMotorSpeed = function(speed){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations[i].relativeVelocity = speed; +}; + +/** + * Get the speed of the rotational constraint motor + * @method getMotorSpeed + * @return {Number} The current speed, or false if the motor is not enabled. + */ +RevoluteConstraint.prototype.getMotorSpeed = function(){ + if(!this.motorEnabled){ + return false; + } + return this.motorEquation.relativeVelocity; +}; + +},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = AngleLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class AngleLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in body A. + * @param {Number} [options.ratio] Gear ratio + */ +function AngleLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); + this.angle = options.angle || 0; + + /** + * The gear ratio. + * @property {Number} ratio + * @private + * @see setRatio + */ + this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; + + this.setRatio(this.ratio); +} +AngleLockEquation.prototype = new Equation(); +AngleLockEquation.prototype.constructor = AngleLockEquation; + +AngleLockEquation.prototype.computeGq = function(){ + return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; +}; + +/** + * Set the gear ratio for this equation + * @method setRatio + * @param {Number} ratio + */ +AngleLockEquation.prototype.setRatio = function(ratio){ + var G = this.G; + G[2] = ratio; + G[5] = -1; + this.ratio = ratio; +}; + +/** + * Set the max force for the equation. + * @method setMaxTorque + * @param {Number} torque + */ +AngleLockEquation.prototype.setMaxTorque = function(torque){ + this.maxForce = torque; + this.minForce = -torque; +}; + +},{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = ContactEquation; + +/** + * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive. + * + * @class ContactEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function ContactEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); + + /** + * Vector from body i center of mass to the contact point. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + this.penetrationVec = vec2.create(); + + /** + * World-oriented vector from body A center of mass to the contact point. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * The normal vector, pointing out of body i + * @property normalA + * @type {Array} + */ + this.normalA = vec2.create(); + + /** + * The restitution to use (0=no bounciness, 1=max bounciness). + * @property restitution + * @type {Number} + */ + this.restitution = 0; + + /** + * This property is set to true if this is the first impact between the bodies (not persistant contact). + * @property firstImpact + * @type {Boolean} + * @readOnly + */ + this.firstImpact = false; + + /** + * The shape in body i that triggered this contact. + * @property shapeA + * @type {Shape} + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this contact. + * @property shapeB + * @type {Shape} + */ + this.shapeB = null; +} +ContactEquation.prototype = new Equation(); +ContactEquation.prototype.constructor = ContactEquation; +ContactEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + xi = bi.position, + xj = bj.position; + + var penetrationVec = this.penetrationVec, + n = this.normalA, + G = this.G; + + // Caluclate cross products + var rixn = vec2.crossLength(ri,n), + rjxn = vec2.crossLength(rj,n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; + + // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector + vec2.add(penetrationVec,xj,rj); + vec2.sub(penetrationVec,penetrationVec,xi); + vec2.sub(penetrationVec,penetrationVec,ri); + + // Compute iteration + var GW, Gq; + if(this.firstImpact && this.restitution !== 0){ + Gq = 0; + GW = (1/b)*(1+this.restitution) * this.computeGW(); + } else { + Gq = vec2.dot(n,penetrationVec) + this.offset; + GW = this.computeGW(); + } + + var GiMf = this.computeGiMf(); + var B = - Gq * a - GW * b - h*GiMf; + + return B; +}; + +var vi = vec2.create(); +var vj = vec2.create(); +var relVel = vec2.create(); + +/** + * Get the relative velocity along the normal vector. + * @return {number} + */ +ContactEquation.prototype.getVelocityAlongNormal = function(){ + + this.bodyA.getVelocityAtPoint(vi, this.contactPointA); + this.bodyB.getVelocityAtPoint(vj, this.contactPointB); + + vec2.subtract(relVel, vi, vj); + + return vec2.dot(this.normalA, relVel); +}; +},{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){ +module.exports = Equation; + +var vec2 = _dereq_('../math/vec2'), + Utils = _dereq_('../utils/Utils'), + Body = _dereq_('../objects/Body'); + +/** + * Base class for constraint equations. + * @class Equation + * @constructor + * @param {Body} bodyA First body participating in the equation + * @param {Body} bodyB Second body participating in the equation + * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE + * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE + */ +function Equation(bodyA, bodyB, minForce, maxForce){ + + /** + * Minimum force to apply when solving. + * @property minForce + * @type {Number} + */ + this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; + + /** + * Max force to apply when solving. + * @property maxForce + * @type {Number} + */ + this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; + + /** + * First body participating in the constraint + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second body participating in the constraint + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; + + /** + * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. + * @property stiffness + * @type {Number} + */ + this.stiffness = Equation.DEFAULT_STIFFNESS; + + /** + * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. + * @property relaxation + * @type {Number} + */ + this.relaxation = Equation.DEFAULT_RELAXATION; + + /** + * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). + * @property G + * @type {Array} + */ + this.G = new Utils.ARRAY_TYPE(6); + for(var i=0; i<6; i++){ + this.G[i]=0; + } + + this.offset = 0; + + this.a = 0; + this.b = 0; + this.epsilon = 0; + this.timeStep = 1/60; + + /** + * Indicates if stiffness or relaxation was changed. + * @property {Boolean} needsUpdate + */ + this.needsUpdate = true; + + /** + * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. + * @property multiplier + * @type {Number} + */ + this.multiplier = 0; + + /** + * Relative velocity. + * @property {Number} relativeVelocity + */ + this.relativeVelocity = 0; + + /** + * Whether this equation is enabled or not. If true, it will be added to the solver. + * @property {Boolean} enabled + */ + this.enabled = true; +} +Equation.prototype.constructor = Equation; + +/** + * The default stiffness when creating a new Equation. + * @static + * @property {Number} DEFAULT_STIFFNESS + * @default 1e6 + */ +Equation.DEFAULT_STIFFNESS = 1e6; + +/** + * The default relaxation when creating a new Equation. + * @static + * @property {Number} DEFAULT_RELAXATION + * @default 4 + */ +Equation.DEFAULT_RELAXATION = 4; + +/** + * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the SPOOK notes. + * @method update + */ +Equation.prototype.update = function(){ + var k = this.stiffness, + d = this.relaxation, + h = this.timeStep; + + this.a = 4.0 / (h * (1 + 4 * d)); + this.b = (4.0 * d) / (1 + 4 * d); + this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); + + this.needsUpdate = false; +}; + +/** + * Multiply a jacobian entry with corresponding positions or velocities + * @method gmult + * @return {Number} + */ +Equation.prototype.gmult = function(G,vi,wi,vj,wj){ + return G[0] * vi[0] + + G[1] * vi[1] + + G[2] * wi + + G[3] * vj[0] + + G[4] * vj[1] + + G[5] * wj; +}; + +/** + * Computes the RHS of the SPOOK equation + * @method computeB + * @return {Number} + */ +Equation.prototype.computeB = function(a,b,h){ + var GW = this.computeGW(); + var Gq = this.computeGq(); + var GiMf = this.computeGiMf(); + return - Gq * a - GW * b - GiMf*h; +}; + +/** + * Computes G\*q, where q are the generalized body coordinates + * @method computeGq + * @return {Number} + */ +var qi = vec2.create(), + qj = vec2.create(); +Equation.prototype.computeGq = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + xi = bi.position, + xj = bj.position, + ai = bi.angle, + aj = bj.angle; + + return this.gmult(G, qi, ai, qj, aj) + this.offset; +}; + +/** + * Computes G\*W, where W are the body velocities + * @method computeGW + * @return {Number} + */ +Equation.prototype.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity; +}; + +/** + * Computes G\*Wlambda, where W are the body velocities + * @method computeGWlambda + * @return {Number} + */ +Equation.prototype.computeGWlambda = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.vlambda, + vj = bj.vlambda, + wi = bi.wlambda, + wj = bj.wlambda; + return this.gmult(G,vi,wi,vj,wj); +}; + +/** + * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. + * @method computeGiMf + * @return {Number} + */ +var iMfi = vec2.create(), + iMfj = vec2.create(); +Equation.prototype.computeGiMf = function(){ + var bi = this.bodyA, + bj = this.bodyB, + fi = bi.force, + ti = bi.angularForce, + fj = bj.force, + tj = bj.angularForce, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + vec2.scale(iMfi, fi, invMassi); + vec2.multiply(iMfi, bi.massMultiplier, iMfi); + vec2.scale(iMfj, fj,invMassj); + vec2.multiply(iMfj, bj.massMultiplier, iMfj); + + return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); +}; + +/** + * Computes G\*inv(M)\*G' + * @method computeGiMGt + * @return {Number} + */ +Equation.prototype.computeGiMGt = function(){ + var bi = this.bodyA, + bj = this.bodyB, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + return G[0] * G[0] * invMassi * bi.massMultiplier[0] + + G[1] * G[1] * invMassi * bi.massMultiplier[1] + + G[2] * G[2] * invIi + + G[3] * G[3] * invMassj * bj.massMultiplier[0] + + G[4] * G[4] * invMassj * bj.massMultiplier[1] + + G[5] * G[5] * invIj; +}; + +var addToWlambda_temp = vec2.create(), + addToWlambda_Gi = vec2.create(), + addToWlambda_Gj = vec2.create(), + addToWlambda_ri = vec2.create(), + addToWlambda_rj = vec2.create(), + addToWlambda_Mdiag = vec2.create(); + +/** + * Add constraint velocity to the bodies. + * @method addToWlambda + * @param {Number} deltalambda + */ +Equation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bodyA, + bj = this.bodyB, + temp = addToWlambda_temp, + Gi = addToWlambda_Gi, + Gj = addToWlambda_Gj, + ri = addToWlambda_ri, + rj = addToWlambda_rj, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + Mdiag = addToWlambda_Mdiag, + G = this.G; + + Gi[0] = G[0]; + Gi[1] = G[1]; + Gj[0] = G[3]; + Gj[1] = G[4]; + + // Add to linear velocity + // v_lambda += inv(M) * delta_lamba * G + vec2.scale(temp, Gi, invMassi*deltalambda); + vec2.multiply(temp, temp, bi.massMultiplier); + vec2.add( bi.vlambda, bi.vlambda, temp); + // This impulse is in the offset frame + // Also add contribution to angular + //bi.wlambda -= vec2.crossLength(temp,ri); + bi.wlambda += invIi * G[2] * deltalambda; + + + vec2.scale(temp, Gj, invMassj*deltalambda); + vec2.multiply(temp, temp, bj.massMultiplier); + vec2.add( bj.vlambda, bj.vlambda, temp); + //bj.wlambda -= vec2.crossLength(temp,rj); + bj.wlambda += invIj * G[5] * deltalambda; +}; + +/** + * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps + * @method computeInvC + * @param {Number} eps + * @return {Number} + */ +Equation.prototype.computeInvC = function(eps){ + return 1.0 / (this.computeGiMGt() + eps); +}; + +},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('./Equation') +, Utils = _dereq_('../utils/Utils'); + +module.exports = FrictionEquation; + +/** + * Constrains the slipping in a contact along a tangent + * + * @class FrictionEquation + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Number} slipForce + * @extends Equation + */ +function FrictionEquation(bodyA, bodyB, slipForce){ + Equation.call(this, bodyA, bodyB, -slipForce, slipForce); + + /** + * Relative vector from center of body A to the contact point, world oriented. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + + /** + * Relative vector from center of body B to the contact point, world oriented. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * Tangent vector that the friction force will act along. World oriented. + * @property t + * @type {Array} + */ + this.t = vec2.create(); + + /** + * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average. + * @property contactEquations + * @type {ContactEquation} + */ + this.contactEquations = []; + + /** + * The shape in body i that triggered this friction. + * @property shapeA + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeA... + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this friction. + * @property shapeB + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeB... + */ + this.shapeB = null; + + /** + * The friction coefficient to use. + * @property frictionCoefficient + * @type {Number} + */ + this.frictionCoefficient = 0.3; +} +FrictionEquation.prototype = new Equation(); +FrictionEquation.prototype.constructor = FrictionEquation; + +/** + * Set the slipping condition for the constraint. The friction force cannot be + * larger than this value. + * @method setSlipForce + * @param {Number} slipForce + */ +FrictionEquation.prototype.setSlipForce = function(slipForce){ + this.maxForce = slipForce; + this.minForce = -slipForce; +}; + +/** + * Get the max force for the constraint. + * @method getSlipForce + * @return {Number} + */ +FrictionEquation.prototype.getSlipForce = function(){ + return this.maxForce; +}; + +FrictionEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + t = this.t, + G = this.G; + + // G = [-t -rixt t rjxt] + // And remember, this is a pure velocity constraint, g is always zero! + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + + var GW = this.computeGW(), + GiMf = this.computeGiMf(); + + var B = /* - g * a */ - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class RotationalLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in bodyA. + */ +function RotationalLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + + /** + * @property {number} angle + */ + this.angle = options.angle || 0; + + var G = this.G; + G[2] = 1; + G[5] = -1; +} +RotationalLockEquation.prototype = new Equation(); +RotationalLockEquation.prototype.constructor = RotationalLockEquation; + +var worldVectorA = vec2.create(), + worldVectorB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1); +RotationalLockEquation.prototype.computeGq = function(){ + vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); + vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); + return vec2.dot(worldVectorA,worldVectorB); +}; + +},{"../math/vec2":30,"./Equation":22}],25:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalVelocityEquation; + +/** + * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). + * + * @class RotationalVelocityEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function RotationalVelocityEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + this.relativeVelocity = 1; + this.ratio = 1; +} +RotationalVelocityEquation.prototype = new Equation(); +RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; +RotationalVelocityEquation.prototype.computeB = function(a,b,h){ + var G = this.G; + G[2] = -1; + G[5] = this.ratio; + + var GiMf = this.computeGiMf(); + var GW = this.computeGW(); + var B = - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"./Equation":22}],26:[function(_dereq_,module,exports){ +/** + * Base class for objects that dispatches events. + * @class EventEmitter + * @constructor + */ +var EventEmitter = function () {}; + +module.exports = EventEmitter; + +EventEmitter.prototype = { + constructor: EventEmitter, + + /** + * Add an event listener + * @method on + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + on: function ( type, listener, context ) { + listener.context = context || this; + if ( this._listeners === undefined ){ + this._listeners = {}; + } + var listeners = this._listeners; + if ( listeners[ type ] === undefined ) { + listeners[ type ] = []; + } + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + listeners[ type ].push( listener ); + } + return this; + }, + + /** + * Check if an event listener is added + * @method has + * @param {String} type + * @param {Function} listener + * @return {Boolean} + */ + has: function ( type, listener ) { + if ( this._listeners === undefined ){ + return false; + } + var listeners = this._listeners; + if(listener){ + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + return true; + } + } else { + if ( listeners[ type ] !== undefined ) { + return true; + } + } + + return false; + }, + + /** + * Remove an event listener + * @method off + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + off: function ( type, listener ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var index = listeners[ type ].indexOf( listener ); + if ( index !== - 1 ) { + listeners[ type ].splice( index, 1 ); + } + return this; + }, + + /** + * Emit an event. + * @method emit + * @param {Object} event + * @param {String} event.type + * @return {EventEmitter} The self object, for chainability. + */ + emit: function ( event ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; + if ( listenerArray !== undefined ) { + event.target = this; + for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { + var listener = listenerArray[ i ]; + listener.call( listener.context, event ); + } + } + return this; + } +}; + +},{}],27:[function(_dereq_,module,exports){ +var Material = _dereq_('./Material'); +var Equation = _dereq_('../equations/Equation'); + +module.exports = ContactMaterial; + +/** + * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. + * @class ContactMaterial + * @constructor + * @param {Material} materialA + * @param {Material} materialB + * @param {Object} [options] + * @param {Number} [options.friction=0.3] Friction coefficient. + * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". + * @param {Number} [options.stiffness] ContactEquation stiffness. + * @param {Number} [options.relaxation] ContactEquation relaxation. + * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. + * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. + * @param {Number} [options.surfaceVelocity=0] Surface velocity. + * @author schteppe + */ +function ContactMaterial(materialA, materialB, options){ + options = options || {}; + + if(!(materialA instanceof Material) || !(materialB instanceof Material)){ + throw new Error("First two arguments must be Material instances."); + } + + /** + * The contact material identifier + * @property id + * @type {Number} + */ + this.id = ContactMaterial.idCounter++; + + /** + * First material participating in the contact material + * @property materialA + * @type {Material} + */ + this.materialA = materialA; + + /** + * Second material participating in the contact material + * @property materialB + * @type {Material} + */ + this.materialB = materialB; + + /** + * Friction coefficient to use in the contact of these two materials. Friction = 0 will make the involved objects super slippery, and friction = 1 will make it much less slippery. A friction coefficient larger than 1 will allow for very large friction forces, which can be convenient for preventing car tires not slip on the ground. + * @property friction + * @type {Number} + * @default 0.3 + */ + this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; + + /** + * Restitution, or "bounciness" to use in the contact of these two materials. A restitution of 0 will make no bounce, while restitution=1 will approximately bounce back with the same velocity the object came with. + * @property restitution + * @type {Number} + * @default 0 + */ + this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0; + + /** + * Hardness of the contact. Less stiffness will make the objects penetrate more, and will make the contact act more like a spring than a contact force. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property stiffness + * @type {Number} + */ + this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting ContactEquation that this ContactMaterial generate. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property relaxation + * @type {Number} + */ + this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Stiffness of the resulting friction force. For most cases, the value of this property should be a large number. I cannot think of any case where you would want less frictionStiffness. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property frictionStiffness + * @type {Number} + */ + this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting friction force. The default value should be good for most simulations. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property frictionRelaxation + * @type {Number} + */ + this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + * @property {Number} surfaceVelocity + * @default 0 + */ + this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; + + /** + * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts". + * @property contactSkinSize + * @type {Number} + */ + this.contactSkinSize = 0.005; +} + +ContactMaterial.idCounter = 0; + +},{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){ +module.exports = Material; + +/** + * Defines a physics material. + * @class Material + * @constructor + * @param {number} id Material identifier + * @author schteppe + */ +function Material(id){ + /** + * The material identifier + * @property id + * @type {Number} + */ + this.id = id || Material.idCounter++; +} + +Material.idCounter = 0; + +},{}],29:[function(_dereq_,module,exports){ + + /* + PolyK library + url: http://polyk.ivank.net + Released under MIT licence. + + Copyright (c) 2012 Ivan Kuckir + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + */ + + var PolyK = {}; + + /* + Is Polygon self-intersecting? + + O(n^2) + */ + /* + PolyK.IsSimple = function(p) + { + var n = p.length>>1; + if(n<4) return true; + var a1 = new PolyK._P(), a2 = new PolyK._P(); + var b1 = new PolyK._P(), b2 = new PolyK._P(); + var c = new PolyK._P(); + + for(var i=0; i>1; + if(n<3) return []; + var tgs = []; + var avl = []; + for(var i=0; i 3) + { + 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; j 3*al) break; // no convex angles :( + } + tgs.push(avl[0], avl[1], avl[2]); + return tgs; + } + /* + PolyK.ContainsPoint = function(p, px, py) + { + var n = p.length>>1; + var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; + var depth = 0; + for(var i=0; i=0 && by>=0) continue; // both "up" or both "donw" + if(ax< 0 && bx< 0) continue; + + var lx = ax + (bx-ax)*(-ay)/(by-ay); + if(lx>0) depth++; + } + return (depth & 1) == 1; + } + + PolyK.Slice = function(p, ax, ay, bx, by) + { + if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; + + var a = new PolyK._P(ax, ay); + var b = new PolyK._P(bx, by); + var iscs = []; // intersections + var ps = []; // points + for(var i=0; i 0) + { + var n = ps.length; + var i0 = iscs[0]; + var i1 = iscs[1]; + var ind0 = ps.indexOf(i0); + var ind1 = ps.indexOf(i1); + var solved = false; + + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + else + { + i0 = iscs[1]; + i1 = iscs[0]; + ind0 = ps.indexOf(i0); + ind1 = ps.indexOf(i1); + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + } + if(solved) + { + dir--; + var pgn = PolyK._getPoints(ps, ind0, ind1); + pgs.push(pgn); + ps = PolyK._getPoints(ps, ind1, ind0); + i0.flag = i1.flag = false; + iscs.splice(0,2); + if(iscs.length == 0) pgs.push(ps); + } + else { dir++; iscs.reverse(); } + if(dir>1) break; + } + var result = []; + for(var i=0; i>1, isc); + } + b1.x = b2.x; b1.y = b2.y; + b2.x = p[0]; b2.y = p[1]; + PolyK._pointLineDist(a1, b1, b2, l>>1, isc); + + var idst = 1/isc.dist; + isc.norm.x = (x-isc.point.x)*idst; + isc.norm.y = (y-isc.point.y)*idst; + return isc; + } + + PolyK._pointLineDist = function(p, a, b, edge, isc) + { + var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; + + var A = x - x1; + var B = y - y1; + var C = x2 - x1; + var D = y2 - y1; + + var dot = A * C + B * D; + var len_sq = C * C + D * D; + var param = dot / len_sq; + + var xx, yy; + + if (param < 0 || (x1 == x2 && y1 == y2)) { + xx = x1; + yy = y1; + } + else if (param > 1) { + xx = x2; + yy = y2; + } + else { + xx = x1 + param * C; + yy = y1 + param * D; + } + + var dx = x - xx; + var dy = y - yy; + var dst = Math.sqrt(dx * dx + dy * dy); + if(dst= 0) && (v >= 0) && (u + v < 1); + } + /* + PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) + { + var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); + var day = (a1.y-a2.y), dby = (b1.y-b2.y); + + var Den = dax*dby - day*dbx; + if (Den == 0) return null; // parallel + + var A = (a1.x * a2.y - a1.y * a2.x); + var B = (b1.x * b2.y - b1.y * b2.x); + + var I = c; + var iDen = 1/Den; + I.x = ( A*dbx - dax*B ) * iDen; + I.y = ( A*dby - day*B ) * iDen; + + if(!PolyK._InRect(I, b1, b2)) return null; + if((day>0 && I.y>a1.y) || (day<0 && I.y0 && I.x>a1.x) || (dax<0 && I.x=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); + if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); + + if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) + && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) + return true; + return false; + } + */ + PolyK._convex = function(ax, ay, bx, by, cx, cy) + { + return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; + } + /* + PolyK._P = function(x,y) + { + this.x = x; + this.y = y; + this.flag = false; + } + PolyK._P.prototype.toString = function() + { + return "Point ["+this.x+", "+this.y+"]"; + } + PolyK._P.dist = function(a,b) + { + var dx = b.x-a.x; + var dy = b.y-a.y; + return Math.sqrt(dx*dx + dy*dy); + } + + PolyK._tp = []; + for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); + */ + +module.exports = PolyK; + +},{}],30:[function(_dereq_,module,exports){ +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. + * @class vec2 + */ + +var vec2 = module.exports = {}; + +var Utils = _dereq_('../utils/Utils'); + +/** + * Make a cross product and only return the z component + * @method crossLength + * @static + * @param {Array} a + * @param {Array} b + * @return {Number} + */ +vec2.crossLength = function(a,b){ + return a[0] * b[1] - a[1] * b[0]; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossVZ + * @static + * @param {Array} out + * @param {Array} vec + * @param {Number} zcomp + * @return {Number} + */ +vec2.crossVZ = function(out, vec, zcomp){ + vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossZV + * @static + * @param {Array} out + * @param {Number} zcomp + * @param {Array} vec + * @return {Number} + */ +vec2.crossZV = function(out, zcomp, vec){ + vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Rotate a vector by an angle + * @method rotate + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate = function(out,a,angle){ + if(angle !== 0){ + 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; + } else { + out[0] = a[0]; + out[1] = a[1]; + } +}; + +/** + * Rotate a vector 90 degrees clockwise + * @method rotate90cw + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate90cw = function(out, a) { + var x = a[0]; + var y = a[1]; + out[0] = y; + out[1] = -x; +}; + +/** + * Transform a point position to local frame. + * @method toLocalFrame + * @param {Array} out + * @param {Array} worldPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ + vec2.copy(out, worldPoint); + vec2.sub(out, out, framePosition); + vec2.rotate(out, out, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ + vec2.copy(out, localPoint); + vec2.rotate(out, out, frameAngle); + vec2.add(out, out, framePosition); +}; + +/** + * Transform a vector to local frame. + * @method vectorToLocalFrame + * @param {Array} out + * @param {Array} worldVector + * @param {Number} frameAngle + */ +vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ + vec2.rotate(out, worldVector, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localVector + * @param {Number} frameAngle + */ +vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){ + vec2.rotate(out, localVector, frameAngle); +}; + +/** + * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php + * @method centroid + * @static + * @param {Array} out + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Array} The out object + */ +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; +}; + +/** + * Creates a new, empty vec2 + * @static + * @method create + * @return {Array} a new 2D vector + */ +vec2.create = function() { + var out = new Utils.ARRAY_TYPE(2); + out[0] = 0; + out[1] = 0; + return out; +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * @static + * @method clone + * @param {Array} a vector to clone + * @return {Array} a new 2D vector + */ +vec2.clone = function(a) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Creates a new vec2 initialized with the given values + * @static + * @method fromValues + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} a new 2D vector + */ +vec2.fromValues = function(x, y) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Copy the values from one vec2 to another + * @static + * @method copy + * @param {Array} out the receiving vector + * @param {Array} a the source vector + * @return {Array} out + */ +vec2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * @static + * @method set + * @param {Array} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} out + */ +vec2.set = function(out, x, y) { + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Adds two vec2's + * @static + * @method add + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +}; + +/** + * Subtracts two vec2's + * @static + * @method subtract + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +}; + +/** + * Alias for vec2.subtract + * @static + * @method sub + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * @static + * @method multiply + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +}; + +/** + * Alias for vec2.multiply + * @static + * @method mul + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * @static + * @method divide + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +}; + +/** + * Alias for vec2.divide + * @static + * @method div + */ +vec2.div = vec2.divide; + +/** + * Scales a vec2 by a scalar number + * @static + * @method scale + * @param {Array} out the receiving vector + * @param {Array} a the vector to scale + * @param {Number} b amount to scale the vector by + * @return {Array} out + */ +vec2.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * @static + * @method distance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} distance between a and b + */ +vec2.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.distance + * @static + * @method dist + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * @static + * @method squaredDistance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} squared distance between a and b + */ +vec2.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredDistance + * @static + * @method sqrDist + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * @static + * @method length + * @param {Array} a vector to calculate length of + * @return {Number} length of a + */ +vec2.length = function (a) { + var x = a[0], + y = a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.length + * @method len + * @static + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * @static + * @method squaredLength + * @param {Array} a vector to calculate squared length of + * @return {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a[0], + y = a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredLength + * @static + * @method sqrLen + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * @static + * @method negate + * @param {Array} out the receiving vector + * @param {Array} a vector to negate + * @return {Array} out + */ +vec2.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +}; + +/** + * Normalize a vec2 + * @static + * @method normalize + * @param {Array} out the receiving vector + * @param {Array} a vector to normalize + * @return {Array} out + */ +vec2.normalize = function(out, a) { + var x = a[0], + y = a[1]; + var len = x*x + y*y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * @static + * @method dot + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1]; +}; + +/** + * Returns a string representation of a vector + * @static + * @method str + * @param {Array} vec vector to represent as a string + * @return {String} string representation of the vector + */ +vec2.str = function (a) { + return 'vec2(' + a[0] + ', ' + a[1] + ')'; +}; + +/** + * Linearly interpolate/mix two vectors. + * @static + * @method lerp + * @param {Array} out + * @param {Array} a First vector + * @param {Array} b Second vector + * @param {number} t Lerp factor + */ +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; +}; + +/** + * Reflect a vector along a normal. + * @static + * @method reflect + * @param {Array} out + * @param {Array} vector + * @param {Array} normal + */ +vec2.reflect = function(out, vector, normal){ + var dot = vector[0] * normal[0] + vector[1] * normal[1]; + out[0] = vector[0] - 2 * normal[0] * dot; + out[1] = vector[1] - 2 * normal[1] * dot; +}; + +/** + * Get the intersection point between two line segments. + * @static + * @method getLineSegmentsIntersection + * @param {Array} out + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {boolean} True if there was an intersection, otherwise false. + */ +vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { + var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); + if(t < 0){ + return false; + } else { + out[0] = p0[0] + (t * (p1[0] - p0[0])); + out[1] = p0[1] + (t * (p1[1] - p0[1])); + return true; + } +}; + +/** + * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) + * @static + * @method getLineSegmentsIntersectionFraction + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. + */ +vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { + var s1_x = p1[0] - p0[0]; + var s1_y = p1[1] - p0[1]; + var s2_x = p3[0] - p2[0]; + var s2_y = p3[1] - p2[1]; + + var s, t; + s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); + t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); + if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + return t; + } + return -1; // No collision +}; + +},{"../utils/Utils":57}],31:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, decomp = _dereq_('poly-decomp') +, Convex = _dereq_('../shapes/Convex') +, RaycastResult = _dereq_('../collision/RaycastResult') +, Ray = _dereq_('../collision/Ray') +, AABB = _dereq_('../collision/AABB') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Body; + +/** + * A rigid body. Has got a center of mass, position, velocity and a number of + * shapes that are used for collisions. + * + * @class Body + * @constructor + * @extends EventEmitter + * @param {Array} [options.force] + * @param {Array} [options.position] + * @param {Array} [options.velocity] + * @param {Boolean} [options.allowSleep] + * @param {Boolean} [options.collisionResponse] + * @param {Number} [options.angle=0] + * @param {Number} [options.angularForce=0] + * @param {Number} [options.angularVelocity=0] + * @param {Number} [options.ccdIterations=10] + * @param {Number} [options.ccdSpeedThreshold=-1] + * @param {Number} [options.fixedRotation=false] + * @param {Number} [options.gravityScale] + * @param {Number} [options.id] + * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. + * @param {Number} [options.sleepSpeedLimit] + * @param {Number} [options.sleepTimeLimit] + * @param {Object} [options] + * + * @example + * + * // Create a typical dynamic body + * var body = new Body({ + * mass: 1, + * position: [0, 0], + * angle: 0, + * velocity: [0, 0], + * angularVelocity: 0 + * }); + * + * // Add a circular shape to the body + * body.addShape(new Circle({ radius: 1 })); + * + * // Add the body to the world + * world.addBody(body); + */ +function Body(options){ + options = options || {}; + + EventEmitter.call(this); + + /** + * The body identifyer + * @property id + * @type {Number} + */ + this.id = options.id || ++Body._idCounter; + + /** + * The world that this body is added to. This property is set to NULL if the body is not added to any world. + * @property world + * @type {World} + */ + this.world = null; + + /** + * The shapes of the body. + * + * @property shapes + * @type {Array} + */ + this.shapes = []; + + /** + * The mass of the body. + * @property mass + * @type {number} + */ + this.mass = options.mass || 0; + + /** + * The inverse mass of the body. + * @property invMass + * @type {number} + */ + this.invMass = 0; + + /** + * The inertia of the body around the Z axis. + * @property inertia + * @type {number} + */ + this.inertia = 0; + + /** + * The inverse inertia of the body. + * @property invInertia + * @type {number} + */ + this.invInertia = 0; + + this.invMassSolve = 0; + this.invInertiaSolve = 0; + + /** + * Set to true if you want to fix the rotation of the body. + * @property fixedRotation + * @type {Boolean} + */ + this.fixedRotation = !!options.fixedRotation; + + /** + * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y. + * @property {Boolean} fixedX + */ + this.fixedX = !!options.fixedX; + + /** + * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X. + * @property {Boolean} fixedY + */ + this.fixedY = !!options.fixedY; + + /** + * @private + * @property {array} massMultiplier + */ + this.massMultiplier = vec2.create(); + + /** + * The position of the body + * @property position + * @type {Array} + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * The interpolated position of the body. Use this for rendering. + * @property interpolatedPosition + * @type {Array} + */ + this.interpolatedPosition = vec2.fromValues(0,0); + + /** + * The interpolated angle of the body. Use this for rendering. + * @property interpolatedAngle + * @type {Number} + */ + this.interpolatedAngle = 0; + + /** + * The previous position of the body. + * @property previousPosition + * @type {Array} + */ + this.previousPosition = vec2.fromValues(0,0); + + /** + * The previous angle of the body. + * @property previousAngle + * @type {Number} + */ + this.previousAngle = 0; + + /** + * The current velocity of the body. + * @property velocity + * @type {Array} + */ + this.velocity = vec2.fromValues(0,0); + if(options.velocity){ + vec2.copy(this.velocity, options.velocity); + } + + /** + * Constraint velocity that was added to the body during the last step. + * @property vlambda + * @type {Array} + */ + this.vlambda = vec2.fromValues(0,0); + + /** + * Angular constraint velocity that was added to the body during last step. + * @property wlambda + * @type {Array} + */ + this.wlambda = 0; + + /** + * The angle of the body, in radians. + * @property angle + * @type {number} + * @example + * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. + * // If you need a value between 0 and 2*pi, use the following function to normalize it. + * function normalizeAngle(angle){ + * angle = angle % (2*Math.PI); + * if(angle < 0){ + * angle += (2*Math.PI); + * } + * return angle; + * } + */ + this.angle = options.angle || 0; + + /** + * The angular velocity of the body, in radians per second. + * @property angularVelocity + * @type {number} + */ + this.angularVelocity = options.angularVelocity || 0; + + /** + * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. + * @property force + * @type {Array} + * + * @example + * // This produces a forcefield of 1 Newton in the positive x direction. + * for(var i=0; i radius){ + radius = offset + r; + } + } + + this.boundingRadius = radius; +}; + +/** + * Add a shape to the body. You can pass a local transform when adding a shape, + * so that the shape gets an offset and angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * + * @method addShape + * @param {Shape} shape + * @param {Array} [offset] Local body offset of the shape. + * @param {Number} [angle] Local body angle. + * + * @example + * var body = new Body(), + * shape = new Circle({ radius: 1 }); + * + * // Add the shape to the body, positioned in the center + * body.addShape(shape); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. + * body.addShape(shape,[1,0]); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. + * body.addShape(shape,[0,1],Math.PI/2); + */ +Body.prototype.addShape = function(shape, offset, angle){ + if(shape.body){ + throw new Error('A shape can only be added to one body.'); + } + shape.body = this; + + // Copy the offset vector + if(offset){ + vec2.copy(shape.position, offset); + } else { + vec2.set(shape.position, 0, 0); + } + + shape.angle = angle || 0; + + this.shapes.push(shape); + this.updateMassProperties(); + this.updateBoundingRadius(); + + this.aabbNeedsUpdate = true; +}; + +/** + * Remove a shape + * @method removeShape + * @param {Shape} shape + * @return {Boolean} True if the shape was found and removed, else false. + */ +Body.prototype.removeShape = function(shape){ + var idx = this.shapes.indexOf(shape); + + if(idx !== -1){ + this.shapes.splice(idx,1); + this.aabbNeedsUpdate = true; + shape.body = null; + return true; + } else { + return false; + } +}; + +/** + * Updates .inertia, .invMass, .invInertia for this Body. Should be called when + * changing the structure or mass of the Body. + * + * @method updateMassProperties + * + * @example + * body.mass += 1; + * body.updateMassProperties(); + */ +Body.prototype.updateMassProperties = function(){ + if(this.type === Body.STATIC || this.type === 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; + } + + // Inverse mass properties are easy + this.invMass = 1 / this.mass; + + vec2.set( + this.massMultiplier, + this.fixedX ? 0 : 1, + this.fixedY ? 0 : 1 + ); + } +}; + +var Body_applyForce_r = vec2.create(); + +/** + * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero. + * @method applyForce + * @param {Array} force The force to add. + * @param {Array} [relativePoint] A world point to apply the force on. + */ +Body.prototype.applyForce = function(force, relativePoint){ + + // Add linear force + vec2.add(this.force, this.force, force); + + if(relativePoint){ + + // Compute produced rotational force + var rotForce = vec2.crossLength(relativePoint,force); + + // Add rotational force + this.angularForce += rotForce; + } +}; + +/** + * Apply force to a body-local point. + * @method applyForceLocal + * @param {Array} localForce The force vector to add, oriented in local body space. + * @param {Array} [localPoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyForce_forceWorld = vec2.create(); +var Body_applyForce_pointWorld = vec2.create(); +var Body_applyForce_pointLocal = vec2.create(); +Body.prototype.applyForceLocal = function(localForce, localPoint){ + localPoint = localPoint || Body_applyForce_pointLocal; + var worldForce = Body_applyForce_forceWorld; + var worldPoint = Body_applyForce_pointWorld; + this.vectorToWorldFrame(worldForce, localForce); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyForce(worldForce, worldPoint); +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulse + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_velo = vec2.create(); +Body.prototype.applyImpulse = function(impulseVector, relativePoint){ + if(this.type !== Body.DYNAMIC){ + return; + } + + // Compute produced central impulse velocity + var velo = Body_applyImpulse_velo; + vec2.scale(velo, impulseVector, this.invMass); + vec2.multiply(velo, this.massMultiplier, velo); + + // Add linear impulse + vec2.add(this.velocity, velo, this.velocity); + + if(relativePoint){ + // Compute produced rotational impulse velocity + var rotVelo = vec2.crossLength(relativePoint, impulseVector); + rotVelo *= this.invInertia; + + // Add rotational Impulse + this.angularVelocity += rotVelo; + } +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulseLocal + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_impulseWorld = vec2.create(); +var Body_applyImpulse_pointWorld = vec2.create(); +var Body_applyImpulse_pointLocal = vec2.create(); +Body.prototype.applyImpulseLocal = function(localImpulse, localPoint){ + localPoint = localPoint || Body_applyImpulse_pointLocal; + var worldImpulse = Body_applyImpulse_impulseWorld; + var worldPoint = Body_applyImpulse_pointWorld; + this.vectorToWorldFrame(worldImpulse, localImpulse); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyImpulse(worldImpulse, worldPoint); +}; + +/** + * Transform a world point to local body frame. + * @method toLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldPoint The input world point + */ +Body.prototype.toLocalFrame = function(out, worldPoint){ + vec2.toLocalFrame(out, worldPoint, this.position, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method toWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localPoint The input local point + */ +Body.prototype.toWorldFrame = function(out, localPoint){ + vec2.toGlobalFrame(out, localPoint, this.position, this.angle); +}; + +/** + * Transform a world point to local body frame. + * @method vectorToLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldVector The input world vector + */ +Body.prototype.vectorToLocalFrame = function(out, worldVector){ + vec2.vectorToLocalFrame(out, worldVector, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method vectorToWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localVector The input local vector + */ +Body.prototype.vectorToWorldFrame = function(out, localVector){ + vec2.vectorToGlobalFrame(out, localVector, this.angle); +}; + +/** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. + * @method fromPolygon + * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. + * @param {Object} [options] + * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. + * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @return {Boolean} True on success, else false. + */ +Body.prototype.fromPolygon = function(path,options){ + options = options || {}; + + // Remove all shapes + for(var i=this.shapes.length; i>=0; --i){ + this.removeShape(this.shapes[i]); + } + + var p = new decomp.Polygon(); + p.vertices = path; + + // Make it counter-clockwise + p.makeCCW(); + + if(typeof(options.removeCollinearPoints) === "number"){ + p.removeCollinearPoints(options.removeCollinearPoints); + } + + // Check if any line segment intersects the path itself + if(typeof(options.skipSimpleCheck) === "undefined"){ + if(!p.isSimple()){ + return false; + } + } + + // Save this path for later + this.concavePath = p.vertices.slice(0); + for(var i=0; ithis for details. + * @method applyDamping + * @param {number} dt Current time step + */ +Body.prototype.applyDamping = function(dt){ + if(this.type === Body.DYNAMIC){ // Only for dynamic bodies + var v = this.velocity; + vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); + this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); + } +}; + +/** + * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. + * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. + * @method wakeUp + */ +Body.prototype.wakeUp = function(){ + var s = this.sleepState; + this.sleepState = Body.AWAKE; + this.idleTime = 0; + if(s !== Body.AWAKE){ + this.emit(Body.wakeUpEvent); + } +}; + +/** + * Force body sleep + * @method sleep + */ +Body.prototype.sleep = function(){ + this.sleepState = Body.SLEEPING; + this.angularVelocity = 0; + this.angularForce = 0; + vec2.set(this.velocity,0,0); + vec2.set(this.force,0,0); + this.emit(Body.sleepEvent); +}; + +/** + * Called every timestep to update internal sleep timer and change sleep state if needed. + * @method sleepTick + * @param {number} time The world time in seconds + * @param {boolean} dontSleep + * @param {number} dt + */ +Body.prototype.sleepTick = function(time, dontSleep, dt){ + if(!this.allowSleep || this.type === Body.SLEEPING){ + return; + } + + this.wantsToSleep = false; + + var sleepState = this.sleepState, + speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), + speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); + + // Add to idle time + if(speedSquared >= 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; + } + } +}; + +/** + * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. + * @method overlaps + * @param {Body} body + * @return {boolean} + */ +Body.prototype.overlaps = function(body){ + return this.world.overlapKeeper.bodiesAreOverlapping(this, body); +}; + +var integrate_fhMinv = vec2.create(); +var integrate_velodt = vec2.create(); + +/** + * Move the body forward in time given its current velocity. + * @method integrate + * @param {Number} dt + */ +Body.prototype.integrate = function(dt){ + var minv = this.invMass, + f = this.force, + pos = this.position, + velo = this.velocity; + + // Save old position + vec2.copy(this.previousPosition, this.position); + this.previousAngle = this.angle; + + // Velocity update + if(!this.fixedRotation){ + this.angularVelocity += this.angularForce * this.invInertia * dt; + } + vec2.scale(integrate_fhMinv, f, dt * minv); + vec2.multiply(integrate_fhMinv, this.massMultiplier, integrate_fhMinv); + vec2.add(velo, integrate_fhMinv, velo); + + // CCD + if(!this.integrateToTimeOfImpact(dt)){ + + // Regular position update + vec2.scale(integrate_velodt, velo, dt); + vec2.add(pos, pos, integrate_velodt); + if(!this.fixedRotation){ + this.angle += this.angularVelocity * dt; + } + } + + this.aabbNeedsUpdate = true; +}; + +var result = new RaycastResult(); +var ray = new Ray({ + mode: Ray.ALL +}); +var direction = vec2.create(); +var end = vec2.create(); +var startToEnd = vec2.create(); +var rememberPosition = vec2.create(); +Body.prototype.integrateToTimeOfImpact = function(dt){ + + if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){ + return false; + } + + vec2.normalize(direction, this.velocity); + + vec2.scale(end, this.velocity, dt); + vec2.add(end, end, this.position); + + vec2.sub(startToEnd, end, this.position); + var startToEndAngle = this.angularVelocity * dt; + var len = vec2.length(startToEnd); + + var timeOfImpact = 1; + + var hit; + var that = this; + result.reset(); + ray.callback = function (result) { + if(result.body === that){ + return; + } + hit = result.body; + result.getHitPoint(end, ray); + vec2.sub(startToEnd, end, that.position); + timeOfImpact = vec2.length(startToEnd) / len; + result.stop(); + }; + vec2.copy(ray.from, this.position); + vec2.copy(ray.to, end); + ray.update(); + this.world.raycast(result, ray); + + if(!hit){ + return false; + } + + var rememberAngle = this.angle; + vec2.copy(rememberPosition, this.position); + + // Got a start and end point. Approximate time of impact using binary search + var iter = 0; + var tmin = 0; + var tmid = 0; + var tmax = timeOfImpact; + while (tmax >= tmin && iter < this.ccdIterations) { + iter++; + + // calculate the midpoint + tmid = (tmax - tmin) / 2; + + // Move the body to that point + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, rememberPosition, integrate_velodt); + this.angle = rememberAngle + startToEndAngle * timeOfImpact; + this.updateAABB(); + + // check overlap + var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit); + + if (overlaps) { + // change min to search upper interval + tmin = tmid; + } else { + // change max to search lower interval + tmax = tmid; + } + } + + timeOfImpact = tmid; + + vec2.copy(this.position, rememberPosition); + this.angle = rememberAngle; + + // move to TOI + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, this.position, integrate_velodt); + if(!this.fixedRotation){ + this.angle += startToEndAngle * timeOfImpact; + } + + return true; +}; + +/** + * Get velocity of a point in the body. + * @method getVelocityAtPoint + * @param {Array} result A vector to store the result in + * @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from + * @return {Array} The result vector + */ +Body.prototype.getVelocityAtPoint = function(result, relativePoint){ + vec2.crossVZ(result, relativePoint, this.angularVelocity); + vec2.subtract(result, this.velocity, result); + return result; +}; + +/** + * @event sleepy + */ +Body.sleepyEvent = { + type: "sleepy" +}; + +/** + * @event sleep + */ +Body.sleepEvent = { + type: "sleep" +}; + +/** + * @event wakeup + */ +Body.wakeUpEvent = { + type: "wakeup" +}; + +/** + * Dynamic body. + * @property DYNAMIC + * @type {Number} + * @static + */ +Body.DYNAMIC = 1; + +/** + * Static body. + * @property STATIC + * @type {Number} + * @static + */ +Body.STATIC = 2; + +/** + * Kinematic body. + * @property KINEMATIC + * @type {Number} + * @static + */ +Body.KINEMATIC = 4; + +/** + * @property AWAKE + * @type {Number} + * @static + */ +Body.AWAKE = 0; + +/** + * @property SLEEPY + * @type {Number} + * @static + */ +Body.SLEEPY = 1; + +/** + * @property SLEEPING + * @type {Number} + * @static + */ +Body.SLEEPING = 2; + + +},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = LinearSpring; + +/** + * A spring, connecting two bodies. + * + * The Spring explicitly adds force and angularForce to the bodies. + * + * @class LinearSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + */ +function LinearSpring(bodyA,bodyB,options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Anchor for bodyA in local bodyA coordinates. + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = vec2.fromValues(0,0); + + /** + * Anchor for bodyB in local bodyB coordinates. + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = vec2.fromValues(0,0); + + if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); } + if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); } + if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } + if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } + + var worldAnchorA = vec2.create(); + var worldAnchorB = vec2.create(); + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + var worldDistance = vec2.distance(worldAnchorA, worldAnchorB); + + /** + * Rest length of the spring. + * @property restLength + * @type {number} + */ + this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance; +} +LinearSpring.prototype = new Spring(); +LinearSpring.prototype.constructor = LinearSpring; + +/** + * Set the anchor point on body A, using world coordinates. + * @method setWorldAnchorA + * @param {Array} worldAnchorA + */ +LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){ + this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); +}; + +/** + * Set the anchor point on body B, using world coordinates. + * @method setWorldAnchorB + * @param {Array} worldAnchorB + */ +LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){ + this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); +}; + +/** + * Get the anchor point on body A, in world coordinates. + * @method getWorldAnchorA + * @param {Array} result The vector to store the result in. + */ +LinearSpring.prototype.getWorldAnchorA = function(result){ + this.bodyA.toWorldFrame(result, this.localAnchorA); +}; + +/** + * Get the anchor point on body B, in world coordinates. + * @method getWorldAnchorB + * @param {Array} result The vector to store the result in. + */ +LinearSpring.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(); + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +LinearSpring.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; + + // Get world anchors + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + + // Get offset points + vec2.sub(ri, worldAnchorA, bodyA.position); + vec2.sub(rj, worldAnchorB, bodyB.position); + + // Compute distance vector between world anchor points + vec2.sub(r, worldAnchorB, worldAnchorA); + var rlen = vec2.len(r); + vec2.normalize(r_unit,r); + + //console.log(rlen) + //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) + + // Compute relative velocity of the anchor points, u + 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); + + // F = - k * ( x - L ) - D * ( u ) + vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); + + // Add forces to bodies + vec2.sub( bodyA.force, bodyA.force, f); + vec2.add( bodyB.force, bodyB.force, f); + + // Angular force + 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":57,"./Spring":34}],33:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); + +module.exports = RotationalSpring; + +/** + * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies. + * + * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap. + * + * @class RotationalSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. + */ +function RotationalSpring(bodyA, bodyB, options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Rest angle of the spring. + * @property restAngle + * @type {number} + */ + this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle; +} +RotationalSpring.prototype = new Spring(); +RotationalSpring.prototype.constructor = RotationalSpring; + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +RotationalSpring.prototype.applyForce = function(){ + var k = this.stiffness, + d = this.damping, + l = this.restAngle, + bodyA = this.bodyA, + bodyB = this.bodyB, + x = bodyB.angle - bodyA.angle, + u = bodyB.angularVelocity - bodyA.angularVelocity; + + var torque = - k * (x - l) - d * u * 0; + + bodyA.angularForce -= torque; + bodyB.angularForce += torque; +}; + +},{"../math/vec2":30,"./Spring":34}],34:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = Spring; + +/** + * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver. + * + * @class Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + */ +function Spring(bodyA, bodyB, options){ + options = Utils.defaults(options,{ + stiffness: 100, + damping: 1, + }); + + /** + * Stiffness of the spring. + * @property stiffness + * @type {number} + */ + this.stiffness = options.stiffness; + + /** + * Damping of the spring. + * @property damping + * @type {number} + */ + this.damping = options.damping; + + /** + * First connected body. + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second connected body. + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; +} + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +Spring.prototype.applyForce = function(){ + // To be implemented by subclasses +}; + +},{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); +var Constraint = _dereq_('../constraints/Constraint'); +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Body = _dereq_('../objects/Body'); + +module.exports = TopDownVehicle; + +/** + * @class TopDownVehicle + * @constructor + * @param {Body} chassisBody A dynamic body, already added to the world. + * @param {Object} [options] + * + * @example + * + * // Create a dynamic body for the chassis + * var chassisBody = new Body({ + * mass: 1 + * }); + * var boxShape = new Box({ width: 0.5, height: 1 }); + * chassisBody.addShape(boxShape); + * world.addBody(chassisBody); + * + * // Create the vehicle + * var vehicle = new TopDownVehicle(chassisBody); + * + * // Add one front wheel and one back wheel - we don't actually need four :) + * var frontWheel = vehicle.addWheel({ + * localPosition: [0, 0.5] // front + * }); + * frontWheel.setSideFriction(4); + * + * // Back wheel + * var backWheel = vehicle.addWheel({ + * localPosition: [0, -0.5] // back + * }); + * backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift + * vehicle.addToWorld(world); + * + * // Steer value zero means straight forward. Positive is left and negative right. + * frontWheel.steerValue = Math.PI / 16; + * + * // Engine force forward + * backWheel.engineForce = 10; + * backWheel.setBrakeForce(0); + */ +function TopDownVehicle(chassisBody, options){ + options = options || {}; + + /** + * @property {Body} chassisBody + */ + this.chassisBody = chassisBody; + + /** + * @property {Array} wheels + */ + this.wheels = []; + + // A dummy body to constrain the chassis to + this.groundBody = new Body({ mass: 0 }); + + this.world = null; + + var that = this; + this.preStepCallback = function(){ + that.update(); + }; +} + +/** + * @method addToWorld + * @param {World} world + */ +TopDownVehicle.prototype.addToWorld = function(world){ + this.world = world; + world.addBody(this.groundBody); + world.on('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.addConstraint(wheel); + } +}; + +/** + * @method removeFromWorld + * @param {World} world + */ +TopDownVehicle.prototype.removeFromWorld = function(){ + var world = this.world; + world.removeBody(this.groundBody); + world.off('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.removeConstraint(wheel); + } + this.world = null; +}; + +/** + * @method addWheel + * @param {object} [wheelOptions] + * @return {WheelConstraint} + */ +TopDownVehicle.prototype.addWheel = function(wheelOptions){ + var wheel = new WheelConstraint(this,wheelOptions); + this.wheels.push(wheel); + return wheel; +}; + +/** + * @method update + */ +TopDownVehicle.prototype.update = function(){ + for (var i = 0; i < this.wheels.length; i++) { + this.wheels[i].update(); + } +}; + +/** + * @class WheelConstraint + * @constructor + * @extends {Constraint} + * @param {Vehicle} vehicle + * @param {object} [options] + * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero. + * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body. + * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction. + */ +function WheelConstraint(vehicle, options){ + options = options || {}; + + this.vehicle = vehicle; + + this.forwardEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + this.sideEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + /** + * @property {number} steerValue + */ + this.steerValue = 0; + + /** + * @property {number} engineForce + */ + this.engineForce = 0; + + this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5); + + /** + * @property {Array} localForwardVector + */ + this.localForwardVector = vec2.fromValues(0, 1); + if(options.localForwardVector){ + vec2.copy(this.localForwardVector, options.localForwardVector); + } + + /** + * @property {Array} localPosition + */ + this.localPosition = vec2.fromValues(0, 0); + if(options.localPosition){ + vec2.copy(this.localPosition, options.localPosition); + } + + Constraint.apply(this, vehicle.chassisBody, vehicle.groundBody); + + this.equations.push( + this.forwardEquation, + this.sideEquation + ); + + this.setBrakeForce(0); +} +WheelConstraint.prototype = new Constraint(); + +/** + * @method setForwardFriction + */ +WheelConstraint.prototype.setBrakeForce = function(force){ + this.forwardEquation.setSlipForce(force); +}; + +/** + * @method setSideFriction + */ +WheelConstraint.prototype.setSideFriction = function(force){ + this.sideEquation.setSlipForce(force); +}; + +var worldVelocity = vec2.create(); +var relativePoint = vec2.create(); + +/** + * @method getSpeed + */ +WheelConstraint.prototype.getSpeed = function(){ + this.vehicle.chassisBody.vectorToWorldFrame(relativePoint, this.localForwardVector); + this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity, relativePoint); + return vec2.dot(worldVelocity, relativePoint); +}; + +var tmpVec = vec2.create(); + +/** + * @method update + */ +WheelConstraint.prototype.update = function(){ + + // Directional + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t, this.localForwardVector); + vec2.rotate(this.sideEquation.t, this.localForwardVector, Math.PI / 2); + this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t, this.sideEquation.t); + + vec2.rotate(this.forwardEquation.t, this.forwardEquation.t, this.steerValue); + vec2.rotate(this.sideEquation.t, this.sideEquation.t, this.steerValue); + + // Attachment point + this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB, this.localPosition); + vec2.copy(this.sideEquation.contactPointB, this.forwardEquation.contactPointB); + + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA, this.localPosition); + vec2.copy(this.sideEquation.contactPointA, this.forwardEquation.contactPointA); + + // Add engine force + vec2.normalize(tmpVec, this.forwardEquation.t); + vec2.scale(tmpVec, tmpVec, this.engineForce); + + this.vehicle.chassisBody.applyForce(tmpVec, this.forwardEquation.contactPointA); +}; +},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(_dereq_,module,exports){ +// Export p2 classes +var p2 = module.exports = { + AABB : _dereq_('./collision/AABB'), + AngleLockEquation : _dereq_('./equations/AngleLockEquation'), + Body : _dereq_('./objects/Body'), + Broadphase : _dereq_('./collision/Broadphase'), + Capsule : _dereq_('./shapes/Capsule'), + Circle : _dereq_('./shapes/Circle'), + Constraint : _dereq_('./constraints/Constraint'), + ContactEquation : _dereq_('./equations/ContactEquation'), + ContactEquationPool : _dereq_('./utils/ContactEquationPool'), + ContactMaterial : _dereq_('./material/ContactMaterial'), + Convex : _dereq_('./shapes/Convex'), + DistanceConstraint : _dereq_('./constraints/DistanceConstraint'), + Equation : _dereq_('./equations/Equation'), + EventEmitter : _dereq_('./events/EventEmitter'), + FrictionEquation : _dereq_('./equations/FrictionEquation'), + FrictionEquationPool : _dereq_('./utils/FrictionEquationPool'), + GearConstraint : _dereq_('./constraints/GearConstraint'), + GSSolver : _dereq_('./solver/GSSolver'), + Heightfield : _dereq_('./shapes/Heightfield'), + Line : _dereq_('./shapes/Line'), + LockConstraint : _dereq_('./constraints/LockConstraint'), + Material : _dereq_('./material/Material'), + Narrowphase : _dereq_('./collision/Narrowphase'), + NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'), + Particle : _dereq_('./shapes/Particle'), + Plane : _dereq_('./shapes/Plane'), + Pool : _dereq_('./utils/Pool'), + RevoluteConstraint : _dereq_('./constraints/RevoluteConstraint'), + PrismaticConstraint : _dereq_('./constraints/PrismaticConstraint'), + Ray : _dereq_('./collision/Ray'), + RaycastResult : _dereq_('./collision/RaycastResult'), + Box : _dereq_('./shapes/Box'), + RotationalVelocityEquation : _dereq_('./equations/RotationalVelocityEquation'), + SAPBroadphase : _dereq_('./collision/SAPBroadphase'), + Shape : _dereq_('./shapes/Shape'), + Solver : _dereq_('./solver/Solver'), + Spring : _dereq_('./objects/Spring'), + TopDownVehicle : _dereq_('./objects/TopDownVehicle'), + LinearSpring : _dereq_('./objects/LinearSpring'), + RotationalSpring : _dereq_('./objects/RotationalSpring'), + Utils : _dereq_('./utils/Utils'), + World : _dereq_('./world/World'), + vec2 : _dereq_('./math/vec2'), + version : _dereq_('../package.json').version, +}; + +Object.defineProperty(p2, 'Rectangle', { + get: function() { + console.warn('The Rectangle class has been renamed to Box.'); + return this.Box; + } +}); +},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":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/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Shape = _dereq_('./Shape') +, Convex = _dereq_('./Convex'); + +module.exports = Box; + +/** + * Box shape class. + * @class Box + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.width=1] Total width of the box + * @param {Number} [options.height=1] Total height of the box + * @extends Convex + */ +function Box(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + width: arguments[0], + height: arguments[1] + }; + console.warn('The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })'); + } + options = options || {}; + + /** + * Total width of the box + * @property width + * @type {Number} + */ + var width = this.width = options.width || 1; + + /** + * Total height of the box + * @property height + * @type {Number} + */ + var height = this.height = options.height || 1; + + var verts = [ + vec2.fromValues(-width/2, -height/2), + vec2.fromValues( width/2, -height/2), + vec2.fromValues( width/2, height/2), + vec2.fromValues(-width/2, height/2) + ]; + var axes = [ + vec2.fromValues(1, 0), + vec2.fromValues(0, 1) + ]; + + options.vertices = verts; + options.axes = axes; + options.type = Shape.BOX; + Convex.call(this, options); +} +Box.prototype = new Convex(); +Box.prototype.constructor = Box; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Box.prototype.computeMomentOfInertia = function(mass){ + var w = this.width, + h = this.height; + return mass * (h*h + w*w) / 12; +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Box.prototype.updateBoundingRadius = function(){ + var w = this.width, + h = this.height; + this.boundingRadius = Math.sqrt(w*w + h*h) / 2; +}; + +var corner1 = vec2.create(), + corner2 = vec2.create(), + corner3 = vec2.create(), + corner4 = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Box.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices,position,angle,0); +}; + +Box.prototype.updateArea = function(){ + this.area = this.width * this.height; +}; + + +},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Capsule; + +/** + * Capsule shape class. + * @class Capsule + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The distance between the end points + * @param {Number} [options.radius=1] Radius of the capsule + * @example + * var capsuleShape = new Capsule({ + * length: 1, + * radius: 2 + * }); + * body.addShape(capsuleShape); + */ +function Capsule(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + length: arguments[0], + radius: arguments[1] + }; + console.warn('The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })'); + } + options = options || {}; + + /** + * The distance between the end points. + * @property {Number} length + */ + this.length = options.length || 1; + + /** + * The radius of the capsule. + * @property {Number} radius + */ + this.radius = options.radius || 1; + + options.type = Shape.CAPSULE; + Shape.call(this, options); +} +Capsule.prototype = new Shape(); +Capsule.prototype.constructor = Capsule; + +/** + * Compute the mass moment of inertia of the Capsule. + * @method conputeMomentOfInertia + * @param {Number} mass + * @return {Number} + * @todo + */ +Capsule.prototype.computeMomentOfInertia = function(mass){ + // Approximate with rectangle + var r = this.radius, + w = this.length + r, // 2*r is too much, 0 is too little + h = r*2; + return mass * (h*h + w*w) / 12; +}; + +/** + * @method updateBoundingRadius + */ +Capsule.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius + this.length/2; +}; + +/** + * @method updateArea + */ +Capsule.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; +}; + +var r = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Capsule.prototype.computeAABB = function(out, position, angle){ + var radius = this.radius; + + // Compute center position of one of the the circles, world oriented, but with local offset + vec2.set(r,this.length / 2,0); + if(angle !== 0){ + vec2.rotate(r,r,angle); + } + + // Get bounds + 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)); + + // Add offset + vec2.add(out.lowerBound, out.lowerBound, position); + vec2.add(out.upperBound, out.upperBound, position); +}; + +var intersectCapsule_hitPointWorld = vec2.create(); +var intersectCapsule_normal = vec2.create(); +var intersectCapsule_l0 = vec2.create(); +var intersectCapsule_l1 = vec2.create(); +var intersectCapsule_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Capsule.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectCapsule_hitPointWorld; + var normal = intersectCapsule_normal; + var l0 = intersectCapsule_l0; + var l1 = intersectCapsule_l1; + + // The sides + var halfLen = this.length / 2; + for(var i=0; i<2; i++){ + + // get start and end of the line + var y = this.radius * (i*2-1); + vec2.set(l0, -halfLen, y); + vec2.set(l1, halfLen, y); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var delta = vec2.getLineSegmentsIntersectionFraction(from, to, l0, l1); + if(delta >= 0){ + vec2.rotate(normal, intersectCapsule_unit_y, angle); + vec2.scale(normal, normal, (i*2-1)); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + // Circles + var diagonalLengthSquared = Math.pow(this.radius, 2) + Math.pow(halfLen, 2); + for(var i=0; i<2; i++){ + vec2.set(l0, halfLen * (i*2-1), 0); + vec2.toGlobalFrame(l0, l0, position, angle); + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - l0[0]) + (to[1] - from[1]) * (from[1] - l0[1])); + var c = Math.pow(from[0] - l0[0], 2) + Math.pow(from[1] - l0[1], 2) - Math.pow(this.radius, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + if(delta < 0){ + // No intersection + continue; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(hitPointWorld, from, to, delta); + + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(hitPointWorld, from, to, d1); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d1, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(hitPointWorld, from, to, d2); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d2, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + } + } +}; +},{"../math/vec2":30,"./Shape":45}],39:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Circle; + +/** + * Circle shape class. + * @class Circle + * @extends Shape + * @constructor + * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {number} [options.radius=1] The radius of this circle + * + * @example + * var circleShape = new Circle({ radius: 1 }); + * body.addShape(circleShape); + */ +function Circle(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + radius: arguments[0] + }; + console.warn('The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })'); + } + options = options || {}; + + /** + * The radius of the circle. + * @property radius + * @type {number} + */ + this.radius = options.radius || 1; + + options.type = Shape.CIRCLE; + Shape.call(this, options); +} +Circle.prototype = new Shape(); +Circle.prototype.constructor = Circle; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Circle.prototype.computeMomentOfInertia = function(mass){ + var r = this.radius; + return mass * r * r / 2; +}; + +/** + * @method updateBoundingRadius + * @return {Number} + */ +Circle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius; +}; + +/** + * @method updateArea + * @return {Number} + */ +Circle.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius; +}; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +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); + } +}; + +var Ray_intersectSphere_intersectionPoint = vec2.create(); +var Ray_intersectSphere_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Circle.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from, + to = ray.to, + r = this.radius; + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1])); + var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + var intersectionPoint = Ray_intersectSphere_intersectionPoint; + var normal = Ray_intersectSphere_normal; + + if(delta < 0){ + // No intersection + return; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(intersectionPoint, from, to, delta); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, delta, normal, -1); + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(intersectionPoint, from, to, d1); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d1, normal, -1); + + if(result.shouldStop(ray)){ + return; + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(intersectionPoint, from, to, d2); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d2, normal, -1); + } + } +}; +},{"../math/vec2":30,"./Shape":45}],40:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, polyk = _dereq_('../math/polyk') +, decomp = _dereq_('poly-decomp'); + +module.exports = Convex; + +/** + * Convex shape class. + * @class Convex + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. + * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex. + * @example + * // Create a box + * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]]; + * var convexShape = new Convex({ vertices: vertices }); + * body.addShape(convexShape); + */ +function Convex(options){ + if(Array.isArray(arguments[0])){ + options = { + vertices: arguments[0], + axes: arguments[1] + }; + console.warn('The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })'); + } + options = options || {}; + + /** + * Vertices defined in the local frame. + * @property vertices + * @type {Array} + */ + this.vertices = []; + + // Copy the verts + var vertices = options.vertices !== undefined ? options.vertices : []; + for(var i=0; i < vertices.length; i++){ + var v = vec2.create(); + vec2.copy(v, vertices[i]); + this.vertices.push(v); + } + + /** + * Axes defined in the local frame. + * @property axes + * @type {Array} + */ + this.axes = []; + + if(options.axes){ + + // Copy the axes + for(var i=0; i < options.axes.length; i++){ + var axis = vec2.create(); + vec2.copy(axis, options.axes[i]); + this.axes.push(axis); + } + + } else { + + // Construct axes from the vertex data + for(var i = 0; i < this.vertices.length; i++){ + // Get the world edge + var worldPoint0 = this.vertices[i]; + var worldPoint1 = this.vertices[(i+1) % this.vertices.length]; + + var normal = vec2.create(); + vec2.sub(normal, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, normal); + vec2.normalize(normal, normal); + + this.axes.push(normal); + } + + } + + /** + * The center of mass of the Convex + * @property centerOfMass + * @type {Array} + */ + this.centerOfMass = vec2.fromValues(0,0); + + /** + * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. + * @property triangles + * @type {Array} + */ + this.triangles = []; + + if(this.vertices.length){ + this.updateTriangles(); + this.updateCenterOfMass(); + } + + /** + * The bounding radius of the convex + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + options.type = Shape.CONVEX; + Shape.call(this, options); + + this.updateBoundingRadius(); + this.updateArea(); + if(this.area < 0){ + throw new Error("Convex vertices must be given in conter-clockwise winding."); + } +} +Convex.prototype = new Shape(); +Convex.prototype.constructor = Convex; + +var tmpVec1 = vec2.create(); +var tmpVec2 = vec2.create(); + +/** + * Project a Convex onto a world-oriented axis + * @method projectOntoAxis + * @static + * @param {Array} offset + * @param {Array} localAxis + * @param {Array} result + */ +Convex.prototype.projectOntoLocalAxis = function(localAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = tmpVec1; + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + vec2.set(result, min, max); +}; + +Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){ + var worldAxis = tmpVec2; + + this.projectOntoLocalAxis(localAxis, result); + + // Project the position of the body onto the axis - need to add this to the result + if(shapeAngle !== 0){ + vec2.rotate(worldAxis, localAxis, shapeAngle); + } else { + worldAxis = localAxis; + } + var offset = vec2.dot(shapeOffset, worldAxis); + + vec2.set(result, result[0] + offset, result[1] + offset); +}; + + +/** + * Update the .triangles property + * @method updateTriangles + */ +Convex.prototype.updateTriangles = function(){ + + this.triangles.length = 0; + + // Rewrite on polyk notation, array of numbers + var polykVerts = []; + for(var i=0; i r2){ + r2 = l2; + } + } + + this.boundingRadius = Math.sqrt(r2); +}; + +/** + * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. + * @static + * @method triangleArea + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +Convex.triangleArea = function(a,b,c){ + return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; +}; + +/** + * Update the .area + * @method updateArea + */ +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]]; + + // Get mass for the triangle (density=1 in this case) + var m = Convex.triangleArea(a,b,c); + this.area += m; + } +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Convex.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices, position, angle, 0); +}; + +var intersectConvex_rayStart = vec2.create(); +var intersectConvex_rayEnd = vec2.create(); +var intersectConvex_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Convex.prototype.raycast = function(result, ray, position, angle){ + var rayStart = intersectConvex_rayStart; + var rayEnd = intersectConvex_rayEnd; + var normal = intersectConvex_normal; + var vertices = this.vertices; + + // Transform to local shape space + vec2.toLocalFrame(rayStart, ray.from, position, angle); + vec2.toLocalFrame(rayEnd, ray.to, position, angle); + + var n = vertices.length; + + for (var i = 0; i < n && !result.shouldStop(ray); i++) { + var q1 = vertices[i]; + var q2 = vertices[(i+1) % n]; + var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2); + + if(delta >= 0){ + vec2.sub(normal, q2, q1); + vec2.rotate(normal, normal, -Math.PI / 2 + angle); + vec2.normalize(normal, normal); + ray.reportIntersection(result, delta, normal, i); + } + } +}; + +},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Heightfield; + +/** + * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". + * @class Heightfield + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {array} [options.heights] An array of Y values that will be used to construct the terrain. + * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given. + * @param {Number} [options.maxValue] Maximum value. + * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction. + * + * @example + * // Generate some height data (y-values). + * var heights = []; + * for(var i = 0; i < 1000; i++){ + * var y = 0.5 * Math.cos(0.2 * i); + * heights.push(y); + * } + * + * // Create the heightfield shape + * var heightfieldShape = new Heightfield({ + * heights: heights, + * elementWidth: 1 // Distance between the data points in X direction + * }); + * var heightfieldBody = new Body(); + * heightfieldBody.addShape(heightfieldShape); + * world.addBody(heightfieldBody); + * + * @todo Should use a scale property with X and Y direction instead of just elementWidth + */ +function Heightfield(options){ + if(Array.isArray(arguments[0])){ + options = { + heights: arguments[0] + }; + + if(typeof(arguments[1]) === 'object'){ + for(var key in arguments[1]){ + options[key] = arguments[1][key]; + } + } + + console.warn('The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })'); + } + options = options || {}; + + /** + * An array of numbers, or height values, that are spread out along the x axis. + * @property {array} heights + */ + this.heights = options.heights ? options.heights.slice(0) : []; + + /** + * Max value of the heights + * @property {number} maxValue + */ + this.maxValue = options.maxValue || null; + + /** + * Max value of the heights + * @property {number} minValue + */ + this.minValue = options.minValue || null; + + /** + * The width of each element + * @property {number} elementWidth + */ + this.elementWidth = options.elementWidth || 0.1; + + if(options.maxValue === undefined || options.minValue === undefined){ + this.updateMaxMinValues(); + } + + options.type = Shape.HEIGHTFIELD; + Shape.call(this, options); +} +Heightfield.prototype = new Shape(); +Heightfield.prototype.constructor = Heightfield; + +/** + * Update the .minValue and the .maxValue + * @method updateMaxMinValues + */ +Heightfield.prototype.updateMaxMinValues = function(){ + var data = this.heights; + var maxValue = data[0]; + var minValue = data[0]; + for(var i=0; i !== data.length; i++){ + var v = data[i]; + if(v > maxValue){ + maxValue = v; + } + if(v < minValue){ + minValue = v; + } + } + this.maxValue = maxValue; + this.minValue = minValue; +}; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Heightfield.prototype.computeMomentOfInertia = function(mass){ + return Number.MAX_VALUE; +}; + +Heightfield.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +Heightfield.prototype.updateArea = function(){ + var data = this.heights, + area = 0; + for(var i=0; i= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + var intX = p0[0] + (t * s1_x); + var intY = p0[1] + (t * s1_y); + out[0] = intX; + out[1] = intY; + return t; + } + return -1; // No collision +} + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Heightfield.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectHeightfield_hitPointWorld; + var worldNormal = intersectHeightfield_worldNormal; + var l0 = intersectHeightfield_l0; + var l1 = intersectHeightfield_l1; + var localFrom = intersectHeightfield_localFrom; + var localTo = intersectHeightfield_localTo; + + // get local ray start and end + vec2.toLocalFrame(localFrom, from, position, angle); + vec2.toLocalFrame(localTo, to, position, angle); + + // Get the segment range + var i0 = this.getClampedSegmentIndex(localFrom); + var i1 = this.getClampedSegmentIndex(localTo); + if(i0 > i1){ + var tmp = i0; + i0 = i1; + i1 = tmp; + } + + // The segments + for(var i=0; i= 0){ + vec2.sub(worldNormal, l1, l0); + vec2.rotate(worldNormal, worldNormal, angle + Math.PI / 2); + vec2.normalize(worldNormal, worldNormal); + ray.reportIntersection(result, t, worldNormal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Line; + +/** + * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * @class Line + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The total length of the line + * @extends Shape + * @constructor + */ +function Line(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + length: arguments[0] + }; + console.warn('The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })'); + } + options = options || {}; + + /** + * Length of this line + * @property {Number} length + * @default 1 + */ + this.length = options.length || 1; + + options.type = Shape.LINE; + Shape.call(this, options); +} +Line.prototype = new Shape(); +Line.prototype.constructor = Line; + +Line.prototype.computeMomentOfInertia = function(mass){ + return mass * Math.pow(this.length,2) / 12; +}; + +Line.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.length/2; +}; + +var points = [vec2.create(),vec2.create()]; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Line.prototype.computeAABB = function(out, position, angle){ + var l2 = this.length / 2; + vec2.set(points[0], -l2, 0); + vec2.set(points[1], l2, 0); + out.setFromPoints(points,position,angle,0); +}; + +var raycast_hitPoint = vec2.create(); +var raycast_normal = vec2.create(); +var raycast_l0 = vec2.create(); +var raycast_l1 = vec2.create(); +var raycast_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {number} angle + * @param {array} position + */ +Line.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + + var l0 = raycast_l0; + var l1 = raycast_l1; + + // get start and end of the line + var halfLen = this.length / 2; + vec2.set(l0, -halfLen, 0); + vec2.set(l1, halfLen, 0); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to); + if(fraction >= 0){ + var normal = raycast_normal; + vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from + ray.reportIntersection(result, fraction, normal, -1); + } +}; +},{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Particle; + +/** + * Particle shape class. + * @class Particle + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @extends Shape + */ +function Particle(options){ + options = options || {}; + options.type = Shape.PARTICLE; + Shape.call(this, options); +} +Particle.prototype = new Shape(); +Particle.prototype.constructor = Particle; + +Particle.prototype.computeMomentOfInertia = function(mass){ + return 0; // Can't rotate a particle +}; + +Particle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = 0; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Particle.prototype.computeAABB = function(out, position, angle){ + vec2.copy(out.lowerBound, position); + vec2.copy(out.upperBound, position); +}; + +},{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Plane; + +/** + * Plane shape class. The plane is facing in the Y direction. + * @class Plane + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + */ +function Plane(options){ + options = options || {}; + options.type = Shape.PLANE; + Shape.call(this, options); +} +Plane.prototype = new Shape(); +Plane.prototype.constructor = Plane; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + */ +Plane.prototype.computeMomentOfInertia = function(mass){ + return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Plane.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Plane.prototype.computeAABB = function(out, position, angle){ + var a = angle % (2 * Math.PI); + var set = vec2.set; + var max = 1e7; + var lowerBound = out.lowerBound; + var upperBound = out.upperBound; + + // Set max bounds + set(lowerBound, -max, -max); + set(upperBound, max, max); + + if(a === 0){ + // y goes from -inf to 0 + upperBound[1] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, max, 0); + + } else if(a === Math.PI / 2){ + + // x goes from 0 to inf + lowerBound[0] = 0; + // set(lowerBound, 0, -max); + // set(upperBound, max, max); + + } else if(a === Math.PI){ + + // y goes from 0 to inf + lowerBound[1] = 0; + // set(lowerBound, -max, 0); + // set(upperBound, max, max); + + } else if(a === 3*Math.PI/2){ + + // x goes from -inf to 0 + upperBound[0] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, 0, max); + + } +}; + +Plane.prototype.updateArea = function(){ + this.area = Number.MAX_VALUE; +}; + +var intersectPlane_planePointToFrom = vec2.create(); +var intersectPlane_dir_scaled_with_t = vec2.create(); +var intersectPlane_hitPoint = vec2.create(); +var intersectPlane_normal = vec2.create(); +var intersectPlane_len = vec2.create(); + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Plane.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + var planePointToFrom = intersectPlane_planePointToFrom; + var dir_scaled_with_t = intersectPlane_dir_scaled_with_t; + var hitPoint = intersectPlane_hitPoint; + var normal = intersectPlane_normal; + var len = intersectPlane_len; + + // Get plane normal + vec2.set(normal, 0, 1); + vec2.rotate(normal, normal, angle); + + vec2.sub(len, from, position); + var planeToFrom = vec2.dot(len, normal); + vec2.sub(len, to, position); + var planeToTo = vec2.dot(len, normal); + + if(planeToFrom * planeToTo > 0){ + // "from" and "to" are on the same side of the plane... bail out + return; + } + + if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){ + return; + } + + var n_dot_dir = vec2.dot(normal, direction); + + vec2.sub(planePointToFrom, from, position); + var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length; + + ray.reportIntersection(result, t, normal, -1); +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(_dereq_,module,exports){ +module.exports = Shape; + +var vec2 = _dereq_('../math/vec2'); + +/** + * Base class for shapes. + * @class Shape + * @constructor + * @param {object} [options] + * @param {array} [options.position] + * @param {number} [options.angle=0] + * @param {number} [options.collisionGroup=1] + * @param {number} [options.collisionMask=1] + * @param {boolean} [options.sensor=false] + * @param {boolean} [options.collisionResponse=true] + * @param {object} [options.type=0] + */ +function Shape(options){ + options = options || {}; + + /** + * The body this shape is attached to. A shape can only be attached to a single body. + * @property {Body} body + */ + this.body = null; + + /** + * Body-local position of the shape. + * @property {Array} position + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * Body-local angle of the shape. + * @property {number} angle + */ + this.angle = options.angle || 0; + + /** + * The type of the shape. One of: + * + * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} + * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} + * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} + * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} + * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} + * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}} + * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} + * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} + * + * @property {number} type + */ + this.type = options.type || 0; + + /** + * Shape object identifier. + * @type {Number} + * @property id + */ + this.id = Shape.idCounter++; + + /** + * Bounding circle radius of this shape + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + /** + * Collision group that this shape belongs to (bit mask). See this tutorial. + * @property collisionGroup + * @type {Number} + * @example + * // Setup bits for each available group + * var PLAYER = Math.pow(2,0), + * ENEMY = Math.pow(2,1), + * GROUND = Math.pow(2,2) + * + * // Put shapes into their groups + * player1Shape.collisionGroup = PLAYER; + * player2Shape.collisionGroup = PLAYER; + * enemyShape .collisionGroup = ENEMY; + * groundShape .collisionGroup = GROUND; + * + * // Assign groups that each shape collide with. + * // Note that the players can collide with ground and enemies, but not with other players. + * player1Shape.collisionMask = ENEMY | GROUND; + * player2Shape.collisionMask = ENEMY | GROUND; + * enemyShape .collisionMask = PLAYER | GROUND; + * groundShape .collisionMask = PLAYER | ENEMY; + * + * @example + * // How collision check is done + * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ + * // The shapes will collide + * } + */ + this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. + * @property {Boolean} collisionResponse + */ + this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; + + /** + * Collision mask of this shape. See .collisionGroup. + * @property collisionMask + * @type {Number} + */ + this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; + + /** + * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. + * @property material + * @type {Material} + */ + this.material = options.material || null; + + /** + * Area of this shape. + * @property area + * @type {Number} + */ + this.area = 0; + + /** + * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. + * @property {Boolean} sensor + */ + this.sensor = options.sensor !== undefined ? options.sensor : false; + + if(this.type){ + this.updateBoundingRadius(); + } + + this.updateArea(); +} + +Shape.idCounter = 0; + +/** + * @static + * @property {Number} CIRCLE + */ +Shape.CIRCLE = 1; + +/** + * @static + * @property {Number} PARTICLE + */ +Shape.PARTICLE = 2; + +/** + * @static + * @property {Number} PLANE + */ +Shape.PLANE = 4; + +/** + * @static + * @property {Number} CONVEX + */ +Shape.CONVEX = 8; + +/** + * @static + * @property {Number} LINE + */ +Shape.LINE = 16; + +/** + * @static + * @property {Number} BOX + */ +Shape.BOX = 32; + +/** + * @static + * @property {Number} CAPSULE + */ +Shape.CAPSULE = 64; + +/** + * @static + * @property {Number} HEIGHTFIELD + */ +Shape.HEIGHTFIELD = 128; + +/** + * Should return the moment of inertia around the Z axis of the body given the total mass. See Wikipedia's list of moments of inertia. + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. + */ +Shape.prototype.computeMomentOfInertia = function(mass){}; + +/** + * Returns the bounding circle radius of this shape. + * @method updateBoundingRadius + * @return {Number} + */ +Shape.prototype.updateBoundingRadius = function(){}; + +/** + * Update the .area property of the shape. + * @method updateArea + */ +Shape.prototype.updateArea = function(){ + // To be implemented in all subclasses +}; + +/** + * Compute the world axis-aligned bounding box (AABB) of this shape. + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position World position of the shape. + * @param {Number} angle World angle of the shape. + */ +Shape.prototype.computeAABB = function(out, position, angle){ + // To be implemented in each subclass +}; + +/** + * Perform raycasting on this shape. + * @method raycast + * @param {RayResult} result Where to store the resulting data. + * @param {Ray} ray The Ray that you want to use for raycasting. + * @param {array} position World position of the shape (the .position property will be ignored). + * @param {number} angle World angle of the shape (the .angle property will be ignored). + */ +Shape.prototype.raycast = function(result, ray, position, angle){ + // To be implemented in each subclass +}; +},{"../math/vec2":30}],46:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Solver = _dereq_('./Solver') +, Utils = _dereq_('../utils/Utils') +, FrictionEquation = _dereq_('../equations/FrictionEquation'); + +module.exports = GSSolver; + +/** + * Iterative Gauss-Seidel constraint equation solver. + * + * @class GSSolver + * @constructor + * @extends Solver + * @param {Object} [options] + * @param {Number} [options.iterations=10] + * @param {Number} [options.tolerance=0] + */ +function GSSolver(options){ + Solver.call(this,options,Solver.GS); + options = options || {}; + + /** + * The max number of iterations to do when solving. More gives better results, but is more expensive. + * @property iterations + * @type {Number} + */ + this.iterations = options.iterations || 10; + + /** + * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. + * @property tolerance + * @type {Number} + * @default 1e-7 + */ + this.tolerance = options.tolerance || 1e-7; + + this.arrayStep = 30; + this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); + + /** + * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. + * @property useZeroRHS + * @type {Boolean} + * @todo Remove, not used + */ + this.useZeroRHS = false; + + /** + * Number of solver iterations that are used to approximate normal forces used for friction (F_friction = mu * F_normal). These friction forces will override any other friction forces that are set. If you set frictionIterations = 0, then this feature will be disabled. + * + * Use only frictionIterations > 0 if the approximated normal force (F_normal = mass * gravity) is not good enough. Examples of where it can happen is in space games where gravity is zero, or in tall stacks where the normal force is large at bottom but small at top. + * + * @property frictionIterations + * @type {Number} + * @default 0 + */ + this.frictionIterations = options.frictionIterations !== undefined ? 0 : options.frictionIterations; + + /** + * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. + * @property {Number} usedIterations + */ + this.usedIterations = 0; +} +GSSolver.prototype = new Solver(); +GSSolver.prototype.constructor = GSSolver; + +function setArrayZero(array){ + var l = array.length; + while(l--){ + array[l] = +0.0; + } +} + +/** + * Solve the system of equations + * @method solve + * @param {Number} h Time step + * @param {World} world World to solve + */ +GSSolver.prototype.solve = function(h, world){ + + this.sortEquations(); + + var iter = 0, + maxIter = this.iterations, + maxFrictionIter = this.frictionIterations, + equations = this.equations, + Neq = equations.length, + tolSquared = Math.pow(this.tolerance*Neq, 2), + bodies = world.bodies, + Nbodies = world.bodies.length, + add = vec2.add, + set = vec2.set, + useZeroRHS = this.useZeroRHS, + lambda = this.lambda; + + this.usedIterations = 0; + + if(Neq){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Update solve mass + b.updateSolveMassProperties(); + } + } + + // Things that does not change during iteration can be computed once + if(lambda.length < Neq){ + lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + } + setArrayZero(lambda); + var invCs = this.invCs, + Bs = this.Bs, + lambda = this.lambda; + + for(var i=0; i!==equations.length; i++){ + var c = equations[i]; + if(c.timeStep !== h || c.needsUpdate){ + c.timeStep = h; + c.update(); + } + Bs[i] = c.computeB(c.a,c.b,h); + invCs[i] = c.computeInvC(c.epsilon); + } + + var q, B, c, deltalambdaTot,i,j; + + if(Neq !== 0){ + + for(i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Reset vlambda + b.resetConstraintVelocity(); + } + + if(maxFrictionIter){ + // Iterate over contact equations to get normal forces + for(iter=0; iter!==maxFrictionIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + + // Set computed friction force + for(j=0; j!==Neq; j++){ + var eq = equations[j]; + if(eq instanceof FrictionEquation){ + var f = 0.0; + for(var k=0; k!==eq.contactEquations.length; k++){ + f += eq.contactEquations[k].multiplier; + } + f *= eq.frictionCoefficient / eq.contactEquations.length; + eq.maxForce = f; + eq.minForce = -f; + } + } + } + + // Iterate over all equations + for(iter=0; iter!==maxIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + // Add result to velocity + for(i=0; i!==Nbodies; i++){ + bodies[i].addConstraintVelocity(); + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + } +}; + +// Sets the .multiplier property of each equation +GSSolver.updateMultipliers = function(equations, lambda, invDt){ + // Set the .multiplier property of each equation + var l = equations.length; + while(l--){ + equations[l].multiplier = lambda[l] * invDt; + } +}; + +GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ + // Compute iteration + var B = Bs[j], + invC = invCs[j], + lambdaj = lambda[j], + GWlambda = eq.computeGWlambda(); + + var maxForce = eq.maxForce, + minForce = eq.minForce; + + if(useZeroRHS){ + B = 0; + } + + var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); + + // Clamp if we are not within the min/max interval + var lambdaj_plus_deltalambda = lambdaj + deltalambda; + if(lambdaj_plus_deltalambda < minForce*dt){ + deltalambda = minForce*dt - lambdaj; + } else if(lambdaj_plus_deltalambda > maxForce*dt){ + deltalambda = maxForce*dt - lambdaj; + } + lambda[j] += deltalambda; + eq.addToWlambda(deltalambda); + + return deltalambda; +}; + +},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Solver; + +/** + * Base class for constraint solvers. + * @class Solver + * @constructor + * @extends EventEmitter + */ +function Solver(options,type){ + options = options || {}; + + EventEmitter.call(this); + + this.type = type; + + /** + * Current equations in the solver. + * + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Function that is used to sort all equations before each solve. + * @property equationSortFunction + * @type {function|boolean} + */ + this.equationSortFunction = options.equationSortFunction || false; +} +Solver.prototype = new EventEmitter(); +Solver.prototype.constructor = Solver; + +/** + * Method to be implemented in each subclass + * @method solve + * @param {Number} dt + * @param {World} world + */ +Solver.prototype.solve = function(dt,world){ + throw new Error("Solver.solve should be implemented by subclasses!"); +}; + +var mockWorld = {bodies:[]}; + +/** + * Solves all constraints in an island. + * @method solveIsland + * @param {Number} dt + * @param {Island} island + */ +Solver.prototype.solveIsland = function(dt,island){ + + this.removeAllEquations(); + + if(island.equations.length){ + // Add equations to solver + this.addEquations(island.equations); + mockWorld.bodies.length = 0; + island.getBodies(mockWorld.bodies); + + // Solve + if(mockWorld.bodies.length){ + this.solve(dt,mockWorld); + } + } +}; + +/** + * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. + * @method sortEquations + */ +Solver.prototype.sortEquations = function(){ + if(this.equationSortFunction){ + this.equations.sort(this.equationSortFunction); + } +}; + +/** + * Add an equation to be solved. + * + * @method addEquation + * @param {Equation} eq + */ +Solver.prototype.addEquation = function(eq){ + if(eq.enabled){ + this.equations.push(eq); + } +}; + +/** + * Add equations. Same as .addEquation, but this time the argument is an array of Equations + * + * @method addEquations + * @param {Array} eqs + */ +Solver.prototype.addEquations = function(eqs){ + //Utils.appendArray(this.equations,eqs); + for(var i=0, N=eqs.length; i!==N; i++){ + var eq = eqs[i]; + if(eq.enabled){ + this.equations.push(eq); + } + } +}; + +/** + * Remove an equation. + * + * @method removeEquation + * @param {Equation} eq + */ +Solver.prototype.removeEquation = function(eq){ + var i = this.equations.indexOf(eq); + if(i !== -1){ + this.equations.splice(i,1); + } +}; + +/** + * Remove all currently added equations. + * + * @method removeAllEquations + */ +Solver.prototype.removeAllEquations = function(){ + this.equations.length=0; +}; + +Solver.GS = 1; +Solver.ISLAND = 2; + +},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){ +var ContactEquation = _dereq_('../equations/ContactEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = ContactEquationPool; + +/** + * @class + */ +function ContactEquationPool() { + Pool.apply(this, arguments); +} +ContactEquationPool.prototype = new Pool(); +ContactEquationPool.prototype.constructor = ContactEquationPool; + +/** + * @method create + * @return {ContactEquation} + */ +ContactEquationPool.prototype.create = function () { + return new ContactEquation(); +}; + +/** + * @method destroy + * @param {ContactEquation} equation + * @return {ContactEquationPool} + */ +ContactEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){ +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = FrictionEquationPool; + +/** + * @class + */ +function FrictionEquationPool() { + Pool.apply(this, arguments); +} +FrictionEquationPool.prototype = new Pool(); +FrictionEquationPool.prototype.constructor = FrictionEquationPool; + +/** + * @method create + * @return {FrictionEquation} + */ +FrictionEquationPool.prototype.create = function () { + return new FrictionEquation(); +}; + +/** + * @method destroy + * @param {FrictionEquation} equation + * @return {FrictionEquationPool} + */ +FrictionEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){ +var IslandNode = _dereq_('../world/IslandNode'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandNodePool; + +/** + * @class + */ +function IslandNodePool() { + Pool.apply(this, arguments); +} +IslandNodePool.prototype = new Pool(); +IslandNodePool.prototype.constructor = IslandNodePool; + +/** + * @method create + * @return {IslandNode} + */ +IslandNodePool.prototype.create = function () { + return new IslandNode(); +}; + +/** + * @method destroy + * @param {IslandNode} node + * @return {IslandNodePool} + */ +IslandNodePool.prototype.destroy = function (node) { + node.reset(); + return this; +}; + +},{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){ +var Island = _dereq_('../world/Island'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandPool; + +/** + * @class + */ +function IslandPool() { + Pool.apply(this, arguments); +} +IslandPool.prototype = new Pool(); +IslandPool.prototype.constructor = IslandPool; + +/** + * @method create + * @return {Island} + */ +IslandPool.prototype.create = function () { + return new Island(); +}; + +/** + * @method destroy + * @param {Island} island + * @return {IslandPool} + */ +IslandPool.prototype.destroy = function (island) { + island.reset(); + return this; +}; + +},{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){ +var TupleDictionary = _dereq_('./TupleDictionary'); +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool'); +var Utils = _dereq_('./Utils'); + +module.exports = OverlapKeeper; + +/** + * Keeps track of overlaps in the current state and the last step state. + * @class OverlapKeeper + * @constructor + */ +function OverlapKeeper() { + this.overlappingShapesLastState = new TupleDictionary(); + this.overlappingShapesCurrentState = new TupleDictionary(); + this.recordPool = new OverlapKeeperRecordPool({ size: 16 }); + this.tmpDict = new TupleDictionary(); + this.tmpArray1 = []; +} + +/** + * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current. + * @method tick + */ +OverlapKeeper.prototype.tick = function() { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Save old objects into pool + var l = last.keys.length; + while(l--){ + var key = last.keys[l]; + var lastObject = last.getByKey(key); + var currentObject = current.getByKey(key); + if(lastObject){ + // The record is only used in the "last" dict, and will be removed. We might as well pool it. + this.recordPool.release(lastObject); + } + } + + // Clear last object + last.reset(); + + // Transfer from new object to old + last.copy(current); + + // Clear current object + current.reset(); +}; + +/** + * @method setOverlapping + * @param {Body} bodyA + * @param {Body} shapeA + * @param {Body} bodyB + * @param {Body} shapeB + */ +OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Store current contact state + if(!current.get(shapeA.id, shapeB.id)){ + var data = this.recordPool.get(); + data.set(bodyA, shapeA, bodyB, shapeB); + current.set(shapeA.id, shapeB.id, data); + } +}; + +OverlapKeeper.prototype.getNewOverlaps = function(result){ + return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result); +}; + +OverlapKeeper.prototype.getEndOverlaps = function(result){ + return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result); +}; + +/** + * Checks if two bodies are currently overlapping. + * @method bodiesAreOverlapping + * @param {Body} bodyA + * @param {Body} bodyB + * @return {boolean} + */ +OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){ + var current = this.overlappingShapesCurrentState; + var l = current.keys.length; + while(l--){ + var key = current.keys[l]; + var data = current.data[key]; + if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){ + return true; + } + } + return false; +}; + +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){ + // Not overlapping in last state, but in current. + result.push(data); + } + } + + return result; +}; + +OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ + var idA = shapeA.id|0, + idB = shapeB.id|0; + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + // Not in last but in new + return !!!last.get(idA, idB) && !!current.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]; + + // Since we use body id's for the accumulator, these will be a subset of the original one + accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); + } + + l = accumulator.keys.length; + while(l--){ + var data = accumulator.getByKey(accumulator.keys[l]); + if(data){ + result.push(data.bodyA, data.bodyB); + } + } + + accumulator.reset(); + + return result; +}; + +},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){ +module.exports = OverlapKeeperRecord; + +/** + * Overlap data container for the OverlapKeeper + * @class OverlapKeeperRecord + * @constructor + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ + /** + * @property {Shape} shapeA + */ + this.shapeA = shapeA; + /** + * @property {Shape} shapeB + */ + this.shapeB = shapeB; + /** + * @property {Body} bodyA + */ + this.bodyA = bodyA; + /** + * @property {Body} bodyB + */ + this.bodyB = bodyB; +} + +/** + * Set the data for the record + * @method set + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ + OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); +}; + +},{}],54:[function(_dereq_,module,exports){ +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var Pool = _dereq_('./Pool'); + +module.exports = OverlapKeeperRecordPool; + +/** + * @class + */ +function OverlapKeeperRecordPool() { + Pool.apply(this, arguments); +} +OverlapKeeperRecordPool.prototype = new Pool(); +OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool; + +/** + * @method create + * @return {OverlapKeeperRecord} + */ +OverlapKeeperRecordPool.prototype.create = function () { + return new OverlapKeeperRecord(); +}; + +/** + * @method destroy + * @param {OverlapKeeperRecord} record + * @return {OverlapKeeperRecordPool} + */ +OverlapKeeperRecordPool.prototype.destroy = function (record) { + record.bodyA = record.bodyB = record.shapeA = record.shapeB = null; + return this; +}; + +},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){ +module.exports = Pool; + +/** + * @class Object pooling utility. + */ +function Pool(options) { + options = options || {}; + + /** + * @property {Array} objects + * @type {Array} + */ + this.objects = []; + + if(options.size !== undefined){ + this.resize(options.size); + } +} + +/** + * @method resize + * @param {number} size + * @return {Pool} Self, for chaining + */ +Pool.prototype.resize = function (size) { + var objects = this.objects; + + while (objects.length > size) { + objects.pop(); + } + + while (objects.length < size) { + objects.push(this.create()); + } + + return this; +}; + +/** + * Get an object from the pool or create a new instance. + * @method get + * @return {Object} + */ +Pool.prototype.get = function () { + var objects = this.objects; + return objects.length ? objects.pop() : this.create(); +}; + +/** + * Clean up and put the object back into the pool for later use. + * @method release + * @param {Object} object + * @return {Pool} Self for chaining + */ +Pool.prototype.release = function (object) { + this.destroy(object); + this.objects.push(object); + return this; +}; + +},{}],56:[function(_dereq_,module,exports){ +var Utils = _dereq_('./Utils'); + +module.exports = TupleDictionary; + +/** + * @class TupleDictionary + * @constructor + */ +function TupleDictionary() { + + /** + * The data storage + * @property data + * @type {Object} + */ + this.data = {}; + + /** + * Keys that are currently used. + * @property {Array} keys + */ + this.keys = []; +} + +/** + * Generate a key given two integers + * @method getKey + * @param {number} i + * @param {number} j + * @return {string} + */ +TupleDictionary.prototype.getKey = function(id1, id2) { + id1 = id1|0; + id2 = id2|0; + + if ( (id1|0) === (id2|0) ){ + return -1; + } + + // valid for values < 2^16 + return ((id1|0) > (id2|0) ? + (id1 << 16) | (id2 & 0xFFFF) : + (id2 << 16) | (id1 & 0xFFFF))|0 + ; +}; + +/** + * @method getByKey + * @param {Number} key + * @return {Object} + */ +TupleDictionary.prototype.getByKey = function(key) { + key = key|0; + return this.data[key]; +}; + +/** + * @method get + * @param {Number} i + * @param {Number} j + * @return {Number} + */ +TupleDictionary.prototype.get = function(i, j) { + return this.data[this.getKey(i, j)]; +}; + +/** + * Set a value. + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +TupleDictionary.prototype.set = function(i, j, value) { + if(!value){ + throw new Error("No data!"); + } + + var key = this.getKey(i, j); + + // Check if key already exists + if(!this.data[key]){ + this.keys.push(key); + } + + this.data[key] = value; + + return key; +}; + +/** + * Remove all data. + * @method reset + */ +TupleDictionary.prototype.reset = function() { + var data = this.data, + keys = this.keys; + + var l = keys.length; + while(l--) { + delete data[keys[l]]; + } + + keys.length = 0; +}; + +/** + * Copy another TupleDictionary. Note that all data in this dictionary will be removed. + * @method copy + * @param {TupleDictionary} dict The TupleDictionary to copy into this one. + */ +TupleDictionary.prototype.copy = function(dict) { + this.reset(); + Utils.appendArray(this.keys, dict.keys); + var l = dict.keys.length; + while(l--){ + var key = dict.keys[l]; + this.data[key] = dict.data[key]; + } +}; + +},{"./Utils":57}],57:[function(_dereq_,module,exports){ +/* global P2_ARRAY_TYPE */ + +module.exports = Utils; + +/** + * Misc utility functions + * @class Utils + * @constructor + */ +function Utils(){} + +/** + * Append the values in array b to the array a. See this for an explanation. + * @method appendArray + * @static + * @param {Array} a + * @param {Array} b + */ +Utils.appendArray = function(a,b){ + if (b.length < 150000) { + a.push.apply(a, b); + } else { + for (var i = 0, len = b.length; i !== len; ++i) { + a.push(b[i]); + } + } +}; + +/** + * Garbage free Array.splice(). Does not allocate a new array. + * @method splice + * @static + * @param {Array} array + * @param {Number} index + * @param {Number} howmany + */ +Utils.splice = function(array,index,howmany){ + howmany = howmany || 1; + for (var i=index, len=array.length-howmany; i < len; i++){ + array[i] = array[i + howmany]; + } + array.length = len; +}; + +/** + * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. + * @static + * @property {function} ARRAY_TYPE + * @example + * + * + */ +if(typeof P2_ARRAY_TYPE !== 'undefined') { + Utils.ARRAY_TYPE = P2_ARRAY_TYPE; +} else if (typeof Float32Array !== 'undefined'){ + Utils.ARRAY_TYPE = Float32Array; +} else { + Utils.ARRAY_TYPE = Array; +} + +/** + * Extend an object with the properties of another + * @static + * @method extend + * @param {object} a + * @param {object} b + */ +Utils.extend = function(a,b){ + for(var key in b){ + a[key] = b[key]; + } +}; + +/** + * Extend an options object with default values. + * @static + * @method defaults + * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. + * @param {object} defaults An object containing default values. + * @return {object} The modified options object. + */ +Utils.defaults = function(options, defaults){ + options = options || {}; + for(var key in defaults){ + if(!(key in options)){ + options[key] = defaults[key]; + } + } + return options; +}; + +},{}],58:[function(_dereq_,module,exports){ +var Body = _dereq_('../objects/Body'); + +module.exports = Island; + +/** + * An island of bodies connected with equations. + * @class Island + * @constructor + */ +function Island(){ + + /** + * Current equations in this island. + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Current bodies in this island. + * @property bodies + * @type {Array} + */ + this.bodies = []; +} + +/** + * Clean this island from bodies and equations. + * @method reset + */ +Island.prototype.reset = function(){ + this.equations.length = this.bodies.length = 0; +}; + +var bodyIds = []; + +/** + * Get all unique bodies in this island. + * @method getBodies + * @return {Array} An array of Body + */ +Island.prototype.getBodies = function(result){ + var bodies = result || [], + eqs = this.equations; + bodyIds.length = 0; + for(var i=0; i!==eqs.length; i++){ + var eq = eqs[i]; + if(bodyIds.indexOf(eq.bodyA.id)===-1){ + bodies.push(eq.bodyA); + bodyIds.push(eq.bodyA.id); + } + if(bodyIds.indexOf(eq.bodyB.id)===-1){ + bodies.push(eq.bodyB); + bodyIds.push(eq.bodyB.id); + } + } + return bodies; +}; + +/** + * Check if the entire island wants to sleep. + * @method wantsToSleep + * @return {Boolean} + */ +Island.prototype.wantsToSleep = function(){ + for(var i=0; i= dt && substeps < maxSubSteps) { + // Do fixed steps to catch up + this.internalStep(dt); + this.time += dt; + this.accumulator -= dt; + substeps++; + } + + var t = (this.accumulator % dt) / dt; + for(var j=0; j!==this.bodies.length; j++){ + var b = this.bodies[j]; + vec2.lerp(b.interpolatedPosition, b.previousPosition, b.position, t); + b.interpolatedAngle = b.previousAngle + t * (b.angle - b.previousAngle); + } + } +}; + +var endOverlaps = []; + +/** + * Make a fixed step. + * @method internalStep + * @param {number} dt + * @private + */ +World.prototype.internalStep = function(dt){ + this.stepping = true; + + var that = this, + Nsprings = this.springs.length, + springs = this.springs, + bodies = this.bodies, + g = this.gravity, + solver = this.solver, + Nbodies = this.bodies.length, + broadphase = this.broadphase, + np = this.narrowphase, + constraints = this.constraints, + t0, t1, + fhMinv = step_fhMinv, + velodt = step_velodt, + mg = step_mg, + scale = vec2.scale, + add = vec2.add, + rotate = vec2.rotate, + islandManager = this.islandManager; + + this.overlapKeeper.tick(); + + this.lastTimeStep = dt; + + // Update approximate friction gravity. + if(this.useWorldGravityAsFrictionGravity){ + var gravityLen = vec2.length(this.gravity); + if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){ + // Nonzero gravity. Use it. + this.frictionGravity = gravityLen; + } + } + + // Add gravity to bodies + if(this.applyGravity){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i], + fi = b.force; + if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ + continue; + } + vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g + add(fi,fi,mg); + } + } + + // Add spring forces + if(this.applySpringForces){ + for(var i=0; i!==Nsprings; i++){ + var s = springs[i]; + s.applyForce(); + } + } + + if(this.applyDamping){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + if(b.type === Body.DYNAMIC){ + b.applyDamping(dt); + } + } + } + + // Broadphase + var result = broadphase.getCollisionPairs(this); + + // Remove ignored collision pairs + var ignoredPairs = this.disabledBodyCollisionPairs; + for(var i=ignoredPairs.length-2; 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); + } + } + } + + // Remove constrained pairs with collideConnected == false + 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); + } + } + } + } + + // postBroadphase event + this.postBroadphaseEvent.pairs = result; + this.emit(this.postBroadphaseEvent); + this.postBroadphaseEvent.pairs = null; + + // Narrowphase + np.reset(this); + for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ + var bi = result[i], + bj = result[i+1]; + + // Loop over all shapes of body i + for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ + var si = bi.shapes[k], + xi = si.position, + ai = si.angle; + + // All shapes of body j + for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ + var sj = bj.shapes[l], + xj = sj.position, + aj = sj.angle; + + 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); + } + } + } + + // Wake up bodies + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + if(body._wakeUpAfterNarrowphase){ + body.wakeUp(); + body._wakeUpAfterNarrowphase = false; + } + } + + // Emit end overlap events + 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.bodyB; + this.emit(e); + } + endOverlaps.length = 0; + } + + var preSolveEvent = this.preSolveEvent; + preSolveEvent.contactEquations = np.contactEquations; + preSolveEvent.frictionEquations = np.frictionEquations; + this.emit(preSolveEvent); + preSolveEvent.contactEquations = preSolveEvent.frictionEquations = null; + + // update constraint equations + var Nconstraints = constraints.length; + for(i=0; i!==Nconstraints; i++){ + constraints[i].update(); + } + + if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){ + if(this.islandSplit){ + // Split into islands + 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 { + + // Add contact equations to solver + solver.addEquations(np.contactEquations); + solver.addEquations(np.frictionEquations); + + // Add user-defined constraint equations + for(i=0; i!==Nconstraints; i++){ + solver.addEquations(constraints[i].equations); + } + + if(this.solveConstraints){ + solver.solve(dt,this); + } + + solver.removeAllEquations(); + } + } + + // Step forward + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + + // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){ + body.integrate(dt); + // } + } + + // Reset force + for(var i=0; i!==Nbodies; i++){ + bodies[i].setZeroForce(); + } + + // Emit impact event + 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); + } + } + } + + // Sleeping update + if(this.sleepMode === World.BODY_SLEEPING){ + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, false, dt); + } + } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){ + + // Tell all bodies to sleep tick but dont sleep yet + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, true, dt); + } + + // Sleep islands + for(var i=0; i 0; + np.frictionCoefficient = cm.friction; + var reducedMass; + if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){ + reducedMass = bj.mass; + } else if(bj.type === Body.STATIC || bj.type === 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; + np.contactSkinSize = cm.contactSkinSize; + np.enabledEquations = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse; + + 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 < sj.type) { + numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); + } else { + numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); + } + var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; + + if(numContacts){ + + if( bi.allowSleep && + bi.type === Body.DYNAMIC && + bi.sleepState === Body.SLEEPING && + bj.sleepState === Body.AWAKE && + bj.type !== Body.STATIC + ){ + var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); + var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); + if(speedSquaredB >= speedLimitSquaredB*2){ + bi._wakeUpAfterNarrowphase = true; + } + } + + if( bj.allowSleep && + bj.type === Body.DYNAMIC && + bj.sleepState === Body.SLEEPING && + bi.sleepState === Body.AWAKE && + bi.type !== 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)){ + + // Report new shape overlap + var e = this.beginContactEvent; + e.shapeA = si; + e.shapeB = sj; + e.bodyA = bi; + e.bodyB = bj; + + // Reset contact equations + e.contactEquations.length = 0; + + if(typeof(numContacts)==="number"){ + for(var i=np.contactEquations.length-numContacts; i 1){ // Why divide by 1? + for(var i=np.frictionEquations.length-numFrictionEquations; i=0; i--){ + this.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.bodies; + for(var i=bodies.length-1; i>=0; i--){ + this.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.springs; + for(var i=springs.length-1; i>=0; i--){ + this.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.contactMaterials; + for(var i=cms.length-1; i>=0; i--){ + this.removeContactMaterial(cms[i]); + } + + World.apply(this); +}; + +var hitTest_tmp1 = vec2.create(), + hitTest_zero = vec2.fromValues(0,0), + hitTest_tmp2 = vec2.fromValues(0,0); + +/** + * Test if a world point overlaps bodies + * @method hitTest + * @param {Array} worldPoint Point to use for intersection tests + * @param {Array} bodies A list of objects to check for intersection + * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @return {Array} Array of bodies that overlap the point + * @todo Should use an api similar to the raycast function + * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient + * @todo Should use the broadphase + */ +World.prototype.hitTest = function(worldPoint,bodies,precision){ + precision = precision || 0; + + // Create a dummy particle body with a particle shape to test against the bodies + 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 = []; + + // Check bodies + 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]; + + // Get shape world position + angle + vec2.rotate(x, s.position, b.angle); + vec2.add(x, x, b.position); + var a = s.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)) < precision*precision) + ){ + result.push(b); + } + } + } + + return result; +}; + +/** + * Set the stiffness for all equations and contact materials. + * @method setGlobalStiffness + * @param {Number} stiffness + */ +World.prototype.setGlobalStiffness = function(stiffness){ + + // Set for all constraints + var constraints = this.constraints; + for(var i=0; i !== constraints.length; i++){ + var c = constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.stiffness = stiffness; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + var contactMaterials = this.contactMaterials; + for(var i=0; i !== contactMaterials.length; i++){ + var c = contactMaterials[i]; + c.stiffness = c.frictionStiffness = stiffness; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.stiffness = c.frictionStiffness = stiffness; +}; + +/** + * Set the relaxation for all equations and contact materials. + * @method setGlobalRelaxation + * @param {Number} relaxation + */ +World.prototype.setGlobalRelaxation = function(relaxation){ + + // Set for all constraints + for(var i=0; i !== this.constraints.length; i++){ + var c = this.constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.relaxation = relaxation; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + for(var i=0; i !== this.contactMaterials.length; i++){ + var c = this.contactMaterials[i]; + c.relaxation = c.frictionRelaxation = relaxation; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.relaxation = c.frictionRelaxation = relaxation; +}; + +var tmpAABB = new AABB(); +var tmpArray = []; + +/** + * Ray cast against all bodies in the world. + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @return {boolean} True if any body was hit. + * + * @example + * var ray = new Ray({ + * mode: Ray.CLOSEST, // or ANY + * from: [0, 0], + * to: [10, 0], + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * @example + * var ray = new Ray({ + * mode: Ray.ALL, + * from: [0, 0], + * to: [10, 0], + * callback: function(result){ + * + * // Print some info about the hit + * console.log('Hit body and shape: ', result.body, result.shape); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * // If you are happy with the hits you got this far, you can stop the traversal here: + * result.stop(); + * } + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + */ +World.prototype.raycast = function(result, ray){ + + // Get all bodies within the ray AABB + ray.getAABB(tmpAABB); + this.broadphase.aabbQuery(this, tmpAABB, tmpArray); + ray.intersectBodies(result, tmpArray); + tmpArray.length = 0; + + return result.hasHit(); +}; + +},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36]) +(36) +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +(function(){ + + var root = this; + +/** + * Namespace-class for [pixi.js](http://www.pixijs.com/). + * + * Contains assorted static properties and enumerations. + * + * @namespace PIXI + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ +var PIXI = PIXI || {}; + +/** +* @author Mat Groves http://matgroves.com @Doormat23 +* @author Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The base class for all objects that are rendered. Contains properties for position, scaling, +* rotation, masks and cache handling. +* +* This is an abstract class and should not be used on its own, rather it should be extended. +* +* It is used internally by the likes of PIXI.Sprite. +* +* @class PIXI.DisplayObject +* @constructor +*/ +PIXI.DisplayObject = function () { + + /** + * The coordinates, in pixels, of this DisplayObject, relative to its parent container. + * + * The value of this property does not reflect any positioning happening further up the display list. + * To obtain that value please see the `worldPosition` property. + * + * @property {PIXI.Point} position + * @default + */ + this.position = new PIXI.Point(0, 0); + + /** + * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject + * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on. + * + * The value of this property does not reflect any scaling happening further up the display list. + * To obtain that value please see the `worldScale` property. + * + * @property {PIXI.Point} scale + * @default + */ + this.scale = new PIXI.Point(1, 1); + + /** + * The pivot point of this DisplayObject that it rotates around. The values are expressed + * in pixel values. + * @property {PIXI.Point} pivot + * @default + */ + this.pivot = new PIXI.Point(0, 0); + + /** + * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on + * a right-handed orientation. + * + * The value of this property does not reflect any rotation happening further up the display list. + * To obtain that value please see the `worldRotation` property. + * + * @property {number} rotation + * @default + */ + this.rotation = 0; + + /** + * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * Please note that an object with an alpha value of 0 is skipped during the render pass. + * + * The value of this property does not reflect any alpha values set further up the display list. + * To obtain that value please see the `worldAlpha` property. + * + * @property {number} alpha + * @default + */ + this.alpha = 1; + + /** + * The visibility of this DisplayObject. A value of `false` makes the object invisible. + * A value of `true` makes it visible. Please note that an object with a visible value of + * `false` is skipped during the render pass. Equally a DisplayObject with visible false will + * not render any of its children. + * + * The value of this property does not reflect any visible values set further up the display list. + * To obtain that value please see the `worldVisible` property. + * + * @property {boolean} visible + * @default + */ + this.visible = true; + + /** + * This is the defined area that will pick up mouse / touch events. It is null by default. + * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children) + * + * @property hitArea + * @type Rectangle|Circle|Ellipse|Polygon + */ + this.hitArea = null; + + /** + * Should this DisplayObject be rendered by the renderer? An object with a renderable value of + * `false` is skipped during the render pass. + * + * @property {boolean} renderable + * @default + */ + this.renderable = false; + + /** + * The parent DisplayObjectContainer that this DisplayObject is a child of. + * All DisplayObjects must belong to a parent in order to be rendered. + * The root parent is the Stage object. This property is set automatically when the + * DisplayObject is added to, or removed from, a DisplayObjectContainer. + * + * @property {PIXI.DisplayObjectContainer} parent + * @default + * @readOnly + */ + this.parent = null; + + /** + * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects + * in the display list. + * + * To obtain, and set, the local alpha value, see the `alpha` property. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldAlpha + * @readOnly + */ + this.worldAlpha = 1; + + /** + * The current transform of this DisplayObject. + * + * This property contains the calculated total, based on the transforms of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {Phaser.Matrix} worldTransform + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * The coordinates, in pixels, of this DisplayObject within the world. + * + * This property contains the calculated total, based on the positions of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldPosition + * @readOnly + */ + this.worldPosition = new PIXI.Point(0, 0); + + /** + * The global scale of this DisplayObject. + * + * This property contains the calculated total, based on the scales of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldScale + * @readOnly + */ + this.worldScale = new PIXI.Point(1, 1); + + /** + * The rotation, in radians, of this DisplayObject. + * + * This property contains the calculated total, based on the rotations of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldRotation + * @readOnly + */ + this.worldRotation = 0; + + /** + * The rectangular area used by filters when rendering a shader for this DisplayObject. + * + * @property {PIXI.Rectangle} filterArea + * @type Rectangle + * @default + */ + this.filterArea = null; + + /** + * @property {number} _sr - Cached rotation value. + * @private + */ + this._sr = 0; + + /** + * @property {number} _cr - Cached rotation value. + * @private + */ + this._cr = 1; + + /** + * @property {PIXI.Rectangle} _bounds - The cached bounds of this object. + * @private + */ + this._bounds = new PIXI.Rectangle(0, 0, 0, 0); + + /** + * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object. + * @private + */ + this._currentBounds = null; + + /** + * @property {PIXI.Rectangle} _mask - The cached mask of this object. + * @private + */ + this._mask = null; + + /** + * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag. + * @private + */ + this._cacheAsBitmap = false; + + /** + * @property {boolean} _cacheIsDirty - Internal dirty cache flag. + * @private + */ + this._cacheIsDirty = false; + +}; + +PIXI.DisplayObject.prototype = { + + constructor: PIXI.DisplayObject, + + /** + * Destroy this DisplayObject. + * + * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask. + * + * Also iteratively calls `destroy` on any children. + * + * @method PIXI.DisplayObject#destroy + */ + destroy: function () { + + if (this.children) + { + var i = this.children.length; + + while (i--) + { + this.children[i].destroy(); + } + + this.children = []; + } + + this.hitArea = null; + this.parent = null; + this.worldTransform = null; + this.filterArea = null; + this.renderable = false; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + }, + + /** + * Updates the transform matrix this DisplayObject uses for rendering. + * + * If the object has no parent, and no parent parameter is provided, it will default to + * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place. + * + * The `parent` parameter has priority over the actual parent. Use it as a parent override. + * Setting it does **not** change the actual parent of this DisplayObject. + * + * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale` + * and `worldRotation` properties. + * + * If a `transformCallback` has been specified, it is called at the end of this method, and is passed + * the new, updated, worldTransform property, along with the parent transform used. + * + * @method PIXI.DisplayObject#updateTransform + * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from. + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateTransform: function (parent) { + + if (!parent && !this.parent && !this.game) + { + return this; + } + + var p = this.parent; + + if (parent) + { + p = parent; + } + else if (!this.parent) + { + p = this.game.world; + } + + // create some matrix refs for easy access + var pt = p.worldTransform; + var wt = this.worldTransform; + + // temporary matrix variables + var a, b, c, d, tx, ty; + + // so if rotation is between 0 then we can simplify the multiplication process.. + if (this.rotation % Phaser.Math.PI2) + { + // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes + if (this.rotation !== this.rotationCache) + { + this.rotationCache = this.rotation; + this._sr = Math.sin(this.rotation); + this._cr = Math.cos(this.rotation); + } + + // get the matrix values of the displayobject based on its transform properties.. + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + tx = this.position.x; + ty = this.position.y; + + // check for pivot.. not often used so geared towards that fact! + if (this.pivot.x || this.pivot.y) + { + tx -= this.pivot.x * a + this.pivot.y * c; + ty -= this.pivot.x * b + this.pivot.y * d; + } + + // concat the parent matrix with the objects transform. + wt.a = a * pt.a + b * pt.c; + wt.b = a * pt.b + b * pt.d; + wt.c = c * pt.a + d * pt.c; + wt.d = c * pt.b + d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + else + { + // lets do the fast version as we know there is no rotation.. + a = this.scale.x; + b = 0; + c = 0; + d = this.scale.y; + tx = this.position.x - this.pivot.x * a; + ty = this.position.y - this.pivot.y * d; + + wt.a = a * pt.a; + wt.b = a * pt.b; + wt.c = d * pt.c; + wt.d = d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + + a = wt.a; + b = wt.b; + c = wt.c; + d = wt.d; + + var determ = (a * d) - (b * c); + + if (a || b) + { + var r = Math.sqrt((a * a) + (b * b)); + + this.worldRotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); + this.worldScale.x = r; + this.worldScale.y = determ / r; + } + else if (c || d) + { + var s = Math.sqrt((c * c) + (d * d)); + + this.worldRotation = Phaser.Math.HALF_PI - ((d > 0) ? Math.acos(-c / s) : -Math.acos(c / s)); + this.worldScale.x = determ / s; + this.worldScale.y = s; + } + else + { + this.worldScale.x = 0; + this.worldScale.y = 0; + } + + // Set the World values + this.worldAlpha = this.alpha * p.worldAlpha; + this.worldPosition.x = wt.tx; + this.worldPosition.y = wt.ty; + + // reset the bounds each time this is called! + this._currentBounds = null; + + // Custom callback? + if (this.transformCallback) + { + this.transformCallback.call(this.transformCallbackContext, wt, pt); + } + + return this; + + }, + + /** + * To be overridden by classes that require it. + * + * @method PIXI.DisplayObject#preUpdate + */ + preUpdate: function () { + + }, + + /** + * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites. + * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times. + * + * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures, + * and references to them, so they don't linger in memory. + * + * @method PIXI.DisplayObject#generateTexture + * @param {number} [resolution=1] - The resolution of the texture being generated. + * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values. + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture. + * @return {Phaser.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked. + */ + generateTexture: function (resolution, scaleMode, renderer) { + + var bounds = this.getLocalBounds(); + + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + + renderTexture.render(this, PIXI.DisplayObject._tempMatrix); + + return renderTexture; + + }, + + /** + * If this DisplayObject has a cached Sprite, this method generates and updates it. + * + * @method PIXI.DisplayObject#updateCache + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateCache: function () { + + this._generateCachedSprite(); + + return this; + + }, + + /** + * Calculates the global position of this DisplayObject, based on the position given. + * + * @method PIXI.DisplayObject#toGlobal + * @param {PIXI.Point} position - The global position to calculate from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toGlobal: function (position) { + + this.updateTransform(); + + return this.worldTransform.apply(position); + + }, + + /** + * Calculates the local position of this DisplayObject, relative to another point. + * + * @method PIXI.DisplayObject#toLocal + * @param {PIXI.Point} position - The world origin to calculate from. + * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toLocal: function (position, from) { + + if (from) + { + position = from.toGlobal(position); + } + + this.updateTransform(); + + return this.worldTransform.applyInverse(position); + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_renderCachedSprite + * @private + * @param {Object} renderSession - The render session + */ + _renderCachedSprite: function (renderSession) { + + this._cachedSprite.worldAlpha = this.worldAlpha; + + if (renderSession.gl) + { + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + } + else + { + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + } + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_generateCachedSprite + * @private + */ + _generateCachedSprite: function () { + + this._cacheAsBitmap = false; + + var bounds = this.getLocalBounds(); + + // Round it off and force non-zero dimensions + bounds.width = Math.max(1, Math.ceil(bounds.width)); + bounds.height = Math.max(1, Math.ceil(bounds.height)); + + this.updateTransform(); + + if (!this._cachedSprite) + { + var textureUnit = 0; + if (this.texture && this.texture.baseTexture && PIXI._enableMultiTextureToggle) + { + textureUnit = this.texture.baseTexture.textureIndex; + } + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width, bounds.height, undefined, undefined, undefined, undefined, textureUnit); + this._cachedSprite = new PIXI.Sprite(renderTexture); + this._cachedSprite.worldTransform = this.worldTransform; + } + else + { + this._cachedSprite.texture.resize(bounds.width, bounds.height); + } + + // Remove filters + var tempFilters = this._filters; + + this._filters = null; + this._cachedSprite.filters = tempFilters; + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true); + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + this._filters = tempFilters; + + this._cacheAsBitmap = true; + + }, + + /** + * Destroys a cached Sprite. + * + * @method PIXI.DisplayObject#_destroyCachedSprite + * @private + */ + _destroyCachedSprite: function () { + + if (!this._cachedSprite) + { + return; + } + + this._cachedSprite.texture.destroy(true); + + this._cachedSprite = null; + + } + +}; + +// Alias for updateTransform. As used in DisplayObject container, etc. +PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform; + +Object.defineProperties(PIXI.DisplayObject.prototype, { + + /** + * The horizontal position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#x + * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent. + */ + 'x': { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + } + + }, + + /** + * The vertical position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#y + * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent. + */ + 'y': { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + + }, + + /** + * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + * @name PIXI.DisplayObject#worldVisible + * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + */ + 'worldVisible': { + + get: function () { + + if (!this.visible) + { + return false; + } + else + { + var item = this.parent; + + if (!item) + { + return this.visible; + } + else + { + do + { + if (!item.visible) + { + return false; + } + + item = item.parent; + } + while (item); + + } + + return true; + } + + } + + }, + + /** + * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object. + * When applied it limits the visible area of this DisplayObject to the shape of the mask. + * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer. + * To remove a mask, set this property to `null`. + * + * @name PIXI.DisplayObject#mask + * @property {Phaser.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask. + */ + 'mask': { + + get: function () { + + return this._mask; + + }, + + set: function (value) { + + if (this._mask) + { + this._mask.isMask = false; + } + + this._mask = value; + + if (value) + { + this._mask.isMask = true; + } + + } + + }, + + /** + * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas + * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter + * using `DisplayObject.filterArea`. + * + * To remove filters, set this property to `null`. + * + * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a + * filter will reset this DisplayObjects blend mode to NORMAL. + * + * @name PIXI.DisplayObject#filters + * @property {Array} filters - An Array of Phaser.Filter objects, or objects that extend them. + */ + 'filters': { + + get: function () { + + return this._filters; + + }, + + set: function (value) { + + if (Array.isArray(value)) + { + // Put all the passes in one place. + var passes = []; + + for (var i = 0; i < value.length; i++) + { + var filterPasses = value[i].passes; + + for (var j = 0; j < filterPasses.length; j++) + { + passes.push(filterPasses[j]); + } + } + + // Needed any more? + this._filterBlock = { target: this, filterPasses: passes }; + } + + this._filters = value; + + if (this.blendMode && this.blendMode === PIXI.blendModes.MULTIPLY) + { + this.blendMode = PIXI.blendModes.NORMAL; + } + + } + + }, + + /** + * Sets if this DisplayObject should be cached as a bitmap. + * + * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it + * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a + * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not + * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`. + * + * To remove a cached bitmap, set this property to `null`. + * + * @name PIXI.DisplayObject#cacheAsBitmap + * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap. + */ + 'cacheAsBitmap': { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + if (this._cacheAsBitmap === value) + { + return; + } + + if (value) + { + this._generateCachedSprite(); + } + else + { + this._destroyCachedSprite(); + } + + this._cacheAsBitmap = value; + + } + + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A DisplayObjectContainer represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + * @class PIXI.DisplayObjectContainer + * @extends PIXI.DisplayObject + * @constructor + */ +PIXI.DisplayObjectContainer = function () { + + PIXI.DisplayObject.call(this); + + /** + * [read-only] The array of children of this container. + * + * @property children + * @type Array(DisplayObject) + * @readOnly + */ + this.children = []; + + /** + * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events. + * + * If this property is `true` then the children will _not_ be considered as valid for Input events. + * + * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. + * @property {boolean} ignoreChildInput + * @default + */ + this.ignoreChildInput = false; + +}; + +PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); +PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; + +/** + * Adds a child to the container. + * + * @method PIXI.DisplayObjectContainer#addChild + * @param child {DisplayObject} The DisplayObject to add to the container + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChild = function (child) { + + return this.addChildAt(child, this.children.length); + +}; + +/** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @method PIXI.DisplayObjectContainer#addChildAt + * @param child {DisplayObject} The child to add + * @param index {Number} The index to place the child in + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) { + + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + return child; + } + else + { + throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); + } + +}; + +/** + * Swaps the position of 2 Display Objects within this container. + * + * @method PIXI.DisplayObjectContainer#swapChildren + * @param child {DisplayObject} + * @param child2 {DisplayObject} + */ +PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) { + + if (child === child2) + { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(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; + +}; + +/** + * Returns the index position of a child DisplayObject instance + * + * @method PIXI.DisplayObjectContainer#getChildIndex + * @param child {DisplayObject} The DisplayObject instance to identify + * @return {Number} The index position of the child display object to identify + */ +PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + +}; + +/** + * Changes the position of an existing child in the display object container + * + * @method PIXI.DisplayObjectContainer#setChildIndex + * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number + * @param index {Number} The resulting index number for the child display object + */ +PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + this.children.splice(currentIndex, 1); //remove from old position + this.children.splice(index, 0, child); //add at new position + +}; + +/** + * Returns the child at the specified index + * + * @method PIXI.DisplayObjectContainer#getChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child at the given index, if any. + */ +PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller'); + } + + return this.children[index]; + +}; + +/** + * Removes a child from the container. + * + * @method PIXI.DisplayObjectContainer#removeChild + * @param child {DisplayObject} The DisplayObject to remove + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChild = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + return; + } + + return this.removeChildAt(index); + +}; + +/** + * Removes a child from the specified index position. + * + * @method PIXI.DisplayObjectContainer#removeChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) { + + var child = this.getChildAt(index); + + if (child) + { + child.parent = undefined; + + this.children.splice(index, 1); + } + + return child; + +}; + +/** +* Removes all children from this container that are within the begin and end indexes. +* +* @method PIXI.DisplayObjectContainer#removeChildren +* @param beginIndex {Number} The beginning position. Default value is 0. +* @param endIndex {Number} The ending position. Default value is size of the container. +*/ +PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { + + if (beginIndex === undefined) { beginIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var range = endIndex - beginIndex; + + if (range > 0 && range <= endIndex) + { + var removed = this.children.splice(beginIndex, range); + + for (var i = 0; i < removed.length; i++) + { + var child = removed[i]; + child.parent = undefined; + } + + return removed; + } + else if (range === 0 && this.children.length === 0) + { + return []; + } + else + { + throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' ); + } + +}; + +/* + * Updates the transform on all children of this container for rendering + * + * @method PIXI.DisplayObjectContainer#updateTransform + * @private + */ +PIXI.DisplayObjectContainer.prototype.updateTransform = function () { + + if (!this.visible) + { + return; + } + + this.displayObjectUpdateTransform(); + + if (this._cacheAsBitmap) + { + return; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +// performance increase to avoid using call.. (10x faster) +PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform; + +/** + * Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getBounds + * @param {PIXI.DisplayObject|Phaser.Matrix} [targetCoordinateSpace] Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpace) { + + var isTargetCoordinateSpaceDisplayObject = (targetCoordinateSpace && targetCoordinateSpace instanceof PIXI.DisplayObject); + var isTargetCoordinateSpaceThisOrParent = true; + + if (!isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace = this; + } + else if (targetCoordinateSpace instanceof PIXI.DisplayObjectContainer) + { + isTargetCoordinateSpaceThisOrParent = targetCoordinateSpace.contains(this); + } + else + { + isTargetCoordinateSpaceThisOrParent = false; + } + + var i; + + if (isTargetCoordinateSpaceDisplayObject) + { + var matrixCache = targetCoordinateSpace.worldTransform; + + targetCoordinateSpace.worldTransform = Phaser.identityMatrix; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + var minX = Infinity; + var minY = Infinity; + + var maxX = -Infinity; + var maxY = -Infinity; + + var childBounds; + var childMaxX; + var childMaxY; + + var childVisible = false; + + for (i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + childVisible = true; + + childBounds = this.children[i].getBounds(); + + minX = (minX < childBounds.x) ? minX : childBounds.x; + minY = (minY < childBounds.y) ? minY : childBounds.y; + + childMaxX = childBounds.width + childBounds.x; + childMaxY = childBounds.height + childBounds.y; + + maxX = (maxX > childMaxX) ? maxX : childMaxX; + maxY = (maxY > childMaxY) ? maxY : childMaxY; + } + + var bounds = this._bounds; + + if (!childVisible) + { + bounds = new PIXI.Rectangle(); + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + maxX = x1; + maxY = y1; + + minX = x1; + minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + } + + bounds.x = minX; + bounds.y = minY; + bounds.width = maxX - minX; + bounds.height = maxY - minY; + + if (isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace.worldTransform = matrixCache; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + if (!isTargetCoordinateSpaceThisOrParent) + { + var targetCoordinateSpaceBounds = targetCoordinateSpace.getBounds(); + + bounds.x -= targetCoordinateSpaceBounds.x; + bounds.y -= targetCoordinateSpaceBounds.y; + } + + return bounds; + +}; + +/** + * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getLocalBounds = function () { + + return this.getBounds(this); + +}; + +/** +* Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. +* +* @method PIXI.DisplayObjectContainer#contains +* @param {DisplayObject} child +* @returns {boolean} +*/ +PIXI.DisplayObjectContainer.prototype.contains = function (child) { + + if (!child) + { + return false; + } + else if (child === this) + { + return true; + } + else + { + return this.contains(child.parent); + } +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.DisplayObjectContainer#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + var i; + + if (this._mask || this._filters) + { + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + renderSession.spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + renderSession.spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + renderSession.spriteBatch.start(); + } + + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + renderSession.spriteBatch.start(); + } + else + { + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.DisplayObjectContainer#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) { + + if (this.visible === false || this.alpha === 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', { + + get: function() { + return this.getLocalBounds().width * this.scale.x; + }, + + set: function(value) { + + var width = this.getLocalBounds().width; + + if (width !== 0) + { + this.scale.x = value / width; + } + else + { + this.scale.x = 1; + } + + this._width = value; + } +}); + +/** + * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', { + + get: function() { + return this.getLocalBounds().height * this.scale.y; + }, + + set: function(value) { + + var height = this.getLocalBounds().height; + + if (height !== 0) + { + this.scale.y = value / height; + } + else + { + this.scale.y = 1; + } + + this._height = value; + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * @class PIXI.Sprite + * @extends PIXI.DisplayObjectContainer + * @constructor + * @param texture {Texture} The texture for this sprite + */ +PIXI.Sprite = function (texture) { + + PIXI.DisplayObjectContainer.call(this); + + /** + * The anchor sets the origin point of the texture. + * The default (0, 0) is the top left. + * (0.5, 0.5) is the center. + * (1, 1) is the bottom right. + * + * You can modify the default values in PIXI.Sprite.defaultAnchor. + * + * @property anchor + * @type Point + */ + this.anchor = new PIXI.Point(PIXI.Sprite.defaultAnchor.x, PIXI.Sprite.defaultAnchor.y); + + /** + * The texture that the sprite is using + * + * @property texture + * @type Texture + */ + this.texture = texture || PIXI.Texture.emptyTexture; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @property _width + * @type Number + * @private + */ + this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @property _height + * @type Number + * @private + */ + this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF (Phaser.Color.WHITE) will remove any tint effect. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @property cachedTint + * @private + * @type Number + * @default -1 + */ + this.cachedTint = -1; + + /** + * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) + * + * @property tintedTexture + * @type Canvas + * @default null + */ + this.tintedTexture = null; + + /** + * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. + * + * Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * The shader that will be used to render this Sprite. + * Set to null to remove a current shader. + * + * @property shader + * @type Phaser.Filter + * @default null + */ + this.shader = null; + + /** + * Controls if this Sprite is processed by the core Phaser game loops and Group loops (except {@link Phaser.Group#update}). + * + * @property exists + * @type Boolean + * @default true + */ + this.exists = true; + + if (this.texture.baseTexture.hasLoaded) + { + this.onTextureUpdate(); + } + + this.renderable = true; + +}; + +/** + * @property PIXI.Sprite.defaultAnchor - A Point-like object. + * @type {{x: number, y: number}} + * @default + */ +PIXI.Sprite.defaultAnchor = {x: 0, y: 0}; + +// constructor +PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +PIXI.Sprite.prototype.constructor = PIXI.Sprite; + +/** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'width', { + + get: function() { + return this.scale.x * this.texture.frame.width; + }, + + set: function(value) { + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'height', { + + get: function() { + return this.scale.y * this.texture.frame.height; + }, + + set: function(value) { + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +/** + * Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous + * texture this Sprite was using. + * + * @method PIXI.Sprite#setTexture + * @param texture {Texture} The PIXI texture that is displayed by the sprite + * @param [destroy=false] {boolean} Call Texture.destroy on the current texture before replacing it with the new one? + */ +PIXI.Sprite.prototype.setTexture = function(texture, destroyBase) +{ + if (destroyBase) + { + this.texture.baseTexture.destroy(); + } + + // Over-ridden by loadTexture as needed + this.texture.baseTexture.skipRender = false; + this.texture = texture; + this.texture.valid = true; + this.cachedTint = -1; +}; + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @method PIXI.Sprite#onTextureUpdate + * @param event + * @private + */ +PIXI.Sprite.prototype.onTextureUpdate = function() +{ + // so if _width is 0 then width was not set.. + if (this._width) this.scale.x = this._width / this.texture.frame.width; + if (this._height) this.scale.y = this._height / this.texture.frame.height; +}; + +/** +* Returns the bounds of the Sprite as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* It is important to note that the transform is not updated when you call this method. +* So if this Sprite is the child of a Display Object which has had its transform +* updated since the last render pass, those changes will not yet have been applied +* to this Sprites worldTransform. If you need to ensure that all parent transforms +* are factored into this getBounds operation then you should call `updateTransform` +* on the root most object in this Sprites display list first. +* +* @method PIXI.Sprite#getBounds +* @param matrix {Matrix} the transformation matrix of the sprite +* @return {Rectangle} the framing rectangle +*/ +PIXI.Sprite.prototype.getBounds = function(matrix) +{ + var width = this.texture.frame.width; + var height = this.texture.frame.height; + + var w0 = width * (1-this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1-this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + if (b === 0 && c === 0) + { + // scale may be negative! + if (a < 0) + { + a *= -1; + var temp = w0; + w0 = -w1; + w1 = -temp; + } + + if (d < 0) + { + d *= -1; + var temp = h0; + h0 = -h1; + h1 = -temp; + } + + // this means there is no rotation going on right? RIGHT? + // if thats the case then we can avoid checking the bound values! yay + minX = a * w1 + tx; + maxX = a * w0 + tx; + minY = d * h1 + ty; + maxY = d * h0 + ty; + } + else + { + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; +}; + +/** + * Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. + * + * @method PIXI.Sprite#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.Sprite.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.Sprite#_renderWebGL +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix) +{ + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha <= 0 || !this.renderable) return; + + // They provided an alternative rendering matrix, so use it + var wt = this.worldTransform; + + if (matrix) + { + wt = matrix; + } + + // A quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) + { + var spriteBatch = renderSession.spriteBatch; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + spriteBatch.start(); + } + + // add this sprite to the batch + spriteBatch.render(this); + + // now loop through the children and make sure they get rendered + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + // time to stop the sprite batch as either a mask element or a filter draw will happen next + spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + spriteBatch.start(); + } + else + { + renderSession.spriteBatch.render(this); + + // Render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession, wt); + } + + } +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.Sprite#_renderCanvas +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix) +{ + // If the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha === 0 || !this.renderable || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { + return; + } + + var wt = this.worldTransform; + + // If they provided an alternative rendering matrix then use it + if (matrix) + { + wt = matrix; + } + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + // Ignore null sources + if (!this.texture.valid) + { + // Update the children and leave + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + return; + } + + var resolution = this.texture.baseTexture.resolution / renderSession.resolution; + + renderSession.context.globalAlpha = this.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for this texture + if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode) + { + renderSession.scaleMode = this.texture.baseTexture.scaleMode; + renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + + // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions + var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width; + var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height; + + var tx = (wt.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (wt.ty * renderSession.resolution) + renderSession.shakeY; + + var cw = this.texture.crop.width; + var ch = this.texture.crop.height; + + if (this.texture.rotated) + { + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var e = cw; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + wt.a = a * 6.123233995736766e-17 + -c; + wt.b = b * 6.123233995736766e-17 + -d; + wt.c = a + c * 6.123233995736766e-17; + wt.d = b + d * 6.123233995736766e-17; + + // Update cropping dimensions. + cw = ch; + ch = e; + } + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx | 0, ty | 0); + dx |= 0; + dy |= 0; + } + else + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + } + + dx /= resolution; + dy /= resolution; + + if (this.tint !== 0xFFFFFF) + { + if (this.texture.requiresReTint || this.cachedTint !== this.tint) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + } + + renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + else + { + var cx = this.texture.crop.x; + var cy = this.texture.crop.y; + + cw = Math.floor(cw) + ch = Math.floor(ch) + + renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @method PIXI.initDefaultShaders +* @static +* @private +*/ +PIXI.initDefaultShaders = function() +{ +}; + +/** +* @method PIXI.CompileVertexShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileVertexShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); +}; + +/** +* @method PIXI.CompileFragmentShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileFragmentShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); +}; + +/** +* @method PIXI._CompileShader +* @static +* @private +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @param shaderType {Number} +* @return {Any} +*/ +PIXI._CompileShader = function(gl, shaderSrc, shaderType) +{ + var src = shaderSrc; + + if (Array.isArray(shaderSrc)) + { + 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; +}; + +/** +* @method PIXI.compileProgram +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param vertexSrc {Array} +* @param fragmentSrc {Array} +* @return {Any} +*/ +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(gl.getProgramInfoLog(shaderProgram)); + window.console.log("Could not initialise shaders"); + } + + return shaderProgram; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + * @author Richard Davey http://www.photonstorm.com @photonstorm + */ + +/** +* @class PIXI.PixiShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PixiShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = null; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + /** + * A local flag + * @property firstRun + * @type Boolean + * @private + */ + this.firstRun = true; + + /** + * A dirty flag + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Uniform attributes cache. + * @property attributes + * @type Array + * @private + */ + this.attributes = []; + + this.init(); +}; + +PIXI.PixiShader.prototype.constructor = PIXI.PixiShader; + +PIXI.PixiShader.prototype.initMultitexShader = function () { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.fragmentSrc = [ + '// PixiShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}', + '}' + ]; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + //this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.uSamplerArray = gl.getUniformLocation(program, 'uSamplerArray[0]'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSamplerArray, indices); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; + +PIXI.PixiShader.prototype.initDefaultShader = function () { + + if (this.fragmentSrc === null) { + this.fragmentSrc = [ + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', + '}' + ]; + } + + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; +/** +* Initialises the shader. +* +* @method PIXI.PixiShader#init +*/ +PIXI.PixiShader.prototype.init = function(usingFilter) +{ + if (PIXI._enableMultiTextureToggle && !usingFilter) { + this.initMultitexShader(); + } else { + this.initDefaultShader(); + } +}; + +/** +* Initialises the shader uniform values. +* +* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ +* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf +* +* @method PIXI.PixiShader#initUniforms +*/ +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') + { + // These require special handling + 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 + { + // GL function reference + 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; + } + } + } + +}; + +/** +* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) +* +* @method PIXI.PixiShader#initSampler2D +*/ +PIXI.PixiShader.prototype.initSampler2D = function(uniform) +{ + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { + return; + } + + var gl = this.gl; + + // No need to do string manipulation for this. + gl.activeTexture(gl.TEXTURE0 + this.textureCount); + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + + // Extended texture data + if (uniform.textureData) + { + var data = uniform.textureData; + + // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); + // GLTextureLinear = mag/min linear, wrap clamp + // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat + // GLTextureNearest = mag/min nearest, wrap clamp + // AudioTexture = whatever + luminance + width 512, height 2, border 0 + // KeyTexture = whatever + luminance + width 256, height 2, border 0 + + // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + + 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; + + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels); + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); + } + else + { + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels); + 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++; + +}; + +/** +* Updates the shader uniform values. +* +* @method PIXI.PixiShader#syncUniforms +*/ +PIXI.PixiShader.prototype.syncUniforms = function() +{ + this.textureCount = 1; + var uniform; + var gl = this.gl; + + // This would probably be faster in an array and it would guarantee key order + 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]); + + if(uniform.value.baseTexture._dirty[gl.id]) + { + PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + } + + // 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); + } + } + } + +}; + +/** +* Destroys the shader. +* +* @method PIXI.PixiShader#destroy +*/ +PIXI.PixiShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** +* The Default Vertex shader source. +* +* @property defaultVertexSrc +* @type String +*/ +PIXI.PixiShader.defaultVertexSrc = [ + '// PixiShader Vertex Shader', + '// With multi-texture rendering', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute vec4 aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + + 'const vec2 center = vec2(-1.0, 1.0);', + + 'void main(void) {', + ' if (aTextureIndex > 0.0) gl_Position = vec4(0.0);', + ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', + ' vTextureCoord = aTextureCoord;', + ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', + ' vTextureIndex = aTextureIndex;', + '}' +]; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @class PIXI.PixiFastShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.PixiFastShader = function (gl) { + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '// PixiFastShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aPositionCoord;', + 'attribute vec2 aScale;', + 'attribute float aRotation;', + 'attribute vec2 aTextureCoord;', + 'attribute float aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform mat3 uMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + + '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;', + ' vTextureIndex = aTextureIndex;', + // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;', + ' vColor = aColor;', + '}' + ]; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + this.init(); +}; + +PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader; + +/** + * Initialises the shader. + * + * @method PIXI.PixiFastShader#init + */ +PIXI.PixiFastShader.prototype.init = function () { + + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + this.uMatrix = gl.getUniformLocation(program, 'uMatrix'); + + // get and store the attributes + 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'); + + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its somthing to do with the current state of the gl context. + // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if (this.colorAttribute === -1) { + this.colorAttribute = 2; + } + + this.attributes = [ + this.aVertexPosition, + this.aPositionCoord, + this.aScale, + this.aRotation, + this.aTextureCoord, + this.colorAttribute, + this.aTextureIndex + ]; + + // End worst hack eva // + + this.program = program; +}; + +/** + * Destroys the shader. + * + * @method PIXI.PixiFastShader#destroy + */ +PIXI.PixiFastShader.prototype.destroy = function () { + this.gl.deleteProgram(this.program); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.StripShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.StripShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord);return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) ;return;}\n' + } + + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord);', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '//StripShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute float aTextureIndex;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + // 'uniform float alpha;', + // 'uniform vec3 tint;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // '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);', + ' vTextureCoord = aTextureCoord;', + ' vTextureIndex = aTextureIndex;', + // ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.StripShader.prototype.constructor = PIXI.StripShader; + +/** +* Initialises the shader. +* +* @method PIXI.StripShader#init +*/ +PIXI.StripShader.prototype.init = function() +{ + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + //this.dimensions = gl.getUniformLocation(this.program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.aTextureIndex]; + + this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix'); + this.alpha = gl.getUniformLocation(program, 'alpha'); + + this.program = program; +}; + +/** +* Destroys the shader. +* +* @method PIXI.StripShader#destroy +*/ +PIXI.StripShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.PrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + 'precision mediump float;', + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform float alpha;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.PrimitiveShader#init +*/ +PIXI.PrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.PrimitiveShader#destroy +*/ +PIXI.PrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.ComplexPrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.ComplexPrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + + 'precision mediump float;', + + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + //'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 color;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.ComplexPrimitiveShader#init +*/ +PIXI.ComplexPrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.color = gl.getUniformLocation(program, 'color'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.ComplexPrimitiveShader#destroy +*/ +PIXI.ComplexPrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +PIXI.glContexts = []; // this is where we store the webGL contexts for easy access. +PIXI.instances = []; +PIXI._enableMultiTextureToggle = false; + +/** + * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class PIXI.WebGLRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.WebGLRenderer = function(game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + this.extensions = {}; + + /** + * @property type + * @type Number + */ + this.type = Phaser.WEBGL; + + /** + * The resolution of the renderer + * + * @property resolution + * @type Number + * @default 1 + */ + this.resolution = game.resolution; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * + * @property preserveDrawingBuffer + * @type Boolean + */ + this.preserveDrawingBuffer = game.preserveDrawingBuffer; + + /** + * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true: + * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0). + * If the Stage is transparent, Pixi will clear to the target Stage's background color. + * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * The width of the canvas view + * + * @property width + * @type Number + */ + this.width = game.width; + + /** + * The height of the canvas view + * + * @property height + * @type Number + */ + this.height = game.height; + + /** + * The canvas element that everything is drawn to + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * @property _contextOptions + * @type Object + * @private + */ + this._contextOptions = { + alpha: this.transparent, + antialias: game.antialias, + failIfMajorPerformanceCaveat: config.failIfMajorPerformanceCaveat, + premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: this.preserveDrawingBuffer + }; + + /** + * @property projection + * @type Point + */ + this.projection = new PIXI.Point(); + + /** + * @property offset + * @type Point + */ + this.offset = new PIXI.Point(); + + // time to create the render managers! each one focuses on managing a state in webGL + + /** + * Deals with managing the shader programs and their attribs + * @property shaderManager + * @type WebGLShaderManager + */ + this.shaderManager = new PIXI.WebGLShaderManager(); + + /** + * Manages the rendering of sprites + * @property spriteBatch + * @type WebGLSpriteBatch + */ + this.spriteBatch = new PIXI.WebGLSpriteBatch(game); + + /** + * Manages the masks using the stencil buffer + * @property maskManager + * @type WebGLMaskManager + */ + this.maskManager = new PIXI.WebGLMaskManager(); + + /** + * Manages the filters + * @property filterManager + * @type WebGLFilterManager + */ + this.filterManager = new PIXI.WebGLFilterManager(); + + /** + * Manages the stencil buffer + * @property stencilManager + * @type WebGLStencilManager + */ + this.stencilManager = new PIXI.WebGLStencilManager(); + + /** + * Manages the blendModes + * @property blendModeManager + * @type WebGLBlendModeManager + */ + this.blendModeManager = new PIXI.WebGLBlendModeManager(); + + /** + * @property renderSession + * @type Object + */ + this.renderSession = {}; + + /** + * @property currentBatchedTextures + * @type Array + */ + this.currentBatchedTextures = []; + + // Needed? + this.renderSession.game = this.game; + this.renderSession.gl = this.gl; + this.renderSession.drawCount = 0; + this.renderSession.shaderManager = this.shaderManager; + this.renderSession.maskManager = this.maskManager; + this.renderSession.filterManager = this.filterManager; + this.renderSession.blendModeManager = this.blendModeManager; + this.renderSession.spriteBatch = this.spriteBatch; + this.renderSession.stencilManager = this.stencilManager; + this.renderSession.renderer = this; + this.renderSession.resolution = this.resolution; + this.renderSession.roundPixels = config.roundPixels || false; + this.renderSession.maxTextureAvailableSpace = null; // filled in setTexturePriority() + + // time init the context.. + this.initContext(); + + // map some webGL blend modes.. + this.mapBlendModes(); + +}; + +// constructor +PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer; + +/** +* @method PIXI.WebGLRenderer#initContext +*/ +PIXI.WebGLRenderer.prototype.initContext = function() +{ + var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); + + this.gl = gl; + + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + this.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.maxTextureSize = this.gl.getParameter(gl.MAX_TEXTURE_SIZE); + + this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++; + + PIXI.glContexts[this.glContextId] = gl; + + PIXI.instances[this.glContextId] = this; + + // set up the default pixi settings.. + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + gl.enable(gl.BLEND); + + // need to set the context for all the managers... + this.shaderManager.setContext(gl); + this.spriteBatch.setContext(gl); + this.maskManager.setContext(gl); + this.filterManager.setContext(gl); + this.blendModeManager.setContext(gl); + this.stencilManager.setContext(gl); + + this.renderSession.gl = this.gl; + + // now resize and we are good to go! + this.resize(this.width, this.height); + + // Load WebGL extension + this.extensions.compression = {}; + + var etc1 = gl.getExtension('WEBGL_compressed_texture_etc1') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'); + var pvrtc = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); + var s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); + + if (etc1) { this.extensions.compression.ETC1 = etc1; } + if (pvrtc) { this.extensions.compression.PVRTC = pvrtc; } + if (s3tc) { this.extensions.compression.S3TC = s3tc; } +}; + +/** +* If Multi Texture support has been enabled, then calling this method will enable batching on the given +* textures. The texture collection is an array of keys, that map to Phaser.Cache image entries. +* +* The number of textures that can be batched is dependent on hardware. If you provide more textures +* than can be batched by the GPU, then only those at the start of the array will be used. Generally +* you shouldn't provide more than 16 textures to this method. You can check the hardware limit via the +* `maxTextures` property. +* +* You can also check the property `currentBatchedTextures` at any time, to see which textures are currently +* being batched. +* +* To stop all textures from being batched, call this method again with an empty array. +* +* To change the textures being batched, call this method with a new array of image keys. The old ones +* will all be purged out and no-longer batched, and the new ones enabled. +* +* Note: Throws a warning if you haven't enabled Multiple Texture batching support in the Phaser Game config. +* +* @method PIXI.WebGLRenderer#setTexturePriority +* @param textureNameCollection {Array} An Array of Texture Cache keys to use for multi-texture batching. +* @return {Array} An array containing the texture keys that were enabled for batching. +*/ +PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + if (!PIXI._enableMultiTextureToggle) + { + console.warn('setTexturePriority error: Multi Texture support hasn\'t been enabled in the Phaser Game Config.'); + return; + } + var clampPot = function (potSize) { + --potSize; + potSize |= potSize >> 1; + potSize |= potSize >> 2; + potSize |= potSize >> 4; + potSize |= potSize >> 8; + potSize |= potSize >> 16; + return ++potSize; + }; + var gl = this.gl; + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + var imageCache = this.game.cache._cache.image; + var imageName = null; + + // Clear out all previously batched textures and reset their flags. + // If the array has been modified, then the developer will have to + // deal with that in their own way. + for (var i = 0; i < this.currentBatchedTextures.length; i++) + { + imageName = this.currentBatchedTextures[i]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + + imageCache[imageName].base.textureIndex = 0; + } + var maxTextureAvailableSpace = (maxTextureSize) - clampPot(Math.max(this.width, this.height)); + this.currentBatchedTextures.length = 0; + // We start from 1 because framebuffer texture uses unit 0. + for (var j = 0; j < textureNameCollection.length; ++j) + { + imageName = textureNameCollection[j]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + // Unit 0 is reserved for Pixi's framebuffer + var base = imageCache[imageName].base; + maxTextureAvailableSpace -= clampPot(Math.max(base.width, base.height)); + if (maxTextureAvailableSpace <= 0) { + base.textureIndex = 0; + console.warn('setTexturePriority: Image "%s" was given textureIndex=0 because there is no available texture space (%s).', + imageName, maxTextureAvailableSpace); + } else { + base.textureIndex = (1 + (j % (maxTextures - 1))); + } + this.currentBatchedTextures.push(imageName); + } + + this.renderSession.maxTextureAvailableSpace = maxTextureAvailableSpace; + + return this.currentBatchedTextures; + +}; + +/** + * Renders the stage to its webGL view + * + * @method PIXI.WebGLRenderer#render + * @param stage {Stage} the Stage element to be rendered + */ +PIXI.WebGLRenderer.prototype.render = function(stage) +{ + // no point rendering if our context has been blown up! + if (this.contextLost) + { + return; + } + + var gl = this.gl; + + // -- Does this need to be set every frame? -- // + gl.viewport(0, 0, this.width, this.height); + + // make sure we are bound to the main frame buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + if (this.game.clearBeforeRender) + { + gl.clearColor(stage._bgColor.r, stage._bgColor.g, stage._bgColor.b, stage._bgColor.a); + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + this.offset.x = this.game.camera._shake.x; + this.offset.y = this.game.camera._shake.y; + + this.renderDisplayObject(stage, this.projection); +}; + +/** + * Renders a Display Object. + * + * @method PIXI.WebGLRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The DisplayObject to render + * @param projection {Point} The projection + * @param buffer {Array} a standard WebGL buffer + */ +PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix) +{ + this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL); + + // reset the render session data.. + this.renderSession.drawCount = 0; + + // make sure to flip the Y if using a render texture.. + this.renderSession.flipY = buffer ? -1 : 1; + + // set the default projection + this.renderSession.projection = projection; + + //set the default offset + this.renderSession.offset = this.offset; + + // start the sprite batch + this.spriteBatch.begin(this.renderSession); + + // start the filter manager + this.filterManager.begin(this.renderSession, buffer); + + // render the scene! + displayObject._renderWebGL(this.renderSession, matrix); + + // finish the sprite batch + this.spriteBatch.end(); +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @method PIXI.WebGLRenderer#resize + * @param width {Number} the new width of the webGL view + * @param height {Number} the new height of the webGL view + */ +PIXI.WebGLRenderer.prototype.resize = function(width, height) +{ + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } + + this.gl.viewport(0, 0, this.width, this.height); + + this.projection.x = this.width / 2 / this.resolution; + this.projection.y = -this.height / 2 / this.resolution; +}; + +/** + * Updates and creates a WebGL compressed texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateCompressedTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateCompressedTexture = function (texture) { + if (!texture.hasLoaded) + { + return false; + } + var gl = this.gl; + var textureMetaData = texture.source; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + textureMetaData.glExtensionFormat, + textureMetaData.width, + textureMetaData.height, + 0, + textureMetaData.textureData + ); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + texture._dirty[gl.id] = false; + return true; +}; + +/** + * Updates and Creates a WebGL texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateTexture = function(texture) +{ + if (!texture.hasLoaded) + { + return false; + } + if (texture.source.compressionAlgorithm) { + return this.updateCompressedTexture(texture); + } + + var gl = this.gl; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha); + + 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); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + + texture._dirty[gl.id] = false; + + // return texture._glTextures[gl.id]; + return true; + +}; + +/** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @method PIXI.WebGLRenderer#destroy + */ +PIXI.WebGLRenderer.prototype.destroy = function() +{ + 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; + + Phaser.CanvasPool.remove(this); + + PIXI.instances[this.glContextId] = null; + + PIXI.WebGLRenderer.glContextId--; +}; + +/** + * Maps Pixi blend modes to WebGL blend modes. + * + * @method PIXI.WebGLRenderer#mapBlendModes + */ +PIXI.WebGLRenderer.prototype.mapBlendModes = function() +{ + var gl = this.gl; + + if (!PIXI.blendModesWebGL) + { + var b = []; + var modes = PIXI.blendModes; + + b[modes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA]; + b[modes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SCREEN] = [gl.SRC_ALPHA, gl.ONE]; + b[modes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + PIXI.blendModesWebGL = b; + } +}; + +PIXI.WebGLRenderer.prototype.getMaxTextureUnit = function() { + var gl = this.gl; + return gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); +}; + +PIXI.enableMultiTexture = function() { + PIXI._enableMultiTextureToggle = true; +}; + +PIXI.WebGLRenderer.glContextId = 0; +PIXI.WebGLRenderer.textureArray = []; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLBlendModeManager +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLBlendModeManager = function() +{ + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 99999; +}; + +PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLBlendModeManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLBlendModeManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Sets-up the given blendMode from WebGL's point of view. +* +* @method PIXI.WebGLBlendModeManager#setBlendMode +* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD +*/ +PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode) +{ + if(this.currentBlendMode === blendMode)return false; + + this.currentBlendMode = blendMode; + + var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode]; + + if (blendModeWebGL) + { + this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLBlendModeManager#destroy +*/ +PIXI.WebGLBlendModeManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLMaskManager +* @constructor +* @private +*/ +PIXI.WebGLMaskManager = function() +{ +}; + +PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLMaskManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLMaskManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLMaskManager#pushMask +* @param maskData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession) +{ + var gl = renderSession.gl; + + if (maskData.dirty) + { + PIXI.WebGLGraphics.updateGraphics(maskData, gl); + } + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLMaskManager#popMask +* @param maskData {Array} +* @param renderSession {Object} an object containing all the useful parameters +*/ +PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession) +{ + var gl = this.gl; + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); + +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLMaskManager#destroy +*/ +PIXI.WebGLMaskManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLStencilManager +* @constructor +* @private +*/ +PIXI.WebGLStencilManager = function() +{ + this.stencilStack = []; + this.reverse = true; + this.count = 0; +}; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLStencilManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLStencilManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLStencilManager#pushMask +* @param graphics {Graphics} +* @param webGLData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.bindGraphics(graphics, webGLData, renderSession); + + if(this.stencilStack.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + this.reverse = true; + this.count = 0; + } + + this.stencilStack.push(webGLData); + + var level = this.count; + + gl.colorMask(false, false, false, false); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + + if(webGLData.mode === 1) + { + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + + this.reverse = !this.reverse; + } + else + { + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + this.count++; +}; + +/** + * TODO this does not belong here! + * + * @method PIXI.WebGLStencilManager#bindGraphics + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession) +{ + //if(this._currentGraphics === graphics)return; + this._currentGraphics = graphics; + + var gl = this.gl; + + // bind the graphics object.. + var projection = renderSession.projection, + offset = renderSession.offset, + shader;// = renderSession.shaderManager.primitiveShader; + + if(webGLData.mode === 1) + { + shader = renderSession.shaderManager.complexPrimitiveShader; + + renderSession.shaderManager.setShader( shader ); + + gl.uniform1f(shader.flipY, renderSession.flipY); + + 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, Phaser.Color.hexToRGBArray(graphics.tint)); + gl.uniform3fv(shader.color, webGLData.color); + + gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0); + + + // now do the rest.. + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } + else + { + //renderSession.shaderManager.activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + renderSession.shaderManager.setShader( shader ); + + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, renderSession.flipY); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } +}; + +/** + * @method PIXI.WebGLStencilManager#popStencil + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.stencilStack.pop(); + + this.count--; + + if(this.stencilStack.length === 0) + { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + + } + else + { + + var level = this.count; + + this.bindGraphics(graphics, webGLData, renderSession); + + gl.colorMask(false, false, false, false); + + if(webGLData.mode === 1) + { + this.reverse = !this.reverse; + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + + } + else + { + // console.log("<<>>") + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + + } +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLStencilManager#destroy +*/ +PIXI.WebGLStencilManager.prototype.destroy = function() +{ + this.stencilStack = null; + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLShaderManager +* @constructor +* @private +*/ +PIXI.WebGLShaderManager = function() +{ + /** + * @property maxAttibs + * @type Number + */ + this.maxAttibs = 10; + + /** + * @property attribState + * @type Array + */ + this.attribState = []; + + /** + * @property tempAttribState + * @type Array + */ + this.tempAttribState = []; + + for (var i = 0; i < this.maxAttibs; i++) + { + this.attribState[i] = false; + } + + /** + * @property stack + * @type Array + */ + this.stack = []; + +}; + +PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLShaderManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLShaderManager.prototype.setContext = function(gl) +{ + this.gl = gl; + + // the next one is used for rendering primitives + this.primitiveShader = new PIXI.PrimitiveShader(gl); + + // the next one is used for rendering triangle strips + this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl); + + // this shader is used for the default sprite rendering + this.defaultShader = new PIXI.PixiShader(gl); + + // this shader is used for the fast sprite rendering + this.fastShader = new PIXI.PixiFastShader(gl); + + // the next one is used for rendering triangle strips + this.stripShader = new PIXI.StripShader(gl); + + // the next one is used for rendering creature meshes + this.creatureShader = PIXI.CreatureShader ? new PIXI.CreatureShader(gl) : null; + + this.setShader(this.defaultShader); +}; + +/** +* Takes the attributes given in parameters. +* +* @method PIXI.WebGLShaderManager#setAttribs +* @param attribs {Array} attribs +*/ +PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs) +{ + // reset temp state + var i; + + for (i = 0; i < this.tempAttribState.length; i++) + { + this.tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + var attribId = attribs[i]; + this.tempAttribState[attribId] = true; + } + + var gl = this.gl; + + for (i = 0; i < this.attribState.length; i++) + { + if(this.attribState[i] !== this.tempAttribState[i]) + { + this.attribState[i] = this.tempAttribState[i]; + + if(this.tempAttribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } +}; + +/** +* Sets the current shader. +* +* @method PIXI.WebGLShaderManager#setShader +* @param shader {Any} +*/ +PIXI.WebGLShaderManager.prototype.setShader = function(shader) +{ + if(this._currentId === shader._UID)return false; + + this._currentId = shader._UID; + + this.currentShader = shader; + + this.gl.useProgram(shader.program); + this.setAttribs(shader.attributes); + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLShaderManager#destroy +*/ +PIXI.WebGLShaderManager.prototype.destroy = function() +{ + this.attribState = null; + + this.tempAttribState = null; + + this.primitiveShader.destroy(); + + this.complexPrimitiveShader.destroy(); + + this.defaultShader.destroy(); + + this.fastShader.destroy(); + + this.stripShader.destroy(); + + if (this.creatureShader) { + this.creatureShader.destroy(); + } + + this.gl = null; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** + * + * @class PIXI.WebGLSpriteBatch + * @private + * @constructor + */ +PIXI.WebGLSpriteBatch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 5; + + /** + * The number of images in the SpriteBatch before it flushes + * @property size + * @type Number + */ + this.size = 2000; //Math.pow(2, 16) / this.vertSize; + + //the total number of bytes in our batch + // Including texture index: + // position + uv + color + textureIndex + // vec2 + vec2 + (char * 4) + float + this.vertexSize = (4 * 2) + (4 * 2) + (4) + (4); + var numVerts = this.vertexSize * this.size * 4; + //this.size * 4 * 4 * this.vertSize; + //the total number of indices in our batch + var numIndices = this.size * 6; + + /** + * Holds the vertices + * + * @property vertices + * @type ArrayBuffer + */ + this.vertices = new ArrayBuffer(numVerts); + + /** + * View on the vertices as a Float32Array + * + * @property positions + * @type Float32Array + */ + this.positions = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array + * + * @property colors + * @type Uint32Array + */ + this.colors = new Uint32Array(this.vertices); + + /** + * Holds the indices + * + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * @property textures + * @type Array + */ + this.textures = []; + + /** + * @property blendModes + * @type Array + */ + this.blendModes = []; + + /** + * @property shaders + * @type Array + */ + this.shaders = []; + + /** + * @property sprites + * @type Array + */ + this.sprites = []; + + /** + * @property defaultShader + * @type Phaser.Filter + */ + this.defaultShader = null; +}; + +/** + * @method PIXI.WebGLSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLSpriteBatch.prototype.setContext = function (gl) { + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.gl = gl; + if (PIXI._enableMultiTextureToggle) { + var dynamicIfs = '\tif (vTextureIndex == 0.0) {gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + 'void main(void) {', + dynamicIfs, + '\tgl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;', + '}' + ]); + } + else + { + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]); + } + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + this.currentBlendMode = 99999; + + var shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = this.defaultShader.fragmentSrc; + shader.uniforms = {}; + shader.init(); + + this.defaultShader.shaders[gl.id] = shader; +}; + +/** + * @method PIXI.WebGLSpriteBatch#begin + * @param renderSession {Object} The RenderSession object + */ +PIXI.WebGLSpriteBatch.prototype.begin = function (renderSession) { + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.defaultShader; + + this.start(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#end + */ +PIXI.WebGLSpriteBatch.prototype.end = function () { + this.flush(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#render + * @param sprite {Sprite} the sprite to render when using this spritebatch + * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. + */ +PIXI.WebGLSpriteBatch.prototype.render = function (sprite, matrix) { + var texture = sprite.texture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + if (PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + baseTexture.textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] = baseTexture; + } + + // They provided an alternative rendering matrix, so use it + var wt = sprite.worldTransform; + + if (matrix) { + wt = matrix; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // get the uvs for the texture + var uvs = texture._uvs; + + // if the uvs have not updated then no point rendering just yet! + if (!uvs) { + return; + } + + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + + var w0, w1, h0, h1; + + if (texture.trim) { + // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords. + var trim = texture.trim; + + w1 = trim.x - aX * trim.width; + w0 = w1 + texture.crop.width; + + h1 = trim.y - aY * trim.height; + h0 = h1 + texture.crop.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 i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + var tiOffset = this.currentBatchSize * 4; + var resolution = texture.baseTexture.resolution; + var textureIndex = texture.baseTexture.textureIndex; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + + var cw = texture.crop.width; + var ch = texture.crop.height; + + if (texture.rotated) + { + var a0 = wt.a; + var b0 = wt.b; + var c0 = wt.c; + var d0 = wt.d; + var _w1 = w1; + var _w0 = w0; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + a = a0 * 6.123233995736766e-17 + -c0; + b = b0 * 6.123233995736766e-17 + -d0; + c = a0 + c0 * 6.123233995736766e-17; + d = b0 + d0 * 6.123233995736766e-17; + + // Update UV coordinates + texture._updateUvsInverted(); + + // Rotate dimensions + w0 = h0; + w1 = h1; + h0 = _w0; + h1 = _w1; + } + + var colors = this.colors; + var positions = this.positions; + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + if (this.renderSession.roundPixels) { + positions[i++] = a * w1 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w1 + ty | 0; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w0 + ty | 0; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w0 + ty | 0; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w1 + ty | 0; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } else { + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx; + positions[i++] = d * h1 + b * w0 + ty; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders a TilingSprite using the spriteBatch. + * + * @method PIXI.WebGLSpriteBatch#renderTilingSprite + * @param sprite {TilingSprite} the sprite to render + */ +PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function (sprite) { + var texture = sprite.tilingTexture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + var textureIndex = sprite.texture.baseTexture.textureIndex; + if (PIXI.WebGLRenderer.textureArray[textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[textureIndex] = baseTexture; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // set the textures uvs temporarily + if (!sprite._uvs) { + sprite._uvs = new PIXI.TextureUvs(); + } + + var uvs = sprite._uvs; + + var w = texture.baseTexture.width; + var h = texture.baseTexture.height; + + // var w = sprite._frame.sourceSizeW; + // var h = sprite._frame.sourceSizeH; + + // w = 16; + // h = 16; + + sprite.tilePosition.x %= w * sprite.tileScaleOffset.x; + sprite.tilePosition.y %= h * sprite.tileScaleOffset.y; + + var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x); + var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y); + + var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x); + var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.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; + + // Get the sprites current alpha and tint and combine them into a single color + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + var positions = this.positions; + var colors = this.colors; + + var width = sprite.width; + var height = sprite.height; + + // TODO trim?? + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + var w0 = width * (1 - aX); + var w1 = width * -aX; + + var h0 = height * (1 - aY); + var h1 = height * -aY; + + var i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + + var resolution = texture.baseTexture.resolution; + + var wt = sprite.worldTransform; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + // xy + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + // uv + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = (a * w0 + c * h1 + tx); + positions[i++] = d * h1 + b * w0 + ty; + // uv + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + // uv + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + // uv + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders the content and empties the current batch. + * + * @method PIXI.WebGLSpriteBatch#flush + */ +PIXI.WebGLSpriteBatch.prototype.flush = function () { + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize === 0) { + return; + } + + var gl = this.gl; + var shader; + + if (this.dirty) { + this.dirty = false; + + shader = this.defaultShader.shaders[gl.id]; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + // this is the same for each shader? + var stride = this.vertexSize; //this.vertSize * 4; + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 8); + + // color attributes will be interpreted as unsigned bytes and normalized + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 16); + + // Texture index + gl.vertexAttribPointer(shader.aTextureIndex, 1, gl.FLOAT, false, stride, 20); + } + + // upload the verts to the buffer + if (this.currentBatchSize > (this.size * 0.5)) { + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + } else { + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + var view = this.positions.subarray(0, this.currentBatchSize * this.vertexSize); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); + } + + var nextTexture, nextBlendMode, nextShader; + var batchSize = 0; + var start = 0; + + var currentBaseTexture = null; + var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode; + var currentShader = null; + + var blendSwap = false; + var shaderSwap = false; + var sprite; + var textureIndex = 0; + + for (var i = 0, j = this.currentBatchSize; i < j; i++) { + + sprite = this.sprites[i]; + + if (sprite.tilingTexture) { + nextTexture = sprite.tilingTexture.baseTexture; + } else { + nextTexture = sprite.texture.baseTexture; + } + + nextBlendMode = sprite.blendMode; + nextShader = sprite.shader || this.defaultShader; + + blendSwap = currentBlendMode !== nextBlendMode; + shaderSwap = currentShader !== nextShader; // should I use _UIDS??? + + var skip = nextTexture.skipRender; + + if (skip && sprite.children.length > 0) { + skip = false; + } + // + if (/*(currentBaseTexture != nextTexture && !skip) ||*/ + blendSwap || + shaderSwap) { + this.renderBatch(currentBaseTexture, batchSize, start); + + start = i; + batchSize = 0; + currentBaseTexture = nextTexture; + + if (blendSwap) { + currentBlendMode = nextBlendMode; + this.renderSession.blendModeManager.setBlendMode(currentBlendMode); + } + + if (shaderSwap) { + currentShader = nextShader; + + shader = currentShader.shaders[gl.id]; + + if (!shader) { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = currentShader.fragmentSrc; + shader.uniforms = currentShader.uniforms; + shader.init(); + + currentShader.shaders[gl.id] = shader; + } + + // set shader function??? + this.renderSession.shaderManager.setShader(shader); + + if (shader.dirty) { + shader.syncUniforms(); + } + + // both these only need to be set if they are changing.. + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(shader.projectionVector, projection.x, projection.y); + + // TODO - this is temporary! + var offsetVector = this.renderSession.offset; + gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y); + + // set the pointers + } + } + + batchSize++; + } + + this.renderBatch(currentBaseTexture, batchSize, start); + + // then reset the batch! + this.currentBatchSize = 0; +}; + +/** + * @method PIXI.WebGLSpriteBatch#renderBatch + * @param texture {Texture} + * @param size {Number} + * @param startIndex {Number} + */ +PIXI.WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { + if (size === 0) { + return; + } + + var gl = this.gl; + + // check if a texture is dirty.. + if (texture._dirty[gl.id]) { + if (!this.renderSession.renderer.updateTexture(texture)) { + // If updateTexture returns false then we cannot render it, so bail out now + return; + } + }else { + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + } + + gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2); + // increment the draw count + this.renderSession.drawCount++; +}; + +/** + * @method PIXI.WebGLSpriteBatch#stop + */ +PIXI.WebGLSpriteBatch.prototype.stop = function () { + this.flush(); + this.dirty = true; +}; + +/** + * @method PIXI.WebGLSpriteBatch#start + */ +PIXI.WebGLSpriteBatch.prototype.start = function () { + this.dirty = true; +}; + +/** + * Destroys the SpriteBatch. + * + * @method PIXI.WebGLSpriteBatch#destroy + */ +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; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** +* @class PIXI.WebGLFastSpriteBatch +* @constructor +*/ +PIXI.WebGLFastSpriteBatch = function(gl) +{ + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 11; + + /** + * @property maxSize + * @type Number + */ + this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize; + + /** + * @property size + * @type Number + */ + this.size = this.maxSize; + + //the total number of floats in our batch + var numVerts = this.size * 4 * this.vertSize; + + //the total number of indices in our batch + var numIndices = this.maxSize * 6; + + /** + * Vertex data + * @property vertices + * @type Float32Array + */ + this.vertices = new Float32Array(numVerts); + + /** + * Index data + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property vertexBuffer + * @type Object + */ + this.vertexBuffer = null; + + /** + * @property indexBuffer + * @type Object + */ + this.indexBuffer = null; + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i=0, j=0; i < numIndices; i += 6, j += 4) + { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 0; + + /** + * @property renderSession + * @type Object + */ + this.renderSession = null; + + /** + * @property shader + * @type Object + */ + this.shader = null; + + /** + * @property matrix + * @type Matrix + */ + this.matrix = null; + + this.setContext(gl); +}; + +PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLFastSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl) +{ + this.gl = gl; + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#begin + * @param spriteBatch {WebGLSpriteBatch} + * @param renderSession {Object} + */ +PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession) +{ + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.fastShader; + + this.matrix = spriteBatch.worldTransform.toArray(true); + + this.start(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#end + */ +PIXI.WebGLFastSpriteBatch.prototype.end = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#render + * @param spriteBatch {WebGLSpriteBatch} + */ +PIXI.WebGLFastSpriteBatch.prototype.render = function (spriteBatch) +{ + var children = spriteBatch.children; + var sprite = children[0]; + + // if the uvs have not updated then no point rendering just yet! + + // check texture. + if(!sprite.texture._uvs)return; + + this.currentBaseTexture = sprite.texture.baseTexture; + + // check blend mode + if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode) + { + this.flush(); + this.renderSession.blendModeManager.setBlendMode(sprite.blendMode); + } + + for(var i=0,j= children.length; i= this.size) + { + this.flush(); + } +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#flush + */ +PIXI.WebGLFastSpriteBatch.prototype.flush = function() +{ + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize===0)return; + + var gl = this.gl; + + // bind the current texture + + if(!this.currentBaseTexture._glTextures[gl.id]) { + this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl); + return; + } + + //gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); + + // upload the verts to the buffer + + if(this.currentBatchSize > ( this.size * 0.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); + } + + // now draw those suckas! + gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0); + + // then reset the batch! + this.currentBatchSize = 0; + + // increment the draw count + this.renderSession.drawCount++; + +}; + + +/** + * @method PIXI.WebGLFastSpriteBatch#stop + */ +PIXI.WebGLFastSpriteBatch.prototype.stop = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#start + */ +PIXI.WebGLFastSpriteBatch.prototype.start = function() +{ + var gl = this.gl; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(this.shader.projectionVector, projection.x, projection.y); + + // set the matrix + gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix); + + // set the pointers + 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); + gl.vertexAttribPointer(this.shader.aTextureIndex, 1, gl.FLOAT, false, stride, 10 * 4); + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLFilterManager +* @constructor +*/ +PIXI.WebGLFilterManager = function() +{ + /** + * @property filterStack + * @type Array + */ + this.filterStack = []; + + /** + * @property offsetX + * @type Number + */ + this.offsetX = 0; + + /** + * @property offsetY + * @type Number + */ + this.offsetY = 0; +}; + +PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLFilterManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLFilterManager.prototype.setContext = function(gl) +{ + this.gl = gl; + this.texturePool = []; + + this.initShaderBuffers(); +}; + +/** +* @method PIXI.WebGLFilterManager#begin +* @param renderSession {RenderSession} +* @param buffer {ArrayBuffer} +*/ +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; +}; + +/** +* Applies the filter and adds it to the current filter stack. +* +* @method PIXI.WebGLFilterManager#pushFilter +* @param filterBlock {Object} the filter that will be pushed to the current filter stack +*/ +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(); + + // >>> modify by nextht + filterBlock._previous_stencil_mgr = this.renderSession.stencilManager; + this.renderSession.stencilManager = new PIXI.WebGLStencilManager(); + this.renderSession.stencilManager.setContext(gl); + gl.disable(gl.STENCIL_TEST); + // <<< modify by nextht + + // filter program + // OPTIMISATION - the first filter is free if its a simple color change? + 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.renderSession.resolution, this.height * this.renderSession.resolution); + } + else + { + texture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + } + + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea; + + var padding = filter.padding; + filterArea.x -= padding; + filterArea.y -= padding; + filterArea.width += padding * 2; + filterArea.height += padding * 2; + + // cap filter to screen size.. + 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer); + + // set view port + gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + projection.x = filterArea.width/2; + projection.y = -filterArea.height/2; + + offset.x = -filterArea.x; + offset.y = -filterArea.y; + + // update projection + // now restore the regular shader.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + //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; + +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLFilterManager#popFilter +*/ +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 * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + 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); + // now set the uvs.. + 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.renderSession.resolution, this.height * this.renderSession.resolution); + outputTexture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + + // need to clear this FBO as it may have some left over elements from a previous filter. + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + gl.clear(gl.COLOR_BUFFER_BIT); + + gl.disable(gl.BLEND); + + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { + var filterPass = filterBlock.filterPasses[i]; + + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture); + + // draw texture.. + //filterPass.applyFilterPass(filterArea.width, filterArea.height); + this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height); + + // swap the textures.. + var temp = inputTexture; + inputTexture = outputTexture; + outputTexture = temp; + } + + gl.enable(gl.BLEND); + + texture = inputTexture; + this.texturePool.push(outputTexture); + } + + var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1]; + + this.offsetX -= filterArea.x; + this.offsetY -= filterArea.y; + + var sizeX = this.width; + var sizeY = this.height; + + var offsetX = 0; + var offsetY = 0; + + var buffer = this.buffer; + + // time to render the filters texture to the previous scene + if(this.filterStack.length === 0) + { + gl.colorMask(true, true, true, true);//this.transparent); + } + else + { + var currentFilter = this.filterStack[this.filterStack.length-1]; + filterArea = currentFilter._filterArea; + + sizeX = filterArea.width; + sizeY = filterArea.height; + + offsetX = filterArea.x; + offsetY = filterArea.y; + + buffer = currentFilter._glFilterTexture.frameBuffer; + } + + // TODO need to remove these global elements.. + projection.x = sizeX/2; + projection.y = -sizeY/2; + + offset.x = offsetX; + offset.y = offsetY; + + filterArea = filterBlock._filterArea; + + var x = filterArea.x-offsetX; + var y = filterArea.y-offsetY; + + // update the buffers.. + // make sure to flip the y! + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + + this.vertexArray[0] = x; + this.vertexArray[1] = y + filterArea.height; + + this.vertexArray[2] = x + filterArea.width; + this.vertexArray[3] = y + filterArea.height; + + this.vertexArray[4] = x; + this.vertexArray[5] = y; + + this.vertexArray[6] = x + filterArea.width; + this.vertexArray[7] = y; + + 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); + + gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution); + + // bind the buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, buffer ); + + // set the blend mode! + //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + // >>> modify by nextht + if (this.renderSession.stencilManager) { + this.renderSession.stencilManager.destroy(); + } + this.renderSession.stencilManager = filterBlock._previous_stencil_mgr; + filterBlock._previous_stencil_mgr = null; + if (this.renderSession.stencilManager.count > 0) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + // <<< modify by nextht + + // apply! + this.applyFilterPass(filter, filterArea, sizeX, sizeY); + + // now restore the regular shader.. should happen automatically now.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2); + // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY); + + // return the texture to the pool + this.texturePool.push(texture); + filterBlock._glFilterTexture = null; +}; + + +/** +* Applies the filter to the specified area. +* +* @method PIXI.WebGLFilterManager#applyFilterPass +* @param filter {Phaser.Filter} the filter that needs to be applied +* @param filterArea {Texture} TODO - might need an update +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +*/ +PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height) +{ + // use program + var gl = this.gl; + var shader = filter.shaders[gl.id]; + + if(!shader) + { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = filter.fragmentSrc; + shader.uniforms = filter.uniforms; + shader.init(true); + + filter.shaders[gl.id] = shader; + } + + // set the shader + this.renderSession.shaderManager.setShader(shader); + +// gl.useProgram(shader.program); + + gl.uniform2f(shader.projectionVector, width/2, -height/2); + gl.uniform2f(shader.offsetVector, 0,0); + + if(filter.uniforms.dimensions) + { + filter.uniforms.dimensions.value[0] = this.width;//width; + filter.uniforms.dimensions.value[1] = this.height;//height; + filter.uniforms.dimensions.value[2] = this.vertexArray[0]; + filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height; + } + + shader.syncUniforms(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // draw the filter... + gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + + this.renderSession.drawCount++; +}; + +/** +* Initialises the shader buffers. +* +* @method PIXI.WebGLFilterManager#initShaderBuffers +*/ +PIXI.WebGLFilterManager.prototype.initShaderBuffers = function() +{ + var gl = this.gl; + + // create some buffers + this.vertexBuffer = gl.createBuffer(); + this.uvBuffer = gl.createBuffer(); + this.colorBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // bind and upload the vertexs.. + // keep a reference to the vertexFloatData.. + this.vertexArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW); + + // bind and upload the uv buffer + this.uvArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW); + + this.colorArray = new Float32Array([1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW); + + // bind and upload the index + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW); + +}; + +/** +* Destroys the filter and removes it from the filter stack. +* +* @method PIXI.WebGLFilterManager#destroy +*/ +PIXI.WebGLFilterManager.prototype.destroy = function() +{ + var gl = this.gl; + + this.filterStack = null; + + this.offsetX = 0; + this.offsetY = 0; + + // destroy textures + for (var i = 0; i < this.texturePool.length; i++) { + this.texturePool[i].destroy(); + } + + this.texturePool = null; + + //destroy buffers.. + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.uvBuffer); + gl.deleteBuffer(this.colorBuffer); + gl.deleteBuffer(this.indexBuffer); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @private + */ +function _CreateEmptyTexture(gl, width, height, scaleMode) { + var texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + return texture; +} + +/** + * @private + */ +var _fbErrors = { + 36054: 'Incomplete attachment', + 36055: 'Missing attachment', + 36057: 'Incomplete dimensions', + 36061: 'Framebuffer unsupported' +}; + +/** + * @private + */ +function _CreateFramebuffer(gl, width, height, scaleMode, textureUnit) { + var framebuffer = gl.createFramebuffer(); + var depthStencilBuffer = gl.createRenderbuffer(); + var colorBuffer = null; + var fbStatus = 0; + + gl.activeTexture(gl.TEXTURE0 + textureUnit); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer); + colorBuffer = _CreateEmptyTexture(gl, width, height, scaleMode); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorBuffer, 0); + fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + if(fbStatus !== gl.FRAMEBUFFER_COMPLETE) { + console.error('Incomplete GL framebuffer. ', _fbErrors[fbStatus]); + } + framebuffer.width = width; + framebuffer.height = height; + framebuffer.targetTexture = colorBuffer; + framebuffer.renderBuffer = depthStencilBuffer; + return framebuffer; +} + +/** +* @class PIXI.FilterTexture +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +* @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values +*/ +PIXI.FilterTexture = function(gl, width, height, scaleMode, textureUnit) +{ + textureUnit = typeof textureUnit === 'number' ? textureUnit : 0; + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + // next time to create a frame buffer and texture + + /** + * @property frameBuffer + * @type Any + */ + this.frameBuffer = _CreateFramebuffer(gl, width, height, scaleMode || PIXI.scaleModes.DEFAULT, textureUnit); + /** + * @property texture + * @type Any + */ + this.texture = this.frameBuffer.targetTexture; + this.width = width; + this.height = height; + this.renderBuffer = this.frameBuffer.renderBuffer; +}; + +PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture; + +/** +* Clears the filter texture. +* +* @method PIXI.FilterTexture#clear +*/ +PIXI.FilterTexture.prototype.clear = function() +{ + var gl = this.gl; + + gl.clearColor(0,0,0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Resizes the texture to the specified width and height + * + * @method PIXI.FilterTexture#resize + * @param width {Number} the new width of the texture + * @param height {Number} the new height of the texture + */ +PIXI.FilterTexture.prototype.resize = function(width, height) +{ + if(this.width === width && this.height === height) return; + + this.width = width; + this.height = height; + + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height ); +}; + +/** +* Destroys the filter texture. +* +* @method PIXI.FilterTexture#destroy +*/ +PIXI.FilterTexture.prototype.destroy = function() +{ + var gl = this.gl; + gl.deleteFramebuffer( this.frameBuffer ); + gl.deleteTexture( this.texture ); + + this.frameBuffer = null; + this.texture = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Creates a Canvas element of the given size. + * + * @class PIXI.CanvasBuffer + * @constructor + * @param width {Number} the width for the newly created canvas + * @param height {Number} the height for the newly created canvas + */ +PIXI.CanvasBuffer = function(width, height) +{ + /** + * The width of the Canvas in pixels. + * + * @property width + * @type Number + */ + this.width = width; + + /** + * The height of the Canvas in pixels. + * + * @property height + * @type Number + */ + this.height = height; + + /** + * The Canvas object that belongs to this CanvasBuffer. + * + * @property canvas + * @type HTMLCanvasElement + */ + this.canvas = Phaser.CanvasPool.create(this, this.width, this.height); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.canvas.getContext("2d"); + + this.canvas.width = width; + this.canvas.height = height; +}; + +PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer; + +/** + * Clears the canvas that was created by the CanvasBuffer class. + * + * @method PIXI.CanvasBuffer#clear + * @private + */ +PIXI.CanvasBuffer.prototype.clear = function() +{ + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0,0, this.width, this.height); +}; + +/** + * Resizes the canvas to the specified width and height. + * + * @method PIXI.CanvasBuffer#resize + * @param width {Number} the new width of the canvas + * @param height {Number} the new height of the canvas + */ +PIXI.CanvasBuffer.prototype.resize = function(width, height) +{ + this.width = this.canvas.width = width; + this.height = this.canvas.height = height; +}; + +/** + * Frees the canvas up for use again. + * + * @method PIXI.CanvasBuffer#destroy + */ +PIXI.CanvasBuffer.prototype.destroy = function() +{ + Phaser.CanvasPool.remove(this); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used to handle masking. + * + * @class PIXI.CanvasMaskManager + * @constructor + */ +PIXI.CanvasMaskManager = function() +{ +}; + +PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; + +/** + * This method adds it to the current stack of masks. + * + * @method PIXI.CanvasMaskManager#pushMask + * @param maskData {Object} the maskData that will be pushed + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) { + + var context = renderSession.context; + + context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.worldTransform; + + var resolution = renderSession.resolution; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution); + + PIXI.CanvasGraphics.renderGraphicsMask(maskData, context); + + context.clip(); + + maskData.worldAlpha = cacheAlpha; +}; + +/** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @method PIXI.CanvasMaskManager#popMask + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.popMask = function(renderSession) +{ + renderSession.context.restore(); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class PIXI.CanvasTinter + * @static + */ +PIXI.CanvasTinter = function() {}; + +/** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @method PIXI.CanvasTinter#getTintedTexture + * @static + * @param sprite {Sprite} the sprite to tint + * @param color {Number} the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ +PIXI.CanvasTinter.getTintedTexture = function(sprite, color) +{ + var canvas = sprite.tintedTexture || Phaser.CanvasPool.create(this); + + PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas); + + return canvas; +}; + +/** + * Tint a texture using the "multiply" operation. + * + * @method PIXI.CanvasTinter#tintWithMultiply + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.clearRect(0, 0, w, h); + + context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, w, h); + + context.globalCompositeOperation = "multiply"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + context.globalCompositeOperation = "destination-atop"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + +}; + +/** + * Tint a texture pixel per pixel. + * + * @method PIXI.CanvasTinter#tintPerPixel + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.globalCompositeOperation = "copy"; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + var rgbValues = Phaser.Color.hexToRGBArray(color); + var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, w, h); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) + { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + + if (!PIXI.CanvasTinter.canHandleAlpha) + { + var alpha = pixels[i + 3]; + + pixels[i + 0] /= 255 / alpha; + pixels[i + 1] /= 255 / alpha; + pixels[i + 2] /= 255 / alpha; + } + } + + context.putImageData(pixelData, 0, 0); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class PIXI.CanvasRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.CanvasRenderer = function (game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + /** + * The renderer type. + * + * @property type + * @type Number + */ + this.type = Phaser.CANVAS; + + /** + * The resolution of the canvas. + * + * @property resolution + * @type Number + */ + this.resolution = game.resolution; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. + * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame. + * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The width of the canvas view + * + * @property width + * @type Number + * @default 800 + */ + this.width = game.width * this.resolution; + + /** + * The height of the canvas view + * + * @property height + * @type Number + * @default 600 + */ + this.height = game.height * this.resolution; + + /** + * The canvas element that everything is drawn to. + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * The canvas 2d context that everything is drawn with + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.view.getContext("2d", { alpha: this.transparent } ); + + /** + * Boolean flag controlling canvas refresh. + * + * @property refresh + * @type Boolean + */ + this.refresh = true; + + /** + * Internal var. + * + * @property count + * @type Number + */ + this.count = 0; + + /** + * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer + * @property CanvasMaskManager + * @type CanvasMaskManager + */ + this.maskManager = new PIXI.CanvasMaskManager(); + + /** + * The render session is just a bunch of parameter used for rendering + * @property renderSession + * @type Object + */ + this.renderSession = { + context: this.context, + maskManager: this.maskManager, + scaleMode: null, + smoothProperty: Phaser.Canvas.getSmoothingPrefix(this.context), + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + */ + roundPixels: config.roundPixels || false + }; + + this.mapBlendModes(); + + this.resize(this.width, this.height); + +}; + +// constructor +PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer; + +/** + * Renders the DisplayObjectContainer, usually the Phaser.Stage, to this canvas view. + * + * @method PIXI.CanvasRenderer#render + * @param root {Phaser.Stage|PIXI.DisplayObjectContainer} The root element to be rendered. + */ +PIXI.CanvasRenderer.prototype.render = function (root) { + + this.context.setTransform(1, 0, 0, 1, 0, 0); + + this.context.globalAlpha = 1; + + this.renderSession.currentBlendMode = 0; + this.renderSession.shakeX = this.game.camera._shake.x; + this.renderSession.shakeY = this.game.camera._shake.y; + + this.context.globalCompositeOperation = 'source-over'; + + if (navigator.isCocoonJS && this.view.screencanvas) + { + this.context.fillStyle = "black"; + this.context.clear(); + } + + if (this.clearBeforeRender) + { + if (this.transparent) + { + this.context.clearRect(0, 0, this.width, this.height); + } + else if (root._bgColor) + { + this.context.fillStyle = root._bgColor.rgba; + this.context.fillRect(0, 0, this.width , this.height); + } + } + + this.renderDisplayObject(root); + +}; + +PIXI.CanvasRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + // Does nothing on Canvas, but here to allow you to simply set + // `game.renderer.setTexturePriority()` without having to worry about + // running in WebGL or not. + +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @method PIXI.CanvasRenderer#destroy + * @param [removeView=true] {boolean} Removes the Canvas element from the DOM. + */ +PIXI.CanvasRenderer.prototype.destroy = function (removeView) { + + if (removeView === undefined) { removeView = true; } + + if (removeView && this.view.parent) + { + this.view.parent.removeChild(this.view); + } + + this.view = null; + this.context = null; + this.maskManager = null; + this.renderSession = null; + +}; + +/** + * Resizes the canvas view to the specified width and height + * + * @method PIXI.CanvasRenderer#resize + * @param width {Number} the new width of the canvas view + * @param height {Number} the new height of the canvas view + */ +PIXI.CanvasRenderer.prototype.resize = function (width, height) { + + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) + { + this.view.style.width = this.width / this.resolution + "px"; + this.view.style.height = this.height / this.resolution + "px"; + } + + if (this.renderSession.smoothProperty) + { + this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + +}; + +/** + * Renders a display object + * + * @method PIXI.CanvasRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The displayObject to render + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. + * @private + */ +PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) { + + this.renderSession.context = context || this.context; + this.renderSession.resolution = this.resolution; + displayObject._renderCanvas(this.renderSession, matrix); + +}; + +/** + * Maps Pixi blend modes to canvas blend modes. + * + * @method PIXI.CanvasRenderer#mapBlendModes + * @private + */ +PIXI.CanvasRenderer.prototype.mapBlendModes = function () { + + if (!PIXI.blendModesCanvas) + { + var b = []; + var modes = PIXI.blendModes; + var useNew = this.game.device.canUseMultiply; + + b[modes.NORMAL] = 'source-over'; + b[modes.ADD] = 'lighter'; + b[modes.MULTIPLY] = (useNew) ? 'multiply' : 'source-over'; + b[modes.SCREEN] = (useNew) ? 'screen' : 'source-over'; + b[modes.OVERLAY] = (useNew) ? 'overlay' : 'source-over'; + b[modes.DARKEN] = (useNew) ? 'darken' : 'source-over'; + b[modes.LIGHTEN] = (useNew) ? 'lighten' : 'source-over'; + b[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : 'source-over'; + b[modes.COLOR_BURN] = (useNew) ? 'color-burn' : 'source-over'; + b[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : 'source-over'; + b[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : 'source-over'; + b[modes.DIFFERENCE] = (useNew) ? 'difference' : 'source-over'; + b[modes.EXCLUSION] = (useNew) ? 'exclusion' : 'source-over'; + b[modes.HUE] = (useNew) ? 'hue' : 'source-over'; + b[modes.SATURATION] = (useNew) ? 'saturation' : 'source-over'; + b[modes.COLOR] = (useNew) ? 'color' : 'source-over'; + b[modes.LUMINOSITY] = (useNew) ? 'luminosity' : 'source-over'; + + PIXI.blendModesCanvas = b; + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class PIXI.BaseTexture + * @constructor + * @param source {String|Canvas} the source object (image or canvas) + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + */ +PIXI.BaseTexture = function(source, scaleMode, resolution) +{ + /** + * The Resolution of the texture. + * + * @property resolution + * @type Number + */ + this.resolution = resolution || 1; + + /** + * [read-only] The width of the base texture set when the image has loaded + * + * @property width + * @type Number + * @readOnly + */ + this.width = 100; + + /** + * [read-only] The height of the base texture set when the image has loaded + * + * @property height + * @type Number + * @readOnly + */ + this.height = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @property scaleMode + * @type {Number} + * @default PIXI.scaleModes.LINEAR + */ + this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT; + + /** + * [read-only] Set to true once the base texture has loaded + * + * @property hasLoaded + * @type Boolean + * @readOnly + */ + this.hasLoaded = false; + + /** + * The image source that is used to create the texture. + * + * @property source + * @type Image + */ + this.source = source; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * + * @property premultipliedAlpha + * @type Boolean + * @default true + */ + this.premultipliedAlpha = true; + + // used for webGL + + /** + * @property _glTextures + * @type Array + * @private + */ + this._glTextures = []; + + /** + * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @property mipmap + * @type {Boolean} + */ + this.mipmap = false; + + /** + * The multi texture batching index number. + * @property textureIndex + * @type Number + */ + this.textureIndex = 0; + + /** + * @property _dirty + * @type Array + * @private + */ + this._dirty = [true, true, true, true]; + + if (!source) + { + return; + } + + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { + this.hasLoaded = true; + this.width = this.source.naturalWidth || this.source.width; + this.height = this.source.naturalHeight || this.source.height; + this.dirty(); + } + + /** + * A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch. + * + * You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture) + * that has children that you do want to render, without causing a batch flush in the process. + * + * @property skipRender + * @type Boolean + */ + this.skipRender = false; + + /** + * @property _powerOf2 + * @type Boolean + * @private + */ + this._powerOf2 = false; + +}; + +PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture; + +/** + * Forces this BaseTexture to be set as loaded, with the given width and height. + * Then calls BaseTexture.dirty. + * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have. + * + * @method PIXI.BaseTexture#forceLoaded + * @param {number} width - The new width to force the BaseTexture to be. + * @param {number} height - The new height to force the BaseTexture to be. + */ +PIXI.BaseTexture.prototype.forceLoaded = function(width, height) +{ + this.hasLoaded = true; + this.width = width; + this.height = height; + this.dirty(); +}; + +/** + * Destroys this base texture + * + * @method PIXI.BaseTexture#destroy + */ +PIXI.BaseTexture.prototype.destroy = function() +{ + if (this.source) + { + Phaser.CanvasPool.removeByCanvas(this.source); + } + + this.source = null; + + this.unloadFromGPU(); +}; + +/** + * Sets all glTextures to be dirty. + * + * @method PIXI.BaseTexture#dirty + */ +PIXI.BaseTexture.prototype.dirty = function() +{ + for (var i = 0; i < this._glTextures.length; i++) + { + this._dirty[i] = true; + } +}; + +/** + * Removes the base texture from the GPU, useful for managing resources on the GPU. + * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it. + * + * @method PIXI.BaseTexture#unloadFromGPU + */ +PIXI.BaseTexture.prototype.unloadFromGPU = function() +{ + this.dirty(); + + // delete the webGL textures if any. + for (var i = this._glTextures.length - 1; i >= 0; i--) + { + var glTexture = this._glTextures[i]; + var gl = PIXI.glContexts[i]; + + if(gl && glTexture) + { + gl.deleteTexture(glTexture); + } + + } + + this._glTextures.length = 0; + + this.dirty(); +}; + +/** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @method PIXI.BaseTexture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + * @return {BaseTexture} + */ +PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode, resolution) +{ + if (canvas.width === 0) + { + canvas.width = 1; + } + + if (canvas.height === 0) + { + canvas.height = 1; + } + + resolution = resolution || 1; + + return new PIXI.BaseTexture(canvas, scaleMode, resolution); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * TextureSilentFail is a boolean that defaults to `false`. + * If `true` then {@link PIXI.Texture#setFrame} will no longer throw an error if the texture dimensions are incorrect. + * Instead {@link PIXI.Texture#valid} will be set to `false` (#1556) + * + * @type {boolean} + */ +PIXI.TextureSilentFail = false; + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used. + * + * @class PIXI.Texture + * @constructor + * @param baseTexture {BaseTexture} The base texture source to create the texture from + * @param frame {Rectangle} The rectangle frame of the texture to show + * @param [crop] {Rectangle} The area of original texture + * @param [trim] {Rectangle} Trimmed texture rectangle + */ +PIXI.Texture = function(baseTexture, frame, crop, trim) +{ + /** + * Does this Texture have any frame data assigned to it? + * + * @property noFrame + * @type Boolean + */ + this.noFrame = false; + + if (!frame) + { + this.noFrame = true; + frame = new PIXI.Rectangle(0,0,1,1); + } + + if (baseTexture instanceof PIXI.Texture) + { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = baseTexture; + + /** + * The frame specifies the region of the base texture that this texture uses + * + * @property frame + * @type Rectangle + */ + this.frame = frame; + + /** + * The texture trim data. + * + * @property trim + * @type Rectangle + */ + this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @property valid + * @type Boolean + */ + this.valid = false; + + /** + * Is this a tiling texture? As used by the likes of a TilingSprite. + * + * @property isTiling + * @type Boolean + */ + this.isTiling = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @property requiresUpdate + * @type Boolean + */ + this.requiresUpdate = false; + + /** + * This will let a renderer know that a tinted parent has updated its texture. + * + * @property requiresReTint + * @type Boolean + */ + this.requiresReTint = false; + + /** + * The WebGL UV data cache. + * + * @property _uvs + * @type Object + * @private + */ + this._uvs = null; + + /** + * The width of the Texture in pixels. + * + * @property width + * @type Number + */ + this.width = 0; + + /** + * The height of the Texture in pixels. + * + * @property height + * @type Number + */ + this.height = 0; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @property crop + * @type Rectangle + */ + this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1); + + /** + * A flag that controls if this frame is rotated or not. + * Rotation allows you to use rotated frames in texture atlas packing, it has nothing to do with + * Sprite rotation. + * + * @property rotated + * @type Boolean + */ + this.rotated = false; + + if (baseTexture.hasLoaded) + { + if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + this.setFrame(frame); + } + +}; + +PIXI.Texture.prototype.constructor = PIXI.Texture; + +/** + * Called when the base texture is loaded + * + * @method PIXI.Texture#onBaseTextureLoaded + * @private + */ +PIXI.Texture.prototype.onBaseTextureLoaded = function() +{ + var baseTexture = this.baseTexture; + + if (this.noFrame) + { + this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } + + this.setFrame(this.frame); +}; + +/** + * Destroys this texture + * + * @method PIXI.Texture#destroy + * @param destroyBase {Boolean} Whether to destroy the base texture as well + */ +PIXI.Texture.prototype.destroy = function(destroyBase) +{ + if (destroyBase) this.baseTexture.destroy(); + + this.valid = false; +}; + +/** + * Specifies the region of the baseTexture that this texture will use. + * + * @method PIXI.Texture#setFrame + * @param frame {Rectangle} The frame of the texture to set it to + */ +PIXI.Texture.prototype.setFrame = function(frame) +{ + this.noFrame = false; + + this.frame = frame; + this.width = frame.width; + this.height = frame.height; + + this.crop.x = frame.x; + this.crop.y = frame.y; + this.crop.width = frame.width; + this.crop.height = frame.height; + + if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { + if (!PIXI.TextureSilentFail) + { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + this.valid = false; + return; + } + + this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + + if (this.trim) + { + this.width = this.trim.width; + this.height = this.trim.height; + this.frame.width = this.trim.width; + this.frame.height = this.trim.height; + } + + if (this.valid) this._updateUvs(); + +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvs + * @private + */ +PIXI.Texture.prototype._updateUvs = function() +{ + if(!this._uvs)this._uvs = new PIXI.TextureUvs(); + + var frame = this.crop; + 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; +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvsInverted + * @private + */ +PIXI.Texture.prototype._updateUvsInverted = function () { + + if (!this._uvs) { this._uvs = new PIXI.TextureUvs(); } + + var frame = this.crop; + 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.height) / tw; + this._uvs.y1 = frame.y / th; + + this._uvs.x2 = (frame.x + frame.height) / tw; + this._uvs.y2 = (frame.y + frame.width) / th; + + this._uvs.x3 = frame.x / tw; + this._uvs.y3 = (frame.y + frame.width) / th; + +}; + +/** + * Helper function that creates a new a Texture based on the given canvas element. + * + * @static + * @method PIXI.Texture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @return {Texture} + */ +PIXI.Texture.fromCanvas = function(canvas, scaleMode) +{ + var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode); + + return new PIXI.Texture(baseTexture); +}; + +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.y3 = 0; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = PIXI; + } + exports.PIXI = PIXI; + } else if (typeof define !== 'undefined' && define.amd) { + define('PIXI', (function() { return root.PIXI = PIXI; })() ); + } else { + root.PIXI = PIXI; + } + + return PIXI; +}).call(this); +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +(function(){ + + var root = this; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @namespace Phaser +*/ +var Phaser = Phaser || { // jshint ignore:line + + /** + * The Phaser version number. + * @constant Phaser.VERSION + * @type {string} + */ + VERSION: '2.10.0', + + /** + * An array of Phaser game instances. + * @constant Phaser.GAMES + * @type {array} + */ + GAMES: [], + + /** + * AUTO renderer - picks between WebGL or Canvas based on device. + * @constant Phaser.AUTO + * @type {integer} + */ + AUTO: 0, + + /** + * Canvas Renderer. + * @constant Phaser.CANVAS + * @type {integer} + */ + CANVAS: 1, + + /** + * WebGL Renderer. + * @constant Phaser.WEBGL + * @type {integer} + */ + WEBGL: 2, + + /** + * Headless renderer (not visual output) + * @constant Phaser.HEADLESS + * @type {integer} + */ + HEADLESS: 3, + + /** + * WebGL Renderer with MultiTexture support enabled. + * @constant Phaser.WEBGL_MULTI + * @type {integer} + */ + WEBGL_MULTI: 4, + + /** + * Direction constant. + * @constant Phaser.NONE + * @type {integer} + */ + NONE: 0, + + /** + * Direction constant. + * @constant Phaser.LEFT + * @type {integer} + */ + LEFT: 1, + + /** + * Direction constant. + * @constant Phaser.RIGHT + * @type {integer} + */ + RIGHT: 2, + + /** + * Direction constant. + * @constant Phaser.UP + * @type {integer} + */ + UP: 3, + + /** + * Direction constant. + * @constant Phaser.DOWN + * @type {integer} + */ + DOWN: 4, + + /** + * Game Object type. + * @constant Phaser.SPRITE + * @type {integer} + */ + SPRITE: 0, + + /** + * Game Object type. + * @constant Phaser.BUTTON + * @type {integer} + */ + BUTTON: 1, + + /** + * Game Object type. + * @constant Phaser.IMAGE + * @type {integer} + */ + IMAGE: 2, + + /** + * Game Object type. + * @constant Phaser.GRAPHICS + * @type {integer} + */ + GRAPHICS: 3, + + /** + * Game Object type. + * @constant Phaser.TEXT + * @type {integer} + */ + TEXT: 4, + + /** + * Game Object type. + * @constant Phaser.TILESPRITE + * @type {integer} + */ + TILESPRITE: 5, + + /** + * Game Object type. + * @constant Phaser.BITMAPTEXT + * @type {integer} + */ + BITMAPTEXT: 6, + + /** + * Game Object type. + * @constant Phaser.GROUP + * @type {integer} + */ + GROUP: 7, + + /** + * Game Object type. + * @constant Phaser.RENDERTEXTURE + * @type {integer} + */ + RENDERTEXTURE: 8, + + /** + * Game Object type. + * @constant Phaser.TILEMAP + * @type {integer} + */ + TILEMAP: 9, + + /** + * Game Object type. + * @constant Phaser.TILEMAPLAYER + * @type {integer} + */ + TILEMAPLAYER: 10, + + /** + * Game Object type. + * @constant Phaser.EMITTER + * @type {integer} + */ + EMITTER: 11, + + /** + * Game Object type. + * @constant Phaser.POLYGON + * @type {integer} + */ + POLYGON: 12, + + /** + * Game Object type. + * @constant Phaser.BITMAPDATA + * @type {integer} + */ + BITMAPDATA: 13, + + /** + * Game Object type. + * @constant Phaser.CANVAS_FILTER + * @type {integer} + */ + CANVAS_FILTER: 14, + + /** + * Game Object type. + * @constant Phaser.WEBGL_FILTER + * @type {integer} + */ + WEBGL_FILTER: 15, + + /** + * Game Object type. + * @constant Phaser.ELLIPSE + * @type {integer} + */ + ELLIPSE: 16, + + /** + * Game Object type. + * @constant Phaser.SPRITEBATCH + * @type {integer} + */ + SPRITEBATCH: 17, + + /** + * Game Object type. + * @constant Phaser.RETROFONT + * @type {integer} + */ + RETROFONT: 18, + + /** + * Game Object type. + * @constant Phaser.POINTER + * @type {integer} + */ + POINTER: 19, + + /** + * Game Object type. + * @constant Phaser.ROPE + * @type {integer} + */ + ROPE: 20, + + /** + * Game Object type. + * @constant Phaser.CIRCLE + * @type {integer} + */ + CIRCLE: 21, + + /** + * Game Object type. + * @constant Phaser.RECTANGLE + * @type {integer} + */ + RECTANGLE: 22, + + /** + * Game Object type. + * @constant Phaser.LINE + * @type {integer} + */ + LINE: 23, + + /** + * Game Object type. + * @constant Phaser.MATRIX + * @type {integer} + */ + MATRIX: 24, + + /** + * Game Object type. + * @constant Phaser.POINT + * @type {integer} + */ + POINT: 25, + + /** + * Game Object type. + * @constant Phaser.ROUNDEDRECTANGLE + * @type {integer} + */ + ROUNDEDRECTANGLE: 26, + + /** + * Game Object type. + * @constant Phaser.CREATURE + * @type {integer} + */ + CREATURE: 27, + + /** + * Game Object type. + * @constant Phaser.VIDEO + * @type {integer} + */ + VIDEO: 28, + + /** + * Game Object type. + * @constant Phaser.PENDING_ATLAS + * @type {integer} + */ + PENDING_ATLAS: -1, + + /** + * A horizontal orientation + * @constant Phaser.HORIZONTAL + * @type {integer} + */ + HORIZONTAL: 0, + + /** + * A vertical orientation + * @constant Phaser.VERTICAL + * @type {integer} + */ + VERTICAL: 1, + + /** + * A landscape orientation + * @constant Phaser.LANDSCAPE + * @type {integer} + */ + LANDSCAPE: 0, + + /** + * A portrait orientation + * @constant Phaser.PORTRAIT + * @type {integer} + */ + PORTRAIT: 1, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face up. + * @constant Phaser.ANGLE_UP + * @type {integer} + */ + ANGLE_UP: 270, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face down. + * @constant Phaser.ANGLE_DOWN + * @type {integer} + */ + ANGLE_DOWN: 90, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face left. + * @constant Phaser.ANGLE_LEFT + * @type {integer} + */ + ANGLE_LEFT: 180, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face right. + * @constant Phaser.ANGLE_RIGHT + * @type {integer} + */ + ANGLE_RIGHT: 0, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north east. + * @constant Phaser.ANGLE_NORTH_EAST + * @type {integer} + */ + ANGLE_NORTH_EAST: 315, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north west. + * @constant Phaser.ANGLE_NORTH_WEST + * @type {integer} + */ + ANGLE_NORTH_WEST: 225, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south east. + * @constant Phaser.ANGLE_SOUTH_EAST + * @type {integer} + */ + ANGLE_SOUTH_EAST: 45, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south west. + * @constant Phaser.ANGLE_SOUTH_WEST + * @type {integer} + */ + ANGLE_SOUTH_WEST: 135, + + /** + * A constant representing a top-left alignment or position. + * @constant Phaser.TOP_LEFT + * @type {integer} + */ + TOP_LEFT: 0, + + /** + * A constant representing a top-center alignment or position. + * @constant Phaser.TOP_CENTER + * @type {integer} + */ + TOP_CENTER: 1, + + /** + * A constant representing a top-right alignment or position. + * @constant Phaser.TOP_RIGHT + * @type {integer} + */ + TOP_RIGHT: 2, + + /** + * A constant representing a left-top alignment or position. + * @constant Phaser.Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_TOP: 3, + + /** + * A constant representing a left-center alignment or position. + * @constant Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_CENTER: 4, + + /** + * A constant representing a left-bottom alignment or position. + * @constant Phaser.LEFT_BOTTOM + * @type {integer} + */ + LEFT_BOTTOM: 5, + + /** + * A constant representing a center alignment or position. + * @constant Phaser.CENTER + * @type {integer} + */ + CENTER: 6, + + /** + * A constant representing a right-top alignment or position. + * @constant Phaser.RIGHT_TOP + * @type {integer} + */ + RIGHT_TOP: 7, + + /** + * A constant representing a right-center alignment or position. + * @constant Phaser.RIGHT_CENTER + * @type {integer} + */ + RIGHT_CENTER: 8, + + /** + * A constant representing a right-bottom alignment or position. + * @constant Phaser.RIGHT_BOTTOM + * @type {integer} + */ + RIGHT_BOTTOM: 9, + + /** + * A constant representing a bottom-left alignment or position. + * @constant Phaser.BOTTOM_LEFT + * @type {integer} + */ + BOTTOM_LEFT: 10, + + /** + * A constant representing a bottom-center alignment or position. + * @constant Phaser.BOTTOM_CENTER + * @type {integer} + */ + BOTTOM_CENTER: 11, + + /** + * A constant representing a bottom-right alignment or position. + * @constant Phaser.BOTTOM_RIGHT + * @type {integer} + */ + BOTTOM_RIGHT: 12, + + /** + * Various blend modes supported by Pixi. See the samples in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing Canvas Tutorial: Compositing}. + * + * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * + * @constant {Object} Phaser.blendModes + * @property {Number} blendModes.NORMAL - Draws new shapes on top of the existing content. This is the default setting. + * @property {Number} blendModes.ADD - Where both shapes overlap the color is determined by adding color values. + * @property {Number} blendModes.MULTIPLY - The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer, making a darker picture. + * @property {Number} blendModes.SCREEN - The pixels are inverted, multiplied, and inverted again, making a lighter picture. + * @property {Number} blendModes.OVERLAY + * @property {Number} blendModes.DARKEN + * @property {Number} blendModes.LIGHTEN + * @property {Number} blendModes.COLOR_DODGE + * @property {Number} blendModes.COLOR_BURN + * @property {Number} blendModes.HARD_LIGHT + * @property {Number} blendModes.SOFT_LIGHT + * @property {Number} blendModes.DIFFERENCE + * @property {Number} blendModes.EXCLUSION + * @property {Number} blendModes.HUE + * @property {Number} blendModes.SATURATION + * @property {Number} blendModes.COLOR + * @property {Number} blendModes.LUMINOSITY + * @static + */ + 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 + }, + + /** + * The scale modes that are supported by Pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @constant {Object} Phaser.scaleModes + * @property {Number} Phaser.scaleModes.DEFAULT=LINEAR + * @property {Number} Phaser.scaleModes.LINEAR Smooth scaling + * @property {Number} Phaser.scaleModes.NEAREST Pixelating scaling + * @static + */ + scaleModes: { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 + }, + + PIXI: PIXI || {}, + + // Used to create IDs for various Pixi objects. + _UID: 0 + +}; + +/** +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc +if (!Math.trunc) { + Math.trunc = function trunc(x) { + return x < 0 ? Math.ceil(x) : Math.floor(x); + }; +} + +/** +* A polyfill for Function.prototype.bind +*/ +if (!Function.prototype.bind) { + + /* jshint freeze: false */ + 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)) + { + /* jshint supernew: true */ + return new F; + } + })(target.prototype); + + return bound; + }; + })(); +} + +/** +* A polyfill for Array.isArray +*/ +if (!Array.isArray) +{ + Array.isArray = function (arg) + { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + +/** +* A polyfill for Array.forEach +* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach +*/ +if (!Array.prototype.forEach) +{ + Array.prototype.forEach = function(fun /*, thisArg */) + { + "use strict"; + + if (this === void 0 || this === null) + { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + if (typeof fun !== "function") + { + throw new TypeError(); + } + + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + + for (var i = 0; i < len; i++) + { + if (i in t) + { + fun.call(thisArg, t[i], i, t); + } + } + }; +} + +/** +* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 +* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ +* Cameron Foale (http://www.kibibu.com) +*/ +if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object") +{ + var CheapArray = function(type) + { + var proto = new Array(); // jshint ignore:line + + window[type] = function(arg) { + + if (typeof(arg) === "number") + { + Array.call(this, arg); + this.length = arg; + + for (var i = 0; i < this.length; i++) + { + this[i] = 0; + } + } + else + { + Array.call(this, arg.length); + + this.length = arg.length; + + for (var i = 0; i < this.length; i++) + { + this[i] = arg[i]; + } + } + }; + + window[type].prototype = proto; + window[type].constructor = window[type]; + }; + + CheapArray('Float32Array'); // jshint ignore:line + CheapArray('Uint32Array'); // jshint ignore:line + CheapArray('Uint16Array'); // jshint ignore:line + CheapArray('Int16Array'); // jshint ignore:line + CheapArray('ArrayBuffer'); // jshint ignore:line +} + +/** + * Also fix for the absent console in IE9 + */ +if (!window.console) +{ + window.console = {}; + window.console.log = window.console.assert = function(){}; + window.console.warn = window.console.assert = function(){}; +} + +/** + * Fix for Object.assign not existing on older devices + */ + +if (!Object.assign) { + /* jshint -W098 */ + // We include `varArgs` (unused) to ensure Object.assign.length === 2 + Object.assign = function(target, varArgs) { + /* jshint +W098 */ + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + var hasOwn = Object.prototype.hasOwnProperty; + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (hasOwn.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @class Phaser.Utils +* @static +*/ +Phaser.Utils = { + + /** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @method Phaser.Utils.reverseString + * @param {string} string - The string to be reversed. + * @return {string} The reversed string. + */ + reverseString: function (string) { + + return string.split('').reverse().join(''); + + }, + + /** + * Gets an object's property by string. + * + * @method Phaser.Utils.getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + getProperty: function(obj, name) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + return obj[name]; + case 2: + return obj[parts[0]][parts[1]]; + case 3: + return obj[parts[0]][parts[1]][parts[2]]; + case 4: + return obj[parts[0]][parts[1]][parts[2]][parts[3]]; + default: + return this._getProperty(obj, name); + } + + }, + + /** + * Sets an object's properties from a map of property names and values. + * + * ```javascript + * Phaser.Utils.setProperties(sprite, { + * 'animations.paused': true, + * 'body.enable': false, + * 'input.draggable': true, + * }); + * ``` + * + * @method Phaser.Utils.setProperties + * @param {object} obj - The object to modify. + * @param {object} props - The property names and values to set on the object (see {@link #setProperty}). + * @return {object} The modified object. + */ + setProperties: function(obj, props) { + + for (var name in props) + { + this.setProperty(obj, name, props[name]); + } + + return obj; + + }, + + /** + * Sets an object's property by name and value. + * + * ```javascript + * Phaser.Utils.setProperty(sprite, 'body.velocity.x', 60); + * ``` + * + * @method Phaser.Utils.setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + + setProperty: function(obj, name, value) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + obj[name] = value; + break; + case 2: + obj[parts[0]][parts[1]] = value; + break; + case 3: + obj[parts[0]][parts[1]][parts[2]] = value; + break; + case 4: + obj[parts[0]][parts[1]][parts[2]][parts[3]] = value; + break; + default: + this._setProperty(obj, name, value); + } + }, + + /** + * Gets an object's property by string. + * + * @private + * @method Phaser.Utils._getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property whose value will be returned. + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + _getProperty: function(obj, name) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + val = obj; + + while (i < len) + { + var key = parts[i]; + + if (val != null) + { + val = val[key]; + i++; + } + else + { + return undefined; + } + } + + return val; + + }, + + /** + * Sets an object's property by name and value. + * + * @private + * @method Phaser.Utils._setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + _setProperty: function(obj, name, value) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + currentObj = obj, + key = parts[0]; + + if (len === 1) + { + obj[name] = value; + } + else + { + while (i < (len - 1)) + { + currentObj = currentObj[key]; + i++; + key = parts[i]; + } + + currentObj[key] = value; + } + + return obj; + + }, + + /** + * Generate a random bool result based on the chance value. + * + * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance + * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. + * + * @method Phaser.Utils#chanceRoll + * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). + * @return {boolean} True if the roll passed, or false otherwise. + */ + chanceRoll: function (chance) { + if (chance === undefined) { chance = 50; } + return chance > 0 && (Math.random() * 100 <= chance); + }, + + /** + * Choose between one of two values randomly. + * + * @method Phaser.Utils#randomChoice + * @param {any} choice1 + * @param {any} choice2 + * @return {any} The randomly selected choice + */ + randomChoice: function (choice1, choice2) { + return (Math.random() < 0.5) ? choice1 : choice2; + }, + + /** + * Get a unit dimension from a string. + * + * @method Phaser.Utils.parseDimension + * @param {string|number} size - The size to parse. + * @param {number} dimension - The window dimension to check. + * @return {number} The parsed dimension. + */ + parseDimension: function (size, dimension) { + + var f = 0; + var px = 0; + + if (typeof size === 'string') + { + // %? + if (size.substr(-1) === '%') + { + f = parseInt(size, 10) / 100; + + if (dimension === 0) + { + px = window.innerWidth * f; + } + else + { + px = window.innerHeight * f; + } + } + else + { + px = parseInt(size, 10); + } + } + else + { + px = size; + } + + return px; + + }, + + /** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @method Phaser.Utils.pad + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * @return {string} The padded string. + */ + pad: function (str, len, pad, dir) { + + if (len === undefined) { var len = 0; } + if (pad === undefined) { var pad = ' '; } + if (dir === undefined) { var dir = 3; } + + str = str.toString(); + + 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; + + }, + + /** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * @method Phaser.Utils.isPlainObject + * @param {object} obj - The object to inspect. + * @return {boolean} - true if the object is plain, otherwise false. + */ + isPlainObject: function (obj) { + + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) + { + return false; + } + + // Support: Firefox <20 + // The try/catch suppresses exceptions thrown when attempting to access + // the "constructor" property of certain host objects, ie. |window.location| + // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + try { + if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) + { + return false; + } + } catch (e) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + /** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @method Phaser.Utils.extend + * @param {boolean} deep - Perform a deep copy? + * @param {object} target - The target object to copy to. + * @return {object} The extended object. + */ + extend: function () { + + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if (typeof target === "boolean") + { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } + + for (; i < length; i++) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) + { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = Phaser.Utils.extend(deep, clone, copy); + + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; + + }, + + /** + * Mixes in an existing mixin object with the target. + * + * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` + * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and + * the result is assigned directly. + * + * @method Phaser.Utils.mixinPrototype + * @param {object} target - The target object to receive the new functions. + * @param {object} mixin - The object to copy the functions from. + * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not? + */ + mixinPrototype: function (target, mixin, replace) { + + if (replace === undefined) { replace = false; } + + var mixinKeys = Object.keys(mixin); + + for (var i = 0; i < mixinKeys.length; i++) + { + var key = mixinKeys[i]; + var value = mixin[key]; + + if (!replace && (key in target)) + { + // Not overwriting existing property + continue; + } + else + { + if (value && + (typeof value.get === 'function' || typeof value.set === 'function')) + { + // Special case for classes like Phaser.Point which has a 'set' function! + if (typeof value.clone === 'function') + { + target[key] = value.clone(); + } + else + { + Object.defineProperty(target, key, value); + } + } + else + { + target[key] = value; + } + } + } + + }, + + /** + * Mixes the source object into the destination object, returning the newly modified destination object. + * Based on original code by @mudcube + * + * @method Phaser.Utils.mixin + * @param {object} from - The object to copy (the source object). + * @param {object} to - The object to copy to (the destination object). + * @return {object} The modified destination object. + */ + mixin: function (from, to) { + + if (!from || typeof (from) !== "object") + { + return to; + } + + for (var key in from) + { + var o = from[key]; + + if (o.childNodes || o.cloneNode) + { + continue; + } + + var type = typeof (from[key]); + + if (!from[key] || type !== "object") + { + to[key] = from[key]; + } + else + { + // Clone sub-object + if (typeof (to[key]) === type) + { + to[key] = Phaser.Utils.mixin(from[key], to[key]); + } + else + { + to[key] = Phaser.Utils.mixin(from[key], new o.constructor()); + } + } + } + + return to; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. +* If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. +* +* @class Phaser.Circle +* @constructor +* @param {number} [x=0] - The x coordinate of the center of the circle. +* @param {number} [y=0] - The y coordinate of the center of the circle. +* @param {number} [diameter=0] - The diameter of the circle. +*/ +Phaser.Circle = function (x, y, diameter) { + + x = x || 0; + y = y || 0; + diameter = diameter || 0; + + /** + * @property {number} x - The x coordinate of the center of the circle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the center of the circle. + */ + this.y = y; + + /** + * @property {number} _diameter - The diameter of the circle. + * @private + */ + this._diameter = diameter; + + /** + * @property {number} _radius - The radius of the circle. + * @private + */ + this._radius = 0; + + if (diameter > 0) + { + this._radius = diameter * 0.5; + } + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.CIRCLE; + +}; + +Phaser.Circle.prototype = { + + /** + * The circumference of the circle. + * + * @method Phaser.Circle#circumference + * @return {number} The circumference of the circle. + */ + circumference: function () { + + return 2 * (Math.PI * this._radius); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Circle. + * + * @method Phaser.Circle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = 2 * Math.PI * Math.random(); + var u = Math.random() + Math.random(); + var r = (u > 1) ? 2 - u : u; + var x = r * Math.cos(t); + var y = r * Math.sin(t); + + out.x = this.x + (x * this.radius); + out.y = this.y + (y * this.radius); + + return out; + + }, + + /** + * Returns the framing rectangle of the circle as a Phaser.Rectangle object. + * + * @method Phaser.Circle#getBounds + * @return {Phaser.Rectangle} The bounds of the Circle. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter); + + }, + + /** + * Sets the members of Circle to the specified values. + * @method Phaser.Circle#setTo + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} diameter - The diameter of the circle. + * @return {Circle} This circle object. + */ + setTo: function (x, y, diameter) { + + this.x = x; + this.y = y; + this._diameter = diameter; + this._radius = diameter * 0.5; + + return this; + + }, + + /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method Phaser.Circle#copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.diameter); + + }, + + /** + * Copies the x, y and diameter properties from this Circle to any given object. + * @method Phaser.Circle#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.diameter = this._diameter; + + return dest; + + }, + + /** + * Returns the distance from the center of the Circle object to the given object + * (can be Circle, Point or anything with x/y properties) + * @method Phaser.Circle#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round=false] - Round the distance to the nearest integer. + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y); + return round ? Math.round(distance) : distance; + + }, + + /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. + * @method Phaser.Circle#clone + * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} The cloned Circle object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Circle(this.x, this.y, this.diameter); + } + else + { + output.setTo(this.x, this.y, this.diameter); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Circle object. + * @method Phaser.Circle#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this circle, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Circle.contains(this, x, y); + + }, + + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method Phaser.Circle#circumferencePoint + * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ + circumferencePoint: function (angle, asDegrees, out) { + + return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out); + + }, + + + /** + * Creates or positions points on the circle. + * + * The points are equally distributed in the half-closed interval [startAngle, endAngle). The default arc is the entire circle. + * + * If the `out` argument is omitted, this method creates and returns an array of {@link Phaser.Point points}. If an array is passed as `out`, its items are treated as points and placed in the same way. + * + * @param {type} [steps=60] - The number of points to place. + * @param {type} [startAngle=0] - The starting angle in radians (unless asDegrees is true). + * @param {type} [endAngle=Phaser.Math.PI2] - The end angle in radians (unless asDegrees is true). + * @param {type} [asDegrees=false] - Are the given angles in radians (false) or degrees (true)? + * @param {any[]} [out] - An array of points or point-like objects (e.g., sprites). It should start at index 0 and its length should be equal to or greater than `steps`. + * @return {any[]} - The modified `out` argument or a new array of points. + */ + sample: function (steps, startAngle, endAngle, asDegrees, out) { + + if (!steps) { steps = 60; } + if (startAngle == null) { startAngle = 0; } + if (endAngle == null) { endAngle = Phaser.Math.PI2; } + if (!out) { out = []; } + + var i = 0; + + while (i < steps) + { + this.circumferencePoint( + Phaser.Math.linear(startAngle, endAngle, i / steps), + asDegrees, + out[i] || (out[i] = new Phaser.Point()) + ); + + i += 1; + } + + return out; + + }, + + /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method Phaser.Circle#offset + * @param {number} dx - Moves the x value of the Circle object by this amount. + * @param {number} dy - Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Circle#offsetPoint + * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). + * @return {Circle} This Circle object. + */ + offsetPoint: function (point) { + return this.offset(point.x, point.y); + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Circle#toString + * @return {string} a string representation of the instance. + */ + toString: function () { + return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; + } + +}; + +Phaser.Circle.prototype.constructor = Phaser.Circle; + +/** +* The largest distance between any two points on the circle. The same as the radius * 2. +* +* @name Phaser.Circle#diameter +* @property {number} diameter - Gets or sets the diameter of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "diameter", { + + get: function () { + return this._diameter; + }, + + set: function (value) { + + if (value > 0) + { + this._diameter = value; + this._radius = value * 0.5; + } + } + +}); + +/** +* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. +* @name Phaser.Circle#radius +* @property {number} radius - Gets or sets the radius of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "radius", { + + get: function () { + return this._radius; + }, + + set: function (value) { + + if (value > 0) + { + this._radius = value; + this._diameter = value * 2; + } + + } + +}); + +/** +* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#left +* @propety {number} left - Gets or sets the value of the leftmost point of the circle. +*/ +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; + } + + } + +}); + +/** +* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#right +* @property {number} right - Gets or sets the value of the rightmost point of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "right", { + + get: function () { + return this.x + this._radius; + }, + + set: function (value) { + + if (value < this.x) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.x; + } + + } + +}); + +/** +* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#top +* @property {number} top - Gets or sets the top of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "top", { + + get: function () { + return this.y - this._radius; + }, + + set: function (value) { + + if (value > this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = this.y - value; + } + + } + +}); + +/** +* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#bottom +* @property {number} bottom - Gets or sets the bottom of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "bottom", { + + get: function () { + return this.y + this._radius; + }, + + set: function (value) { + + if (value < this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.y; + } + + } + +}); + +/** +* The area of this Circle. +* @name Phaser.Circle#area +* @property {number} area - The area of this circle. +* @readonly +*/ +Object.defineProperty(Phaser.Circle.prototype, "area", { + + get: function () { + + if (this._radius > 0) + { + return Math.PI * this._radius * this._radius; + } + else + { + return 0; + } + + } + +}); + +/** +* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. +* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. +* @name Phaser.Circle#empty +* @property {boolean} empty - Gets or sets the empty state of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "empty", { + + get: function () { + return (this._diameter === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Circle object. +* @method Phaser.Circle.contains +* @param {Phaser.Circle} a - The Circle to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this circle, otherwise false. +*/ +Phaser.Circle.contains = function (a, x, y) { + + // Check if x/y are within the bounds first + 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; + } + +}; + +/** +* Determines whether the two Circle objects match. This method compares the x, y and diameter properties. +* @method Phaser.Circle.equals +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. +*/ +Phaser.Circle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.diameter === b.diameter); + +}; + +/** +* Determines whether the two Circle objects intersect. +* This method checks the radius distances between the two Circle objects to see if they intersect. +* @method Phaser.Circle.intersects +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. +*/ +Phaser.Circle.intersects = function (a, b) { + + return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius)); + +}; + +/** +* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. +* @method Phaser.Circle.circumferencePoint +* @param {Phaser.Circle} a - The first Circle object. +* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. +* @return {Phaser.Point} The Point object holding the result. +*/ +Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) { + + if (asDegrees === undefined) { asDegrees = false; } + if (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; + +}; + +/** +* Checks if the given Circle and Rectangle objects intersect. +* @method Phaser.Circle.intersectsRectangle +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Rectangle} r - The Rectangle object to test. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +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; + +}; + +/** +* Checks if the given Circle and Line objects intersect. +* @method Phaser.Circle.intersectsLine +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnpoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Circle.intersectsLine = function (c, l, returnPoints) { + var h = c.x; + var k = c.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = c.radius; + var b = c.radius; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Circle = Phaser.Circle; + +/** +* @author Richard Davey +* @author Chad Engler +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a Ellipse object. A curve on a plane surrounding two focal points. +* +* @class Phaser.Ellipse +* @constructor +* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [width=0] - The overall width of this ellipse. +* @param {number} [height=0] - The overall height of this ellipse. +*/ +Phaser.Ellipse = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.x = x; + + /** + * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.y = y; + + /** + * @property {number} width - The overall width of this ellipse. + */ + this.width = width; + + /** + * @property {number} height - The overall height of this ellipse. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ELLIPSE; + +}; + +Phaser.Ellipse.prototype = { + + /** + * Sets the members of the Ellipse to the specified values. + * @method Phaser.Ellipse#setTo + * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} width - The overall width of this ellipse. + * @param {number} height - The overall height of this ellipse. + * @return {Phaser.Ellipse} This Ellipse object. + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. + * + * @method Phaser.Ellipse#getBounds + * @return {Phaser.Rectangle} The bounds of the Ellipse. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Ellipse. + * + * @method Phaser.Ellipse#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Ellipse} This Ellipse object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Ellipse to any given object. + * @method Phaser.Ellipse#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function(dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. + * @method Phaser.Ellipse#clone + * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. + * @return {Phaser.Ellipse} The cloned Ellipse object. + */ + clone: function(output) { + + if (output === undefined || output === null) + { + output = new Phaser.Ellipse(this.x, this.y, this.width, this.height); + } + else + { + output.setTo(this.x, this.y, this.width, this.height); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Ellipse object. + * + * @method Phaser.Ellipse#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this ellipse, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Ellipse.contains(this, x, y); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Ellipse. + * + * @method Phaser.Ellipse#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var p = Math.random() * Math.PI * 2; + var r = Math.random(); + + out.x = Math.sqrt(r) * Math.cos(p); + out.y = Math.sqrt(r) * Math.sin(p); + + out.x = this.x + (out.x * this.width / 2.0); + out.y = this.y + (out.y * this.height / 2.0); + + return out; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Ellipse#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]"; + } + +}; + +Phaser.Ellipse.prototype.constructor = Phaser.Ellipse; + +/** +* The left coordinate of the Ellipse. The same as the X coordinate. +* @name Phaser.Ellipse#left +* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + + this.x = value; + + } + +}); + +/** +* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. +* @name Phaser.Ellipse#right +* @property {number} right - Gets or sets the value of the rightmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "right", { + + get: function () { + return this.x + this.width; + }, + + set: function (value) { + + if (value < this.x) + { + this.width = 0; + } + else + { + this.width = value - this.x; + } + } + +}); + +/** +* The top of the Ellipse. The same as its y property. +* @name Phaser.Ellipse#top +* @property {number} top - Gets or sets the top of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "top", { + + get: function () { + return this.y; + }, + + set: function (value) { + this.y = value; + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. +* @name Phaser.Ellipse#bottom +* @property {number} bottom - Gets or sets the bottom of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value < this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + } + +}); + +/** +* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. +* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. +* @name Phaser.Ellipse#empty +* @property {boolean} empty - Gets or sets the empty state of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "empty", { + + get: function () { + return (this.width === 0 || this.height === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Ellipse object. +* +* @method Phaser.Ellipse.contains +* @param {Phaser.Ellipse} a - The Ellipse to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this ellipse, otherwise false. +*/ +Phaser.Ellipse.contains = function (a, x, y) { + + if (a.width <= 0 || a.height <= 0) { + return false; + } + + // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 + var normx = ((x - a.x) / a.width) - 0.5; + var normy = ((y - a.y) / a.height) - 0.5; + + normx *= normx; + normy *= normy; + + return (normx + normy < 0.25); + +}; + +/** +* Checks if the given Ellipse and Line objects intersect. +* @method Phaser.Ellipse.intersectsLine +* @param {Phaser.Ellipse} e - The Ellipse object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnPoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Ellipse.intersectsLine = function (e, l, returnPoints) { + var h = e.x; + var k = e.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = e.width / 2; + var b = e.height / 2; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Ellipse = Phaser.Ellipse; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Line object with a start and an end point. +* +* @class Phaser.Line +* @constructor +* @param {number} [x1=0] - The x coordinate of the start of the line. +* @param {number} [y1=0] - The y coordinate of the start of the line. +* @param {number} [x2=0] - The x coordinate of the end of the line. +* @param {number} [y2=0] - The y coordinate of the end of the line. +*/ +Phaser.Line = function (x1, y1, x2, y2) { + + x1 = x1 || 0; + y1 = y1 || 0; + x2 = x2 || 0; + y2 = y2 || 0; + + /** + * @property {Phaser.Point} start - The start point of the line. + */ + this.start = new Phaser.Point(x1, y1); + + /** + * @property {Phaser.Point} end - The end point of the line. + */ + this.end = new Phaser.Point(x2, y2); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.LINE; + +}; + +Phaser.Line.prototype = { + + /** + * Sets the components of the Line to the specified values. + * + * @method Phaser.Line#setTo + * @param {number} [x1=0] - The x coordinate of the start of the line. + * @param {number} [y1=0] - The y coordinate of the start of the line. + * @param {number} [x2=0] - The x coordinate of the end of the line. + * @param {number} [y2=0] - The y coordinate of the end of the line. + * @return {Phaser.Line} This line object + */ + setTo: function (x1, y1, x2, y2) { + + this.start.setTo(x1, y1); + this.end.setTo(x2, y2); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given points. + * + * @param {any} start - A {@link Phaser.Point} or point-like object. + * @param {any} end - A {@link Phaser.Point} or point-like object. + * @return {Phaser.Line} - This line object. + */ + fromPoints: function (start, end) { + + this.setTo(start.x, start.y, end.x, end.y); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given sprites. + * Can optionally be calculated from their center coordinates. + * + * @method Phaser.Line#fromSprite + * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {boolean} [useCenter=false] - If true it will use startSprite.centerX, if false startSprite.x. + * @return {Phaser.Line} This line object + */ + fromSprite: function (startSprite, endSprite, useCenter) { + + if (useCenter === undefined) { useCenter = false; } + + if (useCenter) + { + return this.setTo(startSprite.centerX, startSprite.centerY, endSprite.centerX, endSprite.centerY); + } + + return this.fromPoints(startSprite, endSprite); + + }, + + /** + * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. + * + * @method Phaser.Line#fromAngle + * @param {number} x - The x coordinate of the start of the line. + * @param {number} y - The y coordinate of the start of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line in pixels. + * @return {Phaser.Line} This line object + */ + fromAngle: function (x, y, angle, length) { + + this.start.setTo(x, y); + this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length)); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place from the center of the line. + * If you wish to rotate around a different point see Line.rotateAround. + * + * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. + * + * @method Phaser.Line#rotate + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotate: function (angle, asDegrees) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + this.start.rotate(cx, cy, angle, asDegrees); + this.end.rotate(cx, cy, angle, asDegrees); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place around the coordinates given. + * + * @method Phaser.Line#rotateAround + * @param {number} x - The x coordinate to offset the rotation from. + * @param {number} y - The y coordinate to offset the rotation from. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotateAround: function (x, y, angle, asDegrees) { + + this.start.rotate(x, y, angle, asDegrees); + this.end.rotate(x, y, angle, asDegrees); + + return this; + + }, + + /** + * Checks for intersection between this line and another Line. + * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * + * @method Phaser.Line#intersects + * @param {Phaser.Line} line - The line to check against this one. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ + intersects: function (line, asSegment, result) { + + return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result); + + }, + + /** + * Returns the reflected angle between two lines. + * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. + * + * @method Phaser.Line#reflect + * @param {Phaser.Line} line - The line to reflect off this line. + * @return {number} The reflected angle in radians. + */ + reflect: function (line) { + + return Phaser.Line.reflect(this, line); + + }, + + /** + * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. + * + * @method Phaser.Line#midPoint + * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. + * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. + */ + midPoint: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = (this.start.x + this.end.x) / 2; + out.y = (this.start.y + this.end.y) / 2; + + return out; + + }, + + /** + * Centers this Line on the given coordinates. + * + * The line is centered by positioning the start and end points so that the lines midpoint matches + * the coordinates given. + * + * @method Phaser.Line#centerOn + * @param {number} x - The x position to center the line on. + * @param {number} y - The y position to center the line on. + * @return {Phaser.Line} This line object + */ + centerOn: function (x, y) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + var tx = x - cx; + var ty = y - cy; + + this.start.add(tx, ty); + this.end.add(tx, ty); + + }, + + /** + * Tests if the given coordinates fall on this line. See {@link #pointOnSegment} to test against just the line segment. + * + * @method Phaser.Line#pointOnLine + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line, false if not. + */ + pointOnLine: function (x, y, epsilon) { + + return Phaser.Math.fuzzyEqual((x - this.start.x) * (this.end.y - this.start.y), (this.end.x - this.start.x) * (y - this.start.y), epsilon || 0); + + }, + + /** + * Tests if the given coordinates fall on this line and within the segment. See {@link #pointOnLine} to test against just the line. + * + * @method Phaser.Line#pointOnSegment + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line and segment, false if not. + */ + pointOnSegment: function (x, y, epsilon) { + + var xMin = Math.min(this.start.x, this.end.x); + var xMax = Math.max(this.start.x, this.end.x); + var yMin = Math.min(this.start.y, this.end.y); + var yMax = Math.max(this.start.y, this.end.y); + + return (this.pointOnLine(x, y, epsilon) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)); + + }, + + /** + * Picks a random point from anywhere on the Line segment and returns it. + * + * @method Phaser.Line#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = Math.random(); + + out.x = this.start.x + t * (this.end.x - this.start.x); + out.y = this.start.y + t * (this.end.y - this.start.y); + + return out; + + }, + + /** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * The start and end points are rounded before this runs as the algorithm works on integers. + * + * @method Phaser.Line#coordinatesOnLine + * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. + * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. + * @return {array} An array of coordinates. + */ + coordinatesOnLine: function (stepRate, results) { + + if (stepRate === undefined) { stepRate = 1; } + if (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 < x2) ? 1 : -1; + var sy = (y1 < y2) ? 1 : -1; + var err = dx - dy; + + results.push([x1, y1]); + + var i = 1; + + while (!((x1 === x2) && (y1 === y2))) + { + var e2 = err << 1; + + if (e2 > -dy) + { + err -= dy; + x1 += sx; + } + + if (e2 < dx) + { + err += dx; + y1 += sy; + } + + if (i % stepRate === 0) + { + results.push([x1, y1]); + } + + i++; + + } + + return results; + + }, + + /** + * Returns a new Line object with the same values for the start and end properties as this Line object. + * @method Phaser.Line#clone + * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned. + * @return {Phaser.Line} The cloned Line object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y); + } + else + { + output.setTo(this.start.x, this.start.y, this.end.x, this.end.y); + } + + return output; + + } + +}; + +/** +* @name Phaser.Line#length +* @property {number} length - Gets the length of the line segment. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "length", { + + get: function () { + return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#angle +* @property {number} angle - Gets the angle of the line in radians. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "angle", { + + get: function () { + return Phaser.Point.angle(this.end, this.start); + } + +}); + +/** +* @name Phaser.Line#slope +* @property {number} slope - Gets the slope of the line (y/x). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "slope", { + + get: function () { + return (this.end.y - this.start.y) / (this.end.x - this.start.x); + } + +}); + +/** +* @name Phaser.Line#perpSlope +* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "perpSlope", { + + get: function () { + return -((this.end.x - this.start.x) / (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#x +* @property {number} x - Gets the x coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "x", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#y +* @property {number} y - Gets the y coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "y", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#left +* @property {number} left - Gets the left-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "left", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#right +* @property {number} right - Gets the right-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "right", { + + get: function () { + return Math.max(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#top +* @property {number} top - Gets the top-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "top", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#bottom +* @property {number} bottom - Gets the bottom-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "bottom", { + + get: function () { + return Math.max(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#width +* @property {number} width - Gets the width of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "width", { + + get: function () { + return Math.abs(this.start.x - this.end.x); + } + +}); + +/** +* @name Phaser.Line#height +* @property {number} height - Gets the height of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "height", { + + get: function () { + return Math.abs(this.start.y - this.end.y); + } + +}); + +/** +* @name Phaser.Line#normalX +* @property {number} normalX - Gets the x component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalX", { + + get: function () { + return Math.cos(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalY +* @property {number} normalY - Gets the y component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalY", { + + get: function () { + return Math.sin(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalAngle +* @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalAngle", { + + get: function () { + return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI); + } + +}); + +/** +* Checks for intersection between two lines as defined by the given start and end points. +* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersectsPoints +* @param {Phaser.Point} a - The start of the first Line to be checked. +* @param {Phaser.Point} b - The end of the first line to be checked. +* @param {Phaser.Point} e - The start of the second Line to be checked. +* @param {Phaser.Point} f - The end of the second line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) { + + if (asSegment === undefined) { asSegment = true; } + if (result === undefined) { result = new Phaser.Point(); } + + var a1 = b.y - a.y; + var a2 = f.y - e.y; + var b1 = a.x - b.x; + var b2 = e.x - f.x; + var c1 = (b.x * a.y) - (a.x * b.y); + var c2 = (f.x * e.y) - (e.x * f.y); + var denom = (a1 * b2) - (a2 * b1); + + if (denom === 0) + { + return null; + } + + result.x = ((b1 * c2) - (b2 * c1)) / denom; + result.y = ((a2 * c1) - (a1 * c2)) / denom; + + if (asSegment) + { + var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y)); + var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc; + var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc; + + if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) + { + return result; + } + else + { + return null; + } + } + + return result; + +}; + +/** +* Checks for intersection between two lines. +* If asSegment is true it will check for segment intersection. +* If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersects +* @param {Phaser.Line} a - The first Line to be checked. +* @param {Phaser.Line} b - The second Line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersects = function (a, b, asSegment, result) { + + return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result); + +}; + +/** +* Checks for intersection between the Line and a Rectangle shape, or a rectangle-like +* object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. +* +* An intersection is considered valid if: +* +* The line starts within or ends within the rectangle; or +* The line segment intersects one of the 4 rectangle edges; and +* The line has a non-zero length; and +* The rectangle is not empty. +* +* For the purposes of this function rectangles are considered 'solid'. +* +* @method Phaser.Line.intersectsRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle. +*/ +Phaser.Line.intersectsRectangle = function (line, rect) { + + // Quick bail out + if (line.length === 0 || rect.empty) + { + return false; + } + + var x1 = line.start.x; + var y1 = line.start.y; + + var x2 = line.end.x; + var y2 = line.end.y; + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + + var t = 0; + + // If the start or end of the line is inside the rect then we assume + // collision, as rects are solid for our use-case. + + if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || + (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) + { + return true; + } + + if (x1 < bx1 && x2 >= bx1) + { + // Left edge + t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); + + if (t > by1 && t <= by2) + { + return true; + } + } + else if (x1 > bx2 && x2 <= bx2) + { + // Right edge + t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); + + if (t >= by1 && t <= by2) + { + return true; + } + } + + if (y1 < by1 && y2 >= by1) + { + // Top edge + t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + else if (y1 > by2 && y2 <= by2) + { + // Bottom edge + t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + + return false; + +}; + +/** +* Finds the closest intersection between the Line and a Rectangle shape, or a rectangle-like +* object, such as a Sprite or Body. +* +* @method Phaser.Line.intersectionWithRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @param {Phaser.Point} [result] - A Point object to store the result in. +* @return {?Phaser.Point} - The intersection closest to the Line's start, or null if there is no intersection. +*/ +Phaser.Line.intersectionWithRectangle = function (line, rect, result) { + + var self = Phaser.Line.intersectionWithRectangle; + + if (!result) + { + result = new Phaser.Point(); + } + + if (!self.edges) + { + self.edges = [new Phaser.Line(), new Phaser.Line(), new Phaser.Line(), new Phaser.Line()]; + } + + if (!self.edgeIntersection) + { + self.edgeIntersection = new Phaser.Point(); + } + + var edges = self.edges; + var edgeIntersection = self.edgeIntersection.set(0); + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + var closestDistance = Infinity; + + edges[0].setTo(bx1, by1, bx2, by1); + edges[1].setTo(bx1, by2, bx2, by2); + edges[2].setTo(bx1, by1, bx1, by2); + edges[3].setTo(bx2, by1, bx2, by2); + + for (var edge, i = 0; (edge = edges[i]); i++) + { + if (line.intersects(edge, true, edgeIntersection)) + { + var distance = line.start.distance(edgeIntersection); + + if (distance < closestDistance) + { + closestDistance = distance; + result.copyFrom(edgeIntersection); + } + } + } + + if (distance != null) + { + return result; + } + + return null; + +}; + +/** +* Returns the reflected angle between two lines. +* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. +* +* @method Phaser.Line.reflect +* @param {Phaser.Line} a - The base line. +* @param {Phaser.Line} b - The line to be reflected from the base line. +* @return {number} The reflected angle in radians. +*/ +Phaser.Line.reflect = function (a, b) { + + return 2 * b.normalAngle - 3.141592653589793 - a.angle; + +}; + +/** +* @author Mat Groves http://matgroves.com/ @Doormat23 +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. +* +* It is represented like so: +* +* | a | b | tx | +* | c | d | ty | +* | 0 | 0 | 1 | +* +* @class Phaser.Matrix +* @constructor +* @param {number} [a=1] - Horizontal scaling +* @param {number} [b=0] - Horizontal skewing +* @param {number} [c=0] - Vertical skewing +* @param {number} [d=1] - Vertical scaling +* @param {number} [tx=0] - Horizontal translation +* @param {number} [ty=0] - Vertical translation +*/ +Phaser.Matrix = function (a, b, c, d, tx, ty) { + + if (a === undefined || a === null) { a = 1; } + if (b === undefined || b === null) { b = 0; } + if (c === undefined || c === null) { c = 0; } + if (d === undefined || d === null) { d = 1; } + if (tx === undefined || tx === null) { tx = 0; } + if (ty === undefined || ty === null) { ty = 0; } + + /** + * @property {number} a + * @default 1 + */ + this.a = a; + + /** + * @property {number} b + * @default 0 + */ + this.b = b; + + /** + * @property {number} c + * @default 0 + */ + this.c = c; + + /** + * @property {number} d + * @default 1 + */ + this.d = d; + + /** + * @property {number} tx + * @default 0 + */ + this.tx = tx; + + /** + * @property {number} ty + * @default 0 + */ + this.ty = ty; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.MATRIX; + +}; + +Phaser.Matrix.prototype = { + + /** + * Sets the values of this Matrix to the values in the given array. + * + * The Array elements should be set as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @method Phaser.Matrix#fromArray + * @param {Array} array - The array to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + fromArray: function (array) { + + return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]); + + }, + + /** + * Sets the values of this Matrix to the given values. + * + * @method Phaser.Matrix#setTo + * @param {number} a - Horizontal scaling + * @param {number} b - Horizontal skewing + * @param {number} c - Vertical skewing + * @param {number} d - Vertical scaling + * @param {number} tx - Horizontal translation + * @param {number} ty - Vertical translation + * @return {Phaser.Matrix} This Matrix object. + */ + setTo: function (a, b, c, d, tx, ty) { + + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + + }, + + /** + * Creates a new Matrix object based on the values of this Matrix. + * If you provide the output parameter the values of this Matrix will be copied over to it. + * If the output parameter is blank a new Matrix object will be created. + * + * @method Phaser.Matrix#clone + * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created. + * @return {Phaser.Matrix} A clone of this Matrix. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); + } + else + { + output.a = this.a; + output.b = this.b; + output.c = this.c; + output.d = this.d; + output.tx = this.tx; + output.ty = this.ty; + } + + return output; + + }, + + /** + * Copies the properties from this Matrix to the given Matrix. + * + * @method Phaser.Matrix#copyTo + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} The destination Matrix object. + */ + copyTo: function (matrix) { + + matrix.copyFrom(this); + + return matrix; + + }, + + /** + * Copies the properties from the given Matrix into this Matrix. + * + * @method Phaser.Matrix#copyFrom + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + copyFrom: function (matrix) { + + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + + return this; + + }, + + /** + * Creates a Float32 Array with values populated from this Matrix object. + * + * @method Phaser.Matrix#toArray + * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not. + * @param {Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created. + * @return {Float32Array} The newly created array which contains the matrix. + */ + toArray: function (transpose, array) { + + if (array === undefined) { array = new Float32Array(9); } + + if (transpose) + { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else + { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + + }, + + /** + * Get a new position with the current transformation applied. + * + * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) + * + * @method Phaser.Matrix#apply + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, transformed through this matrix. + */ + apply: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + newPos.x = this.a * pos.x + this.c * pos.y + this.tx; + newPos.y = this.b * pos.x + this.d * pos.y + this.ty; + + return newPos; + + }, + + /** + * Get a new position with the inverse of the current transformation applied. + * + * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) + * + * @method Phaser.Matrix#applyInverse + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, inverse transformed through this matrix. + */ + applyInverse: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + var id = 1 / (this.a * this.d + this.c * -this.b); + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + + }, + + /** + * Translates the matrix on the x and y. + * This is the same as Matrix.tx += x. + * + * @method Phaser.Matrix#translate + * @param {number} x - The x value to translate on. + * @param {number} y - The y value to translate on. + * @return {Phaser.Matrix} This Matrix object. + */ + translate: function (x, y) { + + this.tx += x; + this.ty += y; + + return this; + + }, + + /** + * Applies a scale transformation to this matrix. + * + * @method Phaser.Matrix#scale + * @param {number} x - The amount to scale horizontally. + * @param {number} y - The amount to scale vertically. + * @return {Phaser.Matrix} This Matrix object. + */ + scale: function (x, y) { + + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + + }, + + /** + * Applies a rotation transformation to this matrix. + * + * @method Phaser.Matrix#rotate + * @param {number} angle - The angle to rotate by, given in radians. + * @return {Phaser.Matrix} This Matrix object. + */ + rotate: function (angle) { + + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos-this.b * sin; + this.b = a1 * sin+this.b * cos; + this.c = c1 * cos-this.d * sin; + this.d = c1 * sin+this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + + }, + + /** + * Appends the given Matrix to this Matrix. + * + * @method Phaser.Matrix#append + * @param {Phaser.Matrix} matrix - The matrix to append to this one. + * @return {Phaser.Matrix} This Matrix object. + */ + append: function (matrix) { + + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + + }, + + /** + * Resets this Matrix to an identity (default) matrix. + * + * @method Phaser.Matrix#identity + * @return {Phaser.Matrix} This Matrix object. + */ + identity: function () { + + return this.setTo(1, 0, 0, 1, 0, 0); + + } + +}; + +Phaser.identityMatrix = new Phaser.Matrix(); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. +* The following code creates a point at (0,0): +* `var myPoint = new Phaser.Point();` +* You can also use them as 2D Vectors and you'll find different vector related methods in this class. +* +* @class Phaser.Point +* @constructor +* @param {number} [x=0] - The horizontal position of this Point. +* @param {number} [y=0] - The vertical position of this Point. +*/ +Phaser.Point = function (x, y) { + + x = x || 0; + y = y || 0; + + /** + * @property {number} x - The x value of the point. + */ + this.x = x; + + /** + * @property {number} y - The y value of the point. + */ + this.y = y; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINT; + +}; + +Phaser.Point.prototype = { + + /** + * Copies the x and y properties from any given object to this Point. + * + * @method Phaser.Point#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Point} This Point object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y); + + }, + + /** + * Inverts the x and y values of this Point + * + * @method Phaser.Point#invert + * @return {Phaser.Point} This Point object. + */ + invert: function () { + + return this.setTo(this.y, this.x); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.setTo(2)` is the same as `Point.setTo(2, 2)` + * + * Identical to {@link #set}. + * + * @method Phaser.Point#setTo + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setTo: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.set(2)` is the same as `Point.set(2, 2)` + * + * Identical to {@link #setTo}. + * + * @method Phaser.Point#set + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + set: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object from a given polar coordinate. + * + * @method Phaser.Point#setToPolar + * @param {number} azimuth - The angular coordinate, in radians (unless `asDegrees`). + * @param {number} [radius=1] - The radial coordinate (length). + * @param {boolean} [asDegrees=false] - True if `azimuth` is in degrees. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setToPolar: function(azimuth, radius, asDegrees) { + + if (radius == null) { radius = 1; } + if (asDegrees) { azimuth = Phaser.Math.degToRad(azimuth); } + + return this.setTo(Math.cos(azimuth) * radius, Math.sin(azimuth) * radius); + + }, + + /** + * Adds the given x and y values to this Point. + * + * @method Phaser.Point#add + * @param {number} x - The value to add to Point.x. + * @param {number} y - The value to add to Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + add: function (x, y) { + + this.x += x; + this.y += y; + return this; + + }, + + /** + * Subtracts the given x and y values from this Point. + * + * @method Phaser.Point#subtract + * @param {number} x - The value to subtract from Point.x. + * @param {number} y - The value to subtract from Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + subtract: function (x, y) { + + this.x -= x; + this.y -= y; + return this; + + }, + + /** + * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. + * + * @method Phaser.Point#multiply + * @param {number} x - The value to multiply Point.x by. + * @param {number} y - The value to multiply Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + multiply: function (x, y) { + + this.x *= x; + this.y *= y; + return this; + + }, + + /** + * Divides Point.x and Point.y by the given x and y values. + * + * @method Phaser.Point#divide + * @param {number} x - The value to divide Point.x by. + * @param {number} y - The value to divide Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + divide: function (x, y) { + + this.x /= x; + this.y /= y; + return this; + + }, + + /** + * Clamps the x value of this Point to be between the given min and max. + * + * @method Phaser.Point#clampX + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampX: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + return this; + + }, + + /** + * Clamps the y value of this Point to be between the given min and max + * + * @method Phaser.Point#clampY + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampY: function (min, max) { + + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * Clamps this Point object values to be between the given min and max. + * + * @method Phaser.Point#clamp + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clamp: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * If this Point is not within the given object, moves it inside (at the nearest edge). + * + * @method Phaser.Point#clip + * @param {any} rect - A {@link Phaser.Rectangle} or any object with left, top, right, and bottom properties. + * @return {Phaser.Point} This Point object. + */ + clip: function (rect) { + + var left = rect.left, top = rect.top, right = rect.right, bottom = rect.bottom; + + if (this.x < left ) { this.x = left; } + else if (this.x > right) { this.x = right; } + if (this.y < top) { this.y = top; } + else if (this.y > bottom) { this.y = bottom; } + + return this; + + }, + + /** + * Creates a copy of the given Point. + * + * @method Phaser.Point#clone + * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The new Point object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(this.x, this.y); + } + else + { + output.setTo(this.x, this.y); + } + + return output; + + }, + + /** + * Copies the x and y properties from this Point to any given object. + * + * @method Phaser.Point#copyTo + * @param {any} dest - The object to copy to. + * @return {object} The dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + + return dest; + + }, + + /** + * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) + * + * @method Phaser.Point#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round] - Round the distance to the nearest integer (default false). + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + return Phaser.Point.distance(this, dest, round); + + }, + + /** + * Determines whether the given objects x/y values are equal to this Point object. + * + * @method Phaser.Point#equals + * @param {Phaser.Point|any} a - The object to compare with this Point. + * @return {boolean} A value of true if the x and y points are equal, otherwise false. + */ + equals: function (a) { + + return a.x === this.x && a.y === this.y; + + }, + + /** + * Determines whether a set of x-y coordinates are equal to this Point's. + * + * @method Phaser.Point#equalsXY + * @param {number} x - The x-coordinate to compare with this Point. + * @param {number} y - The y-coordinate to compare with this Point. + * @return {boolean} A value of true if the Point's coordinates are identical to the arguments, otherwise false. + */ + equalsXY: function (x, y) { + + return this.x === x && this.y === y; + + }, + + fuzzyEquals: function (a, epsilon) { + + return Phaser.Point.fuzzyEquals(this, a, epsilon); + + }, + + fuzzyEqualsXY: function (x, y, epsilon) { + + return Phaser.Point.fuzzyEqualsXY(this, x, y, epsilon); + + }, + + /** + * Returns the angle between this Point object and another object with public x and y properties. + * + * @method Phaser.Point#angle + * @param {Phaser.Point|any} a - The object to get the angle from this Point to. + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angle: function (a, asDegrees) { + + return this.angleXY(a.x, a.y, asDegrees); + + }, + + /** + * Returns the angle between this Point object and an x-y coordinate pair. + * + * @method Phaser.Point#angleXY + * @param {number} x - The x-coordinate + * @param {number} y - The y-coordinate + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angleXY: function (x, y, asDegrees) { + + var angle = Math.atan2(y - this.y, x - this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Returns the arctangent of this Point. + * + * @method Phaser.Point#atan + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where the vertex is (0, 0). Within [-pi, pi] or [-180deg, 180deg]. + */ + atan: function (asDegrees) { + + var angle = Math.atan2(this.y, this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Rotates this Point around the x/y coordinates given to the desired angle. + * + * @method Phaser.Point#rotate + * @param {number} x - The x coordinate of the anchor point. + * @param {number} y - The y coordinate of the anchor point. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {number} [distance] - An optional distance constraint between the Point and the anchor. + * @return {Phaser.Point} The modified point object. + */ + rotate: function (x, y, angle, asDegrees, distance) { + + return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance); + + }, + + /** + * Calculates the length of the Point object. + * + * @method Phaser.Point#getMagnitude + * @return {number} The length of the Point. + */ + getMagnitude: function () { + + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + + }, + + /** + * Calculates the length squared of the Point object. + * + * @method Phaser.Point#getMagnitudeSq + * @return {number} The length ^ 2 of the Point. + */ + getMagnitudeSq: function () { + + return (this.x * this.x) + (this.y * this.y); + + }, + + /** + * Alters the length of the Point without changing the direction. + * + * @method Phaser.Point#setMagnitude + * @param {number} magnitude - The desired magnitude of the resulting Point. + * @return {Phaser.Point} This Point object. + */ + setMagnitude: function (magnitude) { + + return this.normalize().multiply(magnitude, magnitude); + + }, + + /** + * Alters the Point object so that its length is 1, but it retains the same direction. + * + * @method Phaser.Point#normalize + * @return {Phaser.Point} This Point object. + */ + normalize: function () { + + if (!this.isZero()) + { + var m = this.getMagnitude(); + this.x /= m; + this.y /= m; + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at most the max value. + * + * @method Phaser.Point#limit + * @param {number} max - The maximum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#expand + */ + limit: function (max) { + + if (this.getMagnitudeSq() > max * max) + { + this.setMagnitude(max); + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at least the min value. + * + * @method Phaser.Point#expand + * @param {number} min - The minimum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#limit + */ + expand: function (min) { + + if (this.getMagnitudeSq() < min * min) + { + this.setMagnitude(min); + } + + return this; + + }, + + /** + * Determine if this point is at 0,0. + * + * @method Phaser.Point#isZero + * @return {boolean} True if this Point is 0,0, otherwise false. + */ + isZero: function () { + + return (this.x === 0 && this.y === 0); + + }, + + /** + * The dot product of this and another Point object. + * + * @method Phaser.Point#dot + * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point. + * @return {number} The result. + */ + dot: function (a) { + + return ((this.x * a.x) + (this.y * a.y)); + + }, + + /** + * The cross product of this and another Point object. + * + * @method Phaser.Point#cross + * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point. + * @return {number} The result. + */ + cross: function (a) { + + return ((this.x * a.y) - (this.y * a.x)); + + }, + + /** + * Make this Point perpendicular (90 degrees rotation) + * + * @method Phaser.Point#perp + * @return {Phaser.Point} This Point object. + */ + perp: function () { + + return this.setTo(-this.y, this.x); + + }, + + /** + * Make this Point perpendicular (-90 degrees rotation) + * + * @method Phaser.Point#rperp + * @return {Phaser.Point} This Point object. + */ + rperp: function () { + + return this.setTo(this.y, -this.x); + + }, + + /** + * Right-hand normalize (make unit length) this Point. + * + * @method Phaser.Point#normalRightHand + * @return {Phaser.Point} This Point object. + */ + normalRightHand: function () { + + return this.setTo(this.y * -1, this.x); + + }, + + /** + * Math.floor() both the x and y properties of this Point. + * + * @method Phaser.Point#floor + * @return {Phaser.Point} This Point object. + */ + floor: function () { + + return this.setTo(Math.floor(this.x), Math.floor(this.y)); + + }, + + /** + * Math.ceil() both the x and y properties of this Point. + * + * @method Phaser.Point#ceil + * @return {Phaser.Point} This Point object. + */ + ceil: function () { + + return this.setTo(Math.ceil(this.x), Math.ceil(this.y)); + + }, + + /** + * Math.round() both the x and y properties of this Point. + * + * @method Phaser.Point#round + * @return {Phaser.Point} This Point object. + */ + round: function () { + + return this.setTo(Math.round(this.x), Math.round(this.y)); + + }, + + /** + * Returns a string representation of this object. + * + * @method Phaser.Point#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; + + } + +}; + +Phaser.Point.prototype.constructor = Phaser.Point; + +/** +* Adds the coordinates of two points together to create a new point. +* +* @method Phaser.Point.add +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.add = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x + b.x; + out.y = a.y + b.y; + + return out; + +}; + +/** +* Subtracts the coordinates of two points to create a new point. +* +* @method Phaser.Point.subtract +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.subtract = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x - b.x; + out.y = a.y - b.y; + + return out; + +}; + +/** +* Multiplies the coordinates of two points to create a new point. +* +* @method Phaser.Point.multiply +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiply = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x * b.x; + out.y = a.y * b.y; + + return out; + +}; + +/** +* Divides the coordinates of two points to create a new point. +* +* @method Phaser.Point.divide +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.divide = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x / b.x; + out.y = a.y / b.y; + + return out; + +}; + +/** +* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. +* +* @method Phaser.Point.equals +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {boolean} A value of true if the Points are equal, otherwise false. +*/ +Phaser.Point.equals = function (a, b) { + + return a.x === b.x && a.y === b.y; + +}; + +Phaser.Point.equalsXY = function (a, x, y) { + + return a.x === x && a.y === y; + +}; + +Phaser.Point.fuzzyEquals = function (a, b, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, b.x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, b.y, epsilon); + +}; + +Phaser.Point.fuzzyEqualsXY = function (a, x, y, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, y, epsilon); + +}; + +/** +* Returns the angle between two Point objects. +* +* @method Phaser.Point.angle +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {number} The angle, where b is the vertex. Within [-pi, pi]. +*/ +Phaser.Point.angle = function (a, b) { + + return Math.atan2(a.y - b.y, a.x - b.x); + +}; + +/** +* Creates a negative Point. +* +* @method Phaser.Point.negative +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.negative = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.x, -a.y); + +}; + +/** +* Adds two 2D Points together and multiplies the result by the given scalar. +* +* @method Phaser.Point.multiplyAdd +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} s - The scaling value. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiplyAdd = function (a, b, s, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + b.x * s, a.y + b.y * s); + +}; + +/** +* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. +* +* @method Phaser.Point.interpolate +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.interpolate = function (a, b, f, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f); + +}; + +/** +* Return a perpendicular vector (90 degrees rotation) +* +* @method Phaser.Point.perp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.perp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.y, a.x); + +}; + +/** +* Return a perpendicular vector (-90 degrees rotation) +* +* @method Phaser.Point.rperp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.rperp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y, -a.x); + +}; + +/** +* Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). +* +* @method Phaser.Point.distance +* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. +* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. +* @param {boolean} [round=false] - Round the distance to the nearest integer. +* @return {number} The distance between this Point object and the destination Point object. +*/ +Phaser.Point.distance = function (a, b, round) { + + var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y); + return round ? Math.round(distance) : distance; + +}; + +/** +* Project two Points onto another Point. +* +* @method Phaser.Point.project +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.project = function (a, b, out) { + + if (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; + +}; + +/** +* Project two Points onto a Point of unit length. +* +* @method Phaser.Point.projectUnit +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.projectUnit = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var amt = a.dot(b); + + if (amt !== 0) + { + out.setTo(amt * b.x, amt * b.y); + } + + return out; + +}; + +/** +* Right-hand normalize (make unit length) a Point. +* +* @method Phaser.Point.normalRightHand +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalRightHand = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y * -1, a.x); + +}; + +/** +* Normalize (make unit length) a Point. +* +* @method Phaser.Point.normalize +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalize = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var m = a.getMagnitude(); + + if (m !== 0) + { + out.setTo(a.x / m, a.y / m); + } + + return out; + +}; + +/** +* Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by +* the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument +* is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. +* +* The distance allows you to specify a distance constraint for the rotation between the point and the +* coordinates. If none is given the distance between the two is calculated and used. +* +* @method Phaser.Point.rotate +* @param {Phaser.Point} a - The Point object to rotate. +* @param {number} x - The x coordinate of the anchor point +* @param {number} y - The y coordinate of the anchor point +* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {number} [distance] - An optional distance constraint between the Point and the anchor. +* @return {Phaser.Point} The modified point object. +*/ +Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) { + + if (asDegrees) { angle = Phaser.Math.degToRad(angle); } + + if (distance === undefined) + { + a.subtract(x, y); + + var s = Math.sin(angle); + var c = Math.cos(angle); + + var tx = c * a.x - s * a.y; + var ty = s * a.x + c * a.y; + + a.x = tx + x; + a.y = ty + y; + } + else + { + var t = angle + Math.atan2(a.y - y, a.x - x); + a.x = x + distance * Math.cos(t); + a.y = y + distance * Math.sin(t); + } + + return a; + +}; + +/** +* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. +* +* @method Phaser.Point.centroid +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.centroid = function (points, out) { + + if (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 < pointslength; i++) + { + Phaser.Point.add(out, points[i], out); + } + + out.divide(pointslength, pointslength); + + return out; + +}; + +/** +* Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. +* If the object doesn't contain those properties a Point with x/y of zero will be returned. +* +* @method Phaser.Point.parse +* @static +* @param {object} obj - The object to parse. +* @param {string} [xProp='x'] - The property used to set the Point.x value. +* @param {string} [yProp='y'] - The property used to set the Point.y value. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.parse = function(obj, xProp, yProp) { + + xProp = xProp || 'x'; + yProp = yProp || 'y'; + + var point = new Phaser.Point(); + + if (obj[xProp]) + { + point.x = parseInt(obj[xProp], 10); + } + + if (obj[yProp]) + { + point.y = parseInt(obj[yProp], 10); + } + + return point; + +}; + +/** + * Tests a Point or Point-like object. + * + * @method Phaser.Point.isPoint + * @static + * @return {boolean} - True if the object has numeric x and y properties. + */ +Phaser.Point.isPoint = function(obj) { + + return (obj != null) && (typeof obj.x === 'number') && (typeof obj.y === 'number'); + +}; + +/** +* Sets the `x` and `y` values of an object and returns the object. +* +* @method Phaser.Point#set +* @static +* @param {object} obj - An object with numeric x and y properties. +* @param {number} x - The x value. +* @param {number} [y] - The y value. If not given the x value will be used in its place. +* @return {object} The object. Useful for chaining method calls. +*/ +Phaser.Point.set = function(obj, x, y) { + + obj.x = x || 0; + obj.y = y || ( (y !== 0) ? obj.x : 0 ); + + return obj; + +}; + +/** +* Sorts an array of points in a clockwise direction, relative to a reference point. +* +* The sort is clockwise relative to the display, starting from a 12 o'clock position. +* (In the Cartesian plane, it is anticlockwise, starting from the -y direction.) +* +* Example sequence: (0, -1), (1, 0), (0, 1), (-1, 0) +* +* @method Phaser.Point#sortClockwise +* @static +* @param {array} points - An array of Points or point-like objects (e.g., sprites). +* @param {object|Phaser.Point} [center] - The reference point. If omitted, the {@link #centroid} (midpoint) of the points is used. +* @return {array} The sorted array. +*/ +Phaser.Point.sortClockwise = function(points, center) { + + // Adapted from (ciamej) + + if (!center) + { + center = this.centroid(points); + } + + var cx = center.x; + var cy = center.y; + + var sort = function(a, b) { + if (a.x - cx >= 0 && b.x - cx < 0) + { + return -1; + } + + if (a.x - cx < 0 && b.x - cx >= 0) + { + return 1; + } + + if (a.x - cx === 0 && b.x - cx === 0) + { + if (a.y - cy >= 0 || b.y - cy >= 0) + { + return (a.y > b.y) ? 1 : -1; + } + + return (b.y > a.y) ? 1 : -1; + } + + // Compute the cross product of vectors (center -> a) * (center -> b) + var det = (a.x - cx) * -(b.y - cy) - (b.x - cx) * -(a.y - cy); + + if (det < 0) + { + return -1; + } + + if (det > 0) + { + return 1; + } + + // Points a and b are on the same line from the center + // Check which point is closer to the center + var d1 = (a.x - cx) * (a.x - cx) + (a.y - cy) * (a.y - cy); + var d2 = (b.x - cx) * (b.x - cx) + (b.y - cy) * (b.y - cy); + + return (d1 > d2) ? -1 : 1; + }; + + return points.sort(sort); + +}; + + +// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Point = Phaser.Point; + +/** +* @author Richard Davey +* @author Adrien Brault +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Polygon. +* +* The points can be set from a variety of formats: +* +* - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` +* - An array of objects with public x/y properties: `[obj1, obj2, ...]` +* - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` +* - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` +* - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` +* - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` +* +* @class Phaser.Polygon +* @constructor +* @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. +*/ +Phaser.Polygon = function () { + + /** + * @property {number} area - The area of this Polygon. + */ + this.area = 0; + + /** + * @property {array} _points - An array of Points that make up this Polygon. + * @private + */ + this._points = []; + + if (arguments.length > 0) + { + this.setTo.apply(this, arguments); + } + + /** + * @property {boolean} closed - Is the Polygon closed or not? + */ + this.closed = true; + + /** + * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ? + */ + this.flattened = false; + + /** + * @property {number} type - The base object type. + */ + this.type = Phaser.POLYGON; + +}; + +Phaser.Polygon.prototype = { + + /** + * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] + * + * @method Phaser.Polygon#toNumberArray + * @param {array} [output] - The array to append the points to. If not specified a new array will be created. + * @return {array} The flattened array. + */ + toNumberArray: function (output) { + + if (output === undefined) { output = []; } + + for (var i = 0; i < this._points.length; i++) + { + if (typeof this._points[i] === 'number') + { + output.push(this._points[i]); + output.push(this._points[i + 1]); + i++; + } + else + { + output.push(this._points[i].x); + output.push(this._points[i].y); + } + } + + return output; + + }, + + /** + * Flattens this Polygon so the points are a sequence of numbers. + * Any Point objects found are removed and replaced with two numbers. + * Also sets the Polygon.flattened property to `true`. + * + * @method Phaser.Polygon#flatten + * @return {Phaser.Polygon} This Polygon object + */ + flatten: function () { + + this._points = this.toNumberArray(); + + this.flattened = true; + + return this; + + }, + + /** + * Creates a copy of the given Polygon. + * This is a deep clone, the resulting copy contains new Phaser.Point objects + * + * @method Phaser.Polygon#clone + * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created. + * @return {Phaser.Polygon} The cloned (`output`) polygon object. + */ + clone: function (output) { + + var points = this._points.slice(); + + if (output === undefined || output === null) + { + output = new Phaser.Polygon(points); + } + else + { + output.setTo(points); + } + + return output; + + }, + + /** + * Checks whether the x and y coordinates are contained within this polygon. + * + * @method Phaser.Polygon#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this polygon, otherwise false. + */ + contains: function (x, y) { + + // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva + + var inside = false; + + if (this.flattened) + { + for (var i = -2, j = this._points.length - 2; (i += 2) < this._points.length; j = i) + { + var ix = this._points[i]; + var iy = this._points[i + 1]; + + var jx = this._points[j]; + var jy = this._points[j + 1]; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + + } + else + { + for (var i = -1, j = this._points.length - 1; ++i < this._points.length; j = i) + { + var ix = this._points[i].x; + var iy = this._points[i].y; + + var jx = this._points[j].x; + var jy = this._points[j].y; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + } + + return inside; + + }, + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` + * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` + * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` + * + * `setTo` may also be called without any arguments to remove all points. + * + * @method Phaser.Polygon#setTo + * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. + * @return {Phaser.Polygon} This Polygon object + */ + setTo: function (points) { + + this.area = 0; + this._points = []; + + if (arguments.length > 0) + { + // If points isn't an array, use arguments as the array + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments); + } + + var y0 = Number.MAX_VALUE; + + // Allows for mixed-type arguments + for (var i = 0, len = points.length; i < len; i++) + { + if (typeof points[i] === 'number') + { + var p = new PIXI.Point(points[i], points[i + 1]); + i++; + } + else if (Array.isArray(points[i])) + { + var p = new PIXI.Point(points[i][0], points[i][1]); + } + else + { + var p = new PIXI.Point(points[i].x, points[i].y); + } + + this._points.push(p); + + // Lowest boundary + if (p.y < y0) + { + y0 = p.y; + } + } + + this.calculateArea(y0); + } + + return this; + + }, + + /** + * Calcuates the area of the Polygon. This is available in the property Polygon.area + * + * @method Phaser.Polygon#calculateArea + * @private + * @param {number} y0 - The lowest boundary + * @return {number} The area of the Polygon. + */ + calculateArea: function (y0) { + + var p1; + var p2; + var avgHeight; + var width; + + for (var i = 0, len = this._points.length; i < len; i++) + { + p1 = this._points[i]; + + if (i === len - 1) + { + p2 = this._points[0]; + } + else + { + p2 = this._points[i + 1]; + } + + avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2; + width = p1.x - p2.x; + this.area += avgHeight * width; + } + + return this.area; + + } + +}; + +Phaser.Polygon.prototype.constructor = Phaser.Polygon; + +/** +* The points of this polygon. +* +* You can modify these with {@link Phaser.Polygon#setTo setTo}. +* +* @name Phaser.Polygon#points +* @property {Phaser.Point[]} points - The array of vertex points. +* @readonly +*/ +Object.defineProperty(Phaser.Polygon.prototype, 'points', { + + get: function() { + return this._points; + } + +}); + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Polygon = Phaser.Polygon; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. +* If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. +* +* @class Phaser.Rectangle +* @constructor +* @param {number} x - The x coordinate of the top-left corner of the Rectangle. +* @param {number} y - The y coordinate of the top-left corner of the Rectangle. +* @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. +*/ +Phaser.Rectangle = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.RECTANGLE; + +}; + +Phaser.Rectangle.prototype = { + + /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method Phaser.Rectangle#offset + * @param {number} dx - Moves the x value of the Rectangle object by this amount. + * @param {number} dy - Moves the y value of the Rectangle object by this amount. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Rectangle#offsetPoint + * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offsetPoint: function (point) { + + return this.offset(point.x, point.y); + + }, + + /** + * Sets the members of Rectangle to the specified values. + * @method Phaser.Rectangle#setTo + * @param {number} x - The x coordinate of the top-left corner of the Rectangle. + * @param {number} y - The y coordinate of the top-left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Scales the width and height of this Rectangle by the given amounts. + * + * @method Phaser.Rectangle#scale + * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. + * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. + * @return {Phaser.Rectangle} This Rectangle object + */ + scale: function (x, y) { + + if (y === undefined) { y = x; } + + this.width *= x; + this.height *= y; + + return this; + + }, + + /** + * Centers this Rectangle so that the center coordinates match the given x and y values. + * + * @method Phaser.Rectangle#centerOn + * @param {number} x - The x coordinate to place the center of the Rectangle at. + * @param {number} y - The y coordinate to place the center of the Rectangle at. + * @return {Phaser.Rectangle} This Rectangle object + */ + centerOn: function (x, y) { + + this.centerX = x; + this.centerY = y; + + return this; + + }, + + /** + * Runs Math.floor() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#floor + */ + floor: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + + }, + + /** + * Runs Math.floor() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#floorAll + */ + floorAll: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.width = Math.floor(this.width); + this.height = Math.floor(this.height); + + }, + + /** + * Runs Math.ceil() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#ceil + */ + ceil: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + + }, + + /** + * Runs Math.ceil() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#ceilAll + */ + ceilAll: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.width = Math.ceil(this.width); + this.height = Math.ceil(this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the left, top, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFromBounds + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFromBounds: function(source) { + + return this.setTo(source.left, source.top, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Rectangle to any given object. + * @method Phaser.Rectangle#copyTo + * @param {any} source - The object to copy to. + * @return {object} This object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method Phaser.Rectangle#inflate + * @param {number} dx - The amount to be added to the left side of the Rectangle. + * @param {number} dy - The amount to be added to the bottom side of the Rectangle. + * @return {Phaser.Rectangle} This Rectangle object. + */ + inflate: function (dx, dy) { + + return Phaser.Rectangle.inflate(this, dx, dy); + + }, + + /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method Phaser.Rectangle#size + * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object. + */ + size: function (output) { + + return Phaser.Rectangle.size(this, output); + + }, + + /** + * Resize the Rectangle by providing a new width and height. + * The x and y positions remain unchanged. + * + * @method Phaser.Rectangle#resize + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method Phaser.Rectangle#clone + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ + clone: function (output) { + + return Phaser.Rectangle.clone(this, output); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method Phaser.Rectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + contains: function (x, y) { + + return Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method Phaser.Rectangle#containsRect + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + containsRect: function (b) { + + return Phaser.Rectangle.containsRect(b, this); + + }, + + /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method Phaser.Rectangle#equals + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + */ + equals: function (b) { + + return Phaser.Rectangle.equals(this, b); + + }, + + /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method Phaser.Rectangle#intersection + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ + intersection: function (b, out) { + + return Phaser.Rectangle.intersection(this, b, out); + + }, + + /** + * Determines whether this Rectangle and another given Rectangle intersect with each other. + * This method checks the x, y, width, and height properties of the two Rectangles. + * + * @method Phaser.Rectangle#intersects + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + */ + intersects: function (b) { + + return Phaser.Rectangle.intersects(this, b); + + }, + + /** + * Determines whether the coordinates given intersects (overlaps) with this Rectangle. + * + * @method Phaser.Rectangle#intersectsRaw + * @param {number} left - The x coordinate of the left of the area. + * @param {number} right - The right coordinate of the area. + * @param {number} top - The y coordinate of the area. + * @param {number} bottom - The bottom coordinate of the area. + * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 + * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + */ + intersectsRaw: function (left, right, top, bottom, tolerance) { + + return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance); + + }, + + /** + * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. + * @method Phaser.Rectangle#union + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ + union: function (b, out) { + + return Phaser.Rectangle.union(this, b, out); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Rectangle. + * + * @method Phaser.Rectangle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = this.randomX; + out.y = this.randomY; + + return out; + + }, + + /** + * Returns a point based on the given position constant, which can be one of: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * This method returns the same values as calling Rectangle.bottomLeft, etc, but those + * calls always create a new Point object, where-as this one allows you to use your own. + * + * @method Phaser.Rectangle#getPoint + * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. + * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the point in its `x` and `y` properties. + */ + getPoint: function (position, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + return out.set(this.x, this.y); + + case Phaser.TOP_CENTER: + return out.set(this.centerX, this.y); + + case Phaser.TOP_RIGHT: + return out.set(this.right, this.y); + + case Phaser.LEFT_CENTER: + return out.set(this.x, this.centerY); + + case Phaser.CENTER: + return out.set(this.centerX, this.centerY); + + case Phaser.RIGHT_CENTER: + return out.set(this.right, this.centerY); + + case Phaser.BOTTOM_LEFT: + return out.set(this.x, this.bottom); + + case Phaser.BOTTOM_CENTER: + return out.set(this.centerX, this.bottom); + + case Phaser.BOTTOM_RIGHT: + return out.set(this.right, this.bottom); + } + + }, + + /** + * Creates or positions four {@link Phaser.Line} lines representing the Rectangle's sides. + * + * @method Phaser.Rectangle#sides + * @param {Phaser.Line} [top] + * @param {Phaser.Line} [right] + * @param {Phaser.Line} [bottom] + * @param {Phaser.Line} [left] + * @return {?Phaser.Line[]} - An array containing four lines (if no arguments were given), or null. + */ + sides: function (top, right, bottom, left) { + + if (!arguments.length) { + top = new Phaser.Line(); + right = new Phaser.Line(); + bottom = new Phaser.Line(); + left = new Phaser.Line(); + } + + var x1 = this.x; + var y1 = this.y; + var x2 = this.right; + var y2 = this.bottom; + + top.setTo(x1, y1, x2, y1); + right.setTo(x2, y1, x2, y2); + bottom.setTo(x1, y2, x2, y2); + left.setTo(x1, y1, x1, y2); + + if (!arguments.length) { + return [top, right, bottom, left]; + } + + return null; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Rectangle#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + + } + +}; + +/** +* @name Phaser.Rectangle#halfWidth +* @property {number} halfWidth - Half of the width of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", { + + get: function () { + return Math.round(this.width / 2); + } + +}); + +/** +* @name Phaser.Rectangle#halfHeight +* @property {number} halfHeight - Half of the height of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", { + + get: function () { + return Math.round(this.height / 2); + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. +* @name Phaser.Rectangle#bottom +* @property {number} bottom - The sum of the y and height properties. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value <= this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + + } + +}); + +/** +* The location of the Rectangles bottom left corner as a Point object. +* @name Phaser.Rectangle#bottomLeft +* @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", { + + get: function () { + return new Phaser.Point(this.x, this.bottom); + }, + + set: function (value) { + this.x = value.x; + this.bottom = value.y; + } + +}); + +/** +* The location of the Rectangles bottom right corner as a Point object. +* @name Phaser.Rectangle#bottomRight +* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", { + + get: function () { + return new Phaser.Point(this.right, this.bottom); + }, + + set: function (value) { + this.right = value.x; + this.bottom = value.y; + } + +}); + +/** +* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. +* @name Phaser.Rectangle#left +* @property {number} left - The x coordinate of the left of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + if (value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + } + +}); + +/** +* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. +* @name Phaser.Rectangle#right +* @property {number} right - The sum of the x and width properties. +*/ +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 = value - this.x; + } + } + +}); + +/** +* The volume of the Rectangle derived from width * height. +* @name Phaser.Rectangle#volume +* @property {number} volume - The volume of the Rectangle derived from width * height. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "volume", { + + get: function () { + return this.width * this.height; + } + +}); + +/** +* The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @name Phaser.Rectangle#perimeter +* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", { + + get: function () { + return (this.width * 2) + (this.height * 2); + } + +}); + +/** +* The x coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerX +* @property {number} centerX - The x coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerX", { + + get: function () { + return this.x + this.halfWidth; + }, + + set: function (value) { + this.x = value - this.halfWidth; + } + +}); + +/** +* The y coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerY +* @property {number} centerY - The y coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerY", { + + get: function () { + return this.y + this.halfHeight; + }, + + set: function (value) { + this.y = value - this.halfHeight; + } + +}); + +/** +* A random value between the left and right values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomX +* @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomX", { + + get: function () { + + return this.x + (Math.random() * this.width); + + } + +}); + +/** +* A random value between the top and bottom values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomY +* @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomY", { + + get: function () { + + return this.y + (Math.random() * this.height); + + } + +}); + +/** +* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. +* However it does affect the height property, whereas changing the y value does not affect the height property. +* @name Phaser.Rectangle#top +* @property {number} top - The y coordinate of the top of the Rectangle. +*/ +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); + } + } + +}); + +/** +* The location of the Rectangles top left corner as a Point object. +* @name Phaser.Rectangle#topLeft +* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. +*/ +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; + } + +}); + +/** +* The location of the Rectangles top right corner as a Point object. +* @name Phaser.Rectangle#topRight +* @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "topRight", { + + get: function () { + return new Phaser.Point(this.x + this.width, this.y); + }, + + set: function (value) { + this.right = value.x; + this.y = value.y; + } + +}); + +/** +* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. +* If set to true then all of the Rectangle properties are set to 0. +* @name Phaser.Rectangle#empty +* @property {boolean} empty - Gets or sets the Rectangles empty state. +*/ +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; + +/** +* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. +* @method Phaser.Rectangle.inflate +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} dx - The amount to be added to the left side of the Rectangle. +* @param {number} dy - The amount to be added to the bottom side of the Rectangle. +* @return {Phaser.Rectangle} This Rectangle object. +*/ +Phaser.Rectangle.inflate = function (a, dx, dy) { + + a.x -= dx; + a.width += 2 * dx; + a.y -= dy; + a.height += 2 * dy; + + return a; + +}; + +/** +* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. +* @method Phaser.Rectangle.inflatePoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. +* @return {Phaser.Rectangle} The Rectangle object. +*/ +Phaser.Rectangle.inflatePoint = function (a, point) { + + return Phaser.Rectangle.inflate(a, point.x, point.y); + +}; + +/** +* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. +* @method Phaser.Rectangle.size +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. +* @return {Phaser.Point} The size of the Rectangle object +*/ +Phaser.Rectangle.size = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(a.width, a.height); + } + else + { + output.setTo(a.width, a.height); + } + + return output; + +}; + +/** +* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. +* @method Phaser.Rectangle.clone +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.clone = function (a, output) { + + if (output === undefined || output === null) + { + 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; + +}; + +/** +* Returns a new Rectangle object with the same values for the left, top, width, and height properties as the original object. +* @method Phaser.Rectangle.createFromBounds +* @param {any} a - An object with `left`, `top`, `width`, and `height` properties. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.createFromBounds = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Rectangle(a.x, a.y, a.width, a.height); + } + + return output.copyFromBounds(a); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by this Rectangle object. +* @method Phaser.Rectangle.contains +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +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); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by the given raw values. +* @method Phaser.Rectangle.containsRaw +* @param {number} rx - The x coordinate of the top left of the area. +* @param {number} ry - The y coordinate of the top left of the area. +* @param {number} rw - The width of the area. +* @param {number} rh - The height of the area. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) { + + return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh)); + +}; + +/** +* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. +* @method Phaser.Rectangle.containsPoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsPoint = function (a, point) { + + return Phaser.Rectangle.contains(a, point.x, point.y); + +}; + +/** +* Determines whether the first Rectangle object is fully contained within the second Rectangle object. +* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. +* @method Phaser.Rectangle.containsRect +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRect = function (a, b) { + + // If the given rect has a larger volume than this one then it can never contain it + if (a.volume > b.volume) + { + return false; + } + + return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom); + +}; + +/** +* Determines whether the two Rectangles are equal. +* This method compares the x, y, width and height properties of each Rectangle. +* @method Phaser.Rectangle.equals +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. +*/ +Phaser.Rectangle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height); + +}; + +/** +* Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. +* @method Phaser.Rectangle.sameDimensions +* @param {Rectangle-like} a - The first Rectangle object. +* @param {Rectangle-like} b - The second Rectangle object. +* @return {boolean} True if the object have equivalent values for the width and height properties. +*/ +Phaser.Rectangle.sameDimensions = function (a, b) { + + return (a.width === b.width && a.height === b.height); + +}; + +/** +* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. +* @method Phaser.Rectangle.intersection +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. +*/ +Phaser.Rectangle.intersection = function (a, b, output) { + + if (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; + +}; + +/** +* Determines whether the two Rectangles intersect with each other. +* This method checks the x, y, width, and height properties of the Rectangles. +* @method Phaser.Rectangle.intersects +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. +*/ +Phaser.Rectangle.intersects = function (a, b) { + + if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) + { + return false; + } + + return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom); + +}; + +/** +* Determines whether the object specified intersects (overlaps) with the given values. +* @method Phaser.Rectangle.intersectsRaw +* @param {number} left - The x coordinate of the left of the area. +* @param {number} right - The right coordinate of the area. +* @param {number} top - The y coordinate of the area. +* @param {number} bottom - The bottom coordinate of the area. +* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 +* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. +*/ +Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) { + + if (tolerance === undefined) { tolerance = 0; } + + return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); + +}; + +/** +* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. +* @method Phaser.Rectangle.union +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. +*/ +Phaser.Rectangle.union = function (a, b, output) { + + if (output === undefined) + { + output = new Phaser.Rectangle(); + } + + return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top)); + +}; + +/** +* Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. +* +* @method Phaser.Rectangle#aabb +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. +* @return {Phaser.Rectangle} The new Rectangle object. +* @static +*/ +Phaser.Rectangle.aabb = function(points, out) { + + if (out === undefined) { + out = new Phaser.Rectangle(); + } + + var xMax = Number.NEGATIVE_INFINITY, + xMin = Number.POSITIVE_INFINITY, + yMax = Number.NEGATIVE_INFINITY, + yMin = Number.POSITIVE_INFINITY; + + points.forEach(function(point) { + if (point.x > xMax) { + xMax = point.x; + } + if (point.x < xMin) { + xMin = point.x; + } + + if (point.y > yMax) { + yMax = point.y; + } + if (point.y < yMin) { + yMin = point.y; + } + }); + + out.setTo(xMin, yMin, xMax - xMin, yMax - yMin); + + return out; +}; + +// Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Rectangle = Phaser.Rectangle; +PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0); + +/** +* @author Mat Groves http://matgroves.com/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Rounded Rectangle object is an area defined by its position and has nice rounded corners, +* as indicated by its top-left corner point (x, y) and by its width and its height. +* +* @class Phaser.RoundedRectangle +* @constructor +* @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle. +* @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle. +* @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value. +* @param {number} [radius=20] - Controls the radius of the rounded corners. +*/ +Phaser.RoundedRectangle = function(x, y, width, height, radius) +{ + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + if (radius === undefined) { radius = 20; } + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} radius - The radius of the rounded corners. + */ + this.radius = radius || 20; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROUNDEDRECTANGLE; +}; + +Phaser.RoundedRectangle.prototype = { + + /** + * Returns a new RoundedRectangle object with the same values for the x, y, width, height and + * radius properties as this RoundedRectangle object. + * + * @method Phaser.RoundedRectangle#clone + * @return {Phaser.RoundedRectangle} + */ + clone: function () { + + return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. + * + * @method Phaser.RoundedRectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. + */ + 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; + + } + +}; + +Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle; + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.RoundedRectangle = Phaser.RoundedRectangle; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. +* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y +* +* @class Phaser.Camera +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera +* @param {number} x - Position of the camera on the X axis +* @param {number} y - Position of the camera on the Y axis +* @param {number} width - The width of the view rectangle +* @param {number} height - The height of the view rectangle +*/ +Phaser.Camera = function (game, id, x, y, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + */ + this.world = game.world; + + /** + * @property {number} id - Reserved for future multiple camera set-ups. + * @default + */ + this.id = 0; + + /** + * Camera view. + * The view into the world we wish to render (by default the game dimensions). + * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. + * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. + * @property {Phaser.Rectangle} view + */ + this.view = new Phaser.Rectangle(x, y, width, height); + + /** + * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. + * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound + * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. + * + * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. + */ + this.bounds = new Phaser.Rectangle(x, y, width, height); + + /** + * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move. + */ + this.deadzone = null; + + /** + * @property {boolean} visible - Whether this camera is visible or not. + * @default + */ + this.visible = true; + + /** + * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. + * @default + */ + this.roundPx = true; + + /** + * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. + */ + this.atLimit = { x: false, y: false }; + + /** + * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. + * @default + */ + this.target = null; + + /** + * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot. + */ + this.displayObject = null; + + /** + * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot. + */ + this.scale = null; + + /** + * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. + * @readonly + */ + this.totalInView = 0; + + /** + * The linear interpolation value to use when following a target. + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * @property {Phaser.Point} lerp + * @default + */ + this.lerp = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes. + */ + this.onShakeComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes. + */ + this.onFlashComplete = new Phaser.Signal(); + + /** + * This signal is dispatched when the camera fade effect completes. + * When the fade effect completes you will be left with the screen black (or whatever + * color you faded to). In order to reset this call `Camera.resetFX`. This is called + * automatically when you change State. + * @property {Phaser.Signal} onFadeComplete + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * The Graphics object used to handle camera fx such as fade and flash. + * @property {Phaser.Graphics} fx + * @protected + */ + this.fx = null; + + /** + * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position. + * @private + */ + this._targetPosition = new Phaser.Point(); + + /** + * @property {number} edge - Edge property. + * @private + * @default + */ + this._edge = 0; + + /** + * @property {Phaser.Point} position - Current position of the camera in world. + * @private + * @default + */ + this._position = new Phaser.Point(); + + /** + * @property {Object} _shake - The shake effect container. + * @private + */ + this._shake = { + intensity: 0, + duration: 0, + horizontal: false, + vertical: false, + shakeBounds: true, + x: 0, + y: 0 + }; + + /** + * @property {number} _fxDuration - FX duration timer. + * @private + */ + this._fxDuration = 0; + + /** + * @property {number} _fxType - The FX type running. + * @private + */ + this._fxType = 0; + + /** + * @property {Phaser.Rectangle} + * @private + */ + this._fixedView = new Phaser.Rectangle(); + +}; + +/** +* A follow style that uses no deadzone. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_LOCKON = 0; + +/** +* A follow style that uses a tall, narrow deadzone (0.33 x 0.125) with a center slightly above the view center. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_PLATFORMER = 1; + +/** +* A follow style that uses a square deadzone (0.25 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN = 2; + +/** +* A follow style that uses a small square deadzone (0.125 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_BOTH = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_HORIZONTAL = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_VERTICAL = 6; + +/** +* @constant +* @type {boolean} +*/ +Phaser.Camera.ENABLE_FX = true; + +Phaser.Camera.prototype = { + + /** + * Called automatically by Phaser.World. + * + * @method Phaser.Camera#boot + * @private + */ + boot: function () { + + this.displayObject = this.game.world; + + this.scale = this.game.world.scale; + + this.game.camera = this; + + if (Phaser.Graphics && Phaser.Camera.ENABLE_FX) + { + this.fx = new Phaser.Graphics(this.game); + + this.game.stage.addChild(this.fx); + } + + }, + + /** + * Camera preUpdate. Sets the total view counter to zero. + * + * @method Phaser.Camera#preUpdate + */ + preUpdate: function () { + + this.totalInView = 0; + + }, + + /** + * Tell the camera which sprite to follow. + * + * You can set the follow type and a linear interpolation value. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. + * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. + * + * @method Phaser.Camera#follow + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything. + * @param {number} [style] - Leverage one of the existing {@link deadzone} presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + */ + follow: function (target, style, lerpX, lerpY) { + + if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; } + if (lerpX === undefined) { lerpX = 1; } + if (lerpY === undefined) { lerpY = 1; } + + this.target = target; + this.lerp.set(lerpX, lerpY); + + var helper; + + switch (style) { + + case Phaser.Camera.FOLLOW_PLATFORMER: + var w = this.width / 8; + var h = this.height / 3; + this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN: + helper = Math.max(this.width, this.height) / 4; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT: + helper = Math.max(this.width, this.height) / 8; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_LOCKON: + this.deadzone = null; + break; + + default: + this.deadzone = null; + break; + } + + }, + + /** + * Sets the Camera follow target to null, stopping it from following an object if it's doing so. + * + * @method Phaser.Camera#unfollow + */ + unfollow: function () { + + this.target = null; + + }, + + /** + * Move the camera focus on a display object instantly. + * @method Phaser.Camera#focusOn + * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. + */ + focusOn: function (displayObject) { + + this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight)); + + }, + + /** + * Move the camera focus on a location instantly. + * @method Phaser.Camera#focusOnXY + * @param {number} x - X position. + * @param {number} y - Y position. + */ + focusOnXY: function (x, y) { + + this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight)); + + }, + + /** + * This creates a camera shake effect. It works by applying a random amount of additional + * spacing on the x and y axis each frame. You can control the intensity and duration + * of the effect, and if it should effect both axis or just one. + * + * When the shake effect ends the signal Camera.onShakeComplete is dispatched. + * + * @method Phaser.Camera#shake + * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. + * @param {number} [duration=500] - The duration of the shake effect in milliseconds. + * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL. + * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?). + * @return {boolean} True if the shake effect was started, otherwise false. + */ + shake: function (intensity, duration, force, direction, shakeBounds) { + + if (intensity === undefined) { intensity = 0.05; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = true; } + if (direction === undefined) { direction = Phaser.Camera.SHAKE_BOTH; } + if (shakeBounds === undefined) { shakeBounds = true; } + + if (!force && this._shake.duration > 0) + { + // Can't reset an already running shake + return false; + } + + this._shake.intensity = intensity; + this._shake.duration = duration; + this._shake.shakeBounds = shakeBounds; + + this._shake.x = 0; + this._shake.y = 0; + + this._shake.horizontal = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_HORIZONTAL); + this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL); + + return true; + + }, + + /** + * This creates a camera flash effect. It works by filling the game with the solid fill + * color specified, and then fading it away to alpha 0 over the duration given. + * + * You can use this for things such as hit feedback effects. + * + * When the effect ends the signal Camera.onFlashComplete is dispatched. + * + * @method Phaser.Camera#flash + * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the flash effect in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the flash effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + flash: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0xffffff; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 1; + + this._fxDuration = duration; + this._fxType = 0; + + return true; + + }, + + /** + * This creates a camera fade effect. It works by filling the game with the + * color specified, over the duration given, ending with a solid fill. + * + * You can use this for things such as transitioning to a new scene. + * + * The game will be left 'filled' at the end of this effect, likely obscuring + * everything. In order to reset it you can call `Camera.resetFX` and it will clear the + * fade. Or you can call `Camera.flash` with the same color as the fade, and it will + * reverse the process, bringing the game back into view again. + * + * When the effect ends the signal Camera.onFadeComplete is dispatched. + * + * @method Phaser.Camera#fade + * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the fade in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the fade effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + fade: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0x000000; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 0; + + this._fxDuration = duration; + this._fxType = 1; + + return true; + + }, + + /** + * The camera update loop. This is called automatically by the core game loop. + * + * @method Phaser.Camera#update + * @protected + */ + update: function () { + + if (this._fxDuration > 0) + { + this.updateFX(); + } + + if (this._shake.duration > 0) + { + this.updateShake(); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + this._shake.x = Math.floor(this._shake.x); + this._shake.y = Math.floor(this._shake.y); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the camera flash and fade effects. + * + * @method Phaser.Camera#updateFX + * @private + */ + updateFX: function () { + + if (this._fxType === 0) + { + // flash + this.fx.alpha -= this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha <= 0) + { + this._fxDuration = 0; + this.fx.alpha = 0; + this.onFlashComplete.dispatch(); + } + } + else + { + // fade + this.fx.alpha += this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha >= 1) + { + this._fxDuration = 0; + this.fx.alpha = 1; + this.onFadeComplete.dispatch(); + } + } + + }, + + /** + * Update the camera shake effect. + * + * @method Phaser.Camera#updateShake + * @private + */ + updateShake: function () { + + this._shake.duration -= this.game.time.elapsedMS; + + if (this._shake.duration <= 0) + { + this.onShakeComplete.dispatch(); + this._shake.x = 0; + this._shake.y = 0; + } + else + { + if (this._shake.horizontal) + { + this._shake.x = this.game.rnd.frac() * this._shake.intensity * this.view.width * 2 - this._shake.intensity * this.view.width; + } + + if (this._shake.vertical) + { + this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height; + } + } + + }, + + /** + * Internal method that handles tracking a sprite. + * + * @method Phaser.Camera#updateTarget + * @private + */ + updateTarget: function () { + + this._targetPosition.x = this.view.x + this.target.worldPosition.x; + this._targetPosition.y = this.view.y + this.target.worldPosition.y; + + if (this.deadzone) + { + this._edge = this._targetPosition.x - this.view.x; + + if (this._edge < this.deadzone.left) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.left, this.lerp.x); + } + else if (this._edge > this.deadzone.right) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.right, this.lerp.x); + } + + this._edge = this._targetPosition.y - this.view.y; + + if (this._edge < this.deadzone.top) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.top, this.lerp.y); + } + else if (this._edge > this.deadzone.bottom) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.bottom, this.lerp.y); + } + } + else + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.view.halfWidth, this.lerp.x); + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.view.halfHeight, this.lerp.y); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the Camera bounds to match the game world. + * + * @method Phaser.Camera#setBoundsToWorld + */ + setBoundsToWorld: function () { + + if (this.bounds) + { + this.bounds.copyFrom(this.game.world.bounds); + } + + }, + + /** + * Method called to ensure the camera doesn't venture outside of the game world. + * Called automatically by Camera.update. + * + * @method Phaser.Camera#checkBounds + * @protected + */ + checkBounds: function () { + + this.atLimit.x = false; + this.atLimit.y = false; + + var vx = this.view.x + this._shake.x; + var vw = this.view.right + this._shake.x; + var vy = this.view.y + this._shake.y; + var vh = this.view.bottom + this._shake.y; + + // Make sure we didn't go outside the cameras bounds + if (vx <= this.bounds.x * this.scale.x) + { + this.atLimit.x = true; + this.view.x = this.bounds.x * this.scale.x; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + else if (vw >= this.bounds.right * this.scale.x) + { + this.atLimit.x = true; + this.view.x = (this.bounds.right * this.scale.x) - this.width; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + + if (vy <= this.bounds.top * this.scale.y) + { + this.atLimit.y = true; + this.view.y = this.bounds.top * this.scale.y; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + else if (vh >= this.bounds.bottom * this.scale.y) + { + this.atLimit.y = true; + this.view.y = (this.bounds.bottom * this.scale.y) - this.height; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + + }, + + /** + * A helper function to set both the X and Y properties of the camera at once + * without having to use game.camera.x and game.camera.y. + * + * @method Phaser.Camera#setPosition + * @param {number} x - X position. + * @param {number} y - Y position. + */ + setPosition: function (x, y) { + + this.view.x = x; + this.view.y = y; + + if (this.bounds) + { + this.checkBounds(); + } + + }, + + /** + * Sets the size of the view rectangle given the width and height in parameters. + * + * @method Phaser.Camera#setSize + * @param {number} width - The desired width. + * @param {number} height - The desired height. + */ + setSize: function (width, height) { + + this.view.width = width; + this.view.height = height; + + }, + + /** + * Resets the camera back to 0,0 and un-follows any object it may have been tracking. + * Also immediately resets any camera effects that may have been running such as + * shake, flash or fade. + * + * @method Phaser.Camera#reset + */ + reset: function () { + + this.target = null; + + this.view.x = 0; + this.view.y = 0; + + this._shake.duration = 0; + this._shake.x = 0; + this._shake.y = 0; + + this.resetFX(); + + }, + + /** + * Resets any active FX, such as a fade or flash and immediately clears it. + * Useful to calling after a fade in order to remove the fade from the Stage. + * + * @method Phaser.Camera#resetFX + */ + resetFX: function () { + + if (this.fx) + { + this.fx.clear(); + this.fx.alpha = 0; + } + + this._fxDuration = 0; + + } + +}; + +Phaser.Camera.prototype.constructor = Phaser.Camera; + +/** +* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#x +* @property {number} x - Gets or sets the cameras x position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "x", { + + get: function () { + + return this.view.x; + + }, + + set: function (value) { + + this.view.x = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#y +* @property {number} y - Gets or sets the cameras y position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "y", { + + get: function () { + + return this.view.y; + + }, + + set: function (value) { + + this.view.y = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras position. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#position +* @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object. +*/ +Object.defineProperty(Phaser.Camera.prototype, "position", { + + get: function () { + + this._position.set(this.view.x, this.view.y); + + return this._position; + + }, + + set: function (value) { + + if (typeof value.x !== "undefined") { this.view.x = value.x; } + if (typeof value.y !== "undefined") { this.view.y = value.y; } + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras width. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#width +* @property {number} width - Gets or sets the cameras width. +*/ +Object.defineProperty(Phaser.Camera.prototype, "width", { + + get: function () { + + return this.view.width; + + }, + + set: function (value) { + + this.view.width = value; + + } + +}); + +/** +* The Cameras height. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#height +* @property {number} height - Gets or sets the cameras height. +*/ +Object.defineProperty(Phaser.Camera.prototype, "height", { + + get: function () { + + return this.view.height; + + }, + + set: function (value) { + + this.view.height = value; + + } + +}); + + +/** +* The Cameras shake intensity. +* @name Phaser.Camera#shakeIntensity +* @property {number} shakeIntensity - Gets or sets the cameras shake intensity. +*/ +Object.defineProperty(Phaser.Camera.prototype, "shakeIntensity", { + + get: function () { + + return this._shake.intensity; + + }, + + set: function (value) { + + this._shake.intensity = value; + + } + +}); + + +/** + * Immobile {@link #view} rectangle. Its top-left is always (0, 0). You can use this align fixedToCamera objects. + * @name Phaser.Camera#fixedView + * @property {Phaser.Rectangle} fixedView + * @readonly + */ +Object.defineProperty(Phaser.Camera.prototype, "fixedView", { + + get: function () { + + this._fixedView.setTo(0, 0, this.view.width, this.view.height); + + return this._fixedView; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base State class which can be extended if you are creating your own game. +* It provides quick access to common functions such as the camera, cache, input, match, sound and more. +* +* #### Callbacks +* +* | start | preload | loaded | paused | stop | +* |-------|-------------|------------|--------------|----------| +* | init | | | | | +* | | preload | create | paused | | +* | | loadUpdate* | update* | pauseUpdate* | | +* | | | preRender* | | | +* | | loadRender* | render* | render* | | +* | | | | resumed | | +* | | | | | shutdown | +* +* Update and render calls (*) are repeated. +* +* If your State has a constructor, it will be invoked exactly once, during {@link {@link Phaser.StateManager#add}. +* +* @class Phaser.State +* @constructor +*/ +Phaser.State = function () { + + /** + * @property {Phaser.Game} game - This is a reference to the currently running Game. + */ + this.game = null; + + /** + * @property {string} key - The string based identifier given to the State when added into the State Manager. + */ + this.key = ''; + + /** + * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects. + */ + this.make = null; + + /** + * @property {Phaser.Camera} camera - A handy reference to World.camera. + */ + this.camera = null; + + /** + * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - A reference to the Input Manager. + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions. + */ + this.math = null; + + /** + * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. + */ + this.sound = null; + + /** + * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays. + */ + this.scale = null; + + /** + * @property {Phaser.Stage} stage - A reference to the Stage. + */ + this.stage = null; + + /** + * @property {Phaser.StateManager} stage - A reference to the State Manager, which controls state changes. + */ + this.state = null; + + /** + * @property {Phaser.Time} time - A reference to the game clock and timed events system. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - A reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. + */ + this.world = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. + */ + this.particles = null; + + /** + * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser. + */ + this.physics = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator. + */ + this.rnd = null; + +}; + +Phaser.State.prototype = { + + /** + * init is the very first function called when your State starts up. It's called before preload, create or anything else. + * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables + * or objects before the preloading starts. + * + * @method Phaser.State#init + * @param {...any} args - Any extra arguments passed to {@link Phaser.StateManager#start} or {@link Phaser.StateManager#restart}. + */ + init: function () { + }, + + /** + * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) + * You shouldn't create any objects in this method that require assets that you're also loading in this method, as + * they won't yet be available. + * + * @method Phaser.State#preload + * @param {Phaser.Game} game + */ + preload: function () { + }, + + /** + * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * + * @method Phaser.State#loadUpdate + * @param {Phaser.Game} game + */ + loadUpdate: function () { + }, + + /** + * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. + * + * @method Phaser.State#loadRender + * @param {Phaser.Game} game + */ + loadRender: function () { + }, + + /** + * create is called once preload has completed, this includes the loading of any assets from the Loader. + * If you don't have a preload method then create is the first method called in your State. + * + * @method Phaser.State#create + * @param {Phaser.Game} game + */ + create: function () { + }, + + /** + * The update method is left empty for your own use. + * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. + * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. + * + * @method Phaser.State#update + * @param {Phaser.Game} game + */ + update: function () { + }, + + /** + * The preRender method is called after all Game Objects have been updated, but before any rendering takes place. + * + * @method Phaser.State#preRender + * @param {Phaser.Game} game + * @param {number} elapsedTime + */ + preRender: function () { + }, + + /** + * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. + * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any + * final post-processing style effects here. Note that this happens before plugins postRender takes place. + * + * @method Phaser.State#render + * @param {Phaser.Game} game + */ + render: function () { + }, + + /** + * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. + * + * @method Phaser.State#resize + * @param {number} width + * @param {number} height + */ + resize: function () { + }, + + /** + * This method will be called if the core game loop is paused. + * + * @method Phaser.State#paused + * @param {Phaser.Game} game + */ + paused: function () { + }, + + /** + * This method will be called when the core game loop resumes from a paused state. + * + * @method Phaser.State#resumed + * @param {Phaser.Game} game + */ + resumed: function () { + }, + + /** + * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. + * + * @method Phaser.State#pauseUpdate + * @param {Phaser.Game} game + */ + pauseUpdate: function () { + }, + + /** + * This method will be called when the State is shutdown (i.e. you switch to another state from this one). + * + * @method Phaser.State#shutdown + * @param {Phaser.Game} game + */ + shutdown: function () { + } + +}; + +Phaser.State.prototype.constructor = Phaser.State; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The State Manager is responsible for loading, setting up and switching game states. +* +* @class Phaser.StateManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. +*/ +Phaser.StateManager = function (game, pendingState) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {object} states - The object containing Phaser.States. + */ + this.states = {}; + + /** + * @property {Phaser.State} _pendingState - The state to be switched to in the next frame. + * @private + */ + this._pendingState = null; + + if (typeof pendingState !== 'undefined' && pendingState !== null) + { + this._pendingState = pendingState; + } + + /** + * @property {boolean} _clearWorld - Clear the world when we switch state? + * @private + */ + this._clearWorld = false; + + /** + * @property {boolean} _clearCache - Clear the cache when we switch state? + * @private + */ + this._clearCache = false; + + /** + * @property {boolean} _created - Flag that sets if the State has been created or not. + * @private + */ + this._created = false; + + /** + * @property {any[]} _args - Temporary container when you pass vars from one State to another. + * @private + */ + this._args = []; + + /** + * @property {string} current - The current active State object. + * @default + */ + this.current = ''; + + /** + * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. + * + * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start + * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states + * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. + * + * The callback you specify is sent two parameters: the string based key of the new state, + * and the second parameter is the string based key of the old / previous state. + * + * @property {Phaser.Signal} onStateChange + */ + this.onStateChange = new Phaser.Signal(); + + /** + * @property {function} onInitCallback - This is called when the state is set as the active state. + * @default + */ + this.onInitCallback = null; + + /** + * @property {function} onPreloadCallback - This is called when the state starts to load assets. + * @default + */ + this.onPreloadCallback = null; + + /** + * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins. + * @default + */ + this.onCreateCallback = null; + + /** + * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). + * @default + */ + this.onUpdateCallback = null; + + /** + * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). + * @default + */ + this.onRenderCallback = null; + + /** + * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. + * @default + */ + this.onResizeCallback = null; + + /** + * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. + * @default + */ + this.onPreRenderCallback = null; + + /** + * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase. + * @default + */ + this.onLoadUpdateCallback = null; + + /** + * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase. + * @default + */ + this.onLoadRenderCallback = null; + + /** + * @property {function} onPausedCallback - This is called when the game is paused. + * @default + */ + this.onPausedCallback = null; + + /** + * @property {function} onResumedCallback - This is called when the game is resumed from a paused state. + * @default + */ + this.onResumedCallback = null; + + /** + * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused. + * @default + */ + this.onPauseUpdateCallback = null; + + /** + * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state). + * @default + */ + this.onShutDownCallback = null; + +}; + +Phaser.StateManager.prototype = { + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * @method Phaser.StateManager#boot + * @private + */ + boot: function () { + + this.game.onPause.add(this.pause, this); + this.game.onResume.add(this.resume, this); + + if (this._pendingState !== null && typeof this._pendingState !== 'string') + { + this.add('default', this._pendingState, true); + } + + }, + + /** + * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. + * + * The State can be any of + * + * - a plain JavaScript object containing at least one required callback (see {@link #checkState}) + * - an instance of {@link Phaser.State} + * - an instance of a class extending Phaser.State + * - a constructor function (class) + * + * If a function is given a new state object will be created by calling it, passing the current {@link Phaser.Game game} as the first argument. + * + * @method Phaser.StateManager#add + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + * @param {Phaser.State|object|function} state - The state you want to switch to. + * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it. + */ + add: function (key, state, autoStart) { + + if (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; + + }, + + /** + * Delete the given state. + * @method Phaser.StateManager#remove + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + */ + 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.onPreRenderCallback = null; + this.onRenderCallback = null; + this.onResizeCallback = null; + this.onPausedCallback = null; + this.onResumedCallback = null; + this.onPauseUpdateCallback = null; + } + + delete this.states[key]; + + }, + + /** + * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. + * + * @method Phaser.StateManager#start + * @param {string} key - The key of the state you want to start. + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one). + */ + start: function (key, clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + if (this.checkState(key)) + { + // Place the state in the queue. It will be started the next time the game loop begins. + this._pendingState = key; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 3) + { + this._args = Array.prototype.splice.call(arguments, 3); + } + } + + }, + + /** + * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. + * + * @method Phaser.StateManager#restart + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one. + */ + restart: function (clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + // Place the state in the queue. It will be started the next time the game loop starts. + this._pendingState = this.current; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 2) + { + this._args = Array.prototype.slice.call(arguments, 2); + } + + }, + + /** + * Used by onInit and onShutdown when those functions don't exist on the state + * @method Phaser.StateManager#dummy + * @private + */ + dummy: function () { + }, + + /** + * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. + * + * @method Phaser.StateManager#preUpdate + */ + preUpdate: function () { + + if (this._pendingState && this.game.isBooted) + { + var previousStateKey = this.current; + + // Already got a state running? + this.clearCurrentState(); + + this.setCurrentState(this._pendingState); + + this.onStateChange.dispatch(this.current, previousStateKey); + + if (this.current !== this._pendingState) + { + return; + } + else + { + this._pendingState = null; + } + + // If StateManager.start has been called from the init of a State that ALSO has a preload, then + // onPreloadCallback will be set, but must be ignored + if (this.onPreloadCallback) + { + this.game.load.reset(true); + this.onPreloadCallback.call(this.callbackContext, this.game); + + // Is the loader empty? + if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0) + { + this.loadComplete(); + } + else + { + // Start the loader going as we have something in the queue + this.game.load.start(); + } + } + else + { + // No init? Then there was nothing to load either + this.loadComplete(); + } + } + + }, + + /** + * This method clears the current State, calling its shutdown callback. The process also removes any active tweens, + * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. + * + * @method Phaser.StateManager#clearCurrentState + */ + clearCurrentState: function () { + + if (this.current) + { + if (this.onShutDownCallback) + { + 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(); + + this.game.scale.reset(this._clearWorld); + + if (this.game.debug) + { + this.game.debug.reset(); + } + + if (this._clearWorld) + { + this.game.world.shutdown(); + + if (this._clearCache) + { + this.game.cache.destroy(); + } + } + } + + }, + + /** + * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. + * + * @method Phaser.StateManager#checkState + * @param {string} key - The key of the state you want to check. + * @return {boolean} true if the State has the required functions, otherwise false. + */ + checkState: function (key) { + + var state = this.states[key]; + + if (state) + { + if (state.preload || state.create || state.update || state.render) + { + return true; + } + else + { + console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"); + return false; + } + } + else + { + console.warn("Phaser.StateManager - No state found with the key: " + key); + return false; + } + + }, + + /** + * Links game properties to the State given by the key. + * + * @method Phaser.StateManager#link + * @param {string} key - State key. + * @protected + */ + link: function (key) { + + var state = this.states[key]; + + state.game = this.game; + state.add = this.game.add; + state.make = this.game.make; + state.camera = this.game.camera; + state.cache = this.game.cache; + state.input = this.game.input; + state.load = this.game.load; + state.math = this.game.math; + state.sound = this.game.sound; + state.scale = this.game.scale; + state.state = this; + state.stage = this.game.stage; + state.time = this.game.time; + state.tweens = this.game.tweens; + state.world = this.game.world; + state.particles = this.game.particles; + state.rnd = this.game.rnd; + state.physics = this.game.physics; + state.key = key; + + }, + + /** + * Nulls all State level Phaser properties, including a reference to Game. + * + * @method Phaser.StateManager#unlink + * @param {string} key - State key. + * @protected + */ + unlink: function (key) { + + var state = this.states[key]; + + if (state) + { + state.game = null; + state.add = null; + state.make = null; + state.camera = null; + state.cache = null; + state.input = null; + state.load = null; + state.math = null; + state.sound = null; + state.scale = null; + state.state = null; + state.stage = null; + state.time = null; + state.tweens = null; + state.world = null; + state.particles = null; + state.rnd = null; + state.physics = null; + } + + }, + + /** + * Sets the current State. Should not be called directly (use StateManager.start) + * + * @method Phaser.StateManager#setCurrentState + * @param {string} key - State key. + * @private + */ + setCurrentState: function (key) { + + var state = this.states[key]; + + this.callbackContext = state; + + this.link(key); + + // Used when the state is set as being the current active state + this.onInitCallback = state['init'] || this.dummy; + + this.onPreloadCallback = state['preload'] || null; + this.onLoadRenderCallback = state['loadRender'] || null; + this.onLoadUpdateCallback = state['loadUpdate'] || null; + this.onCreateCallback = state['create'] || null; + this.onUpdateCallback = state['update'] || null; + this.onPreRenderCallback = state['preRender'] || null; + this.onRenderCallback = state['render'] || null; + this.onResizeCallback = state['resize'] || null; + this.onPausedCallback = state['paused'] || null; + this.onResumedCallback = state['resumed'] || null; + this.onPauseUpdateCallback = state['pauseUpdate'] || null; + + // Used when the state is no longer the current active state + this.onShutDownCallback = state['shutdown'] || this.dummy; + + // Reset the physics system, but not on the first state start + if (this.current !== '') + { + this.game.physics.reset(); + } + + this.current = key; + this._created = false; + + // At this point key and pendingState should equal each other + this.onInitCallback.apply(this.callbackContext, this._args); + + // If they no longer do then the init callback hit StateManager.start + if (key === this._pendingState) + { + this._args = []; + } + + this.game._kickstart = true; + + }, + + /** + * Gets the current State. + * + * @method Phaser.StateManager#getCurrentState + * @return {Phaser.State} + * @public + */ + getCurrentState: function() { + return this.states[this.current]; + }, + + /** + * @method Phaser.StateManager#loadComplete + * @protected + */ + loadComplete: function () { + + // Make sure to do load-update one last time before state is set to _created + if (this._created === false && this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + + if (this._created === false && this.onCreateCallback) + { + this._created = true; + this.onCreateCallback.call(this.callbackContext, this.game); + } + else + { + this._created = true; + } + + }, + + /** + * @method Phaser.StateManager#pause + * @protected + */ + pause: function () { + + if (this._created && this.onPausedCallback) + { + this.onPausedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#resume + * @protected + */ + resume: function () { + + if (this._created && this.onResumedCallback) + { + this.onResumedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#update + * @protected + */ + update: function () { + + if (this._created) + { + if (this.onUpdateCallback) + { + this.onUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#pauseUpdate + * @protected + */ + pauseUpdate: function () { + + if (this._created) + { + if (this.onPauseUpdateCallback) + { + this.onPauseUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#preRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + preRender: function (elapsedTime) { + + if (this._created && this.onPreRenderCallback) + { + this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime); + } + + }, + + /** + * @method Phaser.StateManager#resize + * @protected + */ + resize: function (width, height) { + + if (this.onResizeCallback) + { + this.onResizeCallback.call(this.callbackContext, width, height); + } + + }, + + /** + * @method Phaser.StateManager#render + * @protected + */ + render: function () { + + if (this._created) + { + if (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); + this.game.context.restore(); + } + else + { + this.onRenderCallback.call(this.callbackContext, this.game); + } + } + } + else + { + if (this.onLoadRenderCallback) + { + this.onLoadRenderCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. + * You don't recover from this without rebuilding the Phaser instance again. + * @method Phaser.StateManager#destroy + */ + destroy: function () { + + this._clearWorld = true; + this._clearCache = true; + + this.clearCurrentState(); + + 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; + this.current = ''; + + } + +}; + +Phaser.StateManager.prototype.constructor = Phaser.StateManager; + +/** +* @name Phaser.StateManager#created +* @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default). +* @readOnly +*/ +Object.defineProperty(Phaser.StateManager.prototype, "created", { + + get: function () { + + return this._created; + + } + +}); + +/** +* "It's like nailing jelly to a kitten" - Gary Penn +*/ + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Signals are what Phaser uses to handle events and event dispatching. +* You can listen for a Signal by binding a callback / function to it. +* This is done by using either `Signal.add` or `Signal.addOnce`. +* +* For example you can listen for a touch or click event from the Input Manager +* by using its `onDown` Signal: +* +* `game.input.onDown.add(function() { ... });` +* +* Rather than inline your function, you can pass a reference: +* +* `game.input.onDown.add(clicked, this);` +* `function clicked () { ... }` +* +* In this case the second argument (`this`) is the context in which your function should be called. +* +* Now every time the InputManager dispatches the `onDown` signal (or event), your function +* will be called. +* +* Multiple callbacks can be bound to the same signal. +* They're ordered first by their `priority` arguments and then by the order in which they were added. +* If a callback calls {@link #halt} or returns `false`, any remaining callbacks are skipped. +* +* Very often a Signal will send arguments to your function. +* This is specific to the Signal itself. +* If you're unsure then check the documentation, or failing that simply do: +* +* `Signal.add(function() { console.log(arguments); })` +* +* and it will log all of the arguments your function received from the Signal. +* +* Sprites have lots of default signals you can listen to in their Events class, such as: +* +* `sprite.events.onKilled` +* +* Which is called automatically whenever the Sprite is killed. +* There are lots of other events, see the Events component for a list. +* +* As well as listening to pre-defined Signals you can also create your own: +* +* `var mySignal = new Phaser.Signal();` +* +* This creates a new Signal. You can bind a callback to it: +* +* `mySignal.add(myCallback, this);` +* +* and then finally when ready you can dispatch the Signal: +* +* `mySignal.dispatch(your arguments);` +* +* And your callback will be invoked. See the dispatch method for more details. +* +* @class Phaser.Signal +* @constructor +*/ +Phaser.Signal = function () {}; + +Phaser.Signal.prototype = { + + /** + * @property {?Array.} _bindings - Internal variable. + * @private + */ + _bindings: null, + + /** + * @property {any} _prevParams - Internal variable. + * @private + */ + _prevParams: null, + + /** + * Memorize the previously dispatched event? + * + * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}. + * Use {@link #forget} to clear any currently memorized event. + * + * @property {boolean} memorize + */ + memorize: false, + + /** + * @property {boolean} _shouldPropagate + * @private + */ + _shouldPropagate: true, + + /** + * Is the Signal active? Only active signals will broadcast dispatched events. + * + * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}. + * + * @property {boolean} active + * @default + */ + active: true, + + /** + * @property {function} _boundDispatch - The bound dispatch function, if any. + * @private + */ + _boundDispatch: false, + + /** + * @method Phaser.Signal#validateListener + * @param {function} listener - Signal handler function. + * @param {string} fnName - Function name. + * @private + */ + validateListener: function (listener, fnName) { + + if (typeof listener !== 'function') + { + throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); + } + + }, + + /** + * @method Phaser.Signal#_registerListener + * @private + * @param {function} listener - Signal handler function. + * @param {boolean} isOnce - Should the listener only be called once? + * @param {object} [listenerContext] - The context under which the listener is invoked. + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + _registerListener: function (listener, isOnce, listenerContext, priority, args) { + + var prevIndex = this._indexOfListener(listener, listenerContext); + var binding; + + if (prevIndex !== -1) + { + binding = this._bindings[prevIndex]; + + if (binding.isOnce() !== isOnce) + { + throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); + } + } + else + { + binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args); + this._addBinding(binding); + } + + if (this.memorize && this._prevParams) + { + binding.execute(this._prevParams); + } + + return binding; + + }, + + /** + * @method Phaser.Signal#_addBinding + * @private + * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. + */ + _addBinding: function (binding) { + + if (!this._bindings) + { + this._bindings = []; + } + + // Simplified insertion sort + var n = this._bindings.length; + + do { + n--; + } + while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); + + this._bindings.splice(n + 1, 0, binding); + + }, + + /** + * @method Phaser.Signal#_indexOfListener + * @private + * @param {function} listener - Signal handler function. + * @param {object} [context=null] - Signal handler function. + * @return {number} The index of the listener within the private bindings array. + */ + _indexOfListener: function (listener, context) { + + if (!this._bindings) + { + return -1; + } + + if (context === undefined) { context = null; } + + var n = this._bindings.length; + var cur; + + while (n--) + { + cur = this._bindings[n]; + + if (cur._listener === listener && cur.context === context) + { + return n; + } + } + + return -1; + + }, + + /** + * Check if a specific listener is attached. + * + * @method Phaser.Signal#has + * @param {function} listener - Signal handler function. + * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @return {boolean} If Signal has the specified listener. + */ + has: function (listener, context) { + + return this._indexOfListener(listener, context) !== -1; + + }, + + /** + * Add an event listener for this signal. + * + * An event listener is a callback with a related context and priority. + * + * You can optionally provide extra arguments which will be passed to the callback after any internal parameters. + * + * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. + * Any arguments you've specified after `priority` will be sent as well: + * + * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` + * + * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. + * + * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', + * and the value 100 were the custom arguments given in the call to 'add'. + * + * If the callback calls {@link #halt} or returns `false`, any remaining callbacks bound to this Signal are skipped. + * + * @method Phaser.Signal#add + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + add: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'add'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, false, listenerContext, priority, args); + + }, + + /** + * Add a one-time listener - the listener is automatically removed after the first execution. + * + * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and + * the listener will be removed immediately. + * + * @method Phaser.Signal#addOnce + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + addOnce: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'addOnce'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, true, listenerContext, priority, args); + + }, + + /** + * Remove a single event listener. + * + * @method Phaser.Signal#remove + * @param {function} listener - Handler function that should be removed. + * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {function} Listener handler function. + */ + remove: function (listener, context) { + + this.validateListener(listener, 'remove'); + + var i = this._indexOfListener(listener, context); + + if (i !== -1) + { + this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal + this._bindings.splice(i, 1); + } + + return listener; + + }, + + /** + * Remove all event listeners. + * + * @method Phaser.Signal#removeAll + * @param {object} [context=null] - If specified only listeners for the given context will be removed. + */ + removeAll: function (context) { + + if (context === undefined) { context = null; } + + if (!this._bindings) + { + return; + } + + var n = this._bindings.length; + + while (n--) + { + if (context) + { + if (this._bindings[n].context === context) + { + this._bindings[n]._destroy(); + this._bindings.splice(n, 1); + } + } + else + { + this._bindings[n]._destroy(); + } + } + + if (!context) + { + this._bindings.length = 0; + } + + }, + + /** + * Gets the total number of listeners attached to this Signal. + * + * @method Phaser.Signal#getNumListeners + * @return {integer} Number of listeners attached to the Signal. + */ + getNumListeners: function () { + + return this._bindings ? this._bindings.length : 0; + + }, + + /** + * Stop propagation of the event, blocking the dispatch to next listener on the queue. + * + * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. + * See {@link #active} to enable/disable the signal entirely. + * + * @method Phaser.Signal#halt + */ + halt: function () { + + this._shouldPropagate = false; + + }, + + /** + * Dispatch / broadcast the event to all listeners. + * + * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}. + * + * @method Phaser.Signal#dispatch + * @param {any} [params] - Parameters that should be passed to each handler. + */ + dispatch: function () { + + if (!this.active || !this._bindings) + { + return; + } + + var paramsArr = Array.prototype.slice.call(arguments); + var n = this._bindings.length; + var bindings; + + if (this.memorize) + { + this._prevParams = paramsArr; + } + + if (!n) + { + // Should come after memorize + return; + } + + bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch + this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. + + //execute all callbacks until end of the list or until a callback returns `false` or stops propagation + //reverse loop since listeners with higher priority will be added at the end of the list + do { + n--; + } + while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); + + }, + + /** + * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any. + * + * @method Phaser.Signal#forget + */ + forget: function() { + + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * Dispose the signal - no more events can be dispatched. + * + * This removes all event listeners and clears references to external objects. + * Calling methods on a disposed objects results in undefined behavior. + * + * @method Phaser.Signal#dispose + */ + dispose: function () { + + this.removeAll(); + + this._bindings = null; + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * A string representation of the object. + * + * @method Phaser.Signal#toString + * @return {string} String representation of the object. + */ + toString: function () { + + return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']'; + + } + +}; + +/** +* Create a `dispatch` function that maintains a binding to the original Signal context. +* +* Use the resulting value if the dispatch function needs to be passed somewhere +* or called independently of the Signal object. +* +* @memberof Phaser.Signal +* @property {function} boundDispatch +*/ +Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", { + + get: function () { + var _this = this; + return this._boundDispatch || (this._boundDispatch = function () { + return _this.dispatch.apply(_this, arguments); + }); + } + +}); + +Phaser.Signal.prototype.constructor = Phaser.Signal; + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Object that represents a binding between a Signal and a listener function. +* This is an internal constructor and shouldn't be created directly. +* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. +* +* @class Phaser.SignalBinding +* @constructor +* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to. +* @param {function} listener - Handler function bound to the signal. +* @param {boolean} isOnce - If binding should be executed just once. +* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). +* @param {number} [priority] - The priority level of the event listener. (default = 0). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. +*/ +Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) { + + /** + * @property {Phaser.Game} _listener - Handler function bound to the signal. + * @private + */ + this._listener = listener; + + if (isOnce) + { + this._isOnce = true; + } + + if (listenerContext != null) /* not null/undefined */ + { + this.context = listenerContext; + } + + /** + * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to. + * @private + */ + this._signal = signal; + + if (priority) + { + this._priority = priority; + } + + if (args && args.length) + { + this._args = args; + } + +}; + +Phaser.SignalBinding.prototype = { + + /** + * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + */ + context: null, + + /** + * @property {boolean} _isOnce - If binding should be executed just once. + * @private + */ + _isOnce: false, + + /** + * @property {number} _priority - Listener priority. + * @private + */ + _priority: 0, + + /** + * @property {array} _args - Listener arguments. + * @private + */ + _args: null, + + /** + * @property {number} callCount - The number of times the handler function has been called. + */ + callCount: 0, + + /** + * If binding is active and should be executed. + * @property {boolean} active + * @default + */ + active: true, + + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). + * @property {array|null} params + * @default + */ + params: null, + + /** + * Call listener passing arbitrary parameters. + * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. + * @method Phaser.SignalBinding#execute + * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener. + * @return {any} Value returned by the listener. + */ + execute: function(paramsArr) { + + var handlerReturn, params; + + if (this.active && !!this._listener) + { + params = this.params ? this.params.concat(paramsArr) : paramsArr; + + if (this._args) + { + params = params.concat(this._args); + } + + handlerReturn = this._listener.apply(this.context, params); + + this.callCount++; + + if (this._isOnce) + { + this.detach(); + } + } + + return handlerReturn; + + }, + + /** + * Detach binding from signal. + * alias to: @see mySignal.remove(myBinding.getListener()); + * @method Phaser.SignalBinding#detach + * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ + detach: function () { + return this.isBound() ? this._signal.remove(this._listener, this.context) : null; + }, + + /** + * @method Phaser.SignalBinding#isBound + * @return {boolean} True if binding is still bound to the signal and has a listener. + */ + isBound: function () { + return (!!this._signal && !!this._listener); + }, + + /** + * @method Phaser.SignalBinding#isOnce + * @return {boolean} If SignalBinding will only be executed once. + */ + isOnce: function () { + return this._isOnce; + }, + + /** + * @method Phaser.SignalBinding#getListener + * @return {function} Handler function bound to the signal. + */ + getListener: function () { + return this._listener; + }, + + /** + * @method Phaser.SignalBinding#getSignal + * @return {Phaser.Signal} Signal that listener is currently bound to. + */ + getSignal: function () { + return this._signal; + }, + + /** + * Delete instance properties + * @method Phaser.SignalBinding#_destroy + * @private + */ + _destroy: function () { + delete this._signal; + delete this._listener; + delete this.context; + }, + + /** + * @method Phaser.SignalBinding#toString + * @return {string} String representation of the object. + */ + toString: function () { + return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']'; + } + +}; + +Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding; + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Filter class to use for any Phaser filter development. +* If you want to make a custom filter, this should be your base class. +* +* The default uniforms, types and values for all Filters are: +* +* ```javascript +* resolution: { type: '2f', value: { x: 256, y: 256 }} +* time: { type: '1f', value: 0 } +* mouse: { type: '2f', value: { x: 0.0, y: 0.0 } } +* date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] } +* sampleRate: { type: '1f', value: 44100.0 } +* iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* ``` +* +* The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and +* therefore only work in WebGL and are not supported by Canvas at all. +* +* @class Phaser.Filter +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [uniforms] - Uniform mappings object. The uniforms are added on the default uniforms, or replace them if the keys are the same. +* @param {Array|string} [fragmentSrc] - The fragment shader code. Either an array, one element per line of code, or a string. +*/ +Phaser.Filter = function (game, uniforms, fragmentSrc) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. + * @default + */ + this.type = Phaser.WEBGL_FILTER; + + /** + * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. + * For example the blur filter has two passes blurX and blurY. + * @property {array} passes - An array of filter objects. + * @private + */ + this.passes = [ this ]; + + /** + * @property {array} shaders - Array an array of shaders. + * @private + */ + this.shaders = []; + + /** + * @property {boolean} dirty - Internal PIXI var. + * @default + */ + this.dirty = true; + + /** + * @property {number} padding - Internal PIXI var. + * @default + */ + this.padding = 0; + + /** + * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same) + */ + this.prevPoint = new Phaser.Point(); + + /* + * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D. + */ + + var d = new Date(); + + /** + * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. + */ + this.uniforms = { + + resolution: { type: '2f', value: { x: 256, y: 256 }}, + time: { type: '1f', value: 0 }, + mouse: { type: '2f', value: { x: 0.0, y: 0.0 } }, + date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, + sampleRate: { type: '1f', value: 44100.0 }, + iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + + }; + + // Copy over / replace any passed in the constructor + if (uniforms) + { + for (var key in uniforms) + { + this.uniforms[key] = uniforms[key]; + } + } + + // If fragmentSrc is a string, split it based on new-lines into an array + if (typeof fragmentSrc === 'string') + { + fragmentSrc = fragmentSrc.split('\n'); + } + + /** + * @property {array|string} fragmentSrc - The fragment shader code. + */ + this.fragmentSrc = fragmentSrc || []; + +}; + +Phaser.Filter.prototype = { + + /** + * This should be over-ridden. Will receive a variable number of arguments. + * + * @method Phaser.Filter#init + */ + init: function () { + + // This should be over-ridden. Will receive a variable number of arguments. + + }, + + /** + * Set the resolution uniforms on the filter. + * + * @method Phaser.Filter#setResolution + * @param {number} width - The width of the display. + * @param {number} height - The height of the display. + */ + setResolution: function (width, height) { + + this.uniforms.resolution.value.x = width; + this.uniforms.resolution.value.y = height; + + }, + + /** + * Updates the filter. + * + * @method Phaser.Filter#update + * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. + */ + update: function (pointer) { + + if (pointer) + { + var x = pointer.x / this.game.width; + var y = 1 - pointer.y / this.game.height; + + if (x !== this.prevPoint.x || y !== this.prevPoint.y) + { + this.uniforms.mouse.value.x = x.toFixed(2); + this.uniforms.mouse.value.y = y.toFixed(2); + this.prevPoint.set(x, y); + } + } + + this.uniforms.time.value = this.game.time.totalElapsedSeconds(); + + }, + + /** + * Creates a new Phaser.Image object using a blank texture and assigns + * this Filter to it. The image is then added to the world. + * + * If you don't provide width and height values then Filter.width and Filter.height are used. + * + * If you do provide width and height values then this filter will be resized to match those + * values. + * + * @method Phaser.Filter#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. + * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, width, height, anchorX, anchorY) { + + if (anchorX === undefined) { anchorX = 0; } + if (anchorY === undefined) { anchorY = 0; } + + if (width !== undefined && width !== null) + { + this.width = width; + } + else + { + width = this.width; + } + + if (height !== undefined && height !== null) + { + this.height = height; + } + else + { + height = this.height; + } + + var image = this.game.add.image(x, y, Phaser.Cache.DEFAULT); + + image.width = width; + image.height = height; + + image.anchor.set(anchorX, anchorY); + + image.filters = [ this ]; + + return image; + + }, + + /** + * Syncs the uniforms between the class object and the shaders. + * + * @method Phaser.Filter#syncUniforms + */ + syncUniforms: function () { + + for (var i = 0; i < this.shaders.length; i++) + { + this.shaders[i].dirty = true; + } + + }, + + /** + * Clear down this Filter and null out references to game. + * + * @method Phaser.Filter#destroy + */ + destroy: function () { + + this.passes.length = 0; + this.shaders.length = 0; + this.fragmentSrc.length = 0; + + this.game = null; + this.uniforms = null; + this.prevPoint = null; + + } + +}; + +Phaser.Filter.prototype.constructor = Phaser.Filter; + +/** +* @name Phaser.Filter#width +* @property {number} width - The width (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'width', { + + get: function () { + + return this.uniforms.resolution.value.x; + + }, + + set: function (value) { + + this.uniforms.resolution.value.x = value; + + } + +}); + +/** +* @name Phaser.Filter#height +* @property {number} height - The height (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'height', { + + get: function () { + + return this.uniforms.resolution.value.y; + + }, + + set: function (value) { + + this.uniforms.resolution.value.y = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Plugin template to use for any Phaser plugin development. +* +* ##### Callbacks +* +* add | active | visible | remove +* -----|-------------|-------------|-------- +* init | | | +* | preUpdate* | | +* | update* | render* | +* | postUpdate* | postRender* | +* | | | destroy +* +* Update and render calls are repeated (*). +* +* @class Phaser.Plugin +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager. +*/ +Phaser.Plugin = function (game, parent) { + + if (parent === undefined) { parent = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. + */ + this.parent = parent; + + /** + * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. + * @default + */ + this.active = false; + + /** + * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. + * @default + */ + this.visible = false; + + /** + * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. + * @default + */ + this.hasPreUpdate = false; + + /** + * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. + * @default + */ + this.hasUpdate = false; + + /** + * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. + * @default + */ + this.hasPostUpdate = false; + + /** + * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. + * @default + */ + this.hasRender = false; + + /** + * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. + * @default + */ + this.hasPostRender = false; + +}; + +Phaser.Plugin.prototype = { + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It is only called if active is set to true. + * @method Phaser.Plugin#preUpdate + */ + preUpdate: function () { + }, + + /** + * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It is only called if active is set to true. + * @method Phaser.Plugin#update + */ + update: function () { + }, + + /** + * Render is called right after the Game Renderer completes, but before the State.render. + * It is only called if visible is set to true. + * @method Phaser.Plugin#render + */ + render: function () { + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It is only called if visible is set to true. + * @method Phaser.Plugin#postRender + */ + postRender: function () { + }, + + /** + * Clear down this Plugin and null out references + * @method Phaser.Plugin#destroy + */ + destroy: function () { + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + + } + +}; + +Phaser.Plugin.prototype.constructor = Phaser.Plugin; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. +* +* @class Phaser.PluginManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.PluginManager = function(game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager. + */ + this.plugins = []; + + /** + * @property {number} _len - Internal cache var. + * @private + */ + this._len = 0; + + /** + * @property {number} _i - Internal cache var. + * @private + */ + this._i = 0; + +}; + +Phaser.PluginManager.prototype = { + + /** + * Add a new Plugin into the PluginManager. + * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.PluginManager#add + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + add: function (plugin) { + + var args = Array.prototype.slice.call(arguments, 1); + var result = false; + + // Prototype? + if (typeof plugin === 'function') + { + plugin = new plugin(this.game, this); + } + else + { + plugin.game = this.game; + plugin.parent = this; + } + + // Check for methods now to avoid having to do this every loop + 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; + } + + // The plugin must have at least one of the above functions to be added to the PluginManager. + 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); + + // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager + if (typeof plugin['init'] === 'function') + { + plugin.init.apply(plugin, args); + } + + return plugin; + } + else + { + return null; + } + }, + + /** + * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. + * + * @method Phaser.PluginManager#remove + * @param {Phaser.Plugin} plugin - The plugin to be removed. + * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed? + */ + remove: function (plugin, destroy) { + + if (destroy === undefined) { destroy = true; } + + this._i = this._len; + + while (this._i--) + { + if (this.plugins[this._i] === plugin) + { + if (destroy) + { + plugin.destroy(); + } + + this.plugins.splice(this._i, 1); + this._len--; + return; + } + } + + }, + + /** + * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. + * + * @method Phaser.PluginManager#removeAll + */ + removeAll: function() { + + this._i = this._len; + + while (this._i--) + { + this.plugins[this._i].destroy(); + } + + this.plugins.length = 0; + this._len = 0; + + }, + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#preUpdate + */ + 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 is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#update + */ + 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 is the last thing to be called before the world render. + * In particular, it is called after the world postUpdate, which means the camera has been adjusted. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#postUpdate + */ + 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 is called right after the Game Renderer completes, but before the State.render. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#render + */ + 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(); + } + } + + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#postRender + */ + 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(); + } + } + + }, + + /** + * Clear down this PluginManager, calls destroy on every plugin and nulls out references. + * + * @method Phaser.PluginManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.game = null; + + } + +}; + +Phaser.PluginManager.prototype.constructor = Phaser.PluginManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Stage controls root level display objects upon which everything is displayed. +* It also handles browser visibility handling and the pausing due to loss of focus. +* +* @class Phaser.Stage +* @extends PIXI.DisplayObjectContainer +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Stage = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {string} name - The name of this object. + * @default + */ + this.name = '_stage_root'; + + /** + * By default if the browser tab loses focus the game will pause. + * You can stop that behavior by setting this property to true. + * Note that the browser can still elect to pause your game if it wishes to do so, + * for example swapping to another browser tab. This will cause the RAF callback to halt, + * effectively pausing your game, even though no in-game pause event is triggered if you enable this property. + * @property {boolean} disableVisibilityChange + * @default + */ + this.disableVisibilityChange = false; + + /** + * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. + * @default + */ + this.exists = true; + + /** + * @property {Phaser.Matrix} worldTransform - Current transform of the object based on world (parent) factors + * @private + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage) + * @private + * @readOnly + */ + this.stage = this; + + /** + * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. + */ + this.currentRenderOrderID = 0; + + /** + * @property {string} hiddenVar - The page visibility API event name. + * @private + */ + this._hiddenVar = 'hidden'; + + /** + * @property {function} _onChange - The blur/focus event handler. + * @private + */ + this._onChange = null; + + /** + * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor. + * @private + */ + this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' }; + + if (!this.game.transparent) + { + // transparent = 0,0,0,0 - otherwise r,g,b,1 + this._bgColor.a = 1; + } + + if (game.config) + { + this.parseConfig(game.config); + } + +}; + +Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Stage.prototype.constructor = Phaser.Stage; + +/** +* Parses a Game configuration object. +* +* @method Phaser.Stage#parseConfig +* @protected +* @param {object} config -The configuration object to parse. +*/ +Phaser.Stage.prototype.parseConfig = function (config) { + + if (config['disableVisibilityChange']) + { + this.disableVisibilityChange = config['disableVisibilityChange']; + } + + if (config['backgroundColor']) + { + this.setBackgroundColor(config['backgroundColor']); + } + +}; + +/** +* Initialises the stage and adds the event listeners. +* @method Phaser.Stage#boot +* @private +*/ +Phaser.Stage.prototype.boot = function () { + + Phaser.DOM.getOffset(this.game.canvas, this.offset); + + Phaser.Canvas.setUserSelect(this.game.canvas, 'none'); + Phaser.Canvas.setTouchAction(this.game.canvas, 'none'); + + this.checkVisibility(); + +}; + +/** +* This is called automatically after the plugins preUpdate and before the State.update. +* Most objects have preUpdate methods and it's where initial movement and positioning is done. +* +* @method Phaser.Stage#preUpdate +*/ +Phaser.Stage.prototype.preUpdate = function () { + + this.currentRenderOrderID = 0; + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + +}; + +/** +* This is called automatically after the State.update, but before particles or plugins update. +* +* @method Phaser.Stage#update +*/ +Phaser.Stage.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + this.children[i].update(); + } + +}; + +/** +* This is called automatically before the renderer runs and after the plugins have updated. +* In postUpdate this is where all the final physics calculations and object positioning happens. +* The objects are processed in the order of the display list. +* +* @method Phaser.Stage#postUpdate +*/ +Phaser.Stage.prototype.postUpdate = function () { + + // Apply the camera shake, fade, bounds, etc + this.game.camera.update(); + + // Camera target first? + if (this.game.camera.target) + { + this.game.camera.target.postUpdate(); + + this.updateTransform(); + + this.game.camera.updateTarget(); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + this.updateTransform(); + +}; + +/** +* Updates the transforms for all objects on the display list. +* This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. +* +* @method Phaser.Stage#updateTransform +*/ +Phaser.Stage.prototype.updateTransform = function () { + + this.worldAlpha = 1; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +/** +* Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. +* Also listens for window.onblur and window.onfocus. +* +* @method Phaser.Stage#checkVisibility +*/ +Phaser.Stage.prototype.checkVisibility = function () { + + if (document.hidden !== undefined) + { + this._hiddenVar = 'visibilitychange'; + } + else if (document.webkitHidden !== undefined) + { + this._hiddenVar = 'webkitvisibilitychange'; + } + else if (document.mozHidden !== undefined) + { + this._hiddenVar = 'mozvisibilitychange'; + } + else if (document.msHidden !== undefined) + { + this._hiddenVar = 'msvisibilitychange'; + } + else + { + this._hiddenVar = null; + } + + var _this = this; + + this._onChange = function (event) { + return _this.visibilityChange(event); + }; + + this._onClick = function (event) { + if ((document.hasFocus !== undefined) && !document.hasFocus()) + { + _this.visibilityChange(event); + } + }; + + // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus + if (this._hiddenVar) + { + document.addEventListener(this._hiddenVar, this._onChange, false); + } + + window.onblur = this._onChange; + window.onfocus = this._onChange; + + window.onpagehide = this._onChange; + window.onpageshow = this._onChange; + + window.addEventListener('click', this._onClick); + + if (this.game.device.cocoonJSApp) + { + CocoonJS.App.onSuspended.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" }); + }); + + CocoonJS.App.onActivated.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" }); + }); + } + +}; + +/** +* This method is called when the document visibility is changed. +* +* - `blur` and `pagehide` events trigger {@link Phaser.Game#onBlur}. They {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `click`, `focus`, and `pageshow` trigger {@link Phaser.Game#onFocus}. They {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (hidden) and CocoonJS's `onSuspended` {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (visible) and CocoonJS's `onActivated` {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* +* @method Phaser.Stage#visibilityChange +* @param {Event} event - Its type will be used to decide whether the game should be paused or not. +*/ +Phaser.Stage.prototype.visibilityChange = function (event) { + + // These events always trigger the Game#onBlur or Game#onFocus signals. + + switch (event.type) + { + case 'blur': + case 'pagehide': + this.game.focusLoss(event); + return; + case 'click': + case 'focus': + case 'pageshow': + this.game.focusGain(event); + return; + } + + if (this.disableVisibilityChange) + { + return; + } + + if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause") + { + this.game.gamePaused(event); + } + else + { + this.game.gameResumed(event); + } + +}; + +/** +* Sets the background color for the Stage. +* +* The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). +* +* An alpha channel is _not_ supported and will be ignored. +* +* If you've set your game to be {@link Phaser.Game#transparent transparent} then calls to setBackgroundColor are ignored. +* +* If {@link Phaser.Game#clearBeforeRender} is off then the background color won't appear. +* +* @method Phaser.Stage#setBackgroundColor +* @param {number|string} color - The color of the background. +*/ +Phaser.Stage.prototype.setBackgroundColor = function (color) { + + if (this.game.transparent) { return; } + + Phaser.Color.valueToColor(color, this._bgColor); + Phaser.Color.updateColor(this._bgColor); + + // For gl.clearColor (canvas uses _bgColor.rgba) + this._bgColor.r /= 255; + this._bgColor.g /= 255; + this._bgColor.b /= 255; + this._bgColor.a = 1; + +}; + +/** +* Destroys the Stage and removes event listeners. +* +* @method Phaser.Stage#destroy +*/ +Phaser.Stage.prototype.destroy = function () { + + if (this._hiddenVar) + { + document.removeEventListener(this._hiddenVar, this._onChange, false); + } + + window.onpagehide = null; + window.onpageshow = null; + + window.onblur = null; + window.onfocus = null; + + window.removeEventListener('click', this._onClick); + +}; + +/** +* Adds an existing object to the Stage. +* +* The child is automatically added to the front of the Stage, and is displayed above every previous child. +* Or if the _optional_ `index` is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the object was already on the Stage, it is simply returned, and nothing else happens to it. +* +* @method Phaser.Stage#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent] - Unused. Kept for compatibility with {@link Phaser.Group#add}. +* @param {integer} [index] - The index to insert the object to. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Stage.prototype.add = function (child, silent, index) { + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + this.addChild(child); + } + else + { + this.addChildAt(child, index); + } + + return child; + +}; + +/** +* @name Phaser.Stage#backgroundColor +* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' +* @see Phaser.Stage#setBackgroundColor +*/ +Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", { + + get: function () { + + return this._bgColor.color; + + }, + + set: function (color) { + + this.setBackgroundColor(color); + + } + +}); + +/** +* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. +* +* @name Phaser.Stage#smoothed +* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) +*/ +Object.defineProperty(Phaser.Stage.prototype, "smoothed", { + + get: function () { + + return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR; + + }, + + set: function (value) { + + if (value) + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR; + } + else + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}. +* +* Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. +* For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. +* +* In addition, Groups provides support for fast pooling and object recycling. +* +* Groups are also display objects and can be nested as children within other Groups. +* +* @class Phaser.Group +* @extends PIXI.DisplayObjectContainer +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to. +* If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent. +* @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World. +* @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}. +* @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values. +*/ +Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) { + + if (addToStage === undefined) { addToStage = false; } + if (enableBody === undefined) { enableBody = false; } + if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + if (parent === undefined) + { + parent = game.world; + } + + /** + * A name for this group. Not used internally but useful for debugging. + * @property {string} name + */ + this.name = name || 'group'; + + /** + * The z-depth value of this object within its parent container/Group - the World is a Group as well. + * This value must be unique for each child in a Group. + * @property {integer} z + * @readOnly + */ + this.z = 0; + + PIXI.DisplayObjectContainer.call(this); + + if (addToStage) + { + this.game.stage.addChild(this); + this.z = this.game.stage.children.length; + } + else + { + if (parent) + { + parent.addChild(this); + this.z = parent.children.length; + } + } + + /** + * Internal Phaser Type value. + * @property {integer} type + * @protected + */ + this.type = Phaser.GROUP; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. + * @property {boolean} alive + * @default + */ + this.alive = true; + + /** + * If exists is false the group will be excluded from collision checks and filters such as {@link #forEachExists}. The group will not call `preUpdate` and `postUpdate` on its children and the children will not receive physics updates or camera/world boundary checks. The group will still be {@link #visible} and will still call `update` on its children (unless {@link #updateOnlyExistingChildren} is true). + * @property {boolean} exists + * @default + */ + this.exists = true; + + /** + * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. + * @property {boolean} ignoreDestroy + * @default + */ + this.ignoreDestroy = false; + + /** + * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method + * called on the next logic update. + * You can set it directly to flag the Group to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy a Group from within one of its own callbacks + * or a callback of one of its children. + * + * @property {boolean} pendingDestroy + */ + this.pendingDestroy = false; + + /** + * The type of objects that will be created when using {@link #create} or {@link #createMultiple}. + * + * It should extend either Sprite or Image and accept the same constructor arguments: `(game, x, y, key, frame)`. + * + * @property {function} classType + * @default {@link Phaser.Sprite} + */ + this.classType = Phaser.Sprite; + + /** + * The current display object that the group cursor is pointing to, if any. (Can be set manually.) + * + * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}. + * @property {?DisplayObject} cursor + */ + this.cursor = null; + + /** + * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` + * on any children _added_ to, or _created by_, this Group. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * @property {boolean} inputEnableChildren + * @default + */ + this.inputEnableChildren = false; + + /** + * Skip children with `exists = false` in {@link #update}. + * + * @property {boolean} updateOnlyExistingChildren + * @default + */ + this.updateOnlyExistingChildren = false; + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputDown + */ + this.onChildInputDown = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, + * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer + * is still over the Sprite or not. + * + * @property {Phaser.Signal} onChildInputUp + */ + this.onChildInputUp = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOver + */ + this.onChildInputOver = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOut + */ + this.onChildInputOut = new Phaser.Signal(); + + /** + * If true all Sprites created by, or added to this group, will have a physics body enabled on them. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * The default body type is controlled with {@link #physicsBodyType}. + * @property {boolean} enableBody + */ + this.enableBody = enableBody; + + /** + * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well. + * + * This only works for P2 bodies. + * @property {boolean} enableBodyDebug + * @default + */ + this.enableBodyDebug = false; + + /** + * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites. + * + * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc. + * @property {integer} physicsBodyType + */ + this.physicsBodyType = physicsBodyType; + + /** + * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. + * + * It should be set to one of the Phaser.Physics.Arcade sort direction constants: + * + * Phaser.Physics.Arcade.SORT_NONE + * Phaser.Physics.Arcade.LEFT_RIGHT + * Phaser.Physics.Arcade.RIGHT_LEFT + * Phaser.Physics.Arcade.TOP_BOTTOM + * Phaser.Physics.Arcade.BOTTOM_TOP + * + * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. + * + * @property {integer} physicsSortDirection + * @default + */ + this.physicsSortDirection = null; + + /** + * This signal is dispatched when the group is destroyed. + * @property {Phaser.Signal} onDestroy + */ + this.onDestroy = new Phaser.Signal(); + + /** + * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next. + * @readOnly + */ + this.cursorIndex = 0; + + /** + * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. + * + * Note that the cameraOffset values are in addition to any parent in the display list. + * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x + * + * @property {boolean} fixedToCamera + */ + this.fixedToCamera = false; + + /** + * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view. + * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. + * @property {Phaser.Point} cameraOffset + */ + this.cameraOffset = new Phaser.Point(); + + /** + * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. + * + * Only children of this Group can be added to and removed from the hash. + * + * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. + * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own + * sorting and filtering of Group children without touching their z-index (and therefore display draw order) + * + * @property {array} hash + */ + this.hash = []; + + /** + * The property on which children are sorted. + * @property {string} _sortProperty + * @private + */ + this._sortProperty = 'z'; + +}; + +Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Group.prototype.constructor = Phaser.Group; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_NONE = 0; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_TOTAL = 1; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_CHILD = 2; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_ALL = 3; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_ASCENDING = -1; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_DESCENDING = 1; + +/** +* Adds an existing object as the top child in this group. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the child was already in this Group, it is simply returned, and nothing else happens to it. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* Use {@link #create} to create and add a new child. +* +* @method Phaser.Group#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.add = function (child, silent, index) { + + if (silent === undefined) { silent = false; } + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + child.z = this.children.length; + + this.addChild(child); + } + else + { + this.addChildAt(child, index); + + this.updateZ(); + } + + if (this.enableBody && child.hasOwnProperty('body') && child.body === null) + { + this.game.physics.enable(child, this.physicsBodyType); + } + else if (child.body) + { + this.addToHash(child); + } + + if (this.inputEnableChildren && (!child.input || child.inputEnabled)) + { + child.inputEnabled = true; + } + + if (!silent && child.events) + { + child.events.onAddedToGroup$dispatch(child, this); + } + + if (this.cursor === null) + { + this.cursor = child; + } + + return child; + +}; + +/** +* Adds an existing object to this group. +* +* The child is added to the group at the location specified by the index value, this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#addAt +* @param {DisplayObject} child - The display object to add as a child. +* @param {integer} [index=0] - The index within the group to insert the child to. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.addAt = function (child, index, silent) { + + return this.add(child, silent, index); + +}; + +/** +* Adds a child of this Group into the hash array. +* This call will return false if the child is not a child of this Group, or is already in the hash. +* +* @method Phaser.Group#addToHash +* @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. +* @return {boolean} True if the child was successfully added to the hash, otherwise false. +*/ +Phaser.Group.prototype.addToHash = function (child) { + + if (child.parent === this) + { + var index = this.hash.indexOf(child); + + if (index === -1) + { + this.hash.push(child); + return true; + } + } + + return false; + +}; + +/** +* Removes a child of this Group from the hash array. +* This call will return false if the child is not in the hash. +* +* @method Phaser.Group#removeFromHash +* @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash. +* @return {boolean} True if the child was successfully removed from the hash, otherwise false. +*/ +Phaser.Group.prototype.removeFromHash = function (child) { + + if (child) + { + var index = this.hash.indexOf(child); + + if (index !== -1) + { + this.hash.splice(index, 1); + return true; + } + } + + return false; + +}; + +/** +* Adds an array of existing Display Objects to this Group. +* +* The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. +* +* As well as an array you can also pass another Group as the first argument. In this case all of the children from that +* Group will be removed from it and added into this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#addMultiple +* @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group. +*/ +Phaser.Group.prototype.addMultiple = function (children, silent) { + + if (children instanceof Phaser.Group) + { + children.moveAll(this, silent); + } + else if (Array.isArray(children)) + { + for (var i = 0; i < children.length; i++) + { + this.add(children[i], silent); + } + } + + return children; + +}; + +/** +* Returns the child found at the given index within this group. +* +* @method Phaser.Group#getAt +* @param {integer} index - The index to return the child from. +* @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index. +*/ +Phaser.Group.prototype.getAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + return -1; + } + else + { + return this.getChildAt(index); + } + +}; + +/** +* Creates a new Phaser.Sprite object and adds it to the top of this group. +* +* Use {@link #classType} to change the type of object created. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#create +* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. +* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {boolean} [exists=true] - The default exists state of the Sprite. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed. +*/ +Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) { + + if (exists === undefined) { exists = true; } + + var child = new this.classType(this.game, x, y, key, frame); + + child.exists = exists; + child.visible = exists; + child.alive = exists; + + return this.add(child, false, index); + +}; + +/** +* Creates multiple Phaser.Sprite objects and adds them to the top of this Group. +* +* This method is useful if you need to quickly generate a pool of sprites, such as bullets. +* +* Use {@link #classType} to change the type of object created. +* +* You can provide an array as the `key` and / or `frame` arguments. When you do this +* it will create `quantity` Sprites for every key (and frame) in the arrays. +* +* For example: +* +* `createMultiple(25, ['ball', 'carrot'])` +* +* In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be +* created in total, 25 of each. You can also have the `frame` as an array: +* +* `createMultiple(5, 'bricks', [0, 1, 2, 3])` +* +* In the above there is one key (bricks), which is a sprite sheet. The frames array tells +* this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because +* the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with +* frame 1, and so on. +* +* If you set both the key and frame arguments to be arrays then understand it will create +* a total quantity of sprites equal to the size of both arrays times each other. I.e.: +* +* `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` +* +* The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. +* It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. +* In total it will have created 120 sprites. +* +* By default the Sprites will have their `exists` property set to `false`, and they will be +* positioned at 0x0, relative to the `Group.x / y` values. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#createMultiple +* @param {integer} quantity - The number of Sprites to create. +* @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. +* @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. +* @param {boolean} [exists=false] - The default exists state of the Sprite. +* @param {function} [callback] - The function that will be called for each applicable child. It will be passed the new child and the loop index (0 through quantity - 1). +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). The default context is the new child. +* @return {array} An array containing all of the Sprites that were created. +*/ +Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, callback, callbackContext) { + + if (frame === undefined) { frame = 0; } + if (exists === undefined) { exists = false; } + + if (!Array.isArray(key)) + { + key = [ key ]; + } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + + var _this = this; + var children = []; + + key.forEach(function(singleKey) { + + frame.forEach(function(singleFrame) { + + for (var i = 0; i < quantity; i++) + { + var child = _this.create(0, 0, singleKey, singleFrame, exists); + + if (callback) { callback.call(callbackContext || child, child, i); } + + children.push(child); + } + + }); + + }); + + return children; + +}; + +/** +* Internal method that re-applies all of the children's Z values. +* +* This must be called whenever children ordering is altered so that their `z` indices are correctly updated. +* +* @method Phaser.Group#updateZ +* @protected +*/ +Phaser.Group.prototype.updateZ = function () { + + var i = this.children.length; + + while (i--) + { + this.children[i].z = i; + } + +}; + +/** +* This method iterates through all children in the Group (regardless if they are visible or exist) +* and then changes their position so they are arranged in a Grid formation. Children must have +* the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have +* this. +* +* The grid dimensions are determined by the first four arguments. The `width` and `height` arguments +* relate to the width and height of the grid respectively. +* +* For example if the Group had 100 children in it: +* +* `Group.align(10, 10, 32, 32)` +* +* This will align all of the children into a grid formation of 10x10, using 32 pixels per +* grid cell. If you want a wider grid, you could do: +* +* `Group.align(25, 4, 32, 32)` +* +* This will align the children into a grid of 25x4, again using 32 pixels per grid cell. +* +* You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method +* to keep on aligning children until there are no children left. For example if this Group had +* 48 children in it, the following: +* +* `Group.align(-1, 8, 32, 32)` +* +* ... will align the children so that there are 8 children vertically (the second argument), +* and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) +* +* You can also do: +* +* `Group.align(10, -1, 32, 32)` +* +* In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit +* all of the children in. +* +* The `position` property allows you to control where in each grid cell the child is positioned. +* This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, +* `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, +* `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* +* The final argument; `offset` lets you start the alignment from a specific child index. +* +* @method Phaser.Group#align +* @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. +* @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. +* @param {integer} cellWidth - The width of each grid cell, in pixels. +* @param {integer} cellHeight - The height of each grid cell, in pixels. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. +* @return {boolean} True if the Group children were aligned, otherwise false. +*/ +Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, position, offset) { + + if (position === undefined) { position = Phaser.TOP_LEFT; } + if (offset === undefined) { offset = 0; } + + if (this.children.length === 0 || offset > this.children.length || (width === -1 && height === -1)) + { + return false; + } + + var r = new Phaser.Rectangle(0, 0, cellWidth, cellHeight); + var w = (width * cellWidth); + var h = (height * cellHeight); + + for (var i = offset; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child['alignIn']) + { + child.alignIn(r, position); + } + else + { + continue; + } + + if (width === -1) + { + // We keep laying them out horizontally until we've done them all + r.y += cellHeight; + + if (r.y === h) + { + r.x += cellWidth; + r.y = 0; + } + } + else if (height === -1) + { + // We keep laying them out vertically until we've done them all + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + } + } + else + { + // We keep laying them out until we hit the column limit + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + + if (r.y === h) + { + // We've hit the column limit, so return, even if there are children left + return true; + } + } + } + } + + return true; + +}; + +/** +* Sets the group cursor to the first child in the group. +* +* If the optional index parameter is given it sets the cursor to the object at that index instead. +* +* @method Phaser.Group#resetCursor +* @param {integer} [index=0] - Set the cursor to point to a specific index. +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.resetCursor = function (index) { + + if (index === undefined) { index = 0; } + + if (index > this.children.length - 1) + { + index = 0; + } + + if (this.cursor) + { + this.cursorIndex = index; + this.cursor = this.children[this.cursorIndex]; + return this.cursor; + } + +}; + +/** +* Advances the group cursor to the next (higher) object in the group. +* +* If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). +* +* @method Phaser.Group#next +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.next = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex >= this.children.length - 1) + { + this.cursorIndex = 0; + } + else + { + this.cursorIndex++; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Moves the group cursor to the previous (lower) child in the group. +* +* If the cursor is at the start of the group (bottom child) it is moved to the end (top child). +* +* @method Phaser.Group#previous +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.previous = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex === 0) + { + this.cursorIndex = this.children.length - 1; + } + else + { + this.cursorIndex--; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Swaps the position of two children in this group. +* +* Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. +* +* @method Phaser.Group#swap +* @param {any} child1 - The first child to swap. +* @param {any} child2 - The second child to swap. +*/ +Phaser.Group.prototype.swap = function (child1, child2) { + + this.swapChildren(child1, child2); + this.updateZ(); + +}; + +/** +* Brings the given child to the top of this group so it renders above all other children. +* +* @method Phaser.Group#bringToTop +* @param {any} child - The child to bring to the top of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.bringToTop = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length) + { + this.remove(child, false, true); + this.add(child, true); + } + + return child; + +}; + +/** +* Sends the given child to the bottom of this group so it renders below all other children. +* +* @method Phaser.Group#sendToBack +* @param {any} child - The child to send to the bottom of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.sendToBack = function (child) { + + if (child.parent === this && this.getIndex(child) > 0) + { + this.remove(child, false, true); + this.addAt(child, 0, true); + } + + return child; + +}; + +/** +* Moves the given child up one place in this group unless it's already at the top. +* +* @method Phaser.Group#moveUp +* @param {any} child - The child to move up in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveUp = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length - 1) + { + var a = this.getIndex(child); + var b = this.getAt(a + 1); + + if (b) + { + this.swap(child, b); + } + } + + return child; + +}; + +/** +* Moves the given child down one place in this group unless it's already at the bottom. +* +* @method Phaser.Group#moveDown +* @param {any} child - The child to move down in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveDown = 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; + +}; + +/** +* Positions the child found at the given index within this group to the given x and y coordinates. +* +* @method Phaser.Group#xy +* @param {integer} index - The index of the child in the group to set the position of. +* @param {number} x - The new x position of the child. +* @param {number} y - The new y position of the 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; + } + +}; + +/** +* Reverses all children in this group. +* +* This operation applies only to immediate children and does not propagate to subgroups. +* +* @method Phaser.Group#reverse +*/ +Phaser.Group.prototype.reverse = function () { + + this.children.reverse(); + this.updateZ(); + +}; + +/** +* Get the index position of the given child in this group, which should match the child's `z` property. +* +* @method Phaser.Group#getIndex +* @param {any} child - The child to get the index for. +* @return {integer} The index of the child or -1 if it's not a member of this group. +*/ +Phaser.Group.prototype.getIndex = function (child) { + + return this.children.indexOf(child); + +}; + +/** +* Searches the Group for the first instance of a child with the `name` +* property matching the given argument. Should more than one child have +* the same name only the first instance is returned. +* +* @method Phaser.Group#getByName +* @param {string} name - The name to search for. +* @return {any} The first child with a matching name, or null if none were found. +*/ +Phaser.Group.prototype.getByName = function (name) { + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].name === name) + { + return this.children[i]; + } + } + + return null; + +}; + +/** +* Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#replace +* @param {any} oldChild - The child in this group that will be replaced. +* @param {any} newChild - The child to be inserted into this group. +* @return {any} Returns the oldChild that was replaced within this group. +*/ +Phaser.Group.prototype.replace = function (oldChild, newChild) { + + var index = this.getIndex(oldChild); + + if (index !== -1) + { + if (newChild.parent) + { + if (newChild.parent instanceof Phaser.Group) + { + newChild.parent.remove(newChild); + } + else + { + newChild.parent.removeChild(newChild); + } + } + + this.remove(oldChild); + + this.addAt(newChild, index); + + return oldChild; + } + +}; + +/** +* Checks if the child has the given property. +* +* Will scan up to 4 levels deep only. +* +* @method Phaser.Group#hasProperty +* @param {any} child - The child to check for the existence of the property on. +* @param {string[]} key - An array of strings that make up the property. +* @return {boolean} True if the child has the property, otherwise false. +*/ +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; + +}; + +/** +* Sets a property to the given value on the child. The operation parameter controls how the value is set. +* +* The operations are: +* - 0: set the existing value to the given value; if force is `true` a new property will be created if needed +* - 1: will add the given value to the value already present. +* - 2: will subtract the given value from the value already present. +* - 3: will multiply the value already present by the given value. +* - 4: will divide the value already present by the given value. +* +* @method Phaser.Group#setProperty +* @param {any} child - The child to set the property value on. +* @param {array} key - An array of strings that make up the property that will be set. +* @param {any} value - The value that will be set. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) { + + if (force === undefined) { force = false; } + + operation = operation || 0; + + // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration. + + // 0 = Equals + // 1 = Add + // 2 = Subtract + // 3 = Multiply + // 4 = Divide + + // We can't force a property in and the child doesn't have it, so abort. + // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too. + 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; + +}; + +/** +* Checks a property for the given value on the child. +* +* @method Phaser.Group#checkProperty +* @param {any} child - The child to check the property value on. +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} True if `child` is a child of this Group and the property was equal to value, false if not. +*/ +Phaser.Group.prototype.checkProperty = function (child, key, value, force) { + + if (force === undefined) { force = false; } + + if (this !== child.parent) + { + return false; + } + + var result = Phaser.Utils.getProperty(child, key); + + if (((result === undefined) && force) || (result !== value)) + { + return false; + } + + return true; + +}; + +/** +* Quickly set a property on a single child of this group to a new value. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#set +* @param {Phaser.Sprite} child - The child to set the property on. +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true. +* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) { + + if (force === undefined) { force = false; } + + key = key.split('.'); + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible))) + { + return this.setProperty(child, key, value, operation, force); + } + +}; + +/** +* Quickly set the same property across all children of this group to a new value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. +* If you need that ability please see `Group.setAllChildren`. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAll +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + key = key.split('.'); + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + this.setProperty(this.children[i], key, value, operation, force); + } + } + +}; + +/** +* Quickly set the same property across all children of this group, and any child Groups, to a new value. +* +* If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. +* Unlike with `setAll` the property is NOT set on child Groups itself. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAllChildren +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + if (this.children[i] instanceof Phaser.Group) + { + this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force); + } + else + { + this.setProperty(this.children[i], key.split('.'), value, operation, force); + } + } + } + +}; + +/** +* Test that the same property across all children of this group is equal to the given value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAll +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} - True if all eligible children have the given property value (but see `force`); otherwise false. +*/ +Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (!this.checkProperty(child, key, value, force)) + { + return false; + } + } + } + + return true; + +}; + +/** +* Test that at least one child of this group has the given property value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAny +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @return {boolean} - True if at least one eligible child has the given property value; otherwise false. +*/ +Phaser.Group.prototype.checkAny = function (key, value, checkAlive, checkVisible) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (this.checkProperty(child, key, value)) + { + return true; + } + } + } + + return false; + +}; + +/** +* Adds the amount to the given property on all children in this group. +* +* `Group.addAll('x', 10)` will add 10 to the child.x value for each child. +* +* @method Phaser.Group#addAll +* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. +* @param {boolean} [checkAlive] - If true the property will only be changed if the child is alive. +* @param {boolean} [checkVisible] - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 1); + +}; + +/** +* Subtracts the amount from the given property on all children in this group. +* +* `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. +* +* @method Phaser.Group#subAll +* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 2); + +}; + +/** +* Multiplies the given property by the amount on all children in this group. +* +* `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. +* +* @method Phaser.Group#multiplyAll +* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 3); + +}; + +/** +* Divides the given property by the amount on all children in this group. +* +* `Group.divideAll('x', 2)` will half the child.x value for each child. +* +* @method Phaser.Group#divideAll +* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 4); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to false. + * + * @method Phaser.Group#kill + */ +Phaser.Group.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + +}; + +/** + * Kills all children having exists=true. + * + * @method Phaser.Group#killAll + */ +Phaser.Group.prototype.killAll = function () { + + this.callAllExists('kill', true); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to true. + * + * @method Phaser.Group#revive + */ +Phaser.Group.prototype.revive = function () { + + this.alive = true; + this.exists = true; + this.visible = true; + +}; + +/** + * Revives all children having exists=false. + * + * @method Phaser.Group#reviveAll + */ +Phaser.Group.prototype.reviveAll = function () { + + this.callAllExists('revive', false); + +}; + +/** +* Calls {@link #resetChild} on each child (or each existing child). +* +* @method Phaser.Group#resetAll +* @param {number} [x] - The x coordinate to reset each child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset each child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image or texture used by the Sprite during rendering. +* @param {string|number} [frame] - The frame of a sprite sheet or texture atlas. +* @param {boolean} [checkExists=false] - Reset only existing children. +*/ +Phaser.Group.prototype.resetAll = function (x, y, key, frame, checkExists) { + + this.forEach(this.resetChild, this, checkExists, x, y, key, frame); + +}; + +/** +* Calls a function, specified by name, on all children in the group who exist (or do not exist). +* +* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. +* +* @method Phaser.Group#callAllExists +* @param {string} callback - Name of the function on the children to call. +* @param {boolean} existsValue - Only children with exists=existsValue will be called. +* @param {...any} parameter - Additional parameters that will be passed to the callback. +*/ +Phaser.Group.prototype.callAllExists = function (callback, existsValue) { + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].exists === existsValue && this.children[i][callback]) + { + this.children[i][callback].apply(this.children[i], args); + } + } + +}; + +/** +* Returns a reference to a function that exists on a child of the group based on the given callback array. +* +* @method Phaser.Group#callbackFromArray +* @param {object} child - The object to inspect. +* @param {array} callback - The array of function names. +* @param {integer} length - The size of the array (pre-calculated in callAll). +* @protected +*/ +Phaser.Group.prototype.callbackFromArray = function (child, callback, length) { + + // Kinda looks like a Christmas tree + + if (length === 1) + { + if (child[callback[0]]) + { + return child[callback[0]]; + } + } + else if (length === 2) + { + if (child[callback[0]][callback[1]]) + { + return child[callback[0]][callback[1]]; + } + } + else if (length === 3) + { + if (child[callback[0]][callback[1]][callback[2]]) + { + return child[callback[0]][callback[1]][callback[2]]; + } + } + else if (length === 4) + { + if (child[callback[0]][callback[1]][callback[2]][callback[3]]) + { + return child[callback[0]][callback[1]][callback[2]][callback[3]]; + } + } + else if (child[callback]) + { + return child[callback]; + } + + return false; + +}; + +/** +* Calls a function, specified by name, on all on children. +* +* The function is called for all children regardless if they are dead or alive (see callAllExists for different options). +* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. +* +* @method Phaser.Group#callAll +* @param {string} method - Name of the function on the child to call. Deep property lookup is supported. +* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child. +* @param {...any} args - Additional parameters that will be passed to the method. +*/ +Phaser.Group.prototype.callAll = function (method, context) { + + if (method === undefined) + { + return; + } + + // Extract the method into an array + method = method.split('.'); + + var methodLength = method.length; + + if (context === undefined || context === null || context === '') + { + context = null; + } + else + { + // Extract the context into an array + if (typeof context === 'string') + { + context = context.split('.'); + var contextLength = context.length; + } + } + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + var callback = null; + var callbackContext = null; + + for (var i = 0; i < this.children.length; i++) + { + callback = this.callbackFromArray(this.children[i], method, methodLength); + + if (context && callback) + { + callbackContext = this.callbackFromArray(this.children[i], context, contextLength); + + if (callback) + { + callback.apply(callbackContext, args); + } + } + else if (callback) + { + callback.apply(this.children[i], args); + } + } + +}; + +/** +* The core preUpdate - as called by World. +* @method Phaser.Group#preUpdate +* @protected +*/ +Phaser.Group.prototype.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + // This chunk is identical to Phaser.Component.Core.prototype.preUpdateChildren, which is not yet defined. + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + return true; + +}; + +/** +* The core update - as called by World. +* +* Children with `exists = false` are updated unless {@link #updateOnlyExistingChildren} is true. +* +* @method Phaser.Group#update +* @protected +*/ +Phaser.Group.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + var len = this.children.length; + + if (i >= len) { i = len - 1; } + + var child = this.children[i]; + + if (!this.updateOnlyExistingChildren || child.exists) { + child.update(); + } + } + +}; + +/** +* The core postUpdate - as called by World. +* @method Phaser.Group#postUpdate +* @protected +*/ +Phaser.Group.prototype.postUpdate = function () { + + // Fixed to Camera? + if (this.fixedToCamera) + { + this.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; + this.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Find children matching a certain predicate. +* +* For example: +* +* var healthyList = Group.filter(function(child, index, children) { +* return child.health > 10 ? true : false; +* }, true); +* healthyList.callAll('attack'); +* +* Note: Currently this will skip any children which are Groups themselves. +* +* @method Phaser.Group#filter +* @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third +* @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. +* @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for +*/ +Phaser.Group.prototype.filter = function (predicate, checkExists) { + + var index = -1; + var length = this.children.length; + var results = []; + + while (++index < length) + { + var child = this.children[index]; + + if (!checkExists || (checkExists && child.exists)) + { + if (predicate(child, index, this.children)) + { + results.push(child); + } + } + } + + return new Phaser.ArraySet(results); + +}; + +/** +* Call a function on each child in this group. +* +* Additional arguments for the callback can be specified after the `checkExists` parameter. For example, +* +* Group.forEach(awardBonusGold, this, true, 100, 500) +* +* would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. +* +* Note: This check will skip any children which are Groups themselves. +* +* @method Phaser.Group#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) { + + if (checkExists === undefined) { checkExists = false; } + + if (arguments.length <= 3) + { + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + callback.call(callbackContext, this.children[i]); + } + } + } + else + { + // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE. + // Using an array and pushing each element (not a slice!) is _significantly_ faster. + var args = [null]; + + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + } + } + +}; + +/** +* Call a function on each existing child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachExists +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachExists = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each alive child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachAlive +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each dead child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachDead +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachDead = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Sort the children in the group according to a particular key and ordering. +* +* Call this function to sort the group according to a particular key value and order. +* +* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. +* +* Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including +* alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. +* +* @method Phaser.Group#sort +* @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value. +* @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}). +*/ +Phaser.Group.prototype.sort = function (key, order) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + if (key === undefined) { key = 'z'; } + if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; } + + this._sortProperty = key; + + if (order === Phaser.Group.SORT_ASCENDING) + { + this.children.sort(this.ascendingSortHandler.bind(this)); + } + else + { + this.children.sort(this.descendingSortHandler.bind(this)); + } + + this.updateZ(); + +}; + +/** +* Sort the children in the group according to custom sort function. +* +* The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). +* It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. +* +* @method Phaser.Group#customSort +* @param {function} sortHandler - The custom sort function. +* @param {object} [context=undefined] - The context in which the sortHandler is called. +*/ +Phaser.Group.prototype.customSort = function (sortHandler, context) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + this.children.sort(sortHandler.bind(context)); + + this.updateZ(); + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#ascendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.ascendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return -1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return 1; + } + else + { + if (a.z < b.z) + { + return -1; + } + else + { + return 1; + } + } + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#descendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.descendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return 1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return -1; + } + else + { + return 0; + } + +}; + +/** +* Iterates over the children of the group performing one of several actions for matched children. +* +* A child is considered a match when it has a property, named `key`, whose value is equal to `value` +* according to a strict equality comparison. +* +* The result depends on the `returnType`: +* +* - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}: +* The callback, if any, is applied to all matching children. The number of matched children is returned. +* - {@link Phaser.Group.RETURN_NONE RETURN_NONE}: +* The callback, if any, is applied to all matching children. No value is returned. +* - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}: +* The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. +* If there is no matching child then null is returned. +* +* If `args` is specified it must be an array. The matched child will be assigned to the first +* element and the entire array will be applied to the callback function. +* +* @method Phaser.Group#iterate +* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' +* @param {any} value - A child matches if `child[key] === value` is true. +* @param {integer} returnType - How to iterate the children and what to return. +* @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. +* @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null. +*/ +Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) { + + if (this.children.length === 0) + { + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return 0; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return []; + } + } + + var total = 0; + + if (returnType === Phaser.Group.RETURN_ALL) + { + var output = []; + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i][key] === value) + { + total++; + + if (callback) + { + if (args) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + else + { + callback.call(callbackContext, this.children[i]); + } + } + + if (returnType === Phaser.Group.RETURN_CHILD) + { + return this.children[i]; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + output.push(this.children[i]); + } + } + } + + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return total; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return output; + } + else + { + // RETURN_CHILD or RETURN_NONE + return null; + } + +}; + +/** +* Get the first display object with the given property name and value. +* +* @method Phaser.Group#getFirst +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {DisplayObject} The first child matching the query, or `null` if none were found. +*/ +Phaser.Group.prototype.getFirst = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_CHILD); + +}; + +/** +* Get the first display object that exists, or doesn't exist. +* +* You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstExists +* @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child. +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + if (typeof exists !== 'boolean') + { + exists = true; + } + + var child = this.getFirst('exists', exists); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is alive (`child.alive === true`). +* +* This is handy for choosing a squad leader, etc. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstAlive +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', true); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is dead (`child.alive === false`). +* +* This is handy for checking if everything has been wiped out and adding to the pool as needed. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstDead +* @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', false); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. +* +* If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. +* +* The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. +* +* @method Phaser.Group#resetChild +* @param {DisplayObject} child - The child to reset and/or load the texture on. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}. +*/ +Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) { + + if (child === null) + { + return null; + } + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (x !== null && y !== null) + { + child.reset(x, y); + } + + if (key !== undefined) + { + child.loadTexture(key, frame); + } + + return child; + +}; + +/** +* Return the child at the top of this group. +* +* The top child is the child displayed (rendered) above every other child. +* +* @method Phaser.Group#getTop +* @return {any} The child at the top of the Group. +*/ +Phaser.Group.prototype.getTop = function () { + + if (this.children.length > 0) + { + return this.children[this.children.length - 1]; + } + +}; + +/** +* Returns the child at the bottom of this group. +* +* The bottom child the child being displayed (rendered) below every other child. +* +* @method Phaser.Group#getBottom +* @return {any} The child at the bottom of the Group. +*/ +Phaser.Group.prototype.getBottom = function () { + + if (this.children.length > 0) + { + return this.children[0]; + } + +}; + +/** +* Get the closest child to given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getClosestTo +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child closest to given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContext) { + + var distance = Number.MAX_VALUE; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance < distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the child furthest away from the given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getFurthestFrom +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child furthest from the given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackContext) { + + var distance = 0; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance > distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the number of children with the given property name and value. +* +* @method Phaser.Group#count +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {integer} The number of children matching the query. +*/ +Phaser.Group.prototype.count = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_TOTAL); + +}; + +/** +* Get the number of living children in this group. +* +* @method Phaser.Group#countLiving +* @return {integer} The number of children flagged as alive. +*/ +Phaser.Group.prototype.countLiving = function () { + + return this.count('alive', true); + +}; + +/** +* Get the number of dead children in this group. +* +* @method Phaser.Group#countDead +* @return {integer} The number of children flagged as dead. +*/ +Phaser.Group.prototype.countDead = function () { + + return this.count('alive', false); + +}; + +/** +* Returns a random child from the group. +* +* @method Phaser.Group#getRandom +* @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). +* @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. +* @return {any} A random child of this Group. +*/ +Phaser.Group.prototype.getRandom = function (startIndex, length) { + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = this.children.length; } + + if (length === 0) + { + return null; + } + + return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length); + +}; + +/** +* Returns a random child from the Group that has `exists` set to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only +* the first 50 children in the Group. +* +* @method Phaser.Group#getRandomExists +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up to. +* @return {any} A random child of this Group that exists. +*/ +Phaser.Group.prototype.getRandomExists = function (startIndex, endIndex) { + + var list = this.getAll('exists', true, startIndex, endIndex); + + return this.game.rnd.pick(list); + +}; + +/** +* Returns all children in this Group. +* +* You can optionally specify a matching criteria using the `property` and `value` arguments. +* +* For example: `getAll('exists', true)` would return only children that have an `exists` property equal to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return the first 50 children in the Group. +* If `property` and `value` are also specified, only children within the given index range are searched. +* +* @method Phaser.Group#getAll +* @param {string} [property] - An optional property to test against the value argument. +* @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results. +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up until. +* @return {array} - An array containing all, some, or none of the Children of this Group. +*/ +Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) { + + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var output = []; + + for (var i = startIndex; i < endIndex; i++) + { + var child = this.children[i]; + + if (property) + { + if (child[property] === value) + { + output.push(child); + } + } + else + { + output.push(child); + } + } + + return output; + +}; + +/** +* Removes the given child from this group. +* +* This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. +* +* If the group cursor was referring to the removed child it is updated to refer to the next child. +* +* @method Phaser.Group#remove +* @param {any} child - The child to remove. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child. +* @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event. +* @return {boolean} true if the child was removed from this group, otherwise false. +*/ +Phaser.Group.prototype.remove = function (child, destroy, silent) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + + if (this.children.length === 0 || this.children.indexOf(child) === -1) + { + return false; + } + + if (!silent && child.events && !child.destroyPhase) + { + child.events.onRemovedFromGroup$dispatch(child, this); + } + + var removed = this.removeChild(child); + + this.removeFromHash(child); + + this.updateZ(); + + if (this.cursor === child) + { + this.next(); + } + + if (destroy && removed) + { + removed.destroy(true); + } + + return true; + +}; + +/** +* Moves all children from this Group to the Group given. +* +* @method Phaser.Group#moveAll +* @param {Phaser.Group} group - The new Group to which the children will be moved to. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group. +* @return {Phaser.Group} The Group to which all the children were moved. +*/ +Phaser.Group.prototype.moveAll = function (group, silent) { + + if (silent === undefined) { silent = false; } + + if (this.children.length > 0 && group instanceof Phaser.Group) + { + do + { + group.add(this.children[0], silent); + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + } + + return group; + +}; + +/** +* Removes all children from this Group, but does not remove the group from its parent. +* +* The children can be optionally destroyed as they are removed. +* +* You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've +* more than one Game Object sharing the same BaseTexture. +* +* @method Phaser.Group#removeAll +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +* @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. +*/ +Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + if (destroyTexture === undefined) { destroyTexture = false; } + + if (this.children.length === 0) + { + return; + } + + do + { + if (!silent && this.children[0].events) + { + this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this); + } + + var removed = this.removeChild(this.children[0]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true, destroyTexture); + } + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + +}; + +/** +* Removes all children from this group whose index falls beteen the given startIndex and endIndex values. +* +* @method Phaser.Group#removeBetween +* @param {integer} startIndex - The index to start removing children from. +* @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +*/ +Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) { + + if (endIndex === undefined) { endIndex = this.children.length - 1; } + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = 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 (!silent && this.children[i].events) + { + this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this); + } + + var removed = this.removeChild(this.children[i]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true); + } + + if (this.cursor === this.children[i]) + { + this.cursor = null; + } + + i--; + } + + this.updateZ(); + +}; + +/** + * Places each child at a random position within the given Rectangle (or the {@link Phaser.World#bounds World bounds}). + * + * @method Phaser.Group#scatter + * @param {Phaser.Rectangle} [rect=this.game.world.bounds] - A Rectangle. If omitted {@link Phaser.World#bounds} is used. + * @param {boolean} [checkExists=false] - Place only children with exists=true. + */ +Phaser.Group.prototype.scatter = function (rect, checkExists) { + + if (rect == null) { rect = this.game.world.bounds; } + + this.forEach(function (child) { + + child.position.set(rect.randomX, rect.randomY); + + }, null, checkExists); + +}; + +/** + * Orders this Group's children randomly. + * + * This can be more efficient than calling {@link #getRandom} repeatedly. + * + * @method Phaser.Group#shuffle + */ +Phaser.Group.prototype.shuffle = function () { + + Phaser.ArrayUtils.shuffle(this.children); + this.updateZ(); + +}; + +/** +* Destroys this group. +* +* Removes all children, then removes this group from its parent and nulls references. +* +* @method Phaser.Group#destroy +* @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. +*/ +Phaser.Group.prototype.destroy = function (destroyChildren, soft) { + + if (this.game === null || this.ignoreDestroy) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (soft === undefined) { soft = false; } + + this.onDestroy.dispatch(this, destroyChildren, soft); + + this.removeAll(destroyChildren); + + this.cursor = null; + this.filters = null; + this.pendingDestroy = false; + + if (!soft) + { + if (this.parent) + { + this.parent.removeChild(this); + } + + this.game = null; + this.exists = false; + } + +}; + +/** +* Total number of existing children in the group. +* +* @name Phaser.Group#total +* @property {integer} total +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "total", { + + get: function () { + + return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); + + } + +}); + +/** +* Total number of children in this group, regardless of exists/alive status. +* +* @name Phaser.Group#length +* @property {integer} length +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "length", { + + get: function () { + + return this.children.length; + + } + +}); + +/** +* The angle of rotation of the group container, in degrees. +* +* This adjusts the group itself by modifying its local rotation transform. +* +* This has no impact on the rotation/angle properties of the children, but it will update their worldTransform +* and on-screen orientation and position. +* +* @name Phaser.Group#angle +* @property {number} angle +*/ +Object.defineProperty(Phaser.Group.prototype, "angle", { + + get: function() { + return Phaser.Math.radToDeg(this.rotation); + }, + + set: function(value) { + this.rotation = Phaser.Math.degToRad(value); + } + +}); + +/** +* The center x coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerX +* @property {number} centerX +*/ +Object.defineProperty(Phaser.Group.prototype, "centerX", { + + get: function () { + + return this.getBounds(this.parent).centerX; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.halfWidth; + + } + +}); + +/** +* The center y coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerY +* @property {number} centerY +*/ +Object.defineProperty(Phaser.Group.prototype, "centerY", { + + get: function () { + + return this.getBounds(this.parent).centerY; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.halfHeight; + + } + +}); + +/** +* The left coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#left +* @property {number} left +*/ +Object.defineProperty(Phaser.Group.prototype, "left", { + + get: function () { + + return this.getBounds(this.parent).left; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = value + offset; + + } + +}); + +/** +* The right coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#right +* @property {number} right +*/ +Object.defineProperty(Phaser.Group.prototype, "right", { + + get: function () { + + return this.getBounds(this.parent).right; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.width; + + } + +}); + +/** +* The top coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#top +* @property {number} top +*/ +Object.defineProperty(Phaser.Group.prototype, "top", { + + get: function () { + + return this.getBounds(this.parent).top; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset); + + } + +}); + +/** +* The bottom coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#bottom +* @property {number} bottom +*/ +Object.defineProperty(Phaser.Group.prototype, "bottom", { + + get: function () { + + return this.getBounds(this.parent).bottom; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.height; + + } + +}); + +/** +* Aligns this Group within another Game Object, or Rectangle, known as the +* 'container', to one of 9 possible positions. +* +* The container must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the container. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, +* `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, +* `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* container, taking into consideration rotation and scale of its children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignIn +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* Aligns this Group to the side of another Game Object, or Rectangle, known as the +* 'parent', in one of 11 possible positions. +* +* The parent must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the parent. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, +* `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, +* `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` +* and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* parent, taking into consideration rotation and scale of the children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignTo +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* A display object is any object that can be rendered in the Phaser/pixi.js scene graph: +* +* - {@link PIXI.DisplayObject} +* - {@link PIXI.DisplayObjectContainer} +* - {@link Phaser.BitmapText} +* - {@link Phaser.Creature} +* - {@link Phaser.Graphics} +* - {@link Phaser.Group} +* - {@link Phaser.FlexLayer} +* - {@link Phaser.Particles.Arcade.Emitter} +* - {@link Phaser.Physics.P2.BodyDebug} +* - {@link Phaser.SpriteBatch} +* - {@link Phaser.World} +* - {@link Phaser.Rope} +* - {@link Phaser.Stage} +* - {@link PIXI.Sprite} +* - {@link Phaser.Image} +* - {@link Phaser.Button} +* - {@link Phaser.Sprite} +* - {@link Phaser.Bullet} +* - {@link Phaser.Particle} +* - {@link Phaser.Text} +* - {@link Phaser.TilemapLayer} +* - {@link Phaser.TileSprite} +* +* @typedef {object} DisplayObject +*/ +// Documentation stub for linking. + +/** +* The x coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#x +* @property {number} x +*/ + +/** +* The y coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#y +* @property {number} y +*/ + +/** +* The angle of rotation of the group container, in radians. +* +* This will adjust the group container itself by modifying its rotation. +* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#rotation +* @property {number} rotation +*/ + +/** +* The visible state of the group. Non-visible Groups and all of their children are not rendered. +* +* @name Phaser.Group#visible +* @property {boolean} visible +*/ + +/** +* The alpha value of the group container. +* +* @name Phaser.Group#alpha +* @property {number} alpha +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* "This world is but a canvas to our imagination." - Henry David Thoreau +* +* A game has only one world. The world is an abstract place in which all game objects live. It is not bound +* by stage limits and can be any size. You look into the world via cameras. All game objects live within +* the world at world-based coordinates. By default a world is created the same size as your Stage. +* +* @class Phaser.World +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.World = function (game) { + + Phaser.Group.call(this, game, null, '__world', false); + + /** + * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. + * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. + * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. + * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. + * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height); + + /** + * @property {Phaser.Camera} camera - Camera instance. + */ + this.camera = null; + + /** + * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. + * @readonly + */ + this._definedSize = false; + + /** + * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._width = game.width; + + /** + * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._height = game.height; + + this.game.state.onStateChange.add(this.stateChange, this); + +}; + +Phaser.World.prototype = Object.create(Phaser.Group.prototype); +Phaser.World.prototype.constructor = Phaser.World; + +/** +* Initialises the game world. +* +* @method Phaser.World#boot +* @protected +*/ +Phaser.World.prototype.boot = function () { + + this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height); + + this.game.stage.addChild(this); + + this.camera.boot(); + +}; + +/** +* Called whenever the State changes or resets. +* +* It resets the world.x and world.y coordinates back to zero, +* then resets the Camera. +* +* @method Phaser.World#stateChange +* @protected +*/ +Phaser.World.prototype.stateChange = function () { + + this.x = 0; + this.y = 0; + + this.camera.reset(); + +}; + +/** +* Updates the size of this world and sets World.x/y to the given values +* The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. +* +* @method Phaser.World#setBounds +* @param {number} x - Top left most corner of the world. +* @param {number} y - Top left most corner of the world. +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.setBounds = function (x, y, width, height) { + + this._definedSize = true; + this._width = width; + this._height = height; + + this.bounds.setTo(x, y, width, height); + + this.x = x; + this.y = y; + + if (this.camera.bounds) + { + // The Camera can never be smaller than the game size + this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height)); + } + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Updates this world's width and height (but not smaller than any previous {@link #setBounds defined size}). +* +* Phaser uses this to adapt to {@link Phaser.ScaleManager#updateDimensions layout changes}. +* You probably want to use {@link #setBounds} instead. +* +* @method Phaser.World#resize +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.resize = function (width, height) { + + // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size + + if (this._definedSize) + { + if (width < this._width) + { + width = this._width; + } + + if (height < this._height) + { + height = this._height; + } + } + + this.bounds.width = width; + this.bounds.height = height; + + this.game.camera.setBoundsToWorld(); + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Destroyer of worlds. +* +* @method Phaser.World#shutdown +*/ +Phaser.World.prototype.shutdown = function () { + + // World is a Group, so run a soft destruction on this and all children. + this.destroy(true, true); + +}; + +/** +* This will take the given game object and check if its x/y coordinates fall outside of the world bounds. +* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. +* If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. +* +* Please understand there are limitations to this method. For example if you have scaled the World +* then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. +* +* @method Phaser.World#wrap +* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) { + + if (padding === undefined) { padding = 0; } + if (useBounds === undefined) { useBounds = false; } + if (horizontal === undefined) { horizontal = true; } + if (vertical === undefined) { vertical = true; } + + if (!useBounds) + { + if (horizontal && sprite.x + padding < this.bounds.x) + { + sprite.x = this.bounds.right + padding; + } + else if (horizontal && sprite.x - padding > this.bounds.right) + { + sprite.x = this.bounds.left - padding; + } + + if (vertical && sprite.y + padding < this.bounds.top) + { + sprite.y = this.bounds.bottom + padding; + } + else if (vertical && sprite.y - padding > this.bounds.bottom) + { + sprite.y = this.bounds.top - padding; + } + } + else + { + sprite.getBounds(); + + if (horizontal) + { + if ((sprite.x + sprite._currentBounds.width) < this.bounds.x) + { + sprite.x = this.bounds.right; + } + else if (sprite.x > this.bounds.right) + { + sprite.x = this.bounds.left; + } + } + + if (vertical) + { + if ((sprite.y + sprite._currentBounds.height) < this.bounds.top) + { + sprite.y = this.bounds.bottom; + } + else if (sprite.y > this.bounds.bottom) + { + sprite.y = this.bounds.top; + } + } + } + +}; + +/** +* @method Phaser.World#wrapAll +* @param {Phaser.Group} group - A group of sprites. +* @param {boolean} [checkExists=false] - Wrap only sprites having `exists=true`. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrapAll = function (group, checkExists, padding, useBounds, horizontal, vertical) { + + group.forEach(this.wrap, this, checkExists, padding, useBounds, horizontal, vertical); + +}; + +/** +* @name Phaser.World#width +* @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "width", { + + get: function () { + return this.bounds.width; + }, + + set: function (value) { + + if (value < this.game.width) + { + value = this.game.width; + } + + this.bounds.width = value; + this._width = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#height +* @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "height", { + + get: function () { + return this.bounds.height; + }, + + set: function (value) { + + if (value < this.game.height) + { + value = this.game.height; + } + + this.bounds.height = value; + this._height = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#centerX +* @property {number} centerX - Gets the X position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerX", { + + get: function () { + return this.bounds.halfWidth + this.bounds.x; + } + +}); + +/** +* @name Phaser.World#centerY +* @property {number} centerY - Gets the Y position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerY", { + + get: function () { + return this.bounds.halfHeight + this.bounds.y; + } + +}); + +/** +* @name Phaser.World#randomX +* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomX", { + + get: function () { + + if (this.bounds.x < 0) + { + return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x))); + } + else + { + return this.game.rnd.between(this.bounds.x, this.bounds.width); + } + + } + +}); + +/** +* @name Phaser.World#randomY +* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomY", { + + get: function () { + + if (this.bounds.y < 0) + { + return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y))); + } + else + { + return this.game.rnd.between(this.bounds.y, this.bounds.height); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Game object is the main controller for the entire Phaser game. It is responsible +* for handling the boot process, parsing the configuration values, creating the renderer, +* and setting-up all of the Phaser systems, such as physics, sound and input. +* Once that is complete it will start the default State, and then begin the main game loop. +* +* You can access lots of the Phaser systems via the properties on the `game` object. For +* example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on. +* +* Anywhere you can access the `game` property, you can access all of these core systems. +* For example a Sprite has a `game` property, allowing you to talk to the various parts +* of Phaser directly, without having to look after your own references. +* +* In it's most simplest form, a Phaser game can be created by providing the arguments +* to the constructor: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create }); +* ``` +* +* In the example above it is passing in a State object directly. You can also use the State +* Manager to do this: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO); +* game.state.add('Boot', BasicGame.Boot); +* game.state.add('Preloader', BasicGame.Preloader); +* game.state.add('MainMenu', BasicGame.MainMenu); +* game.state.add('Game', BasicGame.Game); +* game.state.start('Boot'); +* ``` +* +* In the example above, 4 States are added to the State Manager, and Phaser is told to +* start running the `Boot` state when it has finished initializing. There are example +* project templates you can use in the Phaser GitHub repo, inside the `resources` folder. +* +* Instead of specifying arguments you can also pass {@link GameConfig a single object} instead: +* +* ```javascript +* var config = { +* width: 800, +* height: 600, +* renderer: Phaser.AUTO, +* antialias: true, +* multiTexture: true, +* state: { +* preload: preload, +* create: create, +* update: update +* } +* } +* +* var game = new Phaser.Game(config); +* ``` +* +* @class Phaser.Game +* @constructor +* @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. +* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. +* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). +* @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body. +* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. +* @param {boolean} [transparent=false] - Use a transparent canvas background or not. +* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) { + + /** + * @property {number} id - Phaser Game ID + * @readonly + */ + this.id = Phaser.GAMES.push(this) - 1; + + /** + * @property {object} config - The Phaser.Game configuration object. + */ + this.config = null; + + /** + * @property {object} physicsConfig - The Phaser.Physics.World configuration object. + */ + this.physicsConfig = physicsConfig; + + /** + * @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted. + * @readonly + * @default + */ + this.parent = ''; + + /** + * The current Game Width in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} width + * @readonly + * @default + */ + this.width = 800; + + /** + * The current Game Height in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} height + * @readonly + * @default + */ + this.height = 600; + + /** + * The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object. + * + * @property {integer} resolution + * @readonly + * @default + */ + this.resolution = 1; + + /** + * @property {integer} _width - Private internal var. + * @private + */ + this._width = 800; + + /** + * @property {integer} _height - Private internal var. + * @private + */ + this._height = 600; + + /** + * @property {boolean} transparent - Use a transparent canvas background or not. + * @default + */ + this.transparent = false; + + /** + * @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead. + * @readonly + * @default + */ + this.antialias = true; + + /** + * Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property. + * To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game + * Configuration object with the property `multiTexture` set to true. It has to be enabled before + * Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it + * via the `game.renderer.setTexturePriority` method. + * + * @property {boolean} multiTexture + * @readonly + * @default + */ + this.multiTexture = false; + + /** + * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * @default + */ + this.preserveDrawingBuffer = false; + + /** + * Clear the Canvas each frame before rendering the display list. + * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. + * This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage. + * @property {boolean} clearBeforeRender + * @default + */ + this.clearBeforeRender = true; + + /** + * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. + * @protected + */ + this.renderer = null; + + /** + * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `render` hooks but not `preRender` or `postRender`; set {@link lockRender} to skip those as well. + * @readonly + */ + this.renderType = Phaser.AUTO; + + /** + * @property {Phaser.StateManager} state - The StateManager. + */ + this.state = null; + + /** + * @property {boolean} isBooted - Whether the game engine is booted, aka available. + * @readonly + */ + this.isBooted = false; + + /** + * @property {boolean} isRunning - Is game running or paused? + * @readonly + */ + this.isRunning = false; + + /** + * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout + * @protected + */ + this.raf = null; + + /** + * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. + */ + this.make = null; + + /** + * @property {Phaser.Cache} cache - Reference to the assets cache. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - Reference to the input manager + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - Reference to the assets loader. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - Reference to the math helper. + */ + this.math = null; + + /** + * @property {Phaser.Net} net - Reference to the network class. + */ + this.net = null; + + /** + * @property {Phaser.ScaleManager} scale - The game scale manager. + */ + this.scale = null; + + /** + * @property {Phaser.SoundManager} sound - Reference to the sound manager. + */ + this.sound = null; + + /** + * @property {Phaser.Stage} stage - Reference to the stage. + */ + this.stage = null; + + /** + * @property {Phaser.Time} time - Reference to the core game clock. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - Reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - Reference to the world. + */ + this.world = null; + + /** + * @property {Phaser.Physics} physics - Reference to the physics manager. + */ + this.physics = null; + + /** + * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. + */ + this.plugins = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. + */ + this.rnd = null; + + /** + * @property {Phaser.Device} device - Contains device information and capabilities. + */ + this.device = Phaser.Device; + + /** + * @property {Phaser.Camera} camera - A handy reference to world.camera. + */ + this.camera = null; + + /** + * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) + */ + this.context = null; + + /** + * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. + */ + this.debug = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. + */ + this.particles = null; + + /** + * @property {Phaser.Create} create - The Asset Generator. + */ + this.create = null; + + /** + * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. + * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. + * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. + * @property {boolean} lockRender + * @default + */ + this.lockRender = false; + + /** + * @property {boolean} pendingDestroy - Destroy the game at the next update. + * @default + */ + this.pendingDestroy = false; + + /** + * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). + * @default + * @readonly + */ + this.stepping = false; + + /** + * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. + * @default + * @readonly + */ + this.pendingStep = false; + + /** + * @property {number} stepCount - When stepping is enabled this contains the current step cycle. + * @default + * @readonly + */ + this.stepCount = 0; + + /** + * @property {Phaser.Signal} onPause - This event is fired when the game pauses. + */ + this.onPause = null; + + /** + * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. + */ + this.onResume = null; + + /** + * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). + */ + this.onBlur = null; + + /** + * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). + */ + this.onFocus = null; + + /** + * @property {boolean} _paused - Is game paused? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _codePaused - Was the game paused via code or a visibility change? + * @private + */ + this._codePaused = false; + + /** + * The ID of the current/last logic update applied this animation frame, starting from 0. + * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` + * @property {integer} currentUpdateID + * @protected + */ + this.currentUpdateID = 0; + + /** + * Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed). + * @property {integer} updatesThisFrame + * @protected + */ + this.updatesThisFrame = 1; + + /** + * Number of renders expected to occur this animation frame. May be 0 if {@link #dropFrames is on} or {@link #forceSingleRender} is off; otherwise it will be 1. + * @property {integer} updatesThisFrame + * @protected + */ + this.rendersThisFrame = 1; + + /** + * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. + * @private + */ + this._deltaTime = 0; + + /** + * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. + * @private + */ + this._lastCount = 0; + + /** + * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. + * @private + */ + this._spiraling = 0; + + /** + * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) + * @private + */ + this._kickstart = true; + + /** + * If the game is struggling to maintain the desired FPS, this signal will be dispatched. + * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. + * @property {Phaser.Signal} fpsProblemNotifier + * @public + */ + this.fpsProblemNotifier = new Phaser.Signal(); + + /** + * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? You can toggle it on the fly. + */ + this.forceSingleUpdate = true; + + /** + * @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update? (During spiraling conditions, {@link #dropFrames} is used instead.) + */ + this.forceSingleRender = true; + + /** + * @property {boolean} dropFrames - When {@link #forceSingleUpdate} is off, skip {@link #updateRender rendering} if logic updates are spiraling upwards. + */ + this.dropFrames = false; + + /** + * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. + * @private + */ + this._nextFpsNotification = 0; + + // Parse the configuration object (if any) + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + this.parseConfig(arguments[0]); + } + else + { + this.config = { enableDebug: true }; + + if (typeof width !== 'undefined') + { + this._width = width; + } + + if (typeof height !== 'undefined') + { + this._height = height; + } + + if (typeof renderer !== 'undefined') + { + 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); + } + + this.device.whenReady(this.boot, this); + + return this; + +}; + +/** +* A configuration object for {@link Phaser.Game}. +* +* @typedef {object} GameConfig +* @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}. +* @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}. +* @property {number|string} [GameConfig.antialias=true] +* @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}. +* @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in. +* @property {string} [GameConfig.canvasId] - `id` attribute value to assign to the game canvas. +* @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas. +* @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}. +* @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange} +* @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing. +* @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production. +* @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO. +* @property {boolean} [GameConfig.forceSetTimeout] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeOut} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available. +* @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen. +* @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked. +* @property {number|string} [GameConfig.height=600] +* @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`. +* @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected. +* @property {object} [GameConfig.physicsConfig] +* @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering. +* @property {number} [GameConfig.renderer=Phaser.AUTO] +* @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels. +* @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices. +* @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen. +* @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}. +* @property {object} [GameConfig.state] +* @property {boolean} [GameConfig.transparent=false] +* @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode. +* @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode. +* @property {number|string} [GameConfig.width=800] +*/ +// Documentation stub for linking. + +Phaser.Game.prototype = { + + /** + * Parses a Game configuration object. + * + * @method Phaser.Game#parseConfig + * @protected + */ + parseConfig: function (config) { + + this.config = config; + + if (config['enableDebug'] === undefined) + { + this.config.enableDebug = true; + } + + if (config['width']) + { + this._width = config['width']; + } + + if (config['height']) + { + this._height = config['height']; + } + + if (config['renderer']) + { + this.renderType = config['renderer']; + } + + if (config['parent']) + { + this.parent = config['parent']; + } + + if (config['transparent'] !== undefined) + { + this.transparent = config['transparent']; + } + + if (config['antialias'] !== undefined) + { + this.antialias = config['antialias']; + } + + if (config['multiTexture'] !== undefined) + { + this.multiTexture = config['multiTexture']; + } + + if (config['resolution']) + { + this.resolution = config['resolution']; + } + + if (config['preserveDrawingBuffer'] !== undefined) + { + this.preserveDrawingBuffer = config['preserveDrawingBuffer']; + } + + 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); + + }, + + /** + * Initialize engine sub modules and start the game. + * + * @method Phaser.Game#boot + * @protected + */ + boot: function () { + + if (this.isBooted) + { + return; + } + + this.onPause = new Phaser.Signal(); + this.onResume = new Phaser.Signal(); + this.onBlur = new Phaser.Signal(); + this.onFocus = new Phaser.Signal(); + + this.isBooted = true; + + PIXI.game = this; + + this.math = Phaser.Math; + + this.scale = new Phaser.ScaleManager(this, this._width, this._height); + this.stage = new Phaser.Stage(this); + + this.setUpRenderer(); + + 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.create = new Phaser.Create(this); + this.plugins = new Phaser.PluginManager(this); + this.net = new Phaser.Net(this); + + this.time.boot(); + this.stage.boot(); + this.world.boot(); + this.scale.boot(); + this.input.boot(); + this.sound.boot(); + this.state.boot(); + + if (this.config['enableDebug']) + { + this.debug = new Phaser.Utils.Debug(this); + this.debug.boot(); + } + else + { + this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {}, isDisabled: true }; + } + + 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._kickstart = true; + + if (window['focus']) + { + if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus)) + { + window.focus(); + } + } + + if (this.config['disableStart']) + { + return; + } + + if (this.cache.isReady) + { + this.raf.start(); + } + else + { + this.cache.onReady.addOnce(function () { + this.raf.start(); + }, this); + } + + }, + + /** + * Displays a Phaser version debug header in the console. + * + * @method Phaser.Game#showDebugHeader + * @protected + */ + showDebugHeader: function () { + + if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner) + { + return; + } + + 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.ie) // https://developer.mozilla.org/en-US/docs/Web/API/Console/log#Browser_compatibility + { + var args = [ + '%c %c %c Phaser CE v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665', + 'background: #fb8cb3', + 'background: #d44a52', + 'color: #ffffff; background: #871905;', + 'background: #d44a52', + 'background: #fb8cb3', + 'background: #ffffff' + ]; + + for (var i = 0; i < 3; i++) + { + if (i < c) + { + args.push('color: #ff2424; background: #fff'); + } + else + { + args.push('color: #959595; background: #fff'); + } + } + + console.log.apply(console, args); + } + else if (window['console']) + { + console.log('Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' | http://phaser.io'); + } + + }, + + /** + * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. + * + * @method Phaser.Game#setUpRenderer + * @protected + */ + setUpRenderer: function () { + + if (!this.device.canvas) + { + // Nothing else to do + throw new Error('Phaser.Game - Cannot create Canvas 2d context, aborting.'); + } + + if (this.config['canvas']) + { + this.canvas = this.config['canvas']; + } + else + { + this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true); + } + + if (this.config['canvasStyle']) + { + this.canvas.style = this.config['canvasStyle']; + } + else + { + this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; + } + + if (this.config['crisp']) + { + Phaser.Canvas.setImageRenderingCrisp(this.canvas); + } + + if ((this.renderType === Phaser.WEBGL) || + (this.renderType === Phaser.WEBGL_MULTI) || + (this.renderType === Phaser.AUTO && this.device.webGL)) + { + if (this.multiTexture || this.renderType === Phaser.WEBGL_MULTI) + { + PIXI.enableMultiTexture(); + this.multiTexture = true; + } + + try + { + this.renderer = new PIXI.WebGLRenderer(this, this.config); + this.renderType = Phaser.WEBGL; + this.context = null; + this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); + this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); + } + catch (webGLRendererError) + { + this.renderer = null; + this.multiTexture = false; + PIXI._enableMultiTextureToggle = false; + + if (this.renderType === Phaser.WEBGL) + { + // No fallback + throw webGLRendererError; + } + } + } + + if (!this.renderer) + { + this.renderer = new PIXI.CanvasRenderer(this, this.config); + this.context = this.renderer.context; + + if (this.renderType === Phaser.AUTO) + { + this.renderType = Phaser.CANVAS; + } + } + + if (this.device.cocoonJS) + { + this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false; + } + + if (this.renderType !== Phaser.HEADLESS) + { + this.stage.smoothed = this.antialias; + + Phaser.Canvas.addToDOM(this.canvas, this.parent, false); + Phaser.Canvas.setTouchAction(this.canvas); + } + + }, + + /** + * Handles WebGL context loss. + * + * @method Phaser.Game#contextLost + * @private + * @param {Event} event - The webglcontextlost event. + */ + contextLost: function (event) { + + event.preventDefault(); + + this.renderer.contextLost = true; + + }, + + /** + * Handles WebGL context restoration. + * + * @method Phaser.Game#contextRestored + * @private + */ + contextRestored: function () { + + this.renderer.initContext(); + + this.cache.clearGLTextures(); + + this.renderer.contextLost = false; + + }, + + /** + * The core game loop. + * + * @method Phaser.Game#update + * @protected + * @param {number} time - The current time as provided by RequestAnimationFrame. + */ + update: function (time) { + + if (this.pendingDestroy) + { + this.destroy(); + return; + } + + this.time.update(time); + + if (this._kickstart) + { + this.updateLogic(this.time.desiredFpsMult); + + // call the game render update exactly once every frame + this.updateRender(this.time.slowMotion * this.time.desiredFps); + + this._kickstart = false; + + return; + } + + // if the logic time is spiraling upwards, skip a frame entirely + if (this._spiraling > 1 && !this.forceSingleUpdate) + { + // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate + if (this.time.time > this._nextFpsNotification) + { + // only permit one fps notification per 10 seconds + this._nextFpsNotification = this.time.time + 10000; + + // dispatch the notification signal + this.fpsProblemNotifier.dispatch(); + } + + // reset the _deltaTime accumulator which will cause all pending late updates to be permanently skipped + this._deltaTime = 0; + this._spiraling = 0; + + if (this.dropFrames) + { + this.rendersThisFrame = 0; + } + else + { + this.updateRender(this.time.slowMotion * this.time.desiredFps); + this.rendersThisFrame = 1; + } + } + else + { + // step size taking into account the slow motion speed + var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps; + + // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals + this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0); + + // call the game update logic multiple times if necessary to "catch up" with dropped frames + // unless forceSingleUpdate is true + var count = 0; + + this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); + + if (this.forceSingleUpdate) + { + this.updatesThisFrame = Math.min(1, this.updatesThisFrame); + } + + if (this.forceSingleRender) + { + this.rendersThisFrame = 1; + } + else + { + this.rendersThisFrame = Math.min(1, this.updatesThisFrame); + } + + while (this._deltaTime >= slowStep) + { + this._deltaTime -= slowStep; + this.currentUpdateID = count; + + this.updateLogic(this.time.desiredFpsMult); + + count++; + + if (this.forceSingleUpdate && count === 1) + { + break; + } + else + { + this.time.refresh(); + } + } + + // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly) + if (count > this._lastCount) + { + this._spiraling++; + } + else if (count < this._lastCount) + { + // looks like it caught up successfully, reset the spiral alert counter + this._spiraling = 0; + } + + this._lastCount = count; + + if (this.rendersThisFrame > 0) + { + this.updateRender(this._deltaTime / slowStep); + } + } + + }, + + /** + * Updates all logic subsystems in Phaser. Called automatically by Game.update. + * + * @method Phaser.Game#updateLogic + * @protected + * @param {number} timeStep - The current timeStep value as determined by Game.update. + */ + updateLogic: function (timeStep) { + + if (!this._paused && !this.pendingStep) + { + if (this.stepping) + { + this.pendingStep = true; + } + + this.time.countUpdate(); + + this.scale.preUpdate(); + this.debug.preUpdate(); + this.camera.preUpdate(); + this.physics.preUpdate(); + this.state.preUpdate(timeStep); + this.plugins.preUpdate(timeStep); + this.stage.preUpdate(); + + this.state.update(); + this.stage.update(); + this.tweens.update(); + this.sound.update(); + this.input.update(); + this.physics.update(); + this.plugins.update(); + + this.stage.postUpdate(); + this.plugins.postUpdate(); + } + else + { + // Scaling and device orientation changes are still reflected when paused. + this.scale.pauseUpdate(); + this.state.pauseUpdate(timeStep); + this.debug.preUpdate(); + this.input.pauseUpdate(); + } + + this.stage.updateTransform(); + + }, + + /** + * Runs the Render cycle. + * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. + * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. + * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. + * After this State.render is called. Any rendering that happens here will take place on-top of the display list. + * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. + * This method is called automatically by Game.update, you don't need to call it directly. + * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. + * Phaser will only render when this boolean is `false`. + * + * @method Phaser.Game#updateRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + updateRender: function (elapsedTime) { + + if (this.lockRender) + { + return; + } + + this.time.countRender(); + + this.state.preRender(elapsedTime); + + if (this.renderType !== Phaser.HEADLESS) + { + this.renderer.render(this.stage); + + this.plugins.render(elapsedTime); + + this.state.render(elapsedTime); + } + + this.plugins.postRender(elapsedTime); + + }, + + /** + * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) + * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! + * + * @method Phaser.Game#enableStep + */ + enableStep: function () { + + this.stepping = true; + this.pendingStep = false; + this.stepCount = 0; + + }, + + /** + * Disables core game loop stepping. + * + * @method Phaser.Game#disableStep + */ + disableStep: function () { + + this.stepping = false; + this.pendingStep = false; + + }, + + /** + * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. + * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. + * + * @method Phaser.Game#step + */ + step: function () { + + this.pendingStep = false; + this.stepCount++; + + }, + + /** + * Nukes the entire game from orbit. + * + * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. + * + * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM + * and resets the PIXI default renderer. + * + * To destroy the game during an update callback, set {@link #pendingDestroy} instead. + * + * @method Phaser.Game#destroy + */ + destroy: function () { + + this.raf.stop(); + + if (this.debug.destroy) + { + this.debug.destroy(); + } + + this.state.destroy(); + this.sound.destroy(); + this.scale.destroy(); + this.stage.destroy(); + this.input.destroy(); + this.physics.destroy(); + this.plugins.destroy(); + + this.debug = null; + this.state = null; + this.sound = null; + this.scale = null; + this.stage = null; + this.input = null; + this.physics = null; + this.plugins = null; + + this.cache = null; + this.load = null; + this.time = null; + this.world = null; + + this.isBooted = false; + + this.renderer.destroy(false); + + Phaser.Canvas.removeFromDOM(this.canvas); + + PIXI.defaultRenderer = null; + + Phaser.GAMES[this.id] = null; + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gamePaused + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gamePaused: function (event) { + + // If the game is already paused it was done via game code, so don't re-pause it + if (!this._paused) + { + this._paused = true; + + this.time.gamePaused(); + + if (this.sound.muteOnPause) + { + this.sound.setMute(); + } + + this.onPause.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = true; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gameResumed + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gameResumed: function (event) { + + // Game is paused, but wasn't paused via code, so resume it + if (this._paused && !this._codePaused) + { + this._paused = false; + + this.time.gameResumed(); + + this.input.reset(); + + if (this.sound.muteOnPause) + { + this.sound.unsetMute(); + } + + this.onResume.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = false; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusLoss + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusLoss: function (event) { + + this.onBlur.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gamePaused(event); + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusGain + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusGain: function (event) { + + this.onFocus.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gameResumed(event); + } + + } + +}; + +Phaser.Game.prototype.constructor = Phaser.Game; + +/** +* The paused state of the Game. A paused game doesn't update any of its subsystems. +* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. +* @name Phaser.Game#paused +* @property {boolean} paused - Gets and sets the paused state of the Game. +*/ +Object.defineProperty(Phaser.Game.prototype, "paused", { + + get: function () { + return this._paused; + }, + + set: function (value) { + + if (value === true) + { + if (this._paused === false) + { + this._paused = true; + this.sound.setMute(); + this.time.gamePaused(); + this.onPause.dispatch(this); + } + this._codePaused = true; + } + else + { + if (this._paused) + { + this._paused = false; + this.input.reset(); + this.sound.unsetMute(); + this.time.gameResumed(); + this.onResume.dispatch(this); + } + this._codePaused = false; + } + + } + +}); + +/** + * + * "Deleted code is debugged code." - Jeff Sickel + * + * ヽ(〃^▽^〃)ノ + * +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. +* The Input manager is updated automatically by the core game loop. +* +* @class Phaser.Input +* @constructor +* @param {Phaser.Game} game - Current game instance. +*/ +Phaser.Input = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. + * @default + */ + this.hitCanvas = null; + + /** + * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. + * @default + */ + this.hitContext = null; + + /** + * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. + * To add a callback to this array please use `Input.addMoveCallback`. + * @property {array} moveCallbacks + * @protected + */ + this.moveCallbacks = []; + + /** + * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandler = null; + + /** + * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandlerContext = null; + + /** + * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. + * @default + */ + this.pollRate = 0; + + /** + * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. + * + * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. + * @default + */ + this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE; + + /** + * @property {Phaser.Point} position - A point object representing the current position of the Pointer. + * @default + */ + this.position = null; + + /** + * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. + */ + this.speed = null; + + /** + * A Circle object centered on the x/y screen coordinates of the Input. + * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. + * @property {Phaser.Circle} circle + */ + this.circle = null; + + /** + * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. + */ + this.scale = null; + + /** + * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1. + * @default -1 (Limited by total pointers.) + */ + this.maxPointers = -1; + + /** + * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. + * @default + */ + this.tapRate = 200; + + /** + * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. + * @default + */ + this.doubleTapRate = 300; + + /** + * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. + * @default + */ + this.holdRate = 2000; + + /** + * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. + * @default + */ + this.justPressedRate = 200; + + /** + * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . + * @default + */ + this.justReleasedRate = 200; + + /** + * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. + * The history is cleared each time the Pointer is pressed down. + * The history is updated at the rate specified in Input.pollRate + * @property {boolean} recordPointerHistory + * @default + */ + this.recordPointerHistory = false; + + /** + * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. + * @default + */ + this.recordRate = 100; + + /** + * The total number of entries that can be recorded into the Pointer objects tracking history. + * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. + * @property {number} recordLimit + * @default + */ + this.recordLimit = 100; + + /** + * An array of callbacks that will be fired every time a native touch start or touch end event (pointerdown or pointerup when using Pointer events) is received from the browser. + * This is used internally to handle audio and video unlocking on mobile devices. + * To add a callback to this array please use `Input.addTouchLockCallback`. + * @property {array} touchLockCallbacks + * @protected + */ + this.touchLockCallbacks = []; + + /** + * @property {Phaser.Pointer} pointer1 - A Pointer object. + */ + this.pointer1 = null; + + /** + * @property {Phaser.Pointer} pointer2 - A Pointer object. + */ + this.pointer2 = null; + + /** + * @property {Phaser.Pointer} pointer3 - A Pointer object. + */ + this.pointer3 = null; + + /** + * @property {Phaser.Pointer} pointer4 - A Pointer object. + */ + this.pointer4 = null; + + /** + * @property {Phaser.Pointer} pointer5 - A Pointer object. + */ + this.pointer5 = null; + + /** + * @property {Phaser.Pointer} pointer6 - A Pointer object. + */ + this.pointer6 = null; + + /** + * @property {Phaser.Pointer} pointer7 - A Pointer object. + */ + this.pointer7 = null; + + /** + * @property {Phaser.Pointer} pointer8 - A Pointer object. + */ + this.pointer8 = null; + + /** + * @property {Phaser.Pointer} pointer9 - A Pointer object. + */ + this.pointer9 = null; + + /** + * @property {Phaser.Pointer} pointer10 - A Pointer object. + */ + this.pointer10 = null; + + /** + * An array of non-mouse pointers that have been added to the game. + * The properties `pointer1..N` are aliases for `pointers[0..N-1]`. + * @property {Phaser.Pointer[]} pointers + * @public + * @readonly + */ + this.pointers = []; + + /** + * The most recently active Pointer object. + * + * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. + * + * @property {Phaser.Pointer} activePointer + */ + this.activePointer = null; + + /** + * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. + * + * @property {Pointer} mousePointer + */ + this.mousePointer = null; + + /** + * The Mouse Input manager. + * + * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Mouse} mouse + */ + this.mouse = null; + + /** + * The Keyboard Input manager. + * + * @property {Phaser.Keyboard} keyboard + */ + this.keyboard = null; + + /** + * The Touch Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Touch} touch + */ + this.touch = null; + + /** + * The MSPointer Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.MSPointer} mspointer + */ + this.mspointer = null; + + /** + * The Gamepad Input manager. + * + * @property {Phaser.Gamepad} gamepad + */ + this.gamepad = null; + + /** + * If the Input Manager has been reset locked then all calls made to InputManager.reset, + * such as from a State change, are ignored. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is pressed down. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onDown + */ + this.onDown = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is released. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onUp + */ + this.onUp = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is tapped. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {boolean} True if this was a double tap. + * + * @property {Phaser.Signal} onTap + */ + this.onTap = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is held down. + * It is sent one argument: + * + * - {Phaser.Pointer} The pointer that caused the event. + * + * @property {Phaser.Signal} onHold + */ + this.onHold = null; + + /** + * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. + * This is useful when stacking UI layers. Set to zero to disable. + * @property {number} minPriorityID + * @default + */ + this.minPriorityID = 0; + + /** + * A list of interactive objects. The InputHandler components add and remove themselves from this list. + * @property {Phaser.ArraySet} interactiveItems + */ + this.interactiveItems = new Phaser.ArraySet(); + + /** + * @property {Phaser.Point} _localPoint - Internal cache var. + * @private + */ + this._localPoint = new Phaser.Point(); + + /** + * @property {number} _pollCounter - Internal var holding the current poll counter. + * @private + */ + this._pollCounter = 0; + + /** + * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. + * @private + */ + this._oldPosition = null; + + /** + * @property {number} _x - x coordinate of the most recent Pointer event + * @private + */ + this._x = 0; + + /** + * @property {number} _y - Y coordinate of the most recent Pointer event + * @private + */ + this._y = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_TOUCH_COMBINE = 2; + +/** +* The maximum number of pointers that can be added. This excludes the mouse pointer. +* @constant +* @type {integer} +*/ +Phaser.Input.MAX_POINTERS = 10; + +Phaser.Input.prototype = { + + /** + * Starts the Input Manager running. + * + * @method Phaser.Input#boot + * @protected + */ + boot: function () { + + this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR); + this.addPointer(); + this.addPointer(); + + this.mouse = new Phaser.Mouse(this.game); + this.touch = new Phaser.Touch(this.game); + this.mspointer = new Phaser.MSPointer(this.game); + + if (Phaser.Keyboard) + { + this.keyboard = new Phaser.Keyboard(this.game); + } + + if (Phaser.Gamepad) + { + this.gamepad = new Phaser.Gamepad(this.game); + } + + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + + this.scale = new Phaser.Point(1, 1); + this.speed = new Phaser.Point(); + this.position = new Phaser.Point(); + this._oldPosition = new Phaser.Point(); + + this.circle = new Phaser.Circle(0, 0, 44); + + this.activePointer = this.mousePointer; + + this.hitCanvas = Phaser.CanvasPool.create(this, 1, 1); + this.hitContext = this.hitCanvas.getContext('2d'); + + this.mouse.start(); + if (!this.game.device.mspointer) + { + // Chrome >= 55 fires both PointerEvent and TouchEvent. + // Pick only one. + this.touch.start(); + } + this.mspointer.start(); + this.mousePointer.active = true; + + if (this.keyboard) + { + this.keyboard.start(); + } + + var _this = this; + + this._onClickTrampoline = function (event) { + _this.onClickTrampoline(event); + }; + + this.game.canvas.addEventListener('click', this._onClickTrampoline, false); + + }, + + /** + * Stops all of the Input Managers from running. + * + * @method Phaser.Input#destroy + */ + destroy: function () { + + this.mouse.stop(); + this.touch.stop(); + this.mspointer.stop(); + + if (this.keyboard) + { + this.keyboard.stop(); + } + + if (this.gamepad) + { + this.gamepad.stop(); + } + + this.moveCallbacks = []; + + Phaser.CanvasPool.remove(this); + + this.game.canvas.removeEventListener('click', this._onClickTrampoline); + + }, + + /** + * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. + * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to + * interact with. It works by polling all of the valid game objects, and then slowly discounting those + * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). + * + * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid + * for input and overlap with the Pointer. If you need fine-grained control over which of the items is + * selected then you can use this callback to do so. + * + * The callback will be sent 3 parameters: + * + * 1) A reference to the Phaser.Pointer object that is processing the Items. + * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. + * 3) The current 'favorite' candidate, based on its priorityID and position in the display list. + * + * Your callback MUST return one of the candidates sent to it. + * + * @method Phaser.Input#setInteractiveCandidateHandler + * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. + * @param {object} context - The context in which the callback will be called. + */ + setInteractiveCandidateHandler: function (callback, context) { + + this.customCandidateHandler = callback; + this.customCandidateHandlerContext = context; + + }, + + /** + * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. + * + * The callback will be sent 4 parameters: + * + * A reference to the Phaser.Pointer object that moved, + * The x position of the pointer, + * The y position, + * A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down). + * + * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best + * to only use if you've limited input to a single pointer (i.e. mouse or touch). + * + * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. + * + * @method Phaser.Input#addMoveCallback + * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. + * @param {object} context - The context in which the callback will be called. + */ + addMoveCallback: function (callback, context) { + + this.moveCallbacks.push({ callback: callback, context: context }); + + }, + + + /** + * Adds a callback that is fired when a browser touchstart/pointerdown or touchend/pointerup event is received. + * + * This is used internally to handle audio and video unlocking on mobile devices. + * + * If the callback returns 'true' then the callback is automatically deleted once invoked. + * + * The callback is added to the {@link #touchLockCallbacks} array and should be removed with {@link #removeTouchLockCallback}. + * + * @method Phaser.Input#addTouchLockCallback + * @param {function} callback - The callback that will be called when a touchstart event is received. + * @param {object} context - The context in which the callback will be called. + * @param {boolean} [onEnd=false] - Will the callback fire on a touchstart/pointerdown (default) or touchend/pointerup event? + */ + addTouchLockCallback: function (callback, context, onEnd) { + + if (onEnd === undefined) { onEnd = false; } + + this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd }); + + }, + + /** + * Removes the callback at the defined index from the {@link #touchLockCallbacks} array + * + * @method Phaser.Input#removeTouchLockCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + * @return {boolean} True if the callback was deleted, otherwise false. + */ + removeTouchLockCallback: function (callback, context) { + + var i = this.touchLockCallbacks.length; + + while (i--) + { + if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context) + { + this.touchLockCallbacks.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Execute any {@link #touchLockCallbacks} of the given type. + * + * @method Phaser.Input#executeTouchLockCallbacks + * @private + * @param {boolean} onEnd - Execute the touchend/pointerup callbacks (true) or the touchstart/pointerdown callbacks (false). Required! + * @param {Event} event - The native event from the browser. + */ + executeTouchLockCallbacks: function (onEnd, event) { + var i = this.touchLockCallbacks.length; + + while (i--) + { + var cb = this.touchLockCallbacks[i]; + + if (cb.onEnd === onEnd && cb.callback.call(cb.context, this, event)) + { + this.touchLockCallbacks.splice(i, 1); + } + } + }, + + /** + * Removes the callback from the Phaser.Input.moveCallbacks array. + * + * @method Phaser.Input#deleteMoveCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + */ + deleteMoveCallback: function (callback, context) { + + var i = this.moveCallbacks.length; + + while (i--) + { + if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context) + { + this.moveCallbacks.splice(i, 1); + return; + } + } + + }, + + /** + * Add a new Pointer object to the Input Manager. + * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. + * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). + * + * @method Phaser.Input#addPointer + * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. + */ + addPointer: function () { + + if (this.pointers.length >= Phaser.Input.MAX_POINTERS) + { + console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached."); + return null; + } + + var id = this.pointers.length + 1; + var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.CONTACT); + + this.pointers.push(pointer); + this['pointer' + id] = pointer; + + return pointer; + + }, + + /** + * Updates the Input Manager. Called by the core Game loop. + * + * @method Phaser.Input#update + * @protected + */ + update: function () { + + if (this.keyboard) + { + this.keyboard.update(); + } + + if (this.pollRate > 0 && this._pollCounter < this.pollRate) + { + this._pollCounter++; + return; + } + + this.speed.x = this.position.x - this._oldPosition.x; + this.speed.y = this.position.y - this._oldPosition.y; + + this._oldPosition.copyFrom(this.position); + this.mousePointer.update(); + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].update(); + } + + this._pollCounter = 0; + + }, + + /** + * Update method while paused. + * + * @method Phaser.Input#pauseUpdate + * @private + */ + pauseUpdate: function () { + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + }, + + /** + * Reset all of the Pointers and Input states. + * + * The optional `hard` parameter will reset any events or callbacks that may be bound. + * Input.reset is called automatically during a State change or if a game loses focus / visibility. + * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. + * + * @method Phaser.Input#reset + * @public + * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. + */ + reset: function (hard) { + + if (!this.game.isBooted || this.resetLocked) + { + return; + } + + if (hard === undefined) { hard = false; } + + this.mousePointer.reset(); + + if (this.keyboard) + { + this.keyboard.reset(hard); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].reset(); + } + + if (this.game.canvas.style.cursor !== 'none') + { + this.game.canvas.style.cursor = ''; + } + + if (hard) + { + this.onDown.dispose(); + this.onUp.dispose(); + this.onTap.dispose(); + this.onHold.dispose(); + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + this.moveCallbacks = []; + } + + this._pollCounter = 0; + + }, + + /** + * Resets the speed and old position properties. + * + * @method Phaser.Input#resetSpeed + * @param {number} x - Sets the oldPosition.x value. + * @param {number} y - Sets the oldPosition.y value. + */ + resetSpeed: function (x, y) { + + this._oldPosition.setTo(x, y); + this.speed.setTo(0, 0); + + }, + + /** + * Find the first free Pointer object and start it, passing in the event data. + * This is called automatically by Phaser.Touch and Phaser.MSPointer. + * + * @method Phaser.Input#startPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. + */ + startPointer: function (event) { + + if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers) + { + return null; + } + + if (!this.pointer1.active) + { + return this.pointer1.start(event); + } + + if (!this.pointer2.active) + { + return this.pointer2.start(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (!pointer.active) + { + return pointer.start(event); + } + } + + return null; + + }, + + /** + * Updates the matching Pointer object, passing in the event data. + * This is called automatically and should not normally need to be invoked. + * + * @method Phaser.Input#updatePointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. + */ + updatePointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.move(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.move(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.move(event); + } + } + + return null; + + }, + + /** + * Stops the matching Pointer object, passing in the event data. + * + * @method Phaser.Input#stopPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. + */ + stopPointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.stop(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.stop(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.stop(event); + } + } + + return null; + + }, + + /** + * Returns the total number of active pointers, not exceeding the specified limit + * + * @name Phaser.Input#countActivePointers + * @private + * @property {integer} [limit=(max pointers)] - Stop counting after this. + * @return {integer} The number of active pointers, or limit - whichever is less. + */ + countActivePointers: function (limit) { + + if (limit === undefined) { limit = this.pointers.length; } + + var count = limit; + + for (var i = 0; i < this.pointers.length && count > 0; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active) + { + count--; + } + } + + return (limit - count); + + }, + + /** + * Get the first Pointer with the given active state. + * + * @method Phaser.Input#getPointer + * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. + */ + getPointer: function (isActive) { + + if (isActive === undefined) { isActive = false; } + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active === isActive) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `identifier` property matches the given identifier value. + * + * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down, and is not fixed once set. + * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. + * + * @method Phaser.Input#getPointerFromIdentifier + * @param {number} identifier - The Pointer.identifier value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromIdentifier: function (identifier) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.identifier === identifier) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `pointerId` property matches the given value. + * + * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down if the browser recycles it. + * + * @method Phaser.Input#getPointerFromId + * @param {number} pointerId - The `pointerId` (not 'id') value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromId: function (pointerId) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.pointerId === pointerId) + { + return pointer; + } + } + + return null; + + }, + + /** + * This will return the local coordinates of the specified displayObject based on the given Pointer. + * + * @method Phaser.Input#getLocalPosition + * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. + * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. + * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. + */ + getLocalPosition: function (displayObject, pointer, output) { + + if (output === undefined) { output = new Phaser.Point(); } + + var wt = displayObject.worldTransform; + var id = 1 / (wt.a * wt.d + wt.c * -wt.b); + + return output.setTo( + wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id, + wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id + ); + + }, + + /** + * Tests if the pointer hits the given object. + * + * @method Phaser.Input#hitTest + * @param {DisplayObject} displayObject - The displayObject to test for a hit. + * @param {Phaser.Pointer} pointer - The pointer to use for the test. + * @param {Phaser.Point} localPoint - The local translated point. + */ + hitTest: function (displayObject, pointer, localPoint) { + + if (!displayObject.worldVisible) + { + return false; + } + + this.getLocalPosition(displayObject, pointer, this._localPoint); + + localPoint.copyFrom(this._localPoint); + + if (displayObject.hitArea && displayObject.hitArea.contains) + { + return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y)); + } + else if (Phaser.Creature && displayObject instanceof Phaser.Creature) { + var width = Math.abs(displayObject.width); + var height = Math.abs(displayObject.height); + var x1 = displayObject.x - (width * displayObject.anchorX); + + if (this.game.camera.x + pointer.x >= x1 && this.game.camera.x + pointer.x < x1 + width) + { + var y1 = displayObject.y - (height * displayObject.anchorY); + + if (this.game.camera.y + pointer.y >= y1 && this.game.camera.y + pointer.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.TileSprite) + { + var width = displayObject.width; + var height = displayObject.height; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof PIXI.Sprite) + { + var width = displayObject.texture.frame.width / displayObject.texture.baseTexture.resolution; + var height = displayObject.texture.frame.height / displayObject.texture.baseTexture.resolution; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.Graphics) + { + for (var i = 0; i < displayObject.graphicsData.length; i++) + { + var data = displayObject.graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // Only deal with fills.. + if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y)) + { + return true; + } + } + } + + // Didn't hit the parent, does it have any children? + + for (var i = 0; i < displayObject.children.length; i++) + { + if (this.hitTest(displayObject.children[i], pointer, localPoint)) + { + return true; + } + } + + return false; + }, + + /** + * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. + * + * @method Phaser.Input#onClickTrampoline + * @private + */ + onClickTrampoline: function () { + + // It might not always be the active pointer, but this does work on + // Desktop browsers (read: IE) with Mouse or MSPointer input. + this.activePointer.processClickTrampolines(); + + } + +}; + +Phaser.Input.prototype.constructor = Phaser.Input; + +/** +* The X coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. +* @name Phaser.Input#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Input.prototype, "x", { + + get: function () { + return this._x; + }, + + set: function (value) { + this._x = Math.floor(value); + } + +}); + +/** +* The Y coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. +* @name Phaser.Input#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Input.prototype, "y", { + + get: function () { + return this._y; + }, + + set: function (value) { + this._y = Math.floor(value); + } + +}); + +/** +* True if the Input is currently poll rate locked. +* @name Phaser.Input#pollLocked +* @property {boolean} pollLocked +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "pollLocked", { + + get: function () { + return (this.pollRate > 0 && this._pollCounter < this.pollRate); + } + +}); + +/** +* The total number of inactive Pointers. +* @name Phaser.Input#totalInactivePointers +* @property {number} totalInactivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", { + + get: function () { + return this.pointers.length - this.countActivePointers(); + } + +}); + +/** +* The total number of active Pointers, not counting the mouse pointer. +* @name Phaser.Input#totalActivePointers +* @property {integers} totalActivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", { + + get: function () { + return this.countActivePointers(); + } + +}); + +/** +* The world X coordinate of the most recently active pointer. +* @name Phaser.Input#worldX +* @property {number} worldX - The world X coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldX", { + + get: function () { + return this.game.camera.view.x + this.x; + } + +}); + +/** +* The world Y coordinate of the most recently active pointer. +* @name Phaser.Input#worldY +* @property {number} worldY - The world Y coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldY", { + + get: function () { + return this.game.camera.view.y + this.y; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Mouse class is responsible for handling all aspects of mouse interaction with the browser. +* +* It captures and processes mouse events that happen on the game canvas object. +* It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released +* when not over the game. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object +* which normalises all game input for you, including accurate button handling. +* +* @class Phaser.Mouse +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Mouse = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down. + */ + this.mouseDownCallback = null; + + /** + * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state. + */ + this.mouseUpCallback = null; + + /** + * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas. + */ + this.mouseOutCallback = null; + + /** + * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). + */ + this.mouseOverCallback = null; + + /** + * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used. + */ + this.mouseWheelCallback = null; + + /** + * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + */ + this.capture = false; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + * @default + */ + this.button = -1; + + /** + * The direction of the _last_ mousewheel usage 1 for up -1 for down. + * @property {number} wheelDelta + */ + this.wheelDelta = 0; + + /** + * Mouse input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true. + * @default + */ + this.locked = false; + + /** + * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas. + * @default + */ + this.stopOnGameOut = false; + + /** + * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state. + * @default + */ + this.pointerLock = new Phaser.Signal(); + + /** + * The browser mouse DOM event. Will be null if no mouse event has ever been received. + * Access this property only inside a Mouse event handler and do not keep references to it. + * @property {MouseEvent|null} event + * @default + */ + this.event = null; + + /** + * @property {function} _onMouseDown - Internal event handler reference. + * @private + */ + this._onMouseDown = null; + + /** + * @property {function} _onMouseMove - Internal event handler reference. + * @private + */ + this._onMouseMove = null; + + /** + * @property {function} _onMouseUp - Internal event handler reference. + * @private + */ + this._onMouseUp = null; + + /** + * @property {function} _onMouseOut - Internal event handler reference. + * @private + */ + this._onMouseOut = null; + + /** + * @property {function} _onMouseOver - Internal event handler reference. + * @private + */ + this._onMouseOver = null; + + /** + * @property {function} _onMouseWheel - Internal event handler reference. + * @private + */ + this._onMouseWheel = null; + + /** + * Wheel proxy event object, if required. Shared for all wheel events for this mouse. + * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent + * @private + */ + this._wheelEvent = null; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.NO_BUTTON = -1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.LEFT_BUTTON = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.MIDDLE_BUTTON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.RIGHT_BUTTON = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.BACK_BUTTON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.FORWARD_BUTTON = 4; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_UP = 1; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_DOWN = -1; + +Phaser.Mouse.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Mouse#start + */ + start: function () { + + if (this.game.device.android && this.game.device.chrome === false) + { + // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ... + return; + } + + if (this._onMouseDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onMouseDown = function (event) { + return _this.onMouseDown(event); + }; + + this._onMouseMove = function (event) { + return _this.onMouseMove(event); + }; + + this._onMouseUp = function (event) { + return _this.onMouseUp(event); + }; + + this._onMouseUpGlobal = function (event) { + return _this.onMouseUpGlobal(event); + }; + + this._onMouseOutGlobal = function (event) { + return _this.onMouseOutGlobal(event); + }; + + this._onMouseOut = function (event) { + return _this.onMouseOut(event); + }; + + this._onMouseOver = function (event) { + return _this.onMouseOver(event); + }; + + this._onMouseWheel = function (event) { + return _this.onMouseWheel(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('mousedown', this._onMouseDown, true); + canvas.addEventListener('mousemove', this._onMouseMove, true); + canvas.addEventListener('mouseup', this._onMouseUp, true); + + if (!this.game.device.cocoonJS) + { + window.addEventListener('mouseup', this._onMouseUpGlobal, true); + window.addEventListener('mouseout', this._onMouseOutGlobal, true); + canvas.addEventListener('mouseover', this._onMouseOver, true); + canvas.addEventListener('mouseout', this._onMouseOut, true); + } + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.addEventListener(wheelEvent, this._onMouseWheel, true); + + if (wheelEvent === 'mousewheel') + { + this._wheelEvent = new WheelEventProxy(-1/40, 1); + } + else if (wheelEvent === 'DOMMouseScroll') + { + this._wheelEvent = new WheelEventProxy(1, 1); + } + } + + }, + + /** + * The internal method that handles the mouse down event from the browser. + * @method Phaser.Mouse#onMouseDown + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseDown: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseDownCallback) + { + this.mouseDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.start(event); + + }, + + /** + * The internal method that handles the mouse move event from the browser. + * @method Phaser.Mouse#onMouseMove + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseMoveCallback) + { + this.mouseMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.move(event); + + }, + + /** + * The internal method that handles the mouse up event from the browser. + * @method Phaser.Mouse#onMouseUp + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUp: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.Mouse#onMouseUpGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUpGlobal: function (event) { + + if (!this.input.mousePointer.withinGame) + { + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + }, + + /** + * The internal method that handles the mouse out event from the window. + * + * @method Phaser.Mouse#onMouseOutGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOutGlobal: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (!this.input.enabled || !this.enabled) + { + return; + } + + // If we get a mouseout event from the window then basically + // something serious has gone down, usually along the lines of + // the browser opening a context-menu or similar. + // On OS X Chrome especially this is bad news, as it blocks + // us then getting a mouseup event, so we need to force that through. + // + // No matter what, we must cancel the left and right buttons + + this.input.mousePointer.stop(event); + + // Clear the button states (again?) + this.input.mousePointer.resetButtons(); + + }, + + /** + * The internal method that handles the mouse out event from the browser. + * + * @method Phaser.Mouse#onMouseOut + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (this.mouseOutCallback) + { + this.mouseOutCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.stopOnGameOut) + { + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + this.input.interactiveItems.callAll('_pointerOutHandler', this.input.mousePointer); + + }, + + /** + * The internal method that handles the mouse over event from the browser. + * + * @method Phaser.Mouse#onMouseOver + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = true; + + if (this.mouseOverCallback) + { + this.mouseOverCallback.call(this.callbackContext, event); + } + + }, + + /** + * The internal method that handles the mouse wheel event from the browser. + * + * @method Phaser.Mouse#onMouseWheel + * @param {MouseEvent} event - The native event from the browser. + */ + onMouseWheel: function (event) { + + if (this._wheelEvent) { + event = this._wheelEvent.bindEvent(event); + } + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + // reverse detail for firefox + this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1); + + if (this.mouseWheelCallback) + { + this.mouseWheelCallback.call(this.callbackContext, event); + } + + }, + + /** + * If the browser supports it you can request that the pointer be locked to the browser window. + * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key. + * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'. + * @method Phaser.Mouse#requestPointerLock + */ + requestPointerLock: function () { + + if (this.game.device.pointerLock) + { + var element = this.game.canvas; + + element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; + + element.requestPointerLock(); + + var _this = this; + + this._pointerLockChange = function (event) { + return _this.pointerLockChange(event); + }; + + document.addEventListener('pointerlockchange', this._pointerLockChange, true); + document.addEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true); + } + + }, + + /** + * Internal pointerLockChange handler. + * + * @method Phaser.Mouse#pointerLockChange + * @param {Event} event - The native event from the browser. This gets stored in Mouse.event. + */ + pointerLockChange: function (event) { + + var element = this.game.canvas; + + if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) + { + // Pointer was successfully locked + this.locked = true; + this.pointerLock.dispatch(true, event); + } + else + { + // Pointer was unlocked + this.locked = false; + this.pointerLock.dispatch(false, event); + } + + }, + + /** + * Internal release pointer lock handler. + * @method Phaser.Mouse#releasePointerLock + */ + releasePointerLock: function () { + + document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; + + document.exitPointerLock(); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + }, + + /** + * Stop the event listeners. + * @method Phaser.Mouse#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('mousedown', this._onMouseDown, true); + canvas.removeEventListener('mousemove', this._onMouseMove, true); + canvas.removeEventListener('mouseup', this._onMouseUp, true); + canvas.removeEventListener('mouseover', this._onMouseOver, true); + canvas.removeEventListener('mouseout', this._onMouseOut, true); + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.removeEventListener(wheelEvent, this._onMouseWheel, true); + } + + window.removeEventListener('mouseup', this._onMouseUpGlobal, true); + window.removeEventListener('mouseout', this._onMouseOutGlobal, true); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + } + +}; + +Phaser.Mouse.prototype.constructor = Phaser.Mouse; + +/* jshint latedef:nofunc */ +/** +* A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel' +* events to 'wheel'-like events. +* +* See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode. +* +* @method Phaser.Mouse#WheelEventProxy +* @private +* @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. +* @param {integer} deltaMode - The reported delta mode. +*/ +function WheelEventProxy (scaleFactor, deltaMode) { + + /** + * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. + * @private + */ + this._scaleFactor = scaleFactor; + + /** + * @property {number} _deltaMode - The reported delta mode. + * @private + */ + this._deltaMode = deltaMode; + + /** + * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit. + * @private + */ + this.originalEvent = null; + +} + +WheelEventProxy.prototype = {}; +WheelEventProxy.prototype.constructor = WheelEventProxy; + +WheelEventProxy.prototype.bindEvent = function (event) { + + // Generate stubs automatically + if (!WheelEventProxy._stubsGenerated && event) + { + var makeBinder = function (name) { + + return function () { + var v = this.originalEvent[name]; + return typeof v !== 'function' ? v : v.bind(this.originalEvent); + }; + + }; + + for (var prop in event) + { + if (!(prop in WheelEventProxy.prototype)) + { + Object.defineProperty(WheelEventProxy.prototype, prop, { + get: makeBinder(prop) + }); + } + } + WheelEventProxy._stubsGenerated = true; + } + + this.originalEvent = event; + return this; + +}; + +Object.defineProperties(WheelEventProxy.prototype, { + "type": { value: "wheel" }, + "deltaMode": { get: function () { return this._deltaMode; } }, + "deltaY": { + get: function () { + return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0; + } + }, + "deltaX": { + get: function () { + return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0; + } + }, + "deltaZ": { value: 0 } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The MSPointer class handles {@link https://developers.google.com/web/updates/2016/10/pointer-events Pointer-event} interactions with the game via a dedicated {@link Phaser.Pointer}. (It's named after the nonstandard {@link https://msdn.microsoft.com/library/hh673557(v=vs.85).aspx MSPointerEvent} since that was the first browser implementation.) +* +* It's {@link http://caniuse.com/#feat=pointer currently supported in IE 10+, Edge, Chrome (including Android), and Opera}. +* +* You should not normally access this class directly, but instead use a {@link Phaser.Pointer} object which +* normalises all game input for you including accurate button handling. +* +* Please note that at the current time of writing Phaser does not yet support chorded button interactions: +* http://www.w3.org/TR/pointerevents/#chorded-button-interactions +* +* You can disable Phaser's use of Pointer Events by either of two ways: +* +* ```javascript +* // **Before** `new Phaser.Game(…)`: +* Phaser.Device.onInitialized.add(function () { +* this.mspointer = false; +* }); +* ``` +* +* ```javascript +* // Once, in the earliest State `init` or `create` callback (e.g., Boot): +* this.input.mspointer.stop(); +* ``` +* +* @class Phaser.MSPointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.MSPointer = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called (defaults to game). + */ + this.callbackContext = this.game; + + /** + * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event. + */ + this.pointerDownCallback = null; + + /** + * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event. + */ + this.pointerMoveCallback = null; + + /** + * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event. + */ + this.pointerUpCallback = null; + + /** + * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, canceling the corresponding MouseEvent or TouchEvent. + */ + this.capture = true; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + */ + this.button = -1; + + /** + * The most recent PointerEvent from the browser. Will be null if no event has ever been received. + * Access this property only inside a Pointer event handler and do not keep references to it. + * @property {MSPointerEvent|PointerEvent|null} event + * @default + */ + this.event = null; + + /** + * PointerEvent input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {function} _onMSPointerDown - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerDown = null; + + /** + * @property {function} _onMSPointerMove - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerMove = null; + + /** + * @property {function} _onMSPointerUp - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUp = null; + + /** + * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUpGlobal = null; + + /** + * @property {function} _onMSPointerOut - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOut = null; + + /** + * @property {function} _onMSPointerOver - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOver = null; + +}; + +Phaser.MSPointer.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.MSPointer#start + */ + start: function () { + + if (this._onMSPointerDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + if (this.game.device.mspointer) + { + this._onMSPointerDown = function (event) { + return _this.onPointerDown(event); + }; + + this._onMSPointerMove = function (event) { + return _this.onPointerMove(event); + }; + + this._onMSPointerUp = function (event) { + return _this.onPointerUp(event); + }; + + this._onMSPointerUpGlobal = function (event) { + return _this.onPointerUpGlobal(event); + }; + + this._onMSPointerOut = function (event) { + return _this.onPointerOut(event); + }; + + this._onMSPointerOver = function (event) { + return _this.onPointerOver(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.addEventListener('pointerdown', this._onMSPointerDown, false); + canvas.addEventListener('pointermove', this._onMSPointerMove, false); + canvas.addEventListener('pointerup', this._onMSPointerUp, false); + + canvas.style['-ms-content-zooming'] = 'none'; + canvas.style['-ms-touch-action'] = 'none'; + + if (!this.game.device.cocoonJS) + { + window.addEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.addEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.addEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.addEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.addEventListener('pointerover', this._onMSPointerOver, true); + canvas.addEventListener('pointerout', this._onMSPointerOut, true); + } + } + + }, + + /** + * The function that handles the PointerDown event. + * + * @method Phaser.MSPointer#onPointerDown + * @param {PointerEvent} event - The native DOM event. + */ + onPointerDown: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerDownCallback) + { + this.pointerDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.start(event); + } + else + { + this.input.startPointer(event); + } + + }, + + /** + * The function that handles the PointerMove event. + * @method Phaser.MSPointer#onPointerMove + * @param {PointerEvent} event - The native DOM event. + */ + onPointerMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerMoveCallback) + { + this.pointerMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.move(event); + } + else + { + this.input.updatePointer(event); + } + + }, + + /** + * The function that handles the PointerUp event. + * @method Phaser.MSPointer#onPointerUp + * @param {PointerEvent} event - The native DOM event. + */ + onPointerUp: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerUpCallback) + { + this.pointerUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.stop(event); + } + else + { + this.input.stopPointer(event); + } + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.MSPointer#onPointerUpGlobal + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerUpGlobal: function (event) { + + if ((event.pointerType === 'mouse' || event.pointerType === 0x00000004) && !this.input.mousePointer.withinGame) + { + this.onPointerUp(event); + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer && pointer.withinGame) + { + this.onPointerUp(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = false; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = false; + } + } + + if (this.input.mouse.mouseOutCallback) + { + this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.input.mouse.stopOnGameOut) + { + event['identifier'] = 0; + + if (pointer) + { + pointer.stop(event); + } + else + { + this.input.mousePointer.stop(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = true; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = true; + } + } + + if (this.input.mouse.mouseOverCallback) + { + this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext, event); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.MSPointer#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.removeEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.removeEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.removeEventListener('pointerdown', this._onMSPointerDown, false); + canvas.removeEventListener('pointermove', this._onMSPointerMove, false); + canvas.removeEventListener('pointerup', this._onMSPointerUp, false); + + window.removeEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.removeEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.removeEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('pointerover', this._onMSPointerOver, true); + canvas.removeEventListener('pointerout', this._onMSPointerOut, true); + + } + +}; + +Phaser.MSPointer.prototype.constructor = Phaser.MSPointer; + +/** +* @author Richard Davey +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. +* +* For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, +* middle button and advanced buttons like back and forward. +* +* Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. +* +* On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. +* +* At the time of writing this there are device limitations you should be aware of: +* +* - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions +* (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, +* even when they are pressed. +* - On Linux (GTK), the 4th button and the 5th button are not supported. +* - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. +* +* @class Phaser.DeviceButton +* @constructor +* @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad. +* @param {number} buttonCode - The button code this DeviceButton is responsible for. +*/ +Phaser.DeviceButton = function (parent, buttonCode) { + + /** + * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = parent.game; + + /** + * @property {object} event - The DOM event that caused the change in button state. + * @default + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the button. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the button. + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - The timestamp when the button was last pressed down. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - The timestamp when the button was last released. + * @default + */ + this.timeUp = 0; + + /** + * Gamepad only. + * If a button is held down this holds down the number of times the button has 'repeated'. + * @property {number} repeats + * @default + */ + this.repeats = 0; + + /** + * True if the alt key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} altKey + * @default + */ + this.altKey = false; + + /** + * True if the shift key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} shiftKey + * @default + */ + this.shiftKey = false; + + /** + * True if the control key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} ctrlKey + * @default + */ + this.ctrlKey = false; + + /** + * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. + * @default + */ + this.value = 0; + + /** + * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. + */ + this.buttonCode = buttonCode; + + /** + * This Signal is dispatched every time this DeviceButton is pressed down. + * It is only dispatched once (until the button is released again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onDown + */ + this.onDown = new Phaser.Signal(); + + /** + * This Signal is dispatched every time this DeviceButton is released from a down state. + * It is only dispatched once (until the button is pressed again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onUp + */ + this.onUp = new Phaser.Signal(); + + /** + * Gamepad only. + * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onFloat + */ + this.onFloat = new Phaser.Signal(); + +}; + +Phaser.DeviceButton.prototype = { + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button down state. + * + * @method Phaser.DeviceButton#start + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + start: function (event, value) { + + if (this.isDown) + { + return; + } + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onDown.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button up state. + * + * @method Phaser.DeviceButton#stop + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + stop: function (event, value) { + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onUp.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer. + * Starts or stops button based on condition. + * + * @method Phaser.DeviceButton#startStop + * @protected + * @param {boolean} [condition] - The condition that decides between start or stop. + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + startStop: function (condition, event, value) { + + if (condition) + { + this.start(event, value); + } + else + { + this.stop(event, value); + } + + }, + + /** + * Called automatically by Phaser.SinglePad. + * + * @method Phaser.DeviceButton#padFloat + * @protected + * @param {number} value - Button value + */ + padFloat: function (value) { + + this.isDown = false; + this.isUp = false; + + this.value = value; + + this.onFloat.dispatch(this, value); + + }, + + /** + * Returns the "just pressed" state of this button. + * Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justPressed + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (duration) { + + duration = duration || 250; + + return (this.isDown && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * Returns the "just released" state of this button. + * Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justReleased + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (duration) { + + duration = duration || 250; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. + * + * @method Phaser.DeviceButton#reset + */ + reset: function () { + + this.isDown = false; + this.isUp = true; + + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.altKey = false; + this.shiftKey = false; + this.ctrlKey = false; + + }, + + /** + * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals + * and clears the parent and game references. + * + * @method Phaser.DeviceButton#destroy + */ + destroy: function () { + + this.onDown.dispose(); + this.onUp.dispose(); + this.onFloat.dispose(); + + this.parent = null; + this.game = null; + + } + +}; + +Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton; + +/** +* How long the button has been held down for in milliseconds. +* If not currently down it returns -1. +* +* @name Phaser.DeviceButton#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.DeviceButton.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. +* +* @class Phaser.Pointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. +* @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or CONTACT. +*/ +Phaser.Pointer = function (game, id, pointerMode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. + */ + this.id = id; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINTER; + + /** + * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps. + * @default + */ + this.exists = true; + + /** + * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.identifier = 0; + + /** + * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. + * @default + */ + this.pointerId = null; + + /** + * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer. + */ + this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT); + + /** + * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.target = null; + + /** + * The button property of the most recent DOM event when this Pointer is started. + * You should not rely on this value for accurate button detection, instead use the Pointer properties + * `leftButton`, `rightButton`, `middleButton` and so on. + * @property {any} button + * @default + */ + this.button = null; + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * @property {Phaser.DeviceButton} leftButton + * @default + */ + this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} middleButton + * @default + */ + this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} rightButton + * @default + */ + this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} backButton + * @default + */ + this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} forwardButton + * @default + */ + this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON); + + /** + * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} eraserButton + * @default + */ + this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON); + + /** + * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event. + * @private + * @default + */ + this._holdSent = false; + + /** + * @property {array} _history - Local private variable storing the short-term history of pointer movements. + * @private + */ + this._history = []; + + /** + * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur. + * @private + */ + this._nextDrop = 0; + + /** + * @property {boolean} _stateReset - Monitor events outside of a state reset loop. + * @private + */ + this._stateReset = false; + + /** + * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false. + */ + this.withinGame = false; + + /** + * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientX = -1; + + /** + * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientY = -1; + + /** + * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document. + */ + this.pageX = -1; + + /** + * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document. + */ + this.pageY = -1; + + /** + * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen. + */ + this.screenX = -1; + + /** + * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen. + */ + this.screenY = -1; + + /** + * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementX = 0; + + /** + * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementY = 0; + + /** + * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementX = 0; + + /** + * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementY = 0; + + /** + * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.x = -1; + + /** + * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.y = -1; + + /** + * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false. + */ + this.isMouse = (id === 0); + + /** + * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. + * @property {boolean} isDown + * @default + */ + this.isDown = false; + + /** + * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. + * @property {boolean} isUp + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen. + * @default + */ + this.timeUp = 0; + + /** + * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked. + * @default + */ + this.previousTapTime = 0; + + /** + * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen. + * @default + */ + this.totalTouches = 0; + + /** + * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event. + * @default + */ + this.msSinceLastClick = Number.MAX_VALUE; + + /** + * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging. + * @default + */ + this.targetObject = null; + + /** + * This array is erased and re-populated every time this Pointer is updated. It contains references to all + * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be + * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over + * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset + * every frame. + * @property {array} interactiveCandidates + * @default + */ + this.interactiveCandidates = []; + + /** + * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active. + * @default + */ + this.active = false; + + /** + * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. + * @default + */ + this.dirty = false; + + /** + * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display. + */ + this.position = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. + */ + this.positionDown = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released. + */ + this.positionUp = new Phaser.Point(); + + /** + * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. + * The Circle size is 44px (Apples recommended "finger tip" size). + * @property {Phaser.Circle} circle + */ + this.circle = new Phaser.Circle(0, 0, 44); + + /** + * Click trampolines associated with this pointer. See `addClickTrampoline`. + * @property {object[]|null} _clickTrampolines + * @private + */ + this._clickTrampolines = null; + + /** + * When the Pointer has click trampolines the last target object is stored here + * so it can be used to check for validity of the trampoline in a post-Up/'stop'. + * @property {object} _trampolineTargetObject + * @private + */ + this._trampolineTargetObject = null; + +}; + +/** +* No buttons at all. +* @constant +* @type {number} +*/ +Phaser.Pointer.NO_BUTTON = 0; + +/** +* The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. +* @constant +* @type {number} +*/ +Phaser.Pointer.LEFT_BUTTON = 1; + +/** +* The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. +* @constant +* @type {number} +*/ +Phaser.Pointer.RIGHT_BUTTON = 2; + +/** +* The Middle Mouse button. +* @constant +* @type {number} +*/ +Phaser.Pointer.MIDDLE_BUTTON = 4; + +/** +* The X1 button. This is typically the mouse Back button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.BACK_BUTTON = 8; + +/** +* The X2 button. This is typically the mouse Forward button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.FORWARD_BUTTON = 16; + +/** +* The Eraser pen button on PointerEvent supported devices only. +* @constant +* @type {number} +*/ +Phaser.Pointer.ERASER_BUTTON = 32; + +Phaser.Pointer.prototype = { + + /** + * Resets the states of all the button booleans. + * + * @method Phaser.Pointer#resetButtons + * @protected + */ + resetButtons: function () { + + this.isDown = false; + this.isUp = true; + + if (this.isMouse) + { + this.leftButton.reset(); + this.middleButton.reset(); + this.rightButton.reset(); + this.backButton.reset(); + this.forwardButton.reset(); + this.eraserButton.reset(); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsDown + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsDown: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.start(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.start(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.start(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.start(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.start(event); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsUp + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUp: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.stop(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.stop(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.stop(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.stop(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.stop(event); + } + + }, + + /** + * Called by updateButtons. + * + * @method Phaser.Pointer#processButtonsUpDown + * @private + * @param {integer} buttons - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons MouseEvent#buttons} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUpDown: function (buttons, event) { + + var down = (event.type.toLowerCase().substr(-4) === 'down'); + var move = (event.type.toLowerCase().substr(-4) === 'move'); + + if (buttons !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && buttons === 1 && event.ctrlKey) + { + buttons = 2; + } + + // Note: These are bitwise checks, not booleans + this.leftButton.startStop(Phaser.Pointer.LEFT_BUTTON & buttons, event); + this.rightButton.startStop(Phaser.Pointer.RIGHT_BUTTON & buttons, event); + this.middleButton.startStop(Phaser.Pointer.MIDDLE_BUTTON & buttons, event); + this.backButton.startStop(Phaser.Pointer.BACK_BUTTON & buttons, event); + this.forwardButton.startStop(Phaser.Pointer.FORWARD_BUTTON & buttons, event); + this.eraserButton.startStop(Phaser.Pointer.ERASER_BUTTON & buttons, event); + } + else + { + // No buttons property (like Safari on OSX when using a trackpad) + // Attempt to use event.button property or fallback to default + if (event.button !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && event.ctrlKey && event.button === 0) + { + this.rightButton.start(event); + } + else + { + if (down) + { + this.processButtonsDown(event.button, event); + } + else if (!move) + { + this.processButtonsUp(event.button, event); + } + } + } + else + { + if (down) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (event.ctrlKey) + { + this.rightButton.start(event); + } + else + { + this.leftButton.start(event); + } + } + else + { + this.leftButton.stop(event); + this.rightButton.stop(event); + } + } + } + + }, + + /** + * Called when the event.buttons property changes from zero. + * Contains a button bitmask. + * + * @method Phaser.Pointer#updateButtons + * @protected + * @param {MouseEvent} event - The DOM event. + */ + updateButtons: function (event) { + + this.button = event.button; + this.processButtonsUpDown(event.buttons, event); + + this.isUp = true; + this.isDown = false; + + if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown) + { + this.isUp = false; + this.isDown = true; + } + + }, + + /** + * Called when the Pointer is pressed onto the touchscreen. + * @method Phaser.Pointer#start + * @param {any} event - The DOM event from the browser. + */ + start: function (event) { + + var input = this.game.input; + + if (event['pointerId']) + { + this.pointerId = event.pointerId; + } + + this.identifier = event.identifier; + this.target = event.target; + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = true; + this.isUp = false; + } + + this.active = true; + this.withinGame = true; + this.dirty = false; + + this._history = []; + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + // Work out how long it has been since the last click + this.msSinceLastClick = this.game.time.time - this.timeDown; + this.timeDown = this.game.time.time; + this._holdSent = false; + + // This sets the x/y and other local values + this.move(event, true); + + // x and y are the old values here? + this.positionDown.setTo(this.x, this.y); + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.x = this.x; + input.y = this.y; + input.position.setTo(this.x, this.y); + input.onDown.dispatch(this, event); + input.resetSpeed(this.x, this.y); + } + + this._stateReset = false; + + this.totalTouches++; + + if (this.targetObject !== null) + { + this.targetObject._touchedHandler(this); + } + + return this; + + }, + + /** + * Called by the Input Manager. + * @method Phaser.Pointer#update + */ + update: function () { + + var input = this.game.input; + + if (this.active) + { + // Force a check? + if (this.dirty) + { + if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(false); + } + + this.dirty = false; + } + + if (this._holdSent === false && this.duration >= input.holdRate) + { + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onHold.dispatch(this); + } + + this._holdSent = true; + } + + // Update the droppings history + if (input.recordPointerHistory && this.game.time.time >= this._nextDrop) + { + this._nextDrop = this.game.time.time + input.recordRate; + + this._history.push({ + x: this.position.x, + y: this.position.y + }); + + if (this._history.length > input.recordLimit) + { + this._history.shift(); + } + } + } + + }, + + /** + * Called when the Pointer is moved. + * + * @method Phaser.Pointer#move + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + * @param {boolean} [fromClick=false] - Was this called from the click event? + */ + move: function (event, fromClick) { + + var input = this.game.input; + + if (input.pollLocked) + { + return; + } + + if (fromClick === undefined) { fromClick = false; } + + if (event.button !== undefined) + { + this.button = event.button; + } + + if (this.isMouse) + { + this.updateButtons(event); + } + + 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 && 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.scale.offset.x) * input.scale.x; + this.y = (this.pageY - this.game.scale.offset.y) * input.scale.y; + + this.position.setTo(this.x, this.y); + this.circle.x = this.x; + this.circle.y = this.y; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.activePointer = this; + input.x = this.x; + input.y = this.y; + input.position.setTo(input.x, input.y); + input.circle.x = input.x; + input.circle.y = input.y; + } + + this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY); + + var i = input.moveCallbacks.length; + + while (i--) + { + input.moveCallbacks[i].callback.call(input.moveCallbacks[i].context, this, this.x, this.y, fromClick); + } + + // Easy out if we're dragging something and it still exists + if (this.targetObject !== null && (!this.game.paused || this.targetObject.noPause) && this.targetObject.isDragged === true) + { + if (this.targetObject.update(this) === false) + { + this.targetObject = null; + } + } + else if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(fromClick); + } + + return this; + + }, + + /** + * Process all interactive objects to find out which ones were updated in the recent Pointer move. + * + * @method Phaser.Pointer#processInteractiveObjects + * @protected + * @param {boolean} [fromClick=false] - Was this called from the click event? + * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. + */ + processInteractiveObjects: function (fromClick) { + + // Work out which object is on the top + var highestRenderOrderID = 0; + var highestInputPriorityID = -1; + var candidateTarget = null; + + // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID + // We know they'll be valid for input detection but not which is the top just yet + + var currentNode = this.game.input.interactiveItems.first; + + this.interactiveCandidates = []; + + while (currentNode) + { + // Reset checked status + currentNode.checked = false; + + if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false) && (!this.game.paused || currentNode.sprite.noPause)) + { + // Flag it as checked so we don't re-scan it on the next phase + currentNode.checked = true; + + if ((fromClick && currentNode.checkPointerDown(this, true)) || + (!fromClick && currentNode.checkPointerOver(this, true))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID + // because if their ID is lower anyway then we can just automatically discount them + // (A node that was previously checked did not request a pixel-perfect check.) + + currentNode = this.game.input.interactiveItems.first; + + while (currentNode) + { + if (!currentNode.checked && + currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true)) + { + if ((fromClick && currentNode.checkPointerDown(this, false)) || + (!fromClick && currentNode.checkPointerOver(this, false))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + if (this.game.input.customCandidateHandler) + { + candidateTarget = this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext, this, this.interactiveCandidates, candidateTarget); + } + + this.swapTarget(candidateTarget, false); + + return (this.targetObject !== null); + + }, + + /** + * This will change the `Pointer.targetObject` object to be the one provided. + * + * This allows you to have fine-grained control over which object the Pointer is targeting. + * + * Note that even if you set a new Target here, it is still able to be replaced by any other valid + * target during the next Pointer update. + * + * @method Phaser.Pointer#swapTarget + * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. + * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. + */ + swapTarget: function (newTarget, silent) { + + if (silent === undefined) { silent = false; } + + // Now we know the top-most item (if any) we can process it + if (newTarget === null) + { + // The pointer isn't currently over anything, check if we've got a lingering previous target + if (this.targetObject) + { + this.targetObject._pointerOutHandler(this, silent); + this.targetObject = null; + } + } + else + { + if (this.targetObject === null) + { + // And now set the new one + this.targetObject = newTarget; + newTarget._pointerOverHandler(this, silent); + } + else + { + // We've got a target from the last update + if (this.targetObject === newTarget) + { + // Same target as before, so update it + if (newTarget.update(this) === false) + { + this.targetObject = null; + } + } + else + { + // The target has changed, so tell the old one we've left it + this.targetObject._pointerOutHandler(this, silent); + + // And now set the new one + this.targetObject = newTarget; + this.targetObject._pointerOverHandler(this, silent); + } + } + } + + }, + + /** + * Called when the Pointer leaves the target area. + * + * @method Phaser.Pointer#leave + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + leave: function (event) { + + this.withinGame = false; + this.move(event, false); + + }, + + /** + * Called when the Pointer leaves the touchscreen. + * + * @method Phaser.Pointer#stop + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + stop: function (event) { + + var input = this.game.input; + + if (this._stateReset && this.withinGame) + { + event.preventDefault(); + return; + } + + this.timeUp = this.game.time.time; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onUp.dispatch(this, event); + + // Was it a tap? + if (this.duration >= 0 && this.duration <= input.tapRate) + { + // Was it a double-tap? + if (this.timeUp - this.previousTapTime < input.doubleTapRate) + { + // Yes, let's dispatch the signal then with the 2nd parameter set to true + input.onTap.dispatch(this, true); + } + else + { + // Wasn't a double-tap, so dispatch a single tap signal + input.onTap.dispatch(this, false); + } + + this.previousTapTime = this.timeUp; + } + } + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = false; + this.isUp = true; + } + + // Mouse is always active + if (this.id > 0) + { + this.active = false; + } + + this.withinGame = this.game.scale.bounds.contains(event.pageX, event.pageY); + this.pointerId = null; + this.identifier = null; + + this.positionUp.setTo(this.x, this.y); + + if (this.isMouse === false) + { + input.currentPointers--; + } + + input.interactiveItems.callAll('_releasedHandler', this); + + if (this._clickTrampolines) + { + this._trampolineTargetObject = this.targetObject; + } + + this.targetObject = null; + + return this; + + }, + + /** + * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. + * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. + * @method Phaser.Pointer#justPressed + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate. + * @return {boolean} true if the Pointer was pressed down within the duration given. + */ + justPressed: function (duration) { + + duration = duration || this.game.input.justPressedRate; + + return (this.isDown === true && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. + * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. + * @method Phaser.Pointer#justReleased + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate. + * @return {boolean} true if the Pointer was released within the duration given. + */ + justReleased: function (duration) { + + duration = duration || this.game.input.justReleasedRate; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Add a click trampoline to this pointer. + * + * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily + * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen + * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. + * + * This is used internally by the ScaleManager; click trampoline usage is uncommon. + * Click trampolines can only be added to pointers that are currently down. + * + * @method Phaser.Pointer#addClickTrampoline + * @protected + * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer. + * @param {function} callback - Callback to run/trampoline. + * @param {object} callbackContext - Context of the callback. + * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array. + */ + addClickTrampoline: function (name, callback, callbackContext, callbackArgs) { + + if (!this.isDown) + { + return; + } + + var trampolines = (this._clickTrampolines = this._clickTrampolines || []); + + for (var i = 0; i < trampolines.length; i++) + { + if (trampolines[i].name === name) + { + trampolines.splice(i, 1); + break; + } + } + + trampolines.push({ + name: name, + targetObject: this.targetObject, + callback: callback, + callbackContext: callbackContext, + callbackArgs: callbackArgs + }); + + }, + + /** + * Fire all click trampolines for which the pointers are still referring to the registered object. + * @method Phaser.Pointer#processClickTrampolines + * @private + */ + processClickTrampolines: function () { + + var trampolines = this._clickTrampolines; + + if (!trampolines) + { + return; + } + + for (var i = 0; i < trampolines.length; i++) + { + var trampoline = trampolines[i]; + + if (trampoline.targetObject === this._trampolineTargetObject) + { + trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs); + } + } + + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + }, + + /** + * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. + * @method Phaser.Pointer#reset + */ + reset: function () { + + if (this.isMouse === false) + { + this.active = false; + } + + this.pointerId = null; + this.identifier = null; + this.dirty = false; + this.totalTouches = 0; + this._holdSent = false; + this._history.length = 0; + this._stateReset = true; + + this.resetButtons(); + + if (this.targetObject) + { + this.targetObject._releasedHandler(this); + } + + this.targetObject = null; + + }, + + /** + * Resets the movementX and movementY properties. Use in your update handler after retrieving the values. + * @method Phaser.Pointer#resetMovement + */ + resetMovement: function() { + + this.movementX = 0; + this.movementY = 0; + + } + +}; + +Phaser.Pointer.prototype.constructor = Phaser.Pointer; + +/** +* How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. +* If not currently down it returns -1. +* If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. +* +* @name Phaser.Pointer#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* Gets the X value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldX +* @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldX", { + + get: function () { + + return this.game.world.camera.x + this.x; + + } + +}); + +/** +* Gets the Y value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldY +* @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldY", { + + get: function () { + + return this.game.world.camera.y + this.y; + + } + +}); + +/** +* Enumeration categorizing operational modes of pointers. +* +* PointerType values represent valid bitmasks. +* For example, a value representing both Mouse and Touch devices +* can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. +* +* Values may be added for future mode categorizations. +* @class Phaser.PointerMode +*/ +Phaser.PointerMode = { + + /** + * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. + * + * It has the property that a cursor is passively moved without activating the input. + * This currently corresponds with {@link Phaser.Pointer#isMouse} property. + * @constant + */ + CURSOR: 1 << 0, + + /** + * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. + * @constant + */ + CONTACT: 1 << 1 + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. +* +* @class Phaser.Touch +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Touch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * Touch events will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} touchStartCallback - A callback that can be fired on a touchStart event. + */ + this.touchStartCallback = null; + + /** + * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event. + */ + this.touchMoveCallback = null; + + /** + * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event. + */ + this.touchEndCallback = null; + + /** + * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event. + */ + this.touchEnterCallback = null; + + /** + * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event. + */ + this.touchLeaveCallback = null; + + /** + * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event. + */ + this.touchCancelCallback = null; + + /** + * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it. + * @default + */ + this.preventDefault = true; + + /** + * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received. + * @default + */ + this.event = null; + + /** + * @property {function} _onTouchStart - Internal event handler reference. + * @private + */ + this._onTouchStart = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + + /** + * @property {function} _onTouchEnd - Internal event handler reference. + * @private + */ + this._onTouchEnd = null; + + /** + * @property {function} _onTouchEnter - Internal event handler reference. + * @private + */ + this._onTouchEnter = null; + + /** + * @property {function} _onTouchLeave - Internal event handler reference. + * @private + */ + this._onTouchLeave = null; + + /** + * @property {function} _onTouchCancel - Internal event handler reference. + * @private + */ + this._onTouchCancel = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + +}; + +Phaser.Touch.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Touch#start + */ + start: function () { + + if (this._onTouchStart !== null) + { + // Avoid setting multiple listeners + 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('touchcancel', this._onTouchCancel, false); + + if (!this.game.device.cocoonJS) + { + this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false); + this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false); + } + } + + }, + + /** + * Consumes all touchmove events on the document (only enable this if you know you need it!). + * @method Phaser.Touch#consumeTouchMove + */ + consumeDocumentTouches: function () { + + this._documentTouchMove = function (event) { + event.preventDefault(); + }; + + document.addEventListener('touchmove', this._documentTouchMove, false); + + }, + + /** + * The internal method that handles the touchstart event from the browser. + * @method Phaser.Touch#onTouchStart + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchStart: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.touchStartCallback) + { + this.touchStartCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.startPointer(event.changedTouches[i]); + } + + }, + + /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. + * @method Phaser.Touch#onTouchCancel + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchCancel: function (event) { + + this.event = event; + + if (this.touchCancelCallback) + { + this.touchCancelCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchEnter + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnter: function (event) { + + this.event = event; + + if (this.touchEnterCallback) + { + this.touchEnterCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchLeave + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchLeave: function (event) { + + this.event = event; + + if (this.touchLeaveCallback) + { + this.touchLeaveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * The handler for the touchmove events. + * @method Phaser.Touch#onTouchMove + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchMove: function (event) { + + this.event = event; + + if (this.touchMoveCallback) + { + this.touchMoveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.updatePointer(event.changedTouches[i]); + } + + }, + + /** + * The handler for the touchend events. + * @method Phaser.Touch#onTouchEnd + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnd: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.touchEndCallback) + { + this.touchEndCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.Touch#stop + */ + stop: function () { + + if (this.game.device.touch) + { + this.game.canvas.removeEventListener('touchstart', this._onTouchStart); + this.game.canvas.removeEventListener('touchmove', this._onTouchMove); + this.game.canvas.removeEventListener('touchend', this._onTouchEnd); + this.game.canvas.removeEventListener('touchenter', this._onTouchEnter); + this.game.canvas.removeEventListener('touchleave', this._onTouchLeave); + this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel); + } + + } + +}; + +Phaser.Touch.prototype.constructor = Phaser.Touch; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. +* +* @class Phaser.InputHandler +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. +*/ +Phaser.InputHandler = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = sprite.game; + + /** + * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity. + * @default + */ + this.enabled = false; + + /** + * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks. + * @protected + */ + this.checked = false; + + /** + * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have + * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can + * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. + * @property {number} priorityID + * @default + */ + this.priorityID = 0; + + /** + * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. + * @default + */ + this.useHandCursor = false; + + /** + * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor? + * @private + */ + this._setHandCursor = false; + + /** + * @property {boolean} isDragged - true if the Sprite is being currently dragged. + * @default + */ + this.isDragged = false; + + /** + * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally. + * @default + */ + this.allowHorizontalDrag = true; + + /** + * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically. + * @default + */ + this.allowVerticalDrag = true; + + /** + * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. + * @default + */ + this.bringToTop = false; + + /** + * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset. + * @default + */ + this.snapOffset = null; + + /** + * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. + * @default + */ + this.snapOnDrag = false; + + /** + * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release. + * @default + */ + this.snapOnRelease = false; + + /** + * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid. + * @default + */ + this.snapX = 0; + + /** + * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid. + * @default + */ + this.snapY = 0; + + /** + * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid. + * @default + */ + this.snapOffsetX = 0; + + /** + * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid.. + * @default + */ + this.snapOffsetY = 0; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. + * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over. + * @default + */ + this.pixelPerfectOver = false; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive so only enable if you really need it. + * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite. + * @default + */ + this.pixelPerfectClick = false; + + /** + * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. + * @default + */ + this.pixelPerfectAlpha = 255; + + /** + * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no + * @default + */ + this.draggable = false; + + /** + * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag. + * @default + */ + this.boundsRect = null; + + /** + * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. + * @default + */ + this.boundsSprite = null; + + /** + * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. + */ + this.scaleLayer = false; + + /** + * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from. + */ + this.dragOffset = new Phaser.Point(); + + /** + * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? + */ + this.dragFromCenter = false; + + /** + * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. + */ + this.dragStopBlocksInputUp = false; + + /** + * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. + */ + this.dragStartPoint = new Phaser.Point(); + + /** + * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. + */ + this.dragDistanceThreshold = 0; + + /** + * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. + */ + this.dragTimeThreshold = 0; + + /** + * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. + */ + this.downPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. + */ + this.snapPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} _dragPoint - Internal cache var. + * @private + */ + this._dragPoint = new Phaser.Point(); + + /** + * @property {boolean} _dragPhase - Internal cache var. + * @private + */ + this._dragPhase = false; + + /** + * @property {boolean} _pendingDrag - Internal cache var. + * @private + */ + this._pendingDrag = false; + + /** + * @property {boolean} _dragTimePass - Internal cache var. + * @private + */ + this._dragTimePass = false; + + /** + * @property {boolean} _dragDistancePass - Internal cache var. + * @private + */ + this._dragDistancePass = false; + + /** + * @property {boolean} _wasEnabled - Internal cache var. + * @private + */ + this._wasEnabled = false; + + /** + * @property {Phaser.Point} _tempPoint - Internal cache var. + * @private + */ + this._tempPoint = new Phaser.Point(); + + /** + * @property {array} _pointerData - Internal cache var. + * @private + */ + this._pointerData = []; + + this._pointerData.push({ + id: 0, + x: 0, + y: 0, + camX: 0, + camY: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }); + +}; + +Phaser.InputHandler.prototype = { + + /** + * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. + * + * @method Phaser.InputHandler#start + * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. + * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) + * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound. + */ + start: function (priority, useHandCursor) { + + priority = priority || 0; + if (useHandCursor === undefined) { useHandCursor = false; } + + // Turning on + if (this.enabled === false) + { + // Register, etc + this.game.input.interactiveItems.add(this); + this.useHandCursor = useHandCursor; + this.priorityID = priority; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + + this.snapOffset = new Phaser.Point(); + this.enabled = true; + this._wasEnabled = true; + + } + + this.sprite.events.onAddedToGroup.add(this.addedToGroup, this); + this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this); + + return this.sprite; + + }, + + /** + * Handles when the parent Sprite is added to a new Group. + * + * @method Phaser.InputHandler#addedToGroup + * @private + */ + addedToGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this._wasEnabled && !this.enabled) + { + this.start(); + } + + }, + + /** + * Handles when the parent Sprite is removed from a Group. + * + * @method Phaser.InputHandler#removedFromGroup + * @private + */ + removedFromGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this.enabled) + { + this._wasEnabled = true; + this.stop(); + } + else + { + this._wasEnabled = false; + } + + }, + + /** + * Resets the Input Handler and disables it. + * @method Phaser.InputHandler#reset + */ + reset: function () { + + this.enabled = false; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + }, + + /** + * Stops the Input Handler from running. + * @method Phaser.InputHandler#stop + */ + stop: function () { + + // Turning off + if (this.enabled === false) + { + return; + } + else + { + // De-register, etc + this.enabled = false; + this.game.input.interactiveItems.remove(this); + } + + }, + + /** + * Clean up memory. + * @method Phaser.InputHandler#destroy + */ + destroy: function () { + + if (this.sprite) + { + if (this._setHandCursor) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + this.enabled = false; + + this.game.input.interactiveItems.remove(this); + + this._pointerData.length = 0; + this.boundsRect = null; + this.boundsSprite = null; + this.sprite = null; + } + + }, + + /** + * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. + * This is called by Phaser.Pointer and shouldn't typically be called directly. + * + * @method Phaser.InputHandler#validForInput + * @protected + * @param {number} highestID - The highest ID currently processed by the Pointer. + * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer. + * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? + * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection. + */ + validForInput: function (highestID, highestRenderID, includePixelPerfect) { + + if (includePixelPerfect === undefined) { includePixelPerfect = true; } + + if (!this.enabled || + this.sprite.scale.x === 0 || + this.sprite.scale.y === 0 || + this.priorityID < this.game.input.minPriorityID || + (this.sprite.parent && this.sprite.parent.ignoreChildInput)) + { + return false; + } + + // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it + if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver)) + { + return false; + } + + if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID > highestRenderID)) + { + return true; + } + + return false; + + }, + + /** + * Is this object using pixel perfect checking? + * + * @method Phaser.InputHandler#isPixelPerfect + * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. + */ + isPixelPerfect: function () { + + return (this.pixelPerfectClick || this.pixelPerfectOver); + + }, + + /** + * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerX + * @param {integer} [pointerId=0] + * @return {number} The x coordinate of the Input pointer. + */ + pointerX: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].x; + + }, + + /** + * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerY + * @param {integer} [pointerId=0] + * @return {number} The y coordinate of the Input pointer. + */ + pointerY: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].y; + + }, + + /** + * If the Pointer is down this returns true. + * This *only* checks if the Pointer is down, not if it's down over any specific Sprite. + * + * @method Phaser.InputHandler#pointerDown + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is down, otherwise false. + */ + pointerDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDown; + + }, + + /** + * If the Pointer is up this returns true. + * This *only* checks if the Pointer is up, not if it's up over any specific Sprite. + * + * @method Phaser.InputHandler#pointerUp + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is up, otherwise false. + */ + pointerUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isUp; + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeDown + * @param {integer} [pointerId=(check all)] + * @return {number} + */ + pointerTimeDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeDown; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeUp + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeUp; + + }, + + /** + * Is the Pointer over this Sprite? + * + * @method Phaser.InputHandler#pointerOver + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object. + */ + pointerOver: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOver) + { + return true; + } + } + + return false; + } + else + { + return this._pointerData[pointerId].isOver; + } + + }, + + /** + * Is the Pointer outside of this Sprite? + * + * @method Phaser.InputHandler#pointerOut + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. + */ + pointerOut: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOut) + { + return true; + } + } + } + else + { + return this._pointerData[pointerId].isOut; + } + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOver + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOver: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOver; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOut + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOut: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOut; + + }, + + /** + * Is this sprite being dragged by the mouse or not? + * + * @method Phaser.InputHandler#pointerDragged + * @param {integer} [pointerId=0] + * @return {boolean} True if the pointer is dragging an object, otherwise false. + */ + pointerDragged: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDragged; + + }, + + /** + * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerDown + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} True if the pointer is down, otherwise false. + */ + checkPointerDown: function (pointer, fastTest) { + + if (!pointer.isDown || + !this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectClick) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Checks if the given pointer is over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerOver + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} + */ + checkPointerOver: function (pointer, fastTest) { + + if (!this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectOver) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. + * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. + * + * @method Phaser.InputHandler#checkPixel + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters. + * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha + */ + checkPixel: function (x, y, pointer) { + + // Grab a pixel from our image into the hitCanvas and then test it + if (this.sprite.texture.baseTexture.source) + { + if (x === null && y === null) + { + // Use the pointer parameter + this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint); + + var x = this._tempPoint.x; + var y = this._tempPoint.y; + } + + if (this.sprite.anchor.x !== 0) + { + x -= -this.sprite.texture.frame.width * this.sprite.anchor.x; + } + + if (this.sprite.anchor.y !== 0) + { + y -= -this.sprite.texture.frame.height * this.sprite.anchor.y; + } + + x += this.sprite.texture.frame.x; + y += this.sprite.texture.frame.y; + + if (this.sprite.texture.trim) + { + x -= this.sprite.texture.trim.x; + y -= this.sprite.texture.trim.y; + + // If the coordinates are outside the trim area we return false immediately, to save doing a draw call + if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom) + { + this._dx = x; + this._dy = y; + return false; + } + } + + this._dx = x; + this._dy = y; + + this.game.input.hitContext.clearRect(0, 0, 1, 1); + this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1); + + if (rgb.data[3] >= this.pixelPerfectAlpha) + { + return true; + } + } + + return false; + + }, + + /** + * Internal Update method. This is called automatically and handles the Pointer + * and drag update loops. + * + * @method Phaser.InputHandler#update + * @protected + * @param {Phaser.Pointer} pointer + * @return {boolean} True if the pointer is still active, otherwise false. + */ + update: function (pointer) { + + if (this.sprite === null || this.sprite.parent === undefined) + { + // Abort. We've been destroyed. + return; + } + + if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible) + { + this._pointerOutHandler(pointer); + return false; + } + + if (this._pendingDrag) + { + if (!this._dragDistancePass) + { + this._dragDistancePass = (Phaser.Math.distance(pointer.x, pointer.y, this.downPoint.x, this.downPoint.y) >= this.dragDistanceThreshold); + } + + if (this._dragDistancePass && this._dragTimePass) + { + this.startDrag(pointer); + } + + return true; + } + else if (this.draggable && this._draggedPointerID === pointer.id) + { + return this.updateDrag(pointer, false); + } + else if (this._pointerData[pointer.id].isOver) + { + 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; + } + } + }, + + /** + * Internal method handling the pointer over event. + * + * @method Phaser.InputHandler#_pointerOverHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOverHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (data.isOver === false || pointer.dirty) + { + var sendEvent = (data.isOver === false); + + data.isOver = true; + data.isOut = false; + data.timeOver = this.game.time.time; + data.x = pointer.x - this.sprite.x; + data.y = pointer.y - this.sprite.y; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = "pointer"; + this._setHandCursor = true; + } + + if (!silent && sendEvent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOver$dispatch(this.sprite, pointer); + } + + if (this.sprite.parent && this.sprite.parent.onChildInputOver) + { + this.sprite.parent.onChildInputOver.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the pointer out event. + * + * @method Phaser.InputHandler#_pointerOutHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOutHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + data.isOver = false; + data.isOut = true; + data.timeOut = this.game.time.time; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + if (!silent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOut$dispatch(this.sprite, pointer); + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputOut) + { + this.sprite.parent.onChildInputOut.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the touched / clicked event. + * + * @method Phaser.InputHandler#_touchedHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + */ + _touchedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (!data.isDown && data.isOver) + { + if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer)) + { + return; + } + + data.isDown = true; + data.isUp = false; + data.timeDown = this.game.time.time; + + this.downPoint.set(pointer.x, pointer.y); + + // It's possible the onInputDown event creates a new Sprite that is on-top of this one, so we ought to force a Pointer update + pointer.dirty = true; + + if (this.sprite && this.sprite.events) + { + this.sprite.events.onInputDown$dispatch(this.sprite, pointer); + + // The event above might have destroyed this sprite. + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputDown) + { + this.sprite.parent.onChildInputDown.dispatch(this.sprite, pointer); + } + + // The events might have destroyed this sprite. + if (this.sprite === null) + { + return; + } + } + + // Start drag + if (this.draggable && this.isDragged === false) + { + if (this.dragTimeThreshold === 0 && this.dragDistanceThreshold === 0) + { + this.startDrag(pointer); + } + else + { + this._pendingDrag = true; + + this._dragDistancePass = (this.dragDistanceThreshold === 0); + + if (this.dragTimeThreshold > 0) + { + this._dragTimePass = false; + this.game.time.events.add(this.dragTimeThreshold, this.dragTimeElapsed, this, pointer); + } + else + { + this._dragTimePass = true; + } + } + } + + if (this.bringToTop) + { + this.sprite.bringToTop(); + } + } + + }, + + /** + * Internal method handling the drag threshold timer. + * + * @method Phaser.InputHandler#dragTimeElapsed + * @private + * @param {Phaser.Pointer} pointer + */ + dragTimeElapsed: function (pointer) { + + this._dragTimePass = true; + + if (this._pendingDrag && this.sprite) + { + if (this._dragDistancePass) + { + this.startDrag(pointer); + } + } + + }, + + /** + * Internal method handling the pointer released event. + * @method Phaser.InputHandler#_releasedHandler + * @private + * @param {Phaser.Pointer} pointer + */ + _releasedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + // If was previously touched by this Pointer, check if still is AND still over this item + if (data.isDown && pointer.isUp) + { + data.isDown = false; + data.isUp = true; + data.timeUp = this.game.time.time; + data.downDuration = data.timeUp - data.timeDown; + + // Only release the InputUp signal if the pointer is still over this sprite + var isOver = this.checkPointerOver(pointer); + + if (this.sprite && this.sprite.events) + { + if (!this.dragStopBlocksInputUp || + this.dragStopBlocksInputUp && !(this.draggable && this.isDragged && this._draggedPointerID === pointer.id)) + { + this.sprite.events.onInputUp$dispatch(this.sprite, pointer, isOver); + } + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputUp) + { + this.sprite.parent.onChildInputUp.dispatch(this.sprite, pointer, isOver); + } + + // The onInputUp event may have changed the sprite so that checkPointerOver is no longer true, so update it. + if (isOver) + { + isOver = this.checkPointerOver(pointer); + } + } + + data.isOver = isOver; + + if (!isOver && this.useHandCursor) + { + this.game.canvas.style.cursor = "default"; + this._setHandCursor = false; + } + + // It's possible the onInputUp event created a new Sprite that is on-top of this one, so force a Pointer update + pointer.dirty = true; + + this._pendingDrag = false; + + // Stop drag + if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id) + { + this.stopDrag(pointer); + } + } + + }, + + /** + * Called as a Pointer actively drags this Game Object. + * + * @method Phaser.InputHandler#updateDrag + * @private + * @param {Phaser.Pointer} pointer - The Pointer causing the drag update. + * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started. + * @return {boolean} + */ + updateDrag: function (pointer, fromStart) { + + if (fromStart === undefined) { fromStart = false; } + + if (pointer.isUp) + { + this.stopDrag(pointer); + return false; + } + + var pointerLocalCoord = this.globalToLocal(pointer); + + if (this.sprite.fixedToCamera) + { + var px = this.game.camera.scale.x * pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = this.game.camera.scale.y * pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + else + { + var px = pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + + if (this.sprite.fixedToCamera) + { + if (this.allowHorizontalDrag) + { + this.sprite.cameraOffset.x = px - this.game.camera.x; + } + + if (this.allowVerticalDrag) + { + this.sprite.cameraOffset.y = py - this.game.camera.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); + this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y); + } + } + else + { + var cx = this.game.camera.x - this._pointerData[pointer.id].camX; + var cy = this.game.camera.y - this._pointerData[pointer.id].camY; + + if (this.allowHorizontalDrag) + { + this.sprite.x = px + cx; + } + + if (this.allowVerticalDrag) + { + this.sprite.y = py + cy; + } + + 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); + this.snapPoint.set(this.sprite.x, this.sprite.y); + } + } + + this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint, fromStart); + + return true; + + }, + + /** + * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOver + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justOver: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOut + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justOut: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay)); + + }, + + /** + * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justPressed + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justPressed: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justReleased + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justReleased: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay)); + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#overDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. + */ + overDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isOver) + { + return this.game.time.time - this._pointerData[pointerId].timeOver; + } + + return -1; + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#downDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. + */ + downDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isDown) + { + return this.game.time.time - this._pointerData[pointerId].timeDown; + } + + return -1; + + }, + + /** + * Allow this Sprite to be dragged by any valid pointer. + * + * When the drag begins the Sprite.events.onDragStart event will be dispatched. + * + * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. + * + * You can control the thresholds over when a drag starts via the properties: + * + * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move + * before the drag will start. + * + * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on + * the Sprite before the drag will start. + * + * You can set either (or both) of these properties after enabling a Sprite for drag. + * + * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually + * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`. + * + * @method Phaser.InputHandler#enableDrag + * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. + * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group. + * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. + * @param {integer} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. + * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. + * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. + */ + enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) { + + if (lockCenter === undefined) { lockCenter = false; } + if (bringToTop === undefined) { bringToTop = false; } + if (pixelPerfect === undefined) { pixelPerfect = false; } + if (alphaThreshold === undefined) { alphaThreshold = 255; } + if (boundsRect === undefined) { boundsRect = null; } + if (boundsSprite === undefined) { boundsSprite = null; } + + this._dragPoint = new Phaser.Point(); + this.draggable = true; + this.bringToTop = bringToTop; + this.dragOffset = new Phaser.Point(); + this.dragFromCenter = lockCenter; + + this.pixelPerfectClick = pixelPerfect; + this.pixelPerfectAlpha = alphaThreshold; + + if (boundsRect) + { + this.boundsRect = boundsRect; + } + + if (boundsSprite) + { + this.boundsSprite = boundsSprite; + } + + }, + + /** + * Stops this sprite from being able to be dragged. + * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. + * + * @method Phaser.InputHandler#disableDrag + */ + disableDrag: function () { + + if (this._pointerData) + { + for (var i = 0; i < 10; i++) + { + this._pointerData[i].isDragged = false; + } + } + + this.draggable = false; + this.isDragged = false; + this._draggedPointerID = -1; + this._pendingDrag = false; + + }, + + /** + * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#startDrag + * @param {Phaser.Pointer} pointer + */ + startDrag: function (pointer) { + + var x = this.sprite.x; + var y = this.sprite.y; + var pointerLocalCoord = this.globalToLocal(pointer); + + this.isDragged = true; + this._draggedPointerID = pointer.id; + + this._pointerData[pointer.id].camX = this.game.camera.x; + this._pointerData[pointer.id].camY = this.game.camera.y; + + this._pointerData[pointer.id].isDragged = true; + + if (this.sprite.fixedToCamera) + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.cameraOffset.x = pointerLocalCoord.x + (this.sprite.cameraOffset.x - boundsCenterLocalCoord.x); + this.sprite.cameraOffset.y = pointerLocalCoord.y + (this.sprite.cameraOffset.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y); + } + else + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.x = pointerLocalCoord.x + (this.sprite.x - boundsCenterLocalCoord.x); + this.sprite.y = pointerLocalCoord.y + (this.sprite.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.x - pointerLocalCoord.x, this.sprite.y - pointerLocalCoord.y); + } + + this.updateDrag(pointer, true); + + if (this.bringToTop) + { + this._dragPhase = true; + this.sprite.bringToTop(); + } + + this.dragStartPoint.set(x, y); + + this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y); + + this._pendingDrag = false; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalX + * @param {number} x + */ + globalToLocalX: function (x) { + + if (this.scaleLayer) + { + x -= this.game.scale.grid.boundsFluid.x; + x *= this.game.scale.grid.scaleFluidInversed.x; + } + + return x; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalY + * @param {number} y + */ + globalToLocalY: function (y) { + + if (this.scaleLayer) + { + y -= this.game.scale.grid.boundsFluid.y; + y *= this.game.scale.grid.scaleFluidInversed.y; + } + + return y; + + }, + + /** + * Convert global coordinates to local sprite coordinates + * + * @method Phaser.InputHandler#globalToLocal + * @param {Phaser.Point} globalCoord - The global coordinates to convert. + * @return {Phaser.Point} A point containing the local coordinates. + */ + globalToLocal: function (globalCoord) { + + if (this.sprite.parent) + { + return this.game.input.getLocalPosition(this.sprite.parent, {x: globalCoord.x, y: globalCoord.y}); + } + else + { + return globalCoord; + } + + }, + + /** + * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#stopDrag + * @param {Phaser.Pointer} pointer + */ + stopDrag: function (pointer) { + + this.isDragged = false; + this._draggedPointerID = -1; + this._pointerData[pointer.id].isDragged = false; + this._dragPhase = false; + this._pendingDrag = false; + + if (this.snapOnRelease) + { + if (this.sprite.fixedToCamera) + { + 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 + { + 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); + } + } + + this.sprite.events.onDragStop$dispatch(this.sprite, pointer); + + if (this.checkPointerOver(pointer) === false) + { + this._pointerOutHandler(pointer); + } + + }, + + /** + * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! + * + * @method Phaser.InputHandler#setDragLock + * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false. + * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false. + */ + setDragLock: function (allowHorizontal, allowVertical) { + + if (allowHorizontal === undefined) { allowHorizontal = true; } + if (allowVertical === undefined) { allowVertical = true; } + + this.allowHorizontalDrag = allowHorizontal; + this.allowVerticalDrag = allowVertical; + + }, + + /** + * Make this Sprite snap to the given grid either during drag or when it's released. + * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. + * + * @method Phaser.InputHandler#enableSnap + * @param {number} snapX - The width of the grid cell to snap to. + * @param {number} snapY - The height of the grid cell to snap to. + * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged. + * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released. + * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid. + * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid. + */ + enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) { + + if (onDrag === undefined) { onDrag = true; } + if (onRelease === undefined) { onRelease = false; } + if (snapOffsetX === undefined) { snapOffsetX = 0; } + if (snapOffsetY === undefined) { snapOffsetY = 0; } + + this.snapX = snapX; + this.snapY = snapY; + this.snapOffsetX = snapOffsetX; + this.snapOffsetY = snapOffsetY; + this.snapOnDrag = onDrag; + this.snapOnRelease = onRelease; + + }, + + /** + * Stops the sprite from snapping to a grid during drag or release. + * + * @method Phaser.InputHandler#disableSnap + */ + disableSnap: function () { + + this.snapOnDrag = false; + this.snapOnRelease = false; + + }, + + /** + * Bounds Rect check for the sprite drag + * + * @method Phaser.InputHandler#checkBoundsRect + */ + checkBoundsRect: function () { + + if (this.sprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsRect.left) + { + this.sprite.cameraOffset.x = this.boundsRect.left; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right) + { + this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsRect.top) + { + this.sprite.cameraOffset.y = this.boundsRect.top; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom) + { + this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsRect.left) + { + this.sprite.x = this.boundsRect.x + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsRect.right) + { + this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsRect.top) + { + this.sprite.y = this.boundsRect.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsRect.bottom) + { + this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + }, + + /** + * Parent Sprite Bounds check for the sprite drag. + * + * @method Phaser.InputHandler#checkBoundsSprite + */ + checkBoundsSprite: function () { + + if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x) + { + this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width)) + { + this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y) + { + this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height)) + { + this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsSprite.left) + { + this.sprite.x = this.boundsSprite.left + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsSprite.right) + { + this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsSprite.top) + { + this.sprite.y = this.boundsSprite.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsSprite.bottom) + { + this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + } + +}; + +Phaser.InputHandler.prototype.constructor = Phaser.InputHandler; + +/** +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Gamepad class handles gamepad input and dispatches gamepad events. +* +* Remember to call `gamepad.start()`. +* +* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! +* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it +* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. +* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. +* +* @class Phaser.Gamepad +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Gamepad = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads + * @private + */ + this._gamepadIndexMap = {}; + + /** + * @property {Array} _rawPads - The raw state of the gamepads from the browser + * @private + */ + this._rawPads = []; + + /** + * @property {boolean} _active - Private flag for whether or not the API is polled + * @private + * @default + */ + this._active = false; + + /** + * Gamepad input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation. + * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not? + * @private + */ + this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') !== -1) || !!navigator.getGamepads; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevRawGamepadTypes + * @private + * @default + */ + this._prevRawGamepadTypes = []; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevTimestamps + * @private + * @default + */ + this._prevTimestamps = []; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._ongamepadconnected = null; + + /** + * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._gamepaddisconnected = null; + + /** + * @property {Array} _gamepads - The four Phaser Gamepads. + * @private + */ + this._gamepads = [ + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this) + ]; + +}; + +Phaser.Gamepad.prototype = { + + /** + * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. + * + * @method Phaser.Gamepad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callback methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + this.callbackContext = context; + } + + }, + + /** + * Starts the Gamepad event handling. + * This MUST be called manually before Phaser will start polling the Gamepad API. + * + * @method Phaser.Gamepad#start + */ + start: function () { + + if (this._active) + { + // Avoid setting multiple listeners + return; + } + + this._active = true; + + var _this = this; + + this._onGamepadConnected = function (event) { + return _this.onGamepadConnected(event); + }; + + this._onGamepadDisconnected = function (event) { + return _this.onGamepadDisconnected(event); + }; + + window.addEventListener('gamepadconnected', this._onGamepadConnected, false); + window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false); + + }, + + /** + * Handles the connection of a Gamepad. + * + * @method onGamepadConnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadConnected: function (event) { + + var newPad = event.gamepad; + this._rawPads.push(newPad); + this._gamepads[newPad.index].connect(newPad); + + }, + + /** + * Handles the disconnection of a Gamepad. + * + * @method onGamepadDisconnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadDisconnected: function (event) { + + var removedPad = event.gamepad; + + for (var i in this._rawPads) + { + if (this._rawPads[i].index === removedPad.index) + { + this._rawPads.splice(i,1); + } + } + + this._gamepads[removedPad.index].disconnect(); + + }, + + /** + * Main gamepad update loop. Should not be called manually. + * @method Phaser.Gamepad#update + * @protected + */ + update: function () { + + this._pollGamepads(); + + this.pad1.pollStatus(); + this.pad2.pollStatus(); + this.pad3.pollStatus(); + this.pad4.pollStatus(); + + }, + + /** + * Updating connected gamepads (for Google Chrome). Should not be called manually. + * + * @method Phaser.Gamepad#_pollGamepads + * @private + */ + _pollGamepads: function () { + + if (!this._active) + { + return; + } + + if (navigator['getGamepads']) + { + var rawGamepads = navigator.getGamepads(); + } + else if (navigator['webkitGetGamepads']) + { + var rawGamepads = navigator.webkitGetGamepads(); + } + else if (navigator['webkitGamepads']) + { + var rawGamepads = navigator.webkitGamepads(); + } + + if (rawGamepads) + { + this._rawPads = []; + + var gamepadsChanged = false; + + for (var i = 0; i < rawGamepads.length; i++) + { + if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i]) + { + gamepadsChanged = true; + this._prevRawGamepadTypes[i] = typeof rawGamepads[i]; + } + + if (rawGamepads[i]) + { + this._rawPads.push(rawGamepads[i]); + } + + // Support max 4 pads at the moment + if (i === 3) + { + break; + } + } + + for (var g = 0; g < this._gamepads.length; g++) + { + this._gamepads[g]._rawPad = this._rawPads[g]; + } + + if (gamepadsChanged) + { + var validConnections = { rawIndices: {}, padIndices: {} }; + var singlePad; + + for (var j = 0; j < this._gamepads.length; j++) + { + singlePad = this._gamepads[j]; + + if (singlePad.connected) + { + for (var k = 0; k < this._rawPads.length; k++) + { + if (this._rawPads[k].index === singlePad.index) + { + validConnections.rawIndices[singlePad.index] = true; + validConnections.padIndices[j] = true; + } + } + } + } + + for (var l = 0; l < this._gamepads.length; l++) + { + singlePad = this._gamepads[l]; + + if (validConnections.padIndices[l]) + { + continue; + } + + if (this._rawPads.length < 1) + { + singlePad.disconnect(); + } + + for (var m = 0; m < this._rawPads.length; m++) + { + if (validConnections.padIndices[l]) + { + break; + } + + var rawPad = this._rawPads[m]; + + if (rawPad) + { + if (validConnections.rawIndices[rawPad.index]) + { + singlePad.disconnect(); + continue; + } + else + { + singlePad.connect(rawPad); + validConnections.rawIndices[rawPad.index] = true; + validConnections.padIndices[l] = true; + } + } + else + { + singlePad.disconnect(); + } + } + } + } + } + }, + + /** + * Sets the deadZone variable for all four gamepads + * @method Phaser.Gamepad#setDeadZones + */ + setDeadZones: function (value) { + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].deadZone = value; + } + + }, + + /** + * Stops the Gamepad event handling. + * + * @method Phaser.Gamepad#stop + */ + stop: function () { + + this._active = false; + + window.removeEventListener('gamepadconnected', this._onGamepadConnected); + window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected); + + }, + + /** + * Reset all buttons/axes of all gamepads + * @method Phaser.Gamepad#reset + */ + reset: function () { + + this.update(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].reset(); + } + + }, + + /** + * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justPressed(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justReleased(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns true if the button is currently pressed down, on ANY gamepad. + * @method Phaser.Gamepad#isDown + * @param {number} buttonCode - The buttonCode of the button to check for. + * @return {boolean} True if a button is currently down. + */ + isDown: function (buttonCode) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].isDown(buttonCode) === true) + { + return true; + } + } + + return false; + }, + + /** + * Destroys this object and the associated event listeners. + * + * @method Phaser.Gamepad#destroy + */ + destroy: function () { + + this.stop(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].destroy(); + } + + } + +}; + +Phaser.Gamepad.prototype.constructor = Phaser.Gamepad; + +/** +* If the gamepad input is active or not - if not active it should not be updated from Input.js +* @name Phaser.Gamepad#active +* @property {boolean} active - If the gamepad input is active or not. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "active", { + + get: function () { + return this._active; + } + +}); + +/** +* Whether or not gamepads are supported in current browser. +* @name Phaser.Gamepad#supported +* @property {boolean} supported - Whether or not gamepads are supported in current browser. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "supported", { + + get: function () { + return this._gamepadSupportAvailable; + } + +}); + +/** +* How many live gamepads are currently connected. +* @name Phaser.Gamepad#padsConnected +* @property {number} padsConnected - How many live gamepads are currently connected. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", { + + get: function () { + return this._rawPads.length; + } + +}); + +/** +* Gamepad #1 +* @name Phaser.Gamepad#pad1 +* @property {Phaser.SinglePad} pad1 - Gamepad #1; +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad1", { + + get: function () { + return this._gamepads[0]; + } + +}); + +/** +* Gamepad #2 +* @name Phaser.Gamepad#pad2 +* @property {Phaser.SinglePad} pad2 - Gamepad #2 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad2", { + + get: function () { + return this._gamepads[1]; + } + +}); + +/** +* Gamepad #3 +* @name Phaser.Gamepad#pad3 +* @property {Phaser.SinglePad} pad3 - Gamepad #3 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad3", { + + get: function () { + return this._gamepads[2]; + } + +}); + +/** +* Gamepad #4 +* @name Phaser.Gamepad#pad4 +* @property {Phaser.SinglePad} pad4 - Gamepad #4 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad4", { + + get: function () { + return this._gamepads[3]; + } + +}); + +Phaser.Gamepad.BUTTON_0 = 0; +Phaser.Gamepad.BUTTON_1 = 1; +Phaser.Gamepad.BUTTON_2 = 2; +Phaser.Gamepad.BUTTON_3 = 3; +Phaser.Gamepad.BUTTON_4 = 4; +Phaser.Gamepad.BUTTON_5 = 5; +Phaser.Gamepad.BUTTON_6 = 6; +Phaser.Gamepad.BUTTON_7 = 7; +Phaser.Gamepad.BUTTON_8 = 8; +Phaser.Gamepad.BUTTON_9 = 9; +Phaser.Gamepad.BUTTON_10 = 10; +Phaser.Gamepad.BUTTON_11 = 11; +Phaser.Gamepad.BUTTON_12 = 12; +Phaser.Gamepad.BUTTON_13 = 13; +Phaser.Gamepad.BUTTON_14 = 14; +Phaser.Gamepad.BUTTON_15 = 15; + +Phaser.Gamepad.AXIS_0 = 0; +Phaser.Gamepad.AXIS_1 = 1; +Phaser.Gamepad.AXIS_2 = 2; +Phaser.Gamepad.AXIS_3 = 3; +Phaser.Gamepad.AXIS_4 = 4; +Phaser.Gamepad.AXIS_5 = 5; +Phaser.Gamepad.AXIS_6 = 6; +Phaser.Gamepad.AXIS_7 = 7; +Phaser.Gamepad.AXIS_8 = 8; +Phaser.Gamepad.AXIS_9 = 9; + +// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7). +// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button. +// In other words - discrepancies when using gamepads. + +Phaser.Gamepad.XBOX360_A = 0; +Phaser.Gamepad.XBOX360_B = 1; +Phaser.Gamepad.XBOX360_X = 2; +Phaser.Gamepad.XBOX360_Y = 3; +Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4; +Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5; +Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6; +Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7; +Phaser.Gamepad.XBOX360_BACK = 8; +Phaser.Gamepad.XBOX360_START = 9; +Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11; + +Phaser.Gamepad.XBOX360_DPAD_LEFT = 14; +Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15; +Phaser.Gamepad.XBOX360_DPAD_UP = 12; +Phaser.Gamepad.XBOX360_DPAD_DOWN = 13; + +// On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right +Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0; +Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1; +Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2; +Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3; + +// PlayStation 3 controller (masquerading as xbox360 controller) button mappings + +Phaser.Gamepad.PS3XC_X = 0; +Phaser.Gamepad.PS3XC_CIRCLE = 1; +Phaser.Gamepad.PS3XC_SQUARE = 2; +Phaser.Gamepad.PS3XC_TRIANGLE = 3; +Phaser.Gamepad.PS3XC_L1 = 4; +Phaser.Gamepad.PS3XC_R1 = 5; +Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_SELECT = 8; +Phaser.Gamepad.PS3XC_START = 9; +Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11; +Phaser.Gamepad.PS3XC_DPAD_UP = 12; +Phaser.Gamepad.PS3XC_DPAD_DOWN = 13; +Phaser.Gamepad.PS3XC_DPAD_LEFT = 14; +Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15; +Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1 + +/** +* @author @karlmacklin +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A single Phaser Gamepad +* +* @class Phaser.SinglePad +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this) +*/ +Phaser.SinglePad = function (game, padParent) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {number} index - The gamepad index as per browsers data + * @readonly + */ + this.index = null; + + /** + * @property {boolean} connected - Whether or not this particular gamepad is connected or not. + * @readonly + */ + this.connected = false; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time a button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time an axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates. + */ + this.deadZone = 0.26; + + /** + * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object + * @private + */ + this._padParent = padParent; + + /** + * @property {object} _rawPad - The 'raw' gamepad data. + * @private + */ + this._rawPad = null; + + /** + * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads. + * @private + */ + this._prevTimestamp = null; + + /** + * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected. + * @private + */ + this._buttons = []; + + /** + * @property {number} _buttonsLen - Length of the _buttons array. + * @private + */ + this._buttonsLen = 0; + + /** + * @property {Array} _axes - Current axes state. + * @private + */ + this._axes = []; + + /** + * @property {number} _axesLen - Length of the _axes array. + * @private + */ + this._axesLen = 0; + +}; + +Phaser.SinglePad.prototype = { + + /** + * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. + * + * @method Phaser.SinglePad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callbak methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + + this.callbackContext = context; + } + }, + + /** + * Gets a DeviceButton object from this controller to be stored and referenced locally. + * The DeviceButton object can then be polled, have events attached to it, etc. + * + * @method Phaser.SinglePad#getButton + * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc. + * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly. + */ + getButton: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode]; + } + else + { + return null; + } + + }, + + /** + * Main update function called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#pollStatus + */ + pollStatus: function () { + + if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp))) + { + return; + } + + for (var i = 0; i < this._buttonsLen; i++) + { + var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i]; + + if (rawButtonVal !== this._buttons[i].value) + { + if (rawButtonVal === 1) + { + this.processButtonDown(i, rawButtonVal); + } + else if (rawButtonVal === 0) + { + this.processButtonUp(i, rawButtonVal); + } + else + { + this.processButtonFloat(i, rawButtonVal); + } + } + } + + for (var index = 0; index < this._axesLen; index++) + { + var value = this._rawPad.axes[index]; + + if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone)) + { + this.processAxisChange(index, value); + } + else + { + this.processAxisChange(index, 0); + } + } + + this._prevTimestamp = this._rawPad.timestamp; + + }, + + /** + * Gamepad connect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#connect + * @param {object} rawPad - The raw gamepad object + */ + connect: function (rawPad) { + + var triggerCallback = !this.connected; + + this.connected = true; + this.index = rawPad.index; + + this._rawPad = rawPad; + + this._buttons = []; + this._buttonsLen = rawPad.buttons.length; + + this._axes = []; + this._axesLen = rawPad.axes.length; + + for (var a = 0; a < this._axesLen; a++) + { + this._axes[a] = rawPad.axes[a]; + } + + for (var buttonCode in rawPad.buttons) + { + buttonCode = parseInt(buttonCode, 10); + this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode); + } + + if (triggerCallback && this._padParent.onConnectCallback) + { + this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index); + } + + if (triggerCallback && this.onConnectCallback) + { + this.onConnectCallback.call(this.callbackContext); + } + + }, + + /** + * Gamepad disconnect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#disconnect + */ + disconnect: function () { + + var triggerCallback = this.connected; + var disconnectingIndex = this.index; + + this.connected = false; + this.index = null; + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + if (triggerCallback && this._padParent.onDisconnectCallback) + { + this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex); + } + + if (triggerCallback && this.onDisconnectCallback) + { + this.onDisconnectCallback.call(this.callbackContext); + } + + }, + + /** + * Destroys this object and associated callback references. + * + * @method Phaser.SinglePad#destroy + */ + destroy: function () { + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + this.onConnectCallback = null; + this.onDisconnectCallback = null; + this.onDownCallback = null; + this.onUpCallback = null; + this.onAxisCallback = null; + this.onFloatCallback = null; + + }, + + /** + * Handles changes in axis. + * + * @method Phaser.SinglePad#processAxisChange + * @param {object} axisState - State of the relevant axis + */ + processAxisChange: function (index, value) { + + if (this._axes[index] === value) + { + return; + } + + this._axes[index] = value; + + if (this._padParent.onAxisCallback) + { + this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value); + } + + if (this.onAxisCallback) + { + this.onAxisCallback.call(this.callbackContext, this, index, value); + } + + }, + + /** + * Handles button down press. + * + * @method Phaser.SinglePad#processButtonDown + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonDown: function (buttonCode, value) { + + if (this._buttons[buttonCode]) + { + this._buttons[buttonCode].start(null, value); + } + + 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); + } + + }, + + /** + * Handles button release. + * + * @method Phaser.SinglePad#processButtonUp + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonUp: function (buttonCode, value) { + + 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._buttons[buttonCode]) + { + this._buttons[buttonCode].stop(null, value); + } + + }, + + /** + * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) + * + * @method Phaser.SinglePad#processButtonFloat + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. + */ + processButtonFloat: function (buttonCode, value) { + + 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].padFloat(value); + } + + }, + + /** + * Returns value of requested axis. + * + * @method Phaser.SinglePad#axis + * @param {number} axisCode - The index of the axis to check + * @return {number} Axis value if available otherwise false + */ + axis: function (axisCode) { + + if (this._axes[axisCode]) + { + return this._axes[axisCode]; + } + + return false; + + }, + + /** + * Returns true if the button is pressed down. + * + * @method Phaser.SinglePad#isDown + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is pressed down. + */ + isDown: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isDown; + } + + return false; + + }, + + /** + * Returns true if the button is not currently pressed. + * + * @method Phaser.SinglePad#isUp + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is not currently pressed down. + */ + isUp: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isUp; + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justReleased + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justReleased(duration); + } + + }, + + /** + * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justPressed(duration); + } + + }, + + /** + * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example + * analog trigger buttons on the XBOX 360 controller. + * + * @method Phaser.SinglePad#buttonValue + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. + */ + buttonValue: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].value; + } + + return null; + + }, + + /** + * Reset all buttons/axes of this gamepad. + * + * @method Phaser.SinglePad#reset + */ + reset: function () { + + for (var j = 0; j < this._axes.length; j++) + { + this._axes[j] = 0; + } + + } + +}; + +Phaser.SinglePad.prototype.constructor = Phaser.SinglePad; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. +* +* @class Phaser.Key +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}. +*/ +Phaser.Key = function (game, keycode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * The enabled state of the key - see `enabled`. + * @property {boolean} _enabled + * @private + */ + this._enabled = true; + + /** + * @property {object} event - Stores the most recent DOM event. + * @readonly + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * @default + */ + this.isUp = true; + + /** + * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. + * @default + */ + this.altKey = false; + + /** + * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. + * @default + */ + this.ctrlKey = false; + + /** + * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. + * @default + */ + this.shiftKey = false; + + /** + * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now. + */ + this.timeDown = 0; + + /** + * If the key is down this value holds the duration of that key press and is constantly updated. + * If the key is up it holds the duration of the previous down session. + * @property {number} duration - The number of milliseconds this key has been held down for. + * @default + */ + this.duration = 0; + + /** + * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now. + * @default + */ + this.timeUp = -2500; + + /** + * If the key is up this value holds the duration of that key release and is constantly updated. + * If the key is down it holds the duration of the previous up session. + * @property {number} duration - The number of milliseconds this key has been up for. + * @default + */ + this.durationUp = -2500; + + /** + * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. + * @default + */ + this.repeats = 0; + + /** + * @property {number} keyCode - The keycode of this key. + */ + this.keyCode = keycode; + + /** + * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). + */ + this.onDown = new Phaser.Signal(); + + /** + * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. + */ + this.onHoldCallback = null; + + /** + * @property {object} onHoldContext - The context under which the onHoldCallback will be called. + */ + this.onHoldContext = null; + + /** + * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). + */ + this.onUp = new Phaser.Signal(); + + /** + * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justDown = false; + + /** + * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justUp = false; + +}; + +Phaser.Key.prototype = { + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#update + * @protected + */ + update: function () { + + if (!this._enabled) { return; } + + if (this.isDown) + { + this.duration = this.game.time.time - this.timeDown; + this.repeats++; + + if (this.onHoldCallback) + { + this.onHoldCallback.call(this.onHoldContext, this); + } + } + else + { + this.durationUp = this.game.time.time - this.timeUp; + } + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyDown + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyDown: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + // exit if this key down is from auto-repeat + if (this.isDown) + { + return; + } + + this.altKey = event.altKey; + this.ctrlKey = event.ctrlKey; + this.shiftKey = event.shiftKey; + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.duration = 0; + this.durationUp = this.game.time.time - this.timeUp; + this.repeats = 0; + + // _justDown will remain true until it is read via the justDown Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justDown = true; + + this.onDown.dispatch(this); + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyUp + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyUp: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = this.game.time.time - this.timeDown; + this.durationUp = 0; + + // _justUp will remain true until it is read via the justUp Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justUp = true; + + this.onUp.dispatch(this); + + }, + + /** + * Resets the state of this Key. + * + * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key. + * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. + * + * @method Phaser.Key#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = 0; + this.durationUp = -2500; + this._enabled = true; // .enabled causes reset(false) + this._justDown = false; + this._justUp = false; + + if (hard) + { + this.onDown.removeAll(); + this.onUp.removeAll(); + this.onHoldCallback = null; + this.onHoldContext = null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#downDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration. + */ + downDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (this.isDown && this.duration < duration); + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#upDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration. + */ + upDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (!this.isDown && ((this.game.time.time - this.timeUp) < duration)); + + }, + + /** + * Returns `true` if the Key was just pressed down this update tick, or `false` if it either isn't down, + * or was pressed down on a previous update tick. + * + * @method Phaser.Key#justPressed + * @return {boolean} True if the key was just pressed down this update tick. + */ + justPressed: function () { + + return (this.isDown && this.duration === 0); + + }, + + /** + * Returns `true` if the Key was just released this update tick, or `false` if it either isn't up, + * or was released on a previous update tick. + * + * @method Phaser.Key#justReleased + * @return {boolean} True if the key was just released this update tick. + */ + justReleased: function () { + + return (!this.isDown && this.durationUp === 0); + + } + +}; + +/** +* The justDown value allows you to test if this Key has just been pressed down or not. +* When you check this value it will return `true` if the Key is down, otherwise `false`. +* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. +* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justDown +* @property {boolean} justDown +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justDown", { + + get: function () { + + var current = this._justDown; + this._justDown = false; + return current; + + } + +}); + +/** +* The justUp value allows you to test if this Key has just been released or not. +* When you check this value it will return `true` if the Key is up, otherwise `false`. +* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again. +* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justUp +* @property {boolean} justUp +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justUp", { + + get: function () { + + var current = this._justUp; + this._justUp = false; + return current; + + } + +}); + +/** +* An enabled key processes its update and dispatches events. +* A key can be disabled momentarily at runtime instead of deleting it. +* @name Phaser.Key#enabled +* @property {boolean} enabled +* @memberof Phaser.Key +* @default true +*/ +Object.defineProperty(Phaser.Key.prototype, "enabled", { + + get: function () { + + return this._enabled; + + }, + + set: function (value) { + + value = !!value; + + if (value !== this._enabled) + { + if (!value) + { + this.reset(false); + } + + this._enabled = value; + } + } + +}); + +Phaser.Key.prototype.constructor = Phaser.Key; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Keyboard class monitors keyboard input and dispatches keyboard events. +* +* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. +* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. +* +* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. +* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. +* So please check your extensions before opening Phaser issues. +* +* @class Phaser.Keyboard +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Keyboard = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Keyboard input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. + */ + this.event = null; + + /** + * @property {object} pressEvent - The most recent DOM event from keypress. + */ + this.pressEvent = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. + */ + this.onDownCallback = null; + + /** + * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. + */ + this.onPressCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a key is released. + */ + this.onUpCallback = null; + + /** + * @property {array} _keys - The array the Phaser.Key objects are stored in. + * @private + */ + this._keys = []; + + /** + * @property {array} _capture - The array the key capture values are stored in. + * @private + */ + this._capture = []; + + /** + * @property {function} _onKeyDown + * @private + * @default + */ + this._onKeyDown = null; + + /** + * @property {function} _onKeyPress + * @private + * @default + */ + this._onKeyPress = null; + + /** + * @property {function} _onKeyUp + * @private + * @default + */ + this._onKeyUp = null; + + /** + * @property {number} _i - Internal cache var + * @private + */ + this._i = 0; + + /** + * @property {number} _k - Internal cache var + * @private + */ + this._k = 0; + +}; + +Phaser.Keyboard.prototype = { + + /** + * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. + * + * @method Phaser.Keyboard#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down. + * @param {function} [onUp=null] - This callback is invoked every time a key is released. + * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised. + */ + addCallbacks: function (context, onDown, onUp, onPress) { + + this.callbackContext = context; + + if (onDown !== undefined && onDown !== null) + { + this.onDownCallback = onDown; + } + + if (onUp !== undefined && onUp !== null) + { + this.onUpCallback = onUp; + } + + if (onPress !== undefined && onPress !== null) + { + this.onPressCallback = onPress; + } + + }, + + /** + * Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}. + * + * @method Phaser.Keyboard#removeCallbacks + */ + removeCallbacks: function () { + + this.callbackContext = this; + this.onDownCallback = null; + this.onUpCallback = null; + this.onPressCallback = null; + + }, + + /** + * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. + * The Key object can then be polled, have events attached to it, etc. + * + * @method Phaser.Keyboard#addKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key. + * @return {Phaser.Key} The Key object which you can store locally and reference directly. + */ + addKey: function (keycode) { + + if (!this._keys[keycode]) + { + this._keys[keycode] = new Phaser.Key(this.game, keycode); + + this.addKeyCapture(keycode); + } + + return this._keys[keycode]; + + }, + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example, + * + * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); + * + * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object. + * + * @method Phaser.Keyboard#addKeys + * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. + * @return {object} An object containing the properties mapped to {@link Phaser.Key} values. + */ + addKeys: function (keys) { + + var output = {}; + + for (var key in keys) + { + output[key] = this.addKey(keys[key]); + } + + return output; + + }, + + /** + * Removes a Key object from the Keyboard manager. + * + * @method Phaser.Keyboard#removeKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove. + */ + removeKey: function (keycode) { + + if (this._keys[keycode]) + { + this._keys[keycode] = null; + + this.removeKeyCapture(keycode); + } + + }, + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. + * + * @method Phaser.Keyboard#createCursorKeys + * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects. + */ + createCursorKeys: function () { + + return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT }); + + }, + + /** + * Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window. + * This is called automatically by Phaser.Input and should not normally be invoked directly. + * + * @method Phaser.Keyboard#start + * @protected + */ + start: function () { + + if (this.game.device.cocoonJS) + { + return; + } + + if (this._onKeyDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onKeyDown = function (event) { + return _this.processKeyDown(event); + }; + + this._onKeyUp = function (event) { + return _this.processKeyUp(event); + }; + + this._onKeyPress = function (event) { + return _this.processKeyPress(event); + }; + + window.addEventListener('keydown', this._onKeyDown, false); + window.addEventListener('keyup', this._onKeyUp, false); + window.addEventListener('keypress', this._onKeyPress, false); + + }, + + /** + * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. + * + * @method Phaser.Keyboard#stop + */ + stop: function () { + + window.removeEventListener('keydown', this._onKeyDown); + window.removeEventListener('keyup', this._onKeyUp); + window.removeEventListener('keypress', this._onKeyPress); + + this._onKeyDown = null; + this._onKeyUp = null; + this._onKeyPress = null; + + }, + + /** + * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. + * Also clears all key captures and currently created Key objects. + * + * @method Phaser.Keyboard#destroy + */ + destroy: function () { + + this.stop(); + + this.clearCaptures(); + + this._keys.length = 0; + this._i = 0; + + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Pass in either a single keycode or an array/hash of keycodes. + * + * @method Phaser.Keyboard#addKeyCapture + * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`. + */ + addKeyCapture: function (keycode) { + + if (typeof keycode === 'object') + { + for (var key in keycode) + { + this._capture[keycode[key]] = true; + } + } + else + { + this._capture[keycode] = true; + } + }, + + /** + * Removes an existing key capture. + * + * @method Phaser.Keyboard#removeKeyCapture + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of. + */ + removeKeyCapture: function (keycode) { + + delete this._capture[keycode]; + + }, + + /** + * Clear all set key captures. + * + * @method Phaser.Keyboard#clearCaptures + */ + clearCaptures: function () { + + this._capture = {}; + + }, + + /** + * Updates all currently defined keys. + * + * @method Phaser.Keyboard#update + */ + update: function () { + + this._i = this._keys.length; + + while (this._i--) + { + if (this._keys[this._i]) + { + this._keys[this._i].update(); + } + } + + }, + + /** + * Process the keydown event. + * + * @method Phaser.Keyboard#processKeyDown + * @param {KeyboardEvent} event + * @protected + */ + processKeyDown: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + // The event is being captured but another hotkey may need it + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyDown(event); + + this._k = key; + + if (this.onDownCallback) + { + this.onDownCallback.call(this.callbackContext, event); + } + + }, + + /** + * Process the keypress event. + * + * @method Phaser.Keyboard#processKeyPress + * @param {KeyboardEvent} event + * @protected + */ + processKeyPress: function (event) { + + this.pressEvent = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.onPressCallback) + { + this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event); + } + + }, + + /** + * Process the keyup event. + * + * @method Phaser.Keyboard#processKeyUp + * @param {KeyboardEvent} event + * @protected + */ + processKeyUp: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyUp(event); + + if (this.onUpCallback) + { + this.onUpCallback.call(this.callbackContext, event); + } + + }, + + /** + * Resets all Keys. + * + * @method Phaser.Keyboard#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.event = null; + + var i = this._keys.length; + + while (i--) + { + if (this._keys[i]) + { + this._keys[i].reset(hard); + } + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#downDuration + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. + */ + downDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].downDuration(duration); + } + else + { + return null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#upDuration + * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found. + */ + upDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].upDuration(duration); + } + else + { + return null; + } + + }, + + justPressed: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justPressed(); + } + else + { + return null; + } + + }, + + justReleased: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justReleased(); + } + else + { + return null; + } + + }, + + /** + * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. + * + * @method Phaser.Keyboard#isDown + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found. + */ + isDown: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].isDown; + } + else + { + return null; + } + + } + +}; + +/** +* Returns the string value of the most recently pressed key. +* @name Phaser.Keyboard#lastChar +* @property {string} lastChar - The string value of the most recently pressed key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", { + + get: function () { + + if (this.event && this.event.charCode === 32) + { + return ''; + } + else if (this.pressEvent) + { + return String.fromCharCode(this.pressEvent.charCode); + } + else + { + return null; + } + + } + +}); + +/** +* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. +* @name Phaser.Keyboard#lastKey +* @property {Phaser.Key} lastKey - The most recently pressed Key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", { + + get: function () { + + return this._keys[this._k]; + + } + +}); + +Phaser.Keyboard.prototype.constructor = Phaser.Keyboard; + +/** +* A key code represents a physical key on a keyboard. +* +* The KeyCode class contains commonly supported keyboard key codes which can be used +* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods. +* +* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. +* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. +* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property. +* +* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; +* the latter approach is supported for compatibility. +* +* @class Phaser.KeyCode +*/ +Phaser.KeyCode = { + /** @static */ + A: "A".charCodeAt(0), + /** @static */ + B: "B".charCodeAt(0), + /** @static */ + C: "C".charCodeAt(0), + /** @static */ + D: "D".charCodeAt(0), + /** @static */ + E: "E".charCodeAt(0), + /** @static */ + F: "F".charCodeAt(0), + /** @static */ + G: "G".charCodeAt(0), + /** @static */ + H: "H".charCodeAt(0), + /** @static */ + I: "I".charCodeAt(0), + /** @static */ + J: "J".charCodeAt(0), + /** @static */ + K: "K".charCodeAt(0), + /** @static */ + L: "L".charCodeAt(0), + /** @static */ + M: "M".charCodeAt(0), + /** @static */ + N: "N".charCodeAt(0), + /** @static */ + O: "O".charCodeAt(0), + /** @static */ + P: "P".charCodeAt(0), + /** @static */ + Q: "Q".charCodeAt(0), + /** @static */ + R: "R".charCodeAt(0), + /** @static */ + S: "S".charCodeAt(0), + /** @static */ + T: "T".charCodeAt(0), + /** @static */ + U: "U".charCodeAt(0), + /** @static */ + V: "V".charCodeAt(0), + /** @static */ + W: "W".charCodeAt(0), + /** @static */ + X: "X".charCodeAt(0), + /** @static */ + Y: "Y".charCodeAt(0), + /** @static */ + Z: "Z".charCodeAt(0), + /** @static */ + ZERO: "0".charCodeAt(0), + /** @static */ + ONE: "1".charCodeAt(0), + /** @static */ + TWO: "2".charCodeAt(0), + /** @static */ + THREE: "3".charCodeAt(0), + /** @static */ + FOUR: "4".charCodeAt(0), + /** @static */ + FIVE: "5".charCodeAt(0), + /** @static */ + SIX: "6".charCodeAt(0), + /** @static */ + SEVEN: "7".charCodeAt(0), + /** @static */ + EIGHT: "8".charCodeAt(0), + /** @static */ + NINE: "9".charCodeAt(0), + /** @static */ + NUMPAD_0: 96, + /** @static */ + NUMPAD_1: 97, + /** @static */ + NUMPAD_2: 98, + /** @static */ + NUMPAD_3: 99, + /** @static */ + NUMPAD_4: 100, + /** @static */ + NUMPAD_5: 101, + /** @static */ + NUMPAD_6: 102, + /** @static */ + NUMPAD_7: 103, + /** @static */ + NUMPAD_8: 104, + /** @static */ + NUMPAD_9: 105, + /** @static */ + NUMPAD_MULTIPLY: 106, + /** @static */ + NUMPAD_ADD: 107, + /** @static */ + NUMPAD_ENTER: 108, + /** @static */ + NUMPAD_SUBTRACT: 109, + /** @static */ + NUMPAD_DECIMAL: 110, + /** @static */ + NUMPAD_DIVIDE: 111, + /** @static */ + F1: 112, + /** @static */ + F2: 113, + /** @static */ + F3: 114, + /** @static */ + F4: 115, + /** @static */ + F5: 116, + /** @static */ + F6: 117, + /** @static */ + F7: 118, + /** @static */ + F8: 119, + /** @static */ + F9: 120, + /** @static */ + F10: 121, + /** @static */ + F11: 122, + /** @static */ + F12: 123, + /** @static */ + F13: 124, + /** @static */ + F14: 125, + /** @static */ + F15: 126, + /** @static */ + COLON: 186, + /** @static */ + EQUALS: 187, + /** @static */ + COMMA: 188, + /** @static */ + UNDERSCORE: 189, + /** @static */ + PERIOD: 190, + /** @static */ + QUESTION_MARK: 191, + /** @static */ + TILDE: 192, + /** @static */ + OPEN_BRACKET: 219, + /** @static */ + BACKWARD_SLASH: 220, + /** @static */ + CLOSED_BRACKET: 221, + /** @static */ + QUOTES: 222, + /** @static */ + BACKSPACE: 8, + /** @static */ + TAB: 9, + /** @static */ + CLEAR: 12, + /** @static */ + ENTER: 13, + /** @static */ + SHIFT: 16, + /** @static */ + CONTROL: 17, + /** @static */ + ALT: 18, + /** @static */ + CAPS_LOCK: 20, + /** @static */ + ESC: 27, + /** @static */ + SPACEBAR: 32, + /** @static */ + PAGE_UP: 33, + /** @static */ + PAGE_DOWN: 34, + /** @static */ + END: 35, + /** @static */ + HOME: 36, + /** @static */ + LEFT: 37, + /** @static */ + UP: 38, + /** @static */ + RIGHT: 39, + /** @static */ + DOWN: 40, + /** @static */ + PLUS: 43, + /** @static */ + MINUS: 44, + /** @static */ + INSERT: 45, + /** @static */ + DELETE: 46, + /** @static */ + HELP: 47, + /** @static */ + NUM_LOCK: 144 +}; + +// Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility +for (var key in Phaser.KeyCode) +{ + if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/)) + { + Phaser.Keyboard[key] = Phaser.KeyCode[key]; + } +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +Phaser.Component = function () {}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. +* +* @class +*/ +Phaser.Component.Angle = function () {}; + +Phaser.Component.Angle.prototype = { + + /** + * The angle property is the rotation of the Game Object in *degrees* from its original orientation. + * + * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. + * + * Values outside this range are added to or subtracted from 360 to obtain a value within the range. + * For example, the statement player.angle = 450 is the same as player.angle = 90. + * + * If you wish to work in radians instead of degrees you can use the property `rotation` instead. + * Working in radians is slightly faster as it doesn't have to perform any calculations. + * + * @property {number} angle + */ + angle: { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); + + }, + + set: function(value) { + + this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. +* +* @class +*/ +Phaser.Component.Animation = function () {}; + +Phaser.Component.Animation.prototype = { + + /** + * Plays an Animation. + * + * The animation should have previously been created via `animations.add`. + * + * If the animation is already playing calling this again won't do anything. + * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. + * + * @method + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation. + */ + play: function (name, frameRate, loop, killOnComplete) { + + if (this.animations) + { + return this.animations.play(name, frameRate, loop, killOnComplete); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. +* It is used by the InWorld component. +* +* @class +*/ +Phaser.Component.AutoCull = function () {}; + +Phaser.Component.AutoCull.prototype = { + + /** + * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. + * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. + * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} autoCull + * @default + */ + autoCull: false, + + /** + * Checks if the Game Objects bounds intersect with the Game Camera bounds. + * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + if (!this.autoCull && !this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + } + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Bounds component contains properties related to the bounds of the Game Object. +* +* @class +*/ +Phaser.Component.Bounds = function () {}; + +Phaser.Component.Bounds.prototype = { + + /** + * The amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * anchor.x`. + * It will only be > 0 if anchor.x is not equal to zero. + * + * @property {number} offsetX + * @readOnly + */ + offsetX: { + + get: function () { + + return this.anchor.x * this.width; + + } + + }, + + /** + * The amount the Game Object is visually offset from its y coordinate. + * This is the same as `height * anchor.y`. + * It will only be > 0 if anchor.y is not equal to zero. + * + * @property {number} offsetY + * @readOnly + */ + offsetY: { + + get: function () { + + return this.anchor.y * this.height; + + } + + }, + + /** + * The local center x coordinate of the Game Object. + * This is the same as `(x - offsetX) + (width / 2)`. + * + * @property {number} centerX + */ + centerX: { + + get: function () { + + return (this.x - this.offsetX) + (this.width * 0.5); + + }, + + set: function (value) { + + this.x = (value + this.offsetX) - (this.width * 0.5); + + } + + }, + + /** + * The local center y coordinate of the Game Object. + * This is the same as `(y - offsetY) + (height / 2)`. + * + * @property {number} centerY + */ + centerY: { + + get: function () { + + return (this.y - this.offsetY) + (this.height * 0.5); + + }, + + set: function (value) { + + this.y = (value + this.offsetY) - (this.height * 0.5); + + } + + }, + + /** + * The left coordinate of the Game Object. + * This is the same as `x - offsetX`. + * + * @property {number} left + */ + left: { + + get: function () { + + return this.x - this.offsetX; + + }, + + set: function (value) { + + this.x = value + this.offsetX; + + } + + }, + + /** + * The right coordinate of the Game Object. + * This is the same as `x + width - offsetX`. + * + * @property {number} right + */ + right: { + + get: function () { + + return (this.x + this.width) - this.offsetX; + + }, + + set: function (value) { + + this.x = value - (this.width) + this.offsetX; + + } + + }, + + /** + * The y coordinate of the Game Object. + * This is the same as `y - offsetY`. + * + * @property {number} top + */ + top: { + + get: function () { + + return this.y - this.offsetY; + + }, + + set: function (value) { + + this.y = value + this.offsetY; + + } + + }, + + /** + * The sum of the y and height properties. + * This is the same as `y + height - offsetY`. + * + * @property {number} bottom + */ + bottom: { + + get: function () { + + return (this.y + this.height) - this.offsetY; + + }, + + set: function (value) { + + this.y = value - (this.height) + this.offsetY; + + } + + }, + + /** + * Aligns this Game Object within another Game Object, or Rectangle, known as the + * 'container', to one of 9 possible positions. + * + * The container must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the container. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, + * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * container, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignIn: function (container, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = container.left - offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = container.centerX + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = container.right + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.left = container.left - offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.CENTER: + this.centerX = container.centerX + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.right = container.right + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = container.left - offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = container.centerX + offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = container.right + offsetX; + this.bottom = container.bottom + offsetY; + break; + } + + return this; + + }, + + /** + * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the + * 'parent', in one of 11 possible positions. + * + * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the parent. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, + * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, + * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * parent, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignTo: function (parent, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = parent.left - offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = parent.centerX + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = parent.right + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.LEFT_TOP: + this.right = parent.left - offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.right = parent.left - offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.LEFT_BOTTOM: + this.right = parent.left - offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.RIGHT_TOP: + this.left = parent.right + offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.left = parent.right + offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.RIGHT_BOTTOM: + this.left = parent.right + offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = parent.left - offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = parent.centerX + offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = parent.right + offsetX; + this.top = parent.bottom + offsetY; + break; + } + + return this; + + } + +}; + +// Phaser.Group extensions + +Phaser.Group.prototype.alignIn = Phaser.Component.Bounds.prototype.alignIn; +Phaser.Group.prototype.alignTo = Phaser.Component.Bounds.prototype.alignTo; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The BringToTop Component features quick access to Group sorting related methods. +* +* @class +*/ +Phaser.Component.BringToTop = function () {}; + +/** +* Brings this Game Object to the top of its parents display list. +* Visually this means it will render over the top of any old child in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.bringToTop = function() { + + if (this.parent) + { + this.parent.bringToTop(this); + } + + return this; + +}; + +/** +* Sends this Game Object to the bottom of its parents display list. +* Visually this means it will render below all other children in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.sendToBack = function() { + + if (this.parent) + { + this.parent.sendToBack(this); + } + + return this; + +}; + +/** +* Moves this Game Object up one place in its parents display list. +* This call has no effect if the Game Object is already at the top of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveUp = function () { + + if (this.parent) + { + this.parent.moveUp(this); + } + + return this; + +}; + +/** +* Moves this Game Object down one place in its parents display list. +* This call has no effect if the Game Object is already at the bottom of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveDown = function () { + + if (this.parent) + { + this.parent.moveDown(this); + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Core Component Features. +* +* @class +*/ +Phaser.Component.Core = function () {}; + +/** + * @property {boolean} skipTypeChecks - Skip type checks in {@link #init}. + * @static + * @default + */ +Phaser.Component.Core.skipTypeChecks = false; + +/** +* Installs / registers mixin components. +* +* The `this` context should be that of the applicable object instance or prototype. +* +* @method +* @protected +*/ +Phaser.Component.Core.install = function (components) { + + // Always install 'Core' first + Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype); + + this.components = {}; + + for (var i = 0; i < components.length; i++) + { + var id = components[i]; + var replace = false; + + if (id === 'Destroy') + { + replace = true; + } + + Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace); + + this.components[id] = true; + } + +}; + +/** +* Initializes the mixin components. +* +* The `this` context should be an instance of the component mixin target. +* +* @method +* @protected +*/ +Phaser.Component.Core.init = function (game, x, y, key, frame) { + + if (!Phaser.Component.Core.skipTypeChecks) + { + if (!(game instanceof Phaser.Game)) + { + throw new Error('The value passed as the `game` argument (' + game + ') is not an instance of Phaser.Game.'); + } + + if (typeof x !== 'number') + { + console.warn('The `x` argument value (%s) should be a number.', x); + x = 0; // This would be done implicitly in position.set(). + } + + if (typeof y !== 'number') + { + console.warn('The `y` argument value (%s) should be a number.', y); + y = 0; // This would be done implicitly in position.set(). + } + } + + this.game = game; + this.key = key; + this.data = {}; + + this.position.set(x, y); + this.world = new Phaser.Point(x, y); + this.previousPosition = new Phaser.Point(x, y); + + this.events = new Phaser.Events(this); + + this._bounds = new Phaser.Rectangle(); + + if (this.components.PhysicsBody) + { + // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype. + this.body = this.body; + } + + if (this.components.Animation) + { + this.animations = new Phaser.AnimationManager(this); + } + + if (this.components.LoadTexture && key !== null) + { + this.loadTexture(key, frame); + } + + if (this.components.FixedToCamera) + { + this.cameraOffset = new Phaser.Point(x, y); + } + +}; + +Phaser.Component.Core.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty); + + if (this.visible) + { + this.renderOrderID = this.game.stage.currentRenderOrderID++; + } + + if (this.animations) + { + this.animations.update(); + } + + if (this.body) + { + this.body.preUpdate(); + } + + this.preUpdateChildren(); + + return true; + +}; + +Phaser.Component.Core.prototype = { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + game: null, + + /** + * A user defined name given to this Game Object. + * This value isn't ever used internally by Phaser, it is meant as a game level property. + * @property {string} name + * @default + */ + name: '', + + /** + * An empty Object that belongs to this Game Object. + * This value isn't ever used internally by Phaser, but may be used by your own code, or + * by Phaser Plugins, to store data that needs to be associated with the Game Object, + * without polluting the Game Object directly. + * @property {Object} data + * @default + */ + data: {}, + + /** + * The components this Game Object has installed. + * @property {object} components + * @protected + */ + components: {}, + + /** + * The z depth of this Game Object within its parent Group. + * No two objects in a Group can have the same z value. + * This value is adjusted automatically whenever the Group hierarchy changes. + * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. + * @property {number} z + * @readOnly + */ + z: 0, + + /** + * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this + * Game Object, or any of its components. + * @see Phaser.Events + * @property {Phaser.Events} events + */ + events: undefined, + + /** + * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. + * Through it you can create, play, pause and stop animations. + * @see Phaser.AnimationManager + * @property {Phaser.AnimationManager} animations + */ + animations: undefined, + + /** + * The key of the image or texture used by this Game Object during rendering. + * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. + * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. + * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. + * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key + */ + key: '', + + /** + * The world coordinates of this Game Object in pixels. + * Depending on where in the display list this Game Object is placed this value can differ from `position`, + * which contains the x/y coordinates relative to the Game Objects parent. + * @property {Phaser.Point} world + */ + world: null, + + /** + * A debug flag designed for use with `Game.enableStep`. + * @property {boolean} debug + * @default + */ + debug: false, + + /** + * The position the Game Object was located in the previous frame. + * @property {Phaser.Point} previousPosition + * @readOnly + */ + previousPosition: null, + + /** + * The rotation the Game Object was in set to in the previous frame. Value is in radians. + * @property {number} previousRotation + * @readOnly + */ + previousRotation: 0, + + /** + * The render order ID is used internally by the renderer and Input Manager and should not be modified. + * This property is mostly used internally by the renderers, but is exposed for the use of plugins. + * @property {number} renderOrderID + * @readOnly + */ + renderOrderID: 0, + + /** + * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. + * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. + * @property {boolean} fresh + * @readOnly + */ + fresh: true, + + /** + * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. + * You can set it directly to allow you to flag an object to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy an object from within one of its own callbacks + * such as with Buttons or other Input events. + * + * @property {boolean} pendingDestroy + */ + pendingDestroy: false, + + /** + * @property {Phaser.Rectangle} _bounds - Internal cache var. + * @private + */ + _bounds: null, + + /** + * @property {boolean} _exists - Internal cache var. + * @private + */ + _exists: true, + + /** + * Controls if this Game Object is processed by the core game loop. + * If this Game Object has a physics body it also controls if its physics body is updated or not. + * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. + * It also toggles the `visible` property to false as well. + * + * Setting `exists` to true will add its physics body back in to the physics world, if it has one. + * It will also set the `visible` property to `true`. + * + * @property {boolean} exists + */ + exists: { + + get: function () { + + return this._exists; + + }, + + set: function (value) { + + if (value) + { + this._exists = true; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.addToWorld(); + } + + this.visible = true; + } + else + { + this._exists = false; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.removeFromWorld(); + } + + this.visible = false; + } + + } + + }, + + /** + * Internal method called by preUpdate. + * + * @method + * @protected + */ + preUpdateChildren: function() { + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + }, + + /** + * Override this method in your own custom objects to handle any update requirements. + * It is called immediately after `preUpdate` and before `postUpdate`. + * Remember if this Game Object has any children you should call update on those too. + * + * @method + */ + update: function() { + + }, + + /** + * Internal method called by the World postUpdate cycle. + * + * @method + * @protected + */ + postUpdate: function() { + + if (this.customRender) + { + this.key.render(); + } + + if (this.components.PhysicsBody) + { + Phaser.Component.PhysicsBody.postUpdate.call(this); + } + + if (this.components.FixedToCamera) + { + Phaser.Component.FixedToCamera.postUpdate.call(this); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, +* which can be updated in real-time. +* +* @class +*/ +Phaser.Component.Crop = function () {}; + +Phaser.Component.Crop.prototype = { + + /** + * The Rectangle used to crop the texture this Game Object uses. + * Set this property via `crop`. + * If you modify this property directly you must call `updateCrop` in order to have the change take effect. + * @property {Phaser.Rectangle} cropRect + * @default + */ + cropRect: null, + + /** + * @property {Phaser.Rectangle} _crop - Internal cache var. + * @private + */ + _crop: null, + + /** + * Crop allows you to crop the texture being used to display this Game Object. + * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. + * + * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, + * or by modifying `cropRect` property directly and then calling `updateCrop`. + * + * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object + * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. + * + * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, + * in which case the values are duplicated to a local object. + * + * @method + * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. + * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. + */ + crop: function (rect, copy) { + + if (copy === undefined) { copy = false; } + + if (rect) + { + if (copy && this.cropRect !== null) + { + this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height); + } + else if (copy && this.cropRect === null) + { + this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height); + } + else + { + this.cropRect = rect; + } + + this.updateCrop(); + } + else + { + this._crop = null; + this.cropRect = null; + + this.resetFrame(); + } + + }, + + /** + * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, + * or the rectangle it references, then you need to update the crop frame by calling this method. + * + * @method + */ + updateCrop: function () { + + if (!this.cropRect) + { + return; + } + + var oldX = this.texture.crop.x; + var oldY = this.texture.crop.y; + var oldW = this.texture.crop.width; + var oldH = this.texture.crop.height; + + this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop); + this._crop.x += this._frame.x; + this._crop.y += this._frame.y; + + var cx = Math.max(this._frame.x, this._crop.x); + var cy = Math.max(this._frame.y, this._crop.y); + var cw = Math.min(this._frame.right, this._crop.right) - cx; + var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy; + + this.texture.crop.x = cx; + this.texture.crop.y = cy; + this.texture.crop.width = cw; + this.texture.crop.height = ch; + + this.texture.frame.width = Math.min(cw, this.cropRect.width); + this.texture.frame.height = Math.min(ch, this.cropRect.height); + + this.texture.width = this.texture.frame.width; + this.texture.height = this.texture.frame.height; + + this.texture._updateUvs(); + + if (this.tint !== 0xffffff && (oldX !== cx || oldY !== cy || oldW !== cw || oldH !== ch)) + { + this.texture.requiresReTint = true; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Delta component provides access to delta values between the Game Objects current and previous position. +* +* @class +*/ +Phaser.Component.Delta = function () {}; + +Phaser.Component.Delta.prototype = { + + /** + * Returns the delta x value. The difference between world.x now and in the previous frame. + * + * The value will be positive if the Game Object has moved to the right or negative if to the left. + * + * @property {number} deltaX + * @readonly + */ + deltaX: { + + get: function() { + + return this.world.x - this.previousPosition.x; + + } + + }, + + /** + * Returns the delta y value. The difference between world.y now and in the previous frame. + * + * The value will be positive if the Game Object has moved down or negative if up. + * + * @property {number} deltaY + * @readonly + */ + deltaY: { + + get: function() { + + return this.world.y - this.previousPosition.y; + + } + + }, + + /** + * Returns the delta z value. The difference between rotation now and in the previous frame. + * + * @property {number} deltaZ - The delta value. + * @readonly + */ + deltaZ: { + + get: function() { + + return this.rotation - this.previousRotation; + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Destroy component is responsible for destroying a Game Object. +* +* @class +*/ +Phaser.Component.Destroy = function () {}; + +Phaser.Component.Destroy.prototype = { + + /** + * As a Game Object runs through its destroy method this flag is set to true, + * and can be checked in any sub-systems or plugins it is being destroyed from. + * @property {boolean} destroyPhase + * @readOnly + */ + destroyPhase: false, + + /** + * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present + * and nulls its reference to `game`, freeing it up for garbage collection. + * + * If this Game Object has the Events component it will also dispatch the `onDestroy` event. + * + * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've + * more than one Game Object sharing the same BaseTexture. + * + * @method + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? + * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. + */ + destroy: function (destroyChildren, destroyTexture) { + + if (this.game === null || this.destroyPhase) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (destroyTexture === undefined) { destroyTexture = false; } + + this.destroyPhase = true; + + if (this.events) + { + this.events.onDestroy$dispatch(this); + } + + if (this.parent) + { + if (this.parent instanceof Phaser.Group) + { + this.parent.remove(this); + } + else + { + this.parent.removeChild(this); + } + } + + if (this.input) + { + this.input.destroy(); + } + + if (this.animations) + { + this.animations.destroy(); + } + + if (this.body) + { + this.body.destroy(); + } + + if (this.events) + { + this.events.destroy(); + } + + this.game.tweens.removeFrom(this); + + var i = this.children.length; + + if (destroyChildren) + { + while (i--) + { + this.children[i].destroy(destroyChildren); + } + } + else + { + while (i--) + { + this.removeChild(this.children[i]); + } + } + + if (this._crop) + { + this._crop = null; + this.cropRect = null; + } + + if (this._frame) + { + this._frame = null; + } + + if (Phaser.Video && this.key instanceof Phaser.Video) + { + this.key.onChangeSource.remove(this.resizeFrame, this); + } + + if (Phaser.BitmapText && this._glyphs) + { + this._glyphs = []; + } + + this.alive = false; + this.exists = false; + this.visible = false; + + this.filters = null; + this.mask = null; + this.game = null; + + this.data = {}; + + // In case Pixi is still going to try and render it even though destroyed + this.renderable = false; + + if (this.transformCallback) + { + this.transformCallback = null; + this.transformCallbackContext = null; + } + + // Pixi level DisplayObject destroy + this.hitArea = null; + this.parent = null; + this.stage = null; + this.worldTransform = null; + this.filterArea = null; + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + // Texture? + if (destroyTexture) + { + this.texture.destroy(true); + } + + this.destroyPhase = false; + this.pendingDestroy = false; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Events component is a collection of events fired by the parent Game Object. +* +* Phaser uses what are known as 'Signals' for all event handling. All of the events in +* this class are signals you can subscribe to, much in the same way you'd "listen" for +* an event. +* +* For example to tell when a Sprite has been added to a new group, you can bind a function +* to the {@link #onAddedToGroup} signal: +* +* `sprite.events.onAddedToGroup.add(yourFunction, this);` +* +* Where `yourFunction` is the function you want called when this event occurs. +* +* For more details about how signals work please see the {@link Phaser.Signal} class. +* +* The Input-related events will only be dispatched if the Sprite has had {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true` +* and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. +* +* @class Phaser.Events +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. +*/ +Phaser.Events = function (sprite) { + + /** + * @property {Phaser.Sprite} parent - The Sprite that owns these events. + */ + this.parent = sprite; + + // The signals are automatically added by the corresponding proxy properties + +}; + +Phaser.Events.prototype = { + + /** + * Removes all events. + * + * @method Phaser.Events#destroy + */ + destroy: function () { + + this._parent = null; + + if (this._onDestroy) { this._onDestroy.dispose(); } + if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } + if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } + if (this._onKilled) { this._onKilled.dispose(); } + if (this._onRevived) { this._onRevived.dispose(); } + if (this._onEnterBounds) { this._onEnterBounds.dispose(); } + if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } + + if (this._onInputOver) { this._onInputOver.dispose(); } + if (this._onInputOut) { this._onInputOut.dispose(); } + if (this._onInputDown) { this._onInputDown.dispose(); } + if (this._onInputUp) { this._onInputUp.dispose(); } + if (this._onDragStart) { this._onDragStart.dispose(); } + if (this._onDragUpdate) { this._onDragUpdate.dispose(); } + if (this._onDragStop) { this._onDragStop.dispose(); } + + if (this._onAnimationStart) { this._onAnimationStart.dispose(); } + if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } + if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } + + }, + + // The following properties are sentinels that will be replaced with getters + + /** + * This signal is dispatched when this Game Object is added to a new {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was added to the Group. + * - {Phaser.Group} The Group it was added to. + * + * @property {Phaser.Signal} onAddedToGroup + */ + onAddedToGroup: null, + + /** + * This signal is dispatched when the Game Object is removed from a {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was removed from the Group. + * - {Phaser.Group} The Group it was removed from. + * + * @property {Phaser.Signal} onRemovedFromGroup + */ + onRemovedFromGroup: null, + + /** + * This signal is dispatched when the Game Object is destroyed. + * This happens when {@link Phaser.Sprite#destroy Sprite.destroy()} is called, or {@link Phaser.Group#destroy Group.destroy()} with `destroyChildren` set to true. + * It is sent one argument: + * + * - {any} The Game Object that was destroyed. + * + * @property {Phaser.Signal} onDestroy + */ + onDestroy: null, + + /** + * This signal is dispatched when the Game Object is killed. + * This happens when {@link Phaser.Sprite#kill Sprite.kill()} is called. + * Please understand the difference between {@link Phaser.Sprite#kill kill} and {@link Phaser.Sprite#destroy destroy} by looking at their respective methods. + * It is sent one argument: + * + * - {any} The Game Object that was killed. + * + * @property {Phaser.Signal} onKilled + */ + onKilled: null, + + /** + * This signal is dispatched when the Game Object is revived from a previously killed state. + * This happens when {@link Phaser.Sprite#revive Sprite.revive()} is called. + * It is sent one argument: + * + * - {any} The Game Object that was revived. + * + * @property {Phaser.Signal} onRevived + */ + onRevived: null, + + /** + * This signal is dispatched when the Game Object leaves the Phaser.World {@link Phaser.World#bounds bounds}. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that left the World bounds. + * + * @property {Phaser.Signal} onOutOfBounds + */ + onOutOfBounds: null, + + /** + * This signal is dispatched when the Game Object returns within the Phaser.World {@link Phaser.World#bounds bounds}, having previously been outside of them. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that entered the World bounds. + * + * @property {Phaser.Signal} onEnterBounds + */ + onEnterBounds: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an over event from a {@link Phaser.Pointer}. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOver + */ + onInputOver: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an out event from a {@link Phaser.Pointer}, which was previously over it. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOut + */ + onInputOut: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives a down event from a {@link Phaser.Pointer}. This effectively means the Pointer has been + * pressed down (but not yet released) on the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputDown + */ + onInputDown: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an up event from a {@link Phaser.Pointer}. This effectively means the Pointer had been + * pressed down, and was then released on the Game Object. + * It is sent three arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {boolean} isOver - Is the Pointer still over the Game Object? + * + * @property {Phaser.Signal} onInputUp + */ + onInputUp: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} starts to drag the Game Object, taking into consideration the various + * drag limitations that may be set. + * It is sent four arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The x coordinate that the drag started from. + * - {number} The y coordinate that the drag started from. + * + * @property {Phaser.Signal} onDragStart + */ + onDragStart: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} is actively dragging the Game Object. + * Be warned: This is a high volume Signal. Be careful what you bind to it. + * It is sent six arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The new x coordinate of the Game Object. + * - {number} The new y coordinate of the Game Object. + * - {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. + * - {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. + * + * @property {Phaser.Signal} onDragUpdate + */ + onDragUpdate: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} stops dragging the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onDragStop + */ + onDragStop: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been played. + * You can also listen to {@link Phaser.Animation#onStart} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was started. + * + * @property {Phaser.Signal} onAnimationStart + */ + onAnimationStart: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been stopped (via {@link Phaser.AnimationManager#stop animation.stop()} and the `dispatchComplete` argument has been set. + * You can also listen to {@link Phaser.Animation#onComplete} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was stopped. + * + * @property {Phaser.Signal} onAnimationComplete + */ + onAnimationComplete: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has looped playback. + * You can also listen to {@link Phaser.Animation#onLoop} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that looped. + * + * @property {Phaser.Signal} onAnimationLoop + */ + onAnimationLoop: null + +}; + +Phaser.Events.prototype.constructor = Phaser.Events; + +// Create an auto-create proxy getter and dispatch method for all events. +// The backing property is the same as the event name, prefixed with '_' +// and the dispatch method is the same as the event name postfixed with '$dispatch'. +for (var prop in Phaser.Events.prototype) +{ + if (!Phaser.Events.prototype.hasOwnProperty(prop) || + prop.indexOf('on') !== 0 || + Phaser.Events.prototype[prop] !== null) + { + continue; + } + + (function (prop, backing) { + 'use strict'; + + // The accessor creates a new Signal; and so it should only be used from user-code. + Object.defineProperty(Phaser.Events.prototype, prop, { + get: function () { + return this[backing] || (this[backing] = new Phaser.Signal()); + } + }); + + // The dispatcher will only broadcast on an already-created signal; call this internally. + Phaser.Events.prototype[prop + '$dispatch'] = function () { + return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; + }; + + })(prop, '_' + prop); + +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless +* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. +* +* @class +*/ +Phaser.Component.FixedToCamera = function () {}; + +/** + * The FixedToCamera component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.FixedToCamera.postUpdate = function () { + + if (this.fixedToCamera) + { + 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.Component.FixedToCamera.prototype = { + + /** + * @property {boolean} _fixedToCamera + * @private + */ + _fixedToCamera: false, + + /** + * A Game Object that is "fixed" to the camera is rendered at a given x/y offsets from the top left of the camera. The offsets + * are stored in the `cameraOffset` property, which is initialized with the current object coordinates. + * + * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. + * + * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world + * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times + * regardless where in the world the camera is. + * + * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. + * + * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. + * + * @property {boolean} fixedToCamera + */ + fixedToCamera: { + + get: function () { + + return this._fixedToCamera; + + }, + + set: function (value) { + + if (value) + { + this._fixedToCamera = true; + this.cameraOffset.set(this.x, this.y); + } + else + { + this._fixedToCamera = false; + } + + } + + }, + + /** + * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. + * + * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. + * @property {Phaser.Point} cameraOffset + */ + cameraOffset: new Phaser.Point() + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Health component provides the ability for Game Objects to have a `health` property +* that can be damaged and reset through game code. +* Requires the LifeSpan component. +* +* @class +*/ +Phaser.Component.Health = function () {}; + +Phaser.Component.Health.prototype = { + + /** + * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. + * + * It can be used in combination with the `damage` method or modified directly. + * + * @property {number} health + * @default + */ + health: 1, + + /** + * The Game Objects maximum health value. This works in combination with the `heal` method to ensure + * the health value never exceeds the maximum. + * + * @property {number} maxHealth + * @default + */ + maxHealth: 100, + + /** + * Damages the Game Object. This removes the given amount of health from the `health` property. + * + * If health is taken below or is equal to zero then the `kill` method is called. + * + * @method + * @param {number} amount - The amount to subtract from the current `health` value. + * @return {Phaser.Sprite} This instance. + */ + damage: function (amount) { + + if (this.alive) + { + this.health -= amount; + + if (this.health <= 0) + { + this.kill(); + } + } + + return this; + + }, + + /** + * Sets the health property of the Game Object to the given amount. + * Will never exceed the `maxHealth` value. + * + * @method + * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + setHealth: function (amount) { + + this.health = amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + + return this; + + }, + + /** + * Heal the Game Object. This adds the given amount of health to the `health` property. + * + * @method + * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + heal: function (amount) { + + if (this.alive) + { + this.health += amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InCamera component checks if the Game Object intersects with the Game Camera. +* +* @class +*/ +Phaser.Component.InCamera = function () {}; + +Phaser.Component.InCamera.prototype = { + + /** + * Checks if this Game Objects bounds intersects with the Game Cameras bounds. + * + * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. + * + * An object outside the bounds can be considered for camera culling if it has the AutoCull component. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. +* +* @class +*/ +Phaser.Component.InputEnabled = function () {}; + +Phaser.Component.InputEnabled.prototype = { + + /** + * The Input Handler for this Game Object. + * + * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. + * + * After you have done this, this property will be a reference to the Phaser InputHandler. + * @property {Phaser.InputHandler|null} input + */ + input: null, + + /** + * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created + * for this Game Object and it will then start to process click / touch events and more. + * + * You can then access the Input Handler via `this.input`. + * + * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. + * + * If you set this property to false it will stop the Input Handler from processing any more input events. + * + * If you want to _temporarily_ disable input for a Game Object, then it's better to set + * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. + * You can then toggle this back on as needed. + * + * @property {boolean} inputEnabled + */ + inputEnabled: { + + get: function () { + + return (this.input && this.input.enabled); + + }, + + set: function (value) { + + if (value) + { + if (this.input === null) + { + this.input = new Phaser.InputHandler(this); + this.input.start(); + } + else if (this.input && !this.input.enabled) + { + this.input.start(); + } + } + else + { + if (this.input && this.input.enabled) + { + this.input.stop(); + } + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InWorld component checks if a Game Object is within the Game World Bounds. +* An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. +* If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. +* +* @class +*/ +Phaser.Component.InWorld = function () {}; + +/** + * The InWorld component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.InWorld.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + // Cache the bounds if we need it + if (this.autoCull || this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + + if (this.autoCull) + { + // Won't get rendered but will still get its transform updated + if (this.game.world.camera.view.intersects(this._bounds)) + { + this.renderable = true; + this.game.world.camera.totalInView++; + } + else + { + this.renderable = false; + + if (this.outOfCameraBoundsKill) + { + this.kill(); + return false; + } + } + } + + if (this.checkWorldBounds) + { + // The Sprite is already out of the world bounds, so let's check to see if it has come back again + if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds)) + { + this._outOfBoundsFired = false; + this.events.onEnterBounds$dispatch(this); + } + else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds)) + { + // The Sprite WAS in the screen, but has now left. + this._outOfBoundsFired = true; + this.events.onOutOfBounds$dispatch(this); + + if (this.outOfBoundsKill) + { + this.kill(); + return false; + } + } + } + } + + return true; + +}; + +Phaser.Component.InWorld.prototype = { + + /** + * If this is set to `true` the Game Object checks if it is within the World bounds each frame. + * + * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. + * + * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. + * + * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. + * + * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} checkWorldBounds + * @default + */ + checkWorldBounds: false, + + /** + * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. + * + * @property {boolean} outOfBoundsKill + * @default + */ + outOfBoundsKill: false, + + /** + * If this and the `autoCull` property are both set to `true`, then the `kill` method + * is called as soon as the Game Object leaves the camera bounds. + * + * @property {boolean} outOfCameraBoundsKill + * @default + */ + outOfCameraBoundsKill: false, + + /** + * @property {boolean} _outOfBoundsFired - Internal state var. + * @private + */ + _outOfBoundsFired: false, + + /** + * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. + * + * @property {boolean} inWorld + * @readonly + */ + inWorld: { + + get: function () { + + return this.game.world.bounds.intersects(this.getBounds()); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* LifeSpan Component Features. +* +* @class +*/ +Phaser.Component.LifeSpan = function () {}; + +/** + * The LifeSpan component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.LifeSpan.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.lifespan > 0) + { + this.lifespan -= this.game.time.physicsElapsedMS; + + if (this.lifespan <= 0) + { + this.kill(); + return false; + } + } + + return true; + +}; + +Phaser.Component.LifeSpan.prototype = { + + /** + * A useful flag to control if the Game Object is alive or dead. + * + * This is set automatically by the Health components `damage` method should the object run out of health. + * Or you can toggle it via your game code. + * + * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. + * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. + * @property {boolean} alive + * @default + */ + alive: true, + + /** + * The lifespan allows you to give a Game Object a lifespan in milliseconds. + * + * Once the Game Object is 'born' you can set this to a positive value. + * + * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. + * When it reaches zero it will call the `kill` method. + * + * Very handy for particles, bullets, collectibles, or any other short-lived entity. + * + * @property {number} lifespan + * @default + */ + lifespan: 0, + + /** + * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. + * + * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. + * + * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. + * + * @method + * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. + * @return {PIXI.DisplayObject} This instance. + */ + revive: function (health) { + + if (health === undefined) { health = 100; } + + this.alive = true; + this.exists = true; + this.visible = true; + + if (typeof this.setHealth === 'function') + { + this.setHealth(health); + } + + if (this.events) + { + this.events.onRevived$dispatch(this); + } + + return this; + + }, + + /** + * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. + * + * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. + * + * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, + * it doesn't destroy the object or free it up from memory. + * + * If you don't need this Game Object any more you should call `destroy` instead. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ + kill: function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + if (this.events) + { + this.events.onKilled$dispatch(this); + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. +* +* @class +*/ +Phaser.Component.LoadTexture = function () {}; + +Phaser.Component.LoadTexture.prototype = { + + /** + * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) + * @private + */ + customRender: false, + + /** + * @property {Phaser.Rectangle} _frame - Internal cache var. + * @private + */ + _frame: null, + + /** + * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. + * + * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. + * + * You should only use `loadTexture` if you want to replace the base texture entirely. + * + * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. + * + * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. + * Doing this then sets the key to be the `frame` argument (the frame is set to zero). + * + * This allows you to create sprites using `load.image` during development, and then change them + * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' + * and swapping it to be the key of the atlas data. + * + * Note: You cannot use a RenderTexture as a texture for a TileSprite. + * + * @method + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. + */ + loadTexture: function (key, frame, stopAnimation) { + + if (key === Phaser.PENDING_ATLAS) + { + key = frame; + frame = 0; + } + else + { + frame = frame || 0; + } + + if ((stopAnimation || stopAnimation === undefined) && this.animations) + { + this.animations.stop(); + } + + this.key = key; + this.customRender = false; + var cache = this.game.cache; + + var setFrame = true; + var smoothed = !this.texture.baseTexture.scaleMode; + + if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture) + { + this.key = key.key; + this.setTexture(key); + } + else if (Phaser.BitmapData && key instanceof Phaser.BitmapData) + { + this.customRender = true; + + this.setTexture(key.texture); + + if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA)) + { + setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame); + } + else + { + setFrame = !this.animations.loadFrameData(key.frameData, 0); + } + } + else if (Phaser.Video && key instanceof Phaser.Video) + { + this.customRender = true; + + // This works from a reference, which probably isn't what we need here + var valid = key.texture.valid; + this.setTexture(key.texture); + this.setFrame(key.texture.frame.clone()); + key.onChangeSource.add(this.resizeFrame, this); + this.texture.valid = valid; + } + else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer) + { + // this.customRender = true; + + this.setTexture(PIXI.Texture.fromCanvas(key.canvas)); + } + else if (key instanceof PIXI.Texture) + { + this.setTexture(key); + } + else + { + var img = cache.getImage(key, true); + + this.key = img.key; + this.setTexture(new PIXI.Texture(img.base)); + + if (key === '__default') + { + this.texture.baseTexture.skipRender = true; + } + else + { + this.texture.baseTexture.skipRender = false; + } + + setFrame = !this.animations.loadFrameData(img.frameData, frame); + } + + if (setFrame) + { + this._frame = Phaser.Rectangle.clone(this.texture.frame); + } + + if (!smoothed) + { + this.texture.baseTexture.scaleMode = 1; + } + + }, + + /** + * Sets the texture frame the Game Object uses for rendering. + * + * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. + * + * @method + * @param {Phaser.Frame} frame - The Frame to be used by the texture. + */ + setFrame: function (frame) { + + this._frame = frame; + + this.texture.frame.x = frame.x; + this.texture.frame.y = frame.y; + this.texture.frame.width = frame.width; + this.texture.frame.height = frame.height; + + this.texture.crop.x = frame.x; + this.texture.crop.y = frame.y; + this.texture.crop.width = frame.width; + this.texture.crop.height = frame.height; + + if (frame.trimmed) + { + if (this.texture.trim) + { + this.texture.trim.x = frame.spriteSourceSizeX; + this.texture.trim.y = frame.spriteSourceSizeY; + this.texture.trim.width = frame.sourceSizeW; + this.texture.trim.height = frame.sourceSizeH; + } + else + { + this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH }; + } + + this.texture.width = frame.sourceSizeW; + this.texture.height = frame.sourceSizeH; + this.texture.frame.width = frame.sourceSizeW; + this.texture.frame.height = frame.sourceSizeH; + } + else if (!frame.trimmed && this.texture.trim) + { + this.texture.trim = null; + } + + if (frame.rotated) + { + this.texture.rotated = true; + } + + if (this.cropRect) + { + this.updateCrop(); + } + + this.texture.requiresReTint = true; + + this.texture._updateUvs(); + + if (this.tilingTexture) + { + this.refreshTexture = true; + } + + }, + + /** + * Resizes the Frame dimensions that the Game Object uses for rendering. + * + * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData + * it can be useful to adjust the dimensions directly in this way. + * + * @method + * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. + * @param {integer} width - The new width of the texture. + * @param {integer} height - The new height of the texture. + */ + resizeFrame: function (parent, width, height) { + + this.texture.frame.resize(width, height); + this.texture.setFrame(this.texture.frame); + + }, + + /** + * Resets the texture frame dimensions that the Game Object uses for rendering. + * + * @method + */ + resetFrame: function () { + + if (this._frame) + { + this.setFrame(this._frame); + } + + }, + + /** + * Gets or sets the current frame index of the texture being used to render this Game Object. + * + * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, + * for example: `player.frame = 4`. + * + * If the frame index given doesn't exist it will revert to the first frame found in the texture. + * + * If you are using a texture atlas then you should use the `frameName` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {integer} frame + */ + frame: { + + get: function () { + return this.animations.frame; + }, + + set: function (value) { + this.animations.frame = value; + } + + }, + + /** + * Gets or sets the current frame name of the texture being used to render this Game Object. + * + * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, + * for example: `player.frameName = "idle"`. + * + * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. + * + * If you are using a sprite sheet then you should use the `frame` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {string} frameName + */ + frameName: { + + get: function () { + return this.animations.frameName; + }, + + set: function (value) { + this.animations.frameName = value; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. +* +* @class +*/ +Phaser.Component.Overlap = function () {}; + +Phaser.Component.Overlap.prototype = { + + /** + * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, + * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. + * + * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. + * + * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. + * It should be fine for low-volume testing where physics isn't required. + * + * @method + * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. + * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. + */ + overlap: function (displayObject) { + + return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds()); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The PhysicsBody component manages the Game Objects physics body and physics enabling. +* It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. +* +* @class +*/ +Phaser.Component.PhysicsBody = function () {}; + +/** + * The PhysicsBody component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.fresh && 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.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (this.body) + { + this.body.preUpdate(); + } + + this.fresh = false; + + this.preUpdateChildren(); + + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this._exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + return true; + +}; + +/** + * The PhysicsBody component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.postUpdate = function () { + + if (this.exists && this.body) + { + this.body.postUpdate(); + } + +}; + +Phaser.Component.PhysicsBody.prototype = { + + /** + * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated + * properties and methods via it. + * + * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. + * + * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object + * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. + * + * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. + * + * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, + * so the physics body is centered on the Game Object. + * + * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. + * + * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body + * @default + */ + body: null, + + /** + * The position of the Game Object on the x axis relative to the local coordinates of the parent. + * + * @property {number} x + */ + x: { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + }, + + /** + * The position of the Game Object on the y axis relative to the local coordinates of the parent. + * + * @property {number} y + */ + y: { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Reset component allows a Game Object to be reset and repositioned to a new location. +* +* @class +*/ +Phaser.Component.Reset = function () {}; + +/** +* Resets the Game Object. +* +* This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, +* `visible` and `renderable` to true. +* +* If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. +* +* If this Game Object has a Physics Body it will reset the Body. +* +* @method +* @param {number} x - The x coordinate (in world space) to position the Game Object at. +* @param {number} y - The y coordinate (in world space) to position the Game Object at. +* @param {number} [health=1] - The health to give the Game Object if it has the Health component. +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.Reset.prototype.reset = function (x, y, health) { + + if (health === undefined) { health = 1; } + + this.world.set(x, y); + this.position.set(x, y); + + this.fresh = true; + this.exists = true; + this.visible = true; + this.renderable = true; + + if (this.components.InWorld) + { + this._outOfBoundsFired = false; + } + + if (this.components.LifeSpan) + { + this.alive = true; + this.health = health; + } + + if (this.components.PhysicsBody) + { + if (this.body) + { + this.body.reset(x, y, false, false); + } + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. +* +* @class +*/ +Phaser.Component.ScaleMinMax = function () {}; + +Phaser.Component.ScaleMinMax.prototype = { + + /** + * The callback that will apply any scale limiting to the worldTransform. + * @property {function} transformCallback + */ + transformCallback: null, + + /** + * The context under which `transformCallback` is called. + * @property {object} transformCallbackContext + */ + transformCallbackContext: this, + + /** + * The minimum scale this Game Object will scale down to. + * + * It allows you to prevent a parent from scaling this Game Object lower than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMin + */ + scaleMin: null, + + /** + * The maximum scale this Game Object will scale up to. + * + * It allows you to prevent a parent from scaling this Game Object higher than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMax + */ + scaleMax: null, + + /** + * Adjust scaling limits, if set, to this Game Object. + * + * @method + * @private + * @param {Phaser.Matrix} wt - The updated worldTransform matrix. + */ + checkTransform: function (wt) { + + if (this.scaleMin) + { + if (wt.a < this.scaleMin.x) + { + wt.a = this.scaleMin.x; + } + + if (wt.d < this.scaleMin.y) + { + wt.d = this.scaleMin.y; + } + } + + if (this.scaleMax) + { + if (wt.a > this.scaleMax.x) + { + wt.a = this.scaleMax.x; + } + + if (wt.d > this.scaleMax.y) + { + wt.d = this.scaleMax.y; + } + } + + }, + + /** + * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. + * + * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored + * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. + * + * By setting these values you can carefully control how Game Objects deal with responsive scaling. + * + * If only one parameter is given then that value will be used for both scaleMin and scaleMax: + * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 + * + * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: + * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 + * + * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, + * or pass `null` for the `maxX` and `maxY` parameters. + * + * Call `setScaleMinMax(null)` to clear all previously set values. + * + * @method + * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to. + * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to. + * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to. + * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to. + */ + setScaleMinMax: function (minX, minY, maxX, maxY) { + + if (minY === undefined) + { + // 1 parameter, set all to it + minY = maxX = maxY = minX; + } + else if (maxX === undefined) + { + // 2 parameters, the first is min, the second max + maxX = maxY = minY; + minY = minX; + } + + if (minX === null) + { + this.scaleMin = null; + } + else + { + if (this.scaleMin) + { + this.scaleMin.set(minX, minY); + } + else + { + this.scaleMin = new Phaser.Point(minX, minY); + } + } + + if (maxX === null) + { + this.scaleMax = null; + } + else + { + if (this.scaleMax) + { + this.scaleMax.set(maxX, maxY); + } + else + { + this.scaleMax = new Phaser.Point(maxX, maxY); + } + } + + if (this.scaleMin === null) + { + this.transformCallback = null; + } + else + { + this.transformCallback = this.checkTransform; + this.transformCallbackContext = this; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. +* +* @class +*/ +Phaser.Component.Smoothed = function () {}; + +Phaser.Component.Smoothed.prototype = { + + /** + * Enable or disable texture smoothing for this Game Object. + * + * It only takes effect if the Game Object is using an image based texture. + * + * Smoothing is enabled by default. + * + * @property {boolean} smoothed + */ + smoothed: { + + get: function () { + + return !this.texture.baseTexture.scaleMode; + + }, + + set: function (value) { + + if (value) + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 0; + this.texture.baseTexture.dirty(); + } + } + else + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 1; + this.texture.baseTexture.dirty(); + } + } + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectFactory is a quick way to create many common game objects +* using {@linkcode Phaser.Game#add `game.add`}. +* +* Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group. +* +* @class Phaser.GameObjectFactory +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectFactory = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectFactory.prototype = { + + /** + * Adds an existing display object to the game world. + * + * @method Phaser.GameObjectFactory#existing + * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object. + * @return {any} The child that was added to the World. + */ + existing: function (object) { + + return this.world.add(object); + + }, + + /** + * Weapons provide the ability to easily create a bullet pool and manager. + * + * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. + * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. + * + * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you + * can usually do with a Group, such as move it around the display list, iterate it, etc can be done + * to the bullets Group too. + * + * Bullets can have textures and even animations. You can control the speed at which they are fired, + * the firing rate, the firing angle, and even set things like gravity for them. + * + * @method Phaser.GameObjectFactory#weapon + * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group. + * @param {function} [bulletClass] - The Class of the bullets that are launched by this Weapon. See {@link Phaser.Weapon#bulletClass} + * @returns {Phaser.Weapon} A Weapon instance. + */ + weapon: function (quantity, key, frame, group, bulletClass) { + + var weapon = this.game.plugins.add(Phaser.Weapon); + + if (bulletClass) + { + weapon.bulletClass = bulletClass; + } + + weapon.createBullets(quantity, key, frame, group); + + return weapon; + + }, + + /** + * Create a new `Image` object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * + * It can still rotate, scale, crop and receive input events. + * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectFactory#image + * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Image} The newly created Image object. + */ + image: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Image(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. + * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), + * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. + * + * @method Phaser.GameObjectFactory#sprite + * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Sprite} The newly created Sprite object. + */ + sprite: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Sprite(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Creature Animation object. + * + * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. + * + * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). + * + * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. + * + * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them + * loaded before your Phaser game boots. + * + * See the Phaser custom build process for more details. + * + * @method Phaser.GameObjectFactory#creature + * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Creature} The newly created Creature object. + */ + creature: function (x, y, key, mesh, group) { + + if (group === undefined) { group = this.world; } + + var obj = new Phaser.Creature(this.game, x, y, key, mesh); + + group.add(obj); + + return obj; + + }, + + /** + * Create a tween on a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectFactory#tween + * @param {object} object - Object the tween will be run on. + * @return {Phaser.Tween} The newly created Phaser.Tween object. + */ + tween: function (object) { + + return this.game.tweens.create(object); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectFactory#group + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates + * are automatically given a physics body. + * + * @method Phaser.GameObjectFactory#physicsGroup + * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc. + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.Group} The newly created Group. + */ + physicsGroup: function (physicsBodyType, parent, name, addToStage) { + + return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType); + + }, + + /** + * A SpriteBatch is a really fast version of a Phaser Group built solely for speed. + * Use when you need a lot of sprites or particles all sharing the same texture. + * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. + * + * @method Phaser.GameObjectFactory#spriteBatch + * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. + * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. + * @return {Phaser.SpriteBatch} The newly created Sprite Batch. + */ + spriteBatch: function (parent, name, addToStage) { + + if (parent === undefined) { parent = null; } + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectFactory#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectFactory#tileSprite + * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TileSprite} The newly created TileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); + + }, + + /** + * Creates a new Rope object. + * + * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js + * + * @method Phaser.GameObjectFactory#rope + * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Array} points - An array of {Phaser.Point}. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Rope} The newly created Rope object. + */ + rope: function (x, y, key, frame, points, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Rope(this.game, x, y, key, frame, points)); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectFactory#text + * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {string} [text=''] - The text string that will be displayed. + * @param {object} [style] - The style object containing style attributes like font, font size , etc. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Text(this.game, x, y, text, style)); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectFactory#button + * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] - The function to call when this button is pressed + * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Button} The newly created Button object. + */ + button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectFactory#graphics + * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Graphics(this.game, x, y)); + + }, + + /** + * Create a new Emitter. + * + * A particle emitter can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accordingly. + * + * @method Phaser.GameObjectFactory#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles)); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectFactory#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectFactory#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size)); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectFactory#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {Phaser.Tilemap} The newly created tilemap object. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectFactory#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a Video object. + * + * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. + * + * @method Phaser.GameObjectFactory#video + * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. + * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) + * @return {Phaser.Video} The newly created Video object. + */ + video: function (key, url) { + + return new Phaser.Video(this.game, key, url); + + }, + + /** + * Create a BitmapData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectFactory#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectFactory#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + }, + + /** + * Add a new Plugin into the PluginManager. + * + * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.GameObjectFactory#plugin + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + plugin: function (plugin) { + + return this.game.plugins.add(plugin); + + } + +}; + +Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world. +* The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}. +* +* @class Phaser.GameObjectCreator +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectCreator = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectCreator.prototype = { + + /** + * Create a new Image object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectCreator#image + * @param {number} x - X position of the image. + * @param {number} y - Y position of the image. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Image} the newly created sprite object. + */ + image: function (x, y, key, frame) { + + return new Phaser.Image(this.game, x, y, key, frame); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * @method Phaser.GameObjectCreator#sprite + * @param {number} x - X position of the new sprite. + * @param {number} y - Y position of the new sprite. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Sprite} the newly created sprite object. + */ + sprite: function (x, y, key, frame) { + + return new Phaser.Sprite(this.game, x, y, key, frame); + + }, + + /** + * Create a tween object for a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectCreator#tween + * @param {object} obj - Object the tween will be run on. + * @return {Phaser.Tween} The Tween object. + */ + tween: function (obj) { + + return new Phaser.Tween(obj, this.game, this.game.tweens); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectCreator#group + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * Create a new SpriteBatch. + * + * @method Phaser.GameObjectCreator#spriteBatch + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.SpriteBatch} The newly created group. + */ + spriteBatch: function (parent, name, addToStage) { + + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectCreator#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectCreator#tileSprite + * @param {number} x - The x coordinate (in world space) to position the TileSprite at. + * @param {number} y - The y coordinate (in world space) to position the TileSprite at. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.TileSprite} The newly created tileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame) { + + return new Phaser.TileSprite(this.game, x, y, width, height, key, frame); + + }, + + /** + * Creates a new Rope object. + * + * @method Phaser.GameObjectCreator#rope + * @param {number} x - The x coordinate (in world space) to position the Rope at. + * @param {number} y - The y coordinate (in world space) to position the Rope at. + * @param {number} width - The width of the Rope. + * @param {number} height - The height of the Rope. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.Rope} The newly created rope object. + */ + rope: function (x, y, key, frame, points) { + + return new Phaser.Rope(this.game, x, y, key, frame, points); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectCreator#text + * @param {number} x - X position of the new text object. + * @param {number} y - Y position of the new text object. + * @param {string} text - The actual text that will be written. + * @param {object} style - The style object containing style attributes like font, font size , etc. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style) { + + return new Phaser.Text(this.game, x, y, text, style); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectCreator#button + * @param {number} [x] X position of the new button object. + * @param {number} [y] Y position of the new button object. + * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] The function to call when this button is pressed + * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @return {Phaser.Button} The newly created button object. + */ + 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); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectCreator#graphics + * @param {number} [x=0] - X position of the new graphics object. + * @param {number} [y=0] - Y position of the new graphics object. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y) { + + return new Phaser.Graphics(this.game, x, y); + + }, + + /** + * Creat a new Emitter. + * + * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accorindgly. + * + * @method Phaser.GameObjectCreator#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectCreator#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectCreator#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, align) { + + return new Phaser.BitmapText(this.game, x, y, font, text, size, align); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectCreator#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectCreator#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a BitmpaData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectCreator#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectCreator#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + } + +}; + +Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Sprites are the lifeblood of your game, used for nearly everything visual. +* +* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. +* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), +* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. +* +* @class Phaser.Sprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. If this argument is omitted, the sprite will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Sprite = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.SPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Sprite.prototype.constructor = Phaser.Sprite; + +Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.Sprite +* @return {boolean} True if the Sprite was rendered, otherwise false. +*/ +Phaser.Sprite.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image is a light-weight object you can use to display anything that doesn't need health, physics, or complex position monitoring. +* +* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. +* +* @class Phaser.Image +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. If this argument is omitted, the image will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Image = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.IMAGE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Image.prototype.constructor = Phaser.Image; + +Phaser.Component.Core.install.call(Phaser.Image.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Image.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Image#preUpdate +* @memberof Phaser.Image +*/ +Phaser.Image.prototype.preUpdate = function() { + + if (!this.preUpdateInWorld() || !this.preUpdateLifeSpan()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. +* +* The four states a Button responds to are: +* +* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. +* * 'Out' - when the Pointer that was previously over the Button moves out of it. +* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. +* * 'Up' - when the Pointer that was pressed down on the Button is released again. +* +* A different texture/frame and activation sound can be specified for any of the states. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. +* +* @class Phaser.Button +* @constructor +* @extends Phaser.Image +* @param {Phaser.Game} game Current game instance. +* @param {number} [x=0] - X position of the Button. +* @param {number} [y=0] - Y position of the Button. +* @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button. +* @param {function} [callback] - The function to call when this Button is pressed, receiving `this` (the Button), `pointer`, and `isOver` (see {@link Phaser.Events#onInputUp}.) +* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) { + + x = x || 0; + y = y || 0; + key = key || null; + callback = callback || null; + callbackContext = callbackContext || this; + + Phaser.Image.call(this, game, x, y, key, outFrame); + + /** + * The Phaser Object Type. + * @property {number} type + * @readonly + */ + this.type = Phaser.BUTTON; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * The name or ID of the Over state frame. + * @property {string|integer} onOverFrame + * @private + */ + this._onOverFrame = null; + + /** + * The name or ID of the Out state frame. + * @property {string|integer} onOutFrame + * @private + */ + this._onOutFrame = null; + + /** + * The name or ID of the Down state frame. + * @property {string|integer} onDownFrame + * @private + */ + this._onDownFrame = null; + + /** + * The name or ID of the Up state frame. + * @property {string|integer} onUpFrame + * @private + */ + this._onUpFrame = null; + + /** + * The Sound to be played when this Buttons Over state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound + * @readonly + */ + this.onOverSound = null; + + /** + * The Sound to be played when this Buttons Out state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound + * @readonly + */ + this.onOutSound = null; + + /** + * The Sound to be played when this Buttons Down state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound + * @readonly + */ + this.onDownSound = null; + + /** + * The Sound to be played when this Buttons Up state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound + * @readonly + */ + this.onUpSound = null; + + /** + * The Sound Marker used in conjunction with the onOverSound. + * @property {string} onOverSoundMarker + * @readonly + */ + this.onOverSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onOutSound. + * @property {string} onOutSoundMarker + * @readonly + */ + this.onOutSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onDownSound. + * @property {string} onDownSoundMarker + * @readonly + */ + this.onDownSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onUpSound. + * @property {string} onUpSoundMarker + * @readonly + */ + this.onUpSoundMarker = ''; + + /** + * The Signal (or event) dispatched when this Button is in an Over state. + * @property {Phaser.Signal} onInputOver + */ + this.onInputOver = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Out state. + * @property {Phaser.Signal} onInputOut + */ + this.onInputOut = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Down state. + * @property {Phaser.Signal} onInputDown + */ + this.onInputDown = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Up state. + * @property {Phaser.Signal} onInputUp + */ + this.onInputUp = new Phaser.Signal(); + + /** + * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. + * The frame will still be changed as applicable. + * + * @property {boolean} onOverMouseOnly + * @default + */ + this.onOverMouseOnly = true; + + /** + * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}. + * + * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. + * + * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR + */ + this.justReleasedPreventsOver = Phaser.PointerMode.CONTACT; + + /** + * When true the the texture frame will not be automatically switched on up/down/over/out events. + * @property {boolean} freezeFrames + * @default + */ + this.freezeFrames = false; + + /** + * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". + * + * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control. + * + * @property {boolean|Phaser.PointerMode} forceOut=false + * @default + */ + this.forceOut = false; + + this.inputEnabled = true; + + this.input.start(0, true); + + this.input.useHandCursor = true; + + this.setFrames(overFrame, outFrame, downFrame, upFrame); + + if (callback !== null) + { + this.onInputUp.add(callback, callbackContext); + } + + // Redirect the input events to here so we can handle animation updates, etc + this.events.onInputOver.add(this.onInputOverHandler, this); + this.events.onInputOut.add(this.onInputOutHandler, this); + this.events.onInputDown.add(this.onInputDownHandler, this); + this.events.onInputUp.add(this.onInputUpHandler, this); + +}; + +Phaser.Button.prototype = Object.create(Phaser.Image.prototype); +Phaser.Button.prototype.constructor = Phaser.Button; + +// State constants; local only. These are tied to property names in Phaser.Button. +var STATE_OVER = 'Over'; +var STATE_OUT = 'Out'; +var STATE_DOWN = 'Down'; +var STATE_UP = 'Up'; + +/** +* Clears all of the frames set on this Button. +* +* @method Phaser.Button#clearFrames +*/ +Phaser.Button.prototype.clearFrames = function () { + + this.setFrames(null, null, null, null); + +}; + +/** +* Set the frame name/ID for the given state. +* +* @method Phaser.Button#setStateFrame +* @private +* @param {object} state - See `STATE_*` +* @param {number|string} frame - The number or string representing the frame. +* @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true. +*/ +Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately) +{ + var frameKey = '_on' + state + 'Frame'; + + if (frame !== null) // not null or undefined + { + this[frameKey] = frame; + + if (switchImmediately) + { + this.changeStateFrame(state); + } + } + else + { + this[frameKey] = null; + } + +}; + +/** +* Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen". +* +* @method Phaser.Button#changeStateFrame +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if the frame was assigned a value, possibly the same one it already had. +*/ +Phaser.Button.prototype.changeStateFrame = function (state) { + + if (this.freezeFrames) + { + return false; + } + + var frameKey = '_on' + state + 'Frame'; + var frame = this[frameKey]; + + if (typeof frame === 'string') + { + this.frameName = frame; + return true; + } + else if (typeof frame === 'number') + { + this.frame = frame; + return true; + } + else + { + return false; + } + +}; + +/** +* Used to manually set the frames that will be used for the different states of the Button. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. +* +* @method Phaser.Button#setFrames +* @public +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) { + + this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver()); + this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver()); + this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown()); + this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp()); + +}; + +/** +* Set the sound/marker for the given state. +* +* @method Phaser.Button#setStateSound +* @private +* @param {object} state - See `STATE_*` +* @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound. +* @param {string} [marker=''] - Sound marker. +*/ +Phaser.Button.prototype.setStateSound = function (state, sound, marker) { + + var soundKey = 'on' + state + 'Sound'; + var markerKey = 'on' + state + 'SoundMarker'; + + if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite) + { + this[soundKey] = sound; + this[markerKey] = typeof marker === 'string' ? marker : ''; + } + else + { + this[soundKey] = null; + this[markerKey] = ''; + } + +}; + +/** +* Play the sound for the given state, _if_ the state has a sound assigned. +* +* @method Phaser.Button#playStateSound +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if a sound was played. +*/ +Phaser.Button.prototype.playStateSound = function (state) { + + var soundKey = 'on' + state + 'Sound'; + var sound = this[soundKey]; + + if (sound) + { + var markerKey = 'on' + state + 'SoundMarker'; + var marker = this[markerKey]; + + sound.play(marker); + return true; + } + else + { + return false; + } + +}; + +/** +* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. +* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. +* +* Call this function with no parameters to reset all sounds on this Button. +* +* @method Phaser.Button#setSounds +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound. +* @param {string} [overMarker] - Over Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound. +* @param {string} [downMarker] - Down Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound. +* @param {string} [outMarker] - Out Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound. +* @param {string} [upMarker] - Up Button Sound Marker. +*/ +Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) { + + this.setStateSound(STATE_OVER, overSound, overMarker); + this.setStateSound(STATE_OUT, outSound, outMarker); + this.setStateSound(STATE_DOWN, downSound, downMarker); + this.setStateSound(STATE_UP, upSound, upMarker); + +}; + +/** +* The Sound to be played when a Pointer moves over this Button. +* +* @method Phaser.Button#setOverSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOverSound = function (sound, marker) { + + this.setStateSound(STATE_OVER, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer moves out of this Button. +* +* @method Phaser.Button#setOutSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOutSound = function (sound, marker) { + + this.setStateSound(STATE_OUT, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer presses down on this Button. +* +* @method Phaser.Button#setDownSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setDownSound = function (sound, marker) { + + this.setStateSound(STATE_DOWN, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer has pressed down and is released from this Button. +* +* @method Phaser.Button#setUpSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setUpSound = function (sound, marker) { + + this.setStateSound(STATE_UP, sound, marker); + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOverHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) { + + if (pointer.justReleased() && + (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode) + { + // If the Pointer was only just released then we don't fire an over event + return; + } + + this.changeStateFrame(STATE_OVER); + + if (this.onOverMouseOnly && !pointer.isMouse) + { + return; + } + + this.playStateSound(STATE_OVER); + + if (this.onInputOver) + { + this.onInputOver.dispatch(this, pointer); + } + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOutHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_OUT); + + this.playStateSound(STATE_OUT); + + if (this.onInputOut) + { + this.onInputOut.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputDownHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_DOWN); + + this.playStateSound(STATE_DOWN); + + if (this.onInputDown) + { + this.onInputDown.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputUpHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) { + + this.playStateSound(STATE_UP); + + // Input dispatched early, before state change (but after sound) + if (this.onInputUp) + { + this.onInputUp.dispatch(this, pointer, isOver); + } + + if (this.freezeFrames) + { + return; + } + + if (this.forceOut === true || (this.forceOut & pointer.pointerMode) === pointer.pointerMode) + { + this.changeStateFrame(STATE_OUT); + } + else + { + var changedUp = this.changeStateFrame(STATE_UP); + if (!changedUp) + { + // No Up frame to show.. + if (isOver) + { + this.changeStateFrame(STATE_OVER); + } + else + { + this.changeStateFrame(STATE_OUT); + } + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. +* It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over +* 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled +* Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. +* +* Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. +* +* @class Phaser.SpriteBatch +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. +* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. +*/ +Phaser.SpriteBatch = function (game, parent, name, addToStage) { + + if (parent === undefined || parent === null) { parent = game.world; } + + Phaser.Group.call(this, game, parent, name, addToStage); + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.SPRITEBATCH; + + /** + * @property {Object} fastSpriteBatch - WebGL Batch Shader. + * @private + */ + this.fastSpriteBatch = null; + + /** + * @property {boolean} ready - Internal flag. + * @private + */ + this.ready = false; + +}; + +Phaser.SpriteBatch.prototype = Object.create(Phaser.Group.prototype); + +Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch; + +/** +* Renders the Sprite Batch using the WebGL renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + if (!this.ready) + { + this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(renderSession.gl); + + this.ready = true; + } + + if (this.fastSpriteBatch.gl !== renderSession.gl) + { + this.fastSpriteBatch.setContext(renderSession.gl); + } + + renderSession.spriteBatch.stop(); + + renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader); + + this.fastSpriteBatch.begin(this, renderSession); + this.fastSpriteBatch.render(this); + + renderSession.spriteBatch.start(); + +}; + +/** +* Renders the Sprite Batch using the Canvas renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + var context = renderSession.context; + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + var transform = this.worldTransform; + + var isRotated = true; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + var texture = child.texture; + var frame = texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) + { + // If rotation === 0 we can avoid setTransform + + if (isRotated) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); + isRotated = false; + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5 + renderSession.shakeX) | 0, + ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5 + renderSession.shakeY) | 0, + frame.width * child.scale.x, + frame.height * child.scale.y); + } + else + { + if (!isRotated) + { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + var tx = (childTransform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (childTransform.ty * renderSession.resolution) + renderSession.shakeY; + + // allow for trimming + + if (renderSession.roundPixels) + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx, ty); + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width) + 0.5) | 0, + ((child.anchor.y) * (-frame.height) + 0.5) | 0, + frame.width, + frame.height); + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. +* A single BitmapData can be used as the texture for one or many Images / Sprites. +* So if you need to dynamically create a Sprite texture then they are a good choice. +* +* Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't +* live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy +* in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. +* +* @class Phaser.BitmapData +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string} key - Internal Phaser reference key for the BitmapData. +* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. +*/ +Phaser.BitmapData = function (game, key, width, height, skipPool) { + + if (width === undefined || width === 0) { width = 256; } + if (height === undefined || height === 0) { height = 256; } + if (skipPool === undefined) { skipPool = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the BitmapData in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} width - The width of the BitmapData in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the BitmapData in pixels. + */ + this.height = height; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. + * @default + */ + this.canvas = Phaser.Canvas.create(this, width, height, null, skipPool); + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + * @default + */ + this.context = this.canvas.getContext('2d', { alpha: true }); + + /** + * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context. + */ + this.ctx = this.context; + + /** + * @property {string} smoothProperty - The context property needed for smoothing this Canvas. + */ + this.smoothProperty = (game.renderType === Phaser.CANVAS) ? game.renderer.renderSession.smoothProperty : Phaser.Canvas.getSmoothingPrefix(this.context); + + /** + * @property {ImageData} imageData - The context image data. + * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. + * This property is updated automatically after the first game loop, according to the dirty flag property. + */ + this.imageData = this.context.getImageData(0, 0, width, height); + + /** + * A Uint8ClampedArray view into BitmapData.buffer. + * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) + * @property {Uint8ClampedArray} data + */ + this.data = null; + + if (this.imageData) + { + this.data = this.imageData.data; + } + + /** + * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer. + */ + this.pixels = null; + + /** + * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData. + */ + if (this.data) + { + 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; + } + } + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + this.baseTexture = new PIXI.BaseTexture(this.canvas, null, this.game.resolution); + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering. + */ + this.frameData = new Phaser.FrameData(); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. + * @default + */ + this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData')); + + this.texture.frame = this.textureFrame; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.BITMAPDATA; + + /** + * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} dirty - If dirty this BitmapData will be re-rendered. + */ + this.dirty = false; + + // Aliases + this.cls = this.clear; + + /** + * @property {number} _image - Internal cache var. + * @private + */ + this._image = null; + + /** + * @property {Phaser.Point} _pos - Internal cache var. + * @private + */ + this._pos = new Phaser.Point(); + + /** + * @property {Phaser.Point} _size - Internal cache var. + * @private + */ + this._size = new Phaser.Point(); + + /** + * @property {Phaser.Point} _scale - Internal cache var. + * @private + */ + this._scale = new Phaser.Point(); + + /** + * @property {number} _rotate - Internal cache var. + * @private + */ + this._rotate = 0; + + /** + * @property {object} _alpha - Internal cache var. + * @private + */ + this._alpha = { prev: 1, current: 1 }; + + /** + * @property {Phaser.Point} _anchor - Internal cache var. + * @private + */ + this._anchor = new Phaser.Point(); + + /** + * @property {number} _tempR - Internal cache var. + * @private + */ + this._tempR = 0; + + /** + * @property {number} _tempG - Internal cache var. + * @private + */ + this._tempG = 0; + + /** + * @property {number} _tempB - Internal cache var. + * @private + */ + this._tempB = 0; + + /** + * @property {Phaser.Circle} _circle - Internal cache var. + * @private + */ + this._circle = new Phaser.Circle(); + + /** + * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods. + * @private + */ + this._swapCanvas = undefined; + +}; + +Phaser.BitmapData.prototype = { + + /** + * Shifts the contents of this BitmapData by the distances given. + * + * The image will wrap-around the edges on all sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#move + * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + move: function (x, y, wrap) { + + if (x !== 0) + { + this.moveH(x, wrap); + } + + if (y !== 0) + { + this.moveV(y, wrap); + } + + return this; + + }, + + /** + * Shifts the contents of this BitmapData horizontally. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveH + * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveH: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var h = this.height; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving to the left + var w = this.width - distance; + + // Left-hand chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h); + } + else + { + // Moving to the right + var w = this.width - distance; + + // Right-hand chunk + if (wrap) + { + ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Shifts the contents of this BitmapData vertically. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveV + * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveV: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var w = this.width; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving up + var h = this.height - distance; + + // Top chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h); + } + else + { + // Moving down + var h = this.height - distance; + + // Bottom chunk + if (wrap) + { + ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Updates the given objects so that they use this BitmapData as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.BitmapData#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. + * The source game object is not modified by this operation. + * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. + * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. + * + * @method Phaser.BitmapData#load + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + load: function (source) { + + if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + } + + if (source) + { + this.resize(source.width, source.height); + this.cls(); + } + else + { + return; + } + + this.draw(source); + + this.update(); + + return this; + + }, + + /** + * Clears the BitmapData context using a clearRect. + * + * @method Phaser.BitmapData#cls + */ + + /** + * Clears the BitmapData context using a clearRect. + * + * You can optionally define the area to clear. + * If the arguments are left empty it will clear the entire canvas. + * + * You may need to call BitmapData.update after this in order to clear out the pixel data, + * but Phaser will not do this automatically for you. + * + * @method Phaser.BitmapData#clear + * @param {number} [x=0] - The x coordinate of the top-left of the area to clear. + * @param {number} [y=0] - The y coordinate of the top-left of the area to clear. + * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width. + * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + clear: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + this.context.clearRect(x, y, width, height); + + this.dirty = true; + + return this; + + }, + + /** + * Fills the BitmapData with the given color. + * + * @method Phaser.BitmapData#fill + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} [a=1] - The alpha color value, between 0 and 1. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + fill: function (r, g, b, a) { + + if (a === undefined) { a = 1; } + + this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; + this.context.fillRect(0, 0, this.width, this.height); + this.dirty = true; + + return this; + + }, + + /** + * Creates a new {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image} element by converting this BitmapDatas canvas into a dataURL. + * + * The image is then stored in the {@link Phaser.Cache image Cache} using the key given. + * + * Finally a {@link PIXI.Texture} is created based on the image and returned. + * + * You can apply the texture to a sprite or any other supporting object by using either the + * key or the texture. First call `generateTexture`: + * + * ```javascript + * var texture = bitmapdata.generateTexture('ball'); + * ``` + * + * Then you can either apply the texture to a sprite: + * + * ```javascript + * game.add.sprite(0, 0, texture); + * ``` + * + * or by using the string based key: + * + * ```javascript + * game.add.sprite(0, 0, 'ball'); + * ``` + * + * Most browsers now load the image data asynchronously, so you should use a callback: + * + * ```javascript + * bitmapdata.generateTexture('ball', function (texture) { + * game.add.sprite(0, 0, texture); + * // or + * game.add.sprite(0, 0, 'ball'); + * }); + * ``` + * + * If this BitmapData is available during preload, you can use {@link Phaser.Loader#imageFromBitmapData} instead. + * + * @method Phaser.BitmapData#generateTexture + * @param {string} key - The key which will be used to store the image in the Cache. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {PIXI.Texture|null} The newly generated texture, or `null` if a callback was passed and the texture isn't available yet. + */ + generateTexture: function (key, callback, callbackContext) { + + var cache = this.game.cache; + var image = new Image(); + + if (callback) + { + image.onload = function () { + var obj = cache.addImage(key, '', image); + var texture = new PIXI.Texture(obj.base); + + callback.call(callbackContext || null, texture); + + image.onload = null; + }; + } + + image.src = this.canvas.toDataURL("image/png"); + + if (!callback) + { + var obj = cache.addImage(key, '', image); + + return new PIXI.Texture(obj.base); + } + + return null; + + }, + + /** + * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. + * + * @method Phaser.BitmapData#resize + * @param {integer} width - The new width of the BitmapData. + * @param {integer} height - The new height of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + resize: function (width, height) { + + if (width !== this.width || height !== this.height) + { + this.width = width; + this.height = height; + + this.canvas.width = width; + this.canvas.height = height; + + if (this._swapCanvas !== undefined) + { + this._swapCanvas.width = width; + this._swapCanvas.height = height; + } + + this.baseTexture.width = width; + this.baseTexture.height = height; + + this.textureFrame.width = width; + this.textureFrame.height = height; + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.update(); + this.dirty = true; + } + + return this; + + }, + + /** + * This re-creates the BitmapData.imageData from the current context. + * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. + * If not given the dimensions defaults to the full size of the context. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.BitmapData#update + * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from. + * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from. + * @param {number} [width=1] - The width of the image data area. + * @param {number} [height=1] - The height of the image data area. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + update: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = Math.max(1, this.width); } + if (height === undefined) { height = Math.max(1, this.height); } + + this.imageData = this.context.getImageData(x, y, width, height); + this.data = this.imageData.data; + + 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; + } + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. + * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. + * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. + * The `color` property is an Int32 of the full color. Note the endianess of this will change per system. + * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. + * The callback will also be sent the pixels x and y coordinates respectively. + * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. + * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. + * + * @method Phaser.BitmapData#processPixelRGB + * @param {function} callback - The callback that will be sent each pixel color object to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixelRGB: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = Phaser.Color.createColor(); + var result = { r: 0, g: 0, b: 0, a: 0 }; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel); + + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== false && result !== null && result !== undefined) + { + this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false); + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. + * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. + * Note that the format of the color received will be different depending on if the system is big or little endian. + * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. + * The callback will also be sent the pixels x and y coordinates respectively. + * + * @method Phaser.BitmapData#processPixel + * @param {function} callback - The callback that will be sent each pixel color to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixel: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = 0; + var result = 0; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + pixel = this.getPixel32(tx, ty); + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== pixel) + { + this.pixels[ty * this.width + tx] = result; + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. + * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. + * + * @method Phaser.BitmapData#replaceRGB + * @param {number} r1 - The red color value to be replaced. Between 0 and 255. + * @param {number} g1 - The green color value to be replaced. Between 0 and 255. + * @param {number} b1 - The blue color value to be replaced. Between 0 and 255. + * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255. + * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255. + * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255. + * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255. + * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255. + * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) { + + var sx = 0; + var sy = 0; + var w = this.width; + var h = this.height; + var source = Phaser.Color.packPixel(r1, g1, b1, a1); + + if (region !== undefined && region instanceof Phaser.Rectangle) + { + sx = region.x; + sy = region.y; + w = region.width; + h = region.height; + } + + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + if (this.getPixel32(sx + x, sy + y) === source) + { + this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false); + } + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * + * @method Phaser.BitmapData#setHSL + * @param {number} [h=null] - The hue, in the range 0 - 1. + * @param {number} [s=null] - The saturation, in the range 0 - 1. + * @param {number} [l=null] - The lightness, in the range 0 - 1. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setHSL: function (h, s, l, region) { + + var bHaveH = h || h === 0; + var bHaveS = s || s === 0; + var bHaveL = l || l === 0; + + if (!bHaveH && !bHaveS && !bHaveL) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (bHaveH) + { + pixel.h = h; + } + + if (bHaveS) + { + pixel.s = s; + } + + if (bHaveL) + { + pixel.l = l; + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * Shifting will add the given value onto the current h, s and l values, not replace them. + * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. + * + * @method Phaser.BitmapData#shiftHSL + * @param {number} [h=null] - The amount to shift the hue by. Within [-1, 1]. + * @param {number} [s=null] - The amount to shift the saturation by. Within [-1, 1]. + * @param {number} [l=null] - The amount to shift the lightness by. Within [-1, 1]. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shiftHSL: function (h, s, l, region) { + + if (h === undefined || h === null) { h = false; } + if (s === undefined || s === null) { s = false; } + if (l === undefined || l === null) { l = false; } + + if (!h && !s && !l) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (h) + { + pixel.h = this.game.math.wrap(pixel.h + h, 0, 1); + } + + if (s) + { + pixel.s = this.game.math.clamp(pixel.s + s, 0, 1); + } + + if (l) + { + pixel.l = this.game.math.clamp(pixel.l + l, 0, 1); + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green, blue and alpha values. + * + * @method Phaser.BitmapData#setPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel32: function (x, y, red, green, blue, alpha, immediate) { + + if (immediate === undefined) { immediate = true; } + + if (x >= 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; + } + } + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green and blue values. + * + * @method Phaser.BitmapData#setPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel: function (x, y, red, green, blue, immediate) { + + return this.setPixel32(x, y, red, green, blue, 255, immediate); + + }, + + /** + * Get the color of a specific pixel in the context into a color object. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + getPixel: function (x, y, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var index = ~~(x + (y * this.width)); + + index *= 4; + + out.r = this.data[index]; + out.g = this.data[++index]; + out.b = this.data[++index]; + out.a = this.data[++index]; + + return out; + + }, + + /** + * Get the color of a specific pixel including its alpha value. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. + * + * @method Phaser.BitmapData#getPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @return {number} A native color value integer (format: 0xAARRGGBB) + */ + getPixel32: function (x, y) { + + if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) + { + return this.pixels[y * this.width + x]; + } + + }, + + /** + * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixelRGB + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + getPixelRGB: function (x, y, out, hsl, hsv) { + + return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv); + + }, + + /** + * Gets all the pixels from the region specified by the given Rectangle object. + * + * @method Phaser.BitmapData#getPixels + * @param {Phaser.Rectangle} rect - The Rectangle region to get. + * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property. + */ + getPixels: function (rect) { + + return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); + + }, + + /** + * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). + * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. + * + * The direction parameter controls from which direction it should start the scan: + * + * 0 = top to bottom + * 1 = bottom to top + * 2 = left to right + * 3 = right to left + * + * @method Phaser.BitmapData#getFirstPixel + * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. + * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. + */ + getFirstPixel: function (direction) { + + if (direction === undefined) { direction = 0; } + + var pixel = Phaser.Color.createColor(); + + var x = 0; + var y = 0; + var v = 1; + var scan = false; + + if (direction === 1) + { + v = -1; + y = this.height; + } + else if (direction === 3) + { + v = -1; + x = this.width; + } + + do { + + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel); + + if (direction === 0 || direction === 1) + { + // Top to Bottom / Bottom to Top + x++; + + if (x === this.width) + { + x = 0; + y += v; + + if (y >= this.height || y <= 0) + { + scan = true; + } + } + } + else if (direction === 2 || direction === 3) + { + // Left to Right / Right to Left + y++; + + if (y === this.height) + { + y = 0; + x += v; + + if (x >= this.width || x <= 0) + { + scan = true; + } + } + } + } + while (pixel.a === 0 && !scan); + + pixel.x = x; + pixel.y = y; + + return pixel; + + }, + + /** + * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. + * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. + * + * @method Phaser.BitmapData#getBounds + * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. + * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. + */ + getBounds: function (rect) { + + if (rect === undefined) { rect = new Phaser.Rectangle(); } + + rect.x = this.getFirstPixel(2).x; + + // If we hit this, there's no point scanning any more, the image is empty + if (rect.x === this.width) + { + return rect.setTo(0, 0, 0, 0); + } + + rect.y = this.getFirstPixel(0).y; + rect.width = (this.getFirstPixel(3).x - rect.x) + 1; + rect.height = (this.getFirstPixel(1).y - rect.y) + 1; + + return rect; + + }, + + /** + * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. + * + * @method Phaser.BitmapData#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself. + * + * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn. + * + * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters. + * + * Note that the source image can also be this BitmapData, which can create some interesting effects. + * + * This method has a lot of parameters for maximum control. + * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all. + * + * You may prefer to use `copyTransform` if you're simply trying to draw a Sprite to this BitmapData, + * and don't wish to translate, scale or rotate it from its original values. + * + * @method Phaser.BitmapData#copy + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image. + * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image. + * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width. + * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height. + * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`. + * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`. + * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter. + * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter. + * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters. + * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) { + + if (source === undefined || source === null) { source = this; } + + if (source instanceof Phaser.RenderTexture) + { + source = source.getCanvas(); + } + + this._image = source; + + if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text || source instanceof PIXI.Sprite) + { + // Copy over sprite values + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + this._scale.set(source.scale.x, source.scale.y); + this._anchor.set(source.anchor.x, source.anchor.y); + this._rotate = source.rotation; + this._alpha.current = source.alpha; + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + if (tx === undefined || tx === null) { tx = source.x; } + if (ty === undefined || ty === null) { ty = source.y; } + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + } + else + { + // Reset + this._pos.set(0); + this._scale.set(1); + this._anchor.set(0); + this._rotate = 0; + this._alpha.current = 1; + + if (source instanceof Phaser.BitmapData) + { + this._image = source.canvas; + } + else if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + + if (source === null) + { + return; + } + else + { + this._image = source; + } + } + + this._size.set(this._image.width, this._image.height); + } + + // The source region to copy from + if (x === undefined || x === null) { x = 0; } + if (y === undefined || y === null) { y = 0; } + + // If they set a width/height then we override the frame values with them + if (width) + { + this._size.x = width; + } + + if (height) + { + this._size.y = height; + } + + // The destination region to copy to + if (tx === undefined || tx === null) { tx = x; } + if (ty === undefined || ty === null) { ty = y; } + if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; } + if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; } + + // Rotation - if set this will override any potential Sprite value + if (typeof rotate === 'number') + { + this._rotate = rotate; + } + + // Anchor - if set this will override any potential Sprite value + if (typeof anchorX === 'number') + { + this._anchor.x = anchorX; + } + + if (typeof anchorY === 'number') + { + this._anchor.y = anchorY; + } + + // Scaling - if set this will override any potential Sprite value + if (typeof scaleX === 'number') + { + this._scale.x = scaleX; + } + + if (typeof scaleY === 'number') + { + this._scale.y = scaleY; + } + + // Effects + if (typeof alpha === 'number') + { + this._alpha.current = alpha; + } + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + // Doesn't work fully with children, or nested scale + rotation transforms (see copyTransform) + ctx.translate(tx, ty); + + ctx.scale(this._scale.x, this._scale.y); + + ctx.rotate(this._rotate); + + ctx.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight); + + // Carry on ... + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the + * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. + * It takes the objects tint and scale mode into consideration before drawing. + * + * You can optionally specify Blend Mode and Round Pixels arguments. + * + * @method Phaser.BitmapData#copyTransform + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyTransform: function (source, blendMode, roundPx) { + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (!source.hasOwnProperty('worldTransform') || !source.worldVisible || source.worldAlpha === 0) + { + return this; + } + + var wt = source.worldTransform; + + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + + if (wt.a === 0 || wt.d === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return this; + } + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + var tx = wt.tx; + var ty = wt.ty; + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + ctx[this.smoothProperty] = (source.texture.baseTexture.scaleMode === PIXI.scaleModes.LINEAR); + + ctx.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + + ctx.drawImage(this._image, + this._pos.x, + this._pos.y, + this._size.x, + this._size.y, + -this._size.x * source.anchor.x, + -this._size.y * source.anchor.y, + this._size.x, + this._size.y); + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. + * + * @method Phaser.BitmapData#copyRect + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. + * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image. + * @param {number} x - The destination x coordinate to copy the image to. + * @param {number} y - The destination y coordinate to copy the image to. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyRect: function (source, area, x, y, alpha, blendMode, roundPx) { + + return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx); + + }, + + /** + * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. + * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. + * + * @method Phaser.BitmapData#draw + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData. + * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`. + * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`. + * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`. + * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + draw: function (source, x, y, width, height, blendMode, roundPx) { + + // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here + return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx); + + }, + + /** + * Draws the immediate children of a Phaser.Group to this BitmapData. + * + * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. + * + * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. + * + * @method Phaser.BitmapData#drawGroup + * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawGroup: function (group, blendMode, roundPx) { + + if (group.total > 0) + { + group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx); + } + + return this; + + }, + + /** + * A proxy for drawGroup that handles child iteration for more complex Game Objects. + * + * @method Phaser.BitmapData#drawGroupProxy + * @private + * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + */ + drawGroupProxy: function (child, blendMode, roundPx) { + + if (child.hasOwnProperty('texture')) + { + this.copyTransform(child, blendMode, roundPx); + } + + if (child.type === Phaser.GROUP && child.exists) + { + this.drawGroup(child, blendMode, roundPx); + } + else + { + if (child.hasOwnProperty('children') && child.children.length > 0) + { + for (var i = 0; i < child.children.length; i++) + { + if (child.children[i].exists) + { + this.copyTransform(child.children[i], blendMode, roundPx); + } + } + } + } + + }, + + /** + * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. + * + * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData + * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the + * bounds of the top-level Game Object. + * + * When drawing it will take into account the child's world rotation, scale and alpha values. + * + * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. + * + * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update + * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can + * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. + * + * @method Phaser.BitmapData#drawFull + * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawFull: function (parent, blendMode, roundPx) { + + if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false)) + { + return this; + } + + if (parent.type !== Phaser.GROUP && parent.type !== Phaser.EMITTER && parent.type !== Phaser.BITMAPTEXT) + { + if (parent.type === Phaser.GRAPHICS) + { + var bounds = parent.getBounds(); + this.ctx.save(); + this.ctx.translate(bounds.x, bounds.y); + PIXI.CanvasGraphics.renderGraphics(parent, this.ctx); + this.ctx.restore(); + } + else + { + this.copy(parent, null, null, null, null, parent.worldPosition.x, parent.worldPosition.y, null, null, parent.worldRotation, null, null, parent.worldScale.x, parent.worldScale.y, parent.worldAlpha, blendMode, roundPx); + } + } + + if (parent.children) + { + for (var i = 0; i < parent.children.length; i++) + { + this.drawFull(parent.children[i], blendMode, roundPx); + } + } + + return this; + + }, + + /** + * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. + * You can cancel an existing shadow by calling this method and passing no parameters. + * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. + * + * @method Phaser.BitmapData#shadow + * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. + * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. + * @param {number} [x=10] - The horizontal offset of the shadow in pixels. + * @param {number} [y=10] - The vertical offset of the shadow in pixels. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shadow: function (color, blur, x, y) { + + var ctx = this.context; + + if (color === undefined || color === null) + { + ctx.shadowColor = 'rgba(0,0,0,0)'; + } + else + { + ctx.shadowColor = color; + ctx.shadowBlur = blur || 5; + ctx.shadowOffsetX = x || 10; + ctx.shadowOffsetY = y || 10; + } + + return this; + + }, + + /** + * Draws the image onto this BitmapData using an image as an alpha mask. + * + * @method Phaser.BitmapData#alphaMask + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. + * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. + * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + alphaMask: function (source, mask, sourceRect, maskRect) { + + if (maskRect === undefined || maskRect === null) + { + this.draw(mask).blendSourceAtop(); + } + else + { + this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop(); + } + + if (sourceRect === undefined || sourceRect === null) + { + this.draw(source).blendReset(); + } + else + { + this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset(); + } + + return this; + + }, + + /** + * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. + * The original BitmapData remains unchanged. + * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. + * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: + * `picture.extract(mask, r, g, b)` + * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. + * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint + * the color during extraction. + * + * @method Phaser.BitmapData#extract + * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. + * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied? + * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255. + * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255. + * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255. + * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on. + */ + extract: function (destination, r, g, b, a, resize, r2, g2, b2) { + + if (a === undefined) { a = 255; } + if (resize === undefined) { resize = false; } + if (r2 === undefined) { r2 = r; } + if (g2 === undefined) { g2 = g; } + if (b2 === undefined) { b2 = b; } + + if (resize) + { + destination.resize(this.width, this.height); + } + + this.processPixelRGB( + function (pixel, x, y) + { + if (pixel.r === r && pixel.g === g && pixel.b === b) + { + destination.setPixel32(x, y, r2, g2, b2, a, false); + } + return false; + }, + this); + + destination.context.putImageData(destination.imageData, 0, 0); + destination.dirty = true; + + return destination; + + }, + + /** + * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. + * + * @method Phaser.BitmapData#rect + * @param {number} x - The x coordinate of the top-left of the Rectangle. + * @param {number} y - The y coordinate of the top-left of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + rect: function (x, y, width, height, fillStyle) { + + if (typeof fillStyle !== 'undefined') + { + this.context.fillStyle = fillStyle; + } + + this.context.fillRect(x, y, width, height); + + return this; + + }, + + /** + * Draws text to the BitmapData in the given font and color. + * The default font is 14px Courier, so useful for quickly drawing debug text. + * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. + * + * @method Phaser.BitmapData#text + * @param {string} text - The text to write to the BitmapData. + * @param {number} x - The x coordinate of the top-left of the text string. + * @param {number} y - The y coordinate of the top-left of the text string. + * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can. + * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in. + * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1) + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + text: function (text, x, y, font, color, shadow) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (font === undefined) { font = '14px Courier'; } + if (color === undefined) { color = 'rgb(255,255,255)'; } + if (shadow === undefined) { shadow = true; } + + var ctx = this.context; + var prevFont = ctx.font; + + ctx.font = font; + + if (shadow) + { + ctx.fillStyle = 'rgb(0,0,0)'; + ctx.fillText(text, x + 1, y + 1); + } + + ctx.fillStyle = color; + ctx.fillText(text, x, y); + + ctx.font = prevFont; + + return this; + + }, + + /** + * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. + * + * @method Phaser.BitmapData#circle + * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle. + * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle. + * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + circle: function (x, y, radius, fillStyle) { + + var ctx = this.context; + + if (fillStyle !== undefined) + { + ctx.fillStyle = fillStyle; + } + + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2, false); + ctx.closePath(); + + ctx.fill(); + + return this; + + }, + + /** + * Draws a line between the coordinates given in the color and thickness specified. + * + * @method Phaser.BitmapData#line + * @param {number} x1 - The x coordinate to start the line from. + * @param {number} y1 - The y coordinate to start the line from. + * @param {number} x2 - The x coordinate to draw the line to. + * @param {number} y2 - The y coordinate to draw the line to. + * @param {string} [color='#fff'] - The stroke color that the line will be drawn in. + * @param {number} [width=1] - The line thickness. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + line: function (x1, y1, x2, y2, color, width) { + + if (color === undefined) { color = '#fff'; } + if (width === undefined) { width = 1; } + + var ctx = this.context; + + ctx.beginPath(); + + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); + + ctx.closePath(); + + return this; + + }, + + /** + * Draws a polygon. + * + * @method Phaser.BitmapData#polygon + * @param {object[]} points - An array of {@link Phaser.Point} or point-like objects. + * @param {CanvasGradient|CanvasPattern|string} [fillStyle] - A color, gradient, or pattern. + * @param {number} [lineWidth=0] - The line thickness. + * @param {CanvasGradient|CanvasPattern|string} [strokeStyle='#fff'] - The line color, gradient, or pattern (when `lineWidth` > 0). + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + polygon: function (points, fillStyle, lineWidth, strokeStyle) { + + // Could reject points.length < 3 + + if (strokeStyle === undefined) { strokeStyle = '#fff'; } + if (lineWidth === undefined) { lineWidth = 0; } + + var ctx = this.context; + + if (fillStyle) + { + ctx.fillStyle = fillStyle; + } + + if (lineWidth) + { + ctx.lineWidth = lineWidth; + ctx.strokeStyle = strokeStyle; + } + + ctx.beginPath(); + + ctx.moveTo(points[0].x, points[0].y); + + for (var i = 1, len = points.length; i < len; i++) + { + var point = points[i]; + ctx.lineTo(point.x, point.y); + } + + ctx.closePath(); + + if (fillStyle) { ctx.fill(); } + if (lineWidth) { ctx.stroke(); } + + return this; + + }, + + /** + * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. + * + * @method Phaser.BitmapData#textureLine + * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line. + * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. + * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + textureLine: function (line, image, repeat) { + + if (repeat === undefined) { repeat = 'repeat-x'; } + + if (typeof image === 'string') + { + image = this.game.cache.getImage(image); + + if (!image) + { + return; + } + } + + var width = line.length; + + if (repeat === 'no-repeat' && width > image.width) + { + width = image.width; + } + + var ctx = this.context; + + ctx.fillStyle = ctx.createPattern(image, repeat); + + this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height); + + this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos); + + ctx.save(); + ctx.translate(this._pos.x, this._pos.y); + ctx.rotate(line.angle); + ctx.fillRect(0, 0, width, image.height); + ctx.restore(); + + this.dirty = true; + + return this; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. + * + * @method Phaser.BitmapData#render + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + render: function () { + + if (!this.disableTextureUpload && this.dirty) + { + this.baseTexture.dirty(); + this.dirty = false; + } + + return this; + + }, + + /** + * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. + * + * @method Phaser.BitmapData#destroy + */ + destroy: function () { + + this.frameData.destroy(); + + this.texture.destroy(true); + + Phaser.CanvasPool.remove(this); + + }, + + /** + * Resets the blend mode (effectively sets it to 'source-over') + * + * @method Phaser.BitmapData#blendReset + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendReset: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-over' + * + * @method Phaser.BitmapData#blendSourceOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOver: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-in' + * + * @method Phaser.BitmapData#blendSourceIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceIn: function () { + + this.op = 'source-in'; + return this; + + }, + + /** + * Sets the blend mode to 'source-out' + * + * @method Phaser.BitmapData#blendSourceOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOut: function () { + + this.op = 'source-out'; + return this; + + }, + + /** + * Sets the blend mode to 'source-atop' + * + * @method Phaser.BitmapData#blendSourceAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceAtop: function () { + + this.op = 'source-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-over' + * + * @method Phaser.BitmapData#blendDestinationOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOver: function () { + + this.op = 'destination-over'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-in' + * + * @method Phaser.BitmapData#blendDestinationIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationIn: function () { + + this.op = 'destination-in'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-out' + * + * @method Phaser.BitmapData#blendDestinationOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOut: function () { + + this.op = 'destination-out'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-atop' + * + * @method Phaser.BitmapData#blendDestinationAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationAtop: function () { + + this.op = 'destination-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'xor' + * + * @method Phaser.BitmapData#blendXor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendXor: function () { + + this.op = 'xor'; + return this; + + }, + + /** + * Sets the blend mode to 'lighter' + * + * @method Phaser.BitmapData#blendAdd + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendAdd: function () { + + this.op = 'lighter'; + return this; + + }, + + /** + * Sets the blend mode to 'multiply' + * + * @method Phaser.BitmapData#blendMultiply + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendMultiply: function () { + + this.op = 'multiply'; + return this; + + }, + + /** + * Sets the blend mode to 'screen' + * + * @method Phaser.BitmapData#blendScreen + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendScreen: function () { + + this.op = 'screen'; + return this; + + }, + + /** + * Sets the blend mode to 'overlay' + * + * @method Phaser.BitmapData#blendOverlay + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendOverlay: function () { + + this.op = 'overlay'; + return this; + + }, + + /** + * Sets the blend mode to 'darken' + * + * @method Phaser.BitmapData#blendDarken + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDarken: function () { + + this.op = 'darken'; + return this; + + }, + + /** + * Sets the blend mode to 'lighten' + * + * @method Phaser.BitmapData#blendLighten + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLighten: function () { + + this.op = 'lighten'; + return this; + + }, + + /** + * Sets the blend mode to 'color-dodge' + * + * @method Phaser.BitmapData#blendColorDodge + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorDodge: function () { + + this.op = 'color-dodge'; + return this; + + }, + + /** + * Sets the blend mode to 'color-burn' + * + * @method Phaser.BitmapData#blendColorBurn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorBurn: function () { + + this.op = 'color-burn'; + return this; + + }, + + /** + * Sets the blend mode to 'hard-light' + * + * @method Phaser.BitmapData#blendHardLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHardLight: function () { + + this.op = 'hard-light'; + return this; + + }, + + /** + * Sets the blend mode to 'soft-light' + * + * @method Phaser.BitmapData#blendSoftLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSoftLight: function () { + + this.op = 'soft-light'; + return this; + + }, + + /** + * Sets the blend mode to 'difference' + * + * @method Phaser.BitmapData#blendDifference + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDifference: function () { + + this.op = 'difference'; + return this; + + }, + + /** + * Sets the blend mode to 'exclusion' + * + * @method Phaser.BitmapData#blendExclusion + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendExclusion: function () { + + this.op = 'exclusion'; + return this; + + }, + + /** + * Sets the blend mode to 'hue' + * + * @method Phaser.BitmapData#blendHue + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHue: function () { + + this.op = 'hue'; + return this; + + }, + + /** + * Sets the blend mode to 'saturation' + * + * @method Phaser.BitmapData#blendSaturation + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSaturation: function () { + + this.op = 'saturation'; + return this; + + }, + + /** + * Sets the blend mode to 'color' + * + * @method Phaser.BitmapData#blendColor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColor: function () { + + this.op = 'color'; + return this; + + }, + + /** + * Sets the blend mode to 'luminosity' + * + * @method Phaser.BitmapData#blendLuminosity + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLuminosity: function () { + + this.op = 'luminosity'; + return this; + + }, + + /** + * Updates a portion of the BitmapData from a source Bitmap. + * This optimization is important if calling update() on a large Bitmap is causing performance issues. + * Make sure you use getPixel32() instead of getPixel(). + * This does not work with floating point numbers for x and y. + * + * @method Phaser.BitmapData#copyBitmapData + * @param {Phaser.BitmapData} [source] - The BitmapData you wish to copy. + * @param {number} [x] - The x coordinate of the top-left of the area to copy. + * @param {number} [y] - The y coordinate of the top-left of the area to copy. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyBitmapData: function(source, x, y) { + + source.update(); + for (var i = 0, destRowStart; i < source.height; i++) { + destRowStart = (y + i) * this.width + x; + for (var j = 0; j < source.width; j++) { + this.pixels[destRowStart + j] = source.pixels[i * source.width + j]; + } + } + return this; + + } + +}; + +/** +* @memberof Phaser.BitmapData +* @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", { + + get: function () { + + Phaser.Canvas.getSmoothingEnabled(this.context); + + }, + + set: function (value) { + + Phaser.Canvas.setSmoothingEnabled(this.context, value); + + } + +}); + +/** +* @memberof Phaser.BitmapData +* @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "op", { + + get: function () { + + return this.context.globalCompositeOperation; + + }, + + set: function (value) { + + this.context.globalCompositeOperation = value; + + } + +}); + +/** + * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform. + * + * @method Phaser.BitmapData.getTransform + * @param {number} translateX - The x translate value. + * @param {number} translateY - The y translate value. + * @param {number} scaleX - The scale x value. + * @param {number} scaleY - The scale y value. + * @param {number} skewX - The skew x value. + * @param {number} skewY - The skew y value. + * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms. + */ +Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) { + + if (typeof translateX !== 'number') { translateX = 0; } + if (typeof translateY !== 'number') { translateY = 0; } + if (typeof scaleX !== 'number') { scaleX = 1; } + if (typeof scaleY !== 'number') { scaleY = 1; } + if (typeof skewX !== 'number') { skewX = 0; } + if (typeof skewY !== 'number') { skewY = 0; } + + return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY }; + +}; + +Phaser.BitmapData.prototype.constructor = Phaser.BitmapData; + +/* jshint ignore:start */ + +/* +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ + +/** +* @class EarCut +*/ +Phaser.EarCut = {}; + +Phaser.EarCut.Triangulate = function (data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = Phaser.EarCut.linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = Phaser.EarCut.eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + Phaser.EarCut.earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +}; + +// create a circular doubly linked list from polygon points in the specified winding order + +Phaser.EarCut.linkedList = function (data, start, end, dim, clockwise) { + var sum = 0, + i, j, last; + + // calculate original winding order of a polygon ring + for (i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + + // link points into circular doubly-linked list in the specified winding order + if (clockwise === (sum > 0)) { + for (i = start; i < end; i += dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } + + return last; +}; + +// eliminate colinear or duplicate points + +Phaser.EarCut.filterPoints = function (start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (Phaser.EarCut.equals(p, p.next) || Phaser.EarCut.area(p.prev, p, p.next) === 0)) { + Phaser.EarCut.removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +}; + +// main ear slicing loop which triangulates a polygon (given as a linked list) + +Phaser.EarCut.earcutLinked = function (ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) Phaser.EarCut.indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? Phaser.EarCut.isEarHashed(ear, minX, minY, size) : Phaser.EarCut.isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + Phaser.EarCut.removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + Phaser.EarCut.earcutLinked(Phaser.EarCut.filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = Phaser.EarCut.cureLocalIntersections(ear, triangles, dim); + Phaser.EarCut.earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + Phaser.EarCut.splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +}; + +// check whether a polygon node forms a valid ear with adjacent nodes + +Phaser.EarCut.isEar = function (ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +}; + +Phaser.EarCut.isEarHashed = function (ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = Phaser.EarCut.zOrder(minTX, minTY, minX, minY, size), + maxZ = Phaser.EarCut.zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +}; + +// go through all polygon nodes and cure small local self-intersections + +Phaser.EarCut.cureLocalIntersections = function (start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) + if (Phaser.EarCut.intersects(a, p, p.next, b) && Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + Phaser.EarCut.removeNode(p); + Phaser.EarCut.removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +}; + +// try splitting polygon into two and triangulate them independently + +Phaser.EarCut.splitEarcut = function (start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && Phaser.EarCut.isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = Phaser.EarCut.splitPolygon(a, b); + + // filter colinear points around the cuts + a = Phaser.EarCut.filterPoints(a, a.next); + c = Phaser.EarCut.filterPoints(c, c.next); + + // run earcut on each half + Phaser.EarCut.earcutLinked(a, triangles, dim, minX, minY, size); + Phaser.EarCut.earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +}; + +// link every hole into the outer loop, producing a single-ring polygon without holes + +Phaser.EarCut.eliminateHoles = function (data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = Phaser.EarCut.linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(Phaser.EarCut.getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + Phaser.EarCut.eliminateHole(queue[i], outerNode); + outerNode = Phaser.EarCut.filterPoints(outerNode, outerNode.next); + } + + return outerNode; +}; + +Phaser.EarCut.compareX = function (a, b) { + return a.x - b.x; +}; + +// find a bridge between vertices that connects hole with an outer ring and and link it + +Phaser.EarCut.eliminateHole = function (hole, outerNode) { + outerNode = Phaser.EarCut.findHoleBridge(hole, outerNode); + if (outerNode) { + var b = Phaser.EarCut.splitPolygon(outerNode, hole); + Phaser.EarCut.filterPoints(b, b.next); + } +}; + +// David Eberly's algorithm for finding a bridge between hole and outer polygon + +Phaser.EarCut.findHoleBridge = function (hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hole.x === m.x) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= m.x && + Phaser.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && Phaser.EarCut.locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +}; + +// interlink polygon nodes in z-order + +Phaser.EarCut.indexCurve = function (start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = Phaser.EarCut.zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + Phaser.EarCut.sortLinked(p); +}; + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + +Phaser.EarCut.sortLinked = function (list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +}; + +// z-order of a point given coords and size of the data bounding box + +Phaser.EarCut.zOrder = function (x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +}; + +// find the leftmost node of a polygon ring + +Phaser.EarCut.getLeftmost = function (start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +}; + +// check if a point lies within a convex triangle + +Phaser.EarCut.pointInTriangle = function (ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +}; + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) + +Phaser.EarCut.isValidDiagonal = function (a, b) { + return Phaser.EarCut.equals(a, b) || a.next.i !== b.i && a.prev.i !== b.i && !Phaser.EarCut.intersectsPolygon(a, b) && + Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a) && Phaser.EarCut.middleInside(a, b); +}; + +// signed area of a triangle + +Phaser.EarCut.area = function (p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +}; + +// check if two points are equal + +Phaser.EarCut.equals = function (p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +}; + +// check if two segments intersect + +Phaser.EarCut.intersects = function (p1, q1, p2, q2) { + return Phaser.EarCut.area(p1, q1, p2) > 0 !== Phaser.EarCut.area(p1, q1, q2) > 0 && + Phaser.EarCut.area(p2, q2, p1) > 0 !== Phaser.EarCut.area(p2, q2, q1) > 0; +}; + +// check if a polygon diagonal intersects any polygon segments + +Phaser.EarCut.intersectsPolygon = function (a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + Phaser.EarCut.intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +}; + +// check if a polygon diagonal is locally inside the polygon + +Phaser.EarCut.locallyInside = function (a, b) { + return Phaser.EarCut.area(a.prev, a, a.next) < 0 ? + Phaser.EarCut.area(a, b, a.next) >= 0 && Phaser.EarCut.area(a, a.prev, b) >= 0 : + Phaser.EarCut.area(a, b, a.prev) < 0 || Phaser.EarCut.area(a, a.next, b) < 0; +}; + +// check if the middle point of a polygon diagonal is inside the polygon + +Phaser.EarCut.middleInside = function (a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +}; + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring + +Phaser.EarCut.splitPolygon = function (a, b) { + var a2 = new Phaser.EarCut.Node(a.i, a.x, a.y), + b2 = new Phaser.EarCut.Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +}; + +// create a node and optionally link it with previous one (in a circular doubly linked list) + +Phaser.EarCut.insertNode = function (i, x, y, last) { + var p = new Phaser.EarCut.Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +}; + +Phaser.EarCut.removeNode = function (p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +}; + +Phaser.EarCut.Node = function (i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +}; + +/* jshint ignore:end */ + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used by the webGL renderer to draw the primitive graphics data + * + * @class PIXI.WebGLGraphics + * @private + * @static + */ +PIXI.WebGLGraphics = function() +{ +}; + +/** + * The number of points beyond which Pixi swaps to using the Stencil Buffer to render the Graphics. + * + * @type {number} + */ +PIXI.WebGLGraphics.stencilBufferLimit = 6; + +/** + * Renders the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.renderGraphics + * @param graphics {Graphics} + * @param renderSession {Object} + */ +PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset) +{ + var gl = renderSession.gl; + var projection = renderSession.projection, + offset = renderSession.offset, + shader = renderSession.shaderManager.primitiveShader, + webGLData; + + if(graphics.dirty) + { + PIXI.WebGLGraphics.updateGraphics(graphics, gl); + } + + var webGL = graphics._webGL[gl.id]; + + // if the graphics object does not exist in the webGL context skip rendering! + if(!webGL) + { + return; + } + + // This could be speeded up for sure! + + for (var i = 0; i < webGL.data.length; i++) + { + if(webGL.data[i].mode === 1) + { + webGLData = webGL.data[i]; + + renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession); + + // render quad.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + renderSession.stencilManager.popStencil(graphics, webGLData, renderSession); + } + else + { + webGLData = webGL.data[i]; + + + renderSession.shaderManager.setShader( shader );//activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, 1); + + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + } + } +}; + +/** + * Updates the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.updateGraphics + * @param graphicsData {Graphics} The graphics object to update + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLGraphics.updateGraphics = function(graphics, gl) +{ + // get the contexts graphics object + var webGL = graphics._webGL[gl.id]; + // if the graphics object does not exist in the webGL context time to create it! + if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; + + // flag the graphics as not dirty as we are about to update it... + graphics.dirty = false; + + var i; + + // if the user cleared the graphics object we will need to clear every object + if(graphics.clearDirty) + { + graphics.clearDirty = false; + + // lop through and return all the webGLDatas to the object pool so than can be reused later on + for (i = 0; i < webGL.data.length; i++) + { + var graphicsData = webGL.data[i]; + graphicsData.reset(); + PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData ); + } + + // clear the array and reset the index.. + webGL.data = []; + webGL.lastIndex = 0; + } + + var webGLData; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + if (data.type === Phaser.POLYGON) + { + // need to add the points the the graphics object.. + data.points = data.shape.points.slice(); + if(data.shape.closed) + { + // close the poly if the value is true! + if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { + data.points.push(data.points[0], data.points[1]); + } + } + + // MAKE SURE WE HAVE THE CORRECT TYPE.. + if(data.fill) + { + if(data.points.length >= PIXI.WebGLGraphics.stencilBufferLimit) + { + if(data.points.length < PIXI.WebGLGraphics.stencilBufferLimit * 2) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData); + // console.log(canDrawUsingSimple); + + if(!canDrawUsingSimple) + { + // console.log("<>>>") + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + } + } + + if(data.lineWidth > 0) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + PIXI.WebGLGraphics.buildLine(data, webGLData); + + } + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + if (data.type === Phaser.RECTANGLE) + { + PIXI.WebGLGraphics.buildRectangle(data, webGLData); + } + else if (data.type === Phaser.CIRCLE || data.type === Phaser.ELLIPSE) + { + PIXI.WebGLGraphics.buildCircle(data, webGLData); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData); + } + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (i = 0; i < webGL.data.length; i++) + { + webGLData = webGL.data[i]; + if(webGLData.dirty)webGLData.upload(); + } +}; + +/** + * @static + * @private + * @method PIXI.WebGLGraphics.switchMode + * @param webGL {WebGLContext} + * @param type {Number} + */ +PIXI.WebGLGraphics.switchMode = function(webGL, type) +{ + var webGLData; + + if(!webGL.data.length) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + else + { + webGLData = webGL.data[webGL.data.length-1]; + + if(webGLData.mode !== type || type === 1) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + } + + webGLData.dirty = true; + + return webGLData; +}; + +/** + * Builds a rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData) +{ + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; + + // start + 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); + + // insert 2 dead triangles.. + 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; + } +}; + +/** + * Builds a rounded rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRoundedRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData) +{ + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + recPoints.push(x, y + radius); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); + + if (graphicsData.fill) { + var color = Phaser.Color.hexToRGBArray(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; + + var triangles = Phaser.EarCut.Triangulate(recPoints, null, 2); + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i+1] + vecPos); + indices.push(triangles[i+2] + vecPos); + indices.push(triangles[i+2] + vecPos); + } + + + for (i = 0; i < recPoints.length; i++) + { + verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @static + * @private + * @method PIXI.WebGLGraphics.quadraticBezierCurve + * @param fromX {Number} Origin point x + * @param fromY {Number} Origin point x + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Array(Number)} + */ +PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) { + + var xa, + ya, + xb, + yb, + x, + y, + n = 20, + points = []; + + function getPt(n1 , n2, perc) { + var diff = n2 - n1; + + return n1 + ( diff * perc ); + } + + var j = 0; + for (var i = 0; i <= n; i++ ) + { + j = i / n; + + // The Green Line + xa = getPt( fromX , cpX , j ); + ya = getPt( fromY , cpY , j ); + xb = getPt( cpX , toX , j ); + yb = getPt( cpY , toY , j ); + + // The Black Dot + x = getPt( xa , xb , j ); + y = getPt( ya , yb , j ); + + points.push(x, y); + } + return points; +}; + +/** + * Builds a circle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildCircle + * @param graphicsData {Graphics} The graphics object to draw + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData) +{ + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + + // TODO - bit hacky?? + if (graphicsData.type === Phaser.CIRCLE) + { + width = circleData.radius; + height = circleData.radius; + } + else + { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = 40; + var seg = (Math.PI * 2) / totalSegs ; + + var i = 0; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; i < totalSegs + 1 ; i++) + { + verts.push(x,y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos-1); + } + + if(graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (i = 0; i < totalSegs + 1; i++) + { + graphicsData.points.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height); + } + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Builds a line to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildLine + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData) +{ + // TODO OPTIMISE! + var i = 0; + var points = graphicsData.points; + if(points.length === 0)return; + + // if the line width is an odd number add 0.5 to align to a whole pixel + if(graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) { + points[i] += 0.5; + } + } + + // get first and last point.. figure out the middle! + var firstPoint = new PIXI.Point( points[0], points[1] ); + var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + // if the first point is the last point - gonna have issues :) + if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length/6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var px, py, p1x, p1y, p2x, p2y, p3x, p3y; + var perpx, perpy, perp2x, perp2y, perp3x, perp3y; + var a1, b1, c1, a2, b2, c2; + var denom, pdist, dist; + + p1x = points[0]; + p1y = points[1]; + + p2x = points[2]; + p2y = points[3]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx , p1y - perpy, + r, g, b, alpha); + + verts.push(p1x + perpx , p1y + perpy, + r, g, b, alpha); + + for (i = 1; i < length-1; i++) + { + p1x = points[(i-1)*2]; + p1y = points[(i-1)*2 + 1]; + + p2x = points[(i)*2]; + p2y = points[(i)*2 + 1]; + + p3x = points[(i+1)*2]; + p3y = points[(i+1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + a1 = (-perpy + p1y) - (-perpy + p2y); + b1 = (-perpx + p2x) - (-perpx + p1x); + c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + a2 = (-perp2y + p3y) - (-perp2y + p2y); + b2 = (-perp2x + p2x) - (-perp2x + p3x); + c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + denom = a1*b2 - a2*b1; + + if(Math.abs(denom) < 0.1 ) + { + + denom+=10.1; + verts.push(p2x - perpx , p2y - perpy, + r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy, + r, g, b, alpha); + + continue; + } + + px = (b1*c2 - b2*c1)/denom; + py = (a2*c1 - a1*c2)/denom; + + + pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); + + + if(pdist > 140 * 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 < indexCount; i++) + { + indices.push(indexStart++); + } + + indices.push(indexStart-1); +}; + +/** + * Builds a complex polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildComplexPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData) +{ + //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. + var points = graphicsData.points.slice(); + if(points.length < 6)return; + + // get first and last point.. figure out the middle! + var indices = webGLData.indices; + webGLData.points = points; + webGLData.alpha = graphicsData.fillAlpha; + webGLData.color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + + /* + calclate the bounds.. + */ + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + var x,y; + + // get size.. + for (var i = 0; i < points.length; i+=2) + { + x = points[i]; + y = points[i+1]; + + minX = x < minX ? x : minX; + maxX = x > maxX ? x : maxX; + + minY = y < minY ? y : minY; + maxY = y > maxY ? y : maxY; + } + + // add a quad to the end cos there is no point making another buffer! + points.push(minX, minY, + maxX, minY, + maxX, maxY, + minX, maxY); + + // push a quad onto the end.. + + //TODO - this aint needed! + var length = points.length / 2; + for (i = 0; i < length; i++) + { + indices.push( i ); + } + +}; + +/** + * Builds a polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData) +{ + var points = graphicsData.points; + + if(points.length < 6)return; + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = Phaser.EarCut.Triangulate(points, null, 2); + + if(!triangles)return false; + + var vertPos = verts.length / 6; + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i] + vertPos); + indices.push(triangles[i+1] + vertPos); + indices.push(triangles[i+2] +vertPos); + indices.push(triangles[i+2] + vertPos); + } + + for (i = 0; i < length; i++) + { + verts.push(points[i * 2], points[i * 2 + 1], + r, g, b, alpha); + } + + return true; +}; + +PIXI.WebGLGraphics.graphicsDataPool = []; + +/** + * @class WebGLGraphicsData + * @private + * @static + */ +PIXI.WebGLGraphicsData = function(gl) +{ + this.gl = gl; + + //TODO does this need to be split before uploding?? + this.color = [0,0,0]; // color split! + this.points = []; + this.indices = []; + this.buffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + this.mode = 1; + this.alpha = 1; + this.dirty = true; +}; + +/** + * @method PIXI.WebGLGraphics.reset + */ +PIXI.WebGLGraphicsData.prototype.reset = function() +{ + this.points = []; + this.indices = []; +}; + +/** + * @method PIXI.WebGLGraphics.upload + */ +PIXI.WebGLGraphicsData.prototype.upload = function() +{ + var gl = this.gl; + +// this.lastIndex = graphics.graphicsData.length; + this.glPoints = new Float32Array(this.points); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW); + + this.glIndicies = new Uint16Array(this.indices); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW); + + this.dirty = false; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + +/** + * A set of functions used by the canvas renderer to draw the primitive graphics data. + * + * @class PIXI.CanvasGraphics + * @static + */ +PIXI.CanvasGraphics = function() +{ +}; + +/** + * Renders a {@link Phaser.Graphics} object to a canvas. + * + * @method PIXI.CanvasGraphics.renderGraphics + * @static + * @param graphics {Graphics} the actual graphics object to render + * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas + */ +PIXI.CanvasGraphics.renderGraphics = function(graphics, context) +{ + var worldAlpha = graphics.worldAlpha; + + if (graphics.dirty) + { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === Phaser.POLYGON) + { + context.beginPath(); + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (shape.closed) + { + context.lineTo(points[0], points[1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.RECTANGLE) + { + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ELLIPSE) + { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + context.beginPath(); + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + +}; + +/** + * Renders a graphics mask + * + * @static + * @private + * @method PIXI.CanvasGraphics.renderGraphicsMask + * @param graphics {Graphics} the graphics which will be used as a mask + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + */ +PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context) +{ + var len = graphics.graphicsData.length; + + if (len === 0) + { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === Phaser.POLYGON) + { + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + } + else if (data.type === Phaser.RECTANGLE) + { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } + else if (data.type === Phaser.ELLIPSE) + { + + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } +}; + +PIXI.CanvasGraphics.updateGraphicsTint = function(graphics) +{ + if (graphics.tint === 0xFFFFFF) + { + return; + } + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF)/ 255; + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255); + data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255); + + } + +}; + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + * @param lineWidth {number} the width of the line to draw + * @param lineColor {number} the color of the line to draw + * @param lineAlpha {number} the alpha of the line to draw + * @param fillColor {number} the color of the fill + * @param fillAlpha {number} the alpha of the fill + * @param fill {boolean} whether or not the shape is filled with a colour + * @param shape {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + +Phaser.GraphicsData = function (lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { + + /* + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /* + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /* + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /* + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /* + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /* + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /* + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /* + * @member {boolean} whether or not the shape is filled with a color + */ + this.fill = fill; + + /* + * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + this.shape = shape; + + /* + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + +}; + +Phaser.GraphicsData.prototype.constructor = Phaser.GraphicsData; + +/** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {GraphicsData} + */ +Phaser.GraphicsData.prototype.clone = function () { + + return new Phaser.GraphicsData( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.fill, + this.shape + ); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, +* Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will +* be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: +* +* ```javascript +* graphics.beginFill(0xff0000); +* graphics.drawCircle(50, 50, 100); +* graphics.endFill(); +* ``` +* +* This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. +* +* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or +* WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the +* graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. +* +* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help +* performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. +* You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then +* you should avoid doing this, as it will constantly generate new textures, which will consume memory. +* +* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful +* in their complexity and quantity of them in your game. +* +* @class Phaser.Graphics +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - X position of the new graphics object. +* @param {number} [y=0] - Y position of the new graphics object. +*/ +Phaser.Graphics = function (game, x, y) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.GRAPHICS; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value. + * @private + */ + this.anchor = new Phaser.Point(); + + PIXI.DisplayObjectContainer.call(this); + + this.renderable = true; + + /** + * The alpha value used when filling the Graphics object. + * + * @property fillAlpha + * @type Number + */ + this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @property lineWidth + * @type Number + */ + this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @property lineColor + * @type String + * @default 0 + */ + this.lineColor = 0; + + /** + * Graphics data + * + * @property graphicsData + * @type Array + * @private + */ + this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF (Phaser.Color.WHITE) to reset the tint. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * Current path + * + * @property currentPath + * @type Object + * @private + */ + this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @property _webGL + * @type Array + * @private + */ + this._webGL = []; + + /** + * Whether this shape is being used as a mask. + * + * @property isMask + * @type Boolean + */ + this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @property boundsPadding + * @type Number + */ + this.boundsPadding = 0; + + this._localBounds = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property dirty + * @type Boolean + * @private + */ + this.dirty = true; + + /** + * Used to detect if the bounds have been invalidated, by this Graphics being cleared or drawn to. + * If this is set to true then the updateLocalBounds is called once in the postUpdate method. + * + * @property _boundsDirty + * @type Boolean + * @private + */ + this._boundsDirty = false; + + /** + * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property webGLDirty + * @type Boolean + * @private + */ + this.webGLDirty = false; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @property cachedSpriteDirty + * @type Boolean + * @private + */ + this.cachedSpriteDirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.Graphics.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Graphics.prototype.constructor = Phaser.Graphics; + +Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Graphics#preUpdate +*/ +Phaser.Graphics.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World +* +* @method Phaser.Graphics#postUpdate +*/ +Phaser.Graphics.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this._boundsDirty) + { + this.updateLocalBounds(); + this._boundsDirty = false; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Destroy this Graphics instance. +* +* @method Phaser.Graphics#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Graphics.prototype.destroy = function (destroyChildren) { + + this.clear(); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Draws a single {@link Phaser.Polygon} triangle from a {@link Phaser.Point} array +* +* @method Phaser.Graphics#drawTriangle +* @param {Array} points - An array of Phaser.Points that make up the three vertices of this triangle +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangle = function (points, cull) { + + if (cull === undefined) { cull = false; } + + var triangle = new Phaser.Polygon(points); + + if (cull) + { + var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y); + var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y); + var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y); + var faceNormal = cb.cross(ab); + + if (cameraToFace.dot(faceNormal) > 0) + { + this.drawPolygon(triangle); + } + } + else + { + this.drawPolygon(triangle); + } + +}; + +/** +* Draws {@link Phaser.Polygon} triangles +* +* @method Phaser.Graphics#drawTriangles +* @param {Array|Array} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles +* @param {Array} [indices=null] - An array of numbers that describe what order to draw the vertices in +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) { + + if (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 < vertices.length / 3; i++) + { + this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull); + } + } + else + { + for (i = 0; i < vertices.length / 6; i++) + { + point1.x = vertices[i * 6 + 0]; + point1.y = vertices[i * 6 + 1]; + point2.x = vertices[i * 6 + 2]; + point2.y = vertices[i * 6 + 3]; + point3.x = vertices[i * 6 + 4]; + point3.y = vertices[i * 6 + 5]; + this.drawTriangle([point1, point2, point3], cull); + } + } + } + else + { + if (vertices[0] instanceof Phaser.Point) + { + for (i = 0; i < indices.length /3; i++) + { + points.push(vertices[indices[i * 3 ]]); + points.push(vertices[indices[i * 3 + 1]]); + points.push(vertices[indices[i * 3 + 2]]); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + else + { + for (i = 0; i < indices.length; i++) + { + point1.x = vertices[indices[i] * 2]; + point1.y = vertices[indices[i] * 2 + 1]; + points.push(point1.copyTo({})); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + } +}; + +/** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. + * + * @method Phaser.Graphics#lineStyle + * @param lineWidth {Number} width of the line to draw, will update the objects stored style + * @param color {Number} color of the line to draw, will update the objects stored style + * @param alpha {Number} alpha of the line to draw, will update the objects stored style + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { + + this.lineWidth = lineWidth || 0; + this.lineColor = color || 0; + this.lineAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { + // halfway through a line? start a new one! + this.drawShape(new Phaser.Polygon(this.currentPath.shape.points.slice(-2))); + } + else + { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + +}; + +/** + * Moves the current drawing position to x, y. + * + * @method Phaser.Graphics#moveTo + * @param x {Number} the X coordinate to move to + * @param y {Number} the Y coordinate to move to + * @return {Graphics} + */ +Phaser.Graphics.prototype.moveTo = function (x, y) { + + this.drawShape(new Phaser.Polygon([ x, y ])); + + return this; + +}; + +/** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @method Phaser.Graphics#lineTo + * @param x {Number} the X coordinate to draw to + * @param y {Number} the Y coordinate to draw to + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineTo = function (x, y) { + + if (!this.currentPath) + { + this.moveTo(0, 0); + } + + this.currentPath.shape.points.push(x, y); + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @method Phaser.Graphics#quadraticCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [ 0, 0 ]; + } + } + else + { + this.moveTo(0,0); + } + + var xa, + ya, + n = 20, + points = this.currentPath.shape.points; + + if (points.length === 0) + { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var j = 0; + for (var i = 1; i <= n; ++i) + { + j = i / n; + + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + + points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), + ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a bezier curve and then draws it. + * + * @method Phaser.Graphics#bezierCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param cpX2 {Number} Second Control point x + * @param cpY2 {Number} Second Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + var n = 20, + dt, + dt2, + dt3, + t2, + t3, + points = this.currentPath.shape.points; + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + var j = 0; + + for (var i = 1; i <= n; ++i) + { + j = i / n; + + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, + dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @method Phaser.Graphics#arcTo + * @param x1 {Number} The x-coordinate of the beginning of the arc + * @param y1 {Number} The y-coordinate of the beginning of the arc + * @param x2 {Number} The x-coordinate of the end of the arc + * @param y2 {Number} The y-coordinate of the end of the arc + * @param radius {Number} The radius of the arc + * @return {Graphics} + */ +Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points.push(x1, y1); + } + } + else + { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points, + fromX = points[points.length-2], + fromY = points[points.length-1], + a1 = fromY - y1, + b1 = fromX - x1, + a2 = y2 - y1, + b2 = x2 - x1, + mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { + points.push(x1, y1); + } + } + else + { + var dd = a1 * a1 + b1 * b1, + cc = a2 * a2 + b2 * b2, + tt = a1 * a2 + b1 * b2, + k1 = radius * Math.sqrt(dd) / mm, + k2 = radius * Math.sqrt(cc) / mm, + j1 = k1 * tt / dd, + j2 = k2 * tt / cc, + cx = k1 * b2 + k2 * b1, + cy = k1 * a2 + k2 * a1, + px = b1 * (k2 + j1), + py = a1 * (k2 + j1), + qx = b2 * (k1 + j2), + qy = a2 * (k1 + j2), + startAngle = Math.atan2(py - cy, px - cx), + endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @method Phaser.Graphics#arc + * @param cx {Number} The x-coordinate of the center of the circle + * @param cy {Number} The y-coordinate of the center of the circle + * @param radius {Number} The radius of the circle + * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) + * @param endAngle {Number} The ending angle, in radians + * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. + * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. + * @return {Graphics} + */ +Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise, segments) { + + // If we do this we can never draw a full circle + if (startAngle === endAngle) + { + return this; + } + + if (anticlockwise === undefined) { anticlockwise = false; } + if (segments === undefined) { segments = 40; } + + if (!anticlockwise && endAngle <= startAngle) + { + endAngle += Math.PI * 2; + } + else if (anticlockwise && startAngle <= endAngle) + { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments; + + // Sweep check - moved here because we don't want to do the moveTo below if the arc fails + if (sweep === 0) + { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (anticlockwise && this.filling) + { + this.moveTo(cx, cy); + } + else + { + this.moveTo(startX, startY); + } + + // currentPath will always exist after calling a moveTo + var points = this.currentPath.shape.points; + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = (segMinus % 1) / segMinus; + + for (var i = 0; i <= segMinus; i++) + { + var real = i + remainder * i; + + var angle = ((theta) + startAngle + (theta2 * real)); + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, + ( (cTheta * -s) + (sTheta * c) ) * radius + cy); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @method Phaser.Graphics#beginFill + * @param color {Number} the color of the fill + * @param alpha {Number} the alpha of the fill + * @return {Graphics} + */ +Phaser.Graphics.prototype.beginFill = function (color, alpha) { + + this.filling = true; + this.fillColor = color || 0; + this.fillAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + +}; + +/** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @method Phaser.Graphics#endFill + * @return {Graphics} + */ +Phaser.Graphics.prototype.endFill = function () { + + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRect + * + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawRect = function (x, y, width, height) { + + this.drawShape(new Phaser.Rectangle(x, y, width, height)); + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRoundedRect + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. + */ +Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + + this.drawShape(new Phaser.RoundedRectangle(x, y, width, height, radius)); + + return this; + +}; + +/** + * Draws a circle. + * + * @method Phaser.Graphics#drawCircle + * @param x {Number} The X coordinate of the center of the circle + * @param y {Number} The Y coordinate of the center of the circle + * @param diameter {Number} The diameter of the circle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) { + + this.drawShape(new Phaser.Circle(x, y, diameter)); + + return this; + +}; + +/** + * Draws an ellipse. + * + * @method Phaser.Graphics#drawEllipse + * @param x {Number} The X coordinate of the center of the ellipse + * @param y {Number} The Y coordinate of the center of the ellipse + * @param width {Number} The half width of the ellipse + * @param height {Number} The half height of the ellipse + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawEllipse = function (x, y, width, height) { + + this.drawShape(new Phaser.Ellipse(x, y, width, height)); + + return this; + +}; + +/** + * Draws a polygon using the given path. + * + * @method Phaser.Graphics#drawPolygon + * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawPolygon = function (path) { + + if (path instanceof Phaser.Polygon) + { + path = path.points; + } + + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) + { + points[i] = arguments[i]; + } + } + + this.drawShape(new Phaser.Polygon(points)); + + return this; + +}; + +/** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @method Phaser.Graphics#clear + * @return {Graphics} + */ +Phaser.Graphics.prototype.clear = function () { + + this.lineWidth = 0; + this.filling = false; + + this.dirty = true; + this._boundsDirty = true; + this.clearDirty = true; + this.graphicsData = []; + + this.updateLocalBounds(); + + return this; + +}; + +/** + * Useful function that returns a texture of the graphics object that can then be used to create sprites + * This can be quite useful if your geometry is complicated and needs to be reused multiple times. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * @method Phaser.Graphics#generateTexture + * @param [resolution=1] {Number} The resolution of the texture being generated + * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts + * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0) + * @return {Texture} a texture of the graphics object + */ +Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, padding) { + + if (resolution === undefined) { resolution = 1; } + if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; } + if (padding === undefined) { padding = 0; } + + var bounds = this.getBounds(); + + bounds.width += padding; + bounds.height += padding; + + var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution); + + var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + + canvasBuffer.context.scale(resolution, resolution); + + canvasBuffer.context.translate(-bounds.x, -bounds.y); + + PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context); + + return texture; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Graphics#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderWebGL = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture on the gpu too! + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.worldAlpha = this.worldAlpha; + + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + + return; + } + else + { + renderSession.spriteBatch.stop(); + renderSession.blendModeManager.setBlendMode(this.blendMode); + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + if (this._filters) + { + renderSession.filterManager.pushFilter(this._filterBlock); + } + + // check blend mode + if (this.blendMode !== renderSession.spriteBatch.currentBlendMode) + { + renderSession.spriteBatch.currentBlendMode = this.blendMode; + var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode]; + renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + // check if the webgl graphic needs to be updated + if (this.webGLDirty) + { + this.dirty = true; + this.webGLDirty = false; + } + + PIXI.WebGLGraphics.renderGraphics(this, renderSession); + + // only render if it has children! + if (this.children.length) + { + renderSession.spriteBatch.start(); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + } + + if (this._filters) + { + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + renderSession.maskManager.popMask(this.mask, renderSession); + } + + renderSession.drawCount++; + + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method Phaser.Graphics#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderCanvas = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) + { + this.dirty = true; + this._prevTint = this.tint; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.alpha = this.alpha; + + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + + return; + } + else + { + var context = renderSession.context; + var transform = this.worldTransform; + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + var resolution = renderSession.resolution; + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + tx, + ty); + + PIXI.CanvasGraphics.renderGraphics(this, context); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + } + +}; + +/** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @method Phaser.Graphics#getBounds + * @return {Rectangle} the rectangular bounding area + */ +Phaser.Graphics.prototype.getBounds = function (matrix) { + + if (this._currentBounds) + { + return this._currentBounds; + } + + // Return an empty object if the item is a mask! + if (!this.renderable) + { + return Phaser.EmptyRectangle; + } + + if (this.dirty) + { + this.updateLocalBounds(); + this.webGLDirty = true; + this.cachedSpriteDirty = true; + this.dirty = false; + } + + var bounds = this._localBounds; + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = x1; + var maxY = y1; + + var minX = x1; + var minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + + this._bounds.x = minX; + this._bounds.width = maxX - minX; + + this._bounds.y = minY; + this._bounds.height = maxY - minY; + + this._currentBounds = this._bounds; + + return this._currentBounds; + +}; + +/** + * Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration. + * + * @method Phaser.Graphics#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +Phaser.Graphics.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Tests if a point is inside this graphics object +* +* @param point {Point} the point to test +* @return {boolean} the result of the test +*/ +Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) { + + if (tempPoint === undefined) { tempPoint = new Phaser.Point(); } + + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; i++) + { + var data = graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // only deal with fills.. + if (data.shape) + { + if (data.shape.contains(tempPoint.x, tempPoint.y)) + { + return true; + } + } + } + + return false; + +}; + +/** + * Update the bounds of the object + * + * @method Phaser.Graphics#updateLocalBounds + */ +Phaser.Graphics.prototype.updateLocalBounds = function () { + + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) + { + var shape, points, x, y, w, h; + + for (var i = 0; i < this.graphicsData.length; i++) + { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + shape = data.shape; + + if (type === Phaser.RECTANGLE || type === Phaser.ROUNDEDRECTANGLE) + { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.CIRCLE) + { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.ELLIPSE) + { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else + { + // POLY - assumes points are sequential, not Point objects + points = shape.points; + + for (var j = 0; j < points.length; j++) + { + if (points[j] instanceof Phaser.Point) + { + x = points[j].x; + y = points[j].y; + } + else + { + x = points[j]; + y = points[j + 1]; + + if (j < points.length - 1) + { + j++; + } + } + + minX = x - lineWidth < minX ? x - lineWidth : minX; + maxX = x + lineWidth > maxX ? x + lineWidth : maxX; + + minY = y - lineWidth < minY ? y - lineWidth : minY; + maxY = y + lineWidth > maxY ? y + lineWidth : maxY; + } + } + } + } + else + { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.x = minX - padding; + this._localBounds.width = (maxX - minX) + padding * 2; + + this._localBounds.y = minY - padding; + this._localBounds.height = (maxY - minY) + padding * 2; + +}; + +/** + * Generates the cached sprite when the sprite has cacheAsBitmap = true + * + * @method Phaser.Graphics#_generateCachedSprite + * @private + */ +Phaser.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); + } + + // leverage the anchor to account for the offset of the element + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + // this._cachedSprite.buffer.context.save(); + this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y); + + // make sure we set the alpha of the graphics to 1 for the render.. + this.worldAlpha = 1; + + // now render the graphic.. + PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context); + this._cachedSprite.alpha = this.alpha; + +}; + +/** + * Updates texture size based on canvas size + * + * @method Phaser.Graphics#updateCachedSpriteTexture + * @private + */ +Phaser.Graphics.prototype.updateCachedSpriteTexture = function () { + + var cachedSprite = this._cachedSprite; + var texture = cachedSprite.texture; + var canvas = cachedSprite.buffer.canvas; + + texture.baseTexture.width = canvas.width; + texture.baseTexture.height = canvas.height; + texture.crop.width = texture.frame.width = canvas.width; + texture.crop.height = texture.frame.height = canvas.height; + + cachedSprite._width = canvas.width; + cachedSprite._height = canvas.height; + + // update the dirty base textures + texture.baseTexture.dirty(); + +}; + +/** + * Destroys a previous cached sprite. + * + * @method Phaser.Graphics#destroyCachedSprite + */ +Phaser.Graphics.prototype.destroyCachedSprite = function () { + + this._cachedSprite.texture.destroy(true); + this._cachedSprite = null; + +}; + +/** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @method Phaser.Graphics#drawShape + * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. + * @return {GraphicsData} The generated GraphicsData object. + */ +Phaser.Graphics.prototype.drawShape = function (shape) { + + if (this.currentPath) + { + // check current path! + if (this.currentPath.shape.points.length <= 2) + { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + // Handle mixed-type polygons + if (shape instanceof Phaser.Polygon) + { + shape = shape.clone(); + shape.flatten(); + } + + var data = new Phaser.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === Phaser.POLYGON) + { + data.shape.closed = this.filling; + this.currentPath = data; + } + + this.dirty = true; + this._boundsDirty = true; + + return data; + +}; + +/** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory. + * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas. + * This is not recommended if you are constantly redrawing the graphics element. + * + * @property cacheAsBitmap + * @type Boolean + * @default false + * @private + */ +Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + this._cacheAsBitmap = value; + + if (this._cacheAsBitmap) + { + this._generateCachedSprite(); + } + else + { + this.destroyCachedSprite(); + } + + this.dirty = true; + this.webGLDirty = true; + + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and +* render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. +* +* @class Phaser.RenderTexture +* @constructor +* @extends PIXI.Texture +* @param {Phaser.Game} game - Current game instance. +* @param {number} [width=100] - The width of the render texture. +* @param {number} [height=100] - The height of the render texture. +* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there. +* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts. +* @param {number} [resolution=1] - The resolution of the texture being generated. +*/ +Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution, renderer, textureUnit) { + + if (width === undefined) { width = 100; } + if (height === undefined) { height = 100; } + if (key === undefined) { key = ''; } + if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; } + if (resolution === undefined) { resolution = 1; } + if (renderer === undefined) { renderer = PIXI.defaultRenderer; } + if (textureUnit === undefined) { textureUnit = 0; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the RenderTexture in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RENDERTEXTURE; + + /** + * @property {Phaser.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture. + * @private + */ + this._tempMatrix = new Phaser.Matrix(); + + this.width = width; + this.height = height; + this.resolution = resolution; + + this.frame = new Phaser.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); + + this.crop = this.frame.clone(); + + /** + * The base texture object that this texture uses + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = new PIXI.BaseTexture(); + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + this.baseTexture._glTextures = []; + this.baseTexture.resolution = this.resolution; + + this.baseTexture.scaleMode = scaleMode; + + this.baseTexture.hasLoaded = true; + + PIXI.Texture.call(this, this.baseTexture, this.frame.clone()); + + /** + * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. + * + * @property renderer + * @type CanvasRenderer|WebGLRenderer + */ + this.renderer = renderer; + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + this.baseTexture.textureIndex = textureUnit; + this.baseTexture._dirty[gl.id] = false; + + this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode, textureUnit); + this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; + + this.projection = new Phaser.Point(this.width * 0.5, -this.height * 0.5); + } + else + { + this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution); + this.baseTexture.source = this.textureBuffer.canvas; + } + + /** + * @property valid + * @type Boolean + */ + this.valid = true; + + this.tempMatrix = new Phaser.Matrix(); + + this._updateUvs(); + +}; + +Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype); +Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it takes into account scale and rotation. +* +* If you don't want those then use RenderTexture.renderRawXY instead. +* +* @method Phaser.RenderTexture.prototype.renderXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) { + + displayObject.updateTransform(); + + this._tempMatrix.copyFrom(displayObject.worldTransform); + this._tempMatrix.tx = x; + this._tempMatrix.ty = y; + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it doesn't take into account scale, rotation or translation. +* +* If you need those then use RenderTexture.renderXY instead. +* +* @method Phaser.RenderTexture.prototype.renderRawXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) { + + this._tempMatrix.identity().translate(x, y); + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture. +* +* In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. +* This is now a Matrix allowing you much more control over how the Display Object is rendered. +* If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. +* +* If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either +* pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. +* +* @method Phaser.RenderTexture.prototype.render +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) { + + if (matrix === undefined || matrix === null) + { + this._tempMatrix.copyFrom(displayObject.worldTransform); + } + else + { + this._tempMatrix.copyFrom(matrix); + } + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* Resizes the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.resize +* @param {number} width - The width to resize to. +* @param {number} height - The height to resize to. +* @param {boolean} updateBase - Should the baseTexture.width and height values be resized as well? +*/ +Phaser.RenderTexture.prototype.resize = function (width, height, updateBase) { + + if (width === this.width && height === this.height) + { + return; + } + + this.valid = (width > 0 && height > 0); + + this.width = width; + this.height = height; + this.frame.width = this.crop.width = width * this.resolution; + this.frame.height = this.crop.height = height * this.resolution; + + if (updateBase) + { + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.projection.x = this.width / 2; + this.projection.y = -this.height / 2; + } + + if (!this.valid) + { + return; + } + + this.textureBuffer.resize(this.width, this.height); + +}; + +/** +* Clears the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.clear +*/ +Phaser.RenderTexture.prototype.clear = function () { + + if (!this.valid) + { + return; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + } + + this.textureBuffer.clear(); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderWebGL +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +* @private +*/ +Phaser.RenderTexture.prototype._renderWebGL = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + wt.translate(0, this.projection.y * 2); + + if (matrix) + { + wt.append(matrix); + } + + wt.scale(1, -1); + + // Time to update all the children of the displayObject with the new matrix. + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + // Time for the webGL fun stuff! + var gl = this.renderer.gl; + + gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + + if (clear) + { + this.textureBuffer.clear(); + } + + this.renderer.spriteBatch.dirty = true; + + this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix); + + this.renderer.spriteBatch.dirty = true; + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderCanvas +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +*/ +Phaser.RenderTexture.prototype._renderCanvas = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + + if (matrix) + { + wt.append(matrix); + } + + // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!) + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + if (clear) + { + this.textureBuffer.clear(); + } + + var realResolution = this.renderer.resolution; + + this.renderer.resolution = this.resolution; + + this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix); + + this.renderer.resolution = realResolution; + +}; + +/** +* Will return a HTML Image of the texture +* +* @method Phaser.RenderTexture.prototype.getImage +* @return {Image} +*/ +Phaser.RenderTexture.prototype.getImage = function () { + + var image = new Image(); + image.src = this.getBase64(); + + return image; + +}; + +/** +* Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. +* +* @method Phaser.RenderTexture.prototype.getBase64 +* @return {String} A base64 encoded string of the texture. +*/ +Phaser.RenderTexture.prototype.getBase64 = function () { + + return this.getCanvas().toDataURL(); + +}; + +/** +* Creates a Canvas element, renders this RenderTexture to it and then returns it. +* +* @method Phaser.RenderTexture.prototype.getCanvas +* @return {HTMLCanvasElement} A Canvas element with the texture rendered on. +*/ +Phaser.RenderTexture.prototype.getCanvas = function () { + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + var width = this.textureBuffer.width; + var height = this.textureBuffer.height; + + var webGLPixels = new Uint8Array(4 * width * height); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + var tempCanvas = new PIXI.CanvasBuffer(width, height); + var canvasData = tempCanvas.context.getImageData(0, 0, width, height); + canvasData.data.set(webGLPixels); + + tempCanvas.context.putImageData(canvasData, 0, 0); + + return tempCanvas.canvas; + } + else + { + return this.textureBuffer.canvas; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new game object for displaying Text. +* +* This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. +* Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. +* +* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers. +* +* @class Phaser.Text +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {number} x - X position of the new text object. +* @param {number} y - Y position of the new text object. +* @param {string} text - The actual text that will be written. +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +*/ +Phaser.Text = function (game, x, y, text, style) { + + x = x || 0; + y = y || 0; + + if (text === undefined || text === null) + { + text = ''; + } + else + { + text = text.toString(); + } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.TEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. + * @property {Phaser.Point} padding + */ + this.padding = new Phaser.Point(); + + /** + * The textBounds property allows you to specify a rectangular region upon which text alignment is based. + * See `Text.setTextBounds` for more details. + * @property {Phaser.Rectangle} textBounds + * @readOnly + */ + this.textBounds = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. + */ + this.canvas = Phaser.CanvasPool.create(this); + + /** + * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. + */ + this.context = this.canvas.getContext('2d'); + + /** + * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}. + */ + this.colors = []; + + /** + * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}. + */ + this.strokeColors = []; + + /** + * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}. + */ + this.fontStyles = []; + + /** + * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}. + */ + this.fontWeights = []; + + /** + * Should the linePositionX and Y values be automatically rounded before rendering the Text? + * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. + * @property {boolean} autoRound + * @default + */ + this.autoRound = false; + + /** + * Will this Text object use Basic or Advanced Word Wrapping? + * + * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. + * White space is condensed (e.g., consecutive spaces are replaced with one). + * Lines are trimmed of white space before processing. + * + * It throws an error if wordWrapWidth is less than a single character. + * @property {boolean} useAdvancedWrap + * @default + */ + this.useAdvancedWrap = false; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + * @property {Object} splitRegExp + */ + this.splitRegExp = /(?:\r\n|\r|\n)/; + + + /** The maximum number of characters that can be set. + * @property {number} characterLimitSize + */ + this.characterLimitSize = -1; + + /** The suffix that is applied to truncated text that is longer than the + * characterLimitSize. + * @property {string} characterLimitSuffix + */ + this.characterLimitSuffix = ''; + + /** + * @property {number} _res - Internal canvas resolution var. + * @private + */ + this._res = game.renderer.resolution; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text; + + /** + * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`. + * @private + */ + this._fontComponents = null; + + /** + * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. + * @private + */ + this._lineSpacing = 0; + + /** + * @property {number} _charCount - Internal character counter used by the text coloring. + * @private + */ + this._charCount = 0; + + /** + * @property {number} _width - Internal width var. + * @private + */ + this._width = 0; + + /** + * @property {number} _height - Internal height var. + * @private + */ + this._height = 0; + + Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas)); + + /** + * @property {object} style + * @private + */ + this.style = {}; + + this.setStyle(style || {}); + + if (text !== '') + { + this.updateText(); + } + +}; + +Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Text.prototype.constructor = Phaser.Text; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Text#preUpdate +* @protected +*/ +Phaser.Text.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override this function to handle any special update requirements. +* +* @method Phaser.Text#update +* @protected +*/ +Phaser.Text.prototype.update = function() { + +}; + +/** +* Destroy this Text object, removing it from the group it belongs to. +* +* @method Phaser.Text#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Text.prototype.destroy = function (destroyChildren) { + + this.texture.destroy(true); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. +* The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. +* The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. +* To remove a shadow already in place you can call this method with no parameters set. +* +* @method Phaser.Text#setShadow +* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +* @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. +* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +* @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set). +* @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; } + if (blur === undefined) { blur = 0; } + if (shadowStroke === undefined) { shadowStroke = true; } + if (shadowFill === undefined) { shadowFill = true; } + + this.style.shadowOffsetX = x; + this.style.shadowOffsetY = y; + this.style.shadowColor = color; + this.style.shadowBlur = blur; + this.style.shadowStroke = shadowStroke; + this.style.shadowFill = shadowFill; + this.dirty = true; + + return this; + +}; + +/** +* Set the style of the text by passing a single style object to it. +* +* @method Phaser.Text#setStyle +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +* @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setStyle = function (style, update) { + + if (update === undefined) { update = false; } + + var newStyle = Object.assign({}, style); + newStyle.font = style.font || 'bold 20pt Arial'; + newStyle.backgroundColor = style.backgroundColor || null; + newStyle.fill = style.fill || 'black'; + newStyle.align = (style.align || 'left').toLowerCase(); + newStyle.boundsAlignH = (style.boundsAlignH || 'left').toLowerCase(); + newStyle.boundsAlignV = (style.boundsAlignV || 'top').toLowerCase(); + newStyle.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136 + newStyle.strokeThickness = Number(style.strokeThickness) || 0; + newStyle.wordWrap = style.wordWrap || false; + newStyle.wordWrapWidth = style.wordWrapWidth || 100; + newStyle.maxLines = style.maxLines || 0; + newStyle.shadowOffsetX = style.shadowOffsetX || 0; + newStyle.shadowOffsetY = style.shadowOffsetY || 0; + newStyle.shadowColor = style.shadowColor || 'rgba(0,0,0,0)'; + newStyle.shadowBlur = style.shadowBlur || 0; + newStyle.tabs = style.tabs || 0; + + var components = this.fontToComponents(newStyle.font); + + if (newStyle.fontStyle) + { + components.fontStyle = newStyle.fontStyle; + } + + if (newStyle.fontVariant) + { + components.fontVariant = newStyle.fontVariant; + } + + if (newStyle.fontWeight) + { + components.fontWeight = newStyle.fontWeight; + } + + if (newStyle.fontSize) + { + if (typeof newStyle.fontSize === 'number') + { + newStyle.fontSize = newStyle.fontSize + 'px'; + } + + components.fontSize = newStyle.fontSize; + } + + this._fontComponents = components; + + newStyle.font = this.componentsToFont(this._fontComponents); + + this.style = newStyle; + this.dirty = true; + + if (update) + { + this.updateText(); + } + + return this; + +}; + +/** +* Renders text to the internal canvas. +* +* @method Phaser.Text#updateText +* @private +*/ +Phaser.Text.prototype.updateText = function () { + + this.texture.baseTexture.resolution = this._res; + + this.context.font = this.style.font; + + var outputText = this.text; + + if (this.characterLimitSize > -1 && this.characterLimitSize < outputText.length) { + outputText = this.text.substring(0, this.characterLimitSize) + this.characterLimitSuffix; + } + + if (this.style.wordWrap) + { + outputText = this.runWordWrap(this.text); + } + + // Split text into lines + var lines = outputText.split(this.splitRegExp); + + // Calculate text width + var tabs = this.style.tabs; + var lineWidths = []; + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this.style.font); + + var drawnLines = lines.length; + + if (this.style.maxLines > 0 && this.style.maxLines < lines.length) + { + drawnLines = this.style.maxLines; + } + + this._charCount = 0; + + for (var i = 0; i < drawnLines; i++) + { + if (tabs === 0) + { + // Simple layout (no tabs) + var lineWidth = this.style.strokeThickness + this.padding.x; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(lines[i]); + } + else + { + lineWidth += this.context.measureText(lines[i]).width; + } + + // Adjust for wrapped text + if (this.style.wordWrap) + { + lineWidth -= this.context.measureText(' ').width; + } + } + else + { + // Complex layout (tabs) + var line = lines[i].split(/(?:\t)/); + var lineWidth = this.padding.x + this.style.strokeThickness; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < line.length; c++) + { + var section = 0; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + section = this.measureLine(line[c]); + } + else + { + section = Math.ceil(this.context.measureText(line[c]).width); + } + + if (c > 0) + { + tab += tabs[c - 1]; + } + + lineWidth = tab + section; + } + } + else + { + for (var c = 0; c < line.length; c++) + { + // How far to the next tab? + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(line[c]); + } + else + { + lineWidth += Math.ceil(this.context.measureText(line[c]).width); + } + + var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth; + + lineWidth += diff; + } + } + } + + lineWidths[i] = Math.ceil(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); + } + + this.canvas.width = maxLineWidth * this._res; + + // Calculate text height + var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y; + var height = lineHeight * drawnLines; + var lineSpacing = this._lineSpacing; + + if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight) + { + lineSpacing = -lineHeight; + } + + // Adjust for line spacing + if (lineSpacing !== 0) + { + height += (lineSpacing > 0) ? lineSpacing * lines.length : lineSpacing * (lines.length - 1); + } + + this.canvas.height = height * this._res; + + this.context.scale(this._res, this._res); + + if (navigator.isCocoonJS) + { + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + } + + if (this.style.backgroundColor) + { + this.context.fillStyle = this.style.backgroundColor; + this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); + } + + this.context.fillStyle = this.style.fill; + this.context.font = this.style.font; + this.context.strokeStyle = this.style.stroke; + this.context.textBaseline = 'alphabetic'; + + this.context.lineWidth = this.style.strokeThickness; + this.context.lineCap = 'round'; + this.context.lineJoin = 'round'; + + var linePositionX; + var linePositionY; + + this._charCount = 0; + + // Draw text line by line + for (i = 0; i < drawnLines; i++) + { + // Split the line by + + linePositionX = this.style.strokeThickness / 2; + linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (i > 0) + { + linePositionY += (lineSpacing * i); + } + + if (this.style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (this.style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (this.autoRound) + { + linePositionX = Math.round(linePositionX); + linePositionY = Math.round(linePositionY); + } + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + this.updateLine(lines[i], linePositionX, linePositionY); + } + else + { + if (this.style.stroke && this.style.strokeThickness) + { + this.updateShadow(this.style.shadowStroke); + + if (tabs === 0) + { + this.context.strokeText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, false); + } + } + + if (this.style.fill) + { + this.updateShadow(this.style.shadowFill); + + if (tabs === 0) + { + this.context.fillText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, true); + } + } + } + } + + this.updateTexture(); + + this.dirty = false; + +}; + +/** +* Renders a line of text that contains tab characters if Text.tab > 0. +* Called automatically by updateText. +* +* @method Phaser.Text#renderTabLine +* @private +* @param {string} line - The line of text to render. +* @param {integer} x - The x position to start rendering from. +* @param {integer} y - The y position to start rendering from. +* @param {boolean} fill - If true uses fillText, if false uses strokeText. +*/ +Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) { + + var text = line.split(/(?:\t)/); + var tabs = this.style.tabs; + var snap = 0; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < text.length; c++) + { + if (c > 0) + { + tab += tabs[c - 1]; + } + + snap = x + tab; + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + } + } + else + { + for (var c = 0; c < text.length; c++) + { + var section = Math.ceil(this.context.measureText(text[c]).width); + + // How far to the next tab? + snap = this.game.math.snapToCeil(x, tabs); + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + + x = snap + section; + } + } + +}; + +/** +* Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. +* This is called automatically by Text.updateText. +* +* @method Phaser.Text#updateShadow +* @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero. +*/ +Phaser.Text.prototype.updateShadow = function (state) { + + if (state) + { + this.context.shadowOffsetX = this.style.shadowOffsetX; + this.context.shadowOffsetY = this.style.shadowOffsetY; + this.context.shadowColor = this.style.shadowColor; + this.context.shadowBlur = this.style.shadowBlur; + } + else + { + this.context.shadowOffsetX = 0; + this.context.shadowOffsetY = 0; + this.context.shadowColor = 0; + this.context.shadowBlur = 0; + } + +}; + +/** +* Measures a line of text character by character taking into the account the specified character styles. +* +* @method Phaser.Text#measureLine +* @private +* @param {string} line - The line of text to measure. +* @return {integer} length of the line. +*/ +Phaser.Text.prototype.measureLine = function (line) { + + var lineLength = 0; + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + } + + lineLength += this.context.measureText(letter).width; + + this._charCount++; + } + + return Math.ceil(lineLength); +}; + +/** +* Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable. +* +* @method Phaser.Text#updateLine +* @private +*/ +Phaser.Text.prototype.updateLine = function (line, x, y) { + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + this.context.strokeText(letter, x, y); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + this.context.fillText(letter, x, y); + } + + x += this.context.measureText(letter).width; + + this._charCount++; + } + +}; + +/** +* Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. +* +* @method Phaser.Text#clearColors +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearColors = function () { + + this.colors = []; + this.strokeColors = []; + this.dirty = true; + + return this; + +}; + +/** +* Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. +* +* @method Phaser.Text#clearFontValues +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearFontValues = function () { + + this.fontStyles = []; + this.fontWeights = []; + this.dirty = true; + + return this; + +}; + +/** +* Set specific colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* If you wish to change the stroke color see addStrokeColor instead. +* +* @method Phaser.Text#addColor +* @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addColor = function (color, position) { + + this.colors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific stroke colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* This has no effect if stroke is disabled or has a thickness of 0. +* +* If you wish to change the text fill color see addColor instead. +* +* @method Phaser.Text#addStrokeColor +* @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addStrokeColor = function (color, position) { + + this.strokeColors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font styles for certain characters within the Text. +* +* It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. +* The position value is the index of the character in the Text string to start applying this font style to. +* Once set the font style remains in use until either another font style or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. +* +* If you wish to change the text font weight see addFontWeight instead. +* +* @method Phaser.Text#addFontStyle +* @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. +* @param {number} position - The index of the character in the string to start applying this font style value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontStyle = function (style, position) { + + this.fontStyles[position] = style; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font weights for certain characters within the Text. +* +* It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. +* The position value is the index of the character in the Text string to start applying this font weight to. +* Once set the font weight remains in use until either another font weight or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. +* +* If you wish to change the text font style see addFontStyle instead. +* +* @method Phaser.Text#addFontWeight +* @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. +* @param {number} position - The index of the character in the string to start applying this font weight value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontWeight = function (weight, position) { + + this.fontWeights[position] = weight; + this.dirty = true; + + return this; + +}; + +/** +* Runs the given text through the Text.runWordWrap function and returns +* the results as an array, where each element of the array corresponds to a wrapped +* line of text. +* +* Useful if you wish to control pagination on long pieces of content. +* +* @method Phaser.Text#precalculateWordWrap +* @param {string} text - The text for which the wrapping will be calculated. +* @return {array} An array of strings with the pieces of wrapped text. +*/ +Phaser.Text.prototype.precalculateWordWrap = function (text) { + + this.texture.baseTexture.resolution = this._res; + this.context.font = this.style.font; + + var wrappedLines = this.runWordWrap(text); + + return wrappedLines.split(/(?:\r\n|\r|\n)/); + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#runWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.runWordWrap = function (text) { + + if (this.useAdvancedWrap) + { + return this.advancedWordWrap(text); + } + else + { + return this.basicWordWrap(text); + } + +}; + +/** +* Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* White space is condensed (e.g., consecutive spaces are replaced with one). +* Lines are trimmed of white space before processing. +* Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character. +* +* @method Phaser.Text#advancedWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.advancedWordWrap = function (text) { + + var context = this.context; + var wordWrapWidth = this.style.wordWrapWidth; + + var output = ''; + + // (1) condense whitespace + // (2) split into lines + var lines = text + .replace(/ +/gi, ' ') + .split(/\r?\n/gi); + + var linesCount = lines.length; + + for (var i = 0; i < linesCount; i++) + { + var line = lines[i]; + var out = ''; + + // trim whitespace + line = line.replace(/^ *|\s*$/gi, ''); + + // if entire line is less than wordWrapWidth + // append the entire line and exit early + var lineWidth = context.measureText(line).width; + + if (lineWidth < wordWrapWidth) + { + output += line + '\n'; + continue; + } + + // otherwise, calculate new lines + var currentLineWidth = wordWrapWidth; + + // split into words + var words = line.split(' '); + + for (var j = 0; j < words.length; j++) + { + var word = words[j]; + var wordWithSpace = word + ' '; + var wordWidth = context.measureText(wordWithSpace).width; + + if (wordWidth > currentLineWidth) + { + // break word + if (j === 0) + { + // shave off letters from word until it's small enough + var newWord = wordWithSpace; + + while (newWord.length) + { + newWord = newWord.slice(0, -1); + wordWidth = context.measureText(newWord).width; + + if (wordWidth <= currentLineWidth) + { + break; + } + } + + // if wordWrapWidth is too small for even a single + // letter, shame user failure with a fatal error + if (!newWord.length) + { + throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); + } + + // replace current word in array with remainder + var secondPart = word.substr(newWord.length); + + words[j] = secondPart; + + // append first piece to output + out += newWord; + } + + // if existing word length is 0, don't include it + var offset = (words[j].length) ? j : j + 1; + + // collapse rest of sentence + var remainder = words.slice(offset).join(' ') + // remove any trailing white space + .replace(/[ \n]*$/gi, ''); + + // prepend remainder to next line + lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); + linesCount = lines.length; + + break; // processing on this line + + // append word with space to output + } + else + { + out += wordWithSpace; + currentLineWidth -= wordWidth; + } + } + + // append processed line to output + output += out.replace(/[ \n]*$/gi, '') + '\n'; + } + + // trim the end of the string + output = output.replace(/[\s|\n]*$/gi, ''); + + return output; + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#basicWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.basicWordWrap = function (text) { + + var result = ''; + var lines = text.split('\n'); + + for (var i = 0; i < lines.length; i++) + { + var spaceLeft = this.style.wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) + { + var wordWidth = this.context.measureText(words[j]).width; + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is greater than the word wrap width. + if (j > 0) + { + result += '\n'; + } + result += words[j] + ' '; + spaceLeft = this.style.wordWrapWidth - wordWidth; + } + else + { + spaceLeft -= wordWidthWithSpace; + result += words[j] + ' '; + } + } + + if (i < lines.length-1) + { + result += '\n'; + } + } + + return result; + +}; + +/** +* Updates the internal `style.font` if it now differs according to generation from components. +* +* @method Phaser.Text#updateFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.updateFont = function (components) { + + var font = this.componentsToFont(components); + + if (this.style.font !== font) + { + this.style.font = font; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + +}; + +/** +* Converting a short CSS-font string into the relevant components. +* +* @method Phaser.Text#fontToComponents +* @private +* @param {string} font - a CSS font string +*/ +Phaser.Text.prototype.fontToComponents = function (font) { + + // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand: + // style - normal | italic | oblique | inherit + // variant - normal | small-caps | inherit + // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit + // size - xx-small | x-small | small | medium | large | x-large | xx-large, + // larger | smaller + // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %) + // font-family - rest (but identifiers or quoted with comma separation) + var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/); + + if (m) + { + var family = m[5].trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(family) && !/['",]/.exec(family)) + { + family = "'" + family + "'"; + } + + return { + font: font, + fontStyle: m[1] || 'normal', + fontVariant: m[2] || 'normal', + fontWeight: m[3] || 'normal', + fontSize: m[4] || 'medium', + fontFamily: family + }; + } + else + { + console.warn("Phaser.Text - unparsable CSS font: " + font); + + return { + font: font + }; + } + +}; + +/** +* Converts individual font components (see `fontToComponents`) to a short CSS font string. +* +* @method Phaser.Text#componentsToFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.componentsToFont = function (components) { + + var parts = []; + var v; + + v = components.fontStyle; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontVariant; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontWeight; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontSize; + if (v && v !== 'medium') { parts.push(v); } + + v = components.fontFamily; + if (v) { parts.push(v); } + + if (!parts.length) + { + // Fallback to whatever value the 'font' was + parts.push(components.font); + } + + return parts.join(" "); + +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* Use the optional `immediate` argument if you need the Text display to update immediately. +* +* If not it will re-create the texture of this Text object during the next time the render +* loop is called. +* +* @method Phaser.Text#setText +* @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present. +* @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setText = function (text, immediate) { + + if (immediate === undefined) { immediate = false; } + + this.text = text.toString() || ''; + + if (immediate) + { + this.updateText(); + } + else + { + this.dirty = true; + } + + return this; + +}; + +/** + * Converts the given array into a tab delimited string and then updates this Text object. + * This is mostly used when you want to display external data using tab stops. + * + * The array can be either single or multi dimensional depending on the result you need: + * + * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`. + * + * Where as: + * + * `[ + * [ 'a', 'b', 'c' ], + * [ 'd', 'e', 'f'] + * ]` + * + * would convert in to: `"a\tb\tc\nd\te\tf"` + * + * @method Phaser.Text#parseList + * @param {array} list - The array of data to convert into a string. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.parseList = function (list) { + + if (!Array.isArray(list)) + { + return this; + } + else + { + var s = ""; + + for (var i = 0; i < list.length; i++) + { + if (Array.isArray(list[i])) + { + s += list[i].join("\t"); + + if (i < list.length - 1) + { + s += "\n"; + } + } + else + { + s += list[i]; + + if (i < list.length - 1) + { + s += "\t"; + } + } + } + } + + this.text = s; + this.dirty = true; + + return this; + +}; + +/** + * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned, + * regardless of the number of lines in the text, the font size or any other attribute. + * + * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly + * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment. + * + * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to + * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of + * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center + * of the text bounds. + * + * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions + * may vary based on font (say for multi-lingual games). + * + * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width. + * + * Call this method with no arguments given to reset an existing textBounds. + * + * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts + * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot` + * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then + * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot. + * + * @method Phaser.Text#setTextBounds + * @param {number} [x] - The x coordinate of the Text Bounds region. + * @param {number} [y] - The y coordinate of the Text Bounds region. + * @param {number} [width] - The width of the Text Bounds region. + * @param {number} [height] - The height of the Text Bounds region. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.setTextBounds = function (x, y, width, height) { + + if (x === undefined) + { + this.textBounds = null; + } + else + { + if (!this.textBounds) + { + this.textBounds = new Phaser.Rectangle(x, y, width, height); + } + else + { + this.textBounds.setTo(x, y, width, height); + } + + if (this.style.wordWrapWidth > width) + { + this.style.wordWrapWidth = width; + } + } + + this.updateTexture(); + + return this; + +}; + +/** + * Updates the texture based on the canvas dimensions. + * + * @method Phaser.Text#updateTexture + * @private + */ +Phaser.Text.prototype.updateTexture = function () { + + var base = this.texture.baseTexture; + var crop = this.texture.crop; + var frame = this.texture.frame; + + var w = this.canvas.width; + var h = this.canvas.height; + + base.width = w; + base.height = h; + + crop.width = w; + crop.height = h; + + frame.width = w; + frame.height = h; + + this.texture.width = w; + this.texture.height = h; + + this._width = w; + this._height = h; + + if (this.textBounds) + { + var x = this.textBounds.x; + var y = this.textBounds.y; + + // Align the canvas based on the bounds + if (this.style.boundsAlignH === 'right') + { + x += this.textBounds.width - this.canvas.width / this.resolution; + } + else if (this.style.boundsAlignH === 'center') + { + x += this.textBounds.halfWidth - (this.canvas.width / this.resolution / 2); + } + + if (this.style.boundsAlignV === 'bottom') + { + y += this.textBounds.height - this.canvas.height / this.resolution; + } + else if (this.style.boundsAlignV === 'middle') + { + y += this.textBounds.halfHeight - (this.canvas.height / this.resolution / 2); + } + + this.pivot.x = -x; + this.pivot.y = -y; + } + + // Can't render something with a zero sized dimension + this.renderable = (w !== 0 && h !== 0); + + this.texture.requiresReTint = true; + + this.texture.baseTexture.dirty(); + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Text#_renderWebGL +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderWebGL = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Renders the object using the Canvas renderer. +* +* @method Phaser.Text#_renderCanvas +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderCanvas = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Calculates the ascent, descent and fontSize of a given font style. +* +* @method Phaser.Text#determineFontProperties +* @private +* @param {object} fontStyle +*/ +Phaser.Text.prototype.determineFontProperties = function (fontStyle) { + + var properties = Phaser.Text.fontPropertiesCache[fontStyle]; + + if (!properties) + { + properties = {}; + + var canvas = Phaser.Text.fontPropertiesCanvas; + var context = Phaser.Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('|MÉq').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + if (!context.getImageData(0, 0, width, height)) + { + properties.ascent = baseline; + properties.descent = baseline + 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + } + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i, j; + + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + properties.descent = i - baseline; + //TODO might need a tweak. kind of a temp fix! + properties.descent += 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; + +}; + +/** +* Returns the bounds of the Text as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Text#getBounds +* @param {Phaser.Matrix} matrix - The transformation matrix of the Text. +* @return {Phaser.Rectangle} The framing rectangle +*/ +Phaser.Text.prototype.getBounds = function (matrix) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return PIXI.Sprite.prototype.getBounds.call(this, matrix); + +}; + +/** +* Sets the character limit of the text, with a suffix. +* If the text is longer than this limit, it is truncated and the suffix is appended. +* +* @method Phaser.Text#setCharacterLimit +* @param {number} [characterLimit] - The x coordinate of the Text Bounds region. +* @param {string} [suffix] - The suffix to append to the truncated text. +*/ +Phaser.Text.prototype.setCharacterLimit = function (characterLimit, suffix) { + + this.characterLimitSuffix = (suffix === undefined) ? '' : suffix; + this.characterLimitSize = characterLimit; + + this.updateText(); +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* @name Phaser.Text#text +* @property {string} text +*/ +Object.defineProperty(Phaser.Text.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* Change the font used. +* +* This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except +* that unlike using `setStyle` this will not change any current font fill/color settings. +* +* The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. +* +* @name Phaser.Text#cssFont +* @property {string} cssFont +*/ +Object.defineProperty(Phaser.Text.prototype, 'cssFont', { + + get: function() { + return this.componentsToFont(this._fontComponents); + }, + + set: function (value) + { + value = value || 'bold 20pt Arial'; + this._fontComponents = this.fontToComponents(value); + this.updateFont(this._fontComponents); + } + +}); + +/** +* Change the font family that the text will be rendered in, such as 'Arial'. +* +* Multiple CSS font families and generic fallbacks can be specified as long as +* {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed. +* +* To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`. +* +* @name Phaser.Text#font +* @property {string} font +*/ +Object.defineProperty(Phaser.Text.prototype, 'font', { + + get: function() { + return this._fontComponents.fontFamily; + }, + + set: function(value) { + + value = value || 'Arial'; + value = value.trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value)) + { + value = "'" + value + "'"; + } + + this._fontComponents.fontFamily = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The size of the font. +* +* If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing +* the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). +* +* @name Phaser.Text#fontSize +* @property {number|string} fontSize +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontSize', { + + get: function() { + + var size = this._fontComponents.fontSize; + + if (size && /(?:^0$|px$)/.exec(size)) + { + return parseInt(size, 10); + } + else + { + return size; + } + + }, + + set: function(value) { + + value = value || '0'; + + if (typeof value === 'number') + { + value = value + 'px'; + } + + this._fontComponents.fontSize = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}. +* @name Phaser.Text#fontWeight +* @property {string} fontWeight +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontWeight', { + + get: function() { + return this._fontComponents.fontWeight || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontWeight = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The style of the font: 'normal', 'italic', 'oblique' +* @name Phaser.Text#fontStyle +* @property {string} fontStyle +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontStyle', { + + get: function() { + return this._fontComponents.fontStyle || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontStyle = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The variant the font: 'normal', 'small-caps' +* @name Phaser.Text#fontVariant +* @property {string} fontVariant +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontVariant', { + + get: function() { + return this._fontComponents.fontVariant || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontVariant = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* @name Phaser.Text#fill +* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'fill', { + + get: function() { + return this.style.fill; + }, + + set: function(value) { + + if (value !== this.style.fill) + { + this.style.fill = value; + this.dirty = true; + } + + } + +}); + +/** +* Controls the horizontal alignment for multiline text. +* Can be: 'left', 'center' or 'right'. +* Does not affect single lines of text. For that please see `setTextBounds`. +* @name Phaser.Text#align +* @property {string} align +*/ +Object.defineProperty(Phaser.Text.prototype, 'align', { + + get: function() { + return this.style.align; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.align) + { + this.style.align = value; + this.dirty = true; + } + + } + +}); + +/** +* The resolution of the canvas the text is rendered to. +* This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. +* @name Phaser.Text#resolution +* @property {integer} resolution +*/ +Object.defineProperty(Phaser.Text.prototype, 'resolution', { + + get: function() { + return this._res; + }, + + set: function(value) { + + if (value !== this._res) + { + this._res = value; + this.dirty = true; + } + + } + +}); + +/** +* The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. +* Can be an integer or an array of varying tab sizes, one tab per element. +* For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. +* If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. +* +* @name Phaser.Text#tabs +* @property {integer|array} tabs +*/ +Object.defineProperty(Phaser.Text.prototype, 'tabs', { + + get: function() { + return this.style.tabs; + }, + + set: function(value) { + + if (value !== this.style.tabs) + { + this.style.tabs = value; + this.dirty = true; + } + + } + +}); + +/** +* Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @name Phaser.Text#boundsAlignH +* @property {string} boundsAlignH +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', { + + get: function() { + return this.style.boundsAlignH; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignH) + { + this.style.boundsAlignH = value; + this.dirty = true; + } + + } + +}); + +/** +* Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @name Phaser.Text#boundsAlignV +* @property {string} boundsAlignV +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', { + + get: function() { + return this.style.boundsAlignV; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignV) + { + this.style.boundsAlignV = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#stroke +* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'stroke', { + + get: function() { + return this.style.stroke; + }, + + set: function(value) { + + if (value !== this.style.stroke) + { + this.style.stroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#strokeThickness +* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke) +*/ +Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', { + + get: function() { + return this.style.strokeThickness; + }, + + set: function(value) { + + if (value !== this.style.strokeThickness) + { + this.style.strokeThickness = Number(value); + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrap +* @property {boolean} wordWrap - Indicates if word wrap should be used. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrap', { + + get: function() { + return this.style.wordWrap; + }, + + set: function(value) { + + if (value !== this.style.wordWrap) + { + this.style.wordWrap = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrapWidth +* @property {number} wordWrapWidth - The width at which text will wrap. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', { + + get: function() { + return this.style.wordWrapWidth; + }, + + set: function(value) { + + if (value !== this.style.wordWrapWidth) + { + this.style.wordWrapWidth = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#lineSpacing +* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. +*/ +Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { + + get: function() { + return this._lineSpacing; + }, + + set: function(value) { + + if (value !== this._lineSpacing) + { + this._lineSpacing = parseFloat(value); + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetX +* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', { + + get: function() { + return this.style.shadowOffsetX; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetX) + { + this.style.shadowOffsetX = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetY +* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', { + + get: function() { + return this.style.shadowOffsetY; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetY) + { + this.style.shadowOffsetY = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowColor +* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowColor', { + + get: function() { + return this.style.shadowColor; + }, + + set: function(value) { + + if (value !== this.style.shadowColor) + { + this.style.shadowColor = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowBlur +* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', { + + get: function() { + return this.style.shadowBlur; + }, + + set: function(value) { + + if (value !== this.style.shadowBlur) + { + this.style.shadowBlur = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowStroke +* @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', { + + get: function() { + return this.style.shadowStroke; + }, + + set: function(value) { + + if (value !== this.style.shadowStroke) + { + this.style.shadowStroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowFill +* @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowFill', { + + get: function() { + return this.style.shadowFill; + }, + + set: function(value) { + + if (value !== this.style.shadowFill) + { + this.style.shadowFill = value; + this.dirty = true; + } + + } + +}); + +/** +* The width of the Text object in pixels. This is width of the Texture frame / the Text.resolution. +* @name Phaser.Text#width +* @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'width', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.x * (this.texture.frame.width / this.resolution); + }, + + set: function(value) { + + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** +* The height of the Text object in pixels. This is height of the Texture frame / the Text.resolution. +* @name Phaser.Text#height +* @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'height', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.y * (this.texture.frame.height / this.resolution); + }, + + set: function(value) { + + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +Phaser.Text.fontPropertiesCache = {}; + +Phaser.Text.fontPropertiesCanvas = document.createElement('canvas'); +Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d'); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. +* It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to +* match the font structure. +* +* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability +* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by +* processing the font texture in an image editor, applying fills and any other effects required. +* +* To create multi-line text insert \r, \n or \r\n escape codes into the text string. +* +* If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly +* updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. +* +* To create a BitmapText data files you can use: +* +* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ +* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner +* Littera (Web-based, free): http://kvazars.com/littera/ +* +* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of +* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson +* +* If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. +* +* @class Phaser.BitmapText +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - X coordinate to display the BitmapText object at. +* @param {number} y - Y coordinate to display the BitmapText object at. +* @param {string} font - The key of the BitmapText as stored in Phaser.Cache. +* @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. +* @param {number} [size=32] - The size the font will be rendered at in pixels. +* @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. +*/ +Phaser.BitmapText = function (game, x, y, font, text, size, align) { + + x = x || 0; + y = y || 0; + font = font || ''; + text = text || ''; + size = size || 32; + align = align || 'left'; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.BITMAPTEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textWidth = 0; + + /** + * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textHeight = 0; + + /** + * @property {Phaser.Point} anchor - The anchor value of this BitmapText. + */ + this.anchor = new Phaser.Point(); + + /** + * @property {Phaser.Point} _prevAnchor - The previous anchor value. + * @private + */ + this._prevAnchor = new Phaser.Point(); + + /** + * @property {array} _glyphs - Private tracker for the letter sprite pool. + * @private + */ + this._glyphs = []; + + /** + * @property {number} _maxWidth - Internal cache var. + * @private + */ + this._maxWidth = 0; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text.toString() || ''; + + /** + * @property {string} _data - Internal cache var. + * @private + */ + this._data = game.cache.getBitmapFont(font); + + /** + * @property {string} _font - Internal cache var. + * @private + */ + this._font = font; + + /** + * @property {number} _fontSize - Internal cache var. + * @private + */ + this._fontSize = size; + + /** + * @property {string} _align - Internal cache var. + * @private + */ + this._align = align; + + /** + * @property {number} _tint - Internal cache var. + * @private + */ + this._tint = 0xFFFFFF; + + this.updateText(); + + /** + * @property {boolean} dirty - The dirty state of this object. + */ + this.dirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.BitmapText.prototype.constructor = Phaser.BitmapText; + +Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.BitmapText +* @return {boolean} True if the BitmapText was rendered, otherwise false. +*/ +Phaser.BitmapText.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.preUpdate. +* @method Phaser.BitmapText.prototype.postUpdate +*/ +Phaser.BitmapText.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this.body && this.body.type === Phaser.Physics.ARCADE) + { + if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight)) + { + this.body.setSize(this.textWidth, this.textHeight); + } + } + +}; + +/** +* The text to be displayed by this BitmapText object. +* +* It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. +* +* @method Phaser.BitmapText.prototype.setText +* @param {string} text - The text to be displayed by this BitmapText object. +*/ +Phaser.BitmapText.prototype.setText = function (text) { + + this.text = text; + +}; + +/** +* Given the input text this will scan the characters until either a newline is encountered, +* or the line exceeds maxWidth, taking into account kerning, character widths and scaling. +* +* @method Phaser.BitmapText.prototype.scanLine +* @private +* @param {object} data - A reference to the font object in the Phaser.Cache. +* @param {float} scale - The scale of the font in relation to the texture. +* @param {string} text - The text to parse. +* @return {object} An object containing the parsed characters, total pixel width and x offsets. +*/ +Phaser.BitmapText.prototype.scanLine = function (data, scale, text) { + + var x = 0; + var w = 0; + var lastSpace = -1; + var wrappedWidth = 0; + var prevCharCode = null; + var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null; + var chars = []; + + // Let's scan the text and work out if any of the lines are > maxWidth + for (var i = 0; i < text.length; i++) + { + var end = (i === text.length - 1) ? true : false; + + if (/(?:\r\n|\r|\n)/.test(text.charAt(i))) + { + return { width: w, text: text.substr(0, i), end: end, chars: chars }; + } + else + { + var charCode = text.charCodeAt(i); + var charData = data.chars[charCode]; + + var c = 0; + + // If the character data isn't found in the data array + // then we replace it with a blank space + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + // Adjust for kerning from previous character to this one + var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0; + + // Record the last space in the string and the current width + if (/(\s)/.test(text.charAt(i))) + { + lastSpace = i; + wrappedWidth = w; + } + + // What will the line width be if we add this character to it? + c = (kerning + charData.texture.width + charData.xOffset) * scale; + + // Do we need to line-wrap? + if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1) + { + // The last space was at "lastSpace" which was "i - lastSpace" characters ago + return { width: wrappedWidth || w, text: text.substr(0, i - (i - lastSpace)), end: false, chars: chars }; + } + else + { + w += (charData.xAdvance + kerning) * scale; + + chars.push(x + (charData.xOffset + kerning) * scale); + + x += (charData.xAdvance + kerning) * scale; + + prevCharCode = charCode; + } + } + } + + return { width: w, text: text, end: end, chars: chars }; + +}; + +/** +* Given a text string this will scan each character in the string to ensure it exists +* in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. +* +* If no font data has been loaded at all this returns an empty string, as nothing can be rendered. +* +* @method Phaser.BitmapText.prototype.cleanText +* @param {string} text - The text to parse. +* @param {string} [replace=''] - The replacement string for any missing characters. +* @return {string} The cleaned text string. +*/ +Phaser.BitmapText.prototype.cleanText = function (text, replace) { + + if (replace === undefined) + { + replace = ''; + } + + var data = this._data.font; + + if (!data) + { + return ''; + } + + var re = /\r\n|\n\r|\n|\r/g; + var lines = text.replace(re, "\n").split("\n"); + + for (var i = 0; i < lines.length; i++) + { + var output = ''; + var line = lines[i]; + + for (var c = 0; c < line.length; c++) + { + if (data.chars[line.charCodeAt(c)]) + { + output = output.concat(line[c]); + } + else + { + output = output.concat(replace); + } + } + + lines[i] = output; + } + + return lines.join("\n"); + +}; + +/** +* Renders text and updates it when needed. +* +* @method Phaser.BitmapText.prototype.updateText +* @private +*/ +Phaser.BitmapText.prototype.updateText = function () { + + var data = this._data.font; + + if (!data) + { + return; + } + + var text = this.text; + var scale = this._fontSize / data.size; + var lines = []; + + var y = 0; + + this.textWidth = 0; + + do + { + var line = this.scanLine(data, scale, text); + + line.y = y; + + lines.push(line); + + if (line.width > this.textWidth) + { + this.textWidth = line.width; + } + + y += (data.lineHeight * scale); + + text = text.substr(line.text.length + 1); + + } while (line.end === false); + + this.textHeight = y; + + var t = 0; + var align = 0; + var ax = this.textWidth * this.anchor.x; + var ay = this.textHeight * this.anchor.y; + + for (var i = 0; i < lines.length; i++) + { + var line = lines[i]; + + if (this._align === 'right') + { + align = this.textWidth - line.width; + } + else if (this._align === 'center') + { + align = (this.textWidth - line.width) / 2; + } + + for (var c = 0; c < line.text.length; c++) + { + var charCode = line.text.charCodeAt(c); + var charData = data.chars[charCode]; + + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + var g = this._glyphs[t]; + + if (g) + { + // Sprite already exists in the glyphs pool, so we'll reuse it for this letter + g.texture = charData.texture; + } + else + { + // We need a new sprite as the pool is empty or exhausted + g = new PIXI.Sprite(charData.texture); + g.name = line.text[c]; + this._glyphs.push(g); + } + + g.position.x = (line.chars[c] + align) - ax; + g.position.y = (line.y + (charData.yOffset * scale)) - ay; + + g.scale.set(scale); + g.tint = this.tint; + g.texture.requiresReTint = true; + g.cachedTint = 0xFFFFFF; + + if (!g.parent) + { + this.addChild(g); + } + + t++; + } + } + + // Remove unnecessary children + // This moves them from the display list (children array) but retains them in the _glyphs pool + for (i = t; i < this._glyphs.length; i++) + { + this.removeChild(this._glyphs[i]); + } + +}; + +/** +* If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of +* Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they +* still take up memory while sat in the glyphs pool waiting to be re-used in the future. +* +* If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool +* by calling this method. +* +* Calling this doesn't prevent you from increasing the length of the text again in the future. +* +* @method Phaser.BitmapText.prototype.purgeGlyphs +* @return {integer} The amount of glyphs removed from the pool. +*/ +Phaser.BitmapText.prototype.purgeGlyphs = function () { + + var len = this._glyphs.length; + var kept = []; + + for (var i = 0; i < this._glyphs.length; i++) + { + if (this._glyphs[i].parent !== this) + { + this._glyphs[i].destroy(); + } + else + { + kept.push(this._glyphs[i]); + } + } + + this._glyphs = []; + this._glyphs = kept; + + this.updateText(); + + return len - kept.length; + +}; + +/** +* Updates the transform of this object. +* +* @method Phaser.BitmapText.prototype.updateTransform +* @private +*/ +Phaser.BitmapText.prototype.updateTransform = function () { + + if (this.dirty || !this.anchor.equals(this._prevAnchor)) + { + this.updateText(); + this.dirty = false; + this._prevAnchor.copyFrom(this.anchor); + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/** +* @name Phaser.BitmapText#align +* @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'align', { + + get: function() { + return this._align; + }, + + set: function(value) { + + if (value !== this._align && (value === 'left' || value === 'center' || value === 'right')) + { + this._align = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#tint +* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'tint', { + + get: function() { + return this._tint; + }, + + set: function(value) { + + if (value !== this._tint) + { + this._tint = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#font +* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'font', { + + get: function() { + return this._font; + }, + + set: function(value) { + + if (value !== this._font) + { + this._font = value.trim(); + this._data = this.game.cache.getBitmapFont(this._font); + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#fontSize +* @property {number} fontSize - The size of the font in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { + + get: function() { + return this._fontSize; + }, + + set: function(value) { + + value = parseInt(value, 10); + + if (value !== this._fontSize && value > 0) + { + this._fontSize = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#text +* @property {string} text - The text to be displayed by this BitmapText object. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.updateText(); + } + + } + +}); + +/** +* The maximum display width of this BitmapText in pixels. +* +* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped +* based on the last whitespace character found in the line. +* +* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. +* +* Disable maxWidth by setting the value to 0. +* +* @name Phaser.BitmapText#maxWidth +* @property {number} maxWidth - The maximum width of this BitmapText in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', { + + get: function() { + + return this._maxWidth; + + }, + + set: function(value) { + + if (value !== this._maxWidth) + { + this._maxWidth = value; + this.updateText(); + } + + } + +}); + +/** +* Enable or disable texture smoothing for this BitmapText. +* +* The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. +* +* Smoothing is enabled by default. +* +* @name Phaser.BitmapText#smoothed +* @property {boolean} smoothed +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', { + + get: function() { + + return !this._data.base.scaleMode; + + }, + + set: function(value) { + + if (value) + { + this._data.base.scaleMode = 0; + } + else + { + this._data.base.scaleMode = 1; + } + this._data.base.dirty(); + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont +* is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. +* +* @class Phaser.RetroFont +* @extends Phaser.RenderTexture +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {string} key - The font set graphic set as stored in the Game.Cache. +* @param {number} characterWidth - The width of each character in the font set. +* @param {number} characterHeight - The height of each character in the font set. +* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. +* @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. +* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. +* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { + + if (!game.cache.checkImageKey(key)) + { + return false; + } + + if (charsPerRow === undefined || charsPerRow === null) + { + charsPerRow = game.cache.getImage(key).width / characterWidth; + } + + /** + * @property {number} characterWidth - The width of each character in the font set. + */ + this.characterWidth = characterWidth; + + /** + * @property {number} characterHeight - The height of each character in the font set. + */ + this.characterHeight = characterHeight; + + /** + * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here. + */ + this.characterSpacingX = xSpacing || 0; + + /** + * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here. + */ + this.characterSpacingY = ySpacing || 0; + + /** + * @property {number} characterPerRow - The number of characters per row in the font set. + */ + this.characterPerRow = charsPerRow; + + /** + * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @readonly + */ + this.offsetX = xOffset || 0; + + /** + * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @readonly + */ + this.offsetY = yOffset || 0; + + /** + * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + */ + this.align = "left"; + + /** + * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) + * @default + */ + this.multiLine = false; + + /** + * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. + * @default + */ + this.autoUpperCase = true; + + /** + * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels. + * @default + */ + this.customSpacingX = 0; + + /** + * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels. + * @default + */ + this.customSpacingY = 0; + + /** + * If you need this RetroFont image to have a fixed width you can set the width in this value. + * If text is wider than the width specified it will be cropped off. + * @property {number} fixedWidth + */ + this.fixedWidth = 0; + + /** + * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font. + */ + this.fontSet = game.cache.getImage(key); + + /** + * @property {string} _text - The text of the font image. + * @private + */ + this._text = ''; + + /** + * @property {array} grabData - An array of rects for faster character pasting. + * @private + */ + this.grabData = []; + + /** + * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font. + */ + this.frameData = new Phaser.FrameData(); + + // Now generate our rects for faster copying later on + var currentX = this.offsetX; + var currentY = this.offsetY; + var r = 0; + + for (var c = 0; c < chars.length; c++) + { + var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight)); + + this.grabData[chars.charCodeAt(c)] = frame.index; + + r++; + + if (r === this.characterPerRow) + { + r = 0; + currentX = this.offsetX; + currentY += this.characterHeight + this.characterSpacingY; + } + else + { + currentX += this.characterWidth + this.characterSpacingX; + } + } + + game.cache.updateFrameData(key, this.frameData); + + /** + * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font. + * @readonly + */ + this.stamp = new Phaser.Image(game, 0, 0, key, 0); + + Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST); + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RETROFONT; + +}; + +Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype); +Phaser.RetroFont.prototype.constructor = Phaser.RetroFont; + +/** +* Align each line of multi-line text to the left. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_LEFT = "left"; + +/** +* Align each line of multi-line text to the right. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_RIGHT = "right"; + +/** +* Align each line of multi-line text in the center. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_CENTER = "center"; + +/** +* Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + +/** +* Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "; + +/** +* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789"; + +/** +* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789"; + +/** +* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' "; + +/** +* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39"; + +/** +* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!"; + +/** +* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"; + +/** +* If you need this RetroFont to have a fixed width and custom alignment you can set the width here. +* If text is wider than the width specified it will be cropped off. +* +* @method Phaser.RetroFont#setFixedWidth +* @memberof Phaser.RetroFont +* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. +* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +*/ +Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) { + + if (lineAlignment === undefined) { lineAlignment = 'left'; } + + this.fixedWidth = width; + this.align = lineAlignment; + +}; + +/** +* A helper function that quickly sets lots of variables at once, and then updates the text. +* +* @method Phaser.RetroFont#setText +* @memberof Phaser.RetroFont +* @param {string} content - The text of this sprite. +* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. +* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels. +* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels. +* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. +*/ +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; + } + +}; + +/** +* Updates the texture with the new text. +* +* @method Phaser.RetroFont#buildRetroFontText +* @memberof Phaser.RetroFont +*/ +Phaser.RetroFont.prototype.buildRetroFontText = function () { + + var cx = 0; + var cy = 0; + + // Clears the textureBuffer + 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); + } + + // Loop through each line of text + for (var i = 0; i < lines.length; i++) + { + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + // This line of text is held in lines[i] - need to work out the alignment + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(lines[i], cx, cy, this.customSpacingX); + + cy += this.characterHeight + this.customSpacingY; + } + } + else + { + if (this.fixedWidth > 0) + { + this.resize(this.fixedWidth, this.characterHeight, true); + } + else + { + this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true); + } + + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(this._text, cx, 0, this.customSpacingX); + } + + this.requiresReTint = true; + +}; + +/** +* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. +* Used by getLine and getMultiLine +* +* @method Phaser.RetroFont#pasteLine +* @memberof Phaser.RetroFont +* @param {string} line - The single line of text to paste. +* @param {number} x - The x coordinate. +* @param {number} y - The y coordinate. +* @param {number} customSpacingX - Custom X spacing. +*/ +Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) { + + for (var c = 0; c < line.length; c++) + { + // If it's a space then there is no point copying, so leave a blank space + if (line.charAt(c) === " ") + { + x += this.characterWidth + customSpacingX; + } + else + { + // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it + if (this.grabData[line.charCodeAt(c)] >= 0) + { + this.stamp.frame = this.grabData[line.charCodeAt(c)]; + this.renderXY(this.stamp, x, y, false); + + x += this.characterWidth + customSpacingX; + + if (x > this.width) + { + break; + } + } + } + } +}; + +/** +* Works out the longest line of text in _text and returns its length +* +* @method Phaser.RetroFont#getLongestLine +* @memberof Phaser.RetroFont +* @return {number} The length of the longest line of text. +*/ +Phaser.RetroFont.prototype.getLongestLine = function () { + + var longestLine = 0; + + if (this._text.length > 0) + { + var lines = this._text.split("\n"); + + for (var i = 0; i < lines.length; i++) + { + if (lines[i].length > longestLine) + { + longestLine = lines[i].length; + } + } + } + + return longestLine; +}; + +/** +* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set. +* +* @method Phaser.RetroFont#removeUnsupportedCharacters +* @memberof Phaser.RetroFont +* @protected +* @param {boolean} [stripCR=true] - Should it strip carriage returns as well? +* @return {string} A clean version of the string. +*/ +Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) { + + var newString = ""; + + for (var c = 0; c < this._text.length; c++) + { + var aChar = this._text[c]; + var code = aChar.charCodeAt(0); + + if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n")) + { + newString = newString.concat(aChar); + } + } + + return newString; + +}; + +/** +* Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. +* Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. +* So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. +* +* @method Phaser.RetroFont#updateOffset +* @memberof Phaser.RetroFont +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont.prototype.updateOffset = function (x, y) { + + if (this.offsetX === x && this.offsetY === y) + { + return; + } + + var diffX = x - this.offsetX; + var diffY = y - this.offsetY; + + var frames = this.game.cache.getFrameData(this.stamp.key).getFrames(); + var i = frames.length; + + while (i--) + { + frames[i].x += diffX; + frames[i].y += diffY; + } + + this.buildRetroFontText(); + +}; + +/** +* @name Phaser.RetroFont#text +* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. +*/ +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(); + } + + } + +}); + +/** +* @name Phaser.RetroFont#smoothed +* @property {boolean} smoothed - Sets if the stamp is smoothed or not. +*/ +Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", { + + get: function () { + + return this.stamp.smoothed; + + }, + + set: function (value) { + + this.stamp.smoothed = value; + this.buildRetroFontText(); + + } + +}); + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @author Rovanion Luckey +* @copyright 2016 Photon Storm Ltd, Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Rope is a Sprite that has a repeating texture. +* +* The texture will automatically wrap on the edges as it moves. +* +* Please note that Ropes cannot have an input handler. +* +* @class Phaser.Rope +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Rope at. +* @param {number} y - The y coordinate (in world space) to position the Rope at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {Array} points - An array of {Phaser.Point}. +*/ +Phaser.Rope = function (game, x, y, key, frame, points) { + + this.points = points || []; + this._hasUpdateAnimation = false; + this._updateAnimationCallback = null; + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROPE; + + PIXI.DisplayObjectContainer.call(this); + + this.texture = Phaser.Cache.DEFAULT; + + // set up the main bits.. + this.uvs = new Float32Array([0, 1, + 1, 1, + 1, 0, + 0, 1]); + + this.vertices = new Float32Array([0, 0, + 100, 0, + 100, 100, + 0, 100]); + + this.colors = new Float32Array([1, 1, 1, 1]); + + this.indices = new Uint16Array([0, 1, 2, 3]); + + if (points) + { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + /** + * Whether the strip is dirty or not + * + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. + * + * @property canvasPadding + * @type Number + */ + this.canvasPadding = 0; + + this.drawMode = Phaser.Rope.TRIANGLE_STRIP; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + + this.refresh(); + +}; + +Phaser.Rope.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Rope.prototype.constructor = Phaser.Rope; + +Phaser.Component.Core.install.call(Phaser.Rope.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +Phaser.Rope.TRIANGLE_STRIP = 0; +Phaser.Rope.TRIANGLES = 1; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Rope#preUpdate +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override and use this function in your own custom objects to handle any update requirements you may have. +* +* @method Phaser.Rope#update +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.update = function() { + + if (this._hasUpdateAnimation) + { + this.updateAnimation.call(this); + } + +}; + +/** +* Resets the Rope. This places the Rope at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the Rope has a physics body that too is reset. +* +* @method Phaser.Rope#reset +* @memberof Phaser.Rope +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.Rope} This instance. +*/ +Phaser.Rope.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + return this; + +}; + +/* +* Refreshes the rope texture and UV coordinates. +* +* @method Phaser.Rope#refresh +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.refresh = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + this.count -= 0.2; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + var index; + var amount; + + for (var i = 1; i < total; i++) + { + index = i * 4; + + // time to do some smart drawing! + amount = i / (total - 1); + + if (i % 2) + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + else + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + +}; + +/* +* Updates the Ropes transform ready for rendering. +* +* @method Phaser.Rope#updateTransform +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.updateTransform = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var lastPoint = points[0]; + var nextPoint; + var perp = { x:0, y:0 }; + + this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + var point; + var index; + var ratio; + var perpLength; + var num; + + for (var i = 0; i < total; i++) + { + point = points[i]; + index = i * 4; + + if(i < points.length - 1) + { + nextPoint = points[i + 1]; + } + else + { + nextPoint = point; + } + + perp.y = -(nextPoint.x - lastPoint.x); + perp.x = nextPoint.y - lastPoint.y; + + ratio = (1 - (i / (total - 1))) * 10; + + if (ratio > 1) + { + ratio = 1; + } + + perpLength = Math.sqrt((perp.x * perp.x) + (perp.y * perp.y)); + num = this.texture.height / 2; + perp.x /= perpLength; + perp.y /= perpLength; + + perp.x *= num; + perp.y *= num; + + vertices[index] = point.x + perp.x; + vertices[index + 1] = point.y + perp.y; + vertices[index + 2] = point.x - perp.x; + vertices[index + 3] = point.y - perp.y; + + lastPoint = point; + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/* +* Sets the Texture this Rope uses for rendering. +* +* @method Phaser.Rope#setTexture +* @memberof Phaser.Rope +* @param {Texture} texture - The texture that will be used. +*/ +Phaser.Rope.prototype.setTexture = function (texture) { + + this.texture = texture; + +}; + +/* +* Renders the Rope to WebGL. +* +* @private +* @method Phaser.Rope#_renderWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + renderSession.spriteBatch.stop(); + + if (!this._vertexBuffer) + { + this._initWebGL(renderSession); + } + + renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader); + + this._renderStrip(renderSession); + + renderSession.spriteBatch.start(); + +}; + +/* +* Builds the Strip. +* +* @private +* @method Phaser.Rope#_initWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._initWebGL = function (renderSession) { + + // build the strip! + var gl = renderSession.gl; + + this._vertexBuffer = gl.createBuffer(); + this._indexBuffer = gl.createBuffer(); + this._uvBuffer = gl.createBuffer(); + this._colorBuffer = gl.createBuffer(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + +}; + +/* +* Renders the Strip to WebGL. +* +* @private +* @method Phaser.Rope#_renderStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderStrip = function (renderSession) { + + var gl = renderSession.gl; + var projection = renderSession.projection; + var offset = renderSession.offset; + var shader = renderSession.shaderManager.stripShader; + + var drawMode = (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + renderSession.blendModeManager.setBlendMode(this.blendMode); + + // set uniforms + gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true)); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + gl.uniform1f(shader.alpha, this.worldAlpha); + + if (!this.dirty) + { + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + } + else + { + this.dirty = false; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + } + + gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0); + +}; + +/* +* Renders the Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvas +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvas = function (renderSession) { + + var context = renderSession.context; + + var transform = this.worldTransform; + + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + if (renderSession.roundPixels) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx, ty); + } + + if (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) + { + this._renderCanvasTriangleStrip(context); + } + else + { + this._renderCanvasTriangles(context); + } + +}; + +/* +* Renders a Triangle Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangleStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangleStrip = function (context) { + + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + + var length = vertices.length / 2; + + this.count++; + + for (var i = 0; i < length - 2; i++) + { + var index = i * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangles +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangles = function (context) { + + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + + var length = indices.length; + + this.count++; + + for (var i = 0; i < length; i += 3) + { + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasDrawTriangle +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { + + var textureSource = this.texture.baseTexture.source; + var textureWidth = this.texture.width; + var textureHeight = this.texture.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var u0 = uvs[index0] * textureWidth; + var u1 = uvs[index1] * textureWidth; + var u2 = uvs[index2] * textureWidth; + var v0 = uvs[index0 + 1] * textureHeight; + var v1 = uvs[index1 + 1] * textureHeight; + var v2 = uvs[index2 + 1] * textureHeight; + + if (this.canvasPadding > 0) + { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt((normX * normX) + (normY * normY)); + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2); + var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2); + var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2); + var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2); + var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2); + var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2); + var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2); + + context.transform( + deltaA / delta, + deltaD / delta, + deltaB / delta, + deltaE / delta, + deltaC / delta, + deltaF / delta); + + context.drawImage(textureSource, 0, 0); + context.restore(); + +}; + +/* +* Renders a flat strip. +* +* @method Phaser.Rope#renderStripFlat +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.renderStripFlat = function (strip) { + + var context = this.context; + var vertices = strip.vertices; + + var length = vertices.length / 2; + + this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; i++) + { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var x1 = vertices[index + 2]; + var x2 = vertices[index + 4]; + var y0 = vertices[index + 1]; + var y1 = vertices[index + 3]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + +}; + +/* +* Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Rope#getBounds +* @memberof Phaser.Rope +* @param {Matrix} matrix - The transformation matrix of the Sprite. +* @return {Rectangle} The framing rectangle. +*/ +Phaser.Rope.prototype.getBounds = function (matrix) { + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + var vertices = this.vertices; + + for (var i = 0; i < vertices.length; i += 2) + { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + if (minX === -Infinity || maxY === Infinity) + { + return PIXI.EmptyRectangle; + } + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // Store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* A Rope will call its updateAnimation function on each update loop if it has one. +* +* @name Phaser.Rope#updateAnimation +* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. +*/ +Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", { + + get: function () { + + return this._updateAnimation; + + }, + + set: function (value) { + + if (value && typeof value === 'function') + { + this._hasUpdateAnimation = true; + this._updateAnimation = value; + } + else + { + this._hasUpdateAnimation = false; + this._updateAnimation = null; + } + + } + +}); + +/** +* The segments that make up the rope body as an array of Phaser.Rectangles +* +* @name Phaser.Rope#segments +* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope +*/ +Object.defineProperty(Phaser.Rope.prototype, "segments", { + + get: function () { + + var segments = []; + var index, x1, y1, x2, y2, width, height, rect; + + for (var i = 0; i < this.points.length; i++) + { + index = i * 4; + + x1 = this.vertices[index] * this.scale.x; + y1 = this.vertices[index + 1] * this.scale.y; + x2 = this.vertices[index + 4] * this.scale.x; + y2 = this.vertices[index + 3] * this.scale.y; + + width = Phaser.Math.difference(x1, x2); + height = Phaser.Math.difference(y1, y2); + + x1 += this.world.x; + y1 += this.world.y; + rect = new Phaser.Rectangle(x1, y1, width, height); + segments.push(rect); + } + + return segments; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. +* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. +* +* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. +* +* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background +* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` +* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will +* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to +* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. +* +* An important note about texture dimensions: +* +* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be +* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two +* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and +* bottom of your frame. To avoid this ensure your textures are perfect powers of two. +* +* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However +* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive +* additional padding to enforce it to be so. +* +* @class Phaser.TileSprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate (in world space) to position the TileSprite at. +* @param {number} [y=0] - The y coordinate (in world space) to position the TileSprite at. +* @param {number} [width=256] - The width of the TileSprite. +* @param {number} [height=256] - The height of the TileSprite. +* @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. +* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.TileSprite = function (game, x, y, width, height, key, frame) { + + x = x || 0; + y = y || 0; + width = width || 256; + height = height || 256; + key = key || null; + frame = frame || null; + + PIXI.Sprite.call(this, new PIXI.Texture(Phaser.Cache.DEFAULT.baseTexture), width, height); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.TILESPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} _scroll - Internal cache var. + * @private + */ + this._scroll = new Phaser.Point(); + + /** + * @property {Phaser.Point} tileScale - The scale applied to the image being tiled. + */ + this.tileScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tileScaleOffset - The scale offset applied to the image being tiled. + */ + this.tileScaleOffset = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tilePosition - The offset position of the image being tiled. + */ + this.tilePosition = new Phaser.Point(); + + /** + * If enabled a green rectangle will be drawn behind the generated tiling texture, + * allowing you to visually debug the texture being used. + * + * @property {boolean} textureDebug + */ + this.textureDebug = false; + + /** + * The CanvasBuffer object that the tiled texture is drawn to. + * + * @property {PIXI.CanvasBuffer} canvasBuffer + */ + this.canvasBuffer = null; + + /** + * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. + * + * @property {PIXI.Texture} tilingTexture + */ + this.tilingTexture = null; + + /** + * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). + * + * @property {object} tilePattern + */ + this.tilePattern = null; + + /** + * If true the TileSprite will run `generateTexture` on its **next** render pass. + * This is set by the likes of Phaser.LoadTexture.setFrame. + * + * @property {boolean} refreshTexture + */ + this.refreshTexture = true; + + this.frameWidth = 0; + this.frameHeight = 0; + + this._width = width; + this._height = height; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.TileSprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.TileSprite.prototype.constructor = Phaser.TileSprite; + +Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'Smoothed' +]); + +Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TileSprite#preUpdate +* @memberof Phaser.TileSprite +* @return {boolean} +*/ +Phaser.TileSprite.prototype.preUpdate = function () { + + if (this._scroll.x !== 0) + { + this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed; + } + + if (this._scroll.y !== 0) + { + this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed; + } + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). +* The scroll speed is specified in pixels per second. +* A negative x value will scroll to the left. A positive x value will scroll to the right. +* A negative y value will scroll up. A positive y value will scroll down. +* +* @method Phaser.TileSprite#autoScroll +* @memberof Phaser.TileSprite +* @param {number} x - Horizontal scroll speed in pixels per second. +* @param {number} y - Vertical scroll speed in pixels per second. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.autoScroll = function (x, y) { + + this._scroll.set(x, y); + + return this; + +}; + +/** +* Stops an automatically scrolling TileSprite. +* +* @method Phaser.TileSprite#stopScroll +* @memberof Phaser.TileSprite +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.stopScroll = function () { + + this._scroll.set(0, 0); + + return this; + +}; + +/** +* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present +* and nulls its reference to game, freeing it up for garbage collection. +* +* @method Phaser.TileSprite#destroy +* @memberof Phaser.TileSprite +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.TileSprite.prototype.destroy = function (destroyChildren) { + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + + PIXI.Sprite.prototype.destroy.call(this); + + if (this.canvasBuffer) + { + this.canvasBuffer.destroy(); + this.canvasBuffer = null; + } + + this.tileScale = null; + this.tileScaleOffset = null; + this.tilePosition = null; + + if (this.tilingTexture) + { + this.tilingTexture.destroy(true); + this.tilingTexture = null; + } + +}; + +/** +* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the TileSprite has a physics body that too is reset. +* +* @method Phaser.TileSprite#reset +* @memberof Phaser.TileSprite +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + this.tilePosition.x = 0; + this.tilePosition.y = 0; + + return this; + +}; + +/** +* Changes the texture being rendered by this TileSprite. +* Causes a texture refresh to take place on the next render. +* +* @method Phaser.TileSprite#setTexture +* @memberof Phaser.TileSprite +* @param {PIXI.Texture} texture - The texture to apply to this TileSprite. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.setTexture = function (texture) { + + if (this.texture !== texture) + { + this.texture = texture; + this.refreshTexture = true; + this.cachedTint = 0xFFFFFF; + } + + return this; + +}; + +/** +* Renders the TileSprite using the WebGL Renderer. +* +* @private +* @method Phaser.TileSprite#_renderWebGL +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + 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.refreshTexture) + { + this.generateTilingTexture(true, renderSession); + + if (this.tilingTexture) + { + if (this.tilingTexture.needsUpdate) + { + this.tilingTexture.baseTexture.textureIndex = this.texture.baseTexture.textureIndex; + renderSession.renderer.updateTexture(this.tilingTexture.baseTexture); + this.tilingTexture.needsUpdate = false; + } + } + else + { + return; + } + } + + renderSession.spriteBatch.renderTilingSprite(this); + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + var restartBatch = false; + + if (this._filters) + { + restartBatch = true; + renderSession.spriteBatch.stop(); + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + if (!restartBatch) + { + renderSession.spriteBatch.stop(); + } + + renderSession.maskManager.popMask(this._mask, renderSession); + } + + if (restartBatch) + { + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the TileSprite using the Canvas Renderer. +* +* @private +* @method Phaser.TileSprite#_renderCanvas +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + var context = renderSession.context; + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + context.globalAlpha = this.worldAlpha; + + var wt = this.worldTransform; + var resolution = renderSession.resolution; + var tx = (wt.tx * resolution) + renderSession.shakeX; + var ty = (wt.ty * resolution) + renderSession.shakeY; + + context.setTransform(wt.a * resolution, wt.b * resolution, wt.c * resolution, wt.d * resolution, tx, ty); + + if (this.tint !== 0xFFFFFF && (this.texture.requiresReTint || this.cachedTint !== this.tint)) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + this.refreshTexture = true; + } + + if (this.refreshTexture) + { + this.generateTilingTexture(false, renderSession); + + if (this.tilingTexture) + { + this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat'); + } + else + { + return; + } + } + + var sessionBlendMode = renderSession.currentBlendMode; + + // Check blend mode + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + var tilePosition = this.tilePosition; + var tileScale = this.tileScale; + + tilePosition.x %= this.tilingTexture.baseTexture.width; + tilePosition.y %= this.tilingTexture.baseTexture.height; + + // Translate + context.scale(tileScale.x, tileScale.y); + context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height)); + + context.fillStyle = this.tilePattern; + + tx = -tilePosition.x; + ty = -tilePosition.y; + + var tw = this._width / tileScale.x; + var th = this._height / tileScale.y; + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + tx |= 0; + ty |= 0; + tw |= 0; + th |= 0; + } + + context.fillRect(tx, ty, tw, th); + + // Translate back again + context.scale(1 / tileScale.x, 1 / tileScale.y); + context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height)); + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + // Reset blend mode + if (sessionBlendMode !== this.blendMode) + { + renderSession.currentBlendMode = sessionBlendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode]; + } + +}; + +/** +* Override the Sprite method. +* +* @private +* @method Phaser.TileSprite#onTextureUpdate +* @memberof Phaser.TileSprite +*/ +Phaser.TileSprite.prototype.onTextureUpdate = function () { + + // overriding the sprite version of this! + +}; + +/** +* Internal method that generates a new tiling texture. +* +* @method Phaser.TileSprite#generateTilingTexture +* @memberof Phaser.TileSprite +* @param {boolean} forcePowerOfTwo - Whether we want to force the texture to be a power of two +*/ +Phaser.TileSprite.prototype.generateTilingTexture = function (forcePowerOfTwo) { + + if (!this.texture.baseTexture.hasLoaded) + { + return; + } + + var texture = this.texture; + var frame = texture.frame; + + var targetWidth = this._frame.sourceSizeW || this._frame.width; + var targetHeight = this._frame.sourceSizeH || this._frame.height; + + var dx = 0; + var dy = 0; + + if (this._frame.trimmed) + { + dx = this._frame.spriteSourceSizeX; + dy = this._frame.spriteSourceSizeY; + } + + if (forcePowerOfTwo) + { + targetWidth = Phaser.Math.getNextPowerOfTwo(targetWidth); + targetHeight = Phaser.Math.getNextPowerOfTwo(targetHeight); + } + + if (this.canvasBuffer) + { + this.canvasBuffer.resize(targetWidth, targetHeight); + this.tilingTexture.baseTexture.width = targetWidth; + this.tilingTexture.baseTexture.height = targetHeight; + this.tilingTexture.needsUpdate = true; + } + else + { + this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight); + this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas); + this.tilingTexture.isTiling = true; + this.tilingTexture.needsUpdate = true; + } + + if (this.textureDebug) + { + this.canvasBuffer.context.strokeStyle = '#00ff00'; + this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight); + } + + // If a sprite sheet we need this: + var w = texture.crop.width; + var h = texture.crop.height; + + if (w !== targetWidth || h !== targetHeight) + { + w = targetWidth; + h = targetHeight; + } + + var targetTexture = this.tintedTexture ? this.tintedTexture : texture.baseTexture.source; + + this.canvasBuffer.context.drawImage( + targetTexture, + texture.crop.x, + texture.crop.y, + texture.crop.width, + texture.crop.height, + dx, + dy, + w, + h + ); + + this.tileScaleOffset.x = frame.width / targetWidth; + this.tileScaleOffset.y = frame.height / targetHeight; + + this.refreshTexture = false; + + this.tilingTexture.baseTexture._powerOf2 = true; + +}; + +/** +* Returns the framing rectangle of the Tile Sprite. +* +* @method Phaser.TileSprite#getBounds +* @memberof Phaser.TileSprite +* @return {Phaser.Rectangle} The bounds of the Tile Sprite. +*/ +Phaser.TileSprite.prototype.getBounds = function () { + + var width = this._width; + var height = this._height; + + var w0 = width * (1 - this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1 - this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = (a * w1) + (c * h1) + tx; + var y1 = (d * h1) + (b * w1) + ty; + + var x2 = (a * w0) + (c * h1) + tx; + var y2 = (d * h1) + (b * w0) + ty; + + var x3 = (a * w0) + (c * h0) + tx; + var y3 = (d * h0) + (b * w0) + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // TODO: This is surely always undefined? As it's not set anywhere in the parent objects + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* The width of the sprite, setting this will actually modify the scale to achieve the value set +* +* @property width +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'width', { + + get: function () { + + return this._width; + + }, + + set: function (value) { + + this._width = value; + + } + +}); + +/** +* The height of the TilingSprite, setting this will actually modify the scale to achieve the value set +* +* @property height +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'height', { + + get: function () { + + return this._height; + + }, + + set: function (value) { + + this._height = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The CanvasPool is a global static object, that allows Phaser to recycle and pool Canvas DOM elements. +* +* @class Phaser.CanvasPool +* @static +*/ +Phaser.CanvasPool = { + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @method Phaser.CanvasPool.create + * @static + * @param {any} parent - The parent of the canvas element. + * @param {number} width - The width of the canvas element. + * @param {number} height - The height of the canvas element. + * @return {HTMLCanvasElement} The canvas element. + */ + create: function (parent, width, height) { + + var idx = Phaser.CanvasPool.getFirst(); + var canvas; + + if (idx === -1) + { + var container = { + parent: parent, + canvas: document.createElement('canvas') + }; + + Phaser.CanvasPool.pool.push(container); + + canvas = container.canvas; + } + else + { + Phaser.CanvasPool.pool[idx].parent = parent; + + canvas = Phaser.CanvasPool.pool[idx].canvas; + } + + if (width !== undefined) + { + canvas.width = width; + canvas.height = height; + } + + return canvas; + + }, + + /** + * Gets the first free canvas index from the pool. + * + * @static + * @method Phaser.CanvasPool.getFirst + * @return {number} + */ + getFirst: function () { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + return i; + } + } + + return -1; + + }, + + /** + * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.remove + * @param {any} parent - The parent of the canvas element. + */ + remove: function (parent) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent === parent) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Looks up a canvas based on its type, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.removeByCanvas + * @param {HTMLCanvasElement} canvas - The canvas element to remove. + */ + removeByCanvas: function (canvas) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].canvas === canvas) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Gets the total number of used canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getTotal + * @return {number} The number of in-use (parented) canvas elements in the pool. + */ + getTotal: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent) + { + c++; + } + } + + return c; + + }, + + /** + * Gets the total number of free canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getFree + * @return {number} The number of free (un-parented) canvas elements in the pool. + */ + getFree: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + c++; + } + } + + return c; + + }, + + + /** + * Prints in-use, free, and total counts to console.log. + * + * @static + * @method Phaser.CanvasPool.log + */ + log: function () { + + console.log('CanvasPool: %s used, %s free, %s total', this.getTotal(), this.getFree(), this.pool.length); + + } + +}; + +/** + * The pool into which the canvas elements are placed. + * + * @property pool + * @type Array + * @static + */ +Phaser.CanvasPool.pool = []; + + +/** + * The total number of canvas elements in the {@link Phaser.CanvasPool.pool pool}. + * + * @property length + * @type number + * @static + * @readonly + */ +Object.defineProperty(Phaser.CanvasPool, 'length', { + get: function () { + return this.pool.length; + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}. +* +* This class represents a singleton object that can be accessed directly as `game.device` +* (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it. +* +* Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization +* occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase. +* Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal, e.g., +* +* ```javascript +* Phaser.Device.onInitialized.add(function (device) { +* +* device.canvasBitBltShift = true; +* device.mspointer = false; +* +* }); +* +* var game = new Phaser.Game(); +* ``` +* +* When checking features using the exposed properties only the *truth-iness* of the value should be relied upon +* unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined` +* when indicating the lack of a feature. +* +* Uses elements from System.js by MrDoob and Modernizr +* +* @description +* It is not possible to instantiate the Device class manually. +* +* @class +* @protected +*/ +Phaser.Device = function () { + + /** + * The time the device became ready. + * @property {integer} deviceReadyAt + * @protected + */ + this.deviceReadyAt = 0; + + /** + * The time as which initialization has completed. + * @property {boolean} initialized + * @protected + */ + this.initialized = false; + + // Browser / Host / Operating System + + /** + * @property {boolean} desktop - Is running on a desktop? + * @default + */ + this.desktop = false; + + /** + * @property {boolean} iOS - Is running on iOS? + * @default + */ + this.iOS = false; + + /** + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @default + */ + this.iOSVersion = 0; + + /** + * @property {boolean} cocoonJS - Is the game running under CocoonJS? + * @default + */ + this.cocoonJS = false; + + /** + * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App? + * @default + */ + this.cocoonJSApp = false; + + /** + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @default + */ + this.cordova = false; + + /** + * @property {boolean} node - Is the game running under Node.js? + * @default + */ + this.node = false; + + /** + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @default + */ + this.nodeWebkit = false; + + /** + * @property {boolean} electron - Is the game running under GitHub Electron? + * @default + */ + this.electron = false; + + /** + * @property {boolean} ejecta - Is the game running under Ejecta? + * @default + */ + this.ejecta = false; + + /** + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @default + */ + this.crosswalk = false; + + /** + * @property {boolean} android - Is running on android? + * @default + */ + this.android = false; + + /** + * @property {boolean} chromeOS - Is running on chromeOS? + * @default + */ + this.chromeOS = false; + + /** + * @property {boolean} linux - Is running on linux? + * @default + */ + this.linux = false; + + /** + * @property {boolean} macOS - Is running on macOS? + * @default + */ + this.macOS = false; + + /** + * @property {boolean} windows - Is running on windows? + * @default + */ + this.windows = false; + + /** + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @default + */ + this.windowsPhone = false; + + // Features + + /** + * @property {boolean} canvas - Is canvas available? + * @default + */ + this.canvas = false; + + /** + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @default + */ + this.canvasBitBltShift = null; + + /** + * If the browser isn't capable of handling tinting with alpha this will be false. + * @property {boolean} canHandleAlpha + * @default + */ + this.canHandleAlpha = false; + + /** + * Whether or not the {@link http://caniuse.com/#feat=canvas-blending Canvas Blend Modes} are supported, consequently the ability to tint using the multiply method. + * + * Expect `false` in Internet Explorer <= 11. + * + * @property {boolean} canUseMultiply + * @default + */ + this.canUseMultiply = false; + + /** + * @property {boolean} webGL - Is webGL available? + * @default + */ + this.webGL = false; + + /** + * @property {boolean} file - Is file available? + * @default + */ + this.file = false; + + /** + * @property {boolean} fileSystem - Is fileSystem available? + * @default + */ + this.fileSystem = false; + + /** + * @property {boolean} localStorage - Is localStorage available? + * @default + */ + this.localStorage = false; + + /** + * @property {boolean} worker - Is worker available? + * @default + */ + this.worker = false; + + /** + * @property {boolean} css3D - Is css3D available? + * @default + */ + this.css3D = false; + + /** + * @property {boolean} pointerLock - Is Pointer Lock available? + * @default + */ + this.pointerLock = false; + + /** + * @property {boolean} typedArray - Does the browser support TypedArrays? + * @default + */ + this.typedArray = false; + + /** + * @property {boolean} vibration - Does the device support the Vibration API? + * @default + */ + this.vibration = false; + + /** + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @default + */ + this.getUserMedia = true; + + /** + * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true) + * @default + */ + this.quirksMode = false; + + // Input + + /** + * @property {boolean} touch - Is touch available? + * @default + */ + this.touch = false; + + /** + * @property {boolean} mspointer - Is mspointer available? + * @default + */ + this.mspointer = false; + + /** + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @default + * @protected + */ + this.wheelEvent = null; + + // Browser + + /** + * @property {boolean} arora - Set to true if running in Arora. + * @default + */ + this.arora = false; + + /** + * @property {boolean} chrome - Set to true if running in Chrome. + * @default + */ + this.chrome = false; + + /** + * @property {number} chromeVersion - If running in Chrome this will contain the major version number. + * @default + */ + this.chromeVersion = 0; + + /** + * @property {boolean} epiphany - Set to true if running in Epiphany. + * @default + */ + this.epiphany = false; + + /** + * @property {boolean} firefox - Set to true if running in Firefox. + * @default + */ + this.firefox = false; + + /** + * @property {number} firefoxVersion - If running in Firefox this will contain the major version number. + * @default + */ + this.firefoxVersion = 0; + + /** + * @property {boolean} ie - Set to true if running in Internet Explorer. + * @default + */ + this.ie = false; + + /** + * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. + * @default + */ + this.ieVersion = 0; + + /** + * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+) + * @default + */ + this.trident = false; + + /** + * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx} + * @default + */ + this.tridentVersion = 0; + + /** + * @property {boolean} edge - Set to true if running in Microsoft Edge browser. + * @default + */ + this.edge = false; + + /** + * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. + * @default + */ + this.mobileSafari = false; + + /** + * @property {boolean} midori - Set to true if running in Midori. + * @default + */ + this.midori = false; + + /** + * @property {boolean} opera - Set to true if running in Opera. + * @default + */ + this.opera = false; + + /** + * @property {boolean} safari - Set to true if running in Safari. + * @default + */ + this.safari = false; + + /** + * @property {number} safariVersion - If running in Safari this will contain the major version number. + * @default + */ + this.safariVersion = 0; + + /** + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @default + */ + this.webApp = false; + + /** + * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle) + * @default + */ + this.silk = false; + + // Audio + + /** + * @property {boolean} audioData - Are Audio tags available? + * @default + */ + this.audioData = false; + + /** + * @property {boolean} webAudio - Is the WebAudio API available? + * @default + */ + this.webAudio = false; + + /** + * @property {boolean} ogg - Can this device play ogg files? + * @default + */ + this.ogg = false; + + /** + * @property {boolean} opus - Can this device play opus files? + * @default + */ + this.opus = false; + + /** + * @property {boolean} mp3 - Can this device play mp3 files? + * @default + */ + this.mp3 = false; + + /** + * @property {boolean} wav - Can this device play wav files? + * @default + */ + this.wav = false; + + /** + * Can this device play m4a files? + * @property {boolean} m4a - True if this device can play m4a files. + * @default + */ + this.m4a = false; + + /** + * @property {boolean} webm - Can this device play webm files? + * @default + */ + this.webm = false; + + /** + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @default + */ + this.dolby = false; + + // Video + + /** + * @property {boolean} oggVideo - Can this device play ogg video files? + * @default + */ + this.oggVideo = false; + + /** + * @property {boolean} h264Video - Can this device play h264 mp4 video files? + * @default + */ + this.h264Video = false; + + /** + * @property {boolean} mp4Video - Can this device play h264 mp4 video files? + * @default + */ + this.mp4Video = false; + + /** + * @property {boolean} webmVideo - Can this device play webm video files? + * @default + */ + this.webmVideo = false; + + /** + * @property {boolean} vp9Video - Can this device play vp9 video files? + * @default + */ + this.vp9Video = false; + + /** + * @property {boolean} hlsVideo - Can this device play hls video files? + * @default + */ + this.hlsVideo = false; + + // Device + + /** + * @property {boolean} iPhone - Is running on iPhone? + * @default + */ + this.iPhone = false; + + /** + * @property {boolean} iPhone4 - Is running on iPhone4? + * @default + */ + this.iPhone4 = false; + + /** + * @property {boolean} iPad - Is running on iPad? + * @default + */ + this.iPad = false; + + // Device features + + /** + * @property {number} pixelRatio - PixelRatio of the host device? + * @default + */ + this.pixelRatio = 0; + + /** + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @default + */ + this.littleEndian = false; + + /** + * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`. + * @default + */ + this.LITTLE_ENDIAN = false; + + /** + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @default + */ + this.support32bit = false; + + /** + * @property {boolean} fullscreen - Does the browser support the Full Screen API? + * @default + */ + this.fullscreen = false; + + /** + * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it. + * @default + */ + this.requestFullscreen = ''; + + /** + * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @default + */ + this.cancelFullscreen = ''; + + /** + * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @default + */ + this.fullscreenKeyboard = false; + +}; + +// Device is really a singleton/static entity; instantiate it +// and add new methods directly sans-prototype. +Phaser.Device = new Phaser.Device(); + +/** +* This signal is dispatched after device initialization occurs but before any of the ready +* callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked. +* +* Local "patching" for a particular device can/should be done in this event. +* +* _Note_: This signal is removed after the device has been readied; if a handler has not been +* added _before_ `new Phaser.Game(..)` it is probably too late. +* +* @type {?Phaser.Signal} +* @static +*/ +Phaser.Device.onInitialized = new Phaser.Signal(); + +/** +* Add a device-ready handler and ensure the device ready sequence is started. +* +* Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added, +* which is normally done automatically be calling `new Phaser.Game(..)`. +* +* The handler is invoked when the device is considered "ready", which may be immediately +* if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}. +* +* @method +* @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. +* @param {object} [context] - Context in which to invoke the handler +* @param {boolean} [nonPrimer=false] - If true the device ready check will not be started. +*/ +Phaser.Device.whenReady = function (callback, context, nonPrimer) { + + var readyCheck = this._readyCheck; + + if (this.deviceReadyAt || !readyCheck) + { + callback.call(context, this); + } + else if (readyCheck._monitor || nonPrimer) + { + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + } + else + { + readyCheck._monitor = readyCheck.bind(this); + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + + var cordova = typeof window.cordova !== 'undefined'; + var cocoonJS = navigator['isCocoonJS']; + + if (document.readyState === 'complete' || document.readyState === 'interactive') + { + // Why is there an additional timeout here? + window.setTimeout(readyCheck._monitor, 0); + } + else if (cordova && !cocoonJS) + { + // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + // Cordova, but NOT Cocoon? + document.addEventListener('deviceready', readyCheck._monitor, false); + } + else + { + document.addEventListener('DOMContentLoaded', readyCheck._monitor, false); + window.addEventListener('load', readyCheck._monitor, false); + } + } + +}; + +/** +* Internal method used for checking when the device is ready. +* This function is removed from Phaser.Device when the device becomes ready. +* +* @method +* @private +*/ +Phaser.Device._readyCheck = function () { + + var readyCheck = this._readyCheck; + + if (!document.body) + { + window.setTimeout(readyCheck._monitor, 20); + } + else if (!this.deviceReadyAt) + { + this.deviceReadyAt = Date.now(); + + document.removeEventListener('deviceready', readyCheck._monitor); + document.removeEventListener('DOMContentLoaded', readyCheck._monitor); + window.removeEventListener('load', readyCheck._monitor); + + this._initialize(); + this.initialized = true; + + this.onInitialized.dispatch(this); + + var item; + while ((item = readyCheck._queue.shift())) + { + var callback = item[0]; + var context = item[1]; + callback.call(context, this); + } + + // Remove no longer useful methods and properties. + this._readyCheck = null; + this._initialize = null; + this.onInitialized = null; + } + +}; + +/** +* Internal method to initialize the capability checks. +* This function is removed from Phaser.Device once the device is initialized. +* +* @method +* @private +*/ +Phaser.Device._initialize = function () { + + var device = this; + + /** + * Check which OS is game running on. + */ + function _checkOS () { + + var ua = navigator.userAgent; + + if (/Playstation Vita/.test(ua)) + { + device.vita = true; + } + else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua)) + { + device.kindle = true; + // This will NOT detect early generations of Kindle Fire, I think there is no reliable way... + // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true" + } + else if (/Android/.test(ua)) + { + device.android = true; + } + else if (/CrOS/.test(ua)) + { + device.chromeOS = true; + } + else if (/iP[ao]d|iPhone/i.test(ua)) + { + device.iOS = true; + (navigator.appVersion).match(/OS (\d+)/); + device.iOSVersion = parseInt(RegExp.$1, 10); + } + else if (/Linux/.test(ua)) + { + device.linux = true; + } + else if (/Mac OS/.test(ua)) + { + device.macOS = true; + } + else if (/Windows/.test(ua)) + { + device.windows = true; + } + + if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua)) + { + device.android = false; + device.iOS = false; + device.macOS = false; + device.windows = true; + device.windowsPhone = true; + } + + var silk = /Silk/.test(ua); // detected in browsers + + if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS) + { + device.desktop = true; + } + + // Windows Phone / Table reset + if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) + { + device.desktop = false; + } + + } + + /** + * Checks if the browser correctly supports putImageData alpha channels. + * If the browser isn't capable of handling tinting with alpha, `Device.canHandleAlpha` will be false. + * Also checks whether the Canvas BlendModes are supported by the current browser for drawImage. + */ + function _checkCanvasFeatures () { + + var canvas = Phaser.CanvasPool.create(this, 6, 1); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgba(10, 20, 30, 0.5)'; + + // Draw a single pixel + context.fillRect(0, 0, 1, 1); + + // Get the color values + var s1 = context.getImageData(0, 0, 1, 1); + + if (s1) + { + // Plot them to x2 + context.putImageData(s1, 1, 0); + + // Get those values + var s2 = context.getImageData(1, 0, 1, 1); + + // Compare and set + device.canHandleAlpha = ( + s2.data[0] === s1.data[0] && + s2.data[1] === s1.data[1] && + s2.data[2] === s1.data[2] && + s2.data[3] === s1.data[3] + ); + } + + // Checks whether the Canvas BlendModes are supported by the current browser for drawImage. + context.globalCompositeOperation = 'multiply'; + device.canUseMultiply = (context.globalCompositeOperation === 'multiply'); + + Phaser.CanvasPool.removeByCanvas(canvas); + + PIXI.CanvasTinter.tintMethod = (device.canUseMultiply) ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel; + + } + + /** + * Check HTML5 features of the host environment. + */ + function _checkFeatures () { + + device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS; + + try { + device.localStorage = !!localStorage.getItem; + } catch (error) { + device.localStorage = false; + } + + device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; + device.fileSystem = !!window['requestFileSystem']; + + device.webGL = !!window.WebGLRenderingContext; + + device.worker = !!window['Worker']; + + device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; + + device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL; + + // Older versions of firefox (< 21) apparently claim support but user media does not actually work + if (device.firefox && device.firefoxVersion < 21) + { + device.getUserMedia = false; + } + + // TODO: replace canvasBitBltShift detection with actual feature check + + // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it + // is safer to not try and use the fast copy-over method. + if (!device.iOS && (device.ie || device.firefox || device.chrome)) + { + device.canvasBitBltShift = true; + } + + // Known not to work + if (device.safari || device.mobileSafari) + { + device.canvasBitBltShift = false; + } + + } + + /** + * Checks/configures various input. + */ + function _checkInput () { + + if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1)) + { + device.touch = true; + } + + if (window.PointerEvent || window.MSPointerEvent || window.navigator.msPointerEnabled || window.navigator.pointerEnabled) + { + device.mspointer = true; + } + + if (!device.cocoonJS) + { + // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel + if ('onwheel' in window || (device.ie && 'WheelEvent' in window)) + { + // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ + device.wheelEvent = 'wheel'; + } + else if ('onmousewheel' in window) + { + // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. + device.wheelEvent = 'mousewheel'; + } + else if (device.firefox && 'MouseScrollEvent' in window) + { + // FF prior to 17. This should probably be scrubbed. + device.wheelEvent = 'DOMMouseScroll'; + } + } + + } + + /** + * Checks for support of the Full Screen API. + */ + function _checkFullScreenSupport () { + + var fs = [ + 'requestFullscreen', + 'requestFullScreen', + 'webkitRequestFullscreen', + 'webkitRequestFullScreen', + 'msRequestFullscreen', + 'msRequestFullScreen', + 'mozRequestFullScreen', + 'mozRequestFullscreen' + ]; + + var element = document.createElement('div'); + + for (var i = 0; i < fs.length; i++) + { + if (element[fs[i]]) + { + device.fullscreen = true; + device.requestFullscreen = fs[i]; + break; + } + } + + var cfs = [ + 'cancelFullScreen', + 'exitFullscreen', + 'webkitCancelFullScreen', + 'webkitExitFullscreen', + 'msCancelFullScreen', + 'msExitFullscreen', + 'mozCancelFullScreen', + 'mozExitFullscreen' + ]; + + if (device.fullscreen) + { + for (var i = 0; i < cfs.length; i++) + { + if (document[cfs[i]]) + { + device.cancelFullscreen = cfs[i]; + break; + } + } + } + + // Keyboard Input? + if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT']) + { + device.fullscreenKeyboard = true; + } + + } + + /** + * Check what browser is game running in. + */ + function _checkBrowser () { + + var ua = navigator.userAgent; + + if (/Arora/.test(ua)) + { + device.arora = true; + } + else if (/Edge\/\d+/.test(ua)) + { + device.edge = true; + } + else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.chrome = true; + device.chromeVersion = parseInt(RegExp.$1, 10); + } + else if (/Epiphany/.test(ua)) + { + device.epiphany = true; + } + else if (/Firefox\D+(\d+)/.test(ua)) + { + device.firefox = true; + device.firefoxVersion = parseInt(RegExp.$1, 10); + } + else if (/AppleWebKit/.test(ua) && device.iOS) + { + device.mobileSafari = true; + } + else if (/MSIE (\d+\.\d+);/.test(ua)) + { + device.ie = true; + device.ieVersion = parseInt(RegExp.$1, 10); + } + else if (/Midori/.test(ua)) + { + device.midori = true; + } + else if (/Opera/.test(ua)) + { + device.opera = true; + } + else if (/Safari\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.safari = true; + + if (/Version\/(\d+)\./.test(ua)) + { + device.safariVersion = parseInt(RegExp.$1, 10); + } + } + else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua)) + { + device.ie = true; + device.trident = true; + device.tridentVersion = parseInt(RegExp.$1, 10); + device.ieVersion = parseInt(RegExp.$3, 10); + } + + // Silk gets its own if clause because its ua also contains 'Safari' + if (/Silk/.test(ua)) + { + device.silk = true; + } + + // WebApp mode in iOS + if (navigator['standalone']) + { + device.webApp = true; + } + + if (typeof window.cordova !== 'undefined') + { + device.cordova = true; + } + + if (typeof process !== 'undefined' && typeof require !== 'undefined') + { + device.node = true; + } + + if (device.node && typeof process.versions === 'object') + { + device.nodeWebkit = !!process.versions['node-webkit']; + + device.electron = !!process.versions.electron; + } + + if (navigator['isCocoonJS']) + { + device.cocoonJS = true; + } + + if (device.cocoonJS) + { + try { + device.cocoonJSApp = (typeof CocoonJS !== 'undefined'); + } + catch(error) + { + device.cocoonJSApp = false; + } + } + + if (typeof window.ejecta !== 'undefined') + { + device.ejecta = true; + } + + if (/Crosswalk/.test(ua)) + { + device.crosswalk = true; + } + + } + + /** + * Check video support. + */ + function _checkVideo () { + + var videoElement = document.createElement("video"); + var result = false; + + try { + if (result = !!videoElement.canPlayType) + { + if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) + { + device.oggVideo = true; + } + + if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + device.h264Video = true; + device.mp4Video = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) + { + device.webmVideo = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) + { + device.vp9Video = true; + } + + if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + device.hlsVideo = true; + } + } + } catch (e) {} + } + + /** + * Check audio support. + */ + function _checkAudio () { + + device.audioData = !!(window['Audio']); + device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); + var audioElement = document.createElement('audio'); + var result = false; + + try { + if (result = !!audioElement.canPlayType) + { + if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) + { + device.ogg = true; + } + + if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) + { + device.opus = true; + } + + if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) + { + device.mp3 = true; + } + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) + { + device.wav = true; + } + + if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) + { + device.m4a = true; + } + + if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) + { + device.webm = true; + } + + if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') + { + if (device.edge) + { + device.dolby = true; + } + else if (device.safari && device.safariVersion >= 9) + { + if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)) + { + var major = parseInt(RegExp.$1, 10); + var minor = parseInt(RegExp.$2, 10); + + if ((major === 10 && minor >= 11) || major > 10) + { + device.dolby = true; + } + } + } + } + } + } catch (e) { + } + + } + + /** + * Check Little or Big Endian system. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsLittleEndian () { + + var a = new ArrayBuffer(4); + var b = new Uint8Array(a); + var c = new Uint32Array(a); + + b[0] = 0xa1; + b[1] = 0xb2; + b[2] = 0xc3; + b[3] = 0xd4; + + if (c[0] === 0xd4c3b2a1) + { + return true; + } + + if (c[0] === 0xa1b2c3d4) + { + return false; + } + else + { + // Could not determine endianness + return null; + } + + } + + /** + * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsUint8ClampedImageData () { + + if (Uint8ClampedArray === undefined) + { + return false; + } + + var elem = Phaser.CanvasPool.create(this, 1, 1); + var ctx = elem.getContext('2d'); + + if (!ctx) + { + return false; + } + + var image = ctx.createImageData(1, 1); + + Phaser.CanvasPool.remove(this); + + return image.data instanceof Uint8ClampedArray; + + } + + /** + * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess. + */ + function _checkDevice () { + + device.pixelRatio = window['devicePixelRatio'] || 1; + device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1; + device.iPhone4 = (device.pixelRatio === 2 && device.iPhone); + device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') !== -1; + + if (typeof Int8Array !== 'undefined') + { + device.typedArray = true; + } + else + { + device.typedArray = false; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') + { + device.littleEndian = _checkIsLittleEndian(); + device.LITTLE_ENDIAN = device.littleEndian; + } + + device.support32bit = (typeof ArrayBuffer !== 'undefined' && typeof Uint8ClampedArray !== 'undefined' && typeof Int32Array !== 'undefined' && device.littleEndian !== null && _checkIsUint8ClampedImageData()); + + navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; + + if (navigator.vibrate) + { + device.vibration = true; + } + + } + + /** + * Check whether the host environment support 3D CSS. + */ + function _checkCSS3D () { + + var el = document.createElement('p'); + var has3d; + var transforms = { + 'webkitTransform': '-webkit-transform', + 'OTransform': '-o-transform', + 'msTransform': '-ms-transform', + 'MozTransform': '-moz-transform', + 'transform': 'transform' + }; + + // Add it to the body to get the computed style. + document.body.insertBefore(el, null); + + for (var t in transforms) + { + if (el.style[t] !== undefined) + { + el.style[t] = "translate3d(1px,1px,1px)"; + has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]); + } + } + + document.body.removeChild(el); + device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none"); + + } + + // Run the checks + _checkOS(); + _checkBrowser(); + _checkAudio(); + _checkVideo(); + _checkCSS3D(); + _checkDevice(); + _checkFeatures(); + _checkCanvasFeatures(); + _checkFullScreenSupport(); + _checkInput(); + +}; + +/** +* Check whether the host environment can play audio. +* +* @method canPlayAudio +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.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 === 'opus' && this.opus) + { + return true; + } + else if (type === 'wav' && this.wav) + { + return true; + } + else if (type === 'webm' && this.webm) + { + return true; + } + else if (type === 'mp4' && this.dolby) + { + return true; + } + + return false; + +}; + +/** +* Check whether the host environment can play video files. +* +* @method canPlayVideo +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.canPlayVideo = function (type) { + + if (type === 'webm' && (this.webmVideo || this.vp9Video)) + { + return true; + } + else if (type === 'mp4' && (this.mp4Video || this.h264Video)) + { + return true; + } + else if ((type === 'ogg' || type === 'ogv') && this.oggVideo) + { + return true; + } + else if (type === 'mpeg' && this.hlsVideo) + { + return true; + } + + return false; + +}; + +/** + * Whether the device plays audio/video only in response to a user touch event. + * + * @method needsTouchUnlock + * @memberof Phaser.Device.prototype + * @return {boolean} + */ +Phaser.Device.needsTouchUnlock = function () { + return !!(!this.cocoonJS && (this.iOS || this.android) || (window.PhaserGlobal && window.PhaserGlobal.fakeiOSTouchLock)); +}; + +/** +* Detect if the host is a an Android Stock browser. +* This is available before the device "ready" event. +* +* Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. +* +* @example +* var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; +* +* @method isAndroidStockBrowser +* @memberof Phaser.Device.prototype +*/ +Phaser.Device.isAndroidStockBrowser = function () { + + var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/); + return matches && matches[1] < 537; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, +* including styles, offset and aspect ratio. +* +* @class Phaser.Canvas +* @static +*/ +Phaser.Canvas = { + + /** + * Creates a `canvas` DOM element. The element is not automatically added to the document. + * + * @method Phaser.Canvas.create + * @param {object} parent - The object that will own the canvas that is created. + * @param {number} [width=256] - The width of the canvas element. + * @param {number} [height=256] - The height of the canvas element.. + * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. + * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global. + * @return {HTMLCanvasElement} The newly created canvas element. + */ + create: function (parent, width, height, id, skipPool) { + + width = width || 256; + height = height || 256; + + var canvas = (skipPool) ? document.createElement('canvas') : Phaser.CanvasPool.create(parent, width, height); + + if (typeof id === 'string' && id !== '') + { + canvas.id = id; + } + + canvas.width = width; + canvas.height = height; + canvas.style.display = 'block'; + + return canvas; + + }, + + /** + * Sets the background color behind the canvas. This changes the canvas style property. + * + * @method Phaser.Canvas.setBackgroundColor + * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. + * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setBackgroundColor: function (canvas, color) { + + color = color || 'rgb(0,0,0)'; + + canvas.style.backgroundColor = color; + + return canvas; + + }, + + /** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @method Phaser.Canvas.setTouchAction + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @method Phaser.Canvas.setUserSelect + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. + * If no parent is given it will be added as a child of the document.body. + * + * @method Phaser.Canvas.addToDOM + * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM. + * @param {string|HTMLElement} parent - The DOM element to add the canvas to. + * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + addToDOM: function (canvas, parent, overflowHidden) { + + var target; + + if (overflowHidden === undefined) { overflowHidden = true; } + + if (parent) + { + if (typeof parent === 'string') + { + // hopefully an element ID + target = document.getElementById(parent); + } + else if (typeof parent === 'object' && parent.nodeType === 1) + { + // quick test for a HTMLelement + target = parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + target = document.body; + } + + if (overflowHidden && target.style) + { + target.style.overflow = 'hidden'; + } + + target.appendChild(canvas); + + return canvas; + + }, + + /** + * Removes the given canvas element from the DOM. + * + * @method Phaser.Canvas.removeFromDOM + * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM. + */ + removeFromDOM: function (canvas) { + + if (canvas.parentNode) + { + canvas.parentNode.removeChild(canvas); + } + + }, + + /** + * Sets the transform of the given canvas to the matrix values provided. + * + * @method Phaser.Canvas.setTransform + * @param {CanvasRenderingContext2D} context - The context to set the transform on. + * @param {number} translateX - The value to translate horizontally by. + * @param {number} translateY - The value to translate vertically by. + * @param {number} scaleX - The value to scale horizontally by. + * @param {number} scaleY - The value to scale vertically by. + * @param {number} skewX - The value to skew horizontaly by. + * @param {number} skewY - The value to skew vertically by. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) { + + context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); + + return context; + + }, + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @method Phaser.Canvas.setSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setSmoothingEnabled: function (context, value) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + context[s] = value; + } + + return context; + + }, + + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @method Phaser.Canvas.getSmoothingPrefix + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context. + */ + getSmoothingPrefix: function (context) { + + var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; + + for (var prefix in vendor) + { + var s = vendor[prefix] + 'mageSmoothingEnabled'; + + if (s in context) + { + return s; + } + } + + return null; + + }, + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * + * @method Phaser.Canvas.getSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to check for smoothing on. + * @return {boolean} True if the given context has image smoothing enabled, otherwise false. + */ + getSmoothingEnabled: function (context) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + return context[s]; + } + + }, + + /** + * Sets the CSS image-rendering property to `pixelated` or `crisp-edges`. + * This can remove blurring when the game canvas is scaled up. + * In some browsers this has no visible effect in WEBGL mode. + * Note that if this doesn't given the desired result then see the setSmoothingEnabled. + * + * @method Phaser.Canvas.setImageRenderingCrisp + * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. + * @return {HTMLCanvasElement} Returns the source canvas. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering + * @see https://caniuse.com/#feat=css-crisp-edges + */ + setImageRenderingCrisp: function (canvas) { + + var types = [ '-webkit-optimize-contrast', '-moz-crisp-edges', 'crisp-edges', 'pixelated' ]; + + for (var i = 0; i < types.length; i++) + { + canvas.style['image-rendering'] = types[i]; + } + + canvas.style.msInterpolationMode = 'nearest-neighbor'; + + return canvas; + + }, + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method Phaser.Canvas.setImageRenderingBicubic + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setImageRenderingBicubic: function (canvas) { + + canvas.style['image-rendering'] = 'auto'; + canvas.style.msInterpolationMode = 'bicubic'; + + return canvas; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Abstracts away the use of RAF or setTimeOut for the core game update loop. +* +* @class Phaser.RequestAnimationFrame +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available. +*/ +Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) { + + if (forceSetTimeOut === undefined) { forceSetTimeOut = false; } + + /** + * @property {Phaser.Game} game - The currently running game. + */ + this.game = game; + + /** + * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available. + */ + this.forceSetTimeOut = forceSetTimeOut; + + var vendors = [ + 'ms', + 'moz', + 'webkit', + 'o' + ]; + + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) + { + window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; + } + + /** + * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. + * @private + */ + this._isSetTimeOut = false; + + /** + * @property {function} _onLoop - The function called by the update. + * @private + */ + this._onLoop = null; + + /** + * @property {number} _timeOutID - The callback ID used when calling cancel. + * @private + */ + this._timeOutID = null; + +}; + +Phaser.RequestAnimationFrame.prototype = { + + /** + * Starts the requestAnimationFrame running or setTimeout if unavailable in browser + * @method Phaser.RequestAnimationFrame#start + */ + start: function () { + + this.isRunning = true; + + var _this = this; + + if (!window.requestAnimationFrame || this.forceSetTimeOut) + { + this._isSetTimeOut = true; + + this._onLoop = function () { + return _this.updateSetTimeout(); + }; + + this._timeOutID = window.setTimeout(this._onLoop, 0); + } + else + { + this._isSetTimeOut = false; + + this._onLoop = function (time) { + return _this.updateRAF(time); + }; + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the requestAnimationFrame + * @method Phaser.RequestAnimationFrame#updateRAF + */ + updateRAF: function (rafTime) { + + if (this.isRunning) + { + // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below) + this.game.update(Math.floor(rafTime)); + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the setTimeout. + * @method Phaser.RequestAnimationFrame#updateSetTimeout + */ + updateSetTimeout: function () { + + if (this.isRunning) + { + this.game.update(Date.now()); + + this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); + } + + }, + + /** + * Stops the requestAnimationFrame from running. + * @method Phaser.RequestAnimationFrame#stop + */ + stop: function () { + + if (this._isSetTimeOut) + { + clearTimeout(this._timeOutID); + } + else + { + window.cancelAnimationFrame(this._timeOutID); + } + + this.isRunning = false; + + }, + + /** + * Is the browser using setTimeout? + * @method Phaser.RequestAnimationFrame#isSetTimeOut + * @return {boolean} + */ + isSetTimeOut: function () { + return this._isSetTimeOut; + }, + + /** + * Is the browser using requestAnimationFrame? + * @method Phaser.RequestAnimationFrame#isRAF + * @return {boolean} + */ + isRAF: function () { + return (this._isSetTimeOut === false); + } + +}; + +Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of useful mathematical functions. +* +* These are normally accessed through `game.math`. +* +* @class Phaser.Math +* @static +* @see {@link Phaser.Utils} +* @see {@link Phaser.ArrayUtils} +*/ +Phaser.Math = { + + /** + * Twice PI. + * @property {number} Phaser.Math#PI2 + * @default ~6.283 + */ + PI2: Math.PI * 2, + + /** + * Half PI. + * @property {number} Phaser.Math#HALF_PI + * @default ~1.570 + */ + HALF_PI: Math.PI * 0.5, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#DEG_TO_RAD + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#RAD_TO_DEG + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * Convert degrees to radians. + * + * @method Phaser.Math#degToRad + * @param {number} degrees - Angle in degrees. + * @return {number} Angle in radians. + */ + degToRad: function (degrees) { + + return degrees * Phaser.Math.DEG_TO_RAD; + + }, + + /** + * Convert radians to degrees. + * + * @method Phaser.Math#radToDeg + * @param {number} radians - Angle in radians. + * @return {number} Angle in degrees + */ + radToDeg: function (radians) { + + return radians * Phaser.Math.RAD_TO_DEG; + + }, + + /** + * Given a number, this function returns the closest number that is a power of two. + * This function is from the Starling Framework. + * + * @method Phaser.Math#getNextPowerOfTwo + * @param {number} value - The value to get the closest power of two from. + * @return {number} The closest number that is a power of two. + */ + getNextPowerOfTwo: function (value) { + + if (value > 0 && (value & (value - 1)) === 0) + { + // http://goo.gl/D9kPj + return value; + } + else + { + var result = 1; + + while (result < value) + { + result <<= 1; + } + + return result; + } + + }, + + /** + * Checks if the given dimensions make a power of two texture. + * + * @method Phaser.Math#isPowerOfTwo + * @param {number} width - The width to check. + * @param {number} height - The height to check. + * @return {boolean} True if the width and height are a power of two. + */ + isPowerOfTwo: function (width, height) { + + return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); + + }, + + /** + * Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#random + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} A floating point number between min (inclusive) and max (exclusive). + */ + random: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + return (Math.random() * (max - min) + min); + + }, + + /** + * Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#between + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} An integer between min (inclusive) and max (inclusive). + */ + between: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + min = Math.ceil(min); + max = Math.floor(max); + + return Math.floor(Math.random() * (max - min + 1)) + min; + + }, + + /** + * Two number are fuzzyEqual if their difference is less than epsilon. + * + * @method Phaser.Math#fuzzyEqual + * @param {number} a - The first number to compare. + * @param {number} b - The second number to compare. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {boolean} True if |a-b|b+epsilon + */ + fuzzyGreaterThan: function (a, b, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return a > b - epsilon; + + }, + + /** + * Applies a fuzzy ceil to the given value. + * + * @method Phaser.Math#fuzzyCeil + * @param {number} val - The value to ceil. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} ceiling(val-epsilon) + */ + fuzzyCeil: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.ceil(val - epsilon); + + }, + + /** + * Applies a fuzzy floor to the given value. + * + * @method Phaser.Math#fuzzyFloor + * @param {number} val - The value to floor. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} floor(val+epsilon) + */ + fuzzyFloor: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.floor(val + epsilon); + + }, + + /** + * Averages all values passed to the function and returns the result. + * + * @method Phaser.Math#average + * @params {...number} The numbers to average + * @return {number} The average of all given values. + */ + average: function () { + + var sum = 0; + var len = arguments.length; + + for (var i = 0; i < len; i++) + { + sum += (+arguments[i]); + } + + return sum / len; + + }, + + /** + * @method Phaser.Math#shear + * @param {number} n + * @return {number} n mod 1 + */ + shear: function (n) { + + return n % 1; + + }, + + /** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. + * + * @method Phaser.Math#snapTo + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapTo: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.round(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. + * As will 14 snap to 10... but 16 will snap to 15. + * + * @method Phaser.Math#snapToFloor + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToFloor: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.floor(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. + * As will 14 will snap to 15... but 16 will snap to 20. + * + * @method Phaser.Math#snapToCeil + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToCeil: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.ceil(input / gap); + + return start + input; + + }, + + /** + * Round to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) === 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + * + * @method Phaser.Math#roundTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + roundTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.round(value * p) / p; + + }, + + /** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#floorTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + floorTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.floor(value * p) / p; + + }, + + /** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#ceilTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + ceilTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.ceil(value * p) / p; + + }, + + /** + * Rotates currentAngle towards targetAngle, taking the shortest rotation distance. + * The lerp argument is the amount to rotate by in this call. + * + * @method Phaser.Math#rotateToAngle + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * @return {number} The adjusted angle. + */ + rotateToAngle: function (currentAngle, targetAngle, lerp) { + + if (lerp === undefined) { lerp = 0.05; } + + if (currentAngle === targetAngle) + { + return currentAngle; + } + + if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (Phaser.Math.PI2 - lerp)) + { + currentAngle = targetAngle; + } + else + { + if (Math.abs(targetAngle - currentAngle) > Math.PI) + { + if (targetAngle < currentAngle) + { + targetAngle += Phaser.Math.PI2; + } + else + { + targetAngle -= Phaser.Math.PI2; + } + } + + if (targetAngle > currentAngle) + { + currentAngle += lerp; + } + else if (targetAngle < currentAngle) + { + currentAngle -= lerp; + } + } + + return currentAngle; + + }, + + /** + * Gets the shortest angle between `angle1` and `angle2`. + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method, and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * @method Phaser.Math#getShortestAngle + * @param {number} angle1 - The first angle. In the range -180 to 180. + * @param {number} angle2 - The second angle. In the range -180 to 180. + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ + getShortestAngle: function (angle1, angle2) { + + var difference = angle2 - angle1; + + if (difference === 0) + { + return 0; + } + + var times = Math.floor((difference - (-180)) / 360); + + return difference - (times * 360); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @method Phaser.Math#angleBetween + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetween: function (x1, y1, x2, y2) { + + return Math.atan2(y2 - y1, x2 - x1); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels + * down the screen. + * + * @method Phaser.Math#angleBetweenY + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetweenY: function (x1, y1, x2, y2) { + + return Math.atan2(x2 - x1, y2 - y1); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * @method Phaser.Math#angleBetweenPoints + * @param {Phaser.Point} point1 - The first point. + * @param {Phaser.Point} point2 - The second point. + * @return {number} The angle between the two points, in radians. + */ + angleBetweenPoints: function (point1, point2) { + + return Math.atan2(point2.y - point1.y, point2.x - point1.x); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * @method Phaser.Math#angleBetweenPointsY + * @param {Phaser.Point} point1 + * @param {Phaser.Point} point2 + * @return {number} The angle, in radians. + */ + angleBetweenPointsY: function (point1, point2) { + + return Math.atan2(point2.x - point1.x, point2.y - point1.y); + + }, + + /** + * Reverses an angle. + * @method Phaser.Math#reverseAngle + * @param {number} angleRad - The angle to reverse, in radians. + * @return {number} The reverse angle, in radians. + */ + reverseAngle: function (angleRad) { + + return this.normalizeAngle(angleRad + Math.PI, true); + + }, + + /** + * Normalizes an angle to the [0,2pi) range. + * @method Phaser.Math#normalizeAngle + * @param {number} angleRad - The angle to normalize, in radians. + * @return {number} The angle, fit within the [0,2pi] range, in radians. + */ + normalizeAngle: function (angleRad) { + + angleRad = angleRad % (2 * Math.PI); + return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI; + + }, + + /** + * Adds the given amount to the value, but never lets the value go over the specified maximum. + * + * @method Phaser.Math#maxAdd + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The new value. + */ + maxAdd: function (value, amount, max) { + + return Math.min(value + amount, max); + + }, + + /** + * Subtracts the given amount from the value, but never lets the value go below the specified minimum. + * + * @method Phaser.Math#minSub + * @param {number} value - The base value. + * @param {number} amount - The amount to subtract from the base value. + * @param {number} min - The minimum the value is allowed to be. + * @return {number} The new value. + */ + minSub: function (value, amount, min) { + + return Math.max(value - amount, min); + + }, + + /** + * Ensures that the value always stays between min and max, by wrapping the value around. + * + * If `max` is not larger than `min` the result is 0. + * + * @method Phaser.Math#wrap + * @param {number} value - The value to wrap. + * @param {number} min - The minimum the value is allowed to be. + * @param {number} max - The maximum the value is allowed to be, should be larger than `min`. + * @return {number} The wrapped value. + */ + wrap: function (value, min, max) { + + var range = max - min; + + if (range <= 0) + { + return 0; + } + + var result = (value - min) % range; + + if (result < 0) + { + result += range; + } + + return result + min; + + }, + + /** + * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. + * + * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. + * + * @method Phaser.Math#wrapValue + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The wrapped value. + */ + wrapValue: function (value, amount, max) { + + var diff; + value = Math.abs(value); + amount = Math.abs(amount); + max = Math.abs(max); + diff = (value + amount) % max; + + return diff; + + }, + + /** + * Returns true if the number given is odd. + * + * @method Phaser.Math#isOdd + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is odd. False if the given number is even. + */ + isOdd: function (n) { + + // Does not work with extremely large values + return !!(n & 1); + + }, + + /** + * Returns true if the number given is even. + * + * @method Phaser.Math#isEven + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is even. False if the given number is odd. + */ + isEven: function (n) { + + // Does not work with extremely large values + return !(n & 1); + + }, + + /** + * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.min` function when appropriate. + * + * @method Phaser.Math#min + * @return {number} The lowest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + 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; i < len; i++) + { + if (data[i] < data[min]) + { + min = i; + } + } + + return data[min]; + + }, + + /** + * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.max` function when appropriate. + * + * @method Phaser.Math#max + * @return {number} The largest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + max: function () { + + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + var data = arguments[0]; + } + else + { + var data = arguments; + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i] > data[max]) + { + max = i; + } + } + + return data[max]; + + }, + + /** + * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. + * It will find the lowest matching property value from the given objects. + * + * @method Phaser.Math#minProperty + * @return {number} The lowest value from those given. + */ + 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; i < len; i++) + { + if (data[i][property] < data[min][property]) + { + min = i; + } + } + + return data[min][property]; + + }, + + /** + * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. + * It will find the largest matching property value from the given objects. + * + * @method Phaser.Math#maxProperty + * @return {number} The largest value from those given. + */ + maxProperty: function (property) { + + if (arguments.length === 2 && typeof arguments[1] === 'object') + { + var data = arguments[1]; + } + else + { + var data = arguments.slice(1); + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i][property] > data[max][property]) + { + max = i; + } + } + + return data[max][property]; + + }, + + /** + * Keeps an angle value between -180 and +180; or -PI and PI if radians. + * + * @method Phaser.Math#wrapAngle + * @param {number} angle - The angle value to wrap + * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected. + * @return {number} The new angle value; will be the same as the input angle if it was within bounds. + */ + wrapAngle: function (angle, radians) { + + return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180); + + }, + + /** + * A Linear Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#linearInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + linearInterpolation: function (v, k) { + + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (k < 0) + { + return this.linear(v[0], v[1], f); + } + + if (k > 1) + { + return this.linear(v[m], v[m - 1], m - f); + } + + return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); + + }, + + /** + * A Bezier Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#bezierInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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; + + }, + + /** + * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#catmullRomInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + } + + }, + + /** + * Calculates a linear (interpolation) value over t. + * + * @method Phaser.Math#linear + * @param {number} p0 + * @param {number} p1 + * @param {number} t - A value between 0 and 1. + * @return {number} + */ + linear: function (p0, p1, t) { + + return (p1 - p0) * t + p0; + + }, + + /** + * @method Phaser.Math#bernstein + * @protected + * @param {number} n + * @param {number} i + * @return {number} + */ + bernstein: function (n, i) { + + return this.factorial(n) / this.factorial(i) / this.factorial(n - i); + + }, + + /** + * @method Phaser.Math#factorial + * @param {number} value - the number you want to evaluate + * @return {number} + */ + factorial: function (value) { + + if (value === 0) + { + return 1; + } + + var res = value; + + while(--value) + { + res *= value; + } + + return res; + + }, + + /** + * Calculates a catmum rom value. + * + * @method Phaser.Math#catmullRom + * @protected + * @param {number} p0 + * @param {number} p1 + * @param {number} p2 + * @param {number} p3 + * @param {number} t + * @return {number} + */ + catmullRom: function (p0, p1, p2, p3, t) { + + var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + + }, + + /** + * The absolute difference between two values. + * + * @method Phaser.Math#difference + * @param {number} a - The first value to check. + * @param {number} b - The second value to check. + * @return {number} The absolute difference between the two values. + */ + difference: function (a, b) { + + return Math.abs(a - b); + + }, + + /** + * Round to the next whole number _away_ from zero. + * + * @method Phaser.Math#roundAwayFromZero + * @param {number} value - Any number. + * @return {integer} The rounded value of that number. + */ + roundAwayFromZero: function (value) { + + // "Opposite" of truncate. + return (value > 0) ? Math.ceil(value) : Math.floor(value); + + }, + + /** + * Generate a sine and cosine table simultaneously and extremely quickly. + * The parameters allow you to specify the length, amplitude and frequency of the wave. + * This generator is fast enough to be used in real-time. + * Code based on research by Franky of scene.at + * + * @method Phaser.Math#sinCosGenerator + * @param {number} length - The length of the wave + * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} frequency - The frequency of the sine and cosine table data + * @return {{sin:number[], cos:number[]}} Returns the table data. + */ + sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) { + + if (sinAmplitude === undefined) { sinAmplitude = 1.0; } + if (cosAmplitude === undefined) { cosAmplitude = 1.0; } + if (frequency === undefined) { frequency = 1.0; } + + var sin = sinAmplitude; + var cos = cosAmplitude; + var frq = frequency * Math.PI / length; + + var cosTable = []; + var sinTable = []; + + for (var c = 0; c < length; c++) { + + cos -= sin * frq; + sin += cos * frq; + + cosTable[c] = cos; + sinTable[c] = sin; + + } + + return { sin: sinTable, cos: cosTable, length: length }; + + }, + + /** + * Returns the length of the hypotenuse connecting two segments of given lengths. + * + * @method Phaser.Math#hypot + * @param {number} a + * @param {number} b + * @return {number} The length of the hypotenuse connecting the given lengths. + */ + hypot: function (a, b) { + + return Math.sqrt(a * a + b * b); + + }, + + /** + * Returns the euclidian distance between the two given set of coordinates. + * + * @method Phaser.Math#distance + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance between the two sets of coordinates. + */ + distance: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Returns the euclidean distance squared between the two given set of + * coordinates (cuts out a square root operation before returning). + * + * @method Phaser.Math#distanceSq + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance squared between the two sets of coordinates. + */ + distanceSq: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return dx * dx + dy * dy; + + }, + + /** + * Returns the distance between the two given set of coordinates at the power given. + * + * @method Phaser.Math#distancePow + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} [pow=2] + * @return {number} The distance between the two sets of coordinates. + */ + distancePow: function (x1, y1, x2, y2, pow) { + + if (pow === undefined) { pow = 2; } + + return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); + + }, + + /** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @method Phaser.Math#clamp + * @param {float} v - The value to be clamped. + * @param {float} min - The minimum bounds. + * @param {float} max - The maximum bounds. + * @return {number} The clamped value. + */ + clamp: function (v, min, max) { + + if (v < min) + { + return min; + } + else if (max < v) + { + return max; + } + else + { + return v; + } + + }, + + /** + * Clamp `x` to the range `[a, Infinity)`. + * Roughly the same as `Math.max(x, a)`, except for NaN handling. + * + * @method Phaser.Math#clampBottom + * @param {number} x + * @param {number} a + * @return {number} + */ + clampBottom: function (x, a) { + + return x < a ? a : x; + + }, + + /** + * Checks if two values are within the given tolerance of each other. + * + * @method Phaser.Math#within + * @param {number} a - The first number to check + * @param {number} b - The second number to check + * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range. + * @return {boolean} True if a is <= tolerance of b. + * @see {@link Phaser.Math.fuzzyEqual} + */ + within: function (a, b, tolerance) { + + return (Math.abs(a - b) <= tolerance); + + }, + + /** + * Linear mapping from range to range + * + * @method Phaser.Math#mapLinear + * @param {number} x - The value to map + * @param {number} a1 - First endpoint of the range + * @param {number} a2 - Final endpoint of the range + * @param {number} b1 - First endpoint of the range + * @param {number} b2 - Final endpoint of the range + * @return {number} + */ + mapLinear: function (x, a1, a2, b1, b2) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + + }, + + /** + * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smoothstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smoothstep: function (x, min, max) { + + // Scale, bias and saturate x to 0..1 range + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + // Evaluate polynomial + return x * x * (3 - 2 * x); + + }, + + /** + * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smootherstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smootherstep: function (x, min, max) { + + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + return x * x * x * (x * (x * 6 - 15) + 10); + + }, + + /** + * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. + * + * This works differently from `Math.sign` for values of NaN and -0, etc. + * + * @method Phaser.Math#sign + * @param {number} x + * @return {integer} An integer in {-1, 0, 1} + */ + sign: function (x) { + + return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); + + }, + + /** + * Work out what percentage value `a` is of value `b` using the given base. + * + * @method Phaser.Math#percent + * @param {number} a - The value to work out the percentage for. + * @param {number} b - The value you wish to get the percentage of. + * @param {number} [base=0] - The base value. + * @return {number} The percentage a is of b, between 0 and 1. + */ + percent: function (a, b, base) { + + if (base === undefined) { base = 0; } + + if (a > b || base > b) + { + return 1; + } + else if (a < base || base > a) + { + return 0; + } + else + { + return (a - base) / b; + } + + } + +}; + +/* jshint noempty: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An extremely useful repeatable random data generator. +* +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. +* +* The random number genererator is based on the Alea PRNG, but is modified. +* - https://github.com/coverslide/node-alea +* - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror +* - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404) +* +* @class Phaser.RandomDataGenerator +* @constructor +* @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}). +*/ +Phaser.RandomDataGenerator = function (seeds) { + + if (seeds === undefined) { seeds = []; } + + /** + * @property {number} c - Internal var. + * @private + */ + this.c = 1; + + /** + * @property {number} s0 - Internal var. + * @private + */ + this.s0 = 0; + + /** + * @property {number} s1 - Internal var. + * @private + */ + this.s1 = 0; + + /** + * @property {number} s2 - Internal var. + * @private + */ + this.s2 = 0; + + if (typeof seeds === 'string') + { + this.state(seeds); + } + else + { + this.sow(seeds); + } + +}; + +Phaser.RandomDataGenerator.prototype = { + + /** + * Private random helper. + * + * @method Phaser.RandomDataGenerator#rnd + * @private + * @return {number} + */ + rnd: function () { + + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + + return this.s2; + }, + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.RandomDataGenerator#sow + * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used. + */ + sow: function (seeds) { + + // Always reset to default seed + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + this.c = 1; + + if (!seeds) + { + return; + } + + // Apply any seeds + for (var i = 0; i < seeds.length && (seeds[i] != null); i++) + { + var 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); + } + + }, + + /** + * Internal method that creates a seed hash. + * + * @method Phaser.RandomDataGenerator#hash + * @private + * @param {any} data + * @return {number} hashed value. + */ + hash: function (data) { + + var h, i, n; + n = 0xefc8249d; + data = data.toString(); + + for (i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } + + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + + }, + + /** + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#integer + * @return {number} A random integer between 0 and 2^32. + */ + integer: function() { + + return this.rnd.apply(this) * 0x100000000;// 2^32 + + }, + + /** + * Returns a random real number between 0 and 1. + * + * @method Phaser.RandomDataGenerator#frac + * @return {number} A random real number between 0 and 1. + */ + frac: function() { + + return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 + + }, + + /** + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#real + * @return {number} A random real number between 0 and 2^32. + */ + real: function() { + + return this.integer() + this.frac(); + + }, + + /** + * Returns a random integer between and including min and max. + * + * @method Phaser.RandomDataGenerator#integerInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + integerInRange: function (min, max) { + + return Math.floor(this.realInRange(0, max - min + 1) + min); + + }, + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.RandomDataGenerator#between + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + between: function (min, max) { + + return this.integerInRange(min, max); + + }, + + /** + * Returns a random real number between min and max. + * + * @method Phaser.RandomDataGenerator#realInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + realInRange: function (min, max) { + + return this.frac() * (max - min) + min; + + }, + + /** + * Returns a random real number between -1 and 1. + * + * @method Phaser.RandomDataGenerator#normal + * @return {number} A random real number between -1 and 1. + */ + normal: function () { + + return 1 - 2 * this.frac(); + + }, + + /** + * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 + * + * @method Phaser.RandomDataGenerator#uuid + * @return {string} A valid RFC4122 version4 ID hex string + */ + 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; + + }, + + /** + * Returns a random member of `array`. + * + * @method Phaser.RandomDataGenerator#pick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + pick: function (ary) { + + return ary[this.integerInRange(0, ary.length - 1)]; + + }, + + /** + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.RandomDataGenerator#sign + * @return {number} -1 or +1. + */ + sign: function () { + + return this.pick([-1, 1]); + + }, + + /** + * Returns a random member of `array`, favoring the earlier entries. + * + * @method Phaser.RandomDataGenerator#weightedPick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + weightedPick: function (ary) { + + return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)]; + + }, + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.RandomDataGenerator#timestamp + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random timestamp between min and max. + */ + timestamp: function (min, max) { + + return this.realInRange(min || 946684800000, max || 1577862000000); + + }, + + /** + * Returns a random angle between -180 and 180. + * + * @method Phaser.RandomDataGenerator#angle + * @return {number} A random number between -180 and 180. + */ + angle: function() { + + return this.integerInRange(-180, 180); + + }, + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.RandomDataGenerator#state + * @param {string} [state] - Generator state to be set. + * @return {string} The current state of the generator. + */ + state: function (state) { + + if (typeof state === 'string' && state.match(/^!rnd/)) + { + state = state.split(','); + + this.c = parseFloat(state[1]); + this.s0 = parseFloat(state[2]); + this.s1 = parseFloat(state[3]); + this.s2 = parseFloat(state[4]); + } + + return ['!rnd', this.c, this.s0, this.s1, this.s2].join(','); + + } + +}; + +Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator; + +/** + * @author Timo Hausmann + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** +* A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. +* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. +* Original version at https://github.com/timohausmann/quadtree-js/ +* +* @class Phaser.QuadTree +* @constructor +* @param {number} x - The top left coordinate of the quadtree. +* @param {number} y - The top left coordinate of the quadtree. +* @param {number} width - The width of the quadtree in pixels. +* @param {number} height - The height of the quadtree in pixels. +* @param {number} [maxObjects=10] - The maximum number of objects per node. +* @param {number} [maxLevels=4] - The maximum number of levels to iterate to. +* @param {number} [level=0] - Which level is this? +*/ +Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) { + + /** + * @property {number} maxObjects - The maximum number of objects per node. + * @default + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - The maximum number of levels to break down to. + * @default + */ + this.maxLevels = 4; + + /** + * @property {number} level - The current level. + */ + this.level = 0; + + /** + * @property {object} bounds - Object that contains the quadtree bounds. + */ + this.bounds = {}; + + /** + * @property {array} objects - Array of quadtree children. + */ + this.objects = []; + + /** + * @property {array} nodes - Array of associated child nodes. + */ + this.nodes = []; + + /** + * @property {array} _empty - Internal empty array. + * @private + */ + this._empty = []; + + this.reset(x, y, width, height, maxObjects, maxLevels, level); + +}; + +Phaser.QuadTree.prototype = { + + /** + * Resets the QuadTree. + * + * @method Phaser.QuadTree#reset + * @param {number} x - The top left coordinate of the quadtree. + * @param {number} y - The top left coordinate of the quadtree. + * @param {number} width - The width of the quadtree in pixels. + * @param {number} height - The height of the quadtree in pixels. + * @param {number} [maxObjects=10] - The maximum number of objects per node. + * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. + * @param {number} [level=0] - Which level is this? + */ + 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; + + }, + + /** + * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. + * + * @method Phaser.QuadTree#populate + * @param {Phaser.Group} group - The Group to add to the quadtree. + */ + populate: function (group) { + + group.forEach(this.populateHandler, this, true); + + }, + + /** + * Handler for the populate method. + * + * @method Phaser.QuadTree#populateHandler + * @param {Phaser.Sprite|object} sprite - The Sprite to check. + */ + populateHandler: function (sprite) { + + if (sprite.body && sprite.exists) + { + this.insert(sprite.body); + } + + }, + + /** + * Split the node into 4 subnodes + * + * @method Phaser.QuadTree#split + */ + split: function () { + + // top right node + this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // top left node + this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom left node + this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom right node + this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + }, + + /** + * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. + * + * @method Phaser.QuadTree#insert + * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. + */ + insert: function (body) { + + var i = 0; + var index; + + // if we have subnodes ... + 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.level < this.maxLevels) + { + // Split if we don't already have subnodes + if (this.nodes[0] == null) + { + this.split(); + } + + // Add objects to subnodes + while (i < this.objects.length) + { + index = this.getIndex(this.objects[i]); + + if (index !== -1) + { + // this is expensive - see what we can do about it + this.nodes[index].insert(this.objects.splice(i, 1)[0]); + } + else + { + i++; + } + } + } + + }, + + /** + * Determine which node the object belongs to. + * + * @method Phaser.QuadTree#getIndex + * @param {Phaser.Rectangle|object} rect - The bounds in which to check. + * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. + */ + getIndex: function (rect) { + + // default is that rect doesn't fit, i.e. it straddles the internal quadrants + var index = -1; + + if (rect.x < this.bounds.right && rect.right < this.bounds.right) + { + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-left quadrant of this quadtree + index = 1; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-left quadrant of this quadtree + index = 2; + } + } + else if (rect.x > this.bounds.right) + { + // rect can completely fit within the right quadrants + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-right quadrant of this quadtree + index = 0; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-right quadrant of this quadtree + index = 3; + } + } + + return index; + + }, + + /** + * Return all objects that could collide with the given Sprite or Rectangle. + * + * @method Phaser.QuadTree#retrieve + * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle. + * @return {array} - Array with all detected objects. + */ + 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 rect fits into a subnode .. + if (index !== -1) + { + returnObjects = returnObjects.concat(this.nodes[index].retrieve(source)); + } + else + { + // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed) + 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 the quadtree. + * @method Phaser.QuadTree#clear + */ + 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; + +/** +* Javascript QuadTree +* @version 1.0 +* +* @version 1.3, March 11th 2014 +* @author Richard Davey +* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked +* it massively to add node indexing, removed lots of temp. var creation and significantly +* increased performance as a result. +* +* Original version at https://github.com/timohausmann/quadtree-js/ +*/ + +/** +* @copyright © 2012 Timo Hausmann +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. +* +* @class Phaser.Net +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Net = function (game) { + + this.game = game; + +}; + +Phaser.Net.prototype = { + + /** + * Returns the hostname given by the browser. + * + * @method Phaser.Net#getHostName + * @return {string} + */ + getHostName: function () { + + if (window.location && window.location.hostname) { + return window.location.hostname; + } + + return null; + + }, + + /** + * Compares the given domain name against the hostname of the browser containing the game. + * If the domain name is found it returns true. + * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. + * Do not include 'http://' at the start. + * + * @method Phaser.Net#checkDomainName + * @param {string} domain + * @return {boolean} true if the given domain fragment can be found in the window.location.hostname + */ + checkDomainName: function (domain) { + return window.location.hostname.indexOf(domain) !== -1; + }, + + /** + * Updates a value on the Query String and returns it in full. + * If the value doesn't already exist it is set. + * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. + * Optionally you can redirect to the new url, or just return it as a string. + * + * @method Phaser.Net#updateQueryString + * @param {string} key - The querystring key to update. + * @param {string} value - The new value to be set. If it already exists it will be replaced. + * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. + * @param {string} url - The URL to modify. If none is given it uses window.location.href. + * @return {string} If redirect is false then the modified url and query string is returned. + */ + updateQueryString: function (key, value, redirect, url) { + + if (redirect === undefined) { redirect = false; } + if (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; + } + + }, + + /** + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#getQueryString + * @param {string} [parameter=''] - If specified this will return just the value for that key. + * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. + */ + getQueryString: function (parameter) { + + if (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 && parameter === this.decodeURI(key[0])) + { + return this.decodeURI(key[1]); + } + else + { + output[this.decodeURI(key[0])] = this.decodeURI(key[1]); + } + } + } + + return output; + + }, + + /** + * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and + * decodes it, replacing \ with spaces in the return. Used internally by the Net classes. + * + * @method Phaser.Net#decodeURI + * @param {string} value - The URI component to be decoded. + * @return {string} The decoded value. + */ + decodeURI: function (value) { + return decodeURIComponent(value.replace(/\+/g, " ")); + } + +}; + +Phaser.Net.prototype.constructor = Phaser.Net; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. +* Tweens are hooked into the game clock and pause system, adjusting based on the game state. +* +* TweenManager is based heavily on tween.js by http://soledadpenades.com. +* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. +* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. +* Please see https://github.com/sole/tween.js for a full list of contributors. +* +* @class Phaser.TweenManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.TweenManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * @property {boolean} frameBased + * @default + */ + this.frameBased = false; + + /** + * @property {array} _tweens - All of the currently running tweens. + * @private + */ + this._tweens = []; + + /** + * @property {array} _add - All of the tweens queued to be added in the next update. + * @private + */ + this._add = []; + + this.easeMap = { + + "Power0": Phaser.Easing.Power0, + "Power1": Phaser.Easing.Power1, + "Power2": Phaser.Easing.Power2, + "Power3": Phaser.Easing.Power3, + "Power4": Phaser.Easing.Power4, + + "Linear": Phaser.Easing.Linear.None, + "Quad": Phaser.Easing.Quadratic.Out, + "Cubic": Phaser.Easing.Cubic.Out, + "Quart": Phaser.Easing.Quartic.Out, + "Quint": Phaser.Easing.Quintic.Out, + "Sine": Phaser.Easing.Sinusoidal.Out, + "Expo": Phaser.Easing.Exponential.Out, + "Circ": Phaser.Easing.Circular.Out, + "Elastic": Phaser.Easing.Elastic.Out, + "Back": Phaser.Easing.Back.Out, + "Bounce": Phaser.Easing.Bounce.Out, + + "Quad.easeIn": Phaser.Easing.Quadratic.In, + "Cubic.easeIn": Phaser.Easing.Cubic.In, + "Quart.easeIn": Phaser.Easing.Quartic.In, + "Quint.easeIn": Phaser.Easing.Quintic.In, + "Sine.easeIn": Phaser.Easing.Sinusoidal.In, + "Expo.easeIn": Phaser.Easing.Exponential.In, + "Circ.easeIn": Phaser.Easing.Circular.In, + "Elastic.easeIn": Phaser.Easing.Elastic.In, + "Back.easeIn": Phaser.Easing.Back.In, + "Bounce.easeIn": Phaser.Easing.Bounce.In, + + "Quad.easeOut": Phaser.Easing.Quadratic.Out, + "Cubic.easeOut": Phaser.Easing.Cubic.Out, + "Quart.easeOut": Phaser.Easing.Quartic.Out, + "Quint.easeOut": Phaser.Easing.Quintic.Out, + "Sine.easeOut": Phaser.Easing.Sinusoidal.Out, + "Expo.easeOut": Phaser.Easing.Exponential.Out, + "Circ.easeOut": Phaser.Easing.Circular.Out, + "Elastic.easeOut": Phaser.Easing.Elastic.Out, + "Back.easeOut": Phaser.Easing.Back.Out, + "Bounce.easeOut": Phaser.Easing.Bounce.Out, + + "Quad.easeInOut": Phaser.Easing.Quadratic.InOut, + "Cubic.easeInOut": Phaser.Easing.Cubic.InOut, + "Quart.easeInOut": Phaser.Easing.Quartic.InOut, + "Quint.easeInOut": Phaser.Easing.Quintic.InOut, + "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut, + "Expo.easeInOut": Phaser.Easing.Exponential.InOut, + "Circ.easeInOut": Phaser.Easing.Circular.InOut, + "Elastic.easeInOut": Phaser.Easing.Elastic.InOut, + "Back.easeInOut": Phaser.Easing.Back.InOut, + "Bounce.easeInOut": Phaser.Easing.Bounce.InOut + + }; + + this.game.onPause.add(this._pauseAll, this); + this.game.onResume.add(this._resumeAll, this); + +}; + +Phaser.TweenManager.prototype = { + + /** + * Get all the tween objects in an array. + * @method Phaser.TweenManager#getAll + * @returns {Phaser.Tween[]} Array with all tween objects. + */ + getAll: function () { + + return this._tweens; + + }, + + /** + * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. + * @method Phaser.TweenManager#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._tweens.length; i++) + { + this._tweens[i].pendingDelete = true; + } + + this._add = []; + + }, + + /** + * Remove all tweens from a specific object, array of objects or Group. + * + * @method Phaser.TweenManager#removeFrom + * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. + * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. + */ + removeFrom: function (obj, children) { + + if (children === undefined) { children = true; } + + var i; + var len; + + if (Array.isArray(obj)) + { + for (i = 0, len = obj.length; i < len; i++) + { + this.removeFrom(obj[i]); + } + } + else if (obj.type === Phaser.GROUP && children) + { + for (var i = 0, len = obj.children.length; i < len; i++) + { + this.removeFrom(obj.children[i]); + } + } + else + { + for (i = 0, len = this._tweens.length; i < len; i++) + { + if (obj === this._tweens[i].target) + { + this.remove(this._tweens[i]); + } + } + + for (i = 0, len = this._add.length; i < len; i++) + { + if (obj === this._add[i].target) + { + this.remove(this._add[i]); + } + } + } + + }, + + /** + * Add a new tween into the TweenManager. + * + * @method Phaser.TweenManager#add + * @param {Phaser.Tween} tween - The tween object you want to add. + * @returns {Phaser.Tween} The tween object you added to the manager. + */ + add: function (tween) { + + tween._manager = this; + this._add.push(tween); + + }, + + /** + * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.TweenManager#create + * @param {object} object - Object the tween will be run on. + * @returns {Phaser.Tween} The newly created tween object. + */ + create: function (object) { + + return new Phaser.Tween(object, this.game, this); + + }, + + /** + * Remove a tween from this manager. + * + * @method Phaser.TweenManager#remove + * @param {Phaser.Tween} tween - The tween object you want to remove. + */ + remove: function (tween) { + + var i = this._tweens.indexOf(tween); + + if (i !== -1) + { + this._tweens[i].pendingDelete = true; + } + else + { + i = this._add.indexOf(tween); + + if (i !== -1) + { + this._add[i].pendingDelete = true; + } + } + + }, + + /** + * Update all the tween objects you added to this manager. + * + * @method Phaser.TweenManager#update + * @returns {boolean} Return false if there's no tween to update, otherwise return true. + */ + update: function () { + + var addTweens = this._add.length; + var numTweens = this._tweens.length; + + if (numTweens === 0 && addTweens === 0) + { + return false; + } + + var i = 0; + + while (i < numTweens) + { + if (this._tweens[i].update(this.game.time.time)) + { + i++; + } + else + { + this._tweens.splice(i, 1); + + numTweens--; + } + } + + // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running + if (addTweens > 0) + { + this._tweens = this._tweens.concat(this._add); + this._add.length = 0; + } + + return true; + + }, + + /** + * Checks to see if a particular Sprite is currently being tweened. + * + * The `checkIsRunning` parameter will exclude tweens that have **just** completed or been stopped but haven't yet been removed from the manager. + * + * @method Phaser.TweenManager#isTweening + * @param {object} object - The object to check for tweens against. + * @param {boolean} [checkIsRunning=false] - Also check that the tween is running and is not marked for deletion. + * @returns {boolean} Returns true if the object is currently being tweened, false if not. + */ + isTweening: function(object, checkIsRunning) { + + if (!checkIsRunning) { checkIsRunning = false; } + + return this._tweens.some(function(tween) { + return (tween.target === object) && (!checkIsRunning || (tween.isRunning && !tween.pendingDelete)); + }); + + }, + + /** + * Private. Called by game focus loss. Pauses all currently running tweens. + * + * @method Phaser.TweenManager#_pauseAll + * @private + */ + _pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._pause(); + } + + }, + + /** + * Private. Called by game focus loss. Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#_resumeAll + * @private + */ + _resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._resume(); + } + + }, + + /** + * Pauses all currently running tweens. + * + * @method Phaser.TweenManager#pauseAll + */ + pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].pause(); + } + + }, + + /** + * Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#resumeAll + */ + resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].resume(true); + } + + } + +}; + +Phaser.TweenManager.prototype.constructor = Phaser.TweenManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tween allows you to alter one or more properties of a target object over a defined period of time. +* This can be used for things such as alpha fading Sprites, scaling them or motion. +* Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object +* by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and +* are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. +* +* @class Phaser.Tween +* @constructor +* @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. +* @param {Phaser.Game} game - Current game instance. +* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. +*/ +Phaser.Tween = function (target, game, manager) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. + */ + this.target = target; + + /** + * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween. + */ + this.manager = manager; + + /** + * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween. + */ + this.timeline = []; + + /** + * If set to `true` the current tween will play in reverse. + * If the tween hasn't yet started this has no effect. + * If there are child tweens then all child tweens will play in reverse from the current point. + * @property {boolean} reverse + * @default + */ + this.reverse = false; + + /** + * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. + * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. + * + * @property {number} timeScale + * @default + */ + this.timeScale = 1; + + /** + * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count. + */ + this.repeatCounter = 0; + + /** + * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager. + * @default + * @readonly + */ + this.pendingDelete = false; + + /** + * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onStart + */ + this.onStart = new Phaser.Signal(); + + /** + * The onLoop event is fired if the Tween, or any child tweens loop. + * It will be sent 2 parameters: the target object and this tween. + * + * @property {Phaser.Signal} onLoop + */ + this.onLoop = new Phaser.Signal(); + + /** + * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onRepeat + */ + this.onRepeat = new Phaser.Signal(); + + /** + * The onChildComplete event is fired when the Tween or any of its children completes. + * Fires every time a child completes unless a child is set to repeat forever. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onChildComplete + */ + this.onChildComplete = new Phaser.Signal(); + + /** + * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. + * @default + */ + this.isRunning = false; + + /** + * @property {number} current - The current Tween child being run. + * @default + * @readonly + */ + this.current = 0; + + /** + * @property {object} properties - Target property cache used when building the child data values. + */ + this.properties = {}; + + /** + * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it. + */ + this.chainedTween = null; + + /** + * @property {boolean} isPaused - Is this Tween paused or not? + * @default + */ + this.isPaused = false; + + /** + * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * + * The default value is whatever you've set in TweenManager.frameBased. + * + * @property {boolean} frameBased + * @default + */ + this.frameBased = manager.frameBased; + + /** + * @property {function} _onUpdateCallback - An onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallback = null; + + /** + * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallbackContext = null; + + /** + * @property {number} _pausedTime - Private pause timer. + * @private + * @default + */ + this._pausedTime = 0; + + /** + * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not. + * @private + */ + this._hasStarted = false; +}; + +/** +* A helper for tweening {@link Phaser.Color.createColor color objects}. +* +* It can be passed to {@link #onUpdateCallback}. +* +* ```javascript +* var color = Phaser.Color.createColor(255, 0, 0); // red +* +* var tween = game.add.tween(color).to({ +* r: 0, g: 0, b: 255 // blue +* }); +* +* tween.onUpdateCallback(Phaser.Tween.updateColor); +* +* tween.start(); +* ``` +* +* @method Phaser.Tween.updateColor +* @static +* @param {Phaser.Tween} tween - A Tween with a {@link #target} that is a {@link Phaser.Color.createColor color object}. +*/ +Phaser.Tween.updateColor = function (tween) { + + Phaser.Color.updateColor(tween.target); + +}; + +Phaser.Tween.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#to + * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined || duration <= 0) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.to cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#from + * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.from cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Starts the tween running. Can also be called by the `autoStart` parameter of {@link #to} or {@link #from}. + * This sets the {@link #isRunning} property to `true` and dispatches the {@link #onStart} signal. + * If the tween has a delay set then nothing will start tweening until the delay has expired. + * If the tween is already running, is flagged for deletion (such as after {@link #stop}), + * or has an empty timeline, calling start has no effect and the `onStart` signal is not dispatched. + * + * @method Phaser.Tween#start + * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + start: function (index) { + + if (index === undefined) { index = 0; } + + if (this.pendingDelete) + { + console.warn('Phaser.Tween.start cannot be called after Tween.stop'); + return this; + } + + if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning) + { + return this; + } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + this.manager.add(this); + + this.isRunning = true; + + if (index < 0 || index > this.timeline.length - 1) + { + index = 0; + } + + this.current = index; + + this.timeline[this.current].start(); + + return this; + + }, + + /** + * Stops the tween if running and flags it for deletion from the TweenManager. The tween can't be {@link #start restarted} after this. + * The {@link #onComplete} signal is not dispatched and no chained tweens are started unless the `complete` parameter is set to `true`. + * If you just wish to pause a tween then use {@link #pause} instead. + * If the tween is not running, it is **not** flagged for deletion and can be started again. + * + * @method Phaser.Tween#stop + * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + stop: function (complete) { + + if (complete === undefined) { complete = false; } + + this.isRunning = false; + + this._onUpdateCallback = null; + this._onUpdateCallbackContext = null; + + if (complete) + { + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + } + + this.manager.remove(this); + + return this; + + }, + + /** + * Updates either a single TweenData or all TweenData objects properties to the given value. + * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. + * The property is not checked, so if you pass an invalid one you'll generate a run-time error. + * + * @method Phaser.Tween#updateTweenData + * @param {string} property - The property to update. + * @param {number|function} value - The value to set the property to. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + updateTweenData: function (property, value, index) { + + if (this.timeline.length === 0) { return this; } + + if (index === undefined) { index = 0; } + + if (index === -1) + { + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i][property] = value; + } + } + else + { + this.timeline[index][property] = value; + } + + return this; + + }, + + /** + * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. + * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. + * If you have child tweens and pass -1 as the index value it sets the delay across all of them. + * + * @method Phaser.Tween#delay + * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + delay: function (duration, index) { + + return this.updateTweenData('delay', duration, index); + + }, + + /** + * Sets the number of times this tween will repeat. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. + * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. + * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. + * + * @method Phaser.Tween#repeat + * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeat: function (total, repeatDelay, index) { + + if (repeatDelay === undefined) { repeatDelay = 0; } + + this.updateTweenData('repeatCounter', total, index); + this.updateTweenData('repeatTotal', total, index); + + return this.updateTweenData('repeatDelay', repeatDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will repeat itself. + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#repeatDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatDelay: function (duration, index) { + + return this.updateTweenData('repeatDelay', duration, index); + + }, + + /** + * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. + * Used in combination with repeat you can create endless loops. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. + * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. + * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. + * + * @method Phaser.Tween#yoyo + * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo. + * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyo: function(enable, yoyoDelay, index) { + + if (yoyoDelay === undefined) { yoyoDelay = 0; } + + this.updateTweenData('yoyo', enable, index); + + return this.updateTweenData('yoyoDelay', yoyoDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#yoyoDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyoDelay: function (duration, index) { + + return this.updateTweenData('yoyoDelay', duration, index); + + }, + + /** + * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. + * + * @method Phaser.Tween#easing + * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + easing: function (ease, index) { + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + return this.updateTweenData('easingFunction', ease, index); + + }, + + /** + * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. + * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. + * The interpolation function is only used if the target properties is an array. + * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. + * + * @method Phaser.Tween#interpolation + * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) + * @param {object} [context] - The context under which the interpolation function will be run. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + interpolation: function (interpolation, context, index) { + + if (context === undefined) { context = Phaser.Math; } + + this.updateTweenData('interpolationFunction', interpolation, index); + + return this.updateTweenData('interpolationContext', context, index); + + }, + + /** + * Set how many times this tween and all of its children will repeat. + * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. + * + * @method Phaser.Tween#repeatAll + * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatAll: function (total) { + + if (total === undefined) { total = 0; } + + this.repeatCounter = total; + + return this; + + }, + + /** + * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called + * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. + * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. + * For that you should listen to `onComplete` on the final tween in your chain. + * + * If you pass multiple tweens to this method they will be joined into a single long chain. + * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. + * Any previously chained tweens that may have been set will be overwritten. + * + * @method Phaser.Tween#chain + * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + chain: function () { + + var i = arguments.length; + + while (i--) + { + if (i > 0) + { + arguments[i - 1].chainedTween = arguments[i]; + } + else + { + this.chainedTween = arguments[i]; + } + } + + return this; + + }, + + /** + * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. + * + * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. + * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. + * + * Usage: + * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) + * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) + * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) + * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) + * .loop(); + * @method Phaser.Tween#loop + * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + loop: function (value) { + + if (value === undefined) { value = true; } + + this.repeatCounter = (value) ? -1 : 0; + + return this; + + }, + + /** + * Sets a callback to be fired each time this tween updates. + * + * The callback receives the current Tween, the {@link Phaser.TweenData#value 'value' of the current TweenData}, and the current {@link Phaser.TweenData TweenData}. The second parameter is most useful. + * + * ```javascript + * tween.onUpdateCallback(function (tween, value, tweenData) { + * console.log('Tween running -- percent: %.2f value: %.2f', tweenData.percent, value); + * }); + * ``` + * + * @method Phaser.Tween#onUpdateCallback + * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. + * @param {object} callbackContext - The context in which to call the onUpdate callback. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + onUpdateCallback: function (callback, callbackContext) { + + this._onUpdateCallback = callback; + this._onUpdateCallbackContext = callbackContext; + + return this; + + }, + + /** + * Pauses the tween. Resume playback with Tween.resume. + * + * @method Phaser.Tween#pause + */ + pause: function () { + + this.isPaused = true; + + this._codePaused = true; + + this._pausedTime = this.game.time.time; + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * + * @private + * @method Phaser.Tween#_pause + */ + _pause: function () { + + if (!this._codePaused) + { + this.isPaused = true; + + this._pausedTime = this.game.time.time; + } + + }, + + /** + * Resumes a paused tween. + * + * @method Phaser.Tween#resume + */ + resume: function () { + + if (this.isPaused) + { + this.isPaused = false; + + this._codePaused = false; + + for (var i = 0; i < this.timeline.length; i++) + { + if (!this.timeline[i].isRunning) + { + this.timeline[i].startTime += (this.game.time.time - this._pausedTime); + } + } + } + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * @method Phaser.Tween#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Core tween update function called by the TweenManager. Does not need to be invoked directly. + * + * @method Phaser.Tween#update + * @param {number} time - A timestamp passed in by the TweenManager. + * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). + */ + update: function (time) { + + if (this.pendingDelete || !this.target) + { + return false; + } + + if (this.isPaused) + { + return true; + } + + var status = this.timeline[this.current].update(time); + + if (status === Phaser.TweenData.PENDING) + { + return true; + } + else if (status === Phaser.TweenData.RUNNING) + { + if (!this._hasStarted) + { + this.onStart.dispatch(this.target, this); + this._hasStarted = true; + } + + if (this._onUpdateCallback !== null) + { + this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]); + } + + // In case the update callback modifies this tween + return this.isRunning; + } + else if (status === Phaser.TweenData.LOOPED) + { + if (this.timeline[this.current].repeatCounter === -1) + { + this.onLoop.dispatch(this.target, this); + } + else + { + this.onRepeat.dispatch(this.target, this); + } + + return true; + } + else if (status === Phaser.TweenData.COMPLETE) + { + var complete = false; + + // What now? + if (this.reverse) + { + this.current--; + + if (this.current < 0) + { + this.current = this.timeline.length - 1; + complete = true; + } + } + else + { + this.current++; + + if (this.current === this.timeline.length) + { + this.current = 0; + complete = true; + } + } + + if (complete) + { + // We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it? + if (this.repeatCounter === -1) + { + this.timeline[this.current].start(); + this.onLoop.dispatch(this.target, this); + return true; + } + else if (this.repeatCounter > 0) + { + this.repeatCounter--; + + this.timeline[this.current].start(); + this.onRepeat.dispatch(this.target, this); + return true; + } + else + { + // No more repeats and no more children, so we're done + this.isRunning = false; + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + + return false; + } + } + else + { + // We've still got some children to go + this.onChildComplete.dispatch(this.target, this); + this.timeline[this.current].start(); + return true; + } + } + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * It ignores delay and repeat counts and any chained tweens, but does include child tweens. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.Tween#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate, data) { + + if (this.game === null || this.target === null) + { + return null; + } + + if (frameRate === undefined) { frameRate = 60; } + if (data === undefined) { data = []; } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + for (var i = 0; i < this.timeline.length; i++) + { + data = data.concat(this.timeline[i].generateData(frameRate)); + } + + return data; + + } + +}; + +/** +* @name Phaser.Tween#totalDuration +* @property {number} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds. +*/ +Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', { + + get: function () { + + var total = 0; + + for (var i = 0; i < this.timeline.length; i++) + { + total += this.timeline[i].duration; + } + + return total; + + } + +}); + +Phaser.Tween.prototype.constructor = Phaser.Tween; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the +* starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for +* TweenData objects and can contain multiple TweenData objects. +* +* @class Phaser.TweenData +* @constructor +* @param {Phaser.Tween} parent - The Tween that owns this TweenData object. +*/ +Phaser.TweenData = function (parent) { + + /** + * @property {Phaser.Tween} parent - The Tween which owns this TweenData. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = parent.game; + + /** + * @property {object} vStart - An object containing the values at the start of the tween. + * @private + */ + this.vStart = {}; + + /** + * @property {object} vStartCache - Cached starting values. + * @private + */ + this.vStartCache = {}; + + /** + * @property {object} vEnd - An object containing the values at the end of the tween. + * @private + */ + this.vEnd = {}; + + /** + * @property {object} vEndCache - Cached ending values. + * @private + */ + this.vEndCache = {}; + + /** + * @property {number} duration - The duration of the tween in ms. + * @default + */ + this.duration = 1000; + + /** + * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is. + * @readonly + */ + this.percent = 0; + + /** + * @property {number} value - The output of the easing function for the current {@link #percent}. Depending on the easing function, this will be within [0, 1] or a slightly larger range (e.g., Bounce). When easing is Linear, this will be identical to {@link #percent}. + * @readonly + */ + this.value = 0; + + /** + * @property {number} repeatCounter - If the Tween is set to repeat this is the number of repeats remaining (and `repeatTotal - repeatCounter` is the number of repeats completed). + */ + this.repeatCounter = 0; + + /** + * @property {number} repeatDelay - The amount of time in ms between repeats of this tween. + */ + this.repeatDelay = 0; + + /** + * @property {number} repeatTotal - The total number of times this Tween will repeat. + * @readonly + */ + this.repeatTotal = 0; + + /** + * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween) + * @default + * @todo Appears unused. + */ + this.interpolate = false; + + /** + * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false. + * @default + */ + this.yoyo = false; + + /** + * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween. + */ + this.yoyoDelay = 0; + + /** + * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). + * @default + */ + this.inReverse = false; + + /** + * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. + * @default + */ + this.delay = 0; + + /** + * @property {number} dt - Current time value. + */ + this.dt = 0; + + /** + * @property {number} startTime - The time the Tween started or null if it hasn't yet started. + */ + this.startTime = null; + + /** + * @property {function} easingFunction - The easing function used for the Tween. + * @default Phaser.Easing.Default + */ + this.easingFunction = Phaser.Easing.Default; + + /** + * @property {function} interpolationFunction - The interpolation function used for Array-based Tween. + * @default Phaser.Math.linearInterpolation + */ + this.interpolationFunction = Phaser.Math.linearInterpolation; + + /** + * @property {object} interpolationContext - The interpolation function context used for the Tween. + * @default Phaser.Math + */ + this.interpolationContext = Phaser.Math; + + /** + * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} isFrom - Is this a from tween or a to tween? + * @default + */ + this.isFrom = false; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.PENDING = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.RUNNING = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.LOOPED = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.COMPLETE = 3; + +Phaser.TweenData.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * + * @method Phaser.TweenData#to + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + to: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = false; + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * + * @method Phaser.TweenData#from + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + from: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = true; + + return this; + + }, + + /** + * Starts the Tween running. + * + * @method Phaser.TweenData#start + * @return {Phaser.TweenData} This Tween object. + */ + start: function () { + + this.startTime = this.game.time.time + this.delay; + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + if (this.delay > 0) + { + this.isRunning = false; + } + else + { + this.isRunning = true; + } + + if (this.isFrom) + { + // Reverse them all and instant set them + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + this.parent.target[property] = this.vStart[property]; + } + } + + this.value = 0; + this.repeatCounter = this.repeatTotal; + + return this; + + }, + + /** + * Loads the values from the target object into this Tween. + * + * @private + * @method Phaser.TweenData#loadValues + * @return {Phaser.TweenData} This Tween object. + */ + loadValues: function () { + + for (var property in this.parent.properties) + { + // Load the property from the parent object + this.vStart[property] = this.parent.properties[property]; + + // Check if an Array was provided as property value + if (Array.isArray(this.vEnd[property])) + { + if (this.vEnd[property].length === 0) + { + continue; + } + + if (this.percent === 0) + { + // Put the start value at the beginning of the array + // but we only want to do this once, if the Tween hasn't run before + this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]); + } + } + + if (typeof this.vEnd[property] !== 'undefined') + { + if (typeof this.vEnd[property] === 'string') + { + // Parses relative end values with start as base (e.g.: +10, -3) + this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10); + } + + this.parent.properties[property] = this.vEnd[property]; + } + else + { + // Null tween + this.vEnd[property] = this.vStart[property]; + } + + this.vStartCache[property] = this.vStart[property]; + this.vEndCache[property] = this.vEnd[property]; + } + + return this; + + }, + + /** + * Updates this Tween. This is called automatically by Phaser.Tween. + * + * @protected + * @method Phaser.TweenData#update + * @param {number} time - A timestamp passed in by the Tween parent. + * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. + */ + update: function (time) { + + if (!this.isRunning) + { + if (time >= this.startTime) + { + this.isRunning = true; + } + else + { + return Phaser.TweenData.PENDING; + } + } + else + { + // Is Running, but is waiting to repeat + if (time < this.startTime) + { + return Phaser.TweenData.RUNNING; + } + } + + var ms = (this.parent.frameBased) ? this.game.time.physicsElapsedMS : this.game.time.elapsedMS; + + if (this.parent.reverse) + { + this.dt -= ms * this.parent.timeScale; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += ms * this.parent.timeScale; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + this.parent.target[property] = start + ((end - start) * this.value); + } + } + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + return this.repeat(); + } + + return Phaser.TweenData.RUNNING; + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.TweenData#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate) { + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + var data = []; + var complete = false; + var fps = (1 / frameRate) * 1000; + + do + { + if (this.parent.reverse) + { + this.dt -= fps; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += fps; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + var blob = {}; + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + blob[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + blob[property] = start + ((end - start) * this.value); + } + } + + data.push(blob); + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + complete = true; + } + + } while (!complete); + + if (this.yoyo) + { + var reversed = data.slice(); + reversed.reverse(); + data = data.concat(reversed); + } + + return data; + + }, + + /** + * Checks if this Tween is meant to repeat or yoyo and handles doing so. + * + * @private + * @method Phaser.TweenData#repeat + * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE. + */ + repeat: function () { + + // If not a yoyo and repeatCounter = 0 then we're done + if (this.yoyo) + { + // We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end + if (this.inReverse && this.repeatCounter === 0) + { + // Restore the properties + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + this.inReverse = false; + + return Phaser.TweenData.COMPLETE; + } + + this.inReverse = !this.inReverse; + } + else + { + if (this.repeatCounter === 0) + { + return Phaser.TweenData.COMPLETE; + } + } + + if (this.inReverse) + { + // If inReverse we're going from vEnd to vStartCache + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + } + } + else + { + // If not inReverse we're just repopulating the cache again + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + // -1 means repeat forever, otherwise decrement the repeatCounter + // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total + if (this.repeatCounter > 0) + { + this.repeatCounter--; + } + } + + this.startTime = this.game.time.time; + + if (this.yoyo && this.inReverse) + { + this.startTime += this.yoyoDelay; + } + else if (!this.inReverse) + { + this.startTime += this.repeatDelay; + } + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + return Phaser.TweenData.LOOPED; + + } + +}; + +Phaser.TweenData.prototype.constructor = Phaser.TweenData; + +/* jshint curly: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of easing methods defining ease-in and ease-out curves. +* +* @class Phaser.Easing +*/ +Phaser.Easing = { + + /** + * Linear easing. + * + * @class Phaser.Easing.Linear + */ + Linear: { + + /** + * Linear Easing (no variation). + * + * @method Phaser.Easing.Linear#None + * @param {number} k - The value to be tweened. + * @returns {number} k. + */ + None: function ( k ) { + + return k; + + } + + }, + + /** + * Quadratic easing. + * + * @class Phaser.Easing.Quadratic + */ + Quadratic: { + + /** + * Ease-in. + * + * @method Phaser.Easing.Quadratic#In + * @param {number} k - The value to be tweened. + * @returns {number} k^2. + */ + In: function ( k ) { + + return k * k; + + }, + + /** + * Ease-out. + * + * @method Phaser.Easing.Quadratic#Out + * @param {number} k - The value to be tweened. + * @returns {number} k* (2-k). + */ + Out: function ( k ) { + + return k * ( 2 - k ); + + }, + + /** + * Ease-in/out. + * + * @method Phaser.Easing.Quadratic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; + return - 0.5 * ( --k * ( k - 2 ) - 1 ); + + } + + }, + + /** + * Cubic easing. + * + * @class Phaser.Easing.Cubic + */ + Cubic: { + + /** + * Cubic ease-in. + * + * @method Phaser.Easing.Cubic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k; + + }, + + /** + * Cubic ease-out. + * + * @method Phaser.Easing.Cubic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k + 1; + + }, + + /** + * Cubic ease-in/out. + * + * @method Phaser.Easing.Cubic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k + 2 ); + + } + + }, + + /** + * Quartic easing. + * + * @class Phaser.Easing.Quartic + */ + Quartic: { + + /** + * Quartic ease-in. + * + * @method Phaser.Easing.Quartic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k; + + }, + + /** + * Quartic ease-out. + * + * @method Phaser.Easing.Quartic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return 1 - ( --k * k * k * k ); + + }, + + /** + * Quartic ease-in/out. + * + * @method Phaser.Easing.Quartic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; + return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); + + } + + }, + + /** + * Quintic easing. + * + * @class Phaser.Easing.Quintic + */ + Quintic: { + + /** + * Quintic ease-in. + * + * @method Phaser.Easing.Quintic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k * k; + + }, + + /** + * Quintic ease-out. + * + * @method Phaser.Easing.Quintic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k * k * k + 1; + + }, + + /** + * Quintic ease-in/out. + * + * @method Phaser.Easing.Quintic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); + + } + + }, + + /** + * Sinusoidal easing. + * + * @class Phaser.Easing.Sinusoidal + */ + Sinusoidal: { + + /** + * Sinusoidal ease-in. + * + * @method Phaser.Easing.Sinusoidal#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 1 - Math.cos( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-out. + * + * @method Phaser.Easing.Sinusoidal#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return Math.sin( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-in/out. + * + * @method Phaser.Easing.Sinusoidal#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); + + } + + }, + + /** + * Exponential easing. + * + * @class Phaser.Easing.Exponential + */ + Exponential: { + + /** + * Exponential ease-in. + * + * @method Phaser.Easing.Exponential#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k === 0 ? 0 : Math.pow( 1024, k - 1 ); + + }, + + /** + * Exponential ease-out. + * + * @method Phaser.Easing.Exponential#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); + + }, + + /** + * Exponential ease-in/out. + * + * @method Phaser.Easing.Exponential#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); + return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); + + } + + }, + + /** + * Circular easing. + * + * @class Phaser.Easing.Circular + */ + Circular: { + + /** + * Circular ease-in. + * + * @method Phaser.Easing.Circular#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Math.sqrt( 1 - k * k ); + + }, + + /** + * Circular ease-out. + * + * @method Phaser.Easing.Circular#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return Math.sqrt( 1 - ( --k * k ) ); + + }, + + /** + * Circular ease-in/out. + * + * @method Phaser.Easing.Circular#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); + return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); + + } + + }, + + /** + * Elastic easing. + * + * @class Phaser.Easing.Elastic + */ + Elastic: { + + /** + * Elastic ease-in. + * + * @method Phaser.Easing.Elastic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + + }, + + /** + * Elastic ease-out. + * + * @method Phaser.Easing.Elastic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); + + }, + + /** + * Elastic ease-in/out. + * + * @method Phaser.Easing.Elastic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; + + } + + }, + + /** + * Back easing. + * + * @class Phaser.Easing.Back + */ + Back: { + + /** + * Back ease-in. + * + * @method Phaser.Easing.Back#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s = 1.70158; + return k * k * ( ( s + 1 ) * k - s ); + + }, + + /** + * Back ease-out. + * + * @method Phaser.Easing.Back#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s = 1.70158; + return --k * k * ( ( s + 1 ) * k + s ) + 1; + + }, + + /** + * Back ease-in/out. + * + * @method Phaser.Easing.Back#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s = 1.70158 * 1.525; + if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); + return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); + + } + + }, + + /** + * Bounce easing. + * + * @class Phaser.Easing.Bounce + */ + Bounce: { + + /** + * Bounce ease-in. + * + * @method Phaser.Easing.Bounce#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Phaser.Easing.Bounce.Out( 1 - k ); + + }, + + /** + * Bounce ease-out. + * + * @method Phaser.Easing.Bounce#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if ( k < ( 1 / 2.75 ) ) { + + return 7.5625 * k * k; + + } else if ( k < ( 2 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; + + } else if ( k < ( 2.5 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; + + } else { + + return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; + + } + + }, + + /** + * Bounce ease-in/out. + * + * @method Phaser.Easing.Bounce#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5; + return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5; + + } + + } + +}; + +Phaser.Easing.Default = Phaser.Easing.Linear.None; +Phaser.Easing.Power0 = Phaser.Easing.Linear.None; +Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out; +Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out; +Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out; +Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is the core internal game clock. +* +* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, +* and also handles the standard Timer pool. +* +* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}. +* +* There are different *types* of time in Phaser: +* +* - ***Game time*** always runs at the speed of time in real life. +* +* Unlike wall-clock time, *game time stops when Phaser is paused*. +* +* Game time is used for {@link Phaser.Timer timer events}. +* +* - ***Physics time*** represents the amount of time given to physics calculations. +* +* *When {@link #slowMotion} is in effect physics time runs slower than game time.* +* Like game time, physics time stops when Phaser is paused. +* +* Physics time is used for physics calculations and {@link Phaser.Tween tweens}. +* +* - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time. +* +* This time is independent of Phaser and always progresses, regardless of if Phaser is paused. +* +* @class Phaser.Time +* @constructor +* @param {Phaser.Game} game A reference to the currently running game. +*/ +Phaser.Time = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * The `Date.now()` value when the time was last updated. + * @property {integer} time + * @protected + */ + this.time = 0; + + /** + * The `now` when the previous update occurred. + * @property {number} prevTime + * @protected + */ + this.prevTime = 0; + + /** + * An increasing value representing cumulative milliseconds since an undisclosed epoch. + * + * While this value is in milliseconds and can be used to compute time deltas, + * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference. + * + * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; + * the value can only be relied upon within a particular game instance. + * + * @property {number} now + * @protected + */ + this.now = 0; + + /** + * Elapsed time since the last time update, in milliseconds, based on `now`. + * + * This value _may_ include time that the game is paused/inactive. + * + * While the game is active, this will be similar to (1000 / {@link #fps}). + * + * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {number} elapsed + * @see Phaser.Time.time + * @protected + */ + this.elapsed = 0; + + /** + * The time in ms since the last time update, in milliseconds, based on `time`. + * + * This value is corrected for game pauses and will be "about zero" after a game is resumed. + * + * _Note:_ This is updated once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {integer} elapsedMS + * @protected + */ + this.elapsedMS = 0; + + /** + * The physics update delta, in fractional seconds. + * + * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) + * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system + * is unable to consistently maintain the desired FPS. + * + * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. + * + * @property {number} physicsElapsed + */ + this.physicsElapsed = 1 / 60; + + /** + * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. + * + * @property {number} physicsElapsedMS + */ + this.physicsElapsedMS = (1 / 60) * 1000; + + /** + * The desiredFps multiplier as used by Game.update. + * @property {integer} desiredFpsMult + * @protected + */ + this.desiredFpsMult = 1.0 / 60; + + /** + * The desired frame rate of the game. + * + * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates. + * + * @property {number} _desiredFps + * @private + * @default + */ + this._desiredFps = 60; + + /** + * The suggested frame rate for your game, based on an averaged real frame rate. + * This value is only populated if `Time.advancedTiming` is enabled. + * + * _Note:_ This is not available until after a few frames have passed; until then + * it's set to the same value as desiredFps. + * + * @property {number} suggestedFps + * @default + */ + this.suggestedFps = this.desiredFps; + + /** + * Scaling factor to make the game move smoothly in slow motion (or fast motion) + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * You likely need to adjust {@link #desiredFps} as well such that `desiredFps / slowMotion === 60`. + * + * @property {number} slowMotion + * @default + */ + this.slowMotion = 1.0; + + /** + * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. This isn't expensive, but displaying it with {@link Phaser.Utils.Debug#text} can be, especially in WebGL mode. + * @property {boolean} advancedTiming + * @default + */ + this.advancedTiming = false; + + /** + * Advanced timing result: The number of animation frames received from the browser in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} frames + * @readonly + */ + this.frames = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateLogic logic updates} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} updates + * @readonly + */ + this.updates = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateRender renders} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} renders + * @readonly + */ + this.renders = 0; + + /** + * Advanced timing result: Frames per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} fps + * @readonly + */ + this.fps = 0; + + /** + * Advanced timing result: Logic updates per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} ups + * @readonly + */ + this.ups = 0; + + /** + * Advanced timing result: Renders per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} rps + * @readonly + */ + this.rps = 0; + + /** + * Advanced timing result: The lowest rate the fps has dropped to. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMin + */ + this.fpsMin = 1000; + + /** + * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMax + */ + this.fpsMax = 0; + + /** + * Advanced timing result: The minimum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMin + * @default + */ + this.msMin = 1000; + + /** + * Advanced timing result: The maximum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMax + */ + this.msMax = 0; + + /** + * Records how long the game was last paused, in milliseconds. + * (This is not updated until the game is resumed.) + * @property {number} pauseDuration + */ + this.pauseDuration = 0; + + /** + * @property {number} timeToCall - The value that setTimeout needs to work out when to next update + * @protected + */ + this.timeToCall = 0; + + /** + * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop + * @protected + */ + this.timeExpected = 0; + + /** + * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to. + * @property {Phaser.Timer} events + */ + this.events = new Phaser.Timer(this.game, false); + + /** + * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated + * @private + */ + this._frameCount = 0; + + /** + * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated + * @private + */ + this._elapsedAccumulator = 0; + + /** + * @property {number} _started - The time at which the Game instance started. + * @private + */ + this._started = 0; + + /** + * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. + * @private + */ + this._timeLastSecond = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {boolean} _justResumed - Internal value used to recover from the game pause state. + * @private + */ + this._justResumed = false; + + /** + * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects. + * @private + */ + this._timers = []; + +}; + +Phaser.Time.prototype = { + + /** + * Called automatically by Phaser.Game after boot. Should not be called directly. + * + * @method Phaser.Time#boot + * @protected + */ + boot: function () { + + this._started = Date.now(); + this.time = Date.now(); + this.events.start(); + this.timeExpected = this.time; + + }, + + /** + * Adds an existing Phaser.Timer object to the Timer pool. + * + * @method Phaser.Time#add + * @param {Phaser.Timer} timer - An existing Phaser.Timer object. + * @return {Phaser.Timer} The given Phaser.Timer object. + */ + add: function (timer) { + + this._timers.push(timer); + + return timer; + + }, + + /** + * Creates a new stand-alone Phaser.Timer object. + * + * @method Phaser.Time#create + * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). + * @return {Phaser.Timer} The Timer object that was created. + */ + create: function (autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + var timer = new Phaser.Timer(this.game, autoDestroy); + + this._timers.push(timer); + + return timer; + + }, + + /** + * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer. + * + * @method Phaser.Time#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._timers.length; i++) + { + this._timers[i].destroy(); + } + + this._timers = []; + + this.events.removeAll(); + + }, + + /** + * Refreshes the Time.time and Time.elapsedMS properties from the system clock. + * + * @method Phaser.Time#refresh + */ + refresh: function () { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + }, + + /** + * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. + * + * @method Phaser.Time#update + * @protected + * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}. + */ + update: function (time) { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + // 'now' is currently still holding the time of the last call, move it into prevTime + this.prevTime = this.now; + + // update 'now' to hold the current time + // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now) + this.now = time; + + // elapsed time between previous call and now - this could be a high resolution value + this.elapsed = this.now - this.prevTime; + + if (this.game.raf._isSetTimeOut) + { + // console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time); + + // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game + this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time))); + + // time when the next call is expected if using timers + this.timeExpected = time + this.timeToCall; + + // console.log('Time expect', this.timeExpected); + } + + if (this.advancedTiming) + { + this.updateAdvancedTiming(); + } + + // Paused but still running? + if (!this.game.paused) + { + // Our internal Phaser.Timer + this.events.update(this.time); + + if (this._timers.length) + { + this.updateTimers(); + } + } + + }, + + /** + * Handles the updating of the Phaser.Timers (if any) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateTimers + * @private + */ + updateTimers: function () { + + // Any game level timers + var i = 0; + var len = this._timers.length; + + while (i < len) + { + if (this._timers[i].update(this.time)) + { + i++; + } + else + { + // Timer requests to be removed + this._timers.splice(i, 1); + len--; + } + } + + }, + + /** + * Handles the updating of the advanced timing values (if enabled) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateAdvancedTiming + * @private + */ + updateAdvancedTiming: function () { + + // count the number of time.update calls + this._frameCount++; + this._elapsedAccumulator += this.elapsed; + + // occasionally recalculate the suggestedFps based on the accumulated elapsed time + if (this._frameCount >= this._desiredFps * 2) + { + // this formula calculates suggestedFps in multiples of 5 fps + this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5; + this._frameCount = 0; + this._elapsedAccumulator = 0; + } + + this.msMin = Math.min(this.msMin, this.elapsed); + this.msMax = Math.max(this.msMax, this.elapsed); + + this.frames++; + + if (this.now > this._timeLastSecond + 1000) + { + var interval = this.now - this._timeLastSecond; + this.fps = Math.round((this.frames * 1000) / interval); + this.ups = Math.round((this.updates * 1000) / interval); + this.rps = Math.round((this.renders * 1000) / interval); + this.fpsMin = Math.min(this.fpsMin, this.fps); + this.fpsMax = Math.max(this.fpsMax, this.fps); + this._timeLastSecond = this.now; + this.frames = 0; + this.updates = 0; + this.renders = 0; + } + + }, + + /** + * Counts one logic update (if advanced timing is enabled). + * + * @method Phaser.Time#countUpdate + * @private + */ + countUpdate: function () { + + if (this.advancedTiming) + { + this.updates++; + } + + }, + + /** + * Counts one render (if advanced timing is enabled). + * + * @method Phaser.Time#countRender + * @private + */ + countRender: function () { + + if (this.advancedTiming) + { + this.renders++; + } + + }, + + /** + * Called when the game enters a paused state. + * + * @method Phaser.Time#gamePaused + * @private + */ + gamePaused: function () { + + this._pauseStarted = Date.now(); + + this.events.pause(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._pause(); + } + + }, + + /** + * Called when the game resumes from a paused state. + * + * @method Phaser.Time#gameResumed + * @private + */ + gameResumed: function () { + + // Set the parameter which stores Date.now() to make sure it's correct on resume + this.time = Date.now(); + + this.pauseDuration = this.time - this._pauseStarted; + + this.events.resume(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._resume(); + } + + }, + + /** + * The number of seconds that have elapsed since the game was started. + * + * @method Phaser.Time#totalElapsedSeconds + * @return {number} The number of seconds that have elapsed since the game was started. + */ + totalElapsedSeconds: function() { + return (this.time - this._started) * 0.001; + }, + + /** + * How long has passed since the given time. + * + * @method Phaser.Time#elapsedSince + * @param {number} since - The time you want to measure against. + * @return {number} The difference between the given time and now. + */ + elapsedSince: function (since) { + return this.time - since; + }, + + /** + * How long has passed since the given time (in seconds). + * + * @method Phaser.Time#elapsedSecondsSince + * @param {number} since - The time you want to measure (in seconds). + * @return {number} Duration between given time and now (in seconds). + */ + elapsedSecondsSince: function (since) { + return (this.time - since) * 0.001; + }, + + /** + * Resets the private _started value to now and removes all currently running Timers. + * + * @method Phaser.Time#reset + */ + reset: function () { + + this._started = this.time; + this.removeAll(); + + } + +}; + +/** +* The number of logic updates per second. +* +* This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. +* +* The render rate is unaffected unless you also turn off {@link Phaser.Game#forceSingleRender}. +* +* @name Phaser.Time#desiredFps +* @type {integer} +* @default 60 +*/ +Object.defineProperty(Phaser.Time.prototype, "desiredFps", { + + get: function () { + + return this._desiredFps; + + }, + + set: function (value) { + + this._desiredFps = value; + + // Set the physics elapsed time... this will always be 1 / this.desiredFps + // because we're using fixed time steps in game.update + this.physicsElapsed = 1 / value; + + this.physicsElapsedMS = this.physicsElapsed * 1000; + + this.desiredFpsMult = 1.0 / value; + + } + +}); + +Phaser.Time.prototype.constructor = Phaser.Time; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback. +* Many different timer events, with individual delays, can be added to the same Timer. +* +* All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. +* +* Timers are based on real life time, adjusted for game pause durations. +* That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account. +* +* @class Phaser.Timer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). +*/ +Phaser.Timer = function (game, autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * True if the Timer is actively running. + * + * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer. + * @property {boolean} running + * @default + * @readonly + */ + this.running = false; + + /** + * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). + * @property {boolean} autoDestroy + */ + this.autoDestroy = autoDestroy; + + /** + * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending. + * @readonly + * @default + */ + this.expired = false; + + /** + * @property {number} elapsed - Elapsed time since the last frame (in ms). + * @protected + */ + this.elapsed = 0; + + /** + * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. + */ + this.events = []; + + /** + * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. + * + * The signal is supplied with one argument, `timer`, which is this Timer object. + * + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {number} nextTick - The time the next tick will occur. + * @readonly + * @protected + */ + this.nextTick = 0; + + /** + * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. + */ + this.timeCap = 1000; + + /** + * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. + * @readonly + * @default + */ + this.paused = false; + + /** + * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {number} _started - The time at which this Timer instance started running. + * @private + * @default + */ + this._started = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {number} _pauseTotal - Total paused time. + * @private + */ + this._pauseTotal = 0; + + /** + * @property {number} _now - The current start-time adjusted time. + * @private + */ + this._now = Date.now(); + + /** + * @property {number} _len - Temp. array length variable. + * @private + */ + this._len = 0; + + /** + * @property {number} _marked - Temp. counter variable. + * @private + */ + this._marked = 0; + + /** + * @property {number} _i - Temp. array counter variable. + * @private + */ + this._i = 0; + + /** + * @property {number} _diff - Internal cache var. + * @private + */ + this._diff = 0; + + /** + * @property {number} _newTick - Internal cache var. + * @private + */ + this._newTick = 0; + +}; + +/** +* Number of milliseconds in a minute. +* @constant +* @type {integer} +*/ +Phaser.Timer.MINUTE = 60000; + +/** +* Number of milliseconds in a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.SECOND = 1000; + +/** +* Number of milliseconds in half a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.HALF = 500; + +/** +* Number of milliseconds in a quarter of a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.QUARTER = 250; + +Phaser.Timer.prototype = { + + /** + * Creates a new TimerEvent on this Timer. + * + * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. + * + * @method Phaser.Timer#create + * @private + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {boolean} loop - Should the event loop or not? + * @param {number} repeatCount - The number of times the event will repeat. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {any[]} arguments - The values to be sent to your callback function when it is called. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + create: function (delay, loop, repeatCount, callback, callbackContext, args) { + + delay = Math.round(delay); + + var tick = delay; + + if (this._now === 0) + { + tick += this.game.time.time; + } + else + { + tick += this._now; + } + + var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args); + + this.events.push(event); + + this.order(); + + this.expired = false; + + return event; + + }, + + /** + * Adds a new Event to this Timer. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#add + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + add: function (delay, callback, callbackContext) { + + return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. + * If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#repeat + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + repeat: function (delay, repeatCount, callback, callbackContext) { + + return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4)); + + }, + + /** + * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#loop + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + loop: function (delay, callback, callbackContext) { + + return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Starts this Timer running. + * @method Phaser.Timer#start + * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start. + */ + start: function (delay) { + + if (this.running) + { + return; + } + + this._started = this.game.time.time + (delay || 0); + + this.running = true; + + for (var i = 0; i < this.events.length; i++) + { + this.events[i].tick = this.events[i].delay + this._started; + } + + }, + + /** + * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. + * @method Phaser.Timer#stop + * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain. + */ + stop: function (clearEvents) { + + this.running = false; + + if (clearEvents === undefined) { clearEvents = true; } + + if (clearEvents) + { + this.events.length = 0; + } + + }, + + /** + * Removes a pending TimerEvent from the queue. + * @param {Phaser.TimerEvent} event - The event to remove from the queue. + * @method Phaser.Timer#remove + */ + remove: function (event) { + + for (var i = 0; i < this.events.length; i++) + { + if (this.events[i] === event) + { + this.events[i].pendingDelete = true; + return true; + } + } + + return false; + + }, + + /** + * Orders the events on this Timer so they are in tick order. + * This is called automatically when new events are created. + * @method Phaser.Timer#order + * @protected + */ + order: function () { + + if (this.events.length > 0) + { + // Sort the events so the one with the lowest tick is first + this.events.sort(this.sortHandler); + + this.nextTick = this.events[0].tick; + } + + }, + + /** + * Sort handler used by Phaser.Timer.order. + * @method Phaser.Timer#sortHandler + * @private + */ + sortHandler: function (a, b) { + + if (a.tick < b.tick) + { + return -1; + } + else if (a.tick > b.tick) + { + return 1; + } + + return 0; + + }, + + /** + * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values. + * + * @method Phaser.Timer#clearPendingEvents + * @protected + */ + 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; + + }, + + /** + * The main Timer update event, called automatically by Phaser.Time.update. + * + * @method Phaser.Timer#update + * @protected + * @param {number} time - The time from the core game clock. + * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. + */ + update: function (time) { + + if (this.paused) + { + return true; + } + + this.elapsed = time - this._now; + this._now = time; + + // spike-dislike + if (this.elapsed > this.timeCap) + { + // For some reason the time between now and the last time the game was updated was larger than our timeCap. + // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause. + // In this case we need to adjust the TimerEvents and nextTick. + this.adjustEvents(time - this.elapsed); + } + + this._marked = 0; + + // Clears events marked for deletion and resets _len and _i to 0. + this.clearPendingEvents(); + + if (this.running && this._now >= this.nextTick && this._len > 0) + { + while (this._i < this._len && this.running) + { + var event = this.events[this._i]; + + if (this._now >= event.tick && !event.pendingDelete) + { + // (now + delay) - (time difference from last tick to now) + this._newTick = (this._now + event.delay) - (this._now - event.tick); + + if (this._newTick < 0) + { + this._newTick = this._now + event.delay; + } + + if (event.loop === true) + { + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else if (event.repeatCount > 0) + { + event.repeatCount--; + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else + { + this._marked++; + event.pendingDelete = true; + event.callback.apply(event.callbackContext, event.args); + } + + this._i++; + } + else + { + break; + } + } + + // Are there any events left? + 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; + } + + }, + + /** + * Pauses the Timer and all events in the queue. + * @method Phaser.Timer#pause + */ + pause: function () { + + if (!this.running) + { + return; + } + + this._codePaused = true; + + if (this.paused) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Internal pause/resume control - user code should use Timer.pause instead. + * @method Phaser.Timer#_pause + * @private + */ + _pause: function () { + + if (this.paused || !this.running) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Adjusts the time of all pending events and the nextTick by the given baseTime. + * + * @method Phaser.Timer#adjustEvents + * @protected + */ + adjustEvents: function (baseTime) { + + for (var i = 0; i < this.events.length; i++) + { + if (!this.events[i].pendingDelete) + { + // Work out how long there would have been from when the game paused until the events next tick + var t = this.events[i].tick - baseTime; + + if (t < 0) + { + t = 0; + } + + // Add the difference on to the time now + this.events[i].tick = this._now + t; + } + } + + var d = this.nextTick - baseTime; + + if (d < 0) + { + this.nextTick = this._now; + } + else + { + this.nextTick = this._now + d; + } + + }, + + /** + * Resumes the Timer and updates all pending events. + * + * @method Phaser.Timer#resume + */ + resume: function () { + + if (!this.paused) + { + return; + } + + var now = this.game.time.time; + this._pauseTotal += now - this._now; + this._now = now; + + this.adjustEvents(this._pauseStarted); + + this.paused = false; + this._codePaused = false; + + }, + + /** + * Internal pause/resume control - user code should use Timer.resume instead. + * @method Phaser.Timer#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#removeAll + */ + removeAll: function () { + + this.onComplete.removeAll(); + this.events.length = 0; + this._len = 0; + this._i = 0; + + }, + + /** + * Destroys this Timer. Any pending Events are not dispatched. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#destroy + */ + destroy: function () { + + this.onComplete.removeAll(); + this.running = false; + this.expired = true; + this.events = []; + this._len = 0; + this._i = 0; + + } + +}; + +/** +* @name Phaser.Timer#next +* @property {number} next - The time at which the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "next", { + + get: function () { + return this.nextTick; + } + +}); + +/** +* @name Phaser.Timer#duration +* @property {number} duration - The duration in ms remaining until the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "duration", { + + get: function () { + + if (this.running && this.nextTick > this._now) + { + return this.nextTick - this._now; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#length +* @property {number} length - The number of pending events in the queue. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "length", { + + get: function () { + return this.events.length; + } + +}); + +/** +* @name Phaser.Timer#ms +* @property {number} ms - The duration in milliseconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "ms", { + + get: function () { + + if (this.running) + { + return this._now - this._started - this._pauseTotal; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#seconds +* @property {number} seconds - The duration in seconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "seconds", { + + get: function () { + + if (this.running) + { + return this.ms * 0.001; + } + else + { + return 0; + } + + } + +}); + +Phaser.Timer.prototype.constructor = Phaser.Timer; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TimerEvent is a single event that is processed by a Phaser.Timer. +* +* It consists of a delay, which is a value in milliseconds after which the event will fire. +* When the event fires it calls a specific callback with the specified arguments. +* +* TimerEvents are removed by their parent timer once finished firing or repeating. +* +* Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. +* +* @class Phaser.TimerEvent +* @constructor +* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. +* @param {number} delay - The delay in ms at which this TimerEvent fires. +* @param {number} tick - The tick is the next game clock time that this event will fire at. +* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times. +* @param {boolean} loop - True if this TimerEvent loops, otherwise false. +* @param {function} callback - The callback that will be called when the TimerEvent occurs. +* @param {object} callbackContext - The context in which the callback will be called. +* @param {any[]} arguments - Additional arguments to be passed to the callback. +*/ +Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) { + + /** + * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. + * @protected + * @readonly + */ + this.timer = timer; + + /** + * @property {number} delay - The delay in ms at which this TimerEvent fires. + */ + this.delay = delay; + + /** + * @property {number} tick - The tick is the next game clock time that this event will fire at. + */ + this.tick = tick; + + /** + * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times. + */ + this.repeatCount = repeatCount - 1; + + /** + * @property {boolean} loop - True if this TimerEvent loops, otherwise false. + */ + this.loop = loop; + + /** + * @property {function} callback - The callback that will be called when the TimerEvent occurs. + */ + this.callback = callback; + + /** + * @property {object} callbackContext - The context in which the callback will be called. + */ + this.callbackContext = callbackContext; + + /** + * @property {any[]} arguments - Additional arguments to be passed to the callback. + */ + this.args = args; + + /** + * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion. + * @protected + */ + this.pendingDelete = false; + +}; + +Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Manager is used to add, play and update Phaser Animations. +* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. +* +* @class Phaser.AnimationManager +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. +*/ +Phaser.AnimationManager = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = sprite.game; + + /** + * The currently displayed Frame of animation, if any. + * This property is only set once an Animation starts playing. Until that point it remains set as `null`. + * + * @property {Phaser.Frame} currentFrame + * @default + */ + this.currentFrame = null; + + /** + * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any. + * @default + */ + this.currentAnim = null; + + /** + * @property {boolean} updateIfVisible - Update the animation data only while the the sprite is {@link Phaser.Sprite#visible}. Set to `false` to continue updating while the sprite is invisible. + * @default + */ + this.updateIfVisible = true; + + /** + * @property {boolean} isLoaded - Set to true once animation data has been loaded. + * @default + */ + this.isLoaded = false; + + /** + * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. + * @private + * @default + */ + this._frameData = null; + + /** + * @property {object} _anims - An internal object that stores all of the Animation instances. + * @private + */ + this._anims = {}; + + /** + * @property {object} _outputFrames - An internal object to help avoid gc. + * @private + */ + this._outputFrames = []; + +}; + +Phaser.AnimationManager.prototype = { + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#loadFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + loadFrameData: function (frameData, frame) { + + if (frameData === undefined) + { + return false; + } + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(frameData); + } + } + + this._frameData = frameData; + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#copyFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + copyFrameData: function (frameData, frame) { + + this._frameData = frameData.clone(); + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(this._frameData); + } + } + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. + * Animations added in this way are played back with the play function. + * + * @method Phaser.AnimationManager#add + * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". + * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. + * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. + * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? + * @return {Phaser.Animation} The Animation object that was created. + */ + add: function (name, frames, frameRate, loop, useNumericIndex) { + + frames = frames || []; + frameRate = frameRate || 60; + + if (loop === undefined) { loop = false; } + + // If they didn't set the useNumericIndex then let's at least try and guess it + if (useNumericIndex === undefined) + { + if (frames && typeof frames[0] === 'number') + { + useNumericIndex = true; + } + else + { + useNumericIndex = false; + } + } + + this._outputFrames = []; + + 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]; + + if (this.sprite.tilingTexture) + { + this.sprite.refreshTexture = true; + } + + return this._anims[name]; + + }, + + /** + * Check whether the frames in the given array are valid and exist. + * + * @method Phaser.AnimationManager#validateFrames + * @param {Array} frames - An array of frames to be validated. + * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) + * @return {boolean} True if all given Frames are valid, otherwise false. + */ + validateFrames: function (frames, useNumericIndex) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + + for (var i = 0; i < frames.length; i++) + { + if (useNumericIndex === true) + { + if (frames[i] > this._frameData.total) + { + return false; + } + } + else + { + if (this._frameData.checkFrameName(frames[i]) === false) + { + return false; + } + } + } + + return true; + + }, + + /** + * Play an animation based on the given key. The animation should previously have been added via `animations.add` + * + * If the requested animation is already playing this request will be ignored. + * If you need to reset an already running animation do so directly on the Animation object itself. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.AnimationManager#play + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation instance. + */ + 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); + } + + return this.currentAnim; + } + else + { + if (this.currentAnim && this.currentAnim.isPlaying) + { + this.currentAnim.stop(); + } + + this.currentAnim = this._anims[name]; + this.currentAnim.paused = false; + this.currentFrame = this.currentAnim.currentFrame; + return this.currentAnim.play(frameRate, loop, killOnComplete); + } + } + + }, + + /** + * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. + * The currentAnim property of the AnimationManager is automatically set to the animation given. + * + * @method Phaser.AnimationManager#stop + * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. + * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) + */ + stop: function (name, resetFrame) { + + if (resetFrame === undefined) { resetFrame = false; } + + if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name)) + { + this.currentAnim.stop(resetFrame); + } + + }, + + /** + * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. + * + * @method Phaser.AnimationManager#update + * @protected + * @return {boolean} True if a new animation frame has been set, otherwise false. + */ + update: function () { + + if (this.updateIfVisible && !this.sprite.visible) + { + return false; + } + + if (this.currentAnim && this.currentAnim.update()) + { + this.currentFrame = this.currentAnim.currentFrame; + return true; + } + + return false; + + }, + + /** + * Advances by the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.next(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Moves backwards the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.previous(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Returns an animation that was previously added by name. + * + * @method Phaser.AnimationManager#getAnimation + * @param {string} name - The name of the animation to be returned, e.g. "fire". + * @return {Phaser.Animation} The Animation instance, if found, otherwise null. + */ + getAnimation: function (name) { + + if (typeof name === 'string') + { + if (this._anims[name]) + { + return this._anims[name]; + } + } + + return null; + + }, + + /** + * Refreshes the current frame data back to the parent Sprite and also resets the texture data. + * + * @method Phaser.AnimationManager#refreshFrame + */ + refreshFrame: function () { + + // TODO + // this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); + + }, + + /** + * Destroys all references this AnimationManager contains. + * Iterates through the list of animations stored in this manager and calls destroy on each of them. + * + * @method Phaser.AnimationManager#destroy + */ + destroy: function () { + + var anim = null; + + for (var anim in this._anims) + { + if (this._anims.hasOwnProperty(anim)) + { + this._anims[anim].destroy(); + } + } + + this._anims = {}; + this._outputFrames = []; + this._frameData = null; + this.currentAnim = null; + this.currentFrame = null; + this.sprite = null; + this.game = null; + + } + +}; + +Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager; + +/** +* @name Phaser.AnimationManager#frameData +* @property {Phaser.FrameData} frameData - The current animations FrameData. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', { + + get: function () { + return this._frameData; + } + +}); + +/** +* @name Phaser.AnimationManager#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', { + + get: function () { + + return this._frameData.total; + } + +}); + +/** +* @name Phaser.AnimationManager#paused +* @property {boolean} paused - Gets and sets the paused state of the current animation. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', { + + get: function () { + + return this.currentAnim.isPaused; + + }, + + set: function (value) { + + this.currentAnim.paused = value; + + } + +}); + +/** +* @name Phaser.AnimationManager#name +* @property {string} name - Gets the current animation name, if set. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'name', { + + get: function () { + + if (this.currentAnim) + { + return this.currentAnim.name; + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.index; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'number' && this._frameData && (gotFrame = this._frameData.getFrame(value))) + { + this.currentFrame = gotFrame; + this.sprite.setFrame(this.currentFrame); + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frameName +* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.name; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'string' && this._frameData && (gotFrame = this._frameData.getFrameByName(value))) + { + this.currentFrame = gotFrame; + this._frameIndex = this.currentFrame.index; + this.sprite.setFrame(this.currentFrame); + } + else + { + console.warn('Cannot set frameName: ' + value); + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Animation instance contains a single animation and the controls to play it. +* +* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. +* +* @class Phaser.Animation +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Sprite} parent - A reference to the owner of this Animation. +* @param {string} name - The unique name for this animation, used in playback commands. +* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. +* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +*/ +Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) { + + if (loop === undefined) { loop = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. + * @private + */ + this._parent = parent; + + /** + * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. + * @private + */ + this._frameData = frameData; + + /** + * @property {string} name - The user defined name given to this Animation. + */ + this.name = name; + + /** + * @property {array} _frames + * @private + */ + this._frames = []; + this._frames = this._frames.concat(frames); + + /** + * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. + */ + this.delay = 1000 / frameRate; + + /** + * @property {boolean} loop - The loop state of the Animation. + */ + this.loop = loop; + + /** + * @property {number} loopCount - The number of times the animation has looped since it was last started. + */ + this.loopCount = 0; + + /** + * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? + * @default + */ + this.killOnComplete = false; + + /** + * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. + * @default + */ + this.isFinished = false; + + /** + * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. + * @default + */ + this.isPlaying = false; + + /** + * @property {boolean} isPaused - The paused state of the Animation. + * @default + */ + this.isPaused = false; + + /** + * @property {boolean} _pauseStartTime - The time the animation paused. + * @private + * @default + */ + this._pauseStartTime = 0; + + /** + * @property {number} _frameIndex + * @private + * @default + */ + this._frameIndex = 0; + + /** + * @property {number} _frameDiff + * @private + * @default + */ + this._frameDiff = 0; + + /** + * @property {number} _frameSkip + * @private + * @default + */ + this._frameSkip = 1; + + /** + * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. + */ + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + /** + * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. + */ + this.onStart = new Phaser.Signal(); + + /** + * This event is dispatched when the Animation changes frame. + * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. + * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations + * will automatically frame-skip to try and claw back time, so do not base your code on expecting to + * receive a perfectly sequential set of frames from this event. + * @property {Phaser.Signal|null} onUpdate + * @default + */ + this.onUpdate = null; + + /** + * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {boolean} isReversed - Indicates if the animation will play backwards. + * @default + */ + this.isReversed = false; + + // Set-up some event listeners + this.game.onPause.add(this.onPause, this); + this.game.onResume.add(this.onResume, this); + +}; + +Phaser.Animation.prototype = { + + /** + * Plays this animation. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.Animation#play + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} - A reference to this Animation instance. + */ + play: function (frameRate, loop, killOnComplete) { + + if (typeof frameRate === 'number') + { + // If they set a new frame rate then use it, otherwise use the one set on creation + this.delay = 1000 / frameRate; + } + + if (typeof loop === 'boolean') + { + // If they set a new loop value then use it, otherwise use the one set on creation + this.loop = loop; + } + + if (typeof killOnComplete !== 'undefined') + { + // Remove the parent sprite once the animation has finished? + this.killOnComplete = killOnComplete; + } + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = this.isReversed ? this._frames.length - 1 : 0; + this.updateCurrentFrame(false, true); + + this._parent.events.onAnimationStart$dispatch(this._parent, this); + + this.onStart.dispatch(this._parent, this); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + return this; + + }, + + /** + * Sets this animation back to the first frame and restarts the animation. + * + * @method Phaser.Animation#restart + */ + restart: function () { + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = 0; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + this._parent.setFrame(this.currentFrame); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + this.onStart.dispatch(this._parent, this); + + }, + + /** + * Reverses the animation direction. + * + * @method Phaser.Animation#reverse + * @return {Phaser.Animation} The animation instance. + */ + reverse: function () { + + this.reversed = !this.reversed; + + return this; + + }, + + /** + * Reverses the animation direction for the current/next animation only + * Once the onComplete event is called this method will be called again and revert + * the reversed state. + * + * @method Phaser.Animation#reverseOnce + * @return {Phaser.Animation} The animation instance. + */ + reverseOnce: function () { + + this.onComplete.addOnce(this.reverse, this); + + return this.reverse(); + + }, + + /** + * Sets this animations playback to a given frame with the given ID. + * + * @method Phaser.Animation#setFrame + * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. + * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. + */ + setFrame: function(frameId, useLocalFrameIndex) { + + var frameIndex; + + if (useLocalFrameIndex === undefined) + { + useLocalFrameIndex = false; + } + + // Find the index to the desired frame. + if (typeof frameId === "string") + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frameData.getFrame(this._frames[i]).name === frameId) + { + frameIndex = i; + } + } + } + else if (typeof frameId === "number") + { + if (useLocalFrameIndex) + { + frameIndex = frameId; + } + else + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frames[i] === frameId) + { + frameIndex = i; + } + } + } + } + + if (frameIndex) + { + // Set the current frame index to the found index. Subtract a directional offset so that it animates to the desired frame on update. + var directionalOffset = this.isReversed ? -1 : 1; + this._frameIndex = frameIndex - directionalOffset; + + // Make the animation update at next update + this._timeNextFrame = this.game.time.time; + + this.update(); + } + + }, + + /** + * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. + * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. + * + * @method Phaser.Animation#stop + * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. + * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? + */ + stop: function (resetFrame, dispatchComplete) { + + if (resetFrame === undefined) { resetFrame = false; } + if (dispatchComplete === undefined) { dispatchComplete = false; } + + this.isPlaying = false; + this.isFinished = true; + this.paused = false; + + if (resetFrame) + { + this.currentFrame = this._frameData.getFrame(this._frames[0]); + this._parent.setFrame(this.currentFrame); + } + + if (dispatchComplete) + { + this._parent.events.onAnimationComplete$dispatch(this._parent, this); + this.onComplete.dispatch(this._parent, this); + } + + }, + + /** + * Called when the Game enters a paused state. + * + * @method Phaser.Animation#onPause + */ + onPause: function () { + + if (this.isPlaying) + { + this._frameDiff = this._timeNextFrame - this.game.time.time; + } + + }, + + /** + * Called when the Game resumes from a paused state. + * + * @method Phaser.Animation#onResume + */ + onResume: function () { + + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this._frameDiff; + } + + }, + + /** + * Updates this animation. Called automatically by the AnimationManager. + * + * @method Phaser.Animation#update + */ + update: function () { + + if (this.isPaused) + { + return false; + } + + if (this.isPlaying && this.game.time.time >= this._timeNextFrame) + { + this._frameSkip = 1; + + // Lagging? + this._frameDiff = this.game.time.time - this._timeNextFrame; + + this._timeLastFrame = this.game.time.time; + + if (this._frameDiff > this.delay) + { + // We need to skip a frame, work out how many + this._frameSkip = Math.floor(this._frameDiff / this.delay); + this._frameDiff -= (this._frameSkip * this.delay); + } + else + { + this._frameDiff = 0; + } + + // And what's left now? + this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff); + + if (this.isReversed) + { + this._frameIndex -= this._frameSkip; + } + else + { + this._frameIndex += this._frameSkip; + } + + if (!this.isReversed && this._frameIndex >= this._frames.length || this.isReversed && this._frameIndex <= -1) + { + if (this.loop) + { + // Update current state before event callback + this._frameIndex = Math.abs(this._frameIndex) % this._frames.length; + + if (this.isReversed) + { + this._frameIndex = this._frames.length - 1 - this._frameIndex; + } + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + // Instead of calling updateCurrentFrame we do it here instead + if (this.currentFrame) + { + this._parent.setFrame(this.currentFrame); + } + + this.loopCount++; + this._parent.events.onAnimationLoop$dispatch(this._parent, this); + this.onLoop.dispatch(this._parent, this); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + } + else + { + this.complete(); + return false; + } + } + else + { + return this.updateCurrentFrame(true); + } + } + + return false; + + }, + + /** + * Changes the currentFrame per the _frameIndex, updates the display state, + * and triggers the update signal. + * + * Returns true if the current frame update was 'successful', false otherwise. + * + * @method Phaser.Animation#updateCurrentFrame + * @private + * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. + * @param {boolean} fromPlay - Was this call made from the playing of a new animation? + * @return {boolean} True if the current frame was updated, otherwise false. + */ + updateCurrentFrame: function (signalUpdate, fromPlay) { + + if (fromPlay === undefined) { fromPlay = false; } + + if (!this._frameData) + { + // The animation is already destroyed, probably from a callback + return false; + } + + // Previous index + var idx = this.currentFrame.index; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index))) + { + this._parent.setFrame(this.currentFrame); + } + + if (this.onUpdate && signalUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + + }, + + /** + * Advances by the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex + quantity; + + if (frame >= this._frames.length) + { + if (this.loop) + { + frame %= this._frames.length; + } + else + { + frame = this._frames.length - 1; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex - quantity; + + if (frame < 0) + { + if (this.loop) + { + frame = this._frames.length + frame; + } + else + { + frame++; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Changes the FrameData object this Animation is using. + * + * @method Phaser.Animation#updateFrameData + * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. + */ + updateFrameData: function (frameData) { + + this._frameData = frameData; + this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null; + + }, + + /** + * Cleans up this animation ready for deletion. Nulls all values and references. + * + * @method Phaser.Animation#destroy + */ + destroy: function () { + + if (!this._frameData) + { + // Already destroyed + return; + } + + 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(); + + if (this.onUpdate) + { + this.onUpdate.dispose(); + } + + }, + + /** + * Called internally when the animation finishes playback. + * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. + * + * @method Phaser.Animation#complete + */ + complete: function () { + + this._frameIndex = this._frames.length - 1; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + 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; + +/** +* @name Phaser.Animation#paused +* @property {boolean} paused - Gets and sets the paused state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'paused', { + + get: function () { + + return this.isPaused; + + }, + + set: function (value) { + + this.isPaused = value; + + if (value) + { + // Paused + this._pauseStartTime = this.game.time.time; + } + else + { + // Un-paused + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this.delay; + } + } + + } + +}); + +/** +* @name Phaser.Animation#reversed +* @property {boolean} reversed - Gets and sets the isReversed state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'reversed', { + + get: function () { + + return this.isReversed; + + }, + + set: function (value) { + + this.isReversed = value; + + } + +}); + +/** +* @name Phaser.Animation#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @name Phaser.Animation#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +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.setFrame(this.currentFrame); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + } + } + + } + +}); + +/** +* @name Phaser.Animation#speed +* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'speed', { + + get: function () { + + return 1000 / this.delay; + + }, + + set: function (value) { + + if (value > 0) + { + this.delay = 1000 / value; + } + + } + +}); + +/** +* @name Phaser.Animation#enableUpdate +* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { + + get: function () { + + return (this.onUpdate !== null); + + }, + + set: function (value) { + + if (value && this.onUpdate === null) + { + this.onUpdate = new Phaser.Signal(); + } + else if (!value && this.onUpdate !== null) + { + this.onUpdate.dispose(); + this.onUpdate = null; + } + + } + +}); + +/** +* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. +* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' +* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); +* +* @method Phaser.Animation.generateFrameNames +* @static +* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. +* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. +* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. +* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'. +* @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. +* @return {string[]} An array of framenames. +*/ +Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { + + if (suffix === undefined) { suffix = ''; } + + var output = []; + var frame = ''; + + if (start < stop) + { + for (var i = start; i <= stop; i++) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + else + { + for (var i = start; i >= stop; i--) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + + return output; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Frame is a single frame of an animation and is part of a FrameData collection. +* +* @class Phaser.Frame +* @constructor +* @param {number} index - The index of this Frame within the FrameData set it is being added to. +* @param {number} x - X position of the frame within the texture image. +* @param {number} y - Y position of the frame within the texture image. +* @param {number} width - Width of the frame within the texture image. +* @param {number} height - Height of the frame within the texture image. +* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. +*/ +Phaser.Frame = function (index, x, y, width, height, name) { + + /** + * @property {number} index - The index of this Frame within the FrameData set it is being added to. + */ + this.index = index; + + /** + * @property {number} x - X position within the image to cut from. + */ + this.x = x; + + /** + * @property {number} y - Y position within the image to cut from. + */ + this.y = y; + + /** + * @property {number} width - Width of the frame. + */ + this.width = width; + + /** + * @property {number} height - Height of the frame. + */ + this.height = height; + + if (this.width === 0 || this.height === 0) + { + console.warn('Phaser.Frame: Frame "' + this.name + '" has a width or height of zero'); + } + + /** + * @property {string} name - Useful for Texture Atlas files (is set to the filename value). + */ + this.name = name; + + /** + * @property {number} centerX - Center X position within the image to cut from. + */ + this.centerX = Math.floor(width / 2); + + /** + * @property {number} centerY - Center Y position within the image to cut from. + */ + this.centerY = Math.floor(height / 2); + + /** + * @property {number} distance - The distance from the top left to the bottom-right of this Frame. + */ + this.distance = Phaser.Math.distance(0, 0, width, height); + + /** + * @property {boolean} rotated - Is the frame rotated in the source texture? + * @default + */ + this.rotated = false; + + /** + * @property {boolean} trimmed - Was it trimmed when packed? + * @default + */ + this.trimmed = false; + + /** + * @property {number} sourceSizeW - Width of the original sprite before it was trimmed. + */ + this.sourceSizeW = width; + + /** + * @property {number} sourceSizeH - Height of the original sprite before it was trimmed. + */ + this.sourceSizeH = height; + + /** + * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeX = 0; + + /** + * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeY = 0; + + /** + * @property {number} spriteSourceSizeW - Width of the trimmed sprite. + * @default + */ + this.spriteSourceSizeW = 0; + + /** + * @property {number} spriteSourceSizeH - Height of the trimmed sprite. + * @default + */ + this.spriteSourceSizeH = 0; + + /** + * @property {number} right - The right of the Frame (x + width). + */ + this.right = this.x + this.width; + + /** + * @property {number} bottom - The bottom of the frame (y + height). + */ + this.bottom = this.y + this.height; + +}; + +Phaser.Frame.prototype = { + + /** + * Adjusts of all the Frame properties based on the given width and height values. + * + * @method Phaser.Frame#resize + * @param {integer} width - The new width of the Frame. + * @param {integer} height - The new height of the Frame. + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + this.centerX = Math.floor(width / 2); + this.centerY = Math.floor(height / 2); + this.distance = Phaser.Math.distance(0, 0, width, height); + this.sourceSizeW = width; + this.sourceSizeH = height; + this.right = this.x + width; + this.bottom = this.y + height; + + }, + + /** + * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. + * + * @method Phaser.Frame#setTrim + * @param {boolean} trimmed - If this frame was trimmed or not. + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + */ + setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { + + this.trimmed = trimmed; + + if (trimmed) + { + 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; + } + + }, + + /** + * Clones this Frame into a new Phaser.Frame object and returns it. + * Note that all properties are cloned, including the name and index. + * + * @method Phaser.Frame#clone + * @return {Phaser.Frame} An exact copy of this Frame object. + */ + clone: function () { + + var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name); + + for (var prop in this) + { + if (this.hasOwnProperty(prop)) + { + output[prop] = this[prop]; + } + } + + return output; + + }, + + /** + * Returns a Rectangle set to the dimensions of this Frame. + * + * @method Phaser.Frame#getRect + * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to. + * @return {Phaser.Rectangle} A rectangle. + */ + getRect: function (out) { + + if (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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. +* +* @class Phaser.FrameData +* @constructor +*/ +Phaser.FrameData = function () { + + /** + * @property {Array} _frames - Local array of frames. + * @private + */ + this._frames = []; + + /** + * @property {Array} _frameNames - Local array of frame names for name to index conversions. + * @private + */ + this._frameNames = []; + +}; + +Phaser.FrameData.prototype = { + + /** + * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. + * + * @method Phaser.FrameData#addFrame + * @param {Phaser.Frame} frame - The frame to add to this FrameData set. + * @return {Phaser.Frame} The frame that was just added. + */ + addFrame: function (frame) { + + frame.index = this._frames.length; + + this._frames.push(frame); + + if (frame.name !== '') + { + this._frameNames[frame.name] = frame.index; + } + + return frame; + + }, + + /** + * Get a Frame by its numerical index. + * + * @method Phaser.FrameData#getFrame + * @param {number} index - The index of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or undefined. + */ + getFrame: function (index) { + + if (index >= this._frames.length) + { + index = 0; + } + + return this._frames[index]; + + }, + + /** + * Get a Frame by its frame name. + * + * @method Phaser.FrameData#getFrameByName + * @param {string} name - The name of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or null. + */ + getFrameByName: function (name) { + + if (typeof this._frameNames[name] === 'number') + { + return this._frames[this._frameNames[name]]; + } + + return null; + + }, + + /** + * Check if there is a Frame with the given name. + * + * @method Phaser.FrameData#checkFrameName + * @param {string} name - The name of the frame you want to check. + * @return {boolean} True if the frame is found, otherwise false. + */ + checkFrameName: function (name) { + + if (this._frameNames[name] == null) + { + return false; + } + + return true; + + }, + + /** + * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains. + * + * @method Phaser.FrameData#clone + * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains. + */ + clone: function () { + + var output = new Phaser.FrameData(); + + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output._frames.push(this._frames[i].clone()); + } + + for (var p in this._frameNames) + { + if (this._frameNames.hasOwnProperty(p)) + { + output._frameNames.push(this._frameNames[p]); + } + } + + return output; + + }, + + /** + * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. + * + * @method Phaser.FrameData#getFrameRange + * @param {number} start - The starting frame index. + * @param {number} end - The ending frame index. + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. + */ + getFrameRange: function (start, end, output) { + + if (output === undefined) { output = []; } + + for (var i = start; i <= end; i++) + { + output.push(this._frames[i]); + } + + return output; + + }, + + /** + * Returns all of the Frames in this FrameData set where the frame index is found in the input array. + * The frames are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrames + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. + */ + getFrames: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + // We only need the indexes + output.push(this._frames[i]); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the input array contain names or indexes? + if (useNumericIndex) + { + // The actual frame + output.push(this.getFrame(frames[i])); + } + else + { + // The actual frame + output.push(this.getFrameByName(frames[i])); + } + } + } + + return output; + + }, + + /** + * Returns all of the Frame indexes in this FrameData set. + * The frames indexes are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrameIndexes + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frame indexes matching the given names or IDs. + */ + getFrameIndexes: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No frames array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output.push(this._frames[i].index); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the frames array contain names or indexes? + if (useNumericIndex && this._frames[frames[i]]) + { + output.push(this._frames[frames[i]].index); + } + else + { + if (this.getFrameByName(frames[i])) + { + output.push(this.getFrameByName(frames[i]).index); + } + } + } + } + + return output; + + }, + + /** + * Destroys this FrameData collection by nulling the _frames and _frameNames arrays. + * + * @method Phaser.FrameData#destroy + */ + destroy: function () { + + this._frames = null; + this._frameNames = null; + + } + +}; + +Phaser.FrameData.prototype.constructor = Phaser.FrameData; + +/** +* @name Phaser.FrameData#total +* @property {number} total - The total number of frames in this FrameData set. +* @readonly +*/ +Object.defineProperty(Phaser.FrameData.prototype, "total", { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +* +* @class Phaser.AnimationParser +* @static +*/ +Phaser.AnimationParser = { + + /** + * Parse a Sprite Sheet and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.spriteSheet + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. + * @param {number} frameWidth - The fixed width of each frame of the animation. + * @param {number} frameHeight - The fixed height of each frame of the animation. + * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + var img = key; + + if (typeof key === 'string') + { + img = game.cache.getImage(key); + } + + if (img === null) + { + return null; + } + + var width = img.width; + var height = img.height; + + if (frameWidth <= 0) + { + frameWidth = Math.floor(-width / Math.min(-1, frameWidth)); + } + + if (frameHeight <= 0) + { + frameHeight = Math.floor(-height / Math.min(-1, frameHeight)); + } + + var row = Math.floor((width - margin) / (frameWidth + spacing)); + var column = Math.floor((height - margin) / (frameHeight + spacing)); + var total = row * column; + + if (skipFrames > total || skipFrames < -total) + { + console.warn( + "Phaser.AnimationParser.spriteSheet: skipFrames = " + + skipFrames.toString() + " is larger than total sprite number " + + total.toString()); + return null; + } + + if (skipFrames < 0) + { + // Allow negative skipframes. + skipFrames = total + skipFrames; + } + + if (frameMax !== -1) + { + total = skipFrames + frameMax; + } + + // Zero or smaller than frame sizes? + if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0) + { + console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight"); + return null; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var x = margin; + var y = margin; + + for (var i = 0; i < total; i++) + { + data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '')); + + x += frameWidth + spacing; + + if (x + frameWidth > width) + { + x = margin; + y += frameHeight + spacing; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONData: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].frame.x, + frames[i].frame.y, + frames[i].frame.w, + frames[i].frame.h, + frames[i].filename + )); + + if (frames[i].trimmed) + { + newFrame.setTrim( + frames[i].trimmed, + frames[i].sourceSize.w, + frames[i].sourceSize.h, + frames[i].spriteSourceSize.x, + frames[i].spriteSourceSize.y, + frames[i].spriteSourceSize.w, + frames[i].spriteSourceSize.h + ); + } + + if (frames[i].rotated) + { + newFrame.rotated = true; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataPyxel + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataPyxel: function (game, json) { + + // Malformed? There are a few keys to check here. + var signature = ['layers', 'tilewidth','tileheight','tileswide', 'tileshigh']; + + signature.forEach( function(key) { + if (!json[key]) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "' + key + '" key.'); + console.log(json); + return; + } + }); + + // For this purpose, I only care about parsing tilemaps with a single layer. + if (json['layers'].length !== 1) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps.'); + console.log(json); + return; + } + + var data = new Phaser.FrameData(); + + var tileheight = json['tileheight']; + var tilewidth = json['tilewidth']; + + var frames = json['layers'][0]['tiles']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].x, + frames[i].y, + tilewidth, + tileheight, + "frame_" + i // No names are included in pyxel tilemap data. + )); + + // No trim data is included. + newFrame.setTrim(false); + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataHash + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataHash: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + var i = 0; + + for (var key in frames) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[key].frame.x, + frames[key].frame.y, + frames[key].frame.w, + frames[key].frame.h, + key + )); + + if (frames[key].trimmed) + { + newFrame.setTrim( + frames[key].trimmed, + frames[key].sourceSize.w, + frames[key].sourceSize.h, + frames[key].spriteSourceSize.x, + frames[key].spriteSourceSize.y, + frames[key].spriteSourceSize.w, + frames[key].spriteSourceSize.h + ); + } + + if (frames[key].rotated) + { + newFrame.rotated = true; + } + + i++; + } + + return data; + + }, + + /** + * Parse the XML data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.XMLData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + XMLData: function (game, xml) { + + // Malformed? + if (!xml.getElementsByTagName('TextureAtlas')) + { + console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing tag"); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var frames = xml.getElementsByTagName('SubTexture'); + var newFrame; + + var name; + var frame; + var x; + var y; + var width; + var height; + var frameX; + var frameY; + var frameWidth; + var frameHeight; + + for (var i = 0; i < frames.length; i++) + { + frame = frames[i].attributes; + + name = frame.name.value; + x = parseInt(frame.x.value, 10); + y = parseInt(frame.y.value, 10); + width = parseInt(frame.width.value, 10); + height = parseInt(frame.height.value, 10); + + frameX = null; + frameY = null; + + if (frame.frameX) + { + frameX = Math.abs(parseInt(frame.frameX.value, 10)); + frameY = Math.abs(parseInt(frame.frameY.value, 10)); + frameWidth = parseInt(frame.frameWidth.value, 10); + frameHeight = parseInt(frame.frameHeight.value, 10); + } + + newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name)); + + // Trimmed? + if (frameX !== null || frameY !== null) + { + newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight); + } + } + + return data; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser has one single cache in which it stores all assets. +* +* The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using +* a unique string-based key as their identifier. Assets stored in different areas of the cache can have the +* same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, +* because they are unique data types. +* +* The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets +* such as images they are automatically placed into their respective cache. Most common Game Objects, such as +* Sprites and Videos automatically query the cache to extract the assets they need on instantiation. +* +* You can access the cache from within a State via `this.cache`. From here you can call any public method it has, +* including adding new entries to it, deleting them or querying them. +* +* Understand that almost without exception when you get an item from the cache it will return a reference to the +* item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original +* object in the cache will also be updated, even if you don't put it back into the cache again. +* +* By default when you change State the cache is _not_ cleared, although there is an option to clear it should +* your game require it. In a typical game set-up the cache is populated once after the main game has loaded and +* then used as an asset store. +* +* @class Phaser.Cache +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Cache = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. + * @property {boolean} autoResolveURL + */ + this.autoResolveURL = false; + + /** + * The main cache object into which all resources are placed. + * @property {object} _cache + * @private + */ + this._cache = { + canvas: {}, + image: {}, + texture: {}, + sound: {}, + video: {}, + text: {}, + json: {}, + xml: {}, + physics: {}, + tilemap: {}, + binary: {}, + bitmapData: {}, + bitmapFont: {}, + shader: {}, + renderTexture: {}, + compressedTexture: {} + }; + + /** + * @property {object} _urlMap - Maps URLs to resources. + * @private + */ + this._urlMap = {}; + + /** + * @property {Image} _urlResolver - Used to resolve URLs to the absolute path. + * @private + */ + this._urlResolver = new Image(); + + /** + * @property {string} _urlTemp - Temporary variable to hold a resolved url. + * @private + */ + this._urlTemp = null; + + /** + * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices. + */ + this.onSoundUnlock = new Phaser.Signal(); + + /** + * @property {array} _cacheMap - Const to cache object look-up array. + * @private + */ + this._cacheMap = []; + + this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas; + this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image; + this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture; + this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound; + this._cacheMap[Phaser.Cache.TEXT] = this._cache.text; + this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics; + this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap; + this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary; + this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData; + this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont; + this._cacheMap[Phaser.Cache.JSON] = this._cache.json; + this._cacheMap[Phaser.Cache.XML] = this._cache.xml; + this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video; + this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader; + this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture; + + /** + * @property {number} + * @private + */ + this._pendingCount = 0; + + /** + * Dispatched when the DEFAULT and MISSING images have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). + * + * @property {Phaser.Signal} onReady + */ + this.onReady = new Phaser.Signal(); + + this._addImages(); + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.CANVAS = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.IMAGE = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXTURE = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SOUND = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXT = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.PHYSICS = 6; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TILEMAP = 7; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BINARY = 8; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPDATA = 9; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPFONT = 10; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.JSON = 11; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.XML = 12; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.VIDEO = 13; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SHADER = 14; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.RENDER_TEXTURE = 15; + +/** +* The default image used for a texture when no other is specified. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.DEFAULT = null; + +/** + * Key for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_KEY = '__default'; + +/** + * URL for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='; + +/** +* The default image used for a texture when the source image is missing. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.MISSING = null; + +/** + * Key for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_KEY = '__missing'; + +/** + * URL for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='; + +/** +* The maximum amount of time (ms) to wait for the built-in DEFAULT and MISSING images to load. +* @static +* @type {number} +* @default +*/ +Phaser.Cache.READY_TIMEOUT = 1000; + +Phaser.Cache.prototype = { + + ////////////////// + // Add Methods // + ////////////////// + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCompressedTextureMetaData + * @private + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url + * @param {string} extension + * @param {array} arrayBuffer + * @return {object} The compressed texture entry. + */ + addCompressedTextureMetaData: function (key, url, extension, arrayBuffer) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + var data = (extension in Phaser.LoaderParser) ? Phaser.LoaderParser[extension](arrayBuffer) : arrayBuffer; + + var texture = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData(), + fileFormat: extension + }; + + texture.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = texture; + + this._resolveURL(url, texture); + + return texture; + + }, + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCanvas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {HTMLCanvasElement} canvas - The Canvas DOM element. + * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`. + */ + addCanvas: function (key, canvas, context) { + + if (context === undefined) { context = canvas.getContext('2d'); } + + this._cache.canvas[key] = { canvas: canvas, context: context }; + + }, + + /** + * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. + * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. + * + * If the image has not yet been fetched (successfully or not), a `console.warn` message will be displayed. + * + * @method Phaser.Cache#addImage + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra image data. + * @return {object} The full image object that was added to the cache. + */ + addImage: function (key, url, data) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + if (data.complete === false) + { + console.warn('Phaser.Cache.addImage: Image "' + key + '" hasn\'t been retrieved yet'); + } + + var img = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData() + }; + + img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = img; + + this._resolveURL(url, img); + + if (key === '__default') + { + Phaser.Cache.DEFAULT = new PIXI.Texture(img.base); + } + else if (key === '__missing') + { + Phaser.Cache.MISSING = new PIXI.Texture(img.base); + } + + return img; + + }, + + /** + * @method Phaser.Cache#addImageAsync + * @private + */ + addImageAsync: function (key, src, callback) { + + var self = this; + var img = new Image(); + + img.onload = function () { + callback.call(this, self.addImage(key, null, img)); + self._removePending(); + img.onload = null; + }; + + this._addPending(); + img.src = src; + + }, + + /** + * Adds a default image to be used in special cases such as WebGL Filters. + * It uses the special reserved key of `__default`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addDefaultImage + * @protected + */ + addDefaultImage: function () { + + this.addImageAsync(Phaser.Cache.DEFAULT_KEY, Phaser.Cache.DEFAULT_SRC, function (obj) { + // Because we don't want to invalidate the sprite batch for an invisible texture + obj.base.skipRender = true; + + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.DEFAULT = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds an image to be used when a key is wrong / missing. + * It uses the special reserved key of `__missing`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addMissingImage + * @protected + */ + addMissingImage: function () { + + this.addImageAsync(Phaser.Cache.MISSING_KEY, Phaser.Cache.MISSING_SRC, function (obj) { + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.MISSING = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addSound + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sound data. + * @param {boolean} webAudio - True if the file is using web audio. + * @param {boolean} audioTag - True if the file is using legacy HTML audio. + */ + addSound: function (key, url, data, webAudio, audioTag) { + + if (webAudio === undefined) { webAudio = true; audioTag = false; } + if (audioTag === undefined) { webAudio = false; audioTag = true; } + + var decoded = false; + + if (audioTag) + { + decoded = true; + } + + this._cache.sound[key] = { + url: url, + data: data, + isDecoding: false, + decoded: decoded, + webAudio: webAudio, + audioTag: audioTag, + locked: this.game.sound.touchLocked + }; + + this._resolveURL(url, this._cache.sound[key]); + + }, + + /** + * Add a new text data. + * + * @method Phaser.Cache#addText + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addText: function (key, url, data) { + + this._cache.text[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.text[key]); + + }, + + /** + * Add a new physics data object to the Cache. + * + * @method Phaser.Cache#addPhysicsData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} JSONData - The physics data object (a JSON file). + * @param {number} format - The format of the physics data. + */ + addPhysicsData: function (key, url, JSONData, format) { + + this._cache.physics[key] = { url: url, data: JSONData, format: format }; + + this._resolveURL(url, this._cache.physics[key]); + + }, + + /** + * Add a new tilemap to the Cache. + * + * @method Phaser.Cache#addTilemap + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} mapData - The tilemap data object (either a CSV or JSON file). + * @param {number} format - The format of the tilemap data. + */ + addTilemap: function (key, url, mapData, format) { + + this._cache.tilemap[key] = { url: url, data: mapData, format: format }; + + this._resolveURL(url, this._cache.tilemap[key]); + + }, + + /** + * Add a binary object in to the cache. + * + * @method Phaser.Cache#addBinary + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {object} binaryData - The binary object to be added to the cache. + */ + addBinary: function (key, binaryData) { + + this._cache.binary[key] = binaryData; + + }, + + /** + * Add a BitmapData object to the cache. + * + * @method Phaser.Cache#addBitmapData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. + * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. + * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. + */ + addBitmapData: function (key, bitmapData, frameData) { + + bitmapData.key = key; + + if (frameData === undefined) + { + frameData = new Phaser.FrameData(); + frameData.addFrame(bitmapData.textureFrame); + } + + this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData }; + + return bitmapData; + + }, + + /** + * Add a new Bitmap Font to the Cache. + * + * @method Phaser.Cache#addBitmapFont + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra font data. + * @param {object} atlasData - The Bitmap Font data. + * @param {string} [atlasType='xml'] - The format of the Bitmap Font data file: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) { + + var obj = { + url: url, + data: data, + font: null, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + if (atlasType === 'json') + { + obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + else + { + obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new Bitmap Font to the Cache, where the font texture is part of a Texture Atlas. + * + * The atlas must already exist in the cache, and be available based on the given `atlasKey`. + * + * The `atlasFrame` specifies the name of the frame within the atlas that the Bitmap Font is + * stored in. + * + * The `dataKey` is the key of the XML or JSON Bitmap Font Data, which must already be in + * the Cache. + * + * @method Phaser.Cache#addBitmapFontFromAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} atlasKey - The key of the Texture Atlas in the Cache. + * @param {string} atlasFrame - The frame of the Texture Atlas that the Bitmap Font is in. + * @param {string} dataKey - The key of the Bitmap Font data in the Cache + * @param {string} [dataType='xml'] - The format of the Bitmap Font data: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFontFromAtlas: function (key, atlasKey, atlasFrame, dataKey, dataType, xSpacing, ySpacing) { + + var frame = this.getFrameByName(atlasKey, atlasFrame); + + if (!frame) + { + return; + } + + var obj = { + font: null, + base: this.getBaseTexture(atlasKey), + frame: frame + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + var fontData; + + if (dataType === 'json') + { + fontData = this.getJSON(dataKey); + obj.font = Phaser.LoaderParser.jsonBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + else + { + fontData = this.getXML(dataKey); + obj.font = Phaser.LoaderParser.xmlBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + }, + + /** + * Add a new json object into the cache. + * + * @method Phaser.Cache#addJSON + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra json data. + */ + addJSON: function (key, url, data) { + + this._cache.json[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.json[key]); + + }, + + /** + * Add a new xml object into the cache. + * + * @method Phaser.Cache#addXML + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addXML: function (key, url, data) { + + this._cache.xml[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.xml[key]); + + }, + + /** + * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addVideo + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra video data. + * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. + */ + addVideo: function (key, url, data, isBlob) { + + this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true }; + + this._resolveURL(url, this._cache.video[key]); + + }, + + /** + * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addShader + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra shader data. + */ + addShader: function (key, url, data) { + + this._cache.shader[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.shader[key]); + + }, + + /** + * Add a new Phaser.RenderTexture in to the cache. + * + * @method Phaser.Cache#addRenderTexture + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture. + */ + addRenderTexture: function (key, texture) { + + this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') }; + + }, + + /** + * Add a new sprite sheet in to the cache. + * + * @method Phaser.Cache#addSpriteSheet + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sprite sheet data. + * @param {number} frameWidth - Width of the sprite sheet. + * @param {number} frameHeight - Height of the sprite sheet. + * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + */ + addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + var obj = { + key: key, + url: url, + data: data, + frameWidth: frameWidth, + frameHeight: frameHeight, + margin: margin, + spacing: spacing, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) + }; + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new texture atlas to the Cache. + * + * @method Phaser.Cache#addTextureAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra texture atlas data. + * @param {object} atlasData - Texture atlas frames data. + * @param {number} format - The format of the texture atlas. + */ + addTextureAtlas: function (key, url, data, atlasData, format) { + + var obj = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key); + } + else if (format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + obj.frameData = Phaser.AnimationParser.JSONDataPyxel(this.game, atlasData, key); + } + else + { + // Let's just work it out from the frames array + if (Array.isArray(atlasData.frames)) + { + obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key); + } + else + { + obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key); + } + } + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + //////////////////////////// + // Sound Related Methods // + //////////////////////////// + + /** + * Reload a Sound file from the server. + * + * @method Phaser.Cache#reloadSound + * @param {string} key - The key of the asset within the cache. + */ + reloadSound: function (key) { + + var _this = this; + + var sound = this.getSound(key); + + if (sound) + { + sound.data.src = sound.url; + + sound.data.addEventListener('canplaythrough', function () { + return _this.reloadSoundComplete(key); + }, false); + + sound.data.load(); + } + + }, + + /** + * Fires the onSoundUnlock event when the sound has completed reloading. + * + * @method Phaser.Cache#reloadSoundComplete + * @param {string} key - The key of the asset within the cache. + */ + reloadSoundComplete: function (key) { + + var sound = this.getSound(key); + + if (sound) + { + sound.locked = false; + this.onSoundUnlock.dispatch(key); + } + + }, + + /** + * Updates the sound object in the cache. + * + * @method Phaser.Cache#updateSound + * @param {string} key - The key of the asset within the cache. + */ + updateSound: function (key, property, value) { + + var sound = this.getSound(key); + + if (sound) + { + sound[property] = value; + } + + }, + + /** + * Add a new decoded sound. + * + * @method Phaser.Cache#decodedSound + * @param {string} key - The key of the asset within the cache. + * @param {object} data - Extra sound data. + */ + decodedSound: function (key, data) { + + var sound = this.getSound(key); + + sound.data = data; + sound.decoded = true; + sound.isDecoding = false; + + }, + + /** + * Check if the given sound has finished decoding. + * + * @method Phaser.Cache#isSoundDecoded + * @param {string} key - The key of the asset within the cache. + * @return {boolean} The decoded state of the Sound object. + */ + isSoundDecoded: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return sound.decoded; + } + + }, + + /** + * Check if the given sound is ready for playback. + * A sound is considered ready when it has finished decoding and the device is no longer touch locked. + * + * @method Phaser.Cache#isSoundReady + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the sound is decoded and the device is not touch locked. + */ + isSoundReady: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return (sound.decoded && !this.game.sound.touchLocked); + } + + }, + + //////////////////////// + // Check Key Methods // + //////////////////////// + + /** + * Checks if a key for the given cache object type exists. + * + * @method Phaser.Cache#checkKey + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists, otherwise false. + */ + checkKey: function (cache, key) { + + if (this._cacheMap[cache][key]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given URL has been loaded into the Cache. + * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. + * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox + * which may cause double-load instances. + * + * @method Phaser.Cache#checkURL + * @param {string} url - The url to check for in the cache. + * @return {boolean} True if the url exists, otherwise false. + */ + checkURL: function (url) { + + if (this._urlMap[this._resolveURL(url)]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given key exists in the Canvas Cache. + * + * @method Phaser.Cache#checkCanvasKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkCanvasKey: function (key) { + + return this.checkKey(Phaser.Cache.CANVAS, key); + + }, + + /** + * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. + * + * @method Phaser.Cache#checkImageKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkImageKey: function (key) { + + return this.checkKey(Phaser.Cache.IMAGE, key); + + }, + + /** + * Checks if the given key exists in the Texture Cache. + * + * @method Phaser.Cache#checkTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXTURE, key); + + }, + + /** + * Checks if the given key exists in the Sound Cache. + * + * @method Phaser.Cache#checkSoundKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkSoundKey: function (key) { + + return this.checkKey(Phaser.Cache.SOUND, key); + + }, + + /** + * Checks if the given key exists in the Text Cache. + * + * @method Phaser.Cache#checkTextKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXT, key); + + }, + + /** + * Checks if the given key exists in the Physics Cache. + * + * @method Phaser.Cache#checkPhysicsKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkPhysicsKey: function (key) { + + return this.checkKey(Phaser.Cache.PHYSICS, key); + + }, + + /** + * Checks if the given key exists in the Tilemap Cache. + * + * @method Phaser.Cache#checkTilemapKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTilemapKey: function (key) { + + return this.checkKey(Phaser.Cache.TILEMAP, key); + + }, + + /** + * Checks if the given key exists in the Binary Cache. + * + * @method Phaser.Cache#checkBinaryKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBinaryKey: function (key) { + + return this.checkKey(Phaser.Cache.BINARY, key); + + }, + + /** + * Checks if the given key exists in the BitmapData Cache. + * + * @method Phaser.Cache#checkBitmapDataKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapDataKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPDATA, key); + + }, + + /** + * Checks if the given key exists in the BitmapFont Cache. + * + * @method Phaser.Cache#checkBitmapFontKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapFontKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPFONT, key); + + }, + + /** + * Checks if the given key exists in the JSON Cache. + * + * @method Phaser.Cache#checkJSONKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkJSONKey: function (key) { + + return this.checkKey(Phaser.Cache.JSON, key); + + }, + + /** + * Checks if the given key exists in the XML Cache. + * + * @method Phaser.Cache#checkXMLKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkXMLKey: function (key) { + + return this.checkKey(Phaser.Cache.XML, key); + + }, + + /** + * Checks if the given key exists in the Video Cache. + * + * @method Phaser.Cache#checkVideoKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkVideoKey: function (key) { + + return this.checkKey(Phaser.Cache.VIDEO, key); + + }, + + /** + * Checks if the given key exists in the Fragment Shader Cache. + * + * @method Phaser.Cache#checkShaderKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkShaderKey: function (key) { + + return this.checkKey(Phaser.Cache.SHADER, key); + + }, + + /** + * Checks if the given key exists in the Render Texture Cache. + * + * @method Phaser.Cache#checkRenderTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkRenderTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key); + + }, + + //////////////// + // Get Items // + //////////////// + + /** + * Get an item from a cache based on the given key and property. + * + * This method is mostly used internally by other Cache methods such as `getImage` but is exposed + * publicly for your own use as well. + * + * @method Phaser.Cache#getItem + * @param {string} key - The key of the asset within the cache. + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output. + * @param {string} [property] - If you require a specific property from the cache item, specify it here. + * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. + */ + getItem: function (key, cache, method, property) { + + if (!this.checkKey(cache, key)) + { + if (method) + { + console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.'); + } + } + else + { + if (property === undefined) + { + return this._cacheMap[cache][key]; + } + else + { + return this._cacheMap[cache][key][property]; + } + } + + return null; + + }, + + /** + * Gets a Canvas object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getCanvas + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The canvas object or `null` if no item could be found matching the given key. + */ + getCanvas: function (key) { + + return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas'); + + }, + + /** + * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. + * + * If you need the image used by a bitmap font or similar then please use those respective 'get' methods. + * + * @method Phaser.Cache#getImage + * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. + * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned. + * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. + */ + getImage: function (key, full) { + + if (key === undefined || key === null) + { + key = '__default'; + } + + if (full === undefined) { full = false; } + + var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage'); + + if (img === null) + { + img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage'); + } + + if (full) + { + return img; + } + else + { + return img.data; + } + + }, + + /** + * Get a single texture frame by key. + * + * You'd only do this to get the default Frame created for a non-atlas / spritesheet image. + * + * @method Phaser.Cache#getTextureFrame + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Frame} The frame data. + */ + getTextureFrame: function (key) { + + return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame'); + + }, + + /** + * Gets a Phaser.Sound object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSound + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Sound} The sound object. + */ + getSound: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSound'); + + }, + + /** + * Gets a raw Sound data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSoundData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The sound data. + */ + getSoundData: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data'); + + }, + + /** + * Gets a Text object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getText + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The text data. + */ + getText: function (key) { + + return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data'); + + }, + + /** + * Gets a Physics Data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can get either the entire data set, a single object or a single fixture of an object from it. + * + * @method Phaser.Cache#getPhysicsData + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all. + * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. + * @return {object} The requested physics object data if found. + */ + getPhysicsData: function (key, object, fixtureKey) { + + var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data'); + + if (data === null || object === undefined || object === null) + { + return data; + } + else + { + if (data[object]) + { + var fixtures = data[object]; + + // Try to find a fixture by its fixture key if given + if (fixtures && fixtureKey) + { + for (var fixture in fixtures) + { + // This contains the fixture data of a polygon or a circle + fixture = fixtures[fixture]; + + // Test the key + if (fixture.fixtureKey === fixtureKey) + { + return fixture; + } + } + + // We did not find the requested fixture + console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"'); + } + else + { + return fixtures; + } + } + else + { + console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"'); + } + } + + return null; + + }, + + /** + * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getTilemapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The raw tilemap data in CSV or JSON format. + */ + getTilemapData: function (key) { + + return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData'); + + }, + + /** + * Gets a binary object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBinary + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The binary data object. + */ + getBinary: function (key) { + + return this.getItem(key, Phaser.Cache.BINARY, 'getBinary'); + + }, + + /** + * Gets a BitmapData object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. + */ + getBitmapData: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data'); + + }, + + /** + * Gets a Bitmap Font object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapFont + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not. + */ + getBitmapFont: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont'); + + }, + + /** + * Gets a JSON object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can either return the object by reference (the default), or return a clone + * of it by setting the `clone` argument to `true`. + * + * @method Phaser.Cache#getJSON + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false) + * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. + */ + getJSON: function (key, clone) { + + var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data'); + + if (data) + { + if (clone) + { + return Phaser.Utils.extend(true, Array.isArray(data) ? [] : {}, data); + } + else + { + return data; + } + } + else + { + return null; + } + + }, + + /** + * Gets an XML object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getXML + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The XML object. + */ + getXML: function (key) { + + return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data'); + + }, + + /** + * Gets a Phaser.Video object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getVideo + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Video} The video object. + */ + getVideo: function (key) { + + return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo'); + + }, + + /** + * Gets a fragment shader object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getShader + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {string} The shader object. + */ + getShader: function (key) { + + return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data'); + + }, + + /** + * Gets a RenderTexture object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getRenderTexture + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame. + */ + getRenderTexture: function (key) { + + return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture'); + + }, + + //////////////////////////// + // Frame Related Methods // + //////////////////////////// + + /** + * Gets a PIXI.BaseTexture by key from the given Cache. + * + * @method Phaser.Cache#getBaseTexture + * @param {string} key - Asset key of the image for which you want the BaseTexture for. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {PIXI.BaseTexture} The BaseTexture object. + */ + getBaseTexture: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getBaseTexture', 'base'); + + }, + + /** + * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. + * + * @method Phaser.Cache#getFrame + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.Frame} The frame data. + */ + getFrame: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrame', 'frame'); + + }, + + /** + * Get the total number of frames contained in the FrameData object specified by the given key. + * + * @method Phaser.Cache#getFrameCount + * @param {string} key - Asset key of the FrameData you want. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {number} Then number of frames. 0 if the image is not found. + */ + getFrameCount: function (key, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.total; + } + else + { + return 0; + } + + }, + + /** + * Gets a Phaser.FrameData object from the Image Cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.FrameData} The frame data. + */ + getFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrameData', 'frameData'); + + }, + + /** + * Check if the FrameData for the given key exists in the Image Cache. + * + * @method Phaser.Cache#hasFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {boolean} True if the given key has frameData in the cache, otherwise false. + */ + hasFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return (this.getItem(key, cache, '', 'frameData') !== null); + + }, + + /** + * Replaces a set of frameData with a new Phaser.FrameData object. + * + * @method Phaser.Cache#updateFrameData + * @param {string} key - The unique key by which you will reference this object. + * @param {number} frameData - The new FrameData. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + */ + updateFrameData: function (key, frameData, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + if (this._cacheMap[cache][key]) + { + this._cacheMap[cache][key].frameData = frameData; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByIndex + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {number} index - The index of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByIndex: function (key, index, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrame(index); + } + else + { + return null; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByName + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {string} name - The name of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByName: function (key, name, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrameByName(name); + } + else + { + return null; + } + + }, + + /** + * Get a cached object by the URL. + * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. + * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. + * + * @method Phaser.Cache#getURL + * @param {string} url - The url for the object loaded to get from the cache. + * @return {object} The cached object. + */ + getURL: function (url) { + + var url = this._resolveURL(url); + + if (url) + { + return this._urlMap[url]; + } + else + { + console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false'); + return null; + } + + }, + + /** + * Gets all keys used in the requested Cache. + * + * @method Phaser.Cache#getKeys + * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. + * @return {Array} The array of keys in the requested cache. + */ + getKeys: function (cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + var out = []; + + if (this._cacheMap[cache]) + { + for (var key in this._cacheMap[cache]) + { + if (key !== '__default' && key !== '__missing') + { + out.push(key); + } + } + } + + return out; + + }, + + ///////////////////// + // Remove Methods // + ///////////////////// + + /** + * Removes a canvas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeCanvas + * @param {string} key - Key of the asset you want to remove. + */ + removeCanvas: function (key) { + + delete this._cache.canvas[key]; + + }, + + /** + * Removes an image from the cache. + * + * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. + * + * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeImage + * @param {string} key - Key of the asset you want to remove. + * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed? + */ + removeImage: function (key, destroyBaseTexture) { + + if (destroyBaseTexture === undefined) { destroyBaseTexture = true; } + + var img = this.getImage(key, true); + + if (destroyBaseTexture && img.base) + { + img.base.destroy(); + } + + delete this._cache.image[key]; + + }, + + /** + * Removes a sound from the cache. + * + * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will + * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then + * you must finish your house-keeping and destroy them all yourself first, before calling this method. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSound + * @param {string} key - Key of the asset you want to remove. + */ + removeSound: function (key) { + + delete this._cache.sound[key]; + + }, + + /** + * Removes a text file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeText + * @param {string} key - Key of the asset you want to remove. + */ + removeText: function (key) { + + delete this._cache.text[key]; + + }, + + /** + * Removes a physics data file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removePhysics + * @param {string} key - Key of the asset you want to remove. + */ + removePhysics: function (key) { + + delete this._cache.physics[key]; + + }, + + /** + * Removes a tilemap from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTilemap + * @param {string} key - Key of the asset you want to remove. + */ + removeTilemap: function (key) { + + delete this._cache.tilemap[key]; + + }, + + /** + * Removes a binary file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBinary + * @param {string} key - Key of the asset you want to remove. + */ + removeBinary: function (key) { + + delete this._cache.binary[key]; + + }, + + /** + * Removes a bitmap data from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapData + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapData: function (key) { + + delete this._cache.bitmapData[key]; + + }, + + /** + * Removes a bitmap font from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapFont + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapFont: function (key) { + + delete this._cache.bitmapFont[key]; + + }, + + /** + * Removes a json object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeJSON + * @param {string} key - Key of the asset you want to remove. + */ + removeJSON: function (key) { + + delete this._cache.json[key]; + + }, + + /** + * Removes a xml object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeXML + * @param {string} key - Key of the asset you want to remove. + */ + removeXML: function (key) { + + delete this._cache.xml[key]; + + }, + + /** + * Removes a video from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeVideo + * @param {string} key - Key of the asset you want to remove. + */ + removeVideo: function (key) { + + delete this._cache.video[key]; + + }, + + /** + * Removes a shader from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeShader + * @param {string} key - Key of the asset you want to remove. + */ + removeShader: function (key) { + + delete this._cache.shader[key]; + + }, + + /** + * Removes a Render Texture from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeRenderTexture + * @param {string} key - Key of the asset you want to remove. + */ + removeRenderTexture: function (key) { + + delete this._cache.renderTexture[key]; + + }, + + /** + * Removes a Sprite Sheet from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSpriteSheet + * @param {string} key - Key of the asset you want to remove. + */ + removeSpriteSheet: function (key) { + + delete this._cache.spriteSheet[key]; + + }, + + /** + * Removes a Texture Atlas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTextureAtlas + * @param {string} key - Key of the asset you want to remove. + */ + removeTextureAtlas: function (key) { + + delete this._cache.image[key]; + + }, + + /** + * Empties out all of the GL Textures from Images stored in the cache. + * This is called automatically when the WebGL context is lost and then restored. + * + * @method Phaser.Cache#clearGLTextures + * @protected + */ + clearGLTextures: function () { + + for (var key in this._cache.image) + { + this._cache.image[key].base._glTextures = []; + } + + }, + + /** + * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`. + * This is then looked-up by the Cache.getURL and Cache.checkURL calls. + * + * @method Phaser.Cache#_resolveURL + * @private + * @param {string} url - The URL to resolve. This is appended to Loader.baseURL. + * @param {object} [data] - The data associated with the URL to be stored to the URL Map. + * @return {string} The resolved URL. + */ + _resolveURL: function (url, data) { + + if (!this.autoResolveURL) + { + return null; + } + + this._urlResolver.src = this.game.load.baseURL + url; + + this._urlTemp = this._urlResolver.src; + + // Ensure no request is actually made + this._urlResolver.src = ''; + + // Record the URL to the map + if (data) + { + this._urlMap[this._urlTemp] = data; + } + + return this._urlTemp; + + }, + + /** + * Clears the cache. Removes every local cache object reference. + * If an object in the cache has a `destroy` method it will be called; + * otherwise, `destroy` will be called on any of the object's `base`, `data`, + * `frameData`, or `texture` properties. + * + * @method Phaser.Cache#destroy + */ + destroy: function () { + + for (var i = 0; i < this._cacheMap.length; i++) + { + var cache = this._cacheMap[i]; + + for (var key in cache) + { + if (key !== '__default' && key !== '__missing') + { + this.destroyItem(cache[key]); + + delete cache[key]; + } + } + } + + this._urlMap = null; + this._urlResolver = null; + this._urlTemp = null; + + }, + + /** + * @method Phaser.Cache#destroyItem + * @protected + * @param {object} item + */ + destroyItem: function (item) { + + if (item.destroy) + { + item.destroy(); + } + else + { + if (item.base && item.base.destroy) + { + item.base.destroy(); + } + + if (item.data && item.data.destroy) + { + item.data.destroy(); + } + + if (item.frameData && item.frameData.destroy) + { + item.frameData.destroy(); + } + + if (item.texture && item.texture.destroy) + { + item.texture.destroy(true); + } + } + + }, + + /** + * Starts loading the DEFAULT and MISSING images. + * + * @private + */ + _addImages: function () { + + this._pendingCount = 0; + + this.addDefaultImage(); + this.addMissingImage(); + + var self = this; + var readyTimeout = Phaser.Cache.READY_TIMEOUT; + + if (Phaser.Cache.READY_TIMEOUT > 0) + { + setTimeout(function () { + if (!self.isReady) + { + console.warn('Phaser.Cache: Still waiting for images after %s ms.', readyTimeout); + + self._ready(); + } + }, Phaser.Cache.READY_TIMEOUT); + } + else + { + this._ready(); + } + + }, + + + /** + * Increments the pending count. + * + * @private + */ + _addPending: function () { + + this._pendingCount += 1; + + }, + + + /** + * Decrements the pending count and checks if complete. + * + * @private + */ + _removePending: function () { + + this._pendingCount -= 1; + this._checkReady(); + + }, + + + /** + * Calls {@link #_ready} if no pending items remain. + * + * @private + */ + _checkReady: function () { + + if (this.isReady) + { + this._ready(); + } + + }, + + + /** + * Resets pending count and triggers {@link #onReady}. + * + * @private + */ + _ready: function () { + + this._pendingCount = 0; + this.onReady.dispatch(this); + + } + +}; + +Phaser.Cache.prototype.constructor = Phaser.Cache; + +/** +* The DEFAULT and MISSING textures have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). +* +* @property {boolean} Phaser.Cache#isReady +*/ +Object.defineProperty(Phaser.Cache.prototype, 'isReady', { + get: function () { + return this._pendingCount <= 0; + } +}); + +/* jshint wsh:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* +* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. +* +* Parallel loading (see {@link #enableParallel}) is supported and enabled by default. +* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}. +* +* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and +* [Shoebox](http://renderhjs.net/shoebox/) +* +* @class Phaser.Loader +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Loader = function (game) { + + /** + * Local reference to game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + /** + * Local reference to the Phaser.Cache. + * @property {Phaser.Cache} cache + * @protected + */ + this.cache = game.cache; + + /** + * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * True if the Loader is in the process of loading the queue. + * @property {boolean} isLoading + * @default + */ + this.isLoading = false; + + /** + * True if all assets in the queue have finished loading. + * @property {boolean} hasLoaded + * @default + */ + this.hasLoaded = false; + + /** + * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}. + * + * This property is an object containing: sprite, rect, direction, width and height + * + * @property {?object} preloadSprite + * @protected + */ + this.preloadSprite = null; + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * @property {boolean|string} crossOrigin + * @default + */ + this.crossOrigin = false; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * Useful if allowing the asset base url to be configured outside of the game code. + * The string _must_ end with a "/". + * + * @property {string} baseURL + */ + this.baseURL = ''; + + /** + * The value of `path`, if set, is placed before any _relative_ file path given. For example: + * + * ```javascript + * load.path = "images/sprites/"; + * load.image("ball", "ball.png"); + * load.image("tree", "level1/oaktree.png"); + * load.image("boom", "http://server.com/explode.png"); + * ``` + * + * Would load the `ball` file from `images/sprites/ball.png` and the tree from + * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL + * given as it's an absolute URL. + * + * Please note that the path is added before the filename but *after* the baseURL (if set.) + * + * The string _must_ end with a "/". + * + * @property {string} path + */ + this.path = ''; + + /** + * Used to map the application mime-types to to the Accept header in XHR requests. + * If you don't require these mappings, or they cause problems on your server, then + * remove them from the headers object and the XHR request will not try to use them. + * + * This object can also be used to set the `X-Requested-With` header to + * `XMLHttpRequest` (or any other value you need). To enable this do: + * + * ```javascript + * this.load.headers.requestedWith = 'XMLHttpRequest' + * ``` + * + * before adding anything to the Loader. The XHR loader will then call: + * + * ```javascript + * setRequestHeader('X-Requested-With', this.headers['requestedWith']) + * ``` + * + * @property {object} headers + * @default + */ + this.headers = { + "requestedWith": false, + "json": "application/json", + "xml": "application/xml" + }; + + /** + * This event is dispatched when the loading process starts: before the first file has been requested, + * but after all the initial packs have been loaded. + * + * @property {Phaser.Signal} onLoadStart + */ + this.onLoadStart = new Phaser.Signal(); + + /** + * This event is dispatched when the final file in the load queue has either loaded or failed. + * + * @property {Phaser.Signal} onLoadComplete + */ + this.onLoadComplete = new Phaser.Signal(); + + /** + * This event is dispatched when an asset pack has either loaded or failed to load. + * + * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. + * + * Params: `(pack key, success?, total packs loaded, total packs)` + * + * @property {Phaser.Signal} onPackComplete + */ + this.onPackComplete = new Phaser.Signal(); + + /** + * This event is dispatched immediately before a file starts loading. + * It's possible the file may fail (eg. download error, invalid format) after this event is sent. + * + * Params: `(progress, file key, file url)` + * + * @property {Phaser.Signal} onFileStart + */ + this.onFileStart = new Phaser.Signal(); + + /** + * This event is dispatched when a file has either loaded or failed to load. + * + * Any function bound to this will receive the following parameters: + * + * progress, file key, success?, total loaded files, total files + * + * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. + * + * @property {Phaser.Signal} onFileComplete + */ + this.onFileComplete = new Phaser.Signal(); + + /** + * This event is dispatched when a file (or pack) errors as a result of the load request. + * + * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. + * + * Params: `(file key, file)` + * + * @property {Phaser.Signal} onFileError + */ + this.onFileError = new Phaser.Signal(); + + /** + * If true (the default) then parallel downloading will be enabled. + * + * To disable all parallel downloads this must be set to false prior to any resource being loaded. + * + * @property {boolean} enableParallel + */ + this.enableParallel = true; + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Many current browsers limit 6 requests per domain; this is slightly conservative. + * + * This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently. + * + * @property {integer} maxParallelDownloads + */ + this.maxParallelDownloads = 4; + + /** + * A counter: if more than zero, files will be automatically added as a synchronization point. + * @property {integer} _withSyncPointDepth; + */ + this._withSyncPointDepth = 0; + + /** + * Contains all the information for asset files (including packs) to load. + * + * File/assets are only removed from the list after all loading completes. + * + * @property {file[]} _fileList + * @private + */ + this._fileList = []; + + /** + * Inflight files (or packs) that are being fetched/processed. + * + * This means that if there are any files in the flight queue there should still be processing + * going on; it should only be empty before or after loading. + * + * The files in the queue may have additional properties added to them, + * including `requestObject` which is normally the associated XHR. + * + * @property {file[]} _flightQueue + * @private + */ + this._flightQueue = []; + + /** + * The offset into the fileList past all the complete (loaded or error) entries. + * + * @property {integer} _processingHead + * @private + */ + this._processingHead = 0; + + /** + * True when the first file (not pack) has loading started. + * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded. + * + * @property {boolean} _initialPacksLoaded + * @private + */ + this._fileLoadStarted = false; + + /** + * Total packs seen - adjusted when a pack is added. + * @property {integer} _totalPackCount + * @private + */ + this._totalPackCount = 0; + + /** + * Total files seen - adjusted when a file is added. + * @property {integer} _totalFileCount + * @private + */ + this._totalFileCount = 0; + + /** + * Total packs loaded - adjusted just prior to `onPackComplete`. + * @property {integer} _loadedPackCount + * @private + */ + this._loadedPackCount = 0; + + /** + * Total files loaded - adjusted just prior to `onFileComplete`. + * @property {integer} _loadedFileCount + * @private + */ + this._loadedFileCount = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_PHASER_JSON = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5; + +Phaser.Loader.prototype = { + + /** + * Set a Sprite to be a "preload" sprite by passing it to this method. + * + * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. + * This allows you to easily make loading bars for games. + * + * The sprite will automatically be made visible when calling this. + * + * @method Phaser.Loader#setPreloadSprite + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load. + * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. + */ + setPreloadSprite: function (sprite, direction) { + + direction = direction || 0; + + this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null }; + + if (direction === 0) + { + // Horizontal rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height); + } + else + { + // Vertical rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1); + } + + sprite.crop(this.preloadSprite.rect); + + sprite.visible = true; + + }, + + /** + * Called automatically by ScaleManager when the game resizes in RESIZE scalemode. + * + * This can be used to adjust the preloading sprite size, eg. + * + * @method Phaser.Loader#resize + * @protected + */ + resize: function () { + + if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height) + { + this.preloadSprite.rect.height = this.preloadSprite.sprite.height; + } + + }, + + /** + * Check whether a file/asset with a specific key is queued to be loaded. + * + * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey} + * + * @method Phaser.Loader#checkKeyExists + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ + checkKeyExists: function (type, key) { + + return this.getAssetIndex(type, key) > -1; + + }, + + /** + * Get the queue-index of the file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAssetIndex + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {number} The index of this key in the filelist, or -1 if not found. + * The index may change and should only be used immediately following this call + */ + getAssetIndex: function (type, key) { + + var bestFound = -1; + + for (var i = 0; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + if (file.type === type && file.key === key) + { + bestFound = i; + + // An already loaded/loading file may be superceded. + if (!file.loaded && !file.loading) + { + break; + } + } + } + + return bestFound; + + }, + + /** + * Find a file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAsset + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. + * The index may change and should only be used immediately following this call. + */ + getAsset: function (type, key) { + + var fileIndex = this.getAssetIndex(type, key); + + if (fileIndex > -1) + { + return { index: fileIndex, file: this._fileList[fileIndex] }; + } + + return false; + + }, + + /** + * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. + * + * This will abort any loading and clear any queued assets. + * + * Optionally you can clear any associated events. + * + * @method Phaser.Loader#reset + * @protected + * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared. + * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them. + */ + reset: function (hard, clearEvents) { + + if (clearEvents === undefined) { clearEvents = false; } + + if (this.resetLocked) + { + return; + } + + if (hard) + { + this.preloadSprite = null; + } + + this.isLoading = false; + + this._processingHead = 0; + this._fileList.length = 0; + this._flightQueue.length = 0; + + this._fileLoadStarted = false; + this._totalFileCount = 0; + this._totalPackCount = 0; + this._loadedPackCount = 0; + this._loadedFileCount = 0; + + if (clearEvents) + { + this.onLoadStart.removeAll(); + this.onLoadComplete.removeAll(); + this.onPackComplete.removeAll(); + this.onFileStart.removeAll(); + this.onFileComplete.removeAll(); + this.onFileError.removeAll(); + } + + }, + + /** + * Internal function that adds a new entry to the file list. Do not call directly. + * + * @method Phaser.Loader#addToFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} [url] - The URL the asset will be loaded from. + * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. + * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. + * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. + * @return {Phaser.Loader} This instance of the Phaser Loader. + */ + addToFileList: function (type, key, url, properties, overwrite, extension) { + + if (overwrite === undefined) { overwrite = false; } + + if (key === undefined || key === '') + { + console.warn("Phaser.Loader: Invalid or no key given of type " + type); + return this; + } + + if (url === undefined || url === null) + { + if (extension) + { + url = key + extension; + } + else + { + console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key); + return this; + } + } + + var file = { + type: type, + key: key, + path: this.path, + url: url, + syncPoint: this._withSyncPointDepth > 0, + data: null, + loading: false, + loaded: false, + error: false + }; + + if (properties) + { + for (var prop in properties) + { + file[prop] = properties[prop]; + } + } + + var fileIndex = this.getAssetIndex(type, key); + + if (overwrite && fileIndex > -1) + { + var currentFile = this._fileList[fileIndex]; + + if (!currentFile.loading && !currentFile.loaded) + { + this._fileList[fileIndex] = file; + } + else + { + this._fileList.push(file); + this._totalFileCount++; + } + } + else if (fileIndex === -1) + { + this._fileList.push(file); + this._totalFileCount++; + } + + return this; + + }, + + /** + * Internal function that replaces an existing entry in the file list with a new one. Do not call directly. + * + * @method Phaser.Loader#replaceInFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} url - The URL the asset will be loaded from. + * @param {object} properties - Any additional properties needed to load the file. + */ + replaceInFileList: function (type, key, url, properties) { + + return this.addToFileList(type, key, url, properties, true); + + }, + + /** + * Add a JSON resource pack ('packfile') to the Loader. + * + * A packfile is a JSON file that contains a list of assets to the be loaded. + * Please see the example 'loader/asset pack' in the Phaser Examples repository. + * + * Packs are always put before the first non-pack file that is not loaded / loading. + * + * This means that all packs added before any loading has started are added to the front + * of the file queue, in the order added. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#pack + * @param {string} key - Unique asset key of this resource pack. + * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. + * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO + * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. + * @return {Phaser.Loader} This Loader instance. + */ + pack: function (key, url, data, callbackContext) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (callbackContext === undefined) { callbackContext = null; } + + if (!url && !data) + { + console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.'); + + return this; + } + + var pack = { + type: 'packfile', + key: key, + url: url, + path: this.path, + syncPoint: true, + data: null, + loading: false, + loaded: false, + error: false, + callbackContext: callbackContext + }; + + // A data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + pack.data = data || {}; + + // Already consider 'loaded' + pack.loaded = true; + } + + // Add before first non-pack/no-loaded ~ last pack from start prior to loading + // (Read one past for splice-to-end) + for (var i = 0; i < this._fileList.length + 1; i++) + { + var file = this._fileList[i]; + + if (!file || (!file.loaded && !file.loading && file.type !== 'packfile')) + { + this._fileList.splice(i, 0, pack); + this._totalPackCount++; + break; + } + } + + return this; + + }, + + /** + * Adds an Image to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * This method also supports passing in a texture object as the `url` argument. This allows you to load + * compressed textures into Phaser. You can also use `Loader.texture` to do this. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.image('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * @method Phaser.Loader#image + * @param {string} key - Unique asset key of this image file. + * @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + image: function (key, url, overwrite) { + + if (typeof url === 'object') + { + return this.texture(key, url, overwrite); + } + else + { + return this.addToFileList('image', key, url, undefined, overwrite, '.png'); + } + + }, + + /** + * Generate an image from a BitmapData object and add it to the current load queue. + * + * @method Phaser.Loader#imageFromBitmapData + * @param {string} key - Unique asset key for the generated image. + * @param {Phaser.BitmapData} bitmapData + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + imageFromBitmapData: function (key, bitmapData, overwrite) { + + return this.image(key, bitmapData.canvas.toDataURL('image/png'), overwrite); + + }, + + /** + * Generate a grid image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromGrid + * @see Phaser.Create#grid + */ + imageFromGrid: function (key, width, height, cellWidth, cellHeight, color) { + + return this.imageFromBitmapData(key, this.game.create.grid(key, width, height, cellWidth, cellHeight, color, false)); + + }, + + /** + * Generate a texture image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromTexture + * @see Phaser.Create#texture + */ + imageFromTexture: function (key, data, pixelWidth, pixelHeight, palette) { + + return this.imageFromBitmapData(key, this.game.create.texture(key, data, pixelWidth, pixelHeight, palette, false)); + + }, + + /** + * Adds a Compressed Texture Image to the current load queue. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.texture('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#texture + * @param {string} key - Unique asset key of this image file. + * @param {object} object - The texture path data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + texture: function (key, object, overwrite) { + + if (this.game.renderType === Phaser.WEBGL) + { + var compression = this.game.renderer.extensions.compression; + var exkey; + + for (exkey in object) + { + if (exkey.toUpperCase() in compression) + { + return this.addToFileList('texture', key, object[exkey], undefined, overwrite, '.pvr'); + } + } + } + + // Check if we have a truecolor texture to fallback. + // Also catches calls to this function that are from a Canvas renderer + + if (object['truecolor']) + { + this.addToFileList('image', key, object['truecolor'], undefined, overwrite, '.png'); + } + + return this; + + }, + + /** + * Adds an array of images to the current load queue. + * + * It works by passing each element of the array to the Loader.image method. + * + * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. + * + * Retrieve the images via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#images + * @param {array} keys - An array of unique asset keys of the image files. + * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. + * @return {Phaser.Loader} This Loader instance. + */ + images: function (keys, urls) { + + if (Array.isArray(urls)) + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i], urls[i]); + } + } + else + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i]); + } + } + + return this; + + }, + + /** + * Adds a Text file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getText(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#text + * @param {string} key - Unique asset key of the text file. + * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + text: function (key, url, overwrite) { + + return this.addToFileList('text', key, url, undefined, overwrite, '.txt'); + + }, + + /** + * Adds a JSON file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#json + * @param {string} key - Unique asset key of the json file. + * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + json: function (key, url, overwrite) { + + return this.addToFileList('json', key, url, undefined, overwrite, '.json'); + + }, + + /** + * Adds a fragment shader file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getShader(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" + * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#shader + * @param {string} key - Unique asset key of the fragment file. + * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + shader: function (key, url, overwrite) { + + return this.addToFileList('shader', key, url, undefined, overwrite, '.frag'); + + }, + + /** + * Adds an XML file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getXML(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#xml + * @param {string} key - Unique asset key of the xml file. + * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + xml: function (key, url, overwrite) { + + return this.addToFileList('xml', key, url, undefined, overwrite, '.xml'); + + }, + + /** + * Adds a JavaScript file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. + * If you do not desire this action then provide a URL. + * + * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! + * + * A callback, which will be invoked as the script tag has been created, can also be specified. + * The callback must return relevant `data`. + * + * @method Phaser.Loader#script + * @param {string} key - Unique asset key of the script file. + * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing. + * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. + * @return {Phaser.Loader} This Loader instance. + */ + script: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + if (callback !== false && callbackContext === undefined) { callbackContext = this; } + + return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js'); + + }, + + /** + * Adds a binary file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBinary(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. + * If you do not desire this action then provide a URL. + * + * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. + * When the callback is called it will be passed 2 parameters: the key of the file and the file data. + * + * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. + * + * @method Phaser.Loader#binary + * @param {string} key - Unique asset key of the binary file. + * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it. + * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context. + * @return {Phaser.Loader} This Loader instance. + */ + binary: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + // Why is the default callback context the ..callback? + if (callback !== false && callbackContext === undefined) { callbackContext = callback; } + + return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin'); + + }, + + /** + * Adds a Sprite Sheet to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal + * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. + * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. + * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming + * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. + * If you've got an atlas then use `Loader.atlas` instead. + * + * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#spritesheet + * @param {string} key - Unique asset key of the sheet file. + * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet. + * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.Loader} This Loader instance. + */ + spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing, skipFrames: skipFrames }, false, '.png'); + + }, + + /** + * Adds an audio file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getSound(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. + * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. + * The solution is to use a lower encoding rate such as 44100 Hz. + * + * @method Phaser.Loader#audio + * @param {string} key - Unique asset key of the audio file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp3']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audio: function (key, urls, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (autoDecode === undefined) { autoDecode = true; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); + + }, + + /** + * Adds an audio sprite file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Audio Sprites are a combination of audio files and a JSON configuration. + * + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * Retrieve the file via `Cache.getSoundData(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#audioSprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (jsonURL === undefined) { jsonURL = null; } + if (jsonData === undefined) { jsonData = null; } + if (autoDecode === undefined) { autoDecode = true; } + + this.audio(key, urls, autoDecode); + + if (jsonURL) + { + this.json(key + '-audioatlas', jsonURL); + } + else if (jsonData) + { + if (typeof jsonData === 'string') + { + jsonData = JSON.parse(jsonData); + } + + this.cache.addJSON(key + '-audioatlas', '', jsonData); + } + else + { + console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object'); + } + + return this; + + }, + + /** + * A legacy alias for Loader.audioSprite. Please see that method for documentation. + * + * @method Phaser.Loader#audiosprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode); + + }, + + /** + * Adds a video file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getVideo(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. + * + * @method Phaser.Loader#video + * @param {string} key - Unique asset key of the video file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp4']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete. + * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. + * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. + * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the + * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. + * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set. + * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. + * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. + * @return {Phaser.Loader} This Loader instance. + */ + video: function (key, urls, loadEvent, asBlob) { + + if (loadEvent === undefined) + { + if (this.game.device.firefox) + { + loadEvent = 'loadeddata'; + } + else + { + loadEvent = 'canplaythrough'; + } + } + + if (asBlob === undefined) { asBlob = false; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent }); + + }, + + /** + * Adds a Tile Map data file to the current load queue. + * + * Phaser can load data in two different formats: CSV and Tiled JSON. + * + * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". + * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#tilemap + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. + * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + * @return {Phaser.Loader} This Loader instance. + */ + tilemap: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Tilemap.CSV; } + + if (!url && !data) + { + if (format === Phaser.Tilemap.CSV) + { + url = key + '.csv'; + } + else + { + url = key + '.json'; + } + } + + // A map data object has been given + if (data) + { + switch (format) + { + // A csv string or object has been given + case Phaser.Tilemap.CSV: + break; + + // A json string or object has been given + case Phaser.Tilemap.TILED_JSON: + + if (typeof data === 'string') + { + data = JSON.parse(data); + } + break; + } + + this.cache.addTilemap(key, null, data, format); + } + else + { + this.addToFileList('tilemap', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds a physics data file to the current load queue. + * + * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". + * It will always use `.json` as the extension. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#physics + * @param {string} key - Unique asset key of the physics json data. + * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. + * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data. + * @return {Phaser.Loader} This Loader instance. + */ + physics: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; } + + if (!url && !data) + { + url = key + '.json'; + } + + // A map data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + this.cache.addPhysicsData(key, null, data, format); + } + else + { + this.addToFileList('physics', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds Bitmap Font files to the current load queue. + * + * To create the Bitmap Font files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `xmlData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#bitmapFont + * @param {string} key - Unique asset key of the bitmap font. + * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". + * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". + * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json). + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + * @return {Phaser.Loader} This Loader instance. + */ + bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (atlasURL === null && atlasData === null) + { + atlasURL = key + '.xml'; + } + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + // A URL to a json/xml atlas has been given + if (atlasURL) + { + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing }); + } + else + { + // A stringified xml/json atlas has been given + if (typeof atlasData === 'string') + { + var json, xml; + + try + { + json = JSON.parse(atlasData); + } + catch ( e ) + { + xml = this.parseXml(atlasData); + } + + if (!xml && !json) + { + throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given"); + } + + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml, + atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing }); + } + } + + return this; + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONArray + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONHash + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * This call expects the atlas data to be in the Starling XML data format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasXML + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasXML: function (key, textureURL, atlasURL, atlasData) { + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (!atlasURL && !atlasData) + { + atlasURL = key + '.xml'; + } + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlas + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. + * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING. + * @return {Phaser.Loader} This Loader instance. + */ + atlas: function (key, textureURL, atlasURL, atlasData, format) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } + + if (!atlasURL && !atlasData) + { + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + atlasURL = key + '.xml'; + } + else + { + atlasURL = key + '.json'; + } + } + + // A URL to a json/xml file has been given + if (atlasURL) + { + this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); + } + else + { + switch (format) + { + // A json string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: + + if (typeof atlasData === 'string') + { + atlasData = JSON.parse(atlasData); + } + break; + + // An xml string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: + + if (typeof atlasData === 'string') + { + var xml = this.parseXml(atlasData); + + if (!xml) + { + throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); + } + + atlasData = xml; + } + break; + } + + this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); + + } + + return this; + + }, + + /** + * Add a synchronization point to the assets / files added within the supplied callback. + * + * A synchronization point denotes that an asset _must_ be completely loaded before + * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait + * for previous assets to load (unless they are sync-points). Resources, such as packs, may still + * be downloaded around sync-points, as long as they do not finalize loading. + * + * @method Phaser.Loader#withSyncPoint + * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader. + * @param {object} [callbackContext=(loader)] - Context for the callback. + * @return {Phaser.Loader} This Loader instance. + */ + withSyncPoint: function (callback, callbackContext) { + + this._withSyncPointDepth++; + + try { + callback.call(callbackContext || this, this); + } finally { + this._withSyncPointDepth--; + } + + return this; + }, + + /** + * Add a synchronization point to a specific file/asset in the load queue. + * + * This has no effect on already loaded assets. + * + * @method Phaser.Loader#addSyncPoint + * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc). + * @param {string} key - Key of the file you want to turn into a sync point. + * @return {Phaser.Loader} This Loader instance. + * @see {@link Phaser.Loader#withSyncPoint withSyncPoint} + */ + addSyncPoint: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + asset.file.syncPoint = true; + } + + return this; + }, + + /** + * Remove a file/asset from the loading queue. + * + * A file that is loaded or has started loading cannot be removed. + * + * @method Phaser.Loader#removeFile + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - Key of the file you want to remove. + */ + removeFile: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + if (!asset.loaded && !asset.loading) + { + this._fileList.splice(asset.index, 1); + } + } + + }, + + /** + * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead. + * + * @method Phaser.Loader#removeAll + * @protected + */ + removeAll: function () { + + this._fileList.length = 0; + this._flightQueue.length = 0; + + }, + + /** + * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. + * + * @method Phaser.Loader#start + */ + start: function () { + + if (this.isLoading) + { + return; + } + + this.hasLoaded = false; + this.isLoading = true; + + this.updateProgress(); + + this.processLoadQueue(); + + }, + + /** + * Process the next item(s) in the file/asset queue. + * + * Process the queue and start loading enough items to fill up the inflight queue. + * + * If a sync-file is encountered then subsequent asset processing is delayed until it completes. + * The exception to this rule is that packfiles can be downloaded (but not processed) even if + * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel. + * such as during the start phaser. + * + * @method Phaser.Loader#processLoadQueue + * @private + */ + processLoadQueue: function () { + + if (!this.isLoading) + { + console.warn('Phaser.Loader - active loading canceled / reset'); + this.finishedLoading(true); + return; + } + + // Empty the flight queue as applicable + for (var i = 0; i < this._flightQueue.length; i++) + { + var file = this._flightQueue[i]; + + if (file.loaded || file.error) + { + this._flightQueue.splice(i, 1); + i--; + + file.loading = false; + file.requestUrl = null; + file.requestObject = null; + + if (file.error) + { + this.onFileError.dispatch(file.key, file); + } + + if (file.type !== 'packfile') + { + this._loadedFileCount++; + this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount); + } + else if (file.type === 'packfile' && file.error) + { + // Non-error pack files are handled when processing the file queue + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + } + } + + // When true further non-pack file downloads are suppressed + var syncblock = false; + + var inflightLimit = this.enableParallel ? Math.max(1, this.maxParallelDownloads) : 1; + + for (var i = this._processingHead; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + // Pack is fetched (ie. has data) and is currently at the start of the process queue. + if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead) + { + // Processing the pack / adds more files + this.processPack(file); + + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + if (file.loaded || file.error) + { + // Item at the start of file list finished, can skip it in future + if (i === this._processingHead) + { + this._processingHead = i + 1; + } + } + else if (!file.loading && this._flightQueue.length < inflightLimit) + { + // -> not loaded/failed, not loading + if (file.type === 'packfile' && !file.data) + { + // Fetches the pack data: the pack is processed above as it reaches queue-start. + // (Packs do not trigger onLoadStart or onFileStart.) + this._flightQueue.push(file); + file.loading = true; + + this.loadFile(file); + } + else if (!syncblock) + { + if (!this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this._flightQueue.push(file); + file.loading = true; + this.onFileStart.dispatch(this.progress, file.key, file.url); + + this.loadFile(file); + } + } + + if (!file.loaded && file.syncPoint) + { + syncblock = true; + } + + // Stop looking if queue full - or if syncblocked and there are no more packs. + // (As only packs can be loaded around a syncblock) + if (this._flightQueue.length >= inflightLimit || + (syncblock && this._loadedPackCount === this._totalPackCount)) + { + break; + } + } + + this.updateProgress(); + + // True when all items in the queue have been advanced over + // (There should be no inflight items as they are complete - loaded/error.) + if (this._processingHead >= this._fileList.length) + { + this.finishedLoading(); + } + else if (!this._flightQueue.length) + { + // Flight queue is empty but file list is not done being processed. + // This indicates a critical internal error with no known recovery. + console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled"); + + var _this = this; + + setTimeout(function () { + _this.finishedLoading(true); + }, 2000); + } + + }, + + /** + * The loading is all finished. + * + * @method Phaser.Loader#finishedLoading + * @private + * @param {boolean} [abnormal=true] - True if the loading finished abnormally. + */ + finishedLoading: function (abnormal) { + + if (this.hasLoaded) + { + return; + } + + this.hasLoaded = true; + this.isLoading = false; + + // If there were no files make sure to trigger the event anyway, for consistency + if (!abnormal && !this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this.reset(); + + this.onLoadComplete.dispatch(); + + // Check if the state still exists since destroy could have occurred while loading + if (this.game.state) + { + this.game.state.loadComplete(); + } + + }, + + /** + * Informs the loader that the given file resource has been fetched and processed; + * or such a request has failed. + * + * @method Phaser.Loader#asyncComplete + * @private + * @param {object} file + * @param {string} [error=''] - The error message, if any. No message implies no error. + */ + asyncComplete: function (file, errorMessage) { + + if (errorMessage === undefined) { errorMessage = ''; } + + file.loaded = true; + file.error = !!errorMessage; + + if (errorMessage) + { + file.errorMessage = errorMessage; + + console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage); + } + + this.processLoadQueue(); + + }, + + /** + * Process pack data. This will usually modify the file list. + * + * @method Phaser.Loader#processPack + * @private + * @param {object} pack + */ + processPack: function (pack) { + + var packData = pack.data[pack.key]; + + if (!packData) + { + console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key'); + return; + } + + for (var i = 0; i < packData.length; i++) + { + var file = packData[i]; + + switch (file.type) + { + case "image": + this.image(file.key, file.url, file.overwrite); + break; + + case "text": + this.text(file.key, file.url, file.overwrite); + break; + + case "json": + this.json(file.key, file.url, file.overwrite); + break; + + case "xml": + this.xml(file.key, file.url, file.overwrite); + break; + + case "script": + this.script(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "binary": + this.binary(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "spritesheet": + this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case "video": + this.video(file.key, file.urls); + break; + + case "audio": + this.audio(file.key, file.urls, file.autoDecode); + break; + + case "audiosprite": + this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode); + break; + + case "tilemap": + this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]); + break; + + case "physics": + this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]); + break; + + case "bitmapFont": + this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing); + break; + + case "atlasJSONArray": + this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasJSONHash": + this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasXML": + this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlas": + this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]); + break; + + case "shader": + this.shader(file.key, file.url, file.overwrite); + break; + } + } + + }, + + /** + * Transforms the asset URL. + * + * The default implementation prepends the baseURL if the url doesn't begin with http or // + * + * @method Phaser.Loader#transformUrl + * @protected + * @param {string} url - The url to transform. + * @param {object} file - The file object being transformed. + * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead. + */ + transformUrl: function (url, file) { + + if (!url) + { + return false; + } + + if (url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) + { + return url; + } + else + { + return this.baseURL + file.path + url; + } + + }, + + /** + * Start fetching a resource. + * + * All code paths, async or otherwise, from this function must return to `asyncComplete`. + * + * @method Phaser.Loader#loadFile + * @private + * @param {object} file + */ + loadFile: function (file) { + + // Image or Data? + switch (file.type) + { + case 'packfile': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'image': + case 'spritesheet': + case 'textureatlas': + case 'bitmapfont': + this.loadImageTag(file); + break; + + case 'audio': + file.url = this.getAudioURL(file.url); + + if (file.url) + { + // WebAudio or Audio Tag? + if (this.game.sound.usingWebAudio) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + else if (this.game.sound.usingAudioTag) + { + this.loadAudioTag(file); + } + } + else + { + this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support'); + } + break; + + case 'video': + file.url = this.getVideoURL(file.url); + + if (file.url) + { + if (file.asBlob) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'blob', this.fileComplete); + } + else + { + this.loadVideoTag(file); + } + } + else + { + this.fileError(file, null, 'No supported video URL specified or device does not have video playback support'); + } + break; + + case 'json': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + break; + + case 'xml': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete); + break; + + case 'tilemap': + + if (file.format === Phaser.Tilemap.TILED_JSON) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Tilemap.CSV) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete); + } + else + { + this.asyncComplete(file, "invalid Tilemap format: " + file.format); + } + break; + + case 'text': + case 'script': + case 'shader': + case 'physics': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'texture': + + if (file.key.split('_').pop() === 'truecolor') + { + this.loadImageTag(file); + } + else + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + break; + + case 'binary': + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + break; + } + + }, + + /** + * Continue async loading through an Image tag. + * @private + */ + loadImageTag: function (file) { + var _this = this; + + file.data = new Image(); + file.data.name = file.key; + + if (this.crossOrigin) + { + file.data.crossOrigin = this.crossOrigin; + } + + file.data.onload = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileComplete(file); + } + }; + + file.data.onerror = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileError(file); + } + }; + + file.data.src = this.transformUrl(file.url, file); + + // Image is immediately-available/cached + // Special Firefox magic, exclude from cached reload + // More info here: https://github.com/photonstorm/phaser/issues/2534 + if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height) + { + file.data.onload = null; + file.data.onerror = null; + this.fileComplete(file); + } + + }, + + /** + * Continue async loading through a Video tag. + * @private + */ + loadVideoTag: function (file) { + + var _this = this; + + file.data = document.createElement("video"); + file.data.name = file.key; + file.data.controls = false; + file.data.autoplay = false; + + var videoLoadEvent = function () { + + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = true; + Phaser.GAMES[_this.game.id].load.fileComplete(file); + + }; + + file.data.onerror = function () { + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = false; + _this.fileError(file); + }; + + file.data.addEventListener(file.loadEvent, videoLoadEvent, false); + + file.data.src = this.transformUrl(file.url, file); + file.data.load(); + + }, + + /** + * Continue async loading through an Audio tag. + * @private + */ + loadAudioTag: function (file) { + + var _this = this; + + if (this.game.sound.touchLocked) + { + // If audio is locked we can't do this yet, so need to queue this load request. Bum. + file.data = new Audio(); + file.data.name = file.key; + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + + this.fileComplete(file); + } + else + { + file.data = new Audio(); + file.data.name = file.key; + + var playThroughEvent = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileComplete(file); + }; + + file.data.onerror = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileError(file); + }; + + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + file.data.addEventListener('canplaythrough', playThroughEvent, false); + file.data.load(); + } + + }, + + /** + * Starts the xhr loader. + * + * This is designed specifically to use with asset file processing. + * + * @method Phaser.Loader#xhrLoad + * @private + * @param {object} file - The file/pack to load. + * @param {string} url - The URL of the file. + * @param {string} type - The xhr responseType. + * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments. + * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments. + */ + xhrLoad: function (file, url, type, onload, onerror) { + + var xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = type; + + if (this.headers['requestedWith'] !== false) + { + xhr.setRequestHeader('X-Requested-With', this.headers['requestedWith']); + } + + if (this.headers[file.type]) + { + xhr.setRequestHeader('Accept', this.headers[file.type]); + } + + onerror = onerror || this.fileError; + + var _this = this; + + xhr.onload = function () { + + try { + if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. + return onerror.call(_this, file, xhr); + } + else { + return onload.call(_this, file, xhr); + } + } catch (e) { + + // If this was the last file in the queue and an error is thrown in the create method + // then it's caught here, so be sure we don't carry on processing it + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + } + }; + + xhr.onerror = function () { + + try { + + return onerror.call(_this, file, xhr); + + } catch (e) { + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + + } + }; + + file.requestObject = xhr; + file.requestUrl = url; + + xhr.send(); + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getVideoURL + * @private + * @param {object[]|string[]} urls - See {@link #video} for format. + * @return {string} The URL to try and fetch; or null. + */ + getVideoURL: function (urls) { + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var videoType; + + if (url.uri) // {uri: .., type: ..} pair + { + videoType = url.type; + url = url.uri; + + if (this.game.device.canPlayVideo(videoType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + videoType = extension.toLowerCase(); + + if (this.game.device.canPlayVideo(videoType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getAudioURL + * @private + * @param {object[]|string[]} urls - See {@link #audio} for format. + * @return {string} The URL to try and fetch; or null. + */ + getAudioURL: function (urls) { + + if (this.game.sound.noAudio) + { + return null; + } + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var audioType; + + if (url.uri) // {uri: .., type: ..} pair + { + audioType = url.type; + url = url.uri; + + if (this.game.device.canPlayAudio(audioType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + audioType = extension.toLowerCase(); + + if (this.game.device.canPlayAudio(audioType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Error occurred when loading a file. + * + * @method Phaser.Loader#fileError + * @private + * @param {object} file + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + * @param {string} reason + */ + fileError: function (file, xhr, reason) { + + var url = file.requestUrl || this.transformUrl(file.url, file); + var message = 'error loading asset from URL ' + url; + + if (!reason && xhr) + { + reason = xhr.status; + } + + if (reason) + { + message = message + ' (' + reason + ')'; + } + + this.asyncComplete(file, message); + + }, + + /** + * Called when a file has been downloaded and needs to be processed further. + * + * @method Phaser.Loader#fileComplete + * @private + * @param {object} file - File loaded + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + */ + fileComplete: function (file, xhr) { + + var loadNext = true; + + switch (file.type) + { + case 'packfile': + + // Pack data must never be false-ish after it is fetched without error + var data = JSON.parse(xhr.responseText); + file.data = data || {}; + break; + + case 'texture': + + var extension = /\.([^.]+)$/.exec(file.url.split('?', 1)[0])[1].toLowerCase(); + if (file.data !== null) + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, file.data); + } + else + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, xhr.response); + } + break; + + case 'image': + + this.cache.addImage(file.key, file.url, file.data); + break; + + case 'spritesheet': + + this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case 'textureatlas': + + if (file.atlasURL == null) + { + this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); + } + else + { + // Load the JSON or XML before carrying on with the next file + loadNext = false; + + if (file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_HASH || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete); + } + else + { + throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); + } + } + break; + + case 'bitmapfont': + + if (!file.atlasURL) + { + this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing); + } + else + { + // Load the XML before carrying on with the next file + loadNext = false; + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) { + var json; + + try + { + // Try to parse as JSON, if it fails, then it's hopefully XML + json = JSON.parse(xhr.responseText); + } + catch (e) {} + + if (!!json) + { + file.atlasType = 'json'; + this.jsonLoadComplete(file, xhr); + } + else + { + file.atlasType = 'xml'; + this.xmlLoadComplete(file, xhr); + } + }); + } + break; + + case 'video': + + if (file.asBlob) + { + try + { + file.data = xhr.response; + } + catch (e) + { + throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key); + } + } + + this.cache.addVideo(file.key, file.url, file.data, file.asBlob); + break; + + case 'audio': + + if (this.game.sound.usingWebAudio) + { + file.data = xhr.response; + + this.cache.addSound(file.key, file.url, file.data, true, false); + + if (file.autoDecode) + { + this.game.sound.decode(file.key); + } + } + else + { + this.cache.addSound(file.key, file.url, file.data, false, true); + } + break; + + case 'text': + file.data = xhr.responseText; + this.cache.addText(file.key, file.url, file.data); + break; + + case 'shader': + file.data = xhr.responseText; + this.cache.addShader(file.key, file.url, file.data); + break; + + case 'physics': + var data = JSON.parse(xhr.responseText); + this.cache.addPhysicsData(file.key, file.url, data, file.format); + break; + + case 'script': + file.data = document.createElement('script'); + file.data.language = 'javascript'; + file.data.type = 'text/javascript'; + file.data.defer = false; + file.data.text = xhr.responseText; + document.head.appendChild(file.data); + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText); + } + break; + + case 'binary': + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.response); + } + else + { + file.data = xhr.response; + } + + this.cache.addBinary(file.key, file.data); + + break; + } + + if (loadNext) + { + this.asyncComplete(file); + } + + }, + + /** + * Successfully loaded a JSON file - only used for certain types. + * + * @method Phaser.Loader#jsonLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + jsonLoadComplete: function (file, xhr) { + + var data = JSON.parse(xhr.responseText); + + if (file.type === 'tilemap') + { + this.cache.addTilemap(file.key, file.url, data, file.format); + } + else if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'json') + { + this.cache.addJSON(file.key, file.url, data); + } + else + { + this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); + } + + this.asyncComplete(file); + }, + + /** + * Successfully loaded a CSV file - only used for certain types. + * + * @method Phaser.Loader#csvLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + csvLoadComplete: function (file, xhr) { + + var data = xhr.responseText; + + this.cache.addTilemap(file.key, file.url, data, file.format); + + this.asyncComplete(file); + + }, + + /** + * Successfully loaded an XML file - only used for certain types. + * + * @method Phaser.Loader#xmlLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + xmlLoadComplete: function (file, xhr) { + + // Always try parsing the content as XML, regardless of actually response type + var data = xhr.responseText; + var xml = this.parseXml(data); + + if (!xml) + { + var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest + console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')'); + this.asyncComplete(file, "invalid XML"); + return; + } + + if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'textureatlas') + { + this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); + } + else if (file.type === 'xml') + { + this.cache.addXML(file.key, file.url, xml); + } + + this.asyncComplete(file); + + }, + + /** + * Parses string data as XML. + * + * @method Phaser.Loader#parseXml + * @private + * @param {string} data - The XML text to parse + * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document. + */ + parseXml: function (data) { + + var xml; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + // Why is this 'false'? + xml.async = 'false'; + xml.loadXML(data); + } + } + catch (e) + { + xml = null; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + return null; + } + else + { + return xml; + } + + }, + + /** + * Update the loading sprite progress. + * + * @method Phaser.Loader#updateProgress + * @private + */ + updateProgress: function () { + + if (this.preloadSprite) + { + if (this.preloadSprite.direction === 0) + { + this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress); + } + else + { + this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress); + } + + if (this.preloadSprite.sprite) + { + this.preloadSprite.sprite.updateCrop(); + } + else + { + // We seem to have lost our sprite - maybe it was destroyed? + this.preloadSprite = null; + } + } + + }, + + /** + * Returns the number of files that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedFiles + * @protected + * @return {number} The number of files that have already been loaded (even if they errored) + */ + totalLoadedFiles: function () { + + return this._loadedFileCount; + + }, + + /** + * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedFiles + * @protected + * @return {number} The number of files that still remain in the load queue. + */ + totalQueuedFiles: function () { + + return this._totalFileCount - this._loadedFileCount; + + }, + + /** + * Returns the number of asset packs that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedPacks + * @protected + * @return {number} The number of asset packs that have already been loaded (even if they errored) + */ + totalLoadedPacks: function () { + + return this._totalPackCount; + + }, + + /** + * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedPacks + * @protected + * @return {number} The number of asset packs that still remain in the load queue. + */ + totalQueuedPacks: function () { + + return this._totalPackCount - this._loadedPackCount; + + } + +}; + +/** +* The non-rounded load progress value (from 0.0 to 100.0). +* +* A general indicator of the progress. +* It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. +* +* @name Phaser.Loader#progressFloat +* @property {number} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progressFloat", { + + get: function () { + var progress = (this._loadedFileCount / this._totalFileCount) * 100; + return Phaser.Math.clamp(progress || 0, 0, 100); + } + +}); + +/** +* The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}. +* +* @name Phaser.Loader#progress +* @property {integer} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progress", { + + get: function () { + return Math.round(this.progressFloat); + } + +}); + +Phaser.Loader.prototype.constructor = Phaser.Loader; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. +* +* @class Phaser.LoaderParser +*/ +Phaser.LoaderParser = { + + /** + * Alias for xmlBitmapFont, for backwards compatibility. + * + * @method Phaser.LoaderParser.bitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + bitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing, frame, resolution); + + }, + + /** + * Parse a Bitmap Font from an XML file. + * + * @method Phaser.LoaderParser.xmlBitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing; + data.chars = {}; + + var letters = xml.getElementsByTagName('char'); + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + for (var i = 0; i < letters.length; i++) + { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + data.chars[charCode] = { + x: x + parseInt(letters[i].getAttribute('x'), 10), + y: y + parseInt(letters[i].getAttribute('y'), 10), + width: parseInt(letters[i].getAttribute('width'), 10), + height: parseInt(letters[i].getAttribute('height'), 10), + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10) / resolution, + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10) / resolution, + xAdvance: (parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing) / resolution, + kerning: {} + }; + } + + var kernings = xml.getElementsByTagName('kerning'); + + for (i = 0; i < kernings.length; i++) + { + var first = parseInt(kernings[i].getAttribute('first'), 10); + var second = parseInt(kernings[i].getAttribute('second'), 10); + var amount = parseInt(kernings[i].getAttribute('amount'), 10) / resolution; + + data.chars[second].kerning[first] = amount; + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Parse a Bitmap Font from a JSON file. + * + * @method Phaser.LoaderParser.jsonBitmapFont + * @param {object} json - JSON data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = { + font: json.font.info._face, + size: parseInt(json.font.info._size, 10), + lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing, + chars: {} + }; + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + json.font.chars["char"].forEach( + + function parseChar(letter) { + + var charCode = parseInt(letter._id, 10); + + data.chars[charCode] = { + x: x + parseInt(letter._x, 10), + y: y + parseInt(letter._y, 10), + width: parseInt(letter._width, 10), + height: parseInt(letter._height, 10), + xOffset: parseInt(letter._xoffset, 10) / resolution, + yOffset: parseInt(letter._yoffset, 10) / resolution, + xAdvance: (parseInt(letter._xadvance, 10) + xSpacing) / resolution, + kerning: {} + }; + } + + ); + + if (json.font.kernings && json.font.kernings.kerning) + { + json.font.kernings.kerning.forEach( + + function parseKerning(kerning) { + + data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10) / resolution; + + } + + ); + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Finalize Bitmap Font parsing. + * + * @method Phaser.LoaderParser.finalizeBitmapFont + * @private + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {object} bitmapFontData - Pre-parsed bitmap font data. + * @return {object} The parsed Bitmap Font data. + */ + finalizeBitmapFont: function (baseTexture, bitmapFontData) { + + Object.keys(bitmapFontData.chars).forEach( + + function addTexture(charCode) { + + var letter = bitmapFontData.chars[charCode]; + + letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height)); + + } + + ); + + return bitmapFontData; + + }, + + /** + * Extract PVR header from loaded binary + * + * @method Phaser.LoaderParser.pvr + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PVR file including texture data. + */ + pvr: function (arrayBuffer) { + + // Reference: http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf + // PVR 3 header structure + // --------------------------------------- + // address: 0, size: 4 bytes version + // address: 4, size: 4 bytes flags + // address: 8, size: 8 bytes pixel format + // address: 16, size: 4 bytes color space + // address: 20, size: 4 bytes channel type + // address: 24, size: 4 bytes height + // address: 28, size: 4 bytes width + // address: 32, size: 4 bytes depth + // address: 36, size: 4 bytes number of surfaces + // address: 40, size: 4 bytes number of faces + // address: 44, size: 4 bytes number of mipmaps + // address: 48, size: 4 bytes meta data size + // --------------------------------------- + var uintArray = new Uint32Array(arrayBuffer.slice(0, 52)), + byteArray = new Uint8Array(arrayBuffer), + pvrHeader = null, + pixelFormat = (uintArray[3] << 32 | uintArray[2]), + compressionAlgorithm, + glExtensionFormat = 0; + + if (uintArray[0] === 0x03525650 && + [ // Validate WebGL Pixel Format + 0, 1, 2, 3, + 6, 7, 9, 11 + ].indexOf(pixelFormat) >= 0 + ) { + if (pixelFormat >= 0 && pixelFormat <= 3) { + compressionAlgorithm = 'PVRTC'; + } else if (pixelFormat >= 7 && pixelFormat <= 11) { + compressionAlgorithm = 'S3TC'; + } else if (pixelFormat === 6) { + compressionAlgorithm = 'ETC1'; + } + + switch (pixelFormat) { + case 0: + glExtensionFormat = 0x8C01; + break; + case 1: + glExtensionFormat = 0x8C03; + break; + case 2: + glExtensionFormat = 0x8C00; + break; + case 3: + glExtensionFormat = 0x8C02; + break; + case 6: + glExtensionFormat = 0x8D64; + break; + case 7: + glExtensionFormat = 0x83F1; + break; + case 9: + glExtensionFormat = 0x83F2; + break; + case 11: + glExtensionFormat = 0x83F3; + break; + default: + glExtensionFormat = -1; + } + + pvrHeader = { + complete: true, + fileFormat: 'PVR', + compressionAlgorithm: compressionAlgorithm, + flags: uintArray[1], + pixelFormat: pixelFormat, + colorSpace: uintArray[4], + channelType: uintArray[5], + height: uintArray[6], + width: uintArray[7], + depth: uintArray[8], + numberOfSurfaces: uintArray[9], + numberOfFaces: uintArray[10], + numberOfMipmaps: uintArray[11], + metaDataSize: uintArray[12], + textureData: byteArray.subarray(52 + uintArray[12], byteArray.byteLength), + glExtensionFormat: glExtensionFormat + }; + } + + return pvrHeader; + + }, + + /** + * Extract DDS header from loaded binary + * + * @method Phaser.LoaderParser.dds + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed DDS file including texture data. + */ + dds: function (arrayBuffer) { + + // Reference at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx + // DDS header structure + // --------------------------------------- + // address: 0, size: 4 bytes Identifier 'DDS ' + // address: 4, size: 4 bytes size + // address: 8, size: 4 bytes flags + // address: 12, size: 4 bytes height + // address: 16, size: 4 bytes width + // address: 20, size: 4 bytes pitch or linear size + // address: 24, size: 4 bytes depth + // address: 28, size: 4 bytes mipmap count + // address: 32, size: 44 bytes reserved space 1 + // address: 76, size: 4 pixel format size + // address: 80, size: 4 pixel format flag + // address: 84, size: 4 pixel format four CC + // address: 88, size: 4 pixel format bit count + // address: 92, size: 4 pixel format R bit mask + // address: 96, size: 4 pixel format G bit mask + // address: 100, size: 4 pixel format B bit mask + // address: 104, size: 4 pixel format A bit mask + // address: 108, size: 4 caps 1 + // address: 112, size: 4 caps 2 + // address: 116, size: 4 caps 3 + // address: 120, size: 4 caps 4 + // address: 124, size: 4 reserved 2 + // -- DXT10 extension + // address: 130, size: 4 DXGI Format + // address: 134, size: 4 resource dimension + // address: 138, size: 4 misc flag + // address: 142, size: 4 array size + // address: 146, size: 4 misc flag 2 + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ddsHeader = null; + + if (byteArray[0] === 0x44 && + byteArray[1] === 0x44 && + byteArray[2] === 0x53 && + byteArray[3] === 0x20) { + ddsHeader = { + complete: true, + fileFormat: 'DDS', + compressionAlgorithm: 'S3TC', + size: uintArray[1], + flags: uintArray[2], + height: uintArray[3], + width: uintArray[4], + pitch: uintArray[5], + depth: uintArray[6], + mipmapCount: uintArray[7], + formatSize: uintArray[19], + formatFlag: uintArray[19], + formatFourCC: [ + String.fromCharCode(byteArray[84]), + String.fromCharCode(byteArray[85]), + String.fromCharCode(byteArray[86]), + String.fromCharCode(byteArray[87]) + ].join(''), + formatBitCount: uintArray[21], + formatRBitMask: uintArray[22], + formatGBitMask: uintArray[23], + formatBBitMask: uintArray[24], + formatABitMask: uintArray[25], + caps1: uintArray[26], + caps2: uintArray[27], + caps3: uintArray[28], + caps4: uintArray[29], + reserved2: uintArray[30], + DXGIFormat: null, + resourceDimension: null, + miscFlag: null, + arraySize: null, + textureData: byteArray.subarray(uintArray[1] + 4, byteArray.byteLength) + }; + if (ddsHeader.formatFourCC === 'DX10') { + ddsHeader.DXGIFormat = uintArray[31]; + ddsHeader.resourceDimension = uintArray[32]; + ddsHeader.miscFlag = uintArray[33]; + ddsHeader.arraySize = uintArray[34]; + ddsHeader.miscFlag = uintArray[35]; + } + } + + return ddsHeader; + + }, + + /** + * Extract KTX header from loaded binary + * + * @method Phaser.LoaderParser.ktx + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed KTX file including texture data. + */ + ktx: function (arrayBuffer) { + + // Reference: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + // KTX header structure + // --------------------------------------- + // address: 0, size 12 bytes: Identifier '«KTX 11»\r\n\x1A\n' + // address: 12, size 4 bytes: endianness + // address: 16, size 4 bytes: GL type + // address: 20, size 4 bytes: GL type size + // address: 24, size 4 bytes: GL format + // address: 28, size 4 bytes: GL internal format + // address: 32, size 4 bytes: GL base internal format + // address: 36, size 4 bytes: pixel width + // address: 40, size 4 bytes: pixel height + // address: 44, size 4 bytes: pixel depth + // address: 48, size 4 bytes: number of array elements + // address: 52, size 4 bytes: number of faces + // address: 56, size 4 bytes: number of mipmap levels + // address: 60, size 4 bytes: bytes of key value data + // address: 64, size 4 bytes: key and value bytes size + // address: X, size 1 byte : key and value + // address: X, size 1 byte : value padding + // address: X, size 4 byte : image size + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ktxHeader = null, + imageSizeOffset = 16 + (uintArray[15] / 4) | 0, + imageSize = uintArray[imageSizeOffset], + glInternalFormat = uintArray[7], + compressionAlgorithm = 0; + + if (byteArray[0] === 0xAB && byteArray[1] === 0x4B && + byteArray[2] === 0x54 && byteArray[3] === 0x58 && + byteArray[4] === 0x20 && byteArray[5] === 0x31 && + byteArray[6] === 0x31 && byteArray[7] === 0xBB && + byteArray[8] === 0x0D && byteArray[9] === 0x0A && + byteArray[10] === 0x1A && byteArray[11] === 0x0A && + //Check if internal GL format is supported by WebGL + [ + // ETC1 + 0x8D64, + // PVRTC + 0x8C00, 0x8C01, 0x8C02, 0x8C03, + // DXTC | S3TC + 0x83F0, 0x83F1, 0x83F2, 0x83F3 + ].indexOf(glInternalFormat) >= 0) { + switch (glInternalFormat) { + case 0x8D64: + compressionAlgorithm = 'ETC1'; + break; + case 0x8C00: + case 0x8C01: + case 0x8C02: + case 0x8C03: + compressionAlgorithm = 'PVRTC'; + break; + case 0x83F0: + case 0x83F1: + case 0x83F2: + case 0x83F3: + compressionAlgorithm = 'S3TC'; + break; + } + + ktxHeader = { + complete: true, + fileFormat: 'KTX', + compressionAlgorithm: compressionAlgorithm, + endianness: uintArray[3], + glType: uintArray[4], + glTypeSize: uintArray[5], + glFormat: uintArray[6], + glInternalFormat: uintArray[7], + glBaseInternalFormat: uintArray[8], + width: uintArray[9], + height: uintArray[10], + pixelDepth: uintArray[11], + numberOfArrayElements: uintArray[12], + numberOfFaces: uintArray[13], + numberOfMipmapLevels: uintArray[14], + bytesOfKeyValueData: uintArray[15], + keyAndValueByteSize: uintArray[16], + imageSize: imageSize, + textureData: byteArray.subarray((imageSizeOffset + 1) * 4, imageSize + 100) + }; + } + + return ktxHeader; + + }, + + /** + * Extract PKM header from loaded binary + * + * @method Phaser.LoaderParser.pkm + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PKM file including texture data. + */ + pkm: function (arrayBuffer) { + + // PKM header structure + // --------------------------------------- + // address: 0, size 4 bytes: for 'PKM ' + // address: 4, size 2 bytes: for version + // address: 6, size 2 bytes: for type + // address: 8, size 2 bytes: for extended width + // address: 10, size 2 bytes: for extended height + // address: 12, size 2 bytes: for original width + // address: 14, size 2 bytes: for original height + // address: 16, texture data + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + pkmHeader = null; + + if (byteArray[0] === 0x50 && + byteArray[1] === 0x4B && + byteArray[2] === 0x4D && + byteArray[3] === 0x20) { + + pkmHeader = { + complete: true, + fileFormat: 'PKM', + compressionAlgorithm: 'ETC1', + format: ((byteArray[6] << 8 | byteArray[7])) & 0xFFFF, + width: ((byteArray[8] << 8 | byteArray[9])) & 0xFFFF, + height: ((byteArray[10] << 8 | byteArray[11])) & 0xFFFF, + originalWidth: ((byteArray[12] << 8 | byteArray[13])) & 0xFFFF, + originalHeight: ((byteArray[14] << 8 | byteArray[15])) & 0xFFFF, + textureData: byteArray.subarray(16, byteArray.length) + }; + } + + return pkmHeader; + + } + +}; + +/** + * @author Jeremy Dowell + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * Audio Sprites are a combination of audio files and a JSON configuration. + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * @class Phaser.AudioSprite + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + * @param {string} key - Asset key for the sound. + */ +Phaser.AudioSprite = function (game, key) { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * Asset key for the Audio Sprite. + * @property {string} key + */ + this.key = key; + + /** + * JSON audio atlas object. + * @property {object} config + */ + this.config = this.game.cache.getJSON(key + '-audioatlas'); + + /** + * If a sound is set to auto play, this holds the marker key of it. + * @property {string} autoplayKey + */ + this.autoplayKey = null; + + /** + * Is a sound set to autoplay or not? + * @property {boolean} autoplay + * @default + */ + this.autoplay = false; + + /** + * An object containing the Phaser.Sound objects for the Audio Sprite. + * @property {object} sounds + */ + this.sounds = {}; + + for (var k in this.config.spritemap) + { + var marker = this.config.spritemap[k]; + var sound = this.game.add.sound(this.key); + + sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop); + + this.sounds[k] = sound; + } + + if (this.config.autoplay) + { + this.autoplayKey = this.config.autoplay; + this.play(this.autoplayKey); + this.autoplay = this.sounds[this.autoplayKey]; + } + +}; + +Phaser.AudioSprite.prototype = { + + /** + * Play a sound with the given name. + * + * @method Phaser.AudioSprite#play + * @param {string} [marker] - The name of sound to play + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, volume) { + + if (volume === undefined) { volume = 1; } + + return this.sounds[marker].play(marker, null, volume); + + }, + + /** + * Stop a sound with the given name. + * + * @method Phaser.AudioSprite#stop + * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite. + */ + stop: function (marker) { + + if (!marker) + { + for (var key in this.sounds) + { + this.sounds[key].stop(); + } + } + else + { + this.sounds[marker].stop(); + } + + }, + + /** + * Get a sound with the given name. + * + * @method Phaser.AudioSprite#get + * @param {string} marker - The name of sound to get. + * @return {Phaser.Sound} The sound instance. + */ + get: function(marker) { + + return this.sounds[marker]; + + } + +}; + +Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound class constructor. +* +* @class Phaser.Sound +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {string} key - Asset key for the sound. +* @param {number} [volume=1] - Default value for the volume, between 0 and 1. +* @param {boolean} [loop=false] - Whether or not the sound will loop. +*/ +Phaser.Sound = function (game, key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = game.sound.connectToMaster; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * @property {string} name - Name of the sound. + */ + this.name = key; + + /** + * @property {string} key - Asset key for the sound. + */ + this.key = key; + + /** + * @property {boolean} loop - Whether or not the sound or current sound marker will loop. + */ + this.loop = loop; + + /** + * @property {object} markers - The sound markers. + */ + this.markers = {}; + + /** + * @property {AudioContext} context - Reference to the AudioContext instance. + */ + this.context = null; + + /** + * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically. + */ + this.autoplay = false; + + /** + * @property {number} totalDuration - The total duration of the sound in seconds. + */ + this.totalDuration = 0; + + /** + * @property {number} startTime - The time the sound starts at in ms (typically 0 unless starting from a marker). + * @default + */ + this.startTime = 0; + + /** + * @property {number} currentTime - The current time of sound playback in ms. + */ + this.currentTime = 0; + + /** + * @property {number} duration - The duration of the current sound marker in seconds. + */ + this.duration = 0; + + /** + * @property {number} durationMS - The duration of the current sound marker in ms. + */ + this.durationMS = 0; + + /** + * @property {number} position - The position of the current sound marker in ms. + */ + this.position = 0; + + /** + * @property {number} stopTime - The time the sound stopped in ms. + */ + this.stopTime = 0; + + /** + * @property {boolean} paused - true if the sound is paused, otherwise false. + * @default + */ + this.paused = false; + + /** + * @property {number} pausedPosition - The position the sound had reached when it was paused in ms. + */ + this.pausedPosition = 0; + + /** + * @property {number} pausedTime - The game time (ms) at which the sound was paused. + */ + this.pausedTime = 0; + + /** + * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false. + * @default + */ + this.isPlaying = false; + + /** + * @property {string} currentMarker - The string ID of the currently playing marker, if any. + * @default + */ + this.currentMarker = ''; + + /** + * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. + */ + this.fadeTween = null; + + /** + * @property {boolean} pendingPlayback - true if the sound file is pending playback + * @readonly + */ + this.pendingPlayback = false; + + /** + * @property {boolean} override - if true when you play this sound it will always start from the beginning. + * @default + */ + this.override = false; + + /** + * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. + * @default + */ + this.allowMultiple = false; + + /** + * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio. + * @readonly + */ + this.usingWebAudio = this.game.sound.usingWebAudio; + + /** + * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag. + */ + this.usingAudioTag = this.game.sound.usingAudioTag; + + /** + * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. + */ + this.externalNode = null; + + /** + * @property {object} masterGainNode - The master gain node in a Web Audio system. + */ + this.masterGainNode = null; + + /** + * @property {object} gainNode - The gain node in a Web Audio system. + */ + this.gainNode = null; + + /** + * @property {object} _sound - Internal var. + * @private + */ + this._sound = null; + + /** + * @property {object} _globalVolume - Internal var for keeping track of global volume when using AudioTag + * @private + */ + this._globalVolume = 1; + + /** + * @property {boolean} _markedToDelete - When audio stops, disconnect Web Audio nodes. + * @private + */ + this._markedToDelete = false; + + /** + * @property {boolean} _removeFromSoundManager - When audio stops, remove it from the Sound Manager and destroy it. + * @private + */ + this._removeFromSoundManager = false; + + + + if (this.usingWebAudio) + { + this.context = this.game.sound.context; + this.masterGainNode = this.game.sound.masterGain; + + if (this.context.createGain === undefined) + { + this.gainNode = this.context.createGainNode(); + } + else + { + this.gainNode = this.context.createGain(); + } + + this.gainNode.gain.value = volume; + + if (connect) + { + this.gainNode.connect(this.masterGainNode); + } + } + else if (this.usingAudioTag) + { + if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key)) + { + this._sound = this.game.cache.getSoundData(key); + this.totalDuration = 0; + + if (this._sound.duration) + { + this.totalDuration = this._sound.duration; + } + } + else + { + this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this); + } + } + + /** + * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files). It passes one argument, this sound. + */ + this.onDecoded = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played or a looping marker is restarted. It passes one argument, this sound. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. It passes one argument, this sound. + */ + this.onPause = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. It passes one argument, this sound. + */ + this.onResume = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. It passes one argument, this sound. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback or when a non-looping marker completes. It passes two arguments: this sound and any {@link #currentMarker marker} that was playing. + */ + this.onStop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted. It passes one argument, this sound. + */ + this.onMute = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. It passes two arguments: the {@link #currentMarker} and this sound. + */ + this.onMarkerComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out. It passes two arguments: this sound and its current {@link #volume}. + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + */ + this._volume = volume; + + /** + * @property {any} _buffer - Decoded data buffer / Audio tag. + * @private + */ + this._buffer = null; + + /** + * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. + * @private + */ + this._muted = false; + + /** + * @property {number} _tempMarker - Internal marker var. + * @private + */ + this._tempMarker = 0; + + /** + * @property {number} _tempPosition - Internal marker var. + * @private + */ + this._tempPosition = 0; + + /** + * @property {number} _tempVolume - Internal marker var. + * @private + */ + this._tempVolume = 0; + + /** + * @property {number} _tempPause - Internal marker var. + * @private + */ + this._tempPause = 0; + + /** + * @property {number} _muteVolume - Internal cache var. + * @private + */ + this._muteVolume = 0; + + /** + * @property {boolean} _tempLoop - Internal cache var. + * @private + */ + this._tempLoop = 0; + + /** + * @property {boolean} _paused - Was this sound paused via code or a game event? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched? + * @private + */ + this._onDecodedEventDispatched = false; + +}; + +Phaser.Sound.prototype = { + + /** + * Called automatically when this sound is unlocked. + * @method Phaser.Sound#soundHasUnlocked + * @param {string} key - The Phaser.Cache key of the sound file to check for decoding. + * @protected + */ + soundHasUnlocked: function (key) { + + if (key === this.key) + { + this._sound = this.game.cache.getSoundData(this.key); + this.totalDuration = this._sound.duration; + } + + }, + + /** + * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound#addMarker + * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. + * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). + * @param {boolean} [loop=false] - Sets if the sound will loop or not. + */ + addMarker: function (name, start, duration, volume, loop) { + + if (duration === undefined || duration === null) { duration = 1; } + if (volume === undefined || volume === null) { volume = 1; } + if (loop === undefined) { loop = false; } + + this.markers[name] = { + name: name, + start: start, + stop: start + duration, + volume: volume, + duration: duration, + durationMS: duration * 1000, + loop: loop + }; + + }, + + /** + * Removes a marker from the sound. + * @method Phaser.Sound#removeMarker + * @param {string} name - The key of the marker to remove. + */ + removeMarker: function (name) { + + delete this.markers[name]; + + }, + + /** + * Called automatically by the AudioContext when the sound stops playing. + * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. + * + * @method Phaser.Sound#onEndedHandler + * @protected + */ + onEndedHandler: function () { + + this._sound.onended = null; + this.isPlaying = false; + this.currentTime = this.durationMS; + this.stop(); + + if (this._markedToDelete) + { + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + if (this._removeFromSoundManager) + { + this.game.sound.remove(this); + } + else + { + 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(); + } + } + }, + + /** + * Called automatically by Phaser.SoundManager. + * @method Phaser.Sound#update + * @protected + */ + update: function () { + + if (!this.game.cache.checkSoundKey(this.key)) + { + this.destroy(); + return; + } + + if (this.isDecoded && !this._onDecodedEventDispatched) + { + this.onDecoded.dispatch(this); + this._onDecodedEventDispatched = true; + } + + if (this.pendingPlayback && this.game.cache.isSoundReady(this.key)) + { + this.pendingPlayback = false; + this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop); + } + + if (this.isPlaying) + { + this.currentTime = this.game.time.time - this.startTime; + + if (this.currentTime >= this.durationMS) + { + if (this.usingWebAudio) + { + if (this.loop) + { + // won't work with markers, needs to reset the position + this.onLoop.dispatch(this); + + // Gets reset by the play function + this.isPlaying = false; + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + this.isPlaying = true; // play not called again in this case + } + else + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + this.play(this.currentMarker, 0, this.volume, true, true); + } + } + else + { + // Stop if we're using an audio marker, otherwise we let onended handle it + if (this.currentMarker !== '') + { + this.stop(); + } + } + } + else + { + if (this.loop) + { + this.onLoop.dispatch(this); + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + } + + // Gets reset by the play function + this.isPlaying = false; + + this.play(this.currentMarker, 0, this.volume, true, true); + } + else + { + this.stop(); + } + } + } + } + }, + + /** + * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters. + * + * @method Phaser.Sound#loopFull + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + loopFull: function (volume) { + + return this.play(null, 0, volume, true); + + }, + + /** + * Play this sound, or a marked section of it. + * + * @method Phaser.Sound#play + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. + * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, position, volume, loop, forceRestart) { + + if (marker === undefined || marker === false || marker === null) { marker = ''; } + if (forceRestart === undefined) { forceRestart = true; } + + if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override) + { + // Use Restart instead + return this; + } + + if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart)) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) { + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + + this.isPlaying = false; + } + + if (marker === '' && Object.keys(this.markers).length > 0) + { + // If they didn't specify a marker but this is an audio sprite, + // we should never play the entire thing + return this; + } + + if (marker !== '') + { + if (this.markers[marker]) + { + this.currentMarker = marker; + + // Playing a marker? Then we default to the marker values + 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 (volume === undefined) { volume = this._volume; } + if (loop === undefined) { loop = this.loop; } + + this.position = Math.max(0, 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) + { + // Does the sound need decoding? + if (this.game.cache.isSoundDecoded(this.key)) + { + this._sound = this.context.createBufferSource(); + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + this._buffer = this.game.cache.getSoundData(this.key); + this._sound.buffer = this._buffer; + + if (this.loop && marker === '') + { + this._sound.loop = true; + } + + if (!this.loop && marker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + this.totalDuration = this._sound.buffer.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = Math.ceil(this.totalDuration * 1000); + } + + // Useful to cache this somewhere perhaps? + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, this.position, this.duration); + } + else + { + if (this.loop && marker === '') + { + this._sound.start(0, 0); + } + else + { + this._sound.start(0, this.position, this.duration); + } + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + 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 doesn't become available until you call play(), wonderful ... + this.totalDuration = this._sound.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = this.totalDuration * 1000; + } + + this._sound.currentTime = this.position; + this._sound.muted = this._muted; + + if (this._muted || this.game.sound.mute) + { + this._sound.volume = 0; + } + else + { + this._sound.volume = this._volume; + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + this.currentTime = 0; + this.stopTime = this.startTime + this.durationMS; + + this.onPlay.dispatch(this); + } + else + { + this.pendingPlayback = true; + } + } + } + + return this; + + }, + + /** + * Restart the sound, or a marked section of it. + * + * @method Phaser.Sound#restart + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. + * @param {boolean} [loop=false] - Loop when it finished playing? + */ + restart: function (marker, position, volume, loop) { + + marker = marker || ''; + position = position || 0; + volume = volume || 1; + if (loop === undefined) { loop = false; } + + this.play(marker, position, volume, loop, true); + + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound#pause + */ + pause: function () { + + if (this.isPlaying && this._sound) + { + this.paused = true; + this.pausedPosition = this.currentTime; + this.pausedTime = this.game.time.time; + this._tempPause = this._sound.currentTime; + this.onPause.dispatch(this); + this.stop(); + } + + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound#resume + */ + resume: function () { + + if (this.paused && this._sound) + { + if (this.usingWebAudio) + { + var p = Math.max(0, this.position + (this.pausedPosition / 1000)); + + this._sound = this.context.createBufferSource(); + this._sound.buffer = this._buffer; + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + if (this.loop) + { + this._sound.loop = true; + } + + if (!this.loop && this.currentMarker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + var duration = this.duration - (this.pausedPosition / 1000); + + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, p, duration); + //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it + } + else + { + if (this.loop && this.game.device.chrome) + { + // Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099 + if (this.game.device.chromeVersion === 42) + { + this._sound.start(0); + } + else + { + this._sound.start(0, p); + } + } + else + { + this._sound.start(0, p, duration); + } + } + } + else + { + this._sound.currentTime = this._tempPause; + this._sound.play(); + } + + this.isPlaying = true; + this.paused = false; + this.startTime += (this.game.time.time - this.pausedTime); + this.onResume.dispatch(this); + } + + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound#stop + */ + stop: function () { + + if (this.isPlaying && this._sound) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) + { + // Thanks Android 4.4 + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + } + + this.pendingPlayback = false; + this.isPlaying = false; + + if (!this.paused) + { + var prevMarker = this.currentMarker; + + if (this.currentMarker !== '') + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + } + + this.currentMarker = ''; + + if (this.fadeTween !== null) + { + this.fadeTween.stop(); + } + + this.onStop.dispatch(this, prevMarker); + } + + }, + + /** + * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. + * Then increases the volume from 0 to 1 over the duration specified. + * + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (1) as the second parameter. + * + * @method Phaser.Sound#fadeIn + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in. + * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. + * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. + */ + fadeIn: function (duration, loop, marker) { + + if (loop === undefined) { loop = false; } + if (marker === undefined) { marker = this.currentMarker; } + + if (this.paused) + { + return; + } + + this.play(marker, 0, 0, loop); + + this.fadeTo(duration, 1); + + }, + + /** + * Decreases the volume of this Sound from its current value to 0 over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (0) as the second parameter. + * + * @method Phaser.Sound#fadeOut + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out. + */ + fadeOut: function (duration) { + + this.fadeTo(duration, 0); + + }, + + /** + * Fades the volume of this Sound from its current value to the given volume over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (volume) as the second parameter. + * + * @method Phaser.Sound#fadeTo + * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out. + * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1. + */ + fadeTo: function (duration, volume) { + + if (!this.isPlaying || this.paused || volume === this.volume) + { + return; + } + + if (duration === undefined) { duration = 1000; } + + if (volume === undefined) + { + console.warn("Phaser.Sound.fadeTo: No Volume Specified."); + return; + } + + this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true); + + this.fadeTween.onComplete.add(this.fadeComplete, this); + + }, + + /** + * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo. + * + * @method Phaser.Sound#fadeComplete + * @private + */ + fadeComplete: function () { + + this.onFadeComplete.dispatch(this, this.volume); + + if (this.volume === 0) + { + this.stop(); + } + + }, + + /** + * Called automatically by SoundManager.volume. + * + * Sets the volume of AudioTag Sounds as a percentage of the Global Volume. + * + * You should not normally call this directly. + * + * @method Phaser.Sound#updateGlobalVolume + * @protected + * @param {float} globalVolume - The global SoundManager volume. + */ + updateGlobalVolume: function (globalVolume) { + + // this._volume is the % of the global volume this sound should be played at + + if (this.usingAudioTag && this._sound) + { + this._globalVolume = globalVolume; + this._sound.volume = this._globalVolume * this._volume; + } + + }, + + /** + * Destroys this sound and all associated events and removes it from the SoundManager. + * + * @method Phaser.Sound#destroy + * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager. + */ + destroy: function (remove) { + + if (remove === undefined) { remove = true; } + + this._markedToDelete = true; + this._removeFromSoundManager = remove; + this.stop(); + + if (remove) + { + this.game.sound.remove(this); + } + else + { + 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; + +/** +* @name Phaser.Sound#isDecoding +* @property {boolean} isDecoding - Returns true if the sound file is still decoding. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoding", { + + get: function () { + return this.game.cache.getSound(this.key).isDecoding; + } + +}); + +/** +* @name Phaser.Sound#isDecoded +* @property {boolean} isDecoded - Returns true if the sound file has decoded. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoded", { + + get: function () { + return this.game.cache.isSoundDecoded(this.key); + } + +}); + +/** +* @name Phaser.Sound#mute +* @property {boolean} mute - Gets or sets the muted state of this sound. +*/ +Object.defineProperty(Phaser.Sound.prototype, "mute", { + + get: function () { + + return (this._muted || this.game.sound.mute); + + }, + + set: function (value) { + + value = value || false; + + if (value === this._muted) + { + return; + } + + if (value) + { + this._muted = true; + this._muteVolume = this._tempVolume; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = 0; + } + else if (this.usingAudioTag && this._sound) + { + 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); + + } + +}); + +/** +* @name Phaser.Sound#volume +* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Sound.prototype, "volume", { + + get: function () { + return this._volume; + }, + + set: function (value) { + + // Causes an Index size error if you don't clamp the value + if (this.usingAudioTag) + { + value = this.game.math.clamp(value, 0, 1); + } + + if (this._muted) + { + this._muteVolume = value; + return; + } + + this._tempVolume = value; + this._volume = value; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = value; + } + else if (this.usingAudioTag && this._sound) + { + this._sound.volume = this._globalVolume * value; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. +* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. +* The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. +* There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ +* +* If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out +* of AudioContext nodes. If this is the case create a global var called {@link PhaserGlobal} on the window object before creating the game. The active +* AudioContext will then be saved to `window.PhaserGlobal.audioContext` when the Phaser game is destroyed, and re-used when it starts again. +* +* Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. +* When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. +* The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will +* be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. +* +* @class Phaser.SoundManager +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.SoundManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) + */ + this.onSoundDecode = new Phaser.Signal(); + + /** + * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. + * @property {Phaser.Signal} onVolumeChange + */ + this.onVolumeChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. + * @property {Phaser.Signal} onMute + */ + this.onMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. + * @property {Phaser.Signal} onUnMute + */ + this.onUnMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is touch-unlocked. + * If the device doesn't {@link Phaser.Device.needsTouchUnlock need touch-unlocking}, the signal won't be dispatched. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * @property {AudioContext} context - The AudioContext being used for playback. + * @default + */ + this.context = null; + + /** + * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio. + * @readonly + */ + this.usingWebAudio = false; + + /** + * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio. + * @readonly + */ + this.usingAudioTag = false; + + /** + * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. + * @default + */ + this.noAudio = false; + + /** + * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. + * @default + */ + this.connectToMaster = true; + + /** + * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. + * @default + */ + this.touchLocked = false; + + /** + * @property {number} channels - The number of audio channels to use in playback. + * @default + */ + this.channels = 32; + + /** + * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), + * or set to false to keep audio playing, regardless of the game pause state. You may need to + * do this should you wish to control audio muting via external DOM buttons or similar. + * @property {boolean} muteOnPause + * @default + */ + this.muteOnPause = true; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {AudioContext} _unlockSource - Internal unlock tracking var. + * @private + * @default + */ + this._unlockSource = null; + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + * @default + */ + this._volume = 1; + + + /** + * @property {array} _sounds - An array containing all the sounds + * @private + */ + this._sounds = []; + + /** + * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status. + * @private + */ + this._watchList = new Phaser.ArraySet(); + + /** + * @property {boolean} _watching - Is the SoundManager monitoring the watchList? + * @private + */ + this._watching = false; + + /** + * @property {function} _watchCallback - The callback to invoke once the watchlist is clear. + * @private + */ + this._watchCallback = null; + + /** + * @property {object} _watchContext - The context in which to call the watchlist callback. + * @private + */ + this._watchContext = null; + +}; + +Phaser.SoundManager.prototype = { + + /** + * Initialises the sound manager. + * @method Phaser.SoundManager#boot + * @protected + */ + boot: function () { + + var device = this.game.device; + var PhaserGlobal = window.PhaserGlobal; + + if (device.iOS && device.webAudio === false) + { + this.channels = 1; + } + + // PhaserGlobal overrides + if (PhaserGlobal) + { + // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class) + if (PhaserGlobal.disableAudio === true) + { + this.noAudio = true; + this.touchLocked = false; + return; + } + + // Check if the Web Audio API is disabled (for testing Audio Tag playback during development) + if (PhaserGlobal.disableWebAudio === true) + { + this.usingAudioTag = true; + this.touchLocked = false; + return; + } + } + + if (PhaserGlobal && PhaserGlobal.audioContext) + { + this.context = PhaserGlobal.audioContext; + } + else + { + if (!!window['AudioContext']) + { + try { + this.context = new window['AudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + else if (!!window['webkitAudioContext']) + { + try { + this.context = new window['webkitAudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + } + + if (this.context === null) + { + // No Web Audio support - how about legacy Audio? + if (window['Audio'] === undefined) + { + this.noAudio = true; + return; + } + else + { + this.usingAudioTag = true; + } + } + else + { + this.usingWebAudio = true; + + if (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); + } + + if (!this.noAudio) + { + // On mobile we need a native touch event before we can play anything, so capture it here + if (device.needsTouchUnlock()) + { + this.setTouchLock(); + } + } + + if (this.usingWebAudio && device.chrome && device.chromeVersion <= 65) + { + console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. '); + } + + }, + + /** + * Sets the Input Manager touch callback to be SoundManager.unlock. + * Required for iOS audio device unlocking. Mostly just used internally. + * + * @method Phaser.SoundManager#setTouchLock + */ + setTouchLock: function () { + + if (this.noAudio || (window.PhaserGlobal && window.PhaserGlobal.disableAudio === true)) + { + return; + } + + this.game.input.addTouchLockCallback(this.unlock, this, true); + + this.touchLocked = true; + + }, + + /** + * Turns off {@link #touchLocked} and dispatches {@link #onTouchUnlock}. + * + * @method Phaser.SoundManager#setTouchUnlock + * @private + */ + setTouchUnlock: function () { + + this.touchLocked = false; + this._unlockSource = null; + this.onTouchUnlock.dispatch(); + + }, + + /** + * Enables the audio, usually after the first touch. + * + * @method Phaser.SoundManager#unlock + * @return {boolean} True if the callback should be removed, otherwise false. + */ + unlock: function () { + + if (this.noAudio || !this.touchLocked || this._unlockSource !== null) + { + return true; + } + + // Global override (mostly for Audio Tag testing) + if (this.usingAudioTag) + { + this.setTouchUnlock(); + } + else if (this.usingWebAudio) + { + // Create empty buffer and play it + // The SoundManager.update loop captures the state of it and then resets touchLocked to false + + var buffer = this.context.createBuffer(1, 1, 22050); + this._unlockSource = this.context.createBufferSource(); + this._unlockSource.buffer = buffer; + this._unlockSource.connect(this.context.destination); + + if (this._unlockSource.start === undefined) + { + this._unlockSource.noteOn(0); + } + else + { + this._unlockSource.start(0); + } + + //This fixes locked audio in Chrome > 55 cross origin iframes + if (this._unlockSource.context.state === 'suspended') { + this._unlockSource.context.resume(); + } + } + + // We can remove the event because we've done what we needed (started the unlock sound playing) + return true; + + }, + + /** + * Stops all the sounds in the game. + * + * @method Phaser.SoundManager#stopAll + */ + stopAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].stop(); + } + } + + }, + + /** + * Pauses all the sounds in the game. + * + * @method Phaser.SoundManager#pauseAll + */ + pauseAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].pause(); + } + } + + }, + + /** + * Resumes every sound in the game. + * + * @method Phaser.SoundManager#resumeAll + */ + resumeAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].resume(); + } + } + + }, + + /** + * Decode a sound by its asset key. + * + * @method Phaser.SoundManager#decode + * @param {string} key - Assets key of the sound to be decoded. + * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. + */ + decode: function (key, sound) { + + sound = sound || null; + + var soundData = this.game.cache.getSoundData(key); + + if (soundData) + { + if (this.game.cache.isSoundDecoded(key) === false) + { + this.game.cache.updateSound(key, 'isDecoding', true); + + var _this = this; + + try { + this.context.decodeAudioData(soundData, function (buffer) { + + if (buffer) + { + _this.game.cache.decodedSound(key, buffer); + _this.onSoundDecode.dispatch(key, sound); + } + }); + } + catch (e) {} + } + } + + }, + + /** + * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback. + * Once all of the Sound files have finished decoding the callback will be invoked. + * The amount of time spent decoding depends on the codec used and file size. + * If all of the files given have already decoded the callback is triggered immediately. + * + * @method Phaser.SoundManager#setDecodedCallback + * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache. + * @param {Function} callback - The callback which will be invoked once all files have finished decoding. + * @param {Object} callbackContext - The context in which the callback will run. + */ + setDecodedCallback: function (files, callback, callbackContext) { + + if (typeof files === 'string') + { + files = [ files ]; + } + + this._watchList.reset(); + + for (var i = 0; i < files.length; i++) + { + if (files[i] instanceof Phaser.Sound) + { + if (!this.game.cache.isSoundDecoded(files[i].key)) + { + this._watchList.add(files[i].key); + } + } + else if (!this.game.cache.isSoundDecoded(files[i])) + { + this._watchList.add(files[i]); + } + } + + // All decoded already? + if (this._watchList.total === 0) + { + this._watching = false; + callback.call(callbackContext); + } + else + { + this._watching = true; + this._watchCallback = callback; + this._watchContext = callbackContext; + } + + }, + + /** + * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. + * + * @method Phaser.SoundManager#update + * @protected + */ + update: function () { + + if (this.noAudio) + { + return; + } + + if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE)) + { + this.setTouchUnlock(); + } + + for (var i = 0; i < this._sounds.length; i++) + { + this._sounds[i].update(); + } + + if (this._watching) + { + var key = this._watchList.first; + + while (key) + { + if (this.game.cache.isSoundDecoded(key)) + { + this._watchList.remove(key); + } + + key = this._watchList.next; + } + + if (this._watchList.total === 0) + { + this._watching = false; + this._watchCallback.call(this._watchContext); + } + } + + }, + + /** + * Adds a new Sound into the SoundManager. + * + * @method Phaser.SoundManager#add + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The new sound instance. + */ + add: function (key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = this.connectToMaster; } + + var sound = new Phaser.Sound(this.game, key, volume, loop, connect); + + this._sounds.push(sound); + + return sound; + + }, + + /** + * Adds a new AudioSprite into the SoundManager. + * + * @method Phaser.SoundManager#addSprite + * @param {string} key - Asset key for the sound. + * @return {Phaser.AudioSprite} The new AudioSprite instance. + */ + addSprite: function(key) { + + var audioSprite = new Phaser.AudioSprite(this.game, key); + + return audioSprite; + + }, + + /** + * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. + * + * @method Phaser.SoundManager#remove + * @param {Phaser.Sound} sound - The sound object to remove. + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ + remove: function (sound) { + + var i = this._sounds.length; + + while (i--) + { + if (this._sounds[i] === sound) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Removes all Sounds from the SoundManager. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeAll + */ + removeAll: function () { + + this.stopAll(); + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].destroy(); + } + } + + this._sounds.length = 0; + + }, + + /** + * Removes all Sounds from the SoundManager that have an asset key matching the given value. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeByKey + * @param {string} key - The key to match when removing sound objects. + * @return {number} The number of matching sound objects that were removed. + */ + removeByKey: function (key) { + + var i = this._sounds.length; + var removed = 0; + + while (i--) + { + if (this._sounds[i].key === key) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + removed++; + } + } + + return removed; + + }, + + /** + * Adds a new Sound into the SoundManager and starts it playing. + * + * @method Phaser.SoundManager#play + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @return {Phaser.Sound} The new sound instance. + */ + play: function (key, volume, loop) { + + if (this.noAudio) + { + return; + } + + var sound = this.add(key, volume, loop); + + sound.play(); + + return sound; + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + if (this.usingWebAudio) + { + this._muteVolume = this.masterGain.gain.value; + this.masterGain.gain.value = 0; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = true; + } + } + + this.onMute.dispatch(); + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = this._muteVolume; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = false; + } + } + + this.onUnMute.dispatch(); + + }, + + /** + * Stops all the sounds in the game, then destroys them and finally clears up any callbacks. + * + * @method Phaser.SoundManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.onSoundDecode.dispose(); + + if (this.context) + { + if (window.PhaserGlobal) + { + // Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing + window.PhaserGlobal.audioContext = this.context; + } + else + { + if (this.context.close) + { + this.context.close(); + } + } + } + + } + +}; + +Phaser.SoundManager.prototype.constructor = Phaser.SoundManager; + +/** +* @name Phaser.SoundManager#mute +* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || false; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* @name Phaser.SoundManager#volume +* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "volume", { + + get: function () { + + return this._volume; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this._volume !== value) + { + this._volume = value; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = value; + } + else + { + // Loop through the sound cache and change the volume of all html audio tags + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].updateGlobalVolume(value); + } + } + } + + this.onVolumeChange.dispatch(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* The ScaleManager object handles the the scaling, resizing, and alignment of the +* Game size and the game Display canvas. +* +* The Game size is the logical size of the game; the Display canvas has size as an HTML element. +* +* The calculations of these are heavily influenced by the bounding Parent size which is the computed +* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the +* canvas's Parent element play an important role_ in the operation of the ScaleManager. +* +* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size. +* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}). +* +* #### Parent and Display canvas containment guidelines: +* +* - Style the Parent element (of the game canvas) to control the Parent size and +* thus the Display canvas's size and layout. +* +* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior. +* +* - The Parent element should _not_ apply a padding as this is not accounted for. +* If a padding is required apply it to the Parent's parent or apply a margin to the Parent. +* If you need to add a border, margin or any other CSS around your game container, then use a parent element and +* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container. +* +* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as +* they may be updated by the ScaleManager. +* +* #### Example Uses +* +* - ##### Fixed game size; scale canvas proportionally to fill its container +* +* Use `scaleMode` SHOW_ALL. +* +* - ##### Fixed game size; stretch canvas to fill its container (uncommon) +* +* Use `scaleMode` EXACT_FIT. +* +* - ##### Fixed game size; scale canvas proportionally by some other criteria +* +* Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary. +* +* - ##### Fluid game/canvas size +* +* Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary. +* +* - ##### Preferred orientation +* +* Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals. +* +* @description +* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game} +* +* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. +* +* @class +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number|string} width - The width of the game. See above. +* @param {number|string} height - The height of the game. See above. +*/ +Phaser.ScaleManager = function (game, width, height) { + + /** + * A reference to the currently running game. + * @property {Phaser.Game} game + * @protected + * @readonly + */ + this.game = game; + + /** + * Provides access to some cross-device DOM functions. + * @property {Phaser.DOM} dom + * @protected + * @readonly + */ + this.dom = Phaser.DOM; + + /** + * _EXPERIMENTAL:_ A responsive grid on which you can align game objects. + * @property {Phaser.FlexGrid} grid + * @public + */ + this.grid = null; + + /** + * Target width (in pixels) of the Display canvas. + * @property {number} width + * @readonly + */ + this.width = 0; + + /** + * Target height (in pixels) of the Display canvas. + * @property {number} height + * @readonly + */ + this.height = 0; + + /** + * Minimum width the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minWidth + * @readonly + * @protected + */ + this.minWidth = null; + + /** + * Maximum width the canvas should be scaled to (in pixels). + * If null it will scale to whatever width the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxWidth + * @readonly + * @protected + */ + this.maxWidth = null; + + /** + * Minimum height the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minHeight + * @readonly + * @protected + */ + this.minHeight = null; + + /** + * Maximum height the canvas should be scaled to (in pixels). + * If null it will scale to whatever height the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxHeight + * @readonly + * @protected + */ + this.maxHeight = null; + + /** + * The offset coordinates of the Display canvas from the top-left of the browser window. + * The is used internally by Phaser.Pointer (for Input) and possibly other types. + * @property {Phaser.Point} offset + * @readonly + * @protected + */ + this.offset = new Phaser.Point(); + + /** + * If true, the game should only run in a landscape orientation. + * Change with {@link #forceOrientation}. + * @property {boolean} forceLandscape + * @readonly + * @default + * @protected + */ + this.forceLandscape = false; + + /** + * If true, the game should only run in a portrait + * Change with {@link #forceOrientation}. + * @property {boolean} forcePortrait + * @readonly + * @default + * @protected + */ + this.forcePortrait = false; + + /** + * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation. + * + * This value is not updated immediately. + * + * @property {boolean} incorrectOrientation + * @readonly + * @protected + */ + this.incorrectOrientation = false; + + /** + * See {@link #pageAlignHorizontally}. + * @property {boolean} _pageAlignHorizontally + * @private + */ + this._pageAlignHorizontally = false; + + /** + * See {@link #pageAlignVertically}. + * @property {boolean} _pageAlignVertically + * @private + */ + this._pageAlignVertically = false; + + /** + * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes. + * + * The signal is supplied with the following arguments: + * - `scale` - the ScaleManager object + * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}. + * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. + * + * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. + * Thus the following tests can be done: + * + * // The orientation itself changed: + * scale.screenOrientation !== prevOrientation + * // The orientation just became incorrect: + * scale.incorrectOrientation && !wasIncorrect + * + * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation + * correctness changes even if the orientation itself does not change. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onOrientationChange + * @public + */ + this.onOrientationChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} enterIncorrectOrientation + * @public + */ + this.enterIncorrectOrientation = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} leaveIncorrectOrientation + * @public + */ + this.leaveIncorrectOrientation = new Phaser.Signal(); + + /** + * This boolean provides you with a way to determine if the browser is in Full Screen + * mode (via the Full Screen API), and Phaser was the one responsible for activating it. + * + * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the + * one that made the browser go full-screen, so this flag lets you determine that. + * + * @property {boolean} hasPhaserSetFullScreen + * @default + */ + this.hasPhaserSetFullScreen = false; + + /** + * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. + * The target element must have the correct CSS styling and contain the Display canvas. + * + * The elements style will be modified (ie. the width and height might be set to 100%) + * but it will not be added to, removed from, or repositioned within the DOM. + * An attempt is made to restore relevant style changes when fullscreen mode is left. + * + * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. + * + * @property {?DOMElement} fullScreenTarget + * @default + */ + this.fullScreenTarget = null; + + /** + * The fullscreen target, as created by {@link #createFullScreenTarget}. + * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends. + * @property {?DOMElement} _createdFullScreenTarget + * @private + */ + this._createdFullScreenTarget = null; + + /** + * This signal is dispatched when fullscreen mode is ready to be initialized but + * before the fullscreen request. + * + * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. + * + * The `targetElement` is the {@link #fullScreenTarget} element, + * if such is assigned, or a new element created by {@link #createFullScreenTarget}. + * + * Custom CSS styling or resets can be applied to `targetElement` as required. + * + * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}: + * - After initialization the Display canvas is moved onto the `targetElement` for + * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. + * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. + * + * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}. + * + * @property {Phaser.Signal} onFullScreenInit + * @public + */ + this.onFullScreenInit = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine + * if currently running in Fullscreen mode. + * + * @property {Phaser.Signal} onFullScreenChange + * @public + */ + this.onFullScreenChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser fails to enter fullscreen mode; + * or if the device does not support fullscreen mode and `startFullScreen` is invoked. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). + * + * @property {Phaser.Signal} onFullScreenError + * @public + */ + this.onFullScreenError = new Phaser.Signal(); + + /** + * The _last known_ orientation of the screen, as defined in the Window Screen Web API. + * See {@link Phaser.DOM.getScreenOrientation} for possible values. + * + * @property {string} screenOrientation + * @readonly + * @public + */ + this.screenOrientation = this.dom.getScreenOrientation(); + + /** + * The _current_ scale factor based on the game dimensions vs. the scaled dimensions. + * @property {Phaser.Point} scaleFactor + * @readonly + */ + this.scaleFactor = new Phaser.Point(1, 1); + + /** + * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions. + * @property {Phaser.Point} scaleFactorInversed + * @readonly + * @protected + */ + this.scaleFactorInversed = new Phaser.Point(1, 1); + + /** + * The Display canvas is aligned by adjusting the margins; the last margins are stored here. + * + * @property {Bounds-like} margin + * @readonly + * @protected + */ + this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0}; + + /** + * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. + * @property {Phaser.Rectangle} bounds + * @readonly + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The aspect ratio of the scaled Display canvas. + * @property {number} aspectRatio + * @readonly + */ + this.aspectRatio = 0; + + /** + * The aspect ratio of the original game dimensions. + * @property {number} sourceAspectRatio + * @readonly + */ + this.sourceAspectRatio = 0; + + /** + * The native browser events from Fullscreen API changes. + * @property {any} event + * @readonly + * @private + */ + this.event = null; + + /** + * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container. + * + * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. + * - If 'visual', the edge will be constrained to the Window / displayed screen area + * - If 'layout', the edge will be constrained to the CSS Layout bounds + * - An invalid value is treated as 'visual' + * + * @member + * @property {string} bottom + * @property {string} right + * @default + */ + this.windowConstraints = { + right: 'layout', + bottom: '' + }; + + /** + * Various compatibility settings. + * A value of "(auto)" indicates the setting is configured based on device and runtime information. + * + * A {@link #refresh} may need to be performed after making changes. + * + * @protected + * + * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.) + * + * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}. + * + * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. + * + * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh. + * + * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates. + * The height set varies by device and may either be the height of the window or the viewport. + * + * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. + * + * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. + * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. + * Any other string value (including the empty string) prevents using click trampolines. + * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}. + */ + this.compatibility = { + supportsFullScreen: false, + orientationFallback: null, + noMargins: false, + scrollTo: null, + forceMinimumDocumentHeight: false, + canExpandParent: true, + clickTrampoline: '' + }; + + /** + * Scale mode to be used when not in fullscreen. + * @property {number} _scaleMode + * @private + */ + this._scaleMode = Phaser.ScaleManager.NO_SCALE; + + /* + * Scale mode to be used in fullscreen. + * @property {number} _fullScreenScaleMode + * @private + */ + this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE; + + /** + * True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * The {@link #parentNode} property is generally ignored while this is in effect. + * + * @property {boolean} parentIsWindow + */ + this.parentIsWindow = false; + + /** + * The _original_ DOM element for the parent of the Display canvas. + * This may be different in fullscreen - see {@link #createFullScreenTarget}. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * This should only be changed after moving the Game canvas to a different DOM parent. + * + * @property {?DOMElement} parentNode + */ + this.parentNode = null; + + /** + * The scale of the game in relation to its parent container. + * @property {Phaser.Point} parentScaleFactor + * @readonly + */ + this.parentScaleFactor = new Phaser.Point(1, 1); + + /** + * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). + * Update checks normally happen quicker in response to other events. + * + * @property {integer} trackParentInterval + * @default + * @protected + * @see {@link Phaser.ScaleManager#refresh refresh} + */ + this.trackParentInterval = 2000; + + /** + * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. + * When invoked this is done _after_ the Canvas size/position have been updated. + * + * The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.) + * + * This signal is _only_ called when a change occurs and a reflow may be required. + * For example, if the canvas does not change sizes because of CSS settings (such as min-width) + * then this signal will _not_ be triggered. + * + * Use this to handle responsive game layout options. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onSizeChange + */ + this.onSizeChange = new Phaser.Signal(); + + /** + * The callback that will be called each the parent container resizes. + * @property {function} onResize + * @private + */ + this.onResize = null; + + /** + * The context in which the {@link #onResize} callback will be called. + * @property {object} onResizeContext + * @private + */ + this.onResizeContext = null; + + /** + * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot. + * @private + */ + this._pendingScaleMode = null; + + /** + * Information saved when fullscreen mode is started. + * @property {?object} _fullScreenRestore + * @private + */ + this._fullScreenRestore = null; + + /** + * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}. + * @property {Phaser.Rectangle} _gameSize + * @private + */ + this._gameSize = new Phaser.Rectangle(); + + /** + * The user-supplied scale factor, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleFactor + * @private + */ + this._userScaleFactor = new Phaser.Point(1, 1); + + /** + * The user-supplied scale trim, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleTrim + * @private + */ + this._userScaleTrim = new Phaser.Point(0, 0); + + /** + * The last time the bounds were checked in `preUpdate`. + * @property {number} _lastUpdate + * @private + */ + this._lastUpdate = 0; + + /** + * Size checks updates are delayed according to the throttle. + * The throttle increases to `trackParentInterval` over time and is used to more + * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety. + * @property {integer} _updateThrottle + * @private + */ + this._updateThrottle = 0; + + /** + * The minimum throttle allowed until it has slowed down sufficiently. + * @property {integer} _updateThrottleReset + * @private + */ + this._updateThrottleReset = 100; + + /** + * The cached result of the parent (possibly window) bounds; used to invalidate sizing. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._parentBounds = new Phaser.Rectangle(); + + /** + * Temporary bounds used for internal work to cut down on new objects created. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._tempBounds = new Phaser.Rectangle(); + + /** + * The Canvas size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedCanvasSize + * @private + */ + this._lastReportedCanvasSize = new Phaser.Rectangle(); + + /** + * The Game size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedGameSize + * @private + */ + this._lastReportedGameSize = new Phaser.Rectangle(); + + /** + * @property {boolean} _booted - ScaleManager booted state. + * @private + */ + this._booted = false; + + if (game.config) + { + this.parseConfig(game.config); + } + + this.setupScale(width, height); + +}; + +/** +* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.EXACT_FIT = 0; + +/** +* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.NO_SCALE = 1; + +/** +* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.SHOW_ALL = 2; + +/** +* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.RESIZE = 3; + +/** +* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.USER_SCALE = 4; + +/** +* Names of the scale modes, indexed by value. +* +* @constant +* @type {string[]} +*/ +Phaser.ScaleManager.MODES = [ + 'EXACT_FIT', + 'NO_SCALE', + 'SHOW_ALL', + 'RESIZE', + 'USER_SCALE' +]; + +Phaser.ScaleManager.prototype = { + + /** + * Start the ScaleManager. + * + * @method Phaser.ScaleManager#boot + * @protected + */ + boot: function () { + + // Configure device-dependent compatibility + + var compat = this.compatibility; + + compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS; + + // We can't do anything about the status bars in iPads, web apps or desktops + if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop) + { + if (this.game.device.android && !this.game.device.chrome) + { + compat.scrollTo = new Phaser.Point(0, 1); + } + else + { + compat.scrollTo = new Phaser.Point(0, 0); + } + } + + if (this.game.device.desktop) + { + compat.orientationFallback = 'screen'; + compat.clickTrampoline = 'when-not-mouse'; + } + else + { + compat.orientationFallback = ''; + compat.clickTrampoline = ''; + } + + // Configure event listeners + + var _this = this; + + this._orientationChange = function(event) { + return _this.orientationChange(event); + }; + + this._windowResize = function(event) { + return _this.windowResize(event); + }; + + // This does not appear to be on the standards track + window.addEventListener('orientationchange', this._orientationChange, false); + window.addEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + this._fullScreenChange = function(event) { + return _this.fullScreenChange(event); + }; + + this._fullScreenError = function(event) { + return _this.fullScreenError(event); + }; + + document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.addEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.addEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.addEventListener('fullscreenchange', this._fullScreenChange, false); + + document.addEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.addEventListener('mozfullscreenerror', this._fullScreenError, false); + document.addEventListener('MSFullscreenError', this._fullScreenError, false); + document.addEventListener('fullscreenerror', this._fullScreenError, false); + } + + this.game.onResume.add(this._gameResumed, this); + + // Initialize core bounds + + this.dom.getOffset(this.game.canvas, this.offset); + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + this.setGameSize(this.game.width, this.game.height); + + // Don't use updateOrientationState so events are not fired + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + if (Phaser.FlexGrid) + { + this.grid = new Phaser.FlexGrid(this, this.width, this.height); + } + + this._booted = true; + + if (this._pendingScaleMode !== null) + { + this.scaleMode = this._pendingScaleMode; + this._pendingScaleMode = null; + } + + }, + + /** + * Load configuration settings. + * + * @method Phaser.ScaleManager#parseConfig + * @protected + * @param {object} config - The game configuration object. + */ + parseConfig: function (config) { + + if (config['scaleMode'] !== undefined) + { + if (this._booted) + { + this.scaleMode = config['scaleMode']; + } + else + { + this._pendingScaleMode = config['scaleMode']; + } + } + + if (config['fullScreenScaleMode'] !== undefined) + { + this.fullScreenScaleMode = config['fullScreenScaleMode']; + } + + if (config['fullScreenTarget']) + { + this.fullScreenTarget = config['fullScreenTarget']; + } + + this.pageAlignHorizontally = config.alignH || false; + this.pageAlignVertically = config.alignV || false; + + if (config.scaleH && config.scaleV) + { + this.setUserScale(config.scaleH, config.scaleV, config.trimH, config.trimV); + } + + }, + + /** + * Calculates and sets the game dimensions based on the given width and height. + * + * This should _not_ be called when in fullscreen mode. + * + * @method Phaser.ScaleManager#setupScale + * @protected + * @param {number|string} width - The width of the game. + * @param {number|string} height - The height of the game. + */ + setupScale: function (width, height) { + + var target; + var rect = new Phaser.Rectangle(); + + if (this.game.parent !== '') + { + if (typeof this.game.parent === 'string') + { + // hopefully an element ID + target = document.getElementById(this.game.parent); + } + else if (this.game.parent && this.game.parent.nodeType === 1) + { + // quick test for a HTMLelement + target = this.game.parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + // Use the full window + this.parentNode = null; + this.parentIsWindow = true; + + rect.width = this.dom.visualBounds.width; + rect.height = this.dom.visualBounds.height; + + this.offset.set(0, 0); + } + else + { + this.parentNode = target; + this.parentIsWindow = false; + + this.getParentBounds(this._parentBounds); + + rect.width = this._parentBounds.width; + rect.height = this._parentBounds.height; + + this.offset.set(this._parentBounds.x, this._parentBounds.y); + } + + var newWidth = 0; + var newHeight = 0; + + if (typeof width === 'number') + { + newWidth = width; + } + else + { + // Percentage based + this.parentScaleFactor.x = parseInt(width, 10) / 100; + newWidth = rect.width * this.parentScaleFactor.x; + } + + if (typeof height === 'number') + { + newHeight = height; + } + else + { + // Percentage based + this.parentScaleFactor.y = parseInt(height, 10) / 100; + newHeight = rect.height * this.parentScaleFactor.y; + } + + newWidth = Math.floor(newWidth); + newHeight = Math.floor(newHeight); + + this._gameSize.setTo(0, 0, newWidth, newHeight); + + this.updateDimensions(newWidth, newHeight, false); + + }, + + /** + * Invoked when the game is resumed. + * + * @method Phaser.ScaleManager#_gameResumed + * @private + */ + _gameResumed: function () { + + this.queueUpdate(true); + + }, + + /** + * Set the actual Game size. + * Use this instead of directly changing `game.width` or `game.height`. + * + * The actual physical display (Canvas element size) depends on various settings including + * - Scale mode + * - Scaling factor + * - Size of Canvas's parent element or CSS rules such as min-height/max-height; + * - The size of the Window + * + * @method Phaser.ScaleManager#setGameSize + * @public + * @param {integer} width - _Game width_, in pixels. + * @param {integer} height - _Game height_, in pixels. + */ + setGameSize: function (width, height) { + + this._gameSize.setTo(0, 0, width, height); + + if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE) + { + this.updateDimensions(width, height, true); + } + + this.queueUpdate(true); + + }, + + /** + * Set a User scaling factor used in the USER_SCALE scaling mode. + * + * The target canvas size is computed by: + * + * canvas.width = (game.width * hScale) - hTrim + * canvas.height = (game.height * vScale) - vTrim + * + * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly. + * + * @method Phaser.ScaleManager#setUserScale + * @param {number} hScale - Horizontal scaling factor. + * @param {numer} vScale - Vertical scaling factor. + * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling. + * @param {integer} [vTrim=0] - Vertical trim, applied after scaling. + * @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate + * @param {boolean} [force=true] - Force a resize during the next preUpdate + */ + setUserScale: function (hScale, vScale, hTrim, vTrim, queueUpdate, force) { + + this._userScaleFactor.setTo(hScale, vScale); + this._userScaleTrim.setTo(hTrim | 0, vTrim | 0); + + if (queueUpdate === undefined) { queueUpdate = true; } + if (force === undefined) { force = true; } + + if (queueUpdate) + { + this.queueUpdate(force); + } + + }, + + /** + * Sets the callback that will be invoked before sizing calculations. + * + * Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries: + * the browser window has been resized, the device has been rotated, or the parent container's size has changed. + * At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all + * after it makes its sizing calculations). You can read the size of the parent container from the + * `parentBounds` argument to the callback. + * + * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling. + * + * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager + * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. + * + * This callback + * - May be invoked even though the parent container or canvas sizes have not changed + * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated + * - Will be invoked from `preUpdate`, _even when_ the game is paused + * + * See {@link #onSizeChange} for a better way of reacting to layout updates. + * + * @method Phaser.ScaleManager#setResizeCallback + * @public + * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes. + * @param {object} context - The context in which the callback will be called. + */ + setResizeCallback: function (callback, context) { + + this.onResize = callback; + this.onResizeContext = context; + + }, + + /** + * Signals a resize - IF the canvas or Game size differs from the last signal. + * + * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager). + * + * It dispatches the {@link #onSizeChange} signal. + * + * @method Phaser.ScaleManager#signalSizeChange + * @private + */ + signalSizeChange: function () { + + if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) || + !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize)) + { + var width = this.width; + var height = this.height; + + this._lastReportedCanvasSize.setTo(0, 0, width, height); + this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height); + + if (this.grid) + { + this.grid.onResize(width, height); + } + + this.onSizeChange.dispatch(this, width, height); + + // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode. + if (this.currentScaleMode === Phaser.ScaleManager.RESIZE) + { + this.game.state.resize(width, height); + this.game.load.resize(width, height); + } + } + + }, + + /** + * Set the min and max dimensions for the Display canvas. + * + * _Note:_ The min/max dimensions are only applied in some cases + * - When the device is not in an incorrect orientation; or + * - The scale mode is EXACT_FIT when not in fullscreen + * + * @method Phaser.ScaleManager#setMinMax + * @public + * @param {number} minWidth - The minimum width the game is allowed to scale down to. + * @param {number} minHeight - The minimum height the game is allowed to scale down to. + * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified. + * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified. + * @todo These values are only sometimes honored. + */ + setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) { + + this.minWidth = minWidth; + this.minHeight = minHeight; + + if (typeof maxWidth !== 'undefined') + { + this.maxWidth = maxWidth; + } + + if (typeof maxHeight !== 'undefined') + { + this.maxHeight = maxHeight; + } + + }, + + /** + * The ScaleManager.preUpdate is called automatically by the core Game loop. + * + * @method Phaser.ScaleManager#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.game.time.time < (this._lastUpdate + this._updateThrottle)) + { + return; + } + + var prevThrottle = this._updateThrottle; + this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100; + + this.dom.getOffset(this.game.canvas, this.offset); + + var prevWidth = this._parentBounds.width; + var prevHeight = this._parentBounds.height; + var bounds = this.getParentBounds(this._parentBounds); + + var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight; + + // Always invalidate on a newly detected orientation change + var orientationChanged = this.updateOrientationState(); + + if (boundsChanged || orientationChanged) + { + if (this.onResize) + { + this.onResize.call(this.onResizeContext, this, bounds); + } + + this.updateLayout(); + + this.signalSizeChange(); + } + + // Next throttle, eg. 25, 50, 100, 200.. + var throttle = this._updateThrottle * 2; + + // Don't let an update be too eager about resetting the throttle. + if (this._updateThrottle < prevThrottle) + { + throttle = Math.min(prevThrottle, this._updateThrottleReset); + } + + this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval); + this._lastUpdate = this.game.time.time; + + }, + + /** + * Update method while paused. + * + * @method Phaser.ScaleManager#pauseUpdate + * @private + */ + pauseUpdate: function () { + + this.preUpdate(); + + // Updates at slowest. + this._updateThrottle = this.trackParentInterval; + + }, + + /** + * Update the dimensions taking the parent scaling factor into account. + * + * @method Phaser.ScaleManager#updateDimensions + * @private + * @param {number} width - The new width of the parent container. + * @param {number} height - The new height of the parent container. + * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars. + */ + updateDimensions: function (width, height, resize) { + + this.width = width * this.parentScaleFactor.x; + this.height = height * this.parentScaleFactor.y; + + this.game.width = this.width; + this.game.height = this.height; + + this.sourceAspectRatio = this.width / this.height; + this.updateScalingAndBounds(); + + if (resize) + { + // Resize the renderer (which in turn resizes the Display canvas!) + this.game.renderer.resize(this.width, this.height); + + // The Camera can never be smaller than the Game size + this.game.camera.setSize(this.width, this.height); + + // This should only happen if the world is smaller than the new canvas size + this.game.world.resize(this.width, this.height); + } + + }, + + /** + * Update relevant scaling values based on the ScaleManager dimension and game dimensions, + * which should already be set. This does not change {@link #sourceAspectRatio}. + * + * @method Phaser.ScaleManager#updateScalingAndBounds + * @private + */ + updateScalingAndBounds: function () { + + this.scaleFactor.x = this.game.width / this.width; + this.scaleFactor.y = this.game.height / this.height; + + this.scaleFactorInversed.x = this.width / this.game.width; + this.scaleFactorInversed.y = this.height / this.game.height; + + this.aspectRatio = this.width / this.height; + + // This can be invoked in boot pre-canvas + if (this.game.canvas) + { + this.dom.getOffset(this.game.canvas, this.offset); + } + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + // Can be invoked in boot pre-input + if (this.game.input && this.game.input.scale) + { + this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y); + } + + }, + + /** + * Force the game to run in only one orientation. + * + * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. + * + * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor + * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the + * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` + * + * @method Phaser.ScaleManager#forceOrientation + * @public + * @param {boolean} forceLandscape - true if the game should run in landscape mode only. + * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. + */ + forceOrientation: function (forceLandscape, forcePortrait) { + + if (forcePortrait === undefined) { forcePortrait = false; } + + if (forceLandscape === true && forcePortrait === true) + { + console.warn('Phaser.ScaleManager: forceLandscape and forcePortrait cannot both be true.'); + return; + } + + this.forceLandscape = forceLandscape; + this.forcePortrait = forcePortrait; + + this.queueUpdate(true); + + }, + + /** + * Classify the orientation, per `getScreenOrientation`. + * + * @method Phaser.ScaleManager#classifyOrientation + * @private + * @param {string} orientation - The orientation string, e.g. 'portrait-primary'. + * @return {?string} The classified orientation: 'portrait', 'landscape`, or null. + */ + classifyOrientation: function (orientation) { + + if (orientation === 'portrait-primary' || orientation === 'portrait-secondary') + { + return 'portrait'; + } + else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary') + { + return 'landscape'; + } + else + { + return null; + } + + }, + + /** + * Updates the current orientation and dispatches orientation change events. + * + * @method Phaser.ScaleManager#updateOrientationState + * @private + * @return {boolean} True if the orientation state changed which means a forced update is likely required. + */ + updateOrientationState: function () { + + var previousOrientation = this.screenOrientation; + var previouslyIncorrect = this.incorrectOrientation; + + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) || + (this.forcePortrait && !this.isPortrait); + + var changed = previousOrientation !== this.screenOrientation; + var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation; + + if (correctnessChanged) + { + if (this.incorrectOrientation) + { + this.enterIncorrectOrientation.dispatch(); + } + else + { + this.leaveIncorrectOrientation.dispatch(); + } + } + + if (changed || correctnessChanged) + { + this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect); + } + + return changed || correctnessChanged; + + }, + + /** + * window.orientationchange event handler. + * + * @method Phaser.ScaleManager#orientationChange + * @private + * @param {Event} event - The orientationchange event data. + */ + orientationChange: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * window.resize event handler. + * + * @method Phaser.ScaleManager#windowResize + * @private + * @param {Event} event - The resize event data. + */ + windowResize: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * Scroll to the top - in some environments. See `compatibility.scrollTo`. + * + * @method Phaser.ScaleManager#scrollTop + * @private + */ + scrollTop: function () { + + var scrollTo = this.compatibility.scrollTo; + + if (scrollTo) + { + window.scrollTo(scrollTo.x, scrollTo.y); + } + + }, + + /** + * The "refresh" methods informs the ScaleManager that a layout refresh is required. + * + * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) + * when the browser is resized, the orientation changes, or when there is a detected change + * of the Parent size. Refreshing is also done automatically when public properties, + * such as {@link #scaleMode}, are updated or state-changing methods are invoked. + * + * The "refresh" method _may_ need to be used in a few (rare) situtations when + * + * - a device change event is not correctly detected; or + * - the Parent size changes (and an immediate reflow is desired); or + * - the ScaleManager state is updated by non-standard means; or + * - certain {@link #compatibility} properties are manually changed. + * + * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. + * + * @method Phaser.ScaleManager#refresh + * @public + */ + refresh: function () { + + this.scrollTop(); + this.queueUpdate(true); + + }, + + /** + * Updates the game / canvas position and size. + * + * @method Phaser.ScaleManager#updateLayout + * @private + */ + updateLayout: function () { + + var scaleMode = this.currentScaleMode; + + if (scaleMode === Phaser.ScaleManager.RESIZE) + { + this.reflowGame(); + return; + } + + this.scrollTop(); + + if (this.compatibility.forceMinimumDocumentHeight) + { + // (This came from older code, by why is it here?) + // Set minimum height of content to new window height + document.documentElement.style.minHeight = window.innerHeight + 'px'; + } + + if (this.incorrectOrientation) + { + this.setMaximum(); + } + else + { + if (scaleMode === Phaser.ScaleManager.EXACT_FIT) + { + this.setExactFit(); + } + else if (scaleMode === Phaser.ScaleManager.SHOW_ALL) + { + if (!this.isFullScreen && this.boundingParent && + this.compatibility.canExpandParent) + { + // Try to expand parent out, but choosing maximizing dimensions. + // Then select minimize dimensions which should then honor parent + // maximum bound applications. + this.setShowAll(true); + this.resetCanvas(); + this.setShowAll(); + } + else + { + this.setShowAll(); + } + } + else if (scaleMode === Phaser.ScaleManager.NO_SCALE) + { + this.width = this.game.width; + this.height = this.game.height; + } + else if (scaleMode === Phaser.ScaleManager.USER_SCALE) + { + this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x; + this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y; + } + } + + if (!this.compatibility.canExpandParent && + (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE)) + { + var bounds = this.getParentBounds(this._tempBounds); + this.width = Math.min(this.width, bounds.width); + this.height = Math.min(this.height, bounds.height); + } + + // Always truncate / force to integer + this.width = this.width | 0; + this.height = this.height | 0; + + this.reflowCanvas(); + + }, + + /** + * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. + * + * If in fullscreen mode or without parent (see {@link #parentIsWindow}), + * this will be the bounds of the visual viewport itself. + * + * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside + * the viewport then this function may return a smaller than expected size. + * + * Values are rounded to the nearest pixel. + * + * @method Phaser.ScaleManager#getParentBounds + * @protected + * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed. + * @return {Phaser.Rectangle} The established parent bounds. + */ + getParentBounds: function (target) { + + var bounds = target || new Phaser.Rectangle(); + var parentNode = this.boundingParent; + var visualBounds = this.dom.visualBounds; + var layoutBounds = this.dom.layoutBounds; + + if (!parentNode) + { + bounds.setTo(0, 0, visualBounds.width, visualBounds.height); + } + else + { + // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect + var clientRect = parentNode.getBoundingClientRect(); + var parentRect = (parentNode.offsetParent) ? parentNode.offsetParent.getBoundingClientRect() : parentNode.getBoundingClientRect(); + + bounds.setTo(clientRect.left - parentRect.left, clientRect.top - parentRect.top, clientRect.width, clientRect.height); + + var wc = this.windowConstraints; + + if (wc.right) + { + var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds; + bounds.right = Math.min(bounds.right, windowBounds.width); + } + + if (wc.bottom) + { + var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds; + bounds.bottom = Math.min(bounds.bottom, windowBounds.height); + } + } + + bounds.setTo( + Math.round(bounds.x), Math.round(bounds.y), + Math.round(bounds.width), Math.round(bounds.height)); + + return bounds; + + }, + + + /** + * Shorthand for setting {@link #pageAlignHorizontally} and {@link #pageAlignVertically}. + * + * @method Phaser.ScaleManager#align + * @param {boolean} [horizontal] - Value for {@link #pageAlignHorizontally}. Pass `null` to leave unchanged. + * @param {boolean} [vertical] - Value for {@link #pageAlignVertically}. Omit or pass `null` to leave unchanged. + */ + align: function (horizontal, vertical) { + + if (horizontal != null) + { + this.pageAlignHorizontally = horizontal; + } + + if (vertical != null) + { + this.pageAlignVertically = vertical; + } + + }, + + /** + * Update the canvas position/margins - for alignment within the parent container. + * + * The canvas margins _must_ be reset/cleared prior to invoking this. + * + * @method Phaser.ScaleManager#alignCanvas + * @private + * @param {boolean} horizontal - Align horizontally? + * @param {boolean} vertical - Align vertically? + */ + alignCanvas: function (horizontal, vertical) { + + var parentBounds = this.getParentBounds(this._tempBounds); + var canvas = this.game.canvas; + var margin = this.margin; + + if (horizontal) + { + margin.left = margin.right = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.width < parentBounds.width && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.left - parentBounds.x; + var targetEdge = (parentBounds.width / 2) - (this.width / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + + margin.left = Math.round(offset); + } + + canvas.style.marginLeft = margin.left + 'px'; + + if (margin.left !== 0) + { + margin.right = -(parentBounds.width - canvasBounds.width - margin.left); + canvas.style.marginRight = margin.right + 'px'; + } + } + + if (vertical) + { + margin.top = margin.bottom = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.height < parentBounds.height && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.top - parentBounds.y; + var targetEdge = (parentBounds.height / 2) - (this.height / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + margin.top = Math.round(offset); + } + + canvas.style.marginTop = margin.top + 'px'; + + if (margin.top !== 0) + { + margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top); + canvas.style.marginBottom = margin.bottom + 'px'; + } + } + + // Silly backwards compatibility.. + margin.x = margin.left; + margin.y = margin.top; + + }, + + /** + * Updates the Game state / size. + * + * The canvas margins may always be adjusted, even if alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowGame + * @private + */ + reflowGame: function () { + + this.resetCanvas('', ''); + + var bounds = this.getParentBounds(this._tempBounds); + this.updateDimensions(bounds.width, bounds.height, true); + + }, + + /** + * Updates the Display canvas size. + * + * The canvas margins may always be adjusted, even alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowCanvas + * @private + */ + reflowCanvas: function () { + + if (!this.incorrectOrientation) + { + this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width); + this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height); + } + + this.resetCanvas(); + + if (!this.compatibility.noMargins) + { + if (this.isFullScreen && this._createdFullScreenTarget) + { + this.alignCanvas(true, true); + } + else + { + this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically); + } + } + + this.updateScalingAndBounds(); + + }, + + /** + * "Reset" the Display canvas and set the specified width/height. + * + * @method Phaser.ScaleManager#resetCanvas + * @private + * @param {string} [cssWidth=(current width)] - The css width to set. + * @param {string} [cssHeight=(current height)] - The css height to set. + */ + resetCanvas: function (cssWidth, cssHeight) { + + if (cssWidth === undefined) { cssWidth = this.width + 'px'; } + if (cssHeight === undefined) { cssHeight = this.height + 'px'; } + + var canvas = this.game.canvas; + + if (!this.compatibility.noMargins) + { + canvas.style.marginLeft = ''; + canvas.style.marginTop = ''; + canvas.style.marginRight = ''; + canvas.style.marginBottom = ''; + } + + canvas.style.width = cssWidth; + canvas.style.height = cssHeight; + + }, + + /** + * Queues/marks a size/bounds check as needing to occur (from `preUpdate`). + * + * @method Phaser.ScaleManager#queueUpdate + * @private + * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty. + */ + queueUpdate: function (force) { + + if (force) + { + this._parentBounds.width = 0; + this._parentBounds.height = 0; + } + + this._updateThrottle = this._updateThrottleReset; + + }, + + /** + * Reset internal data/state. + * + * @method Phaser.ScaleManager#reset + * @private + */ + reset: function (clearWorld) { + + if (clearWorld && this.grid) + { + this.grid.reset(); + } + + }, + + /** + * Updates the width/height to that of the window. + * + * @method Phaser.ScaleManager#setMaximum + * @private + */ + setMaximum: function () { + + this.width = this.dom.visualBounds.width; + this.height = this.dom.visualBounds.height; + + }, + + /** + * Updates the width/height such that the game is scaled proportionally. + * + * @method Phaser.ScaleManager#setShowAll + * @private + * @param {boolean} expanding - If true then the maximizing dimension is chosen. + */ + setShowAll: function (expanding) { + + var bounds = this.getParentBounds(this._tempBounds); + var width = bounds.width; + var height = bounds.height; + + var multiplier; + + if (expanding) + { + multiplier = Math.max((height / this.game.height), (width / this.game.width)); + } + else + { + multiplier = Math.min((height / this.game.height), (width / this.game.width)); + } + + this.width = Math.round(this.game.width * multiplier); + this.height = Math.round(this.game.height * multiplier); + + }, + + /** + * Updates the width/height such that the game is stretched to the available size. + * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen. + * + * @method Phaser.ScaleManager#setExactFit + * @private + */ + setExactFit: function () { + + var bounds = this.getParentBounds(this._tempBounds); + + this.width = bounds.width; + this.height = bounds.height; + + if (this.isFullScreen) + { + // Max/min not honored fullscreen + return; + } + + if (this.maxWidth) + { + this.width = Math.min(this.width, this.maxWidth); + } + + if (this.maxHeight) + { + this.height = Math.min(this.height, this.maxHeight); + } + + }, + + /** + * Creates a fullscreen target. This is called automatically as as needed when entering + * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}. + * + * Use {@link #onFullScreenInit} to customize the created object. + * + * @method Phaser.ScaleManager#createFullScreenTarget + * @protected + */ + createFullScreenTarget: function () { + + var fsTarget = document.createElement('div'); + + fsTarget.style.margin = '0'; + fsTarget.style.padding = '0'; + fsTarget.style.background = '#000'; + + return fsTarget; + + }, + + /** + * Display the game in the browser's fullscreen mode. + * + * This _must_ be called from a user-input Pointer or Mouse event (and possibly a {@link https://www.chromestatus.com/feature/6131337345892352 "user gesture"}), e.g., + * + * - {@link Phaser.Events#onInputUp} + * - {@link Phaser.Input#onUp} or {@link Phaser.Input#onTap} + * - `click`, `mousedown`, `mouseup`, `pointerup`, or `touchend` + * + * Games within an iframe will also be blocked from fullscreen unless the iframe has the `allowfullscreen` attribute. + * + * The {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} must be {@link http://caniuse.com/#search=fullscreen supported by the browser} for this to work - it is not the same as setting + * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current + * device is reported to support fullscreen mode. + * + * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. + * + * Safari blocks access to keyboard events in fullscreen mode (as a security measure). + * + * @method Phaser.ScaleManager#startFullScreen + * @public + * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. + * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed. + * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) + */ + startFullScreen: function (antialias, allowTrampoline) { + + if (this.isFullScreen) + { + return false; + } + + if (!this.compatibility.supportsFullScreen) + { + // Error is called in timeout to emulate the real fullscreenerror event better + var _this = this; + + setTimeout(function () { + _this.fullScreenError(); + }, 10); + + return; + } + + if (this.compatibility.clickTrampoline === 'when-not-mouse') + { + var input = this.game.input; + + if (input.activePointer && + input.activePointer !== input.mousePointer && + (allowTrampoline || allowTrampoline !== false)) + { + input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]); + return; + } + } + + if (antialias !== undefined && this.game.renderType === Phaser.CANVAS) + { + this.game.stage.smoothed = antialias; + } + + var fsTarget = this.fullScreenTarget; + + if (!fsTarget) + { + this.cleanupCreatedTarget(); + + this._createdFullScreenTarget = this.createFullScreenTarget(); + fsTarget = this._createdFullScreenTarget; + } + + var initData = { + targetElement: fsTarget + }; + + this.hasPhaserSetFullScreen = true; + + this.onFullScreenInit.dispatch(this, initData); + + if (this._createdFullScreenTarget) + { + // Move the Display canvas inside of the target and add the target to the DOM + // (The target has to be added for the Fullscreen API to work.) + var canvas = this.game.canvas; + var parent = canvas.parentNode; + parent.insertBefore(fsTarget, canvas); + fsTarget.appendChild(canvas); + } + + if (this.game.device.fullscreenKeyboard) + { + fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT); + } + else + { + fsTarget[this.game.device.requestFullscreen](); + } + + return true; + + }, + + /** + * Stops / exits fullscreen mode, if active. + * + * @method Phaser.ScaleManager#stopFullScreen + * @public + * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. + */ + stopFullScreen: function () { + + if (!this.isFullScreen || !this.compatibility.supportsFullScreen) + { + return false; + } + + this.hasPhaserSetFullScreen = false; + + document[this.game.device.cancelFullscreen](); + + return true; + + }, + + /** + * Cleans up the previous fullscreen target, if such was automatically created. + * This ensures the canvas is restored to its former parent, assuming the target didn't move. + * + * @method Phaser.ScaleManager#cleanupCreatedTarget + * @private + */ + cleanupCreatedTarget: function () { + + var fsTarget = this._createdFullScreenTarget; + + if (fsTarget && fsTarget.parentNode) + { + // Make sure to cleanup synthetic target for sure; + // swap the canvas back to the parent. + var parent = fsTarget.parentNode; + parent.insertBefore(this.game.canvas, fsTarget); + parent.removeChild(fsTarget); + } + + this._createdFullScreenTarget = null; + + }, + + /** + * Used to prepare/restore extra fullscreen mode settings. + * (This does move any elements within the DOM tree.) + * + * @method Phaser.ScaleManager#prepScreenMode + * @private + * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_. + */ + prepScreenMode: function (enteringFullscreen) { + + var createdTarget = !!this._createdFullScreenTarget; + var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget; + + if (enteringFullscreen) + { + if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT) + { + // Resize target, as long as it's not the canvas + if (fsTarget !== this.game.canvas) + { + this._fullScreenRestore = { + targetWidth: fsTarget.style.width, + targetHeight: fsTarget.style.height + }; + + fsTarget.style.width = '100%'; + fsTarget.style.height = '100%'; + } + } + } + else + { + // Have restore information + if (this._fullScreenRestore) + { + fsTarget.style.width = this._fullScreenRestore.targetWidth; + fsTarget.style.height = this._fullScreenRestore.targetHeight; + + this._fullScreenRestore = null; + } + + // Always reset to game size + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.resetCanvas(); + } + + }, + + /** + * Called automatically when the browser enters of leaves fullscreen mode. + * + * @method Phaser.ScaleManager#fullScreenChange + * @private + * @param {Event} [event=undefined] - The fullscreenchange event + */ + fullScreenChange: function (event) { + + this.event = event; + + if (this.isFullScreen) + { + this.prepScreenMode(true); + + this.updateLayout(); + this.queueUpdate(true); + } + else + { + this.prepScreenMode(false); + + this.cleanupCreatedTarget(); + + this.updateLayout(); + this.queueUpdate(true); + } + + this.onFullScreenChange.dispatch(this, this.width, this.height); + + }, + + /** + * Called automatically when the browser fullscreen request fails; + * or called when a fullscreen request is made on a device for which it is not supported. + * + * @method Phaser.ScaleManager#fullScreenError + * @private + * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API. + */ + fullScreenError: function (event) { + + this.event = event; + + this.cleanupCreatedTarget(); + + console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API'); + + this.onFullScreenError.dispatch(this); + + }, + + /** + * Takes a Sprite or Image object and scales it to fit the given dimensions. + * Scaling happens proportionally without distortion to the sprites texture. + * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the + * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either + * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. + * + * @method Phaser.ScaleManager#scaleSprite + * @protected + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale. + * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. + * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. + * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. + * @return {Phaser.Sprite|Phaser.Image} The scaled sprite. + */ + scaleSprite: function (sprite, width, height, letterBox) { + + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + if (letterBox === undefined) { letterBox = false; } + + if (!sprite || !sprite['scale']) + { + return sprite; + } + + sprite.scale.x = 1; + sprite.scale.y = 1; + + if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0)) + { + return sprite; + } + + var scaleX1 = width; + var scaleY1 = (sprite.height * width) / sprite.width; + + var scaleX2 = (sprite.width * height) / sprite.height; + var scaleY2 = height; + + var scaleOnWidth = (scaleX2 > width); + + if (scaleOnWidth) + { + scaleOnWidth = letterBox; + } + else + { + scaleOnWidth = !letterBox; + } + + if (scaleOnWidth) + { + sprite.width = Math.floor(scaleX1); + sprite.height = Math.floor(scaleY1); + } + else + { + sprite.width = Math.floor(scaleX2); + sprite.height = Math.floor(scaleY2); + } + + // Enable at some point? + // sprite.x = Math.floor((width - sprite.width) / 2); + // sprite.y = Math.floor((height - sprite.height) / 2); + + return sprite; + + }, + + /** + * Destroys the ScaleManager and removes any event listeners. + * This should probably only be called when the game is destroyed. + * + * @method Phaser.ScaleManager#destroy + * @protected + */ + destroy: function () { + + this.game.onResume.remove(this._gameResumed, this); + + window.removeEventListener('orientationchange', this._orientationChange, false); + window.removeEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.removeEventListener('fullscreenchange', this._fullScreenChange, false); + + document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.removeEventListener('mozfullscreenerror', this._fullScreenError, false); + document.removeEventListener('MSFullscreenError', this._fullScreenError, false); + document.removeEventListener('fullscreenerror', this._fullScreenError, false); + } + + } + +}; + +Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager; + +/** +* The DOM element that is considered the Parent bounding element, if any. +* +* This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified. +* It will also be null if there is no game canvas or if the game canvas has no parent. +* +* @name Phaser.ScaleManager#boundingParent +* @property {?DOMElement} boundingParent +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", { + + get: function () { + + if (this.parentIsWindow || + (this.isFullScreen && this.hasPhaserSetFullScreen && !this._createdFullScreenTarget)) + { + return null; + } + + var parentNode = this.game.canvas && this.game.canvas.parentNode; + + return parentNode || null; + + } + +}); + +/** +* The scaling method used by the ScaleManager when not in fullscreen. +* +*
+*
{@link Phaser.ScaleManager.NO_SCALE}
+*
+* The Game display area will not be scaled - even if it is too large for the canvas/screen. +* This mode _ignores_ any applied scaling factor and displays the canvas at the Game size. +*
+*
{@link Phaser.ScaleManager.EXACT_FIT}
+*
+* The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen. +* Proportions are not maintained. +*
+*
{@link Phaser.ScaleManager.SHOW_ALL}
+*
+* Show the entire game display area while _maintaining_ the original aspect ratio. +*
+*
{@link Phaser.ScaleManager.RESIZE}
+*
+* The dimensions of the game display area are changed to match the size of the parent container. +* That is, this mode _changes the Game size_ to match the display size. +*

+* Any manually set Game size (see {@link #setGameSize}) is ignored while in effect. +*

+*
{@link Phaser.ScaleManager.USER_SCALE}
+*
+* The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}. +*

+* This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback} +* for flexible custom-sizing needs. +*

+*
+* +* @name Phaser.ScaleManager#scaleMode +* @property {integer} scaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", { + + get: function () { + + return this._scaleMode; + + }, + + set: function (value) { + + if (value !== this._scaleMode) + { + if (!this.isFullScreen) + { + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.queueUpdate(true); + } + + this._scaleMode = value; + } + + return this._scaleMode; + + } + +}); + +/** +* The scaling method used by the ScaleManager when in fullscreen. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#fullScreenScaleMode +* @property {integer} fullScreenScaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", { + + get: function () { + + return this._fullScreenScaleMode; + + }, + + set: function (value) { + + if (value !== this._fullScreenScaleMode) + { + // If in fullscreen then need a wee bit more work + if (this.isFullScreen) + { + this.prepScreenMode(false); + this._fullScreenScaleMode = value; + this.prepScreenMode(true); + + this.queueUpdate(true); + } + else + { + this._fullScreenScaleMode = value; + } + } + + return this._fullScreenScaleMode; + + } + +}); + +/** +* Returns the current scale mode - for normal or fullscreen operation. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#currentScaleMode +* @property {number} currentScaleMode +* @protected +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", { + + get: function () { + + return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode; + + } + +}); + +/** +* When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align horizontally across the page the Display canvas should be added directly to page; +* or the parent container should itself be horizontally aligned. +* +* Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignHorizontally +* @property {boolean} pageAlignHorizontally +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", { + + get: function () { + + return this._pageAlignHorizontally; + + }, + + set: function (value) { + + if (value !== this._pageAlignHorizontally) + { + this._pageAlignHorizontally = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain +* a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically +* _within_ the remaining available height dictated by the Parent element. +* +* One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. +* If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). +* +* _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height. +* To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true. +* +* Vertical alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignVertically +* @property {boolean} pageAlignVertically +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", { + + get: function () { + + return this._pageAlignVertically; + + }, + + set: function (value) { + + if (value !== this._pageAlignVertically) + { + this._pageAlignVertically = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* Returns true if the browser is in fullscreen mode, otherwise false. +* @name Phaser.ScaleManager#isFullScreen +* @property {boolean} isFullScreen +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", { + + get: function () { + return !!(document['fullscreenElement'] || + document['webkitFullscreenElement'] || + document['mozFullScreenElement'] || + document['msFullscreenElement']); + } + +}); + +/** +* Returns true if the screen orientation is in portrait mode. +* +* @name Phaser.ScaleManager#isPortrait +* @property {boolean} isPortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'portrait'; + } + +}); + +/** +* Returns true if the screen orientation is in landscape mode. +* +* @name Phaser.ScaleManager#isLandscape +* @property {boolean} isLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'landscape'; + } + +}); + +/** +* Returns true if the game dimensions are portrait (height > width). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGamePortrait +* @property {boolean} isGamePortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", { + + get: function () { + return (this.height > this.width); + } + +}); + +/** +* Returns true if the game dimensions are landscape (width > height). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGameLandscape +* @property {boolean} isGameLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", { + + get: function () { + return (this.width > this.height); + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of methods for displaying debug information about game objects. +* +* If your game is running in Canvas mode, then you should invoke all of the Debug methods from +* your games `render` function. This is because they are drawn directly onto the game canvas +* itself, so if you call any debug methods outside of `render` they are likely to be overwritten +* by the game itself. +* +* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture +* to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug +* in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! +* +* @class Phaser.Utils.Debug +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Utils.Debug = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Image} sprite - If debugging in WebGL mode, this is the Image displaying the debug {@link #bmd BitmapData}. + */ + this.sprite = null; + + /** + * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.context = null; + + /** + * @property {string} font - The font that the debug information is rendered in. + * @default + */ + this.font = '14px Courier'; + + /** + * @property {number} columnWidth - The spacing between columns. + * @default + */ + this.columnWidth = 100; + + /** + * @property {number} lineHeight - The line height between the debug text. + * @default + */ + this.lineHeight = 16; + + /** + * @property {number} lineWidth - The width of the stroke on lines and shapes. A positive number. + * @default + */ + this.lineWidth = 1; + + /** + * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. + * @default + */ + this.renderShadow = true; + + /** + * @property {string} currentColor - The color last set by {@link #start} or {@link #text}. + * @default + * @protected + */ + this.currentColor = null; + + /** + * @property {number} currentX - The current X position the debug information will be rendered at. + * @default + */ + this.currentX = 0; + + /** + * @property {number} currentY - The current Y position the debug information will be rendered at. + * @default + */ + this.currentY = 0; + + /** + * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it. + * @default + */ + this.currentAlpha = 1; + + /** + * @property {boolean} dirty - Does the canvas need re-rendering? + * @default + */ + this.dirty = false; + + /** + * @property {boolean} isDisabled - If `enableDebug: false` is passed to {@link Phaser.Game} or if Phaser is built without the Debug class, this will be true. + * @default + * @readonly + */ + this.isDisabled = false; + + /** + * @property {Phaser.Line} _line - A reusable rendering line. + * @private + */ + this._line = null; + + /** + * @property {Phaser.Rectangle} _rect - A reusable rendering rectangle. + * @private + */ + this._rect = null; + +}; + +Phaser.Utils.Debug.prototype = { + + /** + * Internal method that boots the debug displayer. + * + * @method Phaser.Utils.Debug#boot + * @protected + */ + boot: function () { + + if (this.game.renderType === Phaser.CANVAS) + { + this.context = this.game.context; + } + else + { + this.bmd = new Phaser.BitmapData(this.game, '__DEBUG', this.game.width, this.game.height, true); + this.sprite = this.game.make.image(0, 0, this.bmd); + this.game.stage.addChild(this.sprite); + + this.game.scale.onSizeChange.add(this.resize, this); + + this.canvas = Phaser.CanvasPool.create(this, this.game.width, this.game.height); + this.context = this.canvas.getContext('2d'); + } + + this._line = new Phaser.Line(); + this._rect = new Phaser.Rectangle(); + + }, + + /** + * Internal method that resizes the BitmapData and Canvas. + * Called by ScaleManager.onSizeChange only in WebGL mode. + * + * @method Phaser.Utils.Debug#resize + * @protected + */ + resize: function () { + + this.bmd.resize(this.game.width, this.game.height); + + this.canvas.width = this.game.width; + this.canvas.height = this.game.height; + + }, + + /** + * Internal method that clears the canvas (if a Sprite) ready for a new debug session. + * + * @method Phaser.Utils.Debug#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.dirty && this.sprite) + { + this.bmd.clear(); + this.bmd.draw(this.canvas, 0, 0); + + this.context.clearRect(0, 0, this.game.width, this.game.height); + this.dirty = false; + } + + }, + + /** + * Clears the Debug canvas. + * + * @method Phaser.Utils.Debug#reset + */ + reset: function () { + + if (this.context) + { + this.context.clearRect(0, 0, this.game.width, this.game.height); + } + + if (this.sprite) + { + this.bmd.clear(); + } + + }, + + /** + * Internal method that resets and starts the debug output values. + * + * @method Phaser.Utils.Debug#start + * @protected + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + * @param {number} [columnWidth=0] - The spacing between columns. + */ + start: function (x, y, color, columnWidth) { + + if (typeof x !== 'number') { x = 0; } + if (typeof y !== 'number') { y = 0; } + color = color || 'rgb(255,255,255)'; + if (columnWidth === undefined) { columnWidth = 0; } + + this.currentX = x; + this.currentY = y; + this.currentColor = color; + this.columnWidth = columnWidth; + + this.dirty = true; + + this.context.save(); + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.strokeStyle = color; + this.context.fillStyle = color; + this.context.font = this.font; + this.context.globalAlpha = this.currentAlpha; + + }, + + /** + * Internal method that stops the debug output. + * + * @method Phaser.Utils.Debug#stop + * @protected + */ + stop: function () { + + this.context.restore(); + + }, + + /** + * Internal method that outputs a single line of text split over as many columns as needed, one per parameter. + * + * @method Phaser.Utils.Debug#line + * @protected + */ + line: function () { + + var x = this.currentX; + + for (var i = 0; i < arguments.length; i++) + { + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(arguments[i], x + 1, this.currentY + 1); + this.context.fillStyle = this.currentColor; + } + + this.context.fillText(arguments[i], x, this.currentY); + + x += this.columnWidth; + } + + this.currentY += this.lineHeight; + + }, + + /** + * Render Sound Manager information, including volume, mute, audio mode, and locked status. + * + * @method Phaser.Utils.Debug#sound + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + sound: function (x, y, color) { + + var sound = this.game.sound; + + this.start(x, y, color); + + if (sound.noAudio) + { + this.line('Audio is disabled'); + } + else + { + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Mute on pause: ' + sound.muteOnPause); + this.line('Using: ' + (sound.usingWebAudio ? ('Web Audio - ' + sound.context.state) : 'Audio Tag')); + this.line('Touch locked: ' + sound.touchLocked); + } + + this.stop(); + + }, + + /** + * Render Sound information, including decoded state, duration, volume and more. + * + * @method Phaser.Utils.Debug#soundInfo + * @param {Phaser.Sound} sound - The sound object to debug. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + soundInfo: function (sound, x, y, color) { + + this.start(x, y, color); + this.line('Sound: ' + sound.key + ' Touch locked: ' + sound.game.sound.touchLocked); + this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback); + this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding); + this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying + ' Loop: ' + sound.loop); + this.line('Time: ' + sound.currentTime); + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Using: ' + (sound.usingWebAudio ? 'Web Audio' : 'Audio Tag')); + + if (sound.currentMarker !== '') + { + this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')'); + this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop); + this.line('Position: ' + sound.position); + } + + this.stop(); + + }, + + /** + * Marks the follow {@link #target} and {@link #deadzone}. + * + * @method Phaser.Utils.Debug#camera + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {string} [color] - Color of the debug shapes to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the shapes filled (default, true) or stroked (false). + */ + camera: function (camera, color, filled) { + + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + if (deadzone) + { + this._rect.setTo(view.x + deadzone.x, view.y + deadzone.y, deadzone.width, deadzone.height); + this.rectangle(this._rect, color, filled); + } + + if (target) + { + this._line.setTo(view.centerX, view.centerY, target.x, target.y); + this.geom(this._line, color, filled); + this.geom(target, color, false, 3); + } + + }, + + /** + * Render camera information including dimensions and location. + * + * @method Phaser.Utils.Debug#cameraInfo + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + cameraInfo: function (camera, x, y, color) { + + var bounds = camera.bounds; + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + this.start(x, y, color); + this.line('Camera (' + camera.width + ' x ' + camera.height + ')'); + this.line('x: ' + camera.x + ' y: ' + camera.y); + this.line('Bounds: ' + (bounds ? ('x: ' + bounds.x + ' y: ' + bounds.y + ' w: ' + bounds.width + ' h: ' + bounds.height) : 'none')); + this.line('View: x: ' + view.x + ' y: ' + view.y + ' w: ' + view.width + ' h: ' + view.height); + this.line('Deadzone: ' + (deadzone ? ('x: ' + deadzone.x + ' y: ' + deadzone.y + ' w: ' + deadzone.width + ' h: ' + deadzone.height) : deadzone)); + this.line('Total in view: ' + camera.totalInView); + this.line('At limit: x: ' + camera.atLimit.x + ' y: ' + camera.atLimit.y); + this.line('Target: ' + (target ? (target.name || target) : 'none')); + this.stop(); + + }, + + /** + * Render Timer information. + * + * @method Phaser.Utils.Debug#timer + * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + timer: function (timer, x, y, color) { + + this.start(x, y, color); + this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')'); + this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration); + this.line('Paused: ' + timer.paused + ' Length: ' + timer.length); + this.stop(); + + }, + + /** + * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text. + * + * @method Phaser.Utils.Debug#pointer + * @param {Phaser.Pointer} pointer - The Pointer you wish to display. + * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. + * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down. + * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false). + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + pointer: function (pointer, hideIfUp, downColor, upColor, color) { + + if (pointer == null) + { + return; + } + + if (hideIfUp === undefined) { hideIfUp = false; } + downColor = downColor || 'rgba(0,255,0,0.5)'; + upColor = upColor || 'rgba(255,0,0,0.5)'; + + if (hideIfUp === true && pointer.isUp === true) + { + return; + } + + this.start(pointer.x, pointer.y - 100, color); + this.context.beginPath(); + this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2); + + if (pointer.active) + { + this.context.fillStyle = downColor; + } + else + { + this.context.fillStyle = upColor; + } + + this.context.fill(); + this.context.closePath(); + + // Render the points + this.context.beginPath(); + this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y); + this.context.lineTo(pointer.position.x, pointer.position.y); + this.context.lineWidth = 2; + this.context.stroke(); + this.context.closePath(); + + // Render the text + this.line('ID: ' + pointer.id + " Active: " + pointer.active); + this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY); + this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y + " In: " + pointer.withinGame); + this.line('Duration: ' + pointer.duration + " ms"); + this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp); + this.stop(); + + }, + + /** + * Render Sprite Input Debug information. + * + * @method Phaser.Utils.Debug#spriteInputInfo + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInputInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')'); + this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1)); + this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0)); + this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0)); + this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut()); + this.stop(); + + }, + + /** + * Renders Phaser.Key object information. + * + * @method Phaser.Utils.Debug#key + * @param {Phaser.Key} key - The Key to render the information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + key: function (key, x, y, color) { + + this.start(x, y, color, 150); + + this.line('Key:', key.keyCode, 'isDown:', key.isDown); + this.line('justDown:', key.justDown, 'justUp:', key.justUp); + this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0)); + + this.stop(); + + }, + + /** + * Render debug information about the Input object. + * + * @method Phaser.Utils.Debug#inputInfo + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + inputInfo: function (x, y, color) { + + this.start(x, y, color); + this.line('Input'); + this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y); + this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY); + this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1)); + this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY); + this.stop(); + + }, + + /** + * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! + * + * @method Phaser.Utils.Debug#spriteBounds + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + spriteBounds: function (sprite, color, filled) { + + var bounds = sprite.getBounds(); + + bounds.x += this.game.camera.x; + bounds.y += this.game.camera.y; + + this.rectangle(bounds, color, filled); + + }, + + /** + * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it + * + * @method Phaser.Utils.Debug#ropeSegments + * @param {Phaser.Rope} rope - The rope to display the segments of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + ropeSegments: function (rope, color, filled) { + + var segments = rope.segments; + + var self = this; + + segments.forEach(function(segment) { + self.rectangle(segment, color, filled); + }, this); + + }, + + /** + * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. + * + * @method Phaser.Utils.Debug#spriteInfo + * @param {Phaser.Sprite} sprite - The Sprite to display the information of. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + + this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y); + this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1)); + this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1)); + this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera); + this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1)); + + this.stop(); + + }, + + /** + * Renders the sprite coordinates in local, positional and world space. + * + * @method Phaser.Utils.Debug#spriteCoords + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteCoords: function (sprite, x, y, color) { + + this.start(x, y, color, 100); + + if (sprite.name) + { + this.line(sprite.name); + } + + this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2)); + this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2)); + this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2)); + + this.stop(); + + }, + + /** + * Renders Line information in the given color. + * + * @method Phaser.Utils.Debug#lineInfo + * @param {Phaser.Line} line - The Line to display the data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + lineInfo: function (line, x, y, color) { + + this.start(x, y, color, 80); + this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2)); + this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2)); + this.line('length:', line.length.toFixed(2), 'angle:', line.angle); + this.stop(); + + }, + + /** + * Renders a single pixel at the given size. + * + * @method Phaser.Utils.Debug#pixel + * @param {number} x - X position of the pixel to be rendered. + * @param {number} y - Y position of the pixel to be rendered. + * @param {string} [color] - Color of the pixel (format is css color string). + * @param {number} [size=2] - The 'size' to render the pixel at. + */ + pixel: function (x, y, color, size) { + + size = size || 2; + + this.start(); + this.context.fillStyle = color; + this.context.fillRect(x, y, size, size); + this.stop(); + + }, + + /** + * Renders a Phaser geometry object including Rectangle, Circle, Ellipse, Point or Line. + * + * @method Phaser.Utils.Debug#geom + * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Ellipse|Phaser.Point|Phaser.Line} object - The geometry object to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) + * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle,3 = Point, 4 = Line and 5 = Ellipse. + */ + geom: function (object, color, filled, forceType) { + + if (filled === undefined) { filled = true; } + if (forceType === undefined) { forceType = 0; } + + color = color || 'rgba(0,255,0,0.4)'; + + this.start(); + + this.context.fillStyle = color; + this.context.strokeStyle = color; + this.context.lineWidth = this.lineWidth; + + if (object instanceof Phaser.Rectangle || forceType === 1) + { + if (filled) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + } + else if (object instanceof Phaser.Circle || forceType === 2) + { + this.context.beginPath(); + this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + else if (object instanceof Phaser.Point || forceType === 3) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4); + } + else if (object instanceof Phaser.Line || forceType === 4) + { + this.context.beginPath(); + this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y); + this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y); + this.context.closePath(); + this.context.stroke(); + } + else if (object instanceof Phaser.Ellipse || forceType === 5) + { + this.context.beginPath(); + this.context.ellipse(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width/2, object.height/2, 0,2 * Math.PI,false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + + this.stop(); + + }, + + /** + * Renders a Rectangle. + * + * @method Phaser.Utils.Debug#rectangle + * @param {Phaser.Rectangle|object} object - The rectangle to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as filled (default, true) or a stroked (false) + */ + rectangle: function (object, color, filled) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0, 255, 0, 0.4)'; + + this.start(); + + if (filled) + { + this.context.fillStyle = color; + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.lineWidth = this.lineWidth; + this.context.strokeStyle = color; + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + + this.stop(); + + }, + + /** + * Render a string of text. + * + * @method Phaser.Utils.Debug#text + * @param {string} text - The line of text to draw. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {string} [font] - The font of text to draw. + */ + text: function (text, x, y, color, font) { + + color = color || 'rgb(255,255,255)'; + font = font || '16px Courier'; + + this.start(); + this.context.font = font; + + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(text, x + 1, y + 1); + } + + this.context.fillStyle = color; + this.context.fillText(text, x, y); + + this.stop(); + + }, + + /** + * Visually renders a QuadTree to the display. + * + * @method Phaser.Utils.Debug#quadTree + * @param {Phaser.QuadTree} quadtree - The quadtree to render. + * @param {string} color - The color of the lines in the quadtree. + */ + quadTree: function (quadtree, color) { + + color = color || 'rgba(255,0,0,0.3)'; + + this.start(); + + var bounds = quadtree.bounds; + + if (quadtree.nodes.length === 0) + { + this.context.strokeStyle = color; + this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height); + this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier'); + + this.context.strokeStyle = 'rgb(0,255,0)'; + + for (var i = 0; i < quadtree.objects.length; i++) + { + this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height); + } + } + else + { + for (var i = 0; i < quadtree.nodes.length; i++) + { + this.quadTree(quadtree.nodes[i]); + } + } + + this.stop(); + + }, + + /** + * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. + * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. + * To display a P2 Physics body you should enable debug mode on the body when creating it. + * + * @method Phaser.Utils.Debug#body + * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false) + */ + body: function (sprite, color, filled) { + + if (sprite.body) + { + this.start(); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled, this.lineWidth); + } + else if (sprite.body.type === Phaser.Physics.NINJA) + { + Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color); + } + + this.stop(); + } + + }, + + /** + * Render a Sprites Physic Body information. + * + * @method Phaser.Utils.Debug#bodyInfo + * @param {Phaser.Sprite} sprite - The sprite to be rendered. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + bodyInfo: function (sprite, x, y, color) { + + if (sprite.body) + { + this.start(x, y, color, 210); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + this.game.physics.box2d.renderBodyInfo(this, sprite.body); + } + + this.stop(); + } + + }, + + /** + * Renders 'debug draw' data for the Box2D world if it exists. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by + * the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dWorld + */ + box2dWorld: function () { + + this.start(); + + this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0); + this.game.physics.box2d.renderDebugDraw(this.context); + + this.stop(); + + }, + + /** + * Renders 'debug draw' data for the given Box2D body. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dBody + * @param {Phaser.Physics.Box2D.Body} body - The body to be rendered. + * @param {string} [color='rgb(0,255,0)'] - Color of the rendering (format is css color string). + */ + box2dBody: function (body, color) { + + this.start(); + Phaser.Physics.Box2D.renderBody(this.context, body, color); + this.stop(); + + }, + + /** + * Call this function from the Dev Tools console. + * + * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. + * + * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) + * + * @method Phaser.Utils.Debug#displayList + * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World. + */ + displayList: function (displayObject) { + + if (displayObject === undefined) { displayObject = this.game.world; } + + if (displayObject.hasOwnProperty('renderOrderID')) + { + console.log('[' + displayObject.renderOrderID + ']', displayObject); + } + else + { + console.log('[]', displayObject); + } + + if (displayObject.children && displayObject.children.length > 0) + { + for (var i = 0; i < displayObject.children.length; i++) + { + this.game.debug.displayList(displayObject.children[i]); + } + } + + }, + + /** + * Prints a description of the {@link Phaser.Game#renderer renderer} and render session. + * + * @method Phaser.Utils.Debug#renderer + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + renderer: function (x, y, color) { + + var r = this.game.renderer; + var s = r.renderSession; + + this.start(x, y, color); + + this.line((r.gl ? 'WebGL' : 'Canvas') + ' Renderer (' + r.width + ' x ' + r.height + ')'); + this.line('autoResize: ' + r.autoResize); + this.line('clearBeforeRender: ' + r.clearBeforeRender); + this.line('resolution: ' + r.resolution); + this.line('transparent: ' + r.transparent); + this.line('renderSession:'); + + if (r.gl) + { + this.line(' currentBatchedTextures: ('+ r.currentBatchedTextures.length + ')'); + + for (var i = 0; i < r.currentBatchedTextures.length; i++) + { + this.line(' ' + r.currentBatchedTextures[i]); + } + + this.line(' drawCount: ' + s.drawCount); + this.line(' maxTextures: ' + r.maxTextures); + this.line(' maxTextureSize: ' + r.maxTextureSize); + this.line(' maxTextureAvailableSpace: ' + s.maxTextureAvailableSpace); + this.line(' roundPixels: ' + s.roundPixels); + } + else + { + this.line(' roundPixels: ' + s.roundPixels); + this.line(' scaleMode: ' + (s.scaleMode === 0 ? 'LINEAR' : (s.scaleMode === 1 ? 'NEAREST' : s.scaleMode))); + } + + this.stop(); + + }, + + canvasPool: function (x, y, color, columnWidth) { + var pool = Phaser.CanvasPool; + + this.start(x, y, color, columnWidth || 100); + this.line('Canvas Pool'); + this.line('Used:', pool.getTotal()); + this.line('Free:', pool.getFree()); + this.line('Total:', pool.length); + this.stop(); + }, + + /** + * Render each physics {@link #body} in a group. + * + * @method Phaser.Utils.Debug#physicsGroup + * @param {Phaser.Group} group - A group containing physics-enabled sprites. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false). + * @param {boolean} [checkExists=false] Render only children with `exists=true`. + */ + physicsGroup: function (group, color, filled, checkExists) { + + group.forEach(this.body, this, checkExists, color, filled); + + }, + + /** + * Prints Phaser {@link Phaser.VERSION version}, {@link Phaser.Game.#renderType rendering mode}, and {@link Phaser.Device#webAudio device audio support}. + * + * @method Phaser.Utils.Debug#phaser + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + phaser: function (x, y, color) { + + this.text('Phaser v' + Phaser.VERSION + ' ' + + (this.game.renderType === Phaser.WEBGL ? 'WebGL' : 'Canvas') + ' ' + + (this.game.device.webAudio ? 'WebAudio' : 'HTML Audio'), + x, y, color, this.font); + + }, + + /** + * Prints game/canvas dimensions and {@link Phaser.ScaleManager game scale} settings. + * + * @method Phaser.Utils.Debug#scale + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + scale: function (x, y, color) { + + this.start(x, y, color); + + var scale = this.game.scale; + var factor = scale.scaleFactorInversed; + var bounds = scale._parentBounds; + var x = ' x '; + + this.line('Game: ' + this.game.width + x + this.game.height); + this.line('Canvas: ' + scale.width + x + scale.height + + ' (' + factor.x.toFixed(2) + x + factor.y.toFixed(2) + ')' + + ' [' + scale.aspectRatio.toFixed(2) + ']'); + this.line('Mode: ' + Phaser.ScaleManager.MODES[scale.currentScaleMode] + + (scale.currentScaleMode === Phaser.ScaleManager.USER_SCALE ? + (' (' + scale._userScaleFactor.x + x + scale._userScaleFactor.y + ')') : + '')); + this.line('Parent: ' + (scale.parentIsWindow ? 'window' : scale.parentNode) + + (bounds.empty ? '' : (' (' + bounds.width + x + bounds.height + ')'))); + this.line('Screen: ' + scale.classifyOrientation(scale.screenOrientation) + + (scale.incorrectOrientation ? ' (incorrect)' : '')); + + this.stop(); + + }, + + /** + * Prints the progress of a {@link Phaser.Loader}. + * + * Typically you would call this within a {@link State#loadRender} callback and pass `game.load` ({@link Phaser.Game#load}). + * + * You can enable {@link Phaser.Loader#resetLocked} to temporarily hold the loader in its 'complete' state. + * Just remember to disable it before restarting the loader (such as when changing states). + * + * @method Phaser.Utils.Debug#loader + * @param {Phaser.Loader} loader - The loader. Usually `game.load` ({@link Phaser.Game#load}). + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + loader: function (loader, x, y, color) { + + var pad = Phaser.Utils.pad; + + this.start(x, y, color); + + if (loader.hasLoaded) + { + this.line('Complete' + (loader.resetLocked ? ' [locked]' : '')); + } + else if (loader.isLoading) + { + this.line('Loading'); + } + else + { + this.line('Not started'); + } + + if (!loader.hasLoaded || loader.resetLocked) + { + this.line('Progress: ' + (pad(loader.progress, 3) + '%')); + this.line('Files: ' + loader._loadedFileCount + ' of ' + + loader._totalFileCount); + this.line('Packs: ' + loader._loadedPackCount + ' of ' + + loader._loadedPackCount); + } + + this.stop(); + + }, + + /** + * Destroy this object. + * + * @method Phaser.Utils.Debug#destroy + */ + destroy: function () { + + Phaser.CanvasPool.remove(this); + + } + +}; + +Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DOM utility class. +* +* Provides a useful Window and Element functions as well as cross-browser compatibility buffer. +* +* Some code originally derived from {@link https://github.com/ryanve/verge verge}. +* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. +* +* @class Phaser.DOM +* @static +*/ +Phaser.DOM = { + + /** + * Get the [absolute] position of the element relative to the Document. + * + * The value may vary slightly as the page is scrolled due to rounding errors. + * + * @method Phaser.DOM.getOffset + * @param {DOMElement} element - The targeted element that we want to retrieve the offset. + * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. + * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. + */ + getOffset: function (element, point) { + + point = point || new Phaser.Point(); + + var box = element.getBoundingClientRect(); + + var scrollTop = Phaser.DOM.scrollY; + var scrollLeft = Phaser.DOM.scrollX; + var clientTop = document.documentElement.clientTop; + var clientLeft = document.documentElement.clientLeft; + + point.x = box.left + scrollLeft - clientLeft; + point.y = box.top + scrollTop - clientTop; + + return point; + + }, + + /** + * A cross-browser element.getBoundingClientRect method with optional cushion. + * + * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. + * Its properties match the native rectangle. + * The cushion parameter is an amount of pixels (+/-) to cushion the element. + * It adjusts the measurements such that it is possible to detect when an element is near the viewport. + * + * @method Phaser.DOM.getBounds + * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for. + * @param {number} [cushion] - A +/- pixel adjustment amount. + * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. + */ + getBounds: function (element, cushion) { + + if (cushion === undefined) { cushion = 0; } + + element = element && !element.nodeType ? element[0] : element; + + if (!element || element.nodeType !== 1) + { + return false; + } + else + { + return this.calibrate(element.getBoundingClientRect(), cushion); + } + + }, + + /** + * Calibrates element coordinates for `inLayoutViewport` checks. + * + * @method Phaser.DOM.calibrate + * @private + * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}` + * @param {number} [cushion] - A value to adjust the coordinates by. + * @return {object} The calibrated element coordinates + */ + calibrate: function (coords, cushion) { + + cushion = +cushion || 0; + + var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 }; + + output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion); + output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion); + + return output; + + }, + + /** + * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) + * + * @method Phaser.DOM.getAspectRatio + * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. + * @return {number} The aspect ratio. + */ + getAspectRatio: function (object) { + + object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object; + + var w = object['width']; + var h = object['height']; + + if (typeof w === 'function') + { + w = w.call(object); + } + + if (typeof h === 'function') + { + h = h.call(object); + } + + return w / h; + + }, + + /** + * Tests if the given DOM element is within the Layout viewport. + * + * The optional cushion parameter allows you to specify a distance. + * + * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. + * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. + * + * @method Phaser.DOM.inLayoutViewport + * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas. + * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport. + * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it. + */ + inLayoutViewport: function (element, cushion) { + + var r = this.getBounds(element, cushion); + + return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height; + + }, + + /** + * Returns the device screen orientation. + * + * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. + * + * Order of resolving: + * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. + * - Screen size ratio check - If fallback is 'screen', suited for desktops. + * - Viewport size ratio check - If fallback is 'viewport', suited for mobile. + * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. + * - Media query + * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..) + * + * See + * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) + * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) + * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx + * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries + * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation + * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation + * + * @method Phaser.DOM.getScreenOrientation + * @protected + * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'. + */ + getScreenOrientation: function (primaryFallback) { + + var screen = window.screen; + var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; + + if (orientation && typeof orientation.type === 'string') + { + // Screen Orientation API specification + return orientation.type; + } + else if (typeof orientation === 'string') + { + // moz/ms-orientation are strings + return orientation; + } + + var PORTRAIT = 'portrait-primary'; + var LANDSCAPE = 'landscape-primary'; + + if (primaryFallback === 'screen') + { + return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'viewport') + { + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number') + { + // This may change by device based on "natural" orientation. + return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE; + } + else if (window.matchMedia) + { + if (window.matchMedia("(orientation: portrait)").matches) + { + return PORTRAIT; + } + else if (window.matchMedia("(orientation: landscape)").matches) + { + return LANDSCAPE; + } + } + + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + + }, + + /** + * The bounds of the Visual viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one} + * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers. + * + * Supported mobile: + * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} x - Scroll, left offset - eg. "scrollX" + * @property {number} y - Scroll, top offset - eg. "scrollY" + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + visualBounds: new Phaser.Rectangle(), + + /** + * The bounds of the Layout viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two}; + * but honoring the constraints as specified applicable viewport meta-tag. + * + * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see + * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}). + * + * This is _not_ representative of the Visual bounds: in particular the non-primary axis will + * generally be significantly larger than the screen height on mobile devices when running with a + * constrained viewport. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + layoutBounds: new Phaser.Rectangle(), + + /** + * The size of the document / Layout viewport. + * + * This incorrectly reports the dimensions in IE. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Document width in pixels. + * @property {number} height - Document height in pixels. + * @readonly + */ + documentBounds: new Phaser.Rectangle() + +}; + +Phaser.Device.whenReady(function (device) { + + // All target browsers should support page[XY]Offset. + var scrollX = window && ('pageXOffset' in window) ? + function () { return window.pageXOffset; } : + function () { return document.documentElement.scrollLeft; }; + + var scrollY = window && ('pageYOffset' in window) ? + function () { return window.pageYOffset; } : + function () { return document.documentElement.scrollTop; }; + + /** + * A cross-browser window.scrollX. + * + * @name Phaser.DOM.scrollX + * @property {number} scrollX + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollX", { + get: scrollX + }); + + /** + * A cross-browser window.scrollY. + * + * @name Phaser.DOM.scrollY + * @property {number} scrollY + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollY", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "x", { + get: scrollX + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "y", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "y", { + value: 0 + }); + + var treatAsDesktop = device.desktop && + (document.documentElement.clientWidth <= window.innerWidth) && + (document.documentElement.clientHeight <= window.innerHeight); + + // Desktop browsers align the layout viewport with the visual viewport. + // This differs from mobile browsers with their zooming design. + // Ref. http://quirksmode.org/mobile/tableViewport.html + if (treatAsDesktop) + { + + // PST- When scrollbars are not included this causes upstream issues in ScaleManager. + // So reverted to the old "include scrollbars." + var clientWidth = function () { + return Math.max(window.innerWidth, document.documentElement.clientWidth); + }; + var clientHeight = function () { + return Math.max(window.innerHeight, document.documentElement.clientHeight); + }; + + // Interested in area sans-scrollbar + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: clientHeight + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + get: clientHeight + }); + + } else { + + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: function () { + return window.innerWidth; + } + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: function () { + return window.innerHeight; + } + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + + get: function () { + var a = document.documentElement.clientWidth; + var b = window.innerWidth; + + return a < b ? b : a; // max + } + + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + + get: function () { + var a = document.documentElement.clientHeight; + var b = window.innerHeight; + + return a < b ? b : a; // max + } + + }); + + } + + // For Phaser.DOM.documentBounds + // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html + + Object.defineProperty(Phaser.DOM.documentBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "y", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "width", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth); + } + + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "height", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight); + } + + }); + +}, null, true); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* ArraySet is a Set data structure (items must be unique within the set) that also maintains order. +* This allows specific items to be easily added or removed from the Set. +* +* Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. +* +* This used primarily by the Input subsystem. +* +* @class Phaser.ArraySet +* @constructor +* @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet. +*/ +Phaser.ArraySet = function (list) { + + /** + * Current cursor position as established by `first` and `next`. + * @property {integer} position + * @default + */ + this.position = 0; + + /** + * The backing array. + * @property {any[]} list + */ + this.list = list || []; + +}; + +Phaser.ArraySet.prototype = { + + /** + * Adds a new element to the end of the list. + * If the item already exists in the list it is not moved. + * + * @method Phaser.ArraySet#add + * @param {any} item - The element to add to this list. + * @return {any} The item that was added. + */ + add: function (item) { + + if (!this.exists(item)) + { + this.list.push(item); + } + + return item; + + }, + + /** + * Gets the index of the item in the list, or -1 if it isn't in the list. + * + * @method Phaser.ArraySet#getIndex + * @param {any} item - The element to get the list index for. + * @return {integer} The index of the item or -1 if not found. + */ + getIndex: function (item) { + + return this.list.indexOf(item); + + }, + + /** + * Gets an item from the set based on the property strictly equaling the value given. + * Returns null if not found. + * + * @method Phaser.ArraySet#getByKey + * @param {string} property - The property to check against the value. + * @param {any} value - The value to check if the property strictly equals. + * @return {any} The item that was found, or null if nothing matched. + */ + getByKey: function (property, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i][property] === value) + { + return this.list[i]; + } + } + + return null; + + }, + + /** + * Checks for the item within this list. + * + * @method Phaser.ArraySet#exists + * @param {any} item - The element to get the list index for. + * @return {boolean} True if the item is found in the list, otherwise false. + */ + exists: function (item) { + + return (this.list.indexOf(item) > -1); + + }, + + /** + * Removes all the items. + * + * @method Phaser.ArraySet#reset + */ + reset: function () { + + this.list.length = 0; + + }, + + /** + * Removes the given element from this list if it exists. + * + * @method Phaser.ArraySet#remove + * @param {any} item - The item to be removed from the list. + * @return {any} item - The item that was removed. + */ + remove: function (item) { + + var idx = this.list.indexOf(item); + + if (idx > -1) + { + this.list.splice(idx, 1); + return item; + } + + }, + + /** + * Sets the property `key` to the given value on all members of this list. + * + * @method Phaser.ArraySet#setAll + * @param {any} key - The property of the item to set. + * @param {any} value - The value to set the property to. + */ + setAll: function (key, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + this.list[i][key] = value; + } + } + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * + * If the `key` property is present it must be a function. + * The function is invoked using the item as the context. + * + * @method Phaser.ArraySet#callAll + * @param {string} key - The name of the property with the function to call. + * @param {...*} parameter - Additional parameters that will be passed to the callback. + */ + callAll: function (key) { + + var args = Array.prototype.slice.call(arguments, 1); + + var i = this.list.length; + + while (i--) + { + if (this.list[i] && this.list[i][key]) + { + this.list[i][key].apply(this.list[i], args); + } + } + + }, + + /** + * Removes every member from this ArraySet and optionally destroys it. + * + * @method Phaser.ArraySet#removeAll + * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set. + */ + removeAll: function (destroy) { + + if (destroy === undefined) { destroy = false; } + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + var item = this.remove(this.list[i]); + + if (destroy) + { + item.destroy(); + } + } + } + + this.position = 0; + this.list = []; + + } + +}; + +/** +* Number of items in the ArraySet. Same as `list.length`. +* +* @name Phaser.ArraySet#total +* @property {integer} total +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "total", { + + get: function () { + return this.list.length; + } + +}); + +/** +* Returns the first item and resets the cursor to the start. +* +* @name Phaser.ArraySet#first +* @property {any} first +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "first", { + + get: function () { + + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + + } + +}); + +/** +* Returns the the next item (based on the cursor) and advances the cursor. +* +* @name Phaser.ArraySet#next +* @property {any} next +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "next", { + + get: function () { + + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + + } + +}); + +Phaser.ArraySet.prototype.constructor = Phaser.ArraySet; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Utility functions for dealing with Arrays. +* +* @class Phaser.ArrayUtils +* @static +*/ +Phaser.ArrayUtils = { + + /** + * Fetch a random entry from the given array. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.getRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was selected. + */ + getRandomItem: function (objects, startIndex, length) { + + if (objects === null) { return null; } + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + + return objects[randomIndex] === undefined ? null : objects[randomIndex]; + + }, + + /** + * Removes a random object from the given array and returns it. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.removeRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was removed. + */ + removeRandomItem: function (objects, startIndex, length) { + + if (objects == null) { // undefined or null + return null; + } + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + if (randomIndex < objects.length) + { + var removed = objects.splice(randomIndex, 1); + return removed[0] === undefined ? null : removed[0]; + } + else + { + return null; + } + + }, + + /** + * Remove one or more items at the given index and reorder the array. + * + * The new array length will be `array.length - count`. + * + * This is an alternative to `array.splice(startIndex, count)`. + * + * @see https://github.com/mreinstein/remove-array-items + * @see https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ + * + * @method Phaser.ArrayUtils.remove + * @param {any[]} array + * @param {integer} startIndex + * @param {integer} [count=1] + * @return {any[]} The modified array. + */ + remove: function (array, startIndex, count) + { + var length = array.length; + + if (startIndex >= length || count === 0) { return; } + + if (count == null) { count = 1; } + + var newLength = length - count; + + for (var i = startIndex; i < newLength; ++i) + { + array[i] = array[i + count]; + } + + array.length = newLength; + }, + + /** + * A standard Fisher-Yates Array shuffle implementation which modifies the array in place. + * + * @method Phaser.ArrayUtils.shuffle + * @param {any[]} array - The array to shuffle. + * @return {any[]} The original array, now shuffled. + */ + shuffle: function (array) { + + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; + + }, + + /** + * Transposes the elements of the given matrix (array of arrays). + * + * @method Phaser.ArrayUtils.transposeMatrix + * @param {Array} array - The matrix to transpose. + * @return {Array} A new transposed matrix + */ + transposeMatrix: function (array) { + + var sourceRowCount = array.length; + var sourceColCount = array[0].length; + + var result = new Array(sourceColCount); + + for (var i = 0; i < sourceColCount; i++) + { + result[i] = new Array(sourceRowCount); + + for (var j = sourceRowCount - 1; j > -1; j--) + { + result[i][j] = array[j][i]; + } + } + + return result; + + }, + + /** + * Rotates the given matrix (array of arrays). + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @method Phaser.ArrayUtils.rotateMatrix + * @param {Array} matrix - The array to rotate; this matrix _may_ be altered. + * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). + * @return {Array} The rotated matrix. The source matrix should be discarded for the returned matrix. + */ + rotateMatrix: function (matrix, direction) { + + if (typeof direction !== 'string') + { + direction = ((direction % 360) + 360) % 360; + } + + if (direction === 90 || direction === -270 || direction === 'rotateLeft') + { + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + matrix = matrix.reverse(); + } + else if (direction === -90 || direction === 270 || direction === 'rotateRight') + { + matrix = matrix.reverse(); + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + } + else if (Math.abs(direction) === 180 || direction === 'rotate180') + { + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + matrix = matrix.reverse(); + } + + return matrix; + + }, + + /** + * Snaps a value to the nearest value in a sorted numeric array. + * The result will always be in the range `[first_value, last_value]`. + * + * @method Phaser.ArrayUtils.findClosest + * @param {number} value - The search value + * @param {number[]} arr - The input array which _must_ be sorted. + * @return {number} The nearest value found. + */ + findClosest: function (value, arr) { + + if (!arr.length) + { + return NaN; + } + else if (arr.length === 1 || value < arr[0]) + { + return arr[0]; + } + + var i = 1; + while (arr[i] < value) { + i++; + } + + var low = arr[i - 1]; + var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; + + return ((high - value) <= (value - low)) ? high : low; + + }, + + /** + * Moves the element from the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ F, A, B, C, D, E ]` + * + * See also Phaser.ArrayUtils.rotateLeft. + * + * @method Phaser.ArrayUtils.rotateRight + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The shifted value. + */ + rotateRight: function (array) { + + var s = array.pop(); + array.unshift(s); + + return s; + + }, + + /** + * Moves the element from the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ B, C, D, E, F, A ]` + * + * See also Phaser.ArrayUtils.rotateRight + * + * @method Phaser.ArrayUtils.rotateLeft + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The rotated value. + */ + rotateLeft: function (array) { + + var s = array.shift(); + array.push(s); + + return s; + + }, + + /** + * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]` (or `[0, start]`, if `end` is omitted). + * This is equivalent to `numberArrayStep(start, 1 + end, 1)`. + * + * When exactly one argument is passed, it's used as `end` and 0 is used as `start`. The length of the result is (1 + end). + * + * ##### Examples + * + * ```javascript + * numberArray(3); // -> [0, 1, 2, 3] + * numberArray(0, 3); // -> [0, 1, 2, 3] + * numberArray(1, 3); // -> [1, 2, 3] + * ``` + * + * @method Phaser.ArrayUtils.numberArray + * @param {number} start - The minimum value the array starts with. + * @param {number} [end] - The maximum value the array contains. + * @return {number[]} The array of number values. + */ + numberArray: function (start, end) { + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + var result = []; + + for (var i = start; i <= end; i++) + { + result.push(i); + } + + return result; + + }, + + /** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @method Phaser.ArrayUtils.numberArrayStep + * @param {number} start - The start of the range. + * @param {number} [end] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * @returns {Array} Returns the new array of numbers. + * @example + * Phaser.ArrayUtils.numberArrayStep(4); + * // => [0, 1, 2, 3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * Phaser.ArrayUtils.numberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * Phaser.ArrayUtils.numberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * Phaser.ArrayUtils.numberArrayStep(0); + * // => [] + */ + numberArrayStep: function (start, end, step) { + + if (start === undefined || start === null) { start = 0; } + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + if (step === undefined) { step = 1; } + + var result = []; + var total = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0); + + for (var i = 0; i < total; i++) + { + result.push(start); + start += step; + } + + return result; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A basic Linked List data structure. +* +* This implementation _modifies_ the `prev` and `next` properties of each item added: +* - The `prev` and `next` properties must be writable and should not be used for any other purpose. +* - Items _cannot_ be added to multiple LinkedLists at the same time. +* - Only objects can be added. +* +* @class Phaser.LinkedList +* @constructor +*/ +Phaser.LinkedList = function () { + + /** + * Next element in the list. + * @property {object} next + * @default + */ + this.next = null; + + /** + * Previous element in the list. + * @property {object} prev + * @default + */ + this.prev = null; + + /** + * First element in the list. + * @property {object} first + * @default + */ + this.first = null; + + /** + * Last element in the list. + * @property {object} last + * @default + */ + this.last = null; + + /** + * Number of elements in the list. + * @property {integer} total + * @default + */ + this.total = 0; + +}; + +Phaser.LinkedList.prototype = { + + /** + * Adds a new element to this linked list. + * + * @method Phaser.LinkedList#add + * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. + * @return {object} The item that was added. + */ + add: function (item) { + + // If the list is empty + if (this.total === 0 && this.first === null && this.last === null) + { + this.first = item; + this.last = item; + this.next = item; + item.prev = this; + this.total++; + return item; + } + + // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list) + this.last.next = item; + + item.prev = this.last; + + this.last = item; + + this.total++; + + return item; + + }, + + /** + * Resets the first, last, next and previous node pointers in this list. + * + * @method Phaser.LinkedList#reset + */ + reset: function () { + + this.first = null; + this.last = null; + this.next = null; + this.prev = null; + this.total = 0; + + }, + + /** + * Removes the given element from this linked list if it exists. + * + * @method Phaser.LinkedList#remove + * @param {object} item - The item to be removed from the list. + */ + remove: function (item) { + + if (this.total === 1) + { + this.reset(); + item.next = item.prev = null; + return; + } + + if (item === this.first) + { + // It was 'first', make 'first' point to first.next + this.first = this.first.next; + } + else if (item === this.last) + { + // It was 'last', make 'last' point to last.prev + this.last = this.last.prev; + } + + if (item.prev) + { + // make item.prev.next point to childs.next instead of item + item.prev.next = item.next; + } + + if (item.next) + { + // make item.next.prev point to item.prev instead of item + item.next.prev = item.prev; + } + + item.next = item.prev = null; + + if (this.first === null ) + { + this.last = null; + } + + this.total--; + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * The function must exist on the member. + * + * @method Phaser.LinkedList#callAll + * @param {function} callback - The function to call. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content +* quickly and easily, without the need for any external files. You can create textures for sprites and in +* coming releases we'll add dynamic sound effect generation support as well (like sfxr). +* +* Access this via `Game.create` (`this.game.create` from within a State object). +* +* @class Phaser.Create +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Create = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.ctx = null; + + /** + * @property {array} palettes - A range of 16 color palettes for use with sprite generation. + */ + this.palettes = [ + { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' }, + { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' }, + { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' } + ]; + +}; + +/** +* A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_ARNE = 0; + +/** +* A 16 color JMP inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JMP = 1; + +/** +* A 16 color CGA inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_CGA = 2; + +/** +* A 16 color C64 inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_C64 = 3; + +/** +* A 16 color palette inspired by Japanese computers like the MSX. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JAPANESE_MACHINE = 4; + +Phaser.Create.prototype = { + + /** + * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite. + * + * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images + * rather than Phaser.Graphics objects, which are expensive to render and limited in scope. + * + * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts. + * + * For example: + * + * `var data = [ + * ' 333 ', + * ' 777 ', + * 'E333E', + * ' 333 ', + * ' 3 3 ' + * ];` + * + * `game.create.texture('bob', data);` + * + * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it + * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');` + * + * Use {@link Phaser.Loader#imageFromTexture} to preload an image of the same. + * + * @method Phaser.Create#texture + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {array} data - An array of pixel data. + * @param {integer} [pixelWidth=8] - The width of each pixel. + * @param {integer} [pixelHeight=8] - The height of each pixel. + * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + texture: function (key, data, pixelWidth, pixelHeight, palette, generateTexture, callback, callbackContext) { + + if (pixelWidth === undefined) { pixelWidth = 8; } + if (pixelHeight === undefined) { pixelHeight = pixelWidth; } + if (palette === undefined) { palette = 0; } + if (generateTexture === undefined) { generateTexture = true; } + + var w = data[0].length * pixelWidth; + var h = data.length * pixelHeight; + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(w, h); + this.bmd.clear(); + + // Draw it + for (var y = 0; y < data.length; y++) + { + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var d = row[x]; + + if (d !== '.' && d !== ' ') + { + this.ctx.fillStyle = this.palettes[palette][d]; + this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); + } + } + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Creates a grid texture based on the given dimensions. + * + * Use {@link Phaser.Loader#imageFromGrid} to preload an image of the same. + * + * @method Phaser.Create#grid + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {integer} width - The width of the grid in pixels. + * @param {integer} height - The height of the grid in pixels. + * @param {integer} cellWidth - The width of the grid cells in pixels. + * @param {integer} cellHeight - The height of the grid cells in pixels. + * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + grid: function (key, width, height, cellWidth, cellHeight, color, generateTexture, callback, callbackContext) { + + if (generateTexture === undefined) { generateTexture = true; } + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(width, height); + + this.ctx.fillStyle = color; + + for (var y = 0; y < height; y += cellHeight) + { + this.ctx.fillRect(0, y, width, 1); + } + + for (var x = 0; x < width; x += cellWidth) + { + this.ctx.fillRect(x, 0, 1, height); + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Copies the contents of {@link bmd Create's canvas} to the given BitmapData object, or a new BitmapData object. + * + * @param {Phaser.BitmapData} [dest] - The BitmapData receiving the copied image. + * @param {number} [x=0] - The x coordinate to translate to before drawing. + * @param {number} [y=0] - The y coordinate to translate to before drawing. + * @param {number} [width] - The new width of the Sprite being copied. + * @param {number} [height] - The new height of the Sprite being copied. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} - The `dest` argument (if passed), or a new BitmapData object + */ + copy: function (dest, x, y, width, height, blendMode, roundPx) { + + if (dest == null) { dest = this.game.make.bitmapData(); } + + dest.resize(this.bmd.width, this.bmd.height); + + return dest.draw(this.bmd, x, y, width, height, blendMode, roundPx); + + } + +}; + +Phaser.Create.prototype.constructor = Phaser.Create; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers +* to provide for game object positioning in a responsive manner. +* +* @class Phaser.FlexGrid +* @constructor +* @param {Phaser.ScaleManager} manager - The ScaleManager. +* @param {number} width - The width of the game. +* @param {number} height - The height of the game. +*/ +Phaser.FlexGrid = function (manager, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = manager.game; + + /** + * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager. + */ + this.manager = manager; + + // The perfect dimensions on which everything else is based + this.width = width; + this.height = height; + + this.boundsCustom = new Phaser.Rectangle(0, 0, width, height); + this.boundsFluid = new Phaser.Rectangle(0, 0, width, height); + this.boundsFull = new Phaser.Rectangle(0, 0, width, height); + this.boundsNone = new Phaser.Rectangle(0, 0, width, height); + + /** + * @property {Phaser.Point} position - + * @readonly + */ + this.positionCustom = new Phaser.Point(0, 0); + this.positionFluid = new Phaser.Point(0, 0); + this.positionFull = new Phaser.Point(0, 0); + this.positionNone = new Phaser.Point(0, 0); + + /** + * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. + * @readonly + */ + this.scaleCustom = new Phaser.Point(1, 1); + this.scaleFluid = new Phaser.Point(1, 1); + this.scaleFluidInversed = new Phaser.Point(1, 1); + this.scaleFull = new Phaser.Point(1, 1); + this.scaleNone = new Phaser.Point(1, 1); + + this.customWidth = 0; + this.customHeight = 0; + this.customOffsetX = 0; + this.customOffsetY = 0; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.multiplier = 0; + + this.layers = []; + +}; + +Phaser.FlexGrid.prototype = { + + /** + * Sets the core game size. This resets the w/h parameters and bounds. + * + * @method Phaser.FlexGrid#setSize + * @param {number} width - The new dimensions. + * @param {number} height - The new dimensions. + */ + setSize: function (width, height) { + + // These are locked and don't change until setSize is called again + this.width = width; + this.height = height; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.scaleNone = new Phaser.Point(1, 1); + + this.boundsNone.width = this.width; + this.boundsNone.height = this.height; + + this.refresh(); + + }, + + // Need ability to create your own layers with custom scaling, etc. + + /** + * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createCustomLayer + * @param {number} width - Width of this layer in pixels. + * @param {number} height - Height of this layer in pixels. + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createCustomLayer: function (width, height, children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + this.customWidth = width; + this.customHeight = height; + + this.boundsCustom.width = width; + this.boundsCustom.height = height; + + var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createFluidLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFluidLayer: function (children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios. + * + * @method Phaser.FlexGrid#createFullLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFullLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled. + * + * @method Phaser.FlexGrid#createFixedLayer + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFixedLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * Resets the layer children references + * + * @method Phaser.FlexGrid#reset + */ + reset: function () { + + var i = this.layers.length; + + while (i--) + { + if (!this.layers[i].persist) + { + // Remove references to this class + this.layers[i].position = null; + this.layers[i].scale = null; + this.layers.slice(i, 1); + } + } + + }, + + /** + * Called when the game container changes dimensions. + * + * @method Phaser.FlexGrid#onResize + * @param {number} width - The new width of the game container. + * @param {number} height - The new height of the game container. + */ + onResize: function (width, height) { + + this.ratioH = width / height; + this.ratioV = height / width; + + this.refresh(width, height); + + }, + + /** + * Updates all internal vars such as the bounds and scale values. + * + * @method Phaser.FlexGrid#refresh + */ + refresh: function () { + + this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width)); + + this.boundsFluid.width = Math.round(this.width * this.multiplier); + this.boundsFluid.height = Math.round(this.height * this.multiplier); + + this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height); + this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height); + + this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height); + + this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x); + this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y); + + this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + + this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y); + this.positionNone.set(this.boundsNone.x, this.boundsNone.y); + + }, + + /** + * Fits a sprites width to the bounds. + * + * @method Phaser.FlexGrid#fitSprite + * @param {Phaser.Sprite} sprite - The Sprite to fit. + */ + fitSprite: function (sprite) { + + this.manager.scaleSprite(sprite); + + sprite.x = this.manager.bounds.centerX; + sprite.y = this.manager.bounds.centerY; + + }, + + /** + * Call in the render function to output the bounds rects. + * + * @method Phaser.FlexGrid#debug + */ + debug: function () { + + // for (var i = 0; i < this.layers.length; i++) + // { + // this.layers[i].debug(); + // } + + // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16); + // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false); + + this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16); + this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false); + + // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16); + // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false); + + // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16); + // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false); + + } + +}; + +Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* A responsive grid layer. +* +* @class Phaser.FlexLayer +* @extends Phaser.Group +* @constructor +* @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer. +* @param {Phaser.Point} position - A reference to the Point object used for positioning. +* @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds. +* @param {Phaser.Point} scale - A reference to the Point object used for layer scaling. +*/ +Phaser.FlexLayer = function (manager, position, bounds, scale) { + + Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false); + + /** + * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager. + */ + this.manager = manager.manager; + + /** + * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer. + */ + this.grid = manager; + + /** + * Should the FlexLayer remain through a State swap? + * + * @type {boolean} + */ + this.persist = false; + + /** + * @property {Phaser.Point} position + */ + this.position = position; + + /** + * @property {Phaser.Rectangle} bounds + */ + this.bounds = bounds; + + /** + * @property {Phaser.Point} scale + */ + this.scale = scale; + + /** + * @property {Phaser.Point} topLeft + */ + this.topLeft = bounds.topLeft; + + /** + * @property {Phaser.Point} topMiddle + */ + this.topMiddle = new Phaser.Point(bounds.halfWidth, 0); + + /** + * @property {Phaser.Point} topRight + */ + this.topRight = bounds.topRight; + + /** + * @property {Phaser.Point} bottomLeft + */ + this.bottomLeft = bounds.bottomLeft; + + /** + * @property {Phaser.Point} bottomMiddle + */ + this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom); + + /** + * @property {Phaser.Point} bottomRight + */ + this.bottomRight = bounds.bottomRight; + +}; + +Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype); +Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer; + +/** + * Resize. + * + * @method Phaser.FlexLayer#resize + */ +Phaser.FlexLayer.prototype.resize = function () { +}; + +/** + * Debug. + * + * @method Phaser.FlexLayer#debug + */ +Phaser.FlexLayer.prototype.debug = function () { + + this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16); + this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false); + + this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9'); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. +* +* @class Phaser.Color +*/ +Phaser.Color = { + + /** + * Red (0xff0000) + * + * @type number + * @constant + * @default + */ + RED: 0xff0000, + + /** + * Orange (0xff9900) + * + * @type number + * @constant + * @default + */ + ORANGE: 0xff9900, + + /** + * Yellow (0xffff00) + * + * @type number + * @constant + * @default + */ + YELLOW: 0xffff00, + + /** + * Green (0x00ff00) + * + * @type number + * @constant + * @default + */ + GREEN: 0x00ff00, + + /** + * Aqua (0x00ffff) + * + * @type number + * @constant + * @default + */ + AQUA: 0x00ffff, + + /** + * Blue (0x0000ff) + * + * @type number + * @constant + * @default + */ + BLUE: 0x0000ff, + + /** + * Violet/purple (0xff00ff) + * + * @type number + * @constant + * @default + */ + VIOLET: 0xff00ff, + + /** + * White (0xffffff) + * + * @type number + * @constant + * @default + */ + WHITE: 0xffffff, + + /** + * Black (0x000000) + * + * @type number + * @constant + * @default + */ + BLACK: 0, + + /** + * Gray (0x666666) + * + * @type number + * @constant + * @default + */ + GRAY: 0x666666, + + /** + * Packs the r, g, b, a components into a single integer, for use with Int32Array. + * If device is little endian then ABGR order is used. Otherwise RGBA order is used. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.packPixel + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} The packed color as uint32 + */ + packPixel: function (r, g, b, a) { + + if (Phaser.Device.LITTLE_ENDIAN) + { + return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0; + } + else + { + return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0; + } + + }, + + /** + * Unpacks the r, g, b, a components into the specified color object, or a new + * object, for use with Int32Array. If little endian, then ABGR order is used when + * unpacking, otherwise, RGBA order is used. The resulting color object has the + * `r, g, b, a` properties which are unrelated to endianness. + * + * Note that the integer is assumed to be packed in the correct endianness. On little-endian + * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a + * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.unpackPixel + * @static + * @param {number} rgba - The integer, packed in endian order by packPixel. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + unpackPixel: function (rgba, out, hsl, hsv) { + + if (out === undefined || out === null) { out = Phaser.Color.createColor(); } + if (hsl === undefined || hsl === null) { hsl = false; } + if (hsv === undefined || hsv === null) { hsv = false; } + + if (Phaser.Device.LITTLE_ENDIAN) + { + out.a = ((rgba & 0xff000000) >>> 24); + out.b = ((rgba & 0x00ff0000) >>> 16); + out.g = ((rgba & 0x0000ff00) >>> 8); + out.r = ((rgba & 0x000000ff)); + } + else + { + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + } + + 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; + + }, + + /** + * A utility to convert an integer in 0xRRGGBBAA format to a color object. + * This does not rely on endianness. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.fromRGBA + * @static + * @param {number} rgba - An RGBA hex + * @param {object} [out] - The object to use, optional. + * @return {object} A color object. + */ + fromRGBA: function (rgba, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + + out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')'; + + return out; + + }, + + /** + * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.toRGBA + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toRGBA: function (r, g, b, a) { + + return (r << 24) | (g << 16) | (b << 8) | a; + + }, + + /** + * Converts RGBA components to a 32 bit integer in AABBGGRR format. + * + * @method Phaser.Color.toABGR + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toABGR: function (r, g, b, a) { + + return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; + + }, + + /** + * Converts a hex color value to an [R, G, B] array. + * + * @static + * @method Phaser.Color.hexToRGBArray + * @param {number} color - The color to convert to an RGB array. In the format 0xRRGGBB. + * @return {array} An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + */ + hexToRGBArray: function (color) { + + return [ + (color >> 16 & 0xFF) / 255, + (color >> 8 & 0xFF) / 255, + (color & 0xFF) / 255 + ]; + + }, + + /** + * Converts an RGB color array, in the format: [R, G, B], to a hex color value. + * + * @static + * @method Phaser.Color.RGBArrayToHex + * @param {array} rgb - An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + * @return {number} The color value, in the format 0xRRGGBB. + */ + RGBArrayToHex: function (rgb) { + + return ((rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255); + + }, + + /** + * Converts an RGB color value to HSL (hue, saturation and lightness). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSL + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. + */ + 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); + + // achromatic by default + out.h = 0; + out.s = 0; + out.l = (max + min) / 2; + + if (max !== min) + { + var d = max - min; + + out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min); + + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSL (hue, saturation and lightness) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSLtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} l - The lightness, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSLtoRGB: function (h, s, l, out) { + + if (!out) + { + out = Phaser.Color.createColor(l, l, l); + } + else + { + // achromatic by default + out.r = l; + out.g = l; + out.b = l; + } + + if (s !== 0) + { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3); + out.g = Phaser.Color.hueToColor(p, q, h); + out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3); + } + + // out.r = (out.r * 255 | 0); + // out.g = (out.g * 255 | 0); + // out.b = (out.b * 255 | 0); + + out.r = Math.floor((out.r * 255 | 0)); + out.g = Math.floor((out.g * 255 | 0)); + out.b = Math.floor((out.b * 255 | 0)); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts an RGB color value to HSV (hue, saturation and value). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSV + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and value set in the h, s and v properties. + */ + RGBtoHSV: function (r, g, b, out) { + + if (!out) + { + out = Phaser.Color.createColor(r, g, b, 255); + } + + r /= 255; + g /= 255; + b /= 255; + + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var d = max - min; + + // achromatic by default + out.h = 0; + out.s = max === 0 ? 0 : d / max; + out.v = max; + + if (max !== min) + { + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSVtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} v - The value, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSVtoRGB: function (h, s, v, out) { + + if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); } + + var r, g, b; + var i = Math.floor(h * 6); + var f = h * 6 - i; + var p = v * (1 - s); + var q = v * (1 - f * s); + var t = v * (1 - (1 - f) * s); + + switch (i % 6) + { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } + + out.r = Math.floor(r * 255); + out.g = Math.floor(g * 255); + out.b = Math.floor(b * 255); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.hueToColor + * @static + * @param {number} p + * @param {number} q + * @param {number} t + * @return {number} The color component value. + */ + hueToColor: function (p, q, t) { + + if (t < 0) + { + t += 1; + } + + if (t > 1) + { + t -= 1; + } + + if (t < 1 / 6) + { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) + { + return q; + } + + if (t < 2 / 3) + { + return p + (q - p) * (2 / 3 - t) * 6; + } + + return p; + + }, + + /** + * A utility function to create a lightweight 'color' object with the default components. + * Any components that are not specified will default to zero. + * + * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.createColor + * @static + * @param {number} [r=0] - The red color component, in the range 0 - 255. + * @param {number} [g=0] - The green color component, in the range 0 - 255. + * @param {number} [b=0] - The blue color component, in the range 0 - 255. + * @param {number} [a=1] - The alpha color component, in the range 0 - 1. + * @param {number} [h=0] - The hue, in the range 0 - 1. + * @param {number} [s=0] - The saturation, in the range 0 - 1. + * @param {number} [l=0] - The lightness, in the range 0 - 1. + * @param {number} [v=0] - The value, in the range 0 - 1. + * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. + */ + 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, color32: 0, rgba: '' }; + + return Phaser.Color.updateColor(out); + + }, + + /** + * Takes a color object and updates the rgba, color and color32 properties. + * + * @method Phaser.Color.updateColor + * @static + * @param {object} out - The color object to update. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + updateColor: function (out) { + + out.rgba = 'rgba(' + out.r.toFixed() + ',' + out.g.toFixed() + ',' + out.b.toFixed() + ',' + out.a.toString() + ')'; + out.color = Phaser.Color.getColor(out.r, out.g, out.b); + out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b); + + return out; + + }, + + /** + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor32 + * @static + * @param {number} a - The alpha color component, in the range 0 - 255. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + getColor32: function (a, r, g, b) { + + return a << 24 | r << 16 | g << 8 | b; + + }, + + /** + * Given 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xRRGGBB). + */ + getColor: function (r, g, b) { + + return r << 16 | g << 8 | b; + + }, + + /** + * Converts the given color values into a string. + * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + * + * @method Phaser.Color.RGBtoString + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255. + * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. + * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + */ + RGBtoString: function (r, g, b, a, prefix) { + + if (a === undefined) { a = 255; } + if (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); + } + + }, + + /** + * Converts a hex string into an integer color value. + * + * @method Phaser.Color.hexToRGB + * @static + * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. + * @return {number} The rgb color value in the format 0xAARRGGBB. + */ + hexToRGB: function (hex) { + + var rgb = Phaser.Color.hexToColor(hex); + + if (rgb) + { + return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b); + } + + }, + + /** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @method Phaser.Color.hexToColor + * @static + * @param {string} hex - The color string in a hex format. + * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + hexToColor: function (hex, out) { + + // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") + hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { + return r + r + g + g + b + b; + }); + + var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + + if (result) + { + var r = parseInt(result[1], 16); + var g = parseInt(result[2], 16); + var b = parseInt(result[3], 16); + + if (!out) + { + out = Phaser.Color.createColor(r, g, b); + } + else + { + out.r = r; + out.g = g; + out.b = b; + } + } + + return out; + + }, + + /** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @method Phaser.Color.webToColor + * @static + * @param {string} web - The color string in CSS 'web' format. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + webToColor: function (web, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web); + + if (result) + { + out.r = ~~Number(result[1]); + out.g = ~~Number(result[2]); + out.b = ~~Number(result[3]); + out.a = result[4] !== undefined ? Number(result[4]) : 1; + Phaser.Color.updateColor(out); + } + + return out; + + }, + + /** + * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. + * + * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). + * + * An alpha channel is _not_ supported when specifying a hex string. + * + * @method Phaser.Color.valueToColor + * @static + * @param {string|number} value - The color expressed as a recognized string format or a packed integer. + * @param {object} [out] - The object to use for the output. If not provided a new object will be created. + * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. + */ + valueToColor: function (value, out) { + + // The behavior is not consistent between hexToColor/webToColor on invalid input. + // This unifies both by returning a new object, but returning null may be better. + if (!out) + { + out = Phaser.Color.createColor(); + } + + if (typeof value === 'string') + { + if (value.indexOf('rgb') === 0) + { + return Phaser.Color.webToColor(value, out); + } + else + { + // `hexToColor` does not support alpha; match `createColor`. + out.a = 1; + return Phaser.Color.hexToColor(value, out); + } + } + else if (typeof value === 'number') + { + // `getRGB` does not take optional object to modify; + // alpha is also adjusted to match `createColor`. + var tempColor = Phaser.Color.getRGB(value); + out.r = tempColor.r; + out.g = tempColor.g; + out.b = tempColor.b; + out.a = tempColor.a / 255; + return out; + } + else + { + return out; + } + + }, + + /** + * Return a string containing a hex representation of the given color component. + * + * @method Phaser.Color.componentToHex + * @static + * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. + * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ + componentToHex: function (color) { + + var hex = color.toString(16); + + return (hex.length === 1) ? '0' + hex : hex; + + }, + + /** + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSVColorWheel + * @static + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSV color wheel. + */ + HSVColorWheel: function (s, v) { + + if (s === undefined) { s = 1.0; } + if (v === undefined) { v = 1.0; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v)); + } + + return colors; + + }, + + /** + * Get HSL color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSLColorWheel + * @static + * @param {number} [s=0.5] - The saturation, in the range 0 - 1. + * @param {number} [l=0.5] - The lightness, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSL color wheel. + */ + HSLColorWheel: function (s, l) { + + if (s === undefined) { s = 0.5; } + if (l === undefined) { l = 0.5; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l)); + } + + return colors; + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColor + * @static + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @param {number} [alpha] - The alpha of the returned color. + * @param {number} [colorSpace=0] - The color space to interpolate in. 0 = RGB, 1 = HSV. + * @returns {number} The interpolated color value. + */ + interpolateColor: function (color1, color2, steps, currentStep, alpha, colorSpace) { + + if (alpha === undefined) { alpha = 255; } + if (colorSpace === undefined) { colorSpace = 0; } + + var src1 = Phaser.Color.getRGB(color1); + var src2 = Phaser.Color.getRGB(color2); + + if (colorSpace === 0) + { + 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; + } + + if (colorSpace === 1) + { + var hsv1 = Phaser.Color.RGBtoHSV(src1.r, src1.g, src1.b); + var hsv2 = Phaser.Color.RGBtoHSV(src2.r, src2.g, src2.b); + var dh = hsv2.h - hsv1.h; + var h; + + if (hsv1.h > hsv2.h) + { + var h3 = hsv2.h; + hsv2.h = hsv1.h; + hsv1.h = h3; + dh = -dh; + currentStep = steps - currentStep; + } + + if (dh > 0.5) + { + hsv1.h = hsv1.h + 1; + h = (((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h) % 1; + } + + if (dh <= 0.5) + { + h = ((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h; + } + + var s = (((hsv2.s - hsv1.s) * currentStep) / steps) + hsv1.s; + var v = (((hsv2.v - hsv1.v) * currentStep) / steps) + hsv1.v; + + var rgb = Phaser.Color.HSVtoRGB(h, s, v, rgb); + var r = rgb.r; + var g = rgb.g; + var b = rgb.b; + } + + return Phaser.Color.getColor32(alpha, r, g, b); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColorWithRGB + * @static + * @param {number} color - The first color value. + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * @method Phaser.Color.interpolateRGB + * @static + * @param {number} r1 - The red color value, between 0 and 0xFF (255). + * @param {number} g1 - The green color value, between 0 and 0xFF (255). + * @param {number} b1 - The blue color value, between 0 and 0xFF (255). + * @param {number} r2 - The red color value, between 0 and 0xFF (255). + * @param {number} g2 - The green color value, between 0 and 0xFF (255). + * @param {number} b2 - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + + /** + * Calculates a linear (interpolation) value of two colors over t. + * + * This is a slightly simpler interface to {@link Phaser.Color.interpolateColor}. + * + * The arguments are similar to {@link Phaser.Math.linear}. + * + * @method Phaser.Color.linear + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linear: function (color1, color2, t) { + + return this.interpolateColor(color1, color2, 1, t); + + }, + + /** + * Calculates a linear (interpolation) value of an array of colors over t. + * + * The arguments are similar to {@link Phaser.Math.linearInterpolation}. + * + * This can be used as a {@link Phaser.TweenData#interpolationFunction}. + * + * @method Phaser.Color.linearInterpolation + * @param {number[]} colors - The input array of color values to interpolate between. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linearInterpolation: function (colors, t) { + + var k = Phaser.Math.linear(0, colors.length - 1, t); + var color1 = colors[ Math.floor(k) ]; + var color2 = colors[ Math.ceil(k)] ; + + return this.linear(color1, color2, k % 1); + + }, + + /** + * Returns a random color value between black and white + * Set the min value to start each channel from the given offset. + * Set the max value to restrict the maximum color used per channel. + * + * @method Phaser.Color.getRandomColor + * @static + * @param {number} [min=0] - The lowest value to use for the color. + * @param {number} [max=255] - The highest value to use for the color. + * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). + * @returns {number} 32-bit color value with alpha. + */ + getRandomColor: function (min, max, alpha) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + if (alpha === undefined) { alpha = 255; } + + // Sanity checks + 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); + + }, + + /** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exist in the given color (0xAARRGGBB) + * + * @method Phaser.Color.getRGB + * @static + * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). + * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. + */ + getRGB: function (color) { + + if (color > 16777215) + { + // The color value has an alpha component + return { + alpha: color >>> 24, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: color >>> 24, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + else + { + return { + alpha: 255, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: 255, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + + }, + + /** + * Returns a CSS friendly string value from the given color. + * + * @method Phaser.Color.getWebRGB + * @static + * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. + * @returns {string} A string in the format: 'rgba(r,g,b,a)' + */ + getWebRGB: function (color) { + + if (typeof color === 'object') + { + return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')'; + } + else + { + var rgb = Phaser.Color.getRGB(color); + return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')'; + } + + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. + * + * @method Phaser.Color.getAlpha + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlpha: function (color) { + return color >>> 24; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. + * + * @method Phaser.Color.getAlphaFloat + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlphaFloat: function (color) { + return (color >>> 24) / 255; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. + * + * @method Phaser.Color.getRed + * @static + * @param {number} color In the format 0xAARRGGBB. + * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). + */ + getRed: function (color) { + return color >> 16 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. + * + * @method Phaser.Color.getGreen + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). + */ + getGreen: function (color) { + return color >> 8 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. + * + * @method Phaser.Color.getBlue + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). + */ + getBlue: function (color) { + return color & 0xFF; + }, + + /** + * Blends the source color, ignoring the backdrop. + * + * @method Phaser.Color.blendNormal + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNormal: function (a) { + return a; + }, + + /** + * Selects the lighter of the backdrop and source colors. + * + * @method Phaser.Color.blendLighten + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLighten: function (a, b) { + return (b > a) ? b : a; + }, + + /** + * Selects the darker of the backdrop and source colors. + * + * @method Phaser.Color.blendDarken + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDarken: function (a, b) { + return (b > a) ? a : b; + }, + + /** + * Multiplies the backdrop and source color values. + * The result color is always at least as dark as either of the two constituent + * colors. Multiplying any color with black produces black; + * multiplying with white leaves the original color unchanged. + * + * @method Phaser.Color.blendMultiply + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendMultiply: function (a, b) { + return (a * b) / 255; + }, + + /** + * Takes the average of the source and backdrop colors. + * + * @method Phaser.Color.blendAverage + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAverage: function (a, b) { + return (a + b) / 2; + }, + + /** + * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. + * + * @method Phaser.Color.blendAdd + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAdd: function (a, b) { + return Math.min(255, a + b); + }, + + /** + * Combines the source and backdrop colors and returns their value minus 255. + * + * @method Phaser.Color.blendSubtract + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSubtract: function (a, b) { + return Math.max(0, a + b - 255); + }, + + /** + * Subtracts the darker of the two constituent colors from the lighter. + * + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendDifference + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDifference: function (a, b) { + return Math.abs(a - b); + }, + + /** + * Negation blend mode. + * + * @method Phaser.Color.blendNegation + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNegation: function (a, b) { + return 255 - Math.abs(255 - a - b); + }, + + /** + * Multiplies the complements of the backdrop and source color values, then complements the result. + * The result color is always at least as light as either of the two constituent colors. + * Screening any color with white produces white; screening with black leaves the original color unchanged. + * + * @method Phaser.Color.blendScreen + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendScreen: function (a, b) { + return 255 - (((255 - a) * (255 - b)) >> 8); + }, + + /** + * Produces an effect similar to that of the Difference mode, but lower in contrast. + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendExclusion + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendExclusion: function (a, b) { + return a + b - 2 * a * b / 255; + }, + + /** + * Multiplies or screens the colors, depending on the backdrop color. + * Source colors overlay the backdrop while preserving its highlights and shadows. + * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. + * + * @method Phaser.Color.blendOverlay + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendOverlay: function (a, b) { + return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255); + }, + + /** + * Darkens or lightens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. + * The effect is similar to shining a diffused spotlight on the backdrop. + * + * @method Phaser.Color.blendSoftLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSoftLight: function (a, b) { + return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255); + }, + + /** + * Multiplies or screens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; + * this is useful for adding shadows to a scene. + * + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. + * + * @method Phaser.Color.blendHardLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardLight: function (a, b) { + return Phaser.Color.blendOverlay(b, a); + }, + + /** + * Brightens the backdrop color to reflect the source color. + * Painting with black produces no change. + * + * @method Phaser.Color.blendColorDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorDodge: function (a, b) { + return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b))); + }, + + /** + * Darkens the backdrop color to reflect the source color. + * Painting with white produces no change. + * + * @method Phaser.Color.blendColorBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorBurn: function (a, b) { + return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b)); + }, + + /** + * An alias for blendAdd, it simply sums the values of the two colors. + * + * @method Phaser.Color.blendLinearDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearDodge: function (a, b) { + return Phaser.Color.blendAdd(a, b); + }, + + /** + * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. + * + * @method Phaser.Color.blendLinearBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearBurn: function (a, b) { + return Phaser.Color.blendSubtract(a, b); + }, + + /** + * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). + * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. + * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. + * + * @method Phaser.Color.blendLinearLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearLight: function (a, b) { + return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128))); + }, + + /** + * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). + * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. + * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom + * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. + * + * @method Phaser.Color.blendVividLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendVividLight: function (a, b) { + return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128))); + }, + + /** + * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. + * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. + * + * @method Phaser.Color.blendPinLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPinLight: function (a, b) { + return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128))); + }, + + /** + * Runs blendVividLight on the source and backdrop colors. + * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. + * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. + * This changes all pixels to primary additive colors (red, green, or blue), white, or black. + * + * @method Phaser.Color.blendHardMix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardMix: function (a, b) { + return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255; + }, + + /** + * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. + * + * @method Phaser.Color.blendReflect + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendReflect: function (a, b) { + return b === 255 ? b : Math.min(255, (a * a / (255 - b))); + }, + + /** + * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. + * + * @method Phaser.Color.blendGlow + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendGlow: function (a, b) { + return Phaser.Color.blendReflect(b, a); + }, + + /** + * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. + * + * @method Phaser.Color.blendPhoenix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPhoenix: function (a, b) { + return Math.min(a, b) - Math.max(a, b) + 255; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Manager is responsible for looking after all of the running physics systems. +* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. +* +* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. +* +* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the +* faster (due to being much simpler) Arcade Physics system. +* +* @class Phaser.Physics +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Physics = function (game, config) { + + config = config || {}; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} config - The physics configuration object as passed to the game on creation. + */ + this.config = config; + + /** + * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. + */ + this.arcade = null; + + /** + * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. + */ + this.p2 = null; + + /** + * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. + */ + this.ninja = null; + + /** + * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. + */ + this.box2d = null; + + /** + * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). + */ + this.chipmunk = null; + + /** + * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). + */ + this.matter = null; + + this.parseConfig(); + +}; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.ARCADE = 0; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.P2JS = 1; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.NINJA = 2; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.BOX2D = 3; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.CHIPMUNK = 4; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.MATTERJS = 5; + +Phaser.Physics.prototype = { + + /** + * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. + * + * @method Phaser.Physics#parseConfig + */ + parseConfig: function () { + + if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade')) + { + // If Arcade isn't specified, we create it automatically if we can + this.arcade = new Phaser.Physics.Arcade(this.game); + } + + 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); + } + + if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D')) + { + this.box2d = new Phaser.Physics.BOX2D(this.game, this.config); + } + + if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter')) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + + }, + + /** + * This will create an instance of the requested physics simulation. + * Phaser.Physics.Arcade is running by default, but all others need activating directly. + * + * You can start the following physics systems: + * + * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. + * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) + * + * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. + * They are not bundled into the core Phaser library. + * + * If the physics world has already been created (i.e. in another state in your game) then + * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors + * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. + * + * @method Phaser.Physics#startSystem + * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. + */ + startSystem: function (system) { + + if (system === Phaser.Physics.ARCADE) + { + this.arcade = new Phaser.Physics.Arcade(this.game); + } + else if (system === Phaser.Physics.P2JS) + { + if (this.p2 === null) + { + this.p2 = new Phaser.Physics.P2(this.game, this.config); + } + else + { + this.p2.reset(); + } + } + else if (system === Phaser.Physics.NINJA) + { + this.ninja = new Phaser.Physics.Ninja(this.game); + } + else if (system === Phaser.Physics.BOX2D) + { + if (this.box2d === null) + { + this.box2d = new Phaser.Physics.Box2D(this.game, this.config); + } + else + { + this.box2d.reset(); + } + } + else if (system === Phaser.Physics.MATTERJS) + { + if (this.matter === null) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + else + { + this.matter.reset(); + } + } + + }, + + /** + * This will create a default physics body on the given game object or array of objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * It can be for any of the physics systems that have been started: + * + * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. + * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. + * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 + * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) + * Phaser.Physics.CHIPMUNK is still in development. + * + * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the + * individual physics systems `enable` methods instead of using this generic one. + * + * @method Phaser.Physics#enable + * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. + * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. + * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. + */ + enable: function (object, system, debug) { + + if (system === undefined) { system = Phaser.Physics.ARCADE; } + if (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); + } + else if (system === Phaser.Physics.BOX2D && this.box2d) + { + this.box2d.enable(object); + } + else if (system === Phaser.Physics.MATTERJS && this.matter) + { + this.matter.enable(object); + } + else + { + console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.'); + } + + }, + + /** + * preUpdate checks. + * + * @method Phaser.Physics#preUpdate + * @protected + */ + preUpdate: function () { + + // ArcadePhysics / Ninja don't have a core to preUpdate + + if (this.p2) + { + this.p2.preUpdate(); + } + + if (this.box2d) + { + this.box2d.preUpdate(); + } + + if (this.matter) + { + this.matter.preUpdate(); + } + + }, + + /** + * Updates all running physics systems. + * + * @method Phaser.Physics#update + * @protected + */ + update: function () { + + // ArcadePhysics / Ninja don't have a core to update + + if (this.p2) + { + this.p2.update(); + } + + if (this.box2d) + { + this.box2d.update(); + } + + if (this.matter) + { + this.matter.update(); + } + + }, + + /** + * Updates the physics bounds to match the world dimensions. + * + * @method Phaser.Physics#setBoundsToWorld + * @protected + */ + setBoundsToWorld: function () { + + if (this.arcade) + { + this.arcade.setBoundsToWorld(); + } + + if (this.ninja) + { + this.ninja.setBoundsToWorld(); + } + + if (this.p2) + { + this.p2.setBoundsToWorld(); + } + + if (this.box2d) + { + this.box2d.setBoundsToWorld(); + } + + if (this.matter) + { + this.matter.setBoundsToWorld(); + } + + }, + + /** + * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. + * + * @method Phaser.Physics#clear + * @protected + */ + clear: function () { + + if (this.p2) + { + this.p2.clear(); + } + + if (this.box2d) + { + this.box2d.clear(); + } + + if (this.matter) + { + this.matter.clear(); + } + + }, + + /** + * Resets the active physics system. Called automatically on a Phaser.State swap. + * + * @method Phaser.Physics#reset + * @protected + */ + reset: function () { + + if (this.p2) + { + this.p2.reset(); + } + + if (this.box2d) + { + this.box2d.reset(); + } + + if (this.matter) + { + this.matter.reset(); + } + + }, + + /** + * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. + * + * @method Phaser.Physics#destroy + */ + destroy: function () { + + if (this.p2) + { + this.p2.destroy(); + } + + if (this.box2d) + { + this.box2d.destroy(); + } + + if (this.matter) + { + this.matter.destroy(); + } + + this.arcade = null; + this.ninja = null; + this.p2 = null; + this.box2d = null; + this.matter = null; + + } + +}; + +Phaser.Physics.prototype.constructor = Phaser.Physics; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. +* +* @class Phaser.Physics.Arcade +* @constructor +* @param {Phaser.Game} game - reference to the current game instance. +*/ +Phaser.Physics.Arcade = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height); + + /** + * Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`. + * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. + * @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right). + */ + this.checkCollision = { up: true, down: true, left: true, right: true }; + + /** + * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. + */ + this.maxLevels = 4; + + /** + * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. + * @default + */ + this.OVERLAP_BIAS = 4; + + /** + * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. + */ + this.forceX = false; + + /** + * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT. + * @default + */ + this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT; + + /** + * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. + */ + this.skipQuadTree = true; + + /** + * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. + */ + this.isPaused = false; + + /** + * @property {Phaser.QuadTree} quadTree - The world QuadTree. + */ + 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); + + /** + * @property {number} _total - Internal cache var. + * @private + */ + this._total = 0; + + // By default we want the bounds the same size as the world bounds + this.setBoundsToWorld(); + +}; + +Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade; + +/** +* A constant used for the sortDirection value. +* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.SORT_NONE = 0; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.LEFT_RIGHT = 1; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.RIGHT_LEFT = 2; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.TOP_BOTTOM = 3; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.BOTTOM_TOP = 4; + +Phaser.Physics.Arcade.prototype = { + + /** + * Updates the size of this physics world. + * + * @method Phaser.Physics.Arcade#setBounds + * @param {number} x - Top left most corner of the world. + * @param {number} y - Top left most corner of the world. + * @param {number} width - New width of the world. Can never be smaller than the Game.width. + * @param {number} height - New height of the world. Can never be smaller than the Game.height. + */ + setBounds: function (x, y, width, height) { + + this.bounds.setTo(x, y, width, height); + + }, + + /** + * Updates the size of this physics world to match the size of the game world. + * + * @method Phaser.Physics.Arcade#setBoundsToWorld + */ + setBoundsToWorld: function () { + + this.bounds.copyFrom(this.game.world.bounds); + + }, + + /** + * This will create an Arcade Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * + * @method Phaser.Physics.Arcade#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, children) { + + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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) + { + // If it's a Group then we do it on the children regardless + this.enable(object.children, children); + } + else + { + this.enableBody(object); + + if (children && object.hasOwnProperty('children') && object.children.length > 0) + { + this.enable(object.children, true); + } + } + } + + }, + + /** + * Creates an Arcade Physics body on the given game object. + * + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. + * + * @method Phaser.Physics.Arcade#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + */ + enableBody: function (object) { + + if (object.hasOwnProperty('body') && object.body === null) + { + object.body = new Phaser.Physics.Arcade.Body(object); + + if (object.parent && object.parent instanceof Phaser.Group) + { + object.parent.addToHash(object); + } + } + + }, + + /** + * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. + * + * @method Phaser.Physics.Arcade#updateMotion + * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. + */ + updateMotion: function (body) { + + if (body.allowRotation) + { + var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity; + body.angularVelocity += 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); + + }, + + /** + * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * Based on a function in Flixel by @ADAMATOMIC + * + * @method Phaser.Physics.Arcade#computeVelocity + * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical. + * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. + * @param {number} velocity - Any component of velocity (e.g. 20). + * @param {number} acceleration - Rate at which the velocity is changing. + * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. + * @param {number} [max=10000] - An absolute value cap for the velocity. + * @return {number} The altered Velocity value. + */ + computeVelocity: function (axis, body, velocity, acceleration, drag, max) { + + if (max === undefined) { max = 10000; } + + 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 && body.allowDrag) + { + drag *= this.game.time.physicsElapsed; + + if (velocity - drag > 0) + { + velocity -= drag; + } + else if (velocity + drag < 0) + { + velocity += drag; + } + else + { + velocity = 0; + } + } + + if (velocity > max) + { + velocity = max; + } + else if (velocity < -max) + { + velocity = -max; + } + + return velocity; + + }, + + /** + * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. + * + * Unlike {@link #collide} the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. + * Both the first and second parameter can be arrays of objects, of differing types. + * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups within Groups). + * + * ##### Tilemaps + * + * Any overlapping tiles, including blank/null tiles, will give a positive result. Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) have no special status, and callbacks added via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} are not invoked. So calling this method without any callbacks isn't very useful. + * + * If you're interested only in whether an object overlaps a certain tile or class of tiles, filter the tiles with `processCallback` and then use the result returned by this method. Blank/null tiles can be excluded by their {@link Phaser.Tile#index index} (-1). + * + * If you want to take action on certain overlaps, examine the tiles in `collideCallback` and then handle as you like. + * + * @method Phaser.Physics.Arcade#overlap + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if an overlap occurred otherwise false. + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) { + + overlapCallback = overlapCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || overlapCallback; + + this._total = 0; + + this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + + return (this._total > 0); + + }, + + /** + * Checks for collision between two game objects and separates them if colliding ({@link https://gist.github.com/samme/cbb81dd19f564dcfe2232761e575063d details}). If you don't require separation then use {@link #overlap} instead. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. + * Both the `object1` and `object2` can be arrays of objects, of differing types. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If one Group **only** is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If either object is `null` the collision test will fail. + * + * Bodies with `enable = false` and Sprites with `exists = false` are skipped (ignored). + * + * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. + * + * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). + * + * ##### Examples + * + * ```javascript + * collide(group); + * collide(group, undefined); // equivalent + * + * collide(sprite1, sprite2); + * + * collide(sprite, group); + * + * collide(group1, group2); + * + * collide([sprite1, sprite2], [sprite3, sprite4]); // 1 vs. 3, 1 vs. 4, 2 vs. 3, 2 vs. 4 + * ``` + * + * ##### Tilemaps + * + * Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) are "solid". If a Sprite collides with one of these tiles, the two are separated by moving the Sprite outside the tile's edges. Enable {@link Phaser.TilemapLayer#debug} to see the colliding edges of the Tilemap. + * + * Tiles with a callback attached via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} invoke the callback if a Sprite collides with them. If a tile has a callback attached via both methods, only the location callback is invoked. The colliding Sprite is separated from the tile only if the callback returns `true`. + * + * @method Phaser.Physics.Arcade#collide + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. + * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if a collision occurred otherwise false. + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) { + + collideCallback = collideCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || collideCallback; + + this._total = 0; + + this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + + return (this._total > 0); + + }, + + /** + * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortLeftRight + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortLeftRight: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.x - b.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortRightLeft + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortRightLeft: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.x - a.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortTopBottom + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortTopBottom: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.y - b.body.y; + + }, + + /** + * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortBottomTop + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortBottomTop: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.y - a.body.y; + + }, + + /** + * This method will sort a Groups hash array. + * + * If the Group has `physicsSortDirection` set it will use the sort direction defined. + * + * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection. + * + * By changing Group.physicsSortDirection you can customise each Group to sort in a different order. + * + * @method Phaser.Physics.Arcade#sort + * @param {Phaser.Group} group - The Group to sort. + * @param {integer} [sortDirection] - The sort direction used to sort this Group. + */ + sort: function (group, sortDirection) { + + if (group.physicsSortDirection !== null) + { + sortDirection = group.physicsSortDirection; + } + else + { + if (sortDirection === undefined) { sortDirection = this.sortDirection; } + } + + if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + // Game world is say 2000x600 and you start at 0 + group.hash.sort(this.sortLeftRight); + } + else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + // Game world is say 2000x600 and you start at 2000 + group.hash.sort(this.sortRightLeft); + } + else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + // Game world is say 800x2000 and you start at 0 + group.hash.sort(this.sortTopBottom); + } + else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + // Game world is say 800x2000 and you start at 2000 + group.hash.sort(this.sortBottomTop); + } + + }, + + /** + * Internal collision handler. Extracts objects for {@link #collideHandler}. + * + * @method Phaser.Physics.Arcade#collideObjects + * @private + */ + collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object2.length; i++) + { + if (!object2[i]) { continue; } + + this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && !Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + for (var j = 0; j < object2.length; j++) + { + if (!object2[j]) { continue; } + + this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + + }, + + /** + * Internal collision handler. Matches arguments to other handlers. + * + * @method Phaser.Physics.Arcade#collideHandler + * @private + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + // Only collide valid objects + if (object2 === undefined && object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly); + return; + } + + // If neither of the objects are set or exist then bail out + if (!object1 || !object2 || !object1.exists || !object2.exists) + { + return; + } + + // Groups? Sort them + if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE) + { + if (object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + } + + if (object2.physicsType === Phaser.GROUP) + { + this.sort(object2); + } + } + + // SPRITES + if (object1.physicsType === Phaser.SPRITE) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // GROUPS + else if (object1.physicsType === Phaser.GROUP) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // TILEMAP LAYERS + else if (object1.physicsType === Phaser.TILEMAPLAYER) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsSprite + * @private + * @param {Phaser.Sprite} sprite1 - The first sprite to check. + * @param {Phaser.Sprite} sprite2 - The second sprite to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + 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; + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsGroup + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0 || !sprite.body) + { + return; + } + + if (this.skipQuadTree || sprite.body.skipQuadTree) + { + var bounds = {}; + + for (var i = 0; i < group.hash.length; i++) + { + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds object + bounds = object1.body.getBounds(bounds); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (sprite.body.right < bounds.x) + { + break; + } + else if (bounds.right < sprite.body.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (sprite.body.x > bounds.right) + { + break; + } + else if (bounds.x > sprite.body.right) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (sprite.body.bottom < bounds.y) + { + break; + } + else if (bounds.bottom < sprite.body.y) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (sprite.body.y > bounds.bottom) + { + break; + } + else if (bounds.y > sprite.body.bottom) + { + continue; + } + } + + this.collideSpriteVsSprite(sprite, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else + { + // What is the sprite colliding with in the quadtree? + 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 items = this.quadTree.retrieve(sprite); + + for (var i = 0; i < items.length; i++) + { + // We have our potential suspects, are they in this group? + if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, items[i].sprite); + } + + this._total++; + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsSelf + * @private + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.hash.length; i++) + { + var bounds1 = {}; + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds1 object + bounds1 = object1.body.getBounds(bounds1); + + for (var j = i + 1; j < group.hash.length; j++) + { + var bounds2 = {}; + var object2 = group.hash[j]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object2 || !object2.exists || !object2.body) + { + continue; + } + + // Inject the Body bounds data into the bounds2 object + bounds2 = object2.body.getBounds(bounds2); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (bounds1.right < bounds2.x) + { + break; + } + else if (bounds2.right < bounds1.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (bounds1.x > bounds2.right) + { + continue; + } + else if (bounds2.x > bounds1.right) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (bounds1.bottom < bounds2.y) + { + continue; + } + else if (bounds2.bottom < bounds1.y) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (bounds1.y > bounds2.bottom) + { + continue; + } + else if (bounds2.y > object1.body.bottom) + { + break; + } + } + + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsGroup + * @private + * @param {Phaser.Group} group1 - The first Group to check. + * @param {Phaser.Group} group2 - The second Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group1.length === 0 || group2.length === 0) + { + return; + } + + for (var i = 0; i < group1.children.length; i++) + { + if (group1.children[i].exists) + { + if (group1.children[i].physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else + { + this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + + }, + + /** + * The core separation function to separate two physics bodies. + * + * @private + * @method Phaser.Physics.Arcade#separate + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true. + * @param {object} [callbackContext] - The context in which to run the process callback. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} Returns true if the bodies collided, otherwise false. + */ + separate: function (body1, body2, processCallback, callbackContext, overlapOnly) { + + if ( + !body1.enable || + !body2.enable || + body1.checkCollision.none || + body2.checkCollision.none || + !this.intersects(body1, body2)) + { + return false; + } + + // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. + if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false) + { + return false; + } + + // Circle vs. Circle quick bail out + if (body1.isCircle && body2.isCircle) + { + return this.separateCircle(body1, body2, overlapOnly); + } + + // We define the behavior of bodies in a collision circle and rectangle + // If a collision occurs in the corner points of the rectangle, the body behave like circles + + // Either body1 or body2 is a circle + if (body1.isCircle !== body2.isCircle) + { + var bodyRect = (body1.isCircle) ? body2 : body1; + var bodyCircle = (body1.isCircle) ? body1 : body2; + + var rect = { + x: bodyRect.x, + y: bodyRect.y, + right: bodyRect.right, + bottom: bodyRect.bottom + }; + + var circle = bodyCircle.center; + + if (circle.y < rect.y || circle.y > rect.bottom) + { + if (circle.x < rect.x || circle.x > rect.right) + { + return this.separateCircle(body1, body2, overlapOnly); + } + } + } + + var resultX = false; + var resultY = false; + + // Do we separate on x or y first? + if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) + { + resultX = this.separateX(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultY = this.separateY(body1, body2, overlapOnly); + } + } + else + { + resultY = this.separateY(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultX = this.separateX(body1, body2, overlapOnly); + } + } + + var result = (resultX || resultY); + + if (result) + { + if (overlapOnly) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + else + { + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + } + } + + return result; + + }, + + /** + * Check for intersection against two bodies. + * + * @method Phaser.Physics.Arcade#intersects + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check. + * @return {boolean} True if they intersect, otherwise false. + */ + intersects: function (body1, body2) { + + if (body1 === body2) + { + return false; + } + + if (body1.isCircle) + { + if (body2.isCircle) + { + // Circle vs. Circle + return Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); + } + else + { + // Circle vs. Rect + return this.circleBodyIntersects(body1, body2); + } + } + else + { + if (body2.isCircle) + { + // Rect vs. Circle + return this.circleBodyIntersects(body2, body1); + } + else + { + // Rect vs. Rect + if (body1.right <= body2.position.x) + { + return false; + } + + if (body1.bottom <= body2.position.y) + { + return false; + } + + if (body1.position.x >= body2.right) + { + return false; + } + + if (body1.position.y >= body2.bottom) + { + return false; + } + + return true; + } + } + + }, + + /** + * Checks to see if a circular Body intersects with a Rectangular Body. + * + * @method Phaser.Physics.Arcade#circleBodyIntersects + * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set. + * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape) + * @return {boolean} Returns true if the bodies intersect, otherwise false. + */ + circleBodyIntersects: function (circle, body) { + + var x = Phaser.Math.clamp(circle.center.x, body.left, body.right); + var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom); + + var dx = (circle.center.x - x) * (circle.center.x - x); + var dy = (circle.center.y - y) * (circle.center.y - y); + + return (dx + dy) <= (circle.halfWidth * circle.halfWidth); + + }, + + /** + * The core separation function to separate two circular physics bodies. + * + * @method Phaser.Physics.Arcade#separateCircle + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateCircle: function (body1, body2, overlapOnly) { + + // Set the bounding box overlap values + this.getOverlapX(body1, body2); + this.getOverlapY(body1, body2); + + var dx = body2.center.x - body1.center.x; + var dy = body2.center.y - body1.center.y; + + var angleCollision = Math.atan2(dy, dx); + + var overlap = 0; + + if (body1.isCircle !== body2.isCircle) + { + var rect = { + x: (body2.isCircle) ? body1.position.x : body2.position.x, + y: (body2.isCircle) ? body1.position.y : body2.position.y, + right: (body2.isCircle) ? body1.right : body2.right, + bottom: (body2.isCircle) ? body1.bottom : body2.bottom + }; + + var circle = { + x: (body1.isCircle) ? body1.center.x : body2.center.x, + y: (body1.isCircle) ? body1.center.y : body2.center.y, + radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth + }; + + if (circle.y < rect.y) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.y) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.y) - circle.radius; + } + } + else if (circle.y > rect.bottom) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; + } + } + + overlap *= -1; + } + else + { + overlap = (body1.halfWidth + body2.halfWidth) - Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y); + } + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + if (overlap !== 0) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + + // return true if there was some overlap, otherwise false + return (overlap !== 0); + } + + // Transform the velocity vector to the coordinate system oriented along the direction of impact. + // This is done to eliminate the vertical component of the velocity + var v1 = { + x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision), + y: body1.velocity.x * Math.sin(angleCollision) - body1.velocity.y * Math.cos(angleCollision) + }; + + var v2 = { + x: body2.velocity.x * Math.cos(angleCollision) + body2.velocity.y * Math.sin(angleCollision), + y: body2.velocity.x * Math.sin(angleCollision) - body2.velocity.y * Math.cos(angleCollision) + }; + + // We expect the new velocity after impact + var tempVel1 = ((body1.mass - body2.mass) * v1.x + 2 * body2.mass * v2.x) / (body1.mass + body2.mass); + var tempVel2 = (2 * body1.mass * v1.x + (body2.mass - body1.mass) * v2.x) / (body1.mass + body2.mass); + + // We convert the vector to the original coordinate system and multiplied by factor of rebound + if (!body1.immovable) + { + body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x; + body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y; + } + + if (!body2.immovable) + { + body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x; + body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y; + } + + // When the collision angle is almost perpendicular to the total initial velocity vector + // (collision on a tangent) vector direction can be determined incorrectly. + // This code fixes the problem + + if (Math.abs(angleCollision) < Math.PI / 2) + { + if ((body1.velocity.x > 0) && !body1.immovable && (body2.velocity.x > body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x < 0) && !body2.immovable && (body1.velocity.x < body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y > 0) && !body1.immovable && (body2.velocity.y > body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y < 0) && !body2.immovable && (body1.velocity.y < body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + else if (Math.abs(angleCollision) > Math.PI / 2) + { + if ((body1.velocity.x < 0) && !body1.immovable && (body2.velocity.x < body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y < 0) && !body1.immovable && (body2.velocity.y < body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + + if (!body1.immovable) + { + body1.x += (body1.velocity.x * this.game.time.physicsElapsed) - overlap * Math.cos(angleCollision); + body1.y += (body1.velocity.y * this.game.time.physicsElapsed) - overlap * Math.sin(angleCollision); + } + + if (!body2.immovable) + { + body2.x += (body2.velocity.x * this.game.time.physicsElapsed) + overlap * Math.cos(angleCollision); + body2.y += (body2.velocity.y * this.game.time.physicsElapsed) + overlap * Math.sin(angleCollision); + } + + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + + return true; + + }, + + /** + * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: + * `touching.left`, `touching.right` and `overlapX`. + * + * @method Phaser.Physics.Arcade#getOverlapX + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of horizontal overlap between the two bodies. + */ + getOverlapX: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS; + + if (body1.deltaX() === 0 && body2.deltaX() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaX() > body2.deltaX()) + { + // Body1 is moving right and / or Body2 is moving left + overlap = body1.right - body2.x; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.right = true; + body2.touching.none = false; + body2.touching.left = true; + } + } + else if (body1.deltaX() < body2.deltaX()) + { + // Body1 is moving left and/or Body2 is moving right + overlap = body1.x - body2.width - body2.x; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.left = true; + body2.touching.none = false; + body2.touching.right = true; + } + } + + // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapX = overlap; + body2.overlapX = overlap; + + return overlap; + + }, + + /** + * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: + * `touching.up`, `touching.down` and `overlapY`. + * + * @method Phaser.Physics.Arcade#getOverlapY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of vertical overlap between the two bodies. + */ + getOverlapY: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS; + + if (body1.deltaY() === 0 && body2.deltaY() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaY() > body2.deltaY()) + { + // Body1 is moving down and/or Body2 is moving up + overlap = body1.bottom - body2.y; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.down = true; + body2.touching.none = false; + body2.touching.up = true; + } + } + else if (body1.deltaY() < body2.deltaY()) + { + // Body1 is moving up and/or Body2 is moving down + overlap = body1.y - body2.bottom; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.up = true; + body2.touching.none = false; + body2.touching.down = true; + } + } + + // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapY = overlap; + body2.overlapY = overlap; + + return overlap; + + }, + + /** + * The core separation function to separate two physics bodies on the x axis. + * + * @method Phaser.Physics.Arcade#separateX + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateX: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapX(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.x; + var v2 = body2.velocity.x; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.x -= overlap; + body2.x += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.x = avg + nv1 * body1.bounce.x; + body2.velocity.x = avg + nv2 * body2.bounce.x; + } + else if (!body1.immovable) + { + body1.x -= overlap; + body1.velocity.x = v2 - v1 * body1.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body2.moves) + { + body1.y += (body2.y - body2.prev.y) * body2.friction.y; + } + } + else + { + body2.x += overlap; + body2.velocity.x = v1 - v2 * body2.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body1.moves) + { + body2.y += (body1.y - body1.prev.y) * body1.friction.y; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * The core separation function to separate two physics bodies on the y axis. + * + * @private + * @method Phaser.Physics.Arcade#separateY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateY: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapY(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.y; + var v2 = body2.velocity.y; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.y -= overlap; + body2.y += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.y = avg + nv1 * body1.bounce.y; + body2.velocity.y = avg + nv2 * body2.bounce.y; + } + else if (!body1.immovable) + { + body1.y -= overlap; + body1.velocity.y = v2 - v1 * body1.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body2.moves) + { + body1.x += (body2.x - body2.prev.x) * body2.friction.x; + } + } + else + { + body2.y += overlap; + body2.velocity.y = v1 - v2 * body2.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body1.moves) + { + body2.x += (body1.x - body1.prev.x) * body1.friction.x; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. + * + * @method Phaser.Physics.Arcade#getObjectsUnderPointer + * @param {Phaser.Pointer} pointer - The Pointer to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. + * @param {object} [callbackContext] - The context in which to run the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates. + */ + getObjectsUnderPointer: function (pointer, group, callback, callbackContext) { + + if (group.length === 0 || !pointer.exists) + { + return; + } + + return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer); + + }, + + /** + * Given a Group and a location this will check to see which Group children overlap with the coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. + * + * @method Phaser.Physics.Arcade#getObjectsAtLocation + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. + * @param {object} [callbackContext] - The context in which to run the callback. + * @param {object} [callbackArg] - An argument to pass to the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates. + */ + getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) { + + 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(x, y, 1, 1); + var output = []; + + var items = this.quadTree.retrieve(rect); + + for (var i = 0; i < items.length; i++) + { + if (items[i].hitTest(x, y)) + { + if (callback) + { + callback.call(callbackContext, callbackArg, items[i].sprite); + } + + output.push(items[i].sprite); + } + } + + return output; + + }, + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToObject: function (displayObject, destination, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Phaser.Point.angle(destination, displayObject); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#moveToPointer + * @param {any} displayObject - The display object to move. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToPointer: function (displayObject, speed, pointer, maxTime) { + + if (speed === undefined) { speed = 60; } + pointer = pointer || this.game.input.activePointer; + if (maxTime === undefined) { maxTime = 0; } + + var angle = this.angleToPointer(displayObject, pointer); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToXY: function (displayObject, x, y, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Math.atan2(y - displayObject.y, x - displayObject.x); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromAngle + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromAngle: function (angle, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(angle, speed, true); + + }, + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. + * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. + * + * @method Phaser.Physics.Arcade#accelerationFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. + * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. + */ + accelerationFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleBetween(displayObject, destination); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToPointer + * @param {any} displayObject - The display object to move. + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToPointer(displayObject, pointer); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToXY(displayObject, x, y); + + displayObject.body.acceleration.setTo(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Find the distance between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * If you have nested objects and need to calculate the distance between their centers in World coordinates, + * set their anchors to (0.5, 0.5) and use the `world` argument. + * + * If objects aren't nested or they share a parent's offset, you can calculate the distance between their + * centers with the `useCenter` argument, regardless of their anchor values. + * + * @method Phaser.Physics.Arcade#distanceBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {number} The distance between the source and target objects. + */ + distanceBetween: function (source, target, world, useCenter) { + + if (world === undefined) { world = false; } + + var dx; + var dy; + + if (useCenter) + { + dx = source.centerX - target.centerX; + dy = source.centerY - target.centerY; + } + else if (world) + { + dx = source.world.x - target.world.x; + dy = source.world.y - target.world.y; + } + else + { + dx = source.x - target.x; + dy = source.y - target.y; + } + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and the given x/y coordinates. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the x/y coordinates. + */ + distanceToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - x : displayObject.x - x; + var dy = (world) ? displayObject.world.y - y : displayObject.y - y; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the Pointer. + */ + distanceToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.x - pointer.worldX; + var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + + /** + * From a set of points or display objects, find the one closest to a source point or object. + * + * @method Phaser.Physics.Arcade#closest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The first target closest to the origin. + */ + closest: function (source, targets, world, useCenter) { + var min = Infinity; + var closest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance < min) + { + closest = target; + min = distance; + } + } + + return closest; + }, + + /** + * From a set of points or display objects, find the one farthest from a source point or object. + * + * @method Phaser.Physics.Arcade#farthest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The target closest to the origin. + */ + farthest: function (source, targets, world, useCenter) { + var max = -1; + var farthest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance > max) + { + farthest = target; + max = distance; + } + } + + return farthest; + }, + + /** + * Find the angle in radians between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetween: function (source, target, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Phaser.Point.angle(target.world, source.world); + } + else + { + return Phaser.Point.angle(target, source); + } + + }, + + /** + * Find the angle in radians between centers of two display objects (like Sprites). + * + * @method Phaser.Physics.Arcade#angleBetweenCenters + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetweenCenters: function (source, target) { + + var dx = target.centerX - source.centerX; + var dy = target.centerY - source.centerY; + + return Math.atan2(dy, dx); + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to get the angle to. + * @param {number} y - The y coordinate to get the angle to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(y - displayObject.world.y, x - displayObject.world.x); + } + else + { + return Math.atan2(y - displayObject.y, x - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x); + } + else + { + return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, + * taking their x/y and center into account relative to the world. + * + * @method Phaser.Physics.Arcade#worldAngleToPointer + * @param {any} displayObject - The DisplayObjerct to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY + */ + worldAngleToPointer: function (displayObject, pointer) { + + return this.angleToPointer(displayObject, pointer, true); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than +* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. +* +* @class Phaser.Physics.Arcade.Body +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. +*/ +Phaser.Physics.Arcade.Body = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = sprite.game; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.ARCADE; + + /** + * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. + * @default + */ + this.enable = true; + + /** + * If `true` this Body is using circular collision detection. If `false` it is using rectangular. + * Use `Body.setCircle` to control the collision shape this Body uses. + * @property {boolean} isCircle + * @default + * @readOnly + */ + this.isCircle = false; + + /** + * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled, relative to the Sprite's _texture_. + * If you wish to change the radius then call {@link #setCircle} again with the new value. + * If you wish to stop the Body using a circle then call {@link #setCircle} with a radius of zero (or undefined). + * The actual radius of the Body (at any Sprite scale) is equal to {@link #halfWidth} and the diameter is equal to {@link #width}. + * @property {number} radius + * @default + * @readOnly + */ + this.radius = 0; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite's texture. + */ + this.offset = new Phaser.Point(); + + /** + * @property {Phaser.Point} position - The position of the physics body, equivalent to ({@link #left}, {@link #top}). + * @readonly + */ + this.position = new Phaser.Point(sprite.x, sprite.y); + + /** + * @property {Phaser.Point} prev - The previous position of the physics body. + * @readonly + */ + this.prev = new Phaser.Point(this.position.x, this.position.y); + + /** + * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) + * @default + */ + this.allowRotation = true; + + /** + * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body + * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. + * @property {number} rotation + */ + this.rotation = sprite.angle; + + /** + * @property {number} preRotation - The previous rotation of the physics body, in degrees. + * @readonly + */ + this.preRotation = sprite.angle; + + /** + * @property {number} width - The calculated width of the physics body. + * @readonly + */ + this.width = sprite.width; + + /** + * @property {number} height - The calculated height of the physics body. + * @readonly + */ + this.height = sprite.height; + + /** + * @property {number} sourceWidth - The un-scaled original size. + * @readonly + */ + this.sourceWidth = sprite.width; + + /** + * @property {number} sourceHeight - The un-scaled original size. + * @readonly + */ + this.sourceHeight = sprite.height; + + if (sprite.texture) + { + this.sourceWidth = sprite.texture.frame.width; + this.sourceHeight = sprite.texture.frame.height; + } + + /** + * @property {number} halfWidth - The calculated width / 2 of the physics body. + * @readonly + */ + this.halfWidth = Math.abs(sprite.width / 2); + + /** + * @property {number} halfHeight - The calculated height / 2 of the physics body. + * @readonly + */ + this.halfHeight = Math.abs(sprite.height / 2); + + /** + * @property {Phaser.Point} center - The center coordinate of the Physics Body. + * @readonly + */ + this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight); + + /** + * @property {Phaser.Point} velocity - The velocity, or rate of change the Body's position. Measured in pixels per second. + */ + this.velocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} newVelocity - The distanced traveled during the last update, equal to `velocity * physicsElapsed`. Calculated during the Body.preUpdate and applied to its position. + * @readonly + */ + this.newVelocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. + */ + this.deltaMax = new Phaser.Point(); + + /** + * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + */ + this.acceleration = new Phaser.Point(); + + /** + * @property {boolean} allowDrag - Allow this Body to be influenced by {@link #drag}? + * @default + */ + this.allowDrag = true; + + /** + * @property {Phaser.Point} drag - The drag applied to the motion of the Body (when {@link #allowDrag} is enabled). Measured in pixels per second squared. + */ + this.drag = new Phaser.Point(); + + /** + * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local. + * @default + */ + this.allowGravity = true; + + /** + * @property {Phaser.Point} gravity - This Body's local gravity, **added** to any world gravity, unless Body.allowGravity is set to false. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. + */ + this.bounce = new Phaser.Point(); + + /** + * The elasticity of the Body when colliding with the World bounds. + * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property + * to a Phaser.Point object in order to enable a World bounds specific bounce value. + * @property {Phaser.Point} worldBounce + */ + this.worldBounce = null; + + /** + * A Signal that is dispatched when this Body collides with the world bounds. + * Due to the potentially high volume of signals this could create it is disabled by default. + * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` + * and it will be called when a collision happens, passing five arguments: + * `onWorldBounds(sprite, up, down, left, right)` + * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans + * indicating on which side of the world the Body collided. + * @property {Phaser.Signal} onWorldBounds + */ + this.onWorldBounds = null; + + /** + * A Signal that is dispatched when this Body collides with another Body. + * + * You still need to call `game.physics.arcade.collide` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `collide` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onCollide + */ + this.onCollide = null; + + /** + * A Signal that is dispatched when this Body overlaps with another Body. + * + * You still need to call `game.physics.arcade.overlap` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `overlap` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onOverlap + */ + this.onOverlap = null; + + /** + * @property {Phaser.Point} maxVelocity - The maximum velocity (in pixels per second squared) that the Body can reach. + * @default + */ + this.maxVelocity = new Phaser.Point(10000, 10000); + + /** + * @property {Phaser.Point} friction - If this Body is {@link #immovable} and moving, and another Body is 'riding' this one, this is the amount of motion the riding Body receives on each axis. + */ + this.friction = new Phaser.Point(1, 0); + + /** + * @property {number} angularVelocity - The angular velocity is the rate of change of the Body's rotation. It is measured in degrees per second. + * @default + */ + this.angularVelocity = 0; + + /** + * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. + * @default + */ + this.angularAcceleration = 0; + + /** + * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach. + * @default + */ + this.maxAngular = 1000; + + /** + * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. + * @default + */ + this.mass = 1; + + /** + * @property {number} angle - The angle of the Body's **velocity** in radians. + * @readonly + */ + this.angle = 0; + + /** + * @property {number} speed - The speed of the Body in pixels per second, equal to the magnitude of the velocity. + * @readonly + */ + this.speed = 0; + + /** + * @property {number} facing - A const reference to the direction the Body is traveling or facing: Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.UP, or Phaser.DOWN. If the Body is moving on both axes, UP and DOWN take precedence. + * @default + */ + this.facing = Phaser.NONE; + + /** + * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. **Two** immovable Bodies can't separate or exchange momentum and will pass through each other. + * @default + */ + this.immovable = false; + + /** + * Whether the physics system should update the Body's position and rotation based on its velocity, acceleration, drag, and gravity. + * + * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never + * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. + * If you want the physics system to move the body around, then set moves to true. + * + * A Body with moves = false can still be moved slightly (but not accelerated) during collision separation unless you set {@link #immovable} as well. + * + * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually. + * @default + */ + this.moves = true; + + /** + * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateX = false; + + /** + * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateY = false; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapX - The amount of horizontal overlap during the collision. + */ + this.overlapX = 0; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapY - The amount of vertical overlap during the collision. + */ + this.overlapY = 0; + + /** + * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. + * @property {number} overlapR - The amount of overlap during the collision. + */ + this.overlapR = 0; + + /** + * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. + * @property {boolean} embedded - Body embed value. + */ + this.embedded = false; + + /** + * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. + * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? + */ + this.collideWorldBounds = false; + + /** + * Set the checkCollision properties to control which directions collision is processed for this Body. + * For example checkCollision.up = false means it won't collide when the collision happened while moving up. + * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. + * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. + * @property {object} checkCollision - An object containing allowed collision (none, up, down, left, right). + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * This object is populated with boolean values when the Body collides with another. + * touching.up = true means the collision happened to the top of this Body for example. + * @property {object} touching - An object containing touching results (none, up, down, left, right). + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with previous touching values from the bodies previous collision. + * @property {object} wasTouching - An object containing previous touching results (none, up, down, left, right). + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with boolean values when the Body collides with the World bounds or a Tile. + * For example if blocked.up is true then the Body cannot move up. + * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any (none, up, down, left, right). + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. + * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. + * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision. + */ + this.tilePadding = new Phaser.Point(); + + /** + * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state? + */ + this.dirty = false; + + /** + * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. + */ + this.skipQuadTree = false; + + /** + * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. + * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. + * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, + * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. + * @property {boolean} syncBounds + * @default + */ + this.syncBounds = false; + + /** + * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods. + */ + this.isMoving = false; + + /** + * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods. + */ + this.stopVelocityOnCollide = true; + + /** + * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveTimer = 0; + + /** + * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDistance = 0; + + /** + * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDuration = 0; + + /** + * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveTarget = null; + + /** + * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveEnd = null; + + /** + * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events. + */ + this.onMoveComplete = new Phaser.Signal(); + + /** + * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. + */ + this.movementCallback = null; + + /** + * @property {object} movementCallbackContext - Context in which to call the movementCallback. + */ + this.movementCallbackContext = null; + + /** + * @property {boolean} _reset - Internal cache var. + * @private + */ + this._reset = true; + + /** + * @property {number} _sx - Internal cache var. + * @private + */ + this._sx = sprite.scale.x; + + /** + * @property {number} _sy - Internal cache var. + * @private + */ + this._sy = sprite.scale.y; + + /** + * @property {number} _dx - Internal cache var. + * @private + */ + this._dx = 0; + + /** + * @property {number} _dy - Internal cache var. + * @private + */ + this._dy = 0; + +}; + +Phaser.Physics.Arcade.Body.prototype = { + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @protected + */ + updateBounds: function () { + + if (this.syncBounds) + { + var b = this.sprite.getBounds(); + b.ceilAll(); + + if (b.width !== this.width || b.height !== this.height) + { + this.width = b.width; + this.height = b.height; + this._reset = true; + } + } + else + { + 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._sx = asx; + this._sy = asy; + this._reset = true; + } + } + + if (this._reset) + { + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.updateCenter(); + } + + }, + + /** + * Update the Body's center from its position. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @protected + */ + updateCenter: function () { + + this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @protected + */ + preUpdate: function () { + + if (!this.enable || this.game.physics.arcade.isPaused) + { + return; + } + + this.dirty = true; + + // Store and reset collision flags + 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.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; + + this.overlapR = 0; + this.overlapX = 0; + this.overlapY = 0; + + this.embedded = false; + + this.updateBounds(); + + this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.updateCenter(); + + this.rotation = this.sprite.angle; + + this.preRotation = this.rotation; + + if (this._reset || this.sprite.fresh) + { + 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; + this.updateCenter(); + + if (this.position.x !== this.prev.x || this.position.y !== this.prev.y) + { + this.angle = this.velocity.atan(); + } + + this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); + + // Now the State update will throw collision checks at the Body + // And finally we'll integrate the new position back to the Sprite in postUpdate + + if (this.collideWorldBounds) + { + if (this.checkWorldBounds() && this.onWorldBounds) + { + this.onWorldBounds.dispatch(this.sprite, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); + } + } + } + + this._dx = this.deltaX(); + this._dy = this.deltaY(); + + this._reset = false; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateMovement + * @protected + */ + updateMovement: function () { + + var percent = 0; + var collided = (this.overlapX !== 0 || this.overlapY !== 0); + + // Duration or Distance based? + + if (this.moveDuration > 0) + { + this.moveTimer += this.game.time.elapsedMS; + + percent = this.moveTimer / this.moveDuration; + } + else + { + this.moveTarget.end.set(this.position.x, this.position.y); + + percent = this.moveTarget.length / this.moveDistance; + } + + if (this.movementCallback) + { + var result = this.movementCallback.call(this.movementCallbackContext, this, this.velocity, percent); + } + + if (collided || percent >= 1 || (result !== undefined && result !== true)) + { + this.stopMovement((percent >= 1) || (this.stopVelocityOnCollide && collided)); + return false; + } + + return true; + + }, + + /** + * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it + * has Body.isMoving true), then calling this method will stop the movement before + * either the duration or distance counters expire. + * + * The `onMoveComplete` signal is dispatched. + * + * @method Phaser.Physics.Arcade.Body#stopMovement + * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero? + */ + stopMovement: function (stopVelocity) { + + if (this.isMoving) + { + this.isMoving = false; + + if (stopVelocity) + { + this.velocity.set(0); + } + + // Send the Sprite this Body belongs to + // and a boolean indicating if it stopped because of a collision or not + this.onMoveComplete.dispatch(this.sprite, (this.overlapX !== 0 || this.overlapY !== 0)); + } + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @protected + */ + postUpdate: function () { + + // Only allow postUpdate to be called once per frame + if (!this.enable || !this.dirty) + { + return; + } + + // Moving? + if (this.isMoving) + { + this.updateMovement(); + } + + this.dirty = false; + + 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.position.x += this._dx; + this.sprite.position.y += this._dy; + this._reset = true; + } + + this.updateCenter(); + + if (this.allowRotation) + { + this.sprite.angle += this.deltaZ(); + } + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @protected + * @return {boolean} True if the Body collided with the world bounds, otherwise false. + */ + checkWorldBounds: function () { + + var pos = this.position; + var bounds = this.game.physics.arcade.bounds; + var check = this.game.physics.arcade.checkCollision; + + var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; + var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; + + if (pos.x < bounds.x && check.left) + { + pos.x = bounds.x; + this.velocity.x *= bx; + this.blocked.left = true; + this.blocked.none = false; + } + else if (this.right > bounds.right && check.right) + { + pos.x = bounds.right - this.width; + this.velocity.x *= bx; + this.blocked.right = true; + this.blocked.none = false; + } + + if (pos.y < bounds.y && check.up) + { + pos.y = bounds.y; + this.velocity.y *= by; + this.blocked.up = true; + this.blocked.none = false; + } + else if (this.bottom > bounds.bottom && check.down) + { + pos.y = bounds.bottom - this.height; + this.velocity.y *= by; + this.blocked.down = true; + this.blocked.none = false; + } + + return !this.blocked.none; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal timer, and then + * monitoring the duration each frame. When the duration is up the movement is + * stopped and the `Body.onMoveComplete` signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * You can optionally set a speed in pixels per second. If not specified it + * will use the current `Body.speed` value. If this is zero, the function will return false. + * + * Please note that due to browser timings you should allow for a variance in + * when the duration will actually expire. Depending on system it may be as much as + * +- 50ms. Also this method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveFrom + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveFrom: function (duration, speed, direction) { + + if (speed === undefined) { speed = this.speed; } + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + this.moveTimer = 0; + this.moveDuration = duration; + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal distance counter. + * The distance is monitored each frame. When the distance equals the distance + * specified in this call, the movement is stopped, and the `Body.onMoveComplete` + * signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * Please note that due to browser timings you should allow for a variance in + * when the distance will actually expire. + * + * Note: This method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveTo + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} distance - The distance, in pixels, the Body will move. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveTo: function (duration, distance, direction) { + + var speed = distance / (duration / 1000); + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + distance = Math.abs(distance); + + this.moveDuration = 0; + this.moveDistance = distance; + + if (this.moveTarget === null) + { + this.moveTarget = new Phaser.Line(); + this.moveEnd = new Phaser.Point(); + } + + this.moveTarget.fromAngle(this.x, this.y, angle, distance); + + this.moveEnd.set(this.moveTarget.end.x, this.moveTarget.end.y); + + this.moveTarget.setTo(this.x, this.y, this.x, this.y); + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * You can modify the size of the physics Body to be any dimension you need. + * This allows you to make it smaller, or larger, than the parent Sprite. You + * can also control the x and y offset of the Body. + * + * The width, height, and offset arguments are relative to the Sprite + * _texture_ and are scaled with the Sprite's {@link Phaser.Sprite#scale} + * (but **not** the scale of any ancestors or the {@link Phaser.Camera#scale + * Camera scale}). + * + * For example: If you have a Sprite with a texture that is 80x100 in size, + * and you want the physics body to be 32x32 pixels in the middle of the + * texture, you would do: + * + * `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, + * 34)` + * + * Where the first two parameters are the new Body size (32x32 pixels) + * relative to the Sprite's scale. 24 is the horizontal offset of the Body + * from the top-left of the Sprites texture, and 34 is the vertical offset. + * + * If you've scaled a Sprite by altering its `width`, `height`, or `scale` + * and you want to position the Body relative to the Sprite's dimensions + * (which will differ from its texture's dimensions), you should divide these + * arguments by the Sprite's current scale: + * + * `setSize(32 / sprite.scale.x, 32 / sprite.scale.y)` + * + * Calling `setSize` on a Body that has already had `setCircle` will reset + * all of the Circle properties, making this Body rectangular again. + * @method Phaser.Physics.Arcade.Body#setSize + * @param {number} width - The width of the Body, relative to the Sprite's + * texture. + * @param {number} height - The height of the Body, relative to the Sprite's + * texture. + * @param {number} [offsetX] - The X offset of the Body from the left of the + * Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the + * Sprite's texture. + */ + setSize: function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { 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.updateCenter(); + + this.isCircle = false; + this.radius = 0; + + }, + + /** + * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. + * The radius is given in pixels (relative to the Sprite's _texture_) and is the distance from the center of the circle to the edge. + * + * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite's texture. + * + * To change a Body back to being rectangular again call `Body.setSize`. + * + * Note: Circular collision only happens with other Arcade Physics bodies, it does not + * work against tile maps, where rectangular collision is the only method supported. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. + * @param {number} [offsetX] - The X offset of the Body from the left of the Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the Sprite's texture. + */ + setCircle: function (radius, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.isCircle = true; + this.radius = radius; + + this.sourceWidth = radius * 2; + this.sourceHeight = radius * 2; + + 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.updateCenter(); + } + else + { + this.isCircle = false; + } + + }, + + /** + * Resets all Body values (velocity, acceleration, rotation, etc) + * + * @method Phaser.Physics.Arcade.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new y position of the Body. + */ + reset: function (x, y) { + + this.stop(); + + this.position.x = (x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + this.rotation = this.sprite.angle; + this.preRotation = this.rotation; + + this.updateBounds(); + + this.updateCenter(); + + }, + + /** + * Sets acceleration, velocity, and {@link #speed} to 0. + * + * @method Phaser.Physics.Arcade.Body#stop + */ + stop: function () { + + this.velocity.set(0); + this.acceleration.set(0); + this.speed = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + + }, + + /** + * Returns the bounds of this physics body. + * + * Only used internally by the World collision methods. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @param {object} obj - The object in which to set the bounds values. + * @return {object} The object that was given to this method. + */ + getBounds: function (obj) { + + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + + }, + + /** + * Tests if a world point lies within this Body. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @param {number} x - The world x coordinate to test. + * @param {number} y - The world y coordinate to test. + * @return {boolean} True if the given coordinates are inside this Body, otherwise false. + */ + hitTest: function (x, y) { + + return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Returns true if the bottom of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onFloor: function () { + + return this.blocked.down; + + }, + + /** + * Returns true if the top of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onCeiling: function(){ + + return this.blocked.up; + + }, + + /** + * Returns true if either side of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onWall: function () { + + return (this.blocked.left || this.blocked.right); + + }, + + /** + * Returns the absolute delta x value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @return {number} The absolute delta value. + */ + deltaAbsX: function () { + + return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); + + }, + + /** + * Returns the absolute delta y value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @return {number} The absolute delta value. + */ + deltaAbsY: function () { + + return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); + + }, + + /** + * Returns the delta x value. The difference between Body.x now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. + */ + deltaX: function () { + + return this.position.x - this.prev.x; + + }, + + /** + * Returns the delta y value. The difference between Body.y now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. + */ + deltaY: function () { + + return this.position.y - this.prev.y; + + }, + + /** + * Returns the delta z value. The difference between Body.rotation now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise. + */ + deltaZ: function () { + + return this.rotation - this.preRotation; + + }, + + /** + * Destroys this Body. + * + * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. + * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. + * + * @method Phaser.Physics.Arcade.Body#destroy + */ + destroy: function () { + + if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group) + { + this.sprite.parent.removeFromHash(this.sprite); + } + + this.sprite.body = null; + this.sprite = null; + + } + +}; + +/** +* @name Phaser.Physics.Arcade.Body#left +* @property {number} left - The x position of the Body. The same as `Body.x`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "left", { + + get: function () { + + return this.position.x; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#right +* @property {number} right - The right value of this Body (same as Body.x + Body.width) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", { + + get: function () { + + return this.position.x + this.width; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#top +* @property {number} top - The y position of the Body. The same as `Body.y`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "top", { + + get: function () { + + return this.position.y; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#bottom +* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", { + + get: function () { + + return this.position.y + this.height; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#x +* @property {number} x - The x position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#y +* @property {number} y - The y position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + +}); + +/** +* Render Sprite Body. +* +* @method Phaser.Physics.Arcade.Body#render +* @param {object} context - The context to render to. +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string). +* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) +* @param {number} [lineWidth=1] - The width of the stroke when unfilled. +*/ +Phaser.Physics.Arcade.Body.render = function (context, body, color, filled, lineWidth) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0,255,0,0.4)'; + + context.fillStyle = color; + context.strokeStyle = color; + context.lineWidth = lineWidth || 1; + + if (body.isCircle) + { + context.beginPath(); + context.arc(body.center.x - body.game.camera.x, body.center.y - body.game.camera.y, body.halfWidth, 0, 2 * Math.PI); + + if (filled) + { + context.fill(); + } + else + { + context.stroke(); + } + } + else + { + if (filled) + { + context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + else + { + context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + } + +}; + +/** +* Render Sprite Body Physics Data as text. +* +* @method Phaser.Physics.Arcade.Body#renderBodyInfo +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {number} x - X position of the debug info to be rendered. +* @param {number} y - Y position of the debug info to be rendered. +* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). +*/ +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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics Tile map collision methods. +* +* @class Phaser.Physics.Arcade.TilemapCollision +* @constructor +*/ +Phaser.Physics.Arcade.TilemapCollision = function () {}; + +Phaser.Physics.Arcade.TilemapCollision.prototype = { + + /** + * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling. + */ + TILE_BIAS: 16, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!sprite.body) + { + return; + } + + var mapData = tilemapLayer.getTiles( + sprite.body.position.x - sprite.body.tilePadding.x - tilemapLayer.getTileOffsetX(), + sprite.body.position.y - sprite.body.tilePadding.y - tilemapLayer.getTileOffsetY(), + sprite.body.width + sprite.body.tilePadding.x, + sprite.body.height + sprite.body.tilePadding.y, + false, false); + + if (mapData.length === 0) + { + return; + } + + for (var i = 0; i < mapData.length; i++) + { + if (processCallback) + { + if (processCallback.call(callbackContext, sprite, mapData[i])) + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + else + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @private + * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer + * @param {Phaser.Group} group - The Group to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.children.length; i++) + { + if (group.children[i].exists) + { + this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * The core separation function to separate a physics body and a tile. + * + * @private + * @method Phaser.Physics.Arcade#separateTile + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to collide against. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {boolean} Returns true if the body was separated, otherwise false. + */ + separateTile: function (i, body, tile, tilemapLayer, overlapOnly) { + + if (!body.enable) + { + return false; + } + + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + // We re-check for collision in case body was separated in a previous step + if (!tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + // no collision so bail out (separated in a previous step) + return false; + } + else if (overlapOnly) + { + // There is an overlap, and we don't need to separate. Bail. + return true; + } + + // They overlap. Any custom callbacks? + + // A local callback always takes priority over a layer level callback + if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + else if (typeof tile.layer.callbacks !== 'undefined' && tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + + // We don't need to go any further if this tile doesn't actually separate + if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom) + { + // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation + return false; + } + + var ox = 0; + var oy = 0; + var minX = 0; + var minY = 1; + + if (body.deltaAbsX() > body.deltaAbsY()) + { + // Moving faster horizontally, check X axis first + minX = -1; + } + else if (body.deltaAbsX() < body.deltaAbsY()) + { + // Moving faster vertically, check Y axis first + minY = -1; + } + + if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom)) + { + // We only need do this if both axis have checking faces AND we're moving in both directions + minX = Math.min(Math.abs((body.position.x - tilemapLayerOffsetX) - tile.right), Math.abs((body.right - tilemapLayerOffsetX) - tile.left)); + minY = Math.min(Math.abs((body.position.y - tilemapLayerOffsetY) - tile.bottom), Math.abs((body.bottom - tilemapLayerOffsetY) - tile.top)); + } + + if (minX < minY) + { + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + + // That's horizontal done, check if we still intersects? If not then we can return now + if (ox !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + } + } + else + { + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + + // That's vertical done, check if we still intersects? If not then we can return now + if (oy !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + } + } + + return (ox !== 0 || oy !== 0); + + }, + + /** + * Check the body against the given tile on the X axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckX: function (body, tile, tilemapLayer) { + + var ox = 0; + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + + if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left) + { + // Body is moving LEFT + if (tile.faceRight && (body.x - tilemapLayerOffsetX) < tile.right) + { + ox = (body.x - tilemapLayerOffsetX) - tile.right; + + if (ox < -this.TILE_BIAS) + { + ox = 0; + } + } + } + else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right) + { + // Body is moving RIGHT + if (tile.faceLeft && (body.right - tilemapLayerOffsetX) > tile.left) + { + ox = (body.right - tilemapLayerOffsetX) - tile.left; + + if (ox > this.TILE_BIAS) + { + ox = 0; + } + } + } + + if (ox !== 0) + { + if (body.customSeparateX) + { + body.overlapX = ox; + } + else + { + this.processTileSeparationX(body, ox); + } + } + + return ox; + + }, + + /** + * Check the body against the given tile on the Y axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckY: function (body, tile, tilemapLayer) { + + var oy = 0; + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up) + { + // Body is moving UP + if (tile.faceBottom && (body.y - tilemapLayerOffsetY) < tile.bottom) + { + oy = (body.y - tilemapLayerOffsetY) - tile.bottom; + + if (oy < -this.TILE_BIAS) + { + oy = 0; + } + } + } + else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down) + { + // Body is moving DOWN + if (tile.faceTop && (body.bottom - tilemapLayerOffsetY) > tile.top) + { + oy = (body.bottom - tilemapLayerOffsetY) - tile.top; + + if (oy > this.TILE_BIAS) + { + oy = 0; + } + } + } + + if (oy !== 0) + { + if (body.customSeparateY) + { + body.overlapY = oy; + } + else + { + this.processTileSeparationY(body, oy); + } + } + + return oy; + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} x - The x separation amount. + */ + processTileSeparationX: function (body, x) { + + if (x < 0) + { + body.blocked.left = true; + body.blocked.none = false; + } + else if (x > 0) + { + body.blocked.right = true; + body.blocked.none = false; + } + + body.position.x -= x; + + if (body.bounce.x === 0) + { + body.velocity.x = 0; + } + else + { + body.velocity.x = -body.velocity.x * body.bounce.x; + } + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} y - The y separation amount. + */ + processTileSeparationY: function (body, y) { + + if (y < 0) + { + body.blocked.up = true; + body.blocked.none = false; + } + else if (y > 0) + { + body.blocked.down = true; + body.blocked.none = false; + } + + body.position.y -= y; + + if (body.bounce.y === 0) + { + body.velocity.y = 0; + } + else + { + body.velocity.y = -body.velocity.y * body.bounce.y; + } + + } + +}; + +// Merge this with the Arcade Physics prototype +Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Add an extra properties to p2 that we need +p2.Body.prototype.parent = null; +p2.Spring.prototype.parent = null; + +/** +* This is your main access to the P2 Physics World. +* From here you can create materials, listen for events and add bodies into the physics simulation. +* +* @class Phaser.Physics.P2 +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {object} [config] - Physics configuration object passed in from the game constructor. +*/ +Phaser.Physics.P2 = function (game, config) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + if (config === undefined) + { + config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; + } + else + { + if (!config.hasOwnProperty('gravity')) + { + config.gravity = [0, 0]; + } + + if (!config.hasOwnProperty('broadphase')) + { + config.broadphase = new p2.SAPBroadphase(); + } + } + + /** + * @property {object} config - The p2 World configuration object. + * @protected + */ + this.config = config; + + /** + * @property {p2.World} world - The p2 World in which the simulation is run. + * @protected + */ + this.world = new p2.World(this.config); + + /** + * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. + * @default + */ + this.frameRate = 1 / 60; + + /** + * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. + * @default + */ + this.useElapsedTime = false; + + /** + * @property {boolean} paused - The paused state of the P2 World. + * @default + */ + this.paused = false; + + /** + * @property {array} materials - A local array of all created Materials. + * @protected + */ + this.materials = []; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. + */ + this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); + + /** + * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * This signal is dispatched when a new Body is added to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world. + * + * @property {Phaser.Signal} onBodyAdded + */ + this.onBodyAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Body is removed to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world. + * + * @property {Phaser.Signal} onBodyRemoved + */ + this.onBodyRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is added to the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world. + * + * @property {Phaser.Signal} onSpringAdded + */ + this.onSpringAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is removed from the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world. + * + * @property {Phaser.Signal} onSpringRemoved + */ + this.onSpringRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is added to the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world. + * + * @property {Phaser.Signal} onConstraintAdded + */ + this.onConstraintAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is removed from the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world. + * + * @property {Phaser.Signal} onConstraintRemoved + */ + this.onConstraintRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is added to the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world. + * + * @property {Phaser.Signal} onContactMaterialAdded + */ + this.onContactMaterialAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is removed from the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world. + * + * @property {Phaser.Signal} onContactMaterialRemoved + */ + this.onContactMaterialRemoved = new Phaser.Signal(); + + /** + * @property {function} postBroadphaseCallback - A postBroadphase callback. + */ + this.postBroadphaseCallback = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are fired. + */ + this.callbackContext = null; + + /** + * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done. + * + * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done. + * + * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + // Pixel to meter function overrides + if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) + { + this.mpx = config.mpx; + this.mpxi = config.mpxi; + this.pxm = config.pxm; + this.pxmi = config.pxmi; + } + + // Hook into the World events + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + /** + * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. + */ + this.collisionGroups = []; + + /** + * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. + */ + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. + */ + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. + */ + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + /** + * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. + */ + this.boundsCollidesWith = []; + + /** + * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. + * @private + */ + this._toRemove = []; + + /** + * @property {number} _collisionGroupID - Internal var. + * @private + */ + this._collisionGroupID = 2; + + /** + * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsLeft = true; + + /** + * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsRight = true; + + /** + * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsTop = true; + + /** + * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsBottom = true; + + /** + * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsOwnGroup = false; + + // By default we want everything colliding with everything + this.setBoundsToWorld(true, true, true, true, false); + +}; + +Phaser.Physics.P2.prototype = { + + /** + * This will add a P2 Physics body into the removal list for the next step. + * + * @method Phaser.Physics.P2#removeBodyNextStep + * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. + */ + removeBodyNextStep: function (body) { + + this._toRemove.push(body); + + }, + + /** + * Called at the start of the core update loop. Purges flagged bodies from the world. + * + * @method Phaser.Physics.P2#preUpdate + */ + preUpdate: function () { + + var i = this._toRemove.length; + + while (i--) + { + this.removeBody(this._toRemove[i]); + } + + this._toRemove.length = 0; + + }, + + /** + * This will create a P2 Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. + * + * @method Phaser.Physics.P2#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [debug=false] - Create a debug object to go with this body? + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, debug, children) { + + if (debug === undefined) { debug = false; } + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + this.enable(object[i].children, debug, children); + } + else + { + this.enableBody(object[i], debug); + + if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) + { + this.enable(object[i], debug, true); + } + } + } + } + else + { + if (object instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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); + } + } + } + + }, + + /** + * Creates a P2 Physics body on the given game object. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * @method Phaser.Physics.P2#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + * @param {boolean} debug - Create a debug object to go with this body? + */ + 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; + if (typeof object.anchor !== 'undefined') { + object.anchor.set(0.5); + } + } + + }, + + /** + * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. + * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. + * + * @method Phaser.Physics.P2#setImpactEvents + * @param {boolean} state - Set to true to enable impact events, or false to disable. + */ + setImpactEvents: function (state) { + + if (state) + { + this.world.on("impact", this.impactHandler, this); + } + else + { + this.world.off("impact", this.impactHandler, this); + } + + }, + + /** + * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. + * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. + * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. + * Returning `true` from the callback will ensure they are checked in the narrowphase. + * + * @method Phaser.Physics.P2#setPostBroadphaseCallback + * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. + * @param {object} context - The context under which the callback will be fired. + */ + 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); + } + + }, + + /** + * Internal handler for the postBroadphase event. + * + * @method Phaser.Physics.P2#postBroadphaseHandler + * @private + * @param {object} event - The event data. + */ + postBroadphaseHandler: function (event) { + + if (!this.postBroadphaseCallback || event.pairs.length === 0) + { + return; + } + + for (var i = event.pairs.length - 2; i >= 0; 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); + } + } + + }, + + /** + * Handles a p2 impact event. + * + * @method Phaser.Physics.P2#impactHandler + * @private + * @param {object} event - The event data. + */ + impactHandler: function (event) { + + if (event.bodyA.parent && event.bodyB.parent) + { + // Body vs. Body callbacks + 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); + } + + // Body vs. Group callbacks + 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); + } + } + + }, + + /** + * Handles a p2 begin contact event. + * + * @method Phaser.Physics.P2#beginContactHandler + * @param {object} event - The event data. + */ + beginContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + 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.bodyB, event.shapeA, event.shapeB, event.contactEquations); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations); + } + } + + }, + + /** + * Handles a p2 end contact event. + * + * @method Phaser.Physics.P2#endContactHandler + * @param {object} event - The event data. + */ + endContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); + + if (event.bodyA.parent) + { + event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA); + } + } + + }, + + /** + * Sets the bounds of the Physics world to match the Game.World dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * + * @method Phaser.Physics#setBoundsToWorld + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + 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); + + }, + + /** + * Sets the given material against the 4 bounds of this World. + * + * @method Phaser.Physics#setWorldMaterial + * @param {Phaser.Physics.P2.Material} material - The material to set. + * @param {boolean} [left=true] - If true will set the material on the left bounds wall. + * @param {boolean} [right=true] - If true will set the material on the right bounds wall. + * @param {boolean} [top=true] - If true will set the material on the top bounds wall. + * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. + */ + setWorldMaterial: function (material, left, right, top, bottom) { + + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (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; + } + + }, + + /** + * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. + * If you start to use your own collision groups then your objects will no longer collide with the bounds. + * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. + * + * @method Phaser.Physics.P2#updateBoundsCollisionGroup + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + updateBoundsCollisionGroup: function (setCollisionGroup) { + + if (setCollisionGroup === undefined) { setCollisionGroup = true; } + + var mask = (setCollisionGroup) ? this.boundsCollisionGroup.mask : this.everythingCollisionGroup.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; + } + + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.P2#setBounds + * @param {number} x - The x coordinate of the top-left corner of the bounds. + * @param {number} y - The y coordinate of the top-left corner of the bounds. + * @param {number} width - The width of the bounds. + * @param {number} height - The height of the bounds. + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { + + if (left === undefined) { left = this._boundsLeft; } + if (right === undefined) { right = this._boundsRight; } + if (top === undefined) { top = this._boundsTop; } + if (bottom === undefined) { bottom = this._boundsBottom; } + if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; } + + this.setupWall(left, 'left', x, y, 1.5707963267948966, setCollisionGroup); + this.setupWall(right, 'right', x + width, y, -1.5707963267948966, setCollisionGroup); + this.setupWall(top, 'top', x, y, -3.141592653589793, setCollisionGroup); + this.setupWall(bottom, 'bottom', x, y + height, 0, setCollisionGroup); + + // Remember the bounds settings in case they change later on via World.setBounds + this._boundsLeft = left; + this._boundsRight = right; + this._boundsTop = top; + this._boundsBottom = bottom; + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Internal method called by setBounds. Responsible for creating, updating or + * removing the wall body shapes. + * + * @method Phaser.Physics.P2#setupWall + * @private + * @param {boolean} create - True to create the wall shape, false to remove it. + * @param {string} wall - The wall segment to update. + * @param {number} x - The x coordinate of the wall. + * @param {number} y - The y coordinate of the wall. + * @param {float} angle - The angle of the wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setupWall: function (create, wall, x, y, angle, setCollisionGroup) { + + if (create) + { + // We need a left wall. Do we have one already? + if (this.walls[wall]) + { + this.walls[wall].position = [ this.pxmi(x), this.pxmi(y) ]; + } + else + { + this.walls[wall] = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: angle }); + this.walls[wall].addShape(new p2.Plane()); + + this.world.addBody(this.walls[wall]); + } + + if (setCollisionGroup) + { + this.walls[wall].shapes[0].collisionGroup = this.boundsCollisionGroup.mask; + } + } + else + { + if (this.walls[wall]) + { + this.world.removeBody(this.walls[wall]); + this.walls[wall] = null; + } + } + + }, + + /** + * Pauses the P2 World independent of the game pause state. + * + * @method Phaser.Physics.P2#pause + */ + pause: function() { + + this.paused = true; + + }, + + /** + * Resumes a paused P2 World. + * + * @method Phaser.Physics.P2#resume + */ + resume: function() { + + this.paused = false; + + }, + + /** + * Internal P2 update loop. + * + * @method Phaser.Physics.P2#update + */ + update: function () { + + // Do nothing if the physics engine was paused before + if (this.paused) + { + return; + } + + if (this.useElapsedTime) + { + this.world.step(this.game.time.physicsElapsed); + } + else + { + this.world.step(this.frameRate); + } + + }, + + /** + * Called by Phaser.Physics when a State swap occurs. + * Starts the begin and end Contact listeners again. + * + * @method Phaser.Physics.P2#reset + */ + reset: function () { + + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + this._collisionGroupID = 2; + + this.setBoundsToWorld(true, true, true, true, false); + + }, + + /** + * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. + * + * The P2 world is also cleared: + * + * * Removes all solver equations + * * Removes all constraints + * * Removes all bodies + * * Removes all springs + * * Removes all contact materials + * + * This is called automatically when you switch state. + * + * @method Phaser.Physics.P2#clear + */ + clear: function () { + + this.world.time = 0; + this.world.fixedStepTime = 0; + + // Remove all solver equations + if (this.world.solver && this.world.solver.equations.length) + { + this.world.solver.removeAllEquations(); + } + + // Remove all constraints + var cs = this.world.constraints; + + for (var i = cs.length - 1; i >= 0; i--) + { + this.world.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.world.bodies; + + for (var i = bodies.length - 1; i >= 0; i--) + { + this.world.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.world.springs; + + for (var i = springs.length - 1; i >= 0; i--) + { + this.world.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.world.contactMaterials; + + for (var i = cms.length - 1; i >= 0; i--) + { + this.world.removeContactMaterial(cms[i]); + } + + 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.boundsCollidesWith = []; + + // Remove the world bounds + this.walls = { left: null, right: null, top: null, bottom: null }; + + }, + + /** + * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. + * + * @method Phaser.Physics.P2#destroy + */ + destroy: function () { + + this.clear(); + + this.game = null; + + }, + + /** + * Add a body to the world. + * + * @method Phaser.Physics.P2#addBody + * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. + * @return {boolean} True if the Body was added successfully, otherwise false. + */ + addBody: function (body) { + + if (body.data.world) + { + return false; + } + else + { + this.world.addBody(body.data); + + this.onBodyAdded.dispatch(body); + + return true; + } + + }, + + /** + * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. + * + * @method Phaser.Physics.P2#removeBody + * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. + * @return {Phaser.Physics.P2.Body} The Body that was removed. + */ + removeBody: function (body) { + + if (body.data.world === this.world) + { + this.world.removeBody(body.data); + + this.onBodyRemoved.dispatch(body); + } + + return body; + + }, + + /** + * Adds a Spring to the world. + * + * @method Phaser.Physics.P2#addSpring + * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was added. + */ + addSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.addSpring(spring.data); + } + else + { + this.world.addSpring(spring); + } + + this.onSpringAdded.dispatch(spring); + + return spring; + + }, + + /** + * Removes a Spring from the world. + * + * @method Phaser.Physics.P2#removeSpring + * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was removed. + */ + removeSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.removeSpring(spring.data); + } + else + { + this.world.removeSpring(spring); + } + + this.onSpringRemoved.dispatch(spring); + + return spring; + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createDistanceConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} distance - The distance to keep between the bodies. + * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. + * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.DistanceConstraint} The constraint + */ + createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, 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, localAnchorA, localAnchorB, maxForce)); + } + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createGearConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [angle=0] - The relative angle + * @param {number} [ratio=1] - The gear ratio. + * @return {Phaser.Physics.P2.GearConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * The pivot points are given in world (pixel) coordinates. + * + * @method Phaser.Physics.P2#createRevoluteConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. + * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint + */ + createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + 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, worldPivot)); + } + + }, + + /** + * Locks the relative position between two bodies. + * + * @method Phaser.Physics.P2#createLockConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.LockConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Constraint that only allows bodies to move along a line, relative to each other. + * See http://www.iforce2d.net/b2dtut/joints-prismatic + * + * @method Phaser.Physics.P2#createPrismaticConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. + * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Adds a Constraint to the world. + * + * @method Phaser.Physics.P2#addConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. + */ + addConstraint: function (constraint) { + + this.world.addConstraint(constraint); + + this.onConstraintAdded.dispatch(constraint); + + return constraint; + + }, + + /** + * Removes a Constraint from the world. + * + * @method Phaser.Physics.P2#removeConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. + */ + removeConstraint: function (constraint) { + + this.world.removeConstraint(constraint); + + this.onConstraintRemoved.dispatch(constraint); + + return constraint; + + }, + + /** + * Adds a Contact Material to the world. + * + * @method Phaser.Physics.P2#addContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. + */ + addContactMaterial: function (material) { + + this.world.addContactMaterial(material); + + this.onContactMaterialAdded.dispatch(material); + + return material; + + }, + + /** + * Removes a Contact Material from the world. + * + * @method Phaser.Physics.P2#removeContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. + */ + removeContactMaterial: function (material) { + + this.world.removeContactMaterial(material); + + this.onContactMaterialRemoved.dispatch(material); + + return material; + + }, + + /** + * Gets a Contact Material based on the two given Materials. + * + * @method Phaser.Physics.P2#getContactMaterial + * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. + * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. + * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. + */ + getContactMaterial: function (materialA, materialB) { + + return this.world.getContactMaterial(materialA, materialB); + + }, + + /** + * Sets the given Material against all Shapes owned by all the Bodies in the given array. + * + * @method Phaser.Physics.P2#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. + * @param {array} bodies - An Array of Body objects that the given Material will be set on. + */ + setMaterial: function (material, bodies) { + + var i = bodies.length; + + while (i--) + { + bodies[i].setMaterial(material); + } + + }, + + /** + * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). + * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. + * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. + * + * @method Phaser.Physics.P2#createMaterial + * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. + * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. + * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. + */ + 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; + + }, + + /** + * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. + * + * @method Phaser.Physics.P2#createContactMaterial + * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {object} [options] - Material options object. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. + */ + createContactMaterial: function (materialA, materialB, options) { + + if (materialA === undefined) { materialA = this.createMaterial(); } + if (materialB === undefined) { materialB = this.createMaterial(); } + + var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); + + return this.addContactMaterial(contact); + + }, + + /** + * Populates and returns an array with references to of all current Bodies in the world. + * + * @method Phaser.Physics.P2#getBodies + * @return {array} An array containing all current Bodies in the world. + */ + getBodies: function () { + + var output = []; + var i = this.world.bodies.length; + + while (i--) + { + output.push(this.world.bodies[i].parent); + } + + return output; + + }, + + /** + * Checks the given object to see if it has a p2.Body and if so returns it. + * + * @method Phaser.Physics.P2#getBody + * @param {object} object - The object to check for a p2.Body on. + * @return {p2.Body} The p2.Body, or null if not found. + */ + getBody: function (object) { + + if (object instanceof p2.Body) + { + // Native p2 body + return object; + } + else if (object instanceof Phaser.Physics.P2.Body) + { + // Phaser P2 Body + return object.data; + } + else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) + { + // Sprite, TileSprite, etc + return object.body.data; + } + + return null; + + }, + + /** + * Populates and returns an array of all current Springs in the world. + * + * @method Phaser.Physics.P2#getSprings + * @return {array} An array containing all current Springs in the world. + */ + getSprings: function () { + + var output = []; + var i = this.world.springs.length; + + while (i--) + { + output.push(this.world.springs[i].parent); + } + + return output; + + }, + + /** + * Populates and returns an array of all current Constraints in the world. + * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain + * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type. + * + * @method Phaser.Physics.P2#getConstraints + * @return {array} An array containing all current Constraints in the world. + */ + getConstraints: function () { + + var output = []; + var i = this.world.constraints.length; + + while (i--) + { + output.push(this.world.constraints[i]); + } + + return output; + + }, + + /** + * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to + * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. + * + * @method Phaser.Physics.P2#hitTest + * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. + * @param {Array} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) + * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. + * @return {Array} Array of bodies that overlap the point. + */ + hitTest: function (worldPoint, bodies, precision, filterStatic) { + + if (bodies === undefined) { bodies = this.world.bodies; } + if (precision === undefined) { precision = 5; } + if (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.type === p2.Body.STATIC)) + { + query.push(bodies[i].data); + } + else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC)) + { + query.push(bodies[i]); + } + else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC)) + { + query.push(bodies[i].body.data); + } + } + + return this.world.hitTest(physicsPosition, query, precision); + + }, + + /** + * Converts the current world into a JSON object. + * + * @method Phaser.Physics.P2#toJSON + * @return {object} A JSON representation of the world. + */ + toJSON: function () { + + return this.world.toJSON(); + + }, + + /** + * Creates a new Collision Group and optionally applies it to the given object. + * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. + * + * @method Phaser.Physics.P2#createCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + */ + 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; + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. + * + * @method Phaser.Physics.P2y#setCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + */ + setCollisionGroup: function (object, group) { + + if (object instanceof Phaser.Group) + { + for (var i = 0; i < object.total; i++) + { + if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) + { + object.children[i].body.setCollisionGroup(group); + } + } + } + else + { + object.body.setCollisionGroup(group); + } + + }, + + /** + * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restLength=1] - Rest length of the spring. A number > 0. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @return {Phaser.Physics.P2.Spring} The spring + */ + createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); + } + + }, + + /** + * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createRotationalSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @return {Phaser.Physics.P2.RotationalSpring} The spring + */ + createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Rotational Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping)); + } + + }, + + /** + * Creates a new Body and adds it to the World. + * + * @method Phaser.Physics.P2#createBody + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {Phaser.Physics.P2.Body} The body + */ + createBody: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Creates a new Particle and adds it to the World. + * + * @method Phaser.Physics.P2#createParticle + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + */ + createParticle: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Converts all of the polyline, polygon, and rectangle objects inside a Tiled ObjectGroup into physics bodies that are added to the world. + * Note that the polylines and polygons must be created in such a way that they can withstand polygon decomposition. + * + * @method Phaser.Physics.P2#convertCollisionObjects + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. + * @return {array} An array of the Phaser.Physics.Body objects that have been created. + */ + convertCollisionObjects: function (map, layer, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var output = []; + + for (var i = 0, len = map.collision[layer].length; i < len; i++) + { + // name: json.layers[i].objects[v].name, + // x: json.layers[i].objects[v].x, + // y: json.layers[i].objects[v].y, + // width: json.layers[i].objects[v].width, + // height: json.layers[i].objects[v].height, + // visible: json.layers[i].objects[v].visible, + // properties: json.layers[i].objects[v].properties, + // polyline: json.layers[i].objects[v].polyline + + var object = map.collision[layer][i]; + var shapeData = object.polyline || object.polygon; + + // polyline/polygon shape data present + if (shapeData) + { + var body = this.createBody(object.x, object.y, 0, addToWorld, {}, shapeData); + } + + // tilemap parser sets rectangle=true when parsing object groups + else if (object.rectangle) + { + var body = this.createBody(object.x, object.y, 0, addToWorld); + body.addRectangle(object.width, object.height, object.width / 2, object.height / 2); + } + + // ellipse could be added here, but Tiled ellipses use height/width instead of radius + // (to support oblong ellipses), which p2 doesn't currently support. + + if (body) + { + output.push(body); + } + } + + return output; + + }, + + /** + * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. + * + * @method Phaser.Physics.P2#clearTilemapLayerBodies + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + */ + 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 = 0; + + }, + + /** + * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. + * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. + * Every time you call this method it will destroy any previously created bodies and remove them from the world. + * Therefore understand it's a very expensive operation and not to be done in a core game update loop. + * + * @method Phaser.Physics.P2#convertTilemap + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. + * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. + * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. + */ + convertTilemap: function (map, layer, addToWorld, optimize) { + + layer = map.getLayer(layer); + + if (addToWorld === undefined) { addToWorld = true; } + if (optimize === undefined) { optimize = true; } + + // If the bodies array is already populated we need to nuke it + this.clearTilemapLayerBodies(map, layer); + + var width = 0; + var sx = 0; + var sy = 0; + + for (var y = 0, h = map.layers[layer].height; y < h; y++) + { + width = 0; + + for (var x = 0, w = map.layers[layer].width; x < w; x++) + { + var tile = map.layers[layer].data[y][x]; + + if (tile && tile.index > -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; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpx + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpx: function (v) { + + return v *= 20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters). + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxm + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxm: function (v) { + + return v * 0.05; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpxi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpxi: function (v) { + + return v *= -20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters) and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxmi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxmi: function (v) { + + return v * -0.05; + + } + +}; + +/** +* @name Phaser.Physics.P2#friction +* @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { + + get: function () { + + return this.world.defaultContactMaterial.friction; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.friction = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#restitution +* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { + + get: function () { + + return this.world.defaultContactMaterial.restitution; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.restitution = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#contactMaterial +* @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { + + get: function () { + + return this.world.defaultContactMaterial; + + }, + + set: function (value) { + + this.world.defaultContactMaterial = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applySpringForces +* @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { + + get: function () { + + return this.world.applySpringForces; + + }, + + set: function (value) { + + this.world.applySpringForces = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyDamping +* @property {boolean} applyDamping - Enable to automatically apply body damping each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { + + get: function () { + + return this.world.applyDamping; + + }, + + set: function (value) { + + this.world.applyDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyGravity +* @property {boolean} applyGravity - Enable to automatically apply gravity each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { + + get: function () { + + return this.world.applyGravity; + + }, + + set: function (value) { + + this.world.applyGravity = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#solveConstraints +* @property {boolean} solveConstraints - Enable/disable constraint solving in each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { + + get: function () { + + return this.world.solveConstraints; + + }, + + set: function (value) { + + this.world.solveConstraints = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#time +* @property {boolean} time - The World time. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "time", { + + get: function () { + + return this.world.time; + + } + +}); + +/** +* @name Phaser.Physics.P2#emitImpactEvent +* @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { + + get: function () { + + return this.world.emitImpactEvent; + + }, + + set: function (value) { + + this.world.emitImpactEvent = value; + + } + +}); + +/** +* How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. +* If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. +* @name Phaser.Physics.P2#sleepMode +* @property {number} sleepMode +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", { + + get: function () { + + return this.world.sleepMode; + + }, + + set: function (value) { + + this.world.sleepMode = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#total +* @property {number} total - The total number of bodies in the world. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "total", { + + get: function () { + + return this.world.bodies.length; + + } + +}); + +/* jshint noarg: false */ + +/** +* @author Georgios Kaleadis https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Allow to access a list of created fixture (coming from Body#addPhaserPolygon) +* which itself parse the input from PhysicsEditor with the custom phaser exporter. +* You can access fixtures of a Body by a group index or even by providing a fixture Key. + +* You can set the fixture key and also the group index for a fixture in PhysicsEditor. +* This gives you the power to create a complex body built of many fixtures and modify them +* during runtime (to remove parts, set masks, categories & sensor properties) +* +* @class Phaser.Physics.P2.FixtureList +* @constructor +* @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) +*/ +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 = { + + /** + * @method Phaser.Physics.P2.FixtureList#init + */ + init: function () { + + /** + * @property {object} namedFixtures - Collect all fixtures with a key + * @private + */ + this.namedFixtures = {}; + + /** + * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group + * @private + */ + this.groupedFixtures = []; + + /** + * @property {Array} allFixtures - This is a list of everything in this collection + * @private + */ + this.allFixtures = []; + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setCategory + * @param {number} bit - The bit to set as the collision group. + * @param {string} fixtureKey - Only apply to the fixture with the given key. + */ + setCategory: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionGroup = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMask + * @param {number} bit - The bit to set as the collision mask + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMask: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionMask = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setSensor + * @param {boolean} value - sensor true or false + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setSensor: function (value, fixtureKey) { + + var setter = function(fixture) { + fixture.sensor = value; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMaterial + * @param {Object} material - The contact material for a fixture + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMaterial: function (material, fixtureKey) { + + var setter = function(fixture) { + fixture.material = material; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * Accessor to get either a list of specified fixtures by key or the whole fixture list + * + * @method Phaser.Physics.P2.FixtureList#getFixtures + * @param {array} keys - A list of fixture keys + */ + 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; + } + + }, + + /** + * Accessor to get either a single fixture by its key. + * + * @method Phaser.Physics.P2.FixtureList#getFixtureByKey + * @param {string} key - The key of the fixture. + */ + getFixtureByKey: function (key) { + + return this.namedFixtures[key]; + + }, + + /** + * Accessor to get a group of fixtures by its group index. + * + * @method Phaser.Physics.P2.FixtureList#getGroup + * @param {number} groupID - The group index. + */ + getGroup: function (groupID) { + + return this.groupedFixtures[groupID]; + + }, + + /** + * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon + * + * @method Phaser.Physics.P2.FixtureList#parse + */ + 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)); + } + + }, + + /** + * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. + * + * @method Phaser.Physics.P2.FixtureList#flatten + * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. + */ + 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; + + } + +}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. +* +* @class Phaser.Physics.P2.PointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.PointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; + +/** +* @name Phaser.Physics.P2.PointProxy#x +* @property {number} x - The x property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { + + get: function () { + + return this.world.mpx(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#y +* @property {number} y - The y property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { + + get: function () { + + return this.world.mpx(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#mx +* @property {number} mx - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#my +* @property {number} my - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. +* +* @class Phaser.Physics.P2.InversePointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.InversePointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; + +/** +* @name Phaser.Physics.P2.InversePointProxy#x +* @property {number} x - The x property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#y +* @property {number} y - The y property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#mx +* @property {number} mx - The x property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = -value; + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#my +* @property {number} my - The y property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = -value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. +* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. +* In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. +* By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. +* Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. +* Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. +* +* @class Phaser.Physics.P2.Body +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. +* @param {number} [x=0] - The x coordinate of this Body. +* @param {number} [y=0] - The y coordinate of this Body. +* @param {number} [mass=1] - The default mass of this Body (0 = static). +*/ +Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { + + sprite = sprite || null; + x = x || 0; + y = y || 0; + if (mass === undefined) { mass = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to the P2 World. + */ + this.world = game.physics.p2; + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.P2JS; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. + */ + this.offset = new Phaser.Point(); + + /** + * @property {p2.Body} data - The p2 Body data. + * @protected + */ + this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); + + this.data.parent = this; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. + */ + this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); + + /** + * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body. + */ + this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); + + /** + * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. + */ + this.gravity = new Phaser.Point(); + + /** + * Dispatched when a first contact is created between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 5 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body is in contact with. + * The Shape from this body that caused the contact. + * The Shape from the contact body. + * The Contact Equation data array. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * Dispatched when contact ends between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 4 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body has ended contact with. + * The Shape from this body that caused the original contact. + * The Shape from the contact body. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + /** + * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. + */ + this.collidesWith = []; + + /** + * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. + */ + this.removeNextStep = false; + + /** + * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. + */ + this.debugBody = null; + + /** + * @property {boolean} dirty - Internally used by Sprite.x/y + */ + this.dirty = false; + + /** + * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. + * @private + */ + this._collideWorldBounds = true; + + /** + * @property {object} _bodyCallbacks - Array of Body callbacks. + * @private + */ + this._bodyCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Body callback contexts. + * @private + */ + this._bodyCallbackContext = {}; + + /** + * @property {object} _groupCallbacks - Array of Group callbacks. + * @private + */ + this._groupCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. + * @private + */ + this._groupCallbackContext = {}; + + /** + * @property {boolean} _reset - Internal var. + * @private + */ + this._reset = false; + + // Set-up the default shape + if (sprite) + { + this.setRectangleFromSprite(sprite); + + if (sprite.exists) + { + this.game.physics.p2.addBody(this); + } + } + +}; + +Phaser.Physics.P2.Body.prototype = { + + /** + * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createBodyCallback + * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + 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; + } + } + + }, + + /** + * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * This callback will only fire if this Body has been assigned a collision group. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createGroupCallback + * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + createGroupCallback: function (group, callback, callbackContext) { + + if (callback === null) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + else + { + this._groupCallbacks[group.mask] = callback; + this._groupCallbackContext[group.mask] = callbackContext; + } + + }, + + /** + * Gets the collision bitmask from the groups this body collides with. + * + * @method Phaser.Physics.P2.Body#getCollisionMask + * @return {number} The bitmask. + */ + getCollisionMask: function () { + + var mask = 0; + + if (this._collideWorldBounds) + { + mask = this.game.physics.p2.boundsCollisionGroup.mask; + } + + for (var i = 0; i < this.collidesWith.length; i++) + { + mask = mask | this.collidesWith[i].mask; + } + + return mask; + + }, + + /** + * Updates the collisionMask. + * + * @method Phaser.Physics.P2.Body#updateCollisionMask + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + updateCollisionMask: function (shape) { + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * This also resets the collisionMask. + * + * @method Phaser.Physics.P2.Body#setCollisionGroup + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + setCollisionGroup: function (group, shape) { + + var mask = this.getCollisionMask(); + + if (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; + } + + }, + + /** + * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. + * + * @method Phaser.Physics.P2.Body#clearCollision + * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? + * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. + */ + clearCollision: function (clearGroup, clearMask, shape) { + + if (clearGroup === undefined) { clearGroup = true; } + if (clearMask === undefined) { clearMask = true; } + + if (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; + } + + }, + + /** + * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#removeCollisionGroup + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore. + * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body. + */ + removeCollisionGroup: function (group, clearCallback, shape) { + + if (clearCallback === undefined) { clearCallback = true; } + + var index; + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + index = this.collidesWith.indexOf(group[i]); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + } + else + { + index = this.collidesWith.indexOf(group); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#collides + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. + * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. + * @param {object} [callbackContext] - The context under which the callback will be called. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. + */ + collides: function (group, callback, callbackContext, shape) { + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + if (this.collidesWith.indexOf(group[i]) === -1) + { + this.collidesWith.push(group[i]); + + if (callback) + { + this.createGroupCallback(group[i], callback, callbackContext); + } + } + } + } + else + { + if (this.collidesWith.indexOf(group) === -1) + { + this.collidesWith.push(group); + + if (callback) + { + this.createGroupCallback(group, callback, callbackContext); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Moves the shape offsets so their center of mass becomes the body center of mass. + * + * @method Phaser.Physics.P2.Body#adjustCenterOfMass + */ + adjustCenterOfMass: function () { + + this.data.adjustCenterOfMass(); + this.shapeChanged(); + + }, + + /** + * Gets the velocity of a point in the body. + * + * @method Phaser.Physics.P2.Body#getVelocityAtPoint + * @param {Array} result - A vector to store the result in. + * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from. + * @return {Array} The result vector. + */ + getVelocityAtPoint: function (result, relativePoint) { + + return this.data.getVelocityAtPoint(result, relativePoint); + + }, + + /** + * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. + * + * @method Phaser.Physics.P2.Body#applyDamping + * @param {number} dt - Current time step. + */ + applyDamping: function (dt) { + + this.data.applyDamping(dt); + + }, + + /** + * Apply impulse to a point relative to the body. + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulse + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space. + * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + */ + applyImpulse: function (impulse, worldX, worldY) { + + this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Apply impulse to a point local to the body. + * + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulseLocal + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space. + * @param {number} localX - A local point on the body. + * @param {number} localY - A local point on the body. + */ + applyImpulseLocal: function (impulse, localX, localY) { + + this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]); + + }, + + /** + * Apply force to a world point. + * + * This could for example be a point on the RigidBody surface. Applying force + * this way will add to Body.force and Body.angularForce. + * + * @method Phaser.Physics.P2.Body#applyForce + * @param {Float32Array|Array} force - The force vector to add. + * @param {number} worldX - The world x point to apply the force on. + * @param {number} worldY - The world y point to apply the force on. + */ + applyForce: function (force, worldX, worldY) { + + this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Sets the force on the body to zero. + * + * @method Phaser.Physics.P2.Body#setZeroForce + */ + setZeroForce: function () { + + this.data.setZeroForce(); + + }, + + /** + * If this Body is dynamic then this will zero its angular velocity. + * + * @method Phaser.Physics.P2.Body#setZeroRotation + */ + setZeroRotation: function () { + + this.data.angularVelocity = 0; + + }, + + /** + * If this Body is dynamic then this will zero its velocity on both axis. + * + * @method Phaser.Physics.P2.Body#setZeroVelocity + */ + setZeroVelocity: function () { + + this.data.velocity[0] = 0; + this.data.velocity[1] = 0; + + }, + + /** + * Sets the Body damping and angularDamping to zero. + * + * @method Phaser.Physics.P2.Body#setZeroDamping + */ + setZeroDamping: function () { + + this.data.damping = 0; + this.data.angularDamping = 0; + + }, + + /** + * Transform a world point to local body frame. + * + * @method Phaser.Physics.P2.Body#toLocalFrame + * @param {Float32Array|Array} out - The vector to store the result in. + * @param {Float32Array|Array} worldPoint - The input world vector. + */ + toLocalFrame: function (out, worldPoint) { + + return this.data.toLocalFrame(out, worldPoint); + + }, + + /** + * Transform a local point to world frame. + * + * @method Phaser.Physics.P2.Body#toWorldFrame + * @param {Array} out - The vector to store the result in. + * @param {Array} localPoint - The input local vector. + */ + toWorldFrame: function (out, localPoint) { + + return this.data.toWorldFrame(out, localPoint); + + }, + + /** + * This will rotate the Body by the given speed to the left (counter-clockwise). + * + * @method Phaser.Physics.P2.Body#rotateLeft + * @param {number} speed - The speed at which it should rotate. + */ + rotateLeft: function (speed) { + + this.data.angularVelocity = this.world.pxm(-speed); + + }, + + /** + * This will rotate the Body by the given speed to the left (clockwise). + * + * @method Phaser.Physics.P2.Body#rotateRight + * @param {number} speed - The speed at which it should rotate. + */ + rotateRight: function (speed) { + + this.data.angularVelocity = this.world.pxm(speed); + + }, + + /** + * Moves the Body forwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveForward + * @param {number} speed - The speed at which it should move forwards. + */ + 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); + + }, + + /** + * Moves the Body backwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveBackward + * @param {number} speed - The speed at which it should move backwards. + */ + 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)); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrust + * @param {number} speed - The speed at which it should thrust. + */ + 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); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustLeft + * @param {number} speed - The speed at which it should move to the left. + */ + thrustLeft: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] += magnitude * Math.cos(angle); + this.data.force[1] += magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustRight + * @param {number} speed - The speed at which it should move to the right. + */ + thrustRight: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] -= magnitude * Math.cos(angle); + this.data.force[1] -= magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#reverse + * @param {number} speed - The speed at which it should reverse. + */ + 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); + + }, + + /** + * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveLeft + * @param {number} speed - The speed at which it should move to the left, in pixels per second. + */ + moveLeft: function (speed) { + + this.data.velocity[0] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveRight + * @param {number} speed - The speed at which it should move to the right, in pixels per second. + */ + moveRight: function (speed) { + + this.data.velocity[0] = this.world.pxmi(speed); + + }, + + /** + * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveUp + * @param {number} speed - The speed at which it should move up, in pixels per second. + */ + moveUp: function (speed) { + + this.data.velocity[1] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveDown + * @param {number} speed - The speed at which it should move down, in pixels per second. + */ + moveDown: function (speed) { + + this.data.velocity[1] = this.world.pxmi(speed); + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#preUpdate + * @protected + */ + preUpdate: function () { + + this.dirty = true; + + if (this.removeNextStep) + { + this.removeFromWorld(); + this.removeNextStep = false; + } + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#postUpdate + * @protected + */ + postUpdate: function () { + + this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x; + this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y; + + if (!this.fixedRotation) + { + this.sprite.rotation = this.data.angle; + } + + if (this.debugBody) + { + this.debugBody.updateSpriteTransform(); + } + + this.dirty = false; + + }, + + /** + * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. + * + * @method Phaser.Physics.P2.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new x position of the Body. + * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. + * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. + */ + reset: function (x, y, resetDamping, resetMass) { + + if (resetDamping === undefined) { resetDamping = false; } + if (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; + + }, + + /** + * Adds this physics body to the world. + * + * @method Phaser.Physics.P2.Body#addToWorld + */ + addToWorld: function () { + + if (this.game.physics.p2._toRemove) + { + for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) + { + if (this.game.physics.p2._toRemove[i] === this) + { + this.game.physics.p2._toRemove.splice(i, 1); + } + } + } + + if (this.data.world !== this.game.physics.p2.world) + { + this.game.physics.p2.addBody(this); + } + + }, + + /** + * Removes this physics body from the world. + * + * @method Phaser.Physics.P2.Body#removeFromWorld + */ + removeFromWorld: function () { + + if (this.data.world === this.game.physics.p2.world) + { + this.game.physics.p2.removeBodyNextStep(this); + } + + }, + + /** + * Destroys this Body and all references it holds to other objects. + * + * @method Phaser.Physics.P2.Body#destroy + */ + destroy: function () { + + this.removeFromWorld(); + + this.clearShapes(); + + this._bodyCallbacks = {}; + this._bodyCallbackContext = {}; + this._groupCallbacks = {}; + this._groupCallbackContext = {}; + + if (this.debugBody) + { + this.debugBody.destroy(true, true); + } + + this.debugBody = null; + + if (this.sprite) + { + this.sprite.body = null; + this.sprite = null; + } + + }, + + /** + * Removes all Shapes from this Body. + * + * @method Phaser.Physics.P2.Body#clearShapes + */ + clearShapes: function () { + + var i = this.data.shapes.length; + + while (i--) + { + this.data.removeShape(this.data.shapes[i]); + } + + this.shapeChanged(); + + }, + + /** + * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#addShape + + * @param {p2.Shape} shape - The shape to add to the body. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Shape} The shape that was added to the body. + */ + addShape: function (shape, offsetX, offsetY, rotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (rotation === undefined) { rotation = 0; } + + this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); + this.shapeChanged(); + + return shape; + + }, + + /** + * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Circle} The Circle shape that was added to the Body. + */ + addCircle: function (radius, offsetX, offsetY, rotation) { + + var shape = new p2.Circle({ radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addRectangle + * @param {number} width - The width of the rectangle in pixels. + * @param {number} height - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Box} The shape that was added to the Body. + */ + addRectangle: function (width, height, offsetX, offsetY, rotation) { + + var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addPlane + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Plane} The Plane shape that was added to the Body. + */ + addPlane: function (offsetX, offsetY, rotation) { + + var shape = new p2.Plane(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addParticle + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Particle} The Particle shape that was added to the Body. + */ + addParticle: function (offsetX, offsetY, rotation) { + + var shape = new p2.Particle(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Line shape to this Body. + * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addLine + * @param {number} length - The length of this line (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Line} The Line shape that was added to the Body. + */ + addLine: function (length, offsetX, offsetY, rotation) { + + var shape = new p2.Line({ length: this.world.pxm(length)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Capsule shape to this Body. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCapsule + * @param {number} length - The distance between the end points in pixels. + * @param {number} radius - Radius of the capsule in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Capsule} The Capsule shape that was added to the Body. + */ + addCapsule: function (length, radius, offsetX, offsetY, rotation) { + + var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. + * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. + * + * @method Phaser.Physics.P2.Body#addPolygon + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...]. In the first form **the array will mutate**. + * Or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {boolean} True on success, else false. + */ + addPolygon: function (options, points) { + + options = options || {}; + + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments, 1); + } + + var path = []; + + // Did they pass in a single array of points? + if (points.length === 1 && Array.isArray(points[0])) + { + path = points[0].slice(0); + } + else if (Array.isArray(points[0])) + { + path = points.slice(); + } + else if (typeof points[0] === 'number') + { + // We've a list of numbers + for (var i = 0, len = points.length; i < len; i += 2) + { + path.push([points[i], points[i + 1]]); + } + } + + // top and tail + var idx = path.length - 1; + + if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) + { + path.pop(); + } + + // Now process them into p2 values + for (var p = 0; p < path.length; p++) + { + path[p][0] = this.world.pxmi(path[p][0]); + path[p][1] = this.world.pxmi(path[p][1]); + } + + var result = this.data.fromPolygon(path, options); + + this.shapeChanged(); + + return result; + + }, + + /** + * Remove a shape from the body. Will automatically update the mass properties and bounding radius. + * + * @method Phaser.Physics.P2.Body#removeShape + * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. + * @return {boolean} True if the shape was found and removed, else false. + */ + removeShape: function (shape) { + + var result = this.data.removeShape(shape); + + this.shapeChanged(); + + return result; + }, + + /** + * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + */ + setCircle: function (radius, offsetX, offsetY, rotation) { + + this.clearShapes(); + + return this.addCircle(radius, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. + * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangle + * @param {number} [width=16] - The width of the rectangle in pixels. + * @param {number} [height=16] - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangle: function (width, height, offsetX, offsetY, rotation) { + + if (width === undefined) { width = 16; } + if (height === undefined) { height = 16; } + + this.clearShapes(); + + return this.addRectangle(width, height, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. + * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. + * If no Sprite is given it defaults to using the parent of this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangleFromSprite + * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangleFromSprite: function (sprite) { + + if (sprite === undefined) { sprite = this.sprite; } + + this.clearShapes(); + + return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); + + }, + + /** + * Adds the given Material to all Shapes that belong to this Body. + * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. + * + * @method Phaser.Physics.P2.Body#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. + */ + setMaterial: function (material, shape) { + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].material = material; + } + } + else + { + shape.material = material; + } + + }, + + /** + * Updates the debug draw if any body shapes change. + * + * @method Phaser.Physics.P2.Body#shapeChanged + */ + shapeChanged: function() { + + if (this.debugBody) + { + this.debugBody.draw(); + } + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * The shape data format is based on the output of the + * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for + * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor} + * + * @method Phaser.Physics.P2.Body#addPhaserPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. + * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. + * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList + */ + addPhaserPolygon: function (key, object) { + + var data = this.game.cache.getPhysicsData(key, object); + var createdFixtures = []; + + // Cycle through the fixtures + for (var i = 0; i < data.length; i++) + { + var fixtureData = data[i]; + var shapesOfFixture = this.addFixture(fixtureData); + + // Always add to a group + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); + + // if (unique) fixture key is provided + if (fixtureData.fixtureKey) + { + createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; + } + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return createdFixtures; + + }, + + /** + * Add a polygon fixture. This is used during #loadPolygon. + * + * @method Phaser.Physics.P2.Body#addFixture + * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. + * @return {array} An array containing the generated shapes for the given polygon. + */ + addFixture: function (fixtureData) { + + var generatedShapes = []; + + if (fixtureData.circle) + { + var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) }); + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + var offset = p2.vec2.create(); + offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); + offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); + + this.data.addShape(shape, offset); + generatedShapes.push(shape); + } + else + { + var polygons = fixtureData.polygons; + var cm = p2.vec2.create(); + + for (var i = 0; i < polygons.length; i++) + { + var shapes = polygons[i]; + var vertices = []; + + for (var s = 0; s < shapes.length; s += 2) + { + vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); + } + + var shape = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== shape.vertices.length; j++) + { + var v = shape.vertices[j]; + p2.vec2.sub(v, v, shape.centerOfMass); + } + + p2.vec2.scale(cm, shape.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + shape.updateTriangles(); + shape.updateCenterOfMass(); + shape.updateBoundingRadius(); + + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + this.data.addShape(shape, cm); + + generatedShapes.push(shape); + } + } + + return generatedShapes; + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * + * As well as reading the data from the Cache you can also pass `null` as the first argument and a + * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance. + * + * For more details see the format of the Lime / Corona Physics Editor export. + * + * @method Phaser.Physics.P2.Body#loadPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the + * data as the 2nd argument. + * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from, + * or if key is null pass the actual physics data object itself as this parameter. + * @param {number} [scale=1] - Optionally resize the loaded polygon. + * @return {boolean} True on success, else false. + */ + loadPolygon: function (key, object, scale) { + + if (key === null) + { + var data = object; + } + else + { + var data = this.game.cache.getPhysicsData(key, object); + } + + if (typeof scale !== "number") + { + scale = 1; + } + + // We've multiple Convex shapes, they should be CCW automatically + var cm = p2.vec2.create(); + + for (var i = 0; i < data.length; i++) + { + var vertices = []; + + for (var s = 0; s < data[i].shape.length; s += 2) + { + vertices.push([ + this.world.pxmi(data[i].shape[s] * scale), + this.world.pxmi(data[i].shape[s + 1] * scale) + ]); + } + + var c = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== c.vertices.length; j++) + { + var v = c.vertices[j]; + p2.vec2.sub(v, v, c.centerOfMass); + } + + p2.vec2.scale(cm, c.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + c.updateTriangles(); + c.updateCenterOfMass(); + c.updateBoundingRadius(); + + this.data.addShape(c, cm); + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return true; + + } + +}; + +Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; + +/** + * Dynamic body. Dynamic bodies body can move and respond to collisions and forces. + * @property DYNAMIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.DYNAMIC = 1; + +/** + * Static body. Static bodies do not move, and they do not respond to forces or collision. + * @property STATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.STATIC = 2; + +/** + * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. + * @property KINEMATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.KINEMATIC = 4; + +/** +* @name Phaser.Physics.P2.Body#static +* @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.STATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#dynamic +* @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#kinematic +* @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.KINEMATIC; + this.mass = 4; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#allowSleep +* @property {boolean} allowSleep - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { + + get: function () { + + return this.data.allowSleep; + + }, + + set: function (value) { + + if (value !== this.data.allowSleep) + { + this.data.allowSleep = value; + } + + } + +}); + +/** +* The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. +* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. +* If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#angle +* @property {number} angle - The angle of this Body in degrees. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); + + }, + + set: function(value) { + + this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#angularDamping +* @property {number} angularDamping - The angular damping acting acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { + + get: function () { + + return this.data.angularDamping; + + }, + + set: function (value) { + + this.data.angularDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularForce +* @property {number} angularForce - The angular force acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { + + get: function () { + + return this.data.angularForce; + + }, + + set: function (value) { + + this.data.angularForce = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularVelocity +* @property {number} angularVelocity - The angular velocity of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { + + get: function () { + + return this.data.angularVelocity; + + }, + + set: function (value) { + + this.data.angularVelocity = value; + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#damping +* @property {number} damping - The linear damping acting on the body in the velocity direction. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { + + get: function () { + + return this.data.damping; + + }, + + set: function (value) { + + this.data.damping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#fixedRotation +* @property {boolean} fixedRotation - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { + + get: function () { + + return this.data.fixedRotation; + + }, + + set: function (value) { + + if (value !== this.data.fixedRotation) + { + this.data.fixedRotation = value; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#inertia +* @property {number} inertia - The inertia of the body around the Z axis.. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { + + get: function () { + + return this.data.inertia; + + }, + + set: function (value) { + + this.data.inertia = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#mass +* @property {number} mass - The mass of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { + + get: function () { + + return this.data.mass; + + }, + + set: function (value) { + + if (value !== this.data.mass) + { + this.data.mass = value; + this.data.updateMassProperties(); + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#motionState +* @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { + + get: function () { + + return this.data.type; + + }, + + set: function (value) { + + if (value !== this.data.type) + { + this.data.type = value; + } + + } + +}); + +/** +* The angle of the Body in radians. +* If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#rotation +* @property {number} rotation - The angle of this Body in radians. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { + + get: function() { + + return this.data.angle; + + }, + + set: function(value) { + + this.data.angle = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#sleepSpeedLimit +* @property {number} sleepSpeedLimit - . +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { + + get: function () { + + return this.data.sleepSpeedLimit; + + }, + + set: function (value) { + + this.data.sleepSpeedLimit = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#x +* @property {number} x - The x coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.data.position[0]); + + }, + + set: function (value) { + + this.data.position[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#y +* @property {number} y - The y coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.data.position[1]); + + }, + + set: function (value) { + + this.data.position[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#id +* @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { + + get: function () { + + return this.data.id; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#debug +* @property {boolean} debug - Enable or disable debug drawing of this body +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { + + get: function () { + + return (this.debugBody !== null); + + }, + + set: function (value) { + + if (value && !this.debugBody) + { + // This will be added to the global space + this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); + } + else if (!value && this.debugBody) + { + this.debugBody.destroy(); + this.debugBody = null; + } + + } + +}); + +/** +* A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. +* Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. +* Also note that when you set this it will only affect Body shapes that already exist. If you then add further shapes to your Body +* after setting this it will *not* proactively set them to collide with the bounds. +* +* @name Phaser.Physics.P2.Body#collideWorldBounds +* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? +* @default true +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { + + get: function () { + + return this._collideWorldBounds; + + }, + + set: function (value) { + + if (value && !this._collideWorldBounds) + { + this._collideWorldBounds = true; + this.updateCollisionMask(); + } + else if (!value && this._collideWorldBounds) + { + this._collideWorldBounds = false; + this.updateCollisionMask(); + } + + } + +}); + +/** +* @author George https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Draws a P2 Body to a Graphics instance for visual debugging. +* Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. +* So use sparingly and rarely (if ever) in production code. +* +* Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you +* manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will +* need to manually adjust its BodyDebug as well. +* +* @class Phaser.Physics.P2.BodyDebug +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. +* @param {object} settings - Settings object. +*/ +Phaser.Physics.P2.BodyDebug = function(game, body, settings) { + + Phaser.Group.call(this, game); + + /** + * @property {object} defaultSettings - Default debug settings. + * @private + */ + var defaultSettings = { + pixelsPerLengthUnit: game.physics.p2.mpx(1), + debugPolygons: false, + lineWidth: 1, + alpha: 0.5 + }; + + this.settings = Object.assign(defaultSettings, settings); + + /** + * @property {number} ppu - Pixels per Length Unit. + */ + this.ppu = this.settings.pixelsPerLengthUnit; + this.ppu = -1 * this.ppu; + + /** + * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. + */ + this.body = body; + + /** + * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. + */ + this.canvas = new Phaser.Graphics(game); + + this.canvas.alpha = this.settings.alpha; + + this.add(this.canvas); + + this.draw(); + + this.updateSpriteTransform(); + +}; + +Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); +Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; + +Object.assign(Phaser.Physics.P2.BodyDebug.prototype, { + + /** + * Core update. + * + * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform + */ + updateSpriteTransform: function() { + + this.position.x = this.body.position[0] * this.ppu; + this.position.y = this.body.position[1] * this.ppu; + this.rotation = this.body.angle; + + }, + + /** + * Draws the P2 shapes to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#draw + */ + draw: function() { + + var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; + + obj = this.body; + sprite = this.canvas; + sprite.clear(); + color = parseInt(this.randomPastelHex(), 16); + lineColor = 0xff0000; + lw = this.lineWidth; + + if (obj instanceof p2.Body && obj.shapes.length) + { + var l = obj.shapes.length; + + i = 0; + + while (i !== l) + { + child = obj.shapes[i]; + offset = child.position || 0; + angle = child.angle || 0; + + if (child instanceof p2.Circle) + { + this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); + } + else if (child instanceof p2.Capsule) + { + this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw); + } + 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.Box) + { + this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); + } + else if (child instanceof p2.Convex) + { + verts = []; + vrot = p2.vec2.create(); + + for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _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]); + } + + i++; + } + } + + }, + + /** + * Draws a p2.Box to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawRectangle + * @private + */ + drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + g.beginFill(fillColor); + g.drawRect(x - w / 2, y - h / 2, w, h); + + }, + + /** + * Draws a p2.Circle to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCircle + * @private + */ + drawCircle: function(g, x, y, angle, radius, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + g.lineStyle(lineWidth, 0x000000, 1); + g.beginFill(color, 1.0); + g.drawCircle(x, y, -radius*2); + g.endFill(); + g.moveTo(x, y); + g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); + + }, + + /** + * Draws a p2.Line to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawLine + * @private + */ + drawLine: function(g, len, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth * 5, color, 1); + g.moveTo(-len / 2, 0); + g.lineTo(len / 2, 0); + + }, + + /** + * Draws a p2.Convex to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawConvex + * @private + */ + drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { + + var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + 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 = [0xff0000, 0x00ff00, 0x0000ff]; + 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, 0x000000, 1); + return g.drawCircle(offset[0], offset[1], lineWidth * 2); + } + + }, + + /** + * Draws a p2.Path to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPath + * @private + */ + drawPath: function(g, path, color, fillColor, lineWidth) { + + var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + if (typeof fillColor === "number") + { + g.beginFill(fillColor); + } + + lastx = null; + lasty = null; + i = 0; + + while (i < path.length) + { + v = path[i]; + x = v[0]; + y = v[1]; + + if (x !== lastx || y !== lasty) + { + if (i === 0) + { + g.moveTo(x, y); + } + else + { + p1x = lastx; + p1y = lasty; + p2x = x; + p2y = y; + p3x = path[(i + 1) % path.length][0]; + p3y = path[(i + 1) % path.length][1]; + area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); + + if (area !== 0) + { + g.lineTo(x, y); + } + } + lastx = x; + lasty = y; + } + + i++; + + } + + if (typeof fillColor === "number") + { + g.endFill(); + } + + if (path.length > 2 && typeof fillColor === "number") + { + g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); + g.lineTo(path[0][0], path[0][1]); + } + + }, + + /** + * Draws a p2.Plane to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPlane + * @private + */ + drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { + + var max, xd, yd; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + + 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); + + }, + + /** + * Draws a p2.Capsule to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCapsule + * @private + */ + drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + // Draw circles at ends + var c = Math.cos(angle); + var s = Math.sin(angle); + + g.beginFill(fillColor, 1); + g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2); + g.drawCircle( len/2*c + x, len/2*s + y, -radius * 2); + g.endFill(); + + // Draw rectangle + g.lineStyle(lineWidth, color, 0); + g.beginFill(fillColor, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.endFill(); + + // Draw lines in between + g.lineStyle(lineWidth, color, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + + }, + + /** + * Picks a random pastel color. + * + * @method Phaser.Physics.P2.BodyDebug#randomPastelHex + * @private + */ + 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); + + }, + + /** + * Converts from RGB to Hex. + * + * @method Phaser.Physics.P2.BodyDebug#rgbToHex + * @private + */ + rgbToHex: function(r, g, b) { + return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); + }, + + /** + * Component to hex conversion. + * + * @method Phaser.Physics.P2.BodyDebug#componentToHex + * @private + */ + componentToHex: function(c) { + + var hex; + hex = c.toString(16); + + if (hex.length === 2) + { + return hex; + } + else + { + return hex + '0'; + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.Spring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restLength=1] - Rest length of the spring. A number > 0. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +*/ +Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restLength === undefined) { restLength = 1; } + if (stiffness === undefined) { stiffness = 100; } + if (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]) ]; + } + + /** + * @property {p2.LinearSpring} data - The actual p2 spring object. + */ + this.data = new p2.LinearSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.RotationalSpring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +*/ +Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restAngle === undefined) { restAngle = null; } + if (stiffness === undefined) { stiffness = 100; } + if (damping === undefined) { damping = 1; } + + if (restAngle) + { + restAngle = world.pxm(restAngle); + } + + var options = { + restAngle: restAngle, + stiffness: stiffness, + damping: damping + }; + + /** + * @property {p2.RotationalSpring} data - The actual p2 spring object. + */ + this.data = new p2.RotationalSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A P2 Material. +* +* \o/ ~ "Because I'm a Material girl" +* +* @class Phaser.Physics.P2.Material +* @constructor +* @param {string} name - The user defined name given to this Material. +*/ +Phaser.Physics.P2.Material = function (name) { + + /** + * @property {string} name - The user defined name given to this Material. + * @default + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Defines a physics material +* +* @class Phaser.Physics.P2.ContactMaterial +* @constructor +* @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. +* @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. +* @param {object} [options] - Additional configuration options. +*/ +Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { + + /** + * @property {number} id - The contact material identifier. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. + */ + + /** + * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. + */ + + /** + * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. + */ + + /** + * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + */ + + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Collision Group +* +* @class Phaser.Physics.P2.CollisionGroup +* @constructor +* @param {number} bitmask - The CollisionGroup bitmask. +*/ +Phaser.Physics.P2.CollisionGroup = function (bitmask) { + + /** + * @property {number} mask - The CollisionGroup bitmask. + */ + this.mask = bitmask; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A constraint that tries to keep the distance between two bodies constant. +* +* @class Phaser.Physics.P2.DistanceConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} distance - The distance to keep between the bodies. +* @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. +* @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. +* @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply. +*/ +Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { + + if (distance === undefined) { distance = 100; } + if (localAnchorA === undefined) { localAnchorA = [0, 0]; } + if (localAnchorB === undefined) { localAnchorB = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + distance = world.pxm(distance); + + localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ]; + localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ]; + + var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce }; + + p2.DistanceConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); +Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.GearConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [angle=0] - The relative angle +* @param {number} [ratio=1] - The gear ratio. +*/ +Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { + + if (angle === undefined) { angle = 0; } + if (ratio === undefined) { ratio = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Locks the relative position between two bodies. +* +* @class Phaser.Physics.P2.LockConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [angle=0] - The angle of bodyB in bodyA's frame. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { + + if (offset === undefined) { offset = [0, 0]; } + if (angle === undefined) { angle = 0; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.PrismaticConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. +* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { + + if (lockRotation === undefined) { lockRotation = true; } + if (anchorA === undefined) { anchorA = [0, 0]; } + if (anchorB === undefined) { anchorB = [0, 0]; } + if (axis === undefined) { axis = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* The pivot points are given in world (pixel) coordinates. +* +* @class Phaser.Physics.P2.RevoluteConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {p2.Body} bodyB - Second connected body. +* @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. +* @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. +*/ +Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + if (worldPivot === undefined) { worldPivot = null; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; + pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; + + if (worldPivot) + { + worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ]; + } + + var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce }; + + p2.RevoluteConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); +Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image Collection is a special tileset containing mulitple images, with no slicing into each image. +* +* Image Collections are normally created automatically when Tiled data is loaded. +* +* @class Phaser.ImageCollection +* @constructor +* @param {string} name - The name of the image collection in the map data. +* @param {integer} firstgid - The first image index this image collection contains. +* @param {integer} [width=32] - Width of widest image (in pixels). +* @param {integer} [height=32] - Height of tallest image (in pixels). +* @param {integer} [margin=0] - The margin around all images in the collection (in pixels). +* @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). +* @param {object} [properties={}] - Custom Image Collection properties. +*/ +Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Image Collection. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of the widest image (in pixels). + * @property {integer} imageWidth + * @readonly + */ + this.imageWidth = width | 0; + + /** + * The height of the tallest image (in pixels). + * @property {integer} imageHeight + * @readonly + */ + this.imageHeight = height | 0; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageMarge + * @readonly + */ + // Modified internally + this.imageMargin = margin | 0; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageSpacing + * @readonly + */ + this.imageSpacing = spacing | 0; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached images that are a part of this collection. + * @property {array} images + * @readonly + */ + // Modified internally + this.images = []; + + /** + * The total number of images in the image collection. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; +}; + +Phaser.ImageCollection.prototype = { + + /** + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.ImageCollection#containsImageIndex + * @param {integer} imageIndex - The image index to search for. + * @return {boolean} True if this Image Collection contains the given index. + */ + containsImageIndex: function (imageIndex) { + + return ( + imageIndex >= this.firstgid && + imageIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Add an image to this Image Collection. + * + * @method Phaser.ImageCollection#addImage + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + */ + addImage: function (gid, image) { + + this.images.push({ gid: gid, image: image }); + this.total++; + + } + +}; + +Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile is a representation of a single tile within the Tilemap. +* +* @class Phaser.Tile +* @constructor +* @param {object} layer - The layer in the Tilemap data that this tile belongs to. +* @param {number} index - The index of this tile type in the core map data. +* @param {number} x - The x coordinate of this tile. +* @param {number} y - The y coordinate of this tile. +* @param {number} width - Width of the tile. +* @param {number} height - Height of the tile. +*/ +Phaser.Tile = function (layer, index, x, y, width, height) { + + /** + * @property {object} layer - The layer in the Tilemap data that this tile belongs to. + */ + this.layer = layer; + + /** + * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. + */ + this.index = index; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.x = x; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.y = y; + + /** + * @property {number} rotation - The rotation angle of this tile. + */ + this.rotation = 0; + + /** + * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not. + */ + this.flipped = false; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.worldX = x * width; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.worldY = y * height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.height = height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.centerX = Math.abs(width / 2); + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.centerY = Math.abs(height / 2); + + /** + * @property {number} alpha - The alpha value at which this tile is drawn to the canvas. + */ + this.alpha = 1; + + /** + * @property {object} properties - Tile specific properties. + */ + this.properties = {}; + + /** + * @property {boolean} scanned - Has this tile been walked / turned into a poly? + */ + this.scanned = false; + + /** + * @property {boolean} faceTop - Is the top of this tile an interesting edge? + */ + this.faceTop = false; + + /** + * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge? + */ + this.faceBottom = false; + + /** + * @property {boolean} faceLeft - Is the left of this tile an interesting edge? + */ + this.faceLeft = false; + + /** + * @property {boolean} faceRight - Is the right of this tile an interesting edge? + */ + this.faceRight = false; + + /** + * @property {boolean} collideLeft - Indicating collide with any object on the left. + * @default + */ + this.collideLeft = false; + + /** + * @property {boolean} collideRight - Indicating collide with any object on the right. + * @default + */ + this.collideRight = false; + + /** + * @property {boolean} collideUp - Indicating collide with any object on the top. + * @default + */ + this.collideUp = false; + + /** + * @property {boolean} collideDown - Indicating collide with any object on the bottom. + * @default + */ + this.collideDown = false; + + /** + * @property {function} collisionCallback - Tile collision callback. + * @default + */ + this.collisionCallback = null; + + /** + * @property {object} collisionCallbackContext - The context in which the collision callback will be called. + * @default + */ + this.collisionCallbackContext = this; + + /** + * @property {boolean} debug + * @default + */ + this.debug = false; + +}; + +Phaser.Tile.prototype = { + + /** + * Check if the given x and y world coordinates are within this Tile. + * + * @method Phaser.Tile#containsPoint + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ + containsPoint: function (x, y) { + + return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom); + + }, + + /** + * Check for intersection with this tile. + * + * @method Phaser.Tile#intersects + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + */ + 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; + + }, + + /** + * Set a callback to be called when this tile is hit by an object. + * The callback must true true for collision processing to take place. + * + * @method Phaser.Tile#setCollisionCallback + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + */ + setCollisionCallback: function (callback, context) { + + this.collisionCallback = callback; + this.collisionCallbackContext = context; + + }, + + /** + * Clean up memory. + * + * @method Phaser.Tile#destroy + */ + destroy: function () { + + this.collisionCallback = null; + this.collisionCallbackContext = null; + this.properties = null; + + }, + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tile#setCollision + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} right - Indicating collide with any object on the right. + * @param {boolean} up - Indicating collide with any object on the top. + * @param {boolean} down - Indicating collide with any object on the bottom. + */ + setCollision: function (left, right, up, down) { + + this.collideLeft = left; + this.collideRight = right; + this.collideUp = up; + this.collideDown = down; + + this.faceLeft = left; + this.faceRight = right; + this.faceTop = up; + this.faceBottom = down; + + }, + + /** + * Reset collision status flags. + * + * @method Phaser.Tile#resetCollision + */ + 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; + + }, + + /** + * Is this tile interesting? + * + * @method Phaser.Tile#isInteresting + * @param {boolean} collides - If true will check any collides value. + * @param {boolean} faces - If true will check any face value. + * @return {boolean} True if the Tile is interesting, otherwise false. + */ + isInteresting: function (collides, faces) { + + if (collides && faces) + { + // Does this tile have any collide flags OR interesting face? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback); + } + else if (collides) + { + // Does this tile collide? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + else if (faces) + { + // Does this tile have an interesting face? + return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); + } + + return false; + + }, + + /** + * Copies the tile data and properties from the given tile to this tile. + * + * @method Phaser.Tile#copy + * @param {Phaser.Tile} tile - The tile to copy from. + */ + 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; + +/** +* @name Phaser.Tile#collides +* @property {boolean} collides - True if this tile can collide on any of its faces. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "collides", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + +}); + +/** +* @name Phaser.Tile#canCollide +* @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "canCollide", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); + } + +}); + +/** +* @name Phaser.Tile#left +* @property {number} left - The x value in pixels. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "left", { + + get: function () { + return this.worldX; + } + +}); + +/** +* @name Phaser.Tile#right +* @property {number} right - The sum of the x and width properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "right", { + + get: function () { + return this.worldX + this.width; + } + +}); + +/** +* @name Phaser.Tile#top +* @property {number} top - The y value. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "top", { + + get: function () { + return this.worldY; + } + +}); + +/** +* @name Phaser.Tile#bottom +* @property {number} bottom - The sum of the y and height properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "bottom", { + + get: function () { + return this.worldY + this.height; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. +* +* Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org +* +* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. +* When using CSV data you must provide the key and the tileWidth and tileHeight parameters. +* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. +* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. +* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. +* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. +* +* @class Phaser.Tilemap +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. +* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +*/ +Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {string} key - The key of this map data in the Phaser.Cache. + */ + this.key = key; + + var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height); + + if (data === null) + { + return; + } + + /** + * @property {number} width - The width of the map (in tiles). + */ + this.width = data.width; + + /** + * @property {number} height - The height of the map (in tiles). + */ + this.height = data.height; + + /** + * @property {number} tileWidth - The base width of the tiles in the map (in pixels). + */ + this.tileWidth = data.tileWidth; + + /** + * @property {number} tileHeight - The base height of the tiles in the map (in pixels). + */ + this.tileHeight = data.tileHeight; + + /** + * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + */ + this.orientation = data.orientation; + + /** + * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + */ + this.format = data.format; + + /** + * @property {number} version - The version of the map data (as specified in Tiled, usually 1). + */ + this.version = data.version; + + /** + * @property {object} properties - Map specific properties as specified in Tiled. + */ + this.properties = data.properties; + + /** + * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth. + */ + this.widthInPixels = data.widthInPixels; + + /** + * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight. + */ + this.heightInPixels = data.heightInPixels; + + /** + * @property {array} layers - An array of Tilemap layer data. + */ + this.layers = data.layers; + + /** + * @property {array} tilesets - An array of Tilesets. + */ + this.tilesets = data.tilesets; + + /** + * @property {array} imagecollections - An array of Image Collections. + */ + this.imagecollections = data.imagecollections; + + /** + * @property {array} tiles - The super array of Tiles. + */ + this.tiles = data.tiles; + + /** + * @property {array} objects - An array of Tiled Object Layers. + */ + this.objects = data.objects; + + /** + * @property {array} collideIndexes - An array of tile indexes that collide. + */ + this.collideIndexes = []; + + /** + * @property {array} collision - An array of collision data (polylines, etc). + */ + this.collision = data.collision; + + /** + * @property {array} images - An array of Tiled Image Layers. + */ + this.images = data.images; + + /** + * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data. + */ + this.enableDebug = false; + + /** + * @property {number} currentLayer - The current layer. + */ + this.currentLayer = 0; + + /** + * @property {array} debugMap - Map data used for debug values only. + */ + this.debugMap = []; + + /** + * @property {array} _results - Internal var. + * @private + */ + this._results = []; + + /** + * @property {number} _tempA - Internal var. + * @private + */ + this._tempA = 0; + + /** + * @property {number} _tempB - Internal var. + * @private + */ + this._tempB = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.CSV = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.TILED_JSON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.NORTH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.EAST = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.SOUTH = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.WEST = 3; + +Phaser.Tilemap.prototype = { + + /** + * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. + * + * @method Phaser.Tilemap#create + * @param {string} name - The name of the default layer of the map. + * @param {number} width - The width of the map in tiles. + * @param {number} height - The height of the map in tiles. + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + create: function (name, width, height, tileWidth, tileHeight, group) { + + if (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); + + }, + + /** + * Sets the base tile size for the map. + * + * @method Phaser.Tilemap#setTileSize + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + */ + setTileSize: function (tileWidth, tileHeight) { + + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.widthInPixels = this.width * tileWidth; + this.heightInPixels = this.height * tileHeight; + + }, + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. + * + * @method Phaser.Tilemap#addTilesetImage + * @param {string} tileset - The name of the tileset as specified in the map data. + * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset. + * If `undefined` or `null` it will look for an image with a key matching the tileset parameter. + * You can also pass in a BitmapData which can be used instead of an Image. + * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. + * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. + * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. + * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. + * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. + * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed. + */ + addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { + + if (tileset === undefined) { return null; } + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (gid === undefined) { gid = 0; } + + // In-case we're working from a blank map + if (tileWidth === 0) + { + tileWidth = 32; + } + + if (tileHeight === 0) + { + tileHeight = 32; + } + + var img = null; + + if (key === undefined || key === null) + { + key = tileset; + } + + if (key instanceof Phaser.BitmapData) + { + img = key.canvas; + } + else + { + if (!this.game.cache.checkImageKey(key)) + { + console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"'); + return null; + } + + img = this.game.cache.getImage(key); + } + + var idx = this.getTilesetIndex(tileset); + + if (idx === null && this.format === Phaser.Tilemap.TILED_JSON) + { + console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + tileset + '"'); + console.log('Tilesets: ', this.tilesets); + return null; + } + + if (this.tilesets[idx]) + { + this.tilesets[idx].setImage(img); + return this.tilesets[idx]; + } + else + { + var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {}); + + newSet.setImage(img); + + 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; t < gid + newSet.total; t++) + { + this.tiles[t] = [x, y, i]; + + x += tileWidth + tileSpacing; + + count++; + + if (count === newSet.total) + { + break; + } + + countX++; + + if (countX === newSet.columns) + { + x = tileMargin; + y += tileHeight + tileSpacing; + + countX = 0; + countY++; + + if (countY === newSet.rows) + { + break; + } + } + } + + return newSet; + + } + + return null; + + }, + + /** + * Creates a Sprite for every {@link http://doc.mapeditor.org/reference/tmx-map-format/#object object} matching the `gid` argument. You can optionally specify the group that the Sprite will be created in. If none is + * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to + * configure Sprite properties from within the map editor. For example giving an object a property of `alpha: 0.5` in the map editor will duplicate that when the + * Sprite is created. You could also give it a value like: `body.velocity.x: 100` to set it moving automatically. + * + * The `gid` argument is matched against: + * + * 1. For a tile object, the tile identifier (`gid`); or + * 2. The object's unique ID (`id`); or + * 3. The object's `name` (a string) + * + * @method Phaser.Tilemap#createFromObjects + * @param {string} name - The name of the Object Group to create Sprites from. + * @param {number|string} gid - The object's tile reference (gid), unique ID (id) or name. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. + * @param {boolean} [exists=true] - The default exists state of the Sprite. + * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. + * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. + * @param {boolean} [adjustSize=true] - By default the width and height of the objects are transferred to the sprite. This parameter controls that behavior. + */ + createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY, adjustSize) { + + if (exists === undefined) { exists = true; } + if (autoCull === undefined) { autoCull = false; } + if (group === undefined) { group = this.game.world; } + if (CustomClass === undefined) { CustomClass = Phaser.Sprite; } + if (adjustY === undefined) { adjustY = true; } + if (adjustSize === undefined) { adjustSize = true; } + + if (!this.objects[name]) + { + console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name); + console.log('Objects: ', this.objects); + return; + } + + for (var i = 0; i < this.objects[name].length; i++) + { + var found = false; + var obj = this.objects[name][i]; + + if (obj.gid !== undefined && typeof gid === 'number' && obj.gid === gid) + { + found = true; + } + else if (obj.id !== undefined && typeof gid === 'number' && obj.id === gid) + { + found = true; + } + else if (obj.name !== undefined && typeof gid === 'string' && obj.name === gid) + { + found = true; + } + + if (found) + { + var sprite = new CustomClass(this.game, parseFloat(obj.x, 10), parseFloat(obj.y, 10), key, frame); + + sprite.name = obj.name; + sprite.autoCull = autoCull; + sprite.exists = exists; + sprite.visible = obj.visible; + + if (adjustSize) + { + if (obj.width) + { + sprite.width = obj.width; + } + + if (obj.height) + { + sprite.height = obj.height; + } + } + + if (obj.rotation) + { + sprite.angle = obj.rotation; + } + + if (adjustY) + { + sprite.y -= sprite.height; + } + + group.add(sprite); + + for (var property in obj.properties) + { + group.set(sprite, property, obj.properties[property], false, false, 0, true); + } + } + } + + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the map data. + * You can specify the group that the Sprite will be created in. If none is given it will be created in the World. + * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special + * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemap#createFromTiles + * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from. + * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. + * @return {integer} The number of Sprites that were created. + */ + createFromTiles: function (tiles, replacements, key, layer, group, properties) { + + if (typeof tiles === 'number') { tiles = [tiles]; } + + if (replacements === undefined || replacements === null) + { + replacements = []; + } + else if (typeof replacements === 'number') + { + replacements = [replacements]; + } + + layer = this.getLayer(layer); + + if (group === undefined) { group = this.game.world; } + if (properties === undefined) { properties = {}; } + + if (properties.customClass === undefined) + { + properties.customClass = Phaser.Sprite; + } + + if (properties.adjustY === undefined) + { + properties.adjustY = true; + } + + var lw = this.layers[layer].width; + var lh = this.layers[layer].height; + + this.copy(0, 0, lw, lh, layer); + + if (this._results.length < 2) + { + return 0; + } + + var total = 0; + var sprite; + + for (var i = 1, len = this._results.length; i < len; i++) + { + if (tiles.indexOf(this._results[i].index) !== -1) + { + sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key); + + for (var property in properties) + { + sprite[property] = properties[property]; + } + + group.add(sprite); + total++; + } + + } + + if (replacements.length === 1) + { + // Assume 1 replacement for all types of tile given + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer); + } + } + else if (replacements.length > 1) + { + // Assume 1 for 1 mapping + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer); + } + } + + return total; + + }, + + /** + * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. + * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. + * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. + * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. + * + * @method Phaser.Tilemap#createLayer + * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. + * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. + * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. + * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. + */ + createLayer: function (layer, width, height, group) { + + // Add Buffer support for the left of the canvas + + if (width === undefined) { width = this.game.width; } + if (height === undefined) { height = this.game.height; } + if (group === undefined) { group = this.game.world; } + + var index = layer; + + if (typeof layer === 'string') + { + index = this.getLayerIndex(layer); + } + + if (index === null || index > this.layers.length) + { + console.warn('Tilemap.createLayer: Invalid layer ID given: "' + layer + '"'); + console.log('Layers: ', this.layers); + return; + } + + // Sort out the display dimensions, so they never render too much, or too little. + + if (width === undefined || width <= 0) + { + width = Math.min(this.game.width, this.layers[index].widthInPixels); + } + else if (width > this.game.width) + { + width = this.game.width; + } + + if (height === undefined || height <= 0) + { + height = Math.min(this.game.height, this.layers[index].heightInPixels); + } + else if (height > this.game.height) + { + height = this.game.height; + } + + if (this.enableDebug) + { + console.group('Tilemap.createLayer'); + console.log('Name:', this.layers[index].name); + console.log('Size:', width, 'x', height); + console.log('Tileset:', this.tilesets[0].name, 'index:', index); + } + + var rootLayer = group.add(new Phaser.TilemapLayer(this.game, this, index, width, height)); + + if (this.enableDebug) + { + console.groupEnd(); + } + + return rootLayer; + + }, + + + /** + * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. + * + * @method Phaser.Tilemap#createBlankLayer + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {number} width - The width of the layer in tiles. + * @param {number} height - The height of the layer in tiles. + * @param {number} tileWidth - The width of the tiles the layer uses for calculations. + * @param {number} tileHeight - The height of the tiles the layer uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) { + + if (group === undefined) { group = this.game.world; } + + if (this.getLayerIndex(name) !== null) + { + console.warn('Tilemap.createBlankLayer: Layer with matching name already exists: ' + name); + 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; y < height; y++) + { + row = []; + + for (var x = 0; x < width; x++) + { + row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight)); + } + + output.push(row); + } + + layer.data = output; + + this.layers.push(layer); + + this.currentLayer = this.layers.length - 1; + + var w = layer.widthInPixels; + var h = layer.heightInPixels; + + if (w > this.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); + + }, + + /** + * Gets the layer index based on the layers name. + * + * @method Phaser.Tilemap#getIndex + * @protected + * @param {array} location - The local array to search. + * @param {string} name - The name of the array element to get. + * @return {number} The index of the element in the array, or null if not found. + */ + getIndex: function (location, name) { + + for (var i = 0; i < location.length; i++) + { + if (location[i].name === name) + { + return i; + } + } + + return null; + + }, + + /** + * Gets the layer index based on its name. + * + * @method Phaser.Tilemap#getLayerIndex + * @param {string} name - The name of the layer to get. + * @return {number} The index of the layer in this tilemap, or null if not found. + */ + getLayerIndex: function (name) { + + return this.getIndex(this.layers, name); + + }, + + /** + * Gets the tileset index based on its name. + * + * @method Phaser.Tilemap#getTilesetIndex + * @param {string} name - The name of the tileset to get. + * @return {number} The index of the tileset in this tilemap, or null if not found. + */ + getTilesetIndex: function (name) { + + return this.getIndex(this.tilesets, name); + + }, + + /** + * Gets the image index based on its name. + * + * @method Phaser.Tilemap#getImageIndex + * @param {string} name - The name of the image to get. + * @return {number} The index of the image in this tilemap, or null if not found. + */ + getImageIndex: function (name) { + + return this.getIndex(this.images, name); + + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileIndexCallback + * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileIndexCallback: function (indexes, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes]; + } + else + { + // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much + // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit. + this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext }; + } + } + else + { + for (var i = 0, len = indexes.length; i < len; i++) + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes[i]]; + } + else + { + this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext }; + } + } + } + + }, + + /** + * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileLocationCallback + * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} width - The width of the area to copy (given in tiles, not pixels) + * @param {number} height - The height of the area to copy (given in tiles, not pixels) + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].setCollisionCallback(callback, callbackContext); + } + + }, + + /** + * Sets collision on the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [2, 3, 15, 20]. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * Collision-enabled tiles can be collided against Sprites using {@link Phaser.Physics.Arcade#collide}. + * + * You can verify the collision faces by enabling {@link Phaser.TilemapLayer#debug}. + * + * @method Phaser.Tilemap#setCollision + * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollision: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + return this.setCollisionByIndex(indexes, collides, layer, true); + } + else if (Array.isArray(indexes)) + { + // Collide all of the IDs given in the indexes array + for (var i = 0; i < indexes.length; i++) + { + this.setCollisionByIndex(indexes[i], collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + } + + }, + + /** + * Sets collision on a range of tiles where the tile IDs increment sequentially. + * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionBetween + * @param {number} start - The first index of the tile to be set for collision. + * @param {number} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionBetween: function (start, stop, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (start > stop) + { + return; + } + + for (var index = start; index <= stop; index++) + { + this.setCollisionByIndex(index, collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision on all tiles in the given layer, except for the IDs of those in the given array. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionByExclusion + * @param {array} indexes - An array of the tile IDs to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByExclusion: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + // Collide everything, except the IDs given in the indexes array + for (var i = 0, len = this.tiles.length; i < len; i++) + { + if (indexes.indexOf(i) === -1) + { + this.setCollisionByIndex(i, collides, layer, false); + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision values on a tile in the set. + * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. + * + * @method Phaser.Tilemap#setCollisionByIndex + * @protected + * @param {number} index - The index of the tile on the layer. + * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile. + * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByIndex: function (index, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (layer === undefined) { layer = this.currentLayer; } + if (recalculate === undefined) { recalculate = true; } + + if (collides) + { + this.collideIndexes.push(index); + } + else + { + var i = this.collideIndexes.indexOf(index); + + if (i > -1) + { + this.collideIndexes.splice(i, 1); + } + } + + for (var y = 0; y < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile && tile.index === index) + { + if (collides) + { + tile.setCollision(true, true, true, true); + } + else + { + tile.resetCollision(); + } + + tile.faceTop = collides; + tile.faceBottom = collides; + tile.faceLeft = collides; + tile.faceRight = collides; + } + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + return layer; + + }, + + /** + * Gets the TilemapLayer index as used in the setCollision calls. + * + * @method Phaser.Tilemap#getLayer + * @protected + * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer. + * @return {number} The TilemapLayer index. + */ + getLayer: function (layer) { + + if (layer === undefined) + { + layer = this.currentLayer; + } + else if (typeof layer === 'string') + { + var layerArg = layer; + + layer = this.getLayerIndex(layer); + + if (!layer) + { + console.warn('No such layer name: ' + layerArg); + } + } + else if (layer instanceof Phaser.TilemapLayer) + { + layer = layer.index; + } + + return layer; + + }, + + /** + * Turn off/on the recalculation of faces for tile or collision updates. + * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. + * + * @method Phaser.Tilemap#setPreventRecalculate + * @param {boolean} value - If true it will put the recalculation on hold. + */ + setPreventRecalculate: function (value) { + + if (value === true && this.preventingRecalculate !== true) + { + this.preventingRecalculate = true; + this.needToRecalculate = {}; + } + + if (value === false && this.preventingRecalculate === true) + { + this.preventingRecalculate = false; + + for (var i in this.needToRecalculate) + { + this.calculateFaces(i); + } + + this.needToRecalculate = false; + } + + }, + + /** + * Internal function. + * + * @method Phaser.Tilemap#calculateFaces + * @protected + * @param {number} layer - The index of the TilemapLayer to operate on. + */ + calculateFaces: function (layer) { + + if (this.preventingRecalculate) + { + this.needToRecalculate[layer] = true; + return; + } + + var above = null; + var below = null; + var left = null; + var right = null; + + for (var y = 0, h = this.layers[layer].height; y < h; y++) + { + for (var x = 0, w = this.layers[layer].width; x < w; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile) + { + above = this.getTileAbove(layer, x, y); + below = this.getTileBelow(layer, x, y); + left = this.getTileLeft(layer, x, y); + right = this.getTileRight(layer, x, y); + + if (tile.collides) + { + tile.faceTop = true; + tile.faceBottom = true; + tile.faceLeft = true; + tile.faceRight = true; + } + + if (above && above.collides) + { + // There is a tile above this one that also collides, so the top of this tile is no longer interesting + tile.faceTop = false; + } + + if (below && below.collides) + { + // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting + tile.faceBottom = false; + } + + if (left && left.collides) + { + // There is a tile left this one that also collides, so the left of this tile is no longer interesting + tile.faceLeft = false; + } + + if (right && right.collides) + { + // There is a tile right this one that also collides, so the right of this tile is no longer interesting + tile.faceRight = false; + } + } + } + } + + }, + + /** + * Gets the tile above the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileAbove + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileAbove: function (layer, x, y) { + + if (y > 0) + { + return this.layers[layer].data[y - 1][x]; + } + + return null; + + }, + + /** + * Gets the tile below the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileBelow + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileBelow: function (layer, x, y) { + + if (y < this.layers[layer].height - 1) + { + return this.layers[layer].data[y + 1][x]; + } + + return null; + + }, + + /** + * Gets the tile to the left of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileLeft + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileLeft: function (layer, x, y) { + + if (x > 0) + { + return this.layers[layer].data[y][x - 1]; + } + + return null; + + }, + + /** + * Gets the tile to the right of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileRight + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileRight: function (layer, x, y) { + + if (x < this.layers[layer].width - 1) + { + return this.layers[layer].data[y][x + 1]; + } + + return null; + + }, + + /** + * Sets the current layer to the given index. + * + * @method Phaser.Tilemap#setLayer + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + */ + setLayer: function (layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer]) + { + this.currentLayer = layer; + } + + }, + + /** + * Checks if there is a tile at the given location. + * + * @method Phaser.Tilemap#hasTile + * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels) + * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + * @return {boolean} True if there is a tile at the given location, otherwise false. + */ + hasTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined) + { + return false; + } + + return (this.layers[layer].data[y][x].index > -1); + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. + * + * @method Phaser.Tilemap#removeTile + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.hasTile(x, y, layer)) + { + var tile = this.layers[layer].data[y][x]; + + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight); + + this.layers[layer].dirty = true; + + this.calculateFaces(layer); + + return tile; + } + } + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#removeTileWorldXY + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTileWorldXY: function (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.removeTile(x, y, layer); + + }, + + /** + * Puts a tile of the given index value at the coordinate specified. + * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. + * + * @method Phaser.Tilemap#putTile + * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map. + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + putTile: function (tile, x, y, layer) { + + if (tile === null) + { + return this.removeTile(x, y, layer); + } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + var index; + + if (tile instanceof Phaser.Tile) + { + index = tile.index; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].copy(tile); + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height); + } + } + else + { + index = tile; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].index = index; + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight); + } + } + + if (this.collideIndexes.indexOf(index) > -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; + + }, + + /** + * Puts a tile into the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#putTileWorldXY + * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object. + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + 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); + + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. + * If no match is found it returns null. + * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. + * + * @method Phaser.Tilemap#searchTileIndex + * @param {number} index - The tile index value to search for. + * @param {number} [skip=0] - The number of times to skip a matching tile before returning. + * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @return {Phaser.Tile} The first (or n skipped) tile with the matching index. + */ + searchTileIndex: function (index, skip, reverse, layer) { + + if (skip === undefined) { skip = 0; } + if (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 < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + if (this.layers[layer].data[y][x].index === index) + { + if (c === skip) + { + return this.layers[layer].data[y][x]; + } + else + { + c++; + } + } + } + } + } + + return null; + + }, + + /** + * Gets a tile from the Tilemap Layer. The coordinates are given in tile values. + * + * @method Phaser.Tilemap#getTile + * @param {number} x - X position to get the tile from (given in tile units, not pixels) + * @param {number} y - Y position to get the tile from (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTile: function (x, y, layer, nonNull) { + + if (nonNull === undefined) { nonNull = false; } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.layers[layer].data[y][x].index === -1) + { + if (nonNull) + { + return this.layers[layer].data[y][x]; + } + else + { + return null; + } + } + else + { + return this.layers[layer].data[y][x]; + } + } + else + { + return null; + } + + }, + + /** + * Gets a tile from the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#getTileWorldXY + * @param {number} x - X position to get the tile from (given in pixels) + * @param {number} y - Y position to get the tile from (given in pixels) + * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used. + * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates. + */ + getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) { + + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + + layer = this.getLayer(layer); + + x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; + y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; + + return this.getTile(x, y, layer, nonNull); + + }, + + /** + * Copies all of the tiles in the given rectangular block into the tilemap data buffer. + * + * @method Phaser.Tilemap#copy + * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} width - The width of the area to copy (given in tiles, not pixels) + * @param {integer} height - The height of the area to copy (given in tiles, not pixels) + * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from. + * @return {array} An array of the tiles that were copied. + */ + copy: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + if (!this.layers[layer]) + { + this._results.length = 0; + return; + } + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.layers[layer].width; } + if (height === undefined) { height = this.layers[layer].height; } + + if (x < 0) + { + x = 0; + } + + if (y < 0) + { + y = 0; + } + + if (width > this.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; ty < y + height; ty++) + { + for (var tx = x; tx < x + width; tx++) + { + this._results.push(this.layers[layer].data[ty][tx]); + } + } + + return this._results; + + }, + + /** + * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. + * + * @method Phaser.Tilemap#paste + * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels) + * @param {array} tileblock - The block of tiles to paste. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into. + */ + paste: function (x, y, tileblock, layer) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + layer = this.getLayer(layer); + + if (!tileblock || tileblock.length < 2) + { + return; + } + + // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste + var diffX = x - tileblock[1].x; + var diffY = y - tileblock[1].y; + + for (var i = 1; i < tileblock.length; i++) + { + this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]); + } + + this.layers[layer].dirty = true; + this.calculateFaces(layer); + + }, + + /** + * Scans the given area for tiles with an index matching tileA and swaps them with tileB. + * + * @method Phaser.Tilemap#swap + * @param {number} tileA - First tile index. + * @param {number} tileB - Second tile index. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + swap: function (tileA, tileB, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._tempA = tileA; + this._tempB = tileB; + + this._results.forEach(this.swapHandler, this); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Internal function that handles the swapping of tiles. + * + * @method Phaser.Tilemap#swapHandler + * @private + * @param {number} value + */ + swapHandler: function (value) { + + if (value.index === this._tempA) + { + // Swap A with B + value.index = this._tempB; + } + else if (value.index === this._tempB) + { + // Swap B with A + value.index = this._tempA; + } + + }, + + /** + * For each tile in the given area defined by x/y and width/height run the given callback. + * + * @method Phaser.Tilemap#forEach + * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {number} context - The context under which the callback should be run. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + forEach: function (callback, context, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._results.forEach(callback, context); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. + * + * @method Phaser.Tilemap#replace + * @param {number} source - The tile index value to scan for. + * @param {number} dest - The tile index value to replace found tiles with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + replace: function (source, dest, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + if (this._results[i].index === source) + { + this._results[i].index = dest; + } + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Randomises a set of tiles in a given area. + * + * @method Phaser.Tilemap#random + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + random: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + var idx = this._results[t].index; + + if (indexes.indexOf(idx) === -1) + { + indexes.push(idx); + } + } + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = this.game.rnd.pick(indexes); + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! + * + * @method Phaser.Tilemap#shuffle + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + shuffle: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + indexes.push(this._results[t].index); + } + } + + Phaser.ArrayUtils.shuffle(indexes); + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = indexes[i - 1]; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Fills the given area with the specified tile. + * + * @method Phaser.Tilemap#fill + * @param {number} index - The index of the tile that the area will be filled with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + fill: function (index, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = index; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Removes all layers from this tile map. + * + * @method Phaser.Tilemap#removeAllLayers + */ + removeAllLayers: function () { + + this.layers.length = 0; + this.currentLayer = 0; + + }, + + /** + * Dumps the tilemap data out to the console. + * + * @method Phaser.Tilemap#dump + */ + dump: function () { + + var txt = ''; + var args = ['']; + + for (var y = 0; y < this.layers[this.currentLayer].height; y++) + { + for (var x = 0; x < this.layers[this.currentLayer].width; x++) + { + txt += "%c "; + + if (this.layers[this.currentLayer].data[y][x] > 1) + { + 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); + + }, + + /** + * Removes all layer data from this tile map and nulls the game reference. + * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. + * + * @method Phaser.Tilemap#destroy + */ + destroy: function () { + + this.removeAllLayers(); + this.data = []; + this.game = null; + + } + +}; + +Phaser.Tilemap.prototype.constructor = Phaser.Tilemap; + +/** +* @name Phaser.Tilemap#layer +* @property {number|string|Phaser.TilemapLayer} layer - The current layer object. +*/ +Object.defineProperty(Phaser.Tilemap.prototype, "layer", { + + get: function () { + + return this.layers[this.currentLayer]; + + }, + + set: function (value) { + + if (value !== this.currentLayer) + { + this.setLayer(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. +* +* Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. +* +* By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. +* +* @class Phaser.TilemapLayer +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs. +* @param {integer} index - The index of the TileLayer to render within the Tilemap. +* @param {integer} width - Width of the renderable area of the layer (in pixels). +* @param {integer} height - Height of the renderable area of the layer (in pixels). +*/ +Phaser.TilemapLayer = function (game, tilemap, index, width, height) { + + width |= 0; + height |= 0; + + Phaser.Sprite.call(this, game, 0, 0); + + /** + * The Tilemap to which this layer is bound. + * @property {Phaser.Tilemap} map + * @protected + * @readonly + */ + this.map = tilemap; + + /** + * The index of this layer within the Tilemap. + * @property {number} index + * @protected + * @readonly + */ + this.index = index; + + /** + * The layer object within the Tilemap that this layer represents. + * @property {object} layer + * @protected + * @readonly + */ + this.layer = tilemap.layers[index]; + + /** + * The canvas to which this TilemapLayer draws. + * @property {HTMLCanvasElement} canvas + * @protected + */ + this.canvas = Phaser.CanvasPool.create(this, width, height); + + /** + * The 2d context of the canvas. + * @property {CanvasRenderingContext2D} context + * @private + */ + this.context = this.canvas.getContext('2d'); + + this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas, null, this.game.resolution))); + + /** + * The const type of this object. + * @property {number} type + * @readonly + * @protected + * @default Phaser.TILEMAPLAYER + */ + this.type = Phaser.TILEMAPLAYER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.TILEMAPLAYER; + + /** + * Settings that control standard (non-diagnostic) rendering. + * + * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view. + * This can greatly improve scrolling rendering performance, especially when there are many small tiles. + * It should only be disabled in rare cases. + * + * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas. + * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior + * in some browsers, notably Safari. + * + * @default + */ + this.renderSettings = { + enableScrollDelta: true, + overdrawRatio: 0.20, + copyCanvas: null + }; + + /** + * Enable an additional "debug rendering" pass to display collision information. + * + * @property {boolean} debug + * @default + */ + this.debug = false; + + /** + * @property {boolean} exists - Controls if the core game loop and physics update this game object or not. + */ + this.exists = true; + + /** + * Settings used for debugging and diagnostics. + * + * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. + * + * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. + * + * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. + * + * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. + * + */ + this.debugSettings = { + + missingImageFill: 'rgb(255,255,255)', + debuggedTileOverfill: 'rgba(0,255,0,0.4)', + + forceFullRedraw: true, + + debugAlpha: 0.5, + facingEdgeStroke: 'rgba(0,255,0,1)', + collidingTileOverfill: 'rgba(0,255,0,0.2)' + + }; + + /** + * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). + * @property {number} scrollFactorX + * @public + * @default + */ + this.scrollFactorX = 1; + + /** + * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) + * @property {number} scrollFactorY + * @public + * @default + */ + this.scrollFactorY = 1; + + /** + * If true tiles will be force rendered, even if such is not believed to be required. + * @property {boolean} dirty + * @protected + */ + this.dirty = true; + + /** + * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. + * @property {integer} rayStepRate + * @default + */ + this.rayStepRate = 4; + + /** + * Flag controlling if the layer tiles wrap at the edges. + * @property {boolean} _wrap + * @private + */ + this._wrap = false; + + /** + * Local map data and calculation cache. + * @property {object} _mc + * @private + */ + this._mc = { + + // Used to bypass rendering without reliance on `dirty` and detect changes. + scrollX: 0, + scrollY: 0, + renderWidth: 0, + renderHeight: 0, + + tileWidth: tilemap.tileWidth, + tileHeight: tilemap.tileHeight, + + // Collision width/height (pixels) + // What purpose do these have? Most things use tile width/height directly. + // This also only extends collisions right and down. + cw: tilemap.tileWidth, + ch: tilemap.tileHeight, + + // Cached tilesets from index -> Tileset + tilesets: [] + + }; + + /** + * The current canvas left after scroll is applied. + * @property {number} _scrollX + * @private + */ + this._scrollX = 0; + + /** + * The current canvas top after scroll is applied. + * @property {number} _scrollY + * @private + */ + this._scrollY = 0; + + /** + * The position offset of the layer's tiles. + * @property {Phaser.Point} + */ + this.tileOffset = new Phaser.Point(this.layer.offsetX || 0, this.layer.offsetY || 0); + + /** + * Used for caching the tiles / array of tiles. + * @property {Phaser.Tile[]} _results + * @private + */ + this._results = []; + + if (!game.device.canvasBitBltShift) + { + this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas(); + } + + this.fixedToCamera = true; + +}; + +Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer; + +Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* The shared double-copy canvas, created as needed. +* +* @private +* @static +*/ +Phaser.TilemapLayer.sharedCopyCanvas = null; + +/** +* Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. +* +* Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. +* +* @method Phaser.TilemapLayer#ensureSharedCopyCanvas +* @protected +* @static +*/ +Phaser.TilemapLayer.ensureSharedCopyCanvas = function () { + + if (!this.sharedCopyCanvas) + { + this.sharedCopyCanvas = Phaser.CanvasPool.create(this, 2, 2); + } + + return this.sharedCopyCanvas; + +}; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TilemapLayer#preUpdate +*/ +Phaser.TilemapLayer.prototype.preUpdate = function() { + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.postUpdate. Handles cache updates. +* +* @method Phaser.TilemapLayer#postUpdate +* @protected +*/ +Phaser.TilemapLayer.prototype.postUpdate = function () { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderCanvas function. +* +* @method Phaser.TilemapLayer#_renderCanvas +* @private +*/ +Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderWebGL function. +* +* @method Phaser.TilemapLayer#_renderWebGL +* @private +*/ +Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Destroys this TilemapLayer. +* +* @method Phaser.TilemapLayer#destroy +*/ +Phaser.TilemapLayer.prototype.destroy = function() { + + Phaser.CanvasPool.remove(this); + + Phaser.Component.Destroy.prototype.destroy.call(this); + +}; + +/** +* Resizes the internal canvas and texture frame used by this TilemapLayer. +* +* This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully +* selected times. +* +* Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not +* modified either. You will have to handle both of these things from your game code if required. +* +* @method Phaser.TilemapLayer#resize +* @param {number} width - The new width of the TilemapLayer +* @param {number} height - The new height of the TilemapLayer +*/ +Phaser.TilemapLayer.prototype.resize = function (width, height) { + + this.canvas.width = width; + this.canvas.height = height; + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.texture.baseTexture.width = width; + this.texture.baseTexture.height = height; + + this.texture.baseTexture.dirty(); + this.texture.requiresUpdate = true; + + this.texture._updateUvs(); + + this.dirty = true; + +}; + +/** +* Sets the world size to match the size of this layer. +* +* @method Phaser.TilemapLayer#resizeWorld +* @public +*/ +Phaser.TilemapLayer.prototype.resizeWorld = function () { + + this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y); + +}; + +/** + * Get the X axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getLayerOffsetX + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetX = function () { + + return this.tileOffset.x || ((!this.fixedToCamera) ? this.position.x : 0); + +}; + +/** + * Get the Y axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getTileOffsetY + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetY = function () { + + return this.tileOffset.y || ((!this.fixedToCamera) ? this.position.y : 0); + +}; + +/** +* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixX +* @private +* @param {number} x - x coordinate in camera space +* @return {number} x coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixX = function (x) { + + if (this.scrollFactorX === 1 || (this.scrollFactorX === 0 && this.position.x === 0)) + { + return x; + } + + // This executes if the scrollFactorX is 0 and the x position of the tilemap is off from standard. + if (this.scrollFactorX === 0 && this.position.x !== 0) + { + return x - this.position.x; + } + + return this._scrollX + (x - (this._scrollX / this.scrollFactorX)); + +}; + +/** +* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixX +* @private +* @param {number} x - x coordinate in scrollFactor-adjusted dimensions +* @return {number} x coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixX = function (x) { + + if (this.scrollFactorX === 1) + { + return x; + } + + return (this._scrollX / this.scrollFactorX) + (x - this._scrollX); + +}; + +/** +* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixY +* @private +* @param {number} y - y coordinate in camera space +* @return {number} y coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixY = function (y) { + + if (this.scrollFactorY === 1 || (this.scrollFactorY === 0 && this.position.y === 0)) + { + return y; + } + + // This executes if the scrollFactorY is 0 and the y position of the tilemap is off from standard. + if (this.scrollFactorY === 0 && this.position.y !== 0) + { + return y - this.position.y; + } + + return this._scrollY + (y - (this._scrollY / this.scrollFactorY)); + +}; + +/** +* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixY +* @private +* @param {number} y - y coordinate in scrollFactor-adjusted dimensions +* @return {number} y coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixY = function (y) { + + if (this.scrollFactorY === 1) + { + return y; + } + + return (this._scrollY / this.scrollFactorY) + (y - this._scrollY); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileX +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @return {integer} The X map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileX = function (x) { + + // var tileWidth = this.tileWidth * this.scale.x; + return Math.floor(this._fixX(x) / this._mc.tileWidth); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileY +* @public +* @param {number} y - Y position of the point in target tile (in pixels). +* @return {integer} The Y map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileY = function (y) { + + // var tileHeight = this.tileHeight * this.scale.y; + return Math.floor(this._fixY(y) / this._mc.tileHeight); + +}; + +/** +* Convert a pixel coordinate to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileXY +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @param {number} y - Y position of the point in target tile (in pixels). +* @param {(Phaser.Point|object)} point - The Point/object to update. +* @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set. +*/ +Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) { + + point.x = this.getTileX(x); + point.y = this.getTileY(y); + + return point; + +}; + +/** +* Gets all tiles that intersect with the given line. +* +* @method Phaser.TilemapLayer#getRayCastTiles +* @public +* @param {Phaser.Line} line - The line used to determine which tiles to return. +* @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`. +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {Phaser.Tile[]} An array of Phaser.Tiles. +*/ +Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) { + + if (!stepRate) { stepRate = this.rayStepRate; } + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + // First get all tiles that touch the bounds of the line + var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace); + + if (tiles.length === 0) + { + return []; + } + + // Now we only want the tiles that intersect with the points on this line + var coords = line.coordinatesOnLine(stepRate); + var results = []; + + for (var i = 0; i < tiles.length; i++) + { + for (var t = 0; t < coords.length; t++) + { + var tile = tiles[i]; + var coord = coords[t]; + if (tile.containsPoint(coord[0], coord[1])) + { + results.push(tile); + break; + } + } + } + + return results; + +}; + +/** +* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. +* +* @method Phaser.TilemapLayer#getTiles +* @public +* @param {number} x - X position of the top left corner (in pixels). +* @param {number} y - Y position of the top left corner (in pixels). +* @param {number} width - Width of the area to get (in pixels). +* @param {number} height - Height of the area to get (in pixels). +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {array} An array of Tiles. +*/ +Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) { + + // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all) + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + var fetchAll = !(collides || interestingFace); + + // Adjust the x,y coordinates for scrollFactor + x = this._fixX(x); + y = this._fixY(y); + + // Convert the pixel values into tile coordinates + var tx = Math.floor(x / (this._mc.cw * this.scale.x)); + var ty = Math.floor(y / (this._mc.ch * this.scale.y)); + // Don't just use ceil(width/cw) to allow account for x/y diff within cell + var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx; + var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty; + + while (this._results.length) + { + this._results.pop(); + } + + for (var wy = ty; wy < ty + th; wy++) + { + for (var wx = tx; wx < tx + tw; wx++) + { + var row = this.layer.data[wy]; + + if (row && row[wx]) + { + if (fetchAll || row[wx].isInteresting(collides, interestingFace)) + { + this._results.push(row[wx]); + } + } + } + } + + return this._results.slice(); + +}; + +/** +* Returns the appropriate tileset for the index, updating the internal cache as required. +* This should only be called if `tilesets[index]` evaluates to undefined. +* +* @method Phaser.TilemapLayer#resolveTileset +* @private +* @param {integer} Tile index +* @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping. +*/ +Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) { + + var tilesets = this._mc.tilesets; + + // Try for dense array if reasonable + if (tileIndex < 2000) + { + while (tilesets.length < tileIndex) + { + tilesets.push(undefined); + } + } + + var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2]; + + if (setIndex !== null) + { + var tileset = this.map.tilesets[setIndex]; + + if (tileset && tileset.containsTileIndex(tileIndex)) + { + return (tilesets[tileIndex] = tileset); + } + } + + return (tilesets[tileIndex] = null); + +}; + +/** +* The TilemapLayer caches tileset look-ups. +* +* Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. +* +* @method Phaser.TilemapLayer#resetTilesetCache +* @public +*/ +Phaser.TilemapLayer.prototype.resetTilesetCache = function () { + + var tilesets = this._mc.tilesets; + + while (tilesets.length) + { + tilesets.pop(); + } + +}; + +/** + * This method will set the scale of the tilemap as well as update the underlying block data of this layer. + * + * @method Phaser.TilemapLayer#setScale + * @param {number} [xScale=1] - The scale factor along the X-plane + * @param {number} [yScale] - The scale factor along the Y-plane + */ +Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) { + + xScale = xScale || 1; + yScale = yScale || xScale; + + for (var y = 0; y < this.layer.data.length; y++) + { + var row = this.layer.data[y]; + + for (var x = 0; x < row.length; x++) + { + var tile = row[x]; + + tile.width = this.map.tileWidth * xScale; + tile.height = this.map.tileHeight * yScale; + + tile.worldX = tile.x * tile.width; + tile.worldY = tile.y * tile.height; + } + } + + this.scale.setTo(xScale, yScale); + +}; + +/** +* Shifts the contents of the canvas - does extra math so that different browsers agree on the result. +* +* The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in. +* +* @method Phaser.TilemapLayer#shiftCanvas +* @private +* @param {CanvasRenderingContext2D} context - The context to shift +* @param {integer} x +* @param {integer} y +*/ +Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) { + + var canvas = context.canvas; + var copyW = canvas.width - Math.abs(x); + var copyH = canvas.height - Math.abs(y); + + // When x/y non-negative + var dx = 0; + var dy = 0; + var sx = x; + var sy = y; + + if (x < 0) + { + dx = -x; + sx = 0; + } + + if (y < 0) + { + dy = -y; + sy = 0; + } + + var copyCanvas = this.renderSettings.copyCanvas; + + if (copyCanvas) + { + // Use a second copy buffer, without slice support, for Safari .. again. + // Ensure copy canvas is large enough + if (copyCanvas.width < copyW || copyCanvas.height < copyH) + { + copyCanvas.width = copyW; + copyCanvas.height = copyH; + } + + var copyContext = copyCanvas.getContext('2d'); + copyContext.clearRect(0, 0, copyW, copyH); + copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH); + // clear allows default 'source-over' semantics + context.clearRect(sx, sy, copyW, copyH); + context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH); + } + else + { + // Avoids a second copy but flickers in Safari / Safari Mobile + // Ref. https://github.com/photonstorm/phaser/issues/1439 + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH); + context.restore(); + } + +}; + +/** +* Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor. +* This will constrain the tile coordinates based on wrapping but not physical coordinates. +* +* @method Phaser.TilemapLayer#renderRegion +* @private +* @param {integer} scrollX - Render x offset/scroll. +* @param {integer} scrollY - Render y offset/scroll. +* @param {integer} left - Leftmost column to render. +* @param {integer} top - Topmost row to render. +* @param {integer} right - Rightmost column to render. +* @param {integer} bottom - Bottommost row to render. +*/ +Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) { + + var context = this.context; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var tilesets = this._mc.tilesets; + var lastAlpha = NaN; + + if (!this._wrap) + { + if (left <= right) // Only adjust if going to render + { + left = Math.max(0, left); + right = Math.min(width - 1, right); + } + if (top <= bottom) + { + top = Math.max(0, top); + bottom = Math.min(height - 1, bottom); + } + } + + // top-left pixel of top-left cell + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values. + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + // tx/ty - are pixel coordinates where tile is drawn + // x/y - is cell location, normalized [0..width/height) in loop + // xmax/ymax - remaining cells to render on column/row + var tx, ty, x, y, xmax, ymax; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + + if (!tile || tile.index < 0) + { + continue; + } + + var index = tile.index; + + var set = tilesets[index]; + + if (set === undefined) + { + set = this.resolveTileset(index); + } + + // Setting the globalAlpha is "surprisingly expensive" in Chrome (38) + if (tile.alpha !== lastAlpha && !this.debug) + { + context.globalAlpha = tile.alpha; + lastAlpha = tile.alpha; + } + + if (set) + { + if (tile.rotation || tile.flipped) + { + context.save(); + context.translate(tx + tile.centerX, ty + tile.centerY); + context.rotate(tile.rotation); + + if (tile.flipped) + { + context.scale(-1, 1); + } + + set.draw(context, -tile.centerX, -tile.centerY, index); + context.restore(); + } + else + { + set.draw(context, tx, ty, index); + } + } + else if (this.debugSettings.missingImageFill) + { + context.fillStyle = this.debugSettings.missingImageFill; + context.fillRect(tx, ty, tw, th); + } + + if (tile.debug && this.debugSettings.debuggedTileOverfill) + { + context.fillStyle = this.debugSettings.debuggedTileOverfill; + context.fillRect(tx, ty, tw, th); + } + + } + + } + +}; + +/** +* Shifts the canvas and render damaged edge tiles. +* +* @method Phaser.TilemapLayer#renderDeltaScroll +* @private +*/ +Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds. + + // Start in pixels + var left = 0; + var right = -tw; + var top = 0; + var bottom = -th; + + if (shiftX < 0) // layer moving left, damage right + { + left = renderW + shiftX; // shiftX neg. + right = renderW - 1; + } + else if (shiftX > 0) + { + // left -> 0 + right = shiftX; + } + + if (shiftY < 0) // layer moving down, damage top + { + top = renderH + shiftY; // shiftY neg. + bottom = renderH - 1; + } + else if (shiftY > 0) + { + // top -> 0 + bottom = shiftY; + } + + this.shiftCanvas(this.context, shiftX, shiftY); + + // Transform into tile-space + left = Math.floor((left + scrollX) / tw); + right = Math.floor((right + scrollX) / tw); + top = Math.floor((top + scrollY) / th); + bottom = Math.floor((bottom + scrollY) / th); + + if (left <= right) + { + // Clear left or right edge + this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH); + + var trueTop = Math.floor((0 + scrollY) / th); + var trueBottom = Math.floor((renderH - 1 + scrollY) / th); + this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom); + } + + if (top <= bottom) + { + // Clear top or bottom edge + this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th); + + var trueLeft = Math.floor((0 + scrollX) / tw); + var trueRight = Math.floor((renderW - 1 + scrollX) / tw); + this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom); + } + +}; + +/** +* Clear and render the entire canvas. +* +* @method Phaser.TilemapLayer#renderFull +* @private +*/ +Phaser.TilemapLayer.prototype.renderFull = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + this.context.clearRect(0, 0, renderW, renderH); + + this.renderRegion(scrollX, scrollY, left, top, right, bottom); + +}; + +/** +* Renders the tiles to the layer canvas and pushes to the display. +* +* @method Phaser.TilemapLayer#render +* @protected +*/ +Phaser.TilemapLayer.prototype.render = function () { + + var redrawAll = false; + + if (!this.visible) + { + return; + } + + if (this.dirty || this.layer.dirty) + { + this.layer.dirty = false; + redrawAll = true; + } + + var renderWidth = this.canvas.width; // Use Sprite.width/height? + var renderHeight = this.canvas.height; + + // Scrolling bias; whole pixels only + var scrollX = this._scrollX | 0; + var scrollY = this._scrollY | 0; + + var mc = this._mc; + var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down + var shiftY = mc.scrollY - scrollY; + + if (!redrawAll && + shiftX === 0 && shiftY === 0 && + mc.renderWidth === renderWidth && mc.renderHeight === renderHeight) + { + // No reason to redraw map, looking at same thing and not invalidated. + return; + } + + this.context.save(); + + mc.scrollX = scrollX; + mc.scrollY = scrollY; + + if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight) + { + // Could support automatic canvas resizing + mc.renderWidth = renderWidth; + mc.renderHeight = renderHeight; + } + + if (this.debug) + { + this.context.globalAlpha = this.debugSettings.debugAlpha; + + if (this.debugSettings.forceFullRedraw) + { + redrawAll = true; + } + } + + if (!redrawAll && + this.renderSettings.enableScrollDelta && + (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight)) + { + this.renderDeltaScroll(shiftX, shiftY); + } + else + { + // Too much change or otherwise requires full render + this.renderFull(); + } + + if (this.debug) + { + this.context.globalAlpha = 1; + this.renderDebug(); + } + + this.texture.baseTexture.dirty(); + + this.dirty = false; + + this.context.restore(); + + return true; + +}; + +/** +* Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true. +* +* See `debugSettings` for assorted configuration options. +* +* @method Phaser.TilemapLayer#renderDebug +* @private +*/ +Phaser.TilemapLayer.prototype.renderDebug = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var context = this.context; + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + var tx, ty, x, y, xmax, ymax; + + context.strokeStyle = this.debugSettings.facingEdgeStroke; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + if (!tile || tile.index < 0 || !tile.collides) + { + continue; + } + + if (this.debugSettings.collidingTileOverfill) + { + context.fillStyle = this.debugSettings.collidingTileOverfill; + context.fillRect(tx, ty, this._mc.cw, this._mc.ch); + } + + if (this.debugSettings.facingEdgeStroke) + { + context.beginPath(); + + if (tile.faceTop) + { + context.moveTo(tx, ty); + context.lineTo(tx + this._mc.cw, ty); + } + + if (tile.faceBottom) + { + context.moveTo(tx, ty + this._mc.ch); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + if (tile.faceLeft) + { + context.moveTo(tx, ty); + context.lineTo(tx, ty + this._mc.ch); + } + + if (tile.faceRight) + { + context.moveTo(tx + this._mc.cw, ty); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + context.closePath(); + + context.stroke(); + } + + } + + } + +}; + +/** +* Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size. +* +* @property {boolean} wrap +* @memberof Phaser.TilemapLayer +* @public +* @default false +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", { + + get: function () { + return this._wrap; + }, + + set: function (value) { + this._wrap = value; + this.dirty = true; + } + +}); + +/** +* Scrolls the map horizontally or returns the current x position. +* +* @property {number} scrollX +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", { + + get: function () { + return this._scrollX; + }, + + set: function (value) { + this._scrollX = value; + } + +}); + +/** +* Scrolls the map vertically or returns the current y position. +* +* @property {number} scrollY +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", { + + get: function () { + return this._scrollY; + }, + + set: function (value) { + this._scrollY = value; + } + +}); + +/** +* The width of the collision tiles (in pixels). +* +* @property {integer} collisionWidth +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", { + + get: function () { + return this._mc.cw; + }, + + set: function (value) { + this._mc.cw = value | 0; + this.dirty = true; + } + +}); + +/** +* The height of the collision tiles (in pixels). +* +* @property {integer} collisionHeight +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", { + + get: function () { + return this._mc.ch; + }, + + set: function (value) { + this._mc.ch = value | 0; + this.dirty = true; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. +* +* @class Phaser.TilemapParser +* @static +*/ +Phaser.TilemapParser = { + + /** + * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or + * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type + * depends how this should be configured. If you've a large sparsely populated map and the tile + * data doesn't need to change then setting this value to `true` will help with memory consumption. + * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes + * during the game) then leave the default value set. + * + * @constant + * @type {boolean} + */ + INSERT_NULL: false, + + /** + * Parse tilemap data from the cache and creates data for a Tilemap object. + * + * @method Phaser.TilemapParser.parse + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {string} key - The key of the tilemap in the Cache. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {object} The parsed map object. + */ + parse: function (game, key, tileWidth, tileHeight, width, height) { + + if (tileWidth === undefined) { tileWidth = 32; } + if (tileHeight === undefined) { tileHeight = 32; } + if (width === undefined) { width = 10; } + if (height === undefined) { height = 10; } + + if (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); + } + + }, + + /** + * Parses a CSV file into valid map data. + * + * @method Phaser.TilemapParser.parseCSV + * @param {string} key - The name you want to give the map data. + * @param {string} data - The CSV file data. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @return {object} Generated map data. + */ + parseCSV: function (key, data, tileWidth, tileHeight) { + + var map = this.getEmptyData(); + + // Trim any rogue whitespace from the data + data = data.trim(); + + var output = []; + var rows = data.split("\n"); + var height = rows.length; + var width = 0; + + for (var y = 0; y < rows.length; y++) + { + output[y] = []; + + var column = rows[y].split(","); + + for (var x = 0; x < column.length; x++) + { + output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight); + } + + if (width === 0) + { + width = column.length; + } + } + + map.format = Phaser.Tilemap.CSV; + map.name = key; + map.width = width; + map.height = height; + map.tileWidth = tileWidth; + map.tileHeight = tileHeight; + map.widthInPixels = width * tileWidth; + map.heightInPixels = height * tileHeight; + + map.layers[0].width = width; + map.layers[0].height = height; + map.layers[0].widthInPixels = map.widthInPixels; + map.layers[0].heightInPixels = map.heightInPixels; + map.layers[0].data = output; + + return map; + + }, + + /** + * Returns an empty map data object. + * + * @method Phaser.TilemapParser.getEmptyData + * @return {object} Generated map data. + */ + getEmptyData: function (tileWidth, tileHeight, width, height) { + + return { + width: (width !== undefined && width !== null) ? width : 0, + height: (height !== undefined && height !== null) ? height : 0, + tileWidth: (tileWidth !== undefined && tileWidth !== null) ? tileWidth : 0, + tileHeight: (tileHeight !== undefined && tileHeight !== null) ? tileHeight : 0, + orientation: 'orthogonal', + version: '1', + properties: {}, + widthInPixels: 0, + heightInPixels: 0, + layers: [ + { + name: 'layer', + x: 0, + y: 0, + width: 0, + height: 0, + widthInPixels: 0, + heightInPixels: 0, + alpha: 1, + visible: true, + properties: {}, + indexes: [], + callbacks: [], + bodies: [], + data: [] + } + ], + images: [], + objects: {}, + collision: {}, + tilesets: [], + tiles: [] + }; + + }, + + _slice: function(obj, fields) { + var sliced = {}; + + for (var k in fields) + { + var key = fields[k]; + + if (typeof obj[key] !== 'undefined') + { + sliced[key] = obj[key]; + } + } + + return sliced; + }, + + /** + * Parses an object group in Tiled JSON files. Object groups can be found in both layers and tilesets. Called internally in parseTiledJSON. + * @method Phaser.TilemapParser.parseObjectGroup + * @param {object} objectGroup - A JSON object group. + * @param {object} objectsCollection - An object into which new array of Tiled map objects will be added. + * @param {object} collisionCollection - An object into which new array of collision objects will be added. Currently only polylines are added. + * @param {string} [nameKey=objectGroup.name] - Key under which to store objects in collisions in objectsCollection and collisionCollection + * @param {object} [relativePosition={x: 0, y: 0}] - Coordinates the object group's position is relative to. + * @return {object} A object literal containing the objectsCollection and collisionCollection + */ + parseObjectGroup: function(objectGroup, objectsCollection, collisionCollection, nameKey, relativePosition) { + + var nameKey = nameKey || objectGroup.name; + var relativePosition = relativePosition || {x: 0, y: 0}; + var slice = this._slice; + + if (!nameKey) + { + console.warn('No name found for objectGroup', objectGroup); + } + + if (relativePosition.x === undefined || relativePosition.y === undefined) + { + console.warn('Malformed xy properties in relativePosition', relativePosition); + } + + objectsCollection[nameKey] = objectsCollection[nameKey] || []; + collisionCollection[nameKey] = collisionCollection[nameKey] || []; + + for (var v = 0, len = objectGroup.objects.length; v < len; v++) + { + var o = objectGroup.objects[v]; + + // Object Tiles + if (o.gid) + { + var object = { + gid: o.gid, + name: o.name, + type: o.type || '', + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + objectsCollection[nameKey].push(object); + } + else if (o.polyline) + { + var object = { + name: o.name, + type: o.type, + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + object.polyline = []; + + // Parse the polyline into an array + for (var p = 0; p < o.polyline.length; p++) + { + object.polyline.push([o.polyline[p].x, o.polyline[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // polygon + else if (o.polygon) + { + var object = slice(o, ['name', 'type', 'x', 'y', 'visible', 'rotation', 'properties']); + + object.x += relativePosition.x; + object.y += relativePosition.y; + + // Parse the polygon into an array + object.polygon = []; + + for (var p = 0; p < o.polygon.length; p++) + { + object.polygon.push([o.polygon[p].x, o.polygon[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // ellipse + else if (o.ellipse) + { + var object = slice(o, ['name', 'type', 'ellipse', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // otherwise it's a rectangle + else + { + var object = slice(o, ['name', 'type', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + object.rectangle = true; + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + } + + return { + objectsCollection: objectsCollection, + collisionCollection: collisionCollection + }; + }, + + /** + * Parses a Tiled JSON file into valid map data. + * @method Phaser.TilemapParser.parseTiledJSON + * @param {object} json - The JSON map data. + * @return {object} Generated and parsed map data. + */ + parseTiledJSON: function (json) { + + if (json.orientation !== 'orthogonal') + { + console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser'); + return null; + } + + // Map data will consist of: layers, objects, images, tilesets, sizes + var map = { + width: json.width, + height: json.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + orientation: json.orientation, + format: Phaser.Tilemap.TILED_JSON, + version: json.version, + properties: json.properties, + widthInPixels: json.width * json.tilewidth, + heightInPixels: json.height * json.tileheight + }; + + // Tile Layers + var layers = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'tilelayer') + { + continue; + } + + var curl = json.layers[i]; + + // Base64 decode data if necessary + // NOTE: uncompressed base64 only. + + if (!curl.compression && curl.encoding && curl.encoding === 'base64') + { + var binaryString = window.atob(curl.data); + var len = binaryString.length; + var bytes = new Array(len); + + // Interpret binaryString as an array of bytes representing + // little-endian encoded uint32 values. + for (var j = 0; j < len; j+=4) + { + bytes[j / 4] = ( + binaryString.charCodeAt(j) | + binaryString.charCodeAt(j + 1) << 8 | + binaryString.charCodeAt(j + 2) << 16 | + binaryString.charCodeAt(j + 3) << 24 + ) >>> 0; + } + + curl.data = bytes; + + delete curl.encoding; + } + else if (curl.compression) + { + console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\''); + continue; + } + + var layer = { + + name: curl.name, + x: curl.x, + y: curl.y, + width: curl.width, + height: curl.height, + widthInPixels: curl.width * json.tilewidth, + heightInPixels: curl.height * json.tileheight, + alpha: curl.opacity, + offsetX: curl.offsetx, + offsetY: curl.offsety, + visible: curl.visible, + properties: {}, + indexes: [], + callbacks: [], + bodies: [] + + }; + + if (curl.properties) + { + layer.properties = curl.properties; + } + + var x = 0; + var row = []; + var output = []; + var rotation, flipped, flippedVal, gid; + + // Loop through the data field in the JSON. + + // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV) + // If the map contains multiple tilesets then the indexes are relative to that which the set starts from. + // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset. + + for (var t = 0, len = curl.data.length; t < len; t++) + { + rotation = 0; + flipped = false; + gid = curl.data[t]; + flippedVal = 0; + + // If true the current tile is flipped or rotated (Tiled TMX format) + if (gid > 0x20000000) + { + // FlippedX + if (gid > 0x80000000) + { + gid -= 0x80000000; + flippedVal += 4; + } + + // FlippedY + if (gid > 0x40000000) + { + gid -= 0x40000000; + flippedVal += 2; + } + + // FlippedAD (anti-diagonal = top-right is swapped with bottom-left corners) + if (gid > 0x20000000) + { + gid -= 0x20000000; + flippedVal += 1; + } + + switch (flippedVal) + { + case 5: + rotation = Math.PI / 2; + break; + + case 6: + rotation = Math.PI; + break; + + case 3: + rotation = 3 * Math.PI / 2; + break; + + case 4: + rotation = 0; + flipped = true; + break; + + case 7: + rotation = Math.PI / 2; + flipped = true; + break; + + case 2: + rotation = Math.PI; + flipped = true; + break; + + case 1: + rotation = 3 * Math.PI / 2; + flipped = true; + break; + } + } + + // index, x, y, width, height + if (gid > 0) + { + var tile = new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight); + + tile.rotation = rotation; + tile.flipped = flipped; + + if (flippedVal !== 0) + { + // The WebGL renderer uses this to flip UV coordinates before drawing + tile.flippedVal = flippedVal; + } + + row.push(tile); + } + else + { + if (Phaser.TilemapParser.INSERT_NULL) + { + row.push(null); + } + else + { + row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight)); + } + } + + x++; + + if (x === curl.width) + { + output.push(row); + x = 0; + row = []; + } + } + + layer.data = output; + + layers.push(layer); + } + + map.layers = layers; + + // Images + var images = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'imagelayer') + { + continue; + } + + var curi = json.layers[i]; + + var image = { + + name: curi.name, + image: curi.image, + x: curi.x, + y: curi.y, + alpha: curi.opacity, + visible: curi.visible, + properties: {} + + }; + + if (curi.properties) + { + image.properties = curi.properties; + } + + images.push(image); + + } + + map.images = images; + + // Tilesets & Image Collections + var tilesets = []; + var tilesetGroupObjects = {}; + var imagecollections = []; + var lastSet = null; + + for (var i = 0; i < json.tilesets.length; i++) + { + // name, firstgid, width, height, margin, spacing, properties + var set = json.tilesets[i]; + + if (set.source) + { + console.warn('Phaser.TilemapParser - Phaser can\'t load external tilesets (%s). Use the Embed Tileset button and then export the map again.', set.source); + } + else if (set.image) + { + var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + if (set.tileproperties) + { + newSet.tileProperties = set.tileproperties; + } + + // For a normal sliced tileset the row/count/size information is computed when updated. + // This is done (again) after the image is set. + newSet.updateTileData(set.imagewidth, set.imageheight); + + tilesets.push(newSet); + } + else if (set.tiles) + { + var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + for (var ti in set.tiles) + { + var image = set.tiles[ti].image; + var gid = set.firstgid + parseInt(ti, 10); + newCollection.addImage(gid, image); + } + + imagecollections.push(newCollection); + } + else + { + throw new Error('Tileset ' + set.name + ' has no `image` or `tiles` property.'); + } + + // build a temporary object for objectgroups found in the tileset's tiles + for (var ti in set.tiles) + { + var objectGroup = set.tiles[ti].objectgroup; + + if (!objectGroup) + { + continue; + } + + tilesetGroupObjects[parseInt(ti, 10) + set.firstgid] = objectGroup; + } + + // We've got a new Tileset, so set the lastgid into the previous one + if (lastSet) + { + lastSet.lastgid = set.firstgid - 1; + } + + lastSet = set; + } + + if (tilesets.length === 0 && imagecollections.length === 0) + { + throw new Error('This tilemap has no tilesets.'); + } + + map.tilesets = tilesets; + map.imagecollections = imagecollections; + + // Objects & Collision Data (polylines, etc) + var objects = {}; + var collision = {}; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'objectgroup') + { + continue; + } + + var objectGroup = json.layers[i]; + this.parseObjectGroup(objectGroup, objects, collision); + } + + map.objects = objects; + map.collision = collision; + + map.tiles = []; + + // Finally lets build our super tileset index + for (var i = 0; i < map.tilesets.length; i++) + { + var set = map.tilesets[i]; + + var x = set.tileMargin; + var y = set.tileMargin; + + var count = 0; + var countX = 0; + var countY = 0; + + for (var t = set.firstgid; t < set.firstgid + set.total; t++) + { + // Can add extra properties here as needed + map.tiles[t] = [x, y, i]; + + x += set.tileWidth + set.tileSpacing; + + count++; + + if (count === set.total) + { + break; + } + + countX++; + + if (countX === set.columns) + { + x = set.tileMargin; + y += set.tileHeight + set.tileSpacing; + + countX = 0; + countY++; + + if (countY === set.rows) + { + break; + } + } + } + + } + + // assign tile properties + + var layer; + var tile; + var sid; + var set; + + // go through each of the map data layers + for (var i = 0; i < map.layers.length; i++) + { + layer = map.layers[i]; + collision[layer.name] = []; + set = null; + + // rows of tiles + for (var j = 0; j < layer.data.length; j++) + { + row = layer.data[j]; + + // individual tiles + for (var k = 0; k < row.length; k++) + { + tile = row[k]; + + if (tile === null || tile.index < 0) + { + continue; + } + + // find the relevant tileset + + sid = map.tiles[tile.index][2]; + set = map.tilesets[sid]; + + + // if that tile type has any properties, add them to the tile object + + if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) + { + tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties); + } + + var objectGroup = tilesetGroupObjects[tile.index]; + if (objectGroup) + { + // build collisions and objects for objectgroups found in the tileset's tiles + this.parseObjectGroup( + objectGroup, + map.objects, + map.collision, + tile.layer.name, + { + x: tile.worldX + objectGroup.x, + y: tile.worldY + objectGroup.y + }); + } + + } + } + } + + return map; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile set is a combination of an image containing the tiles and collision data per tile. +* +* Tilesets are normally created automatically when Tiled data is loaded. +* +* @class Phaser.Tileset +* @constructor +* @param {string} name - The name of the tileset in the map data. +* @param {integer} firstgid - The first tile index this tileset contains. +* @param {integer} [width=32] - Width of each tile (in pixels). +* @param {integer} [height=32] - Height of each tile (in pixels). +* @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels). +* @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels). +* @param {object} [properties={}] - Custom Tileset properties. +*/ +Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Tileset. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first tile index this Tileset contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of each tile (in pixels). + * @property {integer} tileWidth + * @readonly + */ + this.tileWidth = width | 0; + + /** + * The height of each tile (in pixels). + * @property {integer} tileHeight + * @readonly + */ + this.tileHeight = height | 0; + + /** + * The margin around the tiles in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileMarge + * @readonly + */ + // Modified internally + this.tileMargin = margin | 0; + + /** + * The spacing between each tile in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileSpacing + * @readonly + */ + this.tileSpacing = spacing | 0; + + /** + * Tileset-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set. + * @property {?object} image + * @readonly + */ + // Modified internally + this.image = null; + + /** + * The number of tile rows in the the tileset. + * @property {integer} + * @readonly + */ + // Modified internally + this.rows = 0; + + /** + * The number of tile columns in the tileset. + * @property {integer} columns + * @readonly + */ + // Modified internally + this.columns = 0; + + /** + * The total number of tiles in the tileset. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; + + /** + * The look-up table to specific tile image offsets. + * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1. + * @property {integer[]} drawCoords + * @private + */ + this.drawCoords = []; + +}; + +Phaser.Tileset.prototype = { + + /** + * Draws a tile from this Tileset at the given coordinates on the context. + * + * @method Phaser.Tileset#draw + * @public + * @param {CanvasRenderingContext2D} context - The context to draw the tile onto. + * @param {number} x - The x coordinate to draw to. + * @param {number} y - The y coordinate to draw to. + * @param {integer} index - The index of the tile within the set to draw. + */ + draw: function (context, x, y, index) { + + // Correct the tile index for the set and bias for interlacing + var coordIndex = (index - this.firstgid) << 1; + + if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length) + { + context.drawImage( + this.image, + this.drawCoords[coordIndex], + this.drawCoords[coordIndex + 1], + this.tileWidth, + this.tileHeight, + x, + y, + this.tileWidth, + this.tileHeight + ); + } + + }, + + /** + * Returns true if and only if this tileset contains the given tile index. + * + * @method Phaser.Tileset#containsTileIndex + * @public + * @param {number} tileIndex + * @return {boolean} True if this tileset contains the given index. + */ + containsTileIndex: function (tileIndex) { + + return ( + tileIndex >= this.firstgid && + tileIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Set the image associated with this Tileset and update the tile data. + * + * @method Phaser.Tileset#setImage + * @public + * @param {Image} image - The image that contains the tiles. + */ + setImage: function (image) { + + this.image = image; + this.updateTileData(image.width, image.height); + + }, + + /** + * Sets tile spacing and margins. + * + * @method Phaser.Tileset#setSpacing + * @public + * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels). + */ + setSpacing: function (margin, spacing) { + + this.tileMargin = margin | 0; + this.tileSpacing = spacing | 0; + + if (this.image) + { + this.updateTileData(this.image.width, this.image.height); + } + + }, + + /** + * Updates tile coordinates and tileset data. + * + * @method Phaser.Tileset#updateTileData + * @private + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + */ + updateTileData: function (imageWidth, imageHeight) { + + // May be fractional values + var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); + var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); + + if (rowCount % 1 !== 0 || colCount % 1 !== 0) + { + console.warn( + "Phaser.Tileset - '%s' image tile area (%s x %s) is not a whole multiple of tile size (%s x %s + %s + %s)", + this.name, imageWidth, imageHeight, this.tileWidth, this.tileHeight, this.tileMargin, this.tileSpacing + ); + } + + // In Tiled a tileset image that is not an even multiple of the tile dimensions + // is truncated - hence the floor when calculating the rows/columns. + rowCount = Math.floor(rowCount); + colCount = Math.floor(colCount); + + if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount)) + { + console.warn( + "Phaser.Tileset - Tile layout from image '%s' (%s rows by %s columns) differs from tileset '%s' (%s rows by %s columns)", + this.image.name, colCount, rowCount, this.name, this.columns, this.rows + ); + } + + this.rows = rowCount; + this.columns = colCount; + this.total = rowCount * colCount; + + this.drawCoords.length = 0; + + var tx = this.tileMargin; + var ty = this.tileMargin; + + for (var y = 0; y < this.rows; y++) + { + for (var x = 0; x < this.columns; x++) + { + this.drawCoords.push(tx); + this.drawCoords.push(ty); + tx += this.tileWidth + this.tileSpacing; + } + + tx = this.tileMargin; + ty += this.tileHeight + this.tileSpacing; + } + + } + +}; + +Phaser.Tileset.prototype.constructor = Phaser.Tileset; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. +* +* @class Phaser.Particle +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Particle = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + /** + * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData. + * @protected + */ + this.autoScale = false; + + /** + * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.scaleData = null; + + /** + * @property {number} _s - Internal cache var for tracking auto scale. + * @private + */ + this._s = 0; + + /** + * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. + * @protected + */ + this.autoAlpha = false; + + /** + * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.alphaData = null; + + /** + * @property {number} _a - Internal cache var for tracking auto alpha. + * @private + */ + this._a = 0; + +}; + +Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Particle.prototype.constructor = Phaser.Particle; + +/** +* Updates the Particle scale or alpha if autoScale and autoAlpha are set. +* +* @method Phaser.Particle#update +* @memberof 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; + } + } + +}; + +/** +* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. +* +* @method Phaser.Particle#onEmit +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.onEmit = function() { +}; + +/** +* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. +* +* @method Phaser.Particle#setAlphaData +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.setAlphaData = function(data) { + + this.alphaData = data; + this._a = data.length - 1; + this.alpha = this.alphaData[this._a].v; + this.autoAlpha = true; + +}; + +/** +* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. +* +* @method Phaser.Particle#setScaleData +* @memberof Phaser.Particle +*/ +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; + +}; + +/** +* Resets the Particle. This places the Particle at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. +* If the Particle has a physics body that too is reset. +* +* @method Phaser.Particle#reset +* @memberof Phaser.Particle +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {number} [health=1] - The health to give the Particle. +* @return {Phaser.Particle} This instance. +*/ +Phaser.Particle.prototype.reset = function(x, y, health) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y, health); + + this.alpha = 1; + this.scale.set(1); + + this.autoScale = false; + this.autoAlpha = false; + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Particles tracks any Emitters attached to it. +* +* @class Phaser.Particles +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Particles = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} emitters - Internal emitters store. + */ + this.emitters = {}; + + /** + * @property {number} ID - + * @default + */ + this.ID = 0; + +}; + +Phaser.Particles.prototype = { + + /** + * Adds a new Particle Emitter to the Particle Manager. + * @method Phaser.Particles#add + * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. + * @return {Phaser.Emitter} The emitter that was added. + */ + add: function (emitter) { + this.emitters[emitter.id] = emitter; + return emitter; + }, + + /** + * Removes an existing Particle Emitter from the Particle Manager. + * @method Phaser.Particles#remove + * @param {Phaser.Emitter} emitter - The emitter to remove. + */ + remove: function (emitter) { + delete this.emitters[emitter.id]; + } + +}; + +Phaser.Particles.prototype.constructor = Phaser.Particles; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Arcade Particles is a Particle System integrated with Arcade Physics. +* +* @class Phaser.Particles.Arcade +*/ +Phaser.Particles.Arcade = {}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Emitter is a lightweight particle emitter that uses Arcade Physics. +* It can be used for one-time explosions or for continuous effects like rain and fire. +* All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. +* +* @class Phaser.Particles.Arcade.Emitter +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. +* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. +* @param {number} [maxParticles=50] - The total number of particles in this emitter. +*/ +Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { + + /** + * @property {number} maxParticles - The total number of particles in this emitter. + * @default + */ + this.maxParticles = maxParticles || 50; + + Phaser.Group.call(this, game); + + /** + * @property {number} _id - Internal ID for this emitter -- only used by the Particle System in most cases + * @private + */ + this._id = this.game.particles.ID++; + + /** + * @property {string} name - A handy string name for this emitter. Can be set to anything. + */ + this.name = 'emitter' + this.id; + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.EMITTER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * @property {Phaser.Rectangle} area - The {@link #setSize size} of the emitter's emit area. The **actual** emit area is a rectangle of this size centered on (emitX, emitY): `{x: this.left, y: this.top, width: this.area.width, height: this.area.height}`. Particles are generated at a random position within this area. + * @default + */ + this.area = new Phaser.Rectangle(x, y, 1, 1); + + /** + * @property {?number} minAngle - The minimum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #maxAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.minAngle = null; + + /** + * @property {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #minAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.maxAngle = null; + + /** + * @property {number} minSpeed - The minimum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.minSpeed = 0; + + /** + * @property {number} maxSpeed - The maximum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.maxSpeed = 100; + + /** + * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle. + * @default + */ + this.minParticleSpeed = new Phaser.Point(-100, -100); + + /** + * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle. + * @default + */ + this.maxParticleSpeed = new Phaser.Point(100, 100); + + /** + * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. + * @default + */ + this.minParticleScale = 1; + + /** + * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. + * @default + */ + this.maxParticleScale = 1; + + /** + * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0. + */ + this.scaleData = null; + + /** + * @property {number} minRotation - The minimum possible angular velocity of a particle. + * @default + */ + this.minRotation = -360; + + /** + * @property {number} maxRotation - The maximum possible angular velocity of a particle. + * @default + */ + this.maxRotation = 360; + + /** + * @property {number} minParticleAlpha - The minimum possible alpha value of a particle. + * @default + */ + this.minParticleAlpha = 1; + + /** + * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle. + * @default + */ + this.maxParticleAlpha = 1; + + /** + * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0. + */ + this.alphaData = null; + + /** + * @property {function} particleClass - For emitting your own particle class types. They must extend Phaser.Particle. + * @default + */ + this.particleClass = Phaser.Particle; + + /** + * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter. + */ + this.particleDrag = new Phaser.Point(); + + /** + * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false). + * @default + */ + this.frequency = 100; + + /** + * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. + * @default + */ + this.lifespan = 2000; + + /** + * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. + */ + this.bounce = new Phaser.Point(); + + /** + * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. + * @default + */ + this.on = false; + + /** + * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) + * @default + */ + this.particleAnchor = new Phaser.Point(0.5, 0.5); + + /** + * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) + * @default + */ + this.blendMode = Phaser.blendModes.NORMAL; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitX + */ + this.emitX = x; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitY + */ + this.emitY = y; + + /** + * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. + */ + this.autoScale = false; + + /** + * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. + */ + this.autoAlpha = false; + + /** + * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. + * @default + */ + this.particleBringToTop = false; + + /** + * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. + * @default + */ + this.particleSendToBack = false; + + /** + * @property {object} counts - Records emitter activity. + * @property {number} counts.emitted - How many particles were emitted during the last update. + * @property {number} counts.failed - How many particles could not be emitted during the last update (because no particles were available). + * @property {number} counts.totalEmitted - How many particles have been emitted. + * @property {number} counts.totalFailed - How many particles could not be emitted when they were due (because no particles were available). + */ + this.counts = { + emitted: 0, + failed: 0, + totalEmitted: 0, + totalFailed: 0 + }; + + /** + * @property {Phaser.Point} _gravity - Internal gravity value. + * @private + */ + this._gravity = new Phaser.Point(0, 100); + + /** + * @property {Phaser.Point} _minParticleScale - Internal particle scale var. + * @private + */ + this._minParticleScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} _maxParticleScale - Internal particle scale var. + * @private + */ + this._maxParticleScale = new Phaser.Point(1, 1); + + /** + * @property {number} _total - Internal helper for deciding how many particles to launch (via {@link #start}). + * @private + */ + this._total = 0; + + /** + * @property {number} _timer - Internal helper for deciding when to launch particles or kill them. + * @private + */ + this._timer = 0; + + /** + * @property {number} _counter - Internal counter for figuring out how many particles to launch. + * @private + */ + this._counter = 0; + + /** + * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update. + * @private + */ + this._flowQuantity = 0; + + /** + * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total (via {@link #flow}). + * @private + */ + this._flowTotal = 0; + + /** + * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time). + * @private + */ + this._explode = true; + + /** + * @property {any} _frames - Internal helper for the particle frame. + * @private + */ + this._frames = null; + +}; + +Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); +Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter; + +/** +* Called automatically by the game loop, decides when to launch particles and when to "die". +* +* @method Phaser.Particles.Arcade.Emitter#update +*/ +Phaser.Particles.Arcade.Emitter.prototype.update = function () { + + this.counts.emitted = 0; + this.counts.failed = 0; + + if (this.on && this.game.time.time >= this._timer) + { + this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion; + + if (this._flowTotal !== 0) + { + if (this._flowQuantity > 0) + { + for (var i = 0; i < this._flowQuantity; i++) + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + break; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._total > 0 && this._counter >= this._total) + { + this.on = false; + } + } + } + + } + + var i = this.children.length; + + while (i--) + { + if (this.children[i].exists) + { + this.children[i].update(); + } + } + +}; + +/** +* This function generates a new set of particles for use by this emitter. +* The particles are stored internally waiting to be emitted via Emitter.start. +* +* @method Phaser.Particles.Arcade.Emitter#makeParticles +* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. +* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random. +* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. +* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. +* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. +* @param {object} [particleArguments=null] - Custom arguments to pass to your particle class +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds, particleArguments) { + + if (frames === undefined) { frames = 0; } + if (quantity === undefined) { quantity = this.maxParticles; } + if (collide === undefined) { collide = false; } + if (collideWorldBounds === undefined) { collideWorldBounds = false; } + if (particleArguments === undefined) { particleArguments = null; } + + var particle; + var i = 0; + var rndKey = keys; + var rndFrame = frames; + this._frames = frames; + + if (quantity > this.maxParticles) + { + this.maxParticles = quantity; + } + + while (i < quantity) + { + if (Array.isArray(keys)) + { + rndKey = this.game.rnd.pick(keys); + } + + if (Array.isArray(frames)) + { + rndFrame = this.game.rnd.pick(frames); + } + + particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame, particleArguments); + + this.game.physics.arcade.enable(particle, false); + + particle.body.checkCollision.none = !collide; + particle.body.collideWorldBounds = collideWorldBounds; + particle.body.skipQuadTree = true; + + particle.exists = false; + particle.visible = false; + particle.anchor.copyFrom(this.particleAnchor); + + this.add(particle); + + i++; + } + + return this; + +}; + +/** +* Call this function to turn off all the particles and the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#kill +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.kill = function () { + + this.on = false; + this.alive = false; + this.exists = false; + + return this; + +}; + +/** +* Handy for bringing game objects "back to life". Just sets alive and exists back to true. +* +* @method Phaser.Particles.Arcade.Emitter#revive +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.revive = function () { + + this.alive = true; + this.exists = true; + + return this; + +}; + +/** +* Call this function to emit the given quantity of particles at all once (an explosion) +* +* @method Phaser.Particles.Arcade.Emitter#explode +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [quantity=this.maxParticles] - How many particles to launch. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) { + + if (quantity === undefined) { + quantity = this.maxParticles; + } + + this._flowTotal = 0; + + this.start(true, lifespan, 0, quantity, false); + + return this; + +}; + +/** +* Call this function to start emitting a flow of particles. +* `quantity` particles are released every interval of `frequency` ms until `total` particles have been released (or forever). +* If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 × 5 = 20 total) and then turn {@link #on off}. +* If you set the total to be -1 then no quantity cap is used and it will keep emitting (as long as there are inactive particles available). +* +* {@link #output}, {@link #lifespanOutput}, and {@link #remainder} describe the particle flow rate. +* During a stable flow, the number of active particles approaches {@link #lifespanOutput} and the number of inactive particles approaches {@link #remainder}. +* If {@link #remainder} is less than 0, there will likely be no particles available for a portion of the flow (see {@link #count}). +* +* @method Phaser.Particles.Arcade.Emitter#flow +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of particles, given in ms. Values between 0 and 16.66 will behave the same (60 releases per second). +* @param {number} [quantity=1] - How many particles to launch at each interval. Not larger than {@link #maxParticles}. +* @param {number} [total=-1] - Turn {@link #on off} after launching this many particles in total. If -1 it will carry on indefinitely. +* @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) { + + if (frequency === undefined || frequency === null) { frequency = 250; } + if (quantity === undefined || quantity === 0) { quantity = 1; } + if (total === undefined) { total = -1; } + if (immediate === undefined) { immediate = true; } + + if (quantity > this.maxParticles) + { + quantity = this.maxParticles; + } + + this._counter = 0; + this._flowQuantity = quantity; + this._flowTotal = total; + + if (immediate) + { + this.start(true, lifespan, frequency, quantity); + + this._counter += quantity; + this.on = true; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + else + { + this.start(false, lifespan, frequency, quantity); + } + + return this; + +}; + +/** +* Start emitting particles. +* +* {@link #explode} and {@link #flow} are simpler methods. +* +* There are two patterns, based on the `explode` argument: +* +* ##### explode=true +* +* start(true, lifespan=0, null, total) +* +* When `explode` is true or `forceQuantity` is true, `start` emits `total` particles immediately. You should pass a nonzero `total`. +* +* ##### explode=false +* +* start(false, lifespan=0, frequency=250, total=0) +* +* When `explode` is false and `forceQuantity` is false, `start` emits 1 particle every interval of `frequency` ms. If `total` is not zero, the emitter turns itself off after `total` particles have been released. If `total` is zero, the emitter keeps emitting particles as long as they are available. To emit more than 1 particle per flow interval, use {@link #flow} instead. +* +* `forceQuantity` seems equivalent to `explode` and can probably be avoided. +* +* @method Phaser.Particles.Arcade.Emitter#start +* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false). +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of 1 particle, when `explode` is false. Value given in ms. Ignored if `explode` is set to true. +* @param {number} [total=0] - Turn {@link #on off} after launching this many particles in total. +* @param {number} [forceQuantity=false] - Equivalent to `explodes`. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, total, forceQuantity) { + + if (explode === undefined) { explode = true; } + if (lifespan === undefined) { lifespan = 0; } + if (frequency === undefined || frequency === null) { frequency = 250; } + if (total === undefined) { total = 0; } + if (forceQuantity === undefined) { forceQuantity = false; } + + if (total > this.maxParticles) + { + total = this.maxParticles; + } + + this.revive(); + + this.visible = true; + + this.lifespan = lifespan; + this.frequency = frequency; + + if (explode || forceQuantity) + { + for (var i = 0; i < total; i++) + { + this.emitParticle(); + } + } + else + { + this.on = true; + this._total = total; + this._counter = 0; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + + return this; + +}; + +/** +* This function is used internally to emit the next particle in the queue. +* +* However it can also be called externally to emit a particle. +* +* When called externally you can use the arguments to override any defaults the Emitter has set. +* +* The newly emitted particle is available in {@link Phaser.Particles.Arcade.Emitter#cursor}. +* +* @method Phaser.Particles.Arcade.Emitter#emitParticle +* @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. +* @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {boolean} True if a particle was emitted, otherwise false. +*/ +Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + var particle = this.getNextParticle(); + + if (particle === null) + { + this.counts.failed++; + this.counts.totalFailed++; + + return false; + } + + this.counts.emitted++; + this.counts.totalEmitted++; + + var rnd = this.game.rnd; + + if (key !== undefined && frame !== undefined) + { + particle.loadTexture(key, frame); + } + else if (key !== undefined) + { + particle.loadTexture(key); + particle.frame = Array.isArray(this._frames) ? rnd.pick(this._frames) : this._frames; + } + + var emitX = this.emitX; + var emitY = this.emitY; + + if (x !== null) + { + emitX = x; + } + else if (this.width > 1) + { + emitX = rnd.between(this.left, this.right); + } + + if (y !== null) + { + emitY = y; + } + else if (this.height > 1) + { + emitY = rnd.between(this.top, this.bottom); + } + + this.resetParticle(particle, emitX, emitY); + + return true; + +}; + + +/** +* Helper for {@link #emitParticle}. Gets the next available particle. +* +* @private +* @return {?Phaser.Particle} The first particle with exists=false, or null +*/ +Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () { + + var i = this.length; + + while (i--) + { + var next = this.next(); + + if (!next.exists) + { + return next; + } + } + + return null; + +}; + +/** + * Helper for {@link #emitParticle}. Sets particle properties and calls {@link Particle#onEmit}. + * + * @private + * @param {Phaser.Particle} particle + * @param {number} x + * @param {number} y + */ +Phaser.Particles.Arcade.Emitter.prototype.resetParticle = function (particle, x, y) { + + var rnd = this.game.rnd; + + particle.reset(x, y); + + 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(rnd.realInRange(this.minParticleScale, this.maxParticleScale)); + } + else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y)) + { + particle.scale.set(rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y)); + } + else + { + particle.scale.set(this._minParticleScale.x, this._minParticleScale.y); + } + + if (this.autoAlpha) + { + particle.setAlphaData(this.alphaData); + } + else + { + particle.alpha = rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha); + } + + particle.blendMode = this.blendMode; + + var body = particle.body; + + body.updateBounds(); + + body.bounce.copyFrom(this.bounce); + body.drag.copyFrom(this.particleDrag); + + if (this.minAngle != null && this.maxAngle != null) + { + this.game.physics.arcade.velocityFromAngle( + (this.minAngle === this.maxAngle) ? this.minAngle : rnd.between(this.minAngle, this.maxAngle), + (this.minSpeed === this.maxSpeed) ? this.minSpeed : rnd.between(this.minSpeed, this.maxSpeed), + body.velocity + ); + } + else + { + body.velocity.x = rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x); + body.velocity.y = rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y); + } + + body.angularVelocity = rnd.between(this.minRotation, this.maxRotation); + body.gravity.copyFrom(this.gravity); + body.angularDrag = this.angularDrag; + + particle.onEmit(); + +}; + +/** +* Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. +* +* @method Phaser.Particles.Arcade.Emitter#destroy +*/ +Phaser.Particles.Arcade.Emitter.prototype.destroy = function () { + + this.game.particles.remove(this); + + Phaser.Group.prototype.destroy.call(this, true, false); + +}; + +/** +* A more compact way of setting the width and height of the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#setSize +* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). +* @param {number} height - The desired height of the emitter. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { + + this.area.width = width; + this.area.height = height; + + return this; + +}; + +/** +* A more compact way of setting the X velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setXSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.x = min; + this.maxParticleSpeed.x = max; + + return this; + +}; + +/** +* A more compact way of setting the Y velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setYSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.y = min; + this.maxParticleSpeed.y = max; + + return this; + +}; + +/** +* A more compact way of setting the angular velocity constraints of the particles. +* +* @method Phaser.Particles.Arcade.Emitter#setRotation +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minRotation = min; + this.maxRotation = max; + + return this; + +}; + +/** +* A more compact way of setting the alpha constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. +* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setAlpha +* @param {number} [min=1] - The minimum value for this range. +* @param {number} [max=1] - The maximum value for this range. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) { + + if (min === undefined) { min = 1; } + if (max === undefined) { max = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.alphaData.reverse(); + this.autoAlpha = true; + } + + return this; + +}; + +/** +* A more compact way of setting the scale constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. +* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setScale +* @param {number} [minX=1] - The minimum value of Particle.scale.x. +* @param {number} [maxX=1] - The maximum value of Particle.scale.x. +* @param {number} [minY=1] - The minimum value of Particle.scale.y. +* @param {number} [maxY=1] - The maximum value of Particle.scale.y. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) { + + if (minX === undefined) { minX = 1; } + if (maxX === undefined) { maxX = 1; } + if (minY === undefined) { minY = 1; } + if (maxY === undefined) { maxY = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (yoyo === undefined) { yoyo = false; } + + // Reset these + 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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.scaleData.reverse(); + this.autoScale = true; + } + + return this; + +}; + +/** + * Sets a radial pattern for emitting particles. + * + * This is a shorthand for setting {@link #minAngle}, {@link #maxAngle}, {@link #minSpeed}, and {@link #maxSpeed}. + * + * To remove the radial pattern, use `setAngle(null, null)`. + * + * @method Phaser.Particles.Arcade.Emitter#setAngle + * @param {?number} minAngle - The minimum angle of initial particle velocities, in degrees. + * @param {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. + * @param {number} [minSpeed] - The minimum initial particle speed. + * @param {number} [maxSpeed] - The maximum initial particle speed. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ +Phaser.Particles.Arcade.Emitter.prototype.setAngle = function (minAngle, maxAngle, minSpeed, maxSpeed) { + + this.minAngle = minAngle; + this.maxAngle = maxAngle; + + if (minSpeed != null) { this.minSpeed = minSpeed; } + if (maxSpeed != null) { this.maxSpeed = maxSpeed; } + + return this; + +}; + +/** +* Change the emitter's center to match the center of any object with a `center` property, such as an Arcade Body. +* If the object doesn't have a `center` property it will be set to the object's anchor-adjusted world position (`object.world`). +* +* @method Phaser.Particles.Arcade.Emitter#at +* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +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); + } + + return this; + +}; + +/** + * @name Phaser.Particles.Arcade.Emitter#gravity + * @property {Phaser.Point} gravity - Sets the `body.gravity` of each particle sprite to this on launch. + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "gravity", { + + get: function () { + return this._gravity; + }, + + set: function (value) { + if (typeof value === "number") + { + this._gravity.y = value; + } + else + { + this._gravity = value; + } + } + +}); + + +/** +* @name Phaser.Particles.Arcade.Emitter#id +* @property {number} id - Gets the internal ID that represents this emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "id", { + get: function () { + return this._id; + } +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#width +* @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", { + + get: function () { + return this.area.width; + }, + + set: function (value) { + this.area.width = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#height +* @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", { + + get: function () { + return this.area.height; + }, + + set: function (value) { + this.area.height = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#x +* @property {number} x - Gets or sets the x position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", { + + get: function () { + return this.emitX; + }, + + set: function (value) { + this.emitX = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#y +* @property {number} y - Gets or sets the y position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", { + + get: function () { + return this.emitY; + }, + + set: function (value) { + this.emitY = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#left +* @property {number} left - Gets the left position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", { + + get: function () { + return Math.floor(this.x - (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#right +* @property {number} right - Gets the right position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", { + + get: function () { + return Math.floor(this.x + (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#top +* @property {number} top - Gets the top position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", { + + get: function () { + return Math.floor(this.y - (this.area.height / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#bottom +* @property {number} bottom - Gets the bottom position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", { + + get: function () { + return Math.floor(this.y + (this.area.height / 2)); + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#output + * @property {number} output - The number of particles released per second, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "output", { + + get: function () { + return 1000 * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#lifespanOutput + * @property {number} lifespanOutput - The number of particles released during one particle's {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "lifespanOutput", { + + get: function () { + return (this.lifespan === 0 ? Infinity : this.lifespan) * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#remainder + * @property {number} remainder - The expected number of unreleased particles after a flow interval of {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "remainder", { + + get: function () { + return this.maxParticles - this.lifespanOutput; + } + +}); + +/** +* The last particle released, if any. +* +* You should treat this as read-only (and also avoid {@link #next} and {@link #previous}) once the emitter is started. Phaser uses it internally to track particles. +* +* @name Phaser.Particles.Arcade.Emitter#cursor +* @property {?DisplayObject} cursor +* @readonly +*/ +// Inherited from Phaser.Group#cursor + +/** +* Advances the cursor to the next particle. +* +* @method Phaser.Particles.Arcade.Emitter#next +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#next + +/** +* Moves the group cursor to the previous particle. +* +* @method Phaser.Particles.Arcade.Emitter#previous +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#previous + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Weapon Plugin provides the ability to easily create a bullet pool and manager. +* +* Weapons fire {@link Phaser.Bullet} objects, which are essentially Sprites with a few extra properties. +* The Bullets are enabled for {@link Phaser.Physics.Arcade Arcade Physics}. They do not currently work with P2 Physics. +* +* The Bullets are created inside of {@link #bullets weapon.bullets}, which is a {@link Phaser.Group} instance. Anything you +* can usually do with a Group, such as move it around the display list, iterate it, etc can be done +* to the bullets Group too. +* +* Bullets can have textures and even animations. You can control the speed at which they are fired, +* the firing rate, the firing angle, and even set things like gravity for them. +* +* A small example, using {@link Phaser.GameObjectFactory#weapon add.weapon}, assumed to be running from within a {@link Phaser.State#create} method: +* +* ```javascript +* var weapon = this.add.weapon(10, 'bullet'); +* weapon.fireFrom.set(300, 300); +* this.input.onDown.add(weapon.fire, this); +* ``` +* +* If you want to (re)create the bullet pool separately, you can use: +* +* ```javascript +* var weapon = this.game.plugins.add(Phaser.Weapon); +* // … +* weapon.createBullets(10, 'bullet'); +* ``` +* +* @class Phaser.Weapon +* @constructor +* @param {Phaser.Game} game - A reference to the current Phaser.Game instance. +* @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin. +*/ +Phaser.Weapon = function (game, parent) { + + Phaser.Plugin.call(this, game, parent); + + /** + * This is the Phaser.Group that contains all of the bullets managed by this plugin. + * @type {Phaser.Group} + */ + this.bullets = null; + + /** + * Should the bullet pool run out of bullets (i.e. they are all in flight) then this + * boolean controls if the Group will create a brand new bullet object or not. + * @type {boolean} + * @default + */ + this.autoExpandBulletsGroup = false; + + /** + * Will this weapon auto fire? If set to true then a new bullet will be fired + * based on the {@link #fireRate} value. + * @type {boolean} + * @default + */ + this.autofire = false; + + /** + * The total number of bullets this Weapon has fired so far. + * You can limit the number of shots allowed (via {@link #fireLimit}), and reset + * this total via {@link #resetShots}. + * @type {number} + * @default + */ + this.shots = 0; + + /** + * The maximum number of shots that this Weapon is allowed to fire before it stops. + * When the limit is his the {@link #onFireLimit} Signal is dispatched. + * You can reset the shot counter via {@link #resetShots}. + * @type {number} + * @default + */ + this.fireLimit = 0; + + /** + * The minimum interval between shots, in milliseconds. + * @type {number} + * @default + */ + this.fireRate = 100; + + /** + * This is a modifier that is added to the {@link #fireRate} each update to add variety + * to the firing rate of the Weapon. The value is given in milliseconds. + * If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual + * firing rate of the Weapon will be between 150 and 250. + * @type {number} + * @default + */ + this.fireRateVariance = 0; + + /** + * This is a Rectangle from within which the bullets are fired. By default it's a 1x1 + * rectangle, the equivalent of a Point. But you can change the width and height, and if + * larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from. + * @type {Phaser.Rectangle} + */ + this.fireFrom = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE_UP + * or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right. + * @type {integer} + * @default + */ + this.fireAngle = Phaser.ANGLE_UP; + + /** + * When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set. + * @type {boolean} + * @default + */ + this.bulletInheritSpriteSpeed = false; + + /** + * The string based name of the animation that the Bullet will be given on launch. + * This is set via {@link #addBulletAnimation}. + * @type {string} + * @default + */ + this.bulletAnimation = ''; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to pick a random frame from the set. + * @type {boolean} + * @default + */ + this.bulletFrameRandom = false; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to use the next frame in the set. The frame index is then + * advanced one frame until it reaches the end of the set, then it starts from the start + * again. Cycling frames like this allows you to create varied bullet effects via + * sprite sheets. + * @type {boolean} + * @default + */ + this.bulletFrameCycle = false; + + /** + * Should the Bullets wrap around the world bounds? This automatically calls + * `World.wrap` on the Bullet each frame. See the docs for that method for details. + * @type {boolean} + * @default + */ + this.bulletWorldWrap = false; + + /** + * If `bulletWorldWrap` is true then you can provide an optional padding value with this + * property. It's added to the calculations determining when the Bullet should wrap around + * the world or not. The value is given in pixels. + * @type {integer} + * @default + */ + this.bulletWorldWrapPadding = 0; + + /** + * An optional angle offset applied to the Bullets when they are launched. + * This is useful if for example your bullet sprites have been drawn facing up, instead of + * to the right, and you want to fire them at an angle. In which case you can set the + * angle offset to be 90 and they'll be properly rotated when fired. + * @type {number} + * @default + */ + this.bulletAngleOffset = 0; + + /** + * This is a variance added to the angle of Bullets when they are fired. + * If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual + * angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a + * great 'spread' effect to a Weapon. + * @type {number} + * @default + */ + this.bulletAngleVariance = 0; + + /** + * The initial velocity of fired bullets, in pixels per second. + * @type {number} + * @default + */ + this.bulletSpeed = 200; + + /** + * This is a variance added to the speed of Bullets when they are fired. + * If bullets have a {@link #bulletSpeed} value of 200, and a `bulletSpeedVariance` of 50 + * then the actual speed of the Bullets will be between 150 and 250 pixels per second. + * @type {number} + * @default + */ + this.bulletSpeedVariance = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount + * of lifespan the Bullets have set on launch. The value is given in milliseconds. + * When a Bullet hits its lifespan limit it will be automatically killed. + * @type {number} + * @default + */ + this.bulletLifespan = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_DISTANCE` this controls the distance + * the Bullet can travel before it is automatically killed. The distance is given in pixels. + * @type {number} + * @default + */ + this.bulletKillDistance = 0; + + /** + * This is the amount of {@link Phaser.Physics.Arcade.Body#gravity} added to the Bullets physics body when fired. + * Gravity is expressed in pixels / second / second. + * @type {Phaser.Point} + */ + this.bulletGravity = new Phaser.Point(0, 0); + + /** + * Bullets can optionally adjust their rotation in-flight to match their velocity. + * This can create the effect of a bullet 'pointing' to the path it is following, for example + * an arrow being fired from a bow, and works especially well when added to {@link #bulletGravity}. + * @type {boolean} + * @default + */ + this.bulletRotateToVelocity = false; + + /** + * The Texture Key that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string} + * @default + */ + this.bulletKey = ''; + + /** + * The Texture Frame that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string|integer} + * @default + */ + this.bulletFrame = ''; + + /** + * Private var that holds the public `bulletClass` property. + * @type {function} + * @private + */ + this._bulletClass = Phaser.Bullet; + + /** + * Private var that holds the public `bulletCollideWorldBounds` property. + * @type {boolean} + * @private + */ + this._bulletCollideWorldBounds = false; + + /** + * Private var that holds the public `bulletKillType` property. + * @type {integer} + * @private + */ + this._bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; + + /** + * Holds internal data about custom bullet body sizes. + * + * @type {Object} + * @private + */ + this._data = { + customBody: false, + width: 0, + height: 0, + offsetX: 0, + offsetY: 0 + }; + + /** + * This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not. + * It's used in combination with {@link #bulletKillType} when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS` + * or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored. + * If you are tracking a Sprite or Point then the bounds are centered on that object every frame. + * + * @type {Phaser.Rectangle} + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The Rectangle used to calculate the bullet bounds from. + * + * @type {Phaser.Rectangle} + * @private + */ + this.bulletBounds = game.world.bounds; + + /** + * This array stores the frames added via @link #setBulletFrames. + * + * @type {Array} + * @protected + */ + this.bulletFrames = []; + + /** + * The index of the frame within {@link #bulletFrames} that is currently being used. + * This value is only used if {@link #bulletFrameCycle} is set to `true`. + * @type {number} + * @private + */ + this.bulletFrameIndex = 0; + + /** + * An internal object that stores the animation data added via {@link #addBulletAnimation}. + * @type {Object} + * @private + */ + this.anims = {}; + + /** + * The onFire Signal is dispatched each time {@link #fire} is called, and a Bullet is + * _successfully_ launched. The callback is set two arguments: a reference to the bullet sprite itself, + * and a reference to the Weapon that fired the bullet. + * + * @type {Phaser.Signal} + */ + this.onFire = new Phaser.Signal(); + + /** + * The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result + * of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance. + * The callback is sent one argument: A reference to the bullet sprite itself. + * + * @type {Phaser.Signal} + */ + this.onKill = new Phaser.Signal(); + + /** + * The onFireLimit Signal is dispatched if {@link #fireLimit} is > 0, and a bullet launch takes the number + * of shots fired to equal the fire limit. + * The callback is sent two arguments: A reference to this Weapon, and the value of + * {@link #fireLimit}. + * + * @type {Phaser.Signal} + */ + this.onFireLimit = new Phaser.Signal(); + + /** + * The Sprite currently being tracked by the Weapon, if any. + * This is set via the {@link #trackSprite} method. + * + * @type {Phaser.Sprite|Object} + */ + this.trackedSprite = null; + + /** + * The Pointer currently being tracked by the Weapon, if any. + * This is set via the {@link #trackPointer} method. + * + * @type {Phaser.Pointer} + */ + this.trackedPointer = null; + + /** + * If you want this Weapon to be able to fire more than 1 bullet in a single + * update, then set this property to `true`. When `true` the Weapon plugin won't + * set the shot / firing timers until the `postRender` phase of the game loop. + * This means you can call `fire` (and similar methods) as often as you like in one + * single game update. + * + * @type {boolean} + * @default + */ + this.multiFire = false; + + /** + * Internal multiFire test flag. + * + * @type {boolean} + */ + this._hasFired = false; + + /** + * If the Weapon is tracking a Sprite, should it also track the Sprites rotation? + * This is useful for a game such as Asteroids, where you want the weapon to fire based + * on the sprites rotation. + * + * @type {boolean} + * @default + */ + this.trackRotation = false; + + /** + * The Track Offset is a Point object that allows you to specify a pixel offset that bullets use + * when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels + * in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have + * the bullet launched from the center of the Sprite. + * + * @type {Phaser.Point} + */ + this.trackOffset = new Phaser.Point(); + + /** + * Internal firing rate time tracking variable. + * + * @type {number} + * @private + */ + this._nextFire = 0; + + /** + * Internal firing rate time tracking variable used by multiFire. + * + * @type {number} + * @private + */ + this._tempNextFire = 0; + + /** + * Internal firing rotation tracking point. + * + * @type {Phaser.Point} + * @private + */ + this._rotatedPoint = new Phaser.Point(); + +}; + +Phaser.Weapon.prototype = Object.create(Phaser.Plugin.prototype); +Phaser.Weapon.prototype.constructor = Phaser.Weapon; + +/** +* A {@link #bulletKillType} constant that stops the bullets from ever being destroyed automatically. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_NEVER = 0; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when their {@link #bulletLifespan} expires. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_LIFESPAN = 1; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets after they +* exceed the {@link #bulletDistance} from their original firing position. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_DISTANCE = 2; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WEAPON_BOUNDS = 3; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.Camera#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_CAMERA_BOUNDS = 4; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.World#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WORLD_BOUNDS = 5; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_STATIC_BOUNDS = 6; + +/** +* This method performs two actions: First it will check to see if the {@link #bullets} Group exists or not, +* and if not it creates it, adding it the `group` given as the 4th argument. +* +* Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame +* provided (if any). +* +* If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets +* in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of +* the in-flight bullets have been killed, freeing them up for use by the Weapon again. +* +* If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will +* keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however, +* so be careful it doesn't grow too large. +* +* You can either set the texture key and frame here, or via the {@link #bulletKey} and {@link #bulletFrame} +* properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a +* single Weapon instance must share the same texture key however. +* +* @method Phaser.Weapon#createBullets +* @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. +* @param {string} [key] - The Game.cache key of the image that this Sprite will use. +* @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. +* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.createBullets = function (quantity, key, frame, group) { + + if (quantity === undefined) { quantity = 1; } + if (group === undefined) { group = this.game.world; } + + if (this.bullets && !this.bullets.game) + { + this.bullets = null; + } + + if (!this.bullets) + { + this.bullets = this.game.add.physicsGroup(Phaser.Physics.ARCADE, group); + this.bullets.classType = this._bulletClass; + } + + if (quantity !== 0) + { + if (quantity === -1) + { + this.autoExpandBulletsGroup = true; + quantity = 1; + } + + this.bullets.createMultiple(quantity, key, frame); + + this.bullets.setAll('data.bulletManager', this); + + this.bulletKey = key; + this.bulletFrame = frame; + } + + return this; + +}; + +/** +* Call a function on each in-flight bullet in this Weapon. +* +* See {@link Phaser.Group#forEachExists forEachExists} for more details. +* +* @method Phaser.Weapon#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.forEach = function (callback, callbackContext) { + + this.bullets.forEachExists(callback, callbackContext, arguments); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `false` on each bullet in this Weapon. +* This has the effect of stopping them in-flight should they be moving. +* It also stops them being able to be checked for collision. +* +* @method Phaser.Weapon#pauseAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.pauseAll = function () { + + this.bullets.setAll('body.enable', false); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `true` on each bullet in this Weapon. +* This has the effect of resuming their motion should they be in-flight. +* It also enables them for collision checks again. +* +* @method Phaser.Weapon#resumeAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resumeAll = function () { + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Calls {@link Phaser.Bullet#kill} on every in-flight bullet in this Weapon. +* Also re-enables their physics bodies, should they have been disabled via {@link #pauseAll}. +* +* @method Phaser.Weapon#killAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.killAll = function () { + + this.bullets.callAllExists('kill', true); + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Resets the {@link #shots} counter back to zero. This is used when you've set +* {@link #fireLimit} and have hit (or just wish to reset) your limit. +* +* @method Phaser.Weapon#resetShots +* @param {integer} [newLimit] - Optionally set a new {@link #fireLimit}. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resetShots = function (newLimit) { + + this.shots = 0; + + if (newLimit !== undefined) + { + this.fireLimit = newLimit; + } + + return this; + +}; + +/** +* Destroys this Weapon. It removes itself from the PluginManager, destroys +* the {@link #bullets} Group, and nulls internal references. +* +* @method Phaser.Weapon#destroy +*/ +Phaser.Weapon.prototype.destroy = function () { + + this.parent.remove(this, false); + + this.bullets.destroy(); + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#update +* @protected +*/ +Phaser.Weapon.prototype.update = function () { + + if (this._bulletKillType === Phaser.Weapon.KILL_WEAPON_BOUNDS) + { + if (this.trackedSprite) + { + this.trackedSprite.updateTransform(); + this.bounds.centerOn(this.trackedSprite.worldPosition.x, this.trackedSprite.worldPosition.y); + } + else if (this.trackedPointer) + { + this.bounds.centerOn(this.trackedPointer.worldX, this.trackedPointer.worldY); + } + } + + if (this.autofire) + { + this.fire(); + } + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#postRender +* @protected +*/ +Phaser.Weapon.prototype.postRender = function () { + + if (!this.multiFire || !this._hasFired) + { + return; + } + + this._hasFired = false; + + this._nextFire = this._tempNextFire; + +}; + +/** +* Sets this Weapon to track the given Sprite, or any Object with a public {@link Phaser.Component.Core#world world} Point object. +* When a Weapon tracks a Sprite it will automatically update its {@link #fireFrom} value to match the Sprite's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location. +* +* Calling `trackSprite` will reset {@link #trackedPointer} to null, should it have been set, as you can +* only track _either_ a Sprite, or a Pointer, at once, but not both. +* +* @method Phaser.Weapon#trackSprite +* @param {Phaser.Sprite|Object} sprite - The Sprite to track the position of. +* @param {integer} [offsetX=0] - The horizontal offset from the Sprites position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Sprites position to be applied to the Weapon. +* @param {boolean} [trackRotation=false] - Should the Weapon also track the Sprites rotation? +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackSprite = function (sprite, offsetX, offsetY, trackRotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (trackRotation === undefined) { trackRotation = false; } + + this.trackedPointer = null; + this.trackedSprite = sprite; + this.trackRotation = trackRotation; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Sets this Weapon to track the given Pointer. +* When a Weapon tracks a Pointer it will automatically update its {@link #fireFrom} value to match the Pointer's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location. +* +* Calling `trackPointer` will reset {@link #trackedSprite} to null, should it have been set, as you can +* only track _either_ a Pointer, or a Sprite, at once, but not both. +* +* @method Phaser.Weapon#trackPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to track the position of. Defaults to `Input.activePointer` if not specified. +* @param {integer} [offsetX=0] - The horizontal offset from the Pointers position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Pointers position to be applied to the Weapon. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackPointer = function (pointer, offsetX, offsetY) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this.trackedPointer = pointer; + this.trackedSprite = null; + this.trackRotation = false; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Attempts to fire multiple bullets from the positions defined in the given array. +* +* If you provide a `from` argument, or if there is a tracked Sprite or Pointer, then +* the positions are treated as __offsets__ from the given objects position. +* +* If `from` is undefined, and there is no tracked object, then the bullets are fired +* from the given positions, as they exist in the world. +* +* Calling this method sets {@link #multiFire} to `true`. +* +* If there are not enough bullets available in the pool, and the pool cannot be extended, +* then this method may not fire from all of the given positions. +* +* When the bullets are launched they have their texture and frame updated, as required. +* The velocity of the bullets are calculated based on Weapon properties like {@link #bulletSpeed}. +* +* @method Phaser.Weapon#fireMany +* @param {array} positions - An array of positions. Each position can be any Object, as long as it has public `x` and `y` properties, such as Phaser.Point, { x: 0, y: 0 }, Phaser.Sprite, etc. +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullets **from** the `x` and `y` properties of this object, _instead_ of any {@link #trackedSprite} or `trackedPointer` that is set. +* @return {array} An array containing all of the fired Phaser.Bullet objects, if a launch was successful, otherwise an empty array. +*/ +Phaser.Weapon.prototype.fireMany = function (positions, from) { + + this.multiFire = true; + + var bullets = []; + + var _this = this; + + if (from || this.trackedSprite || this.trackedPointer) + { + positions.forEach(function(offset) { + + bullets.push(_this.fire(from, null, null, offset.x, offset.y)); + + }); + } + else + { + positions.forEach(function(position) { + + bullets.push(_this.fire(position)); + + }); + } + + return bullets; + +}; + +/** +* Attempts to fire a single Bullet from a tracked Sprite or Pointer, but applies an offset +* to the position first. This is the same as calling {@link #fire} and passing in the offset arguments. +* +* If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like {@link #bulletSpeed}. +* +* If you wish to fire multiple bullets in a single game update, then set {@link #multiFire} to `true` +* and you can call this method as many times as you like, per loop. See also {@link #fireMany}. +* +* @method Phaser.Weapon#fireOffset +* @param {number} [offsetX=0] - The horizontal offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @param {number} [offsetY=0] - The vertical offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fireOffset = function (offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + return this.fire(null, null, null, offsetX, offsetY); + +}; + +/** +* Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at. +* +* If you don't provide any of the arguments then it uses those set via properties such as {@link #trackedSprite}, +* {@link #bulletAngle} and so on. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like `bulletSpeed`. +* +* If you wish to fire multiple bullets in a single game update, then set `Weapon.multiFire = true` +* and you can call `fire` as many times as you like, per loop. Multiple fires in a single update +* only counts once towards the `shots` total, but you will still receive a Signal for each bullet. +* +* @method Phaser.Weapon#fire +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides {@link #trackedSprite} or `trackedPointer`. Pass `null` to ignore it. +* @param {number} [x] - The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [offsetX=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a horizontal offset from the launch position. +* @param {number} [offsetY=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a vertical offset from the launch position. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fire = function (from, x, y, offsetX, offsetY) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (this.game.time.now < this._nextFire || (this.fireLimit > 0 && this.shots === this.fireLimit)) + { + return null; + } + + var speed = this.bulletSpeed; + + // Apply +- speed variance + if (this.bulletSpeedVariance !== 0) + { + speed += Phaser.Math.between(-this.bulletSpeedVariance, this.bulletSpeedVariance); + } + + if (from) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(from.x, from.y); + } + else + { + this.fireFrom.x = from.x; + this.fireFrom.y = from.y; + } + } + else if (this.trackedSprite) + { + if (this.trackRotation) + { + this._rotatedPoint.set(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.worldRotation); + + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this._rotatedPoint.x, this._rotatedPoint.y); + } + else + { + this.fireFrom.x = this._rotatedPoint.x; + this.fireFrom.y = this._rotatedPoint.y; + } + } + else + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedSprite.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedSprite.world.y + this.trackOffset.y; + } + } + + if (this.bulletInheritSpriteSpeed) + { + speed += this.trackedSprite.body.speed; + } + } + else if (this.trackedPointer) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedPointer.world.x + this.trackOffset.x, this.trackedPointer.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedPointer.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedPointer.world.y + this.trackOffset.y; + } + } + + if (offsetX !== undefined) + { + this.fireFrom.x += offsetX; + } + + if (offsetY !== undefined) + { + this.fireFrom.y += offsetY; + } + + var fromX = (this.fireFrom.width > 1) ? this.fireFrom.randomX : this.fireFrom.x; + var fromY = (this.fireFrom.height > 1) ? this.fireFrom.randomY : this.fireFrom.y; + + var angle = (this.trackRotation) ? this.trackedSprite.angle : this.fireAngle; + + // The position (in world space) to fire the bullet towards, if set + if (x !== null && y !== null) + { + angle = this.game.math.radToDeg(Math.atan2(y - fromY, x - fromX)); + } + + // Apply +- angle variance + if (this.bulletAngleVariance !== 0) + { + angle += Phaser.Math.between(-this.bulletAngleVariance, this.bulletAngleVariance); + } + + var moveX = 0; + var moveY = 0; + + // Avoid sin/cos for right-angled shots + if (angle === 0 || angle === 180) + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + } + else if (angle === 90 || angle === 270) + { + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + else + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + + var bullet = null; + + if (this.autoExpandBulletsGroup) + { + bullet = this.bullets.getFirstExists(false, true, fromX, fromY, this.bulletKey, this.bulletFrame); + + bullet.data.bulletManager = this; + } + else + { + bullet = this.bullets.getFirstExists(false); + } + + if (bullet) + { + bullet.reset(fromX, fromY); + + bullet.data.fromX = fromX; + bullet.data.fromY = fromY; + bullet.data.killType = this.bulletKillType; + bullet.data.killDistance = this.bulletKillDistance; + bullet.data.rotateToVelocity = this.bulletRotateToVelocity; + + if (this.bulletKillType === Phaser.Weapon.KILL_LIFESPAN) + { + bullet.lifespan = this.bulletLifespan; + } + + bullet.angle = angle + this.bulletAngleOffset; + + // Frames and Animations + if (this.bulletAnimation !== '') + { + if (bullet.animations.getAnimation(this.bulletAnimation) === null) + { + var anim = this.anims[this.bulletAnimation]; + + bullet.animations.add(anim.name, anim.frames, anim.frameRate, anim.loop, anim.useNumericIndex); + } + + bullet.animations.play(this.bulletAnimation); + } + else + { + if (this.bulletFrameCycle) + { + bullet.frame = this.bulletFrames[this.bulletFrameIndex]; + + this.bulletFrameIndex++; + + if (this.bulletFrameIndex >= this.bulletFrames.length) + { + this.bulletFrameIndex = 0; + } + } + else if (this.bulletFrameRandom) + { + bullet.frame = this.bulletFrames[Math.floor(Math.random() * this.bulletFrames.length)]; + } + } + + if (bullet.data.bodyDirty) + { + if (this._data.customBody) + { + bullet.body.setSize(this._data.width, this._data.height, this._data.offsetX, this._data.offsetY); + } + + bullet.body.collideWorldBounds = this.bulletCollideWorldBounds; + + bullet.data.bodyDirty = false; + } + + bullet.body.velocity.set(moveX, moveY); + bullet.body.gravity.set(this.bulletGravity.x, this.bulletGravity.y); + + var next = 0; + + if (this.bulletSpeedVariance !== 0) + { + var rate = this.fireRate; + + rate += Phaser.Math.between(-this.fireRateVariance, this.fireRateVariance); + + if (rate < 0) + { + rate = 0; + } + + next = this.game.time.now + rate; + } + else + { + next = this.game.time.now + this.fireRate; + } + + if (this.multiFire) + { + if (!this._hasFired) + { + // We only add 1 to the 'shots' count for multiFire shots + this._hasFired = true; + this._tempNextFire = next; + this.shots++; + } + } + else + { + this._nextFire = next; + + this.shots++; + } + + this.onFire.dispatch(bullet, this, speed); + + if (this.fireLimit > 0 && this.shots === this.fireLimit) + { + this.onFireLimit.dispatch(this, this.fireLimit); + } + } + + return bullet; + +}; + +/** +* Fires a bullet **at** the given Pointer. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtPointer = function (pointer) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + + return this.fire(null, pointer.worldX, pointer.worldY); + +}; + +/** +* Fires a bullet **at** the given Sprite. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtSprite +* @param {Phaser.Sprite} [sprite] - The Sprite to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtSprite = function (sprite) { + + return this.fire(null, sprite.world.x, sprite.world.y); + +}; + +/** +* Fires a bullet **at** the given coordinates. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtXY +* @param {number} [x] - The x coordinate, in world space, to fire the bullet towards. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtXY = function (x, y) { + + return this.fire(null, x, y); + +}; + +/** +* You can modify the size of the physics Body the Bullets use to be any dimension you need. +* This allows you to make it smaller, or larger, than the parent Sprite. +* You can also control the x and y offset of the Body. This is the position of the +* Body relative to the top-left of the Sprite _texture_. +* +* For example: If you have a Sprite with a texture that is 80x100 in size, +* and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: +* +* `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, 34)` +* +* Where the first two parameters are the new Body size (32x32 pixels) relative to the Sprite's scale. +* 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 +* is the vertical offset. +* +* @method Phaser.Weapon#setBulletBodyOffset +* @param {number} width - The width of the Body. +* @param {number} height - The height of the Body. +* @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture. +* @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture. +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletBodyOffset = function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this._data.customBody = true; + this._data.width = width; + this._data.height = height; + this._data.offsetX = offsetX; + this._data.offsetY = offsetY; + + // Update all bullets in the pool + this.bullets.callAll('body.setSize', 'body', width, height, offsetX, offsetY); + this.bullets.setAll('data.bodyDirty', false); + + return this; + +}; + +/** +* Sets the texture frames that the bullets can use when being launched. +* +* This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet. +* +* It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values +* provided. Then it sets the frame index to be zero. +* +* You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames +* when they're fired, or pick one at random. +* +* @method Phaser.Weapon#setBulletFrames +* @param {integer} min - The minimum value the frame can be. Usually zero. +* @param {integer} max - The maximum value the frame can be. +* @param {boolean} [cycle=true] - Should the bullet frames cycle as they are fired? +* @param {boolean} [random=false] - Should the bullet frames be picked at random as they are fired? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletFrames = function (min, max, cycle, random) { + + if (cycle === undefined) { cycle = true; } + if (random === undefined) { random = false; } + + this.bulletFrames = Phaser.ArrayUtils.numberArray(min, max); + + this.bulletFrameIndex = 0; + + this.bulletFrameCycle = cycle; + this.bulletFrameRandom = random; + + return this; + +}; + +/** +* Adds a new animation under the given key. Optionally set the frames, frame rate and loop. +* The arguments are all the same as for `Animation.add`, and work in the same way. +* +* {@link #bulletAnimation} will be set to this animation after it's created. From that point on, all +* bullets fired will play using this animation. You can swap between animations by calling this method +* several times, and then just changing the {@link #bulletAnimation} property to the name of the animation +* you wish to play for the next launched bullet. +* +* If you wish to stop using animations at all, set {@link #bulletAnimation} to '' (an empty string). +* +* @method Phaser.Weapon#addBulletAnimation +* @param {string} name - The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast". +* @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.addBulletAnimation = function (name, frames, frameRate, loop, useNumericIndex) { + + this.anims[name] = { + name: name, + frames: frames, + frameRate: frameRate, + loop: loop, + useNumericIndex: useNumericIndex + }; + + // Add the animation to any existing bullets in the pool + this.bullets.callAll('animations.add', 'animations', name, frames, frameRate, loop, useNumericIndex); + + this.bulletAnimation = name; + + return this; + +}; + +/** +* Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets +* both in-flight, and available. And optionally the physics debug bodies of the bullets. +* +* @method Phaser.Weapon#debug +* @param {integer} [x=16] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {integer} [y=32] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {boolean} [debugBodies=false] - Optionally draw the physics body of every bullet in-flight. +*/ +Phaser.Weapon.prototype.debug = function (x, y, debugBodies) { + + if (x === undefined) { x = 16; } + if (y === undefined) { y = 32; } + if (debugBodies === undefined) { debugBodies = false; } + + this.game.debug.text("Weapon Plugin", x, y); + this.game.debug.text("Bullets Alive: " + this.bullets.total + " - Total: " + this.bullets.length, x, y + 24); + + if (debugBodies) + { + this.bullets.forEachExists(this.game.debug.body, this.game.debug, 'rgba(255, 0, 255, 0.8)'); + } + +}; + +/** +* The Class of the bullets that are launched by this Weapon. Defaults to {@link Phaser.Bullet}, but can be +* overridden before calling `createBullets` and set to your own class type. +* +* It should be a constructor function accepting `(game, x, y, key, frame)`. +* +* @name Phaser.Weapon#bulletClass +* @property {function} bulletClass +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletClass", { + + get: function () { + + return this._bulletClass; + + }, + + set: function (classType) { + + this._bulletClass = classType; + + // `this.bullets` exists only after createBullets() + if (this.bullets) { + this.bullets.classType = this._bulletClass; + } + } + +}); + +/** +* This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`. +* +* There are 7 different "kill types" available: +* +* * `Phaser.Weapon.KILL_NEVER` +* The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code. +* +* * `Phaser.Weapon.KILL_LIFESPAN` +* The bullets are automatically killed when their `bulletLifespan` amount expires. +* +* * `Phaser.Weapon.KILL_DISTANCE` +* The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position. +* +* * `Phaser.Weapon.KILL_WEAPON_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* +* * `Phaser.Weapon.KILL_CAMERA_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.Camera#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_WORLD_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.World#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_STATIC_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to +* match the position of a tracked sprite or pointer. +* +* @name Phaser.Weapon#bulletKillType +* @property {integer} bulletKillType +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletKillType", { + + get: function () { + + return this._bulletKillType; + + }, + + set: function (type) { + + switch (type) + { + case Phaser.Weapon.KILL_STATIC_BOUNDS: + case Phaser.Weapon.KILL_WEAPON_BOUNDS: + this.bulletBounds = this.bounds; + break; + + case Phaser.Weapon.KILL_CAMERA_BOUNDS: + this.bulletBounds = this.game.camera.view; + break; + + case Phaser.Weapon.KILL_WORLD_BOUNDS: + this.bulletBounds = this.game.world.bounds; + break; + } + + this._bulletKillType = type; + + } + +}); + +/** +* Should bullets collide with the World bounds or not? +* +* @name Phaser.Weapon#bulletCollideWorldBounds +* @property {boolean} bulletCollideWorldBounds +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletCollideWorldBounds", { + + get: function () { + + return this._bulletCollideWorldBounds; + + }, + + set: function (value) { + + this._bulletCollideWorldBounds = value; + + this.bullets.setAll('body.collideWorldBounds', value); + this.bullets.setAll('data.bodyDirty', false); + + } + +}); + +/** +* The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Weapon.prototype, "x", { + + get: function () { + + return this.fireFrom.x; + + }, + + set: function (value) { + + this.fireFrom.x = value; + } + +}); + +/** +* The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Weapon.prototype, "y", { + + get: function () { + + return this.fireFrom.y; + + }, + + set: function (value) { + + this.fireFrom.y = value; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites, +* with a few extra properties in the data object to handle Weapon specific features. +* +* @class Phaser.Bullet +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Bullet = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + this.anchor.set(0.5); + + this.data = { + bulletManager: null, + fromX: 0, + fromY: 0, + bodyDirty: true, + rotateToVelocity: false, + killType: 0, + killDistance: 0 + }; + +}; + +Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Bullet.prototype.constructor = Phaser.Bullet; + +/** +* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool. +* Also dispatches the `Weapon.onKill` signal. +* +* @method Phaser.Bullet#kill +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + this.data.bulletManager.onKill.dispatch(this); + + return this; + +}; + +/** +* Updates the Bullet, killing as required. +* +* @method Phaser.Bullet#update +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.update = function () { + + if (!this.exists) + { + return; + } + + if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN) + { + if (this.data.killType === Phaser.Weapon.KILL_DISTANCE) + { + if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance) + { + this.kill(); + } + } + else + { + if (!this.data.bulletManager.bulletBounds.intersects(this)) + { + this.kill(); + } + } + } + + if (this.data.rotateToVelocity) + { + this.rotation = this.body.velocity.atan(); + } + + if (this.data.bulletManager.bulletWorldWrap) + { + this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding); + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. +* +* Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to +* the Video instead (see `startMediaStream` method) +* +* The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback +* changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. +* +* Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. +* +* If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. +* Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. +* +* On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. +* This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio +* it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` +* method to try and work around this limitation, but see the method help for details. +* +* Small screen devices, especially iPod and iPhone will launch the video in its own native video player, +* outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. +* +* Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) +* then you need to add your own event listener +* +* @class Phaser.Video +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. +* @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) +*/ +Phaser.Video = function (game, key, url) { + + if (key === undefined) { key = null; } + if (url === undefined) { url = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. + * @default null + */ + this.key = key; + + /** + * @property {number} width - The width of the video in pixels. + * @default + */ + this.width = 0; + + /** + * @property {number} height - The height of the video in pixels. + * @default + */ + this.height = 0; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.VIDEO; + + /** + * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. + * @default + */ + this.touchLocked = false; + + /** + * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. + */ + this.onChangeSource = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam. + */ + this.onAccess = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. + */ + this.onError = new Phaser.Signal(); + + /** + * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. + * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. + * @property {Phaser.Signal} onTimeout + */ + this.onTimeout = new Phaser.Signal(); + + /** + * This signal is dispatched when the Video is unlocked. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * Start playing the video when it's unlocked. + * @property {boolean} playWhenUnlocked + * @default + */ + this.playWhenUnlocked = true; + + /** + * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. + * @default + */ + this.timeout = 15000; + + /** + * @property {integer} _timeOutID - setTimeout ID. + * @private + */ + this._timeOutID = null; + + /** + * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document. + */ + this.video = null; + + /** + * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. + */ + this.videoStream = null; + + /** + * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam. + */ + this.isStreaming = false; + + /** + * When starting playback of a video Phaser will monitor its readyState using a setTimeout call. + * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * @property {integer} retryLimit + * @default + */ + this.retryLimit = 20; + + /** + * @property {integer} retry - The current retry attempt. + * @default + */ + this.retry = 0; + + /** + * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video. + * @default + */ + this.retryInterval = 500; + + /** + * @property {integer} _retryID - The callback ID of the retry setTimeout. + * @private + */ + this._retryID = null; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {boolean} _codePaused - Internal paused tracking var. + * @private + * @default + */ + this._codePaused = false; + + /** + * @property {boolean} _paused - Internal paused tracking var. + * @private + * @default + */ + this._paused = false; + + /** + * @property {boolean} _pending - Internal var tracking play pending. + * @private + * @default + */ + this._pending = false; + + /** + * @property {boolean} _pendingChangeSource - Internal var tracking play pending. + * @private + * @default + */ + this._pendingChangeSource = false; + + /** + * @property {boolean} _autoplay - Internal var tracking autoplay when changing source. + * @private + * @default + */ + this._autoplay = false; + + /** + * @property {function} _endCallback - The addEventListener ended function. + * @private + */ + this._endCallback = null; + + /** + * @property {function} _playCallback - The addEventListener playing function. + * @private + */ + this._playCallback = null; + + if (key && this.game.cache.checkVideoKey(key)) + { + var _video = this.game.cache.getVideo(key); + + if (_video.isBlob) + { + this.createVideoFromBlob(_video.data); + } + else + { + this.video = _video.data; + } + + this.width = this.video.videoWidth; + this.height = this.video.videoHeight; + } + else if (url) + { + this.createVideoFromURL(url, false); + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + if (this.video && !url) + { + this.baseTexture = new PIXI.BaseTexture(this.video, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + else + { + this.baseTexture = new PIXI.BaseTexture(Phaser.Cache.DEFAULT.baseTexture.source, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering. + * @default + */ + this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video'); + + this.texture.setFrame(this.textureFrame); + + this.texture.valid = false; + + if (key !== null && this.video) + { + this.texture.valid = this.video.canplay; + } + + /** + * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). + * When called the BitmapData is updated with a grab taken from the current video playing or active video stream. + * If Phaser has been compiled without BitmapData support this property will always be `null`. + * + * @property {Phaser.BitmapData} snapshot + * @readOnly + */ + this.snapshot = null; + + if (Phaser.BitmapData) + { + this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height); + } + + if (this.game.device.needsTouchUnlock()) + { + this.setTouchLock(); + } + else + { + if (_video) + { + _video.locked = false; + } + } + +}; + +Phaser.Video.prototype = { + + /** + * Connects to an external media stream for the webcam, rather than using a local one. + * + * @method Phaser.Video#connectToMediaStream + * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses. + * @param {MediaStream} stream - The Video Stream data. + * @return {Phaser.Video} This Video object for method chaining. + */ + connectToMediaStream: function (video, stream) { + + if (video && stream) + { + this.video = video; + this.videoStream = stream; + + this.isStreaming = true; + this.baseTexture.source = this.video; + this.updateTexture(null, this.video.videoWidth, this.video.videoHeight); + + this.onAccess.dispatch(this); + } + + return this; + + }, + + /** + * Instead of playing a video file this method allows you to stream video data from an attached webcam. + * + * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam. + * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream. + * + * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError + * or MediaStreamError event. + * + * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions. + * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device. + * You can listen for this with the onChangeSource signal. + * + * @method Phaser.Video#startMediaStream + * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream. + * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source. + * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source. + * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia. + */ + startMediaStream: function (captureAudio, width, height) { + + if (captureAudio === undefined) { captureAudio = false; } + if (width === undefined) { width = null; } + if (height === undefined) { height = null; } + + if (!this.game.device.getUserMedia) + { + this.onError.dispatch(this, 'No getUserMedia'); + return false; + } + + if (this.videoStream !== null) + { + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + this.videoStream.stop(); + } + } + + this.removeVideoElement(); + + this.video = document.createElement("video"); + this.video.setAttribute('autoplay', 'autoplay'); + + if (width !== null) + { + this.video.width = width; + } + + if (height !== null) + { + this.video.height = height; + } + + // Request access to the webcam + + this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout); + + try { + navigator.getUserMedia( + { "audio": captureAudio, "video": true }, + this.getUserMediaSuccess.bind(this), + this.getUserMediaError.bind(this) + ); + } + catch (error) + { + this.getUserMediaError(error); + } + + return this; + + }, + + /** + * @method Phaser.Video#getUserMediaTimeout + * @private + */ + getUserMediaTimeout: function () { + + clearTimeout(this._timeOutID); + + this.onTimeout.dispatch(this); + + }, + + /** + * @method Phaser.Video#getUserMediaError + * @private + */ + getUserMediaError: function (event) { + + clearTimeout(this._timeOutID); + + this.onError.dispatch(this, event); + + }, + + /** + * @method Phaser.Video#getUserMediaSuccess + * @private + */ + getUserMediaSuccess: function (stream) { + + clearTimeout(this._timeOutID); + + // Attach the stream to the video + this.videoStream = stream; + + // Set the source of the video element with the stream from the camera + if (this.video.mozSrcObject !== undefined) + { + this.video.mozSrcObject = stream; + } + else + { + this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; + } + + var self = this; + + this.video.onloadeddata = function () { + + var retry = 10; + + function checkStream () { + + if (retry > 0) + { + if (self.video.videoWidth > 0) + { + // Patch for Firefox bug where the height can't be read from the video + var width = self.video.videoWidth; + var height = self.video.videoHeight; + + if (isNaN(self.video.videoHeight)) + { + height = width / (4/3); + } + + self.video.play(); + + self.isStreaming = true; + self.baseTexture.source = self.video; + self.updateTexture(null, width, height); + self.onAccess.dispatch(self); + } + else + { + window.setTimeout(checkStream, 500); + } + } + else + { + console.warn('Unable to connect to video stream. Webcam error?'); + } + + retry--; + } + + checkStream(); + + }; + + }, + + /** + * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format. + * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience. + * + * @method Phaser.Video#createVideoFromBlob + * @param {Blob} blob - The Blob containing the video data. + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromBlob: function (blob) { + + var _this = this; + + this.video = document.createElement("video"); + this.video.controls = false; + this.video.setAttribute('autoplay', 'autoplay'); + this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true); + this.video.src = window.URL.createObjectURL(blob); + this.video.canplay = true; + + return this; + + }, + + /** + * Creates a new Video element from the given URL. + * + * @method Phaser.Video#createVideoFromURL + * @param {string} url - The URL of the video. + * @param {boolean} [autoplay=false] - Automatically start the video? + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromURL: function (url, autoplay) { + + if (autoplay === undefined) { autoplay = false; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + if (this.texture) + { + this.texture.valid = false; + } + + this.video = document.createElement("video"); + this.video.controls = false; + + if (autoplay) + { + this.video.setAttribute('autoplay', 'autoplay'); + } + + this.video.src = url; + + this.video.canplay = true; + + this.video.load(); + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.key = url; + + return this; + + }, + + /** + * Called automatically if the video source changes and updates the internal texture dimensions. + * Then dispatches the onChangeSource signal. + * + * @method Phaser.Video#updateTexture + * @param {object} [event] - The event which triggered the texture update. + * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used. + * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used. + */ + updateTexture: function (event, width, height) { + + var change = false; + + if (width === undefined || width === null) { width = this.video.videoWidth; change = true; } + if (height === undefined || height === null) { height = this.video.videoHeight; } + + this.width = width; + this.height = height; + + if (this.baseTexture.source !== this.video) + { + this.baseTexture.source = this.video; + } + + this.baseTexture.forceLoaded(width, height); + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.valid = true; + + if (this.snapshot) + { + this.snapshot.resize(width, height); + } + + if (change && this.key !== null) + { + this.onChangeSource.dispatch(this, width, height); + + if (this._autoplay) + { + this.video.play(); + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + } + + }, + + /** + * Called when the video completes playback (reaches and ended state). + * Dispatches the Video.onComplete signal. + * + * @method Phaser.Video#complete + */ + complete: function () { + + this.onComplete.dispatch(this); + + }, + + /** + * Starts this video playing. + * + * If the video is already playing, or has been queued to play with `changeSource` then this method just returns. + * + * @method Phaser.Video#play + * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. + * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate. + * @return {Phaser.Video} This Video object for method chaining. + */ + play: function (loop, playbackRate) { + + if (this._pendingChangeSource) + { + return this; + } + + if (loop === undefined) { loop = false; } + if (playbackRate === undefined) { playbackRate = 1; } + + if (this.game.sound.onMute) + { + this.game.sound.onMute.add(this.setMute, this); + this.game.sound.onUnMute.add(this.unsetMute, this); + + if (this.game.sound.mute) + { + this.setMute(); + } + } + + this.game.onPause.add(this.setPause, this); + this.game.onResume.add(this.setResume, this); + + this._endCallback = this.complete.bind(this); + + this.video.addEventListener('ended', this._endCallback, true); + this.video.addEventListener('webkitendfullscreen', this._endCallback, true); + + if (loop) + { + this.video.loop = 'loop'; + } + else + { + this.video.loop = ''; + } + + this.video.playbackRate = playbackRate; + + if (this.touchLocked) + { + this._pending = true; + } + else + { + this._pending = false; + + if (this.key !== null) + { + if (this.video.readyState !== 4) + { + this.retry = this.retryLimit; + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + this._playCallback = this.playHandler.bind(this); + this.video.addEventListener('playing', this._playCallback, true); + } + } + + this.video.play(); + + this.onPlay.dispatch(this, loop, playbackRate); + } + + return this; + + }, + + /** + * Called when the video starts to play. Updates the texture. + * + * @method Phaser.Video#playHandler + * @private + */ + playHandler: function () { + + this.video.removeEventListener('playing', this._playCallback, true); + + this.updateTexture(); + + }, + + /** + * Stops the video playing. + * + * This removes all locally set signals. + * + * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead. + * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to + * call `Video.destroy` instead. + * + * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam. + * + * @method Phaser.Video#stop + * @return {Phaser.Video} This Video object for method chaining. + */ + stop: function () { + + if (this.game.sound.onMute) + { + this.game.sound.onMute.remove(this.setMute, this); + this.game.sound.onUnMute.remove(this.unsetMute, this); + } + + this.game.onPause.remove(this.setPause, this); + this.game.onResume.remove(this.setResume, this); + + // Stream or file? + + if (this.isStreaming) + { + if (this.video.mozSrcObject) + { + this.video.mozSrcObject.stop(); + this.video.src = null; + } + else + { + this.video.src = ''; + + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + if (this.videoStream.getTracks) + { + this.videoStream.getTracks().forEach(function (track) { + track.stop(); + }); + } + else + { + this.videoStream.stop(); + } + } + } + + this.videoStream = null; + this.isStreaming = false; + } + else + { + this.video.removeEventListener('ended', this._endCallback, true); + this.video.removeEventListener('webkitendfullscreen', this._endCallback, true); + this.video.removeEventListener('playing', this._playCallback, true); + + if (this.touchLocked) + { + this._pending = false; + } + else + { + this.video.pause(); + } + } + + return this; + + }, + + /** + * Updates the given Display Objects so they use this Video as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.Video#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.Video} This Video object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. + * + * @method Phaser.Video#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set Video.disableTextureUpload to `true`. + * + * @method Phaser.Video#render + */ + render: function () { + + if (!this.disableTextureUpload && this.playing) + { + this.baseTexture.dirty(); + } + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + this.video.muted = true; + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + this.video.muted = false; + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setPause + * @private + */ + setPause: function () { + + if (this._paused || this.touchLocked) + { + return; + } + + this._paused = true; + + this.video.pause(); + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setResume + * @private + */ + setResume: function () { + + if (!this._paused || this._codePaused || this.touchLocked) + { + return; + } + + this._paused = false; + + if (!this.video.ended) + { + this.video.play(); + } + + }, + + /** + * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it. + * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over" + * split into three different Video objects, then you will need the user to touch-unlock every single one of them. + * + * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains + * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again. + * + * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate. + * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it + * cannot render the new video on iOS (desktop browsers cope better). + * + * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know + * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state + * are adopted automatically by the new video. + * + * @method Phaser.Video#changeSource + * @param {string} src - The new URL to change the video.src to. + * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated? + * @return {Phaser.Video} This Video object for method chaining. + */ + changeSource: function (src, autoplay) { + + if (autoplay === undefined) { autoplay = true; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + this.texture.valid = false; + + this.video.pause(); + + this._pendingChangeSource = true; + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.video.src = src; + + this.video.load(); + + this._autoplay = autoplay; + + if (!autoplay) + { + this.paused = true; + } + + return this; + + }, + + /** + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.Video#checkVideoProgress + * @private + */ + checkVideoProgress: function () { + + // if (this.video.readyState === 2 || this.video.readyState === 4) + if (this.video.readyState === 4) + { + this._pendingChangeSource = false; + + // We've got enough data to update the texture for playback + this.updateTexture(); + } + else + { + this.retry--; + + if (this.retry > 0) + { + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming); + } + } + + }, + + /** + * Sets the Input Manager touch callback to be Video.unlock. + * Required for mobile video unlocking. Mostly just used internally. + * + * @method Phaser.Video#setTouchLock + */ + setTouchLock: function () { + + this.game.input.addTouchLockCallback(this.unlock, this, true); + this.touchLocked = true; + + }, + + /** + * Enables the video on mobile devices, usually after the first touch. + * If the SoundManager hasn't been unlocked then this will automatically unlock that as well. + * Only one video can be pending unlock at any one time. + * + * @method Phaser.Video#unlock + */ + unlock: function () { + + this.touchLocked = false; + + if (this.playWhenUnlocked) + { + this.video.play(); + + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + + if (this.key) + { + var _video = this.game.cache.getVideo(this.key); + + if (_video && !_video.isBlob) + { + _video.locked = false; + } + } + + this.onTouchUnlock.dispatch(this); + + return true; + + }, + + /** + * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData. + * + * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw. + * + * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy. + * + * @method Phaser.Video#grab + * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false. + * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining. + */ + grab: function (clear, alpha, blendMode) { + + if (clear === undefined) { clear = false; } + if (alpha === undefined) { alpha = 1; } + if (blendMode === undefined) { blendMode = null; } + + if (this.snapshot === null) + { + console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable'); + return; + } + + if (clear) + { + this.snapshot.cls(); + } + + this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode); + + return this.snapshot; + + }, + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * Also removes the autoplay and src attributes and nulls the reference. + * + * @method Phaser.Video#removeVideoElement + */ + removeVideoElement: function () { + + if (!this.video) + { + return; + } + + if (this.video.parentNode) + { + this.video.parentNode.removeChild(this.video); + } + + while (this.video.hasChildNodes()) + { + this.video.removeChild(this.video.firstChild); + } + + this.video.removeAttribute('autoplay'); + this.video.removeAttribute('src'); + + this.video = null; + + }, + + /** + * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`. + * If any Sprites are using this Video as their texture it is up to you to manage those. + * + * @method Phaser.Video#destroy + */ + destroy: function () { + + this.stop(); + + this.removeVideoElement(); + + if (this.touchLocked) + { + this.game.input.touch.removeTouchLockCallback(this.unlock, this); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + + } + +}; + +/** +* @name Phaser.Video#currentTime +* @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time. +*/ +Object.defineProperty(Phaser.Video.prototype, "currentTime", { + + get: function () { + + return (this.video) ? this.video.currentTime : 0; + + }, + + set: function (value) { + + this.video.currentTime = value; + + } + +}); + +/** +* @name Phaser.Video#duration +* @property {number} duration - The duration of the video in seconds. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "duration", { + + get: function () { + + return (this.video) ? this.video.duration : 0; + + } + +}); + +/** +* @name Phaser.Video#progress +* @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "progress", { + + get: function () { + + return (this.video) ? (this.video.currentTime / this.video.duration) : 0; + + } + +}); + +/** +* @name Phaser.Video#mute +* @property {boolean} mute - Gets or sets the muted state of the Video. +*/ +Object.defineProperty(Phaser.Video.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || null; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* Gets or sets the paused state of the Video. +* If the video is still touch locked (such as on iOS devices) this call has no effect. +* +* @name Phaser.Video#paused +* @property {boolean} paused +*/ +Object.defineProperty(Phaser.Video.prototype, "paused", { + + get: function () { + + return this._paused; + + }, + + set: function (value) { + + value = value || null; + + if (this.touchLocked) + { + return; + } + + if (value) + { + if (this._paused) + { + return; + } + + this._codePaused = true; + this.setPause(); + } + else + { + if (!this._paused) + { + return; + } + + this._codePaused = false; + this.setResume(); + } + } + +}); + +/** +* @name Phaser.Video#volume +* @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Video.prototype, "volume", { + + get: function () { + + return (this.video) ? this.video.volume : 1; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this.video) + { + this.video.volume = value; + } + + } + +}); + +/** +* @name Phaser.Video#playbackRate +* @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing. +*/ +Object.defineProperty(Phaser.Video.prototype, "playbackRate", { + + get: function () { + + return (this.video) ? this.video.playbackRate : 1; + + }, + + set: function (value) { + + if (this.video) + { + this.video.playbackRate = value; + } + + } + +}); + +/** +* Gets or sets if the Video is set to loop. +* Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. +* If the video isn't yet set this will always return false. +* +* @name Phaser.Video#loop +* @property {boolean} loop +*/ +Object.defineProperty(Phaser.Video.prototype, "loop", { + + get: function () { + + return (this.video) ? this.video.loop : false; + + }, + + set: function (value) { + + if (value && this.video) + { + this.video.loop = 'loop'; + } + else if (this.video) + { + this.video.loop = ''; + } + + } + +}); + +/** +* @name Phaser.Video#playing +* @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "playing", { + + get: function () { + + return (this.video) ? !(this.video.paused && this.video.ended) : false; + + } + +}); + +Phaser.Video.prototype.constructor = Phaser.Video; + +/* global Phaser:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Pixi expects these globals to exist + +if (PIXI.blendModes === undefined) +{ + PIXI.blendModes = Phaser.blendModes; +} + +if (PIXI.scaleModes === undefined) +{ + PIXI.scaleModes = Phaser.scaleModes; +} + +if (PIXI.Texture.emptyTexture === undefined) +{ + PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture()); +} + +if (PIXI.DisplayObject._tempMatrix === undefined) +{ + PIXI.DisplayObject._tempMatrix = new Phaser.Matrix(); +} + +PIXI.TextureSilentFail = true; + +// Required by Particle Storm +PIXI.canUseNewCanvasBlendModes = function () { + return Phaser.Device.canUseMultiply; +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = Phaser; + } + exports.Phaser = Phaser; + } else if (typeof define !== 'undefined' && define.amd) { + define('Phaser', (function() { return root.Phaser = Phaser; })() ); + } else { + root.Phaser = Phaser; + } + + return Phaser; +}).call(this); + +/* +* "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer +*/ diff --git a/Digital Assignment 1/js/phaser.map b/Digital Assignment 1/js/phaser.map new file mode 100644 index 000000000..70723bbf8 --- /dev/null +++ b/Digital Assignment 1/js/phaser.map @@ -0,0 +1 @@ +{"version":3,"sources":["phaser.js"],"names":["e","exports","module","f","window","global","self","p2","t","n","r","s","o","u","a","require","i","Error","call","length","1","_dereq_","Line","Scalar","lineInt","l1","l2","precision","a1","b1","c1","a2","b2","c2","det","eq","segmentsIntersect","p1","q1","q2","dx","dy","da","db","./Scalar","2","Point","area","b","c","left","leftOn","right","rightOn","tmpPoint1","tmpPoint2","collinear","thresholdAngle","ab","bc","dot","magA","Math","sqrt","magB","acos","sqdist","3","Polygon","this","vertices","getIntersectionPoint","delta","prototype","at","v","first","last","clear","append","poly","from","to","push","makeCCW","br","reverse","tmp","N","pop","isReflex","tmpLine1","tmpLine2","canSee","p","dist","copy","j","targetPoly","k","getCutEdges","min","tmp1","tmp2","tmpPoly","nDiags","Number","MAX_VALUE","decomp","edges","slice","cutEdges","Array","polys","cutEdge","result","splice","indexOf","isSimple","path","quickDecomp","reflexVertices","steinerPoints","maxlevel","level","upperInt","lowerInt","upperDist","lowerDist","d","closestDist","upperIndex","lowerIndex","closestIndex","lowerPoly","upperPoly","console","warn","removeCollinearPoints","num","./Line","./Point","4","abs","5","./Polygon","6","name","version","description","author","keywords","main","engines","node","repository","type","url","bugs","licenses","devDependencies","grunt","grunt-contrib-jshint","grunt-contrib-nodeunit","grunt-contrib-uglify","grunt-contrib-watch","grunt-browserify","grunt-contrib-concat","dependencies","poly-decomp","7","AABB","options","lowerBound","vec2","create","upperBound","setFromPoints","points","position","angle","skinSize","l","rotate","cosAngle","cos","sinAngle","sin","x","y","add","aabb","extend","overlaps","u1","u2","containsPoint","point","overlapsRay","ray","dirFracX","direction","dirFracY","t1","t2","t3","t4","tmin","max","tmax","../math/vec2","../utils/Utils","8","Broadphase","world","boundingVolumeType","Body","BOUNDING_CIRCLE","setWorld","getCollisionPairs","boundingRadiusCheck","bodyA","bodyB","sub","d2","squaredLength","boundingRadius","aabbCheck","getAABB","boundingVolumeCheck","canCollide","KINEMATIC","STATIC","sleepState","SLEEPING","NAIVE","SAP","../objects/Body","9","NaiveBroadphase","constructor","bodies","Ncolliding","bi","bj","aabbQuery","aabbNeedsUpdate","updateAABB","../collision/Broadphase","../shapes/Circle","../shapes/Particle","../shapes/Plane","../shapes/Shape","10","Narrowphase","contactEquations","frictionEquations","enableFriction","enabledEquations","slipForce","frictionCoefficient","surfaceVelocity","contactEquationPool","ContactEquationPool","size","frictionEquationPool","FrictionEquationPool","restitution","stiffness","Equation","DEFAULT_STIFFNESS","relaxation","DEFAULT_RELAXATION","frictionStiffness","frictionRelaxation","enableFrictionReduction","collidingBodiesLastStep","TupleDictionary","contactSkinSize","setConvexToCapsuleShapeMiddle","convexShape","capsuleShape","set","radius","pointInConvex","worldPoint","convexOffset","convexAngle","worldVertex0","pic_worldVertex0","worldVertex1","pic_worldVertex1","r0","pic_r0","r1","pic_r1","verts","lastCross","v0","v1","cross","crossLength","Circle","Convex","Shape","Box","yAxis","fromValues","tmp3","tmp4","tmp5","tmp6","tmp7","tmp8","tmp9","tmp10","tmp11","tmp12","tmp13","tmp14","tmp15","tmp16","tmp17","tmp18","tmpArray","bodiesOverlap_shapePositionA","bodiesOverlap_shapePositionB","bodiesOverlap","shapePositionA","shapePositionB","Nshapesi","shapes","shapeA","toWorldFrame","Nshapesj","shapeB","collidedLastStep","id1","id","id2","get","reset","eqs","ce","fe","release","createContactEquation","firstImpact","needsUpdate","enabled","offset","createFrictionEquation","setSlipForce","relativeVelocity","createFrictionFromContact","contactPointA","contactPointB","rotate90cw","normalA","createFrictionFromAverage","numContacts","invNumContacts","scale","normalize","LINE","CONVEX","convexLine","convexBody","lineBody","lineShape","lineOffset","lineAngle","justTest","BOX","lineBox","boxBody","boxShape","boxOffset","boxAngle","convexCapsule_tempRect","width","height","convexCapsule_tempVec","CAPSULE","convexCapsule","convexPosition","capsuleBody","capsulePosition","capsuleAngle","circlePos","result1","circleConvex","result2","convexConvex","lineCapsule","linePosition","capsuleCapsule_tempVec1","capsuleCapsule_tempVec2","capsuleCapsule_tempRect1","capsuleCapsule","si","xi","ai","sj","xj","aj","circlePosi","circlePosj","enableFrictionBefore","circleCircle","rect","lineLine","positionA","angleA","positionB","angleB","PLANE","planeLine","planeBody","planeShape","planeOffset","planeAngle","worldVertex01","worldVertex11","worldEdge","worldEdgeUnit","worldNormal","worldTangent","PARTICLE","particleCapsule","particleBody","particleShape","particlePosition","particleAngle","circleLine","CIRCLE","circleBody","circleShape","circleOffset","circleAngle","lineRadius","circleRadius","orthoDist","lineToCircleOrthoUnit","projectedPoint","centerDist","lineToCircle","lineEndToLineRadius","radiusSum","pos","pos0","pos1","pow","circleCapsule","worldVertex","closestEdgeProjectedPoint","candidate","candidateDist","minCandidate","found","minCandidateDistance","candidateDistance","localVertex","particleConvex","particleOffset","convexToparticle","minEdgeNormal","offsetA","offsetB","radiusA","radiusB","planeConvex","numReported","particlePlane","circleParticle","planeCapsule_tmpCircle","planeCapsule_tmp1","planeCapsule_tmp2","planeCapsule","capsuleOffset","end1","end2","circle","numContacts1","circlePlane","numContacts2","numTotal","planeToCircle","temp","contact","sepAxis","worldPoint0","worldPoint1","penetrationVec","findSeparatingAxis","closestEdge1","getClosestEdge","closestEdge2","closestEdgeA","closestEdgeB","insideNumEdges","pcoa_tmp1","projectConvexOntoAxis","worldAxis","value","localAxis","fsa_tmp1","fsa_tmp2","fsa_tmp3","fsa_tmp4","fsa_tmp5","fsa_tmp6","offset1","angle1","offset2","angle2","maxDist","overlap","edge","normal","span1","span2","gce_tmp1","gce_tmp2","gce_tmp3","axis","flip","closestEdge","maxDot","circleHeightfield_candidate","circleHeightfield_dist","circleHeightfield_v0","circleHeightfield_v1","circleHeightfield_minCandidate","circleHeightfield_worldNormal","circleHeightfield_minCandidateNormal","HEIGHTFIELD","circleHeightfield","hfBody","hfShape","hfPos","hfAngle","data","heights","w","elementWidth","minCandidateNormal","idxA","floor","idxB","ceil","PI","convexHeightfield_v0","convexHeightfield_v1","convexHeightfield_tilePos","convexHeightfield_tempConvexShape","convexHeightfield","convexPos","tilePos","tileConvex","../equations/ContactEquation","../equations/Equation","../equations/FrictionEquation","../shapes/Box","../shapes/Convex","../utils/ContactEquationPool","../utils/FrictionEquationPool","../utils/TupleDictionary","11","Ray","checkCollisionResponse","undefined","skipBackfaces","collisionMask","collisionGroup","mode","ANY","callback","update","distanceFromIntersectionSquared","intersect","squaredDistance","CLOSEST","ALL","intersectBodies","shouldStop","body","intersectBody","intersectBody_worldPosition","collisionResponse","worldPosition","shape","worldAngle","intersectShape","_currentBody","_currentShape","raycast","reportIntersection","fraction","faceIndex","hasHit","../collision/AABB","../collision/RaycastResult","12","RaycastResult","isStopped","getHitDistance","distance","getHitPoint","out","lerp","stop","../collision/Ray","13","SAPBroadphase","axisList","axisIndex","that","_addBodyHandler","_removeBodyHandler","idx","Utils","appendArray","off","on","sortAxisList","sortList","14","Constraint","defaults","collideConnected","wakeUpBodies","equations","wakeUp","DISTANCE","GEAR","LOCK","PRISMATIC","REVOLUTE","setStiffness","setRelaxation","15","DistanceConstraint","localAnchorA","localAnchorB","worldAnchorA","worldAnchorB","maxForce","ri","rj","computeGq","setMaxForce","upperLimitEnabled","upperLimit","lowerLimitEnabled","lowerLimit","normalEquation","G","violating","minForce","rixn","rjxn","getMaxForce","./Constraint","16","GearConstraint","ratio","AngleLockEquation","maxTorque","setMaxTorque","setRatio","torque","getMaxTorque","../equations/AngleLockEquation","17","LockConstraint","localAngleB","rot","g","localOffsetB","force","xAxis","18","PrismaticConstraint","localAxisA","trans","gg","updateJacobian","disableRotationalLock","RotationalLockEquation","velocity","upperLimitEquation","ContactEquation","lowerLimitEquation","motorEquation","motorEnabled","motorSpeed","computeGW","vi","vj","wi","angularVelocity","wj","gmult","worldAxisA","orientedAnchorA","orientedAnchorB","relPosition","enableMotor","disableMotor","setLimits","lower","upper","../equations/RotationalLockEquation","19","RevoluteConstraint","pivotA","pivotB","worldPivot","localPivotA","localPivotB","worldPivotA","worldPivotB","RotationalVelocityEquation","relAngle","setMotorSpeed","speed","getMotorSpeed","../equations/RotationalVelocityEquation","20","./Equation","21","computeB","h","GW","Gq","computeGiMf","relVel","getVelocityAlongNormal","getVelocityAtPoint","subtract","22","ARRAY_TYPE","epsilon","timeStep","multiplier","qi","qj","computeGWlambda","vlambda","wlambda","iMfi","iMfj","fi","ti","angularForce","fj","tj","invMassi","invMassSolve","invMassj","invIi","invInertiaSolve","invIj","multiply","massMultiplier","computeGiMGt","addToWlambda_temp","addToWlambda_Gi","addToWlambda_Gj","addToWlambda","deltalambda","Gi","Gj","computeInvC","eps","23","FrictionEquation","getSlipForce","24","worldVectorA","worldVectorB","25","GiMf","26","EventEmitter","listener","context","_listeners","listeners","has","index","emit","event","listenerArray","target","27","ContactMaterial","materialA","materialB","Material","idCounter","friction","./Material","28","29","PolyK","GetArea","sum","Triangulate","tgs","avl","al","i0","i1","i2","ax","ay","bx","by","cx","cy","earFound","_convex","_PointInTriangle","px","py","v0x","v0y","v1x","v1y","v2x","v2y","dot00","dot01","dot02","dot11","dot12","invDenom","30","crossVZ","vec","zcomp","crossZV","toLocalFrame","framePosition","frameAngle","toGlobalFrame","localPoint","vectorToLocalFrame","worldVector","vectorToGlobalFrame","localVector","centroid","clone","mul","divide","div","sqrDist","len","sqrLen","negate","str","reflect","vector","getLineSegmentsIntersection","p0","p3","getLineSegmentsIntersectionFraction","s1_x","s1_y","s2_x","s2_y","31","_idCounter","mass","invMass","inertia","invInertia","fixedRotation","fixedX","fixedY","interpolatedPosition","interpolatedAngle","previousPosition","previousAngle","damping","angularDamping","DYNAMIC","allowSleep","wantsToSleep","AWAKE","sleepSpeedLimit","sleepTimeLimit","gravityScale","idleTime","timeLastSleepy","ccdSpeedThreshold","ccdIterations","concavePath","_wakeUpAfterNarrowphase","updateMassProperties","updateSolveMassProperties","setDensity","density","totalArea","getArea","shapeAABB","bodyAngle","computeAABB","updateBoundingRadius","addShape","removeShape","m","I","r2","computeMomentOfInertia","applyForce","relativePoint","rotForce","Body_applyForce_forceWorld","Body_applyForce_pointWorld","Body_applyForce_pointLocal","applyForceLocal","localForce","worldForce","vectorToWorldFrame","Body_applyImpulse_velo","applyImpulse","impulseVector","velo","rotVelo","Body_applyImpulse_impulseWorld","Body_applyImpulse_pointWorld","Body_applyImpulse_pointLocal","applyImpulseLocal","localImpulse","worldImpulse","fromPolygon","convexes","optimalDecomp","cm","centerOfMass","updateTriangles","updateCenterOfMass","adjustCenterOfMass","adjustCenterOfMass_tmp2","adjustCenterOfMass_tmp3","adjustCenterOfMass_tmp4","offset_times_area","setZeroForce","resetConstraintVelocity","addConstraintVelocity","applyDamping","dt","wakeUpEvent","sleep","sleepEvent","sleepTick","time","dontSleep","SLEEPY","overlapKeeper","bodiesAreOverlapping","integrate_fhMinv","integrate_velodt","integrate","minv","integrateToTimeOfImpact","end","startToEnd","rememberPosition","hit","startToEndAngle","timeOfImpact","rememberAngle","iter","tmid","narrowphase","sleepyEvent","../events/EventEmitter","32","LinearSpring","Spring","setWorldAnchorA","setWorldAnchorB","getWorldAnchorA","getWorldAnchorB","worldDistance","restLength","applyForce_r","applyForce_r_unit","applyForce_u","applyForce_f","applyForce_worldAnchorA","applyForce_worldAnchorB","applyForce_ri","applyForce_rj","applyForce_tmp","r_unit","rlen","ri_x_f","rj_x_f","./Spring","33","RotationalSpring","restAngle","34","35","TopDownVehicle","chassisBody","wheels","groundBody","preStepCallback","WheelConstraint","vehicle","forwardEquation","sideEquation","steerValue","engineForce","setSideFriction","sideFriction","localForwardVector","localPosition","apply","setBrakeForce","addToWorld","addBody","wheel","addConstraint","removeFromWorld","removeBody","removeConstraint","addWheel","wheelOptions","worldVelocity","getSpeed","tmpVec","../constraints/Constraint","36","Capsule","GSSolver","Heightfield","Particle","Plane","Pool","Solver","World","Object","defineProperty","../package.json","./collision/AABB","./collision/Broadphase","./collision/NaiveBroadphase","./collision/Narrowphase","./collision/Ray","./collision/RaycastResult","./collision/SAPBroadphase","./constraints/Constraint","./constraints/DistanceConstraint","./constraints/GearConstraint","./constraints/LockConstraint","./constraints/PrismaticConstraint","./constraints/RevoluteConstraint","./equations/AngleLockEquation","./equations/ContactEquation","./equations/Equation","./equations/FrictionEquation","./equations/RotationalVelocityEquation","./events/EventEmitter","./material/ContactMaterial","./material/Material","./math/vec2","./objects/Body","./objects/LinearSpring","./objects/RotationalSpring","./objects/Spring","./objects/TopDownVehicle","./shapes/Box","./shapes/Capsule","./shapes/Circle","./shapes/Convex","./shapes/Heightfield","./shapes/Line","./shapes/Particle","./shapes/Plane","./shapes/Shape","./solver/GSSolver","./solver/Solver","./utils/ContactEquationPool","./utils/FrictionEquationPool","./utils/Pool","./utils/Utils","./world/World","37","arguments","axes","updateArea","./Convex","./Shape","38","intersectCapsule_hitPointWorld","intersectCapsule_normal","intersectCapsule_l0","intersectCapsule_l1","intersectCapsule_unit_y","hitPointWorld","l0","halfLen","diagonalLengthSquared","sqrtDelta","inv2a","d1","39","Ray_intersectSphere_intersectionPoint","Ray_intersectSphere_normal","intersectionPoint","40","isArray","triangles","polyk","tmpVec1","tmpVec2","projectOntoLocalAxis","projectOntoWorldAxis","shapeOffset","shapeAngle","polykVerts","id3","updateCenterOfMass_centroid","updateCenterOfMass_centroid_times_mass","updateCenterOfMass_a","updateCenterOfMass_b","updateCenterOfMass_c","centroid_times_mass","triangleArea","denom","numer","intersectConvex_rayStart","intersectConvex_rayEnd","intersectConvex_normal","rayStart","rayEnd","../math/polyk","41","key","maxValue","minValue","updateMaxMinValues","getLineSegment","start","getSegmentIndex","getClampedSegmentIndex","intersectHeightfield_worldNormal","intersectHeightfield_l0","intersectHeightfield_l1","intersectHeightfield_localFrom","intersectHeightfield_localTo","localFrom","localTo","42","raycast_normal","raycast_l0","raycast_l1","raycast_unit_y","43","44","intersectPlane_planePointToFrom","intersectPlane_normal","intersectPlane_len","planePointToFrom","planeToFrom","n_dot_dir","45","material","sensor","46","GS","iterations","tolerance","arrayStep","lambda","Bs","invCs","useZeroRHS","frictionIterations","usedIterations","setArrayZero","array","solve","sortEquations","maxIter","maxFrictionIter","Neq","tolSquared","Nbodies","deltalambdaTot","iterateEquation","updateMultipliers","invDt","B","invC","lambdaj","GWlambda","lambdaj_plus_deltalambda","./Solver","47","equationSortFunction","mockWorld","solveIsland","island","removeAllEquations","addEquations","getBodies","sort","addEquation","removeEquation","ISLAND","48","destroy","equation","./Pool","49","50","IslandNodePool","IslandNode","../world/IslandNode","51","IslandPool","Island","../world/Island","52","OverlapKeeper","overlappingShapesLastState","overlappingShapesCurrentState","recordPool","OverlapKeeperRecordPool","tmpDict","tmpArray1","tick","current","keys","lastObject","getByKey","setOverlapping","getNewOverlaps","getDiff","getEndOverlaps","dictA","dictB","isNewOverlap","idA","idB","getNewBodyOverlaps","getBodyDiff","getEndBodyOverlaps","accumulator","./OverlapKeeperRecord","./OverlapKeeperRecordPool","./TupleDictionary","./Utils","53","OverlapKeeperRecord","54","record","55","objects","resize","object","56","getKey","dict","57","howmany","P2_ARRAY_TYPE","Float32Array","58","bodyIds","59","IslandManager","nodePool","islandPool","islands","nodes","queue","getUnvisitedNode","Nnodes","visited","visit","bds","Neqs","bfs","root","child","neighbors","split","ni","nj","./../utils/IslandNodePool","./../utils/IslandPool","./Island","./IslandNode","60","61","springs","disabledBodyCollisionPairs","solver","islandManager","gravity","frictionGravity","useWorldGravityAsFrictionGravity","useFrictionGravityOnZeroGravity","broadphase","constraints","defaultMaterial","defaultContactMaterial","lastTimeStep","applySpringForces","applyGravity","solveConstraints","contactMaterials","stepping","bodiesToBeRemoved","islandSplit","emitImpactEvent","_constraintIdCounter","_bodyIdCounter","postStepEvent","addBodyEvent","removeBodyEvent","addSpringEvent","spring","impactEvent","contactEquation","postBroadphaseEvent","pairs","sleepMode","NO_SLEEPING","beginContactEvent","endContactEvent","preSolveEvent","BODY_SLEEPING","ISLAND_SLEEPING","constraint","addContactMaterial","contactMaterial","removeContactMaterial","getContactMaterial","cmats","step_mg","xiw","xjw","step","timeSinceLastCalled","maxSubSteps","internalStep","substeps","endOverlaps","Nsprings","np","mg","gravityLen","ignoredPairs","Nconstraints","Nresults","runNarrowphase","ev","glen","aiw","ajw","reducedMass","resolver","numFrictionBefore","numFrictionEquations","addSpring","evt","removeSpring","getBodyById","disableBodyCollision","enableBodyCollision","cs","cms","hitTest_tmp1","hitTest_tmp2","hitTest","pb","ps","NS","setGlobalStiffness","setGlobalRelaxation","tmpAABB","../../package.json","../collision/Narrowphase","../collision/SAPBroadphase","../constraints/DistanceConstraint","../constraints/GearConstraint","../constraints/LockConstraint","../constraints/PrismaticConstraint","../constraints/RevoluteConstraint","../material/ContactMaterial","../material/Material","../objects/LinearSpring","../objects/RotationalSpring","../shapes/Capsule","../shapes/Line","../solver/GSSolver","../solver/Solver","../utils/OverlapKeeper","./IslandManager","_CreateEmptyTexture","gl","scaleMode","texture","createTexture","bindTexture","TEXTURE_2D","texParameteri","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","TEXTURE_MAG_FILTER","PIXI","scaleModes","LINEAR","NEAREST","TEXTURE_MIN_FILTER","texImage2D","RGBA","UNSIGNED_BYTE","_CreateFramebuffer","textureUnit","framebuffer","createFramebuffer","depthStencilBuffer","createRenderbuffer","colorBuffer","fbStatus","activeTexture","TEXTURE0","bindFramebuffer","FRAMEBUFFER","bindRenderbuffer","RENDERBUFFER","framebufferRenderbuffer","DEPTH_STENCIL_ATTACHMENT","renderBuffer","framebufferTexture2D","COLOR_ATTACHMENT0","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","error","_fbErrors","targetTexture","DisplayObject","pivot","rotation","alpha","visible","hitArea","renderable","parent","worldAlpha","worldTransform","Phaser","Matrix","worldScale","worldRotation","filterArea","_sr","_cr","_bounds","Rectangle","_currentBounds","_mask","_cacheAsBitmap","_cacheIsDirty","children","_destroyCachedSprite","updateTransform","game","tx","ty","pt","wt","PI2","rotationCache","determ","HALF_PI","transformCallback","transformCallbackContext","preUpdate","generateTexture","resolution","renderer","bounds","getLocalBounds","renderTexture","RenderTexture","_tempMatrix","render","updateCache","_generateCachedSprite","toGlobal","toLocal","applyInverse","_renderCachedSprite","renderSession","_cachedSprite","Sprite","_renderWebGL","_renderCanvas","baseTexture","_enableMultiTextureToggle","textureIndex","tempFilters","_filters","filters","anchor","displayObjectUpdateTransform","defineProperties","worldVisible","item","mask","isMask","passes","filterPasses","_filterBlock","blendMode","blendModes","MULTIPLY","NORMAL","cacheAsBitmap","DisplayObjectContainer","ignoreChildInput","addChild","addChildAt","removeChild","swapChildren","child2","index1","getChildIndex","index2","setChildIndex","currentIndex","getChildAt","removeChildAt","removeChildren","beginIndex","endIndex","range","removed","displayObjectContainerUpdateTransform","getBounds","targetCoordinateSpace","isTargetCoordinateSpaceDisplayObject","isTargetCoordinateSpaceThisOrParent","contains","matrixCache","identityMatrix","childBounds","childMaxX","childMaxY","minX","Infinity","minY","maxX","maxY","childVisible","w0","w1","h0","h1","x1","y1","x2","y2","x3","y3","x4","y4","targetCoordinateSpaceBounds","spriteBatch","flush","filterManager","pushFilter","maskManager","pushMask","popMask","popFilter","_width","_height","defaultAnchor","Texture","emptyTexture","tint","cachedTint","tintedTexture","shader","exists","hasLoaded","onTextureUpdate","frame","setTexture","destroyBase","skipRender","valid","matrix","crop","currentBlendMode","globalCompositeOperation","blendModesCanvas","globalAlpha","smoothProperty","trim","shakeX","shakeY","cw","ch","rotated","roundPixels","setTransform","requiresReTint","CanvasTinter","getTintedTexture","drawImage","source","initDefaultShaders","CompileVertexShader","shaderSrc","_CompileShader","VERTEX_SHADER","CompileFragmentShader","FRAGMENT_SHADER","shaderType","src","join","createShader","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","log","getShaderInfoLog","compileProgram","vertexSrc","fragmentSrc","fragmentShader","vertexShader","shaderProgram","createProgram","attachShader","linkProgram","getProgramParameter","LINK_STATUS","getProgramInfoLog","PixiShader","_UID","program","textureCount","firstRun","dirty","attributes","init","initMultitexShader","MAX_TEXTURES","getParameter","MAX_TEXTURE_IMAGE_UNITS","dynamicIfs","defaultVertexSrc","useProgram","uSamplerArray","getUniformLocation","projectionVector","offsetVector","dimensions","aVertexPosition","getAttribLocation","aTextureCoord","colorAttribute","aTextureIndex","indices","tempTexture","RGB","uniform1iv","uniforms","uniformLocation","initUniforms","initDefaultShader","uSampler","usingFilter","uniform","_init","initSampler2D","glMatrix","glValueLength","glFunc","uniformMatrix2fv","uniformMatrix3fv","uniformMatrix4fv","_glTextures","textureData","magFilter","minFilter","wrapS","wrapT","format","LUMINANCE","repeat","REPEAT","pixelStorei","UNPACK_FLIP_Y_WEBGL","flipY","border","uniform1i","syncUniforms","transpose","z","_dirty","instances","updateTexture","deleteProgram","PixiFastShader","uMatrix","aPositionCoord","aScale","aRotation","StripShader","translationMatrix","attribute","PrimitiveShader","tintColor","ComplexPrimitiveShader","color","glContexts","WebGLRenderer","config","defaultRenderer","extensions","WEBGL","transparent","autoResize","preserveDrawingBuffer","clearBeforeRender","view","canvas","_contextOptions","antialias","failIfMajorPerformanceCaveat","premultipliedAlpha","stencil","projection","shaderManager","WebGLShaderManager","WebGLSpriteBatch","WebGLMaskManager","WebGLFilterManager","stencilManager","WebGLStencilManager","blendModeManager","WebGLBlendModeManager","currentBatchedTextures","drawCount","maxTextureAvailableSpace","initContext","mapBlendModes","getContext","maxTextures","maxTextureSize","MAX_TEXTURE_SIZE","glContextId","disable","DEPTH_TEST","CULL_FACE","enable","BLEND","setContext","compression","etc1","getExtension","pvrtc","s3tc","ETC1","PVRTC","S3TC","setTexturePriority","textureNameCollection","clampPot","potSize","imageCache","cache","_cache","image","imageName","base","stage","contextLost","viewport","clearColor","_bgColor","COLOR_BUFFER_BIT","camera","_shake","renderDisplayObject","displayObject","buffer","setBlendMode","begin","style","updateCompressedTexture","textureMetaData","compressedTexImage2D","glExtensionFormat","mipmap","isPowerOfTwo","LINEAR_MIPMAP_LINEAR","NEAREST_MIPMAP_NEAREST","generateMipmap","_powerOf2","compressionAlgorithm","UNPACK_PREMULTIPLY_ALPHA_WEBGL","CanvasPool","remove","blendModesWebGL","modes","ONE","ONE_MINUS_SRC_ALPHA","ADD","SRC_ALPHA","DST_ALPHA","DST_COLOR","SCREEN","OVERLAY","DARKEN","LIGHTEN","COLOR_DODGE","COLOR_BURN","HARD_LIGHT","SOFT_LIGHT","DIFFERENCE","EXCLUSION","HUE","SATURATION","COLOR","LUMINOSITY","getMaxTextureUnit","enableMultiTexture","textureArray","blendModeWebGL","blendFunc","maskData","WebGLGraphics","updateGraphics","_webGL","pushStencil","popStencil","stencilStack","count","graphics","webGLData","bindGraphics","STENCIL_TEST","STENCIL_BUFFER_BIT","colorMask","stencilFunc","ALWAYS","stencilOp","KEEP","INVERT","drawElements","TRIANGLE_FAN","UNSIGNED_SHORT","EQUAL","DECR","INCR","TRIANGLE_STRIP","_currentGraphics","complexPrimitiveShader","setShader","uniform1f","toArray","uniform2f","uniform3fv","Color","hexToRGBArray","bindBuffer","ARRAY_BUFFER","vertexAttribPointer","FLOAT","ELEMENT_ARRAY_BUFFER","indexBuffer","primitiveShader","maxAttibs","attribState","tempAttribState","stack","defaultShader","fastShader","stripShader","creatureShader","CreatureShader","setAttribs","attribs","attribId","enableVertexAttribArray","disableVertexAttribArray","_currentId","currentShader","vertSize","vertexSize","numVerts","numIndices","ArrayBuffer","positions","colors","Uint32Array","Uint16Array","lastIndexCount","drawing","currentBatchSize","currentBaseTexture","textures","shaders","sprites","Filter","vertexBuffer","createBuffer","bufferData","STATIC_DRAW","DYNAMIC_DRAW","sprite","uvs","_uvs","aX","aY","a0","b0","c0","d0","_w1","_w0","_updateUvsInverted","x0","y0","renderTilingSprite","tilingTexture","TextureUvs","tilePosition","tileScaleOffset","offsetX","offsetY","scaleX","tileScale","scaleY","stride","bufferSubData","subarray","nextTexture","nextBlendMode","nextShader","batchSize","blendSwap","shaderSwap","skip","renderBatch","startIndex","TRIANGLES","deleteBuffer","WebGLFastSpriteBatch","maxSize","renderSprite","filterStack","texturePool","initShaderBuffers","filterBlock","_filterArea","_previous_stencil_mgr","filter","FilterTexture","padding","frameBuffer","_glFilterTexture","vertexArray","uvBuffer","uvArray","inputTexture","outputTexture","filterPass","applyFilterPass","sizeX","sizeY","currentFilter","colorArray","36054","36055","36057","36061","DEFAULT","renderbufferStorage","DEPTH_STENCIL","deleteFramebuffer","deleteTexture","CanvasBuffer","clearRect","CanvasMaskManager","save","cacheAlpha","transform","CanvasGraphics","renderGraphicsMask","clip","restore","tintMethod","tintWithMultiply","fillStyle","toString","substr","fillRect","tintWithPerPixel","rgbValues","pixelData","getImageData","pixels","canHandleAlpha","putImageData","CanvasRenderer","CANVAS","refresh","Canvas","getSmoothingPrefix","navigator","isCocoonJS","screencanvas","rgba","removeView","useNew","device","canUseMultiply","BaseTexture","complete","naturalWidth","naturalHeight","forceLoaded","removeByCanvas","unloadFromGPU","glTexture","fromCanvas","TextureSilentFail","noFrame","isTiling","requiresUpdate","setFrame","onBaseTextureLoaded","_updateUvs","tw","th","define","amd","WheelEventProxy","scaleFactor","deltaMode","_scaleFactor","_deltaMode","originalEvent","VERSION","GAMES","AUTO","HEADLESS","WEBGL_MULTI","NONE","LEFT","RIGHT","UP","DOWN","SPRITE","BUTTON","IMAGE","GRAPHICS","TEXT","TILESPRITE","BITMAPTEXT","GROUP","RENDERTEXTURE","TILEMAP","TILEMAPLAYER","EMITTER","POLYGON","BITMAPDATA","CANVAS_FILTER","WEBGL_FILTER","ELLIPSE","SPRITEBATCH","RETROFONT","POINTER","ROPE","RECTANGLE","MATRIX","POINT","ROUNDEDRECTANGLE","CREATURE","VIDEO","PENDING_ATLAS","HORIZONTAL","VERTICAL","LANDSCAPE","PORTRAIT","ANGLE_UP","ANGLE_DOWN","ANGLE_LEFT","ANGLE_RIGHT","ANGLE_NORTH_EAST","ANGLE_NORTH_WEST","ANGLE_SOUTH_EAST","ANGLE_SOUTH_WEST","TOP_LEFT","TOP_CENTER","TOP_RIGHT","LEFT_TOP","LEFT_CENTER","LEFT_BOTTOM","CENTER","RIGHT_TOP","RIGHT_CENTER","RIGHT_BOTTOM","BOTTOM_LEFT","BOTTOM_CENTER","BOTTOM_RIGHT","trunc","Function","bind","thisArg","bound","args","boundArgs","concat","TypeError","F","proto","arg","forEach","fun","CheapArray","assert","assign","varArgs","hasOwn","hasOwnProperty","nextSource","nextKey","reverseString","string","getProperty","obj","parts","_getProperty","setProperties","props","setProperty","_setProperty","val","currentObj","chanceRoll","chance","random","randomChoice","choice1","choice2","parseDimension","dimension","parseInt","innerWidth","innerHeight","pad","dir","padlen","isPlainObject","nodeType","copyIsArray","deep","mixinPrototype","mixin","replace","mixinKeys","childNodes","cloneNode","diameter","_diameter","_radius","circumference","setTo","copyFrom","copyTo","dest","round","output","circumferencePoint","asDegrees","sample","steps","startAngle","endAngle","linear","offsetPoint","top","bottom","equals","intersects","degToRad","intersectsRectangle","halfWidth","halfHeight","xCornerDist","yCornerDist","intersectsLine","returnPoints","del","p0Exists","pointOnSegment","p1Exists","Ellipse","normx","normy","fromPoints","fromSprite","startSprite","endSprite","useCenter","centerX","centerY","fromAngle","rotateAround","line","asSegment","intersectsPoints","midPoint","centerOn","pointOnLine","fuzzyEqual","xMin","xMax","yMin","yMax","coordinatesOnLine","stepRate","results","sx","sy","err","e2","wrap","uc","ua","ub","empty","bx1","by1","bx2","by2","intersectionWithRectangle","edgeIntersection","closestDistance","normalAngle","fromArray","newPos","translate","tx1","identity","invert","setToPolar","azimuth","clampX","clamp","clampY","equalsXY","fuzzyEquals","fuzzyEqualsXY","angleXY","atan2","radToDeg","atan","getMagnitude","getMagnitudeSq","setMagnitude","magnitude","isZero","limit","expand","perp","rperp","normalRightHand","negative","multiplyAdd","interpolate","project","amt","projectUnit","pointslength","parse","xProp","yProp","isPoint","sortClockwise","center","_points","closed","flattened","toNumberArray","flatten","inside","ix","iy","jx","jy","calculateArea","avgHeight","floorAll","ceilAll","copyFromBounds","inflate","containsRect","intersection","intersectsRaw","union","randomX","randomY","getPoint","sides","inflatePoint","createFromBounds","containsRaw","rx","ry","rw","rh","volume","sameDimensions","NEGATIVE_INFINITY","POSITIVE_INFINITY","EmptyRectangle","RoundedRectangle","Camera","deadzone","roundPx","atLimit","totalInView","onShakeComplete","Signal","onFlashComplete","onFadeComplete","fx","_targetPosition","_edge","_position","intensity","duration","horizontal","vertical","shakeBounds","_fxDuration","_fxType","_fixedView","FOLLOW_LOCKON","FOLLOW_PLATFORMER","FOLLOW_TOPDOWN","FOLLOW_TOPDOWN_TIGHT","SHAKE_BOTH","SHAKE_HORIZONTAL","SHAKE_VERTICAL","ENABLE_FX","boot","Graphics","follow","lerpX","lerpY","helper","unfollow","focusOn","setPosition","focusOnXY","shake","flash","beginFill","drawRect","endFill","fade","updateFX","updateShake","checkBounds","elapsedMS","dispatch","rnd","frac","updateTarget","math","setBoundsToWorld","vx","vw","vy","vh","setSize","resetFX","State","make","input","load","sound","state","tweens","particles","physics","preload","loadUpdate","loadRender","preRender","paused","resumed","pauseUpdate","shutdown","StateManager","pendingState","states","_pendingState","_clearWorld","_clearCache","_created","_args","onStateChange","onInitCallback","onPreloadCallback","onCreateCallback","onUpdateCallback","onRenderCallback","onResizeCallback","onPreRenderCallback","onLoadUpdateCallback","onLoadRenderCallback","onPausedCallback","onResumedCallback","onPauseUpdateCallback","onShutDownCallback","onPause","pause","onResume","resume","autoStart","newState","isBooted","callbackContext","clearWorld","clearCache","checkState","restart","dummy","previousStateKey","clearCurrentState","setCurrentState","totalQueuedFiles","totalQueuedPacks","loadComplete","removeAll","debug","link","unlink","_kickstart","getCurrentState","elapsedTime","renderType","_bindings","_prevParams","memorize","_shouldPropagate","active","_boundDispatch","validateListener","fnName","_registerListener","isOnce","listenerContext","priority","binding","prevIndex","_indexOfListener","SignalBinding","_addBinding","execute","_priority","cur","_listener","addOnce","_destroy","getNumListeners","halt","bindings","paramsArr","forget","dispose","_this","signal","_isOnce","_signal","callCount","params","handlerReturn","detach","isBound","getListener","getSignal","prevPoint","Date","mouse","date","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","sampleRate","iChannel0","iChannel1","iChannel2","iChannel3","setResolution","pointer","toFixed","totalElapsedSeconds","anchorX","anchorY","Cache","Plugin","hasPreUpdate","hasUpdate","hasPostUpdate","hasRender","hasPostRender","postRender","PluginManager","plugins","_len","_i","plugin","postUpdate","Stage","disableVisibilityChange","currentRenderOrderID","_hiddenVar","_onChange","parseConfig","setBackgroundColor","DOM","getOffset","setUserSelect","setTouchAction","checkVisibility","document","hidden","webkitHidden","mozHidden","msHidden","visibilityChange","_onClick","hasFocus","addEventListener","onblur","onfocus","onpagehide","onpageshow","cocoonJSApp","CocoonJS","App","onSuspended","onActivated","focusLoss","focusGain","gamePaused","gameResumed","valueToColor","updateColor","removeEventListener","silent","hash","removeFromHash","Group","addToStage","enableBody","physicsBodyType","Physics","ARCADE","physicsType","alive","ignoreDestroy","pendingDestroy","classType","cursor","inputEnableChildren","updateOnlyExistingChildren","onChildInputDown","onChildInputUp","onChildInputOver","onChildInputOut","enableBodyDebug","physicsSortDirection","onDestroy","cursorIndex","fixedToCamera","cameraOffset","_sortProperty","RETURN_NONE","RETURN_TOTAL","RETURN_CHILD","RETURN_ALL","SORT_ASCENDING","SORT_DESCENDING","updateZ","addToHash","inputEnabled","events","onAddedToGroup$dispatch","addAt","addMultiple","moveAll","getAt","createMultiple","quantity","singleKey","singleFrame","align","cellWidth","cellHeight","alignIn","resetCursor","next","previous","swap","child1","bringToTop","getIndex","sendToBack","moveUp","moveDown","xy","getByName","oldChild","newChild","hasProperty","operation","checkProperty","checkAlive","checkVisible","setAll","setAllChildren","checkAll","checkAny","addAll","property","amount","subAll","multiplyAll","divideAll","kill","killAll","callAllExists","revive","reviveAll","resetAll","checkExists","resetChild","existsValue","callbackFromArray","callAll","method","methodLength","contextLength","renderOrderID","predicate","ArraySet","forEachExists","iterate","forEachAlive","forEachDead","order","ascendingSortHandler","descendingSortHandler","customSort","sortHandler","returnType","total","getFirst","getFirstExists","createIfNull","getFirstAlive","getFirstDead","loadTexture","getTop","getBottom","getClosestTo","tempDistance","getFurthestFrom","countLiving","countDead","getRandom","ArrayUtils","getRandomItem","getRandomExists","list","getAll","pick","destroyPhase","onRemovedFromGroup$dispatch","group","destroyTexture","removeBetween","scatter","shuffle","destroyChildren","soft","_definedSize","stateChange","setBounds","useBounds","wrapAll","between","Game","physicsConfig","multiTexture","isRunning","raf","net","Device","lockRender","pendingStep","stepCount","onBlur","onFocus","_paused","_codePaused","currentUpdateID","updatesThisFrame","rendersThisFrame","_deltaTime","_lastCount","_spiraling","fpsProblemNotifier","forceSingleUpdate","forceSingleRender","dropFrames","_nextFpsNotification","enableDebug","RandomDataGenerator","now","whenReady","seed","ScaleManager","setUpRenderer","GameObjectFactory","GameObjectCreator","Loader","Time","TweenManager","Input","SoundManager","Particles","Create","Net","Debug","isDisabled","showDebugHeader","RequestAnimationFrame","stopFocus","focus","isReady","onReady","hideBanner","webAudio","ie","setImageRenderingCrisp","webGL","contextRestored","webGLRendererError","cocoonJS","smoothed","addToDOM","preventDefault","clearGLTextures","updateLogic","desiredFpsMult","updateRender","slowMotion","desiredFps","slowStep","elapsed","countUpdate","countRender","enableStep","disableStep","removeFromDOM","muteOnPause","setMute","cordova","iOS","unsetMute","hitCanvas","hitContext","moveCallbacks","customCandidateHandler","customCandidateHandlerContext","pollRate","multiInputOverride","MOUSE_TOUCH_COMBINE","maxPointers","tapRate","doubleTapRate","holdRate","justPressedRate","justReleasedRate","recordPointerHistory","recordRate","recordLimit","touchLockCallbacks","pointer1","pointer2","pointer3","pointer4","pointer5","pointer6","pointer7","pointer8","pointer9","pointer10","pointers","activePointer","mousePointer","keyboard","touch","mspointer","gamepad","resetLocked","onDown","onUp","onTap","onHold","minPriorityID","interactiveItems","_localPoint","_pollCounter","_oldPosition","_x","_y","MOUSE_OVERRIDES_TOUCH","TOUCH_OVERRIDES_MOUSE","MAX_POINTERS","Pointer","PointerMode","CURSOR","addPointer","Mouse","Touch","MSPointer","Keyboard","Gamepad","_onClickTrampoline","onClickTrampoline","setInteractiveCandidateHandler","addMoveCallback","addTouchLockCallback","onEnd","removeTouchLockCallback","executeTouchLockCallbacks","cb","deleteMoveCallback","CONTACT","hard","resetSpeed","startPointer","countActivePointers","updatePointer","identifier","move","stopPointer","getPointer","isActive","getPointerFromIdentifier","getPointerFromId","pointerId","getLocalPosition","Creature","TileSprite","graphicsData","fill","processClickTrampolines","mouseDownCallback","mouseUpCallback","mouseOutCallback","mouseOverCallback","mouseWheelCallback","capture","button","wheelDelta","locked","stopOnGameOut","pointerLock","_onMouseDown","_onMouseMove","_onMouseUp","_onMouseOut","_onMouseOver","_onMouseWheel","_wheelEvent","NO_BUTTON","LEFT_BUTTON","MIDDLE_BUTTON","RIGHT_BUTTON","BACK_BUTTON","FORWARD_BUTTON","WHEEL_UP","WHEEL_DOWN","android","chrome","onMouseDown","onMouseMove","onMouseUp","_onMouseUpGlobal","onMouseUpGlobal","_onMouseOutGlobal","onMouseOutGlobal","onMouseOut","onMouseOver","onMouseWheel","wheelEvent","mouseMoveCallback","withinGame","resetButtons","bindEvent","deltaY","requestPointerLock","element","mozRequestPointerLock","webkitRequestPointerLock","_pointerLockChange","pointerLockChange","pointerLockElement","mozPointerLockElement","webkitPointerLockElement","releasePointerLock","exitPointerLock","mozExitPointerLock","webkitExitPointerLock","_stubsGenerated","prop","makeBinder","detail","deltaX","wheelDeltaX","deltaZ","pointerDownCallback","pointerMoveCallback","pointerUpCallback","_onMSPointerDown","_onMSPointerMove","_onMSPointerUp","_onMSPointerUpGlobal","_onMSPointerOut","_onMSPointerOver","onPointerDown","onPointerMove","onPointerUp","onPointerUpGlobal","onPointerOut","onPointerOver","pointerType","DeviceButton","buttonCode","isDown","isUp","timeDown","timeUp","repeats","altKey","shiftKey","ctrlKey","onFloat","startStop","condition","padFloat","justPressed","justReleased","pointerMode","leftButton","middleButton","rightButton","backButton","forwardButton","eraserButton","ERASER_BUTTON","_holdSent","_history","_nextDrop","_stateReset","clientX","clientY","pageX","pageY","screenX","screenY","rawMovementX","rawMovementY","movementX","movementY","isMouse","previousTapTime","totalTouches","msSinceLastClick","targetObject","interactiveCandidates","positionDown","positionUp","_clickTrampolines","_trampolineTargetObject","processButtonsDown","processButtonsUp","processButtonsUpDown","buttons","down","toLowerCase","updateButtons","totalActivePointers","_touchedHandler","processInteractiveObjects","shift","fromClick","pollLocked","mozMovementX","webkitMovementX","mozMovementY","webkitMovementY","noPause","isDragged","highestRenderOrderID","highestInputPriorityID","candidateTarget","currentNode","checked","validForInput","checkPointerDown","checkPointerOver","priorityID","swapTarget","newTarget","_pointerOutHandler","_pointerOverHandler","leave","currentPointers","addClickTrampoline","callbackArgs","trampolines","trampoline","_releasedHandler","resetMovement","touchStartCallback","touchMoveCallback","touchEndCallback","touchEnterCallback","touchLeaveCallback","touchCancelCallback","_onTouchStart","_onTouchMove","_onTouchEnd","_onTouchEnter","_onTouchLeave","_onTouchCancel","onTouchStart","onTouchMove","onTouchEnd","onTouchEnter","onTouchLeave","onTouchCancel","consumeDocumentTouches","_documentTouchMove","changedTouches","InputHandler","useHandCursor","_setHandCursor","allowHorizontalDrag","allowVerticalDrag","snapOffset","snapOnDrag","snapOnRelease","snapX","snapY","snapOffsetX","snapOffsetY","pixelPerfectOver","pixelPerfectClick","pixelPerfectAlpha","draggable","boundsRect","boundsSprite","scaleLayer","dragOffset","dragFromCenter","dragStopBlocksInputUp","dragStartPoint","dragDistanceThreshold","dragTimeThreshold","downPoint","snapPoint","_dragPoint","_dragPhase","_pendingDrag","_dragTimePass","_dragDistancePass","_wasEnabled","_tempPoint","_pointerData","camX","camY","isOver","isOut","timeOver","timeOut","downDuration","onAddedToGroup","addedToGroup","onRemovedFromGroup","removedFromGroup","highestID","highestRenderID","includePixelPerfect","isPixelPerfect","pointerX","pointerY","pointerDown","pointerUp","pointerTimeDown","pointerTimeUp","pointerOver","pointerOut","pointerTimeOver","pointerTimeOut","pointerDragged","fastTest","checkPixel","_dx","_dy","startDrag","_draggedPointerID","updateDrag","sendEvent","onInputOver$dispatch","onInputOut$dispatch","onInputDown$dispatch","dragTimeElapsed","onInputUp$dispatch","stopDrag","fromStart","pointerLocalCoord","globalToLocal","checkBoundsRect","checkBoundsSprite","onDragUpdate","justOver","delay","overDuration","justOut","enableDrag","lockCenter","pixelPerfect","alphaThreshold","disableDrag","boundsCenterLocalCoord","onDragStart$dispatch","globalToLocalX","grid","boundsFluid","scaleFluidInversed","globalToLocalY","globalCoord","onDragStop$dispatch","setDragLock","allowHorizontal","allowVertical","enableSnap","onDrag","onRelease","disableSnap","_gamepadIndexMap","_rawPads","_active","_gamepadSupportAvailable","webkitGetGamepads","webkitGamepads","userAgent","getGamepads","_prevRawGamepadTypes","_prevTimestamps","onConnectCallback","onDisconnectCallback","onDownCallback","onUpCallback","onAxisCallback","onFloatCallback","_ongamepadconnected","_gamepaddisconnected","_gamepads","SinglePad","addCallbacks","callbacks","onConnect","onDisconnect","onAxis","_onGamepadConnected","onGamepadConnected","_onGamepadDisconnected","onGamepadDisconnected","newPad","connect","removedPad","disconnect","_pollGamepads","pad1","pollStatus","pad2","pad3","pad4","rawGamepads","gamepadsChanged","_rawPad","singlePad","validConnections","rawIndices","padIndices","connected","rawPad","setDeadZones","deadZone","BUTTON_0","BUTTON_1","BUTTON_2","BUTTON_3","BUTTON_4","BUTTON_5","BUTTON_6","BUTTON_7","BUTTON_8","BUTTON_9","BUTTON_10","BUTTON_11","BUTTON_12","BUTTON_13","BUTTON_14","BUTTON_15","AXIS_0","AXIS_1","AXIS_2","AXIS_3","AXIS_4","AXIS_5","AXIS_6","AXIS_7","AXIS_8","AXIS_9","XBOX360_A","XBOX360_B","XBOX360_X","XBOX360_Y","XBOX360_LEFT_BUMPER","XBOX360_RIGHT_BUMPER","XBOX360_LEFT_TRIGGER","XBOX360_RIGHT_TRIGGER","XBOX360_BACK","XBOX360_START","XBOX360_STICK_LEFT_BUTTON","XBOX360_STICK_RIGHT_BUTTON","XBOX360_DPAD_LEFT","XBOX360_DPAD_RIGHT","XBOX360_DPAD_UP","XBOX360_DPAD_DOWN","XBOX360_STICK_LEFT_X","XBOX360_STICK_LEFT_Y","XBOX360_STICK_RIGHT_X","XBOX360_STICK_RIGHT_Y","PS3XC_X","PS3XC_CIRCLE","PS3XC_SQUARE","PS3XC_TRIANGLE","PS3XC_L1","PS3XC_R1","PS3XC_L2","PS3XC_R2","PS3XC_SELECT","PS3XC_START","PS3XC_STICK_LEFT_BUTTON","PS3XC_STICK_RIGHT_BUTTON","PS3XC_DPAD_UP","PS3XC_DPAD_DOWN","PS3XC_DPAD_LEFT","PS3XC_DPAD_RIGHT","PS3XC_STICK_LEFT_X","PS3XC_STICK_LEFT_Y","PS3XC_STICK_RIGHT_X","PS3XC_STICK_RIGHT_Y","padParent","_padParent","_prevTimestamp","_buttons","_buttonsLen","_axes","_axesLen","getButton","timestamp","rawButtonVal","isNaN","processButtonDown","processButtonUp","processButtonFloat","processAxisChange","triggerCallback","disconnectingIndex","axisCode","buttonValue","Key","keycode","_enabled","durationUp","keyCode","onHoldCallback","onHoldContext","_justDown","_justUp","processKeyDown","processKeyUp","upDuration","pressEvent","onPressCallback","_keys","_capture","_onKeyDown","_onKeyPress","_onKeyUp","_k","onPress","removeCallbacks","addKey","addKeyCapture","addKeys","removeKey","removeKeyCapture","createCursorKeys","up","KeyCode","processKeyPress","clearCaptures","String","fromCharCode","charCode","A","charCodeAt","C","D","E","H","J","K","L","M","O","P","Q","R","S","T","U","V","W","X","Y","Z","ZERO","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","NUMPAD_0","NUMPAD_1","NUMPAD_2","NUMPAD_3","NUMPAD_4","NUMPAD_5","NUMPAD_6","NUMPAD_7","NUMPAD_8","NUMPAD_9","NUMPAD_MULTIPLY","NUMPAD_ADD","NUMPAD_ENTER","NUMPAD_SUBTRACT","NUMPAD_DECIMAL","NUMPAD_DIVIDE","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","F13","F14","F15","COLON","EQUALS","COMMA","UNDERSCORE","PERIOD","QUESTION_MARK","TILDE","OPEN_BRACKET","BACKWARD_SLASH","CLOSED_BRACKET","QUOTES","BACKSPACE","TAB","CLEAR","ENTER","SHIFT","CONTROL","ALT","CAPS_LOCK","ESC","SPACEBAR","PAGE_UP","PAGE_DOWN","END","HOME","PLUS","MINUS","INSERT","DELETE","HELP","NUM_LOCK","match","Component","Angle","wrapAngle","Animation","play","frameRate","loop","killOnComplete","animations","AutoCull","autoCull","inCamera","checkWorldBounds","Bounds","container","alignTo","BringToTop","Core","skipTypeChecks","install","components","Events","PhysicsBody","AnimationManager","LoadTexture","FixedToCamera","previousRotation","preUpdateChildren","fresh","_exists","P2JS","customRender","Crop","cropRect","_crop","updateCrop","resetFrame","oldX","oldY","oldW","oldH","_frame","Delta","Destroy","onDestroy$dispatch","removeFrom","Video","onChangeSource","resizeFrame","BitmapText","_glyphs","_parent","_onDestroy","_onAddedToGroup","_onRemovedFromGroup","_onKilled","_onRevived","_onEnterBounds","_onOutOfBounds","_onInputOver","_onInputOut","_onInputDown","_onInputUp","_onDragStart","_onDragUpdate","_onDragStop","_onAnimationStart","_onAnimationComplete","_onAnimationLoop","onKilled","onRevived","onOutOfBounds","onEnterBounds","onInputOver","onInputOut","onInputDown","onInputUp","onDragStart","onDragStop","onAnimationStart","onAnimationComplete","onAnimationLoop","backing","_fixedToCamera","Health","health","maxHealth","damage","setHealth","heal","InCamera","InputEnabled","InWorld","outOfCameraBoundsKill","_outOfBoundsFired","onEnterBounds$dispatch","onOutOfBounds$dispatch","outOfBoundsKill","inWorld","LifeSpan","lifespan","physicsElapsedMS","onRevived$dispatch","onKilled$dispatch","stopAnimation","BitmapData","hasFrameData","loadFrameData","getFrameData","frameData","Tilemap","TilemapLayer","img","getImage","trimmed","spriteSourceSizeX","spriteSourceSizeY","sourceSizeW","sourceSizeH","refreshTexture","frameName","Overlap","_reset","Reset","ScaleMinMax","scaleMin","scaleMax","checkTransform","setScaleMinMax","Smoothed","existing","weapon","bulletClass","Weapon","createBullets","Image","creature","mesh","tween","physicsGroup","SpriteBatch","audio","audioSprite","addSprite","tileSprite","rope","Rope","text","Text","overFrame","outFrame","downFrame","upFrame","Button","emitter","maxParticles","Arcade","Emitter","retroFont","font","characterWidth","characterHeight","chars","charsPerRow","xSpacing","ySpacing","xOffset","yOffset","RetroFont","bitmapText","tilemap","tileWidth","tileHeight","addToCache","uuid","addRenderTexture","video","bitmapData","addBitmapData","Tween","preUpdatePhysics","preUpdateLifeSpan","preUpdateInWorld","preUpdateCore","_onOverFrame","_onOutFrame","_onDownFrame","_onUpFrame","onOverSound","onOutSound","onDownSound","onUpSound","onOverSoundMarker","onOutSoundMarker","onDownSoundMarker","onUpSoundMarker","onOverMouseOnly","justReleasedPreventsOver","freezeFrames","forceOut","setFrames","onInputOverHandler","onInputOutHandler","onInputDownHandler","onInputUpHandler","clearFrames","setStateFrame","switchImmediately","frameKey","changeStateFrame","setStateSound","marker","soundKey","markerKey","Sound","AudioSprite","playStateSound","setSounds","overSound","overMarker","downSound","downMarker","outSound","outMarker","upSound","upMarker","setOverSound","setOutSound","setDownSound","setUpSound","fastSpriteBatch","ready","isRotated","childTransform","skipPool","ctx","imageData","FrameData","textureFrame","addFrame","Frame","disableTextureUpload","cls","_image","_pos","_size","_scale","_rotate","_alpha","prev","_anchor","_tempR","_tempG","_tempB","_circle","_swapCanvas","moveH","moveV","draw","onload","addImage","toDataURL","processPixelRGB","pixel","createColor","unpackPixel","getPixel32","setPixel32","processPixel","replaceRGB","g1","g2","region","packPixel","setHSL","bHaveH","bHaveS","bHaveL","HSLtoRGB","shiftHSL","red","green","blue","immediate","LITTLE_ENDIAN","setPixel","getPixel","getPixelRGB","hsl","hsv","getPixels","getFirstPixel","scan","newWidth","newHeight","getCanvas","op","copyTransform","copyRect","drawGroup","drawGroupProxy","drawFull","renderGraphics","shadow","blur","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","alphaMask","sourceRect","maskRect","blendSourceAtop","blendReset","extract","destination","prevFont","fillText","beginPath","arc","closePath","moveTo","lineTo","lineWidth","strokeStyle","stroke","polygon","textureLine","createPattern","blendSourceOver","blendSourceIn","blendSourceOut","blendDestinationOver","blendDestinationIn","blendDestinationOut","blendDestinationAtop","blendXor","blendAdd","blendMultiply","blendScreen","blendOverlay","blendDarken","blendLighten","blendColorDodge","blendColorBurn","blendHardLight","blendSoftLight","blendDifference","blendExclusion","blendHue","blendSaturation","blendColor","blendLuminosity","copyBitmapData","destRowStart","getSmoothingEnabled","setSmoothingEnabled","getTransform","translateX","translateY","skewX","skewY","EarCut","holeIndices","dim","hasHoles","outerLen","outerNode","linkedList","eliminateHoles","earcutLinked","clockwise","insertNode","filterPoints","again","steiner","removeNode","ear","pass","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","minTX","minTY","maxTX","maxTY","minZ","zOrder","maxZ","nextZ","prevZ","locallyInside","isValidDiagonal","splitPolygon","getLeftmost","compareX","eliminateHole","hole","findHoleBridge","hx","hy","qx","tan","tanMin","sortLinked","q","tail","numMerges","pSize","qSize","inSize","leftmost","intersectsPolygon","middleInside","Node","an","bp","stencilBufferLimit","lastIndex","clearDirty","graphicsDataPool","switchMode","buildPoly","buildComplexPoly","buildLine","buildRectangle","buildCircle","buildRoundedRectangle","upload","WebGLGraphicsData","rectData","fillColor","fillAlpha","vertPos","tempPoints","rrectData","recPoints","quadraticBezierCurve","vecPos","fromX","fromY","cpX","cpY","toX","toY","getPt","n1","n2","perc","xa","ya","xb","yb","circleData","seg","totalSegs","firstPoint","lastPoint","midPointX","midPointY","unshift","p1x","p1y","p2x","p2y","p3x","p3y","perpx","perpy","perp2x","perp2y","perp3x","perp3y","indexCount","indexStart","lineColor","lineAlpha","glPoints","glIndicies","updateGraphicsTint","_fillTint","_lineTint","strokeRect","ox","oy","xe","ye","xm","ym","bezierCurveTo","maxRadius","quadraticCurveTo","tintR","tintG","tintB","GraphicsData","currentPath","boundsPadding","_localBounds","_boundsDirty","webGLDirty","cachedSpriteDirty","updateLocalBounds","drawTriangle","cull","triangle","cameraToFace","faceNormal","drawPolygon","drawTriangles","point1","point2","point3","lineStyle","drawShape","cpX2","cpY2","dt2","dt3","arcTo","mm","dd","cc","tt","k1","k2","j1","j2","qy","anticlockwise","segments","sweep","segs","startX","startY","filling","theta","theta2","cTheta","sTheta","segMinus","remainder","drawRoundedRect","drawCircle","drawEllipse","canvasBuffer","updateCachedSpriteTexture","_prevTint","tempPoint","cachedSprite","destroyCachedSprite","textureBuffer","tempMatrix","renderXY","renderRawXY","updateBase","realResolution","getBase64","webGLPixels","Uint8Array","readPixels","tempCanvas","canvasData","textBounds","strokeColors","fontStyles","fontWeights","autoRound","useAdvancedWrap","splitRegExp","characterLimitSize","characterLimitSuffix","_res","_text","_fontComponents","_lineSpacing","_charCount","setStyle","updateText","setShadow","shadowStroke","shadowFill","newStyle","backgroundColor","boundsAlignH","boundsAlignV","strokeThickness","wordWrap","wordWrapWidth","maxLines","tabs","fontToComponents","fontStyle","fontVariant","fontWeight","fontSize","componentsToFont","outputText","substring","runWordWrap","lines","lineWidths","maxLineWidth","fontProperties","determineFontProperties","drawnLines","measureLine","measureText","tab","section","snapToCeil","lineHeight","lineSpacing","textBaseline","lineCap","lineJoin","linePositionX","linePositionY","ascent","updateLine","updateShadow","strokeText","renderTabLine","snap","lineLength","letter","clearColors","clearFontValues","addColor","addStrokeColor","addFontStyle","addFontWeight","weight","precalculateWordWrap","advancedWordWrap","basicWordWrap","linesCount","currentLineWidth","words","word","wordWithSpace","wordWidth","newWord","secondPart","spaceLeft","wordWidthWithSpace","updateFont","family","exec","fontFamily","setText","parseList","setTextBounds","properties","fontPropertiesCache","fontPropertiesCanvas","fontPropertiesContext","baseline","descent","imagedata","setCharacterLimit","characterLimit","suffix","parseFloat","createElement","textWidth","textHeight","_prevAnchor","_maxWidth","_data","getBitmapFont","_font","_fontSize","_align","_tint","sourceWidth","sourceHeight","scanLine","lastSpace","wrappedWidth","prevCharCode","maxWidth","test","charAt","charData","kerning","xAdvance","cleanText","re","purgeGlyphs","kept","checkImageKey","characterSpacingX","characterSpacingY","characterPerRow","multiLine","autoUpperCase","customSpacingX","customSpacingY","fixedWidth","fontSet","grabData","currentX","currentY","updateFrameData","stamp","ALIGN_LEFT","ALIGN_RIGHT","ALIGN_CENTER","TEXT_SET1","TEXT_SET2","TEXT_SET3","TEXT_SET4","TEXT_SET5","TEXT_SET6","TEXT_SET7","TEXT_SET8","TEXT_SET9","TEXT_SET10","TEXT_SET11","setFixedWidth","lineAlignment","content","characterSpacing","allowLowerCase","buildRetroFontText","getLongestLine","pasteLine","longestLine","removeUnsupportedCharacters","stripCR","newString","aChar","code","updateOffset","diffX","diffY","frames","getFrames","newText","toUpperCase","_hasUpdateAnimation","_updateAnimationCallback","canvasPadding","drawMode","updateAnimation","nextPoint","perpLength","_vertexBuffer","_initWebGL","_renderStrip","_indexBuffer","_uvBuffer","_colorBuffer","_renderCanvasTriangleStrip","_renderCanvasTriangles","_renderCanvasDrawTriangle","index0","textureSource","textureWidth","textureHeight","u0","v2","paddingX","paddingY","normX","normY","deltaA","deltaB","deltaC","deltaD","deltaE","deltaF","renderStripFlat","strip","rawX","rawY","_updateAnimation","difference","_scroll","textureDebug","tilePattern","frameWidth","frameHeight","physicsElapsed","autoScroll","stopScroll","generateTilingTexture","restartBatch","sessionBlendMode","forcePowerOfTwo","targetWidth","targetHeight","getNextPowerOfTwo","pool","getTotal","getFree","deviceReadyAt","initialized","desktop","iOSVersion","nodeWebkit","electron","ejecta","crosswalk","chromeOS","linux","macOS","windows","windowsPhone","canvasBitBltShift","file","fileSystem","localStorage","worker","css3D","typedArray","vibration","getUserMedia","quirksMode","arora","chromeVersion","epiphany","firefox","firefoxVersion","ieVersion","trident","tridentVersion","mobileSafari","midori","opera","safari","safariVersion","webApp","silk","audioData","ogg","opus","mp3","wav","m4a","webm","dolby","oggVideo","h264Video","mp4Video","webmVideo","vp9Video","hlsVideo","iPhone","iPhone4","iPad","pixelRatio","littleEndian","support32bit","fullscreen","requestFullscreen","cancelFullscreen","fullscreenKeyboard","onInitialized","nonPrimer","readyCheck","_readyCheck","_monitor","_queue","readyState","setTimeout","_initialize","_checkIsLittleEndian","_checkIsUint8ClampedImageData","Uint8ClampedArray","createImageData","vita","kindle","RegExp","$1","_checkOS","$3","process","versions","_checkBrowser","audioElement","canPlayType","major","minor","$2","_checkAudio","videoElement","_checkVideo","has3d","el","transforms","webkitTransform","OTransform","msTransform","MozTransform","insertBefore","getComputedStyle","getPropertyValue","_checkCSS3D","Int8Array","Int32Array","vibrate","webkitVibrate","mozVibrate","msVibrate","getItem","WebGLRenderingContext","compatMode","webkitGetUserMedia","mozGetUserMedia","msGetUserMedia","oGetUserMedia","URL","webkitURL","mozURL","msURL","_checkFeatures","s1","s2","_checkCanvasFeatures","fs","cfs","Element","_checkFullScreenSupport","documentElement","maxTouchPoints","PointerEvent","MSPointerEvent","msPointerEnabled","pointerEnabled","canPlayAudio","canPlayVideo","needsTouchUnlock","PhaserGlobal","fakeiOSTouchLock","isAndroidStockBrowser","matches","display","msTouchAction","overflowHidden","getElementById","overflow","appendChild","parentNode","vendor","prefix","types","msInterpolationMode","setImageRenderingBicubic","forceSetTimeOut","vendors","requestAnimationFrame","cancelAnimationFrame","_isSetTimeOut","_onLoop","_timeOutID","updateSetTimeout","updateRAF","rafTime","timeToCall","clearTimeout","isSetTimeOut","isRAF","DEG_TO_RAD","RAD_TO_DEG","degrees","radians","fuzzyLessThan","fuzzyGreaterThan","fuzzyCeil","fuzzyFloor","average","shear","snapTo","gap","snapToFloor","roundTo","place","floorTo","ceilTo","rotateToAngle","currentAngle","targetAngle","getShortestAngle","angleBetween","angleBetweenY","angleBetweenPoints","angleBetweenPointsY","reverseAngle","angleRad","normalizeAngle","maxAdd","minSub","wrapValue","isOdd","isEven","minProperty","maxProperty","linearInterpolation","bezierInterpolation","bernstein","catmullRomInterpolation","catmullRom","factorial","res","roundAwayFromZero","sinCosGenerator","sinAmplitude","cosAmplitude","frequency","frq","cosTable","sinTable","hypot","distanceSq","distancePow","clampBottom","within","mapLinear","smoothstep","smootherstep","sign","percent","seeds","s0","sow","integer","real","integerInRange","realInRange","ary","weightedPick","QuadTree","maxObjects","maxLevels","_empty","subWidth","subHeight","populate","populateHandler","insert","retrieve","returnObjects","getHostName","location","hostname","checkDomainName","domain","updateQueryString","redirect","href","separator","getQueryString","parameter","keyValues","search","decodeURI","decodeURIComponent","frameBased","_tweens","_add","easeMap","Power0","Easing","Power1","Power2","Power3","Power4","Linear","None","Quad","Quadratic","Out","Cubic","Quart","Quartic","Quint","Quintic","Sine","Sinusoidal","Expo","Exponential","Circ","Circular","Elastic","Back","Bounce","Quad.easeIn","In","Cubic.easeIn","Quart.easeIn","Quint.easeIn","Sine.easeIn","Expo.easeIn","Circ.easeIn","Elastic.easeIn","Back.easeIn","Bounce.easeIn","Quad.easeOut","Cubic.easeOut","Quart.easeOut","Quint.easeOut","Sine.easeOut","Expo.easeOut","Circ.easeOut","Elastic.easeOut","Back.easeOut","Bounce.easeOut","Quad.easeInOut","InOut","Cubic.easeInOut","Quart.easeInOut","Quint.easeInOut","Sine.easeInOut","Expo.easeInOut","Circ.easeInOut","Elastic.easeInOut","Back.easeInOut","Bounce.easeInOut","_pauseAll","_resumeAll","pendingDelete","_manager","addTweens","numTweens","isTweening","checkIsRunning","some","_pause","_resume","pauseAll","resumeAll","manager","timeline","timeScale","repeatCounter","onStart","onLoop","onRepeat","onChildComplete","onComplete","chainedTween","isPaused","_onUpdateCallback","_onUpdateCallbackContext","_pausedTime","_hasStarted","ease","yoyo","Default","TweenData","vEnd","loadValues","updateTweenData","repeatDelay","yoyoDelay","easing","interpolation","repeatAll","chain","startTime","status","PENDING","RUNNING","LOOPED","COMPLETE","generateData","vStart","vStartCache","vEndCache","repeatTotal","inReverse","easingFunction","interpolationFunction","interpolationContext","isFrom","ms","fps","blob","reversed","asin","prevTime","_desiredFps","suggestedFps","advancedTiming","updates","renders","ups","rps","fpsMin","fpsMax","msMin","msMax","pauseDuration","timeExpected","Timer","_frameCount","_elapsedAccumulator","_started","_timeLastSecond","_pauseStarted","_justResumed","_timers","timer","autoDestroy","previousDateNow","updateAdvancedTiming","updateTimers","interval","elapsedSince","since","elapsedSecondsSince","running","expired","nextTick","timeCap","_pauseTotal","_now","_marked","_diff","_newTick","MINUTE","SECOND","HALF","QUARTER","repeatCount","TimerEvent","clearEvents","clearPendingEvents","adjustEvents","baseTime","currentFrame","currentAnim","updateIfVisible","isLoaded","_frameData","_anims","_outputFrames","anim","copyFrameData","useNumericIndex","getFrameIndexes","validateFrames","checkFrameName","isPlaying","getAnimation","refreshFrame","gotFrame","getFrame","getFrameByName","_frameIndex","_frames","loopCount","isFinished","_pauseStartTime","_frameDiff","_frameSkip","onUpdate","isReversed","_timeLastFrame","_timeNextFrame","updateCurrentFrame","onAnimationStart$dispatch","reverseOnce","frameId","useLocalFrameIndex","frameIndex","directionalOffset","dispatchComplete","onAnimationComplete$dispatch","onAnimationLoop$dispatch","signalUpdate","fromPlay","generateFrameNames","zeroPad","spriteSourceSizeW","spriteSourceSizeH","setTrim","actualWidth","actualHeight","destX","destY","destWidth","destHeight","getRect","_frameNames","getFrameRange","AnimationParser","spriteSheet","frameMax","margin","spacing","skipFrames","JSONData","json","newFrame","filename","sourceSize","spriteSourceSize","JSONDataPyxel","tileheight","tilewidth","JSONDataHash","XMLData","xml","getElementsByTagName","frameX","frameY","autoResolveURL","binary","bitmapFont","compressedTexture","_urlMap","_urlResolver","_urlTemp","onSoundUnlock","_cacheMap","TEXTURE","SOUND","PHYSICS","BINARY","BITMAPFONT","JSON","XML","SHADER","RENDER_TEXTURE","_pendingCount","_addImages","DEFAULT_KEY","DEFAULT_SRC","MISSING","MISSING_KEY","MISSING_SRC","READY_TIMEOUT","addCompressedTextureMetaData","extension","arrayBuffer","removeImage","LoaderParser","fileFormat","_resolveURL","addCanvas","addImageAsync","_removePending","_addPending","addDefaultImage","addMissingImage","addSound","audioTag","decoded","isDecoding","touchLocked","addText","addPhysicsData","addTilemap","mapData","addBinary","binaryData","addBitmapFont","atlasData","atlasType","jsonBitmapFont","xmlBitmapFont","addBitmapFontFromAtlas","atlasKey","atlasFrame","dataKey","dataType","getBaseTexture","fontData","getJSON","getXML","addJSON","addXML","addVideo","isBlob","addShader","addSpriteSheet","addTextureAtlas","TEXTURE_ATLAS_XML_STARLING","TEXTURE_ATLAS_JSON_PYXEL","reloadSound","getSound","reloadSoundComplete","updateSound","decodedSound","isSoundDecoded","isSoundReady","checkKey","checkURL","checkCanvasKey","checkTextureKey","checkSoundKey","checkTextKey","checkPhysicsKey","checkTilemapKey","checkBinaryKey","checkBitmapDataKey","checkBitmapFontKey","checkJSONKey","checkXMLKey","checkVideoKey","checkShaderKey","checkRenderTextureKey","full","getTextureFrame","getSoundData","getText","getPhysicsData","fixtureKey","fixtures","fixture","getTilemapData","getBinary","getBitmapData","getVideo","getShader","getRenderTexture","getFrameCount","getFrameByIndex","getURL","getKeys","removeCanvas","destroyBaseTexture","removeSound","removeText","removePhysics","removeTilemap","removeBinary","removeBitmapData","removeBitmapFont","removeJSON","removeXML","removeVideo","removeShader","removeRenderTexture","removeSpriteSheet","removeTextureAtlas","baseURL","destroyItem","readyTimeout","_ready","_checkReady","isLoading","preloadSprite","crossOrigin","headers","requestedWith","onLoadStart","onLoadComplete","onPackComplete","onFileStart","onFileComplete","onFileError","enableParallel","maxParallelDownloads","_withSyncPointDepth","_fileList","_flightQueue","_processingHead","_fileLoadStarted","_totalPackCount","_totalFileCount","_loadedPackCount","_loadedFileCount","TEXTURE_ATLAS_JSON_ARRAY","TEXTURE_ATLAS_JSON_HASH","PHYSICS_LIME_CORONA_JSON","PHYSICS_PHASER_JSON","setPreloadSprite","checkKeyExists","getAssetIndex","bestFound","loaded","loading","getAsset","fileIndex","addToFileList","overwrite","syncPoint","currentFile","replaceInFileList","pack","imageFromBitmapData","imageFromGrid","imageFromTexture","pixelWidth","pixelHeight","palette","exkey","images","urls","script","spritesheet","autoDecode","noAudio","jsonURL","jsonData","audiosprite","loadEvent","asBlob","CSV","TILED_JSON","LIME_CORONA_JSON","textureURL","atlasURL","parseXml","atlasJSONArray","atlas","atlasJSONHash","atlasXML","withSyncPoint","addSyncPoint","asset","removeFile","updateProgress","processLoadQueue","finishedLoading","requestUrl","requestObject","progress","syncblock","inflightLimit","processPack","loadFile","abnormal","asyncComplete","errorMessage","packData","transformUrl","xhrLoad","fileComplete","loadImageTag","getAudioURL","usingWebAudio","usingAudioTag","loadAudioTag","fileError","getVideoURL","loadVideoTag","jsonLoadComplete","xmlLoadComplete","csvLoadComplete","onerror","controls","autoplay","videoLoadEvent","canplay","Audio","playThroughEvent","xhr","XMLHttpRequest","open","responseType","setRequestHeader","message","send","videoType","uri","lastIndexOf","audioType","reason","loadNext","responseText","response","decode","language","defer","head","contentType","domparser","DOMParser","parseFromString","ActiveXObject","async","loadXML","totalLoadedFiles","totalLoadedPacks","progressFloat","info","common","getAttribute","letters","kernings","second","finalizeBitmapFont","_face","_lineHeight","_id","_xoffset","_yoffset","_xadvance","_second","_first","_amount","bitmapFontData","pvr","uintArray","byteArray","pvrHeader","pixelFormat","flags","colorSpace","channelType","depth","numberOfSurfaces","numberOfFaces","numberOfMipmaps","metaDataSize","byteLength","dds","ddsHeader","pitch","mipmapCount","formatSize","formatFlag","formatFourCC","formatBitCount","formatRBitMask","formatGBitMask","formatBBitMask","formatABitMask","caps1","caps2","caps3","caps4","reserved2","DXGIFormat","resourceDimension","miscFlag","arraySize","ktx","ktxHeader","imageSizeOffset","imageSize","glInternalFormat","endianness","glType","glTypeSize","glFormat","glBaseInternalFormat","pixelDepth","numberOfArrayElements","numberOfMipmapLevels","bytesOfKeyValueData","keyAndValueByteSize","pkm","pkmHeader","originalWidth","originalHeight","autoplayKey","sounds","spritemap","addMarker","connectToMaster","markers","totalDuration","currentTime","durationMS","stopTime","pausedPosition","pausedTime","currentMarker","fadeTween","pendingPlayback","override","allowMultiple","externalNode","masterGainNode","gainNode","_sound","_globalVolume","_markedToDelete","_removeFromSoundManager","masterGain","createGain","createGainNode","gain","soundHasUnlocked","onDecoded","onPlay","onStop","onMute","onMarkerComplete","_volume","_buffer","_muted","_tempMarker","_tempPosition","_tempVolume","_tempPause","_muteVolume","_tempLoop","_onDecodedEventDispatched","removeMarker","onEndedHandler","onended","isDecoded","loopFull","forceRestart","noteOff","createBufferSource","noteGrainOn","muted","mute","prevMarker","fadeIn","fadeTo","fadeOut","fadeComplete","updateGlobalVolume","globalVolume","onSoundDecode","onVolumeChange","onUnMute","onTouchUnlock","channels","_codeMuted","_unlockSource","_sounds","_watchList","_watching","_watchCallback","_watchContext","disableAudio","disableWebAudio","audioContext","setTouchLock","unlock","setTouchUnlock","noteOn","stopAll","soundData","decodeAudioData","setDecodedCallback","files","playbackState","PLAYING_STATE","FINISHED_STATE","removeByKey","close","dom","minWidth","minHeight","maxHeight","forceLandscape","forcePortrait","incorrectOrientation","_pageAlignHorizontally","_pageAlignVertically","onOrientationChange","enterIncorrectOrientation","leaveIncorrectOrientation","hasPhaserSetFullScreen","fullScreenTarget","_createdFullScreenTarget","onFullScreenInit","onFullScreenChange","onFullScreenError","screenOrientation","getScreenOrientation","scaleFactorInversed","aspectRatio","sourceAspectRatio","windowConstraints","compatibility","supportsFullScreen","orientationFallback","noMargins","scrollTo","forceMinimumDocumentHeight","canExpandParent","clickTrampoline","_scaleMode","NO_SCALE","_fullScreenScaleMode","parentIsWindow","parentScaleFactor","trackParentInterval","onSizeChange","onResize","onResizeContext","_pendingScaleMode","_fullScreenRestore","_gameSize","_userScaleFactor","_userScaleTrim","_lastUpdate","_updateThrottle","_updateThrottleReset","_parentBounds","_tempBounds","_lastReportedCanvasSize","_lastReportedGameSize","_booted","setupScale","EXACT_FIT","SHOW_ALL","RESIZE","USER_SCALE","MODES","compat","_orientationChange","orientationChange","_windowResize","windowResize","_fullScreenChange","fullScreenChange","_fullScreenError","fullScreenError","_gameResumed","setGameSize","FlexGrid","fullScreenScaleMode","pageAlignHorizontally","alignH","pageAlignVertically","alignV","scaleH","scaleV","setUserScale","trimH","trimV","getParentBounds","visualBounds","updateDimensions","queueUpdate","currentScaleMode","hScale","vScale","hTrim","vTrim","setResizeCallback","signalSizeChange","setMinMax","prevThrottle","prevWidth","prevHeight","boundsChanged","orientationChanged","updateOrientationState","updateLayout","throttle","updateScalingAndBounds","forceOrientation","classifyOrientation","orientation","previousOrientation","previouslyIncorrect","isLandscape","isPortrait","changed","correctnessChanged","scrollTop","setMaximum","setExactFit","isFullScreen","boundingParent","setShowAll","resetCanvas","reflowCanvas","reflowGame","layoutBounds","clientRect","getBoundingClientRect","parentRect","offsetParent","wc","windowBounds","alignCanvas","parentBounds","canvasBounds","currentEdge","targetEdge","marginLeft","marginRight","marginTop","marginBottom","cssWidth","cssHeight","expanding","createFullScreenTarget","fsTarget","background","startFullScreen","allowTrampoline","cleanupCreatedTarget","initData","targetElement","ALLOW_KEYBOARD_INPUT","stopFullScreen","prepScreenMode","enteringFullscreen","createdTarget","scaleSprite","letterBox","scaleX1","scaleY1","scaleX2","scaleY2","scaleOnWidth","bmd","columnWidth","renderShadow","currentColor","currentAlpha","_line","_rect","soundInfo","filled","rectangle","geom","cameraInfo","hideIfUp","downColor","upColor","worldX","worldY","spriteInputInfo","justDown","justUp","inputInfo","spriteBounds","ropeSegments","segment","spriteInfo","spriteCoords","lineInfo","forceType","ellipse","quadTree","quadtree","NINJA","Ninja","BOX2D","Box2D","renderBody","bodyInfo","renderBodyInfo","box2d","box2dWorld","renderDebugDraw","box2dBody","displayList","canvasPool","phaser","factor","loader","box","scrollY","scrollLeft","scrollX","clientTop","clientLeft","cushion","calibrate","coords","getAspectRatio","inLayoutViewport","primaryFallback","screen","mozOrientation","msOrientation","matchMedia","documentBounds","pageXOffset","pageYOffset","clientWidth","clientHeight","offsetWidth","scrollWidth","offsetHeight","scrollHeight","randomIndex","removeRandomItem","newLength","transposeMatrix","sourceRowCount","sourceColCount","rotateMatrix","findClosest","arr","NaN","low","high","rotateRight","rotateLeft","numberArray","numberArrayStep","LinkedList","entity","palettes","0","PALETTE_ARNE","PALETTE_JMP","PALETTE_CGA","PALETTE_C64","PALETTE_JAPANESE_MACHINE","row","boundsCustom","boundsFull","boundsNone","positionCustom","positionFluid","positionFull","positionNone","scaleCustom","scaleFluid","scaleFull","scaleNone","customWidth","customHeight","customOffsetX","customOffsetY","ratioH","ratioV","layers","createCustomLayer","layer","FlexLayer","createFluidLayer","createFullLayer","createFixedLayer","persist","fitSprite","topLeft","topMiddle","topRight","bottomLeft","bottomMiddle","bottomRight","RED","ORANGE","YELLOW","GREEN","AQUA","BLUE","VIOLET","WHITE","BLACK","GRAY","RGBtoHSL","RGBtoHSV","fromRGBA","toRGBA","toABGR","RGBArrayToHex","rgb","hueToColor","HSVtoRGB","color32","getColor","getColor32","RGBtoString","componentToHex","hexToRGB","hex","hexToColor","webToColor","web","tempColor","getRGB","HSVColorWheel","HSLColorWheel","interpolateColor","color1","color2","currentStep","src1","src2","hsv1","hsv2","dh","h3","interpolateColorWithRGB","or","og","ob","interpolateRGB","getRandomColor","getWebRGB","getAlpha","getAlphaFloat","getRed","getGreen","getBlue","blendNormal","blendAverage","blendSubtract","blendNegation","blendLinearDodge","blendLinearBurn","blendLinearLight","blendVividLight","blendPinLight","blendHardMix","blendReflect","blendGlow","blendPhoenix","arcade","ninja","chipmunk","matter","CHIPMUNK","MATTERJS","P2","Matter","startSystem","system","enableAABB","checkCollision","OVERLAP_BIAS","forceX","sortDirection","LEFT_RIGHT","skipQuadTree","_total","SORT_NONE","RIGHT_LEFT","TOP_BOTTOM","BOTTOM_TOP","updateMotion","allowRotation","velocityDelta","computeVelocity","angularAcceleration","angularDrag","maxAngular","acceleration","drag","maxVelocity","allowGravity","allowDrag","object1","object2","overlapCallback","processCallback","collideObjects","collide","collideCallback","sortLeftRight","sortRightLeft","sortTopBottom","sortBottomTop","overlapOnly","collideHandler","collideGroupVsSelf","collideSpriteVsSprite","collideSpriteVsGroup","collideSpriteVsTilemapLayer","collideGroupVsGroup","collideGroupVsTilemapLayer","sprite1","sprite2","separate","items","bounds1","bounds2","group1","group2","body1","body2","none","isCircle","separateCircle","bodyRect","bodyCircle","resultX","resultY","separateX","separateY","onOverlap","onCollide","circleBodyIntersects","getOverlapX","getOverlapY","angleCollision","immovable","customSeparateX","tempVel1","tempVel2","bounce","maxOverlap","deltaAbsX","embedded","touching","overlapX","deltaAbsY","overlapY","moves","nv1","nv2","avg","customSeparateY","getObjectsUnderPointer","getObjectsAtLocation","callbackArg","moveToObject","maxTime","distanceBetween","moveToPointer","angleToPointer","distanceToPointer","moveToXY","distanceToXY","velocityFromAngle","velocityFromRotation","accelerationFromRotation","accelerateToObject","xSpeedMax","ySpeedMax","accelerateToPointer","accelerateToXY","angleToXY","closest","targets","farthest","angleBetweenCenters","worldAngleToPointer","preRotation","newVelocity","deltaMax","worldBounce","onWorldBounds","facing","overlapR","collideWorldBounds","wasTouching","blocked","tilePadding","syncBounds","isMoving","stopVelocityOnCollide","moveTimer","moveDistance","moveDuration","moveTarget","moveEnd","onMoveComplete","movementCallback","movementCallbackContext","_sx","_sy","updateBounds","asx","asy","updateCenter","updateMovement","collided","stopMovement","stopVelocity","check","moveFrom","setCircle","onFloor","onCeiling","onWall","TilemapCollision","TILE_BIAS","tilemapLayer","getTiles","getTileOffsetX","getTileOffsetY","separateTile","tile","tilemapLayerOffsetX","tilemapLayerOffsetY","collisionCallback","collisionCallbackContext","faceLeft","faceRight","faceTop","faceBottom","tileCheckX","tileCheckY","collideRight","collideLeft","processTileSeparationX","collideDown","collideUp","processTileSeparationY","useElapsedTime","materials","InversePointProxy","walls","onBodyAdded","onBodyRemoved","onSpringAdded","onSpringRemoved","onConstraintAdded","onConstraintRemoved","onContactMaterialAdded","onContactMaterialRemoved","postBroadphaseCallback","onBeginContact","onEndContact","mpx","mpxi","pxm","pxmi","beginContactHandler","endContactHandler","collisionGroups","nothingCollisionGroup","CollisionGroup","boundsCollisionGroup","everythingCollisionGroup","boundsCollidesWith","_toRemove","_collisionGroupID","_boundsLeft","_boundsRight","_boundsTop","_boundsBottom","_boundsOwnGroup","removeBodyNextStep","setImpactEvents","impactHandler","setPostBroadphaseCallback","postBroadphaseHandler","_bodyCallbacks","_bodyCallbackContext","_groupCallbacks","_groupCallbackContext","setCollisionGroup","setWorldMaterial","updateBoundsCollisionGroup","setupWall","wall","fixedStepTime","impactCallback","createDistanceConstraint","getBody","createGearConstraint","createRevoluteConstraint","createLockConstraint","createPrismaticConstraint","lockRotation","anchorA","anchorB","setMaterial","createMaterial","createContactMaterial","getSprings","getConstraints","filterStatic","physicsPosition","query","toJSON","createCollisionGroup","bitmask","createSpring","worldA","worldB","localA","localB","createRotationalSpring","createBody","addPolygon","createParticle","convertCollisionObjects","map","collision","shapeData","polyline","addRectangle","clearTilemapLayerBodies","getLayer","convertTilemap","optimize","collides","getTileRight","FixtureList","rawList","namedFixtures","groupedFixtures","allFixtures","setCategory","bit","getFixtures","setMask","setSensor","getFixtureByKey","getGroup","groupID","_ref","_results","callee","PointProxy","collidesWith","removeNextStep","debugBody","_collideWorldBounds","setRectangleFromSprite","createBodyCallback","createGroupCallback","getCollisionMask","updateCollisionMask","clearCollision","clearGroup","clearMask","removeCollisionGroup","clearCallback","shapeChanged","impulse","localX","localY","setZeroRotation","setZeroVelocity","setZeroDamping","moveForward","moveBackward","thrust","thrustLeft","thrustRight","moveLeft","moveRight","updateSpriteTransform","resetDamping","resetMass","clearShapes","addCircle","addPlane","addParticle","addLine","addCapsule","setRectangle","addPhaserPolygon","createdFixtures","fixtureData","shapesOfFixture","addFixture","generatedShapes","categoryBits","maskBits","isSensor","polygons","loadPolygon","BodyDebug","settings","defaultSettings","pixelsPerLengthUnit","debugPolygons","ppu","lw","vrot","_j","_ref1","randomPastelHex","drawCapsule","drawPlane","drawLine","drawRectangle","drawConvex","drawPath","lastx","lasty","diagMargin","diagSize","maxLength","xd","yd","mix","rgbToHex","ImageCollection","firstgid","imageWidth","imageHeight","imageMargin","imageSpacing","containsImageIndex","imageIndex","gid","Tile","flipped","scanned","setCollisionCallback","setCollision","resetCollision","isInteresting","faces","TilemapParser","widthInPixels","heightInPixels","tilesets","imagecollections","tiles","collideIndexes","currentLayer","debugMap","_tempA","NORTH","EAST","SOUTH","WEST","setTileSize","createBlankLayer","addTilesetImage","tileset","tileMargin","tileSpacing","getTilesetIndex","setImage","newSet","Tileset","countX","countY","columns","rows","createFromObjects","CustomClass","adjustY","adjustSize","createFromTiles","replacements","customClass","lh","createLayer","getLayerIndex","rootLayer","groupEnd","indexes","getImageIndex","setTileIndexCallback","setTileLocationCallback","recalculate","setCollisionByIndex","calculateFaces","setCollisionBetween","setCollisionByExclusion","layerArg","setPreventRecalculate","preventingRecalculate","needToRecalculate","above","below","getTileAbove","getTileBelow","getTileLeft","setLayer","hasTile","removeTile","removeTileWorldXY","putTile","putTileWorldXY","searchTileIndex","getTile","nonNull","getTileWorldXY","paste","tileblock","tileA","tileB","swapHandler","removeAllLayers","dump","txt","renderSettings","enableScrollDelta","overdrawRatio","copyCanvas","debugSettings","missingImageFill","debuggedTileOverfill","forceFullRedraw","debugAlpha","facingEdgeStroke","collidingTileOverfill","scrollFactorX","scrollFactorY","rayStepRate","_wrap","_mc","renderWidth","renderHeight","_scrollX","_scrollY","tileOffset","ensureSharedCopyCanvas","sharedCopyCanvas","resizeWorld","_fixX","_unfixX","_fixY","_unfixY","getTileX","getTileY","getTileXY","getRayCastTiles","interestingFace","coord","fetchAll","wy","wx","resolveTileset","tileIndex","setIndex","containsTileIndex","resetTilesetCache","setScale","xScale","yScale","shiftCanvas","copyW","copyH","copyContext","renderRegion","lastAlpha","xmax","ymax","baseX","normStartX","renderDeltaScroll","shiftX","shiftY","renderW","renderH","trueTop","trueBottom","trueLeft","trueRight","renderFull","redrawAll","mc","renderDebug","baseY","normStartY","INSERT_NULL","getEmptyData","parseCSV","parseTiledJSON","column","_slice","fields","sliced","parseObjectGroup","objectGroup","objectsCollection","collisionCollection","nameKey","relativePosition","curl","encoding","binaryString","atob","bytes","opacity","offsetx","offsety","flippedVal","curi","tilesetGroupObjects","lastSet","tileproperties","tileProperties","updateTileData","imagewidth","imageheight","newCollection","objectgroup","lastgid","sid","drawCoords","coordIndex","setSpacing","rowCount","colCount","autoScale","scaleData","_s","autoAlpha","alphaData","_a","onEmit","setAlphaData","setScaleData","emitters","ID","minAngle","maxAngle","minSpeed","maxSpeed","minParticleSpeed","maxParticleSpeed","minParticleScale","maxParticleScale","minRotation","maxRotation","minParticleAlpha","maxParticleAlpha","particleClass","particleDrag","particleAnchor","emitX","emitY","particleBringToTop","particleSendToBack","counts","emitted","failed","totalEmitted","totalFailed","_gravity","_minParticleScale","_maxParticleScale","_timer","_counter","_flowQuantity","_flowTotal","_explode","emitParticle","makeParticles","particleArguments","particle","rndKey","rndFrame","explode","flow","forceQuantity","getNextParticle","resetParticle","setXSpeed","setYSpeed","setRotation","setAlpha","rate","tweenData","setAngle","lifespanOutput","bullets","autoExpandBulletsGroup","autofire","shots","fireLimit","fireRate","fireRateVariance","fireFrom","fireAngle","bulletInheritSpriteSpeed","bulletAnimation","bulletFrameRandom","bulletFrameCycle","bulletWorldWrap","bulletWorldWrapPadding","bulletAngleOffset","bulletAngleVariance","bulletSpeed","bulletSpeedVariance","bulletLifespan","bulletKillDistance","bulletGravity","bulletRotateToVelocity","bulletKey","bulletFrame","_bulletClass","Bullet","_bulletCollideWorldBounds","_bulletKillType","KILL_WORLD_BOUNDS","customBody","bulletBounds","bulletFrames","bulletFrameIndex","anims","onFire","onKill","onFireLimit","trackedSprite","trackedPointer","multiFire","_hasFired","trackRotation","trackOffset","_nextFire","_tempNextFire","_rotatedPoint","KILL_NEVER","KILL_LIFESPAN","KILL_DISTANCE","KILL_WEAPON_BOUNDS","KILL_CAMERA_BOUNDS","KILL_STATIC_BOUNDS","resetShots","newLimit","fire","trackSprite","trackPointer","fireMany","fireOffset","moveX","moveY","bullet","bulletManager","killType","bulletKillType","killDistance","rotateToVelocity","bodyDirty","bulletCollideWorldBounds","fireAtPointer","fireAtSprite","fireAtXY","setBulletBodyOffset","setBulletFrames","cycle","addBulletAnimation","debugBodies","onAccess","onError","onTimeout","playWhenUnlocked","timeout","videoStream","isStreaming","retryLimit","retry","retryInterval","_retryID","_pending","_pendingChangeSource","_autoplay","_endCallback","_playCallback","_video","createVideoFromBlob","videoWidth","videoHeight","createVideoFromURL","snapshot","connectToMediaStream","stream","startMediaStream","captureAudio","removeVideoElement","setAttribute","getUserMediaTimeout","getUserMediaSuccess","getUserMediaError","mozSrcObject","createObjectURL","onloadeddata","checkStream","checkVideoProgress","change","playbackRate","setPause","setResume","playHandler","getTracks","track","playing","ended","changeSource","grab","hasChildNodes","firstChild","removeAttribute","canUseNewCanvasBlendModes"],"mappings":";;CAoDC,SAASA,GAAG,GAAG,iBAAiBC,QAAQC,OAAOD,QAAQD,QAAS,CAAmD,IAAIG,EAAE,oBAAoBC,OAAOD,EAAEC,OAAO,oBAAoBC,OAAOF,EAAEE,OAAO,oBAAoBC,OAAOH,EAAEG,MAAMH,EAAEI,GAAGP,KAAzO,CAA+O,WAAqC,OAAO,SAAUA,EAAEQ,EAAEC,EAAEC,GAAG,SAASC,EAAEC,EAAEC,GAAG,IAAIJ,EAAEG,GAAG,CAAC,IAAIJ,EAAEI,GAAG,CAAC,IAAIE,EAAkB,mBAATC,SAAqBA,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hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIW,GACxB/0D,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAIpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW4wB,EAEpB79C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAItW,GACxB99C,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAGpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIpW,GACxBh+C,EAASitB,KAAWmnC,EAAInW,GAExBj+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAKpBn6C,EAASitB,KAAW0wB,EACpB39C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIlW,GACxBl+C,EA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AAK2G,aAEL3G,KAAK2G,WAAajE,EAAOiE,iBAGL77B,IAApBk1B,KAAKC,aAELD,KAAKC,WAAayC,EAAOzC,iBAGKn1B,IAA9Bk1B,KAAK2K,QAAQC,eAEb5K,KAAK2K,QAAQC,aAAe,IAAI5K,KAAK2K,QAAQ,IAAI3K,KAAKwmB,mBAGnB17C,IAAnCk1B,KAAKgC,cAAc6C,cAEnB7E,KAAKgC,cAAc6C,YAAc,IAAInC,EAAOC,QAGhD3C,KAAKinB,mBAAoB,EAGzBjnB,KAAKwxJ,0BAA4B,WAC7B,OAAO9uJ,EAAOgvC,OAAOnrB,gBASE,oBAAZn/D,SACe,oBAAXC,QAA0BA,OAAOD,UACxCA,QAAUC,OAAOD,QAAUs7C,GAE/Bt7C,QAAQs7C,OAASA,GACQ,oBAAXglB,QAA0BA,OAAOC,IAC/CD,OAAO,SAA+B3vB,EAAK2K,OAASA,GAEpD3K,EAAK2K,OAASA,EAGXA,GACRr6C,KAAKmD","file":"phaser.min.js"} \ No newline at end of file diff --git a/Digital Assignment 1/js/phaser.min.js b/Digital Assignment 1/js/phaser.min.js new file mode 100644 index 000000000..6eb048b7a --- /dev/null +++ b/Digital Assignment 1/js/phaser.min.js @@ -0,0 +1,4 @@ +/* Phaser v2.10.0 - http://phaser.io - @photonstorm - (c) 2016 Photon Storm Ltd. */ + +!function(t){if("object"==typeof exports)module.exports=t();else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.p2=t()}}(function(){return function t(e,i,s){function n(o,a){if(!i[o]){if(!e[o]){var h="function"==typeof require&&require;if(!a&&h)return h(o,!0);if(r)return r(o,!0);throw new Error("Cannot find module '"+o+"'")}var l=i[o]={exports:{}};e[o][0].call(l.exports,function(t){var i=e[o][1][t];return n(i||t)},l,l.exports,t,e,i,s)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;se[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;ia)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var T=0;Tm&&(m+=this.vertices.length),g=Number.MAX_VALUE,m3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e) (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.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.1"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;ca[f]&&(a[f]=u[f]),u[f]i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle");var n=t("../collision/Broadphase");t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;az&&Y0)for(G=0;GMath.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=x,f=b,g=_,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var w=r.vertices[y];if(o.rotate(p,w,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var T=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(T.normalA,f);var P=l(g,T.normalA);o.scale(g,T.normalA,P),a(T.contactPointB,p,n.position),a(T.contactPointA,p,g),a(T.contactPointA,T.contactPointA,t.position),this.contactEquations.push(T),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(T))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=x,p=b;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=x;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,w=u;w=w||0;var T=x,P=b,C=_;a(T,g,y),o.rotate(P,v,w);var S=l(P,T);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,P),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,T,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=x,m=b,y=_,v=w,P=T,E=C,M=S,R=A,L=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(M,u,i),l(g,M)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),I=s.getClosestEdge(c,d,g);if(-1===B||-1===I)return 0;for(var O=0;O<2;O++){var k=B,F=I,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===O){var q;q=k,k=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H=3){if(p)return!0;var Z=this.createContactEquation(j,V,D,U);L++;var J=D.vertices[k%D.vertices.length],Q=D.vertices[(k+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(P,v,y),o.rotate90cw(Z.normalA,P),o.normalize(Z.normalA,Z.normalA),a(M,m,y);var $=l(Z.normalA,M);o.scale(E,Z.normalA,$),a(Z.contactPointA,m,G),a(Z.contactPointA,Z.contactPointA,E),h(Z.contactPointA,Z.contactPointA,G),a(Z.contactPointA,Z.contactPointA,j.position),a(Z.contactPointB,m,N),h(Z.contactPointB,Z.contactPointB,N),a(Z.contactPointB,Z.contactPointB,V.position),this.contactEquations.push(Z),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Z))}}}return this.enableFrictionReduction&&this.enableFriction&&L&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;dh)&&(h=a),(null===c||ah){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,x=nt;if(t instanceof y&&n instanceof y)for(P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(C=0;2!==C;C++){0===C?o.set(m,0,1):1===C&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0),u=(S=T[0]-w[1])<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(var C=0;C!==b.vertices.length;C++){o.rotate(f,b.vertices[C],_),o.rotate(g,b.vertices[(C+1)%b.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0);var S=T[0]-w[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,x=pt,b=ct,_=ut,w=Math.floor((i[0]-d-l[0])/f),T=Math.ceil((i[0]+d-l[0])/f);w<0&&(w=0),T>=p.length&&(T=p.length-1);for(var P=p[w],C=p[T],S=w;SP&&(P=p[S]);if(i[1]-d>P)return!u&&0;for(var A=!1,S=w;S=b[0]&&m[0]<_[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,x,-E),o.add(y,m,g),o.copy(v,x);M=this.createContactEquation(n,t,r,e);o.copy(M.normalA,v),o.scale(M.contactPointB,M.normalA,-d),h(M.contactPointB,M.contactPointB,i),a(M.contactPointB,M.contactPointB,t.position),o.copy(M.contactPointA,y),o.sub(M.contactPointA,M.contactPointA,n.position),this.contactEquations.push(M),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(M))}}if(A=!1,d>0)for(S=w;S<=T;S++)if(o.set(b,S*f,p[S]),o.add(b,b,l),o.sub(g,i,b),o.squaredLength(g)=c.length&&(y=c.length-1);for(var v=c[m],x=c[y],b=m;bv&&(v=c[b]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var _=0,b=m;b=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;ne.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){this.from,this.to;var o=this._currentShape,a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;cthis.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.positioni?(a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n)):-1!==(b=t.indexOf(n))&&t.splice(b,1),this.lowerLimitEnabled&&va?(f.angle=a,-1===n.indexOf(f)&&n.push(f)):-1!==(y=n.indexOf(f))&&n.splice(y,1),this.lowerLimitEnabled&&m>1;if(e<3)return[];for(var i=[],n=[],r=0;r3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,x=1/(f*y-g*g),b=(y*m-g*v)*x,_=(f*v-g*m)*x;return b>=0&&_>=0&&b+_<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;ei&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),x=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||x;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(h=this.shapes.length;h>=0;--h)this.removeShape(this.shapes[h]);var i=new r.Polygon;if(i.vertices=t,i.makeCCW(),"number"==typeof e.removeCollinearPoints&&i.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!i.isSimple())return!1;this.concavePath=i.vertices.slice(0);for(h=0;h=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var T=n.create(),P=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(T,i,t*e),n.multiply(T,this.massMultiplier,T),n.add(r,T,r),this.integrateToTimeOfImpact(t)||(n.scale(P,r,t),n.add(s,s,P),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),M=n.create(),R=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)=l&&h=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var b=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),w=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),T=Math.pow(_,2)-4*b*w;if(!(T<0))if(0===T){if(r.lerp(d,n,o,T),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}else{var P=Math.sqrt(T),C=1/(2*b),S=(-_-P)*C,A=(-_+P)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,x=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;x>=0&&x<=1&&(r.lerp(f,n,h,x),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,x,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;in)&&(n=s),(null===o||sn){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;ee&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),nv){var x=y;y=v,v=x}for(var b=0;b=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,_,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};r.create();var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){(t=t||{}).type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){(t=t||{}).type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=t.lowerBound,a=t.upperBound;n(o,-1e7,-1e7),n(a,1e7,1e7),0===s?a[1]=0:s===Math.PI/2?o[0]=0:s===Math.PI?o[1]=0:s===3*Math.PI/2&&(a[0]=0)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}t("../utils/Utils");var n=t("../events/EventEmitter");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){this.overlappingShapesLastState;var n=this.overlappingShapesCurrentState;if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var s=t,n=e;(i=i||[]).length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;)(n=i.getByKey(i.keys[s]))&&e.push(n.bodyA,n.bodyB);return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s=t&&s=0;T-=2)for(S=b.length-2;S>=0;S-=2)(w[T]===b[S]&&w[T+1]===b[S+1]||w[T+1]===b[S]&&w[T]===b[S+1])&&b.splice(S,2);q=u.length;for(T=0;T!==q;T++){var C=u[T];if(!C.collideConnected)for(var S=b.length-2;S>=0;S-=2)(C.bodyA===b[S]&&C.bodyB===b[S+1]||C.bodyB===b[S]&&C.bodyA===b[S+1])&&b.splice(S,2)}this.postBroadphaseEvent.pairs=b,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var T=0,A=b.length;T!==A;T+=2)for(var E=b[T],M=b[T+1],R=0,L=E.shapes.length;R!==L;R++)for(var B=E.shapes[R],I=B.position,O=B.angle,k=0,F=M.shapes.length;k!==F;k++){var D=M.shapes[k],U=D.position,G=D.angle,N=this.defaultContactMaterial;if(B.material&&D.material){var X=this.getContactMaterial(B.material,D.material);X&&(N=X)}this.runNarrowphase(c,E,B,I,O,M,D,U,G,N,this.frictionGravity)}for(T=0;T!==h;T++)(H=n[T])._wakeUpAfterNarrowphase&&(H.wakeUp(),H._wakeUpAfterNarrowphase=!1);if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(P);for(var W=this.endContactEvent,k=P.length;k--;){var j=P[k];W.shapeA=j.shapeA,W.shapeB=j.shapeB,W.bodyA=j.bodyA,W.bodyB=j.bodyB,this.emit(W)}P.length=0}var V=this.preSolveEvent;V.contactEquations=c.contactEquations,V.frictionEquations=c.frictionEquations,this.emit(V),V.contactEquations=V.frictionEquations=null;var q=u.length;for(T=0;T!==q;T++)u[T].update();if(c.contactEquations.length||c.frictionEquations.length||q)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),T=0;T!==q;T++)v.appendArray(g.equations,u[T].equations);g.split(this);for(T=0;T!==g.islands.length;T++)(K=g.islands[T]).equations.length&&a.solveIsland(t,K)}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),T=0;T!==q;T++)a.addEquations(u[T].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(T=0;T!==h;T++){var H=n[T];H.integrate(t)}for(T=0;T!==h;T++)n[T].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var Y=this.impactEvent,T=0;T!==c.contactEquations.length;T++){var z=c.contactEquations[T];z.firstImpact&&(Y.bodyA=z.bodyA,Y.bodyB=z.bodyB,Y.shapeA=z.shapeA,Y.shapeB=z.shapeB,Y.contactEquation=z,this.emit(Y))}if(this.sleepMode===s.BODY_SLEEPING)for(T=0;T!==h;T++)n[T].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(T=0;T!==h;T++)n[T].sleepTick(this.time,!0,t);for(T=0;T0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,x=t.frictionEquations.length;y=i.type=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0),o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC&&r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0),this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var _=this.beginContactEvent;if(_.shapeA=i,_.shapeB=a,_.bodyA=e,_.bodyB=o,_.contactEquations.length=0,"number"==typeof y)for(P=t.contactEquations.length-y;P1)for(var P=t.frictionEquations.length-b;P=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var x=e[y],b=0,_=x.shapes.length;b!==_;b++){var w=x.shapes[b];r.rotate(p,w.position,x.angle),r.add(p,p,x.position);var T=w.angle+x.angle;(w instanceof o&&g.circleParticle(x,w,p,T,s,n,u,0,!0)||w instanceof a&&g.particleConvex(s,n,u,0,x,w,p,T,!0)||w instanceof h&&g.particlePlane(s,n,u,0,x,w,p,T,!0)||w instanceof l&&g.particleCapsule(s,n,u,0,x,w,p,T,!0)||w instanceof c&&r.squaredLength(r.sub(f,p,t))0?Math.acos(i/u):-Math.acos(i/u),this.worldScale.x=u,this.worldScale.y=c/u}else if(n||r){var d=Math.sqrt(n*n+r*r);this.worldRotation=Phaser.Math.HALF_PI-(r>0?Math.acos(-n/d):-Math.acos(n/d)),this.worldScale.x=c/d,this.worldScale.y=d}else this.worldScale.x=0,this.worldScale.y=0;return this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.x=l.tx,this.worldPosition.y=l.ty,this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,l,h),this},preUpdate:function(){},generateTexture:function(t,e,i){var n=this.getLocalBounds(),r=new Phaser.RenderTexture(this.game,0|n.width,0|n.height,i,e,t);return s.DisplayObject._tempMatrix.tx=-n.x,s.DisplayObject._tempMatrix.ty=-n.y,r.render(this,s.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?s.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):s.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=0;this.texture&&this.texture.baseTexture&&s._enableMultiTextureToggle&&(e=this.texture.baseTexture.textureIndex);var i=new Phaser.RenderTexture(this.game,t.width,t.height,void 0,void 0,void 0,void 0,e);this._cachedSprite=new s.Sprite(i),this._cachedSprite.worldTransform=this.worldTransform}var n=this._filters;this._filters=null,this._cachedSprite.filters=n,s.DisplayObject._tempMatrix.tx=-t.x,s.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,s.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=n,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},s.DisplayObject.prototype.displayObjectUpdateTransform=s.DisplayObject.prototype.updateTransform,Object.defineProperties(s.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],i=0;i=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},s.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},s.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},s.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},s.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},s.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},s.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},s.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(t,i),n=0;na?u:a,d=d>h?d:h);var f=this._bounds;if(!p){var g=(f=new s.Rectangle).x,m=f.width+f.x,y=f.y,v=f.height+f.y,x=this.worldTransform,b=x.a,_=x.b,w=x.c,T=x.d,P=x.tx,C=x.ty,S=b*m+w*v+P,A=T*v+_*m+C,E=b*g+w*v+P,M=T*v+_*g+C,R=b*g+w*y+P,L=T*y+_*g+C,B=b*m+w*y+P,I=T*y+_*m+C;u=S,d=A,c=A,l=B<(l=R<(l=E<(l=S)?E:l)?R:l)?B:l,c=I<(c=L<(c=M(u=R>(u=E>u?E:u)?R:u)?B:u,d=I>(d=L>(d=M>d?M:d)?L:d)?I:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n(f=T>(f=_>(f=x>f?x:f)?_:f)?T:f)?C:f,g=S>(g=P>(g=w>(g=b>g?b:g)?w:g)?P:g)?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},s.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=Phaser.identityMatrix;for(var e=0;e= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}","}"];var n=s.compileProgram(t,this.vertexSrc||s.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(n),this.uSamplerArray=t.getUniformLocation(n,"uSamplerArray[0]"),this.projectionVector=t.getUniformLocation(n,"projectionVector"),this.offsetVector=t.getUniformLocation(n,"offsetVector"),this.dimensions=t.getUniformLocation(n,"dimensions"),this.aVertexPosition=t.getAttribLocation(n,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(n,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(n,"aColor"),this.aTextureIndex=t.getAttribLocation(n,"aTextureIndex");var r=[],o=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var a=0;a 0.0) gl_Position = vec4(0.0);"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);"," vTextureIndex = aTextureIndex;","}"],s.PixiFastShader=function(t){if(this._UID=Phaser._UID++,this.gl=t,this.program=null,s._enableMultiTextureToggle){var t=this.gl;this.MAX_TEXTURES=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(var e="\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n",i=1;i= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["// PixiFastShader Fragment Shader.","precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;","}"];this.vertexSrc=["// PixiFastShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","attribute float aTextureIndex;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;"," vColor = aColor;","}"],this.textureCount=0,this.init()},s.PixiFastShader.prototype.constructor=s.PixiFastShader,s.PixiFastShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["//StripShader Fragment Shader.","precision mediump float;","varying vec2 vTextureCoord;","varying float vTextureIndex;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord);","}"];this.vertexSrc=["//StripShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aTextureIndex;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;","}"],this.init()},s.StripShader.prototype.constructor=s.StripShader,s.StripShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t},i=this.gl,n=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),r=i.getParameter(i.MAX_TEXTURE_SIZE),o=this.game.cache._cache.image,a=null,h=0;h=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var a=i._uvs;if(a){var h,l,c,u,d=t.anchor.x,p=t.anchor.y;if(i.trim){var f=i.trim;h=(l=f.x-d*f.width)+i.crop.width,c=(u=f.y-p*f.height)+i.crop.height}else h=i.frame.width*(1-d),l=i.frame.width*-d,c=i.frame.height*(1-p),u=i.frame.height*-p;var g=this.currentBatchSize*this.vertexSize,m=(this.currentBatchSize,i.baseTexture.resolution),y=i.baseTexture.textureIndex,v=o.a/m,x=o.b/m,b=o.c/m,_=o.d/m,w=o.tx,T=o.ty,P=(i.crop.width,i.crop.height);if(i.rotated){var C=o.a,S=o.b,A=o.c,E=o.d,M=l,R=h;w=o.c*P+w,T=o.d*P+T,v=6.123233995736766e-17*C-A,x=6.123233995736766e-17*S-E,b=C+6.123233995736766e-17*A,_=S+6.123233995736766e-17*E,i._updateUvsInverted(),h=c,l=u,c=R,u=M}var L=this.colors,B=this.positions,I=t.tint,O=(I>>16)+(65280&I)+((255&I)<<16)+(255*t.worldAlpha<<24);this.renderSession.roundPixels?(B[g++]=v*l+b*u+w|0,B[g++]=_*u+x*l+T|0,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w|0,B[g++]=_*u+x*h+T|0,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w|0,B[g++]=_*c+x*h+T|0,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w|0,B[g++]=_*c+x*l+T|0,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y):(B[g++]=v*l+b*u+w,B[g++]=_*u+x*l+T,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w,B[g++]=_*u+x*h+T,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w,B[g++]=_*c+x*h+T,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w,B[g++]=_*c+x*l+T,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y),this.sprites[this.currentBatchSize++]=t}},s.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture,i=e.baseTexture,n=this.gl,r=t.texture.baseTexture.textureIndex;s.WebGLRenderer.textureArray[r]!=i&&(this.flush(),n.activeTexture(n.TEXTURE0+r),n.bindTexture(n.TEXTURE_2D,i._glTextures[n.id]),s.WebGLRenderer.textureArray[r]=i),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new s.TextureUvs);var o=t._uvs,a=e.baseTexture.width,h=e.baseTexture.height;t.tilePosition.x%=a*t.tileScaleOffset.x,t.tilePosition.y%=h*t.tileScaleOffset.y;var l=t.tilePosition.x/(a*t.tileScaleOffset.x),c=t.tilePosition.y/(h*t.tileScaleOffset.y),u=t.width/a/(t.tileScale.x*t.tileScaleOffset.x),d=t.height/h/(t.tileScale.y*t.tileScaleOffset.y);o.x0=0-l,o.y0=0-c,o.x1=1*u-l,o.y1=0-c,o.x2=1*u-l,o.y2=1*d-c,o.x3=0-l,o.y3=1*d-c;var p=t.tint,f=(p>>16)+(65280&p)+((255&p)<<16)+(255*t.worldAlpha<<24),g=this.positions,m=this.colors,y=t.width,v=t.height,x=t.anchor.x,b=t.anchor.y,_=y*(1-x),w=y*-x,T=v*(1-b),P=v*-b,C=this.currentBatchSize*this.vertexSize,S=e.baseTexture.resolution,A=t.worldTransform,E=A.a/S,M=A.b/S,R=A.c/S,L=A.d/S,B=A.tx,I=A.ty;g[C++]=E*w+R*P+B,g[C++]=L*P+M*w+I,g[C++]=o.x0,g[C++]=o.y0,m[C++]=f,g[C++]=r,g[C++]=E*_+R*P+B,g[C++]=L*P+M*_+I,g[C++]=o.x1,g[C++]=o.y1,m[C++]=f,g[C++]=r,g[C++]=E*_+R*T+B,g[C++]=L*T+M*_+I,g[C++]=o.x2,g[C++]=o.y2,m[C++]=f,g[C++]=r,g[C++]=E*w+R*T+B,g[C++]=L*T+M*w+I,g[C++]=o.x3,g[C++]=o.y3,m[C++]=f,g[C++]=r,this.sprites[this.currentBatchSize++]=t},s.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,t=this.defaultShader.shaders[e.id],e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var i=this.vertexSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,i,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,i,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,i,16),e.vertexAttribPointer(t.aTextureIndex,1,e.FLOAT,!1,i,20)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);var n=this.positions.subarray(0,this.currentBatchSize*this.vertexSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m0&&(v=!1),(f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){(t=(p=a).shaders[e.id])||((t=new s.PixiShader(e)).fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var x=this.renderSession.projection;e.uniform2f(t.projectionVector,x.x,x.y);var b=this.renderSession.offset;e.uniform2f(t.offsetVector,b.x,b.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},s.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},s.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},s.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},s.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},s.WebGLFastSpriteBatch=function(t){this.vertSize=11,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,i=6*this.maxSize;this.vertices=new Float32Array(e),this.indices=new Uint16Array(i),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var s=0,n=0;s=this.size&&this.flush()}},s.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]){if(this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}else this.renderSession.renderer.updateTexture(this.currentBaseTexture,t)}},s.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},s.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36),t.vertexAttribPointer(this.shader.aTextureIndex,1,t.FLOAT,!1,i,40)},s.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},s.WebGLFilterManager.prototype.constructor=s.WebGLFilterManager,s.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},s.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},s.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,i=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new s.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),i.x=a.width/2,i.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},s.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),i=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,i.width*this.renderSession.resolution,i.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=i.height,this.vertexArray[2]=i.width,this.vertexArray[3]=i.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=i.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=i.width/this.width,this.uvArray[5]=i.height/this.height,this.uvArray[6]=i.width/this.width,this.uvArray[7]=i.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,i,p,f),this.texturePool.push(n),e._glFilterTexture=null},s.WebGLFilterManager.prototype.applyFilterPass=function(t,e,i,n){var r=this.gl,o=t.shaders[r.id];o||((o=new s.PixiShader(r)).fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(!0),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,i/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},s.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},s.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e=0;t--){var e=this._glTextures[t],i=s.glContexts[t];i&&e&&i.deleteTexture(e)}this._glTextures.length=0,this.dirty()},s.BaseTexture.fromCanvas=function(t,e,i){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),i=i||1,new s.BaseTexture(t,e,i)},s.TextureSilentFail=!1,s.Texture=function(t,e,i,n){this.noFrame=!1,e||(this.noFrame=!0,e=new s.Rectangle(0,0,1,1)),t instanceof s.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=i||new s.Rectangle(0,0,1,1),this.rotated=!1,t.hasLoaded&&(this.noFrame&&(e=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},s.Texture.prototype.constructor=s.Texture,s.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},s.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},s.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,this.trim||!(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height))this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs();else{if(!s.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=!1}},s.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/i},s.Texture.prototype._updateUvsInverted=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.height)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.height)/e,this._uvs.y2=(t.y+t.width)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.width)/i},s.Texture.fromCanvas=function(t,e){var i=s.BaseTexture.fromCanvas(t,e);return new s.Texture(i)},s.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=s),exports.PIXI=s):"undefined"!=typeof define&&define.amd?define("PIXI",i.PIXI=s):i.PIXI=s,s}.call(this),function(){function t(t,e){this._scaleFactor=t,this._deltaMode=e,this.originalEvent=null}var e=this,i=i||{VERSION:"2.10.0",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,WEBGL_MULTI:4,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,PENDING_ATLAS:-1,HORIZONTAL:0,VERTICAL:1,LANDSCAPE:0,PORTRAIT:1,ANGLE_UP:270,ANGLE_DOWN:90,ANGLE_LEFT:180,ANGLE_RIGHT:0,ANGLE_NORTH_EAST:315,ANGLE_NORTH_WEST:225,ANGLE_SOUTH_EAST:45,ANGLE_SOUTH_WEST:135,TOP_LEFT:0,TOP_CENTER:1,TOP_RIGHT:2,LEFT_TOP:3,LEFT_CENTER:4,LEFT_BOTTOM:5,CENTER:6,RIGHT_TOP:7,RIGHT_CENTER:8,RIGHT_BOTTOM:9,BOTTOM_LEFT:10,BOTTOM_CENTER:11,BOTTOM_RIGHT:12,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},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{},_UID:0};if(Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Function.prototype.bind||(Function.prototype.bind=function(){var t=Array.prototype.slice;return function(e){function i(){var r=n.concat(t.call(arguments));s.apply(this instanceof i?this:e,r)}var s=this,n=t.call(arguments,1);if("function"!=typeof s)throw new TypeError;return i.prototype=function t(e){if(e&&(t.prototype=e),!(this instanceof t))return new t}(s.prototype),i}}()),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var s=arguments.length>=2?arguments[1]:void 0,n=0;n0&&100*Math.random()<=t},randomChoice:function(t,e){return Math.random()<.5?t:e},parseDimension:function(t,e){var i=0,s=0;return"string"==typeof t?"%"===t.substr(-1)?(i=parseInt(t,10)/100,s=0===e?window.innerWidth*i:window.innerHeight*i):s=parseInt(t,10):s=t,s},pad:function(t,e,i,s){if(void 0===e)var e=0;if(void 0===i)var i=" ";if(void 0===s)var s=3;var n=0;if(e+1>=(t=t.toString()).length)switch(s){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((n=e-t.length)/2),o=n-r;t=new Array(o+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t},isPlainObject:function(t){if("object"!=typeof t||t.nodeType||t===t.window)return!1;try{if(t.constructor&&!{}.hasOwnProperty.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},extend:function(){var t,e,s,n,r,o,a=arguments[0]||{},h=1,l=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[1]||{},h=2),l===h&&(a=this,--h);h0&&(this._radius=.5*s),this.type=i.CIRCLE},i.Circle.prototype={circumference:function(){return Math.PI*this._radius*2},random:function(t){void 0===t&&(t=new i.Point);var e=2*Math.PI*Math.random(),s=Math.random()+Math.random(),n=s>1?2-s:s,r=n*Math.cos(e),o=n*Math.sin(e);return t.x=this.x+r*this.radius,t.y=this.y+o*this.radius,t},getBounds:function(){return new i.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(t,e,i){return this.x=t,this.y=e,this._diameter=i,this._radius=.5*i,this},copyFrom:function(t){return this.setTo(t.x,t.y,t.diameter)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.diameter=this._diameter,t},distance:function(t,e){var s=i.Math.distance(this.x,this.y,t.x,t.y);return e?Math.round(s):s},clone:function(t){return void 0===t||null===t?t=new i.Circle(this.x,this.y,this.diameter):t.setTo(this.x,this.y,this.diameter),t},contains:function(t,e){return i.Circle.contains(this,t,e)},circumferencePoint:function(t,e,s){return i.Circle.circumferencePoint(this,t,e,s)},sample:function(t,e,s,n,r){t||(t=60),null==e&&(e=0),null==s&&(s=i.Math.PI2),r||(r=[]);for(var o=0;o0&&(this._diameter=t,this._radius=.5*t)}}),Object.defineProperty(i.Circle.prototype,"radius",{get:function(){return this._radius},set:function(t){t>0&&(this._radius=t,this._diameter=2*t)}}),Object.defineProperty(i.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(t){t>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-t}}),Object.defineProperty(i.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(t){tthis.y?(this._radius=0,this._diameter=0):this.radius=this.y-t}}),Object.defineProperty(i.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(t){t0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(i.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(t){!0===t&&this.setTo(0,0,0)}}),i.Circle.contains=function(t,e,i){return t.radius>0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius},i.Circle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.diameter===e.diameter},i.Circle.intersects=function(t,e){return i.Math.distance(t.x,t.y,e.x,e.y)<=t.radius+e.radius},i.Circle.circumferencePoint=function(t,e,s,n){return void 0===s&&(s=!1),void 0===n&&(n=new i.Point),!0===s&&(e=i.Math.degToRad(e)),n.x=t.x+t.radius*Math.cos(e),n.y=t.y+t.radius*Math.sin(e),n},i.Circle.intersectsRectangle=function(t,e){var i=Math.abs(t.x-e.x-e.halfWidth);if(i>e.halfWidth+t.radius)return!1;var s=Math.abs(t.y-e.y-e.halfHeight);if(s>e.halfHeight+t.radius)return!1;if(i<=e.halfWidth||s<=e.halfHeight)return!0;var n=i-e.halfWidth,r=s-e.halfHeight;return n*n+r*r<=t.radius*t.radius},i.Circle.intersectsLine=function(t,e,s){var n=t.x,r=t.y,o=(e.end.y-e.start.y)/(e.end.x-e.start.x),a=e.end.y-o*e.end.x,h=t.radius,l=t.radius,c=a+o*n,u=(n*(l*l)-o*(h*h)*(a-r)+h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),d=(n*(l*l)-o*(h*h)*(a-r)-h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),p=o*u+a,f=o*d+a,g=new i.Point(u,p),m=new i.Point(d,f),y=e.pointOnSegment(g.x,g.y,.01),v=e.pointOnSegment(m.x,m.y,.01);return y&&v?!s||[g,m]:y?!s||[g]:v?!s||[m]:!!s&&[]},PIXI.Circle=i.Circle,i.Ellipse=function(t,e,s,n){t=t||0,e=e||0,s=s||0,n=n||0,this.x=t,this.y=e,this.width=s,this.height=n,this.type=i.ELLIPSE},i.Ellipse.prototype={setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},getBounds:function(){return new i.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},clone:function(t){return void 0===t||null===t?t=new i.Ellipse(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t},contains:function(t,e){return i.Ellipse.contains(this,t,e)},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random()*Math.PI*2,s=Math.random();return t.x=Math.sqrt(s)*Math.cos(e),t.y=Math.sqrt(s)*Math.sin(e),t.x=this.x+t.x*this.width/2,t.y=this.y+t.y*this.height/2,t},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},i.Ellipse.prototype.constructor=i.Ellipse,Object.defineProperty(i.Ellipse.prototype,"left",{get:function(){return this.x},set:function(t){this.x=t}}),Object.defineProperty(i.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t=s&&t<=n&&e>=r&&e<=o},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random();return t.x=this.start.x+e*(this.end.x-this.start.x),t.y=this.start.y+e*(this.end.y-this.start.y),t},coordinatesOnLine:function(t,e){void 0===t&&(t=1),void 0===e&&(e=[]);var i=Math.round(this.start.x),s=Math.round(this.start.y),n=Math.round(this.end.x),r=Math.round(this.end.y),o=Math.abs(n-i),a=Math.abs(r-s),h=i-a&&(c-=a,i+=h),d=0&&g<=1&&m>=0&&m<=1?o:null}return o},i.Line.intersects=function(t,e,s,n){return i.Line.intersectsPoints(t.start,t.end,e.start,e.end,s,n)},i.Line.intersectsRectangle=function(t,e){if(0===t.length||e.empty)return!1;var i=t.start.x,s=t.start.y,n=t.end.x,r=t.end.y,o=e.x,a=e.y,h=e.right,l=e.bottom,c=0;if(i>=o&&i<=h&&s>=a&&s<=l||n>=o&&n<=h&&r>=a&&r<=l)return!0;if(i=o){if((c=s+(r-s)*(o-i)/(n-i))>a&&c<=l)return!0}else if(i>h&&n<=h&&(c=s+(r-s)*(h-i)/(n-i))>=a&&c<=l)return!0;if(s=a){if((c=i+(n-i)*(a-s)/(r-s))>=o&&c<=h)return!0}else if(s>l&&r<=l&&(c=i+(n-i)*(l-s)/(r-s))>=o&&c<=h)return!0;return!1},i.Line.intersectionWithRectangle=function(t,e,s){var n=i.Line.intersectionWithRectangle;s||(s=new i.Point),n.edges||(n.edges=[new i.Line,new i.Line,new i.Line,new i.Line]),n.edgeIntersection||(n.edgeIntersection=new i.Point);var r=n.edges,o=n.edgeIntersection.set(0),a=e.x,h=e.y,l=e.right,c=e.bottom,u=1/0;r[0].setTo(a,h,l,h),r[1].setTo(a,c,l,c),r[2].setTo(a,h,a,c),r[3].setTo(l,h,l,c);for(var d,p=0;d=r[p];p++)if(t.intersects(d,!0,o)){var f=t.start.distance(o);fs&&(this.x=s),this.yn&&(this.y=n),this},clone:function(t){return void 0===t||null===t?t=new i.Point(this.x,this.y):t.setTo(this.x,this.y),t},copyTo:function(t){return t.x=this.x,t.y=this.y,t},distance:function(t,e){return i.Point.distance(this,t,e)},equals:function(t){return t.x===this.x&&t.y===this.y},equalsXY:function(t,e){return this.x===t&&this.y===e},fuzzyEquals:function(t,e){return i.Point.fuzzyEquals(this,t,e)},fuzzyEqualsXY:function(t,e,s){return i.Point.fuzzyEqualsXY(this,t,e,s)},angle:function(t,e){return this.angleXY(t.x,t.y,e)},angleXY:function(t,e,s){var n=Math.atan2(e-this.y,t-this.x);return s?i.Math.radToDeg(n):n},atan:function(t){var e=Math.atan2(this.y,this.x);return t?i.Math.radToDeg(e):e},rotate:function(t,e,s,n,r){return i.Point.rotate(this,t,e,s,n,r)},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(t){return this.normalize().multiply(t,t)},normalize:function(){if(!this.isZero()){var t=this.getMagnitude();this.x/=t,this.y/=t}return this},limit:function(t){return this.getMagnitudeSq()>t*t&&this.setMagnitude(t),this},expand:function(t){return this.getMagnitudeSq()=0&&e.x-i<0)return-1;if(t.x-i<0&&e.x-i>=0)return 1;if(t.x-i==0&&e.x-i==0)return t.y-s>=0||e.y-s>=0?t.y>e.y?1:-1:e.y>t.y?1:-1;var n=(t.x-i)*-(e.y-s)-(e.x-i)*-(t.y-s);return n<0?-1:n>0?1:(t.x-i)*(t.x-i)+(t.y-s)*(t.y-s)>(e.x-i)*(e.x-i)+(e.y-s)*(e.y-s)?-1:1})},PIXI.Point=i.Point,i.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.flattened=!1,this.type=i.POLYGON},i.Polygon.prototype={toNumberArray:function(t){void 0===t&&(t=[]);for(var e=0;e0){Array.isArray(t)||(t=Array.prototype.slice.call(arguments));for(var e=Number.MAX_VALUE,i=0,s=t.length;i=this.right?this.width=0:this.width=this.right-t,this.x=t}}),Object.defineProperty(i.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(i.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(i.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(i.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(t){this.x=t-this.halfWidth}}),Object.defineProperty(i.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(t){this.y=t-this.halfHeight}}),Object.defineProperty(i.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(i.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(i.Rectangle.prototype,"top",{get:function(){return this.y},set:function(t){t>=this.bottom?(this.height=0,this.y=t):this.height=this.bottom-t}}),Object.defineProperty(i.Rectangle.prototype,"topLeft",{get:function(){return new i.Point(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"topRight",{get:function(){return new i.Point(this.x+this.width,this.y)},set:function(t){this.right=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),i.Rectangle.prototype.constructor=i.Rectangle,i.Rectangle.inflate=function(t,e,i){return t.x-=e,t.width+=2*e,t.y-=i,t.height+=2*i,t},i.Rectangle.inflatePoint=function(t,e){return i.Rectangle.inflate(t,e.x,e.y)},i.Rectangle.size=function(t,e){return void 0===e||null===e?e=new i.Point(t.width,t.height):e.setTo(t.width,t.height),e},i.Rectangle.clone=function(t,e){return void 0===e||null===e?e=new i.Rectangle(t.x,t.y,t.width,t.height):e.setTo(t.x,t.y,t.width,t.height),e},i.Rectangle.createFromBounds=function(t,e){return void 0!==e&&null!==e||(e=new i.Rectangle(t.x,t.y,t.width,t.height)),e.copyFromBounds(t)},i.Rectangle.contains=function(t,e,i){return!(t.width<=0||t.height<=0)&&(e>=t.x&&e=t.y&&i=t&&n=e&&re.volume)&&(t.x>=e.x&&t.y>=e.y&&t.righte.right||t.y>e.bottom)},i.Rectangle.intersectsRaw=function(t,e,i,s,n,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||ns&&(s=t.x),t.xr&&(r=t.y),t.y=i&&t<=i+this.width){var s=this.y;if(e>=s&&e<=s+this.height)return!0}return!1}},i.RoundedRectangle.prototype.constructor=i.RoundedRectangle,PIXI.RoundedRectangle=i.RoundedRectangle,i.Camera=function(t,e,s,n,r,o){this.game=t,this.world=t.world,this.id=0,this.view=new i.Rectangle(s,n,r,o),this.bounds=new i.Rectangle(s,n,r,o),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this.lerp=new i.Point(1,1),this.onShakeComplete=new i.Signal,this.onFlashComplete=new i.Signal,this.onFadeComplete=new i.Signal,this.fx=null,this._targetPosition=new i.Point,this._edge=0,this._position=new i.Point,this._shake={intensity:0,duration:0,horizontal:!1,vertical:!1,shakeBounds:!0,x:0,y:0},this._fxDuration=0,this._fxType=0,this._fixedView=new i.Rectangle},i.Camera.FOLLOW_LOCKON=0,i.Camera.FOLLOW_PLATFORMER=1,i.Camera.FOLLOW_TOPDOWN=2,i.Camera.FOLLOW_TOPDOWN_TIGHT=3,i.Camera.SHAKE_BOTH=4,i.Camera.SHAKE_HORIZONTAL=5,i.Camera.SHAKE_VERTICAL=6,i.Camera.ENABLE_FX=!0,i.Camera.prototype={boot:function(){this.displayObject=this.game.world,this.scale=this.game.world.scale,this.game.camera=this,i.Graphics&&i.Camera.ENABLE_FX&&(this.fx=new i.Graphics(this.game),this.game.stage.addChild(this.fx))},preUpdate:function(){this.totalInView=0},follow:function(t,e,s,n){void 0===e&&(e=i.Camera.FOLLOW_LOCKON),void 0===s&&(s=1),void 0===n&&(n=1),this.target=t,this.lerp.set(s,n);var r;switch(e){case i.Camera.FOLLOW_PLATFORMER:var o=this.width/8,a=this.height/3;this.deadzone=new i.Rectangle((this.width-o)/2,(this.height-a)/2-.25*a,o,a);break;case i.Camera.FOLLOW_TOPDOWN:r=Math.max(this.width,this.height)/4,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_TOPDOWN_TIGHT:r=Math.max(this.width,this.height)/8,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_LOCKON:default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(t){this.setPosition(Math.round(t.x-this.view.halfWidth),Math.round(t.y-this.view.halfHeight))},focusOnXY:function(t,e){this.setPosition(Math.round(t-this.view.halfWidth),Math.round(e-this.view.halfHeight))},shake:function(t,e,s,n,r){return void 0===t&&(t=.05),void 0===e&&(e=500),void 0===s&&(s=!0),void 0===n&&(n=i.Camera.SHAKE_BOTH),void 0===r&&(r=!0),!(!s&&this._shake.duration>0)&&(this._shake.intensity=t,this._shake.duration=e,this._shake.shakeBounds=r,this._shake.x=0,this._shake.y=0,this._shake.horizontal=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_HORIZONTAL,this._shake.vertical=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_VERTICAL,!0)},flash:function(t,e,i,s){return void 0===t&&(t=16777215),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=1,this._fxDuration=e,this._fxType=0,!0)},fade:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=0,this._fxDuration=e,this._fxType=1,!0)},update:function(){this._fxDuration>0&&this.updateFX(),this._shake.duration>0&&this.updateShake(),this.bounds&&this.checkBounds(),this.roundPx&&(this.view.floor(),this._shake.x=Math.floor(this._shake.x),this._shake.y=Math.floor(this._shake.y)),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateFX:function(){0===this._fxType?(this.fx.alpha-=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha<=0&&(this._fxDuration=0,this.fx.alpha=0,this.onFlashComplete.dispatch())):(this.fx.alpha+=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha>=1&&(this._fxDuration=0,this.fx.alpha=1,this.onFadeComplete.dispatch()))},updateShake:function(){this._shake.duration-=this.game.time.elapsedMS,this._shake.duration<=0?(this.onShakeComplete.dispatch(),this._shake.x=0,this._shake.y=0):(this._shake.horizontal&&(this._shake.x=this.game.rnd.frac()*this._shake.intensity*this.view.width*2-this._shake.intensity*this.view.width),this._shake.vertical&&(this._shake.y=this.game.rnd.frac()*this._shake.intensity*this.view.height*2-this._shake.intensity*this.view.height))},updateTarget:function(){this._targetPosition.x=this.view.x+this.target.worldPosition.x,this._targetPosition.y=this.view.y+this.target.worldPosition.y,this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edgethis.deadzone.right&&(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.right,this.lerp.x)),this._edge=this._targetPosition.y-this.view.y,this._edgethis.deadzone.bottom&&(this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.bottom,this.lerp.y))):(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.view.halfWidth,this.lerp.x),this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.view.halfHeight,this.lerp.y)),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},setBoundsToWorld:function(){this.bounds&&this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1;var t=this.view.x+this._shake.x,e=this.view.right+this._shake.x,i=this.view.y+this._shake.y,s=this.view.bottom+this._shake.y;t<=this.bounds.x*this.scale.x?(this.atLimit.x=!0,this.view.x=this.bounds.x*this.scale.x,this._shake.shakeBounds||(this._shake.x=0)):e>=this.bounds.right*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.right*this.scale.x-this.width,this._shake.shakeBounds||(this._shake.x=0)),i<=this.bounds.top*this.scale.y?(this.atLimit.y=!0,this.view.y=this.bounds.top*this.scale.y,this._shake.shakeBounds||(this._shake.y=0)):s>=this.bounds.bottom*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom*this.scale.y-this.height,this._shake.shakeBounds||(this._shake.y=0))},setPosition:function(t,e){this.view.x=t,this.view.y=e,this.bounds&&this.checkBounds()},setSize:function(t,e){this.view.width=t,this.view.height=e},reset:function(){this.target=null,this.view.x=0,this.view.y=0,this._shake.duration=0,this._shake.x=0,this._shake.y=0,this.resetFX()},resetFX:function(){this.fx&&(this.fx.clear(),this.fx.alpha=0),this._fxDuration=0}},i.Camera.prototype.constructor=i.Camera,Object.defineProperty(i.Camera.prototype,"x",{get:function(){return this.view.x},set:function(t){this.view.x=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"y",{get:function(){return this.view.y},set:function(t){this.view.y=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"position",{get:function(){return this._position.set(this.view.x,this.view.y),this._position},set:function(t){void 0!==t.x&&(this.view.x=t.x),void 0!==t.y&&(this.view.y=t.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"width",{get:function(){return this.view.width},set:function(t){this.view.width=t}}),Object.defineProperty(i.Camera.prototype,"height",{get:function(){return this.view.height},set:function(t){this.view.height=t}}),Object.defineProperty(i.Camera.prototype,"shakeIntensity",{get:function(){return this._shake.intensity},set:function(t){this._shake.intensity=t}}),Object.defineProperty(i.Camera.prototype,"fixedView",{get:function(){return this._fixedView.setTo(0,0,this.view.width,this.view.height),this._fixedView}}),i.State=function(){this.game=null,this.key="",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.state=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},i.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},i.State.prototype.constructor=i.State,i.StateManager=function(t,e){this.game=t,this.states={},this._pendingState=null,void 0!==e&&null!==e&&(this._pendingState=e),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new i.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},i.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(t,e,s){void 0===s&&(s=!1);var n;return e instanceof i.State?n=e:"object"==typeof e?(n=e).game=this.game:"function"==typeof e&&(n=new e(this.game)),this.states[t]=n,s&&(this.game.isBooted?this.start(t):this._pendingState=t),n},remove:function(t){this.current===t&&(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.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[t]},start:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1),this.checkState(t)&&(this._pendingState=t,this._clearWorld=e,this._clearCache=i,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!1),this._pendingState=this.current,this._clearWorld=t,this._clearCache=e,arguments.length>2&&(this._args=Array.prototype.slice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var t=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,t),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache&&this.game.cache.destroy()))},checkState:function(t){var e=this.states[t];return e?!!(e.preload||e.create||e.update||e.render)||(console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"),!1):(console.warn("Phaser.StateManager - No state found with the key: "+t),!1)},link:function(t){var e=this.states[t];e.game=this.game,e.add=this.game.add,e.make=this.game.make,e.camera=this.game.camera,e.cache=this.game.cache,e.input=this.game.input,e.load=this.game.load,e.math=this.game.math,e.sound=this.game.sound,e.scale=this.game.scale,e.state=this,e.stage=this.game.stage,e.time=this.game.time,e.tweens=this.game.tweens,e.world=this.game.world,e.particles=this.game.particles,e.rnd=this.game.rnd,e.physics=this.game.physics,e.key=t},unlink:function(t){var e=this.states[t];e&&(e.game=null,e.add=null,e.make=null,e.camera=null,e.cache=null,e.input=null,e.load=null,e.math=null,e.sound=null,e.scale=null,e.state=null,e.stage=null,e.time=null,e.tweens=null,e.world=null,e.particles=null,e.rnd=null,e.physics=null)},setCurrentState:function(t){var e=this.states[t];this.callbackContext=e,this.link(t),this.onInitCallback=e.init||this.dummy,this.onPreloadCallback=e.preload||null,this.onLoadRenderCallback=e.loadRender||null,this.onLoadUpdateCallback=e.loadUpdate||null,this.onCreateCallback=e.create||null,this.onUpdateCallback=e.update||null,this.onPreRenderCallback=e.preRender||null,this.onRenderCallback=e.render||null,this.onResizeCallback=e.resize||null,this.onPausedCallback=e.paused||null,this.onResumedCallback=e.resumed||null,this.onPauseUpdateCallback=e.pauseUpdate||null,this.onShutDownCallback=e.shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=t,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),t===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){!1===this._created&&this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game),!1===this._created&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(t){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,t)},resize:function(t,e){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,t,e)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===i.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this._clearWorld=!0,this._clearCache=!0,this.clearCurrentState(),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,this.current=""}},i.StateManager.prototype.constructor=i.StateManager,Object.defineProperty(i.StateManager.prototype,"created",{get:function(){return this._created}}),i.Signal=function(){},i.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!1,validateListener:function(t,e){if("function"!=typeof t)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",e))},_registerListener:function(t,e,s,n,r){var o,a=this._indexOfListener(t,s);if(-1!==a){if((o=this._bindings[a]).isOnce()!==e)throw new Error("You cannot add"+(e?"":"Once")+"() then add"+(e?"Once":"")+"() the same listener without removing the relationship first.")}else o=new i.SignalBinding(this,t,e,s,n,r),this._addBinding(o);return this.memorize&&this._prevParams&&o.execute(this._prevParams),o},_addBinding:function(t){this._bindings||(this._bindings=[]);var e=this._bindings.length;do{e--}while(this._bindings[e]&&t._priority<=this._bindings[e]._priority);this._bindings.splice(e+1,0,t)},_indexOfListener:function(t,e){if(!this._bindings)return-1;void 0===e&&(e=null);for(var i,s=this._bindings.length;s--;)if((i=this._bindings[s])._listener===t&&i.context===e)return s;return-1},has:function(t,e){return-1!==this._indexOfListener(t,e)},add:function(t,e,i){this.validateListener(t,"add");var s=[];if(arguments.length>3)for(var n=3;n3)for(var n=3;n=this.children.length?-1:this.getChildAt(t)},i.Group.prototype.create=function(t,e,i,s,n,r){void 0===n&&(n=!0);var o=new this.classType(this.game,t,e,i,s);return o.exists=n,o.visible=n,o.alive=n,this.add(o,!1,r)},i.Group.prototype.createMultiple=function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=!1),Array.isArray(e)||(e=[e]),Array.isArray(i)||(i=[i]);var o=this,a=[];return e.forEach(function(e){i.forEach(function(i){for(var h=0;hthis.children.length||-1===t&&-1===e)return!1;for(var a=new i.Rectangle(0,0,s,n),h=t*s,l=e*n,c=o;cthis.children.length-1&&(t=0),this.cursor)return this.cursorIndex=t,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.next=function(){if(this.cursor)return this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.previous=function(){if(this.cursor)return 0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.swap=function(t,e){this.swapChildren(t,e),this.updateZ()},i.Group.prototype.bringToTop=function(t){return t.parent===this&&this.getIndex(t)0&&(this.remove(t,!1,!0),this.addAt(t,0,!0)),t},i.Group.prototype.moveUp=function(t){if(t.parent===this&&this.getIndex(t)0){var e=this.getIndex(t),i=this.getAt(e-1);i&&this.swap(t,i)}return t},i.Group.prototype.xy=function(t,e,i){if(t<0||t>this.children.length)return-1;this.getChildAt(t).x=e,this.getChildAt(t).y=i},i.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},i.Group.prototype.getIndex=function(t){return this.children.indexOf(t)},i.Group.prototype.getByName=function(t){for(var e=0;e0))return!1;var r=e.length;return 1===r?0===s?t[e[0]]=i:1===s?t[e[0]]+=i:2===s?t[e[0]]-=i:3===s?t[e[0]]*=i:4===s&&(t[e[0]]/=i):2===r?0===s?t[e[0]][e[1]]=i:1===s?t[e[0]][e[1]]+=i:2===s?t[e[0]][e[1]]-=i:3===s?t[e[0]][e[1]]*=i:4===s&&(t[e[0]][e[1]]/=i):3===r?0===s?t[e[0]][e[1]][e[2]]=i:1===s?t[e[0]][e[1]][e[2]]+=i:2===s?t[e[0]][e[1]][e[2]]-=i:3===s?t[e[0]][e[1]][e[2]]*=i:4===s&&(t[e[0]][e[1]][e[2]]/=i):4===r&&(0===s?t[e[0]][e[1]][e[2]][e[3]]=i:1===s?t[e[0]][e[1]][e[2]][e[3]]+=i:2===s?t[e[0]][e[1]][e[2]][e[3]]-=i:3===s?t[e[0]][e[1]][e[2]][e[3]]*=i:4===s&&(t[e[0]][e[1]][e[2]][e[3]]/=i)),!0},i.Group.prototype.checkProperty=function(t,e,s,n){if(void 0===n&&(n=!1),this!==t.parent)return!1;var r=i.Utils.getProperty(t,e);return!(void 0===r&&n||r!==s)},i.Group.prototype.set=function(t,e,i,s,n,r,o){if(void 0===o&&(o=!1),e=e.split("."),void 0===s&&(s=!1),void 0===n&&(n=!1),(!1===s||s&&t.alive)&&(!1===n||n&&t.visible))return this.setProperty(t,e,i,r,o)},i.Group.prototype.setAll=function(t,e,i,s,n,r){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===r&&(r=!1),t=t.split("."),n=n||0;for(var o=0;o2){i=[];for(s=2;s2){n=[];for(a=2;a=e&&(t=e-1);var i=this.children[t];this.updateOnlyExistingChildren&&!i.exists||i.update()}},i.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y);for(var t=0;t2){s=[null];for(var n=2;n2){s=[null];for(var n=2;n2){s=[null];for(var n=2;ne[this._sortProperty]?1:t.ze[this._sortProperty]?-1:0},i.Group.prototype.iterate=function(t,e,s,n,r,o){if(0===this.children.length){if(s===i.Group.RETURN_TOTAL)return 0;if(s===i.Group.RETURN_ALL)return[]}var a=0;if(s===i.Group.RETURN_ALL)var h=[];for(var l=0;l0)return this.children[this.children.length-1]},i.Group.prototype.getBottom=function(){if(this.children.length>0)return this.children[0]},i.Group.prototype.getClosestTo=function(t,e,s){for(var n=Number.MAX_VALUE,r=0,o=null,a=0;an&&(!e||e.call(s,h,r))&&(n=r,o=h)}return o},i.Group.prototype.count=function(t,e){return this.iterate(t,e,i.Group.RETURN_TOTAL)},i.Group.prototype.countLiving=function(){return this.count("alive",!0)},i.Group.prototype.countDead=function(){return this.count("alive",!1)},i.Group.prototype.getRandom=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.children.length),0===e?null:i.ArrayUtils.getRandomItem(this.children,t,e)},i.Group.prototype.getRandomExists=function(t,e){var i=this.getAll("exists",!0,t,e);return this.game.rnd.pick(i)},i.Group.prototype.getAll=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=this.children.length);for(var n=[],r=i;r0&&t instanceof i.Group){do{t.add(this.children[0],e)}while(this.children.length>0);this.hash=[],this.cursor=null}return t},i.Group.prototype.removeAll=function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),0!==this.children.length){do{!e&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var s=this.removeChild(this.children[0]);this.removeFromHash(s),t&&s&&s.destroy(!0,i)}while(this.children.length>0);this.hash=[],this.cursor=null}},i.Group.prototype.removeBetween=function(t,e,i,s){if(void 0===e&&(e=this.children.length-1),void 0===i&&(i=!1),void 0===s&&(s=!1),0!==this.children.length){if(t>e||t<0||e>this.children.length)return!1;for(var n=e;n>=t;){!s&&this.children[n].events&&this.children[n].events.onRemovedFromGroup$dispatch(this.children[n],this);var r=this.removeChild(this.children[n]);this.removeFromHash(r),i&&r&&r.destroy(!0),this.cursor===this.children[n]&&(this.cursor=null),n--}this.updateZ()}},i.Group.prototype.scatter=function(t,e){null==t&&(t=this.game.world.bounds),this.forEach(function(e){e.position.set(t.randomX,t.randomY)},null,e)},i.Group.prototype.shuffle=function(){i.ArrayUtils.shuffle(this.children),this.updateZ()},i.Group.prototype.destroy=function(t,e){null===this.game||this.ignoreDestroy||(void 0===t&&(t=!0),void 0===e&&(e=!1),this.onDestroy.dispatch(this,t,e),this.removeAll(t),this.cursor=null,this.filters=null,this.pendingDestroy=!1,e||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(i.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,i.Group.RETURN_TOTAL)}}),Object.defineProperty(i.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(i.Group.prototype,"angle",{get:function(){return i.Math.radToDeg(this.rotation)},set:function(t){this.rotation=i.Math.degToRad(t)}}),Object.defineProperty(i.Group.prototype,"centerX",{get:function(){return this.getBounds(this.parent).centerX},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.halfWidth}}),Object.defineProperty(i.Group.prototype,"centerY",{get:function(){return this.getBounds(this.parent).centerY},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.halfHeight}}),Object.defineProperty(i.Group.prototype,"left",{get:function(){return this.getBounds(this.parent).left},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i}}),Object.defineProperty(i.Group.prototype,"right",{get:function(){return this.getBounds(this.parent).right},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.width}}),Object.defineProperty(i.Group.prototype,"top",{get:function(){return this.getBounds(this.parent).top},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i}}),Object.defineProperty(i.Group.prototype,"bottom",{get:function(){return this.getBounds(this.parent).bottom},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.height}}),i.World=function(t){i.Group.call(this,t,null,"__world",!1),this.bounds=new i.Rectangle(0,0,t.width,t.height),this.camera=null,this._definedSize=!1,this._width=t.width,this._height=t.height,this.game.state.onStateChange.add(this.stateChange,this)},i.World.prototype=Object.create(i.Group.prototype),i.World.prototype.constructor=i.World,i.World.prototype.boot=function(){this.camera=new i.Camera(this.game,0,0,0,this.game.width,this.game.height),this.game.stage.addChild(this),this.camera.boot()},i.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},i.World.prototype.setBounds=function(t,e,i,s){this._definedSize=!0,this._width=i,this._height=s,this.bounds.setTo(t,e,i,s),this.x=t,this.y=e,this.camera.bounds&&this.camera.bounds.setTo(t,e,Math.max(i,this.game.width),Math.max(s,this.game.height)),this.game.physics.setBoundsToWorld()},i.World.prototype.resize=function(t,e){this._definedSize&&(tthis.bounds.right&&(t.x=this.bounds.left)),n&&(t.y+t._currentBounds.heightthis.bounds.bottom&&(t.y=this.bounds.top))):(s&&t.x+ethis.bounds.right&&(t.x=this.bounds.left-e),n&&t.y+ethis.bounds.bottom&&(t.y=this.bounds.top-e))},i.World.prototype.wrapAll=function(t,e,i,s,n,r){t.forEach(this.wrap,this,e,i,s,n,r)},Object.defineProperty(i.World.prototype,"width",{get:function(){return this.bounds.width},set:function(t){t1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.dropFrames?this.rendersThisFrame=0:(this.updateRender(this.time.slowMotion*this.time.desiredFps),this.rendersThisFrame=1);else{var e=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*e,this.time.elapsed),0);var i=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/e),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame)),this.forceSingleRender?this.rendersThisFrame=1:this.rendersThisFrame=Math.min(1,this.updatesThisFrame);this._deltaTime>=e&&(this._deltaTime-=e,this.currentUpdateID=i,this.updateLogic(this.time.desiredFpsMult),i++,!this.forceSingleUpdate||1!==i);)this.time.refresh();i>this._lastCount?this._spiraling++:i0&&this.updateRender(this._deltaTime/e)}}},updateLogic:function(t){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(t),this.debug.preUpdate(),this.input.pauseUpdate()):(this.stepping&&(this.pendingStep=!0),this.time.countUpdate(),this.scale.preUpdate(),this.debug.preUpdate(),this.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(t),this.plugins.preUpdate(t),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(),this.sound.update(),this.input.update(),this.physics.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate()),this.stage.updateTransform()},updateRender:function(t){this.lockRender||(this.time.countRender(),this.state.preRender(t),this.renderType!==i.HEADLESS&&(this.renderer.render(this.stage),this.plugins.render(t),this.state.render(t)),this.plugins.postRender(t))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.debug.destroy&&this.debug.destroy(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.plugins.destroy(),this.debug=null,this.state=null,this.sound=null,this.scale=null,this.stage=null,this.input=null,this.physics=null,this.plugins=null,this.cache=null,this.load=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),i.Canvas.removeFromDOM(this.canvas),PIXI.defaultRenderer=null,i.GAMES[this.id]=null},gamePaused:function(t){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.muteOnPause&&this.sound.setMute(),this.onPause.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(t){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.muteOnPause&&this.sound.unsetMute(),this.onResume.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(t){this.onBlur.dispatch(t),this.stage.disableVisibilityChange||this.gamePaused(t)},focusGain:function(t){this.onFocus.dispatch(t),this.stage.disableVisibilityChange||this.gameResumed(t)}},i.Game.prototype.constructor=i.Game,Object.defineProperty(i.Game.prototype,"paused",{get:function(){return this._paused},set:function(t){!0===t?(!1===this._paused&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),i.Input=function(t){this.game=t,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.customCandidateHandler=null,this.customCandidateHandlerContext=null,this.pollRate=0,this.enabled=!0,this.multiInputOverride=i.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.touchLockCallbacks=[],this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new i.ArraySet,this._localPoint=new i.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},i.Input.MOUSE_OVERRIDES_TOUCH=0,i.Input.TOUCH_OVERRIDES_MOUSE=1,i.Input.MOUSE_TOUCH_COMBINE=2,i.Input.MAX_POINTERS=10,i.Input.prototype={boot:function(){this.mousePointer=new i.Pointer(this.game,0,i.PointerMode.CURSOR),this.addPointer(),this.addPointer(),this.mouse=new i.Mouse(this.game),this.touch=new i.Touch(this.game),this.mspointer=new i.MSPointer(this.game),i.Keyboard&&(this.keyboard=new i.Keyboard(this.game)),i.Gamepad&&(this.gamepad=new i.Gamepad(this.game)),this.onDown=new i.Signal,this.onUp=new i.Signal,this.onTap=new i.Signal,this.onHold=new i.Signal,this.scale=new i.Point(1,1),this.speed=new i.Point,this.position=new i.Point,this._oldPosition=new i.Point,this.circle=new i.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=i.CanvasPool.create(this,1,1),this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.game.device.mspointer||this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var t=this;this._onClickTrampoline=function(e){t.onClickTrampoline(e)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],i.CanvasPool.remove(this),this.game.canvas.removeEventListener("click",this._onClickTrampoline)},setInteractiveCandidateHandler:function(t,e){this.customCandidateHandler=t,this.customCandidateHandlerContext=e},addMoveCallback:function(t,e){this.moveCallbacks.push({callback:t,context:e})},addTouchLockCallback:function(t,e,i){void 0===i&&(i=!1),this.touchLockCallbacks.push({callback:t,context:e,onEnd:i})},removeTouchLockCallback:function(t,e){for(var i=this.touchLockCallbacks.length;i--;)if(this.touchLockCallbacks[i].callback===t&&this.touchLockCallbacks[i].context===e)return this.touchLockCallbacks.splice(i,1),!0;return!1},executeTouchLockCallbacks:function(t,e){for(var i=this.touchLockCallbacks.length;i--;){var s=this.touchLockCallbacks[i];s.onEnd===t&&s.callback.call(s.context,this,e)&&this.touchLockCallbacks.splice(i,1)}},deleteMoveCallback:function(t,e){for(var i=this.moveCallbacks.length;i--;)if(this.moveCallbacks[i].callback===t&&this.moveCallbacks[i].context===e)return void this.moveCallbacks.splice(i,1)},addPointer:function(){if(this.pointers.length>=i.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+i.Input.MAX_POINTERS+" pointers reached."),null;var t=this.pointers.length+1,e=new i.Pointer(this.game,t,i.PointerMode.CONTACT);return this.pointers.push(e),this["pointer"+t]=e,e},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(t);if(!this.pointer2.active)return this.pointer2.start(t);for(var e=2;e0;i++)this.pointers[i].active&&e--;return t-e},getPointer:function(t){void 0===t&&(t=!1);for(var e=0;e=o&&this.game.camera.x+e.x=a&&this.game.camera.y+e.y=o&&this._localPoint.x=a&&this._localPoint.y=o&&this._localPoint.x=a&&this._localPoint.y0&&this._pollCounterthis.game.time.time},justReleased:function(t){return t=t||250,this.isUp&&this.timeUp+t>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},i.DeviceButton.prototype.constructor=i.DeviceButton,Object.defineProperty(i.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),i.Pointer=function(t,e,s){this.game=t,this.id=e,this.type=i.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.pointerMode=s||i.PointerMode.CURSOR|i.PointerMode.CONTACT,this.target=null,this.button=null,this.leftButton=new i.DeviceButton(this,i.Pointer.LEFT_BUTTON),this.middleButton=new i.DeviceButton(this,i.Pointer.MIDDLE_BUTTON),this.rightButton=new i.DeviceButton(this,i.Pointer.RIGHT_BUTTON),this.backButton=new i.DeviceButton(this,i.Pointer.BACK_BUTTON),this.forwardButton=new i.DeviceButton(this,i.Pointer.FORWARD_BUTTON),this.eraserButton=new i.DeviceButton(this,i.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===e,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.interactiveCandidates=[],this.active=!1,this.dirty=!1,this.position=new i.Point,this.positionDown=new i.Point,this.positionUp=new i.Point,this.circle=new i.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},i.Pointer.NO_BUTTON=0,i.Pointer.LEFT_BUTTON=1,i.Pointer.RIGHT_BUTTON=2,i.Pointer.MIDDLE_BUTTON=4,i.Pointer.BACK_BUTTON=8,i.Pointer.FORWARD_BUTTON=16,i.Pointer.ERASER_BUTTON=32,i.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.start(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.start(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.start(e),t===i.Mouse.BACK_BUTTON&&this.backButton.start(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.start(e)},processButtonsUp:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.stop(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.stop(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(e),t===i.Mouse.BACK_BUTTON&&this.backButton.stop(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(e)},processButtonsUpDown:function(t,e){var s="down"===e.type.toLowerCase().substr(-4),n="move"===e.type.toLowerCase().substr(-4);void 0!==t?(s&&1===t&&e.ctrlKey&&(t=2),this.leftButton.startStop(i.Pointer.LEFT_BUTTON&t,e),this.rightButton.startStop(i.Pointer.RIGHT_BUTTON&t,e),this.middleButton.startStop(i.Pointer.MIDDLE_BUTTON&t,e),this.backButton.startStop(i.Pointer.BACK_BUTTON&t,e),this.forwardButton.startStop(i.Pointer.FORWARD_BUTTON&t,e),this.eraserButton.startStop(i.Pointer.ERASER_BUTTON&t,e)):void 0!==e.button?s&&e.ctrlKey&&0===e.button?this.rightButton.start(e):s?this.processButtonsDown(e.button,e):n||this.processButtonsUp(e.button,e):s?e.ctrlKey?this.rightButton.start(e):this.leftButton.start(e):(this.leftButton.stop(e),this.rightButton.stop(e))},updateButtons:function(t){this.button=t.button,this.processButtonsUpDown(t.buttons,t),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(t){var e=this.game.input;return t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.isMouse?this.updateButtons(t):(this.isDown=!0,this.isUp=!1),this.active=!0,this.withinGame=!0,this.dirty=!1,this._history=[],this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(t,!0),this.positionDown.setTo(this.x,this.y),(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.x=this.x,e.y=this.y,e.position.setTo(this.x,this.y),e.onDown.dispatch(this,t),e.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){var t=this.game.input;this.active&&(this.dirty&&(t.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),!1===this._holdSent&&this.duration>=t.holdRate&&((t.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||t.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||t.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===t.totalActivePointers)&&t.onHold.dispatch(this),this._holdSent=!0),t.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+t.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>t.recordLimit&&this._history.shift()))},move:function(t,e){var s=this.game.input;if(!s.pollLocked){void 0===e&&(e=!1),void 0!==t.button&&(this.button=t.button),this.isMouse&&this.updateButtons(t),this.clientX=t.clientX,this.clientY=t.clientY,this.pageX=t.pageX,this.pageY=t.pageY,this.screenX=t.screenX,this.screenY=t.screenY,this.isMouse&&s.mouse.locked&&!e&&(this.rawMovementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.rawMovementY=t.movementY||t.mozMovementY||t.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*s.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*s.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(s.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||s.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||s.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===s.totalActivePointers)&&(s.activePointer=this,s.x=this.x,s.y=this.y,s.position.setTo(s.x,s.y),s.circle.x=s.x,s.circle.y=s.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY);for(var n=s.moveCallbacks.length;n--;)s.moveCallbacks[n].callback.call(s.moveCallbacks[n].context,this,this.x,this.y,e);return null===this.targetObject||this.game.paused&&!this.targetObject.noPause||!0!==this.targetObject.isDragged?s.interactiveItems.total>0&&this.processInteractiveObjects(e):!1===this.targetObject.update(this)&&(this.targetObject=null),this}},processInteractiveObjects:function(t){var e=0,i=-1,s=null,n=this.game.input.interactiveItems.first;for(this.interactiveCandidates=[];n;)n.checked=!1,!n.validForInput(i,e,!1)||this.game.paused&&!n.sprite.noPause||(n.checked=!0,(t&&n.checkPointerDown(this,!0)||!t&&n.checkPointerOver(this,!0))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n))),n=this.game.input.interactiveItems.next;for(n=this.game.input.interactiveItems.first;n;)!n.checked&&n.validForInput(i,e,!0)&&(t&&n.checkPointerDown(this,!1)||!t&&n.checkPointerOver(this,!1))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n)),n=this.game.input.interactiveItems.next;return this.game.input.customCandidateHandler&&(s=this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext,this,this.interactiveCandidates,s)),this.swapTarget(s,!1),null!==this.targetObject},swapTarget:function(t,e){void 0===e&&(e=!1),null===t?this.targetObject&&(this.targetObject._pointerOutHandler(this,e),this.targetObject=null):null===this.targetObject?(this.targetObject=t,t._pointerOverHandler(this,e)):this.targetObject===t?!1===t.update(this)&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this,e),this.targetObject=t,this.targetObject._pointerOverHandler(this,e))},leave:function(t){this.withinGame=!1,this.move(t,!1)},stop:function(t){var e=this.game.input;{if(!this._stateReset||!this.withinGame)return this.timeUp=this.game.time.time,(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.onUp.dispatch(this,t),this.duration>=0&&this.duration<=e.tapRate&&(this.timeUp-this.previousTapTime0&&(this.active=!1),this.withinGame=this.game.scale.bounds.contains(t.pageX,t.pageY),this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),!1===this.isMouse&&e.currentPointers--,e.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this;t.preventDefault()}},justPressed:function(t){return t=t||this.game.input.justPressedRate,!0===this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||this.game.input.justReleasedRate,this.isUp&&this.timeUp+t>this.game.time.time},addClickTrampoline:function(t,e,i,s){if(this.isDown){for(var n=this._clickTrampolines=this._clickTrampolines||[],r=0;rt||this.priorityID===t&&this.sprite.renderOrderID>e))},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(t){return t=t||0,this._pointerData[t].x},pointerY:function(t){return t=t||0,this._pointerData[t].y},pointerDown:function(t){return t=t||0,this._pointerData[t].isDown},pointerUp:function(t){return t=t||0,this._pointerData[t].isUp},pointerTimeDown:function(t){return t=t||0,this._pointerData[t].timeDown},pointerTimeUp:function(t){return t=t||0,this._pointerData[t].timeUp},pointerOver:function(t){if(!this.enabled)return!1;if(void 0===t){for(var e=0;e<10;e++)if(this._pointerData[e].isOver)return!0;return!1}return this._pointerData[t].isOver},pointerOut:function(t){if(!this.enabled)return!1;if(void 0!==t)return this._pointerData[t].isOut;for(var e=0;e<10;e++)if(this._pointerData[e].isOut)return!0},pointerTimeOver:function(t){return t=t||0,this._pointerData[t].timeOver},pointerTimeOut:function(t){return t=t||0,this._pointerData[t].timeOut},pointerDragged:function(t){return t=t||0,this._pointerData[t].isDragged},checkPointerDown:function(t,e){return!!(t.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectClick)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPointerOver:function(t,e){return!!(this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectOver)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPixel:function(t,e,i){if(this.sprite.texture.baseTexture.source){if(null===t&&null===e){this.game.input.getLocalPosition(this.sprite,i,this._tempPoint);var t=this._tempPoint.x,e=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(t-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(e-=-this.sprite.texture.frame.height*this.sprite.anchor.y),t+=this.sprite.texture.frame.x,e+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(t-=this.sprite.texture.trim.x,e-=this.sprite.texture.trim.y,tthis.sprite.texture.crop.right||ethis.sprite.texture.crop.bottom))return this._dx=t,this._dy=e,!1;if(this._dx=t,this._dy=e,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,t,e,1,1,0,0,1,1),this.game.input.hitContext.getImageData(0,0,1,1).data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(t){if(null!==this.sprite&&void 0!==this.sprite.parent)return this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this._pendingDrag?(this._dragDistancePass||(this._dragDistancePass=i.Math.distance(t.x,t.y,this.downPoint.x,this.downPoint.y)>=this.dragDistanceThreshold),this._dragDistancePass&&this._dragTimePass&&this.startDrag(t),!0):this.draggable&&this._draggedPointerID===t.id?this.updateDrag(t,!1):this._pointerData[t.id].isOver?this.checkPointerOver(t)?(this._pointerData[t.id].x=t.x-this.sprite.x,this._pointerData[t.id].y=t.y-this.sprite.y,!0):(this._pointerOutHandler(t),!1):void 0:(this._pointerOutHandler(t),!1)},_pointerOverHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];if(!1===i.isOver||t.dirty){var s=!1===i.isOver;i.isOver=!0,i.isOut=!1,i.timeOver=this.game.time.time,i.x=t.x-this.sprite.x,i.y=t.y-this.sprite.y,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),!e&&s&&this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,t),this.sprite.parent&&this.sprite.parent.onChildInputOver&&this.sprite.parent.onChildInputOver.dispatch(this.sprite,t)}}},_pointerOutHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];i.isOver=!1,i.isOut=!0,i.timeOut=this.game.time.time,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="",this._setHandCursor=!1),!e&&this.sprite&&this.sprite.events&&(this.sprite.events.onInputOut$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputOut&&this.sprite.parent.onChildInputOut.dispatch(this.sprite,t))}},_touchedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(!e.isDown&&e.isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,t))return;if(e.isDown=!0,e.isUp=!1,e.timeDown=this.game.time.time,this.downPoint.set(t.x,t.y),t.dirty=!0,this.sprite&&this.sprite.events&&(this.sprite.events.onInputDown$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputDown&&this.sprite.parent.onChildInputDown.dispatch(this.sprite,t),null===this.sprite))return;this.draggable&&!1===this.isDragged&&(0===this.dragTimeThreshold&&0===this.dragDistanceThreshold?this.startDrag(t):(this._pendingDrag=!0,this._dragDistancePass=0===this.dragDistanceThreshold,this.dragTimeThreshold>0?(this._dragTimePass=!1,this.game.time.events.add(this.dragTimeThreshold,this.dragTimeElapsed,this,t)):this._dragTimePass=!0)),this.bringToTop&&this.sprite.bringToTop()}}},dragTimeElapsed:function(t){this._dragTimePass=!0,this._pendingDrag&&this.sprite&&this._dragDistancePass&&this.startDrag(t)},_releasedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(e.isDown&&t.isUp){e.isDown=!1,e.isUp=!0,e.timeUp=this.game.time.time,e.downDuration=e.timeUp-e.timeDown;var i=this.checkPointerOver(t);this.sprite&&this.sprite.events&&(this.dragStopBlocksInputUp&&(!this.dragStopBlocksInputUp||this.draggable&&this.isDragged&&this._draggedPointerID===t.id)||this.sprite.events.onInputUp$dispatch(this.sprite,t,i),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputUp&&this.sprite.parent.onChildInputUp.dispatch(this.sprite,t,i),i&&(i=this.checkPointerOver(t))),e.isOver=i,!i&&this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),t.dirty=!0,this._pendingDrag=!1,this.draggable&&this.isDragged&&this._draggedPointerID===t.id&&this.stopDrag(t)}}},updateDrag:function(t,e){if(void 0===e&&(e=!1),t.isUp)return this.stopDrag(t),!1;var i=this.globalToLocal(t);if(this.sprite.fixedToCamera)var s=this.game.camera.scale.x*i.x+this._dragPoint.x+this.dragOffset.x,n=this.game.camera.scale.y*i.y+this._dragPoint.y+this.dragOffset.y;else var s=i.x+this._dragPoint.x+this.dragOffset.x,n=i.y+this._dragPoint.y+this.dragOffset.y;if(this.sprite.fixedToCamera)this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=s-this.game.camera.x),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=n-this.game.camera.y),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y));else{var r=this.game.camera.x-this._pointerData[t.id].camX,o=this.game.camera.y-this._pointerData[t.id].camY;this.allowHorizontalDrag&&(this.sprite.x=s+r),this.allowVerticalDrag&&(this.sprite.y=n+o),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.x,this.sprite.y))}return this.sprite.events.onDragUpdate.dispatch(this.sprite,t,s,n,this.snapPoint,e),!0},justOver:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOver&&this.overDuration(t)this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.ythis.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.leftthis.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.xthis.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.ythis.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.leftthis.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},i.InputHandler.prototype.constructor=i.InputHandler,i.Gamepad=function(t){this.game=t,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!==navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this)]},i.Gamepad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},start:function(){if(!this._active){this._active=!0;var t=this;this._onGamepadConnected=function(e){return t.onGamepadConnected(e)},this._onGamepadDisconnected=function(e){return t.onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(t){var e=t.gamepad;this._rawPads.push(e),this._gamepads[e.index].connect(e)},onGamepadDisconnected:function(t){var e=t.gamepad;for(var i in this._rawPads)this._rawPads[i].index===e.index&&this._rawPads.splice(i,1);this._gamepads[e.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(this._active){if(navigator.getGamepads)t=navigator.getGamepads();else if(navigator.webkitGetGamepads)t=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var t=navigator.webkitGamepads();if(t){this._rawPads=[];for(var e=!1,i=0;i0&&s>this.deadZone||s<0&&s<-this.deadZone?this.processAxisChange(i,s):this.processAxisChange(i,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(t){var e=!this.connected;this.connected=!0,this.index=t.index,this._rawPad=t,this._buttons=[],this._buttonsLen=t.buttons.length,this._axes=[],this._axesLen=t.axes.length;for(var s=0;sthis.maxHealth&&(this.health=this.maxHealth),this},heal:function(t){return this.alive&&(this.health+=t,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},i.Component.InCamera=function(){},i.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},i.Component.InputEnabled=function(){},i.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(t){t?null===this.input?(this.input=new i.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},i.Component.InWorld=function(){},i.Component.InWorld.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(this.autoCull||this.checkWorldBounds){if(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull)if(this.game.world.camera.view.intersects(this._bounds))this.renderable=!0,this.game.world.camera.totalInView++;else if(this.renderable=!1,this.outOfCameraBoundsKill)return this.kill(),!1;if(this.checkWorldBounds)if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1}return!0},i.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,outOfCameraBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},i.Component.LifeSpan=function(){},i.Component.LifeSpan.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):!(this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0))||(this.kill(),!1)},i.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(t){return void 0===t&&(t=100),this.alive=!0,this.exists=!0,this.visible=!0,"function"==typeof this.setHealth&&this.setHealth(t),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},i.Component.LoadTexture=function(){},i.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(t,e,s){t===i.PENDING_ATLAS?(t=e,e=0):e=e||0,(s||void 0===s)&&this.animations&&this.animations.stop(),this.key=t,this.customRender=!1;var n=this.game.cache,r=!0,o=!this.texture.baseTexture.scaleMode;if(i.RenderTexture&&t instanceof i.RenderTexture)this.key=t.key,this.setTexture(t);else if(i.BitmapData&&t instanceof i.BitmapData)this.customRender=!0,this.setTexture(t.texture),r=n.hasFrameData(t.key,i.Cache.BITMAPDATA)?!this.animations.loadFrameData(n.getFrameData(t.key,i.Cache.BITMAPDATA),e):!this.animations.loadFrameData(t.frameData,0);else if(i.Video&&t instanceof i.Video){this.customRender=!0;var a=t.texture.valid;this.setTexture(t.texture),this.setFrame(t.texture.frame.clone()),t.onChangeSource.add(this.resizeFrame,this),this.texture.valid=a}else if(i.Tilemap&&t instanceof i.TilemapLayer)this.setTexture(PIXI.Texture.fromCanvas(t.canvas));else if(t instanceof PIXI.Texture)this.setTexture(t);else{var h=n.getImage(t,!0);this.key=h.key,this.setTexture(new PIXI.Texture(h.base)),this.texture.baseTexture.skipRender="__default"===t,r=!this.animations.loadFrameData(h.frameData,e)}r&&(this._frame=i.Rectangle.clone(this.texture.frame)),o||(this.texture.baseTexture.scaleMode=1)},setFrame:function(t){this._frame=t,this.texture.frame.x=t.x,this.texture.frame.y=t.y,this.texture.frame.width=t.width,this.texture.frame.height=t.height,this.texture.crop.x=t.x,this.texture.crop.y=t.y,this.texture.crop.width=t.width,this.texture.crop.height=t.height,t.trimmed?(this.texture.trim?(this.texture.trim.x=t.spriteSourceSizeX,this.texture.trim.y=t.spriteSourceSizeY,this.texture.trim.width=t.sourceSizeW,this.texture.trim.height=t.sourceSizeH):this.texture.trim={x:t.spriteSourceSizeX,y:t.spriteSourceSizeY,width:t.sourceSizeW,height:t.sourceSizeH},this.texture.width=t.sourceSizeW,this.texture.height=t.sourceSizeH,this.texture.frame.width=t.sourceSizeW,this.texture.frame.height=t.sourceSizeH):!t.trimmed&&this.texture.trim&&(this.texture.trim=null),t.rotated&&(this.texture.rotated=!0),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(t,e,i){this.texture.frame.resize(e,i),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(t){this.animations.frame=t}},frameName:{get:function(){return this.animations.frameName},set:function(t){this.animations.frameName=t}}},i.Component.Overlap=function(){},i.Component.Overlap.prototype={overlap:function(t){return i.Rectangle.intersects(this.getBounds(),t.getBounds())}},i.Component.PhysicsBody=function(){},i.Component.PhysicsBody.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):this.fresh&&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.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,this.preUpdateChildren(),!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!(!this._exists||!this.parent.exists)||(this.renderOrderID=-1,!1))},i.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},i.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(t){this.position.x=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},i.Component.Reset=function(){},i.Component.Reset.prototype.reset=function(t,e,i){return void 0===i&&(i=1),this.world.set(t,e),this.position.set(t,e),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=i),this.components.PhysicsBody&&this.body&&this.body.reset(t,e,!1,!1),this},i.Component.ScaleMinMax=function(){},i.Component.ScaleMinMax.prototype={transformCallback:null,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(t){this.scaleMin&&(t.athis.scaleMax.x&&(t.a=this.scaleMax.x),t.d>this.scaleMax.y&&(t.d=this.scaleMax.y))},setScaleMinMax:function(t,e,s,n){void 0===e?e=s=n=t:void 0===s&&(s=n=e,e=t),null===t?this.scaleMin=null:this.scaleMin?this.scaleMin.set(t,e):this.scaleMin=new i.Point(t,e),null===s?this.scaleMax=null:this.scaleMax?this.scaleMax.set(s,n):this.scaleMax=new i.Point(s,n),null===this.scaleMin?this.transformCallback=null:(this.transformCallback=this.checkTransform,this.transformCallbackContext=this)}},i.Component.Smoothed=function(){},i.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(t){t?this.texture&&(this.texture.baseTexture.scaleMode=0,this.texture.baseTexture.dirty()):this.texture&&(this.texture.baseTexture.scaleMode=1,this.texture.baseTexture.dirty())}}},i.GameObjectFactory=function(t){this.game=t,this.world=this.game.world},i.GameObjectFactory.prototype={existing:function(t){return this.world.add(t)},weapon:function(t,e,s,n,r){var o=this.game.plugins.add(i.Weapon);return r&&(o.bulletClass=r),o.createBullets(t,e,s,n),o},image:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Image(this.game,t,e,s,n))},sprite:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Sprite(this.game,t,e,s,n))},creature:function(t,e,s,n,r){void 0===r&&(r=this.world);var o=new i.Creature(this.game,t,e,s,n);return r.add(o),o},tween:function(t){return this.game.tweens.create(t)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},physicsGroup:function(t,e,s,n){return new i.Group(this.game,e,s,n,!0,t)},spriteBatch:function(t,e,s){return void 0===t&&(t=null),void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},tileSprite:function(t,e,s,n,r,o,a){return void 0===a&&(a=this.world),a.add(new i.TileSprite(this.game,t,e,s,n,r,o))},rope:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.Rope(this.game,t,e,s,n,r))},text:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Text(this.game,t,e,s,n))},button:function(t,e,s,n,r,o,a,h,l,c){return void 0===c&&(c=this.world),c.add(new i.Button(this.game,t,e,s,n,r,o,a,h,l))},graphics:function(t,e,s){return void 0===s&&(s=this.world),s.add(new i.Graphics(this.game,t,e))},emitter:function(t,e,s){return this.game.particles.add(new i.Particles.Arcade.Emitter(this.game,t,e,s))},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.BitmapText(this.game,t,e,s,n,r))},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},video:function(t,e){return new i.Video(this.game,t,e)},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t},plugin:function(t){return this.game.plugins.add(t)}},i.GameObjectFactory.prototype.constructor=i.GameObjectFactory,i.GameObjectCreator=function(t){this.game=t,this.world=this.game.world},i.GameObjectCreator.prototype={image:function(t,e,s,n){return new i.Image(this.game,t,e,s,n)},sprite:function(t,e,s,n){return new i.Sprite(this.game,t,e,s,n)},tween:function(t){return new i.Tween(t,this.game,this.game.tweens)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},spriteBatch:function(t,e,s){return void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},tileSprite:function(t,e,s,n,r,o){return new i.TileSprite(this.game,t,e,s,n,r,o)},rope:function(t,e,s,n,r){return new i.Rope(this.game,t,e,s,n,r)},text:function(t,e,s,n){return new i.Text(this.game,t,e,s,n)},button:function(t,e,s,n,r,o,a,h,l){return new i.Button(this.game,t,e,s,n,r,o,a,h,l)},graphics:function(t,e){return new i.Graphics(this.game,t,e)},emitter:function(t,e,s){return new i.Particles.Arcade.Emitter(this.game,t,e,s)},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return new i.BitmapText(this.game,t,e,s,n,r,o)},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t}},i.GameObjectCreator.prototype.constructor=i.GameObjectCreator,i.Sprite=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.SPRITE,this.physicsType=i.SPRITE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Sprite.prototype=Object.create(PIXI.Sprite.prototype),i.Sprite.prototype.constructor=i.Sprite,i.Component.Core.install.call(i.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Sprite.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Sprite.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Sprite.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Sprite.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Sprite.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Image=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.IMAGE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Image.prototype=Object.create(PIXI.Sprite.prototype),i.Image.prototype.constructor=i.Image,i.Component.Core.install.call(i.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","ScaleMinMax","Smoothed"]),i.Image.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Image.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Image.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Image.prototype.preUpdate=function(){return!(!this.preUpdateInWorld()||!this.preUpdateLifeSpan())&&this.preUpdateCore()},i.Button=function(t,e,s,n,r,o,a,h,l,c){e=e||0,s=s||0,n=n||null,r=r||null,o=o||this,i.Image.call(this,t,e,s,n,h),this.type=i.BUTTON,this.physicsType=i.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new i.Signal,this.onInputOut=new i.Signal,this.onInputDown=new i.Signal,this.onInputUp=new i.Signal,this.onOverMouseOnly=!0,this.justReleasedPreventsOver=i.PointerMode.CONTACT,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(a,h,l,c),null!==r&&this.onInputUp.add(r,o),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this)},i.Button.prototype=Object.create(i.Image.prototype),i.Button.prototype.constructor=i.Button;return i.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},i.Button.prototype.setStateFrame=function(t,e,i){var s="_on"+t+"Frame";null!==e?(this[s]=e,i&&this.changeStateFrame(t)):this[s]=null},i.Button.prototype.changeStateFrame=function(t){if(this.freezeFrames)return!1;var e=this["_on"+t+"Frame"];return"string"==typeof e?(this.frameName=e,!0):"number"==typeof e&&(this.frame=e,!0)},i.Button.prototype.setFrames=function(t,e,i,s){this.setStateFrame("Over",t,this.input.pointerOver()),this.setStateFrame("Out",e,!this.input.pointerOver()),this.setStateFrame("Down",i,this.input.pointerDown()),this.setStateFrame("Up",s,this.input.pointerUp())},i.Button.prototype.setStateSound=function(t,e,s){var n="on"+t+"Sound",r="on"+t+"SoundMarker";e instanceof i.Sound||e instanceof i.AudioSprite?(this[n]=e,this[r]="string"==typeof s?s:""):(this[n]=null,this[r]="")},i.Button.prototype.playStateSound=function(t){var e=this["on"+t+"Sound"];if(e){var i=this["on"+t+"SoundMarker"];return e.play(i),!0}return!1},i.Button.prototype.setSounds=function(t,e,i,s,n,r,o,a){this.setStateSound("Over",t,e),this.setStateSound("Out",n,r),this.setStateSound("Down",i,s),this.setStateSound("Up",o,a)},i.Button.prototype.setOverSound=function(t,e){this.setStateSound("Over",t,e)},i.Button.prototype.setOutSound=function(t,e){this.setStateSound("Out",t,e)},i.Button.prototype.setDownSound=function(t,e){this.setStateSound("Down",t,e)},i.Button.prototype.setUpSound=function(t,e){this.setStateSound("Up",t,e)},i.Button.prototype.onInputOverHandler=function(t,e){e.justReleased()&&(this.justReleasedPreventsOver&e.pointerMode)===e.pointerMode||(this.changeStateFrame("Over"),this.onOverMouseOnly&&!e.isMouse||(this.playStateSound("Over"),this.onInputOver&&this.onInputOver.dispatch(this,e)))},i.Button.prototype.onInputOutHandler=function(t,e){this.changeStateFrame("Out"),this.playStateSound("Out"),this.onInputOut&&this.onInputOut.dispatch(this,e)},i.Button.prototype.onInputDownHandler=function(t,e){this.changeStateFrame("Down"),this.playStateSound("Down"),this.onInputDown&&this.onInputDown.dispatch(this,e)},i.Button.prototype.onInputUpHandler=function(t,e,i){this.playStateSound("Up"),this.onInputUp&&this.onInputUp.dispatch(this,e,i),this.freezeFrames||(!0===this.forceOut||(this.forceOut&e.pointerMode)===e.pointerMode?this.changeStateFrame("Out"):this.changeStateFrame("Up")||(i?this.changeStateFrame("Over"):this.changeStateFrame("Out")))},i.SpriteBatch=function(t,e,s,n){void 0!==e&&null!==e||(e=t.world),i.Group.call(this,t,e,s,n),this.type=i.SPRITEBATCH,this.fastSpriteBatch=null,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.Group.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||(this.fastSpriteBatch=new PIXI.WebGLFastSpriteBatch(t.gl),this.ready=!0),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n=0&&t<=this.width&&e>=0&&e<=this.height&&(i.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|n<<8|s:this.pixels[e*this.width+t]=s<<24|n<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,s){s||(s=i.Color.createColor());var n=~~(t+e*this.width);return n*=4,s.r=this.data[n],s.g=this.data[++n],s.b=this.data[++n],s.a=this.data[++n],s},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,s,n,r){return i.Color.unpackPixel(this.getPixel32(t,e),s,n,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=i.Color.createColor(),s=0,n=0,r=1,o=!1;1===t?(r=-1,n=this.height):3===t&&(r=-1,s=this.width);do{i.Color.unpackPixel(this.getPixel32(s,n),e),0===t||1===t?++s===this.width&&(s=0,((n+=r)>=this.height||n<=0)&&(o=!0)):2!==t&&3!==t||++n===this.height&&(n=0,((s+=r)>=this.width||s<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=s,e.y=n,e},getBounds:function(t){return void 0===t&&(t=new i.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,s,n,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),t instanceof i.RenderTexture&&(t=t.getCanvas()),this._image=t,t instanceof i.Sprite||t instanceof i.Image||t instanceof i.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof i.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==s&&null!==s||(s=0),n&&(this._size.x=n),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=s),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+s,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var n=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===n.a||0===n.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=n.tx,o=n.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),s&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(n.a,n.b,n.c,n.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,s){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,s),t.type===i.GROUP&&t.exists)this.drawGroup(t,e,s);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var n=0;ne.width&&(n=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,s),this._circle=new i.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,n,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),i.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this},copyBitmapData:function(t,e,i){t.update();for(var s,n=0;n80*s){h=c=t[0],l=u=t[1];for(var g=s;gc&&(c=d),p>u&&(u=p);f=Math.max(c-h,u-l)}return i.EarCut.earcutLinked(o,a,s,h,l,f),a},i.EarCut.linkedList=function(t,e,s,n,r){var o,a,h,l=0;for(o=e,a=s-n;o0)for(o=e;o=e;o-=n)h=i.EarCut.insertNode(o,t[o],t[o+1],h);return h},i.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var s,n=t;do{if(s=!1,n.steiner||!i.EarCut.equals(n,n.next)&&0!==i.EarCut.area(n.prev,n,n.next))n=n.next;else{if(i.EarCut.removeNode(n),(n=e=n.prev)===n.next)return null;s=!0}}while(s||n!==e);return e},i.EarCut.earcutLinked=function(t,e,s,n,r,o,a){if(t){!a&&o&&i.EarCut.indexCurve(t,n,r,o);for(var h,l,c=t;t.prev!==t.next;)if(h=t.prev,l=t.next,o?i.EarCut.isEarHashed(t,n,r,o):i.EarCut.isEar(t))e.push(h.i/s),e.push(t.i/s),e.push(l.i/s),i.EarCut.removeNode(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?(t=i.EarCut.cureLocalIntersections(t,e,s),i.EarCut.earcutLinked(t,e,s,n,r,o,2)):2===a&&i.EarCut.splitEarcut(t,e,s,n,r,o):i.EarCut.earcutLinked(i.EarCut.filterPoints(t),e,s,n,r,o,1);break}}},i.EarCut.isEar=function(t){var e=t.prev,s=t,n=t.next;if(i.EarCut.area(e,s,n)>=0)return!1;for(var r=t.next.next;r!==t.prev;){if(i.EarCut.pointInTriangle(e.x,e.y,s.x,s.y,n.x,n.y,r.x,r.y)&&i.EarCut.area(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},i.EarCut.isEarHashed=function(t,e,s,n){var r=t.prev,o=t,a=t.next;if(i.EarCut.area(r,o,a)>=0)return!1;for(var h=r.xo.x?r.x>a.x?r.x:a.x:o.x>a.x?o.x:a.x,u=r.y>o.y?r.y>a.y?r.y:a.y:o.y>a.y?o.y:a.y,d=i.EarCut.zOrder(h,l,e,s,n),p=i.EarCut.zOrder(c,u,e,s,n),f=t.nextZ;f&&f.z<=p;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=d;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0},i.EarCut.cureLocalIntersections=function(t,e,s){var n=t;do{var r=n.prev,o=n.next.next;i.EarCut.intersects(r,n,n.next,o)&&i.EarCut.locallyInside(r,o)&&i.EarCut.locallyInside(o,r)&&(e.push(r.i/s),e.push(n.i/s),e.push(o.i/s),i.EarCut.removeNode(n),i.EarCut.removeNode(n.next),n=t=o),n=n.next}while(n!==t);return n},i.EarCut.splitEarcut=function(t,e,s,n,r,o){var a=t;do{for(var h=a.next.next;h!==a.prev;){if(a.i!==h.i&&i.EarCut.isValidDiagonal(a,h)){var l=i.EarCut.splitPolygon(a,h);return a=i.EarCut.filterPoints(a,a.next),l=i.EarCut.filterPoints(l,l.next),i.EarCut.earcutLinked(a,e,s,n,r,o),void i.EarCut.earcutLinked(l,e,s,n,r,o)}h=h.next}a=a.next}while(a!==t)},i.EarCut.eliminateHoles=function(t,e,s,n){var r,o,a,h,l,c=[];for(r=0,o=e.length;r=n.next.y){var h=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);h<=r&&h>a&&(a=h,s=n.x=n.x&&n.x>=s.x&&i.EarCut.pointInTriangle(os.x)&&i.EarCut.locallyInside(n,t)&&(s=n,u=l),n=n.next;return s},i.EarCut.indexCurve=function(t,e,s,n){var r=t;do{null===r.z&&(r.z=i.EarCut.zOrder(r.x,r.y,e,s,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,i.EarCut.sortLinked(r)},i.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},i.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},i.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},i.EarCut.isValidDiagonal=function(t,e){return i.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!i.EarCut.intersectsPolygon(t,e)&&i.EarCut.locallyInside(t,e)&&i.EarCut.locallyInside(e,t)&&i.EarCut.middleInside(t,e)},i.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},i.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},i.EarCut.intersects=function(t,e,s,n){return i.EarCut.area(t,e,s)>0!=i.EarCut.area(t,e,n)>0&&i.EarCut.area(s,n,t)>0!=i.EarCut.area(s,n,e)>0},i.EarCut.intersectsPolygon=function(t,e){var s=t;do{if(s.i!==t.i&&s.next.i!==t.i&&s.i!==e.i&&s.next.i!==e.i&&i.EarCut.intersects(s,s.next,t,e))return!0;s=s.next}while(s!==t);return!1},i.EarCut.locallyInside=function(t,e){return i.EarCut.area(t.prev,t,t.next)<0?i.EarCut.area(t,e,t.next)>=0&&i.EarCut.area(t,t.prev,e)>=0:i.EarCut.area(t,e,t.prev)<0||i.EarCut.area(t,t.next,e)<0},i.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},i.EarCut.splitPolygon=function(t,e){var s=new i.EarCut.Node(t.i,t.x,t.y),n=new i.EarCut.Node(e.i,e.x,e.y),r=t.next,o=e.prev;return t.next=e,e.prev=t,s.next=r,r.prev=s,n.next=s,s.prev=n,o.next=n,n.prev=o,n},i.EarCut.insertNode=function(t,e,s,n){var r=new i.EarCut.Node(t,e,s);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r},i.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},i.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var s,n=e.gl,r=e.projection,o=e.offset,a=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,n);var h=t._webGL[n.id];if(h)for(var l=0;l=PIXI.WebGLGraphics.stencilBufferLimit&&(a.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit?(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildPoly(a,o)||(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))),a.lineWidth>0&&(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildLine(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,0),a.type===i.RECTANGLE?PIXI.WebGLGraphics.buildRectangle(a,o):a.type===i.CIRCLE||a.type===i.ELLIPSE?PIXI.WebGLGraphics.buildCircle(a,o):a.type===i.ROUNDEDRECTANGLE&&PIXI.WebGLGraphics.buildRoundedRectangle(a,o)),s.lastIndex++}for(n=0;n19600?(_=y-x,w=v-b,_/=R=Math.sqrt(_*_+w*w),w/=R,_*=F,w*=F,L.push(p-_,f-w),L.push(G,N,X,U),L.push(p+_,f+w),L.push(G,N,X,U),L.push(p-_,f-w),L.push(G,N,X,U),O++):(L.push(l,c),L.push(G,N,X,U),L.push(p-(l-p),f-(c-f)),L.push(G,N,X,U));for(u=n[2*(I-2)],d=n[2*(I-2)+1],p=n[2*(I-1)],y=-(d-(f=n[2*(I-1)+1])),v=u-p,y/=R=Math.sqrt(y*y+v*v),v/=R,y*=F,v*=F,L.push(p-y,f-v),L.push(G,N,X,U),L.push(p+y,f+v),L.push(G,N,X,U),B.push(k),s=0;sh?r:h,l=oc?o:c;s.push(a,l,h,l,h,c,a,c);var d=s.length/2;for(u=0;uS?S:C,e.beginPath(),e.moveTo(_,w+C),e.lineTo(_,w+P-C),e.quadraticCurveTo(_,w+P,_+C,w+P),e.lineTo(_+T-C,w+P),e.quadraticCurveTo(_+T,w+P,_+T,w+P-C),e.lineTo(_+T,w+C),e.quadraticCurveTo(_+T,w,_+T-C,w),e.lineTo(_+C,w),e.quadraticCurveTo(_,w,_,w+C),e.closePath(),(r.fillColor||0===r.fillColor)&&(e.globalAlpha=r.fillAlpha*s,e.fillStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.fill()),r.lineWidth&&(e.globalAlpha=r.lineAlpha*s,e.strokeStyle="#"+("00000"+(0|h).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var s=t.graphicsData.length;if(0!==s){e.beginPath();for(var n=0;nP?P:T,e.moveTo(x,b+T),e.lineTo(x,b+w-T),e.quadraticCurveTo(x,b+w,x+T,b+w),e.lineTo(x+_-T,b+w),e.quadraticCurveTo(x+_,b+w,x+_,b+w-T),e.lineTo(x+_,b+T),e.quadraticCurveTo(x+_,b,x+_-T,b),e.lineTo(x+T,b),e.quadraticCurveTo(x,b,x,b+T),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},i.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},i.GraphicsData.prototype.constructor=i.GraphicsData,i.GraphicsData.prototype.clone=function(){return new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},i.Graphics=function(t,e,s){void 0===e&&(e=0),void 0===s&&(s=0),this.type=i.GRAPHICS,this.physicsType=i.SPRITE,this.anchor=new i.Point,PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new i.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1,i.Component.Core.init.call(this,t,e,s,"",null)},i.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Graphics.prototype.constructor=i.Graphics,i.Component.Core.install.call(i.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),i.Graphics.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Graphics.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Graphics.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Graphics.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Graphics.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Graphics.prototype.postUpdate=function(){i.Component.PhysicsBody.postUpdate.call(this),i.Component.FixedToCamera.postUpdate.call(this),this._boundsDirty&&(this.updateLocalBounds(),this._boundsDirty=!1);for(var t=0;t0&&this.drawPolygon(s)}else this.drawPolygon(s)},i.Graphics.prototype.drawTriangles=function(t,e,s){void 0===s&&(s=!1);var n,r=new i.Point,o=new i.Point,a=new i.Point,h=[];if(e)if(t[0]instanceof i.Point)for(n=0;nc*a)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var x=d+s+p*(v+y*v),b=Math.cos(x),_=-Math.sin(x);u.push((f*b+g*_)*i+t,(f*-_+g*b)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},i.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},i.Graphics.prototype.drawRect=function(t,e,s,n){return this.drawShape(new i.Rectangle(t,e,s,n)),this},i.Graphics.prototype.drawRoundedRect=function(t,e,s,n,r){return this.drawShape(new i.RoundedRectangle(t,e,s,n,r)),this},i.Graphics.prototype.drawCircle=function(t,e,s){return this.drawShape(new i.Circle(t,e,s)),this},i.Graphics.prototype.drawEllipse=function(t,e,s,n){return this.drawShape(new i.Ellipse(t,e,s,n)),this},i.Graphics.prototype.drawPolygon=function(t){t instanceof i.Polygon&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var s=0;sw?m:w,w=v>w?v:w,w=b>w?b:w,T=y>T?y:T,T=x>T?x:T,T=_>T?_:T,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=C,this._bounds.height=T-C,this._currentBounds=this._bounds,this._currentBounds},i.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;ee?a+l:e,s=hn?h+c:n;else if(p===i.CIRCLE)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else if(p===i.ELLIPSE)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else{o=r.points;for(var g=0;ge?a+f:e,s=h-fn?h+f:n}}else t=0,e=0,s=0,n=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=s-m,this._localBounds.height=n-s+2*m},i.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},i.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},i.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},i.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof i.Polygon&&(t=t.clone()).flatten();var e=new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===i.POLYGON&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(i.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),i.RenderTexture=function(t,e,s,n,r,o,a,h){if(void 0===e&&(e=100),void 0===s&&(s=100),void 0===n&&(n=""),void 0===r&&(r=i.scaleModes.DEFAULT),void 0===o&&(o=1),void 0===a&&(a=PIXI.defaultRenderer),void 0===h&&(h=0),this.game=t,this.key=n,this.type=i.RENDERTEXTURE,this._tempMatrix=new i.Matrix,this.width=e,this.height=s,this.resolution=o,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=this.frame.clone(),this.baseTexture=new PIXI.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=r,this.baseTexture.hasLoaded=!0,PIXI.Texture.call(this,this.baseTexture,this.frame.clone()),this.renderer=a,this.renderer.type===i.WEBGL){var l=this.renderer.gl;this.baseTexture.textureIndex=h,this.baseTexture._dirty[l.id]=!1,this.textureBuffer=new PIXI.FilterTexture(l,this.width,this.height,this.baseTexture.scaleMode,h),this.baseTexture._glTextures[l.id]=this.textureBuffer.texture,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.textureBuffer=new PIXI.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new i.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(PIXI.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.renderXY=function(t,e,s,n){t.updateTransform(),this._tempMatrix.copyFrom(t.worldTransform),this._tempMatrix.tx=e,this._tempMatrix.ty=s,this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.renderRawXY=function(t,e,s,n){this._tempMatrix.identity().translate(e,s),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.render=function(t,e,s){void 0===e||null===e?this._tempMatrix.copyFrom(t.worldTransform):this._tempMatrix.copyFrom(e),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,s):this._renderCanvas(t,this._tempMatrix,s)},i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype._renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n-1&&this.characterLimitSize0&&this.style.maxLines0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(e[a]):l+=this.context.measureText(e[a]).width,this.style.wordWrap&&(l-=this.context.measureText(" ").width)}else{var h=e[a].split(/(?:\t)/),l=this.padding.x+this.style.strokeThickness;if(Array.isArray(i))for(var c=0,u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.measureLine(h[u]):Math.ceil(this.context.measureText(h[u]).width),u>0&&(c+=i[u-1]),l=c+d}else for(u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(h[u]):l+=Math.ceil(this.context.measureText(h[u]).width),l+=this.game.math.snapToCeil(l,i)-l}s[a]=Math.ceil(l),n=Math.max(n,s[a])}this.canvas.width=n*this._res;var p=r.fontSize+this.style.strokeThickness+this.padding.y,f=p*o,g=this._lineSpacing;g<0&&Math.abs(g)>p&&(g=-p),0!==g&&(f+=g>0?g*e.length:g*(e.length-1)),this.canvas.height=f*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var m,y;for(this._charCount=0,a=0;a0&&(y+=g*a),"right"===this.style.align?m+=n-s[a]:"center"===this.style.align&&(m+=(n-s[a])/2),this.autoRound&&(m=Math.round(m),y=Math.round(y)),this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.updateLine(e[a],m,y):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===i?this.context.strokeText(e[a],m,y):this.renderTabLine(e[a],m,y,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===i?this.context.fillText(e[a],m,y):this.renderTabLine(e[a],m,y,!0)));this.updateTexture(),this.dirty=!1},i.Text.prototype.renderTabLine=function(t,e,i,s){var n=t.split(/(?:\t)/),r=this.style.tabs,o=0;if(Array.isArray(r))for(var a=0,h=0;h0&&(a+=r[h-1]),o=e+a,s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i);else for(h=0;h0||this.fontStyles.length>0){var n=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(n.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(n.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(n)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill)),e+=this.context.measureText(s).width,this._charCount++}return Math.ceil(e)},i.Text.prototype.updateLine=function(t,e,i){for(var s=0;s0||this.fontStyles.length>0){var r=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(r.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(r.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(r)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(n,e,i)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(n,e,i)),e+=this.context.measureText(n).width,this._charCount++}},i.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},i.Text.prototype.clearFontValues=function(){return this.fontStyles=[],this.fontWeights=[],this.dirty=!0,this},i.Text.prototype.addColor=function(t,e){return this.colors[e]=t,this.dirty=!0,this},i.Text.prototype.addStrokeColor=function(t,e){return this.strokeColors[e]=t,this.dirty=!0,this},i.Text.prototype.addFontStyle=function(t,e){return this.fontStyles[e]=t,this.dirty=!0,this},i.Text.prototype.addFontWeight=function(t,e){return this.fontWeights[e]=t,this.dirty=!0,this},i.Text.prototype.precalculateWordWrap=function(t){return this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font,this.runWordWrap(t).split(/(?:\r\n|\r|\n)/)},i.Text.prototype.runWordWrap=function(t){return this.useAdvancedWrap?this.advancedWordWrap(t):this.basicWordWrap(t)},i.Text.prototype.advancedWordWrap=function(t){for(var e=this.context,i=this.style.wordWrapWidth,s="",n=t.replace(/ +/gi," ").split(/\r?\n/gi),r=n.length,o=0;ol){if(0===u){for(var g=p;g.length&&(g=g.slice(0,-1),!((f=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var m=d.substr(g.length);c[u]=m,h+=g}var y=c[u].length?u:u+1,v=c.slice(y).join(" ").replace(/[ \n]*$/gi,"");n[o+1]=v+" "+(n[o+1]||""),r=n.length;break}h+=p,l-=f}s+=h.replace(/[ \n]*$/gi,"")+"\n"}}return s=s.replace(/[\s|\n]*$/gi,"")},i.Text.prototype.basicWordWrap=function(t){for(var e="",i=t.split("\n"),s=0;sn?(o>0&&(e+="\n"),e+=r[o]+" ",n=this.style.wordWrapWidth-a):(n-=h,e+=r[o]+" ")}ss&&(this.style.wordWrapWidth=s)),this.updateTexture(),this},i.Text.prototype.updateTexture=function(){var t=this.texture.baseTexture,e=this.texture.crop,i=this.texture.frame,s=this.canvas.width,n=this.canvas.height;if(t.width=s,t.height=n,e.width=s,e.height=n,i.width=s,i.height=n,this.texture.width=s,this.texture.height=n,this._width=s,this._height=n,this.textBounds){var r=this.textBounds.x,o=this.textBounds.y;"right"===this.style.boundsAlignH?r+=this.textBounds.width-this.canvas.width/this.resolution:"center"===this.style.boundsAlignH&&(r+=this.textBounds.halfWidth-this.canvas.width/this.resolution/2),"bottom"===this.style.boundsAlignV?o+=this.textBounds.height-this.canvas.height/this.resolution:"middle"===this.style.boundsAlignV&&(o+=this.textBounds.halfHeight-this.canvas.height/this.resolution/2),this.pivot.x=-r,this.pivot.y=-o}this.renderable=0!==s&&0!==n,this.texture.requiresReTint=!0,this.texture.baseTexture.dirty()},i.Text.prototype._renderWebGL=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.Text.prototype._renderCanvas=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.Text.prototype.determineFontProperties=function(t){var e=i.Text.fontPropertiesCache[t];if(!e){e={};var s=i.Text.fontPropertiesCanvas,n=i.Text.fontPropertiesContext;n.font=t;var r=Math.ceil(n.measureText("|MÉq").width),o=Math.ceil(n.measureText("|MÉq").width),a=2*o;if(o=1.4*o|0,s.width=r,s.height=a,n.fillStyle="#f00",n.fillRect(0,0,r,a),n.font=t,n.textBaseline="alphabetic",n.fillStyle="#000",n.fillText("|MÉq",0,o),!n.getImageData(0,0,r,a))return e.ascent=o,e.descent=o+6,e.fontSize=e.ascent+e.descent,i.Text.fontPropertiesCache[t]=e,e;var h,l,c=n.getImageData(0,0,r,a).data,u=c.length,d=4*r,p=0,f=!1;for(h=0;ho;h--){for(l=0;l0?this._maxWidth:null,l=[],c=0;c=h&&r>-1)return{width:o||n,text:i.substr(0,c-(c-r)),end:!1,chars:l};n+=(p.xAdvance+g)*e,l.push(s+(p.xOffset+g)*e),s+=(p.xAdvance+g)*e,a=d}return{width:n,text:i,end:u,chars:l}},i.BitmapText.prototype.cleanText=function(t,e){void 0===e&&(e="");var i=this._data.font;if(!i)return"";for(var s=/\r\n|\n\r|\n|\r/g,n=t.replace(s,"\n").split("\n"),r=0;rthis.textWidth&&(this.textWidth=c.width),n+=t.lineHeight*i,e=e.substr(c.text.length+1)}while(!1===c.end);this.textHeight=n;for(var r=0,o=0,a=this.textWidth*this.anchor.x,h=this.textHeight*this.anchor.y,l=0;l0&&(this._fontSize=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"smoothed",{get:function(){return!this._data.base.scaleMode},set:function(t){this._data.base.scaleMode=t?0:1,this._data.base.dirty()}}),i.RetroFont=function(t,e,s,n,r,o,a,h,l,c){if(!t.cache.checkImageKey(e))return!1;void 0!==o&&null!==o||(o=t.cache.getImage(e).width/s),this.characterWidth=s,this.characterHeight=n,this.characterSpacingX=a||0,this.characterSpacingY=h||0,this.characterPerRow=o,this.offsetX=l||0,this.offsetY=c||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=t.cache.getImage(e),this._text="",this.grabData=[],this.frameData=new i.FrameData;for(var u=this.offsetX,d=this.offsetY,p=0,f=0;f?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",i.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",i.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",i.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",i.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",i.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",i.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",i.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",i.RetroFont.prototype.setFixedWidth=function(t,e){void 0===e&&(e="left"),this.fixedWidth=t,this.align=e},i.RetroFont.prototype.setText=function(t,e,i,s,n,r){this.multiLine=e||!1,this.customSpacingX=i||0,this.customSpacingY=s||0,this.align=n||"left",this.autoUpperCase=!r,t.length>0&&(this.text=t)},i.RetroFont.prototype.buildRetroFontText=function(){var t=0,e=0;if(this.clear(),this.multiLine){var s=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var n=0;n0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),t=0,this.align===i.RetroFont.ALIGN_RIGHT?t=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===i.RetroFont.ALIGN_CENTER&&(t=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(this._text,t,0,this.customSpacingX);this.requiresReTint=!0},i.RetroFont.prototype.pasteLine=function(t,e,i,s){for(var n=0;n=0&&(this.stamp.frame=this.grabData[t.charCodeAt(n)],this.renderXY(this.stamp,e,i,!1),(e+=this.characterWidth+s)>this.width))break},i.RetroFont.prototype.getLongestLine=function(){var t=0;if(this._text.length>0)for(var e=this._text.split("\n"),i=0;it&&(t=e[i].length);return t},i.RetroFont.prototype.removeUnsupportedCharacters=function(t){for(var e="",i=0;i=0||!t&&"\n"===s)&&(e=e.concat(s))}return e},i.RetroFont.prototype.updateOffset=function(t,e){if(this.offsetX!==t||this.offsetY!==e){for(var i=t-this.offsetX,s=e-this.offsetY,n=this.game.cache.getFrameData(this.stamp.key).getFrames(),r=n.length;r--;)n[r].x+=i,n[r].y+=s;this.buildRetroFontText()}},Object.defineProperty(i.RetroFont.prototype,"text",{get:function(){return this._text},set:function(t){var e;(e=this.autoUpperCase?t.toUpperCase():t)!==this._text&&(this._text=e,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(i.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(t){this.stamp.smoothed=t,this.buildRetroFontText()}}),i.Rope=function(t,e,s,n,r,o){this.points=o||[],this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.ROPE,PIXI.DisplayObjectContainer.call(this),this.texture=i.Cache.DEFAULT,this.uvs=new Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new Float32Array([0,0,100,0,100,100,0,100]),this.colors=new Float32Array([1,1,1,1]),this.indices=new Uint16Array([0,1,2,3]),o&&(this.vertices=new Float32Array(4*o.length),this.uvs=new Float32Array(4*o.length),this.colors=new Float32Array(2*o.length),this.indices=new Uint16Array(2*o.length)),this.dirty=!0,this.canvasPadding=0,this.drawMode=i.Rope.TRIANGLE_STRIP,i.Component.Core.init.call(this,t,e,s,n,r),this.refresh()},i.Rope.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Rope.prototype.constructor=i.Rope,i.Component.Core.install.call(i.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Rope.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Rope.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Rope.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Rope.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Rope.TRIANGLE_STRIP=0,i.Rope.TRIANGLES=1,i.Rope.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},i.Rope.prototype.reset=function(t,e){return i.Component.Reset.prototype.reset.call(this,t,e),this},i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=this.indices,s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o=t.length,a=1;a1&&1,o=Math.sqrt(s.x*s.x+s.y*s.y),a=this.texture.height/2,s.x/=o,s.y/=o,s.x*=a,s.y*=a,h[r]=n.x+s.x,h[r+1]=n.y+s.y,h[r+2]=n.x-s.x,h[r+3]=n.y-s.y,i=n;PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.Rope.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Rope.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Rope.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Rope.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Rope.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Rope.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Rope.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n0){var _=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,T=(l+c+u)/3,P=(d+p+f)/3,C=l-T,S=d-P,A=Math.sqrt(C*C+S*S);l=T+C/A*(A+_),d=P+S/A*(A+w),S=p-P,c=T+(C=c-T)/(A=Math.sqrt(C*C+S*S))*(A+_),p=P+S/A*(A+w),S=f-P,u=T+(C=u-T)/(A=Math.sqrt(C*C+S*S))*(A+_),f=P+S/A*(A+w)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*x+v*y+m*b-x*y-v*m-g*b,M=l*x+v*u+c*b-x*u-v*c-l*b,R=g*c+l*y+m*u-c*y-l*m-g*u,L=g*x*u+v*c*y+l*m*b-l*x*y-v*m*u-g*c*b,B=d*x+v*f+p*b-x*f-v*p-d*b,I=g*p+d*y+m*f-p*y-d*m-g*f,O=g*x*f+v*p*y+d*m*b-d*x*y-v*m*f-g*p*b;t.transform(M/E,B/E,R/E,I/E,L/E,O/E),t.drawImage(o,0,0),t.restore()},i.Rope.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;nh?m:h,l=y>l?y:l}if(c===-1/0||l===1/0)return PIXI.EmptyRectangle;var v=this._bounds;return v.x=c,v.width=h-c,v.y=u,v.height=l-u,this._currentBounds=v,v},Object.defineProperty(i.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(t){t&&"function"==typeof t?(this._hasUpdateAnimation=!0,this._updateAnimation=t):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(i.Rope.prototype,"segments",{get:function(){for(var t,e,s,n,r,o,a,h,l=[],c=0;c(_=y>(_=g>(_=p>_?p:_)?g:_)?y:_)?x:_,w=b>(w=v>(w=m>(w=f>w?f:w)?m:w)?v:w)?b:w;var C=this._bounds;return C.x=T,C.width=_-T,C.y=P,C.height=w-P,this._currentBounds=C,C},Object.defineProperty(i.TileSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TileSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var e=parseInt(RegExp.$1,10),i=parseInt(RegExp.$2,10);(10===e&&i>=11||e>10)&&(s.dolby=!0)}}catch(t){}}(),function(){var t=document.createElement("video");try{!!t.canPlayType&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(s.oggVideo=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.h264Video=!0,s.mp4Video=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(s.webmVideo=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(s.vp9Video=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.hlsVideo=!0))}catch(t){}}(),function(){var t,e=document.createElement("p"),i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var n in i)void 0!==e.style[n]&&(e.style[n]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(i[n]));document.body.removeChild(e),s.css3D=void 0!==t&&t.length>0&&"none"!==t}(),s.pixelRatio=window.devicePixelRatio||1,s.iPhone=-1!==navigator.userAgent.toLowerCase().indexOf("iphone"),s.iPhone4=2===s.pixelRatio&&s.iPhone,s.iPad=-1!==navigator.userAgent.toLowerCase().indexOf("ipad"),"undefined"!=typeof Int8Array?s.typedArray=!0:s.typedArray=!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(s.littleEndian=t(),s.LITTLE_ENDIAN=s.littleEndian),s.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==s.littleEndian&&e(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(s.vibration=!0),function(){s.canvas=!!window.CanvasRenderingContext2D||s.cocoonJS;try{s.localStorage=!!localStorage.getItem}catch(t){s.localStorage=!1}s.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),s.fileSystem=!!window.requestFileSystem,s.webGL=!!window.WebGLRenderingContext,s.worker=!!window.Worker,s.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,s.quirksMode="CSS1Compat"!==document.compatMode,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,s.getUserMedia=s.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,s.firefox&&s.firefoxVersion<21&&(s.getUserMedia=!1),!s.iOS&&(s.ie||s.firefox||s.chrome)&&(s.canvasBitBltShift=!0),(s.safari||s.mobileSafari)&&(s.canvasBitBltShift=!1)}(),function(){var t=i.CanvasPool.create(this,6,1),e=t.getContext("2d");e.fillStyle="rgba(10, 20, 30, 0.5)",e.fillRect(0,0,1,1);var n=e.getImageData(0,0,1,1);if(n){e.putImageData(n,1,0);var r=e.getImageData(1,0,1,1);s.canHandleAlpha=r.data[0]===n.data[0]&&r.data[1]===n.data[1]&&r.data[2]===n.data[2]&&r.data[3]===n.data[3]}e.globalCompositeOperation="multiply",s.canUseMultiply="multiply"===e.globalCompositeOperation,i.CanvasPool.removeByCanvas(t),PIXI.CanvasTinter.tintMethod=s.canUseMultiply?PIXI.CanvasTinter.tintWithMultiply:PIXI.CanvasTinter.tintWithPerPixel}(),function(){for(var t=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],e=document.createElement("div"),i=0;i=1)&&(s.touch=!0),(window.PointerEvent||window.MSPointerEvent||window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(s.mspointer=!0),s.cocoonJS||("onwheel"in window||s.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":s.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"))},i.Device.canPlayAudio=function(t){return!("mp3"!==t||!this.mp3)||(!("ogg"!==t||!this.ogg&&!this.opus)||(!("m4a"!==t||!this.m4a)||(!("opus"!==t||!this.opus)||(!("wav"!==t||!this.wav)||(!("webm"!==t||!this.webm)||!("mp4"!==t||!this.dolby))))))},i.Device.canPlayVideo=function(t){return!("webm"!==t||!this.webmVideo&&!this.vp9Video)||(!("mp4"!==t||!this.mp4Video&&!this.h264Video)||(!("ogg"!==t&&"ogv"!==t||!this.oggVideo)||!("mpeg"!==t||!this.hlsVideo)))},i.Device.needsTouchUnlock=function(){return!!(!this.cocoonJS&&(this.iOS||this.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)},i.Device.isAndroidStockBrowser=function(){var t=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return t&&t[1]<537},i.Canvas={create:function(t,e,s,n,r){e=e||256,s=s||256;var o=r?document.createElement("canvas"):i.CanvasPool.create(t,e,s);return"string"==typeof n&&""!==n&&(o.id=n),o.width=e,o.height=s,o.style.display="block",o},setBackgroundColor:function(t,e){return e=e||"rgb(0,0,0)",t.style.backgroundColor=e,t},setTouchAction:function(t,e){return e=e||"none",t.style.msTouchAction=e,t.style["ms-touch-action"]=e,t.style["touch-action"]=e,t},setUserSelect:function(t,e){return e=e||"none",t.style["-webkit-touch-callout"]=e,t.style["-webkit-user-select"]=e,t.style["-khtml-user-select"]=e,t.style["-moz-user-select"]=e,t.style["-ms-user-select"]=e,t.style["user-select"]=e,t.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",t},addToDOM:function(t,e,i){var s;return void 0===i&&(i=!0),e&&("string"==typeof e?s=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(s=e)),s||(s=document.body),i&&s.style&&(s.style.overflow="hidden"),s.appendChild(t),t},removeFromDOM:function(t){t.parentNode&&t.parentNode.removeChild(t)},setTransform:function(t,e,i,s,n,r,o){return t.setTransform(s,r,o,n,e,i),t},setSmoothingEnabled:function(t,e){var s=i.Canvas.getSmoothingPrefix(t);return s&&(t[s]=e),t},getSmoothingPrefix:function(t){var e=["i","webkitI","msI","mozI","oI"];for(var i in e){var s=e[i]+"mageSmoothingEnabled";if(s in t)return s}return null},getSmoothingEnabled:function(t){var e=i.Canvas.getSmoothingPrefix(t);if(e)return t[e]},setImageRenderingCrisp:function(t){for(var e=["-webkit-optimize-contrast","-moz-crisp-edges","crisp-edges","pixelated"],i=0;i0&&0==(t&t-1))return t;for(var e=1;e0&&0==(t&t-1)&&e>0&&0==(e&e-1)},random:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return Math.random()*(e-t)+t},between:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t},fuzzyEqual:function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)e-i},fuzzyCeil:function(t,e){return void 0===e&&(e=1e-4),Math.ceil(t-e)},fuzzyFloor:function(t,e){return void 0===e&&(e=1e-4),Math.floor(t+e)},average:function(){for(var t=0,e=arguments.length,i=0;i=i.Math.PI2-s?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=s:e=0?t:t+2*Math.PI},maxAdd:function(t,e,i){return Math.min(t+e,i)},minSub:function(t,e,i){return Math.max(t-e,i)},wrap:function(t,e,i){var s=i-e;if(s<=0)return 0;var n=(t-e)%s;return n<0&&(n+=s),n+e},wrapValue:function(t,e,i){return t=Math.abs(t),e=Math.abs(e),i=Math.abs(i),(t+e)%i},isOdd:function(t){return!!(1&t)},isEven:function(t){return!(1&t)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;et[i]&&(i=e);return t[i]},minProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;ie[s][t]&&(s=i);return e[s][t]},wrapAngle:function(t,e){return e?this.wrap(t,-Math.PI,Math.PI):this.wrap(t,-180,180)},linearInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return e<0?this.linear(t[0],t[1],s):e>1?this.linear(t[i],t[i-1],i-s):this.linear(t[n],t[n+1>i?i:n+1],s-n)},bezierInterpolation:function(t,e){for(var i=0,s=t.length-1,n=0;n<=s;n++)i+=Math.pow(1-e,s-n)*Math.pow(e,n)*t[n]*this.bernstein(s,n);return i},catmullRomInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return t[0]===t[i]?(e<0&&(n=Math.floor(s=i*(1+e))),this.catmullRom(t[(n-1+i)%i],t[n],t[(n+1)%i],t[(n+2)%i],s-n)):e<0?t[0]-(this.catmullRom(t[0],t[0],t[1],t[1],-s)-t[0]):e>1?t[i]-(this.catmullRom(t[i],t[i],t[i-1],t[i-1],s-i)-t[i]):this.catmullRom(t[n?n-1:0],t[n],t[i0?Math.ceil(t):Math.floor(t)},sinCosGenerator:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1);for(var n=e,r=i,o=s*Math.PI/t,a=[],h=[],l=0;l0?1:0},percent:function(t,e,i){return void 0===i&&(i=0),t>e||i>e?1:tt?0:(t-i)/e}},i.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},i.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e>>0,s=(e*=s)>>>0,s+=4294967296*(e-=s);return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},i.RandomDataGenerator.prototype.constructor=i.RandomDataGenerator,i.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},i.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new i.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new i.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new i.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new i.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null==this.nodes[0]||-1===(e=this.getIndex(t))){if(this.objects.push(t),this.objects.length>this.maxObjects&&this.levelthis.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.ythis.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof i.Rectangle)var e=this.objects,s=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,s=this.getIndex(t.body)}return this.nodes[0]&&(e=-1!==s?e.concat(this.nodes[s].retrieve(t)):(e=(e=(e=e.concat(this.nodes[0].retrieve(t))).concat(this.nodes[1].retrieve(t))).concat(this.nodes[2].retrieve(t))).concat(this.nodes[3].retrieve(t))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},i.QuadTree.prototype.constructor=i.QuadTree,i.Net=function(t){this.game=t},i.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},i.Net.prototype.constructor=i.Net,i.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:i.Easing.Power0,Power1:i.Easing.Power1,Power2:i.Easing.Power2,Power3:i.Easing.Power3,Power4:i.Easing.Power4,Linear:i.Easing.Linear.None,Quad:i.Easing.Quadratic.Out,Cubic:i.Easing.Cubic.Out,Quart:i.Easing.Quartic.Out,Quint:i.Easing.Quintic.Out,Sine:i.Easing.Sinusoidal.Out,Expo:i.Easing.Exponential.Out,Circ:i.Easing.Circular.Out,Elastic:i.Easing.Elastic.Out,Back:i.Easing.Back.Out,Bounce:i.Easing.Bounce.Out,"Quad.easeIn":i.Easing.Quadratic.In,"Cubic.easeIn":i.Easing.Cubic.In,"Quart.easeIn":i.Easing.Quartic.In,"Quint.easeIn":i.Easing.Quintic.In,"Sine.easeIn":i.Easing.Sinusoidal.In,"Expo.easeIn":i.Easing.Exponential.In,"Circ.easeIn":i.Easing.Circular.In,"Elastic.easeIn":i.Easing.Elastic.In,"Back.easeIn":i.Easing.Back.In,"Bounce.easeIn":i.Easing.Bounce.In,"Quad.easeOut":i.Easing.Quadratic.Out,"Cubic.easeOut":i.Easing.Cubic.Out,"Quart.easeOut":i.Easing.Quartic.Out,"Quint.easeOut":i.Easing.Quintic.Out,"Sine.easeOut":i.Easing.Sinusoidal.Out,"Expo.easeOut":i.Easing.Exponential.Out,"Circ.easeOut":i.Easing.Circular.Out,"Elastic.easeOut":i.Easing.Elastic.Out,"Back.easeOut":i.Easing.Back.Out,"Bounce.easeOut":i.Easing.Bounce.Out,"Quad.easeInOut":i.Easing.Quadratic.InOut,"Cubic.easeInOut":i.Easing.Cubic.InOut,"Quart.easeInOut":i.Easing.Quartic.InOut,"Quint.easeInOut":i.Easing.Quintic.InOut,"Sine.easeInOut":i.Easing.Sinusoidal.InOut,"Expo.easeInOut":i.Easing.Exponential.InOut,"Circ.easeInOut":i.Easing.Circular.InOut,"Elastic.easeInOut":i.Easing.Elastic.InOut,"Back.easeInOut":i.Easing.Back.InOut,"Bounce.easeInOut":i.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},i.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t,e){return e||(e=!1),this._tweens.some(function(i){return i.target===t&&(!e||i.isRunning&&!i.pendingDelete)})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},i.TweenManager.prototype.constructor=i.TweenManager,i.Tween=function(t,e,s){this.game=e,this.target=t,this.manager=s,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new i.Signal,this.onLoop=new i.Signal,this.onRepeat=new i.Signal,this.onChildComplete=new i.Signal,this.onComplete=new i.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=s.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},i.Tween.updateColor=function(t){i.Color.updateColor(t.target)},i.Tween.prototype={to:function(t,e,s,n,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).to(t,e,s,r,o,a)),n&&this.start(),this)},from:function(t,e,s,n,r,o,a){return void 0===e&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).from(t,e,s,r,o,a)),n&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),this.pendingDelete)return console.warn("Phaser.Tween.start cannot be called after Tween.stop"),this;if(null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(i=0;ithis.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(s=0;s0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t=this.startTime))return i.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var s in this.vEnd){var n=this.vStart[s],r=this.vEnd[s];Array.isArray(r)?this.parent.target[s]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[s]=n+(r-n)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():i.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction.call(this.interpolationContext,a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,i.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return i.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,i.TweenData.LOOPED}},i.TweenData.prototype.constructor=i.TweenData,i.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-i.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*i.Easing.Bounce.In(2*t):.5*i.Easing.Bounce.Out(2*t-1)+.5}}},i.Easing.Default=i.Easing.Linear.None,i.Easing.Power0=i.Easing.Linear.None,i.Easing.Power1=i.Easing.Quadratic.Out,i.Easing.Power2=i.Easing.Cubic.Out,i.Easing.Power3=i.Easing.Quartic.Out,i.Easing.Power4=i.Easing.Quintic.Out,i.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.updates=0,this.renders=0,this.fps=0,this.ups=0,this.rps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new i.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},i.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new i.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3){var t=this.now-this._timeLastSecond;this.fps=Math.round(1e3*this.frames/t),this.ups=Math.round(1e3*this.updates/t),this.rps=Math.round(1e3*this.renders/t),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0,this.updates=0,this.renders=0}},countUpdate:function(){this.advancedTiming&&this.updates++},countRender:function(){this.advancedTiming&&this.renders++},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(i.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),i.Time.prototype.constructor=i.Time,i.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new i.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},i.Timer.MINUTE=6e4,i.Timer.SECOND=1e3,i.Timer.HALF=500,i.Timer.QUARTER=250,i.Timer.prototype={create:function(t,e,s,n,r,o){var a=t=Math.round(t);0===this._now?a+=this.game.time.time:a+=this._now;var h=new i.TimerEvent(this,t,a,s,e,n,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.ticke.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i=e.tick)||e.pendingDelete)break;this._newTick=this._now+e.delay-(this._now-e.tick),this._newTick<0&&(this._newTick=this._now+e.delay),!0===e.loop?(e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):e.repeatCount>0?(e.repeatCount--,e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):(this._marked++,e.pendingDelete=!0,e.callback.apply(e.callbackContext,e.args)),this._i++}this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;ethis._now?this.nextTick-this._now:0}}),Object.defineProperty(i.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(i.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(i.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),i.Timer.prototype.constructor=i.Timer,i.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},i.TimerEvent.prototype.constructor=i.TimerEvent,i.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},i.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,s,n,r){return e=e||[],s=s||60,void 0===n&&(n=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new i.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,s,n),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;ithis._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},i.AnimationManager.prototype.constructor=i.AnimationManager,Object.defineProperty(i.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(i.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(i.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(i.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(i.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){var e;"number"==typeof t&&this._frameData&&(e=this._frameData.getFrame(t))&&(this.currentFrame=e,this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(i.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){var e;"string"==typeof t&&this._frameData&&(e=this._frameData.getFrameByName(t))?(this.currentFrame=e,this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame)):console.warn("Cannot set frameName: "+t)}}),i.Animation=function(t,e,s,n,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=n,this.name=s,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new i.Signal,this.onUpdate=null,this.onComplete=new i.Signal,this.onLoop=new i.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},i.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(s=0;s=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay?(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay):this._frameDiff=0,this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(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=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},i.Animation.prototype.constructor=i.Animation,Object.defineProperty(i.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(i.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(i.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(i.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(i.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(i.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new i.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),i.Animation.generateFrameNames=function(t,e,s,n,r){void 0===n&&(n="");var o=[],a="";if(e=s;h--)a=t+(a="number"==typeof r?i.Utils.pad(h.toString(),r,"0",1):h.toString())+n,o.push(a);return o},i.Frame=function(t,e,s,n,r,o){this.index=t,this.x=e,this.y=s,this.width=n,this.height=r,0!==this.width&&0!==this.height||console.warn('Phaser.Frame: Frame "'+this.name+'" has a width or height of zero'),this.name=o,this.centerX=Math.floor(n/2),this.centerY=Math.floor(r/2),this.distance=i.Math.distance(0,0,n,r),this.rotated=!1,this.trimmed=!1,this.sourceSizeW=n,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},i.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=i.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new i.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new i.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},i.Frame.prototype.constructor=i.Frame,i.FrameData=function(){this._frames=[],this._frameNames=[]},i.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new i.FrameData,e=0;ed||h<-d)return console.warn("Phaser.AnimationParser.spriteSheet: skipFrames = "+h.toString()+" is larger than total sprite number "+d.toString()),null;if(h<0&&(h=d+h),-1!==r&&(d=h+r),0===c||0===u||cc&&(f=o,g+=n+a);return p},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var s,n=new i.FrameData,r=e.frames,o=0;o tag")}},i.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{},compressedTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new i.Signal,this._cacheMap=[],this._cacheMap[i.Cache.CANVAS]=this._cache.canvas,this._cacheMap[i.Cache.IMAGE]=this._cache.image,this._cacheMap[i.Cache.TEXTURE]=this._cache.texture,this._cacheMap[i.Cache.SOUND]=this._cache.sound,this._cacheMap[i.Cache.TEXT]=this._cache.text,this._cacheMap[i.Cache.PHYSICS]=this._cache.physics,this._cacheMap[i.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[i.Cache.BINARY]=this._cache.binary,this._cacheMap[i.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[i.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[i.Cache.JSON]=this._cache.json,this._cacheMap[i.Cache.XML]=this._cache.xml,this._cacheMap[i.Cache.VIDEO]=this._cache.video,this._cacheMap[i.Cache.SHADER]=this._cache.shader,this._cacheMap[i.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this._pendingCount=0,this.onReady=new i.Signal,this._addImages()},i.Cache.CANVAS=1,i.Cache.IMAGE=2,i.Cache.TEXTURE=3,i.Cache.SOUND=4,i.Cache.TEXT=5,i.Cache.PHYSICS=6,i.Cache.TILEMAP=7,i.Cache.BINARY=8,i.Cache.BITMAPDATA=9,i.Cache.BITMAPFONT=10,i.Cache.JSON=11,i.Cache.XML=12,i.Cache.VIDEO=13,i.Cache.SHADER=14,i.Cache.RENDER_TEXTURE=15,i.Cache.DEFAULT=null,i.Cache.DEFAULT_KEY="__default",i.Cache.DEFAULT_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==",i.Cache.MISSING=null,i.Cache.MISSING_KEY="__missing",i.Cache.MISSING_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==",i.Cache.READY_TIMEOUT=1e3,i.Cache.prototype={addCompressedTextureMetaData:function(t,e,s,n){this.checkImageKey(t)&&this.removeImage(t);var r=s in i.LoaderParser?i.LoaderParser[s](n):n,o={key:t,url:e,data:r,base:new PIXI.BaseTexture(r,null,this.game.resolution),frame:new i.Frame(0,0,0,r.width,r.height,t),frameData:new i.FrameData,fileFormat:s};return o.frameData.addFrame(new i.Frame(0,0,0,r.width,r.height,e)),this._cache.image[t]=o,this._resolveURL(e,o),o},addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,s){this.checkImageKey(t)&&this.removeImage(t),!1===s.complete&&console.warn('Phaser.Cache.addImage: Image "'+t+"\" hasn't been retrieved yet");var n={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution),frame:new i.Frame(0,0,0,s.width,s.height,t),frameData:new i.FrameData};return n.frameData.addFrame(new i.Frame(0,0,0,s.width,s.height,e)),this._cache.image[t]=n,this._resolveURL(e,n),"__default"===t?i.Cache.DEFAULT=new PIXI.Texture(n.base):"__missing"===t&&(i.Cache.MISSING=new PIXI.Texture(n.base)),n},addImageAsync:function(t,e,i){var s=this,n=new Image;n.onload=function(){i.call(this,s.addImage(t,null,n)),s._removePending(),n.onload=null},this._addPending(),n.src=e},addDefaultImage:function(){this.addImageAsync(i.Cache.DEFAULT_KEY,i.Cache.DEFAULT_SRC,function(t){t.base.skipRender=!0,i.Cache.DEFAULT=new PIXI.Texture(t.base)})},addMissingImage:function(){this.addImageAsync(i.Cache.MISSING_KEY,i.Cache.MISSING_SRC,function(t){i.Cache.MISSING=new PIXI.Texture(t.base)})},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,s){return e.key=t,void 0===s&&(s=new i.FrameData).addFrame(e.textureFrame),this._cache.bitmapData[t]={data:e,frameData:s},e},addBitmapFont:function(t,e,s,n,r,o,a){var h={url:e,data:s,font:null,base:new PIXI.BaseTexture(s,null,this.game.resolution)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?i.LoaderParser.jsonBitmapFont(n,h.base,o,a,!1,this.game.resolution):i.LoaderParser.xmlBitmapFont(n,h.base,o,a,!1,this.game.resolution),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addBitmapFontFromAtlas:function(t,e,s,n,r,o,a){var h=this.getFrameByName(e,s);if(h){var l={font:null,base:this.getBaseTexture(e),frame:h};void 0===o&&(o=0),void 0===a&&(a=0);var c;"json"===r?(c=this.getJSON(n),l.font=i.LoaderParser.jsonBitmapFont(c,l.base,o,a,h,this.game.resolution)):(c=this.getXML(n),l.font=i.LoaderParser.xmlBitmapFont(c,l.base,o,a,h,this.game.resolution)),this._cache.bitmapFont[t]=l}},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new i.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,s,n,r,o,a,h,l){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var c={key:t,url:e,data:s,frameWidth:n,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(s,null,this.game.resolution),frameData:i.AnimationParser.spriteSheet(this.game,s,n,r,o,a,h,l)};this._cache.image[t]=c,this._resolveURL(e,c)},addTextureAtlas:function(t,e,s,n,r){var o={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution)};r===i.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=i.AnimationParser.XMLData(this.game,n,t):r===i.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=i.AnimationParser.JSONDataPyxel(this.game,n,t):Array.isArray(n.frames)?o.frameData=i.AnimationParser.JSONData(this.game,n,t):o.frameData=i.AnimationParser.JSONDataHash(this.game,n,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(i.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(i.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(i.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(i.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(i.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(i.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(i.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(i.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(i.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(i.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(i.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(i.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(i.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(i.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(i.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,i.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var s=this.getItem(t,i.Cache.IMAGE,"getImage");return null===s&&(s=this.getItem("__missing",i.Cache.IMAGE,"getImage")),e?s:s.data},getTextureFrame:function(t){return this.getItem(t,i.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,i.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,i.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,i.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,s){var n=this.getItem(t,i.Cache.PHYSICS,"getPhysicsData","data");if(null===n||void 0===e||null===e)return n;if(n[e]){var r=n[e];if(!r||!s)return r;for(var o in r)if((o=r[o]).fixtureKey===s)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+s+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,i.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,i.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,i.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,i.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var s=this.getItem(t,i.Cache.JSON,"getJSON","data");return s?e?i.Utils.extend(!0,Array.isArray(s)?[]:{},s):s:null},getXML:function(t){return this.getItem(t,i.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,i.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,i.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,i.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,s){void 0===s&&(s=i.Cache.IMAGE),this._cacheMap[s][t]&&(this._cacheMap[s][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){return(t=this._resolveURL(t))?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=i.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var s in this._cacheMap[t])"__default"!==s&&"__missing"!==s&&e.push(s);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.image[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t0?setTimeout(function(){t.isReady||(console.warn("Phaser.Cache: Still waiting for images after %s ms.",e),t._ready())},i.Cache.READY_TIMEOUT):this._ready()},_addPending:function(){this._pendingCount+=1},_removePending:function(){this._pendingCount-=1,this._checkReady()},_checkReady:function(){this.isReady&&this._ready()},_ready:function(){this._pendingCount=0,this.onReady.dispatch(this)}},i.Cache.prototype.constructor=i.Cache,Object.defineProperty(i.Cache.prototype,"isReady",{get:function(){return this._pendingCount<=0}}),i.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new i.Signal,this.onLoadComplete=new i.Signal,this.onPackComplete=new i.Signal,this.onFileStart=new i.Signal,this.onFileComplete=new i.Signal,this.onFileError=new i.Signal,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},i.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,i.Loader.TEXTURE_ATLAS_JSON_HASH=1,i.Loader.TEXTURE_ATLAS_XML_STARLING=2,i.Loader.PHYSICS_LIME_CORONA_JSON=3,i.Loader.PHYSICS_PHASER_JSON=4,i.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,i.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new i.Rectangle(0,0,1,t.height):new i.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r=e||t&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var n=this;setTimeout(function(){n.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.reset(),this.onLoadComplete.dispatch(),this.game.state&&this.game.state.loadComplete())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(e)for(var s=0;s=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},getVideoURL:function(t){for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s="error loading asset from URL "+(t.requestUrl||this.transformUrl(t.url,t));!i&&e&&(i=e.status),i&&(s=s+" ("+i+")"),this.asyncComplete(t,s)},fileComplete:function(t,e){var s=!0;switch(t.type){case"packfile":r=JSON.parse(e.responseText);t.data=r||{};break;case"texture":var n=/\.([^.]+)$/.exec(t.url.split("?",1)[0])[1].toLowerCase();null!==t.data?this.cache.addCompressedTextureMetaData(t.key,t.url,n,t.data):this.cache.addCompressedTextureMetaData(t.key,t.url,n,e.response);break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing,t.skipFrames);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(s=!1,t.format===i.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===i.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===i.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==i.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(s=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var r=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,r,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}s&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else(e=new ActiveXObject("Microsoft.XMLDOM")).async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(i.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return i.Math.clamp(t||0,0,100)}}),Object.defineProperty(i.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),i.Loader.prototype.constructor=i.Loader,i.LoaderParser={bitmapFont:function(t,e,i,s,n,r){return this.xmlBitmapFont(t,e,i,s,n,r)},xmlBitmapFont:function(t,e,i,s,n,r){null==r&&(r=1);var o={},a=t.getElementsByTagName("info")[0],h=t.getElementsByTagName("common")[0];o.font=a.getAttribute("face"),o.size=parseInt(a.getAttribute("size"),10),o.lineHeight=parseInt(h.getAttribute("lineHeight"),10)+s,o.chars={};for(var l=t.getElementsByTagName("char"),c=n?n.x:0,u=n?n.y:0,d=0;d=0){switch(r>=0&&r<=3?e="PVRTC":r>=7&&r<=11?e="S3TC":6===r&&(e="ETC1"),r){case 0:o=35841;break;case 1:o=35843;break;case 2:o=35840;break;case 3:o=35842;break;case 6:o=36196;break;case 7:o=33777;break;case 9:o=33778;break;case 11:o=33779;break;default:o=-1}n={complete:!0,fileFormat:"PVR",compressionAlgorithm:e,flags:i[1],pixelFormat:r,colorSpace:i[4],channelType:i[5],height:i[6],width:i[7],depth:i[8],numberOfSurfaces:i[9],numberOfFaces:i[10],numberOfMipmaps:i[11],metaDataSize:i[12],textureData:s.subarray(52+i[12],s.byteLength),glExtensionFormat:o}}return n},dds:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null;return 68===e[0]&&68===e[1]&&83===e[2]&&32===e[3]&&"DX10"===(s={complete:!0,fileFormat:"DDS",compressionAlgorithm:"S3TC",size:i[1],flags:i[2],height:i[3],width:i[4],pitch:i[5],depth:i[6],mipmapCount:i[7],formatSize:i[19],formatFlag:i[19],formatFourCC:[String.fromCharCode(e[84]),String.fromCharCode(e[85]),String.fromCharCode(e[86]),String.fromCharCode(e[87])].join(""),formatBitCount:i[21],formatRBitMask:i[22],formatGBitMask:i[23],formatBBitMask:i[24],formatABitMask:i[25],caps1:i[26],caps2:i[27],caps3:i[28],caps4:i[29],reserved2:i[30],DXGIFormat:null,resourceDimension:null,miscFlag:null,arraySize:null,textureData:e.subarray(i[1]+4,e.byteLength)}).formatFourCC&&(s.DXGIFormat=i[31],s.resourceDimension=i[32],s.miscFlag=i[33],s.arraySize=i[34],s.miscFlag=i[35]),s},ktx:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null,n=16+i[15]/4|0,r=i[n],o=i[7],a=0;if(171===e[0]&&75===e[1]&&84===e[2]&&88===e[3]&&32===e[4]&&49===e[5]&&49===e[6]&&187===e[7]&&13===e[8]&&10===e[9]&&26===e[10]&&10===e[11]&&[36196,35840,35841,35842,35843,33776,33777,33778,33779].indexOf(o)>=0){switch(o){case 36196:a="ETC1";break;case 35840:case 35841:case 35842:case 35843:a="PVRTC";break;case 33776:case 33777:case 33778:case 33779:a="S3TC"}s={complete:!0,fileFormat:"KTX",compressionAlgorithm:a,endianness:i[3],glType:i[4],glTypeSize:i[5],glFormat:i[6],glInternalFormat:i[7],glBaseInternalFormat:i[8],width:i[9],height:i[10],pixelDepth:i[11],numberOfArrayElements:i[12],numberOfFaces:i[13],numberOfMipmapLevels:i[14],bytesOfKeyValueData:i[15],keyAndValueByteSize:i[16],imageSize:r,textureData:e.subarray(4*(n+1),r+100)}}return s},pkm:function(t){var e=new Uint8Array(t),i=null;return 80===e[0]&&75===e[1]&&77===e[2]&&32===e[3]&&(i={complete:!0,fileFormat:"PKM",compressionAlgorithm:"ETC1",format:65535&(e[6]<<8|e[7]),width:65535&(e[8]<<8|e[9]),height:65535&(e[10]<<8|e[11]),originalWidth:65535&(e[12]<<8|e[13]),originalHeight:65535&(e[14]<<8|e[15]),textureData:e.subarray(16,e.length)}),i}},i.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},i.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},i.AudioSprite.prototype.constructor=i.AudioSprite,i.Sound=function(t,e,s,n,r){void 0===s&&(s=1),void 0===n&&(n=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=n,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this._globalVolume=1,this._markedToDelete=!1,this._removeFromSoundManager=!1,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=s,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new i.Signal,this.onPlay=new i.Signal,this.onPause=new i.Signal,this.onResume=new i.Signal,this.onLoop=new i.Signal,this.onStop=new i.Signal,this.onMute=new i.Signal,this.onMarkerComplete=new i.Signal,this.onFadeComplete=new i.Signal,this._volume=s,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},i.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop(),this._markedToDelete&&(this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode),this._removeFromSoundManager?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()))},update:function(){this.game.cache.checkSoundKey(this.key)?(this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))):this.destroy()},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){this.isPlaying&&!this.paused&&e!==this.volume&&(void 0===t&&(t=1e3),void 0!==e?(this.fadeTween=this.game.add.tween(this).to({volume:e},t,i.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)):console.warn("Phaser.Sound.fadeTo: No Volume Specified."))},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._globalVolume=t,this._sound.volume=this._globalVolume*this._volume)},destroy:function(t){void 0===t&&(t=!0),this._markedToDelete=!0,this._removeFromSoundManager=t,this.stop(),t?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())}},i.Sound.prototype.constructor=i.Sound,Object.defineProperty(i.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(i.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(i.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(i.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted?this._muteVolume=t:(this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=this._globalVolume*t))}}),i.SoundManager=function(t){this.game=t,this.onSoundDecode=new i.Signal,this.onVolumeChange=new i.Signal,this.onMute=new i.Signal,this.onUnMute=new i.Signal,this.onTouchUnlock=new i.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new i.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},i.SoundManager.prototype={boot:function(){var t=this.game.device,e=window.PhaserGlobal;if(t.iOS&&!1===t.webAudio&&(this.channels=1),e){if(!0===e.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===e.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(e&&e.audioContext)this.context=e.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||t.needsTouchUnlock()&&this.setTouchLock(),this.usingWebAudio&&t.chrome&&t.chromeVersion<=65&&console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. ')},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0)},setTouchUnlock:function(){this.touchLocked=!1,this._unlockSource=null,this.onTouchUnlock.dispatch()},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.setTouchUnlock();else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0),"suspended"===this._unlockSource.context.state&&this._unlockSource.context.resume()}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,s=this._parentBounds.height,n=this.getParentBounds(this._parentBounds),r=n.width!==e||n.height!==s,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,n),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottlee;return(h=h?s:!s)?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},i.ScaleManager.prototype.constructor=i.ScaleManager,Object.defineProperty(i.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(i.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(i.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(i.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),i.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.lineWidth=1,this.renderShadow=!0,this.currentColor=null,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1,this.isDisabled=!1,this._line=null,this._rect=null},i.Utils.Debug.prototype={boot:function(){this.game.renderType===i.CANVAS?this.context=this.game.context:(this.bmd=new i.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=i.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d")),this._line=new i.Line,this._rect=new i.Rectangle},resize:function(){this.bmd.resize(this.game.width,this.game.height),this.canvas.width=this.game.width,this.canvas.height=this.game.height},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e0)for(var e=0;e=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new i.Rectangle,layoutBounds:new i.Rectangle,documentBounds:new i.Rectangle},i.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},s=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(i.DOM,"scrollX",{get:e}),Object.defineProperty(i.DOM,"scrollY",{get:s}),Object.defineProperty(i.DOM.visualBounds,"x",{get:e}),Object.defineProperty(i.DOM.visualBounds,"y",{get:s}),Object.defineProperty(i.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(i.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var n=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(i.DOM.visualBounds,"width",{get:n}),Object.defineProperty(i.DOM.visualBounds,"height",{get:r}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:n}),Object.defineProperty(i.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(i.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(i.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(i.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(i.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(i.ArraySet.prototype,"next",{get:function(){return this.position=s||0===i)){null==i&&(i=1);for(var n=s-i,r=e;r0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=(t=i.ArrayUtils.transposeMatrix(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=i.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var s=0;s>>0:(t<<24|e<<16|s<<8|n)>>>0},unpackPixel:function(t,e,s,n){return void 0!==e&&null!==e||(e=i.Color.createColor()),void 0!==s&&null!==s||(s=!1),void 0!==n&&null!==n||(n=!1),i.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",s&&i.Color.RGBtoHSL(e.r,e.g,e.b,e),n&&i.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=i.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},hexToRGBArray:function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},RGBArrayToHex:function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},RGBtoHSL:function(t,e,s,n){n||(n=i.Color.createColor(t,e,s,1)),t/=255,e/=255,s/=255;var r=Math.min(t,e,s),o=Math.max(t,e,s);if(n.h=0,n.s=0,n.l=(o+r)/2,o!==r){var a=o-r;n.s=n.l>.5?a/(2-o-r):a/(o+r),o===t?n.h=(e-s)/a+(e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,s,n,r,o,a,h){var l={r:t||0,g:e||0,b:s||0,a:n||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return i.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toFixed()+","+t.g.toFixed()+","+t.b.toFixed()+","+t.a.toString()+")",t.color=i.Color.getColor(t.r,t.g,t.b),t.color32=i.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,s,n,r){return void 0===n&&(n=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+s).toString(16).slice(1):"0x"+i.Color.componentToHex(n)+i.Color.componentToHex(t)+i.Color.componentToHex(e)+i.Color.componentToHex(s)},hexToRGB:function(t){var e=i.Color.hexToColor(t);if(e)return i.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var s=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(s){var n=parseInt(s[1],16),r=parseInt(s[2],16),o=parseInt(s[3],16);e?(e.r=n,e.g=r,e.b=o):e=i.Color.createColor(n,r,o)}return e},webToColor:function(t,e){e||(e=i.Color.createColor());var s=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return s&&(e.r=~~Number(s[1]),e.g=~~Number(s[2]),e.b=~~Number(s[3]),e.a=void 0!==s[4]?Number(s[4]):1,i.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=i.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?i.Color.webToColor(t,e):(e.a=1,i.Color.hexToColor(t,e));if("number"==typeof t){var s=i.Color.getRGB(t);return e.r=s.r,e.g=s.g,e.b=s.b,e.a=s.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSVtoRGB(n/359,t,e));return s},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSLtoRGB(n/359,t,e));return s},interpolateColor:function(t,e,s,n,r,o){void 0===r&&(r=255),void 0===o&&(o=0);var a=i.Color.getRGB(t),h=i.Color.getRGB(e);if(0===o)var l=(h.red-a.red)*n/s+a.red,c=(h.green-a.green)*n/s+a.green,u=(h.blue-a.blue)*n/s+a.blue;if(1===o){var d,p=i.Color.RGBtoHSV(a.r,a.g,a.b),f=i.Color.RGBtoHSV(h.r,h.g,h.b),g=f.h-p.h;if(p.h>f.h){var m=f.h;f.h=p.h,p.h=m,g=-g,n=s-n}g>.5&&(p.h=p.h+1,d=((f.h-p.h)*n/s+p.h)%1),g<=.5&&(d=(f.h-p.h)*n/s+p.h);var y=(f.s-p.s)*n/s+p.s,v=(f.v-p.v)*n/s+p.v,x=i.Color.HSVtoRGB(d,y,v,x),l=x.r,c=x.g,u=x.b}return i.Color.getColor32(r,l,c,u)},interpolateColorWithRGB:function(t,e,s,n,r,o){var a=i.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(s-a.green)*o/r+a.green,c=(n-a.blue)*o/r+a.blue;return i.Color.getColor(h,l,c)},interpolateRGB:function(t,e,s,n,r,o,a,h){var l=(n-t)*h/a+t,c=(r-e)*h/a+e,u=(o-s)*h/a+s;return i.Color.getColor(l,c,u)},linear:function(t,e,i){return this.interpolateColor(t,e,1,i)},linearInterpolation:function(t,e){var s=i.Math.linear(0,t.length-1,e),n=t[Math.floor(s)],r=t[Math.ceil(s)];return this.linear(n,r,s%1)},getRandomColor:function(t,e,s){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===s&&(s=255),e>255||t>e)return i.Color.getColor(255,255,255);var n=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return i.Color.getColor32(s,n,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=i.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return i.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return i.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return i.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?i.Color.blendLinearBurn(t,2*e):i.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?i.Color.blendColorBurn(t,2*e):i.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?i.Color.blendDarken(t,2*e):i.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return i.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return i.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},i.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},i.Physics.ARCADE=0,i.Physics.P2JS=1,i.Physics.NINJA=2,i.Physics.BOX2D=3,i.Physics.CHIPMUNK=4,i.Physics.MATTERJS=5,i.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!i.Physics.hasOwnProperty("Arcade")||(this.arcade=new i.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&i.Physics.hasOwnProperty("Ninja")&&(this.ninja=new i.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&i.Physics.hasOwnProperty("P2")&&(this.p2=new i.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&i.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new i.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&i.Physics.hasOwnProperty("Matter")&&(this.matter=new i.Physics.Matter(this.game,this.config))},startSystem:function(t){t===i.Physics.ARCADE?this.arcade=new i.Physics.Arcade(this.game):t===i.Physics.P2JS?null===this.p2?this.p2=new i.Physics.P2(this.game,this.config):this.p2.reset():t===i.Physics.NINJA?this.ninja=new i.Physics.Ninja(this.game):t===i.Physics.BOX2D?null===this.box2d?this.box2d=new i.Physics.Box2D(this.game,this.config):this.box2d.reset():t===i.Physics.MATTERJS&&(null===this.matter?this.matter=new i.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,s){void 0===e&&(e=i.Physics.ARCADE),void 0===s&&(s=!1),e===i.Physics.ARCADE?this.arcade.enable(t):e===i.Physics.P2JS&&this.p2?this.p2.enable(t,s):e===i.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===i.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===i.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},i.Physics.prototype.constructor=i.Physics,i.Physics.Arcade=function(t){this.game=t,this.gravity=new i.Point,this.bounds=new i.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=i.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new i.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._total=0,this.setBoundsToWorld()},i.Physics.Arcade.prototype.constructor=i.Physics.Arcade,i.Physics.Arcade.SORT_NONE=0,i.Physics.Arcade.LEFT_RIGHT=1,i.Physics.Arcade.RIGHT_LEFT=2,i.Physics.Arcade.TOP_BOTTOM=3,i.Physics.Arcade.BOTTOM_TOP=4,i.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof i.Group?this.enable(t[s].children,e):(this.enableBody(t[s]),e&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],!0));else t instanceof i.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.Arcade.Body(t),t.parent&&t.parent instanceof i.Group&&t.parent.addToHash(t))},updateMotion:function(t){if(t.allowRotation){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed}t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&e.allowDrag&&(i-(n*=this.game.time.physicsElapsed)>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!0),this._total>0},collide:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!1),this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===i.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===i.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===i.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===i.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideObjects:function(t,e,i,s,n,r){if(!Array.isArray(t)&&Array.isArray(e))for(o=0;oa.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(t.body.bottoma.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,s,n,r,o)}}else{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(e);for(var c=this.quadTree.retrieve(t),h=0;hc.right)continue;if(c.x>a.right)break}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(a.bottomc.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,s,n,r)}}}}},collideGroupVsGroup:function(t,e,s,n,r,o){if(0!==t.length&&0!==e.length)for(var a=0;aa.bottom)&&(h.xa.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var s=i.Math.clamp(t.center.x,e.left,e.right),n=i.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-s)*(t.center.x-s)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},separateCircle:function(t,e,s){this.getOverlapX(t,e),this.getOverlapY(t,e);var n=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,n),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.center.x:e.center.x,y:t.isCircle?t.center.y:e.center.y,radius:t.isCircle?t.halfWidth:e.halfWidth};l.yh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.xh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.halfWidth+e.halfWidth-i.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(s||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.yMath.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x)>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0):t.deltaX()n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y)>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0):t.deltaY()n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,s,n,r,o){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(s);for(var a=new i.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c0&&(s=this.distanceBetween(t,e)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.setToPolar(n,e),n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},velocityFromAngle:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e,!0)},velocityFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerationFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(o,s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i,s){void 0===i&&(i=!1);var n,r;return s?(n=t.centerX-e.centerX,r=t.centerY-e.centerY):i?(n=t.world.x-e.world.x,r=t.world.y-e.world.y):(n=t.x-e.x,r=t.y-e.y),Math.sqrt(n*n+r*r)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},closest:function(t,e,i,s){for(var n=1/0,r=null,o=0,a=e.length;on&&(r=h,n=l)}return r},angleBetween:function(t,e,s){return void 0===s&&(s=!1),s?i.Point.angle(e.world,t.world):i.Point.angle(e,t)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},i.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=i.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new i.Point,this.position=new i.Point(t.x,t.y),this.prev=new i.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new i.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new i.Point,this.newVelocity=new i.Point,this.deltaMax=new i.Point,this.acceleration=new i.Point,this.allowDrag=!0,this.drag=new i.Point,this.allowGravity=!0,this.gravity=new i.Point,this.bounce=new i.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new i.Point(1e4,1e4),this.friction=new i.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=i.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.tilePadding=new i.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new i.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},i.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter())},updateCenter:function(){this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,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=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.none=!0,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.overlapR=0,this.overlapX=0,this.overlapY=0,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.updateCenter(),this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),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,this.updateCenter(),this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=this.velocity.atan()),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=i.LEFT:this.deltaX()>0&&(this.facing=i.RIGHT),this.deltaY()<0?this.facing=i.UP:this.deltaY()>0&&(this.facing=i.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.updateCenter(),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0,this.blocked.none=!1),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0,this.blocked.none=!1),!this.blocked.none},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.setToPolar(s,e),this.isMoving=!0,!0},moveTo:function(t,e,s){var n=e/(t/1e3);if(0===n)return!1;var r;return void 0===s?(r=this.angle,s=this.game.math.radToDeg(r)):r=this.game.math.degToRad(s),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new i.Line,this.moveEnd=new i.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===s||180===s?this.velocity.set(Math.cos(r)*n,0):90===s||270===s?this.velocity.set(0,Math.sin(r)*n):this.velocity.setToPolar(r,n),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,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(i,s),this.updateCenter(),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,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(e,i),this.updateCenter()):this.isCircle=!1},reset:function(t,e){this.stop(),this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this.updateBounds(),this.updateCenter()},stop:function(){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?i.Circle.contains(this,t,e):i.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},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},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof i.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(i.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),i.Physics.Arcade.Body.render=function(t,e,i,s,n){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,t.lineWidth=n||1,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.halfWidth,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},i.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},i.Physics.Arcade.Body.prototype.constructor=i.Physics.Arcade.Body,i.Physics.Arcade.TilemapCollision=function(){},i.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x-e.getTileOffsetX(),t.body.position.y-t.body.tilePadding.y-e.getTileOffsetY(),t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;ae.deltaAbsY()?l=-1:e.deltaAbsX()0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.getTileOffsetY();return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?(t.blocked.left=!0,t.blocked.none=!1):e>0&&(t.blocked.right=!0,t.blocked.none=!1),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?(t.blocked.up=!0,t.blocked.none=!1):e>0&&(t.blocked.down=!0,t.blocked.none=!1),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},i.Utils.mixinPrototype(i.Physics.Arcade.prototype,i.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,i.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new i.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new i.Signal,this.onBodyRemoved=new i.Signal,this.onSpringAdded=new i.Signal,this.onSpringRemoved=new i.Signal,this.onConstraintAdded=new i.Signal,this.onConstraintRemoved=new i.Signal,this.onContactMaterialAdded=new i.Signal,this.onContactMaterialRemoved=new i.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},i.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,s){void 0===e&&(e=!1),void 0===s&&(s=!0);var n=1;if(Array.isArray(t))for(n=t.length;n--;)t[n]instanceof i.Group?this.enable(t[n].children,e,s):(this.enableBody(t[n],e),s&&t[n].hasOwnProperty("children")&&t[n].children.length>0&&this.enable(t[n],e,!0));else t instanceof i.Group?this.enable(t.children,e,s):(this.enableBody(t,e),s&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);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.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.DistanceConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,s,n){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.GearConstraint(this,t,e,s,n));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),s=this.getBody(s),t&&s)return this.addConstraint(new i.Physics.P2.RevoluteConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,s,n,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.LockConstraint(this,t,e,s,n,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,s,n,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.PrismaticConstraint(this,t,e,s,n,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var s=new i.Physics.P2.Material(t);return this.materials.push(s),void 0!==e&&e.setMaterial(s),s},createContactMaterial:function(t,e,s){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var n=new i.Physics.P2.ContactMaterial(t,e,s);return this.addContactMaterial(n)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof i.Physics.P2.Body?t.data:t.body&&t.body.type===i.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,s,n){void 0===e&&(e=this.world.bodies),void 0===s&&(s=5),void 0===n&&(n=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof i.Physics.P2.Body&&(!n||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!n||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof i.Sprite&&e[a].hasOwnProperty("body")&&(!n||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,s)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var s=new i.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(s),t&&this.setCollisionGroup(t,s),s},setCollisionGroup:function(t,e){if(t instanceof i.Group)for(var s=0;s-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides?n+=u.width:((p=this.createBody(r,o,0,!1)).addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0)}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(i.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(i.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(i.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(i.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(i.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(i.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(i.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(i.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(i.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),i.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},i.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionGroup=t})},setMask:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionMask=t})},setSensor:function(t,e){this.getFixtures(e).forEach(function(e){e.sensor=t})},setMaterial:function(t,e){this.getFixtures(e).forEach(function(e){e.material=t})},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},i.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.PointProxy.prototype.constructor=i.Physics.P2.PointProxy,Object.defineProperty(i.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),i.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.InversePointProxy.prototype.constructor=i.Physics.P2.InversePointProxy,Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),i.Physics.P2.Body=function(t,e,s,n,r){e=e||null,s=s||0,n=n||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=i.Physics.P2JS,this.offset=new i.Point,this.data=new p2.Body({position:[this.world.pxmi(s),this.world.pxmi(n)],mass:r}),this.data.parent=this,this.velocity=new i.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new i.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new i.Point,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},i.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(r=0;r-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var n=this.getCollisionMask();if(void 0===i)for(var r=this.data.shapes.length-1;r>=0;r--)this.data.shapes[r].collisionMask=n;else i.collisionMask=n},collides:function(t,e,i,s){if(Array.isArray(t))for(r=0;r=0;r--)this.data.shapes[r].collisionMask=n;else s.collisionMask=n},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},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(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;np;n=0<=p?++d:--d)l=e.vertices[n],p2.vec2.rotate(u,l,t),c.push([(u[0]+a[0])*this.ppu,-(u[1]+a[1])*this.ppu]);this.drawConvex(h,c,e.triangles,16711680,i,r,this.settings.debugPolygons,[a[0]*this.ppu,-a[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)p=(c=e[l])[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return 2===(e=t.toString(16)).length?e:e+"0"}}),i.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1);var c={restLength:s=t.pxm(s),stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},i.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),i.Physics.P2.Material.prototype.constructor=i.Physics.P2.Material,i.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},i.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),i.Physics.P2.ContactMaterial.prototype.constructor=i.Physics.P2.ContactMaterial,i.Physics.P2.CollisionGroup=function(t){this.mask=t},i.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t;var a={distance:s=t.pxm(s),localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},i.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),i.Physics.P2.DistanceConstraint.prototype.constructor=i.Physics.P2.DistanceConstraint,i.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},i.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),i.Physics.P2.GearConstraint.prototype.constructor=i.Physics.P2.GearConstraint,i.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t;var o={localOffsetB:s=[t.pxm(s[0]),t.pxm(s[1])],localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},i.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),i.Physics.P2.LockConstraint.prototype.constructor=i.Physics.P2.LockConstraint,i.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t;var h={localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},i.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),i.Physics.P2.PrismaticConstraint.prototype.constructor=i.Physics.P2.PrismaticConstraint,i.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},i.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),i.Physics.P2.RevoluteConstraint.prototype.constructor=i.Physics.P2.RevoluteConstraint,i.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},i.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&tthis.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},i.Tile.prototype.constructor=i.Tile,Object.defineProperty(i.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(i.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(i.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(i.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(i.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(i.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),i.Tilemap=function(t,e,s,n,r,o){this.game=t,this.key=e;var a=i.TilemapParser.parse(this.game,e,s,n,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},i.Tilemap.CSV=0,i.Tilemap.TILED_JSON=1,i.Tilemap.NORTH=0,i.Tilemap.EAST=1,i.Tilemap.SOUTH=2,i.Tilemap.WEST=3,i.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,s,n,r,o,a){if(void 0===t)return null;void 0===s&&(s=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===s&&(s=32),0===n&&(n=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof i.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===i.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),console.log("Tilesets: ",this.tilesets),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new i.Tileset(t,a,s,n,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y1)for(u=0;uthis.layers.length)return console.warn('Tilemap.createLayer: Invalid layer ID given: "'+t+'"'),void console.log("Layers: ",this.layers);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===s||s<=0?s=Math.min(this.game.height,this.layers[r].heightInPixels):s>this.game.height&&(s=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",s),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=n.add(new i.TilemapLayer(this.game,this,r,e,s));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,s,n,r,o){void 0===o&&(o=this.game.world);{if(null===this.getLayerIndex(t)){for(var a,h={name:t,x:0,y:0,width:e,height:s,widthInPixels:e*n,heightInPixels:s*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;cthis.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height),(l=new i.TilemapLayer(this.game,this,this.layers.length-1,d,p)).name=t,o.add(l)}console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t)}},getIndex:function(t,e){for(var i=0;ie)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n-1&&this.collideIndexes.splice(n,1)}for(var r=0;r0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e-1},removeTile:function(t,e,s){if(s=this.getLayer(s),t>=0&&t=0&&e=0&&e=0&&s-1?this.layers[n].data[s][e].setCollision(!0,!0,!0,!0):this.layers[n].data[s][e].resetCollision(),this.layers[n].dirty=!0,this.calculateFaces(n),this.layers[n].data[s][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(r=this.layers[s].height-1;r>=0;r--)for(o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r=0&&t=0&&ethis.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},i.Tilemap.prototype.constructor=i.Tilemap,Object.defineProperty(i.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),i.TilemapLayer=function(t,e,s,n,r){n|=0,r|=0,i.Sprite.call(this,t,0,0),this.map=e,this.index=s,this.layer=e.layers[s],this.canvas=i.CanvasPool.create(this,n,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas,null,this.game.resolution))),this.type=i.TILEMAPLAYER,this.physicsType=i.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!0,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this.tileOffset=new i.Point(this.layer.offsetX||0,this.layer.offsetY||0),this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=i.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},i.TilemapLayer.prototype=Object.create(i.Sprite.prototype),i.TilemapLayer.prototype.constructor=i.TilemapLayer,i.TilemapLayer.prototype.preUpdateCore=i.Component.Core.preUpdate,i.TilemapLayer.sharedCopyCanvas=null,i.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=i.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},i.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},i.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y},i.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.TilemapLayer.prototype.destroy=function(){i.CanvasPool.remove(this),i.Component.Destroy.prototype.destroy.call(this)},i.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},i.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},i.TilemapLayer.prototype.getTileOffsetX=function(){return this.tileOffset.x||(this.fixedToCamera?0:this.position.x)},i.TilemapLayer.prototype.getTileOffsetY=function(){return this.tileOffset.y||(this.fixedToCamera?0:this.position.y)},i.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},i.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},i.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},i.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},i.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},i.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},i.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},i.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a=0;m++,v--,f+=c){m>=h&&(m-=h);var _=this.layer.data[m];for(g=b,y=n-i,p=x;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var w=_[g];if(w&&!(w.index<0)){var T=w.index,P=u[T];void 0===P&&(P=this.resolveTileset(T)),w.alpha===d||this.debug||(o.globalAlpha=w.alpha,d=w.alpha),P?w.rotation||w.flipped?(o.save(),o.translate(p+w.centerX,f+w.centerY),o.rotate(w.rotation),w.flipped&&o.scale(-1,1),P.draw(o,-w.centerX,-w.centerY,T),o.restore()):P.draw(o,p,f,T):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),w.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},i.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},i.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},i.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)=0;s++,r--,e+=f){s>=d&&(s-=d);var T=this.layer.data[s];for(i=_,n=m-g,t=x;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var P=T[i];!P||P.index<0||!P.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),P.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),P.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),P.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),P.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(i.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),i.TilemapParser={INSERT_NULL:!1,parse:function(t,e,s,n,r,o){if(void 0===s&&(s=32),void 0===n&&(n=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(s,n,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===i.Tilemap.CSV)return this.parseCSV(e,a.data,s,n);if(!a.format||a.format===i.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,s,n){for(var r=this.getEmptyData(),o=[],a=(e=e.trim()).split("\n"),h=a.length,l=0,c=0;c>>0;r.data=h,delete r.encoding}else if(r.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+r.name+"'");continue}k={name:r.name,x:r.x,y:r.y,width:r.width,height:r.height,widthInPixels:r.width*t.tilewidth,heightInPixels:r.height*t.tileheight,alpha:r.opacity,offsetX:r.offsetx,offsetY:r.offsety,visible:r.visible,properties:{},indexes:[],callbacks:[],bodies:[]};r.properties&&(k.properties=r.properties);for(var c,u,d,p=0,f=[],g=[],m=0,a=r.data.length;m536870912)switch(A>2147483648&&(A-=2147483648,d+=4),A>1073741824&&(A-=1073741824,d+=2),A>536870912&&(A-=536870912,d+=1),d){case 5:c=Math.PI/2;break;case 6:c=Math.PI;break;case 3:c=3*Math.PI/2;break;case 4:c=0,u=!0;break;case 7:c=Math.PI/2,u=!0;break;case 2:c=Math.PI,u=!0;break;case 1:c=3*Math.PI/2,u=!0}A>0?((F=new i.Tile(k,A,p,g.length,t.tilewidth,t.tileheight)).rotation=c,F.flipped=u,0!==d&&(F.flippedVal=d),f.push(F)):i.TilemapParser.INSERT_NULL?f.push(null):f.push(new i.Tile(k,-1,p,g.length,t.tilewidth,t.tileheight)),++p===r.width&&(g.push(f),p=0,f=[])}k.data=g,s.push(k)}e.layers=s;for(var y=[],n=0;n=0&&n+1=this.firstgid&&t=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(t=0;t=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._total>0&&this._counter>=this._total&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},i.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1),void 0===r&&(r=null);var o,a=0,h=t,l=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);athis.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},i.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),this.resetParticle(n,o,a),!0},i.Particles.Arcade.Emitter.prototype.getNextParticle=function(){for(var t=this.length;t--;){var e=this.next();if(!e.exists)return e}return null},i.Particles.Arcade.Emitter.prototype.resetParticle=function(t,e,i){var s=this.game.rnd;t.reset(e,i),t.angle=0,t.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(t):this.particleSendToBack&&this.sendToBack(t),this.autoScale?t.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?t.scale.set(s.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y?t.scale.set(s.realInRange(this._minParticleScale.x,this._maxParticleScale.x),s.realInRange(this._minParticleScale.y,this._maxParticleScale.y)):t.scale.set(this._minParticleScale.x,this._minParticleScale.y),this.autoAlpha?t.setAlphaData(this.alphaData):t.alpha=s.realInRange(this.minParticleAlpha,this.maxParticleAlpha),t.blendMode=this.blendMode;var n=t.body;n.updateBounds(),n.bounce.copyFrom(this.bounce),n.drag.copyFrom(this.particleDrag),null!=this.minAngle&&null!=this.maxAngle?this.game.physics.arcade.velocityFromAngle(this.minAngle===this.maxAngle?this.minAngle:s.between(this.minAngle,this.maxAngle),this.minSpeed===this.maxSpeed?this.minSpeed:s.between(this.minSpeed,this.maxSpeed),n.velocity):(n.velocity.x=s.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),n.velocity.y=s.between(this.minParticleSpeed.y,this.maxParticleSpeed.y)),n.angularVelocity=s.between(this.minRotation,this.maxRotation),n.gravity.copyFrom(this.gravity),n.angularDrag=this.angularDrag,t.onEmit()},i.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),i.Group.prototype.destroy.call(this,!0,!1)},i.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},i.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},i.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},i.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},i.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,s,n,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=0),void 0===n&&(n=i.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,s>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},s,n);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},i.Particles.Arcade.Emitter.prototype.setScale=function(t,e,s,n,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=1),void 0===n&&(n=1),void 0===r&&(r=0),void 0===o&&(o=i.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,s),this._maxParticleScale.set(e,n),this.autoScale=!1,r>0&&(t!==e||s!==n)){var h={x:t,y:s},l=this.game.make.tween(h).to({x:e,y:n},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},i.Particles.Arcade.Emitter.prototype.setAngle=function(t,e,i,s){return this.minAngle=t,this.maxAngle=e,null!=i&&(this.minSpeed=i),null!=s&&(this.maxSpeed=s),this},i.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"gravity",{get:function(){return this._gravity},set:function(t){"number"==typeof t?this._gravity.y=t:this._gravity=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"id",{get:function(){return this._id}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"output",{get:function(){return 1e3*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"lifespanOutput",{get:function(){return(0===this.lifespan?1/0:this.lifespan)*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"remainder",{get:function(){return this.maxParticles-this.lifespanOutput}}),i.Weapon=function(t,e){i.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new i.Rectangle(0,0,1,1),this.fireAngle=i.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new i.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=i.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=i.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new i.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new i.Signal,this.onKill=new i.Signal,this.onFireLimit=new i.Signal,this.trackedSprite=null,this.trackedPointer=null,this.multiFire=!1,this._hasFired=!1,this.trackRotation=!1,this.trackOffset=new i.Point,this._nextFire=0,this._tempNextFire=0,this._rotatedPoint=new i.Point},i.Weapon.prototype=Object.create(i.Plugin.prototype),i.Weapon.prototype.constructor=i.Weapon,i.Weapon.KILL_NEVER=0,i.Weapon.KILL_LIFESPAN=1,i.Weapon.KILL_DISTANCE=2,i.Weapon.KILL_WEAPON_BOUNDS=3,i.Weapon.KILL_CAMERA_BOUNDS=4,i.Weapon.KILL_WORLD_BOUNDS=5,i.Weapon.KILL_STATIC_BOUNDS=6,i.Weapon.prototype.createBullets=function(t,e,s,n){return void 0===t&&(t=1),void 0===n&&(n=this.game.world),this.bullets&&!this.bullets.game&&(this.bullets=null),this.bullets||(this.bullets=this.game.add.physicsGroup(i.Physics.ARCADE,n),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,s),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=s),this},i.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},i.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},i.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},i.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},i.Weapon.prototype.update=function(){this._bulletKillType===i.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},i.Weapon.prototype.postRender=function(){this.multiFire&&this._hasFired&&(this._hasFired=!1,this._nextFire=this._tempNextFire)},i.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},i.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},i.Weapon.prototype.fireMany=function(t,e){this.multiFire=!0;var i=[],s=this;return e||this.trackedSprite||this.trackedPointer?t.forEach(function(t){i.push(s.fire(e,null,null,t.x,t.y))}):t.forEach(function(t){i.push(s.fire(t))}),i},i.Weapon.prototype.fireOffset=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.fire(null,null,null,t,e)},i.Weapon.prototype.fire=function(t,e,s,n,r){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game.time.now0&&this.shots===this.fireLimit)return null;var o=this.bulletSpeed;0!==this.bulletSpeedVariance&&(o+=i.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.worldRotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(o+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y)),void 0!==n&&(this.fireFrom.x+=n),void 0!==r&&(this.fireFrom.y+=r);var a=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,h=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,l=this.trackRotation?this.trackedSprite.angle:this.fireAngle;null!==e&&null!==s&&(l=this.game.math.radToDeg(Math.atan2(s-h,e-a))),0!==this.bulletAngleVariance&&(l+=i.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var c=0,u=0;0===l||180===l?c=Math.cos(this.game.math.degToRad(l))*o:90===l||270===l?u=Math.sin(this.game.math.degToRad(l))*o:(c=Math.cos(this.game.math.degToRad(l))*o,u=Math.sin(this.game.math.degToRad(l))*o);var d=null;if(this.autoExpandBulletsGroup?(d=this.bullets.getFirstExists(!1,!0,a,h,this.bulletKey,this.bulletFrame)).data.bulletManager=this:d=this.bullets.getFirstExists(!1),d){if(d.reset(a,h),d.data.fromX=a,d.data.fromY=h,d.data.killType=this.bulletKillType,d.data.killDistance=this.bulletKillDistance,d.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===i.Weapon.KILL_LIFESPAN&&(d.lifespan=this.bulletLifespan),d.angle=l+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===d.animations.getAnimation(this.bulletAnimation)){var p=this.anims[this.bulletAnimation];d.animations.add(p.name,p.frames,p.frameRate,p.loop,p.useNumericIndex)}d.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(d.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(d.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);d.data.bodyDirty&&(this._data.customBody&&d.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),d.body.collideWorldBounds=this.bulletCollideWorldBounds,d.data.bodyDirty=!1),d.body.velocity.set(c,u),d.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y);var f=0;if(0!==this.bulletSpeedVariance){var g=this.fireRate;(g+=i.Math.between(-this.fireRateVariance,this.fireRateVariance))<0&&(g=0),f=this.game.time.now+g}else f=this.game.time.now+this.fireRate;this.multiFire?this._hasFired||(this._hasFired=!0,this._tempNextFire=f,this.shots++):(this._nextFire=f,this.shots++),this.onFire.dispatch(d,this,o),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return d},i.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},i.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},i.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},i.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},i.Weapon.prototype.setBulletFrames=function(t,e,s,n){return void 0===s&&(s=!0),void 0===n&&(n=!1),this.bulletFrames=i.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=s,this.bulletFrameRandom=n,this},i.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},i.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(i.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets&&(this.bullets.classType=this._bulletClass)}}),Object.defineProperty(i.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case i.Weapon.KILL_STATIC_BOUNDS:case i.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case i.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case i.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(i.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(i.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(i.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),i.Bullet=function(t,e,s,n,r){i.Sprite.call(this,t,e,s,n,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},i.Bullet.prototype=Object.create(i.Sprite.prototype),i.Bullet.prototype.constructor=i.Bullet,i.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},i.Bullet.prototype.update=function(){this.exists&&(this.data.killType>i.Weapon.KILL_LIFESPAN&&(this.data.killType===i.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=this.body.velocity.atan()),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},i.Video=function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=i.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new i.Signal,this.onChangeSource=new i.Signal,this.onComplete=new i.Signal,this.onAccess=new i.Signal,this.onError=new i.Signal,this.onTimeout=new i.Signal,this.onTouchUnlock=new i.Signal,this.playWhenUnlocked=!0,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._pendingChangeSource=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var n=this.game.cache.getVideo(e);n.isBlob?this.createVideoFromBlob(n.data):this.video=n.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else s&&this.createVideoFromURL(s,!1);this.video&&!s?(this.baseTexture=new PIXI.BaseTexture(this.video,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(i.Cache.DEFAULT.baseTexture.source,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new i.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,i.BitmapData&&(this.snapshot=new i.BitmapData(this.game,"",this.width,this.height)),this.game.device.needsTouchUnlock()?this.setTouchLock():n&&(n.locked=!1)},i.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return this._pendingChangeSource?this:(void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this)},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming)},setTouchLock:function(){this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.playWhenUnlocked&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return this.onTouchUnlock.dispatch(this),!0},grab:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null!==this.snapshot)return t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot;console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable")},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(i.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(i.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(i.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(i.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(i.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(i.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(i.Video.prototype,"playing",{get:function(){return!!this.video&&!(this.video.paused&&this.video.ended)}}),i.Video.prototype.constructor=i.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=i.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=i.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new i.Matrix),PIXI.TextureSilentFail=!0,PIXI.canUseNewCanvasBlendModes=function(){return i.Device.canUseMultiply},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=i),exports.Phaser=i):"undefined"!=typeof define&&define.amd?define("Phaser",e.Phaser=i):e.Phaser=i,i}.call(this); +//# sourceMappingURL=phaser.map \ No newline at end of file diff --git a/Digital Assignment 1/sources.txt b/Digital Assignment 1/sources.txt new file mode 100644 index 000000000..20406b50a --- /dev/null +++ b/Digital Assignment 1/sources.txt @@ -0,0 +1 @@ +Lips: https://static1.squarespace.com/static/568abdd11c1210fead12b8db/582e120d197aeaf29b9b0254/5849a7f6c534a5dc24e34fda/1481222135729/IMG_3135.jpg?format=500w \ No newline at end of file diff --git a/Digital Assignment 2/index.html b/Digital Assignment 2/index.html new file mode 100644 index 000000000..0b1137c4d --- /dev/null +++ b/Digital Assignment 2/index.html @@ -0,0 +1,27 @@ + + + + + Digital Assignment2 + + + + + +
+
+

Pass

+ +
+ + diff --git a/Digital Assignment 3/assets/background2.png b/Digital Assignment 3/assets/background2.png new file mode 100644 index 000000000..6a8fdf114 Binary files /dev/null and b/Digital Assignment 3/assets/background2.png differ diff --git a/Digital Assignment 3/assets/block.png b/Digital Assignment 3/assets/block.png new file mode 100644 index 000000000..3d3ffd206 Binary files /dev/null and b/Digital Assignment 3/assets/block.png differ diff --git a/Digital Assignment 3/assets/dude.png b/Digital Assignment 3/assets/dude.png new file mode 100644 index 000000000..6b35f4b4b Binary files /dev/null and b/Digital Assignment 3/assets/dude.png differ diff --git a/Digital Assignment 3/assets/star.png b/Digital Assignment 3/assets/star.png new file mode 100644 index 000000000..acec5a05e Binary files /dev/null and b/Digital Assignment 3/assets/star.png differ diff --git a/Digital Assignment 3/index.html b/Digital Assignment 3/index.html new file mode 100644 index 000000000..3743b171d --- /dev/null +++ b/Digital Assignment 3/index.html @@ -0,0 +1,143 @@ + + + + + Digital Assignment 3 + + + + + + + +
+
+

Pass (Was testing things but didn't get to finish)

+ + +
+ + diff --git a/Digital Assignment 3/js/main.js b/Digital Assignment 3/js/main.js new file mode 100644 index 000000000..03bf2a56f --- /dev/null +++ b/Digital Assignment 3/js/main.js @@ -0,0 +1,233 @@ +//"use strict"; + +window.onload = function() { + // You can copy-and-paste the code from any of the examples at http://examples.phaser.io here. + // You will need to change the fourth parameter to "new Phaser.Game()" from + // 'phaser-example' to 'game', which is the id of the HTML element where we + // want the game to go. + // The assets (and code) can be found at: https://github.com/photonstorm/phaser/tree/master/examples/assets + // You will need to change the paths you pass to "game.load.image()" or any other + // loading functions to reflect where you are putting the assets. + // All loading functions will typically all be found inside "preload()". + + // mods by Patrick OReilly + // twitter: @pato_reilly + + var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'game', { preload: preload, create: create, update: update }); + + function preload() { + + game.load.image('atari', 'assets/block.png'); + game.load.image('background', 'assets/background2.png'); + game.load.spritesheet('dude', 'assets/dude.png', 32, 48); + + } + + var sprite1; + var sprite2; + var sprite3; + var sprite4; + + function create() { + + game.stage.backgroundColor = '#2d2d2d'; + + game.physics.startSystem(Phaser.Physics.ARCADE); + + // Set the world (global) gravity + game.physics.arcade.gravity.y = 100; + + // Sprite 1 will use the World (global) gravity + sprite1 = game.add.sprite(100, 96, 'ilkke'); + + // Sprite 2 is set to ignore the global gravity and use its own value + sprite2 = game.add.sprite(300, 96, 'ilkke'); + + // Sprite 3 will use both the world gravity and its own gravityScale modifier + sprite3 = game.add.sprite(500, 96, 'ilkke'); + + // Sprite 4 will ignore all gravity + sprite4 = game.add.sprite(700, 96, 'ilkke'); + + // Enable physics on those sprites + game.physics.enable( [ sprite1, sprite2, sprite3, sprite4 ], Phaser.Physics.ARCADE); + + sprite1.body.collideWorldBounds = true; + sprite1.body.bounce.y = 0.8; + + sprite2.body.collideWorldBounds = true; + sprite2.body.bounce.y = 0.8; + sprite2.body.gravity.y = 200; + + sprite3.body.collideWorldBounds = true; + sprite3.body.bounce.y = 0.8; + sprite3.body.gravity.y = 50; + + sprite4.body.allowGravity = false; + + } + + function render() { + + game.debug.text('world gravity', sprite1.x - 32, 64); + game.debug.text('local gravity', sprite2.x - 32, 64); + game.debug.text('local / 2', sprite3.x - 32, 64); + game.debug.text('no gravity', sprite4.x - 32, 64); + + } + + /////////////////////////////////////////////////// + /////////////////////////////////////////////////// + + var sprite; + + var player; + var facing = 'left'; + var jumpTimer = 0; + var cursors; + var jumpButton; + var yAxis = p2.vec2.fromValues(0, 1); + + function create() { + + bg = game.add.tileSprite(0, 0, 800, 600, 'background'); + + // Enable p2 physics + game.physics.startSystem(Phaser.Physics.P2JS); + + game.physics.p2.gravity.y = 350; + game.physics.p2.world.defaultContactMaterial.friction = 0.3; + game.physics.p2.world.setGlobalStiffness(1e5); + + // Add a sprite + player = game.add.sprite(200, 200, 'dude'); + player.animations.add('left', [0, 1, 2, 3], 10, true); + player.animations.add('turn', [4], 20, true); + player.animations.add('right', [5, 6, 7, 8], 10, true); + + // Enable if for physics. This creates a default rectangular body. + game.physics.p2.enable(player); + + player.body.fixedRotation = true; + player.body.damping = 0.5; + + var spriteMaterial = game.physics.p2.createMaterial('spriteMaterial', player.body); + var worldMaterial = game.physics.p2.createMaterial('worldMaterial'); + var boxMaterial = game.physics.p2.createMaterial('worldMaterial'); + + // 4 trues = the 4 faces of the world in left, right, top, bottom order + game.physics.p2.setWorldMaterial(worldMaterial, true, true, true, true); + + // A stack of boxes - you'll stick to these + for (var i = 1; i < 4; i++) + { + var box = game.add.sprite(300, 645 - (95 * i), 'atari'); + game.physics.p2.enable(box); + box.body.mass = 6; + // box.body.static = true; + box.body.setMaterial(boxMaterial); + } + + // Here is the contact material. It's a combination of 2 materials, so whenever shapes with + // those 2 materials collide it uses the following settings. + + var groundPlayerCM = game.physics.p2.createContactMaterial(spriteMaterial, worldMaterial, { friction: 0.0 }); + var groundBoxesCM = game.physics.p2.createContactMaterial(worldMaterial, boxMaterial, { friction: 0.6 }); + + // Here are some more options you can set: + + // contactMaterial.friction = 0.0; // Friction to use in the contact of these two materials. + // contactMaterial.restitution = 0.0; // Restitution (i.e. how bouncy it is!) to use in the contact of these two materials. + // contactMaterial.stiffness = 1e3; // Stiffness of the resulting ContactEquation that this ContactMaterial generate. + // contactMaterial.relaxation = 0; // Relaxation of the resulting ContactEquation that this ContactMaterial generate. + // contactMaterial.frictionStiffness = 1e7; // Stiffness of the resulting FrictionEquation that this ContactMaterial generate. + // contactMaterial.frictionRelaxation = 3; // Relaxation of the resulting FrictionEquation that this ContactMaterial generate. + // contactMaterial.surfaceVelocity = 0.0; // Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + + text = game.add.text(20, 20, 'move with arrow, space to jump', { fill: '#ffffff' }); + + cursors = game.input.keyboard.createCursorKeys(); + jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); + + } + + function update() { + + if (cursors.left.isDown) + { + player.body.moveLeft(200); + + if (facing != 'left') + { + player.animations.play('left'); + facing = 'left'; + } + } + else if (cursors.right.isDown) + { + player.body.moveRight(200); + + if (facing != 'right') + { + player.animations.play('right'); + facing = 'right'; + } + } + else + { + player.body.velocity.x = 0; + + if (facing != 'idle') + { + player.animations.stop(); + + if (facing == 'left') + { + player.frame = 0; + } + else + { + player.frame = 5; + } + + facing = 'idle'; + } + } + + if (jumpButton.isDown && game.time.now > jumpTimer && checkIfCanJump()) + { + player.body.moveUp(300); + jumpTimer = game.time.now + 750; + } + + } + + function checkIfCanJump() { + + var result = false; + + for (var i=0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++) + { + var c = game.physics.p2.world.narrowphase.contactEquations[i]; + + if (c.bodyA === player.body.data || c.bodyB === player.body.data) + { + var d = p2.vec2.dot(c.normalA, yAxis); + + if (c.bodyA === player.body.data) + { + d *= -1; + } + + if (d > 0.5) + { + result = true; + } + } + } + + return result; + + } + +}; diff --git a/Digital Assignment 3/js/phaser.js b/Digital Assignment 3/js/phaser.js new file mode 100644 index 000000000..3bac171a7 --- /dev/null +++ b/Digital Assignment 3/js/phaser.js @@ -0,0 +1,107825 @@ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +* +* @overview +* +* Phaser - http://phaser.io +* +* v2.10.0 "2018-01-18" - Built: Thu Jan 18 2018 16:35:03 +* +* By Richard Davey http://www.photonstorm.com @photonstorm +* +* Phaser is a fun, free and fast 2D game framework for making HTML5 games +* for desktop and mobile web browsers, supporting Canvas and WebGL rendering. +* +* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23 +* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe +* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com +* +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate. +* +* Follow development at http://phaser.io and on our forum +* +* "If you want your children to be intelligent, read them fairy tales." +* "If you want them to be more intelligent, read them more fairy tales." +* -- Albert Einstein +*/ + +/** + * The MIT License (MIT) + * + * Copyright (c) 2015 p2.js authors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=0 && s<=1 && t>=0 && t<=1); +}; + + +},{"./Scalar":4}],2:[function(_dereq_,module,exports){ +module.exports = Point; + +/** + * Point related functions + * @class Point + */ +function Point(){}; + +/** + * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. + * @static + * @method area + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +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 = []; + +/** + * Check if three points are collinear + * @method collinear + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. + * @return {Boolean} + */ +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 angle < thresholdAngle; + } +}; + +Point.sqdist = function(a,b){ + var dx = b[0] - a[0]; + var dy = b[1] - a[1]; + return dx * dx + dy * dy; +}; + +},{}],3:[function(_dereq_,module,exports){ +var Line = _dereq_("./Line") +, Point = _dereq_("./Point") +, Scalar = _dereq_("./Scalar") + +module.exports = Polygon; + +/** + * Polygon class. + * @class Polygon + * @constructor + */ +function Polygon(){ + + /** + * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] + * @property vertices + * @type {Array} + */ + this.vertices = []; +} + +/** + * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. + * @method at + * @param {Number} i + * @return {Array} + */ +Polygon.prototype.at = function(i){ + var v = this.vertices, + s = v.length; + return v[i < 0 ? i % s + s : i % s]; +}; + +/** + * Get first vertex + * @method first + * @return {Array} + */ +Polygon.prototype.first = function(){ + return this.vertices[0]; +}; + +/** + * Get last vertex + * @method last + * @return {Array} + */ +Polygon.prototype.last = function(){ + return this.vertices[this.vertices.length-1]; +}; + +/** + * Clear the polygon data + * @method clear + * @return {Array} + */ +Polygon.prototype.clear = function(){ + this.vertices.length = 0; +}; + +/** + * Append points "from" to "to"-1 from an other polygon "poly" onto this one. + * @method append + * @param {Polygon} poly The polygon to get points from. + * @param {Number} from The vertex index in "poly". + * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. + * @return {Array} + */ +Polygon.prototype.append = function(poly,from,to){ + if(typeof(from) == "undefined") throw new Error("From is not given!"); + if(typeof(to) == "undefined") throw new Error("To is not given!"); + + if(to-1 < from) throw new Error("lol1"); + if(to > poly.vertices.length) throw new Error("lol2"); + if(from < 0) throw new Error("lol3"); + + for(var i=from; i v[br][0])) { + br = i; + } + } + + // reverse poly if clockwise + if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { + this.reverse(); + } +}; + +/** + * Reverse the vertices in the polygon + * @method 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; +}; + +/** + * Check if a point in the polygon is a reflex point + * @method isReflex + * @param {Number} i + * @return {Boolean} + */ +Polygon.prototype.isReflex = function(i){ + return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); +}; + +var tmpLine1=[], + tmpLine2=[]; + +/** + * Check if two vertices in the polygon can see each other + * @method canSee + * @param {Number} a Vertex index 1 + * @param {Number} b Vertex index 2 + * @return {Boolean} + */ +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) { // for each edge + if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges + 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))) { // if diag intersects an edge + 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) < dist) { // if edge is blocking visibility to b + return false; + } + } + } + + return true; +}; + +/** + * Copy the polygon from vertex i to vertex j. + * @method copy + * @param {Number} i + * @param {Number} j + * @param {Polygon} [targetPoly] Optional target polygon to save in. + * @return {Polygon} The resulting copy. + */ +Polygon.prototype.copy = function(i,j,targetPoly){ + var p = targetPoly || new Polygon(); + p.clear(); + if (i < j) { + // Insert all vertices from i to j + for(var k=i; k<=j; k++) + p.vertices.push(this.vertices[k]); + + } else { + + // Insert vertices 0 to j + for(var k=0; k<=j; k++) + p.vertices.push(this.vertices[k]); + + // Insert vertices i to end + for(var k=i; k 0) + return this.slice(edges); + else + return [this]; +}; + +/** + * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. + * @method slice + * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() + * @return {Array} + */ +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; i maxlevel){ + console.warn("quickDecomp: max level ("+maxlevel+") reached."); + return result; + } + + for (var i = 0; i < this.vertices.length; ++i) { + if (poly.isReflex(i)) { + reflexVertices.push(poly.vertices[i]); + upperDist = lowerDist = Number.MAX_VALUE; + + + for (var j = 0; j < this.vertices.length; ++j) { + if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge + p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection + if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly + d = Point.sqdist(poly.vertices[i], p); + if (d < lowerDist) { // keep only the closest intersection + lowerDist = d; + lowerInt = p; + lowerIndex = j; + } + } + } + if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); + if (Point.left(poly.at(i - 1), poly.at(i), p)) { + d = Point.sqdist(poly.vertices[i], p); + if (d < upperDist) { + upperDist = d; + upperInt = p; + upperIndex = j; + } + } + } + } + + // if there are no vertices to connect to, choose a point in the middle + if (lowerIndex == (upperIndex + 1) % this.vertices.length) { + //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); + p[0] = (lowerInt[0] + upperInt[0]) / 2; + p[1] = (lowerInt[1] + upperInt[1]) / 2; + steinerPoints.push(p); + + if (i < upperIndex) { + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); + lowerPoly.append(poly, i, upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + if (lowerIndex != 0){ + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); + upperPoly.append(poly,lowerIndex,poly.vertices.length); + } + //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); + lowerPoly.append(poly,i,poly.vertices.length); + } + //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); + lowerPoly.append(poly,0,upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); + upperPoly.append(poly,lowerIndex,i+1); + } + } else { + // connect to the closest point within the triangle + //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); + + if (lowerIndex > upperIndex) { + upperIndex += this.vertices.length; + } + closestDist = Number.MAX_VALUE; + + if(upperIndex < lowerIndex){ + return result; + } + + for (var j = lowerIndex; j <= upperIndex; ++j) { + if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + d = Point.sqdist(poly.at(i), poly.at(j)); + if (d < closestDist) { + closestDist = d; + closestIndex = j % this.vertices.length; + } + } + } + + if (i < closestIndex) { + lowerPoly.append(poly,i,closestIndex+1); + if (closestIndex != 0){ + upperPoly.append(poly,closestIndex,v.length); + } + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + lowerPoly.append(poly,i,v.length); + } + lowerPoly.append(poly,0,closestIndex+1); + upperPoly.append(poly,closestIndex,i+1); + } + } + + // solve smallest poly first + if (lowerPoly.vertices.length < upperPoly.vertices.length) { + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } else { + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } + + return result; + } + } + result.push(this); + + return result; +}; + +/** + * Remove collinear points in the polygon. + * @method removeCollinearPoints + * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. + * @return {Number} The number of points removed + */ +Polygon.prototype.removeCollinearPoints = function(precision){ + var num = 0; + for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ + if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ + // Remove the middle point + this.vertices.splice(i%this.vertices.length,1); + i--; // Jump one point forward. Otherwise we may get a chain removal + num++; + } + } + return num; +}; + +},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){ +module.exports = Scalar; + +/** + * Scalar functions + * @class Scalar + */ +function Scalar(){} + +/** + * Check if two scalars are equal + * @static + * @method eq + * @param {Number} a + * @param {Number} b + * @param {Number} [precision] + * @return {Boolean} + */ +Scalar.eq = function(a,b,precision){ + precision = precision || 0; + return Math.abs(a-b) < precision; +}; + +},{}],5:[function(_dereq_,module,exports){ +module.exports = { + Polygon : _dereq_("./Polygon"), + Point : _dereq_("./Point"), +}; + +},{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){ +module.exports={ + "name": "p2", + "version": "0.7.1", + "description": "A JavaScript 2D physics engine.", + "author": "Stefan Hedman (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.5", + "grunt-contrib-jshint": "^0.11.2", + "grunt-contrib-nodeunit": "^0.4.1", + "grunt-contrib-uglify": "~0.4.0", + "grunt-contrib-watch": "~0.5.0", + "grunt-browserify": "~2.0.1", + "grunt-contrib-concat": "^0.4.0" + }, + "dependencies": { + "poly-decomp": "0.1.1" + } +} + +},{}],7:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = AABB; + +/** + * Axis aligned bounding box class. + * @class AABB + * @constructor + * @param {Object} [options] + * @param {Array} [options.upperBound] + * @param {Array} [options.lowerBound] + */ +function AABB(options){ + + /** + * The lower bound of the bounding box. + * @property lowerBound + * @type {Array} + */ + this.lowerBound = vec2.create(); + if(options && options.lowerBound){ + vec2.copy(this.lowerBound, options.lowerBound); + } + + /** + * The upper bound of the bounding box. + * @property upperBound + * @type {Array} + */ + this.upperBound = vec2.create(); + if(options && options.upperBound){ + vec2.copy(this.upperBound, options.upperBound); + } +} + +var tmp = vec2.create(); + +/** + * Set the AABB bounds from a set of points, transformed by the given position and angle. + * @method setFromPoints + * @param {Array} points An array of vec2's. + * @param {Array} position + * @param {number} angle + * @param {number} skinSize Some margin to be added to the AABB. + */ +AABB.prototype.setFromPoints = function(points, position, angle, skinSize){ + var l = this.lowerBound, + u = this.upperBound; + + if(typeof(angle) !== "number"){ + angle = 0; + } + + // Set to the first point + if(angle !== 0){ + vec2.rotate(l, points[0], angle); + } else { + vec2.copy(l, points[0]); + } + vec2.copy(u, l); + + // Compute cosines and sines just once + var cosAngle = Math.cos(angle), + sinAngle = Math.sin(angle); + for(var i = 1; i u[j]){ + u[j] = p[j]; + } + if(p[j] < l[j]){ + l[j] = p[j]; + } + } + } + + // Add offset + if(position){ + vec2.add(this.lowerBound, this.lowerBound, position); + vec2.add(this.upperBound, this.upperBound, position); + } + + if(skinSize){ + this.lowerBound[0] -= skinSize; + this.lowerBound[1] -= skinSize; + this.upperBound[0] += skinSize; + this.upperBound[1] += skinSize; + } +}; + +/** + * Copy bounds from an AABB to this AABB + * @method copy + * @param {AABB} aabb + */ +AABB.prototype.copy = function(aabb){ + vec2.copy(this.lowerBound, aabb.lowerBound); + vec2.copy(this.upperBound, aabb.upperBound); +}; + +/** + * Extend this AABB so that it covers the given AABB too. + * @method extend + * @param {AABB} aabb + */ +AABB.prototype.extend = function(aabb){ + // Loop over x and y + var i = 2; + while(i--){ + // Extend lower bound + var l = aabb.lowerBound[i]; + if(this.lowerBound[i] > l){ + this.lowerBound[i] = l; + } + + // Upper + var u = aabb.upperBound[i]; + if(this.upperBound[i] < u){ + this.upperBound[i] = u; + } + } +}; + +/** + * Returns true if the given AABB overlaps this AABB. + * @method overlaps + * @param {AABB} aabb + * @return {Boolean} + */ +AABB.prototype.overlaps = function(aabb){ + var l1 = this.lowerBound, + u1 = this.upperBound, + l2 = aabb.lowerBound, + u2 = aabb.upperBound; + + // l2 u2 + // |---------| + // |--------| + // l1 u1 + + 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])); +}; + +/** + * @method containsPoint + * @param {Array} point + * @return {boolean} + */ +AABB.prototype.containsPoint = function(point){ + var l = this.lowerBound, + u = this.upperBound; + return l[0] <= point[0] && point[0] <= u[0] && l[1] <= point[1] && point[1] <= u[1]; +}; + +/** + * Check if the AABB is hit by a ray. + * @method overlapsRay + * @param {Ray} ray + * @return {number} -1 if no hit, a number between 0 and 1 if hit. + */ +AABB.prototype.overlapsRay = function(ray){ + var t = 0; + + // ray.direction is unit direction vector of ray + var dirFracX = 1 / ray.direction[0]; + var dirFracY = 1 / ray.direction[1]; + + // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner + var t1 = (this.lowerBound[0] - ray.from[0]) * dirFracX; + var t2 = (this.upperBound[0] - ray.from[0]) * dirFracX; + var t3 = (this.lowerBound[1] - ray.from[1]) * dirFracY; + var t4 = (this.upperBound[1] - ray.from[1]) * dirFracY; + + var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4))); + var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4))); + + // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us + if (tmax < 0){ + //t = tmax; + return -1; + } + + // if tmin > tmax, ray doesn't intersect AABB + if (tmin > tmax){ + //t = tmax; + return -1; + } + + return tmin; +}; +},{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Body = _dereq_('../objects/Body'); + +module.exports = Broadphase; + +/** + * Base class for broadphase implementations. + * @class Broadphase + * @constructor + */ +function Broadphase(type){ + + this.type = type; + + /** + * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). + * @property result + * @type {Array} + */ + this.result = []; + + /** + * The world to search for collision pairs in. To change it, use .setWorld() + * @property world + * @type {World} + * @readOnly + */ + this.world = null; + + /** + * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE. + * @property {Number} boundingVolumeType + */ + this.boundingVolumeType = Broadphase.AABB; +} + +/** + * Axis aligned bounding box type. + * @static + * @property {Number} AABB + */ +Broadphase.AABB = 1; + +/** + * Bounding circle type. + * @static + * @property {Number} BOUNDING_CIRCLE + */ +Broadphase.BOUNDING_CIRCLE = 2; + +/** + * Set the world that we are searching for collision pairs in. + * @method setWorld + * @param {World} world + */ +Broadphase.prototype.setWorld = function(world){ + this.world = world; +}; + +/** + * Get all potential intersecting body pairs. + * @method getCollisionPairs + * @param {World} world The world to search in. + * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). + */ +Broadphase.prototype.getCollisionPairs = function(world){}; + +var dist = vec2.create(); + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.aabbCheck = function(bodyA, bodyB){ + return bodyA.getAABB().overlaps(bodyB.getAABB()); +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether two bodies are allowed to collide at all. + * @method canCollide + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.canCollide = function(bodyA, bodyB){ + var KINEMATIC = Body.KINEMATIC; + var STATIC = Body.STATIC; + + // Cannot collide static bodies + if(bodyA.type === STATIC && bodyB.type === STATIC){ + return false; + } + + // Cannot collide static vs kinematic bodies + if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) || + (bodyA.type === STATIC && bodyB.type === KINEMATIC)){ + return false; + } + + // Cannot collide kinematic vs kinematic + if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){ + return false; + } + + // Cannot collide both sleeping bodies + if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ + return false; + } + + // Cannot collide if one is static and the other is sleeping + if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === STATIC) || + (bodyB.sleepState === Body.SLEEPING && bodyA.type === STATIC)){ + return false; + } + + return true; +}; + +Broadphase.NAIVE = 1; +Broadphase.SAP = 2; + +},{"../math/vec2":30,"../objects/Body":31}],9:[function(_dereq_,module,exports){ +var Circle = _dereq_('../shapes/Circle'), + Plane = _dereq_('../shapes/Plane'), + Shape = _dereq_('../shapes/Shape'), + Particle = _dereq_('../shapes/Particle'), + Broadphase = _dereq_('../collision/Broadphase'), + vec2 = _dereq_('../math/vec2'); + +module.exports = NaiveBroadphase; + +/** + * Naive broadphase implementation. Does N^2 tests. + * + * @class NaiveBroadphase + * @constructor + * @extends Broadphase + */ +function NaiveBroadphase(){ + Broadphase.call(this, Broadphase.NAIVE); +} +NaiveBroadphase.prototype = new Broadphase(); +NaiveBroadphase.prototype.constructor = NaiveBroadphase; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +NaiveBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = world.bodies, + result = this.result; + + result.length = 0; + + for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ + var bi = bodies[i]; + + for(var j=0; j pos0 && pos < pos1){ + // We got contact! + + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape); + + vec2.scale(c.normalA, orthoDist, -1); + vec2.normalize(c.normalA, c.normalA); + + vec2.scale( c.contactPointA, c.normalA, circleRadius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + sub(c.contactPointB, projectedPoint, lineOffset); + add(c.contactPointB, c.contactPointB, lineOffset); + sub(c.contactPointB, c.contactPointB, lineBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; + } + } + + // Add corner + verts[0] = worldVertex0; + verts[1] = worldVertex1; + + for(var i=0; i 0){ + for(var i=0; i Math.pow(r,2)){ + return 0; + } + + if(justTest){ + return true; + } + + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + 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; +}; + +/** + * Plane/Convex Narrowphase + * @method planeConvex + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} convexBody + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = +Narrowphase.prototype[Shape.PLANE | Shape.BOX] = +Narrowphase.prototype.planeConvex = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + convexBody, + convexShape, + convexOffset, + convexAngle, + justTest +){ + var worldVertex = tmp1, + worldNormal = tmp2, + dist = tmp3; + + var numReported = 0; + vec2.rotate(worldNormal, yAxis, planeAngle); + + for(var i=0; i!==convexShape.vertices.length; i++){ + var v = convexShape.vertices[i]; + vec2.rotate(worldVertex, v, convexAngle); + add(worldVertex, worldVertex, convexOffset); + + sub(dist, worldVertex, planeOffset); + + if(dot(dist,worldNormal) <= 0){ + + if(justTest){ + return true; + } + + // Found vertex + numReported++; + + var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); + + sub(dist, worldVertex, planeOffset); + + vec2.copy(c.normalA, worldNormal); + + var d = dot(dist, c.normalA); + vec2.scale(dist, c.normalA, d); + + // rj is from convex center to contact + sub(c.contactPointB, worldVertex, convexBody.position); + + + // ri is from plane center to contact + sub( c.contactPointA, worldVertex, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + this.contactEquations.push(c); + + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numReported){ + this.frictionEquations.push(this.createFrictionFromAverage(numReported)); + } + } + + return numReported; +}; + +/** + * Narrowphase for particle vs plane + * @method particlePlane + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = +Narrowphase.prototype.particlePlane = function( + particleBody, + particleShape, + particleOffset, + particleAngle, + planeBody, + planeShape, + planeOffset, + planeAngle, + justTest +){ + var dist = tmp1, + worldNormal = tmp2; + + planeAngle = planeAngle || 0; + + sub(dist, particleOffset, planeOffset); + vec2.rotate(worldNormal, yAxis, planeAngle); + + var d = dot(dist, worldNormal); + + if(d > 0){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape); + + vec2.copy(c.normalA, worldNormal); + vec2.scale( dist, c.normalA, d ); + // dist is now the distance vector in the normal direction + + // ri is the particle position projected down onto the plane, from the plane center + sub( c.contactPointA, particleOffset, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + // rj is from the body center to the particle center + sub( c.contactPointB, particleOffset, particleBody.position ); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + return 1; +}; + +/** + * Circle/Particle Narrowphase + * @method circleParticle + * @param {Body} circleBody + * @param {Circle} circleShape + * @param {Array} circleOffset + * @param {Number} circleAngle + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = +Narrowphase.prototype.circleParticle = function( + circleBody, + circleShape, + circleOffset, + circleAngle, + particleBody, + particleShape, + particleOffset, + particleAngle, + justTest +){ + var dist = tmp1; + + sub(dist, particleOffset, circleOffset); + if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape); + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + // Vector from circle to contact point is the normal times the circle radius + vec2.scale(c.contactPointA, c.normalA, circleShape.radius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + // Vector from particle center to contact point is zero + sub(c.contactPointB, particleOffset, particleBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; +}; + +var planeCapsule_tmpCircle = new Circle({ radius: 1 }), + planeCapsule_tmp1 = vec2.create(), + planeCapsule_tmp2 = vec2.create(), + planeCapsule_tmp3 = vec2.create(); + +/** + * @method planeCapsule + * @param {Body} planeBody + * @param {Circle} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} capsuleBody + * @param {Particle} capsuleShape + * @param {Array} capsuleOffset + * @param {Number} capsuleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = +Narrowphase.prototype.planeCapsule = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + capsuleBody, + capsuleShape, + capsuleOffset, + capsuleAngle, + justTest +){ + var end1 = planeCapsule_tmp1, + end2 = planeCapsule_tmp2, + circle = planeCapsule_tmpCircle, + dst = planeCapsule_tmp3; + + // Compute world end positions + vec2.set(end1, -capsuleShape.length/2, 0); + vec2.rotate(end1,end1,capsuleAngle); + add(end1,end1,capsuleOffset); + + vec2.set(end2, capsuleShape.length/2, 0); + vec2.rotate(end2,end2,capsuleAngle); + add(end2,end2,capsuleOffset); + + circle.radius = capsuleShape.radius; + + var enableFrictionBefore; + + // Temporarily turn off friction + if(this.enableFrictionReduction){ + enableFrictionBefore = this.enableFriction; + this.enableFriction = false; + } + + // Do Narrowphase as two circles + var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest), + numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest); + + // Restore friction + if(this.enableFrictionReduction){ + this.enableFriction = enableFrictionBefore; + } + + if(justTest){ + return numContacts1 || numContacts2; + } else { + var numTotal = numContacts1 + numContacts2; + if(this.enableFrictionReduction){ + if(numTotal){ + this.frictionEquations.push(this.createFrictionFromAverage(numTotal)); + } + } + return numTotal; + } +}; + +/** + * Creates ContactEquations and FrictionEquations for a collision. + * @method circlePlane + * @param {Body} bi The first body that should be connected to the equations. + * @param {Circle} si The circle shape participating in the collision. + * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. + * @param {Body} bj The second body that should be connected to the equations. + * @param {Plane} sj The Plane shape that is participating + * @param {Array} xj Extra offset for the plane shape. + * @param {Number} aj Extra angle to apply to the plane + */ +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, // Offset from body center, rotated! + planeBody = bj, + shapeB = sj, + planeOffset = xj, + planeAngle = aj; + + planeAngle = planeAngle || 0; + + // Vector from plane to circle + var planeToCircle = tmp1, + worldNormal = tmp2, + temp = tmp3; + + sub(planeToCircle, circleOffset, planeOffset); + + // World plane normal + vec2.rotate(worldNormal, yAxis, planeAngle); + + // Normal direction distance + var d = dot(worldNormal, planeToCircle); + + if(d > circleShape.radius){ + return 0; // No overlap. Abort. + } + + if(justTest){ + return true; + } + + // Create contact + var contact = this.createContactEquation(planeBody,circleBody,sj,si); + + // ni is the plane world normal + vec2.copy(contact.normalA, worldNormal); + + // rj is the vector from circle center to the contact point + vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); + add(contact.contactPointB, contact.contactPointB, circleOffset); + sub(contact.contactPointB, contact.contactPointB, circleBody.position); + + // ri is the distance from plane center to contact. + vec2.scale(temp, contact.normalA, d); + sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector + 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; +}; + +/** + * Convex/convex Narrowphase.See this article for more info. + * @method convexConvex + * @param {Body} bi + * @param {Convex} si + * @param {Array} xi + * @param {Number} ai + * @param {Body} bj + * @param {Convex} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CONVEX] = +Narrowphase.prototype[Shape.CONVEX | Shape.BOX] = +Narrowphase.prototype[Shape.BOX] = +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 = typeof(precision) === 'number' ? precision : 0; + + var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); + if(!found){ + return 0; + } + + // Make sure the separating axis is directed from shape i to shape j + sub(dist,xj,xi); + if(dot(sepAxis,dist) > 0){ + vec2.scale(sepAxis,sepAxis,-1); + } + + // Find edges with normals closest to the separating axis + var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis + closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); + + if(closestEdge1 === -1 || closestEdge2 === -1){ + return 0; + } + + // Loop over the shapes + 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){ + // Swap! + 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; + } + + // Loop over 2 points in convex B + for(var j=closestEdgeB; j= 3){ + + if(justTest){ + return true; + } + + // worldPoint was on the "inside" side of each of the 3 checked edges. + // Project it to the center edge and use the projection direction as normal + + // Create contact + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + numContacts++; + + // Get center edge from body A + var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], + v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; + + // Construct the edge + 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); // Normal points out of convex A + vec2.normalize(c.normalA,c.normalA); + + sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point + var d = dot(c.normalA,dist); // Penetration + vec2.scale(penetrationVec, c.normalA, d); // Vector penetration + + 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); + + // Todo reduce to 1 friction equation if we have 2 contact points + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numContacts){ + this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); + } + } + + return numContacts; +}; + +// .projectConvex is called by other functions, need local tmp vectors +var pcoa_tmp1 = vec2.fromValues(0,0); + +/** + * Project a Convex onto a world-oriented axis + * @method projectConvexOntoAxis + * @static + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Array} worldAxis + * @param {Array} result + */ +Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = pcoa_tmp1; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, worldAxis, -convexAngle); + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + // Project the position of the body onto the axis - need to add this to the result + var offset = dot(convexOffset, worldAxis); + + vec2.set( result, min + offset, max + offset); +}; + +// .findSeparatingAxis is called by other functions, need local tmp vectors +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); + +/** + * Find a separating axis between the shapes, that maximizes the separating distance between them. + * @method findSeparatingAxis + * @static + * @param {Convex} c1 + * @param {Array} offset1 + * @param {Number} angle1 + * @param {Convex} c2 + * @param {Array} offset2 + * @param {Number} angle2 + * @param {Array} sepAxis The resulting axis + * @return {Boolean} Whether the axis could be found. + */ +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; + + if(c1 instanceof Box && c2 instanceof Box){ + + for(var j=0; j!==2; j++){ + var c = c1, + angle = angle1; + if(j===1){ + c = c2; + angle = angle2; + } + + for(var i=0; i!==2; i++){ + + // Get the world edge + if(i === 0){ + vec2.set(normal, 0, 1); + } else if(i === 1) { + vec2.set(normal, 1, 0); + } + if(angle !== 0){ + vec2.rotate(normal, normal, angle); + } + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + + } else { + + 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++){ + // Get the world edge + vec2.rotate(worldPoint0, c.vertices[i], angle); + vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); + + sub(edge, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, edge); + vec2.normalize(normal,normal); + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + } + + + /* + // Needs to be tested some more + 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.axes.length; i++){ + + var normal = c.axes[i]; + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1); + Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + 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; +}; + +// .getClosestEdge is called by other functions, need local tmp vectors +var gce_tmp1 = vec2.fromValues(0,0) +, gce_tmp2 = vec2.fromValues(0,0) +, gce_tmp3 = vec2.fromValues(0,0); + +/** + * Get the edge that has a normal closest to an axis. + * @method getClosestEdge + * @static + * @param {Convex} c + * @param {Number} angle + * @param {Array} axis + * @param {Boolean} flip + * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. + */ +Narrowphase.getClosestEdge = function(c,angle,axis,flip){ + var localAxis = gce_tmp1, + edge = gce_tmp2, + normal = gce_tmp3; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, axis, -angle); + if(flip){ + vec2.scale(localAxis,localAxis,-1); + } + + var closestEdge = -1, + N = c.vertices.length, + maxDot = -1; + for(var i=0; i!==N; i++){ + // Get the edge + sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + 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(); + +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = +Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, + hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ + var data = hfShape.heights, + 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; + + // Get the index of the points to test against + var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), + idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); + + /*if(idxB < 0 || idxA >= data.length) + return justTest ? false : 0;*/ + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(circlePos[1]-radius > max){ + return justTest ? false : 0; + } + + /* + if(circlePos[1]+radius < min){ + // Below the minimum point... We can just guess. + // TODO + } + */ + + // 1. Check so center of circle is not inside the field. If it is, this wont work... + // 2. For each edge + // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) + // 2. 2. Check if point is inside. + + var found = false; + + // Check all edges first + for(var i=idxA; i= v0[0] && candidate[0] < v1[0] && d <= 0){ + + if(justTest){ + return true; + } + + found = true; + + // Store the candidate point, projected to the edge + vec2.scale(dist,worldNormal,-d); + vec2.add(minCandidate,candidate,dist); + vec2.copy(minCandidateNormal,worldNormal); + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Normal is out of the heightfield + vec2.copy(c.normalA, minCandidateNormal); + + // Vector from circle to heightfield + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + vec2.copy(c.contactPointA, minCandidate); + vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push( this.createFrictionFromContact(c) ); + } + } + } + + // Check all vertices + found = false; + if(radius > 0){ + for(var i=idxA; i<=idxB; i++){ + + // Get point + vec2.set(v0, i*w, data[i]); + vec2.add(v0,v0,hfPos); + + vec2.sub(dist, circlePos, v0); + + if(vec2.squaredLength(dist) < Math.pow(radius, 2)){ + + if(justTest){ + return true; + } + + found = true; + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Construct normal - out of heightfield + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + sub(c.contactPointA, v0, hfPos); + add(c.contactPointA, c.contactPointA, hfPos); + sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(found){ + return 1; + } + + return 0; + +}; + +var convexHeightfield_v0 = vec2.create(), + convexHeightfield_v1 = vec2.create(), + convexHeightfield_tilePos = vec2.create(), + convexHeightfield_tempConvexShape = new Convex({ vertices: [vec2.create(),vec2.create(),vec2.create(),vec2.create()] }); +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.BOX | Shape.HEIGHTFIELD] = +Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = +Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, + hfBody,hfShape,hfPos,hfAngle, justTest ){ + var data = hfShape.heights, + w = hfShape.elementWidth, + v0 = convexHeightfield_v0, + v1 = convexHeightfield_v1, + tilePos = convexHeightfield_tilePos, + tileConvex = convexHeightfield_tempConvexShape; + + // Get the index of the points to test against + var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), + idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(convexBody.aabb.lowerBound[1] > max){ + return justTest ? false : 0; + } + + var found = false; + var numContacts = 0; + + // Loop over all edges + // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape) + for(var i=idxA; i= 0 || aabb.containsPoint(this.from)){ + this.intersectBody(result, body); + } + } +}; + +var intersectBody_worldPosition = vec2.create(); + +/** + * Shoot a ray at a body, get back information about the hit. + * @method intersectBody + * @private + * @param {Body} body + */ +Ray.prototype.intersectBody = function (result, body) { + var checkCollisionResponse = this.checkCollisionResponse; + + if(checkCollisionResponse && !body.collisionResponse){ + return; + } + + var worldPosition = intersectBody_worldPosition; + + for (var i = 0, N = body.shapes.length; i < N; i++) { + var shape = body.shapes[i]; + + if(checkCollisionResponse && !shape.collisionResponse){ + continue; // Skip + } + + if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){ + continue; + } + + // Get world angle and position of the shape + vec2.rotate(worldPosition, shape.position, body.angle); + vec2.add(worldPosition, worldPosition, body.position); + var worldAngle = shape.angle + body.angle; + + this.intersectShape( + result, + shape, + worldAngle, + worldPosition, + body + ); + + if(result.shouldStop(this)){ + break; + } + } +}; + +/** + * @method intersectShape + * @private + * @param {Shape} shape + * @param {number} angle + * @param {array} position + * @param {Body} body + */ +Ray.prototype.intersectShape = function(result, shape, angle, position, body){ + var from = this.from; + + // Checking radius + var distance = distanceFromIntersectionSquared(from, this.direction, position); + if (distance > shape.boundingRadius * shape.boundingRadius) { + return; + } + + this._currentBody = body; + this._currentShape = shape; + + shape.raycast(result, this, position, angle); + + this._currentBody = this._currentShape = null; +}; + +/** + * Get the AABB of the ray. + * @method getAABB + * @param {AABB} aabb + */ +Ray.prototype.getAABB = function(result){ + var to = this.to; + var from = this.from; + vec2.set( + result.lowerBound, + Math.min(to[0], from[0]), + Math.min(to[1], from[1]) + ); + vec2.set( + result.upperBound, + Math.max(to[0], from[0]), + Math.max(to[1], from[1]) + ); +}; + +var hitPointWorld = vec2.create(); + +/** + * @method reportIntersection + * @private + * @param {number} fraction + * @param {array} normal + * @param {number} [faceIndex=-1] + * @return {boolean} True if the intersections should continue + */ +Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){ + var from = this.from; + var to = this.to; + var shape = this._currentShape; + var body = this._currentBody; + + // Skip back faces? + if(this.skipBackfaces && vec2.dot(normal, this.direction) > 0){ + return; + } + + switch(this.mode){ + + case Ray.ALL: + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + this.callback(result); + break; + + case Ray.CLOSEST: + + // Store if closer than current closest + if(fraction < result.fraction || !result.hasHit()){ + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + } + break; + + case Ray.ANY: + + // Report and stop. + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + break; + } +}; + +var v0 = vec2.create(), + intersect = vec2.create(); +function distanceFromIntersectionSquared(from, direction, position) { + + // v0 is vector from from to position + vec2.sub(v0, position, from); + var dot = vec2.dot(v0, direction); + + // intersect = direction * dot + from + vec2.scale(intersect, direction, dot); + vec2.add(intersect, intersect, from); + + return vec2.squaredDistance(position, intersect); +} + + +},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Ray = _dereq_('../collision/Ray'); + +module.exports = RaycastResult; + +/** + * Storage for Ray casting hit data. + * @class RaycastResult + * @constructor + */ +function RaycastResult(){ + + /** + * The normal of the hit, oriented in world space. + * @property {array} normal + */ + this.normal = vec2.create(); + + /** + * The hit shape, or null. + * @property {Shape} shape + */ + this.shape = null; + + /** + * The hit body, or null. + * @property {Body} body + */ + this.body = null; + + /** + * The index of the hit triangle, if the hit shape was indexable. + * @property {number} faceIndex + * @default -1 + */ + this.faceIndex = -1; + + /** + * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet. + * @property {number} fraction + * @default -1 + */ + this.fraction = -1; + + /** + * If the ray should stop traversing. + * @readonly + * @property {Boolean} isStopped + */ + this.isStopped = false; +} + +/** + * Reset all result data. Must be done before re-using the result object. + * @method reset + */ +RaycastResult.prototype.reset = function () { + vec2.set(this.normal, 0, 0); + this.shape = null; + this.body = null; + this.faceIndex = -1; + this.fraction = -1; + this.isStopped = false; +}; + +/** + * Get the distance to the hit point. + * @method getHitDistance + * @param {Ray} ray + */ +RaycastResult.prototype.getHitDistance = function (ray) { + return vec2.distance(ray.from, ray.to) * this.fraction; +}; + +/** + * Returns true if the ray hit something since the last reset(). + * @method hasHit + */ +RaycastResult.prototype.hasHit = function () { + return this.fraction !== -1; +}; + +/** + * Get world hit point. + * @method getHitPoint + * @param {array} out + * @param {Ray} ray + */ +RaycastResult.prototype.getHitPoint = function (out, ray) { + vec2.lerp(out, ray.from, ray.to, this.fraction); +}; + +/** + * Can be called while iterating over hits to stop searching for hit points. + * @method stop + */ +RaycastResult.prototype.stop = function(){ + this.isStopped = true; +}; + +/** + * @method shouldStop + * @private + * @param {Ray} ray + * @return {boolean} + */ +RaycastResult.prototype.shouldStop = function(ray){ + return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY); +}; + +/** + * @method set + * @private + * @param {array} normal + * @param {Shape} shape + * @param {Body} body + * @param {number} fraction + */ +RaycastResult.prototype.set = function( + normal, + shape, + body, + fraction, + faceIndex +){ + vec2.copy(this.normal, normal); + this.shape = shape; + this.body = body; + this.fraction = fraction; + this.faceIndex = faceIndex; +}; +},{"../collision/Ray":11,"../math/vec2":30}],13:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, Broadphase = _dereq_('../collision/Broadphase'); + +module.exports = SAPBroadphase; + +/** + * Sweep and prune broadphase along one axis. + * + * @class SAPBroadphase + * @constructor + * @extends Broadphase + */ +function SAPBroadphase(){ + Broadphase.call(this,Broadphase.SAP); + + /** + * List of bodies currently in the broadphase. + * @property axisList + * @type {Array} + */ + this.axisList = []; + + /** + * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance. + * @property axisIndex + * @type {Number} + */ + this.axisIndex = 0; + + var that = this; + this._addBodyHandler = function(e){ + that.axisList.push(e.body); + }; + + this._removeBodyHandler = function(e){ + // Remove from list + var idx = that.axisList.indexOf(e.body); + if(idx !== -1){ + that.axisList.splice(idx,1); + } + }; +} +SAPBroadphase.prototype = new Broadphase(); +SAPBroadphase.prototype.constructor = SAPBroadphase; + +/** + * Change the world + * @method setWorld + * @param {World} world + */ +SAPBroadphase.prototype.setWorld = function(world){ + // Clear the old axis array + this.axisList.length = 0; + + // Add all bodies from the new world + Utils.appendArray(this.axisList, world.bodies); + + // Remove old handlers, if any + world + .off("addBody",this._addBodyHandler) + .off("removeBody",this._removeBodyHandler); + + // Add handlers to update the list of bodies. + world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); + + this.world = world; +}; + +/** + * Sorts bodies along an axis. + * @method sortAxisList + * @param {Array} a + * @param {number} axisIndex + * @return {Array} + */ +SAPBroadphase.sortAxisList = function(a, axisIndex){ + axisIndex = axisIndex|0; + for(var i=1,l=a.length; 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.sortList = function(){ + var bodies = this.axisList, + axisIndex = this.axisIndex; + + // Sort the lists + SAPBroadphase.sortAxisList(bodies, axisIndex); +}; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +SAPBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = this.axisList, + result = this.result, + axisIndex = this.axisIndex; + + result.length = 0; + + // Update all AABBs if needed + var l = bodies.length; + while(l--){ + var b = bodies[l]; + if(b.aabbNeedsUpdate){ + b.updateAABB(); + } + } + + // Sort the lists + this.sortList(); + + // Look through the X list + for(var i=0, N=bodies.length|0; i!==N; i++){ + var bi = bodies[i]; + + for(var j=i+1; j G = [-n -rixn n rjxn] + + var r = vec2.create(); + var ri = vec2.create(); // worldAnchorA + var rj = vec2.create(); // worldAnchorB + var that = this; + normal.computeGq = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + xi = bodyA.position, + xj = bodyB.position; + + // Transform local anchors to world + vec2.rotate(ri, localAnchorA, bodyA.angle); + vec2.rotate(rj, localAnchorB, bodyB.angle); + + vec2.add(r, xj, rj); + vec2.sub(r, r, ri); + vec2.sub(r, r, xi); + + //vec2.sub(r, bodyB.position, bodyA.position); + return vec2.length(r) - that.distance; + }; + + // Make the contact constraint bilateral + this.setMaxForce(maxForce); + + /** + * If the upper limit is enabled or not. + * @property {Boolean} upperLimitEnabled + */ + this.upperLimitEnabled = false; + + /** + * The upper constraint limit. + * @property {number} upperLimit + */ + this.upperLimit = 1; + + /** + * If the lower limit is enabled or not. + * @property {Boolean} lowerLimitEnabled + */ + this.lowerLimitEnabled = false; + + /** + * The lower constraint limit. + * @property {number} lowerLimit + */ + this.lowerLimit = 0; + + /** + * Current constraint position. This is equal to the current distance between the world anchor points. + * @property {number} position + */ + this.position = 0; +} +DistanceConstraint.prototype = new Constraint(); +DistanceConstraint.prototype.constructor = DistanceConstraint; + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +var n = vec2.create(); +var ri = vec2.create(); // worldAnchorA +var rj = vec2.create(); // worldAnchorB +DistanceConstraint.prototype.update = function(){ + var normal = this.equations[0], + bodyA = this.bodyA, + bodyB = this.bodyB, + distance = this.distance, + xi = bodyA.position, + xj = bodyB.position, + normalEquation = this.equations[0], + G = normal.G; + + // Transform local anchors to world + vec2.rotate(ri, this.localAnchorA, bodyA.angle); + vec2.rotate(rj, this.localAnchorB, bodyB.angle); + + // Get world anchor points and normal + vec2.add(n, xj, rj); + vec2.sub(n, n, ri); + vec2.sub(n, n, xi); + this.position = vec2.length(n); + + var violating = false; + if(this.upperLimitEnabled){ + if(this.position > this.upperLimit){ + normalEquation.maxForce = 0; + normalEquation.minForce = -this.maxForce; + this.distance = this.upperLimit; + violating = true; + } + } + + if(this.lowerLimitEnabled){ + if(this.position < this.lowerLimit){ + normalEquation.maxForce = this.maxForce; + normalEquation.minForce = 0; + this.distance = this.lowerLimit; + violating = true; + } + } + + if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){ + // No constraint needed. + normalEquation.enabled = false; + return; + } + + normalEquation.enabled = true; + + vec2.normalize(n,n); + + // Caluclate cross products + var rixn = vec2.crossLength(ri, n), + rjxn = vec2.crossLength(rj, n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; +}; + +/** + * Set the max force to be used + * @method setMaxForce + * @param {Number} maxForce + */ +DistanceConstraint.prototype.setMaxForce = function(maxForce){ + var normal = this.equations[0]; + normal.minForce = -maxForce; + normal.maxForce = maxForce; +}; + +/** + * Get the max force + * @method getMaxForce + * @return {Number} + */ +DistanceConstraint.prototype.getMaxForce = function(){ + var normal = this.equations[0]; + return normal.maxForce; +}; + +},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, AngleLockEquation = _dereq_('../equations/AngleLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = GearConstraint; + +/** + * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB. + * @class GearConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for). + * @param {Number} [options.ratio=1] Gear ratio. + * @param {Number} [options.maxTorque] Maximum torque to apply. + * @extends Constraint + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB, { + * ratio: 2, + * maxTorque: 1000 + * }); + * world.addConstraint(constraint); + */ +function GearConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); + + /** + * The gear ratio. + * @property ratio + * @type {Number} + */ + this.ratio = options.ratio !== undefined ? options.ratio : 1; + + /** + * The relative angle + * @property angle + * @type {Number} + */ + this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle; + + // Send same parameters to the equation + options.angle = this.angle; + options.ratio = this.ratio; + + this.equations = [ + new AngleLockEquation(bodyA,bodyB,options), + ]; + + // Set max torque + if(options.maxTorque !== undefined){ + this.setMaxTorque(options.maxTorque); + } +} +GearConstraint.prototype = new Constraint(); +GearConstraint.prototype.constructor = GearConstraint; + +GearConstraint.prototype.update = function(){ + var eq = this.equations[0]; + if(eq.ratio !== this.ratio){ + eq.setRatio(this.ratio); + } + eq.angle = this.angle; +}; + +/** + * Set the max torque for the constraint. + * @method setMaxTorque + * @param {Number} torque + */ +GearConstraint.prototype.setMaxTorque = function(torque){ + this.equations[0].setMaxTorque(torque); +}; + +/** + * Get the max torque for the constraint. + * @method getMaxTorque + * @return {Number} + */ +GearConstraint.prototype.getMaxTorque = function(torque){ + return this.equations[0].maxForce; +}; +},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('../equations/Equation'); + +module.exports = LockConstraint; + +/** + * Locks the relative position and rotation between two bodies. + * + * @class LockConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions. + * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles. + * @param {number} [options.maxForce] + * @extends Constraint + * + * @example + * // Locks the relative position and rotation between bodyA and bodyB + * var constraint = new LockConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + */ +function LockConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); + + var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); + + var localAngleB = options.localAngleB || 0; + + // Use 3 equations: + // gx = (xj - xi - l) * xhat = 0 + // gy = (xj - xi - l) * yhat = 0 + // gr = (xi - xj + r) * that = 0 + // + // ...where: + // l is the localOffsetB vector rotated to world in bodyA frame + // r is the same vector but reversed and rotated from bodyB frame + // xhat, yhat are world axis vectors + // that is the tangent of r + // + // For the first two constraints, we get + // G*W = (vj - vi - ldot ) * xhat + // = (vj - vi - wi x l) * xhat + // + // Since (wi x l) * xhat = (l x xhat) * wi, we get + // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] + // + // The last constraint gives + // GW = (vi - vj + wj x r) * that + // = [ that 0 -that (r x t) ] + + var x = new Equation(bodyA,bodyB,-maxForce,maxForce), + y = new Equation(bodyA,bodyB,-maxForce,maxForce), + rot = new Equation(bodyA,bodyB,-maxForce,maxForce); + + var l = vec2.create(), + g = vec2.create(), + that = this; + x.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[0]; + }; + y.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[1]; + }; + var r = vec2.create(), + t = vec2.create(); + rot.computeGq = function(){ + vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); + vec2.scale(r,r,-1); + vec2.sub(g,bodyA.position,bodyB.position); + vec2.add(g,g,r); + vec2.rotate(t,r,-Math.PI/2); + vec2.normalize(t,t); + return vec2.dot(g,t); + }; + + /** + * The offset of bodyB in bodyA's frame. + * @property {Array} localOffsetB + */ + this.localOffsetB = vec2.create(); + if(options.localOffsetB){ + vec2.copy(this.localOffsetB, options.localOffsetB); + } else { + // Construct from current positions + vec2.sub(this.localOffsetB, bodyB.position, bodyA.position); + vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle); + } + + /** + * The offset angle of bodyB in bodyA's frame. + * @property {Number} localAngleB + */ + this.localAngleB = 0; + if(typeof(options.localAngleB) === 'number'){ + this.localAngleB = options.localAngleB; + } else { + // Construct + this.localAngleB = bodyB.angle - bodyA.angle; + } + + this.equations.push(x, y, rot); + this.setMaxForce(maxForce); +} +LockConstraint.prototype = new Constraint(); +LockConstraint.prototype.constructor = LockConstraint; + +/** + * Set the maximum force to be applied. + * @method setMaxForce + * @param {Number} force + */ +LockConstraint.prototype.setMaxForce = function(force){ + var eqs = this.equations; + for(var i=0; ithis tutorial. Also called "slider constraint". + * + * @class PrismaticConstraint + * @constructor + * @extends Constraint + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.maxForce] Max force to be applied by the constraint + * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. + * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. + * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. + * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. + * @param {Number} [options.upperLimit] + * @param {Number} [options.lowerLimit] + * @todo Ability to create using only a point and a worldAxis + */ +function PrismaticConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); + + // Get anchors + var localAnchorA = vec2.fromValues(0,0), + localAxisA = vec2.fromValues(1,0), + localAnchorB = vec2.fromValues(0,0); + if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); } + if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); } + if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); } + + /** + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = localAnchorA; + + /** + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = localAnchorB; + + /** + * @property localAxisA + * @type {Array} + */ + this.localAxisA = localAxisA; + + /* + + The constraint violation for the common axis point is + + g = ( xj + rj - xi - ri ) * t := gg*t + + where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. + + gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) + + Note the use of the chain rule. Now we identify the jacobian + + G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] + + The rotational part is just a rotation lock. + + */ + + var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE; + + // Translational part + var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); + var ri = new vec2.create(), + rj = new vec2.create(), + gg = new vec2.create(), + t = new vec2.create(); + trans.computeGq = function(){ + // g = ( xj + rj - xi - ri ) * t + return vec2.dot(gg,t); + }; + trans.updateJacobian = function(){ + var G = this.G, + xi = bodyA.position, + xj = bodyB.position; + vec2.rotate(ri,localAnchorA,bodyA.angle); + vec2.rotate(rj,localAnchorB,bodyB.angle); + vec2.add(gg,xj,rj); + vec2.sub(gg,gg,xi); + vec2.sub(gg,gg,ri); + vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); + + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + }; + this.equations.push(trans); + + // Rotational part + if(!options.disableRotationalLock){ + var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); + this.equations.push(rot); + } + + /** + * The position of anchor A relative to anchor B, along the constraint axis. + * @property position + * @type {Number} + */ + this.position = 0; + + // Is this one used at all? + this.velocity = 0; + + /** + * Set to true to enable lower limit. + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; + + /** + * Set to true to enable upper limit. + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; + + /** + * Lower constraint limit. The constraint position is forced to be larger than this value. + * @property lowerLimit + * @type {Number} + */ + this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; + + /** + * Upper constraint limit. The constraint position is forced to be smaller than this value. + * @property upperLimit + * @type {Number} + */ + this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; + + // Equations used for limits + this.upperLimitEquation = new ContactEquation(bodyA,bodyB); + this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); + + // Set max/min forces + this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; + this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; + + /** + * Equation used for the motor. + * @property motorEquation + * @type {Equation} + */ + this.motorEquation = new Equation(bodyA,bodyB); + + /** + * The current motor state. Enable or disable the motor using .enableMotor + * @property motorEnabled + * @type {Boolean} + */ + this.motorEnabled = false; + + /** + * Set the target speed for the motor. + * @property motorSpeed + * @type {Number} + */ + this.motorSpeed = 0; + + var that = this; + var motorEquation = this.motorEquation; + var old = motorEquation.computeGW; + motorEquation.computeGq = function(){ return 0; }; + motorEquation.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed; + }; +} + +PrismaticConstraint.prototype = new Constraint(); +PrismaticConstraint.prototype.constructor = PrismaticConstraint; + +var worldAxisA = vec2.create(), + worldAnchorA = vec2.create(), + worldAnchorB = vec2.create(), + orientedAnchorA = vec2.create(), + orientedAnchorB = vec2.create(), + tmp = vec2.create(); + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +PrismaticConstraint.prototype.update = function(){ + var eqs = this.equations, + trans = eqs[0], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation, + bodyA = this.bodyA, + bodyB = this.bodyB, + localAxisA = this.localAxisA, + localAnchorA = this.localAnchorA, + localAnchorB = this.localAnchorB; + + trans.updateJacobian(); + + // Transform local things to world + vec2.rotate(worldAxisA, localAxisA, bodyA.angle); + vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); + vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); + vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); + vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); + + var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); + + // Motor + if(this.motorEnabled){ + // G = [ a a x ri -a -a x rj ] + var G = this.motorEquation.G; + G[0] = worldAxisA[0]; + G[1] = worldAxisA[1]; + G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); + G[3] = -worldAxisA[0]; + G[4] = -worldAxisA[1]; + G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); + } + + /* + Limits strategy: + Add contact equation, with normal along the constraint axis. + min/maxForce is set so the constraint is repulsive in the correct direction. + Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. + + ^ + | + upperLimit x + | ------ + anchorB x<---| B | + | | | + ------ | ------ + | | | + | A |-->x anchorA + ------ | + x lowerLimit + | + axis + */ + + + if(this.upperLimitEnabled && relPosition > upperLimit){ + // Update contact constraint normal, etc + 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 && relPosition < lowerLimit){ + // Update contact constraint normal, etc + vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); + vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); + vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); + vec2.scale(tmp,worldAxisA,lowerLimit); + vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } +}; + +/** + * Enable the motor + * @method enableMotor + */ +PrismaticConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +PrismaticConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the constraint limits. + * @method setLimits + * @param {number} lower Lower limit. + * @param {number} upper Upper limit. + */ +PrismaticConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + + +},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation') +, RotationalLockEquation = _dereq_('../equations/RotationalLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = RevoluteConstraint; + +var worldPivotA = vec2.create(), + worldPivotB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1), + g = vec2.create(); + +/** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * @class RevoluteConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to. + * @param {Array} [options.localPivotB] See localPivotA. + * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. + * @extends Constraint + * + * @example + * // This will create a revolute constraint between two bodies with pivot point in between them. + * var bodyA = new Body({ mass: 1, position: [-1, 0] }); + * var bodyB = new Body({ mass: 1, position: [1, 0] }); + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * worldPivot: [0, 0] + * }); + * world.addConstraint(constraint); + * + * // Using body-local pivot points, the constraint could have been constructed like this: + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * localPivotA: [1, 0], + * localPivotB: [-1, 0] + * }); + */ +function RevoluteConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); + + var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; + + /** + * @property {Array} pivotA + */ + this.pivotA = vec2.create(); + + /** + * @property {Array} pivotB + */ + this.pivotB = vec2.create(); + + if(options.worldPivot){ + // Compute pivotA and pivotB + vec2.sub(this.pivotA, options.worldPivot, bodyA.position); + vec2.sub(this.pivotB, options.worldPivot, bodyB.position); + // Rotate to local coordinate system + vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle); + vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle); + } else { + // Get pivotA and pivotB + vec2.copy(this.pivotA, options.localPivotA); + vec2.copy(this.pivotB, options.localPivotB); + } + + // Equations to be fed to the solver + var eqs = this.equations = [ + new Equation(bodyA,bodyB,-maxForce,maxForce), + new Equation(bodyA,bodyB,-maxForce,maxForce), + ]; + + var x = eqs[0]; + var y = eqs[1]; + var that = this; + + x.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,xAxis); + }; + + y.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,yAxis); + }; + + y.minForce = x.minForce = -maxForce; + y.maxForce = x.maxForce = maxForce; + + this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); + + /** + * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. + * @property {Boolean} motorEnabled + * @readOnly + */ + this.motorEnabled = false; + + /** + * The constraint position. + * @property angle + * @type {Number} + * @readOnly + */ + this.angle = 0; + + /** + * Set to true to enable lower limit + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = false; + + /** + * Set to true to enable upper limit + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = false; + + /** + * The lower limit on the constraint angle. + * @property lowerLimit + * @type {Boolean} + */ + this.lowerLimit = 0; + + /** + * The upper limit on the constraint angle. + * @property upperLimit + * @type {Boolean} + */ + this.upperLimit = 0; + + this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.upperLimitEquation.minForce = 0; + this.lowerLimitEquation.maxForce = 0; +} +RevoluteConstraint.prototype = new Constraint(); +RevoluteConstraint.prototype.constructor = RevoluteConstraint; + +/** + * Set the constraint angle limits. + * @method setLimits + * @param {number} lower Lower angle limit. + * @param {number} upper Upper angle limit. + */ +RevoluteConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + +RevoluteConstraint.prototype.update = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + pivotA = this.pivotA, + pivotB = this.pivotB, + eqs = this.equations, + normal = eqs[0], + tangent= eqs[1], + x = eqs[0], + y = eqs[1], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation; + + var relAngle = this.angle = bodyB.angle - bodyA.angle; + + if(this.upperLimitEnabled && relAngle > upperLimit){ + 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 < lowerLimit){ + lowerLimitEquation.angle = lowerLimit; + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } + + /* + + The constraint violation is + + g = xj + rj - xi - ri + + ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: + + gdot = vj + wj x rj - vi - wi x ri + + We split this into x and y directions. (let x and y be unit vectors along the respective axes) + + gdot * x = ( vj + wj x rj - vi - wi x ri ) * x + = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x + = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi + = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] + = G*W + + ...and similar for y. We have then identified the jacobian entries for x and y directions: + + Gx = [ x (rj x x) -x -(ri x x)] + Gy = [ y (rj x y) -y -(ri x y)] + + */ + + vec2.rotate(worldPivotA, pivotA, bodyA.angle); + vec2.rotate(worldPivotB, pivotB, bodyB.angle); + + // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc + + x.G[0] = -1; + x.G[1] = 0; + x.G[2] = -vec2.crossLength(worldPivotA,xAxis); + x.G[3] = 1; + x.G[4] = 0; + x.G[5] = vec2.crossLength(worldPivotB,xAxis); + + y.G[0] = 0; + y.G[1] = -1; + y.G[2] = -vec2.crossLength(worldPivotA,yAxis); + y.G[3] = 0; + y.G[4] = 1; + y.G[5] = vec2.crossLength(worldPivotB,yAxis); +}; + +/** + * Enable the rotational motor + * @method enableMotor + */ +RevoluteConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +RevoluteConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the speed of the rotational constraint motor + * @method setMotorSpeed + * @param {Number} speed + */ +RevoluteConstraint.prototype.setMotorSpeed = function(speed){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations[i].relativeVelocity = speed; +}; + +/** + * Get the speed of the rotational constraint motor + * @method getMotorSpeed + * @return {Number} The current speed, or false if the motor is not enabled. + */ +RevoluteConstraint.prototype.getMotorSpeed = function(){ + if(!this.motorEnabled){ + return false; + } + return this.motorEquation.relativeVelocity; +}; + +},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = AngleLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class AngleLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in body A. + * @param {Number} [options.ratio] Gear ratio + */ +function AngleLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); + this.angle = options.angle || 0; + + /** + * The gear ratio. + * @property {Number} ratio + * @private + * @see setRatio + */ + this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; + + this.setRatio(this.ratio); +} +AngleLockEquation.prototype = new Equation(); +AngleLockEquation.prototype.constructor = AngleLockEquation; + +AngleLockEquation.prototype.computeGq = function(){ + return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; +}; + +/** + * Set the gear ratio for this equation + * @method setRatio + * @param {Number} ratio + */ +AngleLockEquation.prototype.setRatio = function(ratio){ + var G = this.G; + G[2] = ratio; + G[5] = -1; + this.ratio = ratio; +}; + +/** + * Set the max force for the equation. + * @method setMaxTorque + * @param {Number} torque + */ +AngleLockEquation.prototype.setMaxTorque = function(torque){ + this.maxForce = torque; + this.minForce = -torque; +}; + +},{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = ContactEquation; + +/** + * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive. + * + * @class ContactEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function ContactEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); + + /** + * Vector from body i center of mass to the contact point. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + this.penetrationVec = vec2.create(); + + /** + * World-oriented vector from body A center of mass to the contact point. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * The normal vector, pointing out of body i + * @property normalA + * @type {Array} + */ + this.normalA = vec2.create(); + + /** + * The restitution to use (0=no bounciness, 1=max bounciness). + * @property restitution + * @type {Number} + */ + this.restitution = 0; + + /** + * This property is set to true if this is the first impact between the bodies (not persistant contact). + * @property firstImpact + * @type {Boolean} + * @readOnly + */ + this.firstImpact = false; + + /** + * The shape in body i that triggered this contact. + * @property shapeA + * @type {Shape} + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this contact. + * @property shapeB + * @type {Shape} + */ + this.shapeB = null; +} +ContactEquation.prototype = new Equation(); +ContactEquation.prototype.constructor = ContactEquation; +ContactEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + xi = bi.position, + xj = bj.position; + + var penetrationVec = this.penetrationVec, + n = this.normalA, + G = this.G; + + // Caluclate cross products + var rixn = vec2.crossLength(ri,n), + rjxn = vec2.crossLength(rj,n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; + + // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector + vec2.add(penetrationVec,xj,rj); + vec2.sub(penetrationVec,penetrationVec,xi); + vec2.sub(penetrationVec,penetrationVec,ri); + + // Compute iteration + var GW, Gq; + if(this.firstImpact && this.restitution !== 0){ + Gq = 0; + GW = (1/b)*(1+this.restitution) * this.computeGW(); + } else { + Gq = vec2.dot(n,penetrationVec) + this.offset; + GW = this.computeGW(); + } + + var GiMf = this.computeGiMf(); + var B = - Gq * a - GW * b - h*GiMf; + + return B; +}; + +var vi = vec2.create(); +var vj = vec2.create(); +var relVel = vec2.create(); + +/** + * Get the relative velocity along the normal vector. + * @return {number} + */ +ContactEquation.prototype.getVelocityAlongNormal = function(){ + + this.bodyA.getVelocityAtPoint(vi, this.contactPointA); + this.bodyB.getVelocityAtPoint(vj, this.contactPointB); + + vec2.subtract(relVel, vi, vj); + + return vec2.dot(this.normalA, relVel); +}; +},{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){ +module.exports = Equation; + +var vec2 = _dereq_('../math/vec2'), + Utils = _dereq_('../utils/Utils'), + Body = _dereq_('../objects/Body'); + +/** + * Base class for constraint equations. + * @class Equation + * @constructor + * @param {Body} bodyA First body participating in the equation + * @param {Body} bodyB Second body participating in the equation + * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE + * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE + */ +function Equation(bodyA, bodyB, minForce, maxForce){ + + /** + * Minimum force to apply when solving. + * @property minForce + * @type {Number} + */ + this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; + + /** + * Max force to apply when solving. + * @property maxForce + * @type {Number} + */ + this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; + + /** + * First body participating in the constraint + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second body participating in the constraint + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; + + /** + * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. + * @property stiffness + * @type {Number} + */ + this.stiffness = Equation.DEFAULT_STIFFNESS; + + /** + * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. + * @property relaxation + * @type {Number} + */ + this.relaxation = Equation.DEFAULT_RELAXATION; + + /** + * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). + * @property G + * @type {Array} + */ + this.G = new Utils.ARRAY_TYPE(6); + for(var i=0; i<6; i++){ + this.G[i]=0; + } + + this.offset = 0; + + this.a = 0; + this.b = 0; + this.epsilon = 0; + this.timeStep = 1/60; + + /** + * Indicates if stiffness or relaxation was changed. + * @property {Boolean} needsUpdate + */ + this.needsUpdate = true; + + /** + * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. + * @property multiplier + * @type {Number} + */ + this.multiplier = 0; + + /** + * Relative velocity. + * @property {Number} relativeVelocity + */ + this.relativeVelocity = 0; + + /** + * Whether this equation is enabled or not. If true, it will be added to the solver. + * @property {Boolean} enabled + */ + this.enabled = true; +} +Equation.prototype.constructor = Equation; + +/** + * The default stiffness when creating a new Equation. + * @static + * @property {Number} DEFAULT_STIFFNESS + * @default 1e6 + */ +Equation.DEFAULT_STIFFNESS = 1e6; + +/** + * The default relaxation when creating a new Equation. + * @static + * @property {Number} DEFAULT_RELAXATION + * @default 4 + */ +Equation.DEFAULT_RELAXATION = 4; + +/** + * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the SPOOK notes. + * @method update + */ +Equation.prototype.update = function(){ + var k = this.stiffness, + d = this.relaxation, + h = this.timeStep; + + this.a = 4.0 / (h * (1 + 4 * d)); + this.b = (4.0 * d) / (1 + 4 * d); + this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); + + this.needsUpdate = false; +}; + +/** + * Multiply a jacobian entry with corresponding positions or velocities + * @method gmult + * @return {Number} + */ +Equation.prototype.gmult = function(G,vi,wi,vj,wj){ + return G[0] * vi[0] + + G[1] * vi[1] + + G[2] * wi + + G[3] * vj[0] + + G[4] * vj[1] + + G[5] * wj; +}; + +/** + * Computes the RHS of the SPOOK equation + * @method computeB + * @return {Number} + */ +Equation.prototype.computeB = function(a,b,h){ + var GW = this.computeGW(); + var Gq = this.computeGq(); + var GiMf = this.computeGiMf(); + return - Gq * a - GW * b - GiMf*h; +}; + +/** + * Computes G\*q, where q are the generalized body coordinates + * @method computeGq + * @return {Number} + */ +var qi = vec2.create(), + qj = vec2.create(); +Equation.prototype.computeGq = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + xi = bi.position, + xj = bj.position, + ai = bi.angle, + aj = bj.angle; + + return this.gmult(G, qi, ai, qj, aj) + this.offset; +}; + +/** + * Computes G\*W, where W are the body velocities + * @method computeGW + * @return {Number} + */ +Equation.prototype.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity; +}; + +/** + * Computes G\*Wlambda, where W are the body velocities + * @method computeGWlambda + * @return {Number} + */ +Equation.prototype.computeGWlambda = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.vlambda, + vj = bj.vlambda, + wi = bi.wlambda, + wj = bj.wlambda; + return this.gmult(G,vi,wi,vj,wj); +}; + +/** + * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. + * @method computeGiMf + * @return {Number} + */ +var iMfi = vec2.create(), + iMfj = vec2.create(); +Equation.prototype.computeGiMf = function(){ + var bi = this.bodyA, + bj = this.bodyB, + fi = bi.force, + ti = bi.angularForce, + fj = bj.force, + tj = bj.angularForce, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + vec2.scale(iMfi, fi, invMassi); + vec2.multiply(iMfi, bi.massMultiplier, iMfi); + vec2.scale(iMfj, fj,invMassj); + vec2.multiply(iMfj, bj.massMultiplier, iMfj); + + return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); +}; + +/** + * Computes G\*inv(M)\*G' + * @method computeGiMGt + * @return {Number} + */ +Equation.prototype.computeGiMGt = function(){ + var bi = this.bodyA, + bj = this.bodyB, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + return G[0] * G[0] * invMassi * bi.massMultiplier[0] + + G[1] * G[1] * invMassi * bi.massMultiplier[1] + + G[2] * G[2] * invIi + + G[3] * G[3] * invMassj * bj.massMultiplier[0] + + G[4] * G[4] * invMassj * bj.massMultiplier[1] + + G[5] * G[5] * invIj; +}; + +var addToWlambda_temp = vec2.create(), + addToWlambda_Gi = vec2.create(), + addToWlambda_Gj = vec2.create(), + addToWlambda_ri = vec2.create(), + addToWlambda_rj = vec2.create(), + addToWlambda_Mdiag = vec2.create(); + +/** + * Add constraint velocity to the bodies. + * @method addToWlambda + * @param {Number} deltalambda + */ +Equation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bodyA, + bj = this.bodyB, + temp = addToWlambda_temp, + Gi = addToWlambda_Gi, + Gj = addToWlambda_Gj, + ri = addToWlambda_ri, + rj = addToWlambda_rj, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + Mdiag = addToWlambda_Mdiag, + G = this.G; + + Gi[0] = G[0]; + Gi[1] = G[1]; + Gj[0] = G[3]; + Gj[1] = G[4]; + + // Add to linear velocity + // v_lambda += inv(M) * delta_lamba * G + vec2.scale(temp, Gi, invMassi*deltalambda); + vec2.multiply(temp, temp, bi.massMultiplier); + vec2.add( bi.vlambda, bi.vlambda, temp); + // This impulse is in the offset frame + // Also add contribution to angular + //bi.wlambda -= vec2.crossLength(temp,ri); + bi.wlambda += invIi * G[2] * deltalambda; + + + vec2.scale(temp, Gj, invMassj*deltalambda); + vec2.multiply(temp, temp, bj.massMultiplier); + vec2.add( bj.vlambda, bj.vlambda, temp); + //bj.wlambda -= vec2.crossLength(temp,rj); + bj.wlambda += invIj * G[5] * deltalambda; +}; + +/** + * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps + * @method computeInvC + * @param {Number} eps + * @return {Number} + */ +Equation.prototype.computeInvC = function(eps){ + return 1.0 / (this.computeGiMGt() + eps); +}; + +},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('./Equation') +, Utils = _dereq_('../utils/Utils'); + +module.exports = FrictionEquation; + +/** + * Constrains the slipping in a contact along a tangent + * + * @class FrictionEquation + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Number} slipForce + * @extends Equation + */ +function FrictionEquation(bodyA, bodyB, slipForce){ + Equation.call(this, bodyA, bodyB, -slipForce, slipForce); + + /** + * Relative vector from center of body A to the contact point, world oriented. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + + /** + * Relative vector from center of body B to the contact point, world oriented. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * Tangent vector that the friction force will act along. World oriented. + * @property t + * @type {Array} + */ + this.t = vec2.create(); + + /** + * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average. + * @property contactEquations + * @type {ContactEquation} + */ + this.contactEquations = []; + + /** + * The shape in body i that triggered this friction. + * @property shapeA + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeA... + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this friction. + * @property shapeB + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeB... + */ + this.shapeB = null; + + /** + * The friction coefficient to use. + * @property frictionCoefficient + * @type {Number} + */ + this.frictionCoefficient = 0.3; +} +FrictionEquation.prototype = new Equation(); +FrictionEquation.prototype.constructor = FrictionEquation; + +/** + * Set the slipping condition for the constraint. The friction force cannot be + * larger than this value. + * @method setSlipForce + * @param {Number} slipForce + */ +FrictionEquation.prototype.setSlipForce = function(slipForce){ + this.maxForce = slipForce; + this.minForce = -slipForce; +}; + +/** + * Get the max force for the constraint. + * @method getSlipForce + * @return {Number} + */ +FrictionEquation.prototype.getSlipForce = function(){ + return this.maxForce; +}; + +FrictionEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + t = this.t, + G = this.G; + + // G = [-t -rixt t rjxt] + // And remember, this is a pure velocity constraint, g is always zero! + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + + var GW = this.computeGW(), + GiMf = this.computeGiMf(); + + var B = /* - g * a */ - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class RotationalLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in bodyA. + */ +function RotationalLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + + /** + * @property {number} angle + */ + this.angle = options.angle || 0; + + var G = this.G; + G[2] = 1; + G[5] = -1; +} +RotationalLockEquation.prototype = new Equation(); +RotationalLockEquation.prototype.constructor = RotationalLockEquation; + +var worldVectorA = vec2.create(), + worldVectorB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1); +RotationalLockEquation.prototype.computeGq = function(){ + vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); + vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); + return vec2.dot(worldVectorA,worldVectorB); +}; + +},{"../math/vec2":30,"./Equation":22}],25:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalVelocityEquation; + +/** + * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). + * + * @class RotationalVelocityEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function RotationalVelocityEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + this.relativeVelocity = 1; + this.ratio = 1; +} +RotationalVelocityEquation.prototype = new Equation(); +RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; +RotationalVelocityEquation.prototype.computeB = function(a,b,h){ + var G = this.G; + G[2] = -1; + G[5] = this.ratio; + + var GiMf = this.computeGiMf(); + var GW = this.computeGW(); + var B = - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"./Equation":22}],26:[function(_dereq_,module,exports){ +/** + * Base class for objects that dispatches events. + * @class EventEmitter + * @constructor + */ +var EventEmitter = function () {}; + +module.exports = EventEmitter; + +EventEmitter.prototype = { + constructor: EventEmitter, + + /** + * Add an event listener + * @method on + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + on: function ( type, listener, context ) { + listener.context = context || this; + if ( this._listeners === undefined ){ + this._listeners = {}; + } + var listeners = this._listeners; + if ( listeners[ type ] === undefined ) { + listeners[ type ] = []; + } + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + listeners[ type ].push( listener ); + } + return this; + }, + + /** + * Check if an event listener is added + * @method has + * @param {String} type + * @param {Function} listener + * @return {Boolean} + */ + has: function ( type, listener ) { + if ( this._listeners === undefined ){ + return false; + } + var listeners = this._listeners; + if(listener){ + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + return true; + } + } else { + if ( listeners[ type ] !== undefined ) { + return true; + } + } + + return false; + }, + + /** + * Remove an event listener + * @method off + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + off: function ( type, listener ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var index = listeners[ type ].indexOf( listener ); + if ( index !== - 1 ) { + listeners[ type ].splice( index, 1 ); + } + return this; + }, + + /** + * Emit an event. + * @method emit + * @param {Object} event + * @param {String} event.type + * @return {EventEmitter} The self object, for chainability. + */ + emit: function ( event ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; + if ( listenerArray !== undefined ) { + event.target = this; + for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { + var listener = listenerArray[ i ]; + listener.call( listener.context, event ); + } + } + return this; + } +}; + +},{}],27:[function(_dereq_,module,exports){ +var Material = _dereq_('./Material'); +var Equation = _dereq_('../equations/Equation'); + +module.exports = ContactMaterial; + +/** + * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. + * @class ContactMaterial + * @constructor + * @param {Material} materialA + * @param {Material} materialB + * @param {Object} [options] + * @param {Number} [options.friction=0.3] Friction coefficient. + * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". + * @param {Number} [options.stiffness] ContactEquation stiffness. + * @param {Number} [options.relaxation] ContactEquation relaxation. + * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. + * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. + * @param {Number} [options.surfaceVelocity=0] Surface velocity. + * @author schteppe + */ +function ContactMaterial(materialA, materialB, options){ + options = options || {}; + + if(!(materialA instanceof Material) || !(materialB instanceof Material)){ + throw new Error("First two arguments must be Material instances."); + } + + /** + * The contact material identifier + * @property id + * @type {Number} + */ + this.id = ContactMaterial.idCounter++; + + /** + * First material participating in the contact material + * @property materialA + * @type {Material} + */ + this.materialA = materialA; + + /** + * Second material participating in the contact material + * @property materialB + * @type {Material} + */ + this.materialB = materialB; + + /** + * Friction coefficient to use in the contact of these two materials. Friction = 0 will make the involved objects super slippery, and friction = 1 will make it much less slippery. A friction coefficient larger than 1 will allow for very large friction forces, which can be convenient for preventing car tires not slip on the ground. + * @property friction + * @type {Number} + * @default 0.3 + */ + this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; + + /** + * Restitution, or "bounciness" to use in the contact of these two materials. A restitution of 0 will make no bounce, while restitution=1 will approximately bounce back with the same velocity the object came with. + * @property restitution + * @type {Number} + * @default 0 + */ + this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0; + + /** + * Hardness of the contact. Less stiffness will make the objects penetrate more, and will make the contact act more like a spring than a contact force. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property stiffness + * @type {Number} + */ + this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting ContactEquation that this ContactMaterial generate. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property relaxation + * @type {Number} + */ + this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Stiffness of the resulting friction force. For most cases, the value of this property should be a large number. I cannot think of any case where you would want less frictionStiffness. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property frictionStiffness + * @type {Number} + */ + this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting friction force. The default value should be good for most simulations. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property frictionRelaxation + * @type {Number} + */ + this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + * @property {Number} surfaceVelocity + * @default 0 + */ + this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; + + /** + * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts". + * @property contactSkinSize + * @type {Number} + */ + this.contactSkinSize = 0.005; +} + +ContactMaterial.idCounter = 0; + +},{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){ +module.exports = Material; + +/** + * Defines a physics material. + * @class Material + * @constructor + * @param {number} id Material identifier + * @author schteppe + */ +function Material(id){ + /** + * The material identifier + * @property id + * @type {Number} + */ + this.id = id || Material.idCounter++; +} + +Material.idCounter = 0; + +},{}],29:[function(_dereq_,module,exports){ + + /* + PolyK library + url: http://polyk.ivank.net + Released under MIT licence. + + Copyright (c) 2012 Ivan Kuckir + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + */ + + var PolyK = {}; + + /* + Is Polygon self-intersecting? + + O(n^2) + */ + /* + PolyK.IsSimple = function(p) + { + var n = p.length>>1; + if(n<4) return true; + var a1 = new PolyK._P(), a2 = new PolyK._P(); + var b1 = new PolyK._P(), b2 = new PolyK._P(); + var c = new PolyK._P(); + + for(var i=0; i>1; + if(n<3) return []; + var tgs = []; + var avl = []; + for(var i=0; i 3) + { + 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; j 3*al) break; // no convex angles :( + } + tgs.push(avl[0], avl[1], avl[2]); + return tgs; + } + /* + PolyK.ContainsPoint = function(p, px, py) + { + var n = p.length>>1; + var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; + var depth = 0; + for(var i=0; i=0 && by>=0) continue; // both "up" or both "donw" + if(ax< 0 && bx< 0) continue; + + var lx = ax + (bx-ax)*(-ay)/(by-ay); + if(lx>0) depth++; + } + return (depth & 1) == 1; + } + + PolyK.Slice = function(p, ax, ay, bx, by) + { + if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; + + var a = new PolyK._P(ax, ay); + var b = new PolyK._P(bx, by); + var iscs = []; // intersections + var ps = []; // points + for(var i=0; i 0) + { + var n = ps.length; + var i0 = iscs[0]; + var i1 = iscs[1]; + var ind0 = ps.indexOf(i0); + var ind1 = ps.indexOf(i1); + var solved = false; + + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + else + { + i0 = iscs[1]; + i1 = iscs[0]; + ind0 = ps.indexOf(i0); + ind1 = ps.indexOf(i1); + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + } + if(solved) + { + dir--; + var pgn = PolyK._getPoints(ps, ind0, ind1); + pgs.push(pgn); + ps = PolyK._getPoints(ps, ind1, ind0); + i0.flag = i1.flag = false; + iscs.splice(0,2); + if(iscs.length == 0) pgs.push(ps); + } + else { dir++; iscs.reverse(); } + if(dir>1) break; + } + var result = []; + for(var i=0; i>1, isc); + } + b1.x = b2.x; b1.y = b2.y; + b2.x = p[0]; b2.y = p[1]; + PolyK._pointLineDist(a1, b1, b2, l>>1, isc); + + var idst = 1/isc.dist; + isc.norm.x = (x-isc.point.x)*idst; + isc.norm.y = (y-isc.point.y)*idst; + return isc; + } + + PolyK._pointLineDist = function(p, a, b, edge, isc) + { + var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; + + var A = x - x1; + var B = y - y1; + var C = x2 - x1; + var D = y2 - y1; + + var dot = A * C + B * D; + var len_sq = C * C + D * D; + var param = dot / len_sq; + + var xx, yy; + + if (param < 0 || (x1 == x2 && y1 == y2)) { + xx = x1; + yy = y1; + } + else if (param > 1) { + xx = x2; + yy = y2; + } + else { + xx = x1 + param * C; + yy = y1 + param * D; + } + + var dx = x - xx; + var dy = y - yy; + var dst = Math.sqrt(dx * dx + dy * dy); + if(dst= 0) && (v >= 0) && (u + v < 1); + } + /* + PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) + { + var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); + var day = (a1.y-a2.y), dby = (b1.y-b2.y); + + var Den = dax*dby - day*dbx; + if (Den == 0) return null; // parallel + + var A = (a1.x * a2.y - a1.y * a2.x); + var B = (b1.x * b2.y - b1.y * b2.x); + + var I = c; + var iDen = 1/Den; + I.x = ( A*dbx - dax*B ) * iDen; + I.y = ( A*dby - day*B ) * iDen; + + if(!PolyK._InRect(I, b1, b2)) return null; + if((day>0 && I.y>a1.y) || (day<0 && I.y0 && I.x>a1.x) || (dax<0 && I.x=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); + if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); + + if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) + && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) + return true; + return false; + } + */ + PolyK._convex = function(ax, ay, bx, by, cx, cy) + { + return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; + } + /* + PolyK._P = function(x,y) + { + this.x = x; + this.y = y; + this.flag = false; + } + PolyK._P.prototype.toString = function() + { + return "Point ["+this.x+", "+this.y+"]"; + } + PolyK._P.dist = function(a,b) + { + var dx = b.x-a.x; + var dy = b.y-a.y; + return Math.sqrt(dx*dx + dy*dy); + } + + PolyK._tp = []; + for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); + */ + +module.exports = PolyK; + +},{}],30:[function(_dereq_,module,exports){ +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. + * @class vec2 + */ + +var vec2 = module.exports = {}; + +var Utils = _dereq_('../utils/Utils'); + +/** + * Make a cross product and only return the z component + * @method crossLength + * @static + * @param {Array} a + * @param {Array} b + * @return {Number} + */ +vec2.crossLength = function(a,b){ + return a[0] * b[1] - a[1] * b[0]; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossVZ + * @static + * @param {Array} out + * @param {Array} vec + * @param {Number} zcomp + * @return {Number} + */ +vec2.crossVZ = function(out, vec, zcomp){ + vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossZV + * @static + * @param {Array} out + * @param {Number} zcomp + * @param {Array} vec + * @return {Number} + */ +vec2.crossZV = function(out, zcomp, vec){ + vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Rotate a vector by an angle + * @method rotate + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate = function(out,a,angle){ + if(angle !== 0){ + 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; + } else { + out[0] = a[0]; + out[1] = a[1]; + } +}; + +/** + * Rotate a vector 90 degrees clockwise + * @method rotate90cw + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate90cw = function(out, a) { + var x = a[0]; + var y = a[1]; + out[0] = y; + out[1] = -x; +}; + +/** + * Transform a point position to local frame. + * @method toLocalFrame + * @param {Array} out + * @param {Array} worldPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ + vec2.copy(out, worldPoint); + vec2.sub(out, out, framePosition); + vec2.rotate(out, out, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ + vec2.copy(out, localPoint); + vec2.rotate(out, out, frameAngle); + vec2.add(out, out, framePosition); +}; + +/** + * Transform a vector to local frame. + * @method vectorToLocalFrame + * @param {Array} out + * @param {Array} worldVector + * @param {Number} frameAngle + */ +vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ + vec2.rotate(out, worldVector, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localVector + * @param {Number} frameAngle + */ +vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){ + vec2.rotate(out, localVector, frameAngle); +}; + +/** + * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php + * @method centroid + * @static + * @param {Array} out + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Array} The out object + */ +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; +}; + +/** + * Creates a new, empty vec2 + * @static + * @method create + * @return {Array} a new 2D vector + */ +vec2.create = function() { + var out = new Utils.ARRAY_TYPE(2); + out[0] = 0; + out[1] = 0; + return out; +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * @static + * @method clone + * @param {Array} a vector to clone + * @return {Array} a new 2D vector + */ +vec2.clone = function(a) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Creates a new vec2 initialized with the given values + * @static + * @method fromValues + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} a new 2D vector + */ +vec2.fromValues = function(x, y) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Copy the values from one vec2 to another + * @static + * @method copy + * @param {Array} out the receiving vector + * @param {Array} a the source vector + * @return {Array} out + */ +vec2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * @static + * @method set + * @param {Array} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} out + */ +vec2.set = function(out, x, y) { + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Adds two vec2's + * @static + * @method add + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +}; + +/** + * Subtracts two vec2's + * @static + * @method subtract + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +}; + +/** + * Alias for vec2.subtract + * @static + * @method sub + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * @static + * @method multiply + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +}; + +/** + * Alias for vec2.multiply + * @static + * @method mul + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * @static + * @method divide + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +}; + +/** + * Alias for vec2.divide + * @static + * @method div + */ +vec2.div = vec2.divide; + +/** + * Scales a vec2 by a scalar number + * @static + * @method scale + * @param {Array} out the receiving vector + * @param {Array} a the vector to scale + * @param {Number} b amount to scale the vector by + * @return {Array} out + */ +vec2.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * @static + * @method distance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} distance between a and b + */ +vec2.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.distance + * @static + * @method dist + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * @static + * @method squaredDistance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} squared distance between a and b + */ +vec2.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredDistance + * @static + * @method sqrDist + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * @static + * @method length + * @param {Array} a vector to calculate length of + * @return {Number} length of a + */ +vec2.length = function (a) { + var x = a[0], + y = a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.length + * @method len + * @static + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * @static + * @method squaredLength + * @param {Array} a vector to calculate squared length of + * @return {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a[0], + y = a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredLength + * @static + * @method sqrLen + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * @static + * @method negate + * @param {Array} out the receiving vector + * @param {Array} a vector to negate + * @return {Array} out + */ +vec2.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +}; + +/** + * Normalize a vec2 + * @static + * @method normalize + * @param {Array} out the receiving vector + * @param {Array} a vector to normalize + * @return {Array} out + */ +vec2.normalize = function(out, a) { + var x = a[0], + y = a[1]; + var len = x*x + y*y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * @static + * @method dot + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1]; +}; + +/** + * Returns a string representation of a vector + * @static + * @method str + * @param {Array} vec vector to represent as a string + * @return {String} string representation of the vector + */ +vec2.str = function (a) { + return 'vec2(' + a[0] + ', ' + a[1] + ')'; +}; + +/** + * Linearly interpolate/mix two vectors. + * @static + * @method lerp + * @param {Array} out + * @param {Array} a First vector + * @param {Array} b Second vector + * @param {number} t Lerp factor + */ +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; +}; + +/** + * Reflect a vector along a normal. + * @static + * @method reflect + * @param {Array} out + * @param {Array} vector + * @param {Array} normal + */ +vec2.reflect = function(out, vector, normal){ + var dot = vector[0] * normal[0] + vector[1] * normal[1]; + out[0] = vector[0] - 2 * normal[0] * dot; + out[1] = vector[1] - 2 * normal[1] * dot; +}; + +/** + * Get the intersection point between two line segments. + * @static + * @method getLineSegmentsIntersection + * @param {Array} out + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {boolean} True if there was an intersection, otherwise false. + */ +vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { + var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); + if(t < 0){ + return false; + } else { + out[0] = p0[0] + (t * (p1[0] - p0[0])); + out[1] = p0[1] + (t * (p1[1] - p0[1])); + return true; + } +}; + +/** + * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) + * @static + * @method getLineSegmentsIntersectionFraction + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. + */ +vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { + var s1_x = p1[0] - p0[0]; + var s1_y = p1[1] - p0[1]; + var s2_x = p3[0] - p2[0]; + var s2_y = p3[1] - p2[1]; + + var s, t; + s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); + t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); + if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + return t; + } + return -1; // No collision +}; + +},{"../utils/Utils":57}],31:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, decomp = _dereq_('poly-decomp') +, Convex = _dereq_('../shapes/Convex') +, RaycastResult = _dereq_('../collision/RaycastResult') +, Ray = _dereq_('../collision/Ray') +, AABB = _dereq_('../collision/AABB') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Body; + +/** + * A rigid body. Has got a center of mass, position, velocity and a number of + * shapes that are used for collisions. + * + * @class Body + * @constructor + * @extends EventEmitter + * @param {Array} [options.force] + * @param {Array} [options.position] + * @param {Array} [options.velocity] + * @param {Boolean} [options.allowSleep] + * @param {Boolean} [options.collisionResponse] + * @param {Number} [options.angle=0] + * @param {Number} [options.angularForce=0] + * @param {Number} [options.angularVelocity=0] + * @param {Number} [options.ccdIterations=10] + * @param {Number} [options.ccdSpeedThreshold=-1] + * @param {Number} [options.fixedRotation=false] + * @param {Number} [options.gravityScale] + * @param {Number} [options.id] + * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. + * @param {Number} [options.sleepSpeedLimit] + * @param {Number} [options.sleepTimeLimit] + * @param {Object} [options] + * + * @example + * + * // Create a typical dynamic body + * var body = new Body({ + * mass: 1, + * position: [0, 0], + * angle: 0, + * velocity: [0, 0], + * angularVelocity: 0 + * }); + * + * // Add a circular shape to the body + * body.addShape(new Circle({ radius: 1 })); + * + * // Add the body to the world + * world.addBody(body); + */ +function Body(options){ + options = options || {}; + + EventEmitter.call(this); + + /** + * The body identifyer + * @property id + * @type {Number} + */ + this.id = options.id || ++Body._idCounter; + + /** + * The world that this body is added to. This property is set to NULL if the body is not added to any world. + * @property world + * @type {World} + */ + this.world = null; + + /** + * The shapes of the body. + * + * @property shapes + * @type {Array} + */ + this.shapes = []; + + /** + * The mass of the body. + * @property mass + * @type {number} + */ + this.mass = options.mass || 0; + + /** + * The inverse mass of the body. + * @property invMass + * @type {number} + */ + this.invMass = 0; + + /** + * The inertia of the body around the Z axis. + * @property inertia + * @type {number} + */ + this.inertia = 0; + + /** + * The inverse inertia of the body. + * @property invInertia + * @type {number} + */ + this.invInertia = 0; + + this.invMassSolve = 0; + this.invInertiaSolve = 0; + + /** + * Set to true if you want to fix the rotation of the body. + * @property fixedRotation + * @type {Boolean} + */ + this.fixedRotation = !!options.fixedRotation; + + /** + * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y. + * @property {Boolean} fixedX + */ + this.fixedX = !!options.fixedX; + + /** + * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X. + * @property {Boolean} fixedY + */ + this.fixedY = !!options.fixedY; + + /** + * @private + * @property {array} massMultiplier + */ + this.massMultiplier = vec2.create(); + + /** + * The position of the body + * @property position + * @type {Array} + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * The interpolated position of the body. Use this for rendering. + * @property interpolatedPosition + * @type {Array} + */ + this.interpolatedPosition = vec2.fromValues(0,0); + + /** + * The interpolated angle of the body. Use this for rendering. + * @property interpolatedAngle + * @type {Number} + */ + this.interpolatedAngle = 0; + + /** + * The previous position of the body. + * @property previousPosition + * @type {Array} + */ + this.previousPosition = vec2.fromValues(0,0); + + /** + * The previous angle of the body. + * @property previousAngle + * @type {Number} + */ + this.previousAngle = 0; + + /** + * The current velocity of the body. + * @property velocity + * @type {Array} + */ + this.velocity = vec2.fromValues(0,0); + if(options.velocity){ + vec2.copy(this.velocity, options.velocity); + } + + /** + * Constraint velocity that was added to the body during the last step. + * @property vlambda + * @type {Array} + */ + this.vlambda = vec2.fromValues(0,0); + + /** + * Angular constraint velocity that was added to the body during last step. + * @property wlambda + * @type {Array} + */ + this.wlambda = 0; + + /** + * The angle of the body, in radians. + * @property angle + * @type {number} + * @example + * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. + * // If you need a value between 0 and 2*pi, use the following function to normalize it. + * function normalizeAngle(angle){ + * angle = angle % (2*Math.PI); + * if(angle < 0){ + * angle += (2*Math.PI); + * } + * return angle; + * } + */ + this.angle = options.angle || 0; + + /** + * The angular velocity of the body, in radians per second. + * @property angularVelocity + * @type {number} + */ + this.angularVelocity = options.angularVelocity || 0; + + /** + * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. + * @property force + * @type {Array} + * + * @example + * // This produces a forcefield of 1 Newton in the positive x direction. + * for(var i=0; i radius){ + radius = offset + r; + } + } + + this.boundingRadius = radius; +}; + +/** + * Add a shape to the body. You can pass a local transform when adding a shape, + * so that the shape gets an offset and angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * + * @method addShape + * @param {Shape} shape + * @param {Array} [offset] Local body offset of the shape. + * @param {Number} [angle] Local body angle. + * + * @example + * var body = new Body(), + * shape = new Circle({ radius: 1 }); + * + * // Add the shape to the body, positioned in the center + * body.addShape(shape); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. + * body.addShape(shape,[1,0]); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. + * body.addShape(shape,[0,1],Math.PI/2); + */ +Body.prototype.addShape = function(shape, offset, angle){ + if(shape.body){ + throw new Error('A shape can only be added to one body.'); + } + shape.body = this; + + // Copy the offset vector + if(offset){ + vec2.copy(shape.position, offset); + } else { + vec2.set(shape.position, 0, 0); + } + + shape.angle = angle || 0; + + this.shapes.push(shape); + this.updateMassProperties(); + this.updateBoundingRadius(); + + this.aabbNeedsUpdate = true; +}; + +/** + * Remove a shape + * @method removeShape + * @param {Shape} shape + * @return {Boolean} True if the shape was found and removed, else false. + */ +Body.prototype.removeShape = function(shape){ + var idx = this.shapes.indexOf(shape); + + if(idx !== -1){ + this.shapes.splice(idx,1); + this.aabbNeedsUpdate = true; + shape.body = null; + return true; + } else { + return false; + } +}; + +/** + * Updates .inertia, .invMass, .invInertia for this Body. Should be called when + * changing the structure or mass of the Body. + * + * @method updateMassProperties + * + * @example + * body.mass += 1; + * body.updateMassProperties(); + */ +Body.prototype.updateMassProperties = function(){ + if(this.type === Body.STATIC || this.type === 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; + } + + // Inverse mass properties are easy + this.invMass = 1 / this.mass; + + vec2.set( + this.massMultiplier, + this.fixedX ? 0 : 1, + this.fixedY ? 0 : 1 + ); + } +}; + +var Body_applyForce_r = vec2.create(); + +/** + * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero. + * @method applyForce + * @param {Array} force The force to add. + * @param {Array} [relativePoint] A world point to apply the force on. + */ +Body.prototype.applyForce = function(force, relativePoint){ + + // Add linear force + vec2.add(this.force, this.force, force); + + if(relativePoint){ + + // Compute produced rotational force + var rotForce = vec2.crossLength(relativePoint,force); + + // Add rotational force + this.angularForce += rotForce; + } +}; + +/** + * Apply force to a body-local point. + * @method applyForceLocal + * @param {Array} localForce The force vector to add, oriented in local body space. + * @param {Array} [localPoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyForce_forceWorld = vec2.create(); +var Body_applyForce_pointWorld = vec2.create(); +var Body_applyForce_pointLocal = vec2.create(); +Body.prototype.applyForceLocal = function(localForce, localPoint){ + localPoint = localPoint || Body_applyForce_pointLocal; + var worldForce = Body_applyForce_forceWorld; + var worldPoint = Body_applyForce_pointWorld; + this.vectorToWorldFrame(worldForce, localForce); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyForce(worldForce, worldPoint); +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulse + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_velo = vec2.create(); +Body.prototype.applyImpulse = function(impulseVector, relativePoint){ + if(this.type !== Body.DYNAMIC){ + return; + } + + // Compute produced central impulse velocity + var velo = Body_applyImpulse_velo; + vec2.scale(velo, impulseVector, this.invMass); + vec2.multiply(velo, this.massMultiplier, velo); + + // Add linear impulse + vec2.add(this.velocity, velo, this.velocity); + + if(relativePoint){ + // Compute produced rotational impulse velocity + var rotVelo = vec2.crossLength(relativePoint, impulseVector); + rotVelo *= this.invInertia; + + // Add rotational Impulse + this.angularVelocity += rotVelo; + } +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulseLocal + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_impulseWorld = vec2.create(); +var Body_applyImpulse_pointWorld = vec2.create(); +var Body_applyImpulse_pointLocal = vec2.create(); +Body.prototype.applyImpulseLocal = function(localImpulse, localPoint){ + localPoint = localPoint || Body_applyImpulse_pointLocal; + var worldImpulse = Body_applyImpulse_impulseWorld; + var worldPoint = Body_applyImpulse_pointWorld; + this.vectorToWorldFrame(worldImpulse, localImpulse); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyImpulse(worldImpulse, worldPoint); +}; + +/** + * Transform a world point to local body frame. + * @method toLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldPoint The input world point + */ +Body.prototype.toLocalFrame = function(out, worldPoint){ + vec2.toLocalFrame(out, worldPoint, this.position, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method toWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localPoint The input local point + */ +Body.prototype.toWorldFrame = function(out, localPoint){ + vec2.toGlobalFrame(out, localPoint, this.position, this.angle); +}; + +/** + * Transform a world point to local body frame. + * @method vectorToLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldVector The input world vector + */ +Body.prototype.vectorToLocalFrame = function(out, worldVector){ + vec2.vectorToLocalFrame(out, worldVector, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method vectorToWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localVector The input local vector + */ +Body.prototype.vectorToWorldFrame = function(out, localVector){ + vec2.vectorToGlobalFrame(out, localVector, this.angle); +}; + +/** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. + * @method fromPolygon + * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. + * @param {Object} [options] + * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. + * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @return {Boolean} True on success, else false. + */ +Body.prototype.fromPolygon = function(path,options){ + options = options || {}; + + // Remove all shapes + for(var i=this.shapes.length; i>=0; --i){ + this.removeShape(this.shapes[i]); + } + + var p = new decomp.Polygon(); + p.vertices = path; + + // Make it counter-clockwise + p.makeCCW(); + + if(typeof(options.removeCollinearPoints) === "number"){ + p.removeCollinearPoints(options.removeCollinearPoints); + } + + // Check if any line segment intersects the path itself + if(typeof(options.skipSimpleCheck) === "undefined"){ + if(!p.isSimple()){ + return false; + } + } + + // Save this path for later + this.concavePath = p.vertices.slice(0); + for(var i=0; ithis for details. + * @method applyDamping + * @param {number} dt Current time step + */ +Body.prototype.applyDamping = function(dt){ + if(this.type === Body.DYNAMIC){ // Only for dynamic bodies + var v = this.velocity; + vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); + this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); + } +}; + +/** + * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. + * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. + * @method wakeUp + */ +Body.prototype.wakeUp = function(){ + var s = this.sleepState; + this.sleepState = Body.AWAKE; + this.idleTime = 0; + if(s !== Body.AWAKE){ + this.emit(Body.wakeUpEvent); + } +}; + +/** + * Force body sleep + * @method sleep + */ +Body.prototype.sleep = function(){ + this.sleepState = Body.SLEEPING; + this.angularVelocity = 0; + this.angularForce = 0; + vec2.set(this.velocity,0,0); + vec2.set(this.force,0,0); + this.emit(Body.sleepEvent); +}; + +/** + * Called every timestep to update internal sleep timer and change sleep state if needed. + * @method sleepTick + * @param {number} time The world time in seconds + * @param {boolean} dontSleep + * @param {number} dt + */ +Body.prototype.sleepTick = function(time, dontSleep, dt){ + if(!this.allowSleep || this.type === Body.SLEEPING){ + return; + } + + this.wantsToSleep = false; + + var sleepState = this.sleepState, + speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), + speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); + + // Add to idle time + if(speedSquared >= 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; + } + } +}; + +/** + * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. + * @method overlaps + * @param {Body} body + * @return {boolean} + */ +Body.prototype.overlaps = function(body){ + return this.world.overlapKeeper.bodiesAreOverlapping(this, body); +}; + +var integrate_fhMinv = vec2.create(); +var integrate_velodt = vec2.create(); + +/** + * Move the body forward in time given its current velocity. + * @method integrate + * @param {Number} dt + */ +Body.prototype.integrate = function(dt){ + var minv = this.invMass, + f = this.force, + pos = this.position, + velo = this.velocity; + + // Save old position + vec2.copy(this.previousPosition, this.position); + this.previousAngle = this.angle; + + // Velocity update + if(!this.fixedRotation){ + this.angularVelocity += this.angularForce * this.invInertia * dt; + } + vec2.scale(integrate_fhMinv, f, dt * minv); + vec2.multiply(integrate_fhMinv, this.massMultiplier, integrate_fhMinv); + vec2.add(velo, integrate_fhMinv, velo); + + // CCD + if(!this.integrateToTimeOfImpact(dt)){ + + // Regular position update + vec2.scale(integrate_velodt, velo, dt); + vec2.add(pos, pos, integrate_velodt); + if(!this.fixedRotation){ + this.angle += this.angularVelocity * dt; + } + } + + this.aabbNeedsUpdate = true; +}; + +var result = new RaycastResult(); +var ray = new Ray({ + mode: Ray.ALL +}); +var direction = vec2.create(); +var end = vec2.create(); +var startToEnd = vec2.create(); +var rememberPosition = vec2.create(); +Body.prototype.integrateToTimeOfImpact = function(dt){ + + if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){ + return false; + } + + vec2.normalize(direction, this.velocity); + + vec2.scale(end, this.velocity, dt); + vec2.add(end, end, this.position); + + vec2.sub(startToEnd, end, this.position); + var startToEndAngle = this.angularVelocity * dt; + var len = vec2.length(startToEnd); + + var timeOfImpact = 1; + + var hit; + var that = this; + result.reset(); + ray.callback = function (result) { + if(result.body === that){ + return; + } + hit = result.body; + result.getHitPoint(end, ray); + vec2.sub(startToEnd, end, that.position); + timeOfImpact = vec2.length(startToEnd) / len; + result.stop(); + }; + vec2.copy(ray.from, this.position); + vec2.copy(ray.to, end); + ray.update(); + this.world.raycast(result, ray); + + if(!hit){ + return false; + } + + var rememberAngle = this.angle; + vec2.copy(rememberPosition, this.position); + + // Got a start and end point. Approximate time of impact using binary search + var iter = 0; + var tmin = 0; + var tmid = 0; + var tmax = timeOfImpact; + while (tmax >= tmin && iter < this.ccdIterations) { + iter++; + + // calculate the midpoint + tmid = (tmax - tmin) / 2; + + // Move the body to that point + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, rememberPosition, integrate_velodt); + this.angle = rememberAngle + startToEndAngle * timeOfImpact; + this.updateAABB(); + + // check overlap + var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit); + + if (overlaps) { + // change min to search upper interval + tmin = tmid; + } else { + // change max to search lower interval + tmax = tmid; + } + } + + timeOfImpact = tmid; + + vec2.copy(this.position, rememberPosition); + this.angle = rememberAngle; + + // move to TOI + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, this.position, integrate_velodt); + if(!this.fixedRotation){ + this.angle += startToEndAngle * timeOfImpact; + } + + return true; +}; + +/** + * Get velocity of a point in the body. + * @method getVelocityAtPoint + * @param {Array} result A vector to store the result in + * @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from + * @return {Array} The result vector + */ +Body.prototype.getVelocityAtPoint = function(result, relativePoint){ + vec2.crossVZ(result, relativePoint, this.angularVelocity); + vec2.subtract(result, this.velocity, result); + return result; +}; + +/** + * @event sleepy + */ +Body.sleepyEvent = { + type: "sleepy" +}; + +/** + * @event sleep + */ +Body.sleepEvent = { + type: "sleep" +}; + +/** + * @event wakeup + */ +Body.wakeUpEvent = { + type: "wakeup" +}; + +/** + * Dynamic body. + * @property DYNAMIC + * @type {Number} + * @static + */ +Body.DYNAMIC = 1; + +/** + * Static body. + * @property STATIC + * @type {Number} + * @static + */ +Body.STATIC = 2; + +/** + * Kinematic body. + * @property KINEMATIC + * @type {Number} + * @static + */ +Body.KINEMATIC = 4; + +/** + * @property AWAKE + * @type {Number} + * @static + */ +Body.AWAKE = 0; + +/** + * @property SLEEPY + * @type {Number} + * @static + */ +Body.SLEEPY = 1; + +/** + * @property SLEEPING + * @type {Number} + * @static + */ +Body.SLEEPING = 2; + + +},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = LinearSpring; + +/** + * A spring, connecting two bodies. + * + * The Spring explicitly adds force and angularForce to the bodies. + * + * @class LinearSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + */ +function LinearSpring(bodyA,bodyB,options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Anchor for bodyA in local bodyA coordinates. + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = vec2.fromValues(0,0); + + /** + * Anchor for bodyB in local bodyB coordinates. + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = vec2.fromValues(0,0); + + if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); } + if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); } + if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } + if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } + + var worldAnchorA = vec2.create(); + var worldAnchorB = vec2.create(); + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + var worldDistance = vec2.distance(worldAnchorA, worldAnchorB); + + /** + * Rest length of the spring. + * @property restLength + * @type {number} + */ + this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance; +} +LinearSpring.prototype = new Spring(); +LinearSpring.prototype.constructor = LinearSpring; + +/** + * Set the anchor point on body A, using world coordinates. + * @method setWorldAnchorA + * @param {Array} worldAnchorA + */ +LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){ + this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); +}; + +/** + * Set the anchor point on body B, using world coordinates. + * @method setWorldAnchorB + * @param {Array} worldAnchorB + */ +LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){ + this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); +}; + +/** + * Get the anchor point on body A, in world coordinates. + * @method getWorldAnchorA + * @param {Array} result The vector to store the result in. + */ +LinearSpring.prototype.getWorldAnchorA = function(result){ + this.bodyA.toWorldFrame(result, this.localAnchorA); +}; + +/** + * Get the anchor point on body B, in world coordinates. + * @method getWorldAnchorB + * @param {Array} result The vector to store the result in. + */ +LinearSpring.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(); + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +LinearSpring.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; + + // Get world anchors + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + + // Get offset points + vec2.sub(ri, worldAnchorA, bodyA.position); + vec2.sub(rj, worldAnchorB, bodyB.position); + + // Compute distance vector between world anchor points + vec2.sub(r, worldAnchorB, worldAnchorA); + var rlen = vec2.len(r); + vec2.normalize(r_unit,r); + + //console.log(rlen) + //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) + + // Compute relative velocity of the anchor points, u + 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); + + // F = - k * ( x - L ) - D * ( u ) + vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); + + // Add forces to bodies + vec2.sub( bodyA.force, bodyA.force, f); + vec2.add( bodyB.force, bodyB.force, f); + + // Angular force + 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":57,"./Spring":34}],33:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); + +module.exports = RotationalSpring; + +/** + * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies. + * + * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap. + * + * @class RotationalSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. + */ +function RotationalSpring(bodyA, bodyB, options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Rest angle of the spring. + * @property restAngle + * @type {number} + */ + this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle; +} +RotationalSpring.prototype = new Spring(); +RotationalSpring.prototype.constructor = RotationalSpring; + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +RotationalSpring.prototype.applyForce = function(){ + var k = this.stiffness, + d = this.damping, + l = this.restAngle, + bodyA = this.bodyA, + bodyB = this.bodyB, + x = bodyB.angle - bodyA.angle, + u = bodyB.angularVelocity - bodyA.angularVelocity; + + var torque = - k * (x - l) - d * u * 0; + + bodyA.angularForce -= torque; + bodyB.angularForce += torque; +}; + +},{"../math/vec2":30,"./Spring":34}],34:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = Spring; + +/** + * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver. + * + * @class Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + */ +function Spring(bodyA, bodyB, options){ + options = Utils.defaults(options,{ + stiffness: 100, + damping: 1, + }); + + /** + * Stiffness of the spring. + * @property stiffness + * @type {number} + */ + this.stiffness = options.stiffness; + + /** + * Damping of the spring. + * @property damping + * @type {number} + */ + this.damping = options.damping; + + /** + * First connected body. + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second connected body. + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; +} + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +Spring.prototype.applyForce = function(){ + // To be implemented by subclasses +}; + +},{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); +var Constraint = _dereq_('../constraints/Constraint'); +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Body = _dereq_('../objects/Body'); + +module.exports = TopDownVehicle; + +/** + * @class TopDownVehicle + * @constructor + * @param {Body} chassisBody A dynamic body, already added to the world. + * @param {Object} [options] + * + * @example + * + * // Create a dynamic body for the chassis + * var chassisBody = new Body({ + * mass: 1 + * }); + * var boxShape = new Box({ width: 0.5, height: 1 }); + * chassisBody.addShape(boxShape); + * world.addBody(chassisBody); + * + * // Create the vehicle + * var vehicle = new TopDownVehicle(chassisBody); + * + * // Add one front wheel and one back wheel - we don't actually need four :) + * var frontWheel = vehicle.addWheel({ + * localPosition: [0, 0.5] // front + * }); + * frontWheel.setSideFriction(4); + * + * // Back wheel + * var backWheel = vehicle.addWheel({ + * localPosition: [0, -0.5] // back + * }); + * backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift + * vehicle.addToWorld(world); + * + * // Steer value zero means straight forward. Positive is left and negative right. + * frontWheel.steerValue = Math.PI / 16; + * + * // Engine force forward + * backWheel.engineForce = 10; + * backWheel.setBrakeForce(0); + */ +function TopDownVehicle(chassisBody, options){ + options = options || {}; + + /** + * @property {Body} chassisBody + */ + this.chassisBody = chassisBody; + + /** + * @property {Array} wheels + */ + this.wheels = []; + + // A dummy body to constrain the chassis to + this.groundBody = new Body({ mass: 0 }); + + this.world = null; + + var that = this; + this.preStepCallback = function(){ + that.update(); + }; +} + +/** + * @method addToWorld + * @param {World} world + */ +TopDownVehicle.prototype.addToWorld = function(world){ + this.world = world; + world.addBody(this.groundBody); + world.on('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.addConstraint(wheel); + } +}; + +/** + * @method removeFromWorld + * @param {World} world + */ +TopDownVehicle.prototype.removeFromWorld = function(){ + var world = this.world; + world.removeBody(this.groundBody); + world.off('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.removeConstraint(wheel); + } + this.world = null; +}; + +/** + * @method addWheel + * @param {object} [wheelOptions] + * @return {WheelConstraint} + */ +TopDownVehicle.prototype.addWheel = function(wheelOptions){ + var wheel = new WheelConstraint(this,wheelOptions); + this.wheels.push(wheel); + return wheel; +}; + +/** + * @method update + */ +TopDownVehicle.prototype.update = function(){ + for (var i = 0; i < this.wheels.length; i++) { + this.wheels[i].update(); + } +}; + +/** + * @class WheelConstraint + * @constructor + * @extends {Constraint} + * @param {Vehicle} vehicle + * @param {object} [options] + * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero. + * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body. + * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction. + */ +function WheelConstraint(vehicle, options){ + options = options || {}; + + this.vehicle = vehicle; + + this.forwardEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + this.sideEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + /** + * @property {number} steerValue + */ + this.steerValue = 0; + + /** + * @property {number} engineForce + */ + this.engineForce = 0; + + this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5); + + /** + * @property {Array} localForwardVector + */ + this.localForwardVector = vec2.fromValues(0, 1); + if(options.localForwardVector){ + vec2.copy(this.localForwardVector, options.localForwardVector); + } + + /** + * @property {Array} localPosition + */ + this.localPosition = vec2.fromValues(0, 0); + if(options.localPosition){ + vec2.copy(this.localPosition, options.localPosition); + } + + Constraint.apply(this, vehicle.chassisBody, vehicle.groundBody); + + this.equations.push( + this.forwardEquation, + this.sideEquation + ); + + this.setBrakeForce(0); +} +WheelConstraint.prototype = new Constraint(); + +/** + * @method setForwardFriction + */ +WheelConstraint.prototype.setBrakeForce = function(force){ + this.forwardEquation.setSlipForce(force); +}; + +/** + * @method setSideFriction + */ +WheelConstraint.prototype.setSideFriction = function(force){ + this.sideEquation.setSlipForce(force); +}; + +var worldVelocity = vec2.create(); +var relativePoint = vec2.create(); + +/** + * @method getSpeed + */ +WheelConstraint.prototype.getSpeed = function(){ + this.vehicle.chassisBody.vectorToWorldFrame(relativePoint, this.localForwardVector); + this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity, relativePoint); + return vec2.dot(worldVelocity, relativePoint); +}; + +var tmpVec = vec2.create(); + +/** + * @method update + */ +WheelConstraint.prototype.update = function(){ + + // Directional + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t, this.localForwardVector); + vec2.rotate(this.sideEquation.t, this.localForwardVector, Math.PI / 2); + this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t, this.sideEquation.t); + + vec2.rotate(this.forwardEquation.t, this.forwardEquation.t, this.steerValue); + vec2.rotate(this.sideEquation.t, this.sideEquation.t, this.steerValue); + + // Attachment point + this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB, this.localPosition); + vec2.copy(this.sideEquation.contactPointB, this.forwardEquation.contactPointB); + + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA, this.localPosition); + vec2.copy(this.sideEquation.contactPointA, this.forwardEquation.contactPointA); + + // Add engine force + vec2.normalize(tmpVec, this.forwardEquation.t); + vec2.scale(tmpVec, tmpVec, this.engineForce); + + this.vehicle.chassisBody.applyForce(tmpVec, this.forwardEquation.contactPointA); +}; +},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(_dereq_,module,exports){ +// Export p2 classes +var p2 = module.exports = { + AABB : _dereq_('./collision/AABB'), + AngleLockEquation : _dereq_('./equations/AngleLockEquation'), + Body : _dereq_('./objects/Body'), + Broadphase : _dereq_('./collision/Broadphase'), + Capsule : _dereq_('./shapes/Capsule'), + Circle : _dereq_('./shapes/Circle'), + Constraint : _dereq_('./constraints/Constraint'), + ContactEquation : _dereq_('./equations/ContactEquation'), + ContactEquationPool : _dereq_('./utils/ContactEquationPool'), + ContactMaterial : _dereq_('./material/ContactMaterial'), + Convex : _dereq_('./shapes/Convex'), + DistanceConstraint : _dereq_('./constraints/DistanceConstraint'), + Equation : _dereq_('./equations/Equation'), + EventEmitter : _dereq_('./events/EventEmitter'), + FrictionEquation : _dereq_('./equations/FrictionEquation'), + FrictionEquationPool : _dereq_('./utils/FrictionEquationPool'), + GearConstraint : _dereq_('./constraints/GearConstraint'), + GSSolver : _dereq_('./solver/GSSolver'), + Heightfield : _dereq_('./shapes/Heightfield'), + Line : _dereq_('./shapes/Line'), + LockConstraint : _dereq_('./constraints/LockConstraint'), + Material : _dereq_('./material/Material'), + Narrowphase : _dereq_('./collision/Narrowphase'), + NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'), + Particle : _dereq_('./shapes/Particle'), + Plane : _dereq_('./shapes/Plane'), + Pool : _dereq_('./utils/Pool'), + RevoluteConstraint : _dereq_('./constraints/RevoluteConstraint'), + PrismaticConstraint : _dereq_('./constraints/PrismaticConstraint'), + Ray : _dereq_('./collision/Ray'), + RaycastResult : _dereq_('./collision/RaycastResult'), + Box : _dereq_('./shapes/Box'), + RotationalVelocityEquation : _dereq_('./equations/RotationalVelocityEquation'), + SAPBroadphase : _dereq_('./collision/SAPBroadphase'), + Shape : _dereq_('./shapes/Shape'), + Solver : _dereq_('./solver/Solver'), + Spring : _dereq_('./objects/Spring'), + TopDownVehicle : _dereq_('./objects/TopDownVehicle'), + LinearSpring : _dereq_('./objects/LinearSpring'), + RotationalSpring : _dereq_('./objects/RotationalSpring'), + Utils : _dereq_('./utils/Utils'), + World : _dereq_('./world/World'), + vec2 : _dereq_('./math/vec2'), + version : _dereq_('../package.json').version, +}; + +Object.defineProperty(p2, 'Rectangle', { + get: function() { + console.warn('The Rectangle class has been renamed to Box.'); + return this.Box; + } +}); +},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":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/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Shape = _dereq_('./Shape') +, Convex = _dereq_('./Convex'); + +module.exports = Box; + +/** + * Box shape class. + * @class Box + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.width=1] Total width of the box + * @param {Number} [options.height=1] Total height of the box + * @extends Convex + */ +function Box(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + width: arguments[0], + height: arguments[1] + }; + console.warn('The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })'); + } + options = options || {}; + + /** + * Total width of the box + * @property width + * @type {Number} + */ + var width = this.width = options.width || 1; + + /** + * Total height of the box + * @property height + * @type {Number} + */ + var height = this.height = options.height || 1; + + var verts = [ + vec2.fromValues(-width/2, -height/2), + vec2.fromValues( width/2, -height/2), + vec2.fromValues( width/2, height/2), + vec2.fromValues(-width/2, height/2) + ]; + var axes = [ + vec2.fromValues(1, 0), + vec2.fromValues(0, 1) + ]; + + options.vertices = verts; + options.axes = axes; + options.type = Shape.BOX; + Convex.call(this, options); +} +Box.prototype = new Convex(); +Box.prototype.constructor = Box; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Box.prototype.computeMomentOfInertia = function(mass){ + var w = this.width, + h = this.height; + return mass * (h*h + w*w) / 12; +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Box.prototype.updateBoundingRadius = function(){ + var w = this.width, + h = this.height; + this.boundingRadius = Math.sqrt(w*w + h*h) / 2; +}; + +var corner1 = vec2.create(), + corner2 = vec2.create(), + corner3 = vec2.create(), + corner4 = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Box.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices,position,angle,0); +}; + +Box.prototype.updateArea = function(){ + this.area = this.width * this.height; +}; + + +},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Capsule; + +/** + * Capsule shape class. + * @class Capsule + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The distance between the end points + * @param {Number} [options.radius=1] Radius of the capsule + * @example + * var capsuleShape = new Capsule({ + * length: 1, + * radius: 2 + * }); + * body.addShape(capsuleShape); + */ +function Capsule(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + length: arguments[0], + radius: arguments[1] + }; + console.warn('The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })'); + } + options = options || {}; + + /** + * The distance between the end points. + * @property {Number} length + */ + this.length = options.length || 1; + + /** + * The radius of the capsule. + * @property {Number} radius + */ + this.radius = options.radius || 1; + + options.type = Shape.CAPSULE; + Shape.call(this, options); +} +Capsule.prototype = new Shape(); +Capsule.prototype.constructor = Capsule; + +/** + * Compute the mass moment of inertia of the Capsule. + * @method conputeMomentOfInertia + * @param {Number} mass + * @return {Number} + * @todo + */ +Capsule.prototype.computeMomentOfInertia = function(mass){ + // Approximate with rectangle + var r = this.radius, + w = this.length + r, // 2*r is too much, 0 is too little + h = r*2; + return mass * (h*h + w*w) / 12; +}; + +/** + * @method updateBoundingRadius + */ +Capsule.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius + this.length/2; +}; + +/** + * @method updateArea + */ +Capsule.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; +}; + +var r = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Capsule.prototype.computeAABB = function(out, position, angle){ + var radius = this.radius; + + // Compute center position of one of the the circles, world oriented, but with local offset + vec2.set(r,this.length / 2,0); + if(angle !== 0){ + vec2.rotate(r,r,angle); + } + + // Get bounds + 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)); + + // Add offset + vec2.add(out.lowerBound, out.lowerBound, position); + vec2.add(out.upperBound, out.upperBound, position); +}; + +var intersectCapsule_hitPointWorld = vec2.create(); +var intersectCapsule_normal = vec2.create(); +var intersectCapsule_l0 = vec2.create(); +var intersectCapsule_l1 = vec2.create(); +var intersectCapsule_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Capsule.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectCapsule_hitPointWorld; + var normal = intersectCapsule_normal; + var l0 = intersectCapsule_l0; + var l1 = intersectCapsule_l1; + + // The sides + var halfLen = this.length / 2; + for(var i=0; i<2; i++){ + + // get start and end of the line + var y = this.radius * (i*2-1); + vec2.set(l0, -halfLen, y); + vec2.set(l1, halfLen, y); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var delta = vec2.getLineSegmentsIntersectionFraction(from, to, l0, l1); + if(delta >= 0){ + vec2.rotate(normal, intersectCapsule_unit_y, angle); + vec2.scale(normal, normal, (i*2-1)); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + // Circles + var diagonalLengthSquared = Math.pow(this.radius, 2) + Math.pow(halfLen, 2); + for(var i=0; i<2; i++){ + vec2.set(l0, halfLen * (i*2-1), 0); + vec2.toGlobalFrame(l0, l0, position, angle); + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - l0[0]) + (to[1] - from[1]) * (from[1] - l0[1])); + var c = Math.pow(from[0] - l0[0], 2) + Math.pow(from[1] - l0[1], 2) - Math.pow(this.radius, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + if(delta < 0){ + // No intersection + continue; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(hitPointWorld, from, to, delta); + + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(hitPointWorld, from, to, d1); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d1, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(hitPointWorld, from, to, d2); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d2, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + } + } +}; +},{"../math/vec2":30,"./Shape":45}],39:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Circle; + +/** + * Circle shape class. + * @class Circle + * @extends Shape + * @constructor + * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {number} [options.radius=1] The radius of this circle + * + * @example + * var circleShape = new Circle({ radius: 1 }); + * body.addShape(circleShape); + */ +function Circle(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + radius: arguments[0] + }; + console.warn('The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })'); + } + options = options || {}; + + /** + * The radius of the circle. + * @property radius + * @type {number} + */ + this.radius = options.radius || 1; + + options.type = Shape.CIRCLE; + Shape.call(this, options); +} +Circle.prototype = new Shape(); +Circle.prototype.constructor = Circle; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Circle.prototype.computeMomentOfInertia = function(mass){ + var r = this.radius; + return mass * r * r / 2; +}; + +/** + * @method updateBoundingRadius + * @return {Number} + */ +Circle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius; +}; + +/** + * @method updateArea + * @return {Number} + */ +Circle.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius; +}; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +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); + } +}; + +var Ray_intersectSphere_intersectionPoint = vec2.create(); +var Ray_intersectSphere_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Circle.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from, + to = ray.to, + r = this.radius; + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1])); + var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + var intersectionPoint = Ray_intersectSphere_intersectionPoint; + var normal = Ray_intersectSphere_normal; + + if(delta < 0){ + // No intersection + return; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(intersectionPoint, from, to, delta); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, delta, normal, -1); + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(intersectionPoint, from, to, d1); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d1, normal, -1); + + if(result.shouldStop(ray)){ + return; + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(intersectionPoint, from, to, d2); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d2, normal, -1); + } + } +}; +},{"../math/vec2":30,"./Shape":45}],40:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, polyk = _dereq_('../math/polyk') +, decomp = _dereq_('poly-decomp'); + +module.exports = Convex; + +/** + * Convex shape class. + * @class Convex + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. + * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex. + * @example + * // Create a box + * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]]; + * var convexShape = new Convex({ vertices: vertices }); + * body.addShape(convexShape); + */ +function Convex(options){ + if(Array.isArray(arguments[0])){ + options = { + vertices: arguments[0], + axes: arguments[1] + }; + console.warn('The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })'); + } + options = options || {}; + + /** + * Vertices defined in the local frame. + * @property vertices + * @type {Array} + */ + this.vertices = []; + + // Copy the verts + var vertices = options.vertices !== undefined ? options.vertices : []; + for(var i=0; i < vertices.length; i++){ + var v = vec2.create(); + vec2.copy(v, vertices[i]); + this.vertices.push(v); + } + + /** + * Axes defined in the local frame. + * @property axes + * @type {Array} + */ + this.axes = []; + + if(options.axes){ + + // Copy the axes + for(var i=0; i < options.axes.length; i++){ + var axis = vec2.create(); + vec2.copy(axis, options.axes[i]); + this.axes.push(axis); + } + + } else { + + // Construct axes from the vertex data + for(var i = 0; i < this.vertices.length; i++){ + // Get the world edge + var worldPoint0 = this.vertices[i]; + var worldPoint1 = this.vertices[(i+1) % this.vertices.length]; + + var normal = vec2.create(); + vec2.sub(normal, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, normal); + vec2.normalize(normal, normal); + + this.axes.push(normal); + } + + } + + /** + * The center of mass of the Convex + * @property centerOfMass + * @type {Array} + */ + this.centerOfMass = vec2.fromValues(0,0); + + /** + * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. + * @property triangles + * @type {Array} + */ + this.triangles = []; + + if(this.vertices.length){ + this.updateTriangles(); + this.updateCenterOfMass(); + } + + /** + * The bounding radius of the convex + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + options.type = Shape.CONVEX; + Shape.call(this, options); + + this.updateBoundingRadius(); + this.updateArea(); + if(this.area < 0){ + throw new Error("Convex vertices must be given in conter-clockwise winding."); + } +} +Convex.prototype = new Shape(); +Convex.prototype.constructor = Convex; + +var tmpVec1 = vec2.create(); +var tmpVec2 = vec2.create(); + +/** + * Project a Convex onto a world-oriented axis + * @method projectOntoAxis + * @static + * @param {Array} offset + * @param {Array} localAxis + * @param {Array} result + */ +Convex.prototype.projectOntoLocalAxis = function(localAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = tmpVec1; + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + vec2.set(result, min, max); +}; + +Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){ + var worldAxis = tmpVec2; + + this.projectOntoLocalAxis(localAxis, result); + + // Project the position of the body onto the axis - need to add this to the result + if(shapeAngle !== 0){ + vec2.rotate(worldAxis, localAxis, shapeAngle); + } else { + worldAxis = localAxis; + } + var offset = vec2.dot(shapeOffset, worldAxis); + + vec2.set(result, result[0] + offset, result[1] + offset); +}; + + +/** + * Update the .triangles property + * @method updateTriangles + */ +Convex.prototype.updateTriangles = function(){ + + this.triangles.length = 0; + + // Rewrite on polyk notation, array of numbers + var polykVerts = []; + for(var i=0; i r2){ + r2 = l2; + } + } + + this.boundingRadius = Math.sqrt(r2); +}; + +/** + * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. + * @static + * @method triangleArea + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +Convex.triangleArea = function(a,b,c){ + return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; +}; + +/** + * Update the .area + * @method updateArea + */ +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]]; + + // Get mass for the triangle (density=1 in this case) + var m = Convex.triangleArea(a,b,c); + this.area += m; + } +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Convex.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices, position, angle, 0); +}; + +var intersectConvex_rayStart = vec2.create(); +var intersectConvex_rayEnd = vec2.create(); +var intersectConvex_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Convex.prototype.raycast = function(result, ray, position, angle){ + var rayStart = intersectConvex_rayStart; + var rayEnd = intersectConvex_rayEnd; + var normal = intersectConvex_normal; + var vertices = this.vertices; + + // Transform to local shape space + vec2.toLocalFrame(rayStart, ray.from, position, angle); + vec2.toLocalFrame(rayEnd, ray.to, position, angle); + + var n = vertices.length; + + for (var i = 0; i < n && !result.shouldStop(ray); i++) { + var q1 = vertices[i]; + var q2 = vertices[(i+1) % n]; + var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2); + + if(delta >= 0){ + vec2.sub(normal, q2, q1); + vec2.rotate(normal, normal, -Math.PI / 2 + angle); + vec2.normalize(normal, normal); + ray.reportIntersection(result, delta, normal, i); + } + } +}; + +},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Heightfield; + +/** + * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". + * @class Heightfield + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {array} [options.heights] An array of Y values that will be used to construct the terrain. + * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given. + * @param {Number} [options.maxValue] Maximum value. + * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction. + * + * @example + * // Generate some height data (y-values). + * var heights = []; + * for(var i = 0; i < 1000; i++){ + * var y = 0.5 * Math.cos(0.2 * i); + * heights.push(y); + * } + * + * // Create the heightfield shape + * var heightfieldShape = new Heightfield({ + * heights: heights, + * elementWidth: 1 // Distance between the data points in X direction + * }); + * var heightfieldBody = new Body(); + * heightfieldBody.addShape(heightfieldShape); + * world.addBody(heightfieldBody); + * + * @todo Should use a scale property with X and Y direction instead of just elementWidth + */ +function Heightfield(options){ + if(Array.isArray(arguments[0])){ + options = { + heights: arguments[0] + }; + + if(typeof(arguments[1]) === 'object'){ + for(var key in arguments[1]){ + options[key] = arguments[1][key]; + } + } + + console.warn('The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })'); + } + options = options || {}; + + /** + * An array of numbers, or height values, that are spread out along the x axis. + * @property {array} heights + */ + this.heights = options.heights ? options.heights.slice(0) : []; + + /** + * Max value of the heights + * @property {number} maxValue + */ + this.maxValue = options.maxValue || null; + + /** + * Max value of the heights + * @property {number} minValue + */ + this.minValue = options.minValue || null; + + /** + * The width of each element + * @property {number} elementWidth + */ + this.elementWidth = options.elementWidth || 0.1; + + if(options.maxValue === undefined || options.minValue === undefined){ + this.updateMaxMinValues(); + } + + options.type = Shape.HEIGHTFIELD; + Shape.call(this, options); +} +Heightfield.prototype = new Shape(); +Heightfield.prototype.constructor = Heightfield; + +/** + * Update the .minValue and the .maxValue + * @method updateMaxMinValues + */ +Heightfield.prototype.updateMaxMinValues = function(){ + var data = this.heights; + var maxValue = data[0]; + var minValue = data[0]; + for(var i=0; i !== data.length; i++){ + var v = data[i]; + if(v > maxValue){ + maxValue = v; + } + if(v < minValue){ + minValue = v; + } + } + this.maxValue = maxValue; + this.minValue = minValue; +}; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Heightfield.prototype.computeMomentOfInertia = function(mass){ + return Number.MAX_VALUE; +}; + +Heightfield.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +Heightfield.prototype.updateArea = function(){ + var data = this.heights, + area = 0; + for(var i=0; i= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + var intX = p0[0] + (t * s1_x); + var intY = p0[1] + (t * s1_y); + out[0] = intX; + out[1] = intY; + return t; + } + return -1; // No collision +} + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Heightfield.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectHeightfield_hitPointWorld; + var worldNormal = intersectHeightfield_worldNormal; + var l0 = intersectHeightfield_l0; + var l1 = intersectHeightfield_l1; + var localFrom = intersectHeightfield_localFrom; + var localTo = intersectHeightfield_localTo; + + // get local ray start and end + vec2.toLocalFrame(localFrom, from, position, angle); + vec2.toLocalFrame(localTo, to, position, angle); + + // Get the segment range + var i0 = this.getClampedSegmentIndex(localFrom); + var i1 = this.getClampedSegmentIndex(localTo); + if(i0 > i1){ + var tmp = i0; + i0 = i1; + i1 = tmp; + } + + // The segments + for(var i=0; i= 0){ + vec2.sub(worldNormal, l1, l0); + vec2.rotate(worldNormal, worldNormal, angle + Math.PI / 2); + vec2.normalize(worldNormal, worldNormal); + ray.reportIntersection(result, t, worldNormal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Line; + +/** + * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * @class Line + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The total length of the line + * @extends Shape + * @constructor + */ +function Line(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + length: arguments[0] + }; + console.warn('The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })'); + } + options = options || {}; + + /** + * Length of this line + * @property {Number} length + * @default 1 + */ + this.length = options.length || 1; + + options.type = Shape.LINE; + Shape.call(this, options); +} +Line.prototype = new Shape(); +Line.prototype.constructor = Line; + +Line.prototype.computeMomentOfInertia = function(mass){ + return mass * Math.pow(this.length,2) / 12; +}; + +Line.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.length/2; +}; + +var points = [vec2.create(),vec2.create()]; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Line.prototype.computeAABB = function(out, position, angle){ + var l2 = this.length / 2; + vec2.set(points[0], -l2, 0); + vec2.set(points[1], l2, 0); + out.setFromPoints(points,position,angle,0); +}; + +var raycast_hitPoint = vec2.create(); +var raycast_normal = vec2.create(); +var raycast_l0 = vec2.create(); +var raycast_l1 = vec2.create(); +var raycast_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {number} angle + * @param {array} position + */ +Line.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + + var l0 = raycast_l0; + var l1 = raycast_l1; + + // get start and end of the line + var halfLen = this.length / 2; + vec2.set(l0, -halfLen, 0); + vec2.set(l1, halfLen, 0); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to); + if(fraction >= 0){ + var normal = raycast_normal; + vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from + ray.reportIntersection(result, fraction, normal, -1); + } +}; +},{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Particle; + +/** + * Particle shape class. + * @class Particle + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @extends Shape + */ +function Particle(options){ + options = options || {}; + options.type = Shape.PARTICLE; + Shape.call(this, options); +} +Particle.prototype = new Shape(); +Particle.prototype.constructor = Particle; + +Particle.prototype.computeMomentOfInertia = function(mass){ + return 0; // Can't rotate a particle +}; + +Particle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = 0; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Particle.prototype.computeAABB = function(out, position, angle){ + vec2.copy(out.lowerBound, position); + vec2.copy(out.upperBound, position); +}; + +},{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Plane; + +/** + * Plane shape class. The plane is facing in the Y direction. + * @class Plane + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + */ +function Plane(options){ + options = options || {}; + options.type = Shape.PLANE; + Shape.call(this, options); +} +Plane.prototype = new Shape(); +Plane.prototype.constructor = Plane; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + */ +Plane.prototype.computeMomentOfInertia = function(mass){ + return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Plane.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Plane.prototype.computeAABB = function(out, position, angle){ + var a = angle % (2 * Math.PI); + var set = vec2.set; + var max = 1e7; + var lowerBound = out.lowerBound; + var upperBound = out.upperBound; + + // Set max bounds + set(lowerBound, -max, -max); + set(upperBound, max, max); + + if(a === 0){ + // y goes from -inf to 0 + upperBound[1] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, max, 0); + + } else if(a === Math.PI / 2){ + + // x goes from 0 to inf + lowerBound[0] = 0; + // set(lowerBound, 0, -max); + // set(upperBound, max, max); + + } else if(a === Math.PI){ + + // y goes from 0 to inf + lowerBound[1] = 0; + // set(lowerBound, -max, 0); + // set(upperBound, max, max); + + } else if(a === 3*Math.PI/2){ + + // x goes from -inf to 0 + upperBound[0] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, 0, max); + + } +}; + +Plane.prototype.updateArea = function(){ + this.area = Number.MAX_VALUE; +}; + +var intersectPlane_planePointToFrom = vec2.create(); +var intersectPlane_dir_scaled_with_t = vec2.create(); +var intersectPlane_hitPoint = vec2.create(); +var intersectPlane_normal = vec2.create(); +var intersectPlane_len = vec2.create(); + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Plane.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + var planePointToFrom = intersectPlane_planePointToFrom; + var dir_scaled_with_t = intersectPlane_dir_scaled_with_t; + var hitPoint = intersectPlane_hitPoint; + var normal = intersectPlane_normal; + var len = intersectPlane_len; + + // Get plane normal + vec2.set(normal, 0, 1); + vec2.rotate(normal, normal, angle); + + vec2.sub(len, from, position); + var planeToFrom = vec2.dot(len, normal); + vec2.sub(len, to, position); + var planeToTo = vec2.dot(len, normal); + + if(planeToFrom * planeToTo > 0){ + // "from" and "to" are on the same side of the plane... bail out + return; + } + + if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){ + return; + } + + var n_dot_dir = vec2.dot(normal, direction); + + vec2.sub(planePointToFrom, from, position); + var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length; + + ray.reportIntersection(result, t, normal, -1); +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(_dereq_,module,exports){ +module.exports = Shape; + +var vec2 = _dereq_('../math/vec2'); + +/** + * Base class for shapes. + * @class Shape + * @constructor + * @param {object} [options] + * @param {array} [options.position] + * @param {number} [options.angle=0] + * @param {number} [options.collisionGroup=1] + * @param {number} [options.collisionMask=1] + * @param {boolean} [options.sensor=false] + * @param {boolean} [options.collisionResponse=true] + * @param {object} [options.type=0] + */ +function Shape(options){ + options = options || {}; + + /** + * The body this shape is attached to. A shape can only be attached to a single body. + * @property {Body} body + */ + this.body = null; + + /** + * Body-local position of the shape. + * @property {Array} position + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * Body-local angle of the shape. + * @property {number} angle + */ + this.angle = options.angle || 0; + + /** + * The type of the shape. One of: + * + * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} + * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} + * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} + * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} + * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} + * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}} + * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} + * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} + * + * @property {number} type + */ + this.type = options.type || 0; + + /** + * Shape object identifier. + * @type {Number} + * @property id + */ + this.id = Shape.idCounter++; + + /** + * Bounding circle radius of this shape + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + /** + * Collision group that this shape belongs to (bit mask). See this tutorial. + * @property collisionGroup + * @type {Number} + * @example + * // Setup bits for each available group + * var PLAYER = Math.pow(2,0), + * ENEMY = Math.pow(2,1), + * GROUND = Math.pow(2,2) + * + * // Put shapes into their groups + * player1Shape.collisionGroup = PLAYER; + * player2Shape.collisionGroup = PLAYER; + * enemyShape .collisionGroup = ENEMY; + * groundShape .collisionGroup = GROUND; + * + * // Assign groups that each shape collide with. + * // Note that the players can collide with ground and enemies, but not with other players. + * player1Shape.collisionMask = ENEMY | GROUND; + * player2Shape.collisionMask = ENEMY | GROUND; + * enemyShape .collisionMask = PLAYER | GROUND; + * groundShape .collisionMask = PLAYER | ENEMY; + * + * @example + * // How collision check is done + * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ + * // The shapes will collide + * } + */ + this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. + * @property {Boolean} collisionResponse + */ + this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; + + /** + * Collision mask of this shape. See .collisionGroup. + * @property collisionMask + * @type {Number} + */ + this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; + + /** + * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. + * @property material + * @type {Material} + */ + this.material = options.material || null; + + /** + * Area of this shape. + * @property area + * @type {Number} + */ + this.area = 0; + + /** + * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. + * @property {Boolean} sensor + */ + this.sensor = options.sensor !== undefined ? options.sensor : false; + + if(this.type){ + this.updateBoundingRadius(); + } + + this.updateArea(); +} + +Shape.idCounter = 0; + +/** + * @static + * @property {Number} CIRCLE + */ +Shape.CIRCLE = 1; + +/** + * @static + * @property {Number} PARTICLE + */ +Shape.PARTICLE = 2; + +/** + * @static + * @property {Number} PLANE + */ +Shape.PLANE = 4; + +/** + * @static + * @property {Number} CONVEX + */ +Shape.CONVEX = 8; + +/** + * @static + * @property {Number} LINE + */ +Shape.LINE = 16; + +/** + * @static + * @property {Number} BOX + */ +Shape.BOX = 32; + +/** + * @static + * @property {Number} CAPSULE + */ +Shape.CAPSULE = 64; + +/** + * @static + * @property {Number} HEIGHTFIELD + */ +Shape.HEIGHTFIELD = 128; + +/** + * Should return the moment of inertia around the Z axis of the body given the total mass. See Wikipedia's list of moments of inertia. + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. + */ +Shape.prototype.computeMomentOfInertia = function(mass){}; + +/** + * Returns the bounding circle radius of this shape. + * @method updateBoundingRadius + * @return {Number} + */ +Shape.prototype.updateBoundingRadius = function(){}; + +/** + * Update the .area property of the shape. + * @method updateArea + */ +Shape.prototype.updateArea = function(){ + // To be implemented in all subclasses +}; + +/** + * Compute the world axis-aligned bounding box (AABB) of this shape. + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position World position of the shape. + * @param {Number} angle World angle of the shape. + */ +Shape.prototype.computeAABB = function(out, position, angle){ + // To be implemented in each subclass +}; + +/** + * Perform raycasting on this shape. + * @method raycast + * @param {RayResult} result Where to store the resulting data. + * @param {Ray} ray The Ray that you want to use for raycasting. + * @param {array} position World position of the shape (the .position property will be ignored). + * @param {number} angle World angle of the shape (the .angle property will be ignored). + */ +Shape.prototype.raycast = function(result, ray, position, angle){ + // To be implemented in each subclass +}; +},{"../math/vec2":30}],46:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Solver = _dereq_('./Solver') +, Utils = _dereq_('../utils/Utils') +, FrictionEquation = _dereq_('../equations/FrictionEquation'); + +module.exports = GSSolver; + +/** + * Iterative Gauss-Seidel constraint equation solver. + * + * @class GSSolver + * @constructor + * @extends Solver + * @param {Object} [options] + * @param {Number} [options.iterations=10] + * @param {Number} [options.tolerance=0] + */ +function GSSolver(options){ + Solver.call(this,options,Solver.GS); + options = options || {}; + + /** + * The max number of iterations to do when solving. More gives better results, but is more expensive. + * @property iterations + * @type {Number} + */ + this.iterations = options.iterations || 10; + + /** + * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. + * @property tolerance + * @type {Number} + * @default 1e-7 + */ + this.tolerance = options.tolerance || 1e-7; + + this.arrayStep = 30; + this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); + + /** + * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. + * @property useZeroRHS + * @type {Boolean} + * @todo Remove, not used + */ + this.useZeroRHS = false; + + /** + * Number of solver iterations that are used to approximate normal forces used for friction (F_friction = mu * F_normal). These friction forces will override any other friction forces that are set. If you set frictionIterations = 0, then this feature will be disabled. + * + * Use only frictionIterations > 0 if the approximated normal force (F_normal = mass * gravity) is not good enough. Examples of where it can happen is in space games where gravity is zero, or in tall stacks where the normal force is large at bottom but small at top. + * + * @property frictionIterations + * @type {Number} + * @default 0 + */ + this.frictionIterations = options.frictionIterations !== undefined ? 0 : options.frictionIterations; + + /** + * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. + * @property {Number} usedIterations + */ + this.usedIterations = 0; +} +GSSolver.prototype = new Solver(); +GSSolver.prototype.constructor = GSSolver; + +function setArrayZero(array){ + var l = array.length; + while(l--){ + array[l] = +0.0; + } +} + +/** + * Solve the system of equations + * @method solve + * @param {Number} h Time step + * @param {World} world World to solve + */ +GSSolver.prototype.solve = function(h, world){ + + this.sortEquations(); + + var iter = 0, + maxIter = this.iterations, + maxFrictionIter = this.frictionIterations, + equations = this.equations, + Neq = equations.length, + tolSquared = Math.pow(this.tolerance*Neq, 2), + bodies = world.bodies, + Nbodies = world.bodies.length, + add = vec2.add, + set = vec2.set, + useZeroRHS = this.useZeroRHS, + lambda = this.lambda; + + this.usedIterations = 0; + + if(Neq){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Update solve mass + b.updateSolveMassProperties(); + } + } + + // Things that does not change during iteration can be computed once + if(lambda.length < Neq){ + lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + } + setArrayZero(lambda); + var invCs = this.invCs, + Bs = this.Bs, + lambda = this.lambda; + + for(var i=0; i!==equations.length; i++){ + var c = equations[i]; + if(c.timeStep !== h || c.needsUpdate){ + c.timeStep = h; + c.update(); + } + Bs[i] = c.computeB(c.a,c.b,h); + invCs[i] = c.computeInvC(c.epsilon); + } + + var q, B, c, deltalambdaTot,i,j; + + if(Neq !== 0){ + + for(i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Reset vlambda + b.resetConstraintVelocity(); + } + + if(maxFrictionIter){ + // Iterate over contact equations to get normal forces + for(iter=0; iter!==maxFrictionIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + + // Set computed friction force + for(j=0; j!==Neq; j++){ + var eq = equations[j]; + if(eq instanceof FrictionEquation){ + var f = 0.0; + for(var k=0; k!==eq.contactEquations.length; k++){ + f += eq.contactEquations[k].multiplier; + } + f *= eq.frictionCoefficient / eq.contactEquations.length; + eq.maxForce = f; + eq.minForce = -f; + } + } + } + + // Iterate over all equations + for(iter=0; iter!==maxIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + // Add result to velocity + for(i=0; i!==Nbodies; i++){ + bodies[i].addConstraintVelocity(); + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + } +}; + +// Sets the .multiplier property of each equation +GSSolver.updateMultipliers = function(equations, lambda, invDt){ + // Set the .multiplier property of each equation + var l = equations.length; + while(l--){ + equations[l].multiplier = lambda[l] * invDt; + } +}; + +GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ + // Compute iteration + var B = Bs[j], + invC = invCs[j], + lambdaj = lambda[j], + GWlambda = eq.computeGWlambda(); + + var maxForce = eq.maxForce, + minForce = eq.minForce; + + if(useZeroRHS){ + B = 0; + } + + var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); + + // Clamp if we are not within the min/max interval + var lambdaj_plus_deltalambda = lambdaj + deltalambda; + if(lambdaj_plus_deltalambda < minForce*dt){ + deltalambda = minForce*dt - lambdaj; + } else if(lambdaj_plus_deltalambda > maxForce*dt){ + deltalambda = maxForce*dt - lambdaj; + } + lambda[j] += deltalambda; + eq.addToWlambda(deltalambda); + + return deltalambda; +}; + +},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Solver; + +/** + * Base class for constraint solvers. + * @class Solver + * @constructor + * @extends EventEmitter + */ +function Solver(options,type){ + options = options || {}; + + EventEmitter.call(this); + + this.type = type; + + /** + * Current equations in the solver. + * + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Function that is used to sort all equations before each solve. + * @property equationSortFunction + * @type {function|boolean} + */ + this.equationSortFunction = options.equationSortFunction || false; +} +Solver.prototype = new EventEmitter(); +Solver.prototype.constructor = Solver; + +/** + * Method to be implemented in each subclass + * @method solve + * @param {Number} dt + * @param {World} world + */ +Solver.prototype.solve = function(dt,world){ + throw new Error("Solver.solve should be implemented by subclasses!"); +}; + +var mockWorld = {bodies:[]}; + +/** + * Solves all constraints in an island. + * @method solveIsland + * @param {Number} dt + * @param {Island} island + */ +Solver.prototype.solveIsland = function(dt,island){ + + this.removeAllEquations(); + + if(island.equations.length){ + // Add equations to solver + this.addEquations(island.equations); + mockWorld.bodies.length = 0; + island.getBodies(mockWorld.bodies); + + // Solve + if(mockWorld.bodies.length){ + this.solve(dt,mockWorld); + } + } +}; + +/** + * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. + * @method sortEquations + */ +Solver.prototype.sortEquations = function(){ + if(this.equationSortFunction){ + this.equations.sort(this.equationSortFunction); + } +}; + +/** + * Add an equation to be solved. + * + * @method addEquation + * @param {Equation} eq + */ +Solver.prototype.addEquation = function(eq){ + if(eq.enabled){ + this.equations.push(eq); + } +}; + +/** + * Add equations. Same as .addEquation, but this time the argument is an array of Equations + * + * @method addEquations + * @param {Array} eqs + */ +Solver.prototype.addEquations = function(eqs){ + //Utils.appendArray(this.equations,eqs); + for(var i=0, N=eqs.length; i!==N; i++){ + var eq = eqs[i]; + if(eq.enabled){ + this.equations.push(eq); + } + } +}; + +/** + * Remove an equation. + * + * @method removeEquation + * @param {Equation} eq + */ +Solver.prototype.removeEquation = function(eq){ + var i = this.equations.indexOf(eq); + if(i !== -1){ + this.equations.splice(i,1); + } +}; + +/** + * Remove all currently added equations. + * + * @method removeAllEquations + */ +Solver.prototype.removeAllEquations = function(){ + this.equations.length=0; +}; + +Solver.GS = 1; +Solver.ISLAND = 2; + +},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){ +var ContactEquation = _dereq_('../equations/ContactEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = ContactEquationPool; + +/** + * @class + */ +function ContactEquationPool() { + Pool.apply(this, arguments); +} +ContactEquationPool.prototype = new Pool(); +ContactEquationPool.prototype.constructor = ContactEquationPool; + +/** + * @method create + * @return {ContactEquation} + */ +ContactEquationPool.prototype.create = function () { + return new ContactEquation(); +}; + +/** + * @method destroy + * @param {ContactEquation} equation + * @return {ContactEquationPool} + */ +ContactEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){ +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = FrictionEquationPool; + +/** + * @class + */ +function FrictionEquationPool() { + Pool.apply(this, arguments); +} +FrictionEquationPool.prototype = new Pool(); +FrictionEquationPool.prototype.constructor = FrictionEquationPool; + +/** + * @method create + * @return {FrictionEquation} + */ +FrictionEquationPool.prototype.create = function () { + return new FrictionEquation(); +}; + +/** + * @method destroy + * @param {FrictionEquation} equation + * @return {FrictionEquationPool} + */ +FrictionEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){ +var IslandNode = _dereq_('../world/IslandNode'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandNodePool; + +/** + * @class + */ +function IslandNodePool() { + Pool.apply(this, arguments); +} +IslandNodePool.prototype = new Pool(); +IslandNodePool.prototype.constructor = IslandNodePool; + +/** + * @method create + * @return {IslandNode} + */ +IslandNodePool.prototype.create = function () { + return new IslandNode(); +}; + +/** + * @method destroy + * @param {IslandNode} node + * @return {IslandNodePool} + */ +IslandNodePool.prototype.destroy = function (node) { + node.reset(); + return this; +}; + +},{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){ +var Island = _dereq_('../world/Island'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandPool; + +/** + * @class + */ +function IslandPool() { + Pool.apply(this, arguments); +} +IslandPool.prototype = new Pool(); +IslandPool.prototype.constructor = IslandPool; + +/** + * @method create + * @return {Island} + */ +IslandPool.prototype.create = function () { + return new Island(); +}; + +/** + * @method destroy + * @param {Island} island + * @return {IslandPool} + */ +IslandPool.prototype.destroy = function (island) { + island.reset(); + return this; +}; + +},{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){ +var TupleDictionary = _dereq_('./TupleDictionary'); +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool'); +var Utils = _dereq_('./Utils'); + +module.exports = OverlapKeeper; + +/** + * Keeps track of overlaps in the current state and the last step state. + * @class OverlapKeeper + * @constructor + */ +function OverlapKeeper() { + this.overlappingShapesLastState = new TupleDictionary(); + this.overlappingShapesCurrentState = new TupleDictionary(); + this.recordPool = new OverlapKeeperRecordPool({ size: 16 }); + this.tmpDict = new TupleDictionary(); + this.tmpArray1 = []; +} + +/** + * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current. + * @method tick + */ +OverlapKeeper.prototype.tick = function() { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Save old objects into pool + var l = last.keys.length; + while(l--){ + var key = last.keys[l]; + var lastObject = last.getByKey(key); + var currentObject = current.getByKey(key); + if(lastObject){ + // The record is only used in the "last" dict, and will be removed. We might as well pool it. + this.recordPool.release(lastObject); + } + } + + // Clear last object + last.reset(); + + // Transfer from new object to old + last.copy(current); + + // Clear current object + current.reset(); +}; + +/** + * @method setOverlapping + * @param {Body} bodyA + * @param {Body} shapeA + * @param {Body} bodyB + * @param {Body} shapeB + */ +OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Store current contact state + if(!current.get(shapeA.id, shapeB.id)){ + var data = this.recordPool.get(); + data.set(bodyA, shapeA, bodyB, shapeB); + current.set(shapeA.id, shapeB.id, data); + } +}; + +OverlapKeeper.prototype.getNewOverlaps = function(result){ + return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result); +}; + +OverlapKeeper.prototype.getEndOverlaps = function(result){ + return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result); +}; + +/** + * Checks if two bodies are currently overlapping. + * @method bodiesAreOverlapping + * @param {Body} bodyA + * @param {Body} bodyB + * @return {boolean} + */ +OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){ + var current = this.overlappingShapesCurrentState; + var l = current.keys.length; + while(l--){ + var key = current.keys[l]; + var data = current.data[key]; + if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){ + return true; + } + } + return false; +}; + +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){ + // Not overlapping in last state, but in current. + result.push(data); + } + } + + return result; +}; + +OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ + var idA = shapeA.id|0, + idB = shapeB.id|0; + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + // Not in last but in new + return !!!last.get(idA, idB) && !!current.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]; + + // Since we use body id's for the accumulator, these will be a subset of the original one + accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); + } + + l = accumulator.keys.length; + while(l--){ + var data = accumulator.getByKey(accumulator.keys[l]); + if(data){ + result.push(data.bodyA, data.bodyB); + } + } + + accumulator.reset(); + + return result; +}; + +},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){ +module.exports = OverlapKeeperRecord; + +/** + * Overlap data container for the OverlapKeeper + * @class OverlapKeeperRecord + * @constructor + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ + /** + * @property {Shape} shapeA + */ + this.shapeA = shapeA; + /** + * @property {Shape} shapeB + */ + this.shapeB = shapeB; + /** + * @property {Body} bodyA + */ + this.bodyA = bodyA; + /** + * @property {Body} bodyB + */ + this.bodyB = bodyB; +} + +/** + * Set the data for the record + * @method set + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ + OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); +}; + +},{}],54:[function(_dereq_,module,exports){ +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var Pool = _dereq_('./Pool'); + +module.exports = OverlapKeeperRecordPool; + +/** + * @class + */ +function OverlapKeeperRecordPool() { + Pool.apply(this, arguments); +} +OverlapKeeperRecordPool.prototype = new Pool(); +OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool; + +/** + * @method create + * @return {OverlapKeeperRecord} + */ +OverlapKeeperRecordPool.prototype.create = function () { + return new OverlapKeeperRecord(); +}; + +/** + * @method destroy + * @param {OverlapKeeperRecord} record + * @return {OverlapKeeperRecordPool} + */ +OverlapKeeperRecordPool.prototype.destroy = function (record) { + record.bodyA = record.bodyB = record.shapeA = record.shapeB = null; + return this; +}; + +},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){ +module.exports = Pool; + +/** + * @class Object pooling utility. + */ +function Pool(options) { + options = options || {}; + + /** + * @property {Array} objects + * @type {Array} + */ + this.objects = []; + + if(options.size !== undefined){ + this.resize(options.size); + } +} + +/** + * @method resize + * @param {number} size + * @return {Pool} Self, for chaining + */ +Pool.prototype.resize = function (size) { + var objects = this.objects; + + while (objects.length > size) { + objects.pop(); + } + + while (objects.length < size) { + objects.push(this.create()); + } + + return this; +}; + +/** + * Get an object from the pool or create a new instance. + * @method get + * @return {Object} + */ +Pool.prototype.get = function () { + var objects = this.objects; + return objects.length ? objects.pop() : this.create(); +}; + +/** + * Clean up and put the object back into the pool for later use. + * @method release + * @param {Object} object + * @return {Pool} Self for chaining + */ +Pool.prototype.release = function (object) { + this.destroy(object); + this.objects.push(object); + return this; +}; + +},{}],56:[function(_dereq_,module,exports){ +var Utils = _dereq_('./Utils'); + +module.exports = TupleDictionary; + +/** + * @class TupleDictionary + * @constructor + */ +function TupleDictionary() { + + /** + * The data storage + * @property data + * @type {Object} + */ + this.data = {}; + + /** + * Keys that are currently used. + * @property {Array} keys + */ + this.keys = []; +} + +/** + * Generate a key given two integers + * @method getKey + * @param {number} i + * @param {number} j + * @return {string} + */ +TupleDictionary.prototype.getKey = function(id1, id2) { + id1 = id1|0; + id2 = id2|0; + + if ( (id1|0) === (id2|0) ){ + return -1; + } + + // valid for values < 2^16 + return ((id1|0) > (id2|0) ? + (id1 << 16) | (id2 & 0xFFFF) : + (id2 << 16) | (id1 & 0xFFFF))|0 + ; +}; + +/** + * @method getByKey + * @param {Number} key + * @return {Object} + */ +TupleDictionary.prototype.getByKey = function(key) { + key = key|0; + return this.data[key]; +}; + +/** + * @method get + * @param {Number} i + * @param {Number} j + * @return {Number} + */ +TupleDictionary.prototype.get = function(i, j) { + return this.data[this.getKey(i, j)]; +}; + +/** + * Set a value. + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +TupleDictionary.prototype.set = function(i, j, value) { + if(!value){ + throw new Error("No data!"); + } + + var key = this.getKey(i, j); + + // Check if key already exists + if(!this.data[key]){ + this.keys.push(key); + } + + this.data[key] = value; + + return key; +}; + +/** + * Remove all data. + * @method reset + */ +TupleDictionary.prototype.reset = function() { + var data = this.data, + keys = this.keys; + + var l = keys.length; + while(l--) { + delete data[keys[l]]; + } + + keys.length = 0; +}; + +/** + * Copy another TupleDictionary. Note that all data in this dictionary will be removed. + * @method copy + * @param {TupleDictionary} dict The TupleDictionary to copy into this one. + */ +TupleDictionary.prototype.copy = function(dict) { + this.reset(); + Utils.appendArray(this.keys, dict.keys); + var l = dict.keys.length; + while(l--){ + var key = dict.keys[l]; + this.data[key] = dict.data[key]; + } +}; + +},{"./Utils":57}],57:[function(_dereq_,module,exports){ +/* global P2_ARRAY_TYPE */ + +module.exports = Utils; + +/** + * Misc utility functions + * @class Utils + * @constructor + */ +function Utils(){} + +/** + * Append the values in array b to the array a. See this for an explanation. + * @method appendArray + * @static + * @param {Array} a + * @param {Array} b + */ +Utils.appendArray = function(a,b){ + if (b.length < 150000) { + a.push.apply(a, b); + } else { + for (var i = 0, len = b.length; i !== len; ++i) { + a.push(b[i]); + } + } +}; + +/** + * Garbage free Array.splice(). Does not allocate a new array. + * @method splice + * @static + * @param {Array} array + * @param {Number} index + * @param {Number} howmany + */ +Utils.splice = function(array,index,howmany){ + howmany = howmany || 1; + for (var i=index, len=array.length-howmany; i < len; i++){ + array[i] = array[i + howmany]; + } + array.length = len; +}; + +/** + * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. + * @static + * @property {function} ARRAY_TYPE + * @example + * + * + */ +if(typeof P2_ARRAY_TYPE !== 'undefined') { + Utils.ARRAY_TYPE = P2_ARRAY_TYPE; +} else if (typeof Float32Array !== 'undefined'){ + Utils.ARRAY_TYPE = Float32Array; +} else { + Utils.ARRAY_TYPE = Array; +} + +/** + * Extend an object with the properties of another + * @static + * @method extend + * @param {object} a + * @param {object} b + */ +Utils.extend = function(a,b){ + for(var key in b){ + a[key] = b[key]; + } +}; + +/** + * Extend an options object with default values. + * @static + * @method defaults + * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. + * @param {object} defaults An object containing default values. + * @return {object} The modified options object. + */ +Utils.defaults = function(options, defaults){ + options = options || {}; + for(var key in defaults){ + if(!(key in options)){ + options[key] = defaults[key]; + } + } + return options; +}; + +},{}],58:[function(_dereq_,module,exports){ +var Body = _dereq_('../objects/Body'); + +module.exports = Island; + +/** + * An island of bodies connected with equations. + * @class Island + * @constructor + */ +function Island(){ + + /** + * Current equations in this island. + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Current bodies in this island. + * @property bodies + * @type {Array} + */ + this.bodies = []; +} + +/** + * Clean this island from bodies and equations. + * @method reset + */ +Island.prototype.reset = function(){ + this.equations.length = this.bodies.length = 0; +}; + +var bodyIds = []; + +/** + * Get all unique bodies in this island. + * @method getBodies + * @return {Array} An array of Body + */ +Island.prototype.getBodies = function(result){ + var bodies = result || [], + eqs = this.equations; + bodyIds.length = 0; + for(var i=0; i!==eqs.length; i++){ + var eq = eqs[i]; + if(bodyIds.indexOf(eq.bodyA.id)===-1){ + bodies.push(eq.bodyA); + bodyIds.push(eq.bodyA.id); + } + if(bodyIds.indexOf(eq.bodyB.id)===-1){ + bodies.push(eq.bodyB); + bodyIds.push(eq.bodyB.id); + } + } + return bodies; +}; + +/** + * Check if the entire island wants to sleep. + * @method wantsToSleep + * @return {Boolean} + */ +Island.prototype.wantsToSleep = function(){ + for(var i=0; i= dt && substeps < maxSubSteps) { + // Do fixed steps to catch up + this.internalStep(dt); + this.time += dt; + this.accumulator -= dt; + substeps++; + } + + var t = (this.accumulator % dt) / dt; + for(var j=0; j!==this.bodies.length; j++){ + var b = this.bodies[j]; + vec2.lerp(b.interpolatedPosition, b.previousPosition, b.position, t); + b.interpolatedAngle = b.previousAngle + t * (b.angle - b.previousAngle); + } + } +}; + +var endOverlaps = []; + +/** + * Make a fixed step. + * @method internalStep + * @param {number} dt + * @private + */ +World.prototype.internalStep = function(dt){ + this.stepping = true; + + var that = this, + Nsprings = this.springs.length, + springs = this.springs, + bodies = this.bodies, + g = this.gravity, + solver = this.solver, + Nbodies = this.bodies.length, + broadphase = this.broadphase, + np = this.narrowphase, + constraints = this.constraints, + t0, t1, + fhMinv = step_fhMinv, + velodt = step_velodt, + mg = step_mg, + scale = vec2.scale, + add = vec2.add, + rotate = vec2.rotate, + islandManager = this.islandManager; + + this.overlapKeeper.tick(); + + this.lastTimeStep = dt; + + // Update approximate friction gravity. + if(this.useWorldGravityAsFrictionGravity){ + var gravityLen = vec2.length(this.gravity); + if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){ + // Nonzero gravity. Use it. + this.frictionGravity = gravityLen; + } + } + + // Add gravity to bodies + if(this.applyGravity){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i], + fi = b.force; + if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ + continue; + } + vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g + add(fi,fi,mg); + } + } + + // Add spring forces + if(this.applySpringForces){ + for(var i=0; i!==Nsprings; i++){ + var s = springs[i]; + s.applyForce(); + } + } + + if(this.applyDamping){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + if(b.type === Body.DYNAMIC){ + b.applyDamping(dt); + } + } + } + + // Broadphase + var result = broadphase.getCollisionPairs(this); + + // Remove ignored collision pairs + var ignoredPairs = this.disabledBodyCollisionPairs; + for(var i=ignoredPairs.length-2; 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); + } + } + } + + // Remove constrained pairs with collideConnected == false + 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); + } + } + } + } + + // postBroadphase event + this.postBroadphaseEvent.pairs = result; + this.emit(this.postBroadphaseEvent); + this.postBroadphaseEvent.pairs = null; + + // Narrowphase + np.reset(this); + for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ + var bi = result[i], + bj = result[i+1]; + + // Loop over all shapes of body i + for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ + var si = bi.shapes[k], + xi = si.position, + ai = si.angle; + + // All shapes of body j + for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ + var sj = bj.shapes[l], + xj = sj.position, + aj = sj.angle; + + 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); + } + } + } + + // Wake up bodies + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + if(body._wakeUpAfterNarrowphase){ + body.wakeUp(); + body._wakeUpAfterNarrowphase = false; + } + } + + // Emit end overlap events + 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.bodyB; + this.emit(e); + } + endOverlaps.length = 0; + } + + var preSolveEvent = this.preSolveEvent; + preSolveEvent.contactEquations = np.contactEquations; + preSolveEvent.frictionEquations = np.frictionEquations; + this.emit(preSolveEvent); + preSolveEvent.contactEquations = preSolveEvent.frictionEquations = null; + + // update constraint equations + var Nconstraints = constraints.length; + for(i=0; i!==Nconstraints; i++){ + constraints[i].update(); + } + + if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){ + if(this.islandSplit){ + // Split into islands + 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 { + + // Add contact equations to solver + solver.addEquations(np.contactEquations); + solver.addEquations(np.frictionEquations); + + // Add user-defined constraint equations + for(i=0; i!==Nconstraints; i++){ + solver.addEquations(constraints[i].equations); + } + + if(this.solveConstraints){ + solver.solve(dt,this); + } + + solver.removeAllEquations(); + } + } + + // Step forward + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + + // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){ + body.integrate(dt); + // } + } + + // Reset force + for(var i=0; i!==Nbodies; i++){ + bodies[i].setZeroForce(); + } + + // Emit impact event + 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); + } + } + } + + // Sleeping update + if(this.sleepMode === World.BODY_SLEEPING){ + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, false, dt); + } + } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){ + + // Tell all bodies to sleep tick but dont sleep yet + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, true, dt); + } + + // Sleep islands + for(var i=0; i 0; + np.frictionCoefficient = cm.friction; + var reducedMass; + if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){ + reducedMass = bj.mass; + } else if(bj.type === Body.STATIC || bj.type === 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; + np.contactSkinSize = cm.contactSkinSize; + np.enabledEquations = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse; + + 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 < sj.type) { + numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); + } else { + numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); + } + var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; + + if(numContacts){ + + if( bi.allowSleep && + bi.type === Body.DYNAMIC && + bi.sleepState === Body.SLEEPING && + bj.sleepState === Body.AWAKE && + bj.type !== Body.STATIC + ){ + var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); + var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); + if(speedSquaredB >= speedLimitSquaredB*2){ + bi._wakeUpAfterNarrowphase = true; + } + } + + if( bj.allowSleep && + bj.type === Body.DYNAMIC && + bj.sleepState === Body.SLEEPING && + bi.sleepState === Body.AWAKE && + bi.type !== 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)){ + + // Report new shape overlap + var e = this.beginContactEvent; + e.shapeA = si; + e.shapeB = sj; + e.bodyA = bi; + e.bodyB = bj; + + // Reset contact equations + e.contactEquations.length = 0; + + if(typeof(numContacts)==="number"){ + for(var i=np.contactEquations.length-numContacts; i 1){ // Why divide by 1? + for(var i=np.frictionEquations.length-numFrictionEquations; i=0; i--){ + this.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.bodies; + for(var i=bodies.length-1; i>=0; i--){ + this.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.springs; + for(var i=springs.length-1; i>=0; i--){ + this.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.contactMaterials; + for(var i=cms.length-1; i>=0; i--){ + this.removeContactMaterial(cms[i]); + } + + World.apply(this); +}; + +var hitTest_tmp1 = vec2.create(), + hitTest_zero = vec2.fromValues(0,0), + hitTest_tmp2 = vec2.fromValues(0,0); + +/** + * Test if a world point overlaps bodies + * @method hitTest + * @param {Array} worldPoint Point to use for intersection tests + * @param {Array} bodies A list of objects to check for intersection + * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @return {Array} Array of bodies that overlap the point + * @todo Should use an api similar to the raycast function + * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient + * @todo Should use the broadphase + */ +World.prototype.hitTest = function(worldPoint,bodies,precision){ + precision = precision || 0; + + // Create a dummy particle body with a particle shape to test against the bodies + 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 = []; + + // Check bodies + 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]; + + // Get shape world position + angle + vec2.rotate(x, s.position, b.angle); + vec2.add(x, x, b.position); + var a = s.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)) < precision*precision) + ){ + result.push(b); + } + } + } + + return result; +}; + +/** + * Set the stiffness for all equations and contact materials. + * @method setGlobalStiffness + * @param {Number} stiffness + */ +World.prototype.setGlobalStiffness = function(stiffness){ + + // Set for all constraints + var constraints = this.constraints; + for(var i=0; i !== constraints.length; i++){ + var c = constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.stiffness = stiffness; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + var contactMaterials = this.contactMaterials; + for(var i=0; i !== contactMaterials.length; i++){ + var c = contactMaterials[i]; + c.stiffness = c.frictionStiffness = stiffness; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.stiffness = c.frictionStiffness = stiffness; +}; + +/** + * Set the relaxation for all equations and contact materials. + * @method setGlobalRelaxation + * @param {Number} relaxation + */ +World.prototype.setGlobalRelaxation = function(relaxation){ + + // Set for all constraints + for(var i=0; i !== this.constraints.length; i++){ + var c = this.constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.relaxation = relaxation; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + for(var i=0; i !== this.contactMaterials.length; i++){ + var c = this.contactMaterials[i]; + c.relaxation = c.frictionRelaxation = relaxation; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.relaxation = c.frictionRelaxation = relaxation; +}; + +var tmpAABB = new AABB(); +var tmpArray = []; + +/** + * Ray cast against all bodies in the world. + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @return {boolean} True if any body was hit. + * + * @example + * var ray = new Ray({ + * mode: Ray.CLOSEST, // or ANY + * from: [0, 0], + * to: [10, 0], + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * @example + * var ray = new Ray({ + * mode: Ray.ALL, + * from: [0, 0], + * to: [10, 0], + * callback: function(result){ + * + * // Print some info about the hit + * console.log('Hit body and shape: ', result.body, result.shape); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * // If you are happy with the hits you got this far, you can stop the traversal here: + * result.stop(); + * } + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + */ +World.prototype.raycast = function(result, ray){ + + // Get all bodies within the ray AABB + ray.getAABB(tmpAABB); + this.broadphase.aabbQuery(this, tmpAABB, tmpArray); + ray.intersectBodies(result, tmpArray); + tmpArray.length = 0; + + return result.hasHit(); +}; + +},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36]) +(36) +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +(function(){ + + var root = this; + +/** + * Namespace-class for [pixi.js](http://www.pixijs.com/). + * + * Contains assorted static properties and enumerations. + * + * @namespace PIXI + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ +var PIXI = PIXI || {}; + +/** +* @author Mat Groves http://matgroves.com @Doormat23 +* @author Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The base class for all objects that are rendered. Contains properties for position, scaling, +* rotation, masks and cache handling. +* +* This is an abstract class and should not be used on its own, rather it should be extended. +* +* It is used internally by the likes of PIXI.Sprite. +* +* @class PIXI.DisplayObject +* @constructor +*/ +PIXI.DisplayObject = function () { + + /** + * The coordinates, in pixels, of this DisplayObject, relative to its parent container. + * + * The value of this property does not reflect any positioning happening further up the display list. + * To obtain that value please see the `worldPosition` property. + * + * @property {PIXI.Point} position + * @default + */ + this.position = new PIXI.Point(0, 0); + + /** + * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject + * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on. + * + * The value of this property does not reflect any scaling happening further up the display list. + * To obtain that value please see the `worldScale` property. + * + * @property {PIXI.Point} scale + * @default + */ + this.scale = new PIXI.Point(1, 1); + + /** + * The pivot point of this DisplayObject that it rotates around. The values are expressed + * in pixel values. + * @property {PIXI.Point} pivot + * @default + */ + this.pivot = new PIXI.Point(0, 0); + + /** + * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on + * a right-handed orientation. + * + * The value of this property does not reflect any rotation happening further up the display list. + * To obtain that value please see the `worldRotation` property. + * + * @property {number} rotation + * @default + */ + this.rotation = 0; + + /** + * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * Please note that an object with an alpha value of 0 is skipped during the render pass. + * + * The value of this property does not reflect any alpha values set further up the display list. + * To obtain that value please see the `worldAlpha` property. + * + * @property {number} alpha + * @default + */ + this.alpha = 1; + + /** + * The visibility of this DisplayObject. A value of `false` makes the object invisible. + * A value of `true` makes it visible. Please note that an object with a visible value of + * `false` is skipped during the render pass. Equally a DisplayObject with visible false will + * not render any of its children. + * + * The value of this property does not reflect any visible values set further up the display list. + * To obtain that value please see the `worldVisible` property. + * + * @property {boolean} visible + * @default + */ + this.visible = true; + + /** + * This is the defined area that will pick up mouse / touch events. It is null by default. + * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children) + * + * @property hitArea + * @type Rectangle|Circle|Ellipse|Polygon + */ + this.hitArea = null; + + /** + * Should this DisplayObject be rendered by the renderer? An object with a renderable value of + * `false` is skipped during the render pass. + * + * @property {boolean} renderable + * @default + */ + this.renderable = false; + + /** + * The parent DisplayObjectContainer that this DisplayObject is a child of. + * All DisplayObjects must belong to a parent in order to be rendered. + * The root parent is the Stage object. This property is set automatically when the + * DisplayObject is added to, or removed from, a DisplayObjectContainer. + * + * @property {PIXI.DisplayObjectContainer} parent + * @default + * @readOnly + */ + this.parent = null; + + /** + * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects + * in the display list. + * + * To obtain, and set, the local alpha value, see the `alpha` property. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldAlpha + * @readOnly + */ + this.worldAlpha = 1; + + /** + * The current transform of this DisplayObject. + * + * This property contains the calculated total, based on the transforms of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {Phaser.Matrix} worldTransform + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * The coordinates, in pixels, of this DisplayObject within the world. + * + * This property contains the calculated total, based on the positions of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldPosition + * @readOnly + */ + this.worldPosition = new PIXI.Point(0, 0); + + /** + * The global scale of this DisplayObject. + * + * This property contains the calculated total, based on the scales of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldScale + * @readOnly + */ + this.worldScale = new PIXI.Point(1, 1); + + /** + * The rotation, in radians, of this DisplayObject. + * + * This property contains the calculated total, based on the rotations of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldRotation + * @readOnly + */ + this.worldRotation = 0; + + /** + * The rectangular area used by filters when rendering a shader for this DisplayObject. + * + * @property {PIXI.Rectangle} filterArea + * @type Rectangle + * @default + */ + this.filterArea = null; + + /** + * @property {number} _sr - Cached rotation value. + * @private + */ + this._sr = 0; + + /** + * @property {number} _cr - Cached rotation value. + * @private + */ + this._cr = 1; + + /** + * @property {PIXI.Rectangle} _bounds - The cached bounds of this object. + * @private + */ + this._bounds = new PIXI.Rectangle(0, 0, 0, 0); + + /** + * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object. + * @private + */ + this._currentBounds = null; + + /** + * @property {PIXI.Rectangle} _mask - The cached mask of this object. + * @private + */ + this._mask = null; + + /** + * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag. + * @private + */ + this._cacheAsBitmap = false; + + /** + * @property {boolean} _cacheIsDirty - Internal dirty cache flag. + * @private + */ + this._cacheIsDirty = false; + +}; + +PIXI.DisplayObject.prototype = { + + constructor: PIXI.DisplayObject, + + /** + * Destroy this DisplayObject. + * + * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask. + * + * Also iteratively calls `destroy` on any children. + * + * @method PIXI.DisplayObject#destroy + */ + destroy: function () { + + if (this.children) + { + var i = this.children.length; + + while (i--) + { + this.children[i].destroy(); + } + + this.children = []; + } + + this.hitArea = null; + this.parent = null; + this.worldTransform = null; + this.filterArea = null; + this.renderable = false; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + }, + + /** + * Updates the transform matrix this DisplayObject uses for rendering. + * + * If the object has no parent, and no parent parameter is provided, it will default to + * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place. + * + * The `parent` parameter has priority over the actual parent. Use it as a parent override. + * Setting it does **not** change the actual parent of this DisplayObject. + * + * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale` + * and `worldRotation` properties. + * + * If a `transformCallback` has been specified, it is called at the end of this method, and is passed + * the new, updated, worldTransform property, along with the parent transform used. + * + * @method PIXI.DisplayObject#updateTransform + * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from. + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateTransform: function (parent) { + + if (!parent && !this.parent && !this.game) + { + return this; + } + + var p = this.parent; + + if (parent) + { + p = parent; + } + else if (!this.parent) + { + p = this.game.world; + } + + // create some matrix refs for easy access + var pt = p.worldTransform; + var wt = this.worldTransform; + + // temporary matrix variables + var a, b, c, d, tx, ty; + + // so if rotation is between 0 then we can simplify the multiplication process.. + if (this.rotation % Phaser.Math.PI2) + { + // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes + if (this.rotation !== this.rotationCache) + { + this.rotationCache = this.rotation; + this._sr = Math.sin(this.rotation); + this._cr = Math.cos(this.rotation); + } + + // get the matrix values of the displayobject based on its transform properties.. + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + tx = this.position.x; + ty = this.position.y; + + // check for pivot.. not often used so geared towards that fact! + if (this.pivot.x || this.pivot.y) + { + tx -= this.pivot.x * a + this.pivot.y * c; + ty -= this.pivot.x * b + this.pivot.y * d; + } + + // concat the parent matrix with the objects transform. + wt.a = a * pt.a + b * pt.c; + wt.b = a * pt.b + b * pt.d; + wt.c = c * pt.a + d * pt.c; + wt.d = c * pt.b + d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + else + { + // lets do the fast version as we know there is no rotation.. + a = this.scale.x; + b = 0; + c = 0; + d = this.scale.y; + tx = this.position.x - this.pivot.x * a; + ty = this.position.y - this.pivot.y * d; + + wt.a = a * pt.a; + wt.b = a * pt.b; + wt.c = d * pt.c; + wt.d = d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + + a = wt.a; + b = wt.b; + c = wt.c; + d = wt.d; + + var determ = (a * d) - (b * c); + + if (a || b) + { + var r = Math.sqrt((a * a) + (b * b)); + + this.worldRotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); + this.worldScale.x = r; + this.worldScale.y = determ / r; + } + else if (c || d) + { + var s = Math.sqrt((c * c) + (d * d)); + + this.worldRotation = Phaser.Math.HALF_PI - ((d > 0) ? Math.acos(-c / s) : -Math.acos(c / s)); + this.worldScale.x = determ / s; + this.worldScale.y = s; + } + else + { + this.worldScale.x = 0; + this.worldScale.y = 0; + } + + // Set the World values + this.worldAlpha = this.alpha * p.worldAlpha; + this.worldPosition.x = wt.tx; + this.worldPosition.y = wt.ty; + + // reset the bounds each time this is called! + this._currentBounds = null; + + // Custom callback? + if (this.transformCallback) + { + this.transformCallback.call(this.transformCallbackContext, wt, pt); + } + + return this; + + }, + + /** + * To be overridden by classes that require it. + * + * @method PIXI.DisplayObject#preUpdate + */ + preUpdate: function () { + + }, + + /** + * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites. + * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times. + * + * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures, + * and references to them, so they don't linger in memory. + * + * @method PIXI.DisplayObject#generateTexture + * @param {number} [resolution=1] - The resolution of the texture being generated. + * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values. + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture. + * @return {Phaser.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked. + */ + generateTexture: function (resolution, scaleMode, renderer) { + + var bounds = this.getLocalBounds(); + + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + + renderTexture.render(this, PIXI.DisplayObject._tempMatrix); + + return renderTexture; + + }, + + /** + * If this DisplayObject has a cached Sprite, this method generates and updates it. + * + * @method PIXI.DisplayObject#updateCache + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateCache: function () { + + this._generateCachedSprite(); + + return this; + + }, + + /** + * Calculates the global position of this DisplayObject, based on the position given. + * + * @method PIXI.DisplayObject#toGlobal + * @param {PIXI.Point} position - The global position to calculate from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toGlobal: function (position) { + + this.updateTransform(); + + return this.worldTransform.apply(position); + + }, + + /** + * Calculates the local position of this DisplayObject, relative to another point. + * + * @method PIXI.DisplayObject#toLocal + * @param {PIXI.Point} position - The world origin to calculate from. + * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toLocal: function (position, from) { + + if (from) + { + position = from.toGlobal(position); + } + + this.updateTransform(); + + return this.worldTransform.applyInverse(position); + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_renderCachedSprite + * @private + * @param {Object} renderSession - The render session + */ + _renderCachedSprite: function (renderSession) { + + this._cachedSprite.worldAlpha = this.worldAlpha; + + if (renderSession.gl) + { + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + } + else + { + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + } + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_generateCachedSprite + * @private + */ + _generateCachedSprite: function () { + + this._cacheAsBitmap = false; + + var bounds = this.getLocalBounds(); + + // Round it off and force non-zero dimensions + bounds.width = Math.max(1, Math.ceil(bounds.width)); + bounds.height = Math.max(1, Math.ceil(bounds.height)); + + this.updateTransform(); + + if (!this._cachedSprite) + { + var textureUnit = 0; + if (this.texture && this.texture.baseTexture && PIXI._enableMultiTextureToggle) + { + textureUnit = this.texture.baseTexture.textureIndex; + } + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width, bounds.height, undefined, undefined, undefined, undefined, textureUnit); + this._cachedSprite = new PIXI.Sprite(renderTexture); + this._cachedSprite.worldTransform = this.worldTransform; + } + else + { + this._cachedSprite.texture.resize(bounds.width, bounds.height); + } + + // Remove filters + var tempFilters = this._filters; + + this._filters = null; + this._cachedSprite.filters = tempFilters; + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true); + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + this._filters = tempFilters; + + this._cacheAsBitmap = true; + + }, + + /** + * Destroys a cached Sprite. + * + * @method PIXI.DisplayObject#_destroyCachedSprite + * @private + */ + _destroyCachedSprite: function () { + + if (!this._cachedSprite) + { + return; + } + + this._cachedSprite.texture.destroy(true); + + this._cachedSprite = null; + + } + +}; + +// Alias for updateTransform. As used in DisplayObject container, etc. +PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform; + +Object.defineProperties(PIXI.DisplayObject.prototype, { + + /** + * The horizontal position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#x + * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent. + */ + 'x': { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + } + + }, + + /** + * The vertical position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#y + * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent. + */ + 'y': { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + + }, + + /** + * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + * @name PIXI.DisplayObject#worldVisible + * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + */ + 'worldVisible': { + + get: function () { + + if (!this.visible) + { + return false; + } + else + { + var item = this.parent; + + if (!item) + { + return this.visible; + } + else + { + do + { + if (!item.visible) + { + return false; + } + + item = item.parent; + } + while (item); + + } + + return true; + } + + } + + }, + + /** + * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object. + * When applied it limits the visible area of this DisplayObject to the shape of the mask. + * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer. + * To remove a mask, set this property to `null`. + * + * @name PIXI.DisplayObject#mask + * @property {Phaser.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask. + */ + 'mask': { + + get: function () { + + return this._mask; + + }, + + set: function (value) { + + if (this._mask) + { + this._mask.isMask = false; + } + + this._mask = value; + + if (value) + { + this._mask.isMask = true; + } + + } + + }, + + /** + * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas + * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter + * using `DisplayObject.filterArea`. + * + * To remove filters, set this property to `null`. + * + * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a + * filter will reset this DisplayObjects blend mode to NORMAL. + * + * @name PIXI.DisplayObject#filters + * @property {Array} filters - An Array of Phaser.Filter objects, or objects that extend them. + */ + 'filters': { + + get: function () { + + return this._filters; + + }, + + set: function (value) { + + if (Array.isArray(value)) + { + // Put all the passes in one place. + var passes = []; + + for (var i = 0; i < value.length; i++) + { + var filterPasses = value[i].passes; + + for (var j = 0; j < filterPasses.length; j++) + { + passes.push(filterPasses[j]); + } + } + + // Needed any more? + this._filterBlock = { target: this, filterPasses: passes }; + } + + this._filters = value; + + if (this.blendMode && this.blendMode === PIXI.blendModes.MULTIPLY) + { + this.blendMode = PIXI.blendModes.NORMAL; + } + + } + + }, + + /** + * Sets if this DisplayObject should be cached as a bitmap. + * + * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it + * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a + * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not + * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`. + * + * To remove a cached bitmap, set this property to `null`. + * + * @name PIXI.DisplayObject#cacheAsBitmap + * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap. + */ + 'cacheAsBitmap': { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + if (this._cacheAsBitmap === value) + { + return; + } + + if (value) + { + this._generateCachedSprite(); + } + else + { + this._destroyCachedSprite(); + } + + this._cacheAsBitmap = value; + + } + + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A DisplayObjectContainer represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + * @class PIXI.DisplayObjectContainer + * @extends PIXI.DisplayObject + * @constructor + */ +PIXI.DisplayObjectContainer = function () { + + PIXI.DisplayObject.call(this); + + /** + * [read-only] The array of children of this container. + * + * @property children + * @type Array(DisplayObject) + * @readOnly + */ + this.children = []; + + /** + * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events. + * + * If this property is `true` then the children will _not_ be considered as valid for Input events. + * + * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. + * @property {boolean} ignoreChildInput + * @default + */ + this.ignoreChildInput = false; + +}; + +PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); +PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; + +/** + * Adds a child to the container. + * + * @method PIXI.DisplayObjectContainer#addChild + * @param child {DisplayObject} The DisplayObject to add to the container + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChild = function (child) { + + return this.addChildAt(child, this.children.length); + +}; + +/** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @method PIXI.DisplayObjectContainer#addChildAt + * @param child {DisplayObject} The child to add + * @param index {Number} The index to place the child in + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) { + + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + return child; + } + else + { + throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); + } + +}; + +/** + * Swaps the position of 2 Display Objects within this container. + * + * @method PIXI.DisplayObjectContainer#swapChildren + * @param child {DisplayObject} + * @param child2 {DisplayObject} + */ +PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) { + + if (child === child2) + { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(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; + +}; + +/** + * Returns the index position of a child DisplayObject instance + * + * @method PIXI.DisplayObjectContainer#getChildIndex + * @param child {DisplayObject} The DisplayObject instance to identify + * @return {Number} The index position of the child display object to identify + */ +PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + +}; + +/** + * Changes the position of an existing child in the display object container + * + * @method PIXI.DisplayObjectContainer#setChildIndex + * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number + * @param index {Number} The resulting index number for the child display object + */ +PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + this.children.splice(currentIndex, 1); //remove from old position + this.children.splice(index, 0, child); //add at new position + +}; + +/** + * Returns the child at the specified index + * + * @method PIXI.DisplayObjectContainer#getChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child at the given index, if any. + */ +PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller'); + } + + return this.children[index]; + +}; + +/** + * Removes a child from the container. + * + * @method PIXI.DisplayObjectContainer#removeChild + * @param child {DisplayObject} The DisplayObject to remove + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChild = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + return; + } + + return this.removeChildAt(index); + +}; + +/** + * Removes a child from the specified index position. + * + * @method PIXI.DisplayObjectContainer#removeChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) { + + var child = this.getChildAt(index); + + if (child) + { + child.parent = undefined; + + this.children.splice(index, 1); + } + + return child; + +}; + +/** +* Removes all children from this container that are within the begin and end indexes. +* +* @method PIXI.DisplayObjectContainer#removeChildren +* @param beginIndex {Number} The beginning position. Default value is 0. +* @param endIndex {Number} The ending position. Default value is size of the container. +*/ +PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { + + if (beginIndex === undefined) { beginIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var range = endIndex - beginIndex; + + if (range > 0 && range <= endIndex) + { + var removed = this.children.splice(beginIndex, range); + + for (var i = 0; i < removed.length; i++) + { + var child = removed[i]; + child.parent = undefined; + } + + return removed; + } + else if (range === 0 && this.children.length === 0) + { + return []; + } + else + { + throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' ); + } + +}; + +/* + * Updates the transform on all children of this container for rendering + * + * @method PIXI.DisplayObjectContainer#updateTransform + * @private + */ +PIXI.DisplayObjectContainer.prototype.updateTransform = function () { + + if (!this.visible) + { + return; + } + + this.displayObjectUpdateTransform(); + + if (this._cacheAsBitmap) + { + return; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +// performance increase to avoid using call.. (10x faster) +PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform; + +/** + * Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getBounds + * @param {PIXI.DisplayObject|Phaser.Matrix} [targetCoordinateSpace] Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpace) { + + var isTargetCoordinateSpaceDisplayObject = (targetCoordinateSpace && targetCoordinateSpace instanceof PIXI.DisplayObject); + var isTargetCoordinateSpaceThisOrParent = true; + + if (!isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace = this; + } + else if (targetCoordinateSpace instanceof PIXI.DisplayObjectContainer) + { + isTargetCoordinateSpaceThisOrParent = targetCoordinateSpace.contains(this); + } + else + { + isTargetCoordinateSpaceThisOrParent = false; + } + + var i; + + if (isTargetCoordinateSpaceDisplayObject) + { + var matrixCache = targetCoordinateSpace.worldTransform; + + targetCoordinateSpace.worldTransform = Phaser.identityMatrix; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + var minX = Infinity; + var minY = Infinity; + + var maxX = -Infinity; + var maxY = -Infinity; + + var childBounds; + var childMaxX; + var childMaxY; + + var childVisible = false; + + for (i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + childVisible = true; + + childBounds = this.children[i].getBounds(); + + minX = (minX < childBounds.x) ? minX : childBounds.x; + minY = (minY < childBounds.y) ? minY : childBounds.y; + + childMaxX = childBounds.width + childBounds.x; + childMaxY = childBounds.height + childBounds.y; + + maxX = (maxX > childMaxX) ? maxX : childMaxX; + maxY = (maxY > childMaxY) ? maxY : childMaxY; + } + + var bounds = this._bounds; + + if (!childVisible) + { + bounds = new PIXI.Rectangle(); + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + maxX = x1; + maxY = y1; + + minX = x1; + minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + } + + bounds.x = minX; + bounds.y = minY; + bounds.width = maxX - minX; + bounds.height = maxY - minY; + + if (isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace.worldTransform = matrixCache; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + if (!isTargetCoordinateSpaceThisOrParent) + { + var targetCoordinateSpaceBounds = targetCoordinateSpace.getBounds(); + + bounds.x -= targetCoordinateSpaceBounds.x; + bounds.y -= targetCoordinateSpaceBounds.y; + } + + return bounds; + +}; + +/** + * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getLocalBounds = function () { + + return this.getBounds(this); + +}; + +/** +* Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. +* +* @method PIXI.DisplayObjectContainer#contains +* @param {DisplayObject} child +* @returns {boolean} +*/ +PIXI.DisplayObjectContainer.prototype.contains = function (child) { + + if (!child) + { + return false; + } + else if (child === this) + { + return true; + } + else + { + return this.contains(child.parent); + } +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.DisplayObjectContainer#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + var i; + + if (this._mask || this._filters) + { + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + renderSession.spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + renderSession.spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + renderSession.spriteBatch.start(); + } + + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + renderSession.spriteBatch.start(); + } + else + { + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.DisplayObjectContainer#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) { + + if (this.visible === false || this.alpha === 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', { + + get: function() { + return this.getLocalBounds().width * this.scale.x; + }, + + set: function(value) { + + var width = this.getLocalBounds().width; + + if (width !== 0) + { + this.scale.x = value / width; + } + else + { + this.scale.x = 1; + } + + this._width = value; + } +}); + +/** + * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', { + + get: function() { + return this.getLocalBounds().height * this.scale.y; + }, + + set: function(value) { + + var height = this.getLocalBounds().height; + + if (height !== 0) + { + this.scale.y = value / height; + } + else + { + this.scale.y = 1; + } + + this._height = value; + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * @class PIXI.Sprite + * @extends PIXI.DisplayObjectContainer + * @constructor + * @param texture {Texture} The texture for this sprite + */ +PIXI.Sprite = function (texture) { + + PIXI.DisplayObjectContainer.call(this); + + /** + * The anchor sets the origin point of the texture. + * The default (0, 0) is the top left. + * (0.5, 0.5) is the center. + * (1, 1) is the bottom right. + * + * You can modify the default values in PIXI.Sprite.defaultAnchor. + * + * @property anchor + * @type Point + */ + this.anchor = new PIXI.Point(PIXI.Sprite.defaultAnchor.x, PIXI.Sprite.defaultAnchor.y); + + /** + * The texture that the sprite is using + * + * @property texture + * @type Texture + */ + this.texture = texture || PIXI.Texture.emptyTexture; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @property _width + * @type Number + * @private + */ + this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @property _height + * @type Number + * @private + */ + this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF (Phaser.Color.WHITE) will remove any tint effect. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @property cachedTint + * @private + * @type Number + * @default -1 + */ + this.cachedTint = -1; + + /** + * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) + * + * @property tintedTexture + * @type Canvas + * @default null + */ + this.tintedTexture = null; + + /** + * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. + * + * Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * The shader that will be used to render this Sprite. + * Set to null to remove a current shader. + * + * @property shader + * @type Phaser.Filter + * @default null + */ + this.shader = null; + + /** + * Controls if this Sprite is processed by the core Phaser game loops and Group loops (except {@link Phaser.Group#update}). + * + * @property exists + * @type Boolean + * @default true + */ + this.exists = true; + + if (this.texture.baseTexture.hasLoaded) + { + this.onTextureUpdate(); + } + + this.renderable = true; + +}; + +/** + * @property PIXI.Sprite.defaultAnchor - A Point-like object. + * @type {{x: number, y: number}} + * @default + */ +PIXI.Sprite.defaultAnchor = {x: 0, y: 0}; + +// constructor +PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +PIXI.Sprite.prototype.constructor = PIXI.Sprite; + +/** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'width', { + + get: function() { + return this.scale.x * this.texture.frame.width; + }, + + set: function(value) { + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'height', { + + get: function() { + return this.scale.y * this.texture.frame.height; + }, + + set: function(value) { + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +/** + * Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous + * texture this Sprite was using. + * + * @method PIXI.Sprite#setTexture + * @param texture {Texture} The PIXI texture that is displayed by the sprite + * @param [destroy=false] {boolean} Call Texture.destroy on the current texture before replacing it with the new one? + */ +PIXI.Sprite.prototype.setTexture = function(texture, destroyBase) +{ + if (destroyBase) + { + this.texture.baseTexture.destroy(); + } + + // Over-ridden by loadTexture as needed + this.texture.baseTexture.skipRender = false; + this.texture = texture; + this.texture.valid = true; + this.cachedTint = -1; +}; + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @method PIXI.Sprite#onTextureUpdate + * @param event + * @private + */ +PIXI.Sprite.prototype.onTextureUpdate = function() +{ + // so if _width is 0 then width was not set.. + if (this._width) this.scale.x = this._width / this.texture.frame.width; + if (this._height) this.scale.y = this._height / this.texture.frame.height; +}; + +/** +* Returns the bounds of the Sprite as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* It is important to note that the transform is not updated when you call this method. +* So if this Sprite is the child of a Display Object which has had its transform +* updated since the last render pass, those changes will not yet have been applied +* to this Sprites worldTransform. If you need to ensure that all parent transforms +* are factored into this getBounds operation then you should call `updateTransform` +* on the root most object in this Sprites display list first. +* +* @method PIXI.Sprite#getBounds +* @param matrix {Matrix} the transformation matrix of the sprite +* @return {Rectangle} the framing rectangle +*/ +PIXI.Sprite.prototype.getBounds = function(matrix) +{ + var width = this.texture.frame.width; + var height = this.texture.frame.height; + + var w0 = width * (1-this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1-this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + if (b === 0 && c === 0) + { + // scale may be negative! + if (a < 0) + { + a *= -1; + var temp = w0; + w0 = -w1; + w1 = -temp; + } + + if (d < 0) + { + d *= -1; + var temp = h0; + h0 = -h1; + h1 = -temp; + } + + // this means there is no rotation going on right? RIGHT? + // if thats the case then we can avoid checking the bound values! yay + minX = a * w1 + tx; + maxX = a * w0 + tx; + minY = d * h1 + ty; + maxY = d * h0 + ty; + } + else + { + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; +}; + +/** + * Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. + * + * @method PIXI.Sprite#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.Sprite.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.Sprite#_renderWebGL +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix) +{ + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha <= 0 || !this.renderable) return; + + // They provided an alternative rendering matrix, so use it + var wt = this.worldTransform; + + if (matrix) + { + wt = matrix; + } + + // A quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) + { + var spriteBatch = renderSession.spriteBatch; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + spriteBatch.start(); + } + + // add this sprite to the batch + spriteBatch.render(this); + + // now loop through the children and make sure they get rendered + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + // time to stop the sprite batch as either a mask element or a filter draw will happen next + spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + spriteBatch.start(); + } + else + { + renderSession.spriteBatch.render(this); + + // Render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession, wt); + } + + } +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.Sprite#_renderCanvas +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix) +{ + // If the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha === 0 || !this.renderable || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { + return; + } + + var wt = this.worldTransform; + + // If they provided an alternative rendering matrix then use it + if (matrix) + { + wt = matrix; + } + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + // Ignore null sources + if (!this.texture.valid) + { + // Update the children and leave + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + return; + } + + var resolution = this.texture.baseTexture.resolution / renderSession.resolution; + + renderSession.context.globalAlpha = this.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for this texture + if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode) + { + renderSession.scaleMode = this.texture.baseTexture.scaleMode; + renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + + // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions + var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width; + var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height; + + var tx = (wt.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (wt.ty * renderSession.resolution) + renderSession.shakeY; + + var cw = this.texture.crop.width; + var ch = this.texture.crop.height; + + if (this.texture.rotated) + { + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var e = cw; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + wt.a = a * 6.123233995736766e-17 + -c; + wt.b = b * 6.123233995736766e-17 + -d; + wt.c = a + c * 6.123233995736766e-17; + wt.d = b + d * 6.123233995736766e-17; + + // Update cropping dimensions. + cw = ch; + ch = e; + } + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx | 0, ty | 0); + dx |= 0; + dy |= 0; + } + else + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + } + + dx /= resolution; + dy /= resolution; + + if (this.tint !== 0xFFFFFF) + { + if (this.texture.requiresReTint || this.cachedTint !== this.tint) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + } + + renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + else + { + var cx = this.texture.crop.x; + var cy = this.texture.crop.y; + + cw = Math.floor(cw) + ch = Math.floor(ch) + + renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @method PIXI.initDefaultShaders +* @static +* @private +*/ +PIXI.initDefaultShaders = function() +{ +}; + +/** +* @method PIXI.CompileVertexShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileVertexShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); +}; + +/** +* @method PIXI.CompileFragmentShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileFragmentShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); +}; + +/** +* @method PIXI._CompileShader +* @static +* @private +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @param shaderType {Number} +* @return {Any} +*/ +PIXI._CompileShader = function(gl, shaderSrc, shaderType) +{ + var src = shaderSrc; + + if (Array.isArray(shaderSrc)) + { + 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; +}; + +/** +* @method PIXI.compileProgram +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param vertexSrc {Array} +* @param fragmentSrc {Array} +* @return {Any} +*/ +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(gl.getProgramInfoLog(shaderProgram)); + window.console.log("Could not initialise shaders"); + } + + return shaderProgram; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + * @author Richard Davey http://www.photonstorm.com @photonstorm + */ + +/** +* @class PIXI.PixiShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PixiShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = null; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + /** + * A local flag + * @property firstRun + * @type Boolean + * @private + */ + this.firstRun = true; + + /** + * A dirty flag + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Uniform attributes cache. + * @property attributes + * @type Array + * @private + */ + this.attributes = []; + + this.init(); +}; + +PIXI.PixiShader.prototype.constructor = PIXI.PixiShader; + +PIXI.PixiShader.prototype.initMultitexShader = function () { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.fragmentSrc = [ + '// PixiShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}', + '}' + ]; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + //this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.uSamplerArray = gl.getUniformLocation(program, 'uSamplerArray[0]'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSamplerArray, indices); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; + +PIXI.PixiShader.prototype.initDefaultShader = function () { + + if (this.fragmentSrc === null) { + this.fragmentSrc = [ + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', + '}' + ]; + } + + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; +/** +* Initialises the shader. +* +* @method PIXI.PixiShader#init +*/ +PIXI.PixiShader.prototype.init = function(usingFilter) +{ + if (PIXI._enableMultiTextureToggle && !usingFilter) { + this.initMultitexShader(); + } else { + this.initDefaultShader(); + } +}; + +/** +* Initialises the shader uniform values. +* +* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ +* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf +* +* @method PIXI.PixiShader#initUniforms +*/ +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') + { + // These require special handling + 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 + { + // GL function reference + 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; + } + } + } + +}; + +/** +* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) +* +* @method PIXI.PixiShader#initSampler2D +*/ +PIXI.PixiShader.prototype.initSampler2D = function(uniform) +{ + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { + return; + } + + var gl = this.gl; + + // No need to do string manipulation for this. + gl.activeTexture(gl.TEXTURE0 + this.textureCount); + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + + // Extended texture data + if (uniform.textureData) + { + var data = uniform.textureData; + + // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); + // GLTextureLinear = mag/min linear, wrap clamp + // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat + // GLTextureNearest = mag/min nearest, wrap clamp + // AudioTexture = whatever + luminance + width 512, height 2, border 0 + // KeyTexture = whatever + luminance + width 256, height 2, border 0 + + // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + + 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; + + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels); + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); + } + else + { + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels); + 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++; + +}; + +/** +* Updates the shader uniform values. +* +* @method PIXI.PixiShader#syncUniforms +*/ +PIXI.PixiShader.prototype.syncUniforms = function() +{ + this.textureCount = 1; + var uniform; + var gl = this.gl; + + // This would probably be faster in an array and it would guarantee key order + 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]); + + if(uniform.value.baseTexture._dirty[gl.id]) + { + PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + } + + // 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); + } + } + } + +}; + +/** +* Destroys the shader. +* +* @method PIXI.PixiShader#destroy +*/ +PIXI.PixiShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** +* The Default Vertex shader source. +* +* @property defaultVertexSrc +* @type String +*/ +PIXI.PixiShader.defaultVertexSrc = [ + '// PixiShader Vertex Shader', + '// With multi-texture rendering', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute vec4 aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + + 'const vec2 center = vec2(-1.0, 1.0);', + + 'void main(void) {', + ' if (aTextureIndex > 0.0) gl_Position = vec4(0.0);', + ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', + ' vTextureCoord = aTextureCoord;', + ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', + ' vTextureIndex = aTextureIndex;', + '}' +]; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @class PIXI.PixiFastShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.PixiFastShader = function (gl) { + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '// PixiFastShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aPositionCoord;', + 'attribute vec2 aScale;', + 'attribute float aRotation;', + 'attribute vec2 aTextureCoord;', + 'attribute float aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform mat3 uMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + + '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;', + ' vTextureIndex = aTextureIndex;', + // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;', + ' vColor = aColor;', + '}' + ]; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + this.init(); +}; + +PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader; + +/** + * Initialises the shader. + * + * @method PIXI.PixiFastShader#init + */ +PIXI.PixiFastShader.prototype.init = function () { + + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + this.uMatrix = gl.getUniformLocation(program, 'uMatrix'); + + // get and store the attributes + 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'); + + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its somthing to do with the current state of the gl context. + // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if (this.colorAttribute === -1) { + this.colorAttribute = 2; + } + + this.attributes = [ + this.aVertexPosition, + this.aPositionCoord, + this.aScale, + this.aRotation, + this.aTextureCoord, + this.colorAttribute, + this.aTextureIndex + ]; + + // End worst hack eva // + + this.program = program; +}; + +/** + * Destroys the shader. + * + * @method PIXI.PixiFastShader#destroy + */ +PIXI.PixiFastShader.prototype.destroy = function () { + this.gl.deleteProgram(this.program); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.StripShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.StripShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord);return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) ;return;}\n' + } + + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord);', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '//StripShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute float aTextureIndex;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + // 'uniform float alpha;', + // 'uniform vec3 tint;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // '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);', + ' vTextureCoord = aTextureCoord;', + ' vTextureIndex = aTextureIndex;', + // ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.StripShader.prototype.constructor = PIXI.StripShader; + +/** +* Initialises the shader. +* +* @method PIXI.StripShader#init +*/ +PIXI.StripShader.prototype.init = function() +{ + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + //this.dimensions = gl.getUniformLocation(this.program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.aTextureIndex]; + + this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix'); + this.alpha = gl.getUniformLocation(program, 'alpha'); + + this.program = program; +}; + +/** +* Destroys the shader. +* +* @method PIXI.StripShader#destroy +*/ +PIXI.StripShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.PrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + 'precision mediump float;', + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform float alpha;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.PrimitiveShader#init +*/ +PIXI.PrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.PrimitiveShader#destroy +*/ +PIXI.PrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.ComplexPrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.ComplexPrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + + 'precision mediump float;', + + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + //'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 color;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.ComplexPrimitiveShader#init +*/ +PIXI.ComplexPrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.color = gl.getUniformLocation(program, 'color'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.ComplexPrimitiveShader#destroy +*/ +PIXI.ComplexPrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +PIXI.glContexts = []; // this is where we store the webGL contexts for easy access. +PIXI.instances = []; +PIXI._enableMultiTextureToggle = false; + +/** + * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class PIXI.WebGLRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.WebGLRenderer = function(game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + this.extensions = {}; + + /** + * @property type + * @type Number + */ + this.type = Phaser.WEBGL; + + /** + * The resolution of the renderer + * + * @property resolution + * @type Number + * @default 1 + */ + this.resolution = game.resolution; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * + * @property preserveDrawingBuffer + * @type Boolean + */ + this.preserveDrawingBuffer = game.preserveDrawingBuffer; + + /** + * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true: + * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0). + * If the Stage is transparent, Pixi will clear to the target Stage's background color. + * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * The width of the canvas view + * + * @property width + * @type Number + */ + this.width = game.width; + + /** + * The height of the canvas view + * + * @property height + * @type Number + */ + this.height = game.height; + + /** + * The canvas element that everything is drawn to + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * @property _contextOptions + * @type Object + * @private + */ + this._contextOptions = { + alpha: this.transparent, + antialias: game.antialias, + failIfMajorPerformanceCaveat: config.failIfMajorPerformanceCaveat, + premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: this.preserveDrawingBuffer + }; + + /** + * @property projection + * @type Point + */ + this.projection = new PIXI.Point(); + + /** + * @property offset + * @type Point + */ + this.offset = new PIXI.Point(); + + // time to create the render managers! each one focuses on managing a state in webGL + + /** + * Deals with managing the shader programs and their attribs + * @property shaderManager + * @type WebGLShaderManager + */ + this.shaderManager = new PIXI.WebGLShaderManager(); + + /** + * Manages the rendering of sprites + * @property spriteBatch + * @type WebGLSpriteBatch + */ + this.spriteBatch = new PIXI.WebGLSpriteBatch(game); + + /** + * Manages the masks using the stencil buffer + * @property maskManager + * @type WebGLMaskManager + */ + this.maskManager = new PIXI.WebGLMaskManager(); + + /** + * Manages the filters + * @property filterManager + * @type WebGLFilterManager + */ + this.filterManager = new PIXI.WebGLFilterManager(); + + /** + * Manages the stencil buffer + * @property stencilManager + * @type WebGLStencilManager + */ + this.stencilManager = new PIXI.WebGLStencilManager(); + + /** + * Manages the blendModes + * @property blendModeManager + * @type WebGLBlendModeManager + */ + this.blendModeManager = new PIXI.WebGLBlendModeManager(); + + /** + * @property renderSession + * @type Object + */ + this.renderSession = {}; + + /** + * @property currentBatchedTextures + * @type Array + */ + this.currentBatchedTextures = []; + + // Needed? + this.renderSession.game = this.game; + this.renderSession.gl = this.gl; + this.renderSession.drawCount = 0; + this.renderSession.shaderManager = this.shaderManager; + this.renderSession.maskManager = this.maskManager; + this.renderSession.filterManager = this.filterManager; + this.renderSession.blendModeManager = this.blendModeManager; + this.renderSession.spriteBatch = this.spriteBatch; + this.renderSession.stencilManager = this.stencilManager; + this.renderSession.renderer = this; + this.renderSession.resolution = this.resolution; + this.renderSession.roundPixels = config.roundPixels || false; + this.renderSession.maxTextureAvailableSpace = null; // filled in setTexturePriority() + + // time init the context.. + this.initContext(); + + // map some webGL blend modes.. + this.mapBlendModes(); + +}; + +// constructor +PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer; + +/** +* @method PIXI.WebGLRenderer#initContext +*/ +PIXI.WebGLRenderer.prototype.initContext = function() +{ + var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); + + this.gl = gl; + + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + this.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.maxTextureSize = this.gl.getParameter(gl.MAX_TEXTURE_SIZE); + + this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++; + + PIXI.glContexts[this.glContextId] = gl; + + PIXI.instances[this.glContextId] = this; + + // set up the default pixi settings.. + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + gl.enable(gl.BLEND); + + // need to set the context for all the managers... + this.shaderManager.setContext(gl); + this.spriteBatch.setContext(gl); + this.maskManager.setContext(gl); + this.filterManager.setContext(gl); + this.blendModeManager.setContext(gl); + this.stencilManager.setContext(gl); + + this.renderSession.gl = this.gl; + + // now resize and we are good to go! + this.resize(this.width, this.height); + + // Load WebGL extension + this.extensions.compression = {}; + + var etc1 = gl.getExtension('WEBGL_compressed_texture_etc1') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'); + var pvrtc = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); + var s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); + + if (etc1) { this.extensions.compression.ETC1 = etc1; } + if (pvrtc) { this.extensions.compression.PVRTC = pvrtc; } + if (s3tc) { this.extensions.compression.S3TC = s3tc; } +}; + +/** +* If Multi Texture support has been enabled, then calling this method will enable batching on the given +* textures. The texture collection is an array of keys, that map to Phaser.Cache image entries. +* +* The number of textures that can be batched is dependent on hardware. If you provide more textures +* than can be batched by the GPU, then only those at the start of the array will be used. Generally +* you shouldn't provide more than 16 textures to this method. You can check the hardware limit via the +* `maxTextures` property. +* +* You can also check the property `currentBatchedTextures` at any time, to see which textures are currently +* being batched. +* +* To stop all textures from being batched, call this method again with an empty array. +* +* To change the textures being batched, call this method with a new array of image keys. The old ones +* will all be purged out and no-longer batched, and the new ones enabled. +* +* Note: Throws a warning if you haven't enabled Multiple Texture batching support in the Phaser Game config. +* +* @method PIXI.WebGLRenderer#setTexturePriority +* @param textureNameCollection {Array} An Array of Texture Cache keys to use for multi-texture batching. +* @return {Array} An array containing the texture keys that were enabled for batching. +*/ +PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + if (!PIXI._enableMultiTextureToggle) + { + console.warn('setTexturePriority error: Multi Texture support hasn\'t been enabled in the Phaser Game Config.'); + return; + } + var clampPot = function (potSize) { + --potSize; + potSize |= potSize >> 1; + potSize |= potSize >> 2; + potSize |= potSize >> 4; + potSize |= potSize >> 8; + potSize |= potSize >> 16; + return ++potSize; + }; + var gl = this.gl; + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + var imageCache = this.game.cache._cache.image; + var imageName = null; + + // Clear out all previously batched textures and reset their flags. + // If the array has been modified, then the developer will have to + // deal with that in their own way. + for (var i = 0; i < this.currentBatchedTextures.length; i++) + { + imageName = this.currentBatchedTextures[i]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + + imageCache[imageName].base.textureIndex = 0; + } + var maxTextureAvailableSpace = (maxTextureSize) - clampPot(Math.max(this.width, this.height)); + this.currentBatchedTextures.length = 0; + // We start from 1 because framebuffer texture uses unit 0. + for (var j = 0; j < textureNameCollection.length; ++j) + { + imageName = textureNameCollection[j]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + // Unit 0 is reserved for Pixi's framebuffer + var base = imageCache[imageName].base; + maxTextureAvailableSpace -= clampPot(Math.max(base.width, base.height)); + if (maxTextureAvailableSpace <= 0) { + base.textureIndex = 0; + console.warn('setTexturePriority: Image "%s" was given textureIndex=0 because there is no available texture space (%s).', + imageName, maxTextureAvailableSpace); + } else { + base.textureIndex = (1 + (j % (maxTextures - 1))); + } + this.currentBatchedTextures.push(imageName); + } + + this.renderSession.maxTextureAvailableSpace = maxTextureAvailableSpace; + + return this.currentBatchedTextures; + +}; + +/** + * Renders the stage to its webGL view + * + * @method PIXI.WebGLRenderer#render + * @param stage {Stage} the Stage element to be rendered + */ +PIXI.WebGLRenderer.prototype.render = function(stage) +{ + // no point rendering if our context has been blown up! + if (this.contextLost) + { + return; + } + + var gl = this.gl; + + // -- Does this need to be set every frame? -- // + gl.viewport(0, 0, this.width, this.height); + + // make sure we are bound to the main frame buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + if (this.game.clearBeforeRender) + { + gl.clearColor(stage._bgColor.r, stage._bgColor.g, stage._bgColor.b, stage._bgColor.a); + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + this.offset.x = this.game.camera._shake.x; + this.offset.y = this.game.camera._shake.y; + + this.renderDisplayObject(stage, this.projection); +}; + +/** + * Renders a Display Object. + * + * @method PIXI.WebGLRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The DisplayObject to render + * @param projection {Point} The projection + * @param buffer {Array} a standard WebGL buffer + */ +PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix) +{ + this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL); + + // reset the render session data.. + this.renderSession.drawCount = 0; + + // make sure to flip the Y if using a render texture.. + this.renderSession.flipY = buffer ? -1 : 1; + + // set the default projection + this.renderSession.projection = projection; + + //set the default offset + this.renderSession.offset = this.offset; + + // start the sprite batch + this.spriteBatch.begin(this.renderSession); + + // start the filter manager + this.filterManager.begin(this.renderSession, buffer); + + // render the scene! + displayObject._renderWebGL(this.renderSession, matrix); + + // finish the sprite batch + this.spriteBatch.end(); +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @method PIXI.WebGLRenderer#resize + * @param width {Number} the new width of the webGL view + * @param height {Number} the new height of the webGL view + */ +PIXI.WebGLRenderer.prototype.resize = function(width, height) +{ + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } + + this.gl.viewport(0, 0, this.width, this.height); + + this.projection.x = this.width / 2 / this.resolution; + this.projection.y = -this.height / 2 / this.resolution; +}; + +/** + * Updates and creates a WebGL compressed texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateCompressedTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateCompressedTexture = function (texture) { + if (!texture.hasLoaded) + { + return false; + } + var gl = this.gl; + var textureMetaData = texture.source; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + textureMetaData.glExtensionFormat, + textureMetaData.width, + textureMetaData.height, + 0, + textureMetaData.textureData + ); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + texture._dirty[gl.id] = false; + return true; +}; + +/** + * Updates and Creates a WebGL texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateTexture = function(texture) +{ + if (!texture.hasLoaded) + { + return false; + } + if (texture.source.compressionAlgorithm) { + return this.updateCompressedTexture(texture); + } + + var gl = this.gl; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha); + + 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); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + + texture._dirty[gl.id] = false; + + // return texture._glTextures[gl.id]; + return true; + +}; + +/** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @method PIXI.WebGLRenderer#destroy + */ +PIXI.WebGLRenderer.prototype.destroy = function() +{ + 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; + + Phaser.CanvasPool.remove(this); + + PIXI.instances[this.glContextId] = null; + + PIXI.WebGLRenderer.glContextId--; +}; + +/** + * Maps Pixi blend modes to WebGL blend modes. + * + * @method PIXI.WebGLRenderer#mapBlendModes + */ +PIXI.WebGLRenderer.prototype.mapBlendModes = function() +{ + var gl = this.gl; + + if (!PIXI.blendModesWebGL) + { + var b = []; + var modes = PIXI.blendModes; + + b[modes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA]; + b[modes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SCREEN] = [gl.SRC_ALPHA, gl.ONE]; + b[modes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + PIXI.blendModesWebGL = b; + } +}; + +PIXI.WebGLRenderer.prototype.getMaxTextureUnit = function() { + var gl = this.gl; + return gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); +}; + +PIXI.enableMultiTexture = function() { + PIXI._enableMultiTextureToggle = true; +}; + +PIXI.WebGLRenderer.glContextId = 0; +PIXI.WebGLRenderer.textureArray = []; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLBlendModeManager +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLBlendModeManager = function() +{ + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 99999; +}; + +PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLBlendModeManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLBlendModeManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Sets-up the given blendMode from WebGL's point of view. +* +* @method PIXI.WebGLBlendModeManager#setBlendMode +* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD +*/ +PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode) +{ + if(this.currentBlendMode === blendMode)return false; + + this.currentBlendMode = blendMode; + + var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode]; + + if (blendModeWebGL) + { + this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLBlendModeManager#destroy +*/ +PIXI.WebGLBlendModeManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLMaskManager +* @constructor +* @private +*/ +PIXI.WebGLMaskManager = function() +{ +}; + +PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLMaskManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLMaskManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLMaskManager#pushMask +* @param maskData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession) +{ + var gl = renderSession.gl; + + if (maskData.dirty) + { + PIXI.WebGLGraphics.updateGraphics(maskData, gl); + } + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLMaskManager#popMask +* @param maskData {Array} +* @param renderSession {Object} an object containing all the useful parameters +*/ +PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession) +{ + var gl = this.gl; + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); + +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLMaskManager#destroy +*/ +PIXI.WebGLMaskManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLStencilManager +* @constructor +* @private +*/ +PIXI.WebGLStencilManager = function() +{ + this.stencilStack = []; + this.reverse = true; + this.count = 0; +}; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLStencilManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLStencilManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLStencilManager#pushMask +* @param graphics {Graphics} +* @param webGLData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.bindGraphics(graphics, webGLData, renderSession); + + if(this.stencilStack.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + this.reverse = true; + this.count = 0; + } + + this.stencilStack.push(webGLData); + + var level = this.count; + + gl.colorMask(false, false, false, false); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + + if(webGLData.mode === 1) + { + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + + this.reverse = !this.reverse; + } + else + { + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + this.count++; +}; + +/** + * TODO this does not belong here! + * + * @method PIXI.WebGLStencilManager#bindGraphics + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession) +{ + //if(this._currentGraphics === graphics)return; + this._currentGraphics = graphics; + + var gl = this.gl; + + // bind the graphics object.. + var projection = renderSession.projection, + offset = renderSession.offset, + shader;// = renderSession.shaderManager.primitiveShader; + + if(webGLData.mode === 1) + { + shader = renderSession.shaderManager.complexPrimitiveShader; + + renderSession.shaderManager.setShader( shader ); + + gl.uniform1f(shader.flipY, renderSession.flipY); + + 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, Phaser.Color.hexToRGBArray(graphics.tint)); + gl.uniform3fv(shader.color, webGLData.color); + + gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0); + + + // now do the rest.. + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } + else + { + //renderSession.shaderManager.activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + renderSession.shaderManager.setShader( shader ); + + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, renderSession.flipY); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } +}; + +/** + * @method PIXI.WebGLStencilManager#popStencil + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.stencilStack.pop(); + + this.count--; + + if(this.stencilStack.length === 0) + { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + + } + else + { + + var level = this.count; + + this.bindGraphics(graphics, webGLData, renderSession); + + gl.colorMask(false, false, false, false); + + if(webGLData.mode === 1) + { + this.reverse = !this.reverse; + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + + } + else + { + // console.log("<<>>") + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + + } +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLStencilManager#destroy +*/ +PIXI.WebGLStencilManager.prototype.destroy = function() +{ + this.stencilStack = null; + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLShaderManager +* @constructor +* @private +*/ +PIXI.WebGLShaderManager = function() +{ + /** + * @property maxAttibs + * @type Number + */ + this.maxAttibs = 10; + + /** + * @property attribState + * @type Array + */ + this.attribState = []; + + /** + * @property tempAttribState + * @type Array + */ + this.tempAttribState = []; + + for (var i = 0; i < this.maxAttibs; i++) + { + this.attribState[i] = false; + } + + /** + * @property stack + * @type Array + */ + this.stack = []; + +}; + +PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLShaderManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLShaderManager.prototype.setContext = function(gl) +{ + this.gl = gl; + + // the next one is used for rendering primitives + this.primitiveShader = new PIXI.PrimitiveShader(gl); + + // the next one is used for rendering triangle strips + this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl); + + // this shader is used for the default sprite rendering + this.defaultShader = new PIXI.PixiShader(gl); + + // this shader is used for the fast sprite rendering + this.fastShader = new PIXI.PixiFastShader(gl); + + // the next one is used for rendering triangle strips + this.stripShader = new PIXI.StripShader(gl); + + // the next one is used for rendering creature meshes + this.creatureShader = PIXI.CreatureShader ? new PIXI.CreatureShader(gl) : null; + + this.setShader(this.defaultShader); +}; + +/** +* Takes the attributes given in parameters. +* +* @method PIXI.WebGLShaderManager#setAttribs +* @param attribs {Array} attribs +*/ +PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs) +{ + // reset temp state + var i; + + for (i = 0; i < this.tempAttribState.length; i++) + { + this.tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + var attribId = attribs[i]; + this.tempAttribState[attribId] = true; + } + + var gl = this.gl; + + for (i = 0; i < this.attribState.length; i++) + { + if(this.attribState[i] !== this.tempAttribState[i]) + { + this.attribState[i] = this.tempAttribState[i]; + + if(this.tempAttribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } +}; + +/** +* Sets the current shader. +* +* @method PIXI.WebGLShaderManager#setShader +* @param shader {Any} +*/ +PIXI.WebGLShaderManager.prototype.setShader = function(shader) +{ + if(this._currentId === shader._UID)return false; + + this._currentId = shader._UID; + + this.currentShader = shader; + + this.gl.useProgram(shader.program); + this.setAttribs(shader.attributes); + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLShaderManager#destroy +*/ +PIXI.WebGLShaderManager.prototype.destroy = function() +{ + this.attribState = null; + + this.tempAttribState = null; + + this.primitiveShader.destroy(); + + this.complexPrimitiveShader.destroy(); + + this.defaultShader.destroy(); + + this.fastShader.destroy(); + + this.stripShader.destroy(); + + if (this.creatureShader) { + this.creatureShader.destroy(); + } + + this.gl = null; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** + * + * @class PIXI.WebGLSpriteBatch + * @private + * @constructor + */ +PIXI.WebGLSpriteBatch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 5; + + /** + * The number of images in the SpriteBatch before it flushes + * @property size + * @type Number + */ + this.size = 2000; //Math.pow(2, 16) / this.vertSize; + + //the total number of bytes in our batch + // Including texture index: + // position + uv + color + textureIndex + // vec2 + vec2 + (char * 4) + float + this.vertexSize = (4 * 2) + (4 * 2) + (4) + (4); + var numVerts = this.vertexSize * this.size * 4; + //this.size * 4 * 4 * this.vertSize; + //the total number of indices in our batch + var numIndices = this.size * 6; + + /** + * Holds the vertices + * + * @property vertices + * @type ArrayBuffer + */ + this.vertices = new ArrayBuffer(numVerts); + + /** + * View on the vertices as a Float32Array + * + * @property positions + * @type Float32Array + */ + this.positions = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array + * + * @property colors + * @type Uint32Array + */ + this.colors = new Uint32Array(this.vertices); + + /** + * Holds the indices + * + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * @property textures + * @type Array + */ + this.textures = []; + + /** + * @property blendModes + * @type Array + */ + this.blendModes = []; + + /** + * @property shaders + * @type Array + */ + this.shaders = []; + + /** + * @property sprites + * @type Array + */ + this.sprites = []; + + /** + * @property defaultShader + * @type Phaser.Filter + */ + this.defaultShader = null; +}; + +/** + * @method PIXI.WebGLSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLSpriteBatch.prototype.setContext = function (gl) { + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.gl = gl; + if (PIXI._enableMultiTextureToggle) { + var dynamicIfs = '\tif (vTextureIndex == 0.0) {gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + 'void main(void) {', + dynamicIfs, + '\tgl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;', + '}' + ]); + } + else + { + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]); + } + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + this.currentBlendMode = 99999; + + var shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = this.defaultShader.fragmentSrc; + shader.uniforms = {}; + shader.init(); + + this.defaultShader.shaders[gl.id] = shader; +}; + +/** + * @method PIXI.WebGLSpriteBatch#begin + * @param renderSession {Object} The RenderSession object + */ +PIXI.WebGLSpriteBatch.prototype.begin = function (renderSession) { + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.defaultShader; + + this.start(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#end + */ +PIXI.WebGLSpriteBatch.prototype.end = function () { + this.flush(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#render + * @param sprite {Sprite} the sprite to render when using this spritebatch + * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. + */ +PIXI.WebGLSpriteBatch.prototype.render = function (sprite, matrix) { + var texture = sprite.texture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + if (PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + baseTexture.textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] = baseTexture; + } + + // They provided an alternative rendering matrix, so use it + var wt = sprite.worldTransform; + + if (matrix) { + wt = matrix; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // get the uvs for the texture + var uvs = texture._uvs; + + // if the uvs have not updated then no point rendering just yet! + if (!uvs) { + return; + } + + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + + var w0, w1, h0, h1; + + if (texture.trim) { + // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords. + var trim = texture.trim; + + w1 = trim.x - aX * trim.width; + w0 = w1 + texture.crop.width; + + h1 = trim.y - aY * trim.height; + h0 = h1 + texture.crop.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 i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + var tiOffset = this.currentBatchSize * 4; + var resolution = texture.baseTexture.resolution; + var textureIndex = texture.baseTexture.textureIndex; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + + var cw = texture.crop.width; + var ch = texture.crop.height; + + if (texture.rotated) + { + var a0 = wt.a; + var b0 = wt.b; + var c0 = wt.c; + var d0 = wt.d; + var _w1 = w1; + var _w0 = w0; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + a = a0 * 6.123233995736766e-17 + -c0; + b = b0 * 6.123233995736766e-17 + -d0; + c = a0 + c0 * 6.123233995736766e-17; + d = b0 + d0 * 6.123233995736766e-17; + + // Update UV coordinates + texture._updateUvsInverted(); + + // Rotate dimensions + w0 = h0; + w1 = h1; + h0 = _w0; + h1 = _w1; + } + + var colors = this.colors; + var positions = this.positions; + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + if (this.renderSession.roundPixels) { + positions[i++] = a * w1 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w1 + ty | 0; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w0 + ty | 0; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w0 + ty | 0; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w1 + ty | 0; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } else { + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx; + positions[i++] = d * h1 + b * w0 + ty; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders a TilingSprite using the spriteBatch. + * + * @method PIXI.WebGLSpriteBatch#renderTilingSprite + * @param sprite {TilingSprite} the sprite to render + */ +PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function (sprite) { + var texture = sprite.tilingTexture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + var textureIndex = sprite.texture.baseTexture.textureIndex; + if (PIXI.WebGLRenderer.textureArray[textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[textureIndex] = baseTexture; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // set the textures uvs temporarily + if (!sprite._uvs) { + sprite._uvs = new PIXI.TextureUvs(); + } + + var uvs = sprite._uvs; + + var w = texture.baseTexture.width; + var h = texture.baseTexture.height; + + // var w = sprite._frame.sourceSizeW; + // var h = sprite._frame.sourceSizeH; + + // w = 16; + // h = 16; + + sprite.tilePosition.x %= w * sprite.tileScaleOffset.x; + sprite.tilePosition.y %= h * sprite.tileScaleOffset.y; + + var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x); + var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y); + + var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x); + var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.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; + + // Get the sprites current alpha and tint and combine them into a single color + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + var positions = this.positions; + var colors = this.colors; + + var width = sprite.width; + var height = sprite.height; + + // TODO trim?? + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + var w0 = width * (1 - aX); + var w1 = width * -aX; + + var h0 = height * (1 - aY); + var h1 = height * -aY; + + var i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + + var resolution = texture.baseTexture.resolution; + + var wt = sprite.worldTransform; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + // xy + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + // uv + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = (a * w0 + c * h1 + tx); + positions[i++] = d * h1 + b * w0 + ty; + // uv + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + // uv + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + // uv + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders the content and empties the current batch. + * + * @method PIXI.WebGLSpriteBatch#flush + */ +PIXI.WebGLSpriteBatch.prototype.flush = function () { + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize === 0) { + return; + } + + var gl = this.gl; + var shader; + + if (this.dirty) { + this.dirty = false; + + shader = this.defaultShader.shaders[gl.id]; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + // this is the same for each shader? + var stride = this.vertexSize; //this.vertSize * 4; + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 8); + + // color attributes will be interpreted as unsigned bytes and normalized + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 16); + + // Texture index + gl.vertexAttribPointer(shader.aTextureIndex, 1, gl.FLOAT, false, stride, 20); + } + + // upload the verts to the buffer + if (this.currentBatchSize > (this.size * 0.5)) { + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + } else { + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + var view = this.positions.subarray(0, this.currentBatchSize * this.vertexSize); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); + } + + var nextTexture, nextBlendMode, nextShader; + var batchSize = 0; + var start = 0; + + var currentBaseTexture = null; + var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode; + var currentShader = null; + + var blendSwap = false; + var shaderSwap = false; + var sprite; + var textureIndex = 0; + + for (var i = 0, j = this.currentBatchSize; i < j; i++) { + + sprite = this.sprites[i]; + + if (sprite.tilingTexture) { + nextTexture = sprite.tilingTexture.baseTexture; + } else { + nextTexture = sprite.texture.baseTexture; + } + + nextBlendMode = sprite.blendMode; + nextShader = sprite.shader || this.defaultShader; + + blendSwap = currentBlendMode !== nextBlendMode; + shaderSwap = currentShader !== nextShader; // should I use _UIDS??? + + var skip = nextTexture.skipRender; + + if (skip && sprite.children.length > 0) { + skip = false; + } + // + if (/*(currentBaseTexture != nextTexture && !skip) ||*/ + blendSwap || + shaderSwap) { + this.renderBatch(currentBaseTexture, batchSize, start); + + start = i; + batchSize = 0; + currentBaseTexture = nextTexture; + + if (blendSwap) { + currentBlendMode = nextBlendMode; + this.renderSession.blendModeManager.setBlendMode(currentBlendMode); + } + + if (shaderSwap) { + currentShader = nextShader; + + shader = currentShader.shaders[gl.id]; + + if (!shader) { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = currentShader.fragmentSrc; + shader.uniforms = currentShader.uniforms; + shader.init(); + + currentShader.shaders[gl.id] = shader; + } + + // set shader function??? + this.renderSession.shaderManager.setShader(shader); + + if (shader.dirty) { + shader.syncUniforms(); + } + + // both these only need to be set if they are changing.. + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(shader.projectionVector, projection.x, projection.y); + + // TODO - this is temporary! + var offsetVector = this.renderSession.offset; + gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y); + + // set the pointers + } + } + + batchSize++; + } + + this.renderBatch(currentBaseTexture, batchSize, start); + + // then reset the batch! + this.currentBatchSize = 0; +}; + +/** + * @method PIXI.WebGLSpriteBatch#renderBatch + * @param texture {Texture} + * @param size {Number} + * @param startIndex {Number} + */ +PIXI.WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { + if (size === 0) { + return; + } + + var gl = this.gl; + + // check if a texture is dirty.. + if (texture._dirty[gl.id]) { + if (!this.renderSession.renderer.updateTexture(texture)) { + // If updateTexture returns false then we cannot render it, so bail out now + return; + } + }else { + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + } + + gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2); + // increment the draw count + this.renderSession.drawCount++; +}; + +/** + * @method PIXI.WebGLSpriteBatch#stop + */ +PIXI.WebGLSpriteBatch.prototype.stop = function () { + this.flush(); + this.dirty = true; +}; + +/** + * @method PIXI.WebGLSpriteBatch#start + */ +PIXI.WebGLSpriteBatch.prototype.start = function () { + this.dirty = true; +}; + +/** + * Destroys the SpriteBatch. + * + * @method PIXI.WebGLSpriteBatch#destroy + */ +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; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** +* @class PIXI.WebGLFastSpriteBatch +* @constructor +*/ +PIXI.WebGLFastSpriteBatch = function(gl) +{ + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 11; + + /** + * @property maxSize + * @type Number + */ + this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize; + + /** + * @property size + * @type Number + */ + this.size = this.maxSize; + + //the total number of floats in our batch + var numVerts = this.size * 4 * this.vertSize; + + //the total number of indices in our batch + var numIndices = this.maxSize * 6; + + /** + * Vertex data + * @property vertices + * @type Float32Array + */ + this.vertices = new Float32Array(numVerts); + + /** + * Index data + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property vertexBuffer + * @type Object + */ + this.vertexBuffer = null; + + /** + * @property indexBuffer + * @type Object + */ + this.indexBuffer = null; + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i=0, j=0; i < numIndices; i += 6, j += 4) + { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 0; + + /** + * @property renderSession + * @type Object + */ + this.renderSession = null; + + /** + * @property shader + * @type Object + */ + this.shader = null; + + /** + * @property matrix + * @type Matrix + */ + this.matrix = null; + + this.setContext(gl); +}; + +PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLFastSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl) +{ + this.gl = gl; + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#begin + * @param spriteBatch {WebGLSpriteBatch} + * @param renderSession {Object} + */ +PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession) +{ + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.fastShader; + + this.matrix = spriteBatch.worldTransform.toArray(true); + + this.start(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#end + */ +PIXI.WebGLFastSpriteBatch.prototype.end = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#render + * @param spriteBatch {WebGLSpriteBatch} + */ +PIXI.WebGLFastSpriteBatch.prototype.render = function (spriteBatch) +{ + var children = spriteBatch.children; + var sprite = children[0]; + + // if the uvs have not updated then no point rendering just yet! + + // check texture. + if(!sprite.texture._uvs)return; + + this.currentBaseTexture = sprite.texture.baseTexture; + + // check blend mode + if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode) + { + this.flush(); + this.renderSession.blendModeManager.setBlendMode(sprite.blendMode); + } + + for(var i=0,j= children.length; i= this.size) + { + this.flush(); + } +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#flush + */ +PIXI.WebGLFastSpriteBatch.prototype.flush = function() +{ + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize===0)return; + + var gl = this.gl; + + // bind the current texture + + if(!this.currentBaseTexture._glTextures[gl.id]) { + this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl); + return; + } + + //gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); + + // upload the verts to the buffer + + if(this.currentBatchSize > ( this.size * 0.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); + } + + // now draw those suckas! + gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0); + + // then reset the batch! + this.currentBatchSize = 0; + + // increment the draw count + this.renderSession.drawCount++; + +}; + + +/** + * @method PIXI.WebGLFastSpriteBatch#stop + */ +PIXI.WebGLFastSpriteBatch.prototype.stop = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#start + */ +PIXI.WebGLFastSpriteBatch.prototype.start = function() +{ + var gl = this.gl; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(this.shader.projectionVector, projection.x, projection.y); + + // set the matrix + gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix); + + // set the pointers + 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); + gl.vertexAttribPointer(this.shader.aTextureIndex, 1, gl.FLOAT, false, stride, 10 * 4); + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLFilterManager +* @constructor +*/ +PIXI.WebGLFilterManager = function() +{ + /** + * @property filterStack + * @type Array + */ + this.filterStack = []; + + /** + * @property offsetX + * @type Number + */ + this.offsetX = 0; + + /** + * @property offsetY + * @type Number + */ + this.offsetY = 0; +}; + +PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLFilterManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLFilterManager.prototype.setContext = function(gl) +{ + this.gl = gl; + this.texturePool = []; + + this.initShaderBuffers(); +}; + +/** +* @method PIXI.WebGLFilterManager#begin +* @param renderSession {RenderSession} +* @param buffer {ArrayBuffer} +*/ +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; +}; + +/** +* Applies the filter and adds it to the current filter stack. +* +* @method PIXI.WebGLFilterManager#pushFilter +* @param filterBlock {Object} the filter that will be pushed to the current filter stack +*/ +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(); + + // >>> modify by nextht + filterBlock._previous_stencil_mgr = this.renderSession.stencilManager; + this.renderSession.stencilManager = new PIXI.WebGLStencilManager(); + this.renderSession.stencilManager.setContext(gl); + gl.disable(gl.STENCIL_TEST); + // <<< modify by nextht + + // filter program + // OPTIMISATION - the first filter is free if its a simple color change? + 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.renderSession.resolution, this.height * this.renderSession.resolution); + } + else + { + texture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + } + + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea; + + var padding = filter.padding; + filterArea.x -= padding; + filterArea.y -= padding; + filterArea.width += padding * 2; + filterArea.height += padding * 2; + + // cap filter to screen size.. + 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer); + + // set view port + gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + projection.x = filterArea.width/2; + projection.y = -filterArea.height/2; + + offset.x = -filterArea.x; + offset.y = -filterArea.y; + + // update projection + // now restore the regular shader.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + //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; + +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLFilterManager#popFilter +*/ +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 * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + 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); + // now set the uvs.. + 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.renderSession.resolution, this.height * this.renderSession.resolution); + outputTexture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + + // need to clear this FBO as it may have some left over elements from a previous filter. + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + gl.clear(gl.COLOR_BUFFER_BIT); + + gl.disable(gl.BLEND); + + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { + var filterPass = filterBlock.filterPasses[i]; + + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture); + + // draw texture.. + //filterPass.applyFilterPass(filterArea.width, filterArea.height); + this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height); + + // swap the textures.. + var temp = inputTexture; + inputTexture = outputTexture; + outputTexture = temp; + } + + gl.enable(gl.BLEND); + + texture = inputTexture; + this.texturePool.push(outputTexture); + } + + var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1]; + + this.offsetX -= filterArea.x; + this.offsetY -= filterArea.y; + + var sizeX = this.width; + var sizeY = this.height; + + var offsetX = 0; + var offsetY = 0; + + var buffer = this.buffer; + + // time to render the filters texture to the previous scene + if(this.filterStack.length === 0) + { + gl.colorMask(true, true, true, true);//this.transparent); + } + else + { + var currentFilter = this.filterStack[this.filterStack.length-1]; + filterArea = currentFilter._filterArea; + + sizeX = filterArea.width; + sizeY = filterArea.height; + + offsetX = filterArea.x; + offsetY = filterArea.y; + + buffer = currentFilter._glFilterTexture.frameBuffer; + } + + // TODO need to remove these global elements.. + projection.x = sizeX/2; + projection.y = -sizeY/2; + + offset.x = offsetX; + offset.y = offsetY; + + filterArea = filterBlock._filterArea; + + var x = filterArea.x-offsetX; + var y = filterArea.y-offsetY; + + // update the buffers.. + // make sure to flip the y! + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + + this.vertexArray[0] = x; + this.vertexArray[1] = y + filterArea.height; + + this.vertexArray[2] = x + filterArea.width; + this.vertexArray[3] = y + filterArea.height; + + this.vertexArray[4] = x; + this.vertexArray[5] = y; + + this.vertexArray[6] = x + filterArea.width; + this.vertexArray[7] = y; + + 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); + + gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution); + + // bind the buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, buffer ); + + // set the blend mode! + //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + // >>> modify by nextht + if (this.renderSession.stencilManager) { + this.renderSession.stencilManager.destroy(); + } + this.renderSession.stencilManager = filterBlock._previous_stencil_mgr; + filterBlock._previous_stencil_mgr = null; + if (this.renderSession.stencilManager.count > 0) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + // <<< modify by nextht + + // apply! + this.applyFilterPass(filter, filterArea, sizeX, sizeY); + + // now restore the regular shader.. should happen automatically now.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2); + // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY); + + // return the texture to the pool + this.texturePool.push(texture); + filterBlock._glFilterTexture = null; +}; + + +/** +* Applies the filter to the specified area. +* +* @method PIXI.WebGLFilterManager#applyFilterPass +* @param filter {Phaser.Filter} the filter that needs to be applied +* @param filterArea {Texture} TODO - might need an update +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +*/ +PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height) +{ + // use program + var gl = this.gl; + var shader = filter.shaders[gl.id]; + + if(!shader) + { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = filter.fragmentSrc; + shader.uniforms = filter.uniforms; + shader.init(true); + + filter.shaders[gl.id] = shader; + } + + // set the shader + this.renderSession.shaderManager.setShader(shader); + +// gl.useProgram(shader.program); + + gl.uniform2f(shader.projectionVector, width/2, -height/2); + gl.uniform2f(shader.offsetVector, 0,0); + + if(filter.uniforms.dimensions) + { + filter.uniforms.dimensions.value[0] = this.width;//width; + filter.uniforms.dimensions.value[1] = this.height;//height; + filter.uniforms.dimensions.value[2] = this.vertexArray[0]; + filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height; + } + + shader.syncUniforms(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // draw the filter... + gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + + this.renderSession.drawCount++; +}; + +/** +* Initialises the shader buffers. +* +* @method PIXI.WebGLFilterManager#initShaderBuffers +*/ +PIXI.WebGLFilterManager.prototype.initShaderBuffers = function() +{ + var gl = this.gl; + + // create some buffers + this.vertexBuffer = gl.createBuffer(); + this.uvBuffer = gl.createBuffer(); + this.colorBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // bind and upload the vertexs.. + // keep a reference to the vertexFloatData.. + this.vertexArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW); + + // bind and upload the uv buffer + this.uvArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW); + + this.colorArray = new Float32Array([1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW); + + // bind and upload the index + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW); + +}; + +/** +* Destroys the filter and removes it from the filter stack. +* +* @method PIXI.WebGLFilterManager#destroy +*/ +PIXI.WebGLFilterManager.prototype.destroy = function() +{ + var gl = this.gl; + + this.filterStack = null; + + this.offsetX = 0; + this.offsetY = 0; + + // destroy textures + for (var i = 0; i < this.texturePool.length; i++) { + this.texturePool[i].destroy(); + } + + this.texturePool = null; + + //destroy buffers.. + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.uvBuffer); + gl.deleteBuffer(this.colorBuffer); + gl.deleteBuffer(this.indexBuffer); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @private + */ +function _CreateEmptyTexture(gl, width, height, scaleMode) { + var texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + return texture; +} + +/** + * @private + */ +var _fbErrors = { + 36054: 'Incomplete attachment', + 36055: 'Missing attachment', + 36057: 'Incomplete dimensions', + 36061: 'Framebuffer unsupported' +}; + +/** + * @private + */ +function _CreateFramebuffer(gl, width, height, scaleMode, textureUnit) { + var framebuffer = gl.createFramebuffer(); + var depthStencilBuffer = gl.createRenderbuffer(); + var colorBuffer = null; + var fbStatus = 0; + + gl.activeTexture(gl.TEXTURE0 + textureUnit); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer); + colorBuffer = _CreateEmptyTexture(gl, width, height, scaleMode); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorBuffer, 0); + fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + if(fbStatus !== gl.FRAMEBUFFER_COMPLETE) { + console.error('Incomplete GL framebuffer. ', _fbErrors[fbStatus]); + } + framebuffer.width = width; + framebuffer.height = height; + framebuffer.targetTexture = colorBuffer; + framebuffer.renderBuffer = depthStencilBuffer; + return framebuffer; +} + +/** +* @class PIXI.FilterTexture +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +* @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values +*/ +PIXI.FilterTexture = function(gl, width, height, scaleMode, textureUnit) +{ + textureUnit = typeof textureUnit === 'number' ? textureUnit : 0; + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + // next time to create a frame buffer and texture + + /** + * @property frameBuffer + * @type Any + */ + this.frameBuffer = _CreateFramebuffer(gl, width, height, scaleMode || PIXI.scaleModes.DEFAULT, textureUnit); + /** + * @property texture + * @type Any + */ + this.texture = this.frameBuffer.targetTexture; + this.width = width; + this.height = height; + this.renderBuffer = this.frameBuffer.renderBuffer; +}; + +PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture; + +/** +* Clears the filter texture. +* +* @method PIXI.FilterTexture#clear +*/ +PIXI.FilterTexture.prototype.clear = function() +{ + var gl = this.gl; + + gl.clearColor(0,0,0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Resizes the texture to the specified width and height + * + * @method PIXI.FilterTexture#resize + * @param width {Number} the new width of the texture + * @param height {Number} the new height of the texture + */ +PIXI.FilterTexture.prototype.resize = function(width, height) +{ + if(this.width === width && this.height === height) return; + + this.width = width; + this.height = height; + + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height ); +}; + +/** +* Destroys the filter texture. +* +* @method PIXI.FilterTexture#destroy +*/ +PIXI.FilterTexture.prototype.destroy = function() +{ + var gl = this.gl; + gl.deleteFramebuffer( this.frameBuffer ); + gl.deleteTexture( this.texture ); + + this.frameBuffer = null; + this.texture = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Creates a Canvas element of the given size. + * + * @class PIXI.CanvasBuffer + * @constructor + * @param width {Number} the width for the newly created canvas + * @param height {Number} the height for the newly created canvas + */ +PIXI.CanvasBuffer = function(width, height) +{ + /** + * The width of the Canvas in pixels. + * + * @property width + * @type Number + */ + this.width = width; + + /** + * The height of the Canvas in pixels. + * + * @property height + * @type Number + */ + this.height = height; + + /** + * The Canvas object that belongs to this CanvasBuffer. + * + * @property canvas + * @type HTMLCanvasElement + */ + this.canvas = Phaser.CanvasPool.create(this, this.width, this.height); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.canvas.getContext("2d"); + + this.canvas.width = width; + this.canvas.height = height; +}; + +PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer; + +/** + * Clears the canvas that was created by the CanvasBuffer class. + * + * @method PIXI.CanvasBuffer#clear + * @private + */ +PIXI.CanvasBuffer.prototype.clear = function() +{ + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0,0, this.width, this.height); +}; + +/** + * Resizes the canvas to the specified width and height. + * + * @method PIXI.CanvasBuffer#resize + * @param width {Number} the new width of the canvas + * @param height {Number} the new height of the canvas + */ +PIXI.CanvasBuffer.prototype.resize = function(width, height) +{ + this.width = this.canvas.width = width; + this.height = this.canvas.height = height; +}; + +/** + * Frees the canvas up for use again. + * + * @method PIXI.CanvasBuffer#destroy + */ +PIXI.CanvasBuffer.prototype.destroy = function() +{ + Phaser.CanvasPool.remove(this); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used to handle masking. + * + * @class PIXI.CanvasMaskManager + * @constructor + */ +PIXI.CanvasMaskManager = function() +{ +}; + +PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; + +/** + * This method adds it to the current stack of masks. + * + * @method PIXI.CanvasMaskManager#pushMask + * @param maskData {Object} the maskData that will be pushed + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) { + + var context = renderSession.context; + + context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.worldTransform; + + var resolution = renderSession.resolution; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution); + + PIXI.CanvasGraphics.renderGraphicsMask(maskData, context); + + context.clip(); + + maskData.worldAlpha = cacheAlpha; +}; + +/** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @method PIXI.CanvasMaskManager#popMask + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.popMask = function(renderSession) +{ + renderSession.context.restore(); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class PIXI.CanvasTinter + * @static + */ +PIXI.CanvasTinter = function() {}; + +/** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @method PIXI.CanvasTinter#getTintedTexture + * @static + * @param sprite {Sprite} the sprite to tint + * @param color {Number} the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ +PIXI.CanvasTinter.getTintedTexture = function(sprite, color) +{ + var canvas = sprite.tintedTexture || Phaser.CanvasPool.create(this); + + PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas); + + return canvas; +}; + +/** + * Tint a texture using the "multiply" operation. + * + * @method PIXI.CanvasTinter#tintWithMultiply + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.clearRect(0, 0, w, h); + + context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, w, h); + + context.globalCompositeOperation = "multiply"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + context.globalCompositeOperation = "destination-atop"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + +}; + +/** + * Tint a texture pixel per pixel. + * + * @method PIXI.CanvasTinter#tintPerPixel + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.globalCompositeOperation = "copy"; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + var rgbValues = Phaser.Color.hexToRGBArray(color); + var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, w, h); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) + { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + + if (!PIXI.CanvasTinter.canHandleAlpha) + { + var alpha = pixels[i + 3]; + + pixels[i + 0] /= 255 / alpha; + pixels[i + 1] /= 255 / alpha; + pixels[i + 2] /= 255 / alpha; + } + } + + context.putImageData(pixelData, 0, 0); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class PIXI.CanvasRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.CanvasRenderer = function (game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + /** + * The renderer type. + * + * @property type + * @type Number + */ + this.type = Phaser.CANVAS; + + /** + * The resolution of the canvas. + * + * @property resolution + * @type Number + */ + this.resolution = game.resolution; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. + * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame. + * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The width of the canvas view + * + * @property width + * @type Number + * @default 800 + */ + this.width = game.width * this.resolution; + + /** + * The height of the canvas view + * + * @property height + * @type Number + * @default 600 + */ + this.height = game.height * this.resolution; + + /** + * The canvas element that everything is drawn to. + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * The canvas 2d context that everything is drawn with + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.view.getContext("2d", { alpha: this.transparent } ); + + /** + * Boolean flag controlling canvas refresh. + * + * @property refresh + * @type Boolean + */ + this.refresh = true; + + /** + * Internal var. + * + * @property count + * @type Number + */ + this.count = 0; + + /** + * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer + * @property CanvasMaskManager + * @type CanvasMaskManager + */ + this.maskManager = new PIXI.CanvasMaskManager(); + + /** + * The render session is just a bunch of parameter used for rendering + * @property renderSession + * @type Object + */ + this.renderSession = { + context: this.context, + maskManager: this.maskManager, + scaleMode: null, + smoothProperty: Phaser.Canvas.getSmoothingPrefix(this.context), + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + */ + roundPixels: config.roundPixels || false + }; + + this.mapBlendModes(); + + this.resize(this.width, this.height); + +}; + +// constructor +PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer; + +/** + * Renders the DisplayObjectContainer, usually the Phaser.Stage, to this canvas view. + * + * @method PIXI.CanvasRenderer#render + * @param root {Phaser.Stage|PIXI.DisplayObjectContainer} The root element to be rendered. + */ +PIXI.CanvasRenderer.prototype.render = function (root) { + + this.context.setTransform(1, 0, 0, 1, 0, 0); + + this.context.globalAlpha = 1; + + this.renderSession.currentBlendMode = 0; + this.renderSession.shakeX = this.game.camera._shake.x; + this.renderSession.shakeY = this.game.camera._shake.y; + + this.context.globalCompositeOperation = 'source-over'; + + if (navigator.isCocoonJS && this.view.screencanvas) + { + this.context.fillStyle = "black"; + this.context.clear(); + } + + if (this.clearBeforeRender) + { + if (this.transparent) + { + this.context.clearRect(0, 0, this.width, this.height); + } + else if (root._bgColor) + { + this.context.fillStyle = root._bgColor.rgba; + this.context.fillRect(0, 0, this.width , this.height); + } + } + + this.renderDisplayObject(root); + +}; + +PIXI.CanvasRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + // Does nothing on Canvas, but here to allow you to simply set + // `game.renderer.setTexturePriority()` without having to worry about + // running in WebGL or not. + +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @method PIXI.CanvasRenderer#destroy + * @param [removeView=true] {boolean} Removes the Canvas element from the DOM. + */ +PIXI.CanvasRenderer.prototype.destroy = function (removeView) { + + if (removeView === undefined) { removeView = true; } + + if (removeView && this.view.parent) + { + this.view.parent.removeChild(this.view); + } + + this.view = null; + this.context = null; + this.maskManager = null; + this.renderSession = null; + +}; + +/** + * Resizes the canvas view to the specified width and height + * + * @method PIXI.CanvasRenderer#resize + * @param width {Number} the new width of the canvas view + * @param height {Number} the new height of the canvas view + */ +PIXI.CanvasRenderer.prototype.resize = function (width, height) { + + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) + { + this.view.style.width = this.width / this.resolution + "px"; + this.view.style.height = this.height / this.resolution + "px"; + } + + if (this.renderSession.smoothProperty) + { + this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + +}; + +/** + * Renders a display object + * + * @method PIXI.CanvasRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The displayObject to render + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. + * @private + */ +PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) { + + this.renderSession.context = context || this.context; + this.renderSession.resolution = this.resolution; + displayObject._renderCanvas(this.renderSession, matrix); + +}; + +/** + * Maps Pixi blend modes to canvas blend modes. + * + * @method PIXI.CanvasRenderer#mapBlendModes + * @private + */ +PIXI.CanvasRenderer.prototype.mapBlendModes = function () { + + if (!PIXI.blendModesCanvas) + { + var b = []; + var modes = PIXI.blendModes; + var useNew = this.game.device.canUseMultiply; + + b[modes.NORMAL] = 'source-over'; + b[modes.ADD] = 'lighter'; + b[modes.MULTIPLY] = (useNew) ? 'multiply' : 'source-over'; + b[modes.SCREEN] = (useNew) ? 'screen' : 'source-over'; + b[modes.OVERLAY] = (useNew) ? 'overlay' : 'source-over'; + b[modes.DARKEN] = (useNew) ? 'darken' : 'source-over'; + b[modes.LIGHTEN] = (useNew) ? 'lighten' : 'source-over'; + b[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : 'source-over'; + b[modes.COLOR_BURN] = (useNew) ? 'color-burn' : 'source-over'; + b[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : 'source-over'; + b[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : 'source-over'; + b[modes.DIFFERENCE] = (useNew) ? 'difference' : 'source-over'; + b[modes.EXCLUSION] = (useNew) ? 'exclusion' : 'source-over'; + b[modes.HUE] = (useNew) ? 'hue' : 'source-over'; + b[modes.SATURATION] = (useNew) ? 'saturation' : 'source-over'; + b[modes.COLOR] = (useNew) ? 'color' : 'source-over'; + b[modes.LUMINOSITY] = (useNew) ? 'luminosity' : 'source-over'; + + PIXI.blendModesCanvas = b; + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class PIXI.BaseTexture + * @constructor + * @param source {String|Canvas} the source object (image or canvas) + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + */ +PIXI.BaseTexture = function(source, scaleMode, resolution) +{ + /** + * The Resolution of the texture. + * + * @property resolution + * @type Number + */ + this.resolution = resolution || 1; + + /** + * [read-only] The width of the base texture set when the image has loaded + * + * @property width + * @type Number + * @readOnly + */ + this.width = 100; + + /** + * [read-only] The height of the base texture set when the image has loaded + * + * @property height + * @type Number + * @readOnly + */ + this.height = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @property scaleMode + * @type {Number} + * @default PIXI.scaleModes.LINEAR + */ + this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT; + + /** + * [read-only] Set to true once the base texture has loaded + * + * @property hasLoaded + * @type Boolean + * @readOnly + */ + this.hasLoaded = false; + + /** + * The image source that is used to create the texture. + * + * @property source + * @type Image + */ + this.source = source; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * + * @property premultipliedAlpha + * @type Boolean + * @default true + */ + this.premultipliedAlpha = true; + + // used for webGL + + /** + * @property _glTextures + * @type Array + * @private + */ + this._glTextures = []; + + /** + * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @property mipmap + * @type {Boolean} + */ + this.mipmap = false; + + /** + * The multi texture batching index number. + * @property textureIndex + * @type Number + */ + this.textureIndex = 0; + + /** + * @property _dirty + * @type Array + * @private + */ + this._dirty = [true, true, true, true]; + + if (!source) + { + return; + } + + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { + this.hasLoaded = true; + this.width = this.source.naturalWidth || this.source.width; + this.height = this.source.naturalHeight || this.source.height; + this.dirty(); + } + + /** + * A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch. + * + * You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture) + * that has children that you do want to render, without causing a batch flush in the process. + * + * @property skipRender + * @type Boolean + */ + this.skipRender = false; + + /** + * @property _powerOf2 + * @type Boolean + * @private + */ + this._powerOf2 = false; + +}; + +PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture; + +/** + * Forces this BaseTexture to be set as loaded, with the given width and height. + * Then calls BaseTexture.dirty. + * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have. + * + * @method PIXI.BaseTexture#forceLoaded + * @param {number} width - The new width to force the BaseTexture to be. + * @param {number} height - The new height to force the BaseTexture to be. + */ +PIXI.BaseTexture.prototype.forceLoaded = function(width, height) +{ + this.hasLoaded = true; + this.width = width; + this.height = height; + this.dirty(); +}; + +/** + * Destroys this base texture + * + * @method PIXI.BaseTexture#destroy + */ +PIXI.BaseTexture.prototype.destroy = function() +{ + if (this.source) + { + Phaser.CanvasPool.removeByCanvas(this.source); + } + + this.source = null; + + this.unloadFromGPU(); +}; + +/** + * Sets all glTextures to be dirty. + * + * @method PIXI.BaseTexture#dirty + */ +PIXI.BaseTexture.prototype.dirty = function() +{ + for (var i = 0; i < this._glTextures.length; i++) + { + this._dirty[i] = true; + } +}; + +/** + * Removes the base texture from the GPU, useful for managing resources on the GPU. + * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it. + * + * @method PIXI.BaseTexture#unloadFromGPU + */ +PIXI.BaseTexture.prototype.unloadFromGPU = function() +{ + this.dirty(); + + // delete the webGL textures if any. + for (var i = this._glTextures.length - 1; i >= 0; i--) + { + var glTexture = this._glTextures[i]; + var gl = PIXI.glContexts[i]; + + if(gl && glTexture) + { + gl.deleteTexture(glTexture); + } + + } + + this._glTextures.length = 0; + + this.dirty(); +}; + +/** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @method PIXI.BaseTexture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + * @return {BaseTexture} + */ +PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode, resolution) +{ + if (canvas.width === 0) + { + canvas.width = 1; + } + + if (canvas.height === 0) + { + canvas.height = 1; + } + + resolution = resolution || 1; + + return new PIXI.BaseTexture(canvas, scaleMode, resolution); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * TextureSilentFail is a boolean that defaults to `false`. + * If `true` then {@link PIXI.Texture#setFrame} will no longer throw an error if the texture dimensions are incorrect. + * Instead {@link PIXI.Texture#valid} will be set to `false` (#1556) + * + * @type {boolean} + */ +PIXI.TextureSilentFail = false; + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used. + * + * @class PIXI.Texture + * @constructor + * @param baseTexture {BaseTexture} The base texture source to create the texture from + * @param frame {Rectangle} The rectangle frame of the texture to show + * @param [crop] {Rectangle} The area of original texture + * @param [trim] {Rectangle} Trimmed texture rectangle + */ +PIXI.Texture = function(baseTexture, frame, crop, trim) +{ + /** + * Does this Texture have any frame data assigned to it? + * + * @property noFrame + * @type Boolean + */ + this.noFrame = false; + + if (!frame) + { + this.noFrame = true; + frame = new PIXI.Rectangle(0,0,1,1); + } + + if (baseTexture instanceof PIXI.Texture) + { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = baseTexture; + + /** + * The frame specifies the region of the base texture that this texture uses + * + * @property frame + * @type Rectangle + */ + this.frame = frame; + + /** + * The texture trim data. + * + * @property trim + * @type Rectangle + */ + this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @property valid + * @type Boolean + */ + this.valid = false; + + /** + * Is this a tiling texture? As used by the likes of a TilingSprite. + * + * @property isTiling + * @type Boolean + */ + this.isTiling = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @property requiresUpdate + * @type Boolean + */ + this.requiresUpdate = false; + + /** + * This will let a renderer know that a tinted parent has updated its texture. + * + * @property requiresReTint + * @type Boolean + */ + this.requiresReTint = false; + + /** + * The WebGL UV data cache. + * + * @property _uvs + * @type Object + * @private + */ + this._uvs = null; + + /** + * The width of the Texture in pixels. + * + * @property width + * @type Number + */ + this.width = 0; + + /** + * The height of the Texture in pixels. + * + * @property height + * @type Number + */ + this.height = 0; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @property crop + * @type Rectangle + */ + this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1); + + /** + * A flag that controls if this frame is rotated or not. + * Rotation allows you to use rotated frames in texture atlas packing, it has nothing to do with + * Sprite rotation. + * + * @property rotated + * @type Boolean + */ + this.rotated = false; + + if (baseTexture.hasLoaded) + { + if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + this.setFrame(frame); + } + +}; + +PIXI.Texture.prototype.constructor = PIXI.Texture; + +/** + * Called when the base texture is loaded + * + * @method PIXI.Texture#onBaseTextureLoaded + * @private + */ +PIXI.Texture.prototype.onBaseTextureLoaded = function() +{ + var baseTexture = this.baseTexture; + + if (this.noFrame) + { + this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } + + this.setFrame(this.frame); +}; + +/** + * Destroys this texture + * + * @method PIXI.Texture#destroy + * @param destroyBase {Boolean} Whether to destroy the base texture as well + */ +PIXI.Texture.prototype.destroy = function(destroyBase) +{ + if (destroyBase) this.baseTexture.destroy(); + + this.valid = false; +}; + +/** + * Specifies the region of the baseTexture that this texture will use. + * + * @method PIXI.Texture#setFrame + * @param frame {Rectangle} The frame of the texture to set it to + */ +PIXI.Texture.prototype.setFrame = function(frame) +{ + this.noFrame = false; + + this.frame = frame; + this.width = frame.width; + this.height = frame.height; + + this.crop.x = frame.x; + this.crop.y = frame.y; + this.crop.width = frame.width; + this.crop.height = frame.height; + + if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { + if (!PIXI.TextureSilentFail) + { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + this.valid = false; + return; + } + + this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + + if (this.trim) + { + this.width = this.trim.width; + this.height = this.trim.height; + this.frame.width = this.trim.width; + this.frame.height = this.trim.height; + } + + if (this.valid) this._updateUvs(); + +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvs + * @private + */ +PIXI.Texture.prototype._updateUvs = function() +{ + if(!this._uvs)this._uvs = new PIXI.TextureUvs(); + + var frame = this.crop; + 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; +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvsInverted + * @private + */ +PIXI.Texture.prototype._updateUvsInverted = function () { + + if (!this._uvs) { this._uvs = new PIXI.TextureUvs(); } + + var frame = this.crop; + 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.height) / tw; + this._uvs.y1 = frame.y / th; + + this._uvs.x2 = (frame.x + frame.height) / tw; + this._uvs.y2 = (frame.y + frame.width) / th; + + this._uvs.x3 = frame.x / tw; + this._uvs.y3 = (frame.y + frame.width) / th; + +}; + +/** + * Helper function that creates a new a Texture based on the given canvas element. + * + * @static + * @method PIXI.Texture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @return {Texture} + */ +PIXI.Texture.fromCanvas = function(canvas, scaleMode) +{ + var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode); + + return new PIXI.Texture(baseTexture); +}; + +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.y3 = 0; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = PIXI; + } + exports.PIXI = PIXI; + } else if (typeof define !== 'undefined' && define.amd) { + define('PIXI', (function() { return root.PIXI = PIXI; })() ); + } else { + root.PIXI = PIXI; + } + + return PIXI; +}).call(this); +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +(function(){ + + var root = this; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @namespace Phaser +*/ +var Phaser = Phaser || { // jshint ignore:line + + /** + * The Phaser version number. + * @constant Phaser.VERSION + * @type {string} + */ + VERSION: '2.10.0', + + /** + * An array of Phaser game instances. + * @constant Phaser.GAMES + * @type {array} + */ + GAMES: [], + + /** + * AUTO renderer - picks between WebGL or Canvas based on device. + * @constant Phaser.AUTO + * @type {integer} + */ + AUTO: 0, + + /** + * Canvas Renderer. + * @constant Phaser.CANVAS + * @type {integer} + */ + CANVAS: 1, + + /** + * WebGL Renderer. + * @constant Phaser.WEBGL + * @type {integer} + */ + WEBGL: 2, + + /** + * Headless renderer (not visual output) + * @constant Phaser.HEADLESS + * @type {integer} + */ + HEADLESS: 3, + + /** + * WebGL Renderer with MultiTexture support enabled. + * @constant Phaser.WEBGL_MULTI + * @type {integer} + */ + WEBGL_MULTI: 4, + + /** + * Direction constant. + * @constant Phaser.NONE + * @type {integer} + */ + NONE: 0, + + /** + * Direction constant. + * @constant Phaser.LEFT + * @type {integer} + */ + LEFT: 1, + + /** + * Direction constant. + * @constant Phaser.RIGHT + * @type {integer} + */ + RIGHT: 2, + + /** + * Direction constant. + * @constant Phaser.UP + * @type {integer} + */ + UP: 3, + + /** + * Direction constant. + * @constant Phaser.DOWN + * @type {integer} + */ + DOWN: 4, + + /** + * Game Object type. + * @constant Phaser.SPRITE + * @type {integer} + */ + SPRITE: 0, + + /** + * Game Object type. + * @constant Phaser.BUTTON + * @type {integer} + */ + BUTTON: 1, + + /** + * Game Object type. + * @constant Phaser.IMAGE + * @type {integer} + */ + IMAGE: 2, + + /** + * Game Object type. + * @constant Phaser.GRAPHICS + * @type {integer} + */ + GRAPHICS: 3, + + /** + * Game Object type. + * @constant Phaser.TEXT + * @type {integer} + */ + TEXT: 4, + + /** + * Game Object type. + * @constant Phaser.TILESPRITE + * @type {integer} + */ + TILESPRITE: 5, + + /** + * Game Object type. + * @constant Phaser.BITMAPTEXT + * @type {integer} + */ + BITMAPTEXT: 6, + + /** + * Game Object type. + * @constant Phaser.GROUP + * @type {integer} + */ + GROUP: 7, + + /** + * Game Object type. + * @constant Phaser.RENDERTEXTURE + * @type {integer} + */ + RENDERTEXTURE: 8, + + /** + * Game Object type. + * @constant Phaser.TILEMAP + * @type {integer} + */ + TILEMAP: 9, + + /** + * Game Object type. + * @constant Phaser.TILEMAPLAYER + * @type {integer} + */ + TILEMAPLAYER: 10, + + /** + * Game Object type. + * @constant Phaser.EMITTER + * @type {integer} + */ + EMITTER: 11, + + /** + * Game Object type. + * @constant Phaser.POLYGON + * @type {integer} + */ + POLYGON: 12, + + /** + * Game Object type. + * @constant Phaser.BITMAPDATA + * @type {integer} + */ + BITMAPDATA: 13, + + /** + * Game Object type. + * @constant Phaser.CANVAS_FILTER + * @type {integer} + */ + CANVAS_FILTER: 14, + + /** + * Game Object type. + * @constant Phaser.WEBGL_FILTER + * @type {integer} + */ + WEBGL_FILTER: 15, + + /** + * Game Object type. + * @constant Phaser.ELLIPSE + * @type {integer} + */ + ELLIPSE: 16, + + /** + * Game Object type. + * @constant Phaser.SPRITEBATCH + * @type {integer} + */ + SPRITEBATCH: 17, + + /** + * Game Object type. + * @constant Phaser.RETROFONT + * @type {integer} + */ + RETROFONT: 18, + + /** + * Game Object type. + * @constant Phaser.POINTER + * @type {integer} + */ + POINTER: 19, + + /** + * Game Object type. + * @constant Phaser.ROPE + * @type {integer} + */ + ROPE: 20, + + /** + * Game Object type. + * @constant Phaser.CIRCLE + * @type {integer} + */ + CIRCLE: 21, + + /** + * Game Object type. + * @constant Phaser.RECTANGLE + * @type {integer} + */ + RECTANGLE: 22, + + /** + * Game Object type. + * @constant Phaser.LINE + * @type {integer} + */ + LINE: 23, + + /** + * Game Object type. + * @constant Phaser.MATRIX + * @type {integer} + */ + MATRIX: 24, + + /** + * Game Object type. + * @constant Phaser.POINT + * @type {integer} + */ + POINT: 25, + + /** + * Game Object type. + * @constant Phaser.ROUNDEDRECTANGLE + * @type {integer} + */ + ROUNDEDRECTANGLE: 26, + + /** + * Game Object type. + * @constant Phaser.CREATURE + * @type {integer} + */ + CREATURE: 27, + + /** + * Game Object type. + * @constant Phaser.VIDEO + * @type {integer} + */ + VIDEO: 28, + + /** + * Game Object type. + * @constant Phaser.PENDING_ATLAS + * @type {integer} + */ + PENDING_ATLAS: -1, + + /** + * A horizontal orientation + * @constant Phaser.HORIZONTAL + * @type {integer} + */ + HORIZONTAL: 0, + + /** + * A vertical orientation + * @constant Phaser.VERTICAL + * @type {integer} + */ + VERTICAL: 1, + + /** + * A landscape orientation + * @constant Phaser.LANDSCAPE + * @type {integer} + */ + LANDSCAPE: 0, + + /** + * A portrait orientation + * @constant Phaser.PORTRAIT + * @type {integer} + */ + PORTRAIT: 1, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face up. + * @constant Phaser.ANGLE_UP + * @type {integer} + */ + ANGLE_UP: 270, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face down. + * @constant Phaser.ANGLE_DOWN + * @type {integer} + */ + ANGLE_DOWN: 90, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face left. + * @constant Phaser.ANGLE_LEFT + * @type {integer} + */ + ANGLE_LEFT: 180, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face right. + * @constant Phaser.ANGLE_RIGHT + * @type {integer} + */ + ANGLE_RIGHT: 0, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north east. + * @constant Phaser.ANGLE_NORTH_EAST + * @type {integer} + */ + ANGLE_NORTH_EAST: 315, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north west. + * @constant Phaser.ANGLE_NORTH_WEST + * @type {integer} + */ + ANGLE_NORTH_WEST: 225, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south east. + * @constant Phaser.ANGLE_SOUTH_EAST + * @type {integer} + */ + ANGLE_SOUTH_EAST: 45, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south west. + * @constant Phaser.ANGLE_SOUTH_WEST + * @type {integer} + */ + ANGLE_SOUTH_WEST: 135, + + /** + * A constant representing a top-left alignment or position. + * @constant Phaser.TOP_LEFT + * @type {integer} + */ + TOP_LEFT: 0, + + /** + * A constant representing a top-center alignment or position. + * @constant Phaser.TOP_CENTER + * @type {integer} + */ + TOP_CENTER: 1, + + /** + * A constant representing a top-right alignment or position. + * @constant Phaser.TOP_RIGHT + * @type {integer} + */ + TOP_RIGHT: 2, + + /** + * A constant representing a left-top alignment or position. + * @constant Phaser.Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_TOP: 3, + + /** + * A constant representing a left-center alignment or position. + * @constant Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_CENTER: 4, + + /** + * A constant representing a left-bottom alignment or position. + * @constant Phaser.LEFT_BOTTOM + * @type {integer} + */ + LEFT_BOTTOM: 5, + + /** + * A constant representing a center alignment or position. + * @constant Phaser.CENTER + * @type {integer} + */ + CENTER: 6, + + /** + * A constant representing a right-top alignment or position. + * @constant Phaser.RIGHT_TOP + * @type {integer} + */ + RIGHT_TOP: 7, + + /** + * A constant representing a right-center alignment or position. + * @constant Phaser.RIGHT_CENTER + * @type {integer} + */ + RIGHT_CENTER: 8, + + /** + * A constant representing a right-bottom alignment or position. + * @constant Phaser.RIGHT_BOTTOM + * @type {integer} + */ + RIGHT_BOTTOM: 9, + + /** + * A constant representing a bottom-left alignment or position. + * @constant Phaser.BOTTOM_LEFT + * @type {integer} + */ + BOTTOM_LEFT: 10, + + /** + * A constant representing a bottom-center alignment or position. + * @constant Phaser.BOTTOM_CENTER + * @type {integer} + */ + BOTTOM_CENTER: 11, + + /** + * A constant representing a bottom-right alignment or position. + * @constant Phaser.BOTTOM_RIGHT + * @type {integer} + */ + BOTTOM_RIGHT: 12, + + /** + * Various blend modes supported by Pixi. See the samples in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing Canvas Tutorial: Compositing}. + * + * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * + * @constant {Object} Phaser.blendModes + * @property {Number} blendModes.NORMAL - Draws new shapes on top of the existing content. This is the default setting. + * @property {Number} blendModes.ADD - Where both shapes overlap the color is determined by adding color values. + * @property {Number} blendModes.MULTIPLY - The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer, making a darker picture. + * @property {Number} blendModes.SCREEN - The pixels are inverted, multiplied, and inverted again, making a lighter picture. + * @property {Number} blendModes.OVERLAY + * @property {Number} blendModes.DARKEN + * @property {Number} blendModes.LIGHTEN + * @property {Number} blendModes.COLOR_DODGE + * @property {Number} blendModes.COLOR_BURN + * @property {Number} blendModes.HARD_LIGHT + * @property {Number} blendModes.SOFT_LIGHT + * @property {Number} blendModes.DIFFERENCE + * @property {Number} blendModes.EXCLUSION + * @property {Number} blendModes.HUE + * @property {Number} blendModes.SATURATION + * @property {Number} blendModes.COLOR + * @property {Number} blendModes.LUMINOSITY + * @static + */ + 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 + }, + + /** + * The scale modes that are supported by Pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @constant {Object} Phaser.scaleModes + * @property {Number} Phaser.scaleModes.DEFAULT=LINEAR + * @property {Number} Phaser.scaleModes.LINEAR Smooth scaling + * @property {Number} Phaser.scaleModes.NEAREST Pixelating scaling + * @static + */ + scaleModes: { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 + }, + + PIXI: PIXI || {}, + + // Used to create IDs for various Pixi objects. + _UID: 0 + +}; + +/** +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc +if (!Math.trunc) { + Math.trunc = function trunc(x) { + return x < 0 ? Math.ceil(x) : Math.floor(x); + }; +} + +/** +* A polyfill for Function.prototype.bind +*/ +if (!Function.prototype.bind) { + + /* jshint freeze: false */ + 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)) + { + /* jshint supernew: true */ + return new F; + } + })(target.prototype); + + return bound; + }; + })(); +} + +/** +* A polyfill for Array.isArray +*/ +if (!Array.isArray) +{ + Array.isArray = function (arg) + { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + +/** +* A polyfill for Array.forEach +* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach +*/ +if (!Array.prototype.forEach) +{ + Array.prototype.forEach = function(fun /*, thisArg */) + { + "use strict"; + + if (this === void 0 || this === null) + { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + if (typeof fun !== "function") + { + throw new TypeError(); + } + + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + + for (var i = 0; i < len; i++) + { + if (i in t) + { + fun.call(thisArg, t[i], i, t); + } + } + }; +} + +/** +* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 +* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ +* Cameron Foale (http://www.kibibu.com) +*/ +if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object") +{ + var CheapArray = function(type) + { + var proto = new Array(); // jshint ignore:line + + window[type] = function(arg) { + + if (typeof(arg) === "number") + { + Array.call(this, arg); + this.length = arg; + + for (var i = 0; i < this.length; i++) + { + this[i] = 0; + } + } + else + { + Array.call(this, arg.length); + + this.length = arg.length; + + for (var i = 0; i < this.length; i++) + { + this[i] = arg[i]; + } + } + }; + + window[type].prototype = proto; + window[type].constructor = window[type]; + }; + + CheapArray('Float32Array'); // jshint ignore:line + CheapArray('Uint32Array'); // jshint ignore:line + CheapArray('Uint16Array'); // jshint ignore:line + CheapArray('Int16Array'); // jshint ignore:line + CheapArray('ArrayBuffer'); // jshint ignore:line +} + +/** + * Also fix for the absent console in IE9 + */ +if (!window.console) +{ + window.console = {}; + window.console.log = window.console.assert = function(){}; + window.console.warn = window.console.assert = function(){}; +} + +/** + * Fix for Object.assign not existing on older devices + */ + +if (!Object.assign) { + /* jshint -W098 */ + // We include `varArgs` (unused) to ensure Object.assign.length === 2 + Object.assign = function(target, varArgs) { + /* jshint +W098 */ + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + var hasOwn = Object.prototype.hasOwnProperty; + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (hasOwn.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @class Phaser.Utils +* @static +*/ +Phaser.Utils = { + + /** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @method Phaser.Utils.reverseString + * @param {string} string - The string to be reversed. + * @return {string} The reversed string. + */ + reverseString: function (string) { + + return string.split('').reverse().join(''); + + }, + + /** + * Gets an object's property by string. + * + * @method Phaser.Utils.getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + getProperty: function(obj, name) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + return obj[name]; + case 2: + return obj[parts[0]][parts[1]]; + case 3: + return obj[parts[0]][parts[1]][parts[2]]; + case 4: + return obj[parts[0]][parts[1]][parts[2]][parts[3]]; + default: + return this._getProperty(obj, name); + } + + }, + + /** + * Sets an object's properties from a map of property names and values. + * + * ```javascript + * Phaser.Utils.setProperties(sprite, { + * 'animations.paused': true, + * 'body.enable': false, + * 'input.draggable': true, + * }); + * ``` + * + * @method Phaser.Utils.setProperties + * @param {object} obj - The object to modify. + * @param {object} props - The property names and values to set on the object (see {@link #setProperty}). + * @return {object} The modified object. + */ + setProperties: function(obj, props) { + + for (var name in props) + { + this.setProperty(obj, name, props[name]); + } + + return obj; + + }, + + /** + * Sets an object's property by name and value. + * + * ```javascript + * Phaser.Utils.setProperty(sprite, 'body.velocity.x', 60); + * ``` + * + * @method Phaser.Utils.setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + + setProperty: function(obj, name, value) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + obj[name] = value; + break; + case 2: + obj[parts[0]][parts[1]] = value; + break; + case 3: + obj[parts[0]][parts[1]][parts[2]] = value; + break; + case 4: + obj[parts[0]][parts[1]][parts[2]][parts[3]] = value; + break; + default: + this._setProperty(obj, name, value); + } + }, + + /** + * Gets an object's property by string. + * + * @private + * @method Phaser.Utils._getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property whose value will be returned. + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + _getProperty: function(obj, name) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + val = obj; + + while (i < len) + { + var key = parts[i]; + + if (val != null) + { + val = val[key]; + i++; + } + else + { + return undefined; + } + } + + return val; + + }, + + /** + * Sets an object's property by name and value. + * + * @private + * @method Phaser.Utils._setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + _setProperty: function(obj, name, value) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + currentObj = obj, + key = parts[0]; + + if (len === 1) + { + obj[name] = value; + } + else + { + while (i < (len - 1)) + { + currentObj = currentObj[key]; + i++; + key = parts[i]; + } + + currentObj[key] = value; + } + + return obj; + + }, + + /** + * Generate a random bool result based on the chance value. + * + * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance + * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. + * + * @method Phaser.Utils#chanceRoll + * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). + * @return {boolean} True if the roll passed, or false otherwise. + */ + chanceRoll: function (chance) { + if (chance === undefined) { chance = 50; } + return chance > 0 && (Math.random() * 100 <= chance); + }, + + /** + * Choose between one of two values randomly. + * + * @method Phaser.Utils#randomChoice + * @param {any} choice1 + * @param {any} choice2 + * @return {any} The randomly selected choice + */ + randomChoice: function (choice1, choice2) { + return (Math.random() < 0.5) ? choice1 : choice2; + }, + + /** + * Get a unit dimension from a string. + * + * @method Phaser.Utils.parseDimension + * @param {string|number} size - The size to parse. + * @param {number} dimension - The window dimension to check. + * @return {number} The parsed dimension. + */ + parseDimension: function (size, dimension) { + + var f = 0; + var px = 0; + + if (typeof size === 'string') + { + // %? + if (size.substr(-1) === '%') + { + f = parseInt(size, 10) / 100; + + if (dimension === 0) + { + px = window.innerWidth * f; + } + else + { + px = window.innerHeight * f; + } + } + else + { + px = parseInt(size, 10); + } + } + else + { + px = size; + } + + return px; + + }, + + /** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @method Phaser.Utils.pad + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * @return {string} The padded string. + */ + pad: function (str, len, pad, dir) { + + if (len === undefined) { var len = 0; } + if (pad === undefined) { var pad = ' '; } + if (dir === undefined) { var dir = 3; } + + str = str.toString(); + + 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; + + }, + + /** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * @method Phaser.Utils.isPlainObject + * @param {object} obj - The object to inspect. + * @return {boolean} - true if the object is plain, otherwise false. + */ + isPlainObject: function (obj) { + + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) + { + return false; + } + + // Support: Firefox <20 + // The try/catch suppresses exceptions thrown when attempting to access + // the "constructor" property of certain host objects, ie. |window.location| + // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + try { + if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) + { + return false; + } + } catch (e) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + /** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @method Phaser.Utils.extend + * @param {boolean} deep - Perform a deep copy? + * @param {object} target - The target object to copy to. + * @return {object} The extended object. + */ + extend: function () { + + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if (typeof target === "boolean") + { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } + + for (; i < length; i++) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) + { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = Phaser.Utils.extend(deep, clone, copy); + + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; + + }, + + /** + * Mixes in an existing mixin object with the target. + * + * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` + * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and + * the result is assigned directly. + * + * @method Phaser.Utils.mixinPrototype + * @param {object} target - The target object to receive the new functions. + * @param {object} mixin - The object to copy the functions from. + * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not? + */ + mixinPrototype: function (target, mixin, replace) { + + if (replace === undefined) { replace = false; } + + var mixinKeys = Object.keys(mixin); + + for (var i = 0; i < mixinKeys.length; i++) + { + var key = mixinKeys[i]; + var value = mixin[key]; + + if (!replace && (key in target)) + { + // Not overwriting existing property + continue; + } + else + { + if (value && + (typeof value.get === 'function' || typeof value.set === 'function')) + { + // Special case for classes like Phaser.Point which has a 'set' function! + if (typeof value.clone === 'function') + { + target[key] = value.clone(); + } + else + { + Object.defineProperty(target, key, value); + } + } + else + { + target[key] = value; + } + } + } + + }, + + /** + * Mixes the source object into the destination object, returning the newly modified destination object. + * Based on original code by @mudcube + * + * @method Phaser.Utils.mixin + * @param {object} from - The object to copy (the source object). + * @param {object} to - The object to copy to (the destination object). + * @return {object} The modified destination object. + */ + mixin: function (from, to) { + + if (!from || typeof (from) !== "object") + { + return to; + } + + for (var key in from) + { + var o = from[key]; + + if (o.childNodes || o.cloneNode) + { + continue; + } + + var type = typeof (from[key]); + + if (!from[key] || type !== "object") + { + to[key] = from[key]; + } + else + { + // Clone sub-object + if (typeof (to[key]) === type) + { + to[key] = Phaser.Utils.mixin(from[key], to[key]); + } + else + { + to[key] = Phaser.Utils.mixin(from[key], new o.constructor()); + } + } + } + + return to; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. +* If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. +* +* @class Phaser.Circle +* @constructor +* @param {number} [x=0] - The x coordinate of the center of the circle. +* @param {number} [y=0] - The y coordinate of the center of the circle. +* @param {number} [diameter=0] - The diameter of the circle. +*/ +Phaser.Circle = function (x, y, diameter) { + + x = x || 0; + y = y || 0; + diameter = diameter || 0; + + /** + * @property {number} x - The x coordinate of the center of the circle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the center of the circle. + */ + this.y = y; + + /** + * @property {number} _diameter - The diameter of the circle. + * @private + */ + this._diameter = diameter; + + /** + * @property {number} _radius - The radius of the circle. + * @private + */ + this._radius = 0; + + if (diameter > 0) + { + this._radius = diameter * 0.5; + } + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.CIRCLE; + +}; + +Phaser.Circle.prototype = { + + /** + * The circumference of the circle. + * + * @method Phaser.Circle#circumference + * @return {number} The circumference of the circle. + */ + circumference: function () { + + return 2 * (Math.PI * this._radius); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Circle. + * + * @method Phaser.Circle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = 2 * Math.PI * Math.random(); + var u = Math.random() + Math.random(); + var r = (u > 1) ? 2 - u : u; + var x = r * Math.cos(t); + var y = r * Math.sin(t); + + out.x = this.x + (x * this.radius); + out.y = this.y + (y * this.radius); + + return out; + + }, + + /** + * Returns the framing rectangle of the circle as a Phaser.Rectangle object. + * + * @method Phaser.Circle#getBounds + * @return {Phaser.Rectangle} The bounds of the Circle. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter); + + }, + + /** + * Sets the members of Circle to the specified values. + * @method Phaser.Circle#setTo + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} diameter - The diameter of the circle. + * @return {Circle} This circle object. + */ + setTo: function (x, y, diameter) { + + this.x = x; + this.y = y; + this._diameter = diameter; + this._radius = diameter * 0.5; + + return this; + + }, + + /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method Phaser.Circle#copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.diameter); + + }, + + /** + * Copies the x, y and diameter properties from this Circle to any given object. + * @method Phaser.Circle#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.diameter = this._diameter; + + return dest; + + }, + + /** + * Returns the distance from the center of the Circle object to the given object + * (can be Circle, Point or anything with x/y properties) + * @method Phaser.Circle#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round=false] - Round the distance to the nearest integer. + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y); + return round ? Math.round(distance) : distance; + + }, + + /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. + * @method Phaser.Circle#clone + * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} The cloned Circle object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Circle(this.x, this.y, this.diameter); + } + else + { + output.setTo(this.x, this.y, this.diameter); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Circle object. + * @method Phaser.Circle#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this circle, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Circle.contains(this, x, y); + + }, + + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method Phaser.Circle#circumferencePoint + * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ + circumferencePoint: function (angle, asDegrees, out) { + + return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out); + + }, + + + /** + * Creates or positions points on the circle. + * + * The points are equally distributed in the half-closed interval [startAngle, endAngle). The default arc is the entire circle. + * + * If the `out` argument is omitted, this method creates and returns an array of {@link Phaser.Point points}. If an array is passed as `out`, its items are treated as points and placed in the same way. + * + * @param {type} [steps=60] - The number of points to place. + * @param {type} [startAngle=0] - The starting angle in radians (unless asDegrees is true). + * @param {type} [endAngle=Phaser.Math.PI2] - The end angle in radians (unless asDegrees is true). + * @param {type} [asDegrees=false] - Are the given angles in radians (false) or degrees (true)? + * @param {any[]} [out] - An array of points or point-like objects (e.g., sprites). It should start at index 0 and its length should be equal to or greater than `steps`. + * @return {any[]} - The modified `out` argument or a new array of points. + */ + sample: function (steps, startAngle, endAngle, asDegrees, out) { + + if (!steps) { steps = 60; } + if (startAngle == null) { startAngle = 0; } + if (endAngle == null) { endAngle = Phaser.Math.PI2; } + if (!out) { out = []; } + + var i = 0; + + while (i < steps) + { + this.circumferencePoint( + Phaser.Math.linear(startAngle, endAngle, i / steps), + asDegrees, + out[i] || (out[i] = new Phaser.Point()) + ); + + i += 1; + } + + return out; + + }, + + /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method Phaser.Circle#offset + * @param {number} dx - Moves the x value of the Circle object by this amount. + * @param {number} dy - Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Circle#offsetPoint + * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). + * @return {Circle} This Circle object. + */ + offsetPoint: function (point) { + return this.offset(point.x, point.y); + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Circle#toString + * @return {string} a string representation of the instance. + */ + toString: function () { + return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; + } + +}; + +Phaser.Circle.prototype.constructor = Phaser.Circle; + +/** +* The largest distance between any two points on the circle. The same as the radius * 2. +* +* @name Phaser.Circle#diameter +* @property {number} diameter - Gets or sets the diameter of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "diameter", { + + get: function () { + return this._diameter; + }, + + set: function (value) { + + if (value > 0) + { + this._diameter = value; + this._radius = value * 0.5; + } + } + +}); + +/** +* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. +* @name Phaser.Circle#radius +* @property {number} radius - Gets or sets the radius of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "radius", { + + get: function () { + return this._radius; + }, + + set: function (value) { + + if (value > 0) + { + this._radius = value; + this._diameter = value * 2; + } + + } + +}); + +/** +* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#left +* @propety {number} left - Gets or sets the value of the leftmost point of the circle. +*/ +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; + } + + } + +}); + +/** +* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#right +* @property {number} right - Gets or sets the value of the rightmost point of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "right", { + + get: function () { + return this.x + this._radius; + }, + + set: function (value) { + + if (value < this.x) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.x; + } + + } + +}); + +/** +* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#top +* @property {number} top - Gets or sets the top of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "top", { + + get: function () { + return this.y - this._radius; + }, + + set: function (value) { + + if (value > this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = this.y - value; + } + + } + +}); + +/** +* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#bottom +* @property {number} bottom - Gets or sets the bottom of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "bottom", { + + get: function () { + return this.y + this._radius; + }, + + set: function (value) { + + if (value < this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.y; + } + + } + +}); + +/** +* The area of this Circle. +* @name Phaser.Circle#area +* @property {number} area - The area of this circle. +* @readonly +*/ +Object.defineProperty(Phaser.Circle.prototype, "area", { + + get: function () { + + if (this._radius > 0) + { + return Math.PI * this._radius * this._radius; + } + else + { + return 0; + } + + } + +}); + +/** +* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. +* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. +* @name Phaser.Circle#empty +* @property {boolean} empty - Gets or sets the empty state of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "empty", { + + get: function () { + return (this._diameter === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Circle object. +* @method Phaser.Circle.contains +* @param {Phaser.Circle} a - The Circle to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this circle, otherwise false. +*/ +Phaser.Circle.contains = function (a, x, y) { + + // Check if x/y are within the bounds first + 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; + } + +}; + +/** +* Determines whether the two Circle objects match. This method compares the x, y and diameter properties. +* @method Phaser.Circle.equals +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. +*/ +Phaser.Circle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.diameter === b.diameter); + +}; + +/** +* Determines whether the two Circle objects intersect. +* This method checks the radius distances between the two Circle objects to see if they intersect. +* @method Phaser.Circle.intersects +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. +*/ +Phaser.Circle.intersects = function (a, b) { + + return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius)); + +}; + +/** +* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. +* @method Phaser.Circle.circumferencePoint +* @param {Phaser.Circle} a - The first Circle object. +* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. +* @return {Phaser.Point} The Point object holding the result. +*/ +Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) { + + if (asDegrees === undefined) { asDegrees = false; } + if (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; + +}; + +/** +* Checks if the given Circle and Rectangle objects intersect. +* @method Phaser.Circle.intersectsRectangle +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Rectangle} r - The Rectangle object to test. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +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; + +}; + +/** +* Checks if the given Circle and Line objects intersect. +* @method Phaser.Circle.intersectsLine +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnpoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Circle.intersectsLine = function (c, l, returnPoints) { + var h = c.x; + var k = c.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = c.radius; + var b = c.radius; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Circle = Phaser.Circle; + +/** +* @author Richard Davey +* @author Chad Engler +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a Ellipse object. A curve on a plane surrounding two focal points. +* +* @class Phaser.Ellipse +* @constructor +* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [width=0] - The overall width of this ellipse. +* @param {number} [height=0] - The overall height of this ellipse. +*/ +Phaser.Ellipse = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.x = x; + + /** + * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.y = y; + + /** + * @property {number} width - The overall width of this ellipse. + */ + this.width = width; + + /** + * @property {number} height - The overall height of this ellipse. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ELLIPSE; + +}; + +Phaser.Ellipse.prototype = { + + /** + * Sets the members of the Ellipse to the specified values. + * @method Phaser.Ellipse#setTo + * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} width - The overall width of this ellipse. + * @param {number} height - The overall height of this ellipse. + * @return {Phaser.Ellipse} This Ellipse object. + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. + * + * @method Phaser.Ellipse#getBounds + * @return {Phaser.Rectangle} The bounds of the Ellipse. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Ellipse. + * + * @method Phaser.Ellipse#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Ellipse} This Ellipse object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Ellipse to any given object. + * @method Phaser.Ellipse#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function(dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. + * @method Phaser.Ellipse#clone + * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. + * @return {Phaser.Ellipse} The cloned Ellipse object. + */ + clone: function(output) { + + if (output === undefined || output === null) + { + output = new Phaser.Ellipse(this.x, this.y, this.width, this.height); + } + else + { + output.setTo(this.x, this.y, this.width, this.height); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Ellipse object. + * + * @method Phaser.Ellipse#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this ellipse, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Ellipse.contains(this, x, y); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Ellipse. + * + * @method Phaser.Ellipse#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var p = Math.random() * Math.PI * 2; + var r = Math.random(); + + out.x = Math.sqrt(r) * Math.cos(p); + out.y = Math.sqrt(r) * Math.sin(p); + + out.x = this.x + (out.x * this.width / 2.0); + out.y = this.y + (out.y * this.height / 2.0); + + return out; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Ellipse#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]"; + } + +}; + +Phaser.Ellipse.prototype.constructor = Phaser.Ellipse; + +/** +* The left coordinate of the Ellipse. The same as the X coordinate. +* @name Phaser.Ellipse#left +* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + + this.x = value; + + } + +}); + +/** +* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. +* @name Phaser.Ellipse#right +* @property {number} right - Gets or sets the value of the rightmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "right", { + + get: function () { + return this.x + this.width; + }, + + set: function (value) { + + if (value < this.x) + { + this.width = 0; + } + else + { + this.width = value - this.x; + } + } + +}); + +/** +* The top of the Ellipse. The same as its y property. +* @name Phaser.Ellipse#top +* @property {number} top - Gets or sets the top of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "top", { + + get: function () { + return this.y; + }, + + set: function (value) { + this.y = value; + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. +* @name Phaser.Ellipse#bottom +* @property {number} bottom - Gets or sets the bottom of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value < this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + } + +}); + +/** +* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. +* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. +* @name Phaser.Ellipse#empty +* @property {boolean} empty - Gets or sets the empty state of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "empty", { + + get: function () { + return (this.width === 0 || this.height === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Ellipse object. +* +* @method Phaser.Ellipse.contains +* @param {Phaser.Ellipse} a - The Ellipse to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this ellipse, otherwise false. +*/ +Phaser.Ellipse.contains = function (a, x, y) { + + if (a.width <= 0 || a.height <= 0) { + return false; + } + + // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 + var normx = ((x - a.x) / a.width) - 0.5; + var normy = ((y - a.y) / a.height) - 0.5; + + normx *= normx; + normy *= normy; + + return (normx + normy < 0.25); + +}; + +/** +* Checks if the given Ellipse and Line objects intersect. +* @method Phaser.Ellipse.intersectsLine +* @param {Phaser.Ellipse} e - The Ellipse object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnPoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Ellipse.intersectsLine = function (e, l, returnPoints) { + var h = e.x; + var k = e.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = e.width / 2; + var b = e.height / 2; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Ellipse = Phaser.Ellipse; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Line object with a start and an end point. +* +* @class Phaser.Line +* @constructor +* @param {number} [x1=0] - The x coordinate of the start of the line. +* @param {number} [y1=0] - The y coordinate of the start of the line. +* @param {number} [x2=0] - The x coordinate of the end of the line. +* @param {number} [y2=0] - The y coordinate of the end of the line. +*/ +Phaser.Line = function (x1, y1, x2, y2) { + + x1 = x1 || 0; + y1 = y1 || 0; + x2 = x2 || 0; + y2 = y2 || 0; + + /** + * @property {Phaser.Point} start - The start point of the line. + */ + this.start = new Phaser.Point(x1, y1); + + /** + * @property {Phaser.Point} end - The end point of the line. + */ + this.end = new Phaser.Point(x2, y2); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.LINE; + +}; + +Phaser.Line.prototype = { + + /** + * Sets the components of the Line to the specified values. + * + * @method Phaser.Line#setTo + * @param {number} [x1=0] - The x coordinate of the start of the line. + * @param {number} [y1=0] - The y coordinate of the start of the line. + * @param {number} [x2=0] - The x coordinate of the end of the line. + * @param {number} [y2=0] - The y coordinate of the end of the line. + * @return {Phaser.Line} This line object + */ + setTo: function (x1, y1, x2, y2) { + + this.start.setTo(x1, y1); + this.end.setTo(x2, y2); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given points. + * + * @param {any} start - A {@link Phaser.Point} or point-like object. + * @param {any} end - A {@link Phaser.Point} or point-like object. + * @return {Phaser.Line} - This line object. + */ + fromPoints: function (start, end) { + + this.setTo(start.x, start.y, end.x, end.y); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given sprites. + * Can optionally be calculated from their center coordinates. + * + * @method Phaser.Line#fromSprite + * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {boolean} [useCenter=false] - If true it will use startSprite.centerX, if false startSprite.x. + * @return {Phaser.Line} This line object + */ + fromSprite: function (startSprite, endSprite, useCenter) { + + if (useCenter === undefined) { useCenter = false; } + + if (useCenter) + { + return this.setTo(startSprite.centerX, startSprite.centerY, endSprite.centerX, endSprite.centerY); + } + + return this.fromPoints(startSprite, endSprite); + + }, + + /** + * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. + * + * @method Phaser.Line#fromAngle + * @param {number} x - The x coordinate of the start of the line. + * @param {number} y - The y coordinate of the start of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line in pixels. + * @return {Phaser.Line} This line object + */ + fromAngle: function (x, y, angle, length) { + + this.start.setTo(x, y); + this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length)); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place from the center of the line. + * If you wish to rotate around a different point see Line.rotateAround. + * + * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. + * + * @method Phaser.Line#rotate + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotate: function (angle, asDegrees) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + this.start.rotate(cx, cy, angle, asDegrees); + this.end.rotate(cx, cy, angle, asDegrees); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place around the coordinates given. + * + * @method Phaser.Line#rotateAround + * @param {number} x - The x coordinate to offset the rotation from. + * @param {number} y - The y coordinate to offset the rotation from. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotateAround: function (x, y, angle, asDegrees) { + + this.start.rotate(x, y, angle, asDegrees); + this.end.rotate(x, y, angle, asDegrees); + + return this; + + }, + + /** + * Checks for intersection between this line and another Line. + * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * + * @method Phaser.Line#intersects + * @param {Phaser.Line} line - The line to check against this one. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ + intersects: function (line, asSegment, result) { + + return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result); + + }, + + /** + * Returns the reflected angle between two lines. + * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. + * + * @method Phaser.Line#reflect + * @param {Phaser.Line} line - The line to reflect off this line. + * @return {number} The reflected angle in radians. + */ + reflect: function (line) { + + return Phaser.Line.reflect(this, line); + + }, + + /** + * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. + * + * @method Phaser.Line#midPoint + * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. + * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. + */ + midPoint: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = (this.start.x + this.end.x) / 2; + out.y = (this.start.y + this.end.y) / 2; + + return out; + + }, + + /** + * Centers this Line on the given coordinates. + * + * The line is centered by positioning the start and end points so that the lines midpoint matches + * the coordinates given. + * + * @method Phaser.Line#centerOn + * @param {number} x - The x position to center the line on. + * @param {number} y - The y position to center the line on. + * @return {Phaser.Line} This line object + */ + centerOn: function (x, y) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + var tx = x - cx; + var ty = y - cy; + + this.start.add(tx, ty); + this.end.add(tx, ty); + + }, + + /** + * Tests if the given coordinates fall on this line. See {@link #pointOnSegment} to test against just the line segment. + * + * @method Phaser.Line#pointOnLine + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line, false if not. + */ + pointOnLine: function (x, y, epsilon) { + + return Phaser.Math.fuzzyEqual((x - this.start.x) * (this.end.y - this.start.y), (this.end.x - this.start.x) * (y - this.start.y), epsilon || 0); + + }, + + /** + * Tests if the given coordinates fall on this line and within the segment. See {@link #pointOnLine} to test against just the line. + * + * @method Phaser.Line#pointOnSegment + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line and segment, false if not. + */ + pointOnSegment: function (x, y, epsilon) { + + var xMin = Math.min(this.start.x, this.end.x); + var xMax = Math.max(this.start.x, this.end.x); + var yMin = Math.min(this.start.y, this.end.y); + var yMax = Math.max(this.start.y, this.end.y); + + return (this.pointOnLine(x, y, epsilon) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)); + + }, + + /** + * Picks a random point from anywhere on the Line segment and returns it. + * + * @method Phaser.Line#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = Math.random(); + + out.x = this.start.x + t * (this.end.x - this.start.x); + out.y = this.start.y + t * (this.end.y - this.start.y); + + return out; + + }, + + /** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * The start and end points are rounded before this runs as the algorithm works on integers. + * + * @method Phaser.Line#coordinatesOnLine + * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. + * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. + * @return {array} An array of coordinates. + */ + coordinatesOnLine: function (stepRate, results) { + + if (stepRate === undefined) { stepRate = 1; } + if (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 < x2) ? 1 : -1; + var sy = (y1 < y2) ? 1 : -1; + var err = dx - dy; + + results.push([x1, y1]); + + var i = 1; + + while (!((x1 === x2) && (y1 === y2))) + { + var e2 = err << 1; + + if (e2 > -dy) + { + err -= dy; + x1 += sx; + } + + if (e2 < dx) + { + err += dx; + y1 += sy; + } + + if (i % stepRate === 0) + { + results.push([x1, y1]); + } + + i++; + + } + + return results; + + }, + + /** + * Returns a new Line object with the same values for the start and end properties as this Line object. + * @method Phaser.Line#clone + * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned. + * @return {Phaser.Line} The cloned Line object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y); + } + else + { + output.setTo(this.start.x, this.start.y, this.end.x, this.end.y); + } + + return output; + + } + +}; + +/** +* @name Phaser.Line#length +* @property {number} length - Gets the length of the line segment. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "length", { + + get: function () { + return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#angle +* @property {number} angle - Gets the angle of the line in radians. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "angle", { + + get: function () { + return Phaser.Point.angle(this.end, this.start); + } + +}); + +/** +* @name Phaser.Line#slope +* @property {number} slope - Gets the slope of the line (y/x). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "slope", { + + get: function () { + return (this.end.y - this.start.y) / (this.end.x - this.start.x); + } + +}); + +/** +* @name Phaser.Line#perpSlope +* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "perpSlope", { + + get: function () { + return -((this.end.x - this.start.x) / (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#x +* @property {number} x - Gets the x coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "x", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#y +* @property {number} y - Gets the y coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "y", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#left +* @property {number} left - Gets the left-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "left", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#right +* @property {number} right - Gets the right-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "right", { + + get: function () { + return Math.max(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#top +* @property {number} top - Gets the top-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "top", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#bottom +* @property {number} bottom - Gets the bottom-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "bottom", { + + get: function () { + return Math.max(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#width +* @property {number} width - Gets the width of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "width", { + + get: function () { + return Math.abs(this.start.x - this.end.x); + } + +}); + +/** +* @name Phaser.Line#height +* @property {number} height - Gets the height of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "height", { + + get: function () { + return Math.abs(this.start.y - this.end.y); + } + +}); + +/** +* @name Phaser.Line#normalX +* @property {number} normalX - Gets the x component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalX", { + + get: function () { + return Math.cos(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalY +* @property {number} normalY - Gets the y component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalY", { + + get: function () { + return Math.sin(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalAngle +* @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalAngle", { + + get: function () { + return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI); + } + +}); + +/** +* Checks for intersection between two lines as defined by the given start and end points. +* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersectsPoints +* @param {Phaser.Point} a - The start of the first Line to be checked. +* @param {Phaser.Point} b - The end of the first line to be checked. +* @param {Phaser.Point} e - The start of the second Line to be checked. +* @param {Phaser.Point} f - The end of the second line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) { + + if (asSegment === undefined) { asSegment = true; } + if (result === undefined) { result = new Phaser.Point(); } + + var a1 = b.y - a.y; + var a2 = f.y - e.y; + var b1 = a.x - b.x; + var b2 = e.x - f.x; + var c1 = (b.x * a.y) - (a.x * b.y); + var c2 = (f.x * e.y) - (e.x * f.y); + var denom = (a1 * b2) - (a2 * b1); + + if (denom === 0) + { + return null; + } + + result.x = ((b1 * c2) - (b2 * c1)) / denom; + result.y = ((a2 * c1) - (a1 * c2)) / denom; + + if (asSegment) + { + var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y)); + var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc; + var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc; + + if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) + { + return result; + } + else + { + return null; + } + } + + return result; + +}; + +/** +* Checks for intersection between two lines. +* If asSegment is true it will check for segment intersection. +* If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersects +* @param {Phaser.Line} a - The first Line to be checked. +* @param {Phaser.Line} b - The second Line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersects = function (a, b, asSegment, result) { + + return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result); + +}; + +/** +* Checks for intersection between the Line and a Rectangle shape, or a rectangle-like +* object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. +* +* An intersection is considered valid if: +* +* The line starts within or ends within the rectangle; or +* The line segment intersects one of the 4 rectangle edges; and +* The line has a non-zero length; and +* The rectangle is not empty. +* +* For the purposes of this function rectangles are considered 'solid'. +* +* @method Phaser.Line.intersectsRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle. +*/ +Phaser.Line.intersectsRectangle = function (line, rect) { + + // Quick bail out + if (line.length === 0 || rect.empty) + { + return false; + } + + var x1 = line.start.x; + var y1 = line.start.y; + + var x2 = line.end.x; + var y2 = line.end.y; + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + + var t = 0; + + // If the start or end of the line is inside the rect then we assume + // collision, as rects are solid for our use-case. + + if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || + (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) + { + return true; + } + + if (x1 < bx1 && x2 >= bx1) + { + // Left edge + t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); + + if (t > by1 && t <= by2) + { + return true; + } + } + else if (x1 > bx2 && x2 <= bx2) + { + // Right edge + t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); + + if (t >= by1 && t <= by2) + { + return true; + } + } + + if (y1 < by1 && y2 >= by1) + { + // Top edge + t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + else if (y1 > by2 && y2 <= by2) + { + // Bottom edge + t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + + return false; + +}; + +/** +* Finds the closest intersection between the Line and a Rectangle shape, or a rectangle-like +* object, such as a Sprite or Body. +* +* @method Phaser.Line.intersectionWithRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @param {Phaser.Point} [result] - A Point object to store the result in. +* @return {?Phaser.Point} - The intersection closest to the Line's start, or null if there is no intersection. +*/ +Phaser.Line.intersectionWithRectangle = function (line, rect, result) { + + var self = Phaser.Line.intersectionWithRectangle; + + if (!result) + { + result = new Phaser.Point(); + } + + if (!self.edges) + { + self.edges = [new Phaser.Line(), new Phaser.Line(), new Phaser.Line(), new Phaser.Line()]; + } + + if (!self.edgeIntersection) + { + self.edgeIntersection = new Phaser.Point(); + } + + var edges = self.edges; + var edgeIntersection = self.edgeIntersection.set(0); + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + var closestDistance = Infinity; + + edges[0].setTo(bx1, by1, bx2, by1); + edges[1].setTo(bx1, by2, bx2, by2); + edges[2].setTo(bx1, by1, bx1, by2); + edges[3].setTo(bx2, by1, bx2, by2); + + for (var edge, i = 0; (edge = edges[i]); i++) + { + if (line.intersects(edge, true, edgeIntersection)) + { + var distance = line.start.distance(edgeIntersection); + + if (distance < closestDistance) + { + closestDistance = distance; + result.copyFrom(edgeIntersection); + } + } + } + + if (distance != null) + { + return result; + } + + return null; + +}; + +/** +* Returns the reflected angle between two lines. +* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. +* +* @method Phaser.Line.reflect +* @param {Phaser.Line} a - The base line. +* @param {Phaser.Line} b - The line to be reflected from the base line. +* @return {number} The reflected angle in radians. +*/ +Phaser.Line.reflect = function (a, b) { + + return 2 * b.normalAngle - 3.141592653589793 - a.angle; + +}; + +/** +* @author Mat Groves http://matgroves.com/ @Doormat23 +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. +* +* It is represented like so: +* +* | a | b | tx | +* | c | d | ty | +* | 0 | 0 | 1 | +* +* @class Phaser.Matrix +* @constructor +* @param {number} [a=1] - Horizontal scaling +* @param {number} [b=0] - Horizontal skewing +* @param {number} [c=0] - Vertical skewing +* @param {number} [d=1] - Vertical scaling +* @param {number} [tx=0] - Horizontal translation +* @param {number} [ty=0] - Vertical translation +*/ +Phaser.Matrix = function (a, b, c, d, tx, ty) { + + if (a === undefined || a === null) { a = 1; } + if (b === undefined || b === null) { b = 0; } + if (c === undefined || c === null) { c = 0; } + if (d === undefined || d === null) { d = 1; } + if (tx === undefined || tx === null) { tx = 0; } + if (ty === undefined || ty === null) { ty = 0; } + + /** + * @property {number} a + * @default 1 + */ + this.a = a; + + /** + * @property {number} b + * @default 0 + */ + this.b = b; + + /** + * @property {number} c + * @default 0 + */ + this.c = c; + + /** + * @property {number} d + * @default 1 + */ + this.d = d; + + /** + * @property {number} tx + * @default 0 + */ + this.tx = tx; + + /** + * @property {number} ty + * @default 0 + */ + this.ty = ty; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.MATRIX; + +}; + +Phaser.Matrix.prototype = { + + /** + * Sets the values of this Matrix to the values in the given array. + * + * The Array elements should be set as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @method Phaser.Matrix#fromArray + * @param {Array} array - The array to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + fromArray: function (array) { + + return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]); + + }, + + /** + * Sets the values of this Matrix to the given values. + * + * @method Phaser.Matrix#setTo + * @param {number} a - Horizontal scaling + * @param {number} b - Horizontal skewing + * @param {number} c - Vertical skewing + * @param {number} d - Vertical scaling + * @param {number} tx - Horizontal translation + * @param {number} ty - Vertical translation + * @return {Phaser.Matrix} This Matrix object. + */ + setTo: function (a, b, c, d, tx, ty) { + + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + + }, + + /** + * Creates a new Matrix object based on the values of this Matrix. + * If you provide the output parameter the values of this Matrix will be copied over to it. + * If the output parameter is blank a new Matrix object will be created. + * + * @method Phaser.Matrix#clone + * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created. + * @return {Phaser.Matrix} A clone of this Matrix. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); + } + else + { + output.a = this.a; + output.b = this.b; + output.c = this.c; + output.d = this.d; + output.tx = this.tx; + output.ty = this.ty; + } + + return output; + + }, + + /** + * Copies the properties from this Matrix to the given Matrix. + * + * @method Phaser.Matrix#copyTo + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} The destination Matrix object. + */ + copyTo: function (matrix) { + + matrix.copyFrom(this); + + return matrix; + + }, + + /** + * Copies the properties from the given Matrix into this Matrix. + * + * @method Phaser.Matrix#copyFrom + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + copyFrom: function (matrix) { + + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + + return this; + + }, + + /** + * Creates a Float32 Array with values populated from this Matrix object. + * + * @method Phaser.Matrix#toArray + * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not. + * @param {Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created. + * @return {Float32Array} The newly created array which contains the matrix. + */ + toArray: function (transpose, array) { + + if (array === undefined) { array = new Float32Array(9); } + + if (transpose) + { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else + { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + + }, + + /** + * Get a new position with the current transformation applied. + * + * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) + * + * @method Phaser.Matrix#apply + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, transformed through this matrix. + */ + apply: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + newPos.x = this.a * pos.x + this.c * pos.y + this.tx; + newPos.y = this.b * pos.x + this.d * pos.y + this.ty; + + return newPos; + + }, + + /** + * Get a new position with the inverse of the current transformation applied. + * + * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) + * + * @method Phaser.Matrix#applyInverse + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, inverse transformed through this matrix. + */ + applyInverse: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + var id = 1 / (this.a * this.d + this.c * -this.b); + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + + }, + + /** + * Translates the matrix on the x and y. + * This is the same as Matrix.tx += x. + * + * @method Phaser.Matrix#translate + * @param {number} x - The x value to translate on. + * @param {number} y - The y value to translate on. + * @return {Phaser.Matrix} This Matrix object. + */ + translate: function (x, y) { + + this.tx += x; + this.ty += y; + + return this; + + }, + + /** + * Applies a scale transformation to this matrix. + * + * @method Phaser.Matrix#scale + * @param {number} x - The amount to scale horizontally. + * @param {number} y - The amount to scale vertically. + * @return {Phaser.Matrix} This Matrix object. + */ + scale: function (x, y) { + + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + + }, + + /** + * Applies a rotation transformation to this matrix. + * + * @method Phaser.Matrix#rotate + * @param {number} angle - The angle to rotate by, given in radians. + * @return {Phaser.Matrix} This Matrix object. + */ + rotate: function (angle) { + + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos-this.b * sin; + this.b = a1 * sin+this.b * cos; + this.c = c1 * cos-this.d * sin; + this.d = c1 * sin+this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + + }, + + /** + * Appends the given Matrix to this Matrix. + * + * @method Phaser.Matrix#append + * @param {Phaser.Matrix} matrix - The matrix to append to this one. + * @return {Phaser.Matrix} This Matrix object. + */ + append: function (matrix) { + + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + + }, + + /** + * Resets this Matrix to an identity (default) matrix. + * + * @method Phaser.Matrix#identity + * @return {Phaser.Matrix} This Matrix object. + */ + identity: function () { + + return this.setTo(1, 0, 0, 1, 0, 0); + + } + +}; + +Phaser.identityMatrix = new Phaser.Matrix(); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. +* The following code creates a point at (0,0): +* `var myPoint = new Phaser.Point();` +* You can also use them as 2D Vectors and you'll find different vector related methods in this class. +* +* @class Phaser.Point +* @constructor +* @param {number} [x=0] - The horizontal position of this Point. +* @param {number} [y=0] - The vertical position of this Point. +*/ +Phaser.Point = function (x, y) { + + x = x || 0; + y = y || 0; + + /** + * @property {number} x - The x value of the point. + */ + this.x = x; + + /** + * @property {number} y - The y value of the point. + */ + this.y = y; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINT; + +}; + +Phaser.Point.prototype = { + + /** + * Copies the x and y properties from any given object to this Point. + * + * @method Phaser.Point#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Point} This Point object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y); + + }, + + /** + * Inverts the x and y values of this Point + * + * @method Phaser.Point#invert + * @return {Phaser.Point} This Point object. + */ + invert: function () { + + return this.setTo(this.y, this.x); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.setTo(2)` is the same as `Point.setTo(2, 2)` + * + * Identical to {@link #set}. + * + * @method Phaser.Point#setTo + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setTo: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.set(2)` is the same as `Point.set(2, 2)` + * + * Identical to {@link #setTo}. + * + * @method Phaser.Point#set + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + set: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object from a given polar coordinate. + * + * @method Phaser.Point#setToPolar + * @param {number} azimuth - The angular coordinate, in radians (unless `asDegrees`). + * @param {number} [radius=1] - The radial coordinate (length). + * @param {boolean} [asDegrees=false] - True if `azimuth` is in degrees. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setToPolar: function(azimuth, radius, asDegrees) { + + if (radius == null) { radius = 1; } + if (asDegrees) { azimuth = Phaser.Math.degToRad(azimuth); } + + return this.setTo(Math.cos(azimuth) * radius, Math.sin(azimuth) * radius); + + }, + + /** + * Adds the given x and y values to this Point. + * + * @method Phaser.Point#add + * @param {number} x - The value to add to Point.x. + * @param {number} y - The value to add to Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + add: function (x, y) { + + this.x += x; + this.y += y; + return this; + + }, + + /** + * Subtracts the given x and y values from this Point. + * + * @method Phaser.Point#subtract + * @param {number} x - The value to subtract from Point.x. + * @param {number} y - The value to subtract from Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + subtract: function (x, y) { + + this.x -= x; + this.y -= y; + return this; + + }, + + /** + * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. + * + * @method Phaser.Point#multiply + * @param {number} x - The value to multiply Point.x by. + * @param {number} y - The value to multiply Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + multiply: function (x, y) { + + this.x *= x; + this.y *= y; + return this; + + }, + + /** + * Divides Point.x and Point.y by the given x and y values. + * + * @method Phaser.Point#divide + * @param {number} x - The value to divide Point.x by. + * @param {number} y - The value to divide Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + divide: function (x, y) { + + this.x /= x; + this.y /= y; + return this; + + }, + + /** + * Clamps the x value of this Point to be between the given min and max. + * + * @method Phaser.Point#clampX + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampX: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + return this; + + }, + + /** + * Clamps the y value of this Point to be between the given min and max + * + * @method Phaser.Point#clampY + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampY: function (min, max) { + + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * Clamps this Point object values to be between the given min and max. + * + * @method Phaser.Point#clamp + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clamp: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * If this Point is not within the given object, moves it inside (at the nearest edge). + * + * @method Phaser.Point#clip + * @param {any} rect - A {@link Phaser.Rectangle} or any object with left, top, right, and bottom properties. + * @return {Phaser.Point} This Point object. + */ + clip: function (rect) { + + var left = rect.left, top = rect.top, right = rect.right, bottom = rect.bottom; + + if (this.x < left ) { this.x = left; } + else if (this.x > right) { this.x = right; } + if (this.y < top) { this.y = top; } + else if (this.y > bottom) { this.y = bottom; } + + return this; + + }, + + /** + * Creates a copy of the given Point. + * + * @method Phaser.Point#clone + * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The new Point object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(this.x, this.y); + } + else + { + output.setTo(this.x, this.y); + } + + return output; + + }, + + /** + * Copies the x and y properties from this Point to any given object. + * + * @method Phaser.Point#copyTo + * @param {any} dest - The object to copy to. + * @return {object} The dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + + return dest; + + }, + + /** + * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) + * + * @method Phaser.Point#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round] - Round the distance to the nearest integer (default false). + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + return Phaser.Point.distance(this, dest, round); + + }, + + /** + * Determines whether the given objects x/y values are equal to this Point object. + * + * @method Phaser.Point#equals + * @param {Phaser.Point|any} a - The object to compare with this Point. + * @return {boolean} A value of true if the x and y points are equal, otherwise false. + */ + equals: function (a) { + + return a.x === this.x && a.y === this.y; + + }, + + /** + * Determines whether a set of x-y coordinates are equal to this Point's. + * + * @method Phaser.Point#equalsXY + * @param {number} x - The x-coordinate to compare with this Point. + * @param {number} y - The y-coordinate to compare with this Point. + * @return {boolean} A value of true if the Point's coordinates are identical to the arguments, otherwise false. + */ + equalsXY: function (x, y) { + + return this.x === x && this.y === y; + + }, + + fuzzyEquals: function (a, epsilon) { + + return Phaser.Point.fuzzyEquals(this, a, epsilon); + + }, + + fuzzyEqualsXY: function (x, y, epsilon) { + + return Phaser.Point.fuzzyEqualsXY(this, x, y, epsilon); + + }, + + /** + * Returns the angle between this Point object and another object with public x and y properties. + * + * @method Phaser.Point#angle + * @param {Phaser.Point|any} a - The object to get the angle from this Point to. + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angle: function (a, asDegrees) { + + return this.angleXY(a.x, a.y, asDegrees); + + }, + + /** + * Returns the angle between this Point object and an x-y coordinate pair. + * + * @method Phaser.Point#angleXY + * @param {number} x - The x-coordinate + * @param {number} y - The y-coordinate + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angleXY: function (x, y, asDegrees) { + + var angle = Math.atan2(y - this.y, x - this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Returns the arctangent of this Point. + * + * @method Phaser.Point#atan + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where the vertex is (0, 0). Within [-pi, pi] or [-180deg, 180deg]. + */ + atan: function (asDegrees) { + + var angle = Math.atan2(this.y, this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Rotates this Point around the x/y coordinates given to the desired angle. + * + * @method Phaser.Point#rotate + * @param {number} x - The x coordinate of the anchor point. + * @param {number} y - The y coordinate of the anchor point. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {number} [distance] - An optional distance constraint between the Point and the anchor. + * @return {Phaser.Point} The modified point object. + */ + rotate: function (x, y, angle, asDegrees, distance) { + + return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance); + + }, + + /** + * Calculates the length of the Point object. + * + * @method Phaser.Point#getMagnitude + * @return {number} The length of the Point. + */ + getMagnitude: function () { + + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + + }, + + /** + * Calculates the length squared of the Point object. + * + * @method Phaser.Point#getMagnitudeSq + * @return {number} The length ^ 2 of the Point. + */ + getMagnitudeSq: function () { + + return (this.x * this.x) + (this.y * this.y); + + }, + + /** + * Alters the length of the Point without changing the direction. + * + * @method Phaser.Point#setMagnitude + * @param {number} magnitude - The desired magnitude of the resulting Point. + * @return {Phaser.Point} This Point object. + */ + setMagnitude: function (magnitude) { + + return this.normalize().multiply(magnitude, magnitude); + + }, + + /** + * Alters the Point object so that its length is 1, but it retains the same direction. + * + * @method Phaser.Point#normalize + * @return {Phaser.Point} This Point object. + */ + normalize: function () { + + if (!this.isZero()) + { + var m = this.getMagnitude(); + this.x /= m; + this.y /= m; + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at most the max value. + * + * @method Phaser.Point#limit + * @param {number} max - The maximum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#expand + */ + limit: function (max) { + + if (this.getMagnitudeSq() > max * max) + { + this.setMagnitude(max); + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at least the min value. + * + * @method Phaser.Point#expand + * @param {number} min - The minimum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#limit + */ + expand: function (min) { + + if (this.getMagnitudeSq() < min * min) + { + this.setMagnitude(min); + } + + return this; + + }, + + /** + * Determine if this point is at 0,0. + * + * @method Phaser.Point#isZero + * @return {boolean} True if this Point is 0,0, otherwise false. + */ + isZero: function () { + + return (this.x === 0 && this.y === 0); + + }, + + /** + * The dot product of this and another Point object. + * + * @method Phaser.Point#dot + * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point. + * @return {number} The result. + */ + dot: function (a) { + + return ((this.x * a.x) + (this.y * a.y)); + + }, + + /** + * The cross product of this and another Point object. + * + * @method Phaser.Point#cross + * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point. + * @return {number} The result. + */ + cross: function (a) { + + return ((this.x * a.y) - (this.y * a.x)); + + }, + + /** + * Make this Point perpendicular (90 degrees rotation) + * + * @method Phaser.Point#perp + * @return {Phaser.Point} This Point object. + */ + perp: function () { + + return this.setTo(-this.y, this.x); + + }, + + /** + * Make this Point perpendicular (-90 degrees rotation) + * + * @method Phaser.Point#rperp + * @return {Phaser.Point} This Point object. + */ + rperp: function () { + + return this.setTo(this.y, -this.x); + + }, + + /** + * Right-hand normalize (make unit length) this Point. + * + * @method Phaser.Point#normalRightHand + * @return {Phaser.Point} This Point object. + */ + normalRightHand: function () { + + return this.setTo(this.y * -1, this.x); + + }, + + /** + * Math.floor() both the x and y properties of this Point. + * + * @method Phaser.Point#floor + * @return {Phaser.Point} This Point object. + */ + floor: function () { + + return this.setTo(Math.floor(this.x), Math.floor(this.y)); + + }, + + /** + * Math.ceil() both the x and y properties of this Point. + * + * @method Phaser.Point#ceil + * @return {Phaser.Point} This Point object. + */ + ceil: function () { + + return this.setTo(Math.ceil(this.x), Math.ceil(this.y)); + + }, + + /** + * Math.round() both the x and y properties of this Point. + * + * @method Phaser.Point#round + * @return {Phaser.Point} This Point object. + */ + round: function () { + + return this.setTo(Math.round(this.x), Math.round(this.y)); + + }, + + /** + * Returns a string representation of this object. + * + * @method Phaser.Point#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; + + } + +}; + +Phaser.Point.prototype.constructor = Phaser.Point; + +/** +* Adds the coordinates of two points together to create a new point. +* +* @method Phaser.Point.add +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.add = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x + b.x; + out.y = a.y + b.y; + + return out; + +}; + +/** +* Subtracts the coordinates of two points to create a new point. +* +* @method Phaser.Point.subtract +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.subtract = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x - b.x; + out.y = a.y - b.y; + + return out; + +}; + +/** +* Multiplies the coordinates of two points to create a new point. +* +* @method Phaser.Point.multiply +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiply = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x * b.x; + out.y = a.y * b.y; + + return out; + +}; + +/** +* Divides the coordinates of two points to create a new point. +* +* @method Phaser.Point.divide +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.divide = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x / b.x; + out.y = a.y / b.y; + + return out; + +}; + +/** +* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. +* +* @method Phaser.Point.equals +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {boolean} A value of true if the Points are equal, otherwise false. +*/ +Phaser.Point.equals = function (a, b) { + + return a.x === b.x && a.y === b.y; + +}; + +Phaser.Point.equalsXY = function (a, x, y) { + + return a.x === x && a.y === y; + +}; + +Phaser.Point.fuzzyEquals = function (a, b, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, b.x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, b.y, epsilon); + +}; + +Phaser.Point.fuzzyEqualsXY = function (a, x, y, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, y, epsilon); + +}; + +/** +* Returns the angle between two Point objects. +* +* @method Phaser.Point.angle +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {number} The angle, where b is the vertex. Within [-pi, pi]. +*/ +Phaser.Point.angle = function (a, b) { + + return Math.atan2(a.y - b.y, a.x - b.x); + +}; + +/** +* Creates a negative Point. +* +* @method Phaser.Point.negative +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.negative = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.x, -a.y); + +}; + +/** +* Adds two 2D Points together and multiplies the result by the given scalar. +* +* @method Phaser.Point.multiplyAdd +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} s - The scaling value. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiplyAdd = function (a, b, s, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + b.x * s, a.y + b.y * s); + +}; + +/** +* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. +* +* @method Phaser.Point.interpolate +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.interpolate = function (a, b, f, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f); + +}; + +/** +* Return a perpendicular vector (90 degrees rotation) +* +* @method Phaser.Point.perp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.perp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.y, a.x); + +}; + +/** +* Return a perpendicular vector (-90 degrees rotation) +* +* @method Phaser.Point.rperp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.rperp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y, -a.x); + +}; + +/** +* Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). +* +* @method Phaser.Point.distance +* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. +* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. +* @param {boolean} [round=false] - Round the distance to the nearest integer. +* @return {number} The distance between this Point object and the destination Point object. +*/ +Phaser.Point.distance = function (a, b, round) { + + var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y); + return round ? Math.round(distance) : distance; + +}; + +/** +* Project two Points onto another Point. +* +* @method Phaser.Point.project +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.project = function (a, b, out) { + + if (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; + +}; + +/** +* Project two Points onto a Point of unit length. +* +* @method Phaser.Point.projectUnit +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.projectUnit = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var amt = a.dot(b); + + if (amt !== 0) + { + out.setTo(amt * b.x, amt * b.y); + } + + return out; + +}; + +/** +* Right-hand normalize (make unit length) a Point. +* +* @method Phaser.Point.normalRightHand +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalRightHand = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y * -1, a.x); + +}; + +/** +* Normalize (make unit length) a Point. +* +* @method Phaser.Point.normalize +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalize = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var m = a.getMagnitude(); + + if (m !== 0) + { + out.setTo(a.x / m, a.y / m); + } + + return out; + +}; + +/** +* Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by +* the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument +* is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. +* +* The distance allows you to specify a distance constraint for the rotation between the point and the +* coordinates. If none is given the distance between the two is calculated and used. +* +* @method Phaser.Point.rotate +* @param {Phaser.Point} a - The Point object to rotate. +* @param {number} x - The x coordinate of the anchor point +* @param {number} y - The y coordinate of the anchor point +* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {number} [distance] - An optional distance constraint between the Point and the anchor. +* @return {Phaser.Point} The modified point object. +*/ +Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) { + + if (asDegrees) { angle = Phaser.Math.degToRad(angle); } + + if (distance === undefined) + { + a.subtract(x, y); + + var s = Math.sin(angle); + var c = Math.cos(angle); + + var tx = c * a.x - s * a.y; + var ty = s * a.x + c * a.y; + + a.x = tx + x; + a.y = ty + y; + } + else + { + var t = angle + Math.atan2(a.y - y, a.x - x); + a.x = x + distance * Math.cos(t); + a.y = y + distance * Math.sin(t); + } + + return a; + +}; + +/** +* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. +* +* @method Phaser.Point.centroid +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.centroid = function (points, out) { + + if (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 < pointslength; i++) + { + Phaser.Point.add(out, points[i], out); + } + + out.divide(pointslength, pointslength); + + return out; + +}; + +/** +* Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. +* If the object doesn't contain those properties a Point with x/y of zero will be returned. +* +* @method Phaser.Point.parse +* @static +* @param {object} obj - The object to parse. +* @param {string} [xProp='x'] - The property used to set the Point.x value. +* @param {string} [yProp='y'] - The property used to set the Point.y value. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.parse = function(obj, xProp, yProp) { + + xProp = xProp || 'x'; + yProp = yProp || 'y'; + + var point = new Phaser.Point(); + + if (obj[xProp]) + { + point.x = parseInt(obj[xProp], 10); + } + + if (obj[yProp]) + { + point.y = parseInt(obj[yProp], 10); + } + + return point; + +}; + +/** + * Tests a Point or Point-like object. + * + * @method Phaser.Point.isPoint + * @static + * @return {boolean} - True if the object has numeric x and y properties. + */ +Phaser.Point.isPoint = function(obj) { + + return (obj != null) && (typeof obj.x === 'number') && (typeof obj.y === 'number'); + +}; + +/** +* Sets the `x` and `y` values of an object and returns the object. +* +* @method Phaser.Point#set +* @static +* @param {object} obj - An object with numeric x and y properties. +* @param {number} x - The x value. +* @param {number} [y] - The y value. If not given the x value will be used in its place. +* @return {object} The object. Useful for chaining method calls. +*/ +Phaser.Point.set = function(obj, x, y) { + + obj.x = x || 0; + obj.y = y || ( (y !== 0) ? obj.x : 0 ); + + return obj; + +}; + +/** +* Sorts an array of points in a clockwise direction, relative to a reference point. +* +* The sort is clockwise relative to the display, starting from a 12 o'clock position. +* (In the Cartesian plane, it is anticlockwise, starting from the -y direction.) +* +* Example sequence: (0, -1), (1, 0), (0, 1), (-1, 0) +* +* @method Phaser.Point#sortClockwise +* @static +* @param {array} points - An array of Points or point-like objects (e.g., sprites). +* @param {object|Phaser.Point} [center] - The reference point. If omitted, the {@link #centroid} (midpoint) of the points is used. +* @return {array} The sorted array. +*/ +Phaser.Point.sortClockwise = function(points, center) { + + // Adapted from (ciamej) + + if (!center) + { + center = this.centroid(points); + } + + var cx = center.x; + var cy = center.y; + + var sort = function(a, b) { + if (a.x - cx >= 0 && b.x - cx < 0) + { + return -1; + } + + if (a.x - cx < 0 && b.x - cx >= 0) + { + return 1; + } + + if (a.x - cx === 0 && b.x - cx === 0) + { + if (a.y - cy >= 0 || b.y - cy >= 0) + { + return (a.y > b.y) ? 1 : -1; + } + + return (b.y > a.y) ? 1 : -1; + } + + // Compute the cross product of vectors (center -> a) * (center -> b) + var det = (a.x - cx) * -(b.y - cy) - (b.x - cx) * -(a.y - cy); + + if (det < 0) + { + return -1; + } + + if (det > 0) + { + return 1; + } + + // Points a and b are on the same line from the center + // Check which point is closer to the center + var d1 = (a.x - cx) * (a.x - cx) + (a.y - cy) * (a.y - cy); + var d2 = (b.x - cx) * (b.x - cx) + (b.y - cy) * (b.y - cy); + + return (d1 > d2) ? -1 : 1; + }; + + return points.sort(sort); + +}; + + +// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Point = Phaser.Point; + +/** +* @author Richard Davey +* @author Adrien Brault +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Polygon. +* +* The points can be set from a variety of formats: +* +* - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` +* - An array of objects with public x/y properties: `[obj1, obj2, ...]` +* - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` +* - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` +* - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` +* - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` +* +* @class Phaser.Polygon +* @constructor +* @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. +*/ +Phaser.Polygon = function () { + + /** + * @property {number} area - The area of this Polygon. + */ + this.area = 0; + + /** + * @property {array} _points - An array of Points that make up this Polygon. + * @private + */ + this._points = []; + + if (arguments.length > 0) + { + this.setTo.apply(this, arguments); + } + + /** + * @property {boolean} closed - Is the Polygon closed or not? + */ + this.closed = true; + + /** + * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ? + */ + this.flattened = false; + + /** + * @property {number} type - The base object type. + */ + this.type = Phaser.POLYGON; + +}; + +Phaser.Polygon.prototype = { + + /** + * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] + * + * @method Phaser.Polygon#toNumberArray + * @param {array} [output] - The array to append the points to. If not specified a new array will be created. + * @return {array} The flattened array. + */ + toNumberArray: function (output) { + + if (output === undefined) { output = []; } + + for (var i = 0; i < this._points.length; i++) + { + if (typeof this._points[i] === 'number') + { + output.push(this._points[i]); + output.push(this._points[i + 1]); + i++; + } + else + { + output.push(this._points[i].x); + output.push(this._points[i].y); + } + } + + return output; + + }, + + /** + * Flattens this Polygon so the points are a sequence of numbers. + * Any Point objects found are removed and replaced with two numbers. + * Also sets the Polygon.flattened property to `true`. + * + * @method Phaser.Polygon#flatten + * @return {Phaser.Polygon} This Polygon object + */ + flatten: function () { + + this._points = this.toNumberArray(); + + this.flattened = true; + + return this; + + }, + + /** + * Creates a copy of the given Polygon. + * This is a deep clone, the resulting copy contains new Phaser.Point objects + * + * @method Phaser.Polygon#clone + * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created. + * @return {Phaser.Polygon} The cloned (`output`) polygon object. + */ + clone: function (output) { + + var points = this._points.slice(); + + if (output === undefined || output === null) + { + output = new Phaser.Polygon(points); + } + else + { + output.setTo(points); + } + + return output; + + }, + + /** + * Checks whether the x and y coordinates are contained within this polygon. + * + * @method Phaser.Polygon#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this polygon, otherwise false. + */ + contains: function (x, y) { + + // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva + + var inside = false; + + if (this.flattened) + { + for (var i = -2, j = this._points.length - 2; (i += 2) < this._points.length; j = i) + { + var ix = this._points[i]; + var iy = this._points[i + 1]; + + var jx = this._points[j]; + var jy = this._points[j + 1]; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + + } + else + { + for (var i = -1, j = this._points.length - 1; ++i < this._points.length; j = i) + { + var ix = this._points[i].x; + var iy = this._points[i].y; + + var jx = this._points[j].x; + var jy = this._points[j].y; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + } + + return inside; + + }, + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` + * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` + * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` + * + * `setTo` may also be called without any arguments to remove all points. + * + * @method Phaser.Polygon#setTo + * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. + * @return {Phaser.Polygon} This Polygon object + */ + setTo: function (points) { + + this.area = 0; + this._points = []; + + if (arguments.length > 0) + { + // If points isn't an array, use arguments as the array + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments); + } + + var y0 = Number.MAX_VALUE; + + // Allows for mixed-type arguments + for (var i = 0, len = points.length; i < len; i++) + { + if (typeof points[i] === 'number') + { + var p = new PIXI.Point(points[i], points[i + 1]); + i++; + } + else if (Array.isArray(points[i])) + { + var p = new PIXI.Point(points[i][0], points[i][1]); + } + else + { + var p = new PIXI.Point(points[i].x, points[i].y); + } + + this._points.push(p); + + // Lowest boundary + if (p.y < y0) + { + y0 = p.y; + } + } + + this.calculateArea(y0); + } + + return this; + + }, + + /** + * Calcuates the area of the Polygon. This is available in the property Polygon.area + * + * @method Phaser.Polygon#calculateArea + * @private + * @param {number} y0 - The lowest boundary + * @return {number} The area of the Polygon. + */ + calculateArea: function (y0) { + + var p1; + var p2; + var avgHeight; + var width; + + for (var i = 0, len = this._points.length; i < len; i++) + { + p1 = this._points[i]; + + if (i === len - 1) + { + p2 = this._points[0]; + } + else + { + p2 = this._points[i + 1]; + } + + avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2; + width = p1.x - p2.x; + this.area += avgHeight * width; + } + + return this.area; + + } + +}; + +Phaser.Polygon.prototype.constructor = Phaser.Polygon; + +/** +* The points of this polygon. +* +* You can modify these with {@link Phaser.Polygon#setTo setTo}. +* +* @name Phaser.Polygon#points +* @property {Phaser.Point[]} points - The array of vertex points. +* @readonly +*/ +Object.defineProperty(Phaser.Polygon.prototype, 'points', { + + get: function() { + return this._points; + } + +}); + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Polygon = Phaser.Polygon; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. +* If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. +* +* @class Phaser.Rectangle +* @constructor +* @param {number} x - The x coordinate of the top-left corner of the Rectangle. +* @param {number} y - The y coordinate of the top-left corner of the Rectangle. +* @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. +*/ +Phaser.Rectangle = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.RECTANGLE; + +}; + +Phaser.Rectangle.prototype = { + + /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method Phaser.Rectangle#offset + * @param {number} dx - Moves the x value of the Rectangle object by this amount. + * @param {number} dy - Moves the y value of the Rectangle object by this amount. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Rectangle#offsetPoint + * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offsetPoint: function (point) { + + return this.offset(point.x, point.y); + + }, + + /** + * Sets the members of Rectangle to the specified values. + * @method Phaser.Rectangle#setTo + * @param {number} x - The x coordinate of the top-left corner of the Rectangle. + * @param {number} y - The y coordinate of the top-left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Scales the width and height of this Rectangle by the given amounts. + * + * @method Phaser.Rectangle#scale + * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. + * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. + * @return {Phaser.Rectangle} This Rectangle object + */ + scale: function (x, y) { + + if (y === undefined) { y = x; } + + this.width *= x; + this.height *= y; + + return this; + + }, + + /** + * Centers this Rectangle so that the center coordinates match the given x and y values. + * + * @method Phaser.Rectangle#centerOn + * @param {number} x - The x coordinate to place the center of the Rectangle at. + * @param {number} y - The y coordinate to place the center of the Rectangle at. + * @return {Phaser.Rectangle} This Rectangle object + */ + centerOn: function (x, y) { + + this.centerX = x; + this.centerY = y; + + return this; + + }, + + /** + * Runs Math.floor() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#floor + */ + floor: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + + }, + + /** + * Runs Math.floor() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#floorAll + */ + floorAll: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.width = Math.floor(this.width); + this.height = Math.floor(this.height); + + }, + + /** + * Runs Math.ceil() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#ceil + */ + ceil: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + + }, + + /** + * Runs Math.ceil() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#ceilAll + */ + ceilAll: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.width = Math.ceil(this.width); + this.height = Math.ceil(this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the left, top, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFromBounds + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFromBounds: function(source) { + + return this.setTo(source.left, source.top, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Rectangle to any given object. + * @method Phaser.Rectangle#copyTo + * @param {any} source - The object to copy to. + * @return {object} This object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method Phaser.Rectangle#inflate + * @param {number} dx - The amount to be added to the left side of the Rectangle. + * @param {number} dy - The amount to be added to the bottom side of the Rectangle. + * @return {Phaser.Rectangle} This Rectangle object. + */ + inflate: function (dx, dy) { + + return Phaser.Rectangle.inflate(this, dx, dy); + + }, + + /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method Phaser.Rectangle#size + * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object. + */ + size: function (output) { + + return Phaser.Rectangle.size(this, output); + + }, + + /** + * Resize the Rectangle by providing a new width and height. + * The x and y positions remain unchanged. + * + * @method Phaser.Rectangle#resize + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method Phaser.Rectangle#clone + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ + clone: function (output) { + + return Phaser.Rectangle.clone(this, output); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method Phaser.Rectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + contains: function (x, y) { + + return Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method Phaser.Rectangle#containsRect + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + containsRect: function (b) { + + return Phaser.Rectangle.containsRect(b, this); + + }, + + /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method Phaser.Rectangle#equals + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + */ + equals: function (b) { + + return Phaser.Rectangle.equals(this, b); + + }, + + /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method Phaser.Rectangle#intersection + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ + intersection: function (b, out) { + + return Phaser.Rectangle.intersection(this, b, out); + + }, + + /** + * Determines whether this Rectangle and another given Rectangle intersect with each other. + * This method checks the x, y, width, and height properties of the two Rectangles. + * + * @method Phaser.Rectangle#intersects + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + */ + intersects: function (b) { + + return Phaser.Rectangle.intersects(this, b); + + }, + + /** + * Determines whether the coordinates given intersects (overlaps) with this Rectangle. + * + * @method Phaser.Rectangle#intersectsRaw + * @param {number} left - The x coordinate of the left of the area. + * @param {number} right - The right coordinate of the area. + * @param {number} top - The y coordinate of the area. + * @param {number} bottom - The bottom coordinate of the area. + * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 + * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + */ + intersectsRaw: function (left, right, top, bottom, tolerance) { + + return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance); + + }, + + /** + * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. + * @method Phaser.Rectangle#union + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ + union: function (b, out) { + + return Phaser.Rectangle.union(this, b, out); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Rectangle. + * + * @method Phaser.Rectangle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = this.randomX; + out.y = this.randomY; + + return out; + + }, + + /** + * Returns a point based on the given position constant, which can be one of: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * This method returns the same values as calling Rectangle.bottomLeft, etc, but those + * calls always create a new Point object, where-as this one allows you to use your own. + * + * @method Phaser.Rectangle#getPoint + * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. + * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the point in its `x` and `y` properties. + */ + getPoint: function (position, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + return out.set(this.x, this.y); + + case Phaser.TOP_CENTER: + return out.set(this.centerX, this.y); + + case Phaser.TOP_RIGHT: + return out.set(this.right, this.y); + + case Phaser.LEFT_CENTER: + return out.set(this.x, this.centerY); + + case Phaser.CENTER: + return out.set(this.centerX, this.centerY); + + case Phaser.RIGHT_CENTER: + return out.set(this.right, this.centerY); + + case Phaser.BOTTOM_LEFT: + return out.set(this.x, this.bottom); + + case Phaser.BOTTOM_CENTER: + return out.set(this.centerX, this.bottom); + + case Phaser.BOTTOM_RIGHT: + return out.set(this.right, this.bottom); + } + + }, + + /** + * Creates or positions four {@link Phaser.Line} lines representing the Rectangle's sides. + * + * @method Phaser.Rectangle#sides + * @param {Phaser.Line} [top] + * @param {Phaser.Line} [right] + * @param {Phaser.Line} [bottom] + * @param {Phaser.Line} [left] + * @return {?Phaser.Line[]} - An array containing four lines (if no arguments were given), or null. + */ + sides: function (top, right, bottom, left) { + + if (!arguments.length) { + top = new Phaser.Line(); + right = new Phaser.Line(); + bottom = new Phaser.Line(); + left = new Phaser.Line(); + } + + var x1 = this.x; + var y1 = this.y; + var x2 = this.right; + var y2 = this.bottom; + + top.setTo(x1, y1, x2, y1); + right.setTo(x2, y1, x2, y2); + bottom.setTo(x1, y2, x2, y2); + left.setTo(x1, y1, x1, y2); + + if (!arguments.length) { + return [top, right, bottom, left]; + } + + return null; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Rectangle#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + + } + +}; + +/** +* @name Phaser.Rectangle#halfWidth +* @property {number} halfWidth - Half of the width of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", { + + get: function () { + return Math.round(this.width / 2); + } + +}); + +/** +* @name Phaser.Rectangle#halfHeight +* @property {number} halfHeight - Half of the height of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", { + + get: function () { + return Math.round(this.height / 2); + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. +* @name Phaser.Rectangle#bottom +* @property {number} bottom - The sum of the y and height properties. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value <= this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + + } + +}); + +/** +* The location of the Rectangles bottom left corner as a Point object. +* @name Phaser.Rectangle#bottomLeft +* @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", { + + get: function () { + return new Phaser.Point(this.x, this.bottom); + }, + + set: function (value) { + this.x = value.x; + this.bottom = value.y; + } + +}); + +/** +* The location of the Rectangles bottom right corner as a Point object. +* @name Phaser.Rectangle#bottomRight +* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", { + + get: function () { + return new Phaser.Point(this.right, this.bottom); + }, + + set: function (value) { + this.right = value.x; + this.bottom = value.y; + } + +}); + +/** +* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. +* @name Phaser.Rectangle#left +* @property {number} left - The x coordinate of the left of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + if (value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + } + +}); + +/** +* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. +* @name Phaser.Rectangle#right +* @property {number} right - The sum of the x and width properties. +*/ +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 = value - this.x; + } + } + +}); + +/** +* The volume of the Rectangle derived from width * height. +* @name Phaser.Rectangle#volume +* @property {number} volume - The volume of the Rectangle derived from width * height. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "volume", { + + get: function () { + return this.width * this.height; + } + +}); + +/** +* The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @name Phaser.Rectangle#perimeter +* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", { + + get: function () { + return (this.width * 2) + (this.height * 2); + } + +}); + +/** +* The x coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerX +* @property {number} centerX - The x coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerX", { + + get: function () { + return this.x + this.halfWidth; + }, + + set: function (value) { + this.x = value - this.halfWidth; + } + +}); + +/** +* The y coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerY +* @property {number} centerY - The y coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerY", { + + get: function () { + return this.y + this.halfHeight; + }, + + set: function (value) { + this.y = value - this.halfHeight; + } + +}); + +/** +* A random value between the left and right values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomX +* @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomX", { + + get: function () { + + return this.x + (Math.random() * this.width); + + } + +}); + +/** +* A random value between the top and bottom values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomY +* @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomY", { + + get: function () { + + return this.y + (Math.random() * this.height); + + } + +}); + +/** +* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. +* However it does affect the height property, whereas changing the y value does not affect the height property. +* @name Phaser.Rectangle#top +* @property {number} top - The y coordinate of the top of the Rectangle. +*/ +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); + } + } + +}); + +/** +* The location of the Rectangles top left corner as a Point object. +* @name Phaser.Rectangle#topLeft +* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. +*/ +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; + } + +}); + +/** +* The location of the Rectangles top right corner as a Point object. +* @name Phaser.Rectangle#topRight +* @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "topRight", { + + get: function () { + return new Phaser.Point(this.x + this.width, this.y); + }, + + set: function (value) { + this.right = value.x; + this.y = value.y; + } + +}); + +/** +* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. +* If set to true then all of the Rectangle properties are set to 0. +* @name Phaser.Rectangle#empty +* @property {boolean} empty - Gets or sets the Rectangles empty state. +*/ +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; + +/** +* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. +* @method Phaser.Rectangle.inflate +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} dx - The amount to be added to the left side of the Rectangle. +* @param {number} dy - The amount to be added to the bottom side of the Rectangle. +* @return {Phaser.Rectangle} This Rectangle object. +*/ +Phaser.Rectangle.inflate = function (a, dx, dy) { + + a.x -= dx; + a.width += 2 * dx; + a.y -= dy; + a.height += 2 * dy; + + return a; + +}; + +/** +* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. +* @method Phaser.Rectangle.inflatePoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. +* @return {Phaser.Rectangle} The Rectangle object. +*/ +Phaser.Rectangle.inflatePoint = function (a, point) { + + return Phaser.Rectangle.inflate(a, point.x, point.y); + +}; + +/** +* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. +* @method Phaser.Rectangle.size +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. +* @return {Phaser.Point} The size of the Rectangle object +*/ +Phaser.Rectangle.size = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(a.width, a.height); + } + else + { + output.setTo(a.width, a.height); + } + + return output; + +}; + +/** +* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. +* @method Phaser.Rectangle.clone +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.clone = function (a, output) { + + if (output === undefined || output === null) + { + 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; + +}; + +/** +* Returns a new Rectangle object with the same values for the left, top, width, and height properties as the original object. +* @method Phaser.Rectangle.createFromBounds +* @param {any} a - An object with `left`, `top`, `width`, and `height` properties. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.createFromBounds = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Rectangle(a.x, a.y, a.width, a.height); + } + + return output.copyFromBounds(a); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by this Rectangle object. +* @method Phaser.Rectangle.contains +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +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); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by the given raw values. +* @method Phaser.Rectangle.containsRaw +* @param {number} rx - The x coordinate of the top left of the area. +* @param {number} ry - The y coordinate of the top left of the area. +* @param {number} rw - The width of the area. +* @param {number} rh - The height of the area. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) { + + return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh)); + +}; + +/** +* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. +* @method Phaser.Rectangle.containsPoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsPoint = function (a, point) { + + return Phaser.Rectangle.contains(a, point.x, point.y); + +}; + +/** +* Determines whether the first Rectangle object is fully contained within the second Rectangle object. +* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. +* @method Phaser.Rectangle.containsRect +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRect = function (a, b) { + + // If the given rect has a larger volume than this one then it can never contain it + if (a.volume > b.volume) + { + return false; + } + + return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom); + +}; + +/** +* Determines whether the two Rectangles are equal. +* This method compares the x, y, width and height properties of each Rectangle. +* @method Phaser.Rectangle.equals +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. +*/ +Phaser.Rectangle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height); + +}; + +/** +* Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. +* @method Phaser.Rectangle.sameDimensions +* @param {Rectangle-like} a - The first Rectangle object. +* @param {Rectangle-like} b - The second Rectangle object. +* @return {boolean} True if the object have equivalent values for the width and height properties. +*/ +Phaser.Rectangle.sameDimensions = function (a, b) { + + return (a.width === b.width && a.height === b.height); + +}; + +/** +* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. +* @method Phaser.Rectangle.intersection +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. +*/ +Phaser.Rectangle.intersection = function (a, b, output) { + + if (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; + +}; + +/** +* Determines whether the two Rectangles intersect with each other. +* This method checks the x, y, width, and height properties of the Rectangles. +* @method Phaser.Rectangle.intersects +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. +*/ +Phaser.Rectangle.intersects = function (a, b) { + + if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) + { + return false; + } + + return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom); + +}; + +/** +* Determines whether the object specified intersects (overlaps) with the given values. +* @method Phaser.Rectangle.intersectsRaw +* @param {number} left - The x coordinate of the left of the area. +* @param {number} right - The right coordinate of the area. +* @param {number} top - The y coordinate of the area. +* @param {number} bottom - The bottom coordinate of the area. +* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 +* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. +*/ +Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) { + + if (tolerance === undefined) { tolerance = 0; } + + return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); + +}; + +/** +* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. +* @method Phaser.Rectangle.union +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. +*/ +Phaser.Rectangle.union = function (a, b, output) { + + if (output === undefined) + { + output = new Phaser.Rectangle(); + } + + return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top)); + +}; + +/** +* Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. +* +* @method Phaser.Rectangle#aabb +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. +* @return {Phaser.Rectangle} The new Rectangle object. +* @static +*/ +Phaser.Rectangle.aabb = function(points, out) { + + if (out === undefined) { + out = new Phaser.Rectangle(); + } + + var xMax = Number.NEGATIVE_INFINITY, + xMin = Number.POSITIVE_INFINITY, + yMax = Number.NEGATIVE_INFINITY, + yMin = Number.POSITIVE_INFINITY; + + points.forEach(function(point) { + if (point.x > xMax) { + xMax = point.x; + } + if (point.x < xMin) { + xMin = point.x; + } + + if (point.y > yMax) { + yMax = point.y; + } + if (point.y < yMin) { + yMin = point.y; + } + }); + + out.setTo(xMin, yMin, xMax - xMin, yMax - yMin); + + return out; +}; + +// Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Rectangle = Phaser.Rectangle; +PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0); + +/** +* @author Mat Groves http://matgroves.com/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Rounded Rectangle object is an area defined by its position and has nice rounded corners, +* as indicated by its top-left corner point (x, y) and by its width and its height. +* +* @class Phaser.RoundedRectangle +* @constructor +* @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle. +* @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle. +* @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value. +* @param {number} [radius=20] - Controls the radius of the rounded corners. +*/ +Phaser.RoundedRectangle = function(x, y, width, height, radius) +{ + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + if (radius === undefined) { radius = 20; } + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} radius - The radius of the rounded corners. + */ + this.radius = radius || 20; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROUNDEDRECTANGLE; +}; + +Phaser.RoundedRectangle.prototype = { + + /** + * Returns a new RoundedRectangle object with the same values for the x, y, width, height and + * radius properties as this RoundedRectangle object. + * + * @method Phaser.RoundedRectangle#clone + * @return {Phaser.RoundedRectangle} + */ + clone: function () { + + return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. + * + * @method Phaser.RoundedRectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. + */ + 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; + + } + +}; + +Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle; + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.RoundedRectangle = Phaser.RoundedRectangle; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. +* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y +* +* @class Phaser.Camera +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera +* @param {number} x - Position of the camera on the X axis +* @param {number} y - Position of the camera on the Y axis +* @param {number} width - The width of the view rectangle +* @param {number} height - The height of the view rectangle +*/ +Phaser.Camera = function (game, id, x, y, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + */ + this.world = game.world; + + /** + * @property {number} id - Reserved for future multiple camera set-ups. + * @default + */ + this.id = 0; + + /** + * Camera view. + * The view into the world we wish to render (by default the game dimensions). + * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. + * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. + * @property {Phaser.Rectangle} view + */ + this.view = new Phaser.Rectangle(x, y, width, height); + + /** + * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. + * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound + * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. + * + * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. + */ + this.bounds = new Phaser.Rectangle(x, y, width, height); + + /** + * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move. + */ + this.deadzone = null; + + /** + * @property {boolean} visible - Whether this camera is visible or not. + * @default + */ + this.visible = true; + + /** + * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. + * @default + */ + this.roundPx = true; + + /** + * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. + */ + this.atLimit = { x: false, y: false }; + + /** + * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. + * @default + */ + this.target = null; + + /** + * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot. + */ + this.displayObject = null; + + /** + * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot. + */ + this.scale = null; + + /** + * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. + * @readonly + */ + this.totalInView = 0; + + /** + * The linear interpolation value to use when following a target. + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * @property {Phaser.Point} lerp + * @default + */ + this.lerp = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes. + */ + this.onShakeComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes. + */ + this.onFlashComplete = new Phaser.Signal(); + + /** + * This signal is dispatched when the camera fade effect completes. + * When the fade effect completes you will be left with the screen black (or whatever + * color you faded to). In order to reset this call `Camera.resetFX`. This is called + * automatically when you change State. + * @property {Phaser.Signal} onFadeComplete + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * The Graphics object used to handle camera fx such as fade and flash. + * @property {Phaser.Graphics} fx + * @protected + */ + this.fx = null; + + /** + * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position. + * @private + */ + this._targetPosition = new Phaser.Point(); + + /** + * @property {number} edge - Edge property. + * @private + * @default + */ + this._edge = 0; + + /** + * @property {Phaser.Point} position - Current position of the camera in world. + * @private + * @default + */ + this._position = new Phaser.Point(); + + /** + * @property {Object} _shake - The shake effect container. + * @private + */ + this._shake = { + intensity: 0, + duration: 0, + horizontal: false, + vertical: false, + shakeBounds: true, + x: 0, + y: 0 + }; + + /** + * @property {number} _fxDuration - FX duration timer. + * @private + */ + this._fxDuration = 0; + + /** + * @property {number} _fxType - The FX type running. + * @private + */ + this._fxType = 0; + + /** + * @property {Phaser.Rectangle} + * @private + */ + this._fixedView = new Phaser.Rectangle(); + +}; + +/** +* A follow style that uses no deadzone. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_LOCKON = 0; + +/** +* A follow style that uses a tall, narrow deadzone (0.33 x 0.125) with a center slightly above the view center. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_PLATFORMER = 1; + +/** +* A follow style that uses a square deadzone (0.25 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN = 2; + +/** +* A follow style that uses a small square deadzone (0.125 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_BOTH = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_HORIZONTAL = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_VERTICAL = 6; + +/** +* @constant +* @type {boolean} +*/ +Phaser.Camera.ENABLE_FX = true; + +Phaser.Camera.prototype = { + + /** + * Called automatically by Phaser.World. + * + * @method Phaser.Camera#boot + * @private + */ + boot: function () { + + this.displayObject = this.game.world; + + this.scale = this.game.world.scale; + + this.game.camera = this; + + if (Phaser.Graphics && Phaser.Camera.ENABLE_FX) + { + this.fx = new Phaser.Graphics(this.game); + + this.game.stage.addChild(this.fx); + } + + }, + + /** + * Camera preUpdate. Sets the total view counter to zero. + * + * @method Phaser.Camera#preUpdate + */ + preUpdate: function () { + + this.totalInView = 0; + + }, + + /** + * Tell the camera which sprite to follow. + * + * You can set the follow type and a linear interpolation value. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. + * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. + * + * @method Phaser.Camera#follow + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything. + * @param {number} [style] - Leverage one of the existing {@link deadzone} presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + */ + follow: function (target, style, lerpX, lerpY) { + + if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; } + if (lerpX === undefined) { lerpX = 1; } + if (lerpY === undefined) { lerpY = 1; } + + this.target = target; + this.lerp.set(lerpX, lerpY); + + var helper; + + switch (style) { + + case Phaser.Camera.FOLLOW_PLATFORMER: + var w = this.width / 8; + var h = this.height / 3; + this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN: + helper = Math.max(this.width, this.height) / 4; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT: + helper = Math.max(this.width, this.height) / 8; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_LOCKON: + this.deadzone = null; + break; + + default: + this.deadzone = null; + break; + } + + }, + + /** + * Sets the Camera follow target to null, stopping it from following an object if it's doing so. + * + * @method Phaser.Camera#unfollow + */ + unfollow: function () { + + this.target = null; + + }, + + /** + * Move the camera focus on a display object instantly. + * @method Phaser.Camera#focusOn + * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. + */ + focusOn: function (displayObject) { + + this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight)); + + }, + + /** + * Move the camera focus on a location instantly. + * @method Phaser.Camera#focusOnXY + * @param {number} x - X position. + * @param {number} y - Y position. + */ + focusOnXY: function (x, y) { + + this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight)); + + }, + + /** + * This creates a camera shake effect. It works by applying a random amount of additional + * spacing on the x and y axis each frame. You can control the intensity and duration + * of the effect, and if it should effect both axis or just one. + * + * When the shake effect ends the signal Camera.onShakeComplete is dispatched. + * + * @method Phaser.Camera#shake + * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. + * @param {number} [duration=500] - The duration of the shake effect in milliseconds. + * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL. + * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?). + * @return {boolean} True if the shake effect was started, otherwise false. + */ + shake: function (intensity, duration, force, direction, shakeBounds) { + + if (intensity === undefined) { intensity = 0.05; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = true; } + if (direction === undefined) { direction = Phaser.Camera.SHAKE_BOTH; } + if (shakeBounds === undefined) { shakeBounds = true; } + + if (!force && this._shake.duration > 0) + { + // Can't reset an already running shake + return false; + } + + this._shake.intensity = intensity; + this._shake.duration = duration; + this._shake.shakeBounds = shakeBounds; + + this._shake.x = 0; + this._shake.y = 0; + + this._shake.horizontal = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_HORIZONTAL); + this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL); + + return true; + + }, + + /** + * This creates a camera flash effect. It works by filling the game with the solid fill + * color specified, and then fading it away to alpha 0 over the duration given. + * + * You can use this for things such as hit feedback effects. + * + * When the effect ends the signal Camera.onFlashComplete is dispatched. + * + * @method Phaser.Camera#flash + * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the flash effect in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the flash effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + flash: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0xffffff; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 1; + + this._fxDuration = duration; + this._fxType = 0; + + return true; + + }, + + /** + * This creates a camera fade effect. It works by filling the game with the + * color specified, over the duration given, ending with a solid fill. + * + * You can use this for things such as transitioning to a new scene. + * + * The game will be left 'filled' at the end of this effect, likely obscuring + * everything. In order to reset it you can call `Camera.resetFX` and it will clear the + * fade. Or you can call `Camera.flash` with the same color as the fade, and it will + * reverse the process, bringing the game back into view again. + * + * When the effect ends the signal Camera.onFadeComplete is dispatched. + * + * @method Phaser.Camera#fade + * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the fade in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the fade effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + fade: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0x000000; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 0; + + this._fxDuration = duration; + this._fxType = 1; + + return true; + + }, + + /** + * The camera update loop. This is called automatically by the core game loop. + * + * @method Phaser.Camera#update + * @protected + */ + update: function () { + + if (this._fxDuration > 0) + { + this.updateFX(); + } + + if (this._shake.duration > 0) + { + this.updateShake(); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + this._shake.x = Math.floor(this._shake.x); + this._shake.y = Math.floor(this._shake.y); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the camera flash and fade effects. + * + * @method Phaser.Camera#updateFX + * @private + */ + updateFX: function () { + + if (this._fxType === 0) + { + // flash + this.fx.alpha -= this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha <= 0) + { + this._fxDuration = 0; + this.fx.alpha = 0; + this.onFlashComplete.dispatch(); + } + } + else + { + // fade + this.fx.alpha += this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha >= 1) + { + this._fxDuration = 0; + this.fx.alpha = 1; + this.onFadeComplete.dispatch(); + } + } + + }, + + /** + * Update the camera shake effect. + * + * @method Phaser.Camera#updateShake + * @private + */ + updateShake: function () { + + this._shake.duration -= this.game.time.elapsedMS; + + if (this._shake.duration <= 0) + { + this.onShakeComplete.dispatch(); + this._shake.x = 0; + this._shake.y = 0; + } + else + { + if (this._shake.horizontal) + { + this._shake.x = this.game.rnd.frac() * this._shake.intensity * this.view.width * 2 - this._shake.intensity * this.view.width; + } + + if (this._shake.vertical) + { + this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height; + } + } + + }, + + /** + * Internal method that handles tracking a sprite. + * + * @method Phaser.Camera#updateTarget + * @private + */ + updateTarget: function () { + + this._targetPosition.x = this.view.x + this.target.worldPosition.x; + this._targetPosition.y = this.view.y + this.target.worldPosition.y; + + if (this.deadzone) + { + this._edge = this._targetPosition.x - this.view.x; + + if (this._edge < this.deadzone.left) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.left, this.lerp.x); + } + else if (this._edge > this.deadzone.right) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.right, this.lerp.x); + } + + this._edge = this._targetPosition.y - this.view.y; + + if (this._edge < this.deadzone.top) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.top, this.lerp.y); + } + else if (this._edge > this.deadzone.bottom) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.bottom, this.lerp.y); + } + } + else + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.view.halfWidth, this.lerp.x); + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.view.halfHeight, this.lerp.y); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the Camera bounds to match the game world. + * + * @method Phaser.Camera#setBoundsToWorld + */ + setBoundsToWorld: function () { + + if (this.bounds) + { + this.bounds.copyFrom(this.game.world.bounds); + } + + }, + + /** + * Method called to ensure the camera doesn't venture outside of the game world. + * Called automatically by Camera.update. + * + * @method Phaser.Camera#checkBounds + * @protected + */ + checkBounds: function () { + + this.atLimit.x = false; + this.atLimit.y = false; + + var vx = this.view.x + this._shake.x; + var vw = this.view.right + this._shake.x; + var vy = this.view.y + this._shake.y; + var vh = this.view.bottom + this._shake.y; + + // Make sure we didn't go outside the cameras bounds + if (vx <= this.bounds.x * this.scale.x) + { + this.atLimit.x = true; + this.view.x = this.bounds.x * this.scale.x; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + else if (vw >= this.bounds.right * this.scale.x) + { + this.atLimit.x = true; + this.view.x = (this.bounds.right * this.scale.x) - this.width; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + + if (vy <= this.bounds.top * this.scale.y) + { + this.atLimit.y = true; + this.view.y = this.bounds.top * this.scale.y; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + else if (vh >= this.bounds.bottom * this.scale.y) + { + this.atLimit.y = true; + this.view.y = (this.bounds.bottom * this.scale.y) - this.height; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + + }, + + /** + * A helper function to set both the X and Y properties of the camera at once + * without having to use game.camera.x and game.camera.y. + * + * @method Phaser.Camera#setPosition + * @param {number} x - X position. + * @param {number} y - Y position. + */ + setPosition: function (x, y) { + + this.view.x = x; + this.view.y = y; + + if (this.bounds) + { + this.checkBounds(); + } + + }, + + /** + * Sets the size of the view rectangle given the width and height in parameters. + * + * @method Phaser.Camera#setSize + * @param {number} width - The desired width. + * @param {number} height - The desired height. + */ + setSize: function (width, height) { + + this.view.width = width; + this.view.height = height; + + }, + + /** + * Resets the camera back to 0,0 and un-follows any object it may have been tracking. + * Also immediately resets any camera effects that may have been running such as + * shake, flash or fade. + * + * @method Phaser.Camera#reset + */ + reset: function () { + + this.target = null; + + this.view.x = 0; + this.view.y = 0; + + this._shake.duration = 0; + this._shake.x = 0; + this._shake.y = 0; + + this.resetFX(); + + }, + + /** + * Resets any active FX, such as a fade or flash and immediately clears it. + * Useful to calling after a fade in order to remove the fade from the Stage. + * + * @method Phaser.Camera#resetFX + */ + resetFX: function () { + + if (this.fx) + { + this.fx.clear(); + this.fx.alpha = 0; + } + + this._fxDuration = 0; + + } + +}; + +Phaser.Camera.prototype.constructor = Phaser.Camera; + +/** +* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#x +* @property {number} x - Gets or sets the cameras x position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "x", { + + get: function () { + + return this.view.x; + + }, + + set: function (value) { + + this.view.x = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#y +* @property {number} y - Gets or sets the cameras y position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "y", { + + get: function () { + + return this.view.y; + + }, + + set: function (value) { + + this.view.y = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras position. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#position +* @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object. +*/ +Object.defineProperty(Phaser.Camera.prototype, "position", { + + get: function () { + + this._position.set(this.view.x, this.view.y); + + return this._position; + + }, + + set: function (value) { + + if (typeof value.x !== "undefined") { this.view.x = value.x; } + if (typeof value.y !== "undefined") { this.view.y = value.y; } + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras width. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#width +* @property {number} width - Gets or sets the cameras width. +*/ +Object.defineProperty(Phaser.Camera.prototype, "width", { + + get: function () { + + return this.view.width; + + }, + + set: function (value) { + + this.view.width = value; + + } + +}); + +/** +* The Cameras height. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#height +* @property {number} height - Gets or sets the cameras height. +*/ +Object.defineProperty(Phaser.Camera.prototype, "height", { + + get: function () { + + return this.view.height; + + }, + + set: function (value) { + + this.view.height = value; + + } + +}); + + +/** +* The Cameras shake intensity. +* @name Phaser.Camera#shakeIntensity +* @property {number} shakeIntensity - Gets or sets the cameras shake intensity. +*/ +Object.defineProperty(Phaser.Camera.prototype, "shakeIntensity", { + + get: function () { + + return this._shake.intensity; + + }, + + set: function (value) { + + this._shake.intensity = value; + + } + +}); + + +/** + * Immobile {@link #view} rectangle. Its top-left is always (0, 0). You can use this align fixedToCamera objects. + * @name Phaser.Camera#fixedView + * @property {Phaser.Rectangle} fixedView + * @readonly + */ +Object.defineProperty(Phaser.Camera.prototype, "fixedView", { + + get: function () { + + this._fixedView.setTo(0, 0, this.view.width, this.view.height); + + return this._fixedView; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base State class which can be extended if you are creating your own game. +* It provides quick access to common functions such as the camera, cache, input, match, sound and more. +* +* #### Callbacks +* +* | start | preload | loaded | paused | stop | +* |-------|-------------|------------|--------------|----------| +* | init | | | | | +* | | preload | create | paused | | +* | | loadUpdate* | update* | pauseUpdate* | | +* | | | preRender* | | | +* | | loadRender* | render* | render* | | +* | | | | resumed | | +* | | | | | shutdown | +* +* Update and render calls (*) are repeated. +* +* If your State has a constructor, it will be invoked exactly once, during {@link {@link Phaser.StateManager#add}. +* +* @class Phaser.State +* @constructor +*/ +Phaser.State = function () { + + /** + * @property {Phaser.Game} game - This is a reference to the currently running Game. + */ + this.game = null; + + /** + * @property {string} key - The string based identifier given to the State when added into the State Manager. + */ + this.key = ''; + + /** + * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects. + */ + this.make = null; + + /** + * @property {Phaser.Camera} camera - A handy reference to World.camera. + */ + this.camera = null; + + /** + * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - A reference to the Input Manager. + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions. + */ + this.math = null; + + /** + * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. + */ + this.sound = null; + + /** + * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays. + */ + this.scale = null; + + /** + * @property {Phaser.Stage} stage - A reference to the Stage. + */ + this.stage = null; + + /** + * @property {Phaser.StateManager} stage - A reference to the State Manager, which controls state changes. + */ + this.state = null; + + /** + * @property {Phaser.Time} time - A reference to the game clock and timed events system. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - A reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. + */ + this.world = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. + */ + this.particles = null; + + /** + * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser. + */ + this.physics = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator. + */ + this.rnd = null; + +}; + +Phaser.State.prototype = { + + /** + * init is the very first function called when your State starts up. It's called before preload, create or anything else. + * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables + * or objects before the preloading starts. + * + * @method Phaser.State#init + * @param {...any} args - Any extra arguments passed to {@link Phaser.StateManager#start} or {@link Phaser.StateManager#restart}. + */ + init: function () { + }, + + /** + * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) + * You shouldn't create any objects in this method that require assets that you're also loading in this method, as + * they won't yet be available. + * + * @method Phaser.State#preload + * @param {Phaser.Game} game + */ + preload: function () { + }, + + /** + * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * + * @method Phaser.State#loadUpdate + * @param {Phaser.Game} game + */ + loadUpdate: function () { + }, + + /** + * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. + * + * @method Phaser.State#loadRender + * @param {Phaser.Game} game + */ + loadRender: function () { + }, + + /** + * create is called once preload has completed, this includes the loading of any assets from the Loader. + * If you don't have a preload method then create is the first method called in your State. + * + * @method Phaser.State#create + * @param {Phaser.Game} game + */ + create: function () { + }, + + /** + * The update method is left empty for your own use. + * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. + * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. + * + * @method Phaser.State#update + * @param {Phaser.Game} game + */ + update: function () { + }, + + /** + * The preRender method is called after all Game Objects have been updated, but before any rendering takes place. + * + * @method Phaser.State#preRender + * @param {Phaser.Game} game + * @param {number} elapsedTime + */ + preRender: function () { + }, + + /** + * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. + * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any + * final post-processing style effects here. Note that this happens before plugins postRender takes place. + * + * @method Phaser.State#render + * @param {Phaser.Game} game + */ + render: function () { + }, + + /** + * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. + * + * @method Phaser.State#resize + * @param {number} width + * @param {number} height + */ + resize: function () { + }, + + /** + * This method will be called if the core game loop is paused. + * + * @method Phaser.State#paused + * @param {Phaser.Game} game + */ + paused: function () { + }, + + /** + * This method will be called when the core game loop resumes from a paused state. + * + * @method Phaser.State#resumed + * @param {Phaser.Game} game + */ + resumed: function () { + }, + + /** + * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. + * + * @method Phaser.State#pauseUpdate + * @param {Phaser.Game} game + */ + pauseUpdate: function () { + }, + + /** + * This method will be called when the State is shutdown (i.e. you switch to another state from this one). + * + * @method Phaser.State#shutdown + * @param {Phaser.Game} game + */ + shutdown: function () { + } + +}; + +Phaser.State.prototype.constructor = Phaser.State; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The State Manager is responsible for loading, setting up and switching game states. +* +* @class Phaser.StateManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. +*/ +Phaser.StateManager = function (game, pendingState) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {object} states - The object containing Phaser.States. + */ + this.states = {}; + + /** + * @property {Phaser.State} _pendingState - The state to be switched to in the next frame. + * @private + */ + this._pendingState = null; + + if (typeof pendingState !== 'undefined' && pendingState !== null) + { + this._pendingState = pendingState; + } + + /** + * @property {boolean} _clearWorld - Clear the world when we switch state? + * @private + */ + this._clearWorld = false; + + /** + * @property {boolean} _clearCache - Clear the cache when we switch state? + * @private + */ + this._clearCache = false; + + /** + * @property {boolean} _created - Flag that sets if the State has been created or not. + * @private + */ + this._created = false; + + /** + * @property {any[]} _args - Temporary container when you pass vars from one State to another. + * @private + */ + this._args = []; + + /** + * @property {string} current - The current active State object. + * @default + */ + this.current = ''; + + /** + * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. + * + * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start + * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states + * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. + * + * The callback you specify is sent two parameters: the string based key of the new state, + * and the second parameter is the string based key of the old / previous state. + * + * @property {Phaser.Signal} onStateChange + */ + this.onStateChange = new Phaser.Signal(); + + /** + * @property {function} onInitCallback - This is called when the state is set as the active state. + * @default + */ + this.onInitCallback = null; + + /** + * @property {function} onPreloadCallback - This is called when the state starts to load assets. + * @default + */ + this.onPreloadCallback = null; + + /** + * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins. + * @default + */ + this.onCreateCallback = null; + + /** + * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). + * @default + */ + this.onUpdateCallback = null; + + /** + * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). + * @default + */ + this.onRenderCallback = null; + + /** + * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. + * @default + */ + this.onResizeCallback = null; + + /** + * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. + * @default + */ + this.onPreRenderCallback = null; + + /** + * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase. + * @default + */ + this.onLoadUpdateCallback = null; + + /** + * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase. + * @default + */ + this.onLoadRenderCallback = null; + + /** + * @property {function} onPausedCallback - This is called when the game is paused. + * @default + */ + this.onPausedCallback = null; + + /** + * @property {function} onResumedCallback - This is called when the game is resumed from a paused state. + * @default + */ + this.onResumedCallback = null; + + /** + * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused. + * @default + */ + this.onPauseUpdateCallback = null; + + /** + * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state). + * @default + */ + this.onShutDownCallback = null; + +}; + +Phaser.StateManager.prototype = { + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * @method Phaser.StateManager#boot + * @private + */ + boot: function () { + + this.game.onPause.add(this.pause, this); + this.game.onResume.add(this.resume, this); + + if (this._pendingState !== null && typeof this._pendingState !== 'string') + { + this.add('default', this._pendingState, true); + } + + }, + + /** + * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. + * + * The State can be any of + * + * - a plain JavaScript object containing at least one required callback (see {@link #checkState}) + * - an instance of {@link Phaser.State} + * - an instance of a class extending Phaser.State + * - a constructor function (class) + * + * If a function is given a new state object will be created by calling it, passing the current {@link Phaser.Game game} as the first argument. + * + * @method Phaser.StateManager#add + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + * @param {Phaser.State|object|function} state - The state you want to switch to. + * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it. + */ + add: function (key, state, autoStart) { + + if (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; + + }, + + /** + * Delete the given state. + * @method Phaser.StateManager#remove + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + */ + 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.onPreRenderCallback = null; + this.onRenderCallback = null; + this.onResizeCallback = null; + this.onPausedCallback = null; + this.onResumedCallback = null; + this.onPauseUpdateCallback = null; + } + + delete this.states[key]; + + }, + + /** + * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. + * + * @method Phaser.StateManager#start + * @param {string} key - The key of the state you want to start. + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one). + */ + start: function (key, clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + if (this.checkState(key)) + { + // Place the state in the queue. It will be started the next time the game loop begins. + this._pendingState = key; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 3) + { + this._args = Array.prototype.splice.call(arguments, 3); + } + } + + }, + + /** + * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. + * + * @method Phaser.StateManager#restart + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one. + */ + restart: function (clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + // Place the state in the queue. It will be started the next time the game loop starts. + this._pendingState = this.current; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 2) + { + this._args = Array.prototype.slice.call(arguments, 2); + } + + }, + + /** + * Used by onInit and onShutdown when those functions don't exist on the state + * @method Phaser.StateManager#dummy + * @private + */ + dummy: function () { + }, + + /** + * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. + * + * @method Phaser.StateManager#preUpdate + */ + preUpdate: function () { + + if (this._pendingState && this.game.isBooted) + { + var previousStateKey = this.current; + + // Already got a state running? + this.clearCurrentState(); + + this.setCurrentState(this._pendingState); + + this.onStateChange.dispatch(this.current, previousStateKey); + + if (this.current !== this._pendingState) + { + return; + } + else + { + this._pendingState = null; + } + + // If StateManager.start has been called from the init of a State that ALSO has a preload, then + // onPreloadCallback will be set, but must be ignored + if (this.onPreloadCallback) + { + this.game.load.reset(true); + this.onPreloadCallback.call(this.callbackContext, this.game); + + // Is the loader empty? + if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0) + { + this.loadComplete(); + } + else + { + // Start the loader going as we have something in the queue + this.game.load.start(); + } + } + else + { + // No init? Then there was nothing to load either + this.loadComplete(); + } + } + + }, + + /** + * This method clears the current State, calling its shutdown callback. The process also removes any active tweens, + * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. + * + * @method Phaser.StateManager#clearCurrentState + */ + clearCurrentState: function () { + + if (this.current) + { + if (this.onShutDownCallback) + { + 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(); + + this.game.scale.reset(this._clearWorld); + + if (this.game.debug) + { + this.game.debug.reset(); + } + + if (this._clearWorld) + { + this.game.world.shutdown(); + + if (this._clearCache) + { + this.game.cache.destroy(); + } + } + } + + }, + + /** + * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. + * + * @method Phaser.StateManager#checkState + * @param {string} key - The key of the state you want to check. + * @return {boolean} true if the State has the required functions, otherwise false. + */ + checkState: function (key) { + + var state = this.states[key]; + + if (state) + { + if (state.preload || state.create || state.update || state.render) + { + return true; + } + else + { + console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"); + return false; + } + } + else + { + console.warn("Phaser.StateManager - No state found with the key: " + key); + return false; + } + + }, + + /** + * Links game properties to the State given by the key. + * + * @method Phaser.StateManager#link + * @param {string} key - State key. + * @protected + */ + link: function (key) { + + var state = this.states[key]; + + state.game = this.game; + state.add = this.game.add; + state.make = this.game.make; + state.camera = this.game.camera; + state.cache = this.game.cache; + state.input = this.game.input; + state.load = this.game.load; + state.math = this.game.math; + state.sound = this.game.sound; + state.scale = this.game.scale; + state.state = this; + state.stage = this.game.stage; + state.time = this.game.time; + state.tweens = this.game.tweens; + state.world = this.game.world; + state.particles = this.game.particles; + state.rnd = this.game.rnd; + state.physics = this.game.physics; + state.key = key; + + }, + + /** + * Nulls all State level Phaser properties, including a reference to Game. + * + * @method Phaser.StateManager#unlink + * @param {string} key - State key. + * @protected + */ + unlink: function (key) { + + var state = this.states[key]; + + if (state) + { + state.game = null; + state.add = null; + state.make = null; + state.camera = null; + state.cache = null; + state.input = null; + state.load = null; + state.math = null; + state.sound = null; + state.scale = null; + state.state = null; + state.stage = null; + state.time = null; + state.tweens = null; + state.world = null; + state.particles = null; + state.rnd = null; + state.physics = null; + } + + }, + + /** + * Sets the current State. Should not be called directly (use StateManager.start) + * + * @method Phaser.StateManager#setCurrentState + * @param {string} key - State key. + * @private + */ + setCurrentState: function (key) { + + var state = this.states[key]; + + this.callbackContext = state; + + this.link(key); + + // Used when the state is set as being the current active state + this.onInitCallback = state['init'] || this.dummy; + + this.onPreloadCallback = state['preload'] || null; + this.onLoadRenderCallback = state['loadRender'] || null; + this.onLoadUpdateCallback = state['loadUpdate'] || null; + this.onCreateCallback = state['create'] || null; + this.onUpdateCallback = state['update'] || null; + this.onPreRenderCallback = state['preRender'] || null; + this.onRenderCallback = state['render'] || null; + this.onResizeCallback = state['resize'] || null; + this.onPausedCallback = state['paused'] || null; + this.onResumedCallback = state['resumed'] || null; + this.onPauseUpdateCallback = state['pauseUpdate'] || null; + + // Used when the state is no longer the current active state + this.onShutDownCallback = state['shutdown'] || this.dummy; + + // Reset the physics system, but not on the first state start + if (this.current !== '') + { + this.game.physics.reset(); + } + + this.current = key; + this._created = false; + + // At this point key and pendingState should equal each other + this.onInitCallback.apply(this.callbackContext, this._args); + + // If they no longer do then the init callback hit StateManager.start + if (key === this._pendingState) + { + this._args = []; + } + + this.game._kickstart = true; + + }, + + /** + * Gets the current State. + * + * @method Phaser.StateManager#getCurrentState + * @return {Phaser.State} + * @public + */ + getCurrentState: function() { + return this.states[this.current]; + }, + + /** + * @method Phaser.StateManager#loadComplete + * @protected + */ + loadComplete: function () { + + // Make sure to do load-update one last time before state is set to _created + if (this._created === false && this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + + if (this._created === false && this.onCreateCallback) + { + this._created = true; + this.onCreateCallback.call(this.callbackContext, this.game); + } + else + { + this._created = true; + } + + }, + + /** + * @method Phaser.StateManager#pause + * @protected + */ + pause: function () { + + if (this._created && this.onPausedCallback) + { + this.onPausedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#resume + * @protected + */ + resume: function () { + + if (this._created && this.onResumedCallback) + { + this.onResumedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#update + * @protected + */ + update: function () { + + if (this._created) + { + if (this.onUpdateCallback) + { + this.onUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#pauseUpdate + * @protected + */ + pauseUpdate: function () { + + if (this._created) + { + if (this.onPauseUpdateCallback) + { + this.onPauseUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#preRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + preRender: function (elapsedTime) { + + if (this._created && this.onPreRenderCallback) + { + this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime); + } + + }, + + /** + * @method Phaser.StateManager#resize + * @protected + */ + resize: function (width, height) { + + if (this.onResizeCallback) + { + this.onResizeCallback.call(this.callbackContext, width, height); + } + + }, + + /** + * @method Phaser.StateManager#render + * @protected + */ + render: function () { + + if (this._created) + { + if (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); + this.game.context.restore(); + } + else + { + this.onRenderCallback.call(this.callbackContext, this.game); + } + } + } + else + { + if (this.onLoadRenderCallback) + { + this.onLoadRenderCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. + * You don't recover from this without rebuilding the Phaser instance again. + * @method Phaser.StateManager#destroy + */ + destroy: function () { + + this._clearWorld = true; + this._clearCache = true; + + this.clearCurrentState(); + + 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; + this.current = ''; + + } + +}; + +Phaser.StateManager.prototype.constructor = Phaser.StateManager; + +/** +* @name Phaser.StateManager#created +* @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default). +* @readOnly +*/ +Object.defineProperty(Phaser.StateManager.prototype, "created", { + + get: function () { + + return this._created; + + } + +}); + +/** +* "It's like nailing jelly to a kitten" - Gary Penn +*/ + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Signals are what Phaser uses to handle events and event dispatching. +* You can listen for a Signal by binding a callback / function to it. +* This is done by using either `Signal.add` or `Signal.addOnce`. +* +* For example you can listen for a touch or click event from the Input Manager +* by using its `onDown` Signal: +* +* `game.input.onDown.add(function() { ... });` +* +* Rather than inline your function, you can pass a reference: +* +* `game.input.onDown.add(clicked, this);` +* `function clicked () { ... }` +* +* In this case the second argument (`this`) is the context in which your function should be called. +* +* Now every time the InputManager dispatches the `onDown` signal (or event), your function +* will be called. +* +* Multiple callbacks can be bound to the same signal. +* They're ordered first by their `priority` arguments and then by the order in which they were added. +* If a callback calls {@link #halt} or returns `false`, any remaining callbacks are skipped. +* +* Very often a Signal will send arguments to your function. +* This is specific to the Signal itself. +* If you're unsure then check the documentation, or failing that simply do: +* +* `Signal.add(function() { console.log(arguments); })` +* +* and it will log all of the arguments your function received from the Signal. +* +* Sprites have lots of default signals you can listen to in their Events class, such as: +* +* `sprite.events.onKilled` +* +* Which is called automatically whenever the Sprite is killed. +* There are lots of other events, see the Events component for a list. +* +* As well as listening to pre-defined Signals you can also create your own: +* +* `var mySignal = new Phaser.Signal();` +* +* This creates a new Signal. You can bind a callback to it: +* +* `mySignal.add(myCallback, this);` +* +* and then finally when ready you can dispatch the Signal: +* +* `mySignal.dispatch(your arguments);` +* +* And your callback will be invoked. See the dispatch method for more details. +* +* @class Phaser.Signal +* @constructor +*/ +Phaser.Signal = function () {}; + +Phaser.Signal.prototype = { + + /** + * @property {?Array.} _bindings - Internal variable. + * @private + */ + _bindings: null, + + /** + * @property {any} _prevParams - Internal variable. + * @private + */ + _prevParams: null, + + /** + * Memorize the previously dispatched event? + * + * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}. + * Use {@link #forget} to clear any currently memorized event. + * + * @property {boolean} memorize + */ + memorize: false, + + /** + * @property {boolean} _shouldPropagate + * @private + */ + _shouldPropagate: true, + + /** + * Is the Signal active? Only active signals will broadcast dispatched events. + * + * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}. + * + * @property {boolean} active + * @default + */ + active: true, + + /** + * @property {function} _boundDispatch - The bound dispatch function, if any. + * @private + */ + _boundDispatch: false, + + /** + * @method Phaser.Signal#validateListener + * @param {function} listener - Signal handler function. + * @param {string} fnName - Function name. + * @private + */ + validateListener: function (listener, fnName) { + + if (typeof listener !== 'function') + { + throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); + } + + }, + + /** + * @method Phaser.Signal#_registerListener + * @private + * @param {function} listener - Signal handler function. + * @param {boolean} isOnce - Should the listener only be called once? + * @param {object} [listenerContext] - The context under which the listener is invoked. + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + _registerListener: function (listener, isOnce, listenerContext, priority, args) { + + var prevIndex = this._indexOfListener(listener, listenerContext); + var binding; + + if (prevIndex !== -1) + { + binding = this._bindings[prevIndex]; + + if (binding.isOnce() !== isOnce) + { + throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); + } + } + else + { + binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args); + this._addBinding(binding); + } + + if (this.memorize && this._prevParams) + { + binding.execute(this._prevParams); + } + + return binding; + + }, + + /** + * @method Phaser.Signal#_addBinding + * @private + * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. + */ + _addBinding: function (binding) { + + if (!this._bindings) + { + this._bindings = []; + } + + // Simplified insertion sort + var n = this._bindings.length; + + do { + n--; + } + while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); + + this._bindings.splice(n + 1, 0, binding); + + }, + + /** + * @method Phaser.Signal#_indexOfListener + * @private + * @param {function} listener - Signal handler function. + * @param {object} [context=null] - Signal handler function. + * @return {number} The index of the listener within the private bindings array. + */ + _indexOfListener: function (listener, context) { + + if (!this._bindings) + { + return -1; + } + + if (context === undefined) { context = null; } + + var n = this._bindings.length; + var cur; + + while (n--) + { + cur = this._bindings[n]; + + if (cur._listener === listener && cur.context === context) + { + return n; + } + } + + return -1; + + }, + + /** + * Check if a specific listener is attached. + * + * @method Phaser.Signal#has + * @param {function} listener - Signal handler function. + * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @return {boolean} If Signal has the specified listener. + */ + has: function (listener, context) { + + return this._indexOfListener(listener, context) !== -1; + + }, + + /** + * Add an event listener for this signal. + * + * An event listener is a callback with a related context and priority. + * + * You can optionally provide extra arguments which will be passed to the callback after any internal parameters. + * + * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. + * Any arguments you've specified after `priority` will be sent as well: + * + * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` + * + * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. + * + * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', + * and the value 100 were the custom arguments given in the call to 'add'. + * + * If the callback calls {@link #halt} or returns `false`, any remaining callbacks bound to this Signal are skipped. + * + * @method Phaser.Signal#add + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + add: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'add'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, false, listenerContext, priority, args); + + }, + + /** + * Add a one-time listener - the listener is automatically removed after the first execution. + * + * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and + * the listener will be removed immediately. + * + * @method Phaser.Signal#addOnce + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + addOnce: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'addOnce'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, true, listenerContext, priority, args); + + }, + + /** + * Remove a single event listener. + * + * @method Phaser.Signal#remove + * @param {function} listener - Handler function that should be removed. + * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {function} Listener handler function. + */ + remove: function (listener, context) { + + this.validateListener(listener, 'remove'); + + var i = this._indexOfListener(listener, context); + + if (i !== -1) + { + this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal + this._bindings.splice(i, 1); + } + + return listener; + + }, + + /** + * Remove all event listeners. + * + * @method Phaser.Signal#removeAll + * @param {object} [context=null] - If specified only listeners for the given context will be removed. + */ + removeAll: function (context) { + + if (context === undefined) { context = null; } + + if (!this._bindings) + { + return; + } + + var n = this._bindings.length; + + while (n--) + { + if (context) + { + if (this._bindings[n].context === context) + { + this._bindings[n]._destroy(); + this._bindings.splice(n, 1); + } + } + else + { + this._bindings[n]._destroy(); + } + } + + if (!context) + { + this._bindings.length = 0; + } + + }, + + /** + * Gets the total number of listeners attached to this Signal. + * + * @method Phaser.Signal#getNumListeners + * @return {integer} Number of listeners attached to the Signal. + */ + getNumListeners: function () { + + return this._bindings ? this._bindings.length : 0; + + }, + + /** + * Stop propagation of the event, blocking the dispatch to next listener on the queue. + * + * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. + * See {@link #active} to enable/disable the signal entirely. + * + * @method Phaser.Signal#halt + */ + halt: function () { + + this._shouldPropagate = false; + + }, + + /** + * Dispatch / broadcast the event to all listeners. + * + * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}. + * + * @method Phaser.Signal#dispatch + * @param {any} [params] - Parameters that should be passed to each handler. + */ + dispatch: function () { + + if (!this.active || !this._bindings) + { + return; + } + + var paramsArr = Array.prototype.slice.call(arguments); + var n = this._bindings.length; + var bindings; + + if (this.memorize) + { + this._prevParams = paramsArr; + } + + if (!n) + { + // Should come after memorize + return; + } + + bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch + this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. + + //execute all callbacks until end of the list or until a callback returns `false` or stops propagation + //reverse loop since listeners with higher priority will be added at the end of the list + do { + n--; + } + while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); + + }, + + /** + * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any. + * + * @method Phaser.Signal#forget + */ + forget: function() { + + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * Dispose the signal - no more events can be dispatched. + * + * This removes all event listeners and clears references to external objects. + * Calling methods on a disposed objects results in undefined behavior. + * + * @method Phaser.Signal#dispose + */ + dispose: function () { + + this.removeAll(); + + this._bindings = null; + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * A string representation of the object. + * + * @method Phaser.Signal#toString + * @return {string} String representation of the object. + */ + toString: function () { + + return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']'; + + } + +}; + +/** +* Create a `dispatch` function that maintains a binding to the original Signal context. +* +* Use the resulting value if the dispatch function needs to be passed somewhere +* or called independently of the Signal object. +* +* @memberof Phaser.Signal +* @property {function} boundDispatch +*/ +Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", { + + get: function () { + var _this = this; + return this._boundDispatch || (this._boundDispatch = function () { + return _this.dispatch.apply(_this, arguments); + }); + } + +}); + +Phaser.Signal.prototype.constructor = Phaser.Signal; + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Object that represents a binding between a Signal and a listener function. +* This is an internal constructor and shouldn't be created directly. +* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. +* +* @class Phaser.SignalBinding +* @constructor +* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to. +* @param {function} listener - Handler function bound to the signal. +* @param {boolean} isOnce - If binding should be executed just once. +* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). +* @param {number} [priority] - The priority level of the event listener. (default = 0). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. +*/ +Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) { + + /** + * @property {Phaser.Game} _listener - Handler function bound to the signal. + * @private + */ + this._listener = listener; + + if (isOnce) + { + this._isOnce = true; + } + + if (listenerContext != null) /* not null/undefined */ + { + this.context = listenerContext; + } + + /** + * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to. + * @private + */ + this._signal = signal; + + if (priority) + { + this._priority = priority; + } + + if (args && args.length) + { + this._args = args; + } + +}; + +Phaser.SignalBinding.prototype = { + + /** + * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + */ + context: null, + + /** + * @property {boolean} _isOnce - If binding should be executed just once. + * @private + */ + _isOnce: false, + + /** + * @property {number} _priority - Listener priority. + * @private + */ + _priority: 0, + + /** + * @property {array} _args - Listener arguments. + * @private + */ + _args: null, + + /** + * @property {number} callCount - The number of times the handler function has been called. + */ + callCount: 0, + + /** + * If binding is active and should be executed. + * @property {boolean} active + * @default + */ + active: true, + + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). + * @property {array|null} params + * @default + */ + params: null, + + /** + * Call listener passing arbitrary parameters. + * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. + * @method Phaser.SignalBinding#execute + * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener. + * @return {any} Value returned by the listener. + */ + execute: function(paramsArr) { + + var handlerReturn, params; + + if (this.active && !!this._listener) + { + params = this.params ? this.params.concat(paramsArr) : paramsArr; + + if (this._args) + { + params = params.concat(this._args); + } + + handlerReturn = this._listener.apply(this.context, params); + + this.callCount++; + + if (this._isOnce) + { + this.detach(); + } + } + + return handlerReturn; + + }, + + /** + * Detach binding from signal. + * alias to: @see mySignal.remove(myBinding.getListener()); + * @method Phaser.SignalBinding#detach + * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ + detach: function () { + return this.isBound() ? this._signal.remove(this._listener, this.context) : null; + }, + + /** + * @method Phaser.SignalBinding#isBound + * @return {boolean} True if binding is still bound to the signal and has a listener. + */ + isBound: function () { + return (!!this._signal && !!this._listener); + }, + + /** + * @method Phaser.SignalBinding#isOnce + * @return {boolean} If SignalBinding will only be executed once. + */ + isOnce: function () { + return this._isOnce; + }, + + /** + * @method Phaser.SignalBinding#getListener + * @return {function} Handler function bound to the signal. + */ + getListener: function () { + return this._listener; + }, + + /** + * @method Phaser.SignalBinding#getSignal + * @return {Phaser.Signal} Signal that listener is currently bound to. + */ + getSignal: function () { + return this._signal; + }, + + /** + * Delete instance properties + * @method Phaser.SignalBinding#_destroy + * @private + */ + _destroy: function () { + delete this._signal; + delete this._listener; + delete this.context; + }, + + /** + * @method Phaser.SignalBinding#toString + * @return {string} String representation of the object. + */ + toString: function () { + return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']'; + } + +}; + +Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding; + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Filter class to use for any Phaser filter development. +* If you want to make a custom filter, this should be your base class. +* +* The default uniforms, types and values for all Filters are: +* +* ```javascript +* resolution: { type: '2f', value: { x: 256, y: 256 }} +* time: { type: '1f', value: 0 } +* mouse: { type: '2f', value: { x: 0.0, y: 0.0 } } +* date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] } +* sampleRate: { type: '1f', value: 44100.0 } +* iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* ``` +* +* The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and +* therefore only work in WebGL and are not supported by Canvas at all. +* +* @class Phaser.Filter +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [uniforms] - Uniform mappings object. The uniforms are added on the default uniforms, or replace them if the keys are the same. +* @param {Array|string} [fragmentSrc] - The fragment shader code. Either an array, one element per line of code, or a string. +*/ +Phaser.Filter = function (game, uniforms, fragmentSrc) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. + * @default + */ + this.type = Phaser.WEBGL_FILTER; + + /** + * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. + * For example the blur filter has two passes blurX and blurY. + * @property {array} passes - An array of filter objects. + * @private + */ + this.passes = [ this ]; + + /** + * @property {array} shaders - Array an array of shaders. + * @private + */ + this.shaders = []; + + /** + * @property {boolean} dirty - Internal PIXI var. + * @default + */ + this.dirty = true; + + /** + * @property {number} padding - Internal PIXI var. + * @default + */ + this.padding = 0; + + /** + * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same) + */ + this.prevPoint = new Phaser.Point(); + + /* + * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D. + */ + + var d = new Date(); + + /** + * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. + */ + this.uniforms = { + + resolution: { type: '2f', value: { x: 256, y: 256 }}, + time: { type: '1f', value: 0 }, + mouse: { type: '2f', value: { x: 0.0, y: 0.0 } }, + date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, + sampleRate: { type: '1f', value: 44100.0 }, + iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + + }; + + // Copy over / replace any passed in the constructor + if (uniforms) + { + for (var key in uniforms) + { + this.uniforms[key] = uniforms[key]; + } + } + + // If fragmentSrc is a string, split it based on new-lines into an array + if (typeof fragmentSrc === 'string') + { + fragmentSrc = fragmentSrc.split('\n'); + } + + /** + * @property {array|string} fragmentSrc - The fragment shader code. + */ + this.fragmentSrc = fragmentSrc || []; + +}; + +Phaser.Filter.prototype = { + + /** + * This should be over-ridden. Will receive a variable number of arguments. + * + * @method Phaser.Filter#init + */ + init: function () { + + // This should be over-ridden. Will receive a variable number of arguments. + + }, + + /** + * Set the resolution uniforms on the filter. + * + * @method Phaser.Filter#setResolution + * @param {number} width - The width of the display. + * @param {number} height - The height of the display. + */ + setResolution: function (width, height) { + + this.uniforms.resolution.value.x = width; + this.uniforms.resolution.value.y = height; + + }, + + /** + * Updates the filter. + * + * @method Phaser.Filter#update + * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. + */ + update: function (pointer) { + + if (pointer) + { + var x = pointer.x / this.game.width; + var y = 1 - pointer.y / this.game.height; + + if (x !== this.prevPoint.x || y !== this.prevPoint.y) + { + this.uniforms.mouse.value.x = x.toFixed(2); + this.uniforms.mouse.value.y = y.toFixed(2); + this.prevPoint.set(x, y); + } + } + + this.uniforms.time.value = this.game.time.totalElapsedSeconds(); + + }, + + /** + * Creates a new Phaser.Image object using a blank texture and assigns + * this Filter to it. The image is then added to the world. + * + * If you don't provide width and height values then Filter.width and Filter.height are used. + * + * If you do provide width and height values then this filter will be resized to match those + * values. + * + * @method Phaser.Filter#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. + * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, width, height, anchorX, anchorY) { + + if (anchorX === undefined) { anchorX = 0; } + if (anchorY === undefined) { anchorY = 0; } + + if (width !== undefined && width !== null) + { + this.width = width; + } + else + { + width = this.width; + } + + if (height !== undefined && height !== null) + { + this.height = height; + } + else + { + height = this.height; + } + + var image = this.game.add.image(x, y, Phaser.Cache.DEFAULT); + + image.width = width; + image.height = height; + + image.anchor.set(anchorX, anchorY); + + image.filters = [ this ]; + + return image; + + }, + + /** + * Syncs the uniforms between the class object and the shaders. + * + * @method Phaser.Filter#syncUniforms + */ + syncUniforms: function () { + + for (var i = 0; i < this.shaders.length; i++) + { + this.shaders[i].dirty = true; + } + + }, + + /** + * Clear down this Filter and null out references to game. + * + * @method Phaser.Filter#destroy + */ + destroy: function () { + + this.passes.length = 0; + this.shaders.length = 0; + this.fragmentSrc.length = 0; + + this.game = null; + this.uniforms = null; + this.prevPoint = null; + + } + +}; + +Phaser.Filter.prototype.constructor = Phaser.Filter; + +/** +* @name Phaser.Filter#width +* @property {number} width - The width (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'width', { + + get: function () { + + return this.uniforms.resolution.value.x; + + }, + + set: function (value) { + + this.uniforms.resolution.value.x = value; + + } + +}); + +/** +* @name Phaser.Filter#height +* @property {number} height - The height (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'height', { + + get: function () { + + return this.uniforms.resolution.value.y; + + }, + + set: function (value) { + + this.uniforms.resolution.value.y = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Plugin template to use for any Phaser plugin development. +* +* ##### Callbacks +* +* add | active | visible | remove +* -----|-------------|-------------|-------- +* init | | | +* | preUpdate* | | +* | update* | render* | +* | postUpdate* | postRender* | +* | | | destroy +* +* Update and render calls are repeated (*). +* +* @class Phaser.Plugin +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager. +*/ +Phaser.Plugin = function (game, parent) { + + if (parent === undefined) { parent = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. + */ + this.parent = parent; + + /** + * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. + * @default + */ + this.active = false; + + /** + * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. + * @default + */ + this.visible = false; + + /** + * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. + * @default + */ + this.hasPreUpdate = false; + + /** + * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. + * @default + */ + this.hasUpdate = false; + + /** + * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. + * @default + */ + this.hasPostUpdate = false; + + /** + * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. + * @default + */ + this.hasRender = false; + + /** + * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. + * @default + */ + this.hasPostRender = false; + +}; + +Phaser.Plugin.prototype = { + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It is only called if active is set to true. + * @method Phaser.Plugin#preUpdate + */ + preUpdate: function () { + }, + + /** + * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It is only called if active is set to true. + * @method Phaser.Plugin#update + */ + update: function () { + }, + + /** + * Render is called right after the Game Renderer completes, but before the State.render. + * It is only called if visible is set to true. + * @method Phaser.Plugin#render + */ + render: function () { + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It is only called if visible is set to true. + * @method Phaser.Plugin#postRender + */ + postRender: function () { + }, + + /** + * Clear down this Plugin and null out references + * @method Phaser.Plugin#destroy + */ + destroy: function () { + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + + } + +}; + +Phaser.Plugin.prototype.constructor = Phaser.Plugin; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. +* +* @class Phaser.PluginManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.PluginManager = function(game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager. + */ + this.plugins = []; + + /** + * @property {number} _len - Internal cache var. + * @private + */ + this._len = 0; + + /** + * @property {number} _i - Internal cache var. + * @private + */ + this._i = 0; + +}; + +Phaser.PluginManager.prototype = { + + /** + * Add a new Plugin into the PluginManager. + * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.PluginManager#add + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + add: function (plugin) { + + var args = Array.prototype.slice.call(arguments, 1); + var result = false; + + // Prototype? + if (typeof plugin === 'function') + { + plugin = new plugin(this.game, this); + } + else + { + plugin.game = this.game; + plugin.parent = this; + } + + // Check for methods now to avoid having to do this every loop + 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; + } + + // The plugin must have at least one of the above functions to be added to the PluginManager. + 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); + + // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager + if (typeof plugin['init'] === 'function') + { + plugin.init.apply(plugin, args); + } + + return plugin; + } + else + { + return null; + } + }, + + /** + * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. + * + * @method Phaser.PluginManager#remove + * @param {Phaser.Plugin} plugin - The plugin to be removed. + * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed? + */ + remove: function (plugin, destroy) { + + if (destroy === undefined) { destroy = true; } + + this._i = this._len; + + while (this._i--) + { + if (this.plugins[this._i] === plugin) + { + if (destroy) + { + plugin.destroy(); + } + + this.plugins.splice(this._i, 1); + this._len--; + return; + } + } + + }, + + /** + * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. + * + * @method Phaser.PluginManager#removeAll + */ + removeAll: function() { + + this._i = this._len; + + while (this._i--) + { + this.plugins[this._i].destroy(); + } + + this.plugins.length = 0; + this._len = 0; + + }, + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#preUpdate + */ + 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 is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#update + */ + 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 is the last thing to be called before the world render. + * In particular, it is called after the world postUpdate, which means the camera has been adjusted. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#postUpdate + */ + 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 is called right after the Game Renderer completes, but before the State.render. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#render + */ + 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(); + } + } + + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#postRender + */ + 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(); + } + } + + }, + + /** + * Clear down this PluginManager, calls destroy on every plugin and nulls out references. + * + * @method Phaser.PluginManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.game = null; + + } + +}; + +Phaser.PluginManager.prototype.constructor = Phaser.PluginManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Stage controls root level display objects upon which everything is displayed. +* It also handles browser visibility handling and the pausing due to loss of focus. +* +* @class Phaser.Stage +* @extends PIXI.DisplayObjectContainer +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Stage = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {string} name - The name of this object. + * @default + */ + this.name = '_stage_root'; + + /** + * By default if the browser tab loses focus the game will pause. + * You can stop that behavior by setting this property to true. + * Note that the browser can still elect to pause your game if it wishes to do so, + * for example swapping to another browser tab. This will cause the RAF callback to halt, + * effectively pausing your game, even though no in-game pause event is triggered if you enable this property. + * @property {boolean} disableVisibilityChange + * @default + */ + this.disableVisibilityChange = false; + + /** + * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. + * @default + */ + this.exists = true; + + /** + * @property {Phaser.Matrix} worldTransform - Current transform of the object based on world (parent) factors + * @private + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage) + * @private + * @readOnly + */ + this.stage = this; + + /** + * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. + */ + this.currentRenderOrderID = 0; + + /** + * @property {string} hiddenVar - The page visibility API event name. + * @private + */ + this._hiddenVar = 'hidden'; + + /** + * @property {function} _onChange - The blur/focus event handler. + * @private + */ + this._onChange = null; + + /** + * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor. + * @private + */ + this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' }; + + if (!this.game.transparent) + { + // transparent = 0,0,0,0 - otherwise r,g,b,1 + this._bgColor.a = 1; + } + + if (game.config) + { + this.parseConfig(game.config); + } + +}; + +Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Stage.prototype.constructor = Phaser.Stage; + +/** +* Parses a Game configuration object. +* +* @method Phaser.Stage#parseConfig +* @protected +* @param {object} config -The configuration object to parse. +*/ +Phaser.Stage.prototype.parseConfig = function (config) { + + if (config['disableVisibilityChange']) + { + this.disableVisibilityChange = config['disableVisibilityChange']; + } + + if (config['backgroundColor']) + { + this.setBackgroundColor(config['backgroundColor']); + } + +}; + +/** +* Initialises the stage and adds the event listeners. +* @method Phaser.Stage#boot +* @private +*/ +Phaser.Stage.prototype.boot = function () { + + Phaser.DOM.getOffset(this.game.canvas, this.offset); + + Phaser.Canvas.setUserSelect(this.game.canvas, 'none'); + Phaser.Canvas.setTouchAction(this.game.canvas, 'none'); + + this.checkVisibility(); + +}; + +/** +* This is called automatically after the plugins preUpdate and before the State.update. +* Most objects have preUpdate methods and it's where initial movement and positioning is done. +* +* @method Phaser.Stage#preUpdate +*/ +Phaser.Stage.prototype.preUpdate = function () { + + this.currentRenderOrderID = 0; + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + +}; + +/** +* This is called automatically after the State.update, but before particles or plugins update. +* +* @method Phaser.Stage#update +*/ +Phaser.Stage.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + this.children[i].update(); + } + +}; + +/** +* This is called automatically before the renderer runs and after the plugins have updated. +* In postUpdate this is where all the final physics calculations and object positioning happens. +* The objects are processed in the order of the display list. +* +* @method Phaser.Stage#postUpdate +*/ +Phaser.Stage.prototype.postUpdate = function () { + + // Apply the camera shake, fade, bounds, etc + this.game.camera.update(); + + // Camera target first? + if (this.game.camera.target) + { + this.game.camera.target.postUpdate(); + + this.updateTransform(); + + this.game.camera.updateTarget(); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + this.updateTransform(); + +}; + +/** +* Updates the transforms for all objects on the display list. +* This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. +* +* @method Phaser.Stage#updateTransform +*/ +Phaser.Stage.prototype.updateTransform = function () { + + this.worldAlpha = 1; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +/** +* Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. +* Also listens for window.onblur and window.onfocus. +* +* @method Phaser.Stage#checkVisibility +*/ +Phaser.Stage.prototype.checkVisibility = function () { + + if (document.hidden !== undefined) + { + this._hiddenVar = 'visibilitychange'; + } + else if (document.webkitHidden !== undefined) + { + this._hiddenVar = 'webkitvisibilitychange'; + } + else if (document.mozHidden !== undefined) + { + this._hiddenVar = 'mozvisibilitychange'; + } + else if (document.msHidden !== undefined) + { + this._hiddenVar = 'msvisibilitychange'; + } + else + { + this._hiddenVar = null; + } + + var _this = this; + + this._onChange = function (event) { + return _this.visibilityChange(event); + }; + + this._onClick = function (event) { + if ((document.hasFocus !== undefined) && !document.hasFocus()) + { + _this.visibilityChange(event); + } + }; + + // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus + if (this._hiddenVar) + { + document.addEventListener(this._hiddenVar, this._onChange, false); + } + + window.onblur = this._onChange; + window.onfocus = this._onChange; + + window.onpagehide = this._onChange; + window.onpageshow = this._onChange; + + window.addEventListener('click', this._onClick); + + if (this.game.device.cocoonJSApp) + { + CocoonJS.App.onSuspended.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" }); + }); + + CocoonJS.App.onActivated.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" }); + }); + } + +}; + +/** +* This method is called when the document visibility is changed. +* +* - `blur` and `pagehide` events trigger {@link Phaser.Game#onBlur}. They {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `click`, `focus`, and `pageshow` trigger {@link Phaser.Game#onFocus}. They {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (hidden) and CocoonJS's `onSuspended` {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (visible) and CocoonJS's `onActivated` {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* +* @method Phaser.Stage#visibilityChange +* @param {Event} event - Its type will be used to decide whether the game should be paused or not. +*/ +Phaser.Stage.prototype.visibilityChange = function (event) { + + // These events always trigger the Game#onBlur or Game#onFocus signals. + + switch (event.type) + { + case 'blur': + case 'pagehide': + this.game.focusLoss(event); + return; + case 'click': + case 'focus': + case 'pageshow': + this.game.focusGain(event); + return; + } + + if (this.disableVisibilityChange) + { + return; + } + + if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause") + { + this.game.gamePaused(event); + } + else + { + this.game.gameResumed(event); + } + +}; + +/** +* Sets the background color for the Stage. +* +* The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). +* +* An alpha channel is _not_ supported and will be ignored. +* +* If you've set your game to be {@link Phaser.Game#transparent transparent} then calls to setBackgroundColor are ignored. +* +* If {@link Phaser.Game#clearBeforeRender} is off then the background color won't appear. +* +* @method Phaser.Stage#setBackgroundColor +* @param {number|string} color - The color of the background. +*/ +Phaser.Stage.prototype.setBackgroundColor = function (color) { + + if (this.game.transparent) { return; } + + Phaser.Color.valueToColor(color, this._bgColor); + Phaser.Color.updateColor(this._bgColor); + + // For gl.clearColor (canvas uses _bgColor.rgba) + this._bgColor.r /= 255; + this._bgColor.g /= 255; + this._bgColor.b /= 255; + this._bgColor.a = 1; + +}; + +/** +* Destroys the Stage and removes event listeners. +* +* @method Phaser.Stage#destroy +*/ +Phaser.Stage.prototype.destroy = function () { + + if (this._hiddenVar) + { + document.removeEventListener(this._hiddenVar, this._onChange, false); + } + + window.onpagehide = null; + window.onpageshow = null; + + window.onblur = null; + window.onfocus = null; + + window.removeEventListener('click', this._onClick); + +}; + +/** +* Adds an existing object to the Stage. +* +* The child is automatically added to the front of the Stage, and is displayed above every previous child. +* Or if the _optional_ `index` is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the object was already on the Stage, it is simply returned, and nothing else happens to it. +* +* @method Phaser.Stage#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent] - Unused. Kept for compatibility with {@link Phaser.Group#add}. +* @param {integer} [index] - The index to insert the object to. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Stage.prototype.add = function (child, silent, index) { + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + this.addChild(child); + } + else + { + this.addChildAt(child, index); + } + + return child; + +}; + +/** +* @name Phaser.Stage#backgroundColor +* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' +* @see Phaser.Stage#setBackgroundColor +*/ +Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", { + + get: function () { + + return this._bgColor.color; + + }, + + set: function (color) { + + this.setBackgroundColor(color); + + } + +}); + +/** +* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. +* +* @name Phaser.Stage#smoothed +* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) +*/ +Object.defineProperty(Phaser.Stage.prototype, "smoothed", { + + get: function () { + + return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR; + + }, + + set: function (value) { + + if (value) + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR; + } + else + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}. +* +* Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. +* For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. +* +* In addition, Groups provides support for fast pooling and object recycling. +* +* Groups are also display objects and can be nested as children within other Groups. +* +* @class Phaser.Group +* @extends PIXI.DisplayObjectContainer +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to. +* If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent. +* @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World. +* @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}. +* @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values. +*/ +Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) { + + if (addToStage === undefined) { addToStage = false; } + if (enableBody === undefined) { enableBody = false; } + if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + if (parent === undefined) + { + parent = game.world; + } + + /** + * A name for this group. Not used internally but useful for debugging. + * @property {string} name + */ + this.name = name || 'group'; + + /** + * The z-depth value of this object within its parent container/Group - the World is a Group as well. + * This value must be unique for each child in a Group. + * @property {integer} z + * @readOnly + */ + this.z = 0; + + PIXI.DisplayObjectContainer.call(this); + + if (addToStage) + { + this.game.stage.addChild(this); + this.z = this.game.stage.children.length; + } + else + { + if (parent) + { + parent.addChild(this); + this.z = parent.children.length; + } + } + + /** + * Internal Phaser Type value. + * @property {integer} type + * @protected + */ + this.type = Phaser.GROUP; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. + * @property {boolean} alive + * @default + */ + this.alive = true; + + /** + * If exists is false the group will be excluded from collision checks and filters such as {@link #forEachExists}. The group will not call `preUpdate` and `postUpdate` on its children and the children will not receive physics updates or camera/world boundary checks. The group will still be {@link #visible} and will still call `update` on its children (unless {@link #updateOnlyExistingChildren} is true). + * @property {boolean} exists + * @default + */ + this.exists = true; + + /** + * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. + * @property {boolean} ignoreDestroy + * @default + */ + this.ignoreDestroy = false; + + /** + * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method + * called on the next logic update. + * You can set it directly to flag the Group to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy a Group from within one of its own callbacks + * or a callback of one of its children. + * + * @property {boolean} pendingDestroy + */ + this.pendingDestroy = false; + + /** + * The type of objects that will be created when using {@link #create} or {@link #createMultiple}. + * + * It should extend either Sprite or Image and accept the same constructor arguments: `(game, x, y, key, frame)`. + * + * @property {function} classType + * @default {@link Phaser.Sprite} + */ + this.classType = Phaser.Sprite; + + /** + * The current display object that the group cursor is pointing to, if any. (Can be set manually.) + * + * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}. + * @property {?DisplayObject} cursor + */ + this.cursor = null; + + /** + * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` + * on any children _added_ to, or _created by_, this Group. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * @property {boolean} inputEnableChildren + * @default + */ + this.inputEnableChildren = false; + + /** + * Skip children with `exists = false` in {@link #update}. + * + * @property {boolean} updateOnlyExistingChildren + * @default + */ + this.updateOnlyExistingChildren = false; + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputDown + */ + this.onChildInputDown = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, + * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer + * is still over the Sprite or not. + * + * @property {Phaser.Signal} onChildInputUp + */ + this.onChildInputUp = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOver + */ + this.onChildInputOver = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOut + */ + this.onChildInputOut = new Phaser.Signal(); + + /** + * If true all Sprites created by, or added to this group, will have a physics body enabled on them. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * The default body type is controlled with {@link #physicsBodyType}. + * @property {boolean} enableBody + */ + this.enableBody = enableBody; + + /** + * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well. + * + * This only works for P2 bodies. + * @property {boolean} enableBodyDebug + * @default + */ + this.enableBodyDebug = false; + + /** + * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites. + * + * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc. + * @property {integer} physicsBodyType + */ + this.physicsBodyType = physicsBodyType; + + /** + * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. + * + * It should be set to one of the Phaser.Physics.Arcade sort direction constants: + * + * Phaser.Physics.Arcade.SORT_NONE + * Phaser.Physics.Arcade.LEFT_RIGHT + * Phaser.Physics.Arcade.RIGHT_LEFT + * Phaser.Physics.Arcade.TOP_BOTTOM + * Phaser.Physics.Arcade.BOTTOM_TOP + * + * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. + * + * @property {integer} physicsSortDirection + * @default + */ + this.physicsSortDirection = null; + + /** + * This signal is dispatched when the group is destroyed. + * @property {Phaser.Signal} onDestroy + */ + this.onDestroy = new Phaser.Signal(); + + /** + * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next. + * @readOnly + */ + this.cursorIndex = 0; + + /** + * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. + * + * Note that the cameraOffset values are in addition to any parent in the display list. + * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x + * + * @property {boolean} fixedToCamera + */ + this.fixedToCamera = false; + + /** + * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view. + * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. + * @property {Phaser.Point} cameraOffset + */ + this.cameraOffset = new Phaser.Point(); + + /** + * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. + * + * Only children of this Group can be added to and removed from the hash. + * + * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. + * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own + * sorting and filtering of Group children without touching their z-index (and therefore display draw order) + * + * @property {array} hash + */ + this.hash = []; + + /** + * The property on which children are sorted. + * @property {string} _sortProperty + * @private + */ + this._sortProperty = 'z'; + +}; + +Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Group.prototype.constructor = Phaser.Group; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_NONE = 0; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_TOTAL = 1; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_CHILD = 2; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_ALL = 3; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_ASCENDING = -1; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_DESCENDING = 1; + +/** +* Adds an existing object as the top child in this group. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the child was already in this Group, it is simply returned, and nothing else happens to it. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* Use {@link #create} to create and add a new child. +* +* @method Phaser.Group#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.add = function (child, silent, index) { + + if (silent === undefined) { silent = false; } + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + child.z = this.children.length; + + this.addChild(child); + } + else + { + this.addChildAt(child, index); + + this.updateZ(); + } + + if (this.enableBody && child.hasOwnProperty('body') && child.body === null) + { + this.game.physics.enable(child, this.physicsBodyType); + } + else if (child.body) + { + this.addToHash(child); + } + + if (this.inputEnableChildren && (!child.input || child.inputEnabled)) + { + child.inputEnabled = true; + } + + if (!silent && child.events) + { + child.events.onAddedToGroup$dispatch(child, this); + } + + if (this.cursor === null) + { + this.cursor = child; + } + + return child; + +}; + +/** +* Adds an existing object to this group. +* +* The child is added to the group at the location specified by the index value, this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#addAt +* @param {DisplayObject} child - The display object to add as a child. +* @param {integer} [index=0] - The index within the group to insert the child to. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.addAt = function (child, index, silent) { + + return this.add(child, silent, index); + +}; + +/** +* Adds a child of this Group into the hash array. +* This call will return false if the child is not a child of this Group, or is already in the hash. +* +* @method Phaser.Group#addToHash +* @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. +* @return {boolean} True if the child was successfully added to the hash, otherwise false. +*/ +Phaser.Group.prototype.addToHash = function (child) { + + if (child.parent === this) + { + var index = this.hash.indexOf(child); + + if (index === -1) + { + this.hash.push(child); + return true; + } + } + + return false; + +}; + +/** +* Removes a child of this Group from the hash array. +* This call will return false if the child is not in the hash. +* +* @method Phaser.Group#removeFromHash +* @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash. +* @return {boolean} True if the child was successfully removed from the hash, otherwise false. +*/ +Phaser.Group.prototype.removeFromHash = function (child) { + + if (child) + { + var index = this.hash.indexOf(child); + + if (index !== -1) + { + this.hash.splice(index, 1); + return true; + } + } + + return false; + +}; + +/** +* Adds an array of existing Display Objects to this Group. +* +* The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. +* +* As well as an array you can also pass another Group as the first argument. In this case all of the children from that +* Group will be removed from it and added into this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#addMultiple +* @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group. +*/ +Phaser.Group.prototype.addMultiple = function (children, silent) { + + if (children instanceof Phaser.Group) + { + children.moveAll(this, silent); + } + else if (Array.isArray(children)) + { + for (var i = 0; i < children.length; i++) + { + this.add(children[i], silent); + } + } + + return children; + +}; + +/** +* Returns the child found at the given index within this group. +* +* @method Phaser.Group#getAt +* @param {integer} index - The index to return the child from. +* @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index. +*/ +Phaser.Group.prototype.getAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + return -1; + } + else + { + return this.getChildAt(index); + } + +}; + +/** +* Creates a new Phaser.Sprite object and adds it to the top of this group. +* +* Use {@link #classType} to change the type of object created. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#create +* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. +* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {boolean} [exists=true] - The default exists state of the Sprite. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed. +*/ +Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) { + + if (exists === undefined) { exists = true; } + + var child = new this.classType(this.game, x, y, key, frame); + + child.exists = exists; + child.visible = exists; + child.alive = exists; + + return this.add(child, false, index); + +}; + +/** +* Creates multiple Phaser.Sprite objects and adds them to the top of this Group. +* +* This method is useful if you need to quickly generate a pool of sprites, such as bullets. +* +* Use {@link #classType} to change the type of object created. +* +* You can provide an array as the `key` and / or `frame` arguments. When you do this +* it will create `quantity` Sprites for every key (and frame) in the arrays. +* +* For example: +* +* `createMultiple(25, ['ball', 'carrot'])` +* +* In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be +* created in total, 25 of each. You can also have the `frame` as an array: +* +* `createMultiple(5, 'bricks', [0, 1, 2, 3])` +* +* In the above there is one key (bricks), which is a sprite sheet. The frames array tells +* this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because +* the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with +* frame 1, and so on. +* +* If you set both the key and frame arguments to be arrays then understand it will create +* a total quantity of sprites equal to the size of both arrays times each other. I.e.: +* +* `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` +* +* The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. +* It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. +* In total it will have created 120 sprites. +* +* By default the Sprites will have their `exists` property set to `false`, and they will be +* positioned at 0x0, relative to the `Group.x / y` values. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#createMultiple +* @param {integer} quantity - The number of Sprites to create. +* @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. +* @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. +* @param {boolean} [exists=false] - The default exists state of the Sprite. +* @param {function} [callback] - The function that will be called for each applicable child. It will be passed the new child and the loop index (0 through quantity - 1). +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). The default context is the new child. +* @return {array} An array containing all of the Sprites that were created. +*/ +Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, callback, callbackContext) { + + if (frame === undefined) { frame = 0; } + if (exists === undefined) { exists = false; } + + if (!Array.isArray(key)) + { + key = [ key ]; + } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + + var _this = this; + var children = []; + + key.forEach(function(singleKey) { + + frame.forEach(function(singleFrame) { + + for (var i = 0; i < quantity; i++) + { + var child = _this.create(0, 0, singleKey, singleFrame, exists); + + if (callback) { callback.call(callbackContext || child, child, i); } + + children.push(child); + } + + }); + + }); + + return children; + +}; + +/** +* Internal method that re-applies all of the children's Z values. +* +* This must be called whenever children ordering is altered so that their `z` indices are correctly updated. +* +* @method Phaser.Group#updateZ +* @protected +*/ +Phaser.Group.prototype.updateZ = function () { + + var i = this.children.length; + + while (i--) + { + this.children[i].z = i; + } + +}; + +/** +* This method iterates through all children in the Group (regardless if they are visible or exist) +* and then changes their position so they are arranged in a Grid formation. Children must have +* the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have +* this. +* +* The grid dimensions are determined by the first four arguments. The `width` and `height` arguments +* relate to the width and height of the grid respectively. +* +* For example if the Group had 100 children in it: +* +* `Group.align(10, 10, 32, 32)` +* +* This will align all of the children into a grid formation of 10x10, using 32 pixels per +* grid cell. If you want a wider grid, you could do: +* +* `Group.align(25, 4, 32, 32)` +* +* This will align the children into a grid of 25x4, again using 32 pixels per grid cell. +* +* You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method +* to keep on aligning children until there are no children left. For example if this Group had +* 48 children in it, the following: +* +* `Group.align(-1, 8, 32, 32)` +* +* ... will align the children so that there are 8 children vertically (the second argument), +* and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) +* +* You can also do: +* +* `Group.align(10, -1, 32, 32)` +* +* In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit +* all of the children in. +* +* The `position` property allows you to control where in each grid cell the child is positioned. +* This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, +* `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, +* `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* +* The final argument; `offset` lets you start the alignment from a specific child index. +* +* @method Phaser.Group#align +* @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. +* @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. +* @param {integer} cellWidth - The width of each grid cell, in pixels. +* @param {integer} cellHeight - The height of each grid cell, in pixels. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. +* @return {boolean} True if the Group children were aligned, otherwise false. +*/ +Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, position, offset) { + + if (position === undefined) { position = Phaser.TOP_LEFT; } + if (offset === undefined) { offset = 0; } + + if (this.children.length === 0 || offset > this.children.length || (width === -1 && height === -1)) + { + return false; + } + + var r = new Phaser.Rectangle(0, 0, cellWidth, cellHeight); + var w = (width * cellWidth); + var h = (height * cellHeight); + + for (var i = offset; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child['alignIn']) + { + child.alignIn(r, position); + } + else + { + continue; + } + + if (width === -1) + { + // We keep laying them out horizontally until we've done them all + r.y += cellHeight; + + if (r.y === h) + { + r.x += cellWidth; + r.y = 0; + } + } + else if (height === -1) + { + // We keep laying them out vertically until we've done them all + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + } + } + else + { + // We keep laying them out until we hit the column limit + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + + if (r.y === h) + { + // We've hit the column limit, so return, even if there are children left + return true; + } + } + } + } + + return true; + +}; + +/** +* Sets the group cursor to the first child in the group. +* +* If the optional index parameter is given it sets the cursor to the object at that index instead. +* +* @method Phaser.Group#resetCursor +* @param {integer} [index=0] - Set the cursor to point to a specific index. +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.resetCursor = function (index) { + + if (index === undefined) { index = 0; } + + if (index > this.children.length - 1) + { + index = 0; + } + + if (this.cursor) + { + this.cursorIndex = index; + this.cursor = this.children[this.cursorIndex]; + return this.cursor; + } + +}; + +/** +* Advances the group cursor to the next (higher) object in the group. +* +* If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). +* +* @method Phaser.Group#next +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.next = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex >= this.children.length - 1) + { + this.cursorIndex = 0; + } + else + { + this.cursorIndex++; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Moves the group cursor to the previous (lower) child in the group. +* +* If the cursor is at the start of the group (bottom child) it is moved to the end (top child). +* +* @method Phaser.Group#previous +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.previous = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex === 0) + { + this.cursorIndex = this.children.length - 1; + } + else + { + this.cursorIndex--; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Swaps the position of two children in this group. +* +* Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. +* +* @method Phaser.Group#swap +* @param {any} child1 - The first child to swap. +* @param {any} child2 - The second child to swap. +*/ +Phaser.Group.prototype.swap = function (child1, child2) { + + this.swapChildren(child1, child2); + this.updateZ(); + +}; + +/** +* Brings the given child to the top of this group so it renders above all other children. +* +* @method Phaser.Group#bringToTop +* @param {any} child - The child to bring to the top of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.bringToTop = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length) + { + this.remove(child, false, true); + this.add(child, true); + } + + return child; + +}; + +/** +* Sends the given child to the bottom of this group so it renders below all other children. +* +* @method Phaser.Group#sendToBack +* @param {any} child - The child to send to the bottom of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.sendToBack = function (child) { + + if (child.parent === this && this.getIndex(child) > 0) + { + this.remove(child, false, true); + this.addAt(child, 0, true); + } + + return child; + +}; + +/** +* Moves the given child up one place in this group unless it's already at the top. +* +* @method Phaser.Group#moveUp +* @param {any} child - The child to move up in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveUp = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length - 1) + { + var a = this.getIndex(child); + var b = this.getAt(a + 1); + + if (b) + { + this.swap(child, b); + } + } + + return child; + +}; + +/** +* Moves the given child down one place in this group unless it's already at the bottom. +* +* @method Phaser.Group#moveDown +* @param {any} child - The child to move down in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveDown = 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; + +}; + +/** +* Positions the child found at the given index within this group to the given x and y coordinates. +* +* @method Phaser.Group#xy +* @param {integer} index - The index of the child in the group to set the position of. +* @param {number} x - The new x position of the child. +* @param {number} y - The new y position of the 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; + } + +}; + +/** +* Reverses all children in this group. +* +* This operation applies only to immediate children and does not propagate to subgroups. +* +* @method Phaser.Group#reverse +*/ +Phaser.Group.prototype.reverse = function () { + + this.children.reverse(); + this.updateZ(); + +}; + +/** +* Get the index position of the given child in this group, which should match the child's `z` property. +* +* @method Phaser.Group#getIndex +* @param {any} child - The child to get the index for. +* @return {integer} The index of the child or -1 if it's not a member of this group. +*/ +Phaser.Group.prototype.getIndex = function (child) { + + return this.children.indexOf(child); + +}; + +/** +* Searches the Group for the first instance of a child with the `name` +* property matching the given argument. Should more than one child have +* the same name only the first instance is returned. +* +* @method Phaser.Group#getByName +* @param {string} name - The name to search for. +* @return {any} The first child with a matching name, or null if none were found. +*/ +Phaser.Group.prototype.getByName = function (name) { + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].name === name) + { + return this.children[i]; + } + } + + return null; + +}; + +/** +* Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#replace +* @param {any} oldChild - The child in this group that will be replaced. +* @param {any} newChild - The child to be inserted into this group. +* @return {any} Returns the oldChild that was replaced within this group. +*/ +Phaser.Group.prototype.replace = function (oldChild, newChild) { + + var index = this.getIndex(oldChild); + + if (index !== -1) + { + if (newChild.parent) + { + if (newChild.parent instanceof Phaser.Group) + { + newChild.parent.remove(newChild); + } + else + { + newChild.parent.removeChild(newChild); + } + } + + this.remove(oldChild); + + this.addAt(newChild, index); + + return oldChild; + } + +}; + +/** +* Checks if the child has the given property. +* +* Will scan up to 4 levels deep only. +* +* @method Phaser.Group#hasProperty +* @param {any} child - The child to check for the existence of the property on. +* @param {string[]} key - An array of strings that make up the property. +* @return {boolean} True if the child has the property, otherwise false. +*/ +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; + +}; + +/** +* Sets a property to the given value on the child. The operation parameter controls how the value is set. +* +* The operations are: +* - 0: set the existing value to the given value; if force is `true` a new property will be created if needed +* - 1: will add the given value to the value already present. +* - 2: will subtract the given value from the value already present. +* - 3: will multiply the value already present by the given value. +* - 4: will divide the value already present by the given value. +* +* @method Phaser.Group#setProperty +* @param {any} child - The child to set the property value on. +* @param {array} key - An array of strings that make up the property that will be set. +* @param {any} value - The value that will be set. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) { + + if (force === undefined) { force = false; } + + operation = operation || 0; + + // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration. + + // 0 = Equals + // 1 = Add + // 2 = Subtract + // 3 = Multiply + // 4 = Divide + + // We can't force a property in and the child doesn't have it, so abort. + // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too. + 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; + +}; + +/** +* Checks a property for the given value on the child. +* +* @method Phaser.Group#checkProperty +* @param {any} child - The child to check the property value on. +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} True if `child` is a child of this Group and the property was equal to value, false if not. +*/ +Phaser.Group.prototype.checkProperty = function (child, key, value, force) { + + if (force === undefined) { force = false; } + + if (this !== child.parent) + { + return false; + } + + var result = Phaser.Utils.getProperty(child, key); + + if (((result === undefined) && force) || (result !== value)) + { + return false; + } + + return true; + +}; + +/** +* Quickly set a property on a single child of this group to a new value. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#set +* @param {Phaser.Sprite} child - The child to set the property on. +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true. +* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) { + + if (force === undefined) { force = false; } + + key = key.split('.'); + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible))) + { + return this.setProperty(child, key, value, operation, force); + } + +}; + +/** +* Quickly set the same property across all children of this group to a new value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. +* If you need that ability please see `Group.setAllChildren`. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAll +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + key = key.split('.'); + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + this.setProperty(this.children[i], key, value, operation, force); + } + } + +}; + +/** +* Quickly set the same property across all children of this group, and any child Groups, to a new value. +* +* If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. +* Unlike with `setAll` the property is NOT set on child Groups itself. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAllChildren +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + if (this.children[i] instanceof Phaser.Group) + { + this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force); + } + else + { + this.setProperty(this.children[i], key.split('.'), value, operation, force); + } + } + } + +}; + +/** +* Test that the same property across all children of this group is equal to the given value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAll +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} - True if all eligible children have the given property value (but see `force`); otherwise false. +*/ +Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (!this.checkProperty(child, key, value, force)) + { + return false; + } + } + } + + return true; + +}; + +/** +* Test that at least one child of this group has the given property value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAny +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @return {boolean} - True if at least one eligible child has the given property value; otherwise false. +*/ +Phaser.Group.prototype.checkAny = function (key, value, checkAlive, checkVisible) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (this.checkProperty(child, key, value)) + { + return true; + } + } + } + + return false; + +}; + +/** +* Adds the amount to the given property on all children in this group. +* +* `Group.addAll('x', 10)` will add 10 to the child.x value for each child. +* +* @method Phaser.Group#addAll +* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. +* @param {boolean} [checkAlive] - If true the property will only be changed if the child is alive. +* @param {boolean} [checkVisible] - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 1); + +}; + +/** +* Subtracts the amount from the given property on all children in this group. +* +* `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. +* +* @method Phaser.Group#subAll +* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 2); + +}; + +/** +* Multiplies the given property by the amount on all children in this group. +* +* `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. +* +* @method Phaser.Group#multiplyAll +* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 3); + +}; + +/** +* Divides the given property by the amount on all children in this group. +* +* `Group.divideAll('x', 2)` will half the child.x value for each child. +* +* @method Phaser.Group#divideAll +* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 4); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to false. + * + * @method Phaser.Group#kill + */ +Phaser.Group.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + +}; + +/** + * Kills all children having exists=true. + * + * @method Phaser.Group#killAll + */ +Phaser.Group.prototype.killAll = function () { + + this.callAllExists('kill', true); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to true. + * + * @method Phaser.Group#revive + */ +Phaser.Group.prototype.revive = function () { + + this.alive = true; + this.exists = true; + this.visible = true; + +}; + +/** + * Revives all children having exists=false. + * + * @method Phaser.Group#reviveAll + */ +Phaser.Group.prototype.reviveAll = function () { + + this.callAllExists('revive', false); + +}; + +/** +* Calls {@link #resetChild} on each child (or each existing child). +* +* @method Phaser.Group#resetAll +* @param {number} [x] - The x coordinate to reset each child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset each child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image or texture used by the Sprite during rendering. +* @param {string|number} [frame] - The frame of a sprite sheet or texture atlas. +* @param {boolean} [checkExists=false] - Reset only existing children. +*/ +Phaser.Group.prototype.resetAll = function (x, y, key, frame, checkExists) { + + this.forEach(this.resetChild, this, checkExists, x, y, key, frame); + +}; + +/** +* Calls a function, specified by name, on all children in the group who exist (or do not exist). +* +* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. +* +* @method Phaser.Group#callAllExists +* @param {string} callback - Name of the function on the children to call. +* @param {boolean} existsValue - Only children with exists=existsValue will be called. +* @param {...any} parameter - Additional parameters that will be passed to the callback. +*/ +Phaser.Group.prototype.callAllExists = function (callback, existsValue) { + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].exists === existsValue && this.children[i][callback]) + { + this.children[i][callback].apply(this.children[i], args); + } + } + +}; + +/** +* Returns a reference to a function that exists on a child of the group based on the given callback array. +* +* @method Phaser.Group#callbackFromArray +* @param {object} child - The object to inspect. +* @param {array} callback - The array of function names. +* @param {integer} length - The size of the array (pre-calculated in callAll). +* @protected +*/ +Phaser.Group.prototype.callbackFromArray = function (child, callback, length) { + + // Kinda looks like a Christmas tree + + if (length === 1) + { + if (child[callback[0]]) + { + return child[callback[0]]; + } + } + else if (length === 2) + { + if (child[callback[0]][callback[1]]) + { + return child[callback[0]][callback[1]]; + } + } + else if (length === 3) + { + if (child[callback[0]][callback[1]][callback[2]]) + { + return child[callback[0]][callback[1]][callback[2]]; + } + } + else if (length === 4) + { + if (child[callback[0]][callback[1]][callback[2]][callback[3]]) + { + return child[callback[0]][callback[1]][callback[2]][callback[3]]; + } + } + else if (child[callback]) + { + return child[callback]; + } + + return false; + +}; + +/** +* Calls a function, specified by name, on all on children. +* +* The function is called for all children regardless if they are dead or alive (see callAllExists for different options). +* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. +* +* @method Phaser.Group#callAll +* @param {string} method - Name of the function on the child to call. Deep property lookup is supported. +* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child. +* @param {...any} args - Additional parameters that will be passed to the method. +*/ +Phaser.Group.prototype.callAll = function (method, context) { + + if (method === undefined) + { + return; + } + + // Extract the method into an array + method = method.split('.'); + + var methodLength = method.length; + + if (context === undefined || context === null || context === '') + { + context = null; + } + else + { + // Extract the context into an array + if (typeof context === 'string') + { + context = context.split('.'); + var contextLength = context.length; + } + } + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + var callback = null; + var callbackContext = null; + + for (var i = 0; i < this.children.length; i++) + { + callback = this.callbackFromArray(this.children[i], method, methodLength); + + if (context && callback) + { + callbackContext = this.callbackFromArray(this.children[i], context, contextLength); + + if (callback) + { + callback.apply(callbackContext, args); + } + } + else if (callback) + { + callback.apply(this.children[i], args); + } + } + +}; + +/** +* The core preUpdate - as called by World. +* @method Phaser.Group#preUpdate +* @protected +*/ +Phaser.Group.prototype.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + // This chunk is identical to Phaser.Component.Core.prototype.preUpdateChildren, which is not yet defined. + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + return true; + +}; + +/** +* The core update - as called by World. +* +* Children with `exists = false` are updated unless {@link #updateOnlyExistingChildren} is true. +* +* @method Phaser.Group#update +* @protected +*/ +Phaser.Group.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + var len = this.children.length; + + if (i >= len) { i = len - 1; } + + var child = this.children[i]; + + if (!this.updateOnlyExistingChildren || child.exists) { + child.update(); + } + } + +}; + +/** +* The core postUpdate - as called by World. +* @method Phaser.Group#postUpdate +* @protected +*/ +Phaser.Group.prototype.postUpdate = function () { + + // Fixed to Camera? + if (this.fixedToCamera) + { + this.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; + this.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Find children matching a certain predicate. +* +* For example: +* +* var healthyList = Group.filter(function(child, index, children) { +* return child.health > 10 ? true : false; +* }, true); +* healthyList.callAll('attack'); +* +* Note: Currently this will skip any children which are Groups themselves. +* +* @method Phaser.Group#filter +* @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third +* @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. +* @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for +*/ +Phaser.Group.prototype.filter = function (predicate, checkExists) { + + var index = -1; + var length = this.children.length; + var results = []; + + while (++index < length) + { + var child = this.children[index]; + + if (!checkExists || (checkExists && child.exists)) + { + if (predicate(child, index, this.children)) + { + results.push(child); + } + } + } + + return new Phaser.ArraySet(results); + +}; + +/** +* Call a function on each child in this group. +* +* Additional arguments for the callback can be specified after the `checkExists` parameter. For example, +* +* Group.forEach(awardBonusGold, this, true, 100, 500) +* +* would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. +* +* Note: This check will skip any children which are Groups themselves. +* +* @method Phaser.Group#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) { + + if (checkExists === undefined) { checkExists = false; } + + if (arguments.length <= 3) + { + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + callback.call(callbackContext, this.children[i]); + } + } + } + else + { + // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE. + // Using an array and pushing each element (not a slice!) is _significantly_ faster. + var args = [null]; + + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + } + } + +}; + +/** +* Call a function on each existing child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachExists +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachExists = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each alive child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachAlive +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each dead child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachDead +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachDead = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Sort the children in the group according to a particular key and ordering. +* +* Call this function to sort the group according to a particular key value and order. +* +* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. +* +* Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including +* alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. +* +* @method Phaser.Group#sort +* @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value. +* @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}). +*/ +Phaser.Group.prototype.sort = function (key, order) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + if (key === undefined) { key = 'z'; } + if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; } + + this._sortProperty = key; + + if (order === Phaser.Group.SORT_ASCENDING) + { + this.children.sort(this.ascendingSortHandler.bind(this)); + } + else + { + this.children.sort(this.descendingSortHandler.bind(this)); + } + + this.updateZ(); + +}; + +/** +* Sort the children in the group according to custom sort function. +* +* The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). +* It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. +* +* @method Phaser.Group#customSort +* @param {function} sortHandler - The custom sort function. +* @param {object} [context=undefined] - The context in which the sortHandler is called. +*/ +Phaser.Group.prototype.customSort = function (sortHandler, context) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + this.children.sort(sortHandler.bind(context)); + + this.updateZ(); + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#ascendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.ascendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return -1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return 1; + } + else + { + if (a.z < b.z) + { + return -1; + } + else + { + return 1; + } + } + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#descendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.descendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return 1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return -1; + } + else + { + return 0; + } + +}; + +/** +* Iterates over the children of the group performing one of several actions for matched children. +* +* A child is considered a match when it has a property, named `key`, whose value is equal to `value` +* according to a strict equality comparison. +* +* The result depends on the `returnType`: +* +* - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}: +* The callback, if any, is applied to all matching children. The number of matched children is returned. +* - {@link Phaser.Group.RETURN_NONE RETURN_NONE}: +* The callback, if any, is applied to all matching children. No value is returned. +* - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}: +* The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. +* If there is no matching child then null is returned. +* +* If `args` is specified it must be an array. The matched child will be assigned to the first +* element and the entire array will be applied to the callback function. +* +* @method Phaser.Group#iterate +* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' +* @param {any} value - A child matches if `child[key] === value` is true. +* @param {integer} returnType - How to iterate the children and what to return. +* @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. +* @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null. +*/ +Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) { + + if (this.children.length === 0) + { + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return 0; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return []; + } + } + + var total = 0; + + if (returnType === Phaser.Group.RETURN_ALL) + { + var output = []; + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i][key] === value) + { + total++; + + if (callback) + { + if (args) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + else + { + callback.call(callbackContext, this.children[i]); + } + } + + if (returnType === Phaser.Group.RETURN_CHILD) + { + return this.children[i]; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + output.push(this.children[i]); + } + } + } + + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return total; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return output; + } + else + { + // RETURN_CHILD or RETURN_NONE + return null; + } + +}; + +/** +* Get the first display object with the given property name and value. +* +* @method Phaser.Group#getFirst +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {DisplayObject} The first child matching the query, or `null` if none were found. +*/ +Phaser.Group.prototype.getFirst = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_CHILD); + +}; + +/** +* Get the first display object that exists, or doesn't exist. +* +* You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstExists +* @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child. +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + if (typeof exists !== 'boolean') + { + exists = true; + } + + var child = this.getFirst('exists', exists); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is alive (`child.alive === true`). +* +* This is handy for choosing a squad leader, etc. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstAlive +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', true); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is dead (`child.alive === false`). +* +* This is handy for checking if everything has been wiped out and adding to the pool as needed. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstDead +* @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', false); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. +* +* If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. +* +* The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. +* +* @method Phaser.Group#resetChild +* @param {DisplayObject} child - The child to reset and/or load the texture on. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}. +*/ +Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) { + + if (child === null) + { + return null; + } + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (x !== null && y !== null) + { + child.reset(x, y); + } + + if (key !== undefined) + { + child.loadTexture(key, frame); + } + + return child; + +}; + +/** +* Return the child at the top of this group. +* +* The top child is the child displayed (rendered) above every other child. +* +* @method Phaser.Group#getTop +* @return {any} The child at the top of the Group. +*/ +Phaser.Group.prototype.getTop = function () { + + if (this.children.length > 0) + { + return this.children[this.children.length - 1]; + } + +}; + +/** +* Returns the child at the bottom of this group. +* +* The bottom child the child being displayed (rendered) below every other child. +* +* @method Phaser.Group#getBottom +* @return {any} The child at the bottom of the Group. +*/ +Phaser.Group.prototype.getBottom = function () { + + if (this.children.length > 0) + { + return this.children[0]; + } + +}; + +/** +* Get the closest child to given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getClosestTo +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child closest to given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContext) { + + var distance = Number.MAX_VALUE; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance < distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the child furthest away from the given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getFurthestFrom +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child furthest from the given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackContext) { + + var distance = 0; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance > distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the number of children with the given property name and value. +* +* @method Phaser.Group#count +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {integer} The number of children matching the query. +*/ +Phaser.Group.prototype.count = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_TOTAL); + +}; + +/** +* Get the number of living children in this group. +* +* @method Phaser.Group#countLiving +* @return {integer} The number of children flagged as alive. +*/ +Phaser.Group.prototype.countLiving = function () { + + return this.count('alive', true); + +}; + +/** +* Get the number of dead children in this group. +* +* @method Phaser.Group#countDead +* @return {integer} The number of children flagged as dead. +*/ +Phaser.Group.prototype.countDead = function () { + + return this.count('alive', false); + +}; + +/** +* Returns a random child from the group. +* +* @method Phaser.Group#getRandom +* @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). +* @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. +* @return {any} A random child of this Group. +*/ +Phaser.Group.prototype.getRandom = function (startIndex, length) { + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = this.children.length; } + + if (length === 0) + { + return null; + } + + return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length); + +}; + +/** +* Returns a random child from the Group that has `exists` set to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only +* the first 50 children in the Group. +* +* @method Phaser.Group#getRandomExists +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up to. +* @return {any} A random child of this Group that exists. +*/ +Phaser.Group.prototype.getRandomExists = function (startIndex, endIndex) { + + var list = this.getAll('exists', true, startIndex, endIndex); + + return this.game.rnd.pick(list); + +}; + +/** +* Returns all children in this Group. +* +* You can optionally specify a matching criteria using the `property` and `value` arguments. +* +* For example: `getAll('exists', true)` would return only children that have an `exists` property equal to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return the first 50 children in the Group. +* If `property` and `value` are also specified, only children within the given index range are searched. +* +* @method Phaser.Group#getAll +* @param {string} [property] - An optional property to test against the value argument. +* @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results. +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up until. +* @return {array} - An array containing all, some, or none of the Children of this Group. +*/ +Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) { + + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var output = []; + + for (var i = startIndex; i < endIndex; i++) + { + var child = this.children[i]; + + if (property) + { + if (child[property] === value) + { + output.push(child); + } + } + else + { + output.push(child); + } + } + + return output; + +}; + +/** +* Removes the given child from this group. +* +* This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. +* +* If the group cursor was referring to the removed child it is updated to refer to the next child. +* +* @method Phaser.Group#remove +* @param {any} child - The child to remove. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child. +* @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event. +* @return {boolean} true if the child was removed from this group, otherwise false. +*/ +Phaser.Group.prototype.remove = function (child, destroy, silent) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + + if (this.children.length === 0 || this.children.indexOf(child) === -1) + { + return false; + } + + if (!silent && child.events && !child.destroyPhase) + { + child.events.onRemovedFromGroup$dispatch(child, this); + } + + var removed = this.removeChild(child); + + this.removeFromHash(child); + + this.updateZ(); + + if (this.cursor === child) + { + this.next(); + } + + if (destroy && removed) + { + removed.destroy(true); + } + + return true; + +}; + +/** +* Moves all children from this Group to the Group given. +* +* @method Phaser.Group#moveAll +* @param {Phaser.Group} group - The new Group to which the children will be moved to. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group. +* @return {Phaser.Group} The Group to which all the children were moved. +*/ +Phaser.Group.prototype.moveAll = function (group, silent) { + + if (silent === undefined) { silent = false; } + + if (this.children.length > 0 && group instanceof Phaser.Group) + { + do + { + group.add(this.children[0], silent); + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + } + + return group; + +}; + +/** +* Removes all children from this Group, but does not remove the group from its parent. +* +* The children can be optionally destroyed as they are removed. +* +* You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've +* more than one Game Object sharing the same BaseTexture. +* +* @method Phaser.Group#removeAll +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +* @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. +*/ +Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + if (destroyTexture === undefined) { destroyTexture = false; } + + if (this.children.length === 0) + { + return; + } + + do + { + if (!silent && this.children[0].events) + { + this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this); + } + + var removed = this.removeChild(this.children[0]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true, destroyTexture); + } + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + +}; + +/** +* Removes all children from this group whose index falls beteen the given startIndex and endIndex values. +* +* @method Phaser.Group#removeBetween +* @param {integer} startIndex - The index to start removing children from. +* @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +*/ +Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) { + + if (endIndex === undefined) { endIndex = this.children.length - 1; } + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = 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 (!silent && this.children[i].events) + { + this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this); + } + + var removed = this.removeChild(this.children[i]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true); + } + + if (this.cursor === this.children[i]) + { + this.cursor = null; + } + + i--; + } + + this.updateZ(); + +}; + +/** + * Places each child at a random position within the given Rectangle (or the {@link Phaser.World#bounds World bounds}). + * + * @method Phaser.Group#scatter + * @param {Phaser.Rectangle} [rect=this.game.world.bounds] - A Rectangle. If omitted {@link Phaser.World#bounds} is used. + * @param {boolean} [checkExists=false] - Place only children with exists=true. + */ +Phaser.Group.prototype.scatter = function (rect, checkExists) { + + if (rect == null) { rect = this.game.world.bounds; } + + this.forEach(function (child) { + + child.position.set(rect.randomX, rect.randomY); + + }, null, checkExists); + +}; + +/** + * Orders this Group's children randomly. + * + * This can be more efficient than calling {@link #getRandom} repeatedly. + * + * @method Phaser.Group#shuffle + */ +Phaser.Group.prototype.shuffle = function () { + + Phaser.ArrayUtils.shuffle(this.children); + this.updateZ(); + +}; + +/** +* Destroys this group. +* +* Removes all children, then removes this group from its parent and nulls references. +* +* @method Phaser.Group#destroy +* @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. +*/ +Phaser.Group.prototype.destroy = function (destroyChildren, soft) { + + if (this.game === null || this.ignoreDestroy) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (soft === undefined) { soft = false; } + + this.onDestroy.dispatch(this, destroyChildren, soft); + + this.removeAll(destroyChildren); + + this.cursor = null; + this.filters = null; + this.pendingDestroy = false; + + if (!soft) + { + if (this.parent) + { + this.parent.removeChild(this); + } + + this.game = null; + this.exists = false; + } + +}; + +/** +* Total number of existing children in the group. +* +* @name Phaser.Group#total +* @property {integer} total +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "total", { + + get: function () { + + return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); + + } + +}); + +/** +* Total number of children in this group, regardless of exists/alive status. +* +* @name Phaser.Group#length +* @property {integer} length +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "length", { + + get: function () { + + return this.children.length; + + } + +}); + +/** +* The angle of rotation of the group container, in degrees. +* +* This adjusts the group itself by modifying its local rotation transform. +* +* This has no impact on the rotation/angle properties of the children, but it will update their worldTransform +* and on-screen orientation and position. +* +* @name Phaser.Group#angle +* @property {number} angle +*/ +Object.defineProperty(Phaser.Group.prototype, "angle", { + + get: function() { + return Phaser.Math.radToDeg(this.rotation); + }, + + set: function(value) { + this.rotation = Phaser.Math.degToRad(value); + } + +}); + +/** +* The center x coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerX +* @property {number} centerX +*/ +Object.defineProperty(Phaser.Group.prototype, "centerX", { + + get: function () { + + return this.getBounds(this.parent).centerX; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.halfWidth; + + } + +}); + +/** +* The center y coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerY +* @property {number} centerY +*/ +Object.defineProperty(Phaser.Group.prototype, "centerY", { + + get: function () { + + return this.getBounds(this.parent).centerY; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.halfHeight; + + } + +}); + +/** +* The left coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#left +* @property {number} left +*/ +Object.defineProperty(Phaser.Group.prototype, "left", { + + get: function () { + + return this.getBounds(this.parent).left; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = value + offset; + + } + +}); + +/** +* The right coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#right +* @property {number} right +*/ +Object.defineProperty(Phaser.Group.prototype, "right", { + + get: function () { + + return this.getBounds(this.parent).right; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.width; + + } + +}); + +/** +* The top coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#top +* @property {number} top +*/ +Object.defineProperty(Phaser.Group.prototype, "top", { + + get: function () { + + return this.getBounds(this.parent).top; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset); + + } + +}); + +/** +* The bottom coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#bottom +* @property {number} bottom +*/ +Object.defineProperty(Phaser.Group.prototype, "bottom", { + + get: function () { + + return this.getBounds(this.parent).bottom; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.height; + + } + +}); + +/** +* Aligns this Group within another Game Object, or Rectangle, known as the +* 'container', to one of 9 possible positions. +* +* The container must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the container. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, +* `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, +* `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* container, taking into consideration rotation and scale of its children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignIn +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* Aligns this Group to the side of another Game Object, or Rectangle, known as the +* 'parent', in one of 11 possible positions. +* +* The parent must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the parent. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, +* `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, +* `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` +* and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* parent, taking into consideration rotation and scale of the children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignTo +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* A display object is any object that can be rendered in the Phaser/pixi.js scene graph: +* +* - {@link PIXI.DisplayObject} +* - {@link PIXI.DisplayObjectContainer} +* - {@link Phaser.BitmapText} +* - {@link Phaser.Creature} +* - {@link Phaser.Graphics} +* - {@link Phaser.Group} +* - {@link Phaser.FlexLayer} +* - {@link Phaser.Particles.Arcade.Emitter} +* - {@link Phaser.Physics.P2.BodyDebug} +* - {@link Phaser.SpriteBatch} +* - {@link Phaser.World} +* - {@link Phaser.Rope} +* - {@link Phaser.Stage} +* - {@link PIXI.Sprite} +* - {@link Phaser.Image} +* - {@link Phaser.Button} +* - {@link Phaser.Sprite} +* - {@link Phaser.Bullet} +* - {@link Phaser.Particle} +* - {@link Phaser.Text} +* - {@link Phaser.TilemapLayer} +* - {@link Phaser.TileSprite} +* +* @typedef {object} DisplayObject +*/ +// Documentation stub for linking. + +/** +* The x coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#x +* @property {number} x +*/ + +/** +* The y coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#y +* @property {number} y +*/ + +/** +* The angle of rotation of the group container, in radians. +* +* This will adjust the group container itself by modifying its rotation. +* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#rotation +* @property {number} rotation +*/ + +/** +* The visible state of the group. Non-visible Groups and all of their children are not rendered. +* +* @name Phaser.Group#visible +* @property {boolean} visible +*/ + +/** +* The alpha value of the group container. +* +* @name Phaser.Group#alpha +* @property {number} alpha +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* "This world is but a canvas to our imagination." - Henry David Thoreau +* +* A game has only one world. The world is an abstract place in which all game objects live. It is not bound +* by stage limits and can be any size. You look into the world via cameras. All game objects live within +* the world at world-based coordinates. By default a world is created the same size as your Stage. +* +* @class Phaser.World +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.World = function (game) { + + Phaser.Group.call(this, game, null, '__world', false); + + /** + * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. + * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. + * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. + * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. + * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height); + + /** + * @property {Phaser.Camera} camera - Camera instance. + */ + this.camera = null; + + /** + * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. + * @readonly + */ + this._definedSize = false; + + /** + * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._width = game.width; + + /** + * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._height = game.height; + + this.game.state.onStateChange.add(this.stateChange, this); + +}; + +Phaser.World.prototype = Object.create(Phaser.Group.prototype); +Phaser.World.prototype.constructor = Phaser.World; + +/** +* Initialises the game world. +* +* @method Phaser.World#boot +* @protected +*/ +Phaser.World.prototype.boot = function () { + + this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height); + + this.game.stage.addChild(this); + + this.camera.boot(); + +}; + +/** +* Called whenever the State changes or resets. +* +* It resets the world.x and world.y coordinates back to zero, +* then resets the Camera. +* +* @method Phaser.World#stateChange +* @protected +*/ +Phaser.World.prototype.stateChange = function () { + + this.x = 0; + this.y = 0; + + this.camera.reset(); + +}; + +/** +* Updates the size of this world and sets World.x/y to the given values +* The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. +* +* @method Phaser.World#setBounds +* @param {number} x - Top left most corner of the world. +* @param {number} y - Top left most corner of the world. +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.setBounds = function (x, y, width, height) { + + this._definedSize = true; + this._width = width; + this._height = height; + + this.bounds.setTo(x, y, width, height); + + this.x = x; + this.y = y; + + if (this.camera.bounds) + { + // The Camera can never be smaller than the game size + this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height)); + } + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Updates this world's width and height (but not smaller than any previous {@link #setBounds defined size}). +* +* Phaser uses this to adapt to {@link Phaser.ScaleManager#updateDimensions layout changes}. +* You probably want to use {@link #setBounds} instead. +* +* @method Phaser.World#resize +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.resize = function (width, height) { + + // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size + + if (this._definedSize) + { + if (width < this._width) + { + width = this._width; + } + + if (height < this._height) + { + height = this._height; + } + } + + this.bounds.width = width; + this.bounds.height = height; + + this.game.camera.setBoundsToWorld(); + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Destroyer of worlds. +* +* @method Phaser.World#shutdown +*/ +Phaser.World.prototype.shutdown = function () { + + // World is a Group, so run a soft destruction on this and all children. + this.destroy(true, true); + +}; + +/** +* This will take the given game object and check if its x/y coordinates fall outside of the world bounds. +* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. +* If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. +* +* Please understand there are limitations to this method. For example if you have scaled the World +* then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. +* +* @method Phaser.World#wrap +* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) { + + if (padding === undefined) { padding = 0; } + if (useBounds === undefined) { useBounds = false; } + if (horizontal === undefined) { horizontal = true; } + if (vertical === undefined) { vertical = true; } + + if (!useBounds) + { + if (horizontal && sprite.x + padding < this.bounds.x) + { + sprite.x = this.bounds.right + padding; + } + else if (horizontal && sprite.x - padding > this.bounds.right) + { + sprite.x = this.bounds.left - padding; + } + + if (vertical && sprite.y + padding < this.bounds.top) + { + sprite.y = this.bounds.bottom + padding; + } + else if (vertical && sprite.y - padding > this.bounds.bottom) + { + sprite.y = this.bounds.top - padding; + } + } + else + { + sprite.getBounds(); + + if (horizontal) + { + if ((sprite.x + sprite._currentBounds.width) < this.bounds.x) + { + sprite.x = this.bounds.right; + } + else if (sprite.x > this.bounds.right) + { + sprite.x = this.bounds.left; + } + } + + if (vertical) + { + if ((sprite.y + sprite._currentBounds.height) < this.bounds.top) + { + sprite.y = this.bounds.bottom; + } + else if (sprite.y > this.bounds.bottom) + { + sprite.y = this.bounds.top; + } + } + } + +}; + +/** +* @method Phaser.World#wrapAll +* @param {Phaser.Group} group - A group of sprites. +* @param {boolean} [checkExists=false] - Wrap only sprites having `exists=true`. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrapAll = function (group, checkExists, padding, useBounds, horizontal, vertical) { + + group.forEach(this.wrap, this, checkExists, padding, useBounds, horizontal, vertical); + +}; + +/** +* @name Phaser.World#width +* @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "width", { + + get: function () { + return this.bounds.width; + }, + + set: function (value) { + + if (value < this.game.width) + { + value = this.game.width; + } + + this.bounds.width = value; + this._width = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#height +* @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "height", { + + get: function () { + return this.bounds.height; + }, + + set: function (value) { + + if (value < this.game.height) + { + value = this.game.height; + } + + this.bounds.height = value; + this._height = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#centerX +* @property {number} centerX - Gets the X position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerX", { + + get: function () { + return this.bounds.halfWidth + this.bounds.x; + } + +}); + +/** +* @name Phaser.World#centerY +* @property {number} centerY - Gets the Y position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerY", { + + get: function () { + return this.bounds.halfHeight + this.bounds.y; + } + +}); + +/** +* @name Phaser.World#randomX +* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomX", { + + get: function () { + + if (this.bounds.x < 0) + { + return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x))); + } + else + { + return this.game.rnd.between(this.bounds.x, this.bounds.width); + } + + } + +}); + +/** +* @name Phaser.World#randomY +* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomY", { + + get: function () { + + if (this.bounds.y < 0) + { + return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y))); + } + else + { + return this.game.rnd.between(this.bounds.y, this.bounds.height); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Game object is the main controller for the entire Phaser game. It is responsible +* for handling the boot process, parsing the configuration values, creating the renderer, +* and setting-up all of the Phaser systems, such as physics, sound and input. +* Once that is complete it will start the default State, and then begin the main game loop. +* +* You can access lots of the Phaser systems via the properties on the `game` object. For +* example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on. +* +* Anywhere you can access the `game` property, you can access all of these core systems. +* For example a Sprite has a `game` property, allowing you to talk to the various parts +* of Phaser directly, without having to look after your own references. +* +* In it's most simplest form, a Phaser game can be created by providing the arguments +* to the constructor: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create }); +* ``` +* +* In the example above it is passing in a State object directly. You can also use the State +* Manager to do this: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO); +* game.state.add('Boot', BasicGame.Boot); +* game.state.add('Preloader', BasicGame.Preloader); +* game.state.add('MainMenu', BasicGame.MainMenu); +* game.state.add('Game', BasicGame.Game); +* game.state.start('Boot'); +* ``` +* +* In the example above, 4 States are added to the State Manager, and Phaser is told to +* start running the `Boot` state when it has finished initializing. There are example +* project templates you can use in the Phaser GitHub repo, inside the `resources` folder. +* +* Instead of specifying arguments you can also pass {@link GameConfig a single object} instead: +* +* ```javascript +* var config = { +* width: 800, +* height: 600, +* renderer: Phaser.AUTO, +* antialias: true, +* multiTexture: true, +* state: { +* preload: preload, +* create: create, +* update: update +* } +* } +* +* var game = new Phaser.Game(config); +* ``` +* +* @class Phaser.Game +* @constructor +* @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. +* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. +* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). +* @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body. +* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. +* @param {boolean} [transparent=false] - Use a transparent canvas background or not. +* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) { + + /** + * @property {number} id - Phaser Game ID + * @readonly + */ + this.id = Phaser.GAMES.push(this) - 1; + + /** + * @property {object} config - The Phaser.Game configuration object. + */ + this.config = null; + + /** + * @property {object} physicsConfig - The Phaser.Physics.World configuration object. + */ + this.physicsConfig = physicsConfig; + + /** + * @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted. + * @readonly + * @default + */ + this.parent = ''; + + /** + * The current Game Width in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} width + * @readonly + * @default + */ + this.width = 800; + + /** + * The current Game Height in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} height + * @readonly + * @default + */ + this.height = 600; + + /** + * The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object. + * + * @property {integer} resolution + * @readonly + * @default + */ + this.resolution = 1; + + /** + * @property {integer} _width - Private internal var. + * @private + */ + this._width = 800; + + /** + * @property {integer} _height - Private internal var. + * @private + */ + this._height = 600; + + /** + * @property {boolean} transparent - Use a transparent canvas background or not. + * @default + */ + this.transparent = false; + + /** + * @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead. + * @readonly + * @default + */ + this.antialias = true; + + /** + * Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property. + * To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game + * Configuration object with the property `multiTexture` set to true. It has to be enabled before + * Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it + * via the `game.renderer.setTexturePriority` method. + * + * @property {boolean} multiTexture + * @readonly + * @default + */ + this.multiTexture = false; + + /** + * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * @default + */ + this.preserveDrawingBuffer = false; + + /** + * Clear the Canvas each frame before rendering the display list. + * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. + * This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage. + * @property {boolean} clearBeforeRender + * @default + */ + this.clearBeforeRender = true; + + /** + * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. + * @protected + */ + this.renderer = null; + + /** + * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `render` hooks but not `preRender` or `postRender`; set {@link lockRender} to skip those as well. + * @readonly + */ + this.renderType = Phaser.AUTO; + + /** + * @property {Phaser.StateManager} state - The StateManager. + */ + this.state = null; + + /** + * @property {boolean} isBooted - Whether the game engine is booted, aka available. + * @readonly + */ + this.isBooted = false; + + /** + * @property {boolean} isRunning - Is game running or paused? + * @readonly + */ + this.isRunning = false; + + /** + * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout + * @protected + */ + this.raf = null; + + /** + * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. + */ + this.make = null; + + /** + * @property {Phaser.Cache} cache - Reference to the assets cache. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - Reference to the input manager + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - Reference to the assets loader. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - Reference to the math helper. + */ + this.math = null; + + /** + * @property {Phaser.Net} net - Reference to the network class. + */ + this.net = null; + + /** + * @property {Phaser.ScaleManager} scale - The game scale manager. + */ + this.scale = null; + + /** + * @property {Phaser.SoundManager} sound - Reference to the sound manager. + */ + this.sound = null; + + /** + * @property {Phaser.Stage} stage - Reference to the stage. + */ + this.stage = null; + + /** + * @property {Phaser.Time} time - Reference to the core game clock. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - Reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - Reference to the world. + */ + this.world = null; + + /** + * @property {Phaser.Physics} physics - Reference to the physics manager. + */ + this.physics = null; + + /** + * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. + */ + this.plugins = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. + */ + this.rnd = null; + + /** + * @property {Phaser.Device} device - Contains device information and capabilities. + */ + this.device = Phaser.Device; + + /** + * @property {Phaser.Camera} camera - A handy reference to world.camera. + */ + this.camera = null; + + /** + * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) + */ + this.context = null; + + /** + * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. + */ + this.debug = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. + */ + this.particles = null; + + /** + * @property {Phaser.Create} create - The Asset Generator. + */ + this.create = null; + + /** + * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. + * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. + * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. + * @property {boolean} lockRender + * @default + */ + this.lockRender = false; + + /** + * @property {boolean} pendingDestroy - Destroy the game at the next update. + * @default + */ + this.pendingDestroy = false; + + /** + * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). + * @default + * @readonly + */ + this.stepping = false; + + /** + * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. + * @default + * @readonly + */ + this.pendingStep = false; + + /** + * @property {number} stepCount - When stepping is enabled this contains the current step cycle. + * @default + * @readonly + */ + this.stepCount = 0; + + /** + * @property {Phaser.Signal} onPause - This event is fired when the game pauses. + */ + this.onPause = null; + + /** + * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. + */ + this.onResume = null; + + /** + * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). + */ + this.onBlur = null; + + /** + * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). + */ + this.onFocus = null; + + /** + * @property {boolean} _paused - Is game paused? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _codePaused - Was the game paused via code or a visibility change? + * @private + */ + this._codePaused = false; + + /** + * The ID of the current/last logic update applied this animation frame, starting from 0. + * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` + * @property {integer} currentUpdateID + * @protected + */ + this.currentUpdateID = 0; + + /** + * Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed). + * @property {integer} updatesThisFrame + * @protected + */ + this.updatesThisFrame = 1; + + /** + * Number of renders expected to occur this animation frame. May be 0 if {@link #dropFrames is on} or {@link #forceSingleRender} is off; otherwise it will be 1. + * @property {integer} updatesThisFrame + * @protected + */ + this.rendersThisFrame = 1; + + /** + * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. + * @private + */ + this._deltaTime = 0; + + /** + * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. + * @private + */ + this._lastCount = 0; + + /** + * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. + * @private + */ + this._spiraling = 0; + + /** + * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) + * @private + */ + this._kickstart = true; + + /** + * If the game is struggling to maintain the desired FPS, this signal will be dispatched. + * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. + * @property {Phaser.Signal} fpsProblemNotifier + * @public + */ + this.fpsProblemNotifier = new Phaser.Signal(); + + /** + * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? You can toggle it on the fly. + */ + this.forceSingleUpdate = true; + + /** + * @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update? (During spiraling conditions, {@link #dropFrames} is used instead.) + */ + this.forceSingleRender = true; + + /** + * @property {boolean} dropFrames - When {@link #forceSingleUpdate} is off, skip {@link #updateRender rendering} if logic updates are spiraling upwards. + */ + this.dropFrames = false; + + /** + * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. + * @private + */ + this._nextFpsNotification = 0; + + // Parse the configuration object (if any) + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + this.parseConfig(arguments[0]); + } + else + { + this.config = { enableDebug: true }; + + if (typeof width !== 'undefined') + { + this._width = width; + } + + if (typeof height !== 'undefined') + { + this._height = height; + } + + if (typeof renderer !== 'undefined') + { + 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); + } + + this.device.whenReady(this.boot, this); + + return this; + +}; + +/** +* A configuration object for {@link Phaser.Game}. +* +* @typedef {object} GameConfig +* @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}. +* @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}. +* @property {number|string} [GameConfig.antialias=true] +* @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}. +* @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in. +* @property {string} [GameConfig.canvasId] - `id` attribute value to assign to the game canvas. +* @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas. +* @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}. +* @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange} +* @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing. +* @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production. +* @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO. +* @property {boolean} [GameConfig.forceSetTimeout] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeOut} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available. +* @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen. +* @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked. +* @property {number|string} [GameConfig.height=600] +* @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`. +* @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected. +* @property {object} [GameConfig.physicsConfig] +* @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering. +* @property {number} [GameConfig.renderer=Phaser.AUTO] +* @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels. +* @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices. +* @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen. +* @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}. +* @property {object} [GameConfig.state] +* @property {boolean} [GameConfig.transparent=false] +* @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode. +* @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode. +* @property {number|string} [GameConfig.width=800] +*/ +// Documentation stub for linking. + +Phaser.Game.prototype = { + + /** + * Parses a Game configuration object. + * + * @method Phaser.Game#parseConfig + * @protected + */ + parseConfig: function (config) { + + this.config = config; + + if (config['enableDebug'] === undefined) + { + this.config.enableDebug = true; + } + + if (config['width']) + { + this._width = config['width']; + } + + if (config['height']) + { + this._height = config['height']; + } + + if (config['renderer']) + { + this.renderType = config['renderer']; + } + + if (config['parent']) + { + this.parent = config['parent']; + } + + if (config['transparent'] !== undefined) + { + this.transparent = config['transparent']; + } + + if (config['antialias'] !== undefined) + { + this.antialias = config['antialias']; + } + + if (config['multiTexture'] !== undefined) + { + this.multiTexture = config['multiTexture']; + } + + if (config['resolution']) + { + this.resolution = config['resolution']; + } + + if (config['preserveDrawingBuffer'] !== undefined) + { + this.preserveDrawingBuffer = config['preserveDrawingBuffer']; + } + + 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); + + }, + + /** + * Initialize engine sub modules and start the game. + * + * @method Phaser.Game#boot + * @protected + */ + boot: function () { + + if (this.isBooted) + { + return; + } + + this.onPause = new Phaser.Signal(); + this.onResume = new Phaser.Signal(); + this.onBlur = new Phaser.Signal(); + this.onFocus = new Phaser.Signal(); + + this.isBooted = true; + + PIXI.game = this; + + this.math = Phaser.Math; + + this.scale = new Phaser.ScaleManager(this, this._width, this._height); + this.stage = new Phaser.Stage(this); + + this.setUpRenderer(); + + 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.create = new Phaser.Create(this); + this.plugins = new Phaser.PluginManager(this); + this.net = new Phaser.Net(this); + + this.time.boot(); + this.stage.boot(); + this.world.boot(); + this.scale.boot(); + this.input.boot(); + this.sound.boot(); + this.state.boot(); + + if (this.config['enableDebug']) + { + this.debug = new Phaser.Utils.Debug(this); + this.debug.boot(); + } + else + { + this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {}, isDisabled: true }; + } + + 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._kickstart = true; + + if (window['focus']) + { + if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus)) + { + window.focus(); + } + } + + if (this.config['disableStart']) + { + return; + } + + if (this.cache.isReady) + { + this.raf.start(); + } + else + { + this.cache.onReady.addOnce(function () { + this.raf.start(); + }, this); + } + + }, + + /** + * Displays a Phaser version debug header in the console. + * + * @method Phaser.Game#showDebugHeader + * @protected + */ + showDebugHeader: function () { + + if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner) + { + return; + } + + 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.ie) // https://developer.mozilla.org/en-US/docs/Web/API/Console/log#Browser_compatibility + { + var args = [ + '%c %c %c Phaser CE v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665', + 'background: #fb8cb3', + 'background: #d44a52', + 'color: #ffffff; background: #871905;', + 'background: #d44a52', + 'background: #fb8cb3', + 'background: #ffffff' + ]; + + for (var i = 0; i < 3; i++) + { + if (i < c) + { + args.push('color: #ff2424; background: #fff'); + } + else + { + args.push('color: #959595; background: #fff'); + } + } + + console.log.apply(console, args); + } + else if (window['console']) + { + console.log('Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' | http://phaser.io'); + } + + }, + + /** + * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. + * + * @method Phaser.Game#setUpRenderer + * @protected + */ + setUpRenderer: function () { + + if (!this.device.canvas) + { + // Nothing else to do + throw new Error('Phaser.Game - Cannot create Canvas 2d context, aborting.'); + } + + if (this.config['canvas']) + { + this.canvas = this.config['canvas']; + } + else + { + this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true); + } + + if (this.config['canvasStyle']) + { + this.canvas.style = this.config['canvasStyle']; + } + else + { + this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; + } + + if (this.config['crisp']) + { + Phaser.Canvas.setImageRenderingCrisp(this.canvas); + } + + if ((this.renderType === Phaser.WEBGL) || + (this.renderType === Phaser.WEBGL_MULTI) || + (this.renderType === Phaser.AUTO && this.device.webGL)) + { + if (this.multiTexture || this.renderType === Phaser.WEBGL_MULTI) + { + PIXI.enableMultiTexture(); + this.multiTexture = true; + } + + try + { + this.renderer = new PIXI.WebGLRenderer(this, this.config); + this.renderType = Phaser.WEBGL; + this.context = null; + this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); + this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); + } + catch (webGLRendererError) + { + this.renderer = null; + this.multiTexture = false; + PIXI._enableMultiTextureToggle = false; + + if (this.renderType === Phaser.WEBGL) + { + // No fallback + throw webGLRendererError; + } + } + } + + if (!this.renderer) + { + this.renderer = new PIXI.CanvasRenderer(this, this.config); + this.context = this.renderer.context; + + if (this.renderType === Phaser.AUTO) + { + this.renderType = Phaser.CANVAS; + } + } + + if (this.device.cocoonJS) + { + this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false; + } + + if (this.renderType !== Phaser.HEADLESS) + { + this.stage.smoothed = this.antialias; + + Phaser.Canvas.addToDOM(this.canvas, this.parent, false); + Phaser.Canvas.setTouchAction(this.canvas); + } + + }, + + /** + * Handles WebGL context loss. + * + * @method Phaser.Game#contextLost + * @private + * @param {Event} event - The webglcontextlost event. + */ + contextLost: function (event) { + + event.preventDefault(); + + this.renderer.contextLost = true; + + }, + + /** + * Handles WebGL context restoration. + * + * @method Phaser.Game#contextRestored + * @private + */ + contextRestored: function () { + + this.renderer.initContext(); + + this.cache.clearGLTextures(); + + this.renderer.contextLost = false; + + }, + + /** + * The core game loop. + * + * @method Phaser.Game#update + * @protected + * @param {number} time - The current time as provided by RequestAnimationFrame. + */ + update: function (time) { + + if (this.pendingDestroy) + { + this.destroy(); + return; + } + + this.time.update(time); + + if (this._kickstart) + { + this.updateLogic(this.time.desiredFpsMult); + + // call the game render update exactly once every frame + this.updateRender(this.time.slowMotion * this.time.desiredFps); + + this._kickstart = false; + + return; + } + + // if the logic time is spiraling upwards, skip a frame entirely + if (this._spiraling > 1 && !this.forceSingleUpdate) + { + // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate + if (this.time.time > this._nextFpsNotification) + { + // only permit one fps notification per 10 seconds + this._nextFpsNotification = this.time.time + 10000; + + // dispatch the notification signal + this.fpsProblemNotifier.dispatch(); + } + + // reset the _deltaTime accumulator which will cause all pending late updates to be permanently skipped + this._deltaTime = 0; + this._spiraling = 0; + + if (this.dropFrames) + { + this.rendersThisFrame = 0; + } + else + { + this.updateRender(this.time.slowMotion * this.time.desiredFps); + this.rendersThisFrame = 1; + } + } + else + { + // step size taking into account the slow motion speed + var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps; + + // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals + this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0); + + // call the game update logic multiple times if necessary to "catch up" with dropped frames + // unless forceSingleUpdate is true + var count = 0; + + this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); + + if (this.forceSingleUpdate) + { + this.updatesThisFrame = Math.min(1, this.updatesThisFrame); + } + + if (this.forceSingleRender) + { + this.rendersThisFrame = 1; + } + else + { + this.rendersThisFrame = Math.min(1, this.updatesThisFrame); + } + + while (this._deltaTime >= slowStep) + { + this._deltaTime -= slowStep; + this.currentUpdateID = count; + + this.updateLogic(this.time.desiredFpsMult); + + count++; + + if (this.forceSingleUpdate && count === 1) + { + break; + } + else + { + this.time.refresh(); + } + } + + // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly) + if (count > this._lastCount) + { + this._spiraling++; + } + else if (count < this._lastCount) + { + // looks like it caught up successfully, reset the spiral alert counter + this._spiraling = 0; + } + + this._lastCount = count; + + if (this.rendersThisFrame > 0) + { + this.updateRender(this._deltaTime / slowStep); + } + } + + }, + + /** + * Updates all logic subsystems in Phaser. Called automatically by Game.update. + * + * @method Phaser.Game#updateLogic + * @protected + * @param {number} timeStep - The current timeStep value as determined by Game.update. + */ + updateLogic: function (timeStep) { + + if (!this._paused && !this.pendingStep) + { + if (this.stepping) + { + this.pendingStep = true; + } + + this.time.countUpdate(); + + this.scale.preUpdate(); + this.debug.preUpdate(); + this.camera.preUpdate(); + this.physics.preUpdate(); + this.state.preUpdate(timeStep); + this.plugins.preUpdate(timeStep); + this.stage.preUpdate(); + + this.state.update(); + this.stage.update(); + this.tweens.update(); + this.sound.update(); + this.input.update(); + this.physics.update(); + this.plugins.update(); + + this.stage.postUpdate(); + this.plugins.postUpdate(); + } + else + { + // Scaling and device orientation changes are still reflected when paused. + this.scale.pauseUpdate(); + this.state.pauseUpdate(timeStep); + this.debug.preUpdate(); + this.input.pauseUpdate(); + } + + this.stage.updateTransform(); + + }, + + /** + * Runs the Render cycle. + * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. + * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. + * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. + * After this State.render is called. Any rendering that happens here will take place on-top of the display list. + * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. + * This method is called automatically by Game.update, you don't need to call it directly. + * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. + * Phaser will only render when this boolean is `false`. + * + * @method Phaser.Game#updateRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + updateRender: function (elapsedTime) { + + if (this.lockRender) + { + return; + } + + this.time.countRender(); + + this.state.preRender(elapsedTime); + + if (this.renderType !== Phaser.HEADLESS) + { + this.renderer.render(this.stage); + + this.plugins.render(elapsedTime); + + this.state.render(elapsedTime); + } + + this.plugins.postRender(elapsedTime); + + }, + + /** + * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) + * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! + * + * @method Phaser.Game#enableStep + */ + enableStep: function () { + + this.stepping = true; + this.pendingStep = false; + this.stepCount = 0; + + }, + + /** + * Disables core game loop stepping. + * + * @method Phaser.Game#disableStep + */ + disableStep: function () { + + this.stepping = false; + this.pendingStep = false; + + }, + + /** + * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. + * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. + * + * @method Phaser.Game#step + */ + step: function () { + + this.pendingStep = false; + this.stepCount++; + + }, + + /** + * Nukes the entire game from orbit. + * + * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. + * + * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM + * and resets the PIXI default renderer. + * + * To destroy the game during an update callback, set {@link #pendingDestroy} instead. + * + * @method Phaser.Game#destroy + */ + destroy: function () { + + this.raf.stop(); + + if (this.debug.destroy) + { + this.debug.destroy(); + } + + this.state.destroy(); + this.sound.destroy(); + this.scale.destroy(); + this.stage.destroy(); + this.input.destroy(); + this.physics.destroy(); + this.plugins.destroy(); + + this.debug = null; + this.state = null; + this.sound = null; + this.scale = null; + this.stage = null; + this.input = null; + this.physics = null; + this.plugins = null; + + this.cache = null; + this.load = null; + this.time = null; + this.world = null; + + this.isBooted = false; + + this.renderer.destroy(false); + + Phaser.Canvas.removeFromDOM(this.canvas); + + PIXI.defaultRenderer = null; + + Phaser.GAMES[this.id] = null; + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gamePaused + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gamePaused: function (event) { + + // If the game is already paused it was done via game code, so don't re-pause it + if (!this._paused) + { + this._paused = true; + + this.time.gamePaused(); + + if (this.sound.muteOnPause) + { + this.sound.setMute(); + } + + this.onPause.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = true; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gameResumed + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gameResumed: function (event) { + + // Game is paused, but wasn't paused via code, so resume it + if (this._paused && !this._codePaused) + { + this._paused = false; + + this.time.gameResumed(); + + this.input.reset(); + + if (this.sound.muteOnPause) + { + this.sound.unsetMute(); + } + + this.onResume.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = false; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusLoss + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusLoss: function (event) { + + this.onBlur.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gamePaused(event); + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusGain + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusGain: function (event) { + + this.onFocus.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gameResumed(event); + } + + } + +}; + +Phaser.Game.prototype.constructor = Phaser.Game; + +/** +* The paused state of the Game. A paused game doesn't update any of its subsystems. +* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. +* @name Phaser.Game#paused +* @property {boolean} paused - Gets and sets the paused state of the Game. +*/ +Object.defineProperty(Phaser.Game.prototype, "paused", { + + get: function () { + return this._paused; + }, + + set: function (value) { + + if (value === true) + { + if (this._paused === false) + { + this._paused = true; + this.sound.setMute(); + this.time.gamePaused(); + this.onPause.dispatch(this); + } + this._codePaused = true; + } + else + { + if (this._paused) + { + this._paused = false; + this.input.reset(); + this.sound.unsetMute(); + this.time.gameResumed(); + this.onResume.dispatch(this); + } + this._codePaused = false; + } + + } + +}); + +/** + * + * "Deleted code is debugged code." - Jeff Sickel + * + * ヽ(〃^▽^〃)ノ + * +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. +* The Input manager is updated automatically by the core game loop. +* +* @class Phaser.Input +* @constructor +* @param {Phaser.Game} game - Current game instance. +*/ +Phaser.Input = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. + * @default + */ + this.hitCanvas = null; + + /** + * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. + * @default + */ + this.hitContext = null; + + /** + * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. + * To add a callback to this array please use `Input.addMoveCallback`. + * @property {array} moveCallbacks + * @protected + */ + this.moveCallbacks = []; + + /** + * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandler = null; + + /** + * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandlerContext = null; + + /** + * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. + * @default + */ + this.pollRate = 0; + + /** + * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. + * + * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. + * @default + */ + this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE; + + /** + * @property {Phaser.Point} position - A point object representing the current position of the Pointer. + * @default + */ + this.position = null; + + /** + * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. + */ + this.speed = null; + + /** + * A Circle object centered on the x/y screen coordinates of the Input. + * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. + * @property {Phaser.Circle} circle + */ + this.circle = null; + + /** + * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. + */ + this.scale = null; + + /** + * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1. + * @default -1 (Limited by total pointers.) + */ + this.maxPointers = -1; + + /** + * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. + * @default + */ + this.tapRate = 200; + + /** + * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. + * @default + */ + this.doubleTapRate = 300; + + /** + * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. + * @default + */ + this.holdRate = 2000; + + /** + * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. + * @default + */ + this.justPressedRate = 200; + + /** + * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . + * @default + */ + this.justReleasedRate = 200; + + /** + * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. + * The history is cleared each time the Pointer is pressed down. + * The history is updated at the rate specified in Input.pollRate + * @property {boolean} recordPointerHistory + * @default + */ + this.recordPointerHistory = false; + + /** + * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. + * @default + */ + this.recordRate = 100; + + /** + * The total number of entries that can be recorded into the Pointer objects tracking history. + * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. + * @property {number} recordLimit + * @default + */ + this.recordLimit = 100; + + /** + * An array of callbacks that will be fired every time a native touch start or touch end event (pointerdown or pointerup when using Pointer events) is received from the browser. + * This is used internally to handle audio and video unlocking on mobile devices. + * To add a callback to this array please use `Input.addTouchLockCallback`. + * @property {array} touchLockCallbacks + * @protected + */ + this.touchLockCallbacks = []; + + /** + * @property {Phaser.Pointer} pointer1 - A Pointer object. + */ + this.pointer1 = null; + + /** + * @property {Phaser.Pointer} pointer2 - A Pointer object. + */ + this.pointer2 = null; + + /** + * @property {Phaser.Pointer} pointer3 - A Pointer object. + */ + this.pointer3 = null; + + /** + * @property {Phaser.Pointer} pointer4 - A Pointer object. + */ + this.pointer4 = null; + + /** + * @property {Phaser.Pointer} pointer5 - A Pointer object. + */ + this.pointer5 = null; + + /** + * @property {Phaser.Pointer} pointer6 - A Pointer object. + */ + this.pointer6 = null; + + /** + * @property {Phaser.Pointer} pointer7 - A Pointer object. + */ + this.pointer7 = null; + + /** + * @property {Phaser.Pointer} pointer8 - A Pointer object. + */ + this.pointer8 = null; + + /** + * @property {Phaser.Pointer} pointer9 - A Pointer object. + */ + this.pointer9 = null; + + /** + * @property {Phaser.Pointer} pointer10 - A Pointer object. + */ + this.pointer10 = null; + + /** + * An array of non-mouse pointers that have been added to the game. + * The properties `pointer1..N` are aliases for `pointers[0..N-1]`. + * @property {Phaser.Pointer[]} pointers + * @public + * @readonly + */ + this.pointers = []; + + /** + * The most recently active Pointer object. + * + * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. + * + * @property {Phaser.Pointer} activePointer + */ + this.activePointer = null; + + /** + * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. + * + * @property {Pointer} mousePointer + */ + this.mousePointer = null; + + /** + * The Mouse Input manager. + * + * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Mouse} mouse + */ + this.mouse = null; + + /** + * The Keyboard Input manager. + * + * @property {Phaser.Keyboard} keyboard + */ + this.keyboard = null; + + /** + * The Touch Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Touch} touch + */ + this.touch = null; + + /** + * The MSPointer Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.MSPointer} mspointer + */ + this.mspointer = null; + + /** + * The Gamepad Input manager. + * + * @property {Phaser.Gamepad} gamepad + */ + this.gamepad = null; + + /** + * If the Input Manager has been reset locked then all calls made to InputManager.reset, + * such as from a State change, are ignored. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is pressed down. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onDown + */ + this.onDown = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is released. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onUp + */ + this.onUp = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is tapped. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {boolean} True if this was a double tap. + * + * @property {Phaser.Signal} onTap + */ + this.onTap = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is held down. + * It is sent one argument: + * + * - {Phaser.Pointer} The pointer that caused the event. + * + * @property {Phaser.Signal} onHold + */ + this.onHold = null; + + /** + * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. + * This is useful when stacking UI layers. Set to zero to disable. + * @property {number} minPriorityID + * @default + */ + this.minPriorityID = 0; + + /** + * A list of interactive objects. The InputHandler components add and remove themselves from this list. + * @property {Phaser.ArraySet} interactiveItems + */ + this.interactiveItems = new Phaser.ArraySet(); + + /** + * @property {Phaser.Point} _localPoint - Internal cache var. + * @private + */ + this._localPoint = new Phaser.Point(); + + /** + * @property {number} _pollCounter - Internal var holding the current poll counter. + * @private + */ + this._pollCounter = 0; + + /** + * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. + * @private + */ + this._oldPosition = null; + + /** + * @property {number} _x - x coordinate of the most recent Pointer event + * @private + */ + this._x = 0; + + /** + * @property {number} _y - Y coordinate of the most recent Pointer event + * @private + */ + this._y = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_TOUCH_COMBINE = 2; + +/** +* The maximum number of pointers that can be added. This excludes the mouse pointer. +* @constant +* @type {integer} +*/ +Phaser.Input.MAX_POINTERS = 10; + +Phaser.Input.prototype = { + + /** + * Starts the Input Manager running. + * + * @method Phaser.Input#boot + * @protected + */ + boot: function () { + + this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR); + this.addPointer(); + this.addPointer(); + + this.mouse = new Phaser.Mouse(this.game); + this.touch = new Phaser.Touch(this.game); + this.mspointer = new Phaser.MSPointer(this.game); + + if (Phaser.Keyboard) + { + this.keyboard = new Phaser.Keyboard(this.game); + } + + if (Phaser.Gamepad) + { + this.gamepad = new Phaser.Gamepad(this.game); + } + + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + + this.scale = new Phaser.Point(1, 1); + this.speed = new Phaser.Point(); + this.position = new Phaser.Point(); + this._oldPosition = new Phaser.Point(); + + this.circle = new Phaser.Circle(0, 0, 44); + + this.activePointer = this.mousePointer; + + this.hitCanvas = Phaser.CanvasPool.create(this, 1, 1); + this.hitContext = this.hitCanvas.getContext('2d'); + + this.mouse.start(); + if (!this.game.device.mspointer) + { + // Chrome >= 55 fires both PointerEvent and TouchEvent. + // Pick only one. + this.touch.start(); + } + this.mspointer.start(); + this.mousePointer.active = true; + + if (this.keyboard) + { + this.keyboard.start(); + } + + var _this = this; + + this._onClickTrampoline = function (event) { + _this.onClickTrampoline(event); + }; + + this.game.canvas.addEventListener('click', this._onClickTrampoline, false); + + }, + + /** + * Stops all of the Input Managers from running. + * + * @method Phaser.Input#destroy + */ + destroy: function () { + + this.mouse.stop(); + this.touch.stop(); + this.mspointer.stop(); + + if (this.keyboard) + { + this.keyboard.stop(); + } + + if (this.gamepad) + { + this.gamepad.stop(); + } + + this.moveCallbacks = []; + + Phaser.CanvasPool.remove(this); + + this.game.canvas.removeEventListener('click', this._onClickTrampoline); + + }, + + /** + * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. + * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to + * interact with. It works by polling all of the valid game objects, and then slowly discounting those + * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). + * + * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid + * for input and overlap with the Pointer. If you need fine-grained control over which of the items is + * selected then you can use this callback to do so. + * + * The callback will be sent 3 parameters: + * + * 1) A reference to the Phaser.Pointer object that is processing the Items. + * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. + * 3) The current 'favorite' candidate, based on its priorityID and position in the display list. + * + * Your callback MUST return one of the candidates sent to it. + * + * @method Phaser.Input#setInteractiveCandidateHandler + * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. + * @param {object} context - The context in which the callback will be called. + */ + setInteractiveCandidateHandler: function (callback, context) { + + this.customCandidateHandler = callback; + this.customCandidateHandlerContext = context; + + }, + + /** + * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. + * + * The callback will be sent 4 parameters: + * + * A reference to the Phaser.Pointer object that moved, + * The x position of the pointer, + * The y position, + * A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down). + * + * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best + * to only use if you've limited input to a single pointer (i.e. mouse or touch). + * + * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. + * + * @method Phaser.Input#addMoveCallback + * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. + * @param {object} context - The context in which the callback will be called. + */ + addMoveCallback: function (callback, context) { + + this.moveCallbacks.push({ callback: callback, context: context }); + + }, + + + /** + * Adds a callback that is fired when a browser touchstart/pointerdown or touchend/pointerup event is received. + * + * This is used internally to handle audio and video unlocking on mobile devices. + * + * If the callback returns 'true' then the callback is automatically deleted once invoked. + * + * The callback is added to the {@link #touchLockCallbacks} array and should be removed with {@link #removeTouchLockCallback}. + * + * @method Phaser.Input#addTouchLockCallback + * @param {function} callback - The callback that will be called when a touchstart event is received. + * @param {object} context - The context in which the callback will be called. + * @param {boolean} [onEnd=false] - Will the callback fire on a touchstart/pointerdown (default) or touchend/pointerup event? + */ + addTouchLockCallback: function (callback, context, onEnd) { + + if (onEnd === undefined) { onEnd = false; } + + this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd }); + + }, + + /** + * Removes the callback at the defined index from the {@link #touchLockCallbacks} array + * + * @method Phaser.Input#removeTouchLockCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + * @return {boolean} True if the callback was deleted, otherwise false. + */ + removeTouchLockCallback: function (callback, context) { + + var i = this.touchLockCallbacks.length; + + while (i--) + { + if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context) + { + this.touchLockCallbacks.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Execute any {@link #touchLockCallbacks} of the given type. + * + * @method Phaser.Input#executeTouchLockCallbacks + * @private + * @param {boolean} onEnd - Execute the touchend/pointerup callbacks (true) or the touchstart/pointerdown callbacks (false). Required! + * @param {Event} event - The native event from the browser. + */ + executeTouchLockCallbacks: function (onEnd, event) { + var i = this.touchLockCallbacks.length; + + while (i--) + { + var cb = this.touchLockCallbacks[i]; + + if (cb.onEnd === onEnd && cb.callback.call(cb.context, this, event)) + { + this.touchLockCallbacks.splice(i, 1); + } + } + }, + + /** + * Removes the callback from the Phaser.Input.moveCallbacks array. + * + * @method Phaser.Input#deleteMoveCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + */ + deleteMoveCallback: function (callback, context) { + + var i = this.moveCallbacks.length; + + while (i--) + { + if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context) + { + this.moveCallbacks.splice(i, 1); + return; + } + } + + }, + + /** + * Add a new Pointer object to the Input Manager. + * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. + * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). + * + * @method Phaser.Input#addPointer + * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. + */ + addPointer: function () { + + if (this.pointers.length >= Phaser.Input.MAX_POINTERS) + { + console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached."); + return null; + } + + var id = this.pointers.length + 1; + var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.CONTACT); + + this.pointers.push(pointer); + this['pointer' + id] = pointer; + + return pointer; + + }, + + /** + * Updates the Input Manager. Called by the core Game loop. + * + * @method Phaser.Input#update + * @protected + */ + update: function () { + + if (this.keyboard) + { + this.keyboard.update(); + } + + if (this.pollRate > 0 && this._pollCounter < this.pollRate) + { + this._pollCounter++; + return; + } + + this.speed.x = this.position.x - this._oldPosition.x; + this.speed.y = this.position.y - this._oldPosition.y; + + this._oldPosition.copyFrom(this.position); + this.mousePointer.update(); + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].update(); + } + + this._pollCounter = 0; + + }, + + /** + * Update method while paused. + * + * @method Phaser.Input#pauseUpdate + * @private + */ + pauseUpdate: function () { + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + }, + + /** + * Reset all of the Pointers and Input states. + * + * The optional `hard` parameter will reset any events or callbacks that may be bound. + * Input.reset is called automatically during a State change or if a game loses focus / visibility. + * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. + * + * @method Phaser.Input#reset + * @public + * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. + */ + reset: function (hard) { + + if (!this.game.isBooted || this.resetLocked) + { + return; + } + + if (hard === undefined) { hard = false; } + + this.mousePointer.reset(); + + if (this.keyboard) + { + this.keyboard.reset(hard); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].reset(); + } + + if (this.game.canvas.style.cursor !== 'none') + { + this.game.canvas.style.cursor = ''; + } + + if (hard) + { + this.onDown.dispose(); + this.onUp.dispose(); + this.onTap.dispose(); + this.onHold.dispose(); + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + this.moveCallbacks = []; + } + + this._pollCounter = 0; + + }, + + /** + * Resets the speed and old position properties. + * + * @method Phaser.Input#resetSpeed + * @param {number} x - Sets the oldPosition.x value. + * @param {number} y - Sets the oldPosition.y value. + */ + resetSpeed: function (x, y) { + + this._oldPosition.setTo(x, y); + this.speed.setTo(0, 0); + + }, + + /** + * Find the first free Pointer object and start it, passing in the event data. + * This is called automatically by Phaser.Touch and Phaser.MSPointer. + * + * @method Phaser.Input#startPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. + */ + startPointer: function (event) { + + if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers) + { + return null; + } + + if (!this.pointer1.active) + { + return this.pointer1.start(event); + } + + if (!this.pointer2.active) + { + return this.pointer2.start(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (!pointer.active) + { + return pointer.start(event); + } + } + + return null; + + }, + + /** + * Updates the matching Pointer object, passing in the event data. + * This is called automatically and should not normally need to be invoked. + * + * @method Phaser.Input#updatePointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. + */ + updatePointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.move(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.move(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.move(event); + } + } + + return null; + + }, + + /** + * Stops the matching Pointer object, passing in the event data. + * + * @method Phaser.Input#stopPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. + */ + stopPointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.stop(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.stop(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.stop(event); + } + } + + return null; + + }, + + /** + * Returns the total number of active pointers, not exceeding the specified limit + * + * @name Phaser.Input#countActivePointers + * @private + * @property {integer} [limit=(max pointers)] - Stop counting after this. + * @return {integer} The number of active pointers, or limit - whichever is less. + */ + countActivePointers: function (limit) { + + if (limit === undefined) { limit = this.pointers.length; } + + var count = limit; + + for (var i = 0; i < this.pointers.length && count > 0; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active) + { + count--; + } + } + + return (limit - count); + + }, + + /** + * Get the first Pointer with the given active state. + * + * @method Phaser.Input#getPointer + * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. + */ + getPointer: function (isActive) { + + if (isActive === undefined) { isActive = false; } + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active === isActive) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `identifier` property matches the given identifier value. + * + * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down, and is not fixed once set. + * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. + * + * @method Phaser.Input#getPointerFromIdentifier + * @param {number} identifier - The Pointer.identifier value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromIdentifier: function (identifier) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.identifier === identifier) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `pointerId` property matches the given value. + * + * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down if the browser recycles it. + * + * @method Phaser.Input#getPointerFromId + * @param {number} pointerId - The `pointerId` (not 'id') value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromId: function (pointerId) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.pointerId === pointerId) + { + return pointer; + } + } + + return null; + + }, + + /** + * This will return the local coordinates of the specified displayObject based on the given Pointer. + * + * @method Phaser.Input#getLocalPosition + * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. + * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. + * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. + */ + getLocalPosition: function (displayObject, pointer, output) { + + if (output === undefined) { output = new Phaser.Point(); } + + var wt = displayObject.worldTransform; + var id = 1 / (wt.a * wt.d + wt.c * -wt.b); + + return output.setTo( + wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id, + wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id + ); + + }, + + /** + * Tests if the pointer hits the given object. + * + * @method Phaser.Input#hitTest + * @param {DisplayObject} displayObject - The displayObject to test for a hit. + * @param {Phaser.Pointer} pointer - The pointer to use for the test. + * @param {Phaser.Point} localPoint - The local translated point. + */ + hitTest: function (displayObject, pointer, localPoint) { + + if (!displayObject.worldVisible) + { + return false; + } + + this.getLocalPosition(displayObject, pointer, this._localPoint); + + localPoint.copyFrom(this._localPoint); + + if (displayObject.hitArea && displayObject.hitArea.contains) + { + return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y)); + } + else if (Phaser.Creature && displayObject instanceof Phaser.Creature) { + var width = Math.abs(displayObject.width); + var height = Math.abs(displayObject.height); + var x1 = displayObject.x - (width * displayObject.anchorX); + + if (this.game.camera.x + pointer.x >= x1 && this.game.camera.x + pointer.x < x1 + width) + { + var y1 = displayObject.y - (height * displayObject.anchorY); + + if (this.game.camera.y + pointer.y >= y1 && this.game.camera.y + pointer.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.TileSprite) + { + var width = displayObject.width; + var height = displayObject.height; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof PIXI.Sprite) + { + var width = displayObject.texture.frame.width / displayObject.texture.baseTexture.resolution; + var height = displayObject.texture.frame.height / displayObject.texture.baseTexture.resolution; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.Graphics) + { + for (var i = 0; i < displayObject.graphicsData.length; i++) + { + var data = displayObject.graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // Only deal with fills.. + if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y)) + { + return true; + } + } + } + + // Didn't hit the parent, does it have any children? + + for (var i = 0; i < displayObject.children.length; i++) + { + if (this.hitTest(displayObject.children[i], pointer, localPoint)) + { + return true; + } + } + + return false; + }, + + /** + * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. + * + * @method Phaser.Input#onClickTrampoline + * @private + */ + onClickTrampoline: function () { + + // It might not always be the active pointer, but this does work on + // Desktop browsers (read: IE) with Mouse or MSPointer input. + this.activePointer.processClickTrampolines(); + + } + +}; + +Phaser.Input.prototype.constructor = Phaser.Input; + +/** +* The X coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. +* @name Phaser.Input#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Input.prototype, "x", { + + get: function () { + return this._x; + }, + + set: function (value) { + this._x = Math.floor(value); + } + +}); + +/** +* The Y coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. +* @name Phaser.Input#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Input.prototype, "y", { + + get: function () { + return this._y; + }, + + set: function (value) { + this._y = Math.floor(value); + } + +}); + +/** +* True if the Input is currently poll rate locked. +* @name Phaser.Input#pollLocked +* @property {boolean} pollLocked +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "pollLocked", { + + get: function () { + return (this.pollRate > 0 && this._pollCounter < this.pollRate); + } + +}); + +/** +* The total number of inactive Pointers. +* @name Phaser.Input#totalInactivePointers +* @property {number} totalInactivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", { + + get: function () { + return this.pointers.length - this.countActivePointers(); + } + +}); + +/** +* The total number of active Pointers, not counting the mouse pointer. +* @name Phaser.Input#totalActivePointers +* @property {integers} totalActivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", { + + get: function () { + return this.countActivePointers(); + } + +}); + +/** +* The world X coordinate of the most recently active pointer. +* @name Phaser.Input#worldX +* @property {number} worldX - The world X coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldX", { + + get: function () { + return this.game.camera.view.x + this.x; + } + +}); + +/** +* The world Y coordinate of the most recently active pointer. +* @name Phaser.Input#worldY +* @property {number} worldY - The world Y coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldY", { + + get: function () { + return this.game.camera.view.y + this.y; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Mouse class is responsible for handling all aspects of mouse interaction with the browser. +* +* It captures and processes mouse events that happen on the game canvas object. +* It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released +* when not over the game. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object +* which normalises all game input for you, including accurate button handling. +* +* @class Phaser.Mouse +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Mouse = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down. + */ + this.mouseDownCallback = null; + + /** + * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state. + */ + this.mouseUpCallback = null; + + /** + * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas. + */ + this.mouseOutCallback = null; + + /** + * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). + */ + this.mouseOverCallback = null; + + /** + * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used. + */ + this.mouseWheelCallback = null; + + /** + * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + */ + this.capture = false; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + * @default + */ + this.button = -1; + + /** + * The direction of the _last_ mousewheel usage 1 for up -1 for down. + * @property {number} wheelDelta + */ + this.wheelDelta = 0; + + /** + * Mouse input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true. + * @default + */ + this.locked = false; + + /** + * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas. + * @default + */ + this.stopOnGameOut = false; + + /** + * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state. + * @default + */ + this.pointerLock = new Phaser.Signal(); + + /** + * The browser mouse DOM event. Will be null if no mouse event has ever been received. + * Access this property only inside a Mouse event handler and do not keep references to it. + * @property {MouseEvent|null} event + * @default + */ + this.event = null; + + /** + * @property {function} _onMouseDown - Internal event handler reference. + * @private + */ + this._onMouseDown = null; + + /** + * @property {function} _onMouseMove - Internal event handler reference. + * @private + */ + this._onMouseMove = null; + + /** + * @property {function} _onMouseUp - Internal event handler reference. + * @private + */ + this._onMouseUp = null; + + /** + * @property {function} _onMouseOut - Internal event handler reference. + * @private + */ + this._onMouseOut = null; + + /** + * @property {function} _onMouseOver - Internal event handler reference. + * @private + */ + this._onMouseOver = null; + + /** + * @property {function} _onMouseWheel - Internal event handler reference. + * @private + */ + this._onMouseWheel = null; + + /** + * Wheel proxy event object, if required. Shared for all wheel events for this mouse. + * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent + * @private + */ + this._wheelEvent = null; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.NO_BUTTON = -1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.LEFT_BUTTON = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.MIDDLE_BUTTON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.RIGHT_BUTTON = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.BACK_BUTTON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.FORWARD_BUTTON = 4; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_UP = 1; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_DOWN = -1; + +Phaser.Mouse.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Mouse#start + */ + start: function () { + + if (this.game.device.android && this.game.device.chrome === false) + { + // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ... + return; + } + + if (this._onMouseDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onMouseDown = function (event) { + return _this.onMouseDown(event); + }; + + this._onMouseMove = function (event) { + return _this.onMouseMove(event); + }; + + this._onMouseUp = function (event) { + return _this.onMouseUp(event); + }; + + this._onMouseUpGlobal = function (event) { + return _this.onMouseUpGlobal(event); + }; + + this._onMouseOutGlobal = function (event) { + return _this.onMouseOutGlobal(event); + }; + + this._onMouseOut = function (event) { + return _this.onMouseOut(event); + }; + + this._onMouseOver = function (event) { + return _this.onMouseOver(event); + }; + + this._onMouseWheel = function (event) { + return _this.onMouseWheel(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('mousedown', this._onMouseDown, true); + canvas.addEventListener('mousemove', this._onMouseMove, true); + canvas.addEventListener('mouseup', this._onMouseUp, true); + + if (!this.game.device.cocoonJS) + { + window.addEventListener('mouseup', this._onMouseUpGlobal, true); + window.addEventListener('mouseout', this._onMouseOutGlobal, true); + canvas.addEventListener('mouseover', this._onMouseOver, true); + canvas.addEventListener('mouseout', this._onMouseOut, true); + } + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.addEventListener(wheelEvent, this._onMouseWheel, true); + + if (wheelEvent === 'mousewheel') + { + this._wheelEvent = new WheelEventProxy(-1/40, 1); + } + else if (wheelEvent === 'DOMMouseScroll') + { + this._wheelEvent = new WheelEventProxy(1, 1); + } + } + + }, + + /** + * The internal method that handles the mouse down event from the browser. + * @method Phaser.Mouse#onMouseDown + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseDown: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseDownCallback) + { + this.mouseDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.start(event); + + }, + + /** + * The internal method that handles the mouse move event from the browser. + * @method Phaser.Mouse#onMouseMove + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseMoveCallback) + { + this.mouseMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.move(event); + + }, + + /** + * The internal method that handles the mouse up event from the browser. + * @method Phaser.Mouse#onMouseUp + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUp: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.Mouse#onMouseUpGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUpGlobal: function (event) { + + if (!this.input.mousePointer.withinGame) + { + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + }, + + /** + * The internal method that handles the mouse out event from the window. + * + * @method Phaser.Mouse#onMouseOutGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOutGlobal: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (!this.input.enabled || !this.enabled) + { + return; + } + + // If we get a mouseout event from the window then basically + // something serious has gone down, usually along the lines of + // the browser opening a context-menu or similar. + // On OS X Chrome especially this is bad news, as it blocks + // us then getting a mouseup event, so we need to force that through. + // + // No matter what, we must cancel the left and right buttons + + this.input.mousePointer.stop(event); + + // Clear the button states (again?) + this.input.mousePointer.resetButtons(); + + }, + + /** + * The internal method that handles the mouse out event from the browser. + * + * @method Phaser.Mouse#onMouseOut + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (this.mouseOutCallback) + { + this.mouseOutCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.stopOnGameOut) + { + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + this.input.interactiveItems.callAll('_pointerOutHandler', this.input.mousePointer); + + }, + + /** + * The internal method that handles the mouse over event from the browser. + * + * @method Phaser.Mouse#onMouseOver + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = true; + + if (this.mouseOverCallback) + { + this.mouseOverCallback.call(this.callbackContext, event); + } + + }, + + /** + * The internal method that handles the mouse wheel event from the browser. + * + * @method Phaser.Mouse#onMouseWheel + * @param {MouseEvent} event - The native event from the browser. + */ + onMouseWheel: function (event) { + + if (this._wheelEvent) { + event = this._wheelEvent.bindEvent(event); + } + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + // reverse detail for firefox + this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1); + + if (this.mouseWheelCallback) + { + this.mouseWheelCallback.call(this.callbackContext, event); + } + + }, + + /** + * If the browser supports it you can request that the pointer be locked to the browser window. + * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key. + * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'. + * @method Phaser.Mouse#requestPointerLock + */ + requestPointerLock: function () { + + if (this.game.device.pointerLock) + { + var element = this.game.canvas; + + element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; + + element.requestPointerLock(); + + var _this = this; + + this._pointerLockChange = function (event) { + return _this.pointerLockChange(event); + }; + + document.addEventListener('pointerlockchange', this._pointerLockChange, true); + document.addEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true); + } + + }, + + /** + * Internal pointerLockChange handler. + * + * @method Phaser.Mouse#pointerLockChange + * @param {Event} event - The native event from the browser. This gets stored in Mouse.event. + */ + pointerLockChange: function (event) { + + var element = this.game.canvas; + + if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) + { + // Pointer was successfully locked + this.locked = true; + this.pointerLock.dispatch(true, event); + } + else + { + // Pointer was unlocked + this.locked = false; + this.pointerLock.dispatch(false, event); + } + + }, + + /** + * Internal release pointer lock handler. + * @method Phaser.Mouse#releasePointerLock + */ + releasePointerLock: function () { + + document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; + + document.exitPointerLock(); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + }, + + /** + * Stop the event listeners. + * @method Phaser.Mouse#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('mousedown', this._onMouseDown, true); + canvas.removeEventListener('mousemove', this._onMouseMove, true); + canvas.removeEventListener('mouseup', this._onMouseUp, true); + canvas.removeEventListener('mouseover', this._onMouseOver, true); + canvas.removeEventListener('mouseout', this._onMouseOut, true); + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.removeEventListener(wheelEvent, this._onMouseWheel, true); + } + + window.removeEventListener('mouseup', this._onMouseUpGlobal, true); + window.removeEventListener('mouseout', this._onMouseOutGlobal, true); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + } + +}; + +Phaser.Mouse.prototype.constructor = Phaser.Mouse; + +/* jshint latedef:nofunc */ +/** +* A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel' +* events to 'wheel'-like events. +* +* See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode. +* +* @method Phaser.Mouse#WheelEventProxy +* @private +* @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. +* @param {integer} deltaMode - The reported delta mode. +*/ +function WheelEventProxy (scaleFactor, deltaMode) { + + /** + * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. + * @private + */ + this._scaleFactor = scaleFactor; + + /** + * @property {number} _deltaMode - The reported delta mode. + * @private + */ + this._deltaMode = deltaMode; + + /** + * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit. + * @private + */ + this.originalEvent = null; + +} + +WheelEventProxy.prototype = {}; +WheelEventProxy.prototype.constructor = WheelEventProxy; + +WheelEventProxy.prototype.bindEvent = function (event) { + + // Generate stubs automatically + if (!WheelEventProxy._stubsGenerated && event) + { + var makeBinder = function (name) { + + return function () { + var v = this.originalEvent[name]; + return typeof v !== 'function' ? v : v.bind(this.originalEvent); + }; + + }; + + for (var prop in event) + { + if (!(prop in WheelEventProxy.prototype)) + { + Object.defineProperty(WheelEventProxy.prototype, prop, { + get: makeBinder(prop) + }); + } + } + WheelEventProxy._stubsGenerated = true; + } + + this.originalEvent = event; + return this; + +}; + +Object.defineProperties(WheelEventProxy.prototype, { + "type": { value: "wheel" }, + "deltaMode": { get: function () { return this._deltaMode; } }, + "deltaY": { + get: function () { + return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0; + } + }, + "deltaX": { + get: function () { + return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0; + } + }, + "deltaZ": { value: 0 } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The MSPointer class handles {@link https://developers.google.com/web/updates/2016/10/pointer-events Pointer-event} interactions with the game via a dedicated {@link Phaser.Pointer}. (It's named after the nonstandard {@link https://msdn.microsoft.com/library/hh673557(v=vs.85).aspx MSPointerEvent} since that was the first browser implementation.) +* +* It's {@link http://caniuse.com/#feat=pointer currently supported in IE 10+, Edge, Chrome (including Android), and Opera}. +* +* You should not normally access this class directly, but instead use a {@link Phaser.Pointer} object which +* normalises all game input for you including accurate button handling. +* +* Please note that at the current time of writing Phaser does not yet support chorded button interactions: +* http://www.w3.org/TR/pointerevents/#chorded-button-interactions +* +* You can disable Phaser's use of Pointer Events by either of two ways: +* +* ```javascript +* // **Before** `new Phaser.Game(…)`: +* Phaser.Device.onInitialized.add(function () { +* this.mspointer = false; +* }); +* ``` +* +* ```javascript +* // Once, in the earliest State `init` or `create` callback (e.g., Boot): +* this.input.mspointer.stop(); +* ``` +* +* @class Phaser.MSPointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.MSPointer = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called (defaults to game). + */ + this.callbackContext = this.game; + + /** + * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event. + */ + this.pointerDownCallback = null; + + /** + * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event. + */ + this.pointerMoveCallback = null; + + /** + * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event. + */ + this.pointerUpCallback = null; + + /** + * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, canceling the corresponding MouseEvent or TouchEvent. + */ + this.capture = true; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + */ + this.button = -1; + + /** + * The most recent PointerEvent from the browser. Will be null if no event has ever been received. + * Access this property only inside a Pointer event handler and do not keep references to it. + * @property {MSPointerEvent|PointerEvent|null} event + * @default + */ + this.event = null; + + /** + * PointerEvent input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {function} _onMSPointerDown - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerDown = null; + + /** + * @property {function} _onMSPointerMove - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerMove = null; + + /** + * @property {function} _onMSPointerUp - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUp = null; + + /** + * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUpGlobal = null; + + /** + * @property {function} _onMSPointerOut - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOut = null; + + /** + * @property {function} _onMSPointerOver - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOver = null; + +}; + +Phaser.MSPointer.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.MSPointer#start + */ + start: function () { + + if (this._onMSPointerDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + if (this.game.device.mspointer) + { + this._onMSPointerDown = function (event) { + return _this.onPointerDown(event); + }; + + this._onMSPointerMove = function (event) { + return _this.onPointerMove(event); + }; + + this._onMSPointerUp = function (event) { + return _this.onPointerUp(event); + }; + + this._onMSPointerUpGlobal = function (event) { + return _this.onPointerUpGlobal(event); + }; + + this._onMSPointerOut = function (event) { + return _this.onPointerOut(event); + }; + + this._onMSPointerOver = function (event) { + return _this.onPointerOver(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.addEventListener('pointerdown', this._onMSPointerDown, false); + canvas.addEventListener('pointermove', this._onMSPointerMove, false); + canvas.addEventListener('pointerup', this._onMSPointerUp, false); + + canvas.style['-ms-content-zooming'] = 'none'; + canvas.style['-ms-touch-action'] = 'none'; + + if (!this.game.device.cocoonJS) + { + window.addEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.addEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.addEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.addEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.addEventListener('pointerover', this._onMSPointerOver, true); + canvas.addEventListener('pointerout', this._onMSPointerOut, true); + } + } + + }, + + /** + * The function that handles the PointerDown event. + * + * @method Phaser.MSPointer#onPointerDown + * @param {PointerEvent} event - The native DOM event. + */ + onPointerDown: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerDownCallback) + { + this.pointerDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.start(event); + } + else + { + this.input.startPointer(event); + } + + }, + + /** + * The function that handles the PointerMove event. + * @method Phaser.MSPointer#onPointerMove + * @param {PointerEvent} event - The native DOM event. + */ + onPointerMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerMoveCallback) + { + this.pointerMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.move(event); + } + else + { + this.input.updatePointer(event); + } + + }, + + /** + * The function that handles the PointerUp event. + * @method Phaser.MSPointer#onPointerUp + * @param {PointerEvent} event - The native DOM event. + */ + onPointerUp: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerUpCallback) + { + this.pointerUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.stop(event); + } + else + { + this.input.stopPointer(event); + } + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.MSPointer#onPointerUpGlobal + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerUpGlobal: function (event) { + + if ((event.pointerType === 'mouse' || event.pointerType === 0x00000004) && !this.input.mousePointer.withinGame) + { + this.onPointerUp(event); + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer && pointer.withinGame) + { + this.onPointerUp(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = false; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = false; + } + } + + if (this.input.mouse.mouseOutCallback) + { + this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.input.mouse.stopOnGameOut) + { + event['identifier'] = 0; + + if (pointer) + { + pointer.stop(event); + } + else + { + this.input.mousePointer.stop(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = true; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = true; + } + } + + if (this.input.mouse.mouseOverCallback) + { + this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext, event); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.MSPointer#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.removeEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.removeEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.removeEventListener('pointerdown', this._onMSPointerDown, false); + canvas.removeEventListener('pointermove', this._onMSPointerMove, false); + canvas.removeEventListener('pointerup', this._onMSPointerUp, false); + + window.removeEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.removeEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.removeEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('pointerover', this._onMSPointerOver, true); + canvas.removeEventListener('pointerout', this._onMSPointerOut, true); + + } + +}; + +Phaser.MSPointer.prototype.constructor = Phaser.MSPointer; + +/** +* @author Richard Davey +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. +* +* For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, +* middle button and advanced buttons like back and forward. +* +* Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. +* +* On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. +* +* At the time of writing this there are device limitations you should be aware of: +* +* - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions +* (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, +* even when they are pressed. +* - On Linux (GTK), the 4th button and the 5th button are not supported. +* - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. +* +* @class Phaser.DeviceButton +* @constructor +* @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad. +* @param {number} buttonCode - The button code this DeviceButton is responsible for. +*/ +Phaser.DeviceButton = function (parent, buttonCode) { + + /** + * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = parent.game; + + /** + * @property {object} event - The DOM event that caused the change in button state. + * @default + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the button. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the button. + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - The timestamp when the button was last pressed down. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - The timestamp when the button was last released. + * @default + */ + this.timeUp = 0; + + /** + * Gamepad only. + * If a button is held down this holds down the number of times the button has 'repeated'. + * @property {number} repeats + * @default + */ + this.repeats = 0; + + /** + * True if the alt key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} altKey + * @default + */ + this.altKey = false; + + /** + * True if the shift key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} shiftKey + * @default + */ + this.shiftKey = false; + + /** + * True if the control key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} ctrlKey + * @default + */ + this.ctrlKey = false; + + /** + * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. + * @default + */ + this.value = 0; + + /** + * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. + */ + this.buttonCode = buttonCode; + + /** + * This Signal is dispatched every time this DeviceButton is pressed down. + * It is only dispatched once (until the button is released again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onDown + */ + this.onDown = new Phaser.Signal(); + + /** + * This Signal is dispatched every time this DeviceButton is released from a down state. + * It is only dispatched once (until the button is pressed again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onUp + */ + this.onUp = new Phaser.Signal(); + + /** + * Gamepad only. + * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onFloat + */ + this.onFloat = new Phaser.Signal(); + +}; + +Phaser.DeviceButton.prototype = { + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button down state. + * + * @method Phaser.DeviceButton#start + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + start: function (event, value) { + + if (this.isDown) + { + return; + } + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onDown.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button up state. + * + * @method Phaser.DeviceButton#stop + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + stop: function (event, value) { + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onUp.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer. + * Starts or stops button based on condition. + * + * @method Phaser.DeviceButton#startStop + * @protected + * @param {boolean} [condition] - The condition that decides between start or stop. + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + startStop: function (condition, event, value) { + + if (condition) + { + this.start(event, value); + } + else + { + this.stop(event, value); + } + + }, + + /** + * Called automatically by Phaser.SinglePad. + * + * @method Phaser.DeviceButton#padFloat + * @protected + * @param {number} value - Button value + */ + padFloat: function (value) { + + this.isDown = false; + this.isUp = false; + + this.value = value; + + this.onFloat.dispatch(this, value); + + }, + + /** + * Returns the "just pressed" state of this button. + * Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justPressed + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (duration) { + + duration = duration || 250; + + return (this.isDown && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * Returns the "just released" state of this button. + * Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justReleased + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (duration) { + + duration = duration || 250; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. + * + * @method Phaser.DeviceButton#reset + */ + reset: function () { + + this.isDown = false; + this.isUp = true; + + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.altKey = false; + this.shiftKey = false; + this.ctrlKey = false; + + }, + + /** + * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals + * and clears the parent and game references. + * + * @method Phaser.DeviceButton#destroy + */ + destroy: function () { + + this.onDown.dispose(); + this.onUp.dispose(); + this.onFloat.dispose(); + + this.parent = null; + this.game = null; + + } + +}; + +Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton; + +/** +* How long the button has been held down for in milliseconds. +* If not currently down it returns -1. +* +* @name Phaser.DeviceButton#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.DeviceButton.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. +* +* @class Phaser.Pointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. +* @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or CONTACT. +*/ +Phaser.Pointer = function (game, id, pointerMode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. + */ + this.id = id; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINTER; + + /** + * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps. + * @default + */ + this.exists = true; + + /** + * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.identifier = 0; + + /** + * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. + * @default + */ + this.pointerId = null; + + /** + * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer. + */ + this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT); + + /** + * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.target = null; + + /** + * The button property of the most recent DOM event when this Pointer is started. + * You should not rely on this value for accurate button detection, instead use the Pointer properties + * `leftButton`, `rightButton`, `middleButton` and so on. + * @property {any} button + * @default + */ + this.button = null; + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * @property {Phaser.DeviceButton} leftButton + * @default + */ + this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} middleButton + * @default + */ + this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} rightButton + * @default + */ + this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} backButton + * @default + */ + this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} forwardButton + * @default + */ + this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON); + + /** + * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} eraserButton + * @default + */ + this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON); + + /** + * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event. + * @private + * @default + */ + this._holdSent = false; + + /** + * @property {array} _history - Local private variable storing the short-term history of pointer movements. + * @private + */ + this._history = []; + + /** + * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur. + * @private + */ + this._nextDrop = 0; + + /** + * @property {boolean} _stateReset - Monitor events outside of a state reset loop. + * @private + */ + this._stateReset = false; + + /** + * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false. + */ + this.withinGame = false; + + /** + * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientX = -1; + + /** + * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientY = -1; + + /** + * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document. + */ + this.pageX = -1; + + /** + * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document. + */ + this.pageY = -1; + + /** + * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen. + */ + this.screenX = -1; + + /** + * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen. + */ + this.screenY = -1; + + /** + * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementX = 0; + + /** + * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementY = 0; + + /** + * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementX = 0; + + /** + * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementY = 0; + + /** + * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.x = -1; + + /** + * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.y = -1; + + /** + * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false. + */ + this.isMouse = (id === 0); + + /** + * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. + * @property {boolean} isDown + * @default + */ + this.isDown = false; + + /** + * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. + * @property {boolean} isUp + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen. + * @default + */ + this.timeUp = 0; + + /** + * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked. + * @default + */ + this.previousTapTime = 0; + + /** + * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen. + * @default + */ + this.totalTouches = 0; + + /** + * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event. + * @default + */ + this.msSinceLastClick = Number.MAX_VALUE; + + /** + * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging. + * @default + */ + this.targetObject = null; + + /** + * This array is erased and re-populated every time this Pointer is updated. It contains references to all + * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be + * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over + * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset + * every frame. + * @property {array} interactiveCandidates + * @default + */ + this.interactiveCandidates = []; + + /** + * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active. + * @default + */ + this.active = false; + + /** + * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. + * @default + */ + this.dirty = false; + + /** + * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display. + */ + this.position = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. + */ + this.positionDown = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released. + */ + this.positionUp = new Phaser.Point(); + + /** + * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. + * The Circle size is 44px (Apples recommended "finger tip" size). + * @property {Phaser.Circle} circle + */ + this.circle = new Phaser.Circle(0, 0, 44); + + /** + * Click trampolines associated with this pointer. See `addClickTrampoline`. + * @property {object[]|null} _clickTrampolines + * @private + */ + this._clickTrampolines = null; + + /** + * When the Pointer has click trampolines the last target object is stored here + * so it can be used to check for validity of the trampoline in a post-Up/'stop'. + * @property {object} _trampolineTargetObject + * @private + */ + this._trampolineTargetObject = null; + +}; + +/** +* No buttons at all. +* @constant +* @type {number} +*/ +Phaser.Pointer.NO_BUTTON = 0; + +/** +* The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. +* @constant +* @type {number} +*/ +Phaser.Pointer.LEFT_BUTTON = 1; + +/** +* The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. +* @constant +* @type {number} +*/ +Phaser.Pointer.RIGHT_BUTTON = 2; + +/** +* The Middle Mouse button. +* @constant +* @type {number} +*/ +Phaser.Pointer.MIDDLE_BUTTON = 4; + +/** +* The X1 button. This is typically the mouse Back button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.BACK_BUTTON = 8; + +/** +* The X2 button. This is typically the mouse Forward button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.FORWARD_BUTTON = 16; + +/** +* The Eraser pen button on PointerEvent supported devices only. +* @constant +* @type {number} +*/ +Phaser.Pointer.ERASER_BUTTON = 32; + +Phaser.Pointer.prototype = { + + /** + * Resets the states of all the button booleans. + * + * @method Phaser.Pointer#resetButtons + * @protected + */ + resetButtons: function () { + + this.isDown = false; + this.isUp = true; + + if (this.isMouse) + { + this.leftButton.reset(); + this.middleButton.reset(); + this.rightButton.reset(); + this.backButton.reset(); + this.forwardButton.reset(); + this.eraserButton.reset(); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsDown + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsDown: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.start(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.start(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.start(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.start(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.start(event); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsUp + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUp: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.stop(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.stop(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.stop(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.stop(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.stop(event); + } + + }, + + /** + * Called by updateButtons. + * + * @method Phaser.Pointer#processButtonsUpDown + * @private + * @param {integer} buttons - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons MouseEvent#buttons} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUpDown: function (buttons, event) { + + var down = (event.type.toLowerCase().substr(-4) === 'down'); + var move = (event.type.toLowerCase().substr(-4) === 'move'); + + if (buttons !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && buttons === 1 && event.ctrlKey) + { + buttons = 2; + } + + // Note: These are bitwise checks, not booleans + this.leftButton.startStop(Phaser.Pointer.LEFT_BUTTON & buttons, event); + this.rightButton.startStop(Phaser.Pointer.RIGHT_BUTTON & buttons, event); + this.middleButton.startStop(Phaser.Pointer.MIDDLE_BUTTON & buttons, event); + this.backButton.startStop(Phaser.Pointer.BACK_BUTTON & buttons, event); + this.forwardButton.startStop(Phaser.Pointer.FORWARD_BUTTON & buttons, event); + this.eraserButton.startStop(Phaser.Pointer.ERASER_BUTTON & buttons, event); + } + else + { + // No buttons property (like Safari on OSX when using a trackpad) + // Attempt to use event.button property or fallback to default + if (event.button !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && event.ctrlKey && event.button === 0) + { + this.rightButton.start(event); + } + else + { + if (down) + { + this.processButtonsDown(event.button, event); + } + else if (!move) + { + this.processButtonsUp(event.button, event); + } + } + } + else + { + if (down) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (event.ctrlKey) + { + this.rightButton.start(event); + } + else + { + this.leftButton.start(event); + } + } + else + { + this.leftButton.stop(event); + this.rightButton.stop(event); + } + } + } + + }, + + /** + * Called when the event.buttons property changes from zero. + * Contains a button bitmask. + * + * @method Phaser.Pointer#updateButtons + * @protected + * @param {MouseEvent} event - The DOM event. + */ + updateButtons: function (event) { + + this.button = event.button; + this.processButtonsUpDown(event.buttons, event); + + this.isUp = true; + this.isDown = false; + + if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown) + { + this.isUp = false; + this.isDown = true; + } + + }, + + /** + * Called when the Pointer is pressed onto the touchscreen. + * @method Phaser.Pointer#start + * @param {any} event - The DOM event from the browser. + */ + start: function (event) { + + var input = this.game.input; + + if (event['pointerId']) + { + this.pointerId = event.pointerId; + } + + this.identifier = event.identifier; + this.target = event.target; + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = true; + this.isUp = false; + } + + this.active = true; + this.withinGame = true; + this.dirty = false; + + this._history = []; + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + // Work out how long it has been since the last click + this.msSinceLastClick = this.game.time.time - this.timeDown; + this.timeDown = this.game.time.time; + this._holdSent = false; + + // This sets the x/y and other local values + this.move(event, true); + + // x and y are the old values here? + this.positionDown.setTo(this.x, this.y); + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.x = this.x; + input.y = this.y; + input.position.setTo(this.x, this.y); + input.onDown.dispatch(this, event); + input.resetSpeed(this.x, this.y); + } + + this._stateReset = false; + + this.totalTouches++; + + if (this.targetObject !== null) + { + this.targetObject._touchedHandler(this); + } + + return this; + + }, + + /** + * Called by the Input Manager. + * @method Phaser.Pointer#update + */ + update: function () { + + var input = this.game.input; + + if (this.active) + { + // Force a check? + if (this.dirty) + { + if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(false); + } + + this.dirty = false; + } + + if (this._holdSent === false && this.duration >= input.holdRate) + { + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onHold.dispatch(this); + } + + this._holdSent = true; + } + + // Update the droppings history + if (input.recordPointerHistory && this.game.time.time >= this._nextDrop) + { + this._nextDrop = this.game.time.time + input.recordRate; + + this._history.push({ + x: this.position.x, + y: this.position.y + }); + + if (this._history.length > input.recordLimit) + { + this._history.shift(); + } + } + } + + }, + + /** + * Called when the Pointer is moved. + * + * @method Phaser.Pointer#move + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + * @param {boolean} [fromClick=false] - Was this called from the click event? + */ + move: function (event, fromClick) { + + var input = this.game.input; + + if (input.pollLocked) + { + return; + } + + if (fromClick === undefined) { fromClick = false; } + + if (event.button !== undefined) + { + this.button = event.button; + } + + if (this.isMouse) + { + this.updateButtons(event); + } + + 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 && 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.scale.offset.x) * input.scale.x; + this.y = (this.pageY - this.game.scale.offset.y) * input.scale.y; + + this.position.setTo(this.x, this.y); + this.circle.x = this.x; + this.circle.y = this.y; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.activePointer = this; + input.x = this.x; + input.y = this.y; + input.position.setTo(input.x, input.y); + input.circle.x = input.x; + input.circle.y = input.y; + } + + this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY); + + var i = input.moveCallbacks.length; + + while (i--) + { + input.moveCallbacks[i].callback.call(input.moveCallbacks[i].context, this, this.x, this.y, fromClick); + } + + // Easy out if we're dragging something and it still exists + if (this.targetObject !== null && (!this.game.paused || this.targetObject.noPause) && this.targetObject.isDragged === true) + { + if (this.targetObject.update(this) === false) + { + this.targetObject = null; + } + } + else if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(fromClick); + } + + return this; + + }, + + /** + * Process all interactive objects to find out which ones were updated in the recent Pointer move. + * + * @method Phaser.Pointer#processInteractiveObjects + * @protected + * @param {boolean} [fromClick=false] - Was this called from the click event? + * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. + */ + processInteractiveObjects: function (fromClick) { + + // Work out which object is on the top + var highestRenderOrderID = 0; + var highestInputPriorityID = -1; + var candidateTarget = null; + + // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID + // We know they'll be valid for input detection but not which is the top just yet + + var currentNode = this.game.input.interactiveItems.first; + + this.interactiveCandidates = []; + + while (currentNode) + { + // Reset checked status + currentNode.checked = false; + + if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false) && (!this.game.paused || currentNode.sprite.noPause)) + { + // Flag it as checked so we don't re-scan it on the next phase + currentNode.checked = true; + + if ((fromClick && currentNode.checkPointerDown(this, true)) || + (!fromClick && currentNode.checkPointerOver(this, true))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID + // because if their ID is lower anyway then we can just automatically discount them + // (A node that was previously checked did not request a pixel-perfect check.) + + currentNode = this.game.input.interactiveItems.first; + + while (currentNode) + { + if (!currentNode.checked && + currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true)) + { + if ((fromClick && currentNode.checkPointerDown(this, false)) || + (!fromClick && currentNode.checkPointerOver(this, false))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + if (this.game.input.customCandidateHandler) + { + candidateTarget = this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext, this, this.interactiveCandidates, candidateTarget); + } + + this.swapTarget(candidateTarget, false); + + return (this.targetObject !== null); + + }, + + /** + * This will change the `Pointer.targetObject` object to be the one provided. + * + * This allows you to have fine-grained control over which object the Pointer is targeting. + * + * Note that even if you set a new Target here, it is still able to be replaced by any other valid + * target during the next Pointer update. + * + * @method Phaser.Pointer#swapTarget + * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. + * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. + */ + swapTarget: function (newTarget, silent) { + + if (silent === undefined) { silent = false; } + + // Now we know the top-most item (if any) we can process it + if (newTarget === null) + { + // The pointer isn't currently over anything, check if we've got a lingering previous target + if (this.targetObject) + { + this.targetObject._pointerOutHandler(this, silent); + this.targetObject = null; + } + } + else + { + if (this.targetObject === null) + { + // And now set the new one + this.targetObject = newTarget; + newTarget._pointerOverHandler(this, silent); + } + else + { + // We've got a target from the last update + if (this.targetObject === newTarget) + { + // Same target as before, so update it + if (newTarget.update(this) === false) + { + this.targetObject = null; + } + } + else + { + // The target has changed, so tell the old one we've left it + this.targetObject._pointerOutHandler(this, silent); + + // And now set the new one + this.targetObject = newTarget; + this.targetObject._pointerOverHandler(this, silent); + } + } + } + + }, + + /** + * Called when the Pointer leaves the target area. + * + * @method Phaser.Pointer#leave + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + leave: function (event) { + + this.withinGame = false; + this.move(event, false); + + }, + + /** + * Called when the Pointer leaves the touchscreen. + * + * @method Phaser.Pointer#stop + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + stop: function (event) { + + var input = this.game.input; + + if (this._stateReset && this.withinGame) + { + event.preventDefault(); + return; + } + + this.timeUp = this.game.time.time; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onUp.dispatch(this, event); + + // Was it a tap? + if (this.duration >= 0 && this.duration <= input.tapRate) + { + // Was it a double-tap? + if (this.timeUp - this.previousTapTime < input.doubleTapRate) + { + // Yes, let's dispatch the signal then with the 2nd parameter set to true + input.onTap.dispatch(this, true); + } + else + { + // Wasn't a double-tap, so dispatch a single tap signal + input.onTap.dispatch(this, false); + } + + this.previousTapTime = this.timeUp; + } + } + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = false; + this.isUp = true; + } + + // Mouse is always active + if (this.id > 0) + { + this.active = false; + } + + this.withinGame = this.game.scale.bounds.contains(event.pageX, event.pageY); + this.pointerId = null; + this.identifier = null; + + this.positionUp.setTo(this.x, this.y); + + if (this.isMouse === false) + { + input.currentPointers--; + } + + input.interactiveItems.callAll('_releasedHandler', this); + + if (this._clickTrampolines) + { + this._trampolineTargetObject = this.targetObject; + } + + this.targetObject = null; + + return this; + + }, + + /** + * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. + * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. + * @method Phaser.Pointer#justPressed + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate. + * @return {boolean} true if the Pointer was pressed down within the duration given. + */ + justPressed: function (duration) { + + duration = duration || this.game.input.justPressedRate; + + return (this.isDown === true && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. + * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. + * @method Phaser.Pointer#justReleased + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate. + * @return {boolean} true if the Pointer was released within the duration given. + */ + justReleased: function (duration) { + + duration = duration || this.game.input.justReleasedRate; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Add a click trampoline to this pointer. + * + * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily + * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen + * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. + * + * This is used internally by the ScaleManager; click trampoline usage is uncommon. + * Click trampolines can only be added to pointers that are currently down. + * + * @method Phaser.Pointer#addClickTrampoline + * @protected + * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer. + * @param {function} callback - Callback to run/trampoline. + * @param {object} callbackContext - Context of the callback. + * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array. + */ + addClickTrampoline: function (name, callback, callbackContext, callbackArgs) { + + if (!this.isDown) + { + return; + } + + var trampolines = (this._clickTrampolines = this._clickTrampolines || []); + + for (var i = 0; i < trampolines.length; i++) + { + if (trampolines[i].name === name) + { + trampolines.splice(i, 1); + break; + } + } + + trampolines.push({ + name: name, + targetObject: this.targetObject, + callback: callback, + callbackContext: callbackContext, + callbackArgs: callbackArgs + }); + + }, + + /** + * Fire all click trampolines for which the pointers are still referring to the registered object. + * @method Phaser.Pointer#processClickTrampolines + * @private + */ + processClickTrampolines: function () { + + var trampolines = this._clickTrampolines; + + if (!trampolines) + { + return; + } + + for (var i = 0; i < trampolines.length; i++) + { + var trampoline = trampolines[i]; + + if (trampoline.targetObject === this._trampolineTargetObject) + { + trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs); + } + } + + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + }, + + /** + * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. + * @method Phaser.Pointer#reset + */ + reset: function () { + + if (this.isMouse === false) + { + this.active = false; + } + + this.pointerId = null; + this.identifier = null; + this.dirty = false; + this.totalTouches = 0; + this._holdSent = false; + this._history.length = 0; + this._stateReset = true; + + this.resetButtons(); + + if (this.targetObject) + { + this.targetObject._releasedHandler(this); + } + + this.targetObject = null; + + }, + + /** + * Resets the movementX and movementY properties. Use in your update handler after retrieving the values. + * @method Phaser.Pointer#resetMovement + */ + resetMovement: function() { + + this.movementX = 0; + this.movementY = 0; + + } + +}; + +Phaser.Pointer.prototype.constructor = Phaser.Pointer; + +/** +* How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. +* If not currently down it returns -1. +* If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. +* +* @name Phaser.Pointer#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* Gets the X value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldX +* @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldX", { + + get: function () { + + return this.game.world.camera.x + this.x; + + } + +}); + +/** +* Gets the Y value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldY +* @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldY", { + + get: function () { + + return this.game.world.camera.y + this.y; + + } + +}); + +/** +* Enumeration categorizing operational modes of pointers. +* +* PointerType values represent valid bitmasks. +* For example, a value representing both Mouse and Touch devices +* can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. +* +* Values may be added for future mode categorizations. +* @class Phaser.PointerMode +*/ +Phaser.PointerMode = { + + /** + * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. + * + * It has the property that a cursor is passively moved without activating the input. + * This currently corresponds with {@link Phaser.Pointer#isMouse} property. + * @constant + */ + CURSOR: 1 << 0, + + /** + * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. + * @constant + */ + CONTACT: 1 << 1 + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. +* +* @class Phaser.Touch +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Touch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * Touch events will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} touchStartCallback - A callback that can be fired on a touchStart event. + */ + this.touchStartCallback = null; + + /** + * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event. + */ + this.touchMoveCallback = null; + + /** + * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event. + */ + this.touchEndCallback = null; + + /** + * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event. + */ + this.touchEnterCallback = null; + + /** + * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event. + */ + this.touchLeaveCallback = null; + + /** + * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event. + */ + this.touchCancelCallback = null; + + /** + * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it. + * @default + */ + this.preventDefault = true; + + /** + * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received. + * @default + */ + this.event = null; + + /** + * @property {function} _onTouchStart - Internal event handler reference. + * @private + */ + this._onTouchStart = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + + /** + * @property {function} _onTouchEnd - Internal event handler reference. + * @private + */ + this._onTouchEnd = null; + + /** + * @property {function} _onTouchEnter - Internal event handler reference. + * @private + */ + this._onTouchEnter = null; + + /** + * @property {function} _onTouchLeave - Internal event handler reference. + * @private + */ + this._onTouchLeave = null; + + /** + * @property {function} _onTouchCancel - Internal event handler reference. + * @private + */ + this._onTouchCancel = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + +}; + +Phaser.Touch.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Touch#start + */ + start: function () { + + if (this._onTouchStart !== null) + { + // Avoid setting multiple listeners + 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('touchcancel', this._onTouchCancel, false); + + if (!this.game.device.cocoonJS) + { + this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false); + this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false); + } + } + + }, + + /** + * Consumes all touchmove events on the document (only enable this if you know you need it!). + * @method Phaser.Touch#consumeTouchMove + */ + consumeDocumentTouches: function () { + + this._documentTouchMove = function (event) { + event.preventDefault(); + }; + + document.addEventListener('touchmove', this._documentTouchMove, false); + + }, + + /** + * The internal method that handles the touchstart event from the browser. + * @method Phaser.Touch#onTouchStart + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchStart: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.touchStartCallback) + { + this.touchStartCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.startPointer(event.changedTouches[i]); + } + + }, + + /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. + * @method Phaser.Touch#onTouchCancel + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchCancel: function (event) { + + this.event = event; + + if (this.touchCancelCallback) + { + this.touchCancelCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchEnter + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnter: function (event) { + + this.event = event; + + if (this.touchEnterCallback) + { + this.touchEnterCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchLeave + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchLeave: function (event) { + + this.event = event; + + if (this.touchLeaveCallback) + { + this.touchLeaveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * The handler for the touchmove events. + * @method Phaser.Touch#onTouchMove + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchMove: function (event) { + + this.event = event; + + if (this.touchMoveCallback) + { + this.touchMoveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.updatePointer(event.changedTouches[i]); + } + + }, + + /** + * The handler for the touchend events. + * @method Phaser.Touch#onTouchEnd + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnd: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.touchEndCallback) + { + this.touchEndCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.Touch#stop + */ + stop: function () { + + if (this.game.device.touch) + { + this.game.canvas.removeEventListener('touchstart', this._onTouchStart); + this.game.canvas.removeEventListener('touchmove', this._onTouchMove); + this.game.canvas.removeEventListener('touchend', this._onTouchEnd); + this.game.canvas.removeEventListener('touchenter', this._onTouchEnter); + this.game.canvas.removeEventListener('touchleave', this._onTouchLeave); + this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel); + } + + } + +}; + +Phaser.Touch.prototype.constructor = Phaser.Touch; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. +* +* @class Phaser.InputHandler +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. +*/ +Phaser.InputHandler = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = sprite.game; + + /** + * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity. + * @default + */ + this.enabled = false; + + /** + * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks. + * @protected + */ + this.checked = false; + + /** + * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have + * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can + * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. + * @property {number} priorityID + * @default + */ + this.priorityID = 0; + + /** + * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. + * @default + */ + this.useHandCursor = false; + + /** + * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor? + * @private + */ + this._setHandCursor = false; + + /** + * @property {boolean} isDragged - true if the Sprite is being currently dragged. + * @default + */ + this.isDragged = false; + + /** + * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally. + * @default + */ + this.allowHorizontalDrag = true; + + /** + * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically. + * @default + */ + this.allowVerticalDrag = true; + + /** + * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. + * @default + */ + this.bringToTop = false; + + /** + * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset. + * @default + */ + this.snapOffset = null; + + /** + * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. + * @default + */ + this.snapOnDrag = false; + + /** + * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release. + * @default + */ + this.snapOnRelease = false; + + /** + * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid. + * @default + */ + this.snapX = 0; + + /** + * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid. + * @default + */ + this.snapY = 0; + + /** + * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid. + * @default + */ + this.snapOffsetX = 0; + + /** + * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid.. + * @default + */ + this.snapOffsetY = 0; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. + * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over. + * @default + */ + this.pixelPerfectOver = false; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive so only enable if you really need it. + * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite. + * @default + */ + this.pixelPerfectClick = false; + + /** + * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. + * @default + */ + this.pixelPerfectAlpha = 255; + + /** + * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no + * @default + */ + this.draggable = false; + + /** + * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag. + * @default + */ + this.boundsRect = null; + + /** + * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. + * @default + */ + this.boundsSprite = null; + + /** + * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. + */ + this.scaleLayer = false; + + /** + * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from. + */ + this.dragOffset = new Phaser.Point(); + + /** + * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? + */ + this.dragFromCenter = false; + + /** + * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. + */ + this.dragStopBlocksInputUp = false; + + /** + * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. + */ + this.dragStartPoint = new Phaser.Point(); + + /** + * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. + */ + this.dragDistanceThreshold = 0; + + /** + * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. + */ + this.dragTimeThreshold = 0; + + /** + * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. + */ + this.downPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. + */ + this.snapPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} _dragPoint - Internal cache var. + * @private + */ + this._dragPoint = new Phaser.Point(); + + /** + * @property {boolean} _dragPhase - Internal cache var. + * @private + */ + this._dragPhase = false; + + /** + * @property {boolean} _pendingDrag - Internal cache var. + * @private + */ + this._pendingDrag = false; + + /** + * @property {boolean} _dragTimePass - Internal cache var. + * @private + */ + this._dragTimePass = false; + + /** + * @property {boolean} _dragDistancePass - Internal cache var. + * @private + */ + this._dragDistancePass = false; + + /** + * @property {boolean} _wasEnabled - Internal cache var. + * @private + */ + this._wasEnabled = false; + + /** + * @property {Phaser.Point} _tempPoint - Internal cache var. + * @private + */ + this._tempPoint = new Phaser.Point(); + + /** + * @property {array} _pointerData - Internal cache var. + * @private + */ + this._pointerData = []; + + this._pointerData.push({ + id: 0, + x: 0, + y: 0, + camX: 0, + camY: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }); + +}; + +Phaser.InputHandler.prototype = { + + /** + * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. + * + * @method Phaser.InputHandler#start + * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. + * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) + * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound. + */ + start: function (priority, useHandCursor) { + + priority = priority || 0; + if (useHandCursor === undefined) { useHandCursor = false; } + + // Turning on + if (this.enabled === false) + { + // Register, etc + this.game.input.interactiveItems.add(this); + this.useHandCursor = useHandCursor; + this.priorityID = priority; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + + this.snapOffset = new Phaser.Point(); + this.enabled = true; + this._wasEnabled = true; + + } + + this.sprite.events.onAddedToGroup.add(this.addedToGroup, this); + this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this); + + return this.sprite; + + }, + + /** + * Handles when the parent Sprite is added to a new Group. + * + * @method Phaser.InputHandler#addedToGroup + * @private + */ + addedToGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this._wasEnabled && !this.enabled) + { + this.start(); + } + + }, + + /** + * Handles when the parent Sprite is removed from a Group. + * + * @method Phaser.InputHandler#removedFromGroup + * @private + */ + removedFromGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this.enabled) + { + this._wasEnabled = true; + this.stop(); + } + else + { + this._wasEnabled = false; + } + + }, + + /** + * Resets the Input Handler and disables it. + * @method Phaser.InputHandler#reset + */ + reset: function () { + + this.enabled = false; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + }, + + /** + * Stops the Input Handler from running. + * @method Phaser.InputHandler#stop + */ + stop: function () { + + // Turning off + if (this.enabled === false) + { + return; + } + else + { + // De-register, etc + this.enabled = false; + this.game.input.interactiveItems.remove(this); + } + + }, + + /** + * Clean up memory. + * @method Phaser.InputHandler#destroy + */ + destroy: function () { + + if (this.sprite) + { + if (this._setHandCursor) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + this.enabled = false; + + this.game.input.interactiveItems.remove(this); + + this._pointerData.length = 0; + this.boundsRect = null; + this.boundsSprite = null; + this.sprite = null; + } + + }, + + /** + * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. + * This is called by Phaser.Pointer and shouldn't typically be called directly. + * + * @method Phaser.InputHandler#validForInput + * @protected + * @param {number} highestID - The highest ID currently processed by the Pointer. + * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer. + * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? + * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection. + */ + validForInput: function (highestID, highestRenderID, includePixelPerfect) { + + if (includePixelPerfect === undefined) { includePixelPerfect = true; } + + if (!this.enabled || + this.sprite.scale.x === 0 || + this.sprite.scale.y === 0 || + this.priorityID < this.game.input.minPriorityID || + (this.sprite.parent && this.sprite.parent.ignoreChildInput)) + { + return false; + } + + // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it + if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver)) + { + return false; + } + + if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID > highestRenderID)) + { + return true; + } + + return false; + + }, + + /** + * Is this object using pixel perfect checking? + * + * @method Phaser.InputHandler#isPixelPerfect + * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. + */ + isPixelPerfect: function () { + + return (this.pixelPerfectClick || this.pixelPerfectOver); + + }, + + /** + * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerX + * @param {integer} [pointerId=0] + * @return {number} The x coordinate of the Input pointer. + */ + pointerX: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].x; + + }, + + /** + * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerY + * @param {integer} [pointerId=0] + * @return {number} The y coordinate of the Input pointer. + */ + pointerY: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].y; + + }, + + /** + * If the Pointer is down this returns true. + * This *only* checks if the Pointer is down, not if it's down over any specific Sprite. + * + * @method Phaser.InputHandler#pointerDown + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is down, otherwise false. + */ + pointerDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDown; + + }, + + /** + * If the Pointer is up this returns true. + * This *only* checks if the Pointer is up, not if it's up over any specific Sprite. + * + * @method Phaser.InputHandler#pointerUp + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is up, otherwise false. + */ + pointerUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isUp; + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeDown + * @param {integer} [pointerId=(check all)] + * @return {number} + */ + pointerTimeDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeDown; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeUp + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeUp; + + }, + + /** + * Is the Pointer over this Sprite? + * + * @method Phaser.InputHandler#pointerOver + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object. + */ + pointerOver: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOver) + { + return true; + } + } + + return false; + } + else + { + return this._pointerData[pointerId].isOver; + } + + }, + + /** + * Is the Pointer outside of this Sprite? + * + * @method Phaser.InputHandler#pointerOut + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. + */ + pointerOut: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOut) + { + return true; + } + } + } + else + { + return this._pointerData[pointerId].isOut; + } + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOver + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOver: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOver; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOut + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOut: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOut; + + }, + + /** + * Is this sprite being dragged by the mouse or not? + * + * @method Phaser.InputHandler#pointerDragged + * @param {integer} [pointerId=0] + * @return {boolean} True if the pointer is dragging an object, otherwise false. + */ + pointerDragged: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDragged; + + }, + + /** + * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerDown + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} True if the pointer is down, otherwise false. + */ + checkPointerDown: function (pointer, fastTest) { + + if (!pointer.isDown || + !this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectClick) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Checks if the given pointer is over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerOver + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} + */ + checkPointerOver: function (pointer, fastTest) { + + if (!this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectOver) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. + * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. + * + * @method Phaser.InputHandler#checkPixel + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters. + * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha + */ + checkPixel: function (x, y, pointer) { + + // Grab a pixel from our image into the hitCanvas and then test it + if (this.sprite.texture.baseTexture.source) + { + if (x === null && y === null) + { + // Use the pointer parameter + this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint); + + var x = this._tempPoint.x; + var y = this._tempPoint.y; + } + + if (this.sprite.anchor.x !== 0) + { + x -= -this.sprite.texture.frame.width * this.sprite.anchor.x; + } + + if (this.sprite.anchor.y !== 0) + { + y -= -this.sprite.texture.frame.height * this.sprite.anchor.y; + } + + x += this.sprite.texture.frame.x; + y += this.sprite.texture.frame.y; + + if (this.sprite.texture.trim) + { + x -= this.sprite.texture.trim.x; + y -= this.sprite.texture.trim.y; + + // If the coordinates are outside the trim area we return false immediately, to save doing a draw call + if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom) + { + this._dx = x; + this._dy = y; + return false; + } + } + + this._dx = x; + this._dy = y; + + this.game.input.hitContext.clearRect(0, 0, 1, 1); + this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1); + + if (rgb.data[3] >= this.pixelPerfectAlpha) + { + return true; + } + } + + return false; + + }, + + /** + * Internal Update method. This is called automatically and handles the Pointer + * and drag update loops. + * + * @method Phaser.InputHandler#update + * @protected + * @param {Phaser.Pointer} pointer + * @return {boolean} True if the pointer is still active, otherwise false. + */ + update: function (pointer) { + + if (this.sprite === null || this.sprite.parent === undefined) + { + // Abort. We've been destroyed. + return; + } + + if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible) + { + this._pointerOutHandler(pointer); + return false; + } + + if (this._pendingDrag) + { + if (!this._dragDistancePass) + { + this._dragDistancePass = (Phaser.Math.distance(pointer.x, pointer.y, this.downPoint.x, this.downPoint.y) >= this.dragDistanceThreshold); + } + + if (this._dragDistancePass && this._dragTimePass) + { + this.startDrag(pointer); + } + + return true; + } + else if (this.draggable && this._draggedPointerID === pointer.id) + { + return this.updateDrag(pointer, false); + } + else if (this._pointerData[pointer.id].isOver) + { + 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; + } + } + }, + + /** + * Internal method handling the pointer over event. + * + * @method Phaser.InputHandler#_pointerOverHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOverHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (data.isOver === false || pointer.dirty) + { + var sendEvent = (data.isOver === false); + + data.isOver = true; + data.isOut = false; + data.timeOver = this.game.time.time; + data.x = pointer.x - this.sprite.x; + data.y = pointer.y - this.sprite.y; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = "pointer"; + this._setHandCursor = true; + } + + if (!silent && sendEvent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOver$dispatch(this.sprite, pointer); + } + + if (this.sprite.parent && this.sprite.parent.onChildInputOver) + { + this.sprite.parent.onChildInputOver.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the pointer out event. + * + * @method Phaser.InputHandler#_pointerOutHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOutHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + data.isOver = false; + data.isOut = true; + data.timeOut = this.game.time.time; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + if (!silent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOut$dispatch(this.sprite, pointer); + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputOut) + { + this.sprite.parent.onChildInputOut.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the touched / clicked event. + * + * @method Phaser.InputHandler#_touchedHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + */ + _touchedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (!data.isDown && data.isOver) + { + if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer)) + { + return; + } + + data.isDown = true; + data.isUp = false; + data.timeDown = this.game.time.time; + + this.downPoint.set(pointer.x, pointer.y); + + // It's possible the onInputDown event creates a new Sprite that is on-top of this one, so we ought to force a Pointer update + pointer.dirty = true; + + if (this.sprite && this.sprite.events) + { + this.sprite.events.onInputDown$dispatch(this.sprite, pointer); + + // The event above might have destroyed this sprite. + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputDown) + { + this.sprite.parent.onChildInputDown.dispatch(this.sprite, pointer); + } + + // The events might have destroyed this sprite. + if (this.sprite === null) + { + return; + } + } + + // Start drag + if (this.draggable && this.isDragged === false) + { + if (this.dragTimeThreshold === 0 && this.dragDistanceThreshold === 0) + { + this.startDrag(pointer); + } + else + { + this._pendingDrag = true; + + this._dragDistancePass = (this.dragDistanceThreshold === 0); + + if (this.dragTimeThreshold > 0) + { + this._dragTimePass = false; + this.game.time.events.add(this.dragTimeThreshold, this.dragTimeElapsed, this, pointer); + } + else + { + this._dragTimePass = true; + } + } + } + + if (this.bringToTop) + { + this.sprite.bringToTop(); + } + } + + }, + + /** + * Internal method handling the drag threshold timer. + * + * @method Phaser.InputHandler#dragTimeElapsed + * @private + * @param {Phaser.Pointer} pointer + */ + dragTimeElapsed: function (pointer) { + + this._dragTimePass = true; + + if (this._pendingDrag && this.sprite) + { + if (this._dragDistancePass) + { + this.startDrag(pointer); + } + } + + }, + + /** + * Internal method handling the pointer released event. + * @method Phaser.InputHandler#_releasedHandler + * @private + * @param {Phaser.Pointer} pointer + */ + _releasedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + // If was previously touched by this Pointer, check if still is AND still over this item + if (data.isDown && pointer.isUp) + { + data.isDown = false; + data.isUp = true; + data.timeUp = this.game.time.time; + data.downDuration = data.timeUp - data.timeDown; + + // Only release the InputUp signal if the pointer is still over this sprite + var isOver = this.checkPointerOver(pointer); + + if (this.sprite && this.sprite.events) + { + if (!this.dragStopBlocksInputUp || + this.dragStopBlocksInputUp && !(this.draggable && this.isDragged && this._draggedPointerID === pointer.id)) + { + this.sprite.events.onInputUp$dispatch(this.sprite, pointer, isOver); + } + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputUp) + { + this.sprite.parent.onChildInputUp.dispatch(this.sprite, pointer, isOver); + } + + // The onInputUp event may have changed the sprite so that checkPointerOver is no longer true, so update it. + if (isOver) + { + isOver = this.checkPointerOver(pointer); + } + } + + data.isOver = isOver; + + if (!isOver && this.useHandCursor) + { + this.game.canvas.style.cursor = "default"; + this._setHandCursor = false; + } + + // It's possible the onInputUp event created a new Sprite that is on-top of this one, so force a Pointer update + pointer.dirty = true; + + this._pendingDrag = false; + + // Stop drag + if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id) + { + this.stopDrag(pointer); + } + } + + }, + + /** + * Called as a Pointer actively drags this Game Object. + * + * @method Phaser.InputHandler#updateDrag + * @private + * @param {Phaser.Pointer} pointer - The Pointer causing the drag update. + * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started. + * @return {boolean} + */ + updateDrag: function (pointer, fromStart) { + + if (fromStart === undefined) { fromStart = false; } + + if (pointer.isUp) + { + this.stopDrag(pointer); + return false; + } + + var pointerLocalCoord = this.globalToLocal(pointer); + + if (this.sprite.fixedToCamera) + { + var px = this.game.camera.scale.x * pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = this.game.camera.scale.y * pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + else + { + var px = pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + + if (this.sprite.fixedToCamera) + { + if (this.allowHorizontalDrag) + { + this.sprite.cameraOffset.x = px - this.game.camera.x; + } + + if (this.allowVerticalDrag) + { + this.sprite.cameraOffset.y = py - this.game.camera.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); + this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y); + } + } + else + { + var cx = this.game.camera.x - this._pointerData[pointer.id].camX; + var cy = this.game.camera.y - this._pointerData[pointer.id].camY; + + if (this.allowHorizontalDrag) + { + this.sprite.x = px + cx; + } + + if (this.allowVerticalDrag) + { + this.sprite.y = py + cy; + } + + 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); + this.snapPoint.set(this.sprite.x, this.sprite.y); + } + } + + this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint, fromStart); + + return true; + + }, + + /** + * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOver + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justOver: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOut + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justOut: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay)); + + }, + + /** + * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justPressed + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justPressed: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justReleased + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justReleased: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay)); + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#overDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. + */ + overDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isOver) + { + return this.game.time.time - this._pointerData[pointerId].timeOver; + } + + return -1; + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#downDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. + */ + downDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isDown) + { + return this.game.time.time - this._pointerData[pointerId].timeDown; + } + + return -1; + + }, + + /** + * Allow this Sprite to be dragged by any valid pointer. + * + * When the drag begins the Sprite.events.onDragStart event will be dispatched. + * + * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. + * + * You can control the thresholds over when a drag starts via the properties: + * + * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move + * before the drag will start. + * + * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on + * the Sprite before the drag will start. + * + * You can set either (or both) of these properties after enabling a Sprite for drag. + * + * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually + * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`. + * + * @method Phaser.InputHandler#enableDrag + * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. + * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group. + * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. + * @param {integer} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. + * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. + * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. + */ + enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) { + + if (lockCenter === undefined) { lockCenter = false; } + if (bringToTop === undefined) { bringToTop = false; } + if (pixelPerfect === undefined) { pixelPerfect = false; } + if (alphaThreshold === undefined) { alphaThreshold = 255; } + if (boundsRect === undefined) { boundsRect = null; } + if (boundsSprite === undefined) { boundsSprite = null; } + + this._dragPoint = new Phaser.Point(); + this.draggable = true; + this.bringToTop = bringToTop; + this.dragOffset = new Phaser.Point(); + this.dragFromCenter = lockCenter; + + this.pixelPerfectClick = pixelPerfect; + this.pixelPerfectAlpha = alphaThreshold; + + if (boundsRect) + { + this.boundsRect = boundsRect; + } + + if (boundsSprite) + { + this.boundsSprite = boundsSprite; + } + + }, + + /** + * Stops this sprite from being able to be dragged. + * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. + * + * @method Phaser.InputHandler#disableDrag + */ + disableDrag: function () { + + if (this._pointerData) + { + for (var i = 0; i < 10; i++) + { + this._pointerData[i].isDragged = false; + } + } + + this.draggable = false; + this.isDragged = false; + this._draggedPointerID = -1; + this._pendingDrag = false; + + }, + + /** + * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#startDrag + * @param {Phaser.Pointer} pointer + */ + startDrag: function (pointer) { + + var x = this.sprite.x; + var y = this.sprite.y; + var pointerLocalCoord = this.globalToLocal(pointer); + + this.isDragged = true; + this._draggedPointerID = pointer.id; + + this._pointerData[pointer.id].camX = this.game.camera.x; + this._pointerData[pointer.id].camY = this.game.camera.y; + + this._pointerData[pointer.id].isDragged = true; + + if (this.sprite.fixedToCamera) + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.cameraOffset.x = pointerLocalCoord.x + (this.sprite.cameraOffset.x - boundsCenterLocalCoord.x); + this.sprite.cameraOffset.y = pointerLocalCoord.y + (this.sprite.cameraOffset.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y); + } + else + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.x = pointerLocalCoord.x + (this.sprite.x - boundsCenterLocalCoord.x); + this.sprite.y = pointerLocalCoord.y + (this.sprite.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.x - pointerLocalCoord.x, this.sprite.y - pointerLocalCoord.y); + } + + this.updateDrag(pointer, true); + + if (this.bringToTop) + { + this._dragPhase = true; + this.sprite.bringToTop(); + } + + this.dragStartPoint.set(x, y); + + this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y); + + this._pendingDrag = false; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalX + * @param {number} x + */ + globalToLocalX: function (x) { + + if (this.scaleLayer) + { + x -= this.game.scale.grid.boundsFluid.x; + x *= this.game.scale.grid.scaleFluidInversed.x; + } + + return x; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalY + * @param {number} y + */ + globalToLocalY: function (y) { + + if (this.scaleLayer) + { + y -= this.game.scale.grid.boundsFluid.y; + y *= this.game.scale.grid.scaleFluidInversed.y; + } + + return y; + + }, + + /** + * Convert global coordinates to local sprite coordinates + * + * @method Phaser.InputHandler#globalToLocal + * @param {Phaser.Point} globalCoord - The global coordinates to convert. + * @return {Phaser.Point} A point containing the local coordinates. + */ + globalToLocal: function (globalCoord) { + + if (this.sprite.parent) + { + return this.game.input.getLocalPosition(this.sprite.parent, {x: globalCoord.x, y: globalCoord.y}); + } + else + { + return globalCoord; + } + + }, + + /** + * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#stopDrag + * @param {Phaser.Pointer} pointer + */ + stopDrag: function (pointer) { + + this.isDragged = false; + this._draggedPointerID = -1; + this._pointerData[pointer.id].isDragged = false; + this._dragPhase = false; + this._pendingDrag = false; + + if (this.snapOnRelease) + { + if (this.sprite.fixedToCamera) + { + 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 + { + 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); + } + } + + this.sprite.events.onDragStop$dispatch(this.sprite, pointer); + + if (this.checkPointerOver(pointer) === false) + { + this._pointerOutHandler(pointer); + } + + }, + + /** + * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! + * + * @method Phaser.InputHandler#setDragLock + * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false. + * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false. + */ + setDragLock: function (allowHorizontal, allowVertical) { + + if (allowHorizontal === undefined) { allowHorizontal = true; } + if (allowVertical === undefined) { allowVertical = true; } + + this.allowHorizontalDrag = allowHorizontal; + this.allowVerticalDrag = allowVertical; + + }, + + /** + * Make this Sprite snap to the given grid either during drag or when it's released. + * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. + * + * @method Phaser.InputHandler#enableSnap + * @param {number} snapX - The width of the grid cell to snap to. + * @param {number} snapY - The height of the grid cell to snap to. + * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged. + * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released. + * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid. + * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid. + */ + enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) { + + if (onDrag === undefined) { onDrag = true; } + if (onRelease === undefined) { onRelease = false; } + if (snapOffsetX === undefined) { snapOffsetX = 0; } + if (snapOffsetY === undefined) { snapOffsetY = 0; } + + this.snapX = snapX; + this.snapY = snapY; + this.snapOffsetX = snapOffsetX; + this.snapOffsetY = snapOffsetY; + this.snapOnDrag = onDrag; + this.snapOnRelease = onRelease; + + }, + + /** + * Stops the sprite from snapping to a grid during drag or release. + * + * @method Phaser.InputHandler#disableSnap + */ + disableSnap: function () { + + this.snapOnDrag = false; + this.snapOnRelease = false; + + }, + + /** + * Bounds Rect check for the sprite drag + * + * @method Phaser.InputHandler#checkBoundsRect + */ + checkBoundsRect: function () { + + if (this.sprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsRect.left) + { + this.sprite.cameraOffset.x = this.boundsRect.left; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right) + { + this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsRect.top) + { + this.sprite.cameraOffset.y = this.boundsRect.top; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom) + { + this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsRect.left) + { + this.sprite.x = this.boundsRect.x + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsRect.right) + { + this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsRect.top) + { + this.sprite.y = this.boundsRect.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsRect.bottom) + { + this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + }, + + /** + * Parent Sprite Bounds check for the sprite drag. + * + * @method Phaser.InputHandler#checkBoundsSprite + */ + checkBoundsSprite: function () { + + if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x) + { + this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width)) + { + this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y) + { + this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height)) + { + this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsSprite.left) + { + this.sprite.x = this.boundsSprite.left + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsSprite.right) + { + this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsSprite.top) + { + this.sprite.y = this.boundsSprite.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsSprite.bottom) + { + this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + } + +}; + +Phaser.InputHandler.prototype.constructor = Phaser.InputHandler; + +/** +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Gamepad class handles gamepad input and dispatches gamepad events. +* +* Remember to call `gamepad.start()`. +* +* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! +* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it +* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. +* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. +* +* @class Phaser.Gamepad +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Gamepad = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads + * @private + */ + this._gamepadIndexMap = {}; + + /** + * @property {Array} _rawPads - The raw state of the gamepads from the browser + * @private + */ + this._rawPads = []; + + /** + * @property {boolean} _active - Private flag for whether or not the API is polled + * @private + * @default + */ + this._active = false; + + /** + * Gamepad input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation. + * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not? + * @private + */ + this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') !== -1) || !!navigator.getGamepads; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevRawGamepadTypes + * @private + * @default + */ + this._prevRawGamepadTypes = []; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevTimestamps + * @private + * @default + */ + this._prevTimestamps = []; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._ongamepadconnected = null; + + /** + * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._gamepaddisconnected = null; + + /** + * @property {Array} _gamepads - The four Phaser Gamepads. + * @private + */ + this._gamepads = [ + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this) + ]; + +}; + +Phaser.Gamepad.prototype = { + + /** + * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. + * + * @method Phaser.Gamepad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callback methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + this.callbackContext = context; + } + + }, + + /** + * Starts the Gamepad event handling. + * This MUST be called manually before Phaser will start polling the Gamepad API. + * + * @method Phaser.Gamepad#start + */ + start: function () { + + if (this._active) + { + // Avoid setting multiple listeners + return; + } + + this._active = true; + + var _this = this; + + this._onGamepadConnected = function (event) { + return _this.onGamepadConnected(event); + }; + + this._onGamepadDisconnected = function (event) { + return _this.onGamepadDisconnected(event); + }; + + window.addEventListener('gamepadconnected', this._onGamepadConnected, false); + window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false); + + }, + + /** + * Handles the connection of a Gamepad. + * + * @method onGamepadConnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadConnected: function (event) { + + var newPad = event.gamepad; + this._rawPads.push(newPad); + this._gamepads[newPad.index].connect(newPad); + + }, + + /** + * Handles the disconnection of a Gamepad. + * + * @method onGamepadDisconnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadDisconnected: function (event) { + + var removedPad = event.gamepad; + + for (var i in this._rawPads) + { + if (this._rawPads[i].index === removedPad.index) + { + this._rawPads.splice(i,1); + } + } + + this._gamepads[removedPad.index].disconnect(); + + }, + + /** + * Main gamepad update loop. Should not be called manually. + * @method Phaser.Gamepad#update + * @protected + */ + update: function () { + + this._pollGamepads(); + + this.pad1.pollStatus(); + this.pad2.pollStatus(); + this.pad3.pollStatus(); + this.pad4.pollStatus(); + + }, + + /** + * Updating connected gamepads (for Google Chrome). Should not be called manually. + * + * @method Phaser.Gamepad#_pollGamepads + * @private + */ + _pollGamepads: function () { + + if (!this._active) + { + return; + } + + if (navigator['getGamepads']) + { + var rawGamepads = navigator.getGamepads(); + } + else if (navigator['webkitGetGamepads']) + { + var rawGamepads = navigator.webkitGetGamepads(); + } + else if (navigator['webkitGamepads']) + { + var rawGamepads = navigator.webkitGamepads(); + } + + if (rawGamepads) + { + this._rawPads = []; + + var gamepadsChanged = false; + + for (var i = 0; i < rawGamepads.length; i++) + { + if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i]) + { + gamepadsChanged = true; + this._prevRawGamepadTypes[i] = typeof rawGamepads[i]; + } + + if (rawGamepads[i]) + { + this._rawPads.push(rawGamepads[i]); + } + + // Support max 4 pads at the moment + if (i === 3) + { + break; + } + } + + for (var g = 0; g < this._gamepads.length; g++) + { + this._gamepads[g]._rawPad = this._rawPads[g]; + } + + if (gamepadsChanged) + { + var validConnections = { rawIndices: {}, padIndices: {} }; + var singlePad; + + for (var j = 0; j < this._gamepads.length; j++) + { + singlePad = this._gamepads[j]; + + if (singlePad.connected) + { + for (var k = 0; k < this._rawPads.length; k++) + { + if (this._rawPads[k].index === singlePad.index) + { + validConnections.rawIndices[singlePad.index] = true; + validConnections.padIndices[j] = true; + } + } + } + } + + for (var l = 0; l < this._gamepads.length; l++) + { + singlePad = this._gamepads[l]; + + if (validConnections.padIndices[l]) + { + continue; + } + + if (this._rawPads.length < 1) + { + singlePad.disconnect(); + } + + for (var m = 0; m < this._rawPads.length; m++) + { + if (validConnections.padIndices[l]) + { + break; + } + + var rawPad = this._rawPads[m]; + + if (rawPad) + { + if (validConnections.rawIndices[rawPad.index]) + { + singlePad.disconnect(); + continue; + } + else + { + singlePad.connect(rawPad); + validConnections.rawIndices[rawPad.index] = true; + validConnections.padIndices[l] = true; + } + } + else + { + singlePad.disconnect(); + } + } + } + } + } + }, + + /** + * Sets the deadZone variable for all four gamepads + * @method Phaser.Gamepad#setDeadZones + */ + setDeadZones: function (value) { + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].deadZone = value; + } + + }, + + /** + * Stops the Gamepad event handling. + * + * @method Phaser.Gamepad#stop + */ + stop: function () { + + this._active = false; + + window.removeEventListener('gamepadconnected', this._onGamepadConnected); + window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected); + + }, + + /** + * Reset all buttons/axes of all gamepads + * @method Phaser.Gamepad#reset + */ + reset: function () { + + this.update(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].reset(); + } + + }, + + /** + * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justPressed(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justReleased(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns true if the button is currently pressed down, on ANY gamepad. + * @method Phaser.Gamepad#isDown + * @param {number} buttonCode - The buttonCode of the button to check for. + * @return {boolean} True if a button is currently down. + */ + isDown: function (buttonCode) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].isDown(buttonCode) === true) + { + return true; + } + } + + return false; + }, + + /** + * Destroys this object and the associated event listeners. + * + * @method Phaser.Gamepad#destroy + */ + destroy: function () { + + this.stop(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].destroy(); + } + + } + +}; + +Phaser.Gamepad.prototype.constructor = Phaser.Gamepad; + +/** +* If the gamepad input is active or not - if not active it should not be updated from Input.js +* @name Phaser.Gamepad#active +* @property {boolean} active - If the gamepad input is active or not. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "active", { + + get: function () { + return this._active; + } + +}); + +/** +* Whether or not gamepads are supported in current browser. +* @name Phaser.Gamepad#supported +* @property {boolean} supported - Whether or not gamepads are supported in current browser. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "supported", { + + get: function () { + return this._gamepadSupportAvailable; + } + +}); + +/** +* How many live gamepads are currently connected. +* @name Phaser.Gamepad#padsConnected +* @property {number} padsConnected - How many live gamepads are currently connected. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", { + + get: function () { + return this._rawPads.length; + } + +}); + +/** +* Gamepad #1 +* @name Phaser.Gamepad#pad1 +* @property {Phaser.SinglePad} pad1 - Gamepad #1; +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad1", { + + get: function () { + return this._gamepads[0]; + } + +}); + +/** +* Gamepad #2 +* @name Phaser.Gamepad#pad2 +* @property {Phaser.SinglePad} pad2 - Gamepad #2 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad2", { + + get: function () { + return this._gamepads[1]; + } + +}); + +/** +* Gamepad #3 +* @name Phaser.Gamepad#pad3 +* @property {Phaser.SinglePad} pad3 - Gamepad #3 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad3", { + + get: function () { + return this._gamepads[2]; + } + +}); + +/** +* Gamepad #4 +* @name Phaser.Gamepad#pad4 +* @property {Phaser.SinglePad} pad4 - Gamepad #4 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad4", { + + get: function () { + return this._gamepads[3]; + } + +}); + +Phaser.Gamepad.BUTTON_0 = 0; +Phaser.Gamepad.BUTTON_1 = 1; +Phaser.Gamepad.BUTTON_2 = 2; +Phaser.Gamepad.BUTTON_3 = 3; +Phaser.Gamepad.BUTTON_4 = 4; +Phaser.Gamepad.BUTTON_5 = 5; +Phaser.Gamepad.BUTTON_6 = 6; +Phaser.Gamepad.BUTTON_7 = 7; +Phaser.Gamepad.BUTTON_8 = 8; +Phaser.Gamepad.BUTTON_9 = 9; +Phaser.Gamepad.BUTTON_10 = 10; +Phaser.Gamepad.BUTTON_11 = 11; +Phaser.Gamepad.BUTTON_12 = 12; +Phaser.Gamepad.BUTTON_13 = 13; +Phaser.Gamepad.BUTTON_14 = 14; +Phaser.Gamepad.BUTTON_15 = 15; + +Phaser.Gamepad.AXIS_0 = 0; +Phaser.Gamepad.AXIS_1 = 1; +Phaser.Gamepad.AXIS_2 = 2; +Phaser.Gamepad.AXIS_3 = 3; +Phaser.Gamepad.AXIS_4 = 4; +Phaser.Gamepad.AXIS_5 = 5; +Phaser.Gamepad.AXIS_6 = 6; +Phaser.Gamepad.AXIS_7 = 7; +Phaser.Gamepad.AXIS_8 = 8; +Phaser.Gamepad.AXIS_9 = 9; + +// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7). +// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button. +// In other words - discrepancies when using gamepads. + +Phaser.Gamepad.XBOX360_A = 0; +Phaser.Gamepad.XBOX360_B = 1; +Phaser.Gamepad.XBOX360_X = 2; +Phaser.Gamepad.XBOX360_Y = 3; +Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4; +Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5; +Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6; +Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7; +Phaser.Gamepad.XBOX360_BACK = 8; +Phaser.Gamepad.XBOX360_START = 9; +Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11; + +Phaser.Gamepad.XBOX360_DPAD_LEFT = 14; +Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15; +Phaser.Gamepad.XBOX360_DPAD_UP = 12; +Phaser.Gamepad.XBOX360_DPAD_DOWN = 13; + +// On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right +Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0; +Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1; +Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2; +Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3; + +// PlayStation 3 controller (masquerading as xbox360 controller) button mappings + +Phaser.Gamepad.PS3XC_X = 0; +Phaser.Gamepad.PS3XC_CIRCLE = 1; +Phaser.Gamepad.PS3XC_SQUARE = 2; +Phaser.Gamepad.PS3XC_TRIANGLE = 3; +Phaser.Gamepad.PS3XC_L1 = 4; +Phaser.Gamepad.PS3XC_R1 = 5; +Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_SELECT = 8; +Phaser.Gamepad.PS3XC_START = 9; +Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11; +Phaser.Gamepad.PS3XC_DPAD_UP = 12; +Phaser.Gamepad.PS3XC_DPAD_DOWN = 13; +Phaser.Gamepad.PS3XC_DPAD_LEFT = 14; +Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15; +Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1 + +/** +* @author @karlmacklin +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A single Phaser Gamepad +* +* @class Phaser.SinglePad +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this) +*/ +Phaser.SinglePad = function (game, padParent) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {number} index - The gamepad index as per browsers data + * @readonly + */ + this.index = null; + + /** + * @property {boolean} connected - Whether or not this particular gamepad is connected or not. + * @readonly + */ + this.connected = false; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time a button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time an axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates. + */ + this.deadZone = 0.26; + + /** + * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object + * @private + */ + this._padParent = padParent; + + /** + * @property {object} _rawPad - The 'raw' gamepad data. + * @private + */ + this._rawPad = null; + + /** + * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads. + * @private + */ + this._prevTimestamp = null; + + /** + * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected. + * @private + */ + this._buttons = []; + + /** + * @property {number} _buttonsLen - Length of the _buttons array. + * @private + */ + this._buttonsLen = 0; + + /** + * @property {Array} _axes - Current axes state. + * @private + */ + this._axes = []; + + /** + * @property {number} _axesLen - Length of the _axes array. + * @private + */ + this._axesLen = 0; + +}; + +Phaser.SinglePad.prototype = { + + /** + * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. + * + * @method Phaser.SinglePad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callbak methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + + this.callbackContext = context; + } + }, + + /** + * Gets a DeviceButton object from this controller to be stored and referenced locally. + * The DeviceButton object can then be polled, have events attached to it, etc. + * + * @method Phaser.SinglePad#getButton + * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc. + * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly. + */ + getButton: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode]; + } + else + { + return null; + } + + }, + + /** + * Main update function called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#pollStatus + */ + pollStatus: function () { + + if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp))) + { + return; + } + + for (var i = 0; i < this._buttonsLen; i++) + { + var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i]; + + if (rawButtonVal !== this._buttons[i].value) + { + if (rawButtonVal === 1) + { + this.processButtonDown(i, rawButtonVal); + } + else if (rawButtonVal === 0) + { + this.processButtonUp(i, rawButtonVal); + } + else + { + this.processButtonFloat(i, rawButtonVal); + } + } + } + + for (var index = 0; index < this._axesLen; index++) + { + var value = this._rawPad.axes[index]; + + if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone)) + { + this.processAxisChange(index, value); + } + else + { + this.processAxisChange(index, 0); + } + } + + this._prevTimestamp = this._rawPad.timestamp; + + }, + + /** + * Gamepad connect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#connect + * @param {object} rawPad - The raw gamepad object + */ + connect: function (rawPad) { + + var triggerCallback = !this.connected; + + this.connected = true; + this.index = rawPad.index; + + this._rawPad = rawPad; + + this._buttons = []; + this._buttonsLen = rawPad.buttons.length; + + this._axes = []; + this._axesLen = rawPad.axes.length; + + for (var a = 0; a < this._axesLen; a++) + { + this._axes[a] = rawPad.axes[a]; + } + + for (var buttonCode in rawPad.buttons) + { + buttonCode = parseInt(buttonCode, 10); + this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode); + } + + if (triggerCallback && this._padParent.onConnectCallback) + { + this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index); + } + + if (triggerCallback && this.onConnectCallback) + { + this.onConnectCallback.call(this.callbackContext); + } + + }, + + /** + * Gamepad disconnect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#disconnect + */ + disconnect: function () { + + var triggerCallback = this.connected; + var disconnectingIndex = this.index; + + this.connected = false; + this.index = null; + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + if (triggerCallback && this._padParent.onDisconnectCallback) + { + this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex); + } + + if (triggerCallback && this.onDisconnectCallback) + { + this.onDisconnectCallback.call(this.callbackContext); + } + + }, + + /** + * Destroys this object and associated callback references. + * + * @method Phaser.SinglePad#destroy + */ + destroy: function () { + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + this.onConnectCallback = null; + this.onDisconnectCallback = null; + this.onDownCallback = null; + this.onUpCallback = null; + this.onAxisCallback = null; + this.onFloatCallback = null; + + }, + + /** + * Handles changes in axis. + * + * @method Phaser.SinglePad#processAxisChange + * @param {object} axisState - State of the relevant axis + */ + processAxisChange: function (index, value) { + + if (this._axes[index] === value) + { + return; + } + + this._axes[index] = value; + + if (this._padParent.onAxisCallback) + { + this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value); + } + + if (this.onAxisCallback) + { + this.onAxisCallback.call(this.callbackContext, this, index, value); + } + + }, + + /** + * Handles button down press. + * + * @method Phaser.SinglePad#processButtonDown + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonDown: function (buttonCode, value) { + + if (this._buttons[buttonCode]) + { + this._buttons[buttonCode].start(null, value); + } + + 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); + } + + }, + + /** + * Handles button release. + * + * @method Phaser.SinglePad#processButtonUp + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonUp: function (buttonCode, value) { + + 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._buttons[buttonCode]) + { + this._buttons[buttonCode].stop(null, value); + } + + }, + + /** + * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) + * + * @method Phaser.SinglePad#processButtonFloat + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. + */ + processButtonFloat: function (buttonCode, value) { + + 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].padFloat(value); + } + + }, + + /** + * Returns value of requested axis. + * + * @method Phaser.SinglePad#axis + * @param {number} axisCode - The index of the axis to check + * @return {number} Axis value if available otherwise false + */ + axis: function (axisCode) { + + if (this._axes[axisCode]) + { + return this._axes[axisCode]; + } + + return false; + + }, + + /** + * Returns true if the button is pressed down. + * + * @method Phaser.SinglePad#isDown + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is pressed down. + */ + isDown: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isDown; + } + + return false; + + }, + + /** + * Returns true if the button is not currently pressed. + * + * @method Phaser.SinglePad#isUp + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is not currently pressed down. + */ + isUp: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isUp; + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justReleased + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justReleased(duration); + } + + }, + + /** + * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justPressed(duration); + } + + }, + + /** + * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example + * analog trigger buttons on the XBOX 360 controller. + * + * @method Phaser.SinglePad#buttonValue + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. + */ + buttonValue: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].value; + } + + return null; + + }, + + /** + * Reset all buttons/axes of this gamepad. + * + * @method Phaser.SinglePad#reset + */ + reset: function () { + + for (var j = 0; j < this._axes.length; j++) + { + this._axes[j] = 0; + } + + } + +}; + +Phaser.SinglePad.prototype.constructor = Phaser.SinglePad; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. +* +* @class Phaser.Key +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}. +*/ +Phaser.Key = function (game, keycode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * The enabled state of the key - see `enabled`. + * @property {boolean} _enabled + * @private + */ + this._enabled = true; + + /** + * @property {object} event - Stores the most recent DOM event. + * @readonly + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * @default + */ + this.isUp = true; + + /** + * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. + * @default + */ + this.altKey = false; + + /** + * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. + * @default + */ + this.ctrlKey = false; + + /** + * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. + * @default + */ + this.shiftKey = false; + + /** + * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now. + */ + this.timeDown = 0; + + /** + * If the key is down this value holds the duration of that key press and is constantly updated. + * If the key is up it holds the duration of the previous down session. + * @property {number} duration - The number of milliseconds this key has been held down for. + * @default + */ + this.duration = 0; + + /** + * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now. + * @default + */ + this.timeUp = -2500; + + /** + * If the key is up this value holds the duration of that key release and is constantly updated. + * If the key is down it holds the duration of the previous up session. + * @property {number} duration - The number of milliseconds this key has been up for. + * @default + */ + this.durationUp = -2500; + + /** + * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. + * @default + */ + this.repeats = 0; + + /** + * @property {number} keyCode - The keycode of this key. + */ + this.keyCode = keycode; + + /** + * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). + */ + this.onDown = new Phaser.Signal(); + + /** + * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. + */ + this.onHoldCallback = null; + + /** + * @property {object} onHoldContext - The context under which the onHoldCallback will be called. + */ + this.onHoldContext = null; + + /** + * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). + */ + this.onUp = new Phaser.Signal(); + + /** + * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justDown = false; + + /** + * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justUp = false; + +}; + +Phaser.Key.prototype = { + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#update + * @protected + */ + update: function () { + + if (!this._enabled) { return; } + + if (this.isDown) + { + this.duration = this.game.time.time - this.timeDown; + this.repeats++; + + if (this.onHoldCallback) + { + this.onHoldCallback.call(this.onHoldContext, this); + } + } + else + { + this.durationUp = this.game.time.time - this.timeUp; + } + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyDown + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyDown: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + // exit if this key down is from auto-repeat + if (this.isDown) + { + return; + } + + this.altKey = event.altKey; + this.ctrlKey = event.ctrlKey; + this.shiftKey = event.shiftKey; + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.duration = 0; + this.durationUp = this.game.time.time - this.timeUp; + this.repeats = 0; + + // _justDown will remain true until it is read via the justDown Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justDown = true; + + this.onDown.dispatch(this); + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyUp + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyUp: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = this.game.time.time - this.timeDown; + this.durationUp = 0; + + // _justUp will remain true until it is read via the justUp Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justUp = true; + + this.onUp.dispatch(this); + + }, + + /** + * Resets the state of this Key. + * + * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key. + * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. + * + * @method Phaser.Key#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = 0; + this.durationUp = -2500; + this._enabled = true; // .enabled causes reset(false) + this._justDown = false; + this._justUp = false; + + if (hard) + { + this.onDown.removeAll(); + this.onUp.removeAll(); + this.onHoldCallback = null; + this.onHoldContext = null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#downDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration. + */ + downDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (this.isDown && this.duration < duration); + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#upDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration. + */ + upDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (!this.isDown && ((this.game.time.time - this.timeUp) < duration)); + + }, + + /** + * Returns `true` if the Key was just pressed down this update tick, or `false` if it either isn't down, + * or was pressed down on a previous update tick. + * + * @method Phaser.Key#justPressed + * @return {boolean} True if the key was just pressed down this update tick. + */ + justPressed: function () { + + return (this.isDown && this.duration === 0); + + }, + + /** + * Returns `true` if the Key was just released this update tick, or `false` if it either isn't up, + * or was released on a previous update tick. + * + * @method Phaser.Key#justReleased + * @return {boolean} True if the key was just released this update tick. + */ + justReleased: function () { + + return (!this.isDown && this.durationUp === 0); + + } + +}; + +/** +* The justDown value allows you to test if this Key has just been pressed down or not. +* When you check this value it will return `true` if the Key is down, otherwise `false`. +* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. +* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justDown +* @property {boolean} justDown +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justDown", { + + get: function () { + + var current = this._justDown; + this._justDown = false; + return current; + + } + +}); + +/** +* The justUp value allows you to test if this Key has just been released or not. +* When you check this value it will return `true` if the Key is up, otherwise `false`. +* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again. +* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justUp +* @property {boolean} justUp +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justUp", { + + get: function () { + + var current = this._justUp; + this._justUp = false; + return current; + + } + +}); + +/** +* An enabled key processes its update and dispatches events. +* A key can be disabled momentarily at runtime instead of deleting it. +* @name Phaser.Key#enabled +* @property {boolean} enabled +* @memberof Phaser.Key +* @default true +*/ +Object.defineProperty(Phaser.Key.prototype, "enabled", { + + get: function () { + + return this._enabled; + + }, + + set: function (value) { + + value = !!value; + + if (value !== this._enabled) + { + if (!value) + { + this.reset(false); + } + + this._enabled = value; + } + } + +}); + +Phaser.Key.prototype.constructor = Phaser.Key; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Keyboard class monitors keyboard input and dispatches keyboard events. +* +* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. +* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. +* +* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. +* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. +* So please check your extensions before opening Phaser issues. +* +* @class Phaser.Keyboard +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Keyboard = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Keyboard input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. + */ + this.event = null; + + /** + * @property {object} pressEvent - The most recent DOM event from keypress. + */ + this.pressEvent = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. + */ + this.onDownCallback = null; + + /** + * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. + */ + this.onPressCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a key is released. + */ + this.onUpCallback = null; + + /** + * @property {array} _keys - The array the Phaser.Key objects are stored in. + * @private + */ + this._keys = []; + + /** + * @property {array} _capture - The array the key capture values are stored in. + * @private + */ + this._capture = []; + + /** + * @property {function} _onKeyDown + * @private + * @default + */ + this._onKeyDown = null; + + /** + * @property {function} _onKeyPress + * @private + * @default + */ + this._onKeyPress = null; + + /** + * @property {function} _onKeyUp + * @private + * @default + */ + this._onKeyUp = null; + + /** + * @property {number} _i - Internal cache var + * @private + */ + this._i = 0; + + /** + * @property {number} _k - Internal cache var + * @private + */ + this._k = 0; + +}; + +Phaser.Keyboard.prototype = { + + /** + * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. + * + * @method Phaser.Keyboard#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down. + * @param {function} [onUp=null] - This callback is invoked every time a key is released. + * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised. + */ + addCallbacks: function (context, onDown, onUp, onPress) { + + this.callbackContext = context; + + if (onDown !== undefined && onDown !== null) + { + this.onDownCallback = onDown; + } + + if (onUp !== undefined && onUp !== null) + { + this.onUpCallback = onUp; + } + + if (onPress !== undefined && onPress !== null) + { + this.onPressCallback = onPress; + } + + }, + + /** + * Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}. + * + * @method Phaser.Keyboard#removeCallbacks + */ + removeCallbacks: function () { + + this.callbackContext = this; + this.onDownCallback = null; + this.onUpCallback = null; + this.onPressCallback = null; + + }, + + /** + * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. + * The Key object can then be polled, have events attached to it, etc. + * + * @method Phaser.Keyboard#addKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key. + * @return {Phaser.Key} The Key object which you can store locally and reference directly. + */ + addKey: function (keycode) { + + if (!this._keys[keycode]) + { + this._keys[keycode] = new Phaser.Key(this.game, keycode); + + this.addKeyCapture(keycode); + } + + return this._keys[keycode]; + + }, + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example, + * + * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); + * + * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object. + * + * @method Phaser.Keyboard#addKeys + * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. + * @return {object} An object containing the properties mapped to {@link Phaser.Key} values. + */ + addKeys: function (keys) { + + var output = {}; + + for (var key in keys) + { + output[key] = this.addKey(keys[key]); + } + + return output; + + }, + + /** + * Removes a Key object from the Keyboard manager. + * + * @method Phaser.Keyboard#removeKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove. + */ + removeKey: function (keycode) { + + if (this._keys[keycode]) + { + this._keys[keycode] = null; + + this.removeKeyCapture(keycode); + } + + }, + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. + * + * @method Phaser.Keyboard#createCursorKeys + * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects. + */ + createCursorKeys: function () { + + return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT }); + + }, + + /** + * Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window. + * This is called automatically by Phaser.Input and should not normally be invoked directly. + * + * @method Phaser.Keyboard#start + * @protected + */ + start: function () { + + if (this.game.device.cocoonJS) + { + return; + } + + if (this._onKeyDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onKeyDown = function (event) { + return _this.processKeyDown(event); + }; + + this._onKeyUp = function (event) { + return _this.processKeyUp(event); + }; + + this._onKeyPress = function (event) { + return _this.processKeyPress(event); + }; + + window.addEventListener('keydown', this._onKeyDown, false); + window.addEventListener('keyup', this._onKeyUp, false); + window.addEventListener('keypress', this._onKeyPress, false); + + }, + + /** + * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. + * + * @method Phaser.Keyboard#stop + */ + stop: function () { + + window.removeEventListener('keydown', this._onKeyDown); + window.removeEventListener('keyup', this._onKeyUp); + window.removeEventListener('keypress', this._onKeyPress); + + this._onKeyDown = null; + this._onKeyUp = null; + this._onKeyPress = null; + + }, + + /** + * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. + * Also clears all key captures and currently created Key objects. + * + * @method Phaser.Keyboard#destroy + */ + destroy: function () { + + this.stop(); + + this.clearCaptures(); + + this._keys.length = 0; + this._i = 0; + + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Pass in either a single keycode or an array/hash of keycodes. + * + * @method Phaser.Keyboard#addKeyCapture + * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`. + */ + addKeyCapture: function (keycode) { + + if (typeof keycode === 'object') + { + for (var key in keycode) + { + this._capture[keycode[key]] = true; + } + } + else + { + this._capture[keycode] = true; + } + }, + + /** + * Removes an existing key capture. + * + * @method Phaser.Keyboard#removeKeyCapture + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of. + */ + removeKeyCapture: function (keycode) { + + delete this._capture[keycode]; + + }, + + /** + * Clear all set key captures. + * + * @method Phaser.Keyboard#clearCaptures + */ + clearCaptures: function () { + + this._capture = {}; + + }, + + /** + * Updates all currently defined keys. + * + * @method Phaser.Keyboard#update + */ + update: function () { + + this._i = this._keys.length; + + while (this._i--) + { + if (this._keys[this._i]) + { + this._keys[this._i].update(); + } + } + + }, + + /** + * Process the keydown event. + * + * @method Phaser.Keyboard#processKeyDown + * @param {KeyboardEvent} event + * @protected + */ + processKeyDown: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + // The event is being captured but another hotkey may need it + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyDown(event); + + this._k = key; + + if (this.onDownCallback) + { + this.onDownCallback.call(this.callbackContext, event); + } + + }, + + /** + * Process the keypress event. + * + * @method Phaser.Keyboard#processKeyPress + * @param {KeyboardEvent} event + * @protected + */ + processKeyPress: function (event) { + + this.pressEvent = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.onPressCallback) + { + this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event); + } + + }, + + /** + * Process the keyup event. + * + * @method Phaser.Keyboard#processKeyUp + * @param {KeyboardEvent} event + * @protected + */ + processKeyUp: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyUp(event); + + if (this.onUpCallback) + { + this.onUpCallback.call(this.callbackContext, event); + } + + }, + + /** + * Resets all Keys. + * + * @method Phaser.Keyboard#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.event = null; + + var i = this._keys.length; + + while (i--) + { + if (this._keys[i]) + { + this._keys[i].reset(hard); + } + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#downDuration + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. + */ + downDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].downDuration(duration); + } + else + { + return null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#upDuration + * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found. + */ + upDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].upDuration(duration); + } + else + { + return null; + } + + }, + + justPressed: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justPressed(); + } + else + { + return null; + } + + }, + + justReleased: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justReleased(); + } + else + { + return null; + } + + }, + + /** + * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. + * + * @method Phaser.Keyboard#isDown + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found. + */ + isDown: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].isDown; + } + else + { + return null; + } + + } + +}; + +/** +* Returns the string value of the most recently pressed key. +* @name Phaser.Keyboard#lastChar +* @property {string} lastChar - The string value of the most recently pressed key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", { + + get: function () { + + if (this.event && this.event.charCode === 32) + { + return ''; + } + else if (this.pressEvent) + { + return String.fromCharCode(this.pressEvent.charCode); + } + else + { + return null; + } + + } + +}); + +/** +* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. +* @name Phaser.Keyboard#lastKey +* @property {Phaser.Key} lastKey - The most recently pressed Key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", { + + get: function () { + + return this._keys[this._k]; + + } + +}); + +Phaser.Keyboard.prototype.constructor = Phaser.Keyboard; + +/** +* A key code represents a physical key on a keyboard. +* +* The KeyCode class contains commonly supported keyboard key codes which can be used +* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods. +* +* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. +* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. +* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property. +* +* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; +* the latter approach is supported for compatibility. +* +* @class Phaser.KeyCode +*/ +Phaser.KeyCode = { + /** @static */ + A: "A".charCodeAt(0), + /** @static */ + B: "B".charCodeAt(0), + /** @static */ + C: "C".charCodeAt(0), + /** @static */ + D: "D".charCodeAt(0), + /** @static */ + E: "E".charCodeAt(0), + /** @static */ + F: "F".charCodeAt(0), + /** @static */ + G: "G".charCodeAt(0), + /** @static */ + H: "H".charCodeAt(0), + /** @static */ + I: "I".charCodeAt(0), + /** @static */ + J: "J".charCodeAt(0), + /** @static */ + K: "K".charCodeAt(0), + /** @static */ + L: "L".charCodeAt(0), + /** @static */ + M: "M".charCodeAt(0), + /** @static */ + N: "N".charCodeAt(0), + /** @static */ + O: "O".charCodeAt(0), + /** @static */ + P: "P".charCodeAt(0), + /** @static */ + Q: "Q".charCodeAt(0), + /** @static */ + R: "R".charCodeAt(0), + /** @static */ + S: "S".charCodeAt(0), + /** @static */ + T: "T".charCodeAt(0), + /** @static */ + U: "U".charCodeAt(0), + /** @static */ + V: "V".charCodeAt(0), + /** @static */ + W: "W".charCodeAt(0), + /** @static */ + X: "X".charCodeAt(0), + /** @static */ + Y: "Y".charCodeAt(0), + /** @static */ + Z: "Z".charCodeAt(0), + /** @static */ + ZERO: "0".charCodeAt(0), + /** @static */ + ONE: "1".charCodeAt(0), + /** @static */ + TWO: "2".charCodeAt(0), + /** @static */ + THREE: "3".charCodeAt(0), + /** @static */ + FOUR: "4".charCodeAt(0), + /** @static */ + FIVE: "5".charCodeAt(0), + /** @static */ + SIX: "6".charCodeAt(0), + /** @static */ + SEVEN: "7".charCodeAt(0), + /** @static */ + EIGHT: "8".charCodeAt(0), + /** @static */ + NINE: "9".charCodeAt(0), + /** @static */ + NUMPAD_0: 96, + /** @static */ + NUMPAD_1: 97, + /** @static */ + NUMPAD_2: 98, + /** @static */ + NUMPAD_3: 99, + /** @static */ + NUMPAD_4: 100, + /** @static */ + NUMPAD_5: 101, + /** @static */ + NUMPAD_6: 102, + /** @static */ + NUMPAD_7: 103, + /** @static */ + NUMPAD_8: 104, + /** @static */ + NUMPAD_9: 105, + /** @static */ + NUMPAD_MULTIPLY: 106, + /** @static */ + NUMPAD_ADD: 107, + /** @static */ + NUMPAD_ENTER: 108, + /** @static */ + NUMPAD_SUBTRACT: 109, + /** @static */ + NUMPAD_DECIMAL: 110, + /** @static */ + NUMPAD_DIVIDE: 111, + /** @static */ + F1: 112, + /** @static */ + F2: 113, + /** @static */ + F3: 114, + /** @static */ + F4: 115, + /** @static */ + F5: 116, + /** @static */ + F6: 117, + /** @static */ + F7: 118, + /** @static */ + F8: 119, + /** @static */ + F9: 120, + /** @static */ + F10: 121, + /** @static */ + F11: 122, + /** @static */ + F12: 123, + /** @static */ + F13: 124, + /** @static */ + F14: 125, + /** @static */ + F15: 126, + /** @static */ + COLON: 186, + /** @static */ + EQUALS: 187, + /** @static */ + COMMA: 188, + /** @static */ + UNDERSCORE: 189, + /** @static */ + PERIOD: 190, + /** @static */ + QUESTION_MARK: 191, + /** @static */ + TILDE: 192, + /** @static */ + OPEN_BRACKET: 219, + /** @static */ + BACKWARD_SLASH: 220, + /** @static */ + CLOSED_BRACKET: 221, + /** @static */ + QUOTES: 222, + /** @static */ + BACKSPACE: 8, + /** @static */ + TAB: 9, + /** @static */ + CLEAR: 12, + /** @static */ + ENTER: 13, + /** @static */ + SHIFT: 16, + /** @static */ + CONTROL: 17, + /** @static */ + ALT: 18, + /** @static */ + CAPS_LOCK: 20, + /** @static */ + ESC: 27, + /** @static */ + SPACEBAR: 32, + /** @static */ + PAGE_UP: 33, + /** @static */ + PAGE_DOWN: 34, + /** @static */ + END: 35, + /** @static */ + HOME: 36, + /** @static */ + LEFT: 37, + /** @static */ + UP: 38, + /** @static */ + RIGHT: 39, + /** @static */ + DOWN: 40, + /** @static */ + PLUS: 43, + /** @static */ + MINUS: 44, + /** @static */ + INSERT: 45, + /** @static */ + DELETE: 46, + /** @static */ + HELP: 47, + /** @static */ + NUM_LOCK: 144 +}; + +// Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility +for (var key in Phaser.KeyCode) +{ + if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/)) + { + Phaser.Keyboard[key] = Phaser.KeyCode[key]; + } +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +Phaser.Component = function () {}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. +* +* @class +*/ +Phaser.Component.Angle = function () {}; + +Phaser.Component.Angle.prototype = { + + /** + * The angle property is the rotation of the Game Object in *degrees* from its original orientation. + * + * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. + * + * Values outside this range are added to or subtracted from 360 to obtain a value within the range. + * For example, the statement player.angle = 450 is the same as player.angle = 90. + * + * If you wish to work in radians instead of degrees you can use the property `rotation` instead. + * Working in radians is slightly faster as it doesn't have to perform any calculations. + * + * @property {number} angle + */ + angle: { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); + + }, + + set: function(value) { + + this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. +* +* @class +*/ +Phaser.Component.Animation = function () {}; + +Phaser.Component.Animation.prototype = { + + /** + * Plays an Animation. + * + * The animation should have previously been created via `animations.add`. + * + * If the animation is already playing calling this again won't do anything. + * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. + * + * @method + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation. + */ + play: function (name, frameRate, loop, killOnComplete) { + + if (this.animations) + { + return this.animations.play(name, frameRate, loop, killOnComplete); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. +* It is used by the InWorld component. +* +* @class +*/ +Phaser.Component.AutoCull = function () {}; + +Phaser.Component.AutoCull.prototype = { + + /** + * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. + * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. + * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} autoCull + * @default + */ + autoCull: false, + + /** + * Checks if the Game Objects bounds intersect with the Game Camera bounds. + * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + if (!this.autoCull && !this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + } + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Bounds component contains properties related to the bounds of the Game Object. +* +* @class +*/ +Phaser.Component.Bounds = function () {}; + +Phaser.Component.Bounds.prototype = { + + /** + * The amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * anchor.x`. + * It will only be > 0 if anchor.x is not equal to zero. + * + * @property {number} offsetX + * @readOnly + */ + offsetX: { + + get: function () { + + return this.anchor.x * this.width; + + } + + }, + + /** + * The amount the Game Object is visually offset from its y coordinate. + * This is the same as `height * anchor.y`. + * It will only be > 0 if anchor.y is not equal to zero. + * + * @property {number} offsetY + * @readOnly + */ + offsetY: { + + get: function () { + + return this.anchor.y * this.height; + + } + + }, + + /** + * The local center x coordinate of the Game Object. + * This is the same as `(x - offsetX) + (width / 2)`. + * + * @property {number} centerX + */ + centerX: { + + get: function () { + + return (this.x - this.offsetX) + (this.width * 0.5); + + }, + + set: function (value) { + + this.x = (value + this.offsetX) - (this.width * 0.5); + + } + + }, + + /** + * The local center y coordinate of the Game Object. + * This is the same as `(y - offsetY) + (height / 2)`. + * + * @property {number} centerY + */ + centerY: { + + get: function () { + + return (this.y - this.offsetY) + (this.height * 0.5); + + }, + + set: function (value) { + + this.y = (value + this.offsetY) - (this.height * 0.5); + + } + + }, + + /** + * The left coordinate of the Game Object. + * This is the same as `x - offsetX`. + * + * @property {number} left + */ + left: { + + get: function () { + + return this.x - this.offsetX; + + }, + + set: function (value) { + + this.x = value + this.offsetX; + + } + + }, + + /** + * The right coordinate of the Game Object. + * This is the same as `x + width - offsetX`. + * + * @property {number} right + */ + right: { + + get: function () { + + return (this.x + this.width) - this.offsetX; + + }, + + set: function (value) { + + this.x = value - (this.width) + this.offsetX; + + } + + }, + + /** + * The y coordinate of the Game Object. + * This is the same as `y - offsetY`. + * + * @property {number} top + */ + top: { + + get: function () { + + return this.y - this.offsetY; + + }, + + set: function (value) { + + this.y = value + this.offsetY; + + } + + }, + + /** + * The sum of the y and height properties. + * This is the same as `y + height - offsetY`. + * + * @property {number} bottom + */ + bottom: { + + get: function () { + + return (this.y + this.height) - this.offsetY; + + }, + + set: function (value) { + + this.y = value - (this.height) + this.offsetY; + + } + + }, + + /** + * Aligns this Game Object within another Game Object, or Rectangle, known as the + * 'container', to one of 9 possible positions. + * + * The container must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the container. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, + * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * container, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignIn: function (container, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = container.left - offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = container.centerX + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = container.right + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.left = container.left - offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.CENTER: + this.centerX = container.centerX + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.right = container.right + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = container.left - offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = container.centerX + offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = container.right + offsetX; + this.bottom = container.bottom + offsetY; + break; + } + + return this; + + }, + + /** + * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the + * 'parent', in one of 11 possible positions. + * + * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the parent. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, + * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, + * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * parent, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignTo: function (parent, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = parent.left - offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = parent.centerX + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = parent.right + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.LEFT_TOP: + this.right = parent.left - offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.right = parent.left - offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.LEFT_BOTTOM: + this.right = parent.left - offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.RIGHT_TOP: + this.left = parent.right + offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.left = parent.right + offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.RIGHT_BOTTOM: + this.left = parent.right + offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = parent.left - offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = parent.centerX + offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = parent.right + offsetX; + this.top = parent.bottom + offsetY; + break; + } + + return this; + + } + +}; + +// Phaser.Group extensions + +Phaser.Group.prototype.alignIn = Phaser.Component.Bounds.prototype.alignIn; +Phaser.Group.prototype.alignTo = Phaser.Component.Bounds.prototype.alignTo; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The BringToTop Component features quick access to Group sorting related methods. +* +* @class +*/ +Phaser.Component.BringToTop = function () {}; + +/** +* Brings this Game Object to the top of its parents display list. +* Visually this means it will render over the top of any old child in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.bringToTop = function() { + + if (this.parent) + { + this.parent.bringToTop(this); + } + + return this; + +}; + +/** +* Sends this Game Object to the bottom of its parents display list. +* Visually this means it will render below all other children in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.sendToBack = function() { + + if (this.parent) + { + this.parent.sendToBack(this); + } + + return this; + +}; + +/** +* Moves this Game Object up one place in its parents display list. +* This call has no effect if the Game Object is already at the top of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveUp = function () { + + if (this.parent) + { + this.parent.moveUp(this); + } + + return this; + +}; + +/** +* Moves this Game Object down one place in its parents display list. +* This call has no effect if the Game Object is already at the bottom of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveDown = function () { + + if (this.parent) + { + this.parent.moveDown(this); + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Core Component Features. +* +* @class +*/ +Phaser.Component.Core = function () {}; + +/** + * @property {boolean} skipTypeChecks - Skip type checks in {@link #init}. + * @static + * @default + */ +Phaser.Component.Core.skipTypeChecks = false; + +/** +* Installs / registers mixin components. +* +* The `this` context should be that of the applicable object instance or prototype. +* +* @method +* @protected +*/ +Phaser.Component.Core.install = function (components) { + + // Always install 'Core' first + Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype); + + this.components = {}; + + for (var i = 0; i < components.length; i++) + { + var id = components[i]; + var replace = false; + + if (id === 'Destroy') + { + replace = true; + } + + Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace); + + this.components[id] = true; + } + +}; + +/** +* Initializes the mixin components. +* +* The `this` context should be an instance of the component mixin target. +* +* @method +* @protected +*/ +Phaser.Component.Core.init = function (game, x, y, key, frame) { + + if (!Phaser.Component.Core.skipTypeChecks) + { + if (!(game instanceof Phaser.Game)) + { + throw new Error('The value passed as the `game` argument (' + game + ') is not an instance of Phaser.Game.'); + } + + if (typeof x !== 'number') + { + console.warn('The `x` argument value (%s) should be a number.', x); + x = 0; // This would be done implicitly in position.set(). + } + + if (typeof y !== 'number') + { + console.warn('The `y` argument value (%s) should be a number.', y); + y = 0; // This would be done implicitly in position.set(). + } + } + + this.game = game; + this.key = key; + this.data = {}; + + this.position.set(x, y); + this.world = new Phaser.Point(x, y); + this.previousPosition = new Phaser.Point(x, y); + + this.events = new Phaser.Events(this); + + this._bounds = new Phaser.Rectangle(); + + if (this.components.PhysicsBody) + { + // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype. + this.body = this.body; + } + + if (this.components.Animation) + { + this.animations = new Phaser.AnimationManager(this); + } + + if (this.components.LoadTexture && key !== null) + { + this.loadTexture(key, frame); + } + + if (this.components.FixedToCamera) + { + this.cameraOffset = new Phaser.Point(x, y); + } + +}; + +Phaser.Component.Core.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty); + + if (this.visible) + { + this.renderOrderID = this.game.stage.currentRenderOrderID++; + } + + if (this.animations) + { + this.animations.update(); + } + + if (this.body) + { + this.body.preUpdate(); + } + + this.preUpdateChildren(); + + return true; + +}; + +Phaser.Component.Core.prototype = { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + game: null, + + /** + * A user defined name given to this Game Object. + * This value isn't ever used internally by Phaser, it is meant as a game level property. + * @property {string} name + * @default + */ + name: '', + + /** + * An empty Object that belongs to this Game Object. + * This value isn't ever used internally by Phaser, but may be used by your own code, or + * by Phaser Plugins, to store data that needs to be associated with the Game Object, + * without polluting the Game Object directly. + * @property {Object} data + * @default + */ + data: {}, + + /** + * The components this Game Object has installed. + * @property {object} components + * @protected + */ + components: {}, + + /** + * The z depth of this Game Object within its parent Group. + * No two objects in a Group can have the same z value. + * This value is adjusted automatically whenever the Group hierarchy changes. + * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. + * @property {number} z + * @readOnly + */ + z: 0, + + /** + * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this + * Game Object, or any of its components. + * @see Phaser.Events + * @property {Phaser.Events} events + */ + events: undefined, + + /** + * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. + * Through it you can create, play, pause and stop animations. + * @see Phaser.AnimationManager + * @property {Phaser.AnimationManager} animations + */ + animations: undefined, + + /** + * The key of the image or texture used by this Game Object during rendering. + * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. + * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. + * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. + * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key + */ + key: '', + + /** + * The world coordinates of this Game Object in pixels. + * Depending on where in the display list this Game Object is placed this value can differ from `position`, + * which contains the x/y coordinates relative to the Game Objects parent. + * @property {Phaser.Point} world + */ + world: null, + + /** + * A debug flag designed for use with `Game.enableStep`. + * @property {boolean} debug + * @default + */ + debug: false, + + /** + * The position the Game Object was located in the previous frame. + * @property {Phaser.Point} previousPosition + * @readOnly + */ + previousPosition: null, + + /** + * The rotation the Game Object was in set to in the previous frame. Value is in radians. + * @property {number} previousRotation + * @readOnly + */ + previousRotation: 0, + + /** + * The render order ID is used internally by the renderer and Input Manager and should not be modified. + * This property is mostly used internally by the renderers, but is exposed for the use of plugins. + * @property {number} renderOrderID + * @readOnly + */ + renderOrderID: 0, + + /** + * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. + * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. + * @property {boolean} fresh + * @readOnly + */ + fresh: true, + + /** + * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. + * You can set it directly to allow you to flag an object to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy an object from within one of its own callbacks + * such as with Buttons or other Input events. + * + * @property {boolean} pendingDestroy + */ + pendingDestroy: false, + + /** + * @property {Phaser.Rectangle} _bounds - Internal cache var. + * @private + */ + _bounds: null, + + /** + * @property {boolean} _exists - Internal cache var. + * @private + */ + _exists: true, + + /** + * Controls if this Game Object is processed by the core game loop. + * If this Game Object has a physics body it also controls if its physics body is updated or not. + * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. + * It also toggles the `visible` property to false as well. + * + * Setting `exists` to true will add its physics body back in to the physics world, if it has one. + * It will also set the `visible` property to `true`. + * + * @property {boolean} exists + */ + exists: { + + get: function () { + + return this._exists; + + }, + + set: function (value) { + + if (value) + { + this._exists = true; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.addToWorld(); + } + + this.visible = true; + } + else + { + this._exists = false; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.removeFromWorld(); + } + + this.visible = false; + } + + } + + }, + + /** + * Internal method called by preUpdate. + * + * @method + * @protected + */ + preUpdateChildren: function() { + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + }, + + /** + * Override this method in your own custom objects to handle any update requirements. + * It is called immediately after `preUpdate` and before `postUpdate`. + * Remember if this Game Object has any children you should call update on those too. + * + * @method + */ + update: function() { + + }, + + /** + * Internal method called by the World postUpdate cycle. + * + * @method + * @protected + */ + postUpdate: function() { + + if (this.customRender) + { + this.key.render(); + } + + if (this.components.PhysicsBody) + { + Phaser.Component.PhysicsBody.postUpdate.call(this); + } + + if (this.components.FixedToCamera) + { + Phaser.Component.FixedToCamera.postUpdate.call(this); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, +* which can be updated in real-time. +* +* @class +*/ +Phaser.Component.Crop = function () {}; + +Phaser.Component.Crop.prototype = { + + /** + * The Rectangle used to crop the texture this Game Object uses. + * Set this property via `crop`. + * If you modify this property directly you must call `updateCrop` in order to have the change take effect. + * @property {Phaser.Rectangle} cropRect + * @default + */ + cropRect: null, + + /** + * @property {Phaser.Rectangle} _crop - Internal cache var. + * @private + */ + _crop: null, + + /** + * Crop allows you to crop the texture being used to display this Game Object. + * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. + * + * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, + * or by modifying `cropRect` property directly and then calling `updateCrop`. + * + * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object + * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. + * + * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, + * in which case the values are duplicated to a local object. + * + * @method + * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. + * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. + */ + crop: function (rect, copy) { + + if (copy === undefined) { copy = false; } + + if (rect) + { + if (copy && this.cropRect !== null) + { + this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height); + } + else if (copy && this.cropRect === null) + { + this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height); + } + else + { + this.cropRect = rect; + } + + this.updateCrop(); + } + else + { + this._crop = null; + this.cropRect = null; + + this.resetFrame(); + } + + }, + + /** + * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, + * or the rectangle it references, then you need to update the crop frame by calling this method. + * + * @method + */ + updateCrop: function () { + + if (!this.cropRect) + { + return; + } + + var oldX = this.texture.crop.x; + var oldY = this.texture.crop.y; + var oldW = this.texture.crop.width; + var oldH = this.texture.crop.height; + + this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop); + this._crop.x += this._frame.x; + this._crop.y += this._frame.y; + + var cx = Math.max(this._frame.x, this._crop.x); + var cy = Math.max(this._frame.y, this._crop.y); + var cw = Math.min(this._frame.right, this._crop.right) - cx; + var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy; + + this.texture.crop.x = cx; + this.texture.crop.y = cy; + this.texture.crop.width = cw; + this.texture.crop.height = ch; + + this.texture.frame.width = Math.min(cw, this.cropRect.width); + this.texture.frame.height = Math.min(ch, this.cropRect.height); + + this.texture.width = this.texture.frame.width; + this.texture.height = this.texture.frame.height; + + this.texture._updateUvs(); + + if (this.tint !== 0xffffff && (oldX !== cx || oldY !== cy || oldW !== cw || oldH !== ch)) + { + this.texture.requiresReTint = true; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Delta component provides access to delta values between the Game Objects current and previous position. +* +* @class +*/ +Phaser.Component.Delta = function () {}; + +Phaser.Component.Delta.prototype = { + + /** + * Returns the delta x value. The difference between world.x now and in the previous frame. + * + * The value will be positive if the Game Object has moved to the right or negative if to the left. + * + * @property {number} deltaX + * @readonly + */ + deltaX: { + + get: function() { + + return this.world.x - this.previousPosition.x; + + } + + }, + + /** + * Returns the delta y value. The difference between world.y now and in the previous frame. + * + * The value will be positive if the Game Object has moved down or negative if up. + * + * @property {number} deltaY + * @readonly + */ + deltaY: { + + get: function() { + + return this.world.y - this.previousPosition.y; + + } + + }, + + /** + * Returns the delta z value. The difference between rotation now and in the previous frame. + * + * @property {number} deltaZ - The delta value. + * @readonly + */ + deltaZ: { + + get: function() { + + return this.rotation - this.previousRotation; + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Destroy component is responsible for destroying a Game Object. +* +* @class +*/ +Phaser.Component.Destroy = function () {}; + +Phaser.Component.Destroy.prototype = { + + /** + * As a Game Object runs through its destroy method this flag is set to true, + * and can be checked in any sub-systems or plugins it is being destroyed from. + * @property {boolean} destroyPhase + * @readOnly + */ + destroyPhase: false, + + /** + * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present + * and nulls its reference to `game`, freeing it up for garbage collection. + * + * If this Game Object has the Events component it will also dispatch the `onDestroy` event. + * + * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've + * more than one Game Object sharing the same BaseTexture. + * + * @method + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? + * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. + */ + destroy: function (destroyChildren, destroyTexture) { + + if (this.game === null || this.destroyPhase) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (destroyTexture === undefined) { destroyTexture = false; } + + this.destroyPhase = true; + + if (this.events) + { + this.events.onDestroy$dispatch(this); + } + + if (this.parent) + { + if (this.parent instanceof Phaser.Group) + { + this.parent.remove(this); + } + else + { + this.parent.removeChild(this); + } + } + + if (this.input) + { + this.input.destroy(); + } + + if (this.animations) + { + this.animations.destroy(); + } + + if (this.body) + { + this.body.destroy(); + } + + if (this.events) + { + this.events.destroy(); + } + + this.game.tweens.removeFrom(this); + + var i = this.children.length; + + if (destroyChildren) + { + while (i--) + { + this.children[i].destroy(destroyChildren); + } + } + else + { + while (i--) + { + this.removeChild(this.children[i]); + } + } + + if (this._crop) + { + this._crop = null; + this.cropRect = null; + } + + if (this._frame) + { + this._frame = null; + } + + if (Phaser.Video && this.key instanceof Phaser.Video) + { + this.key.onChangeSource.remove(this.resizeFrame, this); + } + + if (Phaser.BitmapText && this._glyphs) + { + this._glyphs = []; + } + + this.alive = false; + this.exists = false; + this.visible = false; + + this.filters = null; + this.mask = null; + this.game = null; + + this.data = {}; + + // In case Pixi is still going to try and render it even though destroyed + this.renderable = false; + + if (this.transformCallback) + { + this.transformCallback = null; + this.transformCallbackContext = null; + } + + // Pixi level DisplayObject destroy + this.hitArea = null; + this.parent = null; + this.stage = null; + this.worldTransform = null; + this.filterArea = null; + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + // Texture? + if (destroyTexture) + { + this.texture.destroy(true); + } + + this.destroyPhase = false; + this.pendingDestroy = false; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Events component is a collection of events fired by the parent Game Object. +* +* Phaser uses what are known as 'Signals' for all event handling. All of the events in +* this class are signals you can subscribe to, much in the same way you'd "listen" for +* an event. +* +* For example to tell when a Sprite has been added to a new group, you can bind a function +* to the {@link #onAddedToGroup} signal: +* +* `sprite.events.onAddedToGroup.add(yourFunction, this);` +* +* Where `yourFunction` is the function you want called when this event occurs. +* +* For more details about how signals work please see the {@link Phaser.Signal} class. +* +* The Input-related events will only be dispatched if the Sprite has had {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true` +* and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. +* +* @class Phaser.Events +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. +*/ +Phaser.Events = function (sprite) { + + /** + * @property {Phaser.Sprite} parent - The Sprite that owns these events. + */ + this.parent = sprite; + + // The signals are automatically added by the corresponding proxy properties + +}; + +Phaser.Events.prototype = { + + /** + * Removes all events. + * + * @method Phaser.Events#destroy + */ + destroy: function () { + + this._parent = null; + + if (this._onDestroy) { this._onDestroy.dispose(); } + if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } + if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } + if (this._onKilled) { this._onKilled.dispose(); } + if (this._onRevived) { this._onRevived.dispose(); } + if (this._onEnterBounds) { this._onEnterBounds.dispose(); } + if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } + + if (this._onInputOver) { this._onInputOver.dispose(); } + if (this._onInputOut) { this._onInputOut.dispose(); } + if (this._onInputDown) { this._onInputDown.dispose(); } + if (this._onInputUp) { this._onInputUp.dispose(); } + if (this._onDragStart) { this._onDragStart.dispose(); } + if (this._onDragUpdate) { this._onDragUpdate.dispose(); } + if (this._onDragStop) { this._onDragStop.dispose(); } + + if (this._onAnimationStart) { this._onAnimationStart.dispose(); } + if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } + if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } + + }, + + // The following properties are sentinels that will be replaced with getters + + /** + * This signal is dispatched when this Game Object is added to a new {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was added to the Group. + * - {Phaser.Group} The Group it was added to. + * + * @property {Phaser.Signal} onAddedToGroup + */ + onAddedToGroup: null, + + /** + * This signal is dispatched when the Game Object is removed from a {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was removed from the Group. + * - {Phaser.Group} The Group it was removed from. + * + * @property {Phaser.Signal} onRemovedFromGroup + */ + onRemovedFromGroup: null, + + /** + * This signal is dispatched when the Game Object is destroyed. + * This happens when {@link Phaser.Sprite#destroy Sprite.destroy()} is called, or {@link Phaser.Group#destroy Group.destroy()} with `destroyChildren` set to true. + * It is sent one argument: + * + * - {any} The Game Object that was destroyed. + * + * @property {Phaser.Signal} onDestroy + */ + onDestroy: null, + + /** + * This signal is dispatched when the Game Object is killed. + * This happens when {@link Phaser.Sprite#kill Sprite.kill()} is called. + * Please understand the difference between {@link Phaser.Sprite#kill kill} and {@link Phaser.Sprite#destroy destroy} by looking at their respective methods. + * It is sent one argument: + * + * - {any} The Game Object that was killed. + * + * @property {Phaser.Signal} onKilled + */ + onKilled: null, + + /** + * This signal is dispatched when the Game Object is revived from a previously killed state. + * This happens when {@link Phaser.Sprite#revive Sprite.revive()} is called. + * It is sent one argument: + * + * - {any} The Game Object that was revived. + * + * @property {Phaser.Signal} onRevived + */ + onRevived: null, + + /** + * This signal is dispatched when the Game Object leaves the Phaser.World {@link Phaser.World#bounds bounds}. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that left the World bounds. + * + * @property {Phaser.Signal} onOutOfBounds + */ + onOutOfBounds: null, + + /** + * This signal is dispatched when the Game Object returns within the Phaser.World {@link Phaser.World#bounds bounds}, having previously been outside of them. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that entered the World bounds. + * + * @property {Phaser.Signal} onEnterBounds + */ + onEnterBounds: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an over event from a {@link Phaser.Pointer}. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOver + */ + onInputOver: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an out event from a {@link Phaser.Pointer}, which was previously over it. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOut + */ + onInputOut: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives a down event from a {@link Phaser.Pointer}. This effectively means the Pointer has been + * pressed down (but not yet released) on the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputDown + */ + onInputDown: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an up event from a {@link Phaser.Pointer}. This effectively means the Pointer had been + * pressed down, and was then released on the Game Object. + * It is sent three arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {boolean} isOver - Is the Pointer still over the Game Object? + * + * @property {Phaser.Signal} onInputUp + */ + onInputUp: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} starts to drag the Game Object, taking into consideration the various + * drag limitations that may be set. + * It is sent four arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The x coordinate that the drag started from. + * - {number} The y coordinate that the drag started from. + * + * @property {Phaser.Signal} onDragStart + */ + onDragStart: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} is actively dragging the Game Object. + * Be warned: This is a high volume Signal. Be careful what you bind to it. + * It is sent six arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The new x coordinate of the Game Object. + * - {number} The new y coordinate of the Game Object. + * - {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. + * - {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. + * + * @property {Phaser.Signal} onDragUpdate + */ + onDragUpdate: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} stops dragging the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onDragStop + */ + onDragStop: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been played. + * You can also listen to {@link Phaser.Animation#onStart} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was started. + * + * @property {Phaser.Signal} onAnimationStart + */ + onAnimationStart: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been stopped (via {@link Phaser.AnimationManager#stop animation.stop()} and the `dispatchComplete` argument has been set. + * You can also listen to {@link Phaser.Animation#onComplete} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was stopped. + * + * @property {Phaser.Signal} onAnimationComplete + */ + onAnimationComplete: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has looped playback. + * You can also listen to {@link Phaser.Animation#onLoop} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that looped. + * + * @property {Phaser.Signal} onAnimationLoop + */ + onAnimationLoop: null + +}; + +Phaser.Events.prototype.constructor = Phaser.Events; + +// Create an auto-create proxy getter and dispatch method for all events. +// The backing property is the same as the event name, prefixed with '_' +// and the dispatch method is the same as the event name postfixed with '$dispatch'. +for (var prop in Phaser.Events.prototype) +{ + if (!Phaser.Events.prototype.hasOwnProperty(prop) || + prop.indexOf('on') !== 0 || + Phaser.Events.prototype[prop] !== null) + { + continue; + } + + (function (prop, backing) { + 'use strict'; + + // The accessor creates a new Signal; and so it should only be used from user-code. + Object.defineProperty(Phaser.Events.prototype, prop, { + get: function () { + return this[backing] || (this[backing] = new Phaser.Signal()); + } + }); + + // The dispatcher will only broadcast on an already-created signal; call this internally. + Phaser.Events.prototype[prop + '$dispatch'] = function () { + return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; + }; + + })(prop, '_' + prop); + +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless +* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. +* +* @class +*/ +Phaser.Component.FixedToCamera = function () {}; + +/** + * The FixedToCamera component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.FixedToCamera.postUpdate = function () { + + if (this.fixedToCamera) + { + 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.Component.FixedToCamera.prototype = { + + /** + * @property {boolean} _fixedToCamera + * @private + */ + _fixedToCamera: false, + + /** + * A Game Object that is "fixed" to the camera is rendered at a given x/y offsets from the top left of the camera. The offsets + * are stored in the `cameraOffset` property, which is initialized with the current object coordinates. + * + * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. + * + * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world + * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times + * regardless where in the world the camera is. + * + * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. + * + * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. + * + * @property {boolean} fixedToCamera + */ + fixedToCamera: { + + get: function () { + + return this._fixedToCamera; + + }, + + set: function (value) { + + if (value) + { + this._fixedToCamera = true; + this.cameraOffset.set(this.x, this.y); + } + else + { + this._fixedToCamera = false; + } + + } + + }, + + /** + * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. + * + * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. + * @property {Phaser.Point} cameraOffset + */ + cameraOffset: new Phaser.Point() + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Health component provides the ability for Game Objects to have a `health` property +* that can be damaged and reset through game code. +* Requires the LifeSpan component. +* +* @class +*/ +Phaser.Component.Health = function () {}; + +Phaser.Component.Health.prototype = { + + /** + * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. + * + * It can be used in combination with the `damage` method or modified directly. + * + * @property {number} health + * @default + */ + health: 1, + + /** + * The Game Objects maximum health value. This works in combination with the `heal` method to ensure + * the health value never exceeds the maximum. + * + * @property {number} maxHealth + * @default + */ + maxHealth: 100, + + /** + * Damages the Game Object. This removes the given amount of health from the `health` property. + * + * If health is taken below or is equal to zero then the `kill` method is called. + * + * @method + * @param {number} amount - The amount to subtract from the current `health` value. + * @return {Phaser.Sprite} This instance. + */ + damage: function (amount) { + + if (this.alive) + { + this.health -= amount; + + if (this.health <= 0) + { + this.kill(); + } + } + + return this; + + }, + + /** + * Sets the health property of the Game Object to the given amount. + * Will never exceed the `maxHealth` value. + * + * @method + * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + setHealth: function (amount) { + + this.health = amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + + return this; + + }, + + /** + * Heal the Game Object. This adds the given amount of health to the `health` property. + * + * @method + * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + heal: function (amount) { + + if (this.alive) + { + this.health += amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InCamera component checks if the Game Object intersects with the Game Camera. +* +* @class +*/ +Phaser.Component.InCamera = function () {}; + +Phaser.Component.InCamera.prototype = { + + /** + * Checks if this Game Objects bounds intersects with the Game Cameras bounds. + * + * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. + * + * An object outside the bounds can be considered for camera culling if it has the AutoCull component. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. +* +* @class +*/ +Phaser.Component.InputEnabled = function () {}; + +Phaser.Component.InputEnabled.prototype = { + + /** + * The Input Handler for this Game Object. + * + * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. + * + * After you have done this, this property will be a reference to the Phaser InputHandler. + * @property {Phaser.InputHandler|null} input + */ + input: null, + + /** + * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created + * for this Game Object and it will then start to process click / touch events and more. + * + * You can then access the Input Handler via `this.input`. + * + * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. + * + * If you set this property to false it will stop the Input Handler from processing any more input events. + * + * If you want to _temporarily_ disable input for a Game Object, then it's better to set + * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. + * You can then toggle this back on as needed. + * + * @property {boolean} inputEnabled + */ + inputEnabled: { + + get: function () { + + return (this.input && this.input.enabled); + + }, + + set: function (value) { + + if (value) + { + if (this.input === null) + { + this.input = new Phaser.InputHandler(this); + this.input.start(); + } + else if (this.input && !this.input.enabled) + { + this.input.start(); + } + } + else + { + if (this.input && this.input.enabled) + { + this.input.stop(); + } + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InWorld component checks if a Game Object is within the Game World Bounds. +* An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. +* If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. +* +* @class +*/ +Phaser.Component.InWorld = function () {}; + +/** + * The InWorld component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.InWorld.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + // Cache the bounds if we need it + if (this.autoCull || this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + + if (this.autoCull) + { + // Won't get rendered but will still get its transform updated + if (this.game.world.camera.view.intersects(this._bounds)) + { + this.renderable = true; + this.game.world.camera.totalInView++; + } + else + { + this.renderable = false; + + if (this.outOfCameraBoundsKill) + { + this.kill(); + return false; + } + } + } + + if (this.checkWorldBounds) + { + // The Sprite is already out of the world bounds, so let's check to see if it has come back again + if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds)) + { + this._outOfBoundsFired = false; + this.events.onEnterBounds$dispatch(this); + } + else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds)) + { + // The Sprite WAS in the screen, but has now left. + this._outOfBoundsFired = true; + this.events.onOutOfBounds$dispatch(this); + + if (this.outOfBoundsKill) + { + this.kill(); + return false; + } + } + } + } + + return true; + +}; + +Phaser.Component.InWorld.prototype = { + + /** + * If this is set to `true` the Game Object checks if it is within the World bounds each frame. + * + * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. + * + * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. + * + * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. + * + * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} checkWorldBounds + * @default + */ + checkWorldBounds: false, + + /** + * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. + * + * @property {boolean} outOfBoundsKill + * @default + */ + outOfBoundsKill: false, + + /** + * If this and the `autoCull` property are both set to `true`, then the `kill` method + * is called as soon as the Game Object leaves the camera bounds. + * + * @property {boolean} outOfCameraBoundsKill + * @default + */ + outOfCameraBoundsKill: false, + + /** + * @property {boolean} _outOfBoundsFired - Internal state var. + * @private + */ + _outOfBoundsFired: false, + + /** + * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. + * + * @property {boolean} inWorld + * @readonly + */ + inWorld: { + + get: function () { + + return this.game.world.bounds.intersects(this.getBounds()); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* LifeSpan Component Features. +* +* @class +*/ +Phaser.Component.LifeSpan = function () {}; + +/** + * The LifeSpan component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.LifeSpan.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.lifespan > 0) + { + this.lifespan -= this.game.time.physicsElapsedMS; + + if (this.lifespan <= 0) + { + this.kill(); + return false; + } + } + + return true; + +}; + +Phaser.Component.LifeSpan.prototype = { + + /** + * A useful flag to control if the Game Object is alive or dead. + * + * This is set automatically by the Health components `damage` method should the object run out of health. + * Or you can toggle it via your game code. + * + * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. + * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. + * @property {boolean} alive + * @default + */ + alive: true, + + /** + * The lifespan allows you to give a Game Object a lifespan in milliseconds. + * + * Once the Game Object is 'born' you can set this to a positive value. + * + * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. + * When it reaches zero it will call the `kill` method. + * + * Very handy for particles, bullets, collectibles, or any other short-lived entity. + * + * @property {number} lifespan + * @default + */ + lifespan: 0, + + /** + * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. + * + * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. + * + * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. + * + * @method + * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. + * @return {PIXI.DisplayObject} This instance. + */ + revive: function (health) { + + if (health === undefined) { health = 100; } + + this.alive = true; + this.exists = true; + this.visible = true; + + if (typeof this.setHealth === 'function') + { + this.setHealth(health); + } + + if (this.events) + { + this.events.onRevived$dispatch(this); + } + + return this; + + }, + + /** + * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. + * + * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. + * + * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, + * it doesn't destroy the object or free it up from memory. + * + * If you don't need this Game Object any more you should call `destroy` instead. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ + kill: function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + if (this.events) + { + this.events.onKilled$dispatch(this); + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. +* +* @class +*/ +Phaser.Component.LoadTexture = function () {}; + +Phaser.Component.LoadTexture.prototype = { + + /** + * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) + * @private + */ + customRender: false, + + /** + * @property {Phaser.Rectangle} _frame - Internal cache var. + * @private + */ + _frame: null, + + /** + * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. + * + * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. + * + * You should only use `loadTexture` if you want to replace the base texture entirely. + * + * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. + * + * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. + * Doing this then sets the key to be the `frame` argument (the frame is set to zero). + * + * This allows you to create sprites using `load.image` during development, and then change them + * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' + * and swapping it to be the key of the atlas data. + * + * Note: You cannot use a RenderTexture as a texture for a TileSprite. + * + * @method + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. + */ + loadTexture: function (key, frame, stopAnimation) { + + if (key === Phaser.PENDING_ATLAS) + { + key = frame; + frame = 0; + } + else + { + frame = frame || 0; + } + + if ((stopAnimation || stopAnimation === undefined) && this.animations) + { + this.animations.stop(); + } + + this.key = key; + this.customRender = false; + var cache = this.game.cache; + + var setFrame = true; + var smoothed = !this.texture.baseTexture.scaleMode; + + if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture) + { + this.key = key.key; + this.setTexture(key); + } + else if (Phaser.BitmapData && key instanceof Phaser.BitmapData) + { + this.customRender = true; + + this.setTexture(key.texture); + + if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA)) + { + setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame); + } + else + { + setFrame = !this.animations.loadFrameData(key.frameData, 0); + } + } + else if (Phaser.Video && key instanceof Phaser.Video) + { + this.customRender = true; + + // This works from a reference, which probably isn't what we need here + var valid = key.texture.valid; + this.setTexture(key.texture); + this.setFrame(key.texture.frame.clone()); + key.onChangeSource.add(this.resizeFrame, this); + this.texture.valid = valid; + } + else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer) + { + // this.customRender = true; + + this.setTexture(PIXI.Texture.fromCanvas(key.canvas)); + } + else if (key instanceof PIXI.Texture) + { + this.setTexture(key); + } + else + { + var img = cache.getImage(key, true); + + this.key = img.key; + this.setTexture(new PIXI.Texture(img.base)); + + if (key === '__default') + { + this.texture.baseTexture.skipRender = true; + } + else + { + this.texture.baseTexture.skipRender = false; + } + + setFrame = !this.animations.loadFrameData(img.frameData, frame); + } + + if (setFrame) + { + this._frame = Phaser.Rectangle.clone(this.texture.frame); + } + + if (!smoothed) + { + this.texture.baseTexture.scaleMode = 1; + } + + }, + + /** + * Sets the texture frame the Game Object uses for rendering. + * + * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. + * + * @method + * @param {Phaser.Frame} frame - The Frame to be used by the texture. + */ + setFrame: function (frame) { + + this._frame = frame; + + this.texture.frame.x = frame.x; + this.texture.frame.y = frame.y; + this.texture.frame.width = frame.width; + this.texture.frame.height = frame.height; + + this.texture.crop.x = frame.x; + this.texture.crop.y = frame.y; + this.texture.crop.width = frame.width; + this.texture.crop.height = frame.height; + + if (frame.trimmed) + { + if (this.texture.trim) + { + this.texture.trim.x = frame.spriteSourceSizeX; + this.texture.trim.y = frame.spriteSourceSizeY; + this.texture.trim.width = frame.sourceSizeW; + this.texture.trim.height = frame.sourceSizeH; + } + else + { + this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH }; + } + + this.texture.width = frame.sourceSizeW; + this.texture.height = frame.sourceSizeH; + this.texture.frame.width = frame.sourceSizeW; + this.texture.frame.height = frame.sourceSizeH; + } + else if (!frame.trimmed && this.texture.trim) + { + this.texture.trim = null; + } + + if (frame.rotated) + { + this.texture.rotated = true; + } + + if (this.cropRect) + { + this.updateCrop(); + } + + this.texture.requiresReTint = true; + + this.texture._updateUvs(); + + if (this.tilingTexture) + { + this.refreshTexture = true; + } + + }, + + /** + * Resizes the Frame dimensions that the Game Object uses for rendering. + * + * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData + * it can be useful to adjust the dimensions directly in this way. + * + * @method + * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. + * @param {integer} width - The new width of the texture. + * @param {integer} height - The new height of the texture. + */ + resizeFrame: function (parent, width, height) { + + this.texture.frame.resize(width, height); + this.texture.setFrame(this.texture.frame); + + }, + + /** + * Resets the texture frame dimensions that the Game Object uses for rendering. + * + * @method + */ + resetFrame: function () { + + if (this._frame) + { + this.setFrame(this._frame); + } + + }, + + /** + * Gets or sets the current frame index of the texture being used to render this Game Object. + * + * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, + * for example: `player.frame = 4`. + * + * If the frame index given doesn't exist it will revert to the first frame found in the texture. + * + * If you are using a texture atlas then you should use the `frameName` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {integer} frame + */ + frame: { + + get: function () { + return this.animations.frame; + }, + + set: function (value) { + this.animations.frame = value; + } + + }, + + /** + * Gets or sets the current frame name of the texture being used to render this Game Object. + * + * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, + * for example: `player.frameName = "idle"`. + * + * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. + * + * If you are using a sprite sheet then you should use the `frame` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {string} frameName + */ + frameName: { + + get: function () { + return this.animations.frameName; + }, + + set: function (value) { + this.animations.frameName = value; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. +* +* @class +*/ +Phaser.Component.Overlap = function () {}; + +Phaser.Component.Overlap.prototype = { + + /** + * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, + * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. + * + * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. + * + * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. + * It should be fine for low-volume testing where physics isn't required. + * + * @method + * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. + * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. + */ + overlap: function (displayObject) { + + return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds()); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The PhysicsBody component manages the Game Objects physics body and physics enabling. +* It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. +* +* @class +*/ +Phaser.Component.PhysicsBody = function () {}; + +/** + * The PhysicsBody component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.fresh && 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.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (this.body) + { + this.body.preUpdate(); + } + + this.fresh = false; + + this.preUpdateChildren(); + + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this._exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + return true; + +}; + +/** + * The PhysicsBody component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.postUpdate = function () { + + if (this.exists && this.body) + { + this.body.postUpdate(); + } + +}; + +Phaser.Component.PhysicsBody.prototype = { + + /** + * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated + * properties and methods via it. + * + * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. + * + * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object + * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. + * + * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. + * + * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, + * so the physics body is centered on the Game Object. + * + * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. + * + * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body + * @default + */ + body: null, + + /** + * The position of the Game Object on the x axis relative to the local coordinates of the parent. + * + * @property {number} x + */ + x: { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + }, + + /** + * The position of the Game Object on the y axis relative to the local coordinates of the parent. + * + * @property {number} y + */ + y: { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Reset component allows a Game Object to be reset and repositioned to a new location. +* +* @class +*/ +Phaser.Component.Reset = function () {}; + +/** +* Resets the Game Object. +* +* This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, +* `visible` and `renderable` to true. +* +* If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. +* +* If this Game Object has a Physics Body it will reset the Body. +* +* @method +* @param {number} x - The x coordinate (in world space) to position the Game Object at. +* @param {number} y - The y coordinate (in world space) to position the Game Object at. +* @param {number} [health=1] - The health to give the Game Object if it has the Health component. +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.Reset.prototype.reset = function (x, y, health) { + + if (health === undefined) { health = 1; } + + this.world.set(x, y); + this.position.set(x, y); + + this.fresh = true; + this.exists = true; + this.visible = true; + this.renderable = true; + + if (this.components.InWorld) + { + this._outOfBoundsFired = false; + } + + if (this.components.LifeSpan) + { + this.alive = true; + this.health = health; + } + + if (this.components.PhysicsBody) + { + if (this.body) + { + this.body.reset(x, y, false, false); + } + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. +* +* @class +*/ +Phaser.Component.ScaleMinMax = function () {}; + +Phaser.Component.ScaleMinMax.prototype = { + + /** + * The callback that will apply any scale limiting to the worldTransform. + * @property {function} transformCallback + */ + transformCallback: null, + + /** + * The context under which `transformCallback` is called. + * @property {object} transformCallbackContext + */ + transformCallbackContext: this, + + /** + * The minimum scale this Game Object will scale down to. + * + * It allows you to prevent a parent from scaling this Game Object lower than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMin + */ + scaleMin: null, + + /** + * The maximum scale this Game Object will scale up to. + * + * It allows you to prevent a parent from scaling this Game Object higher than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMax + */ + scaleMax: null, + + /** + * Adjust scaling limits, if set, to this Game Object. + * + * @method + * @private + * @param {Phaser.Matrix} wt - The updated worldTransform matrix. + */ + checkTransform: function (wt) { + + if (this.scaleMin) + { + if (wt.a < this.scaleMin.x) + { + wt.a = this.scaleMin.x; + } + + if (wt.d < this.scaleMin.y) + { + wt.d = this.scaleMin.y; + } + } + + if (this.scaleMax) + { + if (wt.a > this.scaleMax.x) + { + wt.a = this.scaleMax.x; + } + + if (wt.d > this.scaleMax.y) + { + wt.d = this.scaleMax.y; + } + } + + }, + + /** + * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. + * + * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored + * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. + * + * By setting these values you can carefully control how Game Objects deal with responsive scaling. + * + * If only one parameter is given then that value will be used for both scaleMin and scaleMax: + * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 + * + * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: + * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 + * + * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, + * or pass `null` for the `maxX` and `maxY` parameters. + * + * Call `setScaleMinMax(null)` to clear all previously set values. + * + * @method + * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to. + * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to. + * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to. + * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to. + */ + setScaleMinMax: function (minX, minY, maxX, maxY) { + + if (minY === undefined) + { + // 1 parameter, set all to it + minY = maxX = maxY = minX; + } + else if (maxX === undefined) + { + // 2 parameters, the first is min, the second max + maxX = maxY = minY; + minY = minX; + } + + if (minX === null) + { + this.scaleMin = null; + } + else + { + if (this.scaleMin) + { + this.scaleMin.set(minX, minY); + } + else + { + this.scaleMin = new Phaser.Point(minX, minY); + } + } + + if (maxX === null) + { + this.scaleMax = null; + } + else + { + if (this.scaleMax) + { + this.scaleMax.set(maxX, maxY); + } + else + { + this.scaleMax = new Phaser.Point(maxX, maxY); + } + } + + if (this.scaleMin === null) + { + this.transformCallback = null; + } + else + { + this.transformCallback = this.checkTransform; + this.transformCallbackContext = this; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. +* +* @class +*/ +Phaser.Component.Smoothed = function () {}; + +Phaser.Component.Smoothed.prototype = { + + /** + * Enable or disable texture smoothing for this Game Object. + * + * It only takes effect if the Game Object is using an image based texture. + * + * Smoothing is enabled by default. + * + * @property {boolean} smoothed + */ + smoothed: { + + get: function () { + + return !this.texture.baseTexture.scaleMode; + + }, + + set: function (value) { + + if (value) + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 0; + this.texture.baseTexture.dirty(); + } + } + else + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 1; + this.texture.baseTexture.dirty(); + } + } + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectFactory is a quick way to create many common game objects +* using {@linkcode Phaser.Game#add `game.add`}. +* +* Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group. +* +* @class Phaser.GameObjectFactory +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectFactory = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectFactory.prototype = { + + /** + * Adds an existing display object to the game world. + * + * @method Phaser.GameObjectFactory#existing + * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object. + * @return {any} The child that was added to the World. + */ + existing: function (object) { + + return this.world.add(object); + + }, + + /** + * Weapons provide the ability to easily create a bullet pool and manager. + * + * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. + * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. + * + * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you + * can usually do with a Group, such as move it around the display list, iterate it, etc can be done + * to the bullets Group too. + * + * Bullets can have textures and even animations. You can control the speed at which they are fired, + * the firing rate, the firing angle, and even set things like gravity for them. + * + * @method Phaser.GameObjectFactory#weapon + * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group. + * @param {function} [bulletClass] - The Class of the bullets that are launched by this Weapon. See {@link Phaser.Weapon#bulletClass} + * @returns {Phaser.Weapon} A Weapon instance. + */ + weapon: function (quantity, key, frame, group, bulletClass) { + + var weapon = this.game.plugins.add(Phaser.Weapon); + + if (bulletClass) + { + weapon.bulletClass = bulletClass; + } + + weapon.createBullets(quantity, key, frame, group); + + return weapon; + + }, + + /** + * Create a new `Image` object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * + * It can still rotate, scale, crop and receive input events. + * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectFactory#image + * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Image} The newly created Image object. + */ + image: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Image(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. + * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), + * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. + * + * @method Phaser.GameObjectFactory#sprite + * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Sprite} The newly created Sprite object. + */ + sprite: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Sprite(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Creature Animation object. + * + * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. + * + * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). + * + * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. + * + * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them + * loaded before your Phaser game boots. + * + * See the Phaser custom build process for more details. + * + * @method Phaser.GameObjectFactory#creature + * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Creature} The newly created Creature object. + */ + creature: function (x, y, key, mesh, group) { + + if (group === undefined) { group = this.world; } + + var obj = new Phaser.Creature(this.game, x, y, key, mesh); + + group.add(obj); + + return obj; + + }, + + /** + * Create a tween on a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectFactory#tween + * @param {object} object - Object the tween will be run on. + * @return {Phaser.Tween} The newly created Phaser.Tween object. + */ + tween: function (object) { + + return this.game.tweens.create(object); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectFactory#group + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates + * are automatically given a physics body. + * + * @method Phaser.GameObjectFactory#physicsGroup + * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc. + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.Group} The newly created Group. + */ + physicsGroup: function (physicsBodyType, parent, name, addToStage) { + + return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType); + + }, + + /** + * A SpriteBatch is a really fast version of a Phaser Group built solely for speed. + * Use when you need a lot of sprites or particles all sharing the same texture. + * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. + * + * @method Phaser.GameObjectFactory#spriteBatch + * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. + * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. + * @return {Phaser.SpriteBatch} The newly created Sprite Batch. + */ + spriteBatch: function (parent, name, addToStage) { + + if (parent === undefined) { parent = null; } + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectFactory#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectFactory#tileSprite + * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TileSprite} The newly created TileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); + + }, + + /** + * Creates a new Rope object. + * + * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js + * + * @method Phaser.GameObjectFactory#rope + * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Array} points - An array of {Phaser.Point}. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Rope} The newly created Rope object. + */ + rope: function (x, y, key, frame, points, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Rope(this.game, x, y, key, frame, points)); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectFactory#text + * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {string} [text=''] - The text string that will be displayed. + * @param {object} [style] - The style object containing style attributes like font, font size , etc. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Text(this.game, x, y, text, style)); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectFactory#button + * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] - The function to call when this button is pressed + * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Button} The newly created Button object. + */ + button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectFactory#graphics + * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Graphics(this.game, x, y)); + + }, + + /** + * Create a new Emitter. + * + * A particle emitter can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accordingly. + * + * @method Phaser.GameObjectFactory#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles)); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectFactory#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectFactory#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size)); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectFactory#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {Phaser.Tilemap} The newly created tilemap object. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectFactory#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a Video object. + * + * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. + * + * @method Phaser.GameObjectFactory#video + * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. + * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) + * @return {Phaser.Video} The newly created Video object. + */ + video: function (key, url) { + + return new Phaser.Video(this.game, key, url); + + }, + + /** + * Create a BitmapData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectFactory#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectFactory#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + }, + + /** + * Add a new Plugin into the PluginManager. + * + * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.GameObjectFactory#plugin + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + plugin: function (plugin) { + + return this.game.plugins.add(plugin); + + } + +}; + +Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world. +* The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}. +* +* @class Phaser.GameObjectCreator +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectCreator = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectCreator.prototype = { + + /** + * Create a new Image object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectCreator#image + * @param {number} x - X position of the image. + * @param {number} y - Y position of the image. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Image} the newly created sprite object. + */ + image: function (x, y, key, frame) { + + return new Phaser.Image(this.game, x, y, key, frame); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * @method Phaser.GameObjectCreator#sprite + * @param {number} x - X position of the new sprite. + * @param {number} y - Y position of the new sprite. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Sprite} the newly created sprite object. + */ + sprite: function (x, y, key, frame) { + + return new Phaser.Sprite(this.game, x, y, key, frame); + + }, + + /** + * Create a tween object for a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectCreator#tween + * @param {object} obj - Object the tween will be run on. + * @return {Phaser.Tween} The Tween object. + */ + tween: function (obj) { + + return new Phaser.Tween(obj, this.game, this.game.tweens); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectCreator#group + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * Create a new SpriteBatch. + * + * @method Phaser.GameObjectCreator#spriteBatch + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.SpriteBatch} The newly created group. + */ + spriteBatch: function (parent, name, addToStage) { + + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectCreator#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectCreator#tileSprite + * @param {number} x - The x coordinate (in world space) to position the TileSprite at. + * @param {number} y - The y coordinate (in world space) to position the TileSprite at. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.TileSprite} The newly created tileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame) { + + return new Phaser.TileSprite(this.game, x, y, width, height, key, frame); + + }, + + /** + * Creates a new Rope object. + * + * @method Phaser.GameObjectCreator#rope + * @param {number} x - The x coordinate (in world space) to position the Rope at. + * @param {number} y - The y coordinate (in world space) to position the Rope at. + * @param {number} width - The width of the Rope. + * @param {number} height - The height of the Rope. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.Rope} The newly created rope object. + */ + rope: function (x, y, key, frame, points) { + + return new Phaser.Rope(this.game, x, y, key, frame, points); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectCreator#text + * @param {number} x - X position of the new text object. + * @param {number} y - Y position of the new text object. + * @param {string} text - The actual text that will be written. + * @param {object} style - The style object containing style attributes like font, font size , etc. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style) { + + return new Phaser.Text(this.game, x, y, text, style); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectCreator#button + * @param {number} [x] X position of the new button object. + * @param {number} [y] Y position of the new button object. + * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] The function to call when this button is pressed + * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @return {Phaser.Button} The newly created button object. + */ + 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); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectCreator#graphics + * @param {number} [x=0] - X position of the new graphics object. + * @param {number} [y=0] - Y position of the new graphics object. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y) { + + return new Phaser.Graphics(this.game, x, y); + + }, + + /** + * Creat a new Emitter. + * + * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accorindgly. + * + * @method Phaser.GameObjectCreator#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectCreator#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectCreator#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, align) { + + return new Phaser.BitmapText(this.game, x, y, font, text, size, align); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectCreator#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectCreator#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a BitmpaData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectCreator#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectCreator#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + } + +}; + +Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Sprites are the lifeblood of your game, used for nearly everything visual. +* +* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. +* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), +* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. +* +* @class Phaser.Sprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. If this argument is omitted, the sprite will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Sprite = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.SPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Sprite.prototype.constructor = Phaser.Sprite; + +Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.Sprite +* @return {boolean} True if the Sprite was rendered, otherwise false. +*/ +Phaser.Sprite.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image is a light-weight object you can use to display anything that doesn't need health, physics, or complex position monitoring. +* +* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. +* +* @class Phaser.Image +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. If this argument is omitted, the image will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Image = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.IMAGE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Image.prototype.constructor = Phaser.Image; + +Phaser.Component.Core.install.call(Phaser.Image.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Image.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Image#preUpdate +* @memberof Phaser.Image +*/ +Phaser.Image.prototype.preUpdate = function() { + + if (!this.preUpdateInWorld() || !this.preUpdateLifeSpan()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. +* +* The four states a Button responds to are: +* +* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. +* * 'Out' - when the Pointer that was previously over the Button moves out of it. +* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. +* * 'Up' - when the Pointer that was pressed down on the Button is released again. +* +* A different texture/frame and activation sound can be specified for any of the states. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. +* +* @class Phaser.Button +* @constructor +* @extends Phaser.Image +* @param {Phaser.Game} game Current game instance. +* @param {number} [x=0] - X position of the Button. +* @param {number} [y=0] - Y position of the Button. +* @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button. +* @param {function} [callback] - The function to call when this Button is pressed, receiving `this` (the Button), `pointer`, and `isOver` (see {@link Phaser.Events#onInputUp}.) +* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) { + + x = x || 0; + y = y || 0; + key = key || null; + callback = callback || null; + callbackContext = callbackContext || this; + + Phaser.Image.call(this, game, x, y, key, outFrame); + + /** + * The Phaser Object Type. + * @property {number} type + * @readonly + */ + this.type = Phaser.BUTTON; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * The name or ID of the Over state frame. + * @property {string|integer} onOverFrame + * @private + */ + this._onOverFrame = null; + + /** + * The name or ID of the Out state frame. + * @property {string|integer} onOutFrame + * @private + */ + this._onOutFrame = null; + + /** + * The name or ID of the Down state frame. + * @property {string|integer} onDownFrame + * @private + */ + this._onDownFrame = null; + + /** + * The name or ID of the Up state frame. + * @property {string|integer} onUpFrame + * @private + */ + this._onUpFrame = null; + + /** + * The Sound to be played when this Buttons Over state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound + * @readonly + */ + this.onOverSound = null; + + /** + * The Sound to be played when this Buttons Out state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound + * @readonly + */ + this.onOutSound = null; + + /** + * The Sound to be played when this Buttons Down state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound + * @readonly + */ + this.onDownSound = null; + + /** + * The Sound to be played when this Buttons Up state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound + * @readonly + */ + this.onUpSound = null; + + /** + * The Sound Marker used in conjunction with the onOverSound. + * @property {string} onOverSoundMarker + * @readonly + */ + this.onOverSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onOutSound. + * @property {string} onOutSoundMarker + * @readonly + */ + this.onOutSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onDownSound. + * @property {string} onDownSoundMarker + * @readonly + */ + this.onDownSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onUpSound. + * @property {string} onUpSoundMarker + * @readonly + */ + this.onUpSoundMarker = ''; + + /** + * The Signal (or event) dispatched when this Button is in an Over state. + * @property {Phaser.Signal} onInputOver + */ + this.onInputOver = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Out state. + * @property {Phaser.Signal} onInputOut + */ + this.onInputOut = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Down state. + * @property {Phaser.Signal} onInputDown + */ + this.onInputDown = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Up state. + * @property {Phaser.Signal} onInputUp + */ + this.onInputUp = new Phaser.Signal(); + + /** + * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. + * The frame will still be changed as applicable. + * + * @property {boolean} onOverMouseOnly + * @default + */ + this.onOverMouseOnly = true; + + /** + * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}. + * + * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. + * + * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR + */ + this.justReleasedPreventsOver = Phaser.PointerMode.CONTACT; + + /** + * When true the the texture frame will not be automatically switched on up/down/over/out events. + * @property {boolean} freezeFrames + * @default + */ + this.freezeFrames = false; + + /** + * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". + * + * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control. + * + * @property {boolean|Phaser.PointerMode} forceOut=false + * @default + */ + this.forceOut = false; + + this.inputEnabled = true; + + this.input.start(0, true); + + this.input.useHandCursor = true; + + this.setFrames(overFrame, outFrame, downFrame, upFrame); + + if (callback !== null) + { + this.onInputUp.add(callback, callbackContext); + } + + // Redirect the input events to here so we can handle animation updates, etc + this.events.onInputOver.add(this.onInputOverHandler, this); + this.events.onInputOut.add(this.onInputOutHandler, this); + this.events.onInputDown.add(this.onInputDownHandler, this); + this.events.onInputUp.add(this.onInputUpHandler, this); + +}; + +Phaser.Button.prototype = Object.create(Phaser.Image.prototype); +Phaser.Button.prototype.constructor = Phaser.Button; + +// State constants; local only. These are tied to property names in Phaser.Button. +var STATE_OVER = 'Over'; +var STATE_OUT = 'Out'; +var STATE_DOWN = 'Down'; +var STATE_UP = 'Up'; + +/** +* Clears all of the frames set on this Button. +* +* @method Phaser.Button#clearFrames +*/ +Phaser.Button.prototype.clearFrames = function () { + + this.setFrames(null, null, null, null); + +}; + +/** +* Set the frame name/ID for the given state. +* +* @method Phaser.Button#setStateFrame +* @private +* @param {object} state - See `STATE_*` +* @param {number|string} frame - The number or string representing the frame. +* @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true. +*/ +Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately) +{ + var frameKey = '_on' + state + 'Frame'; + + if (frame !== null) // not null or undefined + { + this[frameKey] = frame; + + if (switchImmediately) + { + this.changeStateFrame(state); + } + } + else + { + this[frameKey] = null; + } + +}; + +/** +* Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen". +* +* @method Phaser.Button#changeStateFrame +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if the frame was assigned a value, possibly the same one it already had. +*/ +Phaser.Button.prototype.changeStateFrame = function (state) { + + if (this.freezeFrames) + { + return false; + } + + var frameKey = '_on' + state + 'Frame'; + var frame = this[frameKey]; + + if (typeof frame === 'string') + { + this.frameName = frame; + return true; + } + else if (typeof frame === 'number') + { + this.frame = frame; + return true; + } + else + { + return false; + } + +}; + +/** +* Used to manually set the frames that will be used for the different states of the Button. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. +* +* @method Phaser.Button#setFrames +* @public +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) { + + this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver()); + this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver()); + this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown()); + this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp()); + +}; + +/** +* Set the sound/marker for the given state. +* +* @method Phaser.Button#setStateSound +* @private +* @param {object} state - See `STATE_*` +* @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound. +* @param {string} [marker=''] - Sound marker. +*/ +Phaser.Button.prototype.setStateSound = function (state, sound, marker) { + + var soundKey = 'on' + state + 'Sound'; + var markerKey = 'on' + state + 'SoundMarker'; + + if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite) + { + this[soundKey] = sound; + this[markerKey] = typeof marker === 'string' ? marker : ''; + } + else + { + this[soundKey] = null; + this[markerKey] = ''; + } + +}; + +/** +* Play the sound for the given state, _if_ the state has a sound assigned. +* +* @method Phaser.Button#playStateSound +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if a sound was played. +*/ +Phaser.Button.prototype.playStateSound = function (state) { + + var soundKey = 'on' + state + 'Sound'; + var sound = this[soundKey]; + + if (sound) + { + var markerKey = 'on' + state + 'SoundMarker'; + var marker = this[markerKey]; + + sound.play(marker); + return true; + } + else + { + return false; + } + +}; + +/** +* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. +* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. +* +* Call this function with no parameters to reset all sounds on this Button. +* +* @method Phaser.Button#setSounds +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound. +* @param {string} [overMarker] - Over Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound. +* @param {string} [downMarker] - Down Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound. +* @param {string} [outMarker] - Out Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound. +* @param {string} [upMarker] - Up Button Sound Marker. +*/ +Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) { + + this.setStateSound(STATE_OVER, overSound, overMarker); + this.setStateSound(STATE_OUT, outSound, outMarker); + this.setStateSound(STATE_DOWN, downSound, downMarker); + this.setStateSound(STATE_UP, upSound, upMarker); + +}; + +/** +* The Sound to be played when a Pointer moves over this Button. +* +* @method Phaser.Button#setOverSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOverSound = function (sound, marker) { + + this.setStateSound(STATE_OVER, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer moves out of this Button. +* +* @method Phaser.Button#setOutSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOutSound = function (sound, marker) { + + this.setStateSound(STATE_OUT, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer presses down on this Button. +* +* @method Phaser.Button#setDownSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setDownSound = function (sound, marker) { + + this.setStateSound(STATE_DOWN, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer has pressed down and is released from this Button. +* +* @method Phaser.Button#setUpSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setUpSound = function (sound, marker) { + + this.setStateSound(STATE_UP, sound, marker); + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOverHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) { + + if (pointer.justReleased() && + (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode) + { + // If the Pointer was only just released then we don't fire an over event + return; + } + + this.changeStateFrame(STATE_OVER); + + if (this.onOverMouseOnly && !pointer.isMouse) + { + return; + } + + this.playStateSound(STATE_OVER); + + if (this.onInputOver) + { + this.onInputOver.dispatch(this, pointer); + } + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOutHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_OUT); + + this.playStateSound(STATE_OUT); + + if (this.onInputOut) + { + this.onInputOut.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputDownHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_DOWN); + + this.playStateSound(STATE_DOWN); + + if (this.onInputDown) + { + this.onInputDown.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputUpHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) { + + this.playStateSound(STATE_UP); + + // Input dispatched early, before state change (but after sound) + if (this.onInputUp) + { + this.onInputUp.dispatch(this, pointer, isOver); + } + + if (this.freezeFrames) + { + return; + } + + if (this.forceOut === true || (this.forceOut & pointer.pointerMode) === pointer.pointerMode) + { + this.changeStateFrame(STATE_OUT); + } + else + { + var changedUp = this.changeStateFrame(STATE_UP); + if (!changedUp) + { + // No Up frame to show.. + if (isOver) + { + this.changeStateFrame(STATE_OVER); + } + else + { + this.changeStateFrame(STATE_OUT); + } + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. +* It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over +* 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled +* Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. +* +* Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. +* +* @class Phaser.SpriteBatch +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. +* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. +*/ +Phaser.SpriteBatch = function (game, parent, name, addToStage) { + + if (parent === undefined || parent === null) { parent = game.world; } + + Phaser.Group.call(this, game, parent, name, addToStage); + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.SPRITEBATCH; + + /** + * @property {Object} fastSpriteBatch - WebGL Batch Shader. + * @private + */ + this.fastSpriteBatch = null; + + /** + * @property {boolean} ready - Internal flag. + * @private + */ + this.ready = false; + +}; + +Phaser.SpriteBatch.prototype = Object.create(Phaser.Group.prototype); + +Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch; + +/** +* Renders the Sprite Batch using the WebGL renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + if (!this.ready) + { + this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(renderSession.gl); + + this.ready = true; + } + + if (this.fastSpriteBatch.gl !== renderSession.gl) + { + this.fastSpriteBatch.setContext(renderSession.gl); + } + + renderSession.spriteBatch.stop(); + + renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader); + + this.fastSpriteBatch.begin(this, renderSession); + this.fastSpriteBatch.render(this); + + renderSession.spriteBatch.start(); + +}; + +/** +* Renders the Sprite Batch using the Canvas renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + var context = renderSession.context; + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + var transform = this.worldTransform; + + var isRotated = true; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + var texture = child.texture; + var frame = texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) + { + // If rotation === 0 we can avoid setTransform + + if (isRotated) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); + isRotated = false; + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5 + renderSession.shakeX) | 0, + ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5 + renderSession.shakeY) | 0, + frame.width * child.scale.x, + frame.height * child.scale.y); + } + else + { + if (!isRotated) + { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + var tx = (childTransform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (childTransform.ty * renderSession.resolution) + renderSession.shakeY; + + // allow for trimming + + if (renderSession.roundPixels) + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx, ty); + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width) + 0.5) | 0, + ((child.anchor.y) * (-frame.height) + 0.5) | 0, + frame.width, + frame.height); + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. +* A single BitmapData can be used as the texture for one or many Images / Sprites. +* So if you need to dynamically create a Sprite texture then they are a good choice. +* +* Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't +* live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy +* in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. +* +* @class Phaser.BitmapData +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string} key - Internal Phaser reference key for the BitmapData. +* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. +*/ +Phaser.BitmapData = function (game, key, width, height, skipPool) { + + if (width === undefined || width === 0) { width = 256; } + if (height === undefined || height === 0) { height = 256; } + if (skipPool === undefined) { skipPool = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the BitmapData in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} width - The width of the BitmapData in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the BitmapData in pixels. + */ + this.height = height; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. + * @default + */ + this.canvas = Phaser.Canvas.create(this, width, height, null, skipPool); + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + * @default + */ + this.context = this.canvas.getContext('2d', { alpha: true }); + + /** + * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context. + */ + this.ctx = this.context; + + /** + * @property {string} smoothProperty - The context property needed for smoothing this Canvas. + */ + this.smoothProperty = (game.renderType === Phaser.CANVAS) ? game.renderer.renderSession.smoothProperty : Phaser.Canvas.getSmoothingPrefix(this.context); + + /** + * @property {ImageData} imageData - The context image data. + * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. + * This property is updated automatically after the first game loop, according to the dirty flag property. + */ + this.imageData = this.context.getImageData(0, 0, width, height); + + /** + * A Uint8ClampedArray view into BitmapData.buffer. + * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) + * @property {Uint8ClampedArray} data + */ + this.data = null; + + if (this.imageData) + { + this.data = this.imageData.data; + } + + /** + * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer. + */ + this.pixels = null; + + /** + * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData. + */ + if (this.data) + { + 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; + } + } + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + this.baseTexture = new PIXI.BaseTexture(this.canvas, null, this.game.resolution); + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering. + */ + this.frameData = new Phaser.FrameData(); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. + * @default + */ + this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData')); + + this.texture.frame = this.textureFrame; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.BITMAPDATA; + + /** + * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} dirty - If dirty this BitmapData will be re-rendered. + */ + this.dirty = false; + + // Aliases + this.cls = this.clear; + + /** + * @property {number} _image - Internal cache var. + * @private + */ + this._image = null; + + /** + * @property {Phaser.Point} _pos - Internal cache var. + * @private + */ + this._pos = new Phaser.Point(); + + /** + * @property {Phaser.Point} _size - Internal cache var. + * @private + */ + this._size = new Phaser.Point(); + + /** + * @property {Phaser.Point} _scale - Internal cache var. + * @private + */ + this._scale = new Phaser.Point(); + + /** + * @property {number} _rotate - Internal cache var. + * @private + */ + this._rotate = 0; + + /** + * @property {object} _alpha - Internal cache var. + * @private + */ + this._alpha = { prev: 1, current: 1 }; + + /** + * @property {Phaser.Point} _anchor - Internal cache var. + * @private + */ + this._anchor = new Phaser.Point(); + + /** + * @property {number} _tempR - Internal cache var. + * @private + */ + this._tempR = 0; + + /** + * @property {number} _tempG - Internal cache var. + * @private + */ + this._tempG = 0; + + /** + * @property {number} _tempB - Internal cache var. + * @private + */ + this._tempB = 0; + + /** + * @property {Phaser.Circle} _circle - Internal cache var. + * @private + */ + this._circle = new Phaser.Circle(); + + /** + * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods. + * @private + */ + this._swapCanvas = undefined; + +}; + +Phaser.BitmapData.prototype = { + + /** + * Shifts the contents of this BitmapData by the distances given. + * + * The image will wrap-around the edges on all sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#move + * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + move: function (x, y, wrap) { + + if (x !== 0) + { + this.moveH(x, wrap); + } + + if (y !== 0) + { + this.moveV(y, wrap); + } + + return this; + + }, + + /** + * Shifts the contents of this BitmapData horizontally. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveH + * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveH: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var h = this.height; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving to the left + var w = this.width - distance; + + // Left-hand chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h); + } + else + { + // Moving to the right + var w = this.width - distance; + + // Right-hand chunk + if (wrap) + { + ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Shifts the contents of this BitmapData vertically. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveV + * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveV: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var w = this.width; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving up + var h = this.height - distance; + + // Top chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h); + } + else + { + // Moving down + var h = this.height - distance; + + // Bottom chunk + if (wrap) + { + ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Updates the given objects so that they use this BitmapData as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.BitmapData#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. + * The source game object is not modified by this operation. + * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. + * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. + * + * @method Phaser.BitmapData#load + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + load: function (source) { + + if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + } + + if (source) + { + this.resize(source.width, source.height); + this.cls(); + } + else + { + return; + } + + this.draw(source); + + this.update(); + + return this; + + }, + + /** + * Clears the BitmapData context using a clearRect. + * + * @method Phaser.BitmapData#cls + */ + + /** + * Clears the BitmapData context using a clearRect. + * + * You can optionally define the area to clear. + * If the arguments are left empty it will clear the entire canvas. + * + * You may need to call BitmapData.update after this in order to clear out the pixel data, + * but Phaser will not do this automatically for you. + * + * @method Phaser.BitmapData#clear + * @param {number} [x=0] - The x coordinate of the top-left of the area to clear. + * @param {number} [y=0] - The y coordinate of the top-left of the area to clear. + * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width. + * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + clear: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + this.context.clearRect(x, y, width, height); + + this.dirty = true; + + return this; + + }, + + /** + * Fills the BitmapData with the given color. + * + * @method Phaser.BitmapData#fill + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} [a=1] - The alpha color value, between 0 and 1. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + fill: function (r, g, b, a) { + + if (a === undefined) { a = 1; } + + this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; + this.context.fillRect(0, 0, this.width, this.height); + this.dirty = true; + + return this; + + }, + + /** + * Creates a new {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image} element by converting this BitmapDatas canvas into a dataURL. + * + * The image is then stored in the {@link Phaser.Cache image Cache} using the key given. + * + * Finally a {@link PIXI.Texture} is created based on the image and returned. + * + * You can apply the texture to a sprite or any other supporting object by using either the + * key or the texture. First call `generateTexture`: + * + * ```javascript + * var texture = bitmapdata.generateTexture('ball'); + * ``` + * + * Then you can either apply the texture to a sprite: + * + * ```javascript + * game.add.sprite(0, 0, texture); + * ``` + * + * or by using the string based key: + * + * ```javascript + * game.add.sprite(0, 0, 'ball'); + * ``` + * + * Most browsers now load the image data asynchronously, so you should use a callback: + * + * ```javascript + * bitmapdata.generateTexture('ball', function (texture) { + * game.add.sprite(0, 0, texture); + * // or + * game.add.sprite(0, 0, 'ball'); + * }); + * ``` + * + * If this BitmapData is available during preload, you can use {@link Phaser.Loader#imageFromBitmapData} instead. + * + * @method Phaser.BitmapData#generateTexture + * @param {string} key - The key which will be used to store the image in the Cache. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {PIXI.Texture|null} The newly generated texture, or `null` if a callback was passed and the texture isn't available yet. + */ + generateTexture: function (key, callback, callbackContext) { + + var cache = this.game.cache; + var image = new Image(); + + if (callback) + { + image.onload = function () { + var obj = cache.addImage(key, '', image); + var texture = new PIXI.Texture(obj.base); + + callback.call(callbackContext || null, texture); + + image.onload = null; + }; + } + + image.src = this.canvas.toDataURL("image/png"); + + if (!callback) + { + var obj = cache.addImage(key, '', image); + + return new PIXI.Texture(obj.base); + } + + return null; + + }, + + /** + * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. + * + * @method Phaser.BitmapData#resize + * @param {integer} width - The new width of the BitmapData. + * @param {integer} height - The new height of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + resize: function (width, height) { + + if (width !== this.width || height !== this.height) + { + this.width = width; + this.height = height; + + this.canvas.width = width; + this.canvas.height = height; + + if (this._swapCanvas !== undefined) + { + this._swapCanvas.width = width; + this._swapCanvas.height = height; + } + + this.baseTexture.width = width; + this.baseTexture.height = height; + + this.textureFrame.width = width; + this.textureFrame.height = height; + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.update(); + this.dirty = true; + } + + return this; + + }, + + /** + * This re-creates the BitmapData.imageData from the current context. + * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. + * If not given the dimensions defaults to the full size of the context. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.BitmapData#update + * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from. + * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from. + * @param {number} [width=1] - The width of the image data area. + * @param {number} [height=1] - The height of the image data area. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + update: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = Math.max(1, this.width); } + if (height === undefined) { height = Math.max(1, this.height); } + + this.imageData = this.context.getImageData(x, y, width, height); + this.data = this.imageData.data; + + 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; + } + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. + * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. + * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. + * The `color` property is an Int32 of the full color. Note the endianess of this will change per system. + * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. + * The callback will also be sent the pixels x and y coordinates respectively. + * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. + * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. + * + * @method Phaser.BitmapData#processPixelRGB + * @param {function} callback - The callback that will be sent each pixel color object to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixelRGB: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = Phaser.Color.createColor(); + var result = { r: 0, g: 0, b: 0, a: 0 }; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel); + + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== false && result !== null && result !== undefined) + { + this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false); + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. + * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. + * Note that the format of the color received will be different depending on if the system is big or little endian. + * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. + * The callback will also be sent the pixels x and y coordinates respectively. + * + * @method Phaser.BitmapData#processPixel + * @param {function} callback - The callback that will be sent each pixel color to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixel: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = 0; + var result = 0; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + pixel = this.getPixel32(tx, ty); + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== pixel) + { + this.pixels[ty * this.width + tx] = result; + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. + * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. + * + * @method Phaser.BitmapData#replaceRGB + * @param {number} r1 - The red color value to be replaced. Between 0 and 255. + * @param {number} g1 - The green color value to be replaced. Between 0 and 255. + * @param {number} b1 - The blue color value to be replaced. Between 0 and 255. + * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255. + * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255. + * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255. + * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255. + * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255. + * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) { + + var sx = 0; + var sy = 0; + var w = this.width; + var h = this.height; + var source = Phaser.Color.packPixel(r1, g1, b1, a1); + + if (region !== undefined && region instanceof Phaser.Rectangle) + { + sx = region.x; + sy = region.y; + w = region.width; + h = region.height; + } + + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + if (this.getPixel32(sx + x, sy + y) === source) + { + this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false); + } + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * + * @method Phaser.BitmapData#setHSL + * @param {number} [h=null] - The hue, in the range 0 - 1. + * @param {number} [s=null] - The saturation, in the range 0 - 1. + * @param {number} [l=null] - The lightness, in the range 0 - 1. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setHSL: function (h, s, l, region) { + + var bHaveH = h || h === 0; + var bHaveS = s || s === 0; + var bHaveL = l || l === 0; + + if (!bHaveH && !bHaveS && !bHaveL) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (bHaveH) + { + pixel.h = h; + } + + if (bHaveS) + { + pixel.s = s; + } + + if (bHaveL) + { + pixel.l = l; + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * Shifting will add the given value onto the current h, s and l values, not replace them. + * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. + * + * @method Phaser.BitmapData#shiftHSL + * @param {number} [h=null] - The amount to shift the hue by. Within [-1, 1]. + * @param {number} [s=null] - The amount to shift the saturation by. Within [-1, 1]. + * @param {number} [l=null] - The amount to shift the lightness by. Within [-1, 1]. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shiftHSL: function (h, s, l, region) { + + if (h === undefined || h === null) { h = false; } + if (s === undefined || s === null) { s = false; } + if (l === undefined || l === null) { l = false; } + + if (!h && !s && !l) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (h) + { + pixel.h = this.game.math.wrap(pixel.h + h, 0, 1); + } + + if (s) + { + pixel.s = this.game.math.clamp(pixel.s + s, 0, 1); + } + + if (l) + { + pixel.l = this.game.math.clamp(pixel.l + l, 0, 1); + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green, blue and alpha values. + * + * @method Phaser.BitmapData#setPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel32: function (x, y, red, green, blue, alpha, immediate) { + + if (immediate === undefined) { immediate = true; } + + if (x >= 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; + } + } + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green and blue values. + * + * @method Phaser.BitmapData#setPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel: function (x, y, red, green, blue, immediate) { + + return this.setPixel32(x, y, red, green, blue, 255, immediate); + + }, + + /** + * Get the color of a specific pixel in the context into a color object. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + getPixel: function (x, y, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var index = ~~(x + (y * this.width)); + + index *= 4; + + out.r = this.data[index]; + out.g = this.data[++index]; + out.b = this.data[++index]; + out.a = this.data[++index]; + + return out; + + }, + + /** + * Get the color of a specific pixel including its alpha value. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. + * + * @method Phaser.BitmapData#getPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @return {number} A native color value integer (format: 0xAARRGGBB) + */ + getPixel32: function (x, y) { + + if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) + { + return this.pixels[y * this.width + x]; + } + + }, + + /** + * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixelRGB + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + getPixelRGB: function (x, y, out, hsl, hsv) { + + return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv); + + }, + + /** + * Gets all the pixels from the region specified by the given Rectangle object. + * + * @method Phaser.BitmapData#getPixels + * @param {Phaser.Rectangle} rect - The Rectangle region to get. + * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property. + */ + getPixels: function (rect) { + + return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); + + }, + + /** + * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). + * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. + * + * The direction parameter controls from which direction it should start the scan: + * + * 0 = top to bottom + * 1 = bottom to top + * 2 = left to right + * 3 = right to left + * + * @method Phaser.BitmapData#getFirstPixel + * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. + * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. + */ + getFirstPixel: function (direction) { + + if (direction === undefined) { direction = 0; } + + var pixel = Phaser.Color.createColor(); + + var x = 0; + var y = 0; + var v = 1; + var scan = false; + + if (direction === 1) + { + v = -1; + y = this.height; + } + else if (direction === 3) + { + v = -1; + x = this.width; + } + + do { + + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel); + + if (direction === 0 || direction === 1) + { + // Top to Bottom / Bottom to Top + x++; + + if (x === this.width) + { + x = 0; + y += v; + + if (y >= this.height || y <= 0) + { + scan = true; + } + } + } + else if (direction === 2 || direction === 3) + { + // Left to Right / Right to Left + y++; + + if (y === this.height) + { + y = 0; + x += v; + + if (x >= this.width || x <= 0) + { + scan = true; + } + } + } + } + while (pixel.a === 0 && !scan); + + pixel.x = x; + pixel.y = y; + + return pixel; + + }, + + /** + * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. + * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. + * + * @method Phaser.BitmapData#getBounds + * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. + * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. + */ + getBounds: function (rect) { + + if (rect === undefined) { rect = new Phaser.Rectangle(); } + + rect.x = this.getFirstPixel(2).x; + + // If we hit this, there's no point scanning any more, the image is empty + if (rect.x === this.width) + { + return rect.setTo(0, 0, 0, 0); + } + + rect.y = this.getFirstPixel(0).y; + rect.width = (this.getFirstPixel(3).x - rect.x) + 1; + rect.height = (this.getFirstPixel(1).y - rect.y) + 1; + + return rect; + + }, + + /** + * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. + * + * @method Phaser.BitmapData#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself. + * + * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn. + * + * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters. + * + * Note that the source image can also be this BitmapData, which can create some interesting effects. + * + * This method has a lot of parameters for maximum control. + * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all. + * + * You may prefer to use `copyTransform` if you're simply trying to draw a Sprite to this BitmapData, + * and don't wish to translate, scale or rotate it from its original values. + * + * @method Phaser.BitmapData#copy + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image. + * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image. + * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width. + * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height. + * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`. + * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`. + * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter. + * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter. + * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters. + * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) { + + if (source === undefined || source === null) { source = this; } + + if (source instanceof Phaser.RenderTexture) + { + source = source.getCanvas(); + } + + this._image = source; + + if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text || source instanceof PIXI.Sprite) + { + // Copy over sprite values + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + this._scale.set(source.scale.x, source.scale.y); + this._anchor.set(source.anchor.x, source.anchor.y); + this._rotate = source.rotation; + this._alpha.current = source.alpha; + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + if (tx === undefined || tx === null) { tx = source.x; } + if (ty === undefined || ty === null) { ty = source.y; } + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + } + else + { + // Reset + this._pos.set(0); + this._scale.set(1); + this._anchor.set(0); + this._rotate = 0; + this._alpha.current = 1; + + if (source instanceof Phaser.BitmapData) + { + this._image = source.canvas; + } + else if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + + if (source === null) + { + return; + } + else + { + this._image = source; + } + } + + this._size.set(this._image.width, this._image.height); + } + + // The source region to copy from + if (x === undefined || x === null) { x = 0; } + if (y === undefined || y === null) { y = 0; } + + // If they set a width/height then we override the frame values with them + if (width) + { + this._size.x = width; + } + + if (height) + { + this._size.y = height; + } + + // The destination region to copy to + if (tx === undefined || tx === null) { tx = x; } + if (ty === undefined || ty === null) { ty = y; } + if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; } + if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; } + + // Rotation - if set this will override any potential Sprite value + if (typeof rotate === 'number') + { + this._rotate = rotate; + } + + // Anchor - if set this will override any potential Sprite value + if (typeof anchorX === 'number') + { + this._anchor.x = anchorX; + } + + if (typeof anchorY === 'number') + { + this._anchor.y = anchorY; + } + + // Scaling - if set this will override any potential Sprite value + if (typeof scaleX === 'number') + { + this._scale.x = scaleX; + } + + if (typeof scaleY === 'number') + { + this._scale.y = scaleY; + } + + // Effects + if (typeof alpha === 'number') + { + this._alpha.current = alpha; + } + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + // Doesn't work fully with children, or nested scale + rotation transforms (see copyTransform) + ctx.translate(tx, ty); + + ctx.scale(this._scale.x, this._scale.y); + + ctx.rotate(this._rotate); + + ctx.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight); + + // Carry on ... + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the + * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. + * It takes the objects tint and scale mode into consideration before drawing. + * + * You can optionally specify Blend Mode and Round Pixels arguments. + * + * @method Phaser.BitmapData#copyTransform + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyTransform: function (source, blendMode, roundPx) { + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (!source.hasOwnProperty('worldTransform') || !source.worldVisible || source.worldAlpha === 0) + { + return this; + } + + var wt = source.worldTransform; + + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + + if (wt.a === 0 || wt.d === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return this; + } + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + var tx = wt.tx; + var ty = wt.ty; + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + ctx[this.smoothProperty] = (source.texture.baseTexture.scaleMode === PIXI.scaleModes.LINEAR); + + ctx.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + + ctx.drawImage(this._image, + this._pos.x, + this._pos.y, + this._size.x, + this._size.y, + -this._size.x * source.anchor.x, + -this._size.y * source.anchor.y, + this._size.x, + this._size.y); + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. + * + * @method Phaser.BitmapData#copyRect + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. + * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image. + * @param {number} x - The destination x coordinate to copy the image to. + * @param {number} y - The destination y coordinate to copy the image to. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyRect: function (source, area, x, y, alpha, blendMode, roundPx) { + + return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx); + + }, + + /** + * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. + * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. + * + * @method Phaser.BitmapData#draw + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData. + * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`. + * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`. + * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`. + * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + draw: function (source, x, y, width, height, blendMode, roundPx) { + + // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here + return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx); + + }, + + /** + * Draws the immediate children of a Phaser.Group to this BitmapData. + * + * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. + * + * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. + * + * @method Phaser.BitmapData#drawGroup + * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawGroup: function (group, blendMode, roundPx) { + + if (group.total > 0) + { + group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx); + } + + return this; + + }, + + /** + * A proxy for drawGroup that handles child iteration for more complex Game Objects. + * + * @method Phaser.BitmapData#drawGroupProxy + * @private + * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + */ + drawGroupProxy: function (child, blendMode, roundPx) { + + if (child.hasOwnProperty('texture')) + { + this.copyTransform(child, blendMode, roundPx); + } + + if (child.type === Phaser.GROUP && child.exists) + { + this.drawGroup(child, blendMode, roundPx); + } + else + { + if (child.hasOwnProperty('children') && child.children.length > 0) + { + for (var i = 0; i < child.children.length; i++) + { + if (child.children[i].exists) + { + this.copyTransform(child.children[i], blendMode, roundPx); + } + } + } + } + + }, + + /** + * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. + * + * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData + * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the + * bounds of the top-level Game Object. + * + * When drawing it will take into account the child's world rotation, scale and alpha values. + * + * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. + * + * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update + * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can + * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. + * + * @method Phaser.BitmapData#drawFull + * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawFull: function (parent, blendMode, roundPx) { + + if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false)) + { + return this; + } + + if (parent.type !== Phaser.GROUP && parent.type !== Phaser.EMITTER && parent.type !== Phaser.BITMAPTEXT) + { + if (parent.type === Phaser.GRAPHICS) + { + var bounds = parent.getBounds(); + this.ctx.save(); + this.ctx.translate(bounds.x, bounds.y); + PIXI.CanvasGraphics.renderGraphics(parent, this.ctx); + this.ctx.restore(); + } + else + { + this.copy(parent, null, null, null, null, parent.worldPosition.x, parent.worldPosition.y, null, null, parent.worldRotation, null, null, parent.worldScale.x, parent.worldScale.y, parent.worldAlpha, blendMode, roundPx); + } + } + + if (parent.children) + { + for (var i = 0; i < parent.children.length; i++) + { + this.drawFull(parent.children[i], blendMode, roundPx); + } + } + + return this; + + }, + + /** + * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. + * You can cancel an existing shadow by calling this method and passing no parameters. + * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. + * + * @method Phaser.BitmapData#shadow + * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. + * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. + * @param {number} [x=10] - The horizontal offset of the shadow in pixels. + * @param {number} [y=10] - The vertical offset of the shadow in pixels. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shadow: function (color, blur, x, y) { + + var ctx = this.context; + + if (color === undefined || color === null) + { + ctx.shadowColor = 'rgba(0,0,0,0)'; + } + else + { + ctx.shadowColor = color; + ctx.shadowBlur = blur || 5; + ctx.shadowOffsetX = x || 10; + ctx.shadowOffsetY = y || 10; + } + + return this; + + }, + + /** + * Draws the image onto this BitmapData using an image as an alpha mask. + * + * @method Phaser.BitmapData#alphaMask + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. + * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. + * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + alphaMask: function (source, mask, sourceRect, maskRect) { + + if (maskRect === undefined || maskRect === null) + { + this.draw(mask).blendSourceAtop(); + } + else + { + this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop(); + } + + if (sourceRect === undefined || sourceRect === null) + { + this.draw(source).blendReset(); + } + else + { + this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset(); + } + + return this; + + }, + + /** + * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. + * The original BitmapData remains unchanged. + * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. + * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: + * `picture.extract(mask, r, g, b)` + * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. + * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint + * the color during extraction. + * + * @method Phaser.BitmapData#extract + * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. + * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied? + * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255. + * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255. + * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255. + * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on. + */ + extract: function (destination, r, g, b, a, resize, r2, g2, b2) { + + if (a === undefined) { a = 255; } + if (resize === undefined) { resize = false; } + if (r2 === undefined) { r2 = r; } + if (g2 === undefined) { g2 = g; } + if (b2 === undefined) { b2 = b; } + + if (resize) + { + destination.resize(this.width, this.height); + } + + this.processPixelRGB( + function (pixel, x, y) + { + if (pixel.r === r && pixel.g === g && pixel.b === b) + { + destination.setPixel32(x, y, r2, g2, b2, a, false); + } + return false; + }, + this); + + destination.context.putImageData(destination.imageData, 0, 0); + destination.dirty = true; + + return destination; + + }, + + /** + * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. + * + * @method Phaser.BitmapData#rect + * @param {number} x - The x coordinate of the top-left of the Rectangle. + * @param {number} y - The y coordinate of the top-left of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + rect: function (x, y, width, height, fillStyle) { + + if (typeof fillStyle !== 'undefined') + { + this.context.fillStyle = fillStyle; + } + + this.context.fillRect(x, y, width, height); + + return this; + + }, + + /** + * Draws text to the BitmapData in the given font and color. + * The default font is 14px Courier, so useful for quickly drawing debug text. + * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. + * + * @method Phaser.BitmapData#text + * @param {string} text - The text to write to the BitmapData. + * @param {number} x - The x coordinate of the top-left of the text string. + * @param {number} y - The y coordinate of the top-left of the text string. + * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can. + * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in. + * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1) + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + text: function (text, x, y, font, color, shadow) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (font === undefined) { font = '14px Courier'; } + if (color === undefined) { color = 'rgb(255,255,255)'; } + if (shadow === undefined) { shadow = true; } + + var ctx = this.context; + var prevFont = ctx.font; + + ctx.font = font; + + if (shadow) + { + ctx.fillStyle = 'rgb(0,0,0)'; + ctx.fillText(text, x + 1, y + 1); + } + + ctx.fillStyle = color; + ctx.fillText(text, x, y); + + ctx.font = prevFont; + + return this; + + }, + + /** + * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. + * + * @method Phaser.BitmapData#circle + * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle. + * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle. + * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + circle: function (x, y, radius, fillStyle) { + + var ctx = this.context; + + if (fillStyle !== undefined) + { + ctx.fillStyle = fillStyle; + } + + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2, false); + ctx.closePath(); + + ctx.fill(); + + return this; + + }, + + /** + * Draws a line between the coordinates given in the color and thickness specified. + * + * @method Phaser.BitmapData#line + * @param {number} x1 - The x coordinate to start the line from. + * @param {number} y1 - The y coordinate to start the line from. + * @param {number} x2 - The x coordinate to draw the line to. + * @param {number} y2 - The y coordinate to draw the line to. + * @param {string} [color='#fff'] - The stroke color that the line will be drawn in. + * @param {number} [width=1] - The line thickness. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + line: function (x1, y1, x2, y2, color, width) { + + if (color === undefined) { color = '#fff'; } + if (width === undefined) { width = 1; } + + var ctx = this.context; + + ctx.beginPath(); + + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); + + ctx.closePath(); + + return this; + + }, + + /** + * Draws a polygon. + * + * @method Phaser.BitmapData#polygon + * @param {object[]} points - An array of {@link Phaser.Point} or point-like objects. + * @param {CanvasGradient|CanvasPattern|string} [fillStyle] - A color, gradient, or pattern. + * @param {number} [lineWidth=0] - The line thickness. + * @param {CanvasGradient|CanvasPattern|string} [strokeStyle='#fff'] - The line color, gradient, or pattern (when `lineWidth` > 0). + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + polygon: function (points, fillStyle, lineWidth, strokeStyle) { + + // Could reject points.length < 3 + + if (strokeStyle === undefined) { strokeStyle = '#fff'; } + if (lineWidth === undefined) { lineWidth = 0; } + + var ctx = this.context; + + if (fillStyle) + { + ctx.fillStyle = fillStyle; + } + + if (lineWidth) + { + ctx.lineWidth = lineWidth; + ctx.strokeStyle = strokeStyle; + } + + ctx.beginPath(); + + ctx.moveTo(points[0].x, points[0].y); + + for (var i = 1, len = points.length; i < len; i++) + { + var point = points[i]; + ctx.lineTo(point.x, point.y); + } + + ctx.closePath(); + + if (fillStyle) { ctx.fill(); } + if (lineWidth) { ctx.stroke(); } + + return this; + + }, + + /** + * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. + * + * @method Phaser.BitmapData#textureLine + * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line. + * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. + * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + textureLine: function (line, image, repeat) { + + if (repeat === undefined) { repeat = 'repeat-x'; } + + if (typeof image === 'string') + { + image = this.game.cache.getImage(image); + + if (!image) + { + return; + } + } + + var width = line.length; + + if (repeat === 'no-repeat' && width > image.width) + { + width = image.width; + } + + var ctx = this.context; + + ctx.fillStyle = ctx.createPattern(image, repeat); + + this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height); + + this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos); + + ctx.save(); + ctx.translate(this._pos.x, this._pos.y); + ctx.rotate(line.angle); + ctx.fillRect(0, 0, width, image.height); + ctx.restore(); + + this.dirty = true; + + return this; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. + * + * @method Phaser.BitmapData#render + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + render: function () { + + if (!this.disableTextureUpload && this.dirty) + { + this.baseTexture.dirty(); + this.dirty = false; + } + + return this; + + }, + + /** + * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. + * + * @method Phaser.BitmapData#destroy + */ + destroy: function () { + + this.frameData.destroy(); + + this.texture.destroy(true); + + Phaser.CanvasPool.remove(this); + + }, + + /** + * Resets the blend mode (effectively sets it to 'source-over') + * + * @method Phaser.BitmapData#blendReset + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendReset: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-over' + * + * @method Phaser.BitmapData#blendSourceOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOver: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-in' + * + * @method Phaser.BitmapData#blendSourceIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceIn: function () { + + this.op = 'source-in'; + return this; + + }, + + /** + * Sets the blend mode to 'source-out' + * + * @method Phaser.BitmapData#blendSourceOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOut: function () { + + this.op = 'source-out'; + return this; + + }, + + /** + * Sets the blend mode to 'source-atop' + * + * @method Phaser.BitmapData#blendSourceAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceAtop: function () { + + this.op = 'source-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-over' + * + * @method Phaser.BitmapData#blendDestinationOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOver: function () { + + this.op = 'destination-over'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-in' + * + * @method Phaser.BitmapData#blendDestinationIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationIn: function () { + + this.op = 'destination-in'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-out' + * + * @method Phaser.BitmapData#blendDestinationOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOut: function () { + + this.op = 'destination-out'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-atop' + * + * @method Phaser.BitmapData#blendDestinationAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationAtop: function () { + + this.op = 'destination-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'xor' + * + * @method Phaser.BitmapData#blendXor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendXor: function () { + + this.op = 'xor'; + return this; + + }, + + /** + * Sets the blend mode to 'lighter' + * + * @method Phaser.BitmapData#blendAdd + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendAdd: function () { + + this.op = 'lighter'; + return this; + + }, + + /** + * Sets the blend mode to 'multiply' + * + * @method Phaser.BitmapData#blendMultiply + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendMultiply: function () { + + this.op = 'multiply'; + return this; + + }, + + /** + * Sets the blend mode to 'screen' + * + * @method Phaser.BitmapData#blendScreen + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendScreen: function () { + + this.op = 'screen'; + return this; + + }, + + /** + * Sets the blend mode to 'overlay' + * + * @method Phaser.BitmapData#blendOverlay + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendOverlay: function () { + + this.op = 'overlay'; + return this; + + }, + + /** + * Sets the blend mode to 'darken' + * + * @method Phaser.BitmapData#blendDarken + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDarken: function () { + + this.op = 'darken'; + return this; + + }, + + /** + * Sets the blend mode to 'lighten' + * + * @method Phaser.BitmapData#blendLighten + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLighten: function () { + + this.op = 'lighten'; + return this; + + }, + + /** + * Sets the blend mode to 'color-dodge' + * + * @method Phaser.BitmapData#blendColorDodge + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorDodge: function () { + + this.op = 'color-dodge'; + return this; + + }, + + /** + * Sets the blend mode to 'color-burn' + * + * @method Phaser.BitmapData#blendColorBurn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorBurn: function () { + + this.op = 'color-burn'; + return this; + + }, + + /** + * Sets the blend mode to 'hard-light' + * + * @method Phaser.BitmapData#blendHardLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHardLight: function () { + + this.op = 'hard-light'; + return this; + + }, + + /** + * Sets the blend mode to 'soft-light' + * + * @method Phaser.BitmapData#blendSoftLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSoftLight: function () { + + this.op = 'soft-light'; + return this; + + }, + + /** + * Sets the blend mode to 'difference' + * + * @method Phaser.BitmapData#blendDifference + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDifference: function () { + + this.op = 'difference'; + return this; + + }, + + /** + * Sets the blend mode to 'exclusion' + * + * @method Phaser.BitmapData#blendExclusion + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendExclusion: function () { + + this.op = 'exclusion'; + return this; + + }, + + /** + * Sets the blend mode to 'hue' + * + * @method Phaser.BitmapData#blendHue + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHue: function () { + + this.op = 'hue'; + return this; + + }, + + /** + * Sets the blend mode to 'saturation' + * + * @method Phaser.BitmapData#blendSaturation + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSaturation: function () { + + this.op = 'saturation'; + return this; + + }, + + /** + * Sets the blend mode to 'color' + * + * @method Phaser.BitmapData#blendColor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColor: function () { + + this.op = 'color'; + return this; + + }, + + /** + * Sets the blend mode to 'luminosity' + * + * @method Phaser.BitmapData#blendLuminosity + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLuminosity: function () { + + this.op = 'luminosity'; + return this; + + }, + + /** + * Updates a portion of the BitmapData from a source Bitmap. + * This optimization is important if calling update() on a large Bitmap is causing performance issues. + * Make sure you use getPixel32() instead of getPixel(). + * This does not work with floating point numbers for x and y. + * + * @method Phaser.BitmapData#copyBitmapData + * @param {Phaser.BitmapData} [source] - The BitmapData you wish to copy. + * @param {number} [x] - The x coordinate of the top-left of the area to copy. + * @param {number} [y] - The y coordinate of the top-left of the area to copy. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyBitmapData: function(source, x, y) { + + source.update(); + for (var i = 0, destRowStart; i < source.height; i++) { + destRowStart = (y + i) * this.width + x; + for (var j = 0; j < source.width; j++) { + this.pixels[destRowStart + j] = source.pixels[i * source.width + j]; + } + } + return this; + + } + +}; + +/** +* @memberof Phaser.BitmapData +* @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", { + + get: function () { + + Phaser.Canvas.getSmoothingEnabled(this.context); + + }, + + set: function (value) { + + Phaser.Canvas.setSmoothingEnabled(this.context, value); + + } + +}); + +/** +* @memberof Phaser.BitmapData +* @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "op", { + + get: function () { + + return this.context.globalCompositeOperation; + + }, + + set: function (value) { + + this.context.globalCompositeOperation = value; + + } + +}); + +/** + * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform. + * + * @method Phaser.BitmapData.getTransform + * @param {number} translateX - The x translate value. + * @param {number} translateY - The y translate value. + * @param {number} scaleX - The scale x value. + * @param {number} scaleY - The scale y value. + * @param {number} skewX - The skew x value. + * @param {number} skewY - The skew y value. + * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms. + */ +Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) { + + if (typeof translateX !== 'number') { translateX = 0; } + if (typeof translateY !== 'number') { translateY = 0; } + if (typeof scaleX !== 'number') { scaleX = 1; } + if (typeof scaleY !== 'number') { scaleY = 1; } + if (typeof skewX !== 'number') { skewX = 0; } + if (typeof skewY !== 'number') { skewY = 0; } + + return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY }; + +}; + +Phaser.BitmapData.prototype.constructor = Phaser.BitmapData; + +/* jshint ignore:start */ + +/* +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ + +/** +* @class EarCut +*/ +Phaser.EarCut = {}; + +Phaser.EarCut.Triangulate = function (data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = Phaser.EarCut.linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = Phaser.EarCut.eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + Phaser.EarCut.earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +}; + +// create a circular doubly linked list from polygon points in the specified winding order + +Phaser.EarCut.linkedList = function (data, start, end, dim, clockwise) { + var sum = 0, + i, j, last; + + // calculate original winding order of a polygon ring + for (i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + + // link points into circular doubly-linked list in the specified winding order + if (clockwise === (sum > 0)) { + for (i = start; i < end; i += dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } + + return last; +}; + +// eliminate colinear or duplicate points + +Phaser.EarCut.filterPoints = function (start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (Phaser.EarCut.equals(p, p.next) || Phaser.EarCut.area(p.prev, p, p.next) === 0)) { + Phaser.EarCut.removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +}; + +// main ear slicing loop which triangulates a polygon (given as a linked list) + +Phaser.EarCut.earcutLinked = function (ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) Phaser.EarCut.indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? Phaser.EarCut.isEarHashed(ear, minX, minY, size) : Phaser.EarCut.isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + Phaser.EarCut.removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + Phaser.EarCut.earcutLinked(Phaser.EarCut.filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = Phaser.EarCut.cureLocalIntersections(ear, triangles, dim); + Phaser.EarCut.earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + Phaser.EarCut.splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +}; + +// check whether a polygon node forms a valid ear with adjacent nodes + +Phaser.EarCut.isEar = function (ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +}; + +Phaser.EarCut.isEarHashed = function (ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = Phaser.EarCut.zOrder(minTX, minTY, minX, minY, size), + maxZ = Phaser.EarCut.zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +}; + +// go through all polygon nodes and cure small local self-intersections + +Phaser.EarCut.cureLocalIntersections = function (start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) + if (Phaser.EarCut.intersects(a, p, p.next, b) && Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + Phaser.EarCut.removeNode(p); + Phaser.EarCut.removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +}; + +// try splitting polygon into two and triangulate them independently + +Phaser.EarCut.splitEarcut = function (start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && Phaser.EarCut.isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = Phaser.EarCut.splitPolygon(a, b); + + // filter colinear points around the cuts + a = Phaser.EarCut.filterPoints(a, a.next); + c = Phaser.EarCut.filterPoints(c, c.next); + + // run earcut on each half + Phaser.EarCut.earcutLinked(a, triangles, dim, minX, minY, size); + Phaser.EarCut.earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +}; + +// link every hole into the outer loop, producing a single-ring polygon without holes + +Phaser.EarCut.eliminateHoles = function (data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = Phaser.EarCut.linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(Phaser.EarCut.getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + Phaser.EarCut.eliminateHole(queue[i], outerNode); + outerNode = Phaser.EarCut.filterPoints(outerNode, outerNode.next); + } + + return outerNode; +}; + +Phaser.EarCut.compareX = function (a, b) { + return a.x - b.x; +}; + +// find a bridge between vertices that connects hole with an outer ring and and link it + +Phaser.EarCut.eliminateHole = function (hole, outerNode) { + outerNode = Phaser.EarCut.findHoleBridge(hole, outerNode); + if (outerNode) { + var b = Phaser.EarCut.splitPolygon(outerNode, hole); + Phaser.EarCut.filterPoints(b, b.next); + } +}; + +// David Eberly's algorithm for finding a bridge between hole and outer polygon + +Phaser.EarCut.findHoleBridge = function (hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hole.x === m.x) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= m.x && + Phaser.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && Phaser.EarCut.locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +}; + +// interlink polygon nodes in z-order + +Phaser.EarCut.indexCurve = function (start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = Phaser.EarCut.zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + Phaser.EarCut.sortLinked(p); +}; + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + +Phaser.EarCut.sortLinked = function (list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +}; + +// z-order of a point given coords and size of the data bounding box + +Phaser.EarCut.zOrder = function (x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +}; + +// find the leftmost node of a polygon ring + +Phaser.EarCut.getLeftmost = function (start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +}; + +// check if a point lies within a convex triangle + +Phaser.EarCut.pointInTriangle = function (ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +}; + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) + +Phaser.EarCut.isValidDiagonal = function (a, b) { + return Phaser.EarCut.equals(a, b) || a.next.i !== b.i && a.prev.i !== b.i && !Phaser.EarCut.intersectsPolygon(a, b) && + Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a) && Phaser.EarCut.middleInside(a, b); +}; + +// signed area of a triangle + +Phaser.EarCut.area = function (p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +}; + +// check if two points are equal + +Phaser.EarCut.equals = function (p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +}; + +// check if two segments intersect + +Phaser.EarCut.intersects = function (p1, q1, p2, q2) { + return Phaser.EarCut.area(p1, q1, p2) > 0 !== Phaser.EarCut.area(p1, q1, q2) > 0 && + Phaser.EarCut.area(p2, q2, p1) > 0 !== Phaser.EarCut.area(p2, q2, q1) > 0; +}; + +// check if a polygon diagonal intersects any polygon segments + +Phaser.EarCut.intersectsPolygon = function (a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + Phaser.EarCut.intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +}; + +// check if a polygon diagonal is locally inside the polygon + +Phaser.EarCut.locallyInside = function (a, b) { + return Phaser.EarCut.area(a.prev, a, a.next) < 0 ? + Phaser.EarCut.area(a, b, a.next) >= 0 && Phaser.EarCut.area(a, a.prev, b) >= 0 : + Phaser.EarCut.area(a, b, a.prev) < 0 || Phaser.EarCut.area(a, a.next, b) < 0; +}; + +// check if the middle point of a polygon diagonal is inside the polygon + +Phaser.EarCut.middleInside = function (a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +}; + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring + +Phaser.EarCut.splitPolygon = function (a, b) { + var a2 = new Phaser.EarCut.Node(a.i, a.x, a.y), + b2 = new Phaser.EarCut.Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +}; + +// create a node and optionally link it with previous one (in a circular doubly linked list) + +Phaser.EarCut.insertNode = function (i, x, y, last) { + var p = new Phaser.EarCut.Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +}; + +Phaser.EarCut.removeNode = function (p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +}; + +Phaser.EarCut.Node = function (i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +}; + +/* jshint ignore:end */ + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used by the webGL renderer to draw the primitive graphics data + * + * @class PIXI.WebGLGraphics + * @private + * @static + */ +PIXI.WebGLGraphics = function() +{ +}; + +/** + * The number of points beyond which Pixi swaps to using the Stencil Buffer to render the Graphics. + * + * @type {number} + */ +PIXI.WebGLGraphics.stencilBufferLimit = 6; + +/** + * Renders the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.renderGraphics + * @param graphics {Graphics} + * @param renderSession {Object} + */ +PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset) +{ + var gl = renderSession.gl; + var projection = renderSession.projection, + offset = renderSession.offset, + shader = renderSession.shaderManager.primitiveShader, + webGLData; + + if(graphics.dirty) + { + PIXI.WebGLGraphics.updateGraphics(graphics, gl); + } + + var webGL = graphics._webGL[gl.id]; + + // if the graphics object does not exist in the webGL context skip rendering! + if(!webGL) + { + return; + } + + // This could be speeded up for sure! + + for (var i = 0; i < webGL.data.length; i++) + { + if(webGL.data[i].mode === 1) + { + webGLData = webGL.data[i]; + + renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession); + + // render quad.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + renderSession.stencilManager.popStencil(graphics, webGLData, renderSession); + } + else + { + webGLData = webGL.data[i]; + + + renderSession.shaderManager.setShader( shader );//activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, 1); + + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + } + } +}; + +/** + * Updates the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.updateGraphics + * @param graphicsData {Graphics} The graphics object to update + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLGraphics.updateGraphics = function(graphics, gl) +{ + // get the contexts graphics object + var webGL = graphics._webGL[gl.id]; + // if the graphics object does not exist in the webGL context time to create it! + if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; + + // flag the graphics as not dirty as we are about to update it... + graphics.dirty = false; + + var i; + + // if the user cleared the graphics object we will need to clear every object + if(graphics.clearDirty) + { + graphics.clearDirty = false; + + // lop through and return all the webGLDatas to the object pool so than can be reused later on + for (i = 0; i < webGL.data.length; i++) + { + var graphicsData = webGL.data[i]; + graphicsData.reset(); + PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData ); + } + + // clear the array and reset the index.. + webGL.data = []; + webGL.lastIndex = 0; + } + + var webGLData; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + if (data.type === Phaser.POLYGON) + { + // need to add the points the the graphics object.. + data.points = data.shape.points.slice(); + if(data.shape.closed) + { + // close the poly if the value is true! + if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { + data.points.push(data.points[0], data.points[1]); + } + } + + // MAKE SURE WE HAVE THE CORRECT TYPE.. + if(data.fill) + { + if(data.points.length >= PIXI.WebGLGraphics.stencilBufferLimit) + { + if(data.points.length < PIXI.WebGLGraphics.stencilBufferLimit * 2) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData); + // console.log(canDrawUsingSimple); + + if(!canDrawUsingSimple) + { + // console.log("<>>>") + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + } + } + + if(data.lineWidth > 0) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + PIXI.WebGLGraphics.buildLine(data, webGLData); + + } + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + if (data.type === Phaser.RECTANGLE) + { + PIXI.WebGLGraphics.buildRectangle(data, webGLData); + } + else if (data.type === Phaser.CIRCLE || data.type === Phaser.ELLIPSE) + { + PIXI.WebGLGraphics.buildCircle(data, webGLData); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData); + } + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (i = 0; i < webGL.data.length; i++) + { + webGLData = webGL.data[i]; + if(webGLData.dirty)webGLData.upload(); + } +}; + +/** + * @static + * @private + * @method PIXI.WebGLGraphics.switchMode + * @param webGL {WebGLContext} + * @param type {Number} + */ +PIXI.WebGLGraphics.switchMode = function(webGL, type) +{ + var webGLData; + + if(!webGL.data.length) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + else + { + webGLData = webGL.data[webGL.data.length-1]; + + if(webGLData.mode !== type || type === 1) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + } + + webGLData.dirty = true; + + return webGLData; +}; + +/** + * Builds a rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData) +{ + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; + + // start + 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); + + // insert 2 dead triangles.. + 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; + } +}; + +/** + * Builds a rounded rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRoundedRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData) +{ + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + recPoints.push(x, y + radius); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); + + if (graphicsData.fill) { + var color = Phaser.Color.hexToRGBArray(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; + + var triangles = Phaser.EarCut.Triangulate(recPoints, null, 2); + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i+1] + vecPos); + indices.push(triangles[i+2] + vecPos); + indices.push(triangles[i+2] + vecPos); + } + + + for (i = 0; i < recPoints.length; i++) + { + verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @static + * @private + * @method PIXI.WebGLGraphics.quadraticBezierCurve + * @param fromX {Number} Origin point x + * @param fromY {Number} Origin point x + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Array(Number)} + */ +PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) { + + var xa, + ya, + xb, + yb, + x, + y, + n = 20, + points = []; + + function getPt(n1 , n2, perc) { + var diff = n2 - n1; + + return n1 + ( diff * perc ); + } + + var j = 0; + for (var i = 0; i <= n; i++ ) + { + j = i / n; + + // The Green Line + xa = getPt( fromX , cpX , j ); + ya = getPt( fromY , cpY , j ); + xb = getPt( cpX , toX , j ); + yb = getPt( cpY , toY , j ); + + // The Black Dot + x = getPt( xa , xb , j ); + y = getPt( ya , yb , j ); + + points.push(x, y); + } + return points; +}; + +/** + * Builds a circle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildCircle + * @param graphicsData {Graphics} The graphics object to draw + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData) +{ + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + + // TODO - bit hacky?? + if (graphicsData.type === Phaser.CIRCLE) + { + width = circleData.radius; + height = circleData.radius; + } + else + { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = 40; + var seg = (Math.PI * 2) / totalSegs ; + + var i = 0; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; i < totalSegs + 1 ; i++) + { + verts.push(x,y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos-1); + } + + if(graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (i = 0; i < totalSegs + 1; i++) + { + graphicsData.points.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height); + } + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Builds a line to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildLine + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData) +{ + // TODO OPTIMISE! + var i = 0; + var points = graphicsData.points; + if(points.length === 0)return; + + // if the line width is an odd number add 0.5 to align to a whole pixel + if(graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) { + points[i] += 0.5; + } + } + + // get first and last point.. figure out the middle! + var firstPoint = new PIXI.Point( points[0], points[1] ); + var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + // if the first point is the last point - gonna have issues :) + if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length/6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var px, py, p1x, p1y, p2x, p2y, p3x, p3y; + var perpx, perpy, perp2x, perp2y, perp3x, perp3y; + var a1, b1, c1, a2, b2, c2; + var denom, pdist, dist; + + p1x = points[0]; + p1y = points[1]; + + p2x = points[2]; + p2y = points[3]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx , p1y - perpy, + r, g, b, alpha); + + verts.push(p1x + perpx , p1y + perpy, + r, g, b, alpha); + + for (i = 1; i < length-1; i++) + { + p1x = points[(i-1)*2]; + p1y = points[(i-1)*2 + 1]; + + p2x = points[(i)*2]; + p2y = points[(i)*2 + 1]; + + p3x = points[(i+1)*2]; + p3y = points[(i+1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + a1 = (-perpy + p1y) - (-perpy + p2y); + b1 = (-perpx + p2x) - (-perpx + p1x); + c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + a2 = (-perp2y + p3y) - (-perp2y + p2y); + b2 = (-perp2x + p2x) - (-perp2x + p3x); + c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + denom = a1*b2 - a2*b1; + + if(Math.abs(denom) < 0.1 ) + { + + denom+=10.1; + verts.push(p2x - perpx , p2y - perpy, + r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy, + r, g, b, alpha); + + continue; + } + + px = (b1*c2 - b2*c1)/denom; + py = (a2*c1 - a1*c2)/denom; + + + pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); + + + if(pdist > 140 * 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 < indexCount; i++) + { + indices.push(indexStart++); + } + + indices.push(indexStart-1); +}; + +/** + * Builds a complex polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildComplexPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData) +{ + //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. + var points = graphicsData.points.slice(); + if(points.length < 6)return; + + // get first and last point.. figure out the middle! + var indices = webGLData.indices; + webGLData.points = points; + webGLData.alpha = graphicsData.fillAlpha; + webGLData.color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + + /* + calclate the bounds.. + */ + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + var x,y; + + // get size.. + for (var i = 0; i < points.length; i+=2) + { + x = points[i]; + y = points[i+1]; + + minX = x < minX ? x : minX; + maxX = x > maxX ? x : maxX; + + minY = y < minY ? y : minY; + maxY = y > maxY ? y : maxY; + } + + // add a quad to the end cos there is no point making another buffer! + points.push(minX, minY, + maxX, minY, + maxX, maxY, + minX, maxY); + + // push a quad onto the end.. + + //TODO - this aint needed! + var length = points.length / 2; + for (i = 0; i < length; i++) + { + indices.push( i ); + } + +}; + +/** + * Builds a polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData) +{ + var points = graphicsData.points; + + if(points.length < 6)return; + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = Phaser.EarCut.Triangulate(points, null, 2); + + if(!triangles)return false; + + var vertPos = verts.length / 6; + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i] + vertPos); + indices.push(triangles[i+1] + vertPos); + indices.push(triangles[i+2] +vertPos); + indices.push(triangles[i+2] + vertPos); + } + + for (i = 0; i < length; i++) + { + verts.push(points[i * 2], points[i * 2 + 1], + r, g, b, alpha); + } + + return true; +}; + +PIXI.WebGLGraphics.graphicsDataPool = []; + +/** + * @class WebGLGraphicsData + * @private + * @static + */ +PIXI.WebGLGraphicsData = function(gl) +{ + this.gl = gl; + + //TODO does this need to be split before uploding?? + this.color = [0,0,0]; // color split! + this.points = []; + this.indices = []; + this.buffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + this.mode = 1; + this.alpha = 1; + this.dirty = true; +}; + +/** + * @method PIXI.WebGLGraphics.reset + */ +PIXI.WebGLGraphicsData.prototype.reset = function() +{ + this.points = []; + this.indices = []; +}; + +/** + * @method PIXI.WebGLGraphics.upload + */ +PIXI.WebGLGraphicsData.prototype.upload = function() +{ + var gl = this.gl; + +// this.lastIndex = graphics.graphicsData.length; + this.glPoints = new Float32Array(this.points); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW); + + this.glIndicies = new Uint16Array(this.indices); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW); + + this.dirty = false; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + +/** + * A set of functions used by the canvas renderer to draw the primitive graphics data. + * + * @class PIXI.CanvasGraphics + * @static + */ +PIXI.CanvasGraphics = function() +{ +}; + +/** + * Renders a {@link Phaser.Graphics} object to a canvas. + * + * @method PIXI.CanvasGraphics.renderGraphics + * @static + * @param graphics {Graphics} the actual graphics object to render + * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas + */ +PIXI.CanvasGraphics.renderGraphics = function(graphics, context) +{ + var worldAlpha = graphics.worldAlpha; + + if (graphics.dirty) + { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === Phaser.POLYGON) + { + context.beginPath(); + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (shape.closed) + { + context.lineTo(points[0], points[1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.RECTANGLE) + { + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ELLIPSE) + { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + context.beginPath(); + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + +}; + +/** + * Renders a graphics mask + * + * @static + * @private + * @method PIXI.CanvasGraphics.renderGraphicsMask + * @param graphics {Graphics} the graphics which will be used as a mask + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + */ +PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context) +{ + var len = graphics.graphicsData.length; + + if (len === 0) + { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === Phaser.POLYGON) + { + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + } + else if (data.type === Phaser.RECTANGLE) + { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } + else if (data.type === Phaser.ELLIPSE) + { + + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } +}; + +PIXI.CanvasGraphics.updateGraphicsTint = function(graphics) +{ + if (graphics.tint === 0xFFFFFF) + { + return; + } + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF)/ 255; + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255); + data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255); + + } + +}; + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + * @param lineWidth {number} the width of the line to draw + * @param lineColor {number} the color of the line to draw + * @param lineAlpha {number} the alpha of the line to draw + * @param fillColor {number} the color of the fill + * @param fillAlpha {number} the alpha of the fill + * @param fill {boolean} whether or not the shape is filled with a colour + * @param shape {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + +Phaser.GraphicsData = function (lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { + + /* + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /* + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /* + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /* + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /* + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /* + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /* + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /* + * @member {boolean} whether or not the shape is filled with a color + */ + this.fill = fill; + + /* + * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + this.shape = shape; + + /* + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + +}; + +Phaser.GraphicsData.prototype.constructor = Phaser.GraphicsData; + +/** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {GraphicsData} + */ +Phaser.GraphicsData.prototype.clone = function () { + + return new Phaser.GraphicsData( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.fill, + this.shape + ); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, +* Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will +* be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: +* +* ```javascript +* graphics.beginFill(0xff0000); +* graphics.drawCircle(50, 50, 100); +* graphics.endFill(); +* ``` +* +* This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. +* +* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or +* WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the +* graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. +* +* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help +* performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. +* You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then +* you should avoid doing this, as it will constantly generate new textures, which will consume memory. +* +* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful +* in their complexity and quantity of them in your game. +* +* @class Phaser.Graphics +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - X position of the new graphics object. +* @param {number} [y=0] - Y position of the new graphics object. +*/ +Phaser.Graphics = function (game, x, y) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.GRAPHICS; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value. + * @private + */ + this.anchor = new Phaser.Point(); + + PIXI.DisplayObjectContainer.call(this); + + this.renderable = true; + + /** + * The alpha value used when filling the Graphics object. + * + * @property fillAlpha + * @type Number + */ + this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @property lineWidth + * @type Number + */ + this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @property lineColor + * @type String + * @default 0 + */ + this.lineColor = 0; + + /** + * Graphics data + * + * @property graphicsData + * @type Array + * @private + */ + this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF (Phaser.Color.WHITE) to reset the tint. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * Current path + * + * @property currentPath + * @type Object + * @private + */ + this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @property _webGL + * @type Array + * @private + */ + this._webGL = []; + + /** + * Whether this shape is being used as a mask. + * + * @property isMask + * @type Boolean + */ + this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @property boundsPadding + * @type Number + */ + this.boundsPadding = 0; + + this._localBounds = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property dirty + * @type Boolean + * @private + */ + this.dirty = true; + + /** + * Used to detect if the bounds have been invalidated, by this Graphics being cleared or drawn to. + * If this is set to true then the updateLocalBounds is called once in the postUpdate method. + * + * @property _boundsDirty + * @type Boolean + * @private + */ + this._boundsDirty = false; + + /** + * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property webGLDirty + * @type Boolean + * @private + */ + this.webGLDirty = false; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @property cachedSpriteDirty + * @type Boolean + * @private + */ + this.cachedSpriteDirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.Graphics.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Graphics.prototype.constructor = Phaser.Graphics; + +Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Graphics#preUpdate +*/ +Phaser.Graphics.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World +* +* @method Phaser.Graphics#postUpdate +*/ +Phaser.Graphics.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this._boundsDirty) + { + this.updateLocalBounds(); + this._boundsDirty = false; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Destroy this Graphics instance. +* +* @method Phaser.Graphics#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Graphics.prototype.destroy = function (destroyChildren) { + + this.clear(); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Draws a single {@link Phaser.Polygon} triangle from a {@link Phaser.Point} array +* +* @method Phaser.Graphics#drawTriangle +* @param {Array} points - An array of Phaser.Points that make up the three vertices of this triangle +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangle = function (points, cull) { + + if (cull === undefined) { cull = false; } + + var triangle = new Phaser.Polygon(points); + + if (cull) + { + var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y); + var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y); + var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y); + var faceNormal = cb.cross(ab); + + if (cameraToFace.dot(faceNormal) > 0) + { + this.drawPolygon(triangle); + } + } + else + { + this.drawPolygon(triangle); + } + +}; + +/** +* Draws {@link Phaser.Polygon} triangles +* +* @method Phaser.Graphics#drawTriangles +* @param {Array|Array} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles +* @param {Array} [indices=null] - An array of numbers that describe what order to draw the vertices in +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) { + + if (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 < vertices.length / 3; i++) + { + this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull); + } + } + else + { + for (i = 0; i < vertices.length / 6; i++) + { + point1.x = vertices[i * 6 + 0]; + point1.y = vertices[i * 6 + 1]; + point2.x = vertices[i * 6 + 2]; + point2.y = vertices[i * 6 + 3]; + point3.x = vertices[i * 6 + 4]; + point3.y = vertices[i * 6 + 5]; + this.drawTriangle([point1, point2, point3], cull); + } + } + } + else + { + if (vertices[0] instanceof Phaser.Point) + { + for (i = 0; i < indices.length /3; i++) + { + points.push(vertices[indices[i * 3 ]]); + points.push(vertices[indices[i * 3 + 1]]); + points.push(vertices[indices[i * 3 + 2]]); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + else + { + for (i = 0; i < indices.length; i++) + { + point1.x = vertices[indices[i] * 2]; + point1.y = vertices[indices[i] * 2 + 1]; + points.push(point1.copyTo({})); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + } +}; + +/** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. + * + * @method Phaser.Graphics#lineStyle + * @param lineWidth {Number} width of the line to draw, will update the objects stored style + * @param color {Number} color of the line to draw, will update the objects stored style + * @param alpha {Number} alpha of the line to draw, will update the objects stored style + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { + + this.lineWidth = lineWidth || 0; + this.lineColor = color || 0; + this.lineAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { + // halfway through a line? start a new one! + this.drawShape(new Phaser.Polygon(this.currentPath.shape.points.slice(-2))); + } + else + { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + +}; + +/** + * Moves the current drawing position to x, y. + * + * @method Phaser.Graphics#moveTo + * @param x {Number} the X coordinate to move to + * @param y {Number} the Y coordinate to move to + * @return {Graphics} + */ +Phaser.Graphics.prototype.moveTo = function (x, y) { + + this.drawShape(new Phaser.Polygon([ x, y ])); + + return this; + +}; + +/** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @method Phaser.Graphics#lineTo + * @param x {Number} the X coordinate to draw to + * @param y {Number} the Y coordinate to draw to + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineTo = function (x, y) { + + if (!this.currentPath) + { + this.moveTo(0, 0); + } + + this.currentPath.shape.points.push(x, y); + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @method Phaser.Graphics#quadraticCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [ 0, 0 ]; + } + } + else + { + this.moveTo(0,0); + } + + var xa, + ya, + n = 20, + points = this.currentPath.shape.points; + + if (points.length === 0) + { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var j = 0; + for (var i = 1; i <= n; ++i) + { + j = i / n; + + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + + points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), + ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a bezier curve and then draws it. + * + * @method Phaser.Graphics#bezierCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param cpX2 {Number} Second Control point x + * @param cpY2 {Number} Second Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + var n = 20, + dt, + dt2, + dt3, + t2, + t3, + points = this.currentPath.shape.points; + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + var j = 0; + + for (var i = 1; i <= n; ++i) + { + j = i / n; + + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, + dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @method Phaser.Graphics#arcTo + * @param x1 {Number} The x-coordinate of the beginning of the arc + * @param y1 {Number} The y-coordinate of the beginning of the arc + * @param x2 {Number} The x-coordinate of the end of the arc + * @param y2 {Number} The y-coordinate of the end of the arc + * @param radius {Number} The radius of the arc + * @return {Graphics} + */ +Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points.push(x1, y1); + } + } + else + { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points, + fromX = points[points.length-2], + fromY = points[points.length-1], + a1 = fromY - y1, + b1 = fromX - x1, + a2 = y2 - y1, + b2 = x2 - x1, + mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { + points.push(x1, y1); + } + } + else + { + var dd = a1 * a1 + b1 * b1, + cc = a2 * a2 + b2 * b2, + tt = a1 * a2 + b1 * b2, + k1 = radius * Math.sqrt(dd) / mm, + k2 = radius * Math.sqrt(cc) / mm, + j1 = k1 * tt / dd, + j2 = k2 * tt / cc, + cx = k1 * b2 + k2 * b1, + cy = k1 * a2 + k2 * a1, + px = b1 * (k2 + j1), + py = a1 * (k2 + j1), + qx = b2 * (k1 + j2), + qy = a2 * (k1 + j2), + startAngle = Math.atan2(py - cy, px - cx), + endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @method Phaser.Graphics#arc + * @param cx {Number} The x-coordinate of the center of the circle + * @param cy {Number} The y-coordinate of the center of the circle + * @param radius {Number} The radius of the circle + * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) + * @param endAngle {Number} The ending angle, in radians + * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. + * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. + * @return {Graphics} + */ +Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise, segments) { + + // If we do this we can never draw a full circle + if (startAngle === endAngle) + { + return this; + } + + if (anticlockwise === undefined) { anticlockwise = false; } + if (segments === undefined) { segments = 40; } + + if (!anticlockwise && endAngle <= startAngle) + { + endAngle += Math.PI * 2; + } + else if (anticlockwise && startAngle <= endAngle) + { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments; + + // Sweep check - moved here because we don't want to do the moveTo below if the arc fails + if (sweep === 0) + { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (anticlockwise && this.filling) + { + this.moveTo(cx, cy); + } + else + { + this.moveTo(startX, startY); + } + + // currentPath will always exist after calling a moveTo + var points = this.currentPath.shape.points; + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = (segMinus % 1) / segMinus; + + for (var i = 0; i <= segMinus; i++) + { + var real = i + remainder * i; + + var angle = ((theta) + startAngle + (theta2 * real)); + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, + ( (cTheta * -s) + (sTheta * c) ) * radius + cy); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @method Phaser.Graphics#beginFill + * @param color {Number} the color of the fill + * @param alpha {Number} the alpha of the fill + * @return {Graphics} + */ +Phaser.Graphics.prototype.beginFill = function (color, alpha) { + + this.filling = true; + this.fillColor = color || 0; + this.fillAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + +}; + +/** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @method Phaser.Graphics#endFill + * @return {Graphics} + */ +Phaser.Graphics.prototype.endFill = function () { + + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRect + * + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawRect = function (x, y, width, height) { + + this.drawShape(new Phaser.Rectangle(x, y, width, height)); + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRoundedRect + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. + */ +Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + + this.drawShape(new Phaser.RoundedRectangle(x, y, width, height, radius)); + + return this; + +}; + +/** + * Draws a circle. + * + * @method Phaser.Graphics#drawCircle + * @param x {Number} The X coordinate of the center of the circle + * @param y {Number} The Y coordinate of the center of the circle + * @param diameter {Number} The diameter of the circle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) { + + this.drawShape(new Phaser.Circle(x, y, diameter)); + + return this; + +}; + +/** + * Draws an ellipse. + * + * @method Phaser.Graphics#drawEllipse + * @param x {Number} The X coordinate of the center of the ellipse + * @param y {Number} The Y coordinate of the center of the ellipse + * @param width {Number} The half width of the ellipse + * @param height {Number} The half height of the ellipse + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawEllipse = function (x, y, width, height) { + + this.drawShape(new Phaser.Ellipse(x, y, width, height)); + + return this; + +}; + +/** + * Draws a polygon using the given path. + * + * @method Phaser.Graphics#drawPolygon + * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawPolygon = function (path) { + + if (path instanceof Phaser.Polygon) + { + path = path.points; + } + + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) + { + points[i] = arguments[i]; + } + } + + this.drawShape(new Phaser.Polygon(points)); + + return this; + +}; + +/** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @method Phaser.Graphics#clear + * @return {Graphics} + */ +Phaser.Graphics.prototype.clear = function () { + + this.lineWidth = 0; + this.filling = false; + + this.dirty = true; + this._boundsDirty = true; + this.clearDirty = true; + this.graphicsData = []; + + this.updateLocalBounds(); + + return this; + +}; + +/** + * Useful function that returns a texture of the graphics object that can then be used to create sprites + * This can be quite useful if your geometry is complicated and needs to be reused multiple times. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * @method Phaser.Graphics#generateTexture + * @param [resolution=1] {Number} The resolution of the texture being generated + * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts + * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0) + * @return {Texture} a texture of the graphics object + */ +Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, padding) { + + if (resolution === undefined) { resolution = 1; } + if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; } + if (padding === undefined) { padding = 0; } + + var bounds = this.getBounds(); + + bounds.width += padding; + bounds.height += padding; + + var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution); + + var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + + canvasBuffer.context.scale(resolution, resolution); + + canvasBuffer.context.translate(-bounds.x, -bounds.y); + + PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context); + + return texture; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Graphics#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderWebGL = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture on the gpu too! + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.worldAlpha = this.worldAlpha; + + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + + return; + } + else + { + renderSession.spriteBatch.stop(); + renderSession.blendModeManager.setBlendMode(this.blendMode); + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + if (this._filters) + { + renderSession.filterManager.pushFilter(this._filterBlock); + } + + // check blend mode + if (this.blendMode !== renderSession.spriteBatch.currentBlendMode) + { + renderSession.spriteBatch.currentBlendMode = this.blendMode; + var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode]; + renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + // check if the webgl graphic needs to be updated + if (this.webGLDirty) + { + this.dirty = true; + this.webGLDirty = false; + } + + PIXI.WebGLGraphics.renderGraphics(this, renderSession); + + // only render if it has children! + if (this.children.length) + { + renderSession.spriteBatch.start(); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + } + + if (this._filters) + { + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + renderSession.maskManager.popMask(this.mask, renderSession); + } + + renderSession.drawCount++; + + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method Phaser.Graphics#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderCanvas = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) + { + this.dirty = true; + this._prevTint = this.tint; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.alpha = this.alpha; + + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + + return; + } + else + { + var context = renderSession.context; + var transform = this.worldTransform; + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + var resolution = renderSession.resolution; + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + tx, + ty); + + PIXI.CanvasGraphics.renderGraphics(this, context); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + } + +}; + +/** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @method Phaser.Graphics#getBounds + * @return {Rectangle} the rectangular bounding area + */ +Phaser.Graphics.prototype.getBounds = function (matrix) { + + if (this._currentBounds) + { + return this._currentBounds; + } + + // Return an empty object if the item is a mask! + if (!this.renderable) + { + return Phaser.EmptyRectangle; + } + + if (this.dirty) + { + this.updateLocalBounds(); + this.webGLDirty = true; + this.cachedSpriteDirty = true; + this.dirty = false; + } + + var bounds = this._localBounds; + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = x1; + var maxY = y1; + + var minX = x1; + var minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + + this._bounds.x = minX; + this._bounds.width = maxX - minX; + + this._bounds.y = minY; + this._bounds.height = maxY - minY; + + this._currentBounds = this._bounds; + + return this._currentBounds; + +}; + +/** + * Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration. + * + * @method Phaser.Graphics#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +Phaser.Graphics.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Tests if a point is inside this graphics object +* +* @param point {Point} the point to test +* @return {boolean} the result of the test +*/ +Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) { + + if (tempPoint === undefined) { tempPoint = new Phaser.Point(); } + + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; i++) + { + var data = graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // only deal with fills.. + if (data.shape) + { + if (data.shape.contains(tempPoint.x, tempPoint.y)) + { + return true; + } + } + } + + return false; + +}; + +/** + * Update the bounds of the object + * + * @method Phaser.Graphics#updateLocalBounds + */ +Phaser.Graphics.prototype.updateLocalBounds = function () { + + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) + { + var shape, points, x, y, w, h; + + for (var i = 0; i < this.graphicsData.length; i++) + { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + shape = data.shape; + + if (type === Phaser.RECTANGLE || type === Phaser.ROUNDEDRECTANGLE) + { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.CIRCLE) + { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.ELLIPSE) + { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else + { + // POLY - assumes points are sequential, not Point objects + points = shape.points; + + for (var j = 0; j < points.length; j++) + { + if (points[j] instanceof Phaser.Point) + { + x = points[j].x; + y = points[j].y; + } + else + { + x = points[j]; + y = points[j + 1]; + + if (j < points.length - 1) + { + j++; + } + } + + minX = x - lineWidth < minX ? x - lineWidth : minX; + maxX = x + lineWidth > maxX ? x + lineWidth : maxX; + + minY = y - lineWidth < minY ? y - lineWidth : minY; + maxY = y + lineWidth > maxY ? y + lineWidth : maxY; + } + } + } + } + else + { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.x = minX - padding; + this._localBounds.width = (maxX - minX) + padding * 2; + + this._localBounds.y = minY - padding; + this._localBounds.height = (maxY - minY) + padding * 2; + +}; + +/** + * Generates the cached sprite when the sprite has cacheAsBitmap = true + * + * @method Phaser.Graphics#_generateCachedSprite + * @private + */ +Phaser.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); + } + + // leverage the anchor to account for the offset of the element + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + // this._cachedSprite.buffer.context.save(); + this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y); + + // make sure we set the alpha of the graphics to 1 for the render.. + this.worldAlpha = 1; + + // now render the graphic.. + PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context); + this._cachedSprite.alpha = this.alpha; + +}; + +/** + * Updates texture size based on canvas size + * + * @method Phaser.Graphics#updateCachedSpriteTexture + * @private + */ +Phaser.Graphics.prototype.updateCachedSpriteTexture = function () { + + var cachedSprite = this._cachedSprite; + var texture = cachedSprite.texture; + var canvas = cachedSprite.buffer.canvas; + + texture.baseTexture.width = canvas.width; + texture.baseTexture.height = canvas.height; + texture.crop.width = texture.frame.width = canvas.width; + texture.crop.height = texture.frame.height = canvas.height; + + cachedSprite._width = canvas.width; + cachedSprite._height = canvas.height; + + // update the dirty base textures + texture.baseTexture.dirty(); + +}; + +/** + * Destroys a previous cached sprite. + * + * @method Phaser.Graphics#destroyCachedSprite + */ +Phaser.Graphics.prototype.destroyCachedSprite = function () { + + this._cachedSprite.texture.destroy(true); + this._cachedSprite = null; + +}; + +/** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @method Phaser.Graphics#drawShape + * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. + * @return {GraphicsData} The generated GraphicsData object. + */ +Phaser.Graphics.prototype.drawShape = function (shape) { + + if (this.currentPath) + { + // check current path! + if (this.currentPath.shape.points.length <= 2) + { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + // Handle mixed-type polygons + if (shape instanceof Phaser.Polygon) + { + shape = shape.clone(); + shape.flatten(); + } + + var data = new Phaser.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === Phaser.POLYGON) + { + data.shape.closed = this.filling; + this.currentPath = data; + } + + this.dirty = true; + this._boundsDirty = true; + + return data; + +}; + +/** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory. + * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas. + * This is not recommended if you are constantly redrawing the graphics element. + * + * @property cacheAsBitmap + * @type Boolean + * @default false + * @private + */ +Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + this._cacheAsBitmap = value; + + if (this._cacheAsBitmap) + { + this._generateCachedSprite(); + } + else + { + this.destroyCachedSprite(); + } + + this.dirty = true; + this.webGLDirty = true; + + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and +* render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. +* +* @class Phaser.RenderTexture +* @constructor +* @extends PIXI.Texture +* @param {Phaser.Game} game - Current game instance. +* @param {number} [width=100] - The width of the render texture. +* @param {number} [height=100] - The height of the render texture. +* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there. +* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts. +* @param {number} [resolution=1] - The resolution of the texture being generated. +*/ +Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution, renderer, textureUnit) { + + if (width === undefined) { width = 100; } + if (height === undefined) { height = 100; } + if (key === undefined) { key = ''; } + if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; } + if (resolution === undefined) { resolution = 1; } + if (renderer === undefined) { renderer = PIXI.defaultRenderer; } + if (textureUnit === undefined) { textureUnit = 0; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the RenderTexture in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RENDERTEXTURE; + + /** + * @property {Phaser.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture. + * @private + */ + this._tempMatrix = new Phaser.Matrix(); + + this.width = width; + this.height = height; + this.resolution = resolution; + + this.frame = new Phaser.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); + + this.crop = this.frame.clone(); + + /** + * The base texture object that this texture uses + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = new PIXI.BaseTexture(); + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + this.baseTexture._glTextures = []; + this.baseTexture.resolution = this.resolution; + + this.baseTexture.scaleMode = scaleMode; + + this.baseTexture.hasLoaded = true; + + PIXI.Texture.call(this, this.baseTexture, this.frame.clone()); + + /** + * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. + * + * @property renderer + * @type CanvasRenderer|WebGLRenderer + */ + this.renderer = renderer; + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + this.baseTexture.textureIndex = textureUnit; + this.baseTexture._dirty[gl.id] = false; + + this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode, textureUnit); + this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; + + this.projection = new Phaser.Point(this.width * 0.5, -this.height * 0.5); + } + else + { + this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution); + this.baseTexture.source = this.textureBuffer.canvas; + } + + /** + * @property valid + * @type Boolean + */ + this.valid = true; + + this.tempMatrix = new Phaser.Matrix(); + + this._updateUvs(); + +}; + +Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype); +Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it takes into account scale and rotation. +* +* If you don't want those then use RenderTexture.renderRawXY instead. +* +* @method Phaser.RenderTexture.prototype.renderXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) { + + displayObject.updateTransform(); + + this._tempMatrix.copyFrom(displayObject.worldTransform); + this._tempMatrix.tx = x; + this._tempMatrix.ty = y; + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it doesn't take into account scale, rotation or translation. +* +* If you need those then use RenderTexture.renderXY instead. +* +* @method Phaser.RenderTexture.prototype.renderRawXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) { + + this._tempMatrix.identity().translate(x, y); + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture. +* +* In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. +* This is now a Matrix allowing you much more control over how the Display Object is rendered. +* If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. +* +* If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either +* pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. +* +* @method Phaser.RenderTexture.prototype.render +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) { + + if (matrix === undefined || matrix === null) + { + this._tempMatrix.copyFrom(displayObject.worldTransform); + } + else + { + this._tempMatrix.copyFrom(matrix); + } + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* Resizes the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.resize +* @param {number} width - The width to resize to. +* @param {number} height - The height to resize to. +* @param {boolean} updateBase - Should the baseTexture.width and height values be resized as well? +*/ +Phaser.RenderTexture.prototype.resize = function (width, height, updateBase) { + + if (width === this.width && height === this.height) + { + return; + } + + this.valid = (width > 0 && height > 0); + + this.width = width; + this.height = height; + this.frame.width = this.crop.width = width * this.resolution; + this.frame.height = this.crop.height = height * this.resolution; + + if (updateBase) + { + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.projection.x = this.width / 2; + this.projection.y = -this.height / 2; + } + + if (!this.valid) + { + return; + } + + this.textureBuffer.resize(this.width, this.height); + +}; + +/** +* Clears the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.clear +*/ +Phaser.RenderTexture.prototype.clear = function () { + + if (!this.valid) + { + return; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + } + + this.textureBuffer.clear(); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderWebGL +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +* @private +*/ +Phaser.RenderTexture.prototype._renderWebGL = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + wt.translate(0, this.projection.y * 2); + + if (matrix) + { + wt.append(matrix); + } + + wt.scale(1, -1); + + // Time to update all the children of the displayObject with the new matrix. + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + // Time for the webGL fun stuff! + var gl = this.renderer.gl; + + gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + + if (clear) + { + this.textureBuffer.clear(); + } + + this.renderer.spriteBatch.dirty = true; + + this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix); + + this.renderer.spriteBatch.dirty = true; + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderCanvas +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +*/ +Phaser.RenderTexture.prototype._renderCanvas = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + + if (matrix) + { + wt.append(matrix); + } + + // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!) + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + if (clear) + { + this.textureBuffer.clear(); + } + + var realResolution = this.renderer.resolution; + + this.renderer.resolution = this.resolution; + + this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix); + + this.renderer.resolution = realResolution; + +}; + +/** +* Will return a HTML Image of the texture +* +* @method Phaser.RenderTexture.prototype.getImage +* @return {Image} +*/ +Phaser.RenderTexture.prototype.getImage = function () { + + var image = new Image(); + image.src = this.getBase64(); + + return image; + +}; + +/** +* Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. +* +* @method Phaser.RenderTexture.prototype.getBase64 +* @return {String} A base64 encoded string of the texture. +*/ +Phaser.RenderTexture.prototype.getBase64 = function () { + + return this.getCanvas().toDataURL(); + +}; + +/** +* Creates a Canvas element, renders this RenderTexture to it and then returns it. +* +* @method Phaser.RenderTexture.prototype.getCanvas +* @return {HTMLCanvasElement} A Canvas element with the texture rendered on. +*/ +Phaser.RenderTexture.prototype.getCanvas = function () { + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + var width = this.textureBuffer.width; + var height = this.textureBuffer.height; + + var webGLPixels = new Uint8Array(4 * width * height); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + var tempCanvas = new PIXI.CanvasBuffer(width, height); + var canvasData = tempCanvas.context.getImageData(0, 0, width, height); + canvasData.data.set(webGLPixels); + + tempCanvas.context.putImageData(canvasData, 0, 0); + + return tempCanvas.canvas; + } + else + { + return this.textureBuffer.canvas; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new game object for displaying Text. +* +* This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. +* Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. +* +* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers. +* +* @class Phaser.Text +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {number} x - X position of the new text object. +* @param {number} y - Y position of the new text object. +* @param {string} text - The actual text that will be written. +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +*/ +Phaser.Text = function (game, x, y, text, style) { + + x = x || 0; + y = y || 0; + + if (text === undefined || text === null) + { + text = ''; + } + else + { + text = text.toString(); + } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.TEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. + * @property {Phaser.Point} padding + */ + this.padding = new Phaser.Point(); + + /** + * The textBounds property allows you to specify a rectangular region upon which text alignment is based. + * See `Text.setTextBounds` for more details. + * @property {Phaser.Rectangle} textBounds + * @readOnly + */ + this.textBounds = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. + */ + this.canvas = Phaser.CanvasPool.create(this); + + /** + * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. + */ + this.context = this.canvas.getContext('2d'); + + /** + * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}. + */ + this.colors = []; + + /** + * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}. + */ + this.strokeColors = []; + + /** + * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}. + */ + this.fontStyles = []; + + /** + * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}. + */ + this.fontWeights = []; + + /** + * Should the linePositionX and Y values be automatically rounded before rendering the Text? + * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. + * @property {boolean} autoRound + * @default + */ + this.autoRound = false; + + /** + * Will this Text object use Basic or Advanced Word Wrapping? + * + * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. + * White space is condensed (e.g., consecutive spaces are replaced with one). + * Lines are trimmed of white space before processing. + * + * It throws an error if wordWrapWidth is less than a single character. + * @property {boolean} useAdvancedWrap + * @default + */ + this.useAdvancedWrap = false; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + * @property {Object} splitRegExp + */ + this.splitRegExp = /(?:\r\n|\r|\n)/; + + + /** The maximum number of characters that can be set. + * @property {number} characterLimitSize + */ + this.characterLimitSize = -1; + + /** The suffix that is applied to truncated text that is longer than the + * characterLimitSize. + * @property {string} characterLimitSuffix + */ + this.characterLimitSuffix = ''; + + /** + * @property {number} _res - Internal canvas resolution var. + * @private + */ + this._res = game.renderer.resolution; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text; + + /** + * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`. + * @private + */ + this._fontComponents = null; + + /** + * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. + * @private + */ + this._lineSpacing = 0; + + /** + * @property {number} _charCount - Internal character counter used by the text coloring. + * @private + */ + this._charCount = 0; + + /** + * @property {number} _width - Internal width var. + * @private + */ + this._width = 0; + + /** + * @property {number} _height - Internal height var. + * @private + */ + this._height = 0; + + Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas)); + + /** + * @property {object} style + * @private + */ + this.style = {}; + + this.setStyle(style || {}); + + if (text !== '') + { + this.updateText(); + } + +}; + +Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Text.prototype.constructor = Phaser.Text; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Text#preUpdate +* @protected +*/ +Phaser.Text.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override this function to handle any special update requirements. +* +* @method Phaser.Text#update +* @protected +*/ +Phaser.Text.prototype.update = function() { + +}; + +/** +* Destroy this Text object, removing it from the group it belongs to. +* +* @method Phaser.Text#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Text.prototype.destroy = function (destroyChildren) { + + this.texture.destroy(true); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. +* The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. +* The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. +* To remove a shadow already in place you can call this method with no parameters set. +* +* @method Phaser.Text#setShadow +* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +* @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. +* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +* @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set). +* @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; } + if (blur === undefined) { blur = 0; } + if (shadowStroke === undefined) { shadowStroke = true; } + if (shadowFill === undefined) { shadowFill = true; } + + this.style.shadowOffsetX = x; + this.style.shadowOffsetY = y; + this.style.shadowColor = color; + this.style.shadowBlur = blur; + this.style.shadowStroke = shadowStroke; + this.style.shadowFill = shadowFill; + this.dirty = true; + + return this; + +}; + +/** +* Set the style of the text by passing a single style object to it. +* +* @method Phaser.Text#setStyle +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +* @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setStyle = function (style, update) { + + if (update === undefined) { update = false; } + + var newStyle = Object.assign({}, style); + newStyle.font = style.font || 'bold 20pt Arial'; + newStyle.backgroundColor = style.backgroundColor || null; + newStyle.fill = style.fill || 'black'; + newStyle.align = (style.align || 'left').toLowerCase(); + newStyle.boundsAlignH = (style.boundsAlignH || 'left').toLowerCase(); + newStyle.boundsAlignV = (style.boundsAlignV || 'top').toLowerCase(); + newStyle.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136 + newStyle.strokeThickness = Number(style.strokeThickness) || 0; + newStyle.wordWrap = style.wordWrap || false; + newStyle.wordWrapWidth = style.wordWrapWidth || 100; + newStyle.maxLines = style.maxLines || 0; + newStyle.shadowOffsetX = style.shadowOffsetX || 0; + newStyle.shadowOffsetY = style.shadowOffsetY || 0; + newStyle.shadowColor = style.shadowColor || 'rgba(0,0,0,0)'; + newStyle.shadowBlur = style.shadowBlur || 0; + newStyle.tabs = style.tabs || 0; + + var components = this.fontToComponents(newStyle.font); + + if (newStyle.fontStyle) + { + components.fontStyle = newStyle.fontStyle; + } + + if (newStyle.fontVariant) + { + components.fontVariant = newStyle.fontVariant; + } + + if (newStyle.fontWeight) + { + components.fontWeight = newStyle.fontWeight; + } + + if (newStyle.fontSize) + { + if (typeof newStyle.fontSize === 'number') + { + newStyle.fontSize = newStyle.fontSize + 'px'; + } + + components.fontSize = newStyle.fontSize; + } + + this._fontComponents = components; + + newStyle.font = this.componentsToFont(this._fontComponents); + + this.style = newStyle; + this.dirty = true; + + if (update) + { + this.updateText(); + } + + return this; + +}; + +/** +* Renders text to the internal canvas. +* +* @method Phaser.Text#updateText +* @private +*/ +Phaser.Text.prototype.updateText = function () { + + this.texture.baseTexture.resolution = this._res; + + this.context.font = this.style.font; + + var outputText = this.text; + + if (this.characterLimitSize > -1 && this.characterLimitSize < outputText.length) { + outputText = this.text.substring(0, this.characterLimitSize) + this.characterLimitSuffix; + } + + if (this.style.wordWrap) + { + outputText = this.runWordWrap(this.text); + } + + // Split text into lines + var lines = outputText.split(this.splitRegExp); + + // Calculate text width + var tabs = this.style.tabs; + var lineWidths = []; + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this.style.font); + + var drawnLines = lines.length; + + if (this.style.maxLines > 0 && this.style.maxLines < lines.length) + { + drawnLines = this.style.maxLines; + } + + this._charCount = 0; + + for (var i = 0; i < drawnLines; i++) + { + if (tabs === 0) + { + // Simple layout (no tabs) + var lineWidth = this.style.strokeThickness + this.padding.x; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(lines[i]); + } + else + { + lineWidth += this.context.measureText(lines[i]).width; + } + + // Adjust for wrapped text + if (this.style.wordWrap) + { + lineWidth -= this.context.measureText(' ').width; + } + } + else + { + // Complex layout (tabs) + var line = lines[i].split(/(?:\t)/); + var lineWidth = this.padding.x + this.style.strokeThickness; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < line.length; c++) + { + var section = 0; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + section = this.measureLine(line[c]); + } + else + { + section = Math.ceil(this.context.measureText(line[c]).width); + } + + if (c > 0) + { + tab += tabs[c - 1]; + } + + lineWidth = tab + section; + } + } + else + { + for (var c = 0; c < line.length; c++) + { + // How far to the next tab? + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(line[c]); + } + else + { + lineWidth += Math.ceil(this.context.measureText(line[c]).width); + } + + var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth; + + lineWidth += diff; + } + } + } + + lineWidths[i] = Math.ceil(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); + } + + this.canvas.width = maxLineWidth * this._res; + + // Calculate text height + var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y; + var height = lineHeight * drawnLines; + var lineSpacing = this._lineSpacing; + + if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight) + { + lineSpacing = -lineHeight; + } + + // Adjust for line spacing + if (lineSpacing !== 0) + { + height += (lineSpacing > 0) ? lineSpacing * lines.length : lineSpacing * (lines.length - 1); + } + + this.canvas.height = height * this._res; + + this.context.scale(this._res, this._res); + + if (navigator.isCocoonJS) + { + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + } + + if (this.style.backgroundColor) + { + this.context.fillStyle = this.style.backgroundColor; + this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); + } + + this.context.fillStyle = this.style.fill; + this.context.font = this.style.font; + this.context.strokeStyle = this.style.stroke; + this.context.textBaseline = 'alphabetic'; + + this.context.lineWidth = this.style.strokeThickness; + this.context.lineCap = 'round'; + this.context.lineJoin = 'round'; + + var linePositionX; + var linePositionY; + + this._charCount = 0; + + // Draw text line by line + for (i = 0; i < drawnLines; i++) + { + // Split the line by + + linePositionX = this.style.strokeThickness / 2; + linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (i > 0) + { + linePositionY += (lineSpacing * i); + } + + if (this.style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (this.style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (this.autoRound) + { + linePositionX = Math.round(linePositionX); + linePositionY = Math.round(linePositionY); + } + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + this.updateLine(lines[i], linePositionX, linePositionY); + } + else + { + if (this.style.stroke && this.style.strokeThickness) + { + this.updateShadow(this.style.shadowStroke); + + if (tabs === 0) + { + this.context.strokeText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, false); + } + } + + if (this.style.fill) + { + this.updateShadow(this.style.shadowFill); + + if (tabs === 0) + { + this.context.fillText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, true); + } + } + } + } + + this.updateTexture(); + + this.dirty = false; + +}; + +/** +* Renders a line of text that contains tab characters if Text.tab > 0. +* Called automatically by updateText. +* +* @method Phaser.Text#renderTabLine +* @private +* @param {string} line - The line of text to render. +* @param {integer} x - The x position to start rendering from. +* @param {integer} y - The y position to start rendering from. +* @param {boolean} fill - If true uses fillText, if false uses strokeText. +*/ +Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) { + + var text = line.split(/(?:\t)/); + var tabs = this.style.tabs; + var snap = 0; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < text.length; c++) + { + if (c > 0) + { + tab += tabs[c - 1]; + } + + snap = x + tab; + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + } + } + else + { + for (var c = 0; c < text.length; c++) + { + var section = Math.ceil(this.context.measureText(text[c]).width); + + // How far to the next tab? + snap = this.game.math.snapToCeil(x, tabs); + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + + x = snap + section; + } + } + +}; + +/** +* Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. +* This is called automatically by Text.updateText. +* +* @method Phaser.Text#updateShadow +* @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero. +*/ +Phaser.Text.prototype.updateShadow = function (state) { + + if (state) + { + this.context.shadowOffsetX = this.style.shadowOffsetX; + this.context.shadowOffsetY = this.style.shadowOffsetY; + this.context.shadowColor = this.style.shadowColor; + this.context.shadowBlur = this.style.shadowBlur; + } + else + { + this.context.shadowOffsetX = 0; + this.context.shadowOffsetY = 0; + this.context.shadowColor = 0; + this.context.shadowBlur = 0; + } + +}; + +/** +* Measures a line of text character by character taking into the account the specified character styles. +* +* @method Phaser.Text#measureLine +* @private +* @param {string} line - The line of text to measure. +* @return {integer} length of the line. +*/ +Phaser.Text.prototype.measureLine = function (line) { + + var lineLength = 0; + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + } + + lineLength += this.context.measureText(letter).width; + + this._charCount++; + } + + return Math.ceil(lineLength); +}; + +/** +* Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable. +* +* @method Phaser.Text#updateLine +* @private +*/ +Phaser.Text.prototype.updateLine = function (line, x, y) { + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + this.context.strokeText(letter, x, y); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + this.context.fillText(letter, x, y); + } + + x += this.context.measureText(letter).width; + + this._charCount++; + } + +}; + +/** +* Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. +* +* @method Phaser.Text#clearColors +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearColors = function () { + + this.colors = []; + this.strokeColors = []; + this.dirty = true; + + return this; + +}; + +/** +* Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. +* +* @method Phaser.Text#clearFontValues +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearFontValues = function () { + + this.fontStyles = []; + this.fontWeights = []; + this.dirty = true; + + return this; + +}; + +/** +* Set specific colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* If you wish to change the stroke color see addStrokeColor instead. +* +* @method Phaser.Text#addColor +* @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addColor = function (color, position) { + + this.colors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific stroke colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* This has no effect if stroke is disabled or has a thickness of 0. +* +* If you wish to change the text fill color see addColor instead. +* +* @method Phaser.Text#addStrokeColor +* @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addStrokeColor = function (color, position) { + + this.strokeColors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font styles for certain characters within the Text. +* +* It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. +* The position value is the index of the character in the Text string to start applying this font style to. +* Once set the font style remains in use until either another font style or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. +* +* If you wish to change the text font weight see addFontWeight instead. +* +* @method Phaser.Text#addFontStyle +* @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. +* @param {number} position - The index of the character in the string to start applying this font style value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontStyle = function (style, position) { + + this.fontStyles[position] = style; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font weights for certain characters within the Text. +* +* It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. +* The position value is the index of the character in the Text string to start applying this font weight to. +* Once set the font weight remains in use until either another font weight or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. +* +* If you wish to change the text font style see addFontStyle instead. +* +* @method Phaser.Text#addFontWeight +* @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. +* @param {number} position - The index of the character in the string to start applying this font weight value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontWeight = function (weight, position) { + + this.fontWeights[position] = weight; + this.dirty = true; + + return this; + +}; + +/** +* Runs the given text through the Text.runWordWrap function and returns +* the results as an array, where each element of the array corresponds to a wrapped +* line of text. +* +* Useful if you wish to control pagination on long pieces of content. +* +* @method Phaser.Text#precalculateWordWrap +* @param {string} text - The text for which the wrapping will be calculated. +* @return {array} An array of strings with the pieces of wrapped text. +*/ +Phaser.Text.prototype.precalculateWordWrap = function (text) { + + this.texture.baseTexture.resolution = this._res; + this.context.font = this.style.font; + + var wrappedLines = this.runWordWrap(text); + + return wrappedLines.split(/(?:\r\n|\r|\n)/); + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#runWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.runWordWrap = function (text) { + + if (this.useAdvancedWrap) + { + return this.advancedWordWrap(text); + } + else + { + return this.basicWordWrap(text); + } + +}; + +/** +* Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* White space is condensed (e.g., consecutive spaces are replaced with one). +* Lines are trimmed of white space before processing. +* Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character. +* +* @method Phaser.Text#advancedWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.advancedWordWrap = function (text) { + + var context = this.context; + var wordWrapWidth = this.style.wordWrapWidth; + + var output = ''; + + // (1) condense whitespace + // (2) split into lines + var lines = text + .replace(/ +/gi, ' ') + .split(/\r?\n/gi); + + var linesCount = lines.length; + + for (var i = 0; i < linesCount; i++) + { + var line = lines[i]; + var out = ''; + + // trim whitespace + line = line.replace(/^ *|\s*$/gi, ''); + + // if entire line is less than wordWrapWidth + // append the entire line and exit early + var lineWidth = context.measureText(line).width; + + if (lineWidth < wordWrapWidth) + { + output += line + '\n'; + continue; + } + + // otherwise, calculate new lines + var currentLineWidth = wordWrapWidth; + + // split into words + var words = line.split(' '); + + for (var j = 0; j < words.length; j++) + { + var word = words[j]; + var wordWithSpace = word + ' '; + var wordWidth = context.measureText(wordWithSpace).width; + + if (wordWidth > currentLineWidth) + { + // break word + if (j === 0) + { + // shave off letters from word until it's small enough + var newWord = wordWithSpace; + + while (newWord.length) + { + newWord = newWord.slice(0, -1); + wordWidth = context.measureText(newWord).width; + + if (wordWidth <= currentLineWidth) + { + break; + } + } + + // if wordWrapWidth is too small for even a single + // letter, shame user failure with a fatal error + if (!newWord.length) + { + throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); + } + + // replace current word in array with remainder + var secondPart = word.substr(newWord.length); + + words[j] = secondPart; + + // append first piece to output + out += newWord; + } + + // if existing word length is 0, don't include it + var offset = (words[j].length) ? j : j + 1; + + // collapse rest of sentence + var remainder = words.slice(offset).join(' ') + // remove any trailing white space + .replace(/[ \n]*$/gi, ''); + + // prepend remainder to next line + lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); + linesCount = lines.length; + + break; // processing on this line + + // append word with space to output + } + else + { + out += wordWithSpace; + currentLineWidth -= wordWidth; + } + } + + // append processed line to output + output += out.replace(/[ \n]*$/gi, '') + '\n'; + } + + // trim the end of the string + output = output.replace(/[\s|\n]*$/gi, ''); + + return output; + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#basicWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.basicWordWrap = function (text) { + + var result = ''; + var lines = text.split('\n'); + + for (var i = 0; i < lines.length; i++) + { + var spaceLeft = this.style.wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) + { + var wordWidth = this.context.measureText(words[j]).width; + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is greater than the word wrap width. + if (j > 0) + { + result += '\n'; + } + result += words[j] + ' '; + spaceLeft = this.style.wordWrapWidth - wordWidth; + } + else + { + spaceLeft -= wordWidthWithSpace; + result += words[j] + ' '; + } + } + + if (i < lines.length-1) + { + result += '\n'; + } + } + + return result; + +}; + +/** +* Updates the internal `style.font` if it now differs according to generation from components. +* +* @method Phaser.Text#updateFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.updateFont = function (components) { + + var font = this.componentsToFont(components); + + if (this.style.font !== font) + { + this.style.font = font; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + +}; + +/** +* Converting a short CSS-font string into the relevant components. +* +* @method Phaser.Text#fontToComponents +* @private +* @param {string} font - a CSS font string +*/ +Phaser.Text.prototype.fontToComponents = function (font) { + + // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand: + // style - normal | italic | oblique | inherit + // variant - normal | small-caps | inherit + // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit + // size - xx-small | x-small | small | medium | large | x-large | xx-large, + // larger | smaller + // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %) + // font-family - rest (but identifiers or quoted with comma separation) + var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/); + + if (m) + { + var family = m[5].trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(family) && !/['",]/.exec(family)) + { + family = "'" + family + "'"; + } + + return { + font: font, + fontStyle: m[1] || 'normal', + fontVariant: m[2] || 'normal', + fontWeight: m[3] || 'normal', + fontSize: m[4] || 'medium', + fontFamily: family + }; + } + else + { + console.warn("Phaser.Text - unparsable CSS font: " + font); + + return { + font: font + }; + } + +}; + +/** +* Converts individual font components (see `fontToComponents`) to a short CSS font string. +* +* @method Phaser.Text#componentsToFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.componentsToFont = function (components) { + + var parts = []; + var v; + + v = components.fontStyle; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontVariant; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontWeight; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontSize; + if (v && v !== 'medium') { parts.push(v); } + + v = components.fontFamily; + if (v) { parts.push(v); } + + if (!parts.length) + { + // Fallback to whatever value the 'font' was + parts.push(components.font); + } + + return parts.join(" "); + +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* Use the optional `immediate` argument if you need the Text display to update immediately. +* +* If not it will re-create the texture of this Text object during the next time the render +* loop is called. +* +* @method Phaser.Text#setText +* @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present. +* @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setText = function (text, immediate) { + + if (immediate === undefined) { immediate = false; } + + this.text = text.toString() || ''; + + if (immediate) + { + this.updateText(); + } + else + { + this.dirty = true; + } + + return this; + +}; + +/** + * Converts the given array into a tab delimited string and then updates this Text object. + * This is mostly used when you want to display external data using tab stops. + * + * The array can be either single or multi dimensional depending on the result you need: + * + * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`. + * + * Where as: + * + * `[ + * [ 'a', 'b', 'c' ], + * [ 'd', 'e', 'f'] + * ]` + * + * would convert in to: `"a\tb\tc\nd\te\tf"` + * + * @method Phaser.Text#parseList + * @param {array} list - The array of data to convert into a string. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.parseList = function (list) { + + if (!Array.isArray(list)) + { + return this; + } + else + { + var s = ""; + + for (var i = 0; i < list.length; i++) + { + if (Array.isArray(list[i])) + { + s += list[i].join("\t"); + + if (i < list.length - 1) + { + s += "\n"; + } + } + else + { + s += list[i]; + + if (i < list.length - 1) + { + s += "\t"; + } + } + } + } + + this.text = s; + this.dirty = true; + + return this; + +}; + +/** + * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned, + * regardless of the number of lines in the text, the font size or any other attribute. + * + * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly + * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment. + * + * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to + * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of + * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center + * of the text bounds. + * + * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions + * may vary based on font (say for multi-lingual games). + * + * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width. + * + * Call this method with no arguments given to reset an existing textBounds. + * + * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts + * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot` + * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then + * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot. + * + * @method Phaser.Text#setTextBounds + * @param {number} [x] - The x coordinate of the Text Bounds region. + * @param {number} [y] - The y coordinate of the Text Bounds region. + * @param {number} [width] - The width of the Text Bounds region. + * @param {number} [height] - The height of the Text Bounds region. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.setTextBounds = function (x, y, width, height) { + + if (x === undefined) + { + this.textBounds = null; + } + else + { + if (!this.textBounds) + { + this.textBounds = new Phaser.Rectangle(x, y, width, height); + } + else + { + this.textBounds.setTo(x, y, width, height); + } + + if (this.style.wordWrapWidth > width) + { + this.style.wordWrapWidth = width; + } + } + + this.updateTexture(); + + return this; + +}; + +/** + * Updates the texture based on the canvas dimensions. + * + * @method Phaser.Text#updateTexture + * @private + */ +Phaser.Text.prototype.updateTexture = function () { + + var base = this.texture.baseTexture; + var crop = this.texture.crop; + var frame = this.texture.frame; + + var w = this.canvas.width; + var h = this.canvas.height; + + base.width = w; + base.height = h; + + crop.width = w; + crop.height = h; + + frame.width = w; + frame.height = h; + + this.texture.width = w; + this.texture.height = h; + + this._width = w; + this._height = h; + + if (this.textBounds) + { + var x = this.textBounds.x; + var y = this.textBounds.y; + + // Align the canvas based on the bounds + if (this.style.boundsAlignH === 'right') + { + x += this.textBounds.width - this.canvas.width / this.resolution; + } + else if (this.style.boundsAlignH === 'center') + { + x += this.textBounds.halfWidth - (this.canvas.width / this.resolution / 2); + } + + if (this.style.boundsAlignV === 'bottom') + { + y += this.textBounds.height - this.canvas.height / this.resolution; + } + else if (this.style.boundsAlignV === 'middle') + { + y += this.textBounds.halfHeight - (this.canvas.height / this.resolution / 2); + } + + this.pivot.x = -x; + this.pivot.y = -y; + } + + // Can't render something with a zero sized dimension + this.renderable = (w !== 0 && h !== 0); + + this.texture.requiresReTint = true; + + this.texture.baseTexture.dirty(); + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Text#_renderWebGL +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderWebGL = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Renders the object using the Canvas renderer. +* +* @method Phaser.Text#_renderCanvas +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderCanvas = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Calculates the ascent, descent and fontSize of a given font style. +* +* @method Phaser.Text#determineFontProperties +* @private +* @param {object} fontStyle +*/ +Phaser.Text.prototype.determineFontProperties = function (fontStyle) { + + var properties = Phaser.Text.fontPropertiesCache[fontStyle]; + + if (!properties) + { + properties = {}; + + var canvas = Phaser.Text.fontPropertiesCanvas; + var context = Phaser.Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('|MÉq').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + if (!context.getImageData(0, 0, width, height)) + { + properties.ascent = baseline; + properties.descent = baseline + 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + } + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i, j; + + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + properties.descent = i - baseline; + //TODO might need a tweak. kind of a temp fix! + properties.descent += 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; + +}; + +/** +* Returns the bounds of the Text as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Text#getBounds +* @param {Phaser.Matrix} matrix - The transformation matrix of the Text. +* @return {Phaser.Rectangle} The framing rectangle +*/ +Phaser.Text.prototype.getBounds = function (matrix) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return PIXI.Sprite.prototype.getBounds.call(this, matrix); + +}; + +/** +* Sets the character limit of the text, with a suffix. +* If the text is longer than this limit, it is truncated and the suffix is appended. +* +* @method Phaser.Text#setCharacterLimit +* @param {number} [characterLimit] - The x coordinate of the Text Bounds region. +* @param {string} [suffix] - The suffix to append to the truncated text. +*/ +Phaser.Text.prototype.setCharacterLimit = function (characterLimit, suffix) { + + this.characterLimitSuffix = (suffix === undefined) ? '' : suffix; + this.characterLimitSize = characterLimit; + + this.updateText(); +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* @name Phaser.Text#text +* @property {string} text +*/ +Object.defineProperty(Phaser.Text.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* Change the font used. +* +* This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except +* that unlike using `setStyle` this will not change any current font fill/color settings. +* +* The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. +* +* @name Phaser.Text#cssFont +* @property {string} cssFont +*/ +Object.defineProperty(Phaser.Text.prototype, 'cssFont', { + + get: function() { + return this.componentsToFont(this._fontComponents); + }, + + set: function (value) + { + value = value || 'bold 20pt Arial'; + this._fontComponents = this.fontToComponents(value); + this.updateFont(this._fontComponents); + } + +}); + +/** +* Change the font family that the text will be rendered in, such as 'Arial'. +* +* Multiple CSS font families and generic fallbacks can be specified as long as +* {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed. +* +* To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`. +* +* @name Phaser.Text#font +* @property {string} font +*/ +Object.defineProperty(Phaser.Text.prototype, 'font', { + + get: function() { + return this._fontComponents.fontFamily; + }, + + set: function(value) { + + value = value || 'Arial'; + value = value.trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value)) + { + value = "'" + value + "'"; + } + + this._fontComponents.fontFamily = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The size of the font. +* +* If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing +* the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). +* +* @name Phaser.Text#fontSize +* @property {number|string} fontSize +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontSize', { + + get: function() { + + var size = this._fontComponents.fontSize; + + if (size && /(?:^0$|px$)/.exec(size)) + { + return parseInt(size, 10); + } + else + { + return size; + } + + }, + + set: function(value) { + + value = value || '0'; + + if (typeof value === 'number') + { + value = value + 'px'; + } + + this._fontComponents.fontSize = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}. +* @name Phaser.Text#fontWeight +* @property {string} fontWeight +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontWeight', { + + get: function() { + return this._fontComponents.fontWeight || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontWeight = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The style of the font: 'normal', 'italic', 'oblique' +* @name Phaser.Text#fontStyle +* @property {string} fontStyle +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontStyle', { + + get: function() { + return this._fontComponents.fontStyle || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontStyle = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The variant the font: 'normal', 'small-caps' +* @name Phaser.Text#fontVariant +* @property {string} fontVariant +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontVariant', { + + get: function() { + return this._fontComponents.fontVariant || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontVariant = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* @name Phaser.Text#fill +* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'fill', { + + get: function() { + return this.style.fill; + }, + + set: function(value) { + + if (value !== this.style.fill) + { + this.style.fill = value; + this.dirty = true; + } + + } + +}); + +/** +* Controls the horizontal alignment for multiline text. +* Can be: 'left', 'center' or 'right'. +* Does not affect single lines of text. For that please see `setTextBounds`. +* @name Phaser.Text#align +* @property {string} align +*/ +Object.defineProperty(Phaser.Text.prototype, 'align', { + + get: function() { + return this.style.align; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.align) + { + this.style.align = value; + this.dirty = true; + } + + } + +}); + +/** +* The resolution of the canvas the text is rendered to. +* This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. +* @name Phaser.Text#resolution +* @property {integer} resolution +*/ +Object.defineProperty(Phaser.Text.prototype, 'resolution', { + + get: function() { + return this._res; + }, + + set: function(value) { + + if (value !== this._res) + { + this._res = value; + this.dirty = true; + } + + } + +}); + +/** +* The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. +* Can be an integer or an array of varying tab sizes, one tab per element. +* For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. +* If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. +* +* @name Phaser.Text#tabs +* @property {integer|array} tabs +*/ +Object.defineProperty(Phaser.Text.prototype, 'tabs', { + + get: function() { + return this.style.tabs; + }, + + set: function(value) { + + if (value !== this.style.tabs) + { + this.style.tabs = value; + this.dirty = true; + } + + } + +}); + +/** +* Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @name Phaser.Text#boundsAlignH +* @property {string} boundsAlignH +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', { + + get: function() { + return this.style.boundsAlignH; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignH) + { + this.style.boundsAlignH = value; + this.dirty = true; + } + + } + +}); + +/** +* Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @name Phaser.Text#boundsAlignV +* @property {string} boundsAlignV +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', { + + get: function() { + return this.style.boundsAlignV; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignV) + { + this.style.boundsAlignV = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#stroke +* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'stroke', { + + get: function() { + return this.style.stroke; + }, + + set: function(value) { + + if (value !== this.style.stroke) + { + this.style.stroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#strokeThickness +* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke) +*/ +Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', { + + get: function() { + return this.style.strokeThickness; + }, + + set: function(value) { + + if (value !== this.style.strokeThickness) + { + this.style.strokeThickness = Number(value); + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrap +* @property {boolean} wordWrap - Indicates if word wrap should be used. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrap', { + + get: function() { + return this.style.wordWrap; + }, + + set: function(value) { + + if (value !== this.style.wordWrap) + { + this.style.wordWrap = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrapWidth +* @property {number} wordWrapWidth - The width at which text will wrap. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', { + + get: function() { + return this.style.wordWrapWidth; + }, + + set: function(value) { + + if (value !== this.style.wordWrapWidth) + { + this.style.wordWrapWidth = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#lineSpacing +* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. +*/ +Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { + + get: function() { + return this._lineSpacing; + }, + + set: function(value) { + + if (value !== this._lineSpacing) + { + this._lineSpacing = parseFloat(value); + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetX +* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', { + + get: function() { + return this.style.shadowOffsetX; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetX) + { + this.style.shadowOffsetX = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetY +* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', { + + get: function() { + return this.style.shadowOffsetY; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetY) + { + this.style.shadowOffsetY = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowColor +* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowColor', { + + get: function() { + return this.style.shadowColor; + }, + + set: function(value) { + + if (value !== this.style.shadowColor) + { + this.style.shadowColor = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowBlur +* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', { + + get: function() { + return this.style.shadowBlur; + }, + + set: function(value) { + + if (value !== this.style.shadowBlur) + { + this.style.shadowBlur = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowStroke +* @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', { + + get: function() { + return this.style.shadowStroke; + }, + + set: function(value) { + + if (value !== this.style.shadowStroke) + { + this.style.shadowStroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowFill +* @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowFill', { + + get: function() { + return this.style.shadowFill; + }, + + set: function(value) { + + if (value !== this.style.shadowFill) + { + this.style.shadowFill = value; + this.dirty = true; + } + + } + +}); + +/** +* The width of the Text object in pixels. This is width of the Texture frame / the Text.resolution. +* @name Phaser.Text#width +* @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'width', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.x * (this.texture.frame.width / this.resolution); + }, + + set: function(value) { + + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** +* The height of the Text object in pixels. This is height of the Texture frame / the Text.resolution. +* @name Phaser.Text#height +* @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'height', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.y * (this.texture.frame.height / this.resolution); + }, + + set: function(value) { + + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +Phaser.Text.fontPropertiesCache = {}; + +Phaser.Text.fontPropertiesCanvas = document.createElement('canvas'); +Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d'); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. +* It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to +* match the font structure. +* +* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability +* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by +* processing the font texture in an image editor, applying fills and any other effects required. +* +* To create multi-line text insert \r, \n or \r\n escape codes into the text string. +* +* If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly +* updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. +* +* To create a BitmapText data files you can use: +* +* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ +* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner +* Littera (Web-based, free): http://kvazars.com/littera/ +* +* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of +* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson +* +* If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. +* +* @class Phaser.BitmapText +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - X coordinate to display the BitmapText object at. +* @param {number} y - Y coordinate to display the BitmapText object at. +* @param {string} font - The key of the BitmapText as stored in Phaser.Cache. +* @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. +* @param {number} [size=32] - The size the font will be rendered at in pixels. +* @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. +*/ +Phaser.BitmapText = function (game, x, y, font, text, size, align) { + + x = x || 0; + y = y || 0; + font = font || ''; + text = text || ''; + size = size || 32; + align = align || 'left'; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.BITMAPTEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textWidth = 0; + + /** + * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textHeight = 0; + + /** + * @property {Phaser.Point} anchor - The anchor value of this BitmapText. + */ + this.anchor = new Phaser.Point(); + + /** + * @property {Phaser.Point} _prevAnchor - The previous anchor value. + * @private + */ + this._prevAnchor = new Phaser.Point(); + + /** + * @property {array} _glyphs - Private tracker for the letter sprite pool. + * @private + */ + this._glyphs = []; + + /** + * @property {number} _maxWidth - Internal cache var. + * @private + */ + this._maxWidth = 0; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text.toString() || ''; + + /** + * @property {string} _data - Internal cache var. + * @private + */ + this._data = game.cache.getBitmapFont(font); + + /** + * @property {string} _font - Internal cache var. + * @private + */ + this._font = font; + + /** + * @property {number} _fontSize - Internal cache var. + * @private + */ + this._fontSize = size; + + /** + * @property {string} _align - Internal cache var. + * @private + */ + this._align = align; + + /** + * @property {number} _tint - Internal cache var. + * @private + */ + this._tint = 0xFFFFFF; + + this.updateText(); + + /** + * @property {boolean} dirty - The dirty state of this object. + */ + this.dirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.BitmapText.prototype.constructor = Phaser.BitmapText; + +Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.BitmapText +* @return {boolean} True if the BitmapText was rendered, otherwise false. +*/ +Phaser.BitmapText.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.preUpdate. +* @method Phaser.BitmapText.prototype.postUpdate +*/ +Phaser.BitmapText.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this.body && this.body.type === Phaser.Physics.ARCADE) + { + if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight)) + { + this.body.setSize(this.textWidth, this.textHeight); + } + } + +}; + +/** +* The text to be displayed by this BitmapText object. +* +* It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. +* +* @method Phaser.BitmapText.prototype.setText +* @param {string} text - The text to be displayed by this BitmapText object. +*/ +Phaser.BitmapText.prototype.setText = function (text) { + + this.text = text; + +}; + +/** +* Given the input text this will scan the characters until either a newline is encountered, +* or the line exceeds maxWidth, taking into account kerning, character widths and scaling. +* +* @method Phaser.BitmapText.prototype.scanLine +* @private +* @param {object} data - A reference to the font object in the Phaser.Cache. +* @param {float} scale - The scale of the font in relation to the texture. +* @param {string} text - The text to parse. +* @return {object} An object containing the parsed characters, total pixel width and x offsets. +*/ +Phaser.BitmapText.prototype.scanLine = function (data, scale, text) { + + var x = 0; + var w = 0; + var lastSpace = -1; + var wrappedWidth = 0; + var prevCharCode = null; + var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null; + var chars = []; + + // Let's scan the text and work out if any of the lines are > maxWidth + for (var i = 0; i < text.length; i++) + { + var end = (i === text.length - 1) ? true : false; + + if (/(?:\r\n|\r|\n)/.test(text.charAt(i))) + { + return { width: w, text: text.substr(0, i), end: end, chars: chars }; + } + else + { + var charCode = text.charCodeAt(i); + var charData = data.chars[charCode]; + + var c = 0; + + // If the character data isn't found in the data array + // then we replace it with a blank space + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + // Adjust for kerning from previous character to this one + var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0; + + // Record the last space in the string and the current width + if (/(\s)/.test(text.charAt(i))) + { + lastSpace = i; + wrappedWidth = w; + } + + // What will the line width be if we add this character to it? + c = (kerning + charData.texture.width + charData.xOffset) * scale; + + // Do we need to line-wrap? + if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1) + { + // The last space was at "lastSpace" which was "i - lastSpace" characters ago + return { width: wrappedWidth || w, text: text.substr(0, i - (i - lastSpace)), end: false, chars: chars }; + } + else + { + w += (charData.xAdvance + kerning) * scale; + + chars.push(x + (charData.xOffset + kerning) * scale); + + x += (charData.xAdvance + kerning) * scale; + + prevCharCode = charCode; + } + } + } + + return { width: w, text: text, end: end, chars: chars }; + +}; + +/** +* Given a text string this will scan each character in the string to ensure it exists +* in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. +* +* If no font data has been loaded at all this returns an empty string, as nothing can be rendered. +* +* @method Phaser.BitmapText.prototype.cleanText +* @param {string} text - The text to parse. +* @param {string} [replace=''] - The replacement string for any missing characters. +* @return {string} The cleaned text string. +*/ +Phaser.BitmapText.prototype.cleanText = function (text, replace) { + + if (replace === undefined) + { + replace = ''; + } + + var data = this._data.font; + + if (!data) + { + return ''; + } + + var re = /\r\n|\n\r|\n|\r/g; + var lines = text.replace(re, "\n").split("\n"); + + for (var i = 0; i < lines.length; i++) + { + var output = ''; + var line = lines[i]; + + for (var c = 0; c < line.length; c++) + { + if (data.chars[line.charCodeAt(c)]) + { + output = output.concat(line[c]); + } + else + { + output = output.concat(replace); + } + } + + lines[i] = output; + } + + return lines.join("\n"); + +}; + +/** +* Renders text and updates it when needed. +* +* @method Phaser.BitmapText.prototype.updateText +* @private +*/ +Phaser.BitmapText.prototype.updateText = function () { + + var data = this._data.font; + + if (!data) + { + return; + } + + var text = this.text; + var scale = this._fontSize / data.size; + var lines = []; + + var y = 0; + + this.textWidth = 0; + + do + { + var line = this.scanLine(data, scale, text); + + line.y = y; + + lines.push(line); + + if (line.width > this.textWidth) + { + this.textWidth = line.width; + } + + y += (data.lineHeight * scale); + + text = text.substr(line.text.length + 1); + + } while (line.end === false); + + this.textHeight = y; + + var t = 0; + var align = 0; + var ax = this.textWidth * this.anchor.x; + var ay = this.textHeight * this.anchor.y; + + for (var i = 0; i < lines.length; i++) + { + var line = lines[i]; + + if (this._align === 'right') + { + align = this.textWidth - line.width; + } + else if (this._align === 'center') + { + align = (this.textWidth - line.width) / 2; + } + + for (var c = 0; c < line.text.length; c++) + { + var charCode = line.text.charCodeAt(c); + var charData = data.chars[charCode]; + + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + var g = this._glyphs[t]; + + if (g) + { + // Sprite already exists in the glyphs pool, so we'll reuse it for this letter + g.texture = charData.texture; + } + else + { + // We need a new sprite as the pool is empty or exhausted + g = new PIXI.Sprite(charData.texture); + g.name = line.text[c]; + this._glyphs.push(g); + } + + g.position.x = (line.chars[c] + align) - ax; + g.position.y = (line.y + (charData.yOffset * scale)) - ay; + + g.scale.set(scale); + g.tint = this.tint; + g.texture.requiresReTint = true; + g.cachedTint = 0xFFFFFF; + + if (!g.parent) + { + this.addChild(g); + } + + t++; + } + } + + // Remove unnecessary children + // This moves them from the display list (children array) but retains them in the _glyphs pool + for (i = t; i < this._glyphs.length; i++) + { + this.removeChild(this._glyphs[i]); + } + +}; + +/** +* If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of +* Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they +* still take up memory while sat in the glyphs pool waiting to be re-used in the future. +* +* If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool +* by calling this method. +* +* Calling this doesn't prevent you from increasing the length of the text again in the future. +* +* @method Phaser.BitmapText.prototype.purgeGlyphs +* @return {integer} The amount of glyphs removed from the pool. +*/ +Phaser.BitmapText.prototype.purgeGlyphs = function () { + + var len = this._glyphs.length; + var kept = []; + + for (var i = 0; i < this._glyphs.length; i++) + { + if (this._glyphs[i].parent !== this) + { + this._glyphs[i].destroy(); + } + else + { + kept.push(this._glyphs[i]); + } + } + + this._glyphs = []; + this._glyphs = kept; + + this.updateText(); + + return len - kept.length; + +}; + +/** +* Updates the transform of this object. +* +* @method Phaser.BitmapText.prototype.updateTransform +* @private +*/ +Phaser.BitmapText.prototype.updateTransform = function () { + + if (this.dirty || !this.anchor.equals(this._prevAnchor)) + { + this.updateText(); + this.dirty = false; + this._prevAnchor.copyFrom(this.anchor); + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/** +* @name Phaser.BitmapText#align +* @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'align', { + + get: function() { + return this._align; + }, + + set: function(value) { + + if (value !== this._align && (value === 'left' || value === 'center' || value === 'right')) + { + this._align = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#tint +* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'tint', { + + get: function() { + return this._tint; + }, + + set: function(value) { + + if (value !== this._tint) + { + this._tint = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#font +* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'font', { + + get: function() { + return this._font; + }, + + set: function(value) { + + if (value !== this._font) + { + this._font = value.trim(); + this._data = this.game.cache.getBitmapFont(this._font); + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#fontSize +* @property {number} fontSize - The size of the font in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { + + get: function() { + return this._fontSize; + }, + + set: function(value) { + + value = parseInt(value, 10); + + if (value !== this._fontSize && value > 0) + { + this._fontSize = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#text +* @property {string} text - The text to be displayed by this BitmapText object. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.updateText(); + } + + } + +}); + +/** +* The maximum display width of this BitmapText in pixels. +* +* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped +* based on the last whitespace character found in the line. +* +* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. +* +* Disable maxWidth by setting the value to 0. +* +* @name Phaser.BitmapText#maxWidth +* @property {number} maxWidth - The maximum width of this BitmapText in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', { + + get: function() { + + return this._maxWidth; + + }, + + set: function(value) { + + if (value !== this._maxWidth) + { + this._maxWidth = value; + this.updateText(); + } + + } + +}); + +/** +* Enable or disable texture smoothing for this BitmapText. +* +* The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. +* +* Smoothing is enabled by default. +* +* @name Phaser.BitmapText#smoothed +* @property {boolean} smoothed +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', { + + get: function() { + + return !this._data.base.scaleMode; + + }, + + set: function(value) { + + if (value) + { + this._data.base.scaleMode = 0; + } + else + { + this._data.base.scaleMode = 1; + } + this._data.base.dirty(); + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont +* is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. +* +* @class Phaser.RetroFont +* @extends Phaser.RenderTexture +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {string} key - The font set graphic set as stored in the Game.Cache. +* @param {number} characterWidth - The width of each character in the font set. +* @param {number} characterHeight - The height of each character in the font set. +* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. +* @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. +* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. +* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { + + if (!game.cache.checkImageKey(key)) + { + return false; + } + + if (charsPerRow === undefined || charsPerRow === null) + { + charsPerRow = game.cache.getImage(key).width / characterWidth; + } + + /** + * @property {number} characterWidth - The width of each character in the font set. + */ + this.characterWidth = characterWidth; + + /** + * @property {number} characterHeight - The height of each character in the font set. + */ + this.characterHeight = characterHeight; + + /** + * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here. + */ + this.characterSpacingX = xSpacing || 0; + + /** + * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here. + */ + this.characterSpacingY = ySpacing || 0; + + /** + * @property {number} characterPerRow - The number of characters per row in the font set. + */ + this.characterPerRow = charsPerRow; + + /** + * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @readonly + */ + this.offsetX = xOffset || 0; + + /** + * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @readonly + */ + this.offsetY = yOffset || 0; + + /** + * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + */ + this.align = "left"; + + /** + * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) + * @default + */ + this.multiLine = false; + + /** + * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. + * @default + */ + this.autoUpperCase = true; + + /** + * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels. + * @default + */ + this.customSpacingX = 0; + + /** + * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels. + * @default + */ + this.customSpacingY = 0; + + /** + * If you need this RetroFont image to have a fixed width you can set the width in this value. + * If text is wider than the width specified it will be cropped off. + * @property {number} fixedWidth + */ + this.fixedWidth = 0; + + /** + * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font. + */ + this.fontSet = game.cache.getImage(key); + + /** + * @property {string} _text - The text of the font image. + * @private + */ + this._text = ''; + + /** + * @property {array} grabData - An array of rects for faster character pasting. + * @private + */ + this.grabData = []; + + /** + * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font. + */ + this.frameData = new Phaser.FrameData(); + + // Now generate our rects for faster copying later on + var currentX = this.offsetX; + var currentY = this.offsetY; + var r = 0; + + for (var c = 0; c < chars.length; c++) + { + var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight)); + + this.grabData[chars.charCodeAt(c)] = frame.index; + + r++; + + if (r === this.characterPerRow) + { + r = 0; + currentX = this.offsetX; + currentY += this.characterHeight + this.characterSpacingY; + } + else + { + currentX += this.characterWidth + this.characterSpacingX; + } + } + + game.cache.updateFrameData(key, this.frameData); + + /** + * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font. + * @readonly + */ + this.stamp = new Phaser.Image(game, 0, 0, key, 0); + + Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST); + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RETROFONT; + +}; + +Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype); +Phaser.RetroFont.prototype.constructor = Phaser.RetroFont; + +/** +* Align each line of multi-line text to the left. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_LEFT = "left"; + +/** +* Align each line of multi-line text to the right. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_RIGHT = "right"; + +/** +* Align each line of multi-line text in the center. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_CENTER = "center"; + +/** +* Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + +/** +* Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "; + +/** +* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789"; + +/** +* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789"; + +/** +* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' "; + +/** +* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39"; + +/** +* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!"; + +/** +* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"; + +/** +* If you need this RetroFont to have a fixed width and custom alignment you can set the width here. +* If text is wider than the width specified it will be cropped off. +* +* @method Phaser.RetroFont#setFixedWidth +* @memberof Phaser.RetroFont +* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. +* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +*/ +Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) { + + if (lineAlignment === undefined) { lineAlignment = 'left'; } + + this.fixedWidth = width; + this.align = lineAlignment; + +}; + +/** +* A helper function that quickly sets lots of variables at once, and then updates the text. +* +* @method Phaser.RetroFont#setText +* @memberof Phaser.RetroFont +* @param {string} content - The text of this sprite. +* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. +* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels. +* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels. +* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. +*/ +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; + } + +}; + +/** +* Updates the texture with the new text. +* +* @method Phaser.RetroFont#buildRetroFontText +* @memberof Phaser.RetroFont +*/ +Phaser.RetroFont.prototype.buildRetroFontText = function () { + + var cx = 0; + var cy = 0; + + // Clears the textureBuffer + 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); + } + + // Loop through each line of text + for (var i = 0; i < lines.length; i++) + { + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + // This line of text is held in lines[i] - need to work out the alignment + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(lines[i], cx, cy, this.customSpacingX); + + cy += this.characterHeight + this.customSpacingY; + } + } + else + { + if (this.fixedWidth > 0) + { + this.resize(this.fixedWidth, this.characterHeight, true); + } + else + { + this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true); + } + + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(this._text, cx, 0, this.customSpacingX); + } + + this.requiresReTint = true; + +}; + +/** +* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. +* Used by getLine and getMultiLine +* +* @method Phaser.RetroFont#pasteLine +* @memberof Phaser.RetroFont +* @param {string} line - The single line of text to paste. +* @param {number} x - The x coordinate. +* @param {number} y - The y coordinate. +* @param {number} customSpacingX - Custom X spacing. +*/ +Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) { + + for (var c = 0; c < line.length; c++) + { + // If it's a space then there is no point copying, so leave a blank space + if (line.charAt(c) === " ") + { + x += this.characterWidth + customSpacingX; + } + else + { + // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it + if (this.grabData[line.charCodeAt(c)] >= 0) + { + this.stamp.frame = this.grabData[line.charCodeAt(c)]; + this.renderXY(this.stamp, x, y, false); + + x += this.characterWidth + customSpacingX; + + if (x > this.width) + { + break; + } + } + } + } +}; + +/** +* Works out the longest line of text in _text and returns its length +* +* @method Phaser.RetroFont#getLongestLine +* @memberof Phaser.RetroFont +* @return {number} The length of the longest line of text. +*/ +Phaser.RetroFont.prototype.getLongestLine = function () { + + var longestLine = 0; + + if (this._text.length > 0) + { + var lines = this._text.split("\n"); + + for (var i = 0; i < lines.length; i++) + { + if (lines[i].length > longestLine) + { + longestLine = lines[i].length; + } + } + } + + return longestLine; +}; + +/** +* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set. +* +* @method Phaser.RetroFont#removeUnsupportedCharacters +* @memberof Phaser.RetroFont +* @protected +* @param {boolean} [stripCR=true] - Should it strip carriage returns as well? +* @return {string} A clean version of the string. +*/ +Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) { + + var newString = ""; + + for (var c = 0; c < this._text.length; c++) + { + var aChar = this._text[c]; + var code = aChar.charCodeAt(0); + + if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n")) + { + newString = newString.concat(aChar); + } + } + + return newString; + +}; + +/** +* Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. +* Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. +* So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. +* +* @method Phaser.RetroFont#updateOffset +* @memberof Phaser.RetroFont +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont.prototype.updateOffset = function (x, y) { + + if (this.offsetX === x && this.offsetY === y) + { + return; + } + + var diffX = x - this.offsetX; + var diffY = y - this.offsetY; + + var frames = this.game.cache.getFrameData(this.stamp.key).getFrames(); + var i = frames.length; + + while (i--) + { + frames[i].x += diffX; + frames[i].y += diffY; + } + + this.buildRetroFontText(); + +}; + +/** +* @name Phaser.RetroFont#text +* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. +*/ +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(); + } + + } + +}); + +/** +* @name Phaser.RetroFont#smoothed +* @property {boolean} smoothed - Sets if the stamp is smoothed or not. +*/ +Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", { + + get: function () { + + return this.stamp.smoothed; + + }, + + set: function (value) { + + this.stamp.smoothed = value; + this.buildRetroFontText(); + + } + +}); + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @author Rovanion Luckey +* @copyright 2016 Photon Storm Ltd, Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Rope is a Sprite that has a repeating texture. +* +* The texture will automatically wrap on the edges as it moves. +* +* Please note that Ropes cannot have an input handler. +* +* @class Phaser.Rope +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Rope at. +* @param {number} y - The y coordinate (in world space) to position the Rope at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {Array} points - An array of {Phaser.Point}. +*/ +Phaser.Rope = function (game, x, y, key, frame, points) { + + this.points = points || []; + this._hasUpdateAnimation = false; + this._updateAnimationCallback = null; + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROPE; + + PIXI.DisplayObjectContainer.call(this); + + this.texture = Phaser.Cache.DEFAULT; + + // set up the main bits.. + this.uvs = new Float32Array([0, 1, + 1, 1, + 1, 0, + 0, 1]); + + this.vertices = new Float32Array([0, 0, + 100, 0, + 100, 100, + 0, 100]); + + this.colors = new Float32Array([1, 1, 1, 1]); + + this.indices = new Uint16Array([0, 1, 2, 3]); + + if (points) + { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + /** + * Whether the strip is dirty or not + * + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. + * + * @property canvasPadding + * @type Number + */ + this.canvasPadding = 0; + + this.drawMode = Phaser.Rope.TRIANGLE_STRIP; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + + this.refresh(); + +}; + +Phaser.Rope.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Rope.prototype.constructor = Phaser.Rope; + +Phaser.Component.Core.install.call(Phaser.Rope.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +Phaser.Rope.TRIANGLE_STRIP = 0; +Phaser.Rope.TRIANGLES = 1; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Rope#preUpdate +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override and use this function in your own custom objects to handle any update requirements you may have. +* +* @method Phaser.Rope#update +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.update = function() { + + if (this._hasUpdateAnimation) + { + this.updateAnimation.call(this); + } + +}; + +/** +* Resets the Rope. This places the Rope at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the Rope has a physics body that too is reset. +* +* @method Phaser.Rope#reset +* @memberof Phaser.Rope +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.Rope} This instance. +*/ +Phaser.Rope.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + return this; + +}; + +/* +* Refreshes the rope texture and UV coordinates. +* +* @method Phaser.Rope#refresh +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.refresh = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + this.count -= 0.2; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + var index; + var amount; + + for (var i = 1; i < total; i++) + { + index = i * 4; + + // time to do some smart drawing! + amount = i / (total - 1); + + if (i % 2) + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + else + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + +}; + +/* +* Updates the Ropes transform ready for rendering. +* +* @method Phaser.Rope#updateTransform +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.updateTransform = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var lastPoint = points[0]; + var nextPoint; + var perp = { x:0, y:0 }; + + this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + var point; + var index; + var ratio; + var perpLength; + var num; + + for (var i = 0; i < total; i++) + { + point = points[i]; + index = i * 4; + + if(i < points.length - 1) + { + nextPoint = points[i + 1]; + } + else + { + nextPoint = point; + } + + perp.y = -(nextPoint.x - lastPoint.x); + perp.x = nextPoint.y - lastPoint.y; + + ratio = (1 - (i / (total - 1))) * 10; + + if (ratio > 1) + { + ratio = 1; + } + + perpLength = Math.sqrt((perp.x * perp.x) + (perp.y * perp.y)); + num = this.texture.height / 2; + perp.x /= perpLength; + perp.y /= perpLength; + + perp.x *= num; + perp.y *= num; + + vertices[index] = point.x + perp.x; + vertices[index + 1] = point.y + perp.y; + vertices[index + 2] = point.x - perp.x; + vertices[index + 3] = point.y - perp.y; + + lastPoint = point; + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/* +* Sets the Texture this Rope uses for rendering. +* +* @method Phaser.Rope#setTexture +* @memberof Phaser.Rope +* @param {Texture} texture - The texture that will be used. +*/ +Phaser.Rope.prototype.setTexture = function (texture) { + + this.texture = texture; + +}; + +/* +* Renders the Rope to WebGL. +* +* @private +* @method Phaser.Rope#_renderWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + renderSession.spriteBatch.stop(); + + if (!this._vertexBuffer) + { + this._initWebGL(renderSession); + } + + renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader); + + this._renderStrip(renderSession); + + renderSession.spriteBatch.start(); + +}; + +/* +* Builds the Strip. +* +* @private +* @method Phaser.Rope#_initWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._initWebGL = function (renderSession) { + + // build the strip! + var gl = renderSession.gl; + + this._vertexBuffer = gl.createBuffer(); + this._indexBuffer = gl.createBuffer(); + this._uvBuffer = gl.createBuffer(); + this._colorBuffer = gl.createBuffer(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + +}; + +/* +* Renders the Strip to WebGL. +* +* @private +* @method Phaser.Rope#_renderStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderStrip = function (renderSession) { + + var gl = renderSession.gl; + var projection = renderSession.projection; + var offset = renderSession.offset; + var shader = renderSession.shaderManager.stripShader; + + var drawMode = (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + renderSession.blendModeManager.setBlendMode(this.blendMode); + + // set uniforms + gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true)); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + gl.uniform1f(shader.alpha, this.worldAlpha); + + if (!this.dirty) + { + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + } + else + { + this.dirty = false; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + } + + gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0); + +}; + +/* +* Renders the Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvas +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvas = function (renderSession) { + + var context = renderSession.context; + + var transform = this.worldTransform; + + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + if (renderSession.roundPixels) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx, ty); + } + + if (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) + { + this._renderCanvasTriangleStrip(context); + } + else + { + this._renderCanvasTriangles(context); + } + +}; + +/* +* Renders a Triangle Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangleStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangleStrip = function (context) { + + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + + var length = vertices.length / 2; + + this.count++; + + for (var i = 0; i < length - 2; i++) + { + var index = i * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangles +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangles = function (context) { + + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + + var length = indices.length; + + this.count++; + + for (var i = 0; i < length; i += 3) + { + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasDrawTriangle +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { + + var textureSource = this.texture.baseTexture.source; + var textureWidth = this.texture.width; + var textureHeight = this.texture.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var u0 = uvs[index0] * textureWidth; + var u1 = uvs[index1] * textureWidth; + var u2 = uvs[index2] * textureWidth; + var v0 = uvs[index0 + 1] * textureHeight; + var v1 = uvs[index1 + 1] * textureHeight; + var v2 = uvs[index2 + 1] * textureHeight; + + if (this.canvasPadding > 0) + { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt((normX * normX) + (normY * normY)); + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2); + var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2); + var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2); + var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2); + var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2); + var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2); + var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2); + + context.transform( + deltaA / delta, + deltaD / delta, + deltaB / delta, + deltaE / delta, + deltaC / delta, + deltaF / delta); + + context.drawImage(textureSource, 0, 0); + context.restore(); + +}; + +/* +* Renders a flat strip. +* +* @method Phaser.Rope#renderStripFlat +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.renderStripFlat = function (strip) { + + var context = this.context; + var vertices = strip.vertices; + + var length = vertices.length / 2; + + this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; i++) + { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var x1 = vertices[index + 2]; + var x2 = vertices[index + 4]; + var y0 = vertices[index + 1]; + var y1 = vertices[index + 3]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + +}; + +/* +* Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Rope#getBounds +* @memberof Phaser.Rope +* @param {Matrix} matrix - The transformation matrix of the Sprite. +* @return {Rectangle} The framing rectangle. +*/ +Phaser.Rope.prototype.getBounds = function (matrix) { + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + var vertices = this.vertices; + + for (var i = 0; i < vertices.length; i += 2) + { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + if (minX === -Infinity || maxY === Infinity) + { + return PIXI.EmptyRectangle; + } + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // Store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* A Rope will call its updateAnimation function on each update loop if it has one. +* +* @name Phaser.Rope#updateAnimation +* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. +*/ +Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", { + + get: function () { + + return this._updateAnimation; + + }, + + set: function (value) { + + if (value && typeof value === 'function') + { + this._hasUpdateAnimation = true; + this._updateAnimation = value; + } + else + { + this._hasUpdateAnimation = false; + this._updateAnimation = null; + } + + } + +}); + +/** +* The segments that make up the rope body as an array of Phaser.Rectangles +* +* @name Phaser.Rope#segments +* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope +*/ +Object.defineProperty(Phaser.Rope.prototype, "segments", { + + get: function () { + + var segments = []; + var index, x1, y1, x2, y2, width, height, rect; + + for (var i = 0; i < this.points.length; i++) + { + index = i * 4; + + x1 = this.vertices[index] * this.scale.x; + y1 = this.vertices[index + 1] * this.scale.y; + x2 = this.vertices[index + 4] * this.scale.x; + y2 = this.vertices[index + 3] * this.scale.y; + + width = Phaser.Math.difference(x1, x2); + height = Phaser.Math.difference(y1, y2); + + x1 += this.world.x; + y1 += this.world.y; + rect = new Phaser.Rectangle(x1, y1, width, height); + segments.push(rect); + } + + return segments; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. +* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. +* +* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. +* +* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background +* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` +* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will +* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to +* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. +* +* An important note about texture dimensions: +* +* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be +* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two +* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and +* bottom of your frame. To avoid this ensure your textures are perfect powers of two. +* +* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However +* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive +* additional padding to enforce it to be so. +* +* @class Phaser.TileSprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate (in world space) to position the TileSprite at. +* @param {number} [y=0] - The y coordinate (in world space) to position the TileSprite at. +* @param {number} [width=256] - The width of the TileSprite. +* @param {number} [height=256] - The height of the TileSprite. +* @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. +* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.TileSprite = function (game, x, y, width, height, key, frame) { + + x = x || 0; + y = y || 0; + width = width || 256; + height = height || 256; + key = key || null; + frame = frame || null; + + PIXI.Sprite.call(this, new PIXI.Texture(Phaser.Cache.DEFAULT.baseTexture), width, height); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.TILESPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} _scroll - Internal cache var. + * @private + */ + this._scroll = new Phaser.Point(); + + /** + * @property {Phaser.Point} tileScale - The scale applied to the image being tiled. + */ + this.tileScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tileScaleOffset - The scale offset applied to the image being tiled. + */ + this.tileScaleOffset = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tilePosition - The offset position of the image being tiled. + */ + this.tilePosition = new Phaser.Point(); + + /** + * If enabled a green rectangle will be drawn behind the generated tiling texture, + * allowing you to visually debug the texture being used. + * + * @property {boolean} textureDebug + */ + this.textureDebug = false; + + /** + * The CanvasBuffer object that the tiled texture is drawn to. + * + * @property {PIXI.CanvasBuffer} canvasBuffer + */ + this.canvasBuffer = null; + + /** + * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. + * + * @property {PIXI.Texture} tilingTexture + */ + this.tilingTexture = null; + + /** + * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). + * + * @property {object} tilePattern + */ + this.tilePattern = null; + + /** + * If true the TileSprite will run `generateTexture` on its **next** render pass. + * This is set by the likes of Phaser.LoadTexture.setFrame. + * + * @property {boolean} refreshTexture + */ + this.refreshTexture = true; + + this.frameWidth = 0; + this.frameHeight = 0; + + this._width = width; + this._height = height; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.TileSprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.TileSprite.prototype.constructor = Phaser.TileSprite; + +Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'Smoothed' +]); + +Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TileSprite#preUpdate +* @memberof Phaser.TileSprite +* @return {boolean} +*/ +Phaser.TileSprite.prototype.preUpdate = function () { + + if (this._scroll.x !== 0) + { + this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed; + } + + if (this._scroll.y !== 0) + { + this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed; + } + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). +* The scroll speed is specified in pixels per second. +* A negative x value will scroll to the left. A positive x value will scroll to the right. +* A negative y value will scroll up. A positive y value will scroll down. +* +* @method Phaser.TileSprite#autoScroll +* @memberof Phaser.TileSprite +* @param {number} x - Horizontal scroll speed in pixels per second. +* @param {number} y - Vertical scroll speed in pixels per second. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.autoScroll = function (x, y) { + + this._scroll.set(x, y); + + return this; + +}; + +/** +* Stops an automatically scrolling TileSprite. +* +* @method Phaser.TileSprite#stopScroll +* @memberof Phaser.TileSprite +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.stopScroll = function () { + + this._scroll.set(0, 0); + + return this; + +}; + +/** +* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present +* and nulls its reference to game, freeing it up for garbage collection. +* +* @method Phaser.TileSprite#destroy +* @memberof Phaser.TileSprite +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.TileSprite.prototype.destroy = function (destroyChildren) { + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + + PIXI.Sprite.prototype.destroy.call(this); + + if (this.canvasBuffer) + { + this.canvasBuffer.destroy(); + this.canvasBuffer = null; + } + + this.tileScale = null; + this.tileScaleOffset = null; + this.tilePosition = null; + + if (this.tilingTexture) + { + this.tilingTexture.destroy(true); + this.tilingTexture = null; + } + +}; + +/** +* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the TileSprite has a physics body that too is reset. +* +* @method Phaser.TileSprite#reset +* @memberof Phaser.TileSprite +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + this.tilePosition.x = 0; + this.tilePosition.y = 0; + + return this; + +}; + +/** +* Changes the texture being rendered by this TileSprite. +* Causes a texture refresh to take place on the next render. +* +* @method Phaser.TileSprite#setTexture +* @memberof Phaser.TileSprite +* @param {PIXI.Texture} texture - The texture to apply to this TileSprite. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.setTexture = function (texture) { + + if (this.texture !== texture) + { + this.texture = texture; + this.refreshTexture = true; + this.cachedTint = 0xFFFFFF; + } + + return this; + +}; + +/** +* Renders the TileSprite using the WebGL Renderer. +* +* @private +* @method Phaser.TileSprite#_renderWebGL +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + 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.refreshTexture) + { + this.generateTilingTexture(true, renderSession); + + if (this.tilingTexture) + { + if (this.tilingTexture.needsUpdate) + { + this.tilingTexture.baseTexture.textureIndex = this.texture.baseTexture.textureIndex; + renderSession.renderer.updateTexture(this.tilingTexture.baseTexture); + this.tilingTexture.needsUpdate = false; + } + } + else + { + return; + } + } + + renderSession.spriteBatch.renderTilingSprite(this); + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + var restartBatch = false; + + if (this._filters) + { + restartBatch = true; + renderSession.spriteBatch.stop(); + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + if (!restartBatch) + { + renderSession.spriteBatch.stop(); + } + + renderSession.maskManager.popMask(this._mask, renderSession); + } + + if (restartBatch) + { + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the TileSprite using the Canvas Renderer. +* +* @private +* @method Phaser.TileSprite#_renderCanvas +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + var context = renderSession.context; + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + context.globalAlpha = this.worldAlpha; + + var wt = this.worldTransform; + var resolution = renderSession.resolution; + var tx = (wt.tx * resolution) + renderSession.shakeX; + var ty = (wt.ty * resolution) + renderSession.shakeY; + + context.setTransform(wt.a * resolution, wt.b * resolution, wt.c * resolution, wt.d * resolution, tx, ty); + + if (this.tint !== 0xFFFFFF && (this.texture.requiresReTint || this.cachedTint !== this.tint)) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + this.refreshTexture = true; + } + + if (this.refreshTexture) + { + this.generateTilingTexture(false, renderSession); + + if (this.tilingTexture) + { + this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat'); + } + else + { + return; + } + } + + var sessionBlendMode = renderSession.currentBlendMode; + + // Check blend mode + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + var tilePosition = this.tilePosition; + var tileScale = this.tileScale; + + tilePosition.x %= this.tilingTexture.baseTexture.width; + tilePosition.y %= this.tilingTexture.baseTexture.height; + + // Translate + context.scale(tileScale.x, tileScale.y); + context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height)); + + context.fillStyle = this.tilePattern; + + tx = -tilePosition.x; + ty = -tilePosition.y; + + var tw = this._width / tileScale.x; + var th = this._height / tileScale.y; + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + tx |= 0; + ty |= 0; + tw |= 0; + th |= 0; + } + + context.fillRect(tx, ty, tw, th); + + // Translate back again + context.scale(1 / tileScale.x, 1 / tileScale.y); + context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height)); + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + // Reset blend mode + if (sessionBlendMode !== this.blendMode) + { + renderSession.currentBlendMode = sessionBlendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode]; + } + +}; + +/** +* Override the Sprite method. +* +* @private +* @method Phaser.TileSprite#onTextureUpdate +* @memberof Phaser.TileSprite +*/ +Phaser.TileSprite.prototype.onTextureUpdate = function () { + + // overriding the sprite version of this! + +}; + +/** +* Internal method that generates a new tiling texture. +* +* @method Phaser.TileSprite#generateTilingTexture +* @memberof Phaser.TileSprite +* @param {boolean} forcePowerOfTwo - Whether we want to force the texture to be a power of two +*/ +Phaser.TileSprite.prototype.generateTilingTexture = function (forcePowerOfTwo) { + + if (!this.texture.baseTexture.hasLoaded) + { + return; + } + + var texture = this.texture; + var frame = texture.frame; + + var targetWidth = this._frame.sourceSizeW || this._frame.width; + var targetHeight = this._frame.sourceSizeH || this._frame.height; + + var dx = 0; + var dy = 0; + + if (this._frame.trimmed) + { + dx = this._frame.spriteSourceSizeX; + dy = this._frame.spriteSourceSizeY; + } + + if (forcePowerOfTwo) + { + targetWidth = Phaser.Math.getNextPowerOfTwo(targetWidth); + targetHeight = Phaser.Math.getNextPowerOfTwo(targetHeight); + } + + if (this.canvasBuffer) + { + this.canvasBuffer.resize(targetWidth, targetHeight); + this.tilingTexture.baseTexture.width = targetWidth; + this.tilingTexture.baseTexture.height = targetHeight; + this.tilingTexture.needsUpdate = true; + } + else + { + this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight); + this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas); + this.tilingTexture.isTiling = true; + this.tilingTexture.needsUpdate = true; + } + + if (this.textureDebug) + { + this.canvasBuffer.context.strokeStyle = '#00ff00'; + this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight); + } + + // If a sprite sheet we need this: + var w = texture.crop.width; + var h = texture.crop.height; + + if (w !== targetWidth || h !== targetHeight) + { + w = targetWidth; + h = targetHeight; + } + + var targetTexture = this.tintedTexture ? this.tintedTexture : texture.baseTexture.source; + + this.canvasBuffer.context.drawImage( + targetTexture, + texture.crop.x, + texture.crop.y, + texture.crop.width, + texture.crop.height, + dx, + dy, + w, + h + ); + + this.tileScaleOffset.x = frame.width / targetWidth; + this.tileScaleOffset.y = frame.height / targetHeight; + + this.refreshTexture = false; + + this.tilingTexture.baseTexture._powerOf2 = true; + +}; + +/** +* Returns the framing rectangle of the Tile Sprite. +* +* @method Phaser.TileSprite#getBounds +* @memberof Phaser.TileSprite +* @return {Phaser.Rectangle} The bounds of the Tile Sprite. +*/ +Phaser.TileSprite.prototype.getBounds = function () { + + var width = this._width; + var height = this._height; + + var w0 = width * (1 - this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1 - this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = (a * w1) + (c * h1) + tx; + var y1 = (d * h1) + (b * w1) + ty; + + var x2 = (a * w0) + (c * h1) + tx; + var y2 = (d * h1) + (b * w0) + ty; + + var x3 = (a * w0) + (c * h0) + tx; + var y3 = (d * h0) + (b * w0) + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // TODO: This is surely always undefined? As it's not set anywhere in the parent objects + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* The width of the sprite, setting this will actually modify the scale to achieve the value set +* +* @property width +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'width', { + + get: function () { + + return this._width; + + }, + + set: function (value) { + + this._width = value; + + } + +}); + +/** +* The height of the TilingSprite, setting this will actually modify the scale to achieve the value set +* +* @property height +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'height', { + + get: function () { + + return this._height; + + }, + + set: function (value) { + + this._height = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The CanvasPool is a global static object, that allows Phaser to recycle and pool Canvas DOM elements. +* +* @class Phaser.CanvasPool +* @static +*/ +Phaser.CanvasPool = { + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @method Phaser.CanvasPool.create + * @static + * @param {any} parent - The parent of the canvas element. + * @param {number} width - The width of the canvas element. + * @param {number} height - The height of the canvas element. + * @return {HTMLCanvasElement} The canvas element. + */ + create: function (parent, width, height) { + + var idx = Phaser.CanvasPool.getFirst(); + var canvas; + + if (idx === -1) + { + var container = { + parent: parent, + canvas: document.createElement('canvas') + }; + + Phaser.CanvasPool.pool.push(container); + + canvas = container.canvas; + } + else + { + Phaser.CanvasPool.pool[idx].parent = parent; + + canvas = Phaser.CanvasPool.pool[idx].canvas; + } + + if (width !== undefined) + { + canvas.width = width; + canvas.height = height; + } + + return canvas; + + }, + + /** + * Gets the first free canvas index from the pool. + * + * @static + * @method Phaser.CanvasPool.getFirst + * @return {number} + */ + getFirst: function () { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + return i; + } + } + + return -1; + + }, + + /** + * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.remove + * @param {any} parent - The parent of the canvas element. + */ + remove: function (parent) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent === parent) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Looks up a canvas based on its type, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.removeByCanvas + * @param {HTMLCanvasElement} canvas - The canvas element to remove. + */ + removeByCanvas: function (canvas) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].canvas === canvas) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Gets the total number of used canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getTotal + * @return {number} The number of in-use (parented) canvas elements in the pool. + */ + getTotal: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent) + { + c++; + } + } + + return c; + + }, + + /** + * Gets the total number of free canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getFree + * @return {number} The number of free (un-parented) canvas elements in the pool. + */ + getFree: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + c++; + } + } + + return c; + + }, + + + /** + * Prints in-use, free, and total counts to console.log. + * + * @static + * @method Phaser.CanvasPool.log + */ + log: function () { + + console.log('CanvasPool: %s used, %s free, %s total', this.getTotal(), this.getFree(), this.pool.length); + + } + +}; + +/** + * The pool into which the canvas elements are placed. + * + * @property pool + * @type Array + * @static + */ +Phaser.CanvasPool.pool = []; + + +/** + * The total number of canvas elements in the {@link Phaser.CanvasPool.pool pool}. + * + * @property length + * @type number + * @static + * @readonly + */ +Object.defineProperty(Phaser.CanvasPool, 'length', { + get: function () { + return this.pool.length; + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}. +* +* This class represents a singleton object that can be accessed directly as `game.device` +* (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it. +* +* Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization +* occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase. +* Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal, e.g., +* +* ```javascript +* Phaser.Device.onInitialized.add(function (device) { +* +* device.canvasBitBltShift = true; +* device.mspointer = false; +* +* }); +* +* var game = new Phaser.Game(); +* ``` +* +* When checking features using the exposed properties only the *truth-iness* of the value should be relied upon +* unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined` +* when indicating the lack of a feature. +* +* Uses elements from System.js by MrDoob and Modernizr +* +* @description +* It is not possible to instantiate the Device class manually. +* +* @class +* @protected +*/ +Phaser.Device = function () { + + /** + * The time the device became ready. + * @property {integer} deviceReadyAt + * @protected + */ + this.deviceReadyAt = 0; + + /** + * The time as which initialization has completed. + * @property {boolean} initialized + * @protected + */ + this.initialized = false; + + // Browser / Host / Operating System + + /** + * @property {boolean} desktop - Is running on a desktop? + * @default + */ + this.desktop = false; + + /** + * @property {boolean} iOS - Is running on iOS? + * @default + */ + this.iOS = false; + + /** + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @default + */ + this.iOSVersion = 0; + + /** + * @property {boolean} cocoonJS - Is the game running under CocoonJS? + * @default + */ + this.cocoonJS = false; + + /** + * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App? + * @default + */ + this.cocoonJSApp = false; + + /** + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @default + */ + this.cordova = false; + + /** + * @property {boolean} node - Is the game running under Node.js? + * @default + */ + this.node = false; + + /** + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @default + */ + this.nodeWebkit = false; + + /** + * @property {boolean} electron - Is the game running under GitHub Electron? + * @default + */ + this.electron = false; + + /** + * @property {boolean} ejecta - Is the game running under Ejecta? + * @default + */ + this.ejecta = false; + + /** + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @default + */ + this.crosswalk = false; + + /** + * @property {boolean} android - Is running on android? + * @default + */ + this.android = false; + + /** + * @property {boolean} chromeOS - Is running on chromeOS? + * @default + */ + this.chromeOS = false; + + /** + * @property {boolean} linux - Is running on linux? + * @default + */ + this.linux = false; + + /** + * @property {boolean} macOS - Is running on macOS? + * @default + */ + this.macOS = false; + + /** + * @property {boolean} windows - Is running on windows? + * @default + */ + this.windows = false; + + /** + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @default + */ + this.windowsPhone = false; + + // Features + + /** + * @property {boolean} canvas - Is canvas available? + * @default + */ + this.canvas = false; + + /** + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @default + */ + this.canvasBitBltShift = null; + + /** + * If the browser isn't capable of handling tinting with alpha this will be false. + * @property {boolean} canHandleAlpha + * @default + */ + this.canHandleAlpha = false; + + /** + * Whether or not the {@link http://caniuse.com/#feat=canvas-blending Canvas Blend Modes} are supported, consequently the ability to tint using the multiply method. + * + * Expect `false` in Internet Explorer <= 11. + * + * @property {boolean} canUseMultiply + * @default + */ + this.canUseMultiply = false; + + /** + * @property {boolean} webGL - Is webGL available? + * @default + */ + this.webGL = false; + + /** + * @property {boolean} file - Is file available? + * @default + */ + this.file = false; + + /** + * @property {boolean} fileSystem - Is fileSystem available? + * @default + */ + this.fileSystem = false; + + /** + * @property {boolean} localStorage - Is localStorage available? + * @default + */ + this.localStorage = false; + + /** + * @property {boolean} worker - Is worker available? + * @default + */ + this.worker = false; + + /** + * @property {boolean} css3D - Is css3D available? + * @default + */ + this.css3D = false; + + /** + * @property {boolean} pointerLock - Is Pointer Lock available? + * @default + */ + this.pointerLock = false; + + /** + * @property {boolean} typedArray - Does the browser support TypedArrays? + * @default + */ + this.typedArray = false; + + /** + * @property {boolean} vibration - Does the device support the Vibration API? + * @default + */ + this.vibration = false; + + /** + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @default + */ + this.getUserMedia = true; + + /** + * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true) + * @default + */ + this.quirksMode = false; + + // Input + + /** + * @property {boolean} touch - Is touch available? + * @default + */ + this.touch = false; + + /** + * @property {boolean} mspointer - Is mspointer available? + * @default + */ + this.mspointer = false; + + /** + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @default + * @protected + */ + this.wheelEvent = null; + + // Browser + + /** + * @property {boolean} arora - Set to true if running in Arora. + * @default + */ + this.arora = false; + + /** + * @property {boolean} chrome - Set to true if running in Chrome. + * @default + */ + this.chrome = false; + + /** + * @property {number} chromeVersion - If running in Chrome this will contain the major version number. + * @default + */ + this.chromeVersion = 0; + + /** + * @property {boolean} epiphany - Set to true if running in Epiphany. + * @default + */ + this.epiphany = false; + + /** + * @property {boolean} firefox - Set to true if running in Firefox. + * @default + */ + this.firefox = false; + + /** + * @property {number} firefoxVersion - If running in Firefox this will contain the major version number. + * @default + */ + this.firefoxVersion = 0; + + /** + * @property {boolean} ie - Set to true if running in Internet Explorer. + * @default + */ + this.ie = false; + + /** + * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. + * @default + */ + this.ieVersion = 0; + + /** + * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+) + * @default + */ + this.trident = false; + + /** + * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx} + * @default + */ + this.tridentVersion = 0; + + /** + * @property {boolean} edge - Set to true if running in Microsoft Edge browser. + * @default + */ + this.edge = false; + + /** + * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. + * @default + */ + this.mobileSafari = false; + + /** + * @property {boolean} midori - Set to true if running in Midori. + * @default + */ + this.midori = false; + + /** + * @property {boolean} opera - Set to true if running in Opera. + * @default + */ + this.opera = false; + + /** + * @property {boolean} safari - Set to true if running in Safari. + * @default + */ + this.safari = false; + + /** + * @property {number} safariVersion - If running in Safari this will contain the major version number. + * @default + */ + this.safariVersion = 0; + + /** + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @default + */ + this.webApp = false; + + /** + * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle) + * @default + */ + this.silk = false; + + // Audio + + /** + * @property {boolean} audioData - Are Audio tags available? + * @default + */ + this.audioData = false; + + /** + * @property {boolean} webAudio - Is the WebAudio API available? + * @default + */ + this.webAudio = false; + + /** + * @property {boolean} ogg - Can this device play ogg files? + * @default + */ + this.ogg = false; + + /** + * @property {boolean} opus - Can this device play opus files? + * @default + */ + this.opus = false; + + /** + * @property {boolean} mp3 - Can this device play mp3 files? + * @default + */ + this.mp3 = false; + + /** + * @property {boolean} wav - Can this device play wav files? + * @default + */ + this.wav = false; + + /** + * Can this device play m4a files? + * @property {boolean} m4a - True if this device can play m4a files. + * @default + */ + this.m4a = false; + + /** + * @property {boolean} webm - Can this device play webm files? + * @default + */ + this.webm = false; + + /** + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @default + */ + this.dolby = false; + + // Video + + /** + * @property {boolean} oggVideo - Can this device play ogg video files? + * @default + */ + this.oggVideo = false; + + /** + * @property {boolean} h264Video - Can this device play h264 mp4 video files? + * @default + */ + this.h264Video = false; + + /** + * @property {boolean} mp4Video - Can this device play h264 mp4 video files? + * @default + */ + this.mp4Video = false; + + /** + * @property {boolean} webmVideo - Can this device play webm video files? + * @default + */ + this.webmVideo = false; + + /** + * @property {boolean} vp9Video - Can this device play vp9 video files? + * @default + */ + this.vp9Video = false; + + /** + * @property {boolean} hlsVideo - Can this device play hls video files? + * @default + */ + this.hlsVideo = false; + + // Device + + /** + * @property {boolean} iPhone - Is running on iPhone? + * @default + */ + this.iPhone = false; + + /** + * @property {boolean} iPhone4 - Is running on iPhone4? + * @default + */ + this.iPhone4 = false; + + /** + * @property {boolean} iPad - Is running on iPad? + * @default + */ + this.iPad = false; + + // Device features + + /** + * @property {number} pixelRatio - PixelRatio of the host device? + * @default + */ + this.pixelRatio = 0; + + /** + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @default + */ + this.littleEndian = false; + + /** + * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`. + * @default + */ + this.LITTLE_ENDIAN = false; + + /** + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @default + */ + this.support32bit = false; + + /** + * @property {boolean} fullscreen - Does the browser support the Full Screen API? + * @default + */ + this.fullscreen = false; + + /** + * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it. + * @default + */ + this.requestFullscreen = ''; + + /** + * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @default + */ + this.cancelFullscreen = ''; + + /** + * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @default + */ + this.fullscreenKeyboard = false; + +}; + +// Device is really a singleton/static entity; instantiate it +// and add new methods directly sans-prototype. +Phaser.Device = new Phaser.Device(); + +/** +* This signal is dispatched after device initialization occurs but before any of the ready +* callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked. +* +* Local "patching" for a particular device can/should be done in this event. +* +* _Note_: This signal is removed after the device has been readied; if a handler has not been +* added _before_ `new Phaser.Game(..)` it is probably too late. +* +* @type {?Phaser.Signal} +* @static +*/ +Phaser.Device.onInitialized = new Phaser.Signal(); + +/** +* Add a device-ready handler and ensure the device ready sequence is started. +* +* Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added, +* which is normally done automatically be calling `new Phaser.Game(..)`. +* +* The handler is invoked when the device is considered "ready", which may be immediately +* if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}. +* +* @method +* @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. +* @param {object} [context] - Context in which to invoke the handler +* @param {boolean} [nonPrimer=false] - If true the device ready check will not be started. +*/ +Phaser.Device.whenReady = function (callback, context, nonPrimer) { + + var readyCheck = this._readyCheck; + + if (this.deviceReadyAt || !readyCheck) + { + callback.call(context, this); + } + else if (readyCheck._monitor || nonPrimer) + { + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + } + else + { + readyCheck._monitor = readyCheck.bind(this); + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + + var cordova = typeof window.cordova !== 'undefined'; + var cocoonJS = navigator['isCocoonJS']; + + if (document.readyState === 'complete' || document.readyState === 'interactive') + { + // Why is there an additional timeout here? + window.setTimeout(readyCheck._monitor, 0); + } + else if (cordova && !cocoonJS) + { + // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + // Cordova, but NOT Cocoon? + document.addEventListener('deviceready', readyCheck._monitor, false); + } + else + { + document.addEventListener('DOMContentLoaded', readyCheck._monitor, false); + window.addEventListener('load', readyCheck._monitor, false); + } + } + +}; + +/** +* Internal method used for checking when the device is ready. +* This function is removed from Phaser.Device when the device becomes ready. +* +* @method +* @private +*/ +Phaser.Device._readyCheck = function () { + + var readyCheck = this._readyCheck; + + if (!document.body) + { + window.setTimeout(readyCheck._monitor, 20); + } + else if (!this.deviceReadyAt) + { + this.deviceReadyAt = Date.now(); + + document.removeEventListener('deviceready', readyCheck._monitor); + document.removeEventListener('DOMContentLoaded', readyCheck._monitor); + window.removeEventListener('load', readyCheck._monitor); + + this._initialize(); + this.initialized = true; + + this.onInitialized.dispatch(this); + + var item; + while ((item = readyCheck._queue.shift())) + { + var callback = item[0]; + var context = item[1]; + callback.call(context, this); + } + + // Remove no longer useful methods and properties. + this._readyCheck = null; + this._initialize = null; + this.onInitialized = null; + } + +}; + +/** +* Internal method to initialize the capability checks. +* This function is removed from Phaser.Device once the device is initialized. +* +* @method +* @private +*/ +Phaser.Device._initialize = function () { + + var device = this; + + /** + * Check which OS is game running on. + */ + function _checkOS () { + + var ua = navigator.userAgent; + + if (/Playstation Vita/.test(ua)) + { + device.vita = true; + } + else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua)) + { + device.kindle = true; + // This will NOT detect early generations of Kindle Fire, I think there is no reliable way... + // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true" + } + else if (/Android/.test(ua)) + { + device.android = true; + } + else if (/CrOS/.test(ua)) + { + device.chromeOS = true; + } + else if (/iP[ao]d|iPhone/i.test(ua)) + { + device.iOS = true; + (navigator.appVersion).match(/OS (\d+)/); + device.iOSVersion = parseInt(RegExp.$1, 10); + } + else if (/Linux/.test(ua)) + { + device.linux = true; + } + else if (/Mac OS/.test(ua)) + { + device.macOS = true; + } + else if (/Windows/.test(ua)) + { + device.windows = true; + } + + if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua)) + { + device.android = false; + device.iOS = false; + device.macOS = false; + device.windows = true; + device.windowsPhone = true; + } + + var silk = /Silk/.test(ua); // detected in browsers + + if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS) + { + device.desktop = true; + } + + // Windows Phone / Table reset + if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) + { + device.desktop = false; + } + + } + + /** + * Checks if the browser correctly supports putImageData alpha channels. + * If the browser isn't capable of handling tinting with alpha, `Device.canHandleAlpha` will be false. + * Also checks whether the Canvas BlendModes are supported by the current browser for drawImage. + */ + function _checkCanvasFeatures () { + + var canvas = Phaser.CanvasPool.create(this, 6, 1); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgba(10, 20, 30, 0.5)'; + + // Draw a single pixel + context.fillRect(0, 0, 1, 1); + + // Get the color values + var s1 = context.getImageData(0, 0, 1, 1); + + if (s1) + { + // Plot them to x2 + context.putImageData(s1, 1, 0); + + // Get those values + var s2 = context.getImageData(1, 0, 1, 1); + + // Compare and set + device.canHandleAlpha = ( + s2.data[0] === s1.data[0] && + s2.data[1] === s1.data[1] && + s2.data[2] === s1.data[2] && + s2.data[3] === s1.data[3] + ); + } + + // Checks whether the Canvas BlendModes are supported by the current browser for drawImage. + context.globalCompositeOperation = 'multiply'; + device.canUseMultiply = (context.globalCompositeOperation === 'multiply'); + + Phaser.CanvasPool.removeByCanvas(canvas); + + PIXI.CanvasTinter.tintMethod = (device.canUseMultiply) ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel; + + } + + /** + * Check HTML5 features of the host environment. + */ + function _checkFeatures () { + + device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS; + + try { + device.localStorage = !!localStorage.getItem; + } catch (error) { + device.localStorage = false; + } + + device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; + device.fileSystem = !!window['requestFileSystem']; + + device.webGL = !!window.WebGLRenderingContext; + + device.worker = !!window['Worker']; + + device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; + + device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL; + + // Older versions of firefox (< 21) apparently claim support but user media does not actually work + if (device.firefox && device.firefoxVersion < 21) + { + device.getUserMedia = false; + } + + // TODO: replace canvasBitBltShift detection with actual feature check + + // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it + // is safer to not try and use the fast copy-over method. + if (!device.iOS && (device.ie || device.firefox || device.chrome)) + { + device.canvasBitBltShift = true; + } + + // Known not to work + if (device.safari || device.mobileSafari) + { + device.canvasBitBltShift = false; + } + + } + + /** + * Checks/configures various input. + */ + function _checkInput () { + + if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1)) + { + device.touch = true; + } + + if (window.PointerEvent || window.MSPointerEvent || window.navigator.msPointerEnabled || window.navigator.pointerEnabled) + { + device.mspointer = true; + } + + if (!device.cocoonJS) + { + // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel + if ('onwheel' in window || (device.ie && 'WheelEvent' in window)) + { + // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ + device.wheelEvent = 'wheel'; + } + else if ('onmousewheel' in window) + { + // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. + device.wheelEvent = 'mousewheel'; + } + else if (device.firefox && 'MouseScrollEvent' in window) + { + // FF prior to 17. This should probably be scrubbed. + device.wheelEvent = 'DOMMouseScroll'; + } + } + + } + + /** + * Checks for support of the Full Screen API. + */ + function _checkFullScreenSupport () { + + var fs = [ + 'requestFullscreen', + 'requestFullScreen', + 'webkitRequestFullscreen', + 'webkitRequestFullScreen', + 'msRequestFullscreen', + 'msRequestFullScreen', + 'mozRequestFullScreen', + 'mozRequestFullscreen' + ]; + + var element = document.createElement('div'); + + for (var i = 0; i < fs.length; i++) + { + if (element[fs[i]]) + { + device.fullscreen = true; + device.requestFullscreen = fs[i]; + break; + } + } + + var cfs = [ + 'cancelFullScreen', + 'exitFullscreen', + 'webkitCancelFullScreen', + 'webkitExitFullscreen', + 'msCancelFullScreen', + 'msExitFullscreen', + 'mozCancelFullScreen', + 'mozExitFullscreen' + ]; + + if (device.fullscreen) + { + for (var i = 0; i < cfs.length; i++) + { + if (document[cfs[i]]) + { + device.cancelFullscreen = cfs[i]; + break; + } + } + } + + // Keyboard Input? + if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT']) + { + device.fullscreenKeyboard = true; + } + + } + + /** + * Check what browser is game running in. + */ + function _checkBrowser () { + + var ua = navigator.userAgent; + + if (/Arora/.test(ua)) + { + device.arora = true; + } + else if (/Edge\/\d+/.test(ua)) + { + device.edge = true; + } + else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.chrome = true; + device.chromeVersion = parseInt(RegExp.$1, 10); + } + else if (/Epiphany/.test(ua)) + { + device.epiphany = true; + } + else if (/Firefox\D+(\d+)/.test(ua)) + { + device.firefox = true; + device.firefoxVersion = parseInt(RegExp.$1, 10); + } + else if (/AppleWebKit/.test(ua) && device.iOS) + { + device.mobileSafari = true; + } + else if (/MSIE (\d+\.\d+);/.test(ua)) + { + device.ie = true; + device.ieVersion = parseInt(RegExp.$1, 10); + } + else if (/Midori/.test(ua)) + { + device.midori = true; + } + else if (/Opera/.test(ua)) + { + device.opera = true; + } + else if (/Safari\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.safari = true; + + if (/Version\/(\d+)\./.test(ua)) + { + device.safariVersion = parseInt(RegExp.$1, 10); + } + } + else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua)) + { + device.ie = true; + device.trident = true; + device.tridentVersion = parseInt(RegExp.$1, 10); + device.ieVersion = parseInt(RegExp.$3, 10); + } + + // Silk gets its own if clause because its ua also contains 'Safari' + if (/Silk/.test(ua)) + { + device.silk = true; + } + + // WebApp mode in iOS + if (navigator['standalone']) + { + device.webApp = true; + } + + if (typeof window.cordova !== 'undefined') + { + device.cordova = true; + } + + if (typeof process !== 'undefined' && typeof require !== 'undefined') + { + device.node = true; + } + + if (device.node && typeof process.versions === 'object') + { + device.nodeWebkit = !!process.versions['node-webkit']; + + device.electron = !!process.versions.electron; + } + + if (navigator['isCocoonJS']) + { + device.cocoonJS = true; + } + + if (device.cocoonJS) + { + try { + device.cocoonJSApp = (typeof CocoonJS !== 'undefined'); + } + catch(error) + { + device.cocoonJSApp = false; + } + } + + if (typeof window.ejecta !== 'undefined') + { + device.ejecta = true; + } + + if (/Crosswalk/.test(ua)) + { + device.crosswalk = true; + } + + } + + /** + * Check video support. + */ + function _checkVideo () { + + var videoElement = document.createElement("video"); + var result = false; + + try { + if (result = !!videoElement.canPlayType) + { + if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) + { + device.oggVideo = true; + } + + if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + device.h264Video = true; + device.mp4Video = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) + { + device.webmVideo = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) + { + device.vp9Video = true; + } + + if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + device.hlsVideo = true; + } + } + } catch (e) {} + } + + /** + * Check audio support. + */ + function _checkAudio () { + + device.audioData = !!(window['Audio']); + device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); + var audioElement = document.createElement('audio'); + var result = false; + + try { + if (result = !!audioElement.canPlayType) + { + if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) + { + device.ogg = true; + } + + if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) + { + device.opus = true; + } + + if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) + { + device.mp3 = true; + } + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) + { + device.wav = true; + } + + if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) + { + device.m4a = true; + } + + if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) + { + device.webm = true; + } + + if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') + { + if (device.edge) + { + device.dolby = true; + } + else if (device.safari && device.safariVersion >= 9) + { + if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)) + { + var major = parseInt(RegExp.$1, 10); + var minor = parseInt(RegExp.$2, 10); + + if ((major === 10 && minor >= 11) || major > 10) + { + device.dolby = true; + } + } + } + } + } + } catch (e) { + } + + } + + /** + * Check Little or Big Endian system. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsLittleEndian () { + + var a = new ArrayBuffer(4); + var b = new Uint8Array(a); + var c = new Uint32Array(a); + + b[0] = 0xa1; + b[1] = 0xb2; + b[2] = 0xc3; + b[3] = 0xd4; + + if (c[0] === 0xd4c3b2a1) + { + return true; + } + + if (c[0] === 0xa1b2c3d4) + { + return false; + } + else + { + // Could not determine endianness + return null; + } + + } + + /** + * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsUint8ClampedImageData () { + + if (Uint8ClampedArray === undefined) + { + return false; + } + + var elem = Phaser.CanvasPool.create(this, 1, 1); + var ctx = elem.getContext('2d'); + + if (!ctx) + { + return false; + } + + var image = ctx.createImageData(1, 1); + + Phaser.CanvasPool.remove(this); + + return image.data instanceof Uint8ClampedArray; + + } + + /** + * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess. + */ + function _checkDevice () { + + device.pixelRatio = window['devicePixelRatio'] || 1; + device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1; + device.iPhone4 = (device.pixelRatio === 2 && device.iPhone); + device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') !== -1; + + if (typeof Int8Array !== 'undefined') + { + device.typedArray = true; + } + else + { + device.typedArray = false; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') + { + device.littleEndian = _checkIsLittleEndian(); + device.LITTLE_ENDIAN = device.littleEndian; + } + + device.support32bit = (typeof ArrayBuffer !== 'undefined' && typeof Uint8ClampedArray !== 'undefined' && typeof Int32Array !== 'undefined' && device.littleEndian !== null && _checkIsUint8ClampedImageData()); + + navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; + + if (navigator.vibrate) + { + device.vibration = true; + } + + } + + /** + * Check whether the host environment support 3D CSS. + */ + function _checkCSS3D () { + + var el = document.createElement('p'); + var has3d; + var transforms = { + 'webkitTransform': '-webkit-transform', + 'OTransform': '-o-transform', + 'msTransform': '-ms-transform', + 'MozTransform': '-moz-transform', + 'transform': 'transform' + }; + + // Add it to the body to get the computed style. + document.body.insertBefore(el, null); + + for (var t in transforms) + { + if (el.style[t] !== undefined) + { + el.style[t] = "translate3d(1px,1px,1px)"; + has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]); + } + } + + document.body.removeChild(el); + device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none"); + + } + + // Run the checks + _checkOS(); + _checkBrowser(); + _checkAudio(); + _checkVideo(); + _checkCSS3D(); + _checkDevice(); + _checkFeatures(); + _checkCanvasFeatures(); + _checkFullScreenSupport(); + _checkInput(); + +}; + +/** +* Check whether the host environment can play audio. +* +* @method canPlayAudio +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.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 === 'opus' && this.opus) + { + return true; + } + else if (type === 'wav' && this.wav) + { + return true; + } + else if (type === 'webm' && this.webm) + { + return true; + } + else if (type === 'mp4' && this.dolby) + { + return true; + } + + return false; + +}; + +/** +* Check whether the host environment can play video files. +* +* @method canPlayVideo +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.canPlayVideo = function (type) { + + if (type === 'webm' && (this.webmVideo || this.vp9Video)) + { + return true; + } + else if (type === 'mp4' && (this.mp4Video || this.h264Video)) + { + return true; + } + else if ((type === 'ogg' || type === 'ogv') && this.oggVideo) + { + return true; + } + else if (type === 'mpeg' && this.hlsVideo) + { + return true; + } + + return false; + +}; + +/** + * Whether the device plays audio/video only in response to a user touch event. + * + * @method needsTouchUnlock + * @memberof Phaser.Device.prototype + * @return {boolean} + */ +Phaser.Device.needsTouchUnlock = function () { + return !!(!this.cocoonJS && (this.iOS || this.android) || (window.PhaserGlobal && window.PhaserGlobal.fakeiOSTouchLock)); +}; + +/** +* Detect if the host is a an Android Stock browser. +* This is available before the device "ready" event. +* +* Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. +* +* @example +* var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; +* +* @method isAndroidStockBrowser +* @memberof Phaser.Device.prototype +*/ +Phaser.Device.isAndroidStockBrowser = function () { + + var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/); + return matches && matches[1] < 537; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, +* including styles, offset and aspect ratio. +* +* @class Phaser.Canvas +* @static +*/ +Phaser.Canvas = { + + /** + * Creates a `canvas` DOM element. The element is not automatically added to the document. + * + * @method Phaser.Canvas.create + * @param {object} parent - The object that will own the canvas that is created. + * @param {number} [width=256] - The width of the canvas element. + * @param {number} [height=256] - The height of the canvas element.. + * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. + * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global. + * @return {HTMLCanvasElement} The newly created canvas element. + */ + create: function (parent, width, height, id, skipPool) { + + width = width || 256; + height = height || 256; + + var canvas = (skipPool) ? document.createElement('canvas') : Phaser.CanvasPool.create(parent, width, height); + + if (typeof id === 'string' && id !== '') + { + canvas.id = id; + } + + canvas.width = width; + canvas.height = height; + canvas.style.display = 'block'; + + return canvas; + + }, + + /** + * Sets the background color behind the canvas. This changes the canvas style property. + * + * @method Phaser.Canvas.setBackgroundColor + * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. + * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setBackgroundColor: function (canvas, color) { + + color = color || 'rgb(0,0,0)'; + + canvas.style.backgroundColor = color; + + return canvas; + + }, + + /** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @method Phaser.Canvas.setTouchAction + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @method Phaser.Canvas.setUserSelect + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. + * If no parent is given it will be added as a child of the document.body. + * + * @method Phaser.Canvas.addToDOM + * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM. + * @param {string|HTMLElement} parent - The DOM element to add the canvas to. + * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + addToDOM: function (canvas, parent, overflowHidden) { + + var target; + + if (overflowHidden === undefined) { overflowHidden = true; } + + if (parent) + { + if (typeof parent === 'string') + { + // hopefully an element ID + target = document.getElementById(parent); + } + else if (typeof parent === 'object' && parent.nodeType === 1) + { + // quick test for a HTMLelement + target = parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + target = document.body; + } + + if (overflowHidden && target.style) + { + target.style.overflow = 'hidden'; + } + + target.appendChild(canvas); + + return canvas; + + }, + + /** + * Removes the given canvas element from the DOM. + * + * @method Phaser.Canvas.removeFromDOM + * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM. + */ + removeFromDOM: function (canvas) { + + if (canvas.parentNode) + { + canvas.parentNode.removeChild(canvas); + } + + }, + + /** + * Sets the transform of the given canvas to the matrix values provided. + * + * @method Phaser.Canvas.setTransform + * @param {CanvasRenderingContext2D} context - The context to set the transform on. + * @param {number} translateX - The value to translate horizontally by. + * @param {number} translateY - The value to translate vertically by. + * @param {number} scaleX - The value to scale horizontally by. + * @param {number} scaleY - The value to scale vertically by. + * @param {number} skewX - The value to skew horizontaly by. + * @param {number} skewY - The value to skew vertically by. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) { + + context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); + + return context; + + }, + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @method Phaser.Canvas.setSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setSmoothingEnabled: function (context, value) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + context[s] = value; + } + + return context; + + }, + + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @method Phaser.Canvas.getSmoothingPrefix + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context. + */ + getSmoothingPrefix: function (context) { + + var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; + + for (var prefix in vendor) + { + var s = vendor[prefix] + 'mageSmoothingEnabled'; + + if (s in context) + { + return s; + } + } + + return null; + + }, + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * + * @method Phaser.Canvas.getSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to check for smoothing on. + * @return {boolean} True if the given context has image smoothing enabled, otherwise false. + */ + getSmoothingEnabled: function (context) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + return context[s]; + } + + }, + + /** + * Sets the CSS image-rendering property to `pixelated` or `crisp-edges`. + * This can remove blurring when the game canvas is scaled up. + * In some browsers this has no visible effect in WEBGL mode. + * Note that if this doesn't given the desired result then see the setSmoothingEnabled. + * + * @method Phaser.Canvas.setImageRenderingCrisp + * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. + * @return {HTMLCanvasElement} Returns the source canvas. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering + * @see https://caniuse.com/#feat=css-crisp-edges + */ + setImageRenderingCrisp: function (canvas) { + + var types = [ '-webkit-optimize-contrast', '-moz-crisp-edges', 'crisp-edges', 'pixelated' ]; + + for (var i = 0; i < types.length; i++) + { + canvas.style['image-rendering'] = types[i]; + } + + canvas.style.msInterpolationMode = 'nearest-neighbor'; + + return canvas; + + }, + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method Phaser.Canvas.setImageRenderingBicubic + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setImageRenderingBicubic: function (canvas) { + + canvas.style['image-rendering'] = 'auto'; + canvas.style.msInterpolationMode = 'bicubic'; + + return canvas; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Abstracts away the use of RAF or setTimeOut for the core game update loop. +* +* @class Phaser.RequestAnimationFrame +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available. +*/ +Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) { + + if (forceSetTimeOut === undefined) { forceSetTimeOut = false; } + + /** + * @property {Phaser.Game} game - The currently running game. + */ + this.game = game; + + /** + * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available. + */ + this.forceSetTimeOut = forceSetTimeOut; + + var vendors = [ + 'ms', + 'moz', + 'webkit', + 'o' + ]; + + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) + { + window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; + } + + /** + * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. + * @private + */ + this._isSetTimeOut = false; + + /** + * @property {function} _onLoop - The function called by the update. + * @private + */ + this._onLoop = null; + + /** + * @property {number} _timeOutID - The callback ID used when calling cancel. + * @private + */ + this._timeOutID = null; + +}; + +Phaser.RequestAnimationFrame.prototype = { + + /** + * Starts the requestAnimationFrame running or setTimeout if unavailable in browser + * @method Phaser.RequestAnimationFrame#start + */ + start: function () { + + this.isRunning = true; + + var _this = this; + + if (!window.requestAnimationFrame || this.forceSetTimeOut) + { + this._isSetTimeOut = true; + + this._onLoop = function () { + return _this.updateSetTimeout(); + }; + + this._timeOutID = window.setTimeout(this._onLoop, 0); + } + else + { + this._isSetTimeOut = false; + + this._onLoop = function (time) { + return _this.updateRAF(time); + }; + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the requestAnimationFrame + * @method Phaser.RequestAnimationFrame#updateRAF + */ + updateRAF: function (rafTime) { + + if (this.isRunning) + { + // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below) + this.game.update(Math.floor(rafTime)); + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the setTimeout. + * @method Phaser.RequestAnimationFrame#updateSetTimeout + */ + updateSetTimeout: function () { + + if (this.isRunning) + { + this.game.update(Date.now()); + + this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); + } + + }, + + /** + * Stops the requestAnimationFrame from running. + * @method Phaser.RequestAnimationFrame#stop + */ + stop: function () { + + if (this._isSetTimeOut) + { + clearTimeout(this._timeOutID); + } + else + { + window.cancelAnimationFrame(this._timeOutID); + } + + this.isRunning = false; + + }, + + /** + * Is the browser using setTimeout? + * @method Phaser.RequestAnimationFrame#isSetTimeOut + * @return {boolean} + */ + isSetTimeOut: function () { + return this._isSetTimeOut; + }, + + /** + * Is the browser using requestAnimationFrame? + * @method Phaser.RequestAnimationFrame#isRAF + * @return {boolean} + */ + isRAF: function () { + return (this._isSetTimeOut === false); + } + +}; + +Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of useful mathematical functions. +* +* These are normally accessed through `game.math`. +* +* @class Phaser.Math +* @static +* @see {@link Phaser.Utils} +* @see {@link Phaser.ArrayUtils} +*/ +Phaser.Math = { + + /** + * Twice PI. + * @property {number} Phaser.Math#PI2 + * @default ~6.283 + */ + PI2: Math.PI * 2, + + /** + * Half PI. + * @property {number} Phaser.Math#HALF_PI + * @default ~1.570 + */ + HALF_PI: Math.PI * 0.5, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#DEG_TO_RAD + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#RAD_TO_DEG + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * Convert degrees to radians. + * + * @method Phaser.Math#degToRad + * @param {number} degrees - Angle in degrees. + * @return {number} Angle in radians. + */ + degToRad: function (degrees) { + + return degrees * Phaser.Math.DEG_TO_RAD; + + }, + + /** + * Convert radians to degrees. + * + * @method Phaser.Math#radToDeg + * @param {number} radians - Angle in radians. + * @return {number} Angle in degrees + */ + radToDeg: function (radians) { + + return radians * Phaser.Math.RAD_TO_DEG; + + }, + + /** + * Given a number, this function returns the closest number that is a power of two. + * This function is from the Starling Framework. + * + * @method Phaser.Math#getNextPowerOfTwo + * @param {number} value - The value to get the closest power of two from. + * @return {number} The closest number that is a power of two. + */ + getNextPowerOfTwo: function (value) { + + if (value > 0 && (value & (value - 1)) === 0) + { + // http://goo.gl/D9kPj + return value; + } + else + { + var result = 1; + + while (result < value) + { + result <<= 1; + } + + return result; + } + + }, + + /** + * Checks if the given dimensions make a power of two texture. + * + * @method Phaser.Math#isPowerOfTwo + * @param {number} width - The width to check. + * @param {number} height - The height to check. + * @return {boolean} True if the width and height are a power of two. + */ + isPowerOfTwo: function (width, height) { + + return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); + + }, + + /** + * Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#random + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} A floating point number between min (inclusive) and max (exclusive). + */ + random: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + return (Math.random() * (max - min) + min); + + }, + + /** + * Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#between + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} An integer between min (inclusive) and max (inclusive). + */ + between: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + min = Math.ceil(min); + max = Math.floor(max); + + return Math.floor(Math.random() * (max - min + 1)) + min; + + }, + + /** + * Two number are fuzzyEqual if their difference is less than epsilon. + * + * @method Phaser.Math#fuzzyEqual + * @param {number} a - The first number to compare. + * @param {number} b - The second number to compare. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {boolean} True if |a-b|b+epsilon + */ + fuzzyGreaterThan: function (a, b, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return a > b - epsilon; + + }, + + /** + * Applies a fuzzy ceil to the given value. + * + * @method Phaser.Math#fuzzyCeil + * @param {number} val - The value to ceil. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} ceiling(val-epsilon) + */ + fuzzyCeil: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.ceil(val - epsilon); + + }, + + /** + * Applies a fuzzy floor to the given value. + * + * @method Phaser.Math#fuzzyFloor + * @param {number} val - The value to floor. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} floor(val+epsilon) + */ + fuzzyFloor: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.floor(val + epsilon); + + }, + + /** + * Averages all values passed to the function and returns the result. + * + * @method Phaser.Math#average + * @params {...number} The numbers to average + * @return {number} The average of all given values. + */ + average: function () { + + var sum = 0; + var len = arguments.length; + + for (var i = 0; i < len; i++) + { + sum += (+arguments[i]); + } + + return sum / len; + + }, + + /** + * @method Phaser.Math#shear + * @param {number} n + * @return {number} n mod 1 + */ + shear: function (n) { + + return n % 1; + + }, + + /** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. + * + * @method Phaser.Math#snapTo + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapTo: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.round(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. + * As will 14 snap to 10... but 16 will snap to 15. + * + * @method Phaser.Math#snapToFloor + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToFloor: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.floor(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. + * As will 14 will snap to 15... but 16 will snap to 20. + * + * @method Phaser.Math#snapToCeil + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToCeil: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.ceil(input / gap); + + return start + input; + + }, + + /** + * Round to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) === 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + * + * @method Phaser.Math#roundTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + roundTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.round(value * p) / p; + + }, + + /** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#floorTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + floorTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.floor(value * p) / p; + + }, + + /** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#ceilTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + ceilTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.ceil(value * p) / p; + + }, + + /** + * Rotates currentAngle towards targetAngle, taking the shortest rotation distance. + * The lerp argument is the amount to rotate by in this call. + * + * @method Phaser.Math#rotateToAngle + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * @return {number} The adjusted angle. + */ + rotateToAngle: function (currentAngle, targetAngle, lerp) { + + if (lerp === undefined) { lerp = 0.05; } + + if (currentAngle === targetAngle) + { + return currentAngle; + } + + if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (Phaser.Math.PI2 - lerp)) + { + currentAngle = targetAngle; + } + else + { + if (Math.abs(targetAngle - currentAngle) > Math.PI) + { + if (targetAngle < currentAngle) + { + targetAngle += Phaser.Math.PI2; + } + else + { + targetAngle -= Phaser.Math.PI2; + } + } + + if (targetAngle > currentAngle) + { + currentAngle += lerp; + } + else if (targetAngle < currentAngle) + { + currentAngle -= lerp; + } + } + + return currentAngle; + + }, + + /** + * Gets the shortest angle between `angle1` and `angle2`. + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method, and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * @method Phaser.Math#getShortestAngle + * @param {number} angle1 - The first angle. In the range -180 to 180. + * @param {number} angle2 - The second angle. In the range -180 to 180. + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ + getShortestAngle: function (angle1, angle2) { + + var difference = angle2 - angle1; + + if (difference === 0) + { + return 0; + } + + var times = Math.floor((difference - (-180)) / 360); + + return difference - (times * 360); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @method Phaser.Math#angleBetween + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetween: function (x1, y1, x2, y2) { + + return Math.atan2(y2 - y1, x2 - x1); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels + * down the screen. + * + * @method Phaser.Math#angleBetweenY + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetweenY: function (x1, y1, x2, y2) { + + return Math.atan2(x2 - x1, y2 - y1); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * @method Phaser.Math#angleBetweenPoints + * @param {Phaser.Point} point1 - The first point. + * @param {Phaser.Point} point2 - The second point. + * @return {number} The angle between the two points, in radians. + */ + angleBetweenPoints: function (point1, point2) { + + return Math.atan2(point2.y - point1.y, point2.x - point1.x); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * @method Phaser.Math#angleBetweenPointsY + * @param {Phaser.Point} point1 + * @param {Phaser.Point} point2 + * @return {number} The angle, in radians. + */ + angleBetweenPointsY: function (point1, point2) { + + return Math.atan2(point2.x - point1.x, point2.y - point1.y); + + }, + + /** + * Reverses an angle. + * @method Phaser.Math#reverseAngle + * @param {number} angleRad - The angle to reverse, in radians. + * @return {number} The reverse angle, in radians. + */ + reverseAngle: function (angleRad) { + + return this.normalizeAngle(angleRad + Math.PI, true); + + }, + + /** + * Normalizes an angle to the [0,2pi) range. + * @method Phaser.Math#normalizeAngle + * @param {number} angleRad - The angle to normalize, in radians. + * @return {number} The angle, fit within the [0,2pi] range, in radians. + */ + normalizeAngle: function (angleRad) { + + angleRad = angleRad % (2 * Math.PI); + return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI; + + }, + + /** + * Adds the given amount to the value, but never lets the value go over the specified maximum. + * + * @method Phaser.Math#maxAdd + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The new value. + */ + maxAdd: function (value, amount, max) { + + return Math.min(value + amount, max); + + }, + + /** + * Subtracts the given amount from the value, but never lets the value go below the specified minimum. + * + * @method Phaser.Math#minSub + * @param {number} value - The base value. + * @param {number} amount - The amount to subtract from the base value. + * @param {number} min - The minimum the value is allowed to be. + * @return {number} The new value. + */ + minSub: function (value, amount, min) { + + return Math.max(value - amount, min); + + }, + + /** + * Ensures that the value always stays between min and max, by wrapping the value around. + * + * If `max` is not larger than `min` the result is 0. + * + * @method Phaser.Math#wrap + * @param {number} value - The value to wrap. + * @param {number} min - The minimum the value is allowed to be. + * @param {number} max - The maximum the value is allowed to be, should be larger than `min`. + * @return {number} The wrapped value. + */ + wrap: function (value, min, max) { + + var range = max - min; + + if (range <= 0) + { + return 0; + } + + var result = (value - min) % range; + + if (result < 0) + { + result += range; + } + + return result + min; + + }, + + /** + * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. + * + * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. + * + * @method Phaser.Math#wrapValue + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The wrapped value. + */ + wrapValue: function (value, amount, max) { + + var diff; + value = Math.abs(value); + amount = Math.abs(amount); + max = Math.abs(max); + diff = (value + amount) % max; + + return diff; + + }, + + /** + * Returns true if the number given is odd. + * + * @method Phaser.Math#isOdd + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is odd. False if the given number is even. + */ + isOdd: function (n) { + + // Does not work with extremely large values + return !!(n & 1); + + }, + + /** + * Returns true if the number given is even. + * + * @method Phaser.Math#isEven + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is even. False if the given number is odd. + */ + isEven: function (n) { + + // Does not work with extremely large values + return !(n & 1); + + }, + + /** + * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.min` function when appropriate. + * + * @method Phaser.Math#min + * @return {number} The lowest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + 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; i < len; i++) + { + if (data[i] < data[min]) + { + min = i; + } + } + + return data[min]; + + }, + + /** + * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.max` function when appropriate. + * + * @method Phaser.Math#max + * @return {number} The largest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + max: function () { + + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + var data = arguments[0]; + } + else + { + var data = arguments; + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i] > data[max]) + { + max = i; + } + } + + return data[max]; + + }, + + /** + * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. + * It will find the lowest matching property value from the given objects. + * + * @method Phaser.Math#minProperty + * @return {number} The lowest value from those given. + */ + 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; i < len; i++) + { + if (data[i][property] < data[min][property]) + { + min = i; + } + } + + return data[min][property]; + + }, + + /** + * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. + * It will find the largest matching property value from the given objects. + * + * @method Phaser.Math#maxProperty + * @return {number} The largest value from those given. + */ + maxProperty: function (property) { + + if (arguments.length === 2 && typeof arguments[1] === 'object') + { + var data = arguments[1]; + } + else + { + var data = arguments.slice(1); + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i][property] > data[max][property]) + { + max = i; + } + } + + return data[max][property]; + + }, + + /** + * Keeps an angle value between -180 and +180; or -PI and PI if radians. + * + * @method Phaser.Math#wrapAngle + * @param {number} angle - The angle value to wrap + * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected. + * @return {number} The new angle value; will be the same as the input angle if it was within bounds. + */ + wrapAngle: function (angle, radians) { + + return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180); + + }, + + /** + * A Linear Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#linearInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + linearInterpolation: function (v, k) { + + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (k < 0) + { + return this.linear(v[0], v[1], f); + } + + if (k > 1) + { + return this.linear(v[m], v[m - 1], m - f); + } + + return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); + + }, + + /** + * A Bezier Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#bezierInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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; + + }, + + /** + * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#catmullRomInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + } + + }, + + /** + * Calculates a linear (interpolation) value over t. + * + * @method Phaser.Math#linear + * @param {number} p0 + * @param {number} p1 + * @param {number} t - A value between 0 and 1. + * @return {number} + */ + linear: function (p0, p1, t) { + + return (p1 - p0) * t + p0; + + }, + + /** + * @method Phaser.Math#bernstein + * @protected + * @param {number} n + * @param {number} i + * @return {number} + */ + bernstein: function (n, i) { + + return this.factorial(n) / this.factorial(i) / this.factorial(n - i); + + }, + + /** + * @method Phaser.Math#factorial + * @param {number} value - the number you want to evaluate + * @return {number} + */ + factorial: function (value) { + + if (value === 0) + { + return 1; + } + + var res = value; + + while(--value) + { + res *= value; + } + + return res; + + }, + + /** + * Calculates a catmum rom value. + * + * @method Phaser.Math#catmullRom + * @protected + * @param {number} p0 + * @param {number} p1 + * @param {number} p2 + * @param {number} p3 + * @param {number} t + * @return {number} + */ + catmullRom: function (p0, p1, p2, p3, t) { + + var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + + }, + + /** + * The absolute difference between two values. + * + * @method Phaser.Math#difference + * @param {number} a - The first value to check. + * @param {number} b - The second value to check. + * @return {number} The absolute difference between the two values. + */ + difference: function (a, b) { + + return Math.abs(a - b); + + }, + + /** + * Round to the next whole number _away_ from zero. + * + * @method Phaser.Math#roundAwayFromZero + * @param {number} value - Any number. + * @return {integer} The rounded value of that number. + */ + roundAwayFromZero: function (value) { + + // "Opposite" of truncate. + return (value > 0) ? Math.ceil(value) : Math.floor(value); + + }, + + /** + * Generate a sine and cosine table simultaneously and extremely quickly. + * The parameters allow you to specify the length, amplitude and frequency of the wave. + * This generator is fast enough to be used in real-time. + * Code based on research by Franky of scene.at + * + * @method Phaser.Math#sinCosGenerator + * @param {number} length - The length of the wave + * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} frequency - The frequency of the sine and cosine table data + * @return {{sin:number[], cos:number[]}} Returns the table data. + */ + sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) { + + if (sinAmplitude === undefined) { sinAmplitude = 1.0; } + if (cosAmplitude === undefined) { cosAmplitude = 1.0; } + if (frequency === undefined) { frequency = 1.0; } + + var sin = sinAmplitude; + var cos = cosAmplitude; + var frq = frequency * Math.PI / length; + + var cosTable = []; + var sinTable = []; + + for (var c = 0; c < length; c++) { + + cos -= sin * frq; + sin += cos * frq; + + cosTable[c] = cos; + sinTable[c] = sin; + + } + + return { sin: sinTable, cos: cosTable, length: length }; + + }, + + /** + * Returns the length of the hypotenuse connecting two segments of given lengths. + * + * @method Phaser.Math#hypot + * @param {number} a + * @param {number} b + * @return {number} The length of the hypotenuse connecting the given lengths. + */ + hypot: function (a, b) { + + return Math.sqrt(a * a + b * b); + + }, + + /** + * Returns the euclidian distance between the two given set of coordinates. + * + * @method Phaser.Math#distance + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance between the two sets of coordinates. + */ + distance: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Returns the euclidean distance squared between the two given set of + * coordinates (cuts out a square root operation before returning). + * + * @method Phaser.Math#distanceSq + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance squared between the two sets of coordinates. + */ + distanceSq: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return dx * dx + dy * dy; + + }, + + /** + * Returns the distance between the two given set of coordinates at the power given. + * + * @method Phaser.Math#distancePow + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} [pow=2] + * @return {number} The distance between the two sets of coordinates. + */ + distancePow: function (x1, y1, x2, y2, pow) { + + if (pow === undefined) { pow = 2; } + + return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); + + }, + + /** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @method Phaser.Math#clamp + * @param {float} v - The value to be clamped. + * @param {float} min - The minimum bounds. + * @param {float} max - The maximum bounds. + * @return {number} The clamped value. + */ + clamp: function (v, min, max) { + + if (v < min) + { + return min; + } + else if (max < v) + { + return max; + } + else + { + return v; + } + + }, + + /** + * Clamp `x` to the range `[a, Infinity)`. + * Roughly the same as `Math.max(x, a)`, except for NaN handling. + * + * @method Phaser.Math#clampBottom + * @param {number} x + * @param {number} a + * @return {number} + */ + clampBottom: function (x, a) { + + return x < a ? a : x; + + }, + + /** + * Checks if two values are within the given tolerance of each other. + * + * @method Phaser.Math#within + * @param {number} a - The first number to check + * @param {number} b - The second number to check + * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range. + * @return {boolean} True if a is <= tolerance of b. + * @see {@link Phaser.Math.fuzzyEqual} + */ + within: function (a, b, tolerance) { + + return (Math.abs(a - b) <= tolerance); + + }, + + /** + * Linear mapping from range to range + * + * @method Phaser.Math#mapLinear + * @param {number} x - The value to map + * @param {number} a1 - First endpoint of the range + * @param {number} a2 - Final endpoint of the range + * @param {number} b1 - First endpoint of the range + * @param {number} b2 - Final endpoint of the range + * @return {number} + */ + mapLinear: function (x, a1, a2, b1, b2) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + + }, + + /** + * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smoothstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smoothstep: function (x, min, max) { + + // Scale, bias and saturate x to 0..1 range + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + // Evaluate polynomial + return x * x * (3 - 2 * x); + + }, + + /** + * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smootherstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smootherstep: function (x, min, max) { + + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + return x * x * x * (x * (x * 6 - 15) + 10); + + }, + + /** + * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. + * + * This works differently from `Math.sign` for values of NaN and -0, etc. + * + * @method Phaser.Math#sign + * @param {number} x + * @return {integer} An integer in {-1, 0, 1} + */ + sign: function (x) { + + return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); + + }, + + /** + * Work out what percentage value `a` is of value `b` using the given base. + * + * @method Phaser.Math#percent + * @param {number} a - The value to work out the percentage for. + * @param {number} b - The value you wish to get the percentage of. + * @param {number} [base=0] - The base value. + * @return {number} The percentage a is of b, between 0 and 1. + */ + percent: function (a, b, base) { + + if (base === undefined) { base = 0; } + + if (a > b || base > b) + { + return 1; + } + else if (a < base || base > a) + { + return 0; + } + else + { + return (a - base) / b; + } + + } + +}; + +/* jshint noempty: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An extremely useful repeatable random data generator. +* +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. +* +* The random number genererator is based on the Alea PRNG, but is modified. +* - https://github.com/coverslide/node-alea +* - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror +* - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404) +* +* @class Phaser.RandomDataGenerator +* @constructor +* @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}). +*/ +Phaser.RandomDataGenerator = function (seeds) { + + if (seeds === undefined) { seeds = []; } + + /** + * @property {number} c - Internal var. + * @private + */ + this.c = 1; + + /** + * @property {number} s0 - Internal var. + * @private + */ + this.s0 = 0; + + /** + * @property {number} s1 - Internal var. + * @private + */ + this.s1 = 0; + + /** + * @property {number} s2 - Internal var. + * @private + */ + this.s2 = 0; + + if (typeof seeds === 'string') + { + this.state(seeds); + } + else + { + this.sow(seeds); + } + +}; + +Phaser.RandomDataGenerator.prototype = { + + /** + * Private random helper. + * + * @method Phaser.RandomDataGenerator#rnd + * @private + * @return {number} + */ + rnd: function () { + + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + + return this.s2; + }, + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.RandomDataGenerator#sow + * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used. + */ + sow: function (seeds) { + + // Always reset to default seed + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + this.c = 1; + + if (!seeds) + { + return; + } + + // Apply any seeds + for (var i = 0; i < seeds.length && (seeds[i] != null); i++) + { + var 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); + } + + }, + + /** + * Internal method that creates a seed hash. + * + * @method Phaser.RandomDataGenerator#hash + * @private + * @param {any} data + * @return {number} hashed value. + */ + hash: function (data) { + + var h, i, n; + n = 0xefc8249d; + data = data.toString(); + + for (i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } + + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + + }, + + /** + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#integer + * @return {number} A random integer between 0 and 2^32. + */ + integer: function() { + + return this.rnd.apply(this) * 0x100000000;// 2^32 + + }, + + /** + * Returns a random real number between 0 and 1. + * + * @method Phaser.RandomDataGenerator#frac + * @return {number} A random real number between 0 and 1. + */ + frac: function() { + + return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 + + }, + + /** + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#real + * @return {number} A random real number between 0 and 2^32. + */ + real: function() { + + return this.integer() + this.frac(); + + }, + + /** + * Returns a random integer between and including min and max. + * + * @method Phaser.RandomDataGenerator#integerInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + integerInRange: function (min, max) { + + return Math.floor(this.realInRange(0, max - min + 1) + min); + + }, + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.RandomDataGenerator#between + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + between: function (min, max) { + + return this.integerInRange(min, max); + + }, + + /** + * Returns a random real number between min and max. + * + * @method Phaser.RandomDataGenerator#realInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + realInRange: function (min, max) { + + return this.frac() * (max - min) + min; + + }, + + /** + * Returns a random real number between -1 and 1. + * + * @method Phaser.RandomDataGenerator#normal + * @return {number} A random real number between -1 and 1. + */ + normal: function () { + + return 1 - 2 * this.frac(); + + }, + + /** + * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 + * + * @method Phaser.RandomDataGenerator#uuid + * @return {string} A valid RFC4122 version4 ID hex string + */ + 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; + + }, + + /** + * Returns a random member of `array`. + * + * @method Phaser.RandomDataGenerator#pick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + pick: function (ary) { + + return ary[this.integerInRange(0, ary.length - 1)]; + + }, + + /** + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.RandomDataGenerator#sign + * @return {number} -1 or +1. + */ + sign: function () { + + return this.pick([-1, 1]); + + }, + + /** + * Returns a random member of `array`, favoring the earlier entries. + * + * @method Phaser.RandomDataGenerator#weightedPick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + weightedPick: function (ary) { + + return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)]; + + }, + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.RandomDataGenerator#timestamp + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random timestamp between min and max. + */ + timestamp: function (min, max) { + + return this.realInRange(min || 946684800000, max || 1577862000000); + + }, + + /** + * Returns a random angle between -180 and 180. + * + * @method Phaser.RandomDataGenerator#angle + * @return {number} A random number between -180 and 180. + */ + angle: function() { + + return this.integerInRange(-180, 180); + + }, + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.RandomDataGenerator#state + * @param {string} [state] - Generator state to be set. + * @return {string} The current state of the generator. + */ + state: function (state) { + + if (typeof state === 'string' && state.match(/^!rnd/)) + { + state = state.split(','); + + this.c = parseFloat(state[1]); + this.s0 = parseFloat(state[2]); + this.s1 = parseFloat(state[3]); + this.s2 = parseFloat(state[4]); + } + + return ['!rnd', this.c, this.s0, this.s1, this.s2].join(','); + + } + +}; + +Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator; + +/** + * @author Timo Hausmann + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** +* A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. +* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. +* Original version at https://github.com/timohausmann/quadtree-js/ +* +* @class Phaser.QuadTree +* @constructor +* @param {number} x - The top left coordinate of the quadtree. +* @param {number} y - The top left coordinate of the quadtree. +* @param {number} width - The width of the quadtree in pixels. +* @param {number} height - The height of the quadtree in pixels. +* @param {number} [maxObjects=10] - The maximum number of objects per node. +* @param {number} [maxLevels=4] - The maximum number of levels to iterate to. +* @param {number} [level=0] - Which level is this? +*/ +Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) { + + /** + * @property {number} maxObjects - The maximum number of objects per node. + * @default + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - The maximum number of levels to break down to. + * @default + */ + this.maxLevels = 4; + + /** + * @property {number} level - The current level. + */ + this.level = 0; + + /** + * @property {object} bounds - Object that contains the quadtree bounds. + */ + this.bounds = {}; + + /** + * @property {array} objects - Array of quadtree children. + */ + this.objects = []; + + /** + * @property {array} nodes - Array of associated child nodes. + */ + this.nodes = []; + + /** + * @property {array} _empty - Internal empty array. + * @private + */ + this._empty = []; + + this.reset(x, y, width, height, maxObjects, maxLevels, level); + +}; + +Phaser.QuadTree.prototype = { + + /** + * Resets the QuadTree. + * + * @method Phaser.QuadTree#reset + * @param {number} x - The top left coordinate of the quadtree. + * @param {number} y - The top left coordinate of the quadtree. + * @param {number} width - The width of the quadtree in pixels. + * @param {number} height - The height of the quadtree in pixels. + * @param {number} [maxObjects=10] - The maximum number of objects per node. + * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. + * @param {number} [level=0] - Which level is this? + */ + 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; + + }, + + /** + * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. + * + * @method Phaser.QuadTree#populate + * @param {Phaser.Group} group - The Group to add to the quadtree. + */ + populate: function (group) { + + group.forEach(this.populateHandler, this, true); + + }, + + /** + * Handler for the populate method. + * + * @method Phaser.QuadTree#populateHandler + * @param {Phaser.Sprite|object} sprite - The Sprite to check. + */ + populateHandler: function (sprite) { + + if (sprite.body && sprite.exists) + { + this.insert(sprite.body); + } + + }, + + /** + * Split the node into 4 subnodes + * + * @method Phaser.QuadTree#split + */ + split: function () { + + // top right node + this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // top left node + this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom left node + this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom right node + this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + }, + + /** + * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. + * + * @method Phaser.QuadTree#insert + * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. + */ + insert: function (body) { + + var i = 0; + var index; + + // if we have subnodes ... + 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.level < this.maxLevels) + { + // Split if we don't already have subnodes + if (this.nodes[0] == null) + { + this.split(); + } + + // Add objects to subnodes + while (i < this.objects.length) + { + index = this.getIndex(this.objects[i]); + + if (index !== -1) + { + // this is expensive - see what we can do about it + this.nodes[index].insert(this.objects.splice(i, 1)[0]); + } + else + { + i++; + } + } + } + + }, + + /** + * Determine which node the object belongs to. + * + * @method Phaser.QuadTree#getIndex + * @param {Phaser.Rectangle|object} rect - The bounds in which to check. + * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. + */ + getIndex: function (rect) { + + // default is that rect doesn't fit, i.e. it straddles the internal quadrants + var index = -1; + + if (rect.x < this.bounds.right && rect.right < this.bounds.right) + { + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-left quadrant of this quadtree + index = 1; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-left quadrant of this quadtree + index = 2; + } + } + else if (rect.x > this.bounds.right) + { + // rect can completely fit within the right quadrants + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-right quadrant of this quadtree + index = 0; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-right quadrant of this quadtree + index = 3; + } + } + + return index; + + }, + + /** + * Return all objects that could collide with the given Sprite or Rectangle. + * + * @method Phaser.QuadTree#retrieve + * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle. + * @return {array} - Array with all detected objects. + */ + 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 rect fits into a subnode .. + if (index !== -1) + { + returnObjects = returnObjects.concat(this.nodes[index].retrieve(source)); + } + else + { + // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed) + 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 the quadtree. + * @method Phaser.QuadTree#clear + */ + 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; + +/** +* Javascript QuadTree +* @version 1.0 +* +* @version 1.3, March 11th 2014 +* @author Richard Davey +* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked +* it massively to add node indexing, removed lots of temp. var creation and significantly +* increased performance as a result. +* +* Original version at https://github.com/timohausmann/quadtree-js/ +*/ + +/** +* @copyright © 2012 Timo Hausmann +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. +* +* @class Phaser.Net +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Net = function (game) { + + this.game = game; + +}; + +Phaser.Net.prototype = { + + /** + * Returns the hostname given by the browser. + * + * @method Phaser.Net#getHostName + * @return {string} + */ + getHostName: function () { + + if (window.location && window.location.hostname) { + return window.location.hostname; + } + + return null; + + }, + + /** + * Compares the given domain name against the hostname of the browser containing the game. + * If the domain name is found it returns true. + * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. + * Do not include 'http://' at the start. + * + * @method Phaser.Net#checkDomainName + * @param {string} domain + * @return {boolean} true if the given domain fragment can be found in the window.location.hostname + */ + checkDomainName: function (domain) { + return window.location.hostname.indexOf(domain) !== -1; + }, + + /** + * Updates a value on the Query String and returns it in full. + * If the value doesn't already exist it is set. + * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. + * Optionally you can redirect to the new url, or just return it as a string. + * + * @method Phaser.Net#updateQueryString + * @param {string} key - The querystring key to update. + * @param {string} value - The new value to be set. If it already exists it will be replaced. + * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. + * @param {string} url - The URL to modify. If none is given it uses window.location.href. + * @return {string} If redirect is false then the modified url and query string is returned. + */ + updateQueryString: function (key, value, redirect, url) { + + if (redirect === undefined) { redirect = false; } + if (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; + } + + }, + + /** + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#getQueryString + * @param {string} [parameter=''] - If specified this will return just the value for that key. + * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. + */ + getQueryString: function (parameter) { + + if (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 && parameter === this.decodeURI(key[0])) + { + return this.decodeURI(key[1]); + } + else + { + output[this.decodeURI(key[0])] = this.decodeURI(key[1]); + } + } + } + + return output; + + }, + + /** + * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and + * decodes it, replacing \ with spaces in the return. Used internally by the Net classes. + * + * @method Phaser.Net#decodeURI + * @param {string} value - The URI component to be decoded. + * @return {string} The decoded value. + */ + decodeURI: function (value) { + return decodeURIComponent(value.replace(/\+/g, " ")); + } + +}; + +Phaser.Net.prototype.constructor = Phaser.Net; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. +* Tweens are hooked into the game clock and pause system, adjusting based on the game state. +* +* TweenManager is based heavily on tween.js by http://soledadpenades.com. +* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. +* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. +* Please see https://github.com/sole/tween.js for a full list of contributors. +* +* @class Phaser.TweenManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.TweenManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * @property {boolean} frameBased + * @default + */ + this.frameBased = false; + + /** + * @property {array} _tweens - All of the currently running tweens. + * @private + */ + this._tweens = []; + + /** + * @property {array} _add - All of the tweens queued to be added in the next update. + * @private + */ + this._add = []; + + this.easeMap = { + + "Power0": Phaser.Easing.Power0, + "Power1": Phaser.Easing.Power1, + "Power2": Phaser.Easing.Power2, + "Power3": Phaser.Easing.Power3, + "Power4": Phaser.Easing.Power4, + + "Linear": Phaser.Easing.Linear.None, + "Quad": Phaser.Easing.Quadratic.Out, + "Cubic": Phaser.Easing.Cubic.Out, + "Quart": Phaser.Easing.Quartic.Out, + "Quint": Phaser.Easing.Quintic.Out, + "Sine": Phaser.Easing.Sinusoidal.Out, + "Expo": Phaser.Easing.Exponential.Out, + "Circ": Phaser.Easing.Circular.Out, + "Elastic": Phaser.Easing.Elastic.Out, + "Back": Phaser.Easing.Back.Out, + "Bounce": Phaser.Easing.Bounce.Out, + + "Quad.easeIn": Phaser.Easing.Quadratic.In, + "Cubic.easeIn": Phaser.Easing.Cubic.In, + "Quart.easeIn": Phaser.Easing.Quartic.In, + "Quint.easeIn": Phaser.Easing.Quintic.In, + "Sine.easeIn": Phaser.Easing.Sinusoidal.In, + "Expo.easeIn": Phaser.Easing.Exponential.In, + "Circ.easeIn": Phaser.Easing.Circular.In, + "Elastic.easeIn": Phaser.Easing.Elastic.In, + "Back.easeIn": Phaser.Easing.Back.In, + "Bounce.easeIn": Phaser.Easing.Bounce.In, + + "Quad.easeOut": Phaser.Easing.Quadratic.Out, + "Cubic.easeOut": Phaser.Easing.Cubic.Out, + "Quart.easeOut": Phaser.Easing.Quartic.Out, + "Quint.easeOut": Phaser.Easing.Quintic.Out, + "Sine.easeOut": Phaser.Easing.Sinusoidal.Out, + "Expo.easeOut": Phaser.Easing.Exponential.Out, + "Circ.easeOut": Phaser.Easing.Circular.Out, + "Elastic.easeOut": Phaser.Easing.Elastic.Out, + "Back.easeOut": Phaser.Easing.Back.Out, + "Bounce.easeOut": Phaser.Easing.Bounce.Out, + + "Quad.easeInOut": Phaser.Easing.Quadratic.InOut, + "Cubic.easeInOut": Phaser.Easing.Cubic.InOut, + "Quart.easeInOut": Phaser.Easing.Quartic.InOut, + "Quint.easeInOut": Phaser.Easing.Quintic.InOut, + "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut, + "Expo.easeInOut": Phaser.Easing.Exponential.InOut, + "Circ.easeInOut": Phaser.Easing.Circular.InOut, + "Elastic.easeInOut": Phaser.Easing.Elastic.InOut, + "Back.easeInOut": Phaser.Easing.Back.InOut, + "Bounce.easeInOut": Phaser.Easing.Bounce.InOut + + }; + + this.game.onPause.add(this._pauseAll, this); + this.game.onResume.add(this._resumeAll, this); + +}; + +Phaser.TweenManager.prototype = { + + /** + * Get all the tween objects in an array. + * @method Phaser.TweenManager#getAll + * @returns {Phaser.Tween[]} Array with all tween objects. + */ + getAll: function () { + + return this._tweens; + + }, + + /** + * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. + * @method Phaser.TweenManager#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._tweens.length; i++) + { + this._tweens[i].pendingDelete = true; + } + + this._add = []; + + }, + + /** + * Remove all tweens from a specific object, array of objects or Group. + * + * @method Phaser.TweenManager#removeFrom + * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. + * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. + */ + removeFrom: function (obj, children) { + + if (children === undefined) { children = true; } + + var i; + var len; + + if (Array.isArray(obj)) + { + for (i = 0, len = obj.length; i < len; i++) + { + this.removeFrom(obj[i]); + } + } + else if (obj.type === Phaser.GROUP && children) + { + for (var i = 0, len = obj.children.length; i < len; i++) + { + this.removeFrom(obj.children[i]); + } + } + else + { + for (i = 0, len = this._tweens.length; i < len; i++) + { + if (obj === this._tweens[i].target) + { + this.remove(this._tweens[i]); + } + } + + for (i = 0, len = this._add.length; i < len; i++) + { + if (obj === this._add[i].target) + { + this.remove(this._add[i]); + } + } + } + + }, + + /** + * Add a new tween into the TweenManager. + * + * @method Phaser.TweenManager#add + * @param {Phaser.Tween} tween - The tween object you want to add. + * @returns {Phaser.Tween} The tween object you added to the manager. + */ + add: function (tween) { + + tween._manager = this; + this._add.push(tween); + + }, + + /** + * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.TweenManager#create + * @param {object} object - Object the tween will be run on. + * @returns {Phaser.Tween} The newly created tween object. + */ + create: function (object) { + + return new Phaser.Tween(object, this.game, this); + + }, + + /** + * Remove a tween from this manager. + * + * @method Phaser.TweenManager#remove + * @param {Phaser.Tween} tween - The tween object you want to remove. + */ + remove: function (tween) { + + var i = this._tweens.indexOf(tween); + + if (i !== -1) + { + this._tweens[i].pendingDelete = true; + } + else + { + i = this._add.indexOf(tween); + + if (i !== -1) + { + this._add[i].pendingDelete = true; + } + } + + }, + + /** + * Update all the tween objects you added to this manager. + * + * @method Phaser.TweenManager#update + * @returns {boolean} Return false if there's no tween to update, otherwise return true. + */ + update: function () { + + var addTweens = this._add.length; + var numTweens = this._tweens.length; + + if (numTweens === 0 && addTweens === 0) + { + return false; + } + + var i = 0; + + while (i < numTweens) + { + if (this._tweens[i].update(this.game.time.time)) + { + i++; + } + else + { + this._tweens.splice(i, 1); + + numTweens--; + } + } + + // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running + if (addTweens > 0) + { + this._tweens = this._tweens.concat(this._add); + this._add.length = 0; + } + + return true; + + }, + + /** + * Checks to see if a particular Sprite is currently being tweened. + * + * The `checkIsRunning` parameter will exclude tweens that have **just** completed or been stopped but haven't yet been removed from the manager. + * + * @method Phaser.TweenManager#isTweening + * @param {object} object - The object to check for tweens against. + * @param {boolean} [checkIsRunning=false] - Also check that the tween is running and is not marked for deletion. + * @returns {boolean} Returns true if the object is currently being tweened, false if not. + */ + isTweening: function(object, checkIsRunning) { + + if (!checkIsRunning) { checkIsRunning = false; } + + return this._tweens.some(function(tween) { + return (tween.target === object) && (!checkIsRunning || (tween.isRunning && !tween.pendingDelete)); + }); + + }, + + /** + * Private. Called by game focus loss. Pauses all currently running tweens. + * + * @method Phaser.TweenManager#_pauseAll + * @private + */ + _pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._pause(); + } + + }, + + /** + * Private. Called by game focus loss. Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#_resumeAll + * @private + */ + _resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._resume(); + } + + }, + + /** + * Pauses all currently running tweens. + * + * @method Phaser.TweenManager#pauseAll + */ + pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].pause(); + } + + }, + + /** + * Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#resumeAll + */ + resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].resume(true); + } + + } + +}; + +Phaser.TweenManager.prototype.constructor = Phaser.TweenManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tween allows you to alter one or more properties of a target object over a defined period of time. +* This can be used for things such as alpha fading Sprites, scaling them or motion. +* Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object +* by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and +* are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. +* +* @class Phaser.Tween +* @constructor +* @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. +* @param {Phaser.Game} game - Current game instance. +* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. +*/ +Phaser.Tween = function (target, game, manager) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. + */ + this.target = target; + + /** + * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween. + */ + this.manager = manager; + + /** + * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween. + */ + this.timeline = []; + + /** + * If set to `true` the current tween will play in reverse. + * If the tween hasn't yet started this has no effect. + * If there are child tweens then all child tweens will play in reverse from the current point. + * @property {boolean} reverse + * @default + */ + this.reverse = false; + + /** + * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. + * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. + * + * @property {number} timeScale + * @default + */ + this.timeScale = 1; + + /** + * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count. + */ + this.repeatCounter = 0; + + /** + * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager. + * @default + * @readonly + */ + this.pendingDelete = false; + + /** + * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onStart + */ + this.onStart = new Phaser.Signal(); + + /** + * The onLoop event is fired if the Tween, or any child tweens loop. + * It will be sent 2 parameters: the target object and this tween. + * + * @property {Phaser.Signal} onLoop + */ + this.onLoop = new Phaser.Signal(); + + /** + * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onRepeat + */ + this.onRepeat = new Phaser.Signal(); + + /** + * The onChildComplete event is fired when the Tween or any of its children completes. + * Fires every time a child completes unless a child is set to repeat forever. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onChildComplete + */ + this.onChildComplete = new Phaser.Signal(); + + /** + * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. + * @default + */ + this.isRunning = false; + + /** + * @property {number} current - The current Tween child being run. + * @default + * @readonly + */ + this.current = 0; + + /** + * @property {object} properties - Target property cache used when building the child data values. + */ + this.properties = {}; + + /** + * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it. + */ + this.chainedTween = null; + + /** + * @property {boolean} isPaused - Is this Tween paused or not? + * @default + */ + this.isPaused = false; + + /** + * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * + * The default value is whatever you've set in TweenManager.frameBased. + * + * @property {boolean} frameBased + * @default + */ + this.frameBased = manager.frameBased; + + /** + * @property {function} _onUpdateCallback - An onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallback = null; + + /** + * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallbackContext = null; + + /** + * @property {number} _pausedTime - Private pause timer. + * @private + * @default + */ + this._pausedTime = 0; + + /** + * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not. + * @private + */ + this._hasStarted = false; +}; + +/** +* A helper for tweening {@link Phaser.Color.createColor color objects}. +* +* It can be passed to {@link #onUpdateCallback}. +* +* ```javascript +* var color = Phaser.Color.createColor(255, 0, 0); // red +* +* var tween = game.add.tween(color).to({ +* r: 0, g: 0, b: 255 // blue +* }); +* +* tween.onUpdateCallback(Phaser.Tween.updateColor); +* +* tween.start(); +* ``` +* +* @method Phaser.Tween.updateColor +* @static +* @param {Phaser.Tween} tween - A Tween with a {@link #target} that is a {@link Phaser.Color.createColor color object}. +*/ +Phaser.Tween.updateColor = function (tween) { + + Phaser.Color.updateColor(tween.target); + +}; + +Phaser.Tween.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#to + * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined || duration <= 0) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.to cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#from + * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.from cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Starts the tween running. Can also be called by the `autoStart` parameter of {@link #to} or {@link #from}. + * This sets the {@link #isRunning} property to `true` and dispatches the {@link #onStart} signal. + * If the tween has a delay set then nothing will start tweening until the delay has expired. + * If the tween is already running, is flagged for deletion (such as after {@link #stop}), + * or has an empty timeline, calling start has no effect and the `onStart` signal is not dispatched. + * + * @method Phaser.Tween#start + * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + start: function (index) { + + if (index === undefined) { index = 0; } + + if (this.pendingDelete) + { + console.warn('Phaser.Tween.start cannot be called after Tween.stop'); + return this; + } + + if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning) + { + return this; + } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + this.manager.add(this); + + this.isRunning = true; + + if (index < 0 || index > this.timeline.length - 1) + { + index = 0; + } + + this.current = index; + + this.timeline[this.current].start(); + + return this; + + }, + + /** + * Stops the tween if running and flags it for deletion from the TweenManager. The tween can't be {@link #start restarted} after this. + * The {@link #onComplete} signal is not dispatched and no chained tweens are started unless the `complete` parameter is set to `true`. + * If you just wish to pause a tween then use {@link #pause} instead. + * If the tween is not running, it is **not** flagged for deletion and can be started again. + * + * @method Phaser.Tween#stop + * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + stop: function (complete) { + + if (complete === undefined) { complete = false; } + + this.isRunning = false; + + this._onUpdateCallback = null; + this._onUpdateCallbackContext = null; + + if (complete) + { + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + } + + this.manager.remove(this); + + return this; + + }, + + /** + * Updates either a single TweenData or all TweenData objects properties to the given value. + * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. + * The property is not checked, so if you pass an invalid one you'll generate a run-time error. + * + * @method Phaser.Tween#updateTweenData + * @param {string} property - The property to update. + * @param {number|function} value - The value to set the property to. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + updateTweenData: function (property, value, index) { + + if (this.timeline.length === 0) { return this; } + + if (index === undefined) { index = 0; } + + if (index === -1) + { + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i][property] = value; + } + } + else + { + this.timeline[index][property] = value; + } + + return this; + + }, + + /** + * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. + * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. + * If you have child tweens and pass -1 as the index value it sets the delay across all of them. + * + * @method Phaser.Tween#delay + * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + delay: function (duration, index) { + + return this.updateTweenData('delay', duration, index); + + }, + + /** + * Sets the number of times this tween will repeat. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. + * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. + * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. + * + * @method Phaser.Tween#repeat + * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeat: function (total, repeatDelay, index) { + + if (repeatDelay === undefined) { repeatDelay = 0; } + + this.updateTweenData('repeatCounter', total, index); + this.updateTweenData('repeatTotal', total, index); + + return this.updateTweenData('repeatDelay', repeatDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will repeat itself. + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#repeatDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatDelay: function (duration, index) { + + return this.updateTweenData('repeatDelay', duration, index); + + }, + + /** + * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. + * Used in combination with repeat you can create endless loops. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. + * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. + * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. + * + * @method Phaser.Tween#yoyo + * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo. + * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyo: function(enable, yoyoDelay, index) { + + if (yoyoDelay === undefined) { yoyoDelay = 0; } + + this.updateTweenData('yoyo', enable, index); + + return this.updateTweenData('yoyoDelay', yoyoDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#yoyoDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyoDelay: function (duration, index) { + + return this.updateTweenData('yoyoDelay', duration, index); + + }, + + /** + * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. + * + * @method Phaser.Tween#easing + * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + easing: function (ease, index) { + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + return this.updateTweenData('easingFunction', ease, index); + + }, + + /** + * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. + * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. + * The interpolation function is only used if the target properties is an array. + * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. + * + * @method Phaser.Tween#interpolation + * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) + * @param {object} [context] - The context under which the interpolation function will be run. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + interpolation: function (interpolation, context, index) { + + if (context === undefined) { context = Phaser.Math; } + + this.updateTweenData('interpolationFunction', interpolation, index); + + return this.updateTweenData('interpolationContext', context, index); + + }, + + /** + * Set how many times this tween and all of its children will repeat. + * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. + * + * @method Phaser.Tween#repeatAll + * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatAll: function (total) { + + if (total === undefined) { total = 0; } + + this.repeatCounter = total; + + return this; + + }, + + /** + * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called + * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. + * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. + * For that you should listen to `onComplete` on the final tween in your chain. + * + * If you pass multiple tweens to this method they will be joined into a single long chain. + * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. + * Any previously chained tweens that may have been set will be overwritten. + * + * @method Phaser.Tween#chain + * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + chain: function () { + + var i = arguments.length; + + while (i--) + { + if (i > 0) + { + arguments[i - 1].chainedTween = arguments[i]; + } + else + { + this.chainedTween = arguments[i]; + } + } + + return this; + + }, + + /** + * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. + * + * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. + * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. + * + * Usage: + * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) + * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) + * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) + * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) + * .loop(); + * @method Phaser.Tween#loop + * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + loop: function (value) { + + if (value === undefined) { value = true; } + + this.repeatCounter = (value) ? -1 : 0; + + return this; + + }, + + /** + * Sets a callback to be fired each time this tween updates. + * + * The callback receives the current Tween, the {@link Phaser.TweenData#value 'value' of the current TweenData}, and the current {@link Phaser.TweenData TweenData}. The second parameter is most useful. + * + * ```javascript + * tween.onUpdateCallback(function (tween, value, tweenData) { + * console.log('Tween running -- percent: %.2f value: %.2f', tweenData.percent, value); + * }); + * ``` + * + * @method Phaser.Tween#onUpdateCallback + * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. + * @param {object} callbackContext - The context in which to call the onUpdate callback. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + onUpdateCallback: function (callback, callbackContext) { + + this._onUpdateCallback = callback; + this._onUpdateCallbackContext = callbackContext; + + return this; + + }, + + /** + * Pauses the tween. Resume playback with Tween.resume. + * + * @method Phaser.Tween#pause + */ + pause: function () { + + this.isPaused = true; + + this._codePaused = true; + + this._pausedTime = this.game.time.time; + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * + * @private + * @method Phaser.Tween#_pause + */ + _pause: function () { + + if (!this._codePaused) + { + this.isPaused = true; + + this._pausedTime = this.game.time.time; + } + + }, + + /** + * Resumes a paused tween. + * + * @method Phaser.Tween#resume + */ + resume: function () { + + if (this.isPaused) + { + this.isPaused = false; + + this._codePaused = false; + + for (var i = 0; i < this.timeline.length; i++) + { + if (!this.timeline[i].isRunning) + { + this.timeline[i].startTime += (this.game.time.time - this._pausedTime); + } + } + } + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * @method Phaser.Tween#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Core tween update function called by the TweenManager. Does not need to be invoked directly. + * + * @method Phaser.Tween#update + * @param {number} time - A timestamp passed in by the TweenManager. + * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). + */ + update: function (time) { + + if (this.pendingDelete || !this.target) + { + return false; + } + + if (this.isPaused) + { + return true; + } + + var status = this.timeline[this.current].update(time); + + if (status === Phaser.TweenData.PENDING) + { + return true; + } + else if (status === Phaser.TweenData.RUNNING) + { + if (!this._hasStarted) + { + this.onStart.dispatch(this.target, this); + this._hasStarted = true; + } + + if (this._onUpdateCallback !== null) + { + this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]); + } + + // In case the update callback modifies this tween + return this.isRunning; + } + else if (status === Phaser.TweenData.LOOPED) + { + if (this.timeline[this.current].repeatCounter === -1) + { + this.onLoop.dispatch(this.target, this); + } + else + { + this.onRepeat.dispatch(this.target, this); + } + + return true; + } + else if (status === Phaser.TweenData.COMPLETE) + { + var complete = false; + + // What now? + if (this.reverse) + { + this.current--; + + if (this.current < 0) + { + this.current = this.timeline.length - 1; + complete = true; + } + } + else + { + this.current++; + + if (this.current === this.timeline.length) + { + this.current = 0; + complete = true; + } + } + + if (complete) + { + // We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it? + if (this.repeatCounter === -1) + { + this.timeline[this.current].start(); + this.onLoop.dispatch(this.target, this); + return true; + } + else if (this.repeatCounter > 0) + { + this.repeatCounter--; + + this.timeline[this.current].start(); + this.onRepeat.dispatch(this.target, this); + return true; + } + else + { + // No more repeats and no more children, so we're done + this.isRunning = false; + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + + return false; + } + } + else + { + // We've still got some children to go + this.onChildComplete.dispatch(this.target, this); + this.timeline[this.current].start(); + return true; + } + } + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * It ignores delay and repeat counts and any chained tweens, but does include child tweens. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.Tween#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate, data) { + + if (this.game === null || this.target === null) + { + return null; + } + + if (frameRate === undefined) { frameRate = 60; } + if (data === undefined) { data = []; } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + for (var i = 0; i < this.timeline.length; i++) + { + data = data.concat(this.timeline[i].generateData(frameRate)); + } + + return data; + + } + +}; + +/** +* @name Phaser.Tween#totalDuration +* @property {number} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds. +*/ +Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', { + + get: function () { + + var total = 0; + + for (var i = 0; i < this.timeline.length; i++) + { + total += this.timeline[i].duration; + } + + return total; + + } + +}); + +Phaser.Tween.prototype.constructor = Phaser.Tween; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the +* starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for +* TweenData objects and can contain multiple TweenData objects. +* +* @class Phaser.TweenData +* @constructor +* @param {Phaser.Tween} parent - The Tween that owns this TweenData object. +*/ +Phaser.TweenData = function (parent) { + + /** + * @property {Phaser.Tween} parent - The Tween which owns this TweenData. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = parent.game; + + /** + * @property {object} vStart - An object containing the values at the start of the tween. + * @private + */ + this.vStart = {}; + + /** + * @property {object} vStartCache - Cached starting values. + * @private + */ + this.vStartCache = {}; + + /** + * @property {object} vEnd - An object containing the values at the end of the tween. + * @private + */ + this.vEnd = {}; + + /** + * @property {object} vEndCache - Cached ending values. + * @private + */ + this.vEndCache = {}; + + /** + * @property {number} duration - The duration of the tween in ms. + * @default + */ + this.duration = 1000; + + /** + * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is. + * @readonly + */ + this.percent = 0; + + /** + * @property {number} value - The output of the easing function for the current {@link #percent}. Depending on the easing function, this will be within [0, 1] or a slightly larger range (e.g., Bounce). When easing is Linear, this will be identical to {@link #percent}. + * @readonly + */ + this.value = 0; + + /** + * @property {number} repeatCounter - If the Tween is set to repeat this is the number of repeats remaining (and `repeatTotal - repeatCounter` is the number of repeats completed). + */ + this.repeatCounter = 0; + + /** + * @property {number} repeatDelay - The amount of time in ms between repeats of this tween. + */ + this.repeatDelay = 0; + + /** + * @property {number} repeatTotal - The total number of times this Tween will repeat. + * @readonly + */ + this.repeatTotal = 0; + + /** + * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween) + * @default + * @todo Appears unused. + */ + this.interpolate = false; + + /** + * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false. + * @default + */ + this.yoyo = false; + + /** + * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween. + */ + this.yoyoDelay = 0; + + /** + * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). + * @default + */ + this.inReverse = false; + + /** + * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. + * @default + */ + this.delay = 0; + + /** + * @property {number} dt - Current time value. + */ + this.dt = 0; + + /** + * @property {number} startTime - The time the Tween started or null if it hasn't yet started. + */ + this.startTime = null; + + /** + * @property {function} easingFunction - The easing function used for the Tween. + * @default Phaser.Easing.Default + */ + this.easingFunction = Phaser.Easing.Default; + + /** + * @property {function} interpolationFunction - The interpolation function used for Array-based Tween. + * @default Phaser.Math.linearInterpolation + */ + this.interpolationFunction = Phaser.Math.linearInterpolation; + + /** + * @property {object} interpolationContext - The interpolation function context used for the Tween. + * @default Phaser.Math + */ + this.interpolationContext = Phaser.Math; + + /** + * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} isFrom - Is this a from tween or a to tween? + * @default + */ + this.isFrom = false; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.PENDING = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.RUNNING = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.LOOPED = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.COMPLETE = 3; + +Phaser.TweenData.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * + * @method Phaser.TweenData#to + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + to: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = false; + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * + * @method Phaser.TweenData#from + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + from: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = true; + + return this; + + }, + + /** + * Starts the Tween running. + * + * @method Phaser.TweenData#start + * @return {Phaser.TweenData} This Tween object. + */ + start: function () { + + this.startTime = this.game.time.time + this.delay; + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + if (this.delay > 0) + { + this.isRunning = false; + } + else + { + this.isRunning = true; + } + + if (this.isFrom) + { + // Reverse them all and instant set them + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + this.parent.target[property] = this.vStart[property]; + } + } + + this.value = 0; + this.repeatCounter = this.repeatTotal; + + return this; + + }, + + /** + * Loads the values from the target object into this Tween. + * + * @private + * @method Phaser.TweenData#loadValues + * @return {Phaser.TweenData} This Tween object. + */ + loadValues: function () { + + for (var property in this.parent.properties) + { + // Load the property from the parent object + this.vStart[property] = this.parent.properties[property]; + + // Check if an Array was provided as property value + if (Array.isArray(this.vEnd[property])) + { + if (this.vEnd[property].length === 0) + { + continue; + } + + if (this.percent === 0) + { + // Put the start value at the beginning of the array + // but we only want to do this once, if the Tween hasn't run before + this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]); + } + } + + if (typeof this.vEnd[property] !== 'undefined') + { + if (typeof this.vEnd[property] === 'string') + { + // Parses relative end values with start as base (e.g.: +10, -3) + this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10); + } + + this.parent.properties[property] = this.vEnd[property]; + } + else + { + // Null tween + this.vEnd[property] = this.vStart[property]; + } + + this.vStartCache[property] = this.vStart[property]; + this.vEndCache[property] = this.vEnd[property]; + } + + return this; + + }, + + /** + * Updates this Tween. This is called automatically by Phaser.Tween. + * + * @protected + * @method Phaser.TweenData#update + * @param {number} time - A timestamp passed in by the Tween parent. + * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. + */ + update: function (time) { + + if (!this.isRunning) + { + if (time >= this.startTime) + { + this.isRunning = true; + } + else + { + return Phaser.TweenData.PENDING; + } + } + else + { + // Is Running, but is waiting to repeat + if (time < this.startTime) + { + return Phaser.TweenData.RUNNING; + } + } + + var ms = (this.parent.frameBased) ? this.game.time.physicsElapsedMS : this.game.time.elapsedMS; + + if (this.parent.reverse) + { + this.dt -= ms * this.parent.timeScale; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += ms * this.parent.timeScale; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + this.parent.target[property] = start + ((end - start) * this.value); + } + } + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + return this.repeat(); + } + + return Phaser.TweenData.RUNNING; + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.TweenData#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate) { + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + var data = []; + var complete = false; + var fps = (1 / frameRate) * 1000; + + do + { + if (this.parent.reverse) + { + this.dt -= fps; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += fps; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + var blob = {}; + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + blob[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + blob[property] = start + ((end - start) * this.value); + } + } + + data.push(blob); + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + complete = true; + } + + } while (!complete); + + if (this.yoyo) + { + var reversed = data.slice(); + reversed.reverse(); + data = data.concat(reversed); + } + + return data; + + }, + + /** + * Checks if this Tween is meant to repeat or yoyo and handles doing so. + * + * @private + * @method Phaser.TweenData#repeat + * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE. + */ + repeat: function () { + + // If not a yoyo and repeatCounter = 0 then we're done + if (this.yoyo) + { + // We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end + if (this.inReverse && this.repeatCounter === 0) + { + // Restore the properties + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + this.inReverse = false; + + return Phaser.TweenData.COMPLETE; + } + + this.inReverse = !this.inReverse; + } + else + { + if (this.repeatCounter === 0) + { + return Phaser.TweenData.COMPLETE; + } + } + + if (this.inReverse) + { + // If inReverse we're going from vEnd to vStartCache + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + } + } + else + { + // If not inReverse we're just repopulating the cache again + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + // -1 means repeat forever, otherwise decrement the repeatCounter + // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total + if (this.repeatCounter > 0) + { + this.repeatCounter--; + } + } + + this.startTime = this.game.time.time; + + if (this.yoyo && this.inReverse) + { + this.startTime += this.yoyoDelay; + } + else if (!this.inReverse) + { + this.startTime += this.repeatDelay; + } + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + return Phaser.TweenData.LOOPED; + + } + +}; + +Phaser.TweenData.prototype.constructor = Phaser.TweenData; + +/* jshint curly: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of easing methods defining ease-in and ease-out curves. +* +* @class Phaser.Easing +*/ +Phaser.Easing = { + + /** + * Linear easing. + * + * @class Phaser.Easing.Linear + */ + Linear: { + + /** + * Linear Easing (no variation). + * + * @method Phaser.Easing.Linear#None + * @param {number} k - The value to be tweened. + * @returns {number} k. + */ + None: function ( k ) { + + return k; + + } + + }, + + /** + * Quadratic easing. + * + * @class Phaser.Easing.Quadratic + */ + Quadratic: { + + /** + * Ease-in. + * + * @method Phaser.Easing.Quadratic#In + * @param {number} k - The value to be tweened. + * @returns {number} k^2. + */ + In: function ( k ) { + + return k * k; + + }, + + /** + * Ease-out. + * + * @method Phaser.Easing.Quadratic#Out + * @param {number} k - The value to be tweened. + * @returns {number} k* (2-k). + */ + Out: function ( k ) { + + return k * ( 2 - k ); + + }, + + /** + * Ease-in/out. + * + * @method Phaser.Easing.Quadratic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; + return - 0.5 * ( --k * ( k - 2 ) - 1 ); + + } + + }, + + /** + * Cubic easing. + * + * @class Phaser.Easing.Cubic + */ + Cubic: { + + /** + * Cubic ease-in. + * + * @method Phaser.Easing.Cubic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k; + + }, + + /** + * Cubic ease-out. + * + * @method Phaser.Easing.Cubic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k + 1; + + }, + + /** + * Cubic ease-in/out. + * + * @method Phaser.Easing.Cubic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k + 2 ); + + } + + }, + + /** + * Quartic easing. + * + * @class Phaser.Easing.Quartic + */ + Quartic: { + + /** + * Quartic ease-in. + * + * @method Phaser.Easing.Quartic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k; + + }, + + /** + * Quartic ease-out. + * + * @method Phaser.Easing.Quartic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return 1 - ( --k * k * k * k ); + + }, + + /** + * Quartic ease-in/out. + * + * @method Phaser.Easing.Quartic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; + return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); + + } + + }, + + /** + * Quintic easing. + * + * @class Phaser.Easing.Quintic + */ + Quintic: { + + /** + * Quintic ease-in. + * + * @method Phaser.Easing.Quintic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k * k; + + }, + + /** + * Quintic ease-out. + * + * @method Phaser.Easing.Quintic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k * k * k + 1; + + }, + + /** + * Quintic ease-in/out. + * + * @method Phaser.Easing.Quintic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); + + } + + }, + + /** + * Sinusoidal easing. + * + * @class Phaser.Easing.Sinusoidal + */ + Sinusoidal: { + + /** + * Sinusoidal ease-in. + * + * @method Phaser.Easing.Sinusoidal#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 1 - Math.cos( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-out. + * + * @method Phaser.Easing.Sinusoidal#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return Math.sin( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-in/out. + * + * @method Phaser.Easing.Sinusoidal#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); + + } + + }, + + /** + * Exponential easing. + * + * @class Phaser.Easing.Exponential + */ + Exponential: { + + /** + * Exponential ease-in. + * + * @method Phaser.Easing.Exponential#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k === 0 ? 0 : Math.pow( 1024, k - 1 ); + + }, + + /** + * Exponential ease-out. + * + * @method Phaser.Easing.Exponential#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); + + }, + + /** + * Exponential ease-in/out. + * + * @method Phaser.Easing.Exponential#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); + return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); + + } + + }, + + /** + * Circular easing. + * + * @class Phaser.Easing.Circular + */ + Circular: { + + /** + * Circular ease-in. + * + * @method Phaser.Easing.Circular#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Math.sqrt( 1 - k * k ); + + }, + + /** + * Circular ease-out. + * + * @method Phaser.Easing.Circular#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return Math.sqrt( 1 - ( --k * k ) ); + + }, + + /** + * Circular ease-in/out. + * + * @method Phaser.Easing.Circular#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); + return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); + + } + + }, + + /** + * Elastic easing. + * + * @class Phaser.Easing.Elastic + */ + Elastic: { + + /** + * Elastic ease-in. + * + * @method Phaser.Easing.Elastic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + + }, + + /** + * Elastic ease-out. + * + * @method Phaser.Easing.Elastic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); + + }, + + /** + * Elastic ease-in/out. + * + * @method Phaser.Easing.Elastic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; + + } + + }, + + /** + * Back easing. + * + * @class Phaser.Easing.Back + */ + Back: { + + /** + * Back ease-in. + * + * @method Phaser.Easing.Back#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s = 1.70158; + return k * k * ( ( s + 1 ) * k - s ); + + }, + + /** + * Back ease-out. + * + * @method Phaser.Easing.Back#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s = 1.70158; + return --k * k * ( ( s + 1 ) * k + s ) + 1; + + }, + + /** + * Back ease-in/out. + * + * @method Phaser.Easing.Back#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s = 1.70158 * 1.525; + if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); + return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); + + } + + }, + + /** + * Bounce easing. + * + * @class Phaser.Easing.Bounce + */ + Bounce: { + + /** + * Bounce ease-in. + * + * @method Phaser.Easing.Bounce#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Phaser.Easing.Bounce.Out( 1 - k ); + + }, + + /** + * Bounce ease-out. + * + * @method Phaser.Easing.Bounce#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if ( k < ( 1 / 2.75 ) ) { + + return 7.5625 * k * k; + + } else if ( k < ( 2 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; + + } else if ( k < ( 2.5 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; + + } else { + + return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; + + } + + }, + + /** + * Bounce ease-in/out. + * + * @method Phaser.Easing.Bounce#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5; + return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5; + + } + + } + +}; + +Phaser.Easing.Default = Phaser.Easing.Linear.None; +Phaser.Easing.Power0 = Phaser.Easing.Linear.None; +Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out; +Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out; +Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out; +Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is the core internal game clock. +* +* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, +* and also handles the standard Timer pool. +* +* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}. +* +* There are different *types* of time in Phaser: +* +* - ***Game time*** always runs at the speed of time in real life. +* +* Unlike wall-clock time, *game time stops when Phaser is paused*. +* +* Game time is used for {@link Phaser.Timer timer events}. +* +* - ***Physics time*** represents the amount of time given to physics calculations. +* +* *When {@link #slowMotion} is in effect physics time runs slower than game time.* +* Like game time, physics time stops when Phaser is paused. +* +* Physics time is used for physics calculations and {@link Phaser.Tween tweens}. +* +* - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time. +* +* This time is independent of Phaser and always progresses, regardless of if Phaser is paused. +* +* @class Phaser.Time +* @constructor +* @param {Phaser.Game} game A reference to the currently running game. +*/ +Phaser.Time = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * The `Date.now()` value when the time was last updated. + * @property {integer} time + * @protected + */ + this.time = 0; + + /** + * The `now` when the previous update occurred. + * @property {number} prevTime + * @protected + */ + this.prevTime = 0; + + /** + * An increasing value representing cumulative milliseconds since an undisclosed epoch. + * + * While this value is in milliseconds and can be used to compute time deltas, + * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference. + * + * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; + * the value can only be relied upon within a particular game instance. + * + * @property {number} now + * @protected + */ + this.now = 0; + + /** + * Elapsed time since the last time update, in milliseconds, based on `now`. + * + * This value _may_ include time that the game is paused/inactive. + * + * While the game is active, this will be similar to (1000 / {@link #fps}). + * + * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {number} elapsed + * @see Phaser.Time.time + * @protected + */ + this.elapsed = 0; + + /** + * The time in ms since the last time update, in milliseconds, based on `time`. + * + * This value is corrected for game pauses and will be "about zero" after a game is resumed. + * + * _Note:_ This is updated once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {integer} elapsedMS + * @protected + */ + this.elapsedMS = 0; + + /** + * The physics update delta, in fractional seconds. + * + * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) + * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system + * is unable to consistently maintain the desired FPS. + * + * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. + * + * @property {number} physicsElapsed + */ + this.physicsElapsed = 1 / 60; + + /** + * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. + * + * @property {number} physicsElapsedMS + */ + this.physicsElapsedMS = (1 / 60) * 1000; + + /** + * The desiredFps multiplier as used by Game.update. + * @property {integer} desiredFpsMult + * @protected + */ + this.desiredFpsMult = 1.0 / 60; + + /** + * The desired frame rate of the game. + * + * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates. + * + * @property {number} _desiredFps + * @private + * @default + */ + this._desiredFps = 60; + + /** + * The suggested frame rate for your game, based on an averaged real frame rate. + * This value is only populated if `Time.advancedTiming` is enabled. + * + * _Note:_ This is not available until after a few frames have passed; until then + * it's set to the same value as desiredFps. + * + * @property {number} suggestedFps + * @default + */ + this.suggestedFps = this.desiredFps; + + /** + * Scaling factor to make the game move smoothly in slow motion (or fast motion) + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * You likely need to adjust {@link #desiredFps} as well such that `desiredFps / slowMotion === 60`. + * + * @property {number} slowMotion + * @default + */ + this.slowMotion = 1.0; + + /** + * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. This isn't expensive, but displaying it with {@link Phaser.Utils.Debug#text} can be, especially in WebGL mode. + * @property {boolean} advancedTiming + * @default + */ + this.advancedTiming = false; + + /** + * Advanced timing result: The number of animation frames received from the browser in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} frames + * @readonly + */ + this.frames = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateLogic logic updates} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} updates + * @readonly + */ + this.updates = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateRender renders} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} renders + * @readonly + */ + this.renders = 0; + + /** + * Advanced timing result: Frames per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} fps + * @readonly + */ + this.fps = 0; + + /** + * Advanced timing result: Logic updates per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} ups + * @readonly + */ + this.ups = 0; + + /** + * Advanced timing result: Renders per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} rps + * @readonly + */ + this.rps = 0; + + /** + * Advanced timing result: The lowest rate the fps has dropped to. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMin + */ + this.fpsMin = 1000; + + /** + * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMax + */ + this.fpsMax = 0; + + /** + * Advanced timing result: The minimum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMin + * @default + */ + this.msMin = 1000; + + /** + * Advanced timing result: The maximum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMax + */ + this.msMax = 0; + + /** + * Records how long the game was last paused, in milliseconds. + * (This is not updated until the game is resumed.) + * @property {number} pauseDuration + */ + this.pauseDuration = 0; + + /** + * @property {number} timeToCall - The value that setTimeout needs to work out when to next update + * @protected + */ + this.timeToCall = 0; + + /** + * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop + * @protected + */ + this.timeExpected = 0; + + /** + * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to. + * @property {Phaser.Timer} events + */ + this.events = new Phaser.Timer(this.game, false); + + /** + * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated + * @private + */ + this._frameCount = 0; + + /** + * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated + * @private + */ + this._elapsedAccumulator = 0; + + /** + * @property {number} _started - The time at which the Game instance started. + * @private + */ + this._started = 0; + + /** + * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. + * @private + */ + this._timeLastSecond = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {boolean} _justResumed - Internal value used to recover from the game pause state. + * @private + */ + this._justResumed = false; + + /** + * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects. + * @private + */ + this._timers = []; + +}; + +Phaser.Time.prototype = { + + /** + * Called automatically by Phaser.Game after boot. Should not be called directly. + * + * @method Phaser.Time#boot + * @protected + */ + boot: function () { + + this._started = Date.now(); + this.time = Date.now(); + this.events.start(); + this.timeExpected = this.time; + + }, + + /** + * Adds an existing Phaser.Timer object to the Timer pool. + * + * @method Phaser.Time#add + * @param {Phaser.Timer} timer - An existing Phaser.Timer object. + * @return {Phaser.Timer} The given Phaser.Timer object. + */ + add: function (timer) { + + this._timers.push(timer); + + return timer; + + }, + + /** + * Creates a new stand-alone Phaser.Timer object. + * + * @method Phaser.Time#create + * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). + * @return {Phaser.Timer} The Timer object that was created. + */ + create: function (autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + var timer = new Phaser.Timer(this.game, autoDestroy); + + this._timers.push(timer); + + return timer; + + }, + + /** + * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer. + * + * @method Phaser.Time#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._timers.length; i++) + { + this._timers[i].destroy(); + } + + this._timers = []; + + this.events.removeAll(); + + }, + + /** + * Refreshes the Time.time and Time.elapsedMS properties from the system clock. + * + * @method Phaser.Time#refresh + */ + refresh: function () { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + }, + + /** + * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. + * + * @method Phaser.Time#update + * @protected + * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}. + */ + update: function (time) { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + // 'now' is currently still holding the time of the last call, move it into prevTime + this.prevTime = this.now; + + // update 'now' to hold the current time + // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now) + this.now = time; + + // elapsed time between previous call and now - this could be a high resolution value + this.elapsed = this.now - this.prevTime; + + if (this.game.raf._isSetTimeOut) + { + // console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time); + + // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game + this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time))); + + // time when the next call is expected if using timers + this.timeExpected = time + this.timeToCall; + + // console.log('Time expect', this.timeExpected); + } + + if (this.advancedTiming) + { + this.updateAdvancedTiming(); + } + + // Paused but still running? + if (!this.game.paused) + { + // Our internal Phaser.Timer + this.events.update(this.time); + + if (this._timers.length) + { + this.updateTimers(); + } + } + + }, + + /** + * Handles the updating of the Phaser.Timers (if any) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateTimers + * @private + */ + updateTimers: function () { + + // Any game level timers + var i = 0; + var len = this._timers.length; + + while (i < len) + { + if (this._timers[i].update(this.time)) + { + i++; + } + else + { + // Timer requests to be removed + this._timers.splice(i, 1); + len--; + } + } + + }, + + /** + * Handles the updating of the advanced timing values (if enabled) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateAdvancedTiming + * @private + */ + updateAdvancedTiming: function () { + + // count the number of time.update calls + this._frameCount++; + this._elapsedAccumulator += this.elapsed; + + // occasionally recalculate the suggestedFps based on the accumulated elapsed time + if (this._frameCount >= this._desiredFps * 2) + { + // this formula calculates suggestedFps in multiples of 5 fps + this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5; + this._frameCount = 0; + this._elapsedAccumulator = 0; + } + + this.msMin = Math.min(this.msMin, this.elapsed); + this.msMax = Math.max(this.msMax, this.elapsed); + + this.frames++; + + if (this.now > this._timeLastSecond + 1000) + { + var interval = this.now - this._timeLastSecond; + this.fps = Math.round((this.frames * 1000) / interval); + this.ups = Math.round((this.updates * 1000) / interval); + this.rps = Math.round((this.renders * 1000) / interval); + this.fpsMin = Math.min(this.fpsMin, this.fps); + this.fpsMax = Math.max(this.fpsMax, this.fps); + this._timeLastSecond = this.now; + this.frames = 0; + this.updates = 0; + this.renders = 0; + } + + }, + + /** + * Counts one logic update (if advanced timing is enabled). + * + * @method Phaser.Time#countUpdate + * @private + */ + countUpdate: function () { + + if (this.advancedTiming) + { + this.updates++; + } + + }, + + /** + * Counts one render (if advanced timing is enabled). + * + * @method Phaser.Time#countRender + * @private + */ + countRender: function () { + + if (this.advancedTiming) + { + this.renders++; + } + + }, + + /** + * Called when the game enters a paused state. + * + * @method Phaser.Time#gamePaused + * @private + */ + gamePaused: function () { + + this._pauseStarted = Date.now(); + + this.events.pause(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._pause(); + } + + }, + + /** + * Called when the game resumes from a paused state. + * + * @method Phaser.Time#gameResumed + * @private + */ + gameResumed: function () { + + // Set the parameter which stores Date.now() to make sure it's correct on resume + this.time = Date.now(); + + this.pauseDuration = this.time - this._pauseStarted; + + this.events.resume(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._resume(); + } + + }, + + /** + * The number of seconds that have elapsed since the game was started. + * + * @method Phaser.Time#totalElapsedSeconds + * @return {number} The number of seconds that have elapsed since the game was started. + */ + totalElapsedSeconds: function() { + return (this.time - this._started) * 0.001; + }, + + /** + * How long has passed since the given time. + * + * @method Phaser.Time#elapsedSince + * @param {number} since - The time you want to measure against. + * @return {number} The difference between the given time and now. + */ + elapsedSince: function (since) { + return this.time - since; + }, + + /** + * How long has passed since the given time (in seconds). + * + * @method Phaser.Time#elapsedSecondsSince + * @param {number} since - The time you want to measure (in seconds). + * @return {number} Duration between given time and now (in seconds). + */ + elapsedSecondsSince: function (since) { + return (this.time - since) * 0.001; + }, + + /** + * Resets the private _started value to now and removes all currently running Timers. + * + * @method Phaser.Time#reset + */ + reset: function () { + + this._started = this.time; + this.removeAll(); + + } + +}; + +/** +* The number of logic updates per second. +* +* This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. +* +* The render rate is unaffected unless you also turn off {@link Phaser.Game#forceSingleRender}. +* +* @name Phaser.Time#desiredFps +* @type {integer} +* @default 60 +*/ +Object.defineProperty(Phaser.Time.prototype, "desiredFps", { + + get: function () { + + return this._desiredFps; + + }, + + set: function (value) { + + this._desiredFps = value; + + // Set the physics elapsed time... this will always be 1 / this.desiredFps + // because we're using fixed time steps in game.update + this.physicsElapsed = 1 / value; + + this.physicsElapsedMS = this.physicsElapsed * 1000; + + this.desiredFpsMult = 1.0 / value; + + } + +}); + +Phaser.Time.prototype.constructor = Phaser.Time; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback. +* Many different timer events, with individual delays, can be added to the same Timer. +* +* All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. +* +* Timers are based on real life time, adjusted for game pause durations. +* That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account. +* +* @class Phaser.Timer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). +*/ +Phaser.Timer = function (game, autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * True if the Timer is actively running. + * + * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer. + * @property {boolean} running + * @default + * @readonly + */ + this.running = false; + + /** + * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). + * @property {boolean} autoDestroy + */ + this.autoDestroy = autoDestroy; + + /** + * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending. + * @readonly + * @default + */ + this.expired = false; + + /** + * @property {number} elapsed - Elapsed time since the last frame (in ms). + * @protected + */ + this.elapsed = 0; + + /** + * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. + */ + this.events = []; + + /** + * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. + * + * The signal is supplied with one argument, `timer`, which is this Timer object. + * + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {number} nextTick - The time the next tick will occur. + * @readonly + * @protected + */ + this.nextTick = 0; + + /** + * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. + */ + this.timeCap = 1000; + + /** + * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. + * @readonly + * @default + */ + this.paused = false; + + /** + * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {number} _started - The time at which this Timer instance started running. + * @private + * @default + */ + this._started = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {number} _pauseTotal - Total paused time. + * @private + */ + this._pauseTotal = 0; + + /** + * @property {number} _now - The current start-time adjusted time. + * @private + */ + this._now = Date.now(); + + /** + * @property {number} _len - Temp. array length variable. + * @private + */ + this._len = 0; + + /** + * @property {number} _marked - Temp. counter variable. + * @private + */ + this._marked = 0; + + /** + * @property {number} _i - Temp. array counter variable. + * @private + */ + this._i = 0; + + /** + * @property {number} _diff - Internal cache var. + * @private + */ + this._diff = 0; + + /** + * @property {number} _newTick - Internal cache var. + * @private + */ + this._newTick = 0; + +}; + +/** +* Number of milliseconds in a minute. +* @constant +* @type {integer} +*/ +Phaser.Timer.MINUTE = 60000; + +/** +* Number of milliseconds in a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.SECOND = 1000; + +/** +* Number of milliseconds in half a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.HALF = 500; + +/** +* Number of milliseconds in a quarter of a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.QUARTER = 250; + +Phaser.Timer.prototype = { + + /** + * Creates a new TimerEvent on this Timer. + * + * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. + * + * @method Phaser.Timer#create + * @private + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {boolean} loop - Should the event loop or not? + * @param {number} repeatCount - The number of times the event will repeat. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {any[]} arguments - The values to be sent to your callback function when it is called. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + create: function (delay, loop, repeatCount, callback, callbackContext, args) { + + delay = Math.round(delay); + + var tick = delay; + + if (this._now === 0) + { + tick += this.game.time.time; + } + else + { + tick += this._now; + } + + var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args); + + this.events.push(event); + + this.order(); + + this.expired = false; + + return event; + + }, + + /** + * Adds a new Event to this Timer. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#add + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + add: function (delay, callback, callbackContext) { + + return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. + * If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#repeat + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + repeat: function (delay, repeatCount, callback, callbackContext) { + + return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4)); + + }, + + /** + * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#loop + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + loop: function (delay, callback, callbackContext) { + + return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Starts this Timer running. + * @method Phaser.Timer#start + * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start. + */ + start: function (delay) { + + if (this.running) + { + return; + } + + this._started = this.game.time.time + (delay || 0); + + this.running = true; + + for (var i = 0; i < this.events.length; i++) + { + this.events[i].tick = this.events[i].delay + this._started; + } + + }, + + /** + * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. + * @method Phaser.Timer#stop + * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain. + */ + stop: function (clearEvents) { + + this.running = false; + + if (clearEvents === undefined) { clearEvents = true; } + + if (clearEvents) + { + this.events.length = 0; + } + + }, + + /** + * Removes a pending TimerEvent from the queue. + * @param {Phaser.TimerEvent} event - The event to remove from the queue. + * @method Phaser.Timer#remove + */ + remove: function (event) { + + for (var i = 0; i < this.events.length; i++) + { + if (this.events[i] === event) + { + this.events[i].pendingDelete = true; + return true; + } + } + + return false; + + }, + + /** + * Orders the events on this Timer so they are in tick order. + * This is called automatically when new events are created. + * @method Phaser.Timer#order + * @protected + */ + order: function () { + + if (this.events.length > 0) + { + // Sort the events so the one with the lowest tick is first + this.events.sort(this.sortHandler); + + this.nextTick = this.events[0].tick; + } + + }, + + /** + * Sort handler used by Phaser.Timer.order. + * @method Phaser.Timer#sortHandler + * @private + */ + sortHandler: function (a, b) { + + if (a.tick < b.tick) + { + return -1; + } + else if (a.tick > b.tick) + { + return 1; + } + + return 0; + + }, + + /** + * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values. + * + * @method Phaser.Timer#clearPendingEvents + * @protected + */ + 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; + + }, + + /** + * The main Timer update event, called automatically by Phaser.Time.update. + * + * @method Phaser.Timer#update + * @protected + * @param {number} time - The time from the core game clock. + * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. + */ + update: function (time) { + + if (this.paused) + { + return true; + } + + this.elapsed = time - this._now; + this._now = time; + + // spike-dislike + if (this.elapsed > this.timeCap) + { + // For some reason the time between now and the last time the game was updated was larger than our timeCap. + // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause. + // In this case we need to adjust the TimerEvents and nextTick. + this.adjustEvents(time - this.elapsed); + } + + this._marked = 0; + + // Clears events marked for deletion and resets _len and _i to 0. + this.clearPendingEvents(); + + if (this.running && this._now >= this.nextTick && this._len > 0) + { + while (this._i < this._len && this.running) + { + var event = this.events[this._i]; + + if (this._now >= event.tick && !event.pendingDelete) + { + // (now + delay) - (time difference from last tick to now) + this._newTick = (this._now + event.delay) - (this._now - event.tick); + + if (this._newTick < 0) + { + this._newTick = this._now + event.delay; + } + + if (event.loop === true) + { + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else if (event.repeatCount > 0) + { + event.repeatCount--; + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else + { + this._marked++; + event.pendingDelete = true; + event.callback.apply(event.callbackContext, event.args); + } + + this._i++; + } + else + { + break; + } + } + + // Are there any events left? + 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; + } + + }, + + /** + * Pauses the Timer and all events in the queue. + * @method Phaser.Timer#pause + */ + pause: function () { + + if (!this.running) + { + return; + } + + this._codePaused = true; + + if (this.paused) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Internal pause/resume control - user code should use Timer.pause instead. + * @method Phaser.Timer#_pause + * @private + */ + _pause: function () { + + if (this.paused || !this.running) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Adjusts the time of all pending events and the nextTick by the given baseTime. + * + * @method Phaser.Timer#adjustEvents + * @protected + */ + adjustEvents: function (baseTime) { + + for (var i = 0; i < this.events.length; i++) + { + if (!this.events[i].pendingDelete) + { + // Work out how long there would have been from when the game paused until the events next tick + var t = this.events[i].tick - baseTime; + + if (t < 0) + { + t = 0; + } + + // Add the difference on to the time now + this.events[i].tick = this._now + t; + } + } + + var d = this.nextTick - baseTime; + + if (d < 0) + { + this.nextTick = this._now; + } + else + { + this.nextTick = this._now + d; + } + + }, + + /** + * Resumes the Timer and updates all pending events. + * + * @method Phaser.Timer#resume + */ + resume: function () { + + if (!this.paused) + { + return; + } + + var now = this.game.time.time; + this._pauseTotal += now - this._now; + this._now = now; + + this.adjustEvents(this._pauseStarted); + + this.paused = false; + this._codePaused = false; + + }, + + /** + * Internal pause/resume control - user code should use Timer.resume instead. + * @method Phaser.Timer#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#removeAll + */ + removeAll: function () { + + this.onComplete.removeAll(); + this.events.length = 0; + this._len = 0; + this._i = 0; + + }, + + /** + * Destroys this Timer. Any pending Events are not dispatched. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#destroy + */ + destroy: function () { + + this.onComplete.removeAll(); + this.running = false; + this.expired = true; + this.events = []; + this._len = 0; + this._i = 0; + + } + +}; + +/** +* @name Phaser.Timer#next +* @property {number} next - The time at which the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "next", { + + get: function () { + return this.nextTick; + } + +}); + +/** +* @name Phaser.Timer#duration +* @property {number} duration - The duration in ms remaining until the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "duration", { + + get: function () { + + if (this.running && this.nextTick > this._now) + { + return this.nextTick - this._now; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#length +* @property {number} length - The number of pending events in the queue. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "length", { + + get: function () { + return this.events.length; + } + +}); + +/** +* @name Phaser.Timer#ms +* @property {number} ms - The duration in milliseconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "ms", { + + get: function () { + + if (this.running) + { + return this._now - this._started - this._pauseTotal; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#seconds +* @property {number} seconds - The duration in seconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "seconds", { + + get: function () { + + if (this.running) + { + return this.ms * 0.001; + } + else + { + return 0; + } + + } + +}); + +Phaser.Timer.prototype.constructor = Phaser.Timer; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TimerEvent is a single event that is processed by a Phaser.Timer. +* +* It consists of a delay, which is a value in milliseconds after which the event will fire. +* When the event fires it calls a specific callback with the specified arguments. +* +* TimerEvents are removed by their parent timer once finished firing or repeating. +* +* Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. +* +* @class Phaser.TimerEvent +* @constructor +* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. +* @param {number} delay - The delay in ms at which this TimerEvent fires. +* @param {number} tick - The tick is the next game clock time that this event will fire at. +* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times. +* @param {boolean} loop - True if this TimerEvent loops, otherwise false. +* @param {function} callback - The callback that will be called when the TimerEvent occurs. +* @param {object} callbackContext - The context in which the callback will be called. +* @param {any[]} arguments - Additional arguments to be passed to the callback. +*/ +Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) { + + /** + * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. + * @protected + * @readonly + */ + this.timer = timer; + + /** + * @property {number} delay - The delay in ms at which this TimerEvent fires. + */ + this.delay = delay; + + /** + * @property {number} tick - The tick is the next game clock time that this event will fire at. + */ + this.tick = tick; + + /** + * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times. + */ + this.repeatCount = repeatCount - 1; + + /** + * @property {boolean} loop - True if this TimerEvent loops, otherwise false. + */ + this.loop = loop; + + /** + * @property {function} callback - The callback that will be called when the TimerEvent occurs. + */ + this.callback = callback; + + /** + * @property {object} callbackContext - The context in which the callback will be called. + */ + this.callbackContext = callbackContext; + + /** + * @property {any[]} arguments - Additional arguments to be passed to the callback. + */ + this.args = args; + + /** + * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion. + * @protected + */ + this.pendingDelete = false; + +}; + +Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Manager is used to add, play and update Phaser Animations. +* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. +* +* @class Phaser.AnimationManager +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. +*/ +Phaser.AnimationManager = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = sprite.game; + + /** + * The currently displayed Frame of animation, if any. + * This property is only set once an Animation starts playing. Until that point it remains set as `null`. + * + * @property {Phaser.Frame} currentFrame + * @default + */ + this.currentFrame = null; + + /** + * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any. + * @default + */ + this.currentAnim = null; + + /** + * @property {boolean} updateIfVisible - Update the animation data only while the the sprite is {@link Phaser.Sprite#visible}. Set to `false` to continue updating while the sprite is invisible. + * @default + */ + this.updateIfVisible = true; + + /** + * @property {boolean} isLoaded - Set to true once animation data has been loaded. + * @default + */ + this.isLoaded = false; + + /** + * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. + * @private + * @default + */ + this._frameData = null; + + /** + * @property {object} _anims - An internal object that stores all of the Animation instances. + * @private + */ + this._anims = {}; + + /** + * @property {object} _outputFrames - An internal object to help avoid gc. + * @private + */ + this._outputFrames = []; + +}; + +Phaser.AnimationManager.prototype = { + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#loadFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + loadFrameData: function (frameData, frame) { + + if (frameData === undefined) + { + return false; + } + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(frameData); + } + } + + this._frameData = frameData; + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#copyFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + copyFrameData: function (frameData, frame) { + + this._frameData = frameData.clone(); + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(this._frameData); + } + } + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. + * Animations added in this way are played back with the play function. + * + * @method Phaser.AnimationManager#add + * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". + * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. + * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. + * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? + * @return {Phaser.Animation} The Animation object that was created. + */ + add: function (name, frames, frameRate, loop, useNumericIndex) { + + frames = frames || []; + frameRate = frameRate || 60; + + if (loop === undefined) { loop = false; } + + // If they didn't set the useNumericIndex then let's at least try and guess it + if (useNumericIndex === undefined) + { + if (frames && typeof frames[0] === 'number') + { + useNumericIndex = true; + } + else + { + useNumericIndex = false; + } + } + + this._outputFrames = []; + + 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]; + + if (this.sprite.tilingTexture) + { + this.sprite.refreshTexture = true; + } + + return this._anims[name]; + + }, + + /** + * Check whether the frames in the given array are valid and exist. + * + * @method Phaser.AnimationManager#validateFrames + * @param {Array} frames - An array of frames to be validated. + * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) + * @return {boolean} True if all given Frames are valid, otherwise false. + */ + validateFrames: function (frames, useNumericIndex) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + + for (var i = 0; i < frames.length; i++) + { + if (useNumericIndex === true) + { + if (frames[i] > this._frameData.total) + { + return false; + } + } + else + { + if (this._frameData.checkFrameName(frames[i]) === false) + { + return false; + } + } + } + + return true; + + }, + + /** + * Play an animation based on the given key. The animation should previously have been added via `animations.add` + * + * If the requested animation is already playing this request will be ignored. + * If you need to reset an already running animation do so directly on the Animation object itself. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.AnimationManager#play + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation instance. + */ + 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); + } + + return this.currentAnim; + } + else + { + if (this.currentAnim && this.currentAnim.isPlaying) + { + this.currentAnim.stop(); + } + + this.currentAnim = this._anims[name]; + this.currentAnim.paused = false; + this.currentFrame = this.currentAnim.currentFrame; + return this.currentAnim.play(frameRate, loop, killOnComplete); + } + } + + }, + + /** + * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. + * The currentAnim property of the AnimationManager is automatically set to the animation given. + * + * @method Phaser.AnimationManager#stop + * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. + * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) + */ + stop: function (name, resetFrame) { + + if (resetFrame === undefined) { resetFrame = false; } + + if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name)) + { + this.currentAnim.stop(resetFrame); + } + + }, + + /** + * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. + * + * @method Phaser.AnimationManager#update + * @protected + * @return {boolean} True if a new animation frame has been set, otherwise false. + */ + update: function () { + + if (this.updateIfVisible && !this.sprite.visible) + { + return false; + } + + if (this.currentAnim && this.currentAnim.update()) + { + this.currentFrame = this.currentAnim.currentFrame; + return true; + } + + return false; + + }, + + /** + * Advances by the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.next(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Moves backwards the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.previous(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Returns an animation that was previously added by name. + * + * @method Phaser.AnimationManager#getAnimation + * @param {string} name - The name of the animation to be returned, e.g. "fire". + * @return {Phaser.Animation} The Animation instance, if found, otherwise null. + */ + getAnimation: function (name) { + + if (typeof name === 'string') + { + if (this._anims[name]) + { + return this._anims[name]; + } + } + + return null; + + }, + + /** + * Refreshes the current frame data back to the parent Sprite and also resets the texture data. + * + * @method Phaser.AnimationManager#refreshFrame + */ + refreshFrame: function () { + + // TODO + // this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); + + }, + + /** + * Destroys all references this AnimationManager contains. + * Iterates through the list of animations stored in this manager and calls destroy on each of them. + * + * @method Phaser.AnimationManager#destroy + */ + destroy: function () { + + var anim = null; + + for (var anim in this._anims) + { + if (this._anims.hasOwnProperty(anim)) + { + this._anims[anim].destroy(); + } + } + + this._anims = {}; + this._outputFrames = []; + this._frameData = null; + this.currentAnim = null; + this.currentFrame = null; + this.sprite = null; + this.game = null; + + } + +}; + +Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager; + +/** +* @name Phaser.AnimationManager#frameData +* @property {Phaser.FrameData} frameData - The current animations FrameData. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', { + + get: function () { + return this._frameData; + } + +}); + +/** +* @name Phaser.AnimationManager#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', { + + get: function () { + + return this._frameData.total; + } + +}); + +/** +* @name Phaser.AnimationManager#paused +* @property {boolean} paused - Gets and sets the paused state of the current animation. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', { + + get: function () { + + return this.currentAnim.isPaused; + + }, + + set: function (value) { + + this.currentAnim.paused = value; + + } + +}); + +/** +* @name Phaser.AnimationManager#name +* @property {string} name - Gets the current animation name, if set. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'name', { + + get: function () { + + if (this.currentAnim) + { + return this.currentAnim.name; + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.index; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'number' && this._frameData && (gotFrame = this._frameData.getFrame(value))) + { + this.currentFrame = gotFrame; + this.sprite.setFrame(this.currentFrame); + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frameName +* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.name; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'string' && this._frameData && (gotFrame = this._frameData.getFrameByName(value))) + { + this.currentFrame = gotFrame; + this._frameIndex = this.currentFrame.index; + this.sprite.setFrame(this.currentFrame); + } + else + { + console.warn('Cannot set frameName: ' + value); + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Animation instance contains a single animation and the controls to play it. +* +* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. +* +* @class Phaser.Animation +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Sprite} parent - A reference to the owner of this Animation. +* @param {string} name - The unique name for this animation, used in playback commands. +* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. +* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +*/ +Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) { + + if (loop === undefined) { loop = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. + * @private + */ + this._parent = parent; + + /** + * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. + * @private + */ + this._frameData = frameData; + + /** + * @property {string} name - The user defined name given to this Animation. + */ + this.name = name; + + /** + * @property {array} _frames + * @private + */ + this._frames = []; + this._frames = this._frames.concat(frames); + + /** + * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. + */ + this.delay = 1000 / frameRate; + + /** + * @property {boolean} loop - The loop state of the Animation. + */ + this.loop = loop; + + /** + * @property {number} loopCount - The number of times the animation has looped since it was last started. + */ + this.loopCount = 0; + + /** + * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? + * @default + */ + this.killOnComplete = false; + + /** + * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. + * @default + */ + this.isFinished = false; + + /** + * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. + * @default + */ + this.isPlaying = false; + + /** + * @property {boolean} isPaused - The paused state of the Animation. + * @default + */ + this.isPaused = false; + + /** + * @property {boolean} _pauseStartTime - The time the animation paused. + * @private + * @default + */ + this._pauseStartTime = 0; + + /** + * @property {number} _frameIndex + * @private + * @default + */ + this._frameIndex = 0; + + /** + * @property {number} _frameDiff + * @private + * @default + */ + this._frameDiff = 0; + + /** + * @property {number} _frameSkip + * @private + * @default + */ + this._frameSkip = 1; + + /** + * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. + */ + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + /** + * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. + */ + this.onStart = new Phaser.Signal(); + + /** + * This event is dispatched when the Animation changes frame. + * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. + * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations + * will automatically frame-skip to try and claw back time, so do not base your code on expecting to + * receive a perfectly sequential set of frames from this event. + * @property {Phaser.Signal|null} onUpdate + * @default + */ + this.onUpdate = null; + + /** + * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {boolean} isReversed - Indicates if the animation will play backwards. + * @default + */ + this.isReversed = false; + + // Set-up some event listeners + this.game.onPause.add(this.onPause, this); + this.game.onResume.add(this.onResume, this); + +}; + +Phaser.Animation.prototype = { + + /** + * Plays this animation. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.Animation#play + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} - A reference to this Animation instance. + */ + play: function (frameRate, loop, killOnComplete) { + + if (typeof frameRate === 'number') + { + // If they set a new frame rate then use it, otherwise use the one set on creation + this.delay = 1000 / frameRate; + } + + if (typeof loop === 'boolean') + { + // If they set a new loop value then use it, otherwise use the one set on creation + this.loop = loop; + } + + if (typeof killOnComplete !== 'undefined') + { + // Remove the parent sprite once the animation has finished? + this.killOnComplete = killOnComplete; + } + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = this.isReversed ? this._frames.length - 1 : 0; + this.updateCurrentFrame(false, true); + + this._parent.events.onAnimationStart$dispatch(this._parent, this); + + this.onStart.dispatch(this._parent, this); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + return this; + + }, + + /** + * Sets this animation back to the first frame and restarts the animation. + * + * @method Phaser.Animation#restart + */ + restart: function () { + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = 0; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + this._parent.setFrame(this.currentFrame); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + this.onStart.dispatch(this._parent, this); + + }, + + /** + * Reverses the animation direction. + * + * @method Phaser.Animation#reverse + * @return {Phaser.Animation} The animation instance. + */ + reverse: function () { + + this.reversed = !this.reversed; + + return this; + + }, + + /** + * Reverses the animation direction for the current/next animation only + * Once the onComplete event is called this method will be called again and revert + * the reversed state. + * + * @method Phaser.Animation#reverseOnce + * @return {Phaser.Animation} The animation instance. + */ + reverseOnce: function () { + + this.onComplete.addOnce(this.reverse, this); + + return this.reverse(); + + }, + + /** + * Sets this animations playback to a given frame with the given ID. + * + * @method Phaser.Animation#setFrame + * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. + * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. + */ + setFrame: function(frameId, useLocalFrameIndex) { + + var frameIndex; + + if (useLocalFrameIndex === undefined) + { + useLocalFrameIndex = false; + } + + // Find the index to the desired frame. + if (typeof frameId === "string") + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frameData.getFrame(this._frames[i]).name === frameId) + { + frameIndex = i; + } + } + } + else if (typeof frameId === "number") + { + if (useLocalFrameIndex) + { + frameIndex = frameId; + } + else + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frames[i] === frameId) + { + frameIndex = i; + } + } + } + } + + if (frameIndex) + { + // Set the current frame index to the found index. Subtract a directional offset so that it animates to the desired frame on update. + var directionalOffset = this.isReversed ? -1 : 1; + this._frameIndex = frameIndex - directionalOffset; + + // Make the animation update at next update + this._timeNextFrame = this.game.time.time; + + this.update(); + } + + }, + + /** + * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. + * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. + * + * @method Phaser.Animation#stop + * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. + * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? + */ + stop: function (resetFrame, dispatchComplete) { + + if (resetFrame === undefined) { resetFrame = false; } + if (dispatchComplete === undefined) { dispatchComplete = false; } + + this.isPlaying = false; + this.isFinished = true; + this.paused = false; + + if (resetFrame) + { + this.currentFrame = this._frameData.getFrame(this._frames[0]); + this._parent.setFrame(this.currentFrame); + } + + if (dispatchComplete) + { + this._parent.events.onAnimationComplete$dispatch(this._parent, this); + this.onComplete.dispatch(this._parent, this); + } + + }, + + /** + * Called when the Game enters a paused state. + * + * @method Phaser.Animation#onPause + */ + onPause: function () { + + if (this.isPlaying) + { + this._frameDiff = this._timeNextFrame - this.game.time.time; + } + + }, + + /** + * Called when the Game resumes from a paused state. + * + * @method Phaser.Animation#onResume + */ + onResume: function () { + + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this._frameDiff; + } + + }, + + /** + * Updates this animation. Called automatically by the AnimationManager. + * + * @method Phaser.Animation#update + */ + update: function () { + + if (this.isPaused) + { + return false; + } + + if (this.isPlaying && this.game.time.time >= this._timeNextFrame) + { + this._frameSkip = 1; + + // Lagging? + this._frameDiff = this.game.time.time - this._timeNextFrame; + + this._timeLastFrame = this.game.time.time; + + if (this._frameDiff > this.delay) + { + // We need to skip a frame, work out how many + this._frameSkip = Math.floor(this._frameDiff / this.delay); + this._frameDiff -= (this._frameSkip * this.delay); + } + else + { + this._frameDiff = 0; + } + + // And what's left now? + this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff); + + if (this.isReversed) + { + this._frameIndex -= this._frameSkip; + } + else + { + this._frameIndex += this._frameSkip; + } + + if (!this.isReversed && this._frameIndex >= this._frames.length || this.isReversed && this._frameIndex <= -1) + { + if (this.loop) + { + // Update current state before event callback + this._frameIndex = Math.abs(this._frameIndex) % this._frames.length; + + if (this.isReversed) + { + this._frameIndex = this._frames.length - 1 - this._frameIndex; + } + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + // Instead of calling updateCurrentFrame we do it here instead + if (this.currentFrame) + { + this._parent.setFrame(this.currentFrame); + } + + this.loopCount++; + this._parent.events.onAnimationLoop$dispatch(this._parent, this); + this.onLoop.dispatch(this._parent, this); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + } + else + { + this.complete(); + return false; + } + } + else + { + return this.updateCurrentFrame(true); + } + } + + return false; + + }, + + /** + * Changes the currentFrame per the _frameIndex, updates the display state, + * and triggers the update signal. + * + * Returns true if the current frame update was 'successful', false otherwise. + * + * @method Phaser.Animation#updateCurrentFrame + * @private + * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. + * @param {boolean} fromPlay - Was this call made from the playing of a new animation? + * @return {boolean} True if the current frame was updated, otherwise false. + */ + updateCurrentFrame: function (signalUpdate, fromPlay) { + + if (fromPlay === undefined) { fromPlay = false; } + + if (!this._frameData) + { + // The animation is already destroyed, probably from a callback + return false; + } + + // Previous index + var idx = this.currentFrame.index; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index))) + { + this._parent.setFrame(this.currentFrame); + } + + if (this.onUpdate && signalUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + + }, + + /** + * Advances by the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex + quantity; + + if (frame >= this._frames.length) + { + if (this.loop) + { + frame %= this._frames.length; + } + else + { + frame = this._frames.length - 1; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex - quantity; + + if (frame < 0) + { + if (this.loop) + { + frame = this._frames.length + frame; + } + else + { + frame++; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Changes the FrameData object this Animation is using. + * + * @method Phaser.Animation#updateFrameData + * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. + */ + updateFrameData: function (frameData) { + + this._frameData = frameData; + this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null; + + }, + + /** + * Cleans up this animation ready for deletion. Nulls all values and references. + * + * @method Phaser.Animation#destroy + */ + destroy: function () { + + if (!this._frameData) + { + // Already destroyed + return; + } + + 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(); + + if (this.onUpdate) + { + this.onUpdate.dispose(); + } + + }, + + /** + * Called internally when the animation finishes playback. + * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. + * + * @method Phaser.Animation#complete + */ + complete: function () { + + this._frameIndex = this._frames.length - 1; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + 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; + +/** +* @name Phaser.Animation#paused +* @property {boolean} paused - Gets and sets the paused state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'paused', { + + get: function () { + + return this.isPaused; + + }, + + set: function (value) { + + this.isPaused = value; + + if (value) + { + // Paused + this._pauseStartTime = this.game.time.time; + } + else + { + // Un-paused + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this.delay; + } + } + + } + +}); + +/** +* @name Phaser.Animation#reversed +* @property {boolean} reversed - Gets and sets the isReversed state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'reversed', { + + get: function () { + + return this.isReversed; + + }, + + set: function (value) { + + this.isReversed = value; + + } + +}); + +/** +* @name Phaser.Animation#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @name Phaser.Animation#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +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.setFrame(this.currentFrame); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + } + } + + } + +}); + +/** +* @name Phaser.Animation#speed +* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'speed', { + + get: function () { + + return 1000 / this.delay; + + }, + + set: function (value) { + + if (value > 0) + { + this.delay = 1000 / value; + } + + } + +}); + +/** +* @name Phaser.Animation#enableUpdate +* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { + + get: function () { + + return (this.onUpdate !== null); + + }, + + set: function (value) { + + if (value && this.onUpdate === null) + { + this.onUpdate = new Phaser.Signal(); + } + else if (!value && this.onUpdate !== null) + { + this.onUpdate.dispose(); + this.onUpdate = null; + } + + } + +}); + +/** +* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. +* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' +* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); +* +* @method Phaser.Animation.generateFrameNames +* @static +* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. +* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. +* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. +* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'. +* @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. +* @return {string[]} An array of framenames. +*/ +Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { + + if (suffix === undefined) { suffix = ''; } + + var output = []; + var frame = ''; + + if (start < stop) + { + for (var i = start; i <= stop; i++) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + else + { + for (var i = start; i >= stop; i--) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + + return output; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Frame is a single frame of an animation and is part of a FrameData collection. +* +* @class Phaser.Frame +* @constructor +* @param {number} index - The index of this Frame within the FrameData set it is being added to. +* @param {number} x - X position of the frame within the texture image. +* @param {number} y - Y position of the frame within the texture image. +* @param {number} width - Width of the frame within the texture image. +* @param {number} height - Height of the frame within the texture image. +* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. +*/ +Phaser.Frame = function (index, x, y, width, height, name) { + + /** + * @property {number} index - The index of this Frame within the FrameData set it is being added to. + */ + this.index = index; + + /** + * @property {number} x - X position within the image to cut from. + */ + this.x = x; + + /** + * @property {number} y - Y position within the image to cut from. + */ + this.y = y; + + /** + * @property {number} width - Width of the frame. + */ + this.width = width; + + /** + * @property {number} height - Height of the frame. + */ + this.height = height; + + if (this.width === 0 || this.height === 0) + { + console.warn('Phaser.Frame: Frame "' + this.name + '" has a width or height of zero'); + } + + /** + * @property {string} name - Useful for Texture Atlas files (is set to the filename value). + */ + this.name = name; + + /** + * @property {number} centerX - Center X position within the image to cut from. + */ + this.centerX = Math.floor(width / 2); + + /** + * @property {number} centerY - Center Y position within the image to cut from. + */ + this.centerY = Math.floor(height / 2); + + /** + * @property {number} distance - The distance from the top left to the bottom-right of this Frame. + */ + this.distance = Phaser.Math.distance(0, 0, width, height); + + /** + * @property {boolean} rotated - Is the frame rotated in the source texture? + * @default + */ + this.rotated = false; + + /** + * @property {boolean} trimmed - Was it trimmed when packed? + * @default + */ + this.trimmed = false; + + /** + * @property {number} sourceSizeW - Width of the original sprite before it was trimmed. + */ + this.sourceSizeW = width; + + /** + * @property {number} sourceSizeH - Height of the original sprite before it was trimmed. + */ + this.sourceSizeH = height; + + /** + * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeX = 0; + + /** + * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeY = 0; + + /** + * @property {number} spriteSourceSizeW - Width of the trimmed sprite. + * @default + */ + this.spriteSourceSizeW = 0; + + /** + * @property {number} spriteSourceSizeH - Height of the trimmed sprite. + * @default + */ + this.spriteSourceSizeH = 0; + + /** + * @property {number} right - The right of the Frame (x + width). + */ + this.right = this.x + this.width; + + /** + * @property {number} bottom - The bottom of the frame (y + height). + */ + this.bottom = this.y + this.height; + +}; + +Phaser.Frame.prototype = { + + /** + * Adjusts of all the Frame properties based on the given width and height values. + * + * @method Phaser.Frame#resize + * @param {integer} width - The new width of the Frame. + * @param {integer} height - The new height of the Frame. + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + this.centerX = Math.floor(width / 2); + this.centerY = Math.floor(height / 2); + this.distance = Phaser.Math.distance(0, 0, width, height); + this.sourceSizeW = width; + this.sourceSizeH = height; + this.right = this.x + width; + this.bottom = this.y + height; + + }, + + /** + * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. + * + * @method Phaser.Frame#setTrim + * @param {boolean} trimmed - If this frame was trimmed or not. + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + */ + setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { + + this.trimmed = trimmed; + + if (trimmed) + { + 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; + } + + }, + + /** + * Clones this Frame into a new Phaser.Frame object and returns it. + * Note that all properties are cloned, including the name and index. + * + * @method Phaser.Frame#clone + * @return {Phaser.Frame} An exact copy of this Frame object. + */ + clone: function () { + + var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name); + + for (var prop in this) + { + if (this.hasOwnProperty(prop)) + { + output[prop] = this[prop]; + } + } + + return output; + + }, + + /** + * Returns a Rectangle set to the dimensions of this Frame. + * + * @method Phaser.Frame#getRect + * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to. + * @return {Phaser.Rectangle} A rectangle. + */ + getRect: function (out) { + + if (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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. +* +* @class Phaser.FrameData +* @constructor +*/ +Phaser.FrameData = function () { + + /** + * @property {Array} _frames - Local array of frames. + * @private + */ + this._frames = []; + + /** + * @property {Array} _frameNames - Local array of frame names for name to index conversions. + * @private + */ + this._frameNames = []; + +}; + +Phaser.FrameData.prototype = { + + /** + * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. + * + * @method Phaser.FrameData#addFrame + * @param {Phaser.Frame} frame - The frame to add to this FrameData set. + * @return {Phaser.Frame} The frame that was just added. + */ + addFrame: function (frame) { + + frame.index = this._frames.length; + + this._frames.push(frame); + + if (frame.name !== '') + { + this._frameNames[frame.name] = frame.index; + } + + return frame; + + }, + + /** + * Get a Frame by its numerical index. + * + * @method Phaser.FrameData#getFrame + * @param {number} index - The index of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or undefined. + */ + getFrame: function (index) { + + if (index >= this._frames.length) + { + index = 0; + } + + return this._frames[index]; + + }, + + /** + * Get a Frame by its frame name. + * + * @method Phaser.FrameData#getFrameByName + * @param {string} name - The name of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or null. + */ + getFrameByName: function (name) { + + if (typeof this._frameNames[name] === 'number') + { + return this._frames[this._frameNames[name]]; + } + + return null; + + }, + + /** + * Check if there is a Frame with the given name. + * + * @method Phaser.FrameData#checkFrameName + * @param {string} name - The name of the frame you want to check. + * @return {boolean} True if the frame is found, otherwise false. + */ + checkFrameName: function (name) { + + if (this._frameNames[name] == null) + { + return false; + } + + return true; + + }, + + /** + * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains. + * + * @method Phaser.FrameData#clone + * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains. + */ + clone: function () { + + var output = new Phaser.FrameData(); + + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output._frames.push(this._frames[i].clone()); + } + + for (var p in this._frameNames) + { + if (this._frameNames.hasOwnProperty(p)) + { + output._frameNames.push(this._frameNames[p]); + } + } + + return output; + + }, + + /** + * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. + * + * @method Phaser.FrameData#getFrameRange + * @param {number} start - The starting frame index. + * @param {number} end - The ending frame index. + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. + */ + getFrameRange: function (start, end, output) { + + if (output === undefined) { output = []; } + + for (var i = start; i <= end; i++) + { + output.push(this._frames[i]); + } + + return output; + + }, + + /** + * Returns all of the Frames in this FrameData set where the frame index is found in the input array. + * The frames are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrames + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. + */ + getFrames: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + // We only need the indexes + output.push(this._frames[i]); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the input array contain names or indexes? + if (useNumericIndex) + { + // The actual frame + output.push(this.getFrame(frames[i])); + } + else + { + // The actual frame + output.push(this.getFrameByName(frames[i])); + } + } + } + + return output; + + }, + + /** + * Returns all of the Frame indexes in this FrameData set. + * The frames indexes are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrameIndexes + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frame indexes matching the given names or IDs. + */ + getFrameIndexes: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No frames array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output.push(this._frames[i].index); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the frames array contain names or indexes? + if (useNumericIndex && this._frames[frames[i]]) + { + output.push(this._frames[frames[i]].index); + } + else + { + if (this.getFrameByName(frames[i])) + { + output.push(this.getFrameByName(frames[i]).index); + } + } + } + } + + return output; + + }, + + /** + * Destroys this FrameData collection by nulling the _frames and _frameNames arrays. + * + * @method Phaser.FrameData#destroy + */ + destroy: function () { + + this._frames = null; + this._frameNames = null; + + } + +}; + +Phaser.FrameData.prototype.constructor = Phaser.FrameData; + +/** +* @name Phaser.FrameData#total +* @property {number} total - The total number of frames in this FrameData set. +* @readonly +*/ +Object.defineProperty(Phaser.FrameData.prototype, "total", { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +* +* @class Phaser.AnimationParser +* @static +*/ +Phaser.AnimationParser = { + + /** + * Parse a Sprite Sheet and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.spriteSheet + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. + * @param {number} frameWidth - The fixed width of each frame of the animation. + * @param {number} frameHeight - The fixed height of each frame of the animation. + * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + var img = key; + + if (typeof key === 'string') + { + img = game.cache.getImage(key); + } + + if (img === null) + { + return null; + } + + var width = img.width; + var height = img.height; + + if (frameWidth <= 0) + { + frameWidth = Math.floor(-width / Math.min(-1, frameWidth)); + } + + if (frameHeight <= 0) + { + frameHeight = Math.floor(-height / Math.min(-1, frameHeight)); + } + + var row = Math.floor((width - margin) / (frameWidth + spacing)); + var column = Math.floor((height - margin) / (frameHeight + spacing)); + var total = row * column; + + if (skipFrames > total || skipFrames < -total) + { + console.warn( + "Phaser.AnimationParser.spriteSheet: skipFrames = " + + skipFrames.toString() + " is larger than total sprite number " + + total.toString()); + return null; + } + + if (skipFrames < 0) + { + // Allow negative skipframes. + skipFrames = total + skipFrames; + } + + if (frameMax !== -1) + { + total = skipFrames + frameMax; + } + + // Zero or smaller than frame sizes? + if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0) + { + console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight"); + return null; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var x = margin; + var y = margin; + + for (var i = 0; i < total; i++) + { + data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '')); + + x += frameWidth + spacing; + + if (x + frameWidth > width) + { + x = margin; + y += frameHeight + spacing; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONData: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].frame.x, + frames[i].frame.y, + frames[i].frame.w, + frames[i].frame.h, + frames[i].filename + )); + + if (frames[i].trimmed) + { + newFrame.setTrim( + frames[i].trimmed, + frames[i].sourceSize.w, + frames[i].sourceSize.h, + frames[i].spriteSourceSize.x, + frames[i].spriteSourceSize.y, + frames[i].spriteSourceSize.w, + frames[i].spriteSourceSize.h + ); + } + + if (frames[i].rotated) + { + newFrame.rotated = true; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataPyxel + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataPyxel: function (game, json) { + + // Malformed? There are a few keys to check here. + var signature = ['layers', 'tilewidth','tileheight','tileswide', 'tileshigh']; + + signature.forEach( function(key) { + if (!json[key]) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "' + key + '" key.'); + console.log(json); + return; + } + }); + + // For this purpose, I only care about parsing tilemaps with a single layer. + if (json['layers'].length !== 1) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps.'); + console.log(json); + return; + } + + var data = new Phaser.FrameData(); + + var tileheight = json['tileheight']; + var tilewidth = json['tilewidth']; + + var frames = json['layers'][0]['tiles']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].x, + frames[i].y, + tilewidth, + tileheight, + "frame_" + i // No names are included in pyxel tilemap data. + )); + + // No trim data is included. + newFrame.setTrim(false); + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataHash + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataHash: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + var i = 0; + + for (var key in frames) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[key].frame.x, + frames[key].frame.y, + frames[key].frame.w, + frames[key].frame.h, + key + )); + + if (frames[key].trimmed) + { + newFrame.setTrim( + frames[key].trimmed, + frames[key].sourceSize.w, + frames[key].sourceSize.h, + frames[key].spriteSourceSize.x, + frames[key].spriteSourceSize.y, + frames[key].spriteSourceSize.w, + frames[key].spriteSourceSize.h + ); + } + + if (frames[key].rotated) + { + newFrame.rotated = true; + } + + i++; + } + + return data; + + }, + + /** + * Parse the XML data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.XMLData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + XMLData: function (game, xml) { + + // Malformed? + if (!xml.getElementsByTagName('TextureAtlas')) + { + console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing tag"); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var frames = xml.getElementsByTagName('SubTexture'); + var newFrame; + + var name; + var frame; + var x; + var y; + var width; + var height; + var frameX; + var frameY; + var frameWidth; + var frameHeight; + + for (var i = 0; i < frames.length; i++) + { + frame = frames[i].attributes; + + name = frame.name.value; + x = parseInt(frame.x.value, 10); + y = parseInt(frame.y.value, 10); + width = parseInt(frame.width.value, 10); + height = parseInt(frame.height.value, 10); + + frameX = null; + frameY = null; + + if (frame.frameX) + { + frameX = Math.abs(parseInt(frame.frameX.value, 10)); + frameY = Math.abs(parseInt(frame.frameY.value, 10)); + frameWidth = parseInt(frame.frameWidth.value, 10); + frameHeight = parseInt(frame.frameHeight.value, 10); + } + + newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name)); + + // Trimmed? + if (frameX !== null || frameY !== null) + { + newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight); + } + } + + return data; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser has one single cache in which it stores all assets. +* +* The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using +* a unique string-based key as their identifier. Assets stored in different areas of the cache can have the +* same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, +* because they are unique data types. +* +* The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets +* such as images they are automatically placed into their respective cache. Most common Game Objects, such as +* Sprites and Videos automatically query the cache to extract the assets they need on instantiation. +* +* You can access the cache from within a State via `this.cache`. From here you can call any public method it has, +* including adding new entries to it, deleting them or querying them. +* +* Understand that almost without exception when you get an item from the cache it will return a reference to the +* item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original +* object in the cache will also be updated, even if you don't put it back into the cache again. +* +* By default when you change State the cache is _not_ cleared, although there is an option to clear it should +* your game require it. In a typical game set-up the cache is populated once after the main game has loaded and +* then used as an asset store. +* +* @class Phaser.Cache +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Cache = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. + * @property {boolean} autoResolveURL + */ + this.autoResolveURL = false; + + /** + * The main cache object into which all resources are placed. + * @property {object} _cache + * @private + */ + this._cache = { + canvas: {}, + image: {}, + texture: {}, + sound: {}, + video: {}, + text: {}, + json: {}, + xml: {}, + physics: {}, + tilemap: {}, + binary: {}, + bitmapData: {}, + bitmapFont: {}, + shader: {}, + renderTexture: {}, + compressedTexture: {} + }; + + /** + * @property {object} _urlMap - Maps URLs to resources. + * @private + */ + this._urlMap = {}; + + /** + * @property {Image} _urlResolver - Used to resolve URLs to the absolute path. + * @private + */ + this._urlResolver = new Image(); + + /** + * @property {string} _urlTemp - Temporary variable to hold a resolved url. + * @private + */ + this._urlTemp = null; + + /** + * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices. + */ + this.onSoundUnlock = new Phaser.Signal(); + + /** + * @property {array} _cacheMap - Const to cache object look-up array. + * @private + */ + this._cacheMap = []; + + this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas; + this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image; + this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture; + this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound; + this._cacheMap[Phaser.Cache.TEXT] = this._cache.text; + this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics; + this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap; + this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary; + this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData; + this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont; + this._cacheMap[Phaser.Cache.JSON] = this._cache.json; + this._cacheMap[Phaser.Cache.XML] = this._cache.xml; + this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video; + this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader; + this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture; + + /** + * @property {number} + * @private + */ + this._pendingCount = 0; + + /** + * Dispatched when the DEFAULT and MISSING images have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). + * + * @property {Phaser.Signal} onReady + */ + this.onReady = new Phaser.Signal(); + + this._addImages(); + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.CANVAS = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.IMAGE = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXTURE = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SOUND = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXT = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.PHYSICS = 6; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TILEMAP = 7; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BINARY = 8; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPDATA = 9; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPFONT = 10; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.JSON = 11; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.XML = 12; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.VIDEO = 13; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SHADER = 14; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.RENDER_TEXTURE = 15; + +/** +* The default image used for a texture when no other is specified. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.DEFAULT = null; + +/** + * Key for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_KEY = '__default'; + +/** + * URL for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='; + +/** +* The default image used for a texture when the source image is missing. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.MISSING = null; + +/** + * Key for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_KEY = '__missing'; + +/** + * URL for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='; + +/** +* The maximum amount of time (ms) to wait for the built-in DEFAULT and MISSING images to load. +* @static +* @type {number} +* @default +*/ +Phaser.Cache.READY_TIMEOUT = 1000; + +Phaser.Cache.prototype = { + + ////////////////// + // Add Methods // + ////////////////// + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCompressedTextureMetaData + * @private + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url + * @param {string} extension + * @param {array} arrayBuffer + * @return {object} The compressed texture entry. + */ + addCompressedTextureMetaData: function (key, url, extension, arrayBuffer) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + var data = (extension in Phaser.LoaderParser) ? Phaser.LoaderParser[extension](arrayBuffer) : arrayBuffer; + + var texture = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData(), + fileFormat: extension + }; + + texture.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = texture; + + this._resolveURL(url, texture); + + return texture; + + }, + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCanvas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {HTMLCanvasElement} canvas - The Canvas DOM element. + * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`. + */ + addCanvas: function (key, canvas, context) { + + if (context === undefined) { context = canvas.getContext('2d'); } + + this._cache.canvas[key] = { canvas: canvas, context: context }; + + }, + + /** + * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. + * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. + * + * If the image has not yet been fetched (successfully or not), a `console.warn` message will be displayed. + * + * @method Phaser.Cache#addImage + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra image data. + * @return {object} The full image object that was added to the cache. + */ + addImage: function (key, url, data) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + if (data.complete === false) + { + console.warn('Phaser.Cache.addImage: Image "' + key + '" hasn\'t been retrieved yet'); + } + + var img = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData() + }; + + img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = img; + + this._resolveURL(url, img); + + if (key === '__default') + { + Phaser.Cache.DEFAULT = new PIXI.Texture(img.base); + } + else if (key === '__missing') + { + Phaser.Cache.MISSING = new PIXI.Texture(img.base); + } + + return img; + + }, + + /** + * @method Phaser.Cache#addImageAsync + * @private + */ + addImageAsync: function (key, src, callback) { + + var self = this; + var img = new Image(); + + img.onload = function () { + callback.call(this, self.addImage(key, null, img)); + self._removePending(); + img.onload = null; + }; + + this._addPending(); + img.src = src; + + }, + + /** + * Adds a default image to be used in special cases such as WebGL Filters. + * It uses the special reserved key of `__default`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addDefaultImage + * @protected + */ + addDefaultImage: function () { + + this.addImageAsync(Phaser.Cache.DEFAULT_KEY, Phaser.Cache.DEFAULT_SRC, function (obj) { + // Because we don't want to invalidate the sprite batch for an invisible texture + obj.base.skipRender = true; + + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.DEFAULT = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds an image to be used when a key is wrong / missing. + * It uses the special reserved key of `__missing`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addMissingImage + * @protected + */ + addMissingImage: function () { + + this.addImageAsync(Phaser.Cache.MISSING_KEY, Phaser.Cache.MISSING_SRC, function (obj) { + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.MISSING = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addSound + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sound data. + * @param {boolean} webAudio - True if the file is using web audio. + * @param {boolean} audioTag - True if the file is using legacy HTML audio. + */ + addSound: function (key, url, data, webAudio, audioTag) { + + if (webAudio === undefined) { webAudio = true; audioTag = false; } + if (audioTag === undefined) { webAudio = false; audioTag = true; } + + var decoded = false; + + if (audioTag) + { + decoded = true; + } + + this._cache.sound[key] = { + url: url, + data: data, + isDecoding: false, + decoded: decoded, + webAudio: webAudio, + audioTag: audioTag, + locked: this.game.sound.touchLocked + }; + + this._resolveURL(url, this._cache.sound[key]); + + }, + + /** + * Add a new text data. + * + * @method Phaser.Cache#addText + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addText: function (key, url, data) { + + this._cache.text[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.text[key]); + + }, + + /** + * Add a new physics data object to the Cache. + * + * @method Phaser.Cache#addPhysicsData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} JSONData - The physics data object (a JSON file). + * @param {number} format - The format of the physics data. + */ + addPhysicsData: function (key, url, JSONData, format) { + + this._cache.physics[key] = { url: url, data: JSONData, format: format }; + + this._resolveURL(url, this._cache.physics[key]); + + }, + + /** + * Add a new tilemap to the Cache. + * + * @method Phaser.Cache#addTilemap + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} mapData - The tilemap data object (either a CSV or JSON file). + * @param {number} format - The format of the tilemap data. + */ + addTilemap: function (key, url, mapData, format) { + + this._cache.tilemap[key] = { url: url, data: mapData, format: format }; + + this._resolveURL(url, this._cache.tilemap[key]); + + }, + + /** + * Add a binary object in to the cache. + * + * @method Phaser.Cache#addBinary + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {object} binaryData - The binary object to be added to the cache. + */ + addBinary: function (key, binaryData) { + + this._cache.binary[key] = binaryData; + + }, + + /** + * Add a BitmapData object to the cache. + * + * @method Phaser.Cache#addBitmapData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. + * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. + * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. + */ + addBitmapData: function (key, bitmapData, frameData) { + + bitmapData.key = key; + + if (frameData === undefined) + { + frameData = new Phaser.FrameData(); + frameData.addFrame(bitmapData.textureFrame); + } + + this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData }; + + return bitmapData; + + }, + + /** + * Add a new Bitmap Font to the Cache. + * + * @method Phaser.Cache#addBitmapFont + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra font data. + * @param {object} atlasData - The Bitmap Font data. + * @param {string} [atlasType='xml'] - The format of the Bitmap Font data file: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) { + + var obj = { + url: url, + data: data, + font: null, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + if (atlasType === 'json') + { + obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + else + { + obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new Bitmap Font to the Cache, where the font texture is part of a Texture Atlas. + * + * The atlas must already exist in the cache, and be available based on the given `atlasKey`. + * + * The `atlasFrame` specifies the name of the frame within the atlas that the Bitmap Font is + * stored in. + * + * The `dataKey` is the key of the XML or JSON Bitmap Font Data, which must already be in + * the Cache. + * + * @method Phaser.Cache#addBitmapFontFromAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} atlasKey - The key of the Texture Atlas in the Cache. + * @param {string} atlasFrame - The frame of the Texture Atlas that the Bitmap Font is in. + * @param {string} dataKey - The key of the Bitmap Font data in the Cache + * @param {string} [dataType='xml'] - The format of the Bitmap Font data: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFontFromAtlas: function (key, atlasKey, atlasFrame, dataKey, dataType, xSpacing, ySpacing) { + + var frame = this.getFrameByName(atlasKey, atlasFrame); + + if (!frame) + { + return; + } + + var obj = { + font: null, + base: this.getBaseTexture(atlasKey), + frame: frame + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + var fontData; + + if (dataType === 'json') + { + fontData = this.getJSON(dataKey); + obj.font = Phaser.LoaderParser.jsonBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + else + { + fontData = this.getXML(dataKey); + obj.font = Phaser.LoaderParser.xmlBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + }, + + /** + * Add a new json object into the cache. + * + * @method Phaser.Cache#addJSON + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra json data. + */ + addJSON: function (key, url, data) { + + this._cache.json[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.json[key]); + + }, + + /** + * Add a new xml object into the cache. + * + * @method Phaser.Cache#addXML + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addXML: function (key, url, data) { + + this._cache.xml[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.xml[key]); + + }, + + /** + * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addVideo + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra video data. + * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. + */ + addVideo: function (key, url, data, isBlob) { + + this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true }; + + this._resolveURL(url, this._cache.video[key]); + + }, + + /** + * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addShader + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra shader data. + */ + addShader: function (key, url, data) { + + this._cache.shader[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.shader[key]); + + }, + + /** + * Add a new Phaser.RenderTexture in to the cache. + * + * @method Phaser.Cache#addRenderTexture + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture. + */ + addRenderTexture: function (key, texture) { + + this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') }; + + }, + + /** + * Add a new sprite sheet in to the cache. + * + * @method Phaser.Cache#addSpriteSheet + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sprite sheet data. + * @param {number} frameWidth - Width of the sprite sheet. + * @param {number} frameHeight - Height of the sprite sheet. + * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + */ + addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + var obj = { + key: key, + url: url, + data: data, + frameWidth: frameWidth, + frameHeight: frameHeight, + margin: margin, + spacing: spacing, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) + }; + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new texture atlas to the Cache. + * + * @method Phaser.Cache#addTextureAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra texture atlas data. + * @param {object} atlasData - Texture atlas frames data. + * @param {number} format - The format of the texture atlas. + */ + addTextureAtlas: function (key, url, data, atlasData, format) { + + var obj = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key); + } + else if (format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + obj.frameData = Phaser.AnimationParser.JSONDataPyxel(this.game, atlasData, key); + } + else + { + // Let's just work it out from the frames array + if (Array.isArray(atlasData.frames)) + { + obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key); + } + else + { + obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key); + } + } + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + //////////////////////////// + // Sound Related Methods // + //////////////////////////// + + /** + * Reload a Sound file from the server. + * + * @method Phaser.Cache#reloadSound + * @param {string} key - The key of the asset within the cache. + */ + reloadSound: function (key) { + + var _this = this; + + var sound = this.getSound(key); + + if (sound) + { + sound.data.src = sound.url; + + sound.data.addEventListener('canplaythrough', function () { + return _this.reloadSoundComplete(key); + }, false); + + sound.data.load(); + } + + }, + + /** + * Fires the onSoundUnlock event when the sound has completed reloading. + * + * @method Phaser.Cache#reloadSoundComplete + * @param {string} key - The key of the asset within the cache. + */ + reloadSoundComplete: function (key) { + + var sound = this.getSound(key); + + if (sound) + { + sound.locked = false; + this.onSoundUnlock.dispatch(key); + } + + }, + + /** + * Updates the sound object in the cache. + * + * @method Phaser.Cache#updateSound + * @param {string} key - The key of the asset within the cache. + */ + updateSound: function (key, property, value) { + + var sound = this.getSound(key); + + if (sound) + { + sound[property] = value; + } + + }, + + /** + * Add a new decoded sound. + * + * @method Phaser.Cache#decodedSound + * @param {string} key - The key of the asset within the cache. + * @param {object} data - Extra sound data. + */ + decodedSound: function (key, data) { + + var sound = this.getSound(key); + + sound.data = data; + sound.decoded = true; + sound.isDecoding = false; + + }, + + /** + * Check if the given sound has finished decoding. + * + * @method Phaser.Cache#isSoundDecoded + * @param {string} key - The key of the asset within the cache. + * @return {boolean} The decoded state of the Sound object. + */ + isSoundDecoded: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return sound.decoded; + } + + }, + + /** + * Check if the given sound is ready for playback. + * A sound is considered ready when it has finished decoding and the device is no longer touch locked. + * + * @method Phaser.Cache#isSoundReady + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the sound is decoded and the device is not touch locked. + */ + isSoundReady: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return (sound.decoded && !this.game.sound.touchLocked); + } + + }, + + //////////////////////// + // Check Key Methods // + //////////////////////// + + /** + * Checks if a key for the given cache object type exists. + * + * @method Phaser.Cache#checkKey + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists, otherwise false. + */ + checkKey: function (cache, key) { + + if (this._cacheMap[cache][key]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given URL has been loaded into the Cache. + * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. + * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox + * which may cause double-load instances. + * + * @method Phaser.Cache#checkURL + * @param {string} url - The url to check for in the cache. + * @return {boolean} True if the url exists, otherwise false. + */ + checkURL: function (url) { + + if (this._urlMap[this._resolveURL(url)]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given key exists in the Canvas Cache. + * + * @method Phaser.Cache#checkCanvasKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkCanvasKey: function (key) { + + return this.checkKey(Phaser.Cache.CANVAS, key); + + }, + + /** + * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. + * + * @method Phaser.Cache#checkImageKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkImageKey: function (key) { + + return this.checkKey(Phaser.Cache.IMAGE, key); + + }, + + /** + * Checks if the given key exists in the Texture Cache. + * + * @method Phaser.Cache#checkTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXTURE, key); + + }, + + /** + * Checks if the given key exists in the Sound Cache. + * + * @method Phaser.Cache#checkSoundKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkSoundKey: function (key) { + + return this.checkKey(Phaser.Cache.SOUND, key); + + }, + + /** + * Checks if the given key exists in the Text Cache. + * + * @method Phaser.Cache#checkTextKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXT, key); + + }, + + /** + * Checks if the given key exists in the Physics Cache. + * + * @method Phaser.Cache#checkPhysicsKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkPhysicsKey: function (key) { + + return this.checkKey(Phaser.Cache.PHYSICS, key); + + }, + + /** + * Checks if the given key exists in the Tilemap Cache. + * + * @method Phaser.Cache#checkTilemapKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTilemapKey: function (key) { + + return this.checkKey(Phaser.Cache.TILEMAP, key); + + }, + + /** + * Checks if the given key exists in the Binary Cache. + * + * @method Phaser.Cache#checkBinaryKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBinaryKey: function (key) { + + return this.checkKey(Phaser.Cache.BINARY, key); + + }, + + /** + * Checks if the given key exists in the BitmapData Cache. + * + * @method Phaser.Cache#checkBitmapDataKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapDataKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPDATA, key); + + }, + + /** + * Checks if the given key exists in the BitmapFont Cache. + * + * @method Phaser.Cache#checkBitmapFontKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapFontKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPFONT, key); + + }, + + /** + * Checks if the given key exists in the JSON Cache. + * + * @method Phaser.Cache#checkJSONKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkJSONKey: function (key) { + + return this.checkKey(Phaser.Cache.JSON, key); + + }, + + /** + * Checks if the given key exists in the XML Cache. + * + * @method Phaser.Cache#checkXMLKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkXMLKey: function (key) { + + return this.checkKey(Phaser.Cache.XML, key); + + }, + + /** + * Checks if the given key exists in the Video Cache. + * + * @method Phaser.Cache#checkVideoKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkVideoKey: function (key) { + + return this.checkKey(Phaser.Cache.VIDEO, key); + + }, + + /** + * Checks if the given key exists in the Fragment Shader Cache. + * + * @method Phaser.Cache#checkShaderKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkShaderKey: function (key) { + + return this.checkKey(Phaser.Cache.SHADER, key); + + }, + + /** + * Checks if the given key exists in the Render Texture Cache. + * + * @method Phaser.Cache#checkRenderTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkRenderTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key); + + }, + + //////////////// + // Get Items // + //////////////// + + /** + * Get an item from a cache based on the given key and property. + * + * This method is mostly used internally by other Cache methods such as `getImage` but is exposed + * publicly for your own use as well. + * + * @method Phaser.Cache#getItem + * @param {string} key - The key of the asset within the cache. + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output. + * @param {string} [property] - If you require a specific property from the cache item, specify it here. + * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. + */ + getItem: function (key, cache, method, property) { + + if (!this.checkKey(cache, key)) + { + if (method) + { + console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.'); + } + } + else + { + if (property === undefined) + { + return this._cacheMap[cache][key]; + } + else + { + return this._cacheMap[cache][key][property]; + } + } + + return null; + + }, + + /** + * Gets a Canvas object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getCanvas + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The canvas object or `null` if no item could be found matching the given key. + */ + getCanvas: function (key) { + + return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas'); + + }, + + /** + * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. + * + * If you need the image used by a bitmap font or similar then please use those respective 'get' methods. + * + * @method Phaser.Cache#getImage + * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. + * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned. + * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. + */ + getImage: function (key, full) { + + if (key === undefined || key === null) + { + key = '__default'; + } + + if (full === undefined) { full = false; } + + var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage'); + + if (img === null) + { + img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage'); + } + + if (full) + { + return img; + } + else + { + return img.data; + } + + }, + + /** + * Get a single texture frame by key. + * + * You'd only do this to get the default Frame created for a non-atlas / spritesheet image. + * + * @method Phaser.Cache#getTextureFrame + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Frame} The frame data. + */ + getTextureFrame: function (key) { + + return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame'); + + }, + + /** + * Gets a Phaser.Sound object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSound + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Sound} The sound object. + */ + getSound: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSound'); + + }, + + /** + * Gets a raw Sound data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSoundData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The sound data. + */ + getSoundData: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data'); + + }, + + /** + * Gets a Text object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getText + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The text data. + */ + getText: function (key) { + + return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data'); + + }, + + /** + * Gets a Physics Data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can get either the entire data set, a single object or a single fixture of an object from it. + * + * @method Phaser.Cache#getPhysicsData + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all. + * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. + * @return {object} The requested physics object data if found. + */ + getPhysicsData: function (key, object, fixtureKey) { + + var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data'); + + if (data === null || object === undefined || object === null) + { + return data; + } + else + { + if (data[object]) + { + var fixtures = data[object]; + + // Try to find a fixture by its fixture key if given + if (fixtures && fixtureKey) + { + for (var fixture in fixtures) + { + // This contains the fixture data of a polygon or a circle + fixture = fixtures[fixture]; + + // Test the key + if (fixture.fixtureKey === fixtureKey) + { + return fixture; + } + } + + // We did not find the requested fixture + console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"'); + } + else + { + return fixtures; + } + } + else + { + console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"'); + } + } + + return null; + + }, + + /** + * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getTilemapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The raw tilemap data in CSV or JSON format. + */ + getTilemapData: function (key) { + + return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData'); + + }, + + /** + * Gets a binary object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBinary + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The binary data object. + */ + getBinary: function (key) { + + return this.getItem(key, Phaser.Cache.BINARY, 'getBinary'); + + }, + + /** + * Gets a BitmapData object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. + */ + getBitmapData: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data'); + + }, + + /** + * Gets a Bitmap Font object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapFont + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not. + */ + getBitmapFont: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont'); + + }, + + /** + * Gets a JSON object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can either return the object by reference (the default), or return a clone + * of it by setting the `clone` argument to `true`. + * + * @method Phaser.Cache#getJSON + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false) + * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. + */ + getJSON: function (key, clone) { + + var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data'); + + if (data) + { + if (clone) + { + return Phaser.Utils.extend(true, Array.isArray(data) ? [] : {}, data); + } + else + { + return data; + } + } + else + { + return null; + } + + }, + + /** + * Gets an XML object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getXML + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The XML object. + */ + getXML: function (key) { + + return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data'); + + }, + + /** + * Gets a Phaser.Video object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getVideo + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Video} The video object. + */ + getVideo: function (key) { + + return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo'); + + }, + + /** + * Gets a fragment shader object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getShader + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {string} The shader object. + */ + getShader: function (key) { + + return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data'); + + }, + + /** + * Gets a RenderTexture object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getRenderTexture + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame. + */ + getRenderTexture: function (key) { + + return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture'); + + }, + + //////////////////////////// + // Frame Related Methods // + //////////////////////////// + + /** + * Gets a PIXI.BaseTexture by key from the given Cache. + * + * @method Phaser.Cache#getBaseTexture + * @param {string} key - Asset key of the image for which you want the BaseTexture for. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {PIXI.BaseTexture} The BaseTexture object. + */ + getBaseTexture: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getBaseTexture', 'base'); + + }, + + /** + * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. + * + * @method Phaser.Cache#getFrame + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.Frame} The frame data. + */ + getFrame: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrame', 'frame'); + + }, + + /** + * Get the total number of frames contained in the FrameData object specified by the given key. + * + * @method Phaser.Cache#getFrameCount + * @param {string} key - Asset key of the FrameData you want. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {number} Then number of frames. 0 if the image is not found. + */ + getFrameCount: function (key, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.total; + } + else + { + return 0; + } + + }, + + /** + * Gets a Phaser.FrameData object from the Image Cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.FrameData} The frame data. + */ + getFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrameData', 'frameData'); + + }, + + /** + * Check if the FrameData for the given key exists in the Image Cache. + * + * @method Phaser.Cache#hasFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {boolean} True if the given key has frameData in the cache, otherwise false. + */ + hasFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return (this.getItem(key, cache, '', 'frameData') !== null); + + }, + + /** + * Replaces a set of frameData with a new Phaser.FrameData object. + * + * @method Phaser.Cache#updateFrameData + * @param {string} key - The unique key by which you will reference this object. + * @param {number} frameData - The new FrameData. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + */ + updateFrameData: function (key, frameData, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + if (this._cacheMap[cache][key]) + { + this._cacheMap[cache][key].frameData = frameData; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByIndex + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {number} index - The index of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByIndex: function (key, index, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrame(index); + } + else + { + return null; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByName + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {string} name - The name of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByName: function (key, name, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrameByName(name); + } + else + { + return null; + } + + }, + + /** + * Get a cached object by the URL. + * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. + * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. + * + * @method Phaser.Cache#getURL + * @param {string} url - The url for the object loaded to get from the cache. + * @return {object} The cached object. + */ + getURL: function (url) { + + var url = this._resolveURL(url); + + if (url) + { + return this._urlMap[url]; + } + else + { + console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false'); + return null; + } + + }, + + /** + * Gets all keys used in the requested Cache. + * + * @method Phaser.Cache#getKeys + * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. + * @return {Array} The array of keys in the requested cache. + */ + getKeys: function (cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + var out = []; + + if (this._cacheMap[cache]) + { + for (var key in this._cacheMap[cache]) + { + if (key !== '__default' && key !== '__missing') + { + out.push(key); + } + } + } + + return out; + + }, + + ///////////////////// + // Remove Methods // + ///////////////////// + + /** + * Removes a canvas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeCanvas + * @param {string} key - Key of the asset you want to remove. + */ + removeCanvas: function (key) { + + delete this._cache.canvas[key]; + + }, + + /** + * Removes an image from the cache. + * + * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. + * + * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeImage + * @param {string} key - Key of the asset you want to remove. + * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed? + */ + removeImage: function (key, destroyBaseTexture) { + + if (destroyBaseTexture === undefined) { destroyBaseTexture = true; } + + var img = this.getImage(key, true); + + if (destroyBaseTexture && img.base) + { + img.base.destroy(); + } + + delete this._cache.image[key]; + + }, + + /** + * Removes a sound from the cache. + * + * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will + * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then + * you must finish your house-keeping and destroy them all yourself first, before calling this method. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSound + * @param {string} key - Key of the asset you want to remove. + */ + removeSound: function (key) { + + delete this._cache.sound[key]; + + }, + + /** + * Removes a text file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeText + * @param {string} key - Key of the asset you want to remove. + */ + removeText: function (key) { + + delete this._cache.text[key]; + + }, + + /** + * Removes a physics data file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removePhysics + * @param {string} key - Key of the asset you want to remove. + */ + removePhysics: function (key) { + + delete this._cache.physics[key]; + + }, + + /** + * Removes a tilemap from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTilemap + * @param {string} key - Key of the asset you want to remove. + */ + removeTilemap: function (key) { + + delete this._cache.tilemap[key]; + + }, + + /** + * Removes a binary file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBinary + * @param {string} key - Key of the asset you want to remove. + */ + removeBinary: function (key) { + + delete this._cache.binary[key]; + + }, + + /** + * Removes a bitmap data from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapData + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapData: function (key) { + + delete this._cache.bitmapData[key]; + + }, + + /** + * Removes a bitmap font from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapFont + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapFont: function (key) { + + delete this._cache.bitmapFont[key]; + + }, + + /** + * Removes a json object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeJSON + * @param {string} key - Key of the asset you want to remove. + */ + removeJSON: function (key) { + + delete this._cache.json[key]; + + }, + + /** + * Removes a xml object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeXML + * @param {string} key - Key of the asset you want to remove. + */ + removeXML: function (key) { + + delete this._cache.xml[key]; + + }, + + /** + * Removes a video from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeVideo + * @param {string} key - Key of the asset you want to remove. + */ + removeVideo: function (key) { + + delete this._cache.video[key]; + + }, + + /** + * Removes a shader from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeShader + * @param {string} key - Key of the asset you want to remove. + */ + removeShader: function (key) { + + delete this._cache.shader[key]; + + }, + + /** + * Removes a Render Texture from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeRenderTexture + * @param {string} key - Key of the asset you want to remove. + */ + removeRenderTexture: function (key) { + + delete this._cache.renderTexture[key]; + + }, + + /** + * Removes a Sprite Sheet from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSpriteSheet + * @param {string} key - Key of the asset you want to remove. + */ + removeSpriteSheet: function (key) { + + delete this._cache.spriteSheet[key]; + + }, + + /** + * Removes a Texture Atlas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTextureAtlas + * @param {string} key - Key of the asset you want to remove. + */ + removeTextureAtlas: function (key) { + + delete this._cache.image[key]; + + }, + + /** + * Empties out all of the GL Textures from Images stored in the cache. + * This is called automatically when the WebGL context is lost and then restored. + * + * @method Phaser.Cache#clearGLTextures + * @protected + */ + clearGLTextures: function () { + + for (var key in this._cache.image) + { + this._cache.image[key].base._glTextures = []; + } + + }, + + /** + * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`. + * This is then looked-up by the Cache.getURL and Cache.checkURL calls. + * + * @method Phaser.Cache#_resolveURL + * @private + * @param {string} url - The URL to resolve. This is appended to Loader.baseURL. + * @param {object} [data] - The data associated with the URL to be stored to the URL Map. + * @return {string} The resolved URL. + */ + _resolveURL: function (url, data) { + + if (!this.autoResolveURL) + { + return null; + } + + this._urlResolver.src = this.game.load.baseURL + url; + + this._urlTemp = this._urlResolver.src; + + // Ensure no request is actually made + this._urlResolver.src = ''; + + // Record the URL to the map + if (data) + { + this._urlMap[this._urlTemp] = data; + } + + return this._urlTemp; + + }, + + /** + * Clears the cache. Removes every local cache object reference. + * If an object in the cache has a `destroy` method it will be called; + * otherwise, `destroy` will be called on any of the object's `base`, `data`, + * `frameData`, or `texture` properties. + * + * @method Phaser.Cache#destroy + */ + destroy: function () { + + for (var i = 0; i < this._cacheMap.length; i++) + { + var cache = this._cacheMap[i]; + + for (var key in cache) + { + if (key !== '__default' && key !== '__missing') + { + this.destroyItem(cache[key]); + + delete cache[key]; + } + } + } + + this._urlMap = null; + this._urlResolver = null; + this._urlTemp = null; + + }, + + /** + * @method Phaser.Cache#destroyItem + * @protected + * @param {object} item + */ + destroyItem: function (item) { + + if (item.destroy) + { + item.destroy(); + } + else + { + if (item.base && item.base.destroy) + { + item.base.destroy(); + } + + if (item.data && item.data.destroy) + { + item.data.destroy(); + } + + if (item.frameData && item.frameData.destroy) + { + item.frameData.destroy(); + } + + if (item.texture && item.texture.destroy) + { + item.texture.destroy(true); + } + } + + }, + + /** + * Starts loading the DEFAULT and MISSING images. + * + * @private + */ + _addImages: function () { + + this._pendingCount = 0; + + this.addDefaultImage(); + this.addMissingImage(); + + var self = this; + var readyTimeout = Phaser.Cache.READY_TIMEOUT; + + if (Phaser.Cache.READY_TIMEOUT > 0) + { + setTimeout(function () { + if (!self.isReady) + { + console.warn('Phaser.Cache: Still waiting for images after %s ms.', readyTimeout); + + self._ready(); + } + }, Phaser.Cache.READY_TIMEOUT); + } + else + { + this._ready(); + } + + }, + + + /** + * Increments the pending count. + * + * @private + */ + _addPending: function () { + + this._pendingCount += 1; + + }, + + + /** + * Decrements the pending count and checks if complete. + * + * @private + */ + _removePending: function () { + + this._pendingCount -= 1; + this._checkReady(); + + }, + + + /** + * Calls {@link #_ready} if no pending items remain. + * + * @private + */ + _checkReady: function () { + + if (this.isReady) + { + this._ready(); + } + + }, + + + /** + * Resets pending count and triggers {@link #onReady}. + * + * @private + */ + _ready: function () { + + this._pendingCount = 0; + this.onReady.dispatch(this); + + } + +}; + +Phaser.Cache.prototype.constructor = Phaser.Cache; + +/** +* The DEFAULT and MISSING textures have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). +* +* @property {boolean} Phaser.Cache#isReady +*/ +Object.defineProperty(Phaser.Cache.prototype, 'isReady', { + get: function () { + return this._pendingCount <= 0; + } +}); + +/* jshint wsh:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* +* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. +* +* Parallel loading (see {@link #enableParallel}) is supported and enabled by default. +* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}. +* +* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and +* [Shoebox](http://renderhjs.net/shoebox/) +* +* @class Phaser.Loader +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Loader = function (game) { + + /** + * Local reference to game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + /** + * Local reference to the Phaser.Cache. + * @property {Phaser.Cache} cache + * @protected + */ + this.cache = game.cache; + + /** + * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * True if the Loader is in the process of loading the queue. + * @property {boolean} isLoading + * @default + */ + this.isLoading = false; + + /** + * True if all assets in the queue have finished loading. + * @property {boolean} hasLoaded + * @default + */ + this.hasLoaded = false; + + /** + * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}. + * + * This property is an object containing: sprite, rect, direction, width and height + * + * @property {?object} preloadSprite + * @protected + */ + this.preloadSprite = null; + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * @property {boolean|string} crossOrigin + * @default + */ + this.crossOrigin = false; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * Useful if allowing the asset base url to be configured outside of the game code. + * The string _must_ end with a "/". + * + * @property {string} baseURL + */ + this.baseURL = ''; + + /** + * The value of `path`, if set, is placed before any _relative_ file path given. For example: + * + * ```javascript + * load.path = "images/sprites/"; + * load.image("ball", "ball.png"); + * load.image("tree", "level1/oaktree.png"); + * load.image("boom", "http://server.com/explode.png"); + * ``` + * + * Would load the `ball` file from `images/sprites/ball.png` and the tree from + * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL + * given as it's an absolute URL. + * + * Please note that the path is added before the filename but *after* the baseURL (if set.) + * + * The string _must_ end with a "/". + * + * @property {string} path + */ + this.path = ''; + + /** + * Used to map the application mime-types to to the Accept header in XHR requests. + * If you don't require these mappings, or they cause problems on your server, then + * remove them from the headers object and the XHR request will not try to use them. + * + * This object can also be used to set the `X-Requested-With` header to + * `XMLHttpRequest` (or any other value you need). To enable this do: + * + * ```javascript + * this.load.headers.requestedWith = 'XMLHttpRequest' + * ``` + * + * before adding anything to the Loader. The XHR loader will then call: + * + * ```javascript + * setRequestHeader('X-Requested-With', this.headers['requestedWith']) + * ``` + * + * @property {object} headers + * @default + */ + this.headers = { + "requestedWith": false, + "json": "application/json", + "xml": "application/xml" + }; + + /** + * This event is dispatched when the loading process starts: before the first file has been requested, + * but after all the initial packs have been loaded. + * + * @property {Phaser.Signal} onLoadStart + */ + this.onLoadStart = new Phaser.Signal(); + + /** + * This event is dispatched when the final file in the load queue has either loaded or failed. + * + * @property {Phaser.Signal} onLoadComplete + */ + this.onLoadComplete = new Phaser.Signal(); + + /** + * This event is dispatched when an asset pack has either loaded or failed to load. + * + * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. + * + * Params: `(pack key, success?, total packs loaded, total packs)` + * + * @property {Phaser.Signal} onPackComplete + */ + this.onPackComplete = new Phaser.Signal(); + + /** + * This event is dispatched immediately before a file starts loading. + * It's possible the file may fail (eg. download error, invalid format) after this event is sent. + * + * Params: `(progress, file key, file url)` + * + * @property {Phaser.Signal} onFileStart + */ + this.onFileStart = new Phaser.Signal(); + + /** + * This event is dispatched when a file has either loaded or failed to load. + * + * Any function bound to this will receive the following parameters: + * + * progress, file key, success?, total loaded files, total files + * + * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. + * + * @property {Phaser.Signal} onFileComplete + */ + this.onFileComplete = new Phaser.Signal(); + + /** + * This event is dispatched when a file (or pack) errors as a result of the load request. + * + * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. + * + * Params: `(file key, file)` + * + * @property {Phaser.Signal} onFileError + */ + this.onFileError = new Phaser.Signal(); + + /** + * If true (the default) then parallel downloading will be enabled. + * + * To disable all parallel downloads this must be set to false prior to any resource being loaded. + * + * @property {boolean} enableParallel + */ + this.enableParallel = true; + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Many current browsers limit 6 requests per domain; this is slightly conservative. + * + * This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently. + * + * @property {integer} maxParallelDownloads + */ + this.maxParallelDownloads = 4; + + /** + * A counter: if more than zero, files will be automatically added as a synchronization point. + * @property {integer} _withSyncPointDepth; + */ + this._withSyncPointDepth = 0; + + /** + * Contains all the information for asset files (including packs) to load. + * + * File/assets are only removed from the list after all loading completes. + * + * @property {file[]} _fileList + * @private + */ + this._fileList = []; + + /** + * Inflight files (or packs) that are being fetched/processed. + * + * This means that if there are any files in the flight queue there should still be processing + * going on; it should only be empty before or after loading. + * + * The files in the queue may have additional properties added to them, + * including `requestObject` which is normally the associated XHR. + * + * @property {file[]} _flightQueue + * @private + */ + this._flightQueue = []; + + /** + * The offset into the fileList past all the complete (loaded or error) entries. + * + * @property {integer} _processingHead + * @private + */ + this._processingHead = 0; + + /** + * True when the first file (not pack) has loading started. + * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded. + * + * @property {boolean} _initialPacksLoaded + * @private + */ + this._fileLoadStarted = false; + + /** + * Total packs seen - adjusted when a pack is added. + * @property {integer} _totalPackCount + * @private + */ + this._totalPackCount = 0; + + /** + * Total files seen - adjusted when a file is added. + * @property {integer} _totalFileCount + * @private + */ + this._totalFileCount = 0; + + /** + * Total packs loaded - adjusted just prior to `onPackComplete`. + * @property {integer} _loadedPackCount + * @private + */ + this._loadedPackCount = 0; + + /** + * Total files loaded - adjusted just prior to `onFileComplete`. + * @property {integer} _loadedFileCount + * @private + */ + this._loadedFileCount = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_PHASER_JSON = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5; + +Phaser.Loader.prototype = { + + /** + * Set a Sprite to be a "preload" sprite by passing it to this method. + * + * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. + * This allows you to easily make loading bars for games. + * + * The sprite will automatically be made visible when calling this. + * + * @method Phaser.Loader#setPreloadSprite + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load. + * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. + */ + setPreloadSprite: function (sprite, direction) { + + direction = direction || 0; + + this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null }; + + if (direction === 0) + { + // Horizontal rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height); + } + else + { + // Vertical rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1); + } + + sprite.crop(this.preloadSprite.rect); + + sprite.visible = true; + + }, + + /** + * Called automatically by ScaleManager when the game resizes in RESIZE scalemode. + * + * This can be used to adjust the preloading sprite size, eg. + * + * @method Phaser.Loader#resize + * @protected + */ + resize: function () { + + if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height) + { + this.preloadSprite.rect.height = this.preloadSprite.sprite.height; + } + + }, + + /** + * Check whether a file/asset with a specific key is queued to be loaded. + * + * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey} + * + * @method Phaser.Loader#checkKeyExists + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ + checkKeyExists: function (type, key) { + + return this.getAssetIndex(type, key) > -1; + + }, + + /** + * Get the queue-index of the file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAssetIndex + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {number} The index of this key in the filelist, or -1 if not found. + * The index may change and should only be used immediately following this call + */ + getAssetIndex: function (type, key) { + + var bestFound = -1; + + for (var i = 0; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + if (file.type === type && file.key === key) + { + bestFound = i; + + // An already loaded/loading file may be superceded. + if (!file.loaded && !file.loading) + { + break; + } + } + } + + return bestFound; + + }, + + /** + * Find a file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAsset + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. + * The index may change and should only be used immediately following this call. + */ + getAsset: function (type, key) { + + var fileIndex = this.getAssetIndex(type, key); + + if (fileIndex > -1) + { + return { index: fileIndex, file: this._fileList[fileIndex] }; + } + + return false; + + }, + + /** + * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. + * + * This will abort any loading and clear any queued assets. + * + * Optionally you can clear any associated events. + * + * @method Phaser.Loader#reset + * @protected + * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared. + * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them. + */ + reset: function (hard, clearEvents) { + + if (clearEvents === undefined) { clearEvents = false; } + + if (this.resetLocked) + { + return; + } + + if (hard) + { + this.preloadSprite = null; + } + + this.isLoading = false; + + this._processingHead = 0; + this._fileList.length = 0; + this._flightQueue.length = 0; + + this._fileLoadStarted = false; + this._totalFileCount = 0; + this._totalPackCount = 0; + this._loadedPackCount = 0; + this._loadedFileCount = 0; + + if (clearEvents) + { + this.onLoadStart.removeAll(); + this.onLoadComplete.removeAll(); + this.onPackComplete.removeAll(); + this.onFileStart.removeAll(); + this.onFileComplete.removeAll(); + this.onFileError.removeAll(); + } + + }, + + /** + * Internal function that adds a new entry to the file list. Do not call directly. + * + * @method Phaser.Loader#addToFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} [url] - The URL the asset will be loaded from. + * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. + * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. + * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. + * @return {Phaser.Loader} This instance of the Phaser Loader. + */ + addToFileList: function (type, key, url, properties, overwrite, extension) { + + if (overwrite === undefined) { overwrite = false; } + + if (key === undefined || key === '') + { + console.warn("Phaser.Loader: Invalid or no key given of type " + type); + return this; + } + + if (url === undefined || url === null) + { + if (extension) + { + url = key + extension; + } + else + { + console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key); + return this; + } + } + + var file = { + type: type, + key: key, + path: this.path, + url: url, + syncPoint: this._withSyncPointDepth > 0, + data: null, + loading: false, + loaded: false, + error: false + }; + + if (properties) + { + for (var prop in properties) + { + file[prop] = properties[prop]; + } + } + + var fileIndex = this.getAssetIndex(type, key); + + if (overwrite && fileIndex > -1) + { + var currentFile = this._fileList[fileIndex]; + + if (!currentFile.loading && !currentFile.loaded) + { + this._fileList[fileIndex] = file; + } + else + { + this._fileList.push(file); + this._totalFileCount++; + } + } + else if (fileIndex === -1) + { + this._fileList.push(file); + this._totalFileCount++; + } + + return this; + + }, + + /** + * Internal function that replaces an existing entry in the file list with a new one. Do not call directly. + * + * @method Phaser.Loader#replaceInFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} url - The URL the asset will be loaded from. + * @param {object} properties - Any additional properties needed to load the file. + */ + replaceInFileList: function (type, key, url, properties) { + + return this.addToFileList(type, key, url, properties, true); + + }, + + /** + * Add a JSON resource pack ('packfile') to the Loader. + * + * A packfile is a JSON file that contains a list of assets to the be loaded. + * Please see the example 'loader/asset pack' in the Phaser Examples repository. + * + * Packs are always put before the first non-pack file that is not loaded / loading. + * + * This means that all packs added before any loading has started are added to the front + * of the file queue, in the order added. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#pack + * @param {string} key - Unique asset key of this resource pack. + * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. + * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO + * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. + * @return {Phaser.Loader} This Loader instance. + */ + pack: function (key, url, data, callbackContext) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (callbackContext === undefined) { callbackContext = null; } + + if (!url && !data) + { + console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.'); + + return this; + } + + var pack = { + type: 'packfile', + key: key, + url: url, + path: this.path, + syncPoint: true, + data: null, + loading: false, + loaded: false, + error: false, + callbackContext: callbackContext + }; + + // A data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + pack.data = data || {}; + + // Already consider 'loaded' + pack.loaded = true; + } + + // Add before first non-pack/no-loaded ~ last pack from start prior to loading + // (Read one past for splice-to-end) + for (var i = 0; i < this._fileList.length + 1; i++) + { + var file = this._fileList[i]; + + if (!file || (!file.loaded && !file.loading && file.type !== 'packfile')) + { + this._fileList.splice(i, 0, pack); + this._totalPackCount++; + break; + } + } + + return this; + + }, + + /** + * Adds an Image to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * This method also supports passing in a texture object as the `url` argument. This allows you to load + * compressed textures into Phaser. You can also use `Loader.texture` to do this. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.image('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * @method Phaser.Loader#image + * @param {string} key - Unique asset key of this image file. + * @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + image: function (key, url, overwrite) { + + if (typeof url === 'object') + { + return this.texture(key, url, overwrite); + } + else + { + return this.addToFileList('image', key, url, undefined, overwrite, '.png'); + } + + }, + + /** + * Generate an image from a BitmapData object and add it to the current load queue. + * + * @method Phaser.Loader#imageFromBitmapData + * @param {string} key - Unique asset key for the generated image. + * @param {Phaser.BitmapData} bitmapData + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + imageFromBitmapData: function (key, bitmapData, overwrite) { + + return this.image(key, bitmapData.canvas.toDataURL('image/png'), overwrite); + + }, + + /** + * Generate a grid image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromGrid + * @see Phaser.Create#grid + */ + imageFromGrid: function (key, width, height, cellWidth, cellHeight, color) { + + return this.imageFromBitmapData(key, this.game.create.grid(key, width, height, cellWidth, cellHeight, color, false)); + + }, + + /** + * Generate a texture image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromTexture + * @see Phaser.Create#texture + */ + imageFromTexture: function (key, data, pixelWidth, pixelHeight, palette) { + + return this.imageFromBitmapData(key, this.game.create.texture(key, data, pixelWidth, pixelHeight, palette, false)); + + }, + + /** + * Adds a Compressed Texture Image to the current load queue. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.texture('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#texture + * @param {string} key - Unique asset key of this image file. + * @param {object} object - The texture path data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + texture: function (key, object, overwrite) { + + if (this.game.renderType === Phaser.WEBGL) + { + var compression = this.game.renderer.extensions.compression; + var exkey; + + for (exkey in object) + { + if (exkey.toUpperCase() in compression) + { + return this.addToFileList('texture', key, object[exkey], undefined, overwrite, '.pvr'); + } + } + } + + // Check if we have a truecolor texture to fallback. + // Also catches calls to this function that are from a Canvas renderer + + if (object['truecolor']) + { + this.addToFileList('image', key, object['truecolor'], undefined, overwrite, '.png'); + } + + return this; + + }, + + /** + * Adds an array of images to the current load queue. + * + * It works by passing each element of the array to the Loader.image method. + * + * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. + * + * Retrieve the images via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#images + * @param {array} keys - An array of unique asset keys of the image files. + * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. + * @return {Phaser.Loader} This Loader instance. + */ + images: function (keys, urls) { + + if (Array.isArray(urls)) + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i], urls[i]); + } + } + else + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i]); + } + } + + return this; + + }, + + /** + * Adds a Text file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getText(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#text + * @param {string} key - Unique asset key of the text file. + * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + text: function (key, url, overwrite) { + + return this.addToFileList('text', key, url, undefined, overwrite, '.txt'); + + }, + + /** + * Adds a JSON file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#json + * @param {string} key - Unique asset key of the json file. + * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + json: function (key, url, overwrite) { + + return this.addToFileList('json', key, url, undefined, overwrite, '.json'); + + }, + + /** + * Adds a fragment shader file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getShader(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" + * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#shader + * @param {string} key - Unique asset key of the fragment file. + * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + shader: function (key, url, overwrite) { + + return this.addToFileList('shader', key, url, undefined, overwrite, '.frag'); + + }, + + /** + * Adds an XML file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getXML(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#xml + * @param {string} key - Unique asset key of the xml file. + * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + xml: function (key, url, overwrite) { + + return this.addToFileList('xml', key, url, undefined, overwrite, '.xml'); + + }, + + /** + * Adds a JavaScript file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. + * If you do not desire this action then provide a URL. + * + * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! + * + * A callback, which will be invoked as the script tag has been created, can also be specified. + * The callback must return relevant `data`. + * + * @method Phaser.Loader#script + * @param {string} key - Unique asset key of the script file. + * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing. + * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. + * @return {Phaser.Loader} This Loader instance. + */ + script: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + if (callback !== false && callbackContext === undefined) { callbackContext = this; } + + return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js'); + + }, + + /** + * Adds a binary file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBinary(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. + * If you do not desire this action then provide a URL. + * + * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. + * When the callback is called it will be passed 2 parameters: the key of the file and the file data. + * + * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. + * + * @method Phaser.Loader#binary + * @param {string} key - Unique asset key of the binary file. + * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it. + * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context. + * @return {Phaser.Loader} This Loader instance. + */ + binary: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + // Why is the default callback context the ..callback? + if (callback !== false && callbackContext === undefined) { callbackContext = callback; } + + return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin'); + + }, + + /** + * Adds a Sprite Sheet to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal + * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. + * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. + * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming + * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. + * If you've got an atlas then use `Loader.atlas` instead. + * + * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#spritesheet + * @param {string} key - Unique asset key of the sheet file. + * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet. + * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.Loader} This Loader instance. + */ + spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing, skipFrames: skipFrames }, false, '.png'); + + }, + + /** + * Adds an audio file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getSound(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. + * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. + * The solution is to use a lower encoding rate such as 44100 Hz. + * + * @method Phaser.Loader#audio + * @param {string} key - Unique asset key of the audio file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp3']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audio: function (key, urls, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (autoDecode === undefined) { autoDecode = true; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); + + }, + + /** + * Adds an audio sprite file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Audio Sprites are a combination of audio files and a JSON configuration. + * + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * Retrieve the file via `Cache.getSoundData(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#audioSprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (jsonURL === undefined) { jsonURL = null; } + if (jsonData === undefined) { jsonData = null; } + if (autoDecode === undefined) { autoDecode = true; } + + this.audio(key, urls, autoDecode); + + if (jsonURL) + { + this.json(key + '-audioatlas', jsonURL); + } + else if (jsonData) + { + if (typeof jsonData === 'string') + { + jsonData = JSON.parse(jsonData); + } + + this.cache.addJSON(key + '-audioatlas', '', jsonData); + } + else + { + console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object'); + } + + return this; + + }, + + /** + * A legacy alias for Loader.audioSprite. Please see that method for documentation. + * + * @method Phaser.Loader#audiosprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode); + + }, + + /** + * Adds a video file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getVideo(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. + * + * @method Phaser.Loader#video + * @param {string} key - Unique asset key of the video file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp4']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete. + * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. + * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. + * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the + * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. + * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set. + * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. + * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. + * @return {Phaser.Loader} This Loader instance. + */ + video: function (key, urls, loadEvent, asBlob) { + + if (loadEvent === undefined) + { + if (this.game.device.firefox) + { + loadEvent = 'loadeddata'; + } + else + { + loadEvent = 'canplaythrough'; + } + } + + if (asBlob === undefined) { asBlob = false; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent }); + + }, + + /** + * Adds a Tile Map data file to the current load queue. + * + * Phaser can load data in two different formats: CSV and Tiled JSON. + * + * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". + * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#tilemap + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. + * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + * @return {Phaser.Loader} This Loader instance. + */ + tilemap: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Tilemap.CSV; } + + if (!url && !data) + { + if (format === Phaser.Tilemap.CSV) + { + url = key + '.csv'; + } + else + { + url = key + '.json'; + } + } + + // A map data object has been given + if (data) + { + switch (format) + { + // A csv string or object has been given + case Phaser.Tilemap.CSV: + break; + + // A json string or object has been given + case Phaser.Tilemap.TILED_JSON: + + if (typeof data === 'string') + { + data = JSON.parse(data); + } + break; + } + + this.cache.addTilemap(key, null, data, format); + } + else + { + this.addToFileList('tilemap', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds a physics data file to the current load queue. + * + * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". + * It will always use `.json` as the extension. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#physics + * @param {string} key - Unique asset key of the physics json data. + * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. + * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data. + * @return {Phaser.Loader} This Loader instance. + */ + physics: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; } + + if (!url && !data) + { + url = key + '.json'; + } + + // A map data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + this.cache.addPhysicsData(key, null, data, format); + } + else + { + this.addToFileList('physics', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds Bitmap Font files to the current load queue. + * + * To create the Bitmap Font files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `xmlData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#bitmapFont + * @param {string} key - Unique asset key of the bitmap font. + * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". + * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". + * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json). + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + * @return {Phaser.Loader} This Loader instance. + */ + bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (atlasURL === null && atlasData === null) + { + atlasURL = key + '.xml'; + } + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + // A URL to a json/xml atlas has been given + if (atlasURL) + { + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing }); + } + else + { + // A stringified xml/json atlas has been given + if (typeof atlasData === 'string') + { + var json, xml; + + try + { + json = JSON.parse(atlasData); + } + catch ( e ) + { + xml = this.parseXml(atlasData); + } + + if (!xml && !json) + { + throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given"); + } + + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml, + atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing }); + } + } + + return this; + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONArray + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONHash + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * This call expects the atlas data to be in the Starling XML data format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasXML + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasXML: function (key, textureURL, atlasURL, atlasData) { + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (!atlasURL && !atlasData) + { + atlasURL = key + '.xml'; + } + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlas + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. + * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING. + * @return {Phaser.Loader} This Loader instance. + */ + atlas: function (key, textureURL, atlasURL, atlasData, format) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } + + if (!atlasURL && !atlasData) + { + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + atlasURL = key + '.xml'; + } + else + { + atlasURL = key + '.json'; + } + } + + // A URL to a json/xml file has been given + if (atlasURL) + { + this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); + } + else + { + switch (format) + { + // A json string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: + + if (typeof atlasData === 'string') + { + atlasData = JSON.parse(atlasData); + } + break; + + // An xml string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: + + if (typeof atlasData === 'string') + { + var xml = this.parseXml(atlasData); + + if (!xml) + { + throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); + } + + atlasData = xml; + } + break; + } + + this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); + + } + + return this; + + }, + + /** + * Add a synchronization point to the assets / files added within the supplied callback. + * + * A synchronization point denotes that an asset _must_ be completely loaded before + * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait + * for previous assets to load (unless they are sync-points). Resources, such as packs, may still + * be downloaded around sync-points, as long as they do not finalize loading. + * + * @method Phaser.Loader#withSyncPoint + * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader. + * @param {object} [callbackContext=(loader)] - Context for the callback. + * @return {Phaser.Loader} This Loader instance. + */ + withSyncPoint: function (callback, callbackContext) { + + this._withSyncPointDepth++; + + try { + callback.call(callbackContext || this, this); + } finally { + this._withSyncPointDepth--; + } + + return this; + }, + + /** + * Add a synchronization point to a specific file/asset in the load queue. + * + * This has no effect on already loaded assets. + * + * @method Phaser.Loader#addSyncPoint + * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc). + * @param {string} key - Key of the file you want to turn into a sync point. + * @return {Phaser.Loader} This Loader instance. + * @see {@link Phaser.Loader#withSyncPoint withSyncPoint} + */ + addSyncPoint: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + asset.file.syncPoint = true; + } + + return this; + }, + + /** + * Remove a file/asset from the loading queue. + * + * A file that is loaded or has started loading cannot be removed. + * + * @method Phaser.Loader#removeFile + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - Key of the file you want to remove. + */ + removeFile: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + if (!asset.loaded && !asset.loading) + { + this._fileList.splice(asset.index, 1); + } + } + + }, + + /** + * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead. + * + * @method Phaser.Loader#removeAll + * @protected + */ + removeAll: function () { + + this._fileList.length = 0; + this._flightQueue.length = 0; + + }, + + /** + * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. + * + * @method Phaser.Loader#start + */ + start: function () { + + if (this.isLoading) + { + return; + } + + this.hasLoaded = false; + this.isLoading = true; + + this.updateProgress(); + + this.processLoadQueue(); + + }, + + /** + * Process the next item(s) in the file/asset queue. + * + * Process the queue and start loading enough items to fill up the inflight queue. + * + * If a sync-file is encountered then subsequent asset processing is delayed until it completes. + * The exception to this rule is that packfiles can be downloaded (but not processed) even if + * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel. + * such as during the start phaser. + * + * @method Phaser.Loader#processLoadQueue + * @private + */ + processLoadQueue: function () { + + if (!this.isLoading) + { + console.warn('Phaser.Loader - active loading canceled / reset'); + this.finishedLoading(true); + return; + } + + // Empty the flight queue as applicable + for (var i = 0; i < this._flightQueue.length; i++) + { + var file = this._flightQueue[i]; + + if (file.loaded || file.error) + { + this._flightQueue.splice(i, 1); + i--; + + file.loading = false; + file.requestUrl = null; + file.requestObject = null; + + if (file.error) + { + this.onFileError.dispatch(file.key, file); + } + + if (file.type !== 'packfile') + { + this._loadedFileCount++; + this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount); + } + else if (file.type === 'packfile' && file.error) + { + // Non-error pack files are handled when processing the file queue + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + } + } + + // When true further non-pack file downloads are suppressed + var syncblock = false; + + var inflightLimit = this.enableParallel ? Math.max(1, this.maxParallelDownloads) : 1; + + for (var i = this._processingHead; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + // Pack is fetched (ie. has data) and is currently at the start of the process queue. + if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead) + { + // Processing the pack / adds more files + this.processPack(file); + + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + if (file.loaded || file.error) + { + // Item at the start of file list finished, can skip it in future + if (i === this._processingHead) + { + this._processingHead = i + 1; + } + } + else if (!file.loading && this._flightQueue.length < inflightLimit) + { + // -> not loaded/failed, not loading + if (file.type === 'packfile' && !file.data) + { + // Fetches the pack data: the pack is processed above as it reaches queue-start. + // (Packs do not trigger onLoadStart or onFileStart.) + this._flightQueue.push(file); + file.loading = true; + + this.loadFile(file); + } + else if (!syncblock) + { + if (!this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this._flightQueue.push(file); + file.loading = true; + this.onFileStart.dispatch(this.progress, file.key, file.url); + + this.loadFile(file); + } + } + + if (!file.loaded && file.syncPoint) + { + syncblock = true; + } + + // Stop looking if queue full - or if syncblocked and there are no more packs. + // (As only packs can be loaded around a syncblock) + if (this._flightQueue.length >= inflightLimit || + (syncblock && this._loadedPackCount === this._totalPackCount)) + { + break; + } + } + + this.updateProgress(); + + // True when all items in the queue have been advanced over + // (There should be no inflight items as they are complete - loaded/error.) + if (this._processingHead >= this._fileList.length) + { + this.finishedLoading(); + } + else if (!this._flightQueue.length) + { + // Flight queue is empty but file list is not done being processed. + // This indicates a critical internal error with no known recovery. + console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled"); + + var _this = this; + + setTimeout(function () { + _this.finishedLoading(true); + }, 2000); + } + + }, + + /** + * The loading is all finished. + * + * @method Phaser.Loader#finishedLoading + * @private + * @param {boolean} [abnormal=true] - True if the loading finished abnormally. + */ + finishedLoading: function (abnormal) { + + if (this.hasLoaded) + { + return; + } + + this.hasLoaded = true; + this.isLoading = false; + + // If there were no files make sure to trigger the event anyway, for consistency + if (!abnormal && !this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this.reset(); + + this.onLoadComplete.dispatch(); + + // Check if the state still exists since destroy could have occurred while loading + if (this.game.state) + { + this.game.state.loadComplete(); + } + + }, + + /** + * Informs the loader that the given file resource has been fetched and processed; + * or such a request has failed. + * + * @method Phaser.Loader#asyncComplete + * @private + * @param {object} file + * @param {string} [error=''] - The error message, if any. No message implies no error. + */ + asyncComplete: function (file, errorMessage) { + + if (errorMessage === undefined) { errorMessage = ''; } + + file.loaded = true; + file.error = !!errorMessage; + + if (errorMessage) + { + file.errorMessage = errorMessage; + + console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage); + } + + this.processLoadQueue(); + + }, + + /** + * Process pack data. This will usually modify the file list. + * + * @method Phaser.Loader#processPack + * @private + * @param {object} pack + */ + processPack: function (pack) { + + var packData = pack.data[pack.key]; + + if (!packData) + { + console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key'); + return; + } + + for (var i = 0; i < packData.length; i++) + { + var file = packData[i]; + + switch (file.type) + { + case "image": + this.image(file.key, file.url, file.overwrite); + break; + + case "text": + this.text(file.key, file.url, file.overwrite); + break; + + case "json": + this.json(file.key, file.url, file.overwrite); + break; + + case "xml": + this.xml(file.key, file.url, file.overwrite); + break; + + case "script": + this.script(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "binary": + this.binary(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "spritesheet": + this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case "video": + this.video(file.key, file.urls); + break; + + case "audio": + this.audio(file.key, file.urls, file.autoDecode); + break; + + case "audiosprite": + this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode); + break; + + case "tilemap": + this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]); + break; + + case "physics": + this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]); + break; + + case "bitmapFont": + this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing); + break; + + case "atlasJSONArray": + this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasJSONHash": + this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasXML": + this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlas": + this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]); + break; + + case "shader": + this.shader(file.key, file.url, file.overwrite); + break; + } + } + + }, + + /** + * Transforms the asset URL. + * + * The default implementation prepends the baseURL if the url doesn't begin with http or // + * + * @method Phaser.Loader#transformUrl + * @protected + * @param {string} url - The url to transform. + * @param {object} file - The file object being transformed. + * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead. + */ + transformUrl: function (url, file) { + + if (!url) + { + return false; + } + + if (url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) + { + return url; + } + else + { + return this.baseURL + file.path + url; + } + + }, + + /** + * Start fetching a resource. + * + * All code paths, async or otherwise, from this function must return to `asyncComplete`. + * + * @method Phaser.Loader#loadFile + * @private + * @param {object} file + */ + loadFile: function (file) { + + // Image or Data? + switch (file.type) + { + case 'packfile': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'image': + case 'spritesheet': + case 'textureatlas': + case 'bitmapfont': + this.loadImageTag(file); + break; + + case 'audio': + file.url = this.getAudioURL(file.url); + + if (file.url) + { + // WebAudio or Audio Tag? + if (this.game.sound.usingWebAudio) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + else if (this.game.sound.usingAudioTag) + { + this.loadAudioTag(file); + } + } + else + { + this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support'); + } + break; + + case 'video': + file.url = this.getVideoURL(file.url); + + if (file.url) + { + if (file.asBlob) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'blob', this.fileComplete); + } + else + { + this.loadVideoTag(file); + } + } + else + { + this.fileError(file, null, 'No supported video URL specified or device does not have video playback support'); + } + break; + + case 'json': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + break; + + case 'xml': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete); + break; + + case 'tilemap': + + if (file.format === Phaser.Tilemap.TILED_JSON) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Tilemap.CSV) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete); + } + else + { + this.asyncComplete(file, "invalid Tilemap format: " + file.format); + } + break; + + case 'text': + case 'script': + case 'shader': + case 'physics': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'texture': + + if (file.key.split('_').pop() === 'truecolor') + { + this.loadImageTag(file); + } + else + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + break; + + case 'binary': + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + break; + } + + }, + + /** + * Continue async loading through an Image tag. + * @private + */ + loadImageTag: function (file) { + var _this = this; + + file.data = new Image(); + file.data.name = file.key; + + if (this.crossOrigin) + { + file.data.crossOrigin = this.crossOrigin; + } + + file.data.onload = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileComplete(file); + } + }; + + file.data.onerror = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileError(file); + } + }; + + file.data.src = this.transformUrl(file.url, file); + + // Image is immediately-available/cached + // Special Firefox magic, exclude from cached reload + // More info here: https://github.com/photonstorm/phaser/issues/2534 + if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height) + { + file.data.onload = null; + file.data.onerror = null; + this.fileComplete(file); + } + + }, + + /** + * Continue async loading through a Video tag. + * @private + */ + loadVideoTag: function (file) { + + var _this = this; + + file.data = document.createElement("video"); + file.data.name = file.key; + file.data.controls = false; + file.data.autoplay = false; + + var videoLoadEvent = function () { + + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = true; + Phaser.GAMES[_this.game.id].load.fileComplete(file); + + }; + + file.data.onerror = function () { + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = false; + _this.fileError(file); + }; + + file.data.addEventListener(file.loadEvent, videoLoadEvent, false); + + file.data.src = this.transformUrl(file.url, file); + file.data.load(); + + }, + + /** + * Continue async loading through an Audio tag. + * @private + */ + loadAudioTag: function (file) { + + var _this = this; + + if (this.game.sound.touchLocked) + { + // If audio is locked we can't do this yet, so need to queue this load request. Bum. + file.data = new Audio(); + file.data.name = file.key; + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + + this.fileComplete(file); + } + else + { + file.data = new Audio(); + file.data.name = file.key; + + var playThroughEvent = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileComplete(file); + }; + + file.data.onerror = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileError(file); + }; + + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + file.data.addEventListener('canplaythrough', playThroughEvent, false); + file.data.load(); + } + + }, + + /** + * Starts the xhr loader. + * + * This is designed specifically to use with asset file processing. + * + * @method Phaser.Loader#xhrLoad + * @private + * @param {object} file - The file/pack to load. + * @param {string} url - The URL of the file. + * @param {string} type - The xhr responseType. + * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments. + * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments. + */ + xhrLoad: function (file, url, type, onload, onerror) { + + var xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = type; + + if (this.headers['requestedWith'] !== false) + { + xhr.setRequestHeader('X-Requested-With', this.headers['requestedWith']); + } + + if (this.headers[file.type]) + { + xhr.setRequestHeader('Accept', this.headers[file.type]); + } + + onerror = onerror || this.fileError; + + var _this = this; + + xhr.onload = function () { + + try { + if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. + return onerror.call(_this, file, xhr); + } + else { + return onload.call(_this, file, xhr); + } + } catch (e) { + + // If this was the last file in the queue and an error is thrown in the create method + // then it's caught here, so be sure we don't carry on processing it + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + } + }; + + xhr.onerror = function () { + + try { + + return onerror.call(_this, file, xhr); + + } catch (e) { + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + + } + }; + + file.requestObject = xhr; + file.requestUrl = url; + + xhr.send(); + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getVideoURL + * @private + * @param {object[]|string[]} urls - See {@link #video} for format. + * @return {string} The URL to try and fetch; or null. + */ + getVideoURL: function (urls) { + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var videoType; + + if (url.uri) // {uri: .., type: ..} pair + { + videoType = url.type; + url = url.uri; + + if (this.game.device.canPlayVideo(videoType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + videoType = extension.toLowerCase(); + + if (this.game.device.canPlayVideo(videoType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getAudioURL + * @private + * @param {object[]|string[]} urls - See {@link #audio} for format. + * @return {string} The URL to try and fetch; or null. + */ + getAudioURL: function (urls) { + + if (this.game.sound.noAudio) + { + return null; + } + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var audioType; + + if (url.uri) // {uri: .., type: ..} pair + { + audioType = url.type; + url = url.uri; + + if (this.game.device.canPlayAudio(audioType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + audioType = extension.toLowerCase(); + + if (this.game.device.canPlayAudio(audioType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Error occurred when loading a file. + * + * @method Phaser.Loader#fileError + * @private + * @param {object} file + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + * @param {string} reason + */ + fileError: function (file, xhr, reason) { + + var url = file.requestUrl || this.transformUrl(file.url, file); + var message = 'error loading asset from URL ' + url; + + if (!reason && xhr) + { + reason = xhr.status; + } + + if (reason) + { + message = message + ' (' + reason + ')'; + } + + this.asyncComplete(file, message); + + }, + + /** + * Called when a file has been downloaded and needs to be processed further. + * + * @method Phaser.Loader#fileComplete + * @private + * @param {object} file - File loaded + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + */ + fileComplete: function (file, xhr) { + + var loadNext = true; + + switch (file.type) + { + case 'packfile': + + // Pack data must never be false-ish after it is fetched without error + var data = JSON.parse(xhr.responseText); + file.data = data || {}; + break; + + case 'texture': + + var extension = /\.([^.]+)$/.exec(file.url.split('?', 1)[0])[1].toLowerCase(); + if (file.data !== null) + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, file.data); + } + else + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, xhr.response); + } + break; + + case 'image': + + this.cache.addImage(file.key, file.url, file.data); + break; + + case 'spritesheet': + + this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case 'textureatlas': + + if (file.atlasURL == null) + { + this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); + } + else + { + // Load the JSON or XML before carrying on with the next file + loadNext = false; + + if (file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_HASH || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete); + } + else + { + throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); + } + } + break; + + case 'bitmapfont': + + if (!file.atlasURL) + { + this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing); + } + else + { + // Load the XML before carrying on with the next file + loadNext = false; + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) { + var json; + + try + { + // Try to parse as JSON, if it fails, then it's hopefully XML + json = JSON.parse(xhr.responseText); + } + catch (e) {} + + if (!!json) + { + file.atlasType = 'json'; + this.jsonLoadComplete(file, xhr); + } + else + { + file.atlasType = 'xml'; + this.xmlLoadComplete(file, xhr); + } + }); + } + break; + + case 'video': + + if (file.asBlob) + { + try + { + file.data = xhr.response; + } + catch (e) + { + throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key); + } + } + + this.cache.addVideo(file.key, file.url, file.data, file.asBlob); + break; + + case 'audio': + + if (this.game.sound.usingWebAudio) + { + file.data = xhr.response; + + this.cache.addSound(file.key, file.url, file.data, true, false); + + if (file.autoDecode) + { + this.game.sound.decode(file.key); + } + } + else + { + this.cache.addSound(file.key, file.url, file.data, false, true); + } + break; + + case 'text': + file.data = xhr.responseText; + this.cache.addText(file.key, file.url, file.data); + break; + + case 'shader': + file.data = xhr.responseText; + this.cache.addShader(file.key, file.url, file.data); + break; + + case 'physics': + var data = JSON.parse(xhr.responseText); + this.cache.addPhysicsData(file.key, file.url, data, file.format); + break; + + case 'script': + file.data = document.createElement('script'); + file.data.language = 'javascript'; + file.data.type = 'text/javascript'; + file.data.defer = false; + file.data.text = xhr.responseText; + document.head.appendChild(file.data); + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText); + } + break; + + case 'binary': + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.response); + } + else + { + file.data = xhr.response; + } + + this.cache.addBinary(file.key, file.data); + + break; + } + + if (loadNext) + { + this.asyncComplete(file); + } + + }, + + /** + * Successfully loaded a JSON file - only used for certain types. + * + * @method Phaser.Loader#jsonLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + jsonLoadComplete: function (file, xhr) { + + var data = JSON.parse(xhr.responseText); + + if (file.type === 'tilemap') + { + this.cache.addTilemap(file.key, file.url, data, file.format); + } + else if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'json') + { + this.cache.addJSON(file.key, file.url, data); + } + else + { + this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); + } + + this.asyncComplete(file); + }, + + /** + * Successfully loaded a CSV file - only used for certain types. + * + * @method Phaser.Loader#csvLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + csvLoadComplete: function (file, xhr) { + + var data = xhr.responseText; + + this.cache.addTilemap(file.key, file.url, data, file.format); + + this.asyncComplete(file); + + }, + + /** + * Successfully loaded an XML file - only used for certain types. + * + * @method Phaser.Loader#xmlLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + xmlLoadComplete: function (file, xhr) { + + // Always try parsing the content as XML, regardless of actually response type + var data = xhr.responseText; + var xml = this.parseXml(data); + + if (!xml) + { + var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest + console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')'); + this.asyncComplete(file, "invalid XML"); + return; + } + + if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'textureatlas') + { + this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); + } + else if (file.type === 'xml') + { + this.cache.addXML(file.key, file.url, xml); + } + + this.asyncComplete(file); + + }, + + /** + * Parses string data as XML. + * + * @method Phaser.Loader#parseXml + * @private + * @param {string} data - The XML text to parse + * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document. + */ + parseXml: function (data) { + + var xml; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + // Why is this 'false'? + xml.async = 'false'; + xml.loadXML(data); + } + } + catch (e) + { + xml = null; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + return null; + } + else + { + return xml; + } + + }, + + /** + * Update the loading sprite progress. + * + * @method Phaser.Loader#updateProgress + * @private + */ + updateProgress: function () { + + if (this.preloadSprite) + { + if (this.preloadSprite.direction === 0) + { + this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress); + } + else + { + this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress); + } + + if (this.preloadSprite.sprite) + { + this.preloadSprite.sprite.updateCrop(); + } + else + { + // We seem to have lost our sprite - maybe it was destroyed? + this.preloadSprite = null; + } + } + + }, + + /** + * Returns the number of files that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedFiles + * @protected + * @return {number} The number of files that have already been loaded (even if they errored) + */ + totalLoadedFiles: function () { + + return this._loadedFileCount; + + }, + + /** + * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedFiles + * @protected + * @return {number} The number of files that still remain in the load queue. + */ + totalQueuedFiles: function () { + + return this._totalFileCount - this._loadedFileCount; + + }, + + /** + * Returns the number of asset packs that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedPacks + * @protected + * @return {number} The number of asset packs that have already been loaded (even if they errored) + */ + totalLoadedPacks: function () { + + return this._totalPackCount; + + }, + + /** + * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedPacks + * @protected + * @return {number} The number of asset packs that still remain in the load queue. + */ + totalQueuedPacks: function () { + + return this._totalPackCount - this._loadedPackCount; + + } + +}; + +/** +* The non-rounded load progress value (from 0.0 to 100.0). +* +* A general indicator of the progress. +* It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. +* +* @name Phaser.Loader#progressFloat +* @property {number} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progressFloat", { + + get: function () { + var progress = (this._loadedFileCount / this._totalFileCount) * 100; + return Phaser.Math.clamp(progress || 0, 0, 100); + } + +}); + +/** +* The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}. +* +* @name Phaser.Loader#progress +* @property {integer} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progress", { + + get: function () { + return Math.round(this.progressFloat); + } + +}); + +Phaser.Loader.prototype.constructor = Phaser.Loader; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. +* +* @class Phaser.LoaderParser +*/ +Phaser.LoaderParser = { + + /** + * Alias for xmlBitmapFont, for backwards compatibility. + * + * @method Phaser.LoaderParser.bitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + bitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing, frame, resolution); + + }, + + /** + * Parse a Bitmap Font from an XML file. + * + * @method Phaser.LoaderParser.xmlBitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing; + data.chars = {}; + + var letters = xml.getElementsByTagName('char'); + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + for (var i = 0; i < letters.length; i++) + { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + data.chars[charCode] = { + x: x + parseInt(letters[i].getAttribute('x'), 10), + y: y + parseInt(letters[i].getAttribute('y'), 10), + width: parseInt(letters[i].getAttribute('width'), 10), + height: parseInt(letters[i].getAttribute('height'), 10), + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10) / resolution, + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10) / resolution, + xAdvance: (parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing) / resolution, + kerning: {} + }; + } + + var kernings = xml.getElementsByTagName('kerning'); + + for (i = 0; i < kernings.length; i++) + { + var first = parseInt(kernings[i].getAttribute('first'), 10); + var second = parseInt(kernings[i].getAttribute('second'), 10); + var amount = parseInt(kernings[i].getAttribute('amount'), 10) / resolution; + + data.chars[second].kerning[first] = amount; + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Parse a Bitmap Font from a JSON file. + * + * @method Phaser.LoaderParser.jsonBitmapFont + * @param {object} json - JSON data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = { + font: json.font.info._face, + size: parseInt(json.font.info._size, 10), + lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing, + chars: {} + }; + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + json.font.chars["char"].forEach( + + function parseChar(letter) { + + var charCode = parseInt(letter._id, 10); + + data.chars[charCode] = { + x: x + parseInt(letter._x, 10), + y: y + parseInt(letter._y, 10), + width: parseInt(letter._width, 10), + height: parseInt(letter._height, 10), + xOffset: parseInt(letter._xoffset, 10) / resolution, + yOffset: parseInt(letter._yoffset, 10) / resolution, + xAdvance: (parseInt(letter._xadvance, 10) + xSpacing) / resolution, + kerning: {} + }; + } + + ); + + if (json.font.kernings && json.font.kernings.kerning) + { + json.font.kernings.kerning.forEach( + + function parseKerning(kerning) { + + data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10) / resolution; + + } + + ); + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Finalize Bitmap Font parsing. + * + * @method Phaser.LoaderParser.finalizeBitmapFont + * @private + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {object} bitmapFontData - Pre-parsed bitmap font data. + * @return {object} The parsed Bitmap Font data. + */ + finalizeBitmapFont: function (baseTexture, bitmapFontData) { + + Object.keys(bitmapFontData.chars).forEach( + + function addTexture(charCode) { + + var letter = bitmapFontData.chars[charCode]; + + letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height)); + + } + + ); + + return bitmapFontData; + + }, + + /** + * Extract PVR header from loaded binary + * + * @method Phaser.LoaderParser.pvr + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PVR file including texture data. + */ + pvr: function (arrayBuffer) { + + // Reference: http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf + // PVR 3 header structure + // --------------------------------------- + // address: 0, size: 4 bytes version + // address: 4, size: 4 bytes flags + // address: 8, size: 8 bytes pixel format + // address: 16, size: 4 bytes color space + // address: 20, size: 4 bytes channel type + // address: 24, size: 4 bytes height + // address: 28, size: 4 bytes width + // address: 32, size: 4 bytes depth + // address: 36, size: 4 bytes number of surfaces + // address: 40, size: 4 bytes number of faces + // address: 44, size: 4 bytes number of mipmaps + // address: 48, size: 4 bytes meta data size + // --------------------------------------- + var uintArray = new Uint32Array(arrayBuffer.slice(0, 52)), + byteArray = new Uint8Array(arrayBuffer), + pvrHeader = null, + pixelFormat = (uintArray[3] << 32 | uintArray[2]), + compressionAlgorithm, + glExtensionFormat = 0; + + if (uintArray[0] === 0x03525650 && + [ // Validate WebGL Pixel Format + 0, 1, 2, 3, + 6, 7, 9, 11 + ].indexOf(pixelFormat) >= 0 + ) { + if (pixelFormat >= 0 && pixelFormat <= 3) { + compressionAlgorithm = 'PVRTC'; + } else if (pixelFormat >= 7 && pixelFormat <= 11) { + compressionAlgorithm = 'S3TC'; + } else if (pixelFormat === 6) { + compressionAlgorithm = 'ETC1'; + } + + switch (pixelFormat) { + case 0: + glExtensionFormat = 0x8C01; + break; + case 1: + glExtensionFormat = 0x8C03; + break; + case 2: + glExtensionFormat = 0x8C00; + break; + case 3: + glExtensionFormat = 0x8C02; + break; + case 6: + glExtensionFormat = 0x8D64; + break; + case 7: + glExtensionFormat = 0x83F1; + break; + case 9: + glExtensionFormat = 0x83F2; + break; + case 11: + glExtensionFormat = 0x83F3; + break; + default: + glExtensionFormat = -1; + } + + pvrHeader = { + complete: true, + fileFormat: 'PVR', + compressionAlgorithm: compressionAlgorithm, + flags: uintArray[1], + pixelFormat: pixelFormat, + colorSpace: uintArray[4], + channelType: uintArray[5], + height: uintArray[6], + width: uintArray[7], + depth: uintArray[8], + numberOfSurfaces: uintArray[9], + numberOfFaces: uintArray[10], + numberOfMipmaps: uintArray[11], + metaDataSize: uintArray[12], + textureData: byteArray.subarray(52 + uintArray[12], byteArray.byteLength), + glExtensionFormat: glExtensionFormat + }; + } + + return pvrHeader; + + }, + + /** + * Extract DDS header from loaded binary + * + * @method Phaser.LoaderParser.dds + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed DDS file including texture data. + */ + dds: function (arrayBuffer) { + + // Reference at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx + // DDS header structure + // --------------------------------------- + // address: 0, size: 4 bytes Identifier 'DDS ' + // address: 4, size: 4 bytes size + // address: 8, size: 4 bytes flags + // address: 12, size: 4 bytes height + // address: 16, size: 4 bytes width + // address: 20, size: 4 bytes pitch or linear size + // address: 24, size: 4 bytes depth + // address: 28, size: 4 bytes mipmap count + // address: 32, size: 44 bytes reserved space 1 + // address: 76, size: 4 pixel format size + // address: 80, size: 4 pixel format flag + // address: 84, size: 4 pixel format four CC + // address: 88, size: 4 pixel format bit count + // address: 92, size: 4 pixel format R bit mask + // address: 96, size: 4 pixel format G bit mask + // address: 100, size: 4 pixel format B bit mask + // address: 104, size: 4 pixel format A bit mask + // address: 108, size: 4 caps 1 + // address: 112, size: 4 caps 2 + // address: 116, size: 4 caps 3 + // address: 120, size: 4 caps 4 + // address: 124, size: 4 reserved 2 + // -- DXT10 extension + // address: 130, size: 4 DXGI Format + // address: 134, size: 4 resource dimension + // address: 138, size: 4 misc flag + // address: 142, size: 4 array size + // address: 146, size: 4 misc flag 2 + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ddsHeader = null; + + if (byteArray[0] === 0x44 && + byteArray[1] === 0x44 && + byteArray[2] === 0x53 && + byteArray[3] === 0x20) { + ddsHeader = { + complete: true, + fileFormat: 'DDS', + compressionAlgorithm: 'S3TC', + size: uintArray[1], + flags: uintArray[2], + height: uintArray[3], + width: uintArray[4], + pitch: uintArray[5], + depth: uintArray[6], + mipmapCount: uintArray[7], + formatSize: uintArray[19], + formatFlag: uintArray[19], + formatFourCC: [ + String.fromCharCode(byteArray[84]), + String.fromCharCode(byteArray[85]), + String.fromCharCode(byteArray[86]), + String.fromCharCode(byteArray[87]) + ].join(''), + formatBitCount: uintArray[21], + formatRBitMask: uintArray[22], + formatGBitMask: uintArray[23], + formatBBitMask: uintArray[24], + formatABitMask: uintArray[25], + caps1: uintArray[26], + caps2: uintArray[27], + caps3: uintArray[28], + caps4: uintArray[29], + reserved2: uintArray[30], + DXGIFormat: null, + resourceDimension: null, + miscFlag: null, + arraySize: null, + textureData: byteArray.subarray(uintArray[1] + 4, byteArray.byteLength) + }; + if (ddsHeader.formatFourCC === 'DX10') { + ddsHeader.DXGIFormat = uintArray[31]; + ddsHeader.resourceDimension = uintArray[32]; + ddsHeader.miscFlag = uintArray[33]; + ddsHeader.arraySize = uintArray[34]; + ddsHeader.miscFlag = uintArray[35]; + } + } + + return ddsHeader; + + }, + + /** + * Extract KTX header from loaded binary + * + * @method Phaser.LoaderParser.ktx + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed KTX file including texture data. + */ + ktx: function (arrayBuffer) { + + // Reference: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + // KTX header structure + // --------------------------------------- + // address: 0, size 12 bytes: Identifier '«KTX 11»\r\n\x1A\n' + // address: 12, size 4 bytes: endianness + // address: 16, size 4 bytes: GL type + // address: 20, size 4 bytes: GL type size + // address: 24, size 4 bytes: GL format + // address: 28, size 4 bytes: GL internal format + // address: 32, size 4 bytes: GL base internal format + // address: 36, size 4 bytes: pixel width + // address: 40, size 4 bytes: pixel height + // address: 44, size 4 bytes: pixel depth + // address: 48, size 4 bytes: number of array elements + // address: 52, size 4 bytes: number of faces + // address: 56, size 4 bytes: number of mipmap levels + // address: 60, size 4 bytes: bytes of key value data + // address: 64, size 4 bytes: key and value bytes size + // address: X, size 1 byte : key and value + // address: X, size 1 byte : value padding + // address: X, size 4 byte : image size + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ktxHeader = null, + imageSizeOffset = 16 + (uintArray[15] / 4) | 0, + imageSize = uintArray[imageSizeOffset], + glInternalFormat = uintArray[7], + compressionAlgorithm = 0; + + if (byteArray[0] === 0xAB && byteArray[1] === 0x4B && + byteArray[2] === 0x54 && byteArray[3] === 0x58 && + byteArray[4] === 0x20 && byteArray[5] === 0x31 && + byteArray[6] === 0x31 && byteArray[7] === 0xBB && + byteArray[8] === 0x0D && byteArray[9] === 0x0A && + byteArray[10] === 0x1A && byteArray[11] === 0x0A && + //Check if internal GL format is supported by WebGL + [ + // ETC1 + 0x8D64, + // PVRTC + 0x8C00, 0x8C01, 0x8C02, 0x8C03, + // DXTC | S3TC + 0x83F0, 0x83F1, 0x83F2, 0x83F3 + ].indexOf(glInternalFormat) >= 0) { + switch (glInternalFormat) { + case 0x8D64: + compressionAlgorithm = 'ETC1'; + break; + case 0x8C00: + case 0x8C01: + case 0x8C02: + case 0x8C03: + compressionAlgorithm = 'PVRTC'; + break; + case 0x83F0: + case 0x83F1: + case 0x83F2: + case 0x83F3: + compressionAlgorithm = 'S3TC'; + break; + } + + ktxHeader = { + complete: true, + fileFormat: 'KTX', + compressionAlgorithm: compressionAlgorithm, + endianness: uintArray[3], + glType: uintArray[4], + glTypeSize: uintArray[5], + glFormat: uintArray[6], + glInternalFormat: uintArray[7], + glBaseInternalFormat: uintArray[8], + width: uintArray[9], + height: uintArray[10], + pixelDepth: uintArray[11], + numberOfArrayElements: uintArray[12], + numberOfFaces: uintArray[13], + numberOfMipmapLevels: uintArray[14], + bytesOfKeyValueData: uintArray[15], + keyAndValueByteSize: uintArray[16], + imageSize: imageSize, + textureData: byteArray.subarray((imageSizeOffset + 1) * 4, imageSize + 100) + }; + } + + return ktxHeader; + + }, + + /** + * Extract PKM header from loaded binary + * + * @method Phaser.LoaderParser.pkm + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PKM file including texture data. + */ + pkm: function (arrayBuffer) { + + // PKM header structure + // --------------------------------------- + // address: 0, size 4 bytes: for 'PKM ' + // address: 4, size 2 bytes: for version + // address: 6, size 2 bytes: for type + // address: 8, size 2 bytes: for extended width + // address: 10, size 2 bytes: for extended height + // address: 12, size 2 bytes: for original width + // address: 14, size 2 bytes: for original height + // address: 16, texture data + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + pkmHeader = null; + + if (byteArray[0] === 0x50 && + byteArray[1] === 0x4B && + byteArray[2] === 0x4D && + byteArray[3] === 0x20) { + + pkmHeader = { + complete: true, + fileFormat: 'PKM', + compressionAlgorithm: 'ETC1', + format: ((byteArray[6] << 8 | byteArray[7])) & 0xFFFF, + width: ((byteArray[8] << 8 | byteArray[9])) & 0xFFFF, + height: ((byteArray[10] << 8 | byteArray[11])) & 0xFFFF, + originalWidth: ((byteArray[12] << 8 | byteArray[13])) & 0xFFFF, + originalHeight: ((byteArray[14] << 8 | byteArray[15])) & 0xFFFF, + textureData: byteArray.subarray(16, byteArray.length) + }; + } + + return pkmHeader; + + } + +}; + +/** + * @author Jeremy Dowell + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * Audio Sprites are a combination of audio files and a JSON configuration. + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * @class Phaser.AudioSprite + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + * @param {string} key - Asset key for the sound. + */ +Phaser.AudioSprite = function (game, key) { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * Asset key for the Audio Sprite. + * @property {string} key + */ + this.key = key; + + /** + * JSON audio atlas object. + * @property {object} config + */ + this.config = this.game.cache.getJSON(key + '-audioatlas'); + + /** + * If a sound is set to auto play, this holds the marker key of it. + * @property {string} autoplayKey + */ + this.autoplayKey = null; + + /** + * Is a sound set to autoplay or not? + * @property {boolean} autoplay + * @default + */ + this.autoplay = false; + + /** + * An object containing the Phaser.Sound objects for the Audio Sprite. + * @property {object} sounds + */ + this.sounds = {}; + + for (var k in this.config.spritemap) + { + var marker = this.config.spritemap[k]; + var sound = this.game.add.sound(this.key); + + sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop); + + this.sounds[k] = sound; + } + + if (this.config.autoplay) + { + this.autoplayKey = this.config.autoplay; + this.play(this.autoplayKey); + this.autoplay = this.sounds[this.autoplayKey]; + } + +}; + +Phaser.AudioSprite.prototype = { + + /** + * Play a sound with the given name. + * + * @method Phaser.AudioSprite#play + * @param {string} [marker] - The name of sound to play + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, volume) { + + if (volume === undefined) { volume = 1; } + + return this.sounds[marker].play(marker, null, volume); + + }, + + /** + * Stop a sound with the given name. + * + * @method Phaser.AudioSprite#stop + * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite. + */ + stop: function (marker) { + + if (!marker) + { + for (var key in this.sounds) + { + this.sounds[key].stop(); + } + } + else + { + this.sounds[marker].stop(); + } + + }, + + /** + * Get a sound with the given name. + * + * @method Phaser.AudioSprite#get + * @param {string} marker - The name of sound to get. + * @return {Phaser.Sound} The sound instance. + */ + get: function(marker) { + + return this.sounds[marker]; + + } + +}; + +Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound class constructor. +* +* @class Phaser.Sound +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {string} key - Asset key for the sound. +* @param {number} [volume=1] - Default value for the volume, between 0 and 1. +* @param {boolean} [loop=false] - Whether or not the sound will loop. +*/ +Phaser.Sound = function (game, key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = game.sound.connectToMaster; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * @property {string} name - Name of the sound. + */ + this.name = key; + + /** + * @property {string} key - Asset key for the sound. + */ + this.key = key; + + /** + * @property {boolean} loop - Whether or not the sound or current sound marker will loop. + */ + this.loop = loop; + + /** + * @property {object} markers - The sound markers. + */ + this.markers = {}; + + /** + * @property {AudioContext} context - Reference to the AudioContext instance. + */ + this.context = null; + + /** + * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically. + */ + this.autoplay = false; + + /** + * @property {number} totalDuration - The total duration of the sound in seconds. + */ + this.totalDuration = 0; + + /** + * @property {number} startTime - The time the sound starts at in ms (typically 0 unless starting from a marker). + * @default + */ + this.startTime = 0; + + /** + * @property {number} currentTime - The current time of sound playback in ms. + */ + this.currentTime = 0; + + /** + * @property {number} duration - The duration of the current sound marker in seconds. + */ + this.duration = 0; + + /** + * @property {number} durationMS - The duration of the current sound marker in ms. + */ + this.durationMS = 0; + + /** + * @property {number} position - The position of the current sound marker in ms. + */ + this.position = 0; + + /** + * @property {number} stopTime - The time the sound stopped in ms. + */ + this.stopTime = 0; + + /** + * @property {boolean} paused - true if the sound is paused, otherwise false. + * @default + */ + this.paused = false; + + /** + * @property {number} pausedPosition - The position the sound had reached when it was paused in ms. + */ + this.pausedPosition = 0; + + /** + * @property {number} pausedTime - The game time (ms) at which the sound was paused. + */ + this.pausedTime = 0; + + /** + * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false. + * @default + */ + this.isPlaying = false; + + /** + * @property {string} currentMarker - The string ID of the currently playing marker, if any. + * @default + */ + this.currentMarker = ''; + + /** + * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. + */ + this.fadeTween = null; + + /** + * @property {boolean} pendingPlayback - true if the sound file is pending playback + * @readonly + */ + this.pendingPlayback = false; + + /** + * @property {boolean} override - if true when you play this sound it will always start from the beginning. + * @default + */ + this.override = false; + + /** + * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. + * @default + */ + this.allowMultiple = false; + + /** + * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio. + * @readonly + */ + this.usingWebAudio = this.game.sound.usingWebAudio; + + /** + * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag. + */ + this.usingAudioTag = this.game.sound.usingAudioTag; + + /** + * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. + */ + this.externalNode = null; + + /** + * @property {object} masterGainNode - The master gain node in a Web Audio system. + */ + this.masterGainNode = null; + + /** + * @property {object} gainNode - The gain node in a Web Audio system. + */ + this.gainNode = null; + + /** + * @property {object} _sound - Internal var. + * @private + */ + this._sound = null; + + /** + * @property {object} _globalVolume - Internal var for keeping track of global volume when using AudioTag + * @private + */ + this._globalVolume = 1; + + /** + * @property {boolean} _markedToDelete - When audio stops, disconnect Web Audio nodes. + * @private + */ + this._markedToDelete = false; + + /** + * @property {boolean} _removeFromSoundManager - When audio stops, remove it from the Sound Manager and destroy it. + * @private + */ + this._removeFromSoundManager = false; + + + + if (this.usingWebAudio) + { + this.context = this.game.sound.context; + this.masterGainNode = this.game.sound.masterGain; + + if (this.context.createGain === undefined) + { + this.gainNode = this.context.createGainNode(); + } + else + { + this.gainNode = this.context.createGain(); + } + + this.gainNode.gain.value = volume; + + if (connect) + { + this.gainNode.connect(this.masterGainNode); + } + } + else if (this.usingAudioTag) + { + if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key)) + { + this._sound = this.game.cache.getSoundData(key); + this.totalDuration = 0; + + if (this._sound.duration) + { + this.totalDuration = this._sound.duration; + } + } + else + { + this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this); + } + } + + /** + * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files). It passes one argument, this sound. + */ + this.onDecoded = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played or a looping marker is restarted. It passes one argument, this sound. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. It passes one argument, this sound. + */ + this.onPause = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. It passes one argument, this sound. + */ + this.onResume = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. It passes one argument, this sound. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback or when a non-looping marker completes. It passes two arguments: this sound and any {@link #currentMarker marker} that was playing. + */ + this.onStop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted. It passes one argument, this sound. + */ + this.onMute = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. It passes two arguments: the {@link #currentMarker} and this sound. + */ + this.onMarkerComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out. It passes two arguments: this sound and its current {@link #volume}. + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + */ + this._volume = volume; + + /** + * @property {any} _buffer - Decoded data buffer / Audio tag. + * @private + */ + this._buffer = null; + + /** + * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. + * @private + */ + this._muted = false; + + /** + * @property {number} _tempMarker - Internal marker var. + * @private + */ + this._tempMarker = 0; + + /** + * @property {number} _tempPosition - Internal marker var. + * @private + */ + this._tempPosition = 0; + + /** + * @property {number} _tempVolume - Internal marker var. + * @private + */ + this._tempVolume = 0; + + /** + * @property {number} _tempPause - Internal marker var. + * @private + */ + this._tempPause = 0; + + /** + * @property {number} _muteVolume - Internal cache var. + * @private + */ + this._muteVolume = 0; + + /** + * @property {boolean} _tempLoop - Internal cache var. + * @private + */ + this._tempLoop = 0; + + /** + * @property {boolean} _paused - Was this sound paused via code or a game event? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched? + * @private + */ + this._onDecodedEventDispatched = false; + +}; + +Phaser.Sound.prototype = { + + /** + * Called automatically when this sound is unlocked. + * @method Phaser.Sound#soundHasUnlocked + * @param {string} key - The Phaser.Cache key of the sound file to check for decoding. + * @protected + */ + soundHasUnlocked: function (key) { + + if (key === this.key) + { + this._sound = this.game.cache.getSoundData(this.key); + this.totalDuration = this._sound.duration; + } + + }, + + /** + * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound#addMarker + * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. + * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). + * @param {boolean} [loop=false] - Sets if the sound will loop or not. + */ + addMarker: function (name, start, duration, volume, loop) { + + if (duration === undefined || duration === null) { duration = 1; } + if (volume === undefined || volume === null) { volume = 1; } + if (loop === undefined) { loop = false; } + + this.markers[name] = { + name: name, + start: start, + stop: start + duration, + volume: volume, + duration: duration, + durationMS: duration * 1000, + loop: loop + }; + + }, + + /** + * Removes a marker from the sound. + * @method Phaser.Sound#removeMarker + * @param {string} name - The key of the marker to remove. + */ + removeMarker: function (name) { + + delete this.markers[name]; + + }, + + /** + * Called automatically by the AudioContext when the sound stops playing. + * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. + * + * @method Phaser.Sound#onEndedHandler + * @protected + */ + onEndedHandler: function () { + + this._sound.onended = null; + this.isPlaying = false; + this.currentTime = this.durationMS; + this.stop(); + + if (this._markedToDelete) + { + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + if (this._removeFromSoundManager) + { + this.game.sound.remove(this); + } + else + { + 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(); + } + } + }, + + /** + * Called automatically by Phaser.SoundManager. + * @method Phaser.Sound#update + * @protected + */ + update: function () { + + if (!this.game.cache.checkSoundKey(this.key)) + { + this.destroy(); + return; + } + + if (this.isDecoded && !this._onDecodedEventDispatched) + { + this.onDecoded.dispatch(this); + this._onDecodedEventDispatched = true; + } + + if (this.pendingPlayback && this.game.cache.isSoundReady(this.key)) + { + this.pendingPlayback = false; + this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop); + } + + if (this.isPlaying) + { + this.currentTime = this.game.time.time - this.startTime; + + if (this.currentTime >= this.durationMS) + { + if (this.usingWebAudio) + { + if (this.loop) + { + // won't work with markers, needs to reset the position + this.onLoop.dispatch(this); + + // Gets reset by the play function + this.isPlaying = false; + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + this.isPlaying = true; // play not called again in this case + } + else + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + this.play(this.currentMarker, 0, this.volume, true, true); + } + } + else + { + // Stop if we're using an audio marker, otherwise we let onended handle it + if (this.currentMarker !== '') + { + this.stop(); + } + } + } + else + { + if (this.loop) + { + this.onLoop.dispatch(this); + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + } + + // Gets reset by the play function + this.isPlaying = false; + + this.play(this.currentMarker, 0, this.volume, true, true); + } + else + { + this.stop(); + } + } + } + } + }, + + /** + * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters. + * + * @method Phaser.Sound#loopFull + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + loopFull: function (volume) { + + return this.play(null, 0, volume, true); + + }, + + /** + * Play this sound, or a marked section of it. + * + * @method Phaser.Sound#play + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. + * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, position, volume, loop, forceRestart) { + + if (marker === undefined || marker === false || marker === null) { marker = ''; } + if (forceRestart === undefined) { forceRestart = true; } + + if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override) + { + // Use Restart instead + return this; + } + + if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart)) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) { + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + + this.isPlaying = false; + } + + if (marker === '' && Object.keys(this.markers).length > 0) + { + // If they didn't specify a marker but this is an audio sprite, + // we should never play the entire thing + return this; + } + + if (marker !== '') + { + if (this.markers[marker]) + { + this.currentMarker = marker; + + // Playing a marker? Then we default to the marker values + 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 (volume === undefined) { volume = this._volume; } + if (loop === undefined) { loop = this.loop; } + + this.position = Math.max(0, 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) + { + // Does the sound need decoding? + if (this.game.cache.isSoundDecoded(this.key)) + { + this._sound = this.context.createBufferSource(); + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + this._buffer = this.game.cache.getSoundData(this.key); + this._sound.buffer = this._buffer; + + if (this.loop && marker === '') + { + this._sound.loop = true; + } + + if (!this.loop && marker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + this.totalDuration = this._sound.buffer.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = Math.ceil(this.totalDuration * 1000); + } + + // Useful to cache this somewhere perhaps? + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, this.position, this.duration); + } + else + { + if (this.loop && marker === '') + { + this._sound.start(0, 0); + } + else + { + this._sound.start(0, this.position, this.duration); + } + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + 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 doesn't become available until you call play(), wonderful ... + this.totalDuration = this._sound.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = this.totalDuration * 1000; + } + + this._sound.currentTime = this.position; + this._sound.muted = this._muted; + + if (this._muted || this.game.sound.mute) + { + this._sound.volume = 0; + } + else + { + this._sound.volume = this._volume; + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + this.currentTime = 0; + this.stopTime = this.startTime + this.durationMS; + + this.onPlay.dispatch(this); + } + else + { + this.pendingPlayback = true; + } + } + } + + return this; + + }, + + /** + * Restart the sound, or a marked section of it. + * + * @method Phaser.Sound#restart + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. + * @param {boolean} [loop=false] - Loop when it finished playing? + */ + restart: function (marker, position, volume, loop) { + + marker = marker || ''; + position = position || 0; + volume = volume || 1; + if (loop === undefined) { loop = false; } + + this.play(marker, position, volume, loop, true); + + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound#pause + */ + pause: function () { + + if (this.isPlaying && this._sound) + { + this.paused = true; + this.pausedPosition = this.currentTime; + this.pausedTime = this.game.time.time; + this._tempPause = this._sound.currentTime; + this.onPause.dispatch(this); + this.stop(); + } + + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound#resume + */ + resume: function () { + + if (this.paused && this._sound) + { + if (this.usingWebAudio) + { + var p = Math.max(0, this.position + (this.pausedPosition / 1000)); + + this._sound = this.context.createBufferSource(); + this._sound.buffer = this._buffer; + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + if (this.loop) + { + this._sound.loop = true; + } + + if (!this.loop && this.currentMarker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + var duration = this.duration - (this.pausedPosition / 1000); + + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, p, duration); + //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it + } + else + { + if (this.loop && this.game.device.chrome) + { + // Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099 + if (this.game.device.chromeVersion === 42) + { + this._sound.start(0); + } + else + { + this._sound.start(0, p); + } + } + else + { + this._sound.start(0, p, duration); + } + } + } + else + { + this._sound.currentTime = this._tempPause; + this._sound.play(); + } + + this.isPlaying = true; + this.paused = false; + this.startTime += (this.game.time.time - this.pausedTime); + this.onResume.dispatch(this); + } + + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound#stop + */ + stop: function () { + + if (this.isPlaying && this._sound) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) + { + // Thanks Android 4.4 + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + } + + this.pendingPlayback = false; + this.isPlaying = false; + + if (!this.paused) + { + var prevMarker = this.currentMarker; + + if (this.currentMarker !== '') + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + } + + this.currentMarker = ''; + + if (this.fadeTween !== null) + { + this.fadeTween.stop(); + } + + this.onStop.dispatch(this, prevMarker); + } + + }, + + /** + * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. + * Then increases the volume from 0 to 1 over the duration specified. + * + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (1) as the second parameter. + * + * @method Phaser.Sound#fadeIn + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in. + * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. + * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. + */ + fadeIn: function (duration, loop, marker) { + + if (loop === undefined) { loop = false; } + if (marker === undefined) { marker = this.currentMarker; } + + if (this.paused) + { + return; + } + + this.play(marker, 0, 0, loop); + + this.fadeTo(duration, 1); + + }, + + /** + * Decreases the volume of this Sound from its current value to 0 over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (0) as the second parameter. + * + * @method Phaser.Sound#fadeOut + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out. + */ + fadeOut: function (duration) { + + this.fadeTo(duration, 0); + + }, + + /** + * Fades the volume of this Sound from its current value to the given volume over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (volume) as the second parameter. + * + * @method Phaser.Sound#fadeTo + * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out. + * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1. + */ + fadeTo: function (duration, volume) { + + if (!this.isPlaying || this.paused || volume === this.volume) + { + return; + } + + if (duration === undefined) { duration = 1000; } + + if (volume === undefined) + { + console.warn("Phaser.Sound.fadeTo: No Volume Specified."); + return; + } + + this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true); + + this.fadeTween.onComplete.add(this.fadeComplete, this); + + }, + + /** + * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo. + * + * @method Phaser.Sound#fadeComplete + * @private + */ + fadeComplete: function () { + + this.onFadeComplete.dispatch(this, this.volume); + + if (this.volume === 0) + { + this.stop(); + } + + }, + + /** + * Called automatically by SoundManager.volume. + * + * Sets the volume of AudioTag Sounds as a percentage of the Global Volume. + * + * You should not normally call this directly. + * + * @method Phaser.Sound#updateGlobalVolume + * @protected + * @param {float} globalVolume - The global SoundManager volume. + */ + updateGlobalVolume: function (globalVolume) { + + // this._volume is the % of the global volume this sound should be played at + + if (this.usingAudioTag && this._sound) + { + this._globalVolume = globalVolume; + this._sound.volume = this._globalVolume * this._volume; + } + + }, + + /** + * Destroys this sound and all associated events and removes it from the SoundManager. + * + * @method Phaser.Sound#destroy + * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager. + */ + destroy: function (remove) { + + if (remove === undefined) { remove = true; } + + this._markedToDelete = true; + this._removeFromSoundManager = remove; + this.stop(); + + if (remove) + { + this.game.sound.remove(this); + } + else + { + 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; + +/** +* @name Phaser.Sound#isDecoding +* @property {boolean} isDecoding - Returns true if the sound file is still decoding. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoding", { + + get: function () { + return this.game.cache.getSound(this.key).isDecoding; + } + +}); + +/** +* @name Phaser.Sound#isDecoded +* @property {boolean} isDecoded - Returns true if the sound file has decoded. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoded", { + + get: function () { + return this.game.cache.isSoundDecoded(this.key); + } + +}); + +/** +* @name Phaser.Sound#mute +* @property {boolean} mute - Gets or sets the muted state of this sound. +*/ +Object.defineProperty(Phaser.Sound.prototype, "mute", { + + get: function () { + + return (this._muted || this.game.sound.mute); + + }, + + set: function (value) { + + value = value || false; + + if (value === this._muted) + { + return; + } + + if (value) + { + this._muted = true; + this._muteVolume = this._tempVolume; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = 0; + } + else if (this.usingAudioTag && this._sound) + { + 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); + + } + +}); + +/** +* @name Phaser.Sound#volume +* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Sound.prototype, "volume", { + + get: function () { + return this._volume; + }, + + set: function (value) { + + // Causes an Index size error if you don't clamp the value + if (this.usingAudioTag) + { + value = this.game.math.clamp(value, 0, 1); + } + + if (this._muted) + { + this._muteVolume = value; + return; + } + + this._tempVolume = value; + this._volume = value; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = value; + } + else if (this.usingAudioTag && this._sound) + { + this._sound.volume = this._globalVolume * value; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. +* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. +* The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. +* There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ +* +* If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out +* of AudioContext nodes. If this is the case create a global var called {@link PhaserGlobal} on the window object before creating the game. The active +* AudioContext will then be saved to `window.PhaserGlobal.audioContext` when the Phaser game is destroyed, and re-used when it starts again. +* +* Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. +* When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. +* The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will +* be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. +* +* @class Phaser.SoundManager +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.SoundManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) + */ + this.onSoundDecode = new Phaser.Signal(); + + /** + * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. + * @property {Phaser.Signal} onVolumeChange + */ + this.onVolumeChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. + * @property {Phaser.Signal} onMute + */ + this.onMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. + * @property {Phaser.Signal} onUnMute + */ + this.onUnMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is touch-unlocked. + * If the device doesn't {@link Phaser.Device.needsTouchUnlock need touch-unlocking}, the signal won't be dispatched. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * @property {AudioContext} context - The AudioContext being used for playback. + * @default + */ + this.context = null; + + /** + * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio. + * @readonly + */ + this.usingWebAudio = false; + + /** + * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio. + * @readonly + */ + this.usingAudioTag = false; + + /** + * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. + * @default + */ + this.noAudio = false; + + /** + * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. + * @default + */ + this.connectToMaster = true; + + /** + * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. + * @default + */ + this.touchLocked = false; + + /** + * @property {number} channels - The number of audio channels to use in playback. + * @default + */ + this.channels = 32; + + /** + * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), + * or set to false to keep audio playing, regardless of the game pause state. You may need to + * do this should you wish to control audio muting via external DOM buttons or similar. + * @property {boolean} muteOnPause + * @default + */ + this.muteOnPause = true; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {AudioContext} _unlockSource - Internal unlock tracking var. + * @private + * @default + */ + this._unlockSource = null; + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + * @default + */ + this._volume = 1; + + + /** + * @property {array} _sounds - An array containing all the sounds + * @private + */ + this._sounds = []; + + /** + * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status. + * @private + */ + this._watchList = new Phaser.ArraySet(); + + /** + * @property {boolean} _watching - Is the SoundManager monitoring the watchList? + * @private + */ + this._watching = false; + + /** + * @property {function} _watchCallback - The callback to invoke once the watchlist is clear. + * @private + */ + this._watchCallback = null; + + /** + * @property {object} _watchContext - The context in which to call the watchlist callback. + * @private + */ + this._watchContext = null; + +}; + +Phaser.SoundManager.prototype = { + + /** + * Initialises the sound manager. + * @method Phaser.SoundManager#boot + * @protected + */ + boot: function () { + + var device = this.game.device; + var PhaserGlobal = window.PhaserGlobal; + + if (device.iOS && device.webAudio === false) + { + this.channels = 1; + } + + // PhaserGlobal overrides + if (PhaserGlobal) + { + // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class) + if (PhaserGlobal.disableAudio === true) + { + this.noAudio = true; + this.touchLocked = false; + return; + } + + // Check if the Web Audio API is disabled (for testing Audio Tag playback during development) + if (PhaserGlobal.disableWebAudio === true) + { + this.usingAudioTag = true; + this.touchLocked = false; + return; + } + } + + if (PhaserGlobal && PhaserGlobal.audioContext) + { + this.context = PhaserGlobal.audioContext; + } + else + { + if (!!window['AudioContext']) + { + try { + this.context = new window['AudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + else if (!!window['webkitAudioContext']) + { + try { + this.context = new window['webkitAudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + } + + if (this.context === null) + { + // No Web Audio support - how about legacy Audio? + if (window['Audio'] === undefined) + { + this.noAudio = true; + return; + } + else + { + this.usingAudioTag = true; + } + } + else + { + this.usingWebAudio = true; + + if (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); + } + + if (!this.noAudio) + { + // On mobile we need a native touch event before we can play anything, so capture it here + if (device.needsTouchUnlock()) + { + this.setTouchLock(); + } + } + + if (this.usingWebAudio && device.chrome && device.chromeVersion <= 65) + { + console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. '); + } + + }, + + /** + * Sets the Input Manager touch callback to be SoundManager.unlock. + * Required for iOS audio device unlocking. Mostly just used internally. + * + * @method Phaser.SoundManager#setTouchLock + */ + setTouchLock: function () { + + if (this.noAudio || (window.PhaserGlobal && window.PhaserGlobal.disableAudio === true)) + { + return; + } + + this.game.input.addTouchLockCallback(this.unlock, this, true); + + this.touchLocked = true; + + }, + + /** + * Turns off {@link #touchLocked} and dispatches {@link #onTouchUnlock}. + * + * @method Phaser.SoundManager#setTouchUnlock + * @private + */ + setTouchUnlock: function () { + + this.touchLocked = false; + this._unlockSource = null; + this.onTouchUnlock.dispatch(); + + }, + + /** + * Enables the audio, usually after the first touch. + * + * @method Phaser.SoundManager#unlock + * @return {boolean} True if the callback should be removed, otherwise false. + */ + unlock: function () { + + if (this.noAudio || !this.touchLocked || this._unlockSource !== null) + { + return true; + } + + // Global override (mostly for Audio Tag testing) + if (this.usingAudioTag) + { + this.setTouchUnlock(); + } + else if (this.usingWebAudio) + { + // Create empty buffer and play it + // The SoundManager.update loop captures the state of it and then resets touchLocked to false + + var buffer = this.context.createBuffer(1, 1, 22050); + this._unlockSource = this.context.createBufferSource(); + this._unlockSource.buffer = buffer; + this._unlockSource.connect(this.context.destination); + + if (this._unlockSource.start === undefined) + { + this._unlockSource.noteOn(0); + } + else + { + this._unlockSource.start(0); + } + + //This fixes locked audio in Chrome > 55 cross origin iframes + if (this._unlockSource.context.state === 'suspended') { + this._unlockSource.context.resume(); + } + } + + // We can remove the event because we've done what we needed (started the unlock sound playing) + return true; + + }, + + /** + * Stops all the sounds in the game. + * + * @method Phaser.SoundManager#stopAll + */ + stopAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].stop(); + } + } + + }, + + /** + * Pauses all the sounds in the game. + * + * @method Phaser.SoundManager#pauseAll + */ + pauseAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].pause(); + } + } + + }, + + /** + * Resumes every sound in the game. + * + * @method Phaser.SoundManager#resumeAll + */ + resumeAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].resume(); + } + } + + }, + + /** + * Decode a sound by its asset key. + * + * @method Phaser.SoundManager#decode + * @param {string} key - Assets key of the sound to be decoded. + * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. + */ + decode: function (key, sound) { + + sound = sound || null; + + var soundData = this.game.cache.getSoundData(key); + + if (soundData) + { + if (this.game.cache.isSoundDecoded(key) === false) + { + this.game.cache.updateSound(key, 'isDecoding', true); + + var _this = this; + + try { + this.context.decodeAudioData(soundData, function (buffer) { + + if (buffer) + { + _this.game.cache.decodedSound(key, buffer); + _this.onSoundDecode.dispatch(key, sound); + } + }); + } + catch (e) {} + } + } + + }, + + /** + * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback. + * Once all of the Sound files have finished decoding the callback will be invoked. + * The amount of time spent decoding depends on the codec used and file size. + * If all of the files given have already decoded the callback is triggered immediately. + * + * @method Phaser.SoundManager#setDecodedCallback + * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache. + * @param {Function} callback - The callback which will be invoked once all files have finished decoding. + * @param {Object} callbackContext - The context in which the callback will run. + */ + setDecodedCallback: function (files, callback, callbackContext) { + + if (typeof files === 'string') + { + files = [ files ]; + } + + this._watchList.reset(); + + for (var i = 0; i < files.length; i++) + { + if (files[i] instanceof Phaser.Sound) + { + if (!this.game.cache.isSoundDecoded(files[i].key)) + { + this._watchList.add(files[i].key); + } + } + else if (!this.game.cache.isSoundDecoded(files[i])) + { + this._watchList.add(files[i]); + } + } + + // All decoded already? + if (this._watchList.total === 0) + { + this._watching = false; + callback.call(callbackContext); + } + else + { + this._watching = true; + this._watchCallback = callback; + this._watchContext = callbackContext; + } + + }, + + /** + * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. + * + * @method Phaser.SoundManager#update + * @protected + */ + update: function () { + + if (this.noAudio) + { + return; + } + + if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE)) + { + this.setTouchUnlock(); + } + + for (var i = 0; i < this._sounds.length; i++) + { + this._sounds[i].update(); + } + + if (this._watching) + { + var key = this._watchList.first; + + while (key) + { + if (this.game.cache.isSoundDecoded(key)) + { + this._watchList.remove(key); + } + + key = this._watchList.next; + } + + if (this._watchList.total === 0) + { + this._watching = false; + this._watchCallback.call(this._watchContext); + } + } + + }, + + /** + * Adds a new Sound into the SoundManager. + * + * @method Phaser.SoundManager#add + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The new sound instance. + */ + add: function (key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = this.connectToMaster; } + + var sound = new Phaser.Sound(this.game, key, volume, loop, connect); + + this._sounds.push(sound); + + return sound; + + }, + + /** + * Adds a new AudioSprite into the SoundManager. + * + * @method Phaser.SoundManager#addSprite + * @param {string} key - Asset key for the sound. + * @return {Phaser.AudioSprite} The new AudioSprite instance. + */ + addSprite: function(key) { + + var audioSprite = new Phaser.AudioSprite(this.game, key); + + return audioSprite; + + }, + + /** + * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. + * + * @method Phaser.SoundManager#remove + * @param {Phaser.Sound} sound - The sound object to remove. + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ + remove: function (sound) { + + var i = this._sounds.length; + + while (i--) + { + if (this._sounds[i] === sound) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Removes all Sounds from the SoundManager. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeAll + */ + removeAll: function () { + + this.stopAll(); + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].destroy(); + } + } + + this._sounds.length = 0; + + }, + + /** + * Removes all Sounds from the SoundManager that have an asset key matching the given value. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeByKey + * @param {string} key - The key to match when removing sound objects. + * @return {number} The number of matching sound objects that were removed. + */ + removeByKey: function (key) { + + var i = this._sounds.length; + var removed = 0; + + while (i--) + { + if (this._sounds[i].key === key) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + removed++; + } + } + + return removed; + + }, + + /** + * Adds a new Sound into the SoundManager and starts it playing. + * + * @method Phaser.SoundManager#play + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @return {Phaser.Sound} The new sound instance. + */ + play: function (key, volume, loop) { + + if (this.noAudio) + { + return; + } + + var sound = this.add(key, volume, loop); + + sound.play(); + + return sound; + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + if (this.usingWebAudio) + { + this._muteVolume = this.masterGain.gain.value; + this.masterGain.gain.value = 0; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = true; + } + } + + this.onMute.dispatch(); + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = this._muteVolume; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = false; + } + } + + this.onUnMute.dispatch(); + + }, + + /** + * Stops all the sounds in the game, then destroys them and finally clears up any callbacks. + * + * @method Phaser.SoundManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.onSoundDecode.dispose(); + + if (this.context) + { + if (window.PhaserGlobal) + { + // Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing + window.PhaserGlobal.audioContext = this.context; + } + else + { + if (this.context.close) + { + this.context.close(); + } + } + } + + } + +}; + +Phaser.SoundManager.prototype.constructor = Phaser.SoundManager; + +/** +* @name Phaser.SoundManager#mute +* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || false; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* @name Phaser.SoundManager#volume +* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "volume", { + + get: function () { + + return this._volume; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this._volume !== value) + { + this._volume = value; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = value; + } + else + { + // Loop through the sound cache and change the volume of all html audio tags + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].updateGlobalVolume(value); + } + } + } + + this.onVolumeChange.dispatch(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* The ScaleManager object handles the the scaling, resizing, and alignment of the +* Game size and the game Display canvas. +* +* The Game size is the logical size of the game; the Display canvas has size as an HTML element. +* +* The calculations of these are heavily influenced by the bounding Parent size which is the computed +* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the +* canvas's Parent element play an important role_ in the operation of the ScaleManager. +* +* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size. +* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}). +* +* #### Parent and Display canvas containment guidelines: +* +* - Style the Parent element (of the game canvas) to control the Parent size and +* thus the Display canvas's size and layout. +* +* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior. +* +* - The Parent element should _not_ apply a padding as this is not accounted for. +* If a padding is required apply it to the Parent's parent or apply a margin to the Parent. +* If you need to add a border, margin or any other CSS around your game container, then use a parent element and +* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container. +* +* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as +* they may be updated by the ScaleManager. +* +* #### Example Uses +* +* - ##### Fixed game size; scale canvas proportionally to fill its container +* +* Use `scaleMode` SHOW_ALL. +* +* - ##### Fixed game size; stretch canvas to fill its container (uncommon) +* +* Use `scaleMode` EXACT_FIT. +* +* - ##### Fixed game size; scale canvas proportionally by some other criteria +* +* Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary. +* +* - ##### Fluid game/canvas size +* +* Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary. +* +* - ##### Preferred orientation +* +* Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals. +* +* @description +* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game} +* +* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. +* +* @class +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number|string} width - The width of the game. See above. +* @param {number|string} height - The height of the game. See above. +*/ +Phaser.ScaleManager = function (game, width, height) { + + /** + * A reference to the currently running game. + * @property {Phaser.Game} game + * @protected + * @readonly + */ + this.game = game; + + /** + * Provides access to some cross-device DOM functions. + * @property {Phaser.DOM} dom + * @protected + * @readonly + */ + this.dom = Phaser.DOM; + + /** + * _EXPERIMENTAL:_ A responsive grid on which you can align game objects. + * @property {Phaser.FlexGrid} grid + * @public + */ + this.grid = null; + + /** + * Target width (in pixels) of the Display canvas. + * @property {number} width + * @readonly + */ + this.width = 0; + + /** + * Target height (in pixels) of the Display canvas. + * @property {number} height + * @readonly + */ + this.height = 0; + + /** + * Minimum width the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minWidth + * @readonly + * @protected + */ + this.minWidth = null; + + /** + * Maximum width the canvas should be scaled to (in pixels). + * If null it will scale to whatever width the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxWidth + * @readonly + * @protected + */ + this.maxWidth = null; + + /** + * Minimum height the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minHeight + * @readonly + * @protected + */ + this.minHeight = null; + + /** + * Maximum height the canvas should be scaled to (in pixels). + * If null it will scale to whatever height the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxHeight + * @readonly + * @protected + */ + this.maxHeight = null; + + /** + * The offset coordinates of the Display canvas from the top-left of the browser window. + * The is used internally by Phaser.Pointer (for Input) and possibly other types. + * @property {Phaser.Point} offset + * @readonly + * @protected + */ + this.offset = new Phaser.Point(); + + /** + * If true, the game should only run in a landscape orientation. + * Change with {@link #forceOrientation}. + * @property {boolean} forceLandscape + * @readonly + * @default + * @protected + */ + this.forceLandscape = false; + + /** + * If true, the game should only run in a portrait + * Change with {@link #forceOrientation}. + * @property {boolean} forcePortrait + * @readonly + * @default + * @protected + */ + this.forcePortrait = false; + + /** + * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation. + * + * This value is not updated immediately. + * + * @property {boolean} incorrectOrientation + * @readonly + * @protected + */ + this.incorrectOrientation = false; + + /** + * See {@link #pageAlignHorizontally}. + * @property {boolean} _pageAlignHorizontally + * @private + */ + this._pageAlignHorizontally = false; + + /** + * See {@link #pageAlignVertically}. + * @property {boolean} _pageAlignVertically + * @private + */ + this._pageAlignVertically = false; + + /** + * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes. + * + * The signal is supplied with the following arguments: + * - `scale` - the ScaleManager object + * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}. + * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. + * + * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. + * Thus the following tests can be done: + * + * // The orientation itself changed: + * scale.screenOrientation !== prevOrientation + * // The orientation just became incorrect: + * scale.incorrectOrientation && !wasIncorrect + * + * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation + * correctness changes even if the orientation itself does not change. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onOrientationChange + * @public + */ + this.onOrientationChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} enterIncorrectOrientation + * @public + */ + this.enterIncorrectOrientation = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} leaveIncorrectOrientation + * @public + */ + this.leaveIncorrectOrientation = new Phaser.Signal(); + + /** + * This boolean provides you with a way to determine if the browser is in Full Screen + * mode (via the Full Screen API), and Phaser was the one responsible for activating it. + * + * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the + * one that made the browser go full-screen, so this flag lets you determine that. + * + * @property {boolean} hasPhaserSetFullScreen + * @default + */ + this.hasPhaserSetFullScreen = false; + + /** + * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. + * The target element must have the correct CSS styling and contain the Display canvas. + * + * The elements style will be modified (ie. the width and height might be set to 100%) + * but it will not be added to, removed from, or repositioned within the DOM. + * An attempt is made to restore relevant style changes when fullscreen mode is left. + * + * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. + * + * @property {?DOMElement} fullScreenTarget + * @default + */ + this.fullScreenTarget = null; + + /** + * The fullscreen target, as created by {@link #createFullScreenTarget}. + * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends. + * @property {?DOMElement} _createdFullScreenTarget + * @private + */ + this._createdFullScreenTarget = null; + + /** + * This signal is dispatched when fullscreen mode is ready to be initialized but + * before the fullscreen request. + * + * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. + * + * The `targetElement` is the {@link #fullScreenTarget} element, + * if such is assigned, or a new element created by {@link #createFullScreenTarget}. + * + * Custom CSS styling or resets can be applied to `targetElement` as required. + * + * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}: + * - After initialization the Display canvas is moved onto the `targetElement` for + * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. + * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. + * + * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}. + * + * @property {Phaser.Signal} onFullScreenInit + * @public + */ + this.onFullScreenInit = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine + * if currently running in Fullscreen mode. + * + * @property {Phaser.Signal} onFullScreenChange + * @public + */ + this.onFullScreenChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser fails to enter fullscreen mode; + * or if the device does not support fullscreen mode and `startFullScreen` is invoked. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). + * + * @property {Phaser.Signal} onFullScreenError + * @public + */ + this.onFullScreenError = new Phaser.Signal(); + + /** + * The _last known_ orientation of the screen, as defined in the Window Screen Web API. + * See {@link Phaser.DOM.getScreenOrientation} for possible values. + * + * @property {string} screenOrientation + * @readonly + * @public + */ + this.screenOrientation = this.dom.getScreenOrientation(); + + /** + * The _current_ scale factor based on the game dimensions vs. the scaled dimensions. + * @property {Phaser.Point} scaleFactor + * @readonly + */ + this.scaleFactor = new Phaser.Point(1, 1); + + /** + * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions. + * @property {Phaser.Point} scaleFactorInversed + * @readonly + * @protected + */ + this.scaleFactorInversed = new Phaser.Point(1, 1); + + /** + * The Display canvas is aligned by adjusting the margins; the last margins are stored here. + * + * @property {Bounds-like} margin + * @readonly + * @protected + */ + this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0}; + + /** + * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. + * @property {Phaser.Rectangle} bounds + * @readonly + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The aspect ratio of the scaled Display canvas. + * @property {number} aspectRatio + * @readonly + */ + this.aspectRatio = 0; + + /** + * The aspect ratio of the original game dimensions. + * @property {number} sourceAspectRatio + * @readonly + */ + this.sourceAspectRatio = 0; + + /** + * The native browser events from Fullscreen API changes. + * @property {any} event + * @readonly + * @private + */ + this.event = null; + + /** + * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container. + * + * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. + * - If 'visual', the edge will be constrained to the Window / displayed screen area + * - If 'layout', the edge will be constrained to the CSS Layout bounds + * - An invalid value is treated as 'visual' + * + * @member + * @property {string} bottom + * @property {string} right + * @default + */ + this.windowConstraints = { + right: 'layout', + bottom: '' + }; + + /** + * Various compatibility settings. + * A value of "(auto)" indicates the setting is configured based on device and runtime information. + * + * A {@link #refresh} may need to be performed after making changes. + * + * @protected + * + * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.) + * + * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}. + * + * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. + * + * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh. + * + * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates. + * The height set varies by device and may either be the height of the window or the viewport. + * + * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. + * + * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. + * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. + * Any other string value (including the empty string) prevents using click trampolines. + * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}. + */ + this.compatibility = { + supportsFullScreen: false, + orientationFallback: null, + noMargins: false, + scrollTo: null, + forceMinimumDocumentHeight: false, + canExpandParent: true, + clickTrampoline: '' + }; + + /** + * Scale mode to be used when not in fullscreen. + * @property {number} _scaleMode + * @private + */ + this._scaleMode = Phaser.ScaleManager.NO_SCALE; + + /* + * Scale mode to be used in fullscreen. + * @property {number} _fullScreenScaleMode + * @private + */ + this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE; + + /** + * True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * The {@link #parentNode} property is generally ignored while this is in effect. + * + * @property {boolean} parentIsWindow + */ + this.parentIsWindow = false; + + /** + * The _original_ DOM element for the parent of the Display canvas. + * This may be different in fullscreen - see {@link #createFullScreenTarget}. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * This should only be changed after moving the Game canvas to a different DOM parent. + * + * @property {?DOMElement} parentNode + */ + this.parentNode = null; + + /** + * The scale of the game in relation to its parent container. + * @property {Phaser.Point} parentScaleFactor + * @readonly + */ + this.parentScaleFactor = new Phaser.Point(1, 1); + + /** + * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). + * Update checks normally happen quicker in response to other events. + * + * @property {integer} trackParentInterval + * @default + * @protected + * @see {@link Phaser.ScaleManager#refresh refresh} + */ + this.trackParentInterval = 2000; + + /** + * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. + * When invoked this is done _after_ the Canvas size/position have been updated. + * + * The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.) + * + * This signal is _only_ called when a change occurs and a reflow may be required. + * For example, if the canvas does not change sizes because of CSS settings (such as min-width) + * then this signal will _not_ be triggered. + * + * Use this to handle responsive game layout options. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onSizeChange + */ + this.onSizeChange = new Phaser.Signal(); + + /** + * The callback that will be called each the parent container resizes. + * @property {function} onResize + * @private + */ + this.onResize = null; + + /** + * The context in which the {@link #onResize} callback will be called. + * @property {object} onResizeContext + * @private + */ + this.onResizeContext = null; + + /** + * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot. + * @private + */ + this._pendingScaleMode = null; + + /** + * Information saved when fullscreen mode is started. + * @property {?object} _fullScreenRestore + * @private + */ + this._fullScreenRestore = null; + + /** + * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}. + * @property {Phaser.Rectangle} _gameSize + * @private + */ + this._gameSize = new Phaser.Rectangle(); + + /** + * The user-supplied scale factor, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleFactor + * @private + */ + this._userScaleFactor = new Phaser.Point(1, 1); + + /** + * The user-supplied scale trim, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleTrim + * @private + */ + this._userScaleTrim = new Phaser.Point(0, 0); + + /** + * The last time the bounds were checked in `preUpdate`. + * @property {number} _lastUpdate + * @private + */ + this._lastUpdate = 0; + + /** + * Size checks updates are delayed according to the throttle. + * The throttle increases to `trackParentInterval` over time and is used to more + * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety. + * @property {integer} _updateThrottle + * @private + */ + this._updateThrottle = 0; + + /** + * The minimum throttle allowed until it has slowed down sufficiently. + * @property {integer} _updateThrottleReset + * @private + */ + this._updateThrottleReset = 100; + + /** + * The cached result of the parent (possibly window) bounds; used to invalidate sizing. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._parentBounds = new Phaser.Rectangle(); + + /** + * Temporary bounds used for internal work to cut down on new objects created. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._tempBounds = new Phaser.Rectangle(); + + /** + * The Canvas size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedCanvasSize + * @private + */ + this._lastReportedCanvasSize = new Phaser.Rectangle(); + + /** + * The Game size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedGameSize + * @private + */ + this._lastReportedGameSize = new Phaser.Rectangle(); + + /** + * @property {boolean} _booted - ScaleManager booted state. + * @private + */ + this._booted = false; + + if (game.config) + { + this.parseConfig(game.config); + } + + this.setupScale(width, height); + +}; + +/** +* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.EXACT_FIT = 0; + +/** +* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.NO_SCALE = 1; + +/** +* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.SHOW_ALL = 2; + +/** +* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.RESIZE = 3; + +/** +* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.USER_SCALE = 4; + +/** +* Names of the scale modes, indexed by value. +* +* @constant +* @type {string[]} +*/ +Phaser.ScaleManager.MODES = [ + 'EXACT_FIT', + 'NO_SCALE', + 'SHOW_ALL', + 'RESIZE', + 'USER_SCALE' +]; + +Phaser.ScaleManager.prototype = { + + /** + * Start the ScaleManager. + * + * @method Phaser.ScaleManager#boot + * @protected + */ + boot: function () { + + // Configure device-dependent compatibility + + var compat = this.compatibility; + + compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS; + + // We can't do anything about the status bars in iPads, web apps or desktops + if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop) + { + if (this.game.device.android && !this.game.device.chrome) + { + compat.scrollTo = new Phaser.Point(0, 1); + } + else + { + compat.scrollTo = new Phaser.Point(0, 0); + } + } + + if (this.game.device.desktop) + { + compat.orientationFallback = 'screen'; + compat.clickTrampoline = 'when-not-mouse'; + } + else + { + compat.orientationFallback = ''; + compat.clickTrampoline = ''; + } + + // Configure event listeners + + var _this = this; + + this._orientationChange = function(event) { + return _this.orientationChange(event); + }; + + this._windowResize = function(event) { + return _this.windowResize(event); + }; + + // This does not appear to be on the standards track + window.addEventListener('orientationchange', this._orientationChange, false); + window.addEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + this._fullScreenChange = function(event) { + return _this.fullScreenChange(event); + }; + + this._fullScreenError = function(event) { + return _this.fullScreenError(event); + }; + + document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.addEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.addEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.addEventListener('fullscreenchange', this._fullScreenChange, false); + + document.addEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.addEventListener('mozfullscreenerror', this._fullScreenError, false); + document.addEventListener('MSFullscreenError', this._fullScreenError, false); + document.addEventListener('fullscreenerror', this._fullScreenError, false); + } + + this.game.onResume.add(this._gameResumed, this); + + // Initialize core bounds + + this.dom.getOffset(this.game.canvas, this.offset); + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + this.setGameSize(this.game.width, this.game.height); + + // Don't use updateOrientationState so events are not fired + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + if (Phaser.FlexGrid) + { + this.grid = new Phaser.FlexGrid(this, this.width, this.height); + } + + this._booted = true; + + if (this._pendingScaleMode !== null) + { + this.scaleMode = this._pendingScaleMode; + this._pendingScaleMode = null; + } + + }, + + /** + * Load configuration settings. + * + * @method Phaser.ScaleManager#parseConfig + * @protected + * @param {object} config - The game configuration object. + */ + parseConfig: function (config) { + + if (config['scaleMode'] !== undefined) + { + if (this._booted) + { + this.scaleMode = config['scaleMode']; + } + else + { + this._pendingScaleMode = config['scaleMode']; + } + } + + if (config['fullScreenScaleMode'] !== undefined) + { + this.fullScreenScaleMode = config['fullScreenScaleMode']; + } + + if (config['fullScreenTarget']) + { + this.fullScreenTarget = config['fullScreenTarget']; + } + + this.pageAlignHorizontally = config.alignH || false; + this.pageAlignVertically = config.alignV || false; + + if (config.scaleH && config.scaleV) + { + this.setUserScale(config.scaleH, config.scaleV, config.trimH, config.trimV); + } + + }, + + /** + * Calculates and sets the game dimensions based on the given width and height. + * + * This should _not_ be called when in fullscreen mode. + * + * @method Phaser.ScaleManager#setupScale + * @protected + * @param {number|string} width - The width of the game. + * @param {number|string} height - The height of the game. + */ + setupScale: function (width, height) { + + var target; + var rect = new Phaser.Rectangle(); + + if (this.game.parent !== '') + { + if (typeof this.game.parent === 'string') + { + // hopefully an element ID + target = document.getElementById(this.game.parent); + } + else if (this.game.parent && this.game.parent.nodeType === 1) + { + // quick test for a HTMLelement + target = this.game.parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + // Use the full window + this.parentNode = null; + this.parentIsWindow = true; + + rect.width = this.dom.visualBounds.width; + rect.height = this.dom.visualBounds.height; + + this.offset.set(0, 0); + } + else + { + this.parentNode = target; + this.parentIsWindow = false; + + this.getParentBounds(this._parentBounds); + + rect.width = this._parentBounds.width; + rect.height = this._parentBounds.height; + + this.offset.set(this._parentBounds.x, this._parentBounds.y); + } + + var newWidth = 0; + var newHeight = 0; + + if (typeof width === 'number') + { + newWidth = width; + } + else + { + // Percentage based + this.parentScaleFactor.x = parseInt(width, 10) / 100; + newWidth = rect.width * this.parentScaleFactor.x; + } + + if (typeof height === 'number') + { + newHeight = height; + } + else + { + // Percentage based + this.parentScaleFactor.y = parseInt(height, 10) / 100; + newHeight = rect.height * this.parentScaleFactor.y; + } + + newWidth = Math.floor(newWidth); + newHeight = Math.floor(newHeight); + + this._gameSize.setTo(0, 0, newWidth, newHeight); + + this.updateDimensions(newWidth, newHeight, false); + + }, + + /** + * Invoked when the game is resumed. + * + * @method Phaser.ScaleManager#_gameResumed + * @private + */ + _gameResumed: function () { + + this.queueUpdate(true); + + }, + + /** + * Set the actual Game size. + * Use this instead of directly changing `game.width` or `game.height`. + * + * The actual physical display (Canvas element size) depends on various settings including + * - Scale mode + * - Scaling factor + * - Size of Canvas's parent element or CSS rules such as min-height/max-height; + * - The size of the Window + * + * @method Phaser.ScaleManager#setGameSize + * @public + * @param {integer} width - _Game width_, in pixels. + * @param {integer} height - _Game height_, in pixels. + */ + setGameSize: function (width, height) { + + this._gameSize.setTo(0, 0, width, height); + + if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE) + { + this.updateDimensions(width, height, true); + } + + this.queueUpdate(true); + + }, + + /** + * Set a User scaling factor used in the USER_SCALE scaling mode. + * + * The target canvas size is computed by: + * + * canvas.width = (game.width * hScale) - hTrim + * canvas.height = (game.height * vScale) - vTrim + * + * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly. + * + * @method Phaser.ScaleManager#setUserScale + * @param {number} hScale - Horizontal scaling factor. + * @param {numer} vScale - Vertical scaling factor. + * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling. + * @param {integer} [vTrim=0] - Vertical trim, applied after scaling. + * @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate + * @param {boolean} [force=true] - Force a resize during the next preUpdate + */ + setUserScale: function (hScale, vScale, hTrim, vTrim, queueUpdate, force) { + + this._userScaleFactor.setTo(hScale, vScale); + this._userScaleTrim.setTo(hTrim | 0, vTrim | 0); + + if (queueUpdate === undefined) { queueUpdate = true; } + if (force === undefined) { force = true; } + + if (queueUpdate) + { + this.queueUpdate(force); + } + + }, + + /** + * Sets the callback that will be invoked before sizing calculations. + * + * Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries: + * the browser window has been resized, the device has been rotated, or the parent container's size has changed. + * At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all + * after it makes its sizing calculations). You can read the size of the parent container from the + * `parentBounds` argument to the callback. + * + * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling. + * + * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager + * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. + * + * This callback + * - May be invoked even though the parent container or canvas sizes have not changed + * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated + * - Will be invoked from `preUpdate`, _even when_ the game is paused + * + * See {@link #onSizeChange} for a better way of reacting to layout updates. + * + * @method Phaser.ScaleManager#setResizeCallback + * @public + * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes. + * @param {object} context - The context in which the callback will be called. + */ + setResizeCallback: function (callback, context) { + + this.onResize = callback; + this.onResizeContext = context; + + }, + + /** + * Signals a resize - IF the canvas or Game size differs from the last signal. + * + * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager). + * + * It dispatches the {@link #onSizeChange} signal. + * + * @method Phaser.ScaleManager#signalSizeChange + * @private + */ + signalSizeChange: function () { + + if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) || + !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize)) + { + var width = this.width; + var height = this.height; + + this._lastReportedCanvasSize.setTo(0, 0, width, height); + this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height); + + if (this.grid) + { + this.grid.onResize(width, height); + } + + this.onSizeChange.dispatch(this, width, height); + + // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode. + if (this.currentScaleMode === Phaser.ScaleManager.RESIZE) + { + this.game.state.resize(width, height); + this.game.load.resize(width, height); + } + } + + }, + + /** + * Set the min and max dimensions for the Display canvas. + * + * _Note:_ The min/max dimensions are only applied in some cases + * - When the device is not in an incorrect orientation; or + * - The scale mode is EXACT_FIT when not in fullscreen + * + * @method Phaser.ScaleManager#setMinMax + * @public + * @param {number} minWidth - The minimum width the game is allowed to scale down to. + * @param {number} minHeight - The minimum height the game is allowed to scale down to. + * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified. + * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified. + * @todo These values are only sometimes honored. + */ + setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) { + + this.minWidth = minWidth; + this.minHeight = minHeight; + + if (typeof maxWidth !== 'undefined') + { + this.maxWidth = maxWidth; + } + + if (typeof maxHeight !== 'undefined') + { + this.maxHeight = maxHeight; + } + + }, + + /** + * The ScaleManager.preUpdate is called automatically by the core Game loop. + * + * @method Phaser.ScaleManager#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.game.time.time < (this._lastUpdate + this._updateThrottle)) + { + return; + } + + var prevThrottle = this._updateThrottle; + this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100; + + this.dom.getOffset(this.game.canvas, this.offset); + + var prevWidth = this._parentBounds.width; + var prevHeight = this._parentBounds.height; + var bounds = this.getParentBounds(this._parentBounds); + + var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight; + + // Always invalidate on a newly detected orientation change + var orientationChanged = this.updateOrientationState(); + + if (boundsChanged || orientationChanged) + { + if (this.onResize) + { + this.onResize.call(this.onResizeContext, this, bounds); + } + + this.updateLayout(); + + this.signalSizeChange(); + } + + // Next throttle, eg. 25, 50, 100, 200.. + var throttle = this._updateThrottle * 2; + + // Don't let an update be too eager about resetting the throttle. + if (this._updateThrottle < prevThrottle) + { + throttle = Math.min(prevThrottle, this._updateThrottleReset); + } + + this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval); + this._lastUpdate = this.game.time.time; + + }, + + /** + * Update method while paused. + * + * @method Phaser.ScaleManager#pauseUpdate + * @private + */ + pauseUpdate: function () { + + this.preUpdate(); + + // Updates at slowest. + this._updateThrottle = this.trackParentInterval; + + }, + + /** + * Update the dimensions taking the parent scaling factor into account. + * + * @method Phaser.ScaleManager#updateDimensions + * @private + * @param {number} width - The new width of the parent container. + * @param {number} height - The new height of the parent container. + * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars. + */ + updateDimensions: function (width, height, resize) { + + this.width = width * this.parentScaleFactor.x; + this.height = height * this.parentScaleFactor.y; + + this.game.width = this.width; + this.game.height = this.height; + + this.sourceAspectRatio = this.width / this.height; + this.updateScalingAndBounds(); + + if (resize) + { + // Resize the renderer (which in turn resizes the Display canvas!) + this.game.renderer.resize(this.width, this.height); + + // The Camera can never be smaller than the Game size + this.game.camera.setSize(this.width, this.height); + + // This should only happen if the world is smaller than the new canvas size + this.game.world.resize(this.width, this.height); + } + + }, + + /** + * Update relevant scaling values based on the ScaleManager dimension and game dimensions, + * which should already be set. This does not change {@link #sourceAspectRatio}. + * + * @method Phaser.ScaleManager#updateScalingAndBounds + * @private + */ + updateScalingAndBounds: function () { + + this.scaleFactor.x = this.game.width / this.width; + this.scaleFactor.y = this.game.height / this.height; + + this.scaleFactorInversed.x = this.width / this.game.width; + this.scaleFactorInversed.y = this.height / this.game.height; + + this.aspectRatio = this.width / this.height; + + // This can be invoked in boot pre-canvas + if (this.game.canvas) + { + this.dom.getOffset(this.game.canvas, this.offset); + } + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + // Can be invoked in boot pre-input + if (this.game.input && this.game.input.scale) + { + this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y); + } + + }, + + /** + * Force the game to run in only one orientation. + * + * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. + * + * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor + * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the + * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` + * + * @method Phaser.ScaleManager#forceOrientation + * @public + * @param {boolean} forceLandscape - true if the game should run in landscape mode only. + * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. + */ + forceOrientation: function (forceLandscape, forcePortrait) { + + if (forcePortrait === undefined) { forcePortrait = false; } + + if (forceLandscape === true && forcePortrait === true) + { + console.warn('Phaser.ScaleManager: forceLandscape and forcePortrait cannot both be true.'); + return; + } + + this.forceLandscape = forceLandscape; + this.forcePortrait = forcePortrait; + + this.queueUpdate(true); + + }, + + /** + * Classify the orientation, per `getScreenOrientation`. + * + * @method Phaser.ScaleManager#classifyOrientation + * @private + * @param {string} orientation - The orientation string, e.g. 'portrait-primary'. + * @return {?string} The classified orientation: 'portrait', 'landscape`, or null. + */ + classifyOrientation: function (orientation) { + + if (orientation === 'portrait-primary' || orientation === 'portrait-secondary') + { + return 'portrait'; + } + else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary') + { + return 'landscape'; + } + else + { + return null; + } + + }, + + /** + * Updates the current orientation and dispatches orientation change events. + * + * @method Phaser.ScaleManager#updateOrientationState + * @private + * @return {boolean} True if the orientation state changed which means a forced update is likely required. + */ + updateOrientationState: function () { + + var previousOrientation = this.screenOrientation; + var previouslyIncorrect = this.incorrectOrientation; + + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) || + (this.forcePortrait && !this.isPortrait); + + var changed = previousOrientation !== this.screenOrientation; + var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation; + + if (correctnessChanged) + { + if (this.incorrectOrientation) + { + this.enterIncorrectOrientation.dispatch(); + } + else + { + this.leaveIncorrectOrientation.dispatch(); + } + } + + if (changed || correctnessChanged) + { + this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect); + } + + return changed || correctnessChanged; + + }, + + /** + * window.orientationchange event handler. + * + * @method Phaser.ScaleManager#orientationChange + * @private + * @param {Event} event - The orientationchange event data. + */ + orientationChange: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * window.resize event handler. + * + * @method Phaser.ScaleManager#windowResize + * @private + * @param {Event} event - The resize event data. + */ + windowResize: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * Scroll to the top - in some environments. See `compatibility.scrollTo`. + * + * @method Phaser.ScaleManager#scrollTop + * @private + */ + scrollTop: function () { + + var scrollTo = this.compatibility.scrollTo; + + if (scrollTo) + { + window.scrollTo(scrollTo.x, scrollTo.y); + } + + }, + + /** + * The "refresh" methods informs the ScaleManager that a layout refresh is required. + * + * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) + * when the browser is resized, the orientation changes, or when there is a detected change + * of the Parent size. Refreshing is also done automatically when public properties, + * such as {@link #scaleMode}, are updated or state-changing methods are invoked. + * + * The "refresh" method _may_ need to be used in a few (rare) situtations when + * + * - a device change event is not correctly detected; or + * - the Parent size changes (and an immediate reflow is desired); or + * - the ScaleManager state is updated by non-standard means; or + * - certain {@link #compatibility} properties are manually changed. + * + * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. + * + * @method Phaser.ScaleManager#refresh + * @public + */ + refresh: function () { + + this.scrollTop(); + this.queueUpdate(true); + + }, + + /** + * Updates the game / canvas position and size. + * + * @method Phaser.ScaleManager#updateLayout + * @private + */ + updateLayout: function () { + + var scaleMode = this.currentScaleMode; + + if (scaleMode === Phaser.ScaleManager.RESIZE) + { + this.reflowGame(); + return; + } + + this.scrollTop(); + + if (this.compatibility.forceMinimumDocumentHeight) + { + // (This came from older code, by why is it here?) + // Set minimum height of content to new window height + document.documentElement.style.minHeight = window.innerHeight + 'px'; + } + + if (this.incorrectOrientation) + { + this.setMaximum(); + } + else + { + if (scaleMode === Phaser.ScaleManager.EXACT_FIT) + { + this.setExactFit(); + } + else if (scaleMode === Phaser.ScaleManager.SHOW_ALL) + { + if (!this.isFullScreen && this.boundingParent && + this.compatibility.canExpandParent) + { + // Try to expand parent out, but choosing maximizing dimensions. + // Then select minimize dimensions which should then honor parent + // maximum bound applications. + this.setShowAll(true); + this.resetCanvas(); + this.setShowAll(); + } + else + { + this.setShowAll(); + } + } + else if (scaleMode === Phaser.ScaleManager.NO_SCALE) + { + this.width = this.game.width; + this.height = this.game.height; + } + else if (scaleMode === Phaser.ScaleManager.USER_SCALE) + { + this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x; + this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y; + } + } + + if (!this.compatibility.canExpandParent && + (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE)) + { + var bounds = this.getParentBounds(this._tempBounds); + this.width = Math.min(this.width, bounds.width); + this.height = Math.min(this.height, bounds.height); + } + + // Always truncate / force to integer + this.width = this.width | 0; + this.height = this.height | 0; + + this.reflowCanvas(); + + }, + + /** + * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. + * + * If in fullscreen mode or without parent (see {@link #parentIsWindow}), + * this will be the bounds of the visual viewport itself. + * + * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside + * the viewport then this function may return a smaller than expected size. + * + * Values are rounded to the nearest pixel. + * + * @method Phaser.ScaleManager#getParentBounds + * @protected + * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed. + * @return {Phaser.Rectangle} The established parent bounds. + */ + getParentBounds: function (target) { + + var bounds = target || new Phaser.Rectangle(); + var parentNode = this.boundingParent; + var visualBounds = this.dom.visualBounds; + var layoutBounds = this.dom.layoutBounds; + + if (!parentNode) + { + bounds.setTo(0, 0, visualBounds.width, visualBounds.height); + } + else + { + // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect + var clientRect = parentNode.getBoundingClientRect(); + var parentRect = (parentNode.offsetParent) ? parentNode.offsetParent.getBoundingClientRect() : parentNode.getBoundingClientRect(); + + bounds.setTo(clientRect.left - parentRect.left, clientRect.top - parentRect.top, clientRect.width, clientRect.height); + + var wc = this.windowConstraints; + + if (wc.right) + { + var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds; + bounds.right = Math.min(bounds.right, windowBounds.width); + } + + if (wc.bottom) + { + var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds; + bounds.bottom = Math.min(bounds.bottom, windowBounds.height); + } + } + + bounds.setTo( + Math.round(bounds.x), Math.round(bounds.y), + Math.round(bounds.width), Math.round(bounds.height)); + + return bounds; + + }, + + + /** + * Shorthand for setting {@link #pageAlignHorizontally} and {@link #pageAlignVertically}. + * + * @method Phaser.ScaleManager#align + * @param {boolean} [horizontal] - Value for {@link #pageAlignHorizontally}. Pass `null` to leave unchanged. + * @param {boolean} [vertical] - Value for {@link #pageAlignVertically}. Omit or pass `null` to leave unchanged. + */ + align: function (horizontal, vertical) { + + if (horizontal != null) + { + this.pageAlignHorizontally = horizontal; + } + + if (vertical != null) + { + this.pageAlignVertically = vertical; + } + + }, + + /** + * Update the canvas position/margins - for alignment within the parent container. + * + * The canvas margins _must_ be reset/cleared prior to invoking this. + * + * @method Phaser.ScaleManager#alignCanvas + * @private + * @param {boolean} horizontal - Align horizontally? + * @param {boolean} vertical - Align vertically? + */ + alignCanvas: function (horizontal, vertical) { + + var parentBounds = this.getParentBounds(this._tempBounds); + var canvas = this.game.canvas; + var margin = this.margin; + + if (horizontal) + { + margin.left = margin.right = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.width < parentBounds.width && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.left - parentBounds.x; + var targetEdge = (parentBounds.width / 2) - (this.width / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + + margin.left = Math.round(offset); + } + + canvas.style.marginLeft = margin.left + 'px'; + + if (margin.left !== 0) + { + margin.right = -(parentBounds.width - canvasBounds.width - margin.left); + canvas.style.marginRight = margin.right + 'px'; + } + } + + if (vertical) + { + margin.top = margin.bottom = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.height < parentBounds.height && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.top - parentBounds.y; + var targetEdge = (parentBounds.height / 2) - (this.height / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + margin.top = Math.round(offset); + } + + canvas.style.marginTop = margin.top + 'px'; + + if (margin.top !== 0) + { + margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top); + canvas.style.marginBottom = margin.bottom + 'px'; + } + } + + // Silly backwards compatibility.. + margin.x = margin.left; + margin.y = margin.top; + + }, + + /** + * Updates the Game state / size. + * + * The canvas margins may always be adjusted, even if alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowGame + * @private + */ + reflowGame: function () { + + this.resetCanvas('', ''); + + var bounds = this.getParentBounds(this._tempBounds); + this.updateDimensions(bounds.width, bounds.height, true); + + }, + + /** + * Updates the Display canvas size. + * + * The canvas margins may always be adjusted, even alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowCanvas + * @private + */ + reflowCanvas: function () { + + if (!this.incorrectOrientation) + { + this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width); + this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height); + } + + this.resetCanvas(); + + if (!this.compatibility.noMargins) + { + if (this.isFullScreen && this._createdFullScreenTarget) + { + this.alignCanvas(true, true); + } + else + { + this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically); + } + } + + this.updateScalingAndBounds(); + + }, + + /** + * "Reset" the Display canvas and set the specified width/height. + * + * @method Phaser.ScaleManager#resetCanvas + * @private + * @param {string} [cssWidth=(current width)] - The css width to set. + * @param {string} [cssHeight=(current height)] - The css height to set. + */ + resetCanvas: function (cssWidth, cssHeight) { + + if (cssWidth === undefined) { cssWidth = this.width + 'px'; } + if (cssHeight === undefined) { cssHeight = this.height + 'px'; } + + var canvas = this.game.canvas; + + if (!this.compatibility.noMargins) + { + canvas.style.marginLeft = ''; + canvas.style.marginTop = ''; + canvas.style.marginRight = ''; + canvas.style.marginBottom = ''; + } + + canvas.style.width = cssWidth; + canvas.style.height = cssHeight; + + }, + + /** + * Queues/marks a size/bounds check as needing to occur (from `preUpdate`). + * + * @method Phaser.ScaleManager#queueUpdate + * @private + * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty. + */ + queueUpdate: function (force) { + + if (force) + { + this._parentBounds.width = 0; + this._parentBounds.height = 0; + } + + this._updateThrottle = this._updateThrottleReset; + + }, + + /** + * Reset internal data/state. + * + * @method Phaser.ScaleManager#reset + * @private + */ + reset: function (clearWorld) { + + if (clearWorld && this.grid) + { + this.grid.reset(); + } + + }, + + /** + * Updates the width/height to that of the window. + * + * @method Phaser.ScaleManager#setMaximum + * @private + */ + setMaximum: function () { + + this.width = this.dom.visualBounds.width; + this.height = this.dom.visualBounds.height; + + }, + + /** + * Updates the width/height such that the game is scaled proportionally. + * + * @method Phaser.ScaleManager#setShowAll + * @private + * @param {boolean} expanding - If true then the maximizing dimension is chosen. + */ + setShowAll: function (expanding) { + + var bounds = this.getParentBounds(this._tempBounds); + var width = bounds.width; + var height = bounds.height; + + var multiplier; + + if (expanding) + { + multiplier = Math.max((height / this.game.height), (width / this.game.width)); + } + else + { + multiplier = Math.min((height / this.game.height), (width / this.game.width)); + } + + this.width = Math.round(this.game.width * multiplier); + this.height = Math.round(this.game.height * multiplier); + + }, + + /** + * Updates the width/height such that the game is stretched to the available size. + * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen. + * + * @method Phaser.ScaleManager#setExactFit + * @private + */ + setExactFit: function () { + + var bounds = this.getParentBounds(this._tempBounds); + + this.width = bounds.width; + this.height = bounds.height; + + if (this.isFullScreen) + { + // Max/min not honored fullscreen + return; + } + + if (this.maxWidth) + { + this.width = Math.min(this.width, this.maxWidth); + } + + if (this.maxHeight) + { + this.height = Math.min(this.height, this.maxHeight); + } + + }, + + /** + * Creates a fullscreen target. This is called automatically as as needed when entering + * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}. + * + * Use {@link #onFullScreenInit} to customize the created object. + * + * @method Phaser.ScaleManager#createFullScreenTarget + * @protected + */ + createFullScreenTarget: function () { + + var fsTarget = document.createElement('div'); + + fsTarget.style.margin = '0'; + fsTarget.style.padding = '0'; + fsTarget.style.background = '#000'; + + return fsTarget; + + }, + + /** + * Display the game in the browser's fullscreen mode. + * + * This _must_ be called from a user-input Pointer or Mouse event (and possibly a {@link https://www.chromestatus.com/feature/6131337345892352 "user gesture"}), e.g., + * + * - {@link Phaser.Events#onInputUp} + * - {@link Phaser.Input#onUp} or {@link Phaser.Input#onTap} + * - `click`, `mousedown`, `mouseup`, `pointerup`, or `touchend` + * + * Games within an iframe will also be blocked from fullscreen unless the iframe has the `allowfullscreen` attribute. + * + * The {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} must be {@link http://caniuse.com/#search=fullscreen supported by the browser} for this to work - it is not the same as setting + * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current + * device is reported to support fullscreen mode. + * + * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. + * + * Safari blocks access to keyboard events in fullscreen mode (as a security measure). + * + * @method Phaser.ScaleManager#startFullScreen + * @public + * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. + * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed. + * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) + */ + startFullScreen: function (antialias, allowTrampoline) { + + if (this.isFullScreen) + { + return false; + } + + if (!this.compatibility.supportsFullScreen) + { + // Error is called in timeout to emulate the real fullscreenerror event better + var _this = this; + + setTimeout(function () { + _this.fullScreenError(); + }, 10); + + return; + } + + if (this.compatibility.clickTrampoline === 'when-not-mouse') + { + var input = this.game.input; + + if (input.activePointer && + input.activePointer !== input.mousePointer && + (allowTrampoline || allowTrampoline !== false)) + { + input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]); + return; + } + } + + if (antialias !== undefined && this.game.renderType === Phaser.CANVAS) + { + this.game.stage.smoothed = antialias; + } + + var fsTarget = this.fullScreenTarget; + + if (!fsTarget) + { + this.cleanupCreatedTarget(); + + this._createdFullScreenTarget = this.createFullScreenTarget(); + fsTarget = this._createdFullScreenTarget; + } + + var initData = { + targetElement: fsTarget + }; + + this.hasPhaserSetFullScreen = true; + + this.onFullScreenInit.dispatch(this, initData); + + if (this._createdFullScreenTarget) + { + // Move the Display canvas inside of the target and add the target to the DOM + // (The target has to be added for the Fullscreen API to work.) + var canvas = this.game.canvas; + var parent = canvas.parentNode; + parent.insertBefore(fsTarget, canvas); + fsTarget.appendChild(canvas); + } + + if (this.game.device.fullscreenKeyboard) + { + fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT); + } + else + { + fsTarget[this.game.device.requestFullscreen](); + } + + return true; + + }, + + /** + * Stops / exits fullscreen mode, if active. + * + * @method Phaser.ScaleManager#stopFullScreen + * @public + * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. + */ + stopFullScreen: function () { + + if (!this.isFullScreen || !this.compatibility.supportsFullScreen) + { + return false; + } + + this.hasPhaserSetFullScreen = false; + + document[this.game.device.cancelFullscreen](); + + return true; + + }, + + /** + * Cleans up the previous fullscreen target, if such was automatically created. + * This ensures the canvas is restored to its former parent, assuming the target didn't move. + * + * @method Phaser.ScaleManager#cleanupCreatedTarget + * @private + */ + cleanupCreatedTarget: function () { + + var fsTarget = this._createdFullScreenTarget; + + if (fsTarget && fsTarget.parentNode) + { + // Make sure to cleanup synthetic target for sure; + // swap the canvas back to the parent. + var parent = fsTarget.parentNode; + parent.insertBefore(this.game.canvas, fsTarget); + parent.removeChild(fsTarget); + } + + this._createdFullScreenTarget = null; + + }, + + /** + * Used to prepare/restore extra fullscreen mode settings. + * (This does move any elements within the DOM tree.) + * + * @method Phaser.ScaleManager#prepScreenMode + * @private + * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_. + */ + prepScreenMode: function (enteringFullscreen) { + + var createdTarget = !!this._createdFullScreenTarget; + var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget; + + if (enteringFullscreen) + { + if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT) + { + // Resize target, as long as it's not the canvas + if (fsTarget !== this.game.canvas) + { + this._fullScreenRestore = { + targetWidth: fsTarget.style.width, + targetHeight: fsTarget.style.height + }; + + fsTarget.style.width = '100%'; + fsTarget.style.height = '100%'; + } + } + } + else + { + // Have restore information + if (this._fullScreenRestore) + { + fsTarget.style.width = this._fullScreenRestore.targetWidth; + fsTarget.style.height = this._fullScreenRestore.targetHeight; + + this._fullScreenRestore = null; + } + + // Always reset to game size + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.resetCanvas(); + } + + }, + + /** + * Called automatically when the browser enters of leaves fullscreen mode. + * + * @method Phaser.ScaleManager#fullScreenChange + * @private + * @param {Event} [event=undefined] - The fullscreenchange event + */ + fullScreenChange: function (event) { + + this.event = event; + + if (this.isFullScreen) + { + this.prepScreenMode(true); + + this.updateLayout(); + this.queueUpdate(true); + } + else + { + this.prepScreenMode(false); + + this.cleanupCreatedTarget(); + + this.updateLayout(); + this.queueUpdate(true); + } + + this.onFullScreenChange.dispatch(this, this.width, this.height); + + }, + + /** + * Called automatically when the browser fullscreen request fails; + * or called when a fullscreen request is made on a device for which it is not supported. + * + * @method Phaser.ScaleManager#fullScreenError + * @private + * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API. + */ + fullScreenError: function (event) { + + this.event = event; + + this.cleanupCreatedTarget(); + + console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API'); + + this.onFullScreenError.dispatch(this); + + }, + + /** + * Takes a Sprite or Image object and scales it to fit the given dimensions. + * Scaling happens proportionally without distortion to the sprites texture. + * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the + * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either + * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. + * + * @method Phaser.ScaleManager#scaleSprite + * @protected + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale. + * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. + * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. + * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. + * @return {Phaser.Sprite|Phaser.Image} The scaled sprite. + */ + scaleSprite: function (sprite, width, height, letterBox) { + + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + if (letterBox === undefined) { letterBox = false; } + + if (!sprite || !sprite['scale']) + { + return sprite; + } + + sprite.scale.x = 1; + sprite.scale.y = 1; + + if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0)) + { + return sprite; + } + + var scaleX1 = width; + var scaleY1 = (sprite.height * width) / sprite.width; + + var scaleX2 = (sprite.width * height) / sprite.height; + var scaleY2 = height; + + var scaleOnWidth = (scaleX2 > width); + + if (scaleOnWidth) + { + scaleOnWidth = letterBox; + } + else + { + scaleOnWidth = !letterBox; + } + + if (scaleOnWidth) + { + sprite.width = Math.floor(scaleX1); + sprite.height = Math.floor(scaleY1); + } + else + { + sprite.width = Math.floor(scaleX2); + sprite.height = Math.floor(scaleY2); + } + + // Enable at some point? + // sprite.x = Math.floor((width - sprite.width) / 2); + // sprite.y = Math.floor((height - sprite.height) / 2); + + return sprite; + + }, + + /** + * Destroys the ScaleManager and removes any event listeners. + * This should probably only be called when the game is destroyed. + * + * @method Phaser.ScaleManager#destroy + * @protected + */ + destroy: function () { + + this.game.onResume.remove(this._gameResumed, this); + + window.removeEventListener('orientationchange', this._orientationChange, false); + window.removeEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.removeEventListener('fullscreenchange', this._fullScreenChange, false); + + document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.removeEventListener('mozfullscreenerror', this._fullScreenError, false); + document.removeEventListener('MSFullscreenError', this._fullScreenError, false); + document.removeEventListener('fullscreenerror', this._fullScreenError, false); + } + + } + +}; + +Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager; + +/** +* The DOM element that is considered the Parent bounding element, if any. +* +* This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified. +* It will also be null if there is no game canvas or if the game canvas has no parent. +* +* @name Phaser.ScaleManager#boundingParent +* @property {?DOMElement} boundingParent +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", { + + get: function () { + + if (this.parentIsWindow || + (this.isFullScreen && this.hasPhaserSetFullScreen && !this._createdFullScreenTarget)) + { + return null; + } + + var parentNode = this.game.canvas && this.game.canvas.parentNode; + + return parentNode || null; + + } + +}); + +/** +* The scaling method used by the ScaleManager when not in fullscreen. +* +*
+*
{@link Phaser.ScaleManager.NO_SCALE}
+*
+* The Game display area will not be scaled - even if it is too large for the canvas/screen. +* This mode _ignores_ any applied scaling factor and displays the canvas at the Game size. +*
+*
{@link Phaser.ScaleManager.EXACT_FIT}
+*
+* The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen. +* Proportions are not maintained. +*
+*
{@link Phaser.ScaleManager.SHOW_ALL}
+*
+* Show the entire game display area while _maintaining_ the original aspect ratio. +*
+*
{@link Phaser.ScaleManager.RESIZE}
+*
+* The dimensions of the game display area are changed to match the size of the parent container. +* That is, this mode _changes the Game size_ to match the display size. +*

+* Any manually set Game size (see {@link #setGameSize}) is ignored while in effect. +*

+*
{@link Phaser.ScaleManager.USER_SCALE}
+*
+* The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}. +*

+* This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback} +* for flexible custom-sizing needs. +*

+*
+* +* @name Phaser.ScaleManager#scaleMode +* @property {integer} scaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", { + + get: function () { + + return this._scaleMode; + + }, + + set: function (value) { + + if (value !== this._scaleMode) + { + if (!this.isFullScreen) + { + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.queueUpdate(true); + } + + this._scaleMode = value; + } + + return this._scaleMode; + + } + +}); + +/** +* The scaling method used by the ScaleManager when in fullscreen. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#fullScreenScaleMode +* @property {integer} fullScreenScaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", { + + get: function () { + + return this._fullScreenScaleMode; + + }, + + set: function (value) { + + if (value !== this._fullScreenScaleMode) + { + // If in fullscreen then need a wee bit more work + if (this.isFullScreen) + { + this.prepScreenMode(false); + this._fullScreenScaleMode = value; + this.prepScreenMode(true); + + this.queueUpdate(true); + } + else + { + this._fullScreenScaleMode = value; + } + } + + return this._fullScreenScaleMode; + + } + +}); + +/** +* Returns the current scale mode - for normal or fullscreen operation. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#currentScaleMode +* @property {number} currentScaleMode +* @protected +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", { + + get: function () { + + return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode; + + } + +}); + +/** +* When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align horizontally across the page the Display canvas should be added directly to page; +* or the parent container should itself be horizontally aligned. +* +* Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignHorizontally +* @property {boolean} pageAlignHorizontally +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", { + + get: function () { + + return this._pageAlignHorizontally; + + }, + + set: function (value) { + + if (value !== this._pageAlignHorizontally) + { + this._pageAlignHorizontally = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain +* a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically +* _within_ the remaining available height dictated by the Parent element. +* +* One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. +* If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). +* +* _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height. +* To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true. +* +* Vertical alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignVertically +* @property {boolean} pageAlignVertically +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", { + + get: function () { + + return this._pageAlignVertically; + + }, + + set: function (value) { + + if (value !== this._pageAlignVertically) + { + this._pageAlignVertically = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* Returns true if the browser is in fullscreen mode, otherwise false. +* @name Phaser.ScaleManager#isFullScreen +* @property {boolean} isFullScreen +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", { + + get: function () { + return !!(document['fullscreenElement'] || + document['webkitFullscreenElement'] || + document['mozFullScreenElement'] || + document['msFullscreenElement']); + } + +}); + +/** +* Returns true if the screen orientation is in portrait mode. +* +* @name Phaser.ScaleManager#isPortrait +* @property {boolean} isPortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'portrait'; + } + +}); + +/** +* Returns true if the screen orientation is in landscape mode. +* +* @name Phaser.ScaleManager#isLandscape +* @property {boolean} isLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'landscape'; + } + +}); + +/** +* Returns true if the game dimensions are portrait (height > width). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGamePortrait +* @property {boolean} isGamePortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", { + + get: function () { + return (this.height > this.width); + } + +}); + +/** +* Returns true if the game dimensions are landscape (width > height). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGameLandscape +* @property {boolean} isGameLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", { + + get: function () { + return (this.width > this.height); + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of methods for displaying debug information about game objects. +* +* If your game is running in Canvas mode, then you should invoke all of the Debug methods from +* your games `render` function. This is because they are drawn directly onto the game canvas +* itself, so if you call any debug methods outside of `render` they are likely to be overwritten +* by the game itself. +* +* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture +* to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug +* in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! +* +* @class Phaser.Utils.Debug +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Utils.Debug = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Image} sprite - If debugging in WebGL mode, this is the Image displaying the debug {@link #bmd BitmapData}. + */ + this.sprite = null; + + /** + * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.context = null; + + /** + * @property {string} font - The font that the debug information is rendered in. + * @default + */ + this.font = '14px Courier'; + + /** + * @property {number} columnWidth - The spacing between columns. + * @default + */ + this.columnWidth = 100; + + /** + * @property {number} lineHeight - The line height between the debug text. + * @default + */ + this.lineHeight = 16; + + /** + * @property {number} lineWidth - The width of the stroke on lines and shapes. A positive number. + * @default + */ + this.lineWidth = 1; + + /** + * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. + * @default + */ + this.renderShadow = true; + + /** + * @property {string} currentColor - The color last set by {@link #start} or {@link #text}. + * @default + * @protected + */ + this.currentColor = null; + + /** + * @property {number} currentX - The current X position the debug information will be rendered at. + * @default + */ + this.currentX = 0; + + /** + * @property {number} currentY - The current Y position the debug information will be rendered at. + * @default + */ + this.currentY = 0; + + /** + * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it. + * @default + */ + this.currentAlpha = 1; + + /** + * @property {boolean} dirty - Does the canvas need re-rendering? + * @default + */ + this.dirty = false; + + /** + * @property {boolean} isDisabled - If `enableDebug: false` is passed to {@link Phaser.Game} or if Phaser is built without the Debug class, this will be true. + * @default + * @readonly + */ + this.isDisabled = false; + + /** + * @property {Phaser.Line} _line - A reusable rendering line. + * @private + */ + this._line = null; + + /** + * @property {Phaser.Rectangle} _rect - A reusable rendering rectangle. + * @private + */ + this._rect = null; + +}; + +Phaser.Utils.Debug.prototype = { + + /** + * Internal method that boots the debug displayer. + * + * @method Phaser.Utils.Debug#boot + * @protected + */ + boot: function () { + + if (this.game.renderType === Phaser.CANVAS) + { + this.context = this.game.context; + } + else + { + this.bmd = new Phaser.BitmapData(this.game, '__DEBUG', this.game.width, this.game.height, true); + this.sprite = this.game.make.image(0, 0, this.bmd); + this.game.stage.addChild(this.sprite); + + this.game.scale.onSizeChange.add(this.resize, this); + + this.canvas = Phaser.CanvasPool.create(this, this.game.width, this.game.height); + this.context = this.canvas.getContext('2d'); + } + + this._line = new Phaser.Line(); + this._rect = new Phaser.Rectangle(); + + }, + + /** + * Internal method that resizes the BitmapData and Canvas. + * Called by ScaleManager.onSizeChange only in WebGL mode. + * + * @method Phaser.Utils.Debug#resize + * @protected + */ + resize: function () { + + this.bmd.resize(this.game.width, this.game.height); + + this.canvas.width = this.game.width; + this.canvas.height = this.game.height; + + }, + + /** + * Internal method that clears the canvas (if a Sprite) ready for a new debug session. + * + * @method Phaser.Utils.Debug#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.dirty && this.sprite) + { + this.bmd.clear(); + this.bmd.draw(this.canvas, 0, 0); + + this.context.clearRect(0, 0, this.game.width, this.game.height); + this.dirty = false; + } + + }, + + /** + * Clears the Debug canvas. + * + * @method Phaser.Utils.Debug#reset + */ + reset: function () { + + if (this.context) + { + this.context.clearRect(0, 0, this.game.width, this.game.height); + } + + if (this.sprite) + { + this.bmd.clear(); + } + + }, + + /** + * Internal method that resets and starts the debug output values. + * + * @method Phaser.Utils.Debug#start + * @protected + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + * @param {number} [columnWidth=0] - The spacing between columns. + */ + start: function (x, y, color, columnWidth) { + + if (typeof x !== 'number') { x = 0; } + if (typeof y !== 'number') { y = 0; } + color = color || 'rgb(255,255,255)'; + if (columnWidth === undefined) { columnWidth = 0; } + + this.currentX = x; + this.currentY = y; + this.currentColor = color; + this.columnWidth = columnWidth; + + this.dirty = true; + + this.context.save(); + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.strokeStyle = color; + this.context.fillStyle = color; + this.context.font = this.font; + this.context.globalAlpha = this.currentAlpha; + + }, + + /** + * Internal method that stops the debug output. + * + * @method Phaser.Utils.Debug#stop + * @protected + */ + stop: function () { + + this.context.restore(); + + }, + + /** + * Internal method that outputs a single line of text split over as many columns as needed, one per parameter. + * + * @method Phaser.Utils.Debug#line + * @protected + */ + line: function () { + + var x = this.currentX; + + for (var i = 0; i < arguments.length; i++) + { + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(arguments[i], x + 1, this.currentY + 1); + this.context.fillStyle = this.currentColor; + } + + this.context.fillText(arguments[i], x, this.currentY); + + x += this.columnWidth; + } + + this.currentY += this.lineHeight; + + }, + + /** + * Render Sound Manager information, including volume, mute, audio mode, and locked status. + * + * @method Phaser.Utils.Debug#sound + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + sound: function (x, y, color) { + + var sound = this.game.sound; + + this.start(x, y, color); + + if (sound.noAudio) + { + this.line('Audio is disabled'); + } + else + { + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Mute on pause: ' + sound.muteOnPause); + this.line('Using: ' + (sound.usingWebAudio ? ('Web Audio - ' + sound.context.state) : 'Audio Tag')); + this.line('Touch locked: ' + sound.touchLocked); + } + + this.stop(); + + }, + + /** + * Render Sound information, including decoded state, duration, volume and more. + * + * @method Phaser.Utils.Debug#soundInfo + * @param {Phaser.Sound} sound - The sound object to debug. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + soundInfo: function (sound, x, y, color) { + + this.start(x, y, color); + this.line('Sound: ' + sound.key + ' Touch locked: ' + sound.game.sound.touchLocked); + this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback); + this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding); + this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying + ' Loop: ' + sound.loop); + this.line('Time: ' + sound.currentTime); + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Using: ' + (sound.usingWebAudio ? 'Web Audio' : 'Audio Tag')); + + if (sound.currentMarker !== '') + { + this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')'); + this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop); + this.line('Position: ' + sound.position); + } + + this.stop(); + + }, + + /** + * Marks the follow {@link #target} and {@link #deadzone}. + * + * @method Phaser.Utils.Debug#camera + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {string} [color] - Color of the debug shapes to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the shapes filled (default, true) or stroked (false). + */ + camera: function (camera, color, filled) { + + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + if (deadzone) + { + this._rect.setTo(view.x + deadzone.x, view.y + deadzone.y, deadzone.width, deadzone.height); + this.rectangle(this._rect, color, filled); + } + + if (target) + { + this._line.setTo(view.centerX, view.centerY, target.x, target.y); + this.geom(this._line, color, filled); + this.geom(target, color, false, 3); + } + + }, + + /** + * Render camera information including dimensions and location. + * + * @method Phaser.Utils.Debug#cameraInfo + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + cameraInfo: function (camera, x, y, color) { + + var bounds = camera.bounds; + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + this.start(x, y, color); + this.line('Camera (' + camera.width + ' x ' + camera.height + ')'); + this.line('x: ' + camera.x + ' y: ' + camera.y); + this.line('Bounds: ' + (bounds ? ('x: ' + bounds.x + ' y: ' + bounds.y + ' w: ' + bounds.width + ' h: ' + bounds.height) : 'none')); + this.line('View: x: ' + view.x + ' y: ' + view.y + ' w: ' + view.width + ' h: ' + view.height); + this.line('Deadzone: ' + (deadzone ? ('x: ' + deadzone.x + ' y: ' + deadzone.y + ' w: ' + deadzone.width + ' h: ' + deadzone.height) : deadzone)); + this.line('Total in view: ' + camera.totalInView); + this.line('At limit: x: ' + camera.atLimit.x + ' y: ' + camera.atLimit.y); + this.line('Target: ' + (target ? (target.name || target) : 'none')); + this.stop(); + + }, + + /** + * Render Timer information. + * + * @method Phaser.Utils.Debug#timer + * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + timer: function (timer, x, y, color) { + + this.start(x, y, color); + this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')'); + this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration); + this.line('Paused: ' + timer.paused + ' Length: ' + timer.length); + this.stop(); + + }, + + /** + * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text. + * + * @method Phaser.Utils.Debug#pointer + * @param {Phaser.Pointer} pointer - The Pointer you wish to display. + * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. + * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down. + * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false). + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + pointer: function (pointer, hideIfUp, downColor, upColor, color) { + + if (pointer == null) + { + return; + } + + if (hideIfUp === undefined) { hideIfUp = false; } + downColor = downColor || 'rgba(0,255,0,0.5)'; + upColor = upColor || 'rgba(255,0,0,0.5)'; + + if (hideIfUp === true && pointer.isUp === true) + { + return; + } + + this.start(pointer.x, pointer.y - 100, color); + this.context.beginPath(); + this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2); + + if (pointer.active) + { + this.context.fillStyle = downColor; + } + else + { + this.context.fillStyle = upColor; + } + + this.context.fill(); + this.context.closePath(); + + // Render the points + this.context.beginPath(); + this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y); + this.context.lineTo(pointer.position.x, pointer.position.y); + this.context.lineWidth = 2; + this.context.stroke(); + this.context.closePath(); + + // Render the text + this.line('ID: ' + pointer.id + " Active: " + pointer.active); + this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY); + this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y + " In: " + pointer.withinGame); + this.line('Duration: ' + pointer.duration + " ms"); + this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp); + this.stop(); + + }, + + /** + * Render Sprite Input Debug information. + * + * @method Phaser.Utils.Debug#spriteInputInfo + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInputInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')'); + this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1)); + this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0)); + this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0)); + this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut()); + this.stop(); + + }, + + /** + * Renders Phaser.Key object information. + * + * @method Phaser.Utils.Debug#key + * @param {Phaser.Key} key - The Key to render the information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + key: function (key, x, y, color) { + + this.start(x, y, color, 150); + + this.line('Key:', key.keyCode, 'isDown:', key.isDown); + this.line('justDown:', key.justDown, 'justUp:', key.justUp); + this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0)); + + this.stop(); + + }, + + /** + * Render debug information about the Input object. + * + * @method Phaser.Utils.Debug#inputInfo + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + inputInfo: function (x, y, color) { + + this.start(x, y, color); + this.line('Input'); + this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y); + this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY); + this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1)); + this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY); + this.stop(); + + }, + + /** + * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! + * + * @method Phaser.Utils.Debug#spriteBounds + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + spriteBounds: function (sprite, color, filled) { + + var bounds = sprite.getBounds(); + + bounds.x += this.game.camera.x; + bounds.y += this.game.camera.y; + + this.rectangle(bounds, color, filled); + + }, + + /** + * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it + * + * @method Phaser.Utils.Debug#ropeSegments + * @param {Phaser.Rope} rope - The rope to display the segments of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + ropeSegments: function (rope, color, filled) { + + var segments = rope.segments; + + var self = this; + + segments.forEach(function(segment) { + self.rectangle(segment, color, filled); + }, this); + + }, + + /** + * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. + * + * @method Phaser.Utils.Debug#spriteInfo + * @param {Phaser.Sprite} sprite - The Sprite to display the information of. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + + this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y); + this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1)); + this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1)); + this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera); + this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1)); + + this.stop(); + + }, + + /** + * Renders the sprite coordinates in local, positional and world space. + * + * @method Phaser.Utils.Debug#spriteCoords + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteCoords: function (sprite, x, y, color) { + + this.start(x, y, color, 100); + + if (sprite.name) + { + this.line(sprite.name); + } + + this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2)); + this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2)); + this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2)); + + this.stop(); + + }, + + /** + * Renders Line information in the given color. + * + * @method Phaser.Utils.Debug#lineInfo + * @param {Phaser.Line} line - The Line to display the data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + lineInfo: function (line, x, y, color) { + + this.start(x, y, color, 80); + this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2)); + this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2)); + this.line('length:', line.length.toFixed(2), 'angle:', line.angle); + this.stop(); + + }, + + /** + * Renders a single pixel at the given size. + * + * @method Phaser.Utils.Debug#pixel + * @param {number} x - X position of the pixel to be rendered. + * @param {number} y - Y position of the pixel to be rendered. + * @param {string} [color] - Color of the pixel (format is css color string). + * @param {number} [size=2] - The 'size' to render the pixel at. + */ + pixel: function (x, y, color, size) { + + size = size || 2; + + this.start(); + this.context.fillStyle = color; + this.context.fillRect(x, y, size, size); + this.stop(); + + }, + + /** + * Renders a Phaser geometry object including Rectangle, Circle, Ellipse, Point or Line. + * + * @method Phaser.Utils.Debug#geom + * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Ellipse|Phaser.Point|Phaser.Line} object - The geometry object to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) + * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle,3 = Point, 4 = Line and 5 = Ellipse. + */ + geom: function (object, color, filled, forceType) { + + if (filled === undefined) { filled = true; } + if (forceType === undefined) { forceType = 0; } + + color = color || 'rgba(0,255,0,0.4)'; + + this.start(); + + this.context.fillStyle = color; + this.context.strokeStyle = color; + this.context.lineWidth = this.lineWidth; + + if (object instanceof Phaser.Rectangle || forceType === 1) + { + if (filled) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + } + else if (object instanceof Phaser.Circle || forceType === 2) + { + this.context.beginPath(); + this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + else if (object instanceof Phaser.Point || forceType === 3) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4); + } + else if (object instanceof Phaser.Line || forceType === 4) + { + this.context.beginPath(); + this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y); + this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y); + this.context.closePath(); + this.context.stroke(); + } + else if (object instanceof Phaser.Ellipse || forceType === 5) + { + this.context.beginPath(); + this.context.ellipse(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width/2, object.height/2, 0,2 * Math.PI,false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + + this.stop(); + + }, + + /** + * Renders a Rectangle. + * + * @method Phaser.Utils.Debug#rectangle + * @param {Phaser.Rectangle|object} object - The rectangle to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as filled (default, true) or a stroked (false) + */ + rectangle: function (object, color, filled) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0, 255, 0, 0.4)'; + + this.start(); + + if (filled) + { + this.context.fillStyle = color; + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.lineWidth = this.lineWidth; + this.context.strokeStyle = color; + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + + this.stop(); + + }, + + /** + * Render a string of text. + * + * @method Phaser.Utils.Debug#text + * @param {string} text - The line of text to draw. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {string} [font] - The font of text to draw. + */ + text: function (text, x, y, color, font) { + + color = color || 'rgb(255,255,255)'; + font = font || '16px Courier'; + + this.start(); + this.context.font = font; + + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(text, x + 1, y + 1); + } + + this.context.fillStyle = color; + this.context.fillText(text, x, y); + + this.stop(); + + }, + + /** + * Visually renders a QuadTree to the display. + * + * @method Phaser.Utils.Debug#quadTree + * @param {Phaser.QuadTree} quadtree - The quadtree to render. + * @param {string} color - The color of the lines in the quadtree. + */ + quadTree: function (quadtree, color) { + + color = color || 'rgba(255,0,0,0.3)'; + + this.start(); + + var bounds = quadtree.bounds; + + if (quadtree.nodes.length === 0) + { + this.context.strokeStyle = color; + this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height); + this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier'); + + this.context.strokeStyle = 'rgb(0,255,0)'; + + for (var i = 0; i < quadtree.objects.length; i++) + { + this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height); + } + } + else + { + for (var i = 0; i < quadtree.nodes.length; i++) + { + this.quadTree(quadtree.nodes[i]); + } + } + + this.stop(); + + }, + + /** + * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. + * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. + * To display a P2 Physics body you should enable debug mode on the body when creating it. + * + * @method Phaser.Utils.Debug#body + * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false) + */ + body: function (sprite, color, filled) { + + if (sprite.body) + { + this.start(); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled, this.lineWidth); + } + else if (sprite.body.type === Phaser.Physics.NINJA) + { + Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color); + } + + this.stop(); + } + + }, + + /** + * Render a Sprites Physic Body information. + * + * @method Phaser.Utils.Debug#bodyInfo + * @param {Phaser.Sprite} sprite - The sprite to be rendered. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + bodyInfo: function (sprite, x, y, color) { + + if (sprite.body) + { + this.start(x, y, color, 210); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + this.game.physics.box2d.renderBodyInfo(this, sprite.body); + } + + this.stop(); + } + + }, + + /** + * Renders 'debug draw' data for the Box2D world if it exists. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by + * the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dWorld + */ + box2dWorld: function () { + + this.start(); + + this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0); + this.game.physics.box2d.renderDebugDraw(this.context); + + this.stop(); + + }, + + /** + * Renders 'debug draw' data for the given Box2D body. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dBody + * @param {Phaser.Physics.Box2D.Body} body - The body to be rendered. + * @param {string} [color='rgb(0,255,0)'] - Color of the rendering (format is css color string). + */ + box2dBody: function (body, color) { + + this.start(); + Phaser.Physics.Box2D.renderBody(this.context, body, color); + this.stop(); + + }, + + /** + * Call this function from the Dev Tools console. + * + * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. + * + * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) + * + * @method Phaser.Utils.Debug#displayList + * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World. + */ + displayList: function (displayObject) { + + if (displayObject === undefined) { displayObject = this.game.world; } + + if (displayObject.hasOwnProperty('renderOrderID')) + { + console.log('[' + displayObject.renderOrderID + ']', displayObject); + } + else + { + console.log('[]', displayObject); + } + + if (displayObject.children && displayObject.children.length > 0) + { + for (var i = 0; i < displayObject.children.length; i++) + { + this.game.debug.displayList(displayObject.children[i]); + } + } + + }, + + /** + * Prints a description of the {@link Phaser.Game#renderer renderer} and render session. + * + * @method Phaser.Utils.Debug#renderer + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + renderer: function (x, y, color) { + + var r = this.game.renderer; + var s = r.renderSession; + + this.start(x, y, color); + + this.line((r.gl ? 'WebGL' : 'Canvas') + ' Renderer (' + r.width + ' x ' + r.height + ')'); + this.line('autoResize: ' + r.autoResize); + this.line('clearBeforeRender: ' + r.clearBeforeRender); + this.line('resolution: ' + r.resolution); + this.line('transparent: ' + r.transparent); + this.line('renderSession:'); + + if (r.gl) + { + this.line(' currentBatchedTextures: ('+ r.currentBatchedTextures.length + ')'); + + for (var i = 0; i < r.currentBatchedTextures.length; i++) + { + this.line(' ' + r.currentBatchedTextures[i]); + } + + this.line(' drawCount: ' + s.drawCount); + this.line(' maxTextures: ' + r.maxTextures); + this.line(' maxTextureSize: ' + r.maxTextureSize); + this.line(' maxTextureAvailableSpace: ' + s.maxTextureAvailableSpace); + this.line(' roundPixels: ' + s.roundPixels); + } + else + { + this.line(' roundPixels: ' + s.roundPixels); + this.line(' scaleMode: ' + (s.scaleMode === 0 ? 'LINEAR' : (s.scaleMode === 1 ? 'NEAREST' : s.scaleMode))); + } + + this.stop(); + + }, + + canvasPool: function (x, y, color, columnWidth) { + var pool = Phaser.CanvasPool; + + this.start(x, y, color, columnWidth || 100); + this.line('Canvas Pool'); + this.line('Used:', pool.getTotal()); + this.line('Free:', pool.getFree()); + this.line('Total:', pool.length); + this.stop(); + }, + + /** + * Render each physics {@link #body} in a group. + * + * @method Phaser.Utils.Debug#physicsGroup + * @param {Phaser.Group} group - A group containing physics-enabled sprites. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false). + * @param {boolean} [checkExists=false] Render only children with `exists=true`. + */ + physicsGroup: function (group, color, filled, checkExists) { + + group.forEach(this.body, this, checkExists, color, filled); + + }, + + /** + * Prints Phaser {@link Phaser.VERSION version}, {@link Phaser.Game.#renderType rendering mode}, and {@link Phaser.Device#webAudio device audio support}. + * + * @method Phaser.Utils.Debug#phaser + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + phaser: function (x, y, color) { + + this.text('Phaser v' + Phaser.VERSION + ' ' + + (this.game.renderType === Phaser.WEBGL ? 'WebGL' : 'Canvas') + ' ' + + (this.game.device.webAudio ? 'WebAudio' : 'HTML Audio'), + x, y, color, this.font); + + }, + + /** + * Prints game/canvas dimensions and {@link Phaser.ScaleManager game scale} settings. + * + * @method Phaser.Utils.Debug#scale + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + scale: function (x, y, color) { + + this.start(x, y, color); + + var scale = this.game.scale; + var factor = scale.scaleFactorInversed; + var bounds = scale._parentBounds; + var x = ' x '; + + this.line('Game: ' + this.game.width + x + this.game.height); + this.line('Canvas: ' + scale.width + x + scale.height + + ' (' + factor.x.toFixed(2) + x + factor.y.toFixed(2) + ')' + + ' [' + scale.aspectRatio.toFixed(2) + ']'); + this.line('Mode: ' + Phaser.ScaleManager.MODES[scale.currentScaleMode] + + (scale.currentScaleMode === Phaser.ScaleManager.USER_SCALE ? + (' (' + scale._userScaleFactor.x + x + scale._userScaleFactor.y + ')') : + '')); + this.line('Parent: ' + (scale.parentIsWindow ? 'window' : scale.parentNode) + + (bounds.empty ? '' : (' (' + bounds.width + x + bounds.height + ')'))); + this.line('Screen: ' + scale.classifyOrientation(scale.screenOrientation) + + (scale.incorrectOrientation ? ' (incorrect)' : '')); + + this.stop(); + + }, + + /** + * Prints the progress of a {@link Phaser.Loader}. + * + * Typically you would call this within a {@link State#loadRender} callback and pass `game.load` ({@link Phaser.Game#load}). + * + * You can enable {@link Phaser.Loader#resetLocked} to temporarily hold the loader in its 'complete' state. + * Just remember to disable it before restarting the loader (such as when changing states). + * + * @method Phaser.Utils.Debug#loader + * @param {Phaser.Loader} loader - The loader. Usually `game.load` ({@link Phaser.Game#load}). + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + loader: function (loader, x, y, color) { + + var pad = Phaser.Utils.pad; + + this.start(x, y, color); + + if (loader.hasLoaded) + { + this.line('Complete' + (loader.resetLocked ? ' [locked]' : '')); + } + else if (loader.isLoading) + { + this.line('Loading'); + } + else + { + this.line('Not started'); + } + + if (!loader.hasLoaded || loader.resetLocked) + { + this.line('Progress: ' + (pad(loader.progress, 3) + '%')); + this.line('Files: ' + loader._loadedFileCount + ' of ' + + loader._totalFileCount); + this.line('Packs: ' + loader._loadedPackCount + ' of ' + + loader._loadedPackCount); + } + + this.stop(); + + }, + + /** + * Destroy this object. + * + * @method Phaser.Utils.Debug#destroy + */ + destroy: function () { + + Phaser.CanvasPool.remove(this); + + } + +}; + +Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DOM utility class. +* +* Provides a useful Window and Element functions as well as cross-browser compatibility buffer. +* +* Some code originally derived from {@link https://github.com/ryanve/verge verge}. +* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. +* +* @class Phaser.DOM +* @static +*/ +Phaser.DOM = { + + /** + * Get the [absolute] position of the element relative to the Document. + * + * The value may vary slightly as the page is scrolled due to rounding errors. + * + * @method Phaser.DOM.getOffset + * @param {DOMElement} element - The targeted element that we want to retrieve the offset. + * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. + * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. + */ + getOffset: function (element, point) { + + point = point || new Phaser.Point(); + + var box = element.getBoundingClientRect(); + + var scrollTop = Phaser.DOM.scrollY; + var scrollLeft = Phaser.DOM.scrollX; + var clientTop = document.documentElement.clientTop; + var clientLeft = document.documentElement.clientLeft; + + point.x = box.left + scrollLeft - clientLeft; + point.y = box.top + scrollTop - clientTop; + + return point; + + }, + + /** + * A cross-browser element.getBoundingClientRect method with optional cushion. + * + * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. + * Its properties match the native rectangle. + * The cushion parameter is an amount of pixels (+/-) to cushion the element. + * It adjusts the measurements such that it is possible to detect when an element is near the viewport. + * + * @method Phaser.DOM.getBounds + * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for. + * @param {number} [cushion] - A +/- pixel adjustment amount. + * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. + */ + getBounds: function (element, cushion) { + + if (cushion === undefined) { cushion = 0; } + + element = element && !element.nodeType ? element[0] : element; + + if (!element || element.nodeType !== 1) + { + return false; + } + else + { + return this.calibrate(element.getBoundingClientRect(), cushion); + } + + }, + + /** + * Calibrates element coordinates for `inLayoutViewport` checks. + * + * @method Phaser.DOM.calibrate + * @private + * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}` + * @param {number} [cushion] - A value to adjust the coordinates by. + * @return {object} The calibrated element coordinates + */ + calibrate: function (coords, cushion) { + + cushion = +cushion || 0; + + var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 }; + + output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion); + output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion); + + return output; + + }, + + /** + * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) + * + * @method Phaser.DOM.getAspectRatio + * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. + * @return {number} The aspect ratio. + */ + getAspectRatio: function (object) { + + object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object; + + var w = object['width']; + var h = object['height']; + + if (typeof w === 'function') + { + w = w.call(object); + } + + if (typeof h === 'function') + { + h = h.call(object); + } + + return w / h; + + }, + + /** + * Tests if the given DOM element is within the Layout viewport. + * + * The optional cushion parameter allows you to specify a distance. + * + * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. + * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. + * + * @method Phaser.DOM.inLayoutViewport + * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas. + * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport. + * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it. + */ + inLayoutViewport: function (element, cushion) { + + var r = this.getBounds(element, cushion); + + return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height; + + }, + + /** + * Returns the device screen orientation. + * + * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. + * + * Order of resolving: + * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. + * - Screen size ratio check - If fallback is 'screen', suited for desktops. + * - Viewport size ratio check - If fallback is 'viewport', suited for mobile. + * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. + * - Media query + * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..) + * + * See + * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) + * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) + * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx + * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries + * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation + * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation + * + * @method Phaser.DOM.getScreenOrientation + * @protected + * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'. + */ + getScreenOrientation: function (primaryFallback) { + + var screen = window.screen; + var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; + + if (orientation && typeof orientation.type === 'string') + { + // Screen Orientation API specification + return orientation.type; + } + else if (typeof orientation === 'string') + { + // moz/ms-orientation are strings + return orientation; + } + + var PORTRAIT = 'portrait-primary'; + var LANDSCAPE = 'landscape-primary'; + + if (primaryFallback === 'screen') + { + return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'viewport') + { + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number') + { + // This may change by device based on "natural" orientation. + return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE; + } + else if (window.matchMedia) + { + if (window.matchMedia("(orientation: portrait)").matches) + { + return PORTRAIT; + } + else if (window.matchMedia("(orientation: landscape)").matches) + { + return LANDSCAPE; + } + } + + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + + }, + + /** + * The bounds of the Visual viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one} + * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers. + * + * Supported mobile: + * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} x - Scroll, left offset - eg. "scrollX" + * @property {number} y - Scroll, top offset - eg. "scrollY" + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + visualBounds: new Phaser.Rectangle(), + + /** + * The bounds of the Layout viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two}; + * but honoring the constraints as specified applicable viewport meta-tag. + * + * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see + * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}). + * + * This is _not_ representative of the Visual bounds: in particular the non-primary axis will + * generally be significantly larger than the screen height on mobile devices when running with a + * constrained viewport. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + layoutBounds: new Phaser.Rectangle(), + + /** + * The size of the document / Layout viewport. + * + * This incorrectly reports the dimensions in IE. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Document width in pixels. + * @property {number} height - Document height in pixels. + * @readonly + */ + documentBounds: new Phaser.Rectangle() + +}; + +Phaser.Device.whenReady(function (device) { + + // All target browsers should support page[XY]Offset. + var scrollX = window && ('pageXOffset' in window) ? + function () { return window.pageXOffset; } : + function () { return document.documentElement.scrollLeft; }; + + var scrollY = window && ('pageYOffset' in window) ? + function () { return window.pageYOffset; } : + function () { return document.documentElement.scrollTop; }; + + /** + * A cross-browser window.scrollX. + * + * @name Phaser.DOM.scrollX + * @property {number} scrollX + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollX", { + get: scrollX + }); + + /** + * A cross-browser window.scrollY. + * + * @name Phaser.DOM.scrollY + * @property {number} scrollY + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollY", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "x", { + get: scrollX + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "y", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "y", { + value: 0 + }); + + var treatAsDesktop = device.desktop && + (document.documentElement.clientWidth <= window.innerWidth) && + (document.documentElement.clientHeight <= window.innerHeight); + + // Desktop browsers align the layout viewport with the visual viewport. + // This differs from mobile browsers with their zooming design. + // Ref. http://quirksmode.org/mobile/tableViewport.html + if (treatAsDesktop) + { + + // PST- When scrollbars are not included this causes upstream issues in ScaleManager. + // So reverted to the old "include scrollbars." + var clientWidth = function () { + return Math.max(window.innerWidth, document.documentElement.clientWidth); + }; + var clientHeight = function () { + return Math.max(window.innerHeight, document.documentElement.clientHeight); + }; + + // Interested in area sans-scrollbar + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: clientHeight + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + get: clientHeight + }); + + } else { + + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: function () { + return window.innerWidth; + } + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: function () { + return window.innerHeight; + } + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + + get: function () { + var a = document.documentElement.clientWidth; + var b = window.innerWidth; + + return a < b ? b : a; // max + } + + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + + get: function () { + var a = document.documentElement.clientHeight; + var b = window.innerHeight; + + return a < b ? b : a; // max + } + + }); + + } + + // For Phaser.DOM.documentBounds + // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html + + Object.defineProperty(Phaser.DOM.documentBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "y", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "width", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth); + } + + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "height", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight); + } + + }); + +}, null, true); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* ArraySet is a Set data structure (items must be unique within the set) that also maintains order. +* This allows specific items to be easily added or removed from the Set. +* +* Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. +* +* This used primarily by the Input subsystem. +* +* @class Phaser.ArraySet +* @constructor +* @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet. +*/ +Phaser.ArraySet = function (list) { + + /** + * Current cursor position as established by `first` and `next`. + * @property {integer} position + * @default + */ + this.position = 0; + + /** + * The backing array. + * @property {any[]} list + */ + this.list = list || []; + +}; + +Phaser.ArraySet.prototype = { + + /** + * Adds a new element to the end of the list. + * If the item already exists in the list it is not moved. + * + * @method Phaser.ArraySet#add + * @param {any} item - The element to add to this list. + * @return {any} The item that was added. + */ + add: function (item) { + + if (!this.exists(item)) + { + this.list.push(item); + } + + return item; + + }, + + /** + * Gets the index of the item in the list, or -1 if it isn't in the list. + * + * @method Phaser.ArraySet#getIndex + * @param {any} item - The element to get the list index for. + * @return {integer} The index of the item or -1 if not found. + */ + getIndex: function (item) { + + return this.list.indexOf(item); + + }, + + /** + * Gets an item from the set based on the property strictly equaling the value given. + * Returns null if not found. + * + * @method Phaser.ArraySet#getByKey + * @param {string} property - The property to check against the value. + * @param {any} value - The value to check if the property strictly equals. + * @return {any} The item that was found, or null if nothing matched. + */ + getByKey: function (property, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i][property] === value) + { + return this.list[i]; + } + } + + return null; + + }, + + /** + * Checks for the item within this list. + * + * @method Phaser.ArraySet#exists + * @param {any} item - The element to get the list index for. + * @return {boolean} True if the item is found in the list, otherwise false. + */ + exists: function (item) { + + return (this.list.indexOf(item) > -1); + + }, + + /** + * Removes all the items. + * + * @method Phaser.ArraySet#reset + */ + reset: function () { + + this.list.length = 0; + + }, + + /** + * Removes the given element from this list if it exists. + * + * @method Phaser.ArraySet#remove + * @param {any} item - The item to be removed from the list. + * @return {any} item - The item that was removed. + */ + remove: function (item) { + + var idx = this.list.indexOf(item); + + if (idx > -1) + { + this.list.splice(idx, 1); + return item; + } + + }, + + /** + * Sets the property `key` to the given value on all members of this list. + * + * @method Phaser.ArraySet#setAll + * @param {any} key - The property of the item to set. + * @param {any} value - The value to set the property to. + */ + setAll: function (key, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + this.list[i][key] = value; + } + } + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * + * If the `key` property is present it must be a function. + * The function is invoked using the item as the context. + * + * @method Phaser.ArraySet#callAll + * @param {string} key - The name of the property with the function to call. + * @param {...*} parameter - Additional parameters that will be passed to the callback. + */ + callAll: function (key) { + + var args = Array.prototype.slice.call(arguments, 1); + + var i = this.list.length; + + while (i--) + { + if (this.list[i] && this.list[i][key]) + { + this.list[i][key].apply(this.list[i], args); + } + } + + }, + + /** + * Removes every member from this ArraySet and optionally destroys it. + * + * @method Phaser.ArraySet#removeAll + * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set. + */ + removeAll: function (destroy) { + + if (destroy === undefined) { destroy = false; } + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + var item = this.remove(this.list[i]); + + if (destroy) + { + item.destroy(); + } + } + } + + this.position = 0; + this.list = []; + + } + +}; + +/** +* Number of items in the ArraySet. Same as `list.length`. +* +* @name Phaser.ArraySet#total +* @property {integer} total +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "total", { + + get: function () { + return this.list.length; + } + +}); + +/** +* Returns the first item and resets the cursor to the start. +* +* @name Phaser.ArraySet#first +* @property {any} first +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "first", { + + get: function () { + + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + + } + +}); + +/** +* Returns the the next item (based on the cursor) and advances the cursor. +* +* @name Phaser.ArraySet#next +* @property {any} next +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "next", { + + get: function () { + + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + + } + +}); + +Phaser.ArraySet.prototype.constructor = Phaser.ArraySet; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Utility functions for dealing with Arrays. +* +* @class Phaser.ArrayUtils +* @static +*/ +Phaser.ArrayUtils = { + + /** + * Fetch a random entry from the given array. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.getRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was selected. + */ + getRandomItem: function (objects, startIndex, length) { + + if (objects === null) { return null; } + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + + return objects[randomIndex] === undefined ? null : objects[randomIndex]; + + }, + + /** + * Removes a random object from the given array and returns it. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.removeRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was removed. + */ + removeRandomItem: function (objects, startIndex, length) { + + if (objects == null) { // undefined or null + return null; + } + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + if (randomIndex < objects.length) + { + var removed = objects.splice(randomIndex, 1); + return removed[0] === undefined ? null : removed[0]; + } + else + { + return null; + } + + }, + + /** + * Remove one or more items at the given index and reorder the array. + * + * The new array length will be `array.length - count`. + * + * This is an alternative to `array.splice(startIndex, count)`. + * + * @see https://github.com/mreinstein/remove-array-items + * @see https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ + * + * @method Phaser.ArrayUtils.remove + * @param {any[]} array + * @param {integer} startIndex + * @param {integer} [count=1] + * @return {any[]} The modified array. + */ + remove: function (array, startIndex, count) + { + var length = array.length; + + if (startIndex >= length || count === 0) { return; } + + if (count == null) { count = 1; } + + var newLength = length - count; + + for (var i = startIndex; i < newLength; ++i) + { + array[i] = array[i + count]; + } + + array.length = newLength; + }, + + /** + * A standard Fisher-Yates Array shuffle implementation which modifies the array in place. + * + * @method Phaser.ArrayUtils.shuffle + * @param {any[]} array - The array to shuffle. + * @return {any[]} The original array, now shuffled. + */ + shuffle: function (array) { + + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; + + }, + + /** + * Transposes the elements of the given matrix (array of arrays). + * + * @method Phaser.ArrayUtils.transposeMatrix + * @param {Array} array - The matrix to transpose. + * @return {Array} A new transposed matrix + */ + transposeMatrix: function (array) { + + var sourceRowCount = array.length; + var sourceColCount = array[0].length; + + var result = new Array(sourceColCount); + + for (var i = 0; i < sourceColCount; i++) + { + result[i] = new Array(sourceRowCount); + + for (var j = sourceRowCount - 1; j > -1; j--) + { + result[i][j] = array[j][i]; + } + } + + return result; + + }, + + /** + * Rotates the given matrix (array of arrays). + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @method Phaser.ArrayUtils.rotateMatrix + * @param {Array} matrix - The array to rotate; this matrix _may_ be altered. + * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). + * @return {Array} The rotated matrix. The source matrix should be discarded for the returned matrix. + */ + rotateMatrix: function (matrix, direction) { + + if (typeof direction !== 'string') + { + direction = ((direction % 360) + 360) % 360; + } + + if (direction === 90 || direction === -270 || direction === 'rotateLeft') + { + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + matrix = matrix.reverse(); + } + else if (direction === -90 || direction === 270 || direction === 'rotateRight') + { + matrix = matrix.reverse(); + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + } + else if (Math.abs(direction) === 180 || direction === 'rotate180') + { + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + matrix = matrix.reverse(); + } + + return matrix; + + }, + + /** + * Snaps a value to the nearest value in a sorted numeric array. + * The result will always be in the range `[first_value, last_value]`. + * + * @method Phaser.ArrayUtils.findClosest + * @param {number} value - The search value + * @param {number[]} arr - The input array which _must_ be sorted. + * @return {number} The nearest value found. + */ + findClosest: function (value, arr) { + + if (!arr.length) + { + return NaN; + } + else if (arr.length === 1 || value < arr[0]) + { + return arr[0]; + } + + var i = 1; + while (arr[i] < value) { + i++; + } + + var low = arr[i - 1]; + var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; + + return ((high - value) <= (value - low)) ? high : low; + + }, + + /** + * Moves the element from the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ F, A, B, C, D, E ]` + * + * See also Phaser.ArrayUtils.rotateLeft. + * + * @method Phaser.ArrayUtils.rotateRight + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The shifted value. + */ + rotateRight: function (array) { + + var s = array.pop(); + array.unshift(s); + + return s; + + }, + + /** + * Moves the element from the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ B, C, D, E, F, A ]` + * + * See also Phaser.ArrayUtils.rotateRight + * + * @method Phaser.ArrayUtils.rotateLeft + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The rotated value. + */ + rotateLeft: function (array) { + + var s = array.shift(); + array.push(s); + + return s; + + }, + + /** + * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]` (or `[0, start]`, if `end` is omitted). + * This is equivalent to `numberArrayStep(start, 1 + end, 1)`. + * + * When exactly one argument is passed, it's used as `end` and 0 is used as `start`. The length of the result is (1 + end). + * + * ##### Examples + * + * ```javascript + * numberArray(3); // -> [0, 1, 2, 3] + * numberArray(0, 3); // -> [0, 1, 2, 3] + * numberArray(1, 3); // -> [1, 2, 3] + * ``` + * + * @method Phaser.ArrayUtils.numberArray + * @param {number} start - The minimum value the array starts with. + * @param {number} [end] - The maximum value the array contains. + * @return {number[]} The array of number values. + */ + numberArray: function (start, end) { + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + var result = []; + + for (var i = start; i <= end; i++) + { + result.push(i); + } + + return result; + + }, + + /** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @method Phaser.ArrayUtils.numberArrayStep + * @param {number} start - The start of the range. + * @param {number} [end] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * @returns {Array} Returns the new array of numbers. + * @example + * Phaser.ArrayUtils.numberArrayStep(4); + * // => [0, 1, 2, 3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * Phaser.ArrayUtils.numberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * Phaser.ArrayUtils.numberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * Phaser.ArrayUtils.numberArrayStep(0); + * // => [] + */ + numberArrayStep: function (start, end, step) { + + if (start === undefined || start === null) { start = 0; } + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + if (step === undefined) { step = 1; } + + var result = []; + var total = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0); + + for (var i = 0; i < total; i++) + { + result.push(start); + start += step; + } + + return result; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A basic Linked List data structure. +* +* This implementation _modifies_ the `prev` and `next` properties of each item added: +* - The `prev` and `next` properties must be writable and should not be used for any other purpose. +* - Items _cannot_ be added to multiple LinkedLists at the same time. +* - Only objects can be added. +* +* @class Phaser.LinkedList +* @constructor +*/ +Phaser.LinkedList = function () { + + /** + * Next element in the list. + * @property {object} next + * @default + */ + this.next = null; + + /** + * Previous element in the list. + * @property {object} prev + * @default + */ + this.prev = null; + + /** + * First element in the list. + * @property {object} first + * @default + */ + this.first = null; + + /** + * Last element in the list. + * @property {object} last + * @default + */ + this.last = null; + + /** + * Number of elements in the list. + * @property {integer} total + * @default + */ + this.total = 0; + +}; + +Phaser.LinkedList.prototype = { + + /** + * Adds a new element to this linked list. + * + * @method Phaser.LinkedList#add + * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. + * @return {object} The item that was added. + */ + add: function (item) { + + // If the list is empty + if (this.total === 0 && this.first === null && this.last === null) + { + this.first = item; + this.last = item; + this.next = item; + item.prev = this; + this.total++; + return item; + } + + // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list) + this.last.next = item; + + item.prev = this.last; + + this.last = item; + + this.total++; + + return item; + + }, + + /** + * Resets the first, last, next and previous node pointers in this list. + * + * @method Phaser.LinkedList#reset + */ + reset: function () { + + this.first = null; + this.last = null; + this.next = null; + this.prev = null; + this.total = 0; + + }, + + /** + * Removes the given element from this linked list if it exists. + * + * @method Phaser.LinkedList#remove + * @param {object} item - The item to be removed from the list. + */ + remove: function (item) { + + if (this.total === 1) + { + this.reset(); + item.next = item.prev = null; + return; + } + + if (item === this.first) + { + // It was 'first', make 'first' point to first.next + this.first = this.first.next; + } + else if (item === this.last) + { + // It was 'last', make 'last' point to last.prev + this.last = this.last.prev; + } + + if (item.prev) + { + // make item.prev.next point to childs.next instead of item + item.prev.next = item.next; + } + + if (item.next) + { + // make item.next.prev point to item.prev instead of item + item.next.prev = item.prev; + } + + item.next = item.prev = null; + + if (this.first === null ) + { + this.last = null; + } + + this.total--; + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * The function must exist on the member. + * + * @method Phaser.LinkedList#callAll + * @param {function} callback - The function to call. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content +* quickly and easily, without the need for any external files. You can create textures for sprites and in +* coming releases we'll add dynamic sound effect generation support as well (like sfxr). +* +* Access this via `Game.create` (`this.game.create` from within a State object). +* +* @class Phaser.Create +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Create = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.ctx = null; + + /** + * @property {array} palettes - A range of 16 color palettes for use with sprite generation. + */ + this.palettes = [ + { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' }, + { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' }, + { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' } + ]; + +}; + +/** +* A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_ARNE = 0; + +/** +* A 16 color JMP inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JMP = 1; + +/** +* A 16 color CGA inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_CGA = 2; + +/** +* A 16 color C64 inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_C64 = 3; + +/** +* A 16 color palette inspired by Japanese computers like the MSX. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JAPANESE_MACHINE = 4; + +Phaser.Create.prototype = { + + /** + * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite. + * + * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images + * rather than Phaser.Graphics objects, which are expensive to render and limited in scope. + * + * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts. + * + * For example: + * + * `var data = [ + * ' 333 ', + * ' 777 ', + * 'E333E', + * ' 333 ', + * ' 3 3 ' + * ];` + * + * `game.create.texture('bob', data);` + * + * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it + * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');` + * + * Use {@link Phaser.Loader#imageFromTexture} to preload an image of the same. + * + * @method Phaser.Create#texture + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {array} data - An array of pixel data. + * @param {integer} [pixelWidth=8] - The width of each pixel. + * @param {integer} [pixelHeight=8] - The height of each pixel. + * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + texture: function (key, data, pixelWidth, pixelHeight, palette, generateTexture, callback, callbackContext) { + + if (pixelWidth === undefined) { pixelWidth = 8; } + if (pixelHeight === undefined) { pixelHeight = pixelWidth; } + if (palette === undefined) { palette = 0; } + if (generateTexture === undefined) { generateTexture = true; } + + var w = data[0].length * pixelWidth; + var h = data.length * pixelHeight; + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(w, h); + this.bmd.clear(); + + // Draw it + for (var y = 0; y < data.length; y++) + { + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var d = row[x]; + + if (d !== '.' && d !== ' ') + { + this.ctx.fillStyle = this.palettes[palette][d]; + this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); + } + } + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Creates a grid texture based on the given dimensions. + * + * Use {@link Phaser.Loader#imageFromGrid} to preload an image of the same. + * + * @method Phaser.Create#grid + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {integer} width - The width of the grid in pixels. + * @param {integer} height - The height of the grid in pixels. + * @param {integer} cellWidth - The width of the grid cells in pixels. + * @param {integer} cellHeight - The height of the grid cells in pixels. + * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + grid: function (key, width, height, cellWidth, cellHeight, color, generateTexture, callback, callbackContext) { + + if (generateTexture === undefined) { generateTexture = true; } + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(width, height); + + this.ctx.fillStyle = color; + + for (var y = 0; y < height; y += cellHeight) + { + this.ctx.fillRect(0, y, width, 1); + } + + for (var x = 0; x < width; x += cellWidth) + { + this.ctx.fillRect(x, 0, 1, height); + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Copies the contents of {@link bmd Create's canvas} to the given BitmapData object, or a new BitmapData object. + * + * @param {Phaser.BitmapData} [dest] - The BitmapData receiving the copied image. + * @param {number} [x=0] - The x coordinate to translate to before drawing. + * @param {number} [y=0] - The y coordinate to translate to before drawing. + * @param {number} [width] - The new width of the Sprite being copied. + * @param {number} [height] - The new height of the Sprite being copied. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} - The `dest` argument (if passed), or a new BitmapData object + */ + copy: function (dest, x, y, width, height, blendMode, roundPx) { + + if (dest == null) { dest = this.game.make.bitmapData(); } + + dest.resize(this.bmd.width, this.bmd.height); + + return dest.draw(this.bmd, x, y, width, height, blendMode, roundPx); + + } + +}; + +Phaser.Create.prototype.constructor = Phaser.Create; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers +* to provide for game object positioning in a responsive manner. +* +* @class Phaser.FlexGrid +* @constructor +* @param {Phaser.ScaleManager} manager - The ScaleManager. +* @param {number} width - The width of the game. +* @param {number} height - The height of the game. +*/ +Phaser.FlexGrid = function (manager, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = manager.game; + + /** + * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager. + */ + this.manager = manager; + + // The perfect dimensions on which everything else is based + this.width = width; + this.height = height; + + this.boundsCustom = new Phaser.Rectangle(0, 0, width, height); + this.boundsFluid = new Phaser.Rectangle(0, 0, width, height); + this.boundsFull = new Phaser.Rectangle(0, 0, width, height); + this.boundsNone = new Phaser.Rectangle(0, 0, width, height); + + /** + * @property {Phaser.Point} position - + * @readonly + */ + this.positionCustom = new Phaser.Point(0, 0); + this.positionFluid = new Phaser.Point(0, 0); + this.positionFull = new Phaser.Point(0, 0); + this.positionNone = new Phaser.Point(0, 0); + + /** + * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. + * @readonly + */ + this.scaleCustom = new Phaser.Point(1, 1); + this.scaleFluid = new Phaser.Point(1, 1); + this.scaleFluidInversed = new Phaser.Point(1, 1); + this.scaleFull = new Phaser.Point(1, 1); + this.scaleNone = new Phaser.Point(1, 1); + + this.customWidth = 0; + this.customHeight = 0; + this.customOffsetX = 0; + this.customOffsetY = 0; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.multiplier = 0; + + this.layers = []; + +}; + +Phaser.FlexGrid.prototype = { + + /** + * Sets the core game size. This resets the w/h parameters and bounds. + * + * @method Phaser.FlexGrid#setSize + * @param {number} width - The new dimensions. + * @param {number} height - The new dimensions. + */ + setSize: function (width, height) { + + // These are locked and don't change until setSize is called again + this.width = width; + this.height = height; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.scaleNone = new Phaser.Point(1, 1); + + this.boundsNone.width = this.width; + this.boundsNone.height = this.height; + + this.refresh(); + + }, + + // Need ability to create your own layers with custom scaling, etc. + + /** + * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createCustomLayer + * @param {number} width - Width of this layer in pixels. + * @param {number} height - Height of this layer in pixels. + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createCustomLayer: function (width, height, children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + this.customWidth = width; + this.customHeight = height; + + this.boundsCustom.width = width; + this.boundsCustom.height = height; + + var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createFluidLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFluidLayer: function (children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios. + * + * @method Phaser.FlexGrid#createFullLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFullLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled. + * + * @method Phaser.FlexGrid#createFixedLayer + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFixedLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * Resets the layer children references + * + * @method Phaser.FlexGrid#reset + */ + reset: function () { + + var i = this.layers.length; + + while (i--) + { + if (!this.layers[i].persist) + { + // Remove references to this class + this.layers[i].position = null; + this.layers[i].scale = null; + this.layers.slice(i, 1); + } + } + + }, + + /** + * Called when the game container changes dimensions. + * + * @method Phaser.FlexGrid#onResize + * @param {number} width - The new width of the game container. + * @param {number} height - The new height of the game container. + */ + onResize: function (width, height) { + + this.ratioH = width / height; + this.ratioV = height / width; + + this.refresh(width, height); + + }, + + /** + * Updates all internal vars such as the bounds and scale values. + * + * @method Phaser.FlexGrid#refresh + */ + refresh: function () { + + this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width)); + + this.boundsFluid.width = Math.round(this.width * this.multiplier); + this.boundsFluid.height = Math.round(this.height * this.multiplier); + + this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height); + this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height); + + this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height); + + this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x); + this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y); + + this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + + this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y); + this.positionNone.set(this.boundsNone.x, this.boundsNone.y); + + }, + + /** + * Fits a sprites width to the bounds. + * + * @method Phaser.FlexGrid#fitSprite + * @param {Phaser.Sprite} sprite - The Sprite to fit. + */ + fitSprite: function (sprite) { + + this.manager.scaleSprite(sprite); + + sprite.x = this.manager.bounds.centerX; + sprite.y = this.manager.bounds.centerY; + + }, + + /** + * Call in the render function to output the bounds rects. + * + * @method Phaser.FlexGrid#debug + */ + debug: function () { + + // for (var i = 0; i < this.layers.length; i++) + // { + // this.layers[i].debug(); + // } + + // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16); + // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false); + + this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16); + this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false); + + // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16); + // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false); + + // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16); + // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false); + + } + +}; + +Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* A responsive grid layer. +* +* @class Phaser.FlexLayer +* @extends Phaser.Group +* @constructor +* @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer. +* @param {Phaser.Point} position - A reference to the Point object used for positioning. +* @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds. +* @param {Phaser.Point} scale - A reference to the Point object used for layer scaling. +*/ +Phaser.FlexLayer = function (manager, position, bounds, scale) { + + Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false); + + /** + * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager. + */ + this.manager = manager.manager; + + /** + * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer. + */ + this.grid = manager; + + /** + * Should the FlexLayer remain through a State swap? + * + * @type {boolean} + */ + this.persist = false; + + /** + * @property {Phaser.Point} position + */ + this.position = position; + + /** + * @property {Phaser.Rectangle} bounds + */ + this.bounds = bounds; + + /** + * @property {Phaser.Point} scale + */ + this.scale = scale; + + /** + * @property {Phaser.Point} topLeft + */ + this.topLeft = bounds.topLeft; + + /** + * @property {Phaser.Point} topMiddle + */ + this.topMiddle = new Phaser.Point(bounds.halfWidth, 0); + + /** + * @property {Phaser.Point} topRight + */ + this.topRight = bounds.topRight; + + /** + * @property {Phaser.Point} bottomLeft + */ + this.bottomLeft = bounds.bottomLeft; + + /** + * @property {Phaser.Point} bottomMiddle + */ + this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom); + + /** + * @property {Phaser.Point} bottomRight + */ + this.bottomRight = bounds.bottomRight; + +}; + +Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype); +Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer; + +/** + * Resize. + * + * @method Phaser.FlexLayer#resize + */ +Phaser.FlexLayer.prototype.resize = function () { +}; + +/** + * Debug. + * + * @method Phaser.FlexLayer#debug + */ +Phaser.FlexLayer.prototype.debug = function () { + + this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16); + this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false); + + this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9'); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. +* +* @class Phaser.Color +*/ +Phaser.Color = { + + /** + * Red (0xff0000) + * + * @type number + * @constant + * @default + */ + RED: 0xff0000, + + /** + * Orange (0xff9900) + * + * @type number + * @constant + * @default + */ + ORANGE: 0xff9900, + + /** + * Yellow (0xffff00) + * + * @type number + * @constant + * @default + */ + YELLOW: 0xffff00, + + /** + * Green (0x00ff00) + * + * @type number + * @constant + * @default + */ + GREEN: 0x00ff00, + + /** + * Aqua (0x00ffff) + * + * @type number + * @constant + * @default + */ + AQUA: 0x00ffff, + + /** + * Blue (0x0000ff) + * + * @type number + * @constant + * @default + */ + BLUE: 0x0000ff, + + /** + * Violet/purple (0xff00ff) + * + * @type number + * @constant + * @default + */ + VIOLET: 0xff00ff, + + /** + * White (0xffffff) + * + * @type number + * @constant + * @default + */ + WHITE: 0xffffff, + + /** + * Black (0x000000) + * + * @type number + * @constant + * @default + */ + BLACK: 0, + + /** + * Gray (0x666666) + * + * @type number + * @constant + * @default + */ + GRAY: 0x666666, + + /** + * Packs the r, g, b, a components into a single integer, for use with Int32Array. + * If device is little endian then ABGR order is used. Otherwise RGBA order is used. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.packPixel + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} The packed color as uint32 + */ + packPixel: function (r, g, b, a) { + + if (Phaser.Device.LITTLE_ENDIAN) + { + return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0; + } + else + { + return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0; + } + + }, + + /** + * Unpacks the r, g, b, a components into the specified color object, or a new + * object, for use with Int32Array. If little endian, then ABGR order is used when + * unpacking, otherwise, RGBA order is used. The resulting color object has the + * `r, g, b, a` properties which are unrelated to endianness. + * + * Note that the integer is assumed to be packed in the correct endianness. On little-endian + * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a + * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.unpackPixel + * @static + * @param {number} rgba - The integer, packed in endian order by packPixel. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + unpackPixel: function (rgba, out, hsl, hsv) { + + if (out === undefined || out === null) { out = Phaser.Color.createColor(); } + if (hsl === undefined || hsl === null) { hsl = false; } + if (hsv === undefined || hsv === null) { hsv = false; } + + if (Phaser.Device.LITTLE_ENDIAN) + { + out.a = ((rgba & 0xff000000) >>> 24); + out.b = ((rgba & 0x00ff0000) >>> 16); + out.g = ((rgba & 0x0000ff00) >>> 8); + out.r = ((rgba & 0x000000ff)); + } + else + { + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + } + + 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; + + }, + + /** + * A utility to convert an integer in 0xRRGGBBAA format to a color object. + * This does not rely on endianness. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.fromRGBA + * @static + * @param {number} rgba - An RGBA hex + * @param {object} [out] - The object to use, optional. + * @return {object} A color object. + */ + fromRGBA: function (rgba, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + + out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')'; + + return out; + + }, + + /** + * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.toRGBA + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toRGBA: function (r, g, b, a) { + + return (r << 24) | (g << 16) | (b << 8) | a; + + }, + + /** + * Converts RGBA components to a 32 bit integer in AABBGGRR format. + * + * @method Phaser.Color.toABGR + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toABGR: function (r, g, b, a) { + + return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; + + }, + + /** + * Converts a hex color value to an [R, G, B] array. + * + * @static + * @method Phaser.Color.hexToRGBArray + * @param {number} color - The color to convert to an RGB array. In the format 0xRRGGBB. + * @return {array} An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + */ + hexToRGBArray: function (color) { + + return [ + (color >> 16 & 0xFF) / 255, + (color >> 8 & 0xFF) / 255, + (color & 0xFF) / 255 + ]; + + }, + + /** + * Converts an RGB color array, in the format: [R, G, B], to a hex color value. + * + * @static + * @method Phaser.Color.RGBArrayToHex + * @param {array} rgb - An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + * @return {number} The color value, in the format 0xRRGGBB. + */ + RGBArrayToHex: function (rgb) { + + return ((rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255); + + }, + + /** + * Converts an RGB color value to HSL (hue, saturation and lightness). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSL + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. + */ + 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); + + // achromatic by default + out.h = 0; + out.s = 0; + out.l = (max + min) / 2; + + if (max !== min) + { + var d = max - min; + + out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min); + + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSL (hue, saturation and lightness) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSLtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} l - The lightness, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSLtoRGB: function (h, s, l, out) { + + if (!out) + { + out = Phaser.Color.createColor(l, l, l); + } + else + { + // achromatic by default + out.r = l; + out.g = l; + out.b = l; + } + + if (s !== 0) + { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3); + out.g = Phaser.Color.hueToColor(p, q, h); + out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3); + } + + // out.r = (out.r * 255 | 0); + // out.g = (out.g * 255 | 0); + // out.b = (out.b * 255 | 0); + + out.r = Math.floor((out.r * 255 | 0)); + out.g = Math.floor((out.g * 255 | 0)); + out.b = Math.floor((out.b * 255 | 0)); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts an RGB color value to HSV (hue, saturation and value). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSV + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and value set in the h, s and v properties. + */ + RGBtoHSV: function (r, g, b, out) { + + if (!out) + { + out = Phaser.Color.createColor(r, g, b, 255); + } + + r /= 255; + g /= 255; + b /= 255; + + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var d = max - min; + + // achromatic by default + out.h = 0; + out.s = max === 0 ? 0 : d / max; + out.v = max; + + if (max !== min) + { + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSVtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} v - The value, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSVtoRGB: function (h, s, v, out) { + + if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); } + + var r, g, b; + var i = Math.floor(h * 6); + var f = h * 6 - i; + var p = v * (1 - s); + var q = v * (1 - f * s); + var t = v * (1 - (1 - f) * s); + + switch (i % 6) + { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } + + out.r = Math.floor(r * 255); + out.g = Math.floor(g * 255); + out.b = Math.floor(b * 255); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.hueToColor + * @static + * @param {number} p + * @param {number} q + * @param {number} t + * @return {number} The color component value. + */ + hueToColor: function (p, q, t) { + + if (t < 0) + { + t += 1; + } + + if (t > 1) + { + t -= 1; + } + + if (t < 1 / 6) + { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) + { + return q; + } + + if (t < 2 / 3) + { + return p + (q - p) * (2 / 3 - t) * 6; + } + + return p; + + }, + + /** + * A utility function to create a lightweight 'color' object with the default components. + * Any components that are not specified will default to zero. + * + * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.createColor + * @static + * @param {number} [r=0] - The red color component, in the range 0 - 255. + * @param {number} [g=0] - The green color component, in the range 0 - 255. + * @param {number} [b=0] - The blue color component, in the range 0 - 255. + * @param {number} [a=1] - The alpha color component, in the range 0 - 1. + * @param {number} [h=0] - The hue, in the range 0 - 1. + * @param {number} [s=0] - The saturation, in the range 0 - 1. + * @param {number} [l=0] - The lightness, in the range 0 - 1. + * @param {number} [v=0] - The value, in the range 0 - 1. + * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. + */ + 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, color32: 0, rgba: '' }; + + return Phaser.Color.updateColor(out); + + }, + + /** + * Takes a color object and updates the rgba, color and color32 properties. + * + * @method Phaser.Color.updateColor + * @static + * @param {object} out - The color object to update. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + updateColor: function (out) { + + out.rgba = 'rgba(' + out.r.toFixed() + ',' + out.g.toFixed() + ',' + out.b.toFixed() + ',' + out.a.toString() + ')'; + out.color = Phaser.Color.getColor(out.r, out.g, out.b); + out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b); + + return out; + + }, + + /** + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor32 + * @static + * @param {number} a - The alpha color component, in the range 0 - 255. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + getColor32: function (a, r, g, b) { + + return a << 24 | r << 16 | g << 8 | b; + + }, + + /** + * Given 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xRRGGBB). + */ + getColor: function (r, g, b) { + + return r << 16 | g << 8 | b; + + }, + + /** + * Converts the given color values into a string. + * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + * + * @method Phaser.Color.RGBtoString + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255. + * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. + * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + */ + RGBtoString: function (r, g, b, a, prefix) { + + if (a === undefined) { a = 255; } + if (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); + } + + }, + + /** + * Converts a hex string into an integer color value. + * + * @method Phaser.Color.hexToRGB + * @static + * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. + * @return {number} The rgb color value in the format 0xAARRGGBB. + */ + hexToRGB: function (hex) { + + var rgb = Phaser.Color.hexToColor(hex); + + if (rgb) + { + return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b); + } + + }, + + /** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @method Phaser.Color.hexToColor + * @static + * @param {string} hex - The color string in a hex format. + * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + hexToColor: function (hex, out) { + + // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") + hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { + return r + r + g + g + b + b; + }); + + var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + + if (result) + { + var r = parseInt(result[1], 16); + var g = parseInt(result[2], 16); + var b = parseInt(result[3], 16); + + if (!out) + { + out = Phaser.Color.createColor(r, g, b); + } + else + { + out.r = r; + out.g = g; + out.b = b; + } + } + + return out; + + }, + + /** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @method Phaser.Color.webToColor + * @static + * @param {string} web - The color string in CSS 'web' format. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + webToColor: function (web, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web); + + if (result) + { + out.r = ~~Number(result[1]); + out.g = ~~Number(result[2]); + out.b = ~~Number(result[3]); + out.a = result[4] !== undefined ? Number(result[4]) : 1; + Phaser.Color.updateColor(out); + } + + return out; + + }, + + /** + * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. + * + * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). + * + * An alpha channel is _not_ supported when specifying a hex string. + * + * @method Phaser.Color.valueToColor + * @static + * @param {string|number} value - The color expressed as a recognized string format or a packed integer. + * @param {object} [out] - The object to use for the output. If not provided a new object will be created. + * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. + */ + valueToColor: function (value, out) { + + // The behavior is not consistent between hexToColor/webToColor on invalid input. + // This unifies both by returning a new object, but returning null may be better. + if (!out) + { + out = Phaser.Color.createColor(); + } + + if (typeof value === 'string') + { + if (value.indexOf('rgb') === 0) + { + return Phaser.Color.webToColor(value, out); + } + else + { + // `hexToColor` does not support alpha; match `createColor`. + out.a = 1; + return Phaser.Color.hexToColor(value, out); + } + } + else if (typeof value === 'number') + { + // `getRGB` does not take optional object to modify; + // alpha is also adjusted to match `createColor`. + var tempColor = Phaser.Color.getRGB(value); + out.r = tempColor.r; + out.g = tempColor.g; + out.b = tempColor.b; + out.a = tempColor.a / 255; + return out; + } + else + { + return out; + } + + }, + + /** + * Return a string containing a hex representation of the given color component. + * + * @method Phaser.Color.componentToHex + * @static + * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. + * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ + componentToHex: function (color) { + + var hex = color.toString(16); + + return (hex.length === 1) ? '0' + hex : hex; + + }, + + /** + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSVColorWheel + * @static + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSV color wheel. + */ + HSVColorWheel: function (s, v) { + + if (s === undefined) { s = 1.0; } + if (v === undefined) { v = 1.0; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v)); + } + + return colors; + + }, + + /** + * Get HSL color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSLColorWheel + * @static + * @param {number} [s=0.5] - The saturation, in the range 0 - 1. + * @param {number} [l=0.5] - The lightness, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSL color wheel. + */ + HSLColorWheel: function (s, l) { + + if (s === undefined) { s = 0.5; } + if (l === undefined) { l = 0.5; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l)); + } + + return colors; + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColor + * @static + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @param {number} [alpha] - The alpha of the returned color. + * @param {number} [colorSpace=0] - The color space to interpolate in. 0 = RGB, 1 = HSV. + * @returns {number} The interpolated color value. + */ + interpolateColor: function (color1, color2, steps, currentStep, alpha, colorSpace) { + + if (alpha === undefined) { alpha = 255; } + if (colorSpace === undefined) { colorSpace = 0; } + + var src1 = Phaser.Color.getRGB(color1); + var src2 = Phaser.Color.getRGB(color2); + + if (colorSpace === 0) + { + 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; + } + + if (colorSpace === 1) + { + var hsv1 = Phaser.Color.RGBtoHSV(src1.r, src1.g, src1.b); + var hsv2 = Phaser.Color.RGBtoHSV(src2.r, src2.g, src2.b); + var dh = hsv2.h - hsv1.h; + var h; + + if (hsv1.h > hsv2.h) + { + var h3 = hsv2.h; + hsv2.h = hsv1.h; + hsv1.h = h3; + dh = -dh; + currentStep = steps - currentStep; + } + + if (dh > 0.5) + { + hsv1.h = hsv1.h + 1; + h = (((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h) % 1; + } + + if (dh <= 0.5) + { + h = ((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h; + } + + var s = (((hsv2.s - hsv1.s) * currentStep) / steps) + hsv1.s; + var v = (((hsv2.v - hsv1.v) * currentStep) / steps) + hsv1.v; + + var rgb = Phaser.Color.HSVtoRGB(h, s, v, rgb); + var r = rgb.r; + var g = rgb.g; + var b = rgb.b; + } + + return Phaser.Color.getColor32(alpha, r, g, b); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColorWithRGB + * @static + * @param {number} color - The first color value. + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * @method Phaser.Color.interpolateRGB + * @static + * @param {number} r1 - The red color value, between 0 and 0xFF (255). + * @param {number} g1 - The green color value, between 0 and 0xFF (255). + * @param {number} b1 - The blue color value, between 0 and 0xFF (255). + * @param {number} r2 - The red color value, between 0 and 0xFF (255). + * @param {number} g2 - The green color value, between 0 and 0xFF (255). + * @param {number} b2 - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + + /** + * Calculates a linear (interpolation) value of two colors over t. + * + * This is a slightly simpler interface to {@link Phaser.Color.interpolateColor}. + * + * The arguments are similar to {@link Phaser.Math.linear}. + * + * @method Phaser.Color.linear + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linear: function (color1, color2, t) { + + return this.interpolateColor(color1, color2, 1, t); + + }, + + /** + * Calculates a linear (interpolation) value of an array of colors over t. + * + * The arguments are similar to {@link Phaser.Math.linearInterpolation}. + * + * This can be used as a {@link Phaser.TweenData#interpolationFunction}. + * + * @method Phaser.Color.linearInterpolation + * @param {number[]} colors - The input array of color values to interpolate between. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linearInterpolation: function (colors, t) { + + var k = Phaser.Math.linear(0, colors.length - 1, t); + var color1 = colors[ Math.floor(k) ]; + var color2 = colors[ Math.ceil(k)] ; + + return this.linear(color1, color2, k % 1); + + }, + + /** + * Returns a random color value between black and white + * Set the min value to start each channel from the given offset. + * Set the max value to restrict the maximum color used per channel. + * + * @method Phaser.Color.getRandomColor + * @static + * @param {number} [min=0] - The lowest value to use for the color. + * @param {number} [max=255] - The highest value to use for the color. + * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). + * @returns {number} 32-bit color value with alpha. + */ + getRandomColor: function (min, max, alpha) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + if (alpha === undefined) { alpha = 255; } + + // Sanity checks + 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); + + }, + + /** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exist in the given color (0xAARRGGBB) + * + * @method Phaser.Color.getRGB + * @static + * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). + * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. + */ + getRGB: function (color) { + + if (color > 16777215) + { + // The color value has an alpha component + return { + alpha: color >>> 24, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: color >>> 24, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + else + { + return { + alpha: 255, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: 255, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + + }, + + /** + * Returns a CSS friendly string value from the given color. + * + * @method Phaser.Color.getWebRGB + * @static + * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. + * @returns {string} A string in the format: 'rgba(r,g,b,a)' + */ + getWebRGB: function (color) { + + if (typeof color === 'object') + { + return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')'; + } + else + { + var rgb = Phaser.Color.getRGB(color); + return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')'; + } + + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. + * + * @method Phaser.Color.getAlpha + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlpha: function (color) { + return color >>> 24; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. + * + * @method Phaser.Color.getAlphaFloat + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlphaFloat: function (color) { + return (color >>> 24) / 255; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. + * + * @method Phaser.Color.getRed + * @static + * @param {number} color In the format 0xAARRGGBB. + * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). + */ + getRed: function (color) { + return color >> 16 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. + * + * @method Phaser.Color.getGreen + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). + */ + getGreen: function (color) { + return color >> 8 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. + * + * @method Phaser.Color.getBlue + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). + */ + getBlue: function (color) { + return color & 0xFF; + }, + + /** + * Blends the source color, ignoring the backdrop. + * + * @method Phaser.Color.blendNormal + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNormal: function (a) { + return a; + }, + + /** + * Selects the lighter of the backdrop and source colors. + * + * @method Phaser.Color.blendLighten + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLighten: function (a, b) { + return (b > a) ? b : a; + }, + + /** + * Selects the darker of the backdrop and source colors. + * + * @method Phaser.Color.blendDarken + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDarken: function (a, b) { + return (b > a) ? a : b; + }, + + /** + * Multiplies the backdrop and source color values. + * The result color is always at least as dark as either of the two constituent + * colors. Multiplying any color with black produces black; + * multiplying with white leaves the original color unchanged. + * + * @method Phaser.Color.blendMultiply + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendMultiply: function (a, b) { + return (a * b) / 255; + }, + + /** + * Takes the average of the source and backdrop colors. + * + * @method Phaser.Color.blendAverage + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAverage: function (a, b) { + return (a + b) / 2; + }, + + /** + * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. + * + * @method Phaser.Color.blendAdd + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAdd: function (a, b) { + return Math.min(255, a + b); + }, + + /** + * Combines the source and backdrop colors and returns their value minus 255. + * + * @method Phaser.Color.blendSubtract + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSubtract: function (a, b) { + return Math.max(0, a + b - 255); + }, + + /** + * Subtracts the darker of the two constituent colors from the lighter. + * + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendDifference + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDifference: function (a, b) { + return Math.abs(a - b); + }, + + /** + * Negation blend mode. + * + * @method Phaser.Color.blendNegation + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNegation: function (a, b) { + return 255 - Math.abs(255 - a - b); + }, + + /** + * Multiplies the complements of the backdrop and source color values, then complements the result. + * The result color is always at least as light as either of the two constituent colors. + * Screening any color with white produces white; screening with black leaves the original color unchanged. + * + * @method Phaser.Color.blendScreen + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendScreen: function (a, b) { + return 255 - (((255 - a) * (255 - b)) >> 8); + }, + + /** + * Produces an effect similar to that of the Difference mode, but lower in contrast. + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendExclusion + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendExclusion: function (a, b) { + return a + b - 2 * a * b / 255; + }, + + /** + * Multiplies or screens the colors, depending on the backdrop color. + * Source colors overlay the backdrop while preserving its highlights and shadows. + * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. + * + * @method Phaser.Color.blendOverlay + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendOverlay: function (a, b) { + return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255); + }, + + /** + * Darkens or lightens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. + * The effect is similar to shining a diffused spotlight on the backdrop. + * + * @method Phaser.Color.blendSoftLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSoftLight: function (a, b) { + return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255); + }, + + /** + * Multiplies or screens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; + * this is useful for adding shadows to a scene. + * + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. + * + * @method Phaser.Color.blendHardLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardLight: function (a, b) { + return Phaser.Color.blendOverlay(b, a); + }, + + /** + * Brightens the backdrop color to reflect the source color. + * Painting with black produces no change. + * + * @method Phaser.Color.blendColorDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorDodge: function (a, b) { + return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b))); + }, + + /** + * Darkens the backdrop color to reflect the source color. + * Painting with white produces no change. + * + * @method Phaser.Color.blendColorBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorBurn: function (a, b) { + return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b)); + }, + + /** + * An alias for blendAdd, it simply sums the values of the two colors. + * + * @method Phaser.Color.blendLinearDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearDodge: function (a, b) { + return Phaser.Color.blendAdd(a, b); + }, + + /** + * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. + * + * @method Phaser.Color.blendLinearBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearBurn: function (a, b) { + return Phaser.Color.blendSubtract(a, b); + }, + + /** + * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). + * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. + * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. + * + * @method Phaser.Color.blendLinearLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearLight: function (a, b) { + return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128))); + }, + + /** + * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). + * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. + * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom + * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. + * + * @method Phaser.Color.blendVividLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendVividLight: function (a, b) { + return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128))); + }, + + /** + * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. + * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. + * + * @method Phaser.Color.blendPinLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPinLight: function (a, b) { + return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128))); + }, + + /** + * Runs blendVividLight on the source and backdrop colors. + * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. + * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. + * This changes all pixels to primary additive colors (red, green, or blue), white, or black. + * + * @method Phaser.Color.blendHardMix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardMix: function (a, b) { + return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255; + }, + + /** + * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. + * + * @method Phaser.Color.blendReflect + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendReflect: function (a, b) { + return b === 255 ? b : Math.min(255, (a * a / (255 - b))); + }, + + /** + * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. + * + * @method Phaser.Color.blendGlow + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendGlow: function (a, b) { + return Phaser.Color.blendReflect(b, a); + }, + + /** + * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. + * + * @method Phaser.Color.blendPhoenix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPhoenix: function (a, b) { + return Math.min(a, b) - Math.max(a, b) + 255; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Manager is responsible for looking after all of the running physics systems. +* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. +* +* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. +* +* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the +* faster (due to being much simpler) Arcade Physics system. +* +* @class Phaser.Physics +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Physics = function (game, config) { + + config = config || {}; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} config - The physics configuration object as passed to the game on creation. + */ + this.config = config; + + /** + * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. + */ + this.arcade = null; + + /** + * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. + */ + this.p2 = null; + + /** + * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. + */ + this.ninja = null; + + /** + * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. + */ + this.box2d = null; + + /** + * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). + */ + this.chipmunk = null; + + /** + * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). + */ + this.matter = null; + + this.parseConfig(); + +}; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.ARCADE = 0; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.P2JS = 1; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.NINJA = 2; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.BOX2D = 3; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.CHIPMUNK = 4; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.MATTERJS = 5; + +Phaser.Physics.prototype = { + + /** + * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. + * + * @method Phaser.Physics#parseConfig + */ + parseConfig: function () { + + if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade')) + { + // If Arcade isn't specified, we create it automatically if we can + this.arcade = new Phaser.Physics.Arcade(this.game); + } + + 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); + } + + if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D')) + { + this.box2d = new Phaser.Physics.BOX2D(this.game, this.config); + } + + if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter')) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + + }, + + /** + * This will create an instance of the requested physics simulation. + * Phaser.Physics.Arcade is running by default, but all others need activating directly. + * + * You can start the following physics systems: + * + * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. + * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) + * + * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. + * They are not bundled into the core Phaser library. + * + * If the physics world has already been created (i.e. in another state in your game) then + * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors + * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. + * + * @method Phaser.Physics#startSystem + * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. + */ + startSystem: function (system) { + + if (system === Phaser.Physics.ARCADE) + { + this.arcade = new Phaser.Physics.Arcade(this.game); + } + else if (system === Phaser.Physics.P2JS) + { + if (this.p2 === null) + { + this.p2 = new Phaser.Physics.P2(this.game, this.config); + } + else + { + this.p2.reset(); + } + } + else if (system === Phaser.Physics.NINJA) + { + this.ninja = new Phaser.Physics.Ninja(this.game); + } + else if (system === Phaser.Physics.BOX2D) + { + if (this.box2d === null) + { + this.box2d = new Phaser.Physics.Box2D(this.game, this.config); + } + else + { + this.box2d.reset(); + } + } + else if (system === Phaser.Physics.MATTERJS) + { + if (this.matter === null) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + else + { + this.matter.reset(); + } + } + + }, + + /** + * This will create a default physics body on the given game object or array of objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * It can be for any of the physics systems that have been started: + * + * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. + * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. + * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 + * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) + * Phaser.Physics.CHIPMUNK is still in development. + * + * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the + * individual physics systems `enable` methods instead of using this generic one. + * + * @method Phaser.Physics#enable + * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. + * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. + * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. + */ + enable: function (object, system, debug) { + + if (system === undefined) { system = Phaser.Physics.ARCADE; } + if (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); + } + else if (system === Phaser.Physics.BOX2D && this.box2d) + { + this.box2d.enable(object); + } + else if (system === Phaser.Physics.MATTERJS && this.matter) + { + this.matter.enable(object); + } + else + { + console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.'); + } + + }, + + /** + * preUpdate checks. + * + * @method Phaser.Physics#preUpdate + * @protected + */ + preUpdate: function () { + + // ArcadePhysics / Ninja don't have a core to preUpdate + + if (this.p2) + { + this.p2.preUpdate(); + } + + if (this.box2d) + { + this.box2d.preUpdate(); + } + + if (this.matter) + { + this.matter.preUpdate(); + } + + }, + + /** + * Updates all running physics systems. + * + * @method Phaser.Physics#update + * @protected + */ + update: function () { + + // ArcadePhysics / Ninja don't have a core to update + + if (this.p2) + { + this.p2.update(); + } + + if (this.box2d) + { + this.box2d.update(); + } + + if (this.matter) + { + this.matter.update(); + } + + }, + + /** + * Updates the physics bounds to match the world dimensions. + * + * @method Phaser.Physics#setBoundsToWorld + * @protected + */ + setBoundsToWorld: function () { + + if (this.arcade) + { + this.arcade.setBoundsToWorld(); + } + + if (this.ninja) + { + this.ninja.setBoundsToWorld(); + } + + if (this.p2) + { + this.p2.setBoundsToWorld(); + } + + if (this.box2d) + { + this.box2d.setBoundsToWorld(); + } + + if (this.matter) + { + this.matter.setBoundsToWorld(); + } + + }, + + /** + * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. + * + * @method Phaser.Physics#clear + * @protected + */ + clear: function () { + + if (this.p2) + { + this.p2.clear(); + } + + if (this.box2d) + { + this.box2d.clear(); + } + + if (this.matter) + { + this.matter.clear(); + } + + }, + + /** + * Resets the active physics system. Called automatically on a Phaser.State swap. + * + * @method Phaser.Physics#reset + * @protected + */ + reset: function () { + + if (this.p2) + { + this.p2.reset(); + } + + if (this.box2d) + { + this.box2d.reset(); + } + + if (this.matter) + { + this.matter.reset(); + } + + }, + + /** + * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. + * + * @method Phaser.Physics#destroy + */ + destroy: function () { + + if (this.p2) + { + this.p2.destroy(); + } + + if (this.box2d) + { + this.box2d.destroy(); + } + + if (this.matter) + { + this.matter.destroy(); + } + + this.arcade = null; + this.ninja = null; + this.p2 = null; + this.box2d = null; + this.matter = null; + + } + +}; + +Phaser.Physics.prototype.constructor = Phaser.Physics; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. +* +* @class Phaser.Physics.Arcade +* @constructor +* @param {Phaser.Game} game - reference to the current game instance. +*/ +Phaser.Physics.Arcade = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height); + + /** + * Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`. + * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. + * @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right). + */ + this.checkCollision = { up: true, down: true, left: true, right: true }; + + /** + * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. + */ + this.maxLevels = 4; + + /** + * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. + * @default + */ + this.OVERLAP_BIAS = 4; + + /** + * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. + */ + this.forceX = false; + + /** + * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT. + * @default + */ + this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT; + + /** + * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. + */ + this.skipQuadTree = true; + + /** + * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. + */ + this.isPaused = false; + + /** + * @property {Phaser.QuadTree} quadTree - The world QuadTree. + */ + 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); + + /** + * @property {number} _total - Internal cache var. + * @private + */ + this._total = 0; + + // By default we want the bounds the same size as the world bounds + this.setBoundsToWorld(); + +}; + +Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade; + +/** +* A constant used for the sortDirection value. +* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.SORT_NONE = 0; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.LEFT_RIGHT = 1; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.RIGHT_LEFT = 2; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.TOP_BOTTOM = 3; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.BOTTOM_TOP = 4; + +Phaser.Physics.Arcade.prototype = { + + /** + * Updates the size of this physics world. + * + * @method Phaser.Physics.Arcade#setBounds + * @param {number} x - Top left most corner of the world. + * @param {number} y - Top left most corner of the world. + * @param {number} width - New width of the world. Can never be smaller than the Game.width. + * @param {number} height - New height of the world. Can never be smaller than the Game.height. + */ + setBounds: function (x, y, width, height) { + + this.bounds.setTo(x, y, width, height); + + }, + + /** + * Updates the size of this physics world to match the size of the game world. + * + * @method Phaser.Physics.Arcade#setBoundsToWorld + */ + setBoundsToWorld: function () { + + this.bounds.copyFrom(this.game.world.bounds); + + }, + + /** + * This will create an Arcade Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * + * @method Phaser.Physics.Arcade#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, children) { + + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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) + { + // If it's a Group then we do it on the children regardless + this.enable(object.children, children); + } + else + { + this.enableBody(object); + + if (children && object.hasOwnProperty('children') && object.children.length > 0) + { + this.enable(object.children, true); + } + } + } + + }, + + /** + * Creates an Arcade Physics body on the given game object. + * + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. + * + * @method Phaser.Physics.Arcade#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + */ + enableBody: function (object) { + + if (object.hasOwnProperty('body') && object.body === null) + { + object.body = new Phaser.Physics.Arcade.Body(object); + + if (object.parent && object.parent instanceof Phaser.Group) + { + object.parent.addToHash(object); + } + } + + }, + + /** + * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. + * + * @method Phaser.Physics.Arcade#updateMotion + * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. + */ + updateMotion: function (body) { + + if (body.allowRotation) + { + var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity; + body.angularVelocity += 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); + + }, + + /** + * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * Based on a function in Flixel by @ADAMATOMIC + * + * @method Phaser.Physics.Arcade#computeVelocity + * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical. + * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. + * @param {number} velocity - Any component of velocity (e.g. 20). + * @param {number} acceleration - Rate at which the velocity is changing. + * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. + * @param {number} [max=10000] - An absolute value cap for the velocity. + * @return {number} The altered Velocity value. + */ + computeVelocity: function (axis, body, velocity, acceleration, drag, max) { + + if (max === undefined) { max = 10000; } + + 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 && body.allowDrag) + { + drag *= this.game.time.physicsElapsed; + + if (velocity - drag > 0) + { + velocity -= drag; + } + else if (velocity + drag < 0) + { + velocity += drag; + } + else + { + velocity = 0; + } + } + + if (velocity > max) + { + velocity = max; + } + else if (velocity < -max) + { + velocity = -max; + } + + return velocity; + + }, + + /** + * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. + * + * Unlike {@link #collide} the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. + * Both the first and second parameter can be arrays of objects, of differing types. + * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups within Groups). + * + * ##### Tilemaps + * + * Any overlapping tiles, including blank/null tiles, will give a positive result. Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) have no special status, and callbacks added via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} are not invoked. So calling this method without any callbacks isn't very useful. + * + * If you're interested only in whether an object overlaps a certain tile or class of tiles, filter the tiles with `processCallback` and then use the result returned by this method. Blank/null tiles can be excluded by their {@link Phaser.Tile#index index} (-1). + * + * If you want to take action on certain overlaps, examine the tiles in `collideCallback` and then handle as you like. + * + * @method Phaser.Physics.Arcade#overlap + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if an overlap occurred otherwise false. + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) { + + overlapCallback = overlapCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || overlapCallback; + + this._total = 0; + + this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + + return (this._total > 0); + + }, + + /** + * Checks for collision between two game objects and separates them if colliding ({@link https://gist.github.com/samme/cbb81dd19f564dcfe2232761e575063d details}). If you don't require separation then use {@link #overlap} instead. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. + * Both the `object1` and `object2` can be arrays of objects, of differing types. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If one Group **only** is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If either object is `null` the collision test will fail. + * + * Bodies with `enable = false` and Sprites with `exists = false` are skipped (ignored). + * + * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. + * + * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). + * + * ##### Examples + * + * ```javascript + * collide(group); + * collide(group, undefined); // equivalent + * + * collide(sprite1, sprite2); + * + * collide(sprite, group); + * + * collide(group1, group2); + * + * collide([sprite1, sprite2], [sprite3, sprite4]); // 1 vs. 3, 1 vs. 4, 2 vs. 3, 2 vs. 4 + * ``` + * + * ##### Tilemaps + * + * Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) are "solid". If a Sprite collides with one of these tiles, the two are separated by moving the Sprite outside the tile's edges. Enable {@link Phaser.TilemapLayer#debug} to see the colliding edges of the Tilemap. + * + * Tiles with a callback attached via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} invoke the callback if a Sprite collides with them. If a tile has a callback attached via both methods, only the location callback is invoked. The colliding Sprite is separated from the tile only if the callback returns `true`. + * + * @method Phaser.Physics.Arcade#collide + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. + * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if a collision occurred otherwise false. + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) { + + collideCallback = collideCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || collideCallback; + + this._total = 0; + + this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + + return (this._total > 0); + + }, + + /** + * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortLeftRight + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortLeftRight: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.x - b.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortRightLeft + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortRightLeft: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.x - a.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortTopBottom + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortTopBottom: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.y - b.body.y; + + }, + + /** + * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortBottomTop + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortBottomTop: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.y - a.body.y; + + }, + + /** + * This method will sort a Groups hash array. + * + * If the Group has `physicsSortDirection` set it will use the sort direction defined. + * + * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection. + * + * By changing Group.physicsSortDirection you can customise each Group to sort in a different order. + * + * @method Phaser.Physics.Arcade#sort + * @param {Phaser.Group} group - The Group to sort. + * @param {integer} [sortDirection] - The sort direction used to sort this Group. + */ + sort: function (group, sortDirection) { + + if (group.physicsSortDirection !== null) + { + sortDirection = group.physicsSortDirection; + } + else + { + if (sortDirection === undefined) { sortDirection = this.sortDirection; } + } + + if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + // Game world is say 2000x600 and you start at 0 + group.hash.sort(this.sortLeftRight); + } + else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + // Game world is say 2000x600 and you start at 2000 + group.hash.sort(this.sortRightLeft); + } + else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + // Game world is say 800x2000 and you start at 0 + group.hash.sort(this.sortTopBottom); + } + else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + // Game world is say 800x2000 and you start at 2000 + group.hash.sort(this.sortBottomTop); + } + + }, + + /** + * Internal collision handler. Extracts objects for {@link #collideHandler}. + * + * @method Phaser.Physics.Arcade#collideObjects + * @private + */ + collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object2.length; i++) + { + if (!object2[i]) { continue; } + + this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && !Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + for (var j = 0; j < object2.length; j++) + { + if (!object2[j]) { continue; } + + this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + + }, + + /** + * Internal collision handler. Matches arguments to other handlers. + * + * @method Phaser.Physics.Arcade#collideHandler + * @private + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + // Only collide valid objects + if (object2 === undefined && object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly); + return; + } + + // If neither of the objects are set or exist then bail out + if (!object1 || !object2 || !object1.exists || !object2.exists) + { + return; + } + + // Groups? Sort them + if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE) + { + if (object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + } + + if (object2.physicsType === Phaser.GROUP) + { + this.sort(object2); + } + } + + // SPRITES + if (object1.physicsType === Phaser.SPRITE) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // GROUPS + else if (object1.physicsType === Phaser.GROUP) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // TILEMAP LAYERS + else if (object1.physicsType === Phaser.TILEMAPLAYER) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsSprite + * @private + * @param {Phaser.Sprite} sprite1 - The first sprite to check. + * @param {Phaser.Sprite} sprite2 - The second sprite to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + 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; + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsGroup + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0 || !sprite.body) + { + return; + } + + if (this.skipQuadTree || sprite.body.skipQuadTree) + { + var bounds = {}; + + for (var i = 0; i < group.hash.length; i++) + { + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds object + bounds = object1.body.getBounds(bounds); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (sprite.body.right < bounds.x) + { + break; + } + else if (bounds.right < sprite.body.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (sprite.body.x > bounds.right) + { + break; + } + else if (bounds.x > sprite.body.right) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (sprite.body.bottom < bounds.y) + { + break; + } + else if (bounds.bottom < sprite.body.y) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (sprite.body.y > bounds.bottom) + { + break; + } + else if (bounds.y > sprite.body.bottom) + { + continue; + } + } + + this.collideSpriteVsSprite(sprite, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else + { + // What is the sprite colliding with in the quadtree? + 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 items = this.quadTree.retrieve(sprite); + + for (var i = 0; i < items.length; i++) + { + // We have our potential suspects, are they in this group? + if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, items[i].sprite); + } + + this._total++; + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsSelf + * @private + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.hash.length; i++) + { + var bounds1 = {}; + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds1 object + bounds1 = object1.body.getBounds(bounds1); + + for (var j = i + 1; j < group.hash.length; j++) + { + var bounds2 = {}; + var object2 = group.hash[j]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object2 || !object2.exists || !object2.body) + { + continue; + } + + // Inject the Body bounds data into the bounds2 object + bounds2 = object2.body.getBounds(bounds2); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (bounds1.right < bounds2.x) + { + break; + } + else if (bounds2.right < bounds1.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (bounds1.x > bounds2.right) + { + continue; + } + else if (bounds2.x > bounds1.right) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (bounds1.bottom < bounds2.y) + { + continue; + } + else if (bounds2.bottom < bounds1.y) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (bounds1.y > bounds2.bottom) + { + continue; + } + else if (bounds2.y > object1.body.bottom) + { + break; + } + } + + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsGroup + * @private + * @param {Phaser.Group} group1 - The first Group to check. + * @param {Phaser.Group} group2 - The second Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group1.length === 0 || group2.length === 0) + { + return; + } + + for (var i = 0; i < group1.children.length; i++) + { + if (group1.children[i].exists) + { + if (group1.children[i].physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else + { + this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + + }, + + /** + * The core separation function to separate two physics bodies. + * + * @private + * @method Phaser.Physics.Arcade#separate + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true. + * @param {object} [callbackContext] - The context in which to run the process callback. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} Returns true if the bodies collided, otherwise false. + */ + separate: function (body1, body2, processCallback, callbackContext, overlapOnly) { + + if ( + !body1.enable || + !body2.enable || + body1.checkCollision.none || + body2.checkCollision.none || + !this.intersects(body1, body2)) + { + return false; + } + + // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. + if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false) + { + return false; + } + + // Circle vs. Circle quick bail out + if (body1.isCircle && body2.isCircle) + { + return this.separateCircle(body1, body2, overlapOnly); + } + + // We define the behavior of bodies in a collision circle and rectangle + // If a collision occurs in the corner points of the rectangle, the body behave like circles + + // Either body1 or body2 is a circle + if (body1.isCircle !== body2.isCircle) + { + var bodyRect = (body1.isCircle) ? body2 : body1; + var bodyCircle = (body1.isCircle) ? body1 : body2; + + var rect = { + x: bodyRect.x, + y: bodyRect.y, + right: bodyRect.right, + bottom: bodyRect.bottom + }; + + var circle = bodyCircle.center; + + if (circle.y < rect.y || circle.y > rect.bottom) + { + if (circle.x < rect.x || circle.x > rect.right) + { + return this.separateCircle(body1, body2, overlapOnly); + } + } + } + + var resultX = false; + var resultY = false; + + // Do we separate on x or y first? + if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) + { + resultX = this.separateX(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultY = this.separateY(body1, body2, overlapOnly); + } + } + else + { + resultY = this.separateY(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultX = this.separateX(body1, body2, overlapOnly); + } + } + + var result = (resultX || resultY); + + if (result) + { + if (overlapOnly) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + else + { + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + } + } + + return result; + + }, + + /** + * Check for intersection against two bodies. + * + * @method Phaser.Physics.Arcade#intersects + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check. + * @return {boolean} True if they intersect, otherwise false. + */ + intersects: function (body1, body2) { + + if (body1 === body2) + { + return false; + } + + if (body1.isCircle) + { + if (body2.isCircle) + { + // Circle vs. Circle + return Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); + } + else + { + // Circle vs. Rect + return this.circleBodyIntersects(body1, body2); + } + } + else + { + if (body2.isCircle) + { + // Rect vs. Circle + return this.circleBodyIntersects(body2, body1); + } + else + { + // Rect vs. Rect + if (body1.right <= body2.position.x) + { + return false; + } + + if (body1.bottom <= body2.position.y) + { + return false; + } + + if (body1.position.x >= body2.right) + { + return false; + } + + if (body1.position.y >= body2.bottom) + { + return false; + } + + return true; + } + } + + }, + + /** + * Checks to see if a circular Body intersects with a Rectangular Body. + * + * @method Phaser.Physics.Arcade#circleBodyIntersects + * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set. + * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape) + * @return {boolean} Returns true if the bodies intersect, otherwise false. + */ + circleBodyIntersects: function (circle, body) { + + var x = Phaser.Math.clamp(circle.center.x, body.left, body.right); + var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom); + + var dx = (circle.center.x - x) * (circle.center.x - x); + var dy = (circle.center.y - y) * (circle.center.y - y); + + return (dx + dy) <= (circle.halfWidth * circle.halfWidth); + + }, + + /** + * The core separation function to separate two circular physics bodies. + * + * @method Phaser.Physics.Arcade#separateCircle + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateCircle: function (body1, body2, overlapOnly) { + + // Set the bounding box overlap values + this.getOverlapX(body1, body2); + this.getOverlapY(body1, body2); + + var dx = body2.center.x - body1.center.x; + var dy = body2.center.y - body1.center.y; + + var angleCollision = Math.atan2(dy, dx); + + var overlap = 0; + + if (body1.isCircle !== body2.isCircle) + { + var rect = { + x: (body2.isCircle) ? body1.position.x : body2.position.x, + y: (body2.isCircle) ? body1.position.y : body2.position.y, + right: (body2.isCircle) ? body1.right : body2.right, + bottom: (body2.isCircle) ? body1.bottom : body2.bottom + }; + + var circle = { + x: (body1.isCircle) ? body1.center.x : body2.center.x, + y: (body1.isCircle) ? body1.center.y : body2.center.y, + radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth + }; + + if (circle.y < rect.y) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.y) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.y) - circle.radius; + } + } + else if (circle.y > rect.bottom) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; + } + } + + overlap *= -1; + } + else + { + overlap = (body1.halfWidth + body2.halfWidth) - Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y); + } + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + if (overlap !== 0) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + + // return true if there was some overlap, otherwise false + return (overlap !== 0); + } + + // Transform the velocity vector to the coordinate system oriented along the direction of impact. + // This is done to eliminate the vertical component of the velocity + var v1 = { + x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision), + y: body1.velocity.x * Math.sin(angleCollision) - body1.velocity.y * Math.cos(angleCollision) + }; + + var v2 = { + x: body2.velocity.x * Math.cos(angleCollision) + body2.velocity.y * Math.sin(angleCollision), + y: body2.velocity.x * Math.sin(angleCollision) - body2.velocity.y * Math.cos(angleCollision) + }; + + // We expect the new velocity after impact + var tempVel1 = ((body1.mass - body2.mass) * v1.x + 2 * body2.mass * v2.x) / (body1.mass + body2.mass); + var tempVel2 = (2 * body1.mass * v1.x + (body2.mass - body1.mass) * v2.x) / (body1.mass + body2.mass); + + // We convert the vector to the original coordinate system and multiplied by factor of rebound + if (!body1.immovable) + { + body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x; + body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y; + } + + if (!body2.immovable) + { + body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x; + body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y; + } + + // When the collision angle is almost perpendicular to the total initial velocity vector + // (collision on a tangent) vector direction can be determined incorrectly. + // This code fixes the problem + + if (Math.abs(angleCollision) < Math.PI / 2) + { + if ((body1.velocity.x > 0) && !body1.immovable && (body2.velocity.x > body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x < 0) && !body2.immovable && (body1.velocity.x < body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y > 0) && !body1.immovable && (body2.velocity.y > body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y < 0) && !body2.immovable && (body1.velocity.y < body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + else if (Math.abs(angleCollision) > Math.PI / 2) + { + if ((body1.velocity.x < 0) && !body1.immovable && (body2.velocity.x < body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y < 0) && !body1.immovable && (body2.velocity.y < body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + + if (!body1.immovable) + { + body1.x += (body1.velocity.x * this.game.time.physicsElapsed) - overlap * Math.cos(angleCollision); + body1.y += (body1.velocity.y * this.game.time.physicsElapsed) - overlap * Math.sin(angleCollision); + } + + if (!body2.immovable) + { + body2.x += (body2.velocity.x * this.game.time.physicsElapsed) + overlap * Math.cos(angleCollision); + body2.y += (body2.velocity.y * this.game.time.physicsElapsed) + overlap * Math.sin(angleCollision); + } + + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + + return true; + + }, + + /** + * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: + * `touching.left`, `touching.right` and `overlapX`. + * + * @method Phaser.Physics.Arcade#getOverlapX + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of horizontal overlap between the two bodies. + */ + getOverlapX: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS; + + if (body1.deltaX() === 0 && body2.deltaX() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaX() > body2.deltaX()) + { + // Body1 is moving right and / or Body2 is moving left + overlap = body1.right - body2.x; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.right = true; + body2.touching.none = false; + body2.touching.left = true; + } + } + else if (body1.deltaX() < body2.deltaX()) + { + // Body1 is moving left and/or Body2 is moving right + overlap = body1.x - body2.width - body2.x; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.left = true; + body2.touching.none = false; + body2.touching.right = true; + } + } + + // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapX = overlap; + body2.overlapX = overlap; + + return overlap; + + }, + + /** + * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: + * `touching.up`, `touching.down` and `overlapY`. + * + * @method Phaser.Physics.Arcade#getOverlapY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of vertical overlap between the two bodies. + */ + getOverlapY: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS; + + if (body1.deltaY() === 0 && body2.deltaY() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaY() > body2.deltaY()) + { + // Body1 is moving down and/or Body2 is moving up + overlap = body1.bottom - body2.y; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.down = true; + body2.touching.none = false; + body2.touching.up = true; + } + } + else if (body1.deltaY() < body2.deltaY()) + { + // Body1 is moving up and/or Body2 is moving down + overlap = body1.y - body2.bottom; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.up = true; + body2.touching.none = false; + body2.touching.down = true; + } + } + + // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapY = overlap; + body2.overlapY = overlap; + + return overlap; + + }, + + /** + * The core separation function to separate two physics bodies on the x axis. + * + * @method Phaser.Physics.Arcade#separateX + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateX: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapX(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.x; + var v2 = body2.velocity.x; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.x -= overlap; + body2.x += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.x = avg + nv1 * body1.bounce.x; + body2.velocity.x = avg + nv2 * body2.bounce.x; + } + else if (!body1.immovable) + { + body1.x -= overlap; + body1.velocity.x = v2 - v1 * body1.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body2.moves) + { + body1.y += (body2.y - body2.prev.y) * body2.friction.y; + } + } + else + { + body2.x += overlap; + body2.velocity.x = v1 - v2 * body2.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body1.moves) + { + body2.y += (body1.y - body1.prev.y) * body1.friction.y; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * The core separation function to separate two physics bodies on the y axis. + * + * @private + * @method Phaser.Physics.Arcade#separateY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateY: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapY(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.y; + var v2 = body2.velocity.y; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.y -= overlap; + body2.y += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.y = avg + nv1 * body1.bounce.y; + body2.velocity.y = avg + nv2 * body2.bounce.y; + } + else if (!body1.immovable) + { + body1.y -= overlap; + body1.velocity.y = v2 - v1 * body1.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body2.moves) + { + body1.x += (body2.x - body2.prev.x) * body2.friction.x; + } + } + else + { + body2.y += overlap; + body2.velocity.y = v1 - v2 * body2.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body1.moves) + { + body2.x += (body1.x - body1.prev.x) * body1.friction.x; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. + * + * @method Phaser.Physics.Arcade#getObjectsUnderPointer + * @param {Phaser.Pointer} pointer - The Pointer to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. + * @param {object} [callbackContext] - The context in which to run the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates. + */ + getObjectsUnderPointer: function (pointer, group, callback, callbackContext) { + + if (group.length === 0 || !pointer.exists) + { + return; + } + + return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer); + + }, + + /** + * Given a Group and a location this will check to see which Group children overlap with the coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. + * + * @method Phaser.Physics.Arcade#getObjectsAtLocation + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. + * @param {object} [callbackContext] - The context in which to run the callback. + * @param {object} [callbackArg] - An argument to pass to the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates. + */ + getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) { + + 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(x, y, 1, 1); + var output = []; + + var items = this.quadTree.retrieve(rect); + + for (var i = 0; i < items.length; i++) + { + if (items[i].hitTest(x, y)) + { + if (callback) + { + callback.call(callbackContext, callbackArg, items[i].sprite); + } + + output.push(items[i].sprite); + } + } + + return output; + + }, + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToObject: function (displayObject, destination, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Phaser.Point.angle(destination, displayObject); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#moveToPointer + * @param {any} displayObject - The display object to move. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToPointer: function (displayObject, speed, pointer, maxTime) { + + if (speed === undefined) { speed = 60; } + pointer = pointer || this.game.input.activePointer; + if (maxTime === undefined) { maxTime = 0; } + + var angle = this.angleToPointer(displayObject, pointer); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToXY: function (displayObject, x, y, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Math.atan2(y - displayObject.y, x - displayObject.x); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromAngle + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromAngle: function (angle, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(angle, speed, true); + + }, + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. + * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. + * + * @method Phaser.Physics.Arcade#accelerationFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. + * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. + */ + accelerationFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleBetween(displayObject, destination); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToPointer + * @param {any} displayObject - The display object to move. + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToPointer(displayObject, pointer); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToXY(displayObject, x, y); + + displayObject.body.acceleration.setTo(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Find the distance between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * If you have nested objects and need to calculate the distance between their centers in World coordinates, + * set their anchors to (0.5, 0.5) and use the `world` argument. + * + * If objects aren't nested or they share a parent's offset, you can calculate the distance between their + * centers with the `useCenter` argument, regardless of their anchor values. + * + * @method Phaser.Physics.Arcade#distanceBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {number} The distance between the source and target objects. + */ + distanceBetween: function (source, target, world, useCenter) { + + if (world === undefined) { world = false; } + + var dx; + var dy; + + if (useCenter) + { + dx = source.centerX - target.centerX; + dy = source.centerY - target.centerY; + } + else if (world) + { + dx = source.world.x - target.world.x; + dy = source.world.y - target.world.y; + } + else + { + dx = source.x - target.x; + dy = source.y - target.y; + } + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and the given x/y coordinates. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the x/y coordinates. + */ + distanceToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - x : displayObject.x - x; + var dy = (world) ? displayObject.world.y - y : displayObject.y - y; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the Pointer. + */ + distanceToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.x - pointer.worldX; + var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + + /** + * From a set of points or display objects, find the one closest to a source point or object. + * + * @method Phaser.Physics.Arcade#closest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The first target closest to the origin. + */ + closest: function (source, targets, world, useCenter) { + var min = Infinity; + var closest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance < min) + { + closest = target; + min = distance; + } + } + + return closest; + }, + + /** + * From a set of points or display objects, find the one farthest from a source point or object. + * + * @method Phaser.Physics.Arcade#farthest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The target closest to the origin. + */ + farthest: function (source, targets, world, useCenter) { + var max = -1; + var farthest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance > max) + { + farthest = target; + max = distance; + } + } + + return farthest; + }, + + /** + * Find the angle in radians between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetween: function (source, target, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Phaser.Point.angle(target.world, source.world); + } + else + { + return Phaser.Point.angle(target, source); + } + + }, + + /** + * Find the angle in radians between centers of two display objects (like Sprites). + * + * @method Phaser.Physics.Arcade#angleBetweenCenters + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetweenCenters: function (source, target) { + + var dx = target.centerX - source.centerX; + var dy = target.centerY - source.centerY; + + return Math.atan2(dy, dx); + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to get the angle to. + * @param {number} y - The y coordinate to get the angle to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(y - displayObject.world.y, x - displayObject.world.x); + } + else + { + return Math.atan2(y - displayObject.y, x - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x); + } + else + { + return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, + * taking their x/y and center into account relative to the world. + * + * @method Phaser.Physics.Arcade#worldAngleToPointer + * @param {any} displayObject - The DisplayObjerct to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY + */ + worldAngleToPointer: function (displayObject, pointer) { + + return this.angleToPointer(displayObject, pointer, true); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than +* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. +* +* @class Phaser.Physics.Arcade.Body +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. +*/ +Phaser.Physics.Arcade.Body = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = sprite.game; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.ARCADE; + + /** + * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. + * @default + */ + this.enable = true; + + /** + * If `true` this Body is using circular collision detection. If `false` it is using rectangular. + * Use `Body.setCircle` to control the collision shape this Body uses. + * @property {boolean} isCircle + * @default + * @readOnly + */ + this.isCircle = false; + + /** + * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled, relative to the Sprite's _texture_. + * If you wish to change the radius then call {@link #setCircle} again with the new value. + * If you wish to stop the Body using a circle then call {@link #setCircle} with a radius of zero (or undefined). + * The actual radius of the Body (at any Sprite scale) is equal to {@link #halfWidth} and the diameter is equal to {@link #width}. + * @property {number} radius + * @default + * @readOnly + */ + this.radius = 0; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite's texture. + */ + this.offset = new Phaser.Point(); + + /** + * @property {Phaser.Point} position - The position of the physics body, equivalent to ({@link #left}, {@link #top}). + * @readonly + */ + this.position = new Phaser.Point(sprite.x, sprite.y); + + /** + * @property {Phaser.Point} prev - The previous position of the physics body. + * @readonly + */ + this.prev = new Phaser.Point(this.position.x, this.position.y); + + /** + * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) + * @default + */ + this.allowRotation = true; + + /** + * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body + * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. + * @property {number} rotation + */ + this.rotation = sprite.angle; + + /** + * @property {number} preRotation - The previous rotation of the physics body, in degrees. + * @readonly + */ + this.preRotation = sprite.angle; + + /** + * @property {number} width - The calculated width of the physics body. + * @readonly + */ + this.width = sprite.width; + + /** + * @property {number} height - The calculated height of the physics body. + * @readonly + */ + this.height = sprite.height; + + /** + * @property {number} sourceWidth - The un-scaled original size. + * @readonly + */ + this.sourceWidth = sprite.width; + + /** + * @property {number} sourceHeight - The un-scaled original size. + * @readonly + */ + this.sourceHeight = sprite.height; + + if (sprite.texture) + { + this.sourceWidth = sprite.texture.frame.width; + this.sourceHeight = sprite.texture.frame.height; + } + + /** + * @property {number} halfWidth - The calculated width / 2 of the physics body. + * @readonly + */ + this.halfWidth = Math.abs(sprite.width / 2); + + /** + * @property {number} halfHeight - The calculated height / 2 of the physics body. + * @readonly + */ + this.halfHeight = Math.abs(sprite.height / 2); + + /** + * @property {Phaser.Point} center - The center coordinate of the Physics Body. + * @readonly + */ + this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight); + + /** + * @property {Phaser.Point} velocity - The velocity, or rate of change the Body's position. Measured in pixels per second. + */ + this.velocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} newVelocity - The distanced traveled during the last update, equal to `velocity * physicsElapsed`. Calculated during the Body.preUpdate and applied to its position. + * @readonly + */ + this.newVelocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. + */ + this.deltaMax = new Phaser.Point(); + + /** + * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + */ + this.acceleration = new Phaser.Point(); + + /** + * @property {boolean} allowDrag - Allow this Body to be influenced by {@link #drag}? + * @default + */ + this.allowDrag = true; + + /** + * @property {Phaser.Point} drag - The drag applied to the motion of the Body (when {@link #allowDrag} is enabled). Measured in pixels per second squared. + */ + this.drag = new Phaser.Point(); + + /** + * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local. + * @default + */ + this.allowGravity = true; + + /** + * @property {Phaser.Point} gravity - This Body's local gravity, **added** to any world gravity, unless Body.allowGravity is set to false. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. + */ + this.bounce = new Phaser.Point(); + + /** + * The elasticity of the Body when colliding with the World bounds. + * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property + * to a Phaser.Point object in order to enable a World bounds specific bounce value. + * @property {Phaser.Point} worldBounce + */ + this.worldBounce = null; + + /** + * A Signal that is dispatched when this Body collides with the world bounds. + * Due to the potentially high volume of signals this could create it is disabled by default. + * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` + * and it will be called when a collision happens, passing five arguments: + * `onWorldBounds(sprite, up, down, left, right)` + * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans + * indicating on which side of the world the Body collided. + * @property {Phaser.Signal} onWorldBounds + */ + this.onWorldBounds = null; + + /** + * A Signal that is dispatched when this Body collides with another Body. + * + * You still need to call `game.physics.arcade.collide` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `collide` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onCollide + */ + this.onCollide = null; + + /** + * A Signal that is dispatched when this Body overlaps with another Body. + * + * You still need to call `game.physics.arcade.overlap` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `overlap` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onOverlap + */ + this.onOverlap = null; + + /** + * @property {Phaser.Point} maxVelocity - The maximum velocity (in pixels per second squared) that the Body can reach. + * @default + */ + this.maxVelocity = new Phaser.Point(10000, 10000); + + /** + * @property {Phaser.Point} friction - If this Body is {@link #immovable} and moving, and another Body is 'riding' this one, this is the amount of motion the riding Body receives on each axis. + */ + this.friction = new Phaser.Point(1, 0); + + /** + * @property {number} angularVelocity - The angular velocity is the rate of change of the Body's rotation. It is measured in degrees per second. + * @default + */ + this.angularVelocity = 0; + + /** + * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. + * @default + */ + this.angularAcceleration = 0; + + /** + * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach. + * @default + */ + this.maxAngular = 1000; + + /** + * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. + * @default + */ + this.mass = 1; + + /** + * @property {number} angle - The angle of the Body's **velocity** in radians. + * @readonly + */ + this.angle = 0; + + /** + * @property {number} speed - The speed of the Body in pixels per second, equal to the magnitude of the velocity. + * @readonly + */ + this.speed = 0; + + /** + * @property {number} facing - A const reference to the direction the Body is traveling or facing: Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.UP, or Phaser.DOWN. If the Body is moving on both axes, UP and DOWN take precedence. + * @default + */ + this.facing = Phaser.NONE; + + /** + * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. **Two** immovable Bodies can't separate or exchange momentum and will pass through each other. + * @default + */ + this.immovable = false; + + /** + * Whether the physics system should update the Body's position and rotation based on its velocity, acceleration, drag, and gravity. + * + * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never + * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. + * If you want the physics system to move the body around, then set moves to true. + * + * A Body with moves = false can still be moved slightly (but not accelerated) during collision separation unless you set {@link #immovable} as well. + * + * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually. + * @default + */ + this.moves = true; + + /** + * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateX = false; + + /** + * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateY = false; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapX - The amount of horizontal overlap during the collision. + */ + this.overlapX = 0; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapY - The amount of vertical overlap during the collision. + */ + this.overlapY = 0; + + /** + * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. + * @property {number} overlapR - The amount of overlap during the collision. + */ + this.overlapR = 0; + + /** + * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. + * @property {boolean} embedded - Body embed value. + */ + this.embedded = false; + + /** + * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. + * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? + */ + this.collideWorldBounds = false; + + /** + * Set the checkCollision properties to control which directions collision is processed for this Body. + * For example checkCollision.up = false means it won't collide when the collision happened while moving up. + * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. + * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. + * @property {object} checkCollision - An object containing allowed collision (none, up, down, left, right). + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * This object is populated with boolean values when the Body collides with another. + * touching.up = true means the collision happened to the top of this Body for example. + * @property {object} touching - An object containing touching results (none, up, down, left, right). + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with previous touching values from the bodies previous collision. + * @property {object} wasTouching - An object containing previous touching results (none, up, down, left, right). + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with boolean values when the Body collides with the World bounds or a Tile. + * For example if blocked.up is true then the Body cannot move up. + * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any (none, up, down, left, right). + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. + * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. + * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision. + */ + this.tilePadding = new Phaser.Point(); + + /** + * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state? + */ + this.dirty = false; + + /** + * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. + */ + this.skipQuadTree = false; + + /** + * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. + * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. + * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, + * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. + * @property {boolean} syncBounds + * @default + */ + this.syncBounds = false; + + /** + * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods. + */ + this.isMoving = false; + + /** + * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods. + */ + this.stopVelocityOnCollide = true; + + /** + * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveTimer = 0; + + /** + * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDistance = 0; + + /** + * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDuration = 0; + + /** + * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveTarget = null; + + /** + * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveEnd = null; + + /** + * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events. + */ + this.onMoveComplete = new Phaser.Signal(); + + /** + * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. + */ + this.movementCallback = null; + + /** + * @property {object} movementCallbackContext - Context in which to call the movementCallback. + */ + this.movementCallbackContext = null; + + /** + * @property {boolean} _reset - Internal cache var. + * @private + */ + this._reset = true; + + /** + * @property {number} _sx - Internal cache var. + * @private + */ + this._sx = sprite.scale.x; + + /** + * @property {number} _sy - Internal cache var. + * @private + */ + this._sy = sprite.scale.y; + + /** + * @property {number} _dx - Internal cache var. + * @private + */ + this._dx = 0; + + /** + * @property {number} _dy - Internal cache var. + * @private + */ + this._dy = 0; + +}; + +Phaser.Physics.Arcade.Body.prototype = { + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @protected + */ + updateBounds: function () { + + if (this.syncBounds) + { + var b = this.sprite.getBounds(); + b.ceilAll(); + + if (b.width !== this.width || b.height !== this.height) + { + this.width = b.width; + this.height = b.height; + this._reset = true; + } + } + else + { + 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._sx = asx; + this._sy = asy; + this._reset = true; + } + } + + if (this._reset) + { + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.updateCenter(); + } + + }, + + /** + * Update the Body's center from its position. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @protected + */ + updateCenter: function () { + + this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @protected + */ + preUpdate: function () { + + if (!this.enable || this.game.physics.arcade.isPaused) + { + return; + } + + this.dirty = true; + + // Store and reset collision flags + 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.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; + + this.overlapR = 0; + this.overlapX = 0; + this.overlapY = 0; + + this.embedded = false; + + this.updateBounds(); + + this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.updateCenter(); + + this.rotation = this.sprite.angle; + + this.preRotation = this.rotation; + + if (this._reset || this.sprite.fresh) + { + 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; + this.updateCenter(); + + if (this.position.x !== this.prev.x || this.position.y !== this.prev.y) + { + this.angle = this.velocity.atan(); + } + + this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); + + // Now the State update will throw collision checks at the Body + // And finally we'll integrate the new position back to the Sprite in postUpdate + + if (this.collideWorldBounds) + { + if (this.checkWorldBounds() && this.onWorldBounds) + { + this.onWorldBounds.dispatch(this.sprite, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); + } + } + } + + this._dx = this.deltaX(); + this._dy = this.deltaY(); + + this._reset = false; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateMovement + * @protected + */ + updateMovement: function () { + + var percent = 0; + var collided = (this.overlapX !== 0 || this.overlapY !== 0); + + // Duration or Distance based? + + if (this.moveDuration > 0) + { + this.moveTimer += this.game.time.elapsedMS; + + percent = this.moveTimer / this.moveDuration; + } + else + { + this.moveTarget.end.set(this.position.x, this.position.y); + + percent = this.moveTarget.length / this.moveDistance; + } + + if (this.movementCallback) + { + var result = this.movementCallback.call(this.movementCallbackContext, this, this.velocity, percent); + } + + if (collided || percent >= 1 || (result !== undefined && result !== true)) + { + this.stopMovement((percent >= 1) || (this.stopVelocityOnCollide && collided)); + return false; + } + + return true; + + }, + + /** + * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it + * has Body.isMoving true), then calling this method will stop the movement before + * either the duration or distance counters expire. + * + * The `onMoveComplete` signal is dispatched. + * + * @method Phaser.Physics.Arcade.Body#stopMovement + * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero? + */ + stopMovement: function (stopVelocity) { + + if (this.isMoving) + { + this.isMoving = false; + + if (stopVelocity) + { + this.velocity.set(0); + } + + // Send the Sprite this Body belongs to + // and a boolean indicating if it stopped because of a collision or not + this.onMoveComplete.dispatch(this.sprite, (this.overlapX !== 0 || this.overlapY !== 0)); + } + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @protected + */ + postUpdate: function () { + + // Only allow postUpdate to be called once per frame + if (!this.enable || !this.dirty) + { + return; + } + + // Moving? + if (this.isMoving) + { + this.updateMovement(); + } + + this.dirty = false; + + 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.position.x += this._dx; + this.sprite.position.y += this._dy; + this._reset = true; + } + + this.updateCenter(); + + if (this.allowRotation) + { + this.sprite.angle += this.deltaZ(); + } + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @protected + * @return {boolean} True if the Body collided with the world bounds, otherwise false. + */ + checkWorldBounds: function () { + + var pos = this.position; + var bounds = this.game.physics.arcade.bounds; + var check = this.game.physics.arcade.checkCollision; + + var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; + var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; + + if (pos.x < bounds.x && check.left) + { + pos.x = bounds.x; + this.velocity.x *= bx; + this.blocked.left = true; + this.blocked.none = false; + } + else if (this.right > bounds.right && check.right) + { + pos.x = bounds.right - this.width; + this.velocity.x *= bx; + this.blocked.right = true; + this.blocked.none = false; + } + + if (pos.y < bounds.y && check.up) + { + pos.y = bounds.y; + this.velocity.y *= by; + this.blocked.up = true; + this.blocked.none = false; + } + else if (this.bottom > bounds.bottom && check.down) + { + pos.y = bounds.bottom - this.height; + this.velocity.y *= by; + this.blocked.down = true; + this.blocked.none = false; + } + + return !this.blocked.none; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal timer, and then + * monitoring the duration each frame. When the duration is up the movement is + * stopped and the `Body.onMoveComplete` signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * You can optionally set a speed in pixels per second. If not specified it + * will use the current `Body.speed` value. If this is zero, the function will return false. + * + * Please note that due to browser timings you should allow for a variance in + * when the duration will actually expire. Depending on system it may be as much as + * +- 50ms. Also this method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveFrom + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveFrom: function (duration, speed, direction) { + + if (speed === undefined) { speed = this.speed; } + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + this.moveTimer = 0; + this.moveDuration = duration; + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal distance counter. + * The distance is monitored each frame. When the distance equals the distance + * specified in this call, the movement is stopped, and the `Body.onMoveComplete` + * signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * Please note that due to browser timings you should allow for a variance in + * when the distance will actually expire. + * + * Note: This method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveTo + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} distance - The distance, in pixels, the Body will move. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveTo: function (duration, distance, direction) { + + var speed = distance / (duration / 1000); + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + distance = Math.abs(distance); + + this.moveDuration = 0; + this.moveDistance = distance; + + if (this.moveTarget === null) + { + this.moveTarget = new Phaser.Line(); + this.moveEnd = new Phaser.Point(); + } + + this.moveTarget.fromAngle(this.x, this.y, angle, distance); + + this.moveEnd.set(this.moveTarget.end.x, this.moveTarget.end.y); + + this.moveTarget.setTo(this.x, this.y, this.x, this.y); + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * You can modify the size of the physics Body to be any dimension you need. + * This allows you to make it smaller, or larger, than the parent Sprite. You + * can also control the x and y offset of the Body. + * + * The width, height, and offset arguments are relative to the Sprite + * _texture_ and are scaled with the Sprite's {@link Phaser.Sprite#scale} + * (but **not** the scale of any ancestors or the {@link Phaser.Camera#scale + * Camera scale}). + * + * For example: If you have a Sprite with a texture that is 80x100 in size, + * and you want the physics body to be 32x32 pixels in the middle of the + * texture, you would do: + * + * `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, + * 34)` + * + * Where the first two parameters are the new Body size (32x32 pixels) + * relative to the Sprite's scale. 24 is the horizontal offset of the Body + * from the top-left of the Sprites texture, and 34 is the vertical offset. + * + * If you've scaled a Sprite by altering its `width`, `height`, or `scale` + * and you want to position the Body relative to the Sprite's dimensions + * (which will differ from its texture's dimensions), you should divide these + * arguments by the Sprite's current scale: + * + * `setSize(32 / sprite.scale.x, 32 / sprite.scale.y)` + * + * Calling `setSize` on a Body that has already had `setCircle` will reset + * all of the Circle properties, making this Body rectangular again. + * @method Phaser.Physics.Arcade.Body#setSize + * @param {number} width - The width of the Body, relative to the Sprite's + * texture. + * @param {number} height - The height of the Body, relative to the Sprite's + * texture. + * @param {number} [offsetX] - The X offset of the Body from the left of the + * Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the + * Sprite's texture. + */ + setSize: function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { 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.updateCenter(); + + this.isCircle = false; + this.radius = 0; + + }, + + /** + * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. + * The radius is given in pixels (relative to the Sprite's _texture_) and is the distance from the center of the circle to the edge. + * + * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite's texture. + * + * To change a Body back to being rectangular again call `Body.setSize`. + * + * Note: Circular collision only happens with other Arcade Physics bodies, it does not + * work against tile maps, where rectangular collision is the only method supported. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. + * @param {number} [offsetX] - The X offset of the Body from the left of the Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the Sprite's texture. + */ + setCircle: function (radius, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.isCircle = true; + this.radius = radius; + + this.sourceWidth = radius * 2; + this.sourceHeight = radius * 2; + + 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.updateCenter(); + } + else + { + this.isCircle = false; + } + + }, + + /** + * Resets all Body values (velocity, acceleration, rotation, etc) + * + * @method Phaser.Physics.Arcade.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new y position of the Body. + */ + reset: function (x, y) { + + this.stop(); + + this.position.x = (x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + this.rotation = this.sprite.angle; + this.preRotation = this.rotation; + + this.updateBounds(); + + this.updateCenter(); + + }, + + /** + * Sets acceleration, velocity, and {@link #speed} to 0. + * + * @method Phaser.Physics.Arcade.Body#stop + */ + stop: function () { + + this.velocity.set(0); + this.acceleration.set(0); + this.speed = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + + }, + + /** + * Returns the bounds of this physics body. + * + * Only used internally by the World collision methods. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @param {object} obj - The object in which to set the bounds values. + * @return {object} The object that was given to this method. + */ + getBounds: function (obj) { + + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + + }, + + /** + * Tests if a world point lies within this Body. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @param {number} x - The world x coordinate to test. + * @param {number} y - The world y coordinate to test. + * @return {boolean} True if the given coordinates are inside this Body, otherwise false. + */ + hitTest: function (x, y) { + + return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Returns true if the bottom of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onFloor: function () { + + return this.blocked.down; + + }, + + /** + * Returns true if the top of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onCeiling: function(){ + + return this.blocked.up; + + }, + + /** + * Returns true if either side of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onWall: function () { + + return (this.blocked.left || this.blocked.right); + + }, + + /** + * Returns the absolute delta x value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @return {number} The absolute delta value. + */ + deltaAbsX: function () { + + return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); + + }, + + /** + * Returns the absolute delta y value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @return {number} The absolute delta value. + */ + deltaAbsY: function () { + + return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); + + }, + + /** + * Returns the delta x value. The difference between Body.x now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. + */ + deltaX: function () { + + return this.position.x - this.prev.x; + + }, + + /** + * Returns the delta y value. The difference between Body.y now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. + */ + deltaY: function () { + + return this.position.y - this.prev.y; + + }, + + /** + * Returns the delta z value. The difference between Body.rotation now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise. + */ + deltaZ: function () { + + return this.rotation - this.preRotation; + + }, + + /** + * Destroys this Body. + * + * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. + * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. + * + * @method Phaser.Physics.Arcade.Body#destroy + */ + destroy: function () { + + if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group) + { + this.sprite.parent.removeFromHash(this.sprite); + } + + this.sprite.body = null; + this.sprite = null; + + } + +}; + +/** +* @name Phaser.Physics.Arcade.Body#left +* @property {number} left - The x position of the Body. The same as `Body.x`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "left", { + + get: function () { + + return this.position.x; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#right +* @property {number} right - The right value of this Body (same as Body.x + Body.width) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", { + + get: function () { + + return this.position.x + this.width; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#top +* @property {number} top - The y position of the Body. The same as `Body.y`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "top", { + + get: function () { + + return this.position.y; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#bottom +* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", { + + get: function () { + + return this.position.y + this.height; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#x +* @property {number} x - The x position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#y +* @property {number} y - The y position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + +}); + +/** +* Render Sprite Body. +* +* @method Phaser.Physics.Arcade.Body#render +* @param {object} context - The context to render to. +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string). +* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) +* @param {number} [lineWidth=1] - The width of the stroke when unfilled. +*/ +Phaser.Physics.Arcade.Body.render = function (context, body, color, filled, lineWidth) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0,255,0,0.4)'; + + context.fillStyle = color; + context.strokeStyle = color; + context.lineWidth = lineWidth || 1; + + if (body.isCircle) + { + context.beginPath(); + context.arc(body.center.x - body.game.camera.x, body.center.y - body.game.camera.y, body.halfWidth, 0, 2 * Math.PI); + + if (filled) + { + context.fill(); + } + else + { + context.stroke(); + } + } + else + { + if (filled) + { + context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + else + { + context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + } + +}; + +/** +* Render Sprite Body Physics Data as text. +* +* @method Phaser.Physics.Arcade.Body#renderBodyInfo +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {number} x - X position of the debug info to be rendered. +* @param {number} y - Y position of the debug info to be rendered. +* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). +*/ +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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics Tile map collision methods. +* +* @class Phaser.Physics.Arcade.TilemapCollision +* @constructor +*/ +Phaser.Physics.Arcade.TilemapCollision = function () {}; + +Phaser.Physics.Arcade.TilemapCollision.prototype = { + + /** + * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling. + */ + TILE_BIAS: 16, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!sprite.body) + { + return; + } + + var mapData = tilemapLayer.getTiles( + sprite.body.position.x - sprite.body.tilePadding.x - tilemapLayer.getTileOffsetX(), + sprite.body.position.y - sprite.body.tilePadding.y - tilemapLayer.getTileOffsetY(), + sprite.body.width + sprite.body.tilePadding.x, + sprite.body.height + sprite.body.tilePadding.y, + false, false); + + if (mapData.length === 0) + { + return; + } + + for (var i = 0; i < mapData.length; i++) + { + if (processCallback) + { + if (processCallback.call(callbackContext, sprite, mapData[i])) + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + else + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @private + * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer + * @param {Phaser.Group} group - The Group to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.children.length; i++) + { + if (group.children[i].exists) + { + this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * The core separation function to separate a physics body and a tile. + * + * @private + * @method Phaser.Physics.Arcade#separateTile + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to collide against. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {boolean} Returns true if the body was separated, otherwise false. + */ + separateTile: function (i, body, tile, tilemapLayer, overlapOnly) { + + if (!body.enable) + { + return false; + } + + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + // We re-check for collision in case body was separated in a previous step + if (!tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + // no collision so bail out (separated in a previous step) + return false; + } + else if (overlapOnly) + { + // There is an overlap, and we don't need to separate. Bail. + return true; + } + + // They overlap. Any custom callbacks? + + // A local callback always takes priority over a layer level callback + if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + else if (typeof tile.layer.callbacks !== 'undefined' && tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + + // We don't need to go any further if this tile doesn't actually separate + if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom) + { + // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation + return false; + } + + var ox = 0; + var oy = 0; + var minX = 0; + var minY = 1; + + if (body.deltaAbsX() > body.deltaAbsY()) + { + // Moving faster horizontally, check X axis first + minX = -1; + } + else if (body.deltaAbsX() < body.deltaAbsY()) + { + // Moving faster vertically, check Y axis first + minY = -1; + } + + if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom)) + { + // We only need do this if both axis have checking faces AND we're moving in both directions + minX = Math.min(Math.abs((body.position.x - tilemapLayerOffsetX) - tile.right), Math.abs((body.right - tilemapLayerOffsetX) - tile.left)); + minY = Math.min(Math.abs((body.position.y - tilemapLayerOffsetY) - tile.bottom), Math.abs((body.bottom - tilemapLayerOffsetY) - tile.top)); + } + + if (minX < minY) + { + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + + // That's horizontal done, check if we still intersects? If not then we can return now + if (ox !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + } + } + else + { + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + + // That's vertical done, check if we still intersects? If not then we can return now + if (oy !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + } + } + + return (ox !== 0 || oy !== 0); + + }, + + /** + * Check the body against the given tile on the X axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckX: function (body, tile, tilemapLayer) { + + var ox = 0; + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + + if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left) + { + // Body is moving LEFT + if (tile.faceRight && (body.x - tilemapLayerOffsetX) < tile.right) + { + ox = (body.x - tilemapLayerOffsetX) - tile.right; + + if (ox < -this.TILE_BIAS) + { + ox = 0; + } + } + } + else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right) + { + // Body is moving RIGHT + if (tile.faceLeft && (body.right - tilemapLayerOffsetX) > tile.left) + { + ox = (body.right - tilemapLayerOffsetX) - tile.left; + + if (ox > this.TILE_BIAS) + { + ox = 0; + } + } + } + + if (ox !== 0) + { + if (body.customSeparateX) + { + body.overlapX = ox; + } + else + { + this.processTileSeparationX(body, ox); + } + } + + return ox; + + }, + + /** + * Check the body against the given tile on the Y axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckY: function (body, tile, tilemapLayer) { + + var oy = 0; + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up) + { + // Body is moving UP + if (tile.faceBottom && (body.y - tilemapLayerOffsetY) < tile.bottom) + { + oy = (body.y - tilemapLayerOffsetY) - tile.bottom; + + if (oy < -this.TILE_BIAS) + { + oy = 0; + } + } + } + else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down) + { + // Body is moving DOWN + if (tile.faceTop && (body.bottom - tilemapLayerOffsetY) > tile.top) + { + oy = (body.bottom - tilemapLayerOffsetY) - tile.top; + + if (oy > this.TILE_BIAS) + { + oy = 0; + } + } + } + + if (oy !== 0) + { + if (body.customSeparateY) + { + body.overlapY = oy; + } + else + { + this.processTileSeparationY(body, oy); + } + } + + return oy; + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} x - The x separation amount. + */ + processTileSeparationX: function (body, x) { + + if (x < 0) + { + body.blocked.left = true; + body.blocked.none = false; + } + else if (x > 0) + { + body.blocked.right = true; + body.blocked.none = false; + } + + body.position.x -= x; + + if (body.bounce.x === 0) + { + body.velocity.x = 0; + } + else + { + body.velocity.x = -body.velocity.x * body.bounce.x; + } + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} y - The y separation amount. + */ + processTileSeparationY: function (body, y) { + + if (y < 0) + { + body.blocked.up = true; + body.blocked.none = false; + } + else if (y > 0) + { + body.blocked.down = true; + body.blocked.none = false; + } + + body.position.y -= y; + + if (body.bounce.y === 0) + { + body.velocity.y = 0; + } + else + { + body.velocity.y = -body.velocity.y * body.bounce.y; + } + + } + +}; + +// Merge this with the Arcade Physics prototype +Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Add an extra properties to p2 that we need +p2.Body.prototype.parent = null; +p2.Spring.prototype.parent = null; + +/** +* This is your main access to the P2 Physics World. +* From here you can create materials, listen for events and add bodies into the physics simulation. +* +* @class Phaser.Physics.P2 +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {object} [config] - Physics configuration object passed in from the game constructor. +*/ +Phaser.Physics.P2 = function (game, config) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + if (config === undefined) + { + config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; + } + else + { + if (!config.hasOwnProperty('gravity')) + { + config.gravity = [0, 0]; + } + + if (!config.hasOwnProperty('broadphase')) + { + config.broadphase = new p2.SAPBroadphase(); + } + } + + /** + * @property {object} config - The p2 World configuration object. + * @protected + */ + this.config = config; + + /** + * @property {p2.World} world - The p2 World in which the simulation is run. + * @protected + */ + this.world = new p2.World(this.config); + + /** + * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. + * @default + */ + this.frameRate = 1 / 60; + + /** + * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. + * @default + */ + this.useElapsedTime = false; + + /** + * @property {boolean} paused - The paused state of the P2 World. + * @default + */ + this.paused = false; + + /** + * @property {array} materials - A local array of all created Materials. + * @protected + */ + this.materials = []; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. + */ + this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); + + /** + * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * This signal is dispatched when a new Body is added to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world. + * + * @property {Phaser.Signal} onBodyAdded + */ + this.onBodyAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Body is removed to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world. + * + * @property {Phaser.Signal} onBodyRemoved + */ + this.onBodyRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is added to the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world. + * + * @property {Phaser.Signal} onSpringAdded + */ + this.onSpringAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is removed from the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world. + * + * @property {Phaser.Signal} onSpringRemoved + */ + this.onSpringRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is added to the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world. + * + * @property {Phaser.Signal} onConstraintAdded + */ + this.onConstraintAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is removed from the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world. + * + * @property {Phaser.Signal} onConstraintRemoved + */ + this.onConstraintRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is added to the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world. + * + * @property {Phaser.Signal} onContactMaterialAdded + */ + this.onContactMaterialAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is removed from the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world. + * + * @property {Phaser.Signal} onContactMaterialRemoved + */ + this.onContactMaterialRemoved = new Phaser.Signal(); + + /** + * @property {function} postBroadphaseCallback - A postBroadphase callback. + */ + this.postBroadphaseCallback = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are fired. + */ + this.callbackContext = null; + + /** + * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done. + * + * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done. + * + * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + // Pixel to meter function overrides + if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) + { + this.mpx = config.mpx; + this.mpxi = config.mpxi; + this.pxm = config.pxm; + this.pxmi = config.pxmi; + } + + // Hook into the World events + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + /** + * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. + */ + this.collisionGroups = []; + + /** + * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. + */ + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. + */ + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. + */ + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + /** + * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. + */ + this.boundsCollidesWith = []; + + /** + * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. + * @private + */ + this._toRemove = []; + + /** + * @property {number} _collisionGroupID - Internal var. + * @private + */ + this._collisionGroupID = 2; + + /** + * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsLeft = true; + + /** + * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsRight = true; + + /** + * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsTop = true; + + /** + * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsBottom = true; + + /** + * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsOwnGroup = false; + + // By default we want everything colliding with everything + this.setBoundsToWorld(true, true, true, true, false); + +}; + +Phaser.Physics.P2.prototype = { + + /** + * This will add a P2 Physics body into the removal list for the next step. + * + * @method Phaser.Physics.P2#removeBodyNextStep + * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. + */ + removeBodyNextStep: function (body) { + + this._toRemove.push(body); + + }, + + /** + * Called at the start of the core update loop. Purges flagged bodies from the world. + * + * @method Phaser.Physics.P2#preUpdate + */ + preUpdate: function () { + + var i = this._toRemove.length; + + while (i--) + { + this.removeBody(this._toRemove[i]); + } + + this._toRemove.length = 0; + + }, + + /** + * This will create a P2 Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. + * + * @method Phaser.Physics.P2#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [debug=false] - Create a debug object to go with this body? + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, debug, children) { + + if (debug === undefined) { debug = false; } + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + this.enable(object[i].children, debug, children); + } + else + { + this.enableBody(object[i], debug); + + if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) + { + this.enable(object[i], debug, true); + } + } + } + } + else + { + if (object instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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); + } + } + } + + }, + + /** + * Creates a P2 Physics body on the given game object. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * @method Phaser.Physics.P2#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + * @param {boolean} debug - Create a debug object to go with this body? + */ + 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; + if (typeof object.anchor !== 'undefined') { + object.anchor.set(0.5); + } + } + + }, + + /** + * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. + * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. + * + * @method Phaser.Physics.P2#setImpactEvents + * @param {boolean} state - Set to true to enable impact events, or false to disable. + */ + setImpactEvents: function (state) { + + if (state) + { + this.world.on("impact", this.impactHandler, this); + } + else + { + this.world.off("impact", this.impactHandler, this); + } + + }, + + /** + * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. + * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. + * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. + * Returning `true` from the callback will ensure they are checked in the narrowphase. + * + * @method Phaser.Physics.P2#setPostBroadphaseCallback + * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. + * @param {object} context - The context under which the callback will be fired. + */ + 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); + } + + }, + + /** + * Internal handler for the postBroadphase event. + * + * @method Phaser.Physics.P2#postBroadphaseHandler + * @private + * @param {object} event - The event data. + */ + postBroadphaseHandler: function (event) { + + if (!this.postBroadphaseCallback || event.pairs.length === 0) + { + return; + } + + for (var i = event.pairs.length - 2; i >= 0; 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); + } + } + + }, + + /** + * Handles a p2 impact event. + * + * @method Phaser.Physics.P2#impactHandler + * @private + * @param {object} event - The event data. + */ + impactHandler: function (event) { + + if (event.bodyA.parent && event.bodyB.parent) + { + // Body vs. Body callbacks + 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); + } + + // Body vs. Group callbacks + 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); + } + } + + }, + + /** + * Handles a p2 begin contact event. + * + * @method Phaser.Physics.P2#beginContactHandler + * @param {object} event - The event data. + */ + beginContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + 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.bodyB, event.shapeA, event.shapeB, event.contactEquations); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations); + } + } + + }, + + /** + * Handles a p2 end contact event. + * + * @method Phaser.Physics.P2#endContactHandler + * @param {object} event - The event data. + */ + endContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); + + if (event.bodyA.parent) + { + event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA); + } + } + + }, + + /** + * Sets the bounds of the Physics world to match the Game.World dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * + * @method Phaser.Physics#setBoundsToWorld + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + 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); + + }, + + /** + * Sets the given material against the 4 bounds of this World. + * + * @method Phaser.Physics#setWorldMaterial + * @param {Phaser.Physics.P2.Material} material - The material to set. + * @param {boolean} [left=true] - If true will set the material on the left bounds wall. + * @param {boolean} [right=true] - If true will set the material on the right bounds wall. + * @param {boolean} [top=true] - If true will set the material on the top bounds wall. + * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. + */ + setWorldMaterial: function (material, left, right, top, bottom) { + + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (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; + } + + }, + + /** + * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. + * If you start to use your own collision groups then your objects will no longer collide with the bounds. + * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. + * + * @method Phaser.Physics.P2#updateBoundsCollisionGroup + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + updateBoundsCollisionGroup: function (setCollisionGroup) { + + if (setCollisionGroup === undefined) { setCollisionGroup = true; } + + var mask = (setCollisionGroup) ? this.boundsCollisionGroup.mask : this.everythingCollisionGroup.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; + } + + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.P2#setBounds + * @param {number} x - The x coordinate of the top-left corner of the bounds. + * @param {number} y - The y coordinate of the top-left corner of the bounds. + * @param {number} width - The width of the bounds. + * @param {number} height - The height of the bounds. + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { + + if (left === undefined) { left = this._boundsLeft; } + if (right === undefined) { right = this._boundsRight; } + if (top === undefined) { top = this._boundsTop; } + if (bottom === undefined) { bottom = this._boundsBottom; } + if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; } + + this.setupWall(left, 'left', x, y, 1.5707963267948966, setCollisionGroup); + this.setupWall(right, 'right', x + width, y, -1.5707963267948966, setCollisionGroup); + this.setupWall(top, 'top', x, y, -3.141592653589793, setCollisionGroup); + this.setupWall(bottom, 'bottom', x, y + height, 0, setCollisionGroup); + + // Remember the bounds settings in case they change later on via World.setBounds + this._boundsLeft = left; + this._boundsRight = right; + this._boundsTop = top; + this._boundsBottom = bottom; + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Internal method called by setBounds. Responsible for creating, updating or + * removing the wall body shapes. + * + * @method Phaser.Physics.P2#setupWall + * @private + * @param {boolean} create - True to create the wall shape, false to remove it. + * @param {string} wall - The wall segment to update. + * @param {number} x - The x coordinate of the wall. + * @param {number} y - The y coordinate of the wall. + * @param {float} angle - The angle of the wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setupWall: function (create, wall, x, y, angle, setCollisionGroup) { + + if (create) + { + // We need a left wall. Do we have one already? + if (this.walls[wall]) + { + this.walls[wall].position = [ this.pxmi(x), this.pxmi(y) ]; + } + else + { + this.walls[wall] = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: angle }); + this.walls[wall].addShape(new p2.Plane()); + + this.world.addBody(this.walls[wall]); + } + + if (setCollisionGroup) + { + this.walls[wall].shapes[0].collisionGroup = this.boundsCollisionGroup.mask; + } + } + else + { + if (this.walls[wall]) + { + this.world.removeBody(this.walls[wall]); + this.walls[wall] = null; + } + } + + }, + + /** + * Pauses the P2 World independent of the game pause state. + * + * @method Phaser.Physics.P2#pause + */ + pause: function() { + + this.paused = true; + + }, + + /** + * Resumes a paused P2 World. + * + * @method Phaser.Physics.P2#resume + */ + resume: function() { + + this.paused = false; + + }, + + /** + * Internal P2 update loop. + * + * @method Phaser.Physics.P2#update + */ + update: function () { + + // Do nothing if the physics engine was paused before + if (this.paused) + { + return; + } + + if (this.useElapsedTime) + { + this.world.step(this.game.time.physicsElapsed); + } + else + { + this.world.step(this.frameRate); + } + + }, + + /** + * Called by Phaser.Physics when a State swap occurs. + * Starts the begin and end Contact listeners again. + * + * @method Phaser.Physics.P2#reset + */ + reset: function () { + + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + this._collisionGroupID = 2; + + this.setBoundsToWorld(true, true, true, true, false); + + }, + + /** + * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. + * + * The P2 world is also cleared: + * + * * Removes all solver equations + * * Removes all constraints + * * Removes all bodies + * * Removes all springs + * * Removes all contact materials + * + * This is called automatically when you switch state. + * + * @method Phaser.Physics.P2#clear + */ + clear: function () { + + this.world.time = 0; + this.world.fixedStepTime = 0; + + // Remove all solver equations + if (this.world.solver && this.world.solver.equations.length) + { + this.world.solver.removeAllEquations(); + } + + // Remove all constraints + var cs = this.world.constraints; + + for (var i = cs.length - 1; i >= 0; i--) + { + this.world.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.world.bodies; + + for (var i = bodies.length - 1; i >= 0; i--) + { + this.world.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.world.springs; + + for (var i = springs.length - 1; i >= 0; i--) + { + this.world.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.world.contactMaterials; + + for (var i = cms.length - 1; i >= 0; i--) + { + this.world.removeContactMaterial(cms[i]); + } + + 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.boundsCollidesWith = []; + + // Remove the world bounds + this.walls = { left: null, right: null, top: null, bottom: null }; + + }, + + /** + * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. + * + * @method Phaser.Physics.P2#destroy + */ + destroy: function () { + + this.clear(); + + this.game = null; + + }, + + /** + * Add a body to the world. + * + * @method Phaser.Physics.P2#addBody + * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. + * @return {boolean} True if the Body was added successfully, otherwise false. + */ + addBody: function (body) { + + if (body.data.world) + { + return false; + } + else + { + this.world.addBody(body.data); + + this.onBodyAdded.dispatch(body); + + return true; + } + + }, + + /** + * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. + * + * @method Phaser.Physics.P2#removeBody + * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. + * @return {Phaser.Physics.P2.Body} The Body that was removed. + */ + removeBody: function (body) { + + if (body.data.world === this.world) + { + this.world.removeBody(body.data); + + this.onBodyRemoved.dispatch(body); + } + + return body; + + }, + + /** + * Adds a Spring to the world. + * + * @method Phaser.Physics.P2#addSpring + * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was added. + */ + addSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.addSpring(spring.data); + } + else + { + this.world.addSpring(spring); + } + + this.onSpringAdded.dispatch(spring); + + return spring; + + }, + + /** + * Removes a Spring from the world. + * + * @method Phaser.Physics.P2#removeSpring + * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was removed. + */ + removeSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.removeSpring(spring.data); + } + else + { + this.world.removeSpring(spring); + } + + this.onSpringRemoved.dispatch(spring); + + return spring; + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createDistanceConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} distance - The distance to keep between the bodies. + * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. + * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.DistanceConstraint} The constraint + */ + createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, 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, localAnchorA, localAnchorB, maxForce)); + } + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createGearConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [angle=0] - The relative angle + * @param {number} [ratio=1] - The gear ratio. + * @return {Phaser.Physics.P2.GearConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * The pivot points are given in world (pixel) coordinates. + * + * @method Phaser.Physics.P2#createRevoluteConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. + * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint + */ + createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + 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, worldPivot)); + } + + }, + + /** + * Locks the relative position between two bodies. + * + * @method Phaser.Physics.P2#createLockConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.LockConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Constraint that only allows bodies to move along a line, relative to each other. + * See http://www.iforce2d.net/b2dtut/joints-prismatic + * + * @method Phaser.Physics.P2#createPrismaticConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. + * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Adds a Constraint to the world. + * + * @method Phaser.Physics.P2#addConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. + */ + addConstraint: function (constraint) { + + this.world.addConstraint(constraint); + + this.onConstraintAdded.dispatch(constraint); + + return constraint; + + }, + + /** + * Removes a Constraint from the world. + * + * @method Phaser.Physics.P2#removeConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. + */ + removeConstraint: function (constraint) { + + this.world.removeConstraint(constraint); + + this.onConstraintRemoved.dispatch(constraint); + + return constraint; + + }, + + /** + * Adds a Contact Material to the world. + * + * @method Phaser.Physics.P2#addContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. + */ + addContactMaterial: function (material) { + + this.world.addContactMaterial(material); + + this.onContactMaterialAdded.dispatch(material); + + return material; + + }, + + /** + * Removes a Contact Material from the world. + * + * @method Phaser.Physics.P2#removeContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. + */ + removeContactMaterial: function (material) { + + this.world.removeContactMaterial(material); + + this.onContactMaterialRemoved.dispatch(material); + + return material; + + }, + + /** + * Gets a Contact Material based on the two given Materials. + * + * @method Phaser.Physics.P2#getContactMaterial + * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. + * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. + * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. + */ + getContactMaterial: function (materialA, materialB) { + + return this.world.getContactMaterial(materialA, materialB); + + }, + + /** + * Sets the given Material against all Shapes owned by all the Bodies in the given array. + * + * @method Phaser.Physics.P2#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. + * @param {array} bodies - An Array of Body objects that the given Material will be set on. + */ + setMaterial: function (material, bodies) { + + var i = bodies.length; + + while (i--) + { + bodies[i].setMaterial(material); + } + + }, + + /** + * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). + * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. + * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. + * + * @method Phaser.Physics.P2#createMaterial + * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. + * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. + * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. + */ + 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; + + }, + + /** + * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. + * + * @method Phaser.Physics.P2#createContactMaterial + * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {object} [options] - Material options object. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. + */ + createContactMaterial: function (materialA, materialB, options) { + + if (materialA === undefined) { materialA = this.createMaterial(); } + if (materialB === undefined) { materialB = this.createMaterial(); } + + var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); + + return this.addContactMaterial(contact); + + }, + + /** + * Populates and returns an array with references to of all current Bodies in the world. + * + * @method Phaser.Physics.P2#getBodies + * @return {array} An array containing all current Bodies in the world. + */ + getBodies: function () { + + var output = []; + var i = this.world.bodies.length; + + while (i--) + { + output.push(this.world.bodies[i].parent); + } + + return output; + + }, + + /** + * Checks the given object to see if it has a p2.Body and if so returns it. + * + * @method Phaser.Physics.P2#getBody + * @param {object} object - The object to check for a p2.Body on. + * @return {p2.Body} The p2.Body, or null if not found. + */ + getBody: function (object) { + + if (object instanceof p2.Body) + { + // Native p2 body + return object; + } + else if (object instanceof Phaser.Physics.P2.Body) + { + // Phaser P2 Body + return object.data; + } + else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) + { + // Sprite, TileSprite, etc + return object.body.data; + } + + return null; + + }, + + /** + * Populates and returns an array of all current Springs in the world. + * + * @method Phaser.Physics.P2#getSprings + * @return {array} An array containing all current Springs in the world. + */ + getSprings: function () { + + var output = []; + var i = this.world.springs.length; + + while (i--) + { + output.push(this.world.springs[i].parent); + } + + return output; + + }, + + /** + * Populates and returns an array of all current Constraints in the world. + * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain + * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type. + * + * @method Phaser.Physics.P2#getConstraints + * @return {array} An array containing all current Constraints in the world. + */ + getConstraints: function () { + + var output = []; + var i = this.world.constraints.length; + + while (i--) + { + output.push(this.world.constraints[i]); + } + + return output; + + }, + + /** + * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to + * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. + * + * @method Phaser.Physics.P2#hitTest + * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. + * @param {Array} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) + * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. + * @return {Array} Array of bodies that overlap the point. + */ + hitTest: function (worldPoint, bodies, precision, filterStatic) { + + if (bodies === undefined) { bodies = this.world.bodies; } + if (precision === undefined) { precision = 5; } + if (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.type === p2.Body.STATIC)) + { + query.push(bodies[i].data); + } + else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC)) + { + query.push(bodies[i]); + } + else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC)) + { + query.push(bodies[i].body.data); + } + } + + return this.world.hitTest(physicsPosition, query, precision); + + }, + + /** + * Converts the current world into a JSON object. + * + * @method Phaser.Physics.P2#toJSON + * @return {object} A JSON representation of the world. + */ + toJSON: function () { + + return this.world.toJSON(); + + }, + + /** + * Creates a new Collision Group and optionally applies it to the given object. + * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. + * + * @method Phaser.Physics.P2#createCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + */ + 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; + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. + * + * @method Phaser.Physics.P2y#setCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + */ + setCollisionGroup: function (object, group) { + + if (object instanceof Phaser.Group) + { + for (var i = 0; i < object.total; i++) + { + if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) + { + object.children[i].body.setCollisionGroup(group); + } + } + } + else + { + object.body.setCollisionGroup(group); + } + + }, + + /** + * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restLength=1] - Rest length of the spring. A number > 0. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @return {Phaser.Physics.P2.Spring} The spring + */ + createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); + } + + }, + + /** + * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createRotationalSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @return {Phaser.Physics.P2.RotationalSpring} The spring + */ + createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Rotational Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping)); + } + + }, + + /** + * Creates a new Body and adds it to the World. + * + * @method Phaser.Physics.P2#createBody + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {Phaser.Physics.P2.Body} The body + */ + createBody: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Creates a new Particle and adds it to the World. + * + * @method Phaser.Physics.P2#createParticle + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + */ + createParticle: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Converts all of the polyline, polygon, and rectangle objects inside a Tiled ObjectGroup into physics bodies that are added to the world. + * Note that the polylines and polygons must be created in such a way that they can withstand polygon decomposition. + * + * @method Phaser.Physics.P2#convertCollisionObjects + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. + * @return {array} An array of the Phaser.Physics.Body objects that have been created. + */ + convertCollisionObjects: function (map, layer, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var output = []; + + for (var i = 0, len = map.collision[layer].length; i < len; i++) + { + // name: json.layers[i].objects[v].name, + // x: json.layers[i].objects[v].x, + // y: json.layers[i].objects[v].y, + // width: json.layers[i].objects[v].width, + // height: json.layers[i].objects[v].height, + // visible: json.layers[i].objects[v].visible, + // properties: json.layers[i].objects[v].properties, + // polyline: json.layers[i].objects[v].polyline + + var object = map.collision[layer][i]; + var shapeData = object.polyline || object.polygon; + + // polyline/polygon shape data present + if (shapeData) + { + var body = this.createBody(object.x, object.y, 0, addToWorld, {}, shapeData); + } + + // tilemap parser sets rectangle=true when parsing object groups + else if (object.rectangle) + { + var body = this.createBody(object.x, object.y, 0, addToWorld); + body.addRectangle(object.width, object.height, object.width / 2, object.height / 2); + } + + // ellipse could be added here, but Tiled ellipses use height/width instead of radius + // (to support oblong ellipses), which p2 doesn't currently support. + + if (body) + { + output.push(body); + } + } + + return output; + + }, + + /** + * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. + * + * @method Phaser.Physics.P2#clearTilemapLayerBodies + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + */ + 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 = 0; + + }, + + /** + * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. + * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. + * Every time you call this method it will destroy any previously created bodies and remove them from the world. + * Therefore understand it's a very expensive operation and not to be done in a core game update loop. + * + * @method Phaser.Physics.P2#convertTilemap + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. + * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. + * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. + */ + convertTilemap: function (map, layer, addToWorld, optimize) { + + layer = map.getLayer(layer); + + if (addToWorld === undefined) { addToWorld = true; } + if (optimize === undefined) { optimize = true; } + + // If the bodies array is already populated we need to nuke it + this.clearTilemapLayerBodies(map, layer); + + var width = 0; + var sx = 0; + var sy = 0; + + for (var y = 0, h = map.layers[layer].height; y < h; y++) + { + width = 0; + + for (var x = 0, w = map.layers[layer].width; x < w; x++) + { + var tile = map.layers[layer].data[y][x]; + + if (tile && tile.index > -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; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpx + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpx: function (v) { + + return v *= 20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters). + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxm + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxm: function (v) { + + return v * 0.05; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpxi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpxi: function (v) { + + return v *= -20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters) and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxmi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxmi: function (v) { + + return v * -0.05; + + } + +}; + +/** +* @name Phaser.Physics.P2#friction +* @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { + + get: function () { + + return this.world.defaultContactMaterial.friction; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.friction = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#restitution +* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { + + get: function () { + + return this.world.defaultContactMaterial.restitution; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.restitution = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#contactMaterial +* @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { + + get: function () { + + return this.world.defaultContactMaterial; + + }, + + set: function (value) { + + this.world.defaultContactMaterial = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applySpringForces +* @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { + + get: function () { + + return this.world.applySpringForces; + + }, + + set: function (value) { + + this.world.applySpringForces = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyDamping +* @property {boolean} applyDamping - Enable to automatically apply body damping each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { + + get: function () { + + return this.world.applyDamping; + + }, + + set: function (value) { + + this.world.applyDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyGravity +* @property {boolean} applyGravity - Enable to automatically apply gravity each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { + + get: function () { + + return this.world.applyGravity; + + }, + + set: function (value) { + + this.world.applyGravity = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#solveConstraints +* @property {boolean} solveConstraints - Enable/disable constraint solving in each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { + + get: function () { + + return this.world.solveConstraints; + + }, + + set: function (value) { + + this.world.solveConstraints = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#time +* @property {boolean} time - The World time. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "time", { + + get: function () { + + return this.world.time; + + } + +}); + +/** +* @name Phaser.Physics.P2#emitImpactEvent +* @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { + + get: function () { + + return this.world.emitImpactEvent; + + }, + + set: function (value) { + + this.world.emitImpactEvent = value; + + } + +}); + +/** +* How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. +* If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. +* @name Phaser.Physics.P2#sleepMode +* @property {number} sleepMode +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", { + + get: function () { + + return this.world.sleepMode; + + }, + + set: function (value) { + + this.world.sleepMode = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#total +* @property {number} total - The total number of bodies in the world. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "total", { + + get: function () { + + return this.world.bodies.length; + + } + +}); + +/* jshint noarg: false */ + +/** +* @author Georgios Kaleadis https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Allow to access a list of created fixture (coming from Body#addPhaserPolygon) +* which itself parse the input from PhysicsEditor with the custom phaser exporter. +* You can access fixtures of a Body by a group index or even by providing a fixture Key. + +* You can set the fixture key and also the group index for a fixture in PhysicsEditor. +* This gives you the power to create a complex body built of many fixtures and modify them +* during runtime (to remove parts, set masks, categories & sensor properties) +* +* @class Phaser.Physics.P2.FixtureList +* @constructor +* @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) +*/ +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 = { + + /** + * @method Phaser.Physics.P2.FixtureList#init + */ + init: function () { + + /** + * @property {object} namedFixtures - Collect all fixtures with a key + * @private + */ + this.namedFixtures = {}; + + /** + * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group + * @private + */ + this.groupedFixtures = []; + + /** + * @property {Array} allFixtures - This is a list of everything in this collection + * @private + */ + this.allFixtures = []; + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setCategory + * @param {number} bit - The bit to set as the collision group. + * @param {string} fixtureKey - Only apply to the fixture with the given key. + */ + setCategory: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionGroup = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMask + * @param {number} bit - The bit to set as the collision mask + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMask: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionMask = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setSensor + * @param {boolean} value - sensor true or false + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setSensor: function (value, fixtureKey) { + + var setter = function(fixture) { + fixture.sensor = value; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMaterial + * @param {Object} material - The contact material for a fixture + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMaterial: function (material, fixtureKey) { + + var setter = function(fixture) { + fixture.material = material; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * Accessor to get either a list of specified fixtures by key or the whole fixture list + * + * @method Phaser.Physics.P2.FixtureList#getFixtures + * @param {array} keys - A list of fixture keys + */ + 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; + } + + }, + + /** + * Accessor to get either a single fixture by its key. + * + * @method Phaser.Physics.P2.FixtureList#getFixtureByKey + * @param {string} key - The key of the fixture. + */ + getFixtureByKey: function (key) { + + return this.namedFixtures[key]; + + }, + + /** + * Accessor to get a group of fixtures by its group index. + * + * @method Phaser.Physics.P2.FixtureList#getGroup + * @param {number} groupID - The group index. + */ + getGroup: function (groupID) { + + return this.groupedFixtures[groupID]; + + }, + + /** + * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon + * + * @method Phaser.Physics.P2.FixtureList#parse + */ + 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)); + } + + }, + + /** + * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. + * + * @method Phaser.Physics.P2.FixtureList#flatten + * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. + */ + 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; + + } + +}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. +* +* @class Phaser.Physics.P2.PointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.PointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; + +/** +* @name Phaser.Physics.P2.PointProxy#x +* @property {number} x - The x property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { + + get: function () { + + return this.world.mpx(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#y +* @property {number} y - The y property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { + + get: function () { + + return this.world.mpx(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#mx +* @property {number} mx - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#my +* @property {number} my - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. +* +* @class Phaser.Physics.P2.InversePointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.InversePointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; + +/** +* @name Phaser.Physics.P2.InversePointProxy#x +* @property {number} x - The x property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#y +* @property {number} y - The y property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#mx +* @property {number} mx - The x property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = -value; + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#my +* @property {number} my - The y property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = -value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. +* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. +* In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. +* By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. +* Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. +* Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. +* +* @class Phaser.Physics.P2.Body +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. +* @param {number} [x=0] - The x coordinate of this Body. +* @param {number} [y=0] - The y coordinate of this Body. +* @param {number} [mass=1] - The default mass of this Body (0 = static). +*/ +Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { + + sprite = sprite || null; + x = x || 0; + y = y || 0; + if (mass === undefined) { mass = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to the P2 World. + */ + this.world = game.physics.p2; + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.P2JS; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. + */ + this.offset = new Phaser.Point(); + + /** + * @property {p2.Body} data - The p2 Body data. + * @protected + */ + this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); + + this.data.parent = this; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. + */ + this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); + + /** + * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body. + */ + this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); + + /** + * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. + */ + this.gravity = new Phaser.Point(); + + /** + * Dispatched when a first contact is created between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 5 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body is in contact with. + * The Shape from this body that caused the contact. + * The Shape from the contact body. + * The Contact Equation data array. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * Dispatched when contact ends between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 4 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body has ended contact with. + * The Shape from this body that caused the original contact. + * The Shape from the contact body. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + /** + * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. + */ + this.collidesWith = []; + + /** + * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. + */ + this.removeNextStep = false; + + /** + * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. + */ + this.debugBody = null; + + /** + * @property {boolean} dirty - Internally used by Sprite.x/y + */ + this.dirty = false; + + /** + * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. + * @private + */ + this._collideWorldBounds = true; + + /** + * @property {object} _bodyCallbacks - Array of Body callbacks. + * @private + */ + this._bodyCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Body callback contexts. + * @private + */ + this._bodyCallbackContext = {}; + + /** + * @property {object} _groupCallbacks - Array of Group callbacks. + * @private + */ + this._groupCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. + * @private + */ + this._groupCallbackContext = {}; + + /** + * @property {boolean} _reset - Internal var. + * @private + */ + this._reset = false; + + // Set-up the default shape + if (sprite) + { + this.setRectangleFromSprite(sprite); + + if (sprite.exists) + { + this.game.physics.p2.addBody(this); + } + } + +}; + +Phaser.Physics.P2.Body.prototype = { + + /** + * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createBodyCallback + * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + 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; + } + } + + }, + + /** + * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * This callback will only fire if this Body has been assigned a collision group. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createGroupCallback + * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + createGroupCallback: function (group, callback, callbackContext) { + + if (callback === null) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + else + { + this._groupCallbacks[group.mask] = callback; + this._groupCallbackContext[group.mask] = callbackContext; + } + + }, + + /** + * Gets the collision bitmask from the groups this body collides with. + * + * @method Phaser.Physics.P2.Body#getCollisionMask + * @return {number} The bitmask. + */ + getCollisionMask: function () { + + var mask = 0; + + if (this._collideWorldBounds) + { + mask = this.game.physics.p2.boundsCollisionGroup.mask; + } + + for (var i = 0; i < this.collidesWith.length; i++) + { + mask = mask | this.collidesWith[i].mask; + } + + return mask; + + }, + + /** + * Updates the collisionMask. + * + * @method Phaser.Physics.P2.Body#updateCollisionMask + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + updateCollisionMask: function (shape) { + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * This also resets the collisionMask. + * + * @method Phaser.Physics.P2.Body#setCollisionGroup + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + setCollisionGroup: function (group, shape) { + + var mask = this.getCollisionMask(); + + if (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; + } + + }, + + /** + * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. + * + * @method Phaser.Physics.P2.Body#clearCollision + * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? + * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. + */ + clearCollision: function (clearGroup, clearMask, shape) { + + if (clearGroup === undefined) { clearGroup = true; } + if (clearMask === undefined) { clearMask = true; } + + if (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; + } + + }, + + /** + * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#removeCollisionGroup + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore. + * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body. + */ + removeCollisionGroup: function (group, clearCallback, shape) { + + if (clearCallback === undefined) { clearCallback = true; } + + var index; + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + index = this.collidesWith.indexOf(group[i]); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + } + else + { + index = this.collidesWith.indexOf(group); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#collides + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. + * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. + * @param {object} [callbackContext] - The context under which the callback will be called. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. + */ + collides: function (group, callback, callbackContext, shape) { + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + if (this.collidesWith.indexOf(group[i]) === -1) + { + this.collidesWith.push(group[i]); + + if (callback) + { + this.createGroupCallback(group[i], callback, callbackContext); + } + } + } + } + else + { + if (this.collidesWith.indexOf(group) === -1) + { + this.collidesWith.push(group); + + if (callback) + { + this.createGroupCallback(group, callback, callbackContext); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Moves the shape offsets so their center of mass becomes the body center of mass. + * + * @method Phaser.Physics.P2.Body#adjustCenterOfMass + */ + adjustCenterOfMass: function () { + + this.data.adjustCenterOfMass(); + this.shapeChanged(); + + }, + + /** + * Gets the velocity of a point in the body. + * + * @method Phaser.Physics.P2.Body#getVelocityAtPoint + * @param {Array} result - A vector to store the result in. + * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from. + * @return {Array} The result vector. + */ + getVelocityAtPoint: function (result, relativePoint) { + + return this.data.getVelocityAtPoint(result, relativePoint); + + }, + + /** + * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. + * + * @method Phaser.Physics.P2.Body#applyDamping + * @param {number} dt - Current time step. + */ + applyDamping: function (dt) { + + this.data.applyDamping(dt); + + }, + + /** + * Apply impulse to a point relative to the body. + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulse + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space. + * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + */ + applyImpulse: function (impulse, worldX, worldY) { + + this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Apply impulse to a point local to the body. + * + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulseLocal + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space. + * @param {number} localX - A local point on the body. + * @param {number} localY - A local point on the body. + */ + applyImpulseLocal: function (impulse, localX, localY) { + + this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]); + + }, + + /** + * Apply force to a world point. + * + * This could for example be a point on the RigidBody surface. Applying force + * this way will add to Body.force and Body.angularForce. + * + * @method Phaser.Physics.P2.Body#applyForce + * @param {Float32Array|Array} force - The force vector to add. + * @param {number} worldX - The world x point to apply the force on. + * @param {number} worldY - The world y point to apply the force on. + */ + applyForce: function (force, worldX, worldY) { + + this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Sets the force on the body to zero. + * + * @method Phaser.Physics.P2.Body#setZeroForce + */ + setZeroForce: function () { + + this.data.setZeroForce(); + + }, + + /** + * If this Body is dynamic then this will zero its angular velocity. + * + * @method Phaser.Physics.P2.Body#setZeroRotation + */ + setZeroRotation: function () { + + this.data.angularVelocity = 0; + + }, + + /** + * If this Body is dynamic then this will zero its velocity on both axis. + * + * @method Phaser.Physics.P2.Body#setZeroVelocity + */ + setZeroVelocity: function () { + + this.data.velocity[0] = 0; + this.data.velocity[1] = 0; + + }, + + /** + * Sets the Body damping and angularDamping to zero. + * + * @method Phaser.Physics.P2.Body#setZeroDamping + */ + setZeroDamping: function () { + + this.data.damping = 0; + this.data.angularDamping = 0; + + }, + + /** + * Transform a world point to local body frame. + * + * @method Phaser.Physics.P2.Body#toLocalFrame + * @param {Float32Array|Array} out - The vector to store the result in. + * @param {Float32Array|Array} worldPoint - The input world vector. + */ + toLocalFrame: function (out, worldPoint) { + + return this.data.toLocalFrame(out, worldPoint); + + }, + + /** + * Transform a local point to world frame. + * + * @method Phaser.Physics.P2.Body#toWorldFrame + * @param {Array} out - The vector to store the result in. + * @param {Array} localPoint - The input local vector. + */ + toWorldFrame: function (out, localPoint) { + + return this.data.toWorldFrame(out, localPoint); + + }, + + /** + * This will rotate the Body by the given speed to the left (counter-clockwise). + * + * @method Phaser.Physics.P2.Body#rotateLeft + * @param {number} speed - The speed at which it should rotate. + */ + rotateLeft: function (speed) { + + this.data.angularVelocity = this.world.pxm(-speed); + + }, + + /** + * This will rotate the Body by the given speed to the left (clockwise). + * + * @method Phaser.Physics.P2.Body#rotateRight + * @param {number} speed - The speed at which it should rotate. + */ + rotateRight: function (speed) { + + this.data.angularVelocity = this.world.pxm(speed); + + }, + + /** + * Moves the Body forwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveForward + * @param {number} speed - The speed at which it should move forwards. + */ + 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); + + }, + + /** + * Moves the Body backwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveBackward + * @param {number} speed - The speed at which it should move backwards. + */ + 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)); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrust + * @param {number} speed - The speed at which it should thrust. + */ + 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); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustLeft + * @param {number} speed - The speed at which it should move to the left. + */ + thrustLeft: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] += magnitude * Math.cos(angle); + this.data.force[1] += magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustRight + * @param {number} speed - The speed at which it should move to the right. + */ + thrustRight: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] -= magnitude * Math.cos(angle); + this.data.force[1] -= magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#reverse + * @param {number} speed - The speed at which it should reverse. + */ + 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); + + }, + + /** + * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveLeft + * @param {number} speed - The speed at which it should move to the left, in pixels per second. + */ + moveLeft: function (speed) { + + this.data.velocity[0] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveRight + * @param {number} speed - The speed at which it should move to the right, in pixels per second. + */ + moveRight: function (speed) { + + this.data.velocity[0] = this.world.pxmi(speed); + + }, + + /** + * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveUp + * @param {number} speed - The speed at which it should move up, in pixels per second. + */ + moveUp: function (speed) { + + this.data.velocity[1] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveDown + * @param {number} speed - The speed at which it should move down, in pixels per second. + */ + moveDown: function (speed) { + + this.data.velocity[1] = this.world.pxmi(speed); + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#preUpdate + * @protected + */ + preUpdate: function () { + + this.dirty = true; + + if (this.removeNextStep) + { + this.removeFromWorld(); + this.removeNextStep = false; + } + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#postUpdate + * @protected + */ + postUpdate: function () { + + this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x; + this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y; + + if (!this.fixedRotation) + { + this.sprite.rotation = this.data.angle; + } + + if (this.debugBody) + { + this.debugBody.updateSpriteTransform(); + } + + this.dirty = false; + + }, + + /** + * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. + * + * @method Phaser.Physics.P2.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new x position of the Body. + * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. + * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. + */ + reset: function (x, y, resetDamping, resetMass) { + + if (resetDamping === undefined) { resetDamping = false; } + if (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; + + }, + + /** + * Adds this physics body to the world. + * + * @method Phaser.Physics.P2.Body#addToWorld + */ + addToWorld: function () { + + if (this.game.physics.p2._toRemove) + { + for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) + { + if (this.game.physics.p2._toRemove[i] === this) + { + this.game.physics.p2._toRemove.splice(i, 1); + } + } + } + + if (this.data.world !== this.game.physics.p2.world) + { + this.game.physics.p2.addBody(this); + } + + }, + + /** + * Removes this physics body from the world. + * + * @method Phaser.Physics.P2.Body#removeFromWorld + */ + removeFromWorld: function () { + + if (this.data.world === this.game.physics.p2.world) + { + this.game.physics.p2.removeBodyNextStep(this); + } + + }, + + /** + * Destroys this Body and all references it holds to other objects. + * + * @method Phaser.Physics.P2.Body#destroy + */ + destroy: function () { + + this.removeFromWorld(); + + this.clearShapes(); + + this._bodyCallbacks = {}; + this._bodyCallbackContext = {}; + this._groupCallbacks = {}; + this._groupCallbackContext = {}; + + if (this.debugBody) + { + this.debugBody.destroy(true, true); + } + + this.debugBody = null; + + if (this.sprite) + { + this.sprite.body = null; + this.sprite = null; + } + + }, + + /** + * Removes all Shapes from this Body. + * + * @method Phaser.Physics.P2.Body#clearShapes + */ + clearShapes: function () { + + var i = this.data.shapes.length; + + while (i--) + { + this.data.removeShape(this.data.shapes[i]); + } + + this.shapeChanged(); + + }, + + /** + * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#addShape + + * @param {p2.Shape} shape - The shape to add to the body. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Shape} The shape that was added to the body. + */ + addShape: function (shape, offsetX, offsetY, rotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (rotation === undefined) { rotation = 0; } + + this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); + this.shapeChanged(); + + return shape; + + }, + + /** + * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Circle} The Circle shape that was added to the Body. + */ + addCircle: function (radius, offsetX, offsetY, rotation) { + + var shape = new p2.Circle({ radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addRectangle + * @param {number} width - The width of the rectangle in pixels. + * @param {number} height - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Box} The shape that was added to the Body. + */ + addRectangle: function (width, height, offsetX, offsetY, rotation) { + + var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addPlane + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Plane} The Plane shape that was added to the Body. + */ + addPlane: function (offsetX, offsetY, rotation) { + + var shape = new p2.Plane(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addParticle + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Particle} The Particle shape that was added to the Body. + */ + addParticle: function (offsetX, offsetY, rotation) { + + var shape = new p2.Particle(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Line shape to this Body. + * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addLine + * @param {number} length - The length of this line (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Line} The Line shape that was added to the Body. + */ + addLine: function (length, offsetX, offsetY, rotation) { + + var shape = new p2.Line({ length: this.world.pxm(length)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Capsule shape to this Body. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCapsule + * @param {number} length - The distance between the end points in pixels. + * @param {number} radius - Radius of the capsule in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Capsule} The Capsule shape that was added to the Body. + */ + addCapsule: function (length, radius, offsetX, offsetY, rotation) { + + var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. + * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. + * + * @method Phaser.Physics.P2.Body#addPolygon + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...]. In the first form **the array will mutate**. + * Or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {boolean} True on success, else false. + */ + addPolygon: function (options, points) { + + options = options || {}; + + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments, 1); + } + + var path = []; + + // Did they pass in a single array of points? + if (points.length === 1 && Array.isArray(points[0])) + { + path = points[0].slice(0); + } + else if (Array.isArray(points[0])) + { + path = points.slice(); + } + else if (typeof points[0] === 'number') + { + // We've a list of numbers + for (var i = 0, len = points.length; i < len; i += 2) + { + path.push([points[i], points[i + 1]]); + } + } + + // top and tail + var idx = path.length - 1; + + if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) + { + path.pop(); + } + + // Now process them into p2 values + for (var p = 0; p < path.length; p++) + { + path[p][0] = this.world.pxmi(path[p][0]); + path[p][1] = this.world.pxmi(path[p][1]); + } + + var result = this.data.fromPolygon(path, options); + + this.shapeChanged(); + + return result; + + }, + + /** + * Remove a shape from the body. Will automatically update the mass properties and bounding radius. + * + * @method Phaser.Physics.P2.Body#removeShape + * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. + * @return {boolean} True if the shape was found and removed, else false. + */ + removeShape: function (shape) { + + var result = this.data.removeShape(shape); + + this.shapeChanged(); + + return result; + }, + + /** + * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + */ + setCircle: function (radius, offsetX, offsetY, rotation) { + + this.clearShapes(); + + return this.addCircle(radius, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. + * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangle + * @param {number} [width=16] - The width of the rectangle in pixels. + * @param {number} [height=16] - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangle: function (width, height, offsetX, offsetY, rotation) { + + if (width === undefined) { width = 16; } + if (height === undefined) { height = 16; } + + this.clearShapes(); + + return this.addRectangle(width, height, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. + * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. + * If no Sprite is given it defaults to using the parent of this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangleFromSprite + * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangleFromSprite: function (sprite) { + + if (sprite === undefined) { sprite = this.sprite; } + + this.clearShapes(); + + return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); + + }, + + /** + * Adds the given Material to all Shapes that belong to this Body. + * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. + * + * @method Phaser.Physics.P2.Body#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. + */ + setMaterial: function (material, shape) { + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].material = material; + } + } + else + { + shape.material = material; + } + + }, + + /** + * Updates the debug draw if any body shapes change. + * + * @method Phaser.Physics.P2.Body#shapeChanged + */ + shapeChanged: function() { + + if (this.debugBody) + { + this.debugBody.draw(); + } + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * The shape data format is based on the output of the + * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for + * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor} + * + * @method Phaser.Physics.P2.Body#addPhaserPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. + * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. + * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList + */ + addPhaserPolygon: function (key, object) { + + var data = this.game.cache.getPhysicsData(key, object); + var createdFixtures = []; + + // Cycle through the fixtures + for (var i = 0; i < data.length; i++) + { + var fixtureData = data[i]; + var shapesOfFixture = this.addFixture(fixtureData); + + // Always add to a group + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); + + // if (unique) fixture key is provided + if (fixtureData.fixtureKey) + { + createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; + } + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return createdFixtures; + + }, + + /** + * Add a polygon fixture. This is used during #loadPolygon. + * + * @method Phaser.Physics.P2.Body#addFixture + * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. + * @return {array} An array containing the generated shapes for the given polygon. + */ + addFixture: function (fixtureData) { + + var generatedShapes = []; + + if (fixtureData.circle) + { + var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) }); + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + var offset = p2.vec2.create(); + offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); + offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); + + this.data.addShape(shape, offset); + generatedShapes.push(shape); + } + else + { + var polygons = fixtureData.polygons; + var cm = p2.vec2.create(); + + for (var i = 0; i < polygons.length; i++) + { + var shapes = polygons[i]; + var vertices = []; + + for (var s = 0; s < shapes.length; s += 2) + { + vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); + } + + var shape = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== shape.vertices.length; j++) + { + var v = shape.vertices[j]; + p2.vec2.sub(v, v, shape.centerOfMass); + } + + p2.vec2.scale(cm, shape.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + shape.updateTriangles(); + shape.updateCenterOfMass(); + shape.updateBoundingRadius(); + + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + this.data.addShape(shape, cm); + + generatedShapes.push(shape); + } + } + + return generatedShapes; + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * + * As well as reading the data from the Cache you can also pass `null` as the first argument and a + * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance. + * + * For more details see the format of the Lime / Corona Physics Editor export. + * + * @method Phaser.Physics.P2.Body#loadPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the + * data as the 2nd argument. + * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from, + * or if key is null pass the actual physics data object itself as this parameter. + * @param {number} [scale=1] - Optionally resize the loaded polygon. + * @return {boolean} True on success, else false. + */ + loadPolygon: function (key, object, scale) { + + if (key === null) + { + var data = object; + } + else + { + var data = this.game.cache.getPhysicsData(key, object); + } + + if (typeof scale !== "number") + { + scale = 1; + } + + // We've multiple Convex shapes, they should be CCW automatically + var cm = p2.vec2.create(); + + for (var i = 0; i < data.length; i++) + { + var vertices = []; + + for (var s = 0; s < data[i].shape.length; s += 2) + { + vertices.push([ + this.world.pxmi(data[i].shape[s] * scale), + this.world.pxmi(data[i].shape[s + 1] * scale) + ]); + } + + var c = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== c.vertices.length; j++) + { + var v = c.vertices[j]; + p2.vec2.sub(v, v, c.centerOfMass); + } + + p2.vec2.scale(cm, c.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + c.updateTriangles(); + c.updateCenterOfMass(); + c.updateBoundingRadius(); + + this.data.addShape(c, cm); + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return true; + + } + +}; + +Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; + +/** + * Dynamic body. Dynamic bodies body can move and respond to collisions and forces. + * @property DYNAMIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.DYNAMIC = 1; + +/** + * Static body. Static bodies do not move, and they do not respond to forces or collision. + * @property STATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.STATIC = 2; + +/** + * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. + * @property KINEMATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.KINEMATIC = 4; + +/** +* @name Phaser.Physics.P2.Body#static +* @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.STATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#dynamic +* @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#kinematic +* @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.KINEMATIC; + this.mass = 4; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#allowSleep +* @property {boolean} allowSleep - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { + + get: function () { + + return this.data.allowSleep; + + }, + + set: function (value) { + + if (value !== this.data.allowSleep) + { + this.data.allowSleep = value; + } + + } + +}); + +/** +* The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. +* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. +* If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#angle +* @property {number} angle - The angle of this Body in degrees. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); + + }, + + set: function(value) { + + this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#angularDamping +* @property {number} angularDamping - The angular damping acting acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { + + get: function () { + + return this.data.angularDamping; + + }, + + set: function (value) { + + this.data.angularDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularForce +* @property {number} angularForce - The angular force acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { + + get: function () { + + return this.data.angularForce; + + }, + + set: function (value) { + + this.data.angularForce = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularVelocity +* @property {number} angularVelocity - The angular velocity of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { + + get: function () { + + return this.data.angularVelocity; + + }, + + set: function (value) { + + this.data.angularVelocity = value; + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#damping +* @property {number} damping - The linear damping acting on the body in the velocity direction. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { + + get: function () { + + return this.data.damping; + + }, + + set: function (value) { + + this.data.damping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#fixedRotation +* @property {boolean} fixedRotation - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { + + get: function () { + + return this.data.fixedRotation; + + }, + + set: function (value) { + + if (value !== this.data.fixedRotation) + { + this.data.fixedRotation = value; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#inertia +* @property {number} inertia - The inertia of the body around the Z axis.. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { + + get: function () { + + return this.data.inertia; + + }, + + set: function (value) { + + this.data.inertia = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#mass +* @property {number} mass - The mass of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { + + get: function () { + + return this.data.mass; + + }, + + set: function (value) { + + if (value !== this.data.mass) + { + this.data.mass = value; + this.data.updateMassProperties(); + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#motionState +* @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { + + get: function () { + + return this.data.type; + + }, + + set: function (value) { + + if (value !== this.data.type) + { + this.data.type = value; + } + + } + +}); + +/** +* The angle of the Body in radians. +* If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#rotation +* @property {number} rotation - The angle of this Body in radians. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { + + get: function() { + + return this.data.angle; + + }, + + set: function(value) { + + this.data.angle = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#sleepSpeedLimit +* @property {number} sleepSpeedLimit - . +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { + + get: function () { + + return this.data.sleepSpeedLimit; + + }, + + set: function (value) { + + this.data.sleepSpeedLimit = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#x +* @property {number} x - The x coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.data.position[0]); + + }, + + set: function (value) { + + this.data.position[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#y +* @property {number} y - The y coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.data.position[1]); + + }, + + set: function (value) { + + this.data.position[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#id +* @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { + + get: function () { + + return this.data.id; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#debug +* @property {boolean} debug - Enable or disable debug drawing of this body +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { + + get: function () { + + return (this.debugBody !== null); + + }, + + set: function (value) { + + if (value && !this.debugBody) + { + // This will be added to the global space + this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); + } + else if (!value && this.debugBody) + { + this.debugBody.destroy(); + this.debugBody = null; + } + + } + +}); + +/** +* A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. +* Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. +* Also note that when you set this it will only affect Body shapes that already exist. If you then add further shapes to your Body +* after setting this it will *not* proactively set them to collide with the bounds. +* +* @name Phaser.Physics.P2.Body#collideWorldBounds +* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? +* @default true +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { + + get: function () { + + return this._collideWorldBounds; + + }, + + set: function (value) { + + if (value && !this._collideWorldBounds) + { + this._collideWorldBounds = true; + this.updateCollisionMask(); + } + else if (!value && this._collideWorldBounds) + { + this._collideWorldBounds = false; + this.updateCollisionMask(); + } + + } + +}); + +/** +* @author George https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Draws a P2 Body to a Graphics instance for visual debugging. +* Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. +* So use sparingly and rarely (if ever) in production code. +* +* Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you +* manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will +* need to manually adjust its BodyDebug as well. +* +* @class Phaser.Physics.P2.BodyDebug +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. +* @param {object} settings - Settings object. +*/ +Phaser.Physics.P2.BodyDebug = function(game, body, settings) { + + Phaser.Group.call(this, game); + + /** + * @property {object} defaultSettings - Default debug settings. + * @private + */ + var defaultSettings = { + pixelsPerLengthUnit: game.physics.p2.mpx(1), + debugPolygons: false, + lineWidth: 1, + alpha: 0.5 + }; + + this.settings = Object.assign(defaultSettings, settings); + + /** + * @property {number} ppu - Pixels per Length Unit. + */ + this.ppu = this.settings.pixelsPerLengthUnit; + this.ppu = -1 * this.ppu; + + /** + * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. + */ + this.body = body; + + /** + * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. + */ + this.canvas = new Phaser.Graphics(game); + + this.canvas.alpha = this.settings.alpha; + + this.add(this.canvas); + + this.draw(); + + this.updateSpriteTransform(); + +}; + +Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); +Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; + +Object.assign(Phaser.Physics.P2.BodyDebug.prototype, { + + /** + * Core update. + * + * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform + */ + updateSpriteTransform: function() { + + this.position.x = this.body.position[0] * this.ppu; + this.position.y = this.body.position[1] * this.ppu; + this.rotation = this.body.angle; + + }, + + /** + * Draws the P2 shapes to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#draw + */ + draw: function() { + + var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; + + obj = this.body; + sprite = this.canvas; + sprite.clear(); + color = parseInt(this.randomPastelHex(), 16); + lineColor = 0xff0000; + lw = this.lineWidth; + + if (obj instanceof p2.Body && obj.shapes.length) + { + var l = obj.shapes.length; + + i = 0; + + while (i !== l) + { + child = obj.shapes[i]; + offset = child.position || 0; + angle = child.angle || 0; + + if (child instanceof p2.Circle) + { + this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); + } + else if (child instanceof p2.Capsule) + { + this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw); + } + 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.Box) + { + this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); + } + else if (child instanceof p2.Convex) + { + verts = []; + vrot = p2.vec2.create(); + + for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _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]); + } + + i++; + } + } + + }, + + /** + * Draws a p2.Box to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawRectangle + * @private + */ + drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + g.beginFill(fillColor); + g.drawRect(x - w / 2, y - h / 2, w, h); + + }, + + /** + * Draws a p2.Circle to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCircle + * @private + */ + drawCircle: function(g, x, y, angle, radius, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + g.lineStyle(lineWidth, 0x000000, 1); + g.beginFill(color, 1.0); + g.drawCircle(x, y, -radius*2); + g.endFill(); + g.moveTo(x, y); + g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); + + }, + + /** + * Draws a p2.Line to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawLine + * @private + */ + drawLine: function(g, len, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth * 5, color, 1); + g.moveTo(-len / 2, 0); + g.lineTo(len / 2, 0); + + }, + + /** + * Draws a p2.Convex to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawConvex + * @private + */ + drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { + + var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + 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 = [0xff0000, 0x00ff00, 0x0000ff]; + 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, 0x000000, 1); + return g.drawCircle(offset[0], offset[1], lineWidth * 2); + } + + }, + + /** + * Draws a p2.Path to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPath + * @private + */ + drawPath: function(g, path, color, fillColor, lineWidth) { + + var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + if (typeof fillColor === "number") + { + g.beginFill(fillColor); + } + + lastx = null; + lasty = null; + i = 0; + + while (i < path.length) + { + v = path[i]; + x = v[0]; + y = v[1]; + + if (x !== lastx || y !== lasty) + { + if (i === 0) + { + g.moveTo(x, y); + } + else + { + p1x = lastx; + p1y = lasty; + p2x = x; + p2y = y; + p3x = path[(i + 1) % path.length][0]; + p3y = path[(i + 1) % path.length][1]; + area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); + + if (area !== 0) + { + g.lineTo(x, y); + } + } + lastx = x; + lasty = y; + } + + i++; + + } + + if (typeof fillColor === "number") + { + g.endFill(); + } + + if (path.length > 2 && typeof fillColor === "number") + { + g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); + g.lineTo(path[0][0], path[0][1]); + } + + }, + + /** + * Draws a p2.Plane to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPlane + * @private + */ + drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { + + var max, xd, yd; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + + 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); + + }, + + /** + * Draws a p2.Capsule to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCapsule + * @private + */ + drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + // Draw circles at ends + var c = Math.cos(angle); + var s = Math.sin(angle); + + g.beginFill(fillColor, 1); + g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2); + g.drawCircle( len/2*c + x, len/2*s + y, -radius * 2); + g.endFill(); + + // Draw rectangle + g.lineStyle(lineWidth, color, 0); + g.beginFill(fillColor, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.endFill(); + + // Draw lines in between + g.lineStyle(lineWidth, color, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + + }, + + /** + * Picks a random pastel color. + * + * @method Phaser.Physics.P2.BodyDebug#randomPastelHex + * @private + */ + 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); + + }, + + /** + * Converts from RGB to Hex. + * + * @method Phaser.Physics.P2.BodyDebug#rgbToHex + * @private + */ + rgbToHex: function(r, g, b) { + return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); + }, + + /** + * Component to hex conversion. + * + * @method Phaser.Physics.P2.BodyDebug#componentToHex + * @private + */ + componentToHex: function(c) { + + var hex; + hex = c.toString(16); + + if (hex.length === 2) + { + return hex; + } + else + { + return hex + '0'; + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.Spring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restLength=1] - Rest length of the spring. A number > 0. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +*/ +Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restLength === undefined) { restLength = 1; } + if (stiffness === undefined) { stiffness = 100; } + if (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]) ]; + } + + /** + * @property {p2.LinearSpring} data - The actual p2 spring object. + */ + this.data = new p2.LinearSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.RotationalSpring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +*/ +Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restAngle === undefined) { restAngle = null; } + if (stiffness === undefined) { stiffness = 100; } + if (damping === undefined) { damping = 1; } + + if (restAngle) + { + restAngle = world.pxm(restAngle); + } + + var options = { + restAngle: restAngle, + stiffness: stiffness, + damping: damping + }; + + /** + * @property {p2.RotationalSpring} data - The actual p2 spring object. + */ + this.data = new p2.RotationalSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A P2 Material. +* +* \o/ ~ "Because I'm a Material girl" +* +* @class Phaser.Physics.P2.Material +* @constructor +* @param {string} name - The user defined name given to this Material. +*/ +Phaser.Physics.P2.Material = function (name) { + + /** + * @property {string} name - The user defined name given to this Material. + * @default + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Defines a physics material +* +* @class Phaser.Physics.P2.ContactMaterial +* @constructor +* @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. +* @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. +* @param {object} [options] - Additional configuration options. +*/ +Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { + + /** + * @property {number} id - The contact material identifier. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. + */ + + /** + * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. + */ + + /** + * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. + */ + + /** + * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + */ + + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Collision Group +* +* @class Phaser.Physics.P2.CollisionGroup +* @constructor +* @param {number} bitmask - The CollisionGroup bitmask. +*/ +Phaser.Physics.P2.CollisionGroup = function (bitmask) { + + /** + * @property {number} mask - The CollisionGroup bitmask. + */ + this.mask = bitmask; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A constraint that tries to keep the distance between two bodies constant. +* +* @class Phaser.Physics.P2.DistanceConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} distance - The distance to keep between the bodies. +* @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. +* @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. +* @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply. +*/ +Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { + + if (distance === undefined) { distance = 100; } + if (localAnchorA === undefined) { localAnchorA = [0, 0]; } + if (localAnchorB === undefined) { localAnchorB = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + distance = world.pxm(distance); + + localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ]; + localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ]; + + var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce }; + + p2.DistanceConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); +Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.GearConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [angle=0] - The relative angle +* @param {number} [ratio=1] - The gear ratio. +*/ +Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { + + if (angle === undefined) { angle = 0; } + if (ratio === undefined) { ratio = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Locks the relative position between two bodies. +* +* @class Phaser.Physics.P2.LockConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [angle=0] - The angle of bodyB in bodyA's frame. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { + + if (offset === undefined) { offset = [0, 0]; } + if (angle === undefined) { angle = 0; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.PrismaticConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. +* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { + + if (lockRotation === undefined) { lockRotation = true; } + if (anchorA === undefined) { anchorA = [0, 0]; } + if (anchorB === undefined) { anchorB = [0, 0]; } + if (axis === undefined) { axis = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* The pivot points are given in world (pixel) coordinates. +* +* @class Phaser.Physics.P2.RevoluteConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {p2.Body} bodyB - Second connected body. +* @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. +* @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. +*/ +Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + if (worldPivot === undefined) { worldPivot = null; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; + pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; + + if (worldPivot) + { + worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ]; + } + + var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce }; + + p2.RevoluteConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); +Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image Collection is a special tileset containing mulitple images, with no slicing into each image. +* +* Image Collections are normally created automatically when Tiled data is loaded. +* +* @class Phaser.ImageCollection +* @constructor +* @param {string} name - The name of the image collection in the map data. +* @param {integer} firstgid - The first image index this image collection contains. +* @param {integer} [width=32] - Width of widest image (in pixels). +* @param {integer} [height=32] - Height of tallest image (in pixels). +* @param {integer} [margin=0] - The margin around all images in the collection (in pixels). +* @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). +* @param {object} [properties={}] - Custom Image Collection properties. +*/ +Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Image Collection. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of the widest image (in pixels). + * @property {integer} imageWidth + * @readonly + */ + this.imageWidth = width | 0; + + /** + * The height of the tallest image (in pixels). + * @property {integer} imageHeight + * @readonly + */ + this.imageHeight = height | 0; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageMarge + * @readonly + */ + // Modified internally + this.imageMargin = margin | 0; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageSpacing + * @readonly + */ + this.imageSpacing = spacing | 0; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached images that are a part of this collection. + * @property {array} images + * @readonly + */ + // Modified internally + this.images = []; + + /** + * The total number of images in the image collection. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; +}; + +Phaser.ImageCollection.prototype = { + + /** + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.ImageCollection#containsImageIndex + * @param {integer} imageIndex - The image index to search for. + * @return {boolean} True if this Image Collection contains the given index. + */ + containsImageIndex: function (imageIndex) { + + return ( + imageIndex >= this.firstgid && + imageIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Add an image to this Image Collection. + * + * @method Phaser.ImageCollection#addImage + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + */ + addImage: function (gid, image) { + + this.images.push({ gid: gid, image: image }); + this.total++; + + } + +}; + +Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile is a representation of a single tile within the Tilemap. +* +* @class Phaser.Tile +* @constructor +* @param {object} layer - The layer in the Tilemap data that this tile belongs to. +* @param {number} index - The index of this tile type in the core map data. +* @param {number} x - The x coordinate of this tile. +* @param {number} y - The y coordinate of this tile. +* @param {number} width - Width of the tile. +* @param {number} height - Height of the tile. +*/ +Phaser.Tile = function (layer, index, x, y, width, height) { + + /** + * @property {object} layer - The layer in the Tilemap data that this tile belongs to. + */ + this.layer = layer; + + /** + * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. + */ + this.index = index; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.x = x; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.y = y; + + /** + * @property {number} rotation - The rotation angle of this tile. + */ + this.rotation = 0; + + /** + * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not. + */ + this.flipped = false; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.worldX = x * width; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.worldY = y * height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.height = height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.centerX = Math.abs(width / 2); + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.centerY = Math.abs(height / 2); + + /** + * @property {number} alpha - The alpha value at which this tile is drawn to the canvas. + */ + this.alpha = 1; + + /** + * @property {object} properties - Tile specific properties. + */ + this.properties = {}; + + /** + * @property {boolean} scanned - Has this tile been walked / turned into a poly? + */ + this.scanned = false; + + /** + * @property {boolean} faceTop - Is the top of this tile an interesting edge? + */ + this.faceTop = false; + + /** + * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge? + */ + this.faceBottom = false; + + /** + * @property {boolean} faceLeft - Is the left of this tile an interesting edge? + */ + this.faceLeft = false; + + /** + * @property {boolean} faceRight - Is the right of this tile an interesting edge? + */ + this.faceRight = false; + + /** + * @property {boolean} collideLeft - Indicating collide with any object on the left. + * @default + */ + this.collideLeft = false; + + /** + * @property {boolean} collideRight - Indicating collide with any object on the right. + * @default + */ + this.collideRight = false; + + /** + * @property {boolean} collideUp - Indicating collide with any object on the top. + * @default + */ + this.collideUp = false; + + /** + * @property {boolean} collideDown - Indicating collide with any object on the bottom. + * @default + */ + this.collideDown = false; + + /** + * @property {function} collisionCallback - Tile collision callback. + * @default + */ + this.collisionCallback = null; + + /** + * @property {object} collisionCallbackContext - The context in which the collision callback will be called. + * @default + */ + this.collisionCallbackContext = this; + + /** + * @property {boolean} debug + * @default + */ + this.debug = false; + +}; + +Phaser.Tile.prototype = { + + /** + * Check if the given x and y world coordinates are within this Tile. + * + * @method Phaser.Tile#containsPoint + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ + containsPoint: function (x, y) { + + return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom); + + }, + + /** + * Check for intersection with this tile. + * + * @method Phaser.Tile#intersects + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + */ + 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; + + }, + + /** + * Set a callback to be called when this tile is hit by an object. + * The callback must true true for collision processing to take place. + * + * @method Phaser.Tile#setCollisionCallback + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + */ + setCollisionCallback: function (callback, context) { + + this.collisionCallback = callback; + this.collisionCallbackContext = context; + + }, + + /** + * Clean up memory. + * + * @method Phaser.Tile#destroy + */ + destroy: function () { + + this.collisionCallback = null; + this.collisionCallbackContext = null; + this.properties = null; + + }, + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tile#setCollision + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} right - Indicating collide with any object on the right. + * @param {boolean} up - Indicating collide with any object on the top. + * @param {boolean} down - Indicating collide with any object on the bottom. + */ + setCollision: function (left, right, up, down) { + + this.collideLeft = left; + this.collideRight = right; + this.collideUp = up; + this.collideDown = down; + + this.faceLeft = left; + this.faceRight = right; + this.faceTop = up; + this.faceBottom = down; + + }, + + /** + * Reset collision status flags. + * + * @method Phaser.Tile#resetCollision + */ + 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; + + }, + + /** + * Is this tile interesting? + * + * @method Phaser.Tile#isInteresting + * @param {boolean} collides - If true will check any collides value. + * @param {boolean} faces - If true will check any face value. + * @return {boolean} True if the Tile is interesting, otherwise false. + */ + isInteresting: function (collides, faces) { + + if (collides && faces) + { + // Does this tile have any collide flags OR interesting face? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback); + } + else if (collides) + { + // Does this tile collide? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + else if (faces) + { + // Does this tile have an interesting face? + return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); + } + + return false; + + }, + + /** + * Copies the tile data and properties from the given tile to this tile. + * + * @method Phaser.Tile#copy + * @param {Phaser.Tile} tile - The tile to copy from. + */ + 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; + +/** +* @name Phaser.Tile#collides +* @property {boolean} collides - True if this tile can collide on any of its faces. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "collides", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + +}); + +/** +* @name Phaser.Tile#canCollide +* @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "canCollide", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); + } + +}); + +/** +* @name Phaser.Tile#left +* @property {number} left - The x value in pixels. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "left", { + + get: function () { + return this.worldX; + } + +}); + +/** +* @name Phaser.Tile#right +* @property {number} right - The sum of the x and width properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "right", { + + get: function () { + return this.worldX + this.width; + } + +}); + +/** +* @name Phaser.Tile#top +* @property {number} top - The y value. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "top", { + + get: function () { + return this.worldY; + } + +}); + +/** +* @name Phaser.Tile#bottom +* @property {number} bottom - The sum of the y and height properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "bottom", { + + get: function () { + return this.worldY + this.height; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. +* +* Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org +* +* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. +* When using CSV data you must provide the key and the tileWidth and tileHeight parameters. +* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. +* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. +* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. +* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. +* +* @class Phaser.Tilemap +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. +* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +*/ +Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {string} key - The key of this map data in the Phaser.Cache. + */ + this.key = key; + + var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height); + + if (data === null) + { + return; + } + + /** + * @property {number} width - The width of the map (in tiles). + */ + this.width = data.width; + + /** + * @property {number} height - The height of the map (in tiles). + */ + this.height = data.height; + + /** + * @property {number} tileWidth - The base width of the tiles in the map (in pixels). + */ + this.tileWidth = data.tileWidth; + + /** + * @property {number} tileHeight - The base height of the tiles in the map (in pixels). + */ + this.tileHeight = data.tileHeight; + + /** + * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + */ + this.orientation = data.orientation; + + /** + * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + */ + this.format = data.format; + + /** + * @property {number} version - The version of the map data (as specified in Tiled, usually 1). + */ + this.version = data.version; + + /** + * @property {object} properties - Map specific properties as specified in Tiled. + */ + this.properties = data.properties; + + /** + * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth. + */ + this.widthInPixels = data.widthInPixels; + + /** + * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight. + */ + this.heightInPixels = data.heightInPixels; + + /** + * @property {array} layers - An array of Tilemap layer data. + */ + this.layers = data.layers; + + /** + * @property {array} tilesets - An array of Tilesets. + */ + this.tilesets = data.tilesets; + + /** + * @property {array} imagecollections - An array of Image Collections. + */ + this.imagecollections = data.imagecollections; + + /** + * @property {array} tiles - The super array of Tiles. + */ + this.tiles = data.tiles; + + /** + * @property {array} objects - An array of Tiled Object Layers. + */ + this.objects = data.objects; + + /** + * @property {array} collideIndexes - An array of tile indexes that collide. + */ + this.collideIndexes = []; + + /** + * @property {array} collision - An array of collision data (polylines, etc). + */ + this.collision = data.collision; + + /** + * @property {array} images - An array of Tiled Image Layers. + */ + this.images = data.images; + + /** + * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data. + */ + this.enableDebug = false; + + /** + * @property {number} currentLayer - The current layer. + */ + this.currentLayer = 0; + + /** + * @property {array} debugMap - Map data used for debug values only. + */ + this.debugMap = []; + + /** + * @property {array} _results - Internal var. + * @private + */ + this._results = []; + + /** + * @property {number} _tempA - Internal var. + * @private + */ + this._tempA = 0; + + /** + * @property {number} _tempB - Internal var. + * @private + */ + this._tempB = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.CSV = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.TILED_JSON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.NORTH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.EAST = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.SOUTH = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.WEST = 3; + +Phaser.Tilemap.prototype = { + + /** + * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. + * + * @method Phaser.Tilemap#create + * @param {string} name - The name of the default layer of the map. + * @param {number} width - The width of the map in tiles. + * @param {number} height - The height of the map in tiles. + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + create: function (name, width, height, tileWidth, tileHeight, group) { + + if (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); + + }, + + /** + * Sets the base tile size for the map. + * + * @method Phaser.Tilemap#setTileSize + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + */ + setTileSize: function (tileWidth, tileHeight) { + + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.widthInPixels = this.width * tileWidth; + this.heightInPixels = this.height * tileHeight; + + }, + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. + * + * @method Phaser.Tilemap#addTilesetImage + * @param {string} tileset - The name of the tileset as specified in the map data. + * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset. + * If `undefined` or `null` it will look for an image with a key matching the tileset parameter. + * You can also pass in a BitmapData which can be used instead of an Image. + * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. + * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. + * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. + * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. + * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. + * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed. + */ + addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { + + if (tileset === undefined) { return null; } + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (gid === undefined) { gid = 0; } + + // In-case we're working from a blank map + if (tileWidth === 0) + { + tileWidth = 32; + } + + if (tileHeight === 0) + { + tileHeight = 32; + } + + var img = null; + + if (key === undefined || key === null) + { + key = tileset; + } + + if (key instanceof Phaser.BitmapData) + { + img = key.canvas; + } + else + { + if (!this.game.cache.checkImageKey(key)) + { + console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"'); + return null; + } + + img = this.game.cache.getImage(key); + } + + var idx = this.getTilesetIndex(tileset); + + if (idx === null && this.format === Phaser.Tilemap.TILED_JSON) + { + console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + tileset + '"'); + console.log('Tilesets: ', this.tilesets); + return null; + } + + if (this.tilesets[idx]) + { + this.tilesets[idx].setImage(img); + return this.tilesets[idx]; + } + else + { + var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {}); + + newSet.setImage(img); + + 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; t < gid + newSet.total; t++) + { + this.tiles[t] = [x, y, i]; + + x += tileWidth + tileSpacing; + + count++; + + if (count === newSet.total) + { + break; + } + + countX++; + + if (countX === newSet.columns) + { + x = tileMargin; + y += tileHeight + tileSpacing; + + countX = 0; + countY++; + + if (countY === newSet.rows) + { + break; + } + } + } + + return newSet; + + } + + return null; + + }, + + /** + * Creates a Sprite for every {@link http://doc.mapeditor.org/reference/tmx-map-format/#object object} matching the `gid` argument. You can optionally specify the group that the Sprite will be created in. If none is + * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to + * configure Sprite properties from within the map editor. For example giving an object a property of `alpha: 0.5` in the map editor will duplicate that when the + * Sprite is created. You could also give it a value like: `body.velocity.x: 100` to set it moving automatically. + * + * The `gid` argument is matched against: + * + * 1. For a tile object, the tile identifier (`gid`); or + * 2. The object's unique ID (`id`); or + * 3. The object's `name` (a string) + * + * @method Phaser.Tilemap#createFromObjects + * @param {string} name - The name of the Object Group to create Sprites from. + * @param {number|string} gid - The object's tile reference (gid), unique ID (id) or name. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. + * @param {boolean} [exists=true] - The default exists state of the Sprite. + * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. + * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. + * @param {boolean} [adjustSize=true] - By default the width and height of the objects are transferred to the sprite. This parameter controls that behavior. + */ + createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY, adjustSize) { + + if (exists === undefined) { exists = true; } + if (autoCull === undefined) { autoCull = false; } + if (group === undefined) { group = this.game.world; } + if (CustomClass === undefined) { CustomClass = Phaser.Sprite; } + if (adjustY === undefined) { adjustY = true; } + if (adjustSize === undefined) { adjustSize = true; } + + if (!this.objects[name]) + { + console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name); + console.log('Objects: ', this.objects); + return; + } + + for (var i = 0; i < this.objects[name].length; i++) + { + var found = false; + var obj = this.objects[name][i]; + + if (obj.gid !== undefined && typeof gid === 'number' && obj.gid === gid) + { + found = true; + } + else if (obj.id !== undefined && typeof gid === 'number' && obj.id === gid) + { + found = true; + } + else if (obj.name !== undefined && typeof gid === 'string' && obj.name === gid) + { + found = true; + } + + if (found) + { + var sprite = new CustomClass(this.game, parseFloat(obj.x, 10), parseFloat(obj.y, 10), key, frame); + + sprite.name = obj.name; + sprite.autoCull = autoCull; + sprite.exists = exists; + sprite.visible = obj.visible; + + if (adjustSize) + { + if (obj.width) + { + sprite.width = obj.width; + } + + if (obj.height) + { + sprite.height = obj.height; + } + } + + if (obj.rotation) + { + sprite.angle = obj.rotation; + } + + if (adjustY) + { + sprite.y -= sprite.height; + } + + group.add(sprite); + + for (var property in obj.properties) + { + group.set(sprite, property, obj.properties[property], false, false, 0, true); + } + } + } + + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the map data. + * You can specify the group that the Sprite will be created in. If none is given it will be created in the World. + * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special + * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemap#createFromTiles + * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from. + * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. + * @return {integer} The number of Sprites that were created. + */ + createFromTiles: function (tiles, replacements, key, layer, group, properties) { + + if (typeof tiles === 'number') { tiles = [tiles]; } + + if (replacements === undefined || replacements === null) + { + replacements = []; + } + else if (typeof replacements === 'number') + { + replacements = [replacements]; + } + + layer = this.getLayer(layer); + + if (group === undefined) { group = this.game.world; } + if (properties === undefined) { properties = {}; } + + if (properties.customClass === undefined) + { + properties.customClass = Phaser.Sprite; + } + + if (properties.adjustY === undefined) + { + properties.adjustY = true; + } + + var lw = this.layers[layer].width; + var lh = this.layers[layer].height; + + this.copy(0, 0, lw, lh, layer); + + if (this._results.length < 2) + { + return 0; + } + + var total = 0; + var sprite; + + for (var i = 1, len = this._results.length; i < len; i++) + { + if (tiles.indexOf(this._results[i].index) !== -1) + { + sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key); + + for (var property in properties) + { + sprite[property] = properties[property]; + } + + group.add(sprite); + total++; + } + + } + + if (replacements.length === 1) + { + // Assume 1 replacement for all types of tile given + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer); + } + } + else if (replacements.length > 1) + { + // Assume 1 for 1 mapping + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer); + } + } + + return total; + + }, + + /** + * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. + * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. + * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. + * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. + * + * @method Phaser.Tilemap#createLayer + * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. + * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. + * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. + * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. + */ + createLayer: function (layer, width, height, group) { + + // Add Buffer support for the left of the canvas + + if (width === undefined) { width = this.game.width; } + if (height === undefined) { height = this.game.height; } + if (group === undefined) { group = this.game.world; } + + var index = layer; + + if (typeof layer === 'string') + { + index = this.getLayerIndex(layer); + } + + if (index === null || index > this.layers.length) + { + console.warn('Tilemap.createLayer: Invalid layer ID given: "' + layer + '"'); + console.log('Layers: ', this.layers); + return; + } + + // Sort out the display dimensions, so they never render too much, or too little. + + if (width === undefined || width <= 0) + { + width = Math.min(this.game.width, this.layers[index].widthInPixels); + } + else if (width > this.game.width) + { + width = this.game.width; + } + + if (height === undefined || height <= 0) + { + height = Math.min(this.game.height, this.layers[index].heightInPixels); + } + else if (height > this.game.height) + { + height = this.game.height; + } + + if (this.enableDebug) + { + console.group('Tilemap.createLayer'); + console.log('Name:', this.layers[index].name); + console.log('Size:', width, 'x', height); + console.log('Tileset:', this.tilesets[0].name, 'index:', index); + } + + var rootLayer = group.add(new Phaser.TilemapLayer(this.game, this, index, width, height)); + + if (this.enableDebug) + { + console.groupEnd(); + } + + return rootLayer; + + }, + + + /** + * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. + * + * @method Phaser.Tilemap#createBlankLayer + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {number} width - The width of the layer in tiles. + * @param {number} height - The height of the layer in tiles. + * @param {number} tileWidth - The width of the tiles the layer uses for calculations. + * @param {number} tileHeight - The height of the tiles the layer uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) { + + if (group === undefined) { group = this.game.world; } + + if (this.getLayerIndex(name) !== null) + { + console.warn('Tilemap.createBlankLayer: Layer with matching name already exists: ' + name); + 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; y < height; y++) + { + row = []; + + for (var x = 0; x < width; x++) + { + row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight)); + } + + output.push(row); + } + + layer.data = output; + + this.layers.push(layer); + + this.currentLayer = this.layers.length - 1; + + var w = layer.widthInPixels; + var h = layer.heightInPixels; + + if (w > this.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); + + }, + + /** + * Gets the layer index based on the layers name. + * + * @method Phaser.Tilemap#getIndex + * @protected + * @param {array} location - The local array to search. + * @param {string} name - The name of the array element to get. + * @return {number} The index of the element in the array, or null if not found. + */ + getIndex: function (location, name) { + + for (var i = 0; i < location.length; i++) + { + if (location[i].name === name) + { + return i; + } + } + + return null; + + }, + + /** + * Gets the layer index based on its name. + * + * @method Phaser.Tilemap#getLayerIndex + * @param {string} name - The name of the layer to get. + * @return {number} The index of the layer in this tilemap, or null if not found. + */ + getLayerIndex: function (name) { + + return this.getIndex(this.layers, name); + + }, + + /** + * Gets the tileset index based on its name. + * + * @method Phaser.Tilemap#getTilesetIndex + * @param {string} name - The name of the tileset to get. + * @return {number} The index of the tileset in this tilemap, or null if not found. + */ + getTilesetIndex: function (name) { + + return this.getIndex(this.tilesets, name); + + }, + + /** + * Gets the image index based on its name. + * + * @method Phaser.Tilemap#getImageIndex + * @param {string} name - The name of the image to get. + * @return {number} The index of the image in this tilemap, or null if not found. + */ + getImageIndex: function (name) { + + return this.getIndex(this.images, name); + + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileIndexCallback + * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileIndexCallback: function (indexes, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes]; + } + else + { + // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much + // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit. + this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext }; + } + } + else + { + for (var i = 0, len = indexes.length; i < len; i++) + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes[i]]; + } + else + { + this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext }; + } + } + } + + }, + + /** + * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileLocationCallback + * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} width - The width of the area to copy (given in tiles, not pixels) + * @param {number} height - The height of the area to copy (given in tiles, not pixels) + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].setCollisionCallback(callback, callbackContext); + } + + }, + + /** + * Sets collision on the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [2, 3, 15, 20]. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * Collision-enabled tiles can be collided against Sprites using {@link Phaser.Physics.Arcade#collide}. + * + * You can verify the collision faces by enabling {@link Phaser.TilemapLayer#debug}. + * + * @method Phaser.Tilemap#setCollision + * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollision: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + return this.setCollisionByIndex(indexes, collides, layer, true); + } + else if (Array.isArray(indexes)) + { + // Collide all of the IDs given in the indexes array + for (var i = 0; i < indexes.length; i++) + { + this.setCollisionByIndex(indexes[i], collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + } + + }, + + /** + * Sets collision on a range of tiles where the tile IDs increment sequentially. + * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionBetween + * @param {number} start - The first index of the tile to be set for collision. + * @param {number} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionBetween: function (start, stop, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (start > stop) + { + return; + } + + for (var index = start; index <= stop; index++) + { + this.setCollisionByIndex(index, collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision on all tiles in the given layer, except for the IDs of those in the given array. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionByExclusion + * @param {array} indexes - An array of the tile IDs to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByExclusion: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + // Collide everything, except the IDs given in the indexes array + for (var i = 0, len = this.tiles.length; i < len; i++) + { + if (indexes.indexOf(i) === -1) + { + this.setCollisionByIndex(i, collides, layer, false); + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision values on a tile in the set. + * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. + * + * @method Phaser.Tilemap#setCollisionByIndex + * @protected + * @param {number} index - The index of the tile on the layer. + * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile. + * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByIndex: function (index, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (layer === undefined) { layer = this.currentLayer; } + if (recalculate === undefined) { recalculate = true; } + + if (collides) + { + this.collideIndexes.push(index); + } + else + { + var i = this.collideIndexes.indexOf(index); + + if (i > -1) + { + this.collideIndexes.splice(i, 1); + } + } + + for (var y = 0; y < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile && tile.index === index) + { + if (collides) + { + tile.setCollision(true, true, true, true); + } + else + { + tile.resetCollision(); + } + + tile.faceTop = collides; + tile.faceBottom = collides; + tile.faceLeft = collides; + tile.faceRight = collides; + } + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + return layer; + + }, + + /** + * Gets the TilemapLayer index as used in the setCollision calls. + * + * @method Phaser.Tilemap#getLayer + * @protected + * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer. + * @return {number} The TilemapLayer index. + */ + getLayer: function (layer) { + + if (layer === undefined) + { + layer = this.currentLayer; + } + else if (typeof layer === 'string') + { + var layerArg = layer; + + layer = this.getLayerIndex(layer); + + if (!layer) + { + console.warn('No such layer name: ' + layerArg); + } + } + else if (layer instanceof Phaser.TilemapLayer) + { + layer = layer.index; + } + + return layer; + + }, + + /** + * Turn off/on the recalculation of faces for tile or collision updates. + * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. + * + * @method Phaser.Tilemap#setPreventRecalculate + * @param {boolean} value - If true it will put the recalculation on hold. + */ + setPreventRecalculate: function (value) { + + if (value === true && this.preventingRecalculate !== true) + { + this.preventingRecalculate = true; + this.needToRecalculate = {}; + } + + if (value === false && this.preventingRecalculate === true) + { + this.preventingRecalculate = false; + + for (var i in this.needToRecalculate) + { + this.calculateFaces(i); + } + + this.needToRecalculate = false; + } + + }, + + /** + * Internal function. + * + * @method Phaser.Tilemap#calculateFaces + * @protected + * @param {number} layer - The index of the TilemapLayer to operate on. + */ + calculateFaces: function (layer) { + + if (this.preventingRecalculate) + { + this.needToRecalculate[layer] = true; + return; + } + + var above = null; + var below = null; + var left = null; + var right = null; + + for (var y = 0, h = this.layers[layer].height; y < h; y++) + { + for (var x = 0, w = this.layers[layer].width; x < w; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile) + { + above = this.getTileAbove(layer, x, y); + below = this.getTileBelow(layer, x, y); + left = this.getTileLeft(layer, x, y); + right = this.getTileRight(layer, x, y); + + if (tile.collides) + { + tile.faceTop = true; + tile.faceBottom = true; + tile.faceLeft = true; + tile.faceRight = true; + } + + if (above && above.collides) + { + // There is a tile above this one that also collides, so the top of this tile is no longer interesting + tile.faceTop = false; + } + + if (below && below.collides) + { + // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting + tile.faceBottom = false; + } + + if (left && left.collides) + { + // There is a tile left this one that also collides, so the left of this tile is no longer interesting + tile.faceLeft = false; + } + + if (right && right.collides) + { + // There is a tile right this one that also collides, so the right of this tile is no longer interesting + tile.faceRight = false; + } + } + } + } + + }, + + /** + * Gets the tile above the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileAbove + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileAbove: function (layer, x, y) { + + if (y > 0) + { + return this.layers[layer].data[y - 1][x]; + } + + return null; + + }, + + /** + * Gets the tile below the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileBelow + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileBelow: function (layer, x, y) { + + if (y < this.layers[layer].height - 1) + { + return this.layers[layer].data[y + 1][x]; + } + + return null; + + }, + + /** + * Gets the tile to the left of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileLeft + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileLeft: function (layer, x, y) { + + if (x > 0) + { + return this.layers[layer].data[y][x - 1]; + } + + return null; + + }, + + /** + * Gets the tile to the right of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileRight + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileRight: function (layer, x, y) { + + if (x < this.layers[layer].width - 1) + { + return this.layers[layer].data[y][x + 1]; + } + + return null; + + }, + + /** + * Sets the current layer to the given index. + * + * @method Phaser.Tilemap#setLayer + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + */ + setLayer: function (layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer]) + { + this.currentLayer = layer; + } + + }, + + /** + * Checks if there is a tile at the given location. + * + * @method Phaser.Tilemap#hasTile + * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels) + * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + * @return {boolean} True if there is a tile at the given location, otherwise false. + */ + hasTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined) + { + return false; + } + + return (this.layers[layer].data[y][x].index > -1); + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. + * + * @method Phaser.Tilemap#removeTile + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.hasTile(x, y, layer)) + { + var tile = this.layers[layer].data[y][x]; + + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight); + + this.layers[layer].dirty = true; + + this.calculateFaces(layer); + + return tile; + } + } + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#removeTileWorldXY + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTileWorldXY: function (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.removeTile(x, y, layer); + + }, + + /** + * Puts a tile of the given index value at the coordinate specified. + * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. + * + * @method Phaser.Tilemap#putTile + * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map. + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + putTile: function (tile, x, y, layer) { + + if (tile === null) + { + return this.removeTile(x, y, layer); + } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + var index; + + if (tile instanceof Phaser.Tile) + { + index = tile.index; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].copy(tile); + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height); + } + } + else + { + index = tile; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].index = index; + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight); + } + } + + if (this.collideIndexes.indexOf(index) > -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; + + }, + + /** + * Puts a tile into the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#putTileWorldXY + * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object. + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + 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); + + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. + * If no match is found it returns null. + * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. + * + * @method Phaser.Tilemap#searchTileIndex + * @param {number} index - The tile index value to search for. + * @param {number} [skip=0] - The number of times to skip a matching tile before returning. + * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @return {Phaser.Tile} The first (or n skipped) tile with the matching index. + */ + searchTileIndex: function (index, skip, reverse, layer) { + + if (skip === undefined) { skip = 0; } + if (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 < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + if (this.layers[layer].data[y][x].index === index) + { + if (c === skip) + { + return this.layers[layer].data[y][x]; + } + else + { + c++; + } + } + } + } + } + + return null; + + }, + + /** + * Gets a tile from the Tilemap Layer. The coordinates are given in tile values. + * + * @method Phaser.Tilemap#getTile + * @param {number} x - X position to get the tile from (given in tile units, not pixels) + * @param {number} y - Y position to get the tile from (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTile: function (x, y, layer, nonNull) { + + if (nonNull === undefined) { nonNull = false; } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.layers[layer].data[y][x].index === -1) + { + if (nonNull) + { + return this.layers[layer].data[y][x]; + } + else + { + return null; + } + } + else + { + return this.layers[layer].data[y][x]; + } + } + else + { + return null; + } + + }, + + /** + * Gets a tile from the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#getTileWorldXY + * @param {number} x - X position to get the tile from (given in pixels) + * @param {number} y - Y position to get the tile from (given in pixels) + * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used. + * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates. + */ + getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) { + + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + + layer = this.getLayer(layer); + + x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; + y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; + + return this.getTile(x, y, layer, nonNull); + + }, + + /** + * Copies all of the tiles in the given rectangular block into the tilemap data buffer. + * + * @method Phaser.Tilemap#copy + * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} width - The width of the area to copy (given in tiles, not pixels) + * @param {integer} height - The height of the area to copy (given in tiles, not pixels) + * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from. + * @return {array} An array of the tiles that were copied. + */ + copy: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + if (!this.layers[layer]) + { + this._results.length = 0; + return; + } + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.layers[layer].width; } + if (height === undefined) { height = this.layers[layer].height; } + + if (x < 0) + { + x = 0; + } + + if (y < 0) + { + y = 0; + } + + if (width > this.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; ty < y + height; ty++) + { + for (var tx = x; tx < x + width; tx++) + { + this._results.push(this.layers[layer].data[ty][tx]); + } + } + + return this._results; + + }, + + /** + * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. + * + * @method Phaser.Tilemap#paste + * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels) + * @param {array} tileblock - The block of tiles to paste. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into. + */ + paste: function (x, y, tileblock, layer) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + layer = this.getLayer(layer); + + if (!tileblock || tileblock.length < 2) + { + return; + } + + // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste + var diffX = x - tileblock[1].x; + var diffY = y - tileblock[1].y; + + for (var i = 1; i < tileblock.length; i++) + { + this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]); + } + + this.layers[layer].dirty = true; + this.calculateFaces(layer); + + }, + + /** + * Scans the given area for tiles with an index matching tileA and swaps them with tileB. + * + * @method Phaser.Tilemap#swap + * @param {number} tileA - First tile index. + * @param {number} tileB - Second tile index. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + swap: function (tileA, tileB, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._tempA = tileA; + this._tempB = tileB; + + this._results.forEach(this.swapHandler, this); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Internal function that handles the swapping of tiles. + * + * @method Phaser.Tilemap#swapHandler + * @private + * @param {number} value + */ + swapHandler: function (value) { + + if (value.index === this._tempA) + { + // Swap A with B + value.index = this._tempB; + } + else if (value.index === this._tempB) + { + // Swap B with A + value.index = this._tempA; + } + + }, + + /** + * For each tile in the given area defined by x/y and width/height run the given callback. + * + * @method Phaser.Tilemap#forEach + * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {number} context - The context under which the callback should be run. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + forEach: function (callback, context, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._results.forEach(callback, context); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. + * + * @method Phaser.Tilemap#replace + * @param {number} source - The tile index value to scan for. + * @param {number} dest - The tile index value to replace found tiles with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + replace: function (source, dest, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + if (this._results[i].index === source) + { + this._results[i].index = dest; + } + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Randomises a set of tiles in a given area. + * + * @method Phaser.Tilemap#random + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + random: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + var idx = this._results[t].index; + + if (indexes.indexOf(idx) === -1) + { + indexes.push(idx); + } + } + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = this.game.rnd.pick(indexes); + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! + * + * @method Phaser.Tilemap#shuffle + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + shuffle: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + indexes.push(this._results[t].index); + } + } + + Phaser.ArrayUtils.shuffle(indexes); + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = indexes[i - 1]; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Fills the given area with the specified tile. + * + * @method Phaser.Tilemap#fill + * @param {number} index - The index of the tile that the area will be filled with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + fill: function (index, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = index; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Removes all layers from this tile map. + * + * @method Phaser.Tilemap#removeAllLayers + */ + removeAllLayers: function () { + + this.layers.length = 0; + this.currentLayer = 0; + + }, + + /** + * Dumps the tilemap data out to the console. + * + * @method Phaser.Tilemap#dump + */ + dump: function () { + + var txt = ''; + var args = ['']; + + for (var y = 0; y < this.layers[this.currentLayer].height; y++) + { + for (var x = 0; x < this.layers[this.currentLayer].width; x++) + { + txt += "%c "; + + if (this.layers[this.currentLayer].data[y][x] > 1) + { + 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); + + }, + + /** + * Removes all layer data from this tile map and nulls the game reference. + * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. + * + * @method Phaser.Tilemap#destroy + */ + destroy: function () { + + this.removeAllLayers(); + this.data = []; + this.game = null; + + } + +}; + +Phaser.Tilemap.prototype.constructor = Phaser.Tilemap; + +/** +* @name Phaser.Tilemap#layer +* @property {number|string|Phaser.TilemapLayer} layer - The current layer object. +*/ +Object.defineProperty(Phaser.Tilemap.prototype, "layer", { + + get: function () { + + return this.layers[this.currentLayer]; + + }, + + set: function (value) { + + if (value !== this.currentLayer) + { + this.setLayer(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. +* +* Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. +* +* By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. +* +* @class Phaser.TilemapLayer +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs. +* @param {integer} index - The index of the TileLayer to render within the Tilemap. +* @param {integer} width - Width of the renderable area of the layer (in pixels). +* @param {integer} height - Height of the renderable area of the layer (in pixels). +*/ +Phaser.TilemapLayer = function (game, tilemap, index, width, height) { + + width |= 0; + height |= 0; + + Phaser.Sprite.call(this, game, 0, 0); + + /** + * The Tilemap to which this layer is bound. + * @property {Phaser.Tilemap} map + * @protected + * @readonly + */ + this.map = tilemap; + + /** + * The index of this layer within the Tilemap. + * @property {number} index + * @protected + * @readonly + */ + this.index = index; + + /** + * The layer object within the Tilemap that this layer represents. + * @property {object} layer + * @protected + * @readonly + */ + this.layer = tilemap.layers[index]; + + /** + * The canvas to which this TilemapLayer draws. + * @property {HTMLCanvasElement} canvas + * @protected + */ + this.canvas = Phaser.CanvasPool.create(this, width, height); + + /** + * The 2d context of the canvas. + * @property {CanvasRenderingContext2D} context + * @private + */ + this.context = this.canvas.getContext('2d'); + + this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas, null, this.game.resolution))); + + /** + * The const type of this object. + * @property {number} type + * @readonly + * @protected + * @default Phaser.TILEMAPLAYER + */ + this.type = Phaser.TILEMAPLAYER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.TILEMAPLAYER; + + /** + * Settings that control standard (non-diagnostic) rendering. + * + * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view. + * This can greatly improve scrolling rendering performance, especially when there are many small tiles. + * It should only be disabled in rare cases. + * + * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas. + * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior + * in some browsers, notably Safari. + * + * @default + */ + this.renderSettings = { + enableScrollDelta: true, + overdrawRatio: 0.20, + copyCanvas: null + }; + + /** + * Enable an additional "debug rendering" pass to display collision information. + * + * @property {boolean} debug + * @default + */ + this.debug = false; + + /** + * @property {boolean} exists - Controls if the core game loop and physics update this game object or not. + */ + this.exists = true; + + /** + * Settings used for debugging and diagnostics. + * + * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. + * + * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. + * + * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. + * + * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. + * + */ + this.debugSettings = { + + missingImageFill: 'rgb(255,255,255)', + debuggedTileOverfill: 'rgba(0,255,0,0.4)', + + forceFullRedraw: true, + + debugAlpha: 0.5, + facingEdgeStroke: 'rgba(0,255,0,1)', + collidingTileOverfill: 'rgba(0,255,0,0.2)' + + }; + + /** + * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). + * @property {number} scrollFactorX + * @public + * @default + */ + this.scrollFactorX = 1; + + /** + * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) + * @property {number} scrollFactorY + * @public + * @default + */ + this.scrollFactorY = 1; + + /** + * If true tiles will be force rendered, even if such is not believed to be required. + * @property {boolean} dirty + * @protected + */ + this.dirty = true; + + /** + * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. + * @property {integer} rayStepRate + * @default + */ + this.rayStepRate = 4; + + /** + * Flag controlling if the layer tiles wrap at the edges. + * @property {boolean} _wrap + * @private + */ + this._wrap = false; + + /** + * Local map data and calculation cache. + * @property {object} _mc + * @private + */ + this._mc = { + + // Used to bypass rendering without reliance on `dirty` and detect changes. + scrollX: 0, + scrollY: 0, + renderWidth: 0, + renderHeight: 0, + + tileWidth: tilemap.tileWidth, + tileHeight: tilemap.tileHeight, + + // Collision width/height (pixels) + // What purpose do these have? Most things use tile width/height directly. + // This also only extends collisions right and down. + cw: tilemap.tileWidth, + ch: tilemap.tileHeight, + + // Cached tilesets from index -> Tileset + tilesets: [] + + }; + + /** + * The current canvas left after scroll is applied. + * @property {number} _scrollX + * @private + */ + this._scrollX = 0; + + /** + * The current canvas top after scroll is applied. + * @property {number} _scrollY + * @private + */ + this._scrollY = 0; + + /** + * The position offset of the layer's tiles. + * @property {Phaser.Point} + */ + this.tileOffset = new Phaser.Point(this.layer.offsetX || 0, this.layer.offsetY || 0); + + /** + * Used for caching the tiles / array of tiles. + * @property {Phaser.Tile[]} _results + * @private + */ + this._results = []; + + if (!game.device.canvasBitBltShift) + { + this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas(); + } + + this.fixedToCamera = true; + +}; + +Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer; + +Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* The shared double-copy canvas, created as needed. +* +* @private +* @static +*/ +Phaser.TilemapLayer.sharedCopyCanvas = null; + +/** +* Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. +* +* Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. +* +* @method Phaser.TilemapLayer#ensureSharedCopyCanvas +* @protected +* @static +*/ +Phaser.TilemapLayer.ensureSharedCopyCanvas = function () { + + if (!this.sharedCopyCanvas) + { + this.sharedCopyCanvas = Phaser.CanvasPool.create(this, 2, 2); + } + + return this.sharedCopyCanvas; + +}; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TilemapLayer#preUpdate +*/ +Phaser.TilemapLayer.prototype.preUpdate = function() { + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.postUpdate. Handles cache updates. +* +* @method Phaser.TilemapLayer#postUpdate +* @protected +*/ +Phaser.TilemapLayer.prototype.postUpdate = function () { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderCanvas function. +* +* @method Phaser.TilemapLayer#_renderCanvas +* @private +*/ +Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderWebGL function. +* +* @method Phaser.TilemapLayer#_renderWebGL +* @private +*/ +Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Destroys this TilemapLayer. +* +* @method Phaser.TilemapLayer#destroy +*/ +Phaser.TilemapLayer.prototype.destroy = function() { + + Phaser.CanvasPool.remove(this); + + Phaser.Component.Destroy.prototype.destroy.call(this); + +}; + +/** +* Resizes the internal canvas and texture frame used by this TilemapLayer. +* +* This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully +* selected times. +* +* Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not +* modified either. You will have to handle both of these things from your game code if required. +* +* @method Phaser.TilemapLayer#resize +* @param {number} width - The new width of the TilemapLayer +* @param {number} height - The new height of the TilemapLayer +*/ +Phaser.TilemapLayer.prototype.resize = function (width, height) { + + this.canvas.width = width; + this.canvas.height = height; + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.texture.baseTexture.width = width; + this.texture.baseTexture.height = height; + + this.texture.baseTexture.dirty(); + this.texture.requiresUpdate = true; + + this.texture._updateUvs(); + + this.dirty = true; + +}; + +/** +* Sets the world size to match the size of this layer. +* +* @method Phaser.TilemapLayer#resizeWorld +* @public +*/ +Phaser.TilemapLayer.prototype.resizeWorld = function () { + + this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y); + +}; + +/** + * Get the X axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getLayerOffsetX + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetX = function () { + + return this.tileOffset.x || ((!this.fixedToCamera) ? this.position.x : 0); + +}; + +/** + * Get the Y axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getTileOffsetY + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetY = function () { + + return this.tileOffset.y || ((!this.fixedToCamera) ? this.position.y : 0); + +}; + +/** +* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixX +* @private +* @param {number} x - x coordinate in camera space +* @return {number} x coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixX = function (x) { + + if (this.scrollFactorX === 1 || (this.scrollFactorX === 0 && this.position.x === 0)) + { + return x; + } + + // This executes if the scrollFactorX is 0 and the x position of the tilemap is off from standard. + if (this.scrollFactorX === 0 && this.position.x !== 0) + { + return x - this.position.x; + } + + return this._scrollX + (x - (this._scrollX / this.scrollFactorX)); + +}; + +/** +* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixX +* @private +* @param {number} x - x coordinate in scrollFactor-adjusted dimensions +* @return {number} x coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixX = function (x) { + + if (this.scrollFactorX === 1) + { + return x; + } + + return (this._scrollX / this.scrollFactorX) + (x - this._scrollX); + +}; + +/** +* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixY +* @private +* @param {number} y - y coordinate in camera space +* @return {number} y coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixY = function (y) { + + if (this.scrollFactorY === 1 || (this.scrollFactorY === 0 && this.position.y === 0)) + { + return y; + } + + // This executes if the scrollFactorY is 0 and the y position of the tilemap is off from standard. + if (this.scrollFactorY === 0 && this.position.y !== 0) + { + return y - this.position.y; + } + + return this._scrollY + (y - (this._scrollY / this.scrollFactorY)); + +}; + +/** +* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixY +* @private +* @param {number} y - y coordinate in scrollFactor-adjusted dimensions +* @return {number} y coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixY = function (y) { + + if (this.scrollFactorY === 1) + { + return y; + } + + return (this._scrollY / this.scrollFactorY) + (y - this._scrollY); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileX +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @return {integer} The X map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileX = function (x) { + + // var tileWidth = this.tileWidth * this.scale.x; + return Math.floor(this._fixX(x) / this._mc.tileWidth); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileY +* @public +* @param {number} y - Y position of the point in target tile (in pixels). +* @return {integer} The Y map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileY = function (y) { + + // var tileHeight = this.tileHeight * this.scale.y; + return Math.floor(this._fixY(y) / this._mc.tileHeight); + +}; + +/** +* Convert a pixel coordinate to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileXY +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @param {number} y - Y position of the point in target tile (in pixels). +* @param {(Phaser.Point|object)} point - The Point/object to update. +* @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set. +*/ +Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) { + + point.x = this.getTileX(x); + point.y = this.getTileY(y); + + return point; + +}; + +/** +* Gets all tiles that intersect with the given line. +* +* @method Phaser.TilemapLayer#getRayCastTiles +* @public +* @param {Phaser.Line} line - The line used to determine which tiles to return. +* @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`. +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {Phaser.Tile[]} An array of Phaser.Tiles. +*/ +Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) { + + if (!stepRate) { stepRate = this.rayStepRate; } + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + // First get all tiles that touch the bounds of the line + var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace); + + if (tiles.length === 0) + { + return []; + } + + // Now we only want the tiles that intersect with the points on this line + var coords = line.coordinatesOnLine(stepRate); + var results = []; + + for (var i = 0; i < tiles.length; i++) + { + for (var t = 0; t < coords.length; t++) + { + var tile = tiles[i]; + var coord = coords[t]; + if (tile.containsPoint(coord[0], coord[1])) + { + results.push(tile); + break; + } + } + } + + return results; + +}; + +/** +* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. +* +* @method Phaser.TilemapLayer#getTiles +* @public +* @param {number} x - X position of the top left corner (in pixels). +* @param {number} y - Y position of the top left corner (in pixels). +* @param {number} width - Width of the area to get (in pixels). +* @param {number} height - Height of the area to get (in pixels). +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {array} An array of Tiles. +*/ +Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) { + + // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all) + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + var fetchAll = !(collides || interestingFace); + + // Adjust the x,y coordinates for scrollFactor + x = this._fixX(x); + y = this._fixY(y); + + // Convert the pixel values into tile coordinates + var tx = Math.floor(x / (this._mc.cw * this.scale.x)); + var ty = Math.floor(y / (this._mc.ch * this.scale.y)); + // Don't just use ceil(width/cw) to allow account for x/y diff within cell + var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx; + var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty; + + while (this._results.length) + { + this._results.pop(); + } + + for (var wy = ty; wy < ty + th; wy++) + { + for (var wx = tx; wx < tx + tw; wx++) + { + var row = this.layer.data[wy]; + + if (row && row[wx]) + { + if (fetchAll || row[wx].isInteresting(collides, interestingFace)) + { + this._results.push(row[wx]); + } + } + } + } + + return this._results.slice(); + +}; + +/** +* Returns the appropriate tileset for the index, updating the internal cache as required. +* This should only be called if `tilesets[index]` evaluates to undefined. +* +* @method Phaser.TilemapLayer#resolveTileset +* @private +* @param {integer} Tile index +* @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping. +*/ +Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) { + + var tilesets = this._mc.tilesets; + + // Try for dense array if reasonable + if (tileIndex < 2000) + { + while (tilesets.length < tileIndex) + { + tilesets.push(undefined); + } + } + + var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2]; + + if (setIndex !== null) + { + var tileset = this.map.tilesets[setIndex]; + + if (tileset && tileset.containsTileIndex(tileIndex)) + { + return (tilesets[tileIndex] = tileset); + } + } + + return (tilesets[tileIndex] = null); + +}; + +/** +* The TilemapLayer caches tileset look-ups. +* +* Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. +* +* @method Phaser.TilemapLayer#resetTilesetCache +* @public +*/ +Phaser.TilemapLayer.prototype.resetTilesetCache = function () { + + var tilesets = this._mc.tilesets; + + while (tilesets.length) + { + tilesets.pop(); + } + +}; + +/** + * This method will set the scale of the tilemap as well as update the underlying block data of this layer. + * + * @method Phaser.TilemapLayer#setScale + * @param {number} [xScale=1] - The scale factor along the X-plane + * @param {number} [yScale] - The scale factor along the Y-plane + */ +Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) { + + xScale = xScale || 1; + yScale = yScale || xScale; + + for (var y = 0; y < this.layer.data.length; y++) + { + var row = this.layer.data[y]; + + for (var x = 0; x < row.length; x++) + { + var tile = row[x]; + + tile.width = this.map.tileWidth * xScale; + tile.height = this.map.tileHeight * yScale; + + tile.worldX = tile.x * tile.width; + tile.worldY = tile.y * tile.height; + } + } + + this.scale.setTo(xScale, yScale); + +}; + +/** +* Shifts the contents of the canvas - does extra math so that different browsers agree on the result. +* +* The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in. +* +* @method Phaser.TilemapLayer#shiftCanvas +* @private +* @param {CanvasRenderingContext2D} context - The context to shift +* @param {integer} x +* @param {integer} y +*/ +Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) { + + var canvas = context.canvas; + var copyW = canvas.width - Math.abs(x); + var copyH = canvas.height - Math.abs(y); + + // When x/y non-negative + var dx = 0; + var dy = 0; + var sx = x; + var sy = y; + + if (x < 0) + { + dx = -x; + sx = 0; + } + + if (y < 0) + { + dy = -y; + sy = 0; + } + + var copyCanvas = this.renderSettings.copyCanvas; + + if (copyCanvas) + { + // Use a second copy buffer, without slice support, for Safari .. again. + // Ensure copy canvas is large enough + if (copyCanvas.width < copyW || copyCanvas.height < copyH) + { + copyCanvas.width = copyW; + copyCanvas.height = copyH; + } + + var copyContext = copyCanvas.getContext('2d'); + copyContext.clearRect(0, 0, copyW, copyH); + copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH); + // clear allows default 'source-over' semantics + context.clearRect(sx, sy, copyW, copyH); + context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH); + } + else + { + // Avoids a second copy but flickers in Safari / Safari Mobile + // Ref. https://github.com/photonstorm/phaser/issues/1439 + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH); + context.restore(); + } + +}; + +/** +* Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor. +* This will constrain the tile coordinates based on wrapping but not physical coordinates. +* +* @method Phaser.TilemapLayer#renderRegion +* @private +* @param {integer} scrollX - Render x offset/scroll. +* @param {integer} scrollY - Render y offset/scroll. +* @param {integer} left - Leftmost column to render. +* @param {integer} top - Topmost row to render. +* @param {integer} right - Rightmost column to render. +* @param {integer} bottom - Bottommost row to render. +*/ +Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) { + + var context = this.context; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var tilesets = this._mc.tilesets; + var lastAlpha = NaN; + + if (!this._wrap) + { + if (left <= right) // Only adjust if going to render + { + left = Math.max(0, left); + right = Math.min(width - 1, right); + } + if (top <= bottom) + { + top = Math.max(0, top); + bottom = Math.min(height - 1, bottom); + } + } + + // top-left pixel of top-left cell + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values. + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + // tx/ty - are pixel coordinates where tile is drawn + // x/y - is cell location, normalized [0..width/height) in loop + // xmax/ymax - remaining cells to render on column/row + var tx, ty, x, y, xmax, ymax; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + + if (!tile || tile.index < 0) + { + continue; + } + + var index = tile.index; + + var set = tilesets[index]; + + if (set === undefined) + { + set = this.resolveTileset(index); + } + + // Setting the globalAlpha is "surprisingly expensive" in Chrome (38) + if (tile.alpha !== lastAlpha && !this.debug) + { + context.globalAlpha = tile.alpha; + lastAlpha = tile.alpha; + } + + if (set) + { + if (tile.rotation || tile.flipped) + { + context.save(); + context.translate(tx + tile.centerX, ty + tile.centerY); + context.rotate(tile.rotation); + + if (tile.flipped) + { + context.scale(-1, 1); + } + + set.draw(context, -tile.centerX, -tile.centerY, index); + context.restore(); + } + else + { + set.draw(context, tx, ty, index); + } + } + else if (this.debugSettings.missingImageFill) + { + context.fillStyle = this.debugSettings.missingImageFill; + context.fillRect(tx, ty, tw, th); + } + + if (tile.debug && this.debugSettings.debuggedTileOverfill) + { + context.fillStyle = this.debugSettings.debuggedTileOverfill; + context.fillRect(tx, ty, tw, th); + } + + } + + } + +}; + +/** +* Shifts the canvas and render damaged edge tiles. +* +* @method Phaser.TilemapLayer#renderDeltaScroll +* @private +*/ +Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds. + + // Start in pixels + var left = 0; + var right = -tw; + var top = 0; + var bottom = -th; + + if (shiftX < 0) // layer moving left, damage right + { + left = renderW + shiftX; // shiftX neg. + right = renderW - 1; + } + else if (shiftX > 0) + { + // left -> 0 + right = shiftX; + } + + if (shiftY < 0) // layer moving down, damage top + { + top = renderH + shiftY; // shiftY neg. + bottom = renderH - 1; + } + else if (shiftY > 0) + { + // top -> 0 + bottom = shiftY; + } + + this.shiftCanvas(this.context, shiftX, shiftY); + + // Transform into tile-space + left = Math.floor((left + scrollX) / tw); + right = Math.floor((right + scrollX) / tw); + top = Math.floor((top + scrollY) / th); + bottom = Math.floor((bottom + scrollY) / th); + + if (left <= right) + { + // Clear left or right edge + this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH); + + var trueTop = Math.floor((0 + scrollY) / th); + var trueBottom = Math.floor((renderH - 1 + scrollY) / th); + this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom); + } + + if (top <= bottom) + { + // Clear top or bottom edge + this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th); + + var trueLeft = Math.floor((0 + scrollX) / tw); + var trueRight = Math.floor((renderW - 1 + scrollX) / tw); + this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom); + } + +}; + +/** +* Clear and render the entire canvas. +* +* @method Phaser.TilemapLayer#renderFull +* @private +*/ +Phaser.TilemapLayer.prototype.renderFull = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + this.context.clearRect(0, 0, renderW, renderH); + + this.renderRegion(scrollX, scrollY, left, top, right, bottom); + +}; + +/** +* Renders the tiles to the layer canvas and pushes to the display. +* +* @method Phaser.TilemapLayer#render +* @protected +*/ +Phaser.TilemapLayer.prototype.render = function () { + + var redrawAll = false; + + if (!this.visible) + { + return; + } + + if (this.dirty || this.layer.dirty) + { + this.layer.dirty = false; + redrawAll = true; + } + + var renderWidth = this.canvas.width; // Use Sprite.width/height? + var renderHeight = this.canvas.height; + + // Scrolling bias; whole pixels only + var scrollX = this._scrollX | 0; + var scrollY = this._scrollY | 0; + + var mc = this._mc; + var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down + var shiftY = mc.scrollY - scrollY; + + if (!redrawAll && + shiftX === 0 && shiftY === 0 && + mc.renderWidth === renderWidth && mc.renderHeight === renderHeight) + { + // No reason to redraw map, looking at same thing and not invalidated. + return; + } + + this.context.save(); + + mc.scrollX = scrollX; + mc.scrollY = scrollY; + + if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight) + { + // Could support automatic canvas resizing + mc.renderWidth = renderWidth; + mc.renderHeight = renderHeight; + } + + if (this.debug) + { + this.context.globalAlpha = this.debugSettings.debugAlpha; + + if (this.debugSettings.forceFullRedraw) + { + redrawAll = true; + } + } + + if (!redrawAll && + this.renderSettings.enableScrollDelta && + (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight)) + { + this.renderDeltaScroll(shiftX, shiftY); + } + else + { + // Too much change or otherwise requires full render + this.renderFull(); + } + + if (this.debug) + { + this.context.globalAlpha = 1; + this.renderDebug(); + } + + this.texture.baseTexture.dirty(); + + this.dirty = false; + + this.context.restore(); + + return true; + +}; + +/** +* Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true. +* +* See `debugSettings` for assorted configuration options. +* +* @method Phaser.TilemapLayer#renderDebug +* @private +*/ +Phaser.TilemapLayer.prototype.renderDebug = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var context = this.context; + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + var tx, ty, x, y, xmax, ymax; + + context.strokeStyle = this.debugSettings.facingEdgeStroke; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + if (!tile || tile.index < 0 || !tile.collides) + { + continue; + } + + if (this.debugSettings.collidingTileOverfill) + { + context.fillStyle = this.debugSettings.collidingTileOverfill; + context.fillRect(tx, ty, this._mc.cw, this._mc.ch); + } + + if (this.debugSettings.facingEdgeStroke) + { + context.beginPath(); + + if (tile.faceTop) + { + context.moveTo(tx, ty); + context.lineTo(tx + this._mc.cw, ty); + } + + if (tile.faceBottom) + { + context.moveTo(tx, ty + this._mc.ch); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + if (tile.faceLeft) + { + context.moveTo(tx, ty); + context.lineTo(tx, ty + this._mc.ch); + } + + if (tile.faceRight) + { + context.moveTo(tx + this._mc.cw, ty); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + context.closePath(); + + context.stroke(); + } + + } + + } + +}; + +/** +* Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size. +* +* @property {boolean} wrap +* @memberof Phaser.TilemapLayer +* @public +* @default false +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", { + + get: function () { + return this._wrap; + }, + + set: function (value) { + this._wrap = value; + this.dirty = true; + } + +}); + +/** +* Scrolls the map horizontally or returns the current x position. +* +* @property {number} scrollX +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", { + + get: function () { + return this._scrollX; + }, + + set: function (value) { + this._scrollX = value; + } + +}); + +/** +* Scrolls the map vertically or returns the current y position. +* +* @property {number} scrollY +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", { + + get: function () { + return this._scrollY; + }, + + set: function (value) { + this._scrollY = value; + } + +}); + +/** +* The width of the collision tiles (in pixels). +* +* @property {integer} collisionWidth +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", { + + get: function () { + return this._mc.cw; + }, + + set: function (value) { + this._mc.cw = value | 0; + this.dirty = true; + } + +}); + +/** +* The height of the collision tiles (in pixels). +* +* @property {integer} collisionHeight +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", { + + get: function () { + return this._mc.ch; + }, + + set: function (value) { + this._mc.ch = value | 0; + this.dirty = true; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. +* +* @class Phaser.TilemapParser +* @static +*/ +Phaser.TilemapParser = { + + /** + * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or + * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type + * depends how this should be configured. If you've a large sparsely populated map and the tile + * data doesn't need to change then setting this value to `true` will help with memory consumption. + * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes + * during the game) then leave the default value set. + * + * @constant + * @type {boolean} + */ + INSERT_NULL: false, + + /** + * Parse tilemap data from the cache and creates data for a Tilemap object. + * + * @method Phaser.TilemapParser.parse + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {string} key - The key of the tilemap in the Cache. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {object} The parsed map object. + */ + parse: function (game, key, tileWidth, tileHeight, width, height) { + + if (tileWidth === undefined) { tileWidth = 32; } + if (tileHeight === undefined) { tileHeight = 32; } + if (width === undefined) { width = 10; } + if (height === undefined) { height = 10; } + + if (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); + } + + }, + + /** + * Parses a CSV file into valid map data. + * + * @method Phaser.TilemapParser.parseCSV + * @param {string} key - The name you want to give the map data. + * @param {string} data - The CSV file data. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @return {object} Generated map data. + */ + parseCSV: function (key, data, tileWidth, tileHeight) { + + var map = this.getEmptyData(); + + // Trim any rogue whitespace from the data + data = data.trim(); + + var output = []; + var rows = data.split("\n"); + var height = rows.length; + var width = 0; + + for (var y = 0; y < rows.length; y++) + { + output[y] = []; + + var column = rows[y].split(","); + + for (var x = 0; x < column.length; x++) + { + output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight); + } + + if (width === 0) + { + width = column.length; + } + } + + map.format = Phaser.Tilemap.CSV; + map.name = key; + map.width = width; + map.height = height; + map.tileWidth = tileWidth; + map.tileHeight = tileHeight; + map.widthInPixels = width * tileWidth; + map.heightInPixels = height * tileHeight; + + map.layers[0].width = width; + map.layers[0].height = height; + map.layers[0].widthInPixels = map.widthInPixels; + map.layers[0].heightInPixels = map.heightInPixels; + map.layers[0].data = output; + + return map; + + }, + + /** + * Returns an empty map data object. + * + * @method Phaser.TilemapParser.getEmptyData + * @return {object} Generated map data. + */ + getEmptyData: function (tileWidth, tileHeight, width, height) { + + return { + width: (width !== undefined && width !== null) ? width : 0, + height: (height !== undefined && height !== null) ? height : 0, + tileWidth: (tileWidth !== undefined && tileWidth !== null) ? tileWidth : 0, + tileHeight: (tileHeight !== undefined && tileHeight !== null) ? tileHeight : 0, + orientation: 'orthogonal', + version: '1', + properties: {}, + widthInPixels: 0, + heightInPixels: 0, + layers: [ + { + name: 'layer', + x: 0, + y: 0, + width: 0, + height: 0, + widthInPixels: 0, + heightInPixels: 0, + alpha: 1, + visible: true, + properties: {}, + indexes: [], + callbacks: [], + bodies: [], + data: [] + } + ], + images: [], + objects: {}, + collision: {}, + tilesets: [], + tiles: [] + }; + + }, + + _slice: function(obj, fields) { + var sliced = {}; + + for (var k in fields) + { + var key = fields[k]; + + if (typeof obj[key] !== 'undefined') + { + sliced[key] = obj[key]; + } + } + + return sliced; + }, + + /** + * Parses an object group in Tiled JSON files. Object groups can be found in both layers and tilesets. Called internally in parseTiledJSON. + * @method Phaser.TilemapParser.parseObjectGroup + * @param {object} objectGroup - A JSON object group. + * @param {object} objectsCollection - An object into which new array of Tiled map objects will be added. + * @param {object} collisionCollection - An object into which new array of collision objects will be added. Currently only polylines are added. + * @param {string} [nameKey=objectGroup.name] - Key under which to store objects in collisions in objectsCollection and collisionCollection + * @param {object} [relativePosition={x: 0, y: 0}] - Coordinates the object group's position is relative to. + * @return {object} A object literal containing the objectsCollection and collisionCollection + */ + parseObjectGroup: function(objectGroup, objectsCollection, collisionCollection, nameKey, relativePosition) { + + var nameKey = nameKey || objectGroup.name; + var relativePosition = relativePosition || {x: 0, y: 0}; + var slice = this._slice; + + if (!nameKey) + { + console.warn('No name found for objectGroup', objectGroup); + } + + if (relativePosition.x === undefined || relativePosition.y === undefined) + { + console.warn('Malformed xy properties in relativePosition', relativePosition); + } + + objectsCollection[nameKey] = objectsCollection[nameKey] || []; + collisionCollection[nameKey] = collisionCollection[nameKey] || []; + + for (var v = 0, len = objectGroup.objects.length; v < len; v++) + { + var o = objectGroup.objects[v]; + + // Object Tiles + if (o.gid) + { + var object = { + gid: o.gid, + name: o.name, + type: o.type || '', + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + objectsCollection[nameKey].push(object); + } + else if (o.polyline) + { + var object = { + name: o.name, + type: o.type, + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + object.polyline = []; + + // Parse the polyline into an array + for (var p = 0; p < o.polyline.length; p++) + { + object.polyline.push([o.polyline[p].x, o.polyline[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // polygon + else if (o.polygon) + { + var object = slice(o, ['name', 'type', 'x', 'y', 'visible', 'rotation', 'properties']); + + object.x += relativePosition.x; + object.y += relativePosition.y; + + // Parse the polygon into an array + object.polygon = []; + + for (var p = 0; p < o.polygon.length; p++) + { + object.polygon.push([o.polygon[p].x, o.polygon[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // ellipse + else if (o.ellipse) + { + var object = slice(o, ['name', 'type', 'ellipse', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // otherwise it's a rectangle + else + { + var object = slice(o, ['name', 'type', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + object.rectangle = true; + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + } + + return { + objectsCollection: objectsCollection, + collisionCollection: collisionCollection + }; + }, + + /** + * Parses a Tiled JSON file into valid map data. + * @method Phaser.TilemapParser.parseTiledJSON + * @param {object} json - The JSON map data. + * @return {object} Generated and parsed map data. + */ + parseTiledJSON: function (json) { + + if (json.orientation !== 'orthogonal') + { + console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser'); + return null; + } + + // Map data will consist of: layers, objects, images, tilesets, sizes + var map = { + width: json.width, + height: json.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + orientation: json.orientation, + format: Phaser.Tilemap.TILED_JSON, + version: json.version, + properties: json.properties, + widthInPixels: json.width * json.tilewidth, + heightInPixels: json.height * json.tileheight + }; + + // Tile Layers + var layers = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'tilelayer') + { + continue; + } + + var curl = json.layers[i]; + + // Base64 decode data if necessary + // NOTE: uncompressed base64 only. + + if (!curl.compression && curl.encoding && curl.encoding === 'base64') + { + var binaryString = window.atob(curl.data); + var len = binaryString.length; + var bytes = new Array(len); + + // Interpret binaryString as an array of bytes representing + // little-endian encoded uint32 values. + for (var j = 0; j < len; j+=4) + { + bytes[j / 4] = ( + binaryString.charCodeAt(j) | + binaryString.charCodeAt(j + 1) << 8 | + binaryString.charCodeAt(j + 2) << 16 | + binaryString.charCodeAt(j + 3) << 24 + ) >>> 0; + } + + curl.data = bytes; + + delete curl.encoding; + } + else if (curl.compression) + { + console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\''); + continue; + } + + var layer = { + + name: curl.name, + x: curl.x, + y: curl.y, + width: curl.width, + height: curl.height, + widthInPixels: curl.width * json.tilewidth, + heightInPixels: curl.height * json.tileheight, + alpha: curl.opacity, + offsetX: curl.offsetx, + offsetY: curl.offsety, + visible: curl.visible, + properties: {}, + indexes: [], + callbacks: [], + bodies: [] + + }; + + if (curl.properties) + { + layer.properties = curl.properties; + } + + var x = 0; + var row = []; + var output = []; + var rotation, flipped, flippedVal, gid; + + // Loop through the data field in the JSON. + + // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV) + // If the map contains multiple tilesets then the indexes are relative to that which the set starts from. + // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset. + + for (var t = 0, len = curl.data.length; t < len; t++) + { + rotation = 0; + flipped = false; + gid = curl.data[t]; + flippedVal = 0; + + // If true the current tile is flipped or rotated (Tiled TMX format) + if (gid > 0x20000000) + { + // FlippedX + if (gid > 0x80000000) + { + gid -= 0x80000000; + flippedVal += 4; + } + + // FlippedY + if (gid > 0x40000000) + { + gid -= 0x40000000; + flippedVal += 2; + } + + // FlippedAD (anti-diagonal = top-right is swapped with bottom-left corners) + if (gid > 0x20000000) + { + gid -= 0x20000000; + flippedVal += 1; + } + + switch (flippedVal) + { + case 5: + rotation = Math.PI / 2; + break; + + case 6: + rotation = Math.PI; + break; + + case 3: + rotation = 3 * Math.PI / 2; + break; + + case 4: + rotation = 0; + flipped = true; + break; + + case 7: + rotation = Math.PI / 2; + flipped = true; + break; + + case 2: + rotation = Math.PI; + flipped = true; + break; + + case 1: + rotation = 3 * Math.PI / 2; + flipped = true; + break; + } + } + + // index, x, y, width, height + if (gid > 0) + { + var tile = new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight); + + tile.rotation = rotation; + tile.flipped = flipped; + + if (flippedVal !== 0) + { + // The WebGL renderer uses this to flip UV coordinates before drawing + tile.flippedVal = flippedVal; + } + + row.push(tile); + } + else + { + if (Phaser.TilemapParser.INSERT_NULL) + { + row.push(null); + } + else + { + row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight)); + } + } + + x++; + + if (x === curl.width) + { + output.push(row); + x = 0; + row = []; + } + } + + layer.data = output; + + layers.push(layer); + } + + map.layers = layers; + + // Images + var images = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'imagelayer') + { + continue; + } + + var curi = json.layers[i]; + + var image = { + + name: curi.name, + image: curi.image, + x: curi.x, + y: curi.y, + alpha: curi.opacity, + visible: curi.visible, + properties: {} + + }; + + if (curi.properties) + { + image.properties = curi.properties; + } + + images.push(image); + + } + + map.images = images; + + // Tilesets & Image Collections + var tilesets = []; + var tilesetGroupObjects = {}; + var imagecollections = []; + var lastSet = null; + + for (var i = 0; i < json.tilesets.length; i++) + { + // name, firstgid, width, height, margin, spacing, properties + var set = json.tilesets[i]; + + if (set.source) + { + console.warn('Phaser.TilemapParser - Phaser can\'t load external tilesets (%s). Use the Embed Tileset button and then export the map again.', set.source); + } + else if (set.image) + { + var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + if (set.tileproperties) + { + newSet.tileProperties = set.tileproperties; + } + + // For a normal sliced tileset the row/count/size information is computed when updated. + // This is done (again) after the image is set. + newSet.updateTileData(set.imagewidth, set.imageheight); + + tilesets.push(newSet); + } + else if (set.tiles) + { + var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + for (var ti in set.tiles) + { + var image = set.tiles[ti].image; + var gid = set.firstgid + parseInt(ti, 10); + newCollection.addImage(gid, image); + } + + imagecollections.push(newCollection); + } + else + { + throw new Error('Tileset ' + set.name + ' has no `image` or `tiles` property.'); + } + + // build a temporary object for objectgroups found in the tileset's tiles + for (var ti in set.tiles) + { + var objectGroup = set.tiles[ti].objectgroup; + + if (!objectGroup) + { + continue; + } + + tilesetGroupObjects[parseInt(ti, 10) + set.firstgid] = objectGroup; + } + + // We've got a new Tileset, so set the lastgid into the previous one + if (lastSet) + { + lastSet.lastgid = set.firstgid - 1; + } + + lastSet = set; + } + + if (tilesets.length === 0 && imagecollections.length === 0) + { + throw new Error('This tilemap has no tilesets.'); + } + + map.tilesets = tilesets; + map.imagecollections = imagecollections; + + // Objects & Collision Data (polylines, etc) + var objects = {}; + var collision = {}; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'objectgroup') + { + continue; + } + + var objectGroup = json.layers[i]; + this.parseObjectGroup(objectGroup, objects, collision); + } + + map.objects = objects; + map.collision = collision; + + map.tiles = []; + + // Finally lets build our super tileset index + for (var i = 0; i < map.tilesets.length; i++) + { + var set = map.tilesets[i]; + + var x = set.tileMargin; + var y = set.tileMargin; + + var count = 0; + var countX = 0; + var countY = 0; + + for (var t = set.firstgid; t < set.firstgid + set.total; t++) + { + // Can add extra properties here as needed + map.tiles[t] = [x, y, i]; + + x += set.tileWidth + set.tileSpacing; + + count++; + + if (count === set.total) + { + break; + } + + countX++; + + if (countX === set.columns) + { + x = set.tileMargin; + y += set.tileHeight + set.tileSpacing; + + countX = 0; + countY++; + + if (countY === set.rows) + { + break; + } + } + } + + } + + // assign tile properties + + var layer; + var tile; + var sid; + var set; + + // go through each of the map data layers + for (var i = 0; i < map.layers.length; i++) + { + layer = map.layers[i]; + collision[layer.name] = []; + set = null; + + // rows of tiles + for (var j = 0; j < layer.data.length; j++) + { + row = layer.data[j]; + + // individual tiles + for (var k = 0; k < row.length; k++) + { + tile = row[k]; + + if (tile === null || tile.index < 0) + { + continue; + } + + // find the relevant tileset + + sid = map.tiles[tile.index][2]; + set = map.tilesets[sid]; + + + // if that tile type has any properties, add them to the tile object + + if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) + { + tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties); + } + + var objectGroup = tilesetGroupObjects[tile.index]; + if (objectGroup) + { + // build collisions and objects for objectgroups found in the tileset's tiles + this.parseObjectGroup( + objectGroup, + map.objects, + map.collision, + tile.layer.name, + { + x: tile.worldX + objectGroup.x, + y: tile.worldY + objectGroup.y + }); + } + + } + } + } + + return map; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile set is a combination of an image containing the tiles and collision data per tile. +* +* Tilesets are normally created automatically when Tiled data is loaded. +* +* @class Phaser.Tileset +* @constructor +* @param {string} name - The name of the tileset in the map data. +* @param {integer} firstgid - The first tile index this tileset contains. +* @param {integer} [width=32] - Width of each tile (in pixels). +* @param {integer} [height=32] - Height of each tile (in pixels). +* @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels). +* @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels). +* @param {object} [properties={}] - Custom Tileset properties. +*/ +Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Tileset. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first tile index this Tileset contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of each tile (in pixels). + * @property {integer} tileWidth + * @readonly + */ + this.tileWidth = width | 0; + + /** + * The height of each tile (in pixels). + * @property {integer} tileHeight + * @readonly + */ + this.tileHeight = height | 0; + + /** + * The margin around the tiles in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileMarge + * @readonly + */ + // Modified internally + this.tileMargin = margin | 0; + + /** + * The spacing between each tile in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileSpacing + * @readonly + */ + this.tileSpacing = spacing | 0; + + /** + * Tileset-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set. + * @property {?object} image + * @readonly + */ + // Modified internally + this.image = null; + + /** + * The number of tile rows in the the tileset. + * @property {integer} + * @readonly + */ + // Modified internally + this.rows = 0; + + /** + * The number of tile columns in the tileset. + * @property {integer} columns + * @readonly + */ + // Modified internally + this.columns = 0; + + /** + * The total number of tiles in the tileset. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; + + /** + * The look-up table to specific tile image offsets. + * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1. + * @property {integer[]} drawCoords + * @private + */ + this.drawCoords = []; + +}; + +Phaser.Tileset.prototype = { + + /** + * Draws a tile from this Tileset at the given coordinates on the context. + * + * @method Phaser.Tileset#draw + * @public + * @param {CanvasRenderingContext2D} context - The context to draw the tile onto. + * @param {number} x - The x coordinate to draw to. + * @param {number} y - The y coordinate to draw to. + * @param {integer} index - The index of the tile within the set to draw. + */ + draw: function (context, x, y, index) { + + // Correct the tile index for the set and bias for interlacing + var coordIndex = (index - this.firstgid) << 1; + + if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length) + { + context.drawImage( + this.image, + this.drawCoords[coordIndex], + this.drawCoords[coordIndex + 1], + this.tileWidth, + this.tileHeight, + x, + y, + this.tileWidth, + this.tileHeight + ); + } + + }, + + /** + * Returns true if and only if this tileset contains the given tile index. + * + * @method Phaser.Tileset#containsTileIndex + * @public + * @param {number} tileIndex + * @return {boolean} True if this tileset contains the given index. + */ + containsTileIndex: function (tileIndex) { + + return ( + tileIndex >= this.firstgid && + tileIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Set the image associated with this Tileset and update the tile data. + * + * @method Phaser.Tileset#setImage + * @public + * @param {Image} image - The image that contains the tiles. + */ + setImage: function (image) { + + this.image = image; + this.updateTileData(image.width, image.height); + + }, + + /** + * Sets tile spacing and margins. + * + * @method Phaser.Tileset#setSpacing + * @public + * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels). + */ + setSpacing: function (margin, spacing) { + + this.tileMargin = margin | 0; + this.tileSpacing = spacing | 0; + + if (this.image) + { + this.updateTileData(this.image.width, this.image.height); + } + + }, + + /** + * Updates tile coordinates and tileset data. + * + * @method Phaser.Tileset#updateTileData + * @private + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + */ + updateTileData: function (imageWidth, imageHeight) { + + // May be fractional values + var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); + var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); + + if (rowCount % 1 !== 0 || colCount % 1 !== 0) + { + console.warn( + "Phaser.Tileset - '%s' image tile area (%s x %s) is not a whole multiple of tile size (%s x %s + %s + %s)", + this.name, imageWidth, imageHeight, this.tileWidth, this.tileHeight, this.tileMargin, this.tileSpacing + ); + } + + // In Tiled a tileset image that is not an even multiple of the tile dimensions + // is truncated - hence the floor when calculating the rows/columns. + rowCount = Math.floor(rowCount); + colCount = Math.floor(colCount); + + if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount)) + { + console.warn( + "Phaser.Tileset - Tile layout from image '%s' (%s rows by %s columns) differs from tileset '%s' (%s rows by %s columns)", + this.image.name, colCount, rowCount, this.name, this.columns, this.rows + ); + } + + this.rows = rowCount; + this.columns = colCount; + this.total = rowCount * colCount; + + this.drawCoords.length = 0; + + var tx = this.tileMargin; + var ty = this.tileMargin; + + for (var y = 0; y < this.rows; y++) + { + for (var x = 0; x < this.columns; x++) + { + this.drawCoords.push(tx); + this.drawCoords.push(ty); + tx += this.tileWidth + this.tileSpacing; + } + + tx = this.tileMargin; + ty += this.tileHeight + this.tileSpacing; + } + + } + +}; + +Phaser.Tileset.prototype.constructor = Phaser.Tileset; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. +* +* @class Phaser.Particle +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Particle = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + /** + * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData. + * @protected + */ + this.autoScale = false; + + /** + * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.scaleData = null; + + /** + * @property {number} _s - Internal cache var for tracking auto scale. + * @private + */ + this._s = 0; + + /** + * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. + * @protected + */ + this.autoAlpha = false; + + /** + * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.alphaData = null; + + /** + * @property {number} _a - Internal cache var for tracking auto alpha. + * @private + */ + this._a = 0; + +}; + +Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Particle.prototype.constructor = Phaser.Particle; + +/** +* Updates the Particle scale or alpha if autoScale and autoAlpha are set. +* +* @method Phaser.Particle#update +* @memberof 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; + } + } + +}; + +/** +* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. +* +* @method Phaser.Particle#onEmit +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.onEmit = function() { +}; + +/** +* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. +* +* @method Phaser.Particle#setAlphaData +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.setAlphaData = function(data) { + + this.alphaData = data; + this._a = data.length - 1; + this.alpha = this.alphaData[this._a].v; + this.autoAlpha = true; + +}; + +/** +* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. +* +* @method Phaser.Particle#setScaleData +* @memberof Phaser.Particle +*/ +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; + +}; + +/** +* Resets the Particle. This places the Particle at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. +* If the Particle has a physics body that too is reset. +* +* @method Phaser.Particle#reset +* @memberof Phaser.Particle +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {number} [health=1] - The health to give the Particle. +* @return {Phaser.Particle} This instance. +*/ +Phaser.Particle.prototype.reset = function(x, y, health) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y, health); + + this.alpha = 1; + this.scale.set(1); + + this.autoScale = false; + this.autoAlpha = false; + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Particles tracks any Emitters attached to it. +* +* @class Phaser.Particles +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Particles = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} emitters - Internal emitters store. + */ + this.emitters = {}; + + /** + * @property {number} ID - + * @default + */ + this.ID = 0; + +}; + +Phaser.Particles.prototype = { + + /** + * Adds a new Particle Emitter to the Particle Manager. + * @method Phaser.Particles#add + * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. + * @return {Phaser.Emitter} The emitter that was added. + */ + add: function (emitter) { + this.emitters[emitter.id] = emitter; + return emitter; + }, + + /** + * Removes an existing Particle Emitter from the Particle Manager. + * @method Phaser.Particles#remove + * @param {Phaser.Emitter} emitter - The emitter to remove. + */ + remove: function (emitter) { + delete this.emitters[emitter.id]; + } + +}; + +Phaser.Particles.prototype.constructor = Phaser.Particles; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Arcade Particles is a Particle System integrated with Arcade Physics. +* +* @class Phaser.Particles.Arcade +*/ +Phaser.Particles.Arcade = {}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Emitter is a lightweight particle emitter that uses Arcade Physics. +* It can be used for one-time explosions or for continuous effects like rain and fire. +* All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. +* +* @class Phaser.Particles.Arcade.Emitter +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. +* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. +* @param {number} [maxParticles=50] - The total number of particles in this emitter. +*/ +Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { + + /** + * @property {number} maxParticles - The total number of particles in this emitter. + * @default + */ + this.maxParticles = maxParticles || 50; + + Phaser.Group.call(this, game); + + /** + * @property {number} _id - Internal ID for this emitter -- only used by the Particle System in most cases + * @private + */ + this._id = this.game.particles.ID++; + + /** + * @property {string} name - A handy string name for this emitter. Can be set to anything. + */ + this.name = 'emitter' + this.id; + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.EMITTER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * @property {Phaser.Rectangle} area - The {@link #setSize size} of the emitter's emit area. The **actual** emit area is a rectangle of this size centered on (emitX, emitY): `{x: this.left, y: this.top, width: this.area.width, height: this.area.height}`. Particles are generated at a random position within this area. + * @default + */ + this.area = new Phaser.Rectangle(x, y, 1, 1); + + /** + * @property {?number} minAngle - The minimum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #maxAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.minAngle = null; + + /** + * @property {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #minAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.maxAngle = null; + + /** + * @property {number} minSpeed - The minimum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.minSpeed = 0; + + /** + * @property {number} maxSpeed - The maximum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.maxSpeed = 100; + + /** + * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle. + * @default + */ + this.minParticleSpeed = new Phaser.Point(-100, -100); + + /** + * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle. + * @default + */ + this.maxParticleSpeed = new Phaser.Point(100, 100); + + /** + * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. + * @default + */ + this.minParticleScale = 1; + + /** + * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. + * @default + */ + this.maxParticleScale = 1; + + /** + * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0. + */ + this.scaleData = null; + + /** + * @property {number} minRotation - The minimum possible angular velocity of a particle. + * @default + */ + this.minRotation = -360; + + /** + * @property {number} maxRotation - The maximum possible angular velocity of a particle. + * @default + */ + this.maxRotation = 360; + + /** + * @property {number} minParticleAlpha - The minimum possible alpha value of a particle. + * @default + */ + this.minParticleAlpha = 1; + + /** + * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle. + * @default + */ + this.maxParticleAlpha = 1; + + /** + * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0. + */ + this.alphaData = null; + + /** + * @property {function} particleClass - For emitting your own particle class types. They must extend Phaser.Particle. + * @default + */ + this.particleClass = Phaser.Particle; + + /** + * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter. + */ + this.particleDrag = new Phaser.Point(); + + /** + * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false). + * @default + */ + this.frequency = 100; + + /** + * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. + * @default + */ + this.lifespan = 2000; + + /** + * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. + */ + this.bounce = new Phaser.Point(); + + /** + * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. + * @default + */ + this.on = false; + + /** + * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) + * @default + */ + this.particleAnchor = new Phaser.Point(0.5, 0.5); + + /** + * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) + * @default + */ + this.blendMode = Phaser.blendModes.NORMAL; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitX + */ + this.emitX = x; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitY + */ + this.emitY = y; + + /** + * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. + */ + this.autoScale = false; + + /** + * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. + */ + this.autoAlpha = false; + + /** + * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. + * @default + */ + this.particleBringToTop = false; + + /** + * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. + * @default + */ + this.particleSendToBack = false; + + /** + * @property {object} counts - Records emitter activity. + * @property {number} counts.emitted - How many particles were emitted during the last update. + * @property {number} counts.failed - How many particles could not be emitted during the last update (because no particles were available). + * @property {number} counts.totalEmitted - How many particles have been emitted. + * @property {number} counts.totalFailed - How many particles could not be emitted when they were due (because no particles were available). + */ + this.counts = { + emitted: 0, + failed: 0, + totalEmitted: 0, + totalFailed: 0 + }; + + /** + * @property {Phaser.Point} _gravity - Internal gravity value. + * @private + */ + this._gravity = new Phaser.Point(0, 100); + + /** + * @property {Phaser.Point} _minParticleScale - Internal particle scale var. + * @private + */ + this._minParticleScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} _maxParticleScale - Internal particle scale var. + * @private + */ + this._maxParticleScale = new Phaser.Point(1, 1); + + /** + * @property {number} _total - Internal helper for deciding how many particles to launch (via {@link #start}). + * @private + */ + this._total = 0; + + /** + * @property {number} _timer - Internal helper for deciding when to launch particles or kill them. + * @private + */ + this._timer = 0; + + /** + * @property {number} _counter - Internal counter for figuring out how many particles to launch. + * @private + */ + this._counter = 0; + + /** + * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update. + * @private + */ + this._flowQuantity = 0; + + /** + * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total (via {@link #flow}). + * @private + */ + this._flowTotal = 0; + + /** + * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time). + * @private + */ + this._explode = true; + + /** + * @property {any} _frames - Internal helper for the particle frame. + * @private + */ + this._frames = null; + +}; + +Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); +Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter; + +/** +* Called automatically by the game loop, decides when to launch particles and when to "die". +* +* @method Phaser.Particles.Arcade.Emitter#update +*/ +Phaser.Particles.Arcade.Emitter.prototype.update = function () { + + this.counts.emitted = 0; + this.counts.failed = 0; + + if (this.on && this.game.time.time >= this._timer) + { + this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion; + + if (this._flowTotal !== 0) + { + if (this._flowQuantity > 0) + { + for (var i = 0; i < this._flowQuantity; i++) + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + break; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._total > 0 && this._counter >= this._total) + { + this.on = false; + } + } + } + + } + + var i = this.children.length; + + while (i--) + { + if (this.children[i].exists) + { + this.children[i].update(); + } + } + +}; + +/** +* This function generates a new set of particles for use by this emitter. +* The particles are stored internally waiting to be emitted via Emitter.start. +* +* @method Phaser.Particles.Arcade.Emitter#makeParticles +* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. +* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random. +* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. +* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. +* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. +* @param {object} [particleArguments=null] - Custom arguments to pass to your particle class +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds, particleArguments) { + + if (frames === undefined) { frames = 0; } + if (quantity === undefined) { quantity = this.maxParticles; } + if (collide === undefined) { collide = false; } + if (collideWorldBounds === undefined) { collideWorldBounds = false; } + if (particleArguments === undefined) { particleArguments = null; } + + var particle; + var i = 0; + var rndKey = keys; + var rndFrame = frames; + this._frames = frames; + + if (quantity > this.maxParticles) + { + this.maxParticles = quantity; + } + + while (i < quantity) + { + if (Array.isArray(keys)) + { + rndKey = this.game.rnd.pick(keys); + } + + if (Array.isArray(frames)) + { + rndFrame = this.game.rnd.pick(frames); + } + + particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame, particleArguments); + + this.game.physics.arcade.enable(particle, false); + + particle.body.checkCollision.none = !collide; + particle.body.collideWorldBounds = collideWorldBounds; + particle.body.skipQuadTree = true; + + particle.exists = false; + particle.visible = false; + particle.anchor.copyFrom(this.particleAnchor); + + this.add(particle); + + i++; + } + + return this; + +}; + +/** +* Call this function to turn off all the particles and the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#kill +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.kill = function () { + + this.on = false; + this.alive = false; + this.exists = false; + + return this; + +}; + +/** +* Handy for bringing game objects "back to life". Just sets alive and exists back to true. +* +* @method Phaser.Particles.Arcade.Emitter#revive +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.revive = function () { + + this.alive = true; + this.exists = true; + + return this; + +}; + +/** +* Call this function to emit the given quantity of particles at all once (an explosion) +* +* @method Phaser.Particles.Arcade.Emitter#explode +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [quantity=this.maxParticles] - How many particles to launch. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) { + + if (quantity === undefined) { + quantity = this.maxParticles; + } + + this._flowTotal = 0; + + this.start(true, lifespan, 0, quantity, false); + + return this; + +}; + +/** +* Call this function to start emitting a flow of particles. +* `quantity` particles are released every interval of `frequency` ms until `total` particles have been released (or forever). +* If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 × 5 = 20 total) and then turn {@link #on off}. +* If you set the total to be -1 then no quantity cap is used and it will keep emitting (as long as there are inactive particles available). +* +* {@link #output}, {@link #lifespanOutput}, and {@link #remainder} describe the particle flow rate. +* During a stable flow, the number of active particles approaches {@link #lifespanOutput} and the number of inactive particles approaches {@link #remainder}. +* If {@link #remainder} is less than 0, there will likely be no particles available for a portion of the flow (see {@link #count}). +* +* @method Phaser.Particles.Arcade.Emitter#flow +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of particles, given in ms. Values between 0 and 16.66 will behave the same (60 releases per second). +* @param {number} [quantity=1] - How many particles to launch at each interval. Not larger than {@link #maxParticles}. +* @param {number} [total=-1] - Turn {@link #on off} after launching this many particles in total. If -1 it will carry on indefinitely. +* @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) { + + if (frequency === undefined || frequency === null) { frequency = 250; } + if (quantity === undefined || quantity === 0) { quantity = 1; } + if (total === undefined) { total = -1; } + if (immediate === undefined) { immediate = true; } + + if (quantity > this.maxParticles) + { + quantity = this.maxParticles; + } + + this._counter = 0; + this._flowQuantity = quantity; + this._flowTotal = total; + + if (immediate) + { + this.start(true, lifespan, frequency, quantity); + + this._counter += quantity; + this.on = true; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + else + { + this.start(false, lifespan, frequency, quantity); + } + + return this; + +}; + +/** +* Start emitting particles. +* +* {@link #explode} and {@link #flow} are simpler methods. +* +* There are two patterns, based on the `explode` argument: +* +* ##### explode=true +* +* start(true, lifespan=0, null, total) +* +* When `explode` is true or `forceQuantity` is true, `start` emits `total` particles immediately. You should pass a nonzero `total`. +* +* ##### explode=false +* +* start(false, lifespan=0, frequency=250, total=0) +* +* When `explode` is false and `forceQuantity` is false, `start` emits 1 particle every interval of `frequency` ms. If `total` is not zero, the emitter turns itself off after `total` particles have been released. If `total` is zero, the emitter keeps emitting particles as long as they are available. To emit more than 1 particle per flow interval, use {@link #flow} instead. +* +* `forceQuantity` seems equivalent to `explode` and can probably be avoided. +* +* @method Phaser.Particles.Arcade.Emitter#start +* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false). +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of 1 particle, when `explode` is false. Value given in ms. Ignored if `explode` is set to true. +* @param {number} [total=0] - Turn {@link #on off} after launching this many particles in total. +* @param {number} [forceQuantity=false] - Equivalent to `explodes`. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, total, forceQuantity) { + + if (explode === undefined) { explode = true; } + if (lifespan === undefined) { lifespan = 0; } + if (frequency === undefined || frequency === null) { frequency = 250; } + if (total === undefined) { total = 0; } + if (forceQuantity === undefined) { forceQuantity = false; } + + if (total > this.maxParticles) + { + total = this.maxParticles; + } + + this.revive(); + + this.visible = true; + + this.lifespan = lifespan; + this.frequency = frequency; + + if (explode || forceQuantity) + { + for (var i = 0; i < total; i++) + { + this.emitParticle(); + } + } + else + { + this.on = true; + this._total = total; + this._counter = 0; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + + return this; + +}; + +/** +* This function is used internally to emit the next particle in the queue. +* +* However it can also be called externally to emit a particle. +* +* When called externally you can use the arguments to override any defaults the Emitter has set. +* +* The newly emitted particle is available in {@link Phaser.Particles.Arcade.Emitter#cursor}. +* +* @method Phaser.Particles.Arcade.Emitter#emitParticle +* @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. +* @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {boolean} True if a particle was emitted, otherwise false. +*/ +Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + var particle = this.getNextParticle(); + + if (particle === null) + { + this.counts.failed++; + this.counts.totalFailed++; + + return false; + } + + this.counts.emitted++; + this.counts.totalEmitted++; + + var rnd = this.game.rnd; + + if (key !== undefined && frame !== undefined) + { + particle.loadTexture(key, frame); + } + else if (key !== undefined) + { + particle.loadTexture(key); + particle.frame = Array.isArray(this._frames) ? rnd.pick(this._frames) : this._frames; + } + + var emitX = this.emitX; + var emitY = this.emitY; + + if (x !== null) + { + emitX = x; + } + else if (this.width > 1) + { + emitX = rnd.between(this.left, this.right); + } + + if (y !== null) + { + emitY = y; + } + else if (this.height > 1) + { + emitY = rnd.between(this.top, this.bottom); + } + + this.resetParticle(particle, emitX, emitY); + + return true; + +}; + + +/** +* Helper for {@link #emitParticle}. Gets the next available particle. +* +* @private +* @return {?Phaser.Particle} The first particle with exists=false, or null +*/ +Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () { + + var i = this.length; + + while (i--) + { + var next = this.next(); + + if (!next.exists) + { + return next; + } + } + + return null; + +}; + +/** + * Helper for {@link #emitParticle}. Sets particle properties and calls {@link Particle#onEmit}. + * + * @private + * @param {Phaser.Particle} particle + * @param {number} x + * @param {number} y + */ +Phaser.Particles.Arcade.Emitter.prototype.resetParticle = function (particle, x, y) { + + var rnd = this.game.rnd; + + particle.reset(x, y); + + 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(rnd.realInRange(this.minParticleScale, this.maxParticleScale)); + } + else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y)) + { + particle.scale.set(rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y)); + } + else + { + particle.scale.set(this._minParticleScale.x, this._minParticleScale.y); + } + + if (this.autoAlpha) + { + particle.setAlphaData(this.alphaData); + } + else + { + particle.alpha = rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha); + } + + particle.blendMode = this.blendMode; + + var body = particle.body; + + body.updateBounds(); + + body.bounce.copyFrom(this.bounce); + body.drag.copyFrom(this.particleDrag); + + if (this.minAngle != null && this.maxAngle != null) + { + this.game.physics.arcade.velocityFromAngle( + (this.minAngle === this.maxAngle) ? this.minAngle : rnd.between(this.minAngle, this.maxAngle), + (this.minSpeed === this.maxSpeed) ? this.minSpeed : rnd.between(this.minSpeed, this.maxSpeed), + body.velocity + ); + } + else + { + body.velocity.x = rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x); + body.velocity.y = rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y); + } + + body.angularVelocity = rnd.between(this.minRotation, this.maxRotation); + body.gravity.copyFrom(this.gravity); + body.angularDrag = this.angularDrag; + + particle.onEmit(); + +}; + +/** +* Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. +* +* @method Phaser.Particles.Arcade.Emitter#destroy +*/ +Phaser.Particles.Arcade.Emitter.prototype.destroy = function () { + + this.game.particles.remove(this); + + Phaser.Group.prototype.destroy.call(this, true, false); + +}; + +/** +* A more compact way of setting the width and height of the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#setSize +* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). +* @param {number} height - The desired height of the emitter. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { + + this.area.width = width; + this.area.height = height; + + return this; + +}; + +/** +* A more compact way of setting the X velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setXSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.x = min; + this.maxParticleSpeed.x = max; + + return this; + +}; + +/** +* A more compact way of setting the Y velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setYSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.y = min; + this.maxParticleSpeed.y = max; + + return this; + +}; + +/** +* A more compact way of setting the angular velocity constraints of the particles. +* +* @method Phaser.Particles.Arcade.Emitter#setRotation +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minRotation = min; + this.maxRotation = max; + + return this; + +}; + +/** +* A more compact way of setting the alpha constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. +* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setAlpha +* @param {number} [min=1] - The minimum value for this range. +* @param {number} [max=1] - The maximum value for this range. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) { + + if (min === undefined) { min = 1; } + if (max === undefined) { max = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.alphaData.reverse(); + this.autoAlpha = true; + } + + return this; + +}; + +/** +* A more compact way of setting the scale constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. +* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setScale +* @param {number} [minX=1] - The minimum value of Particle.scale.x. +* @param {number} [maxX=1] - The maximum value of Particle.scale.x. +* @param {number} [minY=1] - The minimum value of Particle.scale.y. +* @param {number} [maxY=1] - The maximum value of Particle.scale.y. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) { + + if (minX === undefined) { minX = 1; } + if (maxX === undefined) { maxX = 1; } + if (minY === undefined) { minY = 1; } + if (maxY === undefined) { maxY = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (yoyo === undefined) { yoyo = false; } + + // Reset these + 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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.scaleData.reverse(); + this.autoScale = true; + } + + return this; + +}; + +/** + * Sets a radial pattern for emitting particles. + * + * This is a shorthand for setting {@link #minAngle}, {@link #maxAngle}, {@link #minSpeed}, and {@link #maxSpeed}. + * + * To remove the radial pattern, use `setAngle(null, null)`. + * + * @method Phaser.Particles.Arcade.Emitter#setAngle + * @param {?number} minAngle - The minimum angle of initial particle velocities, in degrees. + * @param {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. + * @param {number} [minSpeed] - The minimum initial particle speed. + * @param {number} [maxSpeed] - The maximum initial particle speed. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ +Phaser.Particles.Arcade.Emitter.prototype.setAngle = function (minAngle, maxAngle, minSpeed, maxSpeed) { + + this.minAngle = minAngle; + this.maxAngle = maxAngle; + + if (minSpeed != null) { this.minSpeed = minSpeed; } + if (maxSpeed != null) { this.maxSpeed = maxSpeed; } + + return this; + +}; + +/** +* Change the emitter's center to match the center of any object with a `center` property, such as an Arcade Body. +* If the object doesn't have a `center` property it will be set to the object's anchor-adjusted world position (`object.world`). +* +* @method Phaser.Particles.Arcade.Emitter#at +* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +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); + } + + return this; + +}; + +/** + * @name Phaser.Particles.Arcade.Emitter#gravity + * @property {Phaser.Point} gravity - Sets the `body.gravity` of each particle sprite to this on launch. + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "gravity", { + + get: function () { + return this._gravity; + }, + + set: function (value) { + if (typeof value === "number") + { + this._gravity.y = value; + } + else + { + this._gravity = value; + } + } + +}); + + +/** +* @name Phaser.Particles.Arcade.Emitter#id +* @property {number} id - Gets the internal ID that represents this emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "id", { + get: function () { + return this._id; + } +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#width +* @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", { + + get: function () { + return this.area.width; + }, + + set: function (value) { + this.area.width = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#height +* @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", { + + get: function () { + return this.area.height; + }, + + set: function (value) { + this.area.height = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#x +* @property {number} x - Gets or sets the x position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", { + + get: function () { + return this.emitX; + }, + + set: function (value) { + this.emitX = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#y +* @property {number} y - Gets or sets the y position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", { + + get: function () { + return this.emitY; + }, + + set: function (value) { + this.emitY = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#left +* @property {number} left - Gets the left position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", { + + get: function () { + return Math.floor(this.x - (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#right +* @property {number} right - Gets the right position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", { + + get: function () { + return Math.floor(this.x + (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#top +* @property {number} top - Gets the top position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", { + + get: function () { + return Math.floor(this.y - (this.area.height / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#bottom +* @property {number} bottom - Gets the bottom position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", { + + get: function () { + return Math.floor(this.y + (this.area.height / 2)); + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#output + * @property {number} output - The number of particles released per second, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "output", { + + get: function () { + return 1000 * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#lifespanOutput + * @property {number} lifespanOutput - The number of particles released during one particle's {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "lifespanOutput", { + + get: function () { + return (this.lifespan === 0 ? Infinity : this.lifespan) * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#remainder + * @property {number} remainder - The expected number of unreleased particles after a flow interval of {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "remainder", { + + get: function () { + return this.maxParticles - this.lifespanOutput; + } + +}); + +/** +* The last particle released, if any. +* +* You should treat this as read-only (and also avoid {@link #next} and {@link #previous}) once the emitter is started. Phaser uses it internally to track particles. +* +* @name Phaser.Particles.Arcade.Emitter#cursor +* @property {?DisplayObject} cursor +* @readonly +*/ +// Inherited from Phaser.Group#cursor + +/** +* Advances the cursor to the next particle. +* +* @method Phaser.Particles.Arcade.Emitter#next +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#next + +/** +* Moves the group cursor to the previous particle. +* +* @method Phaser.Particles.Arcade.Emitter#previous +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#previous + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Weapon Plugin provides the ability to easily create a bullet pool and manager. +* +* Weapons fire {@link Phaser.Bullet} objects, which are essentially Sprites with a few extra properties. +* The Bullets are enabled for {@link Phaser.Physics.Arcade Arcade Physics}. They do not currently work with P2 Physics. +* +* The Bullets are created inside of {@link #bullets weapon.bullets}, which is a {@link Phaser.Group} instance. Anything you +* can usually do with a Group, such as move it around the display list, iterate it, etc can be done +* to the bullets Group too. +* +* Bullets can have textures and even animations. You can control the speed at which they are fired, +* the firing rate, the firing angle, and even set things like gravity for them. +* +* A small example, using {@link Phaser.GameObjectFactory#weapon add.weapon}, assumed to be running from within a {@link Phaser.State#create} method: +* +* ```javascript +* var weapon = this.add.weapon(10, 'bullet'); +* weapon.fireFrom.set(300, 300); +* this.input.onDown.add(weapon.fire, this); +* ``` +* +* If you want to (re)create the bullet pool separately, you can use: +* +* ```javascript +* var weapon = this.game.plugins.add(Phaser.Weapon); +* // … +* weapon.createBullets(10, 'bullet'); +* ``` +* +* @class Phaser.Weapon +* @constructor +* @param {Phaser.Game} game - A reference to the current Phaser.Game instance. +* @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin. +*/ +Phaser.Weapon = function (game, parent) { + + Phaser.Plugin.call(this, game, parent); + + /** + * This is the Phaser.Group that contains all of the bullets managed by this plugin. + * @type {Phaser.Group} + */ + this.bullets = null; + + /** + * Should the bullet pool run out of bullets (i.e. they are all in flight) then this + * boolean controls if the Group will create a brand new bullet object or not. + * @type {boolean} + * @default + */ + this.autoExpandBulletsGroup = false; + + /** + * Will this weapon auto fire? If set to true then a new bullet will be fired + * based on the {@link #fireRate} value. + * @type {boolean} + * @default + */ + this.autofire = false; + + /** + * The total number of bullets this Weapon has fired so far. + * You can limit the number of shots allowed (via {@link #fireLimit}), and reset + * this total via {@link #resetShots}. + * @type {number} + * @default + */ + this.shots = 0; + + /** + * The maximum number of shots that this Weapon is allowed to fire before it stops. + * When the limit is his the {@link #onFireLimit} Signal is dispatched. + * You can reset the shot counter via {@link #resetShots}. + * @type {number} + * @default + */ + this.fireLimit = 0; + + /** + * The minimum interval between shots, in milliseconds. + * @type {number} + * @default + */ + this.fireRate = 100; + + /** + * This is a modifier that is added to the {@link #fireRate} each update to add variety + * to the firing rate of the Weapon. The value is given in milliseconds. + * If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual + * firing rate of the Weapon will be between 150 and 250. + * @type {number} + * @default + */ + this.fireRateVariance = 0; + + /** + * This is a Rectangle from within which the bullets are fired. By default it's a 1x1 + * rectangle, the equivalent of a Point. But you can change the width and height, and if + * larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from. + * @type {Phaser.Rectangle} + */ + this.fireFrom = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE_UP + * or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right. + * @type {integer} + * @default + */ + this.fireAngle = Phaser.ANGLE_UP; + + /** + * When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set. + * @type {boolean} + * @default + */ + this.bulletInheritSpriteSpeed = false; + + /** + * The string based name of the animation that the Bullet will be given on launch. + * This is set via {@link #addBulletAnimation}. + * @type {string} + * @default + */ + this.bulletAnimation = ''; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to pick a random frame from the set. + * @type {boolean} + * @default + */ + this.bulletFrameRandom = false; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to use the next frame in the set. The frame index is then + * advanced one frame until it reaches the end of the set, then it starts from the start + * again. Cycling frames like this allows you to create varied bullet effects via + * sprite sheets. + * @type {boolean} + * @default + */ + this.bulletFrameCycle = false; + + /** + * Should the Bullets wrap around the world bounds? This automatically calls + * `World.wrap` on the Bullet each frame. See the docs for that method for details. + * @type {boolean} + * @default + */ + this.bulletWorldWrap = false; + + /** + * If `bulletWorldWrap` is true then you can provide an optional padding value with this + * property. It's added to the calculations determining when the Bullet should wrap around + * the world or not. The value is given in pixels. + * @type {integer} + * @default + */ + this.bulletWorldWrapPadding = 0; + + /** + * An optional angle offset applied to the Bullets when they are launched. + * This is useful if for example your bullet sprites have been drawn facing up, instead of + * to the right, and you want to fire them at an angle. In which case you can set the + * angle offset to be 90 and they'll be properly rotated when fired. + * @type {number} + * @default + */ + this.bulletAngleOffset = 0; + + /** + * This is a variance added to the angle of Bullets when they are fired. + * If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual + * angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a + * great 'spread' effect to a Weapon. + * @type {number} + * @default + */ + this.bulletAngleVariance = 0; + + /** + * The initial velocity of fired bullets, in pixels per second. + * @type {number} + * @default + */ + this.bulletSpeed = 200; + + /** + * This is a variance added to the speed of Bullets when they are fired. + * If bullets have a {@link #bulletSpeed} value of 200, and a `bulletSpeedVariance` of 50 + * then the actual speed of the Bullets will be between 150 and 250 pixels per second. + * @type {number} + * @default + */ + this.bulletSpeedVariance = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount + * of lifespan the Bullets have set on launch. The value is given in milliseconds. + * When a Bullet hits its lifespan limit it will be automatically killed. + * @type {number} + * @default + */ + this.bulletLifespan = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_DISTANCE` this controls the distance + * the Bullet can travel before it is automatically killed. The distance is given in pixels. + * @type {number} + * @default + */ + this.bulletKillDistance = 0; + + /** + * This is the amount of {@link Phaser.Physics.Arcade.Body#gravity} added to the Bullets physics body when fired. + * Gravity is expressed in pixels / second / second. + * @type {Phaser.Point} + */ + this.bulletGravity = new Phaser.Point(0, 0); + + /** + * Bullets can optionally adjust their rotation in-flight to match their velocity. + * This can create the effect of a bullet 'pointing' to the path it is following, for example + * an arrow being fired from a bow, and works especially well when added to {@link #bulletGravity}. + * @type {boolean} + * @default + */ + this.bulletRotateToVelocity = false; + + /** + * The Texture Key that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string} + * @default + */ + this.bulletKey = ''; + + /** + * The Texture Frame that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string|integer} + * @default + */ + this.bulletFrame = ''; + + /** + * Private var that holds the public `bulletClass` property. + * @type {function} + * @private + */ + this._bulletClass = Phaser.Bullet; + + /** + * Private var that holds the public `bulletCollideWorldBounds` property. + * @type {boolean} + * @private + */ + this._bulletCollideWorldBounds = false; + + /** + * Private var that holds the public `bulletKillType` property. + * @type {integer} + * @private + */ + this._bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; + + /** + * Holds internal data about custom bullet body sizes. + * + * @type {Object} + * @private + */ + this._data = { + customBody: false, + width: 0, + height: 0, + offsetX: 0, + offsetY: 0 + }; + + /** + * This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not. + * It's used in combination with {@link #bulletKillType} when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS` + * or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored. + * If you are tracking a Sprite or Point then the bounds are centered on that object every frame. + * + * @type {Phaser.Rectangle} + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The Rectangle used to calculate the bullet bounds from. + * + * @type {Phaser.Rectangle} + * @private + */ + this.bulletBounds = game.world.bounds; + + /** + * This array stores the frames added via @link #setBulletFrames. + * + * @type {Array} + * @protected + */ + this.bulletFrames = []; + + /** + * The index of the frame within {@link #bulletFrames} that is currently being used. + * This value is only used if {@link #bulletFrameCycle} is set to `true`. + * @type {number} + * @private + */ + this.bulletFrameIndex = 0; + + /** + * An internal object that stores the animation data added via {@link #addBulletAnimation}. + * @type {Object} + * @private + */ + this.anims = {}; + + /** + * The onFire Signal is dispatched each time {@link #fire} is called, and a Bullet is + * _successfully_ launched. The callback is set two arguments: a reference to the bullet sprite itself, + * and a reference to the Weapon that fired the bullet. + * + * @type {Phaser.Signal} + */ + this.onFire = new Phaser.Signal(); + + /** + * The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result + * of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance. + * The callback is sent one argument: A reference to the bullet sprite itself. + * + * @type {Phaser.Signal} + */ + this.onKill = new Phaser.Signal(); + + /** + * The onFireLimit Signal is dispatched if {@link #fireLimit} is > 0, and a bullet launch takes the number + * of shots fired to equal the fire limit. + * The callback is sent two arguments: A reference to this Weapon, and the value of + * {@link #fireLimit}. + * + * @type {Phaser.Signal} + */ + this.onFireLimit = new Phaser.Signal(); + + /** + * The Sprite currently being tracked by the Weapon, if any. + * This is set via the {@link #trackSprite} method. + * + * @type {Phaser.Sprite|Object} + */ + this.trackedSprite = null; + + /** + * The Pointer currently being tracked by the Weapon, if any. + * This is set via the {@link #trackPointer} method. + * + * @type {Phaser.Pointer} + */ + this.trackedPointer = null; + + /** + * If you want this Weapon to be able to fire more than 1 bullet in a single + * update, then set this property to `true`. When `true` the Weapon plugin won't + * set the shot / firing timers until the `postRender` phase of the game loop. + * This means you can call `fire` (and similar methods) as often as you like in one + * single game update. + * + * @type {boolean} + * @default + */ + this.multiFire = false; + + /** + * Internal multiFire test flag. + * + * @type {boolean} + */ + this._hasFired = false; + + /** + * If the Weapon is tracking a Sprite, should it also track the Sprites rotation? + * This is useful for a game such as Asteroids, where you want the weapon to fire based + * on the sprites rotation. + * + * @type {boolean} + * @default + */ + this.trackRotation = false; + + /** + * The Track Offset is a Point object that allows you to specify a pixel offset that bullets use + * when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels + * in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have + * the bullet launched from the center of the Sprite. + * + * @type {Phaser.Point} + */ + this.trackOffset = new Phaser.Point(); + + /** + * Internal firing rate time tracking variable. + * + * @type {number} + * @private + */ + this._nextFire = 0; + + /** + * Internal firing rate time tracking variable used by multiFire. + * + * @type {number} + * @private + */ + this._tempNextFire = 0; + + /** + * Internal firing rotation tracking point. + * + * @type {Phaser.Point} + * @private + */ + this._rotatedPoint = new Phaser.Point(); + +}; + +Phaser.Weapon.prototype = Object.create(Phaser.Plugin.prototype); +Phaser.Weapon.prototype.constructor = Phaser.Weapon; + +/** +* A {@link #bulletKillType} constant that stops the bullets from ever being destroyed automatically. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_NEVER = 0; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when their {@link #bulletLifespan} expires. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_LIFESPAN = 1; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets after they +* exceed the {@link #bulletDistance} from their original firing position. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_DISTANCE = 2; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WEAPON_BOUNDS = 3; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.Camera#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_CAMERA_BOUNDS = 4; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.World#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WORLD_BOUNDS = 5; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_STATIC_BOUNDS = 6; + +/** +* This method performs two actions: First it will check to see if the {@link #bullets} Group exists or not, +* and if not it creates it, adding it the `group` given as the 4th argument. +* +* Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame +* provided (if any). +* +* If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets +* in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of +* the in-flight bullets have been killed, freeing them up for use by the Weapon again. +* +* If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will +* keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however, +* so be careful it doesn't grow too large. +* +* You can either set the texture key and frame here, or via the {@link #bulletKey} and {@link #bulletFrame} +* properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a +* single Weapon instance must share the same texture key however. +* +* @method Phaser.Weapon#createBullets +* @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. +* @param {string} [key] - The Game.cache key of the image that this Sprite will use. +* @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. +* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.createBullets = function (quantity, key, frame, group) { + + if (quantity === undefined) { quantity = 1; } + if (group === undefined) { group = this.game.world; } + + if (this.bullets && !this.bullets.game) + { + this.bullets = null; + } + + if (!this.bullets) + { + this.bullets = this.game.add.physicsGroup(Phaser.Physics.ARCADE, group); + this.bullets.classType = this._bulletClass; + } + + if (quantity !== 0) + { + if (quantity === -1) + { + this.autoExpandBulletsGroup = true; + quantity = 1; + } + + this.bullets.createMultiple(quantity, key, frame); + + this.bullets.setAll('data.bulletManager', this); + + this.bulletKey = key; + this.bulletFrame = frame; + } + + return this; + +}; + +/** +* Call a function on each in-flight bullet in this Weapon. +* +* See {@link Phaser.Group#forEachExists forEachExists} for more details. +* +* @method Phaser.Weapon#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.forEach = function (callback, callbackContext) { + + this.bullets.forEachExists(callback, callbackContext, arguments); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `false` on each bullet in this Weapon. +* This has the effect of stopping them in-flight should they be moving. +* It also stops them being able to be checked for collision. +* +* @method Phaser.Weapon#pauseAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.pauseAll = function () { + + this.bullets.setAll('body.enable', false); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `true` on each bullet in this Weapon. +* This has the effect of resuming their motion should they be in-flight. +* It also enables them for collision checks again. +* +* @method Phaser.Weapon#resumeAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resumeAll = function () { + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Calls {@link Phaser.Bullet#kill} on every in-flight bullet in this Weapon. +* Also re-enables their physics bodies, should they have been disabled via {@link #pauseAll}. +* +* @method Phaser.Weapon#killAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.killAll = function () { + + this.bullets.callAllExists('kill', true); + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Resets the {@link #shots} counter back to zero. This is used when you've set +* {@link #fireLimit} and have hit (or just wish to reset) your limit. +* +* @method Phaser.Weapon#resetShots +* @param {integer} [newLimit] - Optionally set a new {@link #fireLimit}. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resetShots = function (newLimit) { + + this.shots = 0; + + if (newLimit !== undefined) + { + this.fireLimit = newLimit; + } + + return this; + +}; + +/** +* Destroys this Weapon. It removes itself from the PluginManager, destroys +* the {@link #bullets} Group, and nulls internal references. +* +* @method Phaser.Weapon#destroy +*/ +Phaser.Weapon.prototype.destroy = function () { + + this.parent.remove(this, false); + + this.bullets.destroy(); + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#update +* @protected +*/ +Phaser.Weapon.prototype.update = function () { + + if (this._bulletKillType === Phaser.Weapon.KILL_WEAPON_BOUNDS) + { + if (this.trackedSprite) + { + this.trackedSprite.updateTransform(); + this.bounds.centerOn(this.trackedSprite.worldPosition.x, this.trackedSprite.worldPosition.y); + } + else if (this.trackedPointer) + { + this.bounds.centerOn(this.trackedPointer.worldX, this.trackedPointer.worldY); + } + } + + if (this.autofire) + { + this.fire(); + } + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#postRender +* @protected +*/ +Phaser.Weapon.prototype.postRender = function () { + + if (!this.multiFire || !this._hasFired) + { + return; + } + + this._hasFired = false; + + this._nextFire = this._tempNextFire; + +}; + +/** +* Sets this Weapon to track the given Sprite, or any Object with a public {@link Phaser.Component.Core#world world} Point object. +* When a Weapon tracks a Sprite it will automatically update its {@link #fireFrom} value to match the Sprite's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location. +* +* Calling `trackSprite` will reset {@link #trackedPointer} to null, should it have been set, as you can +* only track _either_ a Sprite, or a Pointer, at once, but not both. +* +* @method Phaser.Weapon#trackSprite +* @param {Phaser.Sprite|Object} sprite - The Sprite to track the position of. +* @param {integer} [offsetX=0] - The horizontal offset from the Sprites position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Sprites position to be applied to the Weapon. +* @param {boolean} [trackRotation=false] - Should the Weapon also track the Sprites rotation? +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackSprite = function (sprite, offsetX, offsetY, trackRotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (trackRotation === undefined) { trackRotation = false; } + + this.trackedPointer = null; + this.trackedSprite = sprite; + this.trackRotation = trackRotation; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Sets this Weapon to track the given Pointer. +* When a Weapon tracks a Pointer it will automatically update its {@link #fireFrom} value to match the Pointer's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location. +* +* Calling `trackPointer` will reset {@link #trackedSprite} to null, should it have been set, as you can +* only track _either_ a Pointer, or a Sprite, at once, but not both. +* +* @method Phaser.Weapon#trackPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to track the position of. Defaults to `Input.activePointer` if not specified. +* @param {integer} [offsetX=0] - The horizontal offset from the Pointers position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Pointers position to be applied to the Weapon. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackPointer = function (pointer, offsetX, offsetY) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this.trackedPointer = pointer; + this.trackedSprite = null; + this.trackRotation = false; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Attempts to fire multiple bullets from the positions defined in the given array. +* +* If you provide a `from` argument, or if there is a tracked Sprite or Pointer, then +* the positions are treated as __offsets__ from the given objects position. +* +* If `from` is undefined, and there is no tracked object, then the bullets are fired +* from the given positions, as they exist in the world. +* +* Calling this method sets {@link #multiFire} to `true`. +* +* If there are not enough bullets available in the pool, and the pool cannot be extended, +* then this method may not fire from all of the given positions. +* +* When the bullets are launched they have their texture and frame updated, as required. +* The velocity of the bullets are calculated based on Weapon properties like {@link #bulletSpeed}. +* +* @method Phaser.Weapon#fireMany +* @param {array} positions - An array of positions. Each position can be any Object, as long as it has public `x` and `y` properties, such as Phaser.Point, { x: 0, y: 0 }, Phaser.Sprite, etc. +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullets **from** the `x` and `y` properties of this object, _instead_ of any {@link #trackedSprite} or `trackedPointer` that is set. +* @return {array} An array containing all of the fired Phaser.Bullet objects, if a launch was successful, otherwise an empty array. +*/ +Phaser.Weapon.prototype.fireMany = function (positions, from) { + + this.multiFire = true; + + var bullets = []; + + var _this = this; + + if (from || this.trackedSprite || this.trackedPointer) + { + positions.forEach(function(offset) { + + bullets.push(_this.fire(from, null, null, offset.x, offset.y)); + + }); + } + else + { + positions.forEach(function(position) { + + bullets.push(_this.fire(position)); + + }); + } + + return bullets; + +}; + +/** +* Attempts to fire a single Bullet from a tracked Sprite or Pointer, but applies an offset +* to the position first. This is the same as calling {@link #fire} and passing in the offset arguments. +* +* If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like {@link #bulletSpeed}. +* +* If you wish to fire multiple bullets in a single game update, then set {@link #multiFire} to `true` +* and you can call this method as many times as you like, per loop. See also {@link #fireMany}. +* +* @method Phaser.Weapon#fireOffset +* @param {number} [offsetX=0] - The horizontal offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @param {number} [offsetY=0] - The vertical offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fireOffset = function (offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + return this.fire(null, null, null, offsetX, offsetY); + +}; + +/** +* Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at. +* +* If you don't provide any of the arguments then it uses those set via properties such as {@link #trackedSprite}, +* {@link #bulletAngle} and so on. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like `bulletSpeed`. +* +* If you wish to fire multiple bullets in a single game update, then set `Weapon.multiFire = true` +* and you can call `fire` as many times as you like, per loop. Multiple fires in a single update +* only counts once towards the `shots` total, but you will still receive a Signal for each bullet. +* +* @method Phaser.Weapon#fire +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides {@link #trackedSprite} or `trackedPointer`. Pass `null` to ignore it. +* @param {number} [x] - The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [offsetX=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a horizontal offset from the launch position. +* @param {number} [offsetY=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a vertical offset from the launch position. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fire = function (from, x, y, offsetX, offsetY) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (this.game.time.now < this._nextFire || (this.fireLimit > 0 && this.shots === this.fireLimit)) + { + return null; + } + + var speed = this.bulletSpeed; + + // Apply +- speed variance + if (this.bulletSpeedVariance !== 0) + { + speed += Phaser.Math.between(-this.bulletSpeedVariance, this.bulletSpeedVariance); + } + + if (from) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(from.x, from.y); + } + else + { + this.fireFrom.x = from.x; + this.fireFrom.y = from.y; + } + } + else if (this.trackedSprite) + { + if (this.trackRotation) + { + this._rotatedPoint.set(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.worldRotation); + + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this._rotatedPoint.x, this._rotatedPoint.y); + } + else + { + this.fireFrom.x = this._rotatedPoint.x; + this.fireFrom.y = this._rotatedPoint.y; + } + } + else + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedSprite.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedSprite.world.y + this.trackOffset.y; + } + } + + if (this.bulletInheritSpriteSpeed) + { + speed += this.trackedSprite.body.speed; + } + } + else if (this.trackedPointer) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedPointer.world.x + this.trackOffset.x, this.trackedPointer.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedPointer.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedPointer.world.y + this.trackOffset.y; + } + } + + if (offsetX !== undefined) + { + this.fireFrom.x += offsetX; + } + + if (offsetY !== undefined) + { + this.fireFrom.y += offsetY; + } + + var fromX = (this.fireFrom.width > 1) ? this.fireFrom.randomX : this.fireFrom.x; + var fromY = (this.fireFrom.height > 1) ? this.fireFrom.randomY : this.fireFrom.y; + + var angle = (this.trackRotation) ? this.trackedSprite.angle : this.fireAngle; + + // The position (in world space) to fire the bullet towards, if set + if (x !== null && y !== null) + { + angle = this.game.math.radToDeg(Math.atan2(y - fromY, x - fromX)); + } + + // Apply +- angle variance + if (this.bulletAngleVariance !== 0) + { + angle += Phaser.Math.between(-this.bulletAngleVariance, this.bulletAngleVariance); + } + + var moveX = 0; + var moveY = 0; + + // Avoid sin/cos for right-angled shots + if (angle === 0 || angle === 180) + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + } + else if (angle === 90 || angle === 270) + { + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + else + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + + var bullet = null; + + if (this.autoExpandBulletsGroup) + { + bullet = this.bullets.getFirstExists(false, true, fromX, fromY, this.bulletKey, this.bulletFrame); + + bullet.data.bulletManager = this; + } + else + { + bullet = this.bullets.getFirstExists(false); + } + + if (bullet) + { + bullet.reset(fromX, fromY); + + bullet.data.fromX = fromX; + bullet.data.fromY = fromY; + bullet.data.killType = this.bulletKillType; + bullet.data.killDistance = this.bulletKillDistance; + bullet.data.rotateToVelocity = this.bulletRotateToVelocity; + + if (this.bulletKillType === Phaser.Weapon.KILL_LIFESPAN) + { + bullet.lifespan = this.bulletLifespan; + } + + bullet.angle = angle + this.bulletAngleOffset; + + // Frames and Animations + if (this.bulletAnimation !== '') + { + if (bullet.animations.getAnimation(this.bulletAnimation) === null) + { + var anim = this.anims[this.bulletAnimation]; + + bullet.animations.add(anim.name, anim.frames, anim.frameRate, anim.loop, anim.useNumericIndex); + } + + bullet.animations.play(this.bulletAnimation); + } + else + { + if (this.bulletFrameCycle) + { + bullet.frame = this.bulletFrames[this.bulletFrameIndex]; + + this.bulletFrameIndex++; + + if (this.bulletFrameIndex >= this.bulletFrames.length) + { + this.bulletFrameIndex = 0; + } + } + else if (this.bulletFrameRandom) + { + bullet.frame = this.bulletFrames[Math.floor(Math.random() * this.bulletFrames.length)]; + } + } + + if (bullet.data.bodyDirty) + { + if (this._data.customBody) + { + bullet.body.setSize(this._data.width, this._data.height, this._data.offsetX, this._data.offsetY); + } + + bullet.body.collideWorldBounds = this.bulletCollideWorldBounds; + + bullet.data.bodyDirty = false; + } + + bullet.body.velocity.set(moveX, moveY); + bullet.body.gravity.set(this.bulletGravity.x, this.bulletGravity.y); + + var next = 0; + + if (this.bulletSpeedVariance !== 0) + { + var rate = this.fireRate; + + rate += Phaser.Math.between(-this.fireRateVariance, this.fireRateVariance); + + if (rate < 0) + { + rate = 0; + } + + next = this.game.time.now + rate; + } + else + { + next = this.game.time.now + this.fireRate; + } + + if (this.multiFire) + { + if (!this._hasFired) + { + // We only add 1 to the 'shots' count for multiFire shots + this._hasFired = true; + this._tempNextFire = next; + this.shots++; + } + } + else + { + this._nextFire = next; + + this.shots++; + } + + this.onFire.dispatch(bullet, this, speed); + + if (this.fireLimit > 0 && this.shots === this.fireLimit) + { + this.onFireLimit.dispatch(this, this.fireLimit); + } + } + + return bullet; + +}; + +/** +* Fires a bullet **at** the given Pointer. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtPointer = function (pointer) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + + return this.fire(null, pointer.worldX, pointer.worldY); + +}; + +/** +* Fires a bullet **at** the given Sprite. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtSprite +* @param {Phaser.Sprite} [sprite] - The Sprite to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtSprite = function (sprite) { + + return this.fire(null, sprite.world.x, sprite.world.y); + +}; + +/** +* Fires a bullet **at** the given coordinates. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtXY +* @param {number} [x] - The x coordinate, in world space, to fire the bullet towards. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtXY = function (x, y) { + + return this.fire(null, x, y); + +}; + +/** +* You can modify the size of the physics Body the Bullets use to be any dimension you need. +* This allows you to make it smaller, or larger, than the parent Sprite. +* You can also control the x and y offset of the Body. This is the position of the +* Body relative to the top-left of the Sprite _texture_. +* +* For example: If you have a Sprite with a texture that is 80x100 in size, +* and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: +* +* `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, 34)` +* +* Where the first two parameters are the new Body size (32x32 pixels) relative to the Sprite's scale. +* 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 +* is the vertical offset. +* +* @method Phaser.Weapon#setBulletBodyOffset +* @param {number} width - The width of the Body. +* @param {number} height - The height of the Body. +* @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture. +* @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture. +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletBodyOffset = function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this._data.customBody = true; + this._data.width = width; + this._data.height = height; + this._data.offsetX = offsetX; + this._data.offsetY = offsetY; + + // Update all bullets in the pool + this.bullets.callAll('body.setSize', 'body', width, height, offsetX, offsetY); + this.bullets.setAll('data.bodyDirty', false); + + return this; + +}; + +/** +* Sets the texture frames that the bullets can use when being launched. +* +* This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet. +* +* It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values +* provided. Then it sets the frame index to be zero. +* +* You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames +* when they're fired, or pick one at random. +* +* @method Phaser.Weapon#setBulletFrames +* @param {integer} min - The minimum value the frame can be. Usually zero. +* @param {integer} max - The maximum value the frame can be. +* @param {boolean} [cycle=true] - Should the bullet frames cycle as they are fired? +* @param {boolean} [random=false] - Should the bullet frames be picked at random as they are fired? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletFrames = function (min, max, cycle, random) { + + if (cycle === undefined) { cycle = true; } + if (random === undefined) { random = false; } + + this.bulletFrames = Phaser.ArrayUtils.numberArray(min, max); + + this.bulletFrameIndex = 0; + + this.bulletFrameCycle = cycle; + this.bulletFrameRandom = random; + + return this; + +}; + +/** +* Adds a new animation under the given key. Optionally set the frames, frame rate and loop. +* The arguments are all the same as for `Animation.add`, and work in the same way. +* +* {@link #bulletAnimation} will be set to this animation after it's created. From that point on, all +* bullets fired will play using this animation. You can swap between animations by calling this method +* several times, and then just changing the {@link #bulletAnimation} property to the name of the animation +* you wish to play for the next launched bullet. +* +* If you wish to stop using animations at all, set {@link #bulletAnimation} to '' (an empty string). +* +* @method Phaser.Weapon#addBulletAnimation +* @param {string} name - The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast". +* @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.addBulletAnimation = function (name, frames, frameRate, loop, useNumericIndex) { + + this.anims[name] = { + name: name, + frames: frames, + frameRate: frameRate, + loop: loop, + useNumericIndex: useNumericIndex + }; + + // Add the animation to any existing bullets in the pool + this.bullets.callAll('animations.add', 'animations', name, frames, frameRate, loop, useNumericIndex); + + this.bulletAnimation = name; + + return this; + +}; + +/** +* Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets +* both in-flight, and available. And optionally the physics debug bodies of the bullets. +* +* @method Phaser.Weapon#debug +* @param {integer} [x=16] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {integer} [y=32] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {boolean} [debugBodies=false] - Optionally draw the physics body of every bullet in-flight. +*/ +Phaser.Weapon.prototype.debug = function (x, y, debugBodies) { + + if (x === undefined) { x = 16; } + if (y === undefined) { y = 32; } + if (debugBodies === undefined) { debugBodies = false; } + + this.game.debug.text("Weapon Plugin", x, y); + this.game.debug.text("Bullets Alive: " + this.bullets.total + " - Total: " + this.bullets.length, x, y + 24); + + if (debugBodies) + { + this.bullets.forEachExists(this.game.debug.body, this.game.debug, 'rgba(255, 0, 255, 0.8)'); + } + +}; + +/** +* The Class of the bullets that are launched by this Weapon. Defaults to {@link Phaser.Bullet}, but can be +* overridden before calling `createBullets` and set to your own class type. +* +* It should be a constructor function accepting `(game, x, y, key, frame)`. +* +* @name Phaser.Weapon#bulletClass +* @property {function} bulletClass +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletClass", { + + get: function () { + + return this._bulletClass; + + }, + + set: function (classType) { + + this._bulletClass = classType; + + // `this.bullets` exists only after createBullets() + if (this.bullets) { + this.bullets.classType = this._bulletClass; + } + } + +}); + +/** +* This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`. +* +* There are 7 different "kill types" available: +* +* * `Phaser.Weapon.KILL_NEVER` +* The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code. +* +* * `Phaser.Weapon.KILL_LIFESPAN` +* The bullets are automatically killed when their `bulletLifespan` amount expires. +* +* * `Phaser.Weapon.KILL_DISTANCE` +* The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position. +* +* * `Phaser.Weapon.KILL_WEAPON_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* +* * `Phaser.Weapon.KILL_CAMERA_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.Camera#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_WORLD_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.World#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_STATIC_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to +* match the position of a tracked sprite or pointer. +* +* @name Phaser.Weapon#bulletKillType +* @property {integer} bulletKillType +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletKillType", { + + get: function () { + + return this._bulletKillType; + + }, + + set: function (type) { + + switch (type) + { + case Phaser.Weapon.KILL_STATIC_BOUNDS: + case Phaser.Weapon.KILL_WEAPON_BOUNDS: + this.bulletBounds = this.bounds; + break; + + case Phaser.Weapon.KILL_CAMERA_BOUNDS: + this.bulletBounds = this.game.camera.view; + break; + + case Phaser.Weapon.KILL_WORLD_BOUNDS: + this.bulletBounds = this.game.world.bounds; + break; + } + + this._bulletKillType = type; + + } + +}); + +/** +* Should bullets collide with the World bounds or not? +* +* @name Phaser.Weapon#bulletCollideWorldBounds +* @property {boolean} bulletCollideWorldBounds +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletCollideWorldBounds", { + + get: function () { + + return this._bulletCollideWorldBounds; + + }, + + set: function (value) { + + this._bulletCollideWorldBounds = value; + + this.bullets.setAll('body.collideWorldBounds', value); + this.bullets.setAll('data.bodyDirty', false); + + } + +}); + +/** +* The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Weapon.prototype, "x", { + + get: function () { + + return this.fireFrom.x; + + }, + + set: function (value) { + + this.fireFrom.x = value; + } + +}); + +/** +* The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Weapon.prototype, "y", { + + get: function () { + + return this.fireFrom.y; + + }, + + set: function (value) { + + this.fireFrom.y = value; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites, +* with a few extra properties in the data object to handle Weapon specific features. +* +* @class Phaser.Bullet +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Bullet = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + this.anchor.set(0.5); + + this.data = { + bulletManager: null, + fromX: 0, + fromY: 0, + bodyDirty: true, + rotateToVelocity: false, + killType: 0, + killDistance: 0 + }; + +}; + +Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Bullet.prototype.constructor = Phaser.Bullet; + +/** +* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool. +* Also dispatches the `Weapon.onKill` signal. +* +* @method Phaser.Bullet#kill +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + this.data.bulletManager.onKill.dispatch(this); + + return this; + +}; + +/** +* Updates the Bullet, killing as required. +* +* @method Phaser.Bullet#update +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.update = function () { + + if (!this.exists) + { + return; + } + + if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN) + { + if (this.data.killType === Phaser.Weapon.KILL_DISTANCE) + { + if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance) + { + this.kill(); + } + } + else + { + if (!this.data.bulletManager.bulletBounds.intersects(this)) + { + this.kill(); + } + } + } + + if (this.data.rotateToVelocity) + { + this.rotation = this.body.velocity.atan(); + } + + if (this.data.bulletManager.bulletWorldWrap) + { + this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding); + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. +* +* Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to +* the Video instead (see `startMediaStream` method) +* +* The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback +* changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. +* +* Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. +* +* If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. +* Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. +* +* On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. +* This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio +* it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` +* method to try and work around this limitation, but see the method help for details. +* +* Small screen devices, especially iPod and iPhone will launch the video in its own native video player, +* outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. +* +* Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) +* then you need to add your own event listener +* +* @class Phaser.Video +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. +* @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) +*/ +Phaser.Video = function (game, key, url) { + + if (key === undefined) { key = null; } + if (url === undefined) { url = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. + * @default null + */ + this.key = key; + + /** + * @property {number} width - The width of the video in pixels. + * @default + */ + this.width = 0; + + /** + * @property {number} height - The height of the video in pixels. + * @default + */ + this.height = 0; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.VIDEO; + + /** + * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. + * @default + */ + this.touchLocked = false; + + /** + * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. + */ + this.onChangeSource = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam. + */ + this.onAccess = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. + */ + this.onError = new Phaser.Signal(); + + /** + * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. + * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. + * @property {Phaser.Signal} onTimeout + */ + this.onTimeout = new Phaser.Signal(); + + /** + * This signal is dispatched when the Video is unlocked. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * Start playing the video when it's unlocked. + * @property {boolean} playWhenUnlocked + * @default + */ + this.playWhenUnlocked = true; + + /** + * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. + * @default + */ + this.timeout = 15000; + + /** + * @property {integer} _timeOutID - setTimeout ID. + * @private + */ + this._timeOutID = null; + + /** + * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document. + */ + this.video = null; + + /** + * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. + */ + this.videoStream = null; + + /** + * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam. + */ + this.isStreaming = false; + + /** + * When starting playback of a video Phaser will monitor its readyState using a setTimeout call. + * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * @property {integer} retryLimit + * @default + */ + this.retryLimit = 20; + + /** + * @property {integer} retry - The current retry attempt. + * @default + */ + this.retry = 0; + + /** + * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video. + * @default + */ + this.retryInterval = 500; + + /** + * @property {integer} _retryID - The callback ID of the retry setTimeout. + * @private + */ + this._retryID = null; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {boolean} _codePaused - Internal paused tracking var. + * @private + * @default + */ + this._codePaused = false; + + /** + * @property {boolean} _paused - Internal paused tracking var. + * @private + * @default + */ + this._paused = false; + + /** + * @property {boolean} _pending - Internal var tracking play pending. + * @private + * @default + */ + this._pending = false; + + /** + * @property {boolean} _pendingChangeSource - Internal var tracking play pending. + * @private + * @default + */ + this._pendingChangeSource = false; + + /** + * @property {boolean} _autoplay - Internal var tracking autoplay when changing source. + * @private + * @default + */ + this._autoplay = false; + + /** + * @property {function} _endCallback - The addEventListener ended function. + * @private + */ + this._endCallback = null; + + /** + * @property {function} _playCallback - The addEventListener playing function. + * @private + */ + this._playCallback = null; + + if (key && this.game.cache.checkVideoKey(key)) + { + var _video = this.game.cache.getVideo(key); + + if (_video.isBlob) + { + this.createVideoFromBlob(_video.data); + } + else + { + this.video = _video.data; + } + + this.width = this.video.videoWidth; + this.height = this.video.videoHeight; + } + else if (url) + { + this.createVideoFromURL(url, false); + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + if (this.video && !url) + { + this.baseTexture = new PIXI.BaseTexture(this.video, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + else + { + this.baseTexture = new PIXI.BaseTexture(Phaser.Cache.DEFAULT.baseTexture.source, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering. + * @default + */ + this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video'); + + this.texture.setFrame(this.textureFrame); + + this.texture.valid = false; + + if (key !== null && this.video) + { + this.texture.valid = this.video.canplay; + } + + /** + * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). + * When called the BitmapData is updated with a grab taken from the current video playing or active video stream. + * If Phaser has been compiled without BitmapData support this property will always be `null`. + * + * @property {Phaser.BitmapData} snapshot + * @readOnly + */ + this.snapshot = null; + + if (Phaser.BitmapData) + { + this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height); + } + + if (this.game.device.needsTouchUnlock()) + { + this.setTouchLock(); + } + else + { + if (_video) + { + _video.locked = false; + } + } + +}; + +Phaser.Video.prototype = { + + /** + * Connects to an external media stream for the webcam, rather than using a local one. + * + * @method Phaser.Video#connectToMediaStream + * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses. + * @param {MediaStream} stream - The Video Stream data. + * @return {Phaser.Video} This Video object for method chaining. + */ + connectToMediaStream: function (video, stream) { + + if (video && stream) + { + this.video = video; + this.videoStream = stream; + + this.isStreaming = true; + this.baseTexture.source = this.video; + this.updateTexture(null, this.video.videoWidth, this.video.videoHeight); + + this.onAccess.dispatch(this); + } + + return this; + + }, + + /** + * Instead of playing a video file this method allows you to stream video data from an attached webcam. + * + * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam. + * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream. + * + * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError + * or MediaStreamError event. + * + * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions. + * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device. + * You can listen for this with the onChangeSource signal. + * + * @method Phaser.Video#startMediaStream + * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream. + * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source. + * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source. + * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia. + */ + startMediaStream: function (captureAudio, width, height) { + + if (captureAudio === undefined) { captureAudio = false; } + if (width === undefined) { width = null; } + if (height === undefined) { height = null; } + + if (!this.game.device.getUserMedia) + { + this.onError.dispatch(this, 'No getUserMedia'); + return false; + } + + if (this.videoStream !== null) + { + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + this.videoStream.stop(); + } + } + + this.removeVideoElement(); + + this.video = document.createElement("video"); + this.video.setAttribute('autoplay', 'autoplay'); + + if (width !== null) + { + this.video.width = width; + } + + if (height !== null) + { + this.video.height = height; + } + + // Request access to the webcam + + this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout); + + try { + navigator.getUserMedia( + { "audio": captureAudio, "video": true }, + this.getUserMediaSuccess.bind(this), + this.getUserMediaError.bind(this) + ); + } + catch (error) + { + this.getUserMediaError(error); + } + + return this; + + }, + + /** + * @method Phaser.Video#getUserMediaTimeout + * @private + */ + getUserMediaTimeout: function () { + + clearTimeout(this._timeOutID); + + this.onTimeout.dispatch(this); + + }, + + /** + * @method Phaser.Video#getUserMediaError + * @private + */ + getUserMediaError: function (event) { + + clearTimeout(this._timeOutID); + + this.onError.dispatch(this, event); + + }, + + /** + * @method Phaser.Video#getUserMediaSuccess + * @private + */ + getUserMediaSuccess: function (stream) { + + clearTimeout(this._timeOutID); + + // Attach the stream to the video + this.videoStream = stream; + + // Set the source of the video element with the stream from the camera + if (this.video.mozSrcObject !== undefined) + { + this.video.mozSrcObject = stream; + } + else + { + this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; + } + + var self = this; + + this.video.onloadeddata = function () { + + var retry = 10; + + function checkStream () { + + if (retry > 0) + { + if (self.video.videoWidth > 0) + { + // Patch for Firefox bug where the height can't be read from the video + var width = self.video.videoWidth; + var height = self.video.videoHeight; + + if (isNaN(self.video.videoHeight)) + { + height = width / (4/3); + } + + self.video.play(); + + self.isStreaming = true; + self.baseTexture.source = self.video; + self.updateTexture(null, width, height); + self.onAccess.dispatch(self); + } + else + { + window.setTimeout(checkStream, 500); + } + } + else + { + console.warn('Unable to connect to video stream. Webcam error?'); + } + + retry--; + } + + checkStream(); + + }; + + }, + + /** + * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format. + * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience. + * + * @method Phaser.Video#createVideoFromBlob + * @param {Blob} blob - The Blob containing the video data. + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromBlob: function (blob) { + + var _this = this; + + this.video = document.createElement("video"); + this.video.controls = false; + this.video.setAttribute('autoplay', 'autoplay'); + this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true); + this.video.src = window.URL.createObjectURL(blob); + this.video.canplay = true; + + return this; + + }, + + /** + * Creates a new Video element from the given URL. + * + * @method Phaser.Video#createVideoFromURL + * @param {string} url - The URL of the video. + * @param {boolean} [autoplay=false] - Automatically start the video? + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromURL: function (url, autoplay) { + + if (autoplay === undefined) { autoplay = false; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + if (this.texture) + { + this.texture.valid = false; + } + + this.video = document.createElement("video"); + this.video.controls = false; + + if (autoplay) + { + this.video.setAttribute('autoplay', 'autoplay'); + } + + this.video.src = url; + + this.video.canplay = true; + + this.video.load(); + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.key = url; + + return this; + + }, + + /** + * Called automatically if the video source changes and updates the internal texture dimensions. + * Then dispatches the onChangeSource signal. + * + * @method Phaser.Video#updateTexture + * @param {object} [event] - The event which triggered the texture update. + * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used. + * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used. + */ + updateTexture: function (event, width, height) { + + var change = false; + + if (width === undefined || width === null) { width = this.video.videoWidth; change = true; } + if (height === undefined || height === null) { height = this.video.videoHeight; } + + this.width = width; + this.height = height; + + if (this.baseTexture.source !== this.video) + { + this.baseTexture.source = this.video; + } + + this.baseTexture.forceLoaded(width, height); + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.valid = true; + + if (this.snapshot) + { + this.snapshot.resize(width, height); + } + + if (change && this.key !== null) + { + this.onChangeSource.dispatch(this, width, height); + + if (this._autoplay) + { + this.video.play(); + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + } + + }, + + /** + * Called when the video completes playback (reaches and ended state). + * Dispatches the Video.onComplete signal. + * + * @method Phaser.Video#complete + */ + complete: function () { + + this.onComplete.dispatch(this); + + }, + + /** + * Starts this video playing. + * + * If the video is already playing, or has been queued to play with `changeSource` then this method just returns. + * + * @method Phaser.Video#play + * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. + * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate. + * @return {Phaser.Video} This Video object for method chaining. + */ + play: function (loop, playbackRate) { + + if (this._pendingChangeSource) + { + return this; + } + + if (loop === undefined) { loop = false; } + if (playbackRate === undefined) { playbackRate = 1; } + + if (this.game.sound.onMute) + { + this.game.sound.onMute.add(this.setMute, this); + this.game.sound.onUnMute.add(this.unsetMute, this); + + if (this.game.sound.mute) + { + this.setMute(); + } + } + + this.game.onPause.add(this.setPause, this); + this.game.onResume.add(this.setResume, this); + + this._endCallback = this.complete.bind(this); + + this.video.addEventListener('ended', this._endCallback, true); + this.video.addEventListener('webkitendfullscreen', this._endCallback, true); + + if (loop) + { + this.video.loop = 'loop'; + } + else + { + this.video.loop = ''; + } + + this.video.playbackRate = playbackRate; + + if (this.touchLocked) + { + this._pending = true; + } + else + { + this._pending = false; + + if (this.key !== null) + { + if (this.video.readyState !== 4) + { + this.retry = this.retryLimit; + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + this._playCallback = this.playHandler.bind(this); + this.video.addEventListener('playing', this._playCallback, true); + } + } + + this.video.play(); + + this.onPlay.dispatch(this, loop, playbackRate); + } + + return this; + + }, + + /** + * Called when the video starts to play. Updates the texture. + * + * @method Phaser.Video#playHandler + * @private + */ + playHandler: function () { + + this.video.removeEventListener('playing', this._playCallback, true); + + this.updateTexture(); + + }, + + /** + * Stops the video playing. + * + * This removes all locally set signals. + * + * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead. + * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to + * call `Video.destroy` instead. + * + * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam. + * + * @method Phaser.Video#stop + * @return {Phaser.Video} This Video object for method chaining. + */ + stop: function () { + + if (this.game.sound.onMute) + { + this.game.sound.onMute.remove(this.setMute, this); + this.game.sound.onUnMute.remove(this.unsetMute, this); + } + + this.game.onPause.remove(this.setPause, this); + this.game.onResume.remove(this.setResume, this); + + // Stream or file? + + if (this.isStreaming) + { + if (this.video.mozSrcObject) + { + this.video.mozSrcObject.stop(); + this.video.src = null; + } + else + { + this.video.src = ''; + + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + if (this.videoStream.getTracks) + { + this.videoStream.getTracks().forEach(function (track) { + track.stop(); + }); + } + else + { + this.videoStream.stop(); + } + } + } + + this.videoStream = null; + this.isStreaming = false; + } + else + { + this.video.removeEventListener('ended', this._endCallback, true); + this.video.removeEventListener('webkitendfullscreen', this._endCallback, true); + this.video.removeEventListener('playing', this._playCallback, true); + + if (this.touchLocked) + { + this._pending = false; + } + else + { + this.video.pause(); + } + } + + return this; + + }, + + /** + * Updates the given Display Objects so they use this Video as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.Video#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.Video} This Video object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. + * + * @method Phaser.Video#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set Video.disableTextureUpload to `true`. + * + * @method Phaser.Video#render + */ + render: function () { + + if (!this.disableTextureUpload && this.playing) + { + this.baseTexture.dirty(); + } + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + this.video.muted = true; + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + this.video.muted = false; + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setPause + * @private + */ + setPause: function () { + + if (this._paused || this.touchLocked) + { + return; + } + + this._paused = true; + + this.video.pause(); + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setResume + * @private + */ + setResume: function () { + + if (!this._paused || this._codePaused || this.touchLocked) + { + return; + } + + this._paused = false; + + if (!this.video.ended) + { + this.video.play(); + } + + }, + + /** + * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it. + * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over" + * split into three different Video objects, then you will need the user to touch-unlock every single one of them. + * + * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains + * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again. + * + * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate. + * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it + * cannot render the new video on iOS (desktop browsers cope better). + * + * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know + * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state + * are adopted automatically by the new video. + * + * @method Phaser.Video#changeSource + * @param {string} src - The new URL to change the video.src to. + * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated? + * @return {Phaser.Video} This Video object for method chaining. + */ + changeSource: function (src, autoplay) { + + if (autoplay === undefined) { autoplay = true; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + this.texture.valid = false; + + this.video.pause(); + + this._pendingChangeSource = true; + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.video.src = src; + + this.video.load(); + + this._autoplay = autoplay; + + if (!autoplay) + { + this.paused = true; + } + + return this; + + }, + + /** + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.Video#checkVideoProgress + * @private + */ + checkVideoProgress: function () { + + // if (this.video.readyState === 2 || this.video.readyState === 4) + if (this.video.readyState === 4) + { + this._pendingChangeSource = false; + + // We've got enough data to update the texture for playback + this.updateTexture(); + } + else + { + this.retry--; + + if (this.retry > 0) + { + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming); + } + } + + }, + + /** + * Sets the Input Manager touch callback to be Video.unlock. + * Required for mobile video unlocking. Mostly just used internally. + * + * @method Phaser.Video#setTouchLock + */ + setTouchLock: function () { + + this.game.input.addTouchLockCallback(this.unlock, this, true); + this.touchLocked = true; + + }, + + /** + * Enables the video on mobile devices, usually after the first touch. + * If the SoundManager hasn't been unlocked then this will automatically unlock that as well. + * Only one video can be pending unlock at any one time. + * + * @method Phaser.Video#unlock + */ + unlock: function () { + + this.touchLocked = false; + + if (this.playWhenUnlocked) + { + this.video.play(); + + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + + if (this.key) + { + var _video = this.game.cache.getVideo(this.key); + + if (_video && !_video.isBlob) + { + _video.locked = false; + } + } + + this.onTouchUnlock.dispatch(this); + + return true; + + }, + + /** + * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData. + * + * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw. + * + * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy. + * + * @method Phaser.Video#grab + * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false. + * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining. + */ + grab: function (clear, alpha, blendMode) { + + if (clear === undefined) { clear = false; } + if (alpha === undefined) { alpha = 1; } + if (blendMode === undefined) { blendMode = null; } + + if (this.snapshot === null) + { + console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable'); + return; + } + + if (clear) + { + this.snapshot.cls(); + } + + this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode); + + return this.snapshot; + + }, + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * Also removes the autoplay and src attributes and nulls the reference. + * + * @method Phaser.Video#removeVideoElement + */ + removeVideoElement: function () { + + if (!this.video) + { + return; + } + + if (this.video.parentNode) + { + this.video.parentNode.removeChild(this.video); + } + + while (this.video.hasChildNodes()) + { + this.video.removeChild(this.video.firstChild); + } + + this.video.removeAttribute('autoplay'); + this.video.removeAttribute('src'); + + this.video = null; + + }, + + /** + * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`. + * If any Sprites are using this Video as their texture it is up to you to manage those. + * + * @method Phaser.Video#destroy + */ + destroy: function () { + + this.stop(); + + this.removeVideoElement(); + + if (this.touchLocked) + { + this.game.input.touch.removeTouchLockCallback(this.unlock, this); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + + } + +}; + +/** +* @name Phaser.Video#currentTime +* @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time. +*/ +Object.defineProperty(Phaser.Video.prototype, "currentTime", { + + get: function () { + + return (this.video) ? this.video.currentTime : 0; + + }, + + set: function (value) { + + this.video.currentTime = value; + + } + +}); + +/** +* @name Phaser.Video#duration +* @property {number} duration - The duration of the video in seconds. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "duration", { + + get: function () { + + return (this.video) ? this.video.duration : 0; + + } + +}); + +/** +* @name Phaser.Video#progress +* @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "progress", { + + get: function () { + + return (this.video) ? (this.video.currentTime / this.video.duration) : 0; + + } + +}); + +/** +* @name Phaser.Video#mute +* @property {boolean} mute - Gets or sets the muted state of the Video. +*/ +Object.defineProperty(Phaser.Video.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || null; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* Gets or sets the paused state of the Video. +* If the video is still touch locked (such as on iOS devices) this call has no effect. +* +* @name Phaser.Video#paused +* @property {boolean} paused +*/ +Object.defineProperty(Phaser.Video.prototype, "paused", { + + get: function () { + + return this._paused; + + }, + + set: function (value) { + + value = value || null; + + if (this.touchLocked) + { + return; + } + + if (value) + { + if (this._paused) + { + return; + } + + this._codePaused = true; + this.setPause(); + } + else + { + if (!this._paused) + { + return; + } + + this._codePaused = false; + this.setResume(); + } + } + +}); + +/** +* @name Phaser.Video#volume +* @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Video.prototype, "volume", { + + get: function () { + + return (this.video) ? this.video.volume : 1; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this.video) + { + this.video.volume = value; + } + + } + +}); + +/** +* @name Phaser.Video#playbackRate +* @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing. +*/ +Object.defineProperty(Phaser.Video.prototype, "playbackRate", { + + get: function () { + + return (this.video) ? this.video.playbackRate : 1; + + }, + + set: function (value) { + + if (this.video) + { + this.video.playbackRate = value; + } + + } + +}); + +/** +* Gets or sets if the Video is set to loop. +* Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. +* If the video isn't yet set this will always return false. +* +* @name Phaser.Video#loop +* @property {boolean} loop +*/ +Object.defineProperty(Phaser.Video.prototype, "loop", { + + get: function () { + + return (this.video) ? this.video.loop : false; + + }, + + set: function (value) { + + if (value && this.video) + { + this.video.loop = 'loop'; + } + else if (this.video) + { + this.video.loop = ''; + } + + } + +}); + +/** +* @name Phaser.Video#playing +* @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "playing", { + + get: function () { + + return (this.video) ? !(this.video.paused && this.video.ended) : false; + + } + +}); + +Phaser.Video.prototype.constructor = Phaser.Video; + +/* global Phaser:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Pixi expects these globals to exist + +if (PIXI.blendModes === undefined) +{ + PIXI.blendModes = Phaser.blendModes; +} + +if (PIXI.scaleModes === undefined) +{ + PIXI.scaleModes = Phaser.scaleModes; +} + +if (PIXI.Texture.emptyTexture === undefined) +{ + PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture()); +} + +if (PIXI.DisplayObject._tempMatrix === undefined) +{ + PIXI.DisplayObject._tempMatrix = new Phaser.Matrix(); +} + +PIXI.TextureSilentFail = true; + +// Required by Particle Storm +PIXI.canUseNewCanvasBlendModes = function () { + return Phaser.Device.canUseMultiply; +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = Phaser; + } + exports.Phaser = Phaser; + } else if (typeof define !== 'undefined' && define.amd) { + define('Phaser', (function() { return root.Phaser = Phaser; })() ); + } else { + root.Phaser = Phaser; + } + + return Phaser; +}).call(this); + +/* +* "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer +*/ diff --git a/Digital Assignment 3/js/phaser.map b/Digital Assignment 3/js/phaser.map new file mode 100644 index 000000000..70723bbf8 --- /dev/null +++ b/Digital Assignment 3/js/phaser.map @@ -0,0 +1 @@ +{"version":3,"sources":["phaser.js"],"names":["e","exports","module","f","window","global","self","p2","t","n","r","s","o","u","a","require","i","Error","call","length","1","_dereq_","Line","Scalar","lineInt","l1","l2","precision","a1","b1","c1","a2","b2","c2","det","eq","segmentsIntersect","p1","q1","q2","dx","dy","da","db","./Scalar","2","Point","area","b","c","left","leftOn","right","rightOn","tmpPoint1","tmpPoint2","collinear","thresholdAngle","ab","bc","dot","magA","Math","sqrt","magB","acos","sqdist","3","Polygon","this","vertices","getIntersectionPoint","delta","prototype","at","v","first","last","clear","append","poly","from","to","push","makeCCW","br","reverse","tmp","N","pop","isReflex","tmpLine1","tmpLine2","canSee","p","dist","copy","j","targetPoly","k","getCutEdges","min","tmp1","tmp2","tmpPoly","nDiags","Number","MAX_VALUE","decomp","edges","slice","cutEdges","Array","polys","cutEdge","result","splice","indexOf","isSimple","path","quickDecomp","reflexVertices","steinerPoints","maxlevel","level","upperInt","lowerInt","upperDist","lowerDist","d","closestDist","upperIndex","lowerIndex","closestIndex","lowerPoly","upperPoly","console","warn","removeCollinearPoints","num","./Line","./Point","4","abs","5","./Polygon","6","name","version","description","author","keywords","main","engines","node","repository","type","url","bugs","licenses","devDependencies","grunt","grunt-contrib-jshint","grunt-contrib-nodeunit","grunt-contrib-uglify","grunt-contrib-watch","grunt-browserify","grunt-contrib-concat","dependencies","poly-decomp","7","AABB","options","lowerBound","vec2","create","upperBound","setFromPoints","points","position","angle","skinSize","l","rotate","cosAngle","cos","sinAngle","sin","x","y","add","aabb","extend","overlaps","u1","u2","containsPoint","point","overlapsRay","ray","dirFracX","direction","dirFracY","t1","t2","t3","t4","tmin","max","tmax","../math/vec2","../utils/Utils","8","Broadphase","world","boundingVolumeType","Body","BOUNDING_CIRCLE","setWorld","getCollisionPairs","boundingRadiusCheck","bodyA","bodyB","sub","d2","squaredLength","boundingRadius","aabbCheck","getAABB","boundingVolumeCheck","canCollide","KINEMATIC","STATIC","sleepState","SLEEPING","NAIVE","SAP","../objects/Body","9","NaiveBroadphase","constructor","bodies","Ncolliding","bi","bj","aabbQuery","aabbNeedsUpdate","updateAABB","../collision/Broadphase","../shapes/Circle","../shapes/Particle","../shapes/Plane","../shapes/Shape","10","Narrowphase","contactEquations","frictionEquations","enableFriction","enabledEquations","slipForce","frictionCoefficient","surfaceVelocity","contactEquationPool","ContactEquationPool","size","frictionEquationPool","FrictionEquationPool","restitution","stiffness","Equation","DEFAULT_STIFFNESS","relaxation","DEFAULT_RELAXATION","frictionStiffness","frictionRelaxation","enableFrictionReduction","collidingBodiesLastStep","TupleDictionary","contactSkinSize","setConvexToCapsuleShapeMiddle","convexShape","capsuleShape","set","radius","pointInConvex","worldPoint","convexOffset","convexAngle","worldVertex0","pic_worldVertex0","worldVertex1","pic_worldVertex1","r0","pic_r0","r1","pic_r1","verts","lastCross","v0","v1","cross","crossLength","Circle","Convex","Shape","Box","yAxis","fromValues","tmp3","tmp4","tmp5","tmp6","tmp7","tmp8","tmp9","tmp10","tmp11","tmp12","tmp13","tmp14","tmp15","tmp16","tmp17","tmp18","tmpArray","bodiesOverlap_shapePositionA","bodiesOverlap_shapePositionB","bodiesOverlap","shapePositionA","shapePositionB","Nshapesi","shapes","shapeA","toWorldFrame","Nshapesj","shapeB","collidedLastStep","id1","id","id2","get","reset","eqs","ce","fe","release","createContactEquation","firstImpact","needsUpdate","enabled","offset","createFrictionEquation","setSlipForce","relativeVelocity","createFrictionFromContact","contactPointA","contactPointB","rotate90cw","normalA","createFrictionFromAverage","numContacts","invNumContacts","scale","normalize","LINE","CONVEX","convexLine","convexBody","lineBody","lineShape","lineOffset","lineAngle","justTest","BOX","lineBox","boxBody","boxShape","boxOffset","boxAngle","convexCapsule_tempRect","width","height","convexCapsule_tempVec","CAPSULE","convexCapsule","convexPosition","capsuleBody","capsulePosition","capsuleAngle","circlePos","result1","circleConvex","result2","convexConvex","lineCapsule","linePosition","capsuleCapsule_tempVec1","capsuleCapsule_tempVec2","capsuleCapsule_tempRect1","capsuleCapsule","si","xi","ai","sj","xj","aj","circlePosi","circlePosj","enableFrictionBefore","circleCircle","rect","lineLine","positionA","angleA","positionB","angleB","PLANE","planeLine","planeBody","planeShape","planeOffset","planeAngle","worldVertex01","worldVertex11","worldEdge","worldEdgeUnit","worldNormal","worldTangent","PARTICLE","particleCapsule","particleBody","particleShape","particlePosition","particleAngle","circleLine","CIRCLE","circleBody","circleShape","circleOffset","circleAngle","lineRadius","circleRadius","orthoDist","lineToCircleOrthoUnit","projectedPoint","centerDist","lineToCircle","lineEndToLineRadius","radiusSum","pos","pos0","pos1","pow","circleCapsule","worldVertex","closestEdgeProjectedPoint","candidate","candidateDist","minCandidate","found","minCandidateDistance","candidateDistance","localVertex","particleConvex","particleOffset","convexToparticle","minEdgeNormal","offsetA","offsetB","radiusA","radiusB","planeConvex","numReported","particlePlane","circleParticle","planeCapsule_tmpCircle","planeCapsule_tmp1","planeCapsule_tmp2","planeCapsule","capsuleOffset","end1","end2","circle","numContacts1","circlePlane","numContacts2","numTotal","planeToCircle","temp","contact","sepAxis","worldPoint0","worldPoint1","penetrationVec","findSeparatingAxis","closestEdge1","getClosestEdge","closestEdge2","closestEdgeA","closestEdgeB","insideNumEdges","pcoa_tmp1","projectConvexOntoAxis","worldAxis","value","localAxis","fsa_tmp1","fsa_tmp2","fsa_tmp3","fsa_tmp4","fsa_tmp5","fsa_tmp6","offset1","angle1","offset2","angle2","maxDist","overlap","edge","normal","span1","span2","gce_tmp1","gce_tmp2","gce_tmp3","axis","flip","closestEdge","maxDot","circleHeightfield_candidate","circleHeightfield_dist","circleHeightfield_v0","circleHeightfield_v1","circleHeightfield_minCandidate","circleHeightfield_worldNormal","circleHeightfield_minCandidateNormal","HEIGHTFIELD","circleHeightfield","hfBody","hfShape","hfPos","hfAngle","data","heights","w","elementWidth","minCandidateNormal","idxA","floor","idxB","ceil","PI","convexHeightfield_v0","convexHeightfield_v1","convexHeightfield_tilePos","convexHeightfield_tempConvexShape","convexHeightfield","convexPos","tilePos","tileConvex","../equations/ContactEquation","../equations/Equation","../equations/FrictionEquation","../shapes/Box","../shapes/Convex","../utils/ContactEquationPool","../utils/FrictionEquationPool","../utils/TupleDictionary","11","Ray","checkCollisionResponse","undefined","skipBackfaces","collisionMask","collisionGroup","mode","ANY","callback","update","distanceFromIntersectionSquared","intersect","squaredDistance","CLOSEST","ALL","intersectBodies","shouldStop","body","intersectBody","intersectBody_worldPosition","collisionResponse","worldPosition","shape","worldAngle","intersectShape","_currentBody","_currentShape","raycast","reportIntersection","fraction","faceIndex","hasHit","../collision/AABB","../collision/RaycastResult","12","RaycastResult","isStopped","getHitDistance","distance","getHitPoint","out","lerp","stop","../collision/Ray","13","SAPBroadphase","axisList","axisIndex","that","_addBodyHandler","_removeBodyHandler","idx","Utils","appendArray","off","on","sortAxisList","sortList","14","Constraint","defaults","collideConnected","wakeUpBodies","equations","wakeUp","DISTANCE","GEAR","LOCK","PRISMATIC","REVOLUTE","setStiffness","setRelaxation","15","DistanceConstraint","localAnchorA","localAnchorB","worldAnchorA","worldAnchorB","maxForce","ri","rj","computeGq","setMaxForce","upperLimitEnabled","upperLimit","lowerLimitEnabled","lowerLimit","normalEquation","G","violating","minForce","rixn","rjxn","getMaxForce","./Constraint","16","GearConstraint","ratio","AngleLockEquation","maxTorque","setMaxTorque","setRatio","torque","getMaxTorque","../equations/AngleLockEquation","17","LockConstraint","localAngleB","rot","g","localOffsetB","force","xAxis","18","PrismaticConstraint","localAxisA","trans","gg","updateJacobian","disableRotationalLock","RotationalLockEquation","velocity","upperLimitEquation","ContactEquation","lowerLimitEquation","motorEquation","motorEnabled","motorSpeed","computeGW","vi","vj","wi","angularVelocity","wj","gmult","worldAxisA","orientedAnchorA","orientedAnchorB","relPosition","enableMotor","disableMotor","setLimits","lower","upper","../equations/RotationalLockEquation","19","RevoluteConstraint","pivotA","pivotB","worldPivot","localPivotA","localPivotB","worldPivotA","worldPivotB","RotationalVelocityEquation","relAngle","setMotorSpeed","speed","getMotorSpeed","../equations/RotationalVelocityEquation","20","./Equation","21","computeB","h","GW","Gq","computeGiMf","relVel","getVelocityAlongNormal","getVelocityAtPoint","subtract","22","ARRAY_TYPE","epsilon","timeStep","multiplier","qi","qj","computeGWlambda","vlambda","wlambda","iMfi","iMfj","fi","ti","angularForce","fj","tj","invMassi","invMassSolve","invMassj","invIi","invInertiaSolve","invIj","multiply","massMultiplier","computeGiMGt","addToWlambda_temp","addToWlambda_Gi","addToWlambda_Gj","addToWlambda","deltalambda","Gi","Gj","computeInvC","eps","23","FrictionEquation","getSlipForce","24","worldVectorA","worldVectorB","25","GiMf","26","EventEmitter","listener","context","_listeners","listeners","has","index","emit","event","listenerArray","target","27","ContactMaterial","materialA","materialB","Material","idCounter","friction","./Material","28","29","PolyK","GetArea","sum","Triangulate","tgs","avl","al","i0","i1","i2","ax","ay","bx","by","cx","cy","earFound","_convex","_PointInTriangle","px","py","v0x","v0y","v1x","v1y","v2x","v2y","dot00","dot01","dot02","dot11","dot12","invDenom","30","crossVZ","vec","zcomp","crossZV","toLocalFrame","framePosition","frameAngle","toGlobalFrame","localPoint","vectorToLocalFrame","worldVector","vectorToGlobalFrame","localVector","centroid","clone","mul","divide","div","sqrDist","len","sqrLen","negate","str","reflect","vector","getLineSegmentsIntersection","p0","p3","getLineSegmentsIntersectionFraction","s1_x","s1_y","s2_x","s2_y","31","_idCounter","mass","invMass","inertia","invInertia","fixedRotation","fixedX","fixedY","interpolatedPosition","interpolatedAngle","previousPosition","previousAngle","damping","angularDamping","DYNAMIC","allowSleep","wantsToSleep","AWAKE","sleepSpeedLimit","sleepTimeLimit","gravityScale","idleTime","timeLastSleepy","ccdSpeedThreshold","ccdIterations","concavePath","_wakeUpAfterNarrowphase","updateMassProperties","updateSolveMassProperties","setDensity","density","totalArea","getArea","shapeAABB","bodyAngle","computeAABB","updateBoundingRadius","addShape","removeShape","m","I","r2","computeMomentOfInertia","applyForce","relativePoint","rotForce","Body_applyForce_forceWorld","Body_applyForce_pointWorld","Body_applyForce_pointLocal","applyForceLocal","localForce","worldForce","vectorToWorldFrame","Body_applyImpulse_velo","applyImpulse","impulseVector","velo","rotVelo","Body_applyImpulse_impulseWorld","Body_applyImpulse_pointWorld","Body_applyImpulse_pointLocal","applyImpulseLocal","localImpulse","worldImpulse","fromPolygon","convexes","optimalDecomp","cm","centerOfMass","updateTriangles","updateCenterOfMass","adjustCenterOfMass","adjustCenterOfMass_tmp2","adjustCenterOfMass_tmp3","adjustCenterOfMass_tmp4","offset_times_area","setZeroForce","resetConstraintVelocity","addConstraintVelocity","applyDamping","dt","wakeUpEvent","sleep","sleepEvent","sleepTick","time","dontSleep","SLEEPY","overlapKeeper","bodiesAreOverlapping","integrate_fhMinv","integrate_velodt","integrate","minv","integrateToTimeOfImpact","end","startToEnd","rememberPosition","hit","startToEndAngle","timeOfImpact","rememberAngle","iter","tmid","narrowphase","sleepyEvent","../events/EventEmitter","32","LinearSpring","Spring","setWorldAnchorA","setWorldAnchorB","getWorldAnchorA","getWorldAnchorB","worldDistance","restLength","applyForce_r","applyForce_r_unit","applyForce_u","applyForce_f","applyForce_worldAnchorA","applyForce_worldAnchorB","applyForce_ri","applyForce_rj","applyForce_tmp","r_unit","rlen","ri_x_f","rj_x_f","./Spring","33","RotationalSpring","restAngle","34","35","TopDownVehicle","chassisBody","wheels","groundBody","preStepCallback","WheelConstraint","vehicle","forwardEquation","sideEquation","steerValue","engineForce","setSideFriction","sideFriction","localForwardVector","localPosition","apply","setBrakeForce","addToWorld","addBody","wheel","addConstraint","removeFromWorld","removeBody","removeConstraint","addWheel","wheelOptions","worldVelocity","getSpeed","tmpVec","../constraints/Constraint","36","Capsule","GSSolver","Heightfield","Particle","Plane","Pool","Solver","World","Object","defineProperty","../package.json","./collision/AABB","./collision/Broadphase","./collision/NaiveBroadphase","./collision/Narrowphase","./collision/Ray","./collision/RaycastResult","./collision/SAPBroadphase","./constraints/Constraint","./constraints/DistanceConstraint","./constraints/GearConstraint","./constraints/LockConstraint","./constraints/PrismaticConstraint","./constraints/RevoluteConstraint","./equations/AngleLockEquation","./equations/ContactEquation","./equations/Equation","./equations/FrictionEquation","./equations/RotationalVelocityEquation","./events/EventEmitter","./material/ContactMaterial","./material/Material","./math/vec2","./objects/Body","./objects/LinearSpring","./objects/RotationalSpring","./objects/Spring","./objects/TopDownVehicle","./shapes/Box","./shapes/Capsule","./shapes/Circle","./shapes/Convex","./shapes/Heightfield","./shapes/Line","./shapes/Particle","./shapes/Plane","./shapes/Shape","./solver/GSSolver","./solver/Solver","./utils/ContactEquationPool","./utils/FrictionEquationPool","./utils/Pool","./utils/Utils","./world/World","37","arguments","axes","updateArea","./Convex","./Shape","38","intersectCapsule_hitPointWorld","intersectCapsule_normal","intersectCapsule_l0","intersectCapsule_l1","intersectCapsule_unit_y","hitPointWorld","l0","halfLen","diagonalLengthSquared","sqrtDelta","inv2a","d1","39","Ray_intersectSphere_intersectionPoint","Ray_intersectSphere_normal","intersectionPoint","40","isArray","triangles","polyk","tmpVec1","tmpVec2","projectOntoLocalAxis","projectOntoWorldAxis","shapeOffset","shapeAngle","polykVerts","id3","updateCenterOfMass_centroid","updateCenterOfMass_centroid_times_mass","updateCenterOfMass_a","updateCenterOfMass_b","updateCenterOfMass_c","centroid_times_mass","triangleArea","denom","numer","intersectConvex_rayStart","intersectConvex_rayEnd","intersectConvex_normal","rayStart","rayEnd","../math/polyk","41","key","maxValue","minValue","updateMaxMinValues","getLineSegment","start","getSegmentIndex","getClampedSegmentIndex","intersectHeightfield_worldNormal","intersectHeightfield_l0","intersectHeightfield_l1","intersectHeightfield_localFrom","intersectHeightfield_localTo","localFrom","localTo","42","raycast_normal","raycast_l0","raycast_l1","raycast_unit_y","43","44","intersectPlane_planePointToFrom","intersectPlane_normal","intersectPlane_len","planePointToFrom","planeToFrom","n_dot_dir","45","material","sensor","46","GS","iterations","tolerance","arrayStep","lambda","Bs","invCs","useZeroRHS","frictionIterations","usedIterations","setArrayZero","array","solve","sortEquations","maxIter","maxFrictionIter","Neq","tolSquared","Nbodies","deltalambdaTot","iterateEquation","updateMultipliers","invDt","B","invC","lambdaj","GWlambda","lambdaj_plus_deltalambda","./Solver","47","equationSortFunction","mockWorld","solveIsland","island","removeAllEquations","addEquations","getBodies","sort","addEquation","removeEquation","ISLAND","48","destroy","equation","./Pool","49","50","IslandNodePool","IslandNode","../world/IslandNode","51","IslandPool","Island","../world/Island","52","OverlapKeeper","overlappingShapesLastState","overlappingShapesCurrentState","recordPool","OverlapKeeperRecordPool","tmpDict","tmpArray1","tick","current","keys","lastObject","getByKey","setOverlapping","getNewOverlaps","getDiff","getEndOverlaps","dictA","dictB","isNewOverlap","idA","idB","getNewBodyOverlaps","getBodyDiff","getEndBodyOverlaps","accumulator","./OverlapKeeperRecord","./OverlapKeeperRecordPool","./TupleDictionary","./Utils","53","OverlapKeeperRecord","54","record","55","objects","resize","object","56","getKey","dict","57","howmany","P2_ARRAY_TYPE","Float32Array","58","bodyIds","59","IslandManager","nodePool","islandPool","islands","nodes","queue","getUnvisitedNode","Nnodes","visited","visit","bds","Neqs","bfs","root","child","neighbors","split","ni","nj","./../utils/IslandNodePool","./../utils/IslandPool","./Island","./IslandNode","60","61","springs","disabledBodyCollisionPairs","solver","islandManager","gravity","frictionGravity","useWorldGravityAsFrictionGravity","useFrictionGravityOnZeroGravity","broadphase","constraints","defaultMaterial","defaultContactMaterial","lastTimeStep","applySpringForces","applyGravity","solveConstraints","contactMaterials","stepping","bodiesToBeRemoved","islandSplit","emitImpactEvent","_constraintIdCounter","_bodyIdCounter","postStepEvent","addBodyEvent","removeBodyEvent","addSpringEvent","spring","impactEvent","contactEquation","postBroadphaseEvent","pairs","sleepMode","NO_SLEEPING","beginContactEvent","endContactEvent","preSolveEvent","BODY_SLEEPING","ISLAND_SLEEPING","constraint","addContactMaterial","contactMaterial","removeContactMaterial","getContactMaterial","cmats","step_mg","xiw","xjw","step","timeSinceLastCalled","maxSubSteps","internalStep","substeps","endOverlaps","Nsprings","np","mg","gravityLen","ignoredPairs","Nconstraints","Nresults","runNarrowphase","ev","glen","aiw","ajw","reducedMass","resolver","numFrictionBefore","numFrictionEquations","addSpring","evt","removeSpring","getBodyById","disableBodyCollision","enableBodyCollision","cs","cms","hitTest_tmp1","hitTest_tmp2","hitTest","pb","ps","NS","setGlobalStiffness","setGlobalRelaxation","tmpAABB","../../package.json","../collision/Narrowphase","../collision/SAPBroadphase","../constraints/DistanceConstraint","../constraints/GearConstraint","../constraints/LockConstraint","../constraints/PrismaticConstraint","../constraints/RevoluteConstraint","../material/ContactMaterial","../material/Material","../objects/LinearSpring","../objects/RotationalSpring","../shapes/Capsule","../shapes/Line","../solver/GSSolver","../solver/Solver","../utils/OverlapKeeper","./IslandManager","_CreateEmptyTexture","gl","scaleMode","texture","createTexture","bindTexture","TEXTURE_2D","texParameteri","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","TEXTURE_MAG_FILTER","PIXI","scaleModes","LINEAR","NEAREST","TEXTURE_MIN_FILTER","texImage2D","RGBA","UNSIGNED_BYTE","_CreateFramebuffer","textureUnit","framebuffer","createFramebuffer","depthStencilBuffer","createRenderbuffer","colorBuffer","fbStatus","activeTexture","TEXTURE0","bindFramebuffer","FRAMEBUFFER","bindRenderbuffer","RENDERBUFFER","framebufferRenderbuffer","DEPTH_STENCIL_ATTACHMENT","renderBuffer","framebufferTexture2D","COLOR_ATTACHMENT0","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","error","_fbErrors","targetTexture","DisplayObject","pivot","rotation","alpha","visible","hitArea","renderable","parent","worldAlpha","worldTransform","Phaser","Matrix","worldScale","worldRotation","filterArea","_sr","_cr","_bounds","Rectangle","_currentBounds","_mask","_cacheAsBitmap","_cacheIsDirty","children","_destroyCachedSprite","updateTransform","game","tx","ty","pt","wt","PI2","rotationCache","determ","HALF_PI","transformCallback","transformCallbackContext","preUpdate","generateTexture","resolution","renderer","bounds","getLocalBounds","renderTexture","RenderTexture","_tempMatrix","render","updateCache","_generateCachedSprite","toGlobal","toLocal","applyInverse","_renderCachedSprite","renderSession","_cachedSprite","Sprite","_renderWebGL","_renderCanvas","baseTexture","_enableMultiTextureToggle","textureIndex","tempFilters","_filters","filters","anchor","displayObjectUpdateTransform","defineProperties","worldVisible","item","mask","isMask","passes","filterPasses","_filterBlock","blendMode","blendModes","MULTIPLY","NORMAL","cacheAsBitmap","DisplayObjectContainer","ignoreChildInput","addChild","addChildAt","removeChild","swapChildren","child2","index1","getChildIndex","index2","setChildIndex","currentIndex","getChildAt","removeChildAt","removeChildren","beginIndex","endIndex","range","removed","displayObjectContainerUpdateTransform","getBounds","targetCoordinateSpace","isTargetCoordinateSpaceDisplayObject","isTargetCoordinateSpaceThisOrParent","contains","matrixCache","identityMatrix","childBounds","childMaxX","childMaxY","minX","Infinity","minY","maxX","maxY","childVisible","w0","w1","h0","h1","x1","y1","x2","y2","x3","y3","x4","y4","targetCoordinateSpaceBounds","spriteBatch","flush","filterManager","pushFilter","maskManager","pushMask","popMask","popFilter","_width","_height","defaultAnchor","Texture","emptyTexture","tint","cachedTint","tintedTexture","shader","exists","hasLoaded","onTextureUpdate","frame","setTexture","destroyBase","skipRender","valid","matrix","crop","currentBlendMode","globalCompositeOperation","blendModesCanvas","globalAlpha","smoothProperty","trim","shakeX","shakeY","cw","ch","rotated","roundPixels","setTransform","requiresReTint","CanvasTinter","getTintedTexture","drawImage","source","initDefaultShaders","CompileVertexShader","shaderSrc","_CompileShader","VERTEX_SHADER","CompileFragmentShader","FRAGMENT_SHADER","shaderType","src","join","createShader","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","log","getShaderInfoLog","compileProgram","vertexSrc","fragmentSrc","fragmentShader","vertexShader","shaderProgram","createProgram","attachShader","linkProgram","getProgramParameter","LINK_STATUS","getProgramInfoLog","PixiShader","_UID","program","textureCount","firstRun","dirty","attributes","init","initMultitexShader","MAX_TEXTURES","getParameter","MAX_TEXTURE_IMAGE_UNITS","dynamicIfs","defaultVertexSrc","useProgram","uSamplerArray","getUniformLocation","projectionVector","offsetVector","dimensions","aVertexPosition","getAttribLocation","aTextureCoord","colorAttribute","aTextureIndex","indices","tempTexture","RGB","uniform1iv","uniforms","uniformLocation","initUniforms","initDefaultShader","uSampler","usingFilter","uniform","_init","initSampler2D","glMatrix","glValueLength","glFunc","uniformMatrix2fv","uniformMatrix3fv","uniformMatrix4fv","_glTextures","textureData","magFilter","minFilter","wrapS","wrapT","format","LUMINANCE","repeat","REPEAT","pixelStorei","UNPACK_FLIP_Y_WEBGL","flipY","border","uniform1i","syncUniforms","transpose","z","_dirty","instances","updateTexture","deleteProgram","PixiFastShader","uMatrix","aPositionCoord","aScale","aRotation","StripShader","translationMatrix","attribute","PrimitiveShader","tintColor","ComplexPrimitiveShader","color","glContexts","WebGLRenderer","config","defaultRenderer","extensions","WEBGL","transparent","autoResize","preserveDrawingBuffer","clearBeforeRender","view","canvas","_contextOptions","antialias","failIfMajorPerformanceCaveat","premultipliedAlpha","stencil","projection","shaderManager","WebGLShaderManager","WebGLSpriteBatch","WebGLMaskManager","WebGLFilterManager","stencilManager","WebGLStencilManager","blendModeManager","WebGLBlendModeManager","currentBatchedTextures","drawCount","maxTextureAvailableSpace","initContext","mapBlendModes","getContext","maxTextures","maxTextureSize","MAX_TEXTURE_SIZE","glContextId","disable","DEPTH_TEST","CULL_FACE","enable","BLEND","setContext","compression","etc1","getExtension","pvrtc","s3tc","ETC1","PVRTC","S3TC","setTexturePriority","textureNameCollection","clampPot","potSize","imageCache","cache","_cache","image","imageName","base","stage","contextLost","viewport","clearColor","_bgColor","COLOR_BUFFER_BIT","camera","_shake","renderDisplayObject","displayObject","buffer","setBlendMode","begin","style","updateCompressedTexture","textureMetaData","compressedTexImage2D","glExtensionFormat","mipmap","isPowerOfTwo","LINEAR_MIPMAP_LINEAR","NEAREST_MIPMAP_NEAREST","generateMipmap","_powerOf2","compressionAlgorithm","UNPACK_PREMULTIPLY_ALPHA_WEBGL","CanvasPool","remove","blendModesWebGL","modes","ONE","ONE_MINUS_SRC_ALPHA","ADD","SRC_ALPHA","DST_ALPHA","DST_COLOR","SCREEN","OVERLAY","DARKEN","LIGHTEN","COLOR_DODGE","COLOR_BURN","HARD_LIGHT","SOFT_LIGHT","DIFFERENCE","EXCLUSION","HUE","SATURATION","COLOR","LUMINOSITY","getMaxTextureUnit","enableMultiTexture","textureArray","blendModeWebGL","blendFunc","maskData","WebGLGraphics","updateGraphics","_webGL","pushStencil","popStencil","stencilStack","count","graphics","webGLData","bindGraphics","STENCIL_TEST","STENCIL_BUFFER_BIT","colorMask","stencilFunc","ALWAYS","stencilOp","KEEP","INVERT","drawElements","TRIANGLE_FAN","UNSIGNED_SHORT","EQUAL","DECR","INCR","TRIANGLE_STRIP","_currentGraphics","complexPrimitiveShader","setShader","uniform1f","toArray","uniform2f","uniform3fv","Color","hexToRGBArray","bindBuffer","ARRAY_BUFFER","vertexAttribPointer","FLOAT","ELEMENT_ARRAY_BUFFER","indexBuffer","primitiveShader","maxAttibs","attribState","tempAttribState","stack","defaultShader","fastShader","stripShader","creatureShader","CreatureShader","setAttribs","attribs","attribId","enableVertexAttribArray","disableVertexAttribArray","_currentId","currentShader","vertSize","vertexSize","numVerts","numIndices","ArrayBuffer","positions","colors","Uint32Array","Uint16Array","lastIndexCount","drawing","currentBatchSize","currentBaseTexture","textures","shaders","sprites","Filter","vertexBuffer","createBuffer","bufferData","STATIC_DRAW","DYNAMIC_DRAW","sprite","uvs","_uvs","aX","aY","a0","b0","c0","d0","_w1","_w0","_updateUvsInverted","x0","y0","renderTilingSprite","tilingTexture","TextureUvs","tilePosition","tileScaleOffset","offsetX","offsetY","scaleX","tileScale","scaleY","stride","bufferSubData","subarray","nextTexture","nextBlendMode","nextShader","batchSize","blendSwap","shaderSwap","skip","renderBatch","startIndex","TRIANGLES","deleteBuffer","WebGLFastSpriteBatch","maxSize","renderSprite","filterStack","texturePool","initShaderBuffers","filterBlock","_filterArea","_previous_stencil_mgr","filter","FilterTexture","padding","frameBuffer","_glFilterTexture","vertexArray","uvBuffer","uvArray","inputTexture","outputTexture","filterPass","applyFilterPass","sizeX","sizeY","currentFilter","colorArray","36054","36055","36057","36061","DEFAULT","renderbufferStorage","DEPTH_STENCIL","deleteFramebuffer","deleteTexture","CanvasBuffer","clearRect","CanvasMaskManager","save","cacheAlpha","transform","CanvasGraphics","renderGraphicsMask","clip","restore","tintMethod","tintWithMultiply","fillStyle","toString","substr","fillRect","tintWithPerPixel","rgbValues","pixelData","getImageData","pixels","canHandleAlpha","putImageData","CanvasRenderer","CANVAS","refresh","Canvas","getSmoothingPrefix","navigator","isCocoonJS","screencanvas","rgba","removeView","useNew","device","canUseMultiply","BaseTexture","complete","naturalWidth","naturalHeight","forceLoaded","removeByCanvas","unloadFromGPU","glTexture","fromCanvas","TextureSilentFail","noFrame","isTiling","requiresUpdate","setFrame","onBaseTextureLoaded","_updateUvs","tw","th","define","amd","WheelEventProxy","scaleFactor","deltaMode","_scaleFactor","_deltaMode","originalEvent","VERSION","GAMES","AUTO","HEADLESS","WEBGL_MULTI","NONE","LEFT","RIGHT","UP","DOWN","SPRITE","BUTTON","IMAGE","GRAPHICS","TEXT","TILESPRITE","BITMAPTEXT","GROUP","RENDERTEXTURE","TILEMAP","TILEMAPLAYER","EMITTER","POLYGON","BITMAPDATA","CANVAS_FILTER","WEBGL_FILTER","ELLIPSE","SPRITEBATCH","RETROFONT","POINTER","ROPE","RECTANGLE","MATRIX","POINT","ROUNDEDRECTANGLE","CREATURE","VIDEO","PENDING_ATLAS","HORIZONTAL","VERTICAL","LANDSCAPE","PORTRAIT","ANGLE_UP","ANGLE_DOWN","ANGLE_LEFT","ANGLE_RIGHT","ANGLE_NORTH_EAST","ANGLE_NORTH_WEST","ANGLE_SOUTH_EAST","ANGLE_SOUTH_WEST","TOP_LEFT","TOP_CENTER","TOP_RIGHT","LEFT_TOP","LEFT_CENTER","LEFT_BOTTOM","CENTER","RIGHT_TOP","RIGHT_CENTER","RIGHT_BOTTOM","BOTTOM_LEFT","BOTTOM_CENTER","BOTTOM_RIGHT","trunc","Function","bind","thisArg","bound","args","boundArgs","concat","TypeError","F","proto","arg","forEach","fun","CheapArray","assert","assign","varArgs","hasOwn","hasOwnProperty","nextSource","nextKey","reverseString","string","getProperty","obj","parts","_getProperty","setProperties","props","setProperty","_setProperty","val","currentObj","chanceRoll","chance","random","randomChoice","choice1","choice2","parseDimension","dimension","parseInt","innerWidth","innerHeight","pad","dir","padlen","isPlainObject","nodeType","copyIsArray","deep","mixinPrototype","mixin","replace","mixinKeys","childNodes","cloneNode","diameter","_diameter","_radius","circumference","setTo","copyFrom","copyTo","dest","round","output","circumferencePoint","asDegrees","sample","steps","startAngle","endAngle","linear","offsetPoint","top","bottom","equals","intersects","degToRad","intersectsRectangle","halfWidth","halfHeight","xCornerDist","yCornerDist","intersectsLine","returnPoints","del","p0Exists","pointOnSegment","p1Exists","Ellipse","normx","normy","fromPoints","fromSprite","startSprite","endSprite","useCenter","centerX","centerY","fromAngle","rotateAround","line","asSegment","intersectsPoints","midPoint","centerOn","pointOnLine","fuzzyEqual","xMin","xMax","yMin","yMax","coordinatesOnLine","stepRate","results","sx","sy","err","e2","wrap","uc","ua","ub","empty","bx1","by1","bx2","by2","intersectionWithRectangle","edgeIntersection","closestDistance","normalAngle","fromArray","newPos","translate","tx1","identity","invert","setToPolar","azimuth","clampX","clamp","clampY","equalsXY","fuzzyEquals","fuzzyEqualsXY","angleXY","atan2","radToDeg","atan","getMagnitude","getMagnitudeSq","setMagnitude","magnitude","isZero","limit","expand","perp","rperp","normalRightHand","negative","multiplyAdd","interpolate","project","amt","projectUnit","pointslength","parse","xProp","yProp","isPoint","sortClockwise","center","_points","closed","flattened","toNumberArray","flatten","inside","ix","iy","jx","jy","calculateArea","avgHeight","floorAll","ceilAll","copyFromBounds","inflate","containsRect","intersection","intersectsRaw","union","randomX","randomY","getPoint","sides","inflatePoint","createFromBounds","containsRaw","rx","ry","rw","rh","volume","sameDimensions","NEGATIVE_INFINITY","POSITIVE_INFINITY","EmptyRectangle","RoundedRectangle","Camera","deadzone","roundPx","atLimit","totalInView","onShakeComplete","Signal","onFlashComplete","onFadeComplete","fx","_targetPosition","_edge","_position","intensity","duration","horizontal","vertical","shakeBounds","_fxDuration","_fxType","_fixedView","FOLLOW_LOCKON","FOLLOW_PLATFORMER","FOLLOW_TOPDOWN","FOLLOW_TOPDOWN_TIGHT","SHAKE_BOTH","SHAKE_HORIZONTAL","SHAKE_VERTICAL","ENABLE_FX","boot","Graphics","follow","lerpX","lerpY","helper","unfollow","focusOn","setPosition","focusOnXY","shake","flash","beginFill","drawRect","endFill","fade","updateFX","updateShake","checkBounds","elapsedMS","dispatch","rnd","frac","updateTarget","math","setBoundsToWorld","vx","vw","vy","vh","setSize","resetFX","State","make","input","load","sound","state","tweens","particles","physics","preload","loadUpdate","loadRender","preRender","paused","resumed","pauseUpdate","shutdown","StateManager","pendingState","states","_pendingState","_clearWorld","_clearCache","_created","_args","onStateChange","onInitCallback","onPreloadCallback","onCreateCallback","onUpdateCallback","onRenderCallback","onResizeCallback","onPreRenderCallback","onLoadUpdateCallback","onLoadRenderCallback","onPausedCallback","onResumedCallback","onPauseUpdateCallback","onShutDownCallback","onPause","pause","onResume","resume","autoStart","newState","isBooted","callbackContext","clearWorld","clearCache","checkState","restart","dummy","previousStateKey","clearCurrentState","setCurrentState","totalQueuedFiles","totalQueuedPacks","loadComplete","removeAll","debug","link","unlink","_kickstart","getCurrentState","elapsedTime","renderType","_bindings","_prevParams","memorize","_shouldPropagate","active","_boundDispatch","validateListener","fnName","_registerListener","isOnce","listenerContext","priority","binding","prevIndex","_indexOfListener","SignalBinding","_addBinding","execute","_priority","cur","_listener","addOnce","_destroy","getNumListeners","halt","bindings","paramsArr","forget","dispose","_this","signal","_isOnce","_signal","callCount","params","handlerReturn","detach","isBound","getListener","getSignal","prevPoint","Date","mouse","date","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","sampleRate","iChannel0","iChannel1","iChannel2","iChannel3","setResolution","pointer","toFixed","totalElapsedSeconds","anchorX","anchorY","Cache","Plugin","hasPreUpdate","hasUpdate","hasPostUpdate","hasRender","hasPostRender","postRender","PluginManager","plugins","_len","_i","plugin","postUpdate","Stage","disableVisibilityChange","currentRenderOrderID","_hiddenVar","_onChange","parseConfig","setBackgroundColor","DOM","getOffset","setUserSelect","setTouchAction","checkVisibility","document","hidden","webkitHidden","mozHidden","msHidden","visibilityChange","_onClick","hasFocus","addEventListener","onblur","onfocus","onpagehide","onpageshow","cocoonJSApp","CocoonJS","App","onSuspended","onActivated","focusLoss","focusGain","gamePaused","gameResumed","valueToColor","updateColor","removeEventListener","silent","hash","removeFromHash","Group","addToStage","enableBody","physicsBodyType","Physics","ARCADE","physicsType","alive","ignoreDestroy","pendingDestroy","classType","cursor","inputEnableChildren","updateOnlyExistingChildren","onChildInputDown","onChildInputUp","onChildInputOver","onChildInputOut","enableBodyDebug","physicsSortDirection","onDestroy","cursorIndex","fixedToCamera","cameraOffset","_sortProperty","RETURN_NONE","RETURN_TOTAL","RETURN_CHILD","RETURN_ALL","SORT_ASCENDING","SORT_DESCENDING","updateZ","addToHash","inputEnabled","events","onAddedToGroup$dispatch","addAt","addMultiple","moveAll","getAt","createMultiple","quantity","singleKey","singleFrame","align","cellWidth","cellHeight","alignIn","resetCursor","next","previous","swap","child1","bringToTop","getIndex","sendToBack","moveUp","moveDown","xy","getByName","oldChild","newChild","hasProperty","operation","checkProperty","checkAlive","checkVisible","setAll","setAllChildren","checkAll","checkAny","addAll","property","amount","subAll","multiplyAll","divideAll","kill","killAll","callAllExists","revive","reviveAll","resetAll","checkExists","resetChild","existsValue","callbackFromArray","callAll","method","methodLength","contextLength","renderOrderID","predicate","ArraySet","forEachExists","iterate","forEachAlive","forEachDead","order","ascendingSortHandler","descendingSortHandler","customSort","sortHandler","returnType","total","getFirst","getFirstExists","createIfNull","getFirstAlive","getFirstDead","loadTexture","getTop","getBottom","getClosestTo","tempDistance","getFurthestFrom","countLiving","countDead","getRandom","ArrayUtils","getRandomItem","getRandomExists","list","getAll","pick","destroyPhase","onRemovedFromGroup$dispatch","group","destroyTexture","removeBetween","scatter","shuffle","destroyChildren","soft","_definedSize","stateChange","setBounds","useBounds","wrapAll","between","Game","physicsConfig","multiTexture","isRunning","raf","net","Device","lockRender","pendingStep","stepCount","onBlur","onFocus","_paused","_codePaused","currentUpdateID","updatesThisFrame","rendersThisFrame","_deltaTime","_lastCount","_spiraling","fpsProblemNotifier","forceSingleUpdate","forceSingleRender","dropFrames","_nextFpsNotification","enableDebug","RandomDataGenerator","now","whenReady","seed","ScaleManager","setUpRenderer","GameObjectFactory","GameObjectCreator","Loader","Time","TweenManager","Input","SoundManager","Particles","Create","Net","Debug","isDisabled","showDebugHeader","RequestAnimationFrame","stopFocus","focus","isReady","onReady","hideBanner","webAudio","ie","setImageRenderingCrisp","webGL","contextRestored","webGLRendererError","cocoonJS","smoothed","addToDOM","preventDefault","clearGLTextures","updateLogic","desiredFpsMult","updateRender","slowMotion","desiredFps","slowStep","elapsed","countUpdate","countRender","enableStep","disableStep","removeFromDOM","muteOnPause","setMute","cordova","iOS","unsetMute","hitCanvas","hitContext","moveCallbacks","customCandidateHandler","customCandidateHandlerContext","pollRate","multiInputOverride","MOUSE_TOUCH_COMBINE","maxPointers","tapRate","doubleTapRate","holdRate","justPressedRate","justReleasedRate","recordPointerHistory","recordRate","recordLimit","touchLockCallbacks","pointer1","pointer2","pointer3","pointer4","pointer5","pointer6","pointer7","pointer8","pointer9","pointer10","pointers","activePointer","mousePointer","keyboard","touch","mspointer","gamepad","resetLocked","onDown","onUp","onTap","onHold","minPriorityID","interactiveItems","_localPoint","_pollCounter","_oldPosition","_x","_y","MOUSE_OVERRIDES_TOUCH","TOUCH_OVERRIDES_MOUSE","MAX_POINTERS","Pointer","PointerMode","CURSOR","addPointer","Mouse","Touch","MSPointer","Keyboard","Gamepad","_onClickTrampoline","onClickTrampoline","setInteractiveCandidateHandler","addMoveCallback","addTouchLockCallback","onEnd","removeTouchLockCallback","executeTouchLockCallbacks","cb","deleteMoveCallback","CONTACT","hard","resetSpeed","startPointer","countActivePointers","updatePointer","identifier","move","stopPointer","getPointer","isActive","getPointerFromIdentifier","getPointerFromId","pointerId","getLocalPosition","Creature","TileSprite","graphicsData","fill","processClickTrampolines","mouseDownCallback","mouseUpCallback","mouseOutCallback","mouseOverCallback","mouseWheelCallback","capture","button","wheelDelta","locked","stopOnGameOut","pointerLock","_onMouseDown","_onMouseMove","_onMouseUp","_onMouseOut","_onMouseOver","_onMouseWheel","_wheelEvent","NO_BUTTON","LEFT_BUTTON","MIDDLE_BUTTON","RIGHT_BUTTON","BACK_BUTTON","FORWARD_BUTTON","WHEEL_UP","WHEEL_DOWN","android","chrome","onMouseDown","onMouseMove","onMouseUp","_onMouseUpGlobal","onMouseUpGlobal","_onMouseOutGlobal","onMouseOutGlobal","onMouseOut","onMouseOver","onMouseWheel","wheelEvent","mouseMoveCallback","withinGame","resetButtons","bindEvent","deltaY","requestPointerLock","element","mozRequestPointerLock","webkitRequestPointerLock","_pointerLockChange","pointerLockChange","pointerLockElement","mozPointerLockElement","webkitPointerLockElement","releasePointerLock","exitPointerLock","mozExitPointerLock","webkitExitPointerLock","_stubsGenerated","prop","makeBinder","detail","deltaX","wheelDeltaX","deltaZ","pointerDownCallback","pointerMoveCallback","pointerUpCallback","_onMSPointerDown","_onMSPointerMove","_onMSPointerUp","_onMSPointerUpGlobal","_onMSPointerOut","_onMSPointerOver","onPointerDown","onPointerMove","onPointerUp","onPointerUpGlobal","onPointerOut","onPointerOver","pointerType","DeviceButton","buttonCode","isDown","isUp","timeDown","timeUp","repeats","altKey","shiftKey","ctrlKey","onFloat","startStop","condition","padFloat","justPressed","justReleased","pointerMode","leftButton","middleButton","rightButton","backButton","forwardButton","eraserButton","ERASER_BUTTON","_holdSent","_history","_nextDrop","_stateReset","clientX","clientY","pageX","pageY","screenX","screenY","rawMovementX","rawMovementY","movementX","movementY","isMouse","previousTapTime","totalTouches","msSinceLastClick","targetObject","interactiveCandidates","positionDown","positionUp","_clickTrampolines","_trampolineTargetObject","processButtonsDown","processButtonsUp","processButtonsUpDown","buttons","down","toLowerCase","updateButtons","totalActivePointers","_touchedHandler","processInteractiveObjects","shift","fromClick","pollLocked","mozMovementX","webkitMovementX","mozMovementY","webkitMovementY","noPause","isDragged","highestRenderOrderID","highestInputPriorityID","candidateTarget","currentNode","checked","validForInput","checkPointerDown","checkPointerOver","priorityID","swapTarget","newTarget","_pointerOutHandler","_pointerOverHandler","leave","currentPointers","addClickTrampoline","callbackArgs","trampolines","trampoline","_releasedHandler","resetMovement","touchStartCallback","touchMoveCallback","touchEndCallback","touchEnterCallback","touchLeaveCallback","touchCancelCallback","_onTouchStart","_onTouchMove","_onTouchEnd","_onTouchEnter","_onTouchLeave","_onTouchCancel","onTouchStart","onTouchMove","onTouchEnd","onTouchEnter","onTouchLeave","onTouchCancel","consumeDocumentTouches","_documentTouchMove","changedTouches","InputHandler","useHandCursor","_setHandCursor","allowHorizontalDrag","allowVerticalDrag","snapOffset","snapOnDrag","snapOnRelease","snapX","snapY","snapOffsetX","snapOffsetY","pixelPerfectOver","pixelPerfectClick","pixelPerfectAlpha","draggable","boundsRect","boundsSprite","scaleLayer","dragOffset","dragFromCenter","dragStopBlocksInputUp","dragStartPoint","dragDistanceThreshold","dragTimeThreshold","downPoint","snapPoint","_dragPoint","_dragPhase","_pendingDrag","_dragTimePass","_dragDistancePass","_wasEnabled","_tempPoint","_pointerData","camX","camY","isOver","isOut","timeOver","timeOut","downDuration","onAddedToGroup","addedToGroup","onRemovedFromGroup","removedFromGroup","highestID","highestRenderID","includePixelPerfect","isPixelPerfect","pointerX","pointerY","pointerDown","pointerUp","pointerTimeDown","pointerTimeUp","pointerOver","pointerOut","pointerTimeOver","pointerTimeOut","pointerDragged","fastTest","checkPixel","_dx","_dy","startDrag","_draggedPointerID","updateDrag","sendEvent","onInputOver$dispatch","onInputOut$dispatch","onInputDown$dispatch","dragTimeElapsed","onInputUp$dispatch","stopDrag","fromStart","pointerLocalCoord","globalToLocal","checkBoundsRect","checkBoundsSprite","onDragUpdate","justOver","delay","overDuration","justOut","enableDrag","lockCenter","pixelPerfect","alphaThreshold","disableDrag","boundsCenterLocalCoord","onDragStart$dispatch","globalToLocalX","grid","boundsFluid","scaleFluidInversed","globalToLocalY","globalCoord","onDragStop$dispatch","setDragLock","allowHorizontal","allowVertical","enableSnap","onDrag","onRelease","disableSnap","_gamepadIndexMap","_rawPads","_active","_gamepadSupportAvailable","webkitGetGamepads","webkitGamepads","userAgent","getGamepads","_prevRawGamepadTypes","_prevTimestamps","onConnectCallback","onDisconnectCallback","onDownCallback","onUpCallback","onAxisCallback","onFloatCallback","_ongamepadconnected","_gamepaddisconnected","_gamepads","SinglePad","addCallbacks","callbacks","onConnect","onDisconnect","onAxis","_onGamepadConnected","onGamepadConnected","_onGamepadDisconnected","onGamepadDisconnected","newPad","connect","removedPad","disconnect","_pollGamepads","pad1","pollStatus","pad2","pad3","pad4","rawGamepads","gamepadsChanged","_rawPad","singlePad","validConnections","rawIndices","padIndices","connected","rawPad","setDeadZones","deadZone","BUTTON_0","BUTTON_1","BUTTON_2","BUTTON_3","BUTTON_4","BUTTON_5","BUTTON_6","BUTTON_7","BUTTON_8","BUTTON_9","BUTTON_10","BUTTON_11","BUTTON_12","BUTTON_13","BUTTON_14","BUTTON_15","AXIS_0","AXIS_1","AXIS_2","AXIS_3","AXIS_4","AXIS_5","AXIS_6","AXIS_7","AXIS_8","AXIS_9","XBOX360_A","XBOX360_B","XBOX360_X","XBOX360_Y","XBOX360_LEFT_BUMPER","XBOX360_RIGHT_BUMPER","XBOX360_LEFT_TRIGGER","XBOX360_RIGHT_TRIGGER","XBOX360_BACK","XBOX360_START","XBOX360_STICK_LEFT_BUTTON","XBOX360_STICK_RIGHT_BUTTON","XBOX360_DPAD_LEFT","XBOX360_DPAD_RIGHT","XBOX360_DPAD_UP","XBOX360_DPAD_DOWN","XBOX360_STICK_LEFT_X","XBOX360_STICK_LEFT_Y","XBOX360_STICK_RIGHT_X","XBOX360_STICK_RIGHT_Y","PS3XC_X","PS3XC_CIRCLE","PS3XC_SQUARE","PS3XC_TRIANGLE","PS3XC_L1","PS3XC_R1","PS3XC_L2","PS3XC_R2","PS3XC_SELECT","PS3XC_START","PS3XC_STICK_LEFT_BUTTON","PS3XC_STICK_RIGHT_BUTTON","PS3XC_DPAD_UP","PS3XC_DPAD_DOWN","PS3XC_DPAD_LEFT","PS3XC_DPAD_RIGHT","PS3XC_STICK_LEFT_X","PS3XC_STICK_LEFT_Y","PS3XC_STICK_RIGHT_X","PS3XC_STICK_RIGHT_Y","padParent","_padParent","_prevTimestamp","_buttons","_buttonsLen","_axes","_axesLen","getButton","timestamp","rawButtonVal","isNaN","processButtonDown","processButtonUp","processButtonFloat","processAxisChange","triggerCallback","disconnectingIndex","axisCode","buttonValue","Key","keycode","_enabled","durationUp","keyCode","onHoldCallback","onHoldContext","_justDown","_justUp","processKeyDown","processKeyUp","upDuration","pressEvent","onPressCallback","_keys","_capture","_onKeyDown","_onKeyPress","_onKeyUp","_k","onPress","removeCallbacks","addKey","addKeyCapture","addKeys","removeKey","removeKeyCapture","createCursorKeys","up","KeyCode","processKeyPress","clearCaptures","String","fromCharCode","charCode","A","charCodeAt","C","D","E","H","J","K","L","M","O","P","Q","R","S","T","U","V","W","X","Y","Z","ZERO","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","NUMPAD_0","NUMPAD_1","NUMPAD_2","NUMPAD_3","NUMPAD_4","NUMPAD_5","NUMPAD_6","NUMPAD_7","NUMPAD_8","NUMPAD_9","NUMPAD_MULTIPLY","NUMPAD_ADD","NUMPAD_ENTER","NUMPAD_SUBTRACT","NUMPAD_DECIMAL","NUMPAD_DIVIDE","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","F13","F14","F15","COLON","EQUALS","COMMA","UNDERSCORE","PERIOD","QUESTION_MARK","TILDE","OPEN_BRACKET","BACKWARD_SLASH","CLOSED_BRACKET","QUOTES","BACKSPACE","TAB","CLEAR","ENTER","SHIFT","CONTROL","ALT","CAPS_LOCK","ESC","SPACEBAR","PAGE_UP","PAGE_DOWN","END","HOME","PLUS","MINUS","INSERT","DELETE","HELP","NUM_LOCK","match","Component","Angle","wrapAngle","Animation","play","frameRate","loop","killOnComplete","animations","AutoCull","autoCull","inCamera","checkWorldBounds","Bounds","container","alignTo","BringToTop","Core","skipTypeChecks","install","components","Events","PhysicsBody","AnimationManager","LoadTexture","FixedToCamera","previousRotation","preUpdateChildren","fresh","_exists","P2JS","customRender","Crop","cropRect","_crop","updateCrop","resetFrame","oldX","oldY","oldW","oldH","_frame","Delta","Destroy","onDestroy$dispatch","removeFrom","Video","onChangeSource","resizeFrame","BitmapText","_glyphs","_parent","_onDestroy","_onAddedToGroup","_onRemovedFromGroup","_onKilled","_onRevived","_onEnterBounds","_onOutOfBounds","_onInputOver","_onInputOut","_onInputDown","_onInputUp","_onDragStart","_onDragUpdate","_onDragStop","_onAnimationStart","_onAnimationComplete","_onAnimationLoop","onKilled","onRevived","onOutOfBounds","onEnterBounds","onInputOver","onInputOut","onInputDown","onInputUp","onDragStart","onDragStop","onAnimationStart","onAnimationComplete","onAnimationLoop","backing","_fixedToCamera","Health","health","maxHealth","damage","setHealth","heal","InCamera","InputEnabled","InWorld","outOfCameraBoundsKill","_outOfBoundsFired","onEnterBounds$dispatch","onOutOfBounds$dispatch","outOfBoundsKill","inWorld","LifeSpan","lifespan","physicsElapsedMS","onRevived$dispatch","onKilled$dispatch","stopAnimation","BitmapData","hasFrameData","loadFrameData","getFrameData","frameData","Tilemap","TilemapLayer","img","getImage","trimmed","spriteSourceSizeX","spriteSourceSizeY","sourceSizeW","sourceSizeH","refreshTexture","frameName","Overlap","_reset","Reset","ScaleMinMax","scaleMin","scaleMax","checkTransform","setScaleMinMax","Smoothed","existing","weapon","bulletClass","Weapon","createBullets","Image","creature","mesh","tween","physicsGroup","SpriteBatch","audio","audioSprite","addSprite","tileSprite","rope","Rope","text","Text","overFrame","outFrame","downFrame","upFrame","Button","emitter","maxParticles","Arcade","Emitter","retroFont","font","characterWidth","characterHeight","chars","charsPerRow","xSpacing","ySpacing","xOffset","yOffset","RetroFont","bitmapText","tilemap","tileWidth","tileHeight","addToCache","uuid","addRenderTexture","video","bitmapData","addBitmapData","Tween","preUpdatePhysics","preUpdateLifeSpan","preUpdateInWorld","preUpdateCore","_onOverFrame","_onOutFrame","_onDownFrame","_onUpFrame","onOverSound","onOutSound","onDownSound","onUpSound","onOverSoundMarker","onOutSoundMarker","onDownSoundMarker","onUpSoundMarker","onOverMouseOnly","justReleasedPreventsOver","freezeFrames","forceOut","setFrames","onInputOverHandler","onInputOutHandler","onInputDownHandler","onInputUpHandler","clearFrames","setStateFrame","switchImmediately","frameKey","changeStateFrame","setStateSound","marker","soundKey","markerKey","Sound","AudioSprite","playStateSound","setSounds","overSound","overMarker","downSound","downMarker","outSound","outMarker","upSound","upMarker","setOverSound","setOutSound","setDownSound","setUpSound","fastSpriteBatch","ready","isRotated","childTransform","skipPool","ctx","imageData","FrameData","textureFrame","addFrame","Frame","disableTextureUpload","cls","_image","_pos","_size","_scale","_rotate","_alpha","prev","_anchor","_tempR","_tempG","_tempB","_circle","_swapCanvas","moveH","moveV","draw","onload","addImage","toDataURL","processPixelRGB","pixel","createColor","unpackPixel","getPixel32","setPixel32","processPixel","replaceRGB","g1","g2","region","packPixel","setHSL","bHaveH","bHaveS","bHaveL","HSLtoRGB","shiftHSL","red","green","blue","immediate","LITTLE_ENDIAN","setPixel","getPixel","getPixelRGB","hsl","hsv","getPixels","getFirstPixel","scan","newWidth","newHeight","getCanvas","op","copyTransform","copyRect","drawGroup","drawGroupProxy","drawFull","renderGraphics","shadow","blur","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","alphaMask","sourceRect","maskRect","blendSourceAtop","blendReset","extract","destination","prevFont","fillText","beginPath","arc","closePath","moveTo","lineTo","lineWidth","strokeStyle","stroke","polygon","textureLine","createPattern","blendSourceOver","blendSourceIn","blendSourceOut","blendDestinationOver","blendDestinationIn","blendDestinationOut","blendDestinationAtop","blendXor","blendAdd","blendMultiply","blendScreen","blendOverlay","blendDarken","blendLighten","blendColorDodge","blendColorBurn","blendHardLight","blendSoftLight","blendDifference","blendExclusion","blendHue","blendSaturation","blendColor","blendLuminosity","copyBitmapData","destRowStart","getSmoothingEnabled","setSmoothingEnabled","getTransform","translateX","translateY","skewX","skewY","EarCut","holeIndices","dim","hasHoles","outerLen","outerNode","linkedList","eliminateHoles","earcutLinked","clockwise","insertNode","filterPoints","again","steiner","removeNode","ear","pass","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","minTX","minTY","maxTX","maxTY","minZ","zOrder","maxZ","nextZ","prevZ","locallyInside","isValidDiagonal","splitPolygon","getLeftmost","compareX","eliminateHole","hole","findHoleBridge","hx","hy","qx","tan","tanMin","sortLinked","q","tail","numMerges","pSize","qSize","inSize","leftmost","intersectsPolygon","middleInside","Node","an","bp","stencilBufferLimit","lastIndex","clearDirty","graphicsDataPool","switchMode","buildPoly","buildComplexPoly","buildLine","buildRectangle","buildCircle","buildRoundedRectangle","upload","WebGLGraphicsData","rectData","fillColor","fillAlpha","vertPos","tempPoints","rrectData","recPoints","quadraticBezierCurve","vecPos","fromX","fromY","cpX","cpY","toX","toY","getPt","n1","n2","perc","xa","ya","xb","yb","circleData","seg","totalSegs","firstPoint","lastPoint","midPointX","midPointY","unshift","p1x","p1y","p2x","p2y","p3x","p3y","perpx","perpy","perp2x","perp2y","perp3x","perp3y","indexCount","indexStart","lineColor","lineAlpha","glPoints","glIndicies","updateGraphicsTint","_fillTint","_lineTint","strokeRect","ox","oy","xe","ye","xm","ym","bezierCurveTo","maxRadius","quadraticCurveTo","tintR","tintG","tintB","GraphicsData","currentPath","boundsPadding","_localBounds","_boundsDirty","webGLDirty","cachedSpriteDirty","updateLocalBounds","drawTriangle","cull","triangle","cameraToFace","faceNormal","drawPolygon","drawTriangles","point1","point2","point3","lineStyle","drawShape","cpX2","cpY2","dt2","dt3","arcTo","mm","dd","cc","tt","k1","k2","j1","j2","qy","anticlockwise","segments","sweep","segs","startX","startY","filling","theta","theta2","cTheta","sTheta","segMinus","remainder","drawRoundedRect","drawCircle","drawEllipse","canvasBuffer","updateCachedSpriteTexture","_prevTint","tempPoint","cachedSprite","destroyCachedSprite","textureBuffer","tempMatrix","renderXY","renderRawXY","updateBase","realResolution","getBase64","webGLPixels","Uint8Array","readPixels","tempCanvas","canvasData","textBounds","strokeColors","fontStyles","fontWeights","autoRound","useAdvancedWrap","splitRegExp","characterLimitSize","characterLimitSuffix","_res","_text","_fontComponents","_lineSpacing","_charCount","setStyle","updateText","setShadow","shadowStroke","shadowFill","newStyle","backgroundColor","boundsAlignH","boundsAlignV","strokeThickness","wordWrap","wordWrapWidth","maxLines","tabs","fontToComponents","fontStyle","fontVariant","fontWeight","fontSize","componentsToFont","outputText","substring","runWordWrap","lines","lineWidths","maxLineWidth","fontProperties","determineFontProperties","drawnLines","measureLine","measureText","tab","section","snapToCeil","lineHeight","lineSpacing","textBaseline","lineCap","lineJoin","linePositionX","linePositionY","ascent","updateLine","updateShadow","strokeText","renderTabLine","snap","lineLength","letter","clearColors","clearFontValues","addColor","addStrokeColor","addFontStyle","addFontWeight","weight","precalculateWordWrap","advancedWordWrap","basicWordWrap","linesCount","currentLineWidth","words","word","wordWithSpace","wordWidth","newWord","secondPart","spaceLeft","wordWidthWithSpace","updateFont","family","exec","fontFamily","setText","parseList","setTextBounds","properties","fontPropertiesCache","fontPropertiesCanvas","fontPropertiesContext","baseline","descent","imagedata","setCharacterLimit","characterLimit","suffix","parseFloat","createElement","textWidth","textHeight","_prevAnchor","_maxWidth","_data","getBitmapFont","_font","_fontSize","_align","_tint","sourceWidth","sourceHeight","scanLine","lastSpace","wrappedWidth","prevCharCode","maxWidth","test","charAt","charData","kerning","xAdvance","cleanText","re","purgeGlyphs","kept","checkImageKey","characterSpacingX","characterSpacingY","characterPerRow","multiLine","autoUpperCase","customSpacingX","customSpacingY","fixedWidth","fontSet","grabData","currentX","currentY","updateFrameData","stamp","ALIGN_LEFT","ALIGN_RIGHT","ALIGN_CENTER","TEXT_SET1","TEXT_SET2","TEXT_SET3","TEXT_SET4","TEXT_SET5","TEXT_SET6","TEXT_SET7","TEXT_SET8","TEXT_SET9","TEXT_SET10","TEXT_SET11","setFixedWidth","lineAlignment","content","characterSpacing","allowLowerCase","buildRetroFontText","getLongestLine","pasteLine","longestLine","removeUnsupportedCharacters","stripCR","newString","aChar","code","updateOffset","diffX","diffY","frames","getFrames","newText","toUpperCase","_hasUpdateAnimation","_updateAnimationCallback","canvasPadding","drawMode","updateAnimation","nextPoint","perpLength","_vertexBuffer","_initWebGL","_renderStrip","_indexBuffer","_uvBuffer","_colorBuffer","_renderCanvasTriangleStrip","_renderCanvasTriangles","_renderCanvasDrawTriangle","index0","textureSource","textureWidth","textureHeight","u0","v2","paddingX","paddingY","normX","normY","deltaA","deltaB","deltaC","deltaD","deltaE","deltaF","renderStripFlat","strip","rawX","rawY","_updateAnimation","difference","_scroll","textureDebug","tilePattern","frameWidth","frameHeight","physicsElapsed","autoScroll","stopScroll","generateTilingTexture","restartBatch","sessionBlendMode","forcePowerOfTwo","targetWidth","targetHeight","getNextPowerOfTwo","pool","getTotal","getFree","deviceReadyAt","initialized","desktop","iOSVersion","nodeWebkit","electron","ejecta","crosswalk","chromeOS","linux","macOS","windows","windowsPhone","canvasBitBltShift","file","fileSystem","localStorage","worker","css3D","typedArray","vibration","getUserMedia","quirksMode","arora","chromeVersion","epiphany","firefox","firefoxVersion","ieVersion","trident","tridentVersion","mobileSafari","midori","opera","safari","safariVersion","webApp","silk","audioData","ogg","opus","mp3","wav","m4a","webm","dolby","oggVideo","h264Video","mp4Video","webmVideo","vp9Video","hlsVideo","iPhone","iPhone4","iPad","pixelRatio","littleEndian","support32bit","fullscreen","requestFullscreen","cancelFullscreen","fullscreenKeyboard","onInitialized","nonPrimer","readyCheck","_readyCheck","_monitor","_queue","readyState","setTimeout","_initialize","_checkIsLittleEndian","_checkIsUint8ClampedImageData","Uint8ClampedArray","createImageData","vita","kindle","RegExp","$1","_checkOS","$3","process","versions","_checkBrowser","audioElement","canPlayType","major","minor","$2","_checkAudio","videoElement","_checkVideo","has3d","el","transforms","webkitTransform","OTransform","msTransform","MozTransform","insertBefore","getComputedStyle","getPropertyValue","_checkCSS3D","Int8Array","Int32Array","vibrate","webkitVibrate","mozVibrate","msVibrate","getItem","WebGLRenderingContext","compatMode","webkitGetUserMedia","mozGetUserMedia","msGetUserMedia","oGetUserMedia","URL","webkitURL","mozURL","msURL","_checkFeatures","s1","s2","_checkCanvasFeatures","fs","cfs","Element","_checkFullScreenSupport","documentElement","maxTouchPoints","PointerEvent","MSPointerEvent","msPointerEnabled","pointerEnabled","canPlayAudio","canPlayVideo","needsTouchUnlock","PhaserGlobal","fakeiOSTouchLock","isAndroidStockBrowser","matches","display","msTouchAction","overflowHidden","getElementById","overflow","appendChild","parentNode","vendor","prefix","types","msInterpolationMode","setImageRenderingBicubic","forceSetTimeOut","vendors","requestAnimationFrame","cancelAnimationFrame","_isSetTimeOut","_onLoop","_timeOutID","updateSetTimeout","updateRAF","rafTime","timeToCall","clearTimeout","isSetTimeOut","isRAF","DEG_TO_RAD","RAD_TO_DEG","degrees","radians","fuzzyLessThan","fuzzyGreaterThan","fuzzyCeil","fuzzyFloor","average","shear","snapTo","gap","snapToFloor","roundTo","place","floorTo","ceilTo","rotateToAngle","currentAngle","targetAngle","getShortestAngle","angleBetween","angleBetweenY","angleBetweenPoints","angleBetweenPointsY","reverseAngle","angleRad","normalizeAngle","maxAdd","minSub","wrapValue","isOdd","isEven","minProperty","maxProperty","linearInterpolation","bezierInterpolation","bernstein","catmullRomInterpolation","catmullRom","factorial","res","roundAwayFromZero","sinCosGenerator","sinAmplitude","cosAmplitude","frequency","frq","cosTable","sinTable","hypot","distanceSq","distancePow","clampBottom","within","mapLinear","smoothstep","smootherstep","sign","percent","seeds","s0","sow","integer","real","integerInRange","realInRange","ary","weightedPick","QuadTree","maxObjects","maxLevels","_empty","subWidth","subHeight","populate","populateHandler","insert","retrieve","returnObjects","getHostName","location","hostname","checkDomainName","domain","updateQueryString","redirect","href","separator","getQueryString","parameter","keyValues","search","decodeURI","decodeURIComponent","frameBased","_tweens","_add","easeMap","Power0","Easing","Power1","Power2","Power3","Power4","Linear","None","Quad","Quadratic","Out","Cubic","Quart","Quartic","Quint","Quintic","Sine","Sinusoidal","Expo","Exponential","Circ","Circular","Elastic","Back","Bounce","Quad.easeIn","In","Cubic.easeIn","Quart.easeIn","Quint.easeIn","Sine.easeIn","Expo.easeIn","Circ.easeIn","Elastic.easeIn","Back.easeIn","Bounce.easeIn","Quad.easeOut","Cubic.easeOut","Quart.easeOut","Quint.easeOut","Sine.easeOut","Expo.easeOut","Circ.easeOut","Elastic.easeOut","Back.easeOut","Bounce.easeOut","Quad.easeInOut","InOut","Cubic.easeInOut","Quart.easeInOut","Quint.easeInOut","Sine.easeInOut","Expo.easeInOut","Circ.easeInOut","Elastic.easeInOut","Back.easeInOut","Bounce.easeInOut","_pauseAll","_resumeAll","pendingDelete","_manager","addTweens","numTweens","isTweening","checkIsRunning","some","_pause","_resume","pauseAll","resumeAll","manager","timeline","timeScale","repeatCounter","onStart","onLoop","onRepeat","onChildComplete","onComplete","chainedTween","isPaused","_onUpdateCallback","_onUpdateCallbackContext","_pausedTime","_hasStarted","ease","yoyo","Default","TweenData","vEnd","loadValues","updateTweenData","repeatDelay","yoyoDelay","easing","interpolation","repeatAll","chain","startTime","status","PENDING","RUNNING","LOOPED","COMPLETE","generateData","vStart","vStartCache","vEndCache","repeatTotal","inReverse","easingFunction","interpolationFunction","interpolationContext","isFrom","ms","fps","blob","reversed","asin","prevTime","_desiredFps","suggestedFps","advancedTiming","updates","renders","ups","rps","fpsMin","fpsMax","msMin","msMax","pauseDuration","timeExpected","Timer","_frameCount","_elapsedAccumulator","_started","_timeLastSecond","_pauseStarted","_justResumed","_timers","timer","autoDestroy","previousDateNow","updateAdvancedTiming","updateTimers","interval","elapsedSince","since","elapsedSecondsSince","running","expired","nextTick","timeCap","_pauseTotal","_now","_marked","_diff","_newTick","MINUTE","SECOND","HALF","QUARTER","repeatCount","TimerEvent","clearEvents","clearPendingEvents","adjustEvents","baseTime","currentFrame","currentAnim","updateIfVisible","isLoaded","_frameData","_anims","_outputFrames","anim","copyFrameData","useNumericIndex","getFrameIndexes","validateFrames","checkFrameName","isPlaying","getAnimation","refreshFrame","gotFrame","getFrame","getFrameByName","_frameIndex","_frames","loopCount","isFinished","_pauseStartTime","_frameDiff","_frameSkip","onUpdate","isReversed","_timeLastFrame","_timeNextFrame","updateCurrentFrame","onAnimationStart$dispatch","reverseOnce","frameId","useLocalFrameIndex","frameIndex","directionalOffset","dispatchComplete","onAnimationComplete$dispatch","onAnimationLoop$dispatch","signalUpdate","fromPlay","generateFrameNames","zeroPad","spriteSourceSizeW","spriteSourceSizeH","setTrim","actualWidth","actualHeight","destX","destY","destWidth","destHeight","getRect","_frameNames","getFrameRange","AnimationParser","spriteSheet","frameMax","margin","spacing","skipFrames","JSONData","json","newFrame","filename","sourceSize","spriteSourceSize","JSONDataPyxel","tileheight","tilewidth","JSONDataHash","XMLData","xml","getElementsByTagName","frameX","frameY","autoResolveURL","binary","bitmapFont","compressedTexture","_urlMap","_urlResolver","_urlTemp","onSoundUnlock","_cacheMap","TEXTURE","SOUND","PHYSICS","BINARY","BITMAPFONT","JSON","XML","SHADER","RENDER_TEXTURE","_pendingCount","_addImages","DEFAULT_KEY","DEFAULT_SRC","MISSING","MISSING_KEY","MISSING_SRC","READY_TIMEOUT","addCompressedTextureMetaData","extension","arrayBuffer","removeImage","LoaderParser","fileFormat","_resolveURL","addCanvas","addImageAsync","_removePending","_addPending","addDefaultImage","addMissingImage","addSound","audioTag","decoded","isDecoding","touchLocked","addText","addPhysicsData","addTilemap","mapData","addBinary","binaryData","addBitmapFont","atlasData","atlasType","jsonBitmapFont","xmlBitmapFont","addBitmapFontFromAtlas","atlasKey","atlasFrame","dataKey","dataType","getBaseTexture","fontData","getJSON","getXML","addJSON","addXML","addVideo","isBlob","addShader","addSpriteSheet","addTextureAtlas","TEXTURE_ATLAS_XML_STARLING","TEXTURE_ATLAS_JSON_PYXEL","reloadSound","getSound","reloadSoundComplete","updateSound","decodedSound","isSoundDecoded","isSoundReady","checkKey","checkURL","checkCanvasKey","checkTextureKey","checkSoundKey","checkTextKey","checkPhysicsKey","checkTilemapKey","checkBinaryKey","checkBitmapDataKey","checkBitmapFontKey","checkJSONKey","checkXMLKey","checkVideoKey","checkShaderKey","checkRenderTextureKey","full","getTextureFrame","getSoundData","getText","getPhysicsData","fixtureKey","fixtures","fixture","getTilemapData","getBinary","getBitmapData","getVideo","getShader","getRenderTexture","getFrameCount","getFrameByIndex","getURL","getKeys","removeCanvas","destroyBaseTexture","removeSound","removeText","removePhysics","removeTilemap","removeBinary","removeBitmapData","removeBitmapFont","removeJSON","removeXML","removeVideo","removeShader","removeRenderTexture","removeSpriteSheet","removeTextureAtlas","baseURL","destroyItem","readyTimeout","_ready","_checkReady","isLoading","preloadSprite","crossOrigin","headers","requestedWith","onLoadStart","onLoadComplete","onPackComplete","onFileStart","onFileComplete","onFileError","enableParallel","maxParallelDownloads","_withSyncPointDepth","_fileList","_flightQueue","_processingHead","_fileLoadStarted","_totalPackCount","_totalFileCount","_loadedPackCount","_loadedFileCount","TEXTURE_ATLAS_JSON_ARRAY","TEXTURE_ATLAS_JSON_HASH","PHYSICS_LIME_CORONA_JSON","PHYSICS_PHASER_JSON","setPreloadSprite","checkKeyExists","getAssetIndex","bestFound","loaded","loading","getAsset","fileIndex","addToFileList","overwrite","syncPoint","currentFile","replaceInFileList","pack","imageFromBitmapData","imageFromGrid","imageFromTexture","pixelWidth","pixelHeight","palette","exkey","images","urls","script","spritesheet","autoDecode","noAudio","jsonURL","jsonData","audiosprite","loadEvent","asBlob","CSV","TILED_JSON","LIME_CORONA_JSON","textureURL","atlasURL","parseXml","atlasJSONArray","atlas","atlasJSONHash","atlasXML","withSyncPoint","addSyncPoint","asset","removeFile","updateProgress","processLoadQueue","finishedLoading","requestUrl","requestObject","progress","syncblock","inflightLimit","processPack","loadFile","abnormal","asyncComplete","errorMessage","packData","transformUrl","xhrLoad","fileComplete","loadImageTag","getAudioURL","usingWebAudio","usingAudioTag","loadAudioTag","fileError","getVideoURL","loadVideoTag","jsonLoadComplete","xmlLoadComplete","csvLoadComplete","onerror","controls","autoplay","videoLoadEvent","canplay","Audio","playThroughEvent","xhr","XMLHttpRequest","open","responseType","setRequestHeader","message","send","videoType","uri","lastIndexOf","audioType","reason","loadNext","responseText","response","decode","language","defer","head","contentType","domparser","DOMParser","parseFromString","ActiveXObject","async","loadXML","totalLoadedFiles","totalLoadedPacks","progressFloat","info","common","getAttribute","letters","kernings","second","finalizeBitmapFont","_face","_lineHeight","_id","_xoffset","_yoffset","_xadvance","_second","_first","_amount","bitmapFontData","pvr","uintArray","byteArray","pvrHeader","pixelFormat","flags","colorSpace","channelType","depth","numberOfSurfaces","numberOfFaces","numberOfMipmaps","metaDataSize","byteLength","dds","ddsHeader","pitch","mipmapCount","formatSize","formatFlag","formatFourCC","formatBitCount","formatRBitMask","formatGBitMask","formatBBitMask","formatABitMask","caps1","caps2","caps3","caps4","reserved2","DXGIFormat","resourceDimension","miscFlag","arraySize","ktx","ktxHeader","imageSizeOffset","imageSize","glInternalFormat","endianness","glType","glTypeSize","glFormat","glBaseInternalFormat","pixelDepth","numberOfArrayElements","numberOfMipmapLevels","bytesOfKeyValueData","keyAndValueByteSize","pkm","pkmHeader","originalWidth","originalHeight","autoplayKey","sounds","spritemap","addMarker","connectToMaster","markers","totalDuration","currentTime","durationMS","stopTime","pausedPosition","pausedTime","currentMarker","fadeTween","pendingPlayback","override","allowMultiple","externalNode","masterGainNode","gainNode","_sound","_globalVolume","_markedToDelete","_removeFromSoundManager","masterGain","createGain","createGainNode","gain","soundHasUnlocked","onDecoded","onPlay","onStop","onMute","onMarkerComplete","_volume","_buffer","_muted","_tempMarker","_tempPosition","_tempVolume","_tempPause","_muteVolume","_tempLoop","_onDecodedEventDispatched","removeMarker","onEndedHandler","onended","isDecoded","loopFull","forceRestart","noteOff","createBufferSource","noteGrainOn","muted","mute","prevMarker","fadeIn","fadeTo","fadeOut","fadeComplete","updateGlobalVolume","globalVolume","onSoundDecode","onVolumeChange","onUnMute","onTouchUnlock","channels","_codeMuted","_unlockSource","_sounds","_watchList","_watching","_watchCallback","_watchContext","disableAudio","disableWebAudio","audioContext","setTouchLock","unlock","setTouchUnlock","noteOn","stopAll","soundData","decodeAudioData","setDecodedCallback","files","playbackState","PLAYING_STATE","FINISHED_STATE","removeByKey","close","dom","minWidth","minHeight","maxHeight","forceLandscape","forcePortrait","incorrectOrientation","_pageAlignHorizontally","_pageAlignVertically","onOrientationChange","enterIncorrectOrientation","leaveIncorrectOrientation","hasPhaserSetFullScreen","fullScreenTarget","_createdFullScreenTarget","onFullScreenInit","onFullScreenChange","onFullScreenError","screenOrientation","getScreenOrientation","scaleFactorInversed","aspectRatio","sourceAspectRatio","windowConstraints","compatibility","supportsFullScreen","orientationFallback","noMargins","scrollTo","forceMinimumDocumentHeight","canExpandParent","clickTrampoline","_scaleMode","NO_SCALE","_fullScreenScaleMode","parentIsWindow","parentScaleFactor","trackParentInterval","onSizeChange","onResize","onResizeContext","_pendingScaleMode","_fullScreenRestore","_gameSize","_userScaleFactor","_userScaleTrim","_lastUpdate","_updateThrottle","_updateThrottleReset","_parentBounds","_tempBounds","_lastReportedCanvasSize","_lastReportedGameSize","_booted","setupScale","EXACT_FIT","SHOW_ALL","RESIZE","USER_SCALE","MODES","compat","_orientationChange","orientationChange","_windowResize","windowResize","_fullScreenChange","fullScreenChange","_fullScreenError","fullScreenError","_gameResumed","setGameSize","FlexGrid","fullScreenScaleMode","pageAlignHorizontally","alignH","pageAlignVertically","alignV","scaleH","scaleV","setUserScale","trimH","trimV","getParentBounds","visualBounds","updateDimensions","queueUpdate","currentScaleMode","hScale","vScale","hTrim","vTrim","setResizeCallback","signalSizeChange","setMinMax","prevThrottle","prevWidth","prevHeight","boundsChanged","orientationChanged","updateOrientationState","updateLayout","throttle","updateScalingAndBounds","forceOrientation","classifyOrientation","orientation","previousOrientation","previouslyIncorrect","isLandscape","isPortrait","changed","correctnessChanged","scrollTop","setMaximum","setExactFit","isFullScreen","boundingParent","setShowAll","resetCanvas","reflowCanvas","reflowGame","layoutBounds","clientRect","getBoundingClientRect","parentRect","offsetParent","wc","windowBounds","alignCanvas","parentBounds","canvasBounds","currentEdge","targetEdge","marginLeft","marginRight","marginTop","marginBottom","cssWidth","cssHeight","expanding","createFullScreenTarget","fsTarget","background","startFullScreen","allowTrampoline","cleanupCreatedTarget","initData","targetElement","ALLOW_KEYBOARD_INPUT","stopFullScreen","prepScreenMode","enteringFullscreen","createdTarget","scaleSprite","letterBox","scaleX1","scaleY1","scaleX2","scaleY2","scaleOnWidth","bmd","columnWidth","renderShadow","currentColor","currentAlpha","_line","_rect","soundInfo","filled","rectangle","geom","cameraInfo","hideIfUp","downColor","upColor","worldX","worldY","spriteInputInfo","justDown","justUp","inputInfo","spriteBounds","ropeSegments","segment","spriteInfo","spriteCoords","lineInfo","forceType","ellipse","quadTree","quadtree","NINJA","Ninja","BOX2D","Box2D","renderBody","bodyInfo","renderBodyInfo","box2d","box2dWorld","renderDebugDraw","box2dBody","displayList","canvasPool","phaser","factor","loader","box","scrollY","scrollLeft","scrollX","clientTop","clientLeft","cushion","calibrate","coords","getAspectRatio","inLayoutViewport","primaryFallback","screen","mozOrientation","msOrientation","matchMedia","documentBounds","pageXOffset","pageYOffset","clientWidth","clientHeight","offsetWidth","scrollWidth","offsetHeight","scrollHeight","randomIndex","removeRandomItem","newLength","transposeMatrix","sourceRowCount","sourceColCount","rotateMatrix","findClosest","arr","NaN","low","high","rotateRight","rotateLeft","numberArray","numberArrayStep","LinkedList","entity","palettes","0","PALETTE_ARNE","PALETTE_JMP","PALETTE_CGA","PALETTE_C64","PALETTE_JAPANESE_MACHINE","row","boundsCustom","boundsFull","boundsNone","positionCustom","positionFluid","positionFull","positionNone","scaleCustom","scaleFluid","scaleFull","scaleNone","customWidth","customHeight","customOffsetX","customOffsetY","ratioH","ratioV","layers","createCustomLayer","layer","FlexLayer","createFluidLayer","createFullLayer","createFixedLayer","persist","fitSprite","topLeft","topMiddle","topRight","bottomLeft","bottomMiddle","bottomRight","RED","ORANGE","YELLOW","GREEN","AQUA","BLUE","VIOLET","WHITE","BLACK","GRAY","RGBtoHSL","RGBtoHSV","fromRGBA","toRGBA","toABGR","RGBArrayToHex","rgb","hueToColor","HSVtoRGB","color32","getColor","getColor32","RGBtoString","componentToHex","hexToRGB","hex","hexToColor","webToColor","web","tempColor","getRGB","HSVColorWheel","HSLColorWheel","interpolateColor","color1","color2","currentStep","src1","src2","hsv1","hsv2","dh","h3","interpolateColorWithRGB","or","og","ob","interpolateRGB","getRandomColor","getWebRGB","getAlpha","getAlphaFloat","getRed","getGreen","getBlue","blendNormal","blendAverage","blendSubtract","blendNegation","blendLinearDodge","blendLinearBurn","blendLinearLight","blendVividLight","blendPinLight","blendHardMix","blendReflect","blendGlow","blendPhoenix","arcade","ninja","chipmunk","matter","CHIPMUNK","MATTERJS","P2","Matter","startSystem","system","enableAABB","checkCollision","OVERLAP_BIAS","forceX","sortDirection","LEFT_RIGHT","skipQuadTree","_total","SORT_NONE","RIGHT_LEFT","TOP_BOTTOM","BOTTOM_TOP","updateMotion","allowRotation","velocityDelta","computeVelocity","angularAcceleration","angularDrag","maxAngular","acceleration","drag","maxVelocity","allowGravity","allowDrag","object1","object2","overlapCallback","processCallback","collideObjects","collide","collideCallback","sortLeftRight","sortRightLeft","sortTopBottom","sortBottomTop","overlapOnly","collideHandler","collideGroupVsSelf","collideSpriteVsSprite","collideSpriteVsGroup","collideSpriteVsTilemapLayer","collideGroupVsGroup","collideGroupVsTilemapLayer","sprite1","sprite2","separate","items","bounds1","bounds2","group1","group2","body1","body2","none","isCircle","separateCircle","bodyRect","bodyCircle","resultX","resultY","separateX","separateY","onOverlap","onCollide","circleBodyIntersects","getOverlapX","getOverlapY","angleCollision","immovable","customSeparateX","tempVel1","tempVel2","bounce","maxOverlap","deltaAbsX","embedded","touching","overlapX","deltaAbsY","overlapY","moves","nv1","nv2","avg","customSeparateY","getObjectsUnderPointer","getObjectsAtLocation","callbackArg","moveToObject","maxTime","distanceBetween","moveToPointer","angleToPointer","distanceToPointer","moveToXY","distanceToXY","velocityFromAngle","velocityFromRotation","accelerationFromRotation","accelerateToObject","xSpeedMax","ySpeedMax","accelerateToPointer","accelerateToXY","angleToXY","closest","targets","farthest","angleBetweenCenters","worldAngleToPointer","preRotation","newVelocity","deltaMax","worldBounce","onWorldBounds","facing","overlapR","collideWorldBounds","wasTouching","blocked","tilePadding","syncBounds","isMoving","stopVelocityOnCollide","moveTimer","moveDistance","moveDuration","moveTarget","moveEnd","onMoveComplete","movementCallback","movementCallbackContext","_sx","_sy","updateBounds","asx","asy","updateCenter","updateMovement","collided","stopMovement","stopVelocity","check","moveFrom","setCircle","onFloor","onCeiling","onWall","TilemapCollision","TILE_BIAS","tilemapLayer","getTiles","getTileOffsetX","getTileOffsetY","separateTile","tile","tilemapLayerOffsetX","tilemapLayerOffsetY","collisionCallback","collisionCallbackContext","faceLeft","faceRight","faceTop","faceBottom","tileCheckX","tileCheckY","collideRight","collideLeft","processTileSeparationX","collideDown","collideUp","processTileSeparationY","useElapsedTime","materials","InversePointProxy","walls","onBodyAdded","onBodyRemoved","onSpringAdded","onSpringRemoved","onConstraintAdded","onConstraintRemoved","onContactMaterialAdded","onContactMaterialRemoved","postBroadphaseCallback","onBeginContact","onEndContact","mpx","mpxi","pxm","pxmi","beginContactHandler","endContactHandler","collisionGroups","nothingCollisionGroup","CollisionGroup","boundsCollisionGroup","everythingCollisionGroup","boundsCollidesWith","_toRemove","_collisionGroupID","_boundsLeft","_boundsRight","_boundsTop","_boundsBottom","_boundsOwnGroup","removeBodyNextStep","setImpactEvents","impactHandler","setPostBroadphaseCallback","postBroadphaseHandler","_bodyCallbacks","_bodyCallbackContext","_groupCallbacks","_groupCallbackContext","setCollisionGroup","setWorldMaterial","updateBoundsCollisionGroup","setupWall","wall","fixedStepTime","impactCallback","createDistanceConstraint","getBody","createGearConstraint","createRevoluteConstraint","createLockConstraint","createPrismaticConstraint","lockRotation","anchorA","anchorB","setMaterial","createMaterial","createContactMaterial","getSprings","getConstraints","filterStatic","physicsPosition","query","toJSON","createCollisionGroup","bitmask","createSpring","worldA","worldB","localA","localB","createRotationalSpring","createBody","addPolygon","createParticle","convertCollisionObjects","map","collision","shapeData","polyline","addRectangle","clearTilemapLayerBodies","getLayer","convertTilemap","optimize","collides","getTileRight","FixtureList","rawList","namedFixtures","groupedFixtures","allFixtures","setCategory","bit","getFixtures","setMask","setSensor","getFixtureByKey","getGroup","groupID","_ref","_results","callee","PointProxy","collidesWith","removeNextStep","debugBody","_collideWorldBounds","setRectangleFromSprite","createBodyCallback","createGroupCallback","getCollisionMask","updateCollisionMask","clearCollision","clearGroup","clearMask","removeCollisionGroup","clearCallback","shapeChanged","impulse","localX","localY","setZeroRotation","setZeroVelocity","setZeroDamping","moveForward","moveBackward","thrust","thrustLeft","thrustRight","moveLeft","moveRight","updateSpriteTransform","resetDamping","resetMass","clearShapes","addCircle","addPlane","addParticle","addLine","addCapsule","setRectangle","addPhaserPolygon","createdFixtures","fixtureData","shapesOfFixture","addFixture","generatedShapes","categoryBits","maskBits","isSensor","polygons","loadPolygon","BodyDebug","settings","defaultSettings","pixelsPerLengthUnit","debugPolygons","ppu","lw","vrot","_j","_ref1","randomPastelHex","drawCapsule","drawPlane","drawLine","drawRectangle","drawConvex","drawPath","lastx","lasty","diagMargin","diagSize","maxLength","xd","yd","mix","rgbToHex","ImageCollection","firstgid","imageWidth","imageHeight","imageMargin","imageSpacing","containsImageIndex","imageIndex","gid","Tile","flipped","scanned","setCollisionCallback","setCollision","resetCollision","isInteresting","faces","TilemapParser","widthInPixels","heightInPixels","tilesets","imagecollections","tiles","collideIndexes","currentLayer","debugMap","_tempA","NORTH","EAST","SOUTH","WEST","setTileSize","createBlankLayer","addTilesetImage","tileset","tileMargin","tileSpacing","getTilesetIndex","setImage","newSet","Tileset","countX","countY","columns","rows","createFromObjects","CustomClass","adjustY","adjustSize","createFromTiles","replacements","customClass","lh","createLayer","getLayerIndex","rootLayer","groupEnd","indexes","getImageIndex","setTileIndexCallback","setTileLocationCallback","recalculate","setCollisionByIndex","calculateFaces","setCollisionBetween","setCollisionByExclusion","layerArg","setPreventRecalculate","preventingRecalculate","needToRecalculate","above","below","getTileAbove","getTileBelow","getTileLeft","setLayer","hasTile","removeTile","removeTileWorldXY","putTile","putTileWorldXY","searchTileIndex","getTile","nonNull","getTileWorldXY","paste","tileblock","tileA","tileB","swapHandler","removeAllLayers","dump","txt","renderSettings","enableScrollDelta","overdrawRatio","copyCanvas","debugSettings","missingImageFill","debuggedTileOverfill","forceFullRedraw","debugAlpha","facingEdgeStroke","collidingTileOverfill","scrollFactorX","scrollFactorY","rayStepRate","_wrap","_mc","renderWidth","renderHeight","_scrollX","_scrollY","tileOffset","ensureSharedCopyCanvas","sharedCopyCanvas","resizeWorld","_fixX","_unfixX","_fixY","_unfixY","getTileX","getTileY","getTileXY","getRayCastTiles","interestingFace","coord","fetchAll","wy","wx","resolveTileset","tileIndex","setIndex","containsTileIndex","resetTilesetCache","setScale","xScale","yScale","shiftCanvas","copyW","copyH","copyContext","renderRegion","lastAlpha","xmax","ymax","baseX","normStartX","renderDeltaScroll","shiftX","shiftY","renderW","renderH","trueTop","trueBottom","trueLeft","trueRight","renderFull","redrawAll","mc","renderDebug","baseY","normStartY","INSERT_NULL","getEmptyData","parseCSV","parseTiledJSON","column","_slice","fields","sliced","parseObjectGroup","objectGroup","objectsCollection","collisionCollection","nameKey","relativePosition","curl","encoding","binaryString","atob","bytes","opacity","offsetx","offsety","flippedVal","curi","tilesetGroupObjects","lastSet","tileproperties","tileProperties","updateTileData","imagewidth","imageheight","newCollection","objectgroup","lastgid","sid","drawCoords","coordIndex","setSpacing","rowCount","colCount","autoScale","scaleData","_s","autoAlpha","alphaData","_a","onEmit","setAlphaData","setScaleData","emitters","ID","minAngle","maxAngle","minSpeed","maxSpeed","minParticleSpeed","maxParticleSpeed","minParticleScale","maxParticleScale","minRotation","maxRotation","minParticleAlpha","maxParticleAlpha","particleClass","particleDrag","particleAnchor","emitX","emitY","particleBringToTop","particleSendToBack","counts","emitted","failed","totalEmitted","totalFailed","_gravity","_minParticleScale","_maxParticleScale","_timer","_counter","_flowQuantity","_flowTotal","_explode","emitParticle","makeParticles","particleArguments","particle","rndKey","rndFrame","explode","flow","forceQuantity","getNextParticle","resetParticle","setXSpeed","setYSpeed","setRotation","setAlpha","rate","tweenData","setAngle","lifespanOutput","bullets","autoExpandBulletsGroup","autofire","shots","fireLimit","fireRate","fireRateVariance","fireFrom","fireAngle","bulletInheritSpriteSpeed","bulletAnimation","bulletFrameRandom","bulletFrameCycle","bulletWorldWrap","bulletWorldWrapPadding","bulletAngleOffset","bulletAngleVariance","bulletSpeed","bulletSpeedVariance","bulletLifespan","bulletKillDistance","bulletGravity","bulletRotateToVelocity","bulletKey","bulletFrame","_bulletClass","Bullet","_bulletCollideWorldBounds","_bulletKillType","KILL_WORLD_BOUNDS","customBody","bulletBounds","bulletFrames","bulletFrameIndex","anims","onFire","onKill","onFireLimit","trackedSprite","trackedPointer","multiFire","_hasFired","trackRotation","trackOffset","_nextFire","_tempNextFire","_rotatedPoint","KILL_NEVER","KILL_LIFESPAN","KILL_DISTANCE","KILL_WEAPON_BOUNDS","KILL_CAMERA_BOUNDS","KILL_STATIC_BOUNDS","resetShots","newLimit","fire","trackSprite","trackPointer","fireMany","fireOffset","moveX","moveY","bullet","bulletManager","killType","bulletKillType","killDistance","rotateToVelocity","bodyDirty","bulletCollideWorldBounds","fireAtPointer","fireAtSprite","fireAtXY","setBulletBodyOffset","setBulletFrames","cycle","addBulletAnimation","debugBodies","onAccess","onError","onTimeout","playWhenUnlocked","timeout","videoStream","isStreaming","retryLimit","retry","retryInterval","_retryID","_pending","_pendingChangeSource","_autoplay","_endCallback","_playCallback","_video","createVideoFromBlob","videoWidth","videoHeight","createVideoFromURL","snapshot","connectToMediaStream","stream","startMediaStream","captureAudio","removeVideoElement","setAttribute","getUserMediaTimeout","getUserMediaSuccess","getUserMediaError","mozSrcObject","createObjectURL","onloadeddata","checkStream","checkVideoProgress","change","playbackRate","setPause","setResume","playHandler","getTracks","track","playing","ended","changeSource","grab","hasChildNodes","firstChild","removeAttribute","canUseNewCanvasBlendModes"],"mappings":";;CAoDC,SAASA,GAAG,GAAG,iBAAiBC,QAAQC,OAAOD,QAAQD,QAAS,CAAmD,IAAIG,EAAE,oBAAoBC,OAAOD,EAAEC,OAAO,oBAAoBC,OAAOF,EAAEE,OAAO,oBAAoBC,OAAOH,EAAEG,MAAMH,EAAEI,GAAGP,KAAzO,CAA+O,WAAqC,OAAO,SAAUA,EAAEQ,EAAEC,EAAEC,GAAG,SAASC,EAAEC,EAAEC,GAAG,IAAIJ,EAAEG,GAAG,CAAC,IAAIJ,EAAEI,GAAG,CAAC,IAAIE,EAAkB,mBAATC,SAAqBA,QAAQ,IAAIF,GAAGC,EAAE,OAAOA,EAAEF,GAAE,GAAI,GAAGI,EAAE,OAAOA,EAAEJ,GAAE,GAAI,MAAM,IAAIK,MAAM,uBAAuBL,EAAE,KAAK,IAAIT,EAAEM,EAAEG,IAAIX,YAAYO,EAAEI,GAAG,GAAGM,KAAKf,EAAEF,QAAQ,SAASD,GAAG,IAAIS,EAAED,EAAEI,GAAG,GAAGZ,GAAG,OAAOW,EAAEF,GAAIT,IAAIG,EAAEA,EAAEF,QAAQD,EAAEQ,EAAEC,EAAEC,GAAG,OAAOD,E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H,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAItW,GACxB99C,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAGpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIpW,GACxBh+C,EAASitB,KAAWmnC,EAAInW,GAExBj+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAKpBn6C,EAASitB,KAAW0wB,EACpB39C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIlW,GACxBl+C,EAASitB,KAAWmnC,EAAIjW,GAExBn+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,IAGpBp6C,KAAKyzD,kBAEuBzzD,KAAKmM,MAE7BnM,KAAKy+C,UAObjK,EAAKkiB,qBAAqBt2D,UAAUq+C,MAAQ,WAGxC,GAA4B,IAAxBz+C,KAAKyzD,iBAAT,CAEA,IAAI5f,EAAK7zC,KAAK6zC,GAId,GAAI7zC,KAAK0zD,mBAAmB5N,YAAYjS,EAAGhjC,IAA3C,CASA,GAAG7Q,KAAKyzD,iBAAiC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EAAOzC,iBAGKn1B,IAA9Bk1B,KAAK2K,QAAQC,eAEb5K,KAAK2K,QAAQC,aAAe,IAAI5K,KAAK2K,QAAQ,IAAI3K,KAAKwmB,mBAGnB17C,IAAnCk1B,KAAKgC,cAAc6C,cAEnB7E,KAAKgC,cAAc6C,YAAc,IAAInC,EAAOC,QAGhD3C,KAAKinB,mBAAoB,EAGzBjnB,KAAKwxJ,0BAA4B,WAC7B,OAAO9uJ,EAAOgvC,OAAOnrB,gBASE,oBAAZn/D,SACe,oBAAXC,QAA0BA,OAAOD,UACxCA,QAAUC,OAAOD,QAAUs7C,GAE/Bt7C,QAAQs7C,OAASA,GACQ,oBAAXglB,QAA0BA,OAAOC,IAC/CD,OAAO,SAA+B3vB,EAAK2K,OAASA,GAEpD3K,EAAK2K,OAASA,EAGXA,GACRr6C,KAAKmD","file":"phaser.min.js"} \ No newline at end of file diff --git a/Digital Assignment 3/js/phaser.min.js b/Digital Assignment 3/js/phaser.min.js new file mode 100644 index 000000000..6eb048b7a --- /dev/null +++ b/Digital Assignment 3/js/phaser.min.js @@ -0,0 +1,4 @@ +/* Phaser v2.10.0 - http://phaser.io - @photonstorm - (c) 2016 Photon Storm Ltd. */ + +!function(t){if("object"==typeof exports)module.exports=t();else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.p2=t()}}(function(){return function t(e,i,s){function n(o,a){if(!i[o]){if(!e[o]){var h="function"==typeof require&&require;if(!a&&h)return h(o,!0);if(r)return r(o,!0);throw new Error("Cannot find module '"+o+"'")}var l=i[o]={exports:{}};e[o][0].call(l.exports,function(t){var i=e[o][1][t];return n(i||t)},l,l.exports,t,e,i,s)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;se[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;ia)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var T=0;Tm&&(m+=this.vertices.length),g=Number.MAX_VALUE,m3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e) (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.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.1"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;ca[f]&&(a[f]=u[f]),u[f]i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle");var n=t("../collision/Broadphase");t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;az&&Y0)for(G=0;GMath.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=x,f=b,g=_,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var w=r.vertices[y];if(o.rotate(p,w,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var T=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(T.normalA,f);var P=l(g,T.normalA);o.scale(g,T.normalA,P),a(T.contactPointB,p,n.position),a(T.contactPointA,p,g),a(T.contactPointA,T.contactPointA,t.position),this.contactEquations.push(T),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(T))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=x,p=b;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=x;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,w=u;w=w||0;var T=x,P=b,C=_;a(T,g,y),o.rotate(P,v,w);var S=l(P,T);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,P),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,T,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=x,m=b,y=_,v=w,P=T,E=C,M=S,R=A,L=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(M,u,i),l(g,M)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),I=s.getClosestEdge(c,d,g);if(-1===B||-1===I)return 0;for(var O=0;O<2;O++){var k=B,F=I,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===O){var q;q=k,k=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H=3){if(p)return!0;var Z=this.createContactEquation(j,V,D,U);L++;var J=D.vertices[k%D.vertices.length],Q=D.vertices[(k+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(P,v,y),o.rotate90cw(Z.normalA,P),o.normalize(Z.normalA,Z.normalA),a(M,m,y);var $=l(Z.normalA,M);o.scale(E,Z.normalA,$),a(Z.contactPointA,m,G),a(Z.contactPointA,Z.contactPointA,E),h(Z.contactPointA,Z.contactPointA,G),a(Z.contactPointA,Z.contactPointA,j.position),a(Z.contactPointB,m,N),h(Z.contactPointB,Z.contactPointB,N),a(Z.contactPointB,Z.contactPointB,V.position),this.contactEquations.push(Z),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Z))}}}return this.enableFrictionReduction&&this.enableFriction&&L&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;dh)&&(h=a),(null===c||ah){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,x=nt;if(t instanceof y&&n instanceof y)for(P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(C=0;2!==C;C++){0===C?o.set(m,0,1):1===C&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0),u=(S=T[0]-w[1])<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(var C=0;C!==b.vertices.length;C++){o.rotate(f,b.vertices[C],_),o.rotate(g,b.vertices[(C+1)%b.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0);var S=T[0]-w[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,x=pt,b=ct,_=ut,w=Math.floor((i[0]-d-l[0])/f),T=Math.ceil((i[0]+d-l[0])/f);w<0&&(w=0),T>=p.length&&(T=p.length-1);for(var P=p[w],C=p[T],S=w;SP&&(P=p[S]);if(i[1]-d>P)return!u&&0;for(var A=!1,S=w;S=b[0]&&m[0]<_[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,x,-E),o.add(y,m,g),o.copy(v,x);M=this.createContactEquation(n,t,r,e);o.copy(M.normalA,v),o.scale(M.contactPointB,M.normalA,-d),h(M.contactPointB,M.contactPointB,i),a(M.contactPointB,M.contactPointB,t.position),o.copy(M.contactPointA,y),o.sub(M.contactPointA,M.contactPointA,n.position),this.contactEquations.push(M),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(M))}}if(A=!1,d>0)for(S=w;S<=T;S++)if(o.set(b,S*f,p[S]),o.add(b,b,l),o.sub(g,i,b),o.squaredLength(g)=c.length&&(y=c.length-1);for(var v=c[m],x=c[y],b=m;bv&&(v=c[b]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var _=0,b=m;b=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;ne.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){this.from,this.to;var o=this._currentShape,a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;cthis.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.positioni?(a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n)):-1!==(b=t.indexOf(n))&&t.splice(b,1),this.lowerLimitEnabled&&va?(f.angle=a,-1===n.indexOf(f)&&n.push(f)):-1!==(y=n.indexOf(f))&&n.splice(y,1),this.lowerLimitEnabled&&m>1;if(e<3)return[];for(var i=[],n=[],r=0;r3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,x=1/(f*y-g*g),b=(y*m-g*v)*x,_=(f*v-g*m)*x;return b>=0&&_>=0&&b+_<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;ei&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),x=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||x;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(h=this.shapes.length;h>=0;--h)this.removeShape(this.shapes[h]);var i=new r.Polygon;if(i.vertices=t,i.makeCCW(),"number"==typeof e.removeCollinearPoints&&i.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!i.isSimple())return!1;this.concavePath=i.vertices.slice(0);for(h=0;h=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var T=n.create(),P=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(T,i,t*e),n.multiply(T,this.massMultiplier,T),n.add(r,T,r),this.integrateToTimeOfImpact(t)||(n.scale(P,r,t),n.add(s,s,P),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),M=n.create(),R=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)=l&&h=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var b=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),w=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),T=Math.pow(_,2)-4*b*w;if(!(T<0))if(0===T){if(r.lerp(d,n,o,T),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}else{var P=Math.sqrt(T),C=1/(2*b),S=(-_-P)*C,A=(-_+P)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,x=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;x>=0&&x<=1&&(r.lerp(f,n,h,x),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,x,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;in)&&(n=s),(null===o||sn){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;ee&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),nv){var x=y;y=v,v=x}for(var b=0;b=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,_,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};r.create();var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){(t=t||{}).type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){(t=t||{}).type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=t.lowerBound,a=t.upperBound;n(o,-1e7,-1e7),n(a,1e7,1e7),0===s?a[1]=0:s===Math.PI/2?o[0]=0:s===Math.PI?o[1]=0:s===3*Math.PI/2&&(a[0]=0)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}t("../utils/Utils");var n=t("../events/EventEmitter");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){this.overlappingShapesLastState;var n=this.overlappingShapesCurrentState;if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var s=t,n=e;(i=i||[]).length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;)(n=i.getByKey(i.keys[s]))&&e.push(n.bodyA,n.bodyB);return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s=t&&s=0;T-=2)for(S=b.length-2;S>=0;S-=2)(w[T]===b[S]&&w[T+1]===b[S+1]||w[T+1]===b[S]&&w[T]===b[S+1])&&b.splice(S,2);q=u.length;for(T=0;T!==q;T++){var C=u[T];if(!C.collideConnected)for(var S=b.length-2;S>=0;S-=2)(C.bodyA===b[S]&&C.bodyB===b[S+1]||C.bodyB===b[S]&&C.bodyA===b[S+1])&&b.splice(S,2)}this.postBroadphaseEvent.pairs=b,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var T=0,A=b.length;T!==A;T+=2)for(var E=b[T],M=b[T+1],R=0,L=E.shapes.length;R!==L;R++)for(var B=E.shapes[R],I=B.position,O=B.angle,k=0,F=M.shapes.length;k!==F;k++){var D=M.shapes[k],U=D.position,G=D.angle,N=this.defaultContactMaterial;if(B.material&&D.material){var X=this.getContactMaterial(B.material,D.material);X&&(N=X)}this.runNarrowphase(c,E,B,I,O,M,D,U,G,N,this.frictionGravity)}for(T=0;T!==h;T++)(H=n[T])._wakeUpAfterNarrowphase&&(H.wakeUp(),H._wakeUpAfterNarrowphase=!1);if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(P);for(var W=this.endContactEvent,k=P.length;k--;){var j=P[k];W.shapeA=j.shapeA,W.shapeB=j.shapeB,W.bodyA=j.bodyA,W.bodyB=j.bodyB,this.emit(W)}P.length=0}var V=this.preSolveEvent;V.contactEquations=c.contactEquations,V.frictionEquations=c.frictionEquations,this.emit(V),V.contactEquations=V.frictionEquations=null;var q=u.length;for(T=0;T!==q;T++)u[T].update();if(c.contactEquations.length||c.frictionEquations.length||q)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),T=0;T!==q;T++)v.appendArray(g.equations,u[T].equations);g.split(this);for(T=0;T!==g.islands.length;T++)(K=g.islands[T]).equations.length&&a.solveIsland(t,K)}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),T=0;T!==q;T++)a.addEquations(u[T].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(T=0;T!==h;T++){var H=n[T];H.integrate(t)}for(T=0;T!==h;T++)n[T].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var Y=this.impactEvent,T=0;T!==c.contactEquations.length;T++){var z=c.contactEquations[T];z.firstImpact&&(Y.bodyA=z.bodyA,Y.bodyB=z.bodyB,Y.shapeA=z.shapeA,Y.shapeB=z.shapeB,Y.contactEquation=z,this.emit(Y))}if(this.sleepMode===s.BODY_SLEEPING)for(T=0;T!==h;T++)n[T].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(T=0;T!==h;T++)n[T].sleepTick(this.time,!0,t);for(T=0;T0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,x=t.frictionEquations.length;y=i.type=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0),o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC&&r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0),this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var _=this.beginContactEvent;if(_.shapeA=i,_.shapeB=a,_.bodyA=e,_.bodyB=o,_.contactEquations.length=0,"number"==typeof y)for(P=t.contactEquations.length-y;P1)for(var P=t.frictionEquations.length-b;P=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var x=e[y],b=0,_=x.shapes.length;b!==_;b++){var w=x.shapes[b];r.rotate(p,w.position,x.angle),r.add(p,p,x.position);var T=w.angle+x.angle;(w instanceof o&&g.circleParticle(x,w,p,T,s,n,u,0,!0)||w instanceof a&&g.particleConvex(s,n,u,0,x,w,p,T,!0)||w instanceof h&&g.particlePlane(s,n,u,0,x,w,p,T,!0)||w instanceof l&&g.particleCapsule(s,n,u,0,x,w,p,T,!0)||w instanceof c&&r.squaredLength(r.sub(f,p,t))0?Math.acos(i/u):-Math.acos(i/u),this.worldScale.x=u,this.worldScale.y=c/u}else if(n||r){var d=Math.sqrt(n*n+r*r);this.worldRotation=Phaser.Math.HALF_PI-(r>0?Math.acos(-n/d):-Math.acos(n/d)),this.worldScale.x=c/d,this.worldScale.y=d}else this.worldScale.x=0,this.worldScale.y=0;return this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.x=l.tx,this.worldPosition.y=l.ty,this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,l,h),this},preUpdate:function(){},generateTexture:function(t,e,i){var n=this.getLocalBounds(),r=new Phaser.RenderTexture(this.game,0|n.width,0|n.height,i,e,t);return s.DisplayObject._tempMatrix.tx=-n.x,s.DisplayObject._tempMatrix.ty=-n.y,r.render(this,s.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?s.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):s.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=0;this.texture&&this.texture.baseTexture&&s._enableMultiTextureToggle&&(e=this.texture.baseTexture.textureIndex);var i=new Phaser.RenderTexture(this.game,t.width,t.height,void 0,void 0,void 0,void 0,e);this._cachedSprite=new s.Sprite(i),this._cachedSprite.worldTransform=this.worldTransform}var n=this._filters;this._filters=null,this._cachedSprite.filters=n,s.DisplayObject._tempMatrix.tx=-t.x,s.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,s.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=n,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},s.DisplayObject.prototype.displayObjectUpdateTransform=s.DisplayObject.prototype.updateTransform,Object.defineProperties(s.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],i=0;i=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},s.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},s.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},s.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},s.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},s.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},s.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},s.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(t,i),n=0;na?u:a,d=d>h?d:h);var f=this._bounds;if(!p){var g=(f=new s.Rectangle).x,m=f.width+f.x,y=f.y,v=f.height+f.y,x=this.worldTransform,b=x.a,_=x.b,w=x.c,T=x.d,P=x.tx,C=x.ty,S=b*m+w*v+P,A=T*v+_*m+C,E=b*g+w*v+P,M=T*v+_*g+C,R=b*g+w*y+P,L=T*y+_*g+C,B=b*m+w*y+P,I=T*y+_*m+C;u=S,d=A,c=A,l=B<(l=R<(l=E<(l=S)?E:l)?R:l)?B:l,c=I<(c=L<(c=M(u=R>(u=E>u?E:u)?R:u)?B:u,d=I>(d=L>(d=M>d?M:d)?L:d)?I:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n(f=T>(f=_>(f=x>f?x:f)?_:f)?T:f)?C:f,g=S>(g=P>(g=w>(g=b>g?b:g)?w:g)?P:g)?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},s.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=Phaser.identityMatrix;for(var e=0;e= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}","}"];var n=s.compileProgram(t,this.vertexSrc||s.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(n),this.uSamplerArray=t.getUniformLocation(n,"uSamplerArray[0]"),this.projectionVector=t.getUniformLocation(n,"projectionVector"),this.offsetVector=t.getUniformLocation(n,"offsetVector"),this.dimensions=t.getUniformLocation(n,"dimensions"),this.aVertexPosition=t.getAttribLocation(n,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(n,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(n,"aColor"),this.aTextureIndex=t.getAttribLocation(n,"aTextureIndex");var r=[],o=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var a=0;a 0.0) gl_Position = vec4(0.0);"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);"," vTextureIndex = aTextureIndex;","}"],s.PixiFastShader=function(t){if(this._UID=Phaser._UID++,this.gl=t,this.program=null,s._enableMultiTextureToggle){var t=this.gl;this.MAX_TEXTURES=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(var e="\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n",i=1;i= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["// PixiFastShader Fragment Shader.","precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;","}"];this.vertexSrc=["// PixiFastShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","attribute float aTextureIndex;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;"," vColor = aColor;","}"],this.textureCount=0,this.init()},s.PixiFastShader.prototype.constructor=s.PixiFastShader,s.PixiFastShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["//StripShader Fragment Shader.","precision mediump float;","varying vec2 vTextureCoord;","varying float vTextureIndex;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord);","}"];this.vertexSrc=["//StripShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aTextureIndex;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;","}"],this.init()},s.StripShader.prototype.constructor=s.StripShader,s.StripShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t},i=this.gl,n=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),r=i.getParameter(i.MAX_TEXTURE_SIZE),o=this.game.cache._cache.image,a=null,h=0;h=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var a=i._uvs;if(a){var h,l,c,u,d=t.anchor.x,p=t.anchor.y;if(i.trim){var f=i.trim;h=(l=f.x-d*f.width)+i.crop.width,c=(u=f.y-p*f.height)+i.crop.height}else h=i.frame.width*(1-d),l=i.frame.width*-d,c=i.frame.height*(1-p),u=i.frame.height*-p;var g=this.currentBatchSize*this.vertexSize,m=(this.currentBatchSize,i.baseTexture.resolution),y=i.baseTexture.textureIndex,v=o.a/m,x=o.b/m,b=o.c/m,_=o.d/m,w=o.tx,T=o.ty,P=(i.crop.width,i.crop.height);if(i.rotated){var C=o.a,S=o.b,A=o.c,E=o.d,M=l,R=h;w=o.c*P+w,T=o.d*P+T,v=6.123233995736766e-17*C-A,x=6.123233995736766e-17*S-E,b=C+6.123233995736766e-17*A,_=S+6.123233995736766e-17*E,i._updateUvsInverted(),h=c,l=u,c=R,u=M}var L=this.colors,B=this.positions,I=t.tint,O=(I>>16)+(65280&I)+((255&I)<<16)+(255*t.worldAlpha<<24);this.renderSession.roundPixels?(B[g++]=v*l+b*u+w|0,B[g++]=_*u+x*l+T|0,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w|0,B[g++]=_*u+x*h+T|0,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w|0,B[g++]=_*c+x*h+T|0,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w|0,B[g++]=_*c+x*l+T|0,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y):(B[g++]=v*l+b*u+w,B[g++]=_*u+x*l+T,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w,B[g++]=_*u+x*h+T,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w,B[g++]=_*c+x*h+T,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w,B[g++]=_*c+x*l+T,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y),this.sprites[this.currentBatchSize++]=t}},s.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture,i=e.baseTexture,n=this.gl,r=t.texture.baseTexture.textureIndex;s.WebGLRenderer.textureArray[r]!=i&&(this.flush(),n.activeTexture(n.TEXTURE0+r),n.bindTexture(n.TEXTURE_2D,i._glTextures[n.id]),s.WebGLRenderer.textureArray[r]=i),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new s.TextureUvs);var o=t._uvs,a=e.baseTexture.width,h=e.baseTexture.height;t.tilePosition.x%=a*t.tileScaleOffset.x,t.tilePosition.y%=h*t.tileScaleOffset.y;var l=t.tilePosition.x/(a*t.tileScaleOffset.x),c=t.tilePosition.y/(h*t.tileScaleOffset.y),u=t.width/a/(t.tileScale.x*t.tileScaleOffset.x),d=t.height/h/(t.tileScale.y*t.tileScaleOffset.y);o.x0=0-l,o.y0=0-c,o.x1=1*u-l,o.y1=0-c,o.x2=1*u-l,o.y2=1*d-c,o.x3=0-l,o.y3=1*d-c;var p=t.tint,f=(p>>16)+(65280&p)+((255&p)<<16)+(255*t.worldAlpha<<24),g=this.positions,m=this.colors,y=t.width,v=t.height,x=t.anchor.x,b=t.anchor.y,_=y*(1-x),w=y*-x,T=v*(1-b),P=v*-b,C=this.currentBatchSize*this.vertexSize,S=e.baseTexture.resolution,A=t.worldTransform,E=A.a/S,M=A.b/S,R=A.c/S,L=A.d/S,B=A.tx,I=A.ty;g[C++]=E*w+R*P+B,g[C++]=L*P+M*w+I,g[C++]=o.x0,g[C++]=o.y0,m[C++]=f,g[C++]=r,g[C++]=E*_+R*P+B,g[C++]=L*P+M*_+I,g[C++]=o.x1,g[C++]=o.y1,m[C++]=f,g[C++]=r,g[C++]=E*_+R*T+B,g[C++]=L*T+M*_+I,g[C++]=o.x2,g[C++]=o.y2,m[C++]=f,g[C++]=r,g[C++]=E*w+R*T+B,g[C++]=L*T+M*w+I,g[C++]=o.x3,g[C++]=o.y3,m[C++]=f,g[C++]=r,this.sprites[this.currentBatchSize++]=t},s.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,t=this.defaultShader.shaders[e.id],e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var i=this.vertexSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,i,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,i,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,i,16),e.vertexAttribPointer(t.aTextureIndex,1,e.FLOAT,!1,i,20)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);var n=this.positions.subarray(0,this.currentBatchSize*this.vertexSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m0&&(v=!1),(f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){(t=(p=a).shaders[e.id])||((t=new s.PixiShader(e)).fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var x=this.renderSession.projection;e.uniform2f(t.projectionVector,x.x,x.y);var b=this.renderSession.offset;e.uniform2f(t.offsetVector,b.x,b.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},s.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},s.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},s.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},s.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},s.WebGLFastSpriteBatch=function(t){this.vertSize=11,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,i=6*this.maxSize;this.vertices=new Float32Array(e),this.indices=new Uint16Array(i),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var s=0,n=0;s=this.size&&this.flush()}},s.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]){if(this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}else this.renderSession.renderer.updateTexture(this.currentBaseTexture,t)}},s.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},s.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36),t.vertexAttribPointer(this.shader.aTextureIndex,1,t.FLOAT,!1,i,40)},s.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},s.WebGLFilterManager.prototype.constructor=s.WebGLFilterManager,s.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},s.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},s.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,i=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new s.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),i.x=a.width/2,i.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},s.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),i=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,i.width*this.renderSession.resolution,i.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=i.height,this.vertexArray[2]=i.width,this.vertexArray[3]=i.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=i.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=i.width/this.width,this.uvArray[5]=i.height/this.height,this.uvArray[6]=i.width/this.width,this.uvArray[7]=i.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,i,p,f),this.texturePool.push(n),e._glFilterTexture=null},s.WebGLFilterManager.prototype.applyFilterPass=function(t,e,i,n){var r=this.gl,o=t.shaders[r.id];o||((o=new s.PixiShader(r)).fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(!0),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,i/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},s.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},s.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e=0;t--){var e=this._glTextures[t],i=s.glContexts[t];i&&e&&i.deleteTexture(e)}this._glTextures.length=0,this.dirty()},s.BaseTexture.fromCanvas=function(t,e,i){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),i=i||1,new s.BaseTexture(t,e,i)},s.TextureSilentFail=!1,s.Texture=function(t,e,i,n){this.noFrame=!1,e||(this.noFrame=!0,e=new s.Rectangle(0,0,1,1)),t instanceof s.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=i||new s.Rectangle(0,0,1,1),this.rotated=!1,t.hasLoaded&&(this.noFrame&&(e=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},s.Texture.prototype.constructor=s.Texture,s.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},s.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},s.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,this.trim||!(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height))this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs();else{if(!s.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=!1}},s.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/i},s.Texture.prototype._updateUvsInverted=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.height)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.height)/e,this._uvs.y2=(t.y+t.width)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.width)/i},s.Texture.fromCanvas=function(t,e){var i=s.BaseTexture.fromCanvas(t,e);return new s.Texture(i)},s.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=s),exports.PIXI=s):"undefined"!=typeof define&&define.amd?define("PIXI",i.PIXI=s):i.PIXI=s,s}.call(this),function(){function t(t,e){this._scaleFactor=t,this._deltaMode=e,this.originalEvent=null}var e=this,i=i||{VERSION:"2.10.0",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,WEBGL_MULTI:4,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,PENDING_ATLAS:-1,HORIZONTAL:0,VERTICAL:1,LANDSCAPE:0,PORTRAIT:1,ANGLE_UP:270,ANGLE_DOWN:90,ANGLE_LEFT:180,ANGLE_RIGHT:0,ANGLE_NORTH_EAST:315,ANGLE_NORTH_WEST:225,ANGLE_SOUTH_EAST:45,ANGLE_SOUTH_WEST:135,TOP_LEFT:0,TOP_CENTER:1,TOP_RIGHT:2,LEFT_TOP:3,LEFT_CENTER:4,LEFT_BOTTOM:5,CENTER:6,RIGHT_TOP:7,RIGHT_CENTER:8,RIGHT_BOTTOM:9,BOTTOM_LEFT:10,BOTTOM_CENTER:11,BOTTOM_RIGHT:12,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},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{},_UID:0};if(Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Function.prototype.bind||(Function.prototype.bind=function(){var t=Array.prototype.slice;return function(e){function i(){var r=n.concat(t.call(arguments));s.apply(this instanceof i?this:e,r)}var s=this,n=t.call(arguments,1);if("function"!=typeof s)throw new TypeError;return i.prototype=function t(e){if(e&&(t.prototype=e),!(this instanceof t))return new t}(s.prototype),i}}()),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var s=arguments.length>=2?arguments[1]:void 0,n=0;n0&&100*Math.random()<=t},randomChoice:function(t,e){return Math.random()<.5?t:e},parseDimension:function(t,e){var i=0,s=0;return"string"==typeof t?"%"===t.substr(-1)?(i=parseInt(t,10)/100,s=0===e?window.innerWidth*i:window.innerHeight*i):s=parseInt(t,10):s=t,s},pad:function(t,e,i,s){if(void 0===e)var e=0;if(void 0===i)var i=" ";if(void 0===s)var s=3;var n=0;if(e+1>=(t=t.toString()).length)switch(s){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((n=e-t.length)/2),o=n-r;t=new Array(o+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t},isPlainObject:function(t){if("object"!=typeof t||t.nodeType||t===t.window)return!1;try{if(t.constructor&&!{}.hasOwnProperty.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},extend:function(){var t,e,s,n,r,o,a=arguments[0]||{},h=1,l=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[1]||{},h=2),l===h&&(a=this,--h);h0&&(this._radius=.5*s),this.type=i.CIRCLE},i.Circle.prototype={circumference:function(){return Math.PI*this._radius*2},random:function(t){void 0===t&&(t=new i.Point);var e=2*Math.PI*Math.random(),s=Math.random()+Math.random(),n=s>1?2-s:s,r=n*Math.cos(e),o=n*Math.sin(e);return t.x=this.x+r*this.radius,t.y=this.y+o*this.radius,t},getBounds:function(){return new i.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(t,e,i){return this.x=t,this.y=e,this._diameter=i,this._radius=.5*i,this},copyFrom:function(t){return this.setTo(t.x,t.y,t.diameter)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.diameter=this._diameter,t},distance:function(t,e){var s=i.Math.distance(this.x,this.y,t.x,t.y);return e?Math.round(s):s},clone:function(t){return void 0===t||null===t?t=new i.Circle(this.x,this.y,this.diameter):t.setTo(this.x,this.y,this.diameter),t},contains:function(t,e){return i.Circle.contains(this,t,e)},circumferencePoint:function(t,e,s){return i.Circle.circumferencePoint(this,t,e,s)},sample:function(t,e,s,n,r){t||(t=60),null==e&&(e=0),null==s&&(s=i.Math.PI2),r||(r=[]);for(var o=0;o0&&(this._diameter=t,this._radius=.5*t)}}),Object.defineProperty(i.Circle.prototype,"radius",{get:function(){return this._radius},set:function(t){t>0&&(this._radius=t,this._diameter=2*t)}}),Object.defineProperty(i.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(t){t>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-t}}),Object.defineProperty(i.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(t){tthis.y?(this._radius=0,this._diameter=0):this.radius=this.y-t}}),Object.defineProperty(i.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(t){t0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(i.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(t){!0===t&&this.setTo(0,0,0)}}),i.Circle.contains=function(t,e,i){return t.radius>0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius},i.Circle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.diameter===e.diameter},i.Circle.intersects=function(t,e){return i.Math.distance(t.x,t.y,e.x,e.y)<=t.radius+e.radius},i.Circle.circumferencePoint=function(t,e,s,n){return void 0===s&&(s=!1),void 0===n&&(n=new i.Point),!0===s&&(e=i.Math.degToRad(e)),n.x=t.x+t.radius*Math.cos(e),n.y=t.y+t.radius*Math.sin(e),n},i.Circle.intersectsRectangle=function(t,e){var i=Math.abs(t.x-e.x-e.halfWidth);if(i>e.halfWidth+t.radius)return!1;var s=Math.abs(t.y-e.y-e.halfHeight);if(s>e.halfHeight+t.radius)return!1;if(i<=e.halfWidth||s<=e.halfHeight)return!0;var n=i-e.halfWidth,r=s-e.halfHeight;return n*n+r*r<=t.radius*t.radius},i.Circle.intersectsLine=function(t,e,s){var n=t.x,r=t.y,o=(e.end.y-e.start.y)/(e.end.x-e.start.x),a=e.end.y-o*e.end.x,h=t.radius,l=t.radius,c=a+o*n,u=(n*(l*l)-o*(h*h)*(a-r)+h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),d=(n*(l*l)-o*(h*h)*(a-r)-h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),p=o*u+a,f=o*d+a,g=new i.Point(u,p),m=new i.Point(d,f),y=e.pointOnSegment(g.x,g.y,.01),v=e.pointOnSegment(m.x,m.y,.01);return y&&v?!s||[g,m]:y?!s||[g]:v?!s||[m]:!!s&&[]},PIXI.Circle=i.Circle,i.Ellipse=function(t,e,s,n){t=t||0,e=e||0,s=s||0,n=n||0,this.x=t,this.y=e,this.width=s,this.height=n,this.type=i.ELLIPSE},i.Ellipse.prototype={setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},getBounds:function(){return new i.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},clone:function(t){return void 0===t||null===t?t=new i.Ellipse(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t},contains:function(t,e){return i.Ellipse.contains(this,t,e)},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random()*Math.PI*2,s=Math.random();return t.x=Math.sqrt(s)*Math.cos(e),t.y=Math.sqrt(s)*Math.sin(e),t.x=this.x+t.x*this.width/2,t.y=this.y+t.y*this.height/2,t},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},i.Ellipse.prototype.constructor=i.Ellipse,Object.defineProperty(i.Ellipse.prototype,"left",{get:function(){return this.x},set:function(t){this.x=t}}),Object.defineProperty(i.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t=s&&t<=n&&e>=r&&e<=o},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random();return t.x=this.start.x+e*(this.end.x-this.start.x),t.y=this.start.y+e*(this.end.y-this.start.y),t},coordinatesOnLine:function(t,e){void 0===t&&(t=1),void 0===e&&(e=[]);var i=Math.round(this.start.x),s=Math.round(this.start.y),n=Math.round(this.end.x),r=Math.round(this.end.y),o=Math.abs(n-i),a=Math.abs(r-s),h=i-a&&(c-=a,i+=h),d=0&&g<=1&&m>=0&&m<=1?o:null}return o},i.Line.intersects=function(t,e,s,n){return i.Line.intersectsPoints(t.start,t.end,e.start,e.end,s,n)},i.Line.intersectsRectangle=function(t,e){if(0===t.length||e.empty)return!1;var i=t.start.x,s=t.start.y,n=t.end.x,r=t.end.y,o=e.x,a=e.y,h=e.right,l=e.bottom,c=0;if(i>=o&&i<=h&&s>=a&&s<=l||n>=o&&n<=h&&r>=a&&r<=l)return!0;if(i=o){if((c=s+(r-s)*(o-i)/(n-i))>a&&c<=l)return!0}else if(i>h&&n<=h&&(c=s+(r-s)*(h-i)/(n-i))>=a&&c<=l)return!0;if(s=a){if((c=i+(n-i)*(a-s)/(r-s))>=o&&c<=h)return!0}else if(s>l&&r<=l&&(c=i+(n-i)*(l-s)/(r-s))>=o&&c<=h)return!0;return!1},i.Line.intersectionWithRectangle=function(t,e,s){var n=i.Line.intersectionWithRectangle;s||(s=new i.Point),n.edges||(n.edges=[new i.Line,new i.Line,new i.Line,new i.Line]),n.edgeIntersection||(n.edgeIntersection=new i.Point);var r=n.edges,o=n.edgeIntersection.set(0),a=e.x,h=e.y,l=e.right,c=e.bottom,u=1/0;r[0].setTo(a,h,l,h),r[1].setTo(a,c,l,c),r[2].setTo(a,h,a,c),r[3].setTo(l,h,l,c);for(var d,p=0;d=r[p];p++)if(t.intersects(d,!0,o)){var f=t.start.distance(o);fs&&(this.x=s),this.yn&&(this.y=n),this},clone:function(t){return void 0===t||null===t?t=new i.Point(this.x,this.y):t.setTo(this.x,this.y),t},copyTo:function(t){return t.x=this.x,t.y=this.y,t},distance:function(t,e){return i.Point.distance(this,t,e)},equals:function(t){return t.x===this.x&&t.y===this.y},equalsXY:function(t,e){return this.x===t&&this.y===e},fuzzyEquals:function(t,e){return i.Point.fuzzyEquals(this,t,e)},fuzzyEqualsXY:function(t,e,s){return i.Point.fuzzyEqualsXY(this,t,e,s)},angle:function(t,e){return this.angleXY(t.x,t.y,e)},angleXY:function(t,e,s){var n=Math.atan2(e-this.y,t-this.x);return s?i.Math.radToDeg(n):n},atan:function(t){var e=Math.atan2(this.y,this.x);return t?i.Math.radToDeg(e):e},rotate:function(t,e,s,n,r){return i.Point.rotate(this,t,e,s,n,r)},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(t){return this.normalize().multiply(t,t)},normalize:function(){if(!this.isZero()){var t=this.getMagnitude();this.x/=t,this.y/=t}return this},limit:function(t){return this.getMagnitudeSq()>t*t&&this.setMagnitude(t),this},expand:function(t){return this.getMagnitudeSq()=0&&e.x-i<0)return-1;if(t.x-i<0&&e.x-i>=0)return 1;if(t.x-i==0&&e.x-i==0)return t.y-s>=0||e.y-s>=0?t.y>e.y?1:-1:e.y>t.y?1:-1;var n=(t.x-i)*-(e.y-s)-(e.x-i)*-(t.y-s);return n<0?-1:n>0?1:(t.x-i)*(t.x-i)+(t.y-s)*(t.y-s)>(e.x-i)*(e.x-i)+(e.y-s)*(e.y-s)?-1:1})},PIXI.Point=i.Point,i.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.flattened=!1,this.type=i.POLYGON},i.Polygon.prototype={toNumberArray:function(t){void 0===t&&(t=[]);for(var e=0;e0){Array.isArray(t)||(t=Array.prototype.slice.call(arguments));for(var e=Number.MAX_VALUE,i=0,s=t.length;i=this.right?this.width=0:this.width=this.right-t,this.x=t}}),Object.defineProperty(i.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(i.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(i.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(i.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(t){this.x=t-this.halfWidth}}),Object.defineProperty(i.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(t){this.y=t-this.halfHeight}}),Object.defineProperty(i.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(i.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(i.Rectangle.prototype,"top",{get:function(){return this.y},set:function(t){t>=this.bottom?(this.height=0,this.y=t):this.height=this.bottom-t}}),Object.defineProperty(i.Rectangle.prototype,"topLeft",{get:function(){return new i.Point(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"topRight",{get:function(){return new i.Point(this.x+this.width,this.y)},set:function(t){this.right=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),i.Rectangle.prototype.constructor=i.Rectangle,i.Rectangle.inflate=function(t,e,i){return t.x-=e,t.width+=2*e,t.y-=i,t.height+=2*i,t},i.Rectangle.inflatePoint=function(t,e){return i.Rectangle.inflate(t,e.x,e.y)},i.Rectangle.size=function(t,e){return void 0===e||null===e?e=new i.Point(t.width,t.height):e.setTo(t.width,t.height),e},i.Rectangle.clone=function(t,e){return void 0===e||null===e?e=new i.Rectangle(t.x,t.y,t.width,t.height):e.setTo(t.x,t.y,t.width,t.height),e},i.Rectangle.createFromBounds=function(t,e){return void 0!==e&&null!==e||(e=new i.Rectangle(t.x,t.y,t.width,t.height)),e.copyFromBounds(t)},i.Rectangle.contains=function(t,e,i){return!(t.width<=0||t.height<=0)&&(e>=t.x&&e=t.y&&i=t&&n=e&&re.volume)&&(t.x>=e.x&&t.y>=e.y&&t.righte.right||t.y>e.bottom)},i.Rectangle.intersectsRaw=function(t,e,i,s,n,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||ns&&(s=t.x),t.xr&&(r=t.y),t.y=i&&t<=i+this.width){var s=this.y;if(e>=s&&e<=s+this.height)return!0}return!1}},i.RoundedRectangle.prototype.constructor=i.RoundedRectangle,PIXI.RoundedRectangle=i.RoundedRectangle,i.Camera=function(t,e,s,n,r,o){this.game=t,this.world=t.world,this.id=0,this.view=new i.Rectangle(s,n,r,o),this.bounds=new i.Rectangle(s,n,r,o),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this.lerp=new i.Point(1,1),this.onShakeComplete=new i.Signal,this.onFlashComplete=new i.Signal,this.onFadeComplete=new i.Signal,this.fx=null,this._targetPosition=new i.Point,this._edge=0,this._position=new i.Point,this._shake={intensity:0,duration:0,horizontal:!1,vertical:!1,shakeBounds:!0,x:0,y:0},this._fxDuration=0,this._fxType=0,this._fixedView=new i.Rectangle},i.Camera.FOLLOW_LOCKON=0,i.Camera.FOLLOW_PLATFORMER=1,i.Camera.FOLLOW_TOPDOWN=2,i.Camera.FOLLOW_TOPDOWN_TIGHT=3,i.Camera.SHAKE_BOTH=4,i.Camera.SHAKE_HORIZONTAL=5,i.Camera.SHAKE_VERTICAL=6,i.Camera.ENABLE_FX=!0,i.Camera.prototype={boot:function(){this.displayObject=this.game.world,this.scale=this.game.world.scale,this.game.camera=this,i.Graphics&&i.Camera.ENABLE_FX&&(this.fx=new i.Graphics(this.game),this.game.stage.addChild(this.fx))},preUpdate:function(){this.totalInView=0},follow:function(t,e,s,n){void 0===e&&(e=i.Camera.FOLLOW_LOCKON),void 0===s&&(s=1),void 0===n&&(n=1),this.target=t,this.lerp.set(s,n);var r;switch(e){case i.Camera.FOLLOW_PLATFORMER:var o=this.width/8,a=this.height/3;this.deadzone=new i.Rectangle((this.width-o)/2,(this.height-a)/2-.25*a,o,a);break;case i.Camera.FOLLOW_TOPDOWN:r=Math.max(this.width,this.height)/4,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_TOPDOWN_TIGHT:r=Math.max(this.width,this.height)/8,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_LOCKON:default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(t){this.setPosition(Math.round(t.x-this.view.halfWidth),Math.round(t.y-this.view.halfHeight))},focusOnXY:function(t,e){this.setPosition(Math.round(t-this.view.halfWidth),Math.round(e-this.view.halfHeight))},shake:function(t,e,s,n,r){return void 0===t&&(t=.05),void 0===e&&(e=500),void 0===s&&(s=!0),void 0===n&&(n=i.Camera.SHAKE_BOTH),void 0===r&&(r=!0),!(!s&&this._shake.duration>0)&&(this._shake.intensity=t,this._shake.duration=e,this._shake.shakeBounds=r,this._shake.x=0,this._shake.y=0,this._shake.horizontal=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_HORIZONTAL,this._shake.vertical=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_VERTICAL,!0)},flash:function(t,e,i,s){return void 0===t&&(t=16777215),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=1,this._fxDuration=e,this._fxType=0,!0)},fade:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=0,this._fxDuration=e,this._fxType=1,!0)},update:function(){this._fxDuration>0&&this.updateFX(),this._shake.duration>0&&this.updateShake(),this.bounds&&this.checkBounds(),this.roundPx&&(this.view.floor(),this._shake.x=Math.floor(this._shake.x),this._shake.y=Math.floor(this._shake.y)),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateFX:function(){0===this._fxType?(this.fx.alpha-=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha<=0&&(this._fxDuration=0,this.fx.alpha=0,this.onFlashComplete.dispatch())):(this.fx.alpha+=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha>=1&&(this._fxDuration=0,this.fx.alpha=1,this.onFadeComplete.dispatch()))},updateShake:function(){this._shake.duration-=this.game.time.elapsedMS,this._shake.duration<=0?(this.onShakeComplete.dispatch(),this._shake.x=0,this._shake.y=0):(this._shake.horizontal&&(this._shake.x=this.game.rnd.frac()*this._shake.intensity*this.view.width*2-this._shake.intensity*this.view.width),this._shake.vertical&&(this._shake.y=this.game.rnd.frac()*this._shake.intensity*this.view.height*2-this._shake.intensity*this.view.height))},updateTarget:function(){this._targetPosition.x=this.view.x+this.target.worldPosition.x,this._targetPosition.y=this.view.y+this.target.worldPosition.y,this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edgethis.deadzone.right&&(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.right,this.lerp.x)),this._edge=this._targetPosition.y-this.view.y,this._edgethis.deadzone.bottom&&(this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.bottom,this.lerp.y))):(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.view.halfWidth,this.lerp.x),this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.view.halfHeight,this.lerp.y)),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},setBoundsToWorld:function(){this.bounds&&this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1;var t=this.view.x+this._shake.x,e=this.view.right+this._shake.x,i=this.view.y+this._shake.y,s=this.view.bottom+this._shake.y;t<=this.bounds.x*this.scale.x?(this.atLimit.x=!0,this.view.x=this.bounds.x*this.scale.x,this._shake.shakeBounds||(this._shake.x=0)):e>=this.bounds.right*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.right*this.scale.x-this.width,this._shake.shakeBounds||(this._shake.x=0)),i<=this.bounds.top*this.scale.y?(this.atLimit.y=!0,this.view.y=this.bounds.top*this.scale.y,this._shake.shakeBounds||(this._shake.y=0)):s>=this.bounds.bottom*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom*this.scale.y-this.height,this._shake.shakeBounds||(this._shake.y=0))},setPosition:function(t,e){this.view.x=t,this.view.y=e,this.bounds&&this.checkBounds()},setSize:function(t,e){this.view.width=t,this.view.height=e},reset:function(){this.target=null,this.view.x=0,this.view.y=0,this._shake.duration=0,this._shake.x=0,this._shake.y=0,this.resetFX()},resetFX:function(){this.fx&&(this.fx.clear(),this.fx.alpha=0),this._fxDuration=0}},i.Camera.prototype.constructor=i.Camera,Object.defineProperty(i.Camera.prototype,"x",{get:function(){return this.view.x},set:function(t){this.view.x=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"y",{get:function(){return this.view.y},set:function(t){this.view.y=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"position",{get:function(){return this._position.set(this.view.x,this.view.y),this._position},set:function(t){void 0!==t.x&&(this.view.x=t.x),void 0!==t.y&&(this.view.y=t.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"width",{get:function(){return this.view.width},set:function(t){this.view.width=t}}),Object.defineProperty(i.Camera.prototype,"height",{get:function(){return this.view.height},set:function(t){this.view.height=t}}),Object.defineProperty(i.Camera.prototype,"shakeIntensity",{get:function(){return this._shake.intensity},set:function(t){this._shake.intensity=t}}),Object.defineProperty(i.Camera.prototype,"fixedView",{get:function(){return this._fixedView.setTo(0,0,this.view.width,this.view.height),this._fixedView}}),i.State=function(){this.game=null,this.key="",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.state=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},i.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},i.State.prototype.constructor=i.State,i.StateManager=function(t,e){this.game=t,this.states={},this._pendingState=null,void 0!==e&&null!==e&&(this._pendingState=e),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new i.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},i.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(t,e,s){void 0===s&&(s=!1);var n;return e instanceof i.State?n=e:"object"==typeof e?(n=e).game=this.game:"function"==typeof e&&(n=new e(this.game)),this.states[t]=n,s&&(this.game.isBooted?this.start(t):this._pendingState=t),n},remove:function(t){this.current===t&&(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.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[t]},start:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1),this.checkState(t)&&(this._pendingState=t,this._clearWorld=e,this._clearCache=i,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!1),this._pendingState=this.current,this._clearWorld=t,this._clearCache=e,arguments.length>2&&(this._args=Array.prototype.slice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var t=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,t),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache&&this.game.cache.destroy()))},checkState:function(t){var e=this.states[t];return e?!!(e.preload||e.create||e.update||e.render)||(console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"),!1):(console.warn("Phaser.StateManager - No state found with the key: "+t),!1)},link:function(t){var e=this.states[t];e.game=this.game,e.add=this.game.add,e.make=this.game.make,e.camera=this.game.camera,e.cache=this.game.cache,e.input=this.game.input,e.load=this.game.load,e.math=this.game.math,e.sound=this.game.sound,e.scale=this.game.scale,e.state=this,e.stage=this.game.stage,e.time=this.game.time,e.tweens=this.game.tweens,e.world=this.game.world,e.particles=this.game.particles,e.rnd=this.game.rnd,e.physics=this.game.physics,e.key=t},unlink:function(t){var e=this.states[t];e&&(e.game=null,e.add=null,e.make=null,e.camera=null,e.cache=null,e.input=null,e.load=null,e.math=null,e.sound=null,e.scale=null,e.state=null,e.stage=null,e.time=null,e.tweens=null,e.world=null,e.particles=null,e.rnd=null,e.physics=null)},setCurrentState:function(t){var e=this.states[t];this.callbackContext=e,this.link(t),this.onInitCallback=e.init||this.dummy,this.onPreloadCallback=e.preload||null,this.onLoadRenderCallback=e.loadRender||null,this.onLoadUpdateCallback=e.loadUpdate||null,this.onCreateCallback=e.create||null,this.onUpdateCallback=e.update||null,this.onPreRenderCallback=e.preRender||null,this.onRenderCallback=e.render||null,this.onResizeCallback=e.resize||null,this.onPausedCallback=e.paused||null,this.onResumedCallback=e.resumed||null,this.onPauseUpdateCallback=e.pauseUpdate||null,this.onShutDownCallback=e.shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=t,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),t===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){!1===this._created&&this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game),!1===this._created&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(t){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,t)},resize:function(t,e){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,t,e)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===i.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this._clearWorld=!0,this._clearCache=!0,this.clearCurrentState(),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,this.current=""}},i.StateManager.prototype.constructor=i.StateManager,Object.defineProperty(i.StateManager.prototype,"created",{get:function(){return this._created}}),i.Signal=function(){},i.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!1,validateListener:function(t,e){if("function"!=typeof t)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",e))},_registerListener:function(t,e,s,n,r){var o,a=this._indexOfListener(t,s);if(-1!==a){if((o=this._bindings[a]).isOnce()!==e)throw new Error("You cannot add"+(e?"":"Once")+"() then add"+(e?"Once":"")+"() the same listener without removing the relationship first.")}else o=new i.SignalBinding(this,t,e,s,n,r),this._addBinding(o);return this.memorize&&this._prevParams&&o.execute(this._prevParams),o},_addBinding:function(t){this._bindings||(this._bindings=[]);var e=this._bindings.length;do{e--}while(this._bindings[e]&&t._priority<=this._bindings[e]._priority);this._bindings.splice(e+1,0,t)},_indexOfListener:function(t,e){if(!this._bindings)return-1;void 0===e&&(e=null);for(var i,s=this._bindings.length;s--;)if((i=this._bindings[s])._listener===t&&i.context===e)return s;return-1},has:function(t,e){return-1!==this._indexOfListener(t,e)},add:function(t,e,i){this.validateListener(t,"add");var s=[];if(arguments.length>3)for(var n=3;n3)for(var n=3;n=this.children.length?-1:this.getChildAt(t)},i.Group.prototype.create=function(t,e,i,s,n,r){void 0===n&&(n=!0);var o=new this.classType(this.game,t,e,i,s);return o.exists=n,o.visible=n,o.alive=n,this.add(o,!1,r)},i.Group.prototype.createMultiple=function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=!1),Array.isArray(e)||(e=[e]),Array.isArray(i)||(i=[i]);var o=this,a=[];return e.forEach(function(e){i.forEach(function(i){for(var h=0;hthis.children.length||-1===t&&-1===e)return!1;for(var a=new i.Rectangle(0,0,s,n),h=t*s,l=e*n,c=o;cthis.children.length-1&&(t=0),this.cursor)return this.cursorIndex=t,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.next=function(){if(this.cursor)return this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.previous=function(){if(this.cursor)return 0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.swap=function(t,e){this.swapChildren(t,e),this.updateZ()},i.Group.prototype.bringToTop=function(t){return t.parent===this&&this.getIndex(t)0&&(this.remove(t,!1,!0),this.addAt(t,0,!0)),t},i.Group.prototype.moveUp=function(t){if(t.parent===this&&this.getIndex(t)0){var e=this.getIndex(t),i=this.getAt(e-1);i&&this.swap(t,i)}return t},i.Group.prototype.xy=function(t,e,i){if(t<0||t>this.children.length)return-1;this.getChildAt(t).x=e,this.getChildAt(t).y=i},i.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},i.Group.prototype.getIndex=function(t){return this.children.indexOf(t)},i.Group.prototype.getByName=function(t){for(var e=0;e0))return!1;var r=e.length;return 1===r?0===s?t[e[0]]=i:1===s?t[e[0]]+=i:2===s?t[e[0]]-=i:3===s?t[e[0]]*=i:4===s&&(t[e[0]]/=i):2===r?0===s?t[e[0]][e[1]]=i:1===s?t[e[0]][e[1]]+=i:2===s?t[e[0]][e[1]]-=i:3===s?t[e[0]][e[1]]*=i:4===s&&(t[e[0]][e[1]]/=i):3===r?0===s?t[e[0]][e[1]][e[2]]=i:1===s?t[e[0]][e[1]][e[2]]+=i:2===s?t[e[0]][e[1]][e[2]]-=i:3===s?t[e[0]][e[1]][e[2]]*=i:4===s&&(t[e[0]][e[1]][e[2]]/=i):4===r&&(0===s?t[e[0]][e[1]][e[2]][e[3]]=i:1===s?t[e[0]][e[1]][e[2]][e[3]]+=i:2===s?t[e[0]][e[1]][e[2]][e[3]]-=i:3===s?t[e[0]][e[1]][e[2]][e[3]]*=i:4===s&&(t[e[0]][e[1]][e[2]][e[3]]/=i)),!0},i.Group.prototype.checkProperty=function(t,e,s,n){if(void 0===n&&(n=!1),this!==t.parent)return!1;var r=i.Utils.getProperty(t,e);return!(void 0===r&&n||r!==s)},i.Group.prototype.set=function(t,e,i,s,n,r,o){if(void 0===o&&(o=!1),e=e.split("."),void 0===s&&(s=!1),void 0===n&&(n=!1),(!1===s||s&&t.alive)&&(!1===n||n&&t.visible))return this.setProperty(t,e,i,r,o)},i.Group.prototype.setAll=function(t,e,i,s,n,r){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===r&&(r=!1),t=t.split("."),n=n||0;for(var o=0;o2){i=[];for(s=2;s2){n=[];for(a=2;a=e&&(t=e-1);var i=this.children[t];this.updateOnlyExistingChildren&&!i.exists||i.update()}},i.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y);for(var t=0;t2){s=[null];for(var n=2;n2){s=[null];for(var n=2;n2){s=[null];for(var n=2;ne[this._sortProperty]?1:t.ze[this._sortProperty]?-1:0},i.Group.prototype.iterate=function(t,e,s,n,r,o){if(0===this.children.length){if(s===i.Group.RETURN_TOTAL)return 0;if(s===i.Group.RETURN_ALL)return[]}var a=0;if(s===i.Group.RETURN_ALL)var h=[];for(var l=0;l0)return this.children[this.children.length-1]},i.Group.prototype.getBottom=function(){if(this.children.length>0)return this.children[0]},i.Group.prototype.getClosestTo=function(t,e,s){for(var n=Number.MAX_VALUE,r=0,o=null,a=0;an&&(!e||e.call(s,h,r))&&(n=r,o=h)}return o},i.Group.prototype.count=function(t,e){return this.iterate(t,e,i.Group.RETURN_TOTAL)},i.Group.prototype.countLiving=function(){return this.count("alive",!0)},i.Group.prototype.countDead=function(){return this.count("alive",!1)},i.Group.prototype.getRandom=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.children.length),0===e?null:i.ArrayUtils.getRandomItem(this.children,t,e)},i.Group.prototype.getRandomExists=function(t,e){var i=this.getAll("exists",!0,t,e);return this.game.rnd.pick(i)},i.Group.prototype.getAll=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=this.children.length);for(var n=[],r=i;r0&&t instanceof i.Group){do{t.add(this.children[0],e)}while(this.children.length>0);this.hash=[],this.cursor=null}return t},i.Group.prototype.removeAll=function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),0!==this.children.length){do{!e&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var s=this.removeChild(this.children[0]);this.removeFromHash(s),t&&s&&s.destroy(!0,i)}while(this.children.length>0);this.hash=[],this.cursor=null}},i.Group.prototype.removeBetween=function(t,e,i,s){if(void 0===e&&(e=this.children.length-1),void 0===i&&(i=!1),void 0===s&&(s=!1),0!==this.children.length){if(t>e||t<0||e>this.children.length)return!1;for(var n=e;n>=t;){!s&&this.children[n].events&&this.children[n].events.onRemovedFromGroup$dispatch(this.children[n],this);var r=this.removeChild(this.children[n]);this.removeFromHash(r),i&&r&&r.destroy(!0),this.cursor===this.children[n]&&(this.cursor=null),n--}this.updateZ()}},i.Group.prototype.scatter=function(t,e){null==t&&(t=this.game.world.bounds),this.forEach(function(e){e.position.set(t.randomX,t.randomY)},null,e)},i.Group.prototype.shuffle=function(){i.ArrayUtils.shuffle(this.children),this.updateZ()},i.Group.prototype.destroy=function(t,e){null===this.game||this.ignoreDestroy||(void 0===t&&(t=!0),void 0===e&&(e=!1),this.onDestroy.dispatch(this,t,e),this.removeAll(t),this.cursor=null,this.filters=null,this.pendingDestroy=!1,e||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(i.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,i.Group.RETURN_TOTAL)}}),Object.defineProperty(i.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(i.Group.prototype,"angle",{get:function(){return i.Math.radToDeg(this.rotation)},set:function(t){this.rotation=i.Math.degToRad(t)}}),Object.defineProperty(i.Group.prototype,"centerX",{get:function(){return this.getBounds(this.parent).centerX},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.halfWidth}}),Object.defineProperty(i.Group.prototype,"centerY",{get:function(){return this.getBounds(this.parent).centerY},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.halfHeight}}),Object.defineProperty(i.Group.prototype,"left",{get:function(){return this.getBounds(this.parent).left},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i}}),Object.defineProperty(i.Group.prototype,"right",{get:function(){return this.getBounds(this.parent).right},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.width}}),Object.defineProperty(i.Group.prototype,"top",{get:function(){return this.getBounds(this.parent).top},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i}}),Object.defineProperty(i.Group.prototype,"bottom",{get:function(){return this.getBounds(this.parent).bottom},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.height}}),i.World=function(t){i.Group.call(this,t,null,"__world",!1),this.bounds=new i.Rectangle(0,0,t.width,t.height),this.camera=null,this._definedSize=!1,this._width=t.width,this._height=t.height,this.game.state.onStateChange.add(this.stateChange,this)},i.World.prototype=Object.create(i.Group.prototype),i.World.prototype.constructor=i.World,i.World.prototype.boot=function(){this.camera=new i.Camera(this.game,0,0,0,this.game.width,this.game.height),this.game.stage.addChild(this),this.camera.boot()},i.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},i.World.prototype.setBounds=function(t,e,i,s){this._definedSize=!0,this._width=i,this._height=s,this.bounds.setTo(t,e,i,s),this.x=t,this.y=e,this.camera.bounds&&this.camera.bounds.setTo(t,e,Math.max(i,this.game.width),Math.max(s,this.game.height)),this.game.physics.setBoundsToWorld()},i.World.prototype.resize=function(t,e){this._definedSize&&(tthis.bounds.right&&(t.x=this.bounds.left)),n&&(t.y+t._currentBounds.heightthis.bounds.bottom&&(t.y=this.bounds.top))):(s&&t.x+ethis.bounds.right&&(t.x=this.bounds.left-e),n&&t.y+ethis.bounds.bottom&&(t.y=this.bounds.top-e))},i.World.prototype.wrapAll=function(t,e,i,s,n,r){t.forEach(this.wrap,this,e,i,s,n,r)},Object.defineProperty(i.World.prototype,"width",{get:function(){return this.bounds.width},set:function(t){t1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.dropFrames?this.rendersThisFrame=0:(this.updateRender(this.time.slowMotion*this.time.desiredFps),this.rendersThisFrame=1);else{var e=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*e,this.time.elapsed),0);var i=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/e),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame)),this.forceSingleRender?this.rendersThisFrame=1:this.rendersThisFrame=Math.min(1,this.updatesThisFrame);this._deltaTime>=e&&(this._deltaTime-=e,this.currentUpdateID=i,this.updateLogic(this.time.desiredFpsMult),i++,!this.forceSingleUpdate||1!==i);)this.time.refresh();i>this._lastCount?this._spiraling++:i0&&this.updateRender(this._deltaTime/e)}}},updateLogic:function(t){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(t),this.debug.preUpdate(),this.input.pauseUpdate()):(this.stepping&&(this.pendingStep=!0),this.time.countUpdate(),this.scale.preUpdate(),this.debug.preUpdate(),this.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(t),this.plugins.preUpdate(t),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(),this.sound.update(),this.input.update(),this.physics.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate()),this.stage.updateTransform()},updateRender:function(t){this.lockRender||(this.time.countRender(),this.state.preRender(t),this.renderType!==i.HEADLESS&&(this.renderer.render(this.stage),this.plugins.render(t),this.state.render(t)),this.plugins.postRender(t))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.debug.destroy&&this.debug.destroy(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.plugins.destroy(),this.debug=null,this.state=null,this.sound=null,this.scale=null,this.stage=null,this.input=null,this.physics=null,this.plugins=null,this.cache=null,this.load=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),i.Canvas.removeFromDOM(this.canvas),PIXI.defaultRenderer=null,i.GAMES[this.id]=null},gamePaused:function(t){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.muteOnPause&&this.sound.setMute(),this.onPause.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(t){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.muteOnPause&&this.sound.unsetMute(),this.onResume.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(t){this.onBlur.dispatch(t),this.stage.disableVisibilityChange||this.gamePaused(t)},focusGain:function(t){this.onFocus.dispatch(t),this.stage.disableVisibilityChange||this.gameResumed(t)}},i.Game.prototype.constructor=i.Game,Object.defineProperty(i.Game.prototype,"paused",{get:function(){return this._paused},set:function(t){!0===t?(!1===this._paused&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),i.Input=function(t){this.game=t,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.customCandidateHandler=null,this.customCandidateHandlerContext=null,this.pollRate=0,this.enabled=!0,this.multiInputOverride=i.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.touchLockCallbacks=[],this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new i.ArraySet,this._localPoint=new i.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},i.Input.MOUSE_OVERRIDES_TOUCH=0,i.Input.TOUCH_OVERRIDES_MOUSE=1,i.Input.MOUSE_TOUCH_COMBINE=2,i.Input.MAX_POINTERS=10,i.Input.prototype={boot:function(){this.mousePointer=new i.Pointer(this.game,0,i.PointerMode.CURSOR),this.addPointer(),this.addPointer(),this.mouse=new i.Mouse(this.game),this.touch=new i.Touch(this.game),this.mspointer=new i.MSPointer(this.game),i.Keyboard&&(this.keyboard=new i.Keyboard(this.game)),i.Gamepad&&(this.gamepad=new i.Gamepad(this.game)),this.onDown=new i.Signal,this.onUp=new i.Signal,this.onTap=new i.Signal,this.onHold=new i.Signal,this.scale=new i.Point(1,1),this.speed=new i.Point,this.position=new i.Point,this._oldPosition=new i.Point,this.circle=new i.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=i.CanvasPool.create(this,1,1),this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.game.device.mspointer||this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var t=this;this._onClickTrampoline=function(e){t.onClickTrampoline(e)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],i.CanvasPool.remove(this),this.game.canvas.removeEventListener("click",this._onClickTrampoline)},setInteractiveCandidateHandler:function(t,e){this.customCandidateHandler=t,this.customCandidateHandlerContext=e},addMoveCallback:function(t,e){this.moveCallbacks.push({callback:t,context:e})},addTouchLockCallback:function(t,e,i){void 0===i&&(i=!1),this.touchLockCallbacks.push({callback:t,context:e,onEnd:i})},removeTouchLockCallback:function(t,e){for(var i=this.touchLockCallbacks.length;i--;)if(this.touchLockCallbacks[i].callback===t&&this.touchLockCallbacks[i].context===e)return this.touchLockCallbacks.splice(i,1),!0;return!1},executeTouchLockCallbacks:function(t,e){for(var i=this.touchLockCallbacks.length;i--;){var s=this.touchLockCallbacks[i];s.onEnd===t&&s.callback.call(s.context,this,e)&&this.touchLockCallbacks.splice(i,1)}},deleteMoveCallback:function(t,e){for(var i=this.moveCallbacks.length;i--;)if(this.moveCallbacks[i].callback===t&&this.moveCallbacks[i].context===e)return void this.moveCallbacks.splice(i,1)},addPointer:function(){if(this.pointers.length>=i.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+i.Input.MAX_POINTERS+" pointers reached."),null;var t=this.pointers.length+1,e=new i.Pointer(this.game,t,i.PointerMode.CONTACT);return this.pointers.push(e),this["pointer"+t]=e,e},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(t);if(!this.pointer2.active)return this.pointer2.start(t);for(var e=2;e0;i++)this.pointers[i].active&&e--;return t-e},getPointer:function(t){void 0===t&&(t=!1);for(var e=0;e=o&&this.game.camera.x+e.x=a&&this.game.camera.y+e.y=o&&this._localPoint.x=a&&this._localPoint.y=o&&this._localPoint.x=a&&this._localPoint.y0&&this._pollCounterthis.game.time.time},justReleased:function(t){return t=t||250,this.isUp&&this.timeUp+t>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},i.DeviceButton.prototype.constructor=i.DeviceButton,Object.defineProperty(i.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),i.Pointer=function(t,e,s){this.game=t,this.id=e,this.type=i.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.pointerMode=s||i.PointerMode.CURSOR|i.PointerMode.CONTACT,this.target=null,this.button=null,this.leftButton=new i.DeviceButton(this,i.Pointer.LEFT_BUTTON),this.middleButton=new i.DeviceButton(this,i.Pointer.MIDDLE_BUTTON),this.rightButton=new i.DeviceButton(this,i.Pointer.RIGHT_BUTTON),this.backButton=new i.DeviceButton(this,i.Pointer.BACK_BUTTON),this.forwardButton=new i.DeviceButton(this,i.Pointer.FORWARD_BUTTON),this.eraserButton=new i.DeviceButton(this,i.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===e,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.interactiveCandidates=[],this.active=!1,this.dirty=!1,this.position=new i.Point,this.positionDown=new i.Point,this.positionUp=new i.Point,this.circle=new i.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},i.Pointer.NO_BUTTON=0,i.Pointer.LEFT_BUTTON=1,i.Pointer.RIGHT_BUTTON=2,i.Pointer.MIDDLE_BUTTON=4,i.Pointer.BACK_BUTTON=8,i.Pointer.FORWARD_BUTTON=16,i.Pointer.ERASER_BUTTON=32,i.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.start(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.start(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.start(e),t===i.Mouse.BACK_BUTTON&&this.backButton.start(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.start(e)},processButtonsUp:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.stop(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.stop(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(e),t===i.Mouse.BACK_BUTTON&&this.backButton.stop(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(e)},processButtonsUpDown:function(t,e){var s="down"===e.type.toLowerCase().substr(-4),n="move"===e.type.toLowerCase().substr(-4);void 0!==t?(s&&1===t&&e.ctrlKey&&(t=2),this.leftButton.startStop(i.Pointer.LEFT_BUTTON&t,e),this.rightButton.startStop(i.Pointer.RIGHT_BUTTON&t,e),this.middleButton.startStop(i.Pointer.MIDDLE_BUTTON&t,e),this.backButton.startStop(i.Pointer.BACK_BUTTON&t,e),this.forwardButton.startStop(i.Pointer.FORWARD_BUTTON&t,e),this.eraserButton.startStop(i.Pointer.ERASER_BUTTON&t,e)):void 0!==e.button?s&&e.ctrlKey&&0===e.button?this.rightButton.start(e):s?this.processButtonsDown(e.button,e):n||this.processButtonsUp(e.button,e):s?e.ctrlKey?this.rightButton.start(e):this.leftButton.start(e):(this.leftButton.stop(e),this.rightButton.stop(e))},updateButtons:function(t){this.button=t.button,this.processButtonsUpDown(t.buttons,t),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(t){var e=this.game.input;return t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.isMouse?this.updateButtons(t):(this.isDown=!0,this.isUp=!1),this.active=!0,this.withinGame=!0,this.dirty=!1,this._history=[],this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(t,!0),this.positionDown.setTo(this.x,this.y),(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.x=this.x,e.y=this.y,e.position.setTo(this.x,this.y),e.onDown.dispatch(this,t),e.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){var t=this.game.input;this.active&&(this.dirty&&(t.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),!1===this._holdSent&&this.duration>=t.holdRate&&((t.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||t.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||t.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===t.totalActivePointers)&&t.onHold.dispatch(this),this._holdSent=!0),t.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+t.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>t.recordLimit&&this._history.shift()))},move:function(t,e){var s=this.game.input;if(!s.pollLocked){void 0===e&&(e=!1),void 0!==t.button&&(this.button=t.button),this.isMouse&&this.updateButtons(t),this.clientX=t.clientX,this.clientY=t.clientY,this.pageX=t.pageX,this.pageY=t.pageY,this.screenX=t.screenX,this.screenY=t.screenY,this.isMouse&&s.mouse.locked&&!e&&(this.rawMovementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.rawMovementY=t.movementY||t.mozMovementY||t.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*s.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*s.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(s.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||s.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||s.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===s.totalActivePointers)&&(s.activePointer=this,s.x=this.x,s.y=this.y,s.position.setTo(s.x,s.y),s.circle.x=s.x,s.circle.y=s.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY);for(var n=s.moveCallbacks.length;n--;)s.moveCallbacks[n].callback.call(s.moveCallbacks[n].context,this,this.x,this.y,e);return null===this.targetObject||this.game.paused&&!this.targetObject.noPause||!0!==this.targetObject.isDragged?s.interactiveItems.total>0&&this.processInteractiveObjects(e):!1===this.targetObject.update(this)&&(this.targetObject=null),this}},processInteractiveObjects:function(t){var e=0,i=-1,s=null,n=this.game.input.interactiveItems.first;for(this.interactiveCandidates=[];n;)n.checked=!1,!n.validForInput(i,e,!1)||this.game.paused&&!n.sprite.noPause||(n.checked=!0,(t&&n.checkPointerDown(this,!0)||!t&&n.checkPointerOver(this,!0))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n))),n=this.game.input.interactiveItems.next;for(n=this.game.input.interactiveItems.first;n;)!n.checked&&n.validForInput(i,e,!0)&&(t&&n.checkPointerDown(this,!1)||!t&&n.checkPointerOver(this,!1))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n)),n=this.game.input.interactiveItems.next;return this.game.input.customCandidateHandler&&(s=this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext,this,this.interactiveCandidates,s)),this.swapTarget(s,!1),null!==this.targetObject},swapTarget:function(t,e){void 0===e&&(e=!1),null===t?this.targetObject&&(this.targetObject._pointerOutHandler(this,e),this.targetObject=null):null===this.targetObject?(this.targetObject=t,t._pointerOverHandler(this,e)):this.targetObject===t?!1===t.update(this)&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this,e),this.targetObject=t,this.targetObject._pointerOverHandler(this,e))},leave:function(t){this.withinGame=!1,this.move(t,!1)},stop:function(t){var e=this.game.input;{if(!this._stateReset||!this.withinGame)return this.timeUp=this.game.time.time,(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.onUp.dispatch(this,t),this.duration>=0&&this.duration<=e.tapRate&&(this.timeUp-this.previousTapTime0&&(this.active=!1),this.withinGame=this.game.scale.bounds.contains(t.pageX,t.pageY),this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),!1===this.isMouse&&e.currentPointers--,e.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this;t.preventDefault()}},justPressed:function(t){return t=t||this.game.input.justPressedRate,!0===this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||this.game.input.justReleasedRate,this.isUp&&this.timeUp+t>this.game.time.time},addClickTrampoline:function(t,e,i,s){if(this.isDown){for(var n=this._clickTrampolines=this._clickTrampolines||[],r=0;rt||this.priorityID===t&&this.sprite.renderOrderID>e))},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(t){return t=t||0,this._pointerData[t].x},pointerY:function(t){return t=t||0,this._pointerData[t].y},pointerDown:function(t){return t=t||0,this._pointerData[t].isDown},pointerUp:function(t){return t=t||0,this._pointerData[t].isUp},pointerTimeDown:function(t){return t=t||0,this._pointerData[t].timeDown},pointerTimeUp:function(t){return t=t||0,this._pointerData[t].timeUp},pointerOver:function(t){if(!this.enabled)return!1;if(void 0===t){for(var e=0;e<10;e++)if(this._pointerData[e].isOver)return!0;return!1}return this._pointerData[t].isOver},pointerOut:function(t){if(!this.enabled)return!1;if(void 0!==t)return this._pointerData[t].isOut;for(var e=0;e<10;e++)if(this._pointerData[e].isOut)return!0},pointerTimeOver:function(t){return t=t||0,this._pointerData[t].timeOver},pointerTimeOut:function(t){return t=t||0,this._pointerData[t].timeOut},pointerDragged:function(t){return t=t||0,this._pointerData[t].isDragged},checkPointerDown:function(t,e){return!!(t.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectClick)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPointerOver:function(t,e){return!!(this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectOver)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPixel:function(t,e,i){if(this.sprite.texture.baseTexture.source){if(null===t&&null===e){this.game.input.getLocalPosition(this.sprite,i,this._tempPoint);var t=this._tempPoint.x,e=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(t-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(e-=-this.sprite.texture.frame.height*this.sprite.anchor.y),t+=this.sprite.texture.frame.x,e+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(t-=this.sprite.texture.trim.x,e-=this.sprite.texture.trim.y,tthis.sprite.texture.crop.right||ethis.sprite.texture.crop.bottom))return this._dx=t,this._dy=e,!1;if(this._dx=t,this._dy=e,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,t,e,1,1,0,0,1,1),this.game.input.hitContext.getImageData(0,0,1,1).data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(t){if(null!==this.sprite&&void 0!==this.sprite.parent)return this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this._pendingDrag?(this._dragDistancePass||(this._dragDistancePass=i.Math.distance(t.x,t.y,this.downPoint.x,this.downPoint.y)>=this.dragDistanceThreshold),this._dragDistancePass&&this._dragTimePass&&this.startDrag(t),!0):this.draggable&&this._draggedPointerID===t.id?this.updateDrag(t,!1):this._pointerData[t.id].isOver?this.checkPointerOver(t)?(this._pointerData[t.id].x=t.x-this.sprite.x,this._pointerData[t.id].y=t.y-this.sprite.y,!0):(this._pointerOutHandler(t),!1):void 0:(this._pointerOutHandler(t),!1)},_pointerOverHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];if(!1===i.isOver||t.dirty){var s=!1===i.isOver;i.isOver=!0,i.isOut=!1,i.timeOver=this.game.time.time,i.x=t.x-this.sprite.x,i.y=t.y-this.sprite.y,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),!e&&s&&this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,t),this.sprite.parent&&this.sprite.parent.onChildInputOver&&this.sprite.parent.onChildInputOver.dispatch(this.sprite,t)}}},_pointerOutHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];i.isOver=!1,i.isOut=!0,i.timeOut=this.game.time.time,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="",this._setHandCursor=!1),!e&&this.sprite&&this.sprite.events&&(this.sprite.events.onInputOut$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputOut&&this.sprite.parent.onChildInputOut.dispatch(this.sprite,t))}},_touchedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(!e.isDown&&e.isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,t))return;if(e.isDown=!0,e.isUp=!1,e.timeDown=this.game.time.time,this.downPoint.set(t.x,t.y),t.dirty=!0,this.sprite&&this.sprite.events&&(this.sprite.events.onInputDown$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputDown&&this.sprite.parent.onChildInputDown.dispatch(this.sprite,t),null===this.sprite))return;this.draggable&&!1===this.isDragged&&(0===this.dragTimeThreshold&&0===this.dragDistanceThreshold?this.startDrag(t):(this._pendingDrag=!0,this._dragDistancePass=0===this.dragDistanceThreshold,this.dragTimeThreshold>0?(this._dragTimePass=!1,this.game.time.events.add(this.dragTimeThreshold,this.dragTimeElapsed,this,t)):this._dragTimePass=!0)),this.bringToTop&&this.sprite.bringToTop()}}},dragTimeElapsed:function(t){this._dragTimePass=!0,this._pendingDrag&&this.sprite&&this._dragDistancePass&&this.startDrag(t)},_releasedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(e.isDown&&t.isUp){e.isDown=!1,e.isUp=!0,e.timeUp=this.game.time.time,e.downDuration=e.timeUp-e.timeDown;var i=this.checkPointerOver(t);this.sprite&&this.sprite.events&&(this.dragStopBlocksInputUp&&(!this.dragStopBlocksInputUp||this.draggable&&this.isDragged&&this._draggedPointerID===t.id)||this.sprite.events.onInputUp$dispatch(this.sprite,t,i),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputUp&&this.sprite.parent.onChildInputUp.dispatch(this.sprite,t,i),i&&(i=this.checkPointerOver(t))),e.isOver=i,!i&&this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),t.dirty=!0,this._pendingDrag=!1,this.draggable&&this.isDragged&&this._draggedPointerID===t.id&&this.stopDrag(t)}}},updateDrag:function(t,e){if(void 0===e&&(e=!1),t.isUp)return this.stopDrag(t),!1;var i=this.globalToLocal(t);if(this.sprite.fixedToCamera)var s=this.game.camera.scale.x*i.x+this._dragPoint.x+this.dragOffset.x,n=this.game.camera.scale.y*i.y+this._dragPoint.y+this.dragOffset.y;else var s=i.x+this._dragPoint.x+this.dragOffset.x,n=i.y+this._dragPoint.y+this.dragOffset.y;if(this.sprite.fixedToCamera)this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=s-this.game.camera.x),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=n-this.game.camera.y),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y));else{var r=this.game.camera.x-this._pointerData[t.id].camX,o=this.game.camera.y-this._pointerData[t.id].camY;this.allowHorizontalDrag&&(this.sprite.x=s+r),this.allowVerticalDrag&&(this.sprite.y=n+o),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.x,this.sprite.y))}return this.sprite.events.onDragUpdate.dispatch(this.sprite,t,s,n,this.snapPoint,e),!0},justOver:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOver&&this.overDuration(t)this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.ythis.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.leftthis.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.xthis.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.ythis.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.leftthis.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},i.InputHandler.prototype.constructor=i.InputHandler,i.Gamepad=function(t){this.game=t,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!==navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this)]},i.Gamepad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},start:function(){if(!this._active){this._active=!0;var t=this;this._onGamepadConnected=function(e){return t.onGamepadConnected(e)},this._onGamepadDisconnected=function(e){return t.onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(t){var e=t.gamepad;this._rawPads.push(e),this._gamepads[e.index].connect(e)},onGamepadDisconnected:function(t){var e=t.gamepad;for(var i in this._rawPads)this._rawPads[i].index===e.index&&this._rawPads.splice(i,1);this._gamepads[e.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(this._active){if(navigator.getGamepads)t=navigator.getGamepads();else if(navigator.webkitGetGamepads)t=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var t=navigator.webkitGamepads();if(t){this._rawPads=[];for(var e=!1,i=0;i0&&s>this.deadZone||s<0&&s<-this.deadZone?this.processAxisChange(i,s):this.processAxisChange(i,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(t){var e=!this.connected;this.connected=!0,this.index=t.index,this._rawPad=t,this._buttons=[],this._buttonsLen=t.buttons.length,this._axes=[],this._axesLen=t.axes.length;for(var s=0;sthis.maxHealth&&(this.health=this.maxHealth),this},heal:function(t){return this.alive&&(this.health+=t,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},i.Component.InCamera=function(){},i.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},i.Component.InputEnabled=function(){},i.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(t){t?null===this.input?(this.input=new i.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},i.Component.InWorld=function(){},i.Component.InWorld.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(this.autoCull||this.checkWorldBounds){if(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull)if(this.game.world.camera.view.intersects(this._bounds))this.renderable=!0,this.game.world.camera.totalInView++;else if(this.renderable=!1,this.outOfCameraBoundsKill)return this.kill(),!1;if(this.checkWorldBounds)if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1}return!0},i.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,outOfCameraBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},i.Component.LifeSpan=function(){},i.Component.LifeSpan.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):!(this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0))||(this.kill(),!1)},i.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(t){return void 0===t&&(t=100),this.alive=!0,this.exists=!0,this.visible=!0,"function"==typeof this.setHealth&&this.setHealth(t),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},i.Component.LoadTexture=function(){},i.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(t,e,s){t===i.PENDING_ATLAS?(t=e,e=0):e=e||0,(s||void 0===s)&&this.animations&&this.animations.stop(),this.key=t,this.customRender=!1;var n=this.game.cache,r=!0,o=!this.texture.baseTexture.scaleMode;if(i.RenderTexture&&t instanceof i.RenderTexture)this.key=t.key,this.setTexture(t);else if(i.BitmapData&&t instanceof i.BitmapData)this.customRender=!0,this.setTexture(t.texture),r=n.hasFrameData(t.key,i.Cache.BITMAPDATA)?!this.animations.loadFrameData(n.getFrameData(t.key,i.Cache.BITMAPDATA),e):!this.animations.loadFrameData(t.frameData,0);else if(i.Video&&t instanceof i.Video){this.customRender=!0;var a=t.texture.valid;this.setTexture(t.texture),this.setFrame(t.texture.frame.clone()),t.onChangeSource.add(this.resizeFrame,this),this.texture.valid=a}else if(i.Tilemap&&t instanceof i.TilemapLayer)this.setTexture(PIXI.Texture.fromCanvas(t.canvas));else if(t instanceof PIXI.Texture)this.setTexture(t);else{var h=n.getImage(t,!0);this.key=h.key,this.setTexture(new PIXI.Texture(h.base)),this.texture.baseTexture.skipRender="__default"===t,r=!this.animations.loadFrameData(h.frameData,e)}r&&(this._frame=i.Rectangle.clone(this.texture.frame)),o||(this.texture.baseTexture.scaleMode=1)},setFrame:function(t){this._frame=t,this.texture.frame.x=t.x,this.texture.frame.y=t.y,this.texture.frame.width=t.width,this.texture.frame.height=t.height,this.texture.crop.x=t.x,this.texture.crop.y=t.y,this.texture.crop.width=t.width,this.texture.crop.height=t.height,t.trimmed?(this.texture.trim?(this.texture.trim.x=t.spriteSourceSizeX,this.texture.trim.y=t.spriteSourceSizeY,this.texture.trim.width=t.sourceSizeW,this.texture.trim.height=t.sourceSizeH):this.texture.trim={x:t.spriteSourceSizeX,y:t.spriteSourceSizeY,width:t.sourceSizeW,height:t.sourceSizeH},this.texture.width=t.sourceSizeW,this.texture.height=t.sourceSizeH,this.texture.frame.width=t.sourceSizeW,this.texture.frame.height=t.sourceSizeH):!t.trimmed&&this.texture.trim&&(this.texture.trim=null),t.rotated&&(this.texture.rotated=!0),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(t,e,i){this.texture.frame.resize(e,i),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(t){this.animations.frame=t}},frameName:{get:function(){return this.animations.frameName},set:function(t){this.animations.frameName=t}}},i.Component.Overlap=function(){},i.Component.Overlap.prototype={overlap:function(t){return i.Rectangle.intersects(this.getBounds(),t.getBounds())}},i.Component.PhysicsBody=function(){},i.Component.PhysicsBody.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):this.fresh&&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.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,this.preUpdateChildren(),!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!(!this._exists||!this.parent.exists)||(this.renderOrderID=-1,!1))},i.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},i.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(t){this.position.x=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},i.Component.Reset=function(){},i.Component.Reset.prototype.reset=function(t,e,i){return void 0===i&&(i=1),this.world.set(t,e),this.position.set(t,e),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=i),this.components.PhysicsBody&&this.body&&this.body.reset(t,e,!1,!1),this},i.Component.ScaleMinMax=function(){},i.Component.ScaleMinMax.prototype={transformCallback:null,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(t){this.scaleMin&&(t.athis.scaleMax.x&&(t.a=this.scaleMax.x),t.d>this.scaleMax.y&&(t.d=this.scaleMax.y))},setScaleMinMax:function(t,e,s,n){void 0===e?e=s=n=t:void 0===s&&(s=n=e,e=t),null===t?this.scaleMin=null:this.scaleMin?this.scaleMin.set(t,e):this.scaleMin=new i.Point(t,e),null===s?this.scaleMax=null:this.scaleMax?this.scaleMax.set(s,n):this.scaleMax=new i.Point(s,n),null===this.scaleMin?this.transformCallback=null:(this.transformCallback=this.checkTransform,this.transformCallbackContext=this)}},i.Component.Smoothed=function(){},i.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(t){t?this.texture&&(this.texture.baseTexture.scaleMode=0,this.texture.baseTexture.dirty()):this.texture&&(this.texture.baseTexture.scaleMode=1,this.texture.baseTexture.dirty())}}},i.GameObjectFactory=function(t){this.game=t,this.world=this.game.world},i.GameObjectFactory.prototype={existing:function(t){return this.world.add(t)},weapon:function(t,e,s,n,r){var o=this.game.plugins.add(i.Weapon);return r&&(o.bulletClass=r),o.createBullets(t,e,s,n),o},image:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Image(this.game,t,e,s,n))},sprite:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Sprite(this.game,t,e,s,n))},creature:function(t,e,s,n,r){void 0===r&&(r=this.world);var o=new i.Creature(this.game,t,e,s,n);return r.add(o),o},tween:function(t){return this.game.tweens.create(t)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},physicsGroup:function(t,e,s,n){return new i.Group(this.game,e,s,n,!0,t)},spriteBatch:function(t,e,s){return void 0===t&&(t=null),void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},tileSprite:function(t,e,s,n,r,o,a){return void 0===a&&(a=this.world),a.add(new i.TileSprite(this.game,t,e,s,n,r,o))},rope:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.Rope(this.game,t,e,s,n,r))},text:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Text(this.game,t,e,s,n))},button:function(t,e,s,n,r,o,a,h,l,c){return void 0===c&&(c=this.world),c.add(new i.Button(this.game,t,e,s,n,r,o,a,h,l))},graphics:function(t,e,s){return void 0===s&&(s=this.world),s.add(new i.Graphics(this.game,t,e))},emitter:function(t,e,s){return this.game.particles.add(new i.Particles.Arcade.Emitter(this.game,t,e,s))},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.BitmapText(this.game,t,e,s,n,r))},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},video:function(t,e){return new i.Video(this.game,t,e)},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t},plugin:function(t){return this.game.plugins.add(t)}},i.GameObjectFactory.prototype.constructor=i.GameObjectFactory,i.GameObjectCreator=function(t){this.game=t,this.world=this.game.world},i.GameObjectCreator.prototype={image:function(t,e,s,n){return new i.Image(this.game,t,e,s,n)},sprite:function(t,e,s,n){return new i.Sprite(this.game,t,e,s,n)},tween:function(t){return new i.Tween(t,this.game,this.game.tweens)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},spriteBatch:function(t,e,s){return void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},tileSprite:function(t,e,s,n,r,o){return new i.TileSprite(this.game,t,e,s,n,r,o)},rope:function(t,e,s,n,r){return new i.Rope(this.game,t,e,s,n,r)},text:function(t,e,s,n){return new i.Text(this.game,t,e,s,n)},button:function(t,e,s,n,r,o,a,h,l){return new i.Button(this.game,t,e,s,n,r,o,a,h,l)},graphics:function(t,e){return new i.Graphics(this.game,t,e)},emitter:function(t,e,s){return new i.Particles.Arcade.Emitter(this.game,t,e,s)},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return new i.BitmapText(this.game,t,e,s,n,r,o)},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t}},i.GameObjectCreator.prototype.constructor=i.GameObjectCreator,i.Sprite=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.SPRITE,this.physicsType=i.SPRITE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Sprite.prototype=Object.create(PIXI.Sprite.prototype),i.Sprite.prototype.constructor=i.Sprite,i.Component.Core.install.call(i.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Sprite.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Sprite.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Sprite.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Sprite.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Sprite.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Image=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.IMAGE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Image.prototype=Object.create(PIXI.Sprite.prototype),i.Image.prototype.constructor=i.Image,i.Component.Core.install.call(i.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","ScaleMinMax","Smoothed"]),i.Image.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Image.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Image.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Image.prototype.preUpdate=function(){return!(!this.preUpdateInWorld()||!this.preUpdateLifeSpan())&&this.preUpdateCore()},i.Button=function(t,e,s,n,r,o,a,h,l,c){e=e||0,s=s||0,n=n||null,r=r||null,o=o||this,i.Image.call(this,t,e,s,n,h),this.type=i.BUTTON,this.physicsType=i.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new i.Signal,this.onInputOut=new i.Signal,this.onInputDown=new i.Signal,this.onInputUp=new i.Signal,this.onOverMouseOnly=!0,this.justReleasedPreventsOver=i.PointerMode.CONTACT,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(a,h,l,c),null!==r&&this.onInputUp.add(r,o),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this)},i.Button.prototype=Object.create(i.Image.prototype),i.Button.prototype.constructor=i.Button;return i.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},i.Button.prototype.setStateFrame=function(t,e,i){var s="_on"+t+"Frame";null!==e?(this[s]=e,i&&this.changeStateFrame(t)):this[s]=null},i.Button.prototype.changeStateFrame=function(t){if(this.freezeFrames)return!1;var e=this["_on"+t+"Frame"];return"string"==typeof e?(this.frameName=e,!0):"number"==typeof e&&(this.frame=e,!0)},i.Button.prototype.setFrames=function(t,e,i,s){this.setStateFrame("Over",t,this.input.pointerOver()),this.setStateFrame("Out",e,!this.input.pointerOver()),this.setStateFrame("Down",i,this.input.pointerDown()),this.setStateFrame("Up",s,this.input.pointerUp())},i.Button.prototype.setStateSound=function(t,e,s){var n="on"+t+"Sound",r="on"+t+"SoundMarker";e instanceof i.Sound||e instanceof i.AudioSprite?(this[n]=e,this[r]="string"==typeof s?s:""):(this[n]=null,this[r]="")},i.Button.prototype.playStateSound=function(t){var e=this["on"+t+"Sound"];if(e){var i=this["on"+t+"SoundMarker"];return e.play(i),!0}return!1},i.Button.prototype.setSounds=function(t,e,i,s,n,r,o,a){this.setStateSound("Over",t,e),this.setStateSound("Out",n,r),this.setStateSound("Down",i,s),this.setStateSound("Up",o,a)},i.Button.prototype.setOverSound=function(t,e){this.setStateSound("Over",t,e)},i.Button.prototype.setOutSound=function(t,e){this.setStateSound("Out",t,e)},i.Button.prototype.setDownSound=function(t,e){this.setStateSound("Down",t,e)},i.Button.prototype.setUpSound=function(t,e){this.setStateSound("Up",t,e)},i.Button.prototype.onInputOverHandler=function(t,e){e.justReleased()&&(this.justReleasedPreventsOver&e.pointerMode)===e.pointerMode||(this.changeStateFrame("Over"),this.onOverMouseOnly&&!e.isMouse||(this.playStateSound("Over"),this.onInputOver&&this.onInputOver.dispatch(this,e)))},i.Button.prototype.onInputOutHandler=function(t,e){this.changeStateFrame("Out"),this.playStateSound("Out"),this.onInputOut&&this.onInputOut.dispatch(this,e)},i.Button.prototype.onInputDownHandler=function(t,e){this.changeStateFrame("Down"),this.playStateSound("Down"),this.onInputDown&&this.onInputDown.dispatch(this,e)},i.Button.prototype.onInputUpHandler=function(t,e,i){this.playStateSound("Up"),this.onInputUp&&this.onInputUp.dispatch(this,e,i),this.freezeFrames||(!0===this.forceOut||(this.forceOut&e.pointerMode)===e.pointerMode?this.changeStateFrame("Out"):this.changeStateFrame("Up")||(i?this.changeStateFrame("Over"):this.changeStateFrame("Out")))},i.SpriteBatch=function(t,e,s,n){void 0!==e&&null!==e||(e=t.world),i.Group.call(this,t,e,s,n),this.type=i.SPRITEBATCH,this.fastSpriteBatch=null,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.Group.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||(this.fastSpriteBatch=new PIXI.WebGLFastSpriteBatch(t.gl),this.ready=!0),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n=0&&t<=this.width&&e>=0&&e<=this.height&&(i.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|n<<8|s:this.pixels[e*this.width+t]=s<<24|n<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,s){s||(s=i.Color.createColor());var n=~~(t+e*this.width);return n*=4,s.r=this.data[n],s.g=this.data[++n],s.b=this.data[++n],s.a=this.data[++n],s},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,s,n,r){return i.Color.unpackPixel(this.getPixel32(t,e),s,n,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=i.Color.createColor(),s=0,n=0,r=1,o=!1;1===t?(r=-1,n=this.height):3===t&&(r=-1,s=this.width);do{i.Color.unpackPixel(this.getPixel32(s,n),e),0===t||1===t?++s===this.width&&(s=0,((n+=r)>=this.height||n<=0)&&(o=!0)):2!==t&&3!==t||++n===this.height&&(n=0,((s+=r)>=this.width||s<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=s,e.y=n,e},getBounds:function(t){return void 0===t&&(t=new i.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,s,n,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),t instanceof i.RenderTexture&&(t=t.getCanvas()),this._image=t,t instanceof i.Sprite||t instanceof i.Image||t instanceof i.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof i.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==s&&null!==s||(s=0),n&&(this._size.x=n),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=s),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+s,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var n=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===n.a||0===n.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=n.tx,o=n.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),s&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(n.a,n.b,n.c,n.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,s){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,s),t.type===i.GROUP&&t.exists)this.drawGroup(t,e,s);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var n=0;ne.width&&(n=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,s),this._circle=new i.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,n,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),i.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this},copyBitmapData:function(t,e,i){t.update();for(var s,n=0;n80*s){h=c=t[0],l=u=t[1];for(var g=s;gc&&(c=d),p>u&&(u=p);f=Math.max(c-h,u-l)}return i.EarCut.earcutLinked(o,a,s,h,l,f),a},i.EarCut.linkedList=function(t,e,s,n,r){var o,a,h,l=0;for(o=e,a=s-n;o0)for(o=e;o=e;o-=n)h=i.EarCut.insertNode(o,t[o],t[o+1],h);return h},i.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var s,n=t;do{if(s=!1,n.steiner||!i.EarCut.equals(n,n.next)&&0!==i.EarCut.area(n.prev,n,n.next))n=n.next;else{if(i.EarCut.removeNode(n),(n=e=n.prev)===n.next)return null;s=!0}}while(s||n!==e);return e},i.EarCut.earcutLinked=function(t,e,s,n,r,o,a){if(t){!a&&o&&i.EarCut.indexCurve(t,n,r,o);for(var h,l,c=t;t.prev!==t.next;)if(h=t.prev,l=t.next,o?i.EarCut.isEarHashed(t,n,r,o):i.EarCut.isEar(t))e.push(h.i/s),e.push(t.i/s),e.push(l.i/s),i.EarCut.removeNode(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?(t=i.EarCut.cureLocalIntersections(t,e,s),i.EarCut.earcutLinked(t,e,s,n,r,o,2)):2===a&&i.EarCut.splitEarcut(t,e,s,n,r,o):i.EarCut.earcutLinked(i.EarCut.filterPoints(t),e,s,n,r,o,1);break}}},i.EarCut.isEar=function(t){var e=t.prev,s=t,n=t.next;if(i.EarCut.area(e,s,n)>=0)return!1;for(var r=t.next.next;r!==t.prev;){if(i.EarCut.pointInTriangle(e.x,e.y,s.x,s.y,n.x,n.y,r.x,r.y)&&i.EarCut.area(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},i.EarCut.isEarHashed=function(t,e,s,n){var r=t.prev,o=t,a=t.next;if(i.EarCut.area(r,o,a)>=0)return!1;for(var h=r.xo.x?r.x>a.x?r.x:a.x:o.x>a.x?o.x:a.x,u=r.y>o.y?r.y>a.y?r.y:a.y:o.y>a.y?o.y:a.y,d=i.EarCut.zOrder(h,l,e,s,n),p=i.EarCut.zOrder(c,u,e,s,n),f=t.nextZ;f&&f.z<=p;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=d;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0},i.EarCut.cureLocalIntersections=function(t,e,s){var n=t;do{var r=n.prev,o=n.next.next;i.EarCut.intersects(r,n,n.next,o)&&i.EarCut.locallyInside(r,o)&&i.EarCut.locallyInside(o,r)&&(e.push(r.i/s),e.push(n.i/s),e.push(o.i/s),i.EarCut.removeNode(n),i.EarCut.removeNode(n.next),n=t=o),n=n.next}while(n!==t);return n},i.EarCut.splitEarcut=function(t,e,s,n,r,o){var a=t;do{for(var h=a.next.next;h!==a.prev;){if(a.i!==h.i&&i.EarCut.isValidDiagonal(a,h)){var l=i.EarCut.splitPolygon(a,h);return a=i.EarCut.filterPoints(a,a.next),l=i.EarCut.filterPoints(l,l.next),i.EarCut.earcutLinked(a,e,s,n,r,o),void i.EarCut.earcutLinked(l,e,s,n,r,o)}h=h.next}a=a.next}while(a!==t)},i.EarCut.eliminateHoles=function(t,e,s,n){var r,o,a,h,l,c=[];for(r=0,o=e.length;r=n.next.y){var h=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);h<=r&&h>a&&(a=h,s=n.x=n.x&&n.x>=s.x&&i.EarCut.pointInTriangle(os.x)&&i.EarCut.locallyInside(n,t)&&(s=n,u=l),n=n.next;return s},i.EarCut.indexCurve=function(t,e,s,n){var r=t;do{null===r.z&&(r.z=i.EarCut.zOrder(r.x,r.y,e,s,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,i.EarCut.sortLinked(r)},i.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},i.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},i.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},i.EarCut.isValidDiagonal=function(t,e){return i.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!i.EarCut.intersectsPolygon(t,e)&&i.EarCut.locallyInside(t,e)&&i.EarCut.locallyInside(e,t)&&i.EarCut.middleInside(t,e)},i.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},i.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},i.EarCut.intersects=function(t,e,s,n){return i.EarCut.area(t,e,s)>0!=i.EarCut.area(t,e,n)>0&&i.EarCut.area(s,n,t)>0!=i.EarCut.area(s,n,e)>0},i.EarCut.intersectsPolygon=function(t,e){var s=t;do{if(s.i!==t.i&&s.next.i!==t.i&&s.i!==e.i&&s.next.i!==e.i&&i.EarCut.intersects(s,s.next,t,e))return!0;s=s.next}while(s!==t);return!1},i.EarCut.locallyInside=function(t,e){return i.EarCut.area(t.prev,t,t.next)<0?i.EarCut.area(t,e,t.next)>=0&&i.EarCut.area(t,t.prev,e)>=0:i.EarCut.area(t,e,t.prev)<0||i.EarCut.area(t,t.next,e)<0},i.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},i.EarCut.splitPolygon=function(t,e){var s=new i.EarCut.Node(t.i,t.x,t.y),n=new i.EarCut.Node(e.i,e.x,e.y),r=t.next,o=e.prev;return t.next=e,e.prev=t,s.next=r,r.prev=s,n.next=s,s.prev=n,o.next=n,n.prev=o,n},i.EarCut.insertNode=function(t,e,s,n){var r=new i.EarCut.Node(t,e,s);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r},i.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},i.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var s,n=e.gl,r=e.projection,o=e.offset,a=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,n);var h=t._webGL[n.id];if(h)for(var l=0;l=PIXI.WebGLGraphics.stencilBufferLimit&&(a.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit?(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildPoly(a,o)||(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))),a.lineWidth>0&&(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildLine(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,0),a.type===i.RECTANGLE?PIXI.WebGLGraphics.buildRectangle(a,o):a.type===i.CIRCLE||a.type===i.ELLIPSE?PIXI.WebGLGraphics.buildCircle(a,o):a.type===i.ROUNDEDRECTANGLE&&PIXI.WebGLGraphics.buildRoundedRectangle(a,o)),s.lastIndex++}for(n=0;n19600?(_=y-x,w=v-b,_/=R=Math.sqrt(_*_+w*w),w/=R,_*=F,w*=F,L.push(p-_,f-w),L.push(G,N,X,U),L.push(p+_,f+w),L.push(G,N,X,U),L.push(p-_,f-w),L.push(G,N,X,U),O++):(L.push(l,c),L.push(G,N,X,U),L.push(p-(l-p),f-(c-f)),L.push(G,N,X,U));for(u=n[2*(I-2)],d=n[2*(I-2)+1],p=n[2*(I-1)],y=-(d-(f=n[2*(I-1)+1])),v=u-p,y/=R=Math.sqrt(y*y+v*v),v/=R,y*=F,v*=F,L.push(p-y,f-v),L.push(G,N,X,U),L.push(p+y,f+v),L.push(G,N,X,U),B.push(k),s=0;sh?r:h,l=oc?o:c;s.push(a,l,h,l,h,c,a,c);var d=s.length/2;for(u=0;uS?S:C,e.beginPath(),e.moveTo(_,w+C),e.lineTo(_,w+P-C),e.quadraticCurveTo(_,w+P,_+C,w+P),e.lineTo(_+T-C,w+P),e.quadraticCurveTo(_+T,w+P,_+T,w+P-C),e.lineTo(_+T,w+C),e.quadraticCurveTo(_+T,w,_+T-C,w),e.lineTo(_+C,w),e.quadraticCurveTo(_,w,_,w+C),e.closePath(),(r.fillColor||0===r.fillColor)&&(e.globalAlpha=r.fillAlpha*s,e.fillStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.fill()),r.lineWidth&&(e.globalAlpha=r.lineAlpha*s,e.strokeStyle="#"+("00000"+(0|h).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var s=t.graphicsData.length;if(0!==s){e.beginPath();for(var n=0;nP?P:T,e.moveTo(x,b+T),e.lineTo(x,b+w-T),e.quadraticCurveTo(x,b+w,x+T,b+w),e.lineTo(x+_-T,b+w),e.quadraticCurveTo(x+_,b+w,x+_,b+w-T),e.lineTo(x+_,b+T),e.quadraticCurveTo(x+_,b,x+_-T,b),e.lineTo(x+T,b),e.quadraticCurveTo(x,b,x,b+T),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},i.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},i.GraphicsData.prototype.constructor=i.GraphicsData,i.GraphicsData.prototype.clone=function(){return new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},i.Graphics=function(t,e,s){void 0===e&&(e=0),void 0===s&&(s=0),this.type=i.GRAPHICS,this.physicsType=i.SPRITE,this.anchor=new i.Point,PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new i.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1,i.Component.Core.init.call(this,t,e,s,"",null)},i.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Graphics.prototype.constructor=i.Graphics,i.Component.Core.install.call(i.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),i.Graphics.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Graphics.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Graphics.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Graphics.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Graphics.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Graphics.prototype.postUpdate=function(){i.Component.PhysicsBody.postUpdate.call(this),i.Component.FixedToCamera.postUpdate.call(this),this._boundsDirty&&(this.updateLocalBounds(),this._boundsDirty=!1);for(var t=0;t0&&this.drawPolygon(s)}else this.drawPolygon(s)},i.Graphics.prototype.drawTriangles=function(t,e,s){void 0===s&&(s=!1);var n,r=new i.Point,o=new i.Point,a=new i.Point,h=[];if(e)if(t[0]instanceof i.Point)for(n=0;nc*a)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var x=d+s+p*(v+y*v),b=Math.cos(x),_=-Math.sin(x);u.push((f*b+g*_)*i+t,(f*-_+g*b)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},i.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},i.Graphics.prototype.drawRect=function(t,e,s,n){return this.drawShape(new i.Rectangle(t,e,s,n)),this},i.Graphics.prototype.drawRoundedRect=function(t,e,s,n,r){return this.drawShape(new i.RoundedRectangle(t,e,s,n,r)),this},i.Graphics.prototype.drawCircle=function(t,e,s){return this.drawShape(new i.Circle(t,e,s)),this},i.Graphics.prototype.drawEllipse=function(t,e,s,n){return this.drawShape(new i.Ellipse(t,e,s,n)),this},i.Graphics.prototype.drawPolygon=function(t){t instanceof i.Polygon&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var s=0;sw?m:w,w=v>w?v:w,w=b>w?b:w,T=y>T?y:T,T=x>T?x:T,T=_>T?_:T,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=C,this._bounds.height=T-C,this._currentBounds=this._bounds,this._currentBounds},i.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;ee?a+l:e,s=hn?h+c:n;else if(p===i.CIRCLE)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else if(p===i.ELLIPSE)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else{o=r.points;for(var g=0;ge?a+f:e,s=h-fn?h+f:n}}else t=0,e=0,s=0,n=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=s-m,this._localBounds.height=n-s+2*m},i.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},i.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},i.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},i.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof i.Polygon&&(t=t.clone()).flatten();var e=new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===i.POLYGON&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(i.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),i.RenderTexture=function(t,e,s,n,r,o,a,h){if(void 0===e&&(e=100),void 0===s&&(s=100),void 0===n&&(n=""),void 0===r&&(r=i.scaleModes.DEFAULT),void 0===o&&(o=1),void 0===a&&(a=PIXI.defaultRenderer),void 0===h&&(h=0),this.game=t,this.key=n,this.type=i.RENDERTEXTURE,this._tempMatrix=new i.Matrix,this.width=e,this.height=s,this.resolution=o,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=this.frame.clone(),this.baseTexture=new PIXI.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=r,this.baseTexture.hasLoaded=!0,PIXI.Texture.call(this,this.baseTexture,this.frame.clone()),this.renderer=a,this.renderer.type===i.WEBGL){var l=this.renderer.gl;this.baseTexture.textureIndex=h,this.baseTexture._dirty[l.id]=!1,this.textureBuffer=new PIXI.FilterTexture(l,this.width,this.height,this.baseTexture.scaleMode,h),this.baseTexture._glTextures[l.id]=this.textureBuffer.texture,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.textureBuffer=new PIXI.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new i.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(PIXI.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.renderXY=function(t,e,s,n){t.updateTransform(),this._tempMatrix.copyFrom(t.worldTransform),this._tempMatrix.tx=e,this._tempMatrix.ty=s,this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.renderRawXY=function(t,e,s,n){this._tempMatrix.identity().translate(e,s),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.render=function(t,e,s){void 0===e||null===e?this._tempMatrix.copyFrom(t.worldTransform):this._tempMatrix.copyFrom(e),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,s):this._renderCanvas(t,this._tempMatrix,s)},i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype._renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n-1&&this.characterLimitSize0&&this.style.maxLines0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(e[a]):l+=this.context.measureText(e[a]).width,this.style.wordWrap&&(l-=this.context.measureText(" ").width)}else{var h=e[a].split(/(?:\t)/),l=this.padding.x+this.style.strokeThickness;if(Array.isArray(i))for(var c=0,u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.measureLine(h[u]):Math.ceil(this.context.measureText(h[u]).width),u>0&&(c+=i[u-1]),l=c+d}else for(u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(h[u]):l+=Math.ceil(this.context.measureText(h[u]).width),l+=this.game.math.snapToCeil(l,i)-l}s[a]=Math.ceil(l),n=Math.max(n,s[a])}this.canvas.width=n*this._res;var p=r.fontSize+this.style.strokeThickness+this.padding.y,f=p*o,g=this._lineSpacing;g<0&&Math.abs(g)>p&&(g=-p),0!==g&&(f+=g>0?g*e.length:g*(e.length-1)),this.canvas.height=f*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var m,y;for(this._charCount=0,a=0;a0&&(y+=g*a),"right"===this.style.align?m+=n-s[a]:"center"===this.style.align&&(m+=(n-s[a])/2),this.autoRound&&(m=Math.round(m),y=Math.round(y)),this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.updateLine(e[a],m,y):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===i?this.context.strokeText(e[a],m,y):this.renderTabLine(e[a],m,y,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===i?this.context.fillText(e[a],m,y):this.renderTabLine(e[a],m,y,!0)));this.updateTexture(),this.dirty=!1},i.Text.prototype.renderTabLine=function(t,e,i,s){var n=t.split(/(?:\t)/),r=this.style.tabs,o=0;if(Array.isArray(r))for(var a=0,h=0;h0&&(a+=r[h-1]),o=e+a,s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i);else for(h=0;h0||this.fontStyles.length>0){var n=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(n.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(n.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(n)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill)),e+=this.context.measureText(s).width,this._charCount++}return Math.ceil(e)},i.Text.prototype.updateLine=function(t,e,i){for(var s=0;s0||this.fontStyles.length>0){var r=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(r.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(r.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(r)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(n,e,i)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(n,e,i)),e+=this.context.measureText(n).width,this._charCount++}},i.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},i.Text.prototype.clearFontValues=function(){return this.fontStyles=[],this.fontWeights=[],this.dirty=!0,this},i.Text.prototype.addColor=function(t,e){return this.colors[e]=t,this.dirty=!0,this},i.Text.prototype.addStrokeColor=function(t,e){return this.strokeColors[e]=t,this.dirty=!0,this},i.Text.prototype.addFontStyle=function(t,e){return this.fontStyles[e]=t,this.dirty=!0,this},i.Text.prototype.addFontWeight=function(t,e){return this.fontWeights[e]=t,this.dirty=!0,this},i.Text.prototype.precalculateWordWrap=function(t){return this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font,this.runWordWrap(t).split(/(?:\r\n|\r|\n)/)},i.Text.prototype.runWordWrap=function(t){return this.useAdvancedWrap?this.advancedWordWrap(t):this.basicWordWrap(t)},i.Text.prototype.advancedWordWrap=function(t){for(var e=this.context,i=this.style.wordWrapWidth,s="",n=t.replace(/ +/gi," ").split(/\r?\n/gi),r=n.length,o=0;ol){if(0===u){for(var g=p;g.length&&(g=g.slice(0,-1),!((f=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var m=d.substr(g.length);c[u]=m,h+=g}var y=c[u].length?u:u+1,v=c.slice(y).join(" ").replace(/[ \n]*$/gi,"");n[o+1]=v+" "+(n[o+1]||""),r=n.length;break}h+=p,l-=f}s+=h.replace(/[ \n]*$/gi,"")+"\n"}}return s=s.replace(/[\s|\n]*$/gi,"")},i.Text.prototype.basicWordWrap=function(t){for(var e="",i=t.split("\n"),s=0;sn?(o>0&&(e+="\n"),e+=r[o]+" ",n=this.style.wordWrapWidth-a):(n-=h,e+=r[o]+" ")}ss&&(this.style.wordWrapWidth=s)),this.updateTexture(),this},i.Text.prototype.updateTexture=function(){var t=this.texture.baseTexture,e=this.texture.crop,i=this.texture.frame,s=this.canvas.width,n=this.canvas.height;if(t.width=s,t.height=n,e.width=s,e.height=n,i.width=s,i.height=n,this.texture.width=s,this.texture.height=n,this._width=s,this._height=n,this.textBounds){var r=this.textBounds.x,o=this.textBounds.y;"right"===this.style.boundsAlignH?r+=this.textBounds.width-this.canvas.width/this.resolution:"center"===this.style.boundsAlignH&&(r+=this.textBounds.halfWidth-this.canvas.width/this.resolution/2),"bottom"===this.style.boundsAlignV?o+=this.textBounds.height-this.canvas.height/this.resolution:"middle"===this.style.boundsAlignV&&(o+=this.textBounds.halfHeight-this.canvas.height/this.resolution/2),this.pivot.x=-r,this.pivot.y=-o}this.renderable=0!==s&&0!==n,this.texture.requiresReTint=!0,this.texture.baseTexture.dirty()},i.Text.prototype._renderWebGL=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.Text.prototype._renderCanvas=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.Text.prototype.determineFontProperties=function(t){var e=i.Text.fontPropertiesCache[t];if(!e){e={};var s=i.Text.fontPropertiesCanvas,n=i.Text.fontPropertiesContext;n.font=t;var r=Math.ceil(n.measureText("|MÉq").width),o=Math.ceil(n.measureText("|MÉq").width),a=2*o;if(o=1.4*o|0,s.width=r,s.height=a,n.fillStyle="#f00",n.fillRect(0,0,r,a),n.font=t,n.textBaseline="alphabetic",n.fillStyle="#000",n.fillText("|MÉq",0,o),!n.getImageData(0,0,r,a))return e.ascent=o,e.descent=o+6,e.fontSize=e.ascent+e.descent,i.Text.fontPropertiesCache[t]=e,e;var h,l,c=n.getImageData(0,0,r,a).data,u=c.length,d=4*r,p=0,f=!1;for(h=0;ho;h--){for(l=0;l0?this._maxWidth:null,l=[],c=0;c=h&&r>-1)return{width:o||n,text:i.substr(0,c-(c-r)),end:!1,chars:l};n+=(p.xAdvance+g)*e,l.push(s+(p.xOffset+g)*e),s+=(p.xAdvance+g)*e,a=d}return{width:n,text:i,end:u,chars:l}},i.BitmapText.prototype.cleanText=function(t,e){void 0===e&&(e="");var i=this._data.font;if(!i)return"";for(var s=/\r\n|\n\r|\n|\r/g,n=t.replace(s,"\n").split("\n"),r=0;rthis.textWidth&&(this.textWidth=c.width),n+=t.lineHeight*i,e=e.substr(c.text.length+1)}while(!1===c.end);this.textHeight=n;for(var r=0,o=0,a=this.textWidth*this.anchor.x,h=this.textHeight*this.anchor.y,l=0;l0&&(this._fontSize=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"smoothed",{get:function(){return!this._data.base.scaleMode},set:function(t){this._data.base.scaleMode=t?0:1,this._data.base.dirty()}}),i.RetroFont=function(t,e,s,n,r,o,a,h,l,c){if(!t.cache.checkImageKey(e))return!1;void 0!==o&&null!==o||(o=t.cache.getImage(e).width/s),this.characterWidth=s,this.characterHeight=n,this.characterSpacingX=a||0,this.characterSpacingY=h||0,this.characterPerRow=o,this.offsetX=l||0,this.offsetY=c||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=t.cache.getImage(e),this._text="",this.grabData=[],this.frameData=new i.FrameData;for(var u=this.offsetX,d=this.offsetY,p=0,f=0;f?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",i.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",i.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",i.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",i.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",i.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",i.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",i.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",i.RetroFont.prototype.setFixedWidth=function(t,e){void 0===e&&(e="left"),this.fixedWidth=t,this.align=e},i.RetroFont.prototype.setText=function(t,e,i,s,n,r){this.multiLine=e||!1,this.customSpacingX=i||0,this.customSpacingY=s||0,this.align=n||"left",this.autoUpperCase=!r,t.length>0&&(this.text=t)},i.RetroFont.prototype.buildRetroFontText=function(){var t=0,e=0;if(this.clear(),this.multiLine){var s=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var n=0;n0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),t=0,this.align===i.RetroFont.ALIGN_RIGHT?t=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===i.RetroFont.ALIGN_CENTER&&(t=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(this._text,t,0,this.customSpacingX);this.requiresReTint=!0},i.RetroFont.prototype.pasteLine=function(t,e,i,s){for(var n=0;n=0&&(this.stamp.frame=this.grabData[t.charCodeAt(n)],this.renderXY(this.stamp,e,i,!1),(e+=this.characterWidth+s)>this.width))break},i.RetroFont.prototype.getLongestLine=function(){var t=0;if(this._text.length>0)for(var e=this._text.split("\n"),i=0;it&&(t=e[i].length);return t},i.RetroFont.prototype.removeUnsupportedCharacters=function(t){for(var e="",i=0;i=0||!t&&"\n"===s)&&(e=e.concat(s))}return e},i.RetroFont.prototype.updateOffset=function(t,e){if(this.offsetX!==t||this.offsetY!==e){for(var i=t-this.offsetX,s=e-this.offsetY,n=this.game.cache.getFrameData(this.stamp.key).getFrames(),r=n.length;r--;)n[r].x+=i,n[r].y+=s;this.buildRetroFontText()}},Object.defineProperty(i.RetroFont.prototype,"text",{get:function(){return this._text},set:function(t){var e;(e=this.autoUpperCase?t.toUpperCase():t)!==this._text&&(this._text=e,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(i.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(t){this.stamp.smoothed=t,this.buildRetroFontText()}}),i.Rope=function(t,e,s,n,r,o){this.points=o||[],this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.ROPE,PIXI.DisplayObjectContainer.call(this),this.texture=i.Cache.DEFAULT,this.uvs=new Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new Float32Array([0,0,100,0,100,100,0,100]),this.colors=new Float32Array([1,1,1,1]),this.indices=new Uint16Array([0,1,2,3]),o&&(this.vertices=new Float32Array(4*o.length),this.uvs=new Float32Array(4*o.length),this.colors=new Float32Array(2*o.length),this.indices=new Uint16Array(2*o.length)),this.dirty=!0,this.canvasPadding=0,this.drawMode=i.Rope.TRIANGLE_STRIP,i.Component.Core.init.call(this,t,e,s,n,r),this.refresh()},i.Rope.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Rope.prototype.constructor=i.Rope,i.Component.Core.install.call(i.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Rope.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Rope.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Rope.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Rope.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Rope.TRIANGLE_STRIP=0,i.Rope.TRIANGLES=1,i.Rope.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},i.Rope.prototype.reset=function(t,e){return i.Component.Reset.prototype.reset.call(this,t,e),this},i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=this.indices,s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o=t.length,a=1;a1&&1,o=Math.sqrt(s.x*s.x+s.y*s.y),a=this.texture.height/2,s.x/=o,s.y/=o,s.x*=a,s.y*=a,h[r]=n.x+s.x,h[r+1]=n.y+s.y,h[r+2]=n.x-s.x,h[r+3]=n.y-s.y,i=n;PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.Rope.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Rope.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Rope.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Rope.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Rope.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Rope.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Rope.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n0){var _=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,T=(l+c+u)/3,P=(d+p+f)/3,C=l-T,S=d-P,A=Math.sqrt(C*C+S*S);l=T+C/A*(A+_),d=P+S/A*(A+w),S=p-P,c=T+(C=c-T)/(A=Math.sqrt(C*C+S*S))*(A+_),p=P+S/A*(A+w),S=f-P,u=T+(C=u-T)/(A=Math.sqrt(C*C+S*S))*(A+_),f=P+S/A*(A+w)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*x+v*y+m*b-x*y-v*m-g*b,M=l*x+v*u+c*b-x*u-v*c-l*b,R=g*c+l*y+m*u-c*y-l*m-g*u,L=g*x*u+v*c*y+l*m*b-l*x*y-v*m*u-g*c*b,B=d*x+v*f+p*b-x*f-v*p-d*b,I=g*p+d*y+m*f-p*y-d*m-g*f,O=g*x*f+v*p*y+d*m*b-d*x*y-v*m*f-g*p*b;t.transform(M/E,B/E,R/E,I/E,L/E,O/E),t.drawImage(o,0,0),t.restore()},i.Rope.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;nh?m:h,l=y>l?y:l}if(c===-1/0||l===1/0)return PIXI.EmptyRectangle;var v=this._bounds;return v.x=c,v.width=h-c,v.y=u,v.height=l-u,this._currentBounds=v,v},Object.defineProperty(i.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(t){t&&"function"==typeof t?(this._hasUpdateAnimation=!0,this._updateAnimation=t):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(i.Rope.prototype,"segments",{get:function(){for(var t,e,s,n,r,o,a,h,l=[],c=0;c(_=y>(_=g>(_=p>_?p:_)?g:_)?y:_)?x:_,w=b>(w=v>(w=m>(w=f>w?f:w)?m:w)?v:w)?b:w;var C=this._bounds;return C.x=T,C.width=_-T,C.y=P,C.height=w-P,this._currentBounds=C,C},Object.defineProperty(i.TileSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TileSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var e=parseInt(RegExp.$1,10),i=parseInt(RegExp.$2,10);(10===e&&i>=11||e>10)&&(s.dolby=!0)}}catch(t){}}(),function(){var t=document.createElement("video");try{!!t.canPlayType&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(s.oggVideo=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.h264Video=!0,s.mp4Video=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(s.webmVideo=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(s.vp9Video=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.hlsVideo=!0))}catch(t){}}(),function(){var t,e=document.createElement("p"),i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var n in i)void 0!==e.style[n]&&(e.style[n]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(i[n]));document.body.removeChild(e),s.css3D=void 0!==t&&t.length>0&&"none"!==t}(),s.pixelRatio=window.devicePixelRatio||1,s.iPhone=-1!==navigator.userAgent.toLowerCase().indexOf("iphone"),s.iPhone4=2===s.pixelRatio&&s.iPhone,s.iPad=-1!==navigator.userAgent.toLowerCase().indexOf("ipad"),"undefined"!=typeof Int8Array?s.typedArray=!0:s.typedArray=!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(s.littleEndian=t(),s.LITTLE_ENDIAN=s.littleEndian),s.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==s.littleEndian&&e(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(s.vibration=!0),function(){s.canvas=!!window.CanvasRenderingContext2D||s.cocoonJS;try{s.localStorage=!!localStorage.getItem}catch(t){s.localStorage=!1}s.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),s.fileSystem=!!window.requestFileSystem,s.webGL=!!window.WebGLRenderingContext,s.worker=!!window.Worker,s.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,s.quirksMode="CSS1Compat"!==document.compatMode,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,s.getUserMedia=s.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,s.firefox&&s.firefoxVersion<21&&(s.getUserMedia=!1),!s.iOS&&(s.ie||s.firefox||s.chrome)&&(s.canvasBitBltShift=!0),(s.safari||s.mobileSafari)&&(s.canvasBitBltShift=!1)}(),function(){var t=i.CanvasPool.create(this,6,1),e=t.getContext("2d");e.fillStyle="rgba(10, 20, 30, 0.5)",e.fillRect(0,0,1,1);var n=e.getImageData(0,0,1,1);if(n){e.putImageData(n,1,0);var r=e.getImageData(1,0,1,1);s.canHandleAlpha=r.data[0]===n.data[0]&&r.data[1]===n.data[1]&&r.data[2]===n.data[2]&&r.data[3]===n.data[3]}e.globalCompositeOperation="multiply",s.canUseMultiply="multiply"===e.globalCompositeOperation,i.CanvasPool.removeByCanvas(t),PIXI.CanvasTinter.tintMethod=s.canUseMultiply?PIXI.CanvasTinter.tintWithMultiply:PIXI.CanvasTinter.tintWithPerPixel}(),function(){for(var t=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],e=document.createElement("div"),i=0;i=1)&&(s.touch=!0),(window.PointerEvent||window.MSPointerEvent||window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(s.mspointer=!0),s.cocoonJS||("onwheel"in window||s.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":s.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"))},i.Device.canPlayAudio=function(t){return!("mp3"!==t||!this.mp3)||(!("ogg"!==t||!this.ogg&&!this.opus)||(!("m4a"!==t||!this.m4a)||(!("opus"!==t||!this.opus)||(!("wav"!==t||!this.wav)||(!("webm"!==t||!this.webm)||!("mp4"!==t||!this.dolby))))))},i.Device.canPlayVideo=function(t){return!("webm"!==t||!this.webmVideo&&!this.vp9Video)||(!("mp4"!==t||!this.mp4Video&&!this.h264Video)||(!("ogg"!==t&&"ogv"!==t||!this.oggVideo)||!("mpeg"!==t||!this.hlsVideo)))},i.Device.needsTouchUnlock=function(){return!!(!this.cocoonJS&&(this.iOS||this.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)},i.Device.isAndroidStockBrowser=function(){var t=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return t&&t[1]<537},i.Canvas={create:function(t,e,s,n,r){e=e||256,s=s||256;var o=r?document.createElement("canvas"):i.CanvasPool.create(t,e,s);return"string"==typeof n&&""!==n&&(o.id=n),o.width=e,o.height=s,o.style.display="block",o},setBackgroundColor:function(t,e){return e=e||"rgb(0,0,0)",t.style.backgroundColor=e,t},setTouchAction:function(t,e){return e=e||"none",t.style.msTouchAction=e,t.style["ms-touch-action"]=e,t.style["touch-action"]=e,t},setUserSelect:function(t,e){return e=e||"none",t.style["-webkit-touch-callout"]=e,t.style["-webkit-user-select"]=e,t.style["-khtml-user-select"]=e,t.style["-moz-user-select"]=e,t.style["-ms-user-select"]=e,t.style["user-select"]=e,t.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",t},addToDOM:function(t,e,i){var s;return void 0===i&&(i=!0),e&&("string"==typeof e?s=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(s=e)),s||(s=document.body),i&&s.style&&(s.style.overflow="hidden"),s.appendChild(t),t},removeFromDOM:function(t){t.parentNode&&t.parentNode.removeChild(t)},setTransform:function(t,e,i,s,n,r,o){return t.setTransform(s,r,o,n,e,i),t},setSmoothingEnabled:function(t,e){var s=i.Canvas.getSmoothingPrefix(t);return s&&(t[s]=e),t},getSmoothingPrefix:function(t){var e=["i","webkitI","msI","mozI","oI"];for(var i in e){var s=e[i]+"mageSmoothingEnabled";if(s in t)return s}return null},getSmoothingEnabled:function(t){var e=i.Canvas.getSmoothingPrefix(t);if(e)return t[e]},setImageRenderingCrisp:function(t){for(var e=["-webkit-optimize-contrast","-moz-crisp-edges","crisp-edges","pixelated"],i=0;i0&&0==(t&t-1))return t;for(var e=1;e0&&0==(t&t-1)&&e>0&&0==(e&e-1)},random:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return Math.random()*(e-t)+t},between:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t},fuzzyEqual:function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)e-i},fuzzyCeil:function(t,e){return void 0===e&&(e=1e-4),Math.ceil(t-e)},fuzzyFloor:function(t,e){return void 0===e&&(e=1e-4),Math.floor(t+e)},average:function(){for(var t=0,e=arguments.length,i=0;i=i.Math.PI2-s?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=s:e=0?t:t+2*Math.PI},maxAdd:function(t,e,i){return Math.min(t+e,i)},minSub:function(t,e,i){return Math.max(t-e,i)},wrap:function(t,e,i){var s=i-e;if(s<=0)return 0;var n=(t-e)%s;return n<0&&(n+=s),n+e},wrapValue:function(t,e,i){return t=Math.abs(t),e=Math.abs(e),i=Math.abs(i),(t+e)%i},isOdd:function(t){return!!(1&t)},isEven:function(t){return!(1&t)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;et[i]&&(i=e);return t[i]},minProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;ie[s][t]&&(s=i);return e[s][t]},wrapAngle:function(t,e){return e?this.wrap(t,-Math.PI,Math.PI):this.wrap(t,-180,180)},linearInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return e<0?this.linear(t[0],t[1],s):e>1?this.linear(t[i],t[i-1],i-s):this.linear(t[n],t[n+1>i?i:n+1],s-n)},bezierInterpolation:function(t,e){for(var i=0,s=t.length-1,n=0;n<=s;n++)i+=Math.pow(1-e,s-n)*Math.pow(e,n)*t[n]*this.bernstein(s,n);return i},catmullRomInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return t[0]===t[i]?(e<0&&(n=Math.floor(s=i*(1+e))),this.catmullRom(t[(n-1+i)%i],t[n],t[(n+1)%i],t[(n+2)%i],s-n)):e<0?t[0]-(this.catmullRom(t[0],t[0],t[1],t[1],-s)-t[0]):e>1?t[i]-(this.catmullRom(t[i],t[i],t[i-1],t[i-1],s-i)-t[i]):this.catmullRom(t[n?n-1:0],t[n],t[i0?Math.ceil(t):Math.floor(t)},sinCosGenerator:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1);for(var n=e,r=i,o=s*Math.PI/t,a=[],h=[],l=0;l0?1:0},percent:function(t,e,i){return void 0===i&&(i=0),t>e||i>e?1:tt?0:(t-i)/e}},i.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},i.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e>>0,s=(e*=s)>>>0,s+=4294967296*(e-=s);return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},i.RandomDataGenerator.prototype.constructor=i.RandomDataGenerator,i.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},i.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new i.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new i.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new i.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new i.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null==this.nodes[0]||-1===(e=this.getIndex(t))){if(this.objects.push(t),this.objects.length>this.maxObjects&&this.levelthis.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.ythis.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof i.Rectangle)var e=this.objects,s=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,s=this.getIndex(t.body)}return this.nodes[0]&&(e=-1!==s?e.concat(this.nodes[s].retrieve(t)):(e=(e=(e=e.concat(this.nodes[0].retrieve(t))).concat(this.nodes[1].retrieve(t))).concat(this.nodes[2].retrieve(t))).concat(this.nodes[3].retrieve(t))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},i.QuadTree.prototype.constructor=i.QuadTree,i.Net=function(t){this.game=t},i.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},i.Net.prototype.constructor=i.Net,i.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:i.Easing.Power0,Power1:i.Easing.Power1,Power2:i.Easing.Power2,Power3:i.Easing.Power3,Power4:i.Easing.Power4,Linear:i.Easing.Linear.None,Quad:i.Easing.Quadratic.Out,Cubic:i.Easing.Cubic.Out,Quart:i.Easing.Quartic.Out,Quint:i.Easing.Quintic.Out,Sine:i.Easing.Sinusoidal.Out,Expo:i.Easing.Exponential.Out,Circ:i.Easing.Circular.Out,Elastic:i.Easing.Elastic.Out,Back:i.Easing.Back.Out,Bounce:i.Easing.Bounce.Out,"Quad.easeIn":i.Easing.Quadratic.In,"Cubic.easeIn":i.Easing.Cubic.In,"Quart.easeIn":i.Easing.Quartic.In,"Quint.easeIn":i.Easing.Quintic.In,"Sine.easeIn":i.Easing.Sinusoidal.In,"Expo.easeIn":i.Easing.Exponential.In,"Circ.easeIn":i.Easing.Circular.In,"Elastic.easeIn":i.Easing.Elastic.In,"Back.easeIn":i.Easing.Back.In,"Bounce.easeIn":i.Easing.Bounce.In,"Quad.easeOut":i.Easing.Quadratic.Out,"Cubic.easeOut":i.Easing.Cubic.Out,"Quart.easeOut":i.Easing.Quartic.Out,"Quint.easeOut":i.Easing.Quintic.Out,"Sine.easeOut":i.Easing.Sinusoidal.Out,"Expo.easeOut":i.Easing.Exponential.Out,"Circ.easeOut":i.Easing.Circular.Out,"Elastic.easeOut":i.Easing.Elastic.Out,"Back.easeOut":i.Easing.Back.Out,"Bounce.easeOut":i.Easing.Bounce.Out,"Quad.easeInOut":i.Easing.Quadratic.InOut,"Cubic.easeInOut":i.Easing.Cubic.InOut,"Quart.easeInOut":i.Easing.Quartic.InOut,"Quint.easeInOut":i.Easing.Quintic.InOut,"Sine.easeInOut":i.Easing.Sinusoidal.InOut,"Expo.easeInOut":i.Easing.Exponential.InOut,"Circ.easeInOut":i.Easing.Circular.InOut,"Elastic.easeInOut":i.Easing.Elastic.InOut,"Back.easeInOut":i.Easing.Back.InOut,"Bounce.easeInOut":i.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},i.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t,e){return e||(e=!1),this._tweens.some(function(i){return i.target===t&&(!e||i.isRunning&&!i.pendingDelete)})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},i.TweenManager.prototype.constructor=i.TweenManager,i.Tween=function(t,e,s){this.game=e,this.target=t,this.manager=s,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new i.Signal,this.onLoop=new i.Signal,this.onRepeat=new i.Signal,this.onChildComplete=new i.Signal,this.onComplete=new i.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=s.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},i.Tween.updateColor=function(t){i.Color.updateColor(t.target)},i.Tween.prototype={to:function(t,e,s,n,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).to(t,e,s,r,o,a)),n&&this.start(),this)},from:function(t,e,s,n,r,o,a){return void 0===e&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).from(t,e,s,r,o,a)),n&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),this.pendingDelete)return console.warn("Phaser.Tween.start cannot be called after Tween.stop"),this;if(null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(i=0;ithis.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(s=0;s0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t=this.startTime))return i.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var s in this.vEnd){var n=this.vStart[s],r=this.vEnd[s];Array.isArray(r)?this.parent.target[s]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[s]=n+(r-n)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():i.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction.call(this.interpolationContext,a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,i.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return i.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,i.TweenData.LOOPED}},i.TweenData.prototype.constructor=i.TweenData,i.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-i.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*i.Easing.Bounce.In(2*t):.5*i.Easing.Bounce.Out(2*t-1)+.5}}},i.Easing.Default=i.Easing.Linear.None,i.Easing.Power0=i.Easing.Linear.None,i.Easing.Power1=i.Easing.Quadratic.Out,i.Easing.Power2=i.Easing.Cubic.Out,i.Easing.Power3=i.Easing.Quartic.Out,i.Easing.Power4=i.Easing.Quintic.Out,i.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.updates=0,this.renders=0,this.fps=0,this.ups=0,this.rps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new i.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},i.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new i.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3){var t=this.now-this._timeLastSecond;this.fps=Math.round(1e3*this.frames/t),this.ups=Math.round(1e3*this.updates/t),this.rps=Math.round(1e3*this.renders/t),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0,this.updates=0,this.renders=0}},countUpdate:function(){this.advancedTiming&&this.updates++},countRender:function(){this.advancedTiming&&this.renders++},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(i.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),i.Time.prototype.constructor=i.Time,i.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new i.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},i.Timer.MINUTE=6e4,i.Timer.SECOND=1e3,i.Timer.HALF=500,i.Timer.QUARTER=250,i.Timer.prototype={create:function(t,e,s,n,r,o){var a=t=Math.round(t);0===this._now?a+=this.game.time.time:a+=this._now;var h=new i.TimerEvent(this,t,a,s,e,n,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.ticke.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i=e.tick)||e.pendingDelete)break;this._newTick=this._now+e.delay-(this._now-e.tick),this._newTick<0&&(this._newTick=this._now+e.delay),!0===e.loop?(e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):e.repeatCount>0?(e.repeatCount--,e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):(this._marked++,e.pendingDelete=!0,e.callback.apply(e.callbackContext,e.args)),this._i++}this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;ethis._now?this.nextTick-this._now:0}}),Object.defineProperty(i.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(i.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(i.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),i.Timer.prototype.constructor=i.Timer,i.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},i.TimerEvent.prototype.constructor=i.TimerEvent,i.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},i.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,s,n,r){return e=e||[],s=s||60,void 0===n&&(n=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new i.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,s,n),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;ithis._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},i.AnimationManager.prototype.constructor=i.AnimationManager,Object.defineProperty(i.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(i.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(i.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(i.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(i.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){var e;"number"==typeof t&&this._frameData&&(e=this._frameData.getFrame(t))&&(this.currentFrame=e,this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(i.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){var e;"string"==typeof t&&this._frameData&&(e=this._frameData.getFrameByName(t))?(this.currentFrame=e,this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame)):console.warn("Cannot set frameName: "+t)}}),i.Animation=function(t,e,s,n,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=n,this.name=s,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new i.Signal,this.onUpdate=null,this.onComplete=new i.Signal,this.onLoop=new i.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},i.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(s=0;s=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay?(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay):this._frameDiff=0,this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(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=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},i.Animation.prototype.constructor=i.Animation,Object.defineProperty(i.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(i.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(i.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(i.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(i.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(i.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new i.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),i.Animation.generateFrameNames=function(t,e,s,n,r){void 0===n&&(n="");var o=[],a="";if(e=s;h--)a=t+(a="number"==typeof r?i.Utils.pad(h.toString(),r,"0",1):h.toString())+n,o.push(a);return o},i.Frame=function(t,e,s,n,r,o){this.index=t,this.x=e,this.y=s,this.width=n,this.height=r,0!==this.width&&0!==this.height||console.warn('Phaser.Frame: Frame "'+this.name+'" has a width or height of zero'),this.name=o,this.centerX=Math.floor(n/2),this.centerY=Math.floor(r/2),this.distance=i.Math.distance(0,0,n,r),this.rotated=!1,this.trimmed=!1,this.sourceSizeW=n,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},i.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=i.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new i.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new i.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},i.Frame.prototype.constructor=i.Frame,i.FrameData=function(){this._frames=[],this._frameNames=[]},i.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new i.FrameData,e=0;ed||h<-d)return console.warn("Phaser.AnimationParser.spriteSheet: skipFrames = "+h.toString()+" is larger than total sprite number "+d.toString()),null;if(h<0&&(h=d+h),-1!==r&&(d=h+r),0===c||0===u||cc&&(f=o,g+=n+a);return p},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var s,n=new i.FrameData,r=e.frames,o=0;o tag")}},i.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{},compressedTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new i.Signal,this._cacheMap=[],this._cacheMap[i.Cache.CANVAS]=this._cache.canvas,this._cacheMap[i.Cache.IMAGE]=this._cache.image,this._cacheMap[i.Cache.TEXTURE]=this._cache.texture,this._cacheMap[i.Cache.SOUND]=this._cache.sound,this._cacheMap[i.Cache.TEXT]=this._cache.text,this._cacheMap[i.Cache.PHYSICS]=this._cache.physics,this._cacheMap[i.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[i.Cache.BINARY]=this._cache.binary,this._cacheMap[i.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[i.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[i.Cache.JSON]=this._cache.json,this._cacheMap[i.Cache.XML]=this._cache.xml,this._cacheMap[i.Cache.VIDEO]=this._cache.video,this._cacheMap[i.Cache.SHADER]=this._cache.shader,this._cacheMap[i.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this._pendingCount=0,this.onReady=new i.Signal,this._addImages()},i.Cache.CANVAS=1,i.Cache.IMAGE=2,i.Cache.TEXTURE=3,i.Cache.SOUND=4,i.Cache.TEXT=5,i.Cache.PHYSICS=6,i.Cache.TILEMAP=7,i.Cache.BINARY=8,i.Cache.BITMAPDATA=9,i.Cache.BITMAPFONT=10,i.Cache.JSON=11,i.Cache.XML=12,i.Cache.VIDEO=13,i.Cache.SHADER=14,i.Cache.RENDER_TEXTURE=15,i.Cache.DEFAULT=null,i.Cache.DEFAULT_KEY="__default",i.Cache.DEFAULT_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==",i.Cache.MISSING=null,i.Cache.MISSING_KEY="__missing",i.Cache.MISSING_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==",i.Cache.READY_TIMEOUT=1e3,i.Cache.prototype={addCompressedTextureMetaData:function(t,e,s,n){this.checkImageKey(t)&&this.removeImage(t);var r=s in i.LoaderParser?i.LoaderParser[s](n):n,o={key:t,url:e,data:r,base:new PIXI.BaseTexture(r,null,this.game.resolution),frame:new i.Frame(0,0,0,r.width,r.height,t),frameData:new i.FrameData,fileFormat:s};return o.frameData.addFrame(new i.Frame(0,0,0,r.width,r.height,e)),this._cache.image[t]=o,this._resolveURL(e,o),o},addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,s){this.checkImageKey(t)&&this.removeImage(t),!1===s.complete&&console.warn('Phaser.Cache.addImage: Image "'+t+"\" hasn't been retrieved yet");var n={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution),frame:new i.Frame(0,0,0,s.width,s.height,t),frameData:new i.FrameData};return n.frameData.addFrame(new i.Frame(0,0,0,s.width,s.height,e)),this._cache.image[t]=n,this._resolveURL(e,n),"__default"===t?i.Cache.DEFAULT=new PIXI.Texture(n.base):"__missing"===t&&(i.Cache.MISSING=new PIXI.Texture(n.base)),n},addImageAsync:function(t,e,i){var s=this,n=new Image;n.onload=function(){i.call(this,s.addImage(t,null,n)),s._removePending(),n.onload=null},this._addPending(),n.src=e},addDefaultImage:function(){this.addImageAsync(i.Cache.DEFAULT_KEY,i.Cache.DEFAULT_SRC,function(t){t.base.skipRender=!0,i.Cache.DEFAULT=new PIXI.Texture(t.base)})},addMissingImage:function(){this.addImageAsync(i.Cache.MISSING_KEY,i.Cache.MISSING_SRC,function(t){i.Cache.MISSING=new PIXI.Texture(t.base)})},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,s){return e.key=t,void 0===s&&(s=new i.FrameData).addFrame(e.textureFrame),this._cache.bitmapData[t]={data:e,frameData:s},e},addBitmapFont:function(t,e,s,n,r,o,a){var h={url:e,data:s,font:null,base:new PIXI.BaseTexture(s,null,this.game.resolution)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?i.LoaderParser.jsonBitmapFont(n,h.base,o,a,!1,this.game.resolution):i.LoaderParser.xmlBitmapFont(n,h.base,o,a,!1,this.game.resolution),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addBitmapFontFromAtlas:function(t,e,s,n,r,o,a){var h=this.getFrameByName(e,s);if(h){var l={font:null,base:this.getBaseTexture(e),frame:h};void 0===o&&(o=0),void 0===a&&(a=0);var c;"json"===r?(c=this.getJSON(n),l.font=i.LoaderParser.jsonBitmapFont(c,l.base,o,a,h,this.game.resolution)):(c=this.getXML(n),l.font=i.LoaderParser.xmlBitmapFont(c,l.base,o,a,h,this.game.resolution)),this._cache.bitmapFont[t]=l}},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new i.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,s,n,r,o,a,h,l){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var c={key:t,url:e,data:s,frameWidth:n,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(s,null,this.game.resolution),frameData:i.AnimationParser.spriteSheet(this.game,s,n,r,o,a,h,l)};this._cache.image[t]=c,this._resolveURL(e,c)},addTextureAtlas:function(t,e,s,n,r){var o={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution)};r===i.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=i.AnimationParser.XMLData(this.game,n,t):r===i.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=i.AnimationParser.JSONDataPyxel(this.game,n,t):Array.isArray(n.frames)?o.frameData=i.AnimationParser.JSONData(this.game,n,t):o.frameData=i.AnimationParser.JSONDataHash(this.game,n,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(i.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(i.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(i.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(i.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(i.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(i.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(i.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(i.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(i.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(i.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(i.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(i.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(i.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(i.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(i.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,i.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var s=this.getItem(t,i.Cache.IMAGE,"getImage");return null===s&&(s=this.getItem("__missing",i.Cache.IMAGE,"getImage")),e?s:s.data},getTextureFrame:function(t){return this.getItem(t,i.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,i.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,i.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,i.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,s){var n=this.getItem(t,i.Cache.PHYSICS,"getPhysicsData","data");if(null===n||void 0===e||null===e)return n;if(n[e]){var r=n[e];if(!r||!s)return r;for(var o in r)if((o=r[o]).fixtureKey===s)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+s+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,i.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,i.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,i.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,i.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var s=this.getItem(t,i.Cache.JSON,"getJSON","data");return s?e?i.Utils.extend(!0,Array.isArray(s)?[]:{},s):s:null},getXML:function(t){return this.getItem(t,i.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,i.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,i.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,i.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,s){void 0===s&&(s=i.Cache.IMAGE),this._cacheMap[s][t]&&(this._cacheMap[s][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){return(t=this._resolveURL(t))?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=i.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var s in this._cacheMap[t])"__default"!==s&&"__missing"!==s&&e.push(s);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.image[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t0?setTimeout(function(){t.isReady||(console.warn("Phaser.Cache: Still waiting for images after %s ms.",e),t._ready())},i.Cache.READY_TIMEOUT):this._ready()},_addPending:function(){this._pendingCount+=1},_removePending:function(){this._pendingCount-=1,this._checkReady()},_checkReady:function(){this.isReady&&this._ready()},_ready:function(){this._pendingCount=0,this.onReady.dispatch(this)}},i.Cache.prototype.constructor=i.Cache,Object.defineProperty(i.Cache.prototype,"isReady",{get:function(){return this._pendingCount<=0}}),i.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new i.Signal,this.onLoadComplete=new i.Signal,this.onPackComplete=new i.Signal,this.onFileStart=new i.Signal,this.onFileComplete=new i.Signal,this.onFileError=new i.Signal,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},i.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,i.Loader.TEXTURE_ATLAS_JSON_HASH=1,i.Loader.TEXTURE_ATLAS_XML_STARLING=2,i.Loader.PHYSICS_LIME_CORONA_JSON=3,i.Loader.PHYSICS_PHASER_JSON=4,i.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,i.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new i.Rectangle(0,0,1,t.height):new i.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r=e||t&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var n=this;setTimeout(function(){n.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.reset(),this.onLoadComplete.dispatch(),this.game.state&&this.game.state.loadComplete())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(e)for(var s=0;s=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},getVideoURL:function(t){for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s="error loading asset from URL "+(t.requestUrl||this.transformUrl(t.url,t));!i&&e&&(i=e.status),i&&(s=s+" ("+i+")"),this.asyncComplete(t,s)},fileComplete:function(t,e){var s=!0;switch(t.type){case"packfile":r=JSON.parse(e.responseText);t.data=r||{};break;case"texture":var n=/\.([^.]+)$/.exec(t.url.split("?",1)[0])[1].toLowerCase();null!==t.data?this.cache.addCompressedTextureMetaData(t.key,t.url,n,t.data):this.cache.addCompressedTextureMetaData(t.key,t.url,n,e.response);break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing,t.skipFrames);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(s=!1,t.format===i.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===i.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===i.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==i.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(s=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var r=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,r,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}s&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else(e=new ActiveXObject("Microsoft.XMLDOM")).async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(i.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return i.Math.clamp(t||0,0,100)}}),Object.defineProperty(i.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),i.Loader.prototype.constructor=i.Loader,i.LoaderParser={bitmapFont:function(t,e,i,s,n,r){return this.xmlBitmapFont(t,e,i,s,n,r)},xmlBitmapFont:function(t,e,i,s,n,r){null==r&&(r=1);var o={},a=t.getElementsByTagName("info")[0],h=t.getElementsByTagName("common")[0];o.font=a.getAttribute("face"),o.size=parseInt(a.getAttribute("size"),10),o.lineHeight=parseInt(h.getAttribute("lineHeight"),10)+s,o.chars={};for(var l=t.getElementsByTagName("char"),c=n?n.x:0,u=n?n.y:0,d=0;d=0){switch(r>=0&&r<=3?e="PVRTC":r>=7&&r<=11?e="S3TC":6===r&&(e="ETC1"),r){case 0:o=35841;break;case 1:o=35843;break;case 2:o=35840;break;case 3:o=35842;break;case 6:o=36196;break;case 7:o=33777;break;case 9:o=33778;break;case 11:o=33779;break;default:o=-1}n={complete:!0,fileFormat:"PVR",compressionAlgorithm:e,flags:i[1],pixelFormat:r,colorSpace:i[4],channelType:i[5],height:i[6],width:i[7],depth:i[8],numberOfSurfaces:i[9],numberOfFaces:i[10],numberOfMipmaps:i[11],metaDataSize:i[12],textureData:s.subarray(52+i[12],s.byteLength),glExtensionFormat:o}}return n},dds:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null;return 68===e[0]&&68===e[1]&&83===e[2]&&32===e[3]&&"DX10"===(s={complete:!0,fileFormat:"DDS",compressionAlgorithm:"S3TC",size:i[1],flags:i[2],height:i[3],width:i[4],pitch:i[5],depth:i[6],mipmapCount:i[7],formatSize:i[19],formatFlag:i[19],formatFourCC:[String.fromCharCode(e[84]),String.fromCharCode(e[85]),String.fromCharCode(e[86]),String.fromCharCode(e[87])].join(""),formatBitCount:i[21],formatRBitMask:i[22],formatGBitMask:i[23],formatBBitMask:i[24],formatABitMask:i[25],caps1:i[26],caps2:i[27],caps3:i[28],caps4:i[29],reserved2:i[30],DXGIFormat:null,resourceDimension:null,miscFlag:null,arraySize:null,textureData:e.subarray(i[1]+4,e.byteLength)}).formatFourCC&&(s.DXGIFormat=i[31],s.resourceDimension=i[32],s.miscFlag=i[33],s.arraySize=i[34],s.miscFlag=i[35]),s},ktx:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null,n=16+i[15]/4|0,r=i[n],o=i[7],a=0;if(171===e[0]&&75===e[1]&&84===e[2]&&88===e[3]&&32===e[4]&&49===e[5]&&49===e[6]&&187===e[7]&&13===e[8]&&10===e[9]&&26===e[10]&&10===e[11]&&[36196,35840,35841,35842,35843,33776,33777,33778,33779].indexOf(o)>=0){switch(o){case 36196:a="ETC1";break;case 35840:case 35841:case 35842:case 35843:a="PVRTC";break;case 33776:case 33777:case 33778:case 33779:a="S3TC"}s={complete:!0,fileFormat:"KTX",compressionAlgorithm:a,endianness:i[3],glType:i[4],glTypeSize:i[5],glFormat:i[6],glInternalFormat:i[7],glBaseInternalFormat:i[8],width:i[9],height:i[10],pixelDepth:i[11],numberOfArrayElements:i[12],numberOfFaces:i[13],numberOfMipmapLevels:i[14],bytesOfKeyValueData:i[15],keyAndValueByteSize:i[16],imageSize:r,textureData:e.subarray(4*(n+1),r+100)}}return s},pkm:function(t){var e=new Uint8Array(t),i=null;return 80===e[0]&&75===e[1]&&77===e[2]&&32===e[3]&&(i={complete:!0,fileFormat:"PKM",compressionAlgorithm:"ETC1",format:65535&(e[6]<<8|e[7]),width:65535&(e[8]<<8|e[9]),height:65535&(e[10]<<8|e[11]),originalWidth:65535&(e[12]<<8|e[13]),originalHeight:65535&(e[14]<<8|e[15]),textureData:e.subarray(16,e.length)}),i}},i.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},i.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},i.AudioSprite.prototype.constructor=i.AudioSprite,i.Sound=function(t,e,s,n,r){void 0===s&&(s=1),void 0===n&&(n=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=n,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this._globalVolume=1,this._markedToDelete=!1,this._removeFromSoundManager=!1,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=s,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new i.Signal,this.onPlay=new i.Signal,this.onPause=new i.Signal,this.onResume=new i.Signal,this.onLoop=new i.Signal,this.onStop=new i.Signal,this.onMute=new i.Signal,this.onMarkerComplete=new i.Signal,this.onFadeComplete=new i.Signal,this._volume=s,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},i.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop(),this._markedToDelete&&(this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode),this._removeFromSoundManager?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()))},update:function(){this.game.cache.checkSoundKey(this.key)?(this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))):this.destroy()},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){this.isPlaying&&!this.paused&&e!==this.volume&&(void 0===t&&(t=1e3),void 0!==e?(this.fadeTween=this.game.add.tween(this).to({volume:e},t,i.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)):console.warn("Phaser.Sound.fadeTo: No Volume Specified."))},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._globalVolume=t,this._sound.volume=this._globalVolume*this._volume)},destroy:function(t){void 0===t&&(t=!0),this._markedToDelete=!0,this._removeFromSoundManager=t,this.stop(),t?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())}},i.Sound.prototype.constructor=i.Sound,Object.defineProperty(i.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(i.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(i.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(i.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted?this._muteVolume=t:(this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=this._globalVolume*t))}}),i.SoundManager=function(t){this.game=t,this.onSoundDecode=new i.Signal,this.onVolumeChange=new i.Signal,this.onMute=new i.Signal,this.onUnMute=new i.Signal,this.onTouchUnlock=new i.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new i.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},i.SoundManager.prototype={boot:function(){var t=this.game.device,e=window.PhaserGlobal;if(t.iOS&&!1===t.webAudio&&(this.channels=1),e){if(!0===e.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===e.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(e&&e.audioContext)this.context=e.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||t.needsTouchUnlock()&&this.setTouchLock(),this.usingWebAudio&&t.chrome&&t.chromeVersion<=65&&console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. ')},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0)},setTouchUnlock:function(){this.touchLocked=!1,this._unlockSource=null,this.onTouchUnlock.dispatch()},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.setTouchUnlock();else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0),"suspended"===this._unlockSource.context.state&&this._unlockSource.context.resume()}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,s=this._parentBounds.height,n=this.getParentBounds(this._parentBounds),r=n.width!==e||n.height!==s,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,n),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottlee;return(h=h?s:!s)?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},i.ScaleManager.prototype.constructor=i.ScaleManager,Object.defineProperty(i.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(i.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(i.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(i.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),i.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.lineWidth=1,this.renderShadow=!0,this.currentColor=null,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1,this.isDisabled=!1,this._line=null,this._rect=null},i.Utils.Debug.prototype={boot:function(){this.game.renderType===i.CANVAS?this.context=this.game.context:(this.bmd=new i.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=i.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d")),this._line=new i.Line,this._rect=new i.Rectangle},resize:function(){this.bmd.resize(this.game.width,this.game.height),this.canvas.width=this.game.width,this.canvas.height=this.game.height},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e0)for(var e=0;e=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new i.Rectangle,layoutBounds:new i.Rectangle,documentBounds:new i.Rectangle},i.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},s=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(i.DOM,"scrollX",{get:e}),Object.defineProperty(i.DOM,"scrollY",{get:s}),Object.defineProperty(i.DOM.visualBounds,"x",{get:e}),Object.defineProperty(i.DOM.visualBounds,"y",{get:s}),Object.defineProperty(i.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(i.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var n=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(i.DOM.visualBounds,"width",{get:n}),Object.defineProperty(i.DOM.visualBounds,"height",{get:r}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:n}),Object.defineProperty(i.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(i.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(i.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(i.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(i.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(i.ArraySet.prototype,"next",{get:function(){return this.position=s||0===i)){null==i&&(i=1);for(var n=s-i,r=e;r0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=(t=i.ArrayUtils.transposeMatrix(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=i.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var s=0;s>>0:(t<<24|e<<16|s<<8|n)>>>0},unpackPixel:function(t,e,s,n){return void 0!==e&&null!==e||(e=i.Color.createColor()),void 0!==s&&null!==s||(s=!1),void 0!==n&&null!==n||(n=!1),i.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",s&&i.Color.RGBtoHSL(e.r,e.g,e.b,e),n&&i.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=i.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},hexToRGBArray:function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},RGBArrayToHex:function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},RGBtoHSL:function(t,e,s,n){n||(n=i.Color.createColor(t,e,s,1)),t/=255,e/=255,s/=255;var r=Math.min(t,e,s),o=Math.max(t,e,s);if(n.h=0,n.s=0,n.l=(o+r)/2,o!==r){var a=o-r;n.s=n.l>.5?a/(2-o-r):a/(o+r),o===t?n.h=(e-s)/a+(e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,s,n,r,o,a,h){var l={r:t||0,g:e||0,b:s||0,a:n||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return i.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toFixed()+","+t.g.toFixed()+","+t.b.toFixed()+","+t.a.toString()+")",t.color=i.Color.getColor(t.r,t.g,t.b),t.color32=i.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,s,n,r){return void 0===n&&(n=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+s).toString(16).slice(1):"0x"+i.Color.componentToHex(n)+i.Color.componentToHex(t)+i.Color.componentToHex(e)+i.Color.componentToHex(s)},hexToRGB:function(t){var e=i.Color.hexToColor(t);if(e)return i.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var s=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(s){var n=parseInt(s[1],16),r=parseInt(s[2],16),o=parseInt(s[3],16);e?(e.r=n,e.g=r,e.b=o):e=i.Color.createColor(n,r,o)}return e},webToColor:function(t,e){e||(e=i.Color.createColor());var s=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return s&&(e.r=~~Number(s[1]),e.g=~~Number(s[2]),e.b=~~Number(s[3]),e.a=void 0!==s[4]?Number(s[4]):1,i.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=i.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?i.Color.webToColor(t,e):(e.a=1,i.Color.hexToColor(t,e));if("number"==typeof t){var s=i.Color.getRGB(t);return e.r=s.r,e.g=s.g,e.b=s.b,e.a=s.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSVtoRGB(n/359,t,e));return s},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSLtoRGB(n/359,t,e));return s},interpolateColor:function(t,e,s,n,r,o){void 0===r&&(r=255),void 0===o&&(o=0);var a=i.Color.getRGB(t),h=i.Color.getRGB(e);if(0===o)var l=(h.red-a.red)*n/s+a.red,c=(h.green-a.green)*n/s+a.green,u=(h.blue-a.blue)*n/s+a.blue;if(1===o){var d,p=i.Color.RGBtoHSV(a.r,a.g,a.b),f=i.Color.RGBtoHSV(h.r,h.g,h.b),g=f.h-p.h;if(p.h>f.h){var m=f.h;f.h=p.h,p.h=m,g=-g,n=s-n}g>.5&&(p.h=p.h+1,d=((f.h-p.h)*n/s+p.h)%1),g<=.5&&(d=(f.h-p.h)*n/s+p.h);var y=(f.s-p.s)*n/s+p.s,v=(f.v-p.v)*n/s+p.v,x=i.Color.HSVtoRGB(d,y,v,x),l=x.r,c=x.g,u=x.b}return i.Color.getColor32(r,l,c,u)},interpolateColorWithRGB:function(t,e,s,n,r,o){var a=i.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(s-a.green)*o/r+a.green,c=(n-a.blue)*o/r+a.blue;return i.Color.getColor(h,l,c)},interpolateRGB:function(t,e,s,n,r,o,a,h){var l=(n-t)*h/a+t,c=(r-e)*h/a+e,u=(o-s)*h/a+s;return i.Color.getColor(l,c,u)},linear:function(t,e,i){return this.interpolateColor(t,e,1,i)},linearInterpolation:function(t,e){var s=i.Math.linear(0,t.length-1,e),n=t[Math.floor(s)],r=t[Math.ceil(s)];return this.linear(n,r,s%1)},getRandomColor:function(t,e,s){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===s&&(s=255),e>255||t>e)return i.Color.getColor(255,255,255);var n=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return i.Color.getColor32(s,n,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=i.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return i.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return i.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return i.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?i.Color.blendLinearBurn(t,2*e):i.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?i.Color.blendColorBurn(t,2*e):i.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?i.Color.blendDarken(t,2*e):i.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return i.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return i.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},i.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},i.Physics.ARCADE=0,i.Physics.P2JS=1,i.Physics.NINJA=2,i.Physics.BOX2D=3,i.Physics.CHIPMUNK=4,i.Physics.MATTERJS=5,i.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!i.Physics.hasOwnProperty("Arcade")||(this.arcade=new i.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&i.Physics.hasOwnProperty("Ninja")&&(this.ninja=new i.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&i.Physics.hasOwnProperty("P2")&&(this.p2=new i.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&i.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new i.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&i.Physics.hasOwnProperty("Matter")&&(this.matter=new i.Physics.Matter(this.game,this.config))},startSystem:function(t){t===i.Physics.ARCADE?this.arcade=new i.Physics.Arcade(this.game):t===i.Physics.P2JS?null===this.p2?this.p2=new i.Physics.P2(this.game,this.config):this.p2.reset():t===i.Physics.NINJA?this.ninja=new i.Physics.Ninja(this.game):t===i.Physics.BOX2D?null===this.box2d?this.box2d=new i.Physics.Box2D(this.game,this.config):this.box2d.reset():t===i.Physics.MATTERJS&&(null===this.matter?this.matter=new i.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,s){void 0===e&&(e=i.Physics.ARCADE),void 0===s&&(s=!1),e===i.Physics.ARCADE?this.arcade.enable(t):e===i.Physics.P2JS&&this.p2?this.p2.enable(t,s):e===i.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===i.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===i.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},i.Physics.prototype.constructor=i.Physics,i.Physics.Arcade=function(t){this.game=t,this.gravity=new i.Point,this.bounds=new i.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=i.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new i.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._total=0,this.setBoundsToWorld()},i.Physics.Arcade.prototype.constructor=i.Physics.Arcade,i.Physics.Arcade.SORT_NONE=0,i.Physics.Arcade.LEFT_RIGHT=1,i.Physics.Arcade.RIGHT_LEFT=2,i.Physics.Arcade.TOP_BOTTOM=3,i.Physics.Arcade.BOTTOM_TOP=4,i.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof i.Group?this.enable(t[s].children,e):(this.enableBody(t[s]),e&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],!0));else t instanceof i.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.Arcade.Body(t),t.parent&&t.parent instanceof i.Group&&t.parent.addToHash(t))},updateMotion:function(t){if(t.allowRotation){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed}t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&e.allowDrag&&(i-(n*=this.game.time.physicsElapsed)>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!0),this._total>0},collide:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!1),this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===i.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===i.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===i.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===i.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideObjects:function(t,e,i,s,n,r){if(!Array.isArray(t)&&Array.isArray(e))for(o=0;oa.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(t.body.bottoma.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,s,n,r,o)}}else{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(e);for(var c=this.quadTree.retrieve(t),h=0;hc.right)continue;if(c.x>a.right)break}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(a.bottomc.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,s,n,r)}}}}},collideGroupVsGroup:function(t,e,s,n,r,o){if(0!==t.length&&0!==e.length)for(var a=0;aa.bottom)&&(h.xa.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var s=i.Math.clamp(t.center.x,e.left,e.right),n=i.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-s)*(t.center.x-s)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},separateCircle:function(t,e,s){this.getOverlapX(t,e),this.getOverlapY(t,e);var n=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,n),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.center.x:e.center.x,y:t.isCircle?t.center.y:e.center.y,radius:t.isCircle?t.halfWidth:e.halfWidth};l.yh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.xh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.halfWidth+e.halfWidth-i.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(s||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.yMath.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x)>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0):t.deltaX()n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y)>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0):t.deltaY()n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,s,n,r,o){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(s);for(var a=new i.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c0&&(s=this.distanceBetween(t,e)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.setToPolar(n,e),n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},velocityFromAngle:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e,!0)},velocityFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerationFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(o,s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i,s){void 0===i&&(i=!1);var n,r;return s?(n=t.centerX-e.centerX,r=t.centerY-e.centerY):i?(n=t.world.x-e.world.x,r=t.world.y-e.world.y):(n=t.x-e.x,r=t.y-e.y),Math.sqrt(n*n+r*r)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},closest:function(t,e,i,s){for(var n=1/0,r=null,o=0,a=e.length;on&&(r=h,n=l)}return r},angleBetween:function(t,e,s){return void 0===s&&(s=!1),s?i.Point.angle(e.world,t.world):i.Point.angle(e,t)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},i.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=i.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new i.Point,this.position=new i.Point(t.x,t.y),this.prev=new i.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new i.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new i.Point,this.newVelocity=new i.Point,this.deltaMax=new i.Point,this.acceleration=new i.Point,this.allowDrag=!0,this.drag=new i.Point,this.allowGravity=!0,this.gravity=new i.Point,this.bounce=new i.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new i.Point(1e4,1e4),this.friction=new i.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=i.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.tilePadding=new i.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new i.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},i.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter())},updateCenter:function(){this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,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=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.none=!0,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.overlapR=0,this.overlapX=0,this.overlapY=0,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.updateCenter(),this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),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,this.updateCenter(),this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=this.velocity.atan()),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=i.LEFT:this.deltaX()>0&&(this.facing=i.RIGHT),this.deltaY()<0?this.facing=i.UP:this.deltaY()>0&&(this.facing=i.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.updateCenter(),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0,this.blocked.none=!1),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0,this.blocked.none=!1),!this.blocked.none},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.setToPolar(s,e),this.isMoving=!0,!0},moveTo:function(t,e,s){var n=e/(t/1e3);if(0===n)return!1;var r;return void 0===s?(r=this.angle,s=this.game.math.radToDeg(r)):r=this.game.math.degToRad(s),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new i.Line,this.moveEnd=new i.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===s||180===s?this.velocity.set(Math.cos(r)*n,0):90===s||270===s?this.velocity.set(0,Math.sin(r)*n):this.velocity.setToPolar(r,n),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,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(i,s),this.updateCenter(),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,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(e,i),this.updateCenter()):this.isCircle=!1},reset:function(t,e){this.stop(),this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this.updateBounds(),this.updateCenter()},stop:function(){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?i.Circle.contains(this,t,e):i.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},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},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof i.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(i.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),i.Physics.Arcade.Body.render=function(t,e,i,s,n){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,t.lineWidth=n||1,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.halfWidth,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},i.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},i.Physics.Arcade.Body.prototype.constructor=i.Physics.Arcade.Body,i.Physics.Arcade.TilemapCollision=function(){},i.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x-e.getTileOffsetX(),t.body.position.y-t.body.tilePadding.y-e.getTileOffsetY(),t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;ae.deltaAbsY()?l=-1:e.deltaAbsX()0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.getTileOffsetY();return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?(t.blocked.left=!0,t.blocked.none=!1):e>0&&(t.blocked.right=!0,t.blocked.none=!1),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?(t.blocked.up=!0,t.blocked.none=!1):e>0&&(t.blocked.down=!0,t.blocked.none=!1),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},i.Utils.mixinPrototype(i.Physics.Arcade.prototype,i.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,i.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new i.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new i.Signal,this.onBodyRemoved=new i.Signal,this.onSpringAdded=new i.Signal,this.onSpringRemoved=new i.Signal,this.onConstraintAdded=new i.Signal,this.onConstraintRemoved=new i.Signal,this.onContactMaterialAdded=new i.Signal,this.onContactMaterialRemoved=new i.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},i.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,s){void 0===e&&(e=!1),void 0===s&&(s=!0);var n=1;if(Array.isArray(t))for(n=t.length;n--;)t[n]instanceof i.Group?this.enable(t[n].children,e,s):(this.enableBody(t[n],e),s&&t[n].hasOwnProperty("children")&&t[n].children.length>0&&this.enable(t[n],e,!0));else t instanceof i.Group?this.enable(t.children,e,s):(this.enableBody(t,e),s&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);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.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.DistanceConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,s,n){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.GearConstraint(this,t,e,s,n));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),s=this.getBody(s),t&&s)return this.addConstraint(new i.Physics.P2.RevoluteConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,s,n,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.LockConstraint(this,t,e,s,n,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,s,n,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.PrismaticConstraint(this,t,e,s,n,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var s=new i.Physics.P2.Material(t);return this.materials.push(s),void 0!==e&&e.setMaterial(s),s},createContactMaterial:function(t,e,s){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var n=new i.Physics.P2.ContactMaterial(t,e,s);return this.addContactMaterial(n)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof i.Physics.P2.Body?t.data:t.body&&t.body.type===i.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,s,n){void 0===e&&(e=this.world.bodies),void 0===s&&(s=5),void 0===n&&(n=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof i.Physics.P2.Body&&(!n||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!n||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof i.Sprite&&e[a].hasOwnProperty("body")&&(!n||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,s)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var s=new i.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(s),t&&this.setCollisionGroup(t,s),s},setCollisionGroup:function(t,e){if(t instanceof i.Group)for(var s=0;s-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides?n+=u.width:((p=this.createBody(r,o,0,!1)).addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0)}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(i.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(i.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(i.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(i.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(i.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(i.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(i.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(i.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(i.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),i.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},i.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionGroup=t})},setMask:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionMask=t})},setSensor:function(t,e){this.getFixtures(e).forEach(function(e){e.sensor=t})},setMaterial:function(t,e){this.getFixtures(e).forEach(function(e){e.material=t})},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},i.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.PointProxy.prototype.constructor=i.Physics.P2.PointProxy,Object.defineProperty(i.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),i.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.InversePointProxy.prototype.constructor=i.Physics.P2.InversePointProxy,Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),i.Physics.P2.Body=function(t,e,s,n,r){e=e||null,s=s||0,n=n||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=i.Physics.P2JS,this.offset=new i.Point,this.data=new p2.Body({position:[this.world.pxmi(s),this.world.pxmi(n)],mass:r}),this.data.parent=this,this.velocity=new i.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new i.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new i.Point,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},i.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(r=0;r-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var n=this.getCollisionMask();if(void 0===i)for(var r=this.data.shapes.length-1;r>=0;r--)this.data.shapes[r].collisionMask=n;else i.collisionMask=n},collides:function(t,e,i,s){if(Array.isArray(t))for(r=0;r=0;r--)this.data.shapes[r].collisionMask=n;else s.collisionMask=n},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},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(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;np;n=0<=p?++d:--d)l=e.vertices[n],p2.vec2.rotate(u,l,t),c.push([(u[0]+a[0])*this.ppu,-(u[1]+a[1])*this.ppu]);this.drawConvex(h,c,e.triangles,16711680,i,r,this.settings.debugPolygons,[a[0]*this.ppu,-a[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)p=(c=e[l])[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return 2===(e=t.toString(16)).length?e:e+"0"}}),i.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1);var c={restLength:s=t.pxm(s),stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},i.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),i.Physics.P2.Material.prototype.constructor=i.Physics.P2.Material,i.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},i.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),i.Physics.P2.ContactMaterial.prototype.constructor=i.Physics.P2.ContactMaterial,i.Physics.P2.CollisionGroup=function(t){this.mask=t},i.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t;var a={distance:s=t.pxm(s),localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},i.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),i.Physics.P2.DistanceConstraint.prototype.constructor=i.Physics.P2.DistanceConstraint,i.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},i.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),i.Physics.P2.GearConstraint.prototype.constructor=i.Physics.P2.GearConstraint,i.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t;var o={localOffsetB:s=[t.pxm(s[0]),t.pxm(s[1])],localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},i.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),i.Physics.P2.LockConstraint.prototype.constructor=i.Physics.P2.LockConstraint,i.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t;var h={localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},i.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),i.Physics.P2.PrismaticConstraint.prototype.constructor=i.Physics.P2.PrismaticConstraint,i.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},i.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),i.Physics.P2.RevoluteConstraint.prototype.constructor=i.Physics.P2.RevoluteConstraint,i.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},i.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&tthis.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},i.Tile.prototype.constructor=i.Tile,Object.defineProperty(i.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(i.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(i.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(i.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(i.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(i.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),i.Tilemap=function(t,e,s,n,r,o){this.game=t,this.key=e;var a=i.TilemapParser.parse(this.game,e,s,n,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},i.Tilemap.CSV=0,i.Tilemap.TILED_JSON=1,i.Tilemap.NORTH=0,i.Tilemap.EAST=1,i.Tilemap.SOUTH=2,i.Tilemap.WEST=3,i.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,s,n,r,o,a){if(void 0===t)return null;void 0===s&&(s=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===s&&(s=32),0===n&&(n=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof i.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===i.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),console.log("Tilesets: ",this.tilesets),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new i.Tileset(t,a,s,n,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y1)for(u=0;uthis.layers.length)return console.warn('Tilemap.createLayer: Invalid layer ID given: "'+t+'"'),void console.log("Layers: ",this.layers);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===s||s<=0?s=Math.min(this.game.height,this.layers[r].heightInPixels):s>this.game.height&&(s=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",s),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=n.add(new i.TilemapLayer(this.game,this,r,e,s));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,s,n,r,o){void 0===o&&(o=this.game.world);{if(null===this.getLayerIndex(t)){for(var a,h={name:t,x:0,y:0,width:e,height:s,widthInPixels:e*n,heightInPixels:s*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;cthis.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height),(l=new i.TilemapLayer(this.game,this,this.layers.length-1,d,p)).name=t,o.add(l)}console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t)}},getIndex:function(t,e){for(var i=0;ie)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n-1&&this.collideIndexes.splice(n,1)}for(var r=0;r0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e-1},removeTile:function(t,e,s){if(s=this.getLayer(s),t>=0&&t=0&&e=0&&e=0&&s-1?this.layers[n].data[s][e].setCollision(!0,!0,!0,!0):this.layers[n].data[s][e].resetCollision(),this.layers[n].dirty=!0,this.calculateFaces(n),this.layers[n].data[s][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(r=this.layers[s].height-1;r>=0;r--)for(o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r=0&&t=0&&ethis.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},i.Tilemap.prototype.constructor=i.Tilemap,Object.defineProperty(i.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),i.TilemapLayer=function(t,e,s,n,r){n|=0,r|=0,i.Sprite.call(this,t,0,0),this.map=e,this.index=s,this.layer=e.layers[s],this.canvas=i.CanvasPool.create(this,n,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas,null,this.game.resolution))),this.type=i.TILEMAPLAYER,this.physicsType=i.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!0,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this.tileOffset=new i.Point(this.layer.offsetX||0,this.layer.offsetY||0),this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=i.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},i.TilemapLayer.prototype=Object.create(i.Sprite.prototype),i.TilemapLayer.prototype.constructor=i.TilemapLayer,i.TilemapLayer.prototype.preUpdateCore=i.Component.Core.preUpdate,i.TilemapLayer.sharedCopyCanvas=null,i.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=i.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},i.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},i.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y},i.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.TilemapLayer.prototype.destroy=function(){i.CanvasPool.remove(this),i.Component.Destroy.prototype.destroy.call(this)},i.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},i.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},i.TilemapLayer.prototype.getTileOffsetX=function(){return this.tileOffset.x||(this.fixedToCamera?0:this.position.x)},i.TilemapLayer.prototype.getTileOffsetY=function(){return this.tileOffset.y||(this.fixedToCamera?0:this.position.y)},i.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},i.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},i.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},i.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},i.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},i.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},i.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},i.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a=0;m++,v--,f+=c){m>=h&&(m-=h);var _=this.layer.data[m];for(g=b,y=n-i,p=x;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var w=_[g];if(w&&!(w.index<0)){var T=w.index,P=u[T];void 0===P&&(P=this.resolveTileset(T)),w.alpha===d||this.debug||(o.globalAlpha=w.alpha,d=w.alpha),P?w.rotation||w.flipped?(o.save(),o.translate(p+w.centerX,f+w.centerY),o.rotate(w.rotation),w.flipped&&o.scale(-1,1),P.draw(o,-w.centerX,-w.centerY,T),o.restore()):P.draw(o,p,f,T):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),w.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},i.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},i.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},i.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)=0;s++,r--,e+=f){s>=d&&(s-=d);var T=this.layer.data[s];for(i=_,n=m-g,t=x;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var P=T[i];!P||P.index<0||!P.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),P.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),P.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),P.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),P.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(i.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),i.TilemapParser={INSERT_NULL:!1,parse:function(t,e,s,n,r,o){if(void 0===s&&(s=32),void 0===n&&(n=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(s,n,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===i.Tilemap.CSV)return this.parseCSV(e,a.data,s,n);if(!a.format||a.format===i.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,s,n){for(var r=this.getEmptyData(),o=[],a=(e=e.trim()).split("\n"),h=a.length,l=0,c=0;c>>0;r.data=h,delete r.encoding}else if(r.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+r.name+"'");continue}k={name:r.name,x:r.x,y:r.y,width:r.width,height:r.height,widthInPixels:r.width*t.tilewidth,heightInPixels:r.height*t.tileheight,alpha:r.opacity,offsetX:r.offsetx,offsetY:r.offsety,visible:r.visible,properties:{},indexes:[],callbacks:[],bodies:[]};r.properties&&(k.properties=r.properties);for(var c,u,d,p=0,f=[],g=[],m=0,a=r.data.length;m536870912)switch(A>2147483648&&(A-=2147483648,d+=4),A>1073741824&&(A-=1073741824,d+=2),A>536870912&&(A-=536870912,d+=1),d){case 5:c=Math.PI/2;break;case 6:c=Math.PI;break;case 3:c=3*Math.PI/2;break;case 4:c=0,u=!0;break;case 7:c=Math.PI/2,u=!0;break;case 2:c=Math.PI,u=!0;break;case 1:c=3*Math.PI/2,u=!0}A>0?((F=new i.Tile(k,A,p,g.length,t.tilewidth,t.tileheight)).rotation=c,F.flipped=u,0!==d&&(F.flippedVal=d),f.push(F)):i.TilemapParser.INSERT_NULL?f.push(null):f.push(new i.Tile(k,-1,p,g.length,t.tilewidth,t.tileheight)),++p===r.width&&(g.push(f),p=0,f=[])}k.data=g,s.push(k)}e.layers=s;for(var y=[],n=0;n=0&&n+1=this.firstgid&&t=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(t=0;t=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._total>0&&this._counter>=this._total&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},i.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1),void 0===r&&(r=null);var o,a=0,h=t,l=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);athis.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},i.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),this.resetParticle(n,o,a),!0},i.Particles.Arcade.Emitter.prototype.getNextParticle=function(){for(var t=this.length;t--;){var e=this.next();if(!e.exists)return e}return null},i.Particles.Arcade.Emitter.prototype.resetParticle=function(t,e,i){var s=this.game.rnd;t.reset(e,i),t.angle=0,t.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(t):this.particleSendToBack&&this.sendToBack(t),this.autoScale?t.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?t.scale.set(s.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y?t.scale.set(s.realInRange(this._minParticleScale.x,this._maxParticleScale.x),s.realInRange(this._minParticleScale.y,this._maxParticleScale.y)):t.scale.set(this._minParticleScale.x,this._minParticleScale.y),this.autoAlpha?t.setAlphaData(this.alphaData):t.alpha=s.realInRange(this.minParticleAlpha,this.maxParticleAlpha),t.blendMode=this.blendMode;var n=t.body;n.updateBounds(),n.bounce.copyFrom(this.bounce),n.drag.copyFrom(this.particleDrag),null!=this.minAngle&&null!=this.maxAngle?this.game.physics.arcade.velocityFromAngle(this.minAngle===this.maxAngle?this.minAngle:s.between(this.minAngle,this.maxAngle),this.minSpeed===this.maxSpeed?this.minSpeed:s.between(this.minSpeed,this.maxSpeed),n.velocity):(n.velocity.x=s.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),n.velocity.y=s.between(this.minParticleSpeed.y,this.maxParticleSpeed.y)),n.angularVelocity=s.between(this.minRotation,this.maxRotation),n.gravity.copyFrom(this.gravity),n.angularDrag=this.angularDrag,t.onEmit()},i.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),i.Group.prototype.destroy.call(this,!0,!1)},i.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},i.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},i.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},i.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},i.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,s,n,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=0),void 0===n&&(n=i.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,s>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},s,n);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},i.Particles.Arcade.Emitter.prototype.setScale=function(t,e,s,n,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=1),void 0===n&&(n=1),void 0===r&&(r=0),void 0===o&&(o=i.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,s),this._maxParticleScale.set(e,n),this.autoScale=!1,r>0&&(t!==e||s!==n)){var h={x:t,y:s},l=this.game.make.tween(h).to({x:e,y:n},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},i.Particles.Arcade.Emitter.prototype.setAngle=function(t,e,i,s){return this.minAngle=t,this.maxAngle=e,null!=i&&(this.minSpeed=i),null!=s&&(this.maxSpeed=s),this},i.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"gravity",{get:function(){return this._gravity},set:function(t){"number"==typeof t?this._gravity.y=t:this._gravity=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"id",{get:function(){return this._id}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"output",{get:function(){return 1e3*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"lifespanOutput",{get:function(){return(0===this.lifespan?1/0:this.lifespan)*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"remainder",{get:function(){return this.maxParticles-this.lifespanOutput}}),i.Weapon=function(t,e){i.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new i.Rectangle(0,0,1,1),this.fireAngle=i.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new i.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=i.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=i.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new i.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new i.Signal,this.onKill=new i.Signal,this.onFireLimit=new i.Signal,this.trackedSprite=null,this.trackedPointer=null,this.multiFire=!1,this._hasFired=!1,this.trackRotation=!1,this.trackOffset=new i.Point,this._nextFire=0,this._tempNextFire=0,this._rotatedPoint=new i.Point},i.Weapon.prototype=Object.create(i.Plugin.prototype),i.Weapon.prototype.constructor=i.Weapon,i.Weapon.KILL_NEVER=0,i.Weapon.KILL_LIFESPAN=1,i.Weapon.KILL_DISTANCE=2,i.Weapon.KILL_WEAPON_BOUNDS=3,i.Weapon.KILL_CAMERA_BOUNDS=4,i.Weapon.KILL_WORLD_BOUNDS=5,i.Weapon.KILL_STATIC_BOUNDS=6,i.Weapon.prototype.createBullets=function(t,e,s,n){return void 0===t&&(t=1),void 0===n&&(n=this.game.world),this.bullets&&!this.bullets.game&&(this.bullets=null),this.bullets||(this.bullets=this.game.add.physicsGroup(i.Physics.ARCADE,n),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,s),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=s),this},i.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},i.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},i.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},i.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},i.Weapon.prototype.update=function(){this._bulletKillType===i.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},i.Weapon.prototype.postRender=function(){this.multiFire&&this._hasFired&&(this._hasFired=!1,this._nextFire=this._tempNextFire)},i.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},i.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},i.Weapon.prototype.fireMany=function(t,e){this.multiFire=!0;var i=[],s=this;return e||this.trackedSprite||this.trackedPointer?t.forEach(function(t){i.push(s.fire(e,null,null,t.x,t.y))}):t.forEach(function(t){i.push(s.fire(t))}),i},i.Weapon.prototype.fireOffset=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.fire(null,null,null,t,e)},i.Weapon.prototype.fire=function(t,e,s,n,r){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game.time.now0&&this.shots===this.fireLimit)return null;var o=this.bulletSpeed;0!==this.bulletSpeedVariance&&(o+=i.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.worldRotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(o+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y)),void 0!==n&&(this.fireFrom.x+=n),void 0!==r&&(this.fireFrom.y+=r);var a=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,h=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,l=this.trackRotation?this.trackedSprite.angle:this.fireAngle;null!==e&&null!==s&&(l=this.game.math.radToDeg(Math.atan2(s-h,e-a))),0!==this.bulletAngleVariance&&(l+=i.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var c=0,u=0;0===l||180===l?c=Math.cos(this.game.math.degToRad(l))*o:90===l||270===l?u=Math.sin(this.game.math.degToRad(l))*o:(c=Math.cos(this.game.math.degToRad(l))*o,u=Math.sin(this.game.math.degToRad(l))*o);var d=null;if(this.autoExpandBulletsGroup?(d=this.bullets.getFirstExists(!1,!0,a,h,this.bulletKey,this.bulletFrame)).data.bulletManager=this:d=this.bullets.getFirstExists(!1),d){if(d.reset(a,h),d.data.fromX=a,d.data.fromY=h,d.data.killType=this.bulletKillType,d.data.killDistance=this.bulletKillDistance,d.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===i.Weapon.KILL_LIFESPAN&&(d.lifespan=this.bulletLifespan),d.angle=l+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===d.animations.getAnimation(this.bulletAnimation)){var p=this.anims[this.bulletAnimation];d.animations.add(p.name,p.frames,p.frameRate,p.loop,p.useNumericIndex)}d.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(d.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(d.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);d.data.bodyDirty&&(this._data.customBody&&d.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),d.body.collideWorldBounds=this.bulletCollideWorldBounds,d.data.bodyDirty=!1),d.body.velocity.set(c,u),d.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y);var f=0;if(0!==this.bulletSpeedVariance){var g=this.fireRate;(g+=i.Math.between(-this.fireRateVariance,this.fireRateVariance))<0&&(g=0),f=this.game.time.now+g}else f=this.game.time.now+this.fireRate;this.multiFire?this._hasFired||(this._hasFired=!0,this._tempNextFire=f,this.shots++):(this._nextFire=f,this.shots++),this.onFire.dispatch(d,this,o),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return d},i.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},i.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},i.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},i.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},i.Weapon.prototype.setBulletFrames=function(t,e,s,n){return void 0===s&&(s=!0),void 0===n&&(n=!1),this.bulletFrames=i.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=s,this.bulletFrameRandom=n,this},i.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},i.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(i.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets&&(this.bullets.classType=this._bulletClass)}}),Object.defineProperty(i.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case i.Weapon.KILL_STATIC_BOUNDS:case i.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case i.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case i.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(i.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(i.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(i.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),i.Bullet=function(t,e,s,n,r){i.Sprite.call(this,t,e,s,n,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},i.Bullet.prototype=Object.create(i.Sprite.prototype),i.Bullet.prototype.constructor=i.Bullet,i.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},i.Bullet.prototype.update=function(){this.exists&&(this.data.killType>i.Weapon.KILL_LIFESPAN&&(this.data.killType===i.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=this.body.velocity.atan()),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},i.Video=function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=i.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new i.Signal,this.onChangeSource=new i.Signal,this.onComplete=new i.Signal,this.onAccess=new i.Signal,this.onError=new i.Signal,this.onTimeout=new i.Signal,this.onTouchUnlock=new i.Signal,this.playWhenUnlocked=!0,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._pendingChangeSource=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var n=this.game.cache.getVideo(e);n.isBlob?this.createVideoFromBlob(n.data):this.video=n.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else s&&this.createVideoFromURL(s,!1);this.video&&!s?(this.baseTexture=new PIXI.BaseTexture(this.video,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(i.Cache.DEFAULT.baseTexture.source,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new i.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,i.BitmapData&&(this.snapshot=new i.BitmapData(this.game,"",this.width,this.height)),this.game.device.needsTouchUnlock()?this.setTouchLock():n&&(n.locked=!1)},i.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return this._pendingChangeSource?this:(void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this)},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming)},setTouchLock:function(){this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.playWhenUnlocked&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return this.onTouchUnlock.dispatch(this),!0},grab:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null!==this.snapshot)return t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot;console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable")},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(i.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(i.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(i.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(i.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(i.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(i.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(i.Video.prototype,"playing",{get:function(){return!!this.video&&!(this.video.paused&&this.video.ended)}}),i.Video.prototype.constructor=i.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=i.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=i.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new i.Matrix),PIXI.TextureSilentFail=!0,PIXI.canUseNewCanvasBlendModes=function(){return i.Device.canUseMultiply},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=i),exports.Phaser=i):"undefined"!=typeof define&&define.amd?define("Phaser",e.Phaser=i):e.Phaser=i,i}.call(this); +//# sourceMappingURL=phaser.map \ No newline at end of file diff --git a/Digital Assignment 3/sources.txt b/Digital Assignment 3/sources.txt new file mode 100644 index 000000000..5767df3a2 --- /dev/null +++ b/Digital Assignment 3/sources.txt @@ -0,0 +1 @@ +https://freeclipartimage.com//storage/upload/star-clip-art/star-clip-art-77.png \ No newline at end of file diff --git a/Digital Assignment 4/assets/Arrow.png b/Digital Assignment 4/assets/Arrow.png new file mode 100644 index 000000000..47ac1568c Binary files /dev/null and b/Digital Assignment 4/assets/Arrow.png differ diff --git a/Digital Assignment 4/assets/Background.png b/Digital Assignment 4/assets/Background.png new file mode 100644 index 000000000..67728fb77 Binary files /dev/null and b/Digital Assignment 4/assets/Background.png differ diff --git a/Digital Assignment 4/assets/Husky.png b/Digital Assignment 4/assets/Husky.png new file mode 100644 index 000000000..971469cf0 Binary files /dev/null and b/Digital Assignment 4/assets/Husky.png differ diff --git a/Digital Assignment 4/assets/Play.png b/Digital Assignment 4/assets/Play.png new file mode 100644 index 000000000..ba386c357 Binary files /dev/null and b/Digital Assignment 4/assets/Play.png differ diff --git a/Digital Assignment 4/index.html b/Digital Assignment 4/index.html new file mode 100644 index 000000000..584fd9104 --- /dev/null +++ b/Digital Assignment 4/index.html @@ -0,0 +1,156 @@ + + + + + Digital Assignment 4 + + + + + + + +
+
+

+
    +
  • Game is unfinished. This will be a racing game with animals having special powers.
  • +
  • Directions
  • +
  • 1. Select one of the arrow's to choose a character. You are allowed to reselect your character.
  • +
  • 2. Once a character is selected click on the play button and the game begins.
  • +
  • 3. Move your character with the arrow keys and move to the end zone on the right.
  • +
+ + +
+ + diff --git a/Digital Assignment 4/js/main.js b/Digital Assignment 4/js/main.js new file mode 100644 index 000000000..000ae4520 --- /dev/null +++ b/Digital Assignment 4/js/main.js @@ -0,0 +1,386 @@ +"use strict"; + +window.onload = function() +{ + // You can copy-and-paste the code from any of the examples at http://examples.phaser.io here. + // You will need to change the fourth parameter to "new Phaser.Game()" from + // 'phaser-example' to 'game', which is the id of the HTML element where we + // want the game to go. + // The assets (and code) can be found at: https://github.com/photonstorm/phaser/tree/master/examples/assets + // You will need to change the paths you pass to "game.load.image()" or any other + // loading functions to reflect where you are putting the assets. + // All loading functions will typically all be found inside "preload()". + + // mods by Patrick OReilly + // twitter: @pato_reilly + + var game = new Phaser.Game(900, 600, Phaser.CANVAS, 'game', { preload: preload, create: create, update: update, render: render }); + + function preload() + { + game.load.spritesheet('button', 'assets/Play.png', 200, 90); + game.load.spritesheet('arrow', 'assets/Arrow.png', 101, 50); + game.load.image('background','assets/Background.png'); + game.load.spritesheet('husky','assets/Husky.png', 90, 58, 3); + + } + + var button1; + var button2; + var button3; + var button4; + var button5; + var buttonS; + + var husky1; + var husky2; + var husky3; + var husky4; + var husky5; + + /* + var bound1; + var bound2; + var bound3; + var bound4; + var bound5; + */ + + var player; + var cursors; + var input = -1; + var rng = Math.floor(Math.random() * 5) + 1; + + function create() + { + game.add.tileSprite(0, 0, 1800, 600, 'background'); + + game.world.setBounds(0, 0, 1800, 500); + + game.physics.startSystem(Phaser.Physics.P2JS); + + husky1 = game.add.sprite(150, 50, 'husky', 10); + husky2 = game.add.sprite(150, 150, 'husky', 10); + husky3 = game.add.sprite(150, 250, 'husky', 10); + husky4 = game.add.sprite(150, 350, 'husky', 10); + husky5 = game.add.sprite(150, 450, 'husky', 10); + + husky1.animations.add('wag'); + husky1.animations.play('wag', 8, true); + husky2.animations.add('wag'); + husky2.animations.play('wag', 8, true); + husky3.animations.add('wag'); + husky3.animations.play('wag', 8, true); + husky4.animations.add('wag'); + husky4.animations.play('wag', 8, true); + husky5.animations.add('wag'); + husky5.animations.play('wag', 8, true); + + game.physics.p2.enable(husky1); + game.physics.p2.enable(husky2); + game.physics.p2.enable(husky3); + game.physics.p2.enable(husky4); + game.physics.p2.enable(husky5); + + //bound1 = new Phaser.Rectangle(100, 0, 1700, 100); + //bound2 = new Phaser.Rectangle(100, 100, 1700, 100); + //bound3 = new Phaser.Rectangle(100, 200, 1700, 100); + //bound4 = new Phaser.Rectangle(100, 300, 1700, 100); + //bound5 = new Phaser.Rectangle(100, 400, 1700, 100); + + cursors = game.input.keyboard.createCursorKeys(); + + // new Button(game [, x] [, y] [, key] [, callback] [, callbackContext] [, overFrame] [, outFrame] [, downFrame] [, upFrame]) + button1 = game.add.button(0, 25, 'arrow', actionOnClick1, this, 0, 1, 0); + button2 = game.add.button(0, 125, 'arrow', actionOnClick2, this, 0, 1, 0); + button3 = game.add.button(0, 225, 'arrow', actionOnClick3, this, 0, 1, 0); + button4 = game.add.button(0, 325, 'arrow', actionOnClick4, this, 0, 1, 0); + button5 = game.add.button(0, 425, 'arrow', actionOnClick5, this, 0, 1, 0); + buttonS = game.add.button(150, 510, 'button', click_play, this, 0, 0, 1, 0); + + button1.onInputOver.add(over, this); + button1.onInputOut.add(out, this); + button1.onInputUp.add(up, this); + + button2.onInputOver.add(over, this); + button2.onInputOut.add(out, this); + button2.onInputUp.add(up, this); + + button3.onInputOver.add(over, this); + button3.onInputOut.add(out, this); + button3.onInputUp.add(up, this); + + button4.onInputOver.add(over, this); + button4.onInputOut.add(out, this); + button4.onInputUp.add(up, this); + + button5.onInputOver.add(over, this); + button5.onInputOut.add(out, this); + button5.onInputUp.add(up, this); + + /* + husky1.inputEnabled = true; + husky1.input.boundsRect = bound1; + husky2.input.boundsRect = bound2; + husky3.input.boundsRect = bound3; + husky4.input.boundsRect = bound4; + husky5.input.boundsRect = bound5; + */ + + } + + function update() + { + if (player != null) + { + player.body.setZeroVelocity(); + + if (cursors.up.isDown) + { + player.body.moveUp(300) + } + else if (cursors.down.isDown) + { + player.body.moveDown(300); + } + + if (cursors.left.isDown) + { + player.body.velocity.x = -300; + } + else if (cursors.right.isDown) + { + player.body.moveRight(300); + } + } + } + + function render() + { + //game.debug.cameraInfo(game.camera, 32, 32); + } + + function up() + { + console.log('button up', arguments); + } + + function over() + { + console.log('button over'); + } + + function out() + { + console.log('button out'); + } + + function actionOnClick1() + { + console.log('click 1'); + + button1.setFrames(1, 0, 0, 0); + + switch (input) + { + case 2: + button2.setFrames(0, 1, 0); + button2.inputEnabled = true; + break; + case 3: + button3.setFrames(0, 1, 0); + button3.inputEnabled = true; + break; + case 4: + button4.setFrames(0, 1, 0); + button4.inputEnabled = true; + break; + case 5: + button5.setFrames(0, 1, 0); + button5.inputEnabled = true; + break; + default: + break; + } + + button1.inputEnabled = false; + input = 1; + } + + function actionOnClick2() + { + console.log('click 2'); + + button2.setFrames(1, 0, 0, 0); + + switch (input) + { + case 1: + button1.setFrames(0, 1, 0); + button1.inputEnabled = true; + break; + case 3: + button3.setFrames(0, 1, 0); + button3.inputEnabled = true; + break; + case 4: + button4.setFrames(0, 1, 0); + button4.inputEnabled = true; + break; + case 5: + button5.setFrames(0, 1, 0); + button5.inputEnabled = true; + break; + default: + break; + } + + button2.inputEnabled = false; + input = 2; + } + + function actionOnClick3() + { + console.log('click 3'); + + button3.setFrames(1, 0, 0, 0); + + switch (input) + { + case 1: + button1.setFrames(0, 1, 0); + button1.inputEnabled = true; + break; + case 2: + button2.setFrames(0, 1, 0); + button2.inputEnabled = true; + break; + case 4: + button4.setFrames(0, 1, 0); + button4.inputEnabled = true; + break; + case 5: + button5.setFrames(0, 1, 0); + button5.inputEnabled = true; + break; + default: + break; + } + + button3.inputEnabled = false; + input = 3; + } + + function actionOnClick4() + { + console.log('click 4'); + + button4.setFrames(1, 0, 0, 0); + + switch (input) + { + case 1: + button1.setFrames(0, 1, 0); + button1.inputEnabled = true; + break; + case 2: + button2.setFrames(0, 1, 0); + button2.inputEnabled = true; + break; + case 3: + button3.setFrames(0, 1, 0); + button3.inputEnabled = true; + break; + case 5: + button5.setFrames(0, 1, 0); + button5.inputEnabled = true; + break; + default: + break; + } + + button4.inputEnabled = false; + input = 4; + } + + function actionOnClick5() + { + console.log('click 5'); + + button5.setFrames(1, 0, 0, 0); + + switch (input) + { + case 1: + button1.setFrames(0, 1, 0); + button1.inputEnabled = true; + break; + case 2: + button2.setFrames(0, 1, 0); + button2.inputEnabled = true; + break; + case 3: + button3.setFrames(0, 1, 0); + button3.inputEnabled = true; + break; + case 4: + button4.setFrames(0, 1, 0); + button4.inputEnabled = true; + break; + default: + break; + } + + button5.inputEnabled = false; + input = 5; + } + + function click_play() + { + console.log("Play"); + + if (input == -1) + { + //Do nothing. + } + else + { + switch (input) + { + case 1: + player = husky1; + break; + case 2: + player = husky2; + break; + case 3: + player = husky3; + break; + case 4: + player = husky4; + break; + case 5: + player = husky5; + break; + default: + break; + } + + buttonS.inputEnabled = false; + buttonS.visible = false; + // Notice that the sprite doesn't have any momentum at all, + // it's all just set by the camera follow type. + // 0.1 is the amount of linear interpolation to use. + // The smaller the value, the smooth the camera (and the longer it takes to catch up) + game.camera.follow(player, Phaser.Camera.FOLLOW_LOCKON, 0.1, 0.1); + player.body.fixedRotation = true; + + husky1.body.moveRight(300); + husky2.body.moveRight(300); + husky3.body.moveRight(300); + husky4.body.moveRight(300); + husky5.body.moveRight(300); + + } + } +}; \ No newline at end of file diff --git a/Digital Assignment 4/js/phaser.js b/Digital Assignment 4/js/phaser.js new file mode 100644 index 000000000..3bac171a7 --- /dev/null +++ b/Digital Assignment 4/js/phaser.js @@ -0,0 +1,107825 @@ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +* +* @overview +* +* Phaser - http://phaser.io +* +* v2.10.0 "2018-01-18" - Built: Thu Jan 18 2018 16:35:03 +* +* By Richard Davey http://www.photonstorm.com @photonstorm +* +* Phaser is a fun, free and fast 2D game framework for making HTML5 games +* for desktop and mobile web browsers, supporting Canvas and WebGL rendering. +* +* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23 +* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe +* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com +* +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate. +* +* Follow development at http://phaser.io and on our forum +* +* "If you want your children to be intelligent, read them fairy tales." +* "If you want them to be more intelligent, read them more fairy tales." +* -- Albert Einstein +*/ + +/** + * The MIT License (MIT) + * + * Copyright (c) 2015 p2.js authors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=0 && s<=1 && t>=0 && t<=1); +}; + + +},{"./Scalar":4}],2:[function(_dereq_,module,exports){ +module.exports = Point; + +/** + * Point related functions + * @class Point + */ +function Point(){}; + +/** + * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. + * @static + * @method area + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +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 = []; + +/** + * Check if three points are collinear + * @method collinear + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. + * @return {Boolean} + */ +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 angle < thresholdAngle; + } +}; + +Point.sqdist = function(a,b){ + var dx = b[0] - a[0]; + var dy = b[1] - a[1]; + return dx * dx + dy * dy; +}; + +},{}],3:[function(_dereq_,module,exports){ +var Line = _dereq_("./Line") +, Point = _dereq_("./Point") +, Scalar = _dereq_("./Scalar") + +module.exports = Polygon; + +/** + * Polygon class. + * @class Polygon + * @constructor + */ +function Polygon(){ + + /** + * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] + * @property vertices + * @type {Array} + */ + this.vertices = []; +} + +/** + * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. + * @method at + * @param {Number} i + * @return {Array} + */ +Polygon.prototype.at = function(i){ + var v = this.vertices, + s = v.length; + return v[i < 0 ? i % s + s : i % s]; +}; + +/** + * Get first vertex + * @method first + * @return {Array} + */ +Polygon.prototype.first = function(){ + return this.vertices[0]; +}; + +/** + * Get last vertex + * @method last + * @return {Array} + */ +Polygon.prototype.last = function(){ + return this.vertices[this.vertices.length-1]; +}; + +/** + * Clear the polygon data + * @method clear + * @return {Array} + */ +Polygon.prototype.clear = function(){ + this.vertices.length = 0; +}; + +/** + * Append points "from" to "to"-1 from an other polygon "poly" onto this one. + * @method append + * @param {Polygon} poly The polygon to get points from. + * @param {Number} from The vertex index in "poly". + * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. + * @return {Array} + */ +Polygon.prototype.append = function(poly,from,to){ + if(typeof(from) == "undefined") throw new Error("From is not given!"); + if(typeof(to) == "undefined") throw new Error("To is not given!"); + + if(to-1 < from) throw new Error("lol1"); + if(to > poly.vertices.length) throw new Error("lol2"); + if(from < 0) throw new Error("lol3"); + + for(var i=from; i v[br][0])) { + br = i; + } + } + + // reverse poly if clockwise + if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { + this.reverse(); + } +}; + +/** + * Reverse the vertices in the polygon + * @method 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; +}; + +/** + * Check if a point in the polygon is a reflex point + * @method isReflex + * @param {Number} i + * @return {Boolean} + */ +Polygon.prototype.isReflex = function(i){ + return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); +}; + +var tmpLine1=[], + tmpLine2=[]; + +/** + * Check if two vertices in the polygon can see each other + * @method canSee + * @param {Number} a Vertex index 1 + * @param {Number} b Vertex index 2 + * @return {Boolean} + */ +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) { // for each edge + if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges + 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))) { // if diag intersects an edge + 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) < dist) { // if edge is blocking visibility to b + return false; + } + } + } + + return true; +}; + +/** + * Copy the polygon from vertex i to vertex j. + * @method copy + * @param {Number} i + * @param {Number} j + * @param {Polygon} [targetPoly] Optional target polygon to save in. + * @return {Polygon} The resulting copy. + */ +Polygon.prototype.copy = function(i,j,targetPoly){ + var p = targetPoly || new Polygon(); + p.clear(); + if (i < j) { + // Insert all vertices from i to j + for(var k=i; k<=j; k++) + p.vertices.push(this.vertices[k]); + + } else { + + // Insert vertices 0 to j + for(var k=0; k<=j; k++) + p.vertices.push(this.vertices[k]); + + // Insert vertices i to end + for(var k=i; k 0) + return this.slice(edges); + else + return [this]; +}; + +/** + * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. + * @method slice + * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() + * @return {Array} + */ +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; i maxlevel){ + console.warn("quickDecomp: max level ("+maxlevel+") reached."); + return result; + } + + for (var i = 0; i < this.vertices.length; ++i) { + if (poly.isReflex(i)) { + reflexVertices.push(poly.vertices[i]); + upperDist = lowerDist = Number.MAX_VALUE; + + + for (var j = 0; j < this.vertices.length; ++j) { + if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge + p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection + if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly + d = Point.sqdist(poly.vertices[i], p); + if (d < lowerDist) { // keep only the closest intersection + lowerDist = d; + lowerInt = p; + lowerIndex = j; + } + } + } + if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); + if (Point.left(poly.at(i - 1), poly.at(i), p)) { + d = Point.sqdist(poly.vertices[i], p); + if (d < upperDist) { + upperDist = d; + upperInt = p; + upperIndex = j; + } + } + } + } + + // if there are no vertices to connect to, choose a point in the middle + if (lowerIndex == (upperIndex + 1) % this.vertices.length) { + //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); + p[0] = (lowerInt[0] + upperInt[0]) / 2; + p[1] = (lowerInt[1] + upperInt[1]) / 2; + steinerPoints.push(p); + + if (i < upperIndex) { + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); + lowerPoly.append(poly, i, upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + if (lowerIndex != 0){ + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); + upperPoly.append(poly,lowerIndex,poly.vertices.length); + } + //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); + lowerPoly.append(poly,i,poly.vertices.length); + } + //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); + lowerPoly.append(poly,0,upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); + upperPoly.append(poly,lowerIndex,i+1); + } + } else { + // connect to the closest point within the triangle + //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); + + if (lowerIndex > upperIndex) { + upperIndex += this.vertices.length; + } + closestDist = Number.MAX_VALUE; + + if(upperIndex < lowerIndex){ + return result; + } + + for (var j = lowerIndex; j <= upperIndex; ++j) { + if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + d = Point.sqdist(poly.at(i), poly.at(j)); + if (d < closestDist) { + closestDist = d; + closestIndex = j % this.vertices.length; + } + } + } + + if (i < closestIndex) { + lowerPoly.append(poly,i,closestIndex+1); + if (closestIndex != 0){ + upperPoly.append(poly,closestIndex,v.length); + } + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + lowerPoly.append(poly,i,v.length); + } + lowerPoly.append(poly,0,closestIndex+1); + upperPoly.append(poly,closestIndex,i+1); + } + } + + // solve smallest poly first + if (lowerPoly.vertices.length < upperPoly.vertices.length) { + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } else { + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } + + return result; + } + } + result.push(this); + + return result; +}; + +/** + * Remove collinear points in the polygon. + * @method removeCollinearPoints + * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. + * @return {Number} The number of points removed + */ +Polygon.prototype.removeCollinearPoints = function(precision){ + var num = 0; + for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ + if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ + // Remove the middle point + this.vertices.splice(i%this.vertices.length,1); + i--; // Jump one point forward. Otherwise we may get a chain removal + num++; + } + } + return num; +}; + +},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){ +module.exports = Scalar; + +/** + * Scalar functions + * @class Scalar + */ +function Scalar(){} + +/** + * Check if two scalars are equal + * @static + * @method eq + * @param {Number} a + * @param {Number} b + * @param {Number} [precision] + * @return {Boolean} + */ +Scalar.eq = function(a,b,precision){ + precision = precision || 0; + return Math.abs(a-b) < precision; +}; + +},{}],5:[function(_dereq_,module,exports){ +module.exports = { + Polygon : _dereq_("./Polygon"), + Point : _dereq_("./Point"), +}; + +},{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){ +module.exports={ + "name": "p2", + "version": "0.7.1", + "description": "A JavaScript 2D physics engine.", + "author": "Stefan Hedman (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.5", + "grunt-contrib-jshint": "^0.11.2", + "grunt-contrib-nodeunit": "^0.4.1", + "grunt-contrib-uglify": "~0.4.0", + "grunt-contrib-watch": "~0.5.0", + "grunt-browserify": "~2.0.1", + "grunt-contrib-concat": "^0.4.0" + }, + "dependencies": { + "poly-decomp": "0.1.1" + } +} + +},{}],7:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = AABB; + +/** + * Axis aligned bounding box class. + * @class AABB + * @constructor + * @param {Object} [options] + * @param {Array} [options.upperBound] + * @param {Array} [options.lowerBound] + */ +function AABB(options){ + + /** + * The lower bound of the bounding box. + * @property lowerBound + * @type {Array} + */ + this.lowerBound = vec2.create(); + if(options && options.lowerBound){ + vec2.copy(this.lowerBound, options.lowerBound); + } + + /** + * The upper bound of the bounding box. + * @property upperBound + * @type {Array} + */ + this.upperBound = vec2.create(); + if(options && options.upperBound){ + vec2.copy(this.upperBound, options.upperBound); + } +} + +var tmp = vec2.create(); + +/** + * Set the AABB bounds from a set of points, transformed by the given position and angle. + * @method setFromPoints + * @param {Array} points An array of vec2's. + * @param {Array} position + * @param {number} angle + * @param {number} skinSize Some margin to be added to the AABB. + */ +AABB.prototype.setFromPoints = function(points, position, angle, skinSize){ + var l = this.lowerBound, + u = this.upperBound; + + if(typeof(angle) !== "number"){ + angle = 0; + } + + // Set to the first point + if(angle !== 0){ + vec2.rotate(l, points[0], angle); + } else { + vec2.copy(l, points[0]); + } + vec2.copy(u, l); + + // Compute cosines and sines just once + var cosAngle = Math.cos(angle), + sinAngle = Math.sin(angle); + for(var i = 1; i u[j]){ + u[j] = p[j]; + } + if(p[j] < l[j]){ + l[j] = p[j]; + } + } + } + + // Add offset + if(position){ + vec2.add(this.lowerBound, this.lowerBound, position); + vec2.add(this.upperBound, this.upperBound, position); + } + + if(skinSize){ + this.lowerBound[0] -= skinSize; + this.lowerBound[1] -= skinSize; + this.upperBound[0] += skinSize; + this.upperBound[1] += skinSize; + } +}; + +/** + * Copy bounds from an AABB to this AABB + * @method copy + * @param {AABB} aabb + */ +AABB.prototype.copy = function(aabb){ + vec2.copy(this.lowerBound, aabb.lowerBound); + vec2.copy(this.upperBound, aabb.upperBound); +}; + +/** + * Extend this AABB so that it covers the given AABB too. + * @method extend + * @param {AABB} aabb + */ +AABB.prototype.extend = function(aabb){ + // Loop over x and y + var i = 2; + while(i--){ + // Extend lower bound + var l = aabb.lowerBound[i]; + if(this.lowerBound[i] > l){ + this.lowerBound[i] = l; + } + + // Upper + var u = aabb.upperBound[i]; + if(this.upperBound[i] < u){ + this.upperBound[i] = u; + } + } +}; + +/** + * Returns true if the given AABB overlaps this AABB. + * @method overlaps + * @param {AABB} aabb + * @return {Boolean} + */ +AABB.prototype.overlaps = function(aabb){ + var l1 = this.lowerBound, + u1 = this.upperBound, + l2 = aabb.lowerBound, + u2 = aabb.upperBound; + + // l2 u2 + // |---------| + // |--------| + // l1 u1 + + 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])); +}; + +/** + * @method containsPoint + * @param {Array} point + * @return {boolean} + */ +AABB.prototype.containsPoint = function(point){ + var l = this.lowerBound, + u = this.upperBound; + return l[0] <= point[0] && point[0] <= u[0] && l[1] <= point[1] && point[1] <= u[1]; +}; + +/** + * Check if the AABB is hit by a ray. + * @method overlapsRay + * @param {Ray} ray + * @return {number} -1 if no hit, a number between 0 and 1 if hit. + */ +AABB.prototype.overlapsRay = function(ray){ + var t = 0; + + // ray.direction is unit direction vector of ray + var dirFracX = 1 / ray.direction[0]; + var dirFracY = 1 / ray.direction[1]; + + // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner + var t1 = (this.lowerBound[0] - ray.from[0]) * dirFracX; + var t2 = (this.upperBound[0] - ray.from[0]) * dirFracX; + var t3 = (this.lowerBound[1] - ray.from[1]) * dirFracY; + var t4 = (this.upperBound[1] - ray.from[1]) * dirFracY; + + var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4))); + var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4))); + + // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us + if (tmax < 0){ + //t = tmax; + return -1; + } + + // if tmin > tmax, ray doesn't intersect AABB + if (tmin > tmax){ + //t = tmax; + return -1; + } + + return tmin; +}; +},{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Body = _dereq_('../objects/Body'); + +module.exports = Broadphase; + +/** + * Base class for broadphase implementations. + * @class Broadphase + * @constructor + */ +function Broadphase(type){ + + this.type = type; + + /** + * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). + * @property result + * @type {Array} + */ + this.result = []; + + /** + * The world to search for collision pairs in. To change it, use .setWorld() + * @property world + * @type {World} + * @readOnly + */ + this.world = null; + + /** + * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE. + * @property {Number} boundingVolumeType + */ + this.boundingVolumeType = Broadphase.AABB; +} + +/** + * Axis aligned bounding box type. + * @static + * @property {Number} AABB + */ +Broadphase.AABB = 1; + +/** + * Bounding circle type. + * @static + * @property {Number} BOUNDING_CIRCLE + */ +Broadphase.BOUNDING_CIRCLE = 2; + +/** + * Set the world that we are searching for collision pairs in. + * @method setWorld + * @param {World} world + */ +Broadphase.prototype.setWorld = function(world){ + this.world = world; +}; + +/** + * Get all potential intersecting body pairs. + * @method getCollisionPairs + * @param {World} world The world to search in. + * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). + */ +Broadphase.prototype.getCollisionPairs = function(world){}; + +var dist = vec2.create(); + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.aabbCheck = function(bodyA, bodyB){ + return bodyA.getAABB().overlaps(bodyB.getAABB()); +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether two bodies are allowed to collide at all. + * @method canCollide + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.canCollide = function(bodyA, bodyB){ + var KINEMATIC = Body.KINEMATIC; + var STATIC = Body.STATIC; + + // Cannot collide static bodies + if(bodyA.type === STATIC && bodyB.type === STATIC){ + return false; + } + + // Cannot collide static vs kinematic bodies + if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) || + (bodyA.type === STATIC && bodyB.type === KINEMATIC)){ + return false; + } + + // Cannot collide kinematic vs kinematic + if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){ + return false; + } + + // Cannot collide both sleeping bodies + if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ + return false; + } + + // Cannot collide if one is static and the other is sleeping + if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === STATIC) || + (bodyB.sleepState === Body.SLEEPING && bodyA.type === STATIC)){ + return false; + } + + return true; +}; + +Broadphase.NAIVE = 1; +Broadphase.SAP = 2; + +},{"../math/vec2":30,"../objects/Body":31}],9:[function(_dereq_,module,exports){ +var Circle = _dereq_('../shapes/Circle'), + Plane = _dereq_('../shapes/Plane'), + Shape = _dereq_('../shapes/Shape'), + Particle = _dereq_('../shapes/Particle'), + Broadphase = _dereq_('../collision/Broadphase'), + vec2 = _dereq_('../math/vec2'); + +module.exports = NaiveBroadphase; + +/** + * Naive broadphase implementation. Does N^2 tests. + * + * @class NaiveBroadphase + * @constructor + * @extends Broadphase + */ +function NaiveBroadphase(){ + Broadphase.call(this, Broadphase.NAIVE); +} +NaiveBroadphase.prototype = new Broadphase(); +NaiveBroadphase.prototype.constructor = NaiveBroadphase; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +NaiveBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = world.bodies, + result = this.result; + + result.length = 0; + + for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ + var bi = bodies[i]; + + for(var j=0; j pos0 && pos < pos1){ + // We got contact! + + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape); + + vec2.scale(c.normalA, orthoDist, -1); + vec2.normalize(c.normalA, c.normalA); + + vec2.scale( c.contactPointA, c.normalA, circleRadius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + sub(c.contactPointB, projectedPoint, lineOffset); + add(c.contactPointB, c.contactPointB, lineOffset); + sub(c.contactPointB, c.contactPointB, lineBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; + } + } + + // Add corner + verts[0] = worldVertex0; + verts[1] = worldVertex1; + + for(var i=0; i 0){ + for(var i=0; i Math.pow(r,2)){ + return 0; + } + + if(justTest){ + return true; + } + + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + 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; +}; + +/** + * Plane/Convex Narrowphase + * @method planeConvex + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} convexBody + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = +Narrowphase.prototype[Shape.PLANE | Shape.BOX] = +Narrowphase.prototype.planeConvex = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + convexBody, + convexShape, + convexOffset, + convexAngle, + justTest +){ + var worldVertex = tmp1, + worldNormal = tmp2, + dist = tmp3; + + var numReported = 0; + vec2.rotate(worldNormal, yAxis, planeAngle); + + for(var i=0; i!==convexShape.vertices.length; i++){ + var v = convexShape.vertices[i]; + vec2.rotate(worldVertex, v, convexAngle); + add(worldVertex, worldVertex, convexOffset); + + sub(dist, worldVertex, planeOffset); + + if(dot(dist,worldNormal) <= 0){ + + if(justTest){ + return true; + } + + // Found vertex + numReported++; + + var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); + + sub(dist, worldVertex, planeOffset); + + vec2.copy(c.normalA, worldNormal); + + var d = dot(dist, c.normalA); + vec2.scale(dist, c.normalA, d); + + // rj is from convex center to contact + sub(c.contactPointB, worldVertex, convexBody.position); + + + // ri is from plane center to contact + sub( c.contactPointA, worldVertex, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + this.contactEquations.push(c); + + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numReported){ + this.frictionEquations.push(this.createFrictionFromAverage(numReported)); + } + } + + return numReported; +}; + +/** + * Narrowphase for particle vs plane + * @method particlePlane + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = +Narrowphase.prototype.particlePlane = function( + particleBody, + particleShape, + particleOffset, + particleAngle, + planeBody, + planeShape, + planeOffset, + planeAngle, + justTest +){ + var dist = tmp1, + worldNormal = tmp2; + + planeAngle = planeAngle || 0; + + sub(dist, particleOffset, planeOffset); + vec2.rotate(worldNormal, yAxis, planeAngle); + + var d = dot(dist, worldNormal); + + if(d > 0){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape); + + vec2.copy(c.normalA, worldNormal); + vec2.scale( dist, c.normalA, d ); + // dist is now the distance vector in the normal direction + + // ri is the particle position projected down onto the plane, from the plane center + sub( c.contactPointA, particleOffset, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + // rj is from the body center to the particle center + sub( c.contactPointB, particleOffset, particleBody.position ); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + return 1; +}; + +/** + * Circle/Particle Narrowphase + * @method circleParticle + * @param {Body} circleBody + * @param {Circle} circleShape + * @param {Array} circleOffset + * @param {Number} circleAngle + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = +Narrowphase.prototype.circleParticle = function( + circleBody, + circleShape, + circleOffset, + circleAngle, + particleBody, + particleShape, + particleOffset, + particleAngle, + justTest +){ + var dist = tmp1; + + sub(dist, particleOffset, circleOffset); + if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape); + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + // Vector from circle to contact point is the normal times the circle radius + vec2.scale(c.contactPointA, c.normalA, circleShape.radius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + // Vector from particle center to contact point is zero + sub(c.contactPointB, particleOffset, particleBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; +}; + +var planeCapsule_tmpCircle = new Circle({ radius: 1 }), + planeCapsule_tmp1 = vec2.create(), + planeCapsule_tmp2 = vec2.create(), + planeCapsule_tmp3 = vec2.create(); + +/** + * @method planeCapsule + * @param {Body} planeBody + * @param {Circle} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} capsuleBody + * @param {Particle} capsuleShape + * @param {Array} capsuleOffset + * @param {Number} capsuleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = +Narrowphase.prototype.planeCapsule = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + capsuleBody, + capsuleShape, + capsuleOffset, + capsuleAngle, + justTest +){ + var end1 = planeCapsule_tmp1, + end2 = planeCapsule_tmp2, + circle = planeCapsule_tmpCircle, + dst = planeCapsule_tmp3; + + // Compute world end positions + vec2.set(end1, -capsuleShape.length/2, 0); + vec2.rotate(end1,end1,capsuleAngle); + add(end1,end1,capsuleOffset); + + vec2.set(end2, capsuleShape.length/2, 0); + vec2.rotate(end2,end2,capsuleAngle); + add(end2,end2,capsuleOffset); + + circle.radius = capsuleShape.radius; + + var enableFrictionBefore; + + // Temporarily turn off friction + if(this.enableFrictionReduction){ + enableFrictionBefore = this.enableFriction; + this.enableFriction = false; + } + + // Do Narrowphase as two circles + var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest), + numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest); + + // Restore friction + if(this.enableFrictionReduction){ + this.enableFriction = enableFrictionBefore; + } + + if(justTest){ + return numContacts1 || numContacts2; + } else { + var numTotal = numContacts1 + numContacts2; + if(this.enableFrictionReduction){ + if(numTotal){ + this.frictionEquations.push(this.createFrictionFromAverage(numTotal)); + } + } + return numTotal; + } +}; + +/** + * Creates ContactEquations and FrictionEquations for a collision. + * @method circlePlane + * @param {Body} bi The first body that should be connected to the equations. + * @param {Circle} si The circle shape participating in the collision. + * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. + * @param {Body} bj The second body that should be connected to the equations. + * @param {Plane} sj The Plane shape that is participating + * @param {Array} xj Extra offset for the plane shape. + * @param {Number} aj Extra angle to apply to the plane + */ +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, // Offset from body center, rotated! + planeBody = bj, + shapeB = sj, + planeOffset = xj, + planeAngle = aj; + + planeAngle = planeAngle || 0; + + // Vector from plane to circle + var planeToCircle = tmp1, + worldNormal = tmp2, + temp = tmp3; + + sub(planeToCircle, circleOffset, planeOffset); + + // World plane normal + vec2.rotate(worldNormal, yAxis, planeAngle); + + // Normal direction distance + var d = dot(worldNormal, planeToCircle); + + if(d > circleShape.radius){ + return 0; // No overlap. Abort. + } + + if(justTest){ + return true; + } + + // Create contact + var contact = this.createContactEquation(planeBody,circleBody,sj,si); + + // ni is the plane world normal + vec2.copy(contact.normalA, worldNormal); + + // rj is the vector from circle center to the contact point + vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); + add(contact.contactPointB, contact.contactPointB, circleOffset); + sub(contact.contactPointB, contact.contactPointB, circleBody.position); + + // ri is the distance from plane center to contact. + vec2.scale(temp, contact.normalA, d); + sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector + 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; +}; + +/** + * Convex/convex Narrowphase.See this article for more info. + * @method convexConvex + * @param {Body} bi + * @param {Convex} si + * @param {Array} xi + * @param {Number} ai + * @param {Body} bj + * @param {Convex} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CONVEX] = +Narrowphase.prototype[Shape.CONVEX | Shape.BOX] = +Narrowphase.prototype[Shape.BOX] = +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 = typeof(precision) === 'number' ? precision : 0; + + var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); + if(!found){ + return 0; + } + + // Make sure the separating axis is directed from shape i to shape j + sub(dist,xj,xi); + if(dot(sepAxis,dist) > 0){ + vec2.scale(sepAxis,sepAxis,-1); + } + + // Find edges with normals closest to the separating axis + var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis + closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); + + if(closestEdge1 === -1 || closestEdge2 === -1){ + return 0; + } + + // Loop over the shapes + 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){ + // Swap! + 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; + } + + // Loop over 2 points in convex B + for(var j=closestEdgeB; j= 3){ + + if(justTest){ + return true; + } + + // worldPoint was on the "inside" side of each of the 3 checked edges. + // Project it to the center edge and use the projection direction as normal + + // Create contact + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + numContacts++; + + // Get center edge from body A + var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], + v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; + + // Construct the edge + 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); // Normal points out of convex A + vec2.normalize(c.normalA,c.normalA); + + sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point + var d = dot(c.normalA,dist); // Penetration + vec2.scale(penetrationVec, c.normalA, d); // Vector penetration + + 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); + + // Todo reduce to 1 friction equation if we have 2 contact points + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numContacts){ + this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); + } + } + + return numContacts; +}; + +// .projectConvex is called by other functions, need local tmp vectors +var pcoa_tmp1 = vec2.fromValues(0,0); + +/** + * Project a Convex onto a world-oriented axis + * @method projectConvexOntoAxis + * @static + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Array} worldAxis + * @param {Array} result + */ +Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = pcoa_tmp1; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, worldAxis, -convexAngle); + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + // Project the position of the body onto the axis - need to add this to the result + var offset = dot(convexOffset, worldAxis); + + vec2.set( result, min + offset, max + offset); +}; + +// .findSeparatingAxis is called by other functions, need local tmp vectors +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); + +/** + * Find a separating axis between the shapes, that maximizes the separating distance between them. + * @method findSeparatingAxis + * @static + * @param {Convex} c1 + * @param {Array} offset1 + * @param {Number} angle1 + * @param {Convex} c2 + * @param {Array} offset2 + * @param {Number} angle2 + * @param {Array} sepAxis The resulting axis + * @return {Boolean} Whether the axis could be found. + */ +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; + + if(c1 instanceof Box && c2 instanceof Box){ + + for(var j=0; j!==2; j++){ + var c = c1, + angle = angle1; + if(j===1){ + c = c2; + angle = angle2; + } + + for(var i=0; i!==2; i++){ + + // Get the world edge + if(i === 0){ + vec2.set(normal, 0, 1); + } else if(i === 1) { + vec2.set(normal, 1, 0); + } + if(angle !== 0){ + vec2.rotate(normal, normal, angle); + } + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + + } else { + + 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++){ + // Get the world edge + vec2.rotate(worldPoint0, c.vertices[i], angle); + vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); + + sub(edge, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, edge); + vec2.normalize(normal,normal); + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + } + + + /* + // Needs to be tested some more + 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.axes.length; i++){ + + var normal = c.axes[i]; + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1); + Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + 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; +}; + +// .getClosestEdge is called by other functions, need local tmp vectors +var gce_tmp1 = vec2.fromValues(0,0) +, gce_tmp2 = vec2.fromValues(0,0) +, gce_tmp3 = vec2.fromValues(0,0); + +/** + * Get the edge that has a normal closest to an axis. + * @method getClosestEdge + * @static + * @param {Convex} c + * @param {Number} angle + * @param {Array} axis + * @param {Boolean} flip + * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. + */ +Narrowphase.getClosestEdge = function(c,angle,axis,flip){ + var localAxis = gce_tmp1, + edge = gce_tmp2, + normal = gce_tmp3; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, axis, -angle); + if(flip){ + vec2.scale(localAxis,localAxis,-1); + } + + var closestEdge = -1, + N = c.vertices.length, + maxDot = -1; + for(var i=0; i!==N; i++){ + // Get the edge + sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + 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(); + +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = +Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, + hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ + var data = hfShape.heights, + 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; + + // Get the index of the points to test against + var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), + idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); + + /*if(idxB < 0 || idxA >= data.length) + return justTest ? false : 0;*/ + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(circlePos[1]-radius > max){ + return justTest ? false : 0; + } + + /* + if(circlePos[1]+radius < min){ + // Below the minimum point... We can just guess. + // TODO + } + */ + + // 1. Check so center of circle is not inside the field. If it is, this wont work... + // 2. For each edge + // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) + // 2. 2. Check if point is inside. + + var found = false; + + // Check all edges first + for(var i=idxA; i= v0[0] && candidate[0] < v1[0] && d <= 0){ + + if(justTest){ + return true; + } + + found = true; + + // Store the candidate point, projected to the edge + vec2.scale(dist,worldNormal,-d); + vec2.add(minCandidate,candidate,dist); + vec2.copy(minCandidateNormal,worldNormal); + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Normal is out of the heightfield + vec2.copy(c.normalA, minCandidateNormal); + + // Vector from circle to heightfield + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + vec2.copy(c.contactPointA, minCandidate); + vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push( this.createFrictionFromContact(c) ); + } + } + } + + // Check all vertices + found = false; + if(radius > 0){ + for(var i=idxA; i<=idxB; i++){ + + // Get point + vec2.set(v0, i*w, data[i]); + vec2.add(v0,v0,hfPos); + + vec2.sub(dist, circlePos, v0); + + if(vec2.squaredLength(dist) < Math.pow(radius, 2)){ + + if(justTest){ + return true; + } + + found = true; + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Construct normal - out of heightfield + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + sub(c.contactPointA, v0, hfPos); + add(c.contactPointA, c.contactPointA, hfPos); + sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(found){ + return 1; + } + + return 0; + +}; + +var convexHeightfield_v0 = vec2.create(), + convexHeightfield_v1 = vec2.create(), + convexHeightfield_tilePos = vec2.create(), + convexHeightfield_tempConvexShape = new Convex({ vertices: [vec2.create(),vec2.create(),vec2.create(),vec2.create()] }); +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.BOX | Shape.HEIGHTFIELD] = +Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = +Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, + hfBody,hfShape,hfPos,hfAngle, justTest ){ + var data = hfShape.heights, + w = hfShape.elementWidth, + v0 = convexHeightfield_v0, + v1 = convexHeightfield_v1, + tilePos = convexHeightfield_tilePos, + tileConvex = convexHeightfield_tempConvexShape; + + // Get the index of the points to test against + var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), + idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(convexBody.aabb.lowerBound[1] > max){ + return justTest ? false : 0; + } + + var found = false; + var numContacts = 0; + + // Loop over all edges + // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape) + for(var i=idxA; i= 0 || aabb.containsPoint(this.from)){ + this.intersectBody(result, body); + } + } +}; + +var intersectBody_worldPosition = vec2.create(); + +/** + * Shoot a ray at a body, get back information about the hit. + * @method intersectBody + * @private + * @param {Body} body + */ +Ray.prototype.intersectBody = function (result, body) { + var checkCollisionResponse = this.checkCollisionResponse; + + if(checkCollisionResponse && !body.collisionResponse){ + return; + } + + var worldPosition = intersectBody_worldPosition; + + for (var i = 0, N = body.shapes.length; i < N; i++) { + var shape = body.shapes[i]; + + if(checkCollisionResponse && !shape.collisionResponse){ + continue; // Skip + } + + if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){ + continue; + } + + // Get world angle and position of the shape + vec2.rotate(worldPosition, shape.position, body.angle); + vec2.add(worldPosition, worldPosition, body.position); + var worldAngle = shape.angle + body.angle; + + this.intersectShape( + result, + shape, + worldAngle, + worldPosition, + body + ); + + if(result.shouldStop(this)){ + break; + } + } +}; + +/** + * @method intersectShape + * @private + * @param {Shape} shape + * @param {number} angle + * @param {array} position + * @param {Body} body + */ +Ray.prototype.intersectShape = function(result, shape, angle, position, body){ + var from = this.from; + + // Checking radius + var distance = distanceFromIntersectionSquared(from, this.direction, position); + if (distance > shape.boundingRadius * shape.boundingRadius) { + return; + } + + this._currentBody = body; + this._currentShape = shape; + + shape.raycast(result, this, position, angle); + + this._currentBody = this._currentShape = null; +}; + +/** + * Get the AABB of the ray. + * @method getAABB + * @param {AABB} aabb + */ +Ray.prototype.getAABB = function(result){ + var to = this.to; + var from = this.from; + vec2.set( + result.lowerBound, + Math.min(to[0], from[0]), + Math.min(to[1], from[1]) + ); + vec2.set( + result.upperBound, + Math.max(to[0], from[0]), + Math.max(to[1], from[1]) + ); +}; + +var hitPointWorld = vec2.create(); + +/** + * @method reportIntersection + * @private + * @param {number} fraction + * @param {array} normal + * @param {number} [faceIndex=-1] + * @return {boolean} True if the intersections should continue + */ +Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){ + var from = this.from; + var to = this.to; + var shape = this._currentShape; + var body = this._currentBody; + + // Skip back faces? + if(this.skipBackfaces && vec2.dot(normal, this.direction) > 0){ + return; + } + + switch(this.mode){ + + case Ray.ALL: + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + this.callback(result); + break; + + case Ray.CLOSEST: + + // Store if closer than current closest + if(fraction < result.fraction || !result.hasHit()){ + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + } + break; + + case Ray.ANY: + + // Report and stop. + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + break; + } +}; + +var v0 = vec2.create(), + intersect = vec2.create(); +function distanceFromIntersectionSquared(from, direction, position) { + + // v0 is vector from from to position + vec2.sub(v0, position, from); + var dot = vec2.dot(v0, direction); + + // intersect = direction * dot + from + vec2.scale(intersect, direction, dot); + vec2.add(intersect, intersect, from); + + return vec2.squaredDistance(position, intersect); +} + + +},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Ray = _dereq_('../collision/Ray'); + +module.exports = RaycastResult; + +/** + * Storage for Ray casting hit data. + * @class RaycastResult + * @constructor + */ +function RaycastResult(){ + + /** + * The normal of the hit, oriented in world space. + * @property {array} normal + */ + this.normal = vec2.create(); + + /** + * The hit shape, or null. + * @property {Shape} shape + */ + this.shape = null; + + /** + * The hit body, or null. + * @property {Body} body + */ + this.body = null; + + /** + * The index of the hit triangle, if the hit shape was indexable. + * @property {number} faceIndex + * @default -1 + */ + this.faceIndex = -1; + + /** + * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet. + * @property {number} fraction + * @default -1 + */ + this.fraction = -1; + + /** + * If the ray should stop traversing. + * @readonly + * @property {Boolean} isStopped + */ + this.isStopped = false; +} + +/** + * Reset all result data. Must be done before re-using the result object. + * @method reset + */ +RaycastResult.prototype.reset = function () { + vec2.set(this.normal, 0, 0); + this.shape = null; + this.body = null; + this.faceIndex = -1; + this.fraction = -1; + this.isStopped = false; +}; + +/** + * Get the distance to the hit point. + * @method getHitDistance + * @param {Ray} ray + */ +RaycastResult.prototype.getHitDistance = function (ray) { + return vec2.distance(ray.from, ray.to) * this.fraction; +}; + +/** + * Returns true if the ray hit something since the last reset(). + * @method hasHit + */ +RaycastResult.prototype.hasHit = function () { + return this.fraction !== -1; +}; + +/** + * Get world hit point. + * @method getHitPoint + * @param {array} out + * @param {Ray} ray + */ +RaycastResult.prototype.getHitPoint = function (out, ray) { + vec2.lerp(out, ray.from, ray.to, this.fraction); +}; + +/** + * Can be called while iterating over hits to stop searching for hit points. + * @method stop + */ +RaycastResult.prototype.stop = function(){ + this.isStopped = true; +}; + +/** + * @method shouldStop + * @private + * @param {Ray} ray + * @return {boolean} + */ +RaycastResult.prototype.shouldStop = function(ray){ + return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY); +}; + +/** + * @method set + * @private + * @param {array} normal + * @param {Shape} shape + * @param {Body} body + * @param {number} fraction + */ +RaycastResult.prototype.set = function( + normal, + shape, + body, + fraction, + faceIndex +){ + vec2.copy(this.normal, normal); + this.shape = shape; + this.body = body; + this.fraction = fraction; + this.faceIndex = faceIndex; +}; +},{"../collision/Ray":11,"../math/vec2":30}],13:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, Broadphase = _dereq_('../collision/Broadphase'); + +module.exports = SAPBroadphase; + +/** + * Sweep and prune broadphase along one axis. + * + * @class SAPBroadphase + * @constructor + * @extends Broadphase + */ +function SAPBroadphase(){ + Broadphase.call(this,Broadphase.SAP); + + /** + * List of bodies currently in the broadphase. + * @property axisList + * @type {Array} + */ + this.axisList = []; + + /** + * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance. + * @property axisIndex + * @type {Number} + */ + this.axisIndex = 0; + + var that = this; + this._addBodyHandler = function(e){ + that.axisList.push(e.body); + }; + + this._removeBodyHandler = function(e){ + // Remove from list + var idx = that.axisList.indexOf(e.body); + if(idx !== -1){ + that.axisList.splice(idx,1); + } + }; +} +SAPBroadphase.prototype = new Broadphase(); +SAPBroadphase.prototype.constructor = SAPBroadphase; + +/** + * Change the world + * @method setWorld + * @param {World} world + */ +SAPBroadphase.prototype.setWorld = function(world){ + // Clear the old axis array + this.axisList.length = 0; + + // Add all bodies from the new world + Utils.appendArray(this.axisList, world.bodies); + + // Remove old handlers, if any + world + .off("addBody",this._addBodyHandler) + .off("removeBody",this._removeBodyHandler); + + // Add handlers to update the list of bodies. + world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); + + this.world = world; +}; + +/** + * Sorts bodies along an axis. + * @method sortAxisList + * @param {Array} a + * @param {number} axisIndex + * @return {Array} + */ +SAPBroadphase.sortAxisList = function(a, axisIndex){ + axisIndex = axisIndex|0; + for(var i=1,l=a.length; 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.sortList = function(){ + var bodies = this.axisList, + axisIndex = this.axisIndex; + + // Sort the lists + SAPBroadphase.sortAxisList(bodies, axisIndex); +}; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +SAPBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = this.axisList, + result = this.result, + axisIndex = this.axisIndex; + + result.length = 0; + + // Update all AABBs if needed + var l = bodies.length; + while(l--){ + var b = bodies[l]; + if(b.aabbNeedsUpdate){ + b.updateAABB(); + } + } + + // Sort the lists + this.sortList(); + + // Look through the X list + for(var i=0, N=bodies.length|0; i!==N; i++){ + var bi = bodies[i]; + + for(var j=i+1; j G = [-n -rixn n rjxn] + + var r = vec2.create(); + var ri = vec2.create(); // worldAnchorA + var rj = vec2.create(); // worldAnchorB + var that = this; + normal.computeGq = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + xi = bodyA.position, + xj = bodyB.position; + + // Transform local anchors to world + vec2.rotate(ri, localAnchorA, bodyA.angle); + vec2.rotate(rj, localAnchorB, bodyB.angle); + + vec2.add(r, xj, rj); + vec2.sub(r, r, ri); + vec2.sub(r, r, xi); + + //vec2.sub(r, bodyB.position, bodyA.position); + return vec2.length(r) - that.distance; + }; + + // Make the contact constraint bilateral + this.setMaxForce(maxForce); + + /** + * If the upper limit is enabled or not. + * @property {Boolean} upperLimitEnabled + */ + this.upperLimitEnabled = false; + + /** + * The upper constraint limit. + * @property {number} upperLimit + */ + this.upperLimit = 1; + + /** + * If the lower limit is enabled or not. + * @property {Boolean} lowerLimitEnabled + */ + this.lowerLimitEnabled = false; + + /** + * The lower constraint limit. + * @property {number} lowerLimit + */ + this.lowerLimit = 0; + + /** + * Current constraint position. This is equal to the current distance between the world anchor points. + * @property {number} position + */ + this.position = 0; +} +DistanceConstraint.prototype = new Constraint(); +DistanceConstraint.prototype.constructor = DistanceConstraint; + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +var n = vec2.create(); +var ri = vec2.create(); // worldAnchorA +var rj = vec2.create(); // worldAnchorB +DistanceConstraint.prototype.update = function(){ + var normal = this.equations[0], + bodyA = this.bodyA, + bodyB = this.bodyB, + distance = this.distance, + xi = bodyA.position, + xj = bodyB.position, + normalEquation = this.equations[0], + G = normal.G; + + // Transform local anchors to world + vec2.rotate(ri, this.localAnchorA, bodyA.angle); + vec2.rotate(rj, this.localAnchorB, bodyB.angle); + + // Get world anchor points and normal + vec2.add(n, xj, rj); + vec2.sub(n, n, ri); + vec2.sub(n, n, xi); + this.position = vec2.length(n); + + var violating = false; + if(this.upperLimitEnabled){ + if(this.position > this.upperLimit){ + normalEquation.maxForce = 0; + normalEquation.minForce = -this.maxForce; + this.distance = this.upperLimit; + violating = true; + } + } + + if(this.lowerLimitEnabled){ + if(this.position < this.lowerLimit){ + normalEquation.maxForce = this.maxForce; + normalEquation.minForce = 0; + this.distance = this.lowerLimit; + violating = true; + } + } + + if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){ + // No constraint needed. + normalEquation.enabled = false; + return; + } + + normalEquation.enabled = true; + + vec2.normalize(n,n); + + // Caluclate cross products + var rixn = vec2.crossLength(ri, n), + rjxn = vec2.crossLength(rj, n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; +}; + +/** + * Set the max force to be used + * @method setMaxForce + * @param {Number} maxForce + */ +DistanceConstraint.prototype.setMaxForce = function(maxForce){ + var normal = this.equations[0]; + normal.minForce = -maxForce; + normal.maxForce = maxForce; +}; + +/** + * Get the max force + * @method getMaxForce + * @return {Number} + */ +DistanceConstraint.prototype.getMaxForce = function(){ + var normal = this.equations[0]; + return normal.maxForce; +}; + +},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, AngleLockEquation = _dereq_('../equations/AngleLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = GearConstraint; + +/** + * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB. + * @class GearConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for). + * @param {Number} [options.ratio=1] Gear ratio. + * @param {Number} [options.maxTorque] Maximum torque to apply. + * @extends Constraint + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB, { + * ratio: 2, + * maxTorque: 1000 + * }); + * world.addConstraint(constraint); + */ +function GearConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); + + /** + * The gear ratio. + * @property ratio + * @type {Number} + */ + this.ratio = options.ratio !== undefined ? options.ratio : 1; + + /** + * The relative angle + * @property angle + * @type {Number} + */ + this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle; + + // Send same parameters to the equation + options.angle = this.angle; + options.ratio = this.ratio; + + this.equations = [ + new AngleLockEquation(bodyA,bodyB,options), + ]; + + // Set max torque + if(options.maxTorque !== undefined){ + this.setMaxTorque(options.maxTorque); + } +} +GearConstraint.prototype = new Constraint(); +GearConstraint.prototype.constructor = GearConstraint; + +GearConstraint.prototype.update = function(){ + var eq = this.equations[0]; + if(eq.ratio !== this.ratio){ + eq.setRatio(this.ratio); + } + eq.angle = this.angle; +}; + +/** + * Set the max torque for the constraint. + * @method setMaxTorque + * @param {Number} torque + */ +GearConstraint.prototype.setMaxTorque = function(torque){ + this.equations[0].setMaxTorque(torque); +}; + +/** + * Get the max torque for the constraint. + * @method getMaxTorque + * @return {Number} + */ +GearConstraint.prototype.getMaxTorque = function(torque){ + return this.equations[0].maxForce; +}; +},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('../equations/Equation'); + +module.exports = LockConstraint; + +/** + * Locks the relative position and rotation between two bodies. + * + * @class LockConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions. + * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles. + * @param {number} [options.maxForce] + * @extends Constraint + * + * @example + * // Locks the relative position and rotation between bodyA and bodyB + * var constraint = new LockConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + */ +function LockConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); + + var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); + + var localAngleB = options.localAngleB || 0; + + // Use 3 equations: + // gx = (xj - xi - l) * xhat = 0 + // gy = (xj - xi - l) * yhat = 0 + // gr = (xi - xj + r) * that = 0 + // + // ...where: + // l is the localOffsetB vector rotated to world in bodyA frame + // r is the same vector but reversed and rotated from bodyB frame + // xhat, yhat are world axis vectors + // that is the tangent of r + // + // For the first two constraints, we get + // G*W = (vj - vi - ldot ) * xhat + // = (vj - vi - wi x l) * xhat + // + // Since (wi x l) * xhat = (l x xhat) * wi, we get + // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] + // + // The last constraint gives + // GW = (vi - vj + wj x r) * that + // = [ that 0 -that (r x t) ] + + var x = new Equation(bodyA,bodyB,-maxForce,maxForce), + y = new Equation(bodyA,bodyB,-maxForce,maxForce), + rot = new Equation(bodyA,bodyB,-maxForce,maxForce); + + var l = vec2.create(), + g = vec2.create(), + that = this; + x.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[0]; + }; + y.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[1]; + }; + var r = vec2.create(), + t = vec2.create(); + rot.computeGq = function(){ + vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); + vec2.scale(r,r,-1); + vec2.sub(g,bodyA.position,bodyB.position); + vec2.add(g,g,r); + vec2.rotate(t,r,-Math.PI/2); + vec2.normalize(t,t); + return vec2.dot(g,t); + }; + + /** + * The offset of bodyB in bodyA's frame. + * @property {Array} localOffsetB + */ + this.localOffsetB = vec2.create(); + if(options.localOffsetB){ + vec2.copy(this.localOffsetB, options.localOffsetB); + } else { + // Construct from current positions + vec2.sub(this.localOffsetB, bodyB.position, bodyA.position); + vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle); + } + + /** + * The offset angle of bodyB in bodyA's frame. + * @property {Number} localAngleB + */ + this.localAngleB = 0; + if(typeof(options.localAngleB) === 'number'){ + this.localAngleB = options.localAngleB; + } else { + // Construct + this.localAngleB = bodyB.angle - bodyA.angle; + } + + this.equations.push(x, y, rot); + this.setMaxForce(maxForce); +} +LockConstraint.prototype = new Constraint(); +LockConstraint.prototype.constructor = LockConstraint; + +/** + * Set the maximum force to be applied. + * @method setMaxForce + * @param {Number} force + */ +LockConstraint.prototype.setMaxForce = function(force){ + var eqs = this.equations; + for(var i=0; ithis tutorial. Also called "slider constraint". + * + * @class PrismaticConstraint + * @constructor + * @extends Constraint + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.maxForce] Max force to be applied by the constraint + * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. + * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. + * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. + * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. + * @param {Number} [options.upperLimit] + * @param {Number} [options.lowerLimit] + * @todo Ability to create using only a point and a worldAxis + */ +function PrismaticConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); + + // Get anchors + var localAnchorA = vec2.fromValues(0,0), + localAxisA = vec2.fromValues(1,0), + localAnchorB = vec2.fromValues(0,0); + if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); } + if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); } + if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); } + + /** + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = localAnchorA; + + /** + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = localAnchorB; + + /** + * @property localAxisA + * @type {Array} + */ + this.localAxisA = localAxisA; + + /* + + The constraint violation for the common axis point is + + g = ( xj + rj - xi - ri ) * t := gg*t + + where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. + + gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) + + Note the use of the chain rule. Now we identify the jacobian + + G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] + + The rotational part is just a rotation lock. + + */ + + var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE; + + // Translational part + var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); + var ri = new vec2.create(), + rj = new vec2.create(), + gg = new vec2.create(), + t = new vec2.create(); + trans.computeGq = function(){ + // g = ( xj + rj - xi - ri ) * t + return vec2.dot(gg,t); + }; + trans.updateJacobian = function(){ + var G = this.G, + xi = bodyA.position, + xj = bodyB.position; + vec2.rotate(ri,localAnchorA,bodyA.angle); + vec2.rotate(rj,localAnchorB,bodyB.angle); + vec2.add(gg,xj,rj); + vec2.sub(gg,gg,xi); + vec2.sub(gg,gg,ri); + vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); + + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + }; + this.equations.push(trans); + + // Rotational part + if(!options.disableRotationalLock){ + var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); + this.equations.push(rot); + } + + /** + * The position of anchor A relative to anchor B, along the constraint axis. + * @property position + * @type {Number} + */ + this.position = 0; + + // Is this one used at all? + this.velocity = 0; + + /** + * Set to true to enable lower limit. + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; + + /** + * Set to true to enable upper limit. + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; + + /** + * Lower constraint limit. The constraint position is forced to be larger than this value. + * @property lowerLimit + * @type {Number} + */ + this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; + + /** + * Upper constraint limit. The constraint position is forced to be smaller than this value. + * @property upperLimit + * @type {Number} + */ + this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; + + // Equations used for limits + this.upperLimitEquation = new ContactEquation(bodyA,bodyB); + this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); + + // Set max/min forces + this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; + this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; + + /** + * Equation used for the motor. + * @property motorEquation + * @type {Equation} + */ + this.motorEquation = new Equation(bodyA,bodyB); + + /** + * The current motor state. Enable or disable the motor using .enableMotor + * @property motorEnabled + * @type {Boolean} + */ + this.motorEnabled = false; + + /** + * Set the target speed for the motor. + * @property motorSpeed + * @type {Number} + */ + this.motorSpeed = 0; + + var that = this; + var motorEquation = this.motorEquation; + var old = motorEquation.computeGW; + motorEquation.computeGq = function(){ return 0; }; + motorEquation.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed; + }; +} + +PrismaticConstraint.prototype = new Constraint(); +PrismaticConstraint.prototype.constructor = PrismaticConstraint; + +var worldAxisA = vec2.create(), + worldAnchorA = vec2.create(), + worldAnchorB = vec2.create(), + orientedAnchorA = vec2.create(), + orientedAnchorB = vec2.create(), + tmp = vec2.create(); + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +PrismaticConstraint.prototype.update = function(){ + var eqs = this.equations, + trans = eqs[0], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation, + bodyA = this.bodyA, + bodyB = this.bodyB, + localAxisA = this.localAxisA, + localAnchorA = this.localAnchorA, + localAnchorB = this.localAnchorB; + + trans.updateJacobian(); + + // Transform local things to world + vec2.rotate(worldAxisA, localAxisA, bodyA.angle); + vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); + vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); + vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); + vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); + + var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); + + // Motor + if(this.motorEnabled){ + // G = [ a a x ri -a -a x rj ] + var G = this.motorEquation.G; + G[0] = worldAxisA[0]; + G[1] = worldAxisA[1]; + G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); + G[3] = -worldAxisA[0]; + G[4] = -worldAxisA[1]; + G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); + } + + /* + Limits strategy: + Add contact equation, with normal along the constraint axis. + min/maxForce is set so the constraint is repulsive in the correct direction. + Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. + + ^ + | + upperLimit x + | ------ + anchorB x<---| B | + | | | + ------ | ------ + | | | + | A |-->x anchorA + ------ | + x lowerLimit + | + axis + */ + + + if(this.upperLimitEnabled && relPosition > upperLimit){ + // Update contact constraint normal, etc + 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 && relPosition < lowerLimit){ + // Update contact constraint normal, etc + vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); + vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); + vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); + vec2.scale(tmp,worldAxisA,lowerLimit); + vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } +}; + +/** + * Enable the motor + * @method enableMotor + */ +PrismaticConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +PrismaticConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the constraint limits. + * @method setLimits + * @param {number} lower Lower limit. + * @param {number} upper Upper limit. + */ +PrismaticConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + + +},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation') +, RotationalLockEquation = _dereq_('../equations/RotationalLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = RevoluteConstraint; + +var worldPivotA = vec2.create(), + worldPivotB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1), + g = vec2.create(); + +/** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * @class RevoluteConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to. + * @param {Array} [options.localPivotB] See localPivotA. + * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. + * @extends Constraint + * + * @example + * // This will create a revolute constraint between two bodies with pivot point in between them. + * var bodyA = new Body({ mass: 1, position: [-1, 0] }); + * var bodyB = new Body({ mass: 1, position: [1, 0] }); + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * worldPivot: [0, 0] + * }); + * world.addConstraint(constraint); + * + * // Using body-local pivot points, the constraint could have been constructed like this: + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * localPivotA: [1, 0], + * localPivotB: [-1, 0] + * }); + */ +function RevoluteConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); + + var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; + + /** + * @property {Array} pivotA + */ + this.pivotA = vec2.create(); + + /** + * @property {Array} pivotB + */ + this.pivotB = vec2.create(); + + if(options.worldPivot){ + // Compute pivotA and pivotB + vec2.sub(this.pivotA, options.worldPivot, bodyA.position); + vec2.sub(this.pivotB, options.worldPivot, bodyB.position); + // Rotate to local coordinate system + vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle); + vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle); + } else { + // Get pivotA and pivotB + vec2.copy(this.pivotA, options.localPivotA); + vec2.copy(this.pivotB, options.localPivotB); + } + + // Equations to be fed to the solver + var eqs = this.equations = [ + new Equation(bodyA,bodyB,-maxForce,maxForce), + new Equation(bodyA,bodyB,-maxForce,maxForce), + ]; + + var x = eqs[0]; + var y = eqs[1]; + var that = this; + + x.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,xAxis); + }; + + y.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,yAxis); + }; + + y.minForce = x.minForce = -maxForce; + y.maxForce = x.maxForce = maxForce; + + this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); + + /** + * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. + * @property {Boolean} motorEnabled + * @readOnly + */ + this.motorEnabled = false; + + /** + * The constraint position. + * @property angle + * @type {Number} + * @readOnly + */ + this.angle = 0; + + /** + * Set to true to enable lower limit + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = false; + + /** + * Set to true to enable upper limit + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = false; + + /** + * The lower limit on the constraint angle. + * @property lowerLimit + * @type {Boolean} + */ + this.lowerLimit = 0; + + /** + * The upper limit on the constraint angle. + * @property upperLimit + * @type {Boolean} + */ + this.upperLimit = 0; + + this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.upperLimitEquation.minForce = 0; + this.lowerLimitEquation.maxForce = 0; +} +RevoluteConstraint.prototype = new Constraint(); +RevoluteConstraint.prototype.constructor = RevoluteConstraint; + +/** + * Set the constraint angle limits. + * @method setLimits + * @param {number} lower Lower angle limit. + * @param {number} upper Upper angle limit. + */ +RevoluteConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + +RevoluteConstraint.prototype.update = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + pivotA = this.pivotA, + pivotB = this.pivotB, + eqs = this.equations, + normal = eqs[0], + tangent= eqs[1], + x = eqs[0], + y = eqs[1], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation; + + var relAngle = this.angle = bodyB.angle - bodyA.angle; + + if(this.upperLimitEnabled && relAngle > upperLimit){ + 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 < lowerLimit){ + lowerLimitEquation.angle = lowerLimit; + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } + + /* + + The constraint violation is + + g = xj + rj - xi - ri + + ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: + + gdot = vj + wj x rj - vi - wi x ri + + We split this into x and y directions. (let x and y be unit vectors along the respective axes) + + gdot * x = ( vj + wj x rj - vi - wi x ri ) * x + = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x + = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi + = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] + = G*W + + ...and similar for y. We have then identified the jacobian entries for x and y directions: + + Gx = [ x (rj x x) -x -(ri x x)] + Gy = [ y (rj x y) -y -(ri x y)] + + */ + + vec2.rotate(worldPivotA, pivotA, bodyA.angle); + vec2.rotate(worldPivotB, pivotB, bodyB.angle); + + // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc + + x.G[0] = -1; + x.G[1] = 0; + x.G[2] = -vec2.crossLength(worldPivotA,xAxis); + x.G[3] = 1; + x.G[4] = 0; + x.G[5] = vec2.crossLength(worldPivotB,xAxis); + + y.G[0] = 0; + y.G[1] = -1; + y.G[2] = -vec2.crossLength(worldPivotA,yAxis); + y.G[3] = 0; + y.G[4] = 1; + y.G[5] = vec2.crossLength(worldPivotB,yAxis); +}; + +/** + * Enable the rotational motor + * @method enableMotor + */ +RevoluteConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +RevoluteConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the speed of the rotational constraint motor + * @method setMotorSpeed + * @param {Number} speed + */ +RevoluteConstraint.prototype.setMotorSpeed = function(speed){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations[i].relativeVelocity = speed; +}; + +/** + * Get the speed of the rotational constraint motor + * @method getMotorSpeed + * @return {Number} The current speed, or false if the motor is not enabled. + */ +RevoluteConstraint.prototype.getMotorSpeed = function(){ + if(!this.motorEnabled){ + return false; + } + return this.motorEquation.relativeVelocity; +}; + +},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = AngleLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class AngleLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in body A. + * @param {Number} [options.ratio] Gear ratio + */ +function AngleLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); + this.angle = options.angle || 0; + + /** + * The gear ratio. + * @property {Number} ratio + * @private + * @see setRatio + */ + this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; + + this.setRatio(this.ratio); +} +AngleLockEquation.prototype = new Equation(); +AngleLockEquation.prototype.constructor = AngleLockEquation; + +AngleLockEquation.prototype.computeGq = function(){ + return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; +}; + +/** + * Set the gear ratio for this equation + * @method setRatio + * @param {Number} ratio + */ +AngleLockEquation.prototype.setRatio = function(ratio){ + var G = this.G; + G[2] = ratio; + G[5] = -1; + this.ratio = ratio; +}; + +/** + * Set the max force for the equation. + * @method setMaxTorque + * @param {Number} torque + */ +AngleLockEquation.prototype.setMaxTorque = function(torque){ + this.maxForce = torque; + this.minForce = -torque; +}; + +},{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = ContactEquation; + +/** + * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive. + * + * @class ContactEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function ContactEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); + + /** + * Vector from body i center of mass to the contact point. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + this.penetrationVec = vec2.create(); + + /** + * World-oriented vector from body A center of mass to the contact point. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * The normal vector, pointing out of body i + * @property normalA + * @type {Array} + */ + this.normalA = vec2.create(); + + /** + * The restitution to use (0=no bounciness, 1=max bounciness). + * @property restitution + * @type {Number} + */ + this.restitution = 0; + + /** + * This property is set to true if this is the first impact between the bodies (not persistant contact). + * @property firstImpact + * @type {Boolean} + * @readOnly + */ + this.firstImpact = false; + + /** + * The shape in body i that triggered this contact. + * @property shapeA + * @type {Shape} + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this contact. + * @property shapeB + * @type {Shape} + */ + this.shapeB = null; +} +ContactEquation.prototype = new Equation(); +ContactEquation.prototype.constructor = ContactEquation; +ContactEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + xi = bi.position, + xj = bj.position; + + var penetrationVec = this.penetrationVec, + n = this.normalA, + G = this.G; + + // Caluclate cross products + var rixn = vec2.crossLength(ri,n), + rjxn = vec2.crossLength(rj,n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; + + // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector + vec2.add(penetrationVec,xj,rj); + vec2.sub(penetrationVec,penetrationVec,xi); + vec2.sub(penetrationVec,penetrationVec,ri); + + // Compute iteration + var GW, Gq; + if(this.firstImpact && this.restitution !== 0){ + Gq = 0; + GW = (1/b)*(1+this.restitution) * this.computeGW(); + } else { + Gq = vec2.dot(n,penetrationVec) + this.offset; + GW = this.computeGW(); + } + + var GiMf = this.computeGiMf(); + var B = - Gq * a - GW * b - h*GiMf; + + return B; +}; + +var vi = vec2.create(); +var vj = vec2.create(); +var relVel = vec2.create(); + +/** + * Get the relative velocity along the normal vector. + * @return {number} + */ +ContactEquation.prototype.getVelocityAlongNormal = function(){ + + this.bodyA.getVelocityAtPoint(vi, this.contactPointA); + this.bodyB.getVelocityAtPoint(vj, this.contactPointB); + + vec2.subtract(relVel, vi, vj); + + return vec2.dot(this.normalA, relVel); +}; +},{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){ +module.exports = Equation; + +var vec2 = _dereq_('../math/vec2'), + Utils = _dereq_('../utils/Utils'), + Body = _dereq_('../objects/Body'); + +/** + * Base class for constraint equations. + * @class Equation + * @constructor + * @param {Body} bodyA First body participating in the equation + * @param {Body} bodyB Second body participating in the equation + * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE + * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE + */ +function Equation(bodyA, bodyB, minForce, maxForce){ + + /** + * Minimum force to apply when solving. + * @property minForce + * @type {Number} + */ + this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; + + /** + * Max force to apply when solving. + * @property maxForce + * @type {Number} + */ + this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; + + /** + * First body participating in the constraint + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second body participating in the constraint + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; + + /** + * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. + * @property stiffness + * @type {Number} + */ + this.stiffness = Equation.DEFAULT_STIFFNESS; + + /** + * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. + * @property relaxation + * @type {Number} + */ + this.relaxation = Equation.DEFAULT_RELAXATION; + + /** + * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). + * @property G + * @type {Array} + */ + this.G = new Utils.ARRAY_TYPE(6); + for(var i=0; i<6; i++){ + this.G[i]=0; + } + + this.offset = 0; + + this.a = 0; + this.b = 0; + this.epsilon = 0; + this.timeStep = 1/60; + + /** + * Indicates if stiffness or relaxation was changed. + * @property {Boolean} needsUpdate + */ + this.needsUpdate = true; + + /** + * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. + * @property multiplier + * @type {Number} + */ + this.multiplier = 0; + + /** + * Relative velocity. + * @property {Number} relativeVelocity + */ + this.relativeVelocity = 0; + + /** + * Whether this equation is enabled or not. If true, it will be added to the solver. + * @property {Boolean} enabled + */ + this.enabled = true; +} +Equation.prototype.constructor = Equation; + +/** + * The default stiffness when creating a new Equation. + * @static + * @property {Number} DEFAULT_STIFFNESS + * @default 1e6 + */ +Equation.DEFAULT_STIFFNESS = 1e6; + +/** + * The default relaxation when creating a new Equation. + * @static + * @property {Number} DEFAULT_RELAXATION + * @default 4 + */ +Equation.DEFAULT_RELAXATION = 4; + +/** + * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the SPOOK notes. + * @method update + */ +Equation.prototype.update = function(){ + var k = this.stiffness, + d = this.relaxation, + h = this.timeStep; + + this.a = 4.0 / (h * (1 + 4 * d)); + this.b = (4.0 * d) / (1 + 4 * d); + this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); + + this.needsUpdate = false; +}; + +/** + * Multiply a jacobian entry with corresponding positions or velocities + * @method gmult + * @return {Number} + */ +Equation.prototype.gmult = function(G,vi,wi,vj,wj){ + return G[0] * vi[0] + + G[1] * vi[1] + + G[2] * wi + + G[3] * vj[0] + + G[4] * vj[1] + + G[5] * wj; +}; + +/** + * Computes the RHS of the SPOOK equation + * @method computeB + * @return {Number} + */ +Equation.prototype.computeB = function(a,b,h){ + var GW = this.computeGW(); + var Gq = this.computeGq(); + var GiMf = this.computeGiMf(); + return - Gq * a - GW * b - GiMf*h; +}; + +/** + * Computes G\*q, where q are the generalized body coordinates + * @method computeGq + * @return {Number} + */ +var qi = vec2.create(), + qj = vec2.create(); +Equation.prototype.computeGq = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + xi = bi.position, + xj = bj.position, + ai = bi.angle, + aj = bj.angle; + + return this.gmult(G, qi, ai, qj, aj) + this.offset; +}; + +/** + * Computes G\*W, where W are the body velocities + * @method computeGW + * @return {Number} + */ +Equation.prototype.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity; +}; + +/** + * Computes G\*Wlambda, where W are the body velocities + * @method computeGWlambda + * @return {Number} + */ +Equation.prototype.computeGWlambda = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.vlambda, + vj = bj.vlambda, + wi = bi.wlambda, + wj = bj.wlambda; + return this.gmult(G,vi,wi,vj,wj); +}; + +/** + * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. + * @method computeGiMf + * @return {Number} + */ +var iMfi = vec2.create(), + iMfj = vec2.create(); +Equation.prototype.computeGiMf = function(){ + var bi = this.bodyA, + bj = this.bodyB, + fi = bi.force, + ti = bi.angularForce, + fj = bj.force, + tj = bj.angularForce, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + vec2.scale(iMfi, fi, invMassi); + vec2.multiply(iMfi, bi.massMultiplier, iMfi); + vec2.scale(iMfj, fj,invMassj); + vec2.multiply(iMfj, bj.massMultiplier, iMfj); + + return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); +}; + +/** + * Computes G\*inv(M)\*G' + * @method computeGiMGt + * @return {Number} + */ +Equation.prototype.computeGiMGt = function(){ + var bi = this.bodyA, + bj = this.bodyB, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + return G[0] * G[0] * invMassi * bi.massMultiplier[0] + + G[1] * G[1] * invMassi * bi.massMultiplier[1] + + G[2] * G[2] * invIi + + G[3] * G[3] * invMassj * bj.massMultiplier[0] + + G[4] * G[4] * invMassj * bj.massMultiplier[1] + + G[5] * G[5] * invIj; +}; + +var addToWlambda_temp = vec2.create(), + addToWlambda_Gi = vec2.create(), + addToWlambda_Gj = vec2.create(), + addToWlambda_ri = vec2.create(), + addToWlambda_rj = vec2.create(), + addToWlambda_Mdiag = vec2.create(); + +/** + * Add constraint velocity to the bodies. + * @method addToWlambda + * @param {Number} deltalambda + */ +Equation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bodyA, + bj = this.bodyB, + temp = addToWlambda_temp, + Gi = addToWlambda_Gi, + Gj = addToWlambda_Gj, + ri = addToWlambda_ri, + rj = addToWlambda_rj, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + Mdiag = addToWlambda_Mdiag, + G = this.G; + + Gi[0] = G[0]; + Gi[1] = G[1]; + Gj[0] = G[3]; + Gj[1] = G[4]; + + // Add to linear velocity + // v_lambda += inv(M) * delta_lamba * G + vec2.scale(temp, Gi, invMassi*deltalambda); + vec2.multiply(temp, temp, bi.massMultiplier); + vec2.add( bi.vlambda, bi.vlambda, temp); + // This impulse is in the offset frame + // Also add contribution to angular + //bi.wlambda -= vec2.crossLength(temp,ri); + bi.wlambda += invIi * G[2] * deltalambda; + + + vec2.scale(temp, Gj, invMassj*deltalambda); + vec2.multiply(temp, temp, bj.massMultiplier); + vec2.add( bj.vlambda, bj.vlambda, temp); + //bj.wlambda -= vec2.crossLength(temp,rj); + bj.wlambda += invIj * G[5] * deltalambda; +}; + +/** + * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps + * @method computeInvC + * @param {Number} eps + * @return {Number} + */ +Equation.prototype.computeInvC = function(eps){ + return 1.0 / (this.computeGiMGt() + eps); +}; + +},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('./Equation') +, Utils = _dereq_('../utils/Utils'); + +module.exports = FrictionEquation; + +/** + * Constrains the slipping in a contact along a tangent + * + * @class FrictionEquation + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Number} slipForce + * @extends Equation + */ +function FrictionEquation(bodyA, bodyB, slipForce){ + Equation.call(this, bodyA, bodyB, -slipForce, slipForce); + + /** + * Relative vector from center of body A to the contact point, world oriented. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + + /** + * Relative vector from center of body B to the contact point, world oriented. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * Tangent vector that the friction force will act along. World oriented. + * @property t + * @type {Array} + */ + this.t = vec2.create(); + + /** + * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average. + * @property contactEquations + * @type {ContactEquation} + */ + this.contactEquations = []; + + /** + * The shape in body i that triggered this friction. + * @property shapeA + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeA... + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this friction. + * @property shapeB + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeB... + */ + this.shapeB = null; + + /** + * The friction coefficient to use. + * @property frictionCoefficient + * @type {Number} + */ + this.frictionCoefficient = 0.3; +} +FrictionEquation.prototype = new Equation(); +FrictionEquation.prototype.constructor = FrictionEquation; + +/** + * Set the slipping condition for the constraint. The friction force cannot be + * larger than this value. + * @method setSlipForce + * @param {Number} slipForce + */ +FrictionEquation.prototype.setSlipForce = function(slipForce){ + this.maxForce = slipForce; + this.minForce = -slipForce; +}; + +/** + * Get the max force for the constraint. + * @method getSlipForce + * @return {Number} + */ +FrictionEquation.prototype.getSlipForce = function(){ + return this.maxForce; +}; + +FrictionEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + t = this.t, + G = this.G; + + // G = [-t -rixt t rjxt] + // And remember, this is a pure velocity constraint, g is always zero! + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + + var GW = this.computeGW(), + GiMf = this.computeGiMf(); + + var B = /* - g * a */ - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class RotationalLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in bodyA. + */ +function RotationalLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + + /** + * @property {number} angle + */ + this.angle = options.angle || 0; + + var G = this.G; + G[2] = 1; + G[5] = -1; +} +RotationalLockEquation.prototype = new Equation(); +RotationalLockEquation.prototype.constructor = RotationalLockEquation; + +var worldVectorA = vec2.create(), + worldVectorB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1); +RotationalLockEquation.prototype.computeGq = function(){ + vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); + vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); + return vec2.dot(worldVectorA,worldVectorB); +}; + +},{"../math/vec2":30,"./Equation":22}],25:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalVelocityEquation; + +/** + * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). + * + * @class RotationalVelocityEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function RotationalVelocityEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + this.relativeVelocity = 1; + this.ratio = 1; +} +RotationalVelocityEquation.prototype = new Equation(); +RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; +RotationalVelocityEquation.prototype.computeB = function(a,b,h){ + var G = this.G; + G[2] = -1; + G[5] = this.ratio; + + var GiMf = this.computeGiMf(); + var GW = this.computeGW(); + var B = - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"./Equation":22}],26:[function(_dereq_,module,exports){ +/** + * Base class for objects that dispatches events. + * @class EventEmitter + * @constructor + */ +var EventEmitter = function () {}; + +module.exports = EventEmitter; + +EventEmitter.prototype = { + constructor: EventEmitter, + + /** + * Add an event listener + * @method on + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + on: function ( type, listener, context ) { + listener.context = context || this; + if ( this._listeners === undefined ){ + this._listeners = {}; + } + var listeners = this._listeners; + if ( listeners[ type ] === undefined ) { + listeners[ type ] = []; + } + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + listeners[ type ].push( listener ); + } + return this; + }, + + /** + * Check if an event listener is added + * @method has + * @param {String} type + * @param {Function} listener + * @return {Boolean} + */ + has: function ( type, listener ) { + if ( this._listeners === undefined ){ + return false; + } + var listeners = this._listeners; + if(listener){ + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + return true; + } + } else { + if ( listeners[ type ] !== undefined ) { + return true; + } + } + + return false; + }, + + /** + * Remove an event listener + * @method off + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + off: function ( type, listener ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var index = listeners[ type ].indexOf( listener ); + if ( index !== - 1 ) { + listeners[ type ].splice( index, 1 ); + } + return this; + }, + + /** + * Emit an event. + * @method emit + * @param {Object} event + * @param {String} event.type + * @return {EventEmitter} The self object, for chainability. + */ + emit: function ( event ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; + if ( listenerArray !== undefined ) { + event.target = this; + for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { + var listener = listenerArray[ i ]; + listener.call( listener.context, event ); + } + } + return this; + } +}; + +},{}],27:[function(_dereq_,module,exports){ +var Material = _dereq_('./Material'); +var Equation = _dereq_('../equations/Equation'); + +module.exports = ContactMaterial; + +/** + * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. + * @class ContactMaterial + * @constructor + * @param {Material} materialA + * @param {Material} materialB + * @param {Object} [options] + * @param {Number} [options.friction=0.3] Friction coefficient. + * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". + * @param {Number} [options.stiffness] ContactEquation stiffness. + * @param {Number} [options.relaxation] ContactEquation relaxation. + * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. + * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. + * @param {Number} [options.surfaceVelocity=0] Surface velocity. + * @author schteppe + */ +function ContactMaterial(materialA, materialB, options){ + options = options || {}; + + if(!(materialA instanceof Material) || !(materialB instanceof Material)){ + throw new Error("First two arguments must be Material instances."); + } + + /** + * The contact material identifier + * @property id + * @type {Number} + */ + this.id = ContactMaterial.idCounter++; + + /** + * First material participating in the contact material + * @property materialA + * @type {Material} + */ + this.materialA = materialA; + + /** + * Second material participating in the contact material + * @property materialB + * @type {Material} + */ + this.materialB = materialB; + + /** + * Friction coefficient to use in the contact of these two materials. Friction = 0 will make the involved objects super slippery, and friction = 1 will make it much less slippery. A friction coefficient larger than 1 will allow for very large friction forces, which can be convenient for preventing car tires not slip on the ground. + * @property friction + * @type {Number} + * @default 0.3 + */ + this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; + + /** + * Restitution, or "bounciness" to use in the contact of these two materials. A restitution of 0 will make no bounce, while restitution=1 will approximately bounce back with the same velocity the object came with. + * @property restitution + * @type {Number} + * @default 0 + */ + this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0; + + /** + * Hardness of the contact. Less stiffness will make the objects penetrate more, and will make the contact act more like a spring than a contact force. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property stiffness + * @type {Number} + */ + this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting ContactEquation that this ContactMaterial generate. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property relaxation + * @type {Number} + */ + this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Stiffness of the resulting friction force. For most cases, the value of this property should be a large number. I cannot think of any case where you would want less frictionStiffness. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property frictionStiffness + * @type {Number} + */ + this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting friction force. The default value should be good for most simulations. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property frictionRelaxation + * @type {Number} + */ + this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + * @property {Number} surfaceVelocity + * @default 0 + */ + this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; + + /** + * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts". + * @property contactSkinSize + * @type {Number} + */ + this.contactSkinSize = 0.005; +} + +ContactMaterial.idCounter = 0; + +},{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){ +module.exports = Material; + +/** + * Defines a physics material. + * @class Material + * @constructor + * @param {number} id Material identifier + * @author schteppe + */ +function Material(id){ + /** + * The material identifier + * @property id + * @type {Number} + */ + this.id = id || Material.idCounter++; +} + +Material.idCounter = 0; + +},{}],29:[function(_dereq_,module,exports){ + + /* + PolyK library + url: http://polyk.ivank.net + Released under MIT licence. + + Copyright (c) 2012 Ivan Kuckir + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + */ + + var PolyK = {}; + + /* + Is Polygon self-intersecting? + + O(n^2) + */ + /* + PolyK.IsSimple = function(p) + { + var n = p.length>>1; + if(n<4) return true; + var a1 = new PolyK._P(), a2 = new PolyK._P(); + var b1 = new PolyK._P(), b2 = new PolyK._P(); + var c = new PolyK._P(); + + for(var i=0; i>1; + if(n<3) return []; + var tgs = []; + var avl = []; + for(var i=0; i 3) + { + 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; j 3*al) break; // no convex angles :( + } + tgs.push(avl[0], avl[1], avl[2]); + return tgs; + } + /* + PolyK.ContainsPoint = function(p, px, py) + { + var n = p.length>>1; + var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; + var depth = 0; + for(var i=0; i=0 && by>=0) continue; // both "up" or both "donw" + if(ax< 0 && bx< 0) continue; + + var lx = ax + (bx-ax)*(-ay)/(by-ay); + if(lx>0) depth++; + } + return (depth & 1) == 1; + } + + PolyK.Slice = function(p, ax, ay, bx, by) + { + if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; + + var a = new PolyK._P(ax, ay); + var b = new PolyK._P(bx, by); + var iscs = []; // intersections + var ps = []; // points + for(var i=0; i 0) + { + var n = ps.length; + var i0 = iscs[0]; + var i1 = iscs[1]; + var ind0 = ps.indexOf(i0); + var ind1 = ps.indexOf(i1); + var solved = false; + + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + else + { + i0 = iscs[1]; + i1 = iscs[0]; + ind0 = ps.indexOf(i0); + ind1 = ps.indexOf(i1); + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + } + if(solved) + { + dir--; + var pgn = PolyK._getPoints(ps, ind0, ind1); + pgs.push(pgn); + ps = PolyK._getPoints(ps, ind1, ind0); + i0.flag = i1.flag = false; + iscs.splice(0,2); + if(iscs.length == 0) pgs.push(ps); + } + else { dir++; iscs.reverse(); } + if(dir>1) break; + } + var result = []; + for(var i=0; i>1, isc); + } + b1.x = b2.x; b1.y = b2.y; + b2.x = p[0]; b2.y = p[1]; + PolyK._pointLineDist(a1, b1, b2, l>>1, isc); + + var idst = 1/isc.dist; + isc.norm.x = (x-isc.point.x)*idst; + isc.norm.y = (y-isc.point.y)*idst; + return isc; + } + + PolyK._pointLineDist = function(p, a, b, edge, isc) + { + var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; + + var A = x - x1; + var B = y - y1; + var C = x2 - x1; + var D = y2 - y1; + + var dot = A * C + B * D; + var len_sq = C * C + D * D; + var param = dot / len_sq; + + var xx, yy; + + if (param < 0 || (x1 == x2 && y1 == y2)) { + xx = x1; + yy = y1; + } + else if (param > 1) { + xx = x2; + yy = y2; + } + else { + xx = x1 + param * C; + yy = y1 + param * D; + } + + var dx = x - xx; + var dy = y - yy; + var dst = Math.sqrt(dx * dx + dy * dy); + if(dst= 0) && (v >= 0) && (u + v < 1); + } + /* + PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) + { + var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); + var day = (a1.y-a2.y), dby = (b1.y-b2.y); + + var Den = dax*dby - day*dbx; + if (Den == 0) return null; // parallel + + var A = (a1.x * a2.y - a1.y * a2.x); + var B = (b1.x * b2.y - b1.y * b2.x); + + var I = c; + var iDen = 1/Den; + I.x = ( A*dbx - dax*B ) * iDen; + I.y = ( A*dby - day*B ) * iDen; + + if(!PolyK._InRect(I, b1, b2)) return null; + if((day>0 && I.y>a1.y) || (day<0 && I.y0 && I.x>a1.x) || (dax<0 && I.x=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); + if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); + + if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) + && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) + return true; + return false; + } + */ + PolyK._convex = function(ax, ay, bx, by, cx, cy) + { + return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; + } + /* + PolyK._P = function(x,y) + { + this.x = x; + this.y = y; + this.flag = false; + } + PolyK._P.prototype.toString = function() + { + return "Point ["+this.x+", "+this.y+"]"; + } + PolyK._P.dist = function(a,b) + { + var dx = b.x-a.x; + var dy = b.y-a.y; + return Math.sqrt(dx*dx + dy*dy); + } + + PolyK._tp = []; + for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); + */ + +module.exports = PolyK; + +},{}],30:[function(_dereq_,module,exports){ +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. + * @class vec2 + */ + +var vec2 = module.exports = {}; + +var Utils = _dereq_('../utils/Utils'); + +/** + * Make a cross product and only return the z component + * @method crossLength + * @static + * @param {Array} a + * @param {Array} b + * @return {Number} + */ +vec2.crossLength = function(a,b){ + return a[0] * b[1] - a[1] * b[0]; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossVZ + * @static + * @param {Array} out + * @param {Array} vec + * @param {Number} zcomp + * @return {Number} + */ +vec2.crossVZ = function(out, vec, zcomp){ + vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossZV + * @static + * @param {Array} out + * @param {Number} zcomp + * @param {Array} vec + * @return {Number} + */ +vec2.crossZV = function(out, zcomp, vec){ + vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Rotate a vector by an angle + * @method rotate + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate = function(out,a,angle){ + if(angle !== 0){ + 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; + } else { + out[0] = a[0]; + out[1] = a[1]; + } +}; + +/** + * Rotate a vector 90 degrees clockwise + * @method rotate90cw + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate90cw = function(out, a) { + var x = a[0]; + var y = a[1]; + out[0] = y; + out[1] = -x; +}; + +/** + * Transform a point position to local frame. + * @method toLocalFrame + * @param {Array} out + * @param {Array} worldPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ + vec2.copy(out, worldPoint); + vec2.sub(out, out, framePosition); + vec2.rotate(out, out, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ + vec2.copy(out, localPoint); + vec2.rotate(out, out, frameAngle); + vec2.add(out, out, framePosition); +}; + +/** + * Transform a vector to local frame. + * @method vectorToLocalFrame + * @param {Array} out + * @param {Array} worldVector + * @param {Number} frameAngle + */ +vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ + vec2.rotate(out, worldVector, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localVector + * @param {Number} frameAngle + */ +vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){ + vec2.rotate(out, localVector, frameAngle); +}; + +/** + * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php + * @method centroid + * @static + * @param {Array} out + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Array} The out object + */ +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; +}; + +/** + * Creates a new, empty vec2 + * @static + * @method create + * @return {Array} a new 2D vector + */ +vec2.create = function() { + var out = new Utils.ARRAY_TYPE(2); + out[0] = 0; + out[1] = 0; + return out; +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * @static + * @method clone + * @param {Array} a vector to clone + * @return {Array} a new 2D vector + */ +vec2.clone = function(a) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Creates a new vec2 initialized with the given values + * @static + * @method fromValues + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} a new 2D vector + */ +vec2.fromValues = function(x, y) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Copy the values from one vec2 to another + * @static + * @method copy + * @param {Array} out the receiving vector + * @param {Array} a the source vector + * @return {Array} out + */ +vec2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * @static + * @method set + * @param {Array} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} out + */ +vec2.set = function(out, x, y) { + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Adds two vec2's + * @static + * @method add + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +}; + +/** + * Subtracts two vec2's + * @static + * @method subtract + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +}; + +/** + * Alias for vec2.subtract + * @static + * @method sub + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * @static + * @method multiply + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +}; + +/** + * Alias for vec2.multiply + * @static + * @method mul + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * @static + * @method divide + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +}; + +/** + * Alias for vec2.divide + * @static + * @method div + */ +vec2.div = vec2.divide; + +/** + * Scales a vec2 by a scalar number + * @static + * @method scale + * @param {Array} out the receiving vector + * @param {Array} a the vector to scale + * @param {Number} b amount to scale the vector by + * @return {Array} out + */ +vec2.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * @static + * @method distance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} distance between a and b + */ +vec2.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.distance + * @static + * @method dist + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * @static + * @method squaredDistance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} squared distance between a and b + */ +vec2.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredDistance + * @static + * @method sqrDist + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * @static + * @method length + * @param {Array} a vector to calculate length of + * @return {Number} length of a + */ +vec2.length = function (a) { + var x = a[0], + y = a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.length + * @method len + * @static + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * @static + * @method squaredLength + * @param {Array} a vector to calculate squared length of + * @return {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a[0], + y = a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredLength + * @static + * @method sqrLen + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * @static + * @method negate + * @param {Array} out the receiving vector + * @param {Array} a vector to negate + * @return {Array} out + */ +vec2.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +}; + +/** + * Normalize a vec2 + * @static + * @method normalize + * @param {Array} out the receiving vector + * @param {Array} a vector to normalize + * @return {Array} out + */ +vec2.normalize = function(out, a) { + var x = a[0], + y = a[1]; + var len = x*x + y*y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * @static + * @method dot + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1]; +}; + +/** + * Returns a string representation of a vector + * @static + * @method str + * @param {Array} vec vector to represent as a string + * @return {String} string representation of the vector + */ +vec2.str = function (a) { + return 'vec2(' + a[0] + ', ' + a[1] + ')'; +}; + +/** + * Linearly interpolate/mix two vectors. + * @static + * @method lerp + * @param {Array} out + * @param {Array} a First vector + * @param {Array} b Second vector + * @param {number} t Lerp factor + */ +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; +}; + +/** + * Reflect a vector along a normal. + * @static + * @method reflect + * @param {Array} out + * @param {Array} vector + * @param {Array} normal + */ +vec2.reflect = function(out, vector, normal){ + var dot = vector[0] * normal[0] + vector[1] * normal[1]; + out[0] = vector[0] - 2 * normal[0] * dot; + out[1] = vector[1] - 2 * normal[1] * dot; +}; + +/** + * Get the intersection point between two line segments. + * @static + * @method getLineSegmentsIntersection + * @param {Array} out + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {boolean} True if there was an intersection, otherwise false. + */ +vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { + var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); + if(t < 0){ + return false; + } else { + out[0] = p0[0] + (t * (p1[0] - p0[0])); + out[1] = p0[1] + (t * (p1[1] - p0[1])); + return true; + } +}; + +/** + * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) + * @static + * @method getLineSegmentsIntersectionFraction + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. + */ +vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { + var s1_x = p1[0] - p0[0]; + var s1_y = p1[1] - p0[1]; + var s2_x = p3[0] - p2[0]; + var s2_y = p3[1] - p2[1]; + + var s, t; + s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); + t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); + if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + return t; + } + return -1; // No collision +}; + +},{"../utils/Utils":57}],31:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, decomp = _dereq_('poly-decomp') +, Convex = _dereq_('../shapes/Convex') +, RaycastResult = _dereq_('../collision/RaycastResult') +, Ray = _dereq_('../collision/Ray') +, AABB = _dereq_('../collision/AABB') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Body; + +/** + * A rigid body. Has got a center of mass, position, velocity and a number of + * shapes that are used for collisions. + * + * @class Body + * @constructor + * @extends EventEmitter + * @param {Array} [options.force] + * @param {Array} [options.position] + * @param {Array} [options.velocity] + * @param {Boolean} [options.allowSleep] + * @param {Boolean} [options.collisionResponse] + * @param {Number} [options.angle=0] + * @param {Number} [options.angularForce=0] + * @param {Number} [options.angularVelocity=0] + * @param {Number} [options.ccdIterations=10] + * @param {Number} [options.ccdSpeedThreshold=-1] + * @param {Number} [options.fixedRotation=false] + * @param {Number} [options.gravityScale] + * @param {Number} [options.id] + * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. + * @param {Number} [options.sleepSpeedLimit] + * @param {Number} [options.sleepTimeLimit] + * @param {Object} [options] + * + * @example + * + * // Create a typical dynamic body + * var body = new Body({ + * mass: 1, + * position: [0, 0], + * angle: 0, + * velocity: [0, 0], + * angularVelocity: 0 + * }); + * + * // Add a circular shape to the body + * body.addShape(new Circle({ radius: 1 })); + * + * // Add the body to the world + * world.addBody(body); + */ +function Body(options){ + options = options || {}; + + EventEmitter.call(this); + + /** + * The body identifyer + * @property id + * @type {Number} + */ + this.id = options.id || ++Body._idCounter; + + /** + * The world that this body is added to. This property is set to NULL if the body is not added to any world. + * @property world + * @type {World} + */ + this.world = null; + + /** + * The shapes of the body. + * + * @property shapes + * @type {Array} + */ + this.shapes = []; + + /** + * The mass of the body. + * @property mass + * @type {number} + */ + this.mass = options.mass || 0; + + /** + * The inverse mass of the body. + * @property invMass + * @type {number} + */ + this.invMass = 0; + + /** + * The inertia of the body around the Z axis. + * @property inertia + * @type {number} + */ + this.inertia = 0; + + /** + * The inverse inertia of the body. + * @property invInertia + * @type {number} + */ + this.invInertia = 0; + + this.invMassSolve = 0; + this.invInertiaSolve = 0; + + /** + * Set to true if you want to fix the rotation of the body. + * @property fixedRotation + * @type {Boolean} + */ + this.fixedRotation = !!options.fixedRotation; + + /** + * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y. + * @property {Boolean} fixedX + */ + this.fixedX = !!options.fixedX; + + /** + * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X. + * @property {Boolean} fixedY + */ + this.fixedY = !!options.fixedY; + + /** + * @private + * @property {array} massMultiplier + */ + this.massMultiplier = vec2.create(); + + /** + * The position of the body + * @property position + * @type {Array} + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * The interpolated position of the body. Use this for rendering. + * @property interpolatedPosition + * @type {Array} + */ + this.interpolatedPosition = vec2.fromValues(0,0); + + /** + * The interpolated angle of the body. Use this for rendering. + * @property interpolatedAngle + * @type {Number} + */ + this.interpolatedAngle = 0; + + /** + * The previous position of the body. + * @property previousPosition + * @type {Array} + */ + this.previousPosition = vec2.fromValues(0,0); + + /** + * The previous angle of the body. + * @property previousAngle + * @type {Number} + */ + this.previousAngle = 0; + + /** + * The current velocity of the body. + * @property velocity + * @type {Array} + */ + this.velocity = vec2.fromValues(0,0); + if(options.velocity){ + vec2.copy(this.velocity, options.velocity); + } + + /** + * Constraint velocity that was added to the body during the last step. + * @property vlambda + * @type {Array} + */ + this.vlambda = vec2.fromValues(0,0); + + /** + * Angular constraint velocity that was added to the body during last step. + * @property wlambda + * @type {Array} + */ + this.wlambda = 0; + + /** + * The angle of the body, in radians. + * @property angle + * @type {number} + * @example + * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. + * // If you need a value between 0 and 2*pi, use the following function to normalize it. + * function normalizeAngle(angle){ + * angle = angle % (2*Math.PI); + * if(angle < 0){ + * angle += (2*Math.PI); + * } + * return angle; + * } + */ + this.angle = options.angle || 0; + + /** + * The angular velocity of the body, in radians per second. + * @property angularVelocity + * @type {number} + */ + this.angularVelocity = options.angularVelocity || 0; + + /** + * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. + * @property force + * @type {Array} + * + * @example + * // This produces a forcefield of 1 Newton in the positive x direction. + * for(var i=0; i radius){ + radius = offset + r; + } + } + + this.boundingRadius = radius; +}; + +/** + * Add a shape to the body. You can pass a local transform when adding a shape, + * so that the shape gets an offset and angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * + * @method addShape + * @param {Shape} shape + * @param {Array} [offset] Local body offset of the shape. + * @param {Number} [angle] Local body angle. + * + * @example + * var body = new Body(), + * shape = new Circle({ radius: 1 }); + * + * // Add the shape to the body, positioned in the center + * body.addShape(shape); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. + * body.addShape(shape,[1,0]); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. + * body.addShape(shape,[0,1],Math.PI/2); + */ +Body.prototype.addShape = function(shape, offset, angle){ + if(shape.body){ + throw new Error('A shape can only be added to one body.'); + } + shape.body = this; + + // Copy the offset vector + if(offset){ + vec2.copy(shape.position, offset); + } else { + vec2.set(shape.position, 0, 0); + } + + shape.angle = angle || 0; + + this.shapes.push(shape); + this.updateMassProperties(); + this.updateBoundingRadius(); + + this.aabbNeedsUpdate = true; +}; + +/** + * Remove a shape + * @method removeShape + * @param {Shape} shape + * @return {Boolean} True if the shape was found and removed, else false. + */ +Body.prototype.removeShape = function(shape){ + var idx = this.shapes.indexOf(shape); + + if(idx !== -1){ + this.shapes.splice(idx,1); + this.aabbNeedsUpdate = true; + shape.body = null; + return true; + } else { + return false; + } +}; + +/** + * Updates .inertia, .invMass, .invInertia for this Body. Should be called when + * changing the structure or mass of the Body. + * + * @method updateMassProperties + * + * @example + * body.mass += 1; + * body.updateMassProperties(); + */ +Body.prototype.updateMassProperties = function(){ + if(this.type === Body.STATIC || this.type === 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; + } + + // Inverse mass properties are easy + this.invMass = 1 / this.mass; + + vec2.set( + this.massMultiplier, + this.fixedX ? 0 : 1, + this.fixedY ? 0 : 1 + ); + } +}; + +var Body_applyForce_r = vec2.create(); + +/** + * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero. + * @method applyForce + * @param {Array} force The force to add. + * @param {Array} [relativePoint] A world point to apply the force on. + */ +Body.prototype.applyForce = function(force, relativePoint){ + + // Add linear force + vec2.add(this.force, this.force, force); + + if(relativePoint){ + + // Compute produced rotational force + var rotForce = vec2.crossLength(relativePoint,force); + + // Add rotational force + this.angularForce += rotForce; + } +}; + +/** + * Apply force to a body-local point. + * @method applyForceLocal + * @param {Array} localForce The force vector to add, oriented in local body space. + * @param {Array} [localPoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyForce_forceWorld = vec2.create(); +var Body_applyForce_pointWorld = vec2.create(); +var Body_applyForce_pointLocal = vec2.create(); +Body.prototype.applyForceLocal = function(localForce, localPoint){ + localPoint = localPoint || Body_applyForce_pointLocal; + var worldForce = Body_applyForce_forceWorld; + var worldPoint = Body_applyForce_pointWorld; + this.vectorToWorldFrame(worldForce, localForce); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyForce(worldForce, worldPoint); +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulse + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_velo = vec2.create(); +Body.prototype.applyImpulse = function(impulseVector, relativePoint){ + if(this.type !== Body.DYNAMIC){ + return; + } + + // Compute produced central impulse velocity + var velo = Body_applyImpulse_velo; + vec2.scale(velo, impulseVector, this.invMass); + vec2.multiply(velo, this.massMultiplier, velo); + + // Add linear impulse + vec2.add(this.velocity, velo, this.velocity); + + if(relativePoint){ + // Compute produced rotational impulse velocity + var rotVelo = vec2.crossLength(relativePoint, impulseVector); + rotVelo *= this.invInertia; + + // Add rotational Impulse + this.angularVelocity += rotVelo; + } +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulseLocal + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_impulseWorld = vec2.create(); +var Body_applyImpulse_pointWorld = vec2.create(); +var Body_applyImpulse_pointLocal = vec2.create(); +Body.prototype.applyImpulseLocal = function(localImpulse, localPoint){ + localPoint = localPoint || Body_applyImpulse_pointLocal; + var worldImpulse = Body_applyImpulse_impulseWorld; + var worldPoint = Body_applyImpulse_pointWorld; + this.vectorToWorldFrame(worldImpulse, localImpulse); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyImpulse(worldImpulse, worldPoint); +}; + +/** + * Transform a world point to local body frame. + * @method toLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldPoint The input world point + */ +Body.prototype.toLocalFrame = function(out, worldPoint){ + vec2.toLocalFrame(out, worldPoint, this.position, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method toWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localPoint The input local point + */ +Body.prototype.toWorldFrame = function(out, localPoint){ + vec2.toGlobalFrame(out, localPoint, this.position, this.angle); +}; + +/** + * Transform a world point to local body frame. + * @method vectorToLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldVector The input world vector + */ +Body.prototype.vectorToLocalFrame = function(out, worldVector){ + vec2.vectorToLocalFrame(out, worldVector, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method vectorToWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localVector The input local vector + */ +Body.prototype.vectorToWorldFrame = function(out, localVector){ + vec2.vectorToGlobalFrame(out, localVector, this.angle); +}; + +/** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. + * @method fromPolygon + * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. + * @param {Object} [options] + * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. + * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @return {Boolean} True on success, else false. + */ +Body.prototype.fromPolygon = function(path,options){ + options = options || {}; + + // Remove all shapes + for(var i=this.shapes.length; i>=0; --i){ + this.removeShape(this.shapes[i]); + } + + var p = new decomp.Polygon(); + p.vertices = path; + + // Make it counter-clockwise + p.makeCCW(); + + if(typeof(options.removeCollinearPoints) === "number"){ + p.removeCollinearPoints(options.removeCollinearPoints); + } + + // Check if any line segment intersects the path itself + if(typeof(options.skipSimpleCheck) === "undefined"){ + if(!p.isSimple()){ + return false; + } + } + + // Save this path for later + this.concavePath = p.vertices.slice(0); + for(var i=0; ithis for details. + * @method applyDamping + * @param {number} dt Current time step + */ +Body.prototype.applyDamping = function(dt){ + if(this.type === Body.DYNAMIC){ // Only for dynamic bodies + var v = this.velocity; + vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); + this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); + } +}; + +/** + * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. + * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. + * @method wakeUp + */ +Body.prototype.wakeUp = function(){ + var s = this.sleepState; + this.sleepState = Body.AWAKE; + this.idleTime = 0; + if(s !== Body.AWAKE){ + this.emit(Body.wakeUpEvent); + } +}; + +/** + * Force body sleep + * @method sleep + */ +Body.prototype.sleep = function(){ + this.sleepState = Body.SLEEPING; + this.angularVelocity = 0; + this.angularForce = 0; + vec2.set(this.velocity,0,0); + vec2.set(this.force,0,0); + this.emit(Body.sleepEvent); +}; + +/** + * Called every timestep to update internal sleep timer and change sleep state if needed. + * @method sleepTick + * @param {number} time The world time in seconds + * @param {boolean} dontSleep + * @param {number} dt + */ +Body.prototype.sleepTick = function(time, dontSleep, dt){ + if(!this.allowSleep || this.type === Body.SLEEPING){ + return; + } + + this.wantsToSleep = false; + + var sleepState = this.sleepState, + speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), + speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); + + // Add to idle time + if(speedSquared >= 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; + } + } +}; + +/** + * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. + * @method overlaps + * @param {Body} body + * @return {boolean} + */ +Body.prototype.overlaps = function(body){ + return this.world.overlapKeeper.bodiesAreOverlapping(this, body); +}; + +var integrate_fhMinv = vec2.create(); +var integrate_velodt = vec2.create(); + +/** + * Move the body forward in time given its current velocity. + * @method integrate + * @param {Number} dt + */ +Body.prototype.integrate = function(dt){ + var minv = this.invMass, + f = this.force, + pos = this.position, + velo = this.velocity; + + // Save old position + vec2.copy(this.previousPosition, this.position); + this.previousAngle = this.angle; + + // Velocity update + if(!this.fixedRotation){ + this.angularVelocity += this.angularForce * this.invInertia * dt; + } + vec2.scale(integrate_fhMinv, f, dt * minv); + vec2.multiply(integrate_fhMinv, this.massMultiplier, integrate_fhMinv); + vec2.add(velo, integrate_fhMinv, velo); + + // CCD + if(!this.integrateToTimeOfImpact(dt)){ + + // Regular position update + vec2.scale(integrate_velodt, velo, dt); + vec2.add(pos, pos, integrate_velodt); + if(!this.fixedRotation){ + this.angle += this.angularVelocity * dt; + } + } + + this.aabbNeedsUpdate = true; +}; + +var result = new RaycastResult(); +var ray = new Ray({ + mode: Ray.ALL +}); +var direction = vec2.create(); +var end = vec2.create(); +var startToEnd = vec2.create(); +var rememberPosition = vec2.create(); +Body.prototype.integrateToTimeOfImpact = function(dt){ + + if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){ + return false; + } + + vec2.normalize(direction, this.velocity); + + vec2.scale(end, this.velocity, dt); + vec2.add(end, end, this.position); + + vec2.sub(startToEnd, end, this.position); + var startToEndAngle = this.angularVelocity * dt; + var len = vec2.length(startToEnd); + + var timeOfImpact = 1; + + var hit; + var that = this; + result.reset(); + ray.callback = function (result) { + if(result.body === that){ + return; + } + hit = result.body; + result.getHitPoint(end, ray); + vec2.sub(startToEnd, end, that.position); + timeOfImpact = vec2.length(startToEnd) / len; + result.stop(); + }; + vec2.copy(ray.from, this.position); + vec2.copy(ray.to, end); + ray.update(); + this.world.raycast(result, ray); + + if(!hit){ + return false; + } + + var rememberAngle = this.angle; + vec2.copy(rememberPosition, this.position); + + // Got a start and end point. Approximate time of impact using binary search + var iter = 0; + var tmin = 0; + var tmid = 0; + var tmax = timeOfImpact; + while (tmax >= tmin && iter < this.ccdIterations) { + iter++; + + // calculate the midpoint + tmid = (tmax - tmin) / 2; + + // Move the body to that point + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, rememberPosition, integrate_velodt); + this.angle = rememberAngle + startToEndAngle * timeOfImpact; + this.updateAABB(); + + // check overlap + var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit); + + if (overlaps) { + // change min to search upper interval + tmin = tmid; + } else { + // change max to search lower interval + tmax = tmid; + } + } + + timeOfImpact = tmid; + + vec2.copy(this.position, rememberPosition); + this.angle = rememberAngle; + + // move to TOI + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, this.position, integrate_velodt); + if(!this.fixedRotation){ + this.angle += startToEndAngle * timeOfImpact; + } + + return true; +}; + +/** + * Get velocity of a point in the body. + * @method getVelocityAtPoint + * @param {Array} result A vector to store the result in + * @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from + * @return {Array} The result vector + */ +Body.prototype.getVelocityAtPoint = function(result, relativePoint){ + vec2.crossVZ(result, relativePoint, this.angularVelocity); + vec2.subtract(result, this.velocity, result); + return result; +}; + +/** + * @event sleepy + */ +Body.sleepyEvent = { + type: "sleepy" +}; + +/** + * @event sleep + */ +Body.sleepEvent = { + type: "sleep" +}; + +/** + * @event wakeup + */ +Body.wakeUpEvent = { + type: "wakeup" +}; + +/** + * Dynamic body. + * @property DYNAMIC + * @type {Number} + * @static + */ +Body.DYNAMIC = 1; + +/** + * Static body. + * @property STATIC + * @type {Number} + * @static + */ +Body.STATIC = 2; + +/** + * Kinematic body. + * @property KINEMATIC + * @type {Number} + * @static + */ +Body.KINEMATIC = 4; + +/** + * @property AWAKE + * @type {Number} + * @static + */ +Body.AWAKE = 0; + +/** + * @property SLEEPY + * @type {Number} + * @static + */ +Body.SLEEPY = 1; + +/** + * @property SLEEPING + * @type {Number} + * @static + */ +Body.SLEEPING = 2; + + +},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = LinearSpring; + +/** + * A spring, connecting two bodies. + * + * The Spring explicitly adds force and angularForce to the bodies. + * + * @class LinearSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + */ +function LinearSpring(bodyA,bodyB,options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Anchor for bodyA in local bodyA coordinates. + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = vec2.fromValues(0,0); + + /** + * Anchor for bodyB in local bodyB coordinates. + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = vec2.fromValues(0,0); + + if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); } + if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); } + if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } + if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } + + var worldAnchorA = vec2.create(); + var worldAnchorB = vec2.create(); + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + var worldDistance = vec2.distance(worldAnchorA, worldAnchorB); + + /** + * Rest length of the spring. + * @property restLength + * @type {number} + */ + this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance; +} +LinearSpring.prototype = new Spring(); +LinearSpring.prototype.constructor = LinearSpring; + +/** + * Set the anchor point on body A, using world coordinates. + * @method setWorldAnchorA + * @param {Array} worldAnchorA + */ +LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){ + this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); +}; + +/** + * Set the anchor point on body B, using world coordinates. + * @method setWorldAnchorB + * @param {Array} worldAnchorB + */ +LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){ + this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); +}; + +/** + * Get the anchor point on body A, in world coordinates. + * @method getWorldAnchorA + * @param {Array} result The vector to store the result in. + */ +LinearSpring.prototype.getWorldAnchorA = function(result){ + this.bodyA.toWorldFrame(result, this.localAnchorA); +}; + +/** + * Get the anchor point on body B, in world coordinates. + * @method getWorldAnchorB + * @param {Array} result The vector to store the result in. + */ +LinearSpring.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(); + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +LinearSpring.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; + + // Get world anchors + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + + // Get offset points + vec2.sub(ri, worldAnchorA, bodyA.position); + vec2.sub(rj, worldAnchorB, bodyB.position); + + // Compute distance vector between world anchor points + vec2.sub(r, worldAnchorB, worldAnchorA); + var rlen = vec2.len(r); + vec2.normalize(r_unit,r); + + //console.log(rlen) + //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) + + // Compute relative velocity of the anchor points, u + 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); + + // F = - k * ( x - L ) - D * ( u ) + vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); + + // Add forces to bodies + vec2.sub( bodyA.force, bodyA.force, f); + vec2.add( bodyB.force, bodyB.force, f); + + // Angular force + 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":57,"./Spring":34}],33:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); + +module.exports = RotationalSpring; + +/** + * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies. + * + * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap. + * + * @class RotationalSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. + */ +function RotationalSpring(bodyA, bodyB, options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Rest angle of the spring. + * @property restAngle + * @type {number} + */ + this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle; +} +RotationalSpring.prototype = new Spring(); +RotationalSpring.prototype.constructor = RotationalSpring; + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +RotationalSpring.prototype.applyForce = function(){ + var k = this.stiffness, + d = this.damping, + l = this.restAngle, + bodyA = this.bodyA, + bodyB = this.bodyB, + x = bodyB.angle - bodyA.angle, + u = bodyB.angularVelocity - bodyA.angularVelocity; + + var torque = - k * (x - l) - d * u * 0; + + bodyA.angularForce -= torque; + bodyB.angularForce += torque; +}; + +},{"../math/vec2":30,"./Spring":34}],34:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = Spring; + +/** + * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver. + * + * @class Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + */ +function Spring(bodyA, bodyB, options){ + options = Utils.defaults(options,{ + stiffness: 100, + damping: 1, + }); + + /** + * Stiffness of the spring. + * @property stiffness + * @type {number} + */ + this.stiffness = options.stiffness; + + /** + * Damping of the spring. + * @property damping + * @type {number} + */ + this.damping = options.damping; + + /** + * First connected body. + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second connected body. + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; +} + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +Spring.prototype.applyForce = function(){ + // To be implemented by subclasses +}; + +},{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); +var Constraint = _dereq_('../constraints/Constraint'); +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Body = _dereq_('../objects/Body'); + +module.exports = TopDownVehicle; + +/** + * @class TopDownVehicle + * @constructor + * @param {Body} chassisBody A dynamic body, already added to the world. + * @param {Object} [options] + * + * @example + * + * // Create a dynamic body for the chassis + * var chassisBody = new Body({ + * mass: 1 + * }); + * var boxShape = new Box({ width: 0.5, height: 1 }); + * chassisBody.addShape(boxShape); + * world.addBody(chassisBody); + * + * // Create the vehicle + * var vehicle = new TopDownVehicle(chassisBody); + * + * // Add one front wheel and one back wheel - we don't actually need four :) + * var frontWheel = vehicle.addWheel({ + * localPosition: [0, 0.5] // front + * }); + * frontWheel.setSideFriction(4); + * + * // Back wheel + * var backWheel = vehicle.addWheel({ + * localPosition: [0, -0.5] // back + * }); + * backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift + * vehicle.addToWorld(world); + * + * // Steer value zero means straight forward. Positive is left and negative right. + * frontWheel.steerValue = Math.PI / 16; + * + * // Engine force forward + * backWheel.engineForce = 10; + * backWheel.setBrakeForce(0); + */ +function TopDownVehicle(chassisBody, options){ + options = options || {}; + + /** + * @property {Body} chassisBody + */ + this.chassisBody = chassisBody; + + /** + * @property {Array} wheels + */ + this.wheels = []; + + // A dummy body to constrain the chassis to + this.groundBody = new Body({ mass: 0 }); + + this.world = null; + + var that = this; + this.preStepCallback = function(){ + that.update(); + }; +} + +/** + * @method addToWorld + * @param {World} world + */ +TopDownVehicle.prototype.addToWorld = function(world){ + this.world = world; + world.addBody(this.groundBody); + world.on('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.addConstraint(wheel); + } +}; + +/** + * @method removeFromWorld + * @param {World} world + */ +TopDownVehicle.prototype.removeFromWorld = function(){ + var world = this.world; + world.removeBody(this.groundBody); + world.off('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.removeConstraint(wheel); + } + this.world = null; +}; + +/** + * @method addWheel + * @param {object} [wheelOptions] + * @return {WheelConstraint} + */ +TopDownVehicle.prototype.addWheel = function(wheelOptions){ + var wheel = new WheelConstraint(this,wheelOptions); + this.wheels.push(wheel); + return wheel; +}; + +/** + * @method update + */ +TopDownVehicle.prototype.update = function(){ + for (var i = 0; i < this.wheels.length; i++) { + this.wheels[i].update(); + } +}; + +/** + * @class WheelConstraint + * @constructor + * @extends {Constraint} + * @param {Vehicle} vehicle + * @param {object} [options] + * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero. + * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body. + * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction. + */ +function WheelConstraint(vehicle, options){ + options = options || {}; + + this.vehicle = vehicle; + + this.forwardEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + this.sideEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + /** + * @property {number} steerValue + */ + this.steerValue = 0; + + /** + * @property {number} engineForce + */ + this.engineForce = 0; + + this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5); + + /** + * @property {Array} localForwardVector + */ + this.localForwardVector = vec2.fromValues(0, 1); + if(options.localForwardVector){ + vec2.copy(this.localForwardVector, options.localForwardVector); + } + + /** + * @property {Array} localPosition + */ + this.localPosition = vec2.fromValues(0, 0); + if(options.localPosition){ + vec2.copy(this.localPosition, options.localPosition); + } + + Constraint.apply(this, vehicle.chassisBody, vehicle.groundBody); + + this.equations.push( + this.forwardEquation, + this.sideEquation + ); + + this.setBrakeForce(0); +} +WheelConstraint.prototype = new Constraint(); + +/** + * @method setForwardFriction + */ +WheelConstraint.prototype.setBrakeForce = function(force){ + this.forwardEquation.setSlipForce(force); +}; + +/** + * @method setSideFriction + */ +WheelConstraint.prototype.setSideFriction = function(force){ + this.sideEquation.setSlipForce(force); +}; + +var worldVelocity = vec2.create(); +var relativePoint = vec2.create(); + +/** + * @method getSpeed + */ +WheelConstraint.prototype.getSpeed = function(){ + this.vehicle.chassisBody.vectorToWorldFrame(relativePoint, this.localForwardVector); + this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity, relativePoint); + return vec2.dot(worldVelocity, relativePoint); +}; + +var tmpVec = vec2.create(); + +/** + * @method update + */ +WheelConstraint.prototype.update = function(){ + + // Directional + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t, this.localForwardVector); + vec2.rotate(this.sideEquation.t, this.localForwardVector, Math.PI / 2); + this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t, this.sideEquation.t); + + vec2.rotate(this.forwardEquation.t, this.forwardEquation.t, this.steerValue); + vec2.rotate(this.sideEquation.t, this.sideEquation.t, this.steerValue); + + // Attachment point + this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB, this.localPosition); + vec2.copy(this.sideEquation.contactPointB, this.forwardEquation.contactPointB); + + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA, this.localPosition); + vec2.copy(this.sideEquation.contactPointA, this.forwardEquation.contactPointA); + + // Add engine force + vec2.normalize(tmpVec, this.forwardEquation.t); + vec2.scale(tmpVec, tmpVec, this.engineForce); + + this.vehicle.chassisBody.applyForce(tmpVec, this.forwardEquation.contactPointA); +}; +},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(_dereq_,module,exports){ +// Export p2 classes +var p2 = module.exports = { + AABB : _dereq_('./collision/AABB'), + AngleLockEquation : _dereq_('./equations/AngleLockEquation'), + Body : _dereq_('./objects/Body'), + Broadphase : _dereq_('./collision/Broadphase'), + Capsule : _dereq_('./shapes/Capsule'), + Circle : _dereq_('./shapes/Circle'), + Constraint : _dereq_('./constraints/Constraint'), + ContactEquation : _dereq_('./equations/ContactEquation'), + ContactEquationPool : _dereq_('./utils/ContactEquationPool'), + ContactMaterial : _dereq_('./material/ContactMaterial'), + Convex : _dereq_('./shapes/Convex'), + DistanceConstraint : _dereq_('./constraints/DistanceConstraint'), + Equation : _dereq_('./equations/Equation'), + EventEmitter : _dereq_('./events/EventEmitter'), + FrictionEquation : _dereq_('./equations/FrictionEquation'), + FrictionEquationPool : _dereq_('./utils/FrictionEquationPool'), + GearConstraint : _dereq_('./constraints/GearConstraint'), + GSSolver : _dereq_('./solver/GSSolver'), + Heightfield : _dereq_('./shapes/Heightfield'), + Line : _dereq_('./shapes/Line'), + LockConstraint : _dereq_('./constraints/LockConstraint'), + Material : _dereq_('./material/Material'), + Narrowphase : _dereq_('./collision/Narrowphase'), + NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'), + Particle : _dereq_('./shapes/Particle'), + Plane : _dereq_('./shapes/Plane'), + Pool : _dereq_('./utils/Pool'), + RevoluteConstraint : _dereq_('./constraints/RevoluteConstraint'), + PrismaticConstraint : _dereq_('./constraints/PrismaticConstraint'), + Ray : _dereq_('./collision/Ray'), + RaycastResult : _dereq_('./collision/RaycastResult'), + Box : _dereq_('./shapes/Box'), + RotationalVelocityEquation : _dereq_('./equations/RotationalVelocityEquation'), + SAPBroadphase : _dereq_('./collision/SAPBroadphase'), + Shape : _dereq_('./shapes/Shape'), + Solver : _dereq_('./solver/Solver'), + Spring : _dereq_('./objects/Spring'), + TopDownVehicle : _dereq_('./objects/TopDownVehicle'), + LinearSpring : _dereq_('./objects/LinearSpring'), + RotationalSpring : _dereq_('./objects/RotationalSpring'), + Utils : _dereq_('./utils/Utils'), + World : _dereq_('./world/World'), + vec2 : _dereq_('./math/vec2'), + version : _dereq_('../package.json').version, +}; + +Object.defineProperty(p2, 'Rectangle', { + get: function() { + console.warn('The Rectangle class has been renamed to Box.'); + return this.Box; + } +}); +},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":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/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Shape = _dereq_('./Shape') +, Convex = _dereq_('./Convex'); + +module.exports = Box; + +/** + * Box shape class. + * @class Box + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.width=1] Total width of the box + * @param {Number} [options.height=1] Total height of the box + * @extends Convex + */ +function Box(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + width: arguments[0], + height: arguments[1] + }; + console.warn('The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })'); + } + options = options || {}; + + /** + * Total width of the box + * @property width + * @type {Number} + */ + var width = this.width = options.width || 1; + + /** + * Total height of the box + * @property height + * @type {Number} + */ + var height = this.height = options.height || 1; + + var verts = [ + vec2.fromValues(-width/2, -height/2), + vec2.fromValues( width/2, -height/2), + vec2.fromValues( width/2, height/2), + vec2.fromValues(-width/2, height/2) + ]; + var axes = [ + vec2.fromValues(1, 0), + vec2.fromValues(0, 1) + ]; + + options.vertices = verts; + options.axes = axes; + options.type = Shape.BOX; + Convex.call(this, options); +} +Box.prototype = new Convex(); +Box.prototype.constructor = Box; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Box.prototype.computeMomentOfInertia = function(mass){ + var w = this.width, + h = this.height; + return mass * (h*h + w*w) / 12; +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Box.prototype.updateBoundingRadius = function(){ + var w = this.width, + h = this.height; + this.boundingRadius = Math.sqrt(w*w + h*h) / 2; +}; + +var corner1 = vec2.create(), + corner2 = vec2.create(), + corner3 = vec2.create(), + corner4 = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Box.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices,position,angle,0); +}; + +Box.prototype.updateArea = function(){ + this.area = this.width * this.height; +}; + + +},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Capsule; + +/** + * Capsule shape class. + * @class Capsule + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The distance between the end points + * @param {Number} [options.radius=1] Radius of the capsule + * @example + * var capsuleShape = new Capsule({ + * length: 1, + * radius: 2 + * }); + * body.addShape(capsuleShape); + */ +function Capsule(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + length: arguments[0], + radius: arguments[1] + }; + console.warn('The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })'); + } + options = options || {}; + + /** + * The distance between the end points. + * @property {Number} length + */ + this.length = options.length || 1; + + /** + * The radius of the capsule. + * @property {Number} radius + */ + this.radius = options.radius || 1; + + options.type = Shape.CAPSULE; + Shape.call(this, options); +} +Capsule.prototype = new Shape(); +Capsule.prototype.constructor = Capsule; + +/** + * Compute the mass moment of inertia of the Capsule. + * @method conputeMomentOfInertia + * @param {Number} mass + * @return {Number} + * @todo + */ +Capsule.prototype.computeMomentOfInertia = function(mass){ + // Approximate with rectangle + var r = this.radius, + w = this.length + r, // 2*r is too much, 0 is too little + h = r*2; + return mass * (h*h + w*w) / 12; +}; + +/** + * @method updateBoundingRadius + */ +Capsule.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius + this.length/2; +}; + +/** + * @method updateArea + */ +Capsule.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; +}; + +var r = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Capsule.prototype.computeAABB = function(out, position, angle){ + var radius = this.radius; + + // Compute center position of one of the the circles, world oriented, but with local offset + vec2.set(r,this.length / 2,0); + if(angle !== 0){ + vec2.rotate(r,r,angle); + } + + // Get bounds + 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)); + + // Add offset + vec2.add(out.lowerBound, out.lowerBound, position); + vec2.add(out.upperBound, out.upperBound, position); +}; + +var intersectCapsule_hitPointWorld = vec2.create(); +var intersectCapsule_normal = vec2.create(); +var intersectCapsule_l0 = vec2.create(); +var intersectCapsule_l1 = vec2.create(); +var intersectCapsule_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Capsule.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectCapsule_hitPointWorld; + var normal = intersectCapsule_normal; + var l0 = intersectCapsule_l0; + var l1 = intersectCapsule_l1; + + // The sides + var halfLen = this.length / 2; + for(var i=0; i<2; i++){ + + // get start and end of the line + var y = this.radius * (i*2-1); + vec2.set(l0, -halfLen, y); + vec2.set(l1, halfLen, y); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var delta = vec2.getLineSegmentsIntersectionFraction(from, to, l0, l1); + if(delta >= 0){ + vec2.rotate(normal, intersectCapsule_unit_y, angle); + vec2.scale(normal, normal, (i*2-1)); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + // Circles + var diagonalLengthSquared = Math.pow(this.radius, 2) + Math.pow(halfLen, 2); + for(var i=0; i<2; i++){ + vec2.set(l0, halfLen * (i*2-1), 0); + vec2.toGlobalFrame(l0, l0, position, angle); + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - l0[0]) + (to[1] - from[1]) * (from[1] - l0[1])); + var c = Math.pow(from[0] - l0[0], 2) + Math.pow(from[1] - l0[1], 2) - Math.pow(this.radius, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + if(delta < 0){ + // No intersection + continue; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(hitPointWorld, from, to, delta); + + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(hitPointWorld, from, to, d1); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d1, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(hitPointWorld, from, to, d2); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d2, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + } + } +}; +},{"../math/vec2":30,"./Shape":45}],39:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Circle; + +/** + * Circle shape class. + * @class Circle + * @extends Shape + * @constructor + * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {number} [options.radius=1] The radius of this circle + * + * @example + * var circleShape = new Circle({ radius: 1 }); + * body.addShape(circleShape); + */ +function Circle(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + radius: arguments[0] + }; + console.warn('The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })'); + } + options = options || {}; + + /** + * The radius of the circle. + * @property radius + * @type {number} + */ + this.radius = options.radius || 1; + + options.type = Shape.CIRCLE; + Shape.call(this, options); +} +Circle.prototype = new Shape(); +Circle.prototype.constructor = Circle; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Circle.prototype.computeMomentOfInertia = function(mass){ + var r = this.radius; + return mass * r * r / 2; +}; + +/** + * @method updateBoundingRadius + * @return {Number} + */ +Circle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius; +}; + +/** + * @method updateArea + * @return {Number} + */ +Circle.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius; +}; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +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); + } +}; + +var Ray_intersectSphere_intersectionPoint = vec2.create(); +var Ray_intersectSphere_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Circle.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from, + to = ray.to, + r = this.radius; + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1])); + var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + var intersectionPoint = Ray_intersectSphere_intersectionPoint; + var normal = Ray_intersectSphere_normal; + + if(delta < 0){ + // No intersection + return; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(intersectionPoint, from, to, delta); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, delta, normal, -1); + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(intersectionPoint, from, to, d1); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d1, normal, -1); + + if(result.shouldStop(ray)){ + return; + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(intersectionPoint, from, to, d2); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d2, normal, -1); + } + } +}; +},{"../math/vec2":30,"./Shape":45}],40:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, polyk = _dereq_('../math/polyk') +, decomp = _dereq_('poly-decomp'); + +module.exports = Convex; + +/** + * Convex shape class. + * @class Convex + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. + * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex. + * @example + * // Create a box + * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]]; + * var convexShape = new Convex({ vertices: vertices }); + * body.addShape(convexShape); + */ +function Convex(options){ + if(Array.isArray(arguments[0])){ + options = { + vertices: arguments[0], + axes: arguments[1] + }; + console.warn('The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })'); + } + options = options || {}; + + /** + * Vertices defined in the local frame. + * @property vertices + * @type {Array} + */ + this.vertices = []; + + // Copy the verts + var vertices = options.vertices !== undefined ? options.vertices : []; + for(var i=0; i < vertices.length; i++){ + var v = vec2.create(); + vec2.copy(v, vertices[i]); + this.vertices.push(v); + } + + /** + * Axes defined in the local frame. + * @property axes + * @type {Array} + */ + this.axes = []; + + if(options.axes){ + + // Copy the axes + for(var i=0; i < options.axes.length; i++){ + var axis = vec2.create(); + vec2.copy(axis, options.axes[i]); + this.axes.push(axis); + } + + } else { + + // Construct axes from the vertex data + for(var i = 0; i < this.vertices.length; i++){ + // Get the world edge + var worldPoint0 = this.vertices[i]; + var worldPoint1 = this.vertices[(i+1) % this.vertices.length]; + + var normal = vec2.create(); + vec2.sub(normal, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, normal); + vec2.normalize(normal, normal); + + this.axes.push(normal); + } + + } + + /** + * The center of mass of the Convex + * @property centerOfMass + * @type {Array} + */ + this.centerOfMass = vec2.fromValues(0,0); + + /** + * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. + * @property triangles + * @type {Array} + */ + this.triangles = []; + + if(this.vertices.length){ + this.updateTriangles(); + this.updateCenterOfMass(); + } + + /** + * The bounding radius of the convex + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + options.type = Shape.CONVEX; + Shape.call(this, options); + + this.updateBoundingRadius(); + this.updateArea(); + if(this.area < 0){ + throw new Error("Convex vertices must be given in conter-clockwise winding."); + } +} +Convex.prototype = new Shape(); +Convex.prototype.constructor = Convex; + +var tmpVec1 = vec2.create(); +var tmpVec2 = vec2.create(); + +/** + * Project a Convex onto a world-oriented axis + * @method projectOntoAxis + * @static + * @param {Array} offset + * @param {Array} localAxis + * @param {Array} result + */ +Convex.prototype.projectOntoLocalAxis = function(localAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = tmpVec1; + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + vec2.set(result, min, max); +}; + +Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){ + var worldAxis = tmpVec2; + + this.projectOntoLocalAxis(localAxis, result); + + // Project the position of the body onto the axis - need to add this to the result + if(shapeAngle !== 0){ + vec2.rotate(worldAxis, localAxis, shapeAngle); + } else { + worldAxis = localAxis; + } + var offset = vec2.dot(shapeOffset, worldAxis); + + vec2.set(result, result[0] + offset, result[1] + offset); +}; + + +/** + * Update the .triangles property + * @method updateTriangles + */ +Convex.prototype.updateTriangles = function(){ + + this.triangles.length = 0; + + // Rewrite on polyk notation, array of numbers + var polykVerts = []; + for(var i=0; i r2){ + r2 = l2; + } + } + + this.boundingRadius = Math.sqrt(r2); +}; + +/** + * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. + * @static + * @method triangleArea + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +Convex.triangleArea = function(a,b,c){ + return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; +}; + +/** + * Update the .area + * @method updateArea + */ +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]]; + + // Get mass for the triangle (density=1 in this case) + var m = Convex.triangleArea(a,b,c); + this.area += m; + } +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Convex.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices, position, angle, 0); +}; + +var intersectConvex_rayStart = vec2.create(); +var intersectConvex_rayEnd = vec2.create(); +var intersectConvex_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Convex.prototype.raycast = function(result, ray, position, angle){ + var rayStart = intersectConvex_rayStart; + var rayEnd = intersectConvex_rayEnd; + var normal = intersectConvex_normal; + var vertices = this.vertices; + + // Transform to local shape space + vec2.toLocalFrame(rayStart, ray.from, position, angle); + vec2.toLocalFrame(rayEnd, ray.to, position, angle); + + var n = vertices.length; + + for (var i = 0; i < n && !result.shouldStop(ray); i++) { + var q1 = vertices[i]; + var q2 = vertices[(i+1) % n]; + var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2); + + if(delta >= 0){ + vec2.sub(normal, q2, q1); + vec2.rotate(normal, normal, -Math.PI / 2 + angle); + vec2.normalize(normal, normal); + ray.reportIntersection(result, delta, normal, i); + } + } +}; + +},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Heightfield; + +/** + * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". + * @class Heightfield + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {array} [options.heights] An array of Y values that will be used to construct the terrain. + * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given. + * @param {Number} [options.maxValue] Maximum value. + * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction. + * + * @example + * // Generate some height data (y-values). + * var heights = []; + * for(var i = 0; i < 1000; i++){ + * var y = 0.5 * Math.cos(0.2 * i); + * heights.push(y); + * } + * + * // Create the heightfield shape + * var heightfieldShape = new Heightfield({ + * heights: heights, + * elementWidth: 1 // Distance between the data points in X direction + * }); + * var heightfieldBody = new Body(); + * heightfieldBody.addShape(heightfieldShape); + * world.addBody(heightfieldBody); + * + * @todo Should use a scale property with X and Y direction instead of just elementWidth + */ +function Heightfield(options){ + if(Array.isArray(arguments[0])){ + options = { + heights: arguments[0] + }; + + if(typeof(arguments[1]) === 'object'){ + for(var key in arguments[1]){ + options[key] = arguments[1][key]; + } + } + + console.warn('The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })'); + } + options = options || {}; + + /** + * An array of numbers, or height values, that are spread out along the x axis. + * @property {array} heights + */ + this.heights = options.heights ? options.heights.slice(0) : []; + + /** + * Max value of the heights + * @property {number} maxValue + */ + this.maxValue = options.maxValue || null; + + /** + * Max value of the heights + * @property {number} minValue + */ + this.minValue = options.minValue || null; + + /** + * The width of each element + * @property {number} elementWidth + */ + this.elementWidth = options.elementWidth || 0.1; + + if(options.maxValue === undefined || options.minValue === undefined){ + this.updateMaxMinValues(); + } + + options.type = Shape.HEIGHTFIELD; + Shape.call(this, options); +} +Heightfield.prototype = new Shape(); +Heightfield.prototype.constructor = Heightfield; + +/** + * Update the .minValue and the .maxValue + * @method updateMaxMinValues + */ +Heightfield.prototype.updateMaxMinValues = function(){ + var data = this.heights; + var maxValue = data[0]; + var minValue = data[0]; + for(var i=0; i !== data.length; i++){ + var v = data[i]; + if(v > maxValue){ + maxValue = v; + } + if(v < minValue){ + minValue = v; + } + } + this.maxValue = maxValue; + this.minValue = minValue; +}; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Heightfield.prototype.computeMomentOfInertia = function(mass){ + return Number.MAX_VALUE; +}; + +Heightfield.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +Heightfield.prototype.updateArea = function(){ + var data = this.heights, + area = 0; + for(var i=0; i= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + var intX = p0[0] + (t * s1_x); + var intY = p0[1] + (t * s1_y); + out[0] = intX; + out[1] = intY; + return t; + } + return -1; // No collision +} + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Heightfield.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectHeightfield_hitPointWorld; + var worldNormal = intersectHeightfield_worldNormal; + var l0 = intersectHeightfield_l0; + var l1 = intersectHeightfield_l1; + var localFrom = intersectHeightfield_localFrom; + var localTo = intersectHeightfield_localTo; + + // get local ray start and end + vec2.toLocalFrame(localFrom, from, position, angle); + vec2.toLocalFrame(localTo, to, position, angle); + + // Get the segment range + var i0 = this.getClampedSegmentIndex(localFrom); + var i1 = this.getClampedSegmentIndex(localTo); + if(i0 > i1){ + var tmp = i0; + i0 = i1; + i1 = tmp; + } + + // The segments + for(var i=0; i= 0){ + vec2.sub(worldNormal, l1, l0); + vec2.rotate(worldNormal, worldNormal, angle + Math.PI / 2); + vec2.normalize(worldNormal, worldNormal); + ray.reportIntersection(result, t, worldNormal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Line; + +/** + * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * @class Line + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The total length of the line + * @extends Shape + * @constructor + */ +function Line(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + length: arguments[0] + }; + console.warn('The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })'); + } + options = options || {}; + + /** + * Length of this line + * @property {Number} length + * @default 1 + */ + this.length = options.length || 1; + + options.type = Shape.LINE; + Shape.call(this, options); +} +Line.prototype = new Shape(); +Line.prototype.constructor = Line; + +Line.prototype.computeMomentOfInertia = function(mass){ + return mass * Math.pow(this.length,2) / 12; +}; + +Line.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.length/2; +}; + +var points = [vec2.create(),vec2.create()]; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Line.prototype.computeAABB = function(out, position, angle){ + var l2 = this.length / 2; + vec2.set(points[0], -l2, 0); + vec2.set(points[1], l2, 0); + out.setFromPoints(points,position,angle,0); +}; + +var raycast_hitPoint = vec2.create(); +var raycast_normal = vec2.create(); +var raycast_l0 = vec2.create(); +var raycast_l1 = vec2.create(); +var raycast_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {number} angle + * @param {array} position + */ +Line.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + + var l0 = raycast_l0; + var l1 = raycast_l1; + + // get start and end of the line + var halfLen = this.length / 2; + vec2.set(l0, -halfLen, 0); + vec2.set(l1, halfLen, 0); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to); + if(fraction >= 0){ + var normal = raycast_normal; + vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from + ray.reportIntersection(result, fraction, normal, -1); + } +}; +},{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Particle; + +/** + * Particle shape class. + * @class Particle + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @extends Shape + */ +function Particle(options){ + options = options || {}; + options.type = Shape.PARTICLE; + Shape.call(this, options); +} +Particle.prototype = new Shape(); +Particle.prototype.constructor = Particle; + +Particle.prototype.computeMomentOfInertia = function(mass){ + return 0; // Can't rotate a particle +}; + +Particle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = 0; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Particle.prototype.computeAABB = function(out, position, angle){ + vec2.copy(out.lowerBound, position); + vec2.copy(out.upperBound, position); +}; + +},{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Plane; + +/** + * Plane shape class. The plane is facing in the Y direction. + * @class Plane + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + */ +function Plane(options){ + options = options || {}; + options.type = Shape.PLANE; + Shape.call(this, options); +} +Plane.prototype = new Shape(); +Plane.prototype.constructor = Plane; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + */ +Plane.prototype.computeMomentOfInertia = function(mass){ + return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Plane.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Plane.prototype.computeAABB = function(out, position, angle){ + var a = angle % (2 * Math.PI); + var set = vec2.set; + var max = 1e7; + var lowerBound = out.lowerBound; + var upperBound = out.upperBound; + + // Set max bounds + set(lowerBound, -max, -max); + set(upperBound, max, max); + + if(a === 0){ + // y goes from -inf to 0 + upperBound[1] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, max, 0); + + } else if(a === Math.PI / 2){ + + // x goes from 0 to inf + lowerBound[0] = 0; + // set(lowerBound, 0, -max); + // set(upperBound, max, max); + + } else if(a === Math.PI){ + + // y goes from 0 to inf + lowerBound[1] = 0; + // set(lowerBound, -max, 0); + // set(upperBound, max, max); + + } else if(a === 3*Math.PI/2){ + + // x goes from -inf to 0 + upperBound[0] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, 0, max); + + } +}; + +Plane.prototype.updateArea = function(){ + this.area = Number.MAX_VALUE; +}; + +var intersectPlane_planePointToFrom = vec2.create(); +var intersectPlane_dir_scaled_with_t = vec2.create(); +var intersectPlane_hitPoint = vec2.create(); +var intersectPlane_normal = vec2.create(); +var intersectPlane_len = vec2.create(); + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Plane.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + var planePointToFrom = intersectPlane_planePointToFrom; + var dir_scaled_with_t = intersectPlane_dir_scaled_with_t; + var hitPoint = intersectPlane_hitPoint; + var normal = intersectPlane_normal; + var len = intersectPlane_len; + + // Get plane normal + vec2.set(normal, 0, 1); + vec2.rotate(normal, normal, angle); + + vec2.sub(len, from, position); + var planeToFrom = vec2.dot(len, normal); + vec2.sub(len, to, position); + var planeToTo = vec2.dot(len, normal); + + if(planeToFrom * planeToTo > 0){ + // "from" and "to" are on the same side of the plane... bail out + return; + } + + if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){ + return; + } + + var n_dot_dir = vec2.dot(normal, direction); + + vec2.sub(planePointToFrom, from, position); + var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length; + + ray.reportIntersection(result, t, normal, -1); +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(_dereq_,module,exports){ +module.exports = Shape; + +var vec2 = _dereq_('../math/vec2'); + +/** + * Base class for shapes. + * @class Shape + * @constructor + * @param {object} [options] + * @param {array} [options.position] + * @param {number} [options.angle=0] + * @param {number} [options.collisionGroup=1] + * @param {number} [options.collisionMask=1] + * @param {boolean} [options.sensor=false] + * @param {boolean} [options.collisionResponse=true] + * @param {object} [options.type=0] + */ +function Shape(options){ + options = options || {}; + + /** + * The body this shape is attached to. A shape can only be attached to a single body. + * @property {Body} body + */ + this.body = null; + + /** + * Body-local position of the shape. + * @property {Array} position + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * Body-local angle of the shape. + * @property {number} angle + */ + this.angle = options.angle || 0; + + /** + * The type of the shape. One of: + * + * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} + * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} + * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} + * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} + * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} + * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}} + * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} + * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} + * + * @property {number} type + */ + this.type = options.type || 0; + + /** + * Shape object identifier. + * @type {Number} + * @property id + */ + this.id = Shape.idCounter++; + + /** + * Bounding circle radius of this shape + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + /** + * Collision group that this shape belongs to (bit mask). See this tutorial. + * @property collisionGroup + * @type {Number} + * @example + * // Setup bits for each available group + * var PLAYER = Math.pow(2,0), + * ENEMY = Math.pow(2,1), + * GROUND = Math.pow(2,2) + * + * // Put shapes into their groups + * player1Shape.collisionGroup = PLAYER; + * player2Shape.collisionGroup = PLAYER; + * enemyShape .collisionGroup = ENEMY; + * groundShape .collisionGroup = GROUND; + * + * // Assign groups that each shape collide with. + * // Note that the players can collide with ground and enemies, but not with other players. + * player1Shape.collisionMask = ENEMY | GROUND; + * player2Shape.collisionMask = ENEMY | GROUND; + * enemyShape .collisionMask = PLAYER | GROUND; + * groundShape .collisionMask = PLAYER | ENEMY; + * + * @example + * // How collision check is done + * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ + * // The shapes will collide + * } + */ + this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. + * @property {Boolean} collisionResponse + */ + this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; + + /** + * Collision mask of this shape. See .collisionGroup. + * @property collisionMask + * @type {Number} + */ + this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; + + /** + * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. + * @property material + * @type {Material} + */ + this.material = options.material || null; + + /** + * Area of this shape. + * @property area + * @type {Number} + */ + this.area = 0; + + /** + * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. + * @property {Boolean} sensor + */ + this.sensor = options.sensor !== undefined ? options.sensor : false; + + if(this.type){ + this.updateBoundingRadius(); + } + + this.updateArea(); +} + +Shape.idCounter = 0; + +/** + * @static + * @property {Number} CIRCLE + */ +Shape.CIRCLE = 1; + +/** + * @static + * @property {Number} PARTICLE + */ +Shape.PARTICLE = 2; + +/** + * @static + * @property {Number} PLANE + */ +Shape.PLANE = 4; + +/** + * @static + * @property {Number} CONVEX + */ +Shape.CONVEX = 8; + +/** + * @static + * @property {Number} LINE + */ +Shape.LINE = 16; + +/** + * @static + * @property {Number} BOX + */ +Shape.BOX = 32; + +/** + * @static + * @property {Number} CAPSULE + */ +Shape.CAPSULE = 64; + +/** + * @static + * @property {Number} HEIGHTFIELD + */ +Shape.HEIGHTFIELD = 128; + +/** + * Should return the moment of inertia around the Z axis of the body given the total mass. See Wikipedia's list of moments of inertia. + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. + */ +Shape.prototype.computeMomentOfInertia = function(mass){}; + +/** + * Returns the bounding circle radius of this shape. + * @method updateBoundingRadius + * @return {Number} + */ +Shape.prototype.updateBoundingRadius = function(){}; + +/** + * Update the .area property of the shape. + * @method updateArea + */ +Shape.prototype.updateArea = function(){ + // To be implemented in all subclasses +}; + +/** + * Compute the world axis-aligned bounding box (AABB) of this shape. + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position World position of the shape. + * @param {Number} angle World angle of the shape. + */ +Shape.prototype.computeAABB = function(out, position, angle){ + // To be implemented in each subclass +}; + +/** + * Perform raycasting on this shape. + * @method raycast + * @param {RayResult} result Where to store the resulting data. + * @param {Ray} ray The Ray that you want to use for raycasting. + * @param {array} position World position of the shape (the .position property will be ignored). + * @param {number} angle World angle of the shape (the .angle property will be ignored). + */ +Shape.prototype.raycast = function(result, ray, position, angle){ + // To be implemented in each subclass +}; +},{"../math/vec2":30}],46:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Solver = _dereq_('./Solver') +, Utils = _dereq_('../utils/Utils') +, FrictionEquation = _dereq_('../equations/FrictionEquation'); + +module.exports = GSSolver; + +/** + * Iterative Gauss-Seidel constraint equation solver. + * + * @class GSSolver + * @constructor + * @extends Solver + * @param {Object} [options] + * @param {Number} [options.iterations=10] + * @param {Number} [options.tolerance=0] + */ +function GSSolver(options){ + Solver.call(this,options,Solver.GS); + options = options || {}; + + /** + * The max number of iterations to do when solving. More gives better results, but is more expensive. + * @property iterations + * @type {Number} + */ + this.iterations = options.iterations || 10; + + /** + * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. + * @property tolerance + * @type {Number} + * @default 1e-7 + */ + this.tolerance = options.tolerance || 1e-7; + + this.arrayStep = 30; + this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); + + /** + * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. + * @property useZeroRHS + * @type {Boolean} + * @todo Remove, not used + */ + this.useZeroRHS = false; + + /** + * Number of solver iterations that are used to approximate normal forces used for friction (F_friction = mu * F_normal). These friction forces will override any other friction forces that are set. If you set frictionIterations = 0, then this feature will be disabled. + * + * Use only frictionIterations > 0 if the approximated normal force (F_normal = mass * gravity) is not good enough. Examples of where it can happen is in space games where gravity is zero, or in tall stacks where the normal force is large at bottom but small at top. + * + * @property frictionIterations + * @type {Number} + * @default 0 + */ + this.frictionIterations = options.frictionIterations !== undefined ? 0 : options.frictionIterations; + + /** + * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. + * @property {Number} usedIterations + */ + this.usedIterations = 0; +} +GSSolver.prototype = new Solver(); +GSSolver.prototype.constructor = GSSolver; + +function setArrayZero(array){ + var l = array.length; + while(l--){ + array[l] = +0.0; + } +} + +/** + * Solve the system of equations + * @method solve + * @param {Number} h Time step + * @param {World} world World to solve + */ +GSSolver.prototype.solve = function(h, world){ + + this.sortEquations(); + + var iter = 0, + maxIter = this.iterations, + maxFrictionIter = this.frictionIterations, + equations = this.equations, + Neq = equations.length, + tolSquared = Math.pow(this.tolerance*Neq, 2), + bodies = world.bodies, + Nbodies = world.bodies.length, + add = vec2.add, + set = vec2.set, + useZeroRHS = this.useZeroRHS, + lambda = this.lambda; + + this.usedIterations = 0; + + if(Neq){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Update solve mass + b.updateSolveMassProperties(); + } + } + + // Things that does not change during iteration can be computed once + if(lambda.length < Neq){ + lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + } + setArrayZero(lambda); + var invCs = this.invCs, + Bs = this.Bs, + lambda = this.lambda; + + for(var i=0; i!==equations.length; i++){ + var c = equations[i]; + if(c.timeStep !== h || c.needsUpdate){ + c.timeStep = h; + c.update(); + } + Bs[i] = c.computeB(c.a,c.b,h); + invCs[i] = c.computeInvC(c.epsilon); + } + + var q, B, c, deltalambdaTot,i,j; + + if(Neq !== 0){ + + for(i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Reset vlambda + b.resetConstraintVelocity(); + } + + if(maxFrictionIter){ + // Iterate over contact equations to get normal forces + for(iter=0; iter!==maxFrictionIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + + // Set computed friction force + for(j=0; j!==Neq; j++){ + var eq = equations[j]; + if(eq instanceof FrictionEquation){ + var f = 0.0; + for(var k=0; k!==eq.contactEquations.length; k++){ + f += eq.contactEquations[k].multiplier; + } + f *= eq.frictionCoefficient / eq.contactEquations.length; + eq.maxForce = f; + eq.minForce = -f; + } + } + } + + // Iterate over all equations + for(iter=0; iter!==maxIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + // Add result to velocity + for(i=0; i!==Nbodies; i++){ + bodies[i].addConstraintVelocity(); + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + } +}; + +// Sets the .multiplier property of each equation +GSSolver.updateMultipliers = function(equations, lambda, invDt){ + // Set the .multiplier property of each equation + var l = equations.length; + while(l--){ + equations[l].multiplier = lambda[l] * invDt; + } +}; + +GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ + // Compute iteration + var B = Bs[j], + invC = invCs[j], + lambdaj = lambda[j], + GWlambda = eq.computeGWlambda(); + + var maxForce = eq.maxForce, + minForce = eq.minForce; + + if(useZeroRHS){ + B = 0; + } + + var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); + + // Clamp if we are not within the min/max interval + var lambdaj_plus_deltalambda = lambdaj + deltalambda; + if(lambdaj_plus_deltalambda < minForce*dt){ + deltalambda = minForce*dt - lambdaj; + } else if(lambdaj_plus_deltalambda > maxForce*dt){ + deltalambda = maxForce*dt - lambdaj; + } + lambda[j] += deltalambda; + eq.addToWlambda(deltalambda); + + return deltalambda; +}; + +},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Solver; + +/** + * Base class for constraint solvers. + * @class Solver + * @constructor + * @extends EventEmitter + */ +function Solver(options,type){ + options = options || {}; + + EventEmitter.call(this); + + this.type = type; + + /** + * Current equations in the solver. + * + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Function that is used to sort all equations before each solve. + * @property equationSortFunction + * @type {function|boolean} + */ + this.equationSortFunction = options.equationSortFunction || false; +} +Solver.prototype = new EventEmitter(); +Solver.prototype.constructor = Solver; + +/** + * Method to be implemented in each subclass + * @method solve + * @param {Number} dt + * @param {World} world + */ +Solver.prototype.solve = function(dt,world){ + throw new Error("Solver.solve should be implemented by subclasses!"); +}; + +var mockWorld = {bodies:[]}; + +/** + * Solves all constraints in an island. + * @method solveIsland + * @param {Number} dt + * @param {Island} island + */ +Solver.prototype.solveIsland = function(dt,island){ + + this.removeAllEquations(); + + if(island.equations.length){ + // Add equations to solver + this.addEquations(island.equations); + mockWorld.bodies.length = 0; + island.getBodies(mockWorld.bodies); + + // Solve + if(mockWorld.bodies.length){ + this.solve(dt,mockWorld); + } + } +}; + +/** + * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. + * @method sortEquations + */ +Solver.prototype.sortEquations = function(){ + if(this.equationSortFunction){ + this.equations.sort(this.equationSortFunction); + } +}; + +/** + * Add an equation to be solved. + * + * @method addEquation + * @param {Equation} eq + */ +Solver.prototype.addEquation = function(eq){ + if(eq.enabled){ + this.equations.push(eq); + } +}; + +/** + * Add equations. Same as .addEquation, but this time the argument is an array of Equations + * + * @method addEquations + * @param {Array} eqs + */ +Solver.prototype.addEquations = function(eqs){ + //Utils.appendArray(this.equations,eqs); + for(var i=0, N=eqs.length; i!==N; i++){ + var eq = eqs[i]; + if(eq.enabled){ + this.equations.push(eq); + } + } +}; + +/** + * Remove an equation. + * + * @method removeEquation + * @param {Equation} eq + */ +Solver.prototype.removeEquation = function(eq){ + var i = this.equations.indexOf(eq); + if(i !== -1){ + this.equations.splice(i,1); + } +}; + +/** + * Remove all currently added equations. + * + * @method removeAllEquations + */ +Solver.prototype.removeAllEquations = function(){ + this.equations.length=0; +}; + +Solver.GS = 1; +Solver.ISLAND = 2; + +},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){ +var ContactEquation = _dereq_('../equations/ContactEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = ContactEquationPool; + +/** + * @class + */ +function ContactEquationPool() { + Pool.apply(this, arguments); +} +ContactEquationPool.prototype = new Pool(); +ContactEquationPool.prototype.constructor = ContactEquationPool; + +/** + * @method create + * @return {ContactEquation} + */ +ContactEquationPool.prototype.create = function () { + return new ContactEquation(); +}; + +/** + * @method destroy + * @param {ContactEquation} equation + * @return {ContactEquationPool} + */ +ContactEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){ +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = FrictionEquationPool; + +/** + * @class + */ +function FrictionEquationPool() { + Pool.apply(this, arguments); +} +FrictionEquationPool.prototype = new Pool(); +FrictionEquationPool.prototype.constructor = FrictionEquationPool; + +/** + * @method create + * @return {FrictionEquation} + */ +FrictionEquationPool.prototype.create = function () { + return new FrictionEquation(); +}; + +/** + * @method destroy + * @param {FrictionEquation} equation + * @return {FrictionEquationPool} + */ +FrictionEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){ +var IslandNode = _dereq_('../world/IslandNode'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandNodePool; + +/** + * @class + */ +function IslandNodePool() { + Pool.apply(this, arguments); +} +IslandNodePool.prototype = new Pool(); +IslandNodePool.prototype.constructor = IslandNodePool; + +/** + * @method create + * @return {IslandNode} + */ +IslandNodePool.prototype.create = function () { + return new IslandNode(); +}; + +/** + * @method destroy + * @param {IslandNode} node + * @return {IslandNodePool} + */ +IslandNodePool.prototype.destroy = function (node) { + node.reset(); + return this; +}; + +},{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){ +var Island = _dereq_('../world/Island'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandPool; + +/** + * @class + */ +function IslandPool() { + Pool.apply(this, arguments); +} +IslandPool.prototype = new Pool(); +IslandPool.prototype.constructor = IslandPool; + +/** + * @method create + * @return {Island} + */ +IslandPool.prototype.create = function () { + return new Island(); +}; + +/** + * @method destroy + * @param {Island} island + * @return {IslandPool} + */ +IslandPool.prototype.destroy = function (island) { + island.reset(); + return this; +}; + +},{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){ +var TupleDictionary = _dereq_('./TupleDictionary'); +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool'); +var Utils = _dereq_('./Utils'); + +module.exports = OverlapKeeper; + +/** + * Keeps track of overlaps in the current state and the last step state. + * @class OverlapKeeper + * @constructor + */ +function OverlapKeeper() { + this.overlappingShapesLastState = new TupleDictionary(); + this.overlappingShapesCurrentState = new TupleDictionary(); + this.recordPool = new OverlapKeeperRecordPool({ size: 16 }); + this.tmpDict = new TupleDictionary(); + this.tmpArray1 = []; +} + +/** + * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current. + * @method tick + */ +OverlapKeeper.prototype.tick = function() { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Save old objects into pool + var l = last.keys.length; + while(l--){ + var key = last.keys[l]; + var lastObject = last.getByKey(key); + var currentObject = current.getByKey(key); + if(lastObject){ + // The record is only used in the "last" dict, and will be removed. We might as well pool it. + this.recordPool.release(lastObject); + } + } + + // Clear last object + last.reset(); + + // Transfer from new object to old + last.copy(current); + + // Clear current object + current.reset(); +}; + +/** + * @method setOverlapping + * @param {Body} bodyA + * @param {Body} shapeA + * @param {Body} bodyB + * @param {Body} shapeB + */ +OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Store current contact state + if(!current.get(shapeA.id, shapeB.id)){ + var data = this.recordPool.get(); + data.set(bodyA, shapeA, bodyB, shapeB); + current.set(shapeA.id, shapeB.id, data); + } +}; + +OverlapKeeper.prototype.getNewOverlaps = function(result){ + return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result); +}; + +OverlapKeeper.prototype.getEndOverlaps = function(result){ + return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result); +}; + +/** + * Checks if two bodies are currently overlapping. + * @method bodiesAreOverlapping + * @param {Body} bodyA + * @param {Body} bodyB + * @return {boolean} + */ +OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){ + var current = this.overlappingShapesCurrentState; + var l = current.keys.length; + while(l--){ + var key = current.keys[l]; + var data = current.data[key]; + if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){ + return true; + } + } + return false; +}; + +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){ + // Not overlapping in last state, but in current. + result.push(data); + } + } + + return result; +}; + +OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ + var idA = shapeA.id|0, + idB = shapeB.id|0; + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + // Not in last but in new + return !!!last.get(idA, idB) && !!current.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]; + + // Since we use body id's for the accumulator, these will be a subset of the original one + accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); + } + + l = accumulator.keys.length; + while(l--){ + var data = accumulator.getByKey(accumulator.keys[l]); + if(data){ + result.push(data.bodyA, data.bodyB); + } + } + + accumulator.reset(); + + return result; +}; + +},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){ +module.exports = OverlapKeeperRecord; + +/** + * Overlap data container for the OverlapKeeper + * @class OverlapKeeperRecord + * @constructor + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ + /** + * @property {Shape} shapeA + */ + this.shapeA = shapeA; + /** + * @property {Shape} shapeB + */ + this.shapeB = shapeB; + /** + * @property {Body} bodyA + */ + this.bodyA = bodyA; + /** + * @property {Body} bodyB + */ + this.bodyB = bodyB; +} + +/** + * Set the data for the record + * @method set + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ + OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); +}; + +},{}],54:[function(_dereq_,module,exports){ +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var Pool = _dereq_('./Pool'); + +module.exports = OverlapKeeperRecordPool; + +/** + * @class + */ +function OverlapKeeperRecordPool() { + Pool.apply(this, arguments); +} +OverlapKeeperRecordPool.prototype = new Pool(); +OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool; + +/** + * @method create + * @return {OverlapKeeperRecord} + */ +OverlapKeeperRecordPool.prototype.create = function () { + return new OverlapKeeperRecord(); +}; + +/** + * @method destroy + * @param {OverlapKeeperRecord} record + * @return {OverlapKeeperRecordPool} + */ +OverlapKeeperRecordPool.prototype.destroy = function (record) { + record.bodyA = record.bodyB = record.shapeA = record.shapeB = null; + return this; +}; + +},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){ +module.exports = Pool; + +/** + * @class Object pooling utility. + */ +function Pool(options) { + options = options || {}; + + /** + * @property {Array} objects + * @type {Array} + */ + this.objects = []; + + if(options.size !== undefined){ + this.resize(options.size); + } +} + +/** + * @method resize + * @param {number} size + * @return {Pool} Self, for chaining + */ +Pool.prototype.resize = function (size) { + var objects = this.objects; + + while (objects.length > size) { + objects.pop(); + } + + while (objects.length < size) { + objects.push(this.create()); + } + + return this; +}; + +/** + * Get an object from the pool or create a new instance. + * @method get + * @return {Object} + */ +Pool.prototype.get = function () { + var objects = this.objects; + return objects.length ? objects.pop() : this.create(); +}; + +/** + * Clean up and put the object back into the pool for later use. + * @method release + * @param {Object} object + * @return {Pool} Self for chaining + */ +Pool.prototype.release = function (object) { + this.destroy(object); + this.objects.push(object); + return this; +}; + +},{}],56:[function(_dereq_,module,exports){ +var Utils = _dereq_('./Utils'); + +module.exports = TupleDictionary; + +/** + * @class TupleDictionary + * @constructor + */ +function TupleDictionary() { + + /** + * The data storage + * @property data + * @type {Object} + */ + this.data = {}; + + /** + * Keys that are currently used. + * @property {Array} keys + */ + this.keys = []; +} + +/** + * Generate a key given two integers + * @method getKey + * @param {number} i + * @param {number} j + * @return {string} + */ +TupleDictionary.prototype.getKey = function(id1, id2) { + id1 = id1|0; + id2 = id2|0; + + if ( (id1|0) === (id2|0) ){ + return -1; + } + + // valid for values < 2^16 + return ((id1|0) > (id2|0) ? + (id1 << 16) | (id2 & 0xFFFF) : + (id2 << 16) | (id1 & 0xFFFF))|0 + ; +}; + +/** + * @method getByKey + * @param {Number} key + * @return {Object} + */ +TupleDictionary.prototype.getByKey = function(key) { + key = key|0; + return this.data[key]; +}; + +/** + * @method get + * @param {Number} i + * @param {Number} j + * @return {Number} + */ +TupleDictionary.prototype.get = function(i, j) { + return this.data[this.getKey(i, j)]; +}; + +/** + * Set a value. + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +TupleDictionary.prototype.set = function(i, j, value) { + if(!value){ + throw new Error("No data!"); + } + + var key = this.getKey(i, j); + + // Check if key already exists + if(!this.data[key]){ + this.keys.push(key); + } + + this.data[key] = value; + + return key; +}; + +/** + * Remove all data. + * @method reset + */ +TupleDictionary.prototype.reset = function() { + var data = this.data, + keys = this.keys; + + var l = keys.length; + while(l--) { + delete data[keys[l]]; + } + + keys.length = 0; +}; + +/** + * Copy another TupleDictionary. Note that all data in this dictionary will be removed. + * @method copy + * @param {TupleDictionary} dict The TupleDictionary to copy into this one. + */ +TupleDictionary.prototype.copy = function(dict) { + this.reset(); + Utils.appendArray(this.keys, dict.keys); + var l = dict.keys.length; + while(l--){ + var key = dict.keys[l]; + this.data[key] = dict.data[key]; + } +}; + +},{"./Utils":57}],57:[function(_dereq_,module,exports){ +/* global P2_ARRAY_TYPE */ + +module.exports = Utils; + +/** + * Misc utility functions + * @class Utils + * @constructor + */ +function Utils(){} + +/** + * Append the values in array b to the array a. See this for an explanation. + * @method appendArray + * @static + * @param {Array} a + * @param {Array} b + */ +Utils.appendArray = function(a,b){ + if (b.length < 150000) { + a.push.apply(a, b); + } else { + for (var i = 0, len = b.length; i !== len; ++i) { + a.push(b[i]); + } + } +}; + +/** + * Garbage free Array.splice(). Does not allocate a new array. + * @method splice + * @static + * @param {Array} array + * @param {Number} index + * @param {Number} howmany + */ +Utils.splice = function(array,index,howmany){ + howmany = howmany || 1; + for (var i=index, len=array.length-howmany; i < len; i++){ + array[i] = array[i + howmany]; + } + array.length = len; +}; + +/** + * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. + * @static + * @property {function} ARRAY_TYPE + * @example + * + * + */ +if(typeof P2_ARRAY_TYPE !== 'undefined') { + Utils.ARRAY_TYPE = P2_ARRAY_TYPE; +} else if (typeof Float32Array !== 'undefined'){ + Utils.ARRAY_TYPE = Float32Array; +} else { + Utils.ARRAY_TYPE = Array; +} + +/** + * Extend an object with the properties of another + * @static + * @method extend + * @param {object} a + * @param {object} b + */ +Utils.extend = function(a,b){ + for(var key in b){ + a[key] = b[key]; + } +}; + +/** + * Extend an options object with default values. + * @static + * @method defaults + * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. + * @param {object} defaults An object containing default values. + * @return {object} The modified options object. + */ +Utils.defaults = function(options, defaults){ + options = options || {}; + for(var key in defaults){ + if(!(key in options)){ + options[key] = defaults[key]; + } + } + return options; +}; + +},{}],58:[function(_dereq_,module,exports){ +var Body = _dereq_('../objects/Body'); + +module.exports = Island; + +/** + * An island of bodies connected with equations. + * @class Island + * @constructor + */ +function Island(){ + + /** + * Current equations in this island. + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Current bodies in this island. + * @property bodies + * @type {Array} + */ + this.bodies = []; +} + +/** + * Clean this island from bodies and equations. + * @method reset + */ +Island.prototype.reset = function(){ + this.equations.length = this.bodies.length = 0; +}; + +var bodyIds = []; + +/** + * Get all unique bodies in this island. + * @method getBodies + * @return {Array} An array of Body + */ +Island.prototype.getBodies = function(result){ + var bodies = result || [], + eqs = this.equations; + bodyIds.length = 0; + for(var i=0; i!==eqs.length; i++){ + var eq = eqs[i]; + if(bodyIds.indexOf(eq.bodyA.id)===-1){ + bodies.push(eq.bodyA); + bodyIds.push(eq.bodyA.id); + } + if(bodyIds.indexOf(eq.bodyB.id)===-1){ + bodies.push(eq.bodyB); + bodyIds.push(eq.bodyB.id); + } + } + return bodies; +}; + +/** + * Check if the entire island wants to sleep. + * @method wantsToSleep + * @return {Boolean} + */ +Island.prototype.wantsToSleep = function(){ + for(var i=0; i= dt && substeps < maxSubSteps) { + // Do fixed steps to catch up + this.internalStep(dt); + this.time += dt; + this.accumulator -= dt; + substeps++; + } + + var t = (this.accumulator % dt) / dt; + for(var j=0; j!==this.bodies.length; j++){ + var b = this.bodies[j]; + vec2.lerp(b.interpolatedPosition, b.previousPosition, b.position, t); + b.interpolatedAngle = b.previousAngle + t * (b.angle - b.previousAngle); + } + } +}; + +var endOverlaps = []; + +/** + * Make a fixed step. + * @method internalStep + * @param {number} dt + * @private + */ +World.prototype.internalStep = function(dt){ + this.stepping = true; + + var that = this, + Nsprings = this.springs.length, + springs = this.springs, + bodies = this.bodies, + g = this.gravity, + solver = this.solver, + Nbodies = this.bodies.length, + broadphase = this.broadphase, + np = this.narrowphase, + constraints = this.constraints, + t0, t1, + fhMinv = step_fhMinv, + velodt = step_velodt, + mg = step_mg, + scale = vec2.scale, + add = vec2.add, + rotate = vec2.rotate, + islandManager = this.islandManager; + + this.overlapKeeper.tick(); + + this.lastTimeStep = dt; + + // Update approximate friction gravity. + if(this.useWorldGravityAsFrictionGravity){ + var gravityLen = vec2.length(this.gravity); + if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){ + // Nonzero gravity. Use it. + this.frictionGravity = gravityLen; + } + } + + // Add gravity to bodies + if(this.applyGravity){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i], + fi = b.force; + if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ + continue; + } + vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g + add(fi,fi,mg); + } + } + + // Add spring forces + if(this.applySpringForces){ + for(var i=0; i!==Nsprings; i++){ + var s = springs[i]; + s.applyForce(); + } + } + + if(this.applyDamping){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + if(b.type === Body.DYNAMIC){ + b.applyDamping(dt); + } + } + } + + // Broadphase + var result = broadphase.getCollisionPairs(this); + + // Remove ignored collision pairs + var ignoredPairs = this.disabledBodyCollisionPairs; + for(var i=ignoredPairs.length-2; 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); + } + } + } + + // Remove constrained pairs with collideConnected == false + 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); + } + } + } + } + + // postBroadphase event + this.postBroadphaseEvent.pairs = result; + this.emit(this.postBroadphaseEvent); + this.postBroadphaseEvent.pairs = null; + + // Narrowphase + np.reset(this); + for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ + var bi = result[i], + bj = result[i+1]; + + // Loop over all shapes of body i + for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ + var si = bi.shapes[k], + xi = si.position, + ai = si.angle; + + // All shapes of body j + for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ + var sj = bj.shapes[l], + xj = sj.position, + aj = sj.angle; + + 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); + } + } + } + + // Wake up bodies + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + if(body._wakeUpAfterNarrowphase){ + body.wakeUp(); + body._wakeUpAfterNarrowphase = false; + } + } + + // Emit end overlap events + 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.bodyB; + this.emit(e); + } + endOverlaps.length = 0; + } + + var preSolveEvent = this.preSolveEvent; + preSolveEvent.contactEquations = np.contactEquations; + preSolveEvent.frictionEquations = np.frictionEquations; + this.emit(preSolveEvent); + preSolveEvent.contactEquations = preSolveEvent.frictionEquations = null; + + // update constraint equations + var Nconstraints = constraints.length; + for(i=0; i!==Nconstraints; i++){ + constraints[i].update(); + } + + if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){ + if(this.islandSplit){ + // Split into islands + 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 { + + // Add contact equations to solver + solver.addEquations(np.contactEquations); + solver.addEquations(np.frictionEquations); + + // Add user-defined constraint equations + for(i=0; i!==Nconstraints; i++){ + solver.addEquations(constraints[i].equations); + } + + if(this.solveConstraints){ + solver.solve(dt,this); + } + + solver.removeAllEquations(); + } + } + + // Step forward + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + + // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){ + body.integrate(dt); + // } + } + + // Reset force + for(var i=0; i!==Nbodies; i++){ + bodies[i].setZeroForce(); + } + + // Emit impact event + 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); + } + } + } + + // Sleeping update + if(this.sleepMode === World.BODY_SLEEPING){ + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, false, dt); + } + } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){ + + // Tell all bodies to sleep tick but dont sleep yet + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, true, dt); + } + + // Sleep islands + for(var i=0; i 0; + np.frictionCoefficient = cm.friction; + var reducedMass; + if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){ + reducedMass = bj.mass; + } else if(bj.type === Body.STATIC || bj.type === 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; + np.contactSkinSize = cm.contactSkinSize; + np.enabledEquations = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse; + + 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 < sj.type) { + numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); + } else { + numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); + } + var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; + + if(numContacts){ + + if( bi.allowSleep && + bi.type === Body.DYNAMIC && + bi.sleepState === Body.SLEEPING && + bj.sleepState === Body.AWAKE && + bj.type !== Body.STATIC + ){ + var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); + var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); + if(speedSquaredB >= speedLimitSquaredB*2){ + bi._wakeUpAfterNarrowphase = true; + } + } + + if( bj.allowSleep && + bj.type === Body.DYNAMIC && + bj.sleepState === Body.SLEEPING && + bi.sleepState === Body.AWAKE && + bi.type !== 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)){ + + // Report new shape overlap + var e = this.beginContactEvent; + e.shapeA = si; + e.shapeB = sj; + e.bodyA = bi; + e.bodyB = bj; + + // Reset contact equations + e.contactEquations.length = 0; + + if(typeof(numContacts)==="number"){ + for(var i=np.contactEquations.length-numContacts; i 1){ // Why divide by 1? + for(var i=np.frictionEquations.length-numFrictionEquations; i=0; i--){ + this.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.bodies; + for(var i=bodies.length-1; i>=0; i--){ + this.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.springs; + for(var i=springs.length-1; i>=0; i--){ + this.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.contactMaterials; + for(var i=cms.length-1; i>=0; i--){ + this.removeContactMaterial(cms[i]); + } + + World.apply(this); +}; + +var hitTest_tmp1 = vec2.create(), + hitTest_zero = vec2.fromValues(0,0), + hitTest_tmp2 = vec2.fromValues(0,0); + +/** + * Test if a world point overlaps bodies + * @method hitTest + * @param {Array} worldPoint Point to use for intersection tests + * @param {Array} bodies A list of objects to check for intersection + * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @return {Array} Array of bodies that overlap the point + * @todo Should use an api similar to the raycast function + * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient + * @todo Should use the broadphase + */ +World.prototype.hitTest = function(worldPoint,bodies,precision){ + precision = precision || 0; + + // Create a dummy particle body with a particle shape to test against the bodies + 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 = []; + + // Check bodies + 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]; + + // Get shape world position + angle + vec2.rotate(x, s.position, b.angle); + vec2.add(x, x, b.position); + var a = s.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)) < precision*precision) + ){ + result.push(b); + } + } + } + + return result; +}; + +/** + * Set the stiffness for all equations and contact materials. + * @method setGlobalStiffness + * @param {Number} stiffness + */ +World.prototype.setGlobalStiffness = function(stiffness){ + + // Set for all constraints + var constraints = this.constraints; + for(var i=0; i !== constraints.length; i++){ + var c = constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.stiffness = stiffness; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + var contactMaterials = this.contactMaterials; + for(var i=0; i !== contactMaterials.length; i++){ + var c = contactMaterials[i]; + c.stiffness = c.frictionStiffness = stiffness; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.stiffness = c.frictionStiffness = stiffness; +}; + +/** + * Set the relaxation for all equations and contact materials. + * @method setGlobalRelaxation + * @param {Number} relaxation + */ +World.prototype.setGlobalRelaxation = function(relaxation){ + + // Set for all constraints + for(var i=0; i !== this.constraints.length; i++){ + var c = this.constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.relaxation = relaxation; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + for(var i=0; i !== this.contactMaterials.length; i++){ + var c = this.contactMaterials[i]; + c.relaxation = c.frictionRelaxation = relaxation; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.relaxation = c.frictionRelaxation = relaxation; +}; + +var tmpAABB = new AABB(); +var tmpArray = []; + +/** + * Ray cast against all bodies in the world. + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @return {boolean} True if any body was hit. + * + * @example + * var ray = new Ray({ + * mode: Ray.CLOSEST, // or ANY + * from: [0, 0], + * to: [10, 0], + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * @example + * var ray = new Ray({ + * mode: Ray.ALL, + * from: [0, 0], + * to: [10, 0], + * callback: function(result){ + * + * // Print some info about the hit + * console.log('Hit body and shape: ', result.body, result.shape); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * // If you are happy with the hits you got this far, you can stop the traversal here: + * result.stop(); + * } + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + */ +World.prototype.raycast = function(result, ray){ + + // Get all bodies within the ray AABB + ray.getAABB(tmpAABB); + this.broadphase.aabbQuery(this, tmpAABB, tmpArray); + ray.intersectBodies(result, tmpArray); + tmpArray.length = 0; + + return result.hasHit(); +}; + +},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36]) +(36) +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +(function(){ + + var root = this; + +/** + * Namespace-class for [pixi.js](http://www.pixijs.com/). + * + * Contains assorted static properties and enumerations. + * + * @namespace PIXI + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ +var PIXI = PIXI || {}; + +/** +* @author Mat Groves http://matgroves.com @Doormat23 +* @author Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The base class for all objects that are rendered. Contains properties for position, scaling, +* rotation, masks and cache handling. +* +* This is an abstract class and should not be used on its own, rather it should be extended. +* +* It is used internally by the likes of PIXI.Sprite. +* +* @class PIXI.DisplayObject +* @constructor +*/ +PIXI.DisplayObject = function () { + + /** + * The coordinates, in pixels, of this DisplayObject, relative to its parent container. + * + * The value of this property does not reflect any positioning happening further up the display list. + * To obtain that value please see the `worldPosition` property. + * + * @property {PIXI.Point} position + * @default + */ + this.position = new PIXI.Point(0, 0); + + /** + * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject + * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on. + * + * The value of this property does not reflect any scaling happening further up the display list. + * To obtain that value please see the `worldScale` property. + * + * @property {PIXI.Point} scale + * @default + */ + this.scale = new PIXI.Point(1, 1); + + /** + * The pivot point of this DisplayObject that it rotates around. The values are expressed + * in pixel values. + * @property {PIXI.Point} pivot + * @default + */ + this.pivot = new PIXI.Point(0, 0); + + /** + * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on + * a right-handed orientation. + * + * The value of this property does not reflect any rotation happening further up the display list. + * To obtain that value please see the `worldRotation` property. + * + * @property {number} rotation + * @default + */ + this.rotation = 0; + + /** + * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * Please note that an object with an alpha value of 0 is skipped during the render pass. + * + * The value of this property does not reflect any alpha values set further up the display list. + * To obtain that value please see the `worldAlpha` property. + * + * @property {number} alpha + * @default + */ + this.alpha = 1; + + /** + * The visibility of this DisplayObject. A value of `false` makes the object invisible. + * A value of `true` makes it visible. Please note that an object with a visible value of + * `false` is skipped during the render pass. Equally a DisplayObject with visible false will + * not render any of its children. + * + * The value of this property does not reflect any visible values set further up the display list. + * To obtain that value please see the `worldVisible` property. + * + * @property {boolean} visible + * @default + */ + this.visible = true; + + /** + * This is the defined area that will pick up mouse / touch events. It is null by default. + * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children) + * + * @property hitArea + * @type Rectangle|Circle|Ellipse|Polygon + */ + this.hitArea = null; + + /** + * Should this DisplayObject be rendered by the renderer? An object with a renderable value of + * `false` is skipped during the render pass. + * + * @property {boolean} renderable + * @default + */ + this.renderable = false; + + /** + * The parent DisplayObjectContainer that this DisplayObject is a child of. + * All DisplayObjects must belong to a parent in order to be rendered. + * The root parent is the Stage object. This property is set automatically when the + * DisplayObject is added to, or removed from, a DisplayObjectContainer. + * + * @property {PIXI.DisplayObjectContainer} parent + * @default + * @readOnly + */ + this.parent = null; + + /** + * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects + * in the display list. + * + * To obtain, and set, the local alpha value, see the `alpha` property. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldAlpha + * @readOnly + */ + this.worldAlpha = 1; + + /** + * The current transform of this DisplayObject. + * + * This property contains the calculated total, based on the transforms of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {Phaser.Matrix} worldTransform + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * The coordinates, in pixels, of this DisplayObject within the world. + * + * This property contains the calculated total, based on the positions of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldPosition + * @readOnly + */ + this.worldPosition = new PIXI.Point(0, 0); + + /** + * The global scale of this DisplayObject. + * + * This property contains the calculated total, based on the scales of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldScale + * @readOnly + */ + this.worldScale = new PIXI.Point(1, 1); + + /** + * The rotation, in radians, of this DisplayObject. + * + * This property contains the calculated total, based on the rotations of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldRotation + * @readOnly + */ + this.worldRotation = 0; + + /** + * The rectangular area used by filters when rendering a shader for this DisplayObject. + * + * @property {PIXI.Rectangle} filterArea + * @type Rectangle + * @default + */ + this.filterArea = null; + + /** + * @property {number} _sr - Cached rotation value. + * @private + */ + this._sr = 0; + + /** + * @property {number} _cr - Cached rotation value. + * @private + */ + this._cr = 1; + + /** + * @property {PIXI.Rectangle} _bounds - The cached bounds of this object. + * @private + */ + this._bounds = new PIXI.Rectangle(0, 0, 0, 0); + + /** + * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object. + * @private + */ + this._currentBounds = null; + + /** + * @property {PIXI.Rectangle} _mask - The cached mask of this object. + * @private + */ + this._mask = null; + + /** + * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag. + * @private + */ + this._cacheAsBitmap = false; + + /** + * @property {boolean} _cacheIsDirty - Internal dirty cache flag. + * @private + */ + this._cacheIsDirty = false; + +}; + +PIXI.DisplayObject.prototype = { + + constructor: PIXI.DisplayObject, + + /** + * Destroy this DisplayObject. + * + * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask. + * + * Also iteratively calls `destroy` on any children. + * + * @method PIXI.DisplayObject#destroy + */ + destroy: function () { + + if (this.children) + { + var i = this.children.length; + + while (i--) + { + this.children[i].destroy(); + } + + this.children = []; + } + + this.hitArea = null; + this.parent = null; + this.worldTransform = null; + this.filterArea = null; + this.renderable = false; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + }, + + /** + * Updates the transform matrix this DisplayObject uses for rendering. + * + * If the object has no parent, and no parent parameter is provided, it will default to + * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place. + * + * The `parent` parameter has priority over the actual parent. Use it as a parent override. + * Setting it does **not** change the actual parent of this DisplayObject. + * + * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale` + * and `worldRotation` properties. + * + * If a `transformCallback` has been specified, it is called at the end of this method, and is passed + * the new, updated, worldTransform property, along with the parent transform used. + * + * @method PIXI.DisplayObject#updateTransform + * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from. + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateTransform: function (parent) { + + if (!parent && !this.parent && !this.game) + { + return this; + } + + var p = this.parent; + + if (parent) + { + p = parent; + } + else if (!this.parent) + { + p = this.game.world; + } + + // create some matrix refs for easy access + var pt = p.worldTransform; + var wt = this.worldTransform; + + // temporary matrix variables + var a, b, c, d, tx, ty; + + // so if rotation is between 0 then we can simplify the multiplication process.. + if (this.rotation % Phaser.Math.PI2) + { + // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes + if (this.rotation !== this.rotationCache) + { + this.rotationCache = this.rotation; + this._sr = Math.sin(this.rotation); + this._cr = Math.cos(this.rotation); + } + + // get the matrix values of the displayobject based on its transform properties.. + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + tx = this.position.x; + ty = this.position.y; + + // check for pivot.. not often used so geared towards that fact! + if (this.pivot.x || this.pivot.y) + { + tx -= this.pivot.x * a + this.pivot.y * c; + ty -= this.pivot.x * b + this.pivot.y * d; + } + + // concat the parent matrix with the objects transform. + wt.a = a * pt.a + b * pt.c; + wt.b = a * pt.b + b * pt.d; + wt.c = c * pt.a + d * pt.c; + wt.d = c * pt.b + d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + else + { + // lets do the fast version as we know there is no rotation.. + a = this.scale.x; + b = 0; + c = 0; + d = this.scale.y; + tx = this.position.x - this.pivot.x * a; + ty = this.position.y - this.pivot.y * d; + + wt.a = a * pt.a; + wt.b = a * pt.b; + wt.c = d * pt.c; + wt.d = d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + + a = wt.a; + b = wt.b; + c = wt.c; + d = wt.d; + + var determ = (a * d) - (b * c); + + if (a || b) + { + var r = Math.sqrt((a * a) + (b * b)); + + this.worldRotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); + this.worldScale.x = r; + this.worldScale.y = determ / r; + } + else if (c || d) + { + var s = Math.sqrt((c * c) + (d * d)); + + this.worldRotation = Phaser.Math.HALF_PI - ((d > 0) ? Math.acos(-c / s) : -Math.acos(c / s)); + this.worldScale.x = determ / s; + this.worldScale.y = s; + } + else + { + this.worldScale.x = 0; + this.worldScale.y = 0; + } + + // Set the World values + this.worldAlpha = this.alpha * p.worldAlpha; + this.worldPosition.x = wt.tx; + this.worldPosition.y = wt.ty; + + // reset the bounds each time this is called! + this._currentBounds = null; + + // Custom callback? + if (this.transformCallback) + { + this.transformCallback.call(this.transformCallbackContext, wt, pt); + } + + return this; + + }, + + /** + * To be overridden by classes that require it. + * + * @method PIXI.DisplayObject#preUpdate + */ + preUpdate: function () { + + }, + + /** + * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites. + * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times. + * + * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures, + * and references to them, so they don't linger in memory. + * + * @method PIXI.DisplayObject#generateTexture + * @param {number} [resolution=1] - The resolution of the texture being generated. + * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values. + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture. + * @return {Phaser.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked. + */ + generateTexture: function (resolution, scaleMode, renderer) { + + var bounds = this.getLocalBounds(); + + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + + renderTexture.render(this, PIXI.DisplayObject._tempMatrix); + + return renderTexture; + + }, + + /** + * If this DisplayObject has a cached Sprite, this method generates and updates it. + * + * @method PIXI.DisplayObject#updateCache + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateCache: function () { + + this._generateCachedSprite(); + + return this; + + }, + + /** + * Calculates the global position of this DisplayObject, based on the position given. + * + * @method PIXI.DisplayObject#toGlobal + * @param {PIXI.Point} position - The global position to calculate from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toGlobal: function (position) { + + this.updateTransform(); + + return this.worldTransform.apply(position); + + }, + + /** + * Calculates the local position of this DisplayObject, relative to another point. + * + * @method PIXI.DisplayObject#toLocal + * @param {PIXI.Point} position - The world origin to calculate from. + * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toLocal: function (position, from) { + + if (from) + { + position = from.toGlobal(position); + } + + this.updateTransform(); + + return this.worldTransform.applyInverse(position); + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_renderCachedSprite + * @private + * @param {Object} renderSession - The render session + */ + _renderCachedSprite: function (renderSession) { + + this._cachedSprite.worldAlpha = this.worldAlpha; + + if (renderSession.gl) + { + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + } + else + { + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + } + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_generateCachedSprite + * @private + */ + _generateCachedSprite: function () { + + this._cacheAsBitmap = false; + + var bounds = this.getLocalBounds(); + + // Round it off and force non-zero dimensions + bounds.width = Math.max(1, Math.ceil(bounds.width)); + bounds.height = Math.max(1, Math.ceil(bounds.height)); + + this.updateTransform(); + + if (!this._cachedSprite) + { + var textureUnit = 0; + if (this.texture && this.texture.baseTexture && PIXI._enableMultiTextureToggle) + { + textureUnit = this.texture.baseTexture.textureIndex; + } + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width, bounds.height, undefined, undefined, undefined, undefined, textureUnit); + this._cachedSprite = new PIXI.Sprite(renderTexture); + this._cachedSprite.worldTransform = this.worldTransform; + } + else + { + this._cachedSprite.texture.resize(bounds.width, bounds.height); + } + + // Remove filters + var tempFilters = this._filters; + + this._filters = null; + this._cachedSprite.filters = tempFilters; + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true); + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + this._filters = tempFilters; + + this._cacheAsBitmap = true; + + }, + + /** + * Destroys a cached Sprite. + * + * @method PIXI.DisplayObject#_destroyCachedSprite + * @private + */ + _destroyCachedSprite: function () { + + if (!this._cachedSprite) + { + return; + } + + this._cachedSprite.texture.destroy(true); + + this._cachedSprite = null; + + } + +}; + +// Alias for updateTransform. As used in DisplayObject container, etc. +PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform; + +Object.defineProperties(PIXI.DisplayObject.prototype, { + + /** + * The horizontal position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#x + * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent. + */ + 'x': { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + } + + }, + + /** + * The vertical position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#y + * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent. + */ + 'y': { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + + }, + + /** + * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + * @name PIXI.DisplayObject#worldVisible + * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + */ + 'worldVisible': { + + get: function () { + + if (!this.visible) + { + return false; + } + else + { + var item = this.parent; + + if (!item) + { + return this.visible; + } + else + { + do + { + if (!item.visible) + { + return false; + } + + item = item.parent; + } + while (item); + + } + + return true; + } + + } + + }, + + /** + * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object. + * When applied it limits the visible area of this DisplayObject to the shape of the mask. + * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer. + * To remove a mask, set this property to `null`. + * + * @name PIXI.DisplayObject#mask + * @property {Phaser.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask. + */ + 'mask': { + + get: function () { + + return this._mask; + + }, + + set: function (value) { + + if (this._mask) + { + this._mask.isMask = false; + } + + this._mask = value; + + if (value) + { + this._mask.isMask = true; + } + + } + + }, + + /** + * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas + * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter + * using `DisplayObject.filterArea`. + * + * To remove filters, set this property to `null`. + * + * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a + * filter will reset this DisplayObjects blend mode to NORMAL. + * + * @name PIXI.DisplayObject#filters + * @property {Array} filters - An Array of Phaser.Filter objects, or objects that extend them. + */ + 'filters': { + + get: function () { + + return this._filters; + + }, + + set: function (value) { + + if (Array.isArray(value)) + { + // Put all the passes in one place. + var passes = []; + + for (var i = 0; i < value.length; i++) + { + var filterPasses = value[i].passes; + + for (var j = 0; j < filterPasses.length; j++) + { + passes.push(filterPasses[j]); + } + } + + // Needed any more? + this._filterBlock = { target: this, filterPasses: passes }; + } + + this._filters = value; + + if (this.blendMode && this.blendMode === PIXI.blendModes.MULTIPLY) + { + this.blendMode = PIXI.blendModes.NORMAL; + } + + } + + }, + + /** + * Sets if this DisplayObject should be cached as a bitmap. + * + * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it + * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a + * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not + * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`. + * + * To remove a cached bitmap, set this property to `null`. + * + * @name PIXI.DisplayObject#cacheAsBitmap + * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap. + */ + 'cacheAsBitmap': { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + if (this._cacheAsBitmap === value) + { + return; + } + + if (value) + { + this._generateCachedSprite(); + } + else + { + this._destroyCachedSprite(); + } + + this._cacheAsBitmap = value; + + } + + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A DisplayObjectContainer represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + * @class PIXI.DisplayObjectContainer + * @extends PIXI.DisplayObject + * @constructor + */ +PIXI.DisplayObjectContainer = function () { + + PIXI.DisplayObject.call(this); + + /** + * [read-only] The array of children of this container. + * + * @property children + * @type Array(DisplayObject) + * @readOnly + */ + this.children = []; + + /** + * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events. + * + * If this property is `true` then the children will _not_ be considered as valid for Input events. + * + * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. + * @property {boolean} ignoreChildInput + * @default + */ + this.ignoreChildInput = false; + +}; + +PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); +PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; + +/** + * Adds a child to the container. + * + * @method PIXI.DisplayObjectContainer#addChild + * @param child {DisplayObject} The DisplayObject to add to the container + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChild = function (child) { + + return this.addChildAt(child, this.children.length); + +}; + +/** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @method PIXI.DisplayObjectContainer#addChildAt + * @param child {DisplayObject} The child to add + * @param index {Number} The index to place the child in + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) { + + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + return child; + } + else + { + throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); + } + +}; + +/** + * Swaps the position of 2 Display Objects within this container. + * + * @method PIXI.DisplayObjectContainer#swapChildren + * @param child {DisplayObject} + * @param child2 {DisplayObject} + */ +PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) { + + if (child === child2) + { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(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; + +}; + +/** + * Returns the index position of a child DisplayObject instance + * + * @method PIXI.DisplayObjectContainer#getChildIndex + * @param child {DisplayObject} The DisplayObject instance to identify + * @return {Number} The index position of the child display object to identify + */ +PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + +}; + +/** + * Changes the position of an existing child in the display object container + * + * @method PIXI.DisplayObjectContainer#setChildIndex + * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number + * @param index {Number} The resulting index number for the child display object + */ +PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + this.children.splice(currentIndex, 1); //remove from old position + this.children.splice(index, 0, child); //add at new position + +}; + +/** + * Returns the child at the specified index + * + * @method PIXI.DisplayObjectContainer#getChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child at the given index, if any. + */ +PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller'); + } + + return this.children[index]; + +}; + +/** + * Removes a child from the container. + * + * @method PIXI.DisplayObjectContainer#removeChild + * @param child {DisplayObject} The DisplayObject to remove + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChild = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + return; + } + + return this.removeChildAt(index); + +}; + +/** + * Removes a child from the specified index position. + * + * @method PIXI.DisplayObjectContainer#removeChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) { + + var child = this.getChildAt(index); + + if (child) + { + child.parent = undefined; + + this.children.splice(index, 1); + } + + return child; + +}; + +/** +* Removes all children from this container that are within the begin and end indexes. +* +* @method PIXI.DisplayObjectContainer#removeChildren +* @param beginIndex {Number} The beginning position. Default value is 0. +* @param endIndex {Number} The ending position. Default value is size of the container. +*/ +PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { + + if (beginIndex === undefined) { beginIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var range = endIndex - beginIndex; + + if (range > 0 && range <= endIndex) + { + var removed = this.children.splice(beginIndex, range); + + for (var i = 0; i < removed.length; i++) + { + var child = removed[i]; + child.parent = undefined; + } + + return removed; + } + else if (range === 0 && this.children.length === 0) + { + return []; + } + else + { + throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' ); + } + +}; + +/* + * Updates the transform on all children of this container for rendering + * + * @method PIXI.DisplayObjectContainer#updateTransform + * @private + */ +PIXI.DisplayObjectContainer.prototype.updateTransform = function () { + + if (!this.visible) + { + return; + } + + this.displayObjectUpdateTransform(); + + if (this._cacheAsBitmap) + { + return; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +// performance increase to avoid using call.. (10x faster) +PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform; + +/** + * Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getBounds + * @param {PIXI.DisplayObject|Phaser.Matrix} [targetCoordinateSpace] Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpace) { + + var isTargetCoordinateSpaceDisplayObject = (targetCoordinateSpace && targetCoordinateSpace instanceof PIXI.DisplayObject); + var isTargetCoordinateSpaceThisOrParent = true; + + if (!isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace = this; + } + else if (targetCoordinateSpace instanceof PIXI.DisplayObjectContainer) + { + isTargetCoordinateSpaceThisOrParent = targetCoordinateSpace.contains(this); + } + else + { + isTargetCoordinateSpaceThisOrParent = false; + } + + var i; + + if (isTargetCoordinateSpaceDisplayObject) + { + var matrixCache = targetCoordinateSpace.worldTransform; + + targetCoordinateSpace.worldTransform = Phaser.identityMatrix; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + var minX = Infinity; + var minY = Infinity; + + var maxX = -Infinity; + var maxY = -Infinity; + + var childBounds; + var childMaxX; + var childMaxY; + + var childVisible = false; + + for (i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + childVisible = true; + + childBounds = this.children[i].getBounds(); + + minX = (minX < childBounds.x) ? minX : childBounds.x; + minY = (minY < childBounds.y) ? minY : childBounds.y; + + childMaxX = childBounds.width + childBounds.x; + childMaxY = childBounds.height + childBounds.y; + + maxX = (maxX > childMaxX) ? maxX : childMaxX; + maxY = (maxY > childMaxY) ? maxY : childMaxY; + } + + var bounds = this._bounds; + + if (!childVisible) + { + bounds = new PIXI.Rectangle(); + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + maxX = x1; + maxY = y1; + + minX = x1; + minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + } + + bounds.x = minX; + bounds.y = minY; + bounds.width = maxX - minX; + bounds.height = maxY - minY; + + if (isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace.worldTransform = matrixCache; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + if (!isTargetCoordinateSpaceThisOrParent) + { + var targetCoordinateSpaceBounds = targetCoordinateSpace.getBounds(); + + bounds.x -= targetCoordinateSpaceBounds.x; + bounds.y -= targetCoordinateSpaceBounds.y; + } + + return bounds; + +}; + +/** + * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getLocalBounds = function () { + + return this.getBounds(this); + +}; + +/** +* Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. +* +* @method PIXI.DisplayObjectContainer#contains +* @param {DisplayObject} child +* @returns {boolean} +*/ +PIXI.DisplayObjectContainer.prototype.contains = function (child) { + + if (!child) + { + return false; + } + else if (child === this) + { + return true; + } + else + { + return this.contains(child.parent); + } +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.DisplayObjectContainer#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + var i; + + if (this._mask || this._filters) + { + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + renderSession.spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + renderSession.spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + renderSession.spriteBatch.start(); + } + + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + renderSession.spriteBatch.start(); + } + else + { + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.DisplayObjectContainer#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) { + + if (this.visible === false || this.alpha === 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', { + + get: function() { + return this.getLocalBounds().width * this.scale.x; + }, + + set: function(value) { + + var width = this.getLocalBounds().width; + + if (width !== 0) + { + this.scale.x = value / width; + } + else + { + this.scale.x = 1; + } + + this._width = value; + } +}); + +/** + * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', { + + get: function() { + return this.getLocalBounds().height * this.scale.y; + }, + + set: function(value) { + + var height = this.getLocalBounds().height; + + if (height !== 0) + { + this.scale.y = value / height; + } + else + { + this.scale.y = 1; + } + + this._height = value; + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * @class PIXI.Sprite + * @extends PIXI.DisplayObjectContainer + * @constructor + * @param texture {Texture} The texture for this sprite + */ +PIXI.Sprite = function (texture) { + + PIXI.DisplayObjectContainer.call(this); + + /** + * The anchor sets the origin point of the texture. + * The default (0, 0) is the top left. + * (0.5, 0.5) is the center. + * (1, 1) is the bottom right. + * + * You can modify the default values in PIXI.Sprite.defaultAnchor. + * + * @property anchor + * @type Point + */ + this.anchor = new PIXI.Point(PIXI.Sprite.defaultAnchor.x, PIXI.Sprite.defaultAnchor.y); + + /** + * The texture that the sprite is using + * + * @property texture + * @type Texture + */ + this.texture = texture || PIXI.Texture.emptyTexture; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @property _width + * @type Number + * @private + */ + this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @property _height + * @type Number + * @private + */ + this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF (Phaser.Color.WHITE) will remove any tint effect. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @property cachedTint + * @private + * @type Number + * @default -1 + */ + this.cachedTint = -1; + + /** + * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) + * + * @property tintedTexture + * @type Canvas + * @default null + */ + this.tintedTexture = null; + + /** + * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. + * + * Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * The shader that will be used to render this Sprite. + * Set to null to remove a current shader. + * + * @property shader + * @type Phaser.Filter + * @default null + */ + this.shader = null; + + /** + * Controls if this Sprite is processed by the core Phaser game loops and Group loops (except {@link Phaser.Group#update}). + * + * @property exists + * @type Boolean + * @default true + */ + this.exists = true; + + if (this.texture.baseTexture.hasLoaded) + { + this.onTextureUpdate(); + } + + this.renderable = true; + +}; + +/** + * @property PIXI.Sprite.defaultAnchor - A Point-like object. + * @type {{x: number, y: number}} + * @default + */ +PIXI.Sprite.defaultAnchor = {x: 0, y: 0}; + +// constructor +PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +PIXI.Sprite.prototype.constructor = PIXI.Sprite; + +/** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'width', { + + get: function() { + return this.scale.x * this.texture.frame.width; + }, + + set: function(value) { + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'height', { + + get: function() { + return this.scale.y * this.texture.frame.height; + }, + + set: function(value) { + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +/** + * Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous + * texture this Sprite was using. + * + * @method PIXI.Sprite#setTexture + * @param texture {Texture} The PIXI texture that is displayed by the sprite + * @param [destroy=false] {boolean} Call Texture.destroy on the current texture before replacing it with the new one? + */ +PIXI.Sprite.prototype.setTexture = function(texture, destroyBase) +{ + if (destroyBase) + { + this.texture.baseTexture.destroy(); + } + + // Over-ridden by loadTexture as needed + this.texture.baseTexture.skipRender = false; + this.texture = texture; + this.texture.valid = true; + this.cachedTint = -1; +}; + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @method PIXI.Sprite#onTextureUpdate + * @param event + * @private + */ +PIXI.Sprite.prototype.onTextureUpdate = function() +{ + // so if _width is 0 then width was not set.. + if (this._width) this.scale.x = this._width / this.texture.frame.width; + if (this._height) this.scale.y = this._height / this.texture.frame.height; +}; + +/** +* Returns the bounds of the Sprite as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* It is important to note that the transform is not updated when you call this method. +* So if this Sprite is the child of a Display Object which has had its transform +* updated since the last render pass, those changes will not yet have been applied +* to this Sprites worldTransform. If you need to ensure that all parent transforms +* are factored into this getBounds operation then you should call `updateTransform` +* on the root most object in this Sprites display list first. +* +* @method PIXI.Sprite#getBounds +* @param matrix {Matrix} the transformation matrix of the sprite +* @return {Rectangle} the framing rectangle +*/ +PIXI.Sprite.prototype.getBounds = function(matrix) +{ + var width = this.texture.frame.width; + var height = this.texture.frame.height; + + var w0 = width * (1-this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1-this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + if (b === 0 && c === 0) + { + // scale may be negative! + if (a < 0) + { + a *= -1; + var temp = w0; + w0 = -w1; + w1 = -temp; + } + + if (d < 0) + { + d *= -1; + var temp = h0; + h0 = -h1; + h1 = -temp; + } + + // this means there is no rotation going on right? RIGHT? + // if thats the case then we can avoid checking the bound values! yay + minX = a * w1 + tx; + maxX = a * w0 + tx; + minY = d * h1 + ty; + maxY = d * h0 + ty; + } + else + { + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; +}; + +/** + * Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. + * + * @method PIXI.Sprite#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.Sprite.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.Sprite#_renderWebGL +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix) +{ + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha <= 0 || !this.renderable) return; + + // They provided an alternative rendering matrix, so use it + var wt = this.worldTransform; + + if (matrix) + { + wt = matrix; + } + + // A quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) + { + var spriteBatch = renderSession.spriteBatch; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + spriteBatch.start(); + } + + // add this sprite to the batch + spriteBatch.render(this); + + // now loop through the children and make sure they get rendered + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + // time to stop the sprite batch as either a mask element or a filter draw will happen next + spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + spriteBatch.start(); + } + else + { + renderSession.spriteBatch.render(this); + + // Render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession, wt); + } + + } +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.Sprite#_renderCanvas +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix) +{ + // If the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha === 0 || !this.renderable || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { + return; + } + + var wt = this.worldTransform; + + // If they provided an alternative rendering matrix then use it + if (matrix) + { + wt = matrix; + } + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + // Ignore null sources + if (!this.texture.valid) + { + // Update the children and leave + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + return; + } + + var resolution = this.texture.baseTexture.resolution / renderSession.resolution; + + renderSession.context.globalAlpha = this.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for this texture + if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode) + { + renderSession.scaleMode = this.texture.baseTexture.scaleMode; + renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + + // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions + var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width; + var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height; + + var tx = (wt.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (wt.ty * renderSession.resolution) + renderSession.shakeY; + + var cw = this.texture.crop.width; + var ch = this.texture.crop.height; + + if (this.texture.rotated) + { + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var e = cw; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + wt.a = a * 6.123233995736766e-17 + -c; + wt.b = b * 6.123233995736766e-17 + -d; + wt.c = a + c * 6.123233995736766e-17; + wt.d = b + d * 6.123233995736766e-17; + + // Update cropping dimensions. + cw = ch; + ch = e; + } + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx | 0, ty | 0); + dx |= 0; + dy |= 0; + } + else + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + } + + dx /= resolution; + dy /= resolution; + + if (this.tint !== 0xFFFFFF) + { + if (this.texture.requiresReTint || this.cachedTint !== this.tint) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + } + + renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + else + { + var cx = this.texture.crop.x; + var cy = this.texture.crop.y; + + cw = Math.floor(cw) + ch = Math.floor(ch) + + renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @method PIXI.initDefaultShaders +* @static +* @private +*/ +PIXI.initDefaultShaders = function() +{ +}; + +/** +* @method PIXI.CompileVertexShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileVertexShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); +}; + +/** +* @method PIXI.CompileFragmentShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileFragmentShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); +}; + +/** +* @method PIXI._CompileShader +* @static +* @private +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @param shaderType {Number} +* @return {Any} +*/ +PIXI._CompileShader = function(gl, shaderSrc, shaderType) +{ + var src = shaderSrc; + + if (Array.isArray(shaderSrc)) + { + 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; +}; + +/** +* @method PIXI.compileProgram +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param vertexSrc {Array} +* @param fragmentSrc {Array} +* @return {Any} +*/ +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(gl.getProgramInfoLog(shaderProgram)); + window.console.log("Could not initialise shaders"); + } + + return shaderProgram; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + * @author Richard Davey http://www.photonstorm.com @photonstorm + */ + +/** +* @class PIXI.PixiShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PixiShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = null; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + /** + * A local flag + * @property firstRun + * @type Boolean + * @private + */ + this.firstRun = true; + + /** + * A dirty flag + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Uniform attributes cache. + * @property attributes + * @type Array + * @private + */ + this.attributes = []; + + this.init(); +}; + +PIXI.PixiShader.prototype.constructor = PIXI.PixiShader; + +PIXI.PixiShader.prototype.initMultitexShader = function () { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.fragmentSrc = [ + '// PixiShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}', + '}' + ]; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + //this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.uSamplerArray = gl.getUniformLocation(program, 'uSamplerArray[0]'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSamplerArray, indices); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; + +PIXI.PixiShader.prototype.initDefaultShader = function () { + + if (this.fragmentSrc === null) { + this.fragmentSrc = [ + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', + '}' + ]; + } + + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; +/** +* Initialises the shader. +* +* @method PIXI.PixiShader#init +*/ +PIXI.PixiShader.prototype.init = function(usingFilter) +{ + if (PIXI._enableMultiTextureToggle && !usingFilter) { + this.initMultitexShader(); + } else { + this.initDefaultShader(); + } +}; + +/** +* Initialises the shader uniform values. +* +* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ +* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf +* +* @method PIXI.PixiShader#initUniforms +*/ +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') + { + // These require special handling + 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 + { + // GL function reference + 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; + } + } + } + +}; + +/** +* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) +* +* @method PIXI.PixiShader#initSampler2D +*/ +PIXI.PixiShader.prototype.initSampler2D = function(uniform) +{ + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { + return; + } + + var gl = this.gl; + + // No need to do string manipulation for this. + gl.activeTexture(gl.TEXTURE0 + this.textureCount); + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + + // Extended texture data + if (uniform.textureData) + { + var data = uniform.textureData; + + // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); + // GLTextureLinear = mag/min linear, wrap clamp + // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat + // GLTextureNearest = mag/min nearest, wrap clamp + // AudioTexture = whatever + luminance + width 512, height 2, border 0 + // KeyTexture = whatever + luminance + width 256, height 2, border 0 + + // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + + 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; + + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels); + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); + } + else + { + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels); + 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++; + +}; + +/** +* Updates the shader uniform values. +* +* @method PIXI.PixiShader#syncUniforms +*/ +PIXI.PixiShader.prototype.syncUniforms = function() +{ + this.textureCount = 1; + var uniform; + var gl = this.gl; + + // This would probably be faster in an array and it would guarantee key order + 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]); + + if(uniform.value.baseTexture._dirty[gl.id]) + { + PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + } + + // 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); + } + } + } + +}; + +/** +* Destroys the shader. +* +* @method PIXI.PixiShader#destroy +*/ +PIXI.PixiShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** +* The Default Vertex shader source. +* +* @property defaultVertexSrc +* @type String +*/ +PIXI.PixiShader.defaultVertexSrc = [ + '// PixiShader Vertex Shader', + '// With multi-texture rendering', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute vec4 aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + + 'const vec2 center = vec2(-1.0, 1.0);', + + 'void main(void) {', + ' if (aTextureIndex > 0.0) gl_Position = vec4(0.0);', + ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', + ' vTextureCoord = aTextureCoord;', + ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', + ' vTextureIndex = aTextureIndex;', + '}' +]; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @class PIXI.PixiFastShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.PixiFastShader = function (gl) { + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '// PixiFastShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aPositionCoord;', + 'attribute vec2 aScale;', + 'attribute float aRotation;', + 'attribute vec2 aTextureCoord;', + 'attribute float aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform mat3 uMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + + '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;', + ' vTextureIndex = aTextureIndex;', + // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;', + ' vColor = aColor;', + '}' + ]; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + this.init(); +}; + +PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader; + +/** + * Initialises the shader. + * + * @method PIXI.PixiFastShader#init + */ +PIXI.PixiFastShader.prototype.init = function () { + + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + this.uMatrix = gl.getUniformLocation(program, 'uMatrix'); + + // get and store the attributes + 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'); + + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its somthing to do with the current state of the gl context. + // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if (this.colorAttribute === -1) { + this.colorAttribute = 2; + } + + this.attributes = [ + this.aVertexPosition, + this.aPositionCoord, + this.aScale, + this.aRotation, + this.aTextureCoord, + this.colorAttribute, + this.aTextureIndex + ]; + + // End worst hack eva // + + this.program = program; +}; + +/** + * Destroys the shader. + * + * @method PIXI.PixiFastShader#destroy + */ +PIXI.PixiFastShader.prototype.destroy = function () { + this.gl.deleteProgram(this.program); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.StripShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.StripShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord);return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) ;return;}\n' + } + + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord);', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '//StripShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute float aTextureIndex;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + // 'uniform float alpha;', + // 'uniform vec3 tint;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // '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);', + ' vTextureCoord = aTextureCoord;', + ' vTextureIndex = aTextureIndex;', + // ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.StripShader.prototype.constructor = PIXI.StripShader; + +/** +* Initialises the shader. +* +* @method PIXI.StripShader#init +*/ +PIXI.StripShader.prototype.init = function() +{ + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + //this.dimensions = gl.getUniformLocation(this.program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.aTextureIndex]; + + this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix'); + this.alpha = gl.getUniformLocation(program, 'alpha'); + + this.program = program; +}; + +/** +* Destroys the shader. +* +* @method PIXI.StripShader#destroy +*/ +PIXI.StripShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.PrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + 'precision mediump float;', + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform float alpha;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.PrimitiveShader#init +*/ +PIXI.PrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.PrimitiveShader#destroy +*/ +PIXI.PrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.ComplexPrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.ComplexPrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + + 'precision mediump float;', + + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + //'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 color;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.ComplexPrimitiveShader#init +*/ +PIXI.ComplexPrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.color = gl.getUniformLocation(program, 'color'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.ComplexPrimitiveShader#destroy +*/ +PIXI.ComplexPrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +PIXI.glContexts = []; // this is where we store the webGL contexts for easy access. +PIXI.instances = []; +PIXI._enableMultiTextureToggle = false; + +/** + * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class PIXI.WebGLRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.WebGLRenderer = function(game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + this.extensions = {}; + + /** + * @property type + * @type Number + */ + this.type = Phaser.WEBGL; + + /** + * The resolution of the renderer + * + * @property resolution + * @type Number + * @default 1 + */ + this.resolution = game.resolution; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * + * @property preserveDrawingBuffer + * @type Boolean + */ + this.preserveDrawingBuffer = game.preserveDrawingBuffer; + + /** + * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true: + * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0). + * If the Stage is transparent, Pixi will clear to the target Stage's background color. + * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * The width of the canvas view + * + * @property width + * @type Number + */ + this.width = game.width; + + /** + * The height of the canvas view + * + * @property height + * @type Number + */ + this.height = game.height; + + /** + * The canvas element that everything is drawn to + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * @property _contextOptions + * @type Object + * @private + */ + this._contextOptions = { + alpha: this.transparent, + antialias: game.antialias, + failIfMajorPerformanceCaveat: config.failIfMajorPerformanceCaveat, + premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: this.preserveDrawingBuffer + }; + + /** + * @property projection + * @type Point + */ + this.projection = new PIXI.Point(); + + /** + * @property offset + * @type Point + */ + this.offset = new PIXI.Point(); + + // time to create the render managers! each one focuses on managing a state in webGL + + /** + * Deals with managing the shader programs and their attribs + * @property shaderManager + * @type WebGLShaderManager + */ + this.shaderManager = new PIXI.WebGLShaderManager(); + + /** + * Manages the rendering of sprites + * @property spriteBatch + * @type WebGLSpriteBatch + */ + this.spriteBatch = new PIXI.WebGLSpriteBatch(game); + + /** + * Manages the masks using the stencil buffer + * @property maskManager + * @type WebGLMaskManager + */ + this.maskManager = new PIXI.WebGLMaskManager(); + + /** + * Manages the filters + * @property filterManager + * @type WebGLFilterManager + */ + this.filterManager = new PIXI.WebGLFilterManager(); + + /** + * Manages the stencil buffer + * @property stencilManager + * @type WebGLStencilManager + */ + this.stencilManager = new PIXI.WebGLStencilManager(); + + /** + * Manages the blendModes + * @property blendModeManager + * @type WebGLBlendModeManager + */ + this.blendModeManager = new PIXI.WebGLBlendModeManager(); + + /** + * @property renderSession + * @type Object + */ + this.renderSession = {}; + + /** + * @property currentBatchedTextures + * @type Array + */ + this.currentBatchedTextures = []; + + // Needed? + this.renderSession.game = this.game; + this.renderSession.gl = this.gl; + this.renderSession.drawCount = 0; + this.renderSession.shaderManager = this.shaderManager; + this.renderSession.maskManager = this.maskManager; + this.renderSession.filterManager = this.filterManager; + this.renderSession.blendModeManager = this.blendModeManager; + this.renderSession.spriteBatch = this.spriteBatch; + this.renderSession.stencilManager = this.stencilManager; + this.renderSession.renderer = this; + this.renderSession.resolution = this.resolution; + this.renderSession.roundPixels = config.roundPixels || false; + this.renderSession.maxTextureAvailableSpace = null; // filled in setTexturePriority() + + // time init the context.. + this.initContext(); + + // map some webGL blend modes.. + this.mapBlendModes(); + +}; + +// constructor +PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer; + +/** +* @method PIXI.WebGLRenderer#initContext +*/ +PIXI.WebGLRenderer.prototype.initContext = function() +{ + var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); + + this.gl = gl; + + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + this.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.maxTextureSize = this.gl.getParameter(gl.MAX_TEXTURE_SIZE); + + this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++; + + PIXI.glContexts[this.glContextId] = gl; + + PIXI.instances[this.glContextId] = this; + + // set up the default pixi settings.. + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + gl.enable(gl.BLEND); + + // need to set the context for all the managers... + this.shaderManager.setContext(gl); + this.spriteBatch.setContext(gl); + this.maskManager.setContext(gl); + this.filterManager.setContext(gl); + this.blendModeManager.setContext(gl); + this.stencilManager.setContext(gl); + + this.renderSession.gl = this.gl; + + // now resize and we are good to go! + this.resize(this.width, this.height); + + // Load WebGL extension + this.extensions.compression = {}; + + var etc1 = gl.getExtension('WEBGL_compressed_texture_etc1') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'); + var pvrtc = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); + var s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); + + if (etc1) { this.extensions.compression.ETC1 = etc1; } + if (pvrtc) { this.extensions.compression.PVRTC = pvrtc; } + if (s3tc) { this.extensions.compression.S3TC = s3tc; } +}; + +/** +* If Multi Texture support has been enabled, then calling this method will enable batching on the given +* textures. The texture collection is an array of keys, that map to Phaser.Cache image entries. +* +* The number of textures that can be batched is dependent on hardware. If you provide more textures +* than can be batched by the GPU, then only those at the start of the array will be used. Generally +* you shouldn't provide more than 16 textures to this method. You can check the hardware limit via the +* `maxTextures` property. +* +* You can also check the property `currentBatchedTextures` at any time, to see which textures are currently +* being batched. +* +* To stop all textures from being batched, call this method again with an empty array. +* +* To change the textures being batched, call this method with a new array of image keys. The old ones +* will all be purged out and no-longer batched, and the new ones enabled. +* +* Note: Throws a warning if you haven't enabled Multiple Texture batching support in the Phaser Game config. +* +* @method PIXI.WebGLRenderer#setTexturePriority +* @param textureNameCollection {Array} An Array of Texture Cache keys to use for multi-texture batching. +* @return {Array} An array containing the texture keys that were enabled for batching. +*/ +PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + if (!PIXI._enableMultiTextureToggle) + { + console.warn('setTexturePriority error: Multi Texture support hasn\'t been enabled in the Phaser Game Config.'); + return; + } + var clampPot = function (potSize) { + --potSize; + potSize |= potSize >> 1; + potSize |= potSize >> 2; + potSize |= potSize >> 4; + potSize |= potSize >> 8; + potSize |= potSize >> 16; + return ++potSize; + }; + var gl = this.gl; + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + var imageCache = this.game.cache._cache.image; + var imageName = null; + + // Clear out all previously batched textures and reset their flags. + // If the array has been modified, then the developer will have to + // deal with that in their own way. + for (var i = 0; i < this.currentBatchedTextures.length; i++) + { + imageName = this.currentBatchedTextures[i]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + + imageCache[imageName].base.textureIndex = 0; + } + var maxTextureAvailableSpace = (maxTextureSize) - clampPot(Math.max(this.width, this.height)); + this.currentBatchedTextures.length = 0; + // We start from 1 because framebuffer texture uses unit 0. + for (var j = 0; j < textureNameCollection.length; ++j) + { + imageName = textureNameCollection[j]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + // Unit 0 is reserved for Pixi's framebuffer + var base = imageCache[imageName].base; + maxTextureAvailableSpace -= clampPot(Math.max(base.width, base.height)); + if (maxTextureAvailableSpace <= 0) { + base.textureIndex = 0; + console.warn('setTexturePriority: Image "%s" was given textureIndex=0 because there is no available texture space (%s).', + imageName, maxTextureAvailableSpace); + } else { + base.textureIndex = (1 + (j % (maxTextures - 1))); + } + this.currentBatchedTextures.push(imageName); + } + + this.renderSession.maxTextureAvailableSpace = maxTextureAvailableSpace; + + return this.currentBatchedTextures; + +}; + +/** + * Renders the stage to its webGL view + * + * @method PIXI.WebGLRenderer#render + * @param stage {Stage} the Stage element to be rendered + */ +PIXI.WebGLRenderer.prototype.render = function(stage) +{ + // no point rendering if our context has been blown up! + if (this.contextLost) + { + return; + } + + var gl = this.gl; + + // -- Does this need to be set every frame? -- // + gl.viewport(0, 0, this.width, this.height); + + // make sure we are bound to the main frame buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + if (this.game.clearBeforeRender) + { + gl.clearColor(stage._bgColor.r, stage._bgColor.g, stage._bgColor.b, stage._bgColor.a); + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + this.offset.x = this.game.camera._shake.x; + this.offset.y = this.game.camera._shake.y; + + this.renderDisplayObject(stage, this.projection); +}; + +/** + * Renders a Display Object. + * + * @method PIXI.WebGLRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The DisplayObject to render + * @param projection {Point} The projection + * @param buffer {Array} a standard WebGL buffer + */ +PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix) +{ + this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL); + + // reset the render session data.. + this.renderSession.drawCount = 0; + + // make sure to flip the Y if using a render texture.. + this.renderSession.flipY = buffer ? -1 : 1; + + // set the default projection + this.renderSession.projection = projection; + + //set the default offset + this.renderSession.offset = this.offset; + + // start the sprite batch + this.spriteBatch.begin(this.renderSession); + + // start the filter manager + this.filterManager.begin(this.renderSession, buffer); + + // render the scene! + displayObject._renderWebGL(this.renderSession, matrix); + + // finish the sprite batch + this.spriteBatch.end(); +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @method PIXI.WebGLRenderer#resize + * @param width {Number} the new width of the webGL view + * @param height {Number} the new height of the webGL view + */ +PIXI.WebGLRenderer.prototype.resize = function(width, height) +{ + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } + + this.gl.viewport(0, 0, this.width, this.height); + + this.projection.x = this.width / 2 / this.resolution; + this.projection.y = -this.height / 2 / this.resolution; +}; + +/** + * Updates and creates a WebGL compressed texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateCompressedTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateCompressedTexture = function (texture) { + if (!texture.hasLoaded) + { + return false; + } + var gl = this.gl; + var textureMetaData = texture.source; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + textureMetaData.glExtensionFormat, + textureMetaData.width, + textureMetaData.height, + 0, + textureMetaData.textureData + ); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + texture._dirty[gl.id] = false; + return true; +}; + +/** + * Updates and Creates a WebGL texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateTexture = function(texture) +{ + if (!texture.hasLoaded) + { + return false; + } + if (texture.source.compressionAlgorithm) { + return this.updateCompressedTexture(texture); + } + + var gl = this.gl; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha); + + 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); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + + texture._dirty[gl.id] = false; + + // return texture._glTextures[gl.id]; + return true; + +}; + +/** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @method PIXI.WebGLRenderer#destroy + */ +PIXI.WebGLRenderer.prototype.destroy = function() +{ + 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; + + Phaser.CanvasPool.remove(this); + + PIXI.instances[this.glContextId] = null; + + PIXI.WebGLRenderer.glContextId--; +}; + +/** + * Maps Pixi blend modes to WebGL blend modes. + * + * @method PIXI.WebGLRenderer#mapBlendModes + */ +PIXI.WebGLRenderer.prototype.mapBlendModes = function() +{ + var gl = this.gl; + + if (!PIXI.blendModesWebGL) + { + var b = []; + var modes = PIXI.blendModes; + + b[modes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA]; + b[modes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SCREEN] = [gl.SRC_ALPHA, gl.ONE]; + b[modes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + PIXI.blendModesWebGL = b; + } +}; + +PIXI.WebGLRenderer.prototype.getMaxTextureUnit = function() { + var gl = this.gl; + return gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); +}; + +PIXI.enableMultiTexture = function() { + PIXI._enableMultiTextureToggle = true; +}; + +PIXI.WebGLRenderer.glContextId = 0; +PIXI.WebGLRenderer.textureArray = []; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLBlendModeManager +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLBlendModeManager = function() +{ + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 99999; +}; + +PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLBlendModeManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLBlendModeManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Sets-up the given blendMode from WebGL's point of view. +* +* @method PIXI.WebGLBlendModeManager#setBlendMode +* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD +*/ +PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode) +{ + if(this.currentBlendMode === blendMode)return false; + + this.currentBlendMode = blendMode; + + var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode]; + + if (blendModeWebGL) + { + this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLBlendModeManager#destroy +*/ +PIXI.WebGLBlendModeManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLMaskManager +* @constructor +* @private +*/ +PIXI.WebGLMaskManager = function() +{ +}; + +PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLMaskManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLMaskManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLMaskManager#pushMask +* @param maskData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession) +{ + var gl = renderSession.gl; + + if (maskData.dirty) + { + PIXI.WebGLGraphics.updateGraphics(maskData, gl); + } + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLMaskManager#popMask +* @param maskData {Array} +* @param renderSession {Object} an object containing all the useful parameters +*/ +PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession) +{ + var gl = this.gl; + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); + +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLMaskManager#destroy +*/ +PIXI.WebGLMaskManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLStencilManager +* @constructor +* @private +*/ +PIXI.WebGLStencilManager = function() +{ + this.stencilStack = []; + this.reverse = true; + this.count = 0; +}; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLStencilManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLStencilManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLStencilManager#pushMask +* @param graphics {Graphics} +* @param webGLData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.bindGraphics(graphics, webGLData, renderSession); + + if(this.stencilStack.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + this.reverse = true; + this.count = 0; + } + + this.stencilStack.push(webGLData); + + var level = this.count; + + gl.colorMask(false, false, false, false); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + + if(webGLData.mode === 1) + { + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + + this.reverse = !this.reverse; + } + else + { + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + this.count++; +}; + +/** + * TODO this does not belong here! + * + * @method PIXI.WebGLStencilManager#bindGraphics + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession) +{ + //if(this._currentGraphics === graphics)return; + this._currentGraphics = graphics; + + var gl = this.gl; + + // bind the graphics object.. + var projection = renderSession.projection, + offset = renderSession.offset, + shader;// = renderSession.shaderManager.primitiveShader; + + if(webGLData.mode === 1) + { + shader = renderSession.shaderManager.complexPrimitiveShader; + + renderSession.shaderManager.setShader( shader ); + + gl.uniform1f(shader.flipY, renderSession.flipY); + + 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, Phaser.Color.hexToRGBArray(graphics.tint)); + gl.uniform3fv(shader.color, webGLData.color); + + gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0); + + + // now do the rest.. + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } + else + { + //renderSession.shaderManager.activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + renderSession.shaderManager.setShader( shader ); + + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, renderSession.flipY); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } +}; + +/** + * @method PIXI.WebGLStencilManager#popStencil + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.stencilStack.pop(); + + this.count--; + + if(this.stencilStack.length === 0) + { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + + } + else + { + + var level = this.count; + + this.bindGraphics(graphics, webGLData, renderSession); + + gl.colorMask(false, false, false, false); + + if(webGLData.mode === 1) + { + this.reverse = !this.reverse; + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + + } + else + { + // console.log("<<>>") + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + + } +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLStencilManager#destroy +*/ +PIXI.WebGLStencilManager.prototype.destroy = function() +{ + this.stencilStack = null; + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLShaderManager +* @constructor +* @private +*/ +PIXI.WebGLShaderManager = function() +{ + /** + * @property maxAttibs + * @type Number + */ + this.maxAttibs = 10; + + /** + * @property attribState + * @type Array + */ + this.attribState = []; + + /** + * @property tempAttribState + * @type Array + */ + this.tempAttribState = []; + + for (var i = 0; i < this.maxAttibs; i++) + { + this.attribState[i] = false; + } + + /** + * @property stack + * @type Array + */ + this.stack = []; + +}; + +PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLShaderManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLShaderManager.prototype.setContext = function(gl) +{ + this.gl = gl; + + // the next one is used for rendering primitives + this.primitiveShader = new PIXI.PrimitiveShader(gl); + + // the next one is used for rendering triangle strips + this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl); + + // this shader is used for the default sprite rendering + this.defaultShader = new PIXI.PixiShader(gl); + + // this shader is used for the fast sprite rendering + this.fastShader = new PIXI.PixiFastShader(gl); + + // the next one is used for rendering triangle strips + this.stripShader = new PIXI.StripShader(gl); + + // the next one is used for rendering creature meshes + this.creatureShader = PIXI.CreatureShader ? new PIXI.CreatureShader(gl) : null; + + this.setShader(this.defaultShader); +}; + +/** +* Takes the attributes given in parameters. +* +* @method PIXI.WebGLShaderManager#setAttribs +* @param attribs {Array} attribs +*/ +PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs) +{ + // reset temp state + var i; + + for (i = 0; i < this.tempAttribState.length; i++) + { + this.tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + var attribId = attribs[i]; + this.tempAttribState[attribId] = true; + } + + var gl = this.gl; + + for (i = 0; i < this.attribState.length; i++) + { + if(this.attribState[i] !== this.tempAttribState[i]) + { + this.attribState[i] = this.tempAttribState[i]; + + if(this.tempAttribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } +}; + +/** +* Sets the current shader. +* +* @method PIXI.WebGLShaderManager#setShader +* @param shader {Any} +*/ +PIXI.WebGLShaderManager.prototype.setShader = function(shader) +{ + if(this._currentId === shader._UID)return false; + + this._currentId = shader._UID; + + this.currentShader = shader; + + this.gl.useProgram(shader.program); + this.setAttribs(shader.attributes); + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLShaderManager#destroy +*/ +PIXI.WebGLShaderManager.prototype.destroy = function() +{ + this.attribState = null; + + this.tempAttribState = null; + + this.primitiveShader.destroy(); + + this.complexPrimitiveShader.destroy(); + + this.defaultShader.destroy(); + + this.fastShader.destroy(); + + this.stripShader.destroy(); + + if (this.creatureShader) { + this.creatureShader.destroy(); + } + + this.gl = null; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** + * + * @class PIXI.WebGLSpriteBatch + * @private + * @constructor + */ +PIXI.WebGLSpriteBatch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 5; + + /** + * The number of images in the SpriteBatch before it flushes + * @property size + * @type Number + */ + this.size = 2000; //Math.pow(2, 16) / this.vertSize; + + //the total number of bytes in our batch + // Including texture index: + // position + uv + color + textureIndex + // vec2 + vec2 + (char * 4) + float + this.vertexSize = (4 * 2) + (4 * 2) + (4) + (4); + var numVerts = this.vertexSize * this.size * 4; + //this.size * 4 * 4 * this.vertSize; + //the total number of indices in our batch + var numIndices = this.size * 6; + + /** + * Holds the vertices + * + * @property vertices + * @type ArrayBuffer + */ + this.vertices = new ArrayBuffer(numVerts); + + /** + * View on the vertices as a Float32Array + * + * @property positions + * @type Float32Array + */ + this.positions = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array + * + * @property colors + * @type Uint32Array + */ + this.colors = new Uint32Array(this.vertices); + + /** + * Holds the indices + * + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * @property textures + * @type Array + */ + this.textures = []; + + /** + * @property blendModes + * @type Array + */ + this.blendModes = []; + + /** + * @property shaders + * @type Array + */ + this.shaders = []; + + /** + * @property sprites + * @type Array + */ + this.sprites = []; + + /** + * @property defaultShader + * @type Phaser.Filter + */ + this.defaultShader = null; +}; + +/** + * @method PIXI.WebGLSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLSpriteBatch.prototype.setContext = function (gl) { + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.gl = gl; + if (PIXI._enableMultiTextureToggle) { + var dynamicIfs = '\tif (vTextureIndex == 0.0) {gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + 'void main(void) {', + dynamicIfs, + '\tgl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;', + '}' + ]); + } + else + { + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]); + } + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + this.currentBlendMode = 99999; + + var shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = this.defaultShader.fragmentSrc; + shader.uniforms = {}; + shader.init(); + + this.defaultShader.shaders[gl.id] = shader; +}; + +/** + * @method PIXI.WebGLSpriteBatch#begin + * @param renderSession {Object} The RenderSession object + */ +PIXI.WebGLSpriteBatch.prototype.begin = function (renderSession) { + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.defaultShader; + + this.start(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#end + */ +PIXI.WebGLSpriteBatch.prototype.end = function () { + this.flush(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#render + * @param sprite {Sprite} the sprite to render when using this spritebatch + * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. + */ +PIXI.WebGLSpriteBatch.prototype.render = function (sprite, matrix) { + var texture = sprite.texture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + if (PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + baseTexture.textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] = baseTexture; + } + + // They provided an alternative rendering matrix, so use it + var wt = sprite.worldTransform; + + if (matrix) { + wt = matrix; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // get the uvs for the texture + var uvs = texture._uvs; + + // if the uvs have not updated then no point rendering just yet! + if (!uvs) { + return; + } + + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + + var w0, w1, h0, h1; + + if (texture.trim) { + // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords. + var trim = texture.trim; + + w1 = trim.x - aX * trim.width; + w0 = w1 + texture.crop.width; + + h1 = trim.y - aY * trim.height; + h0 = h1 + texture.crop.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 i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + var tiOffset = this.currentBatchSize * 4; + var resolution = texture.baseTexture.resolution; + var textureIndex = texture.baseTexture.textureIndex; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + + var cw = texture.crop.width; + var ch = texture.crop.height; + + if (texture.rotated) + { + var a0 = wt.a; + var b0 = wt.b; + var c0 = wt.c; + var d0 = wt.d; + var _w1 = w1; + var _w0 = w0; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + a = a0 * 6.123233995736766e-17 + -c0; + b = b0 * 6.123233995736766e-17 + -d0; + c = a0 + c0 * 6.123233995736766e-17; + d = b0 + d0 * 6.123233995736766e-17; + + // Update UV coordinates + texture._updateUvsInverted(); + + // Rotate dimensions + w0 = h0; + w1 = h1; + h0 = _w0; + h1 = _w1; + } + + var colors = this.colors; + var positions = this.positions; + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + if (this.renderSession.roundPixels) { + positions[i++] = a * w1 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w1 + ty | 0; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w0 + ty | 0; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w0 + ty | 0; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w1 + ty | 0; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } else { + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx; + positions[i++] = d * h1 + b * w0 + ty; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders a TilingSprite using the spriteBatch. + * + * @method PIXI.WebGLSpriteBatch#renderTilingSprite + * @param sprite {TilingSprite} the sprite to render + */ +PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function (sprite) { + var texture = sprite.tilingTexture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + var textureIndex = sprite.texture.baseTexture.textureIndex; + if (PIXI.WebGLRenderer.textureArray[textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[textureIndex] = baseTexture; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // set the textures uvs temporarily + if (!sprite._uvs) { + sprite._uvs = new PIXI.TextureUvs(); + } + + var uvs = sprite._uvs; + + var w = texture.baseTexture.width; + var h = texture.baseTexture.height; + + // var w = sprite._frame.sourceSizeW; + // var h = sprite._frame.sourceSizeH; + + // w = 16; + // h = 16; + + sprite.tilePosition.x %= w * sprite.tileScaleOffset.x; + sprite.tilePosition.y %= h * sprite.tileScaleOffset.y; + + var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x); + var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y); + + var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x); + var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.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; + + // Get the sprites current alpha and tint and combine them into a single color + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + var positions = this.positions; + var colors = this.colors; + + var width = sprite.width; + var height = sprite.height; + + // TODO trim?? + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + var w0 = width * (1 - aX); + var w1 = width * -aX; + + var h0 = height * (1 - aY); + var h1 = height * -aY; + + var i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + + var resolution = texture.baseTexture.resolution; + + var wt = sprite.worldTransform; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + // xy + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + // uv + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = (a * w0 + c * h1 + tx); + positions[i++] = d * h1 + b * w0 + ty; + // uv + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + // uv + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + // uv + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders the content and empties the current batch. + * + * @method PIXI.WebGLSpriteBatch#flush + */ +PIXI.WebGLSpriteBatch.prototype.flush = function () { + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize === 0) { + return; + } + + var gl = this.gl; + var shader; + + if (this.dirty) { + this.dirty = false; + + shader = this.defaultShader.shaders[gl.id]; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + // this is the same for each shader? + var stride = this.vertexSize; //this.vertSize * 4; + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 8); + + // color attributes will be interpreted as unsigned bytes and normalized + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 16); + + // Texture index + gl.vertexAttribPointer(shader.aTextureIndex, 1, gl.FLOAT, false, stride, 20); + } + + // upload the verts to the buffer + if (this.currentBatchSize > (this.size * 0.5)) { + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + } else { + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + var view = this.positions.subarray(0, this.currentBatchSize * this.vertexSize); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); + } + + var nextTexture, nextBlendMode, nextShader; + var batchSize = 0; + var start = 0; + + var currentBaseTexture = null; + var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode; + var currentShader = null; + + var blendSwap = false; + var shaderSwap = false; + var sprite; + var textureIndex = 0; + + for (var i = 0, j = this.currentBatchSize; i < j; i++) { + + sprite = this.sprites[i]; + + if (sprite.tilingTexture) { + nextTexture = sprite.tilingTexture.baseTexture; + } else { + nextTexture = sprite.texture.baseTexture; + } + + nextBlendMode = sprite.blendMode; + nextShader = sprite.shader || this.defaultShader; + + blendSwap = currentBlendMode !== nextBlendMode; + shaderSwap = currentShader !== nextShader; // should I use _UIDS??? + + var skip = nextTexture.skipRender; + + if (skip && sprite.children.length > 0) { + skip = false; + } + // + if (/*(currentBaseTexture != nextTexture && !skip) ||*/ + blendSwap || + shaderSwap) { + this.renderBatch(currentBaseTexture, batchSize, start); + + start = i; + batchSize = 0; + currentBaseTexture = nextTexture; + + if (blendSwap) { + currentBlendMode = nextBlendMode; + this.renderSession.blendModeManager.setBlendMode(currentBlendMode); + } + + if (shaderSwap) { + currentShader = nextShader; + + shader = currentShader.shaders[gl.id]; + + if (!shader) { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = currentShader.fragmentSrc; + shader.uniforms = currentShader.uniforms; + shader.init(); + + currentShader.shaders[gl.id] = shader; + } + + // set shader function??? + this.renderSession.shaderManager.setShader(shader); + + if (shader.dirty) { + shader.syncUniforms(); + } + + // both these only need to be set if they are changing.. + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(shader.projectionVector, projection.x, projection.y); + + // TODO - this is temporary! + var offsetVector = this.renderSession.offset; + gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y); + + // set the pointers + } + } + + batchSize++; + } + + this.renderBatch(currentBaseTexture, batchSize, start); + + // then reset the batch! + this.currentBatchSize = 0; +}; + +/** + * @method PIXI.WebGLSpriteBatch#renderBatch + * @param texture {Texture} + * @param size {Number} + * @param startIndex {Number} + */ +PIXI.WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { + if (size === 0) { + return; + } + + var gl = this.gl; + + // check if a texture is dirty.. + if (texture._dirty[gl.id]) { + if (!this.renderSession.renderer.updateTexture(texture)) { + // If updateTexture returns false then we cannot render it, so bail out now + return; + } + }else { + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + } + + gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2); + // increment the draw count + this.renderSession.drawCount++; +}; + +/** + * @method PIXI.WebGLSpriteBatch#stop + */ +PIXI.WebGLSpriteBatch.prototype.stop = function () { + this.flush(); + this.dirty = true; +}; + +/** + * @method PIXI.WebGLSpriteBatch#start + */ +PIXI.WebGLSpriteBatch.prototype.start = function () { + this.dirty = true; +}; + +/** + * Destroys the SpriteBatch. + * + * @method PIXI.WebGLSpriteBatch#destroy + */ +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; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** +* @class PIXI.WebGLFastSpriteBatch +* @constructor +*/ +PIXI.WebGLFastSpriteBatch = function(gl) +{ + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 11; + + /** + * @property maxSize + * @type Number + */ + this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize; + + /** + * @property size + * @type Number + */ + this.size = this.maxSize; + + //the total number of floats in our batch + var numVerts = this.size * 4 * this.vertSize; + + //the total number of indices in our batch + var numIndices = this.maxSize * 6; + + /** + * Vertex data + * @property vertices + * @type Float32Array + */ + this.vertices = new Float32Array(numVerts); + + /** + * Index data + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property vertexBuffer + * @type Object + */ + this.vertexBuffer = null; + + /** + * @property indexBuffer + * @type Object + */ + this.indexBuffer = null; + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i=0, j=0; i < numIndices; i += 6, j += 4) + { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 0; + + /** + * @property renderSession + * @type Object + */ + this.renderSession = null; + + /** + * @property shader + * @type Object + */ + this.shader = null; + + /** + * @property matrix + * @type Matrix + */ + this.matrix = null; + + this.setContext(gl); +}; + +PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLFastSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl) +{ + this.gl = gl; + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#begin + * @param spriteBatch {WebGLSpriteBatch} + * @param renderSession {Object} + */ +PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession) +{ + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.fastShader; + + this.matrix = spriteBatch.worldTransform.toArray(true); + + this.start(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#end + */ +PIXI.WebGLFastSpriteBatch.prototype.end = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#render + * @param spriteBatch {WebGLSpriteBatch} + */ +PIXI.WebGLFastSpriteBatch.prototype.render = function (spriteBatch) +{ + var children = spriteBatch.children; + var sprite = children[0]; + + // if the uvs have not updated then no point rendering just yet! + + // check texture. + if(!sprite.texture._uvs)return; + + this.currentBaseTexture = sprite.texture.baseTexture; + + // check blend mode + if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode) + { + this.flush(); + this.renderSession.blendModeManager.setBlendMode(sprite.blendMode); + } + + for(var i=0,j= children.length; i= this.size) + { + this.flush(); + } +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#flush + */ +PIXI.WebGLFastSpriteBatch.prototype.flush = function() +{ + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize===0)return; + + var gl = this.gl; + + // bind the current texture + + if(!this.currentBaseTexture._glTextures[gl.id]) { + this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl); + return; + } + + //gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); + + // upload the verts to the buffer + + if(this.currentBatchSize > ( this.size * 0.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); + } + + // now draw those suckas! + gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0); + + // then reset the batch! + this.currentBatchSize = 0; + + // increment the draw count + this.renderSession.drawCount++; + +}; + + +/** + * @method PIXI.WebGLFastSpriteBatch#stop + */ +PIXI.WebGLFastSpriteBatch.prototype.stop = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#start + */ +PIXI.WebGLFastSpriteBatch.prototype.start = function() +{ + var gl = this.gl; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(this.shader.projectionVector, projection.x, projection.y); + + // set the matrix + gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix); + + // set the pointers + 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); + gl.vertexAttribPointer(this.shader.aTextureIndex, 1, gl.FLOAT, false, stride, 10 * 4); + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLFilterManager +* @constructor +*/ +PIXI.WebGLFilterManager = function() +{ + /** + * @property filterStack + * @type Array + */ + this.filterStack = []; + + /** + * @property offsetX + * @type Number + */ + this.offsetX = 0; + + /** + * @property offsetY + * @type Number + */ + this.offsetY = 0; +}; + +PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLFilterManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLFilterManager.prototype.setContext = function(gl) +{ + this.gl = gl; + this.texturePool = []; + + this.initShaderBuffers(); +}; + +/** +* @method PIXI.WebGLFilterManager#begin +* @param renderSession {RenderSession} +* @param buffer {ArrayBuffer} +*/ +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; +}; + +/** +* Applies the filter and adds it to the current filter stack. +* +* @method PIXI.WebGLFilterManager#pushFilter +* @param filterBlock {Object} the filter that will be pushed to the current filter stack +*/ +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(); + + // >>> modify by nextht + filterBlock._previous_stencil_mgr = this.renderSession.stencilManager; + this.renderSession.stencilManager = new PIXI.WebGLStencilManager(); + this.renderSession.stencilManager.setContext(gl); + gl.disable(gl.STENCIL_TEST); + // <<< modify by nextht + + // filter program + // OPTIMISATION - the first filter is free if its a simple color change? + 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.renderSession.resolution, this.height * this.renderSession.resolution); + } + else + { + texture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + } + + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea; + + var padding = filter.padding; + filterArea.x -= padding; + filterArea.y -= padding; + filterArea.width += padding * 2; + filterArea.height += padding * 2; + + // cap filter to screen size.. + 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer); + + // set view port + gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + projection.x = filterArea.width/2; + projection.y = -filterArea.height/2; + + offset.x = -filterArea.x; + offset.y = -filterArea.y; + + // update projection + // now restore the regular shader.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + //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; + +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLFilterManager#popFilter +*/ +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 * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + 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); + // now set the uvs.. + 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.renderSession.resolution, this.height * this.renderSession.resolution); + outputTexture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + + // need to clear this FBO as it may have some left over elements from a previous filter. + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + gl.clear(gl.COLOR_BUFFER_BIT); + + gl.disable(gl.BLEND); + + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { + var filterPass = filterBlock.filterPasses[i]; + + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture); + + // draw texture.. + //filterPass.applyFilterPass(filterArea.width, filterArea.height); + this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height); + + // swap the textures.. + var temp = inputTexture; + inputTexture = outputTexture; + outputTexture = temp; + } + + gl.enable(gl.BLEND); + + texture = inputTexture; + this.texturePool.push(outputTexture); + } + + var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1]; + + this.offsetX -= filterArea.x; + this.offsetY -= filterArea.y; + + var sizeX = this.width; + var sizeY = this.height; + + var offsetX = 0; + var offsetY = 0; + + var buffer = this.buffer; + + // time to render the filters texture to the previous scene + if(this.filterStack.length === 0) + { + gl.colorMask(true, true, true, true);//this.transparent); + } + else + { + var currentFilter = this.filterStack[this.filterStack.length-1]; + filterArea = currentFilter._filterArea; + + sizeX = filterArea.width; + sizeY = filterArea.height; + + offsetX = filterArea.x; + offsetY = filterArea.y; + + buffer = currentFilter._glFilterTexture.frameBuffer; + } + + // TODO need to remove these global elements.. + projection.x = sizeX/2; + projection.y = -sizeY/2; + + offset.x = offsetX; + offset.y = offsetY; + + filterArea = filterBlock._filterArea; + + var x = filterArea.x-offsetX; + var y = filterArea.y-offsetY; + + // update the buffers.. + // make sure to flip the y! + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + + this.vertexArray[0] = x; + this.vertexArray[1] = y + filterArea.height; + + this.vertexArray[2] = x + filterArea.width; + this.vertexArray[3] = y + filterArea.height; + + this.vertexArray[4] = x; + this.vertexArray[5] = y; + + this.vertexArray[6] = x + filterArea.width; + this.vertexArray[7] = y; + + 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); + + gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution); + + // bind the buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, buffer ); + + // set the blend mode! + //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + // >>> modify by nextht + if (this.renderSession.stencilManager) { + this.renderSession.stencilManager.destroy(); + } + this.renderSession.stencilManager = filterBlock._previous_stencil_mgr; + filterBlock._previous_stencil_mgr = null; + if (this.renderSession.stencilManager.count > 0) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + // <<< modify by nextht + + // apply! + this.applyFilterPass(filter, filterArea, sizeX, sizeY); + + // now restore the regular shader.. should happen automatically now.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2); + // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY); + + // return the texture to the pool + this.texturePool.push(texture); + filterBlock._glFilterTexture = null; +}; + + +/** +* Applies the filter to the specified area. +* +* @method PIXI.WebGLFilterManager#applyFilterPass +* @param filter {Phaser.Filter} the filter that needs to be applied +* @param filterArea {Texture} TODO - might need an update +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +*/ +PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height) +{ + // use program + var gl = this.gl; + var shader = filter.shaders[gl.id]; + + if(!shader) + { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = filter.fragmentSrc; + shader.uniforms = filter.uniforms; + shader.init(true); + + filter.shaders[gl.id] = shader; + } + + // set the shader + this.renderSession.shaderManager.setShader(shader); + +// gl.useProgram(shader.program); + + gl.uniform2f(shader.projectionVector, width/2, -height/2); + gl.uniform2f(shader.offsetVector, 0,0); + + if(filter.uniforms.dimensions) + { + filter.uniforms.dimensions.value[0] = this.width;//width; + filter.uniforms.dimensions.value[1] = this.height;//height; + filter.uniforms.dimensions.value[2] = this.vertexArray[0]; + filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height; + } + + shader.syncUniforms(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // draw the filter... + gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + + this.renderSession.drawCount++; +}; + +/** +* Initialises the shader buffers. +* +* @method PIXI.WebGLFilterManager#initShaderBuffers +*/ +PIXI.WebGLFilterManager.prototype.initShaderBuffers = function() +{ + var gl = this.gl; + + // create some buffers + this.vertexBuffer = gl.createBuffer(); + this.uvBuffer = gl.createBuffer(); + this.colorBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // bind and upload the vertexs.. + // keep a reference to the vertexFloatData.. + this.vertexArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW); + + // bind and upload the uv buffer + this.uvArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW); + + this.colorArray = new Float32Array([1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW); + + // bind and upload the index + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW); + +}; + +/** +* Destroys the filter and removes it from the filter stack. +* +* @method PIXI.WebGLFilterManager#destroy +*/ +PIXI.WebGLFilterManager.prototype.destroy = function() +{ + var gl = this.gl; + + this.filterStack = null; + + this.offsetX = 0; + this.offsetY = 0; + + // destroy textures + for (var i = 0; i < this.texturePool.length; i++) { + this.texturePool[i].destroy(); + } + + this.texturePool = null; + + //destroy buffers.. + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.uvBuffer); + gl.deleteBuffer(this.colorBuffer); + gl.deleteBuffer(this.indexBuffer); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @private + */ +function _CreateEmptyTexture(gl, width, height, scaleMode) { + var texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + return texture; +} + +/** + * @private + */ +var _fbErrors = { + 36054: 'Incomplete attachment', + 36055: 'Missing attachment', + 36057: 'Incomplete dimensions', + 36061: 'Framebuffer unsupported' +}; + +/** + * @private + */ +function _CreateFramebuffer(gl, width, height, scaleMode, textureUnit) { + var framebuffer = gl.createFramebuffer(); + var depthStencilBuffer = gl.createRenderbuffer(); + var colorBuffer = null; + var fbStatus = 0; + + gl.activeTexture(gl.TEXTURE0 + textureUnit); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer); + colorBuffer = _CreateEmptyTexture(gl, width, height, scaleMode); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorBuffer, 0); + fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + if(fbStatus !== gl.FRAMEBUFFER_COMPLETE) { + console.error('Incomplete GL framebuffer. ', _fbErrors[fbStatus]); + } + framebuffer.width = width; + framebuffer.height = height; + framebuffer.targetTexture = colorBuffer; + framebuffer.renderBuffer = depthStencilBuffer; + return framebuffer; +} + +/** +* @class PIXI.FilterTexture +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +* @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values +*/ +PIXI.FilterTexture = function(gl, width, height, scaleMode, textureUnit) +{ + textureUnit = typeof textureUnit === 'number' ? textureUnit : 0; + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + // next time to create a frame buffer and texture + + /** + * @property frameBuffer + * @type Any + */ + this.frameBuffer = _CreateFramebuffer(gl, width, height, scaleMode || PIXI.scaleModes.DEFAULT, textureUnit); + /** + * @property texture + * @type Any + */ + this.texture = this.frameBuffer.targetTexture; + this.width = width; + this.height = height; + this.renderBuffer = this.frameBuffer.renderBuffer; +}; + +PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture; + +/** +* Clears the filter texture. +* +* @method PIXI.FilterTexture#clear +*/ +PIXI.FilterTexture.prototype.clear = function() +{ + var gl = this.gl; + + gl.clearColor(0,0,0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Resizes the texture to the specified width and height + * + * @method PIXI.FilterTexture#resize + * @param width {Number} the new width of the texture + * @param height {Number} the new height of the texture + */ +PIXI.FilterTexture.prototype.resize = function(width, height) +{ + if(this.width === width && this.height === height) return; + + this.width = width; + this.height = height; + + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height ); +}; + +/** +* Destroys the filter texture. +* +* @method PIXI.FilterTexture#destroy +*/ +PIXI.FilterTexture.prototype.destroy = function() +{ + var gl = this.gl; + gl.deleteFramebuffer( this.frameBuffer ); + gl.deleteTexture( this.texture ); + + this.frameBuffer = null; + this.texture = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Creates a Canvas element of the given size. + * + * @class PIXI.CanvasBuffer + * @constructor + * @param width {Number} the width for the newly created canvas + * @param height {Number} the height for the newly created canvas + */ +PIXI.CanvasBuffer = function(width, height) +{ + /** + * The width of the Canvas in pixels. + * + * @property width + * @type Number + */ + this.width = width; + + /** + * The height of the Canvas in pixels. + * + * @property height + * @type Number + */ + this.height = height; + + /** + * The Canvas object that belongs to this CanvasBuffer. + * + * @property canvas + * @type HTMLCanvasElement + */ + this.canvas = Phaser.CanvasPool.create(this, this.width, this.height); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.canvas.getContext("2d"); + + this.canvas.width = width; + this.canvas.height = height; +}; + +PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer; + +/** + * Clears the canvas that was created by the CanvasBuffer class. + * + * @method PIXI.CanvasBuffer#clear + * @private + */ +PIXI.CanvasBuffer.prototype.clear = function() +{ + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0,0, this.width, this.height); +}; + +/** + * Resizes the canvas to the specified width and height. + * + * @method PIXI.CanvasBuffer#resize + * @param width {Number} the new width of the canvas + * @param height {Number} the new height of the canvas + */ +PIXI.CanvasBuffer.prototype.resize = function(width, height) +{ + this.width = this.canvas.width = width; + this.height = this.canvas.height = height; +}; + +/** + * Frees the canvas up for use again. + * + * @method PIXI.CanvasBuffer#destroy + */ +PIXI.CanvasBuffer.prototype.destroy = function() +{ + Phaser.CanvasPool.remove(this); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used to handle masking. + * + * @class PIXI.CanvasMaskManager + * @constructor + */ +PIXI.CanvasMaskManager = function() +{ +}; + +PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; + +/** + * This method adds it to the current stack of masks. + * + * @method PIXI.CanvasMaskManager#pushMask + * @param maskData {Object} the maskData that will be pushed + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) { + + var context = renderSession.context; + + context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.worldTransform; + + var resolution = renderSession.resolution; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution); + + PIXI.CanvasGraphics.renderGraphicsMask(maskData, context); + + context.clip(); + + maskData.worldAlpha = cacheAlpha; +}; + +/** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @method PIXI.CanvasMaskManager#popMask + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.popMask = function(renderSession) +{ + renderSession.context.restore(); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class PIXI.CanvasTinter + * @static + */ +PIXI.CanvasTinter = function() {}; + +/** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @method PIXI.CanvasTinter#getTintedTexture + * @static + * @param sprite {Sprite} the sprite to tint + * @param color {Number} the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ +PIXI.CanvasTinter.getTintedTexture = function(sprite, color) +{ + var canvas = sprite.tintedTexture || Phaser.CanvasPool.create(this); + + PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas); + + return canvas; +}; + +/** + * Tint a texture using the "multiply" operation. + * + * @method PIXI.CanvasTinter#tintWithMultiply + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.clearRect(0, 0, w, h); + + context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, w, h); + + context.globalCompositeOperation = "multiply"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + context.globalCompositeOperation = "destination-atop"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + +}; + +/** + * Tint a texture pixel per pixel. + * + * @method PIXI.CanvasTinter#tintPerPixel + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.globalCompositeOperation = "copy"; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + var rgbValues = Phaser.Color.hexToRGBArray(color); + var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, w, h); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) + { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + + if (!PIXI.CanvasTinter.canHandleAlpha) + { + var alpha = pixels[i + 3]; + + pixels[i + 0] /= 255 / alpha; + pixels[i + 1] /= 255 / alpha; + pixels[i + 2] /= 255 / alpha; + } + } + + context.putImageData(pixelData, 0, 0); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class PIXI.CanvasRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.CanvasRenderer = function (game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + /** + * The renderer type. + * + * @property type + * @type Number + */ + this.type = Phaser.CANVAS; + + /** + * The resolution of the canvas. + * + * @property resolution + * @type Number + */ + this.resolution = game.resolution; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. + * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame. + * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The width of the canvas view + * + * @property width + * @type Number + * @default 800 + */ + this.width = game.width * this.resolution; + + /** + * The height of the canvas view + * + * @property height + * @type Number + * @default 600 + */ + this.height = game.height * this.resolution; + + /** + * The canvas element that everything is drawn to. + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * The canvas 2d context that everything is drawn with + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.view.getContext("2d", { alpha: this.transparent } ); + + /** + * Boolean flag controlling canvas refresh. + * + * @property refresh + * @type Boolean + */ + this.refresh = true; + + /** + * Internal var. + * + * @property count + * @type Number + */ + this.count = 0; + + /** + * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer + * @property CanvasMaskManager + * @type CanvasMaskManager + */ + this.maskManager = new PIXI.CanvasMaskManager(); + + /** + * The render session is just a bunch of parameter used for rendering + * @property renderSession + * @type Object + */ + this.renderSession = { + context: this.context, + maskManager: this.maskManager, + scaleMode: null, + smoothProperty: Phaser.Canvas.getSmoothingPrefix(this.context), + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + */ + roundPixels: config.roundPixels || false + }; + + this.mapBlendModes(); + + this.resize(this.width, this.height); + +}; + +// constructor +PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer; + +/** + * Renders the DisplayObjectContainer, usually the Phaser.Stage, to this canvas view. + * + * @method PIXI.CanvasRenderer#render + * @param root {Phaser.Stage|PIXI.DisplayObjectContainer} The root element to be rendered. + */ +PIXI.CanvasRenderer.prototype.render = function (root) { + + this.context.setTransform(1, 0, 0, 1, 0, 0); + + this.context.globalAlpha = 1; + + this.renderSession.currentBlendMode = 0; + this.renderSession.shakeX = this.game.camera._shake.x; + this.renderSession.shakeY = this.game.camera._shake.y; + + this.context.globalCompositeOperation = 'source-over'; + + if (navigator.isCocoonJS && this.view.screencanvas) + { + this.context.fillStyle = "black"; + this.context.clear(); + } + + if (this.clearBeforeRender) + { + if (this.transparent) + { + this.context.clearRect(0, 0, this.width, this.height); + } + else if (root._bgColor) + { + this.context.fillStyle = root._bgColor.rgba; + this.context.fillRect(0, 0, this.width , this.height); + } + } + + this.renderDisplayObject(root); + +}; + +PIXI.CanvasRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + // Does nothing on Canvas, but here to allow you to simply set + // `game.renderer.setTexturePriority()` without having to worry about + // running in WebGL or not. + +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @method PIXI.CanvasRenderer#destroy + * @param [removeView=true] {boolean} Removes the Canvas element from the DOM. + */ +PIXI.CanvasRenderer.prototype.destroy = function (removeView) { + + if (removeView === undefined) { removeView = true; } + + if (removeView && this.view.parent) + { + this.view.parent.removeChild(this.view); + } + + this.view = null; + this.context = null; + this.maskManager = null; + this.renderSession = null; + +}; + +/** + * Resizes the canvas view to the specified width and height + * + * @method PIXI.CanvasRenderer#resize + * @param width {Number} the new width of the canvas view + * @param height {Number} the new height of the canvas view + */ +PIXI.CanvasRenderer.prototype.resize = function (width, height) { + + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) + { + this.view.style.width = this.width / this.resolution + "px"; + this.view.style.height = this.height / this.resolution + "px"; + } + + if (this.renderSession.smoothProperty) + { + this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + +}; + +/** + * Renders a display object + * + * @method PIXI.CanvasRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The displayObject to render + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. + * @private + */ +PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) { + + this.renderSession.context = context || this.context; + this.renderSession.resolution = this.resolution; + displayObject._renderCanvas(this.renderSession, matrix); + +}; + +/** + * Maps Pixi blend modes to canvas blend modes. + * + * @method PIXI.CanvasRenderer#mapBlendModes + * @private + */ +PIXI.CanvasRenderer.prototype.mapBlendModes = function () { + + if (!PIXI.blendModesCanvas) + { + var b = []; + var modes = PIXI.blendModes; + var useNew = this.game.device.canUseMultiply; + + b[modes.NORMAL] = 'source-over'; + b[modes.ADD] = 'lighter'; + b[modes.MULTIPLY] = (useNew) ? 'multiply' : 'source-over'; + b[modes.SCREEN] = (useNew) ? 'screen' : 'source-over'; + b[modes.OVERLAY] = (useNew) ? 'overlay' : 'source-over'; + b[modes.DARKEN] = (useNew) ? 'darken' : 'source-over'; + b[modes.LIGHTEN] = (useNew) ? 'lighten' : 'source-over'; + b[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : 'source-over'; + b[modes.COLOR_BURN] = (useNew) ? 'color-burn' : 'source-over'; + b[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : 'source-over'; + b[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : 'source-over'; + b[modes.DIFFERENCE] = (useNew) ? 'difference' : 'source-over'; + b[modes.EXCLUSION] = (useNew) ? 'exclusion' : 'source-over'; + b[modes.HUE] = (useNew) ? 'hue' : 'source-over'; + b[modes.SATURATION] = (useNew) ? 'saturation' : 'source-over'; + b[modes.COLOR] = (useNew) ? 'color' : 'source-over'; + b[modes.LUMINOSITY] = (useNew) ? 'luminosity' : 'source-over'; + + PIXI.blendModesCanvas = b; + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class PIXI.BaseTexture + * @constructor + * @param source {String|Canvas} the source object (image or canvas) + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + */ +PIXI.BaseTexture = function(source, scaleMode, resolution) +{ + /** + * The Resolution of the texture. + * + * @property resolution + * @type Number + */ + this.resolution = resolution || 1; + + /** + * [read-only] The width of the base texture set when the image has loaded + * + * @property width + * @type Number + * @readOnly + */ + this.width = 100; + + /** + * [read-only] The height of the base texture set when the image has loaded + * + * @property height + * @type Number + * @readOnly + */ + this.height = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @property scaleMode + * @type {Number} + * @default PIXI.scaleModes.LINEAR + */ + this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT; + + /** + * [read-only] Set to true once the base texture has loaded + * + * @property hasLoaded + * @type Boolean + * @readOnly + */ + this.hasLoaded = false; + + /** + * The image source that is used to create the texture. + * + * @property source + * @type Image + */ + this.source = source; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * + * @property premultipliedAlpha + * @type Boolean + * @default true + */ + this.premultipliedAlpha = true; + + // used for webGL + + /** + * @property _glTextures + * @type Array + * @private + */ + this._glTextures = []; + + /** + * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @property mipmap + * @type {Boolean} + */ + this.mipmap = false; + + /** + * The multi texture batching index number. + * @property textureIndex + * @type Number + */ + this.textureIndex = 0; + + /** + * @property _dirty + * @type Array + * @private + */ + this._dirty = [true, true, true, true]; + + if (!source) + { + return; + } + + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { + this.hasLoaded = true; + this.width = this.source.naturalWidth || this.source.width; + this.height = this.source.naturalHeight || this.source.height; + this.dirty(); + } + + /** + * A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch. + * + * You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture) + * that has children that you do want to render, without causing a batch flush in the process. + * + * @property skipRender + * @type Boolean + */ + this.skipRender = false; + + /** + * @property _powerOf2 + * @type Boolean + * @private + */ + this._powerOf2 = false; + +}; + +PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture; + +/** + * Forces this BaseTexture to be set as loaded, with the given width and height. + * Then calls BaseTexture.dirty. + * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have. + * + * @method PIXI.BaseTexture#forceLoaded + * @param {number} width - The new width to force the BaseTexture to be. + * @param {number} height - The new height to force the BaseTexture to be. + */ +PIXI.BaseTexture.prototype.forceLoaded = function(width, height) +{ + this.hasLoaded = true; + this.width = width; + this.height = height; + this.dirty(); +}; + +/** + * Destroys this base texture + * + * @method PIXI.BaseTexture#destroy + */ +PIXI.BaseTexture.prototype.destroy = function() +{ + if (this.source) + { + Phaser.CanvasPool.removeByCanvas(this.source); + } + + this.source = null; + + this.unloadFromGPU(); +}; + +/** + * Sets all glTextures to be dirty. + * + * @method PIXI.BaseTexture#dirty + */ +PIXI.BaseTexture.prototype.dirty = function() +{ + for (var i = 0; i < this._glTextures.length; i++) + { + this._dirty[i] = true; + } +}; + +/** + * Removes the base texture from the GPU, useful for managing resources on the GPU. + * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it. + * + * @method PIXI.BaseTexture#unloadFromGPU + */ +PIXI.BaseTexture.prototype.unloadFromGPU = function() +{ + this.dirty(); + + // delete the webGL textures if any. + for (var i = this._glTextures.length - 1; i >= 0; i--) + { + var glTexture = this._glTextures[i]; + var gl = PIXI.glContexts[i]; + + if(gl && glTexture) + { + gl.deleteTexture(glTexture); + } + + } + + this._glTextures.length = 0; + + this.dirty(); +}; + +/** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @method PIXI.BaseTexture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + * @return {BaseTexture} + */ +PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode, resolution) +{ + if (canvas.width === 0) + { + canvas.width = 1; + } + + if (canvas.height === 0) + { + canvas.height = 1; + } + + resolution = resolution || 1; + + return new PIXI.BaseTexture(canvas, scaleMode, resolution); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * TextureSilentFail is a boolean that defaults to `false`. + * If `true` then {@link PIXI.Texture#setFrame} will no longer throw an error if the texture dimensions are incorrect. + * Instead {@link PIXI.Texture#valid} will be set to `false` (#1556) + * + * @type {boolean} + */ +PIXI.TextureSilentFail = false; + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used. + * + * @class PIXI.Texture + * @constructor + * @param baseTexture {BaseTexture} The base texture source to create the texture from + * @param frame {Rectangle} The rectangle frame of the texture to show + * @param [crop] {Rectangle} The area of original texture + * @param [trim] {Rectangle} Trimmed texture rectangle + */ +PIXI.Texture = function(baseTexture, frame, crop, trim) +{ + /** + * Does this Texture have any frame data assigned to it? + * + * @property noFrame + * @type Boolean + */ + this.noFrame = false; + + if (!frame) + { + this.noFrame = true; + frame = new PIXI.Rectangle(0,0,1,1); + } + + if (baseTexture instanceof PIXI.Texture) + { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = baseTexture; + + /** + * The frame specifies the region of the base texture that this texture uses + * + * @property frame + * @type Rectangle + */ + this.frame = frame; + + /** + * The texture trim data. + * + * @property trim + * @type Rectangle + */ + this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @property valid + * @type Boolean + */ + this.valid = false; + + /** + * Is this a tiling texture? As used by the likes of a TilingSprite. + * + * @property isTiling + * @type Boolean + */ + this.isTiling = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @property requiresUpdate + * @type Boolean + */ + this.requiresUpdate = false; + + /** + * This will let a renderer know that a tinted parent has updated its texture. + * + * @property requiresReTint + * @type Boolean + */ + this.requiresReTint = false; + + /** + * The WebGL UV data cache. + * + * @property _uvs + * @type Object + * @private + */ + this._uvs = null; + + /** + * The width of the Texture in pixels. + * + * @property width + * @type Number + */ + this.width = 0; + + /** + * The height of the Texture in pixels. + * + * @property height + * @type Number + */ + this.height = 0; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @property crop + * @type Rectangle + */ + this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1); + + /** + * A flag that controls if this frame is rotated or not. + * Rotation allows you to use rotated frames in texture atlas packing, it has nothing to do with + * Sprite rotation. + * + * @property rotated + * @type Boolean + */ + this.rotated = false; + + if (baseTexture.hasLoaded) + { + if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + this.setFrame(frame); + } + +}; + +PIXI.Texture.prototype.constructor = PIXI.Texture; + +/** + * Called when the base texture is loaded + * + * @method PIXI.Texture#onBaseTextureLoaded + * @private + */ +PIXI.Texture.prototype.onBaseTextureLoaded = function() +{ + var baseTexture = this.baseTexture; + + if (this.noFrame) + { + this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } + + this.setFrame(this.frame); +}; + +/** + * Destroys this texture + * + * @method PIXI.Texture#destroy + * @param destroyBase {Boolean} Whether to destroy the base texture as well + */ +PIXI.Texture.prototype.destroy = function(destroyBase) +{ + if (destroyBase) this.baseTexture.destroy(); + + this.valid = false; +}; + +/** + * Specifies the region of the baseTexture that this texture will use. + * + * @method PIXI.Texture#setFrame + * @param frame {Rectangle} The frame of the texture to set it to + */ +PIXI.Texture.prototype.setFrame = function(frame) +{ + this.noFrame = false; + + this.frame = frame; + this.width = frame.width; + this.height = frame.height; + + this.crop.x = frame.x; + this.crop.y = frame.y; + this.crop.width = frame.width; + this.crop.height = frame.height; + + if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { + if (!PIXI.TextureSilentFail) + { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + this.valid = false; + return; + } + + this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + + if (this.trim) + { + this.width = this.trim.width; + this.height = this.trim.height; + this.frame.width = this.trim.width; + this.frame.height = this.trim.height; + } + + if (this.valid) this._updateUvs(); + +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvs + * @private + */ +PIXI.Texture.prototype._updateUvs = function() +{ + if(!this._uvs)this._uvs = new PIXI.TextureUvs(); + + var frame = this.crop; + 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; +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvsInverted + * @private + */ +PIXI.Texture.prototype._updateUvsInverted = function () { + + if (!this._uvs) { this._uvs = new PIXI.TextureUvs(); } + + var frame = this.crop; + 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.height) / tw; + this._uvs.y1 = frame.y / th; + + this._uvs.x2 = (frame.x + frame.height) / tw; + this._uvs.y2 = (frame.y + frame.width) / th; + + this._uvs.x3 = frame.x / tw; + this._uvs.y3 = (frame.y + frame.width) / th; + +}; + +/** + * Helper function that creates a new a Texture based on the given canvas element. + * + * @static + * @method PIXI.Texture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @return {Texture} + */ +PIXI.Texture.fromCanvas = function(canvas, scaleMode) +{ + var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode); + + return new PIXI.Texture(baseTexture); +}; + +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.y3 = 0; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = PIXI; + } + exports.PIXI = PIXI; + } else if (typeof define !== 'undefined' && define.amd) { + define('PIXI', (function() { return root.PIXI = PIXI; })() ); + } else { + root.PIXI = PIXI; + } + + return PIXI; +}).call(this); +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +(function(){ + + var root = this; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @namespace Phaser +*/ +var Phaser = Phaser || { // jshint ignore:line + + /** + * The Phaser version number. + * @constant Phaser.VERSION + * @type {string} + */ + VERSION: '2.10.0', + + /** + * An array of Phaser game instances. + * @constant Phaser.GAMES + * @type {array} + */ + GAMES: [], + + /** + * AUTO renderer - picks between WebGL or Canvas based on device. + * @constant Phaser.AUTO + * @type {integer} + */ + AUTO: 0, + + /** + * Canvas Renderer. + * @constant Phaser.CANVAS + * @type {integer} + */ + CANVAS: 1, + + /** + * WebGL Renderer. + * @constant Phaser.WEBGL + * @type {integer} + */ + WEBGL: 2, + + /** + * Headless renderer (not visual output) + * @constant Phaser.HEADLESS + * @type {integer} + */ + HEADLESS: 3, + + /** + * WebGL Renderer with MultiTexture support enabled. + * @constant Phaser.WEBGL_MULTI + * @type {integer} + */ + WEBGL_MULTI: 4, + + /** + * Direction constant. + * @constant Phaser.NONE + * @type {integer} + */ + NONE: 0, + + /** + * Direction constant. + * @constant Phaser.LEFT + * @type {integer} + */ + LEFT: 1, + + /** + * Direction constant. + * @constant Phaser.RIGHT + * @type {integer} + */ + RIGHT: 2, + + /** + * Direction constant. + * @constant Phaser.UP + * @type {integer} + */ + UP: 3, + + /** + * Direction constant. + * @constant Phaser.DOWN + * @type {integer} + */ + DOWN: 4, + + /** + * Game Object type. + * @constant Phaser.SPRITE + * @type {integer} + */ + SPRITE: 0, + + /** + * Game Object type. + * @constant Phaser.BUTTON + * @type {integer} + */ + BUTTON: 1, + + /** + * Game Object type. + * @constant Phaser.IMAGE + * @type {integer} + */ + IMAGE: 2, + + /** + * Game Object type. + * @constant Phaser.GRAPHICS + * @type {integer} + */ + GRAPHICS: 3, + + /** + * Game Object type. + * @constant Phaser.TEXT + * @type {integer} + */ + TEXT: 4, + + /** + * Game Object type. + * @constant Phaser.TILESPRITE + * @type {integer} + */ + TILESPRITE: 5, + + /** + * Game Object type. + * @constant Phaser.BITMAPTEXT + * @type {integer} + */ + BITMAPTEXT: 6, + + /** + * Game Object type. + * @constant Phaser.GROUP + * @type {integer} + */ + GROUP: 7, + + /** + * Game Object type. + * @constant Phaser.RENDERTEXTURE + * @type {integer} + */ + RENDERTEXTURE: 8, + + /** + * Game Object type. + * @constant Phaser.TILEMAP + * @type {integer} + */ + TILEMAP: 9, + + /** + * Game Object type. + * @constant Phaser.TILEMAPLAYER + * @type {integer} + */ + TILEMAPLAYER: 10, + + /** + * Game Object type. + * @constant Phaser.EMITTER + * @type {integer} + */ + EMITTER: 11, + + /** + * Game Object type. + * @constant Phaser.POLYGON + * @type {integer} + */ + POLYGON: 12, + + /** + * Game Object type. + * @constant Phaser.BITMAPDATA + * @type {integer} + */ + BITMAPDATA: 13, + + /** + * Game Object type. + * @constant Phaser.CANVAS_FILTER + * @type {integer} + */ + CANVAS_FILTER: 14, + + /** + * Game Object type. + * @constant Phaser.WEBGL_FILTER + * @type {integer} + */ + WEBGL_FILTER: 15, + + /** + * Game Object type. + * @constant Phaser.ELLIPSE + * @type {integer} + */ + ELLIPSE: 16, + + /** + * Game Object type. + * @constant Phaser.SPRITEBATCH + * @type {integer} + */ + SPRITEBATCH: 17, + + /** + * Game Object type. + * @constant Phaser.RETROFONT + * @type {integer} + */ + RETROFONT: 18, + + /** + * Game Object type. + * @constant Phaser.POINTER + * @type {integer} + */ + POINTER: 19, + + /** + * Game Object type. + * @constant Phaser.ROPE + * @type {integer} + */ + ROPE: 20, + + /** + * Game Object type. + * @constant Phaser.CIRCLE + * @type {integer} + */ + CIRCLE: 21, + + /** + * Game Object type. + * @constant Phaser.RECTANGLE + * @type {integer} + */ + RECTANGLE: 22, + + /** + * Game Object type. + * @constant Phaser.LINE + * @type {integer} + */ + LINE: 23, + + /** + * Game Object type. + * @constant Phaser.MATRIX + * @type {integer} + */ + MATRIX: 24, + + /** + * Game Object type. + * @constant Phaser.POINT + * @type {integer} + */ + POINT: 25, + + /** + * Game Object type. + * @constant Phaser.ROUNDEDRECTANGLE + * @type {integer} + */ + ROUNDEDRECTANGLE: 26, + + /** + * Game Object type. + * @constant Phaser.CREATURE + * @type {integer} + */ + CREATURE: 27, + + /** + * Game Object type. + * @constant Phaser.VIDEO + * @type {integer} + */ + VIDEO: 28, + + /** + * Game Object type. + * @constant Phaser.PENDING_ATLAS + * @type {integer} + */ + PENDING_ATLAS: -1, + + /** + * A horizontal orientation + * @constant Phaser.HORIZONTAL + * @type {integer} + */ + HORIZONTAL: 0, + + /** + * A vertical orientation + * @constant Phaser.VERTICAL + * @type {integer} + */ + VERTICAL: 1, + + /** + * A landscape orientation + * @constant Phaser.LANDSCAPE + * @type {integer} + */ + LANDSCAPE: 0, + + /** + * A portrait orientation + * @constant Phaser.PORTRAIT + * @type {integer} + */ + PORTRAIT: 1, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face up. + * @constant Phaser.ANGLE_UP + * @type {integer} + */ + ANGLE_UP: 270, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face down. + * @constant Phaser.ANGLE_DOWN + * @type {integer} + */ + ANGLE_DOWN: 90, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face left. + * @constant Phaser.ANGLE_LEFT + * @type {integer} + */ + ANGLE_LEFT: 180, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face right. + * @constant Phaser.ANGLE_RIGHT + * @type {integer} + */ + ANGLE_RIGHT: 0, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north east. + * @constant Phaser.ANGLE_NORTH_EAST + * @type {integer} + */ + ANGLE_NORTH_EAST: 315, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north west. + * @constant Phaser.ANGLE_NORTH_WEST + * @type {integer} + */ + ANGLE_NORTH_WEST: 225, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south east. + * @constant Phaser.ANGLE_SOUTH_EAST + * @type {integer} + */ + ANGLE_SOUTH_EAST: 45, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south west. + * @constant Phaser.ANGLE_SOUTH_WEST + * @type {integer} + */ + ANGLE_SOUTH_WEST: 135, + + /** + * A constant representing a top-left alignment or position. + * @constant Phaser.TOP_LEFT + * @type {integer} + */ + TOP_LEFT: 0, + + /** + * A constant representing a top-center alignment or position. + * @constant Phaser.TOP_CENTER + * @type {integer} + */ + TOP_CENTER: 1, + + /** + * A constant representing a top-right alignment or position. + * @constant Phaser.TOP_RIGHT + * @type {integer} + */ + TOP_RIGHT: 2, + + /** + * A constant representing a left-top alignment or position. + * @constant Phaser.Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_TOP: 3, + + /** + * A constant representing a left-center alignment or position. + * @constant Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_CENTER: 4, + + /** + * A constant representing a left-bottom alignment or position. + * @constant Phaser.LEFT_BOTTOM + * @type {integer} + */ + LEFT_BOTTOM: 5, + + /** + * A constant representing a center alignment or position. + * @constant Phaser.CENTER + * @type {integer} + */ + CENTER: 6, + + /** + * A constant representing a right-top alignment or position. + * @constant Phaser.RIGHT_TOP + * @type {integer} + */ + RIGHT_TOP: 7, + + /** + * A constant representing a right-center alignment or position. + * @constant Phaser.RIGHT_CENTER + * @type {integer} + */ + RIGHT_CENTER: 8, + + /** + * A constant representing a right-bottom alignment or position. + * @constant Phaser.RIGHT_BOTTOM + * @type {integer} + */ + RIGHT_BOTTOM: 9, + + /** + * A constant representing a bottom-left alignment or position. + * @constant Phaser.BOTTOM_LEFT + * @type {integer} + */ + BOTTOM_LEFT: 10, + + /** + * A constant representing a bottom-center alignment or position. + * @constant Phaser.BOTTOM_CENTER + * @type {integer} + */ + BOTTOM_CENTER: 11, + + /** + * A constant representing a bottom-right alignment or position. + * @constant Phaser.BOTTOM_RIGHT + * @type {integer} + */ + BOTTOM_RIGHT: 12, + + /** + * Various blend modes supported by Pixi. See the samples in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing Canvas Tutorial: Compositing}. + * + * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * + * @constant {Object} Phaser.blendModes + * @property {Number} blendModes.NORMAL - Draws new shapes on top of the existing content. This is the default setting. + * @property {Number} blendModes.ADD - Where both shapes overlap the color is determined by adding color values. + * @property {Number} blendModes.MULTIPLY - The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer, making a darker picture. + * @property {Number} blendModes.SCREEN - The pixels are inverted, multiplied, and inverted again, making a lighter picture. + * @property {Number} blendModes.OVERLAY + * @property {Number} blendModes.DARKEN + * @property {Number} blendModes.LIGHTEN + * @property {Number} blendModes.COLOR_DODGE + * @property {Number} blendModes.COLOR_BURN + * @property {Number} blendModes.HARD_LIGHT + * @property {Number} blendModes.SOFT_LIGHT + * @property {Number} blendModes.DIFFERENCE + * @property {Number} blendModes.EXCLUSION + * @property {Number} blendModes.HUE + * @property {Number} blendModes.SATURATION + * @property {Number} blendModes.COLOR + * @property {Number} blendModes.LUMINOSITY + * @static + */ + 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 + }, + + /** + * The scale modes that are supported by Pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @constant {Object} Phaser.scaleModes + * @property {Number} Phaser.scaleModes.DEFAULT=LINEAR + * @property {Number} Phaser.scaleModes.LINEAR Smooth scaling + * @property {Number} Phaser.scaleModes.NEAREST Pixelating scaling + * @static + */ + scaleModes: { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 + }, + + PIXI: PIXI || {}, + + // Used to create IDs for various Pixi objects. + _UID: 0 + +}; + +/** +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc +if (!Math.trunc) { + Math.trunc = function trunc(x) { + return x < 0 ? Math.ceil(x) : Math.floor(x); + }; +} + +/** +* A polyfill for Function.prototype.bind +*/ +if (!Function.prototype.bind) { + + /* jshint freeze: false */ + 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)) + { + /* jshint supernew: true */ + return new F; + } + })(target.prototype); + + return bound; + }; + })(); +} + +/** +* A polyfill for Array.isArray +*/ +if (!Array.isArray) +{ + Array.isArray = function (arg) + { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + +/** +* A polyfill for Array.forEach +* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach +*/ +if (!Array.prototype.forEach) +{ + Array.prototype.forEach = function(fun /*, thisArg */) + { + "use strict"; + + if (this === void 0 || this === null) + { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + if (typeof fun !== "function") + { + throw new TypeError(); + } + + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + + for (var i = 0; i < len; i++) + { + if (i in t) + { + fun.call(thisArg, t[i], i, t); + } + } + }; +} + +/** +* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 +* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ +* Cameron Foale (http://www.kibibu.com) +*/ +if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object") +{ + var CheapArray = function(type) + { + var proto = new Array(); // jshint ignore:line + + window[type] = function(arg) { + + if (typeof(arg) === "number") + { + Array.call(this, arg); + this.length = arg; + + for (var i = 0; i < this.length; i++) + { + this[i] = 0; + } + } + else + { + Array.call(this, arg.length); + + this.length = arg.length; + + for (var i = 0; i < this.length; i++) + { + this[i] = arg[i]; + } + } + }; + + window[type].prototype = proto; + window[type].constructor = window[type]; + }; + + CheapArray('Float32Array'); // jshint ignore:line + CheapArray('Uint32Array'); // jshint ignore:line + CheapArray('Uint16Array'); // jshint ignore:line + CheapArray('Int16Array'); // jshint ignore:line + CheapArray('ArrayBuffer'); // jshint ignore:line +} + +/** + * Also fix for the absent console in IE9 + */ +if (!window.console) +{ + window.console = {}; + window.console.log = window.console.assert = function(){}; + window.console.warn = window.console.assert = function(){}; +} + +/** + * Fix for Object.assign not existing on older devices + */ + +if (!Object.assign) { + /* jshint -W098 */ + // We include `varArgs` (unused) to ensure Object.assign.length === 2 + Object.assign = function(target, varArgs) { + /* jshint +W098 */ + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + var hasOwn = Object.prototype.hasOwnProperty; + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (hasOwn.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @class Phaser.Utils +* @static +*/ +Phaser.Utils = { + + /** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @method Phaser.Utils.reverseString + * @param {string} string - The string to be reversed. + * @return {string} The reversed string. + */ + reverseString: function (string) { + + return string.split('').reverse().join(''); + + }, + + /** + * Gets an object's property by string. + * + * @method Phaser.Utils.getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + getProperty: function(obj, name) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + return obj[name]; + case 2: + return obj[parts[0]][parts[1]]; + case 3: + return obj[parts[0]][parts[1]][parts[2]]; + case 4: + return obj[parts[0]][parts[1]][parts[2]][parts[3]]; + default: + return this._getProperty(obj, name); + } + + }, + + /** + * Sets an object's properties from a map of property names and values. + * + * ```javascript + * Phaser.Utils.setProperties(sprite, { + * 'animations.paused': true, + * 'body.enable': false, + * 'input.draggable': true, + * }); + * ``` + * + * @method Phaser.Utils.setProperties + * @param {object} obj - The object to modify. + * @param {object} props - The property names and values to set on the object (see {@link #setProperty}). + * @return {object} The modified object. + */ + setProperties: function(obj, props) { + + for (var name in props) + { + this.setProperty(obj, name, props[name]); + } + + return obj; + + }, + + /** + * Sets an object's property by name and value. + * + * ```javascript + * Phaser.Utils.setProperty(sprite, 'body.velocity.x', 60); + * ``` + * + * @method Phaser.Utils.setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + + setProperty: function(obj, name, value) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + obj[name] = value; + break; + case 2: + obj[parts[0]][parts[1]] = value; + break; + case 3: + obj[parts[0]][parts[1]][parts[2]] = value; + break; + case 4: + obj[parts[0]][parts[1]][parts[2]][parts[3]] = value; + break; + default: + this._setProperty(obj, name, value); + } + }, + + /** + * Gets an object's property by string. + * + * @private + * @method Phaser.Utils._getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property whose value will be returned. + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + _getProperty: function(obj, name) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + val = obj; + + while (i < len) + { + var key = parts[i]; + + if (val != null) + { + val = val[key]; + i++; + } + else + { + return undefined; + } + } + + return val; + + }, + + /** + * Sets an object's property by name and value. + * + * @private + * @method Phaser.Utils._setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + _setProperty: function(obj, name, value) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + currentObj = obj, + key = parts[0]; + + if (len === 1) + { + obj[name] = value; + } + else + { + while (i < (len - 1)) + { + currentObj = currentObj[key]; + i++; + key = parts[i]; + } + + currentObj[key] = value; + } + + return obj; + + }, + + /** + * Generate a random bool result based on the chance value. + * + * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance + * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. + * + * @method Phaser.Utils#chanceRoll + * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). + * @return {boolean} True if the roll passed, or false otherwise. + */ + chanceRoll: function (chance) { + if (chance === undefined) { chance = 50; } + return chance > 0 && (Math.random() * 100 <= chance); + }, + + /** + * Choose between one of two values randomly. + * + * @method Phaser.Utils#randomChoice + * @param {any} choice1 + * @param {any} choice2 + * @return {any} The randomly selected choice + */ + randomChoice: function (choice1, choice2) { + return (Math.random() < 0.5) ? choice1 : choice2; + }, + + /** + * Get a unit dimension from a string. + * + * @method Phaser.Utils.parseDimension + * @param {string|number} size - The size to parse. + * @param {number} dimension - The window dimension to check. + * @return {number} The parsed dimension. + */ + parseDimension: function (size, dimension) { + + var f = 0; + var px = 0; + + if (typeof size === 'string') + { + // %? + if (size.substr(-1) === '%') + { + f = parseInt(size, 10) / 100; + + if (dimension === 0) + { + px = window.innerWidth * f; + } + else + { + px = window.innerHeight * f; + } + } + else + { + px = parseInt(size, 10); + } + } + else + { + px = size; + } + + return px; + + }, + + /** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @method Phaser.Utils.pad + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * @return {string} The padded string. + */ + pad: function (str, len, pad, dir) { + + if (len === undefined) { var len = 0; } + if (pad === undefined) { var pad = ' '; } + if (dir === undefined) { var dir = 3; } + + str = str.toString(); + + 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; + + }, + + /** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * @method Phaser.Utils.isPlainObject + * @param {object} obj - The object to inspect. + * @return {boolean} - true if the object is plain, otherwise false. + */ + isPlainObject: function (obj) { + + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) + { + return false; + } + + // Support: Firefox <20 + // The try/catch suppresses exceptions thrown when attempting to access + // the "constructor" property of certain host objects, ie. |window.location| + // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + try { + if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) + { + return false; + } + } catch (e) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + /** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @method Phaser.Utils.extend + * @param {boolean} deep - Perform a deep copy? + * @param {object} target - The target object to copy to. + * @return {object} The extended object. + */ + extend: function () { + + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if (typeof target === "boolean") + { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } + + for (; i < length; i++) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) + { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = Phaser.Utils.extend(deep, clone, copy); + + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; + + }, + + /** + * Mixes in an existing mixin object with the target. + * + * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` + * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and + * the result is assigned directly. + * + * @method Phaser.Utils.mixinPrototype + * @param {object} target - The target object to receive the new functions. + * @param {object} mixin - The object to copy the functions from. + * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not? + */ + mixinPrototype: function (target, mixin, replace) { + + if (replace === undefined) { replace = false; } + + var mixinKeys = Object.keys(mixin); + + for (var i = 0; i < mixinKeys.length; i++) + { + var key = mixinKeys[i]; + var value = mixin[key]; + + if (!replace && (key in target)) + { + // Not overwriting existing property + continue; + } + else + { + if (value && + (typeof value.get === 'function' || typeof value.set === 'function')) + { + // Special case for classes like Phaser.Point which has a 'set' function! + if (typeof value.clone === 'function') + { + target[key] = value.clone(); + } + else + { + Object.defineProperty(target, key, value); + } + } + else + { + target[key] = value; + } + } + } + + }, + + /** + * Mixes the source object into the destination object, returning the newly modified destination object. + * Based on original code by @mudcube + * + * @method Phaser.Utils.mixin + * @param {object} from - The object to copy (the source object). + * @param {object} to - The object to copy to (the destination object). + * @return {object} The modified destination object. + */ + mixin: function (from, to) { + + if (!from || typeof (from) !== "object") + { + return to; + } + + for (var key in from) + { + var o = from[key]; + + if (o.childNodes || o.cloneNode) + { + continue; + } + + var type = typeof (from[key]); + + if (!from[key] || type !== "object") + { + to[key] = from[key]; + } + else + { + // Clone sub-object + if (typeof (to[key]) === type) + { + to[key] = Phaser.Utils.mixin(from[key], to[key]); + } + else + { + to[key] = Phaser.Utils.mixin(from[key], new o.constructor()); + } + } + } + + return to; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. +* If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. +* +* @class Phaser.Circle +* @constructor +* @param {number} [x=0] - The x coordinate of the center of the circle. +* @param {number} [y=0] - The y coordinate of the center of the circle. +* @param {number} [diameter=0] - The diameter of the circle. +*/ +Phaser.Circle = function (x, y, diameter) { + + x = x || 0; + y = y || 0; + diameter = diameter || 0; + + /** + * @property {number} x - The x coordinate of the center of the circle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the center of the circle. + */ + this.y = y; + + /** + * @property {number} _diameter - The diameter of the circle. + * @private + */ + this._diameter = diameter; + + /** + * @property {number} _radius - The radius of the circle. + * @private + */ + this._radius = 0; + + if (diameter > 0) + { + this._radius = diameter * 0.5; + } + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.CIRCLE; + +}; + +Phaser.Circle.prototype = { + + /** + * The circumference of the circle. + * + * @method Phaser.Circle#circumference + * @return {number} The circumference of the circle. + */ + circumference: function () { + + return 2 * (Math.PI * this._radius); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Circle. + * + * @method Phaser.Circle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = 2 * Math.PI * Math.random(); + var u = Math.random() + Math.random(); + var r = (u > 1) ? 2 - u : u; + var x = r * Math.cos(t); + var y = r * Math.sin(t); + + out.x = this.x + (x * this.radius); + out.y = this.y + (y * this.radius); + + return out; + + }, + + /** + * Returns the framing rectangle of the circle as a Phaser.Rectangle object. + * + * @method Phaser.Circle#getBounds + * @return {Phaser.Rectangle} The bounds of the Circle. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter); + + }, + + /** + * Sets the members of Circle to the specified values. + * @method Phaser.Circle#setTo + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} diameter - The diameter of the circle. + * @return {Circle} This circle object. + */ + setTo: function (x, y, diameter) { + + this.x = x; + this.y = y; + this._diameter = diameter; + this._radius = diameter * 0.5; + + return this; + + }, + + /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method Phaser.Circle#copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.diameter); + + }, + + /** + * Copies the x, y and diameter properties from this Circle to any given object. + * @method Phaser.Circle#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.diameter = this._diameter; + + return dest; + + }, + + /** + * Returns the distance from the center of the Circle object to the given object + * (can be Circle, Point or anything with x/y properties) + * @method Phaser.Circle#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round=false] - Round the distance to the nearest integer. + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y); + return round ? Math.round(distance) : distance; + + }, + + /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. + * @method Phaser.Circle#clone + * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} The cloned Circle object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Circle(this.x, this.y, this.diameter); + } + else + { + output.setTo(this.x, this.y, this.diameter); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Circle object. + * @method Phaser.Circle#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this circle, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Circle.contains(this, x, y); + + }, + + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method Phaser.Circle#circumferencePoint + * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ + circumferencePoint: function (angle, asDegrees, out) { + + return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out); + + }, + + + /** + * Creates or positions points on the circle. + * + * The points are equally distributed in the half-closed interval [startAngle, endAngle). The default arc is the entire circle. + * + * If the `out` argument is omitted, this method creates and returns an array of {@link Phaser.Point points}. If an array is passed as `out`, its items are treated as points and placed in the same way. + * + * @param {type} [steps=60] - The number of points to place. + * @param {type} [startAngle=0] - The starting angle in radians (unless asDegrees is true). + * @param {type} [endAngle=Phaser.Math.PI2] - The end angle in radians (unless asDegrees is true). + * @param {type} [asDegrees=false] - Are the given angles in radians (false) or degrees (true)? + * @param {any[]} [out] - An array of points or point-like objects (e.g., sprites). It should start at index 0 and its length should be equal to or greater than `steps`. + * @return {any[]} - The modified `out` argument or a new array of points. + */ + sample: function (steps, startAngle, endAngle, asDegrees, out) { + + if (!steps) { steps = 60; } + if (startAngle == null) { startAngle = 0; } + if (endAngle == null) { endAngle = Phaser.Math.PI2; } + if (!out) { out = []; } + + var i = 0; + + while (i < steps) + { + this.circumferencePoint( + Phaser.Math.linear(startAngle, endAngle, i / steps), + asDegrees, + out[i] || (out[i] = new Phaser.Point()) + ); + + i += 1; + } + + return out; + + }, + + /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method Phaser.Circle#offset + * @param {number} dx - Moves the x value of the Circle object by this amount. + * @param {number} dy - Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Circle#offsetPoint + * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). + * @return {Circle} This Circle object. + */ + offsetPoint: function (point) { + return this.offset(point.x, point.y); + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Circle#toString + * @return {string} a string representation of the instance. + */ + toString: function () { + return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; + } + +}; + +Phaser.Circle.prototype.constructor = Phaser.Circle; + +/** +* The largest distance between any two points on the circle. The same as the radius * 2. +* +* @name Phaser.Circle#diameter +* @property {number} diameter - Gets or sets the diameter of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "diameter", { + + get: function () { + return this._diameter; + }, + + set: function (value) { + + if (value > 0) + { + this._diameter = value; + this._radius = value * 0.5; + } + } + +}); + +/** +* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. +* @name Phaser.Circle#radius +* @property {number} radius - Gets or sets the radius of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "radius", { + + get: function () { + return this._radius; + }, + + set: function (value) { + + if (value > 0) + { + this._radius = value; + this._diameter = value * 2; + } + + } + +}); + +/** +* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#left +* @propety {number} left - Gets or sets the value of the leftmost point of the circle. +*/ +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; + } + + } + +}); + +/** +* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#right +* @property {number} right - Gets or sets the value of the rightmost point of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "right", { + + get: function () { + return this.x + this._radius; + }, + + set: function (value) { + + if (value < this.x) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.x; + } + + } + +}); + +/** +* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#top +* @property {number} top - Gets or sets the top of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "top", { + + get: function () { + return this.y - this._radius; + }, + + set: function (value) { + + if (value > this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = this.y - value; + } + + } + +}); + +/** +* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#bottom +* @property {number} bottom - Gets or sets the bottom of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "bottom", { + + get: function () { + return this.y + this._radius; + }, + + set: function (value) { + + if (value < this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.y; + } + + } + +}); + +/** +* The area of this Circle. +* @name Phaser.Circle#area +* @property {number} area - The area of this circle. +* @readonly +*/ +Object.defineProperty(Phaser.Circle.prototype, "area", { + + get: function () { + + if (this._radius > 0) + { + return Math.PI * this._radius * this._radius; + } + else + { + return 0; + } + + } + +}); + +/** +* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. +* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. +* @name Phaser.Circle#empty +* @property {boolean} empty - Gets or sets the empty state of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "empty", { + + get: function () { + return (this._diameter === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Circle object. +* @method Phaser.Circle.contains +* @param {Phaser.Circle} a - The Circle to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this circle, otherwise false. +*/ +Phaser.Circle.contains = function (a, x, y) { + + // Check if x/y are within the bounds first + 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; + } + +}; + +/** +* Determines whether the two Circle objects match. This method compares the x, y and diameter properties. +* @method Phaser.Circle.equals +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. +*/ +Phaser.Circle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.diameter === b.diameter); + +}; + +/** +* Determines whether the two Circle objects intersect. +* This method checks the radius distances between the two Circle objects to see if they intersect. +* @method Phaser.Circle.intersects +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. +*/ +Phaser.Circle.intersects = function (a, b) { + + return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius)); + +}; + +/** +* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. +* @method Phaser.Circle.circumferencePoint +* @param {Phaser.Circle} a - The first Circle object. +* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. +* @return {Phaser.Point} The Point object holding the result. +*/ +Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) { + + if (asDegrees === undefined) { asDegrees = false; } + if (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; + +}; + +/** +* Checks if the given Circle and Rectangle objects intersect. +* @method Phaser.Circle.intersectsRectangle +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Rectangle} r - The Rectangle object to test. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +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; + +}; + +/** +* Checks if the given Circle and Line objects intersect. +* @method Phaser.Circle.intersectsLine +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnpoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Circle.intersectsLine = function (c, l, returnPoints) { + var h = c.x; + var k = c.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = c.radius; + var b = c.radius; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Circle = Phaser.Circle; + +/** +* @author Richard Davey +* @author Chad Engler +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a Ellipse object. A curve on a plane surrounding two focal points. +* +* @class Phaser.Ellipse +* @constructor +* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [width=0] - The overall width of this ellipse. +* @param {number} [height=0] - The overall height of this ellipse. +*/ +Phaser.Ellipse = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.x = x; + + /** + * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.y = y; + + /** + * @property {number} width - The overall width of this ellipse. + */ + this.width = width; + + /** + * @property {number} height - The overall height of this ellipse. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ELLIPSE; + +}; + +Phaser.Ellipse.prototype = { + + /** + * Sets the members of the Ellipse to the specified values. + * @method Phaser.Ellipse#setTo + * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} width - The overall width of this ellipse. + * @param {number} height - The overall height of this ellipse. + * @return {Phaser.Ellipse} This Ellipse object. + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. + * + * @method Phaser.Ellipse#getBounds + * @return {Phaser.Rectangle} The bounds of the Ellipse. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Ellipse. + * + * @method Phaser.Ellipse#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Ellipse} This Ellipse object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Ellipse to any given object. + * @method Phaser.Ellipse#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function(dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. + * @method Phaser.Ellipse#clone + * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. + * @return {Phaser.Ellipse} The cloned Ellipse object. + */ + clone: function(output) { + + if (output === undefined || output === null) + { + output = new Phaser.Ellipse(this.x, this.y, this.width, this.height); + } + else + { + output.setTo(this.x, this.y, this.width, this.height); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Ellipse object. + * + * @method Phaser.Ellipse#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this ellipse, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Ellipse.contains(this, x, y); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Ellipse. + * + * @method Phaser.Ellipse#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var p = Math.random() * Math.PI * 2; + var r = Math.random(); + + out.x = Math.sqrt(r) * Math.cos(p); + out.y = Math.sqrt(r) * Math.sin(p); + + out.x = this.x + (out.x * this.width / 2.0); + out.y = this.y + (out.y * this.height / 2.0); + + return out; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Ellipse#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]"; + } + +}; + +Phaser.Ellipse.prototype.constructor = Phaser.Ellipse; + +/** +* The left coordinate of the Ellipse. The same as the X coordinate. +* @name Phaser.Ellipse#left +* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + + this.x = value; + + } + +}); + +/** +* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. +* @name Phaser.Ellipse#right +* @property {number} right - Gets or sets the value of the rightmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "right", { + + get: function () { + return this.x + this.width; + }, + + set: function (value) { + + if (value < this.x) + { + this.width = 0; + } + else + { + this.width = value - this.x; + } + } + +}); + +/** +* The top of the Ellipse. The same as its y property. +* @name Phaser.Ellipse#top +* @property {number} top - Gets or sets the top of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "top", { + + get: function () { + return this.y; + }, + + set: function (value) { + this.y = value; + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. +* @name Phaser.Ellipse#bottom +* @property {number} bottom - Gets or sets the bottom of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value < this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + } + +}); + +/** +* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. +* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. +* @name Phaser.Ellipse#empty +* @property {boolean} empty - Gets or sets the empty state of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "empty", { + + get: function () { + return (this.width === 0 || this.height === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Ellipse object. +* +* @method Phaser.Ellipse.contains +* @param {Phaser.Ellipse} a - The Ellipse to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this ellipse, otherwise false. +*/ +Phaser.Ellipse.contains = function (a, x, y) { + + if (a.width <= 0 || a.height <= 0) { + return false; + } + + // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 + var normx = ((x - a.x) / a.width) - 0.5; + var normy = ((y - a.y) / a.height) - 0.5; + + normx *= normx; + normy *= normy; + + return (normx + normy < 0.25); + +}; + +/** +* Checks if the given Ellipse and Line objects intersect. +* @method Phaser.Ellipse.intersectsLine +* @param {Phaser.Ellipse} e - The Ellipse object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnPoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Ellipse.intersectsLine = function (e, l, returnPoints) { + var h = e.x; + var k = e.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = e.width / 2; + var b = e.height / 2; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Ellipse = Phaser.Ellipse; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Line object with a start and an end point. +* +* @class Phaser.Line +* @constructor +* @param {number} [x1=0] - The x coordinate of the start of the line. +* @param {number} [y1=0] - The y coordinate of the start of the line. +* @param {number} [x2=0] - The x coordinate of the end of the line. +* @param {number} [y2=0] - The y coordinate of the end of the line. +*/ +Phaser.Line = function (x1, y1, x2, y2) { + + x1 = x1 || 0; + y1 = y1 || 0; + x2 = x2 || 0; + y2 = y2 || 0; + + /** + * @property {Phaser.Point} start - The start point of the line. + */ + this.start = new Phaser.Point(x1, y1); + + /** + * @property {Phaser.Point} end - The end point of the line. + */ + this.end = new Phaser.Point(x2, y2); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.LINE; + +}; + +Phaser.Line.prototype = { + + /** + * Sets the components of the Line to the specified values. + * + * @method Phaser.Line#setTo + * @param {number} [x1=0] - The x coordinate of the start of the line. + * @param {number} [y1=0] - The y coordinate of the start of the line. + * @param {number} [x2=0] - The x coordinate of the end of the line. + * @param {number} [y2=0] - The y coordinate of the end of the line. + * @return {Phaser.Line} This line object + */ + setTo: function (x1, y1, x2, y2) { + + this.start.setTo(x1, y1); + this.end.setTo(x2, y2); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given points. + * + * @param {any} start - A {@link Phaser.Point} or point-like object. + * @param {any} end - A {@link Phaser.Point} or point-like object. + * @return {Phaser.Line} - This line object. + */ + fromPoints: function (start, end) { + + this.setTo(start.x, start.y, end.x, end.y); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given sprites. + * Can optionally be calculated from their center coordinates. + * + * @method Phaser.Line#fromSprite + * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {boolean} [useCenter=false] - If true it will use startSprite.centerX, if false startSprite.x. + * @return {Phaser.Line} This line object + */ + fromSprite: function (startSprite, endSprite, useCenter) { + + if (useCenter === undefined) { useCenter = false; } + + if (useCenter) + { + return this.setTo(startSprite.centerX, startSprite.centerY, endSprite.centerX, endSprite.centerY); + } + + return this.fromPoints(startSprite, endSprite); + + }, + + /** + * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. + * + * @method Phaser.Line#fromAngle + * @param {number} x - The x coordinate of the start of the line. + * @param {number} y - The y coordinate of the start of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line in pixels. + * @return {Phaser.Line} This line object + */ + fromAngle: function (x, y, angle, length) { + + this.start.setTo(x, y); + this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length)); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place from the center of the line. + * If you wish to rotate around a different point see Line.rotateAround. + * + * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. + * + * @method Phaser.Line#rotate + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotate: function (angle, asDegrees) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + this.start.rotate(cx, cy, angle, asDegrees); + this.end.rotate(cx, cy, angle, asDegrees); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place around the coordinates given. + * + * @method Phaser.Line#rotateAround + * @param {number} x - The x coordinate to offset the rotation from. + * @param {number} y - The y coordinate to offset the rotation from. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotateAround: function (x, y, angle, asDegrees) { + + this.start.rotate(x, y, angle, asDegrees); + this.end.rotate(x, y, angle, asDegrees); + + return this; + + }, + + /** + * Checks for intersection between this line and another Line. + * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * + * @method Phaser.Line#intersects + * @param {Phaser.Line} line - The line to check against this one. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ + intersects: function (line, asSegment, result) { + + return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result); + + }, + + /** + * Returns the reflected angle between two lines. + * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. + * + * @method Phaser.Line#reflect + * @param {Phaser.Line} line - The line to reflect off this line. + * @return {number} The reflected angle in radians. + */ + reflect: function (line) { + + return Phaser.Line.reflect(this, line); + + }, + + /** + * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. + * + * @method Phaser.Line#midPoint + * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. + * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. + */ + midPoint: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = (this.start.x + this.end.x) / 2; + out.y = (this.start.y + this.end.y) / 2; + + return out; + + }, + + /** + * Centers this Line on the given coordinates. + * + * The line is centered by positioning the start and end points so that the lines midpoint matches + * the coordinates given. + * + * @method Phaser.Line#centerOn + * @param {number} x - The x position to center the line on. + * @param {number} y - The y position to center the line on. + * @return {Phaser.Line} This line object + */ + centerOn: function (x, y) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + var tx = x - cx; + var ty = y - cy; + + this.start.add(tx, ty); + this.end.add(tx, ty); + + }, + + /** + * Tests if the given coordinates fall on this line. See {@link #pointOnSegment} to test against just the line segment. + * + * @method Phaser.Line#pointOnLine + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line, false if not. + */ + pointOnLine: function (x, y, epsilon) { + + return Phaser.Math.fuzzyEqual((x - this.start.x) * (this.end.y - this.start.y), (this.end.x - this.start.x) * (y - this.start.y), epsilon || 0); + + }, + + /** + * Tests if the given coordinates fall on this line and within the segment. See {@link #pointOnLine} to test against just the line. + * + * @method Phaser.Line#pointOnSegment + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line and segment, false if not. + */ + pointOnSegment: function (x, y, epsilon) { + + var xMin = Math.min(this.start.x, this.end.x); + var xMax = Math.max(this.start.x, this.end.x); + var yMin = Math.min(this.start.y, this.end.y); + var yMax = Math.max(this.start.y, this.end.y); + + return (this.pointOnLine(x, y, epsilon) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)); + + }, + + /** + * Picks a random point from anywhere on the Line segment and returns it. + * + * @method Phaser.Line#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = Math.random(); + + out.x = this.start.x + t * (this.end.x - this.start.x); + out.y = this.start.y + t * (this.end.y - this.start.y); + + return out; + + }, + + /** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * The start and end points are rounded before this runs as the algorithm works on integers. + * + * @method Phaser.Line#coordinatesOnLine + * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. + * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. + * @return {array} An array of coordinates. + */ + coordinatesOnLine: function (stepRate, results) { + + if (stepRate === undefined) { stepRate = 1; } + if (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 < x2) ? 1 : -1; + var sy = (y1 < y2) ? 1 : -1; + var err = dx - dy; + + results.push([x1, y1]); + + var i = 1; + + while (!((x1 === x2) && (y1 === y2))) + { + var e2 = err << 1; + + if (e2 > -dy) + { + err -= dy; + x1 += sx; + } + + if (e2 < dx) + { + err += dx; + y1 += sy; + } + + if (i % stepRate === 0) + { + results.push([x1, y1]); + } + + i++; + + } + + return results; + + }, + + /** + * Returns a new Line object with the same values for the start and end properties as this Line object. + * @method Phaser.Line#clone + * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned. + * @return {Phaser.Line} The cloned Line object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y); + } + else + { + output.setTo(this.start.x, this.start.y, this.end.x, this.end.y); + } + + return output; + + } + +}; + +/** +* @name Phaser.Line#length +* @property {number} length - Gets the length of the line segment. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "length", { + + get: function () { + return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#angle +* @property {number} angle - Gets the angle of the line in radians. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "angle", { + + get: function () { + return Phaser.Point.angle(this.end, this.start); + } + +}); + +/** +* @name Phaser.Line#slope +* @property {number} slope - Gets the slope of the line (y/x). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "slope", { + + get: function () { + return (this.end.y - this.start.y) / (this.end.x - this.start.x); + } + +}); + +/** +* @name Phaser.Line#perpSlope +* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "perpSlope", { + + get: function () { + return -((this.end.x - this.start.x) / (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#x +* @property {number} x - Gets the x coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "x", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#y +* @property {number} y - Gets the y coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "y", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#left +* @property {number} left - Gets the left-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "left", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#right +* @property {number} right - Gets the right-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "right", { + + get: function () { + return Math.max(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#top +* @property {number} top - Gets the top-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "top", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#bottom +* @property {number} bottom - Gets the bottom-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "bottom", { + + get: function () { + return Math.max(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#width +* @property {number} width - Gets the width of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "width", { + + get: function () { + return Math.abs(this.start.x - this.end.x); + } + +}); + +/** +* @name Phaser.Line#height +* @property {number} height - Gets the height of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "height", { + + get: function () { + return Math.abs(this.start.y - this.end.y); + } + +}); + +/** +* @name Phaser.Line#normalX +* @property {number} normalX - Gets the x component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalX", { + + get: function () { + return Math.cos(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalY +* @property {number} normalY - Gets the y component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalY", { + + get: function () { + return Math.sin(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalAngle +* @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalAngle", { + + get: function () { + return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI); + } + +}); + +/** +* Checks for intersection between two lines as defined by the given start and end points. +* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersectsPoints +* @param {Phaser.Point} a - The start of the first Line to be checked. +* @param {Phaser.Point} b - The end of the first line to be checked. +* @param {Phaser.Point} e - The start of the second Line to be checked. +* @param {Phaser.Point} f - The end of the second line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) { + + if (asSegment === undefined) { asSegment = true; } + if (result === undefined) { result = new Phaser.Point(); } + + var a1 = b.y - a.y; + var a2 = f.y - e.y; + var b1 = a.x - b.x; + var b2 = e.x - f.x; + var c1 = (b.x * a.y) - (a.x * b.y); + var c2 = (f.x * e.y) - (e.x * f.y); + var denom = (a1 * b2) - (a2 * b1); + + if (denom === 0) + { + return null; + } + + result.x = ((b1 * c2) - (b2 * c1)) / denom; + result.y = ((a2 * c1) - (a1 * c2)) / denom; + + if (asSegment) + { + var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y)); + var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc; + var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc; + + if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) + { + return result; + } + else + { + return null; + } + } + + return result; + +}; + +/** +* Checks for intersection between two lines. +* If asSegment is true it will check for segment intersection. +* If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersects +* @param {Phaser.Line} a - The first Line to be checked. +* @param {Phaser.Line} b - The second Line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersects = function (a, b, asSegment, result) { + + return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result); + +}; + +/** +* Checks for intersection between the Line and a Rectangle shape, or a rectangle-like +* object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. +* +* An intersection is considered valid if: +* +* The line starts within or ends within the rectangle; or +* The line segment intersects one of the 4 rectangle edges; and +* The line has a non-zero length; and +* The rectangle is not empty. +* +* For the purposes of this function rectangles are considered 'solid'. +* +* @method Phaser.Line.intersectsRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle. +*/ +Phaser.Line.intersectsRectangle = function (line, rect) { + + // Quick bail out + if (line.length === 0 || rect.empty) + { + return false; + } + + var x1 = line.start.x; + var y1 = line.start.y; + + var x2 = line.end.x; + var y2 = line.end.y; + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + + var t = 0; + + // If the start or end of the line is inside the rect then we assume + // collision, as rects are solid for our use-case. + + if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || + (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) + { + return true; + } + + if (x1 < bx1 && x2 >= bx1) + { + // Left edge + t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); + + if (t > by1 && t <= by2) + { + return true; + } + } + else if (x1 > bx2 && x2 <= bx2) + { + // Right edge + t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); + + if (t >= by1 && t <= by2) + { + return true; + } + } + + if (y1 < by1 && y2 >= by1) + { + // Top edge + t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + else if (y1 > by2 && y2 <= by2) + { + // Bottom edge + t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + + return false; + +}; + +/** +* Finds the closest intersection between the Line and a Rectangle shape, or a rectangle-like +* object, such as a Sprite or Body. +* +* @method Phaser.Line.intersectionWithRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @param {Phaser.Point} [result] - A Point object to store the result in. +* @return {?Phaser.Point} - The intersection closest to the Line's start, or null if there is no intersection. +*/ +Phaser.Line.intersectionWithRectangle = function (line, rect, result) { + + var self = Phaser.Line.intersectionWithRectangle; + + if (!result) + { + result = new Phaser.Point(); + } + + if (!self.edges) + { + self.edges = [new Phaser.Line(), new Phaser.Line(), new Phaser.Line(), new Phaser.Line()]; + } + + if (!self.edgeIntersection) + { + self.edgeIntersection = new Phaser.Point(); + } + + var edges = self.edges; + var edgeIntersection = self.edgeIntersection.set(0); + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + var closestDistance = Infinity; + + edges[0].setTo(bx1, by1, bx2, by1); + edges[1].setTo(bx1, by2, bx2, by2); + edges[2].setTo(bx1, by1, bx1, by2); + edges[3].setTo(bx2, by1, bx2, by2); + + for (var edge, i = 0; (edge = edges[i]); i++) + { + if (line.intersects(edge, true, edgeIntersection)) + { + var distance = line.start.distance(edgeIntersection); + + if (distance < closestDistance) + { + closestDistance = distance; + result.copyFrom(edgeIntersection); + } + } + } + + if (distance != null) + { + return result; + } + + return null; + +}; + +/** +* Returns the reflected angle between two lines. +* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. +* +* @method Phaser.Line.reflect +* @param {Phaser.Line} a - The base line. +* @param {Phaser.Line} b - The line to be reflected from the base line. +* @return {number} The reflected angle in radians. +*/ +Phaser.Line.reflect = function (a, b) { + + return 2 * b.normalAngle - 3.141592653589793 - a.angle; + +}; + +/** +* @author Mat Groves http://matgroves.com/ @Doormat23 +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. +* +* It is represented like so: +* +* | a | b | tx | +* | c | d | ty | +* | 0 | 0 | 1 | +* +* @class Phaser.Matrix +* @constructor +* @param {number} [a=1] - Horizontal scaling +* @param {number} [b=0] - Horizontal skewing +* @param {number} [c=0] - Vertical skewing +* @param {number} [d=1] - Vertical scaling +* @param {number} [tx=0] - Horizontal translation +* @param {number} [ty=0] - Vertical translation +*/ +Phaser.Matrix = function (a, b, c, d, tx, ty) { + + if (a === undefined || a === null) { a = 1; } + if (b === undefined || b === null) { b = 0; } + if (c === undefined || c === null) { c = 0; } + if (d === undefined || d === null) { d = 1; } + if (tx === undefined || tx === null) { tx = 0; } + if (ty === undefined || ty === null) { ty = 0; } + + /** + * @property {number} a + * @default 1 + */ + this.a = a; + + /** + * @property {number} b + * @default 0 + */ + this.b = b; + + /** + * @property {number} c + * @default 0 + */ + this.c = c; + + /** + * @property {number} d + * @default 1 + */ + this.d = d; + + /** + * @property {number} tx + * @default 0 + */ + this.tx = tx; + + /** + * @property {number} ty + * @default 0 + */ + this.ty = ty; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.MATRIX; + +}; + +Phaser.Matrix.prototype = { + + /** + * Sets the values of this Matrix to the values in the given array. + * + * The Array elements should be set as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @method Phaser.Matrix#fromArray + * @param {Array} array - The array to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + fromArray: function (array) { + + return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]); + + }, + + /** + * Sets the values of this Matrix to the given values. + * + * @method Phaser.Matrix#setTo + * @param {number} a - Horizontal scaling + * @param {number} b - Horizontal skewing + * @param {number} c - Vertical skewing + * @param {number} d - Vertical scaling + * @param {number} tx - Horizontal translation + * @param {number} ty - Vertical translation + * @return {Phaser.Matrix} This Matrix object. + */ + setTo: function (a, b, c, d, tx, ty) { + + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + + }, + + /** + * Creates a new Matrix object based on the values of this Matrix. + * If you provide the output parameter the values of this Matrix will be copied over to it. + * If the output parameter is blank a new Matrix object will be created. + * + * @method Phaser.Matrix#clone + * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created. + * @return {Phaser.Matrix} A clone of this Matrix. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); + } + else + { + output.a = this.a; + output.b = this.b; + output.c = this.c; + output.d = this.d; + output.tx = this.tx; + output.ty = this.ty; + } + + return output; + + }, + + /** + * Copies the properties from this Matrix to the given Matrix. + * + * @method Phaser.Matrix#copyTo + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} The destination Matrix object. + */ + copyTo: function (matrix) { + + matrix.copyFrom(this); + + return matrix; + + }, + + /** + * Copies the properties from the given Matrix into this Matrix. + * + * @method Phaser.Matrix#copyFrom + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + copyFrom: function (matrix) { + + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + + return this; + + }, + + /** + * Creates a Float32 Array with values populated from this Matrix object. + * + * @method Phaser.Matrix#toArray + * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not. + * @param {Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created. + * @return {Float32Array} The newly created array which contains the matrix. + */ + toArray: function (transpose, array) { + + if (array === undefined) { array = new Float32Array(9); } + + if (transpose) + { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else + { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + + }, + + /** + * Get a new position with the current transformation applied. + * + * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) + * + * @method Phaser.Matrix#apply + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, transformed through this matrix. + */ + apply: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + newPos.x = this.a * pos.x + this.c * pos.y + this.tx; + newPos.y = this.b * pos.x + this.d * pos.y + this.ty; + + return newPos; + + }, + + /** + * Get a new position with the inverse of the current transformation applied. + * + * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) + * + * @method Phaser.Matrix#applyInverse + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, inverse transformed through this matrix. + */ + applyInverse: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + var id = 1 / (this.a * this.d + this.c * -this.b); + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + + }, + + /** + * Translates the matrix on the x and y. + * This is the same as Matrix.tx += x. + * + * @method Phaser.Matrix#translate + * @param {number} x - The x value to translate on. + * @param {number} y - The y value to translate on. + * @return {Phaser.Matrix} This Matrix object. + */ + translate: function (x, y) { + + this.tx += x; + this.ty += y; + + return this; + + }, + + /** + * Applies a scale transformation to this matrix. + * + * @method Phaser.Matrix#scale + * @param {number} x - The amount to scale horizontally. + * @param {number} y - The amount to scale vertically. + * @return {Phaser.Matrix} This Matrix object. + */ + scale: function (x, y) { + + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + + }, + + /** + * Applies a rotation transformation to this matrix. + * + * @method Phaser.Matrix#rotate + * @param {number} angle - The angle to rotate by, given in radians. + * @return {Phaser.Matrix} This Matrix object. + */ + rotate: function (angle) { + + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos-this.b * sin; + this.b = a1 * sin+this.b * cos; + this.c = c1 * cos-this.d * sin; + this.d = c1 * sin+this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + + }, + + /** + * Appends the given Matrix to this Matrix. + * + * @method Phaser.Matrix#append + * @param {Phaser.Matrix} matrix - The matrix to append to this one. + * @return {Phaser.Matrix} This Matrix object. + */ + append: function (matrix) { + + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + + }, + + /** + * Resets this Matrix to an identity (default) matrix. + * + * @method Phaser.Matrix#identity + * @return {Phaser.Matrix} This Matrix object. + */ + identity: function () { + + return this.setTo(1, 0, 0, 1, 0, 0); + + } + +}; + +Phaser.identityMatrix = new Phaser.Matrix(); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. +* The following code creates a point at (0,0): +* `var myPoint = new Phaser.Point();` +* You can also use them as 2D Vectors and you'll find different vector related methods in this class. +* +* @class Phaser.Point +* @constructor +* @param {number} [x=0] - The horizontal position of this Point. +* @param {number} [y=0] - The vertical position of this Point. +*/ +Phaser.Point = function (x, y) { + + x = x || 0; + y = y || 0; + + /** + * @property {number} x - The x value of the point. + */ + this.x = x; + + /** + * @property {number} y - The y value of the point. + */ + this.y = y; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINT; + +}; + +Phaser.Point.prototype = { + + /** + * Copies the x and y properties from any given object to this Point. + * + * @method Phaser.Point#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Point} This Point object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y); + + }, + + /** + * Inverts the x and y values of this Point + * + * @method Phaser.Point#invert + * @return {Phaser.Point} This Point object. + */ + invert: function () { + + return this.setTo(this.y, this.x); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.setTo(2)` is the same as `Point.setTo(2, 2)` + * + * Identical to {@link #set}. + * + * @method Phaser.Point#setTo + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setTo: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.set(2)` is the same as `Point.set(2, 2)` + * + * Identical to {@link #setTo}. + * + * @method Phaser.Point#set + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + set: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object from a given polar coordinate. + * + * @method Phaser.Point#setToPolar + * @param {number} azimuth - The angular coordinate, in radians (unless `asDegrees`). + * @param {number} [radius=1] - The radial coordinate (length). + * @param {boolean} [asDegrees=false] - True if `azimuth` is in degrees. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setToPolar: function(azimuth, radius, asDegrees) { + + if (radius == null) { radius = 1; } + if (asDegrees) { azimuth = Phaser.Math.degToRad(azimuth); } + + return this.setTo(Math.cos(azimuth) * radius, Math.sin(azimuth) * radius); + + }, + + /** + * Adds the given x and y values to this Point. + * + * @method Phaser.Point#add + * @param {number} x - The value to add to Point.x. + * @param {number} y - The value to add to Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + add: function (x, y) { + + this.x += x; + this.y += y; + return this; + + }, + + /** + * Subtracts the given x and y values from this Point. + * + * @method Phaser.Point#subtract + * @param {number} x - The value to subtract from Point.x. + * @param {number} y - The value to subtract from Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + subtract: function (x, y) { + + this.x -= x; + this.y -= y; + return this; + + }, + + /** + * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. + * + * @method Phaser.Point#multiply + * @param {number} x - The value to multiply Point.x by. + * @param {number} y - The value to multiply Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + multiply: function (x, y) { + + this.x *= x; + this.y *= y; + return this; + + }, + + /** + * Divides Point.x and Point.y by the given x and y values. + * + * @method Phaser.Point#divide + * @param {number} x - The value to divide Point.x by. + * @param {number} y - The value to divide Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + divide: function (x, y) { + + this.x /= x; + this.y /= y; + return this; + + }, + + /** + * Clamps the x value of this Point to be between the given min and max. + * + * @method Phaser.Point#clampX + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampX: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + return this; + + }, + + /** + * Clamps the y value of this Point to be between the given min and max + * + * @method Phaser.Point#clampY + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampY: function (min, max) { + + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * Clamps this Point object values to be between the given min and max. + * + * @method Phaser.Point#clamp + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clamp: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * If this Point is not within the given object, moves it inside (at the nearest edge). + * + * @method Phaser.Point#clip + * @param {any} rect - A {@link Phaser.Rectangle} or any object with left, top, right, and bottom properties. + * @return {Phaser.Point} This Point object. + */ + clip: function (rect) { + + var left = rect.left, top = rect.top, right = rect.right, bottom = rect.bottom; + + if (this.x < left ) { this.x = left; } + else if (this.x > right) { this.x = right; } + if (this.y < top) { this.y = top; } + else if (this.y > bottom) { this.y = bottom; } + + return this; + + }, + + /** + * Creates a copy of the given Point. + * + * @method Phaser.Point#clone + * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The new Point object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(this.x, this.y); + } + else + { + output.setTo(this.x, this.y); + } + + return output; + + }, + + /** + * Copies the x and y properties from this Point to any given object. + * + * @method Phaser.Point#copyTo + * @param {any} dest - The object to copy to. + * @return {object} The dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + + return dest; + + }, + + /** + * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) + * + * @method Phaser.Point#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round] - Round the distance to the nearest integer (default false). + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + return Phaser.Point.distance(this, dest, round); + + }, + + /** + * Determines whether the given objects x/y values are equal to this Point object. + * + * @method Phaser.Point#equals + * @param {Phaser.Point|any} a - The object to compare with this Point. + * @return {boolean} A value of true if the x and y points are equal, otherwise false. + */ + equals: function (a) { + + return a.x === this.x && a.y === this.y; + + }, + + /** + * Determines whether a set of x-y coordinates are equal to this Point's. + * + * @method Phaser.Point#equalsXY + * @param {number} x - The x-coordinate to compare with this Point. + * @param {number} y - The y-coordinate to compare with this Point. + * @return {boolean} A value of true if the Point's coordinates are identical to the arguments, otherwise false. + */ + equalsXY: function (x, y) { + + return this.x === x && this.y === y; + + }, + + fuzzyEquals: function (a, epsilon) { + + return Phaser.Point.fuzzyEquals(this, a, epsilon); + + }, + + fuzzyEqualsXY: function (x, y, epsilon) { + + return Phaser.Point.fuzzyEqualsXY(this, x, y, epsilon); + + }, + + /** + * Returns the angle between this Point object and another object with public x and y properties. + * + * @method Phaser.Point#angle + * @param {Phaser.Point|any} a - The object to get the angle from this Point to. + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angle: function (a, asDegrees) { + + return this.angleXY(a.x, a.y, asDegrees); + + }, + + /** + * Returns the angle between this Point object and an x-y coordinate pair. + * + * @method Phaser.Point#angleXY + * @param {number} x - The x-coordinate + * @param {number} y - The y-coordinate + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angleXY: function (x, y, asDegrees) { + + var angle = Math.atan2(y - this.y, x - this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Returns the arctangent of this Point. + * + * @method Phaser.Point#atan + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where the vertex is (0, 0). Within [-pi, pi] or [-180deg, 180deg]. + */ + atan: function (asDegrees) { + + var angle = Math.atan2(this.y, this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Rotates this Point around the x/y coordinates given to the desired angle. + * + * @method Phaser.Point#rotate + * @param {number} x - The x coordinate of the anchor point. + * @param {number} y - The y coordinate of the anchor point. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {number} [distance] - An optional distance constraint between the Point and the anchor. + * @return {Phaser.Point} The modified point object. + */ + rotate: function (x, y, angle, asDegrees, distance) { + + return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance); + + }, + + /** + * Calculates the length of the Point object. + * + * @method Phaser.Point#getMagnitude + * @return {number} The length of the Point. + */ + getMagnitude: function () { + + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + + }, + + /** + * Calculates the length squared of the Point object. + * + * @method Phaser.Point#getMagnitudeSq + * @return {number} The length ^ 2 of the Point. + */ + getMagnitudeSq: function () { + + return (this.x * this.x) + (this.y * this.y); + + }, + + /** + * Alters the length of the Point without changing the direction. + * + * @method Phaser.Point#setMagnitude + * @param {number} magnitude - The desired magnitude of the resulting Point. + * @return {Phaser.Point} This Point object. + */ + setMagnitude: function (magnitude) { + + return this.normalize().multiply(magnitude, magnitude); + + }, + + /** + * Alters the Point object so that its length is 1, but it retains the same direction. + * + * @method Phaser.Point#normalize + * @return {Phaser.Point} This Point object. + */ + normalize: function () { + + if (!this.isZero()) + { + var m = this.getMagnitude(); + this.x /= m; + this.y /= m; + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at most the max value. + * + * @method Phaser.Point#limit + * @param {number} max - The maximum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#expand + */ + limit: function (max) { + + if (this.getMagnitudeSq() > max * max) + { + this.setMagnitude(max); + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at least the min value. + * + * @method Phaser.Point#expand + * @param {number} min - The minimum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#limit + */ + expand: function (min) { + + if (this.getMagnitudeSq() < min * min) + { + this.setMagnitude(min); + } + + return this; + + }, + + /** + * Determine if this point is at 0,0. + * + * @method Phaser.Point#isZero + * @return {boolean} True if this Point is 0,0, otherwise false. + */ + isZero: function () { + + return (this.x === 0 && this.y === 0); + + }, + + /** + * The dot product of this and another Point object. + * + * @method Phaser.Point#dot + * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point. + * @return {number} The result. + */ + dot: function (a) { + + return ((this.x * a.x) + (this.y * a.y)); + + }, + + /** + * The cross product of this and another Point object. + * + * @method Phaser.Point#cross + * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point. + * @return {number} The result. + */ + cross: function (a) { + + return ((this.x * a.y) - (this.y * a.x)); + + }, + + /** + * Make this Point perpendicular (90 degrees rotation) + * + * @method Phaser.Point#perp + * @return {Phaser.Point} This Point object. + */ + perp: function () { + + return this.setTo(-this.y, this.x); + + }, + + /** + * Make this Point perpendicular (-90 degrees rotation) + * + * @method Phaser.Point#rperp + * @return {Phaser.Point} This Point object. + */ + rperp: function () { + + return this.setTo(this.y, -this.x); + + }, + + /** + * Right-hand normalize (make unit length) this Point. + * + * @method Phaser.Point#normalRightHand + * @return {Phaser.Point} This Point object. + */ + normalRightHand: function () { + + return this.setTo(this.y * -1, this.x); + + }, + + /** + * Math.floor() both the x and y properties of this Point. + * + * @method Phaser.Point#floor + * @return {Phaser.Point} This Point object. + */ + floor: function () { + + return this.setTo(Math.floor(this.x), Math.floor(this.y)); + + }, + + /** + * Math.ceil() both the x and y properties of this Point. + * + * @method Phaser.Point#ceil + * @return {Phaser.Point} This Point object. + */ + ceil: function () { + + return this.setTo(Math.ceil(this.x), Math.ceil(this.y)); + + }, + + /** + * Math.round() both the x and y properties of this Point. + * + * @method Phaser.Point#round + * @return {Phaser.Point} This Point object. + */ + round: function () { + + return this.setTo(Math.round(this.x), Math.round(this.y)); + + }, + + /** + * Returns a string representation of this object. + * + * @method Phaser.Point#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; + + } + +}; + +Phaser.Point.prototype.constructor = Phaser.Point; + +/** +* Adds the coordinates of two points together to create a new point. +* +* @method Phaser.Point.add +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.add = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x + b.x; + out.y = a.y + b.y; + + return out; + +}; + +/** +* Subtracts the coordinates of two points to create a new point. +* +* @method Phaser.Point.subtract +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.subtract = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x - b.x; + out.y = a.y - b.y; + + return out; + +}; + +/** +* Multiplies the coordinates of two points to create a new point. +* +* @method Phaser.Point.multiply +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiply = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x * b.x; + out.y = a.y * b.y; + + return out; + +}; + +/** +* Divides the coordinates of two points to create a new point. +* +* @method Phaser.Point.divide +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.divide = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x / b.x; + out.y = a.y / b.y; + + return out; + +}; + +/** +* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. +* +* @method Phaser.Point.equals +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {boolean} A value of true if the Points are equal, otherwise false. +*/ +Phaser.Point.equals = function (a, b) { + + return a.x === b.x && a.y === b.y; + +}; + +Phaser.Point.equalsXY = function (a, x, y) { + + return a.x === x && a.y === y; + +}; + +Phaser.Point.fuzzyEquals = function (a, b, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, b.x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, b.y, epsilon); + +}; + +Phaser.Point.fuzzyEqualsXY = function (a, x, y, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, y, epsilon); + +}; + +/** +* Returns the angle between two Point objects. +* +* @method Phaser.Point.angle +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {number} The angle, where b is the vertex. Within [-pi, pi]. +*/ +Phaser.Point.angle = function (a, b) { + + return Math.atan2(a.y - b.y, a.x - b.x); + +}; + +/** +* Creates a negative Point. +* +* @method Phaser.Point.negative +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.negative = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.x, -a.y); + +}; + +/** +* Adds two 2D Points together and multiplies the result by the given scalar. +* +* @method Phaser.Point.multiplyAdd +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} s - The scaling value. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiplyAdd = function (a, b, s, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + b.x * s, a.y + b.y * s); + +}; + +/** +* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. +* +* @method Phaser.Point.interpolate +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.interpolate = function (a, b, f, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f); + +}; + +/** +* Return a perpendicular vector (90 degrees rotation) +* +* @method Phaser.Point.perp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.perp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.y, a.x); + +}; + +/** +* Return a perpendicular vector (-90 degrees rotation) +* +* @method Phaser.Point.rperp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.rperp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y, -a.x); + +}; + +/** +* Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). +* +* @method Phaser.Point.distance +* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. +* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. +* @param {boolean} [round=false] - Round the distance to the nearest integer. +* @return {number} The distance between this Point object and the destination Point object. +*/ +Phaser.Point.distance = function (a, b, round) { + + var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y); + return round ? Math.round(distance) : distance; + +}; + +/** +* Project two Points onto another Point. +* +* @method Phaser.Point.project +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.project = function (a, b, out) { + + if (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; + +}; + +/** +* Project two Points onto a Point of unit length. +* +* @method Phaser.Point.projectUnit +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.projectUnit = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var amt = a.dot(b); + + if (amt !== 0) + { + out.setTo(amt * b.x, amt * b.y); + } + + return out; + +}; + +/** +* Right-hand normalize (make unit length) a Point. +* +* @method Phaser.Point.normalRightHand +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalRightHand = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y * -1, a.x); + +}; + +/** +* Normalize (make unit length) a Point. +* +* @method Phaser.Point.normalize +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalize = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var m = a.getMagnitude(); + + if (m !== 0) + { + out.setTo(a.x / m, a.y / m); + } + + return out; + +}; + +/** +* Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by +* the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument +* is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. +* +* The distance allows you to specify a distance constraint for the rotation between the point and the +* coordinates. If none is given the distance between the two is calculated and used. +* +* @method Phaser.Point.rotate +* @param {Phaser.Point} a - The Point object to rotate. +* @param {number} x - The x coordinate of the anchor point +* @param {number} y - The y coordinate of the anchor point +* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {number} [distance] - An optional distance constraint between the Point and the anchor. +* @return {Phaser.Point} The modified point object. +*/ +Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) { + + if (asDegrees) { angle = Phaser.Math.degToRad(angle); } + + if (distance === undefined) + { + a.subtract(x, y); + + var s = Math.sin(angle); + var c = Math.cos(angle); + + var tx = c * a.x - s * a.y; + var ty = s * a.x + c * a.y; + + a.x = tx + x; + a.y = ty + y; + } + else + { + var t = angle + Math.atan2(a.y - y, a.x - x); + a.x = x + distance * Math.cos(t); + a.y = y + distance * Math.sin(t); + } + + return a; + +}; + +/** +* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. +* +* @method Phaser.Point.centroid +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.centroid = function (points, out) { + + if (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 < pointslength; i++) + { + Phaser.Point.add(out, points[i], out); + } + + out.divide(pointslength, pointslength); + + return out; + +}; + +/** +* Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. +* If the object doesn't contain those properties a Point with x/y of zero will be returned. +* +* @method Phaser.Point.parse +* @static +* @param {object} obj - The object to parse. +* @param {string} [xProp='x'] - The property used to set the Point.x value. +* @param {string} [yProp='y'] - The property used to set the Point.y value. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.parse = function(obj, xProp, yProp) { + + xProp = xProp || 'x'; + yProp = yProp || 'y'; + + var point = new Phaser.Point(); + + if (obj[xProp]) + { + point.x = parseInt(obj[xProp], 10); + } + + if (obj[yProp]) + { + point.y = parseInt(obj[yProp], 10); + } + + return point; + +}; + +/** + * Tests a Point or Point-like object. + * + * @method Phaser.Point.isPoint + * @static + * @return {boolean} - True if the object has numeric x and y properties. + */ +Phaser.Point.isPoint = function(obj) { + + return (obj != null) && (typeof obj.x === 'number') && (typeof obj.y === 'number'); + +}; + +/** +* Sets the `x` and `y` values of an object and returns the object. +* +* @method Phaser.Point#set +* @static +* @param {object} obj - An object with numeric x and y properties. +* @param {number} x - The x value. +* @param {number} [y] - The y value. If not given the x value will be used in its place. +* @return {object} The object. Useful for chaining method calls. +*/ +Phaser.Point.set = function(obj, x, y) { + + obj.x = x || 0; + obj.y = y || ( (y !== 0) ? obj.x : 0 ); + + return obj; + +}; + +/** +* Sorts an array of points in a clockwise direction, relative to a reference point. +* +* The sort is clockwise relative to the display, starting from a 12 o'clock position. +* (In the Cartesian plane, it is anticlockwise, starting from the -y direction.) +* +* Example sequence: (0, -1), (1, 0), (0, 1), (-1, 0) +* +* @method Phaser.Point#sortClockwise +* @static +* @param {array} points - An array of Points or point-like objects (e.g., sprites). +* @param {object|Phaser.Point} [center] - The reference point. If omitted, the {@link #centroid} (midpoint) of the points is used. +* @return {array} The sorted array. +*/ +Phaser.Point.sortClockwise = function(points, center) { + + // Adapted from (ciamej) + + if (!center) + { + center = this.centroid(points); + } + + var cx = center.x; + var cy = center.y; + + var sort = function(a, b) { + if (a.x - cx >= 0 && b.x - cx < 0) + { + return -1; + } + + if (a.x - cx < 0 && b.x - cx >= 0) + { + return 1; + } + + if (a.x - cx === 0 && b.x - cx === 0) + { + if (a.y - cy >= 0 || b.y - cy >= 0) + { + return (a.y > b.y) ? 1 : -1; + } + + return (b.y > a.y) ? 1 : -1; + } + + // Compute the cross product of vectors (center -> a) * (center -> b) + var det = (a.x - cx) * -(b.y - cy) - (b.x - cx) * -(a.y - cy); + + if (det < 0) + { + return -1; + } + + if (det > 0) + { + return 1; + } + + // Points a and b are on the same line from the center + // Check which point is closer to the center + var d1 = (a.x - cx) * (a.x - cx) + (a.y - cy) * (a.y - cy); + var d2 = (b.x - cx) * (b.x - cx) + (b.y - cy) * (b.y - cy); + + return (d1 > d2) ? -1 : 1; + }; + + return points.sort(sort); + +}; + + +// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Point = Phaser.Point; + +/** +* @author Richard Davey +* @author Adrien Brault +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Polygon. +* +* The points can be set from a variety of formats: +* +* - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` +* - An array of objects with public x/y properties: `[obj1, obj2, ...]` +* - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` +* - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` +* - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` +* - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` +* +* @class Phaser.Polygon +* @constructor +* @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. +*/ +Phaser.Polygon = function () { + + /** + * @property {number} area - The area of this Polygon. + */ + this.area = 0; + + /** + * @property {array} _points - An array of Points that make up this Polygon. + * @private + */ + this._points = []; + + if (arguments.length > 0) + { + this.setTo.apply(this, arguments); + } + + /** + * @property {boolean} closed - Is the Polygon closed or not? + */ + this.closed = true; + + /** + * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ? + */ + this.flattened = false; + + /** + * @property {number} type - The base object type. + */ + this.type = Phaser.POLYGON; + +}; + +Phaser.Polygon.prototype = { + + /** + * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] + * + * @method Phaser.Polygon#toNumberArray + * @param {array} [output] - The array to append the points to. If not specified a new array will be created. + * @return {array} The flattened array. + */ + toNumberArray: function (output) { + + if (output === undefined) { output = []; } + + for (var i = 0; i < this._points.length; i++) + { + if (typeof this._points[i] === 'number') + { + output.push(this._points[i]); + output.push(this._points[i + 1]); + i++; + } + else + { + output.push(this._points[i].x); + output.push(this._points[i].y); + } + } + + return output; + + }, + + /** + * Flattens this Polygon so the points are a sequence of numbers. + * Any Point objects found are removed and replaced with two numbers. + * Also sets the Polygon.flattened property to `true`. + * + * @method Phaser.Polygon#flatten + * @return {Phaser.Polygon} This Polygon object + */ + flatten: function () { + + this._points = this.toNumberArray(); + + this.flattened = true; + + return this; + + }, + + /** + * Creates a copy of the given Polygon. + * This is a deep clone, the resulting copy contains new Phaser.Point objects + * + * @method Phaser.Polygon#clone + * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created. + * @return {Phaser.Polygon} The cloned (`output`) polygon object. + */ + clone: function (output) { + + var points = this._points.slice(); + + if (output === undefined || output === null) + { + output = new Phaser.Polygon(points); + } + else + { + output.setTo(points); + } + + return output; + + }, + + /** + * Checks whether the x and y coordinates are contained within this polygon. + * + * @method Phaser.Polygon#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this polygon, otherwise false. + */ + contains: function (x, y) { + + // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva + + var inside = false; + + if (this.flattened) + { + for (var i = -2, j = this._points.length - 2; (i += 2) < this._points.length; j = i) + { + var ix = this._points[i]; + var iy = this._points[i + 1]; + + var jx = this._points[j]; + var jy = this._points[j + 1]; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + + } + else + { + for (var i = -1, j = this._points.length - 1; ++i < this._points.length; j = i) + { + var ix = this._points[i].x; + var iy = this._points[i].y; + + var jx = this._points[j].x; + var jy = this._points[j].y; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + } + + return inside; + + }, + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` + * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` + * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` + * + * `setTo` may also be called without any arguments to remove all points. + * + * @method Phaser.Polygon#setTo + * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. + * @return {Phaser.Polygon} This Polygon object + */ + setTo: function (points) { + + this.area = 0; + this._points = []; + + if (arguments.length > 0) + { + // If points isn't an array, use arguments as the array + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments); + } + + var y0 = Number.MAX_VALUE; + + // Allows for mixed-type arguments + for (var i = 0, len = points.length; i < len; i++) + { + if (typeof points[i] === 'number') + { + var p = new PIXI.Point(points[i], points[i + 1]); + i++; + } + else if (Array.isArray(points[i])) + { + var p = new PIXI.Point(points[i][0], points[i][1]); + } + else + { + var p = new PIXI.Point(points[i].x, points[i].y); + } + + this._points.push(p); + + // Lowest boundary + if (p.y < y0) + { + y0 = p.y; + } + } + + this.calculateArea(y0); + } + + return this; + + }, + + /** + * Calcuates the area of the Polygon. This is available in the property Polygon.area + * + * @method Phaser.Polygon#calculateArea + * @private + * @param {number} y0 - The lowest boundary + * @return {number} The area of the Polygon. + */ + calculateArea: function (y0) { + + var p1; + var p2; + var avgHeight; + var width; + + for (var i = 0, len = this._points.length; i < len; i++) + { + p1 = this._points[i]; + + if (i === len - 1) + { + p2 = this._points[0]; + } + else + { + p2 = this._points[i + 1]; + } + + avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2; + width = p1.x - p2.x; + this.area += avgHeight * width; + } + + return this.area; + + } + +}; + +Phaser.Polygon.prototype.constructor = Phaser.Polygon; + +/** +* The points of this polygon. +* +* You can modify these with {@link Phaser.Polygon#setTo setTo}. +* +* @name Phaser.Polygon#points +* @property {Phaser.Point[]} points - The array of vertex points. +* @readonly +*/ +Object.defineProperty(Phaser.Polygon.prototype, 'points', { + + get: function() { + return this._points; + } + +}); + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Polygon = Phaser.Polygon; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. +* If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. +* +* @class Phaser.Rectangle +* @constructor +* @param {number} x - The x coordinate of the top-left corner of the Rectangle. +* @param {number} y - The y coordinate of the top-left corner of the Rectangle. +* @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. +*/ +Phaser.Rectangle = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.RECTANGLE; + +}; + +Phaser.Rectangle.prototype = { + + /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method Phaser.Rectangle#offset + * @param {number} dx - Moves the x value of the Rectangle object by this amount. + * @param {number} dy - Moves the y value of the Rectangle object by this amount. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Rectangle#offsetPoint + * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offsetPoint: function (point) { + + return this.offset(point.x, point.y); + + }, + + /** + * Sets the members of Rectangle to the specified values. + * @method Phaser.Rectangle#setTo + * @param {number} x - The x coordinate of the top-left corner of the Rectangle. + * @param {number} y - The y coordinate of the top-left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Scales the width and height of this Rectangle by the given amounts. + * + * @method Phaser.Rectangle#scale + * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. + * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. + * @return {Phaser.Rectangle} This Rectangle object + */ + scale: function (x, y) { + + if (y === undefined) { y = x; } + + this.width *= x; + this.height *= y; + + return this; + + }, + + /** + * Centers this Rectangle so that the center coordinates match the given x and y values. + * + * @method Phaser.Rectangle#centerOn + * @param {number} x - The x coordinate to place the center of the Rectangle at. + * @param {number} y - The y coordinate to place the center of the Rectangle at. + * @return {Phaser.Rectangle} This Rectangle object + */ + centerOn: function (x, y) { + + this.centerX = x; + this.centerY = y; + + return this; + + }, + + /** + * Runs Math.floor() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#floor + */ + floor: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + + }, + + /** + * Runs Math.floor() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#floorAll + */ + floorAll: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.width = Math.floor(this.width); + this.height = Math.floor(this.height); + + }, + + /** + * Runs Math.ceil() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#ceil + */ + ceil: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + + }, + + /** + * Runs Math.ceil() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#ceilAll + */ + ceilAll: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.width = Math.ceil(this.width); + this.height = Math.ceil(this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the left, top, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFromBounds + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFromBounds: function(source) { + + return this.setTo(source.left, source.top, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Rectangle to any given object. + * @method Phaser.Rectangle#copyTo + * @param {any} source - The object to copy to. + * @return {object} This object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method Phaser.Rectangle#inflate + * @param {number} dx - The amount to be added to the left side of the Rectangle. + * @param {number} dy - The amount to be added to the bottom side of the Rectangle. + * @return {Phaser.Rectangle} This Rectangle object. + */ + inflate: function (dx, dy) { + + return Phaser.Rectangle.inflate(this, dx, dy); + + }, + + /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method Phaser.Rectangle#size + * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object. + */ + size: function (output) { + + return Phaser.Rectangle.size(this, output); + + }, + + /** + * Resize the Rectangle by providing a new width and height. + * The x and y positions remain unchanged. + * + * @method Phaser.Rectangle#resize + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method Phaser.Rectangle#clone + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ + clone: function (output) { + + return Phaser.Rectangle.clone(this, output); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method Phaser.Rectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + contains: function (x, y) { + + return Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method Phaser.Rectangle#containsRect + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + containsRect: function (b) { + + return Phaser.Rectangle.containsRect(b, this); + + }, + + /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method Phaser.Rectangle#equals + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + */ + equals: function (b) { + + return Phaser.Rectangle.equals(this, b); + + }, + + /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method Phaser.Rectangle#intersection + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ + intersection: function (b, out) { + + return Phaser.Rectangle.intersection(this, b, out); + + }, + + /** + * Determines whether this Rectangle and another given Rectangle intersect with each other. + * This method checks the x, y, width, and height properties of the two Rectangles. + * + * @method Phaser.Rectangle#intersects + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + */ + intersects: function (b) { + + return Phaser.Rectangle.intersects(this, b); + + }, + + /** + * Determines whether the coordinates given intersects (overlaps) with this Rectangle. + * + * @method Phaser.Rectangle#intersectsRaw + * @param {number} left - The x coordinate of the left of the area. + * @param {number} right - The right coordinate of the area. + * @param {number} top - The y coordinate of the area. + * @param {number} bottom - The bottom coordinate of the area. + * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 + * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + */ + intersectsRaw: function (left, right, top, bottom, tolerance) { + + return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance); + + }, + + /** + * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. + * @method Phaser.Rectangle#union + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ + union: function (b, out) { + + return Phaser.Rectangle.union(this, b, out); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Rectangle. + * + * @method Phaser.Rectangle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = this.randomX; + out.y = this.randomY; + + return out; + + }, + + /** + * Returns a point based on the given position constant, which can be one of: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * This method returns the same values as calling Rectangle.bottomLeft, etc, but those + * calls always create a new Point object, where-as this one allows you to use your own. + * + * @method Phaser.Rectangle#getPoint + * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. + * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the point in its `x` and `y` properties. + */ + getPoint: function (position, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + return out.set(this.x, this.y); + + case Phaser.TOP_CENTER: + return out.set(this.centerX, this.y); + + case Phaser.TOP_RIGHT: + return out.set(this.right, this.y); + + case Phaser.LEFT_CENTER: + return out.set(this.x, this.centerY); + + case Phaser.CENTER: + return out.set(this.centerX, this.centerY); + + case Phaser.RIGHT_CENTER: + return out.set(this.right, this.centerY); + + case Phaser.BOTTOM_LEFT: + return out.set(this.x, this.bottom); + + case Phaser.BOTTOM_CENTER: + return out.set(this.centerX, this.bottom); + + case Phaser.BOTTOM_RIGHT: + return out.set(this.right, this.bottom); + } + + }, + + /** + * Creates or positions four {@link Phaser.Line} lines representing the Rectangle's sides. + * + * @method Phaser.Rectangle#sides + * @param {Phaser.Line} [top] + * @param {Phaser.Line} [right] + * @param {Phaser.Line} [bottom] + * @param {Phaser.Line} [left] + * @return {?Phaser.Line[]} - An array containing four lines (if no arguments were given), or null. + */ + sides: function (top, right, bottom, left) { + + if (!arguments.length) { + top = new Phaser.Line(); + right = new Phaser.Line(); + bottom = new Phaser.Line(); + left = new Phaser.Line(); + } + + var x1 = this.x; + var y1 = this.y; + var x2 = this.right; + var y2 = this.bottom; + + top.setTo(x1, y1, x2, y1); + right.setTo(x2, y1, x2, y2); + bottom.setTo(x1, y2, x2, y2); + left.setTo(x1, y1, x1, y2); + + if (!arguments.length) { + return [top, right, bottom, left]; + } + + return null; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Rectangle#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + + } + +}; + +/** +* @name Phaser.Rectangle#halfWidth +* @property {number} halfWidth - Half of the width of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", { + + get: function () { + return Math.round(this.width / 2); + } + +}); + +/** +* @name Phaser.Rectangle#halfHeight +* @property {number} halfHeight - Half of the height of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", { + + get: function () { + return Math.round(this.height / 2); + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. +* @name Phaser.Rectangle#bottom +* @property {number} bottom - The sum of the y and height properties. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value <= this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + + } + +}); + +/** +* The location of the Rectangles bottom left corner as a Point object. +* @name Phaser.Rectangle#bottomLeft +* @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", { + + get: function () { + return new Phaser.Point(this.x, this.bottom); + }, + + set: function (value) { + this.x = value.x; + this.bottom = value.y; + } + +}); + +/** +* The location of the Rectangles bottom right corner as a Point object. +* @name Phaser.Rectangle#bottomRight +* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", { + + get: function () { + return new Phaser.Point(this.right, this.bottom); + }, + + set: function (value) { + this.right = value.x; + this.bottom = value.y; + } + +}); + +/** +* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. +* @name Phaser.Rectangle#left +* @property {number} left - The x coordinate of the left of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + if (value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + } + +}); + +/** +* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. +* @name Phaser.Rectangle#right +* @property {number} right - The sum of the x and width properties. +*/ +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 = value - this.x; + } + } + +}); + +/** +* The volume of the Rectangle derived from width * height. +* @name Phaser.Rectangle#volume +* @property {number} volume - The volume of the Rectangle derived from width * height. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "volume", { + + get: function () { + return this.width * this.height; + } + +}); + +/** +* The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @name Phaser.Rectangle#perimeter +* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", { + + get: function () { + return (this.width * 2) + (this.height * 2); + } + +}); + +/** +* The x coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerX +* @property {number} centerX - The x coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerX", { + + get: function () { + return this.x + this.halfWidth; + }, + + set: function (value) { + this.x = value - this.halfWidth; + } + +}); + +/** +* The y coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerY +* @property {number} centerY - The y coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerY", { + + get: function () { + return this.y + this.halfHeight; + }, + + set: function (value) { + this.y = value - this.halfHeight; + } + +}); + +/** +* A random value between the left and right values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomX +* @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomX", { + + get: function () { + + return this.x + (Math.random() * this.width); + + } + +}); + +/** +* A random value between the top and bottom values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomY +* @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomY", { + + get: function () { + + return this.y + (Math.random() * this.height); + + } + +}); + +/** +* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. +* However it does affect the height property, whereas changing the y value does not affect the height property. +* @name Phaser.Rectangle#top +* @property {number} top - The y coordinate of the top of the Rectangle. +*/ +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); + } + } + +}); + +/** +* The location of the Rectangles top left corner as a Point object. +* @name Phaser.Rectangle#topLeft +* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. +*/ +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; + } + +}); + +/** +* The location of the Rectangles top right corner as a Point object. +* @name Phaser.Rectangle#topRight +* @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "topRight", { + + get: function () { + return new Phaser.Point(this.x + this.width, this.y); + }, + + set: function (value) { + this.right = value.x; + this.y = value.y; + } + +}); + +/** +* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. +* If set to true then all of the Rectangle properties are set to 0. +* @name Phaser.Rectangle#empty +* @property {boolean} empty - Gets or sets the Rectangles empty state. +*/ +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; + +/** +* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. +* @method Phaser.Rectangle.inflate +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} dx - The amount to be added to the left side of the Rectangle. +* @param {number} dy - The amount to be added to the bottom side of the Rectangle. +* @return {Phaser.Rectangle} This Rectangle object. +*/ +Phaser.Rectangle.inflate = function (a, dx, dy) { + + a.x -= dx; + a.width += 2 * dx; + a.y -= dy; + a.height += 2 * dy; + + return a; + +}; + +/** +* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. +* @method Phaser.Rectangle.inflatePoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. +* @return {Phaser.Rectangle} The Rectangle object. +*/ +Phaser.Rectangle.inflatePoint = function (a, point) { + + return Phaser.Rectangle.inflate(a, point.x, point.y); + +}; + +/** +* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. +* @method Phaser.Rectangle.size +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. +* @return {Phaser.Point} The size of the Rectangle object +*/ +Phaser.Rectangle.size = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(a.width, a.height); + } + else + { + output.setTo(a.width, a.height); + } + + return output; + +}; + +/** +* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. +* @method Phaser.Rectangle.clone +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.clone = function (a, output) { + + if (output === undefined || output === null) + { + 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; + +}; + +/** +* Returns a new Rectangle object with the same values for the left, top, width, and height properties as the original object. +* @method Phaser.Rectangle.createFromBounds +* @param {any} a - An object with `left`, `top`, `width`, and `height` properties. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.createFromBounds = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Rectangle(a.x, a.y, a.width, a.height); + } + + return output.copyFromBounds(a); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by this Rectangle object. +* @method Phaser.Rectangle.contains +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +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); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by the given raw values. +* @method Phaser.Rectangle.containsRaw +* @param {number} rx - The x coordinate of the top left of the area. +* @param {number} ry - The y coordinate of the top left of the area. +* @param {number} rw - The width of the area. +* @param {number} rh - The height of the area. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) { + + return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh)); + +}; + +/** +* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. +* @method Phaser.Rectangle.containsPoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsPoint = function (a, point) { + + return Phaser.Rectangle.contains(a, point.x, point.y); + +}; + +/** +* Determines whether the first Rectangle object is fully contained within the second Rectangle object. +* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. +* @method Phaser.Rectangle.containsRect +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRect = function (a, b) { + + // If the given rect has a larger volume than this one then it can never contain it + if (a.volume > b.volume) + { + return false; + } + + return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom); + +}; + +/** +* Determines whether the two Rectangles are equal. +* This method compares the x, y, width and height properties of each Rectangle. +* @method Phaser.Rectangle.equals +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. +*/ +Phaser.Rectangle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height); + +}; + +/** +* Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. +* @method Phaser.Rectangle.sameDimensions +* @param {Rectangle-like} a - The first Rectangle object. +* @param {Rectangle-like} b - The second Rectangle object. +* @return {boolean} True if the object have equivalent values for the width and height properties. +*/ +Phaser.Rectangle.sameDimensions = function (a, b) { + + return (a.width === b.width && a.height === b.height); + +}; + +/** +* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. +* @method Phaser.Rectangle.intersection +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. +*/ +Phaser.Rectangle.intersection = function (a, b, output) { + + if (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; + +}; + +/** +* Determines whether the two Rectangles intersect with each other. +* This method checks the x, y, width, and height properties of the Rectangles. +* @method Phaser.Rectangle.intersects +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. +*/ +Phaser.Rectangle.intersects = function (a, b) { + + if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) + { + return false; + } + + return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom); + +}; + +/** +* Determines whether the object specified intersects (overlaps) with the given values. +* @method Phaser.Rectangle.intersectsRaw +* @param {number} left - The x coordinate of the left of the area. +* @param {number} right - The right coordinate of the area. +* @param {number} top - The y coordinate of the area. +* @param {number} bottom - The bottom coordinate of the area. +* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 +* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. +*/ +Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) { + + if (tolerance === undefined) { tolerance = 0; } + + return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); + +}; + +/** +* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. +* @method Phaser.Rectangle.union +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. +*/ +Phaser.Rectangle.union = function (a, b, output) { + + if (output === undefined) + { + output = new Phaser.Rectangle(); + } + + return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top)); + +}; + +/** +* Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. +* +* @method Phaser.Rectangle#aabb +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. +* @return {Phaser.Rectangle} The new Rectangle object. +* @static +*/ +Phaser.Rectangle.aabb = function(points, out) { + + if (out === undefined) { + out = new Phaser.Rectangle(); + } + + var xMax = Number.NEGATIVE_INFINITY, + xMin = Number.POSITIVE_INFINITY, + yMax = Number.NEGATIVE_INFINITY, + yMin = Number.POSITIVE_INFINITY; + + points.forEach(function(point) { + if (point.x > xMax) { + xMax = point.x; + } + if (point.x < xMin) { + xMin = point.x; + } + + if (point.y > yMax) { + yMax = point.y; + } + if (point.y < yMin) { + yMin = point.y; + } + }); + + out.setTo(xMin, yMin, xMax - xMin, yMax - yMin); + + return out; +}; + +// Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Rectangle = Phaser.Rectangle; +PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0); + +/** +* @author Mat Groves http://matgroves.com/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Rounded Rectangle object is an area defined by its position and has nice rounded corners, +* as indicated by its top-left corner point (x, y) and by its width and its height. +* +* @class Phaser.RoundedRectangle +* @constructor +* @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle. +* @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle. +* @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value. +* @param {number} [radius=20] - Controls the radius of the rounded corners. +*/ +Phaser.RoundedRectangle = function(x, y, width, height, radius) +{ + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + if (radius === undefined) { radius = 20; } + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} radius - The radius of the rounded corners. + */ + this.radius = radius || 20; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROUNDEDRECTANGLE; +}; + +Phaser.RoundedRectangle.prototype = { + + /** + * Returns a new RoundedRectangle object with the same values for the x, y, width, height and + * radius properties as this RoundedRectangle object. + * + * @method Phaser.RoundedRectangle#clone + * @return {Phaser.RoundedRectangle} + */ + clone: function () { + + return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. + * + * @method Phaser.RoundedRectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. + */ + 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; + + } + +}; + +Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle; + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.RoundedRectangle = Phaser.RoundedRectangle; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. +* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y +* +* @class Phaser.Camera +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera +* @param {number} x - Position of the camera on the X axis +* @param {number} y - Position of the camera on the Y axis +* @param {number} width - The width of the view rectangle +* @param {number} height - The height of the view rectangle +*/ +Phaser.Camera = function (game, id, x, y, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + */ + this.world = game.world; + + /** + * @property {number} id - Reserved for future multiple camera set-ups. + * @default + */ + this.id = 0; + + /** + * Camera view. + * The view into the world we wish to render (by default the game dimensions). + * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. + * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. + * @property {Phaser.Rectangle} view + */ + this.view = new Phaser.Rectangle(x, y, width, height); + + /** + * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. + * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound + * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. + * + * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. + */ + this.bounds = new Phaser.Rectangle(x, y, width, height); + + /** + * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move. + */ + this.deadzone = null; + + /** + * @property {boolean} visible - Whether this camera is visible or not. + * @default + */ + this.visible = true; + + /** + * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. + * @default + */ + this.roundPx = true; + + /** + * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. + */ + this.atLimit = { x: false, y: false }; + + /** + * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. + * @default + */ + this.target = null; + + /** + * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot. + */ + this.displayObject = null; + + /** + * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot. + */ + this.scale = null; + + /** + * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. + * @readonly + */ + this.totalInView = 0; + + /** + * The linear interpolation value to use when following a target. + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * @property {Phaser.Point} lerp + * @default + */ + this.lerp = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes. + */ + this.onShakeComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes. + */ + this.onFlashComplete = new Phaser.Signal(); + + /** + * This signal is dispatched when the camera fade effect completes. + * When the fade effect completes you will be left with the screen black (or whatever + * color you faded to). In order to reset this call `Camera.resetFX`. This is called + * automatically when you change State. + * @property {Phaser.Signal} onFadeComplete + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * The Graphics object used to handle camera fx such as fade and flash. + * @property {Phaser.Graphics} fx + * @protected + */ + this.fx = null; + + /** + * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position. + * @private + */ + this._targetPosition = new Phaser.Point(); + + /** + * @property {number} edge - Edge property. + * @private + * @default + */ + this._edge = 0; + + /** + * @property {Phaser.Point} position - Current position of the camera in world. + * @private + * @default + */ + this._position = new Phaser.Point(); + + /** + * @property {Object} _shake - The shake effect container. + * @private + */ + this._shake = { + intensity: 0, + duration: 0, + horizontal: false, + vertical: false, + shakeBounds: true, + x: 0, + y: 0 + }; + + /** + * @property {number} _fxDuration - FX duration timer. + * @private + */ + this._fxDuration = 0; + + /** + * @property {number} _fxType - The FX type running. + * @private + */ + this._fxType = 0; + + /** + * @property {Phaser.Rectangle} + * @private + */ + this._fixedView = new Phaser.Rectangle(); + +}; + +/** +* A follow style that uses no deadzone. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_LOCKON = 0; + +/** +* A follow style that uses a tall, narrow deadzone (0.33 x 0.125) with a center slightly above the view center. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_PLATFORMER = 1; + +/** +* A follow style that uses a square deadzone (0.25 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN = 2; + +/** +* A follow style that uses a small square deadzone (0.125 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_BOTH = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_HORIZONTAL = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_VERTICAL = 6; + +/** +* @constant +* @type {boolean} +*/ +Phaser.Camera.ENABLE_FX = true; + +Phaser.Camera.prototype = { + + /** + * Called automatically by Phaser.World. + * + * @method Phaser.Camera#boot + * @private + */ + boot: function () { + + this.displayObject = this.game.world; + + this.scale = this.game.world.scale; + + this.game.camera = this; + + if (Phaser.Graphics && Phaser.Camera.ENABLE_FX) + { + this.fx = new Phaser.Graphics(this.game); + + this.game.stage.addChild(this.fx); + } + + }, + + /** + * Camera preUpdate. Sets the total view counter to zero. + * + * @method Phaser.Camera#preUpdate + */ + preUpdate: function () { + + this.totalInView = 0; + + }, + + /** + * Tell the camera which sprite to follow. + * + * You can set the follow type and a linear interpolation value. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. + * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. + * + * @method Phaser.Camera#follow + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything. + * @param {number} [style] - Leverage one of the existing {@link deadzone} presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + */ + follow: function (target, style, lerpX, lerpY) { + + if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; } + if (lerpX === undefined) { lerpX = 1; } + if (lerpY === undefined) { lerpY = 1; } + + this.target = target; + this.lerp.set(lerpX, lerpY); + + var helper; + + switch (style) { + + case Phaser.Camera.FOLLOW_PLATFORMER: + var w = this.width / 8; + var h = this.height / 3; + this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN: + helper = Math.max(this.width, this.height) / 4; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT: + helper = Math.max(this.width, this.height) / 8; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_LOCKON: + this.deadzone = null; + break; + + default: + this.deadzone = null; + break; + } + + }, + + /** + * Sets the Camera follow target to null, stopping it from following an object if it's doing so. + * + * @method Phaser.Camera#unfollow + */ + unfollow: function () { + + this.target = null; + + }, + + /** + * Move the camera focus on a display object instantly. + * @method Phaser.Camera#focusOn + * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. + */ + focusOn: function (displayObject) { + + this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight)); + + }, + + /** + * Move the camera focus on a location instantly. + * @method Phaser.Camera#focusOnXY + * @param {number} x - X position. + * @param {number} y - Y position. + */ + focusOnXY: function (x, y) { + + this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight)); + + }, + + /** + * This creates a camera shake effect. It works by applying a random amount of additional + * spacing on the x and y axis each frame. You can control the intensity and duration + * of the effect, and if it should effect both axis or just one. + * + * When the shake effect ends the signal Camera.onShakeComplete is dispatched. + * + * @method Phaser.Camera#shake + * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. + * @param {number} [duration=500] - The duration of the shake effect in milliseconds. + * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL. + * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?). + * @return {boolean} True if the shake effect was started, otherwise false. + */ + shake: function (intensity, duration, force, direction, shakeBounds) { + + if (intensity === undefined) { intensity = 0.05; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = true; } + if (direction === undefined) { direction = Phaser.Camera.SHAKE_BOTH; } + if (shakeBounds === undefined) { shakeBounds = true; } + + if (!force && this._shake.duration > 0) + { + // Can't reset an already running shake + return false; + } + + this._shake.intensity = intensity; + this._shake.duration = duration; + this._shake.shakeBounds = shakeBounds; + + this._shake.x = 0; + this._shake.y = 0; + + this._shake.horizontal = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_HORIZONTAL); + this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL); + + return true; + + }, + + /** + * This creates a camera flash effect. It works by filling the game with the solid fill + * color specified, and then fading it away to alpha 0 over the duration given. + * + * You can use this for things such as hit feedback effects. + * + * When the effect ends the signal Camera.onFlashComplete is dispatched. + * + * @method Phaser.Camera#flash + * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the flash effect in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the flash effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + flash: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0xffffff; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 1; + + this._fxDuration = duration; + this._fxType = 0; + + return true; + + }, + + /** + * This creates a camera fade effect. It works by filling the game with the + * color specified, over the duration given, ending with a solid fill. + * + * You can use this for things such as transitioning to a new scene. + * + * The game will be left 'filled' at the end of this effect, likely obscuring + * everything. In order to reset it you can call `Camera.resetFX` and it will clear the + * fade. Or you can call `Camera.flash` with the same color as the fade, and it will + * reverse the process, bringing the game back into view again. + * + * When the effect ends the signal Camera.onFadeComplete is dispatched. + * + * @method Phaser.Camera#fade + * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the fade in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the fade effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + fade: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0x000000; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 0; + + this._fxDuration = duration; + this._fxType = 1; + + return true; + + }, + + /** + * The camera update loop. This is called automatically by the core game loop. + * + * @method Phaser.Camera#update + * @protected + */ + update: function () { + + if (this._fxDuration > 0) + { + this.updateFX(); + } + + if (this._shake.duration > 0) + { + this.updateShake(); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + this._shake.x = Math.floor(this._shake.x); + this._shake.y = Math.floor(this._shake.y); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the camera flash and fade effects. + * + * @method Phaser.Camera#updateFX + * @private + */ + updateFX: function () { + + if (this._fxType === 0) + { + // flash + this.fx.alpha -= this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha <= 0) + { + this._fxDuration = 0; + this.fx.alpha = 0; + this.onFlashComplete.dispatch(); + } + } + else + { + // fade + this.fx.alpha += this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha >= 1) + { + this._fxDuration = 0; + this.fx.alpha = 1; + this.onFadeComplete.dispatch(); + } + } + + }, + + /** + * Update the camera shake effect. + * + * @method Phaser.Camera#updateShake + * @private + */ + updateShake: function () { + + this._shake.duration -= this.game.time.elapsedMS; + + if (this._shake.duration <= 0) + { + this.onShakeComplete.dispatch(); + this._shake.x = 0; + this._shake.y = 0; + } + else + { + if (this._shake.horizontal) + { + this._shake.x = this.game.rnd.frac() * this._shake.intensity * this.view.width * 2 - this._shake.intensity * this.view.width; + } + + if (this._shake.vertical) + { + this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height; + } + } + + }, + + /** + * Internal method that handles tracking a sprite. + * + * @method Phaser.Camera#updateTarget + * @private + */ + updateTarget: function () { + + this._targetPosition.x = this.view.x + this.target.worldPosition.x; + this._targetPosition.y = this.view.y + this.target.worldPosition.y; + + if (this.deadzone) + { + this._edge = this._targetPosition.x - this.view.x; + + if (this._edge < this.deadzone.left) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.left, this.lerp.x); + } + else if (this._edge > this.deadzone.right) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.right, this.lerp.x); + } + + this._edge = this._targetPosition.y - this.view.y; + + if (this._edge < this.deadzone.top) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.top, this.lerp.y); + } + else if (this._edge > this.deadzone.bottom) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.bottom, this.lerp.y); + } + } + else + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.view.halfWidth, this.lerp.x); + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.view.halfHeight, this.lerp.y); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the Camera bounds to match the game world. + * + * @method Phaser.Camera#setBoundsToWorld + */ + setBoundsToWorld: function () { + + if (this.bounds) + { + this.bounds.copyFrom(this.game.world.bounds); + } + + }, + + /** + * Method called to ensure the camera doesn't venture outside of the game world. + * Called automatically by Camera.update. + * + * @method Phaser.Camera#checkBounds + * @protected + */ + checkBounds: function () { + + this.atLimit.x = false; + this.atLimit.y = false; + + var vx = this.view.x + this._shake.x; + var vw = this.view.right + this._shake.x; + var vy = this.view.y + this._shake.y; + var vh = this.view.bottom + this._shake.y; + + // Make sure we didn't go outside the cameras bounds + if (vx <= this.bounds.x * this.scale.x) + { + this.atLimit.x = true; + this.view.x = this.bounds.x * this.scale.x; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + else if (vw >= this.bounds.right * this.scale.x) + { + this.atLimit.x = true; + this.view.x = (this.bounds.right * this.scale.x) - this.width; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + + if (vy <= this.bounds.top * this.scale.y) + { + this.atLimit.y = true; + this.view.y = this.bounds.top * this.scale.y; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + else if (vh >= this.bounds.bottom * this.scale.y) + { + this.atLimit.y = true; + this.view.y = (this.bounds.bottom * this.scale.y) - this.height; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + + }, + + /** + * A helper function to set both the X and Y properties of the camera at once + * without having to use game.camera.x and game.camera.y. + * + * @method Phaser.Camera#setPosition + * @param {number} x - X position. + * @param {number} y - Y position. + */ + setPosition: function (x, y) { + + this.view.x = x; + this.view.y = y; + + if (this.bounds) + { + this.checkBounds(); + } + + }, + + /** + * Sets the size of the view rectangle given the width and height in parameters. + * + * @method Phaser.Camera#setSize + * @param {number} width - The desired width. + * @param {number} height - The desired height. + */ + setSize: function (width, height) { + + this.view.width = width; + this.view.height = height; + + }, + + /** + * Resets the camera back to 0,0 and un-follows any object it may have been tracking. + * Also immediately resets any camera effects that may have been running such as + * shake, flash or fade. + * + * @method Phaser.Camera#reset + */ + reset: function () { + + this.target = null; + + this.view.x = 0; + this.view.y = 0; + + this._shake.duration = 0; + this._shake.x = 0; + this._shake.y = 0; + + this.resetFX(); + + }, + + /** + * Resets any active FX, such as a fade or flash and immediately clears it. + * Useful to calling after a fade in order to remove the fade from the Stage. + * + * @method Phaser.Camera#resetFX + */ + resetFX: function () { + + if (this.fx) + { + this.fx.clear(); + this.fx.alpha = 0; + } + + this._fxDuration = 0; + + } + +}; + +Phaser.Camera.prototype.constructor = Phaser.Camera; + +/** +* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#x +* @property {number} x - Gets or sets the cameras x position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "x", { + + get: function () { + + return this.view.x; + + }, + + set: function (value) { + + this.view.x = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#y +* @property {number} y - Gets or sets the cameras y position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "y", { + + get: function () { + + return this.view.y; + + }, + + set: function (value) { + + this.view.y = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras position. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#position +* @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object. +*/ +Object.defineProperty(Phaser.Camera.prototype, "position", { + + get: function () { + + this._position.set(this.view.x, this.view.y); + + return this._position; + + }, + + set: function (value) { + + if (typeof value.x !== "undefined") { this.view.x = value.x; } + if (typeof value.y !== "undefined") { this.view.y = value.y; } + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras width. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#width +* @property {number} width - Gets or sets the cameras width. +*/ +Object.defineProperty(Phaser.Camera.prototype, "width", { + + get: function () { + + return this.view.width; + + }, + + set: function (value) { + + this.view.width = value; + + } + +}); + +/** +* The Cameras height. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#height +* @property {number} height - Gets or sets the cameras height. +*/ +Object.defineProperty(Phaser.Camera.prototype, "height", { + + get: function () { + + return this.view.height; + + }, + + set: function (value) { + + this.view.height = value; + + } + +}); + + +/** +* The Cameras shake intensity. +* @name Phaser.Camera#shakeIntensity +* @property {number} shakeIntensity - Gets or sets the cameras shake intensity. +*/ +Object.defineProperty(Phaser.Camera.prototype, "shakeIntensity", { + + get: function () { + + return this._shake.intensity; + + }, + + set: function (value) { + + this._shake.intensity = value; + + } + +}); + + +/** + * Immobile {@link #view} rectangle. Its top-left is always (0, 0). You can use this align fixedToCamera objects. + * @name Phaser.Camera#fixedView + * @property {Phaser.Rectangle} fixedView + * @readonly + */ +Object.defineProperty(Phaser.Camera.prototype, "fixedView", { + + get: function () { + + this._fixedView.setTo(0, 0, this.view.width, this.view.height); + + return this._fixedView; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base State class which can be extended if you are creating your own game. +* It provides quick access to common functions such as the camera, cache, input, match, sound and more. +* +* #### Callbacks +* +* | start | preload | loaded | paused | stop | +* |-------|-------------|------------|--------------|----------| +* | init | | | | | +* | | preload | create | paused | | +* | | loadUpdate* | update* | pauseUpdate* | | +* | | | preRender* | | | +* | | loadRender* | render* | render* | | +* | | | | resumed | | +* | | | | | shutdown | +* +* Update and render calls (*) are repeated. +* +* If your State has a constructor, it will be invoked exactly once, during {@link {@link Phaser.StateManager#add}. +* +* @class Phaser.State +* @constructor +*/ +Phaser.State = function () { + + /** + * @property {Phaser.Game} game - This is a reference to the currently running Game. + */ + this.game = null; + + /** + * @property {string} key - The string based identifier given to the State when added into the State Manager. + */ + this.key = ''; + + /** + * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects. + */ + this.make = null; + + /** + * @property {Phaser.Camera} camera - A handy reference to World.camera. + */ + this.camera = null; + + /** + * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - A reference to the Input Manager. + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions. + */ + this.math = null; + + /** + * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. + */ + this.sound = null; + + /** + * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays. + */ + this.scale = null; + + /** + * @property {Phaser.Stage} stage - A reference to the Stage. + */ + this.stage = null; + + /** + * @property {Phaser.StateManager} stage - A reference to the State Manager, which controls state changes. + */ + this.state = null; + + /** + * @property {Phaser.Time} time - A reference to the game clock and timed events system. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - A reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. + */ + this.world = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. + */ + this.particles = null; + + /** + * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser. + */ + this.physics = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator. + */ + this.rnd = null; + +}; + +Phaser.State.prototype = { + + /** + * init is the very first function called when your State starts up. It's called before preload, create or anything else. + * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables + * or objects before the preloading starts. + * + * @method Phaser.State#init + * @param {...any} args - Any extra arguments passed to {@link Phaser.StateManager#start} or {@link Phaser.StateManager#restart}. + */ + init: function () { + }, + + /** + * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) + * You shouldn't create any objects in this method that require assets that you're also loading in this method, as + * they won't yet be available. + * + * @method Phaser.State#preload + * @param {Phaser.Game} game + */ + preload: function () { + }, + + /** + * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * + * @method Phaser.State#loadUpdate + * @param {Phaser.Game} game + */ + loadUpdate: function () { + }, + + /** + * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. + * + * @method Phaser.State#loadRender + * @param {Phaser.Game} game + */ + loadRender: function () { + }, + + /** + * create is called once preload has completed, this includes the loading of any assets from the Loader. + * If you don't have a preload method then create is the first method called in your State. + * + * @method Phaser.State#create + * @param {Phaser.Game} game + */ + create: function () { + }, + + /** + * The update method is left empty for your own use. + * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. + * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. + * + * @method Phaser.State#update + * @param {Phaser.Game} game + */ + update: function () { + }, + + /** + * The preRender method is called after all Game Objects have been updated, but before any rendering takes place. + * + * @method Phaser.State#preRender + * @param {Phaser.Game} game + * @param {number} elapsedTime + */ + preRender: function () { + }, + + /** + * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. + * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any + * final post-processing style effects here. Note that this happens before plugins postRender takes place. + * + * @method Phaser.State#render + * @param {Phaser.Game} game + */ + render: function () { + }, + + /** + * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. + * + * @method Phaser.State#resize + * @param {number} width + * @param {number} height + */ + resize: function () { + }, + + /** + * This method will be called if the core game loop is paused. + * + * @method Phaser.State#paused + * @param {Phaser.Game} game + */ + paused: function () { + }, + + /** + * This method will be called when the core game loop resumes from a paused state. + * + * @method Phaser.State#resumed + * @param {Phaser.Game} game + */ + resumed: function () { + }, + + /** + * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. + * + * @method Phaser.State#pauseUpdate + * @param {Phaser.Game} game + */ + pauseUpdate: function () { + }, + + /** + * This method will be called when the State is shutdown (i.e. you switch to another state from this one). + * + * @method Phaser.State#shutdown + * @param {Phaser.Game} game + */ + shutdown: function () { + } + +}; + +Phaser.State.prototype.constructor = Phaser.State; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The State Manager is responsible for loading, setting up and switching game states. +* +* @class Phaser.StateManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. +*/ +Phaser.StateManager = function (game, pendingState) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {object} states - The object containing Phaser.States. + */ + this.states = {}; + + /** + * @property {Phaser.State} _pendingState - The state to be switched to in the next frame. + * @private + */ + this._pendingState = null; + + if (typeof pendingState !== 'undefined' && pendingState !== null) + { + this._pendingState = pendingState; + } + + /** + * @property {boolean} _clearWorld - Clear the world when we switch state? + * @private + */ + this._clearWorld = false; + + /** + * @property {boolean} _clearCache - Clear the cache when we switch state? + * @private + */ + this._clearCache = false; + + /** + * @property {boolean} _created - Flag that sets if the State has been created or not. + * @private + */ + this._created = false; + + /** + * @property {any[]} _args - Temporary container when you pass vars from one State to another. + * @private + */ + this._args = []; + + /** + * @property {string} current - The current active State object. + * @default + */ + this.current = ''; + + /** + * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. + * + * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start + * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states + * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. + * + * The callback you specify is sent two parameters: the string based key of the new state, + * and the second parameter is the string based key of the old / previous state. + * + * @property {Phaser.Signal} onStateChange + */ + this.onStateChange = new Phaser.Signal(); + + /** + * @property {function} onInitCallback - This is called when the state is set as the active state. + * @default + */ + this.onInitCallback = null; + + /** + * @property {function} onPreloadCallback - This is called when the state starts to load assets. + * @default + */ + this.onPreloadCallback = null; + + /** + * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins. + * @default + */ + this.onCreateCallback = null; + + /** + * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). + * @default + */ + this.onUpdateCallback = null; + + /** + * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). + * @default + */ + this.onRenderCallback = null; + + /** + * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. + * @default + */ + this.onResizeCallback = null; + + /** + * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. + * @default + */ + this.onPreRenderCallback = null; + + /** + * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase. + * @default + */ + this.onLoadUpdateCallback = null; + + /** + * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase. + * @default + */ + this.onLoadRenderCallback = null; + + /** + * @property {function} onPausedCallback - This is called when the game is paused. + * @default + */ + this.onPausedCallback = null; + + /** + * @property {function} onResumedCallback - This is called when the game is resumed from a paused state. + * @default + */ + this.onResumedCallback = null; + + /** + * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused. + * @default + */ + this.onPauseUpdateCallback = null; + + /** + * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state). + * @default + */ + this.onShutDownCallback = null; + +}; + +Phaser.StateManager.prototype = { + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * @method Phaser.StateManager#boot + * @private + */ + boot: function () { + + this.game.onPause.add(this.pause, this); + this.game.onResume.add(this.resume, this); + + if (this._pendingState !== null && typeof this._pendingState !== 'string') + { + this.add('default', this._pendingState, true); + } + + }, + + /** + * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. + * + * The State can be any of + * + * - a plain JavaScript object containing at least one required callback (see {@link #checkState}) + * - an instance of {@link Phaser.State} + * - an instance of a class extending Phaser.State + * - a constructor function (class) + * + * If a function is given a new state object will be created by calling it, passing the current {@link Phaser.Game game} as the first argument. + * + * @method Phaser.StateManager#add + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + * @param {Phaser.State|object|function} state - The state you want to switch to. + * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it. + */ + add: function (key, state, autoStart) { + + if (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; + + }, + + /** + * Delete the given state. + * @method Phaser.StateManager#remove + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + */ + 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.onPreRenderCallback = null; + this.onRenderCallback = null; + this.onResizeCallback = null; + this.onPausedCallback = null; + this.onResumedCallback = null; + this.onPauseUpdateCallback = null; + } + + delete this.states[key]; + + }, + + /** + * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. + * + * @method Phaser.StateManager#start + * @param {string} key - The key of the state you want to start. + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one). + */ + start: function (key, clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + if (this.checkState(key)) + { + // Place the state in the queue. It will be started the next time the game loop begins. + this._pendingState = key; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 3) + { + this._args = Array.prototype.splice.call(arguments, 3); + } + } + + }, + + /** + * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. + * + * @method Phaser.StateManager#restart + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one. + */ + restart: function (clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + // Place the state in the queue. It will be started the next time the game loop starts. + this._pendingState = this.current; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 2) + { + this._args = Array.prototype.slice.call(arguments, 2); + } + + }, + + /** + * Used by onInit and onShutdown when those functions don't exist on the state + * @method Phaser.StateManager#dummy + * @private + */ + dummy: function () { + }, + + /** + * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. + * + * @method Phaser.StateManager#preUpdate + */ + preUpdate: function () { + + if (this._pendingState && this.game.isBooted) + { + var previousStateKey = this.current; + + // Already got a state running? + this.clearCurrentState(); + + this.setCurrentState(this._pendingState); + + this.onStateChange.dispatch(this.current, previousStateKey); + + if (this.current !== this._pendingState) + { + return; + } + else + { + this._pendingState = null; + } + + // If StateManager.start has been called from the init of a State that ALSO has a preload, then + // onPreloadCallback will be set, but must be ignored + if (this.onPreloadCallback) + { + this.game.load.reset(true); + this.onPreloadCallback.call(this.callbackContext, this.game); + + // Is the loader empty? + if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0) + { + this.loadComplete(); + } + else + { + // Start the loader going as we have something in the queue + this.game.load.start(); + } + } + else + { + // No init? Then there was nothing to load either + this.loadComplete(); + } + } + + }, + + /** + * This method clears the current State, calling its shutdown callback. The process also removes any active tweens, + * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. + * + * @method Phaser.StateManager#clearCurrentState + */ + clearCurrentState: function () { + + if (this.current) + { + if (this.onShutDownCallback) + { + 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(); + + this.game.scale.reset(this._clearWorld); + + if (this.game.debug) + { + this.game.debug.reset(); + } + + if (this._clearWorld) + { + this.game.world.shutdown(); + + if (this._clearCache) + { + this.game.cache.destroy(); + } + } + } + + }, + + /** + * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. + * + * @method Phaser.StateManager#checkState + * @param {string} key - The key of the state you want to check. + * @return {boolean} true if the State has the required functions, otherwise false. + */ + checkState: function (key) { + + var state = this.states[key]; + + if (state) + { + if (state.preload || state.create || state.update || state.render) + { + return true; + } + else + { + console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"); + return false; + } + } + else + { + console.warn("Phaser.StateManager - No state found with the key: " + key); + return false; + } + + }, + + /** + * Links game properties to the State given by the key. + * + * @method Phaser.StateManager#link + * @param {string} key - State key. + * @protected + */ + link: function (key) { + + var state = this.states[key]; + + state.game = this.game; + state.add = this.game.add; + state.make = this.game.make; + state.camera = this.game.camera; + state.cache = this.game.cache; + state.input = this.game.input; + state.load = this.game.load; + state.math = this.game.math; + state.sound = this.game.sound; + state.scale = this.game.scale; + state.state = this; + state.stage = this.game.stage; + state.time = this.game.time; + state.tweens = this.game.tweens; + state.world = this.game.world; + state.particles = this.game.particles; + state.rnd = this.game.rnd; + state.physics = this.game.physics; + state.key = key; + + }, + + /** + * Nulls all State level Phaser properties, including a reference to Game. + * + * @method Phaser.StateManager#unlink + * @param {string} key - State key. + * @protected + */ + unlink: function (key) { + + var state = this.states[key]; + + if (state) + { + state.game = null; + state.add = null; + state.make = null; + state.camera = null; + state.cache = null; + state.input = null; + state.load = null; + state.math = null; + state.sound = null; + state.scale = null; + state.state = null; + state.stage = null; + state.time = null; + state.tweens = null; + state.world = null; + state.particles = null; + state.rnd = null; + state.physics = null; + } + + }, + + /** + * Sets the current State. Should not be called directly (use StateManager.start) + * + * @method Phaser.StateManager#setCurrentState + * @param {string} key - State key. + * @private + */ + setCurrentState: function (key) { + + var state = this.states[key]; + + this.callbackContext = state; + + this.link(key); + + // Used when the state is set as being the current active state + this.onInitCallback = state['init'] || this.dummy; + + this.onPreloadCallback = state['preload'] || null; + this.onLoadRenderCallback = state['loadRender'] || null; + this.onLoadUpdateCallback = state['loadUpdate'] || null; + this.onCreateCallback = state['create'] || null; + this.onUpdateCallback = state['update'] || null; + this.onPreRenderCallback = state['preRender'] || null; + this.onRenderCallback = state['render'] || null; + this.onResizeCallback = state['resize'] || null; + this.onPausedCallback = state['paused'] || null; + this.onResumedCallback = state['resumed'] || null; + this.onPauseUpdateCallback = state['pauseUpdate'] || null; + + // Used when the state is no longer the current active state + this.onShutDownCallback = state['shutdown'] || this.dummy; + + // Reset the physics system, but not on the first state start + if (this.current !== '') + { + this.game.physics.reset(); + } + + this.current = key; + this._created = false; + + // At this point key and pendingState should equal each other + this.onInitCallback.apply(this.callbackContext, this._args); + + // If they no longer do then the init callback hit StateManager.start + if (key === this._pendingState) + { + this._args = []; + } + + this.game._kickstart = true; + + }, + + /** + * Gets the current State. + * + * @method Phaser.StateManager#getCurrentState + * @return {Phaser.State} + * @public + */ + getCurrentState: function() { + return this.states[this.current]; + }, + + /** + * @method Phaser.StateManager#loadComplete + * @protected + */ + loadComplete: function () { + + // Make sure to do load-update one last time before state is set to _created + if (this._created === false && this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + + if (this._created === false && this.onCreateCallback) + { + this._created = true; + this.onCreateCallback.call(this.callbackContext, this.game); + } + else + { + this._created = true; + } + + }, + + /** + * @method Phaser.StateManager#pause + * @protected + */ + pause: function () { + + if (this._created && this.onPausedCallback) + { + this.onPausedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#resume + * @protected + */ + resume: function () { + + if (this._created && this.onResumedCallback) + { + this.onResumedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#update + * @protected + */ + update: function () { + + if (this._created) + { + if (this.onUpdateCallback) + { + this.onUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#pauseUpdate + * @protected + */ + pauseUpdate: function () { + + if (this._created) + { + if (this.onPauseUpdateCallback) + { + this.onPauseUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#preRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + preRender: function (elapsedTime) { + + if (this._created && this.onPreRenderCallback) + { + this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime); + } + + }, + + /** + * @method Phaser.StateManager#resize + * @protected + */ + resize: function (width, height) { + + if (this.onResizeCallback) + { + this.onResizeCallback.call(this.callbackContext, width, height); + } + + }, + + /** + * @method Phaser.StateManager#render + * @protected + */ + render: function () { + + if (this._created) + { + if (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); + this.game.context.restore(); + } + else + { + this.onRenderCallback.call(this.callbackContext, this.game); + } + } + } + else + { + if (this.onLoadRenderCallback) + { + this.onLoadRenderCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. + * You don't recover from this without rebuilding the Phaser instance again. + * @method Phaser.StateManager#destroy + */ + destroy: function () { + + this._clearWorld = true; + this._clearCache = true; + + this.clearCurrentState(); + + 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; + this.current = ''; + + } + +}; + +Phaser.StateManager.prototype.constructor = Phaser.StateManager; + +/** +* @name Phaser.StateManager#created +* @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default). +* @readOnly +*/ +Object.defineProperty(Phaser.StateManager.prototype, "created", { + + get: function () { + + return this._created; + + } + +}); + +/** +* "It's like nailing jelly to a kitten" - Gary Penn +*/ + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Signals are what Phaser uses to handle events and event dispatching. +* You can listen for a Signal by binding a callback / function to it. +* This is done by using either `Signal.add` or `Signal.addOnce`. +* +* For example you can listen for a touch or click event from the Input Manager +* by using its `onDown` Signal: +* +* `game.input.onDown.add(function() { ... });` +* +* Rather than inline your function, you can pass a reference: +* +* `game.input.onDown.add(clicked, this);` +* `function clicked () { ... }` +* +* In this case the second argument (`this`) is the context in which your function should be called. +* +* Now every time the InputManager dispatches the `onDown` signal (or event), your function +* will be called. +* +* Multiple callbacks can be bound to the same signal. +* They're ordered first by their `priority` arguments and then by the order in which they were added. +* If a callback calls {@link #halt} or returns `false`, any remaining callbacks are skipped. +* +* Very often a Signal will send arguments to your function. +* This is specific to the Signal itself. +* If you're unsure then check the documentation, or failing that simply do: +* +* `Signal.add(function() { console.log(arguments); })` +* +* and it will log all of the arguments your function received from the Signal. +* +* Sprites have lots of default signals you can listen to in their Events class, such as: +* +* `sprite.events.onKilled` +* +* Which is called automatically whenever the Sprite is killed. +* There are lots of other events, see the Events component for a list. +* +* As well as listening to pre-defined Signals you can also create your own: +* +* `var mySignal = new Phaser.Signal();` +* +* This creates a new Signal. You can bind a callback to it: +* +* `mySignal.add(myCallback, this);` +* +* and then finally when ready you can dispatch the Signal: +* +* `mySignal.dispatch(your arguments);` +* +* And your callback will be invoked. See the dispatch method for more details. +* +* @class Phaser.Signal +* @constructor +*/ +Phaser.Signal = function () {}; + +Phaser.Signal.prototype = { + + /** + * @property {?Array.} _bindings - Internal variable. + * @private + */ + _bindings: null, + + /** + * @property {any} _prevParams - Internal variable. + * @private + */ + _prevParams: null, + + /** + * Memorize the previously dispatched event? + * + * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}. + * Use {@link #forget} to clear any currently memorized event. + * + * @property {boolean} memorize + */ + memorize: false, + + /** + * @property {boolean} _shouldPropagate + * @private + */ + _shouldPropagate: true, + + /** + * Is the Signal active? Only active signals will broadcast dispatched events. + * + * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}. + * + * @property {boolean} active + * @default + */ + active: true, + + /** + * @property {function} _boundDispatch - The bound dispatch function, if any. + * @private + */ + _boundDispatch: false, + + /** + * @method Phaser.Signal#validateListener + * @param {function} listener - Signal handler function. + * @param {string} fnName - Function name. + * @private + */ + validateListener: function (listener, fnName) { + + if (typeof listener !== 'function') + { + throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); + } + + }, + + /** + * @method Phaser.Signal#_registerListener + * @private + * @param {function} listener - Signal handler function. + * @param {boolean} isOnce - Should the listener only be called once? + * @param {object} [listenerContext] - The context under which the listener is invoked. + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + _registerListener: function (listener, isOnce, listenerContext, priority, args) { + + var prevIndex = this._indexOfListener(listener, listenerContext); + var binding; + + if (prevIndex !== -1) + { + binding = this._bindings[prevIndex]; + + if (binding.isOnce() !== isOnce) + { + throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); + } + } + else + { + binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args); + this._addBinding(binding); + } + + if (this.memorize && this._prevParams) + { + binding.execute(this._prevParams); + } + + return binding; + + }, + + /** + * @method Phaser.Signal#_addBinding + * @private + * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. + */ + _addBinding: function (binding) { + + if (!this._bindings) + { + this._bindings = []; + } + + // Simplified insertion sort + var n = this._bindings.length; + + do { + n--; + } + while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); + + this._bindings.splice(n + 1, 0, binding); + + }, + + /** + * @method Phaser.Signal#_indexOfListener + * @private + * @param {function} listener - Signal handler function. + * @param {object} [context=null] - Signal handler function. + * @return {number} The index of the listener within the private bindings array. + */ + _indexOfListener: function (listener, context) { + + if (!this._bindings) + { + return -1; + } + + if (context === undefined) { context = null; } + + var n = this._bindings.length; + var cur; + + while (n--) + { + cur = this._bindings[n]; + + if (cur._listener === listener && cur.context === context) + { + return n; + } + } + + return -1; + + }, + + /** + * Check if a specific listener is attached. + * + * @method Phaser.Signal#has + * @param {function} listener - Signal handler function. + * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @return {boolean} If Signal has the specified listener. + */ + has: function (listener, context) { + + return this._indexOfListener(listener, context) !== -1; + + }, + + /** + * Add an event listener for this signal. + * + * An event listener is a callback with a related context and priority. + * + * You can optionally provide extra arguments which will be passed to the callback after any internal parameters. + * + * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. + * Any arguments you've specified after `priority` will be sent as well: + * + * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` + * + * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. + * + * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', + * and the value 100 were the custom arguments given in the call to 'add'. + * + * If the callback calls {@link #halt} or returns `false`, any remaining callbacks bound to this Signal are skipped. + * + * @method Phaser.Signal#add + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + add: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'add'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, false, listenerContext, priority, args); + + }, + + /** + * Add a one-time listener - the listener is automatically removed after the first execution. + * + * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and + * the listener will be removed immediately. + * + * @method Phaser.Signal#addOnce + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + addOnce: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'addOnce'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, true, listenerContext, priority, args); + + }, + + /** + * Remove a single event listener. + * + * @method Phaser.Signal#remove + * @param {function} listener - Handler function that should be removed. + * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {function} Listener handler function. + */ + remove: function (listener, context) { + + this.validateListener(listener, 'remove'); + + var i = this._indexOfListener(listener, context); + + if (i !== -1) + { + this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal + this._bindings.splice(i, 1); + } + + return listener; + + }, + + /** + * Remove all event listeners. + * + * @method Phaser.Signal#removeAll + * @param {object} [context=null] - If specified only listeners for the given context will be removed. + */ + removeAll: function (context) { + + if (context === undefined) { context = null; } + + if (!this._bindings) + { + return; + } + + var n = this._bindings.length; + + while (n--) + { + if (context) + { + if (this._bindings[n].context === context) + { + this._bindings[n]._destroy(); + this._bindings.splice(n, 1); + } + } + else + { + this._bindings[n]._destroy(); + } + } + + if (!context) + { + this._bindings.length = 0; + } + + }, + + /** + * Gets the total number of listeners attached to this Signal. + * + * @method Phaser.Signal#getNumListeners + * @return {integer} Number of listeners attached to the Signal. + */ + getNumListeners: function () { + + return this._bindings ? this._bindings.length : 0; + + }, + + /** + * Stop propagation of the event, blocking the dispatch to next listener on the queue. + * + * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. + * See {@link #active} to enable/disable the signal entirely. + * + * @method Phaser.Signal#halt + */ + halt: function () { + + this._shouldPropagate = false; + + }, + + /** + * Dispatch / broadcast the event to all listeners. + * + * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}. + * + * @method Phaser.Signal#dispatch + * @param {any} [params] - Parameters that should be passed to each handler. + */ + dispatch: function () { + + if (!this.active || !this._bindings) + { + return; + } + + var paramsArr = Array.prototype.slice.call(arguments); + var n = this._bindings.length; + var bindings; + + if (this.memorize) + { + this._prevParams = paramsArr; + } + + if (!n) + { + // Should come after memorize + return; + } + + bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch + this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. + + //execute all callbacks until end of the list or until a callback returns `false` or stops propagation + //reverse loop since listeners with higher priority will be added at the end of the list + do { + n--; + } + while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); + + }, + + /** + * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any. + * + * @method Phaser.Signal#forget + */ + forget: function() { + + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * Dispose the signal - no more events can be dispatched. + * + * This removes all event listeners and clears references to external objects. + * Calling methods on a disposed objects results in undefined behavior. + * + * @method Phaser.Signal#dispose + */ + dispose: function () { + + this.removeAll(); + + this._bindings = null; + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * A string representation of the object. + * + * @method Phaser.Signal#toString + * @return {string} String representation of the object. + */ + toString: function () { + + return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']'; + + } + +}; + +/** +* Create a `dispatch` function that maintains a binding to the original Signal context. +* +* Use the resulting value if the dispatch function needs to be passed somewhere +* or called independently of the Signal object. +* +* @memberof Phaser.Signal +* @property {function} boundDispatch +*/ +Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", { + + get: function () { + var _this = this; + return this._boundDispatch || (this._boundDispatch = function () { + return _this.dispatch.apply(_this, arguments); + }); + } + +}); + +Phaser.Signal.prototype.constructor = Phaser.Signal; + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Object that represents a binding between a Signal and a listener function. +* This is an internal constructor and shouldn't be created directly. +* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. +* +* @class Phaser.SignalBinding +* @constructor +* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to. +* @param {function} listener - Handler function bound to the signal. +* @param {boolean} isOnce - If binding should be executed just once. +* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). +* @param {number} [priority] - The priority level of the event listener. (default = 0). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. +*/ +Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) { + + /** + * @property {Phaser.Game} _listener - Handler function bound to the signal. + * @private + */ + this._listener = listener; + + if (isOnce) + { + this._isOnce = true; + } + + if (listenerContext != null) /* not null/undefined */ + { + this.context = listenerContext; + } + + /** + * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to. + * @private + */ + this._signal = signal; + + if (priority) + { + this._priority = priority; + } + + if (args && args.length) + { + this._args = args; + } + +}; + +Phaser.SignalBinding.prototype = { + + /** + * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + */ + context: null, + + /** + * @property {boolean} _isOnce - If binding should be executed just once. + * @private + */ + _isOnce: false, + + /** + * @property {number} _priority - Listener priority. + * @private + */ + _priority: 0, + + /** + * @property {array} _args - Listener arguments. + * @private + */ + _args: null, + + /** + * @property {number} callCount - The number of times the handler function has been called. + */ + callCount: 0, + + /** + * If binding is active and should be executed. + * @property {boolean} active + * @default + */ + active: true, + + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). + * @property {array|null} params + * @default + */ + params: null, + + /** + * Call listener passing arbitrary parameters. + * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. + * @method Phaser.SignalBinding#execute + * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener. + * @return {any} Value returned by the listener. + */ + execute: function(paramsArr) { + + var handlerReturn, params; + + if (this.active && !!this._listener) + { + params = this.params ? this.params.concat(paramsArr) : paramsArr; + + if (this._args) + { + params = params.concat(this._args); + } + + handlerReturn = this._listener.apply(this.context, params); + + this.callCount++; + + if (this._isOnce) + { + this.detach(); + } + } + + return handlerReturn; + + }, + + /** + * Detach binding from signal. + * alias to: @see mySignal.remove(myBinding.getListener()); + * @method Phaser.SignalBinding#detach + * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ + detach: function () { + return this.isBound() ? this._signal.remove(this._listener, this.context) : null; + }, + + /** + * @method Phaser.SignalBinding#isBound + * @return {boolean} True if binding is still bound to the signal and has a listener. + */ + isBound: function () { + return (!!this._signal && !!this._listener); + }, + + /** + * @method Phaser.SignalBinding#isOnce + * @return {boolean} If SignalBinding will only be executed once. + */ + isOnce: function () { + return this._isOnce; + }, + + /** + * @method Phaser.SignalBinding#getListener + * @return {function} Handler function bound to the signal. + */ + getListener: function () { + return this._listener; + }, + + /** + * @method Phaser.SignalBinding#getSignal + * @return {Phaser.Signal} Signal that listener is currently bound to. + */ + getSignal: function () { + return this._signal; + }, + + /** + * Delete instance properties + * @method Phaser.SignalBinding#_destroy + * @private + */ + _destroy: function () { + delete this._signal; + delete this._listener; + delete this.context; + }, + + /** + * @method Phaser.SignalBinding#toString + * @return {string} String representation of the object. + */ + toString: function () { + return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']'; + } + +}; + +Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding; + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Filter class to use for any Phaser filter development. +* If you want to make a custom filter, this should be your base class. +* +* The default uniforms, types and values for all Filters are: +* +* ```javascript +* resolution: { type: '2f', value: { x: 256, y: 256 }} +* time: { type: '1f', value: 0 } +* mouse: { type: '2f', value: { x: 0.0, y: 0.0 } } +* date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] } +* sampleRate: { type: '1f', value: 44100.0 } +* iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* ``` +* +* The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and +* therefore only work in WebGL and are not supported by Canvas at all. +* +* @class Phaser.Filter +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [uniforms] - Uniform mappings object. The uniforms are added on the default uniforms, or replace them if the keys are the same. +* @param {Array|string} [fragmentSrc] - The fragment shader code. Either an array, one element per line of code, or a string. +*/ +Phaser.Filter = function (game, uniforms, fragmentSrc) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. + * @default + */ + this.type = Phaser.WEBGL_FILTER; + + /** + * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. + * For example the blur filter has two passes blurX and blurY. + * @property {array} passes - An array of filter objects. + * @private + */ + this.passes = [ this ]; + + /** + * @property {array} shaders - Array an array of shaders. + * @private + */ + this.shaders = []; + + /** + * @property {boolean} dirty - Internal PIXI var. + * @default + */ + this.dirty = true; + + /** + * @property {number} padding - Internal PIXI var. + * @default + */ + this.padding = 0; + + /** + * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same) + */ + this.prevPoint = new Phaser.Point(); + + /* + * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D. + */ + + var d = new Date(); + + /** + * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. + */ + this.uniforms = { + + resolution: { type: '2f', value: { x: 256, y: 256 }}, + time: { type: '1f', value: 0 }, + mouse: { type: '2f', value: { x: 0.0, y: 0.0 } }, + date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, + sampleRate: { type: '1f', value: 44100.0 }, + iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + + }; + + // Copy over / replace any passed in the constructor + if (uniforms) + { + for (var key in uniforms) + { + this.uniforms[key] = uniforms[key]; + } + } + + // If fragmentSrc is a string, split it based on new-lines into an array + if (typeof fragmentSrc === 'string') + { + fragmentSrc = fragmentSrc.split('\n'); + } + + /** + * @property {array|string} fragmentSrc - The fragment shader code. + */ + this.fragmentSrc = fragmentSrc || []; + +}; + +Phaser.Filter.prototype = { + + /** + * This should be over-ridden. Will receive a variable number of arguments. + * + * @method Phaser.Filter#init + */ + init: function () { + + // This should be over-ridden. Will receive a variable number of arguments. + + }, + + /** + * Set the resolution uniforms on the filter. + * + * @method Phaser.Filter#setResolution + * @param {number} width - The width of the display. + * @param {number} height - The height of the display. + */ + setResolution: function (width, height) { + + this.uniforms.resolution.value.x = width; + this.uniforms.resolution.value.y = height; + + }, + + /** + * Updates the filter. + * + * @method Phaser.Filter#update + * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. + */ + update: function (pointer) { + + if (pointer) + { + var x = pointer.x / this.game.width; + var y = 1 - pointer.y / this.game.height; + + if (x !== this.prevPoint.x || y !== this.prevPoint.y) + { + this.uniforms.mouse.value.x = x.toFixed(2); + this.uniforms.mouse.value.y = y.toFixed(2); + this.prevPoint.set(x, y); + } + } + + this.uniforms.time.value = this.game.time.totalElapsedSeconds(); + + }, + + /** + * Creates a new Phaser.Image object using a blank texture and assigns + * this Filter to it. The image is then added to the world. + * + * If you don't provide width and height values then Filter.width and Filter.height are used. + * + * If you do provide width and height values then this filter will be resized to match those + * values. + * + * @method Phaser.Filter#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. + * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, width, height, anchorX, anchorY) { + + if (anchorX === undefined) { anchorX = 0; } + if (anchorY === undefined) { anchorY = 0; } + + if (width !== undefined && width !== null) + { + this.width = width; + } + else + { + width = this.width; + } + + if (height !== undefined && height !== null) + { + this.height = height; + } + else + { + height = this.height; + } + + var image = this.game.add.image(x, y, Phaser.Cache.DEFAULT); + + image.width = width; + image.height = height; + + image.anchor.set(anchorX, anchorY); + + image.filters = [ this ]; + + return image; + + }, + + /** + * Syncs the uniforms between the class object and the shaders. + * + * @method Phaser.Filter#syncUniforms + */ + syncUniforms: function () { + + for (var i = 0; i < this.shaders.length; i++) + { + this.shaders[i].dirty = true; + } + + }, + + /** + * Clear down this Filter and null out references to game. + * + * @method Phaser.Filter#destroy + */ + destroy: function () { + + this.passes.length = 0; + this.shaders.length = 0; + this.fragmentSrc.length = 0; + + this.game = null; + this.uniforms = null; + this.prevPoint = null; + + } + +}; + +Phaser.Filter.prototype.constructor = Phaser.Filter; + +/** +* @name Phaser.Filter#width +* @property {number} width - The width (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'width', { + + get: function () { + + return this.uniforms.resolution.value.x; + + }, + + set: function (value) { + + this.uniforms.resolution.value.x = value; + + } + +}); + +/** +* @name Phaser.Filter#height +* @property {number} height - The height (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'height', { + + get: function () { + + return this.uniforms.resolution.value.y; + + }, + + set: function (value) { + + this.uniforms.resolution.value.y = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Plugin template to use for any Phaser plugin development. +* +* ##### Callbacks +* +* add | active | visible | remove +* -----|-------------|-------------|-------- +* init | | | +* | preUpdate* | | +* | update* | render* | +* | postUpdate* | postRender* | +* | | | destroy +* +* Update and render calls are repeated (*). +* +* @class Phaser.Plugin +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager. +*/ +Phaser.Plugin = function (game, parent) { + + if (parent === undefined) { parent = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. + */ + this.parent = parent; + + /** + * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. + * @default + */ + this.active = false; + + /** + * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. + * @default + */ + this.visible = false; + + /** + * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. + * @default + */ + this.hasPreUpdate = false; + + /** + * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. + * @default + */ + this.hasUpdate = false; + + /** + * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. + * @default + */ + this.hasPostUpdate = false; + + /** + * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. + * @default + */ + this.hasRender = false; + + /** + * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. + * @default + */ + this.hasPostRender = false; + +}; + +Phaser.Plugin.prototype = { + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It is only called if active is set to true. + * @method Phaser.Plugin#preUpdate + */ + preUpdate: function () { + }, + + /** + * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It is only called if active is set to true. + * @method Phaser.Plugin#update + */ + update: function () { + }, + + /** + * Render is called right after the Game Renderer completes, but before the State.render. + * It is only called if visible is set to true. + * @method Phaser.Plugin#render + */ + render: function () { + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It is only called if visible is set to true. + * @method Phaser.Plugin#postRender + */ + postRender: function () { + }, + + /** + * Clear down this Plugin and null out references + * @method Phaser.Plugin#destroy + */ + destroy: function () { + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + + } + +}; + +Phaser.Plugin.prototype.constructor = Phaser.Plugin; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. +* +* @class Phaser.PluginManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.PluginManager = function(game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager. + */ + this.plugins = []; + + /** + * @property {number} _len - Internal cache var. + * @private + */ + this._len = 0; + + /** + * @property {number} _i - Internal cache var. + * @private + */ + this._i = 0; + +}; + +Phaser.PluginManager.prototype = { + + /** + * Add a new Plugin into the PluginManager. + * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.PluginManager#add + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + add: function (plugin) { + + var args = Array.prototype.slice.call(arguments, 1); + var result = false; + + // Prototype? + if (typeof plugin === 'function') + { + plugin = new plugin(this.game, this); + } + else + { + plugin.game = this.game; + plugin.parent = this; + } + + // Check for methods now to avoid having to do this every loop + 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; + } + + // The plugin must have at least one of the above functions to be added to the PluginManager. + 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); + + // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager + if (typeof plugin['init'] === 'function') + { + plugin.init.apply(plugin, args); + } + + return plugin; + } + else + { + return null; + } + }, + + /** + * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. + * + * @method Phaser.PluginManager#remove + * @param {Phaser.Plugin} plugin - The plugin to be removed. + * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed? + */ + remove: function (plugin, destroy) { + + if (destroy === undefined) { destroy = true; } + + this._i = this._len; + + while (this._i--) + { + if (this.plugins[this._i] === plugin) + { + if (destroy) + { + plugin.destroy(); + } + + this.plugins.splice(this._i, 1); + this._len--; + return; + } + } + + }, + + /** + * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. + * + * @method Phaser.PluginManager#removeAll + */ + removeAll: function() { + + this._i = this._len; + + while (this._i--) + { + this.plugins[this._i].destroy(); + } + + this.plugins.length = 0; + this._len = 0; + + }, + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#preUpdate + */ + 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 is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#update + */ + 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 is the last thing to be called before the world render. + * In particular, it is called after the world postUpdate, which means the camera has been adjusted. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#postUpdate + */ + 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 is called right after the Game Renderer completes, but before the State.render. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#render + */ + 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(); + } + } + + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#postRender + */ + 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(); + } + } + + }, + + /** + * Clear down this PluginManager, calls destroy on every plugin and nulls out references. + * + * @method Phaser.PluginManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.game = null; + + } + +}; + +Phaser.PluginManager.prototype.constructor = Phaser.PluginManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Stage controls root level display objects upon which everything is displayed. +* It also handles browser visibility handling and the pausing due to loss of focus. +* +* @class Phaser.Stage +* @extends PIXI.DisplayObjectContainer +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Stage = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {string} name - The name of this object. + * @default + */ + this.name = '_stage_root'; + + /** + * By default if the browser tab loses focus the game will pause. + * You can stop that behavior by setting this property to true. + * Note that the browser can still elect to pause your game if it wishes to do so, + * for example swapping to another browser tab. This will cause the RAF callback to halt, + * effectively pausing your game, even though no in-game pause event is triggered if you enable this property. + * @property {boolean} disableVisibilityChange + * @default + */ + this.disableVisibilityChange = false; + + /** + * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. + * @default + */ + this.exists = true; + + /** + * @property {Phaser.Matrix} worldTransform - Current transform of the object based on world (parent) factors + * @private + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage) + * @private + * @readOnly + */ + this.stage = this; + + /** + * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. + */ + this.currentRenderOrderID = 0; + + /** + * @property {string} hiddenVar - The page visibility API event name. + * @private + */ + this._hiddenVar = 'hidden'; + + /** + * @property {function} _onChange - The blur/focus event handler. + * @private + */ + this._onChange = null; + + /** + * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor. + * @private + */ + this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' }; + + if (!this.game.transparent) + { + // transparent = 0,0,0,0 - otherwise r,g,b,1 + this._bgColor.a = 1; + } + + if (game.config) + { + this.parseConfig(game.config); + } + +}; + +Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Stage.prototype.constructor = Phaser.Stage; + +/** +* Parses a Game configuration object. +* +* @method Phaser.Stage#parseConfig +* @protected +* @param {object} config -The configuration object to parse. +*/ +Phaser.Stage.prototype.parseConfig = function (config) { + + if (config['disableVisibilityChange']) + { + this.disableVisibilityChange = config['disableVisibilityChange']; + } + + if (config['backgroundColor']) + { + this.setBackgroundColor(config['backgroundColor']); + } + +}; + +/** +* Initialises the stage and adds the event listeners. +* @method Phaser.Stage#boot +* @private +*/ +Phaser.Stage.prototype.boot = function () { + + Phaser.DOM.getOffset(this.game.canvas, this.offset); + + Phaser.Canvas.setUserSelect(this.game.canvas, 'none'); + Phaser.Canvas.setTouchAction(this.game.canvas, 'none'); + + this.checkVisibility(); + +}; + +/** +* This is called automatically after the plugins preUpdate and before the State.update. +* Most objects have preUpdate methods and it's where initial movement and positioning is done. +* +* @method Phaser.Stage#preUpdate +*/ +Phaser.Stage.prototype.preUpdate = function () { + + this.currentRenderOrderID = 0; + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + +}; + +/** +* This is called automatically after the State.update, but before particles or plugins update. +* +* @method Phaser.Stage#update +*/ +Phaser.Stage.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + this.children[i].update(); + } + +}; + +/** +* This is called automatically before the renderer runs and after the plugins have updated. +* In postUpdate this is where all the final physics calculations and object positioning happens. +* The objects are processed in the order of the display list. +* +* @method Phaser.Stage#postUpdate +*/ +Phaser.Stage.prototype.postUpdate = function () { + + // Apply the camera shake, fade, bounds, etc + this.game.camera.update(); + + // Camera target first? + if (this.game.camera.target) + { + this.game.camera.target.postUpdate(); + + this.updateTransform(); + + this.game.camera.updateTarget(); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + this.updateTransform(); + +}; + +/** +* Updates the transforms for all objects on the display list. +* This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. +* +* @method Phaser.Stage#updateTransform +*/ +Phaser.Stage.prototype.updateTransform = function () { + + this.worldAlpha = 1; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +/** +* Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. +* Also listens for window.onblur and window.onfocus. +* +* @method Phaser.Stage#checkVisibility +*/ +Phaser.Stage.prototype.checkVisibility = function () { + + if (document.hidden !== undefined) + { + this._hiddenVar = 'visibilitychange'; + } + else if (document.webkitHidden !== undefined) + { + this._hiddenVar = 'webkitvisibilitychange'; + } + else if (document.mozHidden !== undefined) + { + this._hiddenVar = 'mozvisibilitychange'; + } + else if (document.msHidden !== undefined) + { + this._hiddenVar = 'msvisibilitychange'; + } + else + { + this._hiddenVar = null; + } + + var _this = this; + + this._onChange = function (event) { + return _this.visibilityChange(event); + }; + + this._onClick = function (event) { + if ((document.hasFocus !== undefined) && !document.hasFocus()) + { + _this.visibilityChange(event); + } + }; + + // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus + if (this._hiddenVar) + { + document.addEventListener(this._hiddenVar, this._onChange, false); + } + + window.onblur = this._onChange; + window.onfocus = this._onChange; + + window.onpagehide = this._onChange; + window.onpageshow = this._onChange; + + window.addEventListener('click', this._onClick); + + if (this.game.device.cocoonJSApp) + { + CocoonJS.App.onSuspended.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" }); + }); + + CocoonJS.App.onActivated.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" }); + }); + } + +}; + +/** +* This method is called when the document visibility is changed. +* +* - `blur` and `pagehide` events trigger {@link Phaser.Game#onBlur}. They {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `click`, `focus`, and `pageshow` trigger {@link Phaser.Game#onFocus}. They {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (hidden) and CocoonJS's `onSuspended` {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (visible) and CocoonJS's `onActivated` {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* +* @method Phaser.Stage#visibilityChange +* @param {Event} event - Its type will be used to decide whether the game should be paused or not. +*/ +Phaser.Stage.prototype.visibilityChange = function (event) { + + // These events always trigger the Game#onBlur or Game#onFocus signals. + + switch (event.type) + { + case 'blur': + case 'pagehide': + this.game.focusLoss(event); + return; + case 'click': + case 'focus': + case 'pageshow': + this.game.focusGain(event); + return; + } + + if (this.disableVisibilityChange) + { + return; + } + + if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause") + { + this.game.gamePaused(event); + } + else + { + this.game.gameResumed(event); + } + +}; + +/** +* Sets the background color for the Stage. +* +* The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). +* +* An alpha channel is _not_ supported and will be ignored. +* +* If you've set your game to be {@link Phaser.Game#transparent transparent} then calls to setBackgroundColor are ignored. +* +* If {@link Phaser.Game#clearBeforeRender} is off then the background color won't appear. +* +* @method Phaser.Stage#setBackgroundColor +* @param {number|string} color - The color of the background. +*/ +Phaser.Stage.prototype.setBackgroundColor = function (color) { + + if (this.game.transparent) { return; } + + Phaser.Color.valueToColor(color, this._bgColor); + Phaser.Color.updateColor(this._bgColor); + + // For gl.clearColor (canvas uses _bgColor.rgba) + this._bgColor.r /= 255; + this._bgColor.g /= 255; + this._bgColor.b /= 255; + this._bgColor.a = 1; + +}; + +/** +* Destroys the Stage and removes event listeners. +* +* @method Phaser.Stage#destroy +*/ +Phaser.Stage.prototype.destroy = function () { + + if (this._hiddenVar) + { + document.removeEventListener(this._hiddenVar, this._onChange, false); + } + + window.onpagehide = null; + window.onpageshow = null; + + window.onblur = null; + window.onfocus = null; + + window.removeEventListener('click', this._onClick); + +}; + +/** +* Adds an existing object to the Stage. +* +* The child is automatically added to the front of the Stage, and is displayed above every previous child. +* Or if the _optional_ `index` is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the object was already on the Stage, it is simply returned, and nothing else happens to it. +* +* @method Phaser.Stage#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent] - Unused. Kept for compatibility with {@link Phaser.Group#add}. +* @param {integer} [index] - The index to insert the object to. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Stage.prototype.add = function (child, silent, index) { + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + this.addChild(child); + } + else + { + this.addChildAt(child, index); + } + + return child; + +}; + +/** +* @name Phaser.Stage#backgroundColor +* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' +* @see Phaser.Stage#setBackgroundColor +*/ +Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", { + + get: function () { + + return this._bgColor.color; + + }, + + set: function (color) { + + this.setBackgroundColor(color); + + } + +}); + +/** +* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. +* +* @name Phaser.Stage#smoothed +* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) +*/ +Object.defineProperty(Phaser.Stage.prototype, "smoothed", { + + get: function () { + + return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR; + + }, + + set: function (value) { + + if (value) + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR; + } + else + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}. +* +* Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. +* For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. +* +* In addition, Groups provides support for fast pooling and object recycling. +* +* Groups are also display objects and can be nested as children within other Groups. +* +* @class Phaser.Group +* @extends PIXI.DisplayObjectContainer +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to. +* If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent. +* @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World. +* @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}. +* @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values. +*/ +Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) { + + if (addToStage === undefined) { addToStage = false; } + if (enableBody === undefined) { enableBody = false; } + if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + if (parent === undefined) + { + parent = game.world; + } + + /** + * A name for this group. Not used internally but useful for debugging. + * @property {string} name + */ + this.name = name || 'group'; + + /** + * The z-depth value of this object within its parent container/Group - the World is a Group as well. + * This value must be unique for each child in a Group. + * @property {integer} z + * @readOnly + */ + this.z = 0; + + PIXI.DisplayObjectContainer.call(this); + + if (addToStage) + { + this.game.stage.addChild(this); + this.z = this.game.stage.children.length; + } + else + { + if (parent) + { + parent.addChild(this); + this.z = parent.children.length; + } + } + + /** + * Internal Phaser Type value. + * @property {integer} type + * @protected + */ + this.type = Phaser.GROUP; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. + * @property {boolean} alive + * @default + */ + this.alive = true; + + /** + * If exists is false the group will be excluded from collision checks and filters such as {@link #forEachExists}. The group will not call `preUpdate` and `postUpdate` on its children and the children will not receive physics updates or camera/world boundary checks. The group will still be {@link #visible} and will still call `update` on its children (unless {@link #updateOnlyExistingChildren} is true). + * @property {boolean} exists + * @default + */ + this.exists = true; + + /** + * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. + * @property {boolean} ignoreDestroy + * @default + */ + this.ignoreDestroy = false; + + /** + * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method + * called on the next logic update. + * You can set it directly to flag the Group to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy a Group from within one of its own callbacks + * or a callback of one of its children. + * + * @property {boolean} pendingDestroy + */ + this.pendingDestroy = false; + + /** + * The type of objects that will be created when using {@link #create} or {@link #createMultiple}. + * + * It should extend either Sprite or Image and accept the same constructor arguments: `(game, x, y, key, frame)`. + * + * @property {function} classType + * @default {@link Phaser.Sprite} + */ + this.classType = Phaser.Sprite; + + /** + * The current display object that the group cursor is pointing to, if any. (Can be set manually.) + * + * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}. + * @property {?DisplayObject} cursor + */ + this.cursor = null; + + /** + * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` + * on any children _added_ to, or _created by_, this Group. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * @property {boolean} inputEnableChildren + * @default + */ + this.inputEnableChildren = false; + + /** + * Skip children with `exists = false` in {@link #update}. + * + * @property {boolean} updateOnlyExistingChildren + * @default + */ + this.updateOnlyExistingChildren = false; + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputDown + */ + this.onChildInputDown = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, + * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer + * is still over the Sprite or not. + * + * @property {Phaser.Signal} onChildInputUp + */ + this.onChildInputUp = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOver + */ + this.onChildInputOver = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOut + */ + this.onChildInputOut = new Phaser.Signal(); + + /** + * If true all Sprites created by, or added to this group, will have a physics body enabled on them. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * The default body type is controlled with {@link #physicsBodyType}. + * @property {boolean} enableBody + */ + this.enableBody = enableBody; + + /** + * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well. + * + * This only works for P2 bodies. + * @property {boolean} enableBodyDebug + * @default + */ + this.enableBodyDebug = false; + + /** + * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites. + * + * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc. + * @property {integer} physicsBodyType + */ + this.physicsBodyType = physicsBodyType; + + /** + * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. + * + * It should be set to one of the Phaser.Physics.Arcade sort direction constants: + * + * Phaser.Physics.Arcade.SORT_NONE + * Phaser.Physics.Arcade.LEFT_RIGHT + * Phaser.Physics.Arcade.RIGHT_LEFT + * Phaser.Physics.Arcade.TOP_BOTTOM + * Phaser.Physics.Arcade.BOTTOM_TOP + * + * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. + * + * @property {integer} physicsSortDirection + * @default + */ + this.physicsSortDirection = null; + + /** + * This signal is dispatched when the group is destroyed. + * @property {Phaser.Signal} onDestroy + */ + this.onDestroy = new Phaser.Signal(); + + /** + * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next. + * @readOnly + */ + this.cursorIndex = 0; + + /** + * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. + * + * Note that the cameraOffset values are in addition to any parent in the display list. + * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x + * + * @property {boolean} fixedToCamera + */ + this.fixedToCamera = false; + + /** + * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view. + * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. + * @property {Phaser.Point} cameraOffset + */ + this.cameraOffset = new Phaser.Point(); + + /** + * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. + * + * Only children of this Group can be added to and removed from the hash. + * + * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. + * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own + * sorting and filtering of Group children without touching their z-index (and therefore display draw order) + * + * @property {array} hash + */ + this.hash = []; + + /** + * The property on which children are sorted. + * @property {string} _sortProperty + * @private + */ + this._sortProperty = 'z'; + +}; + +Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Group.prototype.constructor = Phaser.Group; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_NONE = 0; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_TOTAL = 1; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_CHILD = 2; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_ALL = 3; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_ASCENDING = -1; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_DESCENDING = 1; + +/** +* Adds an existing object as the top child in this group. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the child was already in this Group, it is simply returned, and nothing else happens to it. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* Use {@link #create} to create and add a new child. +* +* @method Phaser.Group#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.add = function (child, silent, index) { + + if (silent === undefined) { silent = false; } + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + child.z = this.children.length; + + this.addChild(child); + } + else + { + this.addChildAt(child, index); + + this.updateZ(); + } + + if (this.enableBody && child.hasOwnProperty('body') && child.body === null) + { + this.game.physics.enable(child, this.physicsBodyType); + } + else if (child.body) + { + this.addToHash(child); + } + + if (this.inputEnableChildren && (!child.input || child.inputEnabled)) + { + child.inputEnabled = true; + } + + if (!silent && child.events) + { + child.events.onAddedToGroup$dispatch(child, this); + } + + if (this.cursor === null) + { + this.cursor = child; + } + + return child; + +}; + +/** +* Adds an existing object to this group. +* +* The child is added to the group at the location specified by the index value, this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#addAt +* @param {DisplayObject} child - The display object to add as a child. +* @param {integer} [index=0] - The index within the group to insert the child to. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.addAt = function (child, index, silent) { + + return this.add(child, silent, index); + +}; + +/** +* Adds a child of this Group into the hash array. +* This call will return false if the child is not a child of this Group, or is already in the hash. +* +* @method Phaser.Group#addToHash +* @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. +* @return {boolean} True if the child was successfully added to the hash, otherwise false. +*/ +Phaser.Group.prototype.addToHash = function (child) { + + if (child.parent === this) + { + var index = this.hash.indexOf(child); + + if (index === -1) + { + this.hash.push(child); + return true; + } + } + + return false; + +}; + +/** +* Removes a child of this Group from the hash array. +* This call will return false if the child is not in the hash. +* +* @method Phaser.Group#removeFromHash +* @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash. +* @return {boolean} True if the child was successfully removed from the hash, otherwise false. +*/ +Phaser.Group.prototype.removeFromHash = function (child) { + + if (child) + { + var index = this.hash.indexOf(child); + + if (index !== -1) + { + this.hash.splice(index, 1); + return true; + } + } + + return false; + +}; + +/** +* Adds an array of existing Display Objects to this Group. +* +* The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. +* +* As well as an array you can also pass another Group as the first argument. In this case all of the children from that +* Group will be removed from it and added into this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#addMultiple +* @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group. +*/ +Phaser.Group.prototype.addMultiple = function (children, silent) { + + if (children instanceof Phaser.Group) + { + children.moveAll(this, silent); + } + else if (Array.isArray(children)) + { + for (var i = 0; i < children.length; i++) + { + this.add(children[i], silent); + } + } + + return children; + +}; + +/** +* Returns the child found at the given index within this group. +* +* @method Phaser.Group#getAt +* @param {integer} index - The index to return the child from. +* @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index. +*/ +Phaser.Group.prototype.getAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + return -1; + } + else + { + return this.getChildAt(index); + } + +}; + +/** +* Creates a new Phaser.Sprite object and adds it to the top of this group. +* +* Use {@link #classType} to change the type of object created. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#create +* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. +* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {boolean} [exists=true] - The default exists state of the Sprite. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed. +*/ +Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) { + + if (exists === undefined) { exists = true; } + + var child = new this.classType(this.game, x, y, key, frame); + + child.exists = exists; + child.visible = exists; + child.alive = exists; + + return this.add(child, false, index); + +}; + +/** +* Creates multiple Phaser.Sprite objects and adds them to the top of this Group. +* +* This method is useful if you need to quickly generate a pool of sprites, such as bullets. +* +* Use {@link #classType} to change the type of object created. +* +* You can provide an array as the `key` and / or `frame` arguments. When you do this +* it will create `quantity` Sprites for every key (and frame) in the arrays. +* +* For example: +* +* `createMultiple(25, ['ball', 'carrot'])` +* +* In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be +* created in total, 25 of each. You can also have the `frame` as an array: +* +* `createMultiple(5, 'bricks', [0, 1, 2, 3])` +* +* In the above there is one key (bricks), which is a sprite sheet. The frames array tells +* this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because +* the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with +* frame 1, and so on. +* +* If you set both the key and frame arguments to be arrays then understand it will create +* a total quantity of sprites equal to the size of both arrays times each other. I.e.: +* +* `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` +* +* The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. +* It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. +* In total it will have created 120 sprites. +* +* By default the Sprites will have their `exists` property set to `false`, and they will be +* positioned at 0x0, relative to the `Group.x / y` values. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#createMultiple +* @param {integer} quantity - The number of Sprites to create. +* @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. +* @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. +* @param {boolean} [exists=false] - The default exists state of the Sprite. +* @param {function} [callback] - The function that will be called for each applicable child. It will be passed the new child and the loop index (0 through quantity - 1). +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). The default context is the new child. +* @return {array} An array containing all of the Sprites that were created. +*/ +Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, callback, callbackContext) { + + if (frame === undefined) { frame = 0; } + if (exists === undefined) { exists = false; } + + if (!Array.isArray(key)) + { + key = [ key ]; + } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + + var _this = this; + var children = []; + + key.forEach(function(singleKey) { + + frame.forEach(function(singleFrame) { + + for (var i = 0; i < quantity; i++) + { + var child = _this.create(0, 0, singleKey, singleFrame, exists); + + if (callback) { callback.call(callbackContext || child, child, i); } + + children.push(child); + } + + }); + + }); + + return children; + +}; + +/** +* Internal method that re-applies all of the children's Z values. +* +* This must be called whenever children ordering is altered so that their `z` indices are correctly updated. +* +* @method Phaser.Group#updateZ +* @protected +*/ +Phaser.Group.prototype.updateZ = function () { + + var i = this.children.length; + + while (i--) + { + this.children[i].z = i; + } + +}; + +/** +* This method iterates through all children in the Group (regardless if they are visible or exist) +* and then changes their position so they are arranged in a Grid formation. Children must have +* the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have +* this. +* +* The grid dimensions are determined by the first four arguments. The `width` and `height` arguments +* relate to the width and height of the grid respectively. +* +* For example if the Group had 100 children in it: +* +* `Group.align(10, 10, 32, 32)` +* +* This will align all of the children into a grid formation of 10x10, using 32 pixels per +* grid cell. If you want a wider grid, you could do: +* +* `Group.align(25, 4, 32, 32)` +* +* This will align the children into a grid of 25x4, again using 32 pixels per grid cell. +* +* You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method +* to keep on aligning children until there are no children left. For example if this Group had +* 48 children in it, the following: +* +* `Group.align(-1, 8, 32, 32)` +* +* ... will align the children so that there are 8 children vertically (the second argument), +* and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) +* +* You can also do: +* +* `Group.align(10, -1, 32, 32)` +* +* In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit +* all of the children in. +* +* The `position` property allows you to control where in each grid cell the child is positioned. +* This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, +* `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, +* `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* +* The final argument; `offset` lets you start the alignment from a specific child index. +* +* @method Phaser.Group#align +* @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. +* @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. +* @param {integer} cellWidth - The width of each grid cell, in pixels. +* @param {integer} cellHeight - The height of each grid cell, in pixels. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. +* @return {boolean} True if the Group children were aligned, otherwise false. +*/ +Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, position, offset) { + + if (position === undefined) { position = Phaser.TOP_LEFT; } + if (offset === undefined) { offset = 0; } + + if (this.children.length === 0 || offset > this.children.length || (width === -1 && height === -1)) + { + return false; + } + + var r = new Phaser.Rectangle(0, 0, cellWidth, cellHeight); + var w = (width * cellWidth); + var h = (height * cellHeight); + + for (var i = offset; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child['alignIn']) + { + child.alignIn(r, position); + } + else + { + continue; + } + + if (width === -1) + { + // We keep laying them out horizontally until we've done them all + r.y += cellHeight; + + if (r.y === h) + { + r.x += cellWidth; + r.y = 0; + } + } + else if (height === -1) + { + // We keep laying them out vertically until we've done them all + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + } + } + else + { + // We keep laying them out until we hit the column limit + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + + if (r.y === h) + { + // We've hit the column limit, so return, even if there are children left + return true; + } + } + } + } + + return true; + +}; + +/** +* Sets the group cursor to the first child in the group. +* +* If the optional index parameter is given it sets the cursor to the object at that index instead. +* +* @method Phaser.Group#resetCursor +* @param {integer} [index=0] - Set the cursor to point to a specific index. +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.resetCursor = function (index) { + + if (index === undefined) { index = 0; } + + if (index > this.children.length - 1) + { + index = 0; + } + + if (this.cursor) + { + this.cursorIndex = index; + this.cursor = this.children[this.cursorIndex]; + return this.cursor; + } + +}; + +/** +* Advances the group cursor to the next (higher) object in the group. +* +* If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). +* +* @method Phaser.Group#next +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.next = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex >= this.children.length - 1) + { + this.cursorIndex = 0; + } + else + { + this.cursorIndex++; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Moves the group cursor to the previous (lower) child in the group. +* +* If the cursor is at the start of the group (bottom child) it is moved to the end (top child). +* +* @method Phaser.Group#previous +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.previous = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex === 0) + { + this.cursorIndex = this.children.length - 1; + } + else + { + this.cursorIndex--; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Swaps the position of two children in this group. +* +* Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. +* +* @method Phaser.Group#swap +* @param {any} child1 - The first child to swap. +* @param {any} child2 - The second child to swap. +*/ +Phaser.Group.prototype.swap = function (child1, child2) { + + this.swapChildren(child1, child2); + this.updateZ(); + +}; + +/** +* Brings the given child to the top of this group so it renders above all other children. +* +* @method Phaser.Group#bringToTop +* @param {any} child - The child to bring to the top of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.bringToTop = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length) + { + this.remove(child, false, true); + this.add(child, true); + } + + return child; + +}; + +/** +* Sends the given child to the bottom of this group so it renders below all other children. +* +* @method Phaser.Group#sendToBack +* @param {any} child - The child to send to the bottom of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.sendToBack = function (child) { + + if (child.parent === this && this.getIndex(child) > 0) + { + this.remove(child, false, true); + this.addAt(child, 0, true); + } + + return child; + +}; + +/** +* Moves the given child up one place in this group unless it's already at the top. +* +* @method Phaser.Group#moveUp +* @param {any} child - The child to move up in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveUp = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length - 1) + { + var a = this.getIndex(child); + var b = this.getAt(a + 1); + + if (b) + { + this.swap(child, b); + } + } + + return child; + +}; + +/** +* Moves the given child down one place in this group unless it's already at the bottom. +* +* @method Phaser.Group#moveDown +* @param {any} child - The child to move down in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveDown = 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; + +}; + +/** +* Positions the child found at the given index within this group to the given x and y coordinates. +* +* @method Phaser.Group#xy +* @param {integer} index - The index of the child in the group to set the position of. +* @param {number} x - The new x position of the child. +* @param {number} y - The new y position of the 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; + } + +}; + +/** +* Reverses all children in this group. +* +* This operation applies only to immediate children and does not propagate to subgroups. +* +* @method Phaser.Group#reverse +*/ +Phaser.Group.prototype.reverse = function () { + + this.children.reverse(); + this.updateZ(); + +}; + +/** +* Get the index position of the given child in this group, which should match the child's `z` property. +* +* @method Phaser.Group#getIndex +* @param {any} child - The child to get the index for. +* @return {integer} The index of the child or -1 if it's not a member of this group. +*/ +Phaser.Group.prototype.getIndex = function (child) { + + return this.children.indexOf(child); + +}; + +/** +* Searches the Group for the first instance of a child with the `name` +* property matching the given argument. Should more than one child have +* the same name only the first instance is returned. +* +* @method Phaser.Group#getByName +* @param {string} name - The name to search for. +* @return {any} The first child with a matching name, or null if none were found. +*/ +Phaser.Group.prototype.getByName = function (name) { + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].name === name) + { + return this.children[i]; + } + } + + return null; + +}; + +/** +* Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#replace +* @param {any} oldChild - The child in this group that will be replaced. +* @param {any} newChild - The child to be inserted into this group. +* @return {any} Returns the oldChild that was replaced within this group. +*/ +Phaser.Group.prototype.replace = function (oldChild, newChild) { + + var index = this.getIndex(oldChild); + + if (index !== -1) + { + if (newChild.parent) + { + if (newChild.parent instanceof Phaser.Group) + { + newChild.parent.remove(newChild); + } + else + { + newChild.parent.removeChild(newChild); + } + } + + this.remove(oldChild); + + this.addAt(newChild, index); + + return oldChild; + } + +}; + +/** +* Checks if the child has the given property. +* +* Will scan up to 4 levels deep only. +* +* @method Phaser.Group#hasProperty +* @param {any} child - The child to check for the existence of the property on. +* @param {string[]} key - An array of strings that make up the property. +* @return {boolean} True if the child has the property, otherwise false. +*/ +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; + +}; + +/** +* Sets a property to the given value on the child. The operation parameter controls how the value is set. +* +* The operations are: +* - 0: set the existing value to the given value; if force is `true` a new property will be created if needed +* - 1: will add the given value to the value already present. +* - 2: will subtract the given value from the value already present. +* - 3: will multiply the value already present by the given value. +* - 4: will divide the value already present by the given value. +* +* @method Phaser.Group#setProperty +* @param {any} child - The child to set the property value on. +* @param {array} key - An array of strings that make up the property that will be set. +* @param {any} value - The value that will be set. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) { + + if (force === undefined) { force = false; } + + operation = operation || 0; + + // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration. + + // 0 = Equals + // 1 = Add + // 2 = Subtract + // 3 = Multiply + // 4 = Divide + + // We can't force a property in and the child doesn't have it, so abort. + // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too. + 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; + +}; + +/** +* Checks a property for the given value on the child. +* +* @method Phaser.Group#checkProperty +* @param {any} child - The child to check the property value on. +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} True if `child` is a child of this Group and the property was equal to value, false if not. +*/ +Phaser.Group.prototype.checkProperty = function (child, key, value, force) { + + if (force === undefined) { force = false; } + + if (this !== child.parent) + { + return false; + } + + var result = Phaser.Utils.getProperty(child, key); + + if (((result === undefined) && force) || (result !== value)) + { + return false; + } + + return true; + +}; + +/** +* Quickly set a property on a single child of this group to a new value. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#set +* @param {Phaser.Sprite} child - The child to set the property on. +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true. +* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) { + + if (force === undefined) { force = false; } + + key = key.split('.'); + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible))) + { + return this.setProperty(child, key, value, operation, force); + } + +}; + +/** +* Quickly set the same property across all children of this group to a new value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. +* If you need that ability please see `Group.setAllChildren`. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAll +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + key = key.split('.'); + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + this.setProperty(this.children[i], key, value, operation, force); + } + } + +}; + +/** +* Quickly set the same property across all children of this group, and any child Groups, to a new value. +* +* If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. +* Unlike with `setAll` the property is NOT set on child Groups itself. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAllChildren +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + if (this.children[i] instanceof Phaser.Group) + { + this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force); + } + else + { + this.setProperty(this.children[i], key.split('.'), value, operation, force); + } + } + } + +}; + +/** +* Test that the same property across all children of this group is equal to the given value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAll +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} - True if all eligible children have the given property value (but see `force`); otherwise false. +*/ +Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (!this.checkProperty(child, key, value, force)) + { + return false; + } + } + } + + return true; + +}; + +/** +* Test that at least one child of this group has the given property value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAny +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @return {boolean} - True if at least one eligible child has the given property value; otherwise false. +*/ +Phaser.Group.prototype.checkAny = function (key, value, checkAlive, checkVisible) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (this.checkProperty(child, key, value)) + { + return true; + } + } + } + + return false; + +}; + +/** +* Adds the amount to the given property on all children in this group. +* +* `Group.addAll('x', 10)` will add 10 to the child.x value for each child. +* +* @method Phaser.Group#addAll +* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. +* @param {boolean} [checkAlive] - If true the property will only be changed if the child is alive. +* @param {boolean} [checkVisible] - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 1); + +}; + +/** +* Subtracts the amount from the given property on all children in this group. +* +* `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. +* +* @method Phaser.Group#subAll +* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 2); + +}; + +/** +* Multiplies the given property by the amount on all children in this group. +* +* `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. +* +* @method Phaser.Group#multiplyAll +* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 3); + +}; + +/** +* Divides the given property by the amount on all children in this group. +* +* `Group.divideAll('x', 2)` will half the child.x value for each child. +* +* @method Phaser.Group#divideAll +* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 4); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to false. + * + * @method Phaser.Group#kill + */ +Phaser.Group.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + +}; + +/** + * Kills all children having exists=true. + * + * @method Phaser.Group#killAll + */ +Phaser.Group.prototype.killAll = function () { + + this.callAllExists('kill', true); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to true. + * + * @method Phaser.Group#revive + */ +Phaser.Group.prototype.revive = function () { + + this.alive = true; + this.exists = true; + this.visible = true; + +}; + +/** + * Revives all children having exists=false. + * + * @method Phaser.Group#reviveAll + */ +Phaser.Group.prototype.reviveAll = function () { + + this.callAllExists('revive', false); + +}; + +/** +* Calls {@link #resetChild} on each child (or each existing child). +* +* @method Phaser.Group#resetAll +* @param {number} [x] - The x coordinate to reset each child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset each child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image or texture used by the Sprite during rendering. +* @param {string|number} [frame] - The frame of a sprite sheet or texture atlas. +* @param {boolean} [checkExists=false] - Reset only existing children. +*/ +Phaser.Group.prototype.resetAll = function (x, y, key, frame, checkExists) { + + this.forEach(this.resetChild, this, checkExists, x, y, key, frame); + +}; + +/** +* Calls a function, specified by name, on all children in the group who exist (or do not exist). +* +* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. +* +* @method Phaser.Group#callAllExists +* @param {string} callback - Name of the function on the children to call. +* @param {boolean} existsValue - Only children with exists=existsValue will be called. +* @param {...any} parameter - Additional parameters that will be passed to the callback. +*/ +Phaser.Group.prototype.callAllExists = function (callback, existsValue) { + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].exists === existsValue && this.children[i][callback]) + { + this.children[i][callback].apply(this.children[i], args); + } + } + +}; + +/** +* Returns a reference to a function that exists on a child of the group based on the given callback array. +* +* @method Phaser.Group#callbackFromArray +* @param {object} child - The object to inspect. +* @param {array} callback - The array of function names. +* @param {integer} length - The size of the array (pre-calculated in callAll). +* @protected +*/ +Phaser.Group.prototype.callbackFromArray = function (child, callback, length) { + + // Kinda looks like a Christmas tree + + if (length === 1) + { + if (child[callback[0]]) + { + return child[callback[0]]; + } + } + else if (length === 2) + { + if (child[callback[0]][callback[1]]) + { + return child[callback[0]][callback[1]]; + } + } + else if (length === 3) + { + if (child[callback[0]][callback[1]][callback[2]]) + { + return child[callback[0]][callback[1]][callback[2]]; + } + } + else if (length === 4) + { + if (child[callback[0]][callback[1]][callback[2]][callback[3]]) + { + return child[callback[0]][callback[1]][callback[2]][callback[3]]; + } + } + else if (child[callback]) + { + return child[callback]; + } + + return false; + +}; + +/** +* Calls a function, specified by name, on all on children. +* +* The function is called for all children regardless if they are dead or alive (see callAllExists for different options). +* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. +* +* @method Phaser.Group#callAll +* @param {string} method - Name of the function on the child to call. Deep property lookup is supported. +* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child. +* @param {...any} args - Additional parameters that will be passed to the method. +*/ +Phaser.Group.prototype.callAll = function (method, context) { + + if (method === undefined) + { + return; + } + + // Extract the method into an array + method = method.split('.'); + + var methodLength = method.length; + + if (context === undefined || context === null || context === '') + { + context = null; + } + else + { + // Extract the context into an array + if (typeof context === 'string') + { + context = context.split('.'); + var contextLength = context.length; + } + } + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + var callback = null; + var callbackContext = null; + + for (var i = 0; i < this.children.length; i++) + { + callback = this.callbackFromArray(this.children[i], method, methodLength); + + if (context && callback) + { + callbackContext = this.callbackFromArray(this.children[i], context, contextLength); + + if (callback) + { + callback.apply(callbackContext, args); + } + } + else if (callback) + { + callback.apply(this.children[i], args); + } + } + +}; + +/** +* The core preUpdate - as called by World. +* @method Phaser.Group#preUpdate +* @protected +*/ +Phaser.Group.prototype.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + // This chunk is identical to Phaser.Component.Core.prototype.preUpdateChildren, which is not yet defined. + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + return true; + +}; + +/** +* The core update - as called by World. +* +* Children with `exists = false` are updated unless {@link #updateOnlyExistingChildren} is true. +* +* @method Phaser.Group#update +* @protected +*/ +Phaser.Group.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + var len = this.children.length; + + if (i >= len) { i = len - 1; } + + var child = this.children[i]; + + if (!this.updateOnlyExistingChildren || child.exists) { + child.update(); + } + } + +}; + +/** +* The core postUpdate - as called by World. +* @method Phaser.Group#postUpdate +* @protected +*/ +Phaser.Group.prototype.postUpdate = function () { + + // Fixed to Camera? + if (this.fixedToCamera) + { + this.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; + this.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Find children matching a certain predicate. +* +* For example: +* +* var healthyList = Group.filter(function(child, index, children) { +* return child.health > 10 ? true : false; +* }, true); +* healthyList.callAll('attack'); +* +* Note: Currently this will skip any children which are Groups themselves. +* +* @method Phaser.Group#filter +* @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third +* @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. +* @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for +*/ +Phaser.Group.prototype.filter = function (predicate, checkExists) { + + var index = -1; + var length = this.children.length; + var results = []; + + while (++index < length) + { + var child = this.children[index]; + + if (!checkExists || (checkExists && child.exists)) + { + if (predicate(child, index, this.children)) + { + results.push(child); + } + } + } + + return new Phaser.ArraySet(results); + +}; + +/** +* Call a function on each child in this group. +* +* Additional arguments for the callback can be specified after the `checkExists` parameter. For example, +* +* Group.forEach(awardBonusGold, this, true, 100, 500) +* +* would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. +* +* Note: This check will skip any children which are Groups themselves. +* +* @method Phaser.Group#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) { + + if (checkExists === undefined) { checkExists = false; } + + if (arguments.length <= 3) + { + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + callback.call(callbackContext, this.children[i]); + } + } + } + else + { + // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE. + // Using an array and pushing each element (not a slice!) is _significantly_ faster. + var args = [null]; + + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + } + } + +}; + +/** +* Call a function on each existing child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachExists +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachExists = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each alive child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachAlive +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each dead child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachDead +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachDead = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Sort the children in the group according to a particular key and ordering. +* +* Call this function to sort the group according to a particular key value and order. +* +* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. +* +* Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including +* alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. +* +* @method Phaser.Group#sort +* @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value. +* @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}). +*/ +Phaser.Group.prototype.sort = function (key, order) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + if (key === undefined) { key = 'z'; } + if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; } + + this._sortProperty = key; + + if (order === Phaser.Group.SORT_ASCENDING) + { + this.children.sort(this.ascendingSortHandler.bind(this)); + } + else + { + this.children.sort(this.descendingSortHandler.bind(this)); + } + + this.updateZ(); + +}; + +/** +* Sort the children in the group according to custom sort function. +* +* The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). +* It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. +* +* @method Phaser.Group#customSort +* @param {function} sortHandler - The custom sort function. +* @param {object} [context=undefined] - The context in which the sortHandler is called. +*/ +Phaser.Group.prototype.customSort = function (sortHandler, context) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + this.children.sort(sortHandler.bind(context)); + + this.updateZ(); + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#ascendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.ascendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return -1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return 1; + } + else + { + if (a.z < b.z) + { + return -1; + } + else + { + return 1; + } + } + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#descendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.descendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return 1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return -1; + } + else + { + return 0; + } + +}; + +/** +* Iterates over the children of the group performing one of several actions for matched children. +* +* A child is considered a match when it has a property, named `key`, whose value is equal to `value` +* according to a strict equality comparison. +* +* The result depends on the `returnType`: +* +* - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}: +* The callback, if any, is applied to all matching children. The number of matched children is returned. +* - {@link Phaser.Group.RETURN_NONE RETURN_NONE}: +* The callback, if any, is applied to all matching children. No value is returned. +* - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}: +* The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. +* If there is no matching child then null is returned. +* +* If `args` is specified it must be an array. The matched child will be assigned to the first +* element and the entire array will be applied to the callback function. +* +* @method Phaser.Group#iterate +* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' +* @param {any} value - A child matches if `child[key] === value` is true. +* @param {integer} returnType - How to iterate the children and what to return. +* @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. +* @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null. +*/ +Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) { + + if (this.children.length === 0) + { + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return 0; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return []; + } + } + + var total = 0; + + if (returnType === Phaser.Group.RETURN_ALL) + { + var output = []; + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i][key] === value) + { + total++; + + if (callback) + { + if (args) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + else + { + callback.call(callbackContext, this.children[i]); + } + } + + if (returnType === Phaser.Group.RETURN_CHILD) + { + return this.children[i]; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + output.push(this.children[i]); + } + } + } + + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return total; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return output; + } + else + { + // RETURN_CHILD or RETURN_NONE + return null; + } + +}; + +/** +* Get the first display object with the given property name and value. +* +* @method Phaser.Group#getFirst +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {DisplayObject} The first child matching the query, or `null` if none were found. +*/ +Phaser.Group.prototype.getFirst = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_CHILD); + +}; + +/** +* Get the first display object that exists, or doesn't exist. +* +* You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstExists +* @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child. +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + if (typeof exists !== 'boolean') + { + exists = true; + } + + var child = this.getFirst('exists', exists); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is alive (`child.alive === true`). +* +* This is handy for choosing a squad leader, etc. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstAlive +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', true); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is dead (`child.alive === false`). +* +* This is handy for checking if everything has been wiped out and adding to the pool as needed. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstDead +* @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', false); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. +* +* If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. +* +* The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. +* +* @method Phaser.Group#resetChild +* @param {DisplayObject} child - The child to reset and/or load the texture on. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}. +*/ +Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) { + + if (child === null) + { + return null; + } + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (x !== null && y !== null) + { + child.reset(x, y); + } + + if (key !== undefined) + { + child.loadTexture(key, frame); + } + + return child; + +}; + +/** +* Return the child at the top of this group. +* +* The top child is the child displayed (rendered) above every other child. +* +* @method Phaser.Group#getTop +* @return {any} The child at the top of the Group. +*/ +Phaser.Group.prototype.getTop = function () { + + if (this.children.length > 0) + { + return this.children[this.children.length - 1]; + } + +}; + +/** +* Returns the child at the bottom of this group. +* +* The bottom child the child being displayed (rendered) below every other child. +* +* @method Phaser.Group#getBottom +* @return {any} The child at the bottom of the Group. +*/ +Phaser.Group.prototype.getBottom = function () { + + if (this.children.length > 0) + { + return this.children[0]; + } + +}; + +/** +* Get the closest child to given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getClosestTo +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child closest to given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContext) { + + var distance = Number.MAX_VALUE; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance < distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the child furthest away from the given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getFurthestFrom +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child furthest from the given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackContext) { + + var distance = 0; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance > distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the number of children with the given property name and value. +* +* @method Phaser.Group#count +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {integer} The number of children matching the query. +*/ +Phaser.Group.prototype.count = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_TOTAL); + +}; + +/** +* Get the number of living children in this group. +* +* @method Phaser.Group#countLiving +* @return {integer} The number of children flagged as alive. +*/ +Phaser.Group.prototype.countLiving = function () { + + return this.count('alive', true); + +}; + +/** +* Get the number of dead children in this group. +* +* @method Phaser.Group#countDead +* @return {integer} The number of children flagged as dead. +*/ +Phaser.Group.prototype.countDead = function () { + + return this.count('alive', false); + +}; + +/** +* Returns a random child from the group. +* +* @method Phaser.Group#getRandom +* @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). +* @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. +* @return {any} A random child of this Group. +*/ +Phaser.Group.prototype.getRandom = function (startIndex, length) { + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = this.children.length; } + + if (length === 0) + { + return null; + } + + return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length); + +}; + +/** +* Returns a random child from the Group that has `exists` set to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only +* the first 50 children in the Group. +* +* @method Phaser.Group#getRandomExists +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up to. +* @return {any} A random child of this Group that exists. +*/ +Phaser.Group.prototype.getRandomExists = function (startIndex, endIndex) { + + var list = this.getAll('exists', true, startIndex, endIndex); + + return this.game.rnd.pick(list); + +}; + +/** +* Returns all children in this Group. +* +* You can optionally specify a matching criteria using the `property` and `value` arguments. +* +* For example: `getAll('exists', true)` would return only children that have an `exists` property equal to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return the first 50 children in the Group. +* If `property` and `value` are also specified, only children within the given index range are searched. +* +* @method Phaser.Group#getAll +* @param {string} [property] - An optional property to test against the value argument. +* @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results. +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up until. +* @return {array} - An array containing all, some, or none of the Children of this Group. +*/ +Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) { + + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var output = []; + + for (var i = startIndex; i < endIndex; i++) + { + var child = this.children[i]; + + if (property) + { + if (child[property] === value) + { + output.push(child); + } + } + else + { + output.push(child); + } + } + + return output; + +}; + +/** +* Removes the given child from this group. +* +* This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. +* +* If the group cursor was referring to the removed child it is updated to refer to the next child. +* +* @method Phaser.Group#remove +* @param {any} child - The child to remove. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child. +* @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event. +* @return {boolean} true if the child was removed from this group, otherwise false. +*/ +Phaser.Group.prototype.remove = function (child, destroy, silent) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + + if (this.children.length === 0 || this.children.indexOf(child) === -1) + { + return false; + } + + if (!silent && child.events && !child.destroyPhase) + { + child.events.onRemovedFromGroup$dispatch(child, this); + } + + var removed = this.removeChild(child); + + this.removeFromHash(child); + + this.updateZ(); + + if (this.cursor === child) + { + this.next(); + } + + if (destroy && removed) + { + removed.destroy(true); + } + + return true; + +}; + +/** +* Moves all children from this Group to the Group given. +* +* @method Phaser.Group#moveAll +* @param {Phaser.Group} group - The new Group to which the children will be moved to. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group. +* @return {Phaser.Group} The Group to which all the children were moved. +*/ +Phaser.Group.prototype.moveAll = function (group, silent) { + + if (silent === undefined) { silent = false; } + + if (this.children.length > 0 && group instanceof Phaser.Group) + { + do + { + group.add(this.children[0], silent); + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + } + + return group; + +}; + +/** +* Removes all children from this Group, but does not remove the group from its parent. +* +* The children can be optionally destroyed as they are removed. +* +* You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've +* more than one Game Object sharing the same BaseTexture. +* +* @method Phaser.Group#removeAll +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +* @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. +*/ +Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + if (destroyTexture === undefined) { destroyTexture = false; } + + if (this.children.length === 0) + { + return; + } + + do + { + if (!silent && this.children[0].events) + { + this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this); + } + + var removed = this.removeChild(this.children[0]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true, destroyTexture); + } + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + +}; + +/** +* Removes all children from this group whose index falls beteen the given startIndex and endIndex values. +* +* @method Phaser.Group#removeBetween +* @param {integer} startIndex - The index to start removing children from. +* @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +*/ +Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) { + + if (endIndex === undefined) { endIndex = this.children.length - 1; } + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = 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 (!silent && this.children[i].events) + { + this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this); + } + + var removed = this.removeChild(this.children[i]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true); + } + + if (this.cursor === this.children[i]) + { + this.cursor = null; + } + + i--; + } + + this.updateZ(); + +}; + +/** + * Places each child at a random position within the given Rectangle (or the {@link Phaser.World#bounds World bounds}). + * + * @method Phaser.Group#scatter + * @param {Phaser.Rectangle} [rect=this.game.world.bounds] - A Rectangle. If omitted {@link Phaser.World#bounds} is used. + * @param {boolean} [checkExists=false] - Place only children with exists=true. + */ +Phaser.Group.prototype.scatter = function (rect, checkExists) { + + if (rect == null) { rect = this.game.world.bounds; } + + this.forEach(function (child) { + + child.position.set(rect.randomX, rect.randomY); + + }, null, checkExists); + +}; + +/** + * Orders this Group's children randomly. + * + * This can be more efficient than calling {@link #getRandom} repeatedly. + * + * @method Phaser.Group#shuffle + */ +Phaser.Group.prototype.shuffle = function () { + + Phaser.ArrayUtils.shuffle(this.children); + this.updateZ(); + +}; + +/** +* Destroys this group. +* +* Removes all children, then removes this group from its parent and nulls references. +* +* @method Phaser.Group#destroy +* @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. +*/ +Phaser.Group.prototype.destroy = function (destroyChildren, soft) { + + if (this.game === null || this.ignoreDestroy) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (soft === undefined) { soft = false; } + + this.onDestroy.dispatch(this, destroyChildren, soft); + + this.removeAll(destroyChildren); + + this.cursor = null; + this.filters = null; + this.pendingDestroy = false; + + if (!soft) + { + if (this.parent) + { + this.parent.removeChild(this); + } + + this.game = null; + this.exists = false; + } + +}; + +/** +* Total number of existing children in the group. +* +* @name Phaser.Group#total +* @property {integer} total +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "total", { + + get: function () { + + return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); + + } + +}); + +/** +* Total number of children in this group, regardless of exists/alive status. +* +* @name Phaser.Group#length +* @property {integer} length +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "length", { + + get: function () { + + return this.children.length; + + } + +}); + +/** +* The angle of rotation of the group container, in degrees. +* +* This adjusts the group itself by modifying its local rotation transform. +* +* This has no impact on the rotation/angle properties of the children, but it will update their worldTransform +* and on-screen orientation and position. +* +* @name Phaser.Group#angle +* @property {number} angle +*/ +Object.defineProperty(Phaser.Group.prototype, "angle", { + + get: function() { + return Phaser.Math.radToDeg(this.rotation); + }, + + set: function(value) { + this.rotation = Phaser.Math.degToRad(value); + } + +}); + +/** +* The center x coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerX +* @property {number} centerX +*/ +Object.defineProperty(Phaser.Group.prototype, "centerX", { + + get: function () { + + return this.getBounds(this.parent).centerX; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.halfWidth; + + } + +}); + +/** +* The center y coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerY +* @property {number} centerY +*/ +Object.defineProperty(Phaser.Group.prototype, "centerY", { + + get: function () { + + return this.getBounds(this.parent).centerY; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.halfHeight; + + } + +}); + +/** +* The left coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#left +* @property {number} left +*/ +Object.defineProperty(Phaser.Group.prototype, "left", { + + get: function () { + + return this.getBounds(this.parent).left; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = value + offset; + + } + +}); + +/** +* The right coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#right +* @property {number} right +*/ +Object.defineProperty(Phaser.Group.prototype, "right", { + + get: function () { + + return this.getBounds(this.parent).right; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.width; + + } + +}); + +/** +* The top coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#top +* @property {number} top +*/ +Object.defineProperty(Phaser.Group.prototype, "top", { + + get: function () { + + return this.getBounds(this.parent).top; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset); + + } + +}); + +/** +* The bottom coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#bottom +* @property {number} bottom +*/ +Object.defineProperty(Phaser.Group.prototype, "bottom", { + + get: function () { + + return this.getBounds(this.parent).bottom; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.height; + + } + +}); + +/** +* Aligns this Group within another Game Object, or Rectangle, known as the +* 'container', to one of 9 possible positions. +* +* The container must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the container. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, +* `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, +* `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* container, taking into consideration rotation and scale of its children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignIn +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* Aligns this Group to the side of another Game Object, or Rectangle, known as the +* 'parent', in one of 11 possible positions. +* +* The parent must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the parent. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, +* `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, +* `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` +* and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* parent, taking into consideration rotation and scale of the children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignTo +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* A display object is any object that can be rendered in the Phaser/pixi.js scene graph: +* +* - {@link PIXI.DisplayObject} +* - {@link PIXI.DisplayObjectContainer} +* - {@link Phaser.BitmapText} +* - {@link Phaser.Creature} +* - {@link Phaser.Graphics} +* - {@link Phaser.Group} +* - {@link Phaser.FlexLayer} +* - {@link Phaser.Particles.Arcade.Emitter} +* - {@link Phaser.Physics.P2.BodyDebug} +* - {@link Phaser.SpriteBatch} +* - {@link Phaser.World} +* - {@link Phaser.Rope} +* - {@link Phaser.Stage} +* - {@link PIXI.Sprite} +* - {@link Phaser.Image} +* - {@link Phaser.Button} +* - {@link Phaser.Sprite} +* - {@link Phaser.Bullet} +* - {@link Phaser.Particle} +* - {@link Phaser.Text} +* - {@link Phaser.TilemapLayer} +* - {@link Phaser.TileSprite} +* +* @typedef {object} DisplayObject +*/ +// Documentation stub for linking. + +/** +* The x coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#x +* @property {number} x +*/ + +/** +* The y coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#y +* @property {number} y +*/ + +/** +* The angle of rotation of the group container, in radians. +* +* This will adjust the group container itself by modifying its rotation. +* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#rotation +* @property {number} rotation +*/ + +/** +* The visible state of the group. Non-visible Groups and all of their children are not rendered. +* +* @name Phaser.Group#visible +* @property {boolean} visible +*/ + +/** +* The alpha value of the group container. +* +* @name Phaser.Group#alpha +* @property {number} alpha +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* "This world is but a canvas to our imagination." - Henry David Thoreau +* +* A game has only one world. The world is an abstract place in which all game objects live. It is not bound +* by stage limits and can be any size. You look into the world via cameras. All game objects live within +* the world at world-based coordinates. By default a world is created the same size as your Stage. +* +* @class Phaser.World +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.World = function (game) { + + Phaser.Group.call(this, game, null, '__world', false); + + /** + * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. + * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. + * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. + * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. + * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height); + + /** + * @property {Phaser.Camera} camera - Camera instance. + */ + this.camera = null; + + /** + * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. + * @readonly + */ + this._definedSize = false; + + /** + * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._width = game.width; + + /** + * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._height = game.height; + + this.game.state.onStateChange.add(this.stateChange, this); + +}; + +Phaser.World.prototype = Object.create(Phaser.Group.prototype); +Phaser.World.prototype.constructor = Phaser.World; + +/** +* Initialises the game world. +* +* @method Phaser.World#boot +* @protected +*/ +Phaser.World.prototype.boot = function () { + + this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height); + + this.game.stage.addChild(this); + + this.camera.boot(); + +}; + +/** +* Called whenever the State changes or resets. +* +* It resets the world.x and world.y coordinates back to zero, +* then resets the Camera. +* +* @method Phaser.World#stateChange +* @protected +*/ +Phaser.World.prototype.stateChange = function () { + + this.x = 0; + this.y = 0; + + this.camera.reset(); + +}; + +/** +* Updates the size of this world and sets World.x/y to the given values +* The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. +* +* @method Phaser.World#setBounds +* @param {number} x - Top left most corner of the world. +* @param {number} y - Top left most corner of the world. +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.setBounds = function (x, y, width, height) { + + this._definedSize = true; + this._width = width; + this._height = height; + + this.bounds.setTo(x, y, width, height); + + this.x = x; + this.y = y; + + if (this.camera.bounds) + { + // The Camera can never be smaller than the game size + this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height)); + } + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Updates this world's width and height (but not smaller than any previous {@link #setBounds defined size}). +* +* Phaser uses this to adapt to {@link Phaser.ScaleManager#updateDimensions layout changes}. +* You probably want to use {@link #setBounds} instead. +* +* @method Phaser.World#resize +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.resize = function (width, height) { + + // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size + + if (this._definedSize) + { + if (width < this._width) + { + width = this._width; + } + + if (height < this._height) + { + height = this._height; + } + } + + this.bounds.width = width; + this.bounds.height = height; + + this.game.camera.setBoundsToWorld(); + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Destroyer of worlds. +* +* @method Phaser.World#shutdown +*/ +Phaser.World.prototype.shutdown = function () { + + // World is a Group, so run a soft destruction on this and all children. + this.destroy(true, true); + +}; + +/** +* This will take the given game object and check if its x/y coordinates fall outside of the world bounds. +* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. +* If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. +* +* Please understand there are limitations to this method. For example if you have scaled the World +* then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. +* +* @method Phaser.World#wrap +* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) { + + if (padding === undefined) { padding = 0; } + if (useBounds === undefined) { useBounds = false; } + if (horizontal === undefined) { horizontal = true; } + if (vertical === undefined) { vertical = true; } + + if (!useBounds) + { + if (horizontal && sprite.x + padding < this.bounds.x) + { + sprite.x = this.bounds.right + padding; + } + else if (horizontal && sprite.x - padding > this.bounds.right) + { + sprite.x = this.bounds.left - padding; + } + + if (vertical && sprite.y + padding < this.bounds.top) + { + sprite.y = this.bounds.bottom + padding; + } + else if (vertical && sprite.y - padding > this.bounds.bottom) + { + sprite.y = this.bounds.top - padding; + } + } + else + { + sprite.getBounds(); + + if (horizontal) + { + if ((sprite.x + sprite._currentBounds.width) < this.bounds.x) + { + sprite.x = this.bounds.right; + } + else if (sprite.x > this.bounds.right) + { + sprite.x = this.bounds.left; + } + } + + if (vertical) + { + if ((sprite.y + sprite._currentBounds.height) < this.bounds.top) + { + sprite.y = this.bounds.bottom; + } + else if (sprite.y > this.bounds.bottom) + { + sprite.y = this.bounds.top; + } + } + } + +}; + +/** +* @method Phaser.World#wrapAll +* @param {Phaser.Group} group - A group of sprites. +* @param {boolean} [checkExists=false] - Wrap only sprites having `exists=true`. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrapAll = function (group, checkExists, padding, useBounds, horizontal, vertical) { + + group.forEach(this.wrap, this, checkExists, padding, useBounds, horizontal, vertical); + +}; + +/** +* @name Phaser.World#width +* @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "width", { + + get: function () { + return this.bounds.width; + }, + + set: function (value) { + + if (value < this.game.width) + { + value = this.game.width; + } + + this.bounds.width = value; + this._width = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#height +* @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "height", { + + get: function () { + return this.bounds.height; + }, + + set: function (value) { + + if (value < this.game.height) + { + value = this.game.height; + } + + this.bounds.height = value; + this._height = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#centerX +* @property {number} centerX - Gets the X position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerX", { + + get: function () { + return this.bounds.halfWidth + this.bounds.x; + } + +}); + +/** +* @name Phaser.World#centerY +* @property {number} centerY - Gets the Y position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerY", { + + get: function () { + return this.bounds.halfHeight + this.bounds.y; + } + +}); + +/** +* @name Phaser.World#randomX +* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomX", { + + get: function () { + + if (this.bounds.x < 0) + { + return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x))); + } + else + { + return this.game.rnd.between(this.bounds.x, this.bounds.width); + } + + } + +}); + +/** +* @name Phaser.World#randomY +* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomY", { + + get: function () { + + if (this.bounds.y < 0) + { + return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y))); + } + else + { + return this.game.rnd.between(this.bounds.y, this.bounds.height); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Game object is the main controller for the entire Phaser game. It is responsible +* for handling the boot process, parsing the configuration values, creating the renderer, +* and setting-up all of the Phaser systems, such as physics, sound and input. +* Once that is complete it will start the default State, and then begin the main game loop. +* +* You can access lots of the Phaser systems via the properties on the `game` object. For +* example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on. +* +* Anywhere you can access the `game` property, you can access all of these core systems. +* For example a Sprite has a `game` property, allowing you to talk to the various parts +* of Phaser directly, without having to look after your own references. +* +* In it's most simplest form, a Phaser game can be created by providing the arguments +* to the constructor: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create }); +* ``` +* +* In the example above it is passing in a State object directly. You can also use the State +* Manager to do this: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO); +* game.state.add('Boot', BasicGame.Boot); +* game.state.add('Preloader', BasicGame.Preloader); +* game.state.add('MainMenu', BasicGame.MainMenu); +* game.state.add('Game', BasicGame.Game); +* game.state.start('Boot'); +* ``` +* +* In the example above, 4 States are added to the State Manager, and Phaser is told to +* start running the `Boot` state when it has finished initializing. There are example +* project templates you can use in the Phaser GitHub repo, inside the `resources` folder. +* +* Instead of specifying arguments you can also pass {@link GameConfig a single object} instead: +* +* ```javascript +* var config = { +* width: 800, +* height: 600, +* renderer: Phaser.AUTO, +* antialias: true, +* multiTexture: true, +* state: { +* preload: preload, +* create: create, +* update: update +* } +* } +* +* var game = new Phaser.Game(config); +* ``` +* +* @class Phaser.Game +* @constructor +* @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. +* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. +* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). +* @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body. +* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. +* @param {boolean} [transparent=false] - Use a transparent canvas background or not. +* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) { + + /** + * @property {number} id - Phaser Game ID + * @readonly + */ + this.id = Phaser.GAMES.push(this) - 1; + + /** + * @property {object} config - The Phaser.Game configuration object. + */ + this.config = null; + + /** + * @property {object} physicsConfig - The Phaser.Physics.World configuration object. + */ + this.physicsConfig = physicsConfig; + + /** + * @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted. + * @readonly + * @default + */ + this.parent = ''; + + /** + * The current Game Width in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} width + * @readonly + * @default + */ + this.width = 800; + + /** + * The current Game Height in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} height + * @readonly + * @default + */ + this.height = 600; + + /** + * The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object. + * + * @property {integer} resolution + * @readonly + * @default + */ + this.resolution = 1; + + /** + * @property {integer} _width - Private internal var. + * @private + */ + this._width = 800; + + /** + * @property {integer} _height - Private internal var. + * @private + */ + this._height = 600; + + /** + * @property {boolean} transparent - Use a transparent canvas background or not. + * @default + */ + this.transparent = false; + + /** + * @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead. + * @readonly + * @default + */ + this.antialias = true; + + /** + * Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property. + * To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game + * Configuration object with the property `multiTexture` set to true. It has to be enabled before + * Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it + * via the `game.renderer.setTexturePriority` method. + * + * @property {boolean} multiTexture + * @readonly + * @default + */ + this.multiTexture = false; + + /** + * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * @default + */ + this.preserveDrawingBuffer = false; + + /** + * Clear the Canvas each frame before rendering the display list. + * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. + * This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage. + * @property {boolean} clearBeforeRender + * @default + */ + this.clearBeforeRender = true; + + /** + * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. + * @protected + */ + this.renderer = null; + + /** + * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `render` hooks but not `preRender` or `postRender`; set {@link lockRender} to skip those as well. + * @readonly + */ + this.renderType = Phaser.AUTO; + + /** + * @property {Phaser.StateManager} state - The StateManager. + */ + this.state = null; + + /** + * @property {boolean} isBooted - Whether the game engine is booted, aka available. + * @readonly + */ + this.isBooted = false; + + /** + * @property {boolean} isRunning - Is game running or paused? + * @readonly + */ + this.isRunning = false; + + /** + * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout + * @protected + */ + this.raf = null; + + /** + * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. + */ + this.make = null; + + /** + * @property {Phaser.Cache} cache - Reference to the assets cache. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - Reference to the input manager + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - Reference to the assets loader. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - Reference to the math helper. + */ + this.math = null; + + /** + * @property {Phaser.Net} net - Reference to the network class. + */ + this.net = null; + + /** + * @property {Phaser.ScaleManager} scale - The game scale manager. + */ + this.scale = null; + + /** + * @property {Phaser.SoundManager} sound - Reference to the sound manager. + */ + this.sound = null; + + /** + * @property {Phaser.Stage} stage - Reference to the stage. + */ + this.stage = null; + + /** + * @property {Phaser.Time} time - Reference to the core game clock. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - Reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - Reference to the world. + */ + this.world = null; + + /** + * @property {Phaser.Physics} physics - Reference to the physics manager. + */ + this.physics = null; + + /** + * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. + */ + this.plugins = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. + */ + this.rnd = null; + + /** + * @property {Phaser.Device} device - Contains device information and capabilities. + */ + this.device = Phaser.Device; + + /** + * @property {Phaser.Camera} camera - A handy reference to world.camera. + */ + this.camera = null; + + /** + * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) + */ + this.context = null; + + /** + * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. + */ + this.debug = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. + */ + this.particles = null; + + /** + * @property {Phaser.Create} create - The Asset Generator. + */ + this.create = null; + + /** + * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. + * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. + * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. + * @property {boolean} lockRender + * @default + */ + this.lockRender = false; + + /** + * @property {boolean} pendingDestroy - Destroy the game at the next update. + * @default + */ + this.pendingDestroy = false; + + /** + * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). + * @default + * @readonly + */ + this.stepping = false; + + /** + * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. + * @default + * @readonly + */ + this.pendingStep = false; + + /** + * @property {number} stepCount - When stepping is enabled this contains the current step cycle. + * @default + * @readonly + */ + this.stepCount = 0; + + /** + * @property {Phaser.Signal} onPause - This event is fired when the game pauses. + */ + this.onPause = null; + + /** + * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. + */ + this.onResume = null; + + /** + * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). + */ + this.onBlur = null; + + /** + * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). + */ + this.onFocus = null; + + /** + * @property {boolean} _paused - Is game paused? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _codePaused - Was the game paused via code or a visibility change? + * @private + */ + this._codePaused = false; + + /** + * The ID of the current/last logic update applied this animation frame, starting from 0. + * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` + * @property {integer} currentUpdateID + * @protected + */ + this.currentUpdateID = 0; + + /** + * Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed). + * @property {integer} updatesThisFrame + * @protected + */ + this.updatesThisFrame = 1; + + /** + * Number of renders expected to occur this animation frame. May be 0 if {@link #dropFrames is on} or {@link #forceSingleRender} is off; otherwise it will be 1. + * @property {integer} updatesThisFrame + * @protected + */ + this.rendersThisFrame = 1; + + /** + * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. + * @private + */ + this._deltaTime = 0; + + /** + * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. + * @private + */ + this._lastCount = 0; + + /** + * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. + * @private + */ + this._spiraling = 0; + + /** + * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) + * @private + */ + this._kickstart = true; + + /** + * If the game is struggling to maintain the desired FPS, this signal will be dispatched. + * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. + * @property {Phaser.Signal} fpsProblemNotifier + * @public + */ + this.fpsProblemNotifier = new Phaser.Signal(); + + /** + * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? You can toggle it on the fly. + */ + this.forceSingleUpdate = true; + + /** + * @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update? (During spiraling conditions, {@link #dropFrames} is used instead.) + */ + this.forceSingleRender = true; + + /** + * @property {boolean} dropFrames - When {@link #forceSingleUpdate} is off, skip {@link #updateRender rendering} if logic updates are spiraling upwards. + */ + this.dropFrames = false; + + /** + * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. + * @private + */ + this._nextFpsNotification = 0; + + // Parse the configuration object (if any) + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + this.parseConfig(arguments[0]); + } + else + { + this.config = { enableDebug: true }; + + if (typeof width !== 'undefined') + { + this._width = width; + } + + if (typeof height !== 'undefined') + { + this._height = height; + } + + if (typeof renderer !== 'undefined') + { + 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); + } + + this.device.whenReady(this.boot, this); + + return this; + +}; + +/** +* A configuration object for {@link Phaser.Game}. +* +* @typedef {object} GameConfig +* @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}. +* @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}. +* @property {number|string} [GameConfig.antialias=true] +* @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}. +* @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in. +* @property {string} [GameConfig.canvasId] - `id` attribute value to assign to the game canvas. +* @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas. +* @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}. +* @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange} +* @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing. +* @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production. +* @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO. +* @property {boolean} [GameConfig.forceSetTimeout] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeOut} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available. +* @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen. +* @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked. +* @property {number|string} [GameConfig.height=600] +* @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`. +* @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected. +* @property {object} [GameConfig.physicsConfig] +* @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering. +* @property {number} [GameConfig.renderer=Phaser.AUTO] +* @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels. +* @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices. +* @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen. +* @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}. +* @property {object} [GameConfig.state] +* @property {boolean} [GameConfig.transparent=false] +* @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode. +* @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode. +* @property {number|string} [GameConfig.width=800] +*/ +// Documentation stub for linking. + +Phaser.Game.prototype = { + + /** + * Parses a Game configuration object. + * + * @method Phaser.Game#parseConfig + * @protected + */ + parseConfig: function (config) { + + this.config = config; + + if (config['enableDebug'] === undefined) + { + this.config.enableDebug = true; + } + + if (config['width']) + { + this._width = config['width']; + } + + if (config['height']) + { + this._height = config['height']; + } + + if (config['renderer']) + { + this.renderType = config['renderer']; + } + + if (config['parent']) + { + this.parent = config['parent']; + } + + if (config['transparent'] !== undefined) + { + this.transparent = config['transparent']; + } + + if (config['antialias'] !== undefined) + { + this.antialias = config['antialias']; + } + + if (config['multiTexture'] !== undefined) + { + this.multiTexture = config['multiTexture']; + } + + if (config['resolution']) + { + this.resolution = config['resolution']; + } + + if (config['preserveDrawingBuffer'] !== undefined) + { + this.preserveDrawingBuffer = config['preserveDrawingBuffer']; + } + + 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); + + }, + + /** + * Initialize engine sub modules and start the game. + * + * @method Phaser.Game#boot + * @protected + */ + boot: function () { + + if (this.isBooted) + { + return; + } + + this.onPause = new Phaser.Signal(); + this.onResume = new Phaser.Signal(); + this.onBlur = new Phaser.Signal(); + this.onFocus = new Phaser.Signal(); + + this.isBooted = true; + + PIXI.game = this; + + this.math = Phaser.Math; + + this.scale = new Phaser.ScaleManager(this, this._width, this._height); + this.stage = new Phaser.Stage(this); + + this.setUpRenderer(); + + 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.create = new Phaser.Create(this); + this.plugins = new Phaser.PluginManager(this); + this.net = new Phaser.Net(this); + + this.time.boot(); + this.stage.boot(); + this.world.boot(); + this.scale.boot(); + this.input.boot(); + this.sound.boot(); + this.state.boot(); + + if (this.config['enableDebug']) + { + this.debug = new Phaser.Utils.Debug(this); + this.debug.boot(); + } + else + { + this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {}, isDisabled: true }; + } + + 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._kickstart = true; + + if (window['focus']) + { + if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus)) + { + window.focus(); + } + } + + if (this.config['disableStart']) + { + return; + } + + if (this.cache.isReady) + { + this.raf.start(); + } + else + { + this.cache.onReady.addOnce(function () { + this.raf.start(); + }, this); + } + + }, + + /** + * Displays a Phaser version debug header in the console. + * + * @method Phaser.Game#showDebugHeader + * @protected + */ + showDebugHeader: function () { + + if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner) + { + return; + } + + 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.ie) // https://developer.mozilla.org/en-US/docs/Web/API/Console/log#Browser_compatibility + { + var args = [ + '%c %c %c Phaser CE v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665', + 'background: #fb8cb3', + 'background: #d44a52', + 'color: #ffffff; background: #871905;', + 'background: #d44a52', + 'background: #fb8cb3', + 'background: #ffffff' + ]; + + for (var i = 0; i < 3; i++) + { + if (i < c) + { + args.push('color: #ff2424; background: #fff'); + } + else + { + args.push('color: #959595; background: #fff'); + } + } + + console.log.apply(console, args); + } + else if (window['console']) + { + console.log('Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' | http://phaser.io'); + } + + }, + + /** + * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. + * + * @method Phaser.Game#setUpRenderer + * @protected + */ + setUpRenderer: function () { + + if (!this.device.canvas) + { + // Nothing else to do + throw new Error('Phaser.Game - Cannot create Canvas 2d context, aborting.'); + } + + if (this.config['canvas']) + { + this.canvas = this.config['canvas']; + } + else + { + this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true); + } + + if (this.config['canvasStyle']) + { + this.canvas.style = this.config['canvasStyle']; + } + else + { + this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; + } + + if (this.config['crisp']) + { + Phaser.Canvas.setImageRenderingCrisp(this.canvas); + } + + if ((this.renderType === Phaser.WEBGL) || + (this.renderType === Phaser.WEBGL_MULTI) || + (this.renderType === Phaser.AUTO && this.device.webGL)) + { + if (this.multiTexture || this.renderType === Phaser.WEBGL_MULTI) + { + PIXI.enableMultiTexture(); + this.multiTexture = true; + } + + try + { + this.renderer = new PIXI.WebGLRenderer(this, this.config); + this.renderType = Phaser.WEBGL; + this.context = null; + this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); + this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); + } + catch (webGLRendererError) + { + this.renderer = null; + this.multiTexture = false; + PIXI._enableMultiTextureToggle = false; + + if (this.renderType === Phaser.WEBGL) + { + // No fallback + throw webGLRendererError; + } + } + } + + if (!this.renderer) + { + this.renderer = new PIXI.CanvasRenderer(this, this.config); + this.context = this.renderer.context; + + if (this.renderType === Phaser.AUTO) + { + this.renderType = Phaser.CANVAS; + } + } + + if (this.device.cocoonJS) + { + this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false; + } + + if (this.renderType !== Phaser.HEADLESS) + { + this.stage.smoothed = this.antialias; + + Phaser.Canvas.addToDOM(this.canvas, this.parent, false); + Phaser.Canvas.setTouchAction(this.canvas); + } + + }, + + /** + * Handles WebGL context loss. + * + * @method Phaser.Game#contextLost + * @private + * @param {Event} event - The webglcontextlost event. + */ + contextLost: function (event) { + + event.preventDefault(); + + this.renderer.contextLost = true; + + }, + + /** + * Handles WebGL context restoration. + * + * @method Phaser.Game#contextRestored + * @private + */ + contextRestored: function () { + + this.renderer.initContext(); + + this.cache.clearGLTextures(); + + this.renderer.contextLost = false; + + }, + + /** + * The core game loop. + * + * @method Phaser.Game#update + * @protected + * @param {number} time - The current time as provided by RequestAnimationFrame. + */ + update: function (time) { + + if (this.pendingDestroy) + { + this.destroy(); + return; + } + + this.time.update(time); + + if (this._kickstart) + { + this.updateLogic(this.time.desiredFpsMult); + + // call the game render update exactly once every frame + this.updateRender(this.time.slowMotion * this.time.desiredFps); + + this._kickstart = false; + + return; + } + + // if the logic time is spiraling upwards, skip a frame entirely + if (this._spiraling > 1 && !this.forceSingleUpdate) + { + // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate + if (this.time.time > this._nextFpsNotification) + { + // only permit one fps notification per 10 seconds + this._nextFpsNotification = this.time.time + 10000; + + // dispatch the notification signal + this.fpsProblemNotifier.dispatch(); + } + + // reset the _deltaTime accumulator which will cause all pending late updates to be permanently skipped + this._deltaTime = 0; + this._spiraling = 0; + + if (this.dropFrames) + { + this.rendersThisFrame = 0; + } + else + { + this.updateRender(this.time.slowMotion * this.time.desiredFps); + this.rendersThisFrame = 1; + } + } + else + { + // step size taking into account the slow motion speed + var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps; + + // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals + this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0); + + // call the game update logic multiple times if necessary to "catch up" with dropped frames + // unless forceSingleUpdate is true + var count = 0; + + this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); + + if (this.forceSingleUpdate) + { + this.updatesThisFrame = Math.min(1, this.updatesThisFrame); + } + + if (this.forceSingleRender) + { + this.rendersThisFrame = 1; + } + else + { + this.rendersThisFrame = Math.min(1, this.updatesThisFrame); + } + + while (this._deltaTime >= slowStep) + { + this._deltaTime -= slowStep; + this.currentUpdateID = count; + + this.updateLogic(this.time.desiredFpsMult); + + count++; + + if (this.forceSingleUpdate && count === 1) + { + break; + } + else + { + this.time.refresh(); + } + } + + // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly) + if (count > this._lastCount) + { + this._spiraling++; + } + else if (count < this._lastCount) + { + // looks like it caught up successfully, reset the spiral alert counter + this._spiraling = 0; + } + + this._lastCount = count; + + if (this.rendersThisFrame > 0) + { + this.updateRender(this._deltaTime / slowStep); + } + } + + }, + + /** + * Updates all logic subsystems in Phaser. Called automatically by Game.update. + * + * @method Phaser.Game#updateLogic + * @protected + * @param {number} timeStep - The current timeStep value as determined by Game.update. + */ + updateLogic: function (timeStep) { + + if (!this._paused && !this.pendingStep) + { + if (this.stepping) + { + this.pendingStep = true; + } + + this.time.countUpdate(); + + this.scale.preUpdate(); + this.debug.preUpdate(); + this.camera.preUpdate(); + this.physics.preUpdate(); + this.state.preUpdate(timeStep); + this.plugins.preUpdate(timeStep); + this.stage.preUpdate(); + + this.state.update(); + this.stage.update(); + this.tweens.update(); + this.sound.update(); + this.input.update(); + this.physics.update(); + this.plugins.update(); + + this.stage.postUpdate(); + this.plugins.postUpdate(); + } + else + { + // Scaling and device orientation changes are still reflected when paused. + this.scale.pauseUpdate(); + this.state.pauseUpdate(timeStep); + this.debug.preUpdate(); + this.input.pauseUpdate(); + } + + this.stage.updateTransform(); + + }, + + /** + * Runs the Render cycle. + * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. + * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. + * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. + * After this State.render is called. Any rendering that happens here will take place on-top of the display list. + * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. + * This method is called automatically by Game.update, you don't need to call it directly. + * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. + * Phaser will only render when this boolean is `false`. + * + * @method Phaser.Game#updateRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + updateRender: function (elapsedTime) { + + if (this.lockRender) + { + return; + } + + this.time.countRender(); + + this.state.preRender(elapsedTime); + + if (this.renderType !== Phaser.HEADLESS) + { + this.renderer.render(this.stage); + + this.plugins.render(elapsedTime); + + this.state.render(elapsedTime); + } + + this.plugins.postRender(elapsedTime); + + }, + + /** + * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) + * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! + * + * @method Phaser.Game#enableStep + */ + enableStep: function () { + + this.stepping = true; + this.pendingStep = false; + this.stepCount = 0; + + }, + + /** + * Disables core game loop stepping. + * + * @method Phaser.Game#disableStep + */ + disableStep: function () { + + this.stepping = false; + this.pendingStep = false; + + }, + + /** + * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. + * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. + * + * @method Phaser.Game#step + */ + step: function () { + + this.pendingStep = false; + this.stepCount++; + + }, + + /** + * Nukes the entire game from orbit. + * + * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. + * + * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM + * and resets the PIXI default renderer. + * + * To destroy the game during an update callback, set {@link #pendingDestroy} instead. + * + * @method Phaser.Game#destroy + */ + destroy: function () { + + this.raf.stop(); + + if (this.debug.destroy) + { + this.debug.destroy(); + } + + this.state.destroy(); + this.sound.destroy(); + this.scale.destroy(); + this.stage.destroy(); + this.input.destroy(); + this.physics.destroy(); + this.plugins.destroy(); + + this.debug = null; + this.state = null; + this.sound = null; + this.scale = null; + this.stage = null; + this.input = null; + this.physics = null; + this.plugins = null; + + this.cache = null; + this.load = null; + this.time = null; + this.world = null; + + this.isBooted = false; + + this.renderer.destroy(false); + + Phaser.Canvas.removeFromDOM(this.canvas); + + PIXI.defaultRenderer = null; + + Phaser.GAMES[this.id] = null; + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gamePaused + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gamePaused: function (event) { + + // If the game is already paused it was done via game code, so don't re-pause it + if (!this._paused) + { + this._paused = true; + + this.time.gamePaused(); + + if (this.sound.muteOnPause) + { + this.sound.setMute(); + } + + this.onPause.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = true; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gameResumed + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gameResumed: function (event) { + + // Game is paused, but wasn't paused via code, so resume it + if (this._paused && !this._codePaused) + { + this._paused = false; + + this.time.gameResumed(); + + this.input.reset(); + + if (this.sound.muteOnPause) + { + this.sound.unsetMute(); + } + + this.onResume.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = false; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusLoss + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusLoss: function (event) { + + this.onBlur.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gamePaused(event); + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusGain + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusGain: function (event) { + + this.onFocus.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gameResumed(event); + } + + } + +}; + +Phaser.Game.prototype.constructor = Phaser.Game; + +/** +* The paused state of the Game. A paused game doesn't update any of its subsystems. +* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. +* @name Phaser.Game#paused +* @property {boolean} paused - Gets and sets the paused state of the Game. +*/ +Object.defineProperty(Phaser.Game.prototype, "paused", { + + get: function () { + return this._paused; + }, + + set: function (value) { + + if (value === true) + { + if (this._paused === false) + { + this._paused = true; + this.sound.setMute(); + this.time.gamePaused(); + this.onPause.dispatch(this); + } + this._codePaused = true; + } + else + { + if (this._paused) + { + this._paused = false; + this.input.reset(); + this.sound.unsetMute(); + this.time.gameResumed(); + this.onResume.dispatch(this); + } + this._codePaused = false; + } + + } + +}); + +/** + * + * "Deleted code is debugged code." - Jeff Sickel + * + * ヽ(〃^▽^〃)ノ + * +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. +* The Input manager is updated automatically by the core game loop. +* +* @class Phaser.Input +* @constructor +* @param {Phaser.Game} game - Current game instance. +*/ +Phaser.Input = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. + * @default + */ + this.hitCanvas = null; + + /** + * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. + * @default + */ + this.hitContext = null; + + /** + * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. + * To add a callback to this array please use `Input.addMoveCallback`. + * @property {array} moveCallbacks + * @protected + */ + this.moveCallbacks = []; + + /** + * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandler = null; + + /** + * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandlerContext = null; + + /** + * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. + * @default + */ + this.pollRate = 0; + + /** + * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. + * + * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. + * @default + */ + this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE; + + /** + * @property {Phaser.Point} position - A point object representing the current position of the Pointer. + * @default + */ + this.position = null; + + /** + * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. + */ + this.speed = null; + + /** + * A Circle object centered on the x/y screen coordinates of the Input. + * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. + * @property {Phaser.Circle} circle + */ + this.circle = null; + + /** + * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. + */ + this.scale = null; + + /** + * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1. + * @default -1 (Limited by total pointers.) + */ + this.maxPointers = -1; + + /** + * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. + * @default + */ + this.tapRate = 200; + + /** + * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. + * @default + */ + this.doubleTapRate = 300; + + /** + * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. + * @default + */ + this.holdRate = 2000; + + /** + * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. + * @default + */ + this.justPressedRate = 200; + + /** + * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . + * @default + */ + this.justReleasedRate = 200; + + /** + * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. + * The history is cleared each time the Pointer is pressed down. + * The history is updated at the rate specified in Input.pollRate + * @property {boolean} recordPointerHistory + * @default + */ + this.recordPointerHistory = false; + + /** + * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. + * @default + */ + this.recordRate = 100; + + /** + * The total number of entries that can be recorded into the Pointer objects tracking history. + * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. + * @property {number} recordLimit + * @default + */ + this.recordLimit = 100; + + /** + * An array of callbacks that will be fired every time a native touch start or touch end event (pointerdown or pointerup when using Pointer events) is received from the browser. + * This is used internally to handle audio and video unlocking on mobile devices. + * To add a callback to this array please use `Input.addTouchLockCallback`. + * @property {array} touchLockCallbacks + * @protected + */ + this.touchLockCallbacks = []; + + /** + * @property {Phaser.Pointer} pointer1 - A Pointer object. + */ + this.pointer1 = null; + + /** + * @property {Phaser.Pointer} pointer2 - A Pointer object. + */ + this.pointer2 = null; + + /** + * @property {Phaser.Pointer} pointer3 - A Pointer object. + */ + this.pointer3 = null; + + /** + * @property {Phaser.Pointer} pointer4 - A Pointer object. + */ + this.pointer4 = null; + + /** + * @property {Phaser.Pointer} pointer5 - A Pointer object. + */ + this.pointer5 = null; + + /** + * @property {Phaser.Pointer} pointer6 - A Pointer object. + */ + this.pointer6 = null; + + /** + * @property {Phaser.Pointer} pointer7 - A Pointer object. + */ + this.pointer7 = null; + + /** + * @property {Phaser.Pointer} pointer8 - A Pointer object. + */ + this.pointer8 = null; + + /** + * @property {Phaser.Pointer} pointer9 - A Pointer object. + */ + this.pointer9 = null; + + /** + * @property {Phaser.Pointer} pointer10 - A Pointer object. + */ + this.pointer10 = null; + + /** + * An array of non-mouse pointers that have been added to the game. + * The properties `pointer1..N` are aliases for `pointers[0..N-1]`. + * @property {Phaser.Pointer[]} pointers + * @public + * @readonly + */ + this.pointers = []; + + /** + * The most recently active Pointer object. + * + * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. + * + * @property {Phaser.Pointer} activePointer + */ + this.activePointer = null; + + /** + * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. + * + * @property {Pointer} mousePointer + */ + this.mousePointer = null; + + /** + * The Mouse Input manager. + * + * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Mouse} mouse + */ + this.mouse = null; + + /** + * The Keyboard Input manager. + * + * @property {Phaser.Keyboard} keyboard + */ + this.keyboard = null; + + /** + * The Touch Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Touch} touch + */ + this.touch = null; + + /** + * The MSPointer Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.MSPointer} mspointer + */ + this.mspointer = null; + + /** + * The Gamepad Input manager. + * + * @property {Phaser.Gamepad} gamepad + */ + this.gamepad = null; + + /** + * If the Input Manager has been reset locked then all calls made to InputManager.reset, + * such as from a State change, are ignored. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is pressed down. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onDown + */ + this.onDown = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is released. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onUp + */ + this.onUp = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is tapped. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {boolean} True if this was a double tap. + * + * @property {Phaser.Signal} onTap + */ + this.onTap = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is held down. + * It is sent one argument: + * + * - {Phaser.Pointer} The pointer that caused the event. + * + * @property {Phaser.Signal} onHold + */ + this.onHold = null; + + /** + * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. + * This is useful when stacking UI layers. Set to zero to disable. + * @property {number} minPriorityID + * @default + */ + this.minPriorityID = 0; + + /** + * A list of interactive objects. The InputHandler components add and remove themselves from this list. + * @property {Phaser.ArraySet} interactiveItems + */ + this.interactiveItems = new Phaser.ArraySet(); + + /** + * @property {Phaser.Point} _localPoint - Internal cache var. + * @private + */ + this._localPoint = new Phaser.Point(); + + /** + * @property {number} _pollCounter - Internal var holding the current poll counter. + * @private + */ + this._pollCounter = 0; + + /** + * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. + * @private + */ + this._oldPosition = null; + + /** + * @property {number} _x - x coordinate of the most recent Pointer event + * @private + */ + this._x = 0; + + /** + * @property {number} _y - Y coordinate of the most recent Pointer event + * @private + */ + this._y = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_TOUCH_COMBINE = 2; + +/** +* The maximum number of pointers that can be added. This excludes the mouse pointer. +* @constant +* @type {integer} +*/ +Phaser.Input.MAX_POINTERS = 10; + +Phaser.Input.prototype = { + + /** + * Starts the Input Manager running. + * + * @method Phaser.Input#boot + * @protected + */ + boot: function () { + + this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR); + this.addPointer(); + this.addPointer(); + + this.mouse = new Phaser.Mouse(this.game); + this.touch = new Phaser.Touch(this.game); + this.mspointer = new Phaser.MSPointer(this.game); + + if (Phaser.Keyboard) + { + this.keyboard = new Phaser.Keyboard(this.game); + } + + if (Phaser.Gamepad) + { + this.gamepad = new Phaser.Gamepad(this.game); + } + + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + + this.scale = new Phaser.Point(1, 1); + this.speed = new Phaser.Point(); + this.position = new Phaser.Point(); + this._oldPosition = new Phaser.Point(); + + this.circle = new Phaser.Circle(0, 0, 44); + + this.activePointer = this.mousePointer; + + this.hitCanvas = Phaser.CanvasPool.create(this, 1, 1); + this.hitContext = this.hitCanvas.getContext('2d'); + + this.mouse.start(); + if (!this.game.device.mspointer) + { + // Chrome >= 55 fires both PointerEvent and TouchEvent. + // Pick only one. + this.touch.start(); + } + this.mspointer.start(); + this.mousePointer.active = true; + + if (this.keyboard) + { + this.keyboard.start(); + } + + var _this = this; + + this._onClickTrampoline = function (event) { + _this.onClickTrampoline(event); + }; + + this.game.canvas.addEventListener('click', this._onClickTrampoline, false); + + }, + + /** + * Stops all of the Input Managers from running. + * + * @method Phaser.Input#destroy + */ + destroy: function () { + + this.mouse.stop(); + this.touch.stop(); + this.mspointer.stop(); + + if (this.keyboard) + { + this.keyboard.stop(); + } + + if (this.gamepad) + { + this.gamepad.stop(); + } + + this.moveCallbacks = []; + + Phaser.CanvasPool.remove(this); + + this.game.canvas.removeEventListener('click', this._onClickTrampoline); + + }, + + /** + * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. + * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to + * interact with. It works by polling all of the valid game objects, and then slowly discounting those + * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). + * + * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid + * for input and overlap with the Pointer. If you need fine-grained control over which of the items is + * selected then you can use this callback to do so. + * + * The callback will be sent 3 parameters: + * + * 1) A reference to the Phaser.Pointer object that is processing the Items. + * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. + * 3) The current 'favorite' candidate, based on its priorityID and position in the display list. + * + * Your callback MUST return one of the candidates sent to it. + * + * @method Phaser.Input#setInteractiveCandidateHandler + * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. + * @param {object} context - The context in which the callback will be called. + */ + setInteractiveCandidateHandler: function (callback, context) { + + this.customCandidateHandler = callback; + this.customCandidateHandlerContext = context; + + }, + + /** + * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. + * + * The callback will be sent 4 parameters: + * + * A reference to the Phaser.Pointer object that moved, + * The x position of the pointer, + * The y position, + * A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down). + * + * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best + * to only use if you've limited input to a single pointer (i.e. mouse or touch). + * + * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. + * + * @method Phaser.Input#addMoveCallback + * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. + * @param {object} context - The context in which the callback will be called. + */ + addMoveCallback: function (callback, context) { + + this.moveCallbacks.push({ callback: callback, context: context }); + + }, + + + /** + * Adds a callback that is fired when a browser touchstart/pointerdown or touchend/pointerup event is received. + * + * This is used internally to handle audio and video unlocking on mobile devices. + * + * If the callback returns 'true' then the callback is automatically deleted once invoked. + * + * The callback is added to the {@link #touchLockCallbacks} array and should be removed with {@link #removeTouchLockCallback}. + * + * @method Phaser.Input#addTouchLockCallback + * @param {function} callback - The callback that will be called when a touchstart event is received. + * @param {object} context - The context in which the callback will be called. + * @param {boolean} [onEnd=false] - Will the callback fire on a touchstart/pointerdown (default) or touchend/pointerup event? + */ + addTouchLockCallback: function (callback, context, onEnd) { + + if (onEnd === undefined) { onEnd = false; } + + this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd }); + + }, + + /** + * Removes the callback at the defined index from the {@link #touchLockCallbacks} array + * + * @method Phaser.Input#removeTouchLockCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + * @return {boolean} True if the callback was deleted, otherwise false. + */ + removeTouchLockCallback: function (callback, context) { + + var i = this.touchLockCallbacks.length; + + while (i--) + { + if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context) + { + this.touchLockCallbacks.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Execute any {@link #touchLockCallbacks} of the given type. + * + * @method Phaser.Input#executeTouchLockCallbacks + * @private + * @param {boolean} onEnd - Execute the touchend/pointerup callbacks (true) or the touchstart/pointerdown callbacks (false). Required! + * @param {Event} event - The native event from the browser. + */ + executeTouchLockCallbacks: function (onEnd, event) { + var i = this.touchLockCallbacks.length; + + while (i--) + { + var cb = this.touchLockCallbacks[i]; + + if (cb.onEnd === onEnd && cb.callback.call(cb.context, this, event)) + { + this.touchLockCallbacks.splice(i, 1); + } + } + }, + + /** + * Removes the callback from the Phaser.Input.moveCallbacks array. + * + * @method Phaser.Input#deleteMoveCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + */ + deleteMoveCallback: function (callback, context) { + + var i = this.moveCallbacks.length; + + while (i--) + { + if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context) + { + this.moveCallbacks.splice(i, 1); + return; + } + } + + }, + + /** + * Add a new Pointer object to the Input Manager. + * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. + * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). + * + * @method Phaser.Input#addPointer + * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. + */ + addPointer: function () { + + if (this.pointers.length >= Phaser.Input.MAX_POINTERS) + { + console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached."); + return null; + } + + var id = this.pointers.length + 1; + var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.CONTACT); + + this.pointers.push(pointer); + this['pointer' + id] = pointer; + + return pointer; + + }, + + /** + * Updates the Input Manager. Called by the core Game loop. + * + * @method Phaser.Input#update + * @protected + */ + update: function () { + + if (this.keyboard) + { + this.keyboard.update(); + } + + if (this.pollRate > 0 && this._pollCounter < this.pollRate) + { + this._pollCounter++; + return; + } + + this.speed.x = this.position.x - this._oldPosition.x; + this.speed.y = this.position.y - this._oldPosition.y; + + this._oldPosition.copyFrom(this.position); + this.mousePointer.update(); + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].update(); + } + + this._pollCounter = 0; + + }, + + /** + * Update method while paused. + * + * @method Phaser.Input#pauseUpdate + * @private + */ + pauseUpdate: function () { + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + }, + + /** + * Reset all of the Pointers and Input states. + * + * The optional `hard` parameter will reset any events or callbacks that may be bound. + * Input.reset is called automatically during a State change or if a game loses focus / visibility. + * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. + * + * @method Phaser.Input#reset + * @public + * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. + */ + reset: function (hard) { + + if (!this.game.isBooted || this.resetLocked) + { + return; + } + + if (hard === undefined) { hard = false; } + + this.mousePointer.reset(); + + if (this.keyboard) + { + this.keyboard.reset(hard); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].reset(); + } + + if (this.game.canvas.style.cursor !== 'none') + { + this.game.canvas.style.cursor = ''; + } + + if (hard) + { + this.onDown.dispose(); + this.onUp.dispose(); + this.onTap.dispose(); + this.onHold.dispose(); + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + this.moveCallbacks = []; + } + + this._pollCounter = 0; + + }, + + /** + * Resets the speed and old position properties. + * + * @method Phaser.Input#resetSpeed + * @param {number} x - Sets the oldPosition.x value. + * @param {number} y - Sets the oldPosition.y value. + */ + resetSpeed: function (x, y) { + + this._oldPosition.setTo(x, y); + this.speed.setTo(0, 0); + + }, + + /** + * Find the first free Pointer object and start it, passing in the event data. + * This is called automatically by Phaser.Touch and Phaser.MSPointer. + * + * @method Phaser.Input#startPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. + */ + startPointer: function (event) { + + if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers) + { + return null; + } + + if (!this.pointer1.active) + { + return this.pointer1.start(event); + } + + if (!this.pointer2.active) + { + return this.pointer2.start(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (!pointer.active) + { + return pointer.start(event); + } + } + + return null; + + }, + + /** + * Updates the matching Pointer object, passing in the event data. + * This is called automatically and should not normally need to be invoked. + * + * @method Phaser.Input#updatePointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. + */ + updatePointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.move(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.move(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.move(event); + } + } + + return null; + + }, + + /** + * Stops the matching Pointer object, passing in the event data. + * + * @method Phaser.Input#stopPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. + */ + stopPointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.stop(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.stop(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.stop(event); + } + } + + return null; + + }, + + /** + * Returns the total number of active pointers, not exceeding the specified limit + * + * @name Phaser.Input#countActivePointers + * @private + * @property {integer} [limit=(max pointers)] - Stop counting after this. + * @return {integer} The number of active pointers, or limit - whichever is less. + */ + countActivePointers: function (limit) { + + if (limit === undefined) { limit = this.pointers.length; } + + var count = limit; + + for (var i = 0; i < this.pointers.length && count > 0; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active) + { + count--; + } + } + + return (limit - count); + + }, + + /** + * Get the first Pointer with the given active state. + * + * @method Phaser.Input#getPointer + * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. + */ + getPointer: function (isActive) { + + if (isActive === undefined) { isActive = false; } + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active === isActive) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `identifier` property matches the given identifier value. + * + * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down, and is not fixed once set. + * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. + * + * @method Phaser.Input#getPointerFromIdentifier + * @param {number} identifier - The Pointer.identifier value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromIdentifier: function (identifier) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.identifier === identifier) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `pointerId` property matches the given value. + * + * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down if the browser recycles it. + * + * @method Phaser.Input#getPointerFromId + * @param {number} pointerId - The `pointerId` (not 'id') value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromId: function (pointerId) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.pointerId === pointerId) + { + return pointer; + } + } + + return null; + + }, + + /** + * This will return the local coordinates of the specified displayObject based on the given Pointer. + * + * @method Phaser.Input#getLocalPosition + * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. + * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. + * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. + */ + getLocalPosition: function (displayObject, pointer, output) { + + if (output === undefined) { output = new Phaser.Point(); } + + var wt = displayObject.worldTransform; + var id = 1 / (wt.a * wt.d + wt.c * -wt.b); + + return output.setTo( + wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id, + wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id + ); + + }, + + /** + * Tests if the pointer hits the given object. + * + * @method Phaser.Input#hitTest + * @param {DisplayObject} displayObject - The displayObject to test for a hit. + * @param {Phaser.Pointer} pointer - The pointer to use for the test. + * @param {Phaser.Point} localPoint - The local translated point. + */ + hitTest: function (displayObject, pointer, localPoint) { + + if (!displayObject.worldVisible) + { + return false; + } + + this.getLocalPosition(displayObject, pointer, this._localPoint); + + localPoint.copyFrom(this._localPoint); + + if (displayObject.hitArea && displayObject.hitArea.contains) + { + return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y)); + } + else if (Phaser.Creature && displayObject instanceof Phaser.Creature) { + var width = Math.abs(displayObject.width); + var height = Math.abs(displayObject.height); + var x1 = displayObject.x - (width * displayObject.anchorX); + + if (this.game.camera.x + pointer.x >= x1 && this.game.camera.x + pointer.x < x1 + width) + { + var y1 = displayObject.y - (height * displayObject.anchorY); + + if (this.game.camera.y + pointer.y >= y1 && this.game.camera.y + pointer.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.TileSprite) + { + var width = displayObject.width; + var height = displayObject.height; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof PIXI.Sprite) + { + var width = displayObject.texture.frame.width / displayObject.texture.baseTexture.resolution; + var height = displayObject.texture.frame.height / displayObject.texture.baseTexture.resolution; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.Graphics) + { + for (var i = 0; i < displayObject.graphicsData.length; i++) + { + var data = displayObject.graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // Only deal with fills.. + if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y)) + { + return true; + } + } + } + + // Didn't hit the parent, does it have any children? + + for (var i = 0; i < displayObject.children.length; i++) + { + if (this.hitTest(displayObject.children[i], pointer, localPoint)) + { + return true; + } + } + + return false; + }, + + /** + * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. + * + * @method Phaser.Input#onClickTrampoline + * @private + */ + onClickTrampoline: function () { + + // It might not always be the active pointer, but this does work on + // Desktop browsers (read: IE) with Mouse or MSPointer input. + this.activePointer.processClickTrampolines(); + + } + +}; + +Phaser.Input.prototype.constructor = Phaser.Input; + +/** +* The X coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. +* @name Phaser.Input#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Input.prototype, "x", { + + get: function () { + return this._x; + }, + + set: function (value) { + this._x = Math.floor(value); + } + +}); + +/** +* The Y coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. +* @name Phaser.Input#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Input.prototype, "y", { + + get: function () { + return this._y; + }, + + set: function (value) { + this._y = Math.floor(value); + } + +}); + +/** +* True if the Input is currently poll rate locked. +* @name Phaser.Input#pollLocked +* @property {boolean} pollLocked +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "pollLocked", { + + get: function () { + return (this.pollRate > 0 && this._pollCounter < this.pollRate); + } + +}); + +/** +* The total number of inactive Pointers. +* @name Phaser.Input#totalInactivePointers +* @property {number} totalInactivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", { + + get: function () { + return this.pointers.length - this.countActivePointers(); + } + +}); + +/** +* The total number of active Pointers, not counting the mouse pointer. +* @name Phaser.Input#totalActivePointers +* @property {integers} totalActivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", { + + get: function () { + return this.countActivePointers(); + } + +}); + +/** +* The world X coordinate of the most recently active pointer. +* @name Phaser.Input#worldX +* @property {number} worldX - The world X coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldX", { + + get: function () { + return this.game.camera.view.x + this.x; + } + +}); + +/** +* The world Y coordinate of the most recently active pointer. +* @name Phaser.Input#worldY +* @property {number} worldY - The world Y coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldY", { + + get: function () { + return this.game.camera.view.y + this.y; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Mouse class is responsible for handling all aspects of mouse interaction with the browser. +* +* It captures and processes mouse events that happen on the game canvas object. +* It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released +* when not over the game. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object +* which normalises all game input for you, including accurate button handling. +* +* @class Phaser.Mouse +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Mouse = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down. + */ + this.mouseDownCallback = null; + + /** + * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state. + */ + this.mouseUpCallback = null; + + /** + * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas. + */ + this.mouseOutCallback = null; + + /** + * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). + */ + this.mouseOverCallback = null; + + /** + * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used. + */ + this.mouseWheelCallback = null; + + /** + * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + */ + this.capture = false; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + * @default + */ + this.button = -1; + + /** + * The direction of the _last_ mousewheel usage 1 for up -1 for down. + * @property {number} wheelDelta + */ + this.wheelDelta = 0; + + /** + * Mouse input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true. + * @default + */ + this.locked = false; + + /** + * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas. + * @default + */ + this.stopOnGameOut = false; + + /** + * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state. + * @default + */ + this.pointerLock = new Phaser.Signal(); + + /** + * The browser mouse DOM event. Will be null if no mouse event has ever been received. + * Access this property only inside a Mouse event handler and do not keep references to it. + * @property {MouseEvent|null} event + * @default + */ + this.event = null; + + /** + * @property {function} _onMouseDown - Internal event handler reference. + * @private + */ + this._onMouseDown = null; + + /** + * @property {function} _onMouseMove - Internal event handler reference. + * @private + */ + this._onMouseMove = null; + + /** + * @property {function} _onMouseUp - Internal event handler reference. + * @private + */ + this._onMouseUp = null; + + /** + * @property {function} _onMouseOut - Internal event handler reference. + * @private + */ + this._onMouseOut = null; + + /** + * @property {function} _onMouseOver - Internal event handler reference. + * @private + */ + this._onMouseOver = null; + + /** + * @property {function} _onMouseWheel - Internal event handler reference. + * @private + */ + this._onMouseWheel = null; + + /** + * Wheel proxy event object, if required. Shared for all wheel events for this mouse. + * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent + * @private + */ + this._wheelEvent = null; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.NO_BUTTON = -1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.LEFT_BUTTON = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.MIDDLE_BUTTON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.RIGHT_BUTTON = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.BACK_BUTTON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.FORWARD_BUTTON = 4; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_UP = 1; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_DOWN = -1; + +Phaser.Mouse.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Mouse#start + */ + start: function () { + + if (this.game.device.android && this.game.device.chrome === false) + { + // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ... + return; + } + + if (this._onMouseDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onMouseDown = function (event) { + return _this.onMouseDown(event); + }; + + this._onMouseMove = function (event) { + return _this.onMouseMove(event); + }; + + this._onMouseUp = function (event) { + return _this.onMouseUp(event); + }; + + this._onMouseUpGlobal = function (event) { + return _this.onMouseUpGlobal(event); + }; + + this._onMouseOutGlobal = function (event) { + return _this.onMouseOutGlobal(event); + }; + + this._onMouseOut = function (event) { + return _this.onMouseOut(event); + }; + + this._onMouseOver = function (event) { + return _this.onMouseOver(event); + }; + + this._onMouseWheel = function (event) { + return _this.onMouseWheel(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('mousedown', this._onMouseDown, true); + canvas.addEventListener('mousemove', this._onMouseMove, true); + canvas.addEventListener('mouseup', this._onMouseUp, true); + + if (!this.game.device.cocoonJS) + { + window.addEventListener('mouseup', this._onMouseUpGlobal, true); + window.addEventListener('mouseout', this._onMouseOutGlobal, true); + canvas.addEventListener('mouseover', this._onMouseOver, true); + canvas.addEventListener('mouseout', this._onMouseOut, true); + } + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.addEventListener(wheelEvent, this._onMouseWheel, true); + + if (wheelEvent === 'mousewheel') + { + this._wheelEvent = new WheelEventProxy(-1/40, 1); + } + else if (wheelEvent === 'DOMMouseScroll') + { + this._wheelEvent = new WheelEventProxy(1, 1); + } + } + + }, + + /** + * The internal method that handles the mouse down event from the browser. + * @method Phaser.Mouse#onMouseDown + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseDown: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseDownCallback) + { + this.mouseDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.start(event); + + }, + + /** + * The internal method that handles the mouse move event from the browser. + * @method Phaser.Mouse#onMouseMove + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseMoveCallback) + { + this.mouseMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.move(event); + + }, + + /** + * The internal method that handles the mouse up event from the browser. + * @method Phaser.Mouse#onMouseUp + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUp: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.Mouse#onMouseUpGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUpGlobal: function (event) { + + if (!this.input.mousePointer.withinGame) + { + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + }, + + /** + * The internal method that handles the mouse out event from the window. + * + * @method Phaser.Mouse#onMouseOutGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOutGlobal: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (!this.input.enabled || !this.enabled) + { + return; + } + + // If we get a mouseout event from the window then basically + // something serious has gone down, usually along the lines of + // the browser opening a context-menu or similar. + // On OS X Chrome especially this is bad news, as it blocks + // us then getting a mouseup event, so we need to force that through. + // + // No matter what, we must cancel the left and right buttons + + this.input.mousePointer.stop(event); + + // Clear the button states (again?) + this.input.mousePointer.resetButtons(); + + }, + + /** + * The internal method that handles the mouse out event from the browser. + * + * @method Phaser.Mouse#onMouseOut + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (this.mouseOutCallback) + { + this.mouseOutCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.stopOnGameOut) + { + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + this.input.interactiveItems.callAll('_pointerOutHandler', this.input.mousePointer); + + }, + + /** + * The internal method that handles the mouse over event from the browser. + * + * @method Phaser.Mouse#onMouseOver + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = true; + + if (this.mouseOverCallback) + { + this.mouseOverCallback.call(this.callbackContext, event); + } + + }, + + /** + * The internal method that handles the mouse wheel event from the browser. + * + * @method Phaser.Mouse#onMouseWheel + * @param {MouseEvent} event - The native event from the browser. + */ + onMouseWheel: function (event) { + + if (this._wheelEvent) { + event = this._wheelEvent.bindEvent(event); + } + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + // reverse detail for firefox + this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1); + + if (this.mouseWheelCallback) + { + this.mouseWheelCallback.call(this.callbackContext, event); + } + + }, + + /** + * If the browser supports it you can request that the pointer be locked to the browser window. + * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key. + * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'. + * @method Phaser.Mouse#requestPointerLock + */ + requestPointerLock: function () { + + if (this.game.device.pointerLock) + { + var element = this.game.canvas; + + element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; + + element.requestPointerLock(); + + var _this = this; + + this._pointerLockChange = function (event) { + return _this.pointerLockChange(event); + }; + + document.addEventListener('pointerlockchange', this._pointerLockChange, true); + document.addEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true); + } + + }, + + /** + * Internal pointerLockChange handler. + * + * @method Phaser.Mouse#pointerLockChange + * @param {Event} event - The native event from the browser. This gets stored in Mouse.event. + */ + pointerLockChange: function (event) { + + var element = this.game.canvas; + + if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) + { + // Pointer was successfully locked + this.locked = true; + this.pointerLock.dispatch(true, event); + } + else + { + // Pointer was unlocked + this.locked = false; + this.pointerLock.dispatch(false, event); + } + + }, + + /** + * Internal release pointer lock handler. + * @method Phaser.Mouse#releasePointerLock + */ + releasePointerLock: function () { + + document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; + + document.exitPointerLock(); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + }, + + /** + * Stop the event listeners. + * @method Phaser.Mouse#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('mousedown', this._onMouseDown, true); + canvas.removeEventListener('mousemove', this._onMouseMove, true); + canvas.removeEventListener('mouseup', this._onMouseUp, true); + canvas.removeEventListener('mouseover', this._onMouseOver, true); + canvas.removeEventListener('mouseout', this._onMouseOut, true); + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.removeEventListener(wheelEvent, this._onMouseWheel, true); + } + + window.removeEventListener('mouseup', this._onMouseUpGlobal, true); + window.removeEventListener('mouseout', this._onMouseOutGlobal, true); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + } + +}; + +Phaser.Mouse.prototype.constructor = Phaser.Mouse; + +/* jshint latedef:nofunc */ +/** +* A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel' +* events to 'wheel'-like events. +* +* See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode. +* +* @method Phaser.Mouse#WheelEventProxy +* @private +* @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. +* @param {integer} deltaMode - The reported delta mode. +*/ +function WheelEventProxy (scaleFactor, deltaMode) { + + /** + * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. + * @private + */ + this._scaleFactor = scaleFactor; + + /** + * @property {number} _deltaMode - The reported delta mode. + * @private + */ + this._deltaMode = deltaMode; + + /** + * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit. + * @private + */ + this.originalEvent = null; + +} + +WheelEventProxy.prototype = {}; +WheelEventProxy.prototype.constructor = WheelEventProxy; + +WheelEventProxy.prototype.bindEvent = function (event) { + + // Generate stubs automatically + if (!WheelEventProxy._stubsGenerated && event) + { + var makeBinder = function (name) { + + return function () { + var v = this.originalEvent[name]; + return typeof v !== 'function' ? v : v.bind(this.originalEvent); + }; + + }; + + for (var prop in event) + { + if (!(prop in WheelEventProxy.prototype)) + { + Object.defineProperty(WheelEventProxy.prototype, prop, { + get: makeBinder(prop) + }); + } + } + WheelEventProxy._stubsGenerated = true; + } + + this.originalEvent = event; + return this; + +}; + +Object.defineProperties(WheelEventProxy.prototype, { + "type": { value: "wheel" }, + "deltaMode": { get: function () { return this._deltaMode; } }, + "deltaY": { + get: function () { + return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0; + } + }, + "deltaX": { + get: function () { + return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0; + } + }, + "deltaZ": { value: 0 } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The MSPointer class handles {@link https://developers.google.com/web/updates/2016/10/pointer-events Pointer-event} interactions with the game via a dedicated {@link Phaser.Pointer}. (It's named after the nonstandard {@link https://msdn.microsoft.com/library/hh673557(v=vs.85).aspx MSPointerEvent} since that was the first browser implementation.) +* +* It's {@link http://caniuse.com/#feat=pointer currently supported in IE 10+, Edge, Chrome (including Android), and Opera}. +* +* You should not normally access this class directly, but instead use a {@link Phaser.Pointer} object which +* normalises all game input for you including accurate button handling. +* +* Please note that at the current time of writing Phaser does not yet support chorded button interactions: +* http://www.w3.org/TR/pointerevents/#chorded-button-interactions +* +* You can disable Phaser's use of Pointer Events by either of two ways: +* +* ```javascript +* // **Before** `new Phaser.Game(…)`: +* Phaser.Device.onInitialized.add(function () { +* this.mspointer = false; +* }); +* ``` +* +* ```javascript +* // Once, in the earliest State `init` or `create` callback (e.g., Boot): +* this.input.mspointer.stop(); +* ``` +* +* @class Phaser.MSPointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.MSPointer = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called (defaults to game). + */ + this.callbackContext = this.game; + + /** + * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event. + */ + this.pointerDownCallback = null; + + /** + * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event. + */ + this.pointerMoveCallback = null; + + /** + * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event. + */ + this.pointerUpCallback = null; + + /** + * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, canceling the corresponding MouseEvent or TouchEvent. + */ + this.capture = true; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + */ + this.button = -1; + + /** + * The most recent PointerEvent from the browser. Will be null if no event has ever been received. + * Access this property only inside a Pointer event handler and do not keep references to it. + * @property {MSPointerEvent|PointerEvent|null} event + * @default + */ + this.event = null; + + /** + * PointerEvent input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {function} _onMSPointerDown - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerDown = null; + + /** + * @property {function} _onMSPointerMove - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerMove = null; + + /** + * @property {function} _onMSPointerUp - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUp = null; + + /** + * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUpGlobal = null; + + /** + * @property {function} _onMSPointerOut - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOut = null; + + /** + * @property {function} _onMSPointerOver - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOver = null; + +}; + +Phaser.MSPointer.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.MSPointer#start + */ + start: function () { + + if (this._onMSPointerDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + if (this.game.device.mspointer) + { + this._onMSPointerDown = function (event) { + return _this.onPointerDown(event); + }; + + this._onMSPointerMove = function (event) { + return _this.onPointerMove(event); + }; + + this._onMSPointerUp = function (event) { + return _this.onPointerUp(event); + }; + + this._onMSPointerUpGlobal = function (event) { + return _this.onPointerUpGlobal(event); + }; + + this._onMSPointerOut = function (event) { + return _this.onPointerOut(event); + }; + + this._onMSPointerOver = function (event) { + return _this.onPointerOver(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.addEventListener('pointerdown', this._onMSPointerDown, false); + canvas.addEventListener('pointermove', this._onMSPointerMove, false); + canvas.addEventListener('pointerup', this._onMSPointerUp, false); + + canvas.style['-ms-content-zooming'] = 'none'; + canvas.style['-ms-touch-action'] = 'none'; + + if (!this.game.device.cocoonJS) + { + window.addEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.addEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.addEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.addEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.addEventListener('pointerover', this._onMSPointerOver, true); + canvas.addEventListener('pointerout', this._onMSPointerOut, true); + } + } + + }, + + /** + * The function that handles the PointerDown event. + * + * @method Phaser.MSPointer#onPointerDown + * @param {PointerEvent} event - The native DOM event. + */ + onPointerDown: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerDownCallback) + { + this.pointerDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.start(event); + } + else + { + this.input.startPointer(event); + } + + }, + + /** + * The function that handles the PointerMove event. + * @method Phaser.MSPointer#onPointerMove + * @param {PointerEvent} event - The native DOM event. + */ + onPointerMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerMoveCallback) + { + this.pointerMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.move(event); + } + else + { + this.input.updatePointer(event); + } + + }, + + /** + * The function that handles the PointerUp event. + * @method Phaser.MSPointer#onPointerUp + * @param {PointerEvent} event - The native DOM event. + */ + onPointerUp: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerUpCallback) + { + this.pointerUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.stop(event); + } + else + { + this.input.stopPointer(event); + } + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.MSPointer#onPointerUpGlobal + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerUpGlobal: function (event) { + + if ((event.pointerType === 'mouse' || event.pointerType === 0x00000004) && !this.input.mousePointer.withinGame) + { + this.onPointerUp(event); + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer && pointer.withinGame) + { + this.onPointerUp(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = false; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = false; + } + } + + if (this.input.mouse.mouseOutCallback) + { + this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.input.mouse.stopOnGameOut) + { + event['identifier'] = 0; + + if (pointer) + { + pointer.stop(event); + } + else + { + this.input.mousePointer.stop(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = true; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = true; + } + } + + if (this.input.mouse.mouseOverCallback) + { + this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext, event); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.MSPointer#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.removeEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.removeEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.removeEventListener('pointerdown', this._onMSPointerDown, false); + canvas.removeEventListener('pointermove', this._onMSPointerMove, false); + canvas.removeEventListener('pointerup', this._onMSPointerUp, false); + + window.removeEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.removeEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.removeEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('pointerover', this._onMSPointerOver, true); + canvas.removeEventListener('pointerout', this._onMSPointerOut, true); + + } + +}; + +Phaser.MSPointer.prototype.constructor = Phaser.MSPointer; + +/** +* @author Richard Davey +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. +* +* For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, +* middle button and advanced buttons like back and forward. +* +* Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. +* +* On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. +* +* At the time of writing this there are device limitations you should be aware of: +* +* - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions +* (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, +* even when they are pressed. +* - On Linux (GTK), the 4th button and the 5th button are not supported. +* - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. +* +* @class Phaser.DeviceButton +* @constructor +* @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad. +* @param {number} buttonCode - The button code this DeviceButton is responsible for. +*/ +Phaser.DeviceButton = function (parent, buttonCode) { + + /** + * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = parent.game; + + /** + * @property {object} event - The DOM event that caused the change in button state. + * @default + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the button. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the button. + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - The timestamp when the button was last pressed down. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - The timestamp when the button was last released. + * @default + */ + this.timeUp = 0; + + /** + * Gamepad only. + * If a button is held down this holds down the number of times the button has 'repeated'. + * @property {number} repeats + * @default + */ + this.repeats = 0; + + /** + * True if the alt key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} altKey + * @default + */ + this.altKey = false; + + /** + * True if the shift key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} shiftKey + * @default + */ + this.shiftKey = false; + + /** + * True if the control key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} ctrlKey + * @default + */ + this.ctrlKey = false; + + /** + * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. + * @default + */ + this.value = 0; + + /** + * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. + */ + this.buttonCode = buttonCode; + + /** + * This Signal is dispatched every time this DeviceButton is pressed down. + * It is only dispatched once (until the button is released again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onDown + */ + this.onDown = new Phaser.Signal(); + + /** + * This Signal is dispatched every time this DeviceButton is released from a down state. + * It is only dispatched once (until the button is pressed again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onUp + */ + this.onUp = new Phaser.Signal(); + + /** + * Gamepad only. + * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onFloat + */ + this.onFloat = new Phaser.Signal(); + +}; + +Phaser.DeviceButton.prototype = { + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button down state. + * + * @method Phaser.DeviceButton#start + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + start: function (event, value) { + + if (this.isDown) + { + return; + } + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onDown.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button up state. + * + * @method Phaser.DeviceButton#stop + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + stop: function (event, value) { + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onUp.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer. + * Starts or stops button based on condition. + * + * @method Phaser.DeviceButton#startStop + * @protected + * @param {boolean} [condition] - The condition that decides between start or stop. + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + startStop: function (condition, event, value) { + + if (condition) + { + this.start(event, value); + } + else + { + this.stop(event, value); + } + + }, + + /** + * Called automatically by Phaser.SinglePad. + * + * @method Phaser.DeviceButton#padFloat + * @protected + * @param {number} value - Button value + */ + padFloat: function (value) { + + this.isDown = false; + this.isUp = false; + + this.value = value; + + this.onFloat.dispatch(this, value); + + }, + + /** + * Returns the "just pressed" state of this button. + * Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justPressed + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (duration) { + + duration = duration || 250; + + return (this.isDown && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * Returns the "just released" state of this button. + * Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justReleased + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (duration) { + + duration = duration || 250; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. + * + * @method Phaser.DeviceButton#reset + */ + reset: function () { + + this.isDown = false; + this.isUp = true; + + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.altKey = false; + this.shiftKey = false; + this.ctrlKey = false; + + }, + + /** + * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals + * and clears the parent and game references. + * + * @method Phaser.DeviceButton#destroy + */ + destroy: function () { + + this.onDown.dispose(); + this.onUp.dispose(); + this.onFloat.dispose(); + + this.parent = null; + this.game = null; + + } + +}; + +Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton; + +/** +* How long the button has been held down for in milliseconds. +* If not currently down it returns -1. +* +* @name Phaser.DeviceButton#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.DeviceButton.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. +* +* @class Phaser.Pointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. +* @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or CONTACT. +*/ +Phaser.Pointer = function (game, id, pointerMode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. + */ + this.id = id; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINTER; + + /** + * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps. + * @default + */ + this.exists = true; + + /** + * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.identifier = 0; + + /** + * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. + * @default + */ + this.pointerId = null; + + /** + * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer. + */ + this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT); + + /** + * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.target = null; + + /** + * The button property of the most recent DOM event when this Pointer is started. + * You should not rely on this value for accurate button detection, instead use the Pointer properties + * `leftButton`, `rightButton`, `middleButton` and so on. + * @property {any} button + * @default + */ + this.button = null; + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * @property {Phaser.DeviceButton} leftButton + * @default + */ + this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} middleButton + * @default + */ + this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} rightButton + * @default + */ + this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} backButton + * @default + */ + this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} forwardButton + * @default + */ + this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON); + + /** + * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} eraserButton + * @default + */ + this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON); + + /** + * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event. + * @private + * @default + */ + this._holdSent = false; + + /** + * @property {array} _history - Local private variable storing the short-term history of pointer movements. + * @private + */ + this._history = []; + + /** + * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur. + * @private + */ + this._nextDrop = 0; + + /** + * @property {boolean} _stateReset - Monitor events outside of a state reset loop. + * @private + */ + this._stateReset = false; + + /** + * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false. + */ + this.withinGame = false; + + /** + * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientX = -1; + + /** + * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientY = -1; + + /** + * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document. + */ + this.pageX = -1; + + /** + * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document. + */ + this.pageY = -1; + + /** + * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen. + */ + this.screenX = -1; + + /** + * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen. + */ + this.screenY = -1; + + /** + * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementX = 0; + + /** + * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementY = 0; + + /** + * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementX = 0; + + /** + * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementY = 0; + + /** + * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.x = -1; + + /** + * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.y = -1; + + /** + * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false. + */ + this.isMouse = (id === 0); + + /** + * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. + * @property {boolean} isDown + * @default + */ + this.isDown = false; + + /** + * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. + * @property {boolean} isUp + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen. + * @default + */ + this.timeUp = 0; + + /** + * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked. + * @default + */ + this.previousTapTime = 0; + + /** + * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen. + * @default + */ + this.totalTouches = 0; + + /** + * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event. + * @default + */ + this.msSinceLastClick = Number.MAX_VALUE; + + /** + * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging. + * @default + */ + this.targetObject = null; + + /** + * This array is erased and re-populated every time this Pointer is updated. It contains references to all + * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be + * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over + * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset + * every frame. + * @property {array} interactiveCandidates + * @default + */ + this.interactiveCandidates = []; + + /** + * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active. + * @default + */ + this.active = false; + + /** + * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. + * @default + */ + this.dirty = false; + + /** + * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display. + */ + this.position = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. + */ + this.positionDown = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released. + */ + this.positionUp = new Phaser.Point(); + + /** + * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. + * The Circle size is 44px (Apples recommended "finger tip" size). + * @property {Phaser.Circle} circle + */ + this.circle = new Phaser.Circle(0, 0, 44); + + /** + * Click trampolines associated with this pointer. See `addClickTrampoline`. + * @property {object[]|null} _clickTrampolines + * @private + */ + this._clickTrampolines = null; + + /** + * When the Pointer has click trampolines the last target object is stored here + * so it can be used to check for validity of the trampoline in a post-Up/'stop'. + * @property {object} _trampolineTargetObject + * @private + */ + this._trampolineTargetObject = null; + +}; + +/** +* No buttons at all. +* @constant +* @type {number} +*/ +Phaser.Pointer.NO_BUTTON = 0; + +/** +* The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. +* @constant +* @type {number} +*/ +Phaser.Pointer.LEFT_BUTTON = 1; + +/** +* The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. +* @constant +* @type {number} +*/ +Phaser.Pointer.RIGHT_BUTTON = 2; + +/** +* The Middle Mouse button. +* @constant +* @type {number} +*/ +Phaser.Pointer.MIDDLE_BUTTON = 4; + +/** +* The X1 button. This is typically the mouse Back button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.BACK_BUTTON = 8; + +/** +* The X2 button. This is typically the mouse Forward button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.FORWARD_BUTTON = 16; + +/** +* The Eraser pen button on PointerEvent supported devices only. +* @constant +* @type {number} +*/ +Phaser.Pointer.ERASER_BUTTON = 32; + +Phaser.Pointer.prototype = { + + /** + * Resets the states of all the button booleans. + * + * @method Phaser.Pointer#resetButtons + * @protected + */ + resetButtons: function () { + + this.isDown = false; + this.isUp = true; + + if (this.isMouse) + { + this.leftButton.reset(); + this.middleButton.reset(); + this.rightButton.reset(); + this.backButton.reset(); + this.forwardButton.reset(); + this.eraserButton.reset(); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsDown + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsDown: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.start(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.start(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.start(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.start(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.start(event); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsUp + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUp: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.stop(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.stop(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.stop(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.stop(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.stop(event); + } + + }, + + /** + * Called by updateButtons. + * + * @method Phaser.Pointer#processButtonsUpDown + * @private + * @param {integer} buttons - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons MouseEvent#buttons} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUpDown: function (buttons, event) { + + var down = (event.type.toLowerCase().substr(-4) === 'down'); + var move = (event.type.toLowerCase().substr(-4) === 'move'); + + if (buttons !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && buttons === 1 && event.ctrlKey) + { + buttons = 2; + } + + // Note: These are bitwise checks, not booleans + this.leftButton.startStop(Phaser.Pointer.LEFT_BUTTON & buttons, event); + this.rightButton.startStop(Phaser.Pointer.RIGHT_BUTTON & buttons, event); + this.middleButton.startStop(Phaser.Pointer.MIDDLE_BUTTON & buttons, event); + this.backButton.startStop(Phaser.Pointer.BACK_BUTTON & buttons, event); + this.forwardButton.startStop(Phaser.Pointer.FORWARD_BUTTON & buttons, event); + this.eraserButton.startStop(Phaser.Pointer.ERASER_BUTTON & buttons, event); + } + else + { + // No buttons property (like Safari on OSX when using a trackpad) + // Attempt to use event.button property or fallback to default + if (event.button !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && event.ctrlKey && event.button === 0) + { + this.rightButton.start(event); + } + else + { + if (down) + { + this.processButtonsDown(event.button, event); + } + else if (!move) + { + this.processButtonsUp(event.button, event); + } + } + } + else + { + if (down) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (event.ctrlKey) + { + this.rightButton.start(event); + } + else + { + this.leftButton.start(event); + } + } + else + { + this.leftButton.stop(event); + this.rightButton.stop(event); + } + } + } + + }, + + /** + * Called when the event.buttons property changes from zero. + * Contains a button bitmask. + * + * @method Phaser.Pointer#updateButtons + * @protected + * @param {MouseEvent} event - The DOM event. + */ + updateButtons: function (event) { + + this.button = event.button; + this.processButtonsUpDown(event.buttons, event); + + this.isUp = true; + this.isDown = false; + + if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown) + { + this.isUp = false; + this.isDown = true; + } + + }, + + /** + * Called when the Pointer is pressed onto the touchscreen. + * @method Phaser.Pointer#start + * @param {any} event - The DOM event from the browser. + */ + start: function (event) { + + var input = this.game.input; + + if (event['pointerId']) + { + this.pointerId = event.pointerId; + } + + this.identifier = event.identifier; + this.target = event.target; + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = true; + this.isUp = false; + } + + this.active = true; + this.withinGame = true; + this.dirty = false; + + this._history = []; + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + // Work out how long it has been since the last click + this.msSinceLastClick = this.game.time.time - this.timeDown; + this.timeDown = this.game.time.time; + this._holdSent = false; + + // This sets the x/y and other local values + this.move(event, true); + + // x and y are the old values here? + this.positionDown.setTo(this.x, this.y); + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.x = this.x; + input.y = this.y; + input.position.setTo(this.x, this.y); + input.onDown.dispatch(this, event); + input.resetSpeed(this.x, this.y); + } + + this._stateReset = false; + + this.totalTouches++; + + if (this.targetObject !== null) + { + this.targetObject._touchedHandler(this); + } + + return this; + + }, + + /** + * Called by the Input Manager. + * @method Phaser.Pointer#update + */ + update: function () { + + var input = this.game.input; + + if (this.active) + { + // Force a check? + if (this.dirty) + { + if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(false); + } + + this.dirty = false; + } + + if (this._holdSent === false && this.duration >= input.holdRate) + { + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onHold.dispatch(this); + } + + this._holdSent = true; + } + + // Update the droppings history + if (input.recordPointerHistory && this.game.time.time >= this._nextDrop) + { + this._nextDrop = this.game.time.time + input.recordRate; + + this._history.push({ + x: this.position.x, + y: this.position.y + }); + + if (this._history.length > input.recordLimit) + { + this._history.shift(); + } + } + } + + }, + + /** + * Called when the Pointer is moved. + * + * @method Phaser.Pointer#move + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + * @param {boolean} [fromClick=false] - Was this called from the click event? + */ + move: function (event, fromClick) { + + var input = this.game.input; + + if (input.pollLocked) + { + return; + } + + if (fromClick === undefined) { fromClick = false; } + + if (event.button !== undefined) + { + this.button = event.button; + } + + if (this.isMouse) + { + this.updateButtons(event); + } + + 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 && 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.scale.offset.x) * input.scale.x; + this.y = (this.pageY - this.game.scale.offset.y) * input.scale.y; + + this.position.setTo(this.x, this.y); + this.circle.x = this.x; + this.circle.y = this.y; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.activePointer = this; + input.x = this.x; + input.y = this.y; + input.position.setTo(input.x, input.y); + input.circle.x = input.x; + input.circle.y = input.y; + } + + this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY); + + var i = input.moveCallbacks.length; + + while (i--) + { + input.moveCallbacks[i].callback.call(input.moveCallbacks[i].context, this, this.x, this.y, fromClick); + } + + // Easy out if we're dragging something and it still exists + if (this.targetObject !== null && (!this.game.paused || this.targetObject.noPause) && this.targetObject.isDragged === true) + { + if (this.targetObject.update(this) === false) + { + this.targetObject = null; + } + } + else if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(fromClick); + } + + return this; + + }, + + /** + * Process all interactive objects to find out which ones were updated in the recent Pointer move. + * + * @method Phaser.Pointer#processInteractiveObjects + * @protected + * @param {boolean} [fromClick=false] - Was this called from the click event? + * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. + */ + processInteractiveObjects: function (fromClick) { + + // Work out which object is on the top + var highestRenderOrderID = 0; + var highestInputPriorityID = -1; + var candidateTarget = null; + + // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID + // We know they'll be valid for input detection but not which is the top just yet + + var currentNode = this.game.input.interactiveItems.first; + + this.interactiveCandidates = []; + + while (currentNode) + { + // Reset checked status + currentNode.checked = false; + + if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false) && (!this.game.paused || currentNode.sprite.noPause)) + { + // Flag it as checked so we don't re-scan it on the next phase + currentNode.checked = true; + + if ((fromClick && currentNode.checkPointerDown(this, true)) || + (!fromClick && currentNode.checkPointerOver(this, true))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID + // because if their ID is lower anyway then we can just automatically discount them + // (A node that was previously checked did not request a pixel-perfect check.) + + currentNode = this.game.input.interactiveItems.first; + + while (currentNode) + { + if (!currentNode.checked && + currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true)) + { + if ((fromClick && currentNode.checkPointerDown(this, false)) || + (!fromClick && currentNode.checkPointerOver(this, false))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + if (this.game.input.customCandidateHandler) + { + candidateTarget = this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext, this, this.interactiveCandidates, candidateTarget); + } + + this.swapTarget(candidateTarget, false); + + return (this.targetObject !== null); + + }, + + /** + * This will change the `Pointer.targetObject` object to be the one provided. + * + * This allows you to have fine-grained control over which object the Pointer is targeting. + * + * Note that even if you set a new Target here, it is still able to be replaced by any other valid + * target during the next Pointer update. + * + * @method Phaser.Pointer#swapTarget + * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. + * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. + */ + swapTarget: function (newTarget, silent) { + + if (silent === undefined) { silent = false; } + + // Now we know the top-most item (if any) we can process it + if (newTarget === null) + { + // The pointer isn't currently over anything, check if we've got a lingering previous target + if (this.targetObject) + { + this.targetObject._pointerOutHandler(this, silent); + this.targetObject = null; + } + } + else + { + if (this.targetObject === null) + { + // And now set the new one + this.targetObject = newTarget; + newTarget._pointerOverHandler(this, silent); + } + else + { + // We've got a target from the last update + if (this.targetObject === newTarget) + { + // Same target as before, so update it + if (newTarget.update(this) === false) + { + this.targetObject = null; + } + } + else + { + // The target has changed, so tell the old one we've left it + this.targetObject._pointerOutHandler(this, silent); + + // And now set the new one + this.targetObject = newTarget; + this.targetObject._pointerOverHandler(this, silent); + } + } + } + + }, + + /** + * Called when the Pointer leaves the target area. + * + * @method Phaser.Pointer#leave + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + leave: function (event) { + + this.withinGame = false; + this.move(event, false); + + }, + + /** + * Called when the Pointer leaves the touchscreen. + * + * @method Phaser.Pointer#stop + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + stop: function (event) { + + var input = this.game.input; + + if (this._stateReset && this.withinGame) + { + event.preventDefault(); + return; + } + + this.timeUp = this.game.time.time; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onUp.dispatch(this, event); + + // Was it a tap? + if (this.duration >= 0 && this.duration <= input.tapRate) + { + // Was it a double-tap? + if (this.timeUp - this.previousTapTime < input.doubleTapRate) + { + // Yes, let's dispatch the signal then with the 2nd parameter set to true + input.onTap.dispatch(this, true); + } + else + { + // Wasn't a double-tap, so dispatch a single tap signal + input.onTap.dispatch(this, false); + } + + this.previousTapTime = this.timeUp; + } + } + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = false; + this.isUp = true; + } + + // Mouse is always active + if (this.id > 0) + { + this.active = false; + } + + this.withinGame = this.game.scale.bounds.contains(event.pageX, event.pageY); + this.pointerId = null; + this.identifier = null; + + this.positionUp.setTo(this.x, this.y); + + if (this.isMouse === false) + { + input.currentPointers--; + } + + input.interactiveItems.callAll('_releasedHandler', this); + + if (this._clickTrampolines) + { + this._trampolineTargetObject = this.targetObject; + } + + this.targetObject = null; + + return this; + + }, + + /** + * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. + * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. + * @method Phaser.Pointer#justPressed + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate. + * @return {boolean} true if the Pointer was pressed down within the duration given. + */ + justPressed: function (duration) { + + duration = duration || this.game.input.justPressedRate; + + return (this.isDown === true && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. + * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. + * @method Phaser.Pointer#justReleased + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate. + * @return {boolean} true if the Pointer was released within the duration given. + */ + justReleased: function (duration) { + + duration = duration || this.game.input.justReleasedRate; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Add a click trampoline to this pointer. + * + * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily + * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen + * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. + * + * This is used internally by the ScaleManager; click trampoline usage is uncommon. + * Click trampolines can only be added to pointers that are currently down. + * + * @method Phaser.Pointer#addClickTrampoline + * @protected + * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer. + * @param {function} callback - Callback to run/trampoline. + * @param {object} callbackContext - Context of the callback. + * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array. + */ + addClickTrampoline: function (name, callback, callbackContext, callbackArgs) { + + if (!this.isDown) + { + return; + } + + var trampolines = (this._clickTrampolines = this._clickTrampolines || []); + + for (var i = 0; i < trampolines.length; i++) + { + if (trampolines[i].name === name) + { + trampolines.splice(i, 1); + break; + } + } + + trampolines.push({ + name: name, + targetObject: this.targetObject, + callback: callback, + callbackContext: callbackContext, + callbackArgs: callbackArgs + }); + + }, + + /** + * Fire all click trampolines for which the pointers are still referring to the registered object. + * @method Phaser.Pointer#processClickTrampolines + * @private + */ + processClickTrampolines: function () { + + var trampolines = this._clickTrampolines; + + if (!trampolines) + { + return; + } + + for (var i = 0; i < trampolines.length; i++) + { + var trampoline = trampolines[i]; + + if (trampoline.targetObject === this._trampolineTargetObject) + { + trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs); + } + } + + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + }, + + /** + * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. + * @method Phaser.Pointer#reset + */ + reset: function () { + + if (this.isMouse === false) + { + this.active = false; + } + + this.pointerId = null; + this.identifier = null; + this.dirty = false; + this.totalTouches = 0; + this._holdSent = false; + this._history.length = 0; + this._stateReset = true; + + this.resetButtons(); + + if (this.targetObject) + { + this.targetObject._releasedHandler(this); + } + + this.targetObject = null; + + }, + + /** + * Resets the movementX and movementY properties. Use in your update handler after retrieving the values. + * @method Phaser.Pointer#resetMovement + */ + resetMovement: function() { + + this.movementX = 0; + this.movementY = 0; + + } + +}; + +Phaser.Pointer.prototype.constructor = Phaser.Pointer; + +/** +* How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. +* If not currently down it returns -1. +* If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. +* +* @name Phaser.Pointer#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* Gets the X value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldX +* @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldX", { + + get: function () { + + return this.game.world.camera.x + this.x; + + } + +}); + +/** +* Gets the Y value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldY +* @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldY", { + + get: function () { + + return this.game.world.camera.y + this.y; + + } + +}); + +/** +* Enumeration categorizing operational modes of pointers. +* +* PointerType values represent valid bitmasks. +* For example, a value representing both Mouse and Touch devices +* can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. +* +* Values may be added for future mode categorizations. +* @class Phaser.PointerMode +*/ +Phaser.PointerMode = { + + /** + * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. + * + * It has the property that a cursor is passively moved without activating the input. + * This currently corresponds with {@link Phaser.Pointer#isMouse} property. + * @constant + */ + CURSOR: 1 << 0, + + /** + * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. + * @constant + */ + CONTACT: 1 << 1 + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. +* +* @class Phaser.Touch +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Touch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * Touch events will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} touchStartCallback - A callback that can be fired on a touchStart event. + */ + this.touchStartCallback = null; + + /** + * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event. + */ + this.touchMoveCallback = null; + + /** + * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event. + */ + this.touchEndCallback = null; + + /** + * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event. + */ + this.touchEnterCallback = null; + + /** + * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event. + */ + this.touchLeaveCallback = null; + + /** + * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event. + */ + this.touchCancelCallback = null; + + /** + * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it. + * @default + */ + this.preventDefault = true; + + /** + * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received. + * @default + */ + this.event = null; + + /** + * @property {function} _onTouchStart - Internal event handler reference. + * @private + */ + this._onTouchStart = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + + /** + * @property {function} _onTouchEnd - Internal event handler reference. + * @private + */ + this._onTouchEnd = null; + + /** + * @property {function} _onTouchEnter - Internal event handler reference. + * @private + */ + this._onTouchEnter = null; + + /** + * @property {function} _onTouchLeave - Internal event handler reference. + * @private + */ + this._onTouchLeave = null; + + /** + * @property {function} _onTouchCancel - Internal event handler reference. + * @private + */ + this._onTouchCancel = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + +}; + +Phaser.Touch.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Touch#start + */ + start: function () { + + if (this._onTouchStart !== null) + { + // Avoid setting multiple listeners + 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('touchcancel', this._onTouchCancel, false); + + if (!this.game.device.cocoonJS) + { + this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false); + this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false); + } + } + + }, + + /** + * Consumes all touchmove events on the document (only enable this if you know you need it!). + * @method Phaser.Touch#consumeTouchMove + */ + consumeDocumentTouches: function () { + + this._documentTouchMove = function (event) { + event.preventDefault(); + }; + + document.addEventListener('touchmove', this._documentTouchMove, false); + + }, + + /** + * The internal method that handles the touchstart event from the browser. + * @method Phaser.Touch#onTouchStart + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchStart: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.touchStartCallback) + { + this.touchStartCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.startPointer(event.changedTouches[i]); + } + + }, + + /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. + * @method Phaser.Touch#onTouchCancel + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchCancel: function (event) { + + this.event = event; + + if (this.touchCancelCallback) + { + this.touchCancelCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchEnter + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnter: function (event) { + + this.event = event; + + if (this.touchEnterCallback) + { + this.touchEnterCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchLeave + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchLeave: function (event) { + + this.event = event; + + if (this.touchLeaveCallback) + { + this.touchLeaveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * The handler for the touchmove events. + * @method Phaser.Touch#onTouchMove + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchMove: function (event) { + + this.event = event; + + if (this.touchMoveCallback) + { + this.touchMoveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.updatePointer(event.changedTouches[i]); + } + + }, + + /** + * The handler for the touchend events. + * @method Phaser.Touch#onTouchEnd + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnd: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.touchEndCallback) + { + this.touchEndCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.Touch#stop + */ + stop: function () { + + if (this.game.device.touch) + { + this.game.canvas.removeEventListener('touchstart', this._onTouchStart); + this.game.canvas.removeEventListener('touchmove', this._onTouchMove); + this.game.canvas.removeEventListener('touchend', this._onTouchEnd); + this.game.canvas.removeEventListener('touchenter', this._onTouchEnter); + this.game.canvas.removeEventListener('touchleave', this._onTouchLeave); + this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel); + } + + } + +}; + +Phaser.Touch.prototype.constructor = Phaser.Touch; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. +* +* @class Phaser.InputHandler +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. +*/ +Phaser.InputHandler = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = sprite.game; + + /** + * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity. + * @default + */ + this.enabled = false; + + /** + * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks. + * @protected + */ + this.checked = false; + + /** + * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have + * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can + * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. + * @property {number} priorityID + * @default + */ + this.priorityID = 0; + + /** + * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. + * @default + */ + this.useHandCursor = false; + + /** + * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor? + * @private + */ + this._setHandCursor = false; + + /** + * @property {boolean} isDragged - true if the Sprite is being currently dragged. + * @default + */ + this.isDragged = false; + + /** + * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally. + * @default + */ + this.allowHorizontalDrag = true; + + /** + * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically. + * @default + */ + this.allowVerticalDrag = true; + + /** + * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. + * @default + */ + this.bringToTop = false; + + /** + * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset. + * @default + */ + this.snapOffset = null; + + /** + * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. + * @default + */ + this.snapOnDrag = false; + + /** + * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release. + * @default + */ + this.snapOnRelease = false; + + /** + * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid. + * @default + */ + this.snapX = 0; + + /** + * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid. + * @default + */ + this.snapY = 0; + + /** + * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid. + * @default + */ + this.snapOffsetX = 0; + + /** + * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid.. + * @default + */ + this.snapOffsetY = 0; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. + * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over. + * @default + */ + this.pixelPerfectOver = false; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive so only enable if you really need it. + * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite. + * @default + */ + this.pixelPerfectClick = false; + + /** + * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. + * @default + */ + this.pixelPerfectAlpha = 255; + + /** + * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no + * @default + */ + this.draggable = false; + + /** + * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag. + * @default + */ + this.boundsRect = null; + + /** + * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. + * @default + */ + this.boundsSprite = null; + + /** + * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. + */ + this.scaleLayer = false; + + /** + * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from. + */ + this.dragOffset = new Phaser.Point(); + + /** + * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? + */ + this.dragFromCenter = false; + + /** + * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. + */ + this.dragStopBlocksInputUp = false; + + /** + * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. + */ + this.dragStartPoint = new Phaser.Point(); + + /** + * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. + */ + this.dragDistanceThreshold = 0; + + /** + * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. + */ + this.dragTimeThreshold = 0; + + /** + * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. + */ + this.downPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. + */ + this.snapPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} _dragPoint - Internal cache var. + * @private + */ + this._dragPoint = new Phaser.Point(); + + /** + * @property {boolean} _dragPhase - Internal cache var. + * @private + */ + this._dragPhase = false; + + /** + * @property {boolean} _pendingDrag - Internal cache var. + * @private + */ + this._pendingDrag = false; + + /** + * @property {boolean} _dragTimePass - Internal cache var. + * @private + */ + this._dragTimePass = false; + + /** + * @property {boolean} _dragDistancePass - Internal cache var. + * @private + */ + this._dragDistancePass = false; + + /** + * @property {boolean} _wasEnabled - Internal cache var. + * @private + */ + this._wasEnabled = false; + + /** + * @property {Phaser.Point} _tempPoint - Internal cache var. + * @private + */ + this._tempPoint = new Phaser.Point(); + + /** + * @property {array} _pointerData - Internal cache var. + * @private + */ + this._pointerData = []; + + this._pointerData.push({ + id: 0, + x: 0, + y: 0, + camX: 0, + camY: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }); + +}; + +Phaser.InputHandler.prototype = { + + /** + * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. + * + * @method Phaser.InputHandler#start + * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. + * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) + * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound. + */ + start: function (priority, useHandCursor) { + + priority = priority || 0; + if (useHandCursor === undefined) { useHandCursor = false; } + + // Turning on + if (this.enabled === false) + { + // Register, etc + this.game.input.interactiveItems.add(this); + this.useHandCursor = useHandCursor; + this.priorityID = priority; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + + this.snapOffset = new Phaser.Point(); + this.enabled = true; + this._wasEnabled = true; + + } + + this.sprite.events.onAddedToGroup.add(this.addedToGroup, this); + this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this); + + return this.sprite; + + }, + + /** + * Handles when the parent Sprite is added to a new Group. + * + * @method Phaser.InputHandler#addedToGroup + * @private + */ + addedToGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this._wasEnabled && !this.enabled) + { + this.start(); + } + + }, + + /** + * Handles when the parent Sprite is removed from a Group. + * + * @method Phaser.InputHandler#removedFromGroup + * @private + */ + removedFromGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this.enabled) + { + this._wasEnabled = true; + this.stop(); + } + else + { + this._wasEnabled = false; + } + + }, + + /** + * Resets the Input Handler and disables it. + * @method Phaser.InputHandler#reset + */ + reset: function () { + + this.enabled = false; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + }, + + /** + * Stops the Input Handler from running. + * @method Phaser.InputHandler#stop + */ + stop: function () { + + // Turning off + if (this.enabled === false) + { + return; + } + else + { + // De-register, etc + this.enabled = false; + this.game.input.interactiveItems.remove(this); + } + + }, + + /** + * Clean up memory. + * @method Phaser.InputHandler#destroy + */ + destroy: function () { + + if (this.sprite) + { + if (this._setHandCursor) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + this.enabled = false; + + this.game.input.interactiveItems.remove(this); + + this._pointerData.length = 0; + this.boundsRect = null; + this.boundsSprite = null; + this.sprite = null; + } + + }, + + /** + * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. + * This is called by Phaser.Pointer and shouldn't typically be called directly. + * + * @method Phaser.InputHandler#validForInput + * @protected + * @param {number} highestID - The highest ID currently processed by the Pointer. + * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer. + * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? + * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection. + */ + validForInput: function (highestID, highestRenderID, includePixelPerfect) { + + if (includePixelPerfect === undefined) { includePixelPerfect = true; } + + if (!this.enabled || + this.sprite.scale.x === 0 || + this.sprite.scale.y === 0 || + this.priorityID < this.game.input.minPriorityID || + (this.sprite.parent && this.sprite.parent.ignoreChildInput)) + { + return false; + } + + // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it + if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver)) + { + return false; + } + + if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID > highestRenderID)) + { + return true; + } + + return false; + + }, + + /** + * Is this object using pixel perfect checking? + * + * @method Phaser.InputHandler#isPixelPerfect + * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. + */ + isPixelPerfect: function () { + + return (this.pixelPerfectClick || this.pixelPerfectOver); + + }, + + /** + * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerX + * @param {integer} [pointerId=0] + * @return {number} The x coordinate of the Input pointer. + */ + pointerX: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].x; + + }, + + /** + * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerY + * @param {integer} [pointerId=0] + * @return {number} The y coordinate of the Input pointer. + */ + pointerY: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].y; + + }, + + /** + * If the Pointer is down this returns true. + * This *only* checks if the Pointer is down, not if it's down over any specific Sprite. + * + * @method Phaser.InputHandler#pointerDown + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is down, otherwise false. + */ + pointerDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDown; + + }, + + /** + * If the Pointer is up this returns true. + * This *only* checks if the Pointer is up, not if it's up over any specific Sprite. + * + * @method Phaser.InputHandler#pointerUp + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is up, otherwise false. + */ + pointerUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isUp; + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeDown + * @param {integer} [pointerId=(check all)] + * @return {number} + */ + pointerTimeDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeDown; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeUp + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeUp; + + }, + + /** + * Is the Pointer over this Sprite? + * + * @method Phaser.InputHandler#pointerOver + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object. + */ + pointerOver: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOver) + { + return true; + } + } + + return false; + } + else + { + return this._pointerData[pointerId].isOver; + } + + }, + + /** + * Is the Pointer outside of this Sprite? + * + * @method Phaser.InputHandler#pointerOut + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. + */ + pointerOut: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOut) + { + return true; + } + } + } + else + { + return this._pointerData[pointerId].isOut; + } + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOver + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOver: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOver; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOut + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOut: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOut; + + }, + + /** + * Is this sprite being dragged by the mouse or not? + * + * @method Phaser.InputHandler#pointerDragged + * @param {integer} [pointerId=0] + * @return {boolean} True if the pointer is dragging an object, otherwise false. + */ + pointerDragged: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDragged; + + }, + + /** + * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerDown + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} True if the pointer is down, otherwise false. + */ + checkPointerDown: function (pointer, fastTest) { + + if (!pointer.isDown || + !this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectClick) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Checks if the given pointer is over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerOver + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} + */ + checkPointerOver: function (pointer, fastTest) { + + if (!this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectOver) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. + * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. + * + * @method Phaser.InputHandler#checkPixel + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters. + * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha + */ + checkPixel: function (x, y, pointer) { + + // Grab a pixel from our image into the hitCanvas and then test it + if (this.sprite.texture.baseTexture.source) + { + if (x === null && y === null) + { + // Use the pointer parameter + this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint); + + var x = this._tempPoint.x; + var y = this._tempPoint.y; + } + + if (this.sprite.anchor.x !== 0) + { + x -= -this.sprite.texture.frame.width * this.sprite.anchor.x; + } + + if (this.sprite.anchor.y !== 0) + { + y -= -this.sprite.texture.frame.height * this.sprite.anchor.y; + } + + x += this.sprite.texture.frame.x; + y += this.sprite.texture.frame.y; + + if (this.sprite.texture.trim) + { + x -= this.sprite.texture.trim.x; + y -= this.sprite.texture.trim.y; + + // If the coordinates are outside the trim area we return false immediately, to save doing a draw call + if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom) + { + this._dx = x; + this._dy = y; + return false; + } + } + + this._dx = x; + this._dy = y; + + this.game.input.hitContext.clearRect(0, 0, 1, 1); + this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1); + + if (rgb.data[3] >= this.pixelPerfectAlpha) + { + return true; + } + } + + return false; + + }, + + /** + * Internal Update method. This is called automatically and handles the Pointer + * and drag update loops. + * + * @method Phaser.InputHandler#update + * @protected + * @param {Phaser.Pointer} pointer + * @return {boolean} True if the pointer is still active, otherwise false. + */ + update: function (pointer) { + + if (this.sprite === null || this.sprite.parent === undefined) + { + // Abort. We've been destroyed. + return; + } + + if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible) + { + this._pointerOutHandler(pointer); + return false; + } + + if (this._pendingDrag) + { + if (!this._dragDistancePass) + { + this._dragDistancePass = (Phaser.Math.distance(pointer.x, pointer.y, this.downPoint.x, this.downPoint.y) >= this.dragDistanceThreshold); + } + + if (this._dragDistancePass && this._dragTimePass) + { + this.startDrag(pointer); + } + + return true; + } + else if (this.draggable && this._draggedPointerID === pointer.id) + { + return this.updateDrag(pointer, false); + } + else if (this._pointerData[pointer.id].isOver) + { + 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; + } + } + }, + + /** + * Internal method handling the pointer over event. + * + * @method Phaser.InputHandler#_pointerOverHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOverHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (data.isOver === false || pointer.dirty) + { + var sendEvent = (data.isOver === false); + + data.isOver = true; + data.isOut = false; + data.timeOver = this.game.time.time; + data.x = pointer.x - this.sprite.x; + data.y = pointer.y - this.sprite.y; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = "pointer"; + this._setHandCursor = true; + } + + if (!silent && sendEvent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOver$dispatch(this.sprite, pointer); + } + + if (this.sprite.parent && this.sprite.parent.onChildInputOver) + { + this.sprite.parent.onChildInputOver.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the pointer out event. + * + * @method Phaser.InputHandler#_pointerOutHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOutHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + data.isOver = false; + data.isOut = true; + data.timeOut = this.game.time.time; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + if (!silent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOut$dispatch(this.sprite, pointer); + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputOut) + { + this.sprite.parent.onChildInputOut.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the touched / clicked event. + * + * @method Phaser.InputHandler#_touchedHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + */ + _touchedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (!data.isDown && data.isOver) + { + if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer)) + { + return; + } + + data.isDown = true; + data.isUp = false; + data.timeDown = this.game.time.time; + + this.downPoint.set(pointer.x, pointer.y); + + // It's possible the onInputDown event creates a new Sprite that is on-top of this one, so we ought to force a Pointer update + pointer.dirty = true; + + if (this.sprite && this.sprite.events) + { + this.sprite.events.onInputDown$dispatch(this.sprite, pointer); + + // The event above might have destroyed this sprite. + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputDown) + { + this.sprite.parent.onChildInputDown.dispatch(this.sprite, pointer); + } + + // The events might have destroyed this sprite. + if (this.sprite === null) + { + return; + } + } + + // Start drag + if (this.draggable && this.isDragged === false) + { + if (this.dragTimeThreshold === 0 && this.dragDistanceThreshold === 0) + { + this.startDrag(pointer); + } + else + { + this._pendingDrag = true; + + this._dragDistancePass = (this.dragDistanceThreshold === 0); + + if (this.dragTimeThreshold > 0) + { + this._dragTimePass = false; + this.game.time.events.add(this.dragTimeThreshold, this.dragTimeElapsed, this, pointer); + } + else + { + this._dragTimePass = true; + } + } + } + + if (this.bringToTop) + { + this.sprite.bringToTop(); + } + } + + }, + + /** + * Internal method handling the drag threshold timer. + * + * @method Phaser.InputHandler#dragTimeElapsed + * @private + * @param {Phaser.Pointer} pointer + */ + dragTimeElapsed: function (pointer) { + + this._dragTimePass = true; + + if (this._pendingDrag && this.sprite) + { + if (this._dragDistancePass) + { + this.startDrag(pointer); + } + } + + }, + + /** + * Internal method handling the pointer released event. + * @method Phaser.InputHandler#_releasedHandler + * @private + * @param {Phaser.Pointer} pointer + */ + _releasedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + // If was previously touched by this Pointer, check if still is AND still over this item + if (data.isDown && pointer.isUp) + { + data.isDown = false; + data.isUp = true; + data.timeUp = this.game.time.time; + data.downDuration = data.timeUp - data.timeDown; + + // Only release the InputUp signal if the pointer is still over this sprite + var isOver = this.checkPointerOver(pointer); + + if (this.sprite && this.sprite.events) + { + if (!this.dragStopBlocksInputUp || + this.dragStopBlocksInputUp && !(this.draggable && this.isDragged && this._draggedPointerID === pointer.id)) + { + this.sprite.events.onInputUp$dispatch(this.sprite, pointer, isOver); + } + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputUp) + { + this.sprite.parent.onChildInputUp.dispatch(this.sprite, pointer, isOver); + } + + // The onInputUp event may have changed the sprite so that checkPointerOver is no longer true, so update it. + if (isOver) + { + isOver = this.checkPointerOver(pointer); + } + } + + data.isOver = isOver; + + if (!isOver && this.useHandCursor) + { + this.game.canvas.style.cursor = "default"; + this._setHandCursor = false; + } + + // It's possible the onInputUp event created a new Sprite that is on-top of this one, so force a Pointer update + pointer.dirty = true; + + this._pendingDrag = false; + + // Stop drag + if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id) + { + this.stopDrag(pointer); + } + } + + }, + + /** + * Called as a Pointer actively drags this Game Object. + * + * @method Phaser.InputHandler#updateDrag + * @private + * @param {Phaser.Pointer} pointer - The Pointer causing the drag update. + * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started. + * @return {boolean} + */ + updateDrag: function (pointer, fromStart) { + + if (fromStart === undefined) { fromStart = false; } + + if (pointer.isUp) + { + this.stopDrag(pointer); + return false; + } + + var pointerLocalCoord = this.globalToLocal(pointer); + + if (this.sprite.fixedToCamera) + { + var px = this.game.camera.scale.x * pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = this.game.camera.scale.y * pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + else + { + var px = pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + + if (this.sprite.fixedToCamera) + { + if (this.allowHorizontalDrag) + { + this.sprite.cameraOffset.x = px - this.game.camera.x; + } + + if (this.allowVerticalDrag) + { + this.sprite.cameraOffset.y = py - this.game.camera.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); + this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y); + } + } + else + { + var cx = this.game.camera.x - this._pointerData[pointer.id].camX; + var cy = this.game.camera.y - this._pointerData[pointer.id].camY; + + if (this.allowHorizontalDrag) + { + this.sprite.x = px + cx; + } + + if (this.allowVerticalDrag) + { + this.sprite.y = py + cy; + } + + 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); + this.snapPoint.set(this.sprite.x, this.sprite.y); + } + } + + this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint, fromStart); + + return true; + + }, + + /** + * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOver + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justOver: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOut + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justOut: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay)); + + }, + + /** + * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justPressed + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justPressed: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justReleased + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justReleased: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay)); + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#overDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. + */ + overDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isOver) + { + return this.game.time.time - this._pointerData[pointerId].timeOver; + } + + return -1; + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#downDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. + */ + downDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isDown) + { + return this.game.time.time - this._pointerData[pointerId].timeDown; + } + + return -1; + + }, + + /** + * Allow this Sprite to be dragged by any valid pointer. + * + * When the drag begins the Sprite.events.onDragStart event will be dispatched. + * + * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. + * + * You can control the thresholds over when a drag starts via the properties: + * + * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move + * before the drag will start. + * + * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on + * the Sprite before the drag will start. + * + * You can set either (or both) of these properties after enabling a Sprite for drag. + * + * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually + * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`. + * + * @method Phaser.InputHandler#enableDrag + * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. + * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group. + * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. + * @param {integer} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. + * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. + * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. + */ + enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) { + + if (lockCenter === undefined) { lockCenter = false; } + if (bringToTop === undefined) { bringToTop = false; } + if (pixelPerfect === undefined) { pixelPerfect = false; } + if (alphaThreshold === undefined) { alphaThreshold = 255; } + if (boundsRect === undefined) { boundsRect = null; } + if (boundsSprite === undefined) { boundsSprite = null; } + + this._dragPoint = new Phaser.Point(); + this.draggable = true; + this.bringToTop = bringToTop; + this.dragOffset = new Phaser.Point(); + this.dragFromCenter = lockCenter; + + this.pixelPerfectClick = pixelPerfect; + this.pixelPerfectAlpha = alphaThreshold; + + if (boundsRect) + { + this.boundsRect = boundsRect; + } + + if (boundsSprite) + { + this.boundsSprite = boundsSprite; + } + + }, + + /** + * Stops this sprite from being able to be dragged. + * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. + * + * @method Phaser.InputHandler#disableDrag + */ + disableDrag: function () { + + if (this._pointerData) + { + for (var i = 0; i < 10; i++) + { + this._pointerData[i].isDragged = false; + } + } + + this.draggable = false; + this.isDragged = false; + this._draggedPointerID = -1; + this._pendingDrag = false; + + }, + + /** + * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#startDrag + * @param {Phaser.Pointer} pointer + */ + startDrag: function (pointer) { + + var x = this.sprite.x; + var y = this.sprite.y; + var pointerLocalCoord = this.globalToLocal(pointer); + + this.isDragged = true; + this._draggedPointerID = pointer.id; + + this._pointerData[pointer.id].camX = this.game.camera.x; + this._pointerData[pointer.id].camY = this.game.camera.y; + + this._pointerData[pointer.id].isDragged = true; + + if (this.sprite.fixedToCamera) + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.cameraOffset.x = pointerLocalCoord.x + (this.sprite.cameraOffset.x - boundsCenterLocalCoord.x); + this.sprite.cameraOffset.y = pointerLocalCoord.y + (this.sprite.cameraOffset.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y); + } + else + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.x = pointerLocalCoord.x + (this.sprite.x - boundsCenterLocalCoord.x); + this.sprite.y = pointerLocalCoord.y + (this.sprite.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.x - pointerLocalCoord.x, this.sprite.y - pointerLocalCoord.y); + } + + this.updateDrag(pointer, true); + + if (this.bringToTop) + { + this._dragPhase = true; + this.sprite.bringToTop(); + } + + this.dragStartPoint.set(x, y); + + this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y); + + this._pendingDrag = false; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalX + * @param {number} x + */ + globalToLocalX: function (x) { + + if (this.scaleLayer) + { + x -= this.game.scale.grid.boundsFluid.x; + x *= this.game.scale.grid.scaleFluidInversed.x; + } + + return x; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalY + * @param {number} y + */ + globalToLocalY: function (y) { + + if (this.scaleLayer) + { + y -= this.game.scale.grid.boundsFluid.y; + y *= this.game.scale.grid.scaleFluidInversed.y; + } + + return y; + + }, + + /** + * Convert global coordinates to local sprite coordinates + * + * @method Phaser.InputHandler#globalToLocal + * @param {Phaser.Point} globalCoord - The global coordinates to convert. + * @return {Phaser.Point} A point containing the local coordinates. + */ + globalToLocal: function (globalCoord) { + + if (this.sprite.parent) + { + return this.game.input.getLocalPosition(this.sprite.parent, {x: globalCoord.x, y: globalCoord.y}); + } + else + { + return globalCoord; + } + + }, + + /** + * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#stopDrag + * @param {Phaser.Pointer} pointer + */ + stopDrag: function (pointer) { + + this.isDragged = false; + this._draggedPointerID = -1; + this._pointerData[pointer.id].isDragged = false; + this._dragPhase = false; + this._pendingDrag = false; + + if (this.snapOnRelease) + { + if (this.sprite.fixedToCamera) + { + 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 + { + 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); + } + } + + this.sprite.events.onDragStop$dispatch(this.sprite, pointer); + + if (this.checkPointerOver(pointer) === false) + { + this._pointerOutHandler(pointer); + } + + }, + + /** + * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! + * + * @method Phaser.InputHandler#setDragLock + * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false. + * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false. + */ + setDragLock: function (allowHorizontal, allowVertical) { + + if (allowHorizontal === undefined) { allowHorizontal = true; } + if (allowVertical === undefined) { allowVertical = true; } + + this.allowHorizontalDrag = allowHorizontal; + this.allowVerticalDrag = allowVertical; + + }, + + /** + * Make this Sprite snap to the given grid either during drag or when it's released. + * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. + * + * @method Phaser.InputHandler#enableSnap + * @param {number} snapX - The width of the grid cell to snap to. + * @param {number} snapY - The height of the grid cell to snap to. + * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged. + * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released. + * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid. + * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid. + */ + enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) { + + if (onDrag === undefined) { onDrag = true; } + if (onRelease === undefined) { onRelease = false; } + if (snapOffsetX === undefined) { snapOffsetX = 0; } + if (snapOffsetY === undefined) { snapOffsetY = 0; } + + this.snapX = snapX; + this.snapY = snapY; + this.snapOffsetX = snapOffsetX; + this.snapOffsetY = snapOffsetY; + this.snapOnDrag = onDrag; + this.snapOnRelease = onRelease; + + }, + + /** + * Stops the sprite from snapping to a grid during drag or release. + * + * @method Phaser.InputHandler#disableSnap + */ + disableSnap: function () { + + this.snapOnDrag = false; + this.snapOnRelease = false; + + }, + + /** + * Bounds Rect check for the sprite drag + * + * @method Phaser.InputHandler#checkBoundsRect + */ + checkBoundsRect: function () { + + if (this.sprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsRect.left) + { + this.sprite.cameraOffset.x = this.boundsRect.left; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right) + { + this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsRect.top) + { + this.sprite.cameraOffset.y = this.boundsRect.top; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom) + { + this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsRect.left) + { + this.sprite.x = this.boundsRect.x + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsRect.right) + { + this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsRect.top) + { + this.sprite.y = this.boundsRect.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsRect.bottom) + { + this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + }, + + /** + * Parent Sprite Bounds check for the sprite drag. + * + * @method Phaser.InputHandler#checkBoundsSprite + */ + checkBoundsSprite: function () { + + if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x) + { + this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width)) + { + this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y) + { + this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height)) + { + this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsSprite.left) + { + this.sprite.x = this.boundsSprite.left + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsSprite.right) + { + this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsSprite.top) + { + this.sprite.y = this.boundsSprite.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsSprite.bottom) + { + this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + } + +}; + +Phaser.InputHandler.prototype.constructor = Phaser.InputHandler; + +/** +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Gamepad class handles gamepad input and dispatches gamepad events. +* +* Remember to call `gamepad.start()`. +* +* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! +* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it +* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. +* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. +* +* @class Phaser.Gamepad +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Gamepad = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads + * @private + */ + this._gamepadIndexMap = {}; + + /** + * @property {Array} _rawPads - The raw state of the gamepads from the browser + * @private + */ + this._rawPads = []; + + /** + * @property {boolean} _active - Private flag for whether or not the API is polled + * @private + * @default + */ + this._active = false; + + /** + * Gamepad input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation. + * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not? + * @private + */ + this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') !== -1) || !!navigator.getGamepads; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevRawGamepadTypes + * @private + * @default + */ + this._prevRawGamepadTypes = []; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevTimestamps + * @private + * @default + */ + this._prevTimestamps = []; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._ongamepadconnected = null; + + /** + * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._gamepaddisconnected = null; + + /** + * @property {Array} _gamepads - The four Phaser Gamepads. + * @private + */ + this._gamepads = [ + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this) + ]; + +}; + +Phaser.Gamepad.prototype = { + + /** + * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. + * + * @method Phaser.Gamepad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callback methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + this.callbackContext = context; + } + + }, + + /** + * Starts the Gamepad event handling. + * This MUST be called manually before Phaser will start polling the Gamepad API. + * + * @method Phaser.Gamepad#start + */ + start: function () { + + if (this._active) + { + // Avoid setting multiple listeners + return; + } + + this._active = true; + + var _this = this; + + this._onGamepadConnected = function (event) { + return _this.onGamepadConnected(event); + }; + + this._onGamepadDisconnected = function (event) { + return _this.onGamepadDisconnected(event); + }; + + window.addEventListener('gamepadconnected', this._onGamepadConnected, false); + window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false); + + }, + + /** + * Handles the connection of a Gamepad. + * + * @method onGamepadConnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadConnected: function (event) { + + var newPad = event.gamepad; + this._rawPads.push(newPad); + this._gamepads[newPad.index].connect(newPad); + + }, + + /** + * Handles the disconnection of a Gamepad. + * + * @method onGamepadDisconnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadDisconnected: function (event) { + + var removedPad = event.gamepad; + + for (var i in this._rawPads) + { + if (this._rawPads[i].index === removedPad.index) + { + this._rawPads.splice(i,1); + } + } + + this._gamepads[removedPad.index].disconnect(); + + }, + + /** + * Main gamepad update loop. Should not be called manually. + * @method Phaser.Gamepad#update + * @protected + */ + update: function () { + + this._pollGamepads(); + + this.pad1.pollStatus(); + this.pad2.pollStatus(); + this.pad3.pollStatus(); + this.pad4.pollStatus(); + + }, + + /** + * Updating connected gamepads (for Google Chrome). Should not be called manually. + * + * @method Phaser.Gamepad#_pollGamepads + * @private + */ + _pollGamepads: function () { + + if (!this._active) + { + return; + } + + if (navigator['getGamepads']) + { + var rawGamepads = navigator.getGamepads(); + } + else if (navigator['webkitGetGamepads']) + { + var rawGamepads = navigator.webkitGetGamepads(); + } + else if (navigator['webkitGamepads']) + { + var rawGamepads = navigator.webkitGamepads(); + } + + if (rawGamepads) + { + this._rawPads = []; + + var gamepadsChanged = false; + + for (var i = 0; i < rawGamepads.length; i++) + { + if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i]) + { + gamepadsChanged = true; + this._prevRawGamepadTypes[i] = typeof rawGamepads[i]; + } + + if (rawGamepads[i]) + { + this._rawPads.push(rawGamepads[i]); + } + + // Support max 4 pads at the moment + if (i === 3) + { + break; + } + } + + for (var g = 0; g < this._gamepads.length; g++) + { + this._gamepads[g]._rawPad = this._rawPads[g]; + } + + if (gamepadsChanged) + { + var validConnections = { rawIndices: {}, padIndices: {} }; + var singlePad; + + for (var j = 0; j < this._gamepads.length; j++) + { + singlePad = this._gamepads[j]; + + if (singlePad.connected) + { + for (var k = 0; k < this._rawPads.length; k++) + { + if (this._rawPads[k].index === singlePad.index) + { + validConnections.rawIndices[singlePad.index] = true; + validConnections.padIndices[j] = true; + } + } + } + } + + for (var l = 0; l < this._gamepads.length; l++) + { + singlePad = this._gamepads[l]; + + if (validConnections.padIndices[l]) + { + continue; + } + + if (this._rawPads.length < 1) + { + singlePad.disconnect(); + } + + for (var m = 0; m < this._rawPads.length; m++) + { + if (validConnections.padIndices[l]) + { + break; + } + + var rawPad = this._rawPads[m]; + + if (rawPad) + { + if (validConnections.rawIndices[rawPad.index]) + { + singlePad.disconnect(); + continue; + } + else + { + singlePad.connect(rawPad); + validConnections.rawIndices[rawPad.index] = true; + validConnections.padIndices[l] = true; + } + } + else + { + singlePad.disconnect(); + } + } + } + } + } + }, + + /** + * Sets the deadZone variable for all four gamepads + * @method Phaser.Gamepad#setDeadZones + */ + setDeadZones: function (value) { + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].deadZone = value; + } + + }, + + /** + * Stops the Gamepad event handling. + * + * @method Phaser.Gamepad#stop + */ + stop: function () { + + this._active = false; + + window.removeEventListener('gamepadconnected', this._onGamepadConnected); + window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected); + + }, + + /** + * Reset all buttons/axes of all gamepads + * @method Phaser.Gamepad#reset + */ + reset: function () { + + this.update(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].reset(); + } + + }, + + /** + * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justPressed(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justReleased(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns true if the button is currently pressed down, on ANY gamepad. + * @method Phaser.Gamepad#isDown + * @param {number} buttonCode - The buttonCode of the button to check for. + * @return {boolean} True if a button is currently down. + */ + isDown: function (buttonCode) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].isDown(buttonCode) === true) + { + return true; + } + } + + return false; + }, + + /** + * Destroys this object and the associated event listeners. + * + * @method Phaser.Gamepad#destroy + */ + destroy: function () { + + this.stop(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].destroy(); + } + + } + +}; + +Phaser.Gamepad.prototype.constructor = Phaser.Gamepad; + +/** +* If the gamepad input is active or not - if not active it should not be updated from Input.js +* @name Phaser.Gamepad#active +* @property {boolean} active - If the gamepad input is active or not. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "active", { + + get: function () { + return this._active; + } + +}); + +/** +* Whether or not gamepads are supported in current browser. +* @name Phaser.Gamepad#supported +* @property {boolean} supported - Whether or not gamepads are supported in current browser. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "supported", { + + get: function () { + return this._gamepadSupportAvailable; + } + +}); + +/** +* How many live gamepads are currently connected. +* @name Phaser.Gamepad#padsConnected +* @property {number} padsConnected - How many live gamepads are currently connected. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", { + + get: function () { + return this._rawPads.length; + } + +}); + +/** +* Gamepad #1 +* @name Phaser.Gamepad#pad1 +* @property {Phaser.SinglePad} pad1 - Gamepad #1; +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad1", { + + get: function () { + return this._gamepads[0]; + } + +}); + +/** +* Gamepad #2 +* @name Phaser.Gamepad#pad2 +* @property {Phaser.SinglePad} pad2 - Gamepad #2 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad2", { + + get: function () { + return this._gamepads[1]; + } + +}); + +/** +* Gamepad #3 +* @name Phaser.Gamepad#pad3 +* @property {Phaser.SinglePad} pad3 - Gamepad #3 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad3", { + + get: function () { + return this._gamepads[2]; + } + +}); + +/** +* Gamepad #4 +* @name Phaser.Gamepad#pad4 +* @property {Phaser.SinglePad} pad4 - Gamepad #4 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad4", { + + get: function () { + return this._gamepads[3]; + } + +}); + +Phaser.Gamepad.BUTTON_0 = 0; +Phaser.Gamepad.BUTTON_1 = 1; +Phaser.Gamepad.BUTTON_2 = 2; +Phaser.Gamepad.BUTTON_3 = 3; +Phaser.Gamepad.BUTTON_4 = 4; +Phaser.Gamepad.BUTTON_5 = 5; +Phaser.Gamepad.BUTTON_6 = 6; +Phaser.Gamepad.BUTTON_7 = 7; +Phaser.Gamepad.BUTTON_8 = 8; +Phaser.Gamepad.BUTTON_9 = 9; +Phaser.Gamepad.BUTTON_10 = 10; +Phaser.Gamepad.BUTTON_11 = 11; +Phaser.Gamepad.BUTTON_12 = 12; +Phaser.Gamepad.BUTTON_13 = 13; +Phaser.Gamepad.BUTTON_14 = 14; +Phaser.Gamepad.BUTTON_15 = 15; + +Phaser.Gamepad.AXIS_0 = 0; +Phaser.Gamepad.AXIS_1 = 1; +Phaser.Gamepad.AXIS_2 = 2; +Phaser.Gamepad.AXIS_3 = 3; +Phaser.Gamepad.AXIS_4 = 4; +Phaser.Gamepad.AXIS_5 = 5; +Phaser.Gamepad.AXIS_6 = 6; +Phaser.Gamepad.AXIS_7 = 7; +Phaser.Gamepad.AXIS_8 = 8; +Phaser.Gamepad.AXIS_9 = 9; + +// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7). +// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button. +// In other words - discrepancies when using gamepads. + +Phaser.Gamepad.XBOX360_A = 0; +Phaser.Gamepad.XBOX360_B = 1; +Phaser.Gamepad.XBOX360_X = 2; +Phaser.Gamepad.XBOX360_Y = 3; +Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4; +Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5; +Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6; +Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7; +Phaser.Gamepad.XBOX360_BACK = 8; +Phaser.Gamepad.XBOX360_START = 9; +Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11; + +Phaser.Gamepad.XBOX360_DPAD_LEFT = 14; +Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15; +Phaser.Gamepad.XBOX360_DPAD_UP = 12; +Phaser.Gamepad.XBOX360_DPAD_DOWN = 13; + +// On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right +Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0; +Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1; +Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2; +Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3; + +// PlayStation 3 controller (masquerading as xbox360 controller) button mappings + +Phaser.Gamepad.PS3XC_X = 0; +Phaser.Gamepad.PS3XC_CIRCLE = 1; +Phaser.Gamepad.PS3XC_SQUARE = 2; +Phaser.Gamepad.PS3XC_TRIANGLE = 3; +Phaser.Gamepad.PS3XC_L1 = 4; +Phaser.Gamepad.PS3XC_R1 = 5; +Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_SELECT = 8; +Phaser.Gamepad.PS3XC_START = 9; +Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11; +Phaser.Gamepad.PS3XC_DPAD_UP = 12; +Phaser.Gamepad.PS3XC_DPAD_DOWN = 13; +Phaser.Gamepad.PS3XC_DPAD_LEFT = 14; +Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15; +Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1 + +/** +* @author @karlmacklin +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A single Phaser Gamepad +* +* @class Phaser.SinglePad +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this) +*/ +Phaser.SinglePad = function (game, padParent) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {number} index - The gamepad index as per browsers data + * @readonly + */ + this.index = null; + + /** + * @property {boolean} connected - Whether or not this particular gamepad is connected or not. + * @readonly + */ + this.connected = false; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time a button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time an axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates. + */ + this.deadZone = 0.26; + + /** + * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object + * @private + */ + this._padParent = padParent; + + /** + * @property {object} _rawPad - The 'raw' gamepad data. + * @private + */ + this._rawPad = null; + + /** + * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads. + * @private + */ + this._prevTimestamp = null; + + /** + * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected. + * @private + */ + this._buttons = []; + + /** + * @property {number} _buttonsLen - Length of the _buttons array. + * @private + */ + this._buttonsLen = 0; + + /** + * @property {Array} _axes - Current axes state. + * @private + */ + this._axes = []; + + /** + * @property {number} _axesLen - Length of the _axes array. + * @private + */ + this._axesLen = 0; + +}; + +Phaser.SinglePad.prototype = { + + /** + * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. + * + * @method Phaser.SinglePad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callbak methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + + this.callbackContext = context; + } + }, + + /** + * Gets a DeviceButton object from this controller to be stored and referenced locally. + * The DeviceButton object can then be polled, have events attached to it, etc. + * + * @method Phaser.SinglePad#getButton + * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc. + * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly. + */ + getButton: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode]; + } + else + { + return null; + } + + }, + + /** + * Main update function called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#pollStatus + */ + pollStatus: function () { + + if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp))) + { + return; + } + + for (var i = 0; i < this._buttonsLen; i++) + { + var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i]; + + if (rawButtonVal !== this._buttons[i].value) + { + if (rawButtonVal === 1) + { + this.processButtonDown(i, rawButtonVal); + } + else if (rawButtonVal === 0) + { + this.processButtonUp(i, rawButtonVal); + } + else + { + this.processButtonFloat(i, rawButtonVal); + } + } + } + + for (var index = 0; index < this._axesLen; index++) + { + var value = this._rawPad.axes[index]; + + if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone)) + { + this.processAxisChange(index, value); + } + else + { + this.processAxisChange(index, 0); + } + } + + this._prevTimestamp = this._rawPad.timestamp; + + }, + + /** + * Gamepad connect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#connect + * @param {object} rawPad - The raw gamepad object + */ + connect: function (rawPad) { + + var triggerCallback = !this.connected; + + this.connected = true; + this.index = rawPad.index; + + this._rawPad = rawPad; + + this._buttons = []; + this._buttonsLen = rawPad.buttons.length; + + this._axes = []; + this._axesLen = rawPad.axes.length; + + for (var a = 0; a < this._axesLen; a++) + { + this._axes[a] = rawPad.axes[a]; + } + + for (var buttonCode in rawPad.buttons) + { + buttonCode = parseInt(buttonCode, 10); + this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode); + } + + if (triggerCallback && this._padParent.onConnectCallback) + { + this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index); + } + + if (triggerCallback && this.onConnectCallback) + { + this.onConnectCallback.call(this.callbackContext); + } + + }, + + /** + * Gamepad disconnect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#disconnect + */ + disconnect: function () { + + var triggerCallback = this.connected; + var disconnectingIndex = this.index; + + this.connected = false; + this.index = null; + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + if (triggerCallback && this._padParent.onDisconnectCallback) + { + this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex); + } + + if (triggerCallback && this.onDisconnectCallback) + { + this.onDisconnectCallback.call(this.callbackContext); + } + + }, + + /** + * Destroys this object and associated callback references. + * + * @method Phaser.SinglePad#destroy + */ + destroy: function () { + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + this.onConnectCallback = null; + this.onDisconnectCallback = null; + this.onDownCallback = null; + this.onUpCallback = null; + this.onAxisCallback = null; + this.onFloatCallback = null; + + }, + + /** + * Handles changes in axis. + * + * @method Phaser.SinglePad#processAxisChange + * @param {object} axisState - State of the relevant axis + */ + processAxisChange: function (index, value) { + + if (this._axes[index] === value) + { + return; + } + + this._axes[index] = value; + + if (this._padParent.onAxisCallback) + { + this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value); + } + + if (this.onAxisCallback) + { + this.onAxisCallback.call(this.callbackContext, this, index, value); + } + + }, + + /** + * Handles button down press. + * + * @method Phaser.SinglePad#processButtonDown + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonDown: function (buttonCode, value) { + + if (this._buttons[buttonCode]) + { + this._buttons[buttonCode].start(null, value); + } + + 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); + } + + }, + + /** + * Handles button release. + * + * @method Phaser.SinglePad#processButtonUp + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonUp: function (buttonCode, value) { + + 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._buttons[buttonCode]) + { + this._buttons[buttonCode].stop(null, value); + } + + }, + + /** + * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) + * + * @method Phaser.SinglePad#processButtonFloat + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. + */ + processButtonFloat: function (buttonCode, value) { + + 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].padFloat(value); + } + + }, + + /** + * Returns value of requested axis. + * + * @method Phaser.SinglePad#axis + * @param {number} axisCode - The index of the axis to check + * @return {number} Axis value if available otherwise false + */ + axis: function (axisCode) { + + if (this._axes[axisCode]) + { + return this._axes[axisCode]; + } + + return false; + + }, + + /** + * Returns true if the button is pressed down. + * + * @method Phaser.SinglePad#isDown + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is pressed down. + */ + isDown: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isDown; + } + + return false; + + }, + + /** + * Returns true if the button is not currently pressed. + * + * @method Phaser.SinglePad#isUp + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is not currently pressed down. + */ + isUp: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isUp; + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justReleased + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justReleased(duration); + } + + }, + + /** + * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justPressed(duration); + } + + }, + + /** + * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example + * analog trigger buttons on the XBOX 360 controller. + * + * @method Phaser.SinglePad#buttonValue + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. + */ + buttonValue: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].value; + } + + return null; + + }, + + /** + * Reset all buttons/axes of this gamepad. + * + * @method Phaser.SinglePad#reset + */ + reset: function () { + + for (var j = 0; j < this._axes.length; j++) + { + this._axes[j] = 0; + } + + } + +}; + +Phaser.SinglePad.prototype.constructor = Phaser.SinglePad; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. +* +* @class Phaser.Key +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}. +*/ +Phaser.Key = function (game, keycode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * The enabled state of the key - see `enabled`. + * @property {boolean} _enabled + * @private + */ + this._enabled = true; + + /** + * @property {object} event - Stores the most recent DOM event. + * @readonly + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * @default + */ + this.isUp = true; + + /** + * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. + * @default + */ + this.altKey = false; + + /** + * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. + * @default + */ + this.ctrlKey = false; + + /** + * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. + * @default + */ + this.shiftKey = false; + + /** + * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now. + */ + this.timeDown = 0; + + /** + * If the key is down this value holds the duration of that key press and is constantly updated. + * If the key is up it holds the duration of the previous down session. + * @property {number} duration - The number of milliseconds this key has been held down for. + * @default + */ + this.duration = 0; + + /** + * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now. + * @default + */ + this.timeUp = -2500; + + /** + * If the key is up this value holds the duration of that key release and is constantly updated. + * If the key is down it holds the duration of the previous up session. + * @property {number} duration - The number of milliseconds this key has been up for. + * @default + */ + this.durationUp = -2500; + + /** + * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. + * @default + */ + this.repeats = 0; + + /** + * @property {number} keyCode - The keycode of this key. + */ + this.keyCode = keycode; + + /** + * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). + */ + this.onDown = new Phaser.Signal(); + + /** + * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. + */ + this.onHoldCallback = null; + + /** + * @property {object} onHoldContext - The context under which the onHoldCallback will be called. + */ + this.onHoldContext = null; + + /** + * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). + */ + this.onUp = new Phaser.Signal(); + + /** + * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justDown = false; + + /** + * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justUp = false; + +}; + +Phaser.Key.prototype = { + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#update + * @protected + */ + update: function () { + + if (!this._enabled) { return; } + + if (this.isDown) + { + this.duration = this.game.time.time - this.timeDown; + this.repeats++; + + if (this.onHoldCallback) + { + this.onHoldCallback.call(this.onHoldContext, this); + } + } + else + { + this.durationUp = this.game.time.time - this.timeUp; + } + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyDown + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyDown: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + // exit if this key down is from auto-repeat + if (this.isDown) + { + return; + } + + this.altKey = event.altKey; + this.ctrlKey = event.ctrlKey; + this.shiftKey = event.shiftKey; + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.duration = 0; + this.durationUp = this.game.time.time - this.timeUp; + this.repeats = 0; + + // _justDown will remain true until it is read via the justDown Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justDown = true; + + this.onDown.dispatch(this); + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyUp + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyUp: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = this.game.time.time - this.timeDown; + this.durationUp = 0; + + // _justUp will remain true until it is read via the justUp Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justUp = true; + + this.onUp.dispatch(this); + + }, + + /** + * Resets the state of this Key. + * + * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key. + * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. + * + * @method Phaser.Key#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = 0; + this.durationUp = -2500; + this._enabled = true; // .enabled causes reset(false) + this._justDown = false; + this._justUp = false; + + if (hard) + { + this.onDown.removeAll(); + this.onUp.removeAll(); + this.onHoldCallback = null; + this.onHoldContext = null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#downDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration. + */ + downDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (this.isDown && this.duration < duration); + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#upDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration. + */ + upDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (!this.isDown && ((this.game.time.time - this.timeUp) < duration)); + + }, + + /** + * Returns `true` if the Key was just pressed down this update tick, or `false` if it either isn't down, + * or was pressed down on a previous update tick. + * + * @method Phaser.Key#justPressed + * @return {boolean} True if the key was just pressed down this update tick. + */ + justPressed: function () { + + return (this.isDown && this.duration === 0); + + }, + + /** + * Returns `true` if the Key was just released this update tick, or `false` if it either isn't up, + * or was released on a previous update tick. + * + * @method Phaser.Key#justReleased + * @return {boolean} True if the key was just released this update tick. + */ + justReleased: function () { + + return (!this.isDown && this.durationUp === 0); + + } + +}; + +/** +* The justDown value allows you to test if this Key has just been pressed down or not. +* When you check this value it will return `true` if the Key is down, otherwise `false`. +* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. +* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justDown +* @property {boolean} justDown +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justDown", { + + get: function () { + + var current = this._justDown; + this._justDown = false; + return current; + + } + +}); + +/** +* The justUp value allows you to test if this Key has just been released or not. +* When you check this value it will return `true` if the Key is up, otherwise `false`. +* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again. +* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justUp +* @property {boolean} justUp +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justUp", { + + get: function () { + + var current = this._justUp; + this._justUp = false; + return current; + + } + +}); + +/** +* An enabled key processes its update and dispatches events. +* A key can be disabled momentarily at runtime instead of deleting it. +* @name Phaser.Key#enabled +* @property {boolean} enabled +* @memberof Phaser.Key +* @default true +*/ +Object.defineProperty(Phaser.Key.prototype, "enabled", { + + get: function () { + + return this._enabled; + + }, + + set: function (value) { + + value = !!value; + + if (value !== this._enabled) + { + if (!value) + { + this.reset(false); + } + + this._enabled = value; + } + } + +}); + +Phaser.Key.prototype.constructor = Phaser.Key; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Keyboard class monitors keyboard input and dispatches keyboard events. +* +* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. +* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. +* +* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. +* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. +* So please check your extensions before opening Phaser issues. +* +* @class Phaser.Keyboard +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Keyboard = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Keyboard input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. + */ + this.event = null; + + /** + * @property {object} pressEvent - The most recent DOM event from keypress. + */ + this.pressEvent = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. + */ + this.onDownCallback = null; + + /** + * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. + */ + this.onPressCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a key is released. + */ + this.onUpCallback = null; + + /** + * @property {array} _keys - The array the Phaser.Key objects are stored in. + * @private + */ + this._keys = []; + + /** + * @property {array} _capture - The array the key capture values are stored in. + * @private + */ + this._capture = []; + + /** + * @property {function} _onKeyDown + * @private + * @default + */ + this._onKeyDown = null; + + /** + * @property {function} _onKeyPress + * @private + * @default + */ + this._onKeyPress = null; + + /** + * @property {function} _onKeyUp + * @private + * @default + */ + this._onKeyUp = null; + + /** + * @property {number} _i - Internal cache var + * @private + */ + this._i = 0; + + /** + * @property {number} _k - Internal cache var + * @private + */ + this._k = 0; + +}; + +Phaser.Keyboard.prototype = { + + /** + * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. + * + * @method Phaser.Keyboard#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down. + * @param {function} [onUp=null] - This callback is invoked every time a key is released. + * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised. + */ + addCallbacks: function (context, onDown, onUp, onPress) { + + this.callbackContext = context; + + if (onDown !== undefined && onDown !== null) + { + this.onDownCallback = onDown; + } + + if (onUp !== undefined && onUp !== null) + { + this.onUpCallback = onUp; + } + + if (onPress !== undefined && onPress !== null) + { + this.onPressCallback = onPress; + } + + }, + + /** + * Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}. + * + * @method Phaser.Keyboard#removeCallbacks + */ + removeCallbacks: function () { + + this.callbackContext = this; + this.onDownCallback = null; + this.onUpCallback = null; + this.onPressCallback = null; + + }, + + /** + * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. + * The Key object can then be polled, have events attached to it, etc. + * + * @method Phaser.Keyboard#addKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key. + * @return {Phaser.Key} The Key object which you can store locally and reference directly. + */ + addKey: function (keycode) { + + if (!this._keys[keycode]) + { + this._keys[keycode] = new Phaser.Key(this.game, keycode); + + this.addKeyCapture(keycode); + } + + return this._keys[keycode]; + + }, + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example, + * + * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); + * + * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object. + * + * @method Phaser.Keyboard#addKeys + * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. + * @return {object} An object containing the properties mapped to {@link Phaser.Key} values. + */ + addKeys: function (keys) { + + var output = {}; + + for (var key in keys) + { + output[key] = this.addKey(keys[key]); + } + + return output; + + }, + + /** + * Removes a Key object from the Keyboard manager. + * + * @method Phaser.Keyboard#removeKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove. + */ + removeKey: function (keycode) { + + if (this._keys[keycode]) + { + this._keys[keycode] = null; + + this.removeKeyCapture(keycode); + } + + }, + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. + * + * @method Phaser.Keyboard#createCursorKeys + * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects. + */ + createCursorKeys: function () { + + return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT }); + + }, + + /** + * Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window. + * This is called automatically by Phaser.Input and should not normally be invoked directly. + * + * @method Phaser.Keyboard#start + * @protected + */ + start: function () { + + if (this.game.device.cocoonJS) + { + return; + } + + if (this._onKeyDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onKeyDown = function (event) { + return _this.processKeyDown(event); + }; + + this._onKeyUp = function (event) { + return _this.processKeyUp(event); + }; + + this._onKeyPress = function (event) { + return _this.processKeyPress(event); + }; + + window.addEventListener('keydown', this._onKeyDown, false); + window.addEventListener('keyup', this._onKeyUp, false); + window.addEventListener('keypress', this._onKeyPress, false); + + }, + + /** + * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. + * + * @method Phaser.Keyboard#stop + */ + stop: function () { + + window.removeEventListener('keydown', this._onKeyDown); + window.removeEventListener('keyup', this._onKeyUp); + window.removeEventListener('keypress', this._onKeyPress); + + this._onKeyDown = null; + this._onKeyUp = null; + this._onKeyPress = null; + + }, + + /** + * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. + * Also clears all key captures and currently created Key objects. + * + * @method Phaser.Keyboard#destroy + */ + destroy: function () { + + this.stop(); + + this.clearCaptures(); + + this._keys.length = 0; + this._i = 0; + + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Pass in either a single keycode or an array/hash of keycodes. + * + * @method Phaser.Keyboard#addKeyCapture + * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`. + */ + addKeyCapture: function (keycode) { + + if (typeof keycode === 'object') + { + for (var key in keycode) + { + this._capture[keycode[key]] = true; + } + } + else + { + this._capture[keycode] = true; + } + }, + + /** + * Removes an existing key capture. + * + * @method Phaser.Keyboard#removeKeyCapture + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of. + */ + removeKeyCapture: function (keycode) { + + delete this._capture[keycode]; + + }, + + /** + * Clear all set key captures. + * + * @method Phaser.Keyboard#clearCaptures + */ + clearCaptures: function () { + + this._capture = {}; + + }, + + /** + * Updates all currently defined keys. + * + * @method Phaser.Keyboard#update + */ + update: function () { + + this._i = this._keys.length; + + while (this._i--) + { + if (this._keys[this._i]) + { + this._keys[this._i].update(); + } + } + + }, + + /** + * Process the keydown event. + * + * @method Phaser.Keyboard#processKeyDown + * @param {KeyboardEvent} event + * @protected + */ + processKeyDown: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + // The event is being captured but another hotkey may need it + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyDown(event); + + this._k = key; + + if (this.onDownCallback) + { + this.onDownCallback.call(this.callbackContext, event); + } + + }, + + /** + * Process the keypress event. + * + * @method Phaser.Keyboard#processKeyPress + * @param {KeyboardEvent} event + * @protected + */ + processKeyPress: function (event) { + + this.pressEvent = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.onPressCallback) + { + this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event); + } + + }, + + /** + * Process the keyup event. + * + * @method Phaser.Keyboard#processKeyUp + * @param {KeyboardEvent} event + * @protected + */ + processKeyUp: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyUp(event); + + if (this.onUpCallback) + { + this.onUpCallback.call(this.callbackContext, event); + } + + }, + + /** + * Resets all Keys. + * + * @method Phaser.Keyboard#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.event = null; + + var i = this._keys.length; + + while (i--) + { + if (this._keys[i]) + { + this._keys[i].reset(hard); + } + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#downDuration + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. + */ + downDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].downDuration(duration); + } + else + { + return null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#upDuration + * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found. + */ + upDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].upDuration(duration); + } + else + { + return null; + } + + }, + + justPressed: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justPressed(); + } + else + { + return null; + } + + }, + + justReleased: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justReleased(); + } + else + { + return null; + } + + }, + + /** + * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. + * + * @method Phaser.Keyboard#isDown + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found. + */ + isDown: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].isDown; + } + else + { + return null; + } + + } + +}; + +/** +* Returns the string value of the most recently pressed key. +* @name Phaser.Keyboard#lastChar +* @property {string} lastChar - The string value of the most recently pressed key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", { + + get: function () { + + if (this.event && this.event.charCode === 32) + { + return ''; + } + else if (this.pressEvent) + { + return String.fromCharCode(this.pressEvent.charCode); + } + else + { + return null; + } + + } + +}); + +/** +* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. +* @name Phaser.Keyboard#lastKey +* @property {Phaser.Key} lastKey - The most recently pressed Key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", { + + get: function () { + + return this._keys[this._k]; + + } + +}); + +Phaser.Keyboard.prototype.constructor = Phaser.Keyboard; + +/** +* A key code represents a physical key on a keyboard. +* +* The KeyCode class contains commonly supported keyboard key codes which can be used +* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods. +* +* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. +* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. +* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property. +* +* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; +* the latter approach is supported for compatibility. +* +* @class Phaser.KeyCode +*/ +Phaser.KeyCode = { + /** @static */ + A: "A".charCodeAt(0), + /** @static */ + B: "B".charCodeAt(0), + /** @static */ + C: "C".charCodeAt(0), + /** @static */ + D: "D".charCodeAt(0), + /** @static */ + E: "E".charCodeAt(0), + /** @static */ + F: "F".charCodeAt(0), + /** @static */ + G: "G".charCodeAt(0), + /** @static */ + H: "H".charCodeAt(0), + /** @static */ + I: "I".charCodeAt(0), + /** @static */ + J: "J".charCodeAt(0), + /** @static */ + K: "K".charCodeAt(0), + /** @static */ + L: "L".charCodeAt(0), + /** @static */ + M: "M".charCodeAt(0), + /** @static */ + N: "N".charCodeAt(0), + /** @static */ + O: "O".charCodeAt(0), + /** @static */ + P: "P".charCodeAt(0), + /** @static */ + Q: "Q".charCodeAt(0), + /** @static */ + R: "R".charCodeAt(0), + /** @static */ + S: "S".charCodeAt(0), + /** @static */ + T: "T".charCodeAt(0), + /** @static */ + U: "U".charCodeAt(0), + /** @static */ + V: "V".charCodeAt(0), + /** @static */ + W: "W".charCodeAt(0), + /** @static */ + X: "X".charCodeAt(0), + /** @static */ + Y: "Y".charCodeAt(0), + /** @static */ + Z: "Z".charCodeAt(0), + /** @static */ + ZERO: "0".charCodeAt(0), + /** @static */ + ONE: "1".charCodeAt(0), + /** @static */ + TWO: "2".charCodeAt(0), + /** @static */ + THREE: "3".charCodeAt(0), + /** @static */ + FOUR: "4".charCodeAt(0), + /** @static */ + FIVE: "5".charCodeAt(0), + /** @static */ + SIX: "6".charCodeAt(0), + /** @static */ + SEVEN: "7".charCodeAt(0), + /** @static */ + EIGHT: "8".charCodeAt(0), + /** @static */ + NINE: "9".charCodeAt(0), + /** @static */ + NUMPAD_0: 96, + /** @static */ + NUMPAD_1: 97, + /** @static */ + NUMPAD_2: 98, + /** @static */ + NUMPAD_3: 99, + /** @static */ + NUMPAD_4: 100, + /** @static */ + NUMPAD_5: 101, + /** @static */ + NUMPAD_6: 102, + /** @static */ + NUMPAD_7: 103, + /** @static */ + NUMPAD_8: 104, + /** @static */ + NUMPAD_9: 105, + /** @static */ + NUMPAD_MULTIPLY: 106, + /** @static */ + NUMPAD_ADD: 107, + /** @static */ + NUMPAD_ENTER: 108, + /** @static */ + NUMPAD_SUBTRACT: 109, + /** @static */ + NUMPAD_DECIMAL: 110, + /** @static */ + NUMPAD_DIVIDE: 111, + /** @static */ + F1: 112, + /** @static */ + F2: 113, + /** @static */ + F3: 114, + /** @static */ + F4: 115, + /** @static */ + F5: 116, + /** @static */ + F6: 117, + /** @static */ + F7: 118, + /** @static */ + F8: 119, + /** @static */ + F9: 120, + /** @static */ + F10: 121, + /** @static */ + F11: 122, + /** @static */ + F12: 123, + /** @static */ + F13: 124, + /** @static */ + F14: 125, + /** @static */ + F15: 126, + /** @static */ + COLON: 186, + /** @static */ + EQUALS: 187, + /** @static */ + COMMA: 188, + /** @static */ + UNDERSCORE: 189, + /** @static */ + PERIOD: 190, + /** @static */ + QUESTION_MARK: 191, + /** @static */ + TILDE: 192, + /** @static */ + OPEN_BRACKET: 219, + /** @static */ + BACKWARD_SLASH: 220, + /** @static */ + CLOSED_BRACKET: 221, + /** @static */ + QUOTES: 222, + /** @static */ + BACKSPACE: 8, + /** @static */ + TAB: 9, + /** @static */ + CLEAR: 12, + /** @static */ + ENTER: 13, + /** @static */ + SHIFT: 16, + /** @static */ + CONTROL: 17, + /** @static */ + ALT: 18, + /** @static */ + CAPS_LOCK: 20, + /** @static */ + ESC: 27, + /** @static */ + SPACEBAR: 32, + /** @static */ + PAGE_UP: 33, + /** @static */ + PAGE_DOWN: 34, + /** @static */ + END: 35, + /** @static */ + HOME: 36, + /** @static */ + LEFT: 37, + /** @static */ + UP: 38, + /** @static */ + RIGHT: 39, + /** @static */ + DOWN: 40, + /** @static */ + PLUS: 43, + /** @static */ + MINUS: 44, + /** @static */ + INSERT: 45, + /** @static */ + DELETE: 46, + /** @static */ + HELP: 47, + /** @static */ + NUM_LOCK: 144 +}; + +// Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility +for (var key in Phaser.KeyCode) +{ + if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/)) + { + Phaser.Keyboard[key] = Phaser.KeyCode[key]; + } +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +Phaser.Component = function () {}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. +* +* @class +*/ +Phaser.Component.Angle = function () {}; + +Phaser.Component.Angle.prototype = { + + /** + * The angle property is the rotation of the Game Object in *degrees* from its original orientation. + * + * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. + * + * Values outside this range are added to or subtracted from 360 to obtain a value within the range. + * For example, the statement player.angle = 450 is the same as player.angle = 90. + * + * If you wish to work in radians instead of degrees you can use the property `rotation` instead. + * Working in radians is slightly faster as it doesn't have to perform any calculations. + * + * @property {number} angle + */ + angle: { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); + + }, + + set: function(value) { + + this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. +* +* @class +*/ +Phaser.Component.Animation = function () {}; + +Phaser.Component.Animation.prototype = { + + /** + * Plays an Animation. + * + * The animation should have previously been created via `animations.add`. + * + * If the animation is already playing calling this again won't do anything. + * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. + * + * @method + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation. + */ + play: function (name, frameRate, loop, killOnComplete) { + + if (this.animations) + { + return this.animations.play(name, frameRate, loop, killOnComplete); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. +* It is used by the InWorld component. +* +* @class +*/ +Phaser.Component.AutoCull = function () {}; + +Phaser.Component.AutoCull.prototype = { + + /** + * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. + * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. + * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} autoCull + * @default + */ + autoCull: false, + + /** + * Checks if the Game Objects bounds intersect with the Game Camera bounds. + * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + if (!this.autoCull && !this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + } + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Bounds component contains properties related to the bounds of the Game Object. +* +* @class +*/ +Phaser.Component.Bounds = function () {}; + +Phaser.Component.Bounds.prototype = { + + /** + * The amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * anchor.x`. + * It will only be > 0 if anchor.x is not equal to zero. + * + * @property {number} offsetX + * @readOnly + */ + offsetX: { + + get: function () { + + return this.anchor.x * this.width; + + } + + }, + + /** + * The amount the Game Object is visually offset from its y coordinate. + * This is the same as `height * anchor.y`. + * It will only be > 0 if anchor.y is not equal to zero. + * + * @property {number} offsetY + * @readOnly + */ + offsetY: { + + get: function () { + + return this.anchor.y * this.height; + + } + + }, + + /** + * The local center x coordinate of the Game Object. + * This is the same as `(x - offsetX) + (width / 2)`. + * + * @property {number} centerX + */ + centerX: { + + get: function () { + + return (this.x - this.offsetX) + (this.width * 0.5); + + }, + + set: function (value) { + + this.x = (value + this.offsetX) - (this.width * 0.5); + + } + + }, + + /** + * The local center y coordinate of the Game Object. + * This is the same as `(y - offsetY) + (height / 2)`. + * + * @property {number} centerY + */ + centerY: { + + get: function () { + + return (this.y - this.offsetY) + (this.height * 0.5); + + }, + + set: function (value) { + + this.y = (value + this.offsetY) - (this.height * 0.5); + + } + + }, + + /** + * The left coordinate of the Game Object. + * This is the same as `x - offsetX`. + * + * @property {number} left + */ + left: { + + get: function () { + + return this.x - this.offsetX; + + }, + + set: function (value) { + + this.x = value + this.offsetX; + + } + + }, + + /** + * The right coordinate of the Game Object. + * This is the same as `x + width - offsetX`. + * + * @property {number} right + */ + right: { + + get: function () { + + return (this.x + this.width) - this.offsetX; + + }, + + set: function (value) { + + this.x = value - (this.width) + this.offsetX; + + } + + }, + + /** + * The y coordinate of the Game Object. + * This is the same as `y - offsetY`. + * + * @property {number} top + */ + top: { + + get: function () { + + return this.y - this.offsetY; + + }, + + set: function (value) { + + this.y = value + this.offsetY; + + } + + }, + + /** + * The sum of the y and height properties. + * This is the same as `y + height - offsetY`. + * + * @property {number} bottom + */ + bottom: { + + get: function () { + + return (this.y + this.height) - this.offsetY; + + }, + + set: function (value) { + + this.y = value - (this.height) + this.offsetY; + + } + + }, + + /** + * Aligns this Game Object within another Game Object, or Rectangle, known as the + * 'container', to one of 9 possible positions. + * + * The container must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the container. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, + * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * container, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignIn: function (container, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = container.left - offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = container.centerX + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = container.right + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.left = container.left - offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.CENTER: + this.centerX = container.centerX + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.right = container.right + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = container.left - offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = container.centerX + offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = container.right + offsetX; + this.bottom = container.bottom + offsetY; + break; + } + + return this; + + }, + + /** + * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the + * 'parent', in one of 11 possible positions. + * + * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the parent. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, + * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, + * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * parent, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignTo: function (parent, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = parent.left - offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = parent.centerX + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = parent.right + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.LEFT_TOP: + this.right = parent.left - offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.right = parent.left - offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.LEFT_BOTTOM: + this.right = parent.left - offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.RIGHT_TOP: + this.left = parent.right + offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.left = parent.right + offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.RIGHT_BOTTOM: + this.left = parent.right + offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = parent.left - offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = parent.centerX + offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = parent.right + offsetX; + this.top = parent.bottom + offsetY; + break; + } + + return this; + + } + +}; + +// Phaser.Group extensions + +Phaser.Group.prototype.alignIn = Phaser.Component.Bounds.prototype.alignIn; +Phaser.Group.prototype.alignTo = Phaser.Component.Bounds.prototype.alignTo; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The BringToTop Component features quick access to Group sorting related methods. +* +* @class +*/ +Phaser.Component.BringToTop = function () {}; + +/** +* Brings this Game Object to the top of its parents display list. +* Visually this means it will render over the top of any old child in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.bringToTop = function() { + + if (this.parent) + { + this.parent.bringToTop(this); + } + + return this; + +}; + +/** +* Sends this Game Object to the bottom of its parents display list. +* Visually this means it will render below all other children in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.sendToBack = function() { + + if (this.parent) + { + this.parent.sendToBack(this); + } + + return this; + +}; + +/** +* Moves this Game Object up one place in its parents display list. +* This call has no effect if the Game Object is already at the top of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveUp = function () { + + if (this.parent) + { + this.parent.moveUp(this); + } + + return this; + +}; + +/** +* Moves this Game Object down one place in its parents display list. +* This call has no effect if the Game Object is already at the bottom of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveDown = function () { + + if (this.parent) + { + this.parent.moveDown(this); + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Core Component Features. +* +* @class +*/ +Phaser.Component.Core = function () {}; + +/** + * @property {boolean} skipTypeChecks - Skip type checks in {@link #init}. + * @static + * @default + */ +Phaser.Component.Core.skipTypeChecks = false; + +/** +* Installs / registers mixin components. +* +* The `this` context should be that of the applicable object instance or prototype. +* +* @method +* @protected +*/ +Phaser.Component.Core.install = function (components) { + + // Always install 'Core' first + Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype); + + this.components = {}; + + for (var i = 0; i < components.length; i++) + { + var id = components[i]; + var replace = false; + + if (id === 'Destroy') + { + replace = true; + } + + Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace); + + this.components[id] = true; + } + +}; + +/** +* Initializes the mixin components. +* +* The `this` context should be an instance of the component mixin target. +* +* @method +* @protected +*/ +Phaser.Component.Core.init = function (game, x, y, key, frame) { + + if (!Phaser.Component.Core.skipTypeChecks) + { + if (!(game instanceof Phaser.Game)) + { + throw new Error('The value passed as the `game` argument (' + game + ') is not an instance of Phaser.Game.'); + } + + if (typeof x !== 'number') + { + console.warn('The `x` argument value (%s) should be a number.', x); + x = 0; // This would be done implicitly in position.set(). + } + + if (typeof y !== 'number') + { + console.warn('The `y` argument value (%s) should be a number.', y); + y = 0; // This would be done implicitly in position.set(). + } + } + + this.game = game; + this.key = key; + this.data = {}; + + this.position.set(x, y); + this.world = new Phaser.Point(x, y); + this.previousPosition = new Phaser.Point(x, y); + + this.events = new Phaser.Events(this); + + this._bounds = new Phaser.Rectangle(); + + if (this.components.PhysicsBody) + { + // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype. + this.body = this.body; + } + + if (this.components.Animation) + { + this.animations = new Phaser.AnimationManager(this); + } + + if (this.components.LoadTexture && key !== null) + { + this.loadTexture(key, frame); + } + + if (this.components.FixedToCamera) + { + this.cameraOffset = new Phaser.Point(x, y); + } + +}; + +Phaser.Component.Core.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty); + + if (this.visible) + { + this.renderOrderID = this.game.stage.currentRenderOrderID++; + } + + if (this.animations) + { + this.animations.update(); + } + + if (this.body) + { + this.body.preUpdate(); + } + + this.preUpdateChildren(); + + return true; + +}; + +Phaser.Component.Core.prototype = { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + game: null, + + /** + * A user defined name given to this Game Object. + * This value isn't ever used internally by Phaser, it is meant as a game level property. + * @property {string} name + * @default + */ + name: '', + + /** + * An empty Object that belongs to this Game Object. + * This value isn't ever used internally by Phaser, but may be used by your own code, or + * by Phaser Plugins, to store data that needs to be associated with the Game Object, + * without polluting the Game Object directly. + * @property {Object} data + * @default + */ + data: {}, + + /** + * The components this Game Object has installed. + * @property {object} components + * @protected + */ + components: {}, + + /** + * The z depth of this Game Object within its parent Group. + * No two objects in a Group can have the same z value. + * This value is adjusted automatically whenever the Group hierarchy changes. + * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. + * @property {number} z + * @readOnly + */ + z: 0, + + /** + * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this + * Game Object, or any of its components. + * @see Phaser.Events + * @property {Phaser.Events} events + */ + events: undefined, + + /** + * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. + * Through it you can create, play, pause and stop animations. + * @see Phaser.AnimationManager + * @property {Phaser.AnimationManager} animations + */ + animations: undefined, + + /** + * The key of the image or texture used by this Game Object during rendering. + * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. + * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. + * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. + * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key + */ + key: '', + + /** + * The world coordinates of this Game Object in pixels. + * Depending on where in the display list this Game Object is placed this value can differ from `position`, + * which contains the x/y coordinates relative to the Game Objects parent. + * @property {Phaser.Point} world + */ + world: null, + + /** + * A debug flag designed for use with `Game.enableStep`. + * @property {boolean} debug + * @default + */ + debug: false, + + /** + * The position the Game Object was located in the previous frame. + * @property {Phaser.Point} previousPosition + * @readOnly + */ + previousPosition: null, + + /** + * The rotation the Game Object was in set to in the previous frame. Value is in radians. + * @property {number} previousRotation + * @readOnly + */ + previousRotation: 0, + + /** + * The render order ID is used internally by the renderer and Input Manager and should not be modified. + * This property is mostly used internally by the renderers, but is exposed for the use of plugins. + * @property {number} renderOrderID + * @readOnly + */ + renderOrderID: 0, + + /** + * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. + * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. + * @property {boolean} fresh + * @readOnly + */ + fresh: true, + + /** + * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. + * You can set it directly to allow you to flag an object to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy an object from within one of its own callbacks + * such as with Buttons or other Input events. + * + * @property {boolean} pendingDestroy + */ + pendingDestroy: false, + + /** + * @property {Phaser.Rectangle} _bounds - Internal cache var. + * @private + */ + _bounds: null, + + /** + * @property {boolean} _exists - Internal cache var. + * @private + */ + _exists: true, + + /** + * Controls if this Game Object is processed by the core game loop. + * If this Game Object has a physics body it also controls if its physics body is updated or not. + * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. + * It also toggles the `visible` property to false as well. + * + * Setting `exists` to true will add its physics body back in to the physics world, if it has one. + * It will also set the `visible` property to `true`. + * + * @property {boolean} exists + */ + exists: { + + get: function () { + + return this._exists; + + }, + + set: function (value) { + + if (value) + { + this._exists = true; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.addToWorld(); + } + + this.visible = true; + } + else + { + this._exists = false; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.removeFromWorld(); + } + + this.visible = false; + } + + } + + }, + + /** + * Internal method called by preUpdate. + * + * @method + * @protected + */ + preUpdateChildren: function() { + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + }, + + /** + * Override this method in your own custom objects to handle any update requirements. + * It is called immediately after `preUpdate` and before `postUpdate`. + * Remember if this Game Object has any children you should call update on those too. + * + * @method + */ + update: function() { + + }, + + /** + * Internal method called by the World postUpdate cycle. + * + * @method + * @protected + */ + postUpdate: function() { + + if (this.customRender) + { + this.key.render(); + } + + if (this.components.PhysicsBody) + { + Phaser.Component.PhysicsBody.postUpdate.call(this); + } + + if (this.components.FixedToCamera) + { + Phaser.Component.FixedToCamera.postUpdate.call(this); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, +* which can be updated in real-time. +* +* @class +*/ +Phaser.Component.Crop = function () {}; + +Phaser.Component.Crop.prototype = { + + /** + * The Rectangle used to crop the texture this Game Object uses. + * Set this property via `crop`. + * If you modify this property directly you must call `updateCrop` in order to have the change take effect. + * @property {Phaser.Rectangle} cropRect + * @default + */ + cropRect: null, + + /** + * @property {Phaser.Rectangle} _crop - Internal cache var. + * @private + */ + _crop: null, + + /** + * Crop allows you to crop the texture being used to display this Game Object. + * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. + * + * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, + * or by modifying `cropRect` property directly and then calling `updateCrop`. + * + * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object + * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. + * + * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, + * in which case the values are duplicated to a local object. + * + * @method + * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. + * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. + */ + crop: function (rect, copy) { + + if (copy === undefined) { copy = false; } + + if (rect) + { + if (copy && this.cropRect !== null) + { + this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height); + } + else if (copy && this.cropRect === null) + { + this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height); + } + else + { + this.cropRect = rect; + } + + this.updateCrop(); + } + else + { + this._crop = null; + this.cropRect = null; + + this.resetFrame(); + } + + }, + + /** + * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, + * or the rectangle it references, then you need to update the crop frame by calling this method. + * + * @method + */ + updateCrop: function () { + + if (!this.cropRect) + { + return; + } + + var oldX = this.texture.crop.x; + var oldY = this.texture.crop.y; + var oldW = this.texture.crop.width; + var oldH = this.texture.crop.height; + + this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop); + this._crop.x += this._frame.x; + this._crop.y += this._frame.y; + + var cx = Math.max(this._frame.x, this._crop.x); + var cy = Math.max(this._frame.y, this._crop.y); + var cw = Math.min(this._frame.right, this._crop.right) - cx; + var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy; + + this.texture.crop.x = cx; + this.texture.crop.y = cy; + this.texture.crop.width = cw; + this.texture.crop.height = ch; + + this.texture.frame.width = Math.min(cw, this.cropRect.width); + this.texture.frame.height = Math.min(ch, this.cropRect.height); + + this.texture.width = this.texture.frame.width; + this.texture.height = this.texture.frame.height; + + this.texture._updateUvs(); + + if (this.tint !== 0xffffff && (oldX !== cx || oldY !== cy || oldW !== cw || oldH !== ch)) + { + this.texture.requiresReTint = true; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Delta component provides access to delta values between the Game Objects current and previous position. +* +* @class +*/ +Phaser.Component.Delta = function () {}; + +Phaser.Component.Delta.prototype = { + + /** + * Returns the delta x value. The difference between world.x now and in the previous frame. + * + * The value will be positive if the Game Object has moved to the right or negative if to the left. + * + * @property {number} deltaX + * @readonly + */ + deltaX: { + + get: function() { + + return this.world.x - this.previousPosition.x; + + } + + }, + + /** + * Returns the delta y value. The difference between world.y now and in the previous frame. + * + * The value will be positive if the Game Object has moved down or negative if up. + * + * @property {number} deltaY + * @readonly + */ + deltaY: { + + get: function() { + + return this.world.y - this.previousPosition.y; + + } + + }, + + /** + * Returns the delta z value. The difference between rotation now and in the previous frame. + * + * @property {number} deltaZ - The delta value. + * @readonly + */ + deltaZ: { + + get: function() { + + return this.rotation - this.previousRotation; + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Destroy component is responsible for destroying a Game Object. +* +* @class +*/ +Phaser.Component.Destroy = function () {}; + +Phaser.Component.Destroy.prototype = { + + /** + * As a Game Object runs through its destroy method this flag is set to true, + * and can be checked in any sub-systems or plugins it is being destroyed from. + * @property {boolean} destroyPhase + * @readOnly + */ + destroyPhase: false, + + /** + * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present + * and nulls its reference to `game`, freeing it up for garbage collection. + * + * If this Game Object has the Events component it will also dispatch the `onDestroy` event. + * + * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've + * more than one Game Object sharing the same BaseTexture. + * + * @method + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? + * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. + */ + destroy: function (destroyChildren, destroyTexture) { + + if (this.game === null || this.destroyPhase) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (destroyTexture === undefined) { destroyTexture = false; } + + this.destroyPhase = true; + + if (this.events) + { + this.events.onDestroy$dispatch(this); + } + + if (this.parent) + { + if (this.parent instanceof Phaser.Group) + { + this.parent.remove(this); + } + else + { + this.parent.removeChild(this); + } + } + + if (this.input) + { + this.input.destroy(); + } + + if (this.animations) + { + this.animations.destroy(); + } + + if (this.body) + { + this.body.destroy(); + } + + if (this.events) + { + this.events.destroy(); + } + + this.game.tweens.removeFrom(this); + + var i = this.children.length; + + if (destroyChildren) + { + while (i--) + { + this.children[i].destroy(destroyChildren); + } + } + else + { + while (i--) + { + this.removeChild(this.children[i]); + } + } + + if (this._crop) + { + this._crop = null; + this.cropRect = null; + } + + if (this._frame) + { + this._frame = null; + } + + if (Phaser.Video && this.key instanceof Phaser.Video) + { + this.key.onChangeSource.remove(this.resizeFrame, this); + } + + if (Phaser.BitmapText && this._glyphs) + { + this._glyphs = []; + } + + this.alive = false; + this.exists = false; + this.visible = false; + + this.filters = null; + this.mask = null; + this.game = null; + + this.data = {}; + + // In case Pixi is still going to try and render it even though destroyed + this.renderable = false; + + if (this.transformCallback) + { + this.transformCallback = null; + this.transformCallbackContext = null; + } + + // Pixi level DisplayObject destroy + this.hitArea = null; + this.parent = null; + this.stage = null; + this.worldTransform = null; + this.filterArea = null; + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + // Texture? + if (destroyTexture) + { + this.texture.destroy(true); + } + + this.destroyPhase = false; + this.pendingDestroy = false; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Events component is a collection of events fired by the parent Game Object. +* +* Phaser uses what are known as 'Signals' for all event handling. All of the events in +* this class are signals you can subscribe to, much in the same way you'd "listen" for +* an event. +* +* For example to tell when a Sprite has been added to a new group, you can bind a function +* to the {@link #onAddedToGroup} signal: +* +* `sprite.events.onAddedToGroup.add(yourFunction, this);` +* +* Where `yourFunction` is the function you want called when this event occurs. +* +* For more details about how signals work please see the {@link Phaser.Signal} class. +* +* The Input-related events will only be dispatched if the Sprite has had {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true` +* and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. +* +* @class Phaser.Events +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. +*/ +Phaser.Events = function (sprite) { + + /** + * @property {Phaser.Sprite} parent - The Sprite that owns these events. + */ + this.parent = sprite; + + // The signals are automatically added by the corresponding proxy properties + +}; + +Phaser.Events.prototype = { + + /** + * Removes all events. + * + * @method Phaser.Events#destroy + */ + destroy: function () { + + this._parent = null; + + if (this._onDestroy) { this._onDestroy.dispose(); } + if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } + if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } + if (this._onKilled) { this._onKilled.dispose(); } + if (this._onRevived) { this._onRevived.dispose(); } + if (this._onEnterBounds) { this._onEnterBounds.dispose(); } + if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } + + if (this._onInputOver) { this._onInputOver.dispose(); } + if (this._onInputOut) { this._onInputOut.dispose(); } + if (this._onInputDown) { this._onInputDown.dispose(); } + if (this._onInputUp) { this._onInputUp.dispose(); } + if (this._onDragStart) { this._onDragStart.dispose(); } + if (this._onDragUpdate) { this._onDragUpdate.dispose(); } + if (this._onDragStop) { this._onDragStop.dispose(); } + + if (this._onAnimationStart) { this._onAnimationStart.dispose(); } + if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } + if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } + + }, + + // The following properties are sentinels that will be replaced with getters + + /** + * This signal is dispatched when this Game Object is added to a new {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was added to the Group. + * - {Phaser.Group} The Group it was added to. + * + * @property {Phaser.Signal} onAddedToGroup + */ + onAddedToGroup: null, + + /** + * This signal is dispatched when the Game Object is removed from a {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was removed from the Group. + * - {Phaser.Group} The Group it was removed from. + * + * @property {Phaser.Signal} onRemovedFromGroup + */ + onRemovedFromGroup: null, + + /** + * This signal is dispatched when the Game Object is destroyed. + * This happens when {@link Phaser.Sprite#destroy Sprite.destroy()} is called, or {@link Phaser.Group#destroy Group.destroy()} with `destroyChildren` set to true. + * It is sent one argument: + * + * - {any} The Game Object that was destroyed. + * + * @property {Phaser.Signal} onDestroy + */ + onDestroy: null, + + /** + * This signal is dispatched when the Game Object is killed. + * This happens when {@link Phaser.Sprite#kill Sprite.kill()} is called. + * Please understand the difference between {@link Phaser.Sprite#kill kill} and {@link Phaser.Sprite#destroy destroy} by looking at their respective methods. + * It is sent one argument: + * + * - {any} The Game Object that was killed. + * + * @property {Phaser.Signal} onKilled + */ + onKilled: null, + + /** + * This signal is dispatched when the Game Object is revived from a previously killed state. + * This happens when {@link Phaser.Sprite#revive Sprite.revive()} is called. + * It is sent one argument: + * + * - {any} The Game Object that was revived. + * + * @property {Phaser.Signal} onRevived + */ + onRevived: null, + + /** + * This signal is dispatched when the Game Object leaves the Phaser.World {@link Phaser.World#bounds bounds}. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that left the World bounds. + * + * @property {Phaser.Signal} onOutOfBounds + */ + onOutOfBounds: null, + + /** + * This signal is dispatched when the Game Object returns within the Phaser.World {@link Phaser.World#bounds bounds}, having previously been outside of them. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that entered the World bounds. + * + * @property {Phaser.Signal} onEnterBounds + */ + onEnterBounds: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an over event from a {@link Phaser.Pointer}. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOver + */ + onInputOver: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an out event from a {@link Phaser.Pointer}, which was previously over it. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOut + */ + onInputOut: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives a down event from a {@link Phaser.Pointer}. This effectively means the Pointer has been + * pressed down (but not yet released) on the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputDown + */ + onInputDown: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an up event from a {@link Phaser.Pointer}. This effectively means the Pointer had been + * pressed down, and was then released on the Game Object. + * It is sent three arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {boolean} isOver - Is the Pointer still over the Game Object? + * + * @property {Phaser.Signal} onInputUp + */ + onInputUp: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} starts to drag the Game Object, taking into consideration the various + * drag limitations that may be set. + * It is sent four arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The x coordinate that the drag started from. + * - {number} The y coordinate that the drag started from. + * + * @property {Phaser.Signal} onDragStart + */ + onDragStart: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} is actively dragging the Game Object. + * Be warned: This is a high volume Signal. Be careful what you bind to it. + * It is sent six arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The new x coordinate of the Game Object. + * - {number} The new y coordinate of the Game Object. + * - {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. + * - {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. + * + * @property {Phaser.Signal} onDragUpdate + */ + onDragUpdate: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} stops dragging the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onDragStop + */ + onDragStop: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been played. + * You can also listen to {@link Phaser.Animation#onStart} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was started. + * + * @property {Phaser.Signal} onAnimationStart + */ + onAnimationStart: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been stopped (via {@link Phaser.AnimationManager#stop animation.stop()} and the `dispatchComplete` argument has been set. + * You can also listen to {@link Phaser.Animation#onComplete} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was stopped. + * + * @property {Phaser.Signal} onAnimationComplete + */ + onAnimationComplete: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has looped playback. + * You can also listen to {@link Phaser.Animation#onLoop} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that looped. + * + * @property {Phaser.Signal} onAnimationLoop + */ + onAnimationLoop: null + +}; + +Phaser.Events.prototype.constructor = Phaser.Events; + +// Create an auto-create proxy getter and dispatch method for all events. +// The backing property is the same as the event name, prefixed with '_' +// and the dispatch method is the same as the event name postfixed with '$dispatch'. +for (var prop in Phaser.Events.prototype) +{ + if (!Phaser.Events.prototype.hasOwnProperty(prop) || + prop.indexOf('on') !== 0 || + Phaser.Events.prototype[prop] !== null) + { + continue; + } + + (function (prop, backing) { + 'use strict'; + + // The accessor creates a new Signal; and so it should only be used from user-code. + Object.defineProperty(Phaser.Events.prototype, prop, { + get: function () { + return this[backing] || (this[backing] = new Phaser.Signal()); + } + }); + + // The dispatcher will only broadcast on an already-created signal; call this internally. + Phaser.Events.prototype[prop + '$dispatch'] = function () { + return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; + }; + + })(prop, '_' + prop); + +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless +* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. +* +* @class +*/ +Phaser.Component.FixedToCamera = function () {}; + +/** + * The FixedToCamera component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.FixedToCamera.postUpdate = function () { + + if (this.fixedToCamera) + { + 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.Component.FixedToCamera.prototype = { + + /** + * @property {boolean} _fixedToCamera + * @private + */ + _fixedToCamera: false, + + /** + * A Game Object that is "fixed" to the camera is rendered at a given x/y offsets from the top left of the camera. The offsets + * are stored in the `cameraOffset` property, which is initialized with the current object coordinates. + * + * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. + * + * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world + * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times + * regardless where in the world the camera is. + * + * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. + * + * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. + * + * @property {boolean} fixedToCamera + */ + fixedToCamera: { + + get: function () { + + return this._fixedToCamera; + + }, + + set: function (value) { + + if (value) + { + this._fixedToCamera = true; + this.cameraOffset.set(this.x, this.y); + } + else + { + this._fixedToCamera = false; + } + + } + + }, + + /** + * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. + * + * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. + * @property {Phaser.Point} cameraOffset + */ + cameraOffset: new Phaser.Point() + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Health component provides the ability for Game Objects to have a `health` property +* that can be damaged and reset through game code. +* Requires the LifeSpan component. +* +* @class +*/ +Phaser.Component.Health = function () {}; + +Phaser.Component.Health.prototype = { + + /** + * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. + * + * It can be used in combination with the `damage` method or modified directly. + * + * @property {number} health + * @default + */ + health: 1, + + /** + * The Game Objects maximum health value. This works in combination with the `heal` method to ensure + * the health value never exceeds the maximum. + * + * @property {number} maxHealth + * @default + */ + maxHealth: 100, + + /** + * Damages the Game Object. This removes the given amount of health from the `health` property. + * + * If health is taken below or is equal to zero then the `kill` method is called. + * + * @method + * @param {number} amount - The amount to subtract from the current `health` value. + * @return {Phaser.Sprite} This instance. + */ + damage: function (amount) { + + if (this.alive) + { + this.health -= amount; + + if (this.health <= 0) + { + this.kill(); + } + } + + return this; + + }, + + /** + * Sets the health property of the Game Object to the given amount. + * Will never exceed the `maxHealth` value. + * + * @method + * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + setHealth: function (amount) { + + this.health = amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + + return this; + + }, + + /** + * Heal the Game Object. This adds the given amount of health to the `health` property. + * + * @method + * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + heal: function (amount) { + + if (this.alive) + { + this.health += amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InCamera component checks if the Game Object intersects with the Game Camera. +* +* @class +*/ +Phaser.Component.InCamera = function () {}; + +Phaser.Component.InCamera.prototype = { + + /** + * Checks if this Game Objects bounds intersects with the Game Cameras bounds. + * + * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. + * + * An object outside the bounds can be considered for camera culling if it has the AutoCull component. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. +* +* @class +*/ +Phaser.Component.InputEnabled = function () {}; + +Phaser.Component.InputEnabled.prototype = { + + /** + * The Input Handler for this Game Object. + * + * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. + * + * After you have done this, this property will be a reference to the Phaser InputHandler. + * @property {Phaser.InputHandler|null} input + */ + input: null, + + /** + * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created + * for this Game Object and it will then start to process click / touch events and more. + * + * You can then access the Input Handler via `this.input`. + * + * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. + * + * If you set this property to false it will stop the Input Handler from processing any more input events. + * + * If you want to _temporarily_ disable input for a Game Object, then it's better to set + * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. + * You can then toggle this back on as needed. + * + * @property {boolean} inputEnabled + */ + inputEnabled: { + + get: function () { + + return (this.input && this.input.enabled); + + }, + + set: function (value) { + + if (value) + { + if (this.input === null) + { + this.input = new Phaser.InputHandler(this); + this.input.start(); + } + else if (this.input && !this.input.enabled) + { + this.input.start(); + } + } + else + { + if (this.input && this.input.enabled) + { + this.input.stop(); + } + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InWorld component checks if a Game Object is within the Game World Bounds. +* An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. +* If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. +* +* @class +*/ +Phaser.Component.InWorld = function () {}; + +/** + * The InWorld component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.InWorld.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + // Cache the bounds if we need it + if (this.autoCull || this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + + if (this.autoCull) + { + // Won't get rendered but will still get its transform updated + if (this.game.world.camera.view.intersects(this._bounds)) + { + this.renderable = true; + this.game.world.camera.totalInView++; + } + else + { + this.renderable = false; + + if (this.outOfCameraBoundsKill) + { + this.kill(); + return false; + } + } + } + + if (this.checkWorldBounds) + { + // The Sprite is already out of the world bounds, so let's check to see if it has come back again + if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds)) + { + this._outOfBoundsFired = false; + this.events.onEnterBounds$dispatch(this); + } + else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds)) + { + // The Sprite WAS in the screen, but has now left. + this._outOfBoundsFired = true; + this.events.onOutOfBounds$dispatch(this); + + if (this.outOfBoundsKill) + { + this.kill(); + return false; + } + } + } + } + + return true; + +}; + +Phaser.Component.InWorld.prototype = { + + /** + * If this is set to `true` the Game Object checks if it is within the World bounds each frame. + * + * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. + * + * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. + * + * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. + * + * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} checkWorldBounds + * @default + */ + checkWorldBounds: false, + + /** + * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. + * + * @property {boolean} outOfBoundsKill + * @default + */ + outOfBoundsKill: false, + + /** + * If this and the `autoCull` property are both set to `true`, then the `kill` method + * is called as soon as the Game Object leaves the camera bounds. + * + * @property {boolean} outOfCameraBoundsKill + * @default + */ + outOfCameraBoundsKill: false, + + /** + * @property {boolean} _outOfBoundsFired - Internal state var. + * @private + */ + _outOfBoundsFired: false, + + /** + * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. + * + * @property {boolean} inWorld + * @readonly + */ + inWorld: { + + get: function () { + + return this.game.world.bounds.intersects(this.getBounds()); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* LifeSpan Component Features. +* +* @class +*/ +Phaser.Component.LifeSpan = function () {}; + +/** + * The LifeSpan component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.LifeSpan.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.lifespan > 0) + { + this.lifespan -= this.game.time.physicsElapsedMS; + + if (this.lifespan <= 0) + { + this.kill(); + return false; + } + } + + return true; + +}; + +Phaser.Component.LifeSpan.prototype = { + + /** + * A useful flag to control if the Game Object is alive or dead. + * + * This is set automatically by the Health components `damage` method should the object run out of health. + * Or you can toggle it via your game code. + * + * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. + * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. + * @property {boolean} alive + * @default + */ + alive: true, + + /** + * The lifespan allows you to give a Game Object a lifespan in milliseconds. + * + * Once the Game Object is 'born' you can set this to a positive value. + * + * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. + * When it reaches zero it will call the `kill` method. + * + * Very handy for particles, bullets, collectibles, or any other short-lived entity. + * + * @property {number} lifespan + * @default + */ + lifespan: 0, + + /** + * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. + * + * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. + * + * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. + * + * @method + * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. + * @return {PIXI.DisplayObject} This instance. + */ + revive: function (health) { + + if (health === undefined) { health = 100; } + + this.alive = true; + this.exists = true; + this.visible = true; + + if (typeof this.setHealth === 'function') + { + this.setHealth(health); + } + + if (this.events) + { + this.events.onRevived$dispatch(this); + } + + return this; + + }, + + /** + * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. + * + * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. + * + * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, + * it doesn't destroy the object or free it up from memory. + * + * If you don't need this Game Object any more you should call `destroy` instead. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ + kill: function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + if (this.events) + { + this.events.onKilled$dispatch(this); + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. +* +* @class +*/ +Phaser.Component.LoadTexture = function () {}; + +Phaser.Component.LoadTexture.prototype = { + + /** + * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) + * @private + */ + customRender: false, + + /** + * @property {Phaser.Rectangle} _frame - Internal cache var. + * @private + */ + _frame: null, + + /** + * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. + * + * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. + * + * You should only use `loadTexture` if you want to replace the base texture entirely. + * + * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. + * + * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. + * Doing this then sets the key to be the `frame` argument (the frame is set to zero). + * + * This allows you to create sprites using `load.image` during development, and then change them + * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' + * and swapping it to be the key of the atlas data. + * + * Note: You cannot use a RenderTexture as a texture for a TileSprite. + * + * @method + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. + */ + loadTexture: function (key, frame, stopAnimation) { + + if (key === Phaser.PENDING_ATLAS) + { + key = frame; + frame = 0; + } + else + { + frame = frame || 0; + } + + if ((stopAnimation || stopAnimation === undefined) && this.animations) + { + this.animations.stop(); + } + + this.key = key; + this.customRender = false; + var cache = this.game.cache; + + var setFrame = true; + var smoothed = !this.texture.baseTexture.scaleMode; + + if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture) + { + this.key = key.key; + this.setTexture(key); + } + else if (Phaser.BitmapData && key instanceof Phaser.BitmapData) + { + this.customRender = true; + + this.setTexture(key.texture); + + if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA)) + { + setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame); + } + else + { + setFrame = !this.animations.loadFrameData(key.frameData, 0); + } + } + else if (Phaser.Video && key instanceof Phaser.Video) + { + this.customRender = true; + + // This works from a reference, which probably isn't what we need here + var valid = key.texture.valid; + this.setTexture(key.texture); + this.setFrame(key.texture.frame.clone()); + key.onChangeSource.add(this.resizeFrame, this); + this.texture.valid = valid; + } + else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer) + { + // this.customRender = true; + + this.setTexture(PIXI.Texture.fromCanvas(key.canvas)); + } + else if (key instanceof PIXI.Texture) + { + this.setTexture(key); + } + else + { + var img = cache.getImage(key, true); + + this.key = img.key; + this.setTexture(new PIXI.Texture(img.base)); + + if (key === '__default') + { + this.texture.baseTexture.skipRender = true; + } + else + { + this.texture.baseTexture.skipRender = false; + } + + setFrame = !this.animations.loadFrameData(img.frameData, frame); + } + + if (setFrame) + { + this._frame = Phaser.Rectangle.clone(this.texture.frame); + } + + if (!smoothed) + { + this.texture.baseTexture.scaleMode = 1; + } + + }, + + /** + * Sets the texture frame the Game Object uses for rendering. + * + * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. + * + * @method + * @param {Phaser.Frame} frame - The Frame to be used by the texture. + */ + setFrame: function (frame) { + + this._frame = frame; + + this.texture.frame.x = frame.x; + this.texture.frame.y = frame.y; + this.texture.frame.width = frame.width; + this.texture.frame.height = frame.height; + + this.texture.crop.x = frame.x; + this.texture.crop.y = frame.y; + this.texture.crop.width = frame.width; + this.texture.crop.height = frame.height; + + if (frame.trimmed) + { + if (this.texture.trim) + { + this.texture.trim.x = frame.spriteSourceSizeX; + this.texture.trim.y = frame.spriteSourceSizeY; + this.texture.trim.width = frame.sourceSizeW; + this.texture.trim.height = frame.sourceSizeH; + } + else + { + this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH }; + } + + this.texture.width = frame.sourceSizeW; + this.texture.height = frame.sourceSizeH; + this.texture.frame.width = frame.sourceSizeW; + this.texture.frame.height = frame.sourceSizeH; + } + else if (!frame.trimmed && this.texture.trim) + { + this.texture.trim = null; + } + + if (frame.rotated) + { + this.texture.rotated = true; + } + + if (this.cropRect) + { + this.updateCrop(); + } + + this.texture.requiresReTint = true; + + this.texture._updateUvs(); + + if (this.tilingTexture) + { + this.refreshTexture = true; + } + + }, + + /** + * Resizes the Frame dimensions that the Game Object uses for rendering. + * + * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData + * it can be useful to adjust the dimensions directly in this way. + * + * @method + * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. + * @param {integer} width - The new width of the texture. + * @param {integer} height - The new height of the texture. + */ + resizeFrame: function (parent, width, height) { + + this.texture.frame.resize(width, height); + this.texture.setFrame(this.texture.frame); + + }, + + /** + * Resets the texture frame dimensions that the Game Object uses for rendering. + * + * @method + */ + resetFrame: function () { + + if (this._frame) + { + this.setFrame(this._frame); + } + + }, + + /** + * Gets or sets the current frame index of the texture being used to render this Game Object. + * + * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, + * for example: `player.frame = 4`. + * + * If the frame index given doesn't exist it will revert to the first frame found in the texture. + * + * If you are using a texture atlas then you should use the `frameName` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {integer} frame + */ + frame: { + + get: function () { + return this.animations.frame; + }, + + set: function (value) { + this.animations.frame = value; + } + + }, + + /** + * Gets or sets the current frame name of the texture being used to render this Game Object. + * + * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, + * for example: `player.frameName = "idle"`. + * + * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. + * + * If you are using a sprite sheet then you should use the `frame` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {string} frameName + */ + frameName: { + + get: function () { + return this.animations.frameName; + }, + + set: function (value) { + this.animations.frameName = value; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. +* +* @class +*/ +Phaser.Component.Overlap = function () {}; + +Phaser.Component.Overlap.prototype = { + + /** + * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, + * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. + * + * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. + * + * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. + * It should be fine for low-volume testing where physics isn't required. + * + * @method + * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. + * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. + */ + overlap: function (displayObject) { + + return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds()); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The PhysicsBody component manages the Game Objects physics body and physics enabling. +* It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. +* +* @class +*/ +Phaser.Component.PhysicsBody = function () {}; + +/** + * The PhysicsBody component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.fresh && 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.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (this.body) + { + this.body.preUpdate(); + } + + this.fresh = false; + + this.preUpdateChildren(); + + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this._exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + return true; + +}; + +/** + * The PhysicsBody component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.postUpdate = function () { + + if (this.exists && this.body) + { + this.body.postUpdate(); + } + +}; + +Phaser.Component.PhysicsBody.prototype = { + + /** + * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated + * properties and methods via it. + * + * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. + * + * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object + * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. + * + * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. + * + * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, + * so the physics body is centered on the Game Object. + * + * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. + * + * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body + * @default + */ + body: null, + + /** + * The position of the Game Object on the x axis relative to the local coordinates of the parent. + * + * @property {number} x + */ + x: { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + }, + + /** + * The position of the Game Object on the y axis relative to the local coordinates of the parent. + * + * @property {number} y + */ + y: { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Reset component allows a Game Object to be reset and repositioned to a new location. +* +* @class +*/ +Phaser.Component.Reset = function () {}; + +/** +* Resets the Game Object. +* +* This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, +* `visible` and `renderable` to true. +* +* If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. +* +* If this Game Object has a Physics Body it will reset the Body. +* +* @method +* @param {number} x - The x coordinate (in world space) to position the Game Object at. +* @param {number} y - The y coordinate (in world space) to position the Game Object at. +* @param {number} [health=1] - The health to give the Game Object if it has the Health component. +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.Reset.prototype.reset = function (x, y, health) { + + if (health === undefined) { health = 1; } + + this.world.set(x, y); + this.position.set(x, y); + + this.fresh = true; + this.exists = true; + this.visible = true; + this.renderable = true; + + if (this.components.InWorld) + { + this._outOfBoundsFired = false; + } + + if (this.components.LifeSpan) + { + this.alive = true; + this.health = health; + } + + if (this.components.PhysicsBody) + { + if (this.body) + { + this.body.reset(x, y, false, false); + } + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. +* +* @class +*/ +Phaser.Component.ScaleMinMax = function () {}; + +Phaser.Component.ScaleMinMax.prototype = { + + /** + * The callback that will apply any scale limiting to the worldTransform. + * @property {function} transformCallback + */ + transformCallback: null, + + /** + * The context under which `transformCallback` is called. + * @property {object} transformCallbackContext + */ + transformCallbackContext: this, + + /** + * The minimum scale this Game Object will scale down to. + * + * It allows you to prevent a parent from scaling this Game Object lower than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMin + */ + scaleMin: null, + + /** + * The maximum scale this Game Object will scale up to. + * + * It allows you to prevent a parent from scaling this Game Object higher than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMax + */ + scaleMax: null, + + /** + * Adjust scaling limits, if set, to this Game Object. + * + * @method + * @private + * @param {Phaser.Matrix} wt - The updated worldTransform matrix. + */ + checkTransform: function (wt) { + + if (this.scaleMin) + { + if (wt.a < this.scaleMin.x) + { + wt.a = this.scaleMin.x; + } + + if (wt.d < this.scaleMin.y) + { + wt.d = this.scaleMin.y; + } + } + + if (this.scaleMax) + { + if (wt.a > this.scaleMax.x) + { + wt.a = this.scaleMax.x; + } + + if (wt.d > this.scaleMax.y) + { + wt.d = this.scaleMax.y; + } + } + + }, + + /** + * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. + * + * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored + * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. + * + * By setting these values you can carefully control how Game Objects deal with responsive scaling. + * + * If only one parameter is given then that value will be used for both scaleMin and scaleMax: + * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 + * + * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: + * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 + * + * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, + * or pass `null` for the `maxX` and `maxY` parameters. + * + * Call `setScaleMinMax(null)` to clear all previously set values. + * + * @method + * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to. + * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to. + * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to. + * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to. + */ + setScaleMinMax: function (minX, minY, maxX, maxY) { + + if (minY === undefined) + { + // 1 parameter, set all to it + minY = maxX = maxY = minX; + } + else if (maxX === undefined) + { + // 2 parameters, the first is min, the second max + maxX = maxY = minY; + minY = minX; + } + + if (minX === null) + { + this.scaleMin = null; + } + else + { + if (this.scaleMin) + { + this.scaleMin.set(minX, minY); + } + else + { + this.scaleMin = new Phaser.Point(minX, minY); + } + } + + if (maxX === null) + { + this.scaleMax = null; + } + else + { + if (this.scaleMax) + { + this.scaleMax.set(maxX, maxY); + } + else + { + this.scaleMax = new Phaser.Point(maxX, maxY); + } + } + + if (this.scaleMin === null) + { + this.transformCallback = null; + } + else + { + this.transformCallback = this.checkTransform; + this.transformCallbackContext = this; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. +* +* @class +*/ +Phaser.Component.Smoothed = function () {}; + +Phaser.Component.Smoothed.prototype = { + + /** + * Enable or disable texture smoothing for this Game Object. + * + * It only takes effect if the Game Object is using an image based texture. + * + * Smoothing is enabled by default. + * + * @property {boolean} smoothed + */ + smoothed: { + + get: function () { + + return !this.texture.baseTexture.scaleMode; + + }, + + set: function (value) { + + if (value) + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 0; + this.texture.baseTexture.dirty(); + } + } + else + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 1; + this.texture.baseTexture.dirty(); + } + } + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectFactory is a quick way to create many common game objects +* using {@linkcode Phaser.Game#add `game.add`}. +* +* Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group. +* +* @class Phaser.GameObjectFactory +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectFactory = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectFactory.prototype = { + + /** + * Adds an existing display object to the game world. + * + * @method Phaser.GameObjectFactory#existing + * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object. + * @return {any} The child that was added to the World. + */ + existing: function (object) { + + return this.world.add(object); + + }, + + /** + * Weapons provide the ability to easily create a bullet pool and manager. + * + * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. + * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. + * + * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you + * can usually do with a Group, such as move it around the display list, iterate it, etc can be done + * to the bullets Group too. + * + * Bullets can have textures and even animations. You can control the speed at which they are fired, + * the firing rate, the firing angle, and even set things like gravity for them. + * + * @method Phaser.GameObjectFactory#weapon + * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group. + * @param {function} [bulletClass] - The Class of the bullets that are launched by this Weapon. See {@link Phaser.Weapon#bulletClass} + * @returns {Phaser.Weapon} A Weapon instance. + */ + weapon: function (quantity, key, frame, group, bulletClass) { + + var weapon = this.game.plugins.add(Phaser.Weapon); + + if (bulletClass) + { + weapon.bulletClass = bulletClass; + } + + weapon.createBullets(quantity, key, frame, group); + + return weapon; + + }, + + /** + * Create a new `Image` object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * + * It can still rotate, scale, crop and receive input events. + * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectFactory#image + * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Image} The newly created Image object. + */ + image: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Image(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. + * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), + * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. + * + * @method Phaser.GameObjectFactory#sprite + * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Sprite} The newly created Sprite object. + */ + sprite: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Sprite(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Creature Animation object. + * + * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. + * + * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). + * + * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. + * + * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them + * loaded before your Phaser game boots. + * + * See the Phaser custom build process for more details. + * + * @method Phaser.GameObjectFactory#creature + * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Creature} The newly created Creature object. + */ + creature: function (x, y, key, mesh, group) { + + if (group === undefined) { group = this.world; } + + var obj = new Phaser.Creature(this.game, x, y, key, mesh); + + group.add(obj); + + return obj; + + }, + + /** + * Create a tween on a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectFactory#tween + * @param {object} object - Object the tween will be run on. + * @return {Phaser.Tween} The newly created Phaser.Tween object. + */ + tween: function (object) { + + return this.game.tweens.create(object); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectFactory#group + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates + * are automatically given a physics body. + * + * @method Phaser.GameObjectFactory#physicsGroup + * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc. + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.Group} The newly created Group. + */ + physicsGroup: function (physicsBodyType, parent, name, addToStage) { + + return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType); + + }, + + /** + * A SpriteBatch is a really fast version of a Phaser Group built solely for speed. + * Use when you need a lot of sprites or particles all sharing the same texture. + * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. + * + * @method Phaser.GameObjectFactory#spriteBatch + * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. + * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. + * @return {Phaser.SpriteBatch} The newly created Sprite Batch. + */ + spriteBatch: function (parent, name, addToStage) { + + if (parent === undefined) { parent = null; } + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectFactory#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectFactory#tileSprite + * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TileSprite} The newly created TileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); + + }, + + /** + * Creates a new Rope object. + * + * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js + * + * @method Phaser.GameObjectFactory#rope + * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Array} points - An array of {Phaser.Point}. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Rope} The newly created Rope object. + */ + rope: function (x, y, key, frame, points, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Rope(this.game, x, y, key, frame, points)); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectFactory#text + * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {string} [text=''] - The text string that will be displayed. + * @param {object} [style] - The style object containing style attributes like font, font size , etc. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Text(this.game, x, y, text, style)); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectFactory#button + * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] - The function to call when this button is pressed + * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Button} The newly created Button object. + */ + button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectFactory#graphics + * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Graphics(this.game, x, y)); + + }, + + /** + * Create a new Emitter. + * + * A particle emitter can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accordingly. + * + * @method Phaser.GameObjectFactory#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles)); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectFactory#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectFactory#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size)); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectFactory#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {Phaser.Tilemap} The newly created tilemap object. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectFactory#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a Video object. + * + * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. + * + * @method Phaser.GameObjectFactory#video + * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. + * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) + * @return {Phaser.Video} The newly created Video object. + */ + video: function (key, url) { + + return new Phaser.Video(this.game, key, url); + + }, + + /** + * Create a BitmapData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectFactory#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectFactory#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + }, + + /** + * Add a new Plugin into the PluginManager. + * + * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.GameObjectFactory#plugin + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + plugin: function (plugin) { + + return this.game.plugins.add(plugin); + + } + +}; + +Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world. +* The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}. +* +* @class Phaser.GameObjectCreator +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectCreator = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectCreator.prototype = { + + /** + * Create a new Image object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectCreator#image + * @param {number} x - X position of the image. + * @param {number} y - Y position of the image. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Image} the newly created sprite object. + */ + image: function (x, y, key, frame) { + + return new Phaser.Image(this.game, x, y, key, frame); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * @method Phaser.GameObjectCreator#sprite + * @param {number} x - X position of the new sprite. + * @param {number} y - Y position of the new sprite. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Sprite} the newly created sprite object. + */ + sprite: function (x, y, key, frame) { + + return new Phaser.Sprite(this.game, x, y, key, frame); + + }, + + /** + * Create a tween object for a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectCreator#tween + * @param {object} obj - Object the tween will be run on. + * @return {Phaser.Tween} The Tween object. + */ + tween: function (obj) { + + return new Phaser.Tween(obj, this.game, this.game.tweens); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectCreator#group + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * Create a new SpriteBatch. + * + * @method Phaser.GameObjectCreator#spriteBatch + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.SpriteBatch} The newly created group. + */ + spriteBatch: function (parent, name, addToStage) { + + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectCreator#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectCreator#tileSprite + * @param {number} x - The x coordinate (in world space) to position the TileSprite at. + * @param {number} y - The y coordinate (in world space) to position the TileSprite at. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.TileSprite} The newly created tileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame) { + + return new Phaser.TileSprite(this.game, x, y, width, height, key, frame); + + }, + + /** + * Creates a new Rope object. + * + * @method Phaser.GameObjectCreator#rope + * @param {number} x - The x coordinate (in world space) to position the Rope at. + * @param {number} y - The y coordinate (in world space) to position the Rope at. + * @param {number} width - The width of the Rope. + * @param {number} height - The height of the Rope. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.Rope} The newly created rope object. + */ + rope: function (x, y, key, frame, points) { + + return new Phaser.Rope(this.game, x, y, key, frame, points); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectCreator#text + * @param {number} x - X position of the new text object. + * @param {number} y - Y position of the new text object. + * @param {string} text - The actual text that will be written. + * @param {object} style - The style object containing style attributes like font, font size , etc. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style) { + + return new Phaser.Text(this.game, x, y, text, style); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectCreator#button + * @param {number} [x] X position of the new button object. + * @param {number} [y] Y position of the new button object. + * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] The function to call when this button is pressed + * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @return {Phaser.Button} The newly created button object. + */ + 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); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectCreator#graphics + * @param {number} [x=0] - X position of the new graphics object. + * @param {number} [y=0] - Y position of the new graphics object. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y) { + + return new Phaser.Graphics(this.game, x, y); + + }, + + /** + * Creat a new Emitter. + * + * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accorindgly. + * + * @method Phaser.GameObjectCreator#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectCreator#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectCreator#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, align) { + + return new Phaser.BitmapText(this.game, x, y, font, text, size, align); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectCreator#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectCreator#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a BitmpaData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectCreator#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectCreator#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + } + +}; + +Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Sprites are the lifeblood of your game, used for nearly everything visual. +* +* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. +* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), +* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. +* +* @class Phaser.Sprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. If this argument is omitted, the sprite will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Sprite = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.SPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Sprite.prototype.constructor = Phaser.Sprite; + +Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.Sprite +* @return {boolean} True if the Sprite was rendered, otherwise false. +*/ +Phaser.Sprite.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image is a light-weight object you can use to display anything that doesn't need health, physics, or complex position monitoring. +* +* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. +* +* @class Phaser.Image +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. If this argument is omitted, the image will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Image = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.IMAGE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Image.prototype.constructor = Phaser.Image; + +Phaser.Component.Core.install.call(Phaser.Image.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Image.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Image#preUpdate +* @memberof Phaser.Image +*/ +Phaser.Image.prototype.preUpdate = function() { + + if (!this.preUpdateInWorld() || !this.preUpdateLifeSpan()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. +* +* The four states a Button responds to are: +* +* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. +* * 'Out' - when the Pointer that was previously over the Button moves out of it. +* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. +* * 'Up' - when the Pointer that was pressed down on the Button is released again. +* +* A different texture/frame and activation sound can be specified for any of the states. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. +* +* @class Phaser.Button +* @constructor +* @extends Phaser.Image +* @param {Phaser.Game} game Current game instance. +* @param {number} [x=0] - X position of the Button. +* @param {number} [y=0] - Y position of the Button. +* @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button. +* @param {function} [callback] - The function to call when this Button is pressed, receiving `this` (the Button), `pointer`, and `isOver` (see {@link Phaser.Events#onInputUp}.) +* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) { + + x = x || 0; + y = y || 0; + key = key || null; + callback = callback || null; + callbackContext = callbackContext || this; + + Phaser.Image.call(this, game, x, y, key, outFrame); + + /** + * The Phaser Object Type. + * @property {number} type + * @readonly + */ + this.type = Phaser.BUTTON; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * The name or ID of the Over state frame. + * @property {string|integer} onOverFrame + * @private + */ + this._onOverFrame = null; + + /** + * The name or ID of the Out state frame. + * @property {string|integer} onOutFrame + * @private + */ + this._onOutFrame = null; + + /** + * The name or ID of the Down state frame. + * @property {string|integer} onDownFrame + * @private + */ + this._onDownFrame = null; + + /** + * The name or ID of the Up state frame. + * @property {string|integer} onUpFrame + * @private + */ + this._onUpFrame = null; + + /** + * The Sound to be played when this Buttons Over state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound + * @readonly + */ + this.onOverSound = null; + + /** + * The Sound to be played when this Buttons Out state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound + * @readonly + */ + this.onOutSound = null; + + /** + * The Sound to be played when this Buttons Down state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound + * @readonly + */ + this.onDownSound = null; + + /** + * The Sound to be played when this Buttons Up state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound + * @readonly + */ + this.onUpSound = null; + + /** + * The Sound Marker used in conjunction with the onOverSound. + * @property {string} onOverSoundMarker + * @readonly + */ + this.onOverSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onOutSound. + * @property {string} onOutSoundMarker + * @readonly + */ + this.onOutSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onDownSound. + * @property {string} onDownSoundMarker + * @readonly + */ + this.onDownSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onUpSound. + * @property {string} onUpSoundMarker + * @readonly + */ + this.onUpSoundMarker = ''; + + /** + * The Signal (or event) dispatched when this Button is in an Over state. + * @property {Phaser.Signal} onInputOver + */ + this.onInputOver = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Out state. + * @property {Phaser.Signal} onInputOut + */ + this.onInputOut = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Down state. + * @property {Phaser.Signal} onInputDown + */ + this.onInputDown = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Up state. + * @property {Phaser.Signal} onInputUp + */ + this.onInputUp = new Phaser.Signal(); + + /** + * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. + * The frame will still be changed as applicable. + * + * @property {boolean} onOverMouseOnly + * @default + */ + this.onOverMouseOnly = true; + + /** + * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}. + * + * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. + * + * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR + */ + this.justReleasedPreventsOver = Phaser.PointerMode.CONTACT; + + /** + * When true the the texture frame will not be automatically switched on up/down/over/out events. + * @property {boolean} freezeFrames + * @default + */ + this.freezeFrames = false; + + /** + * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". + * + * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control. + * + * @property {boolean|Phaser.PointerMode} forceOut=false + * @default + */ + this.forceOut = false; + + this.inputEnabled = true; + + this.input.start(0, true); + + this.input.useHandCursor = true; + + this.setFrames(overFrame, outFrame, downFrame, upFrame); + + if (callback !== null) + { + this.onInputUp.add(callback, callbackContext); + } + + // Redirect the input events to here so we can handle animation updates, etc + this.events.onInputOver.add(this.onInputOverHandler, this); + this.events.onInputOut.add(this.onInputOutHandler, this); + this.events.onInputDown.add(this.onInputDownHandler, this); + this.events.onInputUp.add(this.onInputUpHandler, this); + +}; + +Phaser.Button.prototype = Object.create(Phaser.Image.prototype); +Phaser.Button.prototype.constructor = Phaser.Button; + +// State constants; local only. These are tied to property names in Phaser.Button. +var STATE_OVER = 'Over'; +var STATE_OUT = 'Out'; +var STATE_DOWN = 'Down'; +var STATE_UP = 'Up'; + +/** +* Clears all of the frames set on this Button. +* +* @method Phaser.Button#clearFrames +*/ +Phaser.Button.prototype.clearFrames = function () { + + this.setFrames(null, null, null, null); + +}; + +/** +* Set the frame name/ID for the given state. +* +* @method Phaser.Button#setStateFrame +* @private +* @param {object} state - See `STATE_*` +* @param {number|string} frame - The number or string representing the frame. +* @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true. +*/ +Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately) +{ + var frameKey = '_on' + state + 'Frame'; + + if (frame !== null) // not null or undefined + { + this[frameKey] = frame; + + if (switchImmediately) + { + this.changeStateFrame(state); + } + } + else + { + this[frameKey] = null; + } + +}; + +/** +* Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen". +* +* @method Phaser.Button#changeStateFrame +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if the frame was assigned a value, possibly the same one it already had. +*/ +Phaser.Button.prototype.changeStateFrame = function (state) { + + if (this.freezeFrames) + { + return false; + } + + var frameKey = '_on' + state + 'Frame'; + var frame = this[frameKey]; + + if (typeof frame === 'string') + { + this.frameName = frame; + return true; + } + else if (typeof frame === 'number') + { + this.frame = frame; + return true; + } + else + { + return false; + } + +}; + +/** +* Used to manually set the frames that will be used for the different states of the Button. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. +* +* @method Phaser.Button#setFrames +* @public +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) { + + this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver()); + this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver()); + this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown()); + this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp()); + +}; + +/** +* Set the sound/marker for the given state. +* +* @method Phaser.Button#setStateSound +* @private +* @param {object} state - See `STATE_*` +* @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound. +* @param {string} [marker=''] - Sound marker. +*/ +Phaser.Button.prototype.setStateSound = function (state, sound, marker) { + + var soundKey = 'on' + state + 'Sound'; + var markerKey = 'on' + state + 'SoundMarker'; + + if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite) + { + this[soundKey] = sound; + this[markerKey] = typeof marker === 'string' ? marker : ''; + } + else + { + this[soundKey] = null; + this[markerKey] = ''; + } + +}; + +/** +* Play the sound for the given state, _if_ the state has a sound assigned. +* +* @method Phaser.Button#playStateSound +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if a sound was played. +*/ +Phaser.Button.prototype.playStateSound = function (state) { + + var soundKey = 'on' + state + 'Sound'; + var sound = this[soundKey]; + + if (sound) + { + var markerKey = 'on' + state + 'SoundMarker'; + var marker = this[markerKey]; + + sound.play(marker); + return true; + } + else + { + return false; + } + +}; + +/** +* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. +* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. +* +* Call this function with no parameters to reset all sounds on this Button. +* +* @method Phaser.Button#setSounds +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound. +* @param {string} [overMarker] - Over Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound. +* @param {string} [downMarker] - Down Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound. +* @param {string} [outMarker] - Out Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound. +* @param {string} [upMarker] - Up Button Sound Marker. +*/ +Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) { + + this.setStateSound(STATE_OVER, overSound, overMarker); + this.setStateSound(STATE_OUT, outSound, outMarker); + this.setStateSound(STATE_DOWN, downSound, downMarker); + this.setStateSound(STATE_UP, upSound, upMarker); + +}; + +/** +* The Sound to be played when a Pointer moves over this Button. +* +* @method Phaser.Button#setOverSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOverSound = function (sound, marker) { + + this.setStateSound(STATE_OVER, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer moves out of this Button. +* +* @method Phaser.Button#setOutSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOutSound = function (sound, marker) { + + this.setStateSound(STATE_OUT, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer presses down on this Button. +* +* @method Phaser.Button#setDownSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setDownSound = function (sound, marker) { + + this.setStateSound(STATE_DOWN, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer has pressed down and is released from this Button. +* +* @method Phaser.Button#setUpSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setUpSound = function (sound, marker) { + + this.setStateSound(STATE_UP, sound, marker); + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOverHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) { + + if (pointer.justReleased() && + (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode) + { + // If the Pointer was only just released then we don't fire an over event + return; + } + + this.changeStateFrame(STATE_OVER); + + if (this.onOverMouseOnly && !pointer.isMouse) + { + return; + } + + this.playStateSound(STATE_OVER); + + if (this.onInputOver) + { + this.onInputOver.dispatch(this, pointer); + } + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOutHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_OUT); + + this.playStateSound(STATE_OUT); + + if (this.onInputOut) + { + this.onInputOut.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputDownHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_DOWN); + + this.playStateSound(STATE_DOWN); + + if (this.onInputDown) + { + this.onInputDown.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputUpHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) { + + this.playStateSound(STATE_UP); + + // Input dispatched early, before state change (but after sound) + if (this.onInputUp) + { + this.onInputUp.dispatch(this, pointer, isOver); + } + + if (this.freezeFrames) + { + return; + } + + if (this.forceOut === true || (this.forceOut & pointer.pointerMode) === pointer.pointerMode) + { + this.changeStateFrame(STATE_OUT); + } + else + { + var changedUp = this.changeStateFrame(STATE_UP); + if (!changedUp) + { + // No Up frame to show.. + if (isOver) + { + this.changeStateFrame(STATE_OVER); + } + else + { + this.changeStateFrame(STATE_OUT); + } + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. +* It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over +* 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled +* Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. +* +* Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. +* +* @class Phaser.SpriteBatch +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. +* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. +*/ +Phaser.SpriteBatch = function (game, parent, name, addToStage) { + + if (parent === undefined || parent === null) { parent = game.world; } + + Phaser.Group.call(this, game, parent, name, addToStage); + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.SPRITEBATCH; + + /** + * @property {Object} fastSpriteBatch - WebGL Batch Shader. + * @private + */ + this.fastSpriteBatch = null; + + /** + * @property {boolean} ready - Internal flag. + * @private + */ + this.ready = false; + +}; + +Phaser.SpriteBatch.prototype = Object.create(Phaser.Group.prototype); + +Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch; + +/** +* Renders the Sprite Batch using the WebGL renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + if (!this.ready) + { + this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(renderSession.gl); + + this.ready = true; + } + + if (this.fastSpriteBatch.gl !== renderSession.gl) + { + this.fastSpriteBatch.setContext(renderSession.gl); + } + + renderSession.spriteBatch.stop(); + + renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader); + + this.fastSpriteBatch.begin(this, renderSession); + this.fastSpriteBatch.render(this); + + renderSession.spriteBatch.start(); + +}; + +/** +* Renders the Sprite Batch using the Canvas renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + var context = renderSession.context; + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + var transform = this.worldTransform; + + var isRotated = true; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + var texture = child.texture; + var frame = texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) + { + // If rotation === 0 we can avoid setTransform + + if (isRotated) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); + isRotated = false; + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5 + renderSession.shakeX) | 0, + ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5 + renderSession.shakeY) | 0, + frame.width * child.scale.x, + frame.height * child.scale.y); + } + else + { + if (!isRotated) + { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + var tx = (childTransform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (childTransform.ty * renderSession.resolution) + renderSession.shakeY; + + // allow for trimming + + if (renderSession.roundPixels) + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx, ty); + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width) + 0.5) | 0, + ((child.anchor.y) * (-frame.height) + 0.5) | 0, + frame.width, + frame.height); + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. +* A single BitmapData can be used as the texture for one or many Images / Sprites. +* So if you need to dynamically create a Sprite texture then they are a good choice. +* +* Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't +* live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy +* in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. +* +* @class Phaser.BitmapData +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string} key - Internal Phaser reference key for the BitmapData. +* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. +*/ +Phaser.BitmapData = function (game, key, width, height, skipPool) { + + if (width === undefined || width === 0) { width = 256; } + if (height === undefined || height === 0) { height = 256; } + if (skipPool === undefined) { skipPool = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the BitmapData in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} width - The width of the BitmapData in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the BitmapData in pixels. + */ + this.height = height; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. + * @default + */ + this.canvas = Phaser.Canvas.create(this, width, height, null, skipPool); + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + * @default + */ + this.context = this.canvas.getContext('2d', { alpha: true }); + + /** + * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context. + */ + this.ctx = this.context; + + /** + * @property {string} smoothProperty - The context property needed for smoothing this Canvas. + */ + this.smoothProperty = (game.renderType === Phaser.CANVAS) ? game.renderer.renderSession.smoothProperty : Phaser.Canvas.getSmoothingPrefix(this.context); + + /** + * @property {ImageData} imageData - The context image data. + * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. + * This property is updated automatically after the first game loop, according to the dirty flag property. + */ + this.imageData = this.context.getImageData(0, 0, width, height); + + /** + * A Uint8ClampedArray view into BitmapData.buffer. + * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) + * @property {Uint8ClampedArray} data + */ + this.data = null; + + if (this.imageData) + { + this.data = this.imageData.data; + } + + /** + * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer. + */ + this.pixels = null; + + /** + * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData. + */ + if (this.data) + { + 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; + } + } + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + this.baseTexture = new PIXI.BaseTexture(this.canvas, null, this.game.resolution); + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering. + */ + this.frameData = new Phaser.FrameData(); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. + * @default + */ + this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData')); + + this.texture.frame = this.textureFrame; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.BITMAPDATA; + + /** + * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} dirty - If dirty this BitmapData will be re-rendered. + */ + this.dirty = false; + + // Aliases + this.cls = this.clear; + + /** + * @property {number} _image - Internal cache var. + * @private + */ + this._image = null; + + /** + * @property {Phaser.Point} _pos - Internal cache var. + * @private + */ + this._pos = new Phaser.Point(); + + /** + * @property {Phaser.Point} _size - Internal cache var. + * @private + */ + this._size = new Phaser.Point(); + + /** + * @property {Phaser.Point} _scale - Internal cache var. + * @private + */ + this._scale = new Phaser.Point(); + + /** + * @property {number} _rotate - Internal cache var. + * @private + */ + this._rotate = 0; + + /** + * @property {object} _alpha - Internal cache var. + * @private + */ + this._alpha = { prev: 1, current: 1 }; + + /** + * @property {Phaser.Point} _anchor - Internal cache var. + * @private + */ + this._anchor = new Phaser.Point(); + + /** + * @property {number} _tempR - Internal cache var. + * @private + */ + this._tempR = 0; + + /** + * @property {number} _tempG - Internal cache var. + * @private + */ + this._tempG = 0; + + /** + * @property {number} _tempB - Internal cache var. + * @private + */ + this._tempB = 0; + + /** + * @property {Phaser.Circle} _circle - Internal cache var. + * @private + */ + this._circle = new Phaser.Circle(); + + /** + * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods. + * @private + */ + this._swapCanvas = undefined; + +}; + +Phaser.BitmapData.prototype = { + + /** + * Shifts the contents of this BitmapData by the distances given. + * + * The image will wrap-around the edges on all sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#move + * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + move: function (x, y, wrap) { + + if (x !== 0) + { + this.moveH(x, wrap); + } + + if (y !== 0) + { + this.moveV(y, wrap); + } + + return this; + + }, + + /** + * Shifts the contents of this BitmapData horizontally. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveH + * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveH: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var h = this.height; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving to the left + var w = this.width - distance; + + // Left-hand chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h); + } + else + { + // Moving to the right + var w = this.width - distance; + + // Right-hand chunk + if (wrap) + { + ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Shifts the contents of this BitmapData vertically. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveV + * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveV: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var w = this.width; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving up + var h = this.height - distance; + + // Top chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h); + } + else + { + // Moving down + var h = this.height - distance; + + // Bottom chunk + if (wrap) + { + ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Updates the given objects so that they use this BitmapData as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.BitmapData#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. + * The source game object is not modified by this operation. + * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. + * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. + * + * @method Phaser.BitmapData#load + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + load: function (source) { + + if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + } + + if (source) + { + this.resize(source.width, source.height); + this.cls(); + } + else + { + return; + } + + this.draw(source); + + this.update(); + + return this; + + }, + + /** + * Clears the BitmapData context using a clearRect. + * + * @method Phaser.BitmapData#cls + */ + + /** + * Clears the BitmapData context using a clearRect. + * + * You can optionally define the area to clear. + * If the arguments are left empty it will clear the entire canvas. + * + * You may need to call BitmapData.update after this in order to clear out the pixel data, + * but Phaser will not do this automatically for you. + * + * @method Phaser.BitmapData#clear + * @param {number} [x=0] - The x coordinate of the top-left of the area to clear. + * @param {number} [y=0] - The y coordinate of the top-left of the area to clear. + * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width. + * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + clear: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + this.context.clearRect(x, y, width, height); + + this.dirty = true; + + return this; + + }, + + /** + * Fills the BitmapData with the given color. + * + * @method Phaser.BitmapData#fill + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} [a=1] - The alpha color value, between 0 and 1. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + fill: function (r, g, b, a) { + + if (a === undefined) { a = 1; } + + this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; + this.context.fillRect(0, 0, this.width, this.height); + this.dirty = true; + + return this; + + }, + + /** + * Creates a new {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image} element by converting this BitmapDatas canvas into a dataURL. + * + * The image is then stored in the {@link Phaser.Cache image Cache} using the key given. + * + * Finally a {@link PIXI.Texture} is created based on the image and returned. + * + * You can apply the texture to a sprite or any other supporting object by using either the + * key or the texture. First call `generateTexture`: + * + * ```javascript + * var texture = bitmapdata.generateTexture('ball'); + * ``` + * + * Then you can either apply the texture to a sprite: + * + * ```javascript + * game.add.sprite(0, 0, texture); + * ``` + * + * or by using the string based key: + * + * ```javascript + * game.add.sprite(0, 0, 'ball'); + * ``` + * + * Most browsers now load the image data asynchronously, so you should use a callback: + * + * ```javascript + * bitmapdata.generateTexture('ball', function (texture) { + * game.add.sprite(0, 0, texture); + * // or + * game.add.sprite(0, 0, 'ball'); + * }); + * ``` + * + * If this BitmapData is available during preload, you can use {@link Phaser.Loader#imageFromBitmapData} instead. + * + * @method Phaser.BitmapData#generateTexture + * @param {string} key - The key which will be used to store the image in the Cache. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {PIXI.Texture|null} The newly generated texture, or `null` if a callback was passed and the texture isn't available yet. + */ + generateTexture: function (key, callback, callbackContext) { + + var cache = this.game.cache; + var image = new Image(); + + if (callback) + { + image.onload = function () { + var obj = cache.addImage(key, '', image); + var texture = new PIXI.Texture(obj.base); + + callback.call(callbackContext || null, texture); + + image.onload = null; + }; + } + + image.src = this.canvas.toDataURL("image/png"); + + if (!callback) + { + var obj = cache.addImage(key, '', image); + + return new PIXI.Texture(obj.base); + } + + return null; + + }, + + /** + * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. + * + * @method Phaser.BitmapData#resize + * @param {integer} width - The new width of the BitmapData. + * @param {integer} height - The new height of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + resize: function (width, height) { + + if (width !== this.width || height !== this.height) + { + this.width = width; + this.height = height; + + this.canvas.width = width; + this.canvas.height = height; + + if (this._swapCanvas !== undefined) + { + this._swapCanvas.width = width; + this._swapCanvas.height = height; + } + + this.baseTexture.width = width; + this.baseTexture.height = height; + + this.textureFrame.width = width; + this.textureFrame.height = height; + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.update(); + this.dirty = true; + } + + return this; + + }, + + /** + * This re-creates the BitmapData.imageData from the current context. + * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. + * If not given the dimensions defaults to the full size of the context. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.BitmapData#update + * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from. + * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from. + * @param {number} [width=1] - The width of the image data area. + * @param {number} [height=1] - The height of the image data area. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + update: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = Math.max(1, this.width); } + if (height === undefined) { height = Math.max(1, this.height); } + + this.imageData = this.context.getImageData(x, y, width, height); + this.data = this.imageData.data; + + 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; + } + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. + * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. + * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. + * The `color` property is an Int32 of the full color. Note the endianess of this will change per system. + * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. + * The callback will also be sent the pixels x and y coordinates respectively. + * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. + * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. + * + * @method Phaser.BitmapData#processPixelRGB + * @param {function} callback - The callback that will be sent each pixel color object to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixelRGB: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = Phaser.Color.createColor(); + var result = { r: 0, g: 0, b: 0, a: 0 }; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel); + + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== false && result !== null && result !== undefined) + { + this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false); + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. + * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. + * Note that the format of the color received will be different depending on if the system is big or little endian. + * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. + * The callback will also be sent the pixels x and y coordinates respectively. + * + * @method Phaser.BitmapData#processPixel + * @param {function} callback - The callback that will be sent each pixel color to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixel: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = 0; + var result = 0; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + pixel = this.getPixel32(tx, ty); + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== pixel) + { + this.pixels[ty * this.width + tx] = result; + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. + * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. + * + * @method Phaser.BitmapData#replaceRGB + * @param {number} r1 - The red color value to be replaced. Between 0 and 255. + * @param {number} g1 - The green color value to be replaced. Between 0 and 255. + * @param {number} b1 - The blue color value to be replaced. Between 0 and 255. + * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255. + * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255. + * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255. + * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255. + * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255. + * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) { + + var sx = 0; + var sy = 0; + var w = this.width; + var h = this.height; + var source = Phaser.Color.packPixel(r1, g1, b1, a1); + + if (region !== undefined && region instanceof Phaser.Rectangle) + { + sx = region.x; + sy = region.y; + w = region.width; + h = region.height; + } + + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + if (this.getPixel32(sx + x, sy + y) === source) + { + this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false); + } + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * + * @method Phaser.BitmapData#setHSL + * @param {number} [h=null] - The hue, in the range 0 - 1. + * @param {number} [s=null] - The saturation, in the range 0 - 1. + * @param {number} [l=null] - The lightness, in the range 0 - 1. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setHSL: function (h, s, l, region) { + + var bHaveH = h || h === 0; + var bHaveS = s || s === 0; + var bHaveL = l || l === 0; + + if (!bHaveH && !bHaveS && !bHaveL) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (bHaveH) + { + pixel.h = h; + } + + if (bHaveS) + { + pixel.s = s; + } + + if (bHaveL) + { + pixel.l = l; + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * Shifting will add the given value onto the current h, s and l values, not replace them. + * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. + * + * @method Phaser.BitmapData#shiftHSL + * @param {number} [h=null] - The amount to shift the hue by. Within [-1, 1]. + * @param {number} [s=null] - The amount to shift the saturation by. Within [-1, 1]. + * @param {number} [l=null] - The amount to shift the lightness by. Within [-1, 1]. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shiftHSL: function (h, s, l, region) { + + if (h === undefined || h === null) { h = false; } + if (s === undefined || s === null) { s = false; } + if (l === undefined || l === null) { l = false; } + + if (!h && !s && !l) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (h) + { + pixel.h = this.game.math.wrap(pixel.h + h, 0, 1); + } + + if (s) + { + pixel.s = this.game.math.clamp(pixel.s + s, 0, 1); + } + + if (l) + { + pixel.l = this.game.math.clamp(pixel.l + l, 0, 1); + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green, blue and alpha values. + * + * @method Phaser.BitmapData#setPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel32: function (x, y, red, green, blue, alpha, immediate) { + + if (immediate === undefined) { immediate = true; } + + if (x >= 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; + } + } + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green and blue values. + * + * @method Phaser.BitmapData#setPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel: function (x, y, red, green, blue, immediate) { + + return this.setPixel32(x, y, red, green, blue, 255, immediate); + + }, + + /** + * Get the color of a specific pixel in the context into a color object. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + getPixel: function (x, y, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var index = ~~(x + (y * this.width)); + + index *= 4; + + out.r = this.data[index]; + out.g = this.data[++index]; + out.b = this.data[++index]; + out.a = this.data[++index]; + + return out; + + }, + + /** + * Get the color of a specific pixel including its alpha value. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. + * + * @method Phaser.BitmapData#getPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @return {number} A native color value integer (format: 0xAARRGGBB) + */ + getPixel32: function (x, y) { + + if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) + { + return this.pixels[y * this.width + x]; + } + + }, + + /** + * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixelRGB + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + getPixelRGB: function (x, y, out, hsl, hsv) { + + return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv); + + }, + + /** + * Gets all the pixels from the region specified by the given Rectangle object. + * + * @method Phaser.BitmapData#getPixels + * @param {Phaser.Rectangle} rect - The Rectangle region to get. + * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property. + */ + getPixels: function (rect) { + + return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); + + }, + + /** + * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). + * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. + * + * The direction parameter controls from which direction it should start the scan: + * + * 0 = top to bottom + * 1 = bottom to top + * 2 = left to right + * 3 = right to left + * + * @method Phaser.BitmapData#getFirstPixel + * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. + * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. + */ + getFirstPixel: function (direction) { + + if (direction === undefined) { direction = 0; } + + var pixel = Phaser.Color.createColor(); + + var x = 0; + var y = 0; + var v = 1; + var scan = false; + + if (direction === 1) + { + v = -1; + y = this.height; + } + else if (direction === 3) + { + v = -1; + x = this.width; + } + + do { + + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel); + + if (direction === 0 || direction === 1) + { + // Top to Bottom / Bottom to Top + x++; + + if (x === this.width) + { + x = 0; + y += v; + + if (y >= this.height || y <= 0) + { + scan = true; + } + } + } + else if (direction === 2 || direction === 3) + { + // Left to Right / Right to Left + y++; + + if (y === this.height) + { + y = 0; + x += v; + + if (x >= this.width || x <= 0) + { + scan = true; + } + } + } + } + while (pixel.a === 0 && !scan); + + pixel.x = x; + pixel.y = y; + + return pixel; + + }, + + /** + * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. + * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. + * + * @method Phaser.BitmapData#getBounds + * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. + * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. + */ + getBounds: function (rect) { + + if (rect === undefined) { rect = new Phaser.Rectangle(); } + + rect.x = this.getFirstPixel(2).x; + + // If we hit this, there's no point scanning any more, the image is empty + if (rect.x === this.width) + { + return rect.setTo(0, 0, 0, 0); + } + + rect.y = this.getFirstPixel(0).y; + rect.width = (this.getFirstPixel(3).x - rect.x) + 1; + rect.height = (this.getFirstPixel(1).y - rect.y) + 1; + + return rect; + + }, + + /** + * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. + * + * @method Phaser.BitmapData#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself. + * + * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn. + * + * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters. + * + * Note that the source image can also be this BitmapData, which can create some interesting effects. + * + * This method has a lot of parameters for maximum control. + * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all. + * + * You may prefer to use `copyTransform` if you're simply trying to draw a Sprite to this BitmapData, + * and don't wish to translate, scale or rotate it from its original values. + * + * @method Phaser.BitmapData#copy + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image. + * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image. + * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width. + * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height. + * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`. + * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`. + * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter. + * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter. + * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters. + * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) { + + if (source === undefined || source === null) { source = this; } + + if (source instanceof Phaser.RenderTexture) + { + source = source.getCanvas(); + } + + this._image = source; + + if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text || source instanceof PIXI.Sprite) + { + // Copy over sprite values + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + this._scale.set(source.scale.x, source.scale.y); + this._anchor.set(source.anchor.x, source.anchor.y); + this._rotate = source.rotation; + this._alpha.current = source.alpha; + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + if (tx === undefined || tx === null) { tx = source.x; } + if (ty === undefined || ty === null) { ty = source.y; } + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + } + else + { + // Reset + this._pos.set(0); + this._scale.set(1); + this._anchor.set(0); + this._rotate = 0; + this._alpha.current = 1; + + if (source instanceof Phaser.BitmapData) + { + this._image = source.canvas; + } + else if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + + if (source === null) + { + return; + } + else + { + this._image = source; + } + } + + this._size.set(this._image.width, this._image.height); + } + + // The source region to copy from + if (x === undefined || x === null) { x = 0; } + if (y === undefined || y === null) { y = 0; } + + // If they set a width/height then we override the frame values with them + if (width) + { + this._size.x = width; + } + + if (height) + { + this._size.y = height; + } + + // The destination region to copy to + if (tx === undefined || tx === null) { tx = x; } + if (ty === undefined || ty === null) { ty = y; } + if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; } + if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; } + + // Rotation - if set this will override any potential Sprite value + if (typeof rotate === 'number') + { + this._rotate = rotate; + } + + // Anchor - if set this will override any potential Sprite value + if (typeof anchorX === 'number') + { + this._anchor.x = anchorX; + } + + if (typeof anchorY === 'number') + { + this._anchor.y = anchorY; + } + + // Scaling - if set this will override any potential Sprite value + if (typeof scaleX === 'number') + { + this._scale.x = scaleX; + } + + if (typeof scaleY === 'number') + { + this._scale.y = scaleY; + } + + // Effects + if (typeof alpha === 'number') + { + this._alpha.current = alpha; + } + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + // Doesn't work fully with children, or nested scale + rotation transforms (see copyTransform) + ctx.translate(tx, ty); + + ctx.scale(this._scale.x, this._scale.y); + + ctx.rotate(this._rotate); + + ctx.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight); + + // Carry on ... + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the + * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. + * It takes the objects tint and scale mode into consideration before drawing. + * + * You can optionally specify Blend Mode and Round Pixels arguments. + * + * @method Phaser.BitmapData#copyTransform + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyTransform: function (source, blendMode, roundPx) { + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (!source.hasOwnProperty('worldTransform') || !source.worldVisible || source.worldAlpha === 0) + { + return this; + } + + var wt = source.worldTransform; + + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + + if (wt.a === 0 || wt.d === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return this; + } + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + var tx = wt.tx; + var ty = wt.ty; + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + ctx[this.smoothProperty] = (source.texture.baseTexture.scaleMode === PIXI.scaleModes.LINEAR); + + ctx.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + + ctx.drawImage(this._image, + this._pos.x, + this._pos.y, + this._size.x, + this._size.y, + -this._size.x * source.anchor.x, + -this._size.y * source.anchor.y, + this._size.x, + this._size.y); + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. + * + * @method Phaser.BitmapData#copyRect + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. + * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image. + * @param {number} x - The destination x coordinate to copy the image to. + * @param {number} y - The destination y coordinate to copy the image to. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyRect: function (source, area, x, y, alpha, blendMode, roundPx) { + + return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx); + + }, + + /** + * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. + * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. + * + * @method Phaser.BitmapData#draw + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData. + * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`. + * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`. + * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`. + * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + draw: function (source, x, y, width, height, blendMode, roundPx) { + + // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here + return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx); + + }, + + /** + * Draws the immediate children of a Phaser.Group to this BitmapData. + * + * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. + * + * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. + * + * @method Phaser.BitmapData#drawGroup + * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawGroup: function (group, blendMode, roundPx) { + + if (group.total > 0) + { + group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx); + } + + return this; + + }, + + /** + * A proxy for drawGroup that handles child iteration for more complex Game Objects. + * + * @method Phaser.BitmapData#drawGroupProxy + * @private + * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + */ + drawGroupProxy: function (child, blendMode, roundPx) { + + if (child.hasOwnProperty('texture')) + { + this.copyTransform(child, blendMode, roundPx); + } + + if (child.type === Phaser.GROUP && child.exists) + { + this.drawGroup(child, blendMode, roundPx); + } + else + { + if (child.hasOwnProperty('children') && child.children.length > 0) + { + for (var i = 0; i < child.children.length; i++) + { + if (child.children[i].exists) + { + this.copyTransform(child.children[i], blendMode, roundPx); + } + } + } + } + + }, + + /** + * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. + * + * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData + * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the + * bounds of the top-level Game Object. + * + * When drawing it will take into account the child's world rotation, scale and alpha values. + * + * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. + * + * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update + * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can + * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. + * + * @method Phaser.BitmapData#drawFull + * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawFull: function (parent, blendMode, roundPx) { + + if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false)) + { + return this; + } + + if (parent.type !== Phaser.GROUP && parent.type !== Phaser.EMITTER && parent.type !== Phaser.BITMAPTEXT) + { + if (parent.type === Phaser.GRAPHICS) + { + var bounds = parent.getBounds(); + this.ctx.save(); + this.ctx.translate(bounds.x, bounds.y); + PIXI.CanvasGraphics.renderGraphics(parent, this.ctx); + this.ctx.restore(); + } + else + { + this.copy(parent, null, null, null, null, parent.worldPosition.x, parent.worldPosition.y, null, null, parent.worldRotation, null, null, parent.worldScale.x, parent.worldScale.y, parent.worldAlpha, blendMode, roundPx); + } + } + + if (parent.children) + { + for (var i = 0; i < parent.children.length; i++) + { + this.drawFull(parent.children[i], blendMode, roundPx); + } + } + + return this; + + }, + + /** + * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. + * You can cancel an existing shadow by calling this method and passing no parameters. + * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. + * + * @method Phaser.BitmapData#shadow + * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. + * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. + * @param {number} [x=10] - The horizontal offset of the shadow in pixels. + * @param {number} [y=10] - The vertical offset of the shadow in pixels. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shadow: function (color, blur, x, y) { + + var ctx = this.context; + + if (color === undefined || color === null) + { + ctx.shadowColor = 'rgba(0,0,0,0)'; + } + else + { + ctx.shadowColor = color; + ctx.shadowBlur = blur || 5; + ctx.shadowOffsetX = x || 10; + ctx.shadowOffsetY = y || 10; + } + + return this; + + }, + + /** + * Draws the image onto this BitmapData using an image as an alpha mask. + * + * @method Phaser.BitmapData#alphaMask + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. + * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. + * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + alphaMask: function (source, mask, sourceRect, maskRect) { + + if (maskRect === undefined || maskRect === null) + { + this.draw(mask).blendSourceAtop(); + } + else + { + this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop(); + } + + if (sourceRect === undefined || sourceRect === null) + { + this.draw(source).blendReset(); + } + else + { + this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset(); + } + + return this; + + }, + + /** + * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. + * The original BitmapData remains unchanged. + * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. + * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: + * `picture.extract(mask, r, g, b)` + * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. + * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint + * the color during extraction. + * + * @method Phaser.BitmapData#extract + * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. + * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied? + * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255. + * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255. + * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255. + * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on. + */ + extract: function (destination, r, g, b, a, resize, r2, g2, b2) { + + if (a === undefined) { a = 255; } + if (resize === undefined) { resize = false; } + if (r2 === undefined) { r2 = r; } + if (g2 === undefined) { g2 = g; } + if (b2 === undefined) { b2 = b; } + + if (resize) + { + destination.resize(this.width, this.height); + } + + this.processPixelRGB( + function (pixel, x, y) + { + if (pixel.r === r && pixel.g === g && pixel.b === b) + { + destination.setPixel32(x, y, r2, g2, b2, a, false); + } + return false; + }, + this); + + destination.context.putImageData(destination.imageData, 0, 0); + destination.dirty = true; + + return destination; + + }, + + /** + * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. + * + * @method Phaser.BitmapData#rect + * @param {number} x - The x coordinate of the top-left of the Rectangle. + * @param {number} y - The y coordinate of the top-left of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + rect: function (x, y, width, height, fillStyle) { + + if (typeof fillStyle !== 'undefined') + { + this.context.fillStyle = fillStyle; + } + + this.context.fillRect(x, y, width, height); + + return this; + + }, + + /** + * Draws text to the BitmapData in the given font and color. + * The default font is 14px Courier, so useful for quickly drawing debug text. + * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. + * + * @method Phaser.BitmapData#text + * @param {string} text - The text to write to the BitmapData. + * @param {number} x - The x coordinate of the top-left of the text string. + * @param {number} y - The y coordinate of the top-left of the text string. + * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can. + * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in. + * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1) + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + text: function (text, x, y, font, color, shadow) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (font === undefined) { font = '14px Courier'; } + if (color === undefined) { color = 'rgb(255,255,255)'; } + if (shadow === undefined) { shadow = true; } + + var ctx = this.context; + var prevFont = ctx.font; + + ctx.font = font; + + if (shadow) + { + ctx.fillStyle = 'rgb(0,0,0)'; + ctx.fillText(text, x + 1, y + 1); + } + + ctx.fillStyle = color; + ctx.fillText(text, x, y); + + ctx.font = prevFont; + + return this; + + }, + + /** + * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. + * + * @method Phaser.BitmapData#circle + * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle. + * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle. + * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + circle: function (x, y, radius, fillStyle) { + + var ctx = this.context; + + if (fillStyle !== undefined) + { + ctx.fillStyle = fillStyle; + } + + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2, false); + ctx.closePath(); + + ctx.fill(); + + return this; + + }, + + /** + * Draws a line between the coordinates given in the color and thickness specified. + * + * @method Phaser.BitmapData#line + * @param {number} x1 - The x coordinate to start the line from. + * @param {number} y1 - The y coordinate to start the line from. + * @param {number} x2 - The x coordinate to draw the line to. + * @param {number} y2 - The y coordinate to draw the line to. + * @param {string} [color='#fff'] - The stroke color that the line will be drawn in. + * @param {number} [width=1] - The line thickness. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + line: function (x1, y1, x2, y2, color, width) { + + if (color === undefined) { color = '#fff'; } + if (width === undefined) { width = 1; } + + var ctx = this.context; + + ctx.beginPath(); + + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); + + ctx.closePath(); + + return this; + + }, + + /** + * Draws a polygon. + * + * @method Phaser.BitmapData#polygon + * @param {object[]} points - An array of {@link Phaser.Point} or point-like objects. + * @param {CanvasGradient|CanvasPattern|string} [fillStyle] - A color, gradient, or pattern. + * @param {number} [lineWidth=0] - The line thickness. + * @param {CanvasGradient|CanvasPattern|string} [strokeStyle='#fff'] - The line color, gradient, or pattern (when `lineWidth` > 0). + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + polygon: function (points, fillStyle, lineWidth, strokeStyle) { + + // Could reject points.length < 3 + + if (strokeStyle === undefined) { strokeStyle = '#fff'; } + if (lineWidth === undefined) { lineWidth = 0; } + + var ctx = this.context; + + if (fillStyle) + { + ctx.fillStyle = fillStyle; + } + + if (lineWidth) + { + ctx.lineWidth = lineWidth; + ctx.strokeStyle = strokeStyle; + } + + ctx.beginPath(); + + ctx.moveTo(points[0].x, points[0].y); + + for (var i = 1, len = points.length; i < len; i++) + { + var point = points[i]; + ctx.lineTo(point.x, point.y); + } + + ctx.closePath(); + + if (fillStyle) { ctx.fill(); } + if (lineWidth) { ctx.stroke(); } + + return this; + + }, + + /** + * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. + * + * @method Phaser.BitmapData#textureLine + * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line. + * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. + * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + textureLine: function (line, image, repeat) { + + if (repeat === undefined) { repeat = 'repeat-x'; } + + if (typeof image === 'string') + { + image = this.game.cache.getImage(image); + + if (!image) + { + return; + } + } + + var width = line.length; + + if (repeat === 'no-repeat' && width > image.width) + { + width = image.width; + } + + var ctx = this.context; + + ctx.fillStyle = ctx.createPattern(image, repeat); + + this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height); + + this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos); + + ctx.save(); + ctx.translate(this._pos.x, this._pos.y); + ctx.rotate(line.angle); + ctx.fillRect(0, 0, width, image.height); + ctx.restore(); + + this.dirty = true; + + return this; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. + * + * @method Phaser.BitmapData#render + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + render: function () { + + if (!this.disableTextureUpload && this.dirty) + { + this.baseTexture.dirty(); + this.dirty = false; + } + + return this; + + }, + + /** + * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. + * + * @method Phaser.BitmapData#destroy + */ + destroy: function () { + + this.frameData.destroy(); + + this.texture.destroy(true); + + Phaser.CanvasPool.remove(this); + + }, + + /** + * Resets the blend mode (effectively sets it to 'source-over') + * + * @method Phaser.BitmapData#blendReset + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendReset: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-over' + * + * @method Phaser.BitmapData#blendSourceOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOver: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-in' + * + * @method Phaser.BitmapData#blendSourceIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceIn: function () { + + this.op = 'source-in'; + return this; + + }, + + /** + * Sets the blend mode to 'source-out' + * + * @method Phaser.BitmapData#blendSourceOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOut: function () { + + this.op = 'source-out'; + return this; + + }, + + /** + * Sets the blend mode to 'source-atop' + * + * @method Phaser.BitmapData#blendSourceAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceAtop: function () { + + this.op = 'source-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-over' + * + * @method Phaser.BitmapData#blendDestinationOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOver: function () { + + this.op = 'destination-over'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-in' + * + * @method Phaser.BitmapData#blendDestinationIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationIn: function () { + + this.op = 'destination-in'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-out' + * + * @method Phaser.BitmapData#blendDestinationOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOut: function () { + + this.op = 'destination-out'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-atop' + * + * @method Phaser.BitmapData#blendDestinationAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationAtop: function () { + + this.op = 'destination-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'xor' + * + * @method Phaser.BitmapData#blendXor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendXor: function () { + + this.op = 'xor'; + return this; + + }, + + /** + * Sets the blend mode to 'lighter' + * + * @method Phaser.BitmapData#blendAdd + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendAdd: function () { + + this.op = 'lighter'; + return this; + + }, + + /** + * Sets the blend mode to 'multiply' + * + * @method Phaser.BitmapData#blendMultiply + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendMultiply: function () { + + this.op = 'multiply'; + return this; + + }, + + /** + * Sets the blend mode to 'screen' + * + * @method Phaser.BitmapData#blendScreen + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendScreen: function () { + + this.op = 'screen'; + return this; + + }, + + /** + * Sets the blend mode to 'overlay' + * + * @method Phaser.BitmapData#blendOverlay + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendOverlay: function () { + + this.op = 'overlay'; + return this; + + }, + + /** + * Sets the blend mode to 'darken' + * + * @method Phaser.BitmapData#blendDarken + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDarken: function () { + + this.op = 'darken'; + return this; + + }, + + /** + * Sets the blend mode to 'lighten' + * + * @method Phaser.BitmapData#blendLighten + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLighten: function () { + + this.op = 'lighten'; + return this; + + }, + + /** + * Sets the blend mode to 'color-dodge' + * + * @method Phaser.BitmapData#blendColorDodge + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorDodge: function () { + + this.op = 'color-dodge'; + return this; + + }, + + /** + * Sets the blend mode to 'color-burn' + * + * @method Phaser.BitmapData#blendColorBurn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorBurn: function () { + + this.op = 'color-burn'; + return this; + + }, + + /** + * Sets the blend mode to 'hard-light' + * + * @method Phaser.BitmapData#blendHardLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHardLight: function () { + + this.op = 'hard-light'; + return this; + + }, + + /** + * Sets the blend mode to 'soft-light' + * + * @method Phaser.BitmapData#blendSoftLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSoftLight: function () { + + this.op = 'soft-light'; + return this; + + }, + + /** + * Sets the blend mode to 'difference' + * + * @method Phaser.BitmapData#blendDifference + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDifference: function () { + + this.op = 'difference'; + return this; + + }, + + /** + * Sets the blend mode to 'exclusion' + * + * @method Phaser.BitmapData#blendExclusion + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendExclusion: function () { + + this.op = 'exclusion'; + return this; + + }, + + /** + * Sets the blend mode to 'hue' + * + * @method Phaser.BitmapData#blendHue + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHue: function () { + + this.op = 'hue'; + return this; + + }, + + /** + * Sets the blend mode to 'saturation' + * + * @method Phaser.BitmapData#blendSaturation + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSaturation: function () { + + this.op = 'saturation'; + return this; + + }, + + /** + * Sets the blend mode to 'color' + * + * @method Phaser.BitmapData#blendColor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColor: function () { + + this.op = 'color'; + return this; + + }, + + /** + * Sets the blend mode to 'luminosity' + * + * @method Phaser.BitmapData#blendLuminosity + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLuminosity: function () { + + this.op = 'luminosity'; + return this; + + }, + + /** + * Updates a portion of the BitmapData from a source Bitmap. + * This optimization is important if calling update() on a large Bitmap is causing performance issues. + * Make sure you use getPixel32() instead of getPixel(). + * This does not work with floating point numbers for x and y. + * + * @method Phaser.BitmapData#copyBitmapData + * @param {Phaser.BitmapData} [source] - The BitmapData you wish to copy. + * @param {number} [x] - The x coordinate of the top-left of the area to copy. + * @param {number} [y] - The y coordinate of the top-left of the area to copy. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyBitmapData: function(source, x, y) { + + source.update(); + for (var i = 0, destRowStart; i < source.height; i++) { + destRowStart = (y + i) * this.width + x; + for (var j = 0; j < source.width; j++) { + this.pixels[destRowStart + j] = source.pixels[i * source.width + j]; + } + } + return this; + + } + +}; + +/** +* @memberof Phaser.BitmapData +* @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", { + + get: function () { + + Phaser.Canvas.getSmoothingEnabled(this.context); + + }, + + set: function (value) { + + Phaser.Canvas.setSmoothingEnabled(this.context, value); + + } + +}); + +/** +* @memberof Phaser.BitmapData +* @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "op", { + + get: function () { + + return this.context.globalCompositeOperation; + + }, + + set: function (value) { + + this.context.globalCompositeOperation = value; + + } + +}); + +/** + * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform. + * + * @method Phaser.BitmapData.getTransform + * @param {number} translateX - The x translate value. + * @param {number} translateY - The y translate value. + * @param {number} scaleX - The scale x value. + * @param {number} scaleY - The scale y value. + * @param {number} skewX - The skew x value. + * @param {number} skewY - The skew y value. + * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms. + */ +Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) { + + if (typeof translateX !== 'number') { translateX = 0; } + if (typeof translateY !== 'number') { translateY = 0; } + if (typeof scaleX !== 'number') { scaleX = 1; } + if (typeof scaleY !== 'number') { scaleY = 1; } + if (typeof skewX !== 'number') { skewX = 0; } + if (typeof skewY !== 'number') { skewY = 0; } + + return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY }; + +}; + +Phaser.BitmapData.prototype.constructor = Phaser.BitmapData; + +/* jshint ignore:start */ + +/* +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ + +/** +* @class EarCut +*/ +Phaser.EarCut = {}; + +Phaser.EarCut.Triangulate = function (data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = Phaser.EarCut.linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = Phaser.EarCut.eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + Phaser.EarCut.earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +}; + +// create a circular doubly linked list from polygon points in the specified winding order + +Phaser.EarCut.linkedList = function (data, start, end, dim, clockwise) { + var sum = 0, + i, j, last; + + // calculate original winding order of a polygon ring + for (i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + + // link points into circular doubly-linked list in the specified winding order + if (clockwise === (sum > 0)) { + for (i = start; i < end; i += dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } + + return last; +}; + +// eliminate colinear or duplicate points + +Phaser.EarCut.filterPoints = function (start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (Phaser.EarCut.equals(p, p.next) || Phaser.EarCut.area(p.prev, p, p.next) === 0)) { + Phaser.EarCut.removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +}; + +// main ear slicing loop which triangulates a polygon (given as a linked list) + +Phaser.EarCut.earcutLinked = function (ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) Phaser.EarCut.indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? Phaser.EarCut.isEarHashed(ear, minX, minY, size) : Phaser.EarCut.isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + Phaser.EarCut.removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + Phaser.EarCut.earcutLinked(Phaser.EarCut.filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = Phaser.EarCut.cureLocalIntersections(ear, triangles, dim); + Phaser.EarCut.earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + Phaser.EarCut.splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +}; + +// check whether a polygon node forms a valid ear with adjacent nodes + +Phaser.EarCut.isEar = function (ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +}; + +Phaser.EarCut.isEarHashed = function (ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = Phaser.EarCut.zOrder(minTX, minTY, minX, minY, size), + maxZ = Phaser.EarCut.zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +}; + +// go through all polygon nodes and cure small local self-intersections + +Phaser.EarCut.cureLocalIntersections = function (start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) + if (Phaser.EarCut.intersects(a, p, p.next, b) && Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + Phaser.EarCut.removeNode(p); + Phaser.EarCut.removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +}; + +// try splitting polygon into two and triangulate them independently + +Phaser.EarCut.splitEarcut = function (start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && Phaser.EarCut.isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = Phaser.EarCut.splitPolygon(a, b); + + // filter colinear points around the cuts + a = Phaser.EarCut.filterPoints(a, a.next); + c = Phaser.EarCut.filterPoints(c, c.next); + + // run earcut on each half + Phaser.EarCut.earcutLinked(a, triangles, dim, minX, minY, size); + Phaser.EarCut.earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +}; + +// link every hole into the outer loop, producing a single-ring polygon without holes + +Phaser.EarCut.eliminateHoles = function (data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = Phaser.EarCut.linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(Phaser.EarCut.getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + Phaser.EarCut.eliminateHole(queue[i], outerNode); + outerNode = Phaser.EarCut.filterPoints(outerNode, outerNode.next); + } + + return outerNode; +}; + +Phaser.EarCut.compareX = function (a, b) { + return a.x - b.x; +}; + +// find a bridge between vertices that connects hole with an outer ring and and link it + +Phaser.EarCut.eliminateHole = function (hole, outerNode) { + outerNode = Phaser.EarCut.findHoleBridge(hole, outerNode); + if (outerNode) { + var b = Phaser.EarCut.splitPolygon(outerNode, hole); + Phaser.EarCut.filterPoints(b, b.next); + } +}; + +// David Eberly's algorithm for finding a bridge between hole and outer polygon + +Phaser.EarCut.findHoleBridge = function (hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hole.x === m.x) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= m.x && + Phaser.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && Phaser.EarCut.locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +}; + +// interlink polygon nodes in z-order + +Phaser.EarCut.indexCurve = function (start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = Phaser.EarCut.zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + Phaser.EarCut.sortLinked(p); +}; + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + +Phaser.EarCut.sortLinked = function (list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +}; + +// z-order of a point given coords and size of the data bounding box + +Phaser.EarCut.zOrder = function (x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +}; + +// find the leftmost node of a polygon ring + +Phaser.EarCut.getLeftmost = function (start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +}; + +// check if a point lies within a convex triangle + +Phaser.EarCut.pointInTriangle = function (ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +}; + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) + +Phaser.EarCut.isValidDiagonal = function (a, b) { + return Phaser.EarCut.equals(a, b) || a.next.i !== b.i && a.prev.i !== b.i && !Phaser.EarCut.intersectsPolygon(a, b) && + Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a) && Phaser.EarCut.middleInside(a, b); +}; + +// signed area of a triangle + +Phaser.EarCut.area = function (p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +}; + +// check if two points are equal + +Phaser.EarCut.equals = function (p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +}; + +// check if two segments intersect + +Phaser.EarCut.intersects = function (p1, q1, p2, q2) { + return Phaser.EarCut.area(p1, q1, p2) > 0 !== Phaser.EarCut.area(p1, q1, q2) > 0 && + Phaser.EarCut.area(p2, q2, p1) > 0 !== Phaser.EarCut.area(p2, q2, q1) > 0; +}; + +// check if a polygon diagonal intersects any polygon segments + +Phaser.EarCut.intersectsPolygon = function (a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + Phaser.EarCut.intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +}; + +// check if a polygon diagonal is locally inside the polygon + +Phaser.EarCut.locallyInside = function (a, b) { + return Phaser.EarCut.area(a.prev, a, a.next) < 0 ? + Phaser.EarCut.area(a, b, a.next) >= 0 && Phaser.EarCut.area(a, a.prev, b) >= 0 : + Phaser.EarCut.area(a, b, a.prev) < 0 || Phaser.EarCut.area(a, a.next, b) < 0; +}; + +// check if the middle point of a polygon diagonal is inside the polygon + +Phaser.EarCut.middleInside = function (a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +}; + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring + +Phaser.EarCut.splitPolygon = function (a, b) { + var a2 = new Phaser.EarCut.Node(a.i, a.x, a.y), + b2 = new Phaser.EarCut.Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +}; + +// create a node and optionally link it with previous one (in a circular doubly linked list) + +Phaser.EarCut.insertNode = function (i, x, y, last) { + var p = new Phaser.EarCut.Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +}; + +Phaser.EarCut.removeNode = function (p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +}; + +Phaser.EarCut.Node = function (i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +}; + +/* jshint ignore:end */ + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used by the webGL renderer to draw the primitive graphics data + * + * @class PIXI.WebGLGraphics + * @private + * @static + */ +PIXI.WebGLGraphics = function() +{ +}; + +/** + * The number of points beyond which Pixi swaps to using the Stencil Buffer to render the Graphics. + * + * @type {number} + */ +PIXI.WebGLGraphics.stencilBufferLimit = 6; + +/** + * Renders the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.renderGraphics + * @param graphics {Graphics} + * @param renderSession {Object} + */ +PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset) +{ + var gl = renderSession.gl; + var projection = renderSession.projection, + offset = renderSession.offset, + shader = renderSession.shaderManager.primitiveShader, + webGLData; + + if(graphics.dirty) + { + PIXI.WebGLGraphics.updateGraphics(graphics, gl); + } + + var webGL = graphics._webGL[gl.id]; + + // if the graphics object does not exist in the webGL context skip rendering! + if(!webGL) + { + return; + } + + // This could be speeded up for sure! + + for (var i = 0; i < webGL.data.length; i++) + { + if(webGL.data[i].mode === 1) + { + webGLData = webGL.data[i]; + + renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession); + + // render quad.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + renderSession.stencilManager.popStencil(graphics, webGLData, renderSession); + } + else + { + webGLData = webGL.data[i]; + + + renderSession.shaderManager.setShader( shader );//activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, 1); + + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + } + } +}; + +/** + * Updates the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.updateGraphics + * @param graphicsData {Graphics} The graphics object to update + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLGraphics.updateGraphics = function(graphics, gl) +{ + // get the contexts graphics object + var webGL = graphics._webGL[gl.id]; + // if the graphics object does not exist in the webGL context time to create it! + if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; + + // flag the graphics as not dirty as we are about to update it... + graphics.dirty = false; + + var i; + + // if the user cleared the graphics object we will need to clear every object + if(graphics.clearDirty) + { + graphics.clearDirty = false; + + // lop through and return all the webGLDatas to the object pool so than can be reused later on + for (i = 0; i < webGL.data.length; i++) + { + var graphicsData = webGL.data[i]; + graphicsData.reset(); + PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData ); + } + + // clear the array and reset the index.. + webGL.data = []; + webGL.lastIndex = 0; + } + + var webGLData; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + if (data.type === Phaser.POLYGON) + { + // need to add the points the the graphics object.. + data.points = data.shape.points.slice(); + if(data.shape.closed) + { + // close the poly if the value is true! + if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { + data.points.push(data.points[0], data.points[1]); + } + } + + // MAKE SURE WE HAVE THE CORRECT TYPE.. + if(data.fill) + { + if(data.points.length >= PIXI.WebGLGraphics.stencilBufferLimit) + { + if(data.points.length < PIXI.WebGLGraphics.stencilBufferLimit * 2) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData); + // console.log(canDrawUsingSimple); + + if(!canDrawUsingSimple) + { + // console.log("<>>>") + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + } + } + + if(data.lineWidth > 0) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + PIXI.WebGLGraphics.buildLine(data, webGLData); + + } + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + if (data.type === Phaser.RECTANGLE) + { + PIXI.WebGLGraphics.buildRectangle(data, webGLData); + } + else if (data.type === Phaser.CIRCLE || data.type === Phaser.ELLIPSE) + { + PIXI.WebGLGraphics.buildCircle(data, webGLData); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData); + } + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (i = 0; i < webGL.data.length; i++) + { + webGLData = webGL.data[i]; + if(webGLData.dirty)webGLData.upload(); + } +}; + +/** + * @static + * @private + * @method PIXI.WebGLGraphics.switchMode + * @param webGL {WebGLContext} + * @param type {Number} + */ +PIXI.WebGLGraphics.switchMode = function(webGL, type) +{ + var webGLData; + + if(!webGL.data.length) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + else + { + webGLData = webGL.data[webGL.data.length-1]; + + if(webGLData.mode !== type || type === 1) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + } + + webGLData.dirty = true; + + return webGLData; +}; + +/** + * Builds a rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData) +{ + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; + + // start + 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); + + // insert 2 dead triangles.. + 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; + } +}; + +/** + * Builds a rounded rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRoundedRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData) +{ + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + recPoints.push(x, y + radius); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); + + if (graphicsData.fill) { + var color = Phaser.Color.hexToRGBArray(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; + + var triangles = Phaser.EarCut.Triangulate(recPoints, null, 2); + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i+1] + vecPos); + indices.push(triangles[i+2] + vecPos); + indices.push(triangles[i+2] + vecPos); + } + + + for (i = 0; i < recPoints.length; i++) + { + verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @static + * @private + * @method PIXI.WebGLGraphics.quadraticBezierCurve + * @param fromX {Number} Origin point x + * @param fromY {Number} Origin point x + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Array(Number)} + */ +PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) { + + var xa, + ya, + xb, + yb, + x, + y, + n = 20, + points = []; + + function getPt(n1 , n2, perc) { + var diff = n2 - n1; + + return n1 + ( diff * perc ); + } + + var j = 0; + for (var i = 0; i <= n; i++ ) + { + j = i / n; + + // The Green Line + xa = getPt( fromX , cpX , j ); + ya = getPt( fromY , cpY , j ); + xb = getPt( cpX , toX , j ); + yb = getPt( cpY , toY , j ); + + // The Black Dot + x = getPt( xa , xb , j ); + y = getPt( ya , yb , j ); + + points.push(x, y); + } + return points; +}; + +/** + * Builds a circle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildCircle + * @param graphicsData {Graphics} The graphics object to draw + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData) +{ + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + + // TODO - bit hacky?? + if (graphicsData.type === Phaser.CIRCLE) + { + width = circleData.radius; + height = circleData.radius; + } + else + { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = 40; + var seg = (Math.PI * 2) / totalSegs ; + + var i = 0; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; i < totalSegs + 1 ; i++) + { + verts.push(x,y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos-1); + } + + if(graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (i = 0; i < totalSegs + 1; i++) + { + graphicsData.points.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height); + } + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Builds a line to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildLine + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData) +{ + // TODO OPTIMISE! + var i = 0; + var points = graphicsData.points; + if(points.length === 0)return; + + // if the line width is an odd number add 0.5 to align to a whole pixel + if(graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) { + points[i] += 0.5; + } + } + + // get first and last point.. figure out the middle! + var firstPoint = new PIXI.Point( points[0], points[1] ); + var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + // if the first point is the last point - gonna have issues :) + if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length/6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var px, py, p1x, p1y, p2x, p2y, p3x, p3y; + var perpx, perpy, perp2x, perp2y, perp3x, perp3y; + var a1, b1, c1, a2, b2, c2; + var denom, pdist, dist; + + p1x = points[0]; + p1y = points[1]; + + p2x = points[2]; + p2y = points[3]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx , p1y - perpy, + r, g, b, alpha); + + verts.push(p1x + perpx , p1y + perpy, + r, g, b, alpha); + + for (i = 1; i < length-1; i++) + { + p1x = points[(i-1)*2]; + p1y = points[(i-1)*2 + 1]; + + p2x = points[(i)*2]; + p2y = points[(i)*2 + 1]; + + p3x = points[(i+1)*2]; + p3y = points[(i+1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + a1 = (-perpy + p1y) - (-perpy + p2y); + b1 = (-perpx + p2x) - (-perpx + p1x); + c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + a2 = (-perp2y + p3y) - (-perp2y + p2y); + b2 = (-perp2x + p2x) - (-perp2x + p3x); + c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + denom = a1*b2 - a2*b1; + + if(Math.abs(denom) < 0.1 ) + { + + denom+=10.1; + verts.push(p2x - perpx , p2y - perpy, + r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy, + r, g, b, alpha); + + continue; + } + + px = (b1*c2 - b2*c1)/denom; + py = (a2*c1 - a1*c2)/denom; + + + pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); + + + if(pdist > 140 * 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 < indexCount; i++) + { + indices.push(indexStart++); + } + + indices.push(indexStart-1); +}; + +/** + * Builds a complex polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildComplexPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData) +{ + //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. + var points = graphicsData.points.slice(); + if(points.length < 6)return; + + // get first and last point.. figure out the middle! + var indices = webGLData.indices; + webGLData.points = points; + webGLData.alpha = graphicsData.fillAlpha; + webGLData.color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + + /* + calclate the bounds.. + */ + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + var x,y; + + // get size.. + for (var i = 0; i < points.length; i+=2) + { + x = points[i]; + y = points[i+1]; + + minX = x < minX ? x : minX; + maxX = x > maxX ? x : maxX; + + minY = y < minY ? y : minY; + maxY = y > maxY ? y : maxY; + } + + // add a quad to the end cos there is no point making another buffer! + points.push(minX, minY, + maxX, minY, + maxX, maxY, + minX, maxY); + + // push a quad onto the end.. + + //TODO - this aint needed! + var length = points.length / 2; + for (i = 0; i < length; i++) + { + indices.push( i ); + } + +}; + +/** + * Builds a polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData) +{ + var points = graphicsData.points; + + if(points.length < 6)return; + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = Phaser.EarCut.Triangulate(points, null, 2); + + if(!triangles)return false; + + var vertPos = verts.length / 6; + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i] + vertPos); + indices.push(triangles[i+1] + vertPos); + indices.push(triangles[i+2] +vertPos); + indices.push(triangles[i+2] + vertPos); + } + + for (i = 0; i < length; i++) + { + verts.push(points[i * 2], points[i * 2 + 1], + r, g, b, alpha); + } + + return true; +}; + +PIXI.WebGLGraphics.graphicsDataPool = []; + +/** + * @class WebGLGraphicsData + * @private + * @static + */ +PIXI.WebGLGraphicsData = function(gl) +{ + this.gl = gl; + + //TODO does this need to be split before uploding?? + this.color = [0,0,0]; // color split! + this.points = []; + this.indices = []; + this.buffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + this.mode = 1; + this.alpha = 1; + this.dirty = true; +}; + +/** + * @method PIXI.WebGLGraphics.reset + */ +PIXI.WebGLGraphicsData.prototype.reset = function() +{ + this.points = []; + this.indices = []; +}; + +/** + * @method PIXI.WebGLGraphics.upload + */ +PIXI.WebGLGraphicsData.prototype.upload = function() +{ + var gl = this.gl; + +// this.lastIndex = graphics.graphicsData.length; + this.glPoints = new Float32Array(this.points); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW); + + this.glIndicies = new Uint16Array(this.indices); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW); + + this.dirty = false; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + +/** + * A set of functions used by the canvas renderer to draw the primitive graphics data. + * + * @class PIXI.CanvasGraphics + * @static + */ +PIXI.CanvasGraphics = function() +{ +}; + +/** + * Renders a {@link Phaser.Graphics} object to a canvas. + * + * @method PIXI.CanvasGraphics.renderGraphics + * @static + * @param graphics {Graphics} the actual graphics object to render + * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas + */ +PIXI.CanvasGraphics.renderGraphics = function(graphics, context) +{ + var worldAlpha = graphics.worldAlpha; + + if (graphics.dirty) + { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === Phaser.POLYGON) + { + context.beginPath(); + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (shape.closed) + { + context.lineTo(points[0], points[1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.RECTANGLE) + { + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ELLIPSE) + { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + context.beginPath(); + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + +}; + +/** + * Renders a graphics mask + * + * @static + * @private + * @method PIXI.CanvasGraphics.renderGraphicsMask + * @param graphics {Graphics} the graphics which will be used as a mask + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + */ +PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context) +{ + var len = graphics.graphicsData.length; + + if (len === 0) + { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === Phaser.POLYGON) + { + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + } + else if (data.type === Phaser.RECTANGLE) + { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } + else if (data.type === Phaser.ELLIPSE) + { + + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } +}; + +PIXI.CanvasGraphics.updateGraphicsTint = function(graphics) +{ + if (graphics.tint === 0xFFFFFF) + { + return; + } + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF)/ 255; + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255); + data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255); + + } + +}; + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + * @param lineWidth {number} the width of the line to draw + * @param lineColor {number} the color of the line to draw + * @param lineAlpha {number} the alpha of the line to draw + * @param fillColor {number} the color of the fill + * @param fillAlpha {number} the alpha of the fill + * @param fill {boolean} whether or not the shape is filled with a colour + * @param shape {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + +Phaser.GraphicsData = function (lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { + + /* + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /* + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /* + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /* + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /* + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /* + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /* + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /* + * @member {boolean} whether or not the shape is filled with a color + */ + this.fill = fill; + + /* + * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + this.shape = shape; + + /* + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + +}; + +Phaser.GraphicsData.prototype.constructor = Phaser.GraphicsData; + +/** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {GraphicsData} + */ +Phaser.GraphicsData.prototype.clone = function () { + + return new Phaser.GraphicsData( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.fill, + this.shape + ); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, +* Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will +* be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: +* +* ```javascript +* graphics.beginFill(0xff0000); +* graphics.drawCircle(50, 50, 100); +* graphics.endFill(); +* ``` +* +* This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. +* +* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or +* WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the +* graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. +* +* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help +* performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. +* You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then +* you should avoid doing this, as it will constantly generate new textures, which will consume memory. +* +* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful +* in their complexity and quantity of them in your game. +* +* @class Phaser.Graphics +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - X position of the new graphics object. +* @param {number} [y=0] - Y position of the new graphics object. +*/ +Phaser.Graphics = function (game, x, y) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.GRAPHICS; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value. + * @private + */ + this.anchor = new Phaser.Point(); + + PIXI.DisplayObjectContainer.call(this); + + this.renderable = true; + + /** + * The alpha value used when filling the Graphics object. + * + * @property fillAlpha + * @type Number + */ + this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @property lineWidth + * @type Number + */ + this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @property lineColor + * @type String + * @default 0 + */ + this.lineColor = 0; + + /** + * Graphics data + * + * @property graphicsData + * @type Array + * @private + */ + this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF (Phaser.Color.WHITE) to reset the tint. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * Current path + * + * @property currentPath + * @type Object + * @private + */ + this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @property _webGL + * @type Array + * @private + */ + this._webGL = []; + + /** + * Whether this shape is being used as a mask. + * + * @property isMask + * @type Boolean + */ + this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @property boundsPadding + * @type Number + */ + this.boundsPadding = 0; + + this._localBounds = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property dirty + * @type Boolean + * @private + */ + this.dirty = true; + + /** + * Used to detect if the bounds have been invalidated, by this Graphics being cleared or drawn to. + * If this is set to true then the updateLocalBounds is called once in the postUpdate method. + * + * @property _boundsDirty + * @type Boolean + * @private + */ + this._boundsDirty = false; + + /** + * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property webGLDirty + * @type Boolean + * @private + */ + this.webGLDirty = false; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @property cachedSpriteDirty + * @type Boolean + * @private + */ + this.cachedSpriteDirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.Graphics.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Graphics.prototype.constructor = Phaser.Graphics; + +Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Graphics#preUpdate +*/ +Phaser.Graphics.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World +* +* @method Phaser.Graphics#postUpdate +*/ +Phaser.Graphics.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this._boundsDirty) + { + this.updateLocalBounds(); + this._boundsDirty = false; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Destroy this Graphics instance. +* +* @method Phaser.Graphics#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Graphics.prototype.destroy = function (destroyChildren) { + + this.clear(); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Draws a single {@link Phaser.Polygon} triangle from a {@link Phaser.Point} array +* +* @method Phaser.Graphics#drawTriangle +* @param {Array} points - An array of Phaser.Points that make up the three vertices of this triangle +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangle = function (points, cull) { + + if (cull === undefined) { cull = false; } + + var triangle = new Phaser.Polygon(points); + + if (cull) + { + var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y); + var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y); + var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y); + var faceNormal = cb.cross(ab); + + if (cameraToFace.dot(faceNormal) > 0) + { + this.drawPolygon(triangle); + } + } + else + { + this.drawPolygon(triangle); + } + +}; + +/** +* Draws {@link Phaser.Polygon} triangles +* +* @method Phaser.Graphics#drawTriangles +* @param {Array|Array} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles +* @param {Array} [indices=null] - An array of numbers that describe what order to draw the vertices in +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) { + + if (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 < vertices.length / 3; i++) + { + this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull); + } + } + else + { + for (i = 0; i < vertices.length / 6; i++) + { + point1.x = vertices[i * 6 + 0]; + point1.y = vertices[i * 6 + 1]; + point2.x = vertices[i * 6 + 2]; + point2.y = vertices[i * 6 + 3]; + point3.x = vertices[i * 6 + 4]; + point3.y = vertices[i * 6 + 5]; + this.drawTriangle([point1, point2, point3], cull); + } + } + } + else + { + if (vertices[0] instanceof Phaser.Point) + { + for (i = 0; i < indices.length /3; i++) + { + points.push(vertices[indices[i * 3 ]]); + points.push(vertices[indices[i * 3 + 1]]); + points.push(vertices[indices[i * 3 + 2]]); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + else + { + for (i = 0; i < indices.length; i++) + { + point1.x = vertices[indices[i] * 2]; + point1.y = vertices[indices[i] * 2 + 1]; + points.push(point1.copyTo({})); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + } +}; + +/** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. + * + * @method Phaser.Graphics#lineStyle + * @param lineWidth {Number} width of the line to draw, will update the objects stored style + * @param color {Number} color of the line to draw, will update the objects stored style + * @param alpha {Number} alpha of the line to draw, will update the objects stored style + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { + + this.lineWidth = lineWidth || 0; + this.lineColor = color || 0; + this.lineAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { + // halfway through a line? start a new one! + this.drawShape(new Phaser.Polygon(this.currentPath.shape.points.slice(-2))); + } + else + { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + +}; + +/** + * Moves the current drawing position to x, y. + * + * @method Phaser.Graphics#moveTo + * @param x {Number} the X coordinate to move to + * @param y {Number} the Y coordinate to move to + * @return {Graphics} + */ +Phaser.Graphics.prototype.moveTo = function (x, y) { + + this.drawShape(new Phaser.Polygon([ x, y ])); + + return this; + +}; + +/** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @method Phaser.Graphics#lineTo + * @param x {Number} the X coordinate to draw to + * @param y {Number} the Y coordinate to draw to + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineTo = function (x, y) { + + if (!this.currentPath) + { + this.moveTo(0, 0); + } + + this.currentPath.shape.points.push(x, y); + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @method Phaser.Graphics#quadraticCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [ 0, 0 ]; + } + } + else + { + this.moveTo(0,0); + } + + var xa, + ya, + n = 20, + points = this.currentPath.shape.points; + + if (points.length === 0) + { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var j = 0; + for (var i = 1; i <= n; ++i) + { + j = i / n; + + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + + points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), + ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a bezier curve and then draws it. + * + * @method Phaser.Graphics#bezierCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param cpX2 {Number} Second Control point x + * @param cpY2 {Number} Second Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + var n = 20, + dt, + dt2, + dt3, + t2, + t3, + points = this.currentPath.shape.points; + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + var j = 0; + + for (var i = 1; i <= n; ++i) + { + j = i / n; + + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, + dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @method Phaser.Graphics#arcTo + * @param x1 {Number} The x-coordinate of the beginning of the arc + * @param y1 {Number} The y-coordinate of the beginning of the arc + * @param x2 {Number} The x-coordinate of the end of the arc + * @param y2 {Number} The y-coordinate of the end of the arc + * @param radius {Number} The radius of the arc + * @return {Graphics} + */ +Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points.push(x1, y1); + } + } + else + { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points, + fromX = points[points.length-2], + fromY = points[points.length-1], + a1 = fromY - y1, + b1 = fromX - x1, + a2 = y2 - y1, + b2 = x2 - x1, + mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { + points.push(x1, y1); + } + } + else + { + var dd = a1 * a1 + b1 * b1, + cc = a2 * a2 + b2 * b2, + tt = a1 * a2 + b1 * b2, + k1 = radius * Math.sqrt(dd) / mm, + k2 = radius * Math.sqrt(cc) / mm, + j1 = k1 * tt / dd, + j2 = k2 * tt / cc, + cx = k1 * b2 + k2 * b1, + cy = k1 * a2 + k2 * a1, + px = b1 * (k2 + j1), + py = a1 * (k2 + j1), + qx = b2 * (k1 + j2), + qy = a2 * (k1 + j2), + startAngle = Math.atan2(py - cy, px - cx), + endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @method Phaser.Graphics#arc + * @param cx {Number} The x-coordinate of the center of the circle + * @param cy {Number} The y-coordinate of the center of the circle + * @param radius {Number} The radius of the circle + * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) + * @param endAngle {Number} The ending angle, in radians + * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. + * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. + * @return {Graphics} + */ +Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise, segments) { + + // If we do this we can never draw a full circle + if (startAngle === endAngle) + { + return this; + } + + if (anticlockwise === undefined) { anticlockwise = false; } + if (segments === undefined) { segments = 40; } + + if (!anticlockwise && endAngle <= startAngle) + { + endAngle += Math.PI * 2; + } + else if (anticlockwise && startAngle <= endAngle) + { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments; + + // Sweep check - moved here because we don't want to do the moveTo below if the arc fails + if (sweep === 0) + { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (anticlockwise && this.filling) + { + this.moveTo(cx, cy); + } + else + { + this.moveTo(startX, startY); + } + + // currentPath will always exist after calling a moveTo + var points = this.currentPath.shape.points; + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = (segMinus % 1) / segMinus; + + for (var i = 0; i <= segMinus; i++) + { + var real = i + remainder * i; + + var angle = ((theta) + startAngle + (theta2 * real)); + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, + ( (cTheta * -s) + (sTheta * c) ) * radius + cy); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @method Phaser.Graphics#beginFill + * @param color {Number} the color of the fill + * @param alpha {Number} the alpha of the fill + * @return {Graphics} + */ +Phaser.Graphics.prototype.beginFill = function (color, alpha) { + + this.filling = true; + this.fillColor = color || 0; + this.fillAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + +}; + +/** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @method Phaser.Graphics#endFill + * @return {Graphics} + */ +Phaser.Graphics.prototype.endFill = function () { + + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRect + * + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawRect = function (x, y, width, height) { + + this.drawShape(new Phaser.Rectangle(x, y, width, height)); + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRoundedRect + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. + */ +Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + + this.drawShape(new Phaser.RoundedRectangle(x, y, width, height, radius)); + + return this; + +}; + +/** + * Draws a circle. + * + * @method Phaser.Graphics#drawCircle + * @param x {Number} The X coordinate of the center of the circle + * @param y {Number} The Y coordinate of the center of the circle + * @param diameter {Number} The diameter of the circle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) { + + this.drawShape(new Phaser.Circle(x, y, diameter)); + + return this; + +}; + +/** + * Draws an ellipse. + * + * @method Phaser.Graphics#drawEllipse + * @param x {Number} The X coordinate of the center of the ellipse + * @param y {Number} The Y coordinate of the center of the ellipse + * @param width {Number} The half width of the ellipse + * @param height {Number} The half height of the ellipse + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawEllipse = function (x, y, width, height) { + + this.drawShape(new Phaser.Ellipse(x, y, width, height)); + + return this; + +}; + +/** + * Draws a polygon using the given path. + * + * @method Phaser.Graphics#drawPolygon + * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawPolygon = function (path) { + + if (path instanceof Phaser.Polygon) + { + path = path.points; + } + + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) + { + points[i] = arguments[i]; + } + } + + this.drawShape(new Phaser.Polygon(points)); + + return this; + +}; + +/** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @method Phaser.Graphics#clear + * @return {Graphics} + */ +Phaser.Graphics.prototype.clear = function () { + + this.lineWidth = 0; + this.filling = false; + + this.dirty = true; + this._boundsDirty = true; + this.clearDirty = true; + this.graphicsData = []; + + this.updateLocalBounds(); + + return this; + +}; + +/** + * Useful function that returns a texture of the graphics object that can then be used to create sprites + * This can be quite useful if your geometry is complicated and needs to be reused multiple times. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * @method Phaser.Graphics#generateTexture + * @param [resolution=1] {Number} The resolution of the texture being generated + * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts + * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0) + * @return {Texture} a texture of the graphics object + */ +Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, padding) { + + if (resolution === undefined) { resolution = 1; } + if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; } + if (padding === undefined) { padding = 0; } + + var bounds = this.getBounds(); + + bounds.width += padding; + bounds.height += padding; + + var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution); + + var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + + canvasBuffer.context.scale(resolution, resolution); + + canvasBuffer.context.translate(-bounds.x, -bounds.y); + + PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context); + + return texture; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Graphics#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderWebGL = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture on the gpu too! + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.worldAlpha = this.worldAlpha; + + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + + return; + } + else + { + renderSession.spriteBatch.stop(); + renderSession.blendModeManager.setBlendMode(this.blendMode); + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + if (this._filters) + { + renderSession.filterManager.pushFilter(this._filterBlock); + } + + // check blend mode + if (this.blendMode !== renderSession.spriteBatch.currentBlendMode) + { + renderSession.spriteBatch.currentBlendMode = this.blendMode; + var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode]; + renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + // check if the webgl graphic needs to be updated + if (this.webGLDirty) + { + this.dirty = true; + this.webGLDirty = false; + } + + PIXI.WebGLGraphics.renderGraphics(this, renderSession); + + // only render if it has children! + if (this.children.length) + { + renderSession.spriteBatch.start(); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + } + + if (this._filters) + { + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + renderSession.maskManager.popMask(this.mask, renderSession); + } + + renderSession.drawCount++; + + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method Phaser.Graphics#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderCanvas = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) + { + this.dirty = true; + this._prevTint = this.tint; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.alpha = this.alpha; + + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + + return; + } + else + { + var context = renderSession.context; + var transform = this.worldTransform; + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + var resolution = renderSession.resolution; + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + tx, + ty); + + PIXI.CanvasGraphics.renderGraphics(this, context); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + } + +}; + +/** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @method Phaser.Graphics#getBounds + * @return {Rectangle} the rectangular bounding area + */ +Phaser.Graphics.prototype.getBounds = function (matrix) { + + if (this._currentBounds) + { + return this._currentBounds; + } + + // Return an empty object if the item is a mask! + if (!this.renderable) + { + return Phaser.EmptyRectangle; + } + + if (this.dirty) + { + this.updateLocalBounds(); + this.webGLDirty = true; + this.cachedSpriteDirty = true; + this.dirty = false; + } + + var bounds = this._localBounds; + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = x1; + var maxY = y1; + + var minX = x1; + var minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + + this._bounds.x = minX; + this._bounds.width = maxX - minX; + + this._bounds.y = minY; + this._bounds.height = maxY - minY; + + this._currentBounds = this._bounds; + + return this._currentBounds; + +}; + +/** + * Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration. + * + * @method Phaser.Graphics#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +Phaser.Graphics.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Tests if a point is inside this graphics object +* +* @param point {Point} the point to test +* @return {boolean} the result of the test +*/ +Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) { + + if (tempPoint === undefined) { tempPoint = new Phaser.Point(); } + + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; i++) + { + var data = graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // only deal with fills.. + if (data.shape) + { + if (data.shape.contains(tempPoint.x, tempPoint.y)) + { + return true; + } + } + } + + return false; + +}; + +/** + * Update the bounds of the object + * + * @method Phaser.Graphics#updateLocalBounds + */ +Phaser.Graphics.prototype.updateLocalBounds = function () { + + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) + { + var shape, points, x, y, w, h; + + for (var i = 0; i < this.graphicsData.length; i++) + { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + shape = data.shape; + + if (type === Phaser.RECTANGLE || type === Phaser.ROUNDEDRECTANGLE) + { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.CIRCLE) + { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.ELLIPSE) + { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else + { + // POLY - assumes points are sequential, not Point objects + points = shape.points; + + for (var j = 0; j < points.length; j++) + { + if (points[j] instanceof Phaser.Point) + { + x = points[j].x; + y = points[j].y; + } + else + { + x = points[j]; + y = points[j + 1]; + + if (j < points.length - 1) + { + j++; + } + } + + minX = x - lineWidth < minX ? x - lineWidth : minX; + maxX = x + lineWidth > maxX ? x + lineWidth : maxX; + + minY = y - lineWidth < minY ? y - lineWidth : minY; + maxY = y + lineWidth > maxY ? y + lineWidth : maxY; + } + } + } + } + else + { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.x = minX - padding; + this._localBounds.width = (maxX - minX) + padding * 2; + + this._localBounds.y = minY - padding; + this._localBounds.height = (maxY - minY) + padding * 2; + +}; + +/** + * Generates the cached sprite when the sprite has cacheAsBitmap = true + * + * @method Phaser.Graphics#_generateCachedSprite + * @private + */ +Phaser.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); + } + + // leverage the anchor to account for the offset of the element + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + // this._cachedSprite.buffer.context.save(); + this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y); + + // make sure we set the alpha of the graphics to 1 for the render.. + this.worldAlpha = 1; + + // now render the graphic.. + PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context); + this._cachedSprite.alpha = this.alpha; + +}; + +/** + * Updates texture size based on canvas size + * + * @method Phaser.Graphics#updateCachedSpriteTexture + * @private + */ +Phaser.Graphics.prototype.updateCachedSpriteTexture = function () { + + var cachedSprite = this._cachedSprite; + var texture = cachedSprite.texture; + var canvas = cachedSprite.buffer.canvas; + + texture.baseTexture.width = canvas.width; + texture.baseTexture.height = canvas.height; + texture.crop.width = texture.frame.width = canvas.width; + texture.crop.height = texture.frame.height = canvas.height; + + cachedSprite._width = canvas.width; + cachedSprite._height = canvas.height; + + // update the dirty base textures + texture.baseTexture.dirty(); + +}; + +/** + * Destroys a previous cached sprite. + * + * @method Phaser.Graphics#destroyCachedSprite + */ +Phaser.Graphics.prototype.destroyCachedSprite = function () { + + this._cachedSprite.texture.destroy(true); + this._cachedSprite = null; + +}; + +/** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @method Phaser.Graphics#drawShape + * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. + * @return {GraphicsData} The generated GraphicsData object. + */ +Phaser.Graphics.prototype.drawShape = function (shape) { + + if (this.currentPath) + { + // check current path! + if (this.currentPath.shape.points.length <= 2) + { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + // Handle mixed-type polygons + if (shape instanceof Phaser.Polygon) + { + shape = shape.clone(); + shape.flatten(); + } + + var data = new Phaser.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === Phaser.POLYGON) + { + data.shape.closed = this.filling; + this.currentPath = data; + } + + this.dirty = true; + this._boundsDirty = true; + + return data; + +}; + +/** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory. + * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas. + * This is not recommended if you are constantly redrawing the graphics element. + * + * @property cacheAsBitmap + * @type Boolean + * @default false + * @private + */ +Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + this._cacheAsBitmap = value; + + if (this._cacheAsBitmap) + { + this._generateCachedSprite(); + } + else + { + this.destroyCachedSprite(); + } + + this.dirty = true; + this.webGLDirty = true; + + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and +* render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. +* +* @class Phaser.RenderTexture +* @constructor +* @extends PIXI.Texture +* @param {Phaser.Game} game - Current game instance. +* @param {number} [width=100] - The width of the render texture. +* @param {number} [height=100] - The height of the render texture. +* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there. +* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts. +* @param {number} [resolution=1] - The resolution of the texture being generated. +*/ +Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution, renderer, textureUnit) { + + if (width === undefined) { width = 100; } + if (height === undefined) { height = 100; } + if (key === undefined) { key = ''; } + if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; } + if (resolution === undefined) { resolution = 1; } + if (renderer === undefined) { renderer = PIXI.defaultRenderer; } + if (textureUnit === undefined) { textureUnit = 0; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the RenderTexture in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RENDERTEXTURE; + + /** + * @property {Phaser.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture. + * @private + */ + this._tempMatrix = new Phaser.Matrix(); + + this.width = width; + this.height = height; + this.resolution = resolution; + + this.frame = new Phaser.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); + + this.crop = this.frame.clone(); + + /** + * The base texture object that this texture uses + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = new PIXI.BaseTexture(); + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + this.baseTexture._glTextures = []; + this.baseTexture.resolution = this.resolution; + + this.baseTexture.scaleMode = scaleMode; + + this.baseTexture.hasLoaded = true; + + PIXI.Texture.call(this, this.baseTexture, this.frame.clone()); + + /** + * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. + * + * @property renderer + * @type CanvasRenderer|WebGLRenderer + */ + this.renderer = renderer; + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + this.baseTexture.textureIndex = textureUnit; + this.baseTexture._dirty[gl.id] = false; + + this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode, textureUnit); + this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; + + this.projection = new Phaser.Point(this.width * 0.5, -this.height * 0.5); + } + else + { + this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution); + this.baseTexture.source = this.textureBuffer.canvas; + } + + /** + * @property valid + * @type Boolean + */ + this.valid = true; + + this.tempMatrix = new Phaser.Matrix(); + + this._updateUvs(); + +}; + +Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype); +Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it takes into account scale and rotation. +* +* If you don't want those then use RenderTexture.renderRawXY instead. +* +* @method Phaser.RenderTexture.prototype.renderXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) { + + displayObject.updateTransform(); + + this._tempMatrix.copyFrom(displayObject.worldTransform); + this._tempMatrix.tx = x; + this._tempMatrix.ty = y; + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it doesn't take into account scale, rotation or translation. +* +* If you need those then use RenderTexture.renderXY instead. +* +* @method Phaser.RenderTexture.prototype.renderRawXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) { + + this._tempMatrix.identity().translate(x, y); + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture. +* +* In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. +* This is now a Matrix allowing you much more control over how the Display Object is rendered. +* If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. +* +* If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either +* pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. +* +* @method Phaser.RenderTexture.prototype.render +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) { + + if (matrix === undefined || matrix === null) + { + this._tempMatrix.copyFrom(displayObject.worldTransform); + } + else + { + this._tempMatrix.copyFrom(matrix); + } + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* Resizes the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.resize +* @param {number} width - The width to resize to. +* @param {number} height - The height to resize to. +* @param {boolean} updateBase - Should the baseTexture.width and height values be resized as well? +*/ +Phaser.RenderTexture.prototype.resize = function (width, height, updateBase) { + + if (width === this.width && height === this.height) + { + return; + } + + this.valid = (width > 0 && height > 0); + + this.width = width; + this.height = height; + this.frame.width = this.crop.width = width * this.resolution; + this.frame.height = this.crop.height = height * this.resolution; + + if (updateBase) + { + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.projection.x = this.width / 2; + this.projection.y = -this.height / 2; + } + + if (!this.valid) + { + return; + } + + this.textureBuffer.resize(this.width, this.height); + +}; + +/** +* Clears the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.clear +*/ +Phaser.RenderTexture.prototype.clear = function () { + + if (!this.valid) + { + return; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + } + + this.textureBuffer.clear(); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderWebGL +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +* @private +*/ +Phaser.RenderTexture.prototype._renderWebGL = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + wt.translate(0, this.projection.y * 2); + + if (matrix) + { + wt.append(matrix); + } + + wt.scale(1, -1); + + // Time to update all the children of the displayObject with the new matrix. + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + // Time for the webGL fun stuff! + var gl = this.renderer.gl; + + gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + + if (clear) + { + this.textureBuffer.clear(); + } + + this.renderer.spriteBatch.dirty = true; + + this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix); + + this.renderer.spriteBatch.dirty = true; + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderCanvas +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +*/ +Phaser.RenderTexture.prototype._renderCanvas = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + + if (matrix) + { + wt.append(matrix); + } + + // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!) + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + if (clear) + { + this.textureBuffer.clear(); + } + + var realResolution = this.renderer.resolution; + + this.renderer.resolution = this.resolution; + + this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix); + + this.renderer.resolution = realResolution; + +}; + +/** +* Will return a HTML Image of the texture +* +* @method Phaser.RenderTexture.prototype.getImage +* @return {Image} +*/ +Phaser.RenderTexture.prototype.getImage = function () { + + var image = new Image(); + image.src = this.getBase64(); + + return image; + +}; + +/** +* Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. +* +* @method Phaser.RenderTexture.prototype.getBase64 +* @return {String} A base64 encoded string of the texture. +*/ +Phaser.RenderTexture.prototype.getBase64 = function () { + + return this.getCanvas().toDataURL(); + +}; + +/** +* Creates a Canvas element, renders this RenderTexture to it and then returns it. +* +* @method Phaser.RenderTexture.prototype.getCanvas +* @return {HTMLCanvasElement} A Canvas element with the texture rendered on. +*/ +Phaser.RenderTexture.prototype.getCanvas = function () { + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + var width = this.textureBuffer.width; + var height = this.textureBuffer.height; + + var webGLPixels = new Uint8Array(4 * width * height); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + var tempCanvas = new PIXI.CanvasBuffer(width, height); + var canvasData = tempCanvas.context.getImageData(0, 0, width, height); + canvasData.data.set(webGLPixels); + + tempCanvas.context.putImageData(canvasData, 0, 0); + + return tempCanvas.canvas; + } + else + { + return this.textureBuffer.canvas; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new game object for displaying Text. +* +* This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. +* Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. +* +* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers. +* +* @class Phaser.Text +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {number} x - X position of the new text object. +* @param {number} y - Y position of the new text object. +* @param {string} text - The actual text that will be written. +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +*/ +Phaser.Text = function (game, x, y, text, style) { + + x = x || 0; + y = y || 0; + + if (text === undefined || text === null) + { + text = ''; + } + else + { + text = text.toString(); + } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.TEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. + * @property {Phaser.Point} padding + */ + this.padding = new Phaser.Point(); + + /** + * The textBounds property allows you to specify a rectangular region upon which text alignment is based. + * See `Text.setTextBounds` for more details. + * @property {Phaser.Rectangle} textBounds + * @readOnly + */ + this.textBounds = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. + */ + this.canvas = Phaser.CanvasPool.create(this); + + /** + * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. + */ + this.context = this.canvas.getContext('2d'); + + /** + * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}. + */ + this.colors = []; + + /** + * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}. + */ + this.strokeColors = []; + + /** + * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}. + */ + this.fontStyles = []; + + /** + * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}. + */ + this.fontWeights = []; + + /** + * Should the linePositionX and Y values be automatically rounded before rendering the Text? + * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. + * @property {boolean} autoRound + * @default + */ + this.autoRound = false; + + /** + * Will this Text object use Basic or Advanced Word Wrapping? + * + * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. + * White space is condensed (e.g., consecutive spaces are replaced with one). + * Lines are trimmed of white space before processing. + * + * It throws an error if wordWrapWidth is less than a single character. + * @property {boolean} useAdvancedWrap + * @default + */ + this.useAdvancedWrap = false; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + * @property {Object} splitRegExp + */ + this.splitRegExp = /(?:\r\n|\r|\n)/; + + + /** The maximum number of characters that can be set. + * @property {number} characterLimitSize + */ + this.characterLimitSize = -1; + + /** The suffix that is applied to truncated text that is longer than the + * characterLimitSize. + * @property {string} characterLimitSuffix + */ + this.characterLimitSuffix = ''; + + /** + * @property {number} _res - Internal canvas resolution var. + * @private + */ + this._res = game.renderer.resolution; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text; + + /** + * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`. + * @private + */ + this._fontComponents = null; + + /** + * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. + * @private + */ + this._lineSpacing = 0; + + /** + * @property {number} _charCount - Internal character counter used by the text coloring. + * @private + */ + this._charCount = 0; + + /** + * @property {number} _width - Internal width var. + * @private + */ + this._width = 0; + + /** + * @property {number} _height - Internal height var. + * @private + */ + this._height = 0; + + Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas)); + + /** + * @property {object} style + * @private + */ + this.style = {}; + + this.setStyle(style || {}); + + if (text !== '') + { + this.updateText(); + } + +}; + +Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Text.prototype.constructor = Phaser.Text; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Text#preUpdate +* @protected +*/ +Phaser.Text.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override this function to handle any special update requirements. +* +* @method Phaser.Text#update +* @protected +*/ +Phaser.Text.prototype.update = function() { + +}; + +/** +* Destroy this Text object, removing it from the group it belongs to. +* +* @method Phaser.Text#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Text.prototype.destroy = function (destroyChildren) { + + this.texture.destroy(true); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. +* The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. +* The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. +* To remove a shadow already in place you can call this method with no parameters set. +* +* @method Phaser.Text#setShadow +* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +* @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. +* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +* @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set). +* @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; } + if (blur === undefined) { blur = 0; } + if (shadowStroke === undefined) { shadowStroke = true; } + if (shadowFill === undefined) { shadowFill = true; } + + this.style.shadowOffsetX = x; + this.style.shadowOffsetY = y; + this.style.shadowColor = color; + this.style.shadowBlur = blur; + this.style.shadowStroke = shadowStroke; + this.style.shadowFill = shadowFill; + this.dirty = true; + + return this; + +}; + +/** +* Set the style of the text by passing a single style object to it. +* +* @method Phaser.Text#setStyle +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +* @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setStyle = function (style, update) { + + if (update === undefined) { update = false; } + + var newStyle = Object.assign({}, style); + newStyle.font = style.font || 'bold 20pt Arial'; + newStyle.backgroundColor = style.backgroundColor || null; + newStyle.fill = style.fill || 'black'; + newStyle.align = (style.align || 'left').toLowerCase(); + newStyle.boundsAlignH = (style.boundsAlignH || 'left').toLowerCase(); + newStyle.boundsAlignV = (style.boundsAlignV || 'top').toLowerCase(); + newStyle.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136 + newStyle.strokeThickness = Number(style.strokeThickness) || 0; + newStyle.wordWrap = style.wordWrap || false; + newStyle.wordWrapWidth = style.wordWrapWidth || 100; + newStyle.maxLines = style.maxLines || 0; + newStyle.shadowOffsetX = style.shadowOffsetX || 0; + newStyle.shadowOffsetY = style.shadowOffsetY || 0; + newStyle.shadowColor = style.shadowColor || 'rgba(0,0,0,0)'; + newStyle.shadowBlur = style.shadowBlur || 0; + newStyle.tabs = style.tabs || 0; + + var components = this.fontToComponents(newStyle.font); + + if (newStyle.fontStyle) + { + components.fontStyle = newStyle.fontStyle; + } + + if (newStyle.fontVariant) + { + components.fontVariant = newStyle.fontVariant; + } + + if (newStyle.fontWeight) + { + components.fontWeight = newStyle.fontWeight; + } + + if (newStyle.fontSize) + { + if (typeof newStyle.fontSize === 'number') + { + newStyle.fontSize = newStyle.fontSize + 'px'; + } + + components.fontSize = newStyle.fontSize; + } + + this._fontComponents = components; + + newStyle.font = this.componentsToFont(this._fontComponents); + + this.style = newStyle; + this.dirty = true; + + if (update) + { + this.updateText(); + } + + return this; + +}; + +/** +* Renders text to the internal canvas. +* +* @method Phaser.Text#updateText +* @private +*/ +Phaser.Text.prototype.updateText = function () { + + this.texture.baseTexture.resolution = this._res; + + this.context.font = this.style.font; + + var outputText = this.text; + + if (this.characterLimitSize > -1 && this.characterLimitSize < outputText.length) { + outputText = this.text.substring(0, this.characterLimitSize) + this.characterLimitSuffix; + } + + if (this.style.wordWrap) + { + outputText = this.runWordWrap(this.text); + } + + // Split text into lines + var lines = outputText.split(this.splitRegExp); + + // Calculate text width + var tabs = this.style.tabs; + var lineWidths = []; + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this.style.font); + + var drawnLines = lines.length; + + if (this.style.maxLines > 0 && this.style.maxLines < lines.length) + { + drawnLines = this.style.maxLines; + } + + this._charCount = 0; + + for (var i = 0; i < drawnLines; i++) + { + if (tabs === 0) + { + // Simple layout (no tabs) + var lineWidth = this.style.strokeThickness + this.padding.x; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(lines[i]); + } + else + { + lineWidth += this.context.measureText(lines[i]).width; + } + + // Adjust for wrapped text + if (this.style.wordWrap) + { + lineWidth -= this.context.measureText(' ').width; + } + } + else + { + // Complex layout (tabs) + var line = lines[i].split(/(?:\t)/); + var lineWidth = this.padding.x + this.style.strokeThickness; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < line.length; c++) + { + var section = 0; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + section = this.measureLine(line[c]); + } + else + { + section = Math.ceil(this.context.measureText(line[c]).width); + } + + if (c > 0) + { + tab += tabs[c - 1]; + } + + lineWidth = tab + section; + } + } + else + { + for (var c = 0; c < line.length; c++) + { + // How far to the next tab? + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(line[c]); + } + else + { + lineWidth += Math.ceil(this.context.measureText(line[c]).width); + } + + var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth; + + lineWidth += diff; + } + } + } + + lineWidths[i] = Math.ceil(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); + } + + this.canvas.width = maxLineWidth * this._res; + + // Calculate text height + var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y; + var height = lineHeight * drawnLines; + var lineSpacing = this._lineSpacing; + + if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight) + { + lineSpacing = -lineHeight; + } + + // Adjust for line spacing + if (lineSpacing !== 0) + { + height += (lineSpacing > 0) ? lineSpacing * lines.length : lineSpacing * (lines.length - 1); + } + + this.canvas.height = height * this._res; + + this.context.scale(this._res, this._res); + + if (navigator.isCocoonJS) + { + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + } + + if (this.style.backgroundColor) + { + this.context.fillStyle = this.style.backgroundColor; + this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); + } + + this.context.fillStyle = this.style.fill; + this.context.font = this.style.font; + this.context.strokeStyle = this.style.stroke; + this.context.textBaseline = 'alphabetic'; + + this.context.lineWidth = this.style.strokeThickness; + this.context.lineCap = 'round'; + this.context.lineJoin = 'round'; + + var linePositionX; + var linePositionY; + + this._charCount = 0; + + // Draw text line by line + for (i = 0; i < drawnLines; i++) + { + // Split the line by + + linePositionX = this.style.strokeThickness / 2; + linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (i > 0) + { + linePositionY += (lineSpacing * i); + } + + if (this.style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (this.style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (this.autoRound) + { + linePositionX = Math.round(linePositionX); + linePositionY = Math.round(linePositionY); + } + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + this.updateLine(lines[i], linePositionX, linePositionY); + } + else + { + if (this.style.stroke && this.style.strokeThickness) + { + this.updateShadow(this.style.shadowStroke); + + if (tabs === 0) + { + this.context.strokeText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, false); + } + } + + if (this.style.fill) + { + this.updateShadow(this.style.shadowFill); + + if (tabs === 0) + { + this.context.fillText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, true); + } + } + } + } + + this.updateTexture(); + + this.dirty = false; + +}; + +/** +* Renders a line of text that contains tab characters if Text.tab > 0. +* Called automatically by updateText. +* +* @method Phaser.Text#renderTabLine +* @private +* @param {string} line - The line of text to render. +* @param {integer} x - The x position to start rendering from. +* @param {integer} y - The y position to start rendering from. +* @param {boolean} fill - If true uses fillText, if false uses strokeText. +*/ +Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) { + + var text = line.split(/(?:\t)/); + var tabs = this.style.tabs; + var snap = 0; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < text.length; c++) + { + if (c > 0) + { + tab += tabs[c - 1]; + } + + snap = x + tab; + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + } + } + else + { + for (var c = 0; c < text.length; c++) + { + var section = Math.ceil(this.context.measureText(text[c]).width); + + // How far to the next tab? + snap = this.game.math.snapToCeil(x, tabs); + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + + x = snap + section; + } + } + +}; + +/** +* Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. +* This is called automatically by Text.updateText. +* +* @method Phaser.Text#updateShadow +* @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero. +*/ +Phaser.Text.prototype.updateShadow = function (state) { + + if (state) + { + this.context.shadowOffsetX = this.style.shadowOffsetX; + this.context.shadowOffsetY = this.style.shadowOffsetY; + this.context.shadowColor = this.style.shadowColor; + this.context.shadowBlur = this.style.shadowBlur; + } + else + { + this.context.shadowOffsetX = 0; + this.context.shadowOffsetY = 0; + this.context.shadowColor = 0; + this.context.shadowBlur = 0; + } + +}; + +/** +* Measures a line of text character by character taking into the account the specified character styles. +* +* @method Phaser.Text#measureLine +* @private +* @param {string} line - The line of text to measure. +* @return {integer} length of the line. +*/ +Phaser.Text.prototype.measureLine = function (line) { + + var lineLength = 0; + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + } + + lineLength += this.context.measureText(letter).width; + + this._charCount++; + } + + return Math.ceil(lineLength); +}; + +/** +* Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable. +* +* @method Phaser.Text#updateLine +* @private +*/ +Phaser.Text.prototype.updateLine = function (line, x, y) { + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + this.context.strokeText(letter, x, y); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + this.context.fillText(letter, x, y); + } + + x += this.context.measureText(letter).width; + + this._charCount++; + } + +}; + +/** +* Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. +* +* @method Phaser.Text#clearColors +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearColors = function () { + + this.colors = []; + this.strokeColors = []; + this.dirty = true; + + return this; + +}; + +/** +* Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. +* +* @method Phaser.Text#clearFontValues +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearFontValues = function () { + + this.fontStyles = []; + this.fontWeights = []; + this.dirty = true; + + return this; + +}; + +/** +* Set specific colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* If you wish to change the stroke color see addStrokeColor instead. +* +* @method Phaser.Text#addColor +* @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addColor = function (color, position) { + + this.colors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific stroke colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* This has no effect if stroke is disabled or has a thickness of 0. +* +* If you wish to change the text fill color see addColor instead. +* +* @method Phaser.Text#addStrokeColor +* @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addStrokeColor = function (color, position) { + + this.strokeColors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font styles for certain characters within the Text. +* +* It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. +* The position value is the index of the character in the Text string to start applying this font style to. +* Once set the font style remains in use until either another font style or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. +* +* If you wish to change the text font weight see addFontWeight instead. +* +* @method Phaser.Text#addFontStyle +* @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. +* @param {number} position - The index of the character in the string to start applying this font style value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontStyle = function (style, position) { + + this.fontStyles[position] = style; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font weights for certain characters within the Text. +* +* It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. +* The position value is the index of the character in the Text string to start applying this font weight to. +* Once set the font weight remains in use until either another font weight or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. +* +* If you wish to change the text font style see addFontStyle instead. +* +* @method Phaser.Text#addFontWeight +* @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. +* @param {number} position - The index of the character in the string to start applying this font weight value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontWeight = function (weight, position) { + + this.fontWeights[position] = weight; + this.dirty = true; + + return this; + +}; + +/** +* Runs the given text through the Text.runWordWrap function and returns +* the results as an array, where each element of the array corresponds to a wrapped +* line of text. +* +* Useful if you wish to control pagination on long pieces of content. +* +* @method Phaser.Text#precalculateWordWrap +* @param {string} text - The text for which the wrapping will be calculated. +* @return {array} An array of strings with the pieces of wrapped text. +*/ +Phaser.Text.prototype.precalculateWordWrap = function (text) { + + this.texture.baseTexture.resolution = this._res; + this.context.font = this.style.font; + + var wrappedLines = this.runWordWrap(text); + + return wrappedLines.split(/(?:\r\n|\r|\n)/); + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#runWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.runWordWrap = function (text) { + + if (this.useAdvancedWrap) + { + return this.advancedWordWrap(text); + } + else + { + return this.basicWordWrap(text); + } + +}; + +/** +* Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* White space is condensed (e.g., consecutive spaces are replaced with one). +* Lines are trimmed of white space before processing. +* Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character. +* +* @method Phaser.Text#advancedWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.advancedWordWrap = function (text) { + + var context = this.context; + var wordWrapWidth = this.style.wordWrapWidth; + + var output = ''; + + // (1) condense whitespace + // (2) split into lines + var lines = text + .replace(/ +/gi, ' ') + .split(/\r?\n/gi); + + var linesCount = lines.length; + + for (var i = 0; i < linesCount; i++) + { + var line = lines[i]; + var out = ''; + + // trim whitespace + line = line.replace(/^ *|\s*$/gi, ''); + + // if entire line is less than wordWrapWidth + // append the entire line and exit early + var lineWidth = context.measureText(line).width; + + if (lineWidth < wordWrapWidth) + { + output += line + '\n'; + continue; + } + + // otherwise, calculate new lines + var currentLineWidth = wordWrapWidth; + + // split into words + var words = line.split(' '); + + for (var j = 0; j < words.length; j++) + { + var word = words[j]; + var wordWithSpace = word + ' '; + var wordWidth = context.measureText(wordWithSpace).width; + + if (wordWidth > currentLineWidth) + { + // break word + if (j === 0) + { + // shave off letters from word until it's small enough + var newWord = wordWithSpace; + + while (newWord.length) + { + newWord = newWord.slice(0, -1); + wordWidth = context.measureText(newWord).width; + + if (wordWidth <= currentLineWidth) + { + break; + } + } + + // if wordWrapWidth is too small for even a single + // letter, shame user failure with a fatal error + if (!newWord.length) + { + throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); + } + + // replace current word in array with remainder + var secondPart = word.substr(newWord.length); + + words[j] = secondPart; + + // append first piece to output + out += newWord; + } + + // if existing word length is 0, don't include it + var offset = (words[j].length) ? j : j + 1; + + // collapse rest of sentence + var remainder = words.slice(offset).join(' ') + // remove any trailing white space + .replace(/[ \n]*$/gi, ''); + + // prepend remainder to next line + lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); + linesCount = lines.length; + + break; // processing on this line + + // append word with space to output + } + else + { + out += wordWithSpace; + currentLineWidth -= wordWidth; + } + } + + // append processed line to output + output += out.replace(/[ \n]*$/gi, '') + '\n'; + } + + // trim the end of the string + output = output.replace(/[\s|\n]*$/gi, ''); + + return output; + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#basicWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.basicWordWrap = function (text) { + + var result = ''; + var lines = text.split('\n'); + + for (var i = 0; i < lines.length; i++) + { + var spaceLeft = this.style.wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) + { + var wordWidth = this.context.measureText(words[j]).width; + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is greater than the word wrap width. + if (j > 0) + { + result += '\n'; + } + result += words[j] + ' '; + spaceLeft = this.style.wordWrapWidth - wordWidth; + } + else + { + spaceLeft -= wordWidthWithSpace; + result += words[j] + ' '; + } + } + + if (i < lines.length-1) + { + result += '\n'; + } + } + + return result; + +}; + +/** +* Updates the internal `style.font` if it now differs according to generation from components. +* +* @method Phaser.Text#updateFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.updateFont = function (components) { + + var font = this.componentsToFont(components); + + if (this.style.font !== font) + { + this.style.font = font; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + +}; + +/** +* Converting a short CSS-font string into the relevant components. +* +* @method Phaser.Text#fontToComponents +* @private +* @param {string} font - a CSS font string +*/ +Phaser.Text.prototype.fontToComponents = function (font) { + + // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand: + // style - normal | italic | oblique | inherit + // variant - normal | small-caps | inherit + // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit + // size - xx-small | x-small | small | medium | large | x-large | xx-large, + // larger | smaller + // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %) + // font-family - rest (but identifiers or quoted with comma separation) + var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/); + + if (m) + { + var family = m[5].trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(family) && !/['",]/.exec(family)) + { + family = "'" + family + "'"; + } + + return { + font: font, + fontStyle: m[1] || 'normal', + fontVariant: m[2] || 'normal', + fontWeight: m[3] || 'normal', + fontSize: m[4] || 'medium', + fontFamily: family + }; + } + else + { + console.warn("Phaser.Text - unparsable CSS font: " + font); + + return { + font: font + }; + } + +}; + +/** +* Converts individual font components (see `fontToComponents`) to a short CSS font string. +* +* @method Phaser.Text#componentsToFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.componentsToFont = function (components) { + + var parts = []; + var v; + + v = components.fontStyle; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontVariant; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontWeight; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontSize; + if (v && v !== 'medium') { parts.push(v); } + + v = components.fontFamily; + if (v) { parts.push(v); } + + if (!parts.length) + { + // Fallback to whatever value the 'font' was + parts.push(components.font); + } + + return parts.join(" "); + +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* Use the optional `immediate` argument if you need the Text display to update immediately. +* +* If not it will re-create the texture of this Text object during the next time the render +* loop is called. +* +* @method Phaser.Text#setText +* @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present. +* @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setText = function (text, immediate) { + + if (immediate === undefined) { immediate = false; } + + this.text = text.toString() || ''; + + if (immediate) + { + this.updateText(); + } + else + { + this.dirty = true; + } + + return this; + +}; + +/** + * Converts the given array into a tab delimited string and then updates this Text object. + * This is mostly used when you want to display external data using tab stops. + * + * The array can be either single or multi dimensional depending on the result you need: + * + * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`. + * + * Where as: + * + * `[ + * [ 'a', 'b', 'c' ], + * [ 'd', 'e', 'f'] + * ]` + * + * would convert in to: `"a\tb\tc\nd\te\tf"` + * + * @method Phaser.Text#parseList + * @param {array} list - The array of data to convert into a string. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.parseList = function (list) { + + if (!Array.isArray(list)) + { + return this; + } + else + { + var s = ""; + + for (var i = 0; i < list.length; i++) + { + if (Array.isArray(list[i])) + { + s += list[i].join("\t"); + + if (i < list.length - 1) + { + s += "\n"; + } + } + else + { + s += list[i]; + + if (i < list.length - 1) + { + s += "\t"; + } + } + } + } + + this.text = s; + this.dirty = true; + + return this; + +}; + +/** + * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned, + * regardless of the number of lines in the text, the font size or any other attribute. + * + * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly + * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment. + * + * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to + * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of + * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center + * of the text bounds. + * + * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions + * may vary based on font (say for multi-lingual games). + * + * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width. + * + * Call this method with no arguments given to reset an existing textBounds. + * + * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts + * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot` + * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then + * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot. + * + * @method Phaser.Text#setTextBounds + * @param {number} [x] - The x coordinate of the Text Bounds region. + * @param {number} [y] - The y coordinate of the Text Bounds region. + * @param {number} [width] - The width of the Text Bounds region. + * @param {number} [height] - The height of the Text Bounds region. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.setTextBounds = function (x, y, width, height) { + + if (x === undefined) + { + this.textBounds = null; + } + else + { + if (!this.textBounds) + { + this.textBounds = new Phaser.Rectangle(x, y, width, height); + } + else + { + this.textBounds.setTo(x, y, width, height); + } + + if (this.style.wordWrapWidth > width) + { + this.style.wordWrapWidth = width; + } + } + + this.updateTexture(); + + return this; + +}; + +/** + * Updates the texture based on the canvas dimensions. + * + * @method Phaser.Text#updateTexture + * @private + */ +Phaser.Text.prototype.updateTexture = function () { + + var base = this.texture.baseTexture; + var crop = this.texture.crop; + var frame = this.texture.frame; + + var w = this.canvas.width; + var h = this.canvas.height; + + base.width = w; + base.height = h; + + crop.width = w; + crop.height = h; + + frame.width = w; + frame.height = h; + + this.texture.width = w; + this.texture.height = h; + + this._width = w; + this._height = h; + + if (this.textBounds) + { + var x = this.textBounds.x; + var y = this.textBounds.y; + + // Align the canvas based on the bounds + if (this.style.boundsAlignH === 'right') + { + x += this.textBounds.width - this.canvas.width / this.resolution; + } + else if (this.style.boundsAlignH === 'center') + { + x += this.textBounds.halfWidth - (this.canvas.width / this.resolution / 2); + } + + if (this.style.boundsAlignV === 'bottom') + { + y += this.textBounds.height - this.canvas.height / this.resolution; + } + else if (this.style.boundsAlignV === 'middle') + { + y += this.textBounds.halfHeight - (this.canvas.height / this.resolution / 2); + } + + this.pivot.x = -x; + this.pivot.y = -y; + } + + // Can't render something with a zero sized dimension + this.renderable = (w !== 0 && h !== 0); + + this.texture.requiresReTint = true; + + this.texture.baseTexture.dirty(); + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Text#_renderWebGL +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderWebGL = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Renders the object using the Canvas renderer. +* +* @method Phaser.Text#_renderCanvas +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderCanvas = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Calculates the ascent, descent and fontSize of a given font style. +* +* @method Phaser.Text#determineFontProperties +* @private +* @param {object} fontStyle +*/ +Phaser.Text.prototype.determineFontProperties = function (fontStyle) { + + var properties = Phaser.Text.fontPropertiesCache[fontStyle]; + + if (!properties) + { + properties = {}; + + var canvas = Phaser.Text.fontPropertiesCanvas; + var context = Phaser.Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('|MÉq').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + if (!context.getImageData(0, 0, width, height)) + { + properties.ascent = baseline; + properties.descent = baseline + 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + } + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i, j; + + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + properties.descent = i - baseline; + //TODO might need a tweak. kind of a temp fix! + properties.descent += 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; + +}; + +/** +* Returns the bounds of the Text as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Text#getBounds +* @param {Phaser.Matrix} matrix - The transformation matrix of the Text. +* @return {Phaser.Rectangle} The framing rectangle +*/ +Phaser.Text.prototype.getBounds = function (matrix) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return PIXI.Sprite.prototype.getBounds.call(this, matrix); + +}; + +/** +* Sets the character limit of the text, with a suffix. +* If the text is longer than this limit, it is truncated and the suffix is appended. +* +* @method Phaser.Text#setCharacterLimit +* @param {number} [characterLimit] - The x coordinate of the Text Bounds region. +* @param {string} [suffix] - The suffix to append to the truncated text. +*/ +Phaser.Text.prototype.setCharacterLimit = function (characterLimit, suffix) { + + this.characterLimitSuffix = (suffix === undefined) ? '' : suffix; + this.characterLimitSize = characterLimit; + + this.updateText(); +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* @name Phaser.Text#text +* @property {string} text +*/ +Object.defineProperty(Phaser.Text.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* Change the font used. +* +* This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except +* that unlike using `setStyle` this will not change any current font fill/color settings. +* +* The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. +* +* @name Phaser.Text#cssFont +* @property {string} cssFont +*/ +Object.defineProperty(Phaser.Text.prototype, 'cssFont', { + + get: function() { + return this.componentsToFont(this._fontComponents); + }, + + set: function (value) + { + value = value || 'bold 20pt Arial'; + this._fontComponents = this.fontToComponents(value); + this.updateFont(this._fontComponents); + } + +}); + +/** +* Change the font family that the text will be rendered in, such as 'Arial'. +* +* Multiple CSS font families and generic fallbacks can be specified as long as +* {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed. +* +* To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`. +* +* @name Phaser.Text#font +* @property {string} font +*/ +Object.defineProperty(Phaser.Text.prototype, 'font', { + + get: function() { + return this._fontComponents.fontFamily; + }, + + set: function(value) { + + value = value || 'Arial'; + value = value.trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value)) + { + value = "'" + value + "'"; + } + + this._fontComponents.fontFamily = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The size of the font. +* +* If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing +* the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). +* +* @name Phaser.Text#fontSize +* @property {number|string} fontSize +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontSize', { + + get: function() { + + var size = this._fontComponents.fontSize; + + if (size && /(?:^0$|px$)/.exec(size)) + { + return parseInt(size, 10); + } + else + { + return size; + } + + }, + + set: function(value) { + + value = value || '0'; + + if (typeof value === 'number') + { + value = value + 'px'; + } + + this._fontComponents.fontSize = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}. +* @name Phaser.Text#fontWeight +* @property {string} fontWeight +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontWeight', { + + get: function() { + return this._fontComponents.fontWeight || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontWeight = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The style of the font: 'normal', 'italic', 'oblique' +* @name Phaser.Text#fontStyle +* @property {string} fontStyle +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontStyle', { + + get: function() { + return this._fontComponents.fontStyle || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontStyle = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The variant the font: 'normal', 'small-caps' +* @name Phaser.Text#fontVariant +* @property {string} fontVariant +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontVariant', { + + get: function() { + return this._fontComponents.fontVariant || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontVariant = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* @name Phaser.Text#fill +* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'fill', { + + get: function() { + return this.style.fill; + }, + + set: function(value) { + + if (value !== this.style.fill) + { + this.style.fill = value; + this.dirty = true; + } + + } + +}); + +/** +* Controls the horizontal alignment for multiline text. +* Can be: 'left', 'center' or 'right'. +* Does not affect single lines of text. For that please see `setTextBounds`. +* @name Phaser.Text#align +* @property {string} align +*/ +Object.defineProperty(Phaser.Text.prototype, 'align', { + + get: function() { + return this.style.align; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.align) + { + this.style.align = value; + this.dirty = true; + } + + } + +}); + +/** +* The resolution of the canvas the text is rendered to. +* This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. +* @name Phaser.Text#resolution +* @property {integer} resolution +*/ +Object.defineProperty(Phaser.Text.prototype, 'resolution', { + + get: function() { + return this._res; + }, + + set: function(value) { + + if (value !== this._res) + { + this._res = value; + this.dirty = true; + } + + } + +}); + +/** +* The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. +* Can be an integer or an array of varying tab sizes, one tab per element. +* For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. +* If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. +* +* @name Phaser.Text#tabs +* @property {integer|array} tabs +*/ +Object.defineProperty(Phaser.Text.prototype, 'tabs', { + + get: function() { + return this.style.tabs; + }, + + set: function(value) { + + if (value !== this.style.tabs) + { + this.style.tabs = value; + this.dirty = true; + } + + } + +}); + +/** +* Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @name Phaser.Text#boundsAlignH +* @property {string} boundsAlignH +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', { + + get: function() { + return this.style.boundsAlignH; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignH) + { + this.style.boundsAlignH = value; + this.dirty = true; + } + + } + +}); + +/** +* Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @name Phaser.Text#boundsAlignV +* @property {string} boundsAlignV +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', { + + get: function() { + return this.style.boundsAlignV; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignV) + { + this.style.boundsAlignV = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#stroke +* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'stroke', { + + get: function() { + return this.style.stroke; + }, + + set: function(value) { + + if (value !== this.style.stroke) + { + this.style.stroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#strokeThickness +* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke) +*/ +Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', { + + get: function() { + return this.style.strokeThickness; + }, + + set: function(value) { + + if (value !== this.style.strokeThickness) + { + this.style.strokeThickness = Number(value); + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrap +* @property {boolean} wordWrap - Indicates if word wrap should be used. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrap', { + + get: function() { + return this.style.wordWrap; + }, + + set: function(value) { + + if (value !== this.style.wordWrap) + { + this.style.wordWrap = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrapWidth +* @property {number} wordWrapWidth - The width at which text will wrap. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', { + + get: function() { + return this.style.wordWrapWidth; + }, + + set: function(value) { + + if (value !== this.style.wordWrapWidth) + { + this.style.wordWrapWidth = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#lineSpacing +* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. +*/ +Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { + + get: function() { + return this._lineSpacing; + }, + + set: function(value) { + + if (value !== this._lineSpacing) + { + this._lineSpacing = parseFloat(value); + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetX +* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', { + + get: function() { + return this.style.shadowOffsetX; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetX) + { + this.style.shadowOffsetX = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetY +* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', { + + get: function() { + return this.style.shadowOffsetY; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetY) + { + this.style.shadowOffsetY = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowColor +* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowColor', { + + get: function() { + return this.style.shadowColor; + }, + + set: function(value) { + + if (value !== this.style.shadowColor) + { + this.style.shadowColor = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowBlur +* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', { + + get: function() { + return this.style.shadowBlur; + }, + + set: function(value) { + + if (value !== this.style.shadowBlur) + { + this.style.shadowBlur = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowStroke +* @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', { + + get: function() { + return this.style.shadowStroke; + }, + + set: function(value) { + + if (value !== this.style.shadowStroke) + { + this.style.shadowStroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowFill +* @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowFill', { + + get: function() { + return this.style.shadowFill; + }, + + set: function(value) { + + if (value !== this.style.shadowFill) + { + this.style.shadowFill = value; + this.dirty = true; + } + + } + +}); + +/** +* The width of the Text object in pixels. This is width of the Texture frame / the Text.resolution. +* @name Phaser.Text#width +* @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'width', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.x * (this.texture.frame.width / this.resolution); + }, + + set: function(value) { + + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** +* The height of the Text object in pixels. This is height of the Texture frame / the Text.resolution. +* @name Phaser.Text#height +* @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'height', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.y * (this.texture.frame.height / this.resolution); + }, + + set: function(value) { + + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +Phaser.Text.fontPropertiesCache = {}; + +Phaser.Text.fontPropertiesCanvas = document.createElement('canvas'); +Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d'); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. +* It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to +* match the font structure. +* +* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability +* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by +* processing the font texture in an image editor, applying fills and any other effects required. +* +* To create multi-line text insert \r, \n or \r\n escape codes into the text string. +* +* If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly +* updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. +* +* To create a BitmapText data files you can use: +* +* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ +* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner +* Littera (Web-based, free): http://kvazars.com/littera/ +* +* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of +* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson +* +* If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. +* +* @class Phaser.BitmapText +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - X coordinate to display the BitmapText object at. +* @param {number} y - Y coordinate to display the BitmapText object at. +* @param {string} font - The key of the BitmapText as stored in Phaser.Cache. +* @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. +* @param {number} [size=32] - The size the font will be rendered at in pixels. +* @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. +*/ +Phaser.BitmapText = function (game, x, y, font, text, size, align) { + + x = x || 0; + y = y || 0; + font = font || ''; + text = text || ''; + size = size || 32; + align = align || 'left'; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.BITMAPTEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textWidth = 0; + + /** + * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textHeight = 0; + + /** + * @property {Phaser.Point} anchor - The anchor value of this BitmapText. + */ + this.anchor = new Phaser.Point(); + + /** + * @property {Phaser.Point} _prevAnchor - The previous anchor value. + * @private + */ + this._prevAnchor = new Phaser.Point(); + + /** + * @property {array} _glyphs - Private tracker for the letter sprite pool. + * @private + */ + this._glyphs = []; + + /** + * @property {number} _maxWidth - Internal cache var. + * @private + */ + this._maxWidth = 0; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text.toString() || ''; + + /** + * @property {string} _data - Internal cache var. + * @private + */ + this._data = game.cache.getBitmapFont(font); + + /** + * @property {string} _font - Internal cache var. + * @private + */ + this._font = font; + + /** + * @property {number} _fontSize - Internal cache var. + * @private + */ + this._fontSize = size; + + /** + * @property {string} _align - Internal cache var. + * @private + */ + this._align = align; + + /** + * @property {number} _tint - Internal cache var. + * @private + */ + this._tint = 0xFFFFFF; + + this.updateText(); + + /** + * @property {boolean} dirty - The dirty state of this object. + */ + this.dirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.BitmapText.prototype.constructor = Phaser.BitmapText; + +Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.BitmapText +* @return {boolean} True if the BitmapText was rendered, otherwise false. +*/ +Phaser.BitmapText.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.preUpdate. +* @method Phaser.BitmapText.prototype.postUpdate +*/ +Phaser.BitmapText.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this.body && this.body.type === Phaser.Physics.ARCADE) + { + if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight)) + { + this.body.setSize(this.textWidth, this.textHeight); + } + } + +}; + +/** +* The text to be displayed by this BitmapText object. +* +* It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. +* +* @method Phaser.BitmapText.prototype.setText +* @param {string} text - The text to be displayed by this BitmapText object. +*/ +Phaser.BitmapText.prototype.setText = function (text) { + + this.text = text; + +}; + +/** +* Given the input text this will scan the characters until either a newline is encountered, +* or the line exceeds maxWidth, taking into account kerning, character widths and scaling. +* +* @method Phaser.BitmapText.prototype.scanLine +* @private +* @param {object} data - A reference to the font object in the Phaser.Cache. +* @param {float} scale - The scale of the font in relation to the texture. +* @param {string} text - The text to parse. +* @return {object} An object containing the parsed characters, total pixel width and x offsets. +*/ +Phaser.BitmapText.prototype.scanLine = function (data, scale, text) { + + var x = 0; + var w = 0; + var lastSpace = -1; + var wrappedWidth = 0; + var prevCharCode = null; + var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null; + var chars = []; + + // Let's scan the text and work out if any of the lines are > maxWidth + for (var i = 0; i < text.length; i++) + { + var end = (i === text.length - 1) ? true : false; + + if (/(?:\r\n|\r|\n)/.test(text.charAt(i))) + { + return { width: w, text: text.substr(0, i), end: end, chars: chars }; + } + else + { + var charCode = text.charCodeAt(i); + var charData = data.chars[charCode]; + + var c = 0; + + // If the character data isn't found in the data array + // then we replace it with a blank space + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + // Adjust for kerning from previous character to this one + var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0; + + // Record the last space in the string and the current width + if (/(\s)/.test(text.charAt(i))) + { + lastSpace = i; + wrappedWidth = w; + } + + // What will the line width be if we add this character to it? + c = (kerning + charData.texture.width + charData.xOffset) * scale; + + // Do we need to line-wrap? + if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1) + { + // The last space was at "lastSpace" which was "i - lastSpace" characters ago + return { width: wrappedWidth || w, text: text.substr(0, i - (i - lastSpace)), end: false, chars: chars }; + } + else + { + w += (charData.xAdvance + kerning) * scale; + + chars.push(x + (charData.xOffset + kerning) * scale); + + x += (charData.xAdvance + kerning) * scale; + + prevCharCode = charCode; + } + } + } + + return { width: w, text: text, end: end, chars: chars }; + +}; + +/** +* Given a text string this will scan each character in the string to ensure it exists +* in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. +* +* If no font data has been loaded at all this returns an empty string, as nothing can be rendered. +* +* @method Phaser.BitmapText.prototype.cleanText +* @param {string} text - The text to parse. +* @param {string} [replace=''] - The replacement string for any missing characters. +* @return {string} The cleaned text string. +*/ +Phaser.BitmapText.prototype.cleanText = function (text, replace) { + + if (replace === undefined) + { + replace = ''; + } + + var data = this._data.font; + + if (!data) + { + return ''; + } + + var re = /\r\n|\n\r|\n|\r/g; + var lines = text.replace(re, "\n").split("\n"); + + for (var i = 0; i < lines.length; i++) + { + var output = ''; + var line = lines[i]; + + for (var c = 0; c < line.length; c++) + { + if (data.chars[line.charCodeAt(c)]) + { + output = output.concat(line[c]); + } + else + { + output = output.concat(replace); + } + } + + lines[i] = output; + } + + return lines.join("\n"); + +}; + +/** +* Renders text and updates it when needed. +* +* @method Phaser.BitmapText.prototype.updateText +* @private +*/ +Phaser.BitmapText.prototype.updateText = function () { + + var data = this._data.font; + + if (!data) + { + return; + } + + var text = this.text; + var scale = this._fontSize / data.size; + var lines = []; + + var y = 0; + + this.textWidth = 0; + + do + { + var line = this.scanLine(data, scale, text); + + line.y = y; + + lines.push(line); + + if (line.width > this.textWidth) + { + this.textWidth = line.width; + } + + y += (data.lineHeight * scale); + + text = text.substr(line.text.length + 1); + + } while (line.end === false); + + this.textHeight = y; + + var t = 0; + var align = 0; + var ax = this.textWidth * this.anchor.x; + var ay = this.textHeight * this.anchor.y; + + for (var i = 0; i < lines.length; i++) + { + var line = lines[i]; + + if (this._align === 'right') + { + align = this.textWidth - line.width; + } + else if (this._align === 'center') + { + align = (this.textWidth - line.width) / 2; + } + + for (var c = 0; c < line.text.length; c++) + { + var charCode = line.text.charCodeAt(c); + var charData = data.chars[charCode]; + + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + var g = this._glyphs[t]; + + if (g) + { + // Sprite already exists in the glyphs pool, so we'll reuse it for this letter + g.texture = charData.texture; + } + else + { + // We need a new sprite as the pool is empty or exhausted + g = new PIXI.Sprite(charData.texture); + g.name = line.text[c]; + this._glyphs.push(g); + } + + g.position.x = (line.chars[c] + align) - ax; + g.position.y = (line.y + (charData.yOffset * scale)) - ay; + + g.scale.set(scale); + g.tint = this.tint; + g.texture.requiresReTint = true; + g.cachedTint = 0xFFFFFF; + + if (!g.parent) + { + this.addChild(g); + } + + t++; + } + } + + // Remove unnecessary children + // This moves them from the display list (children array) but retains them in the _glyphs pool + for (i = t; i < this._glyphs.length; i++) + { + this.removeChild(this._glyphs[i]); + } + +}; + +/** +* If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of +* Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they +* still take up memory while sat in the glyphs pool waiting to be re-used in the future. +* +* If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool +* by calling this method. +* +* Calling this doesn't prevent you from increasing the length of the text again in the future. +* +* @method Phaser.BitmapText.prototype.purgeGlyphs +* @return {integer} The amount of glyphs removed from the pool. +*/ +Phaser.BitmapText.prototype.purgeGlyphs = function () { + + var len = this._glyphs.length; + var kept = []; + + for (var i = 0; i < this._glyphs.length; i++) + { + if (this._glyphs[i].parent !== this) + { + this._glyphs[i].destroy(); + } + else + { + kept.push(this._glyphs[i]); + } + } + + this._glyphs = []; + this._glyphs = kept; + + this.updateText(); + + return len - kept.length; + +}; + +/** +* Updates the transform of this object. +* +* @method Phaser.BitmapText.prototype.updateTransform +* @private +*/ +Phaser.BitmapText.prototype.updateTransform = function () { + + if (this.dirty || !this.anchor.equals(this._prevAnchor)) + { + this.updateText(); + this.dirty = false; + this._prevAnchor.copyFrom(this.anchor); + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/** +* @name Phaser.BitmapText#align +* @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'align', { + + get: function() { + return this._align; + }, + + set: function(value) { + + if (value !== this._align && (value === 'left' || value === 'center' || value === 'right')) + { + this._align = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#tint +* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'tint', { + + get: function() { + return this._tint; + }, + + set: function(value) { + + if (value !== this._tint) + { + this._tint = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#font +* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'font', { + + get: function() { + return this._font; + }, + + set: function(value) { + + if (value !== this._font) + { + this._font = value.trim(); + this._data = this.game.cache.getBitmapFont(this._font); + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#fontSize +* @property {number} fontSize - The size of the font in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { + + get: function() { + return this._fontSize; + }, + + set: function(value) { + + value = parseInt(value, 10); + + if (value !== this._fontSize && value > 0) + { + this._fontSize = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#text +* @property {string} text - The text to be displayed by this BitmapText object. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.updateText(); + } + + } + +}); + +/** +* The maximum display width of this BitmapText in pixels. +* +* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped +* based on the last whitespace character found in the line. +* +* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. +* +* Disable maxWidth by setting the value to 0. +* +* @name Phaser.BitmapText#maxWidth +* @property {number} maxWidth - The maximum width of this BitmapText in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', { + + get: function() { + + return this._maxWidth; + + }, + + set: function(value) { + + if (value !== this._maxWidth) + { + this._maxWidth = value; + this.updateText(); + } + + } + +}); + +/** +* Enable or disable texture smoothing for this BitmapText. +* +* The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. +* +* Smoothing is enabled by default. +* +* @name Phaser.BitmapText#smoothed +* @property {boolean} smoothed +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', { + + get: function() { + + return !this._data.base.scaleMode; + + }, + + set: function(value) { + + if (value) + { + this._data.base.scaleMode = 0; + } + else + { + this._data.base.scaleMode = 1; + } + this._data.base.dirty(); + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont +* is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. +* +* @class Phaser.RetroFont +* @extends Phaser.RenderTexture +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {string} key - The font set graphic set as stored in the Game.Cache. +* @param {number} characterWidth - The width of each character in the font set. +* @param {number} characterHeight - The height of each character in the font set. +* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. +* @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. +* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. +* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { + + if (!game.cache.checkImageKey(key)) + { + return false; + } + + if (charsPerRow === undefined || charsPerRow === null) + { + charsPerRow = game.cache.getImage(key).width / characterWidth; + } + + /** + * @property {number} characterWidth - The width of each character in the font set. + */ + this.characterWidth = characterWidth; + + /** + * @property {number} characterHeight - The height of each character in the font set. + */ + this.characterHeight = characterHeight; + + /** + * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here. + */ + this.characterSpacingX = xSpacing || 0; + + /** + * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here. + */ + this.characterSpacingY = ySpacing || 0; + + /** + * @property {number} characterPerRow - The number of characters per row in the font set. + */ + this.characterPerRow = charsPerRow; + + /** + * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @readonly + */ + this.offsetX = xOffset || 0; + + /** + * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @readonly + */ + this.offsetY = yOffset || 0; + + /** + * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + */ + this.align = "left"; + + /** + * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) + * @default + */ + this.multiLine = false; + + /** + * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. + * @default + */ + this.autoUpperCase = true; + + /** + * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels. + * @default + */ + this.customSpacingX = 0; + + /** + * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels. + * @default + */ + this.customSpacingY = 0; + + /** + * If you need this RetroFont image to have a fixed width you can set the width in this value. + * If text is wider than the width specified it will be cropped off. + * @property {number} fixedWidth + */ + this.fixedWidth = 0; + + /** + * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font. + */ + this.fontSet = game.cache.getImage(key); + + /** + * @property {string} _text - The text of the font image. + * @private + */ + this._text = ''; + + /** + * @property {array} grabData - An array of rects for faster character pasting. + * @private + */ + this.grabData = []; + + /** + * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font. + */ + this.frameData = new Phaser.FrameData(); + + // Now generate our rects for faster copying later on + var currentX = this.offsetX; + var currentY = this.offsetY; + var r = 0; + + for (var c = 0; c < chars.length; c++) + { + var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight)); + + this.grabData[chars.charCodeAt(c)] = frame.index; + + r++; + + if (r === this.characterPerRow) + { + r = 0; + currentX = this.offsetX; + currentY += this.characterHeight + this.characterSpacingY; + } + else + { + currentX += this.characterWidth + this.characterSpacingX; + } + } + + game.cache.updateFrameData(key, this.frameData); + + /** + * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font. + * @readonly + */ + this.stamp = new Phaser.Image(game, 0, 0, key, 0); + + Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST); + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RETROFONT; + +}; + +Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype); +Phaser.RetroFont.prototype.constructor = Phaser.RetroFont; + +/** +* Align each line of multi-line text to the left. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_LEFT = "left"; + +/** +* Align each line of multi-line text to the right. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_RIGHT = "right"; + +/** +* Align each line of multi-line text in the center. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_CENTER = "center"; + +/** +* Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + +/** +* Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "; + +/** +* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789"; + +/** +* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789"; + +/** +* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' "; + +/** +* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39"; + +/** +* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!"; + +/** +* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"; + +/** +* If you need this RetroFont to have a fixed width and custom alignment you can set the width here. +* If text is wider than the width specified it will be cropped off. +* +* @method Phaser.RetroFont#setFixedWidth +* @memberof Phaser.RetroFont +* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. +* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +*/ +Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) { + + if (lineAlignment === undefined) { lineAlignment = 'left'; } + + this.fixedWidth = width; + this.align = lineAlignment; + +}; + +/** +* A helper function that quickly sets lots of variables at once, and then updates the text. +* +* @method Phaser.RetroFont#setText +* @memberof Phaser.RetroFont +* @param {string} content - The text of this sprite. +* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. +* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels. +* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels. +* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. +*/ +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; + } + +}; + +/** +* Updates the texture with the new text. +* +* @method Phaser.RetroFont#buildRetroFontText +* @memberof Phaser.RetroFont +*/ +Phaser.RetroFont.prototype.buildRetroFontText = function () { + + var cx = 0; + var cy = 0; + + // Clears the textureBuffer + 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); + } + + // Loop through each line of text + for (var i = 0; i < lines.length; i++) + { + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + // This line of text is held in lines[i] - need to work out the alignment + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(lines[i], cx, cy, this.customSpacingX); + + cy += this.characterHeight + this.customSpacingY; + } + } + else + { + if (this.fixedWidth > 0) + { + this.resize(this.fixedWidth, this.characterHeight, true); + } + else + { + this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true); + } + + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(this._text, cx, 0, this.customSpacingX); + } + + this.requiresReTint = true; + +}; + +/** +* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. +* Used by getLine and getMultiLine +* +* @method Phaser.RetroFont#pasteLine +* @memberof Phaser.RetroFont +* @param {string} line - The single line of text to paste. +* @param {number} x - The x coordinate. +* @param {number} y - The y coordinate. +* @param {number} customSpacingX - Custom X spacing. +*/ +Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) { + + for (var c = 0; c < line.length; c++) + { + // If it's a space then there is no point copying, so leave a blank space + if (line.charAt(c) === " ") + { + x += this.characterWidth + customSpacingX; + } + else + { + // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it + if (this.grabData[line.charCodeAt(c)] >= 0) + { + this.stamp.frame = this.grabData[line.charCodeAt(c)]; + this.renderXY(this.stamp, x, y, false); + + x += this.characterWidth + customSpacingX; + + if (x > this.width) + { + break; + } + } + } + } +}; + +/** +* Works out the longest line of text in _text and returns its length +* +* @method Phaser.RetroFont#getLongestLine +* @memberof Phaser.RetroFont +* @return {number} The length of the longest line of text. +*/ +Phaser.RetroFont.prototype.getLongestLine = function () { + + var longestLine = 0; + + if (this._text.length > 0) + { + var lines = this._text.split("\n"); + + for (var i = 0; i < lines.length; i++) + { + if (lines[i].length > longestLine) + { + longestLine = lines[i].length; + } + } + } + + return longestLine; +}; + +/** +* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set. +* +* @method Phaser.RetroFont#removeUnsupportedCharacters +* @memberof Phaser.RetroFont +* @protected +* @param {boolean} [stripCR=true] - Should it strip carriage returns as well? +* @return {string} A clean version of the string. +*/ +Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) { + + var newString = ""; + + for (var c = 0; c < this._text.length; c++) + { + var aChar = this._text[c]; + var code = aChar.charCodeAt(0); + + if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n")) + { + newString = newString.concat(aChar); + } + } + + return newString; + +}; + +/** +* Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. +* Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. +* So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. +* +* @method Phaser.RetroFont#updateOffset +* @memberof Phaser.RetroFont +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont.prototype.updateOffset = function (x, y) { + + if (this.offsetX === x && this.offsetY === y) + { + return; + } + + var diffX = x - this.offsetX; + var diffY = y - this.offsetY; + + var frames = this.game.cache.getFrameData(this.stamp.key).getFrames(); + var i = frames.length; + + while (i--) + { + frames[i].x += diffX; + frames[i].y += diffY; + } + + this.buildRetroFontText(); + +}; + +/** +* @name Phaser.RetroFont#text +* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. +*/ +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(); + } + + } + +}); + +/** +* @name Phaser.RetroFont#smoothed +* @property {boolean} smoothed - Sets if the stamp is smoothed or not. +*/ +Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", { + + get: function () { + + return this.stamp.smoothed; + + }, + + set: function (value) { + + this.stamp.smoothed = value; + this.buildRetroFontText(); + + } + +}); + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @author Rovanion Luckey +* @copyright 2016 Photon Storm Ltd, Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Rope is a Sprite that has a repeating texture. +* +* The texture will automatically wrap on the edges as it moves. +* +* Please note that Ropes cannot have an input handler. +* +* @class Phaser.Rope +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Rope at. +* @param {number} y - The y coordinate (in world space) to position the Rope at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {Array} points - An array of {Phaser.Point}. +*/ +Phaser.Rope = function (game, x, y, key, frame, points) { + + this.points = points || []; + this._hasUpdateAnimation = false; + this._updateAnimationCallback = null; + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROPE; + + PIXI.DisplayObjectContainer.call(this); + + this.texture = Phaser.Cache.DEFAULT; + + // set up the main bits.. + this.uvs = new Float32Array([0, 1, + 1, 1, + 1, 0, + 0, 1]); + + this.vertices = new Float32Array([0, 0, + 100, 0, + 100, 100, + 0, 100]); + + this.colors = new Float32Array([1, 1, 1, 1]); + + this.indices = new Uint16Array([0, 1, 2, 3]); + + if (points) + { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + /** + * Whether the strip is dirty or not + * + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. + * + * @property canvasPadding + * @type Number + */ + this.canvasPadding = 0; + + this.drawMode = Phaser.Rope.TRIANGLE_STRIP; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + + this.refresh(); + +}; + +Phaser.Rope.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Rope.prototype.constructor = Phaser.Rope; + +Phaser.Component.Core.install.call(Phaser.Rope.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +Phaser.Rope.TRIANGLE_STRIP = 0; +Phaser.Rope.TRIANGLES = 1; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Rope#preUpdate +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override and use this function in your own custom objects to handle any update requirements you may have. +* +* @method Phaser.Rope#update +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.update = function() { + + if (this._hasUpdateAnimation) + { + this.updateAnimation.call(this); + } + +}; + +/** +* Resets the Rope. This places the Rope at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the Rope has a physics body that too is reset. +* +* @method Phaser.Rope#reset +* @memberof Phaser.Rope +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.Rope} This instance. +*/ +Phaser.Rope.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + return this; + +}; + +/* +* Refreshes the rope texture and UV coordinates. +* +* @method Phaser.Rope#refresh +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.refresh = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + this.count -= 0.2; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + var index; + var amount; + + for (var i = 1; i < total; i++) + { + index = i * 4; + + // time to do some smart drawing! + amount = i / (total - 1); + + if (i % 2) + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + else + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + +}; + +/* +* Updates the Ropes transform ready for rendering. +* +* @method Phaser.Rope#updateTransform +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.updateTransform = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var lastPoint = points[0]; + var nextPoint; + var perp = { x:0, y:0 }; + + this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + var point; + var index; + var ratio; + var perpLength; + var num; + + for (var i = 0; i < total; i++) + { + point = points[i]; + index = i * 4; + + if(i < points.length - 1) + { + nextPoint = points[i + 1]; + } + else + { + nextPoint = point; + } + + perp.y = -(nextPoint.x - lastPoint.x); + perp.x = nextPoint.y - lastPoint.y; + + ratio = (1 - (i / (total - 1))) * 10; + + if (ratio > 1) + { + ratio = 1; + } + + perpLength = Math.sqrt((perp.x * perp.x) + (perp.y * perp.y)); + num = this.texture.height / 2; + perp.x /= perpLength; + perp.y /= perpLength; + + perp.x *= num; + perp.y *= num; + + vertices[index] = point.x + perp.x; + vertices[index + 1] = point.y + perp.y; + vertices[index + 2] = point.x - perp.x; + vertices[index + 3] = point.y - perp.y; + + lastPoint = point; + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/* +* Sets the Texture this Rope uses for rendering. +* +* @method Phaser.Rope#setTexture +* @memberof Phaser.Rope +* @param {Texture} texture - The texture that will be used. +*/ +Phaser.Rope.prototype.setTexture = function (texture) { + + this.texture = texture; + +}; + +/* +* Renders the Rope to WebGL. +* +* @private +* @method Phaser.Rope#_renderWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + renderSession.spriteBatch.stop(); + + if (!this._vertexBuffer) + { + this._initWebGL(renderSession); + } + + renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader); + + this._renderStrip(renderSession); + + renderSession.spriteBatch.start(); + +}; + +/* +* Builds the Strip. +* +* @private +* @method Phaser.Rope#_initWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._initWebGL = function (renderSession) { + + // build the strip! + var gl = renderSession.gl; + + this._vertexBuffer = gl.createBuffer(); + this._indexBuffer = gl.createBuffer(); + this._uvBuffer = gl.createBuffer(); + this._colorBuffer = gl.createBuffer(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + +}; + +/* +* Renders the Strip to WebGL. +* +* @private +* @method Phaser.Rope#_renderStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderStrip = function (renderSession) { + + var gl = renderSession.gl; + var projection = renderSession.projection; + var offset = renderSession.offset; + var shader = renderSession.shaderManager.stripShader; + + var drawMode = (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + renderSession.blendModeManager.setBlendMode(this.blendMode); + + // set uniforms + gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true)); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + gl.uniform1f(shader.alpha, this.worldAlpha); + + if (!this.dirty) + { + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + } + else + { + this.dirty = false; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + } + + gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0); + +}; + +/* +* Renders the Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvas +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvas = function (renderSession) { + + var context = renderSession.context; + + var transform = this.worldTransform; + + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + if (renderSession.roundPixels) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx, ty); + } + + if (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) + { + this._renderCanvasTriangleStrip(context); + } + else + { + this._renderCanvasTriangles(context); + } + +}; + +/* +* Renders a Triangle Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangleStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangleStrip = function (context) { + + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + + var length = vertices.length / 2; + + this.count++; + + for (var i = 0; i < length - 2; i++) + { + var index = i * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangles +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangles = function (context) { + + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + + var length = indices.length; + + this.count++; + + for (var i = 0; i < length; i += 3) + { + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasDrawTriangle +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { + + var textureSource = this.texture.baseTexture.source; + var textureWidth = this.texture.width; + var textureHeight = this.texture.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var u0 = uvs[index0] * textureWidth; + var u1 = uvs[index1] * textureWidth; + var u2 = uvs[index2] * textureWidth; + var v0 = uvs[index0 + 1] * textureHeight; + var v1 = uvs[index1 + 1] * textureHeight; + var v2 = uvs[index2 + 1] * textureHeight; + + if (this.canvasPadding > 0) + { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt((normX * normX) + (normY * normY)); + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2); + var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2); + var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2); + var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2); + var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2); + var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2); + var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2); + + context.transform( + deltaA / delta, + deltaD / delta, + deltaB / delta, + deltaE / delta, + deltaC / delta, + deltaF / delta); + + context.drawImage(textureSource, 0, 0); + context.restore(); + +}; + +/* +* Renders a flat strip. +* +* @method Phaser.Rope#renderStripFlat +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.renderStripFlat = function (strip) { + + var context = this.context; + var vertices = strip.vertices; + + var length = vertices.length / 2; + + this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; i++) + { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var x1 = vertices[index + 2]; + var x2 = vertices[index + 4]; + var y0 = vertices[index + 1]; + var y1 = vertices[index + 3]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + +}; + +/* +* Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Rope#getBounds +* @memberof Phaser.Rope +* @param {Matrix} matrix - The transformation matrix of the Sprite. +* @return {Rectangle} The framing rectangle. +*/ +Phaser.Rope.prototype.getBounds = function (matrix) { + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + var vertices = this.vertices; + + for (var i = 0; i < vertices.length; i += 2) + { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + if (minX === -Infinity || maxY === Infinity) + { + return PIXI.EmptyRectangle; + } + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // Store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* A Rope will call its updateAnimation function on each update loop if it has one. +* +* @name Phaser.Rope#updateAnimation +* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. +*/ +Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", { + + get: function () { + + return this._updateAnimation; + + }, + + set: function (value) { + + if (value && typeof value === 'function') + { + this._hasUpdateAnimation = true; + this._updateAnimation = value; + } + else + { + this._hasUpdateAnimation = false; + this._updateAnimation = null; + } + + } + +}); + +/** +* The segments that make up the rope body as an array of Phaser.Rectangles +* +* @name Phaser.Rope#segments +* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope +*/ +Object.defineProperty(Phaser.Rope.prototype, "segments", { + + get: function () { + + var segments = []; + var index, x1, y1, x2, y2, width, height, rect; + + for (var i = 0; i < this.points.length; i++) + { + index = i * 4; + + x1 = this.vertices[index] * this.scale.x; + y1 = this.vertices[index + 1] * this.scale.y; + x2 = this.vertices[index + 4] * this.scale.x; + y2 = this.vertices[index + 3] * this.scale.y; + + width = Phaser.Math.difference(x1, x2); + height = Phaser.Math.difference(y1, y2); + + x1 += this.world.x; + y1 += this.world.y; + rect = new Phaser.Rectangle(x1, y1, width, height); + segments.push(rect); + } + + return segments; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. +* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. +* +* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. +* +* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background +* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` +* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will +* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to +* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. +* +* An important note about texture dimensions: +* +* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be +* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two +* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and +* bottom of your frame. To avoid this ensure your textures are perfect powers of two. +* +* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However +* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive +* additional padding to enforce it to be so. +* +* @class Phaser.TileSprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate (in world space) to position the TileSprite at. +* @param {number} [y=0] - The y coordinate (in world space) to position the TileSprite at. +* @param {number} [width=256] - The width of the TileSprite. +* @param {number} [height=256] - The height of the TileSprite. +* @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. +* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.TileSprite = function (game, x, y, width, height, key, frame) { + + x = x || 0; + y = y || 0; + width = width || 256; + height = height || 256; + key = key || null; + frame = frame || null; + + PIXI.Sprite.call(this, new PIXI.Texture(Phaser.Cache.DEFAULT.baseTexture), width, height); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.TILESPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} _scroll - Internal cache var. + * @private + */ + this._scroll = new Phaser.Point(); + + /** + * @property {Phaser.Point} tileScale - The scale applied to the image being tiled. + */ + this.tileScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tileScaleOffset - The scale offset applied to the image being tiled. + */ + this.tileScaleOffset = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tilePosition - The offset position of the image being tiled. + */ + this.tilePosition = new Phaser.Point(); + + /** + * If enabled a green rectangle will be drawn behind the generated tiling texture, + * allowing you to visually debug the texture being used. + * + * @property {boolean} textureDebug + */ + this.textureDebug = false; + + /** + * The CanvasBuffer object that the tiled texture is drawn to. + * + * @property {PIXI.CanvasBuffer} canvasBuffer + */ + this.canvasBuffer = null; + + /** + * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. + * + * @property {PIXI.Texture} tilingTexture + */ + this.tilingTexture = null; + + /** + * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). + * + * @property {object} tilePattern + */ + this.tilePattern = null; + + /** + * If true the TileSprite will run `generateTexture` on its **next** render pass. + * This is set by the likes of Phaser.LoadTexture.setFrame. + * + * @property {boolean} refreshTexture + */ + this.refreshTexture = true; + + this.frameWidth = 0; + this.frameHeight = 0; + + this._width = width; + this._height = height; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.TileSprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.TileSprite.prototype.constructor = Phaser.TileSprite; + +Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'Smoothed' +]); + +Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TileSprite#preUpdate +* @memberof Phaser.TileSprite +* @return {boolean} +*/ +Phaser.TileSprite.prototype.preUpdate = function () { + + if (this._scroll.x !== 0) + { + this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed; + } + + if (this._scroll.y !== 0) + { + this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed; + } + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). +* The scroll speed is specified in pixels per second. +* A negative x value will scroll to the left. A positive x value will scroll to the right. +* A negative y value will scroll up. A positive y value will scroll down. +* +* @method Phaser.TileSprite#autoScroll +* @memberof Phaser.TileSprite +* @param {number} x - Horizontal scroll speed in pixels per second. +* @param {number} y - Vertical scroll speed in pixels per second. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.autoScroll = function (x, y) { + + this._scroll.set(x, y); + + return this; + +}; + +/** +* Stops an automatically scrolling TileSprite. +* +* @method Phaser.TileSprite#stopScroll +* @memberof Phaser.TileSprite +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.stopScroll = function () { + + this._scroll.set(0, 0); + + return this; + +}; + +/** +* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present +* and nulls its reference to game, freeing it up for garbage collection. +* +* @method Phaser.TileSprite#destroy +* @memberof Phaser.TileSprite +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.TileSprite.prototype.destroy = function (destroyChildren) { + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + + PIXI.Sprite.prototype.destroy.call(this); + + if (this.canvasBuffer) + { + this.canvasBuffer.destroy(); + this.canvasBuffer = null; + } + + this.tileScale = null; + this.tileScaleOffset = null; + this.tilePosition = null; + + if (this.tilingTexture) + { + this.tilingTexture.destroy(true); + this.tilingTexture = null; + } + +}; + +/** +* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the TileSprite has a physics body that too is reset. +* +* @method Phaser.TileSprite#reset +* @memberof Phaser.TileSprite +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + this.tilePosition.x = 0; + this.tilePosition.y = 0; + + return this; + +}; + +/** +* Changes the texture being rendered by this TileSprite. +* Causes a texture refresh to take place on the next render. +* +* @method Phaser.TileSprite#setTexture +* @memberof Phaser.TileSprite +* @param {PIXI.Texture} texture - The texture to apply to this TileSprite. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.setTexture = function (texture) { + + if (this.texture !== texture) + { + this.texture = texture; + this.refreshTexture = true; + this.cachedTint = 0xFFFFFF; + } + + return this; + +}; + +/** +* Renders the TileSprite using the WebGL Renderer. +* +* @private +* @method Phaser.TileSprite#_renderWebGL +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + 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.refreshTexture) + { + this.generateTilingTexture(true, renderSession); + + if (this.tilingTexture) + { + if (this.tilingTexture.needsUpdate) + { + this.tilingTexture.baseTexture.textureIndex = this.texture.baseTexture.textureIndex; + renderSession.renderer.updateTexture(this.tilingTexture.baseTexture); + this.tilingTexture.needsUpdate = false; + } + } + else + { + return; + } + } + + renderSession.spriteBatch.renderTilingSprite(this); + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + var restartBatch = false; + + if (this._filters) + { + restartBatch = true; + renderSession.spriteBatch.stop(); + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + if (!restartBatch) + { + renderSession.spriteBatch.stop(); + } + + renderSession.maskManager.popMask(this._mask, renderSession); + } + + if (restartBatch) + { + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the TileSprite using the Canvas Renderer. +* +* @private +* @method Phaser.TileSprite#_renderCanvas +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + var context = renderSession.context; + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + context.globalAlpha = this.worldAlpha; + + var wt = this.worldTransform; + var resolution = renderSession.resolution; + var tx = (wt.tx * resolution) + renderSession.shakeX; + var ty = (wt.ty * resolution) + renderSession.shakeY; + + context.setTransform(wt.a * resolution, wt.b * resolution, wt.c * resolution, wt.d * resolution, tx, ty); + + if (this.tint !== 0xFFFFFF && (this.texture.requiresReTint || this.cachedTint !== this.tint)) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + this.refreshTexture = true; + } + + if (this.refreshTexture) + { + this.generateTilingTexture(false, renderSession); + + if (this.tilingTexture) + { + this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat'); + } + else + { + return; + } + } + + var sessionBlendMode = renderSession.currentBlendMode; + + // Check blend mode + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + var tilePosition = this.tilePosition; + var tileScale = this.tileScale; + + tilePosition.x %= this.tilingTexture.baseTexture.width; + tilePosition.y %= this.tilingTexture.baseTexture.height; + + // Translate + context.scale(tileScale.x, tileScale.y); + context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height)); + + context.fillStyle = this.tilePattern; + + tx = -tilePosition.x; + ty = -tilePosition.y; + + var tw = this._width / tileScale.x; + var th = this._height / tileScale.y; + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + tx |= 0; + ty |= 0; + tw |= 0; + th |= 0; + } + + context.fillRect(tx, ty, tw, th); + + // Translate back again + context.scale(1 / tileScale.x, 1 / tileScale.y); + context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height)); + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + // Reset blend mode + if (sessionBlendMode !== this.blendMode) + { + renderSession.currentBlendMode = sessionBlendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode]; + } + +}; + +/** +* Override the Sprite method. +* +* @private +* @method Phaser.TileSprite#onTextureUpdate +* @memberof Phaser.TileSprite +*/ +Phaser.TileSprite.prototype.onTextureUpdate = function () { + + // overriding the sprite version of this! + +}; + +/** +* Internal method that generates a new tiling texture. +* +* @method Phaser.TileSprite#generateTilingTexture +* @memberof Phaser.TileSprite +* @param {boolean} forcePowerOfTwo - Whether we want to force the texture to be a power of two +*/ +Phaser.TileSprite.prototype.generateTilingTexture = function (forcePowerOfTwo) { + + if (!this.texture.baseTexture.hasLoaded) + { + return; + } + + var texture = this.texture; + var frame = texture.frame; + + var targetWidth = this._frame.sourceSizeW || this._frame.width; + var targetHeight = this._frame.sourceSizeH || this._frame.height; + + var dx = 0; + var dy = 0; + + if (this._frame.trimmed) + { + dx = this._frame.spriteSourceSizeX; + dy = this._frame.spriteSourceSizeY; + } + + if (forcePowerOfTwo) + { + targetWidth = Phaser.Math.getNextPowerOfTwo(targetWidth); + targetHeight = Phaser.Math.getNextPowerOfTwo(targetHeight); + } + + if (this.canvasBuffer) + { + this.canvasBuffer.resize(targetWidth, targetHeight); + this.tilingTexture.baseTexture.width = targetWidth; + this.tilingTexture.baseTexture.height = targetHeight; + this.tilingTexture.needsUpdate = true; + } + else + { + this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight); + this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas); + this.tilingTexture.isTiling = true; + this.tilingTexture.needsUpdate = true; + } + + if (this.textureDebug) + { + this.canvasBuffer.context.strokeStyle = '#00ff00'; + this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight); + } + + // If a sprite sheet we need this: + var w = texture.crop.width; + var h = texture.crop.height; + + if (w !== targetWidth || h !== targetHeight) + { + w = targetWidth; + h = targetHeight; + } + + var targetTexture = this.tintedTexture ? this.tintedTexture : texture.baseTexture.source; + + this.canvasBuffer.context.drawImage( + targetTexture, + texture.crop.x, + texture.crop.y, + texture.crop.width, + texture.crop.height, + dx, + dy, + w, + h + ); + + this.tileScaleOffset.x = frame.width / targetWidth; + this.tileScaleOffset.y = frame.height / targetHeight; + + this.refreshTexture = false; + + this.tilingTexture.baseTexture._powerOf2 = true; + +}; + +/** +* Returns the framing rectangle of the Tile Sprite. +* +* @method Phaser.TileSprite#getBounds +* @memberof Phaser.TileSprite +* @return {Phaser.Rectangle} The bounds of the Tile Sprite. +*/ +Phaser.TileSprite.prototype.getBounds = function () { + + var width = this._width; + var height = this._height; + + var w0 = width * (1 - this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1 - this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = (a * w1) + (c * h1) + tx; + var y1 = (d * h1) + (b * w1) + ty; + + var x2 = (a * w0) + (c * h1) + tx; + var y2 = (d * h1) + (b * w0) + ty; + + var x3 = (a * w0) + (c * h0) + tx; + var y3 = (d * h0) + (b * w0) + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // TODO: This is surely always undefined? As it's not set anywhere in the parent objects + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* The width of the sprite, setting this will actually modify the scale to achieve the value set +* +* @property width +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'width', { + + get: function () { + + return this._width; + + }, + + set: function (value) { + + this._width = value; + + } + +}); + +/** +* The height of the TilingSprite, setting this will actually modify the scale to achieve the value set +* +* @property height +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'height', { + + get: function () { + + return this._height; + + }, + + set: function (value) { + + this._height = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The CanvasPool is a global static object, that allows Phaser to recycle and pool Canvas DOM elements. +* +* @class Phaser.CanvasPool +* @static +*/ +Phaser.CanvasPool = { + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @method Phaser.CanvasPool.create + * @static + * @param {any} parent - The parent of the canvas element. + * @param {number} width - The width of the canvas element. + * @param {number} height - The height of the canvas element. + * @return {HTMLCanvasElement} The canvas element. + */ + create: function (parent, width, height) { + + var idx = Phaser.CanvasPool.getFirst(); + var canvas; + + if (idx === -1) + { + var container = { + parent: parent, + canvas: document.createElement('canvas') + }; + + Phaser.CanvasPool.pool.push(container); + + canvas = container.canvas; + } + else + { + Phaser.CanvasPool.pool[idx].parent = parent; + + canvas = Phaser.CanvasPool.pool[idx].canvas; + } + + if (width !== undefined) + { + canvas.width = width; + canvas.height = height; + } + + return canvas; + + }, + + /** + * Gets the first free canvas index from the pool. + * + * @static + * @method Phaser.CanvasPool.getFirst + * @return {number} + */ + getFirst: function () { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + return i; + } + } + + return -1; + + }, + + /** + * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.remove + * @param {any} parent - The parent of the canvas element. + */ + remove: function (parent) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent === parent) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Looks up a canvas based on its type, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.removeByCanvas + * @param {HTMLCanvasElement} canvas - The canvas element to remove. + */ + removeByCanvas: function (canvas) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].canvas === canvas) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Gets the total number of used canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getTotal + * @return {number} The number of in-use (parented) canvas elements in the pool. + */ + getTotal: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent) + { + c++; + } + } + + return c; + + }, + + /** + * Gets the total number of free canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getFree + * @return {number} The number of free (un-parented) canvas elements in the pool. + */ + getFree: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + c++; + } + } + + return c; + + }, + + + /** + * Prints in-use, free, and total counts to console.log. + * + * @static + * @method Phaser.CanvasPool.log + */ + log: function () { + + console.log('CanvasPool: %s used, %s free, %s total', this.getTotal(), this.getFree(), this.pool.length); + + } + +}; + +/** + * The pool into which the canvas elements are placed. + * + * @property pool + * @type Array + * @static + */ +Phaser.CanvasPool.pool = []; + + +/** + * The total number of canvas elements in the {@link Phaser.CanvasPool.pool pool}. + * + * @property length + * @type number + * @static + * @readonly + */ +Object.defineProperty(Phaser.CanvasPool, 'length', { + get: function () { + return this.pool.length; + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}. +* +* This class represents a singleton object that can be accessed directly as `game.device` +* (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it. +* +* Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization +* occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase. +* Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal, e.g., +* +* ```javascript +* Phaser.Device.onInitialized.add(function (device) { +* +* device.canvasBitBltShift = true; +* device.mspointer = false; +* +* }); +* +* var game = new Phaser.Game(); +* ``` +* +* When checking features using the exposed properties only the *truth-iness* of the value should be relied upon +* unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined` +* when indicating the lack of a feature. +* +* Uses elements from System.js by MrDoob and Modernizr +* +* @description +* It is not possible to instantiate the Device class manually. +* +* @class +* @protected +*/ +Phaser.Device = function () { + + /** + * The time the device became ready. + * @property {integer} deviceReadyAt + * @protected + */ + this.deviceReadyAt = 0; + + /** + * The time as which initialization has completed. + * @property {boolean} initialized + * @protected + */ + this.initialized = false; + + // Browser / Host / Operating System + + /** + * @property {boolean} desktop - Is running on a desktop? + * @default + */ + this.desktop = false; + + /** + * @property {boolean} iOS - Is running on iOS? + * @default + */ + this.iOS = false; + + /** + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @default + */ + this.iOSVersion = 0; + + /** + * @property {boolean} cocoonJS - Is the game running under CocoonJS? + * @default + */ + this.cocoonJS = false; + + /** + * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App? + * @default + */ + this.cocoonJSApp = false; + + /** + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @default + */ + this.cordova = false; + + /** + * @property {boolean} node - Is the game running under Node.js? + * @default + */ + this.node = false; + + /** + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @default + */ + this.nodeWebkit = false; + + /** + * @property {boolean} electron - Is the game running under GitHub Electron? + * @default + */ + this.electron = false; + + /** + * @property {boolean} ejecta - Is the game running under Ejecta? + * @default + */ + this.ejecta = false; + + /** + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @default + */ + this.crosswalk = false; + + /** + * @property {boolean} android - Is running on android? + * @default + */ + this.android = false; + + /** + * @property {boolean} chromeOS - Is running on chromeOS? + * @default + */ + this.chromeOS = false; + + /** + * @property {boolean} linux - Is running on linux? + * @default + */ + this.linux = false; + + /** + * @property {boolean} macOS - Is running on macOS? + * @default + */ + this.macOS = false; + + /** + * @property {boolean} windows - Is running on windows? + * @default + */ + this.windows = false; + + /** + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @default + */ + this.windowsPhone = false; + + // Features + + /** + * @property {boolean} canvas - Is canvas available? + * @default + */ + this.canvas = false; + + /** + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @default + */ + this.canvasBitBltShift = null; + + /** + * If the browser isn't capable of handling tinting with alpha this will be false. + * @property {boolean} canHandleAlpha + * @default + */ + this.canHandleAlpha = false; + + /** + * Whether or not the {@link http://caniuse.com/#feat=canvas-blending Canvas Blend Modes} are supported, consequently the ability to tint using the multiply method. + * + * Expect `false` in Internet Explorer <= 11. + * + * @property {boolean} canUseMultiply + * @default + */ + this.canUseMultiply = false; + + /** + * @property {boolean} webGL - Is webGL available? + * @default + */ + this.webGL = false; + + /** + * @property {boolean} file - Is file available? + * @default + */ + this.file = false; + + /** + * @property {boolean} fileSystem - Is fileSystem available? + * @default + */ + this.fileSystem = false; + + /** + * @property {boolean} localStorage - Is localStorage available? + * @default + */ + this.localStorage = false; + + /** + * @property {boolean} worker - Is worker available? + * @default + */ + this.worker = false; + + /** + * @property {boolean} css3D - Is css3D available? + * @default + */ + this.css3D = false; + + /** + * @property {boolean} pointerLock - Is Pointer Lock available? + * @default + */ + this.pointerLock = false; + + /** + * @property {boolean} typedArray - Does the browser support TypedArrays? + * @default + */ + this.typedArray = false; + + /** + * @property {boolean} vibration - Does the device support the Vibration API? + * @default + */ + this.vibration = false; + + /** + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @default + */ + this.getUserMedia = true; + + /** + * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true) + * @default + */ + this.quirksMode = false; + + // Input + + /** + * @property {boolean} touch - Is touch available? + * @default + */ + this.touch = false; + + /** + * @property {boolean} mspointer - Is mspointer available? + * @default + */ + this.mspointer = false; + + /** + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @default + * @protected + */ + this.wheelEvent = null; + + // Browser + + /** + * @property {boolean} arora - Set to true if running in Arora. + * @default + */ + this.arora = false; + + /** + * @property {boolean} chrome - Set to true if running in Chrome. + * @default + */ + this.chrome = false; + + /** + * @property {number} chromeVersion - If running in Chrome this will contain the major version number. + * @default + */ + this.chromeVersion = 0; + + /** + * @property {boolean} epiphany - Set to true if running in Epiphany. + * @default + */ + this.epiphany = false; + + /** + * @property {boolean} firefox - Set to true if running in Firefox. + * @default + */ + this.firefox = false; + + /** + * @property {number} firefoxVersion - If running in Firefox this will contain the major version number. + * @default + */ + this.firefoxVersion = 0; + + /** + * @property {boolean} ie - Set to true if running in Internet Explorer. + * @default + */ + this.ie = false; + + /** + * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. + * @default + */ + this.ieVersion = 0; + + /** + * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+) + * @default + */ + this.trident = false; + + /** + * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx} + * @default + */ + this.tridentVersion = 0; + + /** + * @property {boolean} edge - Set to true if running in Microsoft Edge browser. + * @default + */ + this.edge = false; + + /** + * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. + * @default + */ + this.mobileSafari = false; + + /** + * @property {boolean} midori - Set to true if running in Midori. + * @default + */ + this.midori = false; + + /** + * @property {boolean} opera - Set to true if running in Opera. + * @default + */ + this.opera = false; + + /** + * @property {boolean} safari - Set to true if running in Safari. + * @default + */ + this.safari = false; + + /** + * @property {number} safariVersion - If running in Safari this will contain the major version number. + * @default + */ + this.safariVersion = 0; + + /** + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @default + */ + this.webApp = false; + + /** + * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle) + * @default + */ + this.silk = false; + + // Audio + + /** + * @property {boolean} audioData - Are Audio tags available? + * @default + */ + this.audioData = false; + + /** + * @property {boolean} webAudio - Is the WebAudio API available? + * @default + */ + this.webAudio = false; + + /** + * @property {boolean} ogg - Can this device play ogg files? + * @default + */ + this.ogg = false; + + /** + * @property {boolean} opus - Can this device play opus files? + * @default + */ + this.opus = false; + + /** + * @property {boolean} mp3 - Can this device play mp3 files? + * @default + */ + this.mp3 = false; + + /** + * @property {boolean} wav - Can this device play wav files? + * @default + */ + this.wav = false; + + /** + * Can this device play m4a files? + * @property {boolean} m4a - True if this device can play m4a files. + * @default + */ + this.m4a = false; + + /** + * @property {boolean} webm - Can this device play webm files? + * @default + */ + this.webm = false; + + /** + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @default + */ + this.dolby = false; + + // Video + + /** + * @property {boolean} oggVideo - Can this device play ogg video files? + * @default + */ + this.oggVideo = false; + + /** + * @property {boolean} h264Video - Can this device play h264 mp4 video files? + * @default + */ + this.h264Video = false; + + /** + * @property {boolean} mp4Video - Can this device play h264 mp4 video files? + * @default + */ + this.mp4Video = false; + + /** + * @property {boolean} webmVideo - Can this device play webm video files? + * @default + */ + this.webmVideo = false; + + /** + * @property {boolean} vp9Video - Can this device play vp9 video files? + * @default + */ + this.vp9Video = false; + + /** + * @property {boolean} hlsVideo - Can this device play hls video files? + * @default + */ + this.hlsVideo = false; + + // Device + + /** + * @property {boolean} iPhone - Is running on iPhone? + * @default + */ + this.iPhone = false; + + /** + * @property {boolean} iPhone4 - Is running on iPhone4? + * @default + */ + this.iPhone4 = false; + + /** + * @property {boolean} iPad - Is running on iPad? + * @default + */ + this.iPad = false; + + // Device features + + /** + * @property {number} pixelRatio - PixelRatio of the host device? + * @default + */ + this.pixelRatio = 0; + + /** + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @default + */ + this.littleEndian = false; + + /** + * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`. + * @default + */ + this.LITTLE_ENDIAN = false; + + /** + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @default + */ + this.support32bit = false; + + /** + * @property {boolean} fullscreen - Does the browser support the Full Screen API? + * @default + */ + this.fullscreen = false; + + /** + * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it. + * @default + */ + this.requestFullscreen = ''; + + /** + * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @default + */ + this.cancelFullscreen = ''; + + /** + * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @default + */ + this.fullscreenKeyboard = false; + +}; + +// Device is really a singleton/static entity; instantiate it +// and add new methods directly sans-prototype. +Phaser.Device = new Phaser.Device(); + +/** +* This signal is dispatched after device initialization occurs but before any of the ready +* callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked. +* +* Local "patching" for a particular device can/should be done in this event. +* +* _Note_: This signal is removed after the device has been readied; if a handler has not been +* added _before_ `new Phaser.Game(..)` it is probably too late. +* +* @type {?Phaser.Signal} +* @static +*/ +Phaser.Device.onInitialized = new Phaser.Signal(); + +/** +* Add a device-ready handler and ensure the device ready sequence is started. +* +* Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added, +* which is normally done automatically be calling `new Phaser.Game(..)`. +* +* The handler is invoked when the device is considered "ready", which may be immediately +* if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}. +* +* @method +* @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. +* @param {object} [context] - Context in which to invoke the handler +* @param {boolean} [nonPrimer=false] - If true the device ready check will not be started. +*/ +Phaser.Device.whenReady = function (callback, context, nonPrimer) { + + var readyCheck = this._readyCheck; + + if (this.deviceReadyAt || !readyCheck) + { + callback.call(context, this); + } + else if (readyCheck._monitor || nonPrimer) + { + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + } + else + { + readyCheck._monitor = readyCheck.bind(this); + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + + var cordova = typeof window.cordova !== 'undefined'; + var cocoonJS = navigator['isCocoonJS']; + + if (document.readyState === 'complete' || document.readyState === 'interactive') + { + // Why is there an additional timeout here? + window.setTimeout(readyCheck._monitor, 0); + } + else if (cordova && !cocoonJS) + { + // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + // Cordova, but NOT Cocoon? + document.addEventListener('deviceready', readyCheck._monitor, false); + } + else + { + document.addEventListener('DOMContentLoaded', readyCheck._monitor, false); + window.addEventListener('load', readyCheck._monitor, false); + } + } + +}; + +/** +* Internal method used for checking when the device is ready. +* This function is removed from Phaser.Device when the device becomes ready. +* +* @method +* @private +*/ +Phaser.Device._readyCheck = function () { + + var readyCheck = this._readyCheck; + + if (!document.body) + { + window.setTimeout(readyCheck._monitor, 20); + } + else if (!this.deviceReadyAt) + { + this.deviceReadyAt = Date.now(); + + document.removeEventListener('deviceready', readyCheck._monitor); + document.removeEventListener('DOMContentLoaded', readyCheck._monitor); + window.removeEventListener('load', readyCheck._monitor); + + this._initialize(); + this.initialized = true; + + this.onInitialized.dispatch(this); + + var item; + while ((item = readyCheck._queue.shift())) + { + var callback = item[0]; + var context = item[1]; + callback.call(context, this); + } + + // Remove no longer useful methods and properties. + this._readyCheck = null; + this._initialize = null; + this.onInitialized = null; + } + +}; + +/** +* Internal method to initialize the capability checks. +* This function is removed from Phaser.Device once the device is initialized. +* +* @method +* @private +*/ +Phaser.Device._initialize = function () { + + var device = this; + + /** + * Check which OS is game running on. + */ + function _checkOS () { + + var ua = navigator.userAgent; + + if (/Playstation Vita/.test(ua)) + { + device.vita = true; + } + else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua)) + { + device.kindle = true; + // This will NOT detect early generations of Kindle Fire, I think there is no reliable way... + // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true" + } + else if (/Android/.test(ua)) + { + device.android = true; + } + else if (/CrOS/.test(ua)) + { + device.chromeOS = true; + } + else if (/iP[ao]d|iPhone/i.test(ua)) + { + device.iOS = true; + (navigator.appVersion).match(/OS (\d+)/); + device.iOSVersion = parseInt(RegExp.$1, 10); + } + else if (/Linux/.test(ua)) + { + device.linux = true; + } + else if (/Mac OS/.test(ua)) + { + device.macOS = true; + } + else if (/Windows/.test(ua)) + { + device.windows = true; + } + + if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua)) + { + device.android = false; + device.iOS = false; + device.macOS = false; + device.windows = true; + device.windowsPhone = true; + } + + var silk = /Silk/.test(ua); // detected in browsers + + if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS) + { + device.desktop = true; + } + + // Windows Phone / Table reset + if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) + { + device.desktop = false; + } + + } + + /** + * Checks if the browser correctly supports putImageData alpha channels. + * If the browser isn't capable of handling tinting with alpha, `Device.canHandleAlpha` will be false. + * Also checks whether the Canvas BlendModes are supported by the current browser for drawImage. + */ + function _checkCanvasFeatures () { + + var canvas = Phaser.CanvasPool.create(this, 6, 1); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgba(10, 20, 30, 0.5)'; + + // Draw a single pixel + context.fillRect(0, 0, 1, 1); + + // Get the color values + var s1 = context.getImageData(0, 0, 1, 1); + + if (s1) + { + // Plot them to x2 + context.putImageData(s1, 1, 0); + + // Get those values + var s2 = context.getImageData(1, 0, 1, 1); + + // Compare and set + device.canHandleAlpha = ( + s2.data[0] === s1.data[0] && + s2.data[1] === s1.data[1] && + s2.data[2] === s1.data[2] && + s2.data[3] === s1.data[3] + ); + } + + // Checks whether the Canvas BlendModes are supported by the current browser for drawImage. + context.globalCompositeOperation = 'multiply'; + device.canUseMultiply = (context.globalCompositeOperation === 'multiply'); + + Phaser.CanvasPool.removeByCanvas(canvas); + + PIXI.CanvasTinter.tintMethod = (device.canUseMultiply) ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel; + + } + + /** + * Check HTML5 features of the host environment. + */ + function _checkFeatures () { + + device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS; + + try { + device.localStorage = !!localStorage.getItem; + } catch (error) { + device.localStorage = false; + } + + device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; + device.fileSystem = !!window['requestFileSystem']; + + device.webGL = !!window.WebGLRenderingContext; + + device.worker = !!window['Worker']; + + device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; + + device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL; + + // Older versions of firefox (< 21) apparently claim support but user media does not actually work + if (device.firefox && device.firefoxVersion < 21) + { + device.getUserMedia = false; + } + + // TODO: replace canvasBitBltShift detection with actual feature check + + // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it + // is safer to not try and use the fast copy-over method. + if (!device.iOS && (device.ie || device.firefox || device.chrome)) + { + device.canvasBitBltShift = true; + } + + // Known not to work + if (device.safari || device.mobileSafari) + { + device.canvasBitBltShift = false; + } + + } + + /** + * Checks/configures various input. + */ + function _checkInput () { + + if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1)) + { + device.touch = true; + } + + if (window.PointerEvent || window.MSPointerEvent || window.navigator.msPointerEnabled || window.navigator.pointerEnabled) + { + device.mspointer = true; + } + + if (!device.cocoonJS) + { + // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel + if ('onwheel' in window || (device.ie && 'WheelEvent' in window)) + { + // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ + device.wheelEvent = 'wheel'; + } + else if ('onmousewheel' in window) + { + // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. + device.wheelEvent = 'mousewheel'; + } + else if (device.firefox && 'MouseScrollEvent' in window) + { + // FF prior to 17. This should probably be scrubbed. + device.wheelEvent = 'DOMMouseScroll'; + } + } + + } + + /** + * Checks for support of the Full Screen API. + */ + function _checkFullScreenSupport () { + + var fs = [ + 'requestFullscreen', + 'requestFullScreen', + 'webkitRequestFullscreen', + 'webkitRequestFullScreen', + 'msRequestFullscreen', + 'msRequestFullScreen', + 'mozRequestFullScreen', + 'mozRequestFullscreen' + ]; + + var element = document.createElement('div'); + + for (var i = 0; i < fs.length; i++) + { + if (element[fs[i]]) + { + device.fullscreen = true; + device.requestFullscreen = fs[i]; + break; + } + } + + var cfs = [ + 'cancelFullScreen', + 'exitFullscreen', + 'webkitCancelFullScreen', + 'webkitExitFullscreen', + 'msCancelFullScreen', + 'msExitFullscreen', + 'mozCancelFullScreen', + 'mozExitFullscreen' + ]; + + if (device.fullscreen) + { + for (var i = 0; i < cfs.length; i++) + { + if (document[cfs[i]]) + { + device.cancelFullscreen = cfs[i]; + break; + } + } + } + + // Keyboard Input? + if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT']) + { + device.fullscreenKeyboard = true; + } + + } + + /** + * Check what browser is game running in. + */ + function _checkBrowser () { + + var ua = navigator.userAgent; + + if (/Arora/.test(ua)) + { + device.arora = true; + } + else if (/Edge\/\d+/.test(ua)) + { + device.edge = true; + } + else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.chrome = true; + device.chromeVersion = parseInt(RegExp.$1, 10); + } + else if (/Epiphany/.test(ua)) + { + device.epiphany = true; + } + else if (/Firefox\D+(\d+)/.test(ua)) + { + device.firefox = true; + device.firefoxVersion = parseInt(RegExp.$1, 10); + } + else if (/AppleWebKit/.test(ua) && device.iOS) + { + device.mobileSafari = true; + } + else if (/MSIE (\d+\.\d+);/.test(ua)) + { + device.ie = true; + device.ieVersion = parseInt(RegExp.$1, 10); + } + else if (/Midori/.test(ua)) + { + device.midori = true; + } + else if (/Opera/.test(ua)) + { + device.opera = true; + } + else if (/Safari\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.safari = true; + + if (/Version\/(\d+)\./.test(ua)) + { + device.safariVersion = parseInt(RegExp.$1, 10); + } + } + else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua)) + { + device.ie = true; + device.trident = true; + device.tridentVersion = parseInt(RegExp.$1, 10); + device.ieVersion = parseInt(RegExp.$3, 10); + } + + // Silk gets its own if clause because its ua also contains 'Safari' + if (/Silk/.test(ua)) + { + device.silk = true; + } + + // WebApp mode in iOS + if (navigator['standalone']) + { + device.webApp = true; + } + + if (typeof window.cordova !== 'undefined') + { + device.cordova = true; + } + + if (typeof process !== 'undefined' && typeof require !== 'undefined') + { + device.node = true; + } + + if (device.node && typeof process.versions === 'object') + { + device.nodeWebkit = !!process.versions['node-webkit']; + + device.electron = !!process.versions.electron; + } + + if (navigator['isCocoonJS']) + { + device.cocoonJS = true; + } + + if (device.cocoonJS) + { + try { + device.cocoonJSApp = (typeof CocoonJS !== 'undefined'); + } + catch(error) + { + device.cocoonJSApp = false; + } + } + + if (typeof window.ejecta !== 'undefined') + { + device.ejecta = true; + } + + if (/Crosswalk/.test(ua)) + { + device.crosswalk = true; + } + + } + + /** + * Check video support. + */ + function _checkVideo () { + + var videoElement = document.createElement("video"); + var result = false; + + try { + if (result = !!videoElement.canPlayType) + { + if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) + { + device.oggVideo = true; + } + + if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + device.h264Video = true; + device.mp4Video = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) + { + device.webmVideo = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) + { + device.vp9Video = true; + } + + if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + device.hlsVideo = true; + } + } + } catch (e) {} + } + + /** + * Check audio support. + */ + function _checkAudio () { + + device.audioData = !!(window['Audio']); + device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); + var audioElement = document.createElement('audio'); + var result = false; + + try { + if (result = !!audioElement.canPlayType) + { + if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) + { + device.ogg = true; + } + + if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) + { + device.opus = true; + } + + if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) + { + device.mp3 = true; + } + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) + { + device.wav = true; + } + + if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) + { + device.m4a = true; + } + + if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) + { + device.webm = true; + } + + if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') + { + if (device.edge) + { + device.dolby = true; + } + else if (device.safari && device.safariVersion >= 9) + { + if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)) + { + var major = parseInt(RegExp.$1, 10); + var minor = parseInt(RegExp.$2, 10); + + if ((major === 10 && minor >= 11) || major > 10) + { + device.dolby = true; + } + } + } + } + } + } catch (e) { + } + + } + + /** + * Check Little or Big Endian system. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsLittleEndian () { + + var a = new ArrayBuffer(4); + var b = new Uint8Array(a); + var c = new Uint32Array(a); + + b[0] = 0xa1; + b[1] = 0xb2; + b[2] = 0xc3; + b[3] = 0xd4; + + if (c[0] === 0xd4c3b2a1) + { + return true; + } + + if (c[0] === 0xa1b2c3d4) + { + return false; + } + else + { + // Could not determine endianness + return null; + } + + } + + /** + * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsUint8ClampedImageData () { + + if (Uint8ClampedArray === undefined) + { + return false; + } + + var elem = Phaser.CanvasPool.create(this, 1, 1); + var ctx = elem.getContext('2d'); + + if (!ctx) + { + return false; + } + + var image = ctx.createImageData(1, 1); + + Phaser.CanvasPool.remove(this); + + return image.data instanceof Uint8ClampedArray; + + } + + /** + * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess. + */ + function _checkDevice () { + + device.pixelRatio = window['devicePixelRatio'] || 1; + device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1; + device.iPhone4 = (device.pixelRatio === 2 && device.iPhone); + device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') !== -1; + + if (typeof Int8Array !== 'undefined') + { + device.typedArray = true; + } + else + { + device.typedArray = false; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') + { + device.littleEndian = _checkIsLittleEndian(); + device.LITTLE_ENDIAN = device.littleEndian; + } + + device.support32bit = (typeof ArrayBuffer !== 'undefined' && typeof Uint8ClampedArray !== 'undefined' && typeof Int32Array !== 'undefined' && device.littleEndian !== null && _checkIsUint8ClampedImageData()); + + navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; + + if (navigator.vibrate) + { + device.vibration = true; + } + + } + + /** + * Check whether the host environment support 3D CSS. + */ + function _checkCSS3D () { + + var el = document.createElement('p'); + var has3d; + var transforms = { + 'webkitTransform': '-webkit-transform', + 'OTransform': '-o-transform', + 'msTransform': '-ms-transform', + 'MozTransform': '-moz-transform', + 'transform': 'transform' + }; + + // Add it to the body to get the computed style. + document.body.insertBefore(el, null); + + for (var t in transforms) + { + if (el.style[t] !== undefined) + { + el.style[t] = "translate3d(1px,1px,1px)"; + has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]); + } + } + + document.body.removeChild(el); + device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none"); + + } + + // Run the checks + _checkOS(); + _checkBrowser(); + _checkAudio(); + _checkVideo(); + _checkCSS3D(); + _checkDevice(); + _checkFeatures(); + _checkCanvasFeatures(); + _checkFullScreenSupport(); + _checkInput(); + +}; + +/** +* Check whether the host environment can play audio. +* +* @method canPlayAudio +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.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 === 'opus' && this.opus) + { + return true; + } + else if (type === 'wav' && this.wav) + { + return true; + } + else if (type === 'webm' && this.webm) + { + return true; + } + else if (type === 'mp4' && this.dolby) + { + return true; + } + + return false; + +}; + +/** +* Check whether the host environment can play video files. +* +* @method canPlayVideo +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.canPlayVideo = function (type) { + + if (type === 'webm' && (this.webmVideo || this.vp9Video)) + { + return true; + } + else if (type === 'mp4' && (this.mp4Video || this.h264Video)) + { + return true; + } + else if ((type === 'ogg' || type === 'ogv') && this.oggVideo) + { + return true; + } + else if (type === 'mpeg' && this.hlsVideo) + { + return true; + } + + return false; + +}; + +/** + * Whether the device plays audio/video only in response to a user touch event. + * + * @method needsTouchUnlock + * @memberof Phaser.Device.prototype + * @return {boolean} + */ +Phaser.Device.needsTouchUnlock = function () { + return !!(!this.cocoonJS && (this.iOS || this.android) || (window.PhaserGlobal && window.PhaserGlobal.fakeiOSTouchLock)); +}; + +/** +* Detect if the host is a an Android Stock browser. +* This is available before the device "ready" event. +* +* Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. +* +* @example +* var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; +* +* @method isAndroidStockBrowser +* @memberof Phaser.Device.prototype +*/ +Phaser.Device.isAndroidStockBrowser = function () { + + var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/); + return matches && matches[1] < 537; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, +* including styles, offset and aspect ratio. +* +* @class Phaser.Canvas +* @static +*/ +Phaser.Canvas = { + + /** + * Creates a `canvas` DOM element. The element is not automatically added to the document. + * + * @method Phaser.Canvas.create + * @param {object} parent - The object that will own the canvas that is created. + * @param {number} [width=256] - The width of the canvas element. + * @param {number} [height=256] - The height of the canvas element.. + * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. + * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global. + * @return {HTMLCanvasElement} The newly created canvas element. + */ + create: function (parent, width, height, id, skipPool) { + + width = width || 256; + height = height || 256; + + var canvas = (skipPool) ? document.createElement('canvas') : Phaser.CanvasPool.create(parent, width, height); + + if (typeof id === 'string' && id !== '') + { + canvas.id = id; + } + + canvas.width = width; + canvas.height = height; + canvas.style.display = 'block'; + + return canvas; + + }, + + /** + * Sets the background color behind the canvas. This changes the canvas style property. + * + * @method Phaser.Canvas.setBackgroundColor + * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. + * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setBackgroundColor: function (canvas, color) { + + color = color || 'rgb(0,0,0)'; + + canvas.style.backgroundColor = color; + + return canvas; + + }, + + /** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @method Phaser.Canvas.setTouchAction + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @method Phaser.Canvas.setUserSelect + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. + * If no parent is given it will be added as a child of the document.body. + * + * @method Phaser.Canvas.addToDOM + * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM. + * @param {string|HTMLElement} parent - The DOM element to add the canvas to. + * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + addToDOM: function (canvas, parent, overflowHidden) { + + var target; + + if (overflowHidden === undefined) { overflowHidden = true; } + + if (parent) + { + if (typeof parent === 'string') + { + // hopefully an element ID + target = document.getElementById(parent); + } + else if (typeof parent === 'object' && parent.nodeType === 1) + { + // quick test for a HTMLelement + target = parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + target = document.body; + } + + if (overflowHidden && target.style) + { + target.style.overflow = 'hidden'; + } + + target.appendChild(canvas); + + return canvas; + + }, + + /** + * Removes the given canvas element from the DOM. + * + * @method Phaser.Canvas.removeFromDOM + * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM. + */ + removeFromDOM: function (canvas) { + + if (canvas.parentNode) + { + canvas.parentNode.removeChild(canvas); + } + + }, + + /** + * Sets the transform of the given canvas to the matrix values provided. + * + * @method Phaser.Canvas.setTransform + * @param {CanvasRenderingContext2D} context - The context to set the transform on. + * @param {number} translateX - The value to translate horizontally by. + * @param {number} translateY - The value to translate vertically by. + * @param {number} scaleX - The value to scale horizontally by. + * @param {number} scaleY - The value to scale vertically by. + * @param {number} skewX - The value to skew horizontaly by. + * @param {number} skewY - The value to skew vertically by. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) { + + context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); + + return context; + + }, + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @method Phaser.Canvas.setSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setSmoothingEnabled: function (context, value) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + context[s] = value; + } + + return context; + + }, + + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @method Phaser.Canvas.getSmoothingPrefix + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context. + */ + getSmoothingPrefix: function (context) { + + var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; + + for (var prefix in vendor) + { + var s = vendor[prefix] + 'mageSmoothingEnabled'; + + if (s in context) + { + return s; + } + } + + return null; + + }, + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * + * @method Phaser.Canvas.getSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to check for smoothing on. + * @return {boolean} True if the given context has image smoothing enabled, otherwise false. + */ + getSmoothingEnabled: function (context) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + return context[s]; + } + + }, + + /** + * Sets the CSS image-rendering property to `pixelated` or `crisp-edges`. + * This can remove blurring when the game canvas is scaled up. + * In some browsers this has no visible effect in WEBGL mode. + * Note that if this doesn't given the desired result then see the setSmoothingEnabled. + * + * @method Phaser.Canvas.setImageRenderingCrisp + * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. + * @return {HTMLCanvasElement} Returns the source canvas. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering + * @see https://caniuse.com/#feat=css-crisp-edges + */ + setImageRenderingCrisp: function (canvas) { + + var types = [ '-webkit-optimize-contrast', '-moz-crisp-edges', 'crisp-edges', 'pixelated' ]; + + for (var i = 0; i < types.length; i++) + { + canvas.style['image-rendering'] = types[i]; + } + + canvas.style.msInterpolationMode = 'nearest-neighbor'; + + return canvas; + + }, + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method Phaser.Canvas.setImageRenderingBicubic + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setImageRenderingBicubic: function (canvas) { + + canvas.style['image-rendering'] = 'auto'; + canvas.style.msInterpolationMode = 'bicubic'; + + return canvas; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Abstracts away the use of RAF or setTimeOut for the core game update loop. +* +* @class Phaser.RequestAnimationFrame +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available. +*/ +Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) { + + if (forceSetTimeOut === undefined) { forceSetTimeOut = false; } + + /** + * @property {Phaser.Game} game - The currently running game. + */ + this.game = game; + + /** + * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available. + */ + this.forceSetTimeOut = forceSetTimeOut; + + var vendors = [ + 'ms', + 'moz', + 'webkit', + 'o' + ]; + + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) + { + window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; + } + + /** + * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. + * @private + */ + this._isSetTimeOut = false; + + /** + * @property {function} _onLoop - The function called by the update. + * @private + */ + this._onLoop = null; + + /** + * @property {number} _timeOutID - The callback ID used when calling cancel. + * @private + */ + this._timeOutID = null; + +}; + +Phaser.RequestAnimationFrame.prototype = { + + /** + * Starts the requestAnimationFrame running or setTimeout if unavailable in browser + * @method Phaser.RequestAnimationFrame#start + */ + start: function () { + + this.isRunning = true; + + var _this = this; + + if (!window.requestAnimationFrame || this.forceSetTimeOut) + { + this._isSetTimeOut = true; + + this._onLoop = function () { + return _this.updateSetTimeout(); + }; + + this._timeOutID = window.setTimeout(this._onLoop, 0); + } + else + { + this._isSetTimeOut = false; + + this._onLoop = function (time) { + return _this.updateRAF(time); + }; + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the requestAnimationFrame + * @method Phaser.RequestAnimationFrame#updateRAF + */ + updateRAF: function (rafTime) { + + if (this.isRunning) + { + // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below) + this.game.update(Math.floor(rafTime)); + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the setTimeout. + * @method Phaser.RequestAnimationFrame#updateSetTimeout + */ + updateSetTimeout: function () { + + if (this.isRunning) + { + this.game.update(Date.now()); + + this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); + } + + }, + + /** + * Stops the requestAnimationFrame from running. + * @method Phaser.RequestAnimationFrame#stop + */ + stop: function () { + + if (this._isSetTimeOut) + { + clearTimeout(this._timeOutID); + } + else + { + window.cancelAnimationFrame(this._timeOutID); + } + + this.isRunning = false; + + }, + + /** + * Is the browser using setTimeout? + * @method Phaser.RequestAnimationFrame#isSetTimeOut + * @return {boolean} + */ + isSetTimeOut: function () { + return this._isSetTimeOut; + }, + + /** + * Is the browser using requestAnimationFrame? + * @method Phaser.RequestAnimationFrame#isRAF + * @return {boolean} + */ + isRAF: function () { + return (this._isSetTimeOut === false); + } + +}; + +Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of useful mathematical functions. +* +* These are normally accessed through `game.math`. +* +* @class Phaser.Math +* @static +* @see {@link Phaser.Utils} +* @see {@link Phaser.ArrayUtils} +*/ +Phaser.Math = { + + /** + * Twice PI. + * @property {number} Phaser.Math#PI2 + * @default ~6.283 + */ + PI2: Math.PI * 2, + + /** + * Half PI. + * @property {number} Phaser.Math#HALF_PI + * @default ~1.570 + */ + HALF_PI: Math.PI * 0.5, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#DEG_TO_RAD + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#RAD_TO_DEG + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * Convert degrees to radians. + * + * @method Phaser.Math#degToRad + * @param {number} degrees - Angle in degrees. + * @return {number} Angle in radians. + */ + degToRad: function (degrees) { + + return degrees * Phaser.Math.DEG_TO_RAD; + + }, + + /** + * Convert radians to degrees. + * + * @method Phaser.Math#radToDeg + * @param {number} radians - Angle in radians. + * @return {number} Angle in degrees + */ + radToDeg: function (radians) { + + return radians * Phaser.Math.RAD_TO_DEG; + + }, + + /** + * Given a number, this function returns the closest number that is a power of two. + * This function is from the Starling Framework. + * + * @method Phaser.Math#getNextPowerOfTwo + * @param {number} value - The value to get the closest power of two from. + * @return {number} The closest number that is a power of two. + */ + getNextPowerOfTwo: function (value) { + + if (value > 0 && (value & (value - 1)) === 0) + { + // http://goo.gl/D9kPj + return value; + } + else + { + var result = 1; + + while (result < value) + { + result <<= 1; + } + + return result; + } + + }, + + /** + * Checks if the given dimensions make a power of two texture. + * + * @method Phaser.Math#isPowerOfTwo + * @param {number} width - The width to check. + * @param {number} height - The height to check. + * @return {boolean} True if the width and height are a power of two. + */ + isPowerOfTwo: function (width, height) { + + return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); + + }, + + /** + * Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#random + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} A floating point number between min (inclusive) and max (exclusive). + */ + random: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + return (Math.random() * (max - min) + min); + + }, + + /** + * Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#between + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} An integer between min (inclusive) and max (inclusive). + */ + between: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + min = Math.ceil(min); + max = Math.floor(max); + + return Math.floor(Math.random() * (max - min + 1)) + min; + + }, + + /** + * Two number are fuzzyEqual if their difference is less than epsilon. + * + * @method Phaser.Math#fuzzyEqual + * @param {number} a - The first number to compare. + * @param {number} b - The second number to compare. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {boolean} True if |a-b|b+epsilon + */ + fuzzyGreaterThan: function (a, b, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return a > b - epsilon; + + }, + + /** + * Applies a fuzzy ceil to the given value. + * + * @method Phaser.Math#fuzzyCeil + * @param {number} val - The value to ceil. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} ceiling(val-epsilon) + */ + fuzzyCeil: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.ceil(val - epsilon); + + }, + + /** + * Applies a fuzzy floor to the given value. + * + * @method Phaser.Math#fuzzyFloor + * @param {number} val - The value to floor. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} floor(val+epsilon) + */ + fuzzyFloor: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.floor(val + epsilon); + + }, + + /** + * Averages all values passed to the function and returns the result. + * + * @method Phaser.Math#average + * @params {...number} The numbers to average + * @return {number} The average of all given values. + */ + average: function () { + + var sum = 0; + var len = arguments.length; + + for (var i = 0; i < len; i++) + { + sum += (+arguments[i]); + } + + return sum / len; + + }, + + /** + * @method Phaser.Math#shear + * @param {number} n + * @return {number} n mod 1 + */ + shear: function (n) { + + return n % 1; + + }, + + /** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. + * + * @method Phaser.Math#snapTo + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapTo: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.round(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. + * As will 14 snap to 10... but 16 will snap to 15. + * + * @method Phaser.Math#snapToFloor + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToFloor: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.floor(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. + * As will 14 will snap to 15... but 16 will snap to 20. + * + * @method Phaser.Math#snapToCeil + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToCeil: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.ceil(input / gap); + + return start + input; + + }, + + /** + * Round to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) === 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + * + * @method Phaser.Math#roundTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + roundTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.round(value * p) / p; + + }, + + /** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#floorTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + floorTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.floor(value * p) / p; + + }, + + /** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#ceilTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + ceilTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.ceil(value * p) / p; + + }, + + /** + * Rotates currentAngle towards targetAngle, taking the shortest rotation distance. + * The lerp argument is the amount to rotate by in this call. + * + * @method Phaser.Math#rotateToAngle + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * @return {number} The adjusted angle. + */ + rotateToAngle: function (currentAngle, targetAngle, lerp) { + + if (lerp === undefined) { lerp = 0.05; } + + if (currentAngle === targetAngle) + { + return currentAngle; + } + + if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (Phaser.Math.PI2 - lerp)) + { + currentAngle = targetAngle; + } + else + { + if (Math.abs(targetAngle - currentAngle) > Math.PI) + { + if (targetAngle < currentAngle) + { + targetAngle += Phaser.Math.PI2; + } + else + { + targetAngle -= Phaser.Math.PI2; + } + } + + if (targetAngle > currentAngle) + { + currentAngle += lerp; + } + else if (targetAngle < currentAngle) + { + currentAngle -= lerp; + } + } + + return currentAngle; + + }, + + /** + * Gets the shortest angle between `angle1` and `angle2`. + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method, and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * @method Phaser.Math#getShortestAngle + * @param {number} angle1 - The first angle. In the range -180 to 180. + * @param {number} angle2 - The second angle. In the range -180 to 180. + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ + getShortestAngle: function (angle1, angle2) { + + var difference = angle2 - angle1; + + if (difference === 0) + { + return 0; + } + + var times = Math.floor((difference - (-180)) / 360); + + return difference - (times * 360); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @method Phaser.Math#angleBetween + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetween: function (x1, y1, x2, y2) { + + return Math.atan2(y2 - y1, x2 - x1); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels + * down the screen. + * + * @method Phaser.Math#angleBetweenY + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetweenY: function (x1, y1, x2, y2) { + + return Math.atan2(x2 - x1, y2 - y1); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * @method Phaser.Math#angleBetweenPoints + * @param {Phaser.Point} point1 - The first point. + * @param {Phaser.Point} point2 - The second point. + * @return {number} The angle between the two points, in radians. + */ + angleBetweenPoints: function (point1, point2) { + + return Math.atan2(point2.y - point1.y, point2.x - point1.x); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * @method Phaser.Math#angleBetweenPointsY + * @param {Phaser.Point} point1 + * @param {Phaser.Point} point2 + * @return {number} The angle, in radians. + */ + angleBetweenPointsY: function (point1, point2) { + + return Math.atan2(point2.x - point1.x, point2.y - point1.y); + + }, + + /** + * Reverses an angle. + * @method Phaser.Math#reverseAngle + * @param {number} angleRad - The angle to reverse, in radians. + * @return {number} The reverse angle, in radians. + */ + reverseAngle: function (angleRad) { + + return this.normalizeAngle(angleRad + Math.PI, true); + + }, + + /** + * Normalizes an angle to the [0,2pi) range. + * @method Phaser.Math#normalizeAngle + * @param {number} angleRad - The angle to normalize, in radians. + * @return {number} The angle, fit within the [0,2pi] range, in radians. + */ + normalizeAngle: function (angleRad) { + + angleRad = angleRad % (2 * Math.PI); + return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI; + + }, + + /** + * Adds the given amount to the value, but never lets the value go over the specified maximum. + * + * @method Phaser.Math#maxAdd + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The new value. + */ + maxAdd: function (value, amount, max) { + + return Math.min(value + amount, max); + + }, + + /** + * Subtracts the given amount from the value, but never lets the value go below the specified minimum. + * + * @method Phaser.Math#minSub + * @param {number} value - The base value. + * @param {number} amount - The amount to subtract from the base value. + * @param {number} min - The minimum the value is allowed to be. + * @return {number} The new value. + */ + minSub: function (value, amount, min) { + + return Math.max(value - amount, min); + + }, + + /** + * Ensures that the value always stays between min and max, by wrapping the value around. + * + * If `max` is not larger than `min` the result is 0. + * + * @method Phaser.Math#wrap + * @param {number} value - The value to wrap. + * @param {number} min - The minimum the value is allowed to be. + * @param {number} max - The maximum the value is allowed to be, should be larger than `min`. + * @return {number} The wrapped value. + */ + wrap: function (value, min, max) { + + var range = max - min; + + if (range <= 0) + { + return 0; + } + + var result = (value - min) % range; + + if (result < 0) + { + result += range; + } + + return result + min; + + }, + + /** + * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. + * + * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. + * + * @method Phaser.Math#wrapValue + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The wrapped value. + */ + wrapValue: function (value, amount, max) { + + var diff; + value = Math.abs(value); + amount = Math.abs(amount); + max = Math.abs(max); + diff = (value + amount) % max; + + return diff; + + }, + + /** + * Returns true if the number given is odd. + * + * @method Phaser.Math#isOdd + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is odd. False if the given number is even. + */ + isOdd: function (n) { + + // Does not work with extremely large values + return !!(n & 1); + + }, + + /** + * Returns true if the number given is even. + * + * @method Phaser.Math#isEven + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is even. False if the given number is odd. + */ + isEven: function (n) { + + // Does not work with extremely large values + return !(n & 1); + + }, + + /** + * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.min` function when appropriate. + * + * @method Phaser.Math#min + * @return {number} The lowest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + 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; i < len; i++) + { + if (data[i] < data[min]) + { + min = i; + } + } + + return data[min]; + + }, + + /** + * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.max` function when appropriate. + * + * @method Phaser.Math#max + * @return {number} The largest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + max: function () { + + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + var data = arguments[0]; + } + else + { + var data = arguments; + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i] > data[max]) + { + max = i; + } + } + + return data[max]; + + }, + + /** + * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. + * It will find the lowest matching property value from the given objects. + * + * @method Phaser.Math#minProperty + * @return {number} The lowest value from those given. + */ + 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; i < len; i++) + { + if (data[i][property] < data[min][property]) + { + min = i; + } + } + + return data[min][property]; + + }, + + /** + * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. + * It will find the largest matching property value from the given objects. + * + * @method Phaser.Math#maxProperty + * @return {number} The largest value from those given. + */ + maxProperty: function (property) { + + if (arguments.length === 2 && typeof arguments[1] === 'object') + { + var data = arguments[1]; + } + else + { + var data = arguments.slice(1); + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i][property] > data[max][property]) + { + max = i; + } + } + + return data[max][property]; + + }, + + /** + * Keeps an angle value between -180 and +180; or -PI and PI if radians. + * + * @method Phaser.Math#wrapAngle + * @param {number} angle - The angle value to wrap + * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected. + * @return {number} The new angle value; will be the same as the input angle if it was within bounds. + */ + wrapAngle: function (angle, radians) { + + return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180); + + }, + + /** + * A Linear Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#linearInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + linearInterpolation: function (v, k) { + + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (k < 0) + { + return this.linear(v[0], v[1], f); + } + + if (k > 1) + { + return this.linear(v[m], v[m - 1], m - f); + } + + return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); + + }, + + /** + * A Bezier Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#bezierInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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; + + }, + + /** + * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#catmullRomInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + } + + }, + + /** + * Calculates a linear (interpolation) value over t. + * + * @method Phaser.Math#linear + * @param {number} p0 + * @param {number} p1 + * @param {number} t - A value between 0 and 1. + * @return {number} + */ + linear: function (p0, p1, t) { + + return (p1 - p0) * t + p0; + + }, + + /** + * @method Phaser.Math#bernstein + * @protected + * @param {number} n + * @param {number} i + * @return {number} + */ + bernstein: function (n, i) { + + return this.factorial(n) / this.factorial(i) / this.factorial(n - i); + + }, + + /** + * @method Phaser.Math#factorial + * @param {number} value - the number you want to evaluate + * @return {number} + */ + factorial: function (value) { + + if (value === 0) + { + return 1; + } + + var res = value; + + while(--value) + { + res *= value; + } + + return res; + + }, + + /** + * Calculates a catmum rom value. + * + * @method Phaser.Math#catmullRom + * @protected + * @param {number} p0 + * @param {number} p1 + * @param {number} p2 + * @param {number} p3 + * @param {number} t + * @return {number} + */ + catmullRom: function (p0, p1, p2, p3, t) { + + var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + + }, + + /** + * The absolute difference between two values. + * + * @method Phaser.Math#difference + * @param {number} a - The first value to check. + * @param {number} b - The second value to check. + * @return {number} The absolute difference between the two values. + */ + difference: function (a, b) { + + return Math.abs(a - b); + + }, + + /** + * Round to the next whole number _away_ from zero. + * + * @method Phaser.Math#roundAwayFromZero + * @param {number} value - Any number. + * @return {integer} The rounded value of that number. + */ + roundAwayFromZero: function (value) { + + // "Opposite" of truncate. + return (value > 0) ? Math.ceil(value) : Math.floor(value); + + }, + + /** + * Generate a sine and cosine table simultaneously and extremely quickly. + * The parameters allow you to specify the length, amplitude and frequency of the wave. + * This generator is fast enough to be used in real-time. + * Code based on research by Franky of scene.at + * + * @method Phaser.Math#sinCosGenerator + * @param {number} length - The length of the wave + * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} frequency - The frequency of the sine and cosine table data + * @return {{sin:number[], cos:number[]}} Returns the table data. + */ + sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) { + + if (sinAmplitude === undefined) { sinAmplitude = 1.0; } + if (cosAmplitude === undefined) { cosAmplitude = 1.0; } + if (frequency === undefined) { frequency = 1.0; } + + var sin = sinAmplitude; + var cos = cosAmplitude; + var frq = frequency * Math.PI / length; + + var cosTable = []; + var sinTable = []; + + for (var c = 0; c < length; c++) { + + cos -= sin * frq; + sin += cos * frq; + + cosTable[c] = cos; + sinTable[c] = sin; + + } + + return { sin: sinTable, cos: cosTable, length: length }; + + }, + + /** + * Returns the length of the hypotenuse connecting two segments of given lengths. + * + * @method Phaser.Math#hypot + * @param {number} a + * @param {number} b + * @return {number} The length of the hypotenuse connecting the given lengths. + */ + hypot: function (a, b) { + + return Math.sqrt(a * a + b * b); + + }, + + /** + * Returns the euclidian distance between the two given set of coordinates. + * + * @method Phaser.Math#distance + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance between the two sets of coordinates. + */ + distance: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Returns the euclidean distance squared between the two given set of + * coordinates (cuts out a square root operation before returning). + * + * @method Phaser.Math#distanceSq + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance squared between the two sets of coordinates. + */ + distanceSq: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return dx * dx + dy * dy; + + }, + + /** + * Returns the distance between the two given set of coordinates at the power given. + * + * @method Phaser.Math#distancePow + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} [pow=2] + * @return {number} The distance between the two sets of coordinates. + */ + distancePow: function (x1, y1, x2, y2, pow) { + + if (pow === undefined) { pow = 2; } + + return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); + + }, + + /** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @method Phaser.Math#clamp + * @param {float} v - The value to be clamped. + * @param {float} min - The minimum bounds. + * @param {float} max - The maximum bounds. + * @return {number} The clamped value. + */ + clamp: function (v, min, max) { + + if (v < min) + { + return min; + } + else if (max < v) + { + return max; + } + else + { + return v; + } + + }, + + /** + * Clamp `x` to the range `[a, Infinity)`. + * Roughly the same as `Math.max(x, a)`, except for NaN handling. + * + * @method Phaser.Math#clampBottom + * @param {number} x + * @param {number} a + * @return {number} + */ + clampBottom: function (x, a) { + + return x < a ? a : x; + + }, + + /** + * Checks if two values are within the given tolerance of each other. + * + * @method Phaser.Math#within + * @param {number} a - The first number to check + * @param {number} b - The second number to check + * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range. + * @return {boolean} True if a is <= tolerance of b. + * @see {@link Phaser.Math.fuzzyEqual} + */ + within: function (a, b, tolerance) { + + return (Math.abs(a - b) <= tolerance); + + }, + + /** + * Linear mapping from range to range + * + * @method Phaser.Math#mapLinear + * @param {number} x - The value to map + * @param {number} a1 - First endpoint of the range + * @param {number} a2 - Final endpoint of the range + * @param {number} b1 - First endpoint of the range + * @param {number} b2 - Final endpoint of the range + * @return {number} + */ + mapLinear: function (x, a1, a2, b1, b2) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + + }, + + /** + * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smoothstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smoothstep: function (x, min, max) { + + // Scale, bias and saturate x to 0..1 range + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + // Evaluate polynomial + return x * x * (3 - 2 * x); + + }, + + /** + * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smootherstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smootherstep: function (x, min, max) { + + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + return x * x * x * (x * (x * 6 - 15) + 10); + + }, + + /** + * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. + * + * This works differently from `Math.sign` for values of NaN and -0, etc. + * + * @method Phaser.Math#sign + * @param {number} x + * @return {integer} An integer in {-1, 0, 1} + */ + sign: function (x) { + + return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); + + }, + + /** + * Work out what percentage value `a` is of value `b` using the given base. + * + * @method Phaser.Math#percent + * @param {number} a - The value to work out the percentage for. + * @param {number} b - The value you wish to get the percentage of. + * @param {number} [base=0] - The base value. + * @return {number} The percentage a is of b, between 0 and 1. + */ + percent: function (a, b, base) { + + if (base === undefined) { base = 0; } + + if (a > b || base > b) + { + return 1; + } + else if (a < base || base > a) + { + return 0; + } + else + { + return (a - base) / b; + } + + } + +}; + +/* jshint noempty: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An extremely useful repeatable random data generator. +* +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. +* +* The random number genererator is based on the Alea PRNG, but is modified. +* - https://github.com/coverslide/node-alea +* - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror +* - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404) +* +* @class Phaser.RandomDataGenerator +* @constructor +* @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}). +*/ +Phaser.RandomDataGenerator = function (seeds) { + + if (seeds === undefined) { seeds = []; } + + /** + * @property {number} c - Internal var. + * @private + */ + this.c = 1; + + /** + * @property {number} s0 - Internal var. + * @private + */ + this.s0 = 0; + + /** + * @property {number} s1 - Internal var. + * @private + */ + this.s1 = 0; + + /** + * @property {number} s2 - Internal var. + * @private + */ + this.s2 = 0; + + if (typeof seeds === 'string') + { + this.state(seeds); + } + else + { + this.sow(seeds); + } + +}; + +Phaser.RandomDataGenerator.prototype = { + + /** + * Private random helper. + * + * @method Phaser.RandomDataGenerator#rnd + * @private + * @return {number} + */ + rnd: function () { + + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + + return this.s2; + }, + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.RandomDataGenerator#sow + * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used. + */ + sow: function (seeds) { + + // Always reset to default seed + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + this.c = 1; + + if (!seeds) + { + return; + } + + // Apply any seeds + for (var i = 0; i < seeds.length && (seeds[i] != null); i++) + { + var 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); + } + + }, + + /** + * Internal method that creates a seed hash. + * + * @method Phaser.RandomDataGenerator#hash + * @private + * @param {any} data + * @return {number} hashed value. + */ + hash: function (data) { + + var h, i, n; + n = 0xefc8249d; + data = data.toString(); + + for (i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } + + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + + }, + + /** + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#integer + * @return {number} A random integer between 0 and 2^32. + */ + integer: function() { + + return this.rnd.apply(this) * 0x100000000;// 2^32 + + }, + + /** + * Returns a random real number between 0 and 1. + * + * @method Phaser.RandomDataGenerator#frac + * @return {number} A random real number between 0 and 1. + */ + frac: function() { + + return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 + + }, + + /** + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#real + * @return {number} A random real number between 0 and 2^32. + */ + real: function() { + + return this.integer() + this.frac(); + + }, + + /** + * Returns a random integer between and including min and max. + * + * @method Phaser.RandomDataGenerator#integerInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + integerInRange: function (min, max) { + + return Math.floor(this.realInRange(0, max - min + 1) + min); + + }, + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.RandomDataGenerator#between + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + between: function (min, max) { + + return this.integerInRange(min, max); + + }, + + /** + * Returns a random real number between min and max. + * + * @method Phaser.RandomDataGenerator#realInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + realInRange: function (min, max) { + + return this.frac() * (max - min) + min; + + }, + + /** + * Returns a random real number between -1 and 1. + * + * @method Phaser.RandomDataGenerator#normal + * @return {number} A random real number between -1 and 1. + */ + normal: function () { + + return 1 - 2 * this.frac(); + + }, + + /** + * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 + * + * @method Phaser.RandomDataGenerator#uuid + * @return {string} A valid RFC4122 version4 ID hex string + */ + 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; + + }, + + /** + * Returns a random member of `array`. + * + * @method Phaser.RandomDataGenerator#pick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + pick: function (ary) { + + return ary[this.integerInRange(0, ary.length - 1)]; + + }, + + /** + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.RandomDataGenerator#sign + * @return {number} -1 or +1. + */ + sign: function () { + + return this.pick([-1, 1]); + + }, + + /** + * Returns a random member of `array`, favoring the earlier entries. + * + * @method Phaser.RandomDataGenerator#weightedPick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + weightedPick: function (ary) { + + return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)]; + + }, + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.RandomDataGenerator#timestamp + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random timestamp between min and max. + */ + timestamp: function (min, max) { + + return this.realInRange(min || 946684800000, max || 1577862000000); + + }, + + /** + * Returns a random angle between -180 and 180. + * + * @method Phaser.RandomDataGenerator#angle + * @return {number} A random number between -180 and 180. + */ + angle: function() { + + return this.integerInRange(-180, 180); + + }, + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.RandomDataGenerator#state + * @param {string} [state] - Generator state to be set. + * @return {string} The current state of the generator. + */ + state: function (state) { + + if (typeof state === 'string' && state.match(/^!rnd/)) + { + state = state.split(','); + + this.c = parseFloat(state[1]); + this.s0 = parseFloat(state[2]); + this.s1 = parseFloat(state[3]); + this.s2 = parseFloat(state[4]); + } + + return ['!rnd', this.c, this.s0, this.s1, this.s2].join(','); + + } + +}; + +Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator; + +/** + * @author Timo Hausmann + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** +* A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. +* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. +* Original version at https://github.com/timohausmann/quadtree-js/ +* +* @class Phaser.QuadTree +* @constructor +* @param {number} x - The top left coordinate of the quadtree. +* @param {number} y - The top left coordinate of the quadtree. +* @param {number} width - The width of the quadtree in pixels. +* @param {number} height - The height of the quadtree in pixels. +* @param {number} [maxObjects=10] - The maximum number of objects per node. +* @param {number} [maxLevels=4] - The maximum number of levels to iterate to. +* @param {number} [level=0] - Which level is this? +*/ +Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) { + + /** + * @property {number} maxObjects - The maximum number of objects per node. + * @default + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - The maximum number of levels to break down to. + * @default + */ + this.maxLevels = 4; + + /** + * @property {number} level - The current level. + */ + this.level = 0; + + /** + * @property {object} bounds - Object that contains the quadtree bounds. + */ + this.bounds = {}; + + /** + * @property {array} objects - Array of quadtree children. + */ + this.objects = []; + + /** + * @property {array} nodes - Array of associated child nodes. + */ + this.nodes = []; + + /** + * @property {array} _empty - Internal empty array. + * @private + */ + this._empty = []; + + this.reset(x, y, width, height, maxObjects, maxLevels, level); + +}; + +Phaser.QuadTree.prototype = { + + /** + * Resets the QuadTree. + * + * @method Phaser.QuadTree#reset + * @param {number} x - The top left coordinate of the quadtree. + * @param {number} y - The top left coordinate of the quadtree. + * @param {number} width - The width of the quadtree in pixels. + * @param {number} height - The height of the quadtree in pixels. + * @param {number} [maxObjects=10] - The maximum number of objects per node. + * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. + * @param {number} [level=0] - Which level is this? + */ + 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; + + }, + + /** + * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. + * + * @method Phaser.QuadTree#populate + * @param {Phaser.Group} group - The Group to add to the quadtree. + */ + populate: function (group) { + + group.forEach(this.populateHandler, this, true); + + }, + + /** + * Handler for the populate method. + * + * @method Phaser.QuadTree#populateHandler + * @param {Phaser.Sprite|object} sprite - The Sprite to check. + */ + populateHandler: function (sprite) { + + if (sprite.body && sprite.exists) + { + this.insert(sprite.body); + } + + }, + + /** + * Split the node into 4 subnodes + * + * @method Phaser.QuadTree#split + */ + split: function () { + + // top right node + this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // top left node + this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom left node + this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom right node + this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + }, + + /** + * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. + * + * @method Phaser.QuadTree#insert + * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. + */ + insert: function (body) { + + var i = 0; + var index; + + // if we have subnodes ... + 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.level < this.maxLevels) + { + // Split if we don't already have subnodes + if (this.nodes[0] == null) + { + this.split(); + } + + // Add objects to subnodes + while (i < this.objects.length) + { + index = this.getIndex(this.objects[i]); + + if (index !== -1) + { + // this is expensive - see what we can do about it + this.nodes[index].insert(this.objects.splice(i, 1)[0]); + } + else + { + i++; + } + } + } + + }, + + /** + * Determine which node the object belongs to. + * + * @method Phaser.QuadTree#getIndex + * @param {Phaser.Rectangle|object} rect - The bounds in which to check. + * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. + */ + getIndex: function (rect) { + + // default is that rect doesn't fit, i.e. it straddles the internal quadrants + var index = -1; + + if (rect.x < this.bounds.right && rect.right < this.bounds.right) + { + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-left quadrant of this quadtree + index = 1; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-left quadrant of this quadtree + index = 2; + } + } + else if (rect.x > this.bounds.right) + { + // rect can completely fit within the right quadrants + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-right quadrant of this quadtree + index = 0; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-right quadrant of this quadtree + index = 3; + } + } + + return index; + + }, + + /** + * Return all objects that could collide with the given Sprite or Rectangle. + * + * @method Phaser.QuadTree#retrieve + * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle. + * @return {array} - Array with all detected objects. + */ + 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 rect fits into a subnode .. + if (index !== -1) + { + returnObjects = returnObjects.concat(this.nodes[index].retrieve(source)); + } + else + { + // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed) + 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 the quadtree. + * @method Phaser.QuadTree#clear + */ + 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; + +/** +* Javascript QuadTree +* @version 1.0 +* +* @version 1.3, March 11th 2014 +* @author Richard Davey +* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked +* it massively to add node indexing, removed lots of temp. var creation and significantly +* increased performance as a result. +* +* Original version at https://github.com/timohausmann/quadtree-js/ +*/ + +/** +* @copyright © 2012 Timo Hausmann +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. +* +* @class Phaser.Net +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Net = function (game) { + + this.game = game; + +}; + +Phaser.Net.prototype = { + + /** + * Returns the hostname given by the browser. + * + * @method Phaser.Net#getHostName + * @return {string} + */ + getHostName: function () { + + if (window.location && window.location.hostname) { + return window.location.hostname; + } + + return null; + + }, + + /** + * Compares the given domain name against the hostname of the browser containing the game. + * If the domain name is found it returns true. + * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. + * Do not include 'http://' at the start. + * + * @method Phaser.Net#checkDomainName + * @param {string} domain + * @return {boolean} true if the given domain fragment can be found in the window.location.hostname + */ + checkDomainName: function (domain) { + return window.location.hostname.indexOf(domain) !== -1; + }, + + /** + * Updates a value on the Query String and returns it in full. + * If the value doesn't already exist it is set. + * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. + * Optionally you can redirect to the new url, or just return it as a string. + * + * @method Phaser.Net#updateQueryString + * @param {string} key - The querystring key to update. + * @param {string} value - The new value to be set. If it already exists it will be replaced. + * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. + * @param {string} url - The URL to modify. If none is given it uses window.location.href. + * @return {string} If redirect is false then the modified url and query string is returned. + */ + updateQueryString: function (key, value, redirect, url) { + + if (redirect === undefined) { redirect = false; } + if (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; + } + + }, + + /** + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#getQueryString + * @param {string} [parameter=''] - If specified this will return just the value for that key. + * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. + */ + getQueryString: function (parameter) { + + if (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 && parameter === this.decodeURI(key[0])) + { + return this.decodeURI(key[1]); + } + else + { + output[this.decodeURI(key[0])] = this.decodeURI(key[1]); + } + } + } + + return output; + + }, + + /** + * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and + * decodes it, replacing \ with spaces in the return. Used internally by the Net classes. + * + * @method Phaser.Net#decodeURI + * @param {string} value - The URI component to be decoded. + * @return {string} The decoded value. + */ + decodeURI: function (value) { + return decodeURIComponent(value.replace(/\+/g, " ")); + } + +}; + +Phaser.Net.prototype.constructor = Phaser.Net; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. +* Tweens are hooked into the game clock and pause system, adjusting based on the game state. +* +* TweenManager is based heavily on tween.js by http://soledadpenades.com. +* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. +* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. +* Please see https://github.com/sole/tween.js for a full list of contributors. +* +* @class Phaser.TweenManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.TweenManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * @property {boolean} frameBased + * @default + */ + this.frameBased = false; + + /** + * @property {array} _tweens - All of the currently running tweens. + * @private + */ + this._tweens = []; + + /** + * @property {array} _add - All of the tweens queued to be added in the next update. + * @private + */ + this._add = []; + + this.easeMap = { + + "Power0": Phaser.Easing.Power0, + "Power1": Phaser.Easing.Power1, + "Power2": Phaser.Easing.Power2, + "Power3": Phaser.Easing.Power3, + "Power4": Phaser.Easing.Power4, + + "Linear": Phaser.Easing.Linear.None, + "Quad": Phaser.Easing.Quadratic.Out, + "Cubic": Phaser.Easing.Cubic.Out, + "Quart": Phaser.Easing.Quartic.Out, + "Quint": Phaser.Easing.Quintic.Out, + "Sine": Phaser.Easing.Sinusoidal.Out, + "Expo": Phaser.Easing.Exponential.Out, + "Circ": Phaser.Easing.Circular.Out, + "Elastic": Phaser.Easing.Elastic.Out, + "Back": Phaser.Easing.Back.Out, + "Bounce": Phaser.Easing.Bounce.Out, + + "Quad.easeIn": Phaser.Easing.Quadratic.In, + "Cubic.easeIn": Phaser.Easing.Cubic.In, + "Quart.easeIn": Phaser.Easing.Quartic.In, + "Quint.easeIn": Phaser.Easing.Quintic.In, + "Sine.easeIn": Phaser.Easing.Sinusoidal.In, + "Expo.easeIn": Phaser.Easing.Exponential.In, + "Circ.easeIn": Phaser.Easing.Circular.In, + "Elastic.easeIn": Phaser.Easing.Elastic.In, + "Back.easeIn": Phaser.Easing.Back.In, + "Bounce.easeIn": Phaser.Easing.Bounce.In, + + "Quad.easeOut": Phaser.Easing.Quadratic.Out, + "Cubic.easeOut": Phaser.Easing.Cubic.Out, + "Quart.easeOut": Phaser.Easing.Quartic.Out, + "Quint.easeOut": Phaser.Easing.Quintic.Out, + "Sine.easeOut": Phaser.Easing.Sinusoidal.Out, + "Expo.easeOut": Phaser.Easing.Exponential.Out, + "Circ.easeOut": Phaser.Easing.Circular.Out, + "Elastic.easeOut": Phaser.Easing.Elastic.Out, + "Back.easeOut": Phaser.Easing.Back.Out, + "Bounce.easeOut": Phaser.Easing.Bounce.Out, + + "Quad.easeInOut": Phaser.Easing.Quadratic.InOut, + "Cubic.easeInOut": Phaser.Easing.Cubic.InOut, + "Quart.easeInOut": Phaser.Easing.Quartic.InOut, + "Quint.easeInOut": Phaser.Easing.Quintic.InOut, + "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut, + "Expo.easeInOut": Phaser.Easing.Exponential.InOut, + "Circ.easeInOut": Phaser.Easing.Circular.InOut, + "Elastic.easeInOut": Phaser.Easing.Elastic.InOut, + "Back.easeInOut": Phaser.Easing.Back.InOut, + "Bounce.easeInOut": Phaser.Easing.Bounce.InOut + + }; + + this.game.onPause.add(this._pauseAll, this); + this.game.onResume.add(this._resumeAll, this); + +}; + +Phaser.TweenManager.prototype = { + + /** + * Get all the tween objects in an array. + * @method Phaser.TweenManager#getAll + * @returns {Phaser.Tween[]} Array with all tween objects. + */ + getAll: function () { + + return this._tweens; + + }, + + /** + * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. + * @method Phaser.TweenManager#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._tweens.length; i++) + { + this._tweens[i].pendingDelete = true; + } + + this._add = []; + + }, + + /** + * Remove all tweens from a specific object, array of objects or Group. + * + * @method Phaser.TweenManager#removeFrom + * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. + * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. + */ + removeFrom: function (obj, children) { + + if (children === undefined) { children = true; } + + var i; + var len; + + if (Array.isArray(obj)) + { + for (i = 0, len = obj.length; i < len; i++) + { + this.removeFrom(obj[i]); + } + } + else if (obj.type === Phaser.GROUP && children) + { + for (var i = 0, len = obj.children.length; i < len; i++) + { + this.removeFrom(obj.children[i]); + } + } + else + { + for (i = 0, len = this._tweens.length; i < len; i++) + { + if (obj === this._tweens[i].target) + { + this.remove(this._tweens[i]); + } + } + + for (i = 0, len = this._add.length; i < len; i++) + { + if (obj === this._add[i].target) + { + this.remove(this._add[i]); + } + } + } + + }, + + /** + * Add a new tween into the TweenManager. + * + * @method Phaser.TweenManager#add + * @param {Phaser.Tween} tween - The tween object you want to add. + * @returns {Phaser.Tween} The tween object you added to the manager. + */ + add: function (tween) { + + tween._manager = this; + this._add.push(tween); + + }, + + /** + * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.TweenManager#create + * @param {object} object - Object the tween will be run on. + * @returns {Phaser.Tween} The newly created tween object. + */ + create: function (object) { + + return new Phaser.Tween(object, this.game, this); + + }, + + /** + * Remove a tween from this manager. + * + * @method Phaser.TweenManager#remove + * @param {Phaser.Tween} tween - The tween object you want to remove. + */ + remove: function (tween) { + + var i = this._tweens.indexOf(tween); + + if (i !== -1) + { + this._tweens[i].pendingDelete = true; + } + else + { + i = this._add.indexOf(tween); + + if (i !== -1) + { + this._add[i].pendingDelete = true; + } + } + + }, + + /** + * Update all the tween objects you added to this manager. + * + * @method Phaser.TweenManager#update + * @returns {boolean} Return false if there's no tween to update, otherwise return true. + */ + update: function () { + + var addTweens = this._add.length; + var numTweens = this._tweens.length; + + if (numTweens === 0 && addTweens === 0) + { + return false; + } + + var i = 0; + + while (i < numTweens) + { + if (this._tweens[i].update(this.game.time.time)) + { + i++; + } + else + { + this._tweens.splice(i, 1); + + numTweens--; + } + } + + // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running + if (addTweens > 0) + { + this._tweens = this._tweens.concat(this._add); + this._add.length = 0; + } + + return true; + + }, + + /** + * Checks to see if a particular Sprite is currently being tweened. + * + * The `checkIsRunning` parameter will exclude tweens that have **just** completed or been stopped but haven't yet been removed from the manager. + * + * @method Phaser.TweenManager#isTweening + * @param {object} object - The object to check for tweens against. + * @param {boolean} [checkIsRunning=false] - Also check that the tween is running and is not marked for deletion. + * @returns {boolean} Returns true if the object is currently being tweened, false if not. + */ + isTweening: function(object, checkIsRunning) { + + if (!checkIsRunning) { checkIsRunning = false; } + + return this._tweens.some(function(tween) { + return (tween.target === object) && (!checkIsRunning || (tween.isRunning && !tween.pendingDelete)); + }); + + }, + + /** + * Private. Called by game focus loss. Pauses all currently running tweens. + * + * @method Phaser.TweenManager#_pauseAll + * @private + */ + _pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._pause(); + } + + }, + + /** + * Private. Called by game focus loss. Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#_resumeAll + * @private + */ + _resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._resume(); + } + + }, + + /** + * Pauses all currently running tweens. + * + * @method Phaser.TweenManager#pauseAll + */ + pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].pause(); + } + + }, + + /** + * Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#resumeAll + */ + resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].resume(true); + } + + } + +}; + +Phaser.TweenManager.prototype.constructor = Phaser.TweenManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tween allows you to alter one or more properties of a target object over a defined period of time. +* This can be used for things such as alpha fading Sprites, scaling them or motion. +* Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object +* by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and +* are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. +* +* @class Phaser.Tween +* @constructor +* @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. +* @param {Phaser.Game} game - Current game instance. +* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. +*/ +Phaser.Tween = function (target, game, manager) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. + */ + this.target = target; + + /** + * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween. + */ + this.manager = manager; + + /** + * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween. + */ + this.timeline = []; + + /** + * If set to `true` the current tween will play in reverse. + * If the tween hasn't yet started this has no effect. + * If there are child tweens then all child tweens will play in reverse from the current point. + * @property {boolean} reverse + * @default + */ + this.reverse = false; + + /** + * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. + * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. + * + * @property {number} timeScale + * @default + */ + this.timeScale = 1; + + /** + * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count. + */ + this.repeatCounter = 0; + + /** + * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager. + * @default + * @readonly + */ + this.pendingDelete = false; + + /** + * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onStart + */ + this.onStart = new Phaser.Signal(); + + /** + * The onLoop event is fired if the Tween, or any child tweens loop. + * It will be sent 2 parameters: the target object and this tween. + * + * @property {Phaser.Signal} onLoop + */ + this.onLoop = new Phaser.Signal(); + + /** + * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onRepeat + */ + this.onRepeat = new Phaser.Signal(); + + /** + * The onChildComplete event is fired when the Tween or any of its children completes. + * Fires every time a child completes unless a child is set to repeat forever. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onChildComplete + */ + this.onChildComplete = new Phaser.Signal(); + + /** + * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. + * @default + */ + this.isRunning = false; + + /** + * @property {number} current - The current Tween child being run. + * @default + * @readonly + */ + this.current = 0; + + /** + * @property {object} properties - Target property cache used when building the child data values. + */ + this.properties = {}; + + /** + * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it. + */ + this.chainedTween = null; + + /** + * @property {boolean} isPaused - Is this Tween paused or not? + * @default + */ + this.isPaused = false; + + /** + * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * + * The default value is whatever you've set in TweenManager.frameBased. + * + * @property {boolean} frameBased + * @default + */ + this.frameBased = manager.frameBased; + + /** + * @property {function} _onUpdateCallback - An onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallback = null; + + /** + * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallbackContext = null; + + /** + * @property {number} _pausedTime - Private pause timer. + * @private + * @default + */ + this._pausedTime = 0; + + /** + * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not. + * @private + */ + this._hasStarted = false; +}; + +/** +* A helper for tweening {@link Phaser.Color.createColor color objects}. +* +* It can be passed to {@link #onUpdateCallback}. +* +* ```javascript +* var color = Phaser.Color.createColor(255, 0, 0); // red +* +* var tween = game.add.tween(color).to({ +* r: 0, g: 0, b: 255 // blue +* }); +* +* tween.onUpdateCallback(Phaser.Tween.updateColor); +* +* tween.start(); +* ``` +* +* @method Phaser.Tween.updateColor +* @static +* @param {Phaser.Tween} tween - A Tween with a {@link #target} that is a {@link Phaser.Color.createColor color object}. +*/ +Phaser.Tween.updateColor = function (tween) { + + Phaser.Color.updateColor(tween.target); + +}; + +Phaser.Tween.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#to + * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined || duration <= 0) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.to cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#from + * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.from cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Starts the tween running. Can also be called by the `autoStart` parameter of {@link #to} or {@link #from}. + * This sets the {@link #isRunning} property to `true` and dispatches the {@link #onStart} signal. + * If the tween has a delay set then nothing will start tweening until the delay has expired. + * If the tween is already running, is flagged for deletion (such as after {@link #stop}), + * or has an empty timeline, calling start has no effect and the `onStart` signal is not dispatched. + * + * @method Phaser.Tween#start + * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + start: function (index) { + + if (index === undefined) { index = 0; } + + if (this.pendingDelete) + { + console.warn('Phaser.Tween.start cannot be called after Tween.stop'); + return this; + } + + if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning) + { + return this; + } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + this.manager.add(this); + + this.isRunning = true; + + if (index < 0 || index > this.timeline.length - 1) + { + index = 0; + } + + this.current = index; + + this.timeline[this.current].start(); + + return this; + + }, + + /** + * Stops the tween if running and flags it for deletion from the TweenManager. The tween can't be {@link #start restarted} after this. + * The {@link #onComplete} signal is not dispatched and no chained tweens are started unless the `complete` parameter is set to `true`. + * If you just wish to pause a tween then use {@link #pause} instead. + * If the tween is not running, it is **not** flagged for deletion and can be started again. + * + * @method Phaser.Tween#stop + * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + stop: function (complete) { + + if (complete === undefined) { complete = false; } + + this.isRunning = false; + + this._onUpdateCallback = null; + this._onUpdateCallbackContext = null; + + if (complete) + { + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + } + + this.manager.remove(this); + + return this; + + }, + + /** + * Updates either a single TweenData or all TweenData objects properties to the given value. + * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. + * The property is not checked, so if you pass an invalid one you'll generate a run-time error. + * + * @method Phaser.Tween#updateTweenData + * @param {string} property - The property to update. + * @param {number|function} value - The value to set the property to. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + updateTweenData: function (property, value, index) { + + if (this.timeline.length === 0) { return this; } + + if (index === undefined) { index = 0; } + + if (index === -1) + { + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i][property] = value; + } + } + else + { + this.timeline[index][property] = value; + } + + return this; + + }, + + /** + * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. + * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. + * If you have child tweens and pass -1 as the index value it sets the delay across all of them. + * + * @method Phaser.Tween#delay + * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + delay: function (duration, index) { + + return this.updateTweenData('delay', duration, index); + + }, + + /** + * Sets the number of times this tween will repeat. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. + * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. + * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. + * + * @method Phaser.Tween#repeat + * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeat: function (total, repeatDelay, index) { + + if (repeatDelay === undefined) { repeatDelay = 0; } + + this.updateTweenData('repeatCounter', total, index); + this.updateTweenData('repeatTotal', total, index); + + return this.updateTweenData('repeatDelay', repeatDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will repeat itself. + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#repeatDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatDelay: function (duration, index) { + + return this.updateTweenData('repeatDelay', duration, index); + + }, + + /** + * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. + * Used in combination with repeat you can create endless loops. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. + * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. + * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. + * + * @method Phaser.Tween#yoyo + * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo. + * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyo: function(enable, yoyoDelay, index) { + + if (yoyoDelay === undefined) { yoyoDelay = 0; } + + this.updateTweenData('yoyo', enable, index); + + return this.updateTweenData('yoyoDelay', yoyoDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#yoyoDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyoDelay: function (duration, index) { + + return this.updateTweenData('yoyoDelay', duration, index); + + }, + + /** + * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. + * + * @method Phaser.Tween#easing + * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + easing: function (ease, index) { + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + return this.updateTweenData('easingFunction', ease, index); + + }, + + /** + * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. + * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. + * The interpolation function is only used if the target properties is an array. + * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. + * + * @method Phaser.Tween#interpolation + * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) + * @param {object} [context] - The context under which the interpolation function will be run. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + interpolation: function (interpolation, context, index) { + + if (context === undefined) { context = Phaser.Math; } + + this.updateTweenData('interpolationFunction', interpolation, index); + + return this.updateTweenData('interpolationContext', context, index); + + }, + + /** + * Set how many times this tween and all of its children will repeat. + * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. + * + * @method Phaser.Tween#repeatAll + * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatAll: function (total) { + + if (total === undefined) { total = 0; } + + this.repeatCounter = total; + + return this; + + }, + + /** + * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called + * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. + * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. + * For that you should listen to `onComplete` on the final tween in your chain. + * + * If you pass multiple tweens to this method they will be joined into a single long chain. + * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. + * Any previously chained tweens that may have been set will be overwritten. + * + * @method Phaser.Tween#chain + * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + chain: function () { + + var i = arguments.length; + + while (i--) + { + if (i > 0) + { + arguments[i - 1].chainedTween = arguments[i]; + } + else + { + this.chainedTween = arguments[i]; + } + } + + return this; + + }, + + /** + * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. + * + * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. + * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. + * + * Usage: + * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) + * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) + * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) + * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) + * .loop(); + * @method Phaser.Tween#loop + * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + loop: function (value) { + + if (value === undefined) { value = true; } + + this.repeatCounter = (value) ? -1 : 0; + + return this; + + }, + + /** + * Sets a callback to be fired each time this tween updates. + * + * The callback receives the current Tween, the {@link Phaser.TweenData#value 'value' of the current TweenData}, and the current {@link Phaser.TweenData TweenData}. The second parameter is most useful. + * + * ```javascript + * tween.onUpdateCallback(function (tween, value, tweenData) { + * console.log('Tween running -- percent: %.2f value: %.2f', tweenData.percent, value); + * }); + * ``` + * + * @method Phaser.Tween#onUpdateCallback + * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. + * @param {object} callbackContext - The context in which to call the onUpdate callback. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + onUpdateCallback: function (callback, callbackContext) { + + this._onUpdateCallback = callback; + this._onUpdateCallbackContext = callbackContext; + + return this; + + }, + + /** + * Pauses the tween. Resume playback with Tween.resume. + * + * @method Phaser.Tween#pause + */ + pause: function () { + + this.isPaused = true; + + this._codePaused = true; + + this._pausedTime = this.game.time.time; + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * + * @private + * @method Phaser.Tween#_pause + */ + _pause: function () { + + if (!this._codePaused) + { + this.isPaused = true; + + this._pausedTime = this.game.time.time; + } + + }, + + /** + * Resumes a paused tween. + * + * @method Phaser.Tween#resume + */ + resume: function () { + + if (this.isPaused) + { + this.isPaused = false; + + this._codePaused = false; + + for (var i = 0; i < this.timeline.length; i++) + { + if (!this.timeline[i].isRunning) + { + this.timeline[i].startTime += (this.game.time.time - this._pausedTime); + } + } + } + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * @method Phaser.Tween#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Core tween update function called by the TweenManager. Does not need to be invoked directly. + * + * @method Phaser.Tween#update + * @param {number} time - A timestamp passed in by the TweenManager. + * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). + */ + update: function (time) { + + if (this.pendingDelete || !this.target) + { + return false; + } + + if (this.isPaused) + { + return true; + } + + var status = this.timeline[this.current].update(time); + + if (status === Phaser.TweenData.PENDING) + { + return true; + } + else if (status === Phaser.TweenData.RUNNING) + { + if (!this._hasStarted) + { + this.onStart.dispatch(this.target, this); + this._hasStarted = true; + } + + if (this._onUpdateCallback !== null) + { + this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]); + } + + // In case the update callback modifies this tween + return this.isRunning; + } + else if (status === Phaser.TweenData.LOOPED) + { + if (this.timeline[this.current].repeatCounter === -1) + { + this.onLoop.dispatch(this.target, this); + } + else + { + this.onRepeat.dispatch(this.target, this); + } + + return true; + } + else if (status === Phaser.TweenData.COMPLETE) + { + var complete = false; + + // What now? + if (this.reverse) + { + this.current--; + + if (this.current < 0) + { + this.current = this.timeline.length - 1; + complete = true; + } + } + else + { + this.current++; + + if (this.current === this.timeline.length) + { + this.current = 0; + complete = true; + } + } + + if (complete) + { + // We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it? + if (this.repeatCounter === -1) + { + this.timeline[this.current].start(); + this.onLoop.dispatch(this.target, this); + return true; + } + else if (this.repeatCounter > 0) + { + this.repeatCounter--; + + this.timeline[this.current].start(); + this.onRepeat.dispatch(this.target, this); + return true; + } + else + { + // No more repeats and no more children, so we're done + this.isRunning = false; + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + + return false; + } + } + else + { + // We've still got some children to go + this.onChildComplete.dispatch(this.target, this); + this.timeline[this.current].start(); + return true; + } + } + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * It ignores delay and repeat counts and any chained tweens, but does include child tweens. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.Tween#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate, data) { + + if (this.game === null || this.target === null) + { + return null; + } + + if (frameRate === undefined) { frameRate = 60; } + if (data === undefined) { data = []; } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + for (var i = 0; i < this.timeline.length; i++) + { + data = data.concat(this.timeline[i].generateData(frameRate)); + } + + return data; + + } + +}; + +/** +* @name Phaser.Tween#totalDuration +* @property {number} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds. +*/ +Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', { + + get: function () { + + var total = 0; + + for (var i = 0; i < this.timeline.length; i++) + { + total += this.timeline[i].duration; + } + + return total; + + } + +}); + +Phaser.Tween.prototype.constructor = Phaser.Tween; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the +* starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for +* TweenData objects and can contain multiple TweenData objects. +* +* @class Phaser.TweenData +* @constructor +* @param {Phaser.Tween} parent - The Tween that owns this TweenData object. +*/ +Phaser.TweenData = function (parent) { + + /** + * @property {Phaser.Tween} parent - The Tween which owns this TweenData. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = parent.game; + + /** + * @property {object} vStart - An object containing the values at the start of the tween. + * @private + */ + this.vStart = {}; + + /** + * @property {object} vStartCache - Cached starting values. + * @private + */ + this.vStartCache = {}; + + /** + * @property {object} vEnd - An object containing the values at the end of the tween. + * @private + */ + this.vEnd = {}; + + /** + * @property {object} vEndCache - Cached ending values. + * @private + */ + this.vEndCache = {}; + + /** + * @property {number} duration - The duration of the tween in ms. + * @default + */ + this.duration = 1000; + + /** + * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is. + * @readonly + */ + this.percent = 0; + + /** + * @property {number} value - The output of the easing function for the current {@link #percent}. Depending on the easing function, this will be within [0, 1] or a slightly larger range (e.g., Bounce). When easing is Linear, this will be identical to {@link #percent}. + * @readonly + */ + this.value = 0; + + /** + * @property {number} repeatCounter - If the Tween is set to repeat this is the number of repeats remaining (and `repeatTotal - repeatCounter` is the number of repeats completed). + */ + this.repeatCounter = 0; + + /** + * @property {number} repeatDelay - The amount of time in ms between repeats of this tween. + */ + this.repeatDelay = 0; + + /** + * @property {number} repeatTotal - The total number of times this Tween will repeat. + * @readonly + */ + this.repeatTotal = 0; + + /** + * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween) + * @default + * @todo Appears unused. + */ + this.interpolate = false; + + /** + * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false. + * @default + */ + this.yoyo = false; + + /** + * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween. + */ + this.yoyoDelay = 0; + + /** + * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). + * @default + */ + this.inReverse = false; + + /** + * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. + * @default + */ + this.delay = 0; + + /** + * @property {number} dt - Current time value. + */ + this.dt = 0; + + /** + * @property {number} startTime - The time the Tween started or null if it hasn't yet started. + */ + this.startTime = null; + + /** + * @property {function} easingFunction - The easing function used for the Tween. + * @default Phaser.Easing.Default + */ + this.easingFunction = Phaser.Easing.Default; + + /** + * @property {function} interpolationFunction - The interpolation function used for Array-based Tween. + * @default Phaser.Math.linearInterpolation + */ + this.interpolationFunction = Phaser.Math.linearInterpolation; + + /** + * @property {object} interpolationContext - The interpolation function context used for the Tween. + * @default Phaser.Math + */ + this.interpolationContext = Phaser.Math; + + /** + * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} isFrom - Is this a from tween or a to tween? + * @default + */ + this.isFrom = false; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.PENDING = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.RUNNING = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.LOOPED = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.COMPLETE = 3; + +Phaser.TweenData.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * + * @method Phaser.TweenData#to + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + to: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = false; + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * + * @method Phaser.TweenData#from + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + from: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = true; + + return this; + + }, + + /** + * Starts the Tween running. + * + * @method Phaser.TweenData#start + * @return {Phaser.TweenData} This Tween object. + */ + start: function () { + + this.startTime = this.game.time.time + this.delay; + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + if (this.delay > 0) + { + this.isRunning = false; + } + else + { + this.isRunning = true; + } + + if (this.isFrom) + { + // Reverse them all and instant set them + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + this.parent.target[property] = this.vStart[property]; + } + } + + this.value = 0; + this.repeatCounter = this.repeatTotal; + + return this; + + }, + + /** + * Loads the values from the target object into this Tween. + * + * @private + * @method Phaser.TweenData#loadValues + * @return {Phaser.TweenData} This Tween object. + */ + loadValues: function () { + + for (var property in this.parent.properties) + { + // Load the property from the parent object + this.vStart[property] = this.parent.properties[property]; + + // Check if an Array was provided as property value + if (Array.isArray(this.vEnd[property])) + { + if (this.vEnd[property].length === 0) + { + continue; + } + + if (this.percent === 0) + { + // Put the start value at the beginning of the array + // but we only want to do this once, if the Tween hasn't run before + this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]); + } + } + + if (typeof this.vEnd[property] !== 'undefined') + { + if (typeof this.vEnd[property] === 'string') + { + // Parses relative end values with start as base (e.g.: +10, -3) + this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10); + } + + this.parent.properties[property] = this.vEnd[property]; + } + else + { + // Null tween + this.vEnd[property] = this.vStart[property]; + } + + this.vStartCache[property] = this.vStart[property]; + this.vEndCache[property] = this.vEnd[property]; + } + + return this; + + }, + + /** + * Updates this Tween. This is called automatically by Phaser.Tween. + * + * @protected + * @method Phaser.TweenData#update + * @param {number} time - A timestamp passed in by the Tween parent. + * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. + */ + update: function (time) { + + if (!this.isRunning) + { + if (time >= this.startTime) + { + this.isRunning = true; + } + else + { + return Phaser.TweenData.PENDING; + } + } + else + { + // Is Running, but is waiting to repeat + if (time < this.startTime) + { + return Phaser.TweenData.RUNNING; + } + } + + var ms = (this.parent.frameBased) ? this.game.time.physicsElapsedMS : this.game.time.elapsedMS; + + if (this.parent.reverse) + { + this.dt -= ms * this.parent.timeScale; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += ms * this.parent.timeScale; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + this.parent.target[property] = start + ((end - start) * this.value); + } + } + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + return this.repeat(); + } + + return Phaser.TweenData.RUNNING; + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.TweenData#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate) { + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + var data = []; + var complete = false; + var fps = (1 / frameRate) * 1000; + + do + { + if (this.parent.reverse) + { + this.dt -= fps; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += fps; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + var blob = {}; + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + blob[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + blob[property] = start + ((end - start) * this.value); + } + } + + data.push(blob); + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + complete = true; + } + + } while (!complete); + + if (this.yoyo) + { + var reversed = data.slice(); + reversed.reverse(); + data = data.concat(reversed); + } + + return data; + + }, + + /** + * Checks if this Tween is meant to repeat or yoyo and handles doing so. + * + * @private + * @method Phaser.TweenData#repeat + * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE. + */ + repeat: function () { + + // If not a yoyo and repeatCounter = 0 then we're done + if (this.yoyo) + { + // We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end + if (this.inReverse && this.repeatCounter === 0) + { + // Restore the properties + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + this.inReverse = false; + + return Phaser.TweenData.COMPLETE; + } + + this.inReverse = !this.inReverse; + } + else + { + if (this.repeatCounter === 0) + { + return Phaser.TweenData.COMPLETE; + } + } + + if (this.inReverse) + { + // If inReverse we're going from vEnd to vStartCache + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + } + } + else + { + // If not inReverse we're just repopulating the cache again + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + // -1 means repeat forever, otherwise decrement the repeatCounter + // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total + if (this.repeatCounter > 0) + { + this.repeatCounter--; + } + } + + this.startTime = this.game.time.time; + + if (this.yoyo && this.inReverse) + { + this.startTime += this.yoyoDelay; + } + else if (!this.inReverse) + { + this.startTime += this.repeatDelay; + } + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + return Phaser.TweenData.LOOPED; + + } + +}; + +Phaser.TweenData.prototype.constructor = Phaser.TweenData; + +/* jshint curly: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of easing methods defining ease-in and ease-out curves. +* +* @class Phaser.Easing +*/ +Phaser.Easing = { + + /** + * Linear easing. + * + * @class Phaser.Easing.Linear + */ + Linear: { + + /** + * Linear Easing (no variation). + * + * @method Phaser.Easing.Linear#None + * @param {number} k - The value to be tweened. + * @returns {number} k. + */ + None: function ( k ) { + + return k; + + } + + }, + + /** + * Quadratic easing. + * + * @class Phaser.Easing.Quadratic + */ + Quadratic: { + + /** + * Ease-in. + * + * @method Phaser.Easing.Quadratic#In + * @param {number} k - The value to be tweened. + * @returns {number} k^2. + */ + In: function ( k ) { + + return k * k; + + }, + + /** + * Ease-out. + * + * @method Phaser.Easing.Quadratic#Out + * @param {number} k - The value to be tweened. + * @returns {number} k* (2-k). + */ + Out: function ( k ) { + + return k * ( 2 - k ); + + }, + + /** + * Ease-in/out. + * + * @method Phaser.Easing.Quadratic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; + return - 0.5 * ( --k * ( k - 2 ) - 1 ); + + } + + }, + + /** + * Cubic easing. + * + * @class Phaser.Easing.Cubic + */ + Cubic: { + + /** + * Cubic ease-in. + * + * @method Phaser.Easing.Cubic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k; + + }, + + /** + * Cubic ease-out. + * + * @method Phaser.Easing.Cubic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k + 1; + + }, + + /** + * Cubic ease-in/out. + * + * @method Phaser.Easing.Cubic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k + 2 ); + + } + + }, + + /** + * Quartic easing. + * + * @class Phaser.Easing.Quartic + */ + Quartic: { + + /** + * Quartic ease-in. + * + * @method Phaser.Easing.Quartic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k; + + }, + + /** + * Quartic ease-out. + * + * @method Phaser.Easing.Quartic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return 1 - ( --k * k * k * k ); + + }, + + /** + * Quartic ease-in/out. + * + * @method Phaser.Easing.Quartic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; + return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); + + } + + }, + + /** + * Quintic easing. + * + * @class Phaser.Easing.Quintic + */ + Quintic: { + + /** + * Quintic ease-in. + * + * @method Phaser.Easing.Quintic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k * k; + + }, + + /** + * Quintic ease-out. + * + * @method Phaser.Easing.Quintic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k * k * k + 1; + + }, + + /** + * Quintic ease-in/out. + * + * @method Phaser.Easing.Quintic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); + + } + + }, + + /** + * Sinusoidal easing. + * + * @class Phaser.Easing.Sinusoidal + */ + Sinusoidal: { + + /** + * Sinusoidal ease-in. + * + * @method Phaser.Easing.Sinusoidal#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 1 - Math.cos( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-out. + * + * @method Phaser.Easing.Sinusoidal#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return Math.sin( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-in/out. + * + * @method Phaser.Easing.Sinusoidal#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); + + } + + }, + + /** + * Exponential easing. + * + * @class Phaser.Easing.Exponential + */ + Exponential: { + + /** + * Exponential ease-in. + * + * @method Phaser.Easing.Exponential#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k === 0 ? 0 : Math.pow( 1024, k - 1 ); + + }, + + /** + * Exponential ease-out. + * + * @method Phaser.Easing.Exponential#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); + + }, + + /** + * Exponential ease-in/out. + * + * @method Phaser.Easing.Exponential#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); + return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); + + } + + }, + + /** + * Circular easing. + * + * @class Phaser.Easing.Circular + */ + Circular: { + + /** + * Circular ease-in. + * + * @method Phaser.Easing.Circular#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Math.sqrt( 1 - k * k ); + + }, + + /** + * Circular ease-out. + * + * @method Phaser.Easing.Circular#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return Math.sqrt( 1 - ( --k * k ) ); + + }, + + /** + * Circular ease-in/out. + * + * @method Phaser.Easing.Circular#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); + return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); + + } + + }, + + /** + * Elastic easing. + * + * @class Phaser.Easing.Elastic + */ + Elastic: { + + /** + * Elastic ease-in. + * + * @method Phaser.Easing.Elastic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + + }, + + /** + * Elastic ease-out. + * + * @method Phaser.Easing.Elastic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); + + }, + + /** + * Elastic ease-in/out. + * + * @method Phaser.Easing.Elastic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; + + } + + }, + + /** + * Back easing. + * + * @class Phaser.Easing.Back + */ + Back: { + + /** + * Back ease-in. + * + * @method Phaser.Easing.Back#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s = 1.70158; + return k * k * ( ( s + 1 ) * k - s ); + + }, + + /** + * Back ease-out. + * + * @method Phaser.Easing.Back#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s = 1.70158; + return --k * k * ( ( s + 1 ) * k + s ) + 1; + + }, + + /** + * Back ease-in/out. + * + * @method Phaser.Easing.Back#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s = 1.70158 * 1.525; + if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); + return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); + + } + + }, + + /** + * Bounce easing. + * + * @class Phaser.Easing.Bounce + */ + Bounce: { + + /** + * Bounce ease-in. + * + * @method Phaser.Easing.Bounce#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Phaser.Easing.Bounce.Out( 1 - k ); + + }, + + /** + * Bounce ease-out. + * + * @method Phaser.Easing.Bounce#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if ( k < ( 1 / 2.75 ) ) { + + return 7.5625 * k * k; + + } else if ( k < ( 2 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; + + } else if ( k < ( 2.5 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; + + } else { + + return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; + + } + + }, + + /** + * Bounce ease-in/out. + * + * @method Phaser.Easing.Bounce#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5; + return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5; + + } + + } + +}; + +Phaser.Easing.Default = Phaser.Easing.Linear.None; +Phaser.Easing.Power0 = Phaser.Easing.Linear.None; +Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out; +Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out; +Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out; +Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is the core internal game clock. +* +* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, +* and also handles the standard Timer pool. +* +* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}. +* +* There are different *types* of time in Phaser: +* +* - ***Game time*** always runs at the speed of time in real life. +* +* Unlike wall-clock time, *game time stops when Phaser is paused*. +* +* Game time is used for {@link Phaser.Timer timer events}. +* +* - ***Physics time*** represents the amount of time given to physics calculations. +* +* *When {@link #slowMotion} is in effect physics time runs slower than game time.* +* Like game time, physics time stops when Phaser is paused. +* +* Physics time is used for physics calculations and {@link Phaser.Tween tweens}. +* +* - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time. +* +* This time is independent of Phaser and always progresses, regardless of if Phaser is paused. +* +* @class Phaser.Time +* @constructor +* @param {Phaser.Game} game A reference to the currently running game. +*/ +Phaser.Time = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * The `Date.now()` value when the time was last updated. + * @property {integer} time + * @protected + */ + this.time = 0; + + /** + * The `now` when the previous update occurred. + * @property {number} prevTime + * @protected + */ + this.prevTime = 0; + + /** + * An increasing value representing cumulative milliseconds since an undisclosed epoch. + * + * While this value is in milliseconds and can be used to compute time deltas, + * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference. + * + * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; + * the value can only be relied upon within a particular game instance. + * + * @property {number} now + * @protected + */ + this.now = 0; + + /** + * Elapsed time since the last time update, in milliseconds, based on `now`. + * + * This value _may_ include time that the game is paused/inactive. + * + * While the game is active, this will be similar to (1000 / {@link #fps}). + * + * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {number} elapsed + * @see Phaser.Time.time + * @protected + */ + this.elapsed = 0; + + /** + * The time in ms since the last time update, in milliseconds, based on `time`. + * + * This value is corrected for game pauses and will be "about zero" after a game is resumed. + * + * _Note:_ This is updated once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {integer} elapsedMS + * @protected + */ + this.elapsedMS = 0; + + /** + * The physics update delta, in fractional seconds. + * + * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) + * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system + * is unable to consistently maintain the desired FPS. + * + * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. + * + * @property {number} physicsElapsed + */ + this.physicsElapsed = 1 / 60; + + /** + * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. + * + * @property {number} physicsElapsedMS + */ + this.physicsElapsedMS = (1 / 60) * 1000; + + /** + * The desiredFps multiplier as used by Game.update. + * @property {integer} desiredFpsMult + * @protected + */ + this.desiredFpsMult = 1.0 / 60; + + /** + * The desired frame rate of the game. + * + * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates. + * + * @property {number} _desiredFps + * @private + * @default + */ + this._desiredFps = 60; + + /** + * The suggested frame rate for your game, based on an averaged real frame rate. + * This value is only populated if `Time.advancedTiming` is enabled. + * + * _Note:_ This is not available until after a few frames have passed; until then + * it's set to the same value as desiredFps. + * + * @property {number} suggestedFps + * @default + */ + this.suggestedFps = this.desiredFps; + + /** + * Scaling factor to make the game move smoothly in slow motion (or fast motion) + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * You likely need to adjust {@link #desiredFps} as well such that `desiredFps / slowMotion === 60`. + * + * @property {number} slowMotion + * @default + */ + this.slowMotion = 1.0; + + /** + * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. This isn't expensive, but displaying it with {@link Phaser.Utils.Debug#text} can be, especially in WebGL mode. + * @property {boolean} advancedTiming + * @default + */ + this.advancedTiming = false; + + /** + * Advanced timing result: The number of animation frames received from the browser in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} frames + * @readonly + */ + this.frames = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateLogic logic updates} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} updates + * @readonly + */ + this.updates = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateRender renders} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} renders + * @readonly + */ + this.renders = 0; + + /** + * Advanced timing result: Frames per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} fps + * @readonly + */ + this.fps = 0; + + /** + * Advanced timing result: Logic updates per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} ups + * @readonly + */ + this.ups = 0; + + /** + * Advanced timing result: Renders per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} rps + * @readonly + */ + this.rps = 0; + + /** + * Advanced timing result: The lowest rate the fps has dropped to. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMin + */ + this.fpsMin = 1000; + + /** + * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMax + */ + this.fpsMax = 0; + + /** + * Advanced timing result: The minimum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMin + * @default + */ + this.msMin = 1000; + + /** + * Advanced timing result: The maximum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMax + */ + this.msMax = 0; + + /** + * Records how long the game was last paused, in milliseconds. + * (This is not updated until the game is resumed.) + * @property {number} pauseDuration + */ + this.pauseDuration = 0; + + /** + * @property {number} timeToCall - The value that setTimeout needs to work out when to next update + * @protected + */ + this.timeToCall = 0; + + /** + * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop + * @protected + */ + this.timeExpected = 0; + + /** + * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to. + * @property {Phaser.Timer} events + */ + this.events = new Phaser.Timer(this.game, false); + + /** + * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated + * @private + */ + this._frameCount = 0; + + /** + * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated + * @private + */ + this._elapsedAccumulator = 0; + + /** + * @property {number} _started - The time at which the Game instance started. + * @private + */ + this._started = 0; + + /** + * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. + * @private + */ + this._timeLastSecond = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {boolean} _justResumed - Internal value used to recover from the game pause state. + * @private + */ + this._justResumed = false; + + /** + * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects. + * @private + */ + this._timers = []; + +}; + +Phaser.Time.prototype = { + + /** + * Called automatically by Phaser.Game after boot. Should not be called directly. + * + * @method Phaser.Time#boot + * @protected + */ + boot: function () { + + this._started = Date.now(); + this.time = Date.now(); + this.events.start(); + this.timeExpected = this.time; + + }, + + /** + * Adds an existing Phaser.Timer object to the Timer pool. + * + * @method Phaser.Time#add + * @param {Phaser.Timer} timer - An existing Phaser.Timer object. + * @return {Phaser.Timer} The given Phaser.Timer object. + */ + add: function (timer) { + + this._timers.push(timer); + + return timer; + + }, + + /** + * Creates a new stand-alone Phaser.Timer object. + * + * @method Phaser.Time#create + * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). + * @return {Phaser.Timer} The Timer object that was created. + */ + create: function (autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + var timer = new Phaser.Timer(this.game, autoDestroy); + + this._timers.push(timer); + + return timer; + + }, + + /** + * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer. + * + * @method Phaser.Time#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._timers.length; i++) + { + this._timers[i].destroy(); + } + + this._timers = []; + + this.events.removeAll(); + + }, + + /** + * Refreshes the Time.time and Time.elapsedMS properties from the system clock. + * + * @method Phaser.Time#refresh + */ + refresh: function () { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + }, + + /** + * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. + * + * @method Phaser.Time#update + * @protected + * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}. + */ + update: function (time) { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + // 'now' is currently still holding the time of the last call, move it into prevTime + this.prevTime = this.now; + + // update 'now' to hold the current time + // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now) + this.now = time; + + // elapsed time between previous call and now - this could be a high resolution value + this.elapsed = this.now - this.prevTime; + + if (this.game.raf._isSetTimeOut) + { + // console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time); + + // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game + this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time))); + + // time when the next call is expected if using timers + this.timeExpected = time + this.timeToCall; + + // console.log('Time expect', this.timeExpected); + } + + if (this.advancedTiming) + { + this.updateAdvancedTiming(); + } + + // Paused but still running? + if (!this.game.paused) + { + // Our internal Phaser.Timer + this.events.update(this.time); + + if (this._timers.length) + { + this.updateTimers(); + } + } + + }, + + /** + * Handles the updating of the Phaser.Timers (if any) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateTimers + * @private + */ + updateTimers: function () { + + // Any game level timers + var i = 0; + var len = this._timers.length; + + while (i < len) + { + if (this._timers[i].update(this.time)) + { + i++; + } + else + { + // Timer requests to be removed + this._timers.splice(i, 1); + len--; + } + } + + }, + + /** + * Handles the updating of the advanced timing values (if enabled) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateAdvancedTiming + * @private + */ + updateAdvancedTiming: function () { + + // count the number of time.update calls + this._frameCount++; + this._elapsedAccumulator += this.elapsed; + + // occasionally recalculate the suggestedFps based on the accumulated elapsed time + if (this._frameCount >= this._desiredFps * 2) + { + // this formula calculates suggestedFps in multiples of 5 fps + this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5; + this._frameCount = 0; + this._elapsedAccumulator = 0; + } + + this.msMin = Math.min(this.msMin, this.elapsed); + this.msMax = Math.max(this.msMax, this.elapsed); + + this.frames++; + + if (this.now > this._timeLastSecond + 1000) + { + var interval = this.now - this._timeLastSecond; + this.fps = Math.round((this.frames * 1000) / interval); + this.ups = Math.round((this.updates * 1000) / interval); + this.rps = Math.round((this.renders * 1000) / interval); + this.fpsMin = Math.min(this.fpsMin, this.fps); + this.fpsMax = Math.max(this.fpsMax, this.fps); + this._timeLastSecond = this.now; + this.frames = 0; + this.updates = 0; + this.renders = 0; + } + + }, + + /** + * Counts one logic update (if advanced timing is enabled). + * + * @method Phaser.Time#countUpdate + * @private + */ + countUpdate: function () { + + if (this.advancedTiming) + { + this.updates++; + } + + }, + + /** + * Counts one render (if advanced timing is enabled). + * + * @method Phaser.Time#countRender + * @private + */ + countRender: function () { + + if (this.advancedTiming) + { + this.renders++; + } + + }, + + /** + * Called when the game enters a paused state. + * + * @method Phaser.Time#gamePaused + * @private + */ + gamePaused: function () { + + this._pauseStarted = Date.now(); + + this.events.pause(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._pause(); + } + + }, + + /** + * Called when the game resumes from a paused state. + * + * @method Phaser.Time#gameResumed + * @private + */ + gameResumed: function () { + + // Set the parameter which stores Date.now() to make sure it's correct on resume + this.time = Date.now(); + + this.pauseDuration = this.time - this._pauseStarted; + + this.events.resume(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._resume(); + } + + }, + + /** + * The number of seconds that have elapsed since the game was started. + * + * @method Phaser.Time#totalElapsedSeconds + * @return {number} The number of seconds that have elapsed since the game was started. + */ + totalElapsedSeconds: function() { + return (this.time - this._started) * 0.001; + }, + + /** + * How long has passed since the given time. + * + * @method Phaser.Time#elapsedSince + * @param {number} since - The time you want to measure against. + * @return {number} The difference between the given time and now. + */ + elapsedSince: function (since) { + return this.time - since; + }, + + /** + * How long has passed since the given time (in seconds). + * + * @method Phaser.Time#elapsedSecondsSince + * @param {number} since - The time you want to measure (in seconds). + * @return {number} Duration between given time and now (in seconds). + */ + elapsedSecondsSince: function (since) { + return (this.time - since) * 0.001; + }, + + /** + * Resets the private _started value to now and removes all currently running Timers. + * + * @method Phaser.Time#reset + */ + reset: function () { + + this._started = this.time; + this.removeAll(); + + } + +}; + +/** +* The number of logic updates per second. +* +* This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. +* +* The render rate is unaffected unless you also turn off {@link Phaser.Game#forceSingleRender}. +* +* @name Phaser.Time#desiredFps +* @type {integer} +* @default 60 +*/ +Object.defineProperty(Phaser.Time.prototype, "desiredFps", { + + get: function () { + + return this._desiredFps; + + }, + + set: function (value) { + + this._desiredFps = value; + + // Set the physics elapsed time... this will always be 1 / this.desiredFps + // because we're using fixed time steps in game.update + this.physicsElapsed = 1 / value; + + this.physicsElapsedMS = this.physicsElapsed * 1000; + + this.desiredFpsMult = 1.0 / value; + + } + +}); + +Phaser.Time.prototype.constructor = Phaser.Time; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback. +* Many different timer events, with individual delays, can be added to the same Timer. +* +* All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. +* +* Timers are based on real life time, adjusted for game pause durations. +* That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account. +* +* @class Phaser.Timer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). +*/ +Phaser.Timer = function (game, autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * True if the Timer is actively running. + * + * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer. + * @property {boolean} running + * @default + * @readonly + */ + this.running = false; + + /** + * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). + * @property {boolean} autoDestroy + */ + this.autoDestroy = autoDestroy; + + /** + * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending. + * @readonly + * @default + */ + this.expired = false; + + /** + * @property {number} elapsed - Elapsed time since the last frame (in ms). + * @protected + */ + this.elapsed = 0; + + /** + * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. + */ + this.events = []; + + /** + * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. + * + * The signal is supplied with one argument, `timer`, which is this Timer object. + * + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {number} nextTick - The time the next tick will occur. + * @readonly + * @protected + */ + this.nextTick = 0; + + /** + * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. + */ + this.timeCap = 1000; + + /** + * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. + * @readonly + * @default + */ + this.paused = false; + + /** + * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {number} _started - The time at which this Timer instance started running. + * @private + * @default + */ + this._started = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {number} _pauseTotal - Total paused time. + * @private + */ + this._pauseTotal = 0; + + /** + * @property {number} _now - The current start-time adjusted time. + * @private + */ + this._now = Date.now(); + + /** + * @property {number} _len - Temp. array length variable. + * @private + */ + this._len = 0; + + /** + * @property {number} _marked - Temp. counter variable. + * @private + */ + this._marked = 0; + + /** + * @property {number} _i - Temp. array counter variable. + * @private + */ + this._i = 0; + + /** + * @property {number} _diff - Internal cache var. + * @private + */ + this._diff = 0; + + /** + * @property {number} _newTick - Internal cache var. + * @private + */ + this._newTick = 0; + +}; + +/** +* Number of milliseconds in a minute. +* @constant +* @type {integer} +*/ +Phaser.Timer.MINUTE = 60000; + +/** +* Number of milliseconds in a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.SECOND = 1000; + +/** +* Number of milliseconds in half a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.HALF = 500; + +/** +* Number of milliseconds in a quarter of a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.QUARTER = 250; + +Phaser.Timer.prototype = { + + /** + * Creates a new TimerEvent on this Timer. + * + * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. + * + * @method Phaser.Timer#create + * @private + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {boolean} loop - Should the event loop or not? + * @param {number} repeatCount - The number of times the event will repeat. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {any[]} arguments - The values to be sent to your callback function when it is called. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + create: function (delay, loop, repeatCount, callback, callbackContext, args) { + + delay = Math.round(delay); + + var tick = delay; + + if (this._now === 0) + { + tick += this.game.time.time; + } + else + { + tick += this._now; + } + + var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args); + + this.events.push(event); + + this.order(); + + this.expired = false; + + return event; + + }, + + /** + * Adds a new Event to this Timer. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#add + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + add: function (delay, callback, callbackContext) { + + return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. + * If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#repeat + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + repeat: function (delay, repeatCount, callback, callbackContext) { + + return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4)); + + }, + + /** + * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#loop + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + loop: function (delay, callback, callbackContext) { + + return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Starts this Timer running. + * @method Phaser.Timer#start + * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start. + */ + start: function (delay) { + + if (this.running) + { + return; + } + + this._started = this.game.time.time + (delay || 0); + + this.running = true; + + for (var i = 0; i < this.events.length; i++) + { + this.events[i].tick = this.events[i].delay + this._started; + } + + }, + + /** + * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. + * @method Phaser.Timer#stop + * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain. + */ + stop: function (clearEvents) { + + this.running = false; + + if (clearEvents === undefined) { clearEvents = true; } + + if (clearEvents) + { + this.events.length = 0; + } + + }, + + /** + * Removes a pending TimerEvent from the queue. + * @param {Phaser.TimerEvent} event - The event to remove from the queue. + * @method Phaser.Timer#remove + */ + remove: function (event) { + + for (var i = 0; i < this.events.length; i++) + { + if (this.events[i] === event) + { + this.events[i].pendingDelete = true; + return true; + } + } + + return false; + + }, + + /** + * Orders the events on this Timer so they are in tick order. + * This is called automatically when new events are created. + * @method Phaser.Timer#order + * @protected + */ + order: function () { + + if (this.events.length > 0) + { + // Sort the events so the one with the lowest tick is first + this.events.sort(this.sortHandler); + + this.nextTick = this.events[0].tick; + } + + }, + + /** + * Sort handler used by Phaser.Timer.order. + * @method Phaser.Timer#sortHandler + * @private + */ + sortHandler: function (a, b) { + + if (a.tick < b.tick) + { + return -1; + } + else if (a.tick > b.tick) + { + return 1; + } + + return 0; + + }, + + /** + * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values. + * + * @method Phaser.Timer#clearPendingEvents + * @protected + */ + 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; + + }, + + /** + * The main Timer update event, called automatically by Phaser.Time.update. + * + * @method Phaser.Timer#update + * @protected + * @param {number} time - The time from the core game clock. + * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. + */ + update: function (time) { + + if (this.paused) + { + return true; + } + + this.elapsed = time - this._now; + this._now = time; + + // spike-dislike + if (this.elapsed > this.timeCap) + { + // For some reason the time between now and the last time the game was updated was larger than our timeCap. + // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause. + // In this case we need to adjust the TimerEvents and nextTick. + this.adjustEvents(time - this.elapsed); + } + + this._marked = 0; + + // Clears events marked for deletion and resets _len and _i to 0. + this.clearPendingEvents(); + + if (this.running && this._now >= this.nextTick && this._len > 0) + { + while (this._i < this._len && this.running) + { + var event = this.events[this._i]; + + if (this._now >= event.tick && !event.pendingDelete) + { + // (now + delay) - (time difference from last tick to now) + this._newTick = (this._now + event.delay) - (this._now - event.tick); + + if (this._newTick < 0) + { + this._newTick = this._now + event.delay; + } + + if (event.loop === true) + { + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else if (event.repeatCount > 0) + { + event.repeatCount--; + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else + { + this._marked++; + event.pendingDelete = true; + event.callback.apply(event.callbackContext, event.args); + } + + this._i++; + } + else + { + break; + } + } + + // Are there any events left? + 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; + } + + }, + + /** + * Pauses the Timer and all events in the queue. + * @method Phaser.Timer#pause + */ + pause: function () { + + if (!this.running) + { + return; + } + + this._codePaused = true; + + if (this.paused) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Internal pause/resume control - user code should use Timer.pause instead. + * @method Phaser.Timer#_pause + * @private + */ + _pause: function () { + + if (this.paused || !this.running) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Adjusts the time of all pending events and the nextTick by the given baseTime. + * + * @method Phaser.Timer#adjustEvents + * @protected + */ + adjustEvents: function (baseTime) { + + for (var i = 0; i < this.events.length; i++) + { + if (!this.events[i].pendingDelete) + { + // Work out how long there would have been from when the game paused until the events next tick + var t = this.events[i].tick - baseTime; + + if (t < 0) + { + t = 0; + } + + // Add the difference on to the time now + this.events[i].tick = this._now + t; + } + } + + var d = this.nextTick - baseTime; + + if (d < 0) + { + this.nextTick = this._now; + } + else + { + this.nextTick = this._now + d; + } + + }, + + /** + * Resumes the Timer and updates all pending events. + * + * @method Phaser.Timer#resume + */ + resume: function () { + + if (!this.paused) + { + return; + } + + var now = this.game.time.time; + this._pauseTotal += now - this._now; + this._now = now; + + this.adjustEvents(this._pauseStarted); + + this.paused = false; + this._codePaused = false; + + }, + + /** + * Internal pause/resume control - user code should use Timer.resume instead. + * @method Phaser.Timer#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#removeAll + */ + removeAll: function () { + + this.onComplete.removeAll(); + this.events.length = 0; + this._len = 0; + this._i = 0; + + }, + + /** + * Destroys this Timer. Any pending Events are not dispatched. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#destroy + */ + destroy: function () { + + this.onComplete.removeAll(); + this.running = false; + this.expired = true; + this.events = []; + this._len = 0; + this._i = 0; + + } + +}; + +/** +* @name Phaser.Timer#next +* @property {number} next - The time at which the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "next", { + + get: function () { + return this.nextTick; + } + +}); + +/** +* @name Phaser.Timer#duration +* @property {number} duration - The duration in ms remaining until the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "duration", { + + get: function () { + + if (this.running && this.nextTick > this._now) + { + return this.nextTick - this._now; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#length +* @property {number} length - The number of pending events in the queue. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "length", { + + get: function () { + return this.events.length; + } + +}); + +/** +* @name Phaser.Timer#ms +* @property {number} ms - The duration in milliseconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "ms", { + + get: function () { + + if (this.running) + { + return this._now - this._started - this._pauseTotal; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#seconds +* @property {number} seconds - The duration in seconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "seconds", { + + get: function () { + + if (this.running) + { + return this.ms * 0.001; + } + else + { + return 0; + } + + } + +}); + +Phaser.Timer.prototype.constructor = Phaser.Timer; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TimerEvent is a single event that is processed by a Phaser.Timer. +* +* It consists of a delay, which is a value in milliseconds after which the event will fire. +* When the event fires it calls a specific callback with the specified arguments. +* +* TimerEvents are removed by their parent timer once finished firing or repeating. +* +* Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. +* +* @class Phaser.TimerEvent +* @constructor +* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. +* @param {number} delay - The delay in ms at which this TimerEvent fires. +* @param {number} tick - The tick is the next game clock time that this event will fire at. +* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times. +* @param {boolean} loop - True if this TimerEvent loops, otherwise false. +* @param {function} callback - The callback that will be called when the TimerEvent occurs. +* @param {object} callbackContext - The context in which the callback will be called. +* @param {any[]} arguments - Additional arguments to be passed to the callback. +*/ +Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) { + + /** + * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. + * @protected + * @readonly + */ + this.timer = timer; + + /** + * @property {number} delay - The delay in ms at which this TimerEvent fires. + */ + this.delay = delay; + + /** + * @property {number} tick - The tick is the next game clock time that this event will fire at. + */ + this.tick = tick; + + /** + * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times. + */ + this.repeatCount = repeatCount - 1; + + /** + * @property {boolean} loop - True if this TimerEvent loops, otherwise false. + */ + this.loop = loop; + + /** + * @property {function} callback - The callback that will be called when the TimerEvent occurs. + */ + this.callback = callback; + + /** + * @property {object} callbackContext - The context in which the callback will be called. + */ + this.callbackContext = callbackContext; + + /** + * @property {any[]} arguments - Additional arguments to be passed to the callback. + */ + this.args = args; + + /** + * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion. + * @protected + */ + this.pendingDelete = false; + +}; + +Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Manager is used to add, play and update Phaser Animations. +* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. +* +* @class Phaser.AnimationManager +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. +*/ +Phaser.AnimationManager = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = sprite.game; + + /** + * The currently displayed Frame of animation, if any. + * This property is only set once an Animation starts playing. Until that point it remains set as `null`. + * + * @property {Phaser.Frame} currentFrame + * @default + */ + this.currentFrame = null; + + /** + * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any. + * @default + */ + this.currentAnim = null; + + /** + * @property {boolean} updateIfVisible - Update the animation data only while the the sprite is {@link Phaser.Sprite#visible}. Set to `false` to continue updating while the sprite is invisible. + * @default + */ + this.updateIfVisible = true; + + /** + * @property {boolean} isLoaded - Set to true once animation data has been loaded. + * @default + */ + this.isLoaded = false; + + /** + * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. + * @private + * @default + */ + this._frameData = null; + + /** + * @property {object} _anims - An internal object that stores all of the Animation instances. + * @private + */ + this._anims = {}; + + /** + * @property {object} _outputFrames - An internal object to help avoid gc. + * @private + */ + this._outputFrames = []; + +}; + +Phaser.AnimationManager.prototype = { + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#loadFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + loadFrameData: function (frameData, frame) { + + if (frameData === undefined) + { + return false; + } + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(frameData); + } + } + + this._frameData = frameData; + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#copyFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + copyFrameData: function (frameData, frame) { + + this._frameData = frameData.clone(); + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(this._frameData); + } + } + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. + * Animations added in this way are played back with the play function. + * + * @method Phaser.AnimationManager#add + * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". + * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. + * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. + * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? + * @return {Phaser.Animation} The Animation object that was created. + */ + add: function (name, frames, frameRate, loop, useNumericIndex) { + + frames = frames || []; + frameRate = frameRate || 60; + + if (loop === undefined) { loop = false; } + + // If they didn't set the useNumericIndex then let's at least try and guess it + if (useNumericIndex === undefined) + { + if (frames && typeof frames[0] === 'number') + { + useNumericIndex = true; + } + else + { + useNumericIndex = false; + } + } + + this._outputFrames = []; + + 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]; + + if (this.sprite.tilingTexture) + { + this.sprite.refreshTexture = true; + } + + return this._anims[name]; + + }, + + /** + * Check whether the frames in the given array are valid and exist. + * + * @method Phaser.AnimationManager#validateFrames + * @param {Array} frames - An array of frames to be validated. + * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) + * @return {boolean} True if all given Frames are valid, otherwise false. + */ + validateFrames: function (frames, useNumericIndex) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + + for (var i = 0; i < frames.length; i++) + { + if (useNumericIndex === true) + { + if (frames[i] > this._frameData.total) + { + return false; + } + } + else + { + if (this._frameData.checkFrameName(frames[i]) === false) + { + return false; + } + } + } + + return true; + + }, + + /** + * Play an animation based on the given key. The animation should previously have been added via `animations.add` + * + * If the requested animation is already playing this request will be ignored. + * If you need to reset an already running animation do so directly on the Animation object itself. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.AnimationManager#play + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation instance. + */ + 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); + } + + return this.currentAnim; + } + else + { + if (this.currentAnim && this.currentAnim.isPlaying) + { + this.currentAnim.stop(); + } + + this.currentAnim = this._anims[name]; + this.currentAnim.paused = false; + this.currentFrame = this.currentAnim.currentFrame; + return this.currentAnim.play(frameRate, loop, killOnComplete); + } + } + + }, + + /** + * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. + * The currentAnim property of the AnimationManager is automatically set to the animation given. + * + * @method Phaser.AnimationManager#stop + * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. + * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) + */ + stop: function (name, resetFrame) { + + if (resetFrame === undefined) { resetFrame = false; } + + if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name)) + { + this.currentAnim.stop(resetFrame); + } + + }, + + /** + * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. + * + * @method Phaser.AnimationManager#update + * @protected + * @return {boolean} True if a new animation frame has been set, otherwise false. + */ + update: function () { + + if (this.updateIfVisible && !this.sprite.visible) + { + return false; + } + + if (this.currentAnim && this.currentAnim.update()) + { + this.currentFrame = this.currentAnim.currentFrame; + return true; + } + + return false; + + }, + + /** + * Advances by the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.next(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Moves backwards the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.previous(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Returns an animation that was previously added by name. + * + * @method Phaser.AnimationManager#getAnimation + * @param {string} name - The name of the animation to be returned, e.g. "fire". + * @return {Phaser.Animation} The Animation instance, if found, otherwise null. + */ + getAnimation: function (name) { + + if (typeof name === 'string') + { + if (this._anims[name]) + { + return this._anims[name]; + } + } + + return null; + + }, + + /** + * Refreshes the current frame data back to the parent Sprite and also resets the texture data. + * + * @method Phaser.AnimationManager#refreshFrame + */ + refreshFrame: function () { + + // TODO + // this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); + + }, + + /** + * Destroys all references this AnimationManager contains. + * Iterates through the list of animations stored in this manager and calls destroy on each of them. + * + * @method Phaser.AnimationManager#destroy + */ + destroy: function () { + + var anim = null; + + for (var anim in this._anims) + { + if (this._anims.hasOwnProperty(anim)) + { + this._anims[anim].destroy(); + } + } + + this._anims = {}; + this._outputFrames = []; + this._frameData = null; + this.currentAnim = null; + this.currentFrame = null; + this.sprite = null; + this.game = null; + + } + +}; + +Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager; + +/** +* @name Phaser.AnimationManager#frameData +* @property {Phaser.FrameData} frameData - The current animations FrameData. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', { + + get: function () { + return this._frameData; + } + +}); + +/** +* @name Phaser.AnimationManager#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', { + + get: function () { + + return this._frameData.total; + } + +}); + +/** +* @name Phaser.AnimationManager#paused +* @property {boolean} paused - Gets and sets the paused state of the current animation. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', { + + get: function () { + + return this.currentAnim.isPaused; + + }, + + set: function (value) { + + this.currentAnim.paused = value; + + } + +}); + +/** +* @name Phaser.AnimationManager#name +* @property {string} name - Gets the current animation name, if set. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'name', { + + get: function () { + + if (this.currentAnim) + { + return this.currentAnim.name; + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.index; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'number' && this._frameData && (gotFrame = this._frameData.getFrame(value))) + { + this.currentFrame = gotFrame; + this.sprite.setFrame(this.currentFrame); + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frameName +* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.name; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'string' && this._frameData && (gotFrame = this._frameData.getFrameByName(value))) + { + this.currentFrame = gotFrame; + this._frameIndex = this.currentFrame.index; + this.sprite.setFrame(this.currentFrame); + } + else + { + console.warn('Cannot set frameName: ' + value); + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Animation instance contains a single animation and the controls to play it. +* +* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. +* +* @class Phaser.Animation +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Sprite} parent - A reference to the owner of this Animation. +* @param {string} name - The unique name for this animation, used in playback commands. +* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. +* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +*/ +Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) { + + if (loop === undefined) { loop = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. + * @private + */ + this._parent = parent; + + /** + * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. + * @private + */ + this._frameData = frameData; + + /** + * @property {string} name - The user defined name given to this Animation. + */ + this.name = name; + + /** + * @property {array} _frames + * @private + */ + this._frames = []; + this._frames = this._frames.concat(frames); + + /** + * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. + */ + this.delay = 1000 / frameRate; + + /** + * @property {boolean} loop - The loop state of the Animation. + */ + this.loop = loop; + + /** + * @property {number} loopCount - The number of times the animation has looped since it was last started. + */ + this.loopCount = 0; + + /** + * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? + * @default + */ + this.killOnComplete = false; + + /** + * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. + * @default + */ + this.isFinished = false; + + /** + * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. + * @default + */ + this.isPlaying = false; + + /** + * @property {boolean} isPaused - The paused state of the Animation. + * @default + */ + this.isPaused = false; + + /** + * @property {boolean} _pauseStartTime - The time the animation paused. + * @private + * @default + */ + this._pauseStartTime = 0; + + /** + * @property {number} _frameIndex + * @private + * @default + */ + this._frameIndex = 0; + + /** + * @property {number} _frameDiff + * @private + * @default + */ + this._frameDiff = 0; + + /** + * @property {number} _frameSkip + * @private + * @default + */ + this._frameSkip = 1; + + /** + * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. + */ + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + /** + * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. + */ + this.onStart = new Phaser.Signal(); + + /** + * This event is dispatched when the Animation changes frame. + * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. + * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations + * will automatically frame-skip to try and claw back time, so do not base your code on expecting to + * receive a perfectly sequential set of frames from this event. + * @property {Phaser.Signal|null} onUpdate + * @default + */ + this.onUpdate = null; + + /** + * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {boolean} isReversed - Indicates if the animation will play backwards. + * @default + */ + this.isReversed = false; + + // Set-up some event listeners + this.game.onPause.add(this.onPause, this); + this.game.onResume.add(this.onResume, this); + +}; + +Phaser.Animation.prototype = { + + /** + * Plays this animation. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.Animation#play + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} - A reference to this Animation instance. + */ + play: function (frameRate, loop, killOnComplete) { + + if (typeof frameRate === 'number') + { + // If they set a new frame rate then use it, otherwise use the one set on creation + this.delay = 1000 / frameRate; + } + + if (typeof loop === 'boolean') + { + // If they set a new loop value then use it, otherwise use the one set on creation + this.loop = loop; + } + + if (typeof killOnComplete !== 'undefined') + { + // Remove the parent sprite once the animation has finished? + this.killOnComplete = killOnComplete; + } + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = this.isReversed ? this._frames.length - 1 : 0; + this.updateCurrentFrame(false, true); + + this._parent.events.onAnimationStart$dispatch(this._parent, this); + + this.onStart.dispatch(this._parent, this); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + return this; + + }, + + /** + * Sets this animation back to the first frame and restarts the animation. + * + * @method Phaser.Animation#restart + */ + restart: function () { + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = 0; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + this._parent.setFrame(this.currentFrame); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + this.onStart.dispatch(this._parent, this); + + }, + + /** + * Reverses the animation direction. + * + * @method Phaser.Animation#reverse + * @return {Phaser.Animation} The animation instance. + */ + reverse: function () { + + this.reversed = !this.reversed; + + return this; + + }, + + /** + * Reverses the animation direction for the current/next animation only + * Once the onComplete event is called this method will be called again and revert + * the reversed state. + * + * @method Phaser.Animation#reverseOnce + * @return {Phaser.Animation} The animation instance. + */ + reverseOnce: function () { + + this.onComplete.addOnce(this.reverse, this); + + return this.reverse(); + + }, + + /** + * Sets this animations playback to a given frame with the given ID. + * + * @method Phaser.Animation#setFrame + * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. + * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. + */ + setFrame: function(frameId, useLocalFrameIndex) { + + var frameIndex; + + if (useLocalFrameIndex === undefined) + { + useLocalFrameIndex = false; + } + + // Find the index to the desired frame. + if (typeof frameId === "string") + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frameData.getFrame(this._frames[i]).name === frameId) + { + frameIndex = i; + } + } + } + else if (typeof frameId === "number") + { + if (useLocalFrameIndex) + { + frameIndex = frameId; + } + else + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frames[i] === frameId) + { + frameIndex = i; + } + } + } + } + + if (frameIndex) + { + // Set the current frame index to the found index. Subtract a directional offset so that it animates to the desired frame on update. + var directionalOffset = this.isReversed ? -1 : 1; + this._frameIndex = frameIndex - directionalOffset; + + // Make the animation update at next update + this._timeNextFrame = this.game.time.time; + + this.update(); + } + + }, + + /** + * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. + * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. + * + * @method Phaser.Animation#stop + * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. + * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? + */ + stop: function (resetFrame, dispatchComplete) { + + if (resetFrame === undefined) { resetFrame = false; } + if (dispatchComplete === undefined) { dispatchComplete = false; } + + this.isPlaying = false; + this.isFinished = true; + this.paused = false; + + if (resetFrame) + { + this.currentFrame = this._frameData.getFrame(this._frames[0]); + this._parent.setFrame(this.currentFrame); + } + + if (dispatchComplete) + { + this._parent.events.onAnimationComplete$dispatch(this._parent, this); + this.onComplete.dispatch(this._parent, this); + } + + }, + + /** + * Called when the Game enters a paused state. + * + * @method Phaser.Animation#onPause + */ + onPause: function () { + + if (this.isPlaying) + { + this._frameDiff = this._timeNextFrame - this.game.time.time; + } + + }, + + /** + * Called when the Game resumes from a paused state. + * + * @method Phaser.Animation#onResume + */ + onResume: function () { + + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this._frameDiff; + } + + }, + + /** + * Updates this animation. Called automatically by the AnimationManager. + * + * @method Phaser.Animation#update + */ + update: function () { + + if (this.isPaused) + { + return false; + } + + if (this.isPlaying && this.game.time.time >= this._timeNextFrame) + { + this._frameSkip = 1; + + // Lagging? + this._frameDiff = this.game.time.time - this._timeNextFrame; + + this._timeLastFrame = this.game.time.time; + + if (this._frameDiff > this.delay) + { + // We need to skip a frame, work out how many + this._frameSkip = Math.floor(this._frameDiff / this.delay); + this._frameDiff -= (this._frameSkip * this.delay); + } + else + { + this._frameDiff = 0; + } + + // And what's left now? + this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff); + + if (this.isReversed) + { + this._frameIndex -= this._frameSkip; + } + else + { + this._frameIndex += this._frameSkip; + } + + if (!this.isReversed && this._frameIndex >= this._frames.length || this.isReversed && this._frameIndex <= -1) + { + if (this.loop) + { + // Update current state before event callback + this._frameIndex = Math.abs(this._frameIndex) % this._frames.length; + + if (this.isReversed) + { + this._frameIndex = this._frames.length - 1 - this._frameIndex; + } + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + // Instead of calling updateCurrentFrame we do it here instead + if (this.currentFrame) + { + this._parent.setFrame(this.currentFrame); + } + + this.loopCount++; + this._parent.events.onAnimationLoop$dispatch(this._parent, this); + this.onLoop.dispatch(this._parent, this); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + } + else + { + this.complete(); + return false; + } + } + else + { + return this.updateCurrentFrame(true); + } + } + + return false; + + }, + + /** + * Changes the currentFrame per the _frameIndex, updates the display state, + * and triggers the update signal. + * + * Returns true if the current frame update was 'successful', false otherwise. + * + * @method Phaser.Animation#updateCurrentFrame + * @private + * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. + * @param {boolean} fromPlay - Was this call made from the playing of a new animation? + * @return {boolean} True if the current frame was updated, otherwise false. + */ + updateCurrentFrame: function (signalUpdate, fromPlay) { + + if (fromPlay === undefined) { fromPlay = false; } + + if (!this._frameData) + { + // The animation is already destroyed, probably from a callback + return false; + } + + // Previous index + var idx = this.currentFrame.index; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index))) + { + this._parent.setFrame(this.currentFrame); + } + + if (this.onUpdate && signalUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + + }, + + /** + * Advances by the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex + quantity; + + if (frame >= this._frames.length) + { + if (this.loop) + { + frame %= this._frames.length; + } + else + { + frame = this._frames.length - 1; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex - quantity; + + if (frame < 0) + { + if (this.loop) + { + frame = this._frames.length + frame; + } + else + { + frame++; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Changes the FrameData object this Animation is using. + * + * @method Phaser.Animation#updateFrameData + * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. + */ + updateFrameData: function (frameData) { + + this._frameData = frameData; + this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null; + + }, + + /** + * Cleans up this animation ready for deletion. Nulls all values and references. + * + * @method Phaser.Animation#destroy + */ + destroy: function () { + + if (!this._frameData) + { + // Already destroyed + return; + } + + 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(); + + if (this.onUpdate) + { + this.onUpdate.dispose(); + } + + }, + + /** + * Called internally when the animation finishes playback. + * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. + * + * @method Phaser.Animation#complete + */ + complete: function () { + + this._frameIndex = this._frames.length - 1; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + 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; + +/** +* @name Phaser.Animation#paused +* @property {boolean} paused - Gets and sets the paused state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'paused', { + + get: function () { + + return this.isPaused; + + }, + + set: function (value) { + + this.isPaused = value; + + if (value) + { + // Paused + this._pauseStartTime = this.game.time.time; + } + else + { + // Un-paused + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this.delay; + } + } + + } + +}); + +/** +* @name Phaser.Animation#reversed +* @property {boolean} reversed - Gets and sets the isReversed state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'reversed', { + + get: function () { + + return this.isReversed; + + }, + + set: function (value) { + + this.isReversed = value; + + } + +}); + +/** +* @name Phaser.Animation#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @name Phaser.Animation#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +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.setFrame(this.currentFrame); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + } + } + + } + +}); + +/** +* @name Phaser.Animation#speed +* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'speed', { + + get: function () { + + return 1000 / this.delay; + + }, + + set: function (value) { + + if (value > 0) + { + this.delay = 1000 / value; + } + + } + +}); + +/** +* @name Phaser.Animation#enableUpdate +* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { + + get: function () { + + return (this.onUpdate !== null); + + }, + + set: function (value) { + + if (value && this.onUpdate === null) + { + this.onUpdate = new Phaser.Signal(); + } + else if (!value && this.onUpdate !== null) + { + this.onUpdate.dispose(); + this.onUpdate = null; + } + + } + +}); + +/** +* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. +* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' +* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); +* +* @method Phaser.Animation.generateFrameNames +* @static +* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. +* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. +* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. +* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'. +* @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. +* @return {string[]} An array of framenames. +*/ +Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { + + if (suffix === undefined) { suffix = ''; } + + var output = []; + var frame = ''; + + if (start < stop) + { + for (var i = start; i <= stop; i++) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + else + { + for (var i = start; i >= stop; i--) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + + return output; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Frame is a single frame of an animation and is part of a FrameData collection. +* +* @class Phaser.Frame +* @constructor +* @param {number} index - The index of this Frame within the FrameData set it is being added to. +* @param {number} x - X position of the frame within the texture image. +* @param {number} y - Y position of the frame within the texture image. +* @param {number} width - Width of the frame within the texture image. +* @param {number} height - Height of the frame within the texture image. +* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. +*/ +Phaser.Frame = function (index, x, y, width, height, name) { + + /** + * @property {number} index - The index of this Frame within the FrameData set it is being added to. + */ + this.index = index; + + /** + * @property {number} x - X position within the image to cut from. + */ + this.x = x; + + /** + * @property {number} y - Y position within the image to cut from. + */ + this.y = y; + + /** + * @property {number} width - Width of the frame. + */ + this.width = width; + + /** + * @property {number} height - Height of the frame. + */ + this.height = height; + + if (this.width === 0 || this.height === 0) + { + console.warn('Phaser.Frame: Frame "' + this.name + '" has a width or height of zero'); + } + + /** + * @property {string} name - Useful for Texture Atlas files (is set to the filename value). + */ + this.name = name; + + /** + * @property {number} centerX - Center X position within the image to cut from. + */ + this.centerX = Math.floor(width / 2); + + /** + * @property {number} centerY - Center Y position within the image to cut from. + */ + this.centerY = Math.floor(height / 2); + + /** + * @property {number} distance - The distance from the top left to the bottom-right of this Frame. + */ + this.distance = Phaser.Math.distance(0, 0, width, height); + + /** + * @property {boolean} rotated - Is the frame rotated in the source texture? + * @default + */ + this.rotated = false; + + /** + * @property {boolean} trimmed - Was it trimmed when packed? + * @default + */ + this.trimmed = false; + + /** + * @property {number} sourceSizeW - Width of the original sprite before it was trimmed. + */ + this.sourceSizeW = width; + + /** + * @property {number} sourceSizeH - Height of the original sprite before it was trimmed. + */ + this.sourceSizeH = height; + + /** + * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeX = 0; + + /** + * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeY = 0; + + /** + * @property {number} spriteSourceSizeW - Width of the trimmed sprite. + * @default + */ + this.spriteSourceSizeW = 0; + + /** + * @property {number} spriteSourceSizeH - Height of the trimmed sprite. + * @default + */ + this.spriteSourceSizeH = 0; + + /** + * @property {number} right - The right of the Frame (x + width). + */ + this.right = this.x + this.width; + + /** + * @property {number} bottom - The bottom of the frame (y + height). + */ + this.bottom = this.y + this.height; + +}; + +Phaser.Frame.prototype = { + + /** + * Adjusts of all the Frame properties based on the given width and height values. + * + * @method Phaser.Frame#resize + * @param {integer} width - The new width of the Frame. + * @param {integer} height - The new height of the Frame. + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + this.centerX = Math.floor(width / 2); + this.centerY = Math.floor(height / 2); + this.distance = Phaser.Math.distance(0, 0, width, height); + this.sourceSizeW = width; + this.sourceSizeH = height; + this.right = this.x + width; + this.bottom = this.y + height; + + }, + + /** + * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. + * + * @method Phaser.Frame#setTrim + * @param {boolean} trimmed - If this frame was trimmed or not. + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + */ + setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { + + this.trimmed = trimmed; + + if (trimmed) + { + 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; + } + + }, + + /** + * Clones this Frame into a new Phaser.Frame object and returns it. + * Note that all properties are cloned, including the name and index. + * + * @method Phaser.Frame#clone + * @return {Phaser.Frame} An exact copy of this Frame object. + */ + clone: function () { + + var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name); + + for (var prop in this) + { + if (this.hasOwnProperty(prop)) + { + output[prop] = this[prop]; + } + } + + return output; + + }, + + /** + * Returns a Rectangle set to the dimensions of this Frame. + * + * @method Phaser.Frame#getRect + * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to. + * @return {Phaser.Rectangle} A rectangle. + */ + getRect: function (out) { + + if (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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. +* +* @class Phaser.FrameData +* @constructor +*/ +Phaser.FrameData = function () { + + /** + * @property {Array} _frames - Local array of frames. + * @private + */ + this._frames = []; + + /** + * @property {Array} _frameNames - Local array of frame names for name to index conversions. + * @private + */ + this._frameNames = []; + +}; + +Phaser.FrameData.prototype = { + + /** + * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. + * + * @method Phaser.FrameData#addFrame + * @param {Phaser.Frame} frame - The frame to add to this FrameData set. + * @return {Phaser.Frame} The frame that was just added. + */ + addFrame: function (frame) { + + frame.index = this._frames.length; + + this._frames.push(frame); + + if (frame.name !== '') + { + this._frameNames[frame.name] = frame.index; + } + + return frame; + + }, + + /** + * Get a Frame by its numerical index. + * + * @method Phaser.FrameData#getFrame + * @param {number} index - The index of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or undefined. + */ + getFrame: function (index) { + + if (index >= this._frames.length) + { + index = 0; + } + + return this._frames[index]; + + }, + + /** + * Get a Frame by its frame name. + * + * @method Phaser.FrameData#getFrameByName + * @param {string} name - The name of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or null. + */ + getFrameByName: function (name) { + + if (typeof this._frameNames[name] === 'number') + { + return this._frames[this._frameNames[name]]; + } + + return null; + + }, + + /** + * Check if there is a Frame with the given name. + * + * @method Phaser.FrameData#checkFrameName + * @param {string} name - The name of the frame you want to check. + * @return {boolean} True if the frame is found, otherwise false. + */ + checkFrameName: function (name) { + + if (this._frameNames[name] == null) + { + return false; + } + + return true; + + }, + + /** + * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains. + * + * @method Phaser.FrameData#clone + * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains. + */ + clone: function () { + + var output = new Phaser.FrameData(); + + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output._frames.push(this._frames[i].clone()); + } + + for (var p in this._frameNames) + { + if (this._frameNames.hasOwnProperty(p)) + { + output._frameNames.push(this._frameNames[p]); + } + } + + return output; + + }, + + /** + * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. + * + * @method Phaser.FrameData#getFrameRange + * @param {number} start - The starting frame index. + * @param {number} end - The ending frame index. + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. + */ + getFrameRange: function (start, end, output) { + + if (output === undefined) { output = []; } + + for (var i = start; i <= end; i++) + { + output.push(this._frames[i]); + } + + return output; + + }, + + /** + * Returns all of the Frames in this FrameData set where the frame index is found in the input array. + * The frames are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrames + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. + */ + getFrames: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + // We only need the indexes + output.push(this._frames[i]); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the input array contain names or indexes? + if (useNumericIndex) + { + // The actual frame + output.push(this.getFrame(frames[i])); + } + else + { + // The actual frame + output.push(this.getFrameByName(frames[i])); + } + } + } + + return output; + + }, + + /** + * Returns all of the Frame indexes in this FrameData set. + * The frames indexes are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrameIndexes + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frame indexes matching the given names or IDs. + */ + getFrameIndexes: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No frames array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output.push(this._frames[i].index); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the frames array contain names or indexes? + if (useNumericIndex && this._frames[frames[i]]) + { + output.push(this._frames[frames[i]].index); + } + else + { + if (this.getFrameByName(frames[i])) + { + output.push(this.getFrameByName(frames[i]).index); + } + } + } + } + + return output; + + }, + + /** + * Destroys this FrameData collection by nulling the _frames and _frameNames arrays. + * + * @method Phaser.FrameData#destroy + */ + destroy: function () { + + this._frames = null; + this._frameNames = null; + + } + +}; + +Phaser.FrameData.prototype.constructor = Phaser.FrameData; + +/** +* @name Phaser.FrameData#total +* @property {number} total - The total number of frames in this FrameData set. +* @readonly +*/ +Object.defineProperty(Phaser.FrameData.prototype, "total", { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +* +* @class Phaser.AnimationParser +* @static +*/ +Phaser.AnimationParser = { + + /** + * Parse a Sprite Sheet and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.spriteSheet + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. + * @param {number} frameWidth - The fixed width of each frame of the animation. + * @param {number} frameHeight - The fixed height of each frame of the animation. + * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + var img = key; + + if (typeof key === 'string') + { + img = game.cache.getImage(key); + } + + if (img === null) + { + return null; + } + + var width = img.width; + var height = img.height; + + if (frameWidth <= 0) + { + frameWidth = Math.floor(-width / Math.min(-1, frameWidth)); + } + + if (frameHeight <= 0) + { + frameHeight = Math.floor(-height / Math.min(-1, frameHeight)); + } + + var row = Math.floor((width - margin) / (frameWidth + spacing)); + var column = Math.floor((height - margin) / (frameHeight + spacing)); + var total = row * column; + + if (skipFrames > total || skipFrames < -total) + { + console.warn( + "Phaser.AnimationParser.spriteSheet: skipFrames = " + + skipFrames.toString() + " is larger than total sprite number " + + total.toString()); + return null; + } + + if (skipFrames < 0) + { + // Allow negative skipframes. + skipFrames = total + skipFrames; + } + + if (frameMax !== -1) + { + total = skipFrames + frameMax; + } + + // Zero or smaller than frame sizes? + if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0) + { + console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight"); + return null; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var x = margin; + var y = margin; + + for (var i = 0; i < total; i++) + { + data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '')); + + x += frameWidth + spacing; + + if (x + frameWidth > width) + { + x = margin; + y += frameHeight + spacing; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONData: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].frame.x, + frames[i].frame.y, + frames[i].frame.w, + frames[i].frame.h, + frames[i].filename + )); + + if (frames[i].trimmed) + { + newFrame.setTrim( + frames[i].trimmed, + frames[i].sourceSize.w, + frames[i].sourceSize.h, + frames[i].spriteSourceSize.x, + frames[i].spriteSourceSize.y, + frames[i].spriteSourceSize.w, + frames[i].spriteSourceSize.h + ); + } + + if (frames[i].rotated) + { + newFrame.rotated = true; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataPyxel + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataPyxel: function (game, json) { + + // Malformed? There are a few keys to check here. + var signature = ['layers', 'tilewidth','tileheight','tileswide', 'tileshigh']; + + signature.forEach( function(key) { + if (!json[key]) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "' + key + '" key.'); + console.log(json); + return; + } + }); + + // For this purpose, I only care about parsing tilemaps with a single layer. + if (json['layers'].length !== 1) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps.'); + console.log(json); + return; + } + + var data = new Phaser.FrameData(); + + var tileheight = json['tileheight']; + var tilewidth = json['tilewidth']; + + var frames = json['layers'][0]['tiles']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].x, + frames[i].y, + tilewidth, + tileheight, + "frame_" + i // No names are included in pyxel tilemap data. + )); + + // No trim data is included. + newFrame.setTrim(false); + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataHash + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataHash: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + var i = 0; + + for (var key in frames) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[key].frame.x, + frames[key].frame.y, + frames[key].frame.w, + frames[key].frame.h, + key + )); + + if (frames[key].trimmed) + { + newFrame.setTrim( + frames[key].trimmed, + frames[key].sourceSize.w, + frames[key].sourceSize.h, + frames[key].spriteSourceSize.x, + frames[key].spriteSourceSize.y, + frames[key].spriteSourceSize.w, + frames[key].spriteSourceSize.h + ); + } + + if (frames[key].rotated) + { + newFrame.rotated = true; + } + + i++; + } + + return data; + + }, + + /** + * Parse the XML data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.XMLData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + XMLData: function (game, xml) { + + // Malformed? + if (!xml.getElementsByTagName('TextureAtlas')) + { + console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing tag"); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var frames = xml.getElementsByTagName('SubTexture'); + var newFrame; + + var name; + var frame; + var x; + var y; + var width; + var height; + var frameX; + var frameY; + var frameWidth; + var frameHeight; + + for (var i = 0; i < frames.length; i++) + { + frame = frames[i].attributes; + + name = frame.name.value; + x = parseInt(frame.x.value, 10); + y = parseInt(frame.y.value, 10); + width = parseInt(frame.width.value, 10); + height = parseInt(frame.height.value, 10); + + frameX = null; + frameY = null; + + if (frame.frameX) + { + frameX = Math.abs(parseInt(frame.frameX.value, 10)); + frameY = Math.abs(parseInt(frame.frameY.value, 10)); + frameWidth = parseInt(frame.frameWidth.value, 10); + frameHeight = parseInt(frame.frameHeight.value, 10); + } + + newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name)); + + // Trimmed? + if (frameX !== null || frameY !== null) + { + newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight); + } + } + + return data; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser has one single cache in which it stores all assets. +* +* The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using +* a unique string-based key as their identifier. Assets stored in different areas of the cache can have the +* same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, +* because they are unique data types. +* +* The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets +* such as images they are automatically placed into their respective cache. Most common Game Objects, such as +* Sprites and Videos automatically query the cache to extract the assets they need on instantiation. +* +* You can access the cache from within a State via `this.cache`. From here you can call any public method it has, +* including adding new entries to it, deleting them or querying them. +* +* Understand that almost without exception when you get an item from the cache it will return a reference to the +* item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original +* object in the cache will also be updated, even if you don't put it back into the cache again. +* +* By default when you change State the cache is _not_ cleared, although there is an option to clear it should +* your game require it. In a typical game set-up the cache is populated once after the main game has loaded and +* then used as an asset store. +* +* @class Phaser.Cache +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Cache = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. + * @property {boolean} autoResolveURL + */ + this.autoResolveURL = false; + + /** + * The main cache object into which all resources are placed. + * @property {object} _cache + * @private + */ + this._cache = { + canvas: {}, + image: {}, + texture: {}, + sound: {}, + video: {}, + text: {}, + json: {}, + xml: {}, + physics: {}, + tilemap: {}, + binary: {}, + bitmapData: {}, + bitmapFont: {}, + shader: {}, + renderTexture: {}, + compressedTexture: {} + }; + + /** + * @property {object} _urlMap - Maps URLs to resources. + * @private + */ + this._urlMap = {}; + + /** + * @property {Image} _urlResolver - Used to resolve URLs to the absolute path. + * @private + */ + this._urlResolver = new Image(); + + /** + * @property {string} _urlTemp - Temporary variable to hold a resolved url. + * @private + */ + this._urlTemp = null; + + /** + * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices. + */ + this.onSoundUnlock = new Phaser.Signal(); + + /** + * @property {array} _cacheMap - Const to cache object look-up array. + * @private + */ + this._cacheMap = []; + + this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas; + this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image; + this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture; + this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound; + this._cacheMap[Phaser.Cache.TEXT] = this._cache.text; + this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics; + this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap; + this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary; + this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData; + this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont; + this._cacheMap[Phaser.Cache.JSON] = this._cache.json; + this._cacheMap[Phaser.Cache.XML] = this._cache.xml; + this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video; + this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader; + this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture; + + /** + * @property {number} + * @private + */ + this._pendingCount = 0; + + /** + * Dispatched when the DEFAULT and MISSING images have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). + * + * @property {Phaser.Signal} onReady + */ + this.onReady = new Phaser.Signal(); + + this._addImages(); + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.CANVAS = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.IMAGE = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXTURE = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SOUND = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXT = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.PHYSICS = 6; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TILEMAP = 7; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BINARY = 8; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPDATA = 9; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPFONT = 10; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.JSON = 11; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.XML = 12; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.VIDEO = 13; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SHADER = 14; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.RENDER_TEXTURE = 15; + +/** +* The default image used for a texture when no other is specified. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.DEFAULT = null; + +/** + * Key for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_KEY = '__default'; + +/** + * URL for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='; + +/** +* The default image used for a texture when the source image is missing. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.MISSING = null; + +/** + * Key for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_KEY = '__missing'; + +/** + * URL for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='; + +/** +* The maximum amount of time (ms) to wait for the built-in DEFAULT and MISSING images to load. +* @static +* @type {number} +* @default +*/ +Phaser.Cache.READY_TIMEOUT = 1000; + +Phaser.Cache.prototype = { + + ////////////////// + // Add Methods // + ////////////////// + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCompressedTextureMetaData + * @private + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url + * @param {string} extension + * @param {array} arrayBuffer + * @return {object} The compressed texture entry. + */ + addCompressedTextureMetaData: function (key, url, extension, arrayBuffer) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + var data = (extension in Phaser.LoaderParser) ? Phaser.LoaderParser[extension](arrayBuffer) : arrayBuffer; + + var texture = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData(), + fileFormat: extension + }; + + texture.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = texture; + + this._resolveURL(url, texture); + + return texture; + + }, + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCanvas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {HTMLCanvasElement} canvas - The Canvas DOM element. + * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`. + */ + addCanvas: function (key, canvas, context) { + + if (context === undefined) { context = canvas.getContext('2d'); } + + this._cache.canvas[key] = { canvas: canvas, context: context }; + + }, + + /** + * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. + * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. + * + * If the image has not yet been fetched (successfully or not), a `console.warn` message will be displayed. + * + * @method Phaser.Cache#addImage + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra image data. + * @return {object} The full image object that was added to the cache. + */ + addImage: function (key, url, data) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + if (data.complete === false) + { + console.warn('Phaser.Cache.addImage: Image "' + key + '" hasn\'t been retrieved yet'); + } + + var img = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData() + }; + + img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = img; + + this._resolveURL(url, img); + + if (key === '__default') + { + Phaser.Cache.DEFAULT = new PIXI.Texture(img.base); + } + else if (key === '__missing') + { + Phaser.Cache.MISSING = new PIXI.Texture(img.base); + } + + return img; + + }, + + /** + * @method Phaser.Cache#addImageAsync + * @private + */ + addImageAsync: function (key, src, callback) { + + var self = this; + var img = new Image(); + + img.onload = function () { + callback.call(this, self.addImage(key, null, img)); + self._removePending(); + img.onload = null; + }; + + this._addPending(); + img.src = src; + + }, + + /** + * Adds a default image to be used in special cases such as WebGL Filters. + * It uses the special reserved key of `__default`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addDefaultImage + * @protected + */ + addDefaultImage: function () { + + this.addImageAsync(Phaser.Cache.DEFAULT_KEY, Phaser.Cache.DEFAULT_SRC, function (obj) { + // Because we don't want to invalidate the sprite batch for an invisible texture + obj.base.skipRender = true; + + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.DEFAULT = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds an image to be used when a key is wrong / missing. + * It uses the special reserved key of `__missing`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addMissingImage + * @protected + */ + addMissingImage: function () { + + this.addImageAsync(Phaser.Cache.MISSING_KEY, Phaser.Cache.MISSING_SRC, function (obj) { + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.MISSING = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addSound + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sound data. + * @param {boolean} webAudio - True if the file is using web audio. + * @param {boolean} audioTag - True if the file is using legacy HTML audio. + */ + addSound: function (key, url, data, webAudio, audioTag) { + + if (webAudio === undefined) { webAudio = true; audioTag = false; } + if (audioTag === undefined) { webAudio = false; audioTag = true; } + + var decoded = false; + + if (audioTag) + { + decoded = true; + } + + this._cache.sound[key] = { + url: url, + data: data, + isDecoding: false, + decoded: decoded, + webAudio: webAudio, + audioTag: audioTag, + locked: this.game.sound.touchLocked + }; + + this._resolveURL(url, this._cache.sound[key]); + + }, + + /** + * Add a new text data. + * + * @method Phaser.Cache#addText + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addText: function (key, url, data) { + + this._cache.text[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.text[key]); + + }, + + /** + * Add a new physics data object to the Cache. + * + * @method Phaser.Cache#addPhysicsData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} JSONData - The physics data object (a JSON file). + * @param {number} format - The format of the physics data. + */ + addPhysicsData: function (key, url, JSONData, format) { + + this._cache.physics[key] = { url: url, data: JSONData, format: format }; + + this._resolveURL(url, this._cache.physics[key]); + + }, + + /** + * Add a new tilemap to the Cache. + * + * @method Phaser.Cache#addTilemap + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} mapData - The tilemap data object (either a CSV or JSON file). + * @param {number} format - The format of the tilemap data. + */ + addTilemap: function (key, url, mapData, format) { + + this._cache.tilemap[key] = { url: url, data: mapData, format: format }; + + this._resolveURL(url, this._cache.tilemap[key]); + + }, + + /** + * Add a binary object in to the cache. + * + * @method Phaser.Cache#addBinary + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {object} binaryData - The binary object to be added to the cache. + */ + addBinary: function (key, binaryData) { + + this._cache.binary[key] = binaryData; + + }, + + /** + * Add a BitmapData object to the cache. + * + * @method Phaser.Cache#addBitmapData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. + * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. + * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. + */ + addBitmapData: function (key, bitmapData, frameData) { + + bitmapData.key = key; + + if (frameData === undefined) + { + frameData = new Phaser.FrameData(); + frameData.addFrame(bitmapData.textureFrame); + } + + this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData }; + + return bitmapData; + + }, + + /** + * Add a new Bitmap Font to the Cache. + * + * @method Phaser.Cache#addBitmapFont + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra font data. + * @param {object} atlasData - The Bitmap Font data. + * @param {string} [atlasType='xml'] - The format of the Bitmap Font data file: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) { + + var obj = { + url: url, + data: data, + font: null, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + if (atlasType === 'json') + { + obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + else + { + obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new Bitmap Font to the Cache, where the font texture is part of a Texture Atlas. + * + * The atlas must already exist in the cache, and be available based on the given `atlasKey`. + * + * The `atlasFrame` specifies the name of the frame within the atlas that the Bitmap Font is + * stored in. + * + * The `dataKey` is the key of the XML or JSON Bitmap Font Data, which must already be in + * the Cache. + * + * @method Phaser.Cache#addBitmapFontFromAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} atlasKey - The key of the Texture Atlas in the Cache. + * @param {string} atlasFrame - The frame of the Texture Atlas that the Bitmap Font is in. + * @param {string} dataKey - The key of the Bitmap Font data in the Cache + * @param {string} [dataType='xml'] - The format of the Bitmap Font data: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFontFromAtlas: function (key, atlasKey, atlasFrame, dataKey, dataType, xSpacing, ySpacing) { + + var frame = this.getFrameByName(atlasKey, atlasFrame); + + if (!frame) + { + return; + } + + var obj = { + font: null, + base: this.getBaseTexture(atlasKey), + frame: frame + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + var fontData; + + if (dataType === 'json') + { + fontData = this.getJSON(dataKey); + obj.font = Phaser.LoaderParser.jsonBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + else + { + fontData = this.getXML(dataKey); + obj.font = Phaser.LoaderParser.xmlBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + }, + + /** + * Add a new json object into the cache. + * + * @method Phaser.Cache#addJSON + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra json data. + */ + addJSON: function (key, url, data) { + + this._cache.json[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.json[key]); + + }, + + /** + * Add a new xml object into the cache. + * + * @method Phaser.Cache#addXML + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addXML: function (key, url, data) { + + this._cache.xml[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.xml[key]); + + }, + + /** + * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addVideo + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra video data. + * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. + */ + addVideo: function (key, url, data, isBlob) { + + this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true }; + + this._resolveURL(url, this._cache.video[key]); + + }, + + /** + * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addShader + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra shader data. + */ + addShader: function (key, url, data) { + + this._cache.shader[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.shader[key]); + + }, + + /** + * Add a new Phaser.RenderTexture in to the cache. + * + * @method Phaser.Cache#addRenderTexture + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture. + */ + addRenderTexture: function (key, texture) { + + this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') }; + + }, + + /** + * Add a new sprite sheet in to the cache. + * + * @method Phaser.Cache#addSpriteSheet + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sprite sheet data. + * @param {number} frameWidth - Width of the sprite sheet. + * @param {number} frameHeight - Height of the sprite sheet. + * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + */ + addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + var obj = { + key: key, + url: url, + data: data, + frameWidth: frameWidth, + frameHeight: frameHeight, + margin: margin, + spacing: spacing, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) + }; + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new texture atlas to the Cache. + * + * @method Phaser.Cache#addTextureAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra texture atlas data. + * @param {object} atlasData - Texture atlas frames data. + * @param {number} format - The format of the texture atlas. + */ + addTextureAtlas: function (key, url, data, atlasData, format) { + + var obj = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key); + } + else if (format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + obj.frameData = Phaser.AnimationParser.JSONDataPyxel(this.game, atlasData, key); + } + else + { + // Let's just work it out from the frames array + if (Array.isArray(atlasData.frames)) + { + obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key); + } + else + { + obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key); + } + } + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + //////////////////////////// + // Sound Related Methods // + //////////////////////////// + + /** + * Reload a Sound file from the server. + * + * @method Phaser.Cache#reloadSound + * @param {string} key - The key of the asset within the cache. + */ + reloadSound: function (key) { + + var _this = this; + + var sound = this.getSound(key); + + if (sound) + { + sound.data.src = sound.url; + + sound.data.addEventListener('canplaythrough', function () { + return _this.reloadSoundComplete(key); + }, false); + + sound.data.load(); + } + + }, + + /** + * Fires the onSoundUnlock event when the sound has completed reloading. + * + * @method Phaser.Cache#reloadSoundComplete + * @param {string} key - The key of the asset within the cache. + */ + reloadSoundComplete: function (key) { + + var sound = this.getSound(key); + + if (sound) + { + sound.locked = false; + this.onSoundUnlock.dispatch(key); + } + + }, + + /** + * Updates the sound object in the cache. + * + * @method Phaser.Cache#updateSound + * @param {string} key - The key of the asset within the cache. + */ + updateSound: function (key, property, value) { + + var sound = this.getSound(key); + + if (sound) + { + sound[property] = value; + } + + }, + + /** + * Add a new decoded sound. + * + * @method Phaser.Cache#decodedSound + * @param {string} key - The key of the asset within the cache. + * @param {object} data - Extra sound data. + */ + decodedSound: function (key, data) { + + var sound = this.getSound(key); + + sound.data = data; + sound.decoded = true; + sound.isDecoding = false; + + }, + + /** + * Check if the given sound has finished decoding. + * + * @method Phaser.Cache#isSoundDecoded + * @param {string} key - The key of the asset within the cache. + * @return {boolean} The decoded state of the Sound object. + */ + isSoundDecoded: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return sound.decoded; + } + + }, + + /** + * Check if the given sound is ready for playback. + * A sound is considered ready when it has finished decoding and the device is no longer touch locked. + * + * @method Phaser.Cache#isSoundReady + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the sound is decoded and the device is not touch locked. + */ + isSoundReady: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return (sound.decoded && !this.game.sound.touchLocked); + } + + }, + + //////////////////////// + // Check Key Methods // + //////////////////////// + + /** + * Checks if a key for the given cache object type exists. + * + * @method Phaser.Cache#checkKey + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists, otherwise false. + */ + checkKey: function (cache, key) { + + if (this._cacheMap[cache][key]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given URL has been loaded into the Cache. + * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. + * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox + * which may cause double-load instances. + * + * @method Phaser.Cache#checkURL + * @param {string} url - The url to check for in the cache. + * @return {boolean} True if the url exists, otherwise false. + */ + checkURL: function (url) { + + if (this._urlMap[this._resolveURL(url)]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given key exists in the Canvas Cache. + * + * @method Phaser.Cache#checkCanvasKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkCanvasKey: function (key) { + + return this.checkKey(Phaser.Cache.CANVAS, key); + + }, + + /** + * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. + * + * @method Phaser.Cache#checkImageKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkImageKey: function (key) { + + return this.checkKey(Phaser.Cache.IMAGE, key); + + }, + + /** + * Checks if the given key exists in the Texture Cache. + * + * @method Phaser.Cache#checkTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXTURE, key); + + }, + + /** + * Checks if the given key exists in the Sound Cache. + * + * @method Phaser.Cache#checkSoundKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkSoundKey: function (key) { + + return this.checkKey(Phaser.Cache.SOUND, key); + + }, + + /** + * Checks if the given key exists in the Text Cache. + * + * @method Phaser.Cache#checkTextKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXT, key); + + }, + + /** + * Checks if the given key exists in the Physics Cache. + * + * @method Phaser.Cache#checkPhysicsKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkPhysicsKey: function (key) { + + return this.checkKey(Phaser.Cache.PHYSICS, key); + + }, + + /** + * Checks if the given key exists in the Tilemap Cache. + * + * @method Phaser.Cache#checkTilemapKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTilemapKey: function (key) { + + return this.checkKey(Phaser.Cache.TILEMAP, key); + + }, + + /** + * Checks if the given key exists in the Binary Cache. + * + * @method Phaser.Cache#checkBinaryKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBinaryKey: function (key) { + + return this.checkKey(Phaser.Cache.BINARY, key); + + }, + + /** + * Checks if the given key exists in the BitmapData Cache. + * + * @method Phaser.Cache#checkBitmapDataKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapDataKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPDATA, key); + + }, + + /** + * Checks if the given key exists in the BitmapFont Cache. + * + * @method Phaser.Cache#checkBitmapFontKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapFontKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPFONT, key); + + }, + + /** + * Checks if the given key exists in the JSON Cache. + * + * @method Phaser.Cache#checkJSONKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkJSONKey: function (key) { + + return this.checkKey(Phaser.Cache.JSON, key); + + }, + + /** + * Checks if the given key exists in the XML Cache. + * + * @method Phaser.Cache#checkXMLKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkXMLKey: function (key) { + + return this.checkKey(Phaser.Cache.XML, key); + + }, + + /** + * Checks if the given key exists in the Video Cache. + * + * @method Phaser.Cache#checkVideoKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkVideoKey: function (key) { + + return this.checkKey(Phaser.Cache.VIDEO, key); + + }, + + /** + * Checks if the given key exists in the Fragment Shader Cache. + * + * @method Phaser.Cache#checkShaderKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkShaderKey: function (key) { + + return this.checkKey(Phaser.Cache.SHADER, key); + + }, + + /** + * Checks if the given key exists in the Render Texture Cache. + * + * @method Phaser.Cache#checkRenderTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkRenderTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key); + + }, + + //////////////// + // Get Items // + //////////////// + + /** + * Get an item from a cache based on the given key and property. + * + * This method is mostly used internally by other Cache methods such as `getImage` but is exposed + * publicly for your own use as well. + * + * @method Phaser.Cache#getItem + * @param {string} key - The key of the asset within the cache. + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output. + * @param {string} [property] - If you require a specific property from the cache item, specify it here. + * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. + */ + getItem: function (key, cache, method, property) { + + if (!this.checkKey(cache, key)) + { + if (method) + { + console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.'); + } + } + else + { + if (property === undefined) + { + return this._cacheMap[cache][key]; + } + else + { + return this._cacheMap[cache][key][property]; + } + } + + return null; + + }, + + /** + * Gets a Canvas object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getCanvas + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The canvas object or `null` if no item could be found matching the given key. + */ + getCanvas: function (key) { + + return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas'); + + }, + + /** + * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. + * + * If you need the image used by a bitmap font or similar then please use those respective 'get' methods. + * + * @method Phaser.Cache#getImage + * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. + * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned. + * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. + */ + getImage: function (key, full) { + + if (key === undefined || key === null) + { + key = '__default'; + } + + if (full === undefined) { full = false; } + + var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage'); + + if (img === null) + { + img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage'); + } + + if (full) + { + return img; + } + else + { + return img.data; + } + + }, + + /** + * Get a single texture frame by key. + * + * You'd only do this to get the default Frame created for a non-atlas / spritesheet image. + * + * @method Phaser.Cache#getTextureFrame + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Frame} The frame data. + */ + getTextureFrame: function (key) { + + return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame'); + + }, + + /** + * Gets a Phaser.Sound object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSound + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Sound} The sound object. + */ + getSound: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSound'); + + }, + + /** + * Gets a raw Sound data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSoundData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The sound data. + */ + getSoundData: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data'); + + }, + + /** + * Gets a Text object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getText + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The text data. + */ + getText: function (key) { + + return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data'); + + }, + + /** + * Gets a Physics Data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can get either the entire data set, a single object or a single fixture of an object from it. + * + * @method Phaser.Cache#getPhysicsData + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all. + * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. + * @return {object} The requested physics object data if found. + */ + getPhysicsData: function (key, object, fixtureKey) { + + var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data'); + + if (data === null || object === undefined || object === null) + { + return data; + } + else + { + if (data[object]) + { + var fixtures = data[object]; + + // Try to find a fixture by its fixture key if given + if (fixtures && fixtureKey) + { + for (var fixture in fixtures) + { + // This contains the fixture data of a polygon or a circle + fixture = fixtures[fixture]; + + // Test the key + if (fixture.fixtureKey === fixtureKey) + { + return fixture; + } + } + + // We did not find the requested fixture + console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"'); + } + else + { + return fixtures; + } + } + else + { + console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"'); + } + } + + return null; + + }, + + /** + * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getTilemapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The raw tilemap data in CSV or JSON format. + */ + getTilemapData: function (key) { + + return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData'); + + }, + + /** + * Gets a binary object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBinary + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The binary data object. + */ + getBinary: function (key) { + + return this.getItem(key, Phaser.Cache.BINARY, 'getBinary'); + + }, + + /** + * Gets a BitmapData object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. + */ + getBitmapData: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data'); + + }, + + /** + * Gets a Bitmap Font object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapFont + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not. + */ + getBitmapFont: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont'); + + }, + + /** + * Gets a JSON object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can either return the object by reference (the default), or return a clone + * of it by setting the `clone` argument to `true`. + * + * @method Phaser.Cache#getJSON + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false) + * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. + */ + getJSON: function (key, clone) { + + var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data'); + + if (data) + { + if (clone) + { + return Phaser.Utils.extend(true, Array.isArray(data) ? [] : {}, data); + } + else + { + return data; + } + } + else + { + return null; + } + + }, + + /** + * Gets an XML object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getXML + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The XML object. + */ + getXML: function (key) { + + return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data'); + + }, + + /** + * Gets a Phaser.Video object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getVideo + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Video} The video object. + */ + getVideo: function (key) { + + return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo'); + + }, + + /** + * Gets a fragment shader object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getShader + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {string} The shader object. + */ + getShader: function (key) { + + return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data'); + + }, + + /** + * Gets a RenderTexture object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getRenderTexture + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame. + */ + getRenderTexture: function (key) { + + return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture'); + + }, + + //////////////////////////// + // Frame Related Methods // + //////////////////////////// + + /** + * Gets a PIXI.BaseTexture by key from the given Cache. + * + * @method Phaser.Cache#getBaseTexture + * @param {string} key - Asset key of the image for which you want the BaseTexture for. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {PIXI.BaseTexture} The BaseTexture object. + */ + getBaseTexture: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getBaseTexture', 'base'); + + }, + + /** + * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. + * + * @method Phaser.Cache#getFrame + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.Frame} The frame data. + */ + getFrame: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrame', 'frame'); + + }, + + /** + * Get the total number of frames contained in the FrameData object specified by the given key. + * + * @method Phaser.Cache#getFrameCount + * @param {string} key - Asset key of the FrameData you want. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {number} Then number of frames. 0 if the image is not found. + */ + getFrameCount: function (key, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.total; + } + else + { + return 0; + } + + }, + + /** + * Gets a Phaser.FrameData object from the Image Cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.FrameData} The frame data. + */ + getFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrameData', 'frameData'); + + }, + + /** + * Check if the FrameData for the given key exists in the Image Cache. + * + * @method Phaser.Cache#hasFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {boolean} True if the given key has frameData in the cache, otherwise false. + */ + hasFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return (this.getItem(key, cache, '', 'frameData') !== null); + + }, + + /** + * Replaces a set of frameData with a new Phaser.FrameData object. + * + * @method Phaser.Cache#updateFrameData + * @param {string} key - The unique key by which you will reference this object. + * @param {number} frameData - The new FrameData. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + */ + updateFrameData: function (key, frameData, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + if (this._cacheMap[cache][key]) + { + this._cacheMap[cache][key].frameData = frameData; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByIndex + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {number} index - The index of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByIndex: function (key, index, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrame(index); + } + else + { + return null; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByName + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {string} name - The name of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByName: function (key, name, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrameByName(name); + } + else + { + return null; + } + + }, + + /** + * Get a cached object by the URL. + * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. + * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. + * + * @method Phaser.Cache#getURL + * @param {string} url - The url for the object loaded to get from the cache. + * @return {object} The cached object. + */ + getURL: function (url) { + + var url = this._resolveURL(url); + + if (url) + { + return this._urlMap[url]; + } + else + { + console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false'); + return null; + } + + }, + + /** + * Gets all keys used in the requested Cache. + * + * @method Phaser.Cache#getKeys + * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. + * @return {Array} The array of keys in the requested cache. + */ + getKeys: function (cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + var out = []; + + if (this._cacheMap[cache]) + { + for (var key in this._cacheMap[cache]) + { + if (key !== '__default' && key !== '__missing') + { + out.push(key); + } + } + } + + return out; + + }, + + ///////////////////// + // Remove Methods // + ///////////////////// + + /** + * Removes a canvas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeCanvas + * @param {string} key - Key of the asset you want to remove. + */ + removeCanvas: function (key) { + + delete this._cache.canvas[key]; + + }, + + /** + * Removes an image from the cache. + * + * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. + * + * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeImage + * @param {string} key - Key of the asset you want to remove. + * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed? + */ + removeImage: function (key, destroyBaseTexture) { + + if (destroyBaseTexture === undefined) { destroyBaseTexture = true; } + + var img = this.getImage(key, true); + + if (destroyBaseTexture && img.base) + { + img.base.destroy(); + } + + delete this._cache.image[key]; + + }, + + /** + * Removes a sound from the cache. + * + * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will + * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then + * you must finish your house-keeping and destroy them all yourself first, before calling this method. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSound + * @param {string} key - Key of the asset you want to remove. + */ + removeSound: function (key) { + + delete this._cache.sound[key]; + + }, + + /** + * Removes a text file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeText + * @param {string} key - Key of the asset you want to remove. + */ + removeText: function (key) { + + delete this._cache.text[key]; + + }, + + /** + * Removes a physics data file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removePhysics + * @param {string} key - Key of the asset you want to remove. + */ + removePhysics: function (key) { + + delete this._cache.physics[key]; + + }, + + /** + * Removes a tilemap from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTilemap + * @param {string} key - Key of the asset you want to remove. + */ + removeTilemap: function (key) { + + delete this._cache.tilemap[key]; + + }, + + /** + * Removes a binary file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBinary + * @param {string} key - Key of the asset you want to remove. + */ + removeBinary: function (key) { + + delete this._cache.binary[key]; + + }, + + /** + * Removes a bitmap data from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapData + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapData: function (key) { + + delete this._cache.bitmapData[key]; + + }, + + /** + * Removes a bitmap font from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapFont + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapFont: function (key) { + + delete this._cache.bitmapFont[key]; + + }, + + /** + * Removes a json object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeJSON + * @param {string} key - Key of the asset you want to remove. + */ + removeJSON: function (key) { + + delete this._cache.json[key]; + + }, + + /** + * Removes a xml object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeXML + * @param {string} key - Key of the asset you want to remove. + */ + removeXML: function (key) { + + delete this._cache.xml[key]; + + }, + + /** + * Removes a video from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeVideo + * @param {string} key - Key of the asset you want to remove. + */ + removeVideo: function (key) { + + delete this._cache.video[key]; + + }, + + /** + * Removes a shader from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeShader + * @param {string} key - Key of the asset you want to remove. + */ + removeShader: function (key) { + + delete this._cache.shader[key]; + + }, + + /** + * Removes a Render Texture from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeRenderTexture + * @param {string} key - Key of the asset you want to remove. + */ + removeRenderTexture: function (key) { + + delete this._cache.renderTexture[key]; + + }, + + /** + * Removes a Sprite Sheet from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSpriteSheet + * @param {string} key - Key of the asset you want to remove. + */ + removeSpriteSheet: function (key) { + + delete this._cache.spriteSheet[key]; + + }, + + /** + * Removes a Texture Atlas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTextureAtlas + * @param {string} key - Key of the asset you want to remove. + */ + removeTextureAtlas: function (key) { + + delete this._cache.image[key]; + + }, + + /** + * Empties out all of the GL Textures from Images stored in the cache. + * This is called automatically when the WebGL context is lost and then restored. + * + * @method Phaser.Cache#clearGLTextures + * @protected + */ + clearGLTextures: function () { + + for (var key in this._cache.image) + { + this._cache.image[key].base._glTextures = []; + } + + }, + + /** + * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`. + * This is then looked-up by the Cache.getURL and Cache.checkURL calls. + * + * @method Phaser.Cache#_resolveURL + * @private + * @param {string} url - The URL to resolve. This is appended to Loader.baseURL. + * @param {object} [data] - The data associated with the URL to be stored to the URL Map. + * @return {string} The resolved URL. + */ + _resolveURL: function (url, data) { + + if (!this.autoResolveURL) + { + return null; + } + + this._urlResolver.src = this.game.load.baseURL + url; + + this._urlTemp = this._urlResolver.src; + + // Ensure no request is actually made + this._urlResolver.src = ''; + + // Record the URL to the map + if (data) + { + this._urlMap[this._urlTemp] = data; + } + + return this._urlTemp; + + }, + + /** + * Clears the cache. Removes every local cache object reference. + * If an object in the cache has a `destroy` method it will be called; + * otherwise, `destroy` will be called on any of the object's `base`, `data`, + * `frameData`, or `texture` properties. + * + * @method Phaser.Cache#destroy + */ + destroy: function () { + + for (var i = 0; i < this._cacheMap.length; i++) + { + var cache = this._cacheMap[i]; + + for (var key in cache) + { + if (key !== '__default' && key !== '__missing') + { + this.destroyItem(cache[key]); + + delete cache[key]; + } + } + } + + this._urlMap = null; + this._urlResolver = null; + this._urlTemp = null; + + }, + + /** + * @method Phaser.Cache#destroyItem + * @protected + * @param {object} item + */ + destroyItem: function (item) { + + if (item.destroy) + { + item.destroy(); + } + else + { + if (item.base && item.base.destroy) + { + item.base.destroy(); + } + + if (item.data && item.data.destroy) + { + item.data.destroy(); + } + + if (item.frameData && item.frameData.destroy) + { + item.frameData.destroy(); + } + + if (item.texture && item.texture.destroy) + { + item.texture.destroy(true); + } + } + + }, + + /** + * Starts loading the DEFAULT and MISSING images. + * + * @private + */ + _addImages: function () { + + this._pendingCount = 0; + + this.addDefaultImage(); + this.addMissingImage(); + + var self = this; + var readyTimeout = Phaser.Cache.READY_TIMEOUT; + + if (Phaser.Cache.READY_TIMEOUT > 0) + { + setTimeout(function () { + if (!self.isReady) + { + console.warn('Phaser.Cache: Still waiting for images after %s ms.', readyTimeout); + + self._ready(); + } + }, Phaser.Cache.READY_TIMEOUT); + } + else + { + this._ready(); + } + + }, + + + /** + * Increments the pending count. + * + * @private + */ + _addPending: function () { + + this._pendingCount += 1; + + }, + + + /** + * Decrements the pending count and checks if complete. + * + * @private + */ + _removePending: function () { + + this._pendingCount -= 1; + this._checkReady(); + + }, + + + /** + * Calls {@link #_ready} if no pending items remain. + * + * @private + */ + _checkReady: function () { + + if (this.isReady) + { + this._ready(); + } + + }, + + + /** + * Resets pending count and triggers {@link #onReady}. + * + * @private + */ + _ready: function () { + + this._pendingCount = 0; + this.onReady.dispatch(this); + + } + +}; + +Phaser.Cache.prototype.constructor = Phaser.Cache; + +/** +* The DEFAULT and MISSING textures have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). +* +* @property {boolean} Phaser.Cache#isReady +*/ +Object.defineProperty(Phaser.Cache.prototype, 'isReady', { + get: function () { + return this._pendingCount <= 0; + } +}); + +/* jshint wsh:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* +* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. +* +* Parallel loading (see {@link #enableParallel}) is supported and enabled by default. +* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}. +* +* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and +* [Shoebox](http://renderhjs.net/shoebox/) +* +* @class Phaser.Loader +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Loader = function (game) { + + /** + * Local reference to game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + /** + * Local reference to the Phaser.Cache. + * @property {Phaser.Cache} cache + * @protected + */ + this.cache = game.cache; + + /** + * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * True if the Loader is in the process of loading the queue. + * @property {boolean} isLoading + * @default + */ + this.isLoading = false; + + /** + * True if all assets in the queue have finished loading. + * @property {boolean} hasLoaded + * @default + */ + this.hasLoaded = false; + + /** + * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}. + * + * This property is an object containing: sprite, rect, direction, width and height + * + * @property {?object} preloadSprite + * @protected + */ + this.preloadSprite = null; + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * @property {boolean|string} crossOrigin + * @default + */ + this.crossOrigin = false; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * Useful if allowing the asset base url to be configured outside of the game code. + * The string _must_ end with a "/". + * + * @property {string} baseURL + */ + this.baseURL = ''; + + /** + * The value of `path`, if set, is placed before any _relative_ file path given. For example: + * + * ```javascript + * load.path = "images/sprites/"; + * load.image("ball", "ball.png"); + * load.image("tree", "level1/oaktree.png"); + * load.image("boom", "http://server.com/explode.png"); + * ``` + * + * Would load the `ball` file from `images/sprites/ball.png` and the tree from + * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL + * given as it's an absolute URL. + * + * Please note that the path is added before the filename but *after* the baseURL (if set.) + * + * The string _must_ end with a "/". + * + * @property {string} path + */ + this.path = ''; + + /** + * Used to map the application mime-types to to the Accept header in XHR requests. + * If you don't require these mappings, or they cause problems on your server, then + * remove them from the headers object and the XHR request will not try to use them. + * + * This object can also be used to set the `X-Requested-With` header to + * `XMLHttpRequest` (or any other value you need). To enable this do: + * + * ```javascript + * this.load.headers.requestedWith = 'XMLHttpRequest' + * ``` + * + * before adding anything to the Loader. The XHR loader will then call: + * + * ```javascript + * setRequestHeader('X-Requested-With', this.headers['requestedWith']) + * ``` + * + * @property {object} headers + * @default + */ + this.headers = { + "requestedWith": false, + "json": "application/json", + "xml": "application/xml" + }; + + /** + * This event is dispatched when the loading process starts: before the first file has been requested, + * but after all the initial packs have been loaded. + * + * @property {Phaser.Signal} onLoadStart + */ + this.onLoadStart = new Phaser.Signal(); + + /** + * This event is dispatched when the final file in the load queue has either loaded or failed. + * + * @property {Phaser.Signal} onLoadComplete + */ + this.onLoadComplete = new Phaser.Signal(); + + /** + * This event is dispatched when an asset pack has either loaded or failed to load. + * + * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. + * + * Params: `(pack key, success?, total packs loaded, total packs)` + * + * @property {Phaser.Signal} onPackComplete + */ + this.onPackComplete = new Phaser.Signal(); + + /** + * This event is dispatched immediately before a file starts loading. + * It's possible the file may fail (eg. download error, invalid format) after this event is sent. + * + * Params: `(progress, file key, file url)` + * + * @property {Phaser.Signal} onFileStart + */ + this.onFileStart = new Phaser.Signal(); + + /** + * This event is dispatched when a file has either loaded or failed to load. + * + * Any function bound to this will receive the following parameters: + * + * progress, file key, success?, total loaded files, total files + * + * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. + * + * @property {Phaser.Signal} onFileComplete + */ + this.onFileComplete = new Phaser.Signal(); + + /** + * This event is dispatched when a file (or pack) errors as a result of the load request. + * + * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. + * + * Params: `(file key, file)` + * + * @property {Phaser.Signal} onFileError + */ + this.onFileError = new Phaser.Signal(); + + /** + * If true (the default) then parallel downloading will be enabled. + * + * To disable all parallel downloads this must be set to false prior to any resource being loaded. + * + * @property {boolean} enableParallel + */ + this.enableParallel = true; + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Many current browsers limit 6 requests per domain; this is slightly conservative. + * + * This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently. + * + * @property {integer} maxParallelDownloads + */ + this.maxParallelDownloads = 4; + + /** + * A counter: if more than zero, files will be automatically added as a synchronization point. + * @property {integer} _withSyncPointDepth; + */ + this._withSyncPointDepth = 0; + + /** + * Contains all the information for asset files (including packs) to load. + * + * File/assets are only removed from the list after all loading completes. + * + * @property {file[]} _fileList + * @private + */ + this._fileList = []; + + /** + * Inflight files (or packs) that are being fetched/processed. + * + * This means that if there are any files in the flight queue there should still be processing + * going on; it should only be empty before or after loading. + * + * The files in the queue may have additional properties added to them, + * including `requestObject` which is normally the associated XHR. + * + * @property {file[]} _flightQueue + * @private + */ + this._flightQueue = []; + + /** + * The offset into the fileList past all the complete (loaded or error) entries. + * + * @property {integer} _processingHead + * @private + */ + this._processingHead = 0; + + /** + * True when the first file (not pack) has loading started. + * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded. + * + * @property {boolean} _initialPacksLoaded + * @private + */ + this._fileLoadStarted = false; + + /** + * Total packs seen - adjusted when a pack is added. + * @property {integer} _totalPackCount + * @private + */ + this._totalPackCount = 0; + + /** + * Total files seen - adjusted when a file is added. + * @property {integer} _totalFileCount + * @private + */ + this._totalFileCount = 0; + + /** + * Total packs loaded - adjusted just prior to `onPackComplete`. + * @property {integer} _loadedPackCount + * @private + */ + this._loadedPackCount = 0; + + /** + * Total files loaded - adjusted just prior to `onFileComplete`. + * @property {integer} _loadedFileCount + * @private + */ + this._loadedFileCount = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_PHASER_JSON = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5; + +Phaser.Loader.prototype = { + + /** + * Set a Sprite to be a "preload" sprite by passing it to this method. + * + * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. + * This allows you to easily make loading bars for games. + * + * The sprite will automatically be made visible when calling this. + * + * @method Phaser.Loader#setPreloadSprite + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load. + * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. + */ + setPreloadSprite: function (sprite, direction) { + + direction = direction || 0; + + this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null }; + + if (direction === 0) + { + // Horizontal rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height); + } + else + { + // Vertical rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1); + } + + sprite.crop(this.preloadSprite.rect); + + sprite.visible = true; + + }, + + /** + * Called automatically by ScaleManager when the game resizes in RESIZE scalemode. + * + * This can be used to adjust the preloading sprite size, eg. + * + * @method Phaser.Loader#resize + * @protected + */ + resize: function () { + + if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height) + { + this.preloadSprite.rect.height = this.preloadSprite.sprite.height; + } + + }, + + /** + * Check whether a file/asset with a specific key is queued to be loaded. + * + * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey} + * + * @method Phaser.Loader#checkKeyExists + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ + checkKeyExists: function (type, key) { + + return this.getAssetIndex(type, key) > -1; + + }, + + /** + * Get the queue-index of the file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAssetIndex + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {number} The index of this key in the filelist, or -1 if not found. + * The index may change and should only be used immediately following this call + */ + getAssetIndex: function (type, key) { + + var bestFound = -1; + + for (var i = 0; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + if (file.type === type && file.key === key) + { + bestFound = i; + + // An already loaded/loading file may be superceded. + if (!file.loaded && !file.loading) + { + break; + } + } + } + + return bestFound; + + }, + + /** + * Find a file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAsset + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. + * The index may change and should only be used immediately following this call. + */ + getAsset: function (type, key) { + + var fileIndex = this.getAssetIndex(type, key); + + if (fileIndex > -1) + { + return { index: fileIndex, file: this._fileList[fileIndex] }; + } + + return false; + + }, + + /** + * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. + * + * This will abort any loading and clear any queued assets. + * + * Optionally you can clear any associated events. + * + * @method Phaser.Loader#reset + * @protected + * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared. + * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them. + */ + reset: function (hard, clearEvents) { + + if (clearEvents === undefined) { clearEvents = false; } + + if (this.resetLocked) + { + return; + } + + if (hard) + { + this.preloadSprite = null; + } + + this.isLoading = false; + + this._processingHead = 0; + this._fileList.length = 0; + this._flightQueue.length = 0; + + this._fileLoadStarted = false; + this._totalFileCount = 0; + this._totalPackCount = 0; + this._loadedPackCount = 0; + this._loadedFileCount = 0; + + if (clearEvents) + { + this.onLoadStart.removeAll(); + this.onLoadComplete.removeAll(); + this.onPackComplete.removeAll(); + this.onFileStart.removeAll(); + this.onFileComplete.removeAll(); + this.onFileError.removeAll(); + } + + }, + + /** + * Internal function that adds a new entry to the file list. Do not call directly. + * + * @method Phaser.Loader#addToFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} [url] - The URL the asset will be loaded from. + * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. + * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. + * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. + * @return {Phaser.Loader} This instance of the Phaser Loader. + */ + addToFileList: function (type, key, url, properties, overwrite, extension) { + + if (overwrite === undefined) { overwrite = false; } + + if (key === undefined || key === '') + { + console.warn("Phaser.Loader: Invalid or no key given of type " + type); + return this; + } + + if (url === undefined || url === null) + { + if (extension) + { + url = key + extension; + } + else + { + console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key); + return this; + } + } + + var file = { + type: type, + key: key, + path: this.path, + url: url, + syncPoint: this._withSyncPointDepth > 0, + data: null, + loading: false, + loaded: false, + error: false + }; + + if (properties) + { + for (var prop in properties) + { + file[prop] = properties[prop]; + } + } + + var fileIndex = this.getAssetIndex(type, key); + + if (overwrite && fileIndex > -1) + { + var currentFile = this._fileList[fileIndex]; + + if (!currentFile.loading && !currentFile.loaded) + { + this._fileList[fileIndex] = file; + } + else + { + this._fileList.push(file); + this._totalFileCount++; + } + } + else if (fileIndex === -1) + { + this._fileList.push(file); + this._totalFileCount++; + } + + return this; + + }, + + /** + * Internal function that replaces an existing entry in the file list with a new one. Do not call directly. + * + * @method Phaser.Loader#replaceInFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} url - The URL the asset will be loaded from. + * @param {object} properties - Any additional properties needed to load the file. + */ + replaceInFileList: function (type, key, url, properties) { + + return this.addToFileList(type, key, url, properties, true); + + }, + + /** + * Add a JSON resource pack ('packfile') to the Loader. + * + * A packfile is a JSON file that contains a list of assets to the be loaded. + * Please see the example 'loader/asset pack' in the Phaser Examples repository. + * + * Packs are always put before the first non-pack file that is not loaded / loading. + * + * This means that all packs added before any loading has started are added to the front + * of the file queue, in the order added. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#pack + * @param {string} key - Unique asset key of this resource pack. + * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. + * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO + * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. + * @return {Phaser.Loader} This Loader instance. + */ + pack: function (key, url, data, callbackContext) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (callbackContext === undefined) { callbackContext = null; } + + if (!url && !data) + { + console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.'); + + return this; + } + + var pack = { + type: 'packfile', + key: key, + url: url, + path: this.path, + syncPoint: true, + data: null, + loading: false, + loaded: false, + error: false, + callbackContext: callbackContext + }; + + // A data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + pack.data = data || {}; + + // Already consider 'loaded' + pack.loaded = true; + } + + // Add before first non-pack/no-loaded ~ last pack from start prior to loading + // (Read one past for splice-to-end) + for (var i = 0; i < this._fileList.length + 1; i++) + { + var file = this._fileList[i]; + + if (!file || (!file.loaded && !file.loading && file.type !== 'packfile')) + { + this._fileList.splice(i, 0, pack); + this._totalPackCount++; + break; + } + } + + return this; + + }, + + /** + * Adds an Image to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * This method also supports passing in a texture object as the `url` argument. This allows you to load + * compressed textures into Phaser. You can also use `Loader.texture` to do this. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.image('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * @method Phaser.Loader#image + * @param {string} key - Unique asset key of this image file. + * @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + image: function (key, url, overwrite) { + + if (typeof url === 'object') + { + return this.texture(key, url, overwrite); + } + else + { + return this.addToFileList('image', key, url, undefined, overwrite, '.png'); + } + + }, + + /** + * Generate an image from a BitmapData object and add it to the current load queue. + * + * @method Phaser.Loader#imageFromBitmapData + * @param {string} key - Unique asset key for the generated image. + * @param {Phaser.BitmapData} bitmapData + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + imageFromBitmapData: function (key, bitmapData, overwrite) { + + return this.image(key, bitmapData.canvas.toDataURL('image/png'), overwrite); + + }, + + /** + * Generate a grid image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromGrid + * @see Phaser.Create#grid + */ + imageFromGrid: function (key, width, height, cellWidth, cellHeight, color) { + + return this.imageFromBitmapData(key, this.game.create.grid(key, width, height, cellWidth, cellHeight, color, false)); + + }, + + /** + * Generate a texture image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromTexture + * @see Phaser.Create#texture + */ + imageFromTexture: function (key, data, pixelWidth, pixelHeight, palette) { + + return this.imageFromBitmapData(key, this.game.create.texture(key, data, pixelWidth, pixelHeight, palette, false)); + + }, + + /** + * Adds a Compressed Texture Image to the current load queue. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.texture('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#texture + * @param {string} key - Unique asset key of this image file. + * @param {object} object - The texture path data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + texture: function (key, object, overwrite) { + + if (this.game.renderType === Phaser.WEBGL) + { + var compression = this.game.renderer.extensions.compression; + var exkey; + + for (exkey in object) + { + if (exkey.toUpperCase() in compression) + { + return this.addToFileList('texture', key, object[exkey], undefined, overwrite, '.pvr'); + } + } + } + + // Check if we have a truecolor texture to fallback. + // Also catches calls to this function that are from a Canvas renderer + + if (object['truecolor']) + { + this.addToFileList('image', key, object['truecolor'], undefined, overwrite, '.png'); + } + + return this; + + }, + + /** + * Adds an array of images to the current load queue. + * + * It works by passing each element of the array to the Loader.image method. + * + * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. + * + * Retrieve the images via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#images + * @param {array} keys - An array of unique asset keys of the image files. + * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. + * @return {Phaser.Loader} This Loader instance. + */ + images: function (keys, urls) { + + if (Array.isArray(urls)) + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i], urls[i]); + } + } + else + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i]); + } + } + + return this; + + }, + + /** + * Adds a Text file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getText(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#text + * @param {string} key - Unique asset key of the text file. + * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + text: function (key, url, overwrite) { + + return this.addToFileList('text', key, url, undefined, overwrite, '.txt'); + + }, + + /** + * Adds a JSON file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#json + * @param {string} key - Unique asset key of the json file. + * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + json: function (key, url, overwrite) { + + return this.addToFileList('json', key, url, undefined, overwrite, '.json'); + + }, + + /** + * Adds a fragment shader file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getShader(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" + * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#shader + * @param {string} key - Unique asset key of the fragment file. + * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + shader: function (key, url, overwrite) { + + return this.addToFileList('shader', key, url, undefined, overwrite, '.frag'); + + }, + + /** + * Adds an XML file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getXML(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#xml + * @param {string} key - Unique asset key of the xml file. + * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + xml: function (key, url, overwrite) { + + return this.addToFileList('xml', key, url, undefined, overwrite, '.xml'); + + }, + + /** + * Adds a JavaScript file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. + * If you do not desire this action then provide a URL. + * + * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! + * + * A callback, which will be invoked as the script tag has been created, can also be specified. + * The callback must return relevant `data`. + * + * @method Phaser.Loader#script + * @param {string} key - Unique asset key of the script file. + * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing. + * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. + * @return {Phaser.Loader} This Loader instance. + */ + script: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + if (callback !== false && callbackContext === undefined) { callbackContext = this; } + + return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js'); + + }, + + /** + * Adds a binary file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBinary(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. + * If you do not desire this action then provide a URL. + * + * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. + * When the callback is called it will be passed 2 parameters: the key of the file and the file data. + * + * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. + * + * @method Phaser.Loader#binary + * @param {string} key - Unique asset key of the binary file. + * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it. + * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context. + * @return {Phaser.Loader} This Loader instance. + */ + binary: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + // Why is the default callback context the ..callback? + if (callback !== false && callbackContext === undefined) { callbackContext = callback; } + + return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin'); + + }, + + /** + * Adds a Sprite Sheet to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal + * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. + * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. + * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming + * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. + * If you've got an atlas then use `Loader.atlas` instead. + * + * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#spritesheet + * @param {string} key - Unique asset key of the sheet file. + * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet. + * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.Loader} This Loader instance. + */ + spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing, skipFrames: skipFrames }, false, '.png'); + + }, + + /** + * Adds an audio file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getSound(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. + * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. + * The solution is to use a lower encoding rate such as 44100 Hz. + * + * @method Phaser.Loader#audio + * @param {string} key - Unique asset key of the audio file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp3']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audio: function (key, urls, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (autoDecode === undefined) { autoDecode = true; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); + + }, + + /** + * Adds an audio sprite file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Audio Sprites are a combination of audio files and a JSON configuration. + * + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * Retrieve the file via `Cache.getSoundData(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#audioSprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (jsonURL === undefined) { jsonURL = null; } + if (jsonData === undefined) { jsonData = null; } + if (autoDecode === undefined) { autoDecode = true; } + + this.audio(key, urls, autoDecode); + + if (jsonURL) + { + this.json(key + '-audioatlas', jsonURL); + } + else if (jsonData) + { + if (typeof jsonData === 'string') + { + jsonData = JSON.parse(jsonData); + } + + this.cache.addJSON(key + '-audioatlas', '', jsonData); + } + else + { + console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object'); + } + + return this; + + }, + + /** + * A legacy alias for Loader.audioSprite. Please see that method for documentation. + * + * @method Phaser.Loader#audiosprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode); + + }, + + /** + * Adds a video file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getVideo(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. + * + * @method Phaser.Loader#video + * @param {string} key - Unique asset key of the video file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp4']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete. + * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. + * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. + * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the + * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. + * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set. + * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. + * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. + * @return {Phaser.Loader} This Loader instance. + */ + video: function (key, urls, loadEvent, asBlob) { + + if (loadEvent === undefined) + { + if (this.game.device.firefox) + { + loadEvent = 'loadeddata'; + } + else + { + loadEvent = 'canplaythrough'; + } + } + + if (asBlob === undefined) { asBlob = false; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent }); + + }, + + /** + * Adds a Tile Map data file to the current load queue. + * + * Phaser can load data in two different formats: CSV and Tiled JSON. + * + * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". + * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#tilemap + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. + * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + * @return {Phaser.Loader} This Loader instance. + */ + tilemap: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Tilemap.CSV; } + + if (!url && !data) + { + if (format === Phaser.Tilemap.CSV) + { + url = key + '.csv'; + } + else + { + url = key + '.json'; + } + } + + // A map data object has been given + if (data) + { + switch (format) + { + // A csv string or object has been given + case Phaser.Tilemap.CSV: + break; + + // A json string or object has been given + case Phaser.Tilemap.TILED_JSON: + + if (typeof data === 'string') + { + data = JSON.parse(data); + } + break; + } + + this.cache.addTilemap(key, null, data, format); + } + else + { + this.addToFileList('tilemap', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds a physics data file to the current load queue. + * + * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". + * It will always use `.json` as the extension. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#physics + * @param {string} key - Unique asset key of the physics json data. + * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. + * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data. + * @return {Phaser.Loader} This Loader instance. + */ + physics: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; } + + if (!url && !data) + { + url = key + '.json'; + } + + // A map data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + this.cache.addPhysicsData(key, null, data, format); + } + else + { + this.addToFileList('physics', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds Bitmap Font files to the current load queue. + * + * To create the Bitmap Font files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `xmlData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#bitmapFont + * @param {string} key - Unique asset key of the bitmap font. + * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". + * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". + * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json). + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + * @return {Phaser.Loader} This Loader instance. + */ + bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (atlasURL === null && atlasData === null) + { + atlasURL = key + '.xml'; + } + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + // A URL to a json/xml atlas has been given + if (atlasURL) + { + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing }); + } + else + { + // A stringified xml/json atlas has been given + if (typeof atlasData === 'string') + { + var json, xml; + + try + { + json = JSON.parse(atlasData); + } + catch ( e ) + { + xml = this.parseXml(atlasData); + } + + if (!xml && !json) + { + throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given"); + } + + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml, + atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing }); + } + } + + return this; + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONArray + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONHash + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * This call expects the atlas data to be in the Starling XML data format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasXML + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasXML: function (key, textureURL, atlasURL, atlasData) { + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (!atlasURL && !atlasData) + { + atlasURL = key + '.xml'; + } + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlas + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. + * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING. + * @return {Phaser.Loader} This Loader instance. + */ + atlas: function (key, textureURL, atlasURL, atlasData, format) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } + + if (!atlasURL && !atlasData) + { + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + atlasURL = key + '.xml'; + } + else + { + atlasURL = key + '.json'; + } + } + + // A URL to a json/xml file has been given + if (atlasURL) + { + this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); + } + else + { + switch (format) + { + // A json string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: + + if (typeof atlasData === 'string') + { + atlasData = JSON.parse(atlasData); + } + break; + + // An xml string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: + + if (typeof atlasData === 'string') + { + var xml = this.parseXml(atlasData); + + if (!xml) + { + throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); + } + + atlasData = xml; + } + break; + } + + this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); + + } + + return this; + + }, + + /** + * Add a synchronization point to the assets / files added within the supplied callback. + * + * A synchronization point denotes that an asset _must_ be completely loaded before + * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait + * for previous assets to load (unless they are sync-points). Resources, such as packs, may still + * be downloaded around sync-points, as long as they do not finalize loading. + * + * @method Phaser.Loader#withSyncPoint + * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader. + * @param {object} [callbackContext=(loader)] - Context for the callback. + * @return {Phaser.Loader} This Loader instance. + */ + withSyncPoint: function (callback, callbackContext) { + + this._withSyncPointDepth++; + + try { + callback.call(callbackContext || this, this); + } finally { + this._withSyncPointDepth--; + } + + return this; + }, + + /** + * Add a synchronization point to a specific file/asset in the load queue. + * + * This has no effect on already loaded assets. + * + * @method Phaser.Loader#addSyncPoint + * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc). + * @param {string} key - Key of the file you want to turn into a sync point. + * @return {Phaser.Loader} This Loader instance. + * @see {@link Phaser.Loader#withSyncPoint withSyncPoint} + */ + addSyncPoint: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + asset.file.syncPoint = true; + } + + return this; + }, + + /** + * Remove a file/asset from the loading queue. + * + * A file that is loaded or has started loading cannot be removed. + * + * @method Phaser.Loader#removeFile + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - Key of the file you want to remove. + */ + removeFile: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + if (!asset.loaded && !asset.loading) + { + this._fileList.splice(asset.index, 1); + } + } + + }, + + /** + * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead. + * + * @method Phaser.Loader#removeAll + * @protected + */ + removeAll: function () { + + this._fileList.length = 0; + this._flightQueue.length = 0; + + }, + + /** + * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. + * + * @method Phaser.Loader#start + */ + start: function () { + + if (this.isLoading) + { + return; + } + + this.hasLoaded = false; + this.isLoading = true; + + this.updateProgress(); + + this.processLoadQueue(); + + }, + + /** + * Process the next item(s) in the file/asset queue. + * + * Process the queue and start loading enough items to fill up the inflight queue. + * + * If a sync-file is encountered then subsequent asset processing is delayed until it completes. + * The exception to this rule is that packfiles can be downloaded (but not processed) even if + * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel. + * such as during the start phaser. + * + * @method Phaser.Loader#processLoadQueue + * @private + */ + processLoadQueue: function () { + + if (!this.isLoading) + { + console.warn('Phaser.Loader - active loading canceled / reset'); + this.finishedLoading(true); + return; + } + + // Empty the flight queue as applicable + for (var i = 0; i < this._flightQueue.length; i++) + { + var file = this._flightQueue[i]; + + if (file.loaded || file.error) + { + this._flightQueue.splice(i, 1); + i--; + + file.loading = false; + file.requestUrl = null; + file.requestObject = null; + + if (file.error) + { + this.onFileError.dispatch(file.key, file); + } + + if (file.type !== 'packfile') + { + this._loadedFileCount++; + this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount); + } + else if (file.type === 'packfile' && file.error) + { + // Non-error pack files are handled when processing the file queue + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + } + } + + // When true further non-pack file downloads are suppressed + var syncblock = false; + + var inflightLimit = this.enableParallel ? Math.max(1, this.maxParallelDownloads) : 1; + + for (var i = this._processingHead; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + // Pack is fetched (ie. has data) and is currently at the start of the process queue. + if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead) + { + // Processing the pack / adds more files + this.processPack(file); + + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + if (file.loaded || file.error) + { + // Item at the start of file list finished, can skip it in future + if (i === this._processingHead) + { + this._processingHead = i + 1; + } + } + else if (!file.loading && this._flightQueue.length < inflightLimit) + { + // -> not loaded/failed, not loading + if (file.type === 'packfile' && !file.data) + { + // Fetches the pack data: the pack is processed above as it reaches queue-start. + // (Packs do not trigger onLoadStart or onFileStart.) + this._flightQueue.push(file); + file.loading = true; + + this.loadFile(file); + } + else if (!syncblock) + { + if (!this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this._flightQueue.push(file); + file.loading = true; + this.onFileStart.dispatch(this.progress, file.key, file.url); + + this.loadFile(file); + } + } + + if (!file.loaded && file.syncPoint) + { + syncblock = true; + } + + // Stop looking if queue full - or if syncblocked and there are no more packs. + // (As only packs can be loaded around a syncblock) + if (this._flightQueue.length >= inflightLimit || + (syncblock && this._loadedPackCount === this._totalPackCount)) + { + break; + } + } + + this.updateProgress(); + + // True when all items in the queue have been advanced over + // (There should be no inflight items as they are complete - loaded/error.) + if (this._processingHead >= this._fileList.length) + { + this.finishedLoading(); + } + else if (!this._flightQueue.length) + { + // Flight queue is empty but file list is not done being processed. + // This indicates a critical internal error with no known recovery. + console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled"); + + var _this = this; + + setTimeout(function () { + _this.finishedLoading(true); + }, 2000); + } + + }, + + /** + * The loading is all finished. + * + * @method Phaser.Loader#finishedLoading + * @private + * @param {boolean} [abnormal=true] - True if the loading finished abnormally. + */ + finishedLoading: function (abnormal) { + + if (this.hasLoaded) + { + return; + } + + this.hasLoaded = true; + this.isLoading = false; + + // If there were no files make sure to trigger the event anyway, for consistency + if (!abnormal && !this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this.reset(); + + this.onLoadComplete.dispatch(); + + // Check if the state still exists since destroy could have occurred while loading + if (this.game.state) + { + this.game.state.loadComplete(); + } + + }, + + /** + * Informs the loader that the given file resource has been fetched and processed; + * or such a request has failed. + * + * @method Phaser.Loader#asyncComplete + * @private + * @param {object} file + * @param {string} [error=''] - The error message, if any. No message implies no error. + */ + asyncComplete: function (file, errorMessage) { + + if (errorMessage === undefined) { errorMessage = ''; } + + file.loaded = true; + file.error = !!errorMessage; + + if (errorMessage) + { + file.errorMessage = errorMessage; + + console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage); + } + + this.processLoadQueue(); + + }, + + /** + * Process pack data. This will usually modify the file list. + * + * @method Phaser.Loader#processPack + * @private + * @param {object} pack + */ + processPack: function (pack) { + + var packData = pack.data[pack.key]; + + if (!packData) + { + console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key'); + return; + } + + for (var i = 0; i < packData.length; i++) + { + var file = packData[i]; + + switch (file.type) + { + case "image": + this.image(file.key, file.url, file.overwrite); + break; + + case "text": + this.text(file.key, file.url, file.overwrite); + break; + + case "json": + this.json(file.key, file.url, file.overwrite); + break; + + case "xml": + this.xml(file.key, file.url, file.overwrite); + break; + + case "script": + this.script(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "binary": + this.binary(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "spritesheet": + this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case "video": + this.video(file.key, file.urls); + break; + + case "audio": + this.audio(file.key, file.urls, file.autoDecode); + break; + + case "audiosprite": + this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode); + break; + + case "tilemap": + this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]); + break; + + case "physics": + this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]); + break; + + case "bitmapFont": + this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing); + break; + + case "atlasJSONArray": + this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasJSONHash": + this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasXML": + this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlas": + this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]); + break; + + case "shader": + this.shader(file.key, file.url, file.overwrite); + break; + } + } + + }, + + /** + * Transforms the asset URL. + * + * The default implementation prepends the baseURL if the url doesn't begin with http or // + * + * @method Phaser.Loader#transformUrl + * @protected + * @param {string} url - The url to transform. + * @param {object} file - The file object being transformed. + * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead. + */ + transformUrl: function (url, file) { + + if (!url) + { + return false; + } + + if (url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) + { + return url; + } + else + { + return this.baseURL + file.path + url; + } + + }, + + /** + * Start fetching a resource. + * + * All code paths, async or otherwise, from this function must return to `asyncComplete`. + * + * @method Phaser.Loader#loadFile + * @private + * @param {object} file + */ + loadFile: function (file) { + + // Image or Data? + switch (file.type) + { + case 'packfile': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'image': + case 'spritesheet': + case 'textureatlas': + case 'bitmapfont': + this.loadImageTag(file); + break; + + case 'audio': + file.url = this.getAudioURL(file.url); + + if (file.url) + { + // WebAudio or Audio Tag? + if (this.game.sound.usingWebAudio) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + else if (this.game.sound.usingAudioTag) + { + this.loadAudioTag(file); + } + } + else + { + this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support'); + } + break; + + case 'video': + file.url = this.getVideoURL(file.url); + + if (file.url) + { + if (file.asBlob) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'blob', this.fileComplete); + } + else + { + this.loadVideoTag(file); + } + } + else + { + this.fileError(file, null, 'No supported video URL specified or device does not have video playback support'); + } + break; + + case 'json': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + break; + + case 'xml': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete); + break; + + case 'tilemap': + + if (file.format === Phaser.Tilemap.TILED_JSON) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Tilemap.CSV) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete); + } + else + { + this.asyncComplete(file, "invalid Tilemap format: " + file.format); + } + break; + + case 'text': + case 'script': + case 'shader': + case 'physics': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'texture': + + if (file.key.split('_').pop() === 'truecolor') + { + this.loadImageTag(file); + } + else + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + break; + + case 'binary': + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + break; + } + + }, + + /** + * Continue async loading through an Image tag. + * @private + */ + loadImageTag: function (file) { + var _this = this; + + file.data = new Image(); + file.data.name = file.key; + + if (this.crossOrigin) + { + file.data.crossOrigin = this.crossOrigin; + } + + file.data.onload = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileComplete(file); + } + }; + + file.data.onerror = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileError(file); + } + }; + + file.data.src = this.transformUrl(file.url, file); + + // Image is immediately-available/cached + // Special Firefox magic, exclude from cached reload + // More info here: https://github.com/photonstorm/phaser/issues/2534 + if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height) + { + file.data.onload = null; + file.data.onerror = null; + this.fileComplete(file); + } + + }, + + /** + * Continue async loading through a Video tag. + * @private + */ + loadVideoTag: function (file) { + + var _this = this; + + file.data = document.createElement("video"); + file.data.name = file.key; + file.data.controls = false; + file.data.autoplay = false; + + var videoLoadEvent = function () { + + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = true; + Phaser.GAMES[_this.game.id].load.fileComplete(file); + + }; + + file.data.onerror = function () { + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = false; + _this.fileError(file); + }; + + file.data.addEventListener(file.loadEvent, videoLoadEvent, false); + + file.data.src = this.transformUrl(file.url, file); + file.data.load(); + + }, + + /** + * Continue async loading through an Audio tag. + * @private + */ + loadAudioTag: function (file) { + + var _this = this; + + if (this.game.sound.touchLocked) + { + // If audio is locked we can't do this yet, so need to queue this load request. Bum. + file.data = new Audio(); + file.data.name = file.key; + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + + this.fileComplete(file); + } + else + { + file.data = new Audio(); + file.data.name = file.key; + + var playThroughEvent = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileComplete(file); + }; + + file.data.onerror = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileError(file); + }; + + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + file.data.addEventListener('canplaythrough', playThroughEvent, false); + file.data.load(); + } + + }, + + /** + * Starts the xhr loader. + * + * This is designed specifically to use with asset file processing. + * + * @method Phaser.Loader#xhrLoad + * @private + * @param {object} file - The file/pack to load. + * @param {string} url - The URL of the file. + * @param {string} type - The xhr responseType. + * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments. + * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments. + */ + xhrLoad: function (file, url, type, onload, onerror) { + + var xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = type; + + if (this.headers['requestedWith'] !== false) + { + xhr.setRequestHeader('X-Requested-With', this.headers['requestedWith']); + } + + if (this.headers[file.type]) + { + xhr.setRequestHeader('Accept', this.headers[file.type]); + } + + onerror = onerror || this.fileError; + + var _this = this; + + xhr.onload = function () { + + try { + if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. + return onerror.call(_this, file, xhr); + } + else { + return onload.call(_this, file, xhr); + } + } catch (e) { + + // If this was the last file in the queue and an error is thrown in the create method + // then it's caught here, so be sure we don't carry on processing it + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + } + }; + + xhr.onerror = function () { + + try { + + return onerror.call(_this, file, xhr); + + } catch (e) { + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + + } + }; + + file.requestObject = xhr; + file.requestUrl = url; + + xhr.send(); + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getVideoURL + * @private + * @param {object[]|string[]} urls - See {@link #video} for format. + * @return {string} The URL to try and fetch; or null. + */ + getVideoURL: function (urls) { + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var videoType; + + if (url.uri) // {uri: .., type: ..} pair + { + videoType = url.type; + url = url.uri; + + if (this.game.device.canPlayVideo(videoType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + videoType = extension.toLowerCase(); + + if (this.game.device.canPlayVideo(videoType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getAudioURL + * @private + * @param {object[]|string[]} urls - See {@link #audio} for format. + * @return {string} The URL to try and fetch; or null. + */ + getAudioURL: function (urls) { + + if (this.game.sound.noAudio) + { + return null; + } + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var audioType; + + if (url.uri) // {uri: .., type: ..} pair + { + audioType = url.type; + url = url.uri; + + if (this.game.device.canPlayAudio(audioType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + audioType = extension.toLowerCase(); + + if (this.game.device.canPlayAudio(audioType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Error occurred when loading a file. + * + * @method Phaser.Loader#fileError + * @private + * @param {object} file + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + * @param {string} reason + */ + fileError: function (file, xhr, reason) { + + var url = file.requestUrl || this.transformUrl(file.url, file); + var message = 'error loading asset from URL ' + url; + + if (!reason && xhr) + { + reason = xhr.status; + } + + if (reason) + { + message = message + ' (' + reason + ')'; + } + + this.asyncComplete(file, message); + + }, + + /** + * Called when a file has been downloaded and needs to be processed further. + * + * @method Phaser.Loader#fileComplete + * @private + * @param {object} file - File loaded + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + */ + fileComplete: function (file, xhr) { + + var loadNext = true; + + switch (file.type) + { + case 'packfile': + + // Pack data must never be false-ish after it is fetched without error + var data = JSON.parse(xhr.responseText); + file.data = data || {}; + break; + + case 'texture': + + var extension = /\.([^.]+)$/.exec(file.url.split('?', 1)[0])[1].toLowerCase(); + if (file.data !== null) + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, file.data); + } + else + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, xhr.response); + } + break; + + case 'image': + + this.cache.addImage(file.key, file.url, file.data); + break; + + case 'spritesheet': + + this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case 'textureatlas': + + if (file.atlasURL == null) + { + this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); + } + else + { + // Load the JSON or XML before carrying on with the next file + loadNext = false; + + if (file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_HASH || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete); + } + else + { + throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); + } + } + break; + + case 'bitmapfont': + + if (!file.atlasURL) + { + this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing); + } + else + { + // Load the XML before carrying on with the next file + loadNext = false; + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) { + var json; + + try + { + // Try to parse as JSON, if it fails, then it's hopefully XML + json = JSON.parse(xhr.responseText); + } + catch (e) {} + + if (!!json) + { + file.atlasType = 'json'; + this.jsonLoadComplete(file, xhr); + } + else + { + file.atlasType = 'xml'; + this.xmlLoadComplete(file, xhr); + } + }); + } + break; + + case 'video': + + if (file.asBlob) + { + try + { + file.data = xhr.response; + } + catch (e) + { + throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key); + } + } + + this.cache.addVideo(file.key, file.url, file.data, file.asBlob); + break; + + case 'audio': + + if (this.game.sound.usingWebAudio) + { + file.data = xhr.response; + + this.cache.addSound(file.key, file.url, file.data, true, false); + + if (file.autoDecode) + { + this.game.sound.decode(file.key); + } + } + else + { + this.cache.addSound(file.key, file.url, file.data, false, true); + } + break; + + case 'text': + file.data = xhr.responseText; + this.cache.addText(file.key, file.url, file.data); + break; + + case 'shader': + file.data = xhr.responseText; + this.cache.addShader(file.key, file.url, file.data); + break; + + case 'physics': + var data = JSON.parse(xhr.responseText); + this.cache.addPhysicsData(file.key, file.url, data, file.format); + break; + + case 'script': + file.data = document.createElement('script'); + file.data.language = 'javascript'; + file.data.type = 'text/javascript'; + file.data.defer = false; + file.data.text = xhr.responseText; + document.head.appendChild(file.data); + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText); + } + break; + + case 'binary': + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.response); + } + else + { + file.data = xhr.response; + } + + this.cache.addBinary(file.key, file.data); + + break; + } + + if (loadNext) + { + this.asyncComplete(file); + } + + }, + + /** + * Successfully loaded a JSON file - only used for certain types. + * + * @method Phaser.Loader#jsonLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + jsonLoadComplete: function (file, xhr) { + + var data = JSON.parse(xhr.responseText); + + if (file.type === 'tilemap') + { + this.cache.addTilemap(file.key, file.url, data, file.format); + } + else if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'json') + { + this.cache.addJSON(file.key, file.url, data); + } + else + { + this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); + } + + this.asyncComplete(file); + }, + + /** + * Successfully loaded a CSV file - only used for certain types. + * + * @method Phaser.Loader#csvLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + csvLoadComplete: function (file, xhr) { + + var data = xhr.responseText; + + this.cache.addTilemap(file.key, file.url, data, file.format); + + this.asyncComplete(file); + + }, + + /** + * Successfully loaded an XML file - only used for certain types. + * + * @method Phaser.Loader#xmlLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + xmlLoadComplete: function (file, xhr) { + + // Always try parsing the content as XML, regardless of actually response type + var data = xhr.responseText; + var xml = this.parseXml(data); + + if (!xml) + { + var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest + console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')'); + this.asyncComplete(file, "invalid XML"); + return; + } + + if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'textureatlas') + { + this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); + } + else if (file.type === 'xml') + { + this.cache.addXML(file.key, file.url, xml); + } + + this.asyncComplete(file); + + }, + + /** + * Parses string data as XML. + * + * @method Phaser.Loader#parseXml + * @private + * @param {string} data - The XML text to parse + * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document. + */ + parseXml: function (data) { + + var xml; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + // Why is this 'false'? + xml.async = 'false'; + xml.loadXML(data); + } + } + catch (e) + { + xml = null; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + return null; + } + else + { + return xml; + } + + }, + + /** + * Update the loading sprite progress. + * + * @method Phaser.Loader#updateProgress + * @private + */ + updateProgress: function () { + + if (this.preloadSprite) + { + if (this.preloadSprite.direction === 0) + { + this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress); + } + else + { + this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress); + } + + if (this.preloadSprite.sprite) + { + this.preloadSprite.sprite.updateCrop(); + } + else + { + // We seem to have lost our sprite - maybe it was destroyed? + this.preloadSprite = null; + } + } + + }, + + /** + * Returns the number of files that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedFiles + * @protected + * @return {number} The number of files that have already been loaded (even if they errored) + */ + totalLoadedFiles: function () { + + return this._loadedFileCount; + + }, + + /** + * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedFiles + * @protected + * @return {number} The number of files that still remain in the load queue. + */ + totalQueuedFiles: function () { + + return this._totalFileCount - this._loadedFileCount; + + }, + + /** + * Returns the number of asset packs that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedPacks + * @protected + * @return {number} The number of asset packs that have already been loaded (even if they errored) + */ + totalLoadedPacks: function () { + + return this._totalPackCount; + + }, + + /** + * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedPacks + * @protected + * @return {number} The number of asset packs that still remain in the load queue. + */ + totalQueuedPacks: function () { + + return this._totalPackCount - this._loadedPackCount; + + } + +}; + +/** +* The non-rounded load progress value (from 0.0 to 100.0). +* +* A general indicator of the progress. +* It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. +* +* @name Phaser.Loader#progressFloat +* @property {number} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progressFloat", { + + get: function () { + var progress = (this._loadedFileCount / this._totalFileCount) * 100; + return Phaser.Math.clamp(progress || 0, 0, 100); + } + +}); + +/** +* The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}. +* +* @name Phaser.Loader#progress +* @property {integer} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progress", { + + get: function () { + return Math.round(this.progressFloat); + } + +}); + +Phaser.Loader.prototype.constructor = Phaser.Loader; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. +* +* @class Phaser.LoaderParser +*/ +Phaser.LoaderParser = { + + /** + * Alias for xmlBitmapFont, for backwards compatibility. + * + * @method Phaser.LoaderParser.bitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + bitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing, frame, resolution); + + }, + + /** + * Parse a Bitmap Font from an XML file. + * + * @method Phaser.LoaderParser.xmlBitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing; + data.chars = {}; + + var letters = xml.getElementsByTagName('char'); + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + for (var i = 0; i < letters.length; i++) + { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + data.chars[charCode] = { + x: x + parseInt(letters[i].getAttribute('x'), 10), + y: y + parseInt(letters[i].getAttribute('y'), 10), + width: parseInt(letters[i].getAttribute('width'), 10), + height: parseInt(letters[i].getAttribute('height'), 10), + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10) / resolution, + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10) / resolution, + xAdvance: (parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing) / resolution, + kerning: {} + }; + } + + var kernings = xml.getElementsByTagName('kerning'); + + for (i = 0; i < kernings.length; i++) + { + var first = parseInt(kernings[i].getAttribute('first'), 10); + var second = parseInt(kernings[i].getAttribute('second'), 10); + var amount = parseInt(kernings[i].getAttribute('amount'), 10) / resolution; + + data.chars[second].kerning[first] = amount; + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Parse a Bitmap Font from a JSON file. + * + * @method Phaser.LoaderParser.jsonBitmapFont + * @param {object} json - JSON data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = { + font: json.font.info._face, + size: parseInt(json.font.info._size, 10), + lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing, + chars: {} + }; + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + json.font.chars["char"].forEach( + + function parseChar(letter) { + + var charCode = parseInt(letter._id, 10); + + data.chars[charCode] = { + x: x + parseInt(letter._x, 10), + y: y + parseInt(letter._y, 10), + width: parseInt(letter._width, 10), + height: parseInt(letter._height, 10), + xOffset: parseInt(letter._xoffset, 10) / resolution, + yOffset: parseInt(letter._yoffset, 10) / resolution, + xAdvance: (parseInt(letter._xadvance, 10) + xSpacing) / resolution, + kerning: {} + }; + } + + ); + + if (json.font.kernings && json.font.kernings.kerning) + { + json.font.kernings.kerning.forEach( + + function parseKerning(kerning) { + + data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10) / resolution; + + } + + ); + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Finalize Bitmap Font parsing. + * + * @method Phaser.LoaderParser.finalizeBitmapFont + * @private + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {object} bitmapFontData - Pre-parsed bitmap font data. + * @return {object} The parsed Bitmap Font data. + */ + finalizeBitmapFont: function (baseTexture, bitmapFontData) { + + Object.keys(bitmapFontData.chars).forEach( + + function addTexture(charCode) { + + var letter = bitmapFontData.chars[charCode]; + + letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height)); + + } + + ); + + return bitmapFontData; + + }, + + /** + * Extract PVR header from loaded binary + * + * @method Phaser.LoaderParser.pvr + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PVR file including texture data. + */ + pvr: function (arrayBuffer) { + + // Reference: http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf + // PVR 3 header structure + // --------------------------------------- + // address: 0, size: 4 bytes version + // address: 4, size: 4 bytes flags + // address: 8, size: 8 bytes pixel format + // address: 16, size: 4 bytes color space + // address: 20, size: 4 bytes channel type + // address: 24, size: 4 bytes height + // address: 28, size: 4 bytes width + // address: 32, size: 4 bytes depth + // address: 36, size: 4 bytes number of surfaces + // address: 40, size: 4 bytes number of faces + // address: 44, size: 4 bytes number of mipmaps + // address: 48, size: 4 bytes meta data size + // --------------------------------------- + var uintArray = new Uint32Array(arrayBuffer.slice(0, 52)), + byteArray = new Uint8Array(arrayBuffer), + pvrHeader = null, + pixelFormat = (uintArray[3] << 32 | uintArray[2]), + compressionAlgorithm, + glExtensionFormat = 0; + + if (uintArray[0] === 0x03525650 && + [ // Validate WebGL Pixel Format + 0, 1, 2, 3, + 6, 7, 9, 11 + ].indexOf(pixelFormat) >= 0 + ) { + if (pixelFormat >= 0 && pixelFormat <= 3) { + compressionAlgorithm = 'PVRTC'; + } else if (pixelFormat >= 7 && pixelFormat <= 11) { + compressionAlgorithm = 'S3TC'; + } else if (pixelFormat === 6) { + compressionAlgorithm = 'ETC1'; + } + + switch (pixelFormat) { + case 0: + glExtensionFormat = 0x8C01; + break; + case 1: + glExtensionFormat = 0x8C03; + break; + case 2: + glExtensionFormat = 0x8C00; + break; + case 3: + glExtensionFormat = 0x8C02; + break; + case 6: + glExtensionFormat = 0x8D64; + break; + case 7: + glExtensionFormat = 0x83F1; + break; + case 9: + glExtensionFormat = 0x83F2; + break; + case 11: + glExtensionFormat = 0x83F3; + break; + default: + glExtensionFormat = -1; + } + + pvrHeader = { + complete: true, + fileFormat: 'PVR', + compressionAlgorithm: compressionAlgorithm, + flags: uintArray[1], + pixelFormat: pixelFormat, + colorSpace: uintArray[4], + channelType: uintArray[5], + height: uintArray[6], + width: uintArray[7], + depth: uintArray[8], + numberOfSurfaces: uintArray[9], + numberOfFaces: uintArray[10], + numberOfMipmaps: uintArray[11], + metaDataSize: uintArray[12], + textureData: byteArray.subarray(52 + uintArray[12], byteArray.byteLength), + glExtensionFormat: glExtensionFormat + }; + } + + return pvrHeader; + + }, + + /** + * Extract DDS header from loaded binary + * + * @method Phaser.LoaderParser.dds + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed DDS file including texture data. + */ + dds: function (arrayBuffer) { + + // Reference at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx + // DDS header structure + // --------------------------------------- + // address: 0, size: 4 bytes Identifier 'DDS ' + // address: 4, size: 4 bytes size + // address: 8, size: 4 bytes flags + // address: 12, size: 4 bytes height + // address: 16, size: 4 bytes width + // address: 20, size: 4 bytes pitch or linear size + // address: 24, size: 4 bytes depth + // address: 28, size: 4 bytes mipmap count + // address: 32, size: 44 bytes reserved space 1 + // address: 76, size: 4 pixel format size + // address: 80, size: 4 pixel format flag + // address: 84, size: 4 pixel format four CC + // address: 88, size: 4 pixel format bit count + // address: 92, size: 4 pixel format R bit mask + // address: 96, size: 4 pixel format G bit mask + // address: 100, size: 4 pixel format B bit mask + // address: 104, size: 4 pixel format A bit mask + // address: 108, size: 4 caps 1 + // address: 112, size: 4 caps 2 + // address: 116, size: 4 caps 3 + // address: 120, size: 4 caps 4 + // address: 124, size: 4 reserved 2 + // -- DXT10 extension + // address: 130, size: 4 DXGI Format + // address: 134, size: 4 resource dimension + // address: 138, size: 4 misc flag + // address: 142, size: 4 array size + // address: 146, size: 4 misc flag 2 + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ddsHeader = null; + + if (byteArray[0] === 0x44 && + byteArray[1] === 0x44 && + byteArray[2] === 0x53 && + byteArray[3] === 0x20) { + ddsHeader = { + complete: true, + fileFormat: 'DDS', + compressionAlgorithm: 'S3TC', + size: uintArray[1], + flags: uintArray[2], + height: uintArray[3], + width: uintArray[4], + pitch: uintArray[5], + depth: uintArray[6], + mipmapCount: uintArray[7], + formatSize: uintArray[19], + formatFlag: uintArray[19], + formatFourCC: [ + String.fromCharCode(byteArray[84]), + String.fromCharCode(byteArray[85]), + String.fromCharCode(byteArray[86]), + String.fromCharCode(byteArray[87]) + ].join(''), + formatBitCount: uintArray[21], + formatRBitMask: uintArray[22], + formatGBitMask: uintArray[23], + formatBBitMask: uintArray[24], + formatABitMask: uintArray[25], + caps1: uintArray[26], + caps2: uintArray[27], + caps3: uintArray[28], + caps4: uintArray[29], + reserved2: uintArray[30], + DXGIFormat: null, + resourceDimension: null, + miscFlag: null, + arraySize: null, + textureData: byteArray.subarray(uintArray[1] + 4, byteArray.byteLength) + }; + if (ddsHeader.formatFourCC === 'DX10') { + ddsHeader.DXGIFormat = uintArray[31]; + ddsHeader.resourceDimension = uintArray[32]; + ddsHeader.miscFlag = uintArray[33]; + ddsHeader.arraySize = uintArray[34]; + ddsHeader.miscFlag = uintArray[35]; + } + } + + return ddsHeader; + + }, + + /** + * Extract KTX header from loaded binary + * + * @method Phaser.LoaderParser.ktx + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed KTX file including texture data. + */ + ktx: function (arrayBuffer) { + + // Reference: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + // KTX header structure + // --------------------------------------- + // address: 0, size 12 bytes: Identifier '«KTX 11»\r\n\x1A\n' + // address: 12, size 4 bytes: endianness + // address: 16, size 4 bytes: GL type + // address: 20, size 4 bytes: GL type size + // address: 24, size 4 bytes: GL format + // address: 28, size 4 bytes: GL internal format + // address: 32, size 4 bytes: GL base internal format + // address: 36, size 4 bytes: pixel width + // address: 40, size 4 bytes: pixel height + // address: 44, size 4 bytes: pixel depth + // address: 48, size 4 bytes: number of array elements + // address: 52, size 4 bytes: number of faces + // address: 56, size 4 bytes: number of mipmap levels + // address: 60, size 4 bytes: bytes of key value data + // address: 64, size 4 bytes: key and value bytes size + // address: X, size 1 byte : key and value + // address: X, size 1 byte : value padding + // address: X, size 4 byte : image size + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ktxHeader = null, + imageSizeOffset = 16 + (uintArray[15] / 4) | 0, + imageSize = uintArray[imageSizeOffset], + glInternalFormat = uintArray[7], + compressionAlgorithm = 0; + + if (byteArray[0] === 0xAB && byteArray[1] === 0x4B && + byteArray[2] === 0x54 && byteArray[3] === 0x58 && + byteArray[4] === 0x20 && byteArray[5] === 0x31 && + byteArray[6] === 0x31 && byteArray[7] === 0xBB && + byteArray[8] === 0x0D && byteArray[9] === 0x0A && + byteArray[10] === 0x1A && byteArray[11] === 0x0A && + //Check if internal GL format is supported by WebGL + [ + // ETC1 + 0x8D64, + // PVRTC + 0x8C00, 0x8C01, 0x8C02, 0x8C03, + // DXTC | S3TC + 0x83F0, 0x83F1, 0x83F2, 0x83F3 + ].indexOf(glInternalFormat) >= 0) { + switch (glInternalFormat) { + case 0x8D64: + compressionAlgorithm = 'ETC1'; + break; + case 0x8C00: + case 0x8C01: + case 0x8C02: + case 0x8C03: + compressionAlgorithm = 'PVRTC'; + break; + case 0x83F0: + case 0x83F1: + case 0x83F2: + case 0x83F3: + compressionAlgorithm = 'S3TC'; + break; + } + + ktxHeader = { + complete: true, + fileFormat: 'KTX', + compressionAlgorithm: compressionAlgorithm, + endianness: uintArray[3], + glType: uintArray[4], + glTypeSize: uintArray[5], + glFormat: uintArray[6], + glInternalFormat: uintArray[7], + glBaseInternalFormat: uintArray[8], + width: uintArray[9], + height: uintArray[10], + pixelDepth: uintArray[11], + numberOfArrayElements: uintArray[12], + numberOfFaces: uintArray[13], + numberOfMipmapLevels: uintArray[14], + bytesOfKeyValueData: uintArray[15], + keyAndValueByteSize: uintArray[16], + imageSize: imageSize, + textureData: byteArray.subarray((imageSizeOffset + 1) * 4, imageSize + 100) + }; + } + + return ktxHeader; + + }, + + /** + * Extract PKM header from loaded binary + * + * @method Phaser.LoaderParser.pkm + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PKM file including texture data. + */ + pkm: function (arrayBuffer) { + + // PKM header structure + // --------------------------------------- + // address: 0, size 4 bytes: for 'PKM ' + // address: 4, size 2 bytes: for version + // address: 6, size 2 bytes: for type + // address: 8, size 2 bytes: for extended width + // address: 10, size 2 bytes: for extended height + // address: 12, size 2 bytes: for original width + // address: 14, size 2 bytes: for original height + // address: 16, texture data + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + pkmHeader = null; + + if (byteArray[0] === 0x50 && + byteArray[1] === 0x4B && + byteArray[2] === 0x4D && + byteArray[3] === 0x20) { + + pkmHeader = { + complete: true, + fileFormat: 'PKM', + compressionAlgorithm: 'ETC1', + format: ((byteArray[6] << 8 | byteArray[7])) & 0xFFFF, + width: ((byteArray[8] << 8 | byteArray[9])) & 0xFFFF, + height: ((byteArray[10] << 8 | byteArray[11])) & 0xFFFF, + originalWidth: ((byteArray[12] << 8 | byteArray[13])) & 0xFFFF, + originalHeight: ((byteArray[14] << 8 | byteArray[15])) & 0xFFFF, + textureData: byteArray.subarray(16, byteArray.length) + }; + } + + return pkmHeader; + + } + +}; + +/** + * @author Jeremy Dowell + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * Audio Sprites are a combination of audio files and a JSON configuration. + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * @class Phaser.AudioSprite + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + * @param {string} key - Asset key for the sound. + */ +Phaser.AudioSprite = function (game, key) { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * Asset key for the Audio Sprite. + * @property {string} key + */ + this.key = key; + + /** + * JSON audio atlas object. + * @property {object} config + */ + this.config = this.game.cache.getJSON(key + '-audioatlas'); + + /** + * If a sound is set to auto play, this holds the marker key of it. + * @property {string} autoplayKey + */ + this.autoplayKey = null; + + /** + * Is a sound set to autoplay or not? + * @property {boolean} autoplay + * @default + */ + this.autoplay = false; + + /** + * An object containing the Phaser.Sound objects for the Audio Sprite. + * @property {object} sounds + */ + this.sounds = {}; + + for (var k in this.config.spritemap) + { + var marker = this.config.spritemap[k]; + var sound = this.game.add.sound(this.key); + + sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop); + + this.sounds[k] = sound; + } + + if (this.config.autoplay) + { + this.autoplayKey = this.config.autoplay; + this.play(this.autoplayKey); + this.autoplay = this.sounds[this.autoplayKey]; + } + +}; + +Phaser.AudioSprite.prototype = { + + /** + * Play a sound with the given name. + * + * @method Phaser.AudioSprite#play + * @param {string} [marker] - The name of sound to play + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, volume) { + + if (volume === undefined) { volume = 1; } + + return this.sounds[marker].play(marker, null, volume); + + }, + + /** + * Stop a sound with the given name. + * + * @method Phaser.AudioSprite#stop + * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite. + */ + stop: function (marker) { + + if (!marker) + { + for (var key in this.sounds) + { + this.sounds[key].stop(); + } + } + else + { + this.sounds[marker].stop(); + } + + }, + + /** + * Get a sound with the given name. + * + * @method Phaser.AudioSprite#get + * @param {string} marker - The name of sound to get. + * @return {Phaser.Sound} The sound instance. + */ + get: function(marker) { + + return this.sounds[marker]; + + } + +}; + +Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound class constructor. +* +* @class Phaser.Sound +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {string} key - Asset key for the sound. +* @param {number} [volume=1] - Default value for the volume, between 0 and 1. +* @param {boolean} [loop=false] - Whether or not the sound will loop. +*/ +Phaser.Sound = function (game, key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = game.sound.connectToMaster; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * @property {string} name - Name of the sound. + */ + this.name = key; + + /** + * @property {string} key - Asset key for the sound. + */ + this.key = key; + + /** + * @property {boolean} loop - Whether or not the sound or current sound marker will loop. + */ + this.loop = loop; + + /** + * @property {object} markers - The sound markers. + */ + this.markers = {}; + + /** + * @property {AudioContext} context - Reference to the AudioContext instance. + */ + this.context = null; + + /** + * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically. + */ + this.autoplay = false; + + /** + * @property {number} totalDuration - The total duration of the sound in seconds. + */ + this.totalDuration = 0; + + /** + * @property {number} startTime - The time the sound starts at in ms (typically 0 unless starting from a marker). + * @default + */ + this.startTime = 0; + + /** + * @property {number} currentTime - The current time of sound playback in ms. + */ + this.currentTime = 0; + + /** + * @property {number} duration - The duration of the current sound marker in seconds. + */ + this.duration = 0; + + /** + * @property {number} durationMS - The duration of the current sound marker in ms. + */ + this.durationMS = 0; + + /** + * @property {number} position - The position of the current sound marker in ms. + */ + this.position = 0; + + /** + * @property {number} stopTime - The time the sound stopped in ms. + */ + this.stopTime = 0; + + /** + * @property {boolean} paused - true if the sound is paused, otherwise false. + * @default + */ + this.paused = false; + + /** + * @property {number} pausedPosition - The position the sound had reached when it was paused in ms. + */ + this.pausedPosition = 0; + + /** + * @property {number} pausedTime - The game time (ms) at which the sound was paused. + */ + this.pausedTime = 0; + + /** + * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false. + * @default + */ + this.isPlaying = false; + + /** + * @property {string} currentMarker - The string ID of the currently playing marker, if any. + * @default + */ + this.currentMarker = ''; + + /** + * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. + */ + this.fadeTween = null; + + /** + * @property {boolean} pendingPlayback - true if the sound file is pending playback + * @readonly + */ + this.pendingPlayback = false; + + /** + * @property {boolean} override - if true when you play this sound it will always start from the beginning. + * @default + */ + this.override = false; + + /** + * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. + * @default + */ + this.allowMultiple = false; + + /** + * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio. + * @readonly + */ + this.usingWebAudio = this.game.sound.usingWebAudio; + + /** + * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag. + */ + this.usingAudioTag = this.game.sound.usingAudioTag; + + /** + * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. + */ + this.externalNode = null; + + /** + * @property {object} masterGainNode - The master gain node in a Web Audio system. + */ + this.masterGainNode = null; + + /** + * @property {object} gainNode - The gain node in a Web Audio system. + */ + this.gainNode = null; + + /** + * @property {object} _sound - Internal var. + * @private + */ + this._sound = null; + + /** + * @property {object} _globalVolume - Internal var for keeping track of global volume when using AudioTag + * @private + */ + this._globalVolume = 1; + + /** + * @property {boolean} _markedToDelete - When audio stops, disconnect Web Audio nodes. + * @private + */ + this._markedToDelete = false; + + /** + * @property {boolean} _removeFromSoundManager - When audio stops, remove it from the Sound Manager and destroy it. + * @private + */ + this._removeFromSoundManager = false; + + + + if (this.usingWebAudio) + { + this.context = this.game.sound.context; + this.masterGainNode = this.game.sound.masterGain; + + if (this.context.createGain === undefined) + { + this.gainNode = this.context.createGainNode(); + } + else + { + this.gainNode = this.context.createGain(); + } + + this.gainNode.gain.value = volume; + + if (connect) + { + this.gainNode.connect(this.masterGainNode); + } + } + else if (this.usingAudioTag) + { + if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key)) + { + this._sound = this.game.cache.getSoundData(key); + this.totalDuration = 0; + + if (this._sound.duration) + { + this.totalDuration = this._sound.duration; + } + } + else + { + this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this); + } + } + + /** + * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files). It passes one argument, this sound. + */ + this.onDecoded = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played or a looping marker is restarted. It passes one argument, this sound. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. It passes one argument, this sound. + */ + this.onPause = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. It passes one argument, this sound. + */ + this.onResume = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. It passes one argument, this sound. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback or when a non-looping marker completes. It passes two arguments: this sound and any {@link #currentMarker marker} that was playing. + */ + this.onStop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted. It passes one argument, this sound. + */ + this.onMute = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. It passes two arguments: the {@link #currentMarker} and this sound. + */ + this.onMarkerComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out. It passes two arguments: this sound and its current {@link #volume}. + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + */ + this._volume = volume; + + /** + * @property {any} _buffer - Decoded data buffer / Audio tag. + * @private + */ + this._buffer = null; + + /** + * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. + * @private + */ + this._muted = false; + + /** + * @property {number} _tempMarker - Internal marker var. + * @private + */ + this._tempMarker = 0; + + /** + * @property {number} _tempPosition - Internal marker var. + * @private + */ + this._tempPosition = 0; + + /** + * @property {number} _tempVolume - Internal marker var. + * @private + */ + this._tempVolume = 0; + + /** + * @property {number} _tempPause - Internal marker var. + * @private + */ + this._tempPause = 0; + + /** + * @property {number} _muteVolume - Internal cache var. + * @private + */ + this._muteVolume = 0; + + /** + * @property {boolean} _tempLoop - Internal cache var. + * @private + */ + this._tempLoop = 0; + + /** + * @property {boolean} _paused - Was this sound paused via code or a game event? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched? + * @private + */ + this._onDecodedEventDispatched = false; + +}; + +Phaser.Sound.prototype = { + + /** + * Called automatically when this sound is unlocked. + * @method Phaser.Sound#soundHasUnlocked + * @param {string} key - The Phaser.Cache key of the sound file to check for decoding. + * @protected + */ + soundHasUnlocked: function (key) { + + if (key === this.key) + { + this._sound = this.game.cache.getSoundData(this.key); + this.totalDuration = this._sound.duration; + } + + }, + + /** + * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound#addMarker + * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. + * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). + * @param {boolean} [loop=false] - Sets if the sound will loop or not. + */ + addMarker: function (name, start, duration, volume, loop) { + + if (duration === undefined || duration === null) { duration = 1; } + if (volume === undefined || volume === null) { volume = 1; } + if (loop === undefined) { loop = false; } + + this.markers[name] = { + name: name, + start: start, + stop: start + duration, + volume: volume, + duration: duration, + durationMS: duration * 1000, + loop: loop + }; + + }, + + /** + * Removes a marker from the sound. + * @method Phaser.Sound#removeMarker + * @param {string} name - The key of the marker to remove. + */ + removeMarker: function (name) { + + delete this.markers[name]; + + }, + + /** + * Called automatically by the AudioContext when the sound stops playing. + * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. + * + * @method Phaser.Sound#onEndedHandler + * @protected + */ + onEndedHandler: function () { + + this._sound.onended = null; + this.isPlaying = false; + this.currentTime = this.durationMS; + this.stop(); + + if (this._markedToDelete) + { + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + if (this._removeFromSoundManager) + { + this.game.sound.remove(this); + } + else + { + 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(); + } + } + }, + + /** + * Called automatically by Phaser.SoundManager. + * @method Phaser.Sound#update + * @protected + */ + update: function () { + + if (!this.game.cache.checkSoundKey(this.key)) + { + this.destroy(); + return; + } + + if (this.isDecoded && !this._onDecodedEventDispatched) + { + this.onDecoded.dispatch(this); + this._onDecodedEventDispatched = true; + } + + if (this.pendingPlayback && this.game.cache.isSoundReady(this.key)) + { + this.pendingPlayback = false; + this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop); + } + + if (this.isPlaying) + { + this.currentTime = this.game.time.time - this.startTime; + + if (this.currentTime >= this.durationMS) + { + if (this.usingWebAudio) + { + if (this.loop) + { + // won't work with markers, needs to reset the position + this.onLoop.dispatch(this); + + // Gets reset by the play function + this.isPlaying = false; + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + this.isPlaying = true; // play not called again in this case + } + else + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + this.play(this.currentMarker, 0, this.volume, true, true); + } + } + else + { + // Stop if we're using an audio marker, otherwise we let onended handle it + if (this.currentMarker !== '') + { + this.stop(); + } + } + } + else + { + if (this.loop) + { + this.onLoop.dispatch(this); + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + } + + // Gets reset by the play function + this.isPlaying = false; + + this.play(this.currentMarker, 0, this.volume, true, true); + } + else + { + this.stop(); + } + } + } + } + }, + + /** + * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters. + * + * @method Phaser.Sound#loopFull + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + loopFull: function (volume) { + + return this.play(null, 0, volume, true); + + }, + + /** + * Play this sound, or a marked section of it. + * + * @method Phaser.Sound#play + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. + * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, position, volume, loop, forceRestart) { + + if (marker === undefined || marker === false || marker === null) { marker = ''; } + if (forceRestart === undefined) { forceRestart = true; } + + if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override) + { + // Use Restart instead + return this; + } + + if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart)) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) { + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + + this.isPlaying = false; + } + + if (marker === '' && Object.keys(this.markers).length > 0) + { + // If they didn't specify a marker but this is an audio sprite, + // we should never play the entire thing + return this; + } + + if (marker !== '') + { + if (this.markers[marker]) + { + this.currentMarker = marker; + + // Playing a marker? Then we default to the marker values + 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 (volume === undefined) { volume = this._volume; } + if (loop === undefined) { loop = this.loop; } + + this.position = Math.max(0, 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) + { + // Does the sound need decoding? + if (this.game.cache.isSoundDecoded(this.key)) + { + this._sound = this.context.createBufferSource(); + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + this._buffer = this.game.cache.getSoundData(this.key); + this._sound.buffer = this._buffer; + + if (this.loop && marker === '') + { + this._sound.loop = true; + } + + if (!this.loop && marker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + this.totalDuration = this._sound.buffer.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = Math.ceil(this.totalDuration * 1000); + } + + // Useful to cache this somewhere perhaps? + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, this.position, this.duration); + } + else + { + if (this.loop && marker === '') + { + this._sound.start(0, 0); + } + else + { + this._sound.start(0, this.position, this.duration); + } + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + 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 doesn't become available until you call play(), wonderful ... + this.totalDuration = this._sound.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = this.totalDuration * 1000; + } + + this._sound.currentTime = this.position; + this._sound.muted = this._muted; + + if (this._muted || this.game.sound.mute) + { + this._sound.volume = 0; + } + else + { + this._sound.volume = this._volume; + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + this.currentTime = 0; + this.stopTime = this.startTime + this.durationMS; + + this.onPlay.dispatch(this); + } + else + { + this.pendingPlayback = true; + } + } + } + + return this; + + }, + + /** + * Restart the sound, or a marked section of it. + * + * @method Phaser.Sound#restart + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. + * @param {boolean} [loop=false] - Loop when it finished playing? + */ + restart: function (marker, position, volume, loop) { + + marker = marker || ''; + position = position || 0; + volume = volume || 1; + if (loop === undefined) { loop = false; } + + this.play(marker, position, volume, loop, true); + + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound#pause + */ + pause: function () { + + if (this.isPlaying && this._sound) + { + this.paused = true; + this.pausedPosition = this.currentTime; + this.pausedTime = this.game.time.time; + this._tempPause = this._sound.currentTime; + this.onPause.dispatch(this); + this.stop(); + } + + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound#resume + */ + resume: function () { + + if (this.paused && this._sound) + { + if (this.usingWebAudio) + { + var p = Math.max(0, this.position + (this.pausedPosition / 1000)); + + this._sound = this.context.createBufferSource(); + this._sound.buffer = this._buffer; + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + if (this.loop) + { + this._sound.loop = true; + } + + if (!this.loop && this.currentMarker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + var duration = this.duration - (this.pausedPosition / 1000); + + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, p, duration); + //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it + } + else + { + if (this.loop && this.game.device.chrome) + { + // Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099 + if (this.game.device.chromeVersion === 42) + { + this._sound.start(0); + } + else + { + this._sound.start(0, p); + } + } + else + { + this._sound.start(0, p, duration); + } + } + } + else + { + this._sound.currentTime = this._tempPause; + this._sound.play(); + } + + this.isPlaying = true; + this.paused = false; + this.startTime += (this.game.time.time - this.pausedTime); + this.onResume.dispatch(this); + } + + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound#stop + */ + stop: function () { + + if (this.isPlaying && this._sound) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) + { + // Thanks Android 4.4 + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + } + + this.pendingPlayback = false; + this.isPlaying = false; + + if (!this.paused) + { + var prevMarker = this.currentMarker; + + if (this.currentMarker !== '') + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + } + + this.currentMarker = ''; + + if (this.fadeTween !== null) + { + this.fadeTween.stop(); + } + + this.onStop.dispatch(this, prevMarker); + } + + }, + + /** + * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. + * Then increases the volume from 0 to 1 over the duration specified. + * + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (1) as the second parameter. + * + * @method Phaser.Sound#fadeIn + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in. + * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. + * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. + */ + fadeIn: function (duration, loop, marker) { + + if (loop === undefined) { loop = false; } + if (marker === undefined) { marker = this.currentMarker; } + + if (this.paused) + { + return; + } + + this.play(marker, 0, 0, loop); + + this.fadeTo(duration, 1); + + }, + + /** + * Decreases the volume of this Sound from its current value to 0 over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (0) as the second parameter. + * + * @method Phaser.Sound#fadeOut + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out. + */ + fadeOut: function (duration) { + + this.fadeTo(duration, 0); + + }, + + /** + * Fades the volume of this Sound from its current value to the given volume over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (volume) as the second parameter. + * + * @method Phaser.Sound#fadeTo + * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out. + * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1. + */ + fadeTo: function (duration, volume) { + + if (!this.isPlaying || this.paused || volume === this.volume) + { + return; + } + + if (duration === undefined) { duration = 1000; } + + if (volume === undefined) + { + console.warn("Phaser.Sound.fadeTo: No Volume Specified."); + return; + } + + this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true); + + this.fadeTween.onComplete.add(this.fadeComplete, this); + + }, + + /** + * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo. + * + * @method Phaser.Sound#fadeComplete + * @private + */ + fadeComplete: function () { + + this.onFadeComplete.dispatch(this, this.volume); + + if (this.volume === 0) + { + this.stop(); + } + + }, + + /** + * Called automatically by SoundManager.volume. + * + * Sets the volume of AudioTag Sounds as a percentage of the Global Volume. + * + * You should not normally call this directly. + * + * @method Phaser.Sound#updateGlobalVolume + * @protected + * @param {float} globalVolume - The global SoundManager volume. + */ + updateGlobalVolume: function (globalVolume) { + + // this._volume is the % of the global volume this sound should be played at + + if (this.usingAudioTag && this._sound) + { + this._globalVolume = globalVolume; + this._sound.volume = this._globalVolume * this._volume; + } + + }, + + /** + * Destroys this sound and all associated events and removes it from the SoundManager. + * + * @method Phaser.Sound#destroy + * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager. + */ + destroy: function (remove) { + + if (remove === undefined) { remove = true; } + + this._markedToDelete = true; + this._removeFromSoundManager = remove; + this.stop(); + + if (remove) + { + this.game.sound.remove(this); + } + else + { + 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; + +/** +* @name Phaser.Sound#isDecoding +* @property {boolean} isDecoding - Returns true if the sound file is still decoding. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoding", { + + get: function () { + return this.game.cache.getSound(this.key).isDecoding; + } + +}); + +/** +* @name Phaser.Sound#isDecoded +* @property {boolean} isDecoded - Returns true if the sound file has decoded. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoded", { + + get: function () { + return this.game.cache.isSoundDecoded(this.key); + } + +}); + +/** +* @name Phaser.Sound#mute +* @property {boolean} mute - Gets or sets the muted state of this sound. +*/ +Object.defineProperty(Phaser.Sound.prototype, "mute", { + + get: function () { + + return (this._muted || this.game.sound.mute); + + }, + + set: function (value) { + + value = value || false; + + if (value === this._muted) + { + return; + } + + if (value) + { + this._muted = true; + this._muteVolume = this._tempVolume; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = 0; + } + else if (this.usingAudioTag && this._sound) + { + 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); + + } + +}); + +/** +* @name Phaser.Sound#volume +* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Sound.prototype, "volume", { + + get: function () { + return this._volume; + }, + + set: function (value) { + + // Causes an Index size error if you don't clamp the value + if (this.usingAudioTag) + { + value = this.game.math.clamp(value, 0, 1); + } + + if (this._muted) + { + this._muteVolume = value; + return; + } + + this._tempVolume = value; + this._volume = value; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = value; + } + else if (this.usingAudioTag && this._sound) + { + this._sound.volume = this._globalVolume * value; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. +* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. +* The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. +* There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ +* +* If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out +* of AudioContext nodes. If this is the case create a global var called {@link PhaserGlobal} on the window object before creating the game. The active +* AudioContext will then be saved to `window.PhaserGlobal.audioContext` when the Phaser game is destroyed, and re-used when it starts again. +* +* Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. +* When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. +* The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will +* be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. +* +* @class Phaser.SoundManager +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.SoundManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) + */ + this.onSoundDecode = new Phaser.Signal(); + + /** + * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. + * @property {Phaser.Signal} onVolumeChange + */ + this.onVolumeChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. + * @property {Phaser.Signal} onMute + */ + this.onMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. + * @property {Phaser.Signal} onUnMute + */ + this.onUnMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is touch-unlocked. + * If the device doesn't {@link Phaser.Device.needsTouchUnlock need touch-unlocking}, the signal won't be dispatched. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * @property {AudioContext} context - The AudioContext being used for playback. + * @default + */ + this.context = null; + + /** + * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio. + * @readonly + */ + this.usingWebAudio = false; + + /** + * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio. + * @readonly + */ + this.usingAudioTag = false; + + /** + * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. + * @default + */ + this.noAudio = false; + + /** + * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. + * @default + */ + this.connectToMaster = true; + + /** + * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. + * @default + */ + this.touchLocked = false; + + /** + * @property {number} channels - The number of audio channels to use in playback. + * @default + */ + this.channels = 32; + + /** + * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), + * or set to false to keep audio playing, regardless of the game pause state. You may need to + * do this should you wish to control audio muting via external DOM buttons or similar. + * @property {boolean} muteOnPause + * @default + */ + this.muteOnPause = true; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {AudioContext} _unlockSource - Internal unlock tracking var. + * @private + * @default + */ + this._unlockSource = null; + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + * @default + */ + this._volume = 1; + + + /** + * @property {array} _sounds - An array containing all the sounds + * @private + */ + this._sounds = []; + + /** + * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status. + * @private + */ + this._watchList = new Phaser.ArraySet(); + + /** + * @property {boolean} _watching - Is the SoundManager monitoring the watchList? + * @private + */ + this._watching = false; + + /** + * @property {function} _watchCallback - The callback to invoke once the watchlist is clear. + * @private + */ + this._watchCallback = null; + + /** + * @property {object} _watchContext - The context in which to call the watchlist callback. + * @private + */ + this._watchContext = null; + +}; + +Phaser.SoundManager.prototype = { + + /** + * Initialises the sound manager. + * @method Phaser.SoundManager#boot + * @protected + */ + boot: function () { + + var device = this.game.device; + var PhaserGlobal = window.PhaserGlobal; + + if (device.iOS && device.webAudio === false) + { + this.channels = 1; + } + + // PhaserGlobal overrides + if (PhaserGlobal) + { + // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class) + if (PhaserGlobal.disableAudio === true) + { + this.noAudio = true; + this.touchLocked = false; + return; + } + + // Check if the Web Audio API is disabled (for testing Audio Tag playback during development) + if (PhaserGlobal.disableWebAudio === true) + { + this.usingAudioTag = true; + this.touchLocked = false; + return; + } + } + + if (PhaserGlobal && PhaserGlobal.audioContext) + { + this.context = PhaserGlobal.audioContext; + } + else + { + if (!!window['AudioContext']) + { + try { + this.context = new window['AudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + else if (!!window['webkitAudioContext']) + { + try { + this.context = new window['webkitAudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + } + + if (this.context === null) + { + // No Web Audio support - how about legacy Audio? + if (window['Audio'] === undefined) + { + this.noAudio = true; + return; + } + else + { + this.usingAudioTag = true; + } + } + else + { + this.usingWebAudio = true; + + if (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); + } + + if (!this.noAudio) + { + // On mobile we need a native touch event before we can play anything, so capture it here + if (device.needsTouchUnlock()) + { + this.setTouchLock(); + } + } + + if (this.usingWebAudio && device.chrome && device.chromeVersion <= 65) + { + console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. '); + } + + }, + + /** + * Sets the Input Manager touch callback to be SoundManager.unlock. + * Required for iOS audio device unlocking. Mostly just used internally. + * + * @method Phaser.SoundManager#setTouchLock + */ + setTouchLock: function () { + + if (this.noAudio || (window.PhaserGlobal && window.PhaserGlobal.disableAudio === true)) + { + return; + } + + this.game.input.addTouchLockCallback(this.unlock, this, true); + + this.touchLocked = true; + + }, + + /** + * Turns off {@link #touchLocked} and dispatches {@link #onTouchUnlock}. + * + * @method Phaser.SoundManager#setTouchUnlock + * @private + */ + setTouchUnlock: function () { + + this.touchLocked = false; + this._unlockSource = null; + this.onTouchUnlock.dispatch(); + + }, + + /** + * Enables the audio, usually after the first touch. + * + * @method Phaser.SoundManager#unlock + * @return {boolean} True if the callback should be removed, otherwise false. + */ + unlock: function () { + + if (this.noAudio || !this.touchLocked || this._unlockSource !== null) + { + return true; + } + + // Global override (mostly for Audio Tag testing) + if (this.usingAudioTag) + { + this.setTouchUnlock(); + } + else if (this.usingWebAudio) + { + // Create empty buffer and play it + // The SoundManager.update loop captures the state of it and then resets touchLocked to false + + var buffer = this.context.createBuffer(1, 1, 22050); + this._unlockSource = this.context.createBufferSource(); + this._unlockSource.buffer = buffer; + this._unlockSource.connect(this.context.destination); + + if (this._unlockSource.start === undefined) + { + this._unlockSource.noteOn(0); + } + else + { + this._unlockSource.start(0); + } + + //This fixes locked audio in Chrome > 55 cross origin iframes + if (this._unlockSource.context.state === 'suspended') { + this._unlockSource.context.resume(); + } + } + + // We can remove the event because we've done what we needed (started the unlock sound playing) + return true; + + }, + + /** + * Stops all the sounds in the game. + * + * @method Phaser.SoundManager#stopAll + */ + stopAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].stop(); + } + } + + }, + + /** + * Pauses all the sounds in the game. + * + * @method Phaser.SoundManager#pauseAll + */ + pauseAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].pause(); + } + } + + }, + + /** + * Resumes every sound in the game. + * + * @method Phaser.SoundManager#resumeAll + */ + resumeAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].resume(); + } + } + + }, + + /** + * Decode a sound by its asset key. + * + * @method Phaser.SoundManager#decode + * @param {string} key - Assets key of the sound to be decoded. + * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. + */ + decode: function (key, sound) { + + sound = sound || null; + + var soundData = this.game.cache.getSoundData(key); + + if (soundData) + { + if (this.game.cache.isSoundDecoded(key) === false) + { + this.game.cache.updateSound(key, 'isDecoding', true); + + var _this = this; + + try { + this.context.decodeAudioData(soundData, function (buffer) { + + if (buffer) + { + _this.game.cache.decodedSound(key, buffer); + _this.onSoundDecode.dispatch(key, sound); + } + }); + } + catch (e) {} + } + } + + }, + + /** + * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback. + * Once all of the Sound files have finished decoding the callback will be invoked. + * The amount of time spent decoding depends on the codec used and file size. + * If all of the files given have already decoded the callback is triggered immediately. + * + * @method Phaser.SoundManager#setDecodedCallback + * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache. + * @param {Function} callback - The callback which will be invoked once all files have finished decoding. + * @param {Object} callbackContext - The context in which the callback will run. + */ + setDecodedCallback: function (files, callback, callbackContext) { + + if (typeof files === 'string') + { + files = [ files ]; + } + + this._watchList.reset(); + + for (var i = 0; i < files.length; i++) + { + if (files[i] instanceof Phaser.Sound) + { + if (!this.game.cache.isSoundDecoded(files[i].key)) + { + this._watchList.add(files[i].key); + } + } + else if (!this.game.cache.isSoundDecoded(files[i])) + { + this._watchList.add(files[i]); + } + } + + // All decoded already? + if (this._watchList.total === 0) + { + this._watching = false; + callback.call(callbackContext); + } + else + { + this._watching = true; + this._watchCallback = callback; + this._watchContext = callbackContext; + } + + }, + + /** + * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. + * + * @method Phaser.SoundManager#update + * @protected + */ + update: function () { + + if (this.noAudio) + { + return; + } + + if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE)) + { + this.setTouchUnlock(); + } + + for (var i = 0; i < this._sounds.length; i++) + { + this._sounds[i].update(); + } + + if (this._watching) + { + var key = this._watchList.first; + + while (key) + { + if (this.game.cache.isSoundDecoded(key)) + { + this._watchList.remove(key); + } + + key = this._watchList.next; + } + + if (this._watchList.total === 0) + { + this._watching = false; + this._watchCallback.call(this._watchContext); + } + } + + }, + + /** + * Adds a new Sound into the SoundManager. + * + * @method Phaser.SoundManager#add + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The new sound instance. + */ + add: function (key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = this.connectToMaster; } + + var sound = new Phaser.Sound(this.game, key, volume, loop, connect); + + this._sounds.push(sound); + + return sound; + + }, + + /** + * Adds a new AudioSprite into the SoundManager. + * + * @method Phaser.SoundManager#addSprite + * @param {string} key - Asset key for the sound. + * @return {Phaser.AudioSprite} The new AudioSprite instance. + */ + addSprite: function(key) { + + var audioSprite = new Phaser.AudioSprite(this.game, key); + + return audioSprite; + + }, + + /** + * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. + * + * @method Phaser.SoundManager#remove + * @param {Phaser.Sound} sound - The sound object to remove. + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ + remove: function (sound) { + + var i = this._sounds.length; + + while (i--) + { + if (this._sounds[i] === sound) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Removes all Sounds from the SoundManager. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeAll + */ + removeAll: function () { + + this.stopAll(); + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].destroy(); + } + } + + this._sounds.length = 0; + + }, + + /** + * Removes all Sounds from the SoundManager that have an asset key matching the given value. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeByKey + * @param {string} key - The key to match when removing sound objects. + * @return {number} The number of matching sound objects that were removed. + */ + removeByKey: function (key) { + + var i = this._sounds.length; + var removed = 0; + + while (i--) + { + if (this._sounds[i].key === key) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + removed++; + } + } + + return removed; + + }, + + /** + * Adds a new Sound into the SoundManager and starts it playing. + * + * @method Phaser.SoundManager#play + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @return {Phaser.Sound} The new sound instance. + */ + play: function (key, volume, loop) { + + if (this.noAudio) + { + return; + } + + var sound = this.add(key, volume, loop); + + sound.play(); + + return sound; + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + if (this.usingWebAudio) + { + this._muteVolume = this.masterGain.gain.value; + this.masterGain.gain.value = 0; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = true; + } + } + + this.onMute.dispatch(); + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = this._muteVolume; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = false; + } + } + + this.onUnMute.dispatch(); + + }, + + /** + * Stops all the sounds in the game, then destroys them and finally clears up any callbacks. + * + * @method Phaser.SoundManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.onSoundDecode.dispose(); + + if (this.context) + { + if (window.PhaserGlobal) + { + // Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing + window.PhaserGlobal.audioContext = this.context; + } + else + { + if (this.context.close) + { + this.context.close(); + } + } + } + + } + +}; + +Phaser.SoundManager.prototype.constructor = Phaser.SoundManager; + +/** +* @name Phaser.SoundManager#mute +* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || false; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* @name Phaser.SoundManager#volume +* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "volume", { + + get: function () { + + return this._volume; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this._volume !== value) + { + this._volume = value; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = value; + } + else + { + // Loop through the sound cache and change the volume of all html audio tags + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].updateGlobalVolume(value); + } + } + } + + this.onVolumeChange.dispatch(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* The ScaleManager object handles the the scaling, resizing, and alignment of the +* Game size and the game Display canvas. +* +* The Game size is the logical size of the game; the Display canvas has size as an HTML element. +* +* The calculations of these are heavily influenced by the bounding Parent size which is the computed +* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the +* canvas's Parent element play an important role_ in the operation of the ScaleManager. +* +* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size. +* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}). +* +* #### Parent and Display canvas containment guidelines: +* +* - Style the Parent element (of the game canvas) to control the Parent size and +* thus the Display canvas's size and layout. +* +* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior. +* +* - The Parent element should _not_ apply a padding as this is not accounted for. +* If a padding is required apply it to the Parent's parent or apply a margin to the Parent. +* If you need to add a border, margin or any other CSS around your game container, then use a parent element and +* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container. +* +* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as +* they may be updated by the ScaleManager. +* +* #### Example Uses +* +* - ##### Fixed game size; scale canvas proportionally to fill its container +* +* Use `scaleMode` SHOW_ALL. +* +* - ##### Fixed game size; stretch canvas to fill its container (uncommon) +* +* Use `scaleMode` EXACT_FIT. +* +* - ##### Fixed game size; scale canvas proportionally by some other criteria +* +* Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary. +* +* - ##### Fluid game/canvas size +* +* Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary. +* +* - ##### Preferred orientation +* +* Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals. +* +* @description +* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game} +* +* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. +* +* @class +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number|string} width - The width of the game. See above. +* @param {number|string} height - The height of the game. See above. +*/ +Phaser.ScaleManager = function (game, width, height) { + + /** + * A reference to the currently running game. + * @property {Phaser.Game} game + * @protected + * @readonly + */ + this.game = game; + + /** + * Provides access to some cross-device DOM functions. + * @property {Phaser.DOM} dom + * @protected + * @readonly + */ + this.dom = Phaser.DOM; + + /** + * _EXPERIMENTAL:_ A responsive grid on which you can align game objects. + * @property {Phaser.FlexGrid} grid + * @public + */ + this.grid = null; + + /** + * Target width (in pixels) of the Display canvas. + * @property {number} width + * @readonly + */ + this.width = 0; + + /** + * Target height (in pixels) of the Display canvas. + * @property {number} height + * @readonly + */ + this.height = 0; + + /** + * Minimum width the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minWidth + * @readonly + * @protected + */ + this.minWidth = null; + + /** + * Maximum width the canvas should be scaled to (in pixels). + * If null it will scale to whatever width the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxWidth + * @readonly + * @protected + */ + this.maxWidth = null; + + /** + * Minimum height the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minHeight + * @readonly + * @protected + */ + this.minHeight = null; + + /** + * Maximum height the canvas should be scaled to (in pixels). + * If null it will scale to whatever height the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxHeight + * @readonly + * @protected + */ + this.maxHeight = null; + + /** + * The offset coordinates of the Display canvas from the top-left of the browser window. + * The is used internally by Phaser.Pointer (for Input) and possibly other types. + * @property {Phaser.Point} offset + * @readonly + * @protected + */ + this.offset = new Phaser.Point(); + + /** + * If true, the game should only run in a landscape orientation. + * Change with {@link #forceOrientation}. + * @property {boolean} forceLandscape + * @readonly + * @default + * @protected + */ + this.forceLandscape = false; + + /** + * If true, the game should only run in a portrait + * Change with {@link #forceOrientation}. + * @property {boolean} forcePortrait + * @readonly + * @default + * @protected + */ + this.forcePortrait = false; + + /** + * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation. + * + * This value is not updated immediately. + * + * @property {boolean} incorrectOrientation + * @readonly + * @protected + */ + this.incorrectOrientation = false; + + /** + * See {@link #pageAlignHorizontally}. + * @property {boolean} _pageAlignHorizontally + * @private + */ + this._pageAlignHorizontally = false; + + /** + * See {@link #pageAlignVertically}. + * @property {boolean} _pageAlignVertically + * @private + */ + this._pageAlignVertically = false; + + /** + * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes. + * + * The signal is supplied with the following arguments: + * - `scale` - the ScaleManager object + * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}. + * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. + * + * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. + * Thus the following tests can be done: + * + * // The orientation itself changed: + * scale.screenOrientation !== prevOrientation + * // The orientation just became incorrect: + * scale.incorrectOrientation && !wasIncorrect + * + * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation + * correctness changes even if the orientation itself does not change. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onOrientationChange + * @public + */ + this.onOrientationChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} enterIncorrectOrientation + * @public + */ + this.enterIncorrectOrientation = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} leaveIncorrectOrientation + * @public + */ + this.leaveIncorrectOrientation = new Phaser.Signal(); + + /** + * This boolean provides you with a way to determine if the browser is in Full Screen + * mode (via the Full Screen API), and Phaser was the one responsible for activating it. + * + * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the + * one that made the browser go full-screen, so this flag lets you determine that. + * + * @property {boolean} hasPhaserSetFullScreen + * @default + */ + this.hasPhaserSetFullScreen = false; + + /** + * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. + * The target element must have the correct CSS styling and contain the Display canvas. + * + * The elements style will be modified (ie. the width and height might be set to 100%) + * but it will not be added to, removed from, or repositioned within the DOM. + * An attempt is made to restore relevant style changes when fullscreen mode is left. + * + * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. + * + * @property {?DOMElement} fullScreenTarget + * @default + */ + this.fullScreenTarget = null; + + /** + * The fullscreen target, as created by {@link #createFullScreenTarget}. + * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends. + * @property {?DOMElement} _createdFullScreenTarget + * @private + */ + this._createdFullScreenTarget = null; + + /** + * This signal is dispatched when fullscreen mode is ready to be initialized but + * before the fullscreen request. + * + * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. + * + * The `targetElement` is the {@link #fullScreenTarget} element, + * if such is assigned, or a new element created by {@link #createFullScreenTarget}. + * + * Custom CSS styling or resets can be applied to `targetElement` as required. + * + * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}: + * - After initialization the Display canvas is moved onto the `targetElement` for + * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. + * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. + * + * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}. + * + * @property {Phaser.Signal} onFullScreenInit + * @public + */ + this.onFullScreenInit = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine + * if currently running in Fullscreen mode. + * + * @property {Phaser.Signal} onFullScreenChange + * @public + */ + this.onFullScreenChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser fails to enter fullscreen mode; + * or if the device does not support fullscreen mode and `startFullScreen` is invoked. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). + * + * @property {Phaser.Signal} onFullScreenError + * @public + */ + this.onFullScreenError = new Phaser.Signal(); + + /** + * The _last known_ orientation of the screen, as defined in the Window Screen Web API. + * See {@link Phaser.DOM.getScreenOrientation} for possible values. + * + * @property {string} screenOrientation + * @readonly + * @public + */ + this.screenOrientation = this.dom.getScreenOrientation(); + + /** + * The _current_ scale factor based on the game dimensions vs. the scaled dimensions. + * @property {Phaser.Point} scaleFactor + * @readonly + */ + this.scaleFactor = new Phaser.Point(1, 1); + + /** + * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions. + * @property {Phaser.Point} scaleFactorInversed + * @readonly + * @protected + */ + this.scaleFactorInversed = new Phaser.Point(1, 1); + + /** + * The Display canvas is aligned by adjusting the margins; the last margins are stored here. + * + * @property {Bounds-like} margin + * @readonly + * @protected + */ + this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0}; + + /** + * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. + * @property {Phaser.Rectangle} bounds + * @readonly + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The aspect ratio of the scaled Display canvas. + * @property {number} aspectRatio + * @readonly + */ + this.aspectRatio = 0; + + /** + * The aspect ratio of the original game dimensions. + * @property {number} sourceAspectRatio + * @readonly + */ + this.sourceAspectRatio = 0; + + /** + * The native browser events from Fullscreen API changes. + * @property {any} event + * @readonly + * @private + */ + this.event = null; + + /** + * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container. + * + * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. + * - If 'visual', the edge will be constrained to the Window / displayed screen area + * - If 'layout', the edge will be constrained to the CSS Layout bounds + * - An invalid value is treated as 'visual' + * + * @member + * @property {string} bottom + * @property {string} right + * @default + */ + this.windowConstraints = { + right: 'layout', + bottom: '' + }; + + /** + * Various compatibility settings. + * A value of "(auto)" indicates the setting is configured based on device and runtime information. + * + * A {@link #refresh} may need to be performed after making changes. + * + * @protected + * + * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.) + * + * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}. + * + * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. + * + * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh. + * + * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates. + * The height set varies by device and may either be the height of the window or the viewport. + * + * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. + * + * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. + * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. + * Any other string value (including the empty string) prevents using click trampolines. + * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}. + */ + this.compatibility = { + supportsFullScreen: false, + orientationFallback: null, + noMargins: false, + scrollTo: null, + forceMinimumDocumentHeight: false, + canExpandParent: true, + clickTrampoline: '' + }; + + /** + * Scale mode to be used when not in fullscreen. + * @property {number} _scaleMode + * @private + */ + this._scaleMode = Phaser.ScaleManager.NO_SCALE; + + /* + * Scale mode to be used in fullscreen. + * @property {number} _fullScreenScaleMode + * @private + */ + this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE; + + /** + * True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * The {@link #parentNode} property is generally ignored while this is in effect. + * + * @property {boolean} parentIsWindow + */ + this.parentIsWindow = false; + + /** + * The _original_ DOM element for the parent of the Display canvas. + * This may be different in fullscreen - see {@link #createFullScreenTarget}. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * This should only be changed after moving the Game canvas to a different DOM parent. + * + * @property {?DOMElement} parentNode + */ + this.parentNode = null; + + /** + * The scale of the game in relation to its parent container. + * @property {Phaser.Point} parentScaleFactor + * @readonly + */ + this.parentScaleFactor = new Phaser.Point(1, 1); + + /** + * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). + * Update checks normally happen quicker in response to other events. + * + * @property {integer} trackParentInterval + * @default + * @protected + * @see {@link Phaser.ScaleManager#refresh refresh} + */ + this.trackParentInterval = 2000; + + /** + * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. + * When invoked this is done _after_ the Canvas size/position have been updated. + * + * The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.) + * + * This signal is _only_ called when a change occurs and a reflow may be required. + * For example, if the canvas does not change sizes because of CSS settings (such as min-width) + * then this signal will _not_ be triggered. + * + * Use this to handle responsive game layout options. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onSizeChange + */ + this.onSizeChange = new Phaser.Signal(); + + /** + * The callback that will be called each the parent container resizes. + * @property {function} onResize + * @private + */ + this.onResize = null; + + /** + * The context in which the {@link #onResize} callback will be called. + * @property {object} onResizeContext + * @private + */ + this.onResizeContext = null; + + /** + * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot. + * @private + */ + this._pendingScaleMode = null; + + /** + * Information saved when fullscreen mode is started. + * @property {?object} _fullScreenRestore + * @private + */ + this._fullScreenRestore = null; + + /** + * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}. + * @property {Phaser.Rectangle} _gameSize + * @private + */ + this._gameSize = new Phaser.Rectangle(); + + /** + * The user-supplied scale factor, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleFactor + * @private + */ + this._userScaleFactor = new Phaser.Point(1, 1); + + /** + * The user-supplied scale trim, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleTrim + * @private + */ + this._userScaleTrim = new Phaser.Point(0, 0); + + /** + * The last time the bounds were checked in `preUpdate`. + * @property {number} _lastUpdate + * @private + */ + this._lastUpdate = 0; + + /** + * Size checks updates are delayed according to the throttle. + * The throttle increases to `trackParentInterval` over time and is used to more + * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety. + * @property {integer} _updateThrottle + * @private + */ + this._updateThrottle = 0; + + /** + * The minimum throttle allowed until it has slowed down sufficiently. + * @property {integer} _updateThrottleReset + * @private + */ + this._updateThrottleReset = 100; + + /** + * The cached result of the parent (possibly window) bounds; used to invalidate sizing. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._parentBounds = new Phaser.Rectangle(); + + /** + * Temporary bounds used for internal work to cut down on new objects created. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._tempBounds = new Phaser.Rectangle(); + + /** + * The Canvas size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedCanvasSize + * @private + */ + this._lastReportedCanvasSize = new Phaser.Rectangle(); + + /** + * The Game size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedGameSize + * @private + */ + this._lastReportedGameSize = new Phaser.Rectangle(); + + /** + * @property {boolean} _booted - ScaleManager booted state. + * @private + */ + this._booted = false; + + if (game.config) + { + this.parseConfig(game.config); + } + + this.setupScale(width, height); + +}; + +/** +* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.EXACT_FIT = 0; + +/** +* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.NO_SCALE = 1; + +/** +* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.SHOW_ALL = 2; + +/** +* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.RESIZE = 3; + +/** +* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.USER_SCALE = 4; + +/** +* Names of the scale modes, indexed by value. +* +* @constant +* @type {string[]} +*/ +Phaser.ScaleManager.MODES = [ + 'EXACT_FIT', + 'NO_SCALE', + 'SHOW_ALL', + 'RESIZE', + 'USER_SCALE' +]; + +Phaser.ScaleManager.prototype = { + + /** + * Start the ScaleManager. + * + * @method Phaser.ScaleManager#boot + * @protected + */ + boot: function () { + + // Configure device-dependent compatibility + + var compat = this.compatibility; + + compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS; + + // We can't do anything about the status bars in iPads, web apps or desktops + if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop) + { + if (this.game.device.android && !this.game.device.chrome) + { + compat.scrollTo = new Phaser.Point(0, 1); + } + else + { + compat.scrollTo = new Phaser.Point(0, 0); + } + } + + if (this.game.device.desktop) + { + compat.orientationFallback = 'screen'; + compat.clickTrampoline = 'when-not-mouse'; + } + else + { + compat.orientationFallback = ''; + compat.clickTrampoline = ''; + } + + // Configure event listeners + + var _this = this; + + this._orientationChange = function(event) { + return _this.orientationChange(event); + }; + + this._windowResize = function(event) { + return _this.windowResize(event); + }; + + // This does not appear to be on the standards track + window.addEventListener('orientationchange', this._orientationChange, false); + window.addEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + this._fullScreenChange = function(event) { + return _this.fullScreenChange(event); + }; + + this._fullScreenError = function(event) { + return _this.fullScreenError(event); + }; + + document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.addEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.addEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.addEventListener('fullscreenchange', this._fullScreenChange, false); + + document.addEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.addEventListener('mozfullscreenerror', this._fullScreenError, false); + document.addEventListener('MSFullscreenError', this._fullScreenError, false); + document.addEventListener('fullscreenerror', this._fullScreenError, false); + } + + this.game.onResume.add(this._gameResumed, this); + + // Initialize core bounds + + this.dom.getOffset(this.game.canvas, this.offset); + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + this.setGameSize(this.game.width, this.game.height); + + // Don't use updateOrientationState so events are not fired + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + if (Phaser.FlexGrid) + { + this.grid = new Phaser.FlexGrid(this, this.width, this.height); + } + + this._booted = true; + + if (this._pendingScaleMode !== null) + { + this.scaleMode = this._pendingScaleMode; + this._pendingScaleMode = null; + } + + }, + + /** + * Load configuration settings. + * + * @method Phaser.ScaleManager#parseConfig + * @protected + * @param {object} config - The game configuration object. + */ + parseConfig: function (config) { + + if (config['scaleMode'] !== undefined) + { + if (this._booted) + { + this.scaleMode = config['scaleMode']; + } + else + { + this._pendingScaleMode = config['scaleMode']; + } + } + + if (config['fullScreenScaleMode'] !== undefined) + { + this.fullScreenScaleMode = config['fullScreenScaleMode']; + } + + if (config['fullScreenTarget']) + { + this.fullScreenTarget = config['fullScreenTarget']; + } + + this.pageAlignHorizontally = config.alignH || false; + this.pageAlignVertically = config.alignV || false; + + if (config.scaleH && config.scaleV) + { + this.setUserScale(config.scaleH, config.scaleV, config.trimH, config.trimV); + } + + }, + + /** + * Calculates and sets the game dimensions based on the given width and height. + * + * This should _not_ be called when in fullscreen mode. + * + * @method Phaser.ScaleManager#setupScale + * @protected + * @param {number|string} width - The width of the game. + * @param {number|string} height - The height of the game. + */ + setupScale: function (width, height) { + + var target; + var rect = new Phaser.Rectangle(); + + if (this.game.parent !== '') + { + if (typeof this.game.parent === 'string') + { + // hopefully an element ID + target = document.getElementById(this.game.parent); + } + else if (this.game.parent && this.game.parent.nodeType === 1) + { + // quick test for a HTMLelement + target = this.game.parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + // Use the full window + this.parentNode = null; + this.parentIsWindow = true; + + rect.width = this.dom.visualBounds.width; + rect.height = this.dom.visualBounds.height; + + this.offset.set(0, 0); + } + else + { + this.parentNode = target; + this.parentIsWindow = false; + + this.getParentBounds(this._parentBounds); + + rect.width = this._parentBounds.width; + rect.height = this._parentBounds.height; + + this.offset.set(this._parentBounds.x, this._parentBounds.y); + } + + var newWidth = 0; + var newHeight = 0; + + if (typeof width === 'number') + { + newWidth = width; + } + else + { + // Percentage based + this.parentScaleFactor.x = parseInt(width, 10) / 100; + newWidth = rect.width * this.parentScaleFactor.x; + } + + if (typeof height === 'number') + { + newHeight = height; + } + else + { + // Percentage based + this.parentScaleFactor.y = parseInt(height, 10) / 100; + newHeight = rect.height * this.parentScaleFactor.y; + } + + newWidth = Math.floor(newWidth); + newHeight = Math.floor(newHeight); + + this._gameSize.setTo(0, 0, newWidth, newHeight); + + this.updateDimensions(newWidth, newHeight, false); + + }, + + /** + * Invoked when the game is resumed. + * + * @method Phaser.ScaleManager#_gameResumed + * @private + */ + _gameResumed: function () { + + this.queueUpdate(true); + + }, + + /** + * Set the actual Game size. + * Use this instead of directly changing `game.width` or `game.height`. + * + * The actual physical display (Canvas element size) depends on various settings including + * - Scale mode + * - Scaling factor + * - Size of Canvas's parent element or CSS rules such as min-height/max-height; + * - The size of the Window + * + * @method Phaser.ScaleManager#setGameSize + * @public + * @param {integer} width - _Game width_, in pixels. + * @param {integer} height - _Game height_, in pixels. + */ + setGameSize: function (width, height) { + + this._gameSize.setTo(0, 0, width, height); + + if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE) + { + this.updateDimensions(width, height, true); + } + + this.queueUpdate(true); + + }, + + /** + * Set a User scaling factor used in the USER_SCALE scaling mode. + * + * The target canvas size is computed by: + * + * canvas.width = (game.width * hScale) - hTrim + * canvas.height = (game.height * vScale) - vTrim + * + * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly. + * + * @method Phaser.ScaleManager#setUserScale + * @param {number} hScale - Horizontal scaling factor. + * @param {numer} vScale - Vertical scaling factor. + * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling. + * @param {integer} [vTrim=0] - Vertical trim, applied after scaling. + * @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate + * @param {boolean} [force=true] - Force a resize during the next preUpdate + */ + setUserScale: function (hScale, vScale, hTrim, vTrim, queueUpdate, force) { + + this._userScaleFactor.setTo(hScale, vScale); + this._userScaleTrim.setTo(hTrim | 0, vTrim | 0); + + if (queueUpdate === undefined) { queueUpdate = true; } + if (force === undefined) { force = true; } + + if (queueUpdate) + { + this.queueUpdate(force); + } + + }, + + /** + * Sets the callback that will be invoked before sizing calculations. + * + * Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries: + * the browser window has been resized, the device has been rotated, or the parent container's size has changed. + * At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all + * after it makes its sizing calculations). You can read the size of the parent container from the + * `parentBounds` argument to the callback. + * + * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling. + * + * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager + * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. + * + * This callback + * - May be invoked even though the parent container or canvas sizes have not changed + * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated + * - Will be invoked from `preUpdate`, _even when_ the game is paused + * + * See {@link #onSizeChange} for a better way of reacting to layout updates. + * + * @method Phaser.ScaleManager#setResizeCallback + * @public + * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes. + * @param {object} context - The context in which the callback will be called. + */ + setResizeCallback: function (callback, context) { + + this.onResize = callback; + this.onResizeContext = context; + + }, + + /** + * Signals a resize - IF the canvas or Game size differs from the last signal. + * + * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager). + * + * It dispatches the {@link #onSizeChange} signal. + * + * @method Phaser.ScaleManager#signalSizeChange + * @private + */ + signalSizeChange: function () { + + if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) || + !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize)) + { + var width = this.width; + var height = this.height; + + this._lastReportedCanvasSize.setTo(0, 0, width, height); + this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height); + + if (this.grid) + { + this.grid.onResize(width, height); + } + + this.onSizeChange.dispatch(this, width, height); + + // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode. + if (this.currentScaleMode === Phaser.ScaleManager.RESIZE) + { + this.game.state.resize(width, height); + this.game.load.resize(width, height); + } + } + + }, + + /** + * Set the min and max dimensions for the Display canvas. + * + * _Note:_ The min/max dimensions are only applied in some cases + * - When the device is not in an incorrect orientation; or + * - The scale mode is EXACT_FIT when not in fullscreen + * + * @method Phaser.ScaleManager#setMinMax + * @public + * @param {number} minWidth - The minimum width the game is allowed to scale down to. + * @param {number} minHeight - The minimum height the game is allowed to scale down to. + * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified. + * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified. + * @todo These values are only sometimes honored. + */ + setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) { + + this.minWidth = minWidth; + this.minHeight = minHeight; + + if (typeof maxWidth !== 'undefined') + { + this.maxWidth = maxWidth; + } + + if (typeof maxHeight !== 'undefined') + { + this.maxHeight = maxHeight; + } + + }, + + /** + * The ScaleManager.preUpdate is called automatically by the core Game loop. + * + * @method Phaser.ScaleManager#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.game.time.time < (this._lastUpdate + this._updateThrottle)) + { + return; + } + + var prevThrottle = this._updateThrottle; + this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100; + + this.dom.getOffset(this.game.canvas, this.offset); + + var prevWidth = this._parentBounds.width; + var prevHeight = this._parentBounds.height; + var bounds = this.getParentBounds(this._parentBounds); + + var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight; + + // Always invalidate on a newly detected orientation change + var orientationChanged = this.updateOrientationState(); + + if (boundsChanged || orientationChanged) + { + if (this.onResize) + { + this.onResize.call(this.onResizeContext, this, bounds); + } + + this.updateLayout(); + + this.signalSizeChange(); + } + + // Next throttle, eg. 25, 50, 100, 200.. + var throttle = this._updateThrottle * 2; + + // Don't let an update be too eager about resetting the throttle. + if (this._updateThrottle < prevThrottle) + { + throttle = Math.min(prevThrottle, this._updateThrottleReset); + } + + this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval); + this._lastUpdate = this.game.time.time; + + }, + + /** + * Update method while paused. + * + * @method Phaser.ScaleManager#pauseUpdate + * @private + */ + pauseUpdate: function () { + + this.preUpdate(); + + // Updates at slowest. + this._updateThrottle = this.trackParentInterval; + + }, + + /** + * Update the dimensions taking the parent scaling factor into account. + * + * @method Phaser.ScaleManager#updateDimensions + * @private + * @param {number} width - The new width of the parent container. + * @param {number} height - The new height of the parent container. + * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars. + */ + updateDimensions: function (width, height, resize) { + + this.width = width * this.parentScaleFactor.x; + this.height = height * this.parentScaleFactor.y; + + this.game.width = this.width; + this.game.height = this.height; + + this.sourceAspectRatio = this.width / this.height; + this.updateScalingAndBounds(); + + if (resize) + { + // Resize the renderer (which in turn resizes the Display canvas!) + this.game.renderer.resize(this.width, this.height); + + // The Camera can never be smaller than the Game size + this.game.camera.setSize(this.width, this.height); + + // This should only happen if the world is smaller than the new canvas size + this.game.world.resize(this.width, this.height); + } + + }, + + /** + * Update relevant scaling values based on the ScaleManager dimension and game dimensions, + * which should already be set. This does not change {@link #sourceAspectRatio}. + * + * @method Phaser.ScaleManager#updateScalingAndBounds + * @private + */ + updateScalingAndBounds: function () { + + this.scaleFactor.x = this.game.width / this.width; + this.scaleFactor.y = this.game.height / this.height; + + this.scaleFactorInversed.x = this.width / this.game.width; + this.scaleFactorInversed.y = this.height / this.game.height; + + this.aspectRatio = this.width / this.height; + + // This can be invoked in boot pre-canvas + if (this.game.canvas) + { + this.dom.getOffset(this.game.canvas, this.offset); + } + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + // Can be invoked in boot pre-input + if (this.game.input && this.game.input.scale) + { + this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y); + } + + }, + + /** + * Force the game to run in only one orientation. + * + * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. + * + * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor + * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the + * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` + * + * @method Phaser.ScaleManager#forceOrientation + * @public + * @param {boolean} forceLandscape - true if the game should run in landscape mode only. + * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. + */ + forceOrientation: function (forceLandscape, forcePortrait) { + + if (forcePortrait === undefined) { forcePortrait = false; } + + if (forceLandscape === true && forcePortrait === true) + { + console.warn('Phaser.ScaleManager: forceLandscape and forcePortrait cannot both be true.'); + return; + } + + this.forceLandscape = forceLandscape; + this.forcePortrait = forcePortrait; + + this.queueUpdate(true); + + }, + + /** + * Classify the orientation, per `getScreenOrientation`. + * + * @method Phaser.ScaleManager#classifyOrientation + * @private + * @param {string} orientation - The orientation string, e.g. 'portrait-primary'. + * @return {?string} The classified orientation: 'portrait', 'landscape`, or null. + */ + classifyOrientation: function (orientation) { + + if (orientation === 'portrait-primary' || orientation === 'portrait-secondary') + { + return 'portrait'; + } + else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary') + { + return 'landscape'; + } + else + { + return null; + } + + }, + + /** + * Updates the current orientation and dispatches orientation change events. + * + * @method Phaser.ScaleManager#updateOrientationState + * @private + * @return {boolean} True if the orientation state changed which means a forced update is likely required. + */ + updateOrientationState: function () { + + var previousOrientation = this.screenOrientation; + var previouslyIncorrect = this.incorrectOrientation; + + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) || + (this.forcePortrait && !this.isPortrait); + + var changed = previousOrientation !== this.screenOrientation; + var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation; + + if (correctnessChanged) + { + if (this.incorrectOrientation) + { + this.enterIncorrectOrientation.dispatch(); + } + else + { + this.leaveIncorrectOrientation.dispatch(); + } + } + + if (changed || correctnessChanged) + { + this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect); + } + + return changed || correctnessChanged; + + }, + + /** + * window.orientationchange event handler. + * + * @method Phaser.ScaleManager#orientationChange + * @private + * @param {Event} event - The orientationchange event data. + */ + orientationChange: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * window.resize event handler. + * + * @method Phaser.ScaleManager#windowResize + * @private + * @param {Event} event - The resize event data. + */ + windowResize: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * Scroll to the top - in some environments. See `compatibility.scrollTo`. + * + * @method Phaser.ScaleManager#scrollTop + * @private + */ + scrollTop: function () { + + var scrollTo = this.compatibility.scrollTo; + + if (scrollTo) + { + window.scrollTo(scrollTo.x, scrollTo.y); + } + + }, + + /** + * The "refresh" methods informs the ScaleManager that a layout refresh is required. + * + * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) + * when the browser is resized, the orientation changes, or when there is a detected change + * of the Parent size. Refreshing is also done automatically when public properties, + * such as {@link #scaleMode}, are updated or state-changing methods are invoked. + * + * The "refresh" method _may_ need to be used in a few (rare) situtations when + * + * - a device change event is not correctly detected; or + * - the Parent size changes (and an immediate reflow is desired); or + * - the ScaleManager state is updated by non-standard means; or + * - certain {@link #compatibility} properties are manually changed. + * + * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. + * + * @method Phaser.ScaleManager#refresh + * @public + */ + refresh: function () { + + this.scrollTop(); + this.queueUpdate(true); + + }, + + /** + * Updates the game / canvas position and size. + * + * @method Phaser.ScaleManager#updateLayout + * @private + */ + updateLayout: function () { + + var scaleMode = this.currentScaleMode; + + if (scaleMode === Phaser.ScaleManager.RESIZE) + { + this.reflowGame(); + return; + } + + this.scrollTop(); + + if (this.compatibility.forceMinimumDocumentHeight) + { + // (This came from older code, by why is it here?) + // Set minimum height of content to new window height + document.documentElement.style.minHeight = window.innerHeight + 'px'; + } + + if (this.incorrectOrientation) + { + this.setMaximum(); + } + else + { + if (scaleMode === Phaser.ScaleManager.EXACT_FIT) + { + this.setExactFit(); + } + else if (scaleMode === Phaser.ScaleManager.SHOW_ALL) + { + if (!this.isFullScreen && this.boundingParent && + this.compatibility.canExpandParent) + { + // Try to expand parent out, but choosing maximizing dimensions. + // Then select minimize dimensions which should then honor parent + // maximum bound applications. + this.setShowAll(true); + this.resetCanvas(); + this.setShowAll(); + } + else + { + this.setShowAll(); + } + } + else if (scaleMode === Phaser.ScaleManager.NO_SCALE) + { + this.width = this.game.width; + this.height = this.game.height; + } + else if (scaleMode === Phaser.ScaleManager.USER_SCALE) + { + this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x; + this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y; + } + } + + if (!this.compatibility.canExpandParent && + (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE)) + { + var bounds = this.getParentBounds(this._tempBounds); + this.width = Math.min(this.width, bounds.width); + this.height = Math.min(this.height, bounds.height); + } + + // Always truncate / force to integer + this.width = this.width | 0; + this.height = this.height | 0; + + this.reflowCanvas(); + + }, + + /** + * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. + * + * If in fullscreen mode or without parent (see {@link #parentIsWindow}), + * this will be the bounds of the visual viewport itself. + * + * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside + * the viewport then this function may return a smaller than expected size. + * + * Values are rounded to the nearest pixel. + * + * @method Phaser.ScaleManager#getParentBounds + * @protected + * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed. + * @return {Phaser.Rectangle} The established parent bounds. + */ + getParentBounds: function (target) { + + var bounds = target || new Phaser.Rectangle(); + var parentNode = this.boundingParent; + var visualBounds = this.dom.visualBounds; + var layoutBounds = this.dom.layoutBounds; + + if (!parentNode) + { + bounds.setTo(0, 0, visualBounds.width, visualBounds.height); + } + else + { + // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect + var clientRect = parentNode.getBoundingClientRect(); + var parentRect = (parentNode.offsetParent) ? parentNode.offsetParent.getBoundingClientRect() : parentNode.getBoundingClientRect(); + + bounds.setTo(clientRect.left - parentRect.left, clientRect.top - parentRect.top, clientRect.width, clientRect.height); + + var wc = this.windowConstraints; + + if (wc.right) + { + var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds; + bounds.right = Math.min(bounds.right, windowBounds.width); + } + + if (wc.bottom) + { + var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds; + bounds.bottom = Math.min(bounds.bottom, windowBounds.height); + } + } + + bounds.setTo( + Math.round(bounds.x), Math.round(bounds.y), + Math.round(bounds.width), Math.round(bounds.height)); + + return bounds; + + }, + + + /** + * Shorthand for setting {@link #pageAlignHorizontally} and {@link #pageAlignVertically}. + * + * @method Phaser.ScaleManager#align + * @param {boolean} [horizontal] - Value for {@link #pageAlignHorizontally}. Pass `null` to leave unchanged. + * @param {boolean} [vertical] - Value for {@link #pageAlignVertically}. Omit or pass `null` to leave unchanged. + */ + align: function (horizontal, vertical) { + + if (horizontal != null) + { + this.pageAlignHorizontally = horizontal; + } + + if (vertical != null) + { + this.pageAlignVertically = vertical; + } + + }, + + /** + * Update the canvas position/margins - for alignment within the parent container. + * + * The canvas margins _must_ be reset/cleared prior to invoking this. + * + * @method Phaser.ScaleManager#alignCanvas + * @private + * @param {boolean} horizontal - Align horizontally? + * @param {boolean} vertical - Align vertically? + */ + alignCanvas: function (horizontal, vertical) { + + var parentBounds = this.getParentBounds(this._tempBounds); + var canvas = this.game.canvas; + var margin = this.margin; + + if (horizontal) + { + margin.left = margin.right = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.width < parentBounds.width && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.left - parentBounds.x; + var targetEdge = (parentBounds.width / 2) - (this.width / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + + margin.left = Math.round(offset); + } + + canvas.style.marginLeft = margin.left + 'px'; + + if (margin.left !== 0) + { + margin.right = -(parentBounds.width - canvasBounds.width - margin.left); + canvas.style.marginRight = margin.right + 'px'; + } + } + + if (vertical) + { + margin.top = margin.bottom = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.height < parentBounds.height && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.top - parentBounds.y; + var targetEdge = (parentBounds.height / 2) - (this.height / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + margin.top = Math.round(offset); + } + + canvas.style.marginTop = margin.top + 'px'; + + if (margin.top !== 0) + { + margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top); + canvas.style.marginBottom = margin.bottom + 'px'; + } + } + + // Silly backwards compatibility.. + margin.x = margin.left; + margin.y = margin.top; + + }, + + /** + * Updates the Game state / size. + * + * The canvas margins may always be adjusted, even if alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowGame + * @private + */ + reflowGame: function () { + + this.resetCanvas('', ''); + + var bounds = this.getParentBounds(this._tempBounds); + this.updateDimensions(bounds.width, bounds.height, true); + + }, + + /** + * Updates the Display canvas size. + * + * The canvas margins may always be adjusted, even alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowCanvas + * @private + */ + reflowCanvas: function () { + + if (!this.incorrectOrientation) + { + this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width); + this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height); + } + + this.resetCanvas(); + + if (!this.compatibility.noMargins) + { + if (this.isFullScreen && this._createdFullScreenTarget) + { + this.alignCanvas(true, true); + } + else + { + this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically); + } + } + + this.updateScalingAndBounds(); + + }, + + /** + * "Reset" the Display canvas and set the specified width/height. + * + * @method Phaser.ScaleManager#resetCanvas + * @private + * @param {string} [cssWidth=(current width)] - The css width to set. + * @param {string} [cssHeight=(current height)] - The css height to set. + */ + resetCanvas: function (cssWidth, cssHeight) { + + if (cssWidth === undefined) { cssWidth = this.width + 'px'; } + if (cssHeight === undefined) { cssHeight = this.height + 'px'; } + + var canvas = this.game.canvas; + + if (!this.compatibility.noMargins) + { + canvas.style.marginLeft = ''; + canvas.style.marginTop = ''; + canvas.style.marginRight = ''; + canvas.style.marginBottom = ''; + } + + canvas.style.width = cssWidth; + canvas.style.height = cssHeight; + + }, + + /** + * Queues/marks a size/bounds check as needing to occur (from `preUpdate`). + * + * @method Phaser.ScaleManager#queueUpdate + * @private + * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty. + */ + queueUpdate: function (force) { + + if (force) + { + this._parentBounds.width = 0; + this._parentBounds.height = 0; + } + + this._updateThrottle = this._updateThrottleReset; + + }, + + /** + * Reset internal data/state. + * + * @method Phaser.ScaleManager#reset + * @private + */ + reset: function (clearWorld) { + + if (clearWorld && this.grid) + { + this.grid.reset(); + } + + }, + + /** + * Updates the width/height to that of the window. + * + * @method Phaser.ScaleManager#setMaximum + * @private + */ + setMaximum: function () { + + this.width = this.dom.visualBounds.width; + this.height = this.dom.visualBounds.height; + + }, + + /** + * Updates the width/height such that the game is scaled proportionally. + * + * @method Phaser.ScaleManager#setShowAll + * @private + * @param {boolean} expanding - If true then the maximizing dimension is chosen. + */ + setShowAll: function (expanding) { + + var bounds = this.getParentBounds(this._tempBounds); + var width = bounds.width; + var height = bounds.height; + + var multiplier; + + if (expanding) + { + multiplier = Math.max((height / this.game.height), (width / this.game.width)); + } + else + { + multiplier = Math.min((height / this.game.height), (width / this.game.width)); + } + + this.width = Math.round(this.game.width * multiplier); + this.height = Math.round(this.game.height * multiplier); + + }, + + /** + * Updates the width/height such that the game is stretched to the available size. + * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen. + * + * @method Phaser.ScaleManager#setExactFit + * @private + */ + setExactFit: function () { + + var bounds = this.getParentBounds(this._tempBounds); + + this.width = bounds.width; + this.height = bounds.height; + + if (this.isFullScreen) + { + // Max/min not honored fullscreen + return; + } + + if (this.maxWidth) + { + this.width = Math.min(this.width, this.maxWidth); + } + + if (this.maxHeight) + { + this.height = Math.min(this.height, this.maxHeight); + } + + }, + + /** + * Creates a fullscreen target. This is called automatically as as needed when entering + * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}. + * + * Use {@link #onFullScreenInit} to customize the created object. + * + * @method Phaser.ScaleManager#createFullScreenTarget + * @protected + */ + createFullScreenTarget: function () { + + var fsTarget = document.createElement('div'); + + fsTarget.style.margin = '0'; + fsTarget.style.padding = '0'; + fsTarget.style.background = '#000'; + + return fsTarget; + + }, + + /** + * Display the game in the browser's fullscreen mode. + * + * This _must_ be called from a user-input Pointer or Mouse event (and possibly a {@link https://www.chromestatus.com/feature/6131337345892352 "user gesture"}), e.g., + * + * - {@link Phaser.Events#onInputUp} + * - {@link Phaser.Input#onUp} or {@link Phaser.Input#onTap} + * - `click`, `mousedown`, `mouseup`, `pointerup`, or `touchend` + * + * Games within an iframe will also be blocked from fullscreen unless the iframe has the `allowfullscreen` attribute. + * + * The {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} must be {@link http://caniuse.com/#search=fullscreen supported by the browser} for this to work - it is not the same as setting + * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current + * device is reported to support fullscreen mode. + * + * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. + * + * Safari blocks access to keyboard events in fullscreen mode (as a security measure). + * + * @method Phaser.ScaleManager#startFullScreen + * @public + * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. + * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed. + * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) + */ + startFullScreen: function (antialias, allowTrampoline) { + + if (this.isFullScreen) + { + return false; + } + + if (!this.compatibility.supportsFullScreen) + { + // Error is called in timeout to emulate the real fullscreenerror event better + var _this = this; + + setTimeout(function () { + _this.fullScreenError(); + }, 10); + + return; + } + + if (this.compatibility.clickTrampoline === 'when-not-mouse') + { + var input = this.game.input; + + if (input.activePointer && + input.activePointer !== input.mousePointer && + (allowTrampoline || allowTrampoline !== false)) + { + input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]); + return; + } + } + + if (antialias !== undefined && this.game.renderType === Phaser.CANVAS) + { + this.game.stage.smoothed = antialias; + } + + var fsTarget = this.fullScreenTarget; + + if (!fsTarget) + { + this.cleanupCreatedTarget(); + + this._createdFullScreenTarget = this.createFullScreenTarget(); + fsTarget = this._createdFullScreenTarget; + } + + var initData = { + targetElement: fsTarget + }; + + this.hasPhaserSetFullScreen = true; + + this.onFullScreenInit.dispatch(this, initData); + + if (this._createdFullScreenTarget) + { + // Move the Display canvas inside of the target and add the target to the DOM + // (The target has to be added for the Fullscreen API to work.) + var canvas = this.game.canvas; + var parent = canvas.parentNode; + parent.insertBefore(fsTarget, canvas); + fsTarget.appendChild(canvas); + } + + if (this.game.device.fullscreenKeyboard) + { + fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT); + } + else + { + fsTarget[this.game.device.requestFullscreen](); + } + + return true; + + }, + + /** + * Stops / exits fullscreen mode, if active. + * + * @method Phaser.ScaleManager#stopFullScreen + * @public + * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. + */ + stopFullScreen: function () { + + if (!this.isFullScreen || !this.compatibility.supportsFullScreen) + { + return false; + } + + this.hasPhaserSetFullScreen = false; + + document[this.game.device.cancelFullscreen](); + + return true; + + }, + + /** + * Cleans up the previous fullscreen target, if such was automatically created. + * This ensures the canvas is restored to its former parent, assuming the target didn't move. + * + * @method Phaser.ScaleManager#cleanupCreatedTarget + * @private + */ + cleanupCreatedTarget: function () { + + var fsTarget = this._createdFullScreenTarget; + + if (fsTarget && fsTarget.parentNode) + { + // Make sure to cleanup synthetic target for sure; + // swap the canvas back to the parent. + var parent = fsTarget.parentNode; + parent.insertBefore(this.game.canvas, fsTarget); + parent.removeChild(fsTarget); + } + + this._createdFullScreenTarget = null; + + }, + + /** + * Used to prepare/restore extra fullscreen mode settings. + * (This does move any elements within the DOM tree.) + * + * @method Phaser.ScaleManager#prepScreenMode + * @private + * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_. + */ + prepScreenMode: function (enteringFullscreen) { + + var createdTarget = !!this._createdFullScreenTarget; + var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget; + + if (enteringFullscreen) + { + if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT) + { + // Resize target, as long as it's not the canvas + if (fsTarget !== this.game.canvas) + { + this._fullScreenRestore = { + targetWidth: fsTarget.style.width, + targetHeight: fsTarget.style.height + }; + + fsTarget.style.width = '100%'; + fsTarget.style.height = '100%'; + } + } + } + else + { + // Have restore information + if (this._fullScreenRestore) + { + fsTarget.style.width = this._fullScreenRestore.targetWidth; + fsTarget.style.height = this._fullScreenRestore.targetHeight; + + this._fullScreenRestore = null; + } + + // Always reset to game size + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.resetCanvas(); + } + + }, + + /** + * Called automatically when the browser enters of leaves fullscreen mode. + * + * @method Phaser.ScaleManager#fullScreenChange + * @private + * @param {Event} [event=undefined] - The fullscreenchange event + */ + fullScreenChange: function (event) { + + this.event = event; + + if (this.isFullScreen) + { + this.prepScreenMode(true); + + this.updateLayout(); + this.queueUpdate(true); + } + else + { + this.prepScreenMode(false); + + this.cleanupCreatedTarget(); + + this.updateLayout(); + this.queueUpdate(true); + } + + this.onFullScreenChange.dispatch(this, this.width, this.height); + + }, + + /** + * Called automatically when the browser fullscreen request fails; + * or called when a fullscreen request is made on a device for which it is not supported. + * + * @method Phaser.ScaleManager#fullScreenError + * @private + * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API. + */ + fullScreenError: function (event) { + + this.event = event; + + this.cleanupCreatedTarget(); + + console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API'); + + this.onFullScreenError.dispatch(this); + + }, + + /** + * Takes a Sprite or Image object and scales it to fit the given dimensions. + * Scaling happens proportionally without distortion to the sprites texture. + * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the + * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either + * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. + * + * @method Phaser.ScaleManager#scaleSprite + * @protected + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale. + * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. + * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. + * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. + * @return {Phaser.Sprite|Phaser.Image} The scaled sprite. + */ + scaleSprite: function (sprite, width, height, letterBox) { + + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + if (letterBox === undefined) { letterBox = false; } + + if (!sprite || !sprite['scale']) + { + return sprite; + } + + sprite.scale.x = 1; + sprite.scale.y = 1; + + if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0)) + { + return sprite; + } + + var scaleX1 = width; + var scaleY1 = (sprite.height * width) / sprite.width; + + var scaleX2 = (sprite.width * height) / sprite.height; + var scaleY2 = height; + + var scaleOnWidth = (scaleX2 > width); + + if (scaleOnWidth) + { + scaleOnWidth = letterBox; + } + else + { + scaleOnWidth = !letterBox; + } + + if (scaleOnWidth) + { + sprite.width = Math.floor(scaleX1); + sprite.height = Math.floor(scaleY1); + } + else + { + sprite.width = Math.floor(scaleX2); + sprite.height = Math.floor(scaleY2); + } + + // Enable at some point? + // sprite.x = Math.floor((width - sprite.width) / 2); + // sprite.y = Math.floor((height - sprite.height) / 2); + + return sprite; + + }, + + /** + * Destroys the ScaleManager and removes any event listeners. + * This should probably only be called when the game is destroyed. + * + * @method Phaser.ScaleManager#destroy + * @protected + */ + destroy: function () { + + this.game.onResume.remove(this._gameResumed, this); + + window.removeEventListener('orientationchange', this._orientationChange, false); + window.removeEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.removeEventListener('fullscreenchange', this._fullScreenChange, false); + + document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.removeEventListener('mozfullscreenerror', this._fullScreenError, false); + document.removeEventListener('MSFullscreenError', this._fullScreenError, false); + document.removeEventListener('fullscreenerror', this._fullScreenError, false); + } + + } + +}; + +Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager; + +/** +* The DOM element that is considered the Parent bounding element, if any. +* +* This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified. +* It will also be null if there is no game canvas or if the game canvas has no parent. +* +* @name Phaser.ScaleManager#boundingParent +* @property {?DOMElement} boundingParent +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", { + + get: function () { + + if (this.parentIsWindow || + (this.isFullScreen && this.hasPhaserSetFullScreen && !this._createdFullScreenTarget)) + { + return null; + } + + var parentNode = this.game.canvas && this.game.canvas.parentNode; + + return parentNode || null; + + } + +}); + +/** +* The scaling method used by the ScaleManager when not in fullscreen. +* +*
+*
{@link Phaser.ScaleManager.NO_SCALE}
+*
+* The Game display area will not be scaled - even if it is too large for the canvas/screen. +* This mode _ignores_ any applied scaling factor and displays the canvas at the Game size. +*
+*
{@link Phaser.ScaleManager.EXACT_FIT}
+*
+* The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen. +* Proportions are not maintained. +*
+*
{@link Phaser.ScaleManager.SHOW_ALL}
+*
+* Show the entire game display area while _maintaining_ the original aspect ratio. +*
+*
{@link Phaser.ScaleManager.RESIZE}
+*
+* The dimensions of the game display area are changed to match the size of the parent container. +* That is, this mode _changes the Game size_ to match the display size. +*

+* Any manually set Game size (see {@link #setGameSize}) is ignored while in effect. +*

+*
{@link Phaser.ScaleManager.USER_SCALE}
+*
+* The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}. +*

+* This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback} +* for flexible custom-sizing needs. +*

+*
+* +* @name Phaser.ScaleManager#scaleMode +* @property {integer} scaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", { + + get: function () { + + return this._scaleMode; + + }, + + set: function (value) { + + if (value !== this._scaleMode) + { + if (!this.isFullScreen) + { + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.queueUpdate(true); + } + + this._scaleMode = value; + } + + return this._scaleMode; + + } + +}); + +/** +* The scaling method used by the ScaleManager when in fullscreen. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#fullScreenScaleMode +* @property {integer} fullScreenScaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", { + + get: function () { + + return this._fullScreenScaleMode; + + }, + + set: function (value) { + + if (value !== this._fullScreenScaleMode) + { + // If in fullscreen then need a wee bit more work + if (this.isFullScreen) + { + this.prepScreenMode(false); + this._fullScreenScaleMode = value; + this.prepScreenMode(true); + + this.queueUpdate(true); + } + else + { + this._fullScreenScaleMode = value; + } + } + + return this._fullScreenScaleMode; + + } + +}); + +/** +* Returns the current scale mode - for normal or fullscreen operation. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#currentScaleMode +* @property {number} currentScaleMode +* @protected +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", { + + get: function () { + + return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode; + + } + +}); + +/** +* When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align horizontally across the page the Display canvas should be added directly to page; +* or the parent container should itself be horizontally aligned. +* +* Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignHorizontally +* @property {boolean} pageAlignHorizontally +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", { + + get: function () { + + return this._pageAlignHorizontally; + + }, + + set: function (value) { + + if (value !== this._pageAlignHorizontally) + { + this._pageAlignHorizontally = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain +* a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically +* _within_ the remaining available height dictated by the Parent element. +* +* One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. +* If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). +* +* _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height. +* To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true. +* +* Vertical alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignVertically +* @property {boolean} pageAlignVertically +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", { + + get: function () { + + return this._pageAlignVertically; + + }, + + set: function (value) { + + if (value !== this._pageAlignVertically) + { + this._pageAlignVertically = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* Returns true if the browser is in fullscreen mode, otherwise false. +* @name Phaser.ScaleManager#isFullScreen +* @property {boolean} isFullScreen +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", { + + get: function () { + return !!(document['fullscreenElement'] || + document['webkitFullscreenElement'] || + document['mozFullScreenElement'] || + document['msFullscreenElement']); + } + +}); + +/** +* Returns true if the screen orientation is in portrait mode. +* +* @name Phaser.ScaleManager#isPortrait +* @property {boolean} isPortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'portrait'; + } + +}); + +/** +* Returns true if the screen orientation is in landscape mode. +* +* @name Phaser.ScaleManager#isLandscape +* @property {boolean} isLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'landscape'; + } + +}); + +/** +* Returns true if the game dimensions are portrait (height > width). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGamePortrait +* @property {boolean} isGamePortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", { + + get: function () { + return (this.height > this.width); + } + +}); + +/** +* Returns true if the game dimensions are landscape (width > height). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGameLandscape +* @property {boolean} isGameLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", { + + get: function () { + return (this.width > this.height); + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of methods for displaying debug information about game objects. +* +* If your game is running in Canvas mode, then you should invoke all of the Debug methods from +* your games `render` function. This is because they are drawn directly onto the game canvas +* itself, so if you call any debug methods outside of `render` they are likely to be overwritten +* by the game itself. +* +* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture +* to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug +* in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! +* +* @class Phaser.Utils.Debug +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Utils.Debug = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Image} sprite - If debugging in WebGL mode, this is the Image displaying the debug {@link #bmd BitmapData}. + */ + this.sprite = null; + + /** + * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.context = null; + + /** + * @property {string} font - The font that the debug information is rendered in. + * @default + */ + this.font = '14px Courier'; + + /** + * @property {number} columnWidth - The spacing between columns. + * @default + */ + this.columnWidth = 100; + + /** + * @property {number} lineHeight - The line height between the debug text. + * @default + */ + this.lineHeight = 16; + + /** + * @property {number} lineWidth - The width of the stroke on lines and shapes. A positive number. + * @default + */ + this.lineWidth = 1; + + /** + * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. + * @default + */ + this.renderShadow = true; + + /** + * @property {string} currentColor - The color last set by {@link #start} or {@link #text}. + * @default + * @protected + */ + this.currentColor = null; + + /** + * @property {number} currentX - The current X position the debug information will be rendered at. + * @default + */ + this.currentX = 0; + + /** + * @property {number} currentY - The current Y position the debug information will be rendered at. + * @default + */ + this.currentY = 0; + + /** + * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it. + * @default + */ + this.currentAlpha = 1; + + /** + * @property {boolean} dirty - Does the canvas need re-rendering? + * @default + */ + this.dirty = false; + + /** + * @property {boolean} isDisabled - If `enableDebug: false` is passed to {@link Phaser.Game} or if Phaser is built without the Debug class, this will be true. + * @default + * @readonly + */ + this.isDisabled = false; + + /** + * @property {Phaser.Line} _line - A reusable rendering line. + * @private + */ + this._line = null; + + /** + * @property {Phaser.Rectangle} _rect - A reusable rendering rectangle. + * @private + */ + this._rect = null; + +}; + +Phaser.Utils.Debug.prototype = { + + /** + * Internal method that boots the debug displayer. + * + * @method Phaser.Utils.Debug#boot + * @protected + */ + boot: function () { + + if (this.game.renderType === Phaser.CANVAS) + { + this.context = this.game.context; + } + else + { + this.bmd = new Phaser.BitmapData(this.game, '__DEBUG', this.game.width, this.game.height, true); + this.sprite = this.game.make.image(0, 0, this.bmd); + this.game.stage.addChild(this.sprite); + + this.game.scale.onSizeChange.add(this.resize, this); + + this.canvas = Phaser.CanvasPool.create(this, this.game.width, this.game.height); + this.context = this.canvas.getContext('2d'); + } + + this._line = new Phaser.Line(); + this._rect = new Phaser.Rectangle(); + + }, + + /** + * Internal method that resizes the BitmapData and Canvas. + * Called by ScaleManager.onSizeChange only in WebGL mode. + * + * @method Phaser.Utils.Debug#resize + * @protected + */ + resize: function () { + + this.bmd.resize(this.game.width, this.game.height); + + this.canvas.width = this.game.width; + this.canvas.height = this.game.height; + + }, + + /** + * Internal method that clears the canvas (if a Sprite) ready for a new debug session. + * + * @method Phaser.Utils.Debug#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.dirty && this.sprite) + { + this.bmd.clear(); + this.bmd.draw(this.canvas, 0, 0); + + this.context.clearRect(0, 0, this.game.width, this.game.height); + this.dirty = false; + } + + }, + + /** + * Clears the Debug canvas. + * + * @method Phaser.Utils.Debug#reset + */ + reset: function () { + + if (this.context) + { + this.context.clearRect(0, 0, this.game.width, this.game.height); + } + + if (this.sprite) + { + this.bmd.clear(); + } + + }, + + /** + * Internal method that resets and starts the debug output values. + * + * @method Phaser.Utils.Debug#start + * @protected + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + * @param {number} [columnWidth=0] - The spacing between columns. + */ + start: function (x, y, color, columnWidth) { + + if (typeof x !== 'number') { x = 0; } + if (typeof y !== 'number') { y = 0; } + color = color || 'rgb(255,255,255)'; + if (columnWidth === undefined) { columnWidth = 0; } + + this.currentX = x; + this.currentY = y; + this.currentColor = color; + this.columnWidth = columnWidth; + + this.dirty = true; + + this.context.save(); + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.strokeStyle = color; + this.context.fillStyle = color; + this.context.font = this.font; + this.context.globalAlpha = this.currentAlpha; + + }, + + /** + * Internal method that stops the debug output. + * + * @method Phaser.Utils.Debug#stop + * @protected + */ + stop: function () { + + this.context.restore(); + + }, + + /** + * Internal method that outputs a single line of text split over as many columns as needed, one per parameter. + * + * @method Phaser.Utils.Debug#line + * @protected + */ + line: function () { + + var x = this.currentX; + + for (var i = 0; i < arguments.length; i++) + { + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(arguments[i], x + 1, this.currentY + 1); + this.context.fillStyle = this.currentColor; + } + + this.context.fillText(arguments[i], x, this.currentY); + + x += this.columnWidth; + } + + this.currentY += this.lineHeight; + + }, + + /** + * Render Sound Manager information, including volume, mute, audio mode, and locked status. + * + * @method Phaser.Utils.Debug#sound + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + sound: function (x, y, color) { + + var sound = this.game.sound; + + this.start(x, y, color); + + if (sound.noAudio) + { + this.line('Audio is disabled'); + } + else + { + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Mute on pause: ' + sound.muteOnPause); + this.line('Using: ' + (sound.usingWebAudio ? ('Web Audio - ' + sound.context.state) : 'Audio Tag')); + this.line('Touch locked: ' + sound.touchLocked); + } + + this.stop(); + + }, + + /** + * Render Sound information, including decoded state, duration, volume and more. + * + * @method Phaser.Utils.Debug#soundInfo + * @param {Phaser.Sound} sound - The sound object to debug. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + soundInfo: function (sound, x, y, color) { + + this.start(x, y, color); + this.line('Sound: ' + sound.key + ' Touch locked: ' + sound.game.sound.touchLocked); + this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback); + this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding); + this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying + ' Loop: ' + sound.loop); + this.line('Time: ' + sound.currentTime); + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Using: ' + (sound.usingWebAudio ? 'Web Audio' : 'Audio Tag')); + + if (sound.currentMarker !== '') + { + this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')'); + this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop); + this.line('Position: ' + sound.position); + } + + this.stop(); + + }, + + /** + * Marks the follow {@link #target} and {@link #deadzone}. + * + * @method Phaser.Utils.Debug#camera + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {string} [color] - Color of the debug shapes to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the shapes filled (default, true) or stroked (false). + */ + camera: function (camera, color, filled) { + + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + if (deadzone) + { + this._rect.setTo(view.x + deadzone.x, view.y + deadzone.y, deadzone.width, deadzone.height); + this.rectangle(this._rect, color, filled); + } + + if (target) + { + this._line.setTo(view.centerX, view.centerY, target.x, target.y); + this.geom(this._line, color, filled); + this.geom(target, color, false, 3); + } + + }, + + /** + * Render camera information including dimensions and location. + * + * @method Phaser.Utils.Debug#cameraInfo + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + cameraInfo: function (camera, x, y, color) { + + var bounds = camera.bounds; + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + this.start(x, y, color); + this.line('Camera (' + camera.width + ' x ' + camera.height + ')'); + this.line('x: ' + camera.x + ' y: ' + camera.y); + this.line('Bounds: ' + (bounds ? ('x: ' + bounds.x + ' y: ' + bounds.y + ' w: ' + bounds.width + ' h: ' + bounds.height) : 'none')); + this.line('View: x: ' + view.x + ' y: ' + view.y + ' w: ' + view.width + ' h: ' + view.height); + this.line('Deadzone: ' + (deadzone ? ('x: ' + deadzone.x + ' y: ' + deadzone.y + ' w: ' + deadzone.width + ' h: ' + deadzone.height) : deadzone)); + this.line('Total in view: ' + camera.totalInView); + this.line('At limit: x: ' + camera.atLimit.x + ' y: ' + camera.atLimit.y); + this.line('Target: ' + (target ? (target.name || target) : 'none')); + this.stop(); + + }, + + /** + * Render Timer information. + * + * @method Phaser.Utils.Debug#timer + * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + timer: function (timer, x, y, color) { + + this.start(x, y, color); + this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')'); + this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration); + this.line('Paused: ' + timer.paused + ' Length: ' + timer.length); + this.stop(); + + }, + + /** + * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text. + * + * @method Phaser.Utils.Debug#pointer + * @param {Phaser.Pointer} pointer - The Pointer you wish to display. + * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. + * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down. + * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false). + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + pointer: function (pointer, hideIfUp, downColor, upColor, color) { + + if (pointer == null) + { + return; + } + + if (hideIfUp === undefined) { hideIfUp = false; } + downColor = downColor || 'rgba(0,255,0,0.5)'; + upColor = upColor || 'rgba(255,0,0,0.5)'; + + if (hideIfUp === true && pointer.isUp === true) + { + return; + } + + this.start(pointer.x, pointer.y - 100, color); + this.context.beginPath(); + this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2); + + if (pointer.active) + { + this.context.fillStyle = downColor; + } + else + { + this.context.fillStyle = upColor; + } + + this.context.fill(); + this.context.closePath(); + + // Render the points + this.context.beginPath(); + this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y); + this.context.lineTo(pointer.position.x, pointer.position.y); + this.context.lineWidth = 2; + this.context.stroke(); + this.context.closePath(); + + // Render the text + this.line('ID: ' + pointer.id + " Active: " + pointer.active); + this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY); + this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y + " In: " + pointer.withinGame); + this.line('Duration: ' + pointer.duration + " ms"); + this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp); + this.stop(); + + }, + + /** + * Render Sprite Input Debug information. + * + * @method Phaser.Utils.Debug#spriteInputInfo + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInputInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')'); + this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1)); + this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0)); + this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0)); + this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut()); + this.stop(); + + }, + + /** + * Renders Phaser.Key object information. + * + * @method Phaser.Utils.Debug#key + * @param {Phaser.Key} key - The Key to render the information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + key: function (key, x, y, color) { + + this.start(x, y, color, 150); + + this.line('Key:', key.keyCode, 'isDown:', key.isDown); + this.line('justDown:', key.justDown, 'justUp:', key.justUp); + this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0)); + + this.stop(); + + }, + + /** + * Render debug information about the Input object. + * + * @method Phaser.Utils.Debug#inputInfo + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + inputInfo: function (x, y, color) { + + this.start(x, y, color); + this.line('Input'); + this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y); + this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY); + this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1)); + this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY); + this.stop(); + + }, + + /** + * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! + * + * @method Phaser.Utils.Debug#spriteBounds + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + spriteBounds: function (sprite, color, filled) { + + var bounds = sprite.getBounds(); + + bounds.x += this.game.camera.x; + bounds.y += this.game.camera.y; + + this.rectangle(bounds, color, filled); + + }, + + /** + * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it + * + * @method Phaser.Utils.Debug#ropeSegments + * @param {Phaser.Rope} rope - The rope to display the segments of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + ropeSegments: function (rope, color, filled) { + + var segments = rope.segments; + + var self = this; + + segments.forEach(function(segment) { + self.rectangle(segment, color, filled); + }, this); + + }, + + /** + * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. + * + * @method Phaser.Utils.Debug#spriteInfo + * @param {Phaser.Sprite} sprite - The Sprite to display the information of. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + + this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y); + this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1)); + this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1)); + this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera); + this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1)); + + this.stop(); + + }, + + /** + * Renders the sprite coordinates in local, positional and world space. + * + * @method Phaser.Utils.Debug#spriteCoords + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteCoords: function (sprite, x, y, color) { + + this.start(x, y, color, 100); + + if (sprite.name) + { + this.line(sprite.name); + } + + this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2)); + this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2)); + this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2)); + + this.stop(); + + }, + + /** + * Renders Line information in the given color. + * + * @method Phaser.Utils.Debug#lineInfo + * @param {Phaser.Line} line - The Line to display the data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + lineInfo: function (line, x, y, color) { + + this.start(x, y, color, 80); + this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2)); + this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2)); + this.line('length:', line.length.toFixed(2), 'angle:', line.angle); + this.stop(); + + }, + + /** + * Renders a single pixel at the given size. + * + * @method Phaser.Utils.Debug#pixel + * @param {number} x - X position of the pixel to be rendered. + * @param {number} y - Y position of the pixel to be rendered. + * @param {string} [color] - Color of the pixel (format is css color string). + * @param {number} [size=2] - The 'size' to render the pixel at. + */ + pixel: function (x, y, color, size) { + + size = size || 2; + + this.start(); + this.context.fillStyle = color; + this.context.fillRect(x, y, size, size); + this.stop(); + + }, + + /** + * Renders a Phaser geometry object including Rectangle, Circle, Ellipse, Point or Line. + * + * @method Phaser.Utils.Debug#geom + * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Ellipse|Phaser.Point|Phaser.Line} object - The geometry object to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) + * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle,3 = Point, 4 = Line and 5 = Ellipse. + */ + geom: function (object, color, filled, forceType) { + + if (filled === undefined) { filled = true; } + if (forceType === undefined) { forceType = 0; } + + color = color || 'rgba(0,255,0,0.4)'; + + this.start(); + + this.context.fillStyle = color; + this.context.strokeStyle = color; + this.context.lineWidth = this.lineWidth; + + if (object instanceof Phaser.Rectangle || forceType === 1) + { + if (filled) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + } + else if (object instanceof Phaser.Circle || forceType === 2) + { + this.context.beginPath(); + this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + else if (object instanceof Phaser.Point || forceType === 3) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4); + } + else if (object instanceof Phaser.Line || forceType === 4) + { + this.context.beginPath(); + this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y); + this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y); + this.context.closePath(); + this.context.stroke(); + } + else if (object instanceof Phaser.Ellipse || forceType === 5) + { + this.context.beginPath(); + this.context.ellipse(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width/2, object.height/2, 0,2 * Math.PI,false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + + this.stop(); + + }, + + /** + * Renders a Rectangle. + * + * @method Phaser.Utils.Debug#rectangle + * @param {Phaser.Rectangle|object} object - The rectangle to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as filled (default, true) or a stroked (false) + */ + rectangle: function (object, color, filled) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0, 255, 0, 0.4)'; + + this.start(); + + if (filled) + { + this.context.fillStyle = color; + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.lineWidth = this.lineWidth; + this.context.strokeStyle = color; + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + + this.stop(); + + }, + + /** + * Render a string of text. + * + * @method Phaser.Utils.Debug#text + * @param {string} text - The line of text to draw. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {string} [font] - The font of text to draw. + */ + text: function (text, x, y, color, font) { + + color = color || 'rgb(255,255,255)'; + font = font || '16px Courier'; + + this.start(); + this.context.font = font; + + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(text, x + 1, y + 1); + } + + this.context.fillStyle = color; + this.context.fillText(text, x, y); + + this.stop(); + + }, + + /** + * Visually renders a QuadTree to the display. + * + * @method Phaser.Utils.Debug#quadTree + * @param {Phaser.QuadTree} quadtree - The quadtree to render. + * @param {string} color - The color of the lines in the quadtree. + */ + quadTree: function (quadtree, color) { + + color = color || 'rgba(255,0,0,0.3)'; + + this.start(); + + var bounds = quadtree.bounds; + + if (quadtree.nodes.length === 0) + { + this.context.strokeStyle = color; + this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height); + this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier'); + + this.context.strokeStyle = 'rgb(0,255,0)'; + + for (var i = 0; i < quadtree.objects.length; i++) + { + this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height); + } + } + else + { + for (var i = 0; i < quadtree.nodes.length; i++) + { + this.quadTree(quadtree.nodes[i]); + } + } + + this.stop(); + + }, + + /** + * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. + * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. + * To display a P2 Physics body you should enable debug mode on the body when creating it. + * + * @method Phaser.Utils.Debug#body + * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false) + */ + body: function (sprite, color, filled) { + + if (sprite.body) + { + this.start(); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled, this.lineWidth); + } + else if (sprite.body.type === Phaser.Physics.NINJA) + { + Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color); + } + + this.stop(); + } + + }, + + /** + * Render a Sprites Physic Body information. + * + * @method Phaser.Utils.Debug#bodyInfo + * @param {Phaser.Sprite} sprite - The sprite to be rendered. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + bodyInfo: function (sprite, x, y, color) { + + if (sprite.body) + { + this.start(x, y, color, 210); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + this.game.physics.box2d.renderBodyInfo(this, sprite.body); + } + + this.stop(); + } + + }, + + /** + * Renders 'debug draw' data for the Box2D world if it exists. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by + * the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dWorld + */ + box2dWorld: function () { + + this.start(); + + this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0); + this.game.physics.box2d.renderDebugDraw(this.context); + + this.stop(); + + }, + + /** + * Renders 'debug draw' data for the given Box2D body. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dBody + * @param {Phaser.Physics.Box2D.Body} body - The body to be rendered. + * @param {string} [color='rgb(0,255,0)'] - Color of the rendering (format is css color string). + */ + box2dBody: function (body, color) { + + this.start(); + Phaser.Physics.Box2D.renderBody(this.context, body, color); + this.stop(); + + }, + + /** + * Call this function from the Dev Tools console. + * + * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. + * + * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) + * + * @method Phaser.Utils.Debug#displayList + * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World. + */ + displayList: function (displayObject) { + + if (displayObject === undefined) { displayObject = this.game.world; } + + if (displayObject.hasOwnProperty('renderOrderID')) + { + console.log('[' + displayObject.renderOrderID + ']', displayObject); + } + else + { + console.log('[]', displayObject); + } + + if (displayObject.children && displayObject.children.length > 0) + { + for (var i = 0; i < displayObject.children.length; i++) + { + this.game.debug.displayList(displayObject.children[i]); + } + } + + }, + + /** + * Prints a description of the {@link Phaser.Game#renderer renderer} and render session. + * + * @method Phaser.Utils.Debug#renderer + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + renderer: function (x, y, color) { + + var r = this.game.renderer; + var s = r.renderSession; + + this.start(x, y, color); + + this.line((r.gl ? 'WebGL' : 'Canvas') + ' Renderer (' + r.width + ' x ' + r.height + ')'); + this.line('autoResize: ' + r.autoResize); + this.line('clearBeforeRender: ' + r.clearBeforeRender); + this.line('resolution: ' + r.resolution); + this.line('transparent: ' + r.transparent); + this.line('renderSession:'); + + if (r.gl) + { + this.line(' currentBatchedTextures: ('+ r.currentBatchedTextures.length + ')'); + + for (var i = 0; i < r.currentBatchedTextures.length; i++) + { + this.line(' ' + r.currentBatchedTextures[i]); + } + + this.line(' drawCount: ' + s.drawCount); + this.line(' maxTextures: ' + r.maxTextures); + this.line(' maxTextureSize: ' + r.maxTextureSize); + this.line(' maxTextureAvailableSpace: ' + s.maxTextureAvailableSpace); + this.line(' roundPixels: ' + s.roundPixels); + } + else + { + this.line(' roundPixels: ' + s.roundPixels); + this.line(' scaleMode: ' + (s.scaleMode === 0 ? 'LINEAR' : (s.scaleMode === 1 ? 'NEAREST' : s.scaleMode))); + } + + this.stop(); + + }, + + canvasPool: function (x, y, color, columnWidth) { + var pool = Phaser.CanvasPool; + + this.start(x, y, color, columnWidth || 100); + this.line('Canvas Pool'); + this.line('Used:', pool.getTotal()); + this.line('Free:', pool.getFree()); + this.line('Total:', pool.length); + this.stop(); + }, + + /** + * Render each physics {@link #body} in a group. + * + * @method Phaser.Utils.Debug#physicsGroup + * @param {Phaser.Group} group - A group containing physics-enabled sprites. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false). + * @param {boolean} [checkExists=false] Render only children with `exists=true`. + */ + physicsGroup: function (group, color, filled, checkExists) { + + group.forEach(this.body, this, checkExists, color, filled); + + }, + + /** + * Prints Phaser {@link Phaser.VERSION version}, {@link Phaser.Game.#renderType rendering mode}, and {@link Phaser.Device#webAudio device audio support}. + * + * @method Phaser.Utils.Debug#phaser + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + phaser: function (x, y, color) { + + this.text('Phaser v' + Phaser.VERSION + ' ' + + (this.game.renderType === Phaser.WEBGL ? 'WebGL' : 'Canvas') + ' ' + + (this.game.device.webAudio ? 'WebAudio' : 'HTML Audio'), + x, y, color, this.font); + + }, + + /** + * Prints game/canvas dimensions and {@link Phaser.ScaleManager game scale} settings. + * + * @method Phaser.Utils.Debug#scale + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + scale: function (x, y, color) { + + this.start(x, y, color); + + var scale = this.game.scale; + var factor = scale.scaleFactorInversed; + var bounds = scale._parentBounds; + var x = ' x '; + + this.line('Game: ' + this.game.width + x + this.game.height); + this.line('Canvas: ' + scale.width + x + scale.height + + ' (' + factor.x.toFixed(2) + x + factor.y.toFixed(2) + ')' + + ' [' + scale.aspectRatio.toFixed(2) + ']'); + this.line('Mode: ' + Phaser.ScaleManager.MODES[scale.currentScaleMode] + + (scale.currentScaleMode === Phaser.ScaleManager.USER_SCALE ? + (' (' + scale._userScaleFactor.x + x + scale._userScaleFactor.y + ')') : + '')); + this.line('Parent: ' + (scale.parentIsWindow ? 'window' : scale.parentNode) + + (bounds.empty ? '' : (' (' + bounds.width + x + bounds.height + ')'))); + this.line('Screen: ' + scale.classifyOrientation(scale.screenOrientation) + + (scale.incorrectOrientation ? ' (incorrect)' : '')); + + this.stop(); + + }, + + /** + * Prints the progress of a {@link Phaser.Loader}. + * + * Typically you would call this within a {@link State#loadRender} callback and pass `game.load` ({@link Phaser.Game#load}). + * + * You can enable {@link Phaser.Loader#resetLocked} to temporarily hold the loader in its 'complete' state. + * Just remember to disable it before restarting the loader (such as when changing states). + * + * @method Phaser.Utils.Debug#loader + * @param {Phaser.Loader} loader - The loader. Usually `game.load` ({@link Phaser.Game#load}). + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + loader: function (loader, x, y, color) { + + var pad = Phaser.Utils.pad; + + this.start(x, y, color); + + if (loader.hasLoaded) + { + this.line('Complete' + (loader.resetLocked ? ' [locked]' : '')); + } + else if (loader.isLoading) + { + this.line('Loading'); + } + else + { + this.line('Not started'); + } + + if (!loader.hasLoaded || loader.resetLocked) + { + this.line('Progress: ' + (pad(loader.progress, 3) + '%')); + this.line('Files: ' + loader._loadedFileCount + ' of ' + + loader._totalFileCount); + this.line('Packs: ' + loader._loadedPackCount + ' of ' + + loader._loadedPackCount); + } + + this.stop(); + + }, + + /** + * Destroy this object. + * + * @method Phaser.Utils.Debug#destroy + */ + destroy: function () { + + Phaser.CanvasPool.remove(this); + + } + +}; + +Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DOM utility class. +* +* Provides a useful Window and Element functions as well as cross-browser compatibility buffer. +* +* Some code originally derived from {@link https://github.com/ryanve/verge verge}. +* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. +* +* @class Phaser.DOM +* @static +*/ +Phaser.DOM = { + + /** + * Get the [absolute] position of the element relative to the Document. + * + * The value may vary slightly as the page is scrolled due to rounding errors. + * + * @method Phaser.DOM.getOffset + * @param {DOMElement} element - The targeted element that we want to retrieve the offset. + * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. + * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. + */ + getOffset: function (element, point) { + + point = point || new Phaser.Point(); + + var box = element.getBoundingClientRect(); + + var scrollTop = Phaser.DOM.scrollY; + var scrollLeft = Phaser.DOM.scrollX; + var clientTop = document.documentElement.clientTop; + var clientLeft = document.documentElement.clientLeft; + + point.x = box.left + scrollLeft - clientLeft; + point.y = box.top + scrollTop - clientTop; + + return point; + + }, + + /** + * A cross-browser element.getBoundingClientRect method with optional cushion. + * + * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. + * Its properties match the native rectangle. + * The cushion parameter is an amount of pixels (+/-) to cushion the element. + * It adjusts the measurements such that it is possible to detect when an element is near the viewport. + * + * @method Phaser.DOM.getBounds + * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for. + * @param {number} [cushion] - A +/- pixel adjustment amount. + * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. + */ + getBounds: function (element, cushion) { + + if (cushion === undefined) { cushion = 0; } + + element = element && !element.nodeType ? element[0] : element; + + if (!element || element.nodeType !== 1) + { + return false; + } + else + { + return this.calibrate(element.getBoundingClientRect(), cushion); + } + + }, + + /** + * Calibrates element coordinates for `inLayoutViewport` checks. + * + * @method Phaser.DOM.calibrate + * @private + * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}` + * @param {number} [cushion] - A value to adjust the coordinates by. + * @return {object} The calibrated element coordinates + */ + calibrate: function (coords, cushion) { + + cushion = +cushion || 0; + + var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 }; + + output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion); + output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion); + + return output; + + }, + + /** + * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) + * + * @method Phaser.DOM.getAspectRatio + * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. + * @return {number} The aspect ratio. + */ + getAspectRatio: function (object) { + + object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object; + + var w = object['width']; + var h = object['height']; + + if (typeof w === 'function') + { + w = w.call(object); + } + + if (typeof h === 'function') + { + h = h.call(object); + } + + return w / h; + + }, + + /** + * Tests if the given DOM element is within the Layout viewport. + * + * The optional cushion parameter allows you to specify a distance. + * + * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. + * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. + * + * @method Phaser.DOM.inLayoutViewport + * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas. + * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport. + * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it. + */ + inLayoutViewport: function (element, cushion) { + + var r = this.getBounds(element, cushion); + + return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height; + + }, + + /** + * Returns the device screen orientation. + * + * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. + * + * Order of resolving: + * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. + * - Screen size ratio check - If fallback is 'screen', suited for desktops. + * - Viewport size ratio check - If fallback is 'viewport', suited for mobile. + * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. + * - Media query + * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..) + * + * See + * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) + * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) + * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx + * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries + * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation + * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation + * + * @method Phaser.DOM.getScreenOrientation + * @protected + * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'. + */ + getScreenOrientation: function (primaryFallback) { + + var screen = window.screen; + var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; + + if (orientation && typeof orientation.type === 'string') + { + // Screen Orientation API specification + return orientation.type; + } + else if (typeof orientation === 'string') + { + // moz/ms-orientation are strings + return orientation; + } + + var PORTRAIT = 'portrait-primary'; + var LANDSCAPE = 'landscape-primary'; + + if (primaryFallback === 'screen') + { + return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'viewport') + { + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number') + { + // This may change by device based on "natural" orientation. + return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE; + } + else if (window.matchMedia) + { + if (window.matchMedia("(orientation: portrait)").matches) + { + return PORTRAIT; + } + else if (window.matchMedia("(orientation: landscape)").matches) + { + return LANDSCAPE; + } + } + + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + + }, + + /** + * The bounds of the Visual viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one} + * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers. + * + * Supported mobile: + * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} x - Scroll, left offset - eg. "scrollX" + * @property {number} y - Scroll, top offset - eg. "scrollY" + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + visualBounds: new Phaser.Rectangle(), + + /** + * The bounds of the Layout viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two}; + * but honoring the constraints as specified applicable viewport meta-tag. + * + * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see + * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}). + * + * This is _not_ representative of the Visual bounds: in particular the non-primary axis will + * generally be significantly larger than the screen height on mobile devices when running with a + * constrained viewport. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + layoutBounds: new Phaser.Rectangle(), + + /** + * The size of the document / Layout viewport. + * + * This incorrectly reports the dimensions in IE. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Document width in pixels. + * @property {number} height - Document height in pixels. + * @readonly + */ + documentBounds: new Phaser.Rectangle() + +}; + +Phaser.Device.whenReady(function (device) { + + // All target browsers should support page[XY]Offset. + var scrollX = window && ('pageXOffset' in window) ? + function () { return window.pageXOffset; } : + function () { return document.documentElement.scrollLeft; }; + + var scrollY = window && ('pageYOffset' in window) ? + function () { return window.pageYOffset; } : + function () { return document.documentElement.scrollTop; }; + + /** + * A cross-browser window.scrollX. + * + * @name Phaser.DOM.scrollX + * @property {number} scrollX + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollX", { + get: scrollX + }); + + /** + * A cross-browser window.scrollY. + * + * @name Phaser.DOM.scrollY + * @property {number} scrollY + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollY", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "x", { + get: scrollX + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "y", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "y", { + value: 0 + }); + + var treatAsDesktop = device.desktop && + (document.documentElement.clientWidth <= window.innerWidth) && + (document.documentElement.clientHeight <= window.innerHeight); + + // Desktop browsers align the layout viewport with the visual viewport. + // This differs from mobile browsers with their zooming design. + // Ref. http://quirksmode.org/mobile/tableViewport.html + if (treatAsDesktop) + { + + // PST- When scrollbars are not included this causes upstream issues in ScaleManager. + // So reverted to the old "include scrollbars." + var clientWidth = function () { + return Math.max(window.innerWidth, document.documentElement.clientWidth); + }; + var clientHeight = function () { + return Math.max(window.innerHeight, document.documentElement.clientHeight); + }; + + // Interested in area sans-scrollbar + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: clientHeight + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + get: clientHeight + }); + + } else { + + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: function () { + return window.innerWidth; + } + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: function () { + return window.innerHeight; + } + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + + get: function () { + var a = document.documentElement.clientWidth; + var b = window.innerWidth; + + return a < b ? b : a; // max + } + + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + + get: function () { + var a = document.documentElement.clientHeight; + var b = window.innerHeight; + + return a < b ? b : a; // max + } + + }); + + } + + // For Phaser.DOM.documentBounds + // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html + + Object.defineProperty(Phaser.DOM.documentBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "y", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "width", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth); + } + + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "height", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight); + } + + }); + +}, null, true); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* ArraySet is a Set data structure (items must be unique within the set) that also maintains order. +* This allows specific items to be easily added or removed from the Set. +* +* Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. +* +* This used primarily by the Input subsystem. +* +* @class Phaser.ArraySet +* @constructor +* @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet. +*/ +Phaser.ArraySet = function (list) { + + /** + * Current cursor position as established by `first` and `next`. + * @property {integer} position + * @default + */ + this.position = 0; + + /** + * The backing array. + * @property {any[]} list + */ + this.list = list || []; + +}; + +Phaser.ArraySet.prototype = { + + /** + * Adds a new element to the end of the list. + * If the item already exists in the list it is not moved. + * + * @method Phaser.ArraySet#add + * @param {any} item - The element to add to this list. + * @return {any} The item that was added. + */ + add: function (item) { + + if (!this.exists(item)) + { + this.list.push(item); + } + + return item; + + }, + + /** + * Gets the index of the item in the list, or -1 if it isn't in the list. + * + * @method Phaser.ArraySet#getIndex + * @param {any} item - The element to get the list index for. + * @return {integer} The index of the item or -1 if not found. + */ + getIndex: function (item) { + + return this.list.indexOf(item); + + }, + + /** + * Gets an item from the set based on the property strictly equaling the value given. + * Returns null if not found. + * + * @method Phaser.ArraySet#getByKey + * @param {string} property - The property to check against the value. + * @param {any} value - The value to check if the property strictly equals. + * @return {any} The item that was found, or null if nothing matched. + */ + getByKey: function (property, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i][property] === value) + { + return this.list[i]; + } + } + + return null; + + }, + + /** + * Checks for the item within this list. + * + * @method Phaser.ArraySet#exists + * @param {any} item - The element to get the list index for. + * @return {boolean} True if the item is found in the list, otherwise false. + */ + exists: function (item) { + + return (this.list.indexOf(item) > -1); + + }, + + /** + * Removes all the items. + * + * @method Phaser.ArraySet#reset + */ + reset: function () { + + this.list.length = 0; + + }, + + /** + * Removes the given element from this list if it exists. + * + * @method Phaser.ArraySet#remove + * @param {any} item - The item to be removed from the list. + * @return {any} item - The item that was removed. + */ + remove: function (item) { + + var idx = this.list.indexOf(item); + + if (idx > -1) + { + this.list.splice(idx, 1); + return item; + } + + }, + + /** + * Sets the property `key` to the given value on all members of this list. + * + * @method Phaser.ArraySet#setAll + * @param {any} key - The property of the item to set. + * @param {any} value - The value to set the property to. + */ + setAll: function (key, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + this.list[i][key] = value; + } + } + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * + * If the `key` property is present it must be a function. + * The function is invoked using the item as the context. + * + * @method Phaser.ArraySet#callAll + * @param {string} key - The name of the property with the function to call. + * @param {...*} parameter - Additional parameters that will be passed to the callback. + */ + callAll: function (key) { + + var args = Array.prototype.slice.call(arguments, 1); + + var i = this.list.length; + + while (i--) + { + if (this.list[i] && this.list[i][key]) + { + this.list[i][key].apply(this.list[i], args); + } + } + + }, + + /** + * Removes every member from this ArraySet and optionally destroys it. + * + * @method Phaser.ArraySet#removeAll + * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set. + */ + removeAll: function (destroy) { + + if (destroy === undefined) { destroy = false; } + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + var item = this.remove(this.list[i]); + + if (destroy) + { + item.destroy(); + } + } + } + + this.position = 0; + this.list = []; + + } + +}; + +/** +* Number of items in the ArraySet. Same as `list.length`. +* +* @name Phaser.ArraySet#total +* @property {integer} total +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "total", { + + get: function () { + return this.list.length; + } + +}); + +/** +* Returns the first item and resets the cursor to the start. +* +* @name Phaser.ArraySet#first +* @property {any} first +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "first", { + + get: function () { + + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + + } + +}); + +/** +* Returns the the next item (based on the cursor) and advances the cursor. +* +* @name Phaser.ArraySet#next +* @property {any} next +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "next", { + + get: function () { + + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + + } + +}); + +Phaser.ArraySet.prototype.constructor = Phaser.ArraySet; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Utility functions for dealing with Arrays. +* +* @class Phaser.ArrayUtils +* @static +*/ +Phaser.ArrayUtils = { + + /** + * Fetch a random entry from the given array. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.getRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was selected. + */ + getRandomItem: function (objects, startIndex, length) { + + if (objects === null) { return null; } + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + + return objects[randomIndex] === undefined ? null : objects[randomIndex]; + + }, + + /** + * Removes a random object from the given array and returns it. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.removeRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was removed. + */ + removeRandomItem: function (objects, startIndex, length) { + + if (objects == null) { // undefined or null + return null; + } + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + if (randomIndex < objects.length) + { + var removed = objects.splice(randomIndex, 1); + return removed[0] === undefined ? null : removed[0]; + } + else + { + return null; + } + + }, + + /** + * Remove one or more items at the given index and reorder the array. + * + * The new array length will be `array.length - count`. + * + * This is an alternative to `array.splice(startIndex, count)`. + * + * @see https://github.com/mreinstein/remove-array-items + * @see https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ + * + * @method Phaser.ArrayUtils.remove + * @param {any[]} array + * @param {integer} startIndex + * @param {integer} [count=1] + * @return {any[]} The modified array. + */ + remove: function (array, startIndex, count) + { + var length = array.length; + + if (startIndex >= length || count === 0) { return; } + + if (count == null) { count = 1; } + + var newLength = length - count; + + for (var i = startIndex; i < newLength; ++i) + { + array[i] = array[i + count]; + } + + array.length = newLength; + }, + + /** + * A standard Fisher-Yates Array shuffle implementation which modifies the array in place. + * + * @method Phaser.ArrayUtils.shuffle + * @param {any[]} array - The array to shuffle. + * @return {any[]} The original array, now shuffled. + */ + shuffle: function (array) { + + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; + + }, + + /** + * Transposes the elements of the given matrix (array of arrays). + * + * @method Phaser.ArrayUtils.transposeMatrix + * @param {Array} array - The matrix to transpose. + * @return {Array} A new transposed matrix + */ + transposeMatrix: function (array) { + + var sourceRowCount = array.length; + var sourceColCount = array[0].length; + + var result = new Array(sourceColCount); + + for (var i = 0; i < sourceColCount; i++) + { + result[i] = new Array(sourceRowCount); + + for (var j = sourceRowCount - 1; j > -1; j--) + { + result[i][j] = array[j][i]; + } + } + + return result; + + }, + + /** + * Rotates the given matrix (array of arrays). + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @method Phaser.ArrayUtils.rotateMatrix + * @param {Array} matrix - The array to rotate; this matrix _may_ be altered. + * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). + * @return {Array} The rotated matrix. The source matrix should be discarded for the returned matrix. + */ + rotateMatrix: function (matrix, direction) { + + if (typeof direction !== 'string') + { + direction = ((direction % 360) + 360) % 360; + } + + if (direction === 90 || direction === -270 || direction === 'rotateLeft') + { + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + matrix = matrix.reverse(); + } + else if (direction === -90 || direction === 270 || direction === 'rotateRight') + { + matrix = matrix.reverse(); + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + } + else if (Math.abs(direction) === 180 || direction === 'rotate180') + { + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + matrix = matrix.reverse(); + } + + return matrix; + + }, + + /** + * Snaps a value to the nearest value in a sorted numeric array. + * The result will always be in the range `[first_value, last_value]`. + * + * @method Phaser.ArrayUtils.findClosest + * @param {number} value - The search value + * @param {number[]} arr - The input array which _must_ be sorted. + * @return {number} The nearest value found. + */ + findClosest: function (value, arr) { + + if (!arr.length) + { + return NaN; + } + else if (arr.length === 1 || value < arr[0]) + { + return arr[0]; + } + + var i = 1; + while (arr[i] < value) { + i++; + } + + var low = arr[i - 1]; + var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; + + return ((high - value) <= (value - low)) ? high : low; + + }, + + /** + * Moves the element from the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ F, A, B, C, D, E ]` + * + * See also Phaser.ArrayUtils.rotateLeft. + * + * @method Phaser.ArrayUtils.rotateRight + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The shifted value. + */ + rotateRight: function (array) { + + var s = array.pop(); + array.unshift(s); + + return s; + + }, + + /** + * Moves the element from the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ B, C, D, E, F, A ]` + * + * See also Phaser.ArrayUtils.rotateRight + * + * @method Phaser.ArrayUtils.rotateLeft + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The rotated value. + */ + rotateLeft: function (array) { + + var s = array.shift(); + array.push(s); + + return s; + + }, + + /** + * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]` (or `[0, start]`, if `end` is omitted). + * This is equivalent to `numberArrayStep(start, 1 + end, 1)`. + * + * When exactly one argument is passed, it's used as `end` and 0 is used as `start`. The length of the result is (1 + end). + * + * ##### Examples + * + * ```javascript + * numberArray(3); // -> [0, 1, 2, 3] + * numberArray(0, 3); // -> [0, 1, 2, 3] + * numberArray(1, 3); // -> [1, 2, 3] + * ``` + * + * @method Phaser.ArrayUtils.numberArray + * @param {number} start - The minimum value the array starts with. + * @param {number} [end] - The maximum value the array contains. + * @return {number[]} The array of number values. + */ + numberArray: function (start, end) { + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + var result = []; + + for (var i = start; i <= end; i++) + { + result.push(i); + } + + return result; + + }, + + /** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @method Phaser.ArrayUtils.numberArrayStep + * @param {number} start - The start of the range. + * @param {number} [end] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * @returns {Array} Returns the new array of numbers. + * @example + * Phaser.ArrayUtils.numberArrayStep(4); + * // => [0, 1, 2, 3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * Phaser.ArrayUtils.numberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * Phaser.ArrayUtils.numberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * Phaser.ArrayUtils.numberArrayStep(0); + * // => [] + */ + numberArrayStep: function (start, end, step) { + + if (start === undefined || start === null) { start = 0; } + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + if (step === undefined) { step = 1; } + + var result = []; + var total = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0); + + for (var i = 0; i < total; i++) + { + result.push(start); + start += step; + } + + return result; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A basic Linked List data structure. +* +* This implementation _modifies_ the `prev` and `next` properties of each item added: +* - The `prev` and `next` properties must be writable and should not be used for any other purpose. +* - Items _cannot_ be added to multiple LinkedLists at the same time. +* - Only objects can be added. +* +* @class Phaser.LinkedList +* @constructor +*/ +Phaser.LinkedList = function () { + + /** + * Next element in the list. + * @property {object} next + * @default + */ + this.next = null; + + /** + * Previous element in the list. + * @property {object} prev + * @default + */ + this.prev = null; + + /** + * First element in the list. + * @property {object} first + * @default + */ + this.first = null; + + /** + * Last element in the list. + * @property {object} last + * @default + */ + this.last = null; + + /** + * Number of elements in the list. + * @property {integer} total + * @default + */ + this.total = 0; + +}; + +Phaser.LinkedList.prototype = { + + /** + * Adds a new element to this linked list. + * + * @method Phaser.LinkedList#add + * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. + * @return {object} The item that was added. + */ + add: function (item) { + + // If the list is empty + if (this.total === 0 && this.first === null && this.last === null) + { + this.first = item; + this.last = item; + this.next = item; + item.prev = this; + this.total++; + return item; + } + + // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list) + this.last.next = item; + + item.prev = this.last; + + this.last = item; + + this.total++; + + return item; + + }, + + /** + * Resets the first, last, next and previous node pointers in this list. + * + * @method Phaser.LinkedList#reset + */ + reset: function () { + + this.first = null; + this.last = null; + this.next = null; + this.prev = null; + this.total = 0; + + }, + + /** + * Removes the given element from this linked list if it exists. + * + * @method Phaser.LinkedList#remove + * @param {object} item - The item to be removed from the list. + */ + remove: function (item) { + + if (this.total === 1) + { + this.reset(); + item.next = item.prev = null; + return; + } + + if (item === this.first) + { + // It was 'first', make 'first' point to first.next + this.first = this.first.next; + } + else if (item === this.last) + { + // It was 'last', make 'last' point to last.prev + this.last = this.last.prev; + } + + if (item.prev) + { + // make item.prev.next point to childs.next instead of item + item.prev.next = item.next; + } + + if (item.next) + { + // make item.next.prev point to item.prev instead of item + item.next.prev = item.prev; + } + + item.next = item.prev = null; + + if (this.first === null ) + { + this.last = null; + } + + this.total--; + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * The function must exist on the member. + * + * @method Phaser.LinkedList#callAll + * @param {function} callback - The function to call. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content +* quickly and easily, without the need for any external files. You can create textures for sprites and in +* coming releases we'll add dynamic sound effect generation support as well (like sfxr). +* +* Access this via `Game.create` (`this.game.create` from within a State object). +* +* @class Phaser.Create +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Create = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.ctx = null; + + /** + * @property {array} palettes - A range of 16 color palettes for use with sprite generation. + */ + this.palettes = [ + { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' }, + { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' }, + { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' } + ]; + +}; + +/** +* A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_ARNE = 0; + +/** +* A 16 color JMP inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JMP = 1; + +/** +* A 16 color CGA inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_CGA = 2; + +/** +* A 16 color C64 inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_C64 = 3; + +/** +* A 16 color palette inspired by Japanese computers like the MSX. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JAPANESE_MACHINE = 4; + +Phaser.Create.prototype = { + + /** + * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite. + * + * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images + * rather than Phaser.Graphics objects, which are expensive to render and limited in scope. + * + * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts. + * + * For example: + * + * `var data = [ + * ' 333 ', + * ' 777 ', + * 'E333E', + * ' 333 ', + * ' 3 3 ' + * ];` + * + * `game.create.texture('bob', data);` + * + * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it + * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');` + * + * Use {@link Phaser.Loader#imageFromTexture} to preload an image of the same. + * + * @method Phaser.Create#texture + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {array} data - An array of pixel data. + * @param {integer} [pixelWidth=8] - The width of each pixel. + * @param {integer} [pixelHeight=8] - The height of each pixel. + * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + texture: function (key, data, pixelWidth, pixelHeight, palette, generateTexture, callback, callbackContext) { + + if (pixelWidth === undefined) { pixelWidth = 8; } + if (pixelHeight === undefined) { pixelHeight = pixelWidth; } + if (palette === undefined) { palette = 0; } + if (generateTexture === undefined) { generateTexture = true; } + + var w = data[0].length * pixelWidth; + var h = data.length * pixelHeight; + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(w, h); + this.bmd.clear(); + + // Draw it + for (var y = 0; y < data.length; y++) + { + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var d = row[x]; + + if (d !== '.' && d !== ' ') + { + this.ctx.fillStyle = this.palettes[palette][d]; + this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); + } + } + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Creates a grid texture based on the given dimensions. + * + * Use {@link Phaser.Loader#imageFromGrid} to preload an image of the same. + * + * @method Phaser.Create#grid + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {integer} width - The width of the grid in pixels. + * @param {integer} height - The height of the grid in pixels. + * @param {integer} cellWidth - The width of the grid cells in pixels. + * @param {integer} cellHeight - The height of the grid cells in pixels. + * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + grid: function (key, width, height, cellWidth, cellHeight, color, generateTexture, callback, callbackContext) { + + if (generateTexture === undefined) { generateTexture = true; } + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(width, height); + + this.ctx.fillStyle = color; + + for (var y = 0; y < height; y += cellHeight) + { + this.ctx.fillRect(0, y, width, 1); + } + + for (var x = 0; x < width; x += cellWidth) + { + this.ctx.fillRect(x, 0, 1, height); + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Copies the contents of {@link bmd Create's canvas} to the given BitmapData object, or a new BitmapData object. + * + * @param {Phaser.BitmapData} [dest] - The BitmapData receiving the copied image. + * @param {number} [x=0] - The x coordinate to translate to before drawing. + * @param {number} [y=0] - The y coordinate to translate to before drawing. + * @param {number} [width] - The new width of the Sprite being copied. + * @param {number} [height] - The new height of the Sprite being copied. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} - The `dest` argument (if passed), or a new BitmapData object + */ + copy: function (dest, x, y, width, height, blendMode, roundPx) { + + if (dest == null) { dest = this.game.make.bitmapData(); } + + dest.resize(this.bmd.width, this.bmd.height); + + return dest.draw(this.bmd, x, y, width, height, blendMode, roundPx); + + } + +}; + +Phaser.Create.prototype.constructor = Phaser.Create; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers +* to provide for game object positioning in a responsive manner. +* +* @class Phaser.FlexGrid +* @constructor +* @param {Phaser.ScaleManager} manager - The ScaleManager. +* @param {number} width - The width of the game. +* @param {number} height - The height of the game. +*/ +Phaser.FlexGrid = function (manager, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = manager.game; + + /** + * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager. + */ + this.manager = manager; + + // The perfect dimensions on which everything else is based + this.width = width; + this.height = height; + + this.boundsCustom = new Phaser.Rectangle(0, 0, width, height); + this.boundsFluid = new Phaser.Rectangle(0, 0, width, height); + this.boundsFull = new Phaser.Rectangle(0, 0, width, height); + this.boundsNone = new Phaser.Rectangle(0, 0, width, height); + + /** + * @property {Phaser.Point} position - + * @readonly + */ + this.positionCustom = new Phaser.Point(0, 0); + this.positionFluid = new Phaser.Point(0, 0); + this.positionFull = new Phaser.Point(0, 0); + this.positionNone = new Phaser.Point(0, 0); + + /** + * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. + * @readonly + */ + this.scaleCustom = new Phaser.Point(1, 1); + this.scaleFluid = new Phaser.Point(1, 1); + this.scaleFluidInversed = new Phaser.Point(1, 1); + this.scaleFull = new Phaser.Point(1, 1); + this.scaleNone = new Phaser.Point(1, 1); + + this.customWidth = 0; + this.customHeight = 0; + this.customOffsetX = 0; + this.customOffsetY = 0; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.multiplier = 0; + + this.layers = []; + +}; + +Phaser.FlexGrid.prototype = { + + /** + * Sets the core game size. This resets the w/h parameters and bounds. + * + * @method Phaser.FlexGrid#setSize + * @param {number} width - The new dimensions. + * @param {number} height - The new dimensions. + */ + setSize: function (width, height) { + + // These are locked and don't change until setSize is called again + this.width = width; + this.height = height; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.scaleNone = new Phaser.Point(1, 1); + + this.boundsNone.width = this.width; + this.boundsNone.height = this.height; + + this.refresh(); + + }, + + // Need ability to create your own layers with custom scaling, etc. + + /** + * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createCustomLayer + * @param {number} width - Width of this layer in pixels. + * @param {number} height - Height of this layer in pixels. + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createCustomLayer: function (width, height, children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + this.customWidth = width; + this.customHeight = height; + + this.boundsCustom.width = width; + this.boundsCustom.height = height; + + var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createFluidLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFluidLayer: function (children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios. + * + * @method Phaser.FlexGrid#createFullLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFullLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled. + * + * @method Phaser.FlexGrid#createFixedLayer + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFixedLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * Resets the layer children references + * + * @method Phaser.FlexGrid#reset + */ + reset: function () { + + var i = this.layers.length; + + while (i--) + { + if (!this.layers[i].persist) + { + // Remove references to this class + this.layers[i].position = null; + this.layers[i].scale = null; + this.layers.slice(i, 1); + } + } + + }, + + /** + * Called when the game container changes dimensions. + * + * @method Phaser.FlexGrid#onResize + * @param {number} width - The new width of the game container. + * @param {number} height - The new height of the game container. + */ + onResize: function (width, height) { + + this.ratioH = width / height; + this.ratioV = height / width; + + this.refresh(width, height); + + }, + + /** + * Updates all internal vars such as the bounds and scale values. + * + * @method Phaser.FlexGrid#refresh + */ + refresh: function () { + + this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width)); + + this.boundsFluid.width = Math.round(this.width * this.multiplier); + this.boundsFluid.height = Math.round(this.height * this.multiplier); + + this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height); + this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height); + + this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height); + + this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x); + this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y); + + this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + + this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y); + this.positionNone.set(this.boundsNone.x, this.boundsNone.y); + + }, + + /** + * Fits a sprites width to the bounds. + * + * @method Phaser.FlexGrid#fitSprite + * @param {Phaser.Sprite} sprite - The Sprite to fit. + */ + fitSprite: function (sprite) { + + this.manager.scaleSprite(sprite); + + sprite.x = this.manager.bounds.centerX; + sprite.y = this.manager.bounds.centerY; + + }, + + /** + * Call in the render function to output the bounds rects. + * + * @method Phaser.FlexGrid#debug + */ + debug: function () { + + // for (var i = 0; i < this.layers.length; i++) + // { + // this.layers[i].debug(); + // } + + // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16); + // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false); + + this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16); + this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false); + + // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16); + // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false); + + // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16); + // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false); + + } + +}; + +Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* A responsive grid layer. +* +* @class Phaser.FlexLayer +* @extends Phaser.Group +* @constructor +* @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer. +* @param {Phaser.Point} position - A reference to the Point object used for positioning. +* @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds. +* @param {Phaser.Point} scale - A reference to the Point object used for layer scaling. +*/ +Phaser.FlexLayer = function (manager, position, bounds, scale) { + + Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false); + + /** + * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager. + */ + this.manager = manager.manager; + + /** + * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer. + */ + this.grid = manager; + + /** + * Should the FlexLayer remain through a State swap? + * + * @type {boolean} + */ + this.persist = false; + + /** + * @property {Phaser.Point} position + */ + this.position = position; + + /** + * @property {Phaser.Rectangle} bounds + */ + this.bounds = bounds; + + /** + * @property {Phaser.Point} scale + */ + this.scale = scale; + + /** + * @property {Phaser.Point} topLeft + */ + this.topLeft = bounds.topLeft; + + /** + * @property {Phaser.Point} topMiddle + */ + this.topMiddle = new Phaser.Point(bounds.halfWidth, 0); + + /** + * @property {Phaser.Point} topRight + */ + this.topRight = bounds.topRight; + + /** + * @property {Phaser.Point} bottomLeft + */ + this.bottomLeft = bounds.bottomLeft; + + /** + * @property {Phaser.Point} bottomMiddle + */ + this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom); + + /** + * @property {Phaser.Point} bottomRight + */ + this.bottomRight = bounds.bottomRight; + +}; + +Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype); +Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer; + +/** + * Resize. + * + * @method Phaser.FlexLayer#resize + */ +Phaser.FlexLayer.prototype.resize = function () { +}; + +/** + * Debug. + * + * @method Phaser.FlexLayer#debug + */ +Phaser.FlexLayer.prototype.debug = function () { + + this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16); + this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false); + + this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9'); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. +* +* @class Phaser.Color +*/ +Phaser.Color = { + + /** + * Red (0xff0000) + * + * @type number + * @constant + * @default + */ + RED: 0xff0000, + + /** + * Orange (0xff9900) + * + * @type number + * @constant + * @default + */ + ORANGE: 0xff9900, + + /** + * Yellow (0xffff00) + * + * @type number + * @constant + * @default + */ + YELLOW: 0xffff00, + + /** + * Green (0x00ff00) + * + * @type number + * @constant + * @default + */ + GREEN: 0x00ff00, + + /** + * Aqua (0x00ffff) + * + * @type number + * @constant + * @default + */ + AQUA: 0x00ffff, + + /** + * Blue (0x0000ff) + * + * @type number + * @constant + * @default + */ + BLUE: 0x0000ff, + + /** + * Violet/purple (0xff00ff) + * + * @type number + * @constant + * @default + */ + VIOLET: 0xff00ff, + + /** + * White (0xffffff) + * + * @type number + * @constant + * @default + */ + WHITE: 0xffffff, + + /** + * Black (0x000000) + * + * @type number + * @constant + * @default + */ + BLACK: 0, + + /** + * Gray (0x666666) + * + * @type number + * @constant + * @default + */ + GRAY: 0x666666, + + /** + * Packs the r, g, b, a components into a single integer, for use with Int32Array. + * If device is little endian then ABGR order is used. Otherwise RGBA order is used. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.packPixel + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} The packed color as uint32 + */ + packPixel: function (r, g, b, a) { + + if (Phaser.Device.LITTLE_ENDIAN) + { + return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0; + } + else + { + return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0; + } + + }, + + /** + * Unpacks the r, g, b, a components into the specified color object, or a new + * object, for use with Int32Array. If little endian, then ABGR order is used when + * unpacking, otherwise, RGBA order is used. The resulting color object has the + * `r, g, b, a` properties which are unrelated to endianness. + * + * Note that the integer is assumed to be packed in the correct endianness. On little-endian + * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a + * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.unpackPixel + * @static + * @param {number} rgba - The integer, packed in endian order by packPixel. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + unpackPixel: function (rgba, out, hsl, hsv) { + + if (out === undefined || out === null) { out = Phaser.Color.createColor(); } + if (hsl === undefined || hsl === null) { hsl = false; } + if (hsv === undefined || hsv === null) { hsv = false; } + + if (Phaser.Device.LITTLE_ENDIAN) + { + out.a = ((rgba & 0xff000000) >>> 24); + out.b = ((rgba & 0x00ff0000) >>> 16); + out.g = ((rgba & 0x0000ff00) >>> 8); + out.r = ((rgba & 0x000000ff)); + } + else + { + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + } + + 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; + + }, + + /** + * A utility to convert an integer in 0xRRGGBBAA format to a color object. + * This does not rely on endianness. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.fromRGBA + * @static + * @param {number} rgba - An RGBA hex + * @param {object} [out] - The object to use, optional. + * @return {object} A color object. + */ + fromRGBA: function (rgba, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + + out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')'; + + return out; + + }, + + /** + * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.toRGBA + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toRGBA: function (r, g, b, a) { + + return (r << 24) | (g << 16) | (b << 8) | a; + + }, + + /** + * Converts RGBA components to a 32 bit integer in AABBGGRR format. + * + * @method Phaser.Color.toABGR + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toABGR: function (r, g, b, a) { + + return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; + + }, + + /** + * Converts a hex color value to an [R, G, B] array. + * + * @static + * @method Phaser.Color.hexToRGBArray + * @param {number} color - The color to convert to an RGB array. In the format 0xRRGGBB. + * @return {array} An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + */ + hexToRGBArray: function (color) { + + return [ + (color >> 16 & 0xFF) / 255, + (color >> 8 & 0xFF) / 255, + (color & 0xFF) / 255 + ]; + + }, + + /** + * Converts an RGB color array, in the format: [R, G, B], to a hex color value. + * + * @static + * @method Phaser.Color.RGBArrayToHex + * @param {array} rgb - An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + * @return {number} The color value, in the format 0xRRGGBB. + */ + RGBArrayToHex: function (rgb) { + + return ((rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255); + + }, + + /** + * Converts an RGB color value to HSL (hue, saturation and lightness). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSL + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. + */ + 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); + + // achromatic by default + out.h = 0; + out.s = 0; + out.l = (max + min) / 2; + + if (max !== min) + { + var d = max - min; + + out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min); + + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSL (hue, saturation and lightness) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSLtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} l - The lightness, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSLtoRGB: function (h, s, l, out) { + + if (!out) + { + out = Phaser.Color.createColor(l, l, l); + } + else + { + // achromatic by default + out.r = l; + out.g = l; + out.b = l; + } + + if (s !== 0) + { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3); + out.g = Phaser.Color.hueToColor(p, q, h); + out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3); + } + + // out.r = (out.r * 255 | 0); + // out.g = (out.g * 255 | 0); + // out.b = (out.b * 255 | 0); + + out.r = Math.floor((out.r * 255 | 0)); + out.g = Math.floor((out.g * 255 | 0)); + out.b = Math.floor((out.b * 255 | 0)); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts an RGB color value to HSV (hue, saturation and value). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSV + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and value set in the h, s and v properties. + */ + RGBtoHSV: function (r, g, b, out) { + + if (!out) + { + out = Phaser.Color.createColor(r, g, b, 255); + } + + r /= 255; + g /= 255; + b /= 255; + + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var d = max - min; + + // achromatic by default + out.h = 0; + out.s = max === 0 ? 0 : d / max; + out.v = max; + + if (max !== min) + { + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSVtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} v - The value, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSVtoRGB: function (h, s, v, out) { + + if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); } + + var r, g, b; + var i = Math.floor(h * 6); + var f = h * 6 - i; + var p = v * (1 - s); + var q = v * (1 - f * s); + var t = v * (1 - (1 - f) * s); + + switch (i % 6) + { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } + + out.r = Math.floor(r * 255); + out.g = Math.floor(g * 255); + out.b = Math.floor(b * 255); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.hueToColor + * @static + * @param {number} p + * @param {number} q + * @param {number} t + * @return {number} The color component value. + */ + hueToColor: function (p, q, t) { + + if (t < 0) + { + t += 1; + } + + if (t > 1) + { + t -= 1; + } + + if (t < 1 / 6) + { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) + { + return q; + } + + if (t < 2 / 3) + { + return p + (q - p) * (2 / 3 - t) * 6; + } + + return p; + + }, + + /** + * A utility function to create a lightweight 'color' object with the default components. + * Any components that are not specified will default to zero. + * + * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.createColor + * @static + * @param {number} [r=0] - The red color component, in the range 0 - 255. + * @param {number} [g=0] - The green color component, in the range 0 - 255. + * @param {number} [b=0] - The blue color component, in the range 0 - 255. + * @param {number} [a=1] - The alpha color component, in the range 0 - 1. + * @param {number} [h=0] - The hue, in the range 0 - 1. + * @param {number} [s=0] - The saturation, in the range 0 - 1. + * @param {number} [l=0] - The lightness, in the range 0 - 1. + * @param {number} [v=0] - The value, in the range 0 - 1. + * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. + */ + 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, color32: 0, rgba: '' }; + + return Phaser.Color.updateColor(out); + + }, + + /** + * Takes a color object and updates the rgba, color and color32 properties. + * + * @method Phaser.Color.updateColor + * @static + * @param {object} out - The color object to update. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + updateColor: function (out) { + + out.rgba = 'rgba(' + out.r.toFixed() + ',' + out.g.toFixed() + ',' + out.b.toFixed() + ',' + out.a.toString() + ')'; + out.color = Phaser.Color.getColor(out.r, out.g, out.b); + out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b); + + return out; + + }, + + /** + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor32 + * @static + * @param {number} a - The alpha color component, in the range 0 - 255. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + getColor32: function (a, r, g, b) { + + return a << 24 | r << 16 | g << 8 | b; + + }, + + /** + * Given 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xRRGGBB). + */ + getColor: function (r, g, b) { + + return r << 16 | g << 8 | b; + + }, + + /** + * Converts the given color values into a string. + * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + * + * @method Phaser.Color.RGBtoString + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255. + * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. + * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + */ + RGBtoString: function (r, g, b, a, prefix) { + + if (a === undefined) { a = 255; } + if (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); + } + + }, + + /** + * Converts a hex string into an integer color value. + * + * @method Phaser.Color.hexToRGB + * @static + * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. + * @return {number} The rgb color value in the format 0xAARRGGBB. + */ + hexToRGB: function (hex) { + + var rgb = Phaser.Color.hexToColor(hex); + + if (rgb) + { + return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b); + } + + }, + + /** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @method Phaser.Color.hexToColor + * @static + * @param {string} hex - The color string in a hex format. + * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + hexToColor: function (hex, out) { + + // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") + hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { + return r + r + g + g + b + b; + }); + + var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + + if (result) + { + var r = parseInt(result[1], 16); + var g = parseInt(result[2], 16); + var b = parseInt(result[3], 16); + + if (!out) + { + out = Phaser.Color.createColor(r, g, b); + } + else + { + out.r = r; + out.g = g; + out.b = b; + } + } + + return out; + + }, + + /** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @method Phaser.Color.webToColor + * @static + * @param {string} web - The color string in CSS 'web' format. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + webToColor: function (web, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web); + + if (result) + { + out.r = ~~Number(result[1]); + out.g = ~~Number(result[2]); + out.b = ~~Number(result[3]); + out.a = result[4] !== undefined ? Number(result[4]) : 1; + Phaser.Color.updateColor(out); + } + + return out; + + }, + + /** + * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. + * + * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). + * + * An alpha channel is _not_ supported when specifying a hex string. + * + * @method Phaser.Color.valueToColor + * @static + * @param {string|number} value - The color expressed as a recognized string format or a packed integer. + * @param {object} [out] - The object to use for the output. If not provided a new object will be created. + * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. + */ + valueToColor: function (value, out) { + + // The behavior is not consistent between hexToColor/webToColor on invalid input. + // This unifies both by returning a new object, but returning null may be better. + if (!out) + { + out = Phaser.Color.createColor(); + } + + if (typeof value === 'string') + { + if (value.indexOf('rgb') === 0) + { + return Phaser.Color.webToColor(value, out); + } + else + { + // `hexToColor` does not support alpha; match `createColor`. + out.a = 1; + return Phaser.Color.hexToColor(value, out); + } + } + else if (typeof value === 'number') + { + // `getRGB` does not take optional object to modify; + // alpha is also adjusted to match `createColor`. + var tempColor = Phaser.Color.getRGB(value); + out.r = tempColor.r; + out.g = tempColor.g; + out.b = tempColor.b; + out.a = tempColor.a / 255; + return out; + } + else + { + return out; + } + + }, + + /** + * Return a string containing a hex representation of the given color component. + * + * @method Phaser.Color.componentToHex + * @static + * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. + * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ + componentToHex: function (color) { + + var hex = color.toString(16); + + return (hex.length === 1) ? '0' + hex : hex; + + }, + + /** + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSVColorWheel + * @static + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSV color wheel. + */ + HSVColorWheel: function (s, v) { + + if (s === undefined) { s = 1.0; } + if (v === undefined) { v = 1.0; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v)); + } + + return colors; + + }, + + /** + * Get HSL color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSLColorWheel + * @static + * @param {number} [s=0.5] - The saturation, in the range 0 - 1. + * @param {number} [l=0.5] - The lightness, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSL color wheel. + */ + HSLColorWheel: function (s, l) { + + if (s === undefined) { s = 0.5; } + if (l === undefined) { l = 0.5; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l)); + } + + return colors; + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColor + * @static + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @param {number} [alpha] - The alpha of the returned color. + * @param {number} [colorSpace=0] - The color space to interpolate in. 0 = RGB, 1 = HSV. + * @returns {number} The interpolated color value. + */ + interpolateColor: function (color1, color2, steps, currentStep, alpha, colorSpace) { + + if (alpha === undefined) { alpha = 255; } + if (colorSpace === undefined) { colorSpace = 0; } + + var src1 = Phaser.Color.getRGB(color1); + var src2 = Phaser.Color.getRGB(color2); + + if (colorSpace === 0) + { + 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; + } + + if (colorSpace === 1) + { + var hsv1 = Phaser.Color.RGBtoHSV(src1.r, src1.g, src1.b); + var hsv2 = Phaser.Color.RGBtoHSV(src2.r, src2.g, src2.b); + var dh = hsv2.h - hsv1.h; + var h; + + if (hsv1.h > hsv2.h) + { + var h3 = hsv2.h; + hsv2.h = hsv1.h; + hsv1.h = h3; + dh = -dh; + currentStep = steps - currentStep; + } + + if (dh > 0.5) + { + hsv1.h = hsv1.h + 1; + h = (((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h) % 1; + } + + if (dh <= 0.5) + { + h = ((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h; + } + + var s = (((hsv2.s - hsv1.s) * currentStep) / steps) + hsv1.s; + var v = (((hsv2.v - hsv1.v) * currentStep) / steps) + hsv1.v; + + var rgb = Phaser.Color.HSVtoRGB(h, s, v, rgb); + var r = rgb.r; + var g = rgb.g; + var b = rgb.b; + } + + return Phaser.Color.getColor32(alpha, r, g, b); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColorWithRGB + * @static + * @param {number} color - The first color value. + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * @method Phaser.Color.interpolateRGB + * @static + * @param {number} r1 - The red color value, between 0 and 0xFF (255). + * @param {number} g1 - The green color value, between 0 and 0xFF (255). + * @param {number} b1 - The blue color value, between 0 and 0xFF (255). + * @param {number} r2 - The red color value, between 0 and 0xFF (255). + * @param {number} g2 - The green color value, between 0 and 0xFF (255). + * @param {number} b2 - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + + /** + * Calculates a linear (interpolation) value of two colors over t. + * + * This is a slightly simpler interface to {@link Phaser.Color.interpolateColor}. + * + * The arguments are similar to {@link Phaser.Math.linear}. + * + * @method Phaser.Color.linear + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linear: function (color1, color2, t) { + + return this.interpolateColor(color1, color2, 1, t); + + }, + + /** + * Calculates a linear (interpolation) value of an array of colors over t. + * + * The arguments are similar to {@link Phaser.Math.linearInterpolation}. + * + * This can be used as a {@link Phaser.TweenData#interpolationFunction}. + * + * @method Phaser.Color.linearInterpolation + * @param {number[]} colors - The input array of color values to interpolate between. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linearInterpolation: function (colors, t) { + + var k = Phaser.Math.linear(0, colors.length - 1, t); + var color1 = colors[ Math.floor(k) ]; + var color2 = colors[ Math.ceil(k)] ; + + return this.linear(color1, color2, k % 1); + + }, + + /** + * Returns a random color value between black and white + * Set the min value to start each channel from the given offset. + * Set the max value to restrict the maximum color used per channel. + * + * @method Phaser.Color.getRandomColor + * @static + * @param {number} [min=0] - The lowest value to use for the color. + * @param {number} [max=255] - The highest value to use for the color. + * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). + * @returns {number} 32-bit color value with alpha. + */ + getRandomColor: function (min, max, alpha) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + if (alpha === undefined) { alpha = 255; } + + // Sanity checks + 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); + + }, + + /** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exist in the given color (0xAARRGGBB) + * + * @method Phaser.Color.getRGB + * @static + * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). + * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. + */ + getRGB: function (color) { + + if (color > 16777215) + { + // The color value has an alpha component + return { + alpha: color >>> 24, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: color >>> 24, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + else + { + return { + alpha: 255, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: 255, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + + }, + + /** + * Returns a CSS friendly string value from the given color. + * + * @method Phaser.Color.getWebRGB + * @static + * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. + * @returns {string} A string in the format: 'rgba(r,g,b,a)' + */ + getWebRGB: function (color) { + + if (typeof color === 'object') + { + return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')'; + } + else + { + var rgb = Phaser.Color.getRGB(color); + return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')'; + } + + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. + * + * @method Phaser.Color.getAlpha + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlpha: function (color) { + return color >>> 24; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. + * + * @method Phaser.Color.getAlphaFloat + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlphaFloat: function (color) { + return (color >>> 24) / 255; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. + * + * @method Phaser.Color.getRed + * @static + * @param {number} color In the format 0xAARRGGBB. + * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). + */ + getRed: function (color) { + return color >> 16 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. + * + * @method Phaser.Color.getGreen + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). + */ + getGreen: function (color) { + return color >> 8 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. + * + * @method Phaser.Color.getBlue + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). + */ + getBlue: function (color) { + return color & 0xFF; + }, + + /** + * Blends the source color, ignoring the backdrop. + * + * @method Phaser.Color.blendNormal + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNormal: function (a) { + return a; + }, + + /** + * Selects the lighter of the backdrop and source colors. + * + * @method Phaser.Color.blendLighten + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLighten: function (a, b) { + return (b > a) ? b : a; + }, + + /** + * Selects the darker of the backdrop and source colors. + * + * @method Phaser.Color.blendDarken + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDarken: function (a, b) { + return (b > a) ? a : b; + }, + + /** + * Multiplies the backdrop and source color values. + * The result color is always at least as dark as either of the two constituent + * colors. Multiplying any color with black produces black; + * multiplying with white leaves the original color unchanged. + * + * @method Phaser.Color.blendMultiply + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendMultiply: function (a, b) { + return (a * b) / 255; + }, + + /** + * Takes the average of the source and backdrop colors. + * + * @method Phaser.Color.blendAverage + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAverage: function (a, b) { + return (a + b) / 2; + }, + + /** + * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. + * + * @method Phaser.Color.blendAdd + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAdd: function (a, b) { + return Math.min(255, a + b); + }, + + /** + * Combines the source and backdrop colors and returns their value minus 255. + * + * @method Phaser.Color.blendSubtract + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSubtract: function (a, b) { + return Math.max(0, a + b - 255); + }, + + /** + * Subtracts the darker of the two constituent colors from the lighter. + * + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendDifference + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDifference: function (a, b) { + return Math.abs(a - b); + }, + + /** + * Negation blend mode. + * + * @method Phaser.Color.blendNegation + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNegation: function (a, b) { + return 255 - Math.abs(255 - a - b); + }, + + /** + * Multiplies the complements of the backdrop and source color values, then complements the result. + * The result color is always at least as light as either of the two constituent colors. + * Screening any color with white produces white; screening with black leaves the original color unchanged. + * + * @method Phaser.Color.blendScreen + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendScreen: function (a, b) { + return 255 - (((255 - a) * (255 - b)) >> 8); + }, + + /** + * Produces an effect similar to that of the Difference mode, but lower in contrast. + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendExclusion + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendExclusion: function (a, b) { + return a + b - 2 * a * b / 255; + }, + + /** + * Multiplies or screens the colors, depending on the backdrop color. + * Source colors overlay the backdrop while preserving its highlights and shadows. + * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. + * + * @method Phaser.Color.blendOverlay + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendOverlay: function (a, b) { + return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255); + }, + + /** + * Darkens or lightens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. + * The effect is similar to shining a diffused spotlight on the backdrop. + * + * @method Phaser.Color.blendSoftLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSoftLight: function (a, b) { + return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255); + }, + + /** + * Multiplies or screens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; + * this is useful for adding shadows to a scene. + * + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. + * + * @method Phaser.Color.blendHardLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardLight: function (a, b) { + return Phaser.Color.blendOverlay(b, a); + }, + + /** + * Brightens the backdrop color to reflect the source color. + * Painting with black produces no change. + * + * @method Phaser.Color.blendColorDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorDodge: function (a, b) { + return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b))); + }, + + /** + * Darkens the backdrop color to reflect the source color. + * Painting with white produces no change. + * + * @method Phaser.Color.blendColorBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorBurn: function (a, b) { + return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b)); + }, + + /** + * An alias for blendAdd, it simply sums the values of the two colors. + * + * @method Phaser.Color.blendLinearDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearDodge: function (a, b) { + return Phaser.Color.blendAdd(a, b); + }, + + /** + * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. + * + * @method Phaser.Color.blendLinearBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearBurn: function (a, b) { + return Phaser.Color.blendSubtract(a, b); + }, + + /** + * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). + * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. + * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. + * + * @method Phaser.Color.blendLinearLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearLight: function (a, b) { + return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128))); + }, + + /** + * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). + * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. + * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom + * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. + * + * @method Phaser.Color.blendVividLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendVividLight: function (a, b) { + return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128))); + }, + + /** + * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. + * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. + * + * @method Phaser.Color.blendPinLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPinLight: function (a, b) { + return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128))); + }, + + /** + * Runs blendVividLight on the source and backdrop colors. + * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. + * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. + * This changes all pixels to primary additive colors (red, green, or blue), white, or black. + * + * @method Phaser.Color.blendHardMix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardMix: function (a, b) { + return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255; + }, + + /** + * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. + * + * @method Phaser.Color.blendReflect + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendReflect: function (a, b) { + return b === 255 ? b : Math.min(255, (a * a / (255 - b))); + }, + + /** + * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. + * + * @method Phaser.Color.blendGlow + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendGlow: function (a, b) { + return Phaser.Color.blendReflect(b, a); + }, + + /** + * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. + * + * @method Phaser.Color.blendPhoenix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPhoenix: function (a, b) { + return Math.min(a, b) - Math.max(a, b) + 255; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Manager is responsible for looking after all of the running physics systems. +* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. +* +* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. +* +* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the +* faster (due to being much simpler) Arcade Physics system. +* +* @class Phaser.Physics +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Physics = function (game, config) { + + config = config || {}; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} config - The physics configuration object as passed to the game on creation. + */ + this.config = config; + + /** + * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. + */ + this.arcade = null; + + /** + * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. + */ + this.p2 = null; + + /** + * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. + */ + this.ninja = null; + + /** + * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. + */ + this.box2d = null; + + /** + * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). + */ + this.chipmunk = null; + + /** + * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). + */ + this.matter = null; + + this.parseConfig(); + +}; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.ARCADE = 0; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.P2JS = 1; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.NINJA = 2; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.BOX2D = 3; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.CHIPMUNK = 4; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.MATTERJS = 5; + +Phaser.Physics.prototype = { + + /** + * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. + * + * @method Phaser.Physics#parseConfig + */ + parseConfig: function () { + + if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade')) + { + // If Arcade isn't specified, we create it automatically if we can + this.arcade = new Phaser.Physics.Arcade(this.game); + } + + 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); + } + + if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D')) + { + this.box2d = new Phaser.Physics.BOX2D(this.game, this.config); + } + + if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter')) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + + }, + + /** + * This will create an instance of the requested physics simulation. + * Phaser.Physics.Arcade is running by default, but all others need activating directly. + * + * You can start the following physics systems: + * + * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. + * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) + * + * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. + * They are not bundled into the core Phaser library. + * + * If the physics world has already been created (i.e. in another state in your game) then + * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors + * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. + * + * @method Phaser.Physics#startSystem + * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. + */ + startSystem: function (system) { + + if (system === Phaser.Physics.ARCADE) + { + this.arcade = new Phaser.Physics.Arcade(this.game); + } + else if (system === Phaser.Physics.P2JS) + { + if (this.p2 === null) + { + this.p2 = new Phaser.Physics.P2(this.game, this.config); + } + else + { + this.p2.reset(); + } + } + else if (system === Phaser.Physics.NINJA) + { + this.ninja = new Phaser.Physics.Ninja(this.game); + } + else if (system === Phaser.Physics.BOX2D) + { + if (this.box2d === null) + { + this.box2d = new Phaser.Physics.Box2D(this.game, this.config); + } + else + { + this.box2d.reset(); + } + } + else if (system === Phaser.Physics.MATTERJS) + { + if (this.matter === null) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + else + { + this.matter.reset(); + } + } + + }, + + /** + * This will create a default physics body on the given game object or array of objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * It can be for any of the physics systems that have been started: + * + * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. + * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. + * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 + * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) + * Phaser.Physics.CHIPMUNK is still in development. + * + * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the + * individual physics systems `enable` methods instead of using this generic one. + * + * @method Phaser.Physics#enable + * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. + * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. + * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. + */ + enable: function (object, system, debug) { + + if (system === undefined) { system = Phaser.Physics.ARCADE; } + if (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); + } + else if (system === Phaser.Physics.BOX2D && this.box2d) + { + this.box2d.enable(object); + } + else if (system === Phaser.Physics.MATTERJS && this.matter) + { + this.matter.enable(object); + } + else + { + console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.'); + } + + }, + + /** + * preUpdate checks. + * + * @method Phaser.Physics#preUpdate + * @protected + */ + preUpdate: function () { + + // ArcadePhysics / Ninja don't have a core to preUpdate + + if (this.p2) + { + this.p2.preUpdate(); + } + + if (this.box2d) + { + this.box2d.preUpdate(); + } + + if (this.matter) + { + this.matter.preUpdate(); + } + + }, + + /** + * Updates all running physics systems. + * + * @method Phaser.Physics#update + * @protected + */ + update: function () { + + // ArcadePhysics / Ninja don't have a core to update + + if (this.p2) + { + this.p2.update(); + } + + if (this.box2d) + { + this.box2d.update(); + } + + if (this.matter) + { + this.matter.update(); + } + + }, + + /** + * Updates the physics bounds to match the world dimensions. + * + * @method Phaser.Physics#setBoundsToWorld + * @protected + */ + setBoundsToWorld: function () { + + if (this.arcade) + { + this.arcade.setBoundsToWorld(); + } + + if (this.ninja) + { + this.ninja.setBoundsToWorld(); + } + + if (this.p2) + { + this.p2.setBoundsToWorld(); + } + + if (this.box2d) + { + this.box2d.setBoundsToWorld(); + } + + if (this.matter) + { + this.matter.setBoundsToWorld(); + } + + }, + + /** + * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. + * + * @method Phaser.Physics#clear + * @protected + */ + clear: function () { + + if (this.p2) + { + this.p2.clear(); + } + + if (this.box2d) + { + this.box2d.clear(); + } + + if (this.matter) + { + this.matter.clear(); + } + + }, + + /** + * Resets the active physics system. Called automatically on a Phaser.State swap. + * + * @method Phaser.Physics#reset + * @protected + */ + reset: function () { + + if (this.p2) + { + this.p2.reset(); + } + + if (this.box2d) + { + this.box2d.reset(); + } + + if (this.matter) + { + this.matter.reset(); + } + + }, + + /** + * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. + * + * @method Phaser.Physics#destroy + */ + destroy: function () { + + if (this.p2) + { + this.p2.destroy(); + } + + if (this.box2d) + { + this.box2d.destroy(); + } + + if (this.matter) + { + this.matter.destroy(); + } + + this.arcade = null; + this.ninja = null; + this.p2 = null; + this.box2d = null; + this.matter = null; + + } + +}; + +Phaser.Physics.prototype.constructor = Phaser.Physics; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. +* +* @class Phaser.Physics.Arcade +* @constructor +* @param {Phaser.Game} game - reference to the current game instance. +*/ +Phaser.Physics.Arcade = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height); + + /** + * Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`. + * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. + * @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right). + */ + this.checkCollision = { up: true, down: true, left: true, right: true }; + + /** + * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. + */ + this.maxLevels = 4; + + /** + * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. + * @default + */ + this.OVERLAP_BIAS = 4; + + /** + * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. + */ + this.forceX = false; + + /** + * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT. + * @default + */ + this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT; + + /** + * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. + */ + this.skipQuadTree = true; + + /** + * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. + */ + this.isPaused = false; + + /** + * @property {Phaser.QuadTree} quadTree - The world QuadTree. + */ + 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); + + /** + * @property {number} _total - Internal cache var. + * @private + */ + this._total = 0; + + // By default we want the bounds the same size as the world bounds + this.setBoundsToWorld(); + +}; + +Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade; + +/** +* A constant used for the sortDirection value. +* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.SORT_NONE = 0; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.LEFT_RIGHT = 1; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.RIGHT_LEFT = 2; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.TOP_BOTTOM = 3; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.BOTTOM_TOP = 4; + +Phaser.Physics.Arcade.prototype = { + + /** + * Updates the size of this physics world. + * + * @method Phaser.Physics.Arcade#setBounds + * @param {number} x - Top left most corner of the world. + * @param {number} y - Top left most corner of the world. + * @param {number} width - New width of the world. Can never be smaller than the Game.width. + * @param {number} height - New height of the world. Can never be smaller than the Game.height. + */ + setBounds: function (x, y, width, height) { + + this.bounds.setTo(x, y, width, height); + + }, + + /** + * Updates the size of this physics world to match the size of the game world. + * + * @method Phaser.Physics.Arcade#setBoundsToWorld + */ + setBoundsToWorld: function () { + + this.bounds.copyFrom(this.game.world.bounds); + + }, + + /** + * This will create an Arcade Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * + * @method Phaser.Physics.Arcade#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, children) { + + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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) + { + // If it's a Group then we do it on the children regardless + this.enable(object.children, children); + } + else + { + this.enableBody(object); + + if (children && object.hasOwnProperty('children') && object.children.length > 0) + { + this.enable(object.children, true); + } + } + } + + }, + + /** + * Creates an Arcade Physics body on the given game object. + * + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. + * + * @method Phaser.Physics.Arcade#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + */ + enableBody: function (object) { + + if (object.hasOwnProperty('body') && object.body === null) + { + object.body = new Phaser.Physics.Arcade.Body(object); + + if (object.parent && object.parent instanceof Phaser.Group) + { + object.parent.addToHash(object); + } + } + + }, + + /** + * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. + * + * @method Phaser.Physics.Arcade#updateMotion + * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. + */ + updateMotion: function (body) { + + if (body.allowRotation) + { + var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity; + body.angularVelocity += 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); + + }, + + /** + * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * Based on a function in Flixel by @ADAMATOMIC + * + * @method Phaser.Physics.Arcade#computeVelocity + * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical. + * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. + * @param {number} velocity - Any component of velocity (e.g. 20). + * @param {number} acceleration - Rate at which the velocity is changing. + * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. + * @param {number} [max=10000] - An absolute value cap for the velocity. + * @return {number} The altered Velocity value. + */ + computeVelocity: function (axis, body, velocity, acceleration, drag, max) { + + if (max === undefined) { max = 10000; } + + 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 && body.allowDrag) + { + drag *= this.game.time.physicsElapsed; + + if (velocity - drag > 0) + { + velocity -= drag; + } + else if (velocity + drag < 0) + { + velocity += drag; + } + else + { + velocity = 0; + } + } + + if (velocity > max) + { + velocity = max; + } + else if (velocity < -max) + { + velocity = -max; + } + + return velocity; + + }, + + /** + * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. + * + * Unlike {@link #collide} the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. + * Both the first and second parameter can be arrays of objects, of differing types. + * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups within Groups). + * + * ##### Tilemaps + * + * Any overlapping tiles, including blank/null tiles, will give a positive result. Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) have no special status, and callbacks added via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} are not invoked. So calling this method without any callbacks isn't very useful. + * + * If you're interested only in whether an object overlaps a certain tile or class of tiles, filter the tiles with `processCallback` and then use the result returned by this method. Blank/null tiles can be excluded by their {@link Phaser.Tile#index index} (-1). + * + * If you want to take action on certain overlaps, examine the tiles in `collideCallback` and then handle as you like. + * + * @method Phaser.Physics.Arcade#overlap + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if an overlap occurred otherwise false. + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) { + + overlapCallback = overlapCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || overlapCallback; + + this._total = 0; + + this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + + return (this._total > 0); + + }, + + /** + * Checks for collision between two game objects and separates them if colliding ({@link https://gist.github.com/samme/cbb81dd19f564dcfe2232761e575063d details}). If you don't require separation then use {@link #overlap} instead. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. + * Both the `object1` and `object2` can be arrays of objects, of differing types. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If one Group **only** is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If either object is `null` the collision test will fail. + * + * Bodies with `enable = false` and Sprites with `exists = false` are skipped (ignored). + * + * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. + * + * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). + * + * ##### Examples + * + * ```javascript + * collide(group); + * collide(group, undefined); // equivalent + * + * collide(sprite1, sprite2); + * + * collide(sprite, group); + * + * collide(group1, group2); + * + * collide([sprite1, sprite2], [sprite3, sprite4]); // 1 vs. 3, 1 vs. 4, 2 vs. 3, 2 vs. 4 + * ``` + * + * ##### Tilemaps + * + * Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) are "solid". If a Sprite collides with one of these tiles, the two are separated by moving the Sprite outside the tile's edges. Enable {@link Phaser.TilemapLayer#debug} to see the colliding edges of the Tilemap. + * + * Tiles with a callback attached via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} invoke the callback if a Sprite collides with them. If a tile has a callback attached via both methods, only the location callback is invoked. The colliding Sprite is separated from the tile only if the callback returns `true`. + * + * @method Phaser.Physics.Arcade#collide + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. + * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if a collision occurred otherwise false. + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) { + + collideCallback = collideCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || collideCallback; + + this._total = 0; + + this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + + return (this._total > 0); + + }, + + /** + * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortLeftRight + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortLeftRight: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.x - b.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortRightLeft + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortRightLeft: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.x - a.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortTopBottom + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortTopBottom: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.y - b.body.y; + + }, + + /** + * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortBottomTop + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortBottomTop: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.y - a.body.y; + + }, + + /** + * This method will sort a Groups hash array. + * + * If the Group has `physicsSortDirection` set it will use the sort direction defined. + * + * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection. + * + * By changing Group.physicsSortDirection you can customise each Group to sort in a different order. + * + * @method Phaser.Physics.Arcade#sort + * @param {Phaser.Group} group - The Group to sort. + * @param {integer} [sortDirection] - The sort direction used to sort this Group. + */ + sort: function (group, sortDirection) { + + if (group.physicsSortDirection !== null) + { + sortDirection = group.physicsSortDirection; + } + else + { + if (sortDirection === undefined) { sortDirection = this.sortDirection; } + } + + if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + // Game world is say 2000x600 and you start at 0 + group.hash.sort(this.sortLeftRight); + } + else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + // Game world is say 2000x600 and you start at 2000 + group.hash.sort(this.sortRightLeft); + } + else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + // Game world is say 800x2000 and you start at 0 + group.hash.sort(this.sortTopBottom); + } + else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + // Game world is say 800x2000 and you start at 2000 + group.hash.sort(this.sortBottomTop); + } + + }, + + /** + * Internal collision handler. Extracts objects for {@link #collideHandler}. + * + * @method Phaser.Physics.Arcade#collideObjects + * @private + */ + collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object2.length; i++) + { + if (!object2[i]) { continue; } + + this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && !Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + for (var j = 0; j < object2.length; j++) + { + if (!object2[j]) { continue; } + + this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + + }, + + /** + * Internal collision handler. Matches arguments to other handlers. + * + * @method Phaser.Physics.Arcade#collideHandler + * @private + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + // Only collide valid objects + if (object2 === undefined && object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly); + return; + } + + // If neither of the objects are set or exist then bail out + if (!object1 || !object2 || !object1.exists || !object2.exists) + { + return; + } + + // Groups? Sort them + if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE) + { + if (object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + } + + if (object2.physicsType === Phaser.GROUP) + { + this.sort(object2); + } + } + + // SPRITES + if (object1.physicsType === Phaser.SPRITE) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // GROUPS + else if (object1.physicsType === Phaser.GROUP) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // TILEMAP LAYERS + else if (object1.physicsType === Phaser.TILEMAPLAYER) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsSprite + * @private + * @param {Phaser.Sprite} sprite1 - The first sprite to check. + * @param {Phaser.Sprite} sprite2 - The second sprite to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + 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; + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsGroup + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0 || !sprite.body) + { + return; + } + + if (this.skipQuadTree || sprite.body.skipQuadTree) + { + var bounds = {}; + + for (var i = 0; i < group.hash.length; i++) + { + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds object + bounds = object1.body.getBounds(bounds); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (sprite.body.right < bounds.x) + { + break; + } + else if (bounds.right < sprite.body.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (sprite.body.x > bounds.right) + { + break; + } + else if (bounds.x > sprite.body.right) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (sprite.body.bottom < bounds.y) + { + break; + } + else if (bounds.bottom < sprite.body.y) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (sprite.body.y > bounds.bottom) + { + break; + } + else if (bounds.y > sprite.body.bottom) + { + continue; + } + } + + this.collideSpriteVsSprite(sprite, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else + { + // What is the sprite colliding with in the quadtree? + 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 items = this.quadTree.retrieve(sprite); + + for (var i = 0; i < items.length; i++) + { + // We have our potential suspects, are they in this group? + if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, items[i].sprite); + } + + this._total++; + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsSelf + * @private + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.hash.length; i++) + { + var bounds1 = {}; + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds1 object + bounds1 = object1.body.getBounds(bounds1); + + for (var j = i + 1; j < group.hash.length; j++) + { + var bounds2 = {}; + var object2 = group.hash[j]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object2 || !object2.exists || !object2.body) + { + continue; + } + + // Inject the Body bounds data into the bounds2 object + bounds2 = object2.body.getBounds(bounds2); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (bounds1.right < bounds2.x) + { + break; + } + else if (bounds2.right < bounds1.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (bounds1.x > bounds2.right) + { + continue; + } + else if (bounds2.x > bounds1.right) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (bounds1.bottom < bounds2.y) + { + continue; + } + else if (bounds2.bottom < bounds1.y) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (bounds1.y > bounds2.bottom) + { + continue; + } + else if (bounds2.y > object1.body.bottom) + { + break; + } + } + + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsGroup + * @private + * @param {Phaser.Group} group1 - The first Group to check. + * @param {Phaser.Group} group2 - The second Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group1.length === 0 || group2.length === 0) + { + return; + } + + for (var i = 0; i < group1.children.length; i++) + { + if (group1.children[i].exists) + { + if (group1.children[i].physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else + { + this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + + }, + + /** + * The core separation function to separate two physics bodies. + * + * @private + * @method Phaser.Physics.Arcade#separate + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true. + * @param {object} [callbackContext] - The context in which to run the process callback. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} Returns true if the bodies collided, otherwise false. + */ + separate: function (body1, body2, processCallback, callbackContext, overlapOnly) { + + if ( + !body1.enable || + !body2.enable || + body1.checkCollision.none || + body2.checkCollision.none || + !this.intersects(body1, body2)) + { + return false; + } + + // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. + if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false) + { + return false; + } + + // Circle vs. Circle quick bail out + if (body1.isCircle && body2.isCircle) + { + return this.separateCircle(body1, body2, overlapOnly); + } + + // We define the behavior of bodies in a collision circle and rectangle + // If a collision occurs in the corner points of the rectangle, the body behave like circles + + // Either body1 or body2 is a circle + if (body1.isCircle !== body2.isCircle) + { + var bodyRect = (body1.isCircle) ? body2 : body1; + var bodyCircle = (body1.isCircle) ? body1 : body2; + + var rect = { + x: bodyRect.x, + y: bodyRect.y, + right: bodyRect.right, + bottom: bodyRect.bottom + }; + + var circle = bodyCircle.center; + + if (circle.y < rect.y || circle.y > rect.bottom) + { + if (circle.x < rect.x || circle.x > rect.right) + { + return this.separateCircle(body1, body2, overlapOnly); + } + } + } + + var resultX = false; + var resultY = false; + + // Do we separate on x or y first? + if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) + { + resultX = this.separateX(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultY = this.separateY(body1, body2, overlapOnly); + } + } + else + { + resultY = this.separateY(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultX = this.separateX(body1, body2, overlapOnly); + } + } + + var result = (resultX || resultY); + + if (result) + { + if (overlapOnly) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + else + { + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + } + } + + return result; + + }, + + /** + * Check for intersection against two bodies. + * + * @method Phaser.Physics.Arcade#intersects + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check. + * @return {boolean} True if they intersect, otherwise false. + */ + intersects: function (body1, body2) { + + if (body1 === body2) + { + return false; + } + + if (body1.isCircle) + { + if (body2.isCircle) + { + // Circle vs. Circle + return Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); + } + else + { + // Circle vs. Rect + return this.circleBodyIntersects(body1, body2); + } + } + else + { + if (body2.isCircle) + { + // Rect vs. Circle + return this.circleBodyIntersects(body2, body1); + } + else + { + // Rect vs. Rect + if (body1.right <= body2.position.x) + { + return false; + } + + if (body1.bottom <= body2.position.y) + { + return false; + } + + if (body1.position.x >= body2.right) + { + return false; + } + + if (body1.position.y >= body2.bottom) + { + return false; + } + + return true; + } + } + + }, + + /** + * Checks to see if a circular Body intersects with a Rectangular Body. + * + * @method Phaser.Physics.Arcade#circleBodyIntersects + * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set. + * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape) + * @return {boolean} Returns true if the bodies intersect, otherwise false. + */ + circleBodyIntersects: function (circle, body) { + + var x = Phaser.Math.clamp(circle.center.x, body.left, body.right); + var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom); + + var dx = (circle.center.x - x) * (circle.center.x - x); + var dy = (circle.center.y - y) * (circle.center.y - y); + + return (dx + dy) <= (circle.halfWidth * circle.halfWidth); + + }, + + /** + * The core separation function to separate two circular physics bodies. + * + * @method Phaser.Physics.Arcade#separateCircle + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateCircle: function (body1, body2, overlapOnly) { + + // Set the bounding box overlap values + this.getOverlapX(body1, body2); + this.getOverlapY(body1, body2); + + var dx = body2.center.x - body1.center.x; + var dy = body2.center.y - body1.center.y; + + var angleCollision = Math.atan2(dy, dx); + + var overlap = 0; + + if (body1.isCircle !== body2.isCircle) + { + var rect = { + x: (body2.isCircle) ? body1.position.x : body2.position.x, + y: (body2.isCircle) ? body1.position.y : body2.position.y, + right: (body2.isCircle) ? body1.right : body2.right, + bottom: (body2.isCircle) ? body1.bottom : body2.bottom + }; + + var circle = { + x: (body1.isCircle) ? body1.center.x : body2.center.x, + y: (body1.isCircle) ? body1.center.y : body2.center.y, + radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth + }; + + if (circle.y < rect.y) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.y) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.y) - circle.radius; + } + } + else if (circle.y > rect.bottom) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; + } + } + + overlap *= -1; + } + else + { + overlap = (body1.halfWidth + body2.halfWidth) - Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y); + } + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + if (overlap !== 0) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + + // return true if there was some overlap, otherwise false + return (overlap !== 0); + } + + // Transform the velocity vector to the coordinate system oriented along the direction of impact. + // This is done to eliminate the vertical component of the velocity + var v1 = { + x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision), + y: body1.velocity.x * Math.sin(angleCollision) - body1.velocity.y * Math.cos(angleCollision) + }; + + var v2 = { + x: body2.velocity.x * Math.cos(angleCollision) + body2.velocity.y * Math.sin(angleCollision), + y: body2.velocity.x * Math.sin(angleCollision) - body2.velocity.y * Math.cos(angleCollision) + }; + + // We expect the new velocity after impact + var tempVel1 = ((body1.mass - body2.mass) * v1.x + 2 * body2.mass * v2.x) / (body1.mass + body2.mass); + var tempVel2 = (2 * body1.mass * v1.x + (body2.mass - body1.mass) * v2.x) / (body1.mass + body2.mass); + + // We convert the vector to the original coordinate system and multiplied by factor of rebound + if (!body1.immovable) + { + body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x; + body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y; + } + + if (!body2.immovable) + { + body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x; + body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y; + } + + // When the collision angle is almost perpendicular to the total initial velocity vector + // (collision on a tangent) vector direction can be determined incorrectly. + // This code fixes the problem + + if (Math.abs(angleCollision) < Math.PI / 2) + { + if ((body1.velocity.x > 0) && !body1.immovable && (body2.velocity.x > body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x < 0) && !body2.immovable && (body1.velocity.x < body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y > 0) && !body1.immovable && (body2.velocity.y > body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y < 0) && !body2.immovable && (body1.velocity.y < body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + else if (Math.abs(angleCollision) > Math.PI / 2) + { + if ((body1.velocity.x < 0) && !body1.immovable && (body2.velocity.x < body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y < 0) && !body1.immovable && (body2.velocity.y < body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + + if (!body1.immovable) + { + body1.x += (body1.velocity.x * this.game.time.physicsElapsed) - overlap * Math.cos(angleCollision); + body1.y += (body1.velocity.y * this.game.time.physicsElapsed) - overlap * Math.sin(angleCollision); + } + + if (!body2.immovable) + { + body2.x += (body2.velocity.x * this.game.time.physicsElapsed) + overlap * Math.cos(angleCollision); + body2.y += (body2.velocity.y * this.game.time.physicsElapsed) + overlap * Math.sin(angleCollision); + } + + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + + return true; + + }, + + /** + * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: + * `touching.left`, `touching.right` and `overlapX`. + * + * @method Phaser.Physics.Arcade#getOverlapX + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of horizontal overlap between the two bodies. + */ + getOverlapX: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS; + + if (body1.deltaX() === 0 && body2.deltaX() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaX() > body2.deltaX()) + { + // Body1 is moving right and / or Body2 is moving left + overlap = body1.right - body2.x; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.right = true; + body2.touching.none = false; + body2.touching.left = true; + } + } + else if (body1.deltaX() < body2.deltaX()) + { + // Body1 is moving left and/or Body2 is moving right + overlap = body1.x - body2.width - body2.x; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.left = true; + body2.touching.none = false; + body2.touching.right = true; + } + } + + // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapX = overlap; + body2.overlapX = overlap; + + return overlap; + + }, + + /** + * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: + * `touching.up`, `touching.down` and `overlapY`. + * + * @method Phaser.Physics.Arcade#getOverlapY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of vertical overlap between the two bodies. + */ + getOverlapY: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS; + + if (body1.deltaY() === 0 && body2.deltaY() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaY() > body2.deltaY()) + { + // Body1 is moving down and/or Body2 is moving up + overlap = body1.bottom - body2.y; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.down = true; + body2.touching.none = false; + body2.touching.up = true; + } + } + else if (body1.deltaY() < body2.deltaY()) + { + // Body1 is moving up and/or Body2 is moving down + overlap = body1.y - body2.bottom; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.up = true; + body2.touching.none = false; + body2.touching.down = true; + } + } + + // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapY = overlap; + body2.overlapY = overlap; + + return overlap; + + }, + + /** + * The core separation function to separate two physics bodies on the x axis. + * + * @method Phaser.Physics.Arcade#separateX + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateX: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapX(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.x; + var v2 = body2.velocity.x; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.x -= overlap; + body2.x += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.x = avg + nv1 * body1.bounce.x; + body2.velocity.x = avg + nv2 * body2.bounce.x; + } + else if (!body1.immovable) + { + body1.x -= overlap; + body1.velocity.x = v2 - v1 * body1.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body2.moves) + { + body1.y += (body2.y - body2.prev.y) * body2.friction.y; + } + } + else + { + body2.x += overlap; + body2.velocity.x = v1 - v2 * body2.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body1.moves) + { + body2.y += (body1.y - body1.prev.y) * body1.friction.y; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * The core separation function to separate two physics bodies on the y axis. + * + * @private + * @method Phaser.Physics.Arcade#separateY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateY: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapY(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.y; + var v2 = body2.velocity.y; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.y -= overlap; + body2.y += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.y = avg + nv1 * body1.bounce.y; + body2.velocity.y = avg + nv2 * body2.bounce.y; + } + else if (!body1.immovable) + { + body1.y -= overlap; + body1.velocity.y = v2 - v1 * body1.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body2.moves) + { + body1.x += (body2.x - body2.prev.x) * body2.friction.x; + } + } + else + { + body2.y += overlap; + body2.velocity.y = v1 - v2 * body2.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body1.moves) + { + body2.x += (body1.x - body1.prev.x) * body1.friction.x; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. + * + * @method Phaser.Physics.Arcade#getObjectsUnderPointer + * @param {Phaser.Pointer} pointer - The Pointer to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. + * @param {object} [callbackContext] - The context in which to run the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates. + */ + getObjectsUnderPointer: function (pointer, group, callback, callbackContext) { + + if (group.length === 0 || !pointer.exists) + { + return; + } + + return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer); + + }, + + /** + * Given a Group and a location this will check to see which Group children overlap with the coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. + * + * @method Phaser.Physics.Arcade#getObjectsAtLocation + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. + * @param {object} [callbackContext] - The context in which to run the callback. + * @param {object} [callbackArg] - An argument to pass to the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates. + */ + getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) { + + 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(x, y, 1, 1); + var output = []; + + var items = this.quadTree.retrieve(rect); + + for (var i = 0; i < items.length; i++) + { + if (items[i].hitTest(x, y)) + { + if (callback) + { + callback.call(callbackContext, callbackArg, items[i].sprite); + } + + output.push(items[i].sprite); + } + } + + return output; + + }, + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToObject: function (displayObject, destination, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Phaser.Point.angle(destination, displayObject); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#moveToPointer + * @param {any} displayObject - The display object to move. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToPointer: function (displayObject, speed, pointer, maxTime) { + + if (speed === undefined) { speed = 60; } + pointer = pointer || this.game.input.activePointer; + if (maxTime === undefined) { maxTime = 0; } + + var angle = this.angleToPointer(displayObject, pointer); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToXY: function (displayObject, x, y, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Math.atan2(y - displayObject.y, x - displayObject.x); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromAngle + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromAngle: function (angle, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(angle, speed, true); + + }, + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. + * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. + * + * @method Phaser.Physics.Arcade#accelerationFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. + * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. + */ + accelerationFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleBetween(displayObject, destination); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToPointer + * @param {any} displayObject - The display object to move. + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToPointer(displayObject, pointer); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToXY(displayObject, x, y); + + displayObject.body.acceleration.setTo(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Find the distance between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * If you have nested objects and need to calculate the distance between their centers in World coordinates, + * set their anchors to (0.5, 0.5) and use the `world` argument. + * + * If objects aren't nested or they share a parent's offset, you can calculate the distance between their + * centers with the `useCenter` argument, regardless of their anchor values. + * + * @method Phaser.Physics.Arcade#distanceBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {number} The distance between the source and target objects. + */ + distanceBetween: function (source, target, world, useCenter) { + + if (world === undefined) { world = false; } + + var dx; + var dy; + + if (useCenter) + { + dx = source.centerX - target.centerX; + dy = source.centerY - target.centerY; + } + else if (world) + { + dx = source.world.x - target.world.x; + dy = source.world.y - target.world.y; + } + else + { + dx = source.x - target.x; + dy = source.y - target.y; + } + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and the given x/y coordinates. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the x/y coordinates. + */ + distanceToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - x : displayObject.x - x; + var dy = (world) ? displayObject.world.y - y : displayObject.y - y; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the Pointer. + */ + distanceToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.x - pointer.worldX; + var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + + /** + * From a set of points or display objects, find the one closest to a source point or object. + * + * @method Phaser.Physics.Arcade#closest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The first target closest to the origin. + */ + closest: function (source, targets, world, useCenter) { + var min = Infinity; + var closest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance < min) + { + closest = target; + min = distance; + } + } + + return closest; + }, + + /** + * From a set of points or display objects, find the one farthest from a source point or object. + * + * @method Phaser.Physics.Arcade#farthest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The target closest to the origin. + */ + farthest: function (source, targets, world, useCenter) { + var max = -1; + var farthest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance > max) + { + farthest = target; + max = distance; + } + } + + return farthest; + }, + + /** + * Find the angle in radians between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetween: function (source, target, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Phaser.Point.angle(target.world, source.world); + } + else + { + return Phaser.Point.angle(target, source); + } + + }, + + /** + * Find the angle in radians between centers of two display objects (like Sprites). + * + * @method Phaser.Physics.Arcade#angleBetweenCenters + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetweenCenters: function (source, target) { + + var dx = target.centerX - source.centerX; + var dy = target.centerY - source.centerY; + + return Math.atan2(dy, dx); + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to get the angle to. + * @param {number} y - The y coordinate to get the angle to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(y - displayObject.world.y, x - displayObject.world.x); + } + else + { + return Math.atan2(y - displayObject.y, x - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x); + } + else + { + return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, + * taking their x/y and center into account relative to the world. + * + * @method Phaser.Physics.Arcade#worldAngleToPointer + * @param {any} displayObject - The DisplayObjerct to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY + */ + worldAngleToPointer: function (displayObject, pointer) { + + return this.angleToPointer(displayObject, pointer, true); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than +* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. +* +* @class Phaser.Physics.Arcade.Body +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. +*/ +Phaser.Physics.Arcade.Body = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = sprite.game; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.ARCADE; + + /** + * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. + * @default + */ + this.enable = true; + + /** + * If `true` this Body is using circular collision detection. If `false` it is using rectangular. + * Use `Body.setCircle` to control the collision shape this Body uses. + * @property {boolean} isCircle + * @default + * @readOnly + */ + this.isCircle = false; + + /** + * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled, relative to the Sprite's _texture_. + * If you wish to change the radius then call {@link #setCircle} again with the new value. + * If you wish to stop the Body using a circle then call {@link #setCircle} with a radius of zero (or undefined). + * The actual radius of the Body (at any Sprite scale) is equal to {@link #halfWidth} and the diameter is equal to {@link #width}. + * @property {number} radius + * @default + * @readOnly + */ + this.radius = 0; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite's texture. + */ + this.offset = new Phaser.Point(); + + /** + * @property {Phaser.Point} position - The position of the physics body, equivalent to ({@link #left}, {@link #top}). + * @readonly + */ + this.position = new Phaser.Point(sprite.x, sprite.y); + + /** + * @property {Phaser.Point} prev - The previous position of the physics body. + * @readonly + */ + this.prev = new Phaser.Point(this.position.x, this.position.y); + + /** + * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) + * @default + */ + this.allowRotation = true; + + /** + * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body + * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. + * @property {number} rotation + */ + this.rotation = sprite.angle; + + /** + * @property {number} preRotation - The previous rotation of the physics body, in degrees. + * @readonly + */ + this.preRotation = sprite.angle; + + /** + * @property {number} width - The calculated width of the physics body. + * @readonly + */ + this.width = sprite.width; + + /** + * @property {number} height - The calculated height of the physics body. + * @readonly + */ + this.height = sprite.height; + + /** + * @property {number} sourceWidth - The un-scaled original size. + * @readonly + */ + this.sourceWidth = sprite.width; + + /** + * @property {number} sourceHeight - The un-scaled original size. + * @readonly + */ + this.sourceHeight = sprite.height; + + if (sprite.texture) + { + this.sourceWidth = sprite.texture.frame.width; + this.sourceHeight = sprite.texture.frame.height; + } + + /** + * @property {number} halfWidth - The calculated width / 2 of the physics body. + * @readonly + */ + this.halfWidth = Math.abs(sprite.width / 2); + + /** + * @property {number} halfHeight - The calculated height / 2 of the physics body. + * @readonly + */ + this.halfHeight = Math.abs(sprite.height / 2); + + /** + * @property {Phaser.Point} center - The center coordinate of the Physics Body. + * @readonly + */ + this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight); + + /** + * @property {Phaser.Point} velocity - The velocity, or rate of change the Body's position. Measured in pixels per second. + */ + this.velocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} newVelocity - The distanced traveled during the last update, equal to `velocity * physicsElapsed`. Calculated during the Body.preUpdate and applied to its position. + * @readonly + */ + this.newVelocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. + */ + this.deltaMax = new Phaser.Point(); + + /** + * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + */ + this.acceleration = new Phaser.Point(); + + /** + * @property {boolean} allowDrag - Allow this Body to be influenced by {@link #drag}? + * @default + */ + this.allowDrag = true; + + /** + * @property {Phaser.Point} drag - The drag applied to the motion of the Body (when {@link #allowDrag} is enabled). Measured in pixels per second squared. + */ + this.drag = new Phaser.Point(); + + /** + * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local. + * @default + */ + this.allowGravity = true; + + /** + * @property {Phaser.Point} gravity - This Body's local gravity, **added** to any world gravity, unless Body.allowGravity is set to false. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. + */ + this.bounce = new Phaser.Point(); + + /** + * The elasticity of the Body when colliding with the World bounds. + * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property + * to a Phaser.Point object in order to enable a World bounds specific bounce value. + * @property {Phaser.Point} worldBounce + */ + this.worldBounce = null; + + /** + * A Signal that is dispatched when this Body collides with the world bounds. + * Due to the potentially high volume of signals this could create it is disabled by default. + * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` + * and it will be called when a collision happens, passing five arguments: + * `onWorldBounds(sprite, up, down, left, right)` + * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans + * indicating on which side of the world the Body collided. + * @property {Phaser.Signal} onWorldBounds + */ + this.onWorldBounds = null; + + /** + * A Signal that is dispatched when this Body collides with another Body. + * + * You still need to call `game.physics.arcade.collide` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `collide` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onCollide + */ + this.onCollide = null; + + /** + * A Signal that is dispatched when this Body overlaps with another Body. + * + * You still need to call `game.physics.arcade.overlap` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `overlap` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onOverlap + */ + this.onOverlap = null; + + /** + * @property {Phaser.Point} maxVelocity - The maximum velocity (in pixels per second squared) that the Body can reach. + * @default + */ + this.maxVelocity = new Phaser.Point(10000, 10000); + + /** + * @property {Phaser.Point} friction - If this Body is {@link #immovable} and moving, and another Body is 'riding' this one, this is the amount of motion the riding Body receives on each axis. + */ + this.friction = new Phaser.Point(1, 0); + + /** + * @property {number} angularVelocity - The angular velocity is the rate of change of the Body's rotation. It is measured in degrees per second. + * @default + */ + this.angularVelocity = 0; + + /** + * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. + * @default + */ + this.angularAcceleration = 0; + + /** + * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach. + * @default + */ + this.maxAngular = 1000; + + /** + * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. + * @default + */ + this.mass = 1; + + /** + * @property {number} angle - The angle of the Body's **velocity** in radians. + * @readonly + */ + this.angle = 0; + + /** + * @property {number} speed - The speed of the Body in pixels per second, equal to the magnitude of the velocity. + * @readonly + */ + this.speed = 0; + + /** + * @property {number} facing - A const reference to the direction the Body is traveling or facing: Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.UP, or Phaser.DOWN. If the Body is moving on both axes, UP and DOWN take precedence. + * @default + */ + this.facing = Phaser.NONE; + + /** + * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. **Two** immovable Bodies can't separate or exchange momentum and will pass through each other. + * @default + */ + this.immovable = false; + + /** + * Whether the physics system should update the Body's position and rotation based on its velocity, acceleration, drag, and gravity. + * + * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never + * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. + * If you want the physics system to move the body around, then set moves to true. + * + * A Body with moves = false can still be moved slightly (but not accelerated) during collision separation unless you set {@link #immovable} as well. + * + * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually. + * @default + */ + this.moves = true; + + /** + * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateX = false; + + /** + * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateY = false; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapX - The amount of horizontal overlap during the collision. + */ + this.overlapX = 0; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapY - The amount of vertical overlap during the collision. + */ + this.overlapY = 0; + + /** + * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. + * @property {number} overlapR - The amount of overlap during the collision. + */ + this.overlapR = 0; + + /** + * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. + * @property {boolean} embedded - Body embed value. + */ + this.embedded = false; + + /** + * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. + * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? + */ + this.collideWorldBounds = false; + + /** + * Set the checkCollision properties to control which directions collision is processed for this Body. + * For example checkCollision.up = false means it won't collide when the collision happened while moving up. + * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. + * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. + * @property {object} checkCollision - An object containing allowed collision (none, up, down, left, right). + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * This object is populated with boolean values when the Body collides with another. + * touching.up = true means the collision happened to the top of this Body for example. + * @property {object} touching - An object containing touching results (none, up, down, left, right). + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with previous touching values from the bodies previous collision. + * @property {object} wasTouching - An object containing previous touching results (none, up, down, left, right). + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with boolean values when the Body collides with the World bounds or a Tile. + * For example if blocked.up is true then the Body cannot move up. + * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any (none, up, down, left, right). + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. + * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. + * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision. + */ + this.tilePadding = new Phaser.Point(); + + /** + * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state? + */ + this.dirty = false; + + /** + * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. + */ + this.skipQuadTree = false; + + /** + * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. + * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. + * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, + * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. + * @property {boolean} syncBounds + * @default + */ + this.syncBounds = false; + + /** + * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods. + */ + this.isMoving = false; + + /** + * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods. + */ + this.stopVelocityOnCollide = true; + + /** + * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveTimer = 0; + + /** + * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDistance = 0; + + /** + * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDuration = 0; + + /** + * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveTarget = null; + + /** + * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveEnd = null; + + /** + * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events. + */ + this.onMoveComplete = new Phaser.Signal(); + + /** + * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. + */ + this.movementCallback = null; + + /** + * @property {object} movementCallbackContext - Context in which to call the movementCallback. + */ + this.movementCallbackContext = null; + + /** + * @property {boolean} _reset - Internal cache var. + * @private + */ + this._reset = true; + + /** + * @property {number} _sx - Internal cache var. + * @private + */ + this._sx = sprite.scale.x; + + /** + * @property {number} _sy - Internal cache var. + * @private + */ + this._sy = sprite.scale.y; + + /** + * @property {number} _dx - Internal cache var. + * @private + */ + this._dx = 0; + + /** + * @property {number} _dy - Internal cache var. + * @private + */ + this._dy = 0; + +}; + +Phaser.Physics.Arcade.Body.prototype = { + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @protected + */ + updateBounds: function () { + + if (this.syncBounds) + { + var b = this.sprite.getBounds(); + b.ceilAll(); + + if (b.width !== this.width || b.height !== this.height) + { + this.width = b.width; + this.height = b.height; + this._reset = true; + } + } + else + { + 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._sx = asx; + this._sy = asy; + this._reset = true; + } + } + + if (this._reset) + { + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.updateCenter(); + } + + }, + + /** + * Update the Body's center from its position. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @protected + */ + updateCenter: function () { + + this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @protected + */ + preUpdate: function () { + + if (!this.enable || this.game.physics.arcade.isPaused) + { + return; + } + + this.dirty = true; + + // Store and reset collision flags + 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.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; + + this.overlapR = 0; + this.overlapX = 0; + this.overlapY = 0; + + this.embedded = false; + + this.updateBounds(); + + this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.updateCenter(); + + this.rotation = this.sprite.angle; + + this.preRotation = this.rotation; + + if (this._reset || this.sprite.fresh) + { + 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; + this.updateCenter(); + + if (this.position.x !== this.prev.x || this.position.y !== this.prev.y) + { + this.angle = this.velocity.atan(); + } + + this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); + + // Now the State update will throw collision checks at the Body + // And finally we'll integrate the new position back to the Sprite in postUpdate + + if (this.collideWorldBounds) + { + if (this.checkWorldBounds() && this.onWorldBounds) + { + this.onWorldBounds.dispatch(this.sprite, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); + } + } + } + + this._dx = this.deltaX(); + this._dy = this.deltaY(); + + this._reset = false; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateMovement + * @protected + */ + updateMovement: function () { + + var percent = 0; + var collided = (this.overlapX !== 0 || this.overlapY !== 0); + + // Duration or Distance based? + + if (this.moveDuration > 0) + { + this.moveTimer += this.game.time.elapsedMS; + + percent = this.moveTimer / this.moveDuration; + } + else + { + this.moveTarget.end.set(this.position.x, this.position.y); + + percent = this.moveTarget.length / this.moveDistance; + } + + if (this.movementCallback) + { + var result = this.movementCallback.call(this.movementCallbackContext, this, this.velocity, percent); + } + + if (collided || percent >= 1 || (result !== undefined && result !== true)) + { + this.stopMovement((percent >= 1) || (this.stopVelocityOnCollide && collided)); + return false; + } + + return true; + + }, + + /** + * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it + * has Body.isMoving true), then calling this method will stop the movement before + * either the duration or distance counters expire. + * + * The `onMoveComplete` signal is dispatched. + * + * @method Phaser.Physics.Arcade.Body#stopMovement + * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero? + */ + stopMovement: function (stopVelocity) { + + if (this.isMoving) + { + this.isMoving = false; + + if (stopVelocity) + { + this.velocity.set(0); + } + + // Send the Sprite this Body belongs to + // and a boolean indicating if it stopped because of a collision or not + this.onMoveComplete.dispatch(this.sprite, (this.overlapX !== 0 || this.overlapY !== 0)); + } + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @protected + */ + postUpdate: function () { + + // Only allow postUpdate to be called once per frame + if (!this.enable || !this.dirty) + { + return; + } + + // Moving? + if (this.isMoving) + { + this.updateMovement(); + } + + this.dirty = false; + + 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.position.x += this._dx; + this.sprite.position.y += this._dy; + this._reset = true; + } + + this.updateCenter(); + + if (this.allowRotation) + { + this.sprite.angle += this.deltaZ(); + } + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @protected + * @return {boolean} True if the Body collided with the world bounds, otherwise false. + */ + checkWorldBounds: function () { + + var pos = this.position; + var bounds = this.game.physics.arcade.bounds; + var check = this.game.physics.arcade.checkCollision; + + var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; + var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; + + if (pos.x < bounds.x && check.left) + { + pos.x = bounds.x; + this.velocity.x *= bx; + this.blocked.left = true; + this.blocked.none = false; + } + else if (this.right > bounds.right && check.right) + { + pos.x = bounds.right - this.width; + this.velocity.x *= bx; + this.blocked.right = true; + this.blocked.none = false; + } + + if (pos.y < bounds.y && check.up) + { + pos.y = bounds.y; + this.velocity.y *= by; + this.blocked.up = true; + this.blocked.none = false; + } + else if (this.bottom > bounds.bottom && check.down) + { + pos.y = bounds.bottom - this.height; + this.velocity.y *= by; + this.blocked.down = true; + this.blocked.none = false; + } + + return !this.blocked.none; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal timer, and then + * monitoring the duration each frame. When the duration is up the movement is + * stopped and the `Body.onMoveComplete` signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * You can optionally set a speed in pixels per second. If not specified it + * will use the current `Body.speed` value. If this is zero, the function will return false. + * + * Please note that due to browser timings you should allow for a variance in + * when the duration will actually expire. Depending on system it may be as much as + * +- 50ms. Also this method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveFrom + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveFrom: function (duration, speed, direction) { + + if (speed === undefined) { speed = this.speed; } + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + this.moveTimer = 0; + this.moveDuration = duration; + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal distance counter. + * The distance is monitored each frame. When the distance equals the distance + * specified in this call, the movement is stopped, and the `Body.onMoveComplete` + * signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * Please note that due to browser timings you should allow for a variance in + * when the distance will actually expire. + * + * Note: This method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveTo + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} distance - The distance, in pixels, the Body will move. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveTo: function (duration, distance, direction) { + + var speed = distance / (duration / 1000); + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + distance = Math.abs(distance); + + this.moveDuration = 0; + this.moveDistance = distance; + + if (this.moveTarget === null) + { + this.moveTarget = new Phaser.Line(); + this.moveEnd = new Phaser.Point(); + } + + this.moveTarget.fromAngle(this.x, this.y, angle, distance); + + this.moveEnd.set(this.moveTarget.end.x, this.moveTarget.end.y); + + this.moveTarget.setTo(this.x, this.y, this.x, this.y); + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * You can modify the size of the physics Body to be any dimension you need. + * This allows you to make it smaller, or larger, than the parent Sprite. You + * can also control the x and y offset of the Body. + * + * The width, height, and offset arguments are relative to the Sprite + * _texture_ and are scaled with the Sprite's {@link Phaser.Sprite#scale} + * (but **not** the scale of any ancestors or the {@link Phaser.Camera#scale + * Camera scale}). + * + * For example: If you have a Sprite with a texture that is 80x100 in size, + * and you want the physics body to be 32x32 pixels in the middle of the + * texture, you would do: + * + * `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, + * 34)` + * + * Where the first two parameters are the new Body size (32x32 pixels) + * relative to the Sprite's scale. 24 is the horizontal offset of the Body + * from the top-left of the Sprites texture, and 34 is the vertical offset. + * + * If you've scaled a Sprite by altering its `width`, `height`, or `scale` + * and you want to position the Body relative to the Sprite's dimensions + * (which will differ from its texture's dimensions), you should divide these + * arguments by the Sprite's current scale: + * + * `setSize(32 / sprite.scale.x, 32 / sprite.scale.y)` + * + * Calling `setSize` on a Body that has already had `setCircle` will reset + * all of the Circle properties, making this Body rectangular again. + * @method Phaser.Physics.Arcade.Body#setSize + * @param {number} width - The width of the Body, relative to the Sprite's + * texture. + * @param {number} height - The height of the Body, relative to the Sprite's + * texture. + * @param {number} [offsetX] - The X offset of the Body from the left of the + * Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the + * Sprite's texture. + */ + setSize: function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { 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.updateCenter(); + + this.isCircle = false; + this.radius = 0; + + }, + + /** + * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. + * The radius is given in pixels (relative to the Sprite's _texture_) and is the distance from the center of the circle to the edge. + * + * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite's texture. + * + * To change a Body back to being rectangular again call `Body.setSize`. + * + * Note: Circular collision only happens with other Arcade Physics bodies, it does not + * work against tile maps, where rectangular collision is the only method supported. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. + * @param {number} [offsetX] - The X offset of the Body from the left of the Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the Sprite's texture. + */ + setCircle: function (radius, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.isCircle = true; + this.radius = radius; + + this.sourceWidth = radius * 2; + this.sourceHeight = radius * 2; + + 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.updateCenter(); + } + else + { + this.isCircle = false; + } + + }, + + /** + * Resets all Body values (velocity, acceleration, rotation, etc) + * + * @method Phaser.Physics.Arcade.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new y position of the Body. + */ + reset: function (x, y) { + + this.stop(); + + this.position.x = (x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + this.rotation = this.sprite.angle; + this.preRotation = this.rotation; + + this.updateBounds(); + + this.updateCenter(); + + }, + + /** + * Sets acceleration, velocity, and {@link #speed} to 0. + * + * @method Phaser.Physics.Arcade.Body#stop + */ + stop: function () { + + this.velocity.set(0); + this.acceleration.set(0); + this.speed = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + + }, + + /** + * Returns the bounds of this physics body. + * + * Only used internally by the World collision methods. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @param {object} obj - The object in which to set the bounds values. + * @return {object} The object that was given to this method. + */ + getBounds: function (obj) { + + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + + }, + + /** + * Tests if a world point lies within this Body. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @param {number} x - The world x coordinate to test. + * @param {number} y - The world y coordinate to test. + * @return {boolean} True if the given coordinates are inside this Body, otherwise false. + */ + hitTest: function (x, y) { + + return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Returns true if the bottom of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onFloor: function () { + + return this.blocked.down; + + }, + + /** + * Returns true if the top of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onCeiling: function(){ + + return this.blocked.up; + + }, + + /** + * Returns true if either side of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onWall: function () { + + return (this.blocked.left || this.blocked.right); + + }, + + /** + * Returns the absolute delta x value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @return {number} The absolute delta value. + */ + deltaAbsX: function () { + + return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); + + }, + + /** + * Returns the absolute delta y value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @return {number} The absolute delta value. + */ + deltaAbsY: function () { + + return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); + + }, + + /** + * Returns the delta x value. The difference between Body.x now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. + */ + deltaX: function () { + + return this.position.x - this.prev.x; + + }, + + /** + * Returns the delta y value. The difference between Body.y now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. + */ + deltaY: function () { + + return this.position.y - this.prev.y; + + }, + + /** + * Returns the delta z value. The difference between Body.rotation now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise. + */ + deltaZ: function () { + + return this.rotation - this.preRotation; + + }, + + /** + * Destroys this Body. + * + * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. + * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. + * + * @method Phaser.Physics.Arcade.Body#destroy + */ + destroy: function () { + + if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group) + { + this.sprite.parent.removeFromHash(this.sprite); + } + + this.sprite.body = null; + this.sprite = null; + + } + +}; + +/** +* @name Phaser.Physics.Arcade.Body#left +* @property {number} left - The x position of the Body. The same as `Body.x`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "left", { + + get: function () { + + return this.position.x; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#right +* @property {number} right - The right value of this Body (same as Body.x + Body.width) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", { + + get: function () { + + return this.position.x + this.width; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#top +* @property {number} top - The y position of the Body. The same as `Body.y`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "top", { + + get: function () { + + return this.position.y; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#bottom +* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", { + + get: function () { + + return this.position.y + this.height; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#x +* @property {number} x - The x position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#y +* @property {number} y - The y position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + +}); + +/** +* Render Sprite Body. +* +* @method Phaser.Physics.Arcade.Body#render +* @param {object} context - The context to render to. +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string). +* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) +* @param {number} [lineWidth=1] - The width of the stroke when unfilled. +*/ +Phaser.Physics.Arcade.Body.render = function (context, body, color, filled, lineWidth) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0,255,0,0.4)'; + + context.fillStyle = color; + context.strokeStyle = color; + context.lineWidth = lineWidth || 1; + + if (body.isCircle) + { + context.beginPath(); + context.arc(body.center.x - body.game.camera.x, body.center.y - body.game.camera.y, body.halfWidth, 0, 2 * Math.PI); + + if (filled) + { + context.fill(); + } + else + { + context.stroke(); + } + } + else + { + if (filled) + { + context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + else + { + context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + } + +}; + +/** +* Render Sprite Body Physics Data as text. +* +* @method Phaser.Physics.Arcade.Body#renderBodyInfo +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {number} x - X position of the debug info to be rendered. +* @param {number} y - Y position of the debug info to be rendered. +* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). +*/ +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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics Tile map collision methods. +* +* @class Phaser.Physics.Arcade.TilemapCollision +* @constructor +*/ +Phaser.Physics.Arcade.TilemapCollision = function () {}; + +Phaser.Physics.Arcade.TilemapCollision.prototype = { + + /** + * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling. + */ + TILE_BIAS: 16, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!sprite.body) + { + return; + } + + var mapData = tilemapLayer.getTiles( + sprite.body.position.x - sprite.body.tilePadding.x - tilemapLayer.getTileOffsetX(), + sprite.body.position.y - sprite.body.tilePadding.y - tilemapLayer.getTileOffsetY(), + sprite.body.width + sprite.body.tilePadding.x, + sprite.body.height + sprite.body.tilePadding.y, + false, false); + + if (mapData.length === 0) + { + return; + } + + for (var i = 0; i < mapData.length; i++) + { + if (processCallback) + { + if (processCallback.call(callbackContext, sprite, mapData[i])) + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + else + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @private + * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer + * @param {Phaser.Group} group - The Group to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.children.length; i++) + { + if (group.children[i].exists) + { + this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * The core separation function to separate a physics body and a tile. + * + * @private + * @method Phaser.Physics.Arcade#separateTile + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to collide against. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {boolean} Returns true if the body was separated, otherwise false. + */ + separateTile: function (i, body, tile, tilemapLayer, overlapOnly) { + + if (!body.enable) + { + return false; + } + + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + // We re-check for collision in case body was separated in a previous step + if (!tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + // no collision so bail out (separated in a previous step) + return false; + } + else if (overlapOnly) + { + // There is an overlap, and we don't need to separate. Bail. + return true; + } + + // They overlap. Any custom callbacks? + + // A local callback always takes priority over a layer level callback + if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + else if (typeof tile.layer.callbacks !== 'undefined' && tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + + // We don't need to go any further if this tile doesn't actually separate + if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom) + { + // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation + return false; + } + + var ox = 0; + var oy = 0; + var minX = 0; + var minY = 1; + + if (body.deltaAbsX() > body.deltaAbsY()) + { + // Moving faster horizontally, check X axis first + minX = -1; + } + else if (body.deltaAbsX() < body.deltaAbsY()) + { + // Moving faster vertically, check Y axis first + minY = -1; + } + + if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom)) + { + // We only need do this if both axis have checking faces AND we're moving in both directions + minX = Math.min(Math.abs((body.position.x - tilemapLayerOffsetX) - tile.right), Math.abs((body.right - tilemapLayerOffsetX) - tile.left)); + minY = Math.min(Math.abs((body.position.y - tilemapLayerOffsetY) - tile.bottom), Math.abs((body.bottom - tilemapLayerOffsetY) - tile.top)); + } + + if (minX < minY) + { + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + + // That's horizontal done, check if we still intersects? If not then we can return now + if (ox !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + } + } + else + { + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + + // That's vertical done, check if we still intersects? If not then we can return now + if (oy !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + } + } + + return (ox !== 0 || oy !== 0); + + }, + + /** + * Check the body against the given tile on the X axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckX: function (body, tile, tilemapLayer) { + + var ox = 0; + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + + if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left) + { + // Body is moving LEFT + if (tile.faceRight && (body.x - tilemapLayerOffsetX) < tile.right) + { + ox = (body.x - tilemapLayerOffsetX) - tile.right; + + if (ox < -this.TILE_BIAS) + { + ox = 0; + } + } + } + else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right) + { + // Body is moving RIGHT + if (tile.faceLeft && (body.right - tilemapLayerOffsetX) > tile.left) + { + ox = (body.right - tilemapLayerOffsetX) - tile.left; + + if (ox > this.TILE_BIAS) + { + ox = 0; + } + } + } + + if (ox !== 0) + { + if (body.customSeparateX) + { + body.overlapX = ox; + } + else + { + this.processTileSeparationX(body, ox); + } + } + + return ox; + + }, + + /** + * Check the body against the given tile on the Y axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckY: function (body, tile, tilemapLayer) { + + var oy = 0; + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up) + { + // Body is moving UP + if (tile.faceBottom && (body.y - tilemapLayerOffsetY) < tile.bottom) + { + oy = (body.y - tilemapLayerOffsetY) - tile.bottom; + + if (oy < -this.TILE_BIAS) + { + oy = 0; + } + } + } + else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down) + { + // Body is moving DOWN + if (tile.faceTop && (body.bottom - tilemapLayerOffsetY) > tile.top) + { + oy = (body.bottom - tilemapLayerOffsetY) - tile.top; + + if (oy > this.TILE_BIAS) + { + oy = 0; + } + } + } + + if (oy !== 0) + { + if (body.customSeparateY) + { + body.overlapY = oy; + } + else + { + this.processTileSeparationY(body, oy); + } + } + + return oy; + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} x - The x separation amount. + */ + processTileSeparationX: function (body, x) { + + if (x < 0) + { + body.blocked.left = true; + body.blocked.none = false; + } + else if (x > 0) + { + body.blocked.right = true; + body.blocked.none = false; + } + + body.position.x -= x; + + if (body.bounce.x === 0) + { + body.velocity.x = 0; + } + else + { + body.velocity.x = -body.velocity.x * body.bounce.x; + } + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} y - The y separation amount. + */ + processTileSeparationY: function (body, y) { + + if (y < 0) + { + body.blocked.up = true; + body.blocked.none = false; + } + else if (y > 0) + { + body.blocked.down = true; + body.blocked.none = false; + } + + body.position.y -= y; + + if (body.bounce.y === 0) + { + body.velocity.y = 0; + } + else + { + body.velocity.y = -body.velocity.y * body.bounce.y; + } + + } + +}; + +// Merge this with the Arcade Physics prototype +Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Add an extra properties to p2 that we need +p2.Body.prototype.parent = null; +p2.Spring.prototype.parent = null; + +/** +* This is your main access to the P2 Physics World. +* From here you can create materials, listen for events and add bodies into the physics simulation. +* +* @class Phaser.Physics.P2 +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {object} [config] - Physics configuration object passed in from the game constructor. +*/ +Phaser.Physics.P2 = function (game, config) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + if (config === undefined) + { + config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; + } + else + { + if (!config.hasOwnProperty('gravity')) + { + config.gravity = [0, 0]; + } + + if (!config.hasOwnProperty('broadphase')) + { + config.broadphase = new p2.SAPBroadphase(); + } + } + + /** + * @property {object} config - The p2 World configuration object. + * @protected + */ + this.config = config; + + /** + * @property {p2.World} world - The p2 World in which the simulation is run. + * @protected + */ + this.world = new p2.World(this.config); + + /** + * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. + * @default + */ + this.frameRate = 1 / 60; + + /** + * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. + * @default + */ + this.useElapsedTime = false; + + /** + * @property {boolean} paused - The paused state of the P2 World. + * @default + */ + this.paused = false; + + /** + * @property {array} materials - A local array of all created Materials. + * @protected + */ + this.materials = []; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. + */ + this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); + + /** + * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * This signal is dispatched when a new Body is added to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world. + * + * @property {Phaser.Signal} onBodyAdded + */ + this.onBodyAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Body is removed to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world. + * + * @property {Phaser.Signal} onBodyRemoved + */ + this.onBodyRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is added to the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world. + * + * @property {Phaser.Signal} onSpringAdded + */ + this.onSpringAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is removed from the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world. + * + * @property {Phaser.Signal} onSpringRemoved + */ + this.onSpringRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is added to the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world. + * + * @property {Phaser.Signal} onConstraintAdded + */ + this.onConstraintAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is removed from the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world. + * + * @property {Phaser.Signal} onConstraintRemoved + */ + this.onConstraintRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is added to the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world. + * + * @property {Phaser.Signal} onContactMaterialAdded + */ + this.onContactMaterialAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is removed from the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world. + * + * @property {Phaser.Signal} onContactMaterialRemoved + */ + this.onContactMaterialRemoved = new Phaser.Signal(); + + /** + * @property {function} postBroadphaseCallback - A postBroadphase callback. + */ + this.postBroadphaseCallback = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are fired. + */ + this.callbackContext = null; + + /** + * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done. + * + * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done. + * + * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + // Pixel to meter function overrides + if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) + { + this.mpx = config.mpx; + this.mpxi = config.mpxi; + this.pxm = config.pxm; + this.pxmi = config.pxmi; + } + + // Hook into the World events + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + /** + * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. + */ + this.collisionGroups = []; + + /** + * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. + */ + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. + */ + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. + */ + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + /** + * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. + */ + this.boundsCollidesWith = []; + + /** + * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. + * @private + */ + this._toRemove = []; + + /** + * @property {number} _collisionGroupID - Internal var. + * @private + */ + this._collisionGroupID = 2; + + /** + * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsLeft = true; + + /** + * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsRight = true; + + /** + * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsTop = true; + + /** + * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsBottom = true; + + /** + * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsOwnGroup = false; + + // By default we want everything colliding with everything + this.setBoundsToWorld(true, true, true, true, false); + +}; + +Phaser.Physics.P2.prototype = { + + /** + * This will add a P2 Physics body into the removal list for the next step. + * + * @method Phaser.Physics.P2#removeBodyNextStep + * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. + */ + removeBodyNextStep: function (body) { + + this._toRemove.push(body); + + }, + + /** + * Called at the start of the core update loop. Purges flagged bodies from the world. + * + * @method Phaser.Physics.P2#preUpdate + */ + preUpdate: function () { + + var i = this._toRemove.length; + + while (i--) + { + this.removeBody(this._toRemove[i]); + } + + this._toRemove.length = 0; + + }, + + /** + * This will create a P2 Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. + * + * @method Phaser.Physics.P2#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [debug=false] - Create a debug object to go with this body? + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, debug, children) { + + if (debug === undefined) { debug = false; } + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + this.enable(object[i].children, debug, children); + } + else + { + this.enableBody(object[i], debug); + + if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) + { + this.enable(object[i], debug, true); + } + } + } + } + else + { + if (object instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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); + } + } + } + + }, + + /** + * Creates a P2 Physics body on the given game object. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * @method Phaser.Physics.P2#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + * @param {boolean} debug - Create a debug object to go with this body? + */ + 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; + if (typeof object.anchor !== 'undefined') { + object.anchor.set(0.5); + } + } + + }, + + /** + * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. + * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. + * + * @method Phaser.Physics.P2#setImpactEvents + * @param {boolean} state - Set to true to enable impact events, or false to disable. + */ + setImpactEvents: function (state) { + + if (state) + { + this.world.on("impact", this.impactHandler, this); + } + else + { + this.world.off("impact", this.impactHandler, this); + } + + }, + + /** + * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. + * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. + * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. + * Returning `true` from the callback will ensure they are checked in the narrowphase. + * + * @method Phaser.Physics.P2#setPostBroadphaseCallback + * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. + * @param {object} context - The context under which the callback will be fired. + */ + 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); + } + + }, + + /** + * Internal handler for the postBroadphase event. + * + * @method Phaser.Physics.P2#postBroadphaseHandler + * @private + * @param {object} event - The event data. + */ + postBroadphaseHandler: function (event) { + + if (!this.postBroadphaseCallback || event.pairs.length === 0) + { + return; + } + + for (var i = event.pairs.length - 2; i >= 0; 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); + } + } + + }, + + /** + * Handles a p2 impact event. + * + * @method Phaser.Physics.P2#impactHandler + * @private + * @param {object} event - The event data. + */ + impactHandler: function (event) { + + if (event.bodyA.parent && event.bodyB.parent) + { + // Body vs. Body callbacks + 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); + } + + // Body vs. Group callbacks + 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); + } + } + + }, + + /** + * Handles a p2 begin contact event. + * + * @method Phaser.Physics.P2#beginContactHandler + * @param {object} event - The event data. + */ + beginContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + 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.bodyB, event.shapeA, event.shapeB, event.contactEquations); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations); + } + } + + }, + + /** + * Handles a p2 end contact event. + * + * @method Phaser.Physics.P2#endContactHandler + * @param {object} event - The event data. + */ + endContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); + + if (event.bodyA.parent) + { + event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA); + } + } + + }, + + /** + * Sets the bounds of the Physics world to match the Game.World dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * + * @method Phaser.Physics#setBoundsToWorld + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + 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); + + }, + + /** + * Sets the given material against the 4 bounds of this World. + * + * @method Phaser.Physics#setWorldMaterial + * @param {Phaser.Physics.P2.Material} material - The material to set. + * @param {boolean} [left=true] - If true will set the material on the left bounds wall. + * @param {boolean} [right=true] - If true will set the material on the right bounds wall. + * @param {boolean} [top=true] - If true will set the material on the top bounds wall. + * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. + */ + setWorldMaterial: function (material, left, right, top, bottom) { + + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (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; + } + + }, + + /** + * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. + * If you start to use your own collision groups then your objects will no longer collide with the bounds. + * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. + * + * @method Phaser.Physics.P2#updateBoundsCollisionGroup + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + updateBoundsCollisionGroup: function (setCollisionGroup) { + + if (setCollisionGroup === undefined) { setCollisionGroup = true; } + + var mask = (setCollisionGroup) ? this.boundsCollisionGroup.mask : this.everythingCollisionGroup.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; + } + + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.P2#setBounds + * @param {number} x - The x coordinate of the top-left corner of the bounds. + * @param {number} y - The y coordinate of the top-left corner of the bounds. + * @param {number} width - The width of the bounds. + * @param {number} height - The height of the bounds. + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { + + if (left === undefined) { left = this._boundsLeft; } + if (right === undefined) { right = this._boundsRight; } + if (top === undefined) { top = this._boundsTop; } + if (bottom === undefined) { bottom = this._boundsBottom; } + if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; } + + this.setupWall(left, 'left', x, y, 1.5707963267948966, setCollisionGroup); + this.setupWall(right, 'right', x + width, y, -1.5707963267948966, setCollisionGroup); + this.setupWall(top, 'top', x, y, -3.141592653589793, setCollisionGroup); + this.setupWall(bottom, 'bottom', x, y + height, 0, setCollisionGroup); + + // Remember the bounds settings in case they change later on via World.setBounds + this._boundsLeft = left; + this._boundsRight = right; + this._boundsTop = top; + this._boundsBottom = bottom; + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Internal method called by setBounds. Responsible for creating, updating or + * removing the wall body shapes. + * + * @method Phaser.Physics.P2#setupWall + * @private + * @param {boolean} create - True to create the wall shape, false to remove it. + * @param {string} wall - The wall segment to update. + * @param {number} x - The x coordinate of the wall. + * @param {number} y - The y coordinate of the wall. + * @param {float} angle - The angle of the wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setupWall: function (create, wall, x, y, angle, setCollisionGroup) { + + if (create) + { + // We need a left wall. Do we have one already? + if (this.walls[wall]) + { + this.walls[wall].position = [ this.pxmi(x), this.pxmi(y) ]; + } + else + { + this.walls[wall] = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: angle }); + this.walls[wall].addShape(new p2.Plane()); + + this.world.addBody(this.walls[wall]); + } + + if (setCollisionGroup) + { + this.walls[wall].shapes[0].collisionGroup = this.boundsCollisionGroup.mask; + } + } + else + { + if (this.walls[wall]) + { + this.world.removeBody(this.walls[wall]); + this.walls[wall] = null; + } + } + + }, + + /** + * Pauses the P2 World independent of the game pause state. + * + * @method Phaser.Physics.P2#pause + */ + pause: function() { + + this.paused = true; + + }, + + /** + * Resumes a paused P2 World. + * + * @method Phaser.Physics.P2#resume + */ + resume: function() { + + this.paused = false; + + }, + + /** + * Internal P2 update loop. + * + * @method Phaser.Physics.P2#update + */ + update: function () { + + // Do nothing if the physics engine was paused before + if (this.paused) + { + return; + } + + if (this.useElapsedTime) + { + this.world.step(this.game.time.physicsElapsed); + } + else + { + this.world.step(this.frameRate); + } + + }, + + /** + * Called by Phaser.Physics when a State swap occurs. + * Starts the begin and end Contact listeners again. + * + * @method Phaser.Physics.P2#reset + */ + reset: function () { + + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + this._collisionGroupID = 2; + + this.setBoundsToWorld(true, true, true, true, false); + + }, + + /** + * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. + * + * The P2 world is also cleared: + * + * * Removes all solver equations + * * Removes all constraints + * * Removes all bodies + * * Removes all springs + * * Removes all contact materials + * + * This is called automatically when you switch state. + * + * @method Phaser.Physics.P2#clear + */ + clear: function () { + + this.world.time = 0; + this.world.fixedStepTime = 0; + + // Remove all solver equations + if (this.world.solver && this.world.solver.equations.length) + { + this.world.solver.removeAllEquations(); + } + + // Remove all constraints + var cs = this.world.constraints; + + for (var i = cs.length - 1; i >= 0; i--) + { + this.world.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.world.bodies; + + for (var i = bodies.length - 1; i >= 0; i--) + { + this.world.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.world.springs; + + for (var i = springs.length - 1; i >= 0; i--) + { + this.world.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.world.contactMaterials; + + for (var i = cms.length - 1; i >= 0; i--) + { + this.world.removeContactMaterial(cms[i]); + } + + 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.boundsCollidesWith = []; + + // Remove the world bounds + this.walls = { left: null, right: null, top: null, bottom: null }; + + }, + + /** + * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. + * + * @method Phaser.Physics.P2#destroy + */ + destroy: function () { + + this.clear(); + + this.game = null; + + }, + + /** + * Add a body to the world. + * + * @method Phaser.Physics.P2#addBody + * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. + * @return {boolean} True if the Body was added successfully, otherwise false. + */ + addBody: function (body) { + + if (body.data.world) + { + return false; + } + else + { + this.world.addBody(body.data); + + this.onBodyAdded.dispatch(body); + + return true; + } + + }, + + /** + * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. + * + * @method Phaser.Physics.P2#removeBody + * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. + * @return {Phaser.Physics.P2.Body} The Body that was removed. + */ + removeBody: function (body) { + + if (body.data.world === this.world) + { + this.world.removeBody(body.data); + + this.onBodyRemoved.dispatch(body); + } + + return body; + + }, + + /** + * Adds a Spring to the world. + * + * @method Phaser.Physics.P2#addSpring + * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was added. + */ + addSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.addSpring(spring.data); + } + else + { + this.world.addSpring(spring); + } + + this.onSpringAdded.dispatch(spring); + + return spring; + + }, + + /** + * Removes a Spring from the world. + * + * @method Phaser.Physics.P2#removeSpring + * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was removed. + */ + removeSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.removeSpring(spring.data); + } + else + { + this.world.removeSpring(spring); + } + + this.onSpringRemoved.dispatch(spring); + + return spring; + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createDistanceConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} distance - The distance to keep between the bodies. + * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. + * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.DistanceConstraint} The constraint + */ + createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, 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, localAnchorA, localAnchorB, maxForce)); + } + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createGearConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [angle=0] - The relative angle + * @param {number} [ratio=1] - The gear ratio. + * @return {Phaser.Physics.P2.GearConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * The pivot points are given in world (pixel) coordinates. + * + * @method Phaser.Physics.P2#createRevoluteConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. + * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint + */ + createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + 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, worldPivot)); + } + + }, + + /** + * Locks the relative position between two bodies. + * + * @method Phaser.Physics.P2#createLockConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.LockConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Constraint that only allows bodies to move along a line, relative to each other. + * See http://www.iforce2d.net/b2dtut/joints-prismatic + * + * @method Phaser.Physics.P2#createPrismaticConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. + * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Adds a Constraint to the world. + * + * @method Phaser.Physics.P2#addConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. + */ + addConstraint: function (constraint) { + + this.world.addConstraint(constraint); + + this.onConstraintAdded.dispatch(constraint); + + return constraint; + + }, + + /** + * Removes a Constraint from the world. + * + * @method Phaser.Physics.P2#removeConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. + */ + removeConstraint: function (constraint) { + + this.world.removeConstraint(constraint); + + this.onConstraintRemoved.dispatch(constraint); + + return constraint; + + }, + + /** + * Adds a Contact Material to the world. + * + * @method Phaser.Physics.P2#addContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. + */ + addContactMaterial: function (material) { + + this.world.addContactMaterial(material); + + this.onContactMaterialAdded.dispatch(material); + + return material; + + }, + + /** + * Removes a Contact Material from the world. + * + * @method Phaser.Physics.P2#removeContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. + */ + removeContactMaterial: function (material) { + + this.world.removeContactMaterial(material); + + this.onContactMaterialRemoved.dispatch(material); + + return material; + + }, + + /** + * Gets a Contact Material based on the two given Materials. + * + * @method Phaser.Physics.P2#getContactMaterial + * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. + * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. + * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. + */ + getContactMaterial: function (materialA, materialB) { + + return this.world.getContactMaterial(materialA, materialB); + + }, + + /** + * Sets the given Material against all Shapes owned by all the Bodies in the given array. + * + * @method Phaser.Physics.P2#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. + * @param {array} bodies - An Array of Body objects that the given Material will be set on. + */ + setMaterial: function (material, bodies) { + + var i = bodies.length; + + while (i--) + { + bodies[i].setMaterial(material); + } + + }, + + /** + * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). + * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. + * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. + * + * @method Phaser.Physics.P2#createMaterial + * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. + * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. + * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. + */ + 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; + + }, + + /** + * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. + * + * @method Phaser.Physics.P2#createContactMaterial + * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {object} [options] - Material options object. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. + */ + createContactMaterial: function (materialA, materialB, options) { + + if (materialA === undefined) { materialA = this.createMaterial(); } + if (materialB === undefined) { materialB = this.createMaterial(); } + + var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); + + return this.addContactMaterial(contact); + + }, + + /** + * Populates and returns an array with references to of all current Bodies in the world. + * + * @method Phaser.Physics.P2#getBodies + * @return {array} An array containing all current Bodies in the world. + */ + getBodies: function () { + + var output = []; + var i = this.world.bodies.length; + + while (i--) + { + output.push(this.world.bodies[i].parent); + } + + return output; + + }, + + /** + * Checks the given object to see if it has a p2.Body and if so returns it. + * + * @method Phaser.Physics.P2#getBody + * @param {object} object - The object to check for a p2.Body on. + * @return {p2.Body} The p2.Body, or null if not found. + */ + getBody: function (object) { + + if (object instanceof p2.Body) + { + // Native p2 body + return object; + } + else if (object instanceof Phaser.Physics.P2.Body) + { + // Phaser P2 Body + return object.data; + } + else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) + { + // Sprite, TileSprite, etc + return object.body.data; + } + + return null; + + }, + + /** + * Populates and returns an array of all current Springs in the world. + * + * @method Phaser.Physics.P2#getSprings + * @return {array} An array containing all current Springs in the world. + */ + getSprings: function () { + + var output = []; + var i = this.world.springs.length; + + while (i--) + { + output.push(this.world.springs[i].parent); + } + + return output; + + }, + + /** + * Populates and returns an array of all current Constraints in the world. + * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain + * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type. + * + * @method Phaser.Physics.P2#getConstraints + * @return {array} An array containing all current Constraints in the world. + */ + getConstraints: function () { + + var output = []; + var i = this.world.constraints.length; + + while (i--) + { + output.push(this.world.constraints[i]); + } + + return output; + + }, + + /** + * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to + * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. + * + * @method Phaser.Physics.P2#hitTest + * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. + * @param {Array} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) + * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. + * @return {Array} Array of bodies that overlap the point. + */ + hitTest: function (worldPoint, bodies, precision, filterStatic) { + + if (bodies === undefined) { bodies = this.world.bodies; } + if (precision === undefined) { precision = 5; } + if (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.type === p2.Body.STATIC)) + { + query.push(bodies[i].data); + } + else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC)) + { + query.push(bodies[i]); + } + else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC)) + { + query.push(bodies[i].body.data); + } + } + + return this.world.hitTest(physicsPosition, query, precision); + + }, + + /** + * Converts the current world into a JSON object. + * + * @method Phaser.Physics.P2#toJSON + * @return {object} A JSON representation of the world. + */ + toJSON: function () { + + return this.world.toJSON(); + + }, + + /** + * Creates a new Collision Group and optionally applies it to the given object. + * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. + * + * @method Phaser.Physics.P2#createCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + */ + 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; + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. + * + * @method Phaser.Physics.P2y#setCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + */ + setCollisionGroup: function (object, group) { + + if (object instanceof Phaser.Group) + { + for (var i = 0; i < object.total; i++) + { + if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) + { + object.children[i].body.setCollisionGroup(group); + } + } + } + else + { + object.body.setCollisionGroup(group); + } + + }, + + /** + * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restLength=1] - Rest length of the spring. A number > 0. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @return {Phaser.Physics.P2.Spring} The spring + */ + createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); + } + + }, + + /** + * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createRotationalSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @return {Phaser.Physics.P2.RotationalSpring} The spring + */ + createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Rotational Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping)); + } + + }, + + /** + * Creates a new Body and adds it to the World. + * + * @method Phaser.Physics.P2#createBody + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {Phaser.Physics.P2.Body} The body + */ + createBody: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Creates a new Particle and adds it to the World. + * + * @method Phaser.Physics.P2#createParticle + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + */ + createParticle: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Converts all of the polyline, polygon, and rectangle objects inside a Tiled ObjectGroup into physics bodies that are added to the world. + * Note that the polylines and polygons must be created in such a way that they can withstand polygon decomposition. + * + * @method Phaser.Physics.P2#convertCollisionObjects + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. + * @return {array} An array of the Phaser.Physics.Body objects that have been created. + */ + convertCollisionObjects: function (map, layer, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var output = []; + + for (var i = 0, len = map.collision[layer].length; i < len; i++) + { + // name: json.layers[i].objects[v].name, + // x: json.layers[i].objects[v].x, + // y: json.layers[i].objects[v].y, + // width: json.layers[i].objects[v].width, + // height: json.layers[i].objects[v].height, + // visible: json.layers[i].objects[v].visible, + // properties: json.layers[i].objects[v].properties, + // polyline: json.layers[i].objects[v].polyline + + var object = map.collision[layer][i]; + var shapeData = object.polyline || object.polygon; + + // polyline/polygon shape data present + if (shapeData) + { + var body = this.createBody(object.x, object.y, 0, addToWorld, {}, shapeData); + } + + // tilemap parser sets rectangle=true when parsing object groups + else if (object.rectangle) + { + var body = this.createBody(object.x, object.y, 0, addToWorld); + body.addRectangle(object.width, object.height, object.width / 2, object.height / 2); + } + + // ellipse could be added here, but Tiled ellipses use height/width instead of radius + // (to support oblong ellipses), which p2 doesn't currently support. + + if (body) + { + output.push(body); + } + } + + return output; + + }, + + /** + * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. + * + * @method Phaser.Physics.P2#clearTilemapLayerBodies + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + */ + 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 = 0; + + }, + + /** + * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. + * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. + * Every time you call this method it will destroy any previously created bodies and remove them from the world. + * Therefore understand it's a very expensive operation and not to be done in a core game update loop. + * + * @method Phaser.Physics.P2#convertTilemap + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. + * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. + * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. + */ + convertTilemap: function (map, layer, addToWorld, optimize) { + + layer = map.getLayer(layer); + + if (addToWorld === undefined) { addToWorld = true; } + if (optimize === undefined) { optimize = true; } + + // If the bodies array is already populated we need to nuke it + this.clearTilemapLayerBodies(map, layer); + + var width = 0; + var sx = 0; + var sy = 0; + + for (var y = 0, h = map.layers[layer].height; y < h; y++) + { + width = 0; + + for (var x = 0, w = map.layers[layer].width; x < w; x++) + { + var tile = map.layers[layer].data[y][x]; + + if (tile && tile.index > -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; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpx + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpx: function (v) { + + return v *= 20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters). + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxm + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxm: function (v) { + + return v * 0.05; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpxi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpxi: function (v) { + + return v *= -20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters) and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxmi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxmi: function (v) { + + return v * -0.05; + + } + +}; + +/** +* @name Phaser.Physics.P2#friction +* @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { + + get: function () { + + return this.world.defaultContactMaterial.friction; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.friction = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#restitution +* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { + + get: function () { + + return this.world.defaultContactMaterial.restitution; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.restitution = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#contactMaterial +* @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { + + get: function () { + + return this.world.defaultContactMaterial; + + }, + + set: function (value) { + + this.world.defaultContactMaterial = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applySpringForces +* @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { + + get: function () { + + return this.world.applySpringForces; + + }, + + set: function (value) { + + this.world.applySpringForces = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyDamping +* @property {boolean} applyDamping - Enable to automatically apply body damping each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { + + get: function () { + + return this.world.applyDamping; + + }, + + set: function (value) { + + this.world.applyDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyGravity +* @property {boolean} applyGravity - Enable to automatically apply gravity each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { + + get: function () { + + return this.world.applyGravity; + + }, + + set: function (value) { + + this.world.applyGravity = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#solveConstraints +* @property {boolean} solveConstraints - Enable/disable constraint solving in each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { + + get: function () { + + return this.world.solveConstraints; + + }, + + set: function (value) { + + this.world.solveConstraints = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#time +* @property {boolean} time - The World time. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "time", { + + get: function () { + + return this.world.time; + + } + +}); + +/** +* @name Phaser.Physics.P2#emitImpactEvent +* @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { + + get: function () { + + return this.world.emitImpactEvent; + + }, + + set: function (value) { + + this.world.emitImpactEvent = value; + + } + +}); + +/** +* How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. +* If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. +* @name Phaser.Physics.P2#sleepMode +* @property {number} sleepMode +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", { + + get: function () { + + return this.world.sleepMode; + + }, + + set: function (value) { + + this.world.sleepMode = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#total +* @property {number} total - The total number of bodies in the world. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "total", { + + get: function () { + + return this.world.bodies.length; + + } + +}); + +/* jshint noarg: false */ + +/** +* @author Georgios Kaleadis https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Allow to access a list of created fixture (coming from Body#addPhaserPolygon) +* which itself parse the input from PhysicsEditor with the custom phaser exporter. +* You can access fixtures of a Body by a group index or even by providing a fixture Key. + +* You can set the fixture key and also the group index for a fixture in PhysicsEditor. +* This gives you the power to create a complex body built of many fixtures and modify them +* during runtime (to remove parts, set masks, categories & sensor properties) +* +* @class Phaser.Physics.P2.FixtureList +* @constructor +* @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) +*/ +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 = { + + /** + * @method Phaser.Physics.P2.FixtureList#init + */ + init: function () { + + /** + * @property {object} namedFixtures - Collect all fixtures with a key + * @private + */ + this.namedFixtures = {}; + + /** + * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group + * @private + */ + this.groupedFixtures = []; + + /** + * @property {Array} allFixtures - This is a list of everything in this collection + * @private + */ + this.allFixtures = []; + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setCategory + * @param {number} bit - The bit to set as the collision group. + * @param {string} fixtureKey - Only apply to the fixture with the given key. + */ + setCategory: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionGroup = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMask + * @param {number} bit - The bit to set as the collision mask + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMask: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionMask = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setSensor + * @param {boolean} value - sensor true or false + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setSensor: function (value, fixtureKey) { + + var setter = function(fixture) { + fixture.sensor = value; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMaterial + * @param {Object} material - The contact material for a fixture + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMaterial: function (material, fixtureKey) { + + var setter = function(fixture) { + fixture.material = material; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * Accessor to get either a list of specified fixtures by key or the whole fixture list + * + * @method Phaser.Physics.P2.FixtureList#getFixtures + * @param {array} keys - A list of fixture keys + */ + 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; + } + + }, + + /** + * Accessor to get either a single fixture by its key. + * + * @method Phaser.Physics.P2.FixtureList#getFixtureByKey + * @param {string} key - The key of the fixture. + */ + getFixtureByKey: function (key) { + + return this.namedFixtures[key]; + + }, + + /** + * Accessor to get a group of fixtures by its group index. + * + * @method Phaser.Physics.P2.FixtureList#getGroup + * @param {number} groupID - The group index. + */ + getGroup: function (groupID) { + + return this.groupedFixtures[groupID]; + + }, + + /** + * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon + * + * @method Phaser.Physics.P2.FixtureList#parse + */ + 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)); + } + + }, + + /** + * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. + * + * @method Phaser.Physics.P2.FixtureList#flatten + * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. + */ + 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; + + } + +}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. +* +* @class Phaser.Physics.P2.PointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.PointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; + +/** +* @name Phaser.Physics.P2.PointProxy#x +* @property {number} x - The x property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { + + get: function () { + + return this.world.mpx(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#y +* @property {number} y - The y property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { + + get: function () { + + return this.world.mpx(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#mx +* @property {number} mx - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#my +* @property {number} my - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. +* +* @class Phaser.Physics.P2.InversePointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.InversePointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; + +/** +* @name Phaser.Physics.P2.InversePointProxy#x +* @property {number} x - The x property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#y +* @property {number} y - The y property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#mx +* @property {number} mx - The x property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = -value; + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#my +* @property {number} my - The y property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = -value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. +* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. +* In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. +* By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. +* Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. +* Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. +* +* @class Phaser.Physics.P2.Body +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. +* @param {number} [x=0] - The x coordinate of this Body. +* @param {number} [y=0] - The y coordinate of this Body. +* @param {number} [mass=1] - The default mass of this Body (0 = static). +*/ +Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { + + sprite = sprite || null; + x = x || 0; + y = y || 0; + if (mass === undefined) { mass = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to the P2 World. + */ + this.world = game.physics.p2; + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.P2JS; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. + */ + this.offset = new Phaser.Point(); + + /** + * @property {p2.Body} data - The p2 Body data. + * @protected + */ + this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); + + this.data.parent = this; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. + */ + this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); + + /** + * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body. + */ + this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); + + /** + * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. + */ + this.gravity = new Phaser.Point(); + + /** + * Dispatched when a first contact is created between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 5 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body is in contact with. + * The Shape from this body that caused the contact. + * The Shape from the contact body. + * The Contact Equation data array. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * Dispatched when contact ends between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 4 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body has ended contact with. + * The Shape from this body that caused the original contact. + * The Shape from the contact body. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + /** + * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. + */ + this.collidesWith = []; + + /** + * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. + */ + this.removeNextStep = false; + + /** + * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. + */ + this.debugBody = null; + + /** + * @property {boolean} dirty - Internally used by Sprite.x/y + */ + this.dirty = false; + + /** + * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. + * @private + */ + this._collideWorldBounds = true; + + /** + * @property {object} _bodyCallbacks - Array of Body callbacks. + * @private + */ + this._bodyCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Body callback contexts. + * @private + */ + this._bodyCallbackContext = {}; + + /** + * @property {object} _groupCallbacks - Array of Group callbacks. + * @private + */ + this._groupCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. + * @private + */ + this._groupCallbackContext = {}; + + /** + * @property {boolean} _reset - Internal var. + * @private + */ + this._reset = false; + + // Set-up the default shape + if (sprite) + { + this.setRectangleFromSprite(sprite); + + if (sprite.exists) + { + this.game.physics.p2.addBody(this); + } + } + +}; + +Phaser.Physics.P2.Body.prototype = { + + /** + * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createBodyCallback + * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + 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; + } + } + + }, + + /** + * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * This callback will only fire if this Body has been assigned a collision group. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createGroupCallback + * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + createGroupCallback: function (group, callback, callbackContext) { + + if (callback === null) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + else + { + this._groupCallbacks[group.mask] = callback; + this._groupCallbackContext[group.mask] = callbackContext; + } + + }, + + /** + * Gets the collision bitmask from the groups this body collides with. + * + * @method Phaser.Physics.P2.Body#getCollisionMask + * @return {number} The bitmask. + */ + getCollisionMask: function () { + + var mask = 0; + + if (this._collideWorldBounds) + { + mask = this.game.physics.p2.boundsCollisionGroup.mask; + } + + for (var i = 0; i < this.collidesWith.length; i++) + { + mask = mask | this.collidesWith[i].mask; + } + + return mask; + + }, + + /** + * Updates the collisionMask. + * + * @method Phaser.Physics.P2.Body#updateCollisionMask + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + updateCollisionMask: function (shape) { + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * This also resets the collisionMask. + * + * @method Phaser.Physics.P2.Body#setCollisionGroup + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + setCollisionGroup: function (group, shape) { + + var mask = this.getCollisionMask(); + + if (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; + } + + }, + + /** + * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. + * + * @method Phaser.Physics.P2.Body#clearCollision + * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? + * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. + */ + clearCollision: function (clearGroup, clearMask, shape) { + + if (clearGroup === undefined) { clearGroup = true; } + if (clearMask === undefined) { clearMask = true; } + + if (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; + } + + }, + + /** + * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#removeCollisionGroup + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore. + * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body. + */ + removeCollisionGroup: function (group, clearCallback, shape) { + + if (clearCallback === undefined) { clearCallback = true; } + + var index; + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + index = this.collidesWith.indexOf(group[i]); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + } + else + { + index = this.collidesWith.indexOf(group); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#collides + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. + * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. + * @param {object} [callbackContext] - The context under which the callback will be called. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. + */ + collides: function (group, callback, callbackContext, shape) { + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + if (this.collidesWith.indexOf(group[i]) === -1) + { + this.collidesWith.push(group[i]); + + if (callback) + { + this.createGroupCallback(group[i], callback, callbackContext); + } + } + } + } + else + { + if (this.collidesWith.indexOf(group) === -1) + { + this.collidesWith.push(group); + + if (callback) + { + this.createGroupCallback(group, callback, callbackContext); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Moves the shape offsets so their center of mass becomes the body center of mass. + * + * @method Phaser.Physics.P2.Body#adjustCenterOfMass + */ + adjustCenterOfMass: function () { + + this.data.adjustCenterOfMass(); + this.shapeChanged(); + + }, + + /** + * Gets the velocity of a point in the body. + * + * @method Phaser.Physics.P2.Body#getVelocityAtPoint + * @param {Array} result - A vector to store the result in. + * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from. + * @return {Array} The result vector. + */ + getVelocityAtPoint: function (result, relativePoint) { + + return this.data.getVelocityAtPoint(result, relativePoint); + + }, + + /** + * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. + * + * @method Phaser.Physics.P2.Body#applyDamping + * @param {number} dt - Current time step. + */ + applyDamping: function (dt) { + + this.data.applyDamping(dt); + + }, + + /** + * Apply impulse to a point relative to the body. + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulse + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space. + * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + */ + applyImpulse: function (impulse, worldX, worldY) { + + this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Apply impulse to a point local to the body. + * + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulseLocal + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space. + * @param {number} localX - A local point on the body. + * @param {number} localY - A local point on the body. + */ + applyImpulseLocal: function (impulse, localX, localY) { + + this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]); + + }, + + /** + * Apply force to a world point. + * + * This could for example be a point on the RigidBody surface. Applying force + * this way will add to Body.force and Body.angularForce. + * + * @method Phaser.Physics.P2.Body#applyForce + * @param {Float32Array|Array} force - The force vector to add. + * @param {number} worldX - The world x point to apply the force on. + * @param {number} worldY - The world y point to apply the force on. + */ + applyForce: function (force, worldX, worldY) { + + this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Sets the force on the body to zero. + * + * @method Phaser.Physics.P2.Body#setZeroForce + */ + setZeroForce: function () { + + this.data.setZeroForce(); + + }, + + /** + * If this Body is dynamic then this will zero its angular velocity. + * + * @method Phaser.Physics.P2.Body#setZeroRotation + */ + setZeroRotation: function () { + + this.data.angularVelocity = 0; + + }, + + /** + * If this Body is dynamic then this will zero its velocity on both axis. + * + * @method Phaser.Physics.P2.Body#setZeroVelocity + */ + setZeroVelocity: function () { + + this.data.velocity[0] = 0; + this.data.velocity[1] = 0; + + }, + + /** + * Sets the Body damping and angularDamping to zero. + * + * @method Phaser.Physics.P2.Body#setZeroDamping + */ + setZeroDamping: function () { + + this.data.damping = 0; + this.data.angularDamping = 0; + + }, + + /** + * Transform a world point to local body frame. + * + * @method Phaser.Physics.P2.Body#toLocalFrame + * @param {Float32Array|Array} out - The vector to store the result in. + * @param {Float32Array|Array} worldPoint - The input world vector. + */ + toLocalFrame: function (out, worldPoint) { + + return this.data.toLocalFrame(out, worldPoint); + + }, + + /** + * Transform a local point to world frame. + * + * @method Phaser.Physics.P2.Body#toWorldFrame + * @param {Array} out - The vector to store the result in. + * @param {Array} localPoint - The input local vector. + */ + toWorldFrame: function (out, localPoint) { + + return this.data.toWorldFrame(out, localPoint); + + }, + + /** + * This will rotate the Body by the given speed to the left (counter-clockwise). + * + * @method Phaser.Physics.P2.Body#rotateLeft + * @param {number} speed - The speed at which it should rotate. + */ + rotateLeft: function (speed) { + + this.data.angularVelocity = this.world.pxm(-speed); + + }, + + /** + * This will rotate the Body by the given speed to the left (clockwise). + * + * @method Phaser.Physics.P2.Body#rotateRight + * @param {number} speed - The speed at which it should rotate. + */ + rotateRight: function (speed) { + + this.data.angularVelocity = this.world.pxm(speed); + + }, + + /** + * Moves the Body forwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveForward + * @param {number} speed - The speed at which it should move forwards. + */ + 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); + + }, + + /** + * Moves the Body backwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveBackward + * @param {number} speed - The speed at which it should move backwards. + */ + 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)); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrust + * @param {number} speed - The speed at which it should thrust. + */ + 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); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustLeft + * @param {number} speed - The speed at which it should move to the left. + */ + thrustLeft: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] += magnitude * Math.cos(angle); + this.data.force[1] += magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustRight + * @param {number} speed - The speed at which it should move to the right. + */ + thrustRight: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] -= magnitude * Math.cos(angle); + this.data.force[1] -= magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#reverse + * @param {number} speed - The speed at which it should reverse. + */ + 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); + + }, + + /** + * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveLeft + * @param {number} speed - The speed at which it should move to the left, in pixels per second. + */ + moveLeft: function (speed) { + + this.data.velocity[0] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveRight + * @param {number} speed - The speed at which it should move to the right, in pixels per second. + */ + moveRight: function (speed) { + + this.data.velocity[0] = this.world.pxmi(speed); + + }, + + /** + * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveUp + * @param {number} speed - The speed at which it should move up, in pixels per second. + */ + moveUp: function (speed) { + + this.data.velocity[1] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveDown + * @param {number} speed - The speed at which it should move down, in pixels per second. + */ + moveDown: function (speed) { + + this.data.velocity[1] = this.world.pxmi(speed); + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#preUpdate + * @protected + */ + preUpdate: function () { + + this.dirty = true; + + if (this.removeNextStep) + { + this.removeFromWorld(); + this.removeNextStep = false; + } + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#postUpdate + * @protected + */ + postUpdate: function () { + + this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x; + this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y; + + if (!this.fixedRotation) + { + this.sprite.rotation = this.data.angle; + } + + if (this.debugBody) + { + this.debugBody.updateSpriteTransform(); + } + + this.dirty = false; + + }, + + /** + * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. + * + * @method Phaser.Physics.P2.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new x position of the Body. + * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. + * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. + */ + reset: function (x, y, resetDamping, resetMass) { + + if (resetDamping === undefined) { resetDamping = false; } + if (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; + + }, + + /** + * Adds this physics body to the world. + * + * @method Phaser.Physics.P2.Body#addToWorld + */ + addToWorld: function () { + + if (this.game.physics.p2._toRemove) + { + for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) + { + if (this.game.physics.p2._toRemove[i] === this) + { + this.game.physics.p2._toRemove.splice(i, 1); + } + } + } + + if (this.data.world !== this.game.physics.p2.world) + { + this.game.physics.p2.addBody(this); + } + + }, + + /** + * Removes this physics body from the world. + * + * @method Phaser.Physics.P2.Body#removeFromWorld + */ + removeFromWorld: function () { + + if (this.data.world === this.game.physics.p2.world) + { + this.game.physics.p2.removeBodyNextStep(this); + } + + }, + + /** + * Destroys this Body and all references it holds to other objects. + * + * @method Phaser.Physics.P2.Body#destroy + */ + destroy: function () { + + this.removeFromWorld(); + + this.clearShapes(); + + this._bodyCallbacks = {}; + this._bodyCallbackContext = {}; + this._groupCallbacks = {}; + this._groupCallbackContext = {}; + + if (this.debugBody) + { + this.debugBody.destroy(true, true); + } + + this.debugBody = null; + + if (this.sprite) + { + this.sprite.body = null; + this.sprite = null; + } + + }, + + /** + * Removes all Shapes from this Body. + * + * @method Phaser.Physics.P2.Body#clearShapes + */ + clearShapes: function () { + + var i = this.data.shapes.length; + + while (i--) + { + this.data.removeShape(this.data.shapes[i]); + } + + this.shapeChanged(); + + }, + + /** + * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#addShape + + * @param {p2.Shape} shape - The shape to add to the body. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Shape} The shape that was added to the body. + */ + addShape: function (shape, offsetX, offsetY, rotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (rotation === undefined) { rotation = 0; } + + this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); + this.shapeChanged(); + + return shape; + + }, + + /** + * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Circle} The Circle shape that was added to the Body. + */ + addCircle: function (radius, offsetX, offsetY, rotation) { + + var shape = new p2.Circle({ radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addRectangle + * @param {number} width - The width of the rectangle in pixels. + * @param {number} height - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Box} The shape that was added to the Body. + */ + addRectangle: function (width, height, offsetX, offsetY, rotation) { + + var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addPlane + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Plane} The Plane shape that was added to the Body. + */ + addPlane: function (offsetX, offsetY, rotation) { + + var shape = new p2.Plane(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addParticle + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Particle} The Particle shape that was added to the Body. + */ + addParticle: function (offsetX, offsetY, rotation) { + + var shape = new p2.Particle(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Line shape to this Body. + * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addLine + * @param {number} length - The length of this line (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Line} The Line shape that was added to the Body. + */ + addLine: function (length, offsetX, offsetY, rotation) { + + var shape = new p2.Line({ length: this.world.pxm(length)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Capsule shape to this Body. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCapsule + * @param {number} length - The distance between the end points in pixels. + * @param {number} radius - Radius of the capsule in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Capsule} The Capsule shape that was added to the Body. + */ + addCapsule: function (length, radius, offsetX, offsetY, rotation) { + + var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. + * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. + * + * @method Phaser.Physics.P2.Body#addPolygon + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...]. In the first form **the array will mutate**. + * Or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {boolean} True on success, else false. + */ + addPolygon: function (options, points) { + + options = options || {}; + + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments, 1); + } + + var path = []; + + // Did they pass in a single array of points? + if (points.length === 1 && Array.isArray(points[0])) + { + path = points[0].slice(0); + } + else if (Array.isArray(points[0])) + { + path = points.slice(); + } + else if (typeof points[0] === 'number') + { + // We've a list of numbers + for (var i = 0, len = points.length; i < len; i += 2) + { + path.push([points[i], points[i + 1]]); + } + } + + // top and tail + var idx = path.length - 1; + + if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) + { + path.pop(); + } + + // Now process them into p2 values + for (var p = 0; p < path.length; p++) + { + path[p][0] = this.world.pxmi(path[p][0]); + path[p][1] = this.world.pxmi(path[p][1]); + } + + var result = this.data.fromPolygon(path, options); + + this.shapeChanged(); + + return result; + + }, + + /** + * Remove a shape from the body. Will automatically update the mass properties and bounding radius. + * + * @method Phaser.Physics.P2.Body#removeShape + * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. + * @return {boolean} True if the shape was found and removed, else false. + */ + removeShape: function (shape) { + + var result = this.data.removeShape(shape); + + this.shapeChanged(); + + return result; + }, + + /** + * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + */ + setCircle: function (radius, offsetX, offsetY, rotation) { + + this.clearShapes(); + + return this.addCircle(radius, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. + * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangle + * @param {number} [width=16] - The width of the rectangle in pixels. + * @param {number} [height=16] - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangle: function (width, height, offsetX, offsetY, rotation) { + + if (width === undefined) { width = 16; } + if (height === undefined) { height = 16; } + + this.clearShapes(); + + return this.addRectangle(width, height, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. + * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. + * If no Sprite is given it defaults to using the parent of this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangleFromSprite + * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangleFromSprite: function (sprite) { + + if (sprite === undefined) { sprite = this.sprite; } + + this.clearShapes(); + + return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); + + }, + + /** + * Adds the given Material to all Shapes that belong to this Body. + * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. + * + * @method Phaser.Physics.P2.Body#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. + */ + setMaterial: function (material, shape) { + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].material = material; + } + } + else + { + shape.material = material; + } + + }, + + /** + * Updates the debug draw if any body shapes change. + * + * @method Phaser.Physics.P2.Body#shapeChanged + */ + shapeChanged: function() { + + if (this.debugBody) + { + this.debugBody.draw(); + } + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * The shape data format is based on the output of the + * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for + * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor} + * + * @method Phaser.Physics.P2.Body#addPhaserPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. + * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. + * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList + */ + addPhaserPolygon: function (key, object) { + + var data = this.game.cache.getPhysicsData(key, object); + var createdFixtures = []; + + // Cycle through the fixtures + for (var i = 0; i < data.length; i++) + { + var fixtureData = data[i]; + var shapesOfFixture = this.addFixture(fixtureData); + + // Always add to a group + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); + + // if (unique) fixture key is provided + if (fixtureData.fixtureKey) + { + createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; + } + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return createdFixtures; + + }, + + /** + * Add a polygon fixture. This is used during #loadPolygon. + * + * @method Phaser.Physics.P2.Body#addFixture + * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. + * @return {array} An array containing the generated shapes for the given polygon. + */ + addFixture: function (fixtureData) { + + var generatedShapes = []; + + if (fixtureData.circle) + { + var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) }); + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + var offset = p2.vec2.create(); + offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); + offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); + + this.data.addShape(shape, offset); + generatedShapes.push(shape); + } + else + { + var polygons = fixtureData.polygons; + var cm = p2.vec2.create(); + + for (var i = 0; i < polygons.length; i++) + { + var shapes = polygons[i]; + var vertices = []; + + for (var s = 0; s < shapes.length; s += 2) + { + vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); + } + + var shape = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== shape.vertices.length; j++) + { + var v = shape.vertices[j]; + p2.vec2.sub(v, v, shape.centerOfMass); + } + + p2.vec2.scale(cm, shape.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + shape.updateTriangles(); + shape.updateCenterOfMass(); + shape.updateBoundingRadius(); + + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + this.data.addShape(shape, cm); + + generatedShapes.push(shape); + } + } + + return generatedShapes; + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * + * As well as reading the data from the Cache you can also pass `null` as the first argument and a + * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance. + * + * For more details see the format of the Lime / Corona Physics Editor export. + * + * @method Phaser.Physics.P2.Body#loadPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the + * data as the 2nd argument. + * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from, + * or if key is null pass the actual physics data object itself as this parameter. + * @param {number} [scale=1] - Optionally resize the loaded polygon. + * @return {boolean} True on success, else false. + */ + loadPolygon: function (key, object, scale) { + + if (key === null) + { + var data = object; + } + else + { + var data = this.game.cache.getPhysicsData(key, object); + } + + if (typeof scale !== "number") + { + scale = 1; + } + + // We've multiple Convex shapes, they should be CCW automatically + var cm = p2.vec2.create(); + + for (var i = 0; i < data.length; i++) + { + var vertices = []; + + for (var s = 0; s < data[i].shape.length; s += 2) + { + vertices.push([ + this.world.pxmi(data[i].shape[s] * scale), + this.world.pxmi(data[i].shape[s + 1] * scale) + ]); + } + + var c = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== c.vertices.length; j++) + { + var v = c.vertices[j]; + p2.vec2.sub(v, v, c.centerOfMass); + } + + p2.vec2.scale(cm, c.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + c.updateTriangles(); + c.updateCenterOfMass(); + c.updateBoundingRadius(); + + this.data.addShape(c, cm); + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return true; + + } + +}; + +Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; + +/** + * Dynamic body. Dynamic bodies body can move and respond to collisions and forces. + * @property DYNAMIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.DYNAMIC = 1; + +/** + * Static body. Static bodies do not move, and they do not respond to forces or collision. + * @property STATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.STATIC = 2; + +/** + * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. + * @property KINEMATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.KINEMATIC = 4; + +/** +* @name Phaser.Physics.P2.Body#static +* @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.STATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#dynamic +* @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#kinematic +* @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.KINEMATIC; + this.mass = 4; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#allowSleep +* @property {boolean} allowSleep - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { + + get: function () { + + return this.data.allowSleep; + + }, + + set: function (value) { + + if (value !== this.data.allowSleep) + { + this.data.allowSleep = value; + } + + } + +}); + +/** +* The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. +* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. +* If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#angle +* @property {number} angle - The angle of this Body in degrees. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); + + }, + + set: function(value) { + + this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#angularDamping +* @property {number} angularDamping - The angular damping acting acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { + + get: function () { + + return this.data.angularDamping; + + }, + + set: function (value) { + + this.data.angularDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularForce +* @property {number} angularForce - The angular force acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { + + get: function () { + + return this.data.angularForce; + + }, + + set: function (value) { + + this.data.angularForce = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularVelocity +* @property {number} angularVelocity - The angular velocity of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { + + get: function () { + + return this.data.angularVelocity; + + }, + + set: function (value) { + + this.data.angularVelocity = value; + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#damping +* @property {number} damping - The linear damping acting on the body in the velocity direction. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { + + get: function () { + + return this.data.damping; + + }, + + set: function (value) { + + this.data.damping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#fixedRotation +* @property {boolean} fixedRotation - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { + + get: function () { + + return this.data.fixedRotation; + + }, + + set: function (value) { + + if (value !== this.data.fixedRotation) + { + this.data.fixedRotation = value; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#inertia +* @property {number} inertia - The inertia of the body around the Z axis.. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { + + get: function () { + + return this.data.inertia; + + }, + + set: function (value) { + + this.data.inertia = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#mass +* @property {number} mass - The mass of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { + + get: function () { + + return this.data.mass; + + }, + + set: function (value) { + + if (value !== this.data.mass) + { + this.data.mass = value; + this.data.updateMassProperties(); + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#motionState +* @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { + + get: function () { + + return this.data.type; + + }, + + set: function (value) { + + if (value !== this.data.type) + { + this.data.type = value; + } + + } + +}); + +/** +* The angle of the Body in radians. +* If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#rotation +* @property {number} rotation - The angle of this Body in radians. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { + + get: function() { + + return this.data.angle; + + }, + + set: function(value) { + + this.data.angle = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#sleepSpeedLimit +* @property {number} sleepSpeedLimit - . +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { + + get: function () { + + return this.data.sleepSpeedLimit; + + }, + + set: function (value) { + + this.data.sleepSpeedLimit = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#x +* @property {number} x - The x coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.data.position[0]); + + }, + + set: function (value) { + + this.data.position[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#y +* @property {number} y - The y coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.data.position[1]); + + }, + + set: function (value) { + + this.data.position[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#id +* @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { + + get: function () { + + return this.data.id; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#debug +* @property {boolean} debug - Enable or disable debug drawing of this body +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { + + get: function () { + + return (this.debugBody !== null); + + }, + + set: function (value) { + + if (value && !this.debugBody) + { + // This will be added to the global space + this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); + } + else if (!value && this.debugBody) + { + this.debugBody.destroy(); + this.debugBody = null; + } + + } + +}); + +/** +* A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. +* Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. +* Also note that when you set this it will only affect Body shapes that already exist. If you then add further shapes to your Body +* after setting this it will *not* proactively set them to collide with the bounds. +* +* @name Phaser.Physics.P2.Body#collideWorldBounds +* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? +* @default true +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { + + get: function () { + + return this._collideWorldBounds; + + }, + + set: function (value) { + + if (value && !this._collideWorldBounds) + { + this._collideWorldBounds = true; + this.updateCollisionMask(); + } + else if (!value && this._collideWorldBounds) + { + this._collideWorldBounds = false; + this.updateCollisionMask(); + } + + } + +}); + +/** +* @author George https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Draws a P2 Body to a Graphics instance for visual debugging. +* Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. +* So use sparingly and rarely (if ever) in production code. +* +* Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you +* manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will +* need to manually adjust its BodyDebug as well. +* +* @class Phaser.Physics.P2.BodyDebug +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. +* @param {object} settings - Settings object. +*/ +Phaser.Physics.P2.BodyDebug = function(game, body, settings) { + + Phaser.Group.call(this, game); + + /** + * @property {object} defaultSettings - Default debug settings. + * @private + */ + var defaultSettings = { + pixelsPerLengthUnit: game.physics.p2.mpx(1), + debugPolygons: false, + lineWidth: 1, + alpha: 0.5 + }; + + this.settings = Object.assign(defaultSettings, settings); + + /** + * @property {number} ppu - Pixels per Length Unit. + */ + this.ppu = this.settings.pixelsPerLengthUnit; + this.ppu = -1 * this.ppu; + + /** + * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. + */ + this.body = body; + + /** + * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. + */ + this.canvas = new Phaser.Graphics(game); + + this.canvas.alpha = this.settings.alpha; + + this.add(this.canvas); + + this.draw(); + + this.updateSpriteTransform(); + +}; + +Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); +Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; + +Object.assign(Phaser.Physics.P2.BodyDebug.prototype, { + + /** + * Core update. + * + * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform + */ + updateSpriteTransform: function() { + + this.position.x = this.body.position[0] * this.ppu; + this.position.y = this.body.position[1] * this.ppu; + this.rotation = this.body.angle; + + }, + + /** + * Draws the P2 shapes to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#draw + */ + draw: function() { + + var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; + + obj = this.body; + sprite = this.canvas; + sprite.clear(); + color = parseInt(this.randomPastelHex(), 16); + lineColor = 0xff0000; + lw = this.lineWidth; + + if (obj instanceof p2.Body && obj.shapes.length) + { + var l = obj.shapes.length; + + i = 0; + + while (i !== l) + { + child = obj.shapes[i]; + offset = child.position || 0; + angle = child.angle || 0; + + if (child instanceof p2.Circle) + { + this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); + } + else if (child instanceof p2.Capsule) + { + this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw); + } + 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.Box) + { + this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); + } + else if (child instanceof p2.Convex) + { + verts = []; + vrot = p2.vec2.create(); + + for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _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]); + } + + i++; + } + } + + }, + + /** + * Draws a p2.Box to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawRectangle + * @private + */ + drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + g.beginFill(fillColor); + g.drawRect(x - w / 2, y - h / 2, w, h); + + }, + + /** + * Draws a p2.Circle to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCircle + * @private + */ + drawCircle: function(g, x, y, angle, radius, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + g.lineStyle(lineWidth, 0x000000, 1); + g.beginFill(color, 1.0); + g.drawCircle(x, y, -radius*2); + g.endFill(); + g.moveTo(x, y); + g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); + + }, + + /** + * Draws a p2.Line to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawLine + * @private + */ + drawLine: function(g, len, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth * 5, color, 1); + g.moveTo(-len / 2, 0); + g.lineTo(len / 2, 0); + + }, + + /** + * Draws a p2.Convex to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawConvex + * @private + */ + drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { + + var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + 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 = [0xff0000, 0x00ff00, 0x0000ff]; + 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, 0x000000, 1); + return g.drawCircle(offset[0], offset[1], lineWidth * 2); + } + + }, + + /** + * Draws a p2.Path to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPath + * @private + */ + drawPath: function(g, path, color, fillColor, lineWidth) { + + var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + if (typeof fillColor === "number") + { + g.beginFill(fillColor); + } + + lastx = null; + lasty = null; + i = 0; + + while (i < path.length) + { + v = path[i]; + x = v[0]; + y = v[1]; + + if (x !== lastx || y !== lasty) + { + if (i === 0) + { + g.moveTo(x, y); + } + else + { + p1x = lastx; + p1y = lasty; + p2x = x; + p2y = y; + p3x = path[(i + 1) % path.length][0]; + p3y = path[(i + 1) % path.length][1]; + area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); + + if (area !== 0) + { + g.lineTo(x, y); + } + } + lastx = x; + lasty = y; + } + + i++; + + } + + if (typeof fillColor === "number") + { + g.endFill(); + } + + if (path.length > 2 && typeof fillColor === "number") + { + g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); + g.lineTo(path[0][0], path[0][1]); + } + + }, + + /** + * Draws a p2.Plane to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPlane + * @private + */ + drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { + + var max, xd, yd; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + + 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); + + }, + + /** + * Draws a p2.Capsule to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCapsule + * @private + */ + drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + // Draw circles at ends + var c = Math.cos(angle); + var s = Math.sin(angle); + + g.beginFill(fillColor, 1); + g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2); + g.drawCircle( len/2*c + x, len/2*s + y, -radius * 2); + g.endFill(); + + // Draw rectangle + g.lineStyle(lineWidth, color, 0); + g.beginFill(fillColor, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.endFill(); + + // Draw lines in between + g.lineStyle(lineWidth, color, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + + }, + + /** + * Picks a random pastel color. + * + * @method Phaser.Physics.P2.BodyDebug#randomPastelHex + * @private + */ + 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); + + }, + + /** + * Converts from RGB to Hex. + * + * @method Phaser.Physics.P2.BodyDebug#rgbToHex + * @private + */ + rgbToHex: function(r, g, b) { + return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); + }, + + /** + * Component to hex conversion. + * + * @method Phaser.Physics.P2.BodyDebug#componentToHex + * @private + */ + componentToHex: function(c) { + + var hex; + hex = c.toString(16); + + if (hex.length === 2) + { + return hex; + } + else + { + return hex + '0'; + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.Spring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restLength=1] - Rest length of the spring. A number > 0. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +*/ +Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restLength === undefined) { restLength = 1; } + if (stiffness === undefined) { stiffness = 100; } + if (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]) ]; + } + + /** + * @property {p2.LinearSpring} data - The actual p2 spring object. + */ + this.data = new p2.LinearSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.RotationalSpring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +*/ +Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restAngle === undefined) { restAngle = null; } + if (stiffness === undefined) { stiffness = 100; } + if (damping === undefined) { damping = 1; } + + if (restAngle) + { + restAngle = world.pxm(restAngle); + } + + var options = { + restAngle: restAngle, + stiffness: stiffness, + damping: damping + }; + + /** + * @property {p2.RotationalSpring} data - The actual p2 spring object. + */ + this.data = new p2.RotationalSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A P2 Material. +* +* \o/ ~ "Because I'm a Material girl" +* +* @class Phaser.Physics.P2.Material +* @constructor +* @param {string} name - The user defined name given to this Material. +*/ +Phaser.Physics.P2.Material = function (name) { + + /** + * @property {string} name - The user defined name given to this Material. + * @default + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Defines a physics material +* +* @class Phaser.Physics.P2.ContactMaterial +* @constructor +* @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. +* @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. +* @param {object} [options] - Additional configuration options. +*/ +Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { + + /** + * @property {number} id - The contact material identifier. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. + */ + + /** + * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. + */ + + /** + * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. + */ + + /** + * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + */ + + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Collision Group +* +* @class Phaser.Physics.P2.CollisionGroup +* @constructor +* @param {number} bitmask - The CollisionGroup bitmask. +*/ +Phaser.Physics.P2.CollisionGroup = function (bitmask) { + + /** + * @property {number} mask - The CollisionGroup bitmask. + */ + this.mask = bitmask; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A constraint that tries to keep the distance between two bodies constant. +* +* @class Phaser.Physics.P2.DistanceConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} distance - The distance to keep between the bodies. +* @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. +* @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. +* @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply. +*/ +Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { + + if (distance === undefined) { distance = 100; } + if (localAnchorA === undefined) { localAnchorA = [0, 0]; } + if (localAnchorB === undefined) { localAnchorB = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + distance = world.pxm(distance); + + localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ]; + localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ]; + + var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce }; + + p2.DistanceConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); +Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.GearConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [angle=0] - The relative angle +* @param {number} [ratio=1] - The gear ratio. +*/ +Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { + + if (angle === undefined) { angle = 0; } + if (ratio === undefined) { ratio = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Locks the relative position between two bodies. +* +* @class Phaser.Physics.P2.LockConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [angle=0] - The angle of bodyB in bodyA's frame. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { + + if (offset === undefined) { offset = [0, 0]; } + if (angle === undefined) { angle = 0; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.PrismaticConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. +* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { + + if (lockRotation === undefined) { lockRotation = true; } + if (anchorA === undefined) { anchorA = [0, 0]; } + if (anchorB === undefined) { anchorB = [0, 0]; } + if (axis === undefined) { axis = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* The pivot points are given in world (pixel) coordinates. +* +* @class Phaser.Physics.P2.RevoluteConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {p2.Body} bodyB - Second connected body. +* @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. +* @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. +*/ +Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + if (worldPivot === undefined) { worldPivot = null; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; + pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; + + if (worldPivot) + { + worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ]; + } + + var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce }; + + p2.RevoluteConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); +Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image Collection is a special tileset containing mulitple images, with no slicing into each image. +* +* Image Collections are normally created automatically when Tiled data is loaded. +* +* @class Phaser.ImageCollection +* @constructor +* @param {string} name - The name of the image collection in the map data. +* @param {integer} firstgid - The first image index this image collection contains. +* @param {integer} [width=32] - Width of widest image (in pixels). +* @param {integer} [height=32] - Height of tallest image (in pixels). +* @param {integer} [margin=0] - The margin around all images in the collection (in pixels). +* @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). +* @param {object} [properties={}] - Custom Image Collection properties. +*/ +Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Image Collection. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of the widest image (in pixels). + * @property {integer} imageWidth + * @readonly + */ + this.imageWidth = width | 0; + + /** + * The height of the tallest image (in pixels). + * @property {integer} imageHeight + * @readonly + */ + this.imageHeight = height | 0; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageMarge + * @readonly + */ + // Modified internally + this.imageMargin = margin | 0; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageSpacing + * @readonly + */ + this.imageSpacing = spacing | 0; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached images that are a part of this collection. + * @property {array} images + * @readonly + */ + // Modified internally + this.images = []; + + /** + * The total number of images in the image collection. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; +}; + +Phaser.ImageCollection.prototype = { + + /** + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.ImageCollection#containsImageIndex + * @param {integer} imageIndex - The image index to search for. + * @return {boolean} True if this Image Collection contains the given index. + */ + containsImageIndex: function (imageIndex) { + + return ( + imageIndex >= this.firstgid && + imageIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Add an image to this Image Collection. + * + * @method Phaser.ImageCollection#addImage + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + */ + addImage: function (gid, image) { + + this.images.push({ gid: gid, image: image }); + this.total++; + + } + +}; + +Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile is a representation of a single tile within the Tilemap. +* +* @class Phaser.Tile +* @constructor +* @param {object} layer - The layer in the Tilemap data that this tile belongs to. +* @param {number} index - The index of this tile type in the core map data. +* @param {number} x - The x coordinate of this tile. +* @param {number} y - The y coordinate of this tile. +* @param {number} width - Width of the tile. +* @param {number} height - Height of the tile. +*/ +Phaser.Tile = function (layer, index, x, y, width, height) { + + /** + * @property {object} layer - The layer in the Tilemap data that this tile belongs to. + */ + this.layer = layer; + + /** + * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. + */ + this.index = index; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.x = x; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.y = y; + + /** + * @property {number} rotation - The rotation angle of this tile. + */ + this.rotation = 0; + + /** + * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not. + */ + this.flipped = false; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.worldX = x * width; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.worldY = y * height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.height = height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.centerX = Math.abs(width / 2); + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.centerY = Math.abs(height / 2); + + /** + * @property {number} alpha - The alpha value at which this tile is drawn to the canvas. + */ + this.alpha = 1; + + /** + * @property {object} properties - Tile specific properties. + */ + this.properties = {}; + + /** + * @property {boolean} scanned - Has this tile been walked / turned into a poly? + */ + this.scanned = false; + + /** + * @property {boolean} faceTop - Is the top of this tile an interesting edge? + */ + this.faceTop = false; + + /** + * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge? + */ + this.faceBottom = false; + + /** + * @property {boolean} faceLeft - Is the left of this tile an interesting edge? + */ + this.faceLeft = false; + + /** + * @property {boolean} faceRight - Is the right of this tile an interesting edge? + */ + this.faceRight = false; + + /** + * @property {boolean} collideLeft - Indicating collide with any object on the left. + * @default + */ + this.collideLeft = false; + + /** + * @property {boolean} collideRight - Indicating collide with any object on the right. + * @default + */ + this.collideRight = false; + + /** + * @property {boolean} collideUp - Indicating collide with any object on the top. + * @default + */ + this.collideUp = false; + + /** + * @property {boolean} collideDown - Indicating collide with any object on the bottom. + * @default + */ + this.collideDown = false; + + /** + * @property {function} collisionCallback - Tile collision callback. + * @default + */ + this.collisionCallback = null; + + /** + * @property {object} collisionCallbackContext - The context in which the collision callback will be called. + * @default + */ + this.collisionCallbackContext = this; + + /** + * @property {boolean} debug + * @default + */ + this.debug = false; + +}; + +Phaser.Tile.prototype = { + + /** + * Check if the given x and y world coordinates are within this Tile. + * + * @method Phaser.Tile#containsPoint + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ + containsPoint: function (x, y) { + + return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom); + + }, + + /** + * Check for intersection with this tile. + * + * @method Phaser.Tile#intersects + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + */ + 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; + + }, + + /** + * Set a callback to be called when this tile is hit by an object. + * The callback must true true for collision processing to take place. + * + * @method Phaser.Tile#setCollisionCallback + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + */ + setCollisionCallback: function (callback, context) { + + this.collisionCallback = callback; + this.collisionCallbackContext = context; + + }, + + /** + * Clean up memory. + * + * @method Phaser.Tile#destroy + */ + destroy: function () { + + this.collisionCallback = null; + this.collisionCallbackContext = null; + this.properties = null; + + }, + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tile#setCollision + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} right - Indicating collide with any object on the right. + * @param {boolean} up - Indicating collide with any object on the top. + * @param {boolean} down - Indicating collide with any object on the bottom. + */ + setCollision: function (left, right, up, down) { + + this.collideLeft = left; + this.collideRight = right; + this.collideUp = up; + this.collideDown = down; + + this.faceLeft = left; + this.faceRight = right; + this.faceTop = up; + this.faceBottom = down; + + }, + + /** + * Reset collision status flags. + * + * @method Phaser.Tile#resetCollision + */ + 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; + + }, + + /** + * Is this tile interesting? + * + * @method Phaser.Tile#isInteresting + * @param {boolean} collides - If true will check any collides value. + * @param {boolean} faces - If true will check any face value. + * @return {boolean} True if the Tile is interesting, otherwise false. + */ + isInteresting: function (collides, faces) { + + if (collides && faces) + { + // Does this tile have any collide flags OR interesting face? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback); + } + else if (collides) + { + // Does this tile collide? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + else if (faces) + { + // Does this tile have an interesting face? + return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); + } + + return false; + + }, + + /** + * Copies the tile data and properties from the given tile to this tile. + * + * @method Phaser.Tile#copy + * @param {Phaser.Tile} tile - The tile to copy from. + */ + 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; + +/** +* @name Phaser.Tile#collides +* @property {boolean} collides - True if this tile can collide on any of its faces. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "collides", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + +}); + +/** +* @name Phaser.Tile#canCollide +* @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "canCollide", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); + } + +}); + +/** +* @name Phaser.Tile#left +* @property {number} left - The x value in pixels. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "left", { + + get: function () { + return this.worldX; + } + +}); + +/** +* @name Phaser.Tile#right +* @property {number} right - The sum of the x and width properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "right", { + + get: function () { + return this.worldX + this.width; + } + +}); + +/** +* @name Phaser.Tile#top +* @property {number} top - The y value. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "top", { + + get: function () { + return this.worldY; + } + +}); + +/** +* @name Phaser.Tile#bottom +* @property {number} bottom - The sum of the y and height properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "bottom", { + + get: function () { + return this.worldY + this.height; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. +* +* Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org +* +* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. +* When using CSV data you must provide the key and the tileWidth and tileHeight parameters. +* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. +* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. +* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. +* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. +* +* @class Phaser.Tilemap +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. +* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +*/ +Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {string} key - The key of this map data in the Phaser.Cache. + */ + this.key = key; + + var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height); + + if (data === null) + { + return; + } + + /** + * @property {number} width - The width of the map (in tiles). + */ + this.width = data.width; + + /** + * @property {number} height - The height of the map (in tiles). + */ + this.height = data.height; + + /** + * @property {number} tileWidth - The base width of the tiles in the map (in pixels). + */ + this.tileWidth = data.tileWidth; + + /** + * @property {number} tileHeight - The base height of the tiles in the map (in pixels). + */ + this.tileHeight = data.tileHeight; + + /** + * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + */ + this.orientation = data.orientation; + + /** + * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + */ + this.format = data.format; + + /** + * @property {number} version - The version of the map data (as specified in Tiled, usually 1). + */ + this.version = data.version; + + /** + * @property {object} properties - Map specific properties as specified in Tiled. + */ + this.properties = data.properties; + + /** + * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth. + */ + this.widthInPixels = data.widthInPixels; + + /** + * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight. + */ + this.heightInPixels = data.heightInPixels; + + /** + * @property {array} layers - An array of Tilemap layer data. + */ + this.layers = data.layers; + + /** + * @property {array} tilesets - An array of Tilesets. + */ + this.tilesets = data.tilesets; + + /** + * @property {array} imagecollections - An array of Image Collections. + */ + this.imagecollections = data.imagecollections; + + /** + * @property {array} tiles - The super array of Tiles. + */ + this.tiles = data.tiles; + + /** + * @property {array} objects - An array of Tiled Object Layers. + */ + this.objects = data.objects; + + /** + * @property {array} collideIndexes - An array of tile indexes that collide. + */ + this.collideIndexes = []; + + /** + * @property {array} collision - An array of collision data (polylines, etc). + */ + this.collision = data.collision; + + /** + * @property {array} images - An array of Tiled Image Layers. + */ + this.images = data.images; + + /** + * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data. + */ + this.enableDebug = false; + + /** + * @property {number} currentLayer - The current layer. + */ + this.currentLayer = 0; + + /** + * @property {array} debugMap - Map data used for debug values only. + */ + this.debugMap = []; + + /** + * @property {array} _results - Internal var. + * @private + */ + this._results = []; + + /** + * @property {number} _tempA - Internal var. + * @private + */ + this._tempA = 0; + + /** + * @property {number} _tempB - Internal var. + * @private + */ + this._tempB = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.CSV = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.TILED_JSON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.NORTH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.EAST = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.SOUTH = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.WEST = 3; + +Phaser.Tilemap.prototype = { + + /** + * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. + * + * @method Phaser.Tilemap#create + * @param {string} name - The name of the default layer of the map. + * @param {number} width - The width of the map in tiles. + * @param {number} height - The height of the map in tiles. + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + create: function (name, width, height, tileWidth, tileHeight, group) { + + if (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); + + }, + + /** + * Sets the base tile size for the map. + * + * @method Phaser.Tilemap#setTileSize + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + */ + setTileSize: function (tileWidth, tileHeight) { + + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.widthInPixels = this.width * tileWidth; + this.heightInPixels = this.height * tileHeight; + + }, + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. + * + * @method Phaser.Tilemap#addTilesetImage + * @param {string} tileset - The name of the tileset as specified in the map data. + * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset. + * If `undefined` or `null` it will look for an image with a key matching the tileset parameter. + * You can also pass in a BitmapData which can be used instead of an Image. + * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. + * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. + * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. + * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. + * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. + * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed. + */ + addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { + + if (tileset === undefined) { return null; } + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (gid === undefined) { gid = 0; } + + // In-case we're working from a blank map + if (tileWidth === 0) + { + tileWidth = 32; + } + + if (tileHeight === 0) + { + tileHeight = 32; + } + + var img = null; + + if (key === undefined || key === null) + { + key = tileset; + } + + if (key instanceof Phaser.BitmapData) + { + img = key.canvas; + } + else + { + if (!this.game.cache.checkImageKey(key)) + { + console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"'); + return null; + } + + img = this.game.cache.getImage(key); + } + + var idx = this.getTilesetIndex(tileset); + + if (idx === null && this.format === Phaser.Tilemap.TILED_JSON) + { + console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + tileset + '"'); + console.log('Tilesets: ', this.tilesets); + return null; + } + + if (this.tilesets[idx]) + { + this.tilesets[idx].setImage(img); + return this.tilesets[idx]; + } + else + { + var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {}); + + newSet.setImage(img); + + 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; t < gid + newSet.total; t++) + { + this.tiles[t] = [x, y, i]; + + x += tileWidth + tileSpacing; + + count++; + + if (count === newSet.total) + { + break; + } + + countX++; + + if (countX === newSet.columns) + { + x = tileMargin; + y += tileHeight + tileSpacing; + + countX = 0; + countY++; + + if (countY === newSet.rows) + { + break; + } + } + } + + return newSet; + + } + + return null; + + }, + + /** + * Creates a Sprite for every {@link http://doc.mapeditor.org/reference/tmx-map-format/#object object} matching the `gid` argument. You can optionally specify the group that the Sprite will be created in. If none is + * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to + * configure Sprite properties from within the map editor. For example giving an object a property of `alpha: 0.5` in the map editor will duplicate that when the + * Sprite is created. You could also give it a value like: `body.velocity.x: 100` to set it moving automatically. + * + * The `gid` argument is matched against: + * + * 1. For a tile object, the tile identifier (`gid`); or + * 2. The object's unique ID (`id`); or + * 3. The object's `name` (a string) + * + * @method Phaser.Tilemap#createFromObjects + * @param {string} name - The name of the Object Group to create Sprites from. + * @param {number|string} gid - The object's tile reference (gid), unique ID (id) or name. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. + * @param {boolean} [exists=true] - The default exists state of the Sprite. + * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. + * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. + * @param {boolean} [adjustSize=true] - By default the width and height of the objects are transferred to the sprite. This parameter controls that behavior. + */ + createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY, adjustSize) { + + if (exists === undefined) { exists = true; } + if (autoCull === undefined) { autoCull = false; } + if (group === undefined) { group = this.game.world; } + if (CustomClass === undefined) { CustomClass = Phaser.Sprite; } + if (adjustY === undefined) { adjustY = true; } + if (adjustSize === undefined) { adjustSize = true; } + + if (!this.objects[name]) + { + console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name); + console.log('Objects: ', this.objects); + return; + } + + for (var i = 0; i < this.objects[name].length; i++) + { + var found = false; + var obj = this.objects[name][i]; + + if (obj.gid !== undefined && typeof gid === 'number' && obj.gid === gid) + { + found = true; + } + else if (obj.id !== undefined && typeof gid === 'number' && obj.id === gid) + { + found = true; + } + else if (obj.name !== undefined && typeof gid === 'string' && obj.name === gid) + { + found = true; + } + + if (found) + { + var sprite = new CustomClass(this.game, parseFloat(obj.x, 10), parseFloat(obj.y, 10), key, frame); + + sprite.name = obj.name; + sprite.autoCull = autoCull; + sprite.exists = exists; + sprite.visible = obj.visible; + + if (adjustSize) + { + if (obj.width) + { + sprite.width = obj.width; + } + + if (obj.height) + { + sprite.height = obj.height; + } + } + + if (obj.rotation) + { + sprite.angle = obj.rotation; + } + + if (adjustY) + { + sprite.y -= sprite.height; + } + + group.add(sprite); + + for (var property in obj.properties) + { + group.set(sprite, property, obj.properties[property], false, false, 0, true); + } + } + } + + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the map data. + * You can specify the group that the Sprite will be created in. If none is given it will be created in the World. + * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special + * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemap#createFromTiles + * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from. + * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. + * @return {integer} The number of Sprites that were created. + */ + createFromTiles: function (tiles, replacements, key, layer, group, properties) { + + if (typeof tiles === 'number') { tiles = [tiles]; } + + if (replacements === undefined || replacements === null) + { + replacements = []; + } + else if (typeof replacements === 'number') + { + replacements = [replacements]; + } + + layer = this.getLayer(layer); + + if (group === undefined) { group = this.game.world; } + if (properties === undefined) { properties = {}; } + + if (properties.customClass === undefined) + { + properties.customClass = Phaser.Sprite; + } + + if (properties.adjustY === undefined) + { + properties.adjustY = true; + } + + var lw = this.layers[layer].width; + var lh = this.layers[layer].height; + + this.copy(0, 0, lw, lh, layer); + + if (this._results.length < 2) + { + return 0; + } + + var total = 0; + var sprite; + + for (var i = 1, len = this._results.length; i < len; i++) + { + if (tiles.indexOf(this._results[i].index) !== -1) + { + sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key); + + for (var property in properties) + { + sprite[property] = properties[property]; + } + + group.add(sprite); + total++; + } + + } + + if (replacements.length === 1) + { + // Assume 1 replacement for all types of tile given + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer); + } + } + else if (replacements.length > 1) + { + // Assume 1 for 1 mapping + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer); + } + } + + return total; + + }, + + /** + * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. + * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. + * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. + * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. + * + * @method Phaser.Tilemap#createLayer + * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. + * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. + * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. + * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. + */ + createLayer: function (layer, width, height, group) { + + // Add Buffer support for the left of the canvas + + if (width === undefined) { width = this.game.width; } + if (height === undefined) { height = this.game.height; } + if (group === undefined) { group = this.game.world; } + + var index = layer; + + if (typeof layer === 'string') + { + index = this.getLayerIndex(layer); + } + + if (index === null || index > this.layers.length) + { + console.warn('Tilemap.createLayer: Invalid layer ID given: "' + layer + '"'); + console.log('Layers: ', this.layers); + return; + } + + // Sort out the display dimensions, so they never render too much, or too little. + + if (width === undefined || width <= 0) + { + width = Math.min(this.game.width, this.layers[index].widthInPixels); + } + else if (width > this.game.width) + { + width = this.game.width; + } + + if (height === undefined || height <= 0) + { + height = Math.min(this.game.height, this.layers[index].heightInPixels); + } + else if (height > this.game.height) + { + height = this.game.height; + } + + if (this.enableDebug) + { + console.group('Tilemap.createLayer'); + console.log('Name:', this.layers[index].name); + console.log('Size:', width, 'x', height); + console.log('Tileset:', this.tilesets[0].name, 'index:', index); + } + + var rootLayer = group.add(new Phaser.TilemapLayer(this.game, this, index, width, height)); + + if (this.enableDebug) + { + console.groupEnd(); + } + + return rootLayer; + + }, + + + /** + * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. + * + * @method Phaser.Tilemap#createBlankLayer + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {number} width - The width of the layer in tiles. + * @param {number} height - The height of the layer in tiles. + * @param {number} tileWidth - The width of the tiles the layer uses for calculations. + * @param {number} tileHeight - The height of the tiles the layer uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) { + + if (group === undefined) { group = this.game.world; } + + if (this.getLayerIndex(name) !== null) + { + console.warn('Tilemap.createBlankLayer: Layer with matching name already exists: ' + name); + 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; y < height; y++) + { + row = []; + + for (var x = 0; x < width; x++) + { + row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight)); + } + + output.push(row); + } + + layer.data = output; + + this.layers.push(layer); + + this.currentLayer = this.layers.length - 1; + + var w = layer.widthInPixels; + var h = layer.heightInPixels; + + if (w > this.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); + + }, + + /** + * Gets the layer index based on the layers name. + * + * @method Phaser.Tilemap#getIndex + * @protected + * @param {array} location - The local array to search. + * @param {string} name - The name of the array element to get. + * @return {number} The index of the element in the array, or null if not found. + */ + getIndex: function (location, name) { + + for (var i = 0; i < location.length; i++) + { + if (location[i].name === name) + { + return i; + } + } + + return null; + + }, + + /** + * Gets the layer index based on its name. + * + * @method Phaser.Tilemap#getLayerIndex + * @param {string} name - The name of the layer to get. + * @return {number} The index of the layer in this tilemap, or null if not found. + */ + getLayerIndex: function (name) { + + return this.getIndex(this.layers, name); + + }, + + /** + * Gets the tileset index based on its name. + * + * @method Phaser.Tilemap#getTilesetIndex + * @param {string} name - The name of the tileset to get. + * @return {number} The index of the tileset in this tilemap, or null if not found. + */ + getTilesetIndex: function (name) { + + return this.getIndex(this.tilesets, name); + + }, + + /** + * Gets the image index based on its name. + * + * @method Phaser.Tilemap#getImageIndex + * @param {string} name - The name of the image to get. + * @return {number} The index of the image in this tilemap, or null if not found. + */ + getImageIndex: function (name) { + + return this.getIndex(this.images, name); + + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileIndexCallback + * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileIndexCallback: function (indexes, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes]; + } + else + { + // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much + // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit. + this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext }; + } + } + else + { + for (var i = 0, len = indexes.length; i < len; i++) + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes[i]]; + } + else + { + this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext }; + } + } + } + + }, + + /** + * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileLocationCallback + * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} width - The width of the area to copy (given in tiles, not pixels) + * @param {number} height - The height of the area to copy (given in tiles, not pixels) + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].setCollisionCallback(callback, callbackContext); + } + + }, + + /** + * Sets collision on the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [2, 3, 15, 20]. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * Collision-enabled tiles can be collided against Sprites using {@link Phaser.Physics.Arcade#collide}. + * + * You can verify the collision faces by enabling {@link Phaser.TilemapLayer#debug}. + * + * @method Phaser.Tilemap#setCollision + * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollision: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + return this.setCollisionByIndex(indexes, collides, layer, true); + } + else if (Array.isArray(indexes)) + { + // Collide all of the IDs given in the indexes array + for (var i = 0; i < indexes.length; i++) + { + this.setCollisionByIndex(indexes[i], collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + } + + }, + + /** + * Sets collision on a range of tiles where the tile IDs increment sequentially. + * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionBetween + * @param {number} start - The first index of the tile to be set for collision. + * @param {number} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionBetween: function (start, stop, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (start > stop) + { + return; + } + + for (var index = start; index <= stop; index++) + { + this.setCollisionByIndex(index, collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision on all tiles in the given layer, except for the IDs of those in the given array. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionByExclusion + * @param {array} indexes - An array of the tile IDs to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByExclusion: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + // Collide everything, except the IDs given in the indexes array + for (var i = 0, len = this.tiles.length; i < len; i++) + { + if (indexes.indexOf(i) === -1) + { + this.setCollisionByIndex(i, collides, layer, false); + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision values on a tile in the set. + * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. + * + * @method Phaser.Tilemap#setCollisionByIndex + * @protected + * @param {number} index - The index of the tile on the layer. + * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile. + * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByIndex: function (index, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (layer === undefined) { layer = this.currentLayer; } + if (recalculate === undefined) { recalculate = true; } + + if (collides) + { + this.collideIndexes.push(index); + } + else + { + var i = this.collideIndexes.indexOf(index); + + if (i > -1) + { + this.collideIndexes.splice(i, 1); + } + } + + for (var y = 0; y < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile && tile.index === index) + { + if (collides) + { + tile.setCollision(true, true, true, true); + } + else + { + tile.resetCollision(); + } + + tile.faceTop = collides; + tile.faceBottom = collides; + tile.faceLeft = collides; + tile.faceRight = collides; + } + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + return layer; + + }, + + /** + * Gets the TilemapLayer index as used in the setCollision calls. + * + * @method Phaser.Tilemap#getLayer + * @protected + * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer. + * @return {number} The TilemapLayer index. + */ + getLayer: function (layer) { + + if (layer === undefined) + { + layer = this.currentLayer; + } + else if (typeof layer === 'string') + { + var layerArg = layer; + + layer = this.getLayerIndex(layer); + + if (!layer) + { + console.warn('No such layer name: ' + layerArg); + } + } + else if (layer instanceof Phaser.TilemapLayer) + { + layer = layer.index; + } + + return layer; + + }, + + /** + * Turn off/on the recalculation of faces for tile or collision updates. + * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. + * + * @method Phaser.Tilemap#setPreventRecalculate + * @param {boolean} value - If true it will put the recalculation on hold. + */ + setPreventRecalculate: function (value) { + + if (value === true && this.preventingRecalculate !== true) + { + this.preventingRecalculate = true; + this.needToRecalculate = {}; + } + + if (value === false && this.preventingRecalculate === true) + { + this.preventingRecalculate = false; + + for (var i in this.needToRecalculate) + { + this.calculateFaces(i); + } + + this.needToRecalculate = false; + } + + }, + + /** + * Internal function. + * + * @method Phaser.Tilemap#calculateFaces + * @protected + * @param {number} layer - The index of the TilemapLayer to operate on. + */ + calculateFaces: function (layer) { + + if (this.preventingRecalculate) + { + this.needToRecalculate[layer] = true; + return; + } + + var above = null; + var below = null; + var left = null; + var right = null; + + for (var y = 0, h = this.layers[layer].height; y < h; y++) + { + for (var x = 0, w = this.layers[layer].width; x < w; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile) + { + above = this.getTileAbove(layer, x, y); + below = this.getTileBelow(layer, x, y); + left = this.getTileLeft(layer, x, y); + right = this.getTileRight(layer, x, y); + + if (tile.collides) + { + tile.faceTop = true; + tile.faceBottom = true; + tile.faceLeft = true; + tile.faceRight = true; + } + + if (above && above.collides) + { + // There is a tile above this one that also collides, so the top of this tile is no longer interesting + tile.faceTop = false; + } + + if (below && below.collides) + { + // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting + tile.faceBottom = false; + } + + if (left && left.collides) + { + // There is a tile left this one that also collides, so the left of this tile is no longer interesting + tile.faceLeft = false; + } + + if (right && right.collides) + { + // There is a tile right this one that also collides, so the right of this tile is no longer interesting + tile.faceRight = false; + } + } + } + } + + }, + + /** + * Gets the tile above the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileAbove + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileAbove: function (layer, x, y) { + + if (y > 0) + { + return this.layers[layer].data[y - 1][x]; + } + + return null; + + }, + + /** + * Gets the tile below the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileBelow + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileBelow: function (layer, x, y) { + + if (y < this.layers[layer].height - 1) + { + return this.layers[layer].data[y + 1][x]; + } + + return null; + + }, + + /** + * Gets the tile to the left of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileLeft + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileLeft: function (layer, x, y) { + + if (x > 0) + { + return this.layers[layer].data[y][x - 1]; + } + + return null; + + }, + + /** + * Gets the tile to the right of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileRight + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileRight: function (layer, x, y) { + + if (x < this.layers[layer].width - 1) + { + return this.layers[layer].data[y][x + 1]; + } + + return null; + + }, + + /** + * Sets the current layer to the given index. + * + * @method Phaser.Tilemap#setLayer + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + */ + setLayer: function (layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer]) + { + this.currentLayer = layer; + } + + }, + + /** + * Checks if there is a tile at the given location. + * + * @method Phaser.Tilemap#hasTile + * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels) + * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + * @return {boolean} True if there is a tile at the given location, otherwise false. + */ + hasTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined) + { + return false; + } + + return (this.layers[layer].data[y][x].index > -1); + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. + * + * @method Phaser.Tilemap#removeTile + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.hasTile(x, y, layer)) + { + var tile = this.layers[layer].data[y][x]; + + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight); + + this.layers[layer].dirty = true; + + this.calculateFaces(layer); + + return tile; + } + } + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#removeTileWorldXY + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTileWorldXY: function (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.removeTile(x, y, layer); + + }, + + /** + * Puts a tile of the given index value at the coordinate specified. + * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. + * + * @method Phaser.Tilemap#putTile + * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map. + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + putTile: function (tile, x, y, layer) { + + if (tile === null) + { + return this.removeTile(x, y, layer); + } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + var index; + + if (tile instanceof Phaser.Tile) + { + index = tile.index; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].copy(tile); + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height); + } + } + else + { + index = tile; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].index = index; + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight); + } + } + + if (this.collideIndexes.indexOf(index) > -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; + + }, + + /** + * Puts a tile into the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#putTileWorldXY + * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object. + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + 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); + + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. + * If no match is found it returns null. + * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. + * + * @method Phaser.Tilemap#searchTileIndex + * @param {number} index - The tile index value to search for. + * @param {number} [skip=0] - The number of times to skip a matching tile before returning. + * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @return {Phaser.Tile} The first (or n skipped) tile with the matching index. + */ + searchTileIndex: function (index, skip, reverse, layer) { + + if (skip === undefined) { skip = 0; } + if (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 < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + if (this.layers[layer].data[y][x].index === index) + { + if (c === skip) + { + return this.layers[layer].data[y][x]; + } + else + { + c++; + } + } + } + } + } + + return null; + + }, + + /** + * Gets a tile from the Tilemap Layer. The coordinates are given in tile values. + * + * @method Phaser.Tilemap#getTile + * @param {number} x - X position to get the tile from (given in tile units, not pixels) + * @param {number} y - Y position to get the tile from (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTile: function (x, y, layer, nonNull) { + + if (nonNull === undefined) { nonNull = false; } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.layers[layer].data[y][x].index === -1) + { + if (nonNull) + { + return this.layers[layer].data[y][x]; + } + else + { + return null; + } + } + else + { + return this.layers[layer].data[y][x]; + } + } + else + { + return null; + } + + }, + + /** + * Gets a tile from the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#getTileWorldXY + * @param {number} x - X position to get the tile from (given in pixels) + * @param {number} y - Y position to get the tile from (given in pixels) + * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used. + * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates. + */ + getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) { + + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + + layer = this.getLayer(layer); + + x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; + y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; + + return this.getTile(x, y, layer, nonNull); + + }, + + /** + * Copies all of the tiles in the given rectangular block into the tilemap data buffer. + * + * @method Phaser.Tilemap#copy + * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} width - The width of the area to copy (given in tiles, not pixels) + * @param {integer} height - The height of the area to copy (given in tiles, not pixels) + * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from. + * @return {array} An array of the tiles that were copied. + */ + copy: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + if (!this.layers[layer]) + { + this._results.length = 0; + return; + } + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.layers[layer].width; } + if (height === undefined) { height = this.layers[layer].height; } + + if (x < 0) + { + x = 0; + } + + if (y < 0) + { + y = 0; + } + + if (width > this.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; ty < y + height; ty++) + { + for (var tx = x; tx < x + width; tx++) + { + this._results.push(this.layers[layer].data[ty][tx]); + } + } + + return this._results; + + }, + + /** + * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. + * + * @method Phaser.Tilemap#paste + * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels) + * @param {array} tileblock - The block of tiles to paste. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into. + */ + paste: function (x, y, tileblock, layer) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + layer = this.getLayer(layer); + + if (!tileblock || tileblock.length < 2) + { + return; + } + + // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste + var diffX = x - tileblock[1].x; + var diffY = y - tileblock[1].y; + + for (var i = 1; i < tileblock.length; i++) + { + this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]); + } + + this.layers[layer].dirty = true; + this.calculateFaces(layer); + + }, + + /** + * Scans the given area for tiles with an index matching tileA and swaps them with tileB. + * + * @method Phaser.Tilemap#swap + * @param {number} tileA - First tile index. + * @param {number} tileB - Second tile index. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + swap: function (tileA, tileB, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._tempA = tileA; + this._tempB = tileB; + + this._results.forEach(this.swapHandler, this); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Internal function that handles the swapping of tiles. + * + * @method Phaser.Tilemap#swapHandler + * @private + * @param {number} value + */ + swapHandler: function (value) { + + if (value.index === this._tempA) + { + // Swap A with B + value.index = this._tempB; + } + else if (value.index === this._tempB) + { + // Swap B with A + value.index = this._tempA; + } + + }, + + /** + * For each tile in the given area defined by x/y and width/height run the given callback. + * + * @method Phaser.Tilemap#forEach + * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {number} context - The context under which the callback should be run. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + forEach: function (callback, context, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._results.forEach(callback, context); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. + * + * @method Phaser.Tilemap#replace + * @param {number} source - The tile index value to scan for. + * @param {number} dest - The tile index value to replace found tiles with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + replace: function (source, dest, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + if (this._results[i].index === source) + { + this._results[i].index = dest; + } + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Randomises a set of tiles in a given area. + * + * @method Phaser.Tilemap#random + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + random: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + var idx = this._results[t].index; + + if (indexes.indexOf(idx) === -1) + { + indexes.push(idx); + } + } + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = this.game.rnd.pick(indexes); + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! + * + * @method Phaser.Tilemap#shuffle + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + shuffle: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + indexes.push(this._results[t].index); + } + } + + Phaser.ArrayUtils.shuffle(indexes); + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = indexes[i - 1]; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Fills the given area with the specified tile. + * + * @method Phaser.Tilemap#fill + * @param {number} index - The index of the tile that the area will be filled with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + fill: function (index, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = index; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Removes all layers from this tile map. + * + * @method Phaser.Tilemap#removeAllLayers + */ + removeAllLayers: function () { + + this.layers.length = 0; + this.currentLayer = 0; + + }, + + /** + * Dumps the tilemap data out to the console. + * + * @method Phaser.Tilemap#dump + */ + dump: function () { + + var txt = ''; + var args = ['']; + + for (var y = 0; y < this.layers[this.currentLayer].height; y++) + { + for (var x = 0; x < this.layers[this.currentLayer].width; x++) + { + txt += "%c "; + + if (this.layers[this.currentLayer].data[y][x] > 1) + { + 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); + + }, + + /** + * Removes all layer data from this tile map and nulls the game reference. + * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. + * + * @method Phaser.Tilemap#destroy + */ + destroy: function () { + + this.removeAllLayers(); + this.data = []; + this.game = null; + + } + +}; + +Phaser.Tilemap.prototype.constructor = Phaser.Tilemap; + +/** +* @name Phaser.Tilemap#layer +* @property {number|string|Phaser.TilemapLayer} layer - The current layer object. +*/ +Object.defineProperty(Phaser.Tilemap.prototype, "layer", { + + get: function () { + + return this.layers[this.currentLayer]; + + }, + + set: function (value) { + + if (value !== this.currentLayer) + { + this.setLayer(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. +* +* Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. +* +* By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. +* +* @class Phaser.TilemapLayer +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs. +* @param {integer} index - The index of the TileLayer to render within the Tilemap. +* @param {integer} width - Width of the renderable area of the layer (in pixels). +* @param {integer} height - Height of the renderable area of the layer (in pixels). +*/ +Phaser.TilemapLayer = function (game, tilemap, index, width, height) { + + width |= 0; + height |= 0; + + Phaser.Sprite.call(this, game, 0, 0); + + /** + * The Tilemap to which this layer is bound. + * @property {Phaser.Tilemap} map + * @protected + * @readonly + */ + this.map = tilemap; + + /** + * The index of this layer within the Tilemap. + * @property {number} index + * @protected + * @readonly + */ + this.index = index; + + /** + * The layer object within the Tilemap that this layer represents. + * @property {object} layer + * @protected + * @readonly + */ + this.layer = tilemap.layers[index]; + + /** + * The canvas to which this TilemapLayer draws. + * @property {HTMLCanvasElement} canvas + * @protected + */ + this.canvas = Phaser.CanvasPool.create(this, width, height); + + /** + * The 2d context of the canvas. + * @property {CanvasRenderingContext2D} context + * @private + */ + this.context = this.canvas.getContext('2d'); + + this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas, null, this.game.resolution))); + + /** + * The const type of this object. + * @property {number} type + * @readonly + * @protected + * @default Phaser.TILEMAPLAYER + */ + this.type = Phaser.TILEMAPLAYER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.TILEMAPLAYER; + + /** + * Settings that control standard (non-diagnostic) rendering. + * + * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view. + * This can greatly improve scrolling rendering performance, especially when there are many small tiles. + * It should only be disabled in rare cases. + * + * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas. + * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior + * in some browsers, notably Safari. + * + * @default + */ + this.renderSettings = { + enableScrollDelta: true, + overdrawRatio: 0.20, + copyCanvas: null + }; + + /** + * Enable an additional "debug rendering" pass to display collision information. + * + * @property {boolean} debug + * @default + */ + this.debug = false; + + /** + * @property {boolean} exists - Controls if the core game loop and physics update this game object or not. + */ + this.exists = true; + + /** + * Settings used for debugging and diagnostics. + * + * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. + * + * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. + * + * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. + * + * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. + * + */ + this.debugSettings = { + + missingImageFill: 'rgb(255,255,255)', + debuggedTileOverfill: 'rgba(0,255,0,0.4)', + + forceFullRedraw: true, + + debugAlpha: 0.5, + facingEdgeStroke: 'rgba(0,255,0,1)', + collidingTileOverfill: 'rgba(0,255,0,0.2)' + + }; + + /** + * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). + * @property {number} scrollFactorX + * @public + * @default + */ + this.scrollFactorX = 1; + + /** + * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) + * @property {number} scrollFactorY + * @public + * @default + */ + this.scrollFactorY = 1; + + /** + * If true tiles will be force rendered, even if such is not believed to be required. + * @property {boolean} dirty + * @protected + */ + this.dirty = true; + + /** + * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. + * @property {integer} rayStepRate + * @default + */ + this.rayStepRate = 4; + + /** + * Flag controlling if the layer tiles wrap at the edges. + * @property {boolean} _wrap + * @private + */ + this._wrap = false; + + /** + * Local map data and calculation cache. + * @property {object} _mc + * @private + */ + this._mc = { + + // Used to bypass rendering without reliance on `dirty` and detect changes. + scrollX: 0, + scrollY: 0, + renderWidth: 0, + renderHeight: 0, + + tileWidth: tilemap.tileWidth, + tileHeight: tilemap.tileHeight, + + // Collision width/height (pixels) + // What purpose do these have? Most things use tile width/height directly. + // This also only extends collisions right and down. + cw: tilemap.tileWidth, + ch: tilemap.tileHeight, + + // Cached tilesets from index -> Tileset + tilesets: [] + + }; + + /** + * The current canvas left after scroll is applied. + * @property {number} _scrollX + * @private + */ + this._scrollX = 0; + + /** + * The current canvas top after scroll is applied. + * @property {number} _scrollY + * @private + */ + this._scrollY = 0; + + /** + * The position offset of the layer's tiles. + * @property {Phaser.Point} + */ + this.tileOffset = new Phaser.Point(this.layer.offsetX || 0, this.layer.offsetY || 0); + + /** + * Used for caching the tiles / array of tiles. + * @property {Phaser.Tile[]} _results + * @private + */ + this._results = []; + + if (!game.device.canvasBitBltShift) + { + this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas(); + } + + this.fixedToCamera = true; + +}; + +Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer; + +Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* The shared double-copy canvas, created as needed. +* +* @private +* @static +*/ +Phaser.TilemapLayer.sharedCopyCanvas = null; + +/** +* Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. +* +* Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. +* +* @method Phaser.TilemapLayer#ensureSharedCopyCanvas +* @protected +* @static +*/ +Phaser.TilemapLayer.ensureSharedCopyCanvas = function () { + + if (!this.sharedCopyCanvas) + { + this.sharedCopyCanvas = Phaser.CanvasPool.create(this, 2, 2); + } + + return this.sharedCopyCanvas; + +}; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TilemapLayer#preUpdate +*/ +Phaser.TilemapLayer.prototype.preUpdate = function() { + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.postUpdate. Handles cache updates. +* +* @method Phaser.TilemapLayer#postUpdate +* @protected +*/ +Phaser.TilemapLayer.prototype.postUpdate = function () { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderCanvas function. +* +* @method Phaser.TilemapLayer#_renderCanvas +* @private +*/ +Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderWebGL function. +* +* @method Phaser.TilemapLayer#_renderWebGL +* @private +*/ +Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Destroys this TilemapLayer. +* +* @method Phaser.TilemapLayer#destroy +*/ +Phaser.TilemapLayer.prototype.destroy = function() { + + Phaser.CanvasPool.remove(this); + + Phaser.Component.Destroy.prototype.destroy.call(this); + +}; + +/** +* Resizes the internal canvas and texture frame used by this TilemapLayer. +* +* This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully +* selected times. +* +* Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not +* modified either. You will have to handle both of these things from your game code if required. +* +* @method Phaser.TilemapLayer#resize +* @param {number} width - The new width of the TilemapLayer +* @param {number} height - The new height of the TilemapLayer +*/ +Phaser.TilemapLayer.prototype.resize = function (width, height) { + + this.canvas.width = width; + this.canvas.height = height; + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.texture.baseTexture.width = width; + this.texture.baseTexture.height = height; + + this.texture.baseTexture.dirty(); + this.texture.requiresUpdate = true; + + this.texture._updateUvs(); + + this.dirty = true; + +}; + +/** +* Sets the world size to match the size of this layer. +* +* @method Phaser.TilemapLayer#resizeWorld +* @public +*/ +Phaser.TilemapLayer.prototype.resizeWorld = function () { + + this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y); + +}; + +/** + * Get the X axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getLayerOffsetX + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetX = function () { + + return this.tileOffset.x || ((!this.fixedToCamera) ? this.position.x : 0); + +}; + +/** + * Get the Y axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getTileOffsetY + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetY = function () { + + return this.tileOffset.y || ((!this.fixedToCamera) ? this.position.y : 0); + +}; + +/** +* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixX +* @private +* @param {number} x - x coordinate in camera space +* @return {number} x coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixX = function (x) { + + if (this.scrollFactorX === 1 || (this.scrollFactorX === 0 && this.position.x === 0)) + { + return x; + } + + // This executes if the scrollFactorX is 0 and the x position of the tilemap is off from standard. + if (this.scrollFactorX === 0 && this.position.x !== 0) + { + return x - this.position.x; + } + + return this._scrollX + (x - (this._scrollX / this.scrollFactorX)); + +}; + +/** +* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixX +* @private +* @param {number} x - x coordinate in scrollFactor-adjusted dimensions +* @return {number} x coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixX = function (x) { + + if (this.scrollFactorX === 1) + { + return x; + } + + return (this._scrollX / this.scrollFactorX) + (x - this._scrollX); + +}; + +/** +* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixY +* @private +* @param {number} y - y coordinate in camera space +* @return {number} y coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixY = function (y) { + + if (this.scrollFactorY === 1 || (this.scrollFactorY === 0 && this.position.y === 0)) + { + return y; + } + + // This executes if the scrollFactorY is 0 and the y position of the tilemap is off from standard. + if (this.scrollFactorY === 0 && this.position.y !== 0) + { + return y - this.position.y; + } + + return this._scrollY + (y - (this._scrollY / this.scrollFactorY)); + +}; + +/** +* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixY +* @private +* @param {number} y - y coordinate in scrollFactor-adjusted dimensions +* @return {number} y coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixY = function (y) { + + if (this.scrollFactorY === 1) + { + return y; + } + + return (this._scrollY / this.scrollFactorY) + (y - this._scrollY); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileX +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @return {integer} The X map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileX = function (x) { + + // var tileWidth = this.tileWidth * this.scale.x; + return Math.floor(this._fixX(x) / this._mc.tileWidth); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileY +* @public +* @param {number} y - Y position of the point in target tile (in pixels). +* @return {integer} The Y map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileY = function (y) { + + // var tileHeight = this.tileHeight * this.scale.y; + return Math.floor(this._fixY(y) / this._mc.tileHeight); + +}; + +/** +* Convert a pixel coordinate to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileXY +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @param {number} y - Y position of the point in target tile (in pixels). +* @param {(Phaser.Point|object)} point - The Point/object to update. +* @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set. +*/ +Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) { + + point.x = this.getTileX(x); + point.y = this.getTileY(y); + + return point; + +}; + +/** +* Gets all tiles that intersect with the given line. +* +* @method Phaser.TilemapLayer#getRayCastTiles +* @public +* @param {Phaser.Line} line - The line used to determine which tiles to return. +* @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`. +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {Phaser.Tile[]} An array of Phaser.Tiles. +*/ +Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) { + + if (!stepRate) { stepRate = this.rayStepRate; } + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + // First get all tiles that touch the bounds of the line + var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace); + + if (tiles.length === 0) + { + return []; + } + + // Now we only want the tiles that intersect with the points on this line + var coords = line.coordinatesOnLine(stepRate); + var results = []; + + for (var i = 0; i < tiles.length; i++) + { + for (var t = 0; t < coords.length; t++) + { + var tile = tiles[i]; + var coord = coords[t]; + if (tile.containsPoint(coord[0], coord[1])) + { + results.push(tile); + break; + } + } + } + + return results; + +}; + +/** +* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. +* +* @method Phaser.TilemapLayer#getTiles +* @public +* @param {number} x - X position of the top left corner (in pixels). +* @param {number} y - Y position of the top left corner (in pixels). +* @param {number} width - Width of the area to get (in pixels). +* @param {number} height - Height of the area to get (in pixels). +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {array} An array of Tiles. +*/ +Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) { + + // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all) + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + var fetchAll = !(collides || interestingFace); + + // Adjust the x,y coordinates for scrollFactor + x = this._fixX(x); + y = this._fixY(y); + + // Convert the pixel values into tile coordinates + var tx = Math.floor(x / (this._mc.cw * this.scale.x)); + var ty = Math.floor(y / (this._mc.ch * this.scale.y)); + // Don't just use ceil(width/cw) to allow account for x/y diff within cell + var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx; + var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty; + + while (this._results.length) + { + this._results.pop(); + } + + for (var wy = ty; wy < ty + th; wy++) + { + for (var wx = tx; wx < tx + tw; wx++) + { + var row = this.layer.data[wy]; + + if (row && row[wx]) + { + if (fetchAll || row[wx].isInteresting(collides, interestingFace)) + { + this._results.push(row[wx]); + } + } + } + } + + return this._results.slice(); + +}; + +/** +* Returns the appropriate tileset for the index, updating the internal cache as required. +* This should only be called if `tilesets[index]` evaluates to undefined. +* +* @method Phaser.TilemapLayer#resolveTileset +* @private +* @param {integer} Tile index +* @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping. +*/ +Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) { + + var tilesets = this._mc.tilesets; + + // Try for dense array if reasonable + if (tileIndex < 2000) + { + while (tilesets.length < tileIndex) + { + tilesets.push(undefined); + } + } + + var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2]; + + if (setIndex !== null) + { + var tileset = this.map.tilesets[setIndex]; + + if (tileset && tileset.containsTileIndex(tileIndex)) + { + return (tilesets[tileIndex] = tileset); + } + } + + return (tilesets[tileIndex] = null); + +}; + +/** +* The TilemapLayer caches tileset look-ups. +* +* Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. +* +* @method Phaser.TilemapLayer#resetTilesetCache +* @public +*/ +Phaser.TilemapLayer.prototype.resetTilesetCache = function () { + + var tilesets = this._mc.tilesets; + + while (tilesets.length) + { + tilesets.pop(); + } + +}; + +/** + * This method will set the scale of the tilemap as well as update the underlying block data of this layer. + * + * @method Phaser.TilemapLayer#setScale + * @param {number} [xScale=1] - The scale factor along the X-plane + * @param {number} [yScale] - The scale factor along the Y-plane + */ +Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) { + + xScale = xScale || 1; + yScale = yScale || xScale; + + for (var y = 0; y < this.layer.data.length; y++) + { + var row = this.layer.data[y]; + + for (var x = 0; x < row.length; x++) + { + var tile = row[x]; + + tile.width = this.map.tileWidth * xScale; + tile.height = this.map.tileHeight * yScale; + + tile.worldX = tile.x * tile.width; + tile.worldY = tile.y * tile.height; + } + } + + this.scale.setTo(xScale, yScale); + +}; + +/** +* Shifts the contents of the canvas - does extra math so that different browsers agree on the result. +* +* The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in. +* +* @method Phaser.TilemapLayer#shiftCanvas +* @private +* @param {CanvasRenderingContext2D} context - The context to shift +* @param {integer} x +* @param {integer} y +*/ +Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) { + + var canvas = context.canvas; + var copyW = canvas.width - Math.abs(x); + var copyH = canvas.height - Math.abs(y); + + // When x/y non-negative + var dx = 0; + var dy = 0; + var sx = x; + var sy = y; + + if (x < 0) + { + dx = -x; + sx = 0; + } + + if (y < 0) + { + dy = -y; + sy = 0; + } + + var copyCanvas = this.renderSettings.copyCanvas; + + if (copyCanvas) + { + // Use a second copy buffer, without slice support, for Safari .. again. + // Ensure copy canvas is large enough + if (copyCanvas.width < copyW || copyCanvas.height < copyH) + { + copyCanvas.width = copyW; + copyCanvas.height = copyH; + } + + var copyContext = copyCanvas.getContext('2d'); + copyContext.clearRect(0, 0, copyW, copyH); + copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH); + // clear allows default 'source-over' semantics + context.clearRect(sx, sy, copyW, copyH); + context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH); + } + else + { + // Avoids a second copy but flickers in Safari / Safari Mobile + // Ref. https://github.com/photonstorm/phaser/issues/1439 + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH); + context.restore(); + } + +}; + +/** +* Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor. +* This will constrain the tile coordinates based on wrapping but not physical coordinates. +* +* @method Phaser.TilemapLayer#renderRegion +* @private +* @param {integer} scrollX - Render x offset/scroll. +* @param {integer} scrollY - Render y offset/scroll. +* @param {integer} left - Leftmost column to render. +* @param {integer} top - Topmost row to render. +* @param {integer} right - Rightmost column to render. +* @param {integer} bottom - Bottommost row to render. +*/ +Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) { + + var context = this.context; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var tilesets = this._mc.tilesets; + var lastAlpha = NaN; + + if (!this._wrap) + { + if (left <= right) // Only adjust if going to render + { + left = Math.max(0, left); + right = Math.min(width - 1, right); + } + if (top <= bottom) + { + top = Math.max(0, top); + bottom = Math.min(height - 1, bottom); + } + } + + // top-left pixel of top-left cell + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values. + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + // tx/ty - are pixel coordinates where tile is drawn + // x/y - is cell location, normalized [0..width/height) in loop + // xmax/ymax - remaining cells to render on column/row + var tx, ty, x, y, xmax, ymax; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + + if (!tile || tile.index < 0) + { + continue; + } + + var index = tile.index; + + var set = tilesets[index]; + + if (set === undefined) + { + set = this.resolveTileset(index); + } + + // Setting the globalAlpha is "surprisingly expensive" in Chrome (38) + if (tile.alpha !== lastAlpha && !this.debug) + { + context.globalAlpha = tile.alpha; + lastAlpha = tile.alpha; + } + + if (set) + { + if (tile.rotation || tile.flipped) + { + context.save(); + context.translate(tx + tile.centerX, ty + tile.centerY); + context.rotate(tile.rotation); + + if (tile.flipped) + { + context.scale(-1, 1); + } + + set.draw(context, -tile.centerX, -tile.centerY, index); + context.restore(); + } + else + { + set.draw(context, tx, ty, index); + } + } + else if (this.debugSettings.missingImageFill) + { + context.fillStyle = this.debugSettings.missingImageFill; + context.fillRect(tx, ty, tw, th); + } + + if (tile.debug && this.debugSettings.debuggedTileOverfill) + { + context.fillStyle = this.debugSettings.debuggedTileOverfill; + context.fillRect(tx, ty, tw, th); + } + + } + + } + +}; + +/** +* Shifts the canvas and render damaged edge tiles. +* +* @method Phaser.TilemapLayer#renderDeltaScroll +* @private +*/ +Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds. + + // Start in pixels + var left = 0; + var right = -tw; + var top = 0; + var bottom = -th; + + if (shiftX < 0) // layer moving left, damage right + { + left = renderW + shiftX; // shiftX neg. + right = renderW - 1; + } + else if (shiftX > 0) + { + // left -> 0 + right = shiftX; + } + + if (shiftY < 0) // layer moving down, damage top + { + top = renderH + shiftY; // shiftY neg. + bottom = renderH - 1; + } + else if (shiftY > 0) + { + // top -> 0 + bottom = shiftY; + } + + this.shiftCanvas(this.context, shiftX, shiftY); + + // Transform into tile-space + left = Math.floor((left + scrollX) / tw); + right = Math.floor((right + scrollX) / tw); + top = Math.floor((top + scrollY) / th); + bottom = Math.floor((bottom + scrollY) / th); + + if (left <= right) + { + // Clear left or right edge + this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH); + + var trueTop = Math.floor((0 + scrollY) / th); + var trueBottom = Math.floor((renderH - 1 + scrollY) / th); + this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom); + } + + if (top <= bottom) + { + // Clear top or bottom edge + this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th); + + var trueLeft = Math.floor((0 + scrollX) / tw); + var trueRight = Math.floor((renderW - 1 + scrollX) / tw); + this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom); + } + +}; + +/** +* Clear and render the entire canvas. +* +* @method Phaser.TilemapLayer#renderFull +* @private +*/ +Phaser.TilemapLayer.prototype.renderFull = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + this.context.clearRect(0, 0, renderW, renderH); + + this.renderRegion(scrollX, scrollY, left, top, right, bottom); + +}; + +/** +* Renders the tiles to the layer canvas and pushes to the display. +* +* @method Phaser.TilemapLayer#render +* @protected +*/ +Phaser.TilemapLayer.prototype.render = function () { + + var redrawAll = false; + + if (!this.visible) + { + return; + } + + if (this.dirty || this.layer.dirty) + { + this.layer.dirty = false; + redrawAll = true; + } + + var renderWidth = this.canvas.width; // Use Sprite.width/height? + var renderHeight = this.canvas.height; + + // Scrolling bias; whole pixels only + var scrollX = this._scrollX | 0; + var scrollY = this._scrollY | 0; + + var mc = this._mc; + var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down + var shiftY = mc.scrollY - scrollY; + + if (!redrawAll && + shiftX === 0 && shiftY === 0 && + mc.renderWidth === renderWidth && mc.renderHeight === renderHeight) + { + // No reason to redraw map, looking at same thing and not invalidated. + return; + } + + this.context.save(); + + mc.scrollX = scrollX; + mc.scrollY = scrollY; + + if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight) + { + // Could support automatic canvas resizing + mc.renderWidth = renderWidth; + mc.renderHeight = renderHeight; + } + + if (this.debug) + { + this.context.globalAlpha = this.debugSettings.debugAlpha; + + if (this.debugSettings.forceFullRedraw) + { + redrawAll = true; + } + } + + if (!redrawAll && + this.renderSettings.enableScrollDelta && + (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight)) + { + this.renderDeltaScroll(shiftX, shiftY); + } + else + { + // Too much change or otherwise requires full render + this.renderFull(); + } + + if (this.debug) + { + this.context.globalAlpha = 1; + this.renderDebug(); + } + + this.texture.baseTexture.dirty(); + + this.dirty = false; + + this.context.restore(); + + return true; + +}; + +/** +* Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true. +* +* See `debugSettings` for assorted configuration options. +* +* @method Phaser.TilemapLayer#renderDebug +* @private +*/ +Phaser.TilemapLayer.prototype.renderDebug = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var context = this.context; + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + var tx, ty, x, y, xmax, ymax; + + context.strokeStyle = this.debugSettings.facingEdgeStroke; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + if (!tile || tile.index < 0 || !tile.collides) + { + continue; + } + + if (this.debugSettings.collidingTileOverfill) + { + context.fillStyle = this.debugSettings.collidingTileOverfill; + context.fillRect(tx, ty, this._mc.cw, this._mc.ch); + } + + if (this.debugSettings.facingEdgeStroke) + { + context.beginPath(); + + if (tile.faceTop) + { + context.moveTo(tx, ty); + context.lineTo(tx + this._mc.cw, ty); + } + + if (tile.faceBottom) + { + context.moveTo(tx, ty + this._mc.ch); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + if (tile.faceLeft) + { + context.moveTo(tx, ty); + context.lineTo(tx, ty + this._mc.ch); + } + + if (tile.faceRight) + { + context.moveTo(tx + this._mc.cw, ty); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + context.closePath(); + + context.stroke(); + } + + } + + } + +}; + +/** +* Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size. +* +* @property {boolean} wrap +* @memberof Phaser.TilemapLayer +* @public +* @default false +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", { + + get: function () { + return this._wrap; + }, + + set: function (value) { + this._wrap = value; + this.dirty = true; + } + +}); + +/** +* Scrolls the map horizontally or returns the current x position. +* +* @property {number} scrollX +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", { + + get: function () { + return this._scrollX; + }, + + set: function (value) { + this._scrollX = value; + } + +}); + +/** +* Scrolls the map vertically or returns the current y position. +* +* @property {number} scrollY +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", { + + get: function () { + return this._scrollY; + }, + + set: function (value) { + this._scrollY = value; + } + +}); + +/** +* The width of the collision tiles (in pixels). +* +* @property {integer} collisionWidth +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", { + + get: function () { + return this._mc.cw; + }, + + set: function (value) { + this._mc.cw = value | 0; + this.dirty = true; + } + +}); + +/** +* The height of the collision tiles (in pixels). +* +* @property {integer} collisionHeight +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", { + + get: function () { + return this._mc.ch; + }, + + set: function (value) { + this._mc.ch = value | 0; + this.dirty = true; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. +* +* @class Phaser.TilemapParser +* @static +*/ +Phaser.TilemapParser = { + + /** + * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or + * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type + * depends how this should be configured. If you've a large sparsely populated map and the tile + * data doesn't need to change then setting this value to `true` will help with memory consumption. + * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes + * during the game) then leave the default value set. + * + * @constant + * @type {boolean} + */ + INSERT_NULL: false, + + /** + * Parse tilemap data from the cache and creates data for a Tilemap object. + * + * @method Phaser.TilemapParser.parse + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {string} key - The key of the tilemap in the Cache. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {object} The parsed map object. + */ + parse: function (game, key, tileWidth, tileHeight, width, height) { + + if (tileWidth === undefined) { tileWidth = 32; } + if (tileHeight === undefined) { tileHeight = 32; } + if (width === undefined) { width = 10; } + if (height === undefined) { height = 10; } + + if (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); + } + + }, + + /** + * Parses a CSV file into valid map data. + * + * @method Phaser.TilemapParser.parseCSV + * @param {string} key - The name you want to give the map data. + * @param {string} data - The CSV file data. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @return {object} Generated map data. + */ + parseCSV: function (key, data, tileWidth, tileHeight) { + + var map = this.getEmptyData(); + + // Trim any rogue whitespace from the data + data = data.trim(); + + var output = []; + var rows = data.split("\n"); + var height = rows.length; + var width = 0; + + for (var y = 0; y < rows.length; y++) + { + output[y] = []; + + var column = rows[y].split(","); + + for (var x = 0; x < column.length; x++) + { + output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight); + } + + if (width === 0) + { + width = column.length; + } + } + + map.format = Phaser.Tilemap.CSV; + map.name = key; + map.width = width; + map.height = height; + map.tileWidth = tileWidth; + map.tileHeight = tileHeight; + map.widthInPixels = width * tileWidth; + map.heightInPixels = height * tileHeight; + + map.layers[0].width = width; + map.layers[0].height = height; + map.layers[0].widthInPixels = map.widthInPixels; + map.layers[0].heightInPixels = map.heightInPixels; + map.layers[0].data = output; + + return map; + + }, + + /** + * Returns an empty map data object. + * + * @method Phaser.TilemapParser.getEmptyData + * @return {object} Generated map data. + */ + getEmptyData: function (tileWidth, tileHeight, width, height) { + + return { + width: (width !== undefined && width !== null) ? width : 0, + height: (height !== undefined && height !== null) ? height : 0, + tileWidth: (tileWidth !== undefined && tileWidth !== null) ? tileWidth : 0, + tileHeight: (tileHeight !== undefined && tileHeight !== null) ? tileHeight : 0, + orientation: 'orthogonal', + version: '1', + properties: {}, + widthInPixels: 0, + heightInPixels: 0, + layers: [ + { + name: 'layer', + x: 0, + y: 0, + width: 0, + height: 0, + widthInPixels: 0, + heightInPixels: 0, + alpha: 1, + visible: true, + properties: {}, + indexes: [], + callbacks: [], + bodies: [], + data: [] + } + ], + images: [], + objects: {}, + collision: {}, + tilesets: [], + tiles: [] + }; + + }, + + _slice: function(obj, fields) { + var sliced = {}; + + for (var k in fields) + { + var key = fields[k]; + + if (typeof obj[key] !== 'undefined') + { + sliced[key] = obj[key]; + } + } + + return sliced; + }, + + /** + * Parses an object group in Tiled JSON files. Object groups can be found in both layers and tilesets. Called internally in parseTiledJSON. + * @method Phaser.TilemapParser.parseObjectGroup + * @param {object} objectGroup - A JSON object group. + * @param {object} objectsCollection - An object into which new array of Tiled map objects will be added. + * @param {object} collisionCollection - An object into which new array of collision objects will be added. Currently only polylines are added. + * @param {string} [nameKey=objectGroup.name] - Key under which to store objects in collisions in objectsCollection and collisionCollection + * @param {object} [relativePosition={x: 0, y: 0}] - Coordinates the object group's position is relative to. + * @return {object} A object literal containing the objectsCollection and collisionCollection + */ + parseObjectGroup: function(objectGroup, objectsCollection, collisionCollection, nameKey, relativePosition) { + + var nameKey = nameKey || objectGroup.name; + var relativePosition = relativePosition || {x: 0, y: 0}; + var slice = this._slice; + + if (!nameKey) + { + console.warn('No name found for objectGroup', objectGroup); + } + + if (relativePosition.x === undefined || relativePosition.y === undefined) + { + console.warn('Malformed xy properties in relativePosition', relativePosition); + } + + objectsCollection[nameKey] = objectsCollection[nameKey] || []; + collisionCollection[nameKey] = collisionCollection[nameKey] || []; + + for (var v = 0, len = objectGroup.objects.length; v < len; v++) + { + var o = objectGroup.objects[v]; + + // Object Tiles + if (o.gid) + { + var object = { + gid: o.gid, + name: o.name, + type: o.type || '', + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + objectsCollection[nameKey].push(object); + } + else if (o.polyline) + { + var object = { + name: o.name, + type: o.type, + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + object.polyline = []; + + // Parse the polyline into an array + for (var p = 0; p < o.polyline.length; p++) + { + object.polyline.push([o.polyline[p].x, o.polyline[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // polygon + else if (o.polygon) + { + var object = slice(o, ['name', 'type', 'x', 'y', 'visible', 'rotation', 'properties']); + + object.x += relativePosition.x; + object.y += relativePosition.y; + + // Parse the polygon into an array + object.polygon = []; + + for (var p = 0; p < o.polygon.length; p++) + { + object.polygon.push([o.polygon[p].x, o.polygon[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // ellipse + else if (o.ellipse) + { + var object = slice(o, ['name', 'type', 'ellipse', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // otherwise it's a rectangle + else + { + var object = slice(o, ['name', 'type', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + object.rectangle = true; + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + } + + return { + objectsCollection: objectsCollection, + collisionCollection: collisionCollection + }; + }, + + /** + * Parses a Tiled JSON file into valid map data. + * @method Phaser.TilemapParser.parseTiledJSON + * @param {object} json - The JSON map data. + * @return {object} Generated and parsed map data. + */ + parseTiledJSON: function (json) { + + if (json.orientation !== 'orthogonal') + { + console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser'); + return null; + } + + // Map data will consist of: layers, objects, images, tilesets, sizes + var map = { + width: json.width, + height: json.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + orientation: json.orientation, + format: Phaser.Tilemap.TILED_JSON, + version: json.version, + properties: json.properties, + widthInPixels: json.width * json.tilewidth, + heightInPixels: json.height * json.tileheight + }; + + // Tile Layers + var layers = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'tilelayer') + { + continue; + } + + var curl = json.layers[i]; + + // Base64 decode data if necessary + // NOTE: uncompressed base64 only. + + if (!curl.compression && curl.encoding && curl.encoding === 'base64') + { + var binaryString = window.atob(curl.data); + var len = binaryString.length; + var bytes = new Array(len); + + // Interpret binaryString as an array of bytes representing + // little-endian encoded uint32 values. + for (var j = 0; j < len; j+=4) + { + bytes[j / 4] = ( + binaryString.charCodeAt(j) | + binaryString.charCodeAt(j + 1) << 8 | + binaryString.charCodeAt(j + 2) << 16 | + binaryString.charCodeAt(j + 3) << 24 + ) >>> 0; + } + + curl.data = bytes; + + delete curl.encoding; + } + else if (curl.compression) + { + console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\''); + continue; + } + + var layer = { + + name: curl.name, + x: curl.x, + y: curl.y, + width: curl.width, + height: curl.height, + widthInPixels: curl.width * json.tilewidth, + heightInPixels: curl.height * json.tileheight, + alpha: curl.opacity, + offsetX: curl.offsetx, + offsetY: curl.offsety, + visible: curl.visible, + properties: {}, + indexes: [], + callbacks: [], + bodies: [] + + }; + + if (curl.properties) + { + layer.properties = curl.properties; + } + + var x = 0; + var row = []; + var output = []; + var rotation, flipped, flippedVal, gid; + + // Loop through the data field in the JSON. + + // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV) + // If the map contains multiple tilesets then the indexes are relative to that which the set starts from. + // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset. + + for (var t = 0, len = curl.data.length; t < len; t++) + { + rotation = 0; + flipped = false; + gid = curl.data[t]; + flippedVal = 0; + + // If true the current tile is flipped or rotated (Tiled TMX format) + if (gid > 0x20000000) + { + // FlippedX + if (gid > 0x80000000) + { + gid -= 0x80000000; + flippedVal += 4; + } + + // FlippedY + if (gid > 0x40000000) + { + gid -= 0x40000000; + flippedVal += 2; + } + + // FlippedAD (anti-diagonal = top-right is swapped with bottom-left corners) + if (gid > 0x20000000) + { + gid -= 0x20000000; + flippedVal += 1; + } + + switch (flippedVal) + { + case 5: + rotation = Math.PI / 2; + break; + + case 6: + rotation = Math.PI; + break; + + case 3: + rotation = 3 * Math.PI / 2; + break; + + case 4: + rotation = 0; + flipped = true; + break; + + case 7: + rotation = Math.PI / 2; + flipped = true; + break; + + case 2: + rotation = Math.PI; + flipped = true; + break; + + case 1: + rotation = 3 * Math.PI / 2; + flipped = true; + break; + } + } + + // index, x, y, width, height + if (gid > 0) + { + var tile = new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight); + + tile.rotation = rotation; + tile.flipped = flipped; + + if (flippedVal !== 0) + { + // The WebGL renderer uses this to flip UV coordinates before drawing + tile.flippedVal = flippedVal; + } + + row.push(tile); + } + else + { + if (Phaser.TilemapParser.INSERT_NULL) + { + row.push(null); + } + else + { + row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight)); + } + } + + x++; + + if (x === curl.width) + { + output.push(row); + x = 0; + row = []; + } + } + + layer.data = output; + + layers.push(layer); + } + + map.layers = layers; + + // Images + var images = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'imagelayer') + { + continue; + } + + var curi = json.layers[i]; + + var image = { + + name: curi.name, + image: curi.image, + x: curi.x, + y: curi.y, + alpha: curi.opacity, + visible: curi.visible, + properties: {} + + }; + + if (curi.properties) + { + image.properties = curi.properties; + } + + images.push(image); + + } + + map.images = images; + + // Tilesets & Image Collections + var tilesets = []; + var tilesetGroupObjects = {}; + var imagecollections = []; + var lastSet = null; + + for (var i = 0; i < json.tilesets.length; i++) + { + // name, firstgid, width, height, margin, spacing, properties + var set = json.tilesets[i]; + + if (set.source) + { + console.warn('Phaser.TilemapParser - Phaser can\'t load external tilesets (%s). Use the Embed Tileset button and then export the map again.', set.source); + } + else if (set.image) + { + var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + if (set.tileproperties) + { + newSet.tileProperties = set.tileproperties; + } + + // For a normal sliced tileset the row/count/size information is computed when updated. + // This is done (again) after the image is set. + newSet.updateTileData(set.imagewidth, set.imageheight); + + tilesets.push(newSet); + } + else if (set.tiles) + { + var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + for (var ti in set.tiles) + { + var image = set.tiles[ti].image; + var gid = set.firstgid + parseInt(ti, 10); + newCollection.addImage(gid, image); + } + + imagecollections.push(newCollection); + } + else + { + throw new Error('Tileset ' + set.name + ' has no `image` or `tiles` property.'); + } + + // build a temporary object for objectgroups found in the tileset's tiles + for (var ti in set.tiles) + { + var objectGroup = set.tiles[ti].objectgroup; + + if (!objectGroup) + { + continue; + } + + tilesetGroupObjects[parseInt(ti, 10) + set.firstgid] = objectGroup; + } + + // We've got a new Tileset, so set the lastgid into the previous one + if (lastSet) + { + lastSet.lastgid = set.firstgid - 1; + } + + lastSet = set; + } + + if (tilesets.length === 0 && imagecollections.length === 0) + { + throw new Error('This tilemap has no tilesets.'); + } + + map.tilesets = tilesets; + map.imagecollections = imagecollections; + + // Objects & Collision Data (polylines, etc) + var objects = {}; + var collision = {}; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'objectgroup') + { + continue; + } + + var objectGroup = json.layers[i]; + this.parseObjectGroup(objectGroup, objects, collision); + } + + map.objects = objects; + map.collision = collision; + + map.tiles = []; + + // Finally lets build our super tileset index + for (var i = 0; i < map.tilesets.length; i++) + { + var set = map.tilesets[i]; + + var x = set.tileMargin; + var y = set.tileMargin; + + var count = 0; + var countX = 0; + var countY = 0; + + for (var t = set.firstgid; t < set.firstgid + set.total; t++) + { + // Can add extra properties here as needed + map.tiles[t] = [x, y, i]; + + x += set.tileWidth + set.tileSpacing; + + count++; + + if (count === set.total) + { + break; + } + + countX++; + + if (countX === set.columns) + { + x = set.tileMargin; + y += set.tileHeight + set.tileSpacing; + + countX = 0; + countY++; + + if (countY === set.rows) + { + break; + } + } + } + + } + + // assign tile properties + + var layer; + var tile; + var sid; + var set; + + // go through each of the map data layers + for (var i = 0; i < map.layers.length; i++) + { + layer = map.layers[i]; + collision[layer.name] = []; + set = null; + + // rows of tiles + for (var j = 0; j < layer.data.length; j++) + { + row = layer.data[j]; + + // individual tiles + for (var k = 0; k < row.length; k++) + { + tile = row[k]; + + if (tile === null || tile.index < 0) + { + continue; + } + + // find the relevant tileset + + sid = map.tiles[tile.index][2]; + set = map.tilesets[sid]; + + + // if that tile type has any properties, add them to the tile object + + if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) + { + tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties); + } + + var objectGroup = tilesetGroupObjects[tile.index]; + if (objectGroup) + { + // build collisions and objects for objectgroups found in the tileset's tiles + this.parseObjectGroup( + objectGroup, + map.objects, + map.collision, + tile.layer.name, + { + x: tile.worldX + objectGroup.x, + y: tile.worldY + objectGroup.y + }); + } + + } + } + } + + return map; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile set is a combination of an image containing the tiles and collision data per tile. +* +* Tilesets are normally created automatically when Tiled data is loaded. +* +* @class Phaser.Tileset +* @constructor +* @param {string} name - The name of the tileset in the map data. +* @param {integer} firstgid - The first tile index this tileset contains. +* @param {integer} [width=32] - Width of each tile (in pixels). +* @param {integer} [height=32] - Height of each tile (in pixels). +* @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels). +* @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels). +* @param {object} [properties={}] - Custom Tileset properties. +*/ +Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Tileset. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first tile index this Tileset contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of each tile (in pixels). + * @property {integer} tileWidth + * @readonly + */ + this.tileWidth = width | 0; + + /** + * The height of each tile (in pixels). + * @property {integer} tileHeight + * @readonly + */ + this.tileHeight = height | 0; + + /** + * The margin around the tiles in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileMarge + * @readonly + */ + // Modified internally + this.tileMargin = margin | 0; + + /** + * The spacing between each tile in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileSpacing + * @readonly + */ + this.tileSpacing = spacing | 0; + + /** + * Tileset-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set. + * @property {?object} image + * @readonly + */ + // Modified internally + this.image = null; + + /** + * The number of tile rows in the the tileset. + * @property {integer} + * @readonly + */ + // Modified internally + this.rows = 0; + + /** + * The number of tile columns in the tileset. + * @property {integer} columns + * @readonly + */ + // Modified internally + this.columns = 0; + + /** + * The total number of tiles in the tileset. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; + + /** + * The look-up table to specific tile image offsets. + * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1. + * @property {integer[]} drawCoords + * @private + */ + this.drawCoords = []; + +}; + +Phaser.Tileset.prototype = { + + /** + * Draws a tile from this Tileset at the given coordinates on the context. + * + * @method Phaser.Tileset#draw + * @public + * @param {CanvasRenderingContext2D} context - The context to draw the tile onto. + * @param {number} x - The x coordinate to draw to. + * @param {number} y - The y coordinate to draw to. + * @param {integer} index - The index of the tile within the set to draw. + */ + draw: function (context, x, y, index) { + + // Correct the tile index for the set and bias for interlacing + var coordIndex = (index - this.firstgid) << 1; + + if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length) + { + context.drawImage( + this.image, + this.drawCoords[coordIndex], + this.drawCoords[coordIndex + 1], + this.tileWidth, + this.tileHeight, + x, + y, + this.tileWidth, + this.tileHeight + ); + } + + }, + + /** + * Returns true if and only if this tileset contains the given tile index. + * + * @method Phaser.Tileset#containsTileIndex + * @public + * @param {number} tileIndex + * @return {boolean} True if this tileset contains the given index. + */ + containsTileIndex: function (tileIndex) { + + return ( + tileIndex >= this.firstgid && + tileIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Set the image associated with this Tileset and update the tile data. + * + * @method Phaser.Tileset#setImage + * @public + * @param {Image} image - The image that contains the tiles. + */ + setImage: function (image) { + + this.image = image; + this.updateTileData(image.width, image.height); + + }, + + /** + * Sets tile spacing and margins. + * + * @method Phaser.Tileset#setSpacing + * @public + * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels). + */ + setSpacing: function (margin, spacing) { + + this.tileMargin = margin | 0; + this.tileSpacing = spacing | 0; + + if (this.image) + { + this.updateTileData(this.image.width, this.image.height); + } + + }, + + /** + * Updates tile coordinates and tileset data. + * + * @method Phaser.Tileset#updateTileData + * @private + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + */ + updateTileData: function (imageWidth, imageHeight) { + + // May be fractional values + var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); + var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); + + if (rowCount % 1 !== 0 || colCount % 1 !== 0) + { + console.warn( + "Phaser.Tileset - '%s' image tile area (%s x %s) is not a whole multiple of tile size (%s x %s + %s + %s)", + this.name, imageWidth, imageHeight, this.tileWidth, this.tileHeight, this.tileMargin, this.tileSpacing + ); + } + + // In Tiled a tileset image that is not an even multiple of the tile dimensions + // is truncated - hence the floor when calculating the rows/columns. + rowCount = Math.floor(rowCount); + colCount = Math.floor(colCount); + + if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount)) + { + console.warn( + "Phaser.Tileset - Tile layout from image '%s' (%s rows by %s columns) differs from tileset '%s' (%s rows by %s columns)", + this.image.name, colCount, rowCount, this.name, this.columns, this.rows + ); + } + + this.rows = rowCount; + this.columns = colCount; + this.total = rowCount * colCount; + + this.drawCoords.length = 0; + + var tx = this.tileMargin; + var ty = this.tileMargin; + + for (var y = 0; y < this.rows; y++) + { + for (var x = 0; x < this.columns; x++) + { + this.drawCoords.push(tx); + this.drawCoords.push(ty); + tx += this.tileWidth + this.tileSpacing; + } + + tx = this.tileMargin; + ty += this.tileHeight + this.tileSpacing; + } + + } + +}; + +Phaser.Tileset.prototype.constructor = Phaser.Tileset; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. +* +* @class Phaser.Particle +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Particle = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + /** + * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData. + * @protected + */ + this.autoScale = false; + + /** + * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.scaleData = null; + + /** + * @property {number} _s - Internal cache var for tracking auto scale. + * @private + */ + this._s = 0; + + /** + * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. + * @protected + */ + this.autoAlpha = false; + + /** + * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.alphaData = null; + + /** + * @property {number} _a - Internal cache var for tracking auto alpha. + * @private + */ + this._a = 0; + +}; + +Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Particle.prototype.constructor = Phaser.Particle; + +/** +* Updates the Particle scale or alpha if autoScale and autoAlpha are set. +* +* @method Phaser.Particle#update +* @memberof 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; + } + } + +}; + +/** +* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. +* +* @method Phaser.Particle#onEmit +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.onEmit = function() { +}; + +/** +* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. +* +* @method Phaser.Particle#setAlphaData +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.setAlphaData = function(data) { + + this.alphaData = data; + this._a = data.length - 1; + this.alpha = this.alphaData[this._a].v; + this.autoAlpha = true; + +}; + +/** +* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. +* +* @method Phaser.Particle#setScaleData +* @memberof Phaser.Particle +*/ +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; + +}; + +/** +* Resets the Particle. This places the Particle at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. +* If the Particle has a physics body that too is reset. +* +* @method Phaser.Particle#reset +* @memberof Phaser.Particle +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {number} [health=1] - The health to give the Particle. +* @return {Phaser.Particle} This instance. +*/ +Phaser.Particle.prototype.reset = function(x, y, health) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y, health); + + this.alpha = 1; + this.scale.set(1); + + this.autoScale = false; + this.autoAlpha = false; + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Particles tracks any Emitters attached to it. +* +* @class Phaser.Particles +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Particles = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} emitters - Internal emitters store. + */ + this.emitters = {}; + + /** + * @property {number} ID - + * @default + */ + this.ID = 0; + +}; + +Phaser.Particles.prototype = { + + /** + * Adds a new Particle Emitter to the Particle Manager. + * @method Phaser.Particles#add + * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. + * @return {Phaser.Emitter} The emitter that was added. + */ + add: function (emitter) { + this.emitters[emitter.id] = emitter; + return emitter; + }, + + /** + * Removes an existing Particle Emitter from the Particle Manager. + * @method Phaser.Particles#remove + * @param {Phaser.Emitter} emitter - The emitter to remove. + */ + remove: function (emitter) { + delete this.emitters[emitter.id]; + } + +}; + +Phaser.Particles.prototype.constructor = Phaser.Particles; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Arcade Particles is a Particle System integrated with Arcade Physics. +* +* @class Phaser.Particles.Arcade +*/ +Phaser.Particles.Arcade = {}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Emitter is a lightweight particle emitter that uses Arcade Physics. +* It can be used for one-time explosions or for continuous effects like rain and fire. +* All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. +* +* @class Phaser.Particles.Arcade.Emitter +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. +* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. +* @param {number} [maxParticles=50] - The total number of particles in this emitter. +*/ +Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { + + /** + * @property {number} maxParticles - The total number of particles in this emitter. + * @default + */ + this.maxParticles = maxParticles || 50; + + Phaser.Group.call(this, game); + + /** + * @property {number} _id - Internal ID for this emitter -- only used by the Particle System in most cases + * @private + */ + this._id = this.game.particles.ID++; + + /** + * @property {string} name - A handy string name for this emitter. Can be set to anything. + */ + this.name = 'emitter' + this.id; + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.EMITTER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * @property {Phaser.Rectangle} area - The {@link #setSize size} of the emitter's emit area. The **actual** emit area is a rectangle of this size centered on (emitX, emitY): `{x: this.left, y: this.top, width: this.area.width, height: this.area.height}`. Particles are generated at a random position within this area. + * @default + */ + this.area = new Phaser.Rectangle(x, y, 1, 1); + + /** + * @property {?number} minAngle - The minimum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #maxAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.minAngle = null; + + /** + * @property {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #minAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.maxAngle = null; + + /** + * @property {number} minSpeed - The minimum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.minSpeed = 0; + + /** + * @property {number} maxSpeed - The maximum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.maxSpeed = 100; + + /** + * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle. + * @default + */ + this.minParticleSpeed = new Phaser.Point(-100, -100); + + /** + * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle. + * @default + */ + this.maxParticleSpeed = new Phaser.Point(100, 100); + + /** + * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. + * @default + */ + this.minParticleScale = 1; + + /** + * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. + * @default + */ + this.maxParticleScale = 1; + + /** + * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0. + */ + this.scaleData = null; + + /** + * @property {number} minRotation - The minimum possible angular velocity of a particle. + * @default + */ + this.minRotation = -360; + + /** + * @property {number} maxRotation - The maximum possible angular velocity of a particle. + * @default + */ + this.maxRotation = 360; + + /** + * @property {number} minParticleAlpha - The minimum possible alpha value of a particle. + * @default + */ + this.minParticleAlpha = 1; + + /** + * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle. + * @default + */ + this.maxParticleAlpha = 1; + + /** + * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0. + */ + this.alphaData = null; + + /** + * @property {function} particleClass - For emitting your own particle class types. They must extend Phaser.Particle. + * @default + */ + this.particleClass = Phaser.Particle; + + /** + * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter. + */ + this.particleDrag = new Phaser.Point(); + + /** + * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false). + * @default + */ + this.frequency = 100; + + /** + * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. + * @default + */ + this.lifespan = 2000; + + /** + * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. + */ + this.bounce = new Phaser.Point(); + + /** + * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. + * @default + */ + this.on = false; + + /** + * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) + * @default + */ + this.particleAnchor = new Phaser.Point(0.5, 0.5); + + /** + * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) + * @default + */ + this.blendMode = Phaser.blendModes.NORMAL; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitX + */ + this.emitX = x; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitY + */ + this.emitY = y; + + /** + * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. + */ + this.autoScale = false; + + /** + * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. + */ + this.autoAlpha = false; + + /** + * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. + * @default + */ + this.particleBringToTop = false; + + /** + * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. + * @default + */ + this.particleSendToBack = false; + + /** + * @property {object} counts - Records emitter activity. + * @property {number} counts.emitted - How many particles were emitted during the last update. + * @property {number} counts.failed - How many particles could not be emitted during the last update (because no particles were available). + * @property {number} counts.totalEmitted - How many particles have been emitted. + * @property {number} counts.totalFailed - How many particles could not be emitted when they were due (because no particles were available). + */ + this.counts = { + emitted: 0, + failed: 0, + totalEmitted: 0, + totalFailed: 0 + }; + + /** + * @property {Phaser.Point} _gravity - Internal gravity value. + * @private + */ + this._gravity = new Phaser.Point(0, 100); + + /** + * @property {Phaser.Point} _minParticleScale - Internal particle scale var. + * @private + */ + this._minParticleScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} _maxParticleScale - Internal particle scale var. + * @private + */ + this._maxParticleScale = new Phaser.Point(1, 1); + + /** + * @property {number} _total - Internal helper for deciding how many particles to launch (via {@link #start}). + * @private + */ + this._total = 0; + + /** + * @property {number} _timer - Internal helper for deciding when to launch particles or kill them. + * @private + */ + this._timer = 0; + + /** + * @property {number} _counter - Internal counter for figuring out how many particles to launch. + * @private + */ + this._counter = 0; + + /** + * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update. + * @private + */ + this._flowQuantity = 0; + + /** + * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total (via {@link #flow}). + * @private + */ + this._flowTotal = 0; + + /** + * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time). + * @private + */ + this._explode = true; + + /** + * @property {any} _frames - Internal helper for the particle frame. + * @private + */ + this._frames = null; + +}; + +Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); +Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter; + +/** +* Called automatically by the game loop, decides when to launch particles and when to "die". +* +* @method Phaser.Particles.Arcade.Emitter#update +*/ +Phaser.Particles.Arcade.Emitter.prototype.update = function () { + + this.counts.emitted = 0; + this.counts.failed = 0; + + if (this.on && this.game.time.time >= this._timer) + { + this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion; + + if (this._flowTotal !== 0) + { + if (this._flowQuantity > 0) + { + for (var i = 0; i < this._flowQuantity; i++) + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + break; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._total > 0 && this._counter >= this._total) + { + this.on = false; + } + } + } + + } + + var i = this.children.length; + + while (i--) + { + if (this.children[i].exists) + { + this.children[i].update(); + } + } + +}; + +/** +* This function generates a new set of particles for use by this emitter. +* The particles are stored internally waiting to be emitted via Emitter.start. +* +* @method Phaser.Particles.Arcade.Emitter#makeParticles +* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. +* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random. +* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. +* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. +* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. +* @param {object} [particleArguments=null] - Custom arguments to pass to your particle class +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds, particleArguments) { + + if (frames === undefined) { frames = 0; } + if (quantity === undefined) { quantity = this.maxParticles; } + if (collide === undefined) { collide = false; } + if (collideWorldBounds === undefined) { collideWorldBounds = false; } + if (particleArguments === undefined) { particleArguments = null; } + + var particle; + var i = 0; + var rndKey = keys; + var rndFrame = frames; + this._frames = frames; + + if (quantity > this.maxParticles) + { + this.maxParticles = quantity; + } + + while (i < quantity) + { + if (Array.isArray(keys)) + { + rndKey = this.game.rnd.pick(keys); + } + + if (Array.isArray(frames)) + { + rndFrame = this.game.rnd.pick(frames); + } + + particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame, particleArguments); + + this.game.physics.arcade.enable(particle, false); + + particle.body.checkCollision.none = !collide; + particle.body.collideWorldBounds = collideWorldBounds; + particle.body.skipQuadTree = true; + + particle.exists = false; + particle.visible = false; + particle.anchor.copyFrom(this.particleAnchor); + + this.add(particle); + + i++; + } + + return this; + +}; + +/** +* Call this function to turn off all the particles and the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#kill +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.kill = function () { + + this.on = false; + this.alive = false; + this.exists = false; + + return this; + +}; + +/** +* Handy for bringing game objects "back to life". Just sets alive and exists back to true. +* +* @method Phaser.Particles.Arcade.Emitter#revive +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.revive = function () { + + this.alive = true; + this.exists = true; + + return this; + +}; + +/** +* Call this function to emit the given quantity of particles at all once (an explosion) +* +* @method Phaser.Particles.Arcade.Emitter#explode +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [quantity=this.maxParticles] - How many particles to launch. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) { + + if (quantity === undefined) { + quantity = this.maxParticles; + } + + this._flowTotal = 0; + + this.start(true, lifespan, 0, quantity, false); + + return this; + +}; + +/** +* Call this function to start emitting a flow of particles. +* `quantity` particles are released every interval of `frequency` ms until `total` particles have been released (or forever). +* If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 × 5 = 20 total) and then turn {@link #on off}. +* If you set the total to be -1 then no quantity cap is used and it will keep emitting (as long as there are inactive particles available). +* +* {@link #output}, {@link #lifespanOutput}, and {@link #remainder} describe the particle flow rate. +* During a stable flow, the number of active particles approaches {@link #lifespanOutput} and the number of inactive particles approaches {@link #remainder}. +* If {@link #remainder} is less than 0, there will likely be no particles available for a portion of the flow (see {@link #count}). +* +* @method Phaser.Particles.Arcade.Emitter#flow +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of particles, given in ms. Values between 0 and 16.66 will behave the same (60 releases per second). +* @param {number} [quantity=1] - How many particles to launch at each interval. Not larger than {@link #maxParticles}. +* @param {number} [total=-1] - Turn {@link #on off} after launching this many particles in total. If -1 it will carry on indefinitely. +* @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) { + + if (frequency === undefined || frequency === null) { frequency = 250; } + if (quantity === undefined || quantity === 0) { quantity = 1; } + if (total === undefined) { total = -1; } + if (immediate === undefined) { immediate = true; } + + if (quantity > this.maxParticles) + { + quantity = this.maxParticles; + } + + this._counter = 0; + this._flowQuantity = quantity; + this._flowTotal = total; + + if (immediate) + { + this.start(true, lifespan, frequency, quantity); + + this._counter += quantity; + this.on = true; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + else + { + this.start(false, lifespan, frequency, quantity); + } + + return this; + +}; + +/** +* Start emitting particles. +* +* {@link #explode} and {@link #flow} are simpler methods. +* +* There are two patterns, based on the `explode` argument: +* +* ##### explode=true +* +* start(true, lifespan=0, null, total) +* +* When `explode` is true or `forceQuantity` is true, `start` emits `total` particles immediately. You should pass a nonzero `total`. +* +* ##### explode=false +* +* start(false, lifespan=0, frequency=250, total=0) +* +* When `explode` is false and `forceQuantity` is false, `start` emits 1 particle every interval of `frequency` ms. If `total` is not zero, the emitter turns itself off after `total` particles have been released. If `total` is zero, the emitter keeps emitting particles as long as they are available. To emit more than 1 particle per flow interval, use {@link #flow} instead. +* +* `forceQuantity` seems equivalent to `explode` and can probably be avoided. +* +* @method Phaser.Particles.Arcade.Emitter#start +* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false). +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of 1 particle, when `explode` is false. Value given in ms. Ignored if `explode` is set to true. +* @param {number} [total=0] - Turn {@link #on off} after launching this many particles in total. +* @param {number} [forceQuantity=false] - Equivalent to `explodes`. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, total, forceQuantity) { + + if (explode === undefined) { explode = true; } + if (lifespan === undefined) { lifespan = 0; } + if (frequency === undefined || frequency === null) { frequency = 250; } + if (total === undefined) { total = 0; } + if (forceQuantity === undefined) { forceQuantity = false; } + + if (total > this.maxParticles) + { + total = this.maxParticles; + } + + this.revive(); + + this.visible = true; + + this.lifespan = lifespan; + this.frequency = frequency; + + if (explode || forceQuantity) + { + for (var i = 0; i < total; i++) + { + this.emitParticle(); + } + } + else + { + this.on = true; + this._total = total; + this._counter = 0; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + + return this; + +}; + +/** +* This function is used internally to emit the next particle in the queue. +* +* However it can also be called externally to emit a particle. +* +* When called externally you can use the arguments to override any defaults the Emitter has set. +* +* The newly emitted particle is available in {@link Phaser.Particles.Arcade.Emitter#cursor}. +* +* @method Phaser.Particles.Arcade.Emitter#emitParticle +* @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. +* @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {boolean} True if a particle was emitted, otherwise false. +*/ +Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + var particle = this.getNextParticle(); + + if (particle === null) + { + this.counts.failed++; + this.counts.totalFailed++; + + return false; + } + + this.counts.emitted++; + this.counts.totalEmitted++; + + var rnd = this.game.rnd; + + if (key !== undefined && frame !== undefined) + { + particle.loadTexture(key, frame); + } + else if (key !== undefined) + { + particle.loadTexture(key); + particle.frame = Array.isArray(this._frames) ? rnd.pick(this._frames) : this._frames; + } + + var emitX = this.emitX; + var emitY = this.emitY; + + if (x !== null) + { + emitX = x; + } + else if (this.width > 1) + { + emitX = rnd.between(this.left, this.right); + } + + if (y !== null) + { + emitY = y; + } + else if (this.height > 1) + { + emitY = rnd.between(this.top, this.bottom); + } + + this.resetParticle(particle, emitX, emitY); + + return true; + +}; + + +/** +* Helper for {@link #emitParticle}. Gets the next available particle. +* +* @private +* @return {?Phaser.Particle} The first particle with exists=false, or null +*/ +Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () { + + var i = this.length; + + while (i--) + { + var next = this.next(); + + if (!next.exists) + { + return next; + } + } + + return null; + +}; + +/** + * Helper for {@link #emitParticle}. Sets particle properties and calls {@link Particle#onEmit}. + * + * @private + * @param {Phaser.Particle} particle + * @param {number} x + * @param {number} y + */ +Phaser.Particles.Arcade.Emitter.prototype.resetParticle = function (particle, x, y) { + + var rnd = this.game.rnd; + + particle.reset(x, y); + + 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(rnd.realInRange(this.minParticleScale, this.maxParticleScale)); + } + else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y)) + { + particle.scale.set(rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y)); + } + else + { + particle.scale.set(this._minParticleScale.x, this._minParticleScale.y); + } + + if (this.autoAlpha) + { + particle.setAlphaData(this.alphaData); + } + else + { + particle.alpha = rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha); + } + + particle.blendMode = this.blendMode; + + var body = particle.body; + + body.updateBounds(); + + body.bounce.copyFrom(this.bounce); + body.drag.copyFrom(this.particleDrag); + + if (this.minAngle != null && this.maxAngle != null) + { + this.game.physics.arcade.velocityFromAngle( + (this.minAngle === this.maxAngle) ? this.minAngle : rnd.between(this.minAngle, this.maxAngle), + (this.minSpeed === this.maxSpeed) ? this.minSpeed : rnd.between(this.minSpeed, this.maxSpeed), + body.velocity + ); + } + else + { + body.velocity.x = rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x); + body.velocity.y = rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y); + } + + body.angularVelocity = rnd.between(this.minRotation, this.maxRotation); + body.gravity.copyFrom(this.gravity); + body.angularDrag = this.angularDrag; + + particle.onEmit(); + +}; + +/** +* Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. +* +* @method Phaser.Particles.Arcade.Emitter#destroy +*/ +Phaser.Particles.Arcade.Emitter.prototype.destroy = function () { + + this.game.particles.remove(this); + + Phaser.Group.prototype.destroy.call(this, true, false); + +}; + +/** +* A more compact way of setting the width and height of the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#setSize +* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). +* @param {number} height - The desired height of the emitter. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { + + this.area.width = width; + this.area.height = height; + + return this; + +}; + +/** +* A more compact way of setting the X velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setXSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.x = min; + this.maxParticleSpeed.x = max; + + return this; + +}; + +/** +* A more compact way of setting the Y velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setYSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.y = min; + this.maxParticleSpeed.y = max; + + return this; + +}; + +/** +* A more compact way of setting the angular velocity constraints of the particles. +* +* @method Phaser.Particles.Arcade.Emitter#setRotation +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minRotation = min; + this.maxRotation = max; + + return this; + +}; + +/** +* A more compact way of setting the alpha constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. +* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setAlpha +* @param {number} [min=1] - The minimum value for this range. +* @param {number} [max=1] - The maximum value for this range. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) { + + if (min === undefined) { min = 1; } + if (max === undefined) { max = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.alphaData.reverse(); + this.autoAlpha = true; + } + + return this; + +}; + +/** +* A more compact way of setting the scale constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. +* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setScale +* @param {number} [minX=1] - The minimum value of Particle.scale.x. +* @param {number} [maxX=1] - The maximum value of Particle.scale.x. +* @param {number} [minY=1] - The minimum value of Particle.scale.y. +* @param {number} [maxY=1] - The maximum value of Particle.scale.y. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) { + + if (minX === undefined) { minX = 1; } + if (maxX === undefined) { maxX = 1; } + if (minY === undefined) { minY = 1; } + if (maxY === undefined) { maxY = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (yoyo === undefined) { yoyo = false; } + + // Reset these + 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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.scaleData.reverse(); + this.autoScale = true; + } + + return this; + +}; + +/** + * Sets a radial pattern for emitting particles. + * + * This is a shorthand for setting {@link #minAngle}, {@link #maxAngle}, {@link #minSpeed}, and {@link #maxSpeed}. + * + * To remove the radial pattern, use `setAngle(null, null)`. + * + * @method Phaser.Particles.Arcade.Emitter#setAngle + * @param {?number} minAngle - The minimum angle of initial particle velocities, in degrees. + * @param {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. + * @param {number} [minSpeed] - The minimum initial particle speed. + * @param {number} [maxSpeed] - The maximum initial particle speed. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ +Phaser.Particles.Arcade.Emitter.prototype.setAngle = function (minAngle, maxAngle, minSpeed, maxSpeed) { + + this.minAngle = minAngle; + this.maxAngle = maxAngle; + + if (minSpeed != null) { this.minSpeed = minSpeed; } + if (maxSpeed != null) { this.maxSpeed = maxSpeed; } + + return this; + +}; + +/** +* Change the emitter's center to match the center of any object with a `center` property, such as an Arcade Body. +* If the object doesn't have a `center` property it will be set to the object's anchor-adjusted world position (`object.world`). +* +* @method Phaser.Particles.Arcade.Emitter#at +* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +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); + } + + return this; + +}; + +/** + * @name Phaser.Particles.Arcade.Emitter#gravity + * @property {Phaser.Point} gravity - Sets the `body.gravity` of each particle sprite to this on launch. + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "gravity", { + + get: function () { + return this._gravity; + }, + + set: function (value) { + if (typeof value === "number") + { + this._gravity.y = value; + } + else + { + this._gravity = value; + } + } + +}); + + +/** +* @name Phaser.Particles.Arcade.Emitter#id +* @property {number} id - Gets the internal ID that represents this emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "id", { + get: function () { + return this._id; + } +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#width +* @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", { + + get: function () { + return this.area.width; + }, + + set: function (value) { + this.area.width = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#height +* @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", { + + get: function () { + return this.area.height; + }, + + set: function (value) { + this.area.height = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#x +* @property {number} x - Gets or sets the x position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", { + + get: function () { + return this.emitX; + }, + + set: function (value) { + this.emitX = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#y +* @property {number} y - Gets or sets the y position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", { + + get: function () { + return this.emitY; + }, + + set: function (value) { + this.emitY = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#left +* @property {number} left - Gets the left position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", { + + get: function () { + return Math.floor(this.x - (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#right +* @property {number} right - Gets the right position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", { + + get: function () { + return Math.floor(this.x + (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#top +* @property {number} top - Gets the top position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", { + + get: function () { + return Math.floor(this.y - (this.area.height / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#bottom +* @property {number} bottom - Gets the bottom position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", { + + get: function () { + return Math.floor(this.y + (this.area.height / 2)); + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#output + * @property {number} output - The number of particles released per second, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "output", { + + get: function () { + return 1000 * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#lifespanOutput + * @property {number} lifespanOutput - The number of particles released during one particle's {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "lifespanOutput", { + + get: function () { + return (this.lifespan === 0 ? Infinity : this.lifespan) * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#remainder + * @property {number} remainder - The expected number of unreleased particles after a flow interval of {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "remainder", { + + get: function () { + return this.maxParticles - this.lifespanOutput; + } + +}); + +/** +* The last particle released, if any. +* +* You should treat this as read-only (and also avoid {@link #next} and {@link #previous}) once the emitter is started. Phaser uses it internally to track particles. +* +* @name Phaser.Particles.Arcade.Emitter#cursor +* @property {?DisplayObject} cursor +* @readonly +*/ +// Inherited from Phaser.Group#cursor + +/** +* Advances the cursor to the next particle. +* +* @method Phaser.Particles.Arcade.Emitter#next +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#next + +/** +* Moves the group cursor to the previous particle. +* +* @method Phaser.Particles.Arcade.Emitter#previous +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#previous + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Weapon Plugin provides the ability to easily create a bullet pool and manager. +* +* Weapons fire {@link Phaser.Bullet} objects, which are essentially Sprites with a few extra properties. +* The Bullets are enabled for {@link Phaser.Physics.Arcade Arcade Physics}. They do not currently work with P2 Physics. +* +* The Bullets are created inside of {@link #bullets weapon.bullets}, which is a {@link Phaser.Group} instance. Anything you +* can usually do with a Group, such as move it around the display list, iterate it, etc can be done +* to the bullets Group too. +* +* Bullets can have textures and even animations. You can control the speed at which they are fired, +* the firing rate, the firing angle, and even set things like gravity for them. +* +* A small example, using {@link Phaser.GameObjectFactory#weapon add.weapon}, assumed to be running from within a {@link Phaser.State#create} method: +* +* ```javascript +* var weapon = this.add.weapon(10, 'bullet'); +* weapon.fireFrom.set(300, 300); +* this.input.onDown.add(weapon.fire, this); +* ``` +* +* If you want to (re)create the bullet pool separately, you can use: +* +* ```javascript +* var weapon = this.game.plugins.add(Phaser.Weapon); +* // … +* weapon.createBullets(10, 'bullet'); +* ``` +* +* @class Phaser.Weapon +* @constructor +* @param {Phaser.Game} game - A reference to the current Phaser.Game instance. +* @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin. +*/ +Phaser.Weapon = function (game, parent) { + + Phaser.Plugin.call(this, game, parent); + + /** + * This is the Phaser.Group that contains all of the bullets managed by this plugin. + * @type {Phaser.Group} + */ + this.bullets = null; + + /** + * Should the bullet pool run out of bullets (i.e. they are all in flight) then this + * boolean controls if the Group will create a brand new bullet object or not. + * @type {boolean} + * @default + */ + this.autoExpandBulletsGroup = false; + + /** + * Will this weapon auto fire? If set to true then a new bullet will be fired + * based on the {@link #fireRate} value. + * @type {boolean} + * @default + */ + this.autofire = false; + + /** + * The total number of bullets this Weapon has fired so far. + * You can limit the number of shots allowed (via {@link #fireLimit}), and reset + * this total via {@link #resetShots}. + * @type {number} + * @default + */ + this.shots = 0; + + /** + * The maximum number of shots that this Weapon is allowed to fire before it stops. + * When the limit is his the {@link #onFireLimit} Signal is dispatched. + * You can reset the shot counter via {@link #resetShots}. + * @type {number} + * @default + */ + this.fireLimit = 0; + + /** + * The minimum interval between shots, in milliseconds. + * @type {number} + * @default + */ + this.fireRate = 100; + + /** + * This is a modifier that is added to the {@link #fireRate} each update to add variety + * to the firing rate of the Weapon. The value is given in milliseconds. + * If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual + * firing rate of the Weapon will be between 150 and 250. + * @type {number} + * @default + */ + this.fireRateVariance = 0; + + /** + * This is a Rectangle from within which the bullets are fired. By default it's a 1x1 + * rectangle, the equivalent of a Point. But you can change the width and height, and if + * larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from. + * @type {Phaser.Rectangle} + */ + this.fireFrom = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE_UP + * or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right. + * @type {integer} + * @default + */ + this.fireAngle = Phaser.ANGLE_UP; + + /** + * When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set. + * @type {boolean} + * @default + */ + this.bulletInheritSpriteSpeed = false; + + /** + * The string based name of the animation that the Bullet will be given on launch. + * This is set via {@link #addBulletAnimation}. + * @type {string} + * @default + */ + this.bulletAnimation = ''; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to pick a random frame from the set. + * @type {boolean} + * @default + */ + this.bulletFrameRandom = false; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to use the next frame in the set. The frame index is then + * advanced one frame until it reaches the end of the set, then it starts from the start + * again. Cycling frames like this allows you to create varied bullet effects via + * sprite sheets. + * @type {boolean} + * @default + */ + this.bulletFrameCycle = false; + + /** + * Should the Bullets wrap around the world bounds? This automatically calls + * `World.wrap` on the Bullet each frame. See the docs for that method for details. + * @type {boolean} + * @default + */ + this.bulletWorldWrap = false; + + /** + * If `bulletWorldWrap` is true then you can provide an optional padding value with this + * property. It's added to the calculations determining when the Bullet should wrap around + * the world or not. The value is given in pixels. + * @type {integer} + * @default + */ + this.bulletWorldWrapPadding = 0; + + /** + * An optional angle offset applied to the Bullets when they are launched. + * This is useful if for example your bullet sprites have been drawn facing up, instead of + * to the right, and you want to fire them at an angle. In which case you can set the + * angle offset to be 90 and they'll be properly rotated when fired. + * @type {number} + * @default + */ + this.bulletAngleOffset = 0; + + /** + * This is a variance added to the angle of Bullets when they are fired. + * If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual + * angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a + * great 'spread' effect to a Weapon. + * @type {number} + * @default + */ + this.bulletAngleVariance = 0; + + /** + * The initial velocity of fired bullets, in pixels per second. + * @type {number} + * @default + */ + this.bulletSpeed = 200; + + /** + * This is a variance added to the speed of Bullets when they are fired. + * If bullets have a {@link #bulletSpeed} value of 200, and a `bulletSpeedVariance` of 50 + * then the actual speed of the Bullets will be between 150 and 250 pixels per second. + * @type {number} + * @default + */ + this.bulletSpeedVariance = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount + * of lifespan the Bullets have set on launch. The value is given in milliseconds. + * When a Bullet hits its lifespan limit it will be automatically killed. + * @type {number} + * @default + */ + this.bulletLifespan = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_DISTANCE` this controls the distance + * the Bullet can travel before it is automatically killed. The distance is given in pixels. + * @type {number} + * @default + */ + this.bulletKillDistance = 0; + + /** + * This is the amount of {@link Phaser.Physics.Arcade.Body#gravity} added to the Bullets physics body when fired. + * Gravity is expressed in pixels / second / second. + * @type {Phaser.Point} + */ + this.bulletGravity = new Phaser.Point(0, 0); + + /** + * Bullets can optionally adjust their rotation in-flight to match their velocity. + * This can create the effect of a bullet 'pointing' to the path it is following, for example + * an arrow being fired from a bow, and works especially well when added to {@link #bulletGravity}. + * @type {boolean} + * @default + */ + this.bulletRotateToVelocity = false; + + /** + * The Texture Key that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string} + * @default + */ + this.bulletKey = ''; + + /** + * The Texture Frame that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string|integer} + * @default + */ + this.bulletFrame = ''; + + /** + * Private var that holds the public `bulletClass` property. + * @type {function} + * @private + */ + this._bulletClass = Phaser.Bullet; + + /** + * Private var that holds the public `bulletCollideWorldBounds` property. + * @type {boolean} + * @private + */ + this._bulletCollideWorldBounds = false; + + /** + * Private var that holds the public `bulletKillType` property. + * @type {integer} + * @private + */ + this._bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; + + /** + * Holds internal data about custom bullet body sizes. + * + * @type {Object} + * @private + */ + this._data = { + customBody: false, + width: 0, + height: 0, + offsetX: 0, + offsetY: 0 + }; + + /** + * This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not. + * It's used in combination with {@link #bulletKillType} when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS` + * or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored. + * If you are tracking a Sprite or Point then the bounds are centered on that object every frame. + * + * @type {Phaser.Rectangle} + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The Rectangle used to calculate the bullet bounds from. + * + * @type {Phaser.Rectangle} + * @private + */ + this.bulletBounds = game.world.bounds; + + /** + * This array stores the frames added via @link #setBulletFrames. + * + * @type {Array} + * @protected + */ + this.bulletFrames = []; + + /** + * The index of the frame within {@link #bulletFrames} that is currently being used. + * This value is only used if {@link #bulletFrameCycle} is set to `true`. + * @type {number} + * @private + */ + this.bulletFrameIndex = 0; + + /** + * An internal object that stores the animation data added via {@link #addBulletAnimation}. + * @type {Object} + * @private + */ + this.anims = {}; + + /** + * The onFire Signal is dispatched each time {@link #fire} is called, and a Bullet is + * _successfully_ launched. The callback is set two arguments: a reference to the bullet sprite itself, + * and a reference to the Weapon that fired the bullet. + * + * @type {Phaser.Signal} + */ + this.onFire = new Phaser.Signal(); + + /** + * The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result + * of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance. + * The callback is sent one argument: A reference to the bullet sprite itself. + * + * @type {Phaser.Signal} + */ + this.onKill = new Phaser.Signal(); + + /** + * The onFireLimit Signal is dispatched if {@link #fireLimit} is > 0, and a bullet launch takes the number + * of shots fired to equal the fire limit. + * The callback is sent two arguments: A reference to this Weapon, and the value of + * {@link #fireLimit}. + * + * @type {Phaser.Signal} + */ + this.onFireLimit = new Phaser.Signal(); + + /** + * The Sprite currently being tracked by the Weapon, if any. + * This is set via the {@link #trackSprite} method. + * + * @type {Phaser.Sprite|Object} + */ + this.trackedSprite = null; + + /** + * The Pointer currently being tracked by the Weapon, if any. + * This is set via the {@link #trackPointer} method. + * + * @type {Phaser.Pointer} + */ + this.trackedPointer = null; + + /** + * If you want this Weapon to be able to fire more than 1 bullet in a single + * update, then set this property to `true`. When `true` the Weapon plugin won't + * set the shot / firing timers until the `postRender` phase of the game loop. + * This means you can call `fire` (and similar methods) as often as you like in one + * single game update. + * + * @type {boolean} + * @default + */ + this.multiFire = false; + + /** + * Internal multiFire test flag. + * + * @type {boolean} + */ + this._hasFired = false; + + /** + * If the Weapon is tracking a Sprite, should it also track the Sprites rotation? + * This is useful for a game such as Asteroids, where you want the weapon to fire based + * on the sprites rotation. + * + * @type {boolean} + * @default + */ + this.trackRotation = false; + + /** + * The Track Offset is a Point object that allows you to specify a pixel offset that bullets use + * when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels + * in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have + * the bullet launched from the center of the Sprite. + * + * @type {Phaser.Point} + */ + this.trackOffset = new Phaser.Point(); + + /** + * Internal firing rate time tracking variable. + * + * @type {number} + * @private + */ + this._nextFire = 0; + + /** + * Internal firing rate time tracking variable used by multiFire. + * + * @type {number} + * @private + */ + this._tempNextFire = 0; + + /** + * Internal firing rotation tracking point. + * + * @type {Phaser.Point} + * @private + */ + this._rotatedPoint = new Phaser.Point(); + +}; + +Phaser.Weapon.prototype = Object.create(Phaser.Plugin.prototype); +Phaser.Weapon.prototype.constructor = Phaser.Weapon; + +/** +* A {@link #bulletKillType} constant that stops the bullets from ever being destroyed automatically. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_NEVER = 0; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when their {@link #bulletLifespan} expires. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_LIFESPAN = 1; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets after they +* exceed the {@link #bulletDistance} from their original firing position. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_DISTANCE = 2; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WEAPON_BOUNDS = 3; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.Camera#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_CAMERA_BOUNDS = 4; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.World#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WORLD_BOUNDS = 5; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_STATIC_BOUNDS = 6; + +/** +* This method performs two actions: First it will check to see if the {@link #bullets} Group exists or not, +* and if not it creates it, adding it the `group` given as the 4th argument. +* +* Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame +* provided (if any). +* +* If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets +* in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of +* the in-flight bullets have been killed, freeing them up for use by the Weapon again. +* +* If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will +* keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however, +* so be careful it doesn't grow too large. +* +* You can either set the texture key and frame here, or via the {@link #bulletKey} and {@link #bulletFrame} +* properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a +* single Weapon instance must share the same texture key however. +* +* @method Phaser.Weapon#createBullets +* @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. +* @param {string} [key] - The Game.cache key of the image that this Sprite will use. +* @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. +* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.createBullets = function (quantity, key, frame, group) { + + if (quantity === undefined) { quantity = 1; } + if (group === undefined) { group = this.game.world; } + + if (this.bullets && !this.bullets.game) + { + this.bullets = null; + } + + if (!this.bullets) + { + this.bullets = this.game.add.physicsGroup(Phaser.Physics.ARCADE, group); + this.bullets.classType = this._bulletClass; + } + + if (quantity !== 0) + { + if (quantity === -1) + { + this.autoExpandBulletsGroup = true; + quantity = 1; + } + + this.bullets.createMultiple(quantity, key, frame); + + this.bullets.setAll('data.bulletManager', this); + + this.bulletKey = key; + this.bulletFrame = frame; + } + + return this; + +}; + +/** +* Call a function on each in-flight bullet in this Weapon. +* +* See {@link Phaser.Group#forEachExists forEachExists} for more details. +* +* @method Phaser.Weapon#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.forEach = function (callback, callbackContext) { + + this.bullets.forEachExists(callback, callbackContext, arguments); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `false` on each bullet in this Weapon. +* This has the effect of stopping them in-flight should they be moving. +* It also stops them being able to be checked for collision. +* +* @method Phaser.Weapon#pauseAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.pauseAll = function () { + + this.bullets.setAll('body.enable', false); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `true` on each bullet in this Weapon. +* This has the effect of resuming their motion should they be in-flight. +* It also enables them for collision checks again. +* +* @method Phaser.Weapon#resumeAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resumeAll = function () { + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Calls {@link Phaser.Bullet#kill} on every in-flight bullet in this Weapon. +* Also re-enables their physics bodies, should they have been disabled via {@link #pauseAll}. +* +* @method Phaser.Weapon#killAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.killAll = function () { + + this.bullets.callAllExists('kill', true); + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Resets the {@link #shots} counter back to zero. This is used when you've set +* {@link #fireLimit} and have hit (or just wish to reset) your limit. +* +* @method Phaser.Weapon#resetShots +* @param {integer} [newLimit] - Optionally set a new {@link #fireLimit}. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resetShots = function (newLimit) { + + this.shots = 0; + + if (newLimit !== undefined) + { + this.fireLimit = newLimit; + } + + return this; + +}; + +/** +* Destroys this Weapon. It removes itself from the PluginManager, destroys +* the {@link #bullets} Group, and nulls internal references. +* +* @method Phaser.Weapon#destroy +*/ +Phaser.Weapon.prototype.destroy = function () { + + this.parent.remove(this, false); + + this.bullets.destroy(); + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#update +* @protected +*/ +Phaser.Weapon.prototype.update = function () { + + if (this._bulletKillType === Phaser.Weapon.KILL_WEAPON_BOUNDS) + { + if (this.trackedSprite) + { + this.trackedSprite.updateTransform(); + this.bounds.centerOn(this.trackedSprite.worldPosition.x, this.trackedSprite.worldPosition.y); + } + else if (this.trackedPointer) + { + this.bounds.centerOn(this.trackedPointer.worldX, this.trackedPointer.worldY); + } + } + + if (this.autofire) + { + this.fire(); + } + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#postRender +* @protected +*/ +Phaser.Weapon.prototype.postRender = function () { + + if (!this.multiFire || !this._hasFired) + { + return; + } + + this._hasFired = false; + + this._nextFire = this._tempNextFire; + +}; + +/** +* Sets this Weapon to track the given Sprite, or any Object with a public {@link Phaser.Component.Core#world world} Point object. +* When a Weapon tracks a Sprite it will automatically update its {@link #fireFrom} value to match the Sprite's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location. +* +* Calling `trackSprite` will reset {@link #trackedPointer} to null, should it have been set, as you can +* only track _either_ a Sprite, or a Pointer, at once, but not both. +* +* @method Phaser.Weapon#trackSprite +* @param {Phaser.Sprite|Object} sprite - The Sprite to track the position of. +* @param {integer} [offsetX=0] - The horizontal offset from the Sprites position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Sprites position to be applied to the Weapon. +* @param {boolean} [trackRotation=false] - Should the Weapon also track the Sprites rotation? +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackSprite = function (sprite, offsetX, offsetY, trackRotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (trackRotation === undefined) { trackRotation = false; } + + this.trackedPointer = null; + this.trackedSprite = sprite; + this.trackRotation = trackRotation; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Sets this Weapon to track the given Pointer. +* When a Weapon tracks a Pointer it will automatically update its {@link #fireFrom} value to match the Pointer's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location. +* +* Calling `trackPointer` will reset {@link #trackedSprite} to null, should it have been set, as you can +* only track _either_ a Pointer, or a Sprite, at once, but not both. +* +* @method Phaser.Weapon#trackPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to track the position of. Defaults to `Input.activePointer` if not specified. +* @param {integer} [offsetX=0] - The horizontal offset from the Pointers position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Pointers position to be applied to the Weapon. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackPointer = function (pointer, offsetX, offsetY) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this.trackedPointer = pointer; + this.trackedSprite = null; + this.trackRotation = false; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Attempts to fire multiple bullets from the positions defined in the given array. +* +* If you provide a `from` argument, or if there is a tracked Sprite or Pointer, then +* the positions are treated as __offsets__ from the given objects position. +* +* If `from` is undefined, and there is no tracked object, then the bullets are fired +* from the given positions, as they exist in the world. +* +* Calling this method sets {@link #multiFire} to `true`. +* +* If there are not enough bullets available in the pool, and the pool cannot be extended, +* then this method may not fire from all of the given positions. +* +* When the bullets are launched they have their texture and frame updated, as required. +* The velocity of the bullets are calculated based on Weapon properties like {@link #bulletSpeed}. +* +* @method Phaser.Weapon#fireMany +* @param {array} positions - An array of positions. Each position can be any Object, as long as it has public `x` and `y` properties, such as Phaser.Point, { x: 0, y: 0 }, Phaser.Sprite, etc. +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullets **from** the `x` and `y` properties of this object, _instead_ of any {@link #trackedSprite} or `trackedPointer` that is set. +* @return {array} An array containing all of the fired Phaser.Bullet objects, if a launch was successful, otherwise an empty array. +*/ +Phaser.Weapon.prototype.fireMany = function (positions, from) { + + this.multiFire = true; + + var bullets = []; + + var _this = this; + + if (from || this.trackedSprite || this.trackedPointer) + { + positions.forEach(function(offset) { + + bullets.push(_this.fire(from, null, null, offset.x, offset.y)); + + }); + } + else + { + positions.forEach(function(position) { + + bullets.push(_this.fire(position)); + + }); + } + + return bullets; + +}; + +/** +* Attempts to fire a single Bullet from a tracked Sprite or Pointer, but applies an offset +* to the position first. This is the same as calling {@link #fire} and passing in the offset arguments. +* +* If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like {@link #bulletSpeed}. +* +* If you wish to fire multiple bullets in a single game update, then set {@link #multiFire} to `true` +* and you can call this method as many times as you like, per loop. See also {@link #fireMany}. +* +* @method Phaser.Weapon#fireOffset +* @param {number} [offsetX=0] - The horizontal offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @param {number} [offsetY=0] - The vertical offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fireOffset = function (offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + return this.fire(null, null, null, offsetX, offsetY); + +}; + +/** +* Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at. +* +* If you don't provide any of the arguments then it uses those set via properties such as {@link #trackedSprite}, +* {@link #bulletAngle} and so on. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like `bulletSpeed`. +* +* If you wish to fire multiple bullets in a single game update, then set `Weapon.multiFire = true` +* and you can call `fire` as many times as you like, per loop. Multiple fires in a single update +* only counts once towards the `shots` total, but you will still receive a Signal for each bullet. +* +* @method Phaser.Weapon#fire +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides {@link #trackedSprite} or `trackedPointer`. Pass `null` to ignore it. +* @param {number} [x] - The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [offsetX=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a horizontal offset from the launch position. +* @param {number} [offsetY=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a vertical offset from the launch position. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fire = function (from, x, y, offsetX, offsetY) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (this.game.time.now < this._nextFire || (this.fireLimit > 0 && this.shots === this.fireLimit)) + { + return null; + } + + var speed = this.bulletSpeed; + + // Apply +- speed variance + if (this.bulletSpeedVariance !== 0) + { + speed += Phaser.Math.between(-this.bulletSpeedVariance, this.bulletSpeedVariance); + } + + if (from) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(from.x, from.y); + } + else + { + this.fireFrom.x = from.x; + this.fireFrom.y = from.y; + } + } + else if (this.trackedSprite) + { + if (this.trackRotation) + { + this._rotatedPoint.set(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.worldRotation); + + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this._rotatedPoint.x, this._rotatedPoint.y); + } + else + { + this.fireFrom.x = this._rotatedPoint.x; + this.fireFrom.y = this._rotatedPoint.y; + } + } + else + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedSprite.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedSprite.world.y + this.trackOffset.y; + } + } + + if (this.bulletInheritSpriteSpeed) + { + speed += this.trackedSprite.body.speed; + } + } + else if (this.trackedPointer) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedPointer.world.x + this.trackOffset.x, this.trackedPointer.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedPointer.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedPointer.world.y + this.trackOffset.y; + } + } + + if (offsetX !== undefined) + { + this.fireFrom.x += offsetX; + } + + if (offsetY !== undefined) + { + this.fireFrom.y += offsetY; + } + + var fromX = (this.fireFrom.width > 1) ? this.fireFrom.randomX : this.fireFrom.x; + var fromY = (this.fireFrom.height > 1) ? this.fireFrom.randomY : this.fireFrom.y; + + var angle = (this.trackRotation) ? this.trackedSprite.angle : this.fireAngle; + + // The position (in world space) to fire the bullet towards, if set + if (x !== null && y !== null) + { + angle = this.game.math.radToDeg(Math.atan2(y - fromY, x - fromX)); + } + + // Apply +- angle variance + if (this.bulletAngleVariance !== 0) + { + angle += Phaser.Math.between(-this.bulletAngleVariance, this.bulletAngleVariance); + } + + var moveX = 0; + var moveY = 0; + + // Avoid sin/cos for right-angled shots + if (angle === 0 || angle === 180) + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + } + else if (angle === 90 || angle === 270) + { + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + else + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + + var bullet = null; + + if (this.autoExpandBulletsGroup) + { + bullet = this.bullets.getFirstExists(false, true, fromX, fromY, this.bulletKey, this.bulletFrame); + + bullet.data.bulletManager = this; + } + else + { + bullet = this.bullets.getFirstExists(false); + } + + if (bullet) + { + bullet.reset(fromX, fromY); + + bullet.data.fromX = fromX; + bullet.data.fromY = fromY; + bullet.data.killType = this.bulletKillType; + bullet.data.killDistance = this.bulletKillDistance; + bullet.data.rotateToVelocity = this.bulletRotateToVelocity; + + if (this.bulletKillType === Phaser.Weapon.KILL_LIFESPAN) + { + bullet.lifespan = this.bulletLifespan; + } + + bullet.angle = angle + this.bulletAngleOffset; + + // Frames and Animations + if (this.bulletAnimation !== '') + { + if (bullet.animations.getAnimation(this.bulletAnimation) === null) + { + var anim = this.anims[this.bulletAnimation]; + + bullet.animations.add(anim.name, anim.frames, anim.frameRate, anim.loop, anim.useNumericIndex); + } + + bullet.animations.play(this.bulletAnimation); + } + else + { + if (this.bulletFrameCycle) + { + bullet.frame = this.bulletFrames[this.bulletFrameIndex]; + + this.bulletFrameIndex++; + + if (this.bulletFrameIndex >= this.bulletFrames.length) + { + this.bulletFrameIndex = 0; + } + } + else if (this.bulletFrameRandom) + { + bullet.frame = this.bulletFrames[Math.floor(Math.random() * this.bulletFrames.length)]; + } + } + + if (bullet.data.bodyDirty) + { + if (this._data.customBody) + { + bullet.body.setSize(this._data.width, this._data.height, this._data.offsetX, this._data.offsetY); + } + + bullet.body.collideWorldBounds = this.bulletCollideWorldBounds; + + bullet.data.bodyDirty = false; + } + + bullet.body.velocity.set(moveX, moveY); + bullet.body.gravity.set(this.bulletGravity.x, this.bulletGravity.y); + + var next = 0; + + if (this.bulletSpeedVariance !== 0) + { + var rate = this.fireRate; + + rate += Phaser.Math.between(-this.fireRateVariance, this.fireRateVariance); + + if (rate < 0) + { + rate = 0; + } + + next = this.game.time.now + rate; + } + else + { + next = this.game.time.now + this.fireRate; + } + + if (this.multiFire) + { + if (!this._hasFired) + { + // We only add 1 to the 'shots' count for multiFire shots + this._hasFired = true; + this._tempNextFire = next; + this.shots++; + } + } + else + { + this._nextFire = next; + + this.shots++; + } + + this.onFire.dispatch(bullet, this, speed); + + if (this.fireLimit > 0 && this.shots === this.fireLimit) + { + this.onFireLimit.dispatch(this, this.fireLimit); + } + } + + return bullet; + +}; + +/** +* Fires a bullet **at** the given Pointer. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtPointer = function (pointer) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + + return this.fire(null, pointer.worldX, pointer.worldY); + +}; + +/** +* Fires a bullet **at** the given Sprite. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtSprite +* @param {Phaser.Sprite} [sprite] - The Sprite to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtSprite = function (sprite) { + + return this.fire(null, sprite.world.x, sprite.world.y); + +}; + +/** +* Fires a bullet **at** the given coordinates. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtXY +* @param {number} [x] - The x coordinate, in world space, to fire the bullet towards. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtXY = function (x, y) { + + return this.fire(null, x, y); + +}; + +/** +* You can modify the size of the physics Body the Bullets use to be any dimension you need. +* This allows you to make it smaller, or larger, than the parent Sprite. +* You can also control the x and y offset of the Body. This is the position of the +* Body relative to the top-left of the Sprite _texture_. +* +* For example: If you have a Sprite with a texture that is 80x100 in size, +* and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: +* +* `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, 34)` +* +* Where the first two parameters are the new Body size (32x32 pixels) relative to the Sprite's scale. +* 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 +* is the vertical offset. +* +* @method Phaser.Weapon#setBulletBodyOffset +* @param {number} width - The width of the Body. +* @param {number} height - The height of the Body. +* @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture. +* @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture. +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletBodyOffset = function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this._data.customBody = true; + this._data.width = width; + this._data.height = height; + this._data.offsetX = offsetX; + this._data.offsetY = offsetY; + + // Update all bullets in the pool + this.bullets.callAll('body.setSize', 'body', width, height, offsetX, offsetY); + this.bullets.setAll('data.bodyDirty', false); + + return this; + +}; + +/** +* Sets the texture frames that the bullets can use when being launched. +* +* This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet. +* +* It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values +* provided. Then it sets the frame index to be zero. +* +* You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames +* when they're fired, or pick one at random. +* +* @method Phaser.Weapon#setBulletFrames +* @param {integer} min - The minimum value the frame can be. Usually zero. +* @param {integer} max - The maximum value the frame can be. +* @param {boolean} [cycle=true] - Should the bullet frames cycle as they are fired? +* @param {boolean} [random=false] - Should the bullet frames be picked at random as they are fired? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletFrames = function (min, max, cycle, random) { + + if (cycle === undefined) { cycle = true; } + if (random === undefined) { random = false; } + + this.bulletFrames = Phaser.ArrayUtils.numberArray(min, max); + + this.bulletFrameIndex = 0; + + this.bulletFrameCycle = cycle; + this.bulletFrameRandom = random; + + return this; + +}; + +/** +* Adds a new animation under the given key. Optionally set the frames, frame rate and loop. +* The arguments are all the same as for `Animation.add`, and work in the same way. +* +* {@link #bulletAnimation} will be set to this animation after it's created. From that point on, all +* bullets fired will play using this animation. You can swap between animations by calling this method +* several times, and then just changing the {@link #bulletAnimation} property to the name of the animation +* you wish to play for the next launched bullet. +* +* If you wish to stop using animations at all, set {@link #bulletAnimation} to '' (an empty string). +* +* @method Phaser.Weapon#addBulletAnimation +* @param {string} name - The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast". +* @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.addBulletAnimation = function (name, frames, frameRate, loop, useNumericIndex) { + + this.anims[name] = { + name: name, + frames: frames, + frameRate: frameRate, + loop: loop, + useNumericIndex: useNumericIndex + }; + + // Add the animation to any existing bullets in the pool + this.bullets.callAll('animations.add', 'animations', name, frames, frameRate, loop, useNumericIndex); + + this.bulletAnimation = name; + + return this; + +}; + +/** +* Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets +* both in-flight, and available. And optionally the physics debug bodies of the bullets. +* +* @method Phaser.Weapon#debug +* @param {integer} [x=16] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {integer} [y=32] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {boolean} [debugBodies=false] - Optionally draw the physics body of every bullet in-flight. +*/ +Phaser.Weapon.prototype.debug = function (x, y, debugBodies) { + + if (x === undefined) { x = 16; } + if (y === undefined) { y = 32; } + if (debugBodies === undefined) { debugBodies = false; } + + this.game.debug.text("Weapon Plugin", x, y); + this.game.debug.text("Bullets Alive: " + this.bullets.total + " - Total: " + this.bullets.length, x, y + 24); + + if (debugBodies) + { + this.bullets.forEachExists(this.game.debug.body, this.game.debug, 'rgba(255, 0, 255, 0.8)'); + } + +}; + +/** +* The Class of the bullets that are launched by this Weapon. Defaults to {@link Phaser.Bullet}, but can be +* overridden before calling `createBullets` and set to your own class type. +* +* It should be a constructor function accepting `(game, x, y, key, frame)`. +* +* @name Phaser.Weapon#bulletClass +* @property {function} bulletClass +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletClass", { + + get: function () { + + return this._bulletClass; + + }, + + set: function (classType) { + + this._bulletClass = classType; + + // `this.bullets` exists only after createBullets() + if (this.bullets) { + this.bullets.classType = this._bulletClass; + } + } + +}); + +/** +* This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`. +* +* There are 7 different "kill types" available: +* +* * `Phaser.Weapon.KILL_NEVER` +* The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code. +* +* * `Phaser.Weapon.KILL_LIFESPAN` +* The bullets are automatically killed when their `bulletLifespan` amount expires. +* +* * `Phaser.Weapon.KILL_DISTANCE` +* The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position. +* +* * `Phaser.Weapon.KILL_WEAPON_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* +* * `Phaser.Weapon.KILL_CAMERA_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.Camera#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_WORLD_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.World#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_STATIC_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to +* match the position of a tracked sprite or pointer. +* +* @name Phaser.Weapon#bulletKillType +* @property {integer} bulletKillType +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletKillType", { + + get: function () { + + return this._bulletKillType; + + }, + + set: function (type) { + + switch (type) + { + case Phaser.Weapon.KILL_STATIC_BOUNDS: + case Phaser.Weapon.KILL_WEAPON_BOUNDS: + this.bulletBounds = this.bounds; + break; + + case Phaser.Weapon.KILL_CAMERA_BOUNDS: + this.bulletBounds = this.game.camera.view; + break; + + case Phaser.Weapon.KILL_WORLD_BOUNDS: + this.bulletBounds = this.game.world.bounds; + break; + } + + this._bulletKillType = type; + + } + +}); + +/** +* Should bullets collide with the World bounds or not? +* +* @name Phaser.Weapon#bulletCollideWorldBounds +* @property {boolean} bulletCollideWorldBounds +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletCollideWorldBounds", { + + get: function () { + + return this._bulletCollideWorldBounds; + + }, + + set: function (value) { + + this._bulletCollideWorldBounds = value; + + this.bullets.setAll('body.collideWorldBounds', value); + this.bullets.setAll('data.bodyDirty', false); + + } + +}); + +/** +* The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Weapon.prototype, "x", { + + get: function () { + + return this.fireFrom.x; + + }, + + set: function (value) { + + this.fireFrom.x = value; + } + +}); + +/** +* The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Weapon.prototype, "y", { + + get: function () { + + return this.fireFrom.y; + + }, + + set: function (value) { + + this.fireFrom.y = value; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites, +* with a few extra properties in the data object to handle Weapon specific features. +* +* @class Phaser.Bullet +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Bullet = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + this.anchor.set(0.5); + + this.data = { + bulletManager: null, + fromX: 0, + fromY: 0, + bodyDirty: true, + rotateToVelocity: false, + killType: 0, + killDistance: 0 + }; + +}; + +Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Bullet.prototype.constructor = Phaser.Bullet; + +/** +* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool. +* Also dispatches the `Weapon.onKill` signal. +* +* @method Phaser.Bullet#kill +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + this.data.bulletManager.onKill.dispatch(this); + + return this; + +}; + +/** +* Updates the Bullet, killing as required. +* +* @method Phaser.Bullet#update +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.update = function () { + + if (!this.exists) + { + return; + } + + if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN) + { + if (this.data.killType === Phaser.Weapon.KILL_DISTANCE) + { + if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance) + { + this.kill(); + } + } + else + { + if (!this.data.bulletManager.bulletBounds.intersects(this)) + { + this.kill(); + } + } + } + + if (this.data.rotateToVelocity) + { + this.rotation = this.body.velocity.atan(); + } + + if (this.data.bulletManager.bulletWorldWrap) + { + this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding); + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. +* +* Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to +* the Video instead (see `startMediaStream` method) +* +* The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback +* changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. +* +* Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. +* +* If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. +* Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. +* +* On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. +* This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio +* it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` +* method to try and work around this limitation, but see the method help for details. +* +* Small screen devices, especially iPod and iPhone will launch the video in its own native video player, +* outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. +* +* Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) +* then you need to add your own event listener +* +* @class Phaser.Video +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. +* @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) +*/ +Phaser.Video = function (game, key, url) { + + if (key === undefined) { key = null; } + if (url === undefined) { url = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. + * @default null + */ + this.key = key; + + /** + * @property {number} width - The width of the video in pixels. + * @default + */ + this.width = 0; + + /** + * @property {number} height - The height of the video in pixels. + * @default + */ + this.height = 0; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.VIDEO; + + /** + * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. + * @default + */ + this.touchLocked = false; + + /** + * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. + */ + this.onChangeSource = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam. + */ + this.onAccess = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. + */ + this.onError = new Phaser.Signal(); + + /** + * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. + * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. + * @property {Phaser.Signal} onTimeout + */ + this.onTimeout = new Phaser.Signal(); + + /** + * This signal is dispatched when the Video is unlocked. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * Start playing the video when it's unlocked. + * @property {boolean} playWhenUnlocked + * @default + */ + this.playWhenUnlocked = true; + + /** + * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. + * @default + */ + this.timeout = 15000; + + /** + * @property {integer} _timeOutID - setTimeout ID. + * @private + */ + this._timeOutID = null; + + /** + * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document. + */ + this.video = null; + + /** + * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. + */ + this.videoStream = null; + + /** + * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam. + */ + this.isStreaming = false; + + /** + * When starting playback of a video Phaser will monitor its readyState using a setTimeout call. + * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * @property {integer} retryLimit + * @default + */ + this.retryLimit = 20; + + /** + * @property {integer} retry - The current retry attempt. + * @default + */ + this.retry = 0; + + /** + * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video. + * @default + */ + this.retryInterval = 500; + + /** + * @property {integer} _retryID - The callback ID of the retry setTimeout. + * @private + */ + this._retryID = null; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {boolean} _codePaused - Internal paused tracking var. + * @private + * @default + */ + this._codePaused = false; + + /** + * @property {boolean} _paused - Internal paused tracking var. + * @private + * @default + */ + this._paused = false; + + /** + * @property {boolean} _pending - Internal var tracking play pending. + * @private + * @default + */ + this._pending = false; + + /** + * @property {boolean} _pendingChangeSource - Internal var tracking play pending. + * @private + * @default + */ + this._pendingChangeSource = false; + + /** + * @property {boolean} _autoplay - Internal var tracking autoplay when changing source. + * @private + * @default + */ + this._autoplay = false; + + /** + * @property {function} _endCallback - The addEventListener ended function. + * @private + */ + this._endCallback = null; + + /** + * @property {function} _playCallback - The addEventListener playing function. + * @private + */ + this._playCallback = null; + + if (key && this.game.cache.checkVideoKey(key)) + { + var _video = this.game.cache.getVideo(key); + + if (_video.isBlob) + { + this.createVideoFromBlob(_video.data); + } + else + { + this.video = _video.data; + } + + this.width = this.video.videoWidth; + this.height = this.video.videoHeight; + } + else if (url) + { + this.createVideoFromURL(url, false); + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + if (this.video && !url) + { + this.baseTexture = new PIXI.BaseTexture(this.video, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + else + { + this.baseTexture = new PIXI.BaseTexture(Phaser.Cache.DEFAULT.baseTexture.source, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering. + * @default + */ + this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video'); + + this.texture.setFrame(this.textureFrame); + + this.texture.valid = false; + + if (key !== null && this.video) + { + this.texture.valid = this.video.canplay; + } + + /** + * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). + * When called the BitmapData is updated with a grab taken from the current video playing or active video stream. + * If Phaser has been compiled without BitmapData support this property will always be `null`. + * + * @property {Phaser.BitmapData} snapshot + * @readOnly + */ + this.snapshot = null; + + if (Phaser.BitmapData) + { + this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height); + } + + if (this.game.device.needsTouchUnlock()) + { + this.setTouchLock(); + } + else + { + if (_video) + { + _video.locked = false; + } + } + +}; + +Phaser.Video.prototype = { + + /** + * Connects to an external media stream for the webcam, rather than using a local one. + * + * @method Phaser.Video#connectToMediaStream + * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses. + * @param {MediaStream} stream - The Video Stream data. + * @return {Phaser.Video} This Video object for method chaining. + */ + connectToMediaStream: function (video, stream) { + + if (video && stream) + { + this.video = video; + this.videoStream = stream; + + this.isStreaming = true; + this.baseTexture.source = this.video; + this.updateTexture(null, this.video.videoWidth, this.video.videoHeight); + + this.onAccess.dispatch(this); + } + + return this; + + }, + + /** + * Instead of playing a video file this method allows you to stream video data from an attached webcam. + * + * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam. + * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream. + * + * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError + * or MediaStreamError event. + * + * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions. + * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device. + * You can listen for this with the onChangeSource signal. + * + * @method Phaser.Video#startMediaStream + * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream. + * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source. + * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source. + * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia. + */ + startMediaStream: function (captureAudio, width, height) { + + if (captureAudio === undefined) { captureAudio = false; } + if (width === undefined) { width = null; } + if (height === undefined) { height = null; } + + if (!this.game.device.getUserMedia) + { + this.onError.dispatch(this, 'No getUserMedia'); + return false; + } + + if (this.videoStream !== null) + { + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + this.videoStream.stop(); + } + } + + this.removeVideoElement(); + + this.video = document.createElement("video"); + this.video.setAttribute('autoplay', 'autoplay'); + + if (width !== null) + { + this.video.width = width; + } + + if (height !== null) + { + this.video.height = height; + } + + // Request access to the webcam + + this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout); + + try { + navigator.getUserMedia( + { "audio": captureAudio, "video": true }, + this.getUserMediaSuccess.bind(this), + this.getUserMediaError.bind(this) + ); + } + catch (error) + { + this.getUserMediaError(error); + } + + return this; + + }, + + /** + * @method Phaser.Video#getUserMediaTimeout + * @private + */ + getUserMediaTimeout: function () { + + clearTimeout(this._timeOutID); + + this.onTimeout.dispatch(this); + + }, + + /** + * @method Phaser.Video#getUserMediaError + * @private + */ + getUserMediaError: function (event) { + + clearTimeout(this._timeOutID); + + this.onError.dispatch(this, event); + + }, + + /** + * @method Phaser.Video#getUserMediaSuccess + * @private + */ + getUserMediaSuccess: function (stream) { + + clearTimeout(this._timeOutID); + + // Attach the stream to the video + this.videoStream = stream; + + // Set the source of the video element with the stream from the camera + if (this.video.mozSrcObject !== undefined) + { + this.video.mozSrcObject = stream; + } + else + { + this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; + } + + var self = this; + + this.video.onloadeddata = function () { + + var retry = 10; + + function checkStream () { + + if (retry > 0) + { + if (self.video.videoWidth > 0) + { + // Patch for Firefox bug where the height can't be read from the video + var width = self.video.videoWidth; + var height = self.video.videoHeight; + + if (isNaN(self.video.videoHeight)) + { + height = width / (4/3); + } + + self.video.play(); + + self.isStreaming = true; + self.baseTexture.source = self.video; + self.updateTexture(null, width, height); + self.onAccess.dispatch(self); + } + else + { + window.setTimeout(checkStream, 500); + } + } + else + { + console.warn('Unable to connect to video stream. Webcam error?'); + } + + retry--; + } + + checkStream(); + + }; + + }, + + /** + * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format. + * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience. + * + * @method Phaser.Video#createVideoFromBlob + * @param {Blob} blob - The Blob containing the video data. + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromBlob: function (blob) { + + var _this = this; + + this.video = document.createElement("video"); + this.video.controls = false; + this.video.setAttribute('autoplay', 'autoplay'); + this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true); + this.video.src = window.URL.createObjectURL(blob); + this.video.canplay = true; + + return this; + + }, + + /** + * Creates a new Video element from the given URL. + * + * @method Phaser.Video#createVideoFromURL + * @param {string} url - The URL of the video. + * @param {boolean} [autoplay=false] - Automatically start the video? + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromURL: function (url, autoplay) { + + if (autoplay === undefined) { autoplay = false; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + if (this.texture) + { + this.texture.valid = false; + } + + this.video = document.createElement("video"); + this.video.controls = false; + + if (autoplay) + { + this.video.setAttribute('autoplay', 'autoplay'); + } + + this.video.src = url; + + this.video.canplay = true; + + this.video.load(); + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.key = url; + + return this; + + }, + + /** + * Called automatically if the video source changes and updates the internal texture dimensions. + * Then dispatches the onChangeSource signal. + * + * @method Phaser.Video#updateTexture + * @param {object} [event] - The event which triggered the texture update. + * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used. + * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used. + */ + updateTexture: function (event, width, height) { + + var change = false; + + if (width === undefined || width === null) { width = this.video.videoWidth; change = true; } + if (height === undefined || height === null) { height = this.video.videoHeight; } + + this.width = width; + this.height = height; + + if (this.baseTexture.source !== this.video) + { + this.baseTexture.source = this.video; + } + + this.baseTexture.forceLoaded(width, height); + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.valid = true; + + if (this.snapshot) + { + this.snapshot.resize(width, height); + } + + if (change && this.key !== null) + { + this.onChangeSource.dispatch(this, width, height); + + if (this._autoplay) + { + this.video.play(); + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + } + + }, + + /** + * Called when the video completes playback (reaches and ended state). + * Dispatches the Video.onComplete signal. + * + * @method Phaser.Video#complete + */ + complete: function () { + + this.onComplete.dispatch(this); + + }, + + /** + * Starts this video playing. + * + * If the video is already playing, or has been queued to play with `changeSource` then this method just returns. + * + * @method Phaser.Video#play + * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. + * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate. + * @return {Phaser.Video} This Video object for method chaining. + */ + play: function (loop, playbackRate) { + + if (this._pendingChangeSource) + { + return this; + } + + if (loop === undefined) { loop = false; } + if (playbackRate === undefined) { playbackRate = 1; } + + if (this.game.sound.onMute) + { + this.game.sound.onMute.add(this.setMute, this); + this.game.sound.onUnMute.add(this.unsetMute, this); + + if (this.game.sound.mute) + { + this.setMute(); + } + } + + this.game.onPause.add(this.setPause, this); + this.game.onResume.add(this.setResume, this); + + this._endCallback = this.complete.bind(this); + + this.video.addEventListener('ended', this._endCallback, true); + this.video.addEventListener('webkitendfullscreen', this._endCallback, true); + + if (loop) + { + this.video.loop = 'loop'; + } + else + { + this.video.loop = ''; + } + + this.video.playbackRate = playbackRate; + + if (this.touchLocked) + { + this._pending = true; + } + else + { + this._pending = false; + + if (this.key !== null) + { + if (this.video.readyState !== 4) + { + this.retry = this.retryLimit; + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + this._playCallback = this.playHandler.bind(this); + this.video.addEventListener('playing', this._playCallback, true); + } + } + + this.video.play(); + + this.onPlay.dispatch(this, loop, playbackRate); + } + + return this; + + }, + + /** + * Called when the video starts to play. Updates the texture. + * + * @method Phaser.Video#playHandler + * @private + */ + playHandler: function () { + + this.video.removeEventListener('playing', this._playCallback, true); + + this.updateTexture(); + + }, + + /** + * Stops the video playing. + * + * This removes all locally set signals. + * + * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead. + * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to + * call `Video.destroy` instead. + * + * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam. + * + * @method Phaser.Video#stop + * @return {Phaser.Video} This Video object for method chaining. + */ + stop: function () { + + if (this.game.sound.onMute) + { + this.game.sound.onMute.remove(this.setMute, this); + this.game.sound.onUnMute.remove(this.unsetMute, this); + } + + this.game.onPause.remove(this.setPause, this); + this.game.onResume.remove(this.setResume, this); + + // Stream or file? + + if (this.isStreaming) + { + if (this.video.mozSrcObject) + { + this.video.mozSrcObject.stop(); + this.video.src = null; + } + else + { + this.video.src = ''; + + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + if (this.videoStream.getTracks) + { + this.videoStream.getTracks().forEach(function (track) { + track.stop(); + }); + } + else + { + this.videoStream.stop(); + } + } + } + + this.videoStream = null; + this.isStreaming = false; + } + else + { + this.video.removeEventListener('ended', this._endCallback, true); + this.video.removeEventListener('webkitendfullscreen', this._endCallback, true); + this.video.removeEventListener('playing', this._playCallback, true); + + if (this.touchLocked) + { + this._pending = false; + } + else + { + this.video.pause(); + } + } + + return this; + + }, + + /** + * Updates the given Display Objects so they use this Video as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.Video#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.Video} This Video object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. + * + * @method Phaser.Video#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set Video.disableTextureUpload to `true`. + * + * @method Phaser.Video#render + */ + render: function () { + + if (!this.disableTextureUpload && this.playing) + { + this.baseTexture.dirty(); + } + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + this.video.muted = true; + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + this.video.muted = false; + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setPause + * @private + */ + setPause: function () { + + if (this._paused || this.touchLocked) + { + return; + } + + this._paused = true; + + this.video.pause(); + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setResume + * @private + */ + setResume: function () { + + if (!this._paused || this._codePaused || this.touchLocked) + { + return; + } + + this._paused = false; + + if (!this.video.ended) + { + this.video.play(); + } + + }, + + /** + * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it. + * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over" + * split into three different Video objects, then you will need the user to touch-unlock every single one of them. + * + * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains + * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again. + * + * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate. + * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it + * cannot render the new video on iOS (desktop browsers cope better). + * + * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know + * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state + * are adopted automatically by the new video. + * + * @method Phaser.Video#changeSource + * @param {string} src - The new URL to change the video.src to. + * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated? + * @return {Phaser.Video} This Video object for method chaining. + */ + changeSource: function (src, autoplay) { + + if (autoplay === undefined) { autoplay = true; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + this.texture.valid = false; + + this.video.pause(); + + this._pendingChangeSource = true; + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.video.src = src; + + this.video.load(); + + this._autoplay = autoplay; + + if (!autoplay) + { + this.paused = true; + } + + return this; + + }, + + /** + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.Video#checkVideoProgress + * @private + */ + checkVideoProgress: function () { + + // if (this.video.readyState === 2 || this.video.readyState === 4) + if (this.video.readyState === 4) + { + this._pendingChangeSource = false; + + // We've got enough data to update the texture for playback + this.updateTexture(); + } + else + { + this.retry--; + + if (this.retry > 0) + { + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming); + } + } + + }, + + /** + * Sets the Input Manager touch callback to be Video.unlock. + * Required for mobile video unlocking. Mostly just used internally. + * + * @method Phaser.Video#setTouchLock + */ + setTouchLock: function () { + + this.game.input.addTouchLockCallback(this.unlock, this, true); + this.touchLocked = true; + + }, + + /** + * Enables the video on mobile devices, usually after the first touch. + * If the SoundManager hasn't been unlocked then this will automatically unlock that as well. + * Only one video can be pending unlock at any one time. + * + * @method Phaser.Video#unlock + */ + unlock: function () { + + this.touchLocked = false; + + if (this.playWhenUnlocked) + { + this.video.play(); + + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + + if (this.key) + { + var _video = this.game.cache.getVideo(this.key); + + if (_video && !_video.isBlob) + { + _video.locked = false; + } + } + + this.onTouchUnlock.dispatch(this); + + return true; + + }, + + /** + * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData. + * + * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw. + * + * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy. + * + * @method Phaser.Video#grab + * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false. + * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining. + */ + grab: function (clear, alpha, blendMode) { + + if (clear === undefined) { clear = false; } + if (alpha === undefined) { alpha = 1; } + if (blendMode === undefined) { blendMode = null; } + + if (this.snapshot === null) + { + console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable'); + return; + } + + if (clear) + { + this.snapshot.cls(); + } + + this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode); + + return this.snapshot; + + }, + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * Also removes the autoplay and src attributes and nulls the reference. + * + * @method Phaser.Video#removeVideoElement + */ + removeVideoElement: function () { + + if (!this.video) + { + return; + } + + if (this.video.parentNode) + { + this.video.parentNode.removeChild(this.video); + } + + while (this.video.hasChildNodes()) + { + this.video.removeChild(this.video.firstChild); + } + + this.video.removeAttribute('autoplay'); + this.video.removeAttribute('src'); + + this.video = null; + + }, + + /** + * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`. + * If any Sprites are using this Video as their texture it is up to you to manage those. + * + * @method Phaser.Video#destroy + */ + destroy: function () { + + this.stop(); + + this.removeVideoElement(); + + if (this.touchLocked) + { + this.game.input.touch.removeTouchLockCallback(this.unlock, this); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + + } + +}; + +/** +* @name Phaser.Video#currentTime +* @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time. +*/ +Object.defineProperty(Phaser.Video.prototype, "currentTime", { + + get: function () { + + return (this.video) ? this.video.currentTime : 0; + + }, + + set: function (value) { + + this.video.currentTime = value; + + } + +}); + +/** +* @name Phaser.Video#duration +* @property {number} duration - The duration of the video in seconds. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "duration", { + + get: function () { + + return (this.video) ? this.video.duration : 0; + + } + +}); + +/** +* @name Phaser.Video#progress +* @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "progress", { + + get: function () { + + return (this.video) ? (this.video.currentTime / this.video.duration) : 0; + + } + +}); + +/** +* @name Phaser.Video#mute +* @property {boolean} mute - Gets or sets the muted state of the Video. +*/ +Object.defineProperty(Phaser.Video.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || null; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* Gets or sets the paused state of the Video. +* If the video is still touch locked (such as on iOS devices) this call has no effect. +* +* @name Phaser.Video#paused +* @property {boolean} paused +*/ +Object.defineProperty(Phaser.Video.prototype, "paused", { + + get: function () { + + return this._paused; + + }, + + set: function (value) { + + value = value || null; + + if (this.touchLocked) + { + return; + } + + if (value) + { + if (this._paused) + { + return; + } + + this._codePaused = true; + this.setPause(); + } + else + { + if (!this._paused) + { + return; + } + + this._codePaused = false; + this.setResume(); + } + } + +}); + +/** +* @name Phaser.Video#volume +* @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Video.prototype, "volume", { + + get: function () { + + return (this.video) ? this.video.volume : 1; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this.video) + { + this.video.volume = value; + } + + } + +}); + +/** +* @name Phaser.Video#playbackRate +* @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing. +*/ +Object.defineProperty(Phaser.Video.prototype, "playbackRate", { + + get: function () { + + return (this.video) ? this.video.playbackRate : 1; + + }, + + set: function (value) { + + if (this.video) + { + this.video.playbackRate = value; + } + + } + +}); + +/** +* Gets or sets if the Video is set to loop. +* Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. +* If the video isn't yet set this will always return false. +* +* @name Phaser.Video#loop +* @property {boolean} loop +*/ +Object.defineProperty(Phaser.Video.prototype, "loop", { + + get: function () { + + return (this.video) ? this.video.loop : false; + + }, + + set: function (value) { + + if (value && this.video) + { + this.video.loop = 'loop'; + } + else if (this.video) + { + this.video.loop = ''; + } + + } + +}); + +/** +* @name Phaser.Video#playing +* @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "playing", { + + get: function () { + + return (this.video) ? !(this.video.paused && this.video.ended) : false; + + } + +}); + +Phaser.Video.prototype.constructor = Phaser.Video; + +/* global Phaser:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Pixi expects these globals to exist + +if (PIXI.blendModes === undefined) +{ + PIXI.blendModes = Phaser.blendModes; +} + +if (PIXI.scaleModes === undefined) +{ + PIXI.scaleModes = Phaser.scaleModes; +} + +if (PIXI.Texture.emptyTexture === undefined) +{ + PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture()); +} + +if (PIXI.DisplayObject._tempMatrix === undefined) +{ + PIXI.DisplayObject._tempMatrix = new Phaser.Matrix(); +} + +PIXI.TextureSilentFail = true; + +// Required by Particle Storm +PIXI.canUseNewCanvasBlendModes = function () { + return Phaser.Device.canUseMultiply; +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = Phaser; + } + exports.Phaser = Phaser; + } else if (typeof define !== 'undefined' && define.amd) { + define('Phaser', (function() { return root.Phaser = Phaser; })() ); + } else { + root.Phaser = Phaser; + } + + return Phaser; +}).call(this); + +/* +* "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer +*/ diff --git a/Digital Assignment 4/js/phaser.map b/Digital Assignment 4/js/phaser.map new file mode 100644 index 000000000..70723bbf8 --- /dev/null +++ b/Digital Assignment 4/js/phaser.map @@ -0,0 +1 @@ +{"version":3,"sources":["phaser.js"],"names":["e","exports","module","f","window","global","self","p2","t","n","r","s","o","u","a","require","i","Error","call","length","1","_dereq_","Line","Scalar","lineInt","l1","l2","precision","a1","b1","c1","a2","b2","c2","det","eq","segmentsIntersect","p1","q1","q2","dx","dy","da","db","./Scalar","2","Point","area","b","c","left","leftOn","right","rightOn","tmpPoint1","tmpPoint2","collinear","thresholdAngle","ab","bc","dot","magA","Math","sqrt","magB","acos","sqdist","3","Polygon","this","vertices","getIntersectionPoint","delta","prototype","at","v","first","last","clear","append","poly","from","to","push","makeCCW","br","reverse","tmp","N","pop","isReflex","tmpLine1","tmpLine2","canSee","p","dist","copy","j","targetPoly","k","getCutEdges","min","tmp1","tmp2","tmpPoly","nDiags","Number","MAX_VALUE","decomp","edges","slice","cutEdges","Array","polys","cutEdge","result","splice","indexOf","isSimple","path","quickDecomp","reflexVertices","steinerPoints","maxlevel","level","upperInt","lowerInt","upperDist","lowerDist","d","closestDist","upperIndex","lowerIndex","closestIndex","lowerPoly","upperPoly","console","warn","removeCollinearPoints","num","./Line","./Point","4","abs","5","./Polygon","6","name","version","description","author","keywords","main","engines","node","repository","type","url","bugs","licenses","devDependencies","grunt","grunt-contrib-jshint","grunt-contrib-nodeunit","grunt-contrib-uglify","grunt-contrib-watch","grunt-browserify","grunt-contrib-concat","dependencies","poly-decomp","7","AABB","options","lowerBound","vec2","create","upperBound","setFromPoints","points","position","angle","skinSize","l","rotate","cosAngle","cos","sinAngle","sin","x","y","add","aabb","extend","overlaps","u1","u2","containsPoint","point","overlapsRay","ray","dirFracX","direction","dirFracY","t1","t2","t3","t4","tmin","max","tmax","../math/vec2","../utils/Utils","8","Broadphase","world","boundingVolumeType","Body","BOUNDING_CIRCLE","setWorld","getCollisionPairs","boundingRadiusCheck","bodyA","bodyB","sub","d2","squaredLength","boundingRadius","aabbCheck","getAABB","boundingVolumeCheck","canCollide","KINEMATIC","STATIC","sleepState","SLEEPING","NAIVE","SAP","../objects/Body","9","NaiveBroadphase","constructor","bodies","Ncolliding","bi","bj","aabbQuery","aabbNeedsUpdate","updateAABB","../collision/Broadphase","../shapes/Circle","../shapes/Particle","../shapes/Plane","../shapes/Shape","10","Narrowphase","contactEquations","frictionEquations","enableFriction","enabledEquations","slipForce","frictionCoefficient","surfaceVelocity","contactEquationPool","ContactEquationPool","size","frictionEquationPool","FrictionEquationPool","restitution","stiffness","Equation","DEFAULT_STIFFNESS","relaxation","DEFAULT_RELAXATION","frictionStiffness","frictionRelaxation","enableFrictionReduction","collidingBodiesLastStep","TupleDictionary","contactSkinSize","setConvexToCapsuleShapeMiddle","convexShape","capsuleShape","set","radius","pointInConvex","worldPoint","convexOffset","convexAngle","worldVertex0","pic_worldVertex0","worldVertex1","pic_worldVertex1","r0","pic_r0","r1","pic_r1","verts","lastCross","v0","v1","cross","crossLength","Circle","Convex","Shape","Box","yAxis","fromValues","tmp3","tmp4","tmp5","tmp6","tmp7","tmp8","tmp9","tmp10","tmp11","tmp12","tmp13","tmp14","tmp15","tmp16","tmp17","tmp18","tmpArray","bodiesOverlap_shapePositionA","bodiesOverlap_shapePositionB","bodiesOverlap","shapePositionA","shapePositionB","Nshapesi","shapes","shapeA","toWorldFrame","Nshapesj","shapeB","collidedLastStep","id1","id","id2","get","reset","eqs","ce","fe","release","createContactEquation","firstImpact","needsUpdate","enabled","offset","createFrictionEquation","setSlipForce","relativeVelocity","createFrictionFromContact","contactPointA","contactPointB","rotate90cw","normalA","createFrictionFromAverage","numContacts","invNumContacts","scale","normalize","LINE","CONVEX","convexLine","convexBody","lineBody","lineShape","lineOffset","lineAngle","justTest","BOX","lineBox","boxBody","boxShape","boxOffset","boxAngle","convexCapsule_tempRect","width","height","convexCapsule_tempVec","CAPSULE","convexCapsule","convexPosition","capsuleBody","capsulePosition","capsuleAngle","circlePos","result1","circleConvex","result2","convexConvex","lineCapsule","linePosition","capsuleCapsule_tempVec1","capsuleCapsule_tempVec2","capsuleCapsule_tempRect1","capsuleCapsule","si","xi","ai","sj","xj","aj","circlePosi","circlePosj","enableFrictionBefore","circleCircle","rect","lineLine","positionA","angleA","positionB","angleB","PLANE","planeLine","planeBody","planeShape","planeOffset","planeAngle","worldVertex01","worldVertex11","worldEdge","worldEdgeUnit","worldNormal","worldTangent","PARTICLE","particleCapsule","particleBody","particleShape","particlePosition","particleAngle","circleLine","CIRCLE","circleBody","circleShape","circleOffset","circleAngle","lineRadius","circleRadius","orthoDist","lineToCircleOrthoUnit","projectedPoint","centerDist","lineToCircle","lineEndToLineRadius","radiusSum","pos","pos0","pos1","pow","circleCapsule","worldVertex","closestEdgeProjectedPoint","candidate","candidateDist","minCandidate","found","minCandidateDistance","candidateDistance","localVertex","particleConvex","particleOffset","convexToparticle","minEdgeNormal","offsetA","offsetB","radiusA","radiusB","planeConvex","numReported","particlePlane","circleParticle","planeCapsule_tmpCircle","planeCapsule_tmp1","planeCapsule_tmp2","planeCapsule","capsuleOffset","end1","end2","circle","numContacts1","circlePlane","numContacts2","numTotal","planeToCircle","temp","contact","sepAxis","worldPoint0","worldPoint1","penetrationVec","findSeparatingAxis","closestEdge1","getClosestEdge","closestEdge2","closestEdgeA","closestEdgeB","insideNumEdges","pcoa_tmp1","projectConvexOntoAxis","worldAxis","value","localAxis","fsa_tmp1","fsa_tmp2","fsa_tmp3","fsa_tmp4","fsa_tmp5","fsa_tmp6","offset1","angle1","offset2","angle2","maxDist","overlap","edge","normal","span1","span2","gce_tmp1","gce_tmp2","gce_tmp3","axis","flip","closestEdge","maxDot","circleHeightfield_candidate","circleHeightfield_dist","circleHeightfield_v0","circleHeightfield_v1","circleHeightfield_minCandidate","circleHeightfield_worldNormal","circleHeightfield_minCandidateNormal","HEIGHTFIELD","circleHeightfield","hfBody","hfShape","hfPos","hfAngle","data","heights","w","elementWidth","minCandidateNormal","idxA","floor","idxB","ceil","PI","convexHeightfield_v0","convexHeightfield_v1","convexHeightfield_tilePos","convexHeightfield_tempConvexShape","convexHeightfield","convexPos","tilePos","tileConvex","../equations/ContactEquation","../equations/Equation","../equations/FrictionEquation","../shapes/Box","../shapes/Convex","../utils/ContactEquationPool","../utils/FrictionEquationPool","../utils/TupleDictionary","11","Ray","checkCollisionResponse","undefined","skipBackfaces","collisionMask","collisionGroup","mode","ANY","callback","update","distanceFromIntersectionSquared","intersect","squaredDistance","CLOSEST","ALL","intersectBodies","shouldStop","body","intersectBody","intersectBody_worldPosition","collisionResponse","worldPosition","shape","worldAngle","intersectShape","_currentBody","_currentShape","raycast","reportIntersection","fraction","faceIndex","hasHit","../collision/AABB","../collision/RaycastResult","12","RaycastResult","isStopped","getHitDistance","distance","getHitPoint","out","lerp","stop","../collision/Ray","13","SAPBroadphase","axisList","axisIndex","that","_addBodyHandler","_removeBodyHandler","idx","Utils","appendArray","off","on","sortAxisList","sortList","14","Constraint","defaults","collideConnected","wakeUpBodies","equations","wakeUp","DISTANCE","GEAR","LOCK","PRISMATIC","REVOLUTE","setStiffness","setRelaxation","15","DistanceConstraint","localAnchorA","localAnchorB","worldAnchorA","worldAnchorB","maxForce","ri","rj","computeGq","setMaxForce","upperLimitEnabled","upperLimit","lowerLimitEnabled","lowerLimit","normalEquation","G","violating","minForce","rixn","rjxn","getMaxForce","./Constraint","16","GearConstraint","ratio","AngleLockEquation","maxTorque","setMaxTorque","setRatio","torque","getMaxTorque","../equations/AngleLockEquation","17","LockConstraint","localAngleB","rot","g","localOffsetB","force","xAxis","18","PrismaticConstraint","localAxisA","trans","gg","updateJacobian","disableRotationalLock","RotationalLockEquation","velocity","upperLimitEquation","ContactEquation","lowerLimitEquation","motorEquation","motorEnabled","motorSpeed","computeGW","vi","vj","wi","angularVelocity","wj","gmult","worldAxisA","orientedAnchorA","orientedAnchorB","relPosition","enableMotor","disableMotor","setLimits","lower","upper","../equations/RotationalLockEquation","19","RevoluteConstraint","pivotA","pivotB","worldPivot","localPivotA","localPivotB","worldPivotA","worldPivotB","RotationalVelocityEquation","relAngle","setMotorSpeed","speed","getMotorSpeed","../equations/RotationalVelocityEquation","20","./Equation","21","computeB","h","GW","Gq","computeGiMf","relVel","getVelocityAlongNormal","getVelocityAtPoint","subtract","22","ARRAY_TYPE","epsilon","timeStep","multiplier","qi","qj","computeGWlambda","vlambda","wlambda","iMfi","iMfj","fi","ti","angularForce","fj","tj","invMassi","invMassSolve","invMassj","invIi","invInertiaSolve","invIj","multiply","massMultiplier","computeGiMGt","addToWlambda_temp","addToWlambda_Gi","addToWlambda_Gj","addToWlambda","deltalambda","Gi","Gj","computeInvC","eps","23","FrictionEquation","getSlipForce","24","worldVectorA","worldVectorB","25","GiMf","26","EventEmitter","listener","context","_listeners","listeners","has","index","emit","event","listenerArray","target","27","ContactMaterial","materialA","materialB","Material","idCounter","friction","./Material","28","29","PolyK","GetArea","sum","Triangulate","tgs","avl","al","i0","i1","i2","ax","ay","bx","by","cx","cy","earFound","_convex","_PointInTriangle","px","py","v0x","v0y","v1x","v1y","v2x","v2y","dot00","dot01","dot02","dot11","dot12","invDenom","30","crossVZ","vec","zcomp","crossZV","toLocalFrame","framePosition","frameAngle","toGlobalFrame","localPoint","vectorToLocalFrame","worldVector","vectorToGlobalFrame","localVector","centroid","clone","mul","divide","div","sqrDist","len","sqrLen","negate","str","reflect","vector","getLineSegmentsIntersection","p0","p3","getLineSegmentsIntersectionFraction","s1_x","s1_y","s2_x","s2_y","31","_idCounter","mass","invMass","inertia","invInertia","fixedRotation","fixedX","fixedY","interpolatedPosition","interpolatedAngle","previousPosition","previousAngle","damping","angularDamping","DYNAMIC","allowSleep","wantsToSleep","AWAKE","sleepSpeedLimit","sleepTimeLimit","gravityScale","idleTime","timeLastSleepy","ccdSpeedThreshold","ccdIterations","concavePath","_wakeUpAfterNarrowphase","updateMassProperties","updateSolveMassProperties","setDensity","density","totalArea","getArea","shapeAABB","bodyAngle","computeAABB","updateBoundingRadius","addShape","removeShape","m","I","r2","computeMomentOfInertia","applyForce","relativePoint","rotForce","Body_applyForce_forceWorld","Body_applyForce_pointWorld","Body_applyForce_pointLocal","applyForceLocal","localForce","worldForce","vectorToWorldFrame","Body_applyImpulse_velo","applyImpulse","impulseVector","velo","rotVelo","Body_applyImpulse_impulseWorld","Body_applyImpulse_pointWorld","Body_applyImpulse_pointLocal","applyImpulseLocal","localImpulse","worldImpulse","fromPolygon","convexes","optimalDecomp","cm","centerOfMass","updateTriangles","updateCenterOfMass","adjustCenterOfMass","adjustCenterOfMass_tmp2","adjustCenterOfMass_tmp3","adjustCenterOfMass_tmp4","offset_times_area","setZeroForce","resetConstraintVelocity","addConstraintVelocity","applyDamping","dt","wakeUpEvent","sleep","sleepEvent","sleepTick","time","dontSleep","SLEEPY","overlapKeeper","bodiesAreOverlapping","integrate_fhMinv","integrate_velodt","integrate","minv","integrateToTimeOfImpact","end","startToEnd","rememberPosition","hit","startToEndAngle","timeOfImpact","rememberAngle","iter","tmid","narrowphase","sleepyEvent","../events/EventEmitter","32","LinearSpring","Spring","setWorldAnchorA","setWorldAnchorB","getWorldAnchorA","getWorldAnchorB","worldDistance","restLength","applyForce_r","applyForce_r_unit","applyForce_u","applyForce_f","applyForce_worldAnchorA","applyForce_worldAnchorB","applyForce_ri","applyForce_rj","applyForce_tmp","r_unit","rlen","ri_x_f","rj_x_f","./Spring","33","RotationalSpring","restAngle","34","35","TopDownVehicle","chassisBody","wheels","groundBody","preStepCallback","WheelConstraint","vehicle","forwardEquation","sideEquation","steerValue","engineForce","setSideFriction","sideFriction","localForwardVector","localPosition","apply","setBrakeForce","addToWorld","addBody","wheel","addConstraint","removeFromWorld","removeBody","removeConstraint","addWheel","wheelOptions","worldVelocity","getSpeed","tmpVec","../constraints/Constraint","36","Capsule","GSSolver","Heightfield","Particle","Plane","Pool","Solver","World","Object","defineProperty","../package.json","./collision/AABB","./collision/Broadphase","./collision/NaiveBroadphase","./collision/Narrowphase","./collision/Ray","./collision/RaycastResult","./collision/SAPBroadphase","./constraints/Constraint","./constraints/DistanceConstraint","./constraints/GearConstraint","./constraints/LockConstraint","./constraints/PrismaticConstraint","./constraints/RevoluteConstraint","./equations/AngleLockEquation","./equations/ContactEquation","./equations/Equation","./equations/FrictionEquation","./equations/RotationalVelocityEquation","./events/EventEmitter","./material/ContactMaterial","./material/Material","./math/vec2","./objects/Body","./objects/LinearSpring","./objects/RotationalSpring","./objects/Spring","./objects/TopDownVehicle","./shapes/Box","./shapes/Capsule","./shapes/Circle","./shapes/Convex","./shapes/Heightfield","./shapes/Line","./shapes/Particle","./shapes/Plane","./shapes/Shape","./solver/GSSolver","./solver/Solver","./utils/ContactEquationPool","./utils/FrictionEquationPool","./utils/Pool","./utils/Utils","./world/World","37","arguments","axes","updateArea","./Convex","./Shape","38","intersectCapsule_hitPointWorld","intersectCapsule_normal","intersectCapsule_l0","intersectCapsule_l1","intersectCapsule_unit_y","hitPointWorld","l0","halfLen","diagonalLengthSquared","sqrtDelta","inv2a","d1","39","Ray_intersectSphere_intersectionPoint","Ray_intersectSphere_normal","intersectionPoint","40","isArray","triangles","polyk","tmpVec1","tmpVec2","projectOntoLocalAxis","projectOntoWorldAxis","shapeOffset","shapeAngle","polykVerts","id3","updateCenterOfMass_centroid","updateCenterOfMass_centroid_times_mass","updateCenterOfMass_a","updateCenterOfMass_b","updateCenterOfMass_c","centroid_times_mass","triangleArea","denom","numer","intersectConvex_rayStart","intersectConvex_rayEnd","intersectConvex_normal","rayStart","rayEnd","../math/polyk","41","key","maxValue","minValue","updateMaxMinValues","getLineSegment","start","getSegmentIndex","getClampedSegmentIndex","intersectHeightfield_worldNormal","intersectHeightfield_l0","intersectHeightfield_l1","intersectHeightfield_localFrom","intersectHeightfield_localTo","localFrom","localTo","42","raycast_normal","raycast_l0","raycast_l1","raycast_unit_y","43","44","intersectPlane_planePointToFrom","intersectPlane_normal","intersectPlane_len","planePointToFrom","planeToFrom","n_dot_dir","45","material","sensor","46","GS","iterations","tolerance","arrayStep","lambda","Bs","invCs","useZeroRHS","frictionIterations","usedIterations","setArrayZero","array","solve","sortEquations","maxIter","maxFrictionIter","Neq","tolSquared","Nbodies","deltalambdaTot","iterateEquation","updateMultipliers","invDt","B","invC","lambdaj","GWlambda","lambdaj_plus_deltalambda","./Solver","47","equationSortFunction","mockWorld","solveIsland","island","removeAllEquations","addEquations","getBodies","sort","addEquation","removeEquation","ISLAND","48","destroy","equation","./Pool","49","50","IslandNodePool","IslandNode","../world/IslandNode","51","IslandPool","Island","../world/Island","52","OverlapKeeper","overlappingShapesLastState","overlappingShapesCurrentState","recordPool","OverlapKeeperRecordPool","tmpDict","tmpArray1","tick","current","keys","lastObject","getByKey","setOverlapping","getNewOverlaps","getDiff","getEndOverlaps","dictA","dictB","isNewOverlap","idA","idB","getNewBodyOverlaps","getBodyDiff","getEndBodyOverlaps","accumulator","./OverlapKeeperRecord","./OverlapKeeperRecordPool","./TupleDictionary","./Utils","53","OverlapKeeperRecord","54","record","55","objects","resize","object","56","getKey","dict","57","howmany","P2_ARRAY_TYPE","Float32Array","58","bodyIds","59","IslandManager","nodePool","islandPool","islands","nodes","queue","getUnvisitedNode","Nnodes","visited","visit","bds","Neqs","bfs","root","child","neighbors","split","ni","nj","./../utils/IslandNodePool","./../utils/IslandPool","./Island","./IslandNode","60","61","springs","disabledBodyCollisionPairs","solver","islandManager","gravity","frictionGravity","useWorldGravityAsFrictionGravity","useFrictionGravityOnZeroGravity","broadphase","constraints","defaultMaterial","defaultContactMaterial","lastTimeStep","applySpringForces","applyGravity","solveConstraints","contactMaterials","stepping","bodiesToBeRemoved","islandSplit","emitImpactEvent","_constraintIdCounter","_bodyIdCounter","postStepEvent","addBodyEvent","removeBodyEvent","addSpringEvent","spring","impactEvent","contactEquation","postBroadphaseEvent","pairs","sleepMode","NO_SLEEPING","beginContactEvent","endContactEvent","preSolveEvent","BODY_SLEEPING","ISLAND_SLEEPING","constraint","addContactMaterial","contactMaterial","removeContactMaterial","getContactMaterial","cmats","step_mg","xiw","xjw","step","timeSinceLastCalled","maxSubSteps","internalStep","substeps","endOverlaps","Nsprings","np","mg","gravityLen","ignoredPairs","Nconstraints","Nresults","runNarrowphase","ev","glen","aiw","ajw","reducedMass","resolver","numFrictionBefore","numFrictionEquations","addSpring","evt","removeSpring","getBodyById","disableBodyCollision","enableBodyCollision","cs","cms","hitTest_tmp1","hitTest_tmp2","hitTest","pb","ps","NS","setGlobalStiffness","setGlobalRelaxation","tmpAABB","../../package.json","../collision/Narrowphase","../collision/SAPBroadphase","../constraints/DistanceConstraint","../constraints/GearConstraint","../constraints/LockConstraint","../constraints/PrismaticConstraint","../constraints/RevoluteConstraint","../material/ContactMaterial","../material/Material","../objects/LinearSpring","../objects/RotationalSpring","../shapes/Capsule","../shapes/Line","../solver/GSSolver","../solver/Solver","../utils/OverlapKeeper","./IslandManager","_CreateEmptyTexture","gl","scaleMode","texture","createTexture","bindTexture","TEXTURE_2D","texParameteri","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","TEXTURE_MAG_FILTER","PIXI","scaleModes","LINEAR","NEAREST","TEXTURE_MIN_FILTER","texImage2D","RGBA","UNSIGNED_BYTE","_CreateFramebuffer","textureUnit","framebuffer","createFramebuffer","depthStencilBuffer","createRenderbuffer","colorBuffer","fbStatus","activeTexture","TEXTURE0","bindFramebuffer","FRAMEBUFFER","bindRenderbuffer","RENDERBUFFER","framebufferRenderbuffer","DEPTH_STENCIL_ATTACHMENT","renderBuffer","framebufferTexture2D","COLOR_ATTACHMENT0","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","error","_fbErrors","targetTexture","DisplayObject","pivot","rotation","alpha","visible","hitArea","renderable","parent","worldAlpha","worldTransform","Phaser","Matrix","worldScale","worldRotation","filterArea","_sr","_cr","_bounds","Rectangle","_currentBounds","_mask","_cacheAsBitmap","_cacheIsDirty","children","_destroyCachedSprite","updateTransform","game","tx","ty","pt","wt","PI2","rotationCache","determ","HALF_PI","transformCallback","transformCallbackContext","preUpdate","generateTexture","resolution","renderer","bounds","getLocalBounds","renderTexture","RenderTexture","_tempMatrix","render","updateCache","_generateCachedSprite","toGlobal","toLocal","applyInverse","_renderCachedSprite","renderSession","_cachedSprite","Sprite","_renderWebGL","_renderCanvas","baseTexture","_enableMultiTextureToggle","textureIndex","tempFilters","_filters","filters","anchor","displayObjectUpdateTransform","defineProperties","worldVisible","item","mask","isMask","passes","filterPasses","_filterBlock","blendMode","blendModes","MULTIPLY","NORMAL","cacheAsBitmap","DisplayObjectContainer","ignoreChildInput","addChild","addChildAt","removeChild","swapChildren","child2","index1","getChildIndex","index2","setChildIndex","currentIndex","getChildAt","removeChildAt","removeChildren","beginIndex","endIndex","range","removed","displayObjectContainerUpdateTransform","getBounds","targetCoordinateSpace","isTargetCoordinateSpaceDisplayObject","isTargetCoordinateSpaceThisOrParent","contains","matrixCache","identityMatrix","childBounds","childMaxX","childMaxY","minX","Infinity","minY","maxX","maxY","childVisible","w0","w1","h0","h1","x1","y1","x2","y2","x3","y3","x4","y4","targetCoordinateSpaceBounds","spriteBatch","flush","filterManager","pushFilter","maskManager","pushMask","popMask","popFilter","_width","_height","defaultAnchor","Texture","emptyTexture","tint","cachedTint","tintedTexture","shader","exists","hasLoaded","onTextureUpdate","frame","setTexture","destroyBase","skipRender","valid","matrix","crop","currentBlendMode","globalCompositeOperation","blendModesCanvas","globalAlpha","smoothProperty","trim","shakeX","shakeY","cw","ch","rotated","roundPixels","setTransform","requiresReTint","CanvasTinter","getTintedTexture","drawImage","source","initDefaultShaders","CompileVertexShader","shaderSrc","_CompileShader","VERTEX_SHADER","CompileFragmentShader","FRAGMENT_SHADER","shaderType","src","join","createShader","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","log","getShaderInfoLog","compileProgram","vertexSrc","fragmentSrc","fragmentShader","vertexShader","shaderProgram","createProgram","attachShader","linkProgram","getProgramParameter","LINK_STATUS","getProgramInfoLog","PixiShader","_UID","program","textureCount","firstRun","dirty","attributes","init","initMultitexShader","MAX_TEXTURES","getParameter","MAX_TEXTURE_IMAGE_UNITS","dynamicIfs","defaultVertexSrc","useProgram","uSamplerArray","getUniformLocation","projectionVector","offsetVector","dimensions","aVertexPosition","getAttribLocation","aTextureCoord","colorAttribute","aTextureIndex","indices","tempTexture","RGB","uniform1iv","uniforms","uniformLocation","initUniforms","initDefaultShader","uSampler","usingFilter","uniform","_init","initSampler2D","glMatrix","glValueLength","glFunc","uniformMatrix2fv","uniformMatrix3fv","uniformMatrix4fv","_glTextures","textureData","magFilter","minFilter","wrapS","wrapT","format","LUMINANCE","repeat","REPEAT","pixelStorei","UNPACK_FLIP_Y_WEBGL","flipY","border","uniform1i","syncUniforms","transpose","z","_dirty","instances","updateTexture","deleteProgram","PixiFastShader","uMatrix","aPositionCoord","aScale","aRotation","StripShader","translationMatrix","attribute","PrimitiveShader","tintColor","ComplexPrimitiveShader","color","glContexts","WebGLRenderer","config","defaultRenderer","extensions","WEBGL","transparent","autoResize","preserveDrawingBuffer","clearBeforeRender","view","canvas","_contextOptions","antialias","failIfMajorPerformanceCaveat","premultipliedAlpha","stencil","projection","shaderManager","WebGLShaderManager","WebGLSpriteBatch","WebGLMaskManager","WebGLFilterManager","stencilManager","WebGLStencilManager","blendModeManager","WebGLBlendModeManager","currentBatchedTextures","drawCount","maxTextureAvailableSpace","initContext","mapBlendModes","getContext","maxTextures","maxTextureSize","MAX_TEXTURE_SIZE","glContextId","disable","DEPTH_TEST","CULL_FACE","enable","BLEND","setContext","compression","etc1","getExtension","pvrtc","s3tc","ETC1","PVRTC","S3TC","setTexturePriority","textureNameCollection","clampPot","potSize","imageCache","cache","_cache","image","imageName","base","stage","contextLost","viewport","clearColor","_bgColor","COLOR_BUFFER_BIT","camera","_shake","renderDisplayObject","displayObject","buffer","setBlendMode","begin","style","updateCompressedTexture","textureMetaData","compressedTexImage2D","glExtensionFormat","mipmap","isPowerOfTwo","LINEAR_MIPMAP_LINEAR","NEAREST_MIPMAP_NEAREST","generateMipmap","_powerOf2","compressionAlgorithm","UNPACK_PREMULTIPLY_ALPHA_WEBGL","CanvasPool","remove","blendModesWebGL","modes","ONE","ONE_MINUS_SRC_ALPHA","ADD","SRC_ALPHA","DST_ALPHA","DST_COLOR","SCREEN","OVERLAY","DARKEN","LIGHTEN","COLOR_DODGE","COLOR_BURN","HARD_LIGHT","SOFT_LIGHT","DIFFERENCE","EXCLUSION","HUE","SATURATION","COLOR","LUMINOSITY","getMaxTextureUnit","enableMultiTexture","textureArray","blendModeWebGL","blendFunc","maskData","WebGLGraphics","updateGraphics","_webGL","pushStencil","popStencil","stencilStack","count","graphics","webGLData","bindGraphics","STENCIL_TEST","STENCIL_BUFFER_BIT","colorMask","stencilFunc","ALWAYS","stencilOp","KEEP","INVERT","drawElements","TRIANGLE_FAN","UNSIGNED_SHORT","EQUAL","DECR","INCR","TRIANGLE_STRIP","_currentGraphics","complexPrimitiveShader","setShader","uniform1f","toArray","uniform2f","uniform3fv","Color","hexToRGBArray","bindBuffer","ARRAY_BUFFER","vertexAttribPointer","FLOAT","ELEMENT_ARRAY_BUFFER","indexBuffer","primitiveShader","maxAttibs","attribState","tempAttribState","stack","defaultShader","fastShader","stripShader","creatureShader","CreatureShader","setAttribs","attribs","attribId","enableVertexAttribArray","disableVertexAttribArray","_currentId","currentShader","vertSize","vertexSize","numVerts","numIndices","ArrayBuffer","positions","colors","Uint32Array","Uint16Array","lastIndexCount","drawing","currentBatchSize","currentBaseTexture","textures","shaders","sprites","Filter","vertexBuffer","createBuffer","bufferData","STATIC_DRAW","DYNAMIC_DRAW","sprite","uvs","_uvs","aX","aY","a0","b0","c0","d0","_w1","_w0","_updateUvsInverted","x0","y0","renderTilingSprite","tilingTexture","TextureUvs","tilePosition","tileScaleOffset","offsetX","offsetY","scaleX","tileScale","scaleY","stride","bufferSubData","subarray","nextTexture","nextBlendMode","nextShader","batchSize","blendSwap","shaderSwap","skip","renderBatch","startIndex","TRIANGLES","deleteBuffer","WebGLFastSpriteBatch","maxSize","renderSprite","filterStack","texturePool","initShaderBuffers","filterBlock","_filterArea","_previous_stencil_mgr","filter","FilterTexture","padding","frameBuffer","_glFilterTexture","vertexArray","uvBuffer","uvArray","inputTexture","outputTexture","filterPass","applyFilterPass","sizeX","sizeY","currentFilter","colorArray","36054","36055","36057","36061","DEFAULT","renderbufferStorage","DEPTH_STENCIL","deleteFramebuffer","deleteTexture","CanvasBuffer","clearRect","CanvasMaskManager","save","cacheAlpha","transform","CanvasGraphics","renderGraphicsMask","clip","restore","tintMethod","tintWithMultiply","fillStyle","toString","substr","fillRect","tintWithPerPixel","rgbValues","pixelData","getImageData","pixels","canHandleAlpha","putImageData","CanvasRenderer","CANVAS","refresh","Canvas","getSmoothingPrefix","navigator","isCocoonJS","screencanvas","rgba","removeView","useNew","device","canUseMultiply","BaseTexture","complete","naturalWidth","naturalHeight","forceLoaded","removeByCanvas","unloadFromGPU","glTexture","fromCanvas","TextureSilentFail","noFrame","isTiling","requiresUpdate","setFrame","onBaseTextureLoaded","_updateUvs","tw","th","define","amd","WheelEventProxy","scaleFactor","deltaMode","_scaleFactor","_deltaMode","originalEvent","VERSION","GAMES","AUTO","HEADLESS","WEBGL_MULTI","NONE","LEFT","RIGHT","UP","DOWN","SPRITE","BUTTON","IMAGE","GRAPHICS","TEXT","TILESPRITE","BITMAPTEXT","GROUP","RENDERTEXTURE","TILEMAP","TILEMAPLAYER","EMITTER","POLYGON","BITMAPDATA","CANVAS_FILTER","WEBGL_FILTER","ELLIPSE","SPRITEBATCH","RETROFONT","POINTER","ROPE","RECTANGLE","MATRIX","POINT","ROUNDEDRECTANGLE","CREATURE","VIDEO","PENDING_ATLAS","HORIZONTAL","VERTICAL","LANDSCAPE","PORTRAIT","ANGLE_UP","ANGLE_DOWN","ANGLE_LEFT","ANGLE_RIGHT","ANGLE_NORTH_EAST","ANGLE_NORTH_WEST","ANGLE_SOUTH_EAST","ANGLE_SOUTH_WEST","TOP_LEFT","TOP_CENTER","TOP_RIGHT","LEFT_TOP","LEFT_CENTER","LEFT_BOTTOM","CENTER","RIGHT_TOP","RIGHT_CENTER","RIGHT_BOTTOM","BOTTOM_LEFT","BOTTOM_CENTER","BOTTOM_RIGHT","trunc","Function","bind","thisArg","bound","args","boundArgs","concat","TypeError","F","proto","arg","forEach","fun","CheapArray","assert","assign","varArgs","hasOwn","hasOwnProperty","nextSource","nextKey","reverseString","string","getProperty","obj","parts","_getProperty","setProperties","props","setProperty","_setProperty","val","currentObj","chanceRoll","chance","random","randomChoice","choice1","choice2","parseDimension","dimension","parseInt","innerWidth","innerHeight","pad","dir","padlen","isPlainObject","nodeType","copyIsArray","deep","mixinPrototype","mixin","replace","mixinKeys","childNodes","cloneNode","diameter","_diameter","_radius","circumference","setTo","copyFrom","copyTo","dest","round","output","circumferencePoint","asDegrees","sample","steps","startAngle","endAngle","linear","offsetPoint","top","bottom","equals","intersects","degToRad","intersectsRectangle","halfWidth","halfHeight","xCornerDist","yCornerDist","intersectsLine","returnPoints","del","p0Exists","pointOnSegment","p1Exists","Ellipse","normx","normy","fromPoints","fromSprite","startSprite","endSprite","useCenter","centerX","centerY","fromAngle","rotateAround","line","asSegment","intersectsPoints","midPoint","centerOn","pointOnLine","fuzzyEqual","xMin","xMax","yMin","yMax","coordinatesOnLine","stepRate","results","sx","sy","err","e2","wrap","uc","ua","ub","empty","bx1","by1","bx2","by2","intersectionWithRectangle","edgeIntersection","closestDistance","normalAngle","fromArray","newPos","translate","tx1","identity","invert","setToPolar","azimuth","clampX","clamp","clampY","equalsXY","fuzzyEquals","fuzzyEqualsXY","angleXY","atan2","radToDeg","atan","getMagnitude","getMagnitudeSq","setMagnitude","magnitude","isZero","limit","expand","perp","rperp","normalRightHand","negative","multiplyAdd","interpolate","project","amt","projectUnit","pointslength","parse","xProp","yProp","isPoint","sortClockwise","center","_points","closed","flattened","toNumberArray","flatten","inside","ix","iy","jx","jy","calculateArea","avgHeight","floorAll","ceilAll","copyFromBounds","inflate","containsRect","intersection","intersectsRaw","union","randomX","randomY","getPoint","sides","inflatePoint","createFromBounds","containsRaw","rx","ry","rw","rh","volume","sameDimensions","NEGATIVE_INFINITY","POSITIVE_INFINITY","EmptyRectangle","RoundedRectangle","Camera","deadzone","roundPx","atLimit","totalInView","onShakeComplete","Signal","onFlashComplete","onFadeComplete","fx","_targetPosition","_edge","_position","intensity","duration","horizontal","vertical","shakeBounds","_fxDuration","_fxType","_fixedView","FOLLOW_LOCKON","FOLLOW_PLATFORMER","FOLLOW_TOPDOWN","FOLLOW_TOPDOWN_TIGHT","SHAKE_BOTH","SHAKE_HORIZONTAL","SHAKE_VERTICAL","ENABLE_FX","boot","Graphics","follow","lerpX","lerpY","helper","unfollow","focusOn","setPosition","focusOnXY","shake","flash","beginFill","drawRect","endFill","fade","updateFX","updateShake","checkBounds","elapsedMS","dispatch","rnd","frac","updateTarget","math","setBoundsToWorld","vx","vw","vy","vh","setSize","resetFX","State","make","input","load","sound","state","tweens","particles","physics","preload","loadUpdate","loadRender","preRender","paused","resumed","pauseUpdate","shutdown","StateManager","pendingState","states","_pendingState","_clearWorld","_clearCache","_created","_args","onStateChange","onInitCallback","onPreloadCallback","onCreateCallback","onUpdateCallback","onRenderCallback","onResizeCallback","onPreRenderCallback","onLoadUpdateCallback","onLoadRenderCallback","onPausedCallback","onResumedCallback","onPauseUpdateCallback","onShutDownCallback","onPause","pause","onResume","resume","autoStart","newState","isBooted","callbackContext","clearWorld","clearCache","checkState","restart","dummy","previousStateKey","clearCurrentState","setCurrentState","totalQueuedFiles","totalQueuedPacks","loadComplete","removeAll","debug","link","unlink","_kickstart","getCurrentState","elapsedTime","renderType","_bindings","_prevParams","memorize","_shouldPropagate","active","_boundDispatch","validateListener","fnName","_registerListener","isOnce","listenerContext","priority","binding","prevIndex","_indexOfListener","SignalBinding","_addBinding","execute","_priority","cur","_listener","addOnce","_destroy","getNumListeners","halt","bindings","paramsArr","forget","dispose","_this","signal","_isOnce","_signal","callCount","params","handlerReturn","detach","isBound","getListener","getSignal","prevPoint","Date","mouse","date","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","sampleRate","iChannel0","iChannel1","iChannel2","iChannel3","setResolution","pointer","toFixed","totalElapsedSeconds","anchorX","anchorY","Cache","Plugin","hasPreUpdate","hasUpdate","hasPostUpdate","hasRender","hasPostRender","postRender","PluginManager","plugins","_len","_i","plugin","postUpdate","Stage","disableVisibilityChange","currentRenderOrderID","_hiddenVar","_onChange","parseConfig","setBackgroundColor","DOM","getOffset","setUserSelect","setTouchAction","checkVisibility","document","hidden","webkitHidden","mozHidden","msHidden","visibilityChange","_onClick","hasFocus","addEventListener","onblur","onfocus","onpagehide","onpageshow","cocoonJSApp","CocoonJS","App","onSuspended","onActivated","focusLoss","focusGain","gamePaused","gameResumed","valueToColor","updateColor","removeEventListener","silent","hash","removeFromHash","Group","addToStage","enableBody","physicsBodyType","Physics","ARCADE","physicsType","alive","ignoreDestroy","pendingDestroy","classType","cursor","inputEnableChildren","updateOnlyExistingChildren","onChildInputDown","onChildInputUp","onChildInputOver","onChildInputOut","enableBodyDebug","physicsSortDirection","onDestroy","cursorIndex","fixedToCamera","cameraOffset","_sortProperty","RETURN_NONE","RETURN_TOTAL","RETURN_CHILD","RETURN_ALL","SORT_ASCENDING","SORT_DESCENDING","updateZ","addToHash","inputEnabled","events","onAddedToGroup$dispatch","addAt","addMultiple","moveAll","getAt","createMultiple","quantity","singleKey","singleFrame","align","cellWidth","cellHeight","alignIn","resetCursor","next","previous","swap","child1","bringToTop","getIndex","sendToBack","moveUp","moveDown","xy","getByName","oldChild","newChild","hasProperty","operation","checkProperty","checkAlive","checkVisible","setAll","setAllChildren","checkAll","checkAny","addAll","property","amount","subAll","multiplyAll","divideAll","kill","killAll","callAllExists","revive","reviveAll","resetAll","checkExists","resetChild","existsValue","callbackFromArray","callAll","method","methodLength","contextLength","renderOrderID","predicate","ArraySet","forEachExists","iterate","forEachAlive","forEachDead","order","ascendingSortHandler","descendingSortHandler","customSort","sortHandler","returnType","total","getFirst","getFirstExists","createIfNull","getFirstAlive","getFirstDead","loadTexture","getTop","getBottom","getClosestTo","tempDistance","getFurthestFrom","countLiving","countDead","getRandom","ArrayUtils","getRandomItem","getRandomExists","list","getAll","pick","destroyPhase","onRemovedFromGroup$dispatch","group","destroyTexture","removeBetween","scatter","shuffle","destroyChildren","soft","_definedSize","stateChange","setBounds","useBounds","wrapAll","between","Game","physicsConfig","multiTexture","isRunning","raf","net","Device","lockRender","pendingStep","stepCount","onBlur","onFocus","_paused","_codePaused","currentUpdateID","updatesThisFrame","rendersThisFrame","_deltaTime","_lastCount","_spiraling","fpsProblemNotifier","forceSingleUpdate","forceSingleRender","dropFrames","_nextFpsNotification","enableDebug","RandomDataGenerator","now","whenReady","seed","ScaleManager","setUpRenderer","GameObjectFactory","GameObjectCreator","Loader","Time","TweenManager","Input","SoundManager","Particles","Create","Net","Debug","isDisabled","showDebugHeader","RequestAnimationFrame","stopFocus","focus","isReady","onReady","hideBanner","webAudio","ie","setImageRenderingCrisp","webGL","contextRestored","webGLRendererError","cocoonJS","smoothed","addToDOM","preventDefault","clearGLTextures","updateLogic","desiredFpsMult","updateRender","slowMotion","desiredFps","slowStep","elapsed","countUpdate","countRender","enableStep","disableStep","removeFromDOM","muteOnPause","setMute","cordova","iOS","unsetMute","hitCanvas","hitContext","moveCallbacks","customCandidateHandler","customCandidateHandlerContext","pollRate","multiInputOverride","MOUSE_TOUCH_COMBINE","maxPointers","tapRate","doubleTapRate","holdRate","justPressedRate","justReleasedRate","recordPointerHistory","recordRate","recordLimit","touchLockCallbacks","pointer1","pointer2","pointer3","pointer4","pointer5","pointer6","pointer7","pointer8","pointer9","pointer10","pointers","activePointer","mousePointer","keyboard","touch","mspointer","gamepad","resetLocked","onDown","onUp","onTap","onHold","minPriorityID","interactiveItems","_localPoint","_pollCounter","_oldPosition","_x","_y","MOUSE_OVERRIDES_TOUCH","TOUCH_OVERRIDES_MOUSE","MAX_POINTERS","Pointer","PointerMode","CURSOR","addPointer","Mouse","Touch","MSPointer","Keyboard","Gamepad","_onClickTrampoline","onClickTrampoline","setInteractiveCandidateHandler","addMoveCallback","addTouchLockCallback","onEnd","removeTouchLockCallback","executeTouchLockCallbacks","cb","deleteMoveCallback","CONTACT","hard","resetSpeed","startPointer","countActivePointers","updatePointer","identifier","move","stopPointer","getPointer","isActive","getPointerFromIdentifier","getPointerFromId","pointerId","getLocalPosition","Creature","TileSprite","graphicsData","fill","processClickTrampolines","mouseDownCallback","mouseUpCallback","mouseOutCallback","mouseOverCallback","mouseWheelCallback","capture","button","wheelDelta","locked","stopOnGameOut","pointerLock","_onMouseDown","_onMouseMove","_onMouseUp","_onMouseOut","_onMouseOver","_onMouseWheel","_wheelEvent","NO_BUTTON","LEFT_BUTTON","MIDDLE_BUTTON","RIGHT_BUTTON","BACK_BUTTON","FORWARD_BUTTON","WHEEL_UP","WHEEL_DOWN","android","chrome","onMouseDown","onMouseMove","onMouseUp","_onMouseUpGlobal","onMouseUpGlobal","_onMouseOutGlobal","onMouseOutGlobal","onMouseOut","onMouseOver","onMouseWheel","wheelEvent","mouseMoveCallback","withinGame","resetButtons","bindEvent","deltaY","requestPointerLock","element","mozRequestPointerLock","webkitRequestPointerLock","_pointerLockChange","pointerLockChange","pointerLockElement","mozPointerLockElement","webkitPointerLockElement","releasePointerLock","exitPointerLock","mozExitPointerLock","webkitExitPointerLock","_stubsGenerated","prop","makeBinder","detail","deltaX","wheelDeltaX","deltaZ","pointerDownCallback","pointerMoveCallback","pointerUpCallback","_onMSPointerDown","_onMSPointerMove","_onMSPointerUp","_onMSPointerUpGlobal","_onMSPointerOut","_onMSPointerOver","onPointerDown","onPointerMove","onPointerUp","onPointerUpGlobal","onPointerOut","onPointerOver","pointerType","DeviceButton","buttonCode","isDown","isUp","timeDown","timeUp","repeats","altKey","shiftKey","ctrlKey","onFloat","startStop","condition","padFloat","justPressed","justReleased","pointerMode","leftButton","middleButton","rightButton","backButton","forwardButton","eraserButton","ERASER_BUTTON","_holdSent","_history","_nextDrop","_stateReset","clientX","clientY","pageX","pageY","screenX","screenY","rawMovementX","rawMovementY","movementX","movementY","isMouse","previousTapTime","totalTouches","msSinceLastClick","targetObject","interactiveCandidates","positionDown","positionUp","_clickTrampolines","_trampolineTargetObject","processButtonsDown","processButtonsUp","processButtonsUpDown","buttons","down","toLowerCase","updateButtons","totalActivePointers","_touchedHandler","processInteractiveObjects","shift","fromClick","pollLocked","mozMovementX","webkitMovementX","mozMovementY","webkitMovementY","noPause","isDragged","highestRenderOrderID","highestInputPriorityID","candidateTarget","currentNode","checked","validForInput","checkPointerDown","checkPointerOver","priorityID","swapTarget","newTarget","_pointerOutHandler","_pointerOverHandler","leave","currentPointers","addClickTrampoline","callbackArgs","trampolines","trampoline","_releasedHandler","resetMovement","touchStartCallback","touchMoveCallback","touchEndCallback","touchEnterCallback","touchLeaveCallback","touchCancelCallback","_onTouchStart","_onTouchMove","_onTouchEnd","_onTouchEnter","_onTouchLeave","_onTouchCancel","onTouchStart","onTouchMove","onTouchEnd","onTouchEnter","onTouchLeave","onTouchCancel","consumeDocumentTouches","_documentTouchMove","changedTouches","InputHandler","useHandCursor","_setHandCursor","allowHorizontalDrag","allowVerticalDrag","snapOffset","snapOnDrag","snapOnRelease","snapX","snapY","snapOffsetX","snapOffsetY","pixelPerfectOver","pixelPerfectClick","pixelPerfectAlpha","draggable","boundsRect","boundsSprite","scaleLayer","dragOffset","dragFromCenter","dragStopBlocksInputUp","dragStartPoint","dragDistanceThreshold","dragTimeThreshold","downPoint","snapPoint","_dragPoint","_dragPhase","_pendingDrag","_dragTimePass","_dragDistancePass","_wasEnabled","_tempPoint","_pointerData","camX","camY","isOver","isOut","timeOver","timeOut","downDuration","onAddedToGroup","addedToGroup","onRemovedFromGroup","removedFromGroup","highestID","highestRenderID","includePixelPerfect","isPixelPerfect","pointerX","pointerY","pointerDown","pointerUp","pointerTimeDown","pointerTimeUp","pointerOver","pointerOut","pointerTimeOver","pointerTimeOut","pointerDragged","fastTest","checkPixel","_dx","_dy","startDrag","_draggedPointerID","updateDrag","sendEvent","onInputOver$dispatch","onInputOut$dispatch","onInputDown$dispatch","dragTimeElapsed","onInputUp$dispatch","stopDrag","fromStart","pointerLocalCoord","globalToLocal","checkBoundsRect","checkBoundsSprite","onDragUpdate","justOver","delay","overDuration","justOut","enableDrag","lockCenter","pixelPerfect","alphaThreshold","disableDrag","boundsCenterLocalCoord","onDragStart$dispatch","globalToLocalX","grid","boundsFluid","scaleFluidInversed","globalToLocalY","globalCoord","onDragStop$dispatch","setDragLock","allowHorizontal","allowVertical","enableSnap","onDrag","onRelease","disableSnap","_gamepadIndexMap","_rawPads","_active","_gamepadSupportAvailable","webkitGetGamepads","webkitGamepads","userAgent","getGamepads","_prevRawGamepadTypes","_prevTimestamps","onConnectCallback","onDisconnectCallback","onDownCallback","onUpCallback","onAxisCallback","onFloatCallback","_ongamepadconnected","_gamepaddisconnected","_gamepads","SinglePad","addCallbacks","callbacks","onConnect","onDisconnect","onAxis","_onGamepadConnected","onGamepadConnected","_onGamepadDisconnected","onGamepadDisconnected","newPad","connect","removedPad","disconnect","_pollGamepads","pad1","pollStatus","pad2","pad3","pad4","rawGamepads","gamepadsChanged","_rawPad","singlePad","validConnections","rawIndices","padIndices","connected","rawPad","setDeadZones","deadZone","BUTTON_0","BUTTON_1","BUTTON_2","BUTTON_3","BUTTON_4","BUTTON_5","BUTTON_6","BUTTON_7","BUTTON_8","BUTTON_9","BUTTON_10","BUTTON_11","BUTTON_12","BUTTON_13","BUTTON_14","BUTTON_15","AXIS_0","AXIS_1","AXIS_2","AXIS_3","AXIS_4","AXIS_5","AXIS_6","AXIS_7","AXIS_8","AXIS_9","XBOX360_A","XBOX360_B","XBOX360_X","XBOX360_Y","XBOX360_LEFT_BUMPER","XBOX360_RIGHT_BUMPER","XBOX360_LEFT_TRIGGER","XBOX360_RIGHT_TRIGGER","XBOX360_BACK","XBOX360_START","XBOX360_STICK_LEFT_BUTTON","XBOX360_STICK_RIGHT_BUTTON","XBOX360_DPAD_LEFT","XBOX360_DPAD_RIGHT","XBOX360_DPAD_UP","XBOX360_DPAD_DOWN","XBOX360_STICK_LEFT_X","XBOX360_STICK_LEFT_Y","XBOX360_STICK_RIGHT_X","XBOX360_STICK_RIGHT_Y","PS3XC_X","PS3XC_CIRCLE","PS3XC_SQUARE","PS3XC_TRIANGLE","PS3XC_L1","PS3XC_R1","PS3XC_L2","PS3XC_R2","PS3XC_SELECT","PS3XC_START","PS3XC_STICK_LEFT_BUTTON","PS3XC_STICK_RIGHT_BUTTON","PS3XC_DPAD_UP","PS3XC_DPAD_DOWN","PS3XC_DPAD_LEFT","PS3XC_DPAD_RIGHT","PS3XC_STICK_LEFT_X","PS3XC_STICK_LEFT_Y","PS3XC_STICK_RIGHT_X","PS3XC_STICK_RIGHT_Y","padParent","_padParent","_prevTimestamp","_buttons","_buttonsLen","_axes","_axesLen","getButton","timestamp","rawButtonVal","isNaN","processButtonDown","processButtonUp","processButtonFloat","processAxisChange","triggerCallback","disconnectingIndex","axisCode","buttonValue","Key","keycode","_enabled","durationUp","keyCode","onHoldCallback","onHoldContext","_justDown","_justUp","processKeyDown","processKeyUp","upDuration","pressEvent","onPressCallback","_keys","_capture","_onKeyDown","_onKeyPress","_onKeyUp","_k","onPress","removeCallbacks","addKey","addKeyCapture","addKeys","removeKey","removeKeyCapture","createCursorKeys","up","KeyCode","processKeyPress","clearCaptures","String","fromCharCode","charCode","A","charCodeAt","C","D","E","H","J","K","L","M","O","P","Q","R","S","T","U","V","W","X","Y","Z","ZERO","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","NUMPAD_0","NUMPAD_1","NUMPAD_2","NUMPAD_3","NUMPAD_4","NUMPAD_5","NUMPAD_6","NUMPAD_7","NUMPAD_8","NUMPAD_9","NUMPAD_MULTIPLY","NUMPAD_ADD","NUMPAD_ENTER","NUMPAD_SUBTRACT","NUMPAD_DECIMAL","NUMPAD_DIVIDE","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","F13","F14","F15","COLON","EQUALS","COMMA","UNDERSCORE","PERIOD","QUESTION_MARK","TILDE","OPEN_BRACKET","BACKWARD_SLASH","CLOSED_BRACKET","QUOTES","BACKSPACE","TAB","CLEAR","ENTER","SHIFT","CONTROL","ALT","CAPS_LOCK","ESC","SPACEBAR","PAGE_UP","PAGE_DOWN","END","HOME","PLUS","MINUS","INSERT","DELETE","HELP","NUM_LOCK","match","Component","Angle","wrapAngle","Animation","play","frameRate","loop","killOnComplete","animations","AutoCull","autoCull","inCamera","checkWorldBounds","Bounds","container","alignTo","BringToTop","Core","skipTypeChecks","install","components","Events","PhysicsBody","AnimationManager","LoadTexture","FixedToCamera","previousRotation","preUpdateChildren","fresh","_exists","P2JS","customRender","Crop","cropRect","_crop","updateCrop","resetFrame","oldX","oldY","oldW","oldH","_frame","Delta","Destroy","onDestroy$dispatch","removeFrom","Video","onChangeSource","resizeFrame","BitmapText","_glyphs","_parent","_onDestroy","_onAddedToGroup","_onRemovedFromGroup","_onKilled","_onRevived","_onEnterBounds","_onOutOfBounds","_onInputOver","_onInputOut","_onInputDown","_onInputUp","_onDragStart","_onDragUpdate","_onDragStop","_onAnimationStart","_onAnimationComplete","_onAnimationLoop","onKilled","onRevived","onOutOfBounds","onEnterBounds","onInputOver","onInputOut","onInputDown","onInputUp","onDragStart","onDragStop","onAnimationStart","onAnimationComplete","onAnimationLoop","backing","_fixedToCamera","Health","health","maxHealth","damage","setHealth","heal","InCamera","InputEnabled","InWorld","outOfCameraBoundsKill","_outOfBoundsFired","onEnterBounds$dispatch","onOutOfBounds$dispatch","outOfBoundsKill","inWorld","LifeSpan","lifespan","physicsElapsedMS","onRevived$dispatch","onKilled$dispatch","stopAnimation","BitmapData","hasFrameData","loadFrameData","getFrameData","frameData","Tilemap","TilemapLayer","img","getImage","trimmed","spriteSourceSizeX","spriteSourceSizeY","sourceSizeW","sourceSizeH","refreshTexture","frameName","Overlap","_reset","Reset","ScaleMinMax","scaleMin","scaleMax","checkTransform","setScaleMinMax","Smoothed","existing","weapon","bulletClass","Weapon","createBullets","Image","creature","mesh","tween","physicsGroup","SpriteBatch","audio","audioSprite","addSprite","tileSprite","rope","Rope","text","Text","overFrame","outFrame","downFrame","upFrame","Button","emitter","maxParticles","Arcade","Emitter","retroFont","font","characterWidth","characterHeight","chars","charsPerRow","xSpacing","ySpacing","xOffset","yOffset","RetroFont","bitmapText","tilemap","tileWidth","tileHeight","addToCache","uuid","addRenderTexture","video","bitmapData","addBitmapData","Tween","preUpdatePhysics","preUpdateLifeSpan","preUpdateInWorld","preUpdateCore","_onOverFrame","_onOutFrame","_onDownFrame","_onUpFrame","onOverSound","onOutSound","onDownSound","onUpSound","onOverSoundMarker","onOutSoundMarker","onDownSoundMarker","onUpSoundMarker","onOverMouseOnly","justReleasedPreventsOver","freezeFrames","forceOut","setFrames","onInputOverHandler","onInputOutHandler","onInputDownHandler","onInputUpHandler","clearFrames","setStateFrame","switchImmediately","frameKey","changeStateFrame","setStateSound","marker","soundKey","markerKey","Sound","AudioSprite","playStateSound","setSounds","overSound","overMarker","downSound","downMarker","outSound","outMarker","upSound","upMarker","setOverSound","setOutSound","setDownSound","setUpSound","fastSpriteBatch","ready","isRotated","childTransform","skipPool","ctx","imageData","FrameData","textureFrame","addFrame","Frame","disableTextureUpload","cls","_image","_pos","_size","_scale","_rotate","_alpha","prev","_anchor","_tempR","_tempG","_tempB","_circle","_swapCanvas","moveH","moveV","draw","onload","addImage","toDataURL","processPixelRGB","pixel","createColor","unpackPixel","getPixel32","setPixel32","processPixel","replaceRGB","g1","g2","region","packPixel","setHSL","bHaveH","bHaveS","bHaveL","HSLtoRGB","shiftHSL","red","green","blue","immediate","LITTLE_ENDIAN","setPixel","getPixel","getPixelRGB","hsl","hsv","getPixels","getFirstPixel","scan","newWidth","newHeight","getCanvas","op","copyTransform","copyRect","drawGroup","drawGroupProxy","drawFull","renderGraphics","shadow","blur","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","alphaMask","sourceRect","maskRect","blendSourceAtop","blendReset","extract","destination","prevFont","fillText","beginPath","arc","closePath","moveTo","lineTo","lineWidth","strokeStyle","stroke","polygon","textureLine","createPattern","blendSourceOver","blendSourceIn","blendSourceOut","blendDestinationOver","blendDestinationIn","blendDestinationOut","blendDestinationAtop","blendXor","blendAdd","blendMultiply","blendScreen","blendOverlay","blendDarken","blendLighten","blendColorDodge","blendColorBurn","blendHardLight","blendSoftLight","blendDifference","blendExclusion","blendHue","blendSaturation","blendColor","blendLuminosity","copyBitmapData","destRowStart","getSmoothingEnabled","setSmoothingEnabled","getTransform","translateX","translateY","skewX","skewY","EarCut","holeIndices","dim","hasHoles","outerLen","outerNode","linkedList","eliminateHoles","earcutLinked","clockwise","insertNode","filterPoints","again","steiner","removeNode","ear","pass","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","minTX","minTY","maxTX","maxTY","minZ","zOrder","maxZ","nextZ","prevZ","locallyInside","isValidDiagonal","splitPolygon","getLeftmost","compareX","eliminateHole","hole","findHoleBridge","hx","hy","qx","tan","tanMin","sortLinked","q","tail","numMerges","pSize","qSize","inSize","leftmost","intersectsPolygon","middleInside","Node","an","bp","stencilBufferLimit","lastIndex","clearDirty","graphicsDataPool","switchMode","buildPoly","buildComplexPoly","buildLine","buildRectangle","buildCircle","buildRoundedRectangle","upload","WebGLGraphicsData","rectData","fillColor","fillAlpha","vertPos","tempPoints","rrectData","recPoints","quadraticBezierCurve","vecPos","fromX","fromY","cpX","cpY","toX","toY","getPt","n1","n2","perc","xa","ya","xb","yb","circleData","seg","totalSegs","firstPoint","lastPoint","midPointX","midPointY","unshift","p1x","p1y","p2x","p2y","p3x","p3y","perpx","perpy","perp2x","perp2y","perp3x","perp3y","indexCount","indexStart","lineColor","lineAlpha","glPoints","glIndicies","updateGraphicsTint","_fillTint","_lineTint","strokeRect","ox","oy","xe","ye","xm","ym","bezierCurveTo","maxRadius","quadraticCurveTo","tintR","tintG","tintB","GraphicsData","currentPath","boundsPadding","_localBounds","_boundsDirty","webGLDirty","cachedSpriteDirty","updateLocalBounds","drawTriangle","cull","triangle","cameraToFace","faceNormal","drawPolygon","drawTriangles","point1","point2","point3","lineStyle","drawShape","cpX2","cpY2","dt2","dt3","arcTo","mm","dd","cc","tt","k1","k2","j1","j2","qy","anticlockwise","segments","sweep","segs","startX","startY","filling","theta","theta2","cTheta","sTheta","segMinus","remainder","drawRoundedRect","drawCircle","drawEllipse","canvasBuffer","updateCachedSpriteTexture","_prevTint","tempPoint","cachedSprite","destroyCachedSprite","textureBuffer","tempMatrix","renderXY","renderRawXY","updateBase","realResolution","getBase64","webGLPixels","Uint8Array","readPixels","tempCanvas","canvasData","textBounds","strokeColors","fontStyles","fontWeights","autoRound","useAdvancedWrap","splitRegExp","characterLimitSize","characterLimitSuffix","_res","_text","_fontComponents","_lineSpacing","_charCount","setStyle","updateText","setShadow","shadowStroke","shadowFill","newStyle","backgroundColor","boundsAlignH","boundsAlignV","strokeThickness","wordWrap","wordWrapWidth","maxLines","tabs","fontToComponents","fontStyle","fontVariant","fontWeight","fontSize","componentsToFont","outputText","substring","runWordWrap","lines","lineWidths","maxLineWidth","fontProperties","determineFontProperties","drawnLines","measureLine","measureText","tab","section","snapToCeil","lineHeight","lineSpacing","textBaseline","lineCap","lineJoin","linePositionX","linePositionY","ascent","updateLine","updateShadow","strokeText","renderTabLine","snap","lineLength","letter","clearColors","clearFontValues","addColor","addStrokeColor","addFontStyle","addFontWeight","weight","precalculateWordWrap","advancedWordWrap","basicWordWrap","linesCount","currentLineWidth","words","word","wordWithSpace","wordWidth","newWord","secondPart","spaceLeft","wordWidthWithSpace","updateFont","family","exec","fontFamily","setText","parseList","setTextBounds","properties","fontPropertiesCache","fontPropertiesCanvas","fontPropertiesContext","baseline","descent","imagedata","setCharacterLimit","characterLimit","suffix","parseFloat","createElement","textWidth","textHeight","_prevAnchor","_maxWidth","_data","getBitmapFont","_font","_fontSize","_align","_tint","sourceWidth","sourceHeight","scanLine","lastSpace","wrappedWidth","prevCharCode","maxWidth","test","charAt","charData","kerning","xAdvance","cleanText","re","purgeGlyphs","kept","checkImageKey","characterSpacingX","characterSpacingY","characterPerRow","multiLine","autoUpperCase","customSpacingX","customSpacingY","fixedWidth","fontSet","grabData","currentX","currentY","updateFrameData","stamp","ALIGN_LEFT","ALIGN_RIGHT","ALIGN_CENTER","TEXT_SET1","TEXT_SET2","TEXT_SET3","TEXT_SET4","TEXT_SET5","TEXT_SET6","TEXT_SET7","TEXT_SET8","TEXT_SET9","TEXT_SET10","TEXT_SET11","setFixedWidth","lineAlignment","content","characterSpacing","allowLowerCase","buildRetroFontText","getLongestLine","pasteLine","longestLine","removeUnsupportedCharacters","stripCR","newString","aChar","code","updateOffset","diffX","diffY","frames","getFrames","newText","toUpperCase","_hasUpdateAnimation","_updateAnimationCallback","canvasPadding","drawMode","updateAnimation","nextPoint","perpLength","_vertexBuffer","_initWebGL","_renderStrip","_indexBuffer","_uvBuffer","_colorBuffer","_renderCanvasTriangleStrip","_renderCanvasTriangles","_renderCanvasDrawTriangle","index0","textureSource","textureWidth","textureHeight","u0","v2","paddingX","paddingY","normX","normY","deltaA","deltaB","deltaC","deltaD","deltaE","deltaF","renderStripFlat","strip","rawX","rawY","_updateAnimation","difference","_scroll","textureDebug","tilePattern","frameWidth","frameHeight","physicsElapsed","autoScroll","stopScroll","generateTilingTexture","restartBatch","sessionBlendMode","forcePowerOfTwo","targetWidth","targetHeight","getNextPowerOfTwo","pool","getTotal","getFree","deviceReadyAt","initialized","desktop","iOSVersion","nodeWebkit","electron","ejecta","crosswalk","chromeOS","linux","macOS","windows","windowsPhone","canvasBitBltShift","file","fileSystem","localStorage","worker","css3D","typedArray","vibration","getUserMedia","quirksMode","arora","chromeVersion","epiphany","firefox","firefoxVersion","ieVersion","trident","tridentVersion","mobileSafari","midori","opera","safari","safariVersion","webApp","silk","audioData","ogg","opus","mp3","wav","m4a","webm","dolby","oggVideo","h264Video","mp4Video","webmVideo","vp9Video","hlsVideo","iPhone","iPhone4","iPad","pixelRatio","littleEndian","support32bit","fullscreen","requestFullscreen","cancelFullscreen","fullscreenKeyboard","onInitialized","nonPrimer","readyCheck","_readyCheck","_monitor","_queue","readyState","setTimeout","_initialize","_checkIsLittleEndian","_checkIsUint8ClampedImageData","Uint8ClampedArray","createImageData","vita","kindle","RegExp","$1","_checkOS","$3","process","versions","_checkBrowser","audioElement","canPlayType","major","minor","$2","_checkAudio","videoElement","_checkVideo","has3d","el","transforms","webkitTransform","OTransform","msTransform","MozTransform","insertBefore","getComputedStyle","getPropertyValue","_checkCSS3D","Int8Array","Int32Array","vibrate","webkitVibrate","mozVibrate","msVibrate","getItem","WebGLRenderingContext","compatMode","webkitGetUserMedia","mozGetUserMedia","msGetUserMedia","oGetUserMedia","URL","webkitURL","mozURL","msURL","_checkFeatures","s1","s2","_checkCanvasFeatures","fs","cfs","Element","_checkFullScreenSupport","documentElement","maxTouchPoints","PointerEvent","MSPointerEvent","msPointerEnabled","pointerEnabled","canPlayAudio","canPlayVideo","needsTouchUnlock","PhaserGlobal","fakeiOSTouchLock","isAndroidStockBrowser","matches","display","msTouchAction","overflowHidden","getElementById","overflow","appendChild","parentNode","vendor","prefix","types","msInterpolationMode","setImageRenderingBicubic","forceSetTimeOut","vendors","requestAnimationFrame","cancelAnimationFrame","_isSetTimeOut","_onLoop","_timeOutID","updateSetTimeout","updateRAF","rafTime","timeToCall","clearTimeout","isSetTimeOut","isRAF","DEG_TO_RAD","RAD_TO_DEG","degrees","radians","fuzzyLessThan","fuzzyGreaterThan","fuzzyCeil","fuzzyFloor","average","shear","snapTo","gap","snapToFloor","roundTo","place","floorTo","ceilTo","rotateToAngle","currentAngle","targetAngle","getShortestAngle","angleBetween","angleBetweenY","angleBetweenPoints","angleBetweenPointsY","reverseAngle","angleRad","normalizeAngle","maxAdd","minSub","wrapValue","isOdd","isEven","minProperty","maxProperty","linearInterpolation","bezierInterpolation","bernstein","catmullRomInterpolation","catmullRom","factorial","res","roundAwayFromZero","sinCosGenerator","sinAmplitude","cosAmplitude","frequency","frq","cosTable","sinTable","hypot","distanceSq","distancePow","clampBottom","within","mapLinear","smoothstep","smootherstep","sign","percent","seeds","s0","sow","integer","real","integerInRange","realInRange","ary","weightedPick","QuadTree","maxObjects","maxLevels","_empty","subWidth","subHeight","populate","populateHandler","insert","retrieve","returnObjects","getHostName","location","hostname","checkDomainName","domain","updateQueryString","redirect","href","separator","getQueryString","parameter","keyValues","search","decodeURI","decodeURIComponent","frameBased","_tweens","_add","easeMap","Power0","Easing","Power1","Power2","Power3","Power4","Linear","None","Quad","Quadratic","Out","Cubic","Quart","Quartic","Quint","Quintic","Sine","Sinusoidal","Expo","Exponential","Circ","Circular","Elastic","Back","Bounce","Quad.easeIn","In","Cubic.easeIn","Quart.easeIn","Quint.easeIn","Sine.easeIn","Expo.easeIn","Circ.easeIn","Elastic.easeIn","Back.easeIn","Bounce.easeIn","Quad.easeOut","Cubic.easeOut","Quart.easeOut","Quint.easeOut","Sine.easeOut","Expo.easeOut","Circ.easeOut","Elastic.easeOut","Back.easeOut","Bounce.easeOut","Quad.easeInOut","InOut","Cubic.easeInOut","Quart.easeInOut","Quint.easeInOut","Sine.easeInOut","Expo.easeInOut","Circ.easeInOut","Elastic.easeInOut","Back.easeInOut","Bounce.easeInOut","_pauseAll","_resumeAll","pendingDelete","_manager","addTweens","numTweens","isTweening","checkIsRunning","some","_pause","_resume","pauseAll","resumeAll","manager","timeline","timeScale","repeatCounter","onStart","onLoop","onRepeat","onChildComplete","onComplete","chainedTween","isPaused","_onUpdateCallback","_onUpdateCallbackContext","_pausedTime","_hasStarted","ease","yoyo","Default","TweenData","vEnd","loadValues","updateTweenData","repeatDelay","yoyoDelay","easing","interpolation","repeatAll","chain","startTime","status","PENDING","RUNNING","LOOPED","COMPLETE","generateData","vStart","vStartCache","vEndCache","repeatTotal","inReverse","easingFunction","interpolationFunction","interpolationContext","isFrom","ms","fps","blob","reversed","asin","prevTime","_desiredFps","suggestedFps","advancedTiming","updates","renders","ups","rps","fpsMin","fpsMax","msMin","msMax","pauseDuration","timeExpected","Timer","_frameCount","_elapsedAccumulator","_started","_timeLastSecond","_pauseStarted","_justResumed","_timers","timer","autoDestroy","previousDateNow","updateAdvancedTiming","updateTimers","interval","elapsedSince","since","elapsedSecondsSince","running","expired","nextTick","timeCap","_pauseTotal","_now","_marked","_diff","_newTick","MINUTE","SECOND","HALF","QUARTER","repeatCount","TimerEvent","clearEvents","clearPendingEvents","adjustEvents","baseTime","currentFrame","currentAnim","updateIfVisible","isLoaded","_frameData","_anims","_outputFrames","anim","copyFrameData","useNumericIndex","getFrameIndexes","validateFrames","checkFrameName","isPlaying","getAnimation","refreshFrame","gotFrame","getFrame","getFrameByName","_frameIndex","_frames","loopCount","isFinished","_pauseStartTime","_frameDiff","_frameSkip","onUpdate","isReversed","_timeLastFrame","_timeNextFrame","updateCurrentFrame","onAnimationStart$dispatch","reverseOnce","frameId","useLocalFrameIndex","frameIndex","directionalOffset","dispatchComplete","onAnimationComplete$dispatch","onAnimationLoop$dispatch","signalUpdate","fromPlay","generateFrameNames","zeroPad","spriteSourceSizeW","spriteSourceSizeH","setTrim","actualWidth","actualHeight","destX","destY","destWidth","destHeight","getRect","_frameNames","getFrameRange","AnimationParser","spriteSheet","frameMax","margin","spacing","skipFrames","JSONData","json","newFrame","filename","sourceSize","spriteSourceSize","JSONDataPyxel","tileheight","tilewidth","JSONDataHash","XMLData","xml","getElementsByTagName","frameX","frameY","autoResolveURL","binary","bitmapFont","compressedTexture","_urlMap","_urlResolver","_urlTemp","onSoundUnlock","_cacheMap","TEXTURE","SOUND","PHYSICS","BINARY","BITMAPFONT","JSON","XML","SHADER","RENDER_TEXTURE","_pendingCount","_addImages","DEFAULT_KEY","DEFAULT_SRC","MISSING","MISSING_KEY","MISSING_SRC","READY_TIMEOUT","addCompressedTextureMetaData","extension","arrayBuffer","removeImage","LoaderParser","fileFormat","_resolveURL","addCanvas","addImageAsync","_removePending","_addPending","addDefaultImage","addMissingImage","addSound","audioTag","decoded","isDecoding","touchLocked","addText","addPhysicsData","addTilemap","mapData","addBinary","binaryData","addBitmapFont","atlasData","atlasType","jsonBitmapFont","xmlBitmapFont","addBitmapFontFromAtlas","atlasKey","atlasFrame","dataKey","dataType","getBaseTexture","fontData","getJSON","getXML","addJSON","addXML","addVideo","isBlob","addShader","addSpriteSheet","addTextureAtlas","TEXTURE_ATLAS_XML_STARLING","TEXTURE_ATLAS_JSON_PYXEL","reloadSound","getSound","reloadSoundComplete","updateSound","decodedSound","isSoundDecoded","isSoundReady","checkKey","checkURL","checkCanvasKey","checkTextureKey","checkSoundKey","checkTextKey","checkPhysicsKey","checkTilemapKey","checkBinaryKey","checkBitmapDataKey","checkBitmapFontKey","checkJSONKey","checkXMLKey","checkVideoKey","checkShaderKey","checkRenderTextureKey","full","getTextureFrame","getSoundData","getText","getPhysicsData","fixtureKey","fixtures","fixture","getTilemapData","getBinary","getBitmapData","getVideo","getShader","getRenderTexture","getFrameCount","getFrameByIndex","getURL","getKeys","removeCanvas","destroyBaseTexture","removeSound","removeText","removePhysics","removeTilemap","removeBinary","removeBitmapData","removeBitmapFont","removeJSON","removeXML","removeVideo","removeShader","removeRenderTexture","removeSpriteSheet","removeTextureAtlas","baseURL","destroyItem","readyTimeout","_ready","_checkReady","isLoading","preloadSprite","crossOrigin","headers","requestedWith","onLoadStart","onLoadComplete","onPackComplete","onFileStart","onFileComplete","onFileError","enableParallel","maxParallelDownloads","_withSyncPointDepth","_fileList","_flightQueue","_processingHead","_fileLoadStarted","_totalPackCount","_totalFileCount","_loadedPackCount","_loadedFileCount","TEXTURE_ATLAS_JSON_ARRAY","TEXTURE_ATLAS_JSON_HASH","PHYSICS_LIME_CORONA_JSON","PHYSICS_PHASER_JSON","setPreloadSprite","checkKeyExists","getAssetIndex","bestFound","loaded","loading","getAsset","fileIndex","addToFileList","overwrite","syncPoint","currentFile","replaceInFileList","pack","imageFromBitmapData","imageFromGrid","imageFromTexture","pixelWidth","pixelHeight","palette","exkey","images","urls","script","spritesheet","autoDecode","noAudio","jsonURL","jsonData","audiosprite","loadEvent","asBlob","CSV","TILED_JSON","LIME_CORONA_JSON","textureURL","atlasURL","parseXml","atlasJSONArray","atlas","atlasJSONHash","atlasXML","withSyncPoint","addSyncPoint","asset","removeFile","updateProgress","processLoadQueue","finishedLoading","requestUrl","requestObject","progress","syncblock","inflightLimit","processPack","loadFile","abnormal","asyncComplete","errorMessage","packData","transformUrl","xhrLoad","fileComplete","loadImageTag","getAudioURL","usingWebAudio","usingAudioTag","loadAudioTag","fileError","getVideoURL","loadVideoTag","jsonLoadComplete","xmlLoadComplete","csvLoadComplete","onerror","controls","autoplay","videoLoadEvent","canplay","Audio","playThroughEvent","xhr","XMLHttpRequest","open","responseType","setRequestHeader","message","send","videoType","uri","lastIndexOf","audioType","reason","loadNext","responseText","response","decode","language","defer","head","contentType","domparser","DOMParser","parseFromString","ActiveXObject","async","loadXML","totalLoadedFiles","totalLoadedPacks","progressFloat","info","common","getAttribute","letters","kernings","second","finalizeBitmapFont","_face","_lineHeight","_id","_xoffset","_yoffset","_xadvance","_second","_first","_amount","bitmapFontData","pvr","uintArray","byteArray","pvrHeader","pixelFormat","flags","colorSpace","channelType","depth","numberOfSurfaces","numberOfFaces","numberOfMipmaps","metaDataSize","byteLength","dds","ddsHeader","pitch","mipmapCount","formatSize","formatFlag","formatFourCC","formatBitCount","formatRBitMask","formatGBitMask","formatBBitMask","formatABitMask","caps1","caps2","caps3","caps4","reserved2","DXGIFormat","resourceDimension","miscFlag","arraySize","ktx","ktxHeader","imageSizeOffset","imageSize","glInternalFormat","endianness","glType","glTypeSize","glFormat","glBaseInternalFormat","pixelDepth","numberOfArrayElements","numberOfMipmapLevels","bytesOfKeyValueData","keyAndValueByteSize","pkm","pkmHeader","originalWidth","originalHeight","autoplayKey","sounds","spritemap","addMarker","connectToMaster","markers","totalDuration","currentTime","durationMS","stopTime","pausedPosition","pausedTime","currentMarker","fadeTween","pendingPlayback","override","allowMultiple","externalNode","masterGainNode","gainNode","_sound","_globalVolume","_markedToDelete","_removeFromSoundManager","masterGain","createGain","createGainNode","gain","soundHasUnlocked","onDecoded","onPlay","onStop","onMute","onMarkerComplete","_volume","_buffer","_muted","_tempMarker","_tempPosition","_tempVolume","_tempPause","_muteVolume","_tempLoop","_onDecodedEventDispatched","removeMarker","onEndedHandler","onended","isDecoded","loopFull","forceRestart","noteOff","createBufferSource","noteGrainOn","muted","mute","prevMarker","fadeIn","fadeTo","fadeOut","fadeComplete","updateGlobalVolume","globalVolume","onSoundDecode","onVolumeChange","onUnMute","onTouchUnlock","channels","_codeMuted","_unlockSource","_sounds","_watchList","_watching","_watchCallback","_watchContext","disableAudio","disableWebAudio","audioContext","setTouchLock","unlock","setTouchUnlock","noteOn","stopAll","soundData","decodeAudioData","setDecodedCallback","files","playbackState","PLAYING_STATE","FINISHED_STATE","removeByKey","close","dom","minWidth","minHeight","maxHeight","forceLandscape","forcePortrait","incorrectOrientation","_pageAlignHorizontally","_pageAlignVertically","onOrientationChange","enterIncorrectOrientation","leaveIncorrectOrientation","hasPhaserSetFullScreen","fullScreenTarget","_createdFullScreenTarget","onFullScreenInit","onFullScreenChange","onFullScreenError","screenOrientation","getScreenOrientation","scaleFactorInversed","aspectRatio","sourceAspectRatio","windowConstraints","compatibility","supportsFullScreen","orientationFallback","noMargins","scrollTo","forceMinimumDocumentHeight","canExpandParent","clickTrampoline","_scaleMode","NO_SCALE","_fullScreenScaleMode","parentIsWindow","parentScaleFactor","trackParentInterval","onSizeChange","onResize","onResizeContext","_pendingScaleMode","_fullScreenRestore","_gameSize","_userScaleFactor","_userScaleTrim","_lastUpdate","_updateThrottle","_updateThrottleReset","_parentBounds","_tempBounds","_lastReportedCanvasSize","_lastReportedGameSize","_booted","setupScale","EXACT_FIT","SHOW_ALL","RESIZE","USER_SCALE","MODES","compat","_orientationChange","orientationChange","_windowResize","windowResize","_fullScreenChange","fullScreenChange","_fullScreenError","fullScreenError","_gameResumed","setGameSize","FlexGrid","fullScreenScaleMode","pageAlignHorizontally","alignH","pageAlignVertically","alignV","scaleH","scaleV","setUserScale","trimH","trimV","getParentBounds","visualBounds","updateDimensions","queueUpdate","currentScaleMode","hScale","vScale","hTrim","vTrim","setResizeCallback","signalSizeChange","setMinMax","prevThrottle","prevWidth","prevHeight","boundsChanged","orientationChanged","updateOrientationState","updateLayout","throttle","updateScalingAndBounds","forceOrientation","classifyOrientation","orientation","previousOrientation","previouslyIncorrect","isLandscape","isPortrait","changed","correctnessChanged","scrollTop","setMaximum","setExactFit","isFullScreen","boundingParent","setShowAll","resetCanvas","reflowCanvas","reflowGame","layoutBounds","clientRect","getBoundingClientRect","parentRect","offsetParent","wc","windowBounds","alignCanvas","parentBounds","canvasBounds","currentEdge","targetEdge","marginLeft","marginRight","marginTop","marginBottom","cssWidth","cssHeight","expanding","createFullScreenTarget","fsTarget","background","startFullScreen","allowTrampoline","cleanupCreatedTarget","initData","targetElement","ALLOW_KEYBOARD_INPUT","stopFullScreen","prepScreenMode","enteringFullscreen","createdTarget","scaleSprite","letterBox","scaleX1","scaleY1","scaleX2","scaleY2","scaleOnWidth","bmd","columnWidth","renderShadow","currentColor","currentAlpha","_line","_rect","soundInfo","filled","rectangle","geom","cameraInfo","hideIfUp","downColor","upColor","worldX","worldY","spriteInputInfo","justDown","justUp","inputInfo","spriteBounds","ropeSegments","segment","spriteInfo","spriteCoords","lineInfo","forceType","ellipse","quadTree","quadtree","NINJA","Ninja","BOX2D","Box2D","renderBody","bodyInfo","renderBodyInfo","box2d","box2dWorld","renderDebugDraw","box2dBody","displayList","canvasPool","phaser","factor","loader","box","scrollY","scrollLeft","scrollX","clientTop","clientLeft","cushion","calibrate","coords","getAspectRatio","inLayoutViewport","primaryFallback","screen","mozOrientation","msOrientation","matchMedia","documentBounds","pageXOffset","pageYOffset","clientWidth","clientHeight","offsetWidth","scrollWidth","offsetHeight","scrollHeight","randomIndex","removeRandomItem","newLength","transposeMatrix","sourceRowCount","sourceColCount","rotateMatrix","findClosest","arr","NaN","low","high","rotateRight","rotateLeft","numberArray","numberArrayStep","LinkedList","entity","palettes","0","PALETTE_ARNE","PALETTE_JMP","PALETTE_CGA","PALETTE_C64","PALETTE_JAPANESE_MACHINE","row","boundsCustom","boundsFull","boundsNone","positionCustom","positionFluid","positionFull","positionNone","scaleCustom","scaleFluid","scaleFull","scaleNone","customWidth","customHeight","customOffsetX","customOffsetY","ratioH","ratioV","layers","createCustomLayer","layer","FlexLayer","createFluidLayer","createFullLayer","createFixedLayer","persist","fitSprite","topLeft","topMiddle","topRight","bottomLeft","bottomMiddle","bottomRight","RED","ORANGE","YELLOW","GREEN","AQUA","BLUE","VIOLET","WHITE","BLACK","GRAY","RGBtoHSL","RGBtoHSV","fromRGBA","toRGBA","toABGR","RGBArrayToHex","rgb","hueToColor","HSVtoRGB","color32","getColor","getColor32","RGBtoString","componentToHex","hexToRGB","hex","hexToColor","webToColor","web","tempColor","getRGB","HSVColorWheel","HSLColorWheel","interpolateColor","color1","color2","currentStep","src1","src2","hsv1","hsv2","dh","h3","interpolateColorWithRGB","or","og","ob","interpolateRGB","getRandomColor","getWebRGB","getAlpha","getAlphaFloat","getRed","getGreen","getBlue","blendNormal","blendAverage","blendSubtract","blendNegation","blendLinearDodge","blendLinearBurn","blendLinearLight","blendVividLight","blendPinLight","blendHardMix","blendReflect","blendGlow","blendPhoenix","arcade","ninja","chipmunk","matter","CHIPMUNK","MATTERJS","P2","Matter","startSystem","system","enableAABB","checkCollision","OVERLAP_BIAS","forceX","sortDirection","LEFT_RIGHT","skipQuadTree","_total","SORT_NONE","RIGHT_LEFT","TOP_BOTTOM","BOTTOM_TOP","updateMotion","allowRotation","velocityDelta","computeVelocity","angularAcceleration","angularDrag","maxAngular","acceleration","drag","maxVelocity","allowGravity","allowDrag","object1","object2","overlapCallback","processCallback","collideObjects","collide","collideCallback","sortLeftRight","sortRightLeft","sortTopBottom","sortBottomTop","overlapOnly","collideHandler","collideGroupVsSelf","collideSpriteVsSprite","collideSpriteVsGroup","collideSpriteVsTilemapLayer","collideGroupVsGroup","collideGroupVsTilemapLayer","sprite1","sprite2","separate","items","bounds1","bounds2","group1","group2","body1","body2","none","isCircle","separateCircle","bodyRect","bodyCircle","resultX","resultY","separateX","separateY","onOverlap","onCollide","circleBodyIntersects","getOverlapX","getOverlapY","angleCollision","immovable","customSeparateX","tempVel1","tempVel2","bounce","maxOverlap","deltaAbsX","embedded","touching","overlapX","deltaAbsY","overlapY","moves","nv1","nv2","avg","customSeparateY","getObjectsUnderPointer","getObjectsAtLocation","callbackArg","moveToObject","maxTime","distanceBetween","moveToPointer","angleToPointer","distanceToPointer","moveToXY","distanceToXY","velocityFromAngle","velocityFromRotation","accelerationFromRotation","accelerateToObject","xSpeedMax","ySpeedMax","accelerateToPointer","accelerateToXY","angleToXY","closest","targets","farthest","angleBetweenCenters","worldAngleToPointer","preRotation","newVelocity","deltaMax","worldBounce","onWorldBounds","facing","overlapR","collideWorldBounds","wasTouching","blocked","tilePadding","syncBounds","isMoving","stopVelocityOnCollide","moveTimer","moveDistance","moveDuration","moveTarget","moveEnd","onMoveComplete","movementCallback","movementCallbackContext","_sx","_sy","updateBounds","asx","asy","updateCenter","updateMovement","collided","stopMovement","stopVelocity","check","moveFrom","setCircle","onFloor","onCeiling","onWall","TilemapCollision","TILE_BIAS","tilemapLayer","getTiles","getTileOffsetX","getTileOffsetY","separateTile","tile","tilemapLayerOffsetX","tilemapLayerOffsetY","collisionCallback","collisionCallbackContext","faceLeft","faceRight","faceTop","faceBottom","tileCheckX","tileCheckY","collideRight","collideLeft","processTileSeparationX","collideDown","collideUp","processTileSeparationY","useElapsedTime","materials","InversePointProxy","walls","onBodyAdded","onBodyRemoved","onSpringAdded","onSpringRemoved","onConstraintAdded","onConstraintRemoved","onContactMaterialAdded","onContactMaterialRemoved","postBroadphaseCallback","onBeginContact","onEndContact","mpx","mpxi","pxm","pxmi","beginContactHandler","endContactHandler","collisionGroups","nothingCollisionGroup","CollisionGroup","boundsCollisionGroup","everythingCollisionGroup","boundsCollidesWith","_toRemove","_collisionGroupID","_boundsLeft","_boundsRight","_boundsTop","_boundsBottom","_boundsOwnGroup","removeBodyNextStep","setImpactEvents","impactHandler","setPostBroadphaseCallback","postBroadphaseHandler","_bodyCallbacks","_bodyCallbackContext","_groupCallbacks","_groupCallbackContext","setCollisionGroup","setWorldMaterial","updateBoundsCollisionGroup","setupWall","wall","fixedStepTime","impactCallback","createDistanceConstraint","getBody","createGearConstraint","createRevoluteConstraint","createLockConstraint","createPrismaticConstraint","lockRotation","anchorA","anchorB","setMaterial","createMaterial","createContactMaterial","getSprings","getConstraints","filterStatic","physicsPosition","query","toJSON","createCollisionGroup","bitmask","createSpring","worldA","worldB","localA","localB","createRotationalSpring","createBody","addPolygon","createParticle","convertCollisionObjects","map","collision","shapeData","polyline","addRectangle","clearTilemapLayerBodies","getLayer","convertTilemap","optimize","collides","getTileRight","FixtureList","rawList","namedFixtures","groupedFixtures","allFixtures","setCategory","bit","getFixtures","setMask","setSensor","getFixtureByKey","getGroup","groupID","_ref","_results","callee","PointProxy","collidesWith","removeNextStep","debugBody","_collideWorldBounds","setRectangleFromSprite","createBodyCallback","createGroupCallback","getCollisionMask","updateCollisionMask","clearCollision","clearGroup","clearMask","removeCollisionGroup","clearCallback","shapeChanged","impulse","localX","localY","setZeroRotation","setZeroVelocity","setZeroDamping","moveForward","moveBackward","thrust","thrustLeft","thrustRight","moveLeft","moveRight","updateSpriteTransform","resetDamping","resetMass","clearShapes","addCircle","addPlane","addParticle","addLine","addCapsule","setRectangle","addPhaserPolygon","createdFixtures","fixtureData","shapesOfFixture","addFixture","generatedShapes","categoryBits","maskBits","isSensor","polygons","loadPolygon","BodyDebug","settings","defaultSettings","pixelsPerLengthUnit","debugPolygons","ppu","lw","vrot","_j","_ref1","randomPastelHex","drawCapsule","drawPlane","drawLine","drawRectangle","drawConvex","drawPath","lastx","lasty","diagMargin","diagSize","maxLength","xd","yd","mix","rgbToHex","ImageCollection","firstgid","imageWidth","imageHeight","imageMargin","imageSpacing","containsImageIndex","imageIndex","gid","Tile","flipped","scanned","setCollisionCallback","setCollision","resetCollision","isInteresting","faces","TilemapParser","widthInPixels","heightInPixels","tilesets","imagecollections","tiles","collideIndexes","currentLayer","debugMap","_tempA","NORTH","EAST","SOUTH","WEST","setTileSize","createBlankLayer","addTilesetImage","tileset","tileMargin","tileSpacing","getTilesetIndex","setImage","newSet","Tileset","countX","countY","columns","rows","createFromObjects","CustomClass","adjustY","adjustSize","createFromTiles","replacements","customClass","lh","createLayer","getLayerIndex","rootLayer","groupEnd","indexes","getImageIndex","setTileIndexCallback","setTileLocationCallback","recalculate","setCollisionByIndex","calculateFaces","setCollisionBetween","setCollisionByExclusion","layerArg","setPreventRecalculate","preventingRecalculate","needToRecalculate","above","below","getTileAbove","getTileBelow","getTileLeft","setLayer","hasTile","removeTile","removeTileWorldXY","putTile","putTileWorldXY","searchTileIndex","getTile","nonNull","getTileWorldXY","paste","tileblock","tileA","tileB","swapHandler","removeAllLayers","dump","txt","renderSettings","enableScrollDelta","overdrawRatio","copyCanvas","debugSettings","missingImageFill","debuggedTileOverfill","forceFullRedraw","debugAlpha","facingEdgeStroke","collidingTileOverfill","scrollFactorX","scrollFactorY","rayStepRate","_wrap","_mc","renderWidth","renderHeight","_scrollX","_scrollY","tileOffset","ensureSharedCopyCanvas","sharedCopyCanvas","resizeWorld","_fixX","_unfixX","_fixY","_unfixY","getTileX","getTileY","getTileXY","getRayCastTiles","interestingFace","coord","fetchAll","wy","wx","resolveTileset","tileIndex","setIndex","containsTileIndex","resetTilesetCache","setScale","xScale","yScale","shiftCanvas","copyW","copyH","copyContext","renderRegion","lastAlpha","xmax","ymax","baseX","normStartX","renderDeltaScroll","shiftX","shiftY","renderW","renderH","trueTop","trueBottom","trueLeft","trueRight","renderFull","redrawAll","mc","renderDebug","baseY","normStartY","INSERT_NULL","getEmptyData","parseCSV","parseTiledJSON","column","_slice","fields","sliced","parseObjectGroup","objectGroup","objectsCollection","collisionCollection","nameKey","relativePosition","curl","encoding","binaryString","atob","bytes","opacity","offsetx","offsety","flippedVal","curi","tilesetGroupObjects","lastSet","tileproperties","tileProperties","updateTileData","imagewidth","imageheight","newCollection","objectgroup","lastgid","sid","drawCoords","coordIndex","setSpacing","rowCount","colCount","autoScale","scaleData","_s","autoAlpha","alphaData","_a","onEmit","setAlphaData","setScaleData","emitters","ID","minAngle","maxAngle","minSpeed","maxSpeed","minParticleSpeed","maxParticleSpeed","minParticleScale","maxParticleScale","minRotation","maxRotation","minParticleAlpha","maxParticleAlpha","particleClass","particleDrag","particleAnchor","emitX","emitY","particleBringToTop","particleSendToBack","counts","emitted","failed","totalEmitted","totalFailed","_gravity","_minParticleScale","_maxParticleScale","_timer","_counter","_flowQuantity","_flowTotal","_explode","emitParticle","makeParticles","particleArguments","particle","rndKey","rndFrame","explode","flow","forceQuantity","getNextParticle","resetParticle","setXSpeed","setYSpeed","setRotation","setAlpha","rate","tweenData","setAngle","lifespanOutput","bullets","autoExpandBulletsGroup","autofire","shots","fireLimit","fireRate","fireRateVariance","fireFrom","fireAngle","bulletInheritSpriteSpeed","bulletAnimation","bulletFrameRandom","bulletFrameCycle","bulletWorldWrap","bulletWorldWrapPadding","bulletAngleOffset","bulletAngleVariance","bulletSpeed","bulletSpeedVariance","bulletLifespan","bulletKillDistance","bulletGravity","bulletRotateToVelocity","bulletKey","bulletFrame","_bulletClass","Bullet","_bulletCollideWorldBounds","_bulletKillType","KILL_WORLD_BOUNDS","customBody","bulletBounds","bulletFrames","bulletFrameIndex","anims","onFire","onKill","onFireLimit","trackedSprite","trackedPointer","multiFire","_hasFired","trackRotation","trackOffset","_nextFire","_tempNextFire","_rotatedPoint","KILL_NEVER","KILL_LIFESPAN","KILL_DISTANCE","KILL_WEAPON_BOUNDS","KILL_CAMERA_BOUNDS","KILL_STATIC_BOUNDS","resetShots","newLimit","fire","trackSprite","trackPointer","fireMany","fireOffset","moveX","moveY","bullet","bulletManager","killType","bulletKillType","killDistance","rotateToVelocity","bodyDirty","bulletCollideWorldBounds","fireAtPointer","fireAtSprite","fireAtXY","setBulletBodyOffset","setBulletFrames","cycle","addBulletAnimation","debugBodies","onAccess","onError","onTimeout","playWhenUnlocked","timeout","videoStream","isStreaming","retryLimit","retry","retryInterval","_retryID","_pending","_pendingChangeSource","_autoplay","_endCallback","_playCallback","_video","createVideoFromBlob","videoWidth","videoHeight","createVideoFromURL","snapshot","connectToMediaStream","stream","startMediaStream","captureAudio","removeVideoElement","setAttribute","getUserMediaTimeout","getUserMediaSuccess","getUserMediaError","mozSrcObject","createObjectURL","onloadeddata","checkStream","checkVideoProgress","change","playbackRate","setPause","setResume","playHandler","getTracks","track","playing","ended","changeSource","grab","hasChildNodes","firstChild","removeAttribute","canUseNewCanvasBlendModes"],"mappings":";;CAoDC,SAASA,GAAG,GAAG,iBAAiBC,QAAQC,OAAOD,QAAQD,QAAS,CAAmD,IAAIG,EAAE,oBAAoBC,OAAOD,EAAEC,OAAO,oBAAoBC,OAAOF,EAAEE,OAAO,oBAAoBC,OAAOH,EAAEG,MAAMH,EAAEI,GAAGP,KAAzO,CAA+O,WAAqC,OAAO,SAAUA,EAAEQ,EAAEC,EAAEC,GAAG,SAASC,EAAEC,EAAEC,GAAG,IAAIJ,EAAEG,GAAG,CAAC,IAAIJ,EAAEI,GAAG,CAAC,IAAIE,EAAkB,mBAATC,SAAqBA,QAAQ,IAAIF,GAAGC,EAAE,OAAOA,EAAEF,GAAE,GAAI,GAAGI,EAAE,OAAOA,EAAEJ,GAAE,GAAI,MAAM,IAAIK,MAAM,uBAAuBL,EAAE,KAAK,IAAIT,EAAEM,EAAEG,IAAIX,YAAYO,EAAEI,GAAG,GAAGM,KAAKf,EAAEF,QAAQ,SAASD,GAAG,IAAIS,EAAED,EAAEI,GAAG,GAAGZ,GAAG,OAAOW,EAAEF,GAAIT,IAAIG,EAAEA,EAAEF,QAAQD,EAAEQ,EAAEC,EAAEC,GAAG,OAAOD,EAAEG,GAAGX,QAAkD,IAAI,IAA1Ce,EAAkB,mBAATD,SAAqBA,QAAgBH,EAAE,EAAEA,EAAEF,EAAES,OAAOP,IAAID,EAAED,EAAEE,IAAI,OAAOD,EAArZ,EAA0ZS,GAAG,SAASC,EAAQnB,EAAOD,GASjtB,SAASqB,KART,IAAIC,EAASF,EAAQ,YAErBnB,EAAOD,QAAUqB,EAiBjBA,EAAKE,QAAU,SAASC,EAAGC,EAAGC,GAC1BA,EAAYA,GAAa,EACzB,IACIC,EAAIC,EAAIC,EAAIC,EAAIC,EAAIC,EAAIC,EADxBlB,GAAK,EAAE,GAaX,OAXAY,EAAKH,EAAG,GAAG,GAAKA,EA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D,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAItW,GACxB99C,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAGpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIpW,GACxBh+C,EAASitB,KAAWmnC,EAAInW,GAExBj+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAKpBn6C,EAASitB,KAAW0wB,EACpB39C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIlW,GACxBl+C,EAASitB,KAAWmnC,EAAIjW,GAExBn+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,IAGpBp6C,KAAKyzD,kBAEuBzzD,KAAKmM,MAE7BnM,KAAKy+C,UAObjK,EAAKkiB,qBAAqBt2D,UAAUq+C,MAAQ,WAGxC,GAA4B,IAAxBz+C,KAAKyzD,iBAAT,CAEA,IAAI5f,EAAK7zC,KAAK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,KAAKC,aAELD,KAAKC,WAAayC,EAAOzC,iBAGKn1B,IAA9Bk1B,KAAK2K,QAAQC,eAEb5K,KAAK2K,QAAQC,aAAe,IAAI5K,KAAK2K,QAAQ,IAAI3K,KAAKwmB,mBAGnB17C,IAAnCk1B,KAAKgC,cAAc6C,cAEnB7E,KAAKgC,cAAc6C,YAAc,IAAInC,EAAOC,QAGhD3C,KAAKinB,mBAAoB,EAGzBjnB,KAAKwxJ,0BAA4B,WAC7B,OAAO9uJ,EAAOgvC,OAAOnrB,gBASE,oBAAZn/D,SACe,oBAAXC,QAA0BA,OAAOD,UACxCA,QAAUC,OAAOD,QAAUs7C,GAE/Bt7C,QAAQs7C,OAASA,GACQ,oBAAXglB,QAA0BA,OAAOC,IAC/CD,OAAO,SAA+B3vB,EAAK2K,OAASA,GAEpD3K,EAAK2K,OAASA,EAGXA,GACRr6C,KAAKmD","file":"phaser.min.js"} \ No newline at end of file diff --git a/Digital Assignment 4/js/phaser.min.js b/Digital Assignment 4/js/phaser.min.js new file mode 100644 index 000000000..6eb048b7a --- /dev/null +++ b/Digital Assignment 4/js/phaser.min.js @@ -0,0 +1,4 @@ +/* Phaser v2.10.0 - http://phaser.io - @photonstorm - (c) 2016 Photon Storm Ltd. */ + +!function(t){if("object"==typeof exports)module.exports=t();else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.p2=t()}}(function(){return function t(e,i,s){function n(o,a){if(!i[o]){if(!e[o]){var h="function"==typeof require&&require;if(!a&&h)return h(o,!0);if(r)return r(o,!0);throw new Error("Cannot find module '"+o+"'")}var l=i[o]={exports:{}};e[o][0].call(l.exports,function(t){var i=e[o][1][t];return n(i||t)},l,l.exports,t,e,i,s)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;se[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;ia)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var T=0;Tm&&(m+=this.vertices.length),g=Number.MAX_VALUE,m3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e) (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.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.1"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;ca[f]&&(a[f]=u[f]),u[f]i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle");var n=t("../collision/Broadphase");t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;az&&Y0)for(G=0;GMath.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=x,f=b,g=_,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var w=r.vertices[y];if(o.rotate(p,w,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var T=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(T.normalA,f);var P=l(g,T.normalA);o.scale(g,T.normalA,P),a(T.contactPointB,p,n.position),a(T.contactPointA,p,g),a(T.contactPointA,T.contactPointA,t.position),this.contactEquations.push(T),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(T))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=x,p=b;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=x;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,w=u;w=w||0;var T=x,P=b,C=_;a(T,g,y),o.rotate(P,v,w);var S=l(P,T);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,P),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,T,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=x,m=b,y=_,v=w,P=T,E=C,M=S,R=A,L=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(M,u,i),l(g,M)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),I=s.getClosestEdge(c,d,g);if(-1===B||-1===I)return 0;for(var O=0;O<2;O++){var k=B,F=I,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===O){var q;q=k,k=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H=3){if(p)return!0;var Z=this.createContactEquation(j,V,D,U);L++;var J=D.vertices[k%D.vertices.length],Q=D.vertices[(k+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(P,v,y),o.rotate90cw(Z.normalA,P),o.normalize(Z.normalA,Z.normalA),a(M,m,y);var $=l(Z.normalA,M);o.scale(E,Z.normalA,$),a(Z.contactPointA,m,G),a(Z.contactPointA,Z.contactPointA,E),h(Z.contactPointA,Z.contactPointA,G),a(Z.contactPointA,Z.contactPointA,j.position),a(Z.contactPointB,m,N),h(Z.contactPointB,Z.contactPointB,N),a(Z.contactPointB,Z.contactPointB,V.position),this.contactEquations.push(Z),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Z))}}}return this.enableFrictionReduction&&this.enableFriction&&L&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;dh)&&(h=a),(null===c||ah){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,x=nt;if(t instanceof y&&n instanceof y)for(P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(C=0;2!==C;C++){0===C?o.set(m,0,1):1===C&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0),u=(S=T[0]-w[1])<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(var C=0;C!==b.vertices.length;C++){o.rotate(f,b.vertices[C],_),o.rotate(g,b.vertices[(C+1)%b.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0);var S=T[0]-w[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,x=pt,b=ct,_=ut,w=Math.floor((i[0]-d-l[0])/f),T=Math.ceil((i[0]+d-l[0])/f);w<0&&(w=0),T>=p.length&&(T=p.length-1);for(var P=p[w],C=p[T],S=w;SP&&(P=p[S]);if(i[1]-d>P)return!u&&0;for(var A=!1,S=w;S=b[0]&&m[0]<_[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,x,-E),o.add(y,m,g),o.copy(v,x);M=this.createContactEquation(n,t,r,e);o.copy(M.normalA,v),o.scale(M.contactPointB,M.normalA,-d),h(M.contactPointB,M.contactPointB,i),a(M.contactPointB,M.contactPointB,t.position),o.copy(M.contactPointA,y),o.sub(M.contactPointA,M.contactPointA,n.position),this.contactEquations.push(M),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(M))}}if(A=!1,d>0)for(S=w;S<=T;S++)if(o.set(b,S*f,p[S]),o.add(b,b,l),o.sub(g,i,b),o.squaredLength(g)=c.length&&(y=c.length-1);for(var v=c[m],x=c[y],b=m;bv&&(v=c[b]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var _=0,b=m;b=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;ne.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){this.from,this.to;var o=this._currentShape,a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;cthis.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.positioni?(a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n)):-1!==(b=t.indexOf(n))&&t.splice(b,1),this.lowerLimitEnabled&&va?(f.angle=a,-1===n.indexOf(f)&&n.push(f)):-1!==(y=n.indexOf(f))&&n.splice(y,1),this.lowerLimitEnabled&&m>1;if(e<3)return[];for(var i=[],n=[],r=0;r3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,x=1/(f*y-g*g),b=(y*m-g*v)*x,_=(f*v-g*m)*x;return b>=0&&_>=0&&b+_<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;ei&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),x=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||x;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(h=this.shapes.length;h>=0;--h)this.removeShape(this.shapes[h]);var i=new r.Polygon;if(i.vertices=t,i.makeCCW(),"number"==typeof e.removeCollinearPoints&&i.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!i.isSimple())return!1;this.concavePath=i.vertices.slice(0);for(h=0;h=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var T=n.create(),P=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(T,i,t*e),n.multiply(T,this.massMultiplier,T),n.add(r,T,r),this.integrateToTimeOfImpact(t)||(n.scale(P,r,t),n.add(s,s,P),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),M=n.create(),R=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)=l&&h=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var b=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),w=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),T=Math.pow(_,2)-4*b*w;if(!(T<0))if(0===T){if(r.lerp(d,n,o,T),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}else{var P=Math.sqrt(T),C=1/(2*b),S=(-_-P)*C,A=(-_+P)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,x=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;x>=0&&x<=1&&(r.lerp(f,n,h,x),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,x,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;in)&&(n=s),(null===o||sn){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;ee&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),nv){var x=y;y=v,v=x}for(var b=0;b=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,_,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};r.create();var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){(t=t||{}).type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){(t=t||{}).type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=t.lowerBound,a=t.upperBound;n(o,-1e7,-1e7),n(a,1e7,1e7),0===s?a[1]=0:s===Math.PI/2?o[0]=0:s===Math.PI?o[1]=0:s===3*Math.PI/2&&(a[0]=0)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}t("../utils/Utils");var n=t("../events/EventEmitter");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){this.overlappingShapesLastState;var n=this.overlappingShapesCurrentState;if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var s=t,n=e;(i=i||[]).length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;)(n=i.getByKey(i.keys[s]))&&e.push(n.bodyA,n.bodyB);return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s=t&&s=0;T-=2)for(S=b.length-2;S>=0;S-=2)(w[T]===b[S]&&w[T+1]===b[S+1]||w[T+1]===b[S]&&w[T]===b[S+1])&&b.splice(S,2);q=u.length;for(T=0;T!==q;T++){var C=u[T];if(!C.collideConnected)for(var S=b.length-2;S>=0;S-=2)(C.bodyA===b[S]&&C.bodyB===b[S+1]||C.bodyB===b[S]&&C.bodyA===b[S+1])&&b.splice(S,2)}this.postBroadphaseEvent.pairs=b,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var T=0,A=b.length;T!==A;T+=2)for(var E=b[T],M=b[T+1],R=0,L=E.shapes.length;R!==L;R++)for(var B=E.shapes[R],I=B.position,O=B.angle,k=0,F=M.shapes.length;k!==F;k++){var D=M.shapes[k],U=D.position,G=D.angle,N=this.defaultContactMaterial;if(B.material&&D.material){var X=this.getContactMaterial(B.material,D.material);X&&(N=X)}this.runNarrowphase(c,E,B,I,O,M,D,U,G,N,this.frictionGravity)}for(T=0;T!==h;T++)(H=n[T])._wakeUpAfterNarrowphase&&(H.wakeUp(),H._wakeUpAfterNarrowphase=!1);if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(P);for(var W=this.endContactEvent,k=P.length;k--;){var j=P[k];W.shapeA=j.shapeA,W.shapeB=j.shapeB,W.bodyA=j.bodyA,W.bodyB=j.bodyB,this.emit(W)}P.length=0}var V=this.preSolveEvent;V.contactEquations=c.contactEquations,V.frictionEquations=c.frictionEquations,this.emit(V),V.contactEquations=V.frictionEquations=null;var q=u.length;for(T=0;T!==q;T++)u[T].update();if(c.contactEquations.length||c.frictionEquations.length||q)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),T=0;T!==q;T++)v.appendArray(g.equations,u[T].equations);g.split(this);for(T=0;T!==g.islands.length;T++)(K=g.islands[T]).equations.length&&a.solveIsland(t,K)}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),T=0;T!==q;T++)a.addEquations(u[T].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(T=0;T!==h;T++){var H=n[T];H.integrate(t)}for(T=0;T!==h;T++)n[T].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var Y=this.impactEvent,T=0;T!==c.contactEquations.length;T++){var z=c.contactEquations[T];z.firstImpact&&(Y.bodyA=z.bodyA,Y.bodyB=z.bodyB,Y.shapeA=z.shapeA,Y.shapeB=z.shapeB,Y.contactEquation=z,this.emit(Y))}if(this.sleepMode===s.BODY_SLEEPING)for(T=0;T!==h;T++)n[T].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(T=0;T!==h;T++)n[T].sleepTick(this.time,!0,t);for(T=0;T0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,x=t.frictionEquations.length;y=i.type=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0),o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC&&r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0),this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var _=this.beginContactEvent;if(_.shapeA=i,_.shapeB=a,_.bodyA=e,_.bodyB=o,_.contactEquations.length=0,"number"==typeof y)for(P=t.contactEquations.length-y;P1)for(var P=t.frictionEquations.length-b;P=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var x=e[y],b=0,_=x.shapes.length;b!==_;b++){var w=x.shapes[b];r.rotate(p,w.position,x.angle),r.add(p,p,x.position);var T=w.angle+x.angle;(w instanceof o&&g.circleParticle(x,w,p,T,s,n,u,0,!0)||w instanceof a&&g.particleConvex(s,n,u,0,x,w,p,T,!0)||w instanceof h&&g.particlePlane(s,n,u,0,x,w,p,T,!0)||w instanceof l&&g.particleCapsule(s,n,u,0,x,w,p,T,!0)||w instanceof c&&r.squaredLength(r.sub(f,p,t))0?Math.acos(i/u):-Math.acos(i/u),this.worldScale.x=u,this.worldScale.y=c/u}else if(n||r){var d=Math.sqrt(n*n+r*r);this.worldRotation=Phaser.Math.HALF_PI-(r>0?Math.acos(-n/d):-Math.acos(n/d)),this.worldScale.x=c/d,this.worldScale.y=d}else this.worldScale.x=0,this.worldScale.y=0;return this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.x=l.tx,this.worldPosition.y=l.ty,this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,l,h),this},preUpdate:function(){},generateTexture:function(t,e,i){var n=this.getLocalBounds(),r=new Phaser.RenderTexture(this.game,0|n.width,0|n.height,i,e,t);return s.DisplayObject._tempMatrix.tx=-n.x,s.DisplayObject._tempMatrix.ty=-n.y,r.render(this,s.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?s.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):s.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=0;this.texture&&this.texture.baseTexture&&s._enableMultiTextureToggle&&(e=this.texture.baseTexture.textureIndex);var i=new Phaser.RenderTexture(this.game,t.width,t.height,void 0,void 0,void 0,void 0,e);this._cachedSprite=new s.Sprite(i),this._cachedSprite.worldTransform=this.worldTransform}var n=this._filters;this._filters=null,this._cachedSprite.filters=n,s.DisplayObject._tempMatrix.tx=-t.x,s.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,s.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=n,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},s.DisplayObject.prototype.displayObjectUpdateTransform=s.DisplayObject.prototype.updateTransform,Object.defineProperties(s.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],i=0;i=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},s.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},s.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},s.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},s.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},s.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},s.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},s.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(t,i),n=0;na?u:a,d=d>h?d:h);var f=this._bounds;if(!p){var g=(f=new s.Rectangle).x,m=f.width+f.x,y=f.y,v=f.height+f.y,x=this.worldTransform,b=x.a,_=x.b,w=x.c,T=x.d,P=x.tx,C=x.ty,S=b*m+w*v+P,A=T*v+_*m+C,E=b*g+w*v+P,M=T*v+_*g+C,R=b*g+w*y+P,L=T*y+_*g+C,B=b*m+w*y+P,I=T*y+_*m+C;u=S,d=A,c=A,l=B<(l=R<(l=E<(l=S)?E:l)?R:l)?B:l,c=I<(c=L<(c=M(u=R>(u=E>u?E:u)?R:u)?B:u,d=I>(d=L>(d=M>d?M:d)?L:d)?I:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n(f=T>(f=_>(f=x>f?x:f)?_:f)?T:f)?C:f,g=S>(g=P>(g=w>(g=b>g?b:g)?w:g)?P:g)?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},s.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=Phaser.identityMatrix;for(var e=0;e= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}","}"];var n=s.compileProgram(t,this.vertexSrc||s.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(n),this.uSamplerArray=t.getUniformLocation(n,"uSamplerArray[0]"),this.projectionVector=t.getUniformLocation(n,"projectionVector"),this.offsetVector=t.getUniformLocation(n,"offsetVector"),this.dimensions=t.getUniformLocation(n,"dimensions"),this.aVertexPosition=t.getAttribLocation(n,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(n,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(n,"aColor"),this.aTextureIndex=t.getAttribLocation(n,"aTextureIndex");var r=[],o=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var a=0;a 0.0) gl_Position = vec4(0.0);"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);"," vTextureIndex = aTextureIndex;","}"],s.PixiFastShader=function(t){if(this._UID=Phaser._UID++,this.gl=t,this.program=null,s._enableMultiTextureToggle){var t=this.gl;this.MAX_TEXTURES=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(var e="\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n",i=1;i= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["// PixiFastShader Fragment Shader.","precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;","}"];this.vertexSrc=["// PixiFastShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","attribute float aTextureIndex;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;"," vColor = aColor;","}"],this.textureCount=0,this.init()},s.PixiFastShader.prototype.constructor=s.PixiFastShader,s.PixiFastShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["//StripShader Fragment Shader.","precision mediump float;","varying vec2 vTextureCoord;","varying float vTextureIndex;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord);","}"];this.vertexSrc=["//StripShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aTextureIndex;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;","}"],this.init()},s.StripShader.prototype.constructor=s.StripShader,s.StripShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t},i=this.gl,n=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),r=i.getParameter(i.MAX_TEXTURE_SIZE),o=this.game.cache._cache.image,a=null,h=0;h=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var a=i._uvs;if(a){var h,l,c,u,d=t.anchor.x,p=t.anchor.y;if(i.trim){var f=i.trim;h=(l=f.x-d*f.width)+i.crop.width,c=(u=f.y-p*f.height)+i.crop.height}else h=i.frame.width*(1-d),l=i.frame.width*-d,c=i.frame.height*(1-p),u=i.frame.height*-p;var g=this.currentBatchSize*this.vertexSize,m=(this.currentBatchSize,i.baseTexture.resolution),y=i.baseTexture.textureIndex,v=o.a/m,x=o.b/m,b=o.c/m,_=o.d/m,w=o.tx,T=o.ty,P=(i.crop.width,i.crop.height);if(i.rotated){var C=o.a,S=o.b,A=o.c,E=o.d,M=l,R=h;w=o.c*P+w,T=o.d*P+T,v=6.123233995736766e-17*C-A,x=6.123233995736766e-17*S-E,b=C+6.123233995736766e-17*A,_=S+6.123233995736766e-17*E,i._updateUvsInverted(),h=c,l=u,c=R,u=M}var L=this.colors,B=this.positions,I=t.tint,O=(I>>16)+(65280&I)+((255&I)<<16)+(255*t.worldAlpha<<24);this.renderSession.roundPixels?(B[g++]=v*l+b*u+w|0,B[g++]=_*u+x*l+T|0,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w|0,B[g++]=_*u+x*h+T|0,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w|0,B[g++]=_*c+x*h+T|0,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w|0,B[g++]=_*c+x*l+T|0,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y):(B[g++]=v*l+b*u+w,B[g++]=_*u+x*l+T,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w,B[g++]=_*u+x*h+T,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w,B[g++]=_*c+x*h+T,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w,B[g++]=_*c+x*l+T,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y),this.sprites[this.currentBatchSize++]=t}},s.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture,i=e.baseTexture,n=this.gl,r=t.texture.baseTexture.textureIndex;s.WebGLRenderer.textureArray[r]!=i&&(this.flush(),n.activeTexture(n.TEXTURE0+r),n.bindTexture(n.TEXTURE_2D,i._glTextures[n.id]),s.WebGLRenderer.textureArray[r]=i),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new s.TextureUvs);var o=t._uvs,a=e.baseTexture.width,h=e.baseTexture.height;t.tilePosition.x%=a*t.tileScaleOffset.x,t.tilePosition.y%=h*t.tileScaleOffset.y;var l=t.tilePosition.x/(a*t.tileScaleOffset.x),c=t.tilePosition.y/(h*t.tileScaleOffset.y),u=t.width/a/(t.tileScale.x*t.tileScaleOffset.x),d=t.height/h/(t.tileScale.y*t.tileScaleOffset.y);o.x0=0-l,o.y0=0-c,o.x1=1*u-l,o.y1=0-c,o.x2=1*u-l,o.y2=1*d-c,o.x3=0-l,o.y3=1*d-c;var p=t.tint,f=(p>>16)+(65280&p)+((255&p)<<16)+(255*t.worldAlpha<<24),g=this.positions,m=this.colors,y=t.width,v=t.height,x=t.anchor.x,b=t.anchor.y,_=y*(1-x),w=y*-x,T=v*(1-b),P=v*-b,C=this.currentBatchSize*this.vertexSize,S=e.baseTexture.resolution,A=t.worldTransform,E=A.a/S,M=A.b/S,R=A.c/S,L=A.d/S,B=A.tx,I=A.ty;g[C++]=E*w+R*P+B,g[C++]=L*P+M*w+I,g[C++]=o.x0,g[C++]=o.y0,m[C++]=f,g[C++]=r,g[C++]=E*_+R*P+B,g[C++]=L*P+M*_+I,g[C++]=o.x1,g[C++]=o.y1,m[C++]=f,g[C++]=r,g[C++]=E*_+R*T+B,g[C++]=L*T+M*_+I,g[C++]=o.x2,g[C++]=o.y2,m[C++]=f,g[C++]=r,g[C++]=E*w+R*T+B,g[C++]=L*T+M*w+I,g[C++]=o.x3,g[C++]=o.y3,m[C++]=f,g[C++]=r,this.sprites[this.currentBatchSize++]=t},s.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,t=this.defaultShader.shaders[e.id],e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var i=this.vertexSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,i,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,i,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,i,16),e.vertexAttribPointer(t.aTextureIndex,1,e.FLOAT,!1,i,20)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);var n=this.positions.subarray(0,this.currentBatchSize*this.vertexSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m0&&(v=!1),(f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){(t=(p=a).shaders[e.id])||((t=new s.PixiShader(e)).fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var x=this.renderSession.projection;e.uniform2f(t.projectionVector,x.x,x.y);var b=this.renderSession.offset;e.uniform2f(t.offsetVector,b.x,b.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},s.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},s.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},s.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},s.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},s.WebGLFastSpriteBatch=function(t){this.vertSize=11,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,i=6*this.maxSize;this.vertices=new Float32Array(e),this.indices=new Uint16Array(i),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var s=0,n=0;s=this.size&&this.flush()}},s.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]){if(this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}else this.renderSession.renderer.updateTexture(this.currentBaseTexture,t)}},s.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},s.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36),t.vertexAttribPointer(this.shader.aTextureIndex,1,t.FLOAT,!1,i,40)},s.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},s.WebGLFilterManager.prototype.constructor=s.WebGLFilterManager,s.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},s.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},s.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,i=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new s.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),i.x=a.width/2,i.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},s.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),i=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,i.width*this.renderSession.resolution,i.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=i.height,this.vertexArray[2]=i.width,this.vertexArray[3]=i.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=i.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=i.width/this.width,this.uvArray[5]=i.height/this.height,this.uvArray[6]=i.width/this.width,this.uvArray[7]=i.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,i,p,f),this.texturePool.push(n),e._glFilterTexture=null},s.WebGLFilterManager.prototype.applyFilterPass=function(t,e,i,n){var r=this.gl,o=t.shaders[r.id];o||((o=new s.PixiShader(r)).fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(!0),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,i/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},s.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},s.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e=0;t--){var e=this._glTextures[t],i=s.glContexts[t];i&&e&&i.deleteTexture(e)}this._glTextures.length=0,this.dirty()},s.BaseTexture.fromCanvas=function(t,e,i){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),i=i||1,new s.BaseTexture(t,e,i)},s.TextureSilentFail=!1,s.Texture=function(t,e,i,n){this.noFrame=!1,e||(this.noFrame=!0,e=new s.Rectangle(0,0,1,1)),t instanceof s.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=i||new s.Rectangle(0,0,1,1),this.rotated=!1,t.hasLoaded&&(this.noFrame&&(e=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},s.Texture.prototype.constructor=s.Texture,s.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},s.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},s.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,this.trim||!(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height))this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs();else{if(!s.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=!1}},s.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/i},s.Texture.prototype._updateUvsInverted=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.height)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.height)/e,this._uvs.y2=(t.y+t.width)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.width)/i},s.Texture.fromCanvas=function(t,e){var i=s.BaseTexture.fromCanvas(t,e);return new s.Texture(i)},s.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=s),exports.PIXI=s):"undefined"!=typeof define&&define.amd?define("PIXI",i.PIXI=s):i.PIXI=s,s}.call(this),function(){function t(t,e){this._scaleFactor=t,this._deltaMode=e,this.originalEvent=null}var e=this,i=i||{VERSION:"2.10.0",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,WEBGL_MULTI:4,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,PENDING_ATLAS:-1,HORIZONTAL:0,VERTICAL:1,LANDSCAPE:0,PORTRAIT:1,ANGLE_UP:270,ANGLE_DOWN:90,ANGLE_LEFT:180,ANGLE_RIGHT:0,ANGLE_NORTH_EAST:315,ANGLE_NORTH_WEST:225,ANGLE_SOUTH_EAST:45,ANGLE_SOUTH_WEST:135,TOP_LEFT:0,TOP_CENTER:1,TOP_RIGHT:2,LEFT_TOP:3,LEFT_CENTER:4,LEFT_BOTTOM:5,CENTER:6,RIGHT_TOP:7,RIGHT_CENTER:8,RIGHT_BOTTOM:9,BOTTOM_LEFT:10,BOTTOM_CENTER:11,BOTTOM_RIGHT:12,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},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{},_UID:0};if(Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Function.prototype.bind||(Function.prototype.bind=function(){var t=Array.prototype.slice;return function(e){function i(){var r=n.concat(t.call(arguments));s.apply(this instanceof i?this:e,r)}var s=this,n=t.call(arguments,1);if("function"!=typeof s)throw new TypeError;return i.prototype=function t(e){if(e&&(t.prototype=e),!(this instanceof t))return new t}(s.prototype),i}}()),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var s=arguments.length>=2?arguments[1]:void 0,n=0;n0&&100*Math.random()<=t},randomChoice:function(t,e){return Math.random()<.5?t:e},parseDimension:function(t,e){var i=0,s=0;return"string"==typeof t?"%"===t.substr(-1)?(i=parseInt(t,10)/100,s=0===e?window.innerWidth*i:window.innerHeight*i):s=parseInt(t,10):s=t,s},pad:function(t,e,i,s){if(void 0===e)var e=0;if(void 0===i)var i=" ";if(void 0===s)var s=3;var n=0;if(e+1>=(t=t.toString()).length)switch(s){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((n=e-t.length)/2),o=n-r;t=new Array(o+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t},isPlainObject:function(t){if("object"!=typeof t||t.nodeType||t===t.window)return!1;try{if(t.constructor&&!{}.hasOwnProperty.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},extend:function(){var t,e,s,n,r,o,a=arguments[0]||{},h=1,l=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[1]||{},h=2),l===h&&(a=this,--h);h0&&(this._radius=.5*s),this.type=i.CIRCLE},i.Circle.prototype={circumference:function(){return Math.PI*this._radius*2},random:function(t){void 0===t&&(t=new i.Point);var e=2*Math.PI*Math.random(),s=Math.random()+Math.random(),n=s>1?2-s:s,r=n*Math.cos(e),o=n*Math.sin(e);return t.x=this.x+r*this.radius,t.y=this.y+o*this.radius,t},getBounds:function(){return new i.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(t,e,i){return this.x=t,this.y=e,this._diameter=i,this._radius=.5*i,this},copyFrom:function(t){return this.setTo(t.x,t.y,t.diameter)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.diameter=this._diameter,t},distance:function(t,e){var s=i.Math.distance(this.x,this.y,t.x,t.y);return e?Math.round(s):s},clone:function(t){return void 0===t||null===t?t=new i.Circle(this.x,this.y,this.diameter):t.setTo(this.x,this.y,this.diameter),t},contains:function(t,e){return i.Circle.contains(this,t,e)},circumferencePoint:function(t,e,s){return i.Circle.circumferencePoint(this,t,e,s)},sample:function(t,e,s,n,r){t||(t=60),null==e&&(e=0),null==s&&(s=i.Math.PI2),r||(r=[]);for(var o=0;o0&&(this._diameter=t,this._radius=.5*t)}}),Object.defineProperty(i.Circle.prototype,"radius",{get:function(){return this._radius},set:function(t){t>0&&(this._radius=t,this._diameter=2*t)}}),Object.defineProperty(i.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(t){t>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-t}}),Object.defineProperty(i.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(t){tthis.y?(this._radius=0,this._diameter=0):this.radius=this.y-t}}),Object.defineProperty(i.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(t){t0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(i.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(t){!0===t&&this.setTo(0,0,0)}}),i.Circle.contains=function(t,e,i){return t.radius>0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius},i.Circle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.diameter===e.diameter},i.Circle.intersects=function(t,e){return i.Math.distance(t.x,t.y,e.x,e.y)<=t.radius+e.radius},i.Circle.circumferencePoint=function(t,e,s,n){return void 0===s&&(s=!1),void 0===n&&(n=new i.Point),!0===s&&(e=i.Math.degToRad(e)),n.x=t.x+t.radius*Math.cos(e),n.y=t.y+t.radius*Math.sin(e),n},i.Circle.intersectsRectangle=function(t,e){var i=Math.abs(t.x-e.x-e.halfWidth);if(i>e.halfWidth+t.radius)return!1;var s=Math.abs(t.y-e.y-e.halfHeight);if(s>e.halfHeight+t.radius)return!1;if(i<=e.halfWidth||s<=e.halfHeight)return!0;var n=i-e.halfWidth,r=s-e.halfHeight;return n*n+r*r<=t.radius*t.radius},i.Circle.intersectsLine=function(t,e,s){var n=t.x,r=t.y,o=(e.end.y-e.start.y)/(e.end.x-e.start.x),a=e.end.y-o*e.end.x,h=t.radius,l=t.radius,c=a+o*n,u=(n*(l*l)-o*(h*h)*(a-r)+h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),d=(n*(l*l)-o*(h*h)*(a-r)-h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),p=o*u+a,f=o*d+a,g=new i.Point(u,p),m=new i.Point(d,f),y=e.pointOnSegment(g.x,g.y,.01),v=e.pointOnSegment(m.x,m.y,.01);return y&&v?!s||[g,m]:y?!s||[g]:v?!s||[m]:!!s&&[]},PIXI.Circle=i.Circle,i.Ellipse=function(t,e,s,n){t=t||0,e=e||0,s=s||0,n=n||0,this.x=t,this.y=e,this.width=s,this.height=n,this.type=i.ELLIPSE},i.Ellipse.prototype={setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},getBounds:function(){return new i.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},clone:function(t){return void 0===t||null===t?t=new i.Ellipse(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t},contains:function(t,e){return i.Ellipse.contains(this,t,e)},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random()*Math.PI*2,s=Math.random();return t.x=Math.sqrt(s)*Math.cos(e),t.y=Math.sqrt(s)*Math.sin(e),t.x=this.x+t.x*this.width/2,t.y=this.y+t.y*this.height/2,t},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},i.Ellipse.prototype.constructor=i.Ellipse,Object.defineProperty(i.Ellipse.prototype,"left",{get:function(){return this.x},set:function(t){this.x=t}}),Object.defineProperty(i.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t=s&&t<=n&&e>=r&&e<=o},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random();return t.x=this.start.x+e*(this.end.x-this.start.x),t.y=this.start.y+e*(this.end.y-this.start.y),t},coordinatesOnLine:function(t,e){void 0===t&&(t=1),void 0===e&&(e=[]);var i=Math.round(this.start.x),s=Math.round(this.start.y),n=Math.round(this.end.x),r=Math.round(this.end.y),o=Math.abs(n-i),a=Math.abs(r-s),h=i-a&&(c-=a,i+=h),d=0&&g<=1&&m>=0&&m<=1?o:null}return o},i.Line.intersects=function(t,e,s,n){return i.Line.intersectsPoints(t.start,t.end,e.start,e.end,s,n)},i.Line.intersectsRectangle=function(t,e){if(0===t.length||e.empty)return!1;var i=t.start.x,s=t.start.y,n=t.end.x,r=t.end.y,o=e.x,a=e.y,h=e.right,l=e.bottom,c=0;if(i>=o&&i<=h&&s>=a&&s<=l||n>=o&&n<=h&&r>=a&&r<=l)return!0;if(i=o){if((c=s+(r-s)*(o-i)/(n-i))>a&&c<=l)return!0}else if(i>h&&n<=h&&(c=s+(r-s)*(h-i)/(n-i))>=a&&c<=l)return!0;if(s=a){if((c=i+(n-i)*(a-s)/(r-s))>=o&&c<=h)return!0}else if(s>l&&r<=l&&(c=i+(n-i)*(l-s)/(r-s))>=o&&c<=h)return!0;return!1},i.Line.intersectionWithRectangle=function(t,e,s){var n=i.Line.intersectionWithRectangle;s||(s=new i.Point),n.edges||(n.edges=[new i.Line,new i.Line,new i.Line,new i.Line]),n.edgeIntersection||(n.edgeIntersection=new i.Point);var r=n.edges,o=n.edgeIntersection.set(0),a=e.x,h=e.y,l=e.right,c=e.bottom,u=1/0;r[0].setTo(a,h,l,h),r[1].setTo(a,c,l,c),r[2].setTo(a,h,a,c),r[3].setTo(l,h,l,c);for(var d,p=0;d=r[p];p++)if(t.intersects(d,!0,o)){var f=t.start.distance(o);fs&&(this.x=s),this.yn&&(this.y=n),this},clone:function(t){return void 0===t||null===t?t=new i.Point(this.x,this.y):t.setTo(this.x,this.y),t},copyTo:function(t){return t.x=this.x,t.y=this.y,t},distance:function(t,e){return i.Point.distance(this,t,e)},equals:function(t){return t.x===this.x&&t.y===this.y},equalsXY:function(t,e){return this.x===t&&this.y===e},fuzzyEquals:function(t,e){return i.Point.fuzzyEquals(this,t,e)},fuzzyEqualsXY:function(t,e,s){return i.Point.fuzzyEqualsXY(this,t,e,s)},angle:function(t,e){return this.angleXY(t.x,t.y,e)},angleXY:function(t,e,s){var n=Math.atan2(e-this.y,t-this.x);return s?i.Math.radToDeg(n):n},atan:function(t){var e=Math.atan2(this.y,this.x);return t?i.Math.radToDeg(e):e},rotate:function(t,e,s,n,r){return i.Point.rotate(this,t,e,s,n,r)},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(t){return this.normalize().multiply(t,t)},normalize:function(){if(!this.isZero()){var t=this.getMagnitude();this.x/=t,this.y/=t}return this},limit:function(t){return this.getMagnitudeSq()>t*t&&this.setMagnitude(t),this},expand:function(t){return this.getMagnitudeSq()=0&&e.x-i<0)return-1;if(t.x-i<0&&e.x-i>=0)return 1;if(t.x-i==0&&e.x-i==0)return t.y-s>=0||e.y-s>=0?t.y>e.y?1:-1:e.y>t.y?1:-1;var n=(t.x-i)*-(e.y-s)-(e.x-i)*-(t.y-s);return n<0?-1:n>0?1:(t.x-i)*(t.x-i)+(t.y-s)*(t.y-s)>(e.x-i)*(e.x-i)+(e.y-s)*(e.y-s)?-1:1})},PIXI.Point=i.Point,i.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.flattened=!1,this.type=i.POLYGON},i.Polygon.prototype={toNumberArray:function(t){void 0===t&&(t=[]);for(var e=0;e0){Array.isArray(t)||(t=Array.prototype.slice.call(arguments));for(var e=Number.MAX_VALUE,i=0,s=t.length;i=this.right?this.width=0:this.width=this.right-t,this.x=t}}),Object.defineProperty(i.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(i.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(i.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(i.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(t){this.x=t-this.halfWidth}}),Object.defineProperty(i.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(t){this.y=t-this.halfHeight}}),Object.defineProperty(i.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(i.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(i.Rectangle.prototype,"top",{get:function(){return this.y},set:function(t){t>=this.bottom?(this.height=0,this.y=t):this.height=this.bottom-t}}),Object.defineProperty(i.Rectangle.prototype,"topLeft",{get:function(){return new i.Point(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"topRight",{get:function(){return new i.Point(this.x+this.width,this.y)},set:function(t){this.right=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),i.Rectangle.prototype.constructor=i.Rectangle,i.Rectangle.inflate=function(t,e,i){return t.x-=e,t.width+=2*e,t.y-=i,t.height+=2*i,t},i.Rectangle.inflatePoint=function(t,e){return i.Rectangle.inflate(t,e.x,e.y)},i.Rectangle.size=function(t,e){return void 0===e||null===e?e=new i.Point(t.width,t.height):e.setTo(t.width,t.height),e},i.Rectangle.clone=function(t,e){return void 0===e||null===e?e=new i.Rectangle(t.x,t.y,t.width,t.height):e.setTo(t.x,t.y,t.width,t.height),e},i.Rectangle.createFromBounds=function(t,e){return void 0!==e&&null!==e||(e=new i.Rectangle(t.x,t.y,t.width,t.height)),e.copyFromBounds(t)},i.Rectangle.contains=function(t,e,i){return!(t.width<=0||t.height<=0)&&(e>=t.x&&e=t.y&&i=t&&n=e&&re.volume)&&(t.x>=e.x&&t.y>=e.y&&t.righte.right||t.y>e.bottom)},i.Rectangle.intersectsRaw=function(t,e,i,s,n,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||ns&&(s=t.x),t.xr&&(r=t.y),t.y=i&&t<=i+this.width){var s=this.y;if(e>=s&&e<=s+this.height)return!0}return!1}},i.RoundedRectangle.prototype.constructor=i.RoundedRectangle,PIXI.RoundedRectangle=i.RoundedRectangle,i.Camera=function(t,e,s,n,r,o){this.game=t,this.world=t.world,this.id=0,this.view=new i.Rectangle(s,n,r,o),this.bounds=new i.Rectangle(s,n,r,o),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this.lerp=new i.Point(1,1),this.onShakeComplete=new i.Signal,this.onFlashComplete=new i.Signal,this.onFadeComplete=new i.Signal,this.fx=null,this._targetPosition=new i.Point,this._edge=0,this._position=new i.Point,this._shake={intensity:0,duration:0,horizontal:!1,vertical:!1,shakeBounds:!0,x:0,y:0},this._fxDuration=0,this._fxType=0,this._fixedView=new i.Rectangle},i.Camera.FOLLOW_LOCKON=0,i.Camera.FOLLOW_PLATFORMER=1,i.Camera.FOLLOW_TOPDOWN=2,i.Camera.FOLLOW_TOPDOWN_TIGHT=3,i.Camera.SHAKE_BOTH=4,i.Camera.SHAKE_HORIZONTAL=5,i.Camera.SHAKE_VERTICAL=6,i.Camera.ENABLE_FX=!0,i.Camera.prototype={boot:function(){this.displayObject=this.game.world,this.scale=this.game.world.scale,this.game.camera=this,i.Graphics&&i.Camera.ENABLE_FX&&(this.fx=new i.Graphics(this.game),this.game.stage.addChild(this.fx))},preUpdate:function(){this.totalInView=0},follow:function(t,e,s,n){void 0===e&&(e=i.Camera.FOLLOW_LOCKON),void 0===s&&(s=1),void 0===n&&(n=1),this.target=t,this.lerp.set(s,n);var r;switch(e){case i.Camera.FOLLOW_PLATFORMER:var o=this.width/8,a=this.height/3;this.deadzone=new i.Rectangle((this.width-o)/2,(this.height-a)/2-.25*a,o,a);break;case i.Camera.FOLLOW_TOPDOWN:r=Math.max(this.width,this.height)/4,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_TOPDOWN_TIGHT:r=Math.max(this.width,this.height)/8,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_LOCKON:default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(t){this.setPosition(Math.round(t.x-this.view.halfWidth),Math.round(t.y-this.view.halfHeight))},focusOnXY:function(t,e){this.setPosition(Math.round(t-this.view.halfWidth),Math.round(e-this.view.halfHeight))},shake:function(t,e,s,n,r){return void 0===t&&(t=.05),void 0===e&&(e=500),void 0===s&&(s=!0),void 0===n&&(n=i.Camera.SHAKE_BOTH),void 0===r&&(r=!0),!(!s&&this._shake.duration>0)&&(this._shake.intensity=t,this._shake.duration=e,this._shake.shakeBounds=r,this._shake.x=0,this._shake.y=0,this._shake.horizontal=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_HORIZONTAL,this._shake.vertical=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_VERTICAL,!0)},flash:function(t,e,i,s){return void 0===t&&(t=16777215),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=1,this._fxDuration=e,this._fxType=0,!0)},fade:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=0,this._fxDuration=e,this._fxType=1,!0)},update:function(){this._fxDuration>0&&this.updateFX(),this._shake.duration>0&&this.updateShake(),this.bounds&&this.checkBounds(),this.roundPx&&(this.view.floor(),this._shake.x=Math.floor(this._shake.x),this._shake.y=Math.floor(this._shake.y)),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateFX:function(){0===this._fxType?(this.fx.alpha-=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha<=0&&(this._fxDuration=0,this.fx.alpha=0,this.onFlashComplete.dispatch())):(this.fx.alpha+=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha>=1&&(this._fxDuration=0,this.fx.alpha=1,this.onFadeComplete.dispatch()))},updateShake:function(){this._shake.duration-=this.game.time.elapsedMS,this._shake.duration<=0?(this.onShakeComplete.dispatch(),this._shake.x=0,this._shake.y=0):(this._shake.horizontal&&(this._shake.x=this.game.rnd.frac()*this._shake.intensity*this.view.width*2-this._shake.intensity*this.view.width),this._shake.vertical&&(this._shake.y=this.game.rnd.frac()*this._shake.intensity*this.view.height*2-this._shake.intensity*this.view.height))},updateTarget:function(){this._targetPosition.x=this.view.x+this.target.worldPosition.x,this._targetPosition.y=this.view.y+this.target.worldPosition.y,this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edgethis.deadzone.right&&(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.right,this.lerp.x)),this._edge=this._targetPosition.y-this.view.y,this._edgethis.deadzone.bottom&&(this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.bottom,this.lerp.y))):(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.view.halfWidth,this.lerp.x),this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.view.halfHeight,this.lerp.y)),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},setBoundsToWorld:function(){this.bounds&&this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1;var t=this.view.x+this._shake.x,e=this.view.right+this._shake.x,i=this.view.y+this._shake.y,s=this.view.bottom+this._shake.y;t<=this.bounds.x*this.scale.x?(this.atLimit.x=!0,this.view.x=this.bounds.x*this.scale.x,this._shake.shakeBounds||(this._shake.x=0)):e>=this.bounds.right*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.right*this.scale.x-this.width,this._shake.shakeBounds||(this._shake.x=0)),i<=this.bounds.top*this.scale.y?(this.atLimit.y=!0,this.view.y=this.bounds.top*this.scale.y,this._shake.shakeBounds||(this._shake.y=0)):s>=this.bounds.bottom*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom*this.scale.y-this.height,this._shake.shakeBounds||(this._shake.y=0))},setPosition:function(t,e){this.view.x=t,this.view.y=e,this.bounds&&this.checkBounds()},setSize:function(t,e){this.view.width=t,this.view.height=e},reset:function(){this.target=null,this.view.x=0,this.view.y=0,this._shake.duration=0,this._shake.x=0,this._shake.y=0,this.resetFX()},resetFX:function(){this.fx&&(this.fx.clear(),this.fx.alpha=0),this._fxDuration=0}},i.Camera.prototype.constructor=i.Camera,Object.defineProperty(i.Camera.prototype,"x",{get:function(){return this.view.x},set:function(t){this.view.x=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"y",{get:function(){return this.view.y},set:function(t){this.view.y=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"position",{get:function(){return this._position.set(this.view.x,this.view.y),this._position},set:function(t){void 0!==t.x&&(this.view.x=t.x),void 0!==t.y&&(this.view.y=t.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"width",{get:function(){return this.view.width},set:function(t){this.view.width=t}}),Object.defineProperty(i.Camera.prototype,"height",{get:function(){return this.view.height},set:function(t){this.view.height=t}}),Object.defineProperty(i.Camera.prototype,"shakeIntensity",{get:function(){return this._shake.intensity},set:function(t){this._shake.intensity=t}}),Object.defineProperty(i.Camera.prototype,"fixedView",{get:function(){return this._fixedView.setTo(0,0,this.view.width,this.view.height),this._fixedView}}),i.State=function(){this.game=null,this.key="",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.state=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},i.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},i.State.prototype.constructor=i.State,i.StateManager=function(t,e){this.game=t,this.states={},this._pendingState=null,void 0!==e&&null!==e&&(this._pendingState=e),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new i.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},i.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(t,e,s){void 0===s&&(s=!1);var n;return e instanceof i.State?n=e:"object"==typeof e?(n=e).game=this.game:"function"==typeof e&&(n=new e(this.game)),this.states[t]=n,s&&(this.game.isBooted?this.start(t):this._pendingState=t),n},remove:function(t){this.current===t&&(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.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[t]},start:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1),this.checkState(t)&&(this._pendingState=t,this._clearWorld=e,this._clearCache=i,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!1),this._pendingState=this.current,this._clearWorld=t,this._clearCache=e,arguments.length>2&&(this._args=Array.prototype.slice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var t=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,t),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache&&this.game.cache.destroy()))},checkState:function(t){var e=this.states[t];return e?!!(e.preload||e.create||e.update||e.render)||(console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"),!1):(console.warn("Phaser.StateManager - No state found with the key: "+t),!1)},link:function(t){var e=this.states[t];e.game=this.game,e.add=this.game.add,e.make=this.game.make,e.camera=this.game.camera,e.cache=this.game.cache,e.input=this.game.input,e.load=this.game.load,e.math=this.game.math,e.sound=this.game.sound,e.scale=this.game.scale,e.state=this,e.stage=this.game.stage,e.time=this.game.time,e.tweens=this.game.tweens,e.world=this.game.world,e.particles=this.game.particles,e.rnd=this.game.rnd,e.physics=this.game.physics,e.key=t},unlink:function(t){var e=this.states[t];e&&(e.game=null,e.add=null,e.make=null,e.camera=null,e.cache=null,e.input=null,e.load=null,e.math=null,e.sound=null,e.scale=null,e.state=null,e.stage=null,e.time=null,e.tweens=null,e.world=null,e.particles=null,e.rnd=null,e.physics=null)},setCurrentState:function(t){var e=this.states[t];this.callbackContext=e,this.link(t),this.onInitCallback=e.init||this.dummy,this.onPreloadCallback=e.preload||null,this.onLoadRenderCallback=e.loadRender||null,this.onLoadUpdateCallback=e.loadUpdate||null,this.onCreateCallback=e.create||null,this.onUpdateCallback=e.update||null,this.onPreRenderCallback=e.preRender||null,this.onRenderCallback=e.render||null,this.onResizeCallback=e.resize||null,this.onPausedCallback=e.paused||null,this.onResumedCallback=e.resumed||null,this.onPauseUpdateCallback=e.pauseUpdate||null,this.onShutDownCallback=e.shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=t,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),t===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){!1===this._created&&this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game),!1===this._created&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(t){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,t)},resize:function(t,e){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,t,e)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===i.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this._clearWorld=!0,this._clearCache=!0,this.clearCurrentState(),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,this.current=""}},i.StateManager.prototype.constructor=i.StateManager,Object.defineProperty(i.StateManager.prototype,"created",{get:function(){return this._created}}),i.Signal=function(){},i.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!1,validateListener:function(t,e){if("function"!=typeof t)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",e))},_registerListener:function(t,e,s,n,r){var o,a=this._indexOfListener(t,s);if(-1!==a){if((o=this._bindings[a]).isOnce()!==e)throw new Error("You cannot add"+(e?"":"Once")+"() then add"+(e?"Once":"")+"() the same listener without removing the relationship first.")}else o=new i.SignalBinding(this,t,e,s,n,r),this._addBinding(o);return this.memorize&&this._prevParams&&o.execute(this._prevParams),o},_addBinding:function(t){this._bindings||(this._bindings=[]);var e=this._bindings.length;do{e--}while(this._bindings[e]&&t._priority<=this._bindings[e]._priority);this._bindings.splice(e+1,0,t)},_indexOfListener:function(t,e){if(!this._bindings)return-1;void 0===e&&(e=null);for(var i,s=this._bindings.length;s--;)if((i=this._bindings[s])._listener===t&&i.context===e)return s;return-1},has:function(t,e){return-1!==this._indexOfListener(t,e)},add:function(t,e,i){this.validateListener(t,"add");var s=[];if(arguments.length>3)for(var n=3;n3)for(var n=3;n=this.children.length?-1:this.getChildAt(t)},i.Group.prototype.create=function(t,e,i,s,n,r){void 0===n&&(n=!0);var o=new this.classType(this.game,t,e,i,s);return o.exists=n,o.visible=n,o.alive=n,this.add(o,!1,r)},i.Group.prototype.createMultiple=function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=!1),Array.isArray(e)||(e=[e]),Array.isArray(i)||(i=[i]);var o=this,a=[];return e.forEach(function(e){i.forEach(function(i){for(var h=0;hthis.children.length||-1===t&&-1===e)return!1;for(var a=new i.Rectangle(0,0,s,n),h=t*s,l=e*n,c=o;cthis.children.length-1&&(t=0),this.cursor)return this.cursorIndex=t,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.next=function(){if(this.cursor)return this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.previous=function(){if(this.cursor)return 0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.swap=function(t,e){this.swapChildren(t,e),this.updateZ()},i.Group.prototype.bringToTop=function(t){return t.parent===this&&this.getIndex(t)0&&(this.remove(t,!1,!0),this.addAt(t,0,!0)),t},i.Group.prototype.moveUp=function(t){if(t.parent===this&&this.getIndex(t)0){var e=this.getIndex(t),i=this.getAt(e-1);i&&this.swap(t,i)}return t},i.Group.prototype.xy=function(t,e,i){if(t<0||t>this.children.length)return-1;this.getChildAt(t).x=e,this.getChildAt(t).y=i},i.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},i.Group.prototype.getIndex=function(t){return this.children.indexOf(t)},i.Group.prototype.getByName=function(t){for(var e=0;e0))return!1;var r=e.length;return 1===r?0===s?t[e[0]]=i:1===s?t[e[0]]+=i:2===s?t[e[0]]-=i:3===s?t[e[0]]*=i:4===s&&(t[e[0]]/=i):2===r?0===s?t[e[0]][e[1]]=i:1===s?t[e[0]][e[1]]+=i:2===s?t[e[0]][e[1]]-=i:3===s?t[e[0]][e[1]]*=i:4===s&&(t[e[0]][e[1]]/=i):3===r?0===s?t[e[0]][e[1]][e[2]]=i:1===s?t[e[0]][e[1]][e[2]]+=i:2===s?t[e[0]][e[1]][e[2]]-=i:3===s?t[e[0]][e[1]][e[2]]*=i:4===s&&(t[e[0]][e[1]][e[2]]/=i):4===r&&(0===s?t[e[0]][e[1]][e[2]][e[3]]=i:1===s?t[e[0]][e[1]][e[2]][e[3]]+=i:2===s?t[e[0]][e[1]][e[2]][e[3]]-=i:3===s?t[e[0]][e[1]][e[2]][e[3]]*=i:4===s&&(t[e[0]][e[1]][e[2]][e[3]]/=i)),!0},i.Group.prototype.checkProperty=function(t,e,s,n){if(void 0===n&&(n=!1),this!==t.parent)return!1;var r=i.Utils.getProperty(t,e);return!(void 0===r&&n||r!==s)},i.Group.prototype.set=function(t,e,i,s,n,r,o){if(void 0===o&&(o=!1),e=e.split("."),void 0===s&&(s=!1),void 0===n&&(n=!1),(!1===s||s&&t.alive)&&(!1===n||n&&t.visible))return this.setProperty(t,e,i,r,o)},i.Group.prototype.setAll=function(t,e,i,s,n,r){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===r&&(r=!1),t=t.split("."),n=n||0;for(var o=0;o2){i=[];for(s=2;s2){n=[];for(a=2;a=e&&(t=e-1);var i=this.children[t];this.updateOnlyExistingChildren&&!i.exists||i.update()}},i.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y);for(var t=0;t2){s=[null];for(var n=2;n2){s=[null];for(var n=2;n2){s=[null];for(var n=2;ne[this._sortProperty]?1:t.ze[this._sortProperty]?-1:0},i.Group.prototype.iterate=function(t,e,s,n,r,o){if(0===this.children.length){if(s===i.Group.RETURN_TOTAL)return 0;if(s===i.Group.RETURN_ALL)return[]}var a=0;if(s===i.Group.RETURN_ALL)var h=[];for(var l=0;l0)return this.children[this.children.length-1]},i.Group.prototype.getBottom=function(){if(this.children.length>0)return this.children[0]},i.Group.prototype.getClosestTo=function(t,e,s){for(var n=Number.MAX_VALUE,r=0,o=null,a=0;an&&(!e||e.call(s,h,r))&&(n=r,o=h)}return o},i.Group.prototype.count=function(t,e){return this.iterate(t,e,i.Group.RETURN_TOTAL)},i.Group.prototype.countLiving=function(){return this.count("alive",!0)},i.Group.prototype.countDead=function(){return this.count("alive",!1)},i.Group.prototype.getRandom=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.children.length),0===e?null:i.ArrayUtils.getRandomItem(this.children,t,e)},i.Group.prototype.getRandomExists=function(t,e){var i=this.getAll("exists",!0,t,e);return this.game.rnd.pick(i)},i.Group.prototype.getAll=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=this.children.length);for(var n=[],r=i;r0&&t instanceof i.Group){do{t.add(this.children[0],e)}while(this.children.length>0);this.hash=[],this.cursor=null}return t},i.Group.prototype.removeAll=function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),0!==this.children.length){do{!e&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var s=this.removeChild(this.children[0]);this.removeFromHash(s),t&&s&&s.destroy(!0,i)}while(this.children.length>0);this.hash=[],this.cursor=null}},i.Group.prototype.removeBetween=function(t,e,i,s){if(void 0===e&&(e=this.children.length-1),void 0===i&&(i=!1),void 0===s&&(s=!1),0!==this.children.length){if(t>e||t<0||e>this.children.length)return!1;for(var n=e;n>=t;){!s&&this.children[n].events&&this.children[n].events.onRemovedFromGroup$dispatch(this.children[n],this);var r=this.removeChild(this.children[n]);this.removeFromHash(r),i&&r&&r.destroy(!0),this.cursor===this.children[n]&&(this.cursor=null),n--}this.updateZ()}},i.Group.prototype.scatter=function(t,e){null==t&&(t=this.game.world.bounds),this.forEach(function(e){e.position.set(t.randomX,t.randomY)},null,e)},i.Group.prototype.shuffle=function(){i.ArrayUtils.shuffle(this.children),this.updateZ()},i.Group.prototype.destroy=function(t,e){null===this.game||this.ignoreDestroy||(void 0===t&&(t=!0),void 0===e&&(e=!1),this.onDestroy.dispatch(this,t,e),this.removeAll(t),this.cursor=null,this.filters=null,this.pendingDestroy=!1,e||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(i.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,i.Group.RETURN_TOTAL)}}),Object.defineProperty(i.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(i.Group.prototype,"angle",{get:function(){return i.Math.radToDeg(this.rotation)},set:function(t){this.rotation=i.Math.degToRad(t)}}),Object.defineProperty(i.Group.prototype,"centerX",{get:function(){return this.getBounds(this.parent).centerX},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.halfWidth}}),Object.defineProperty(i.Group.prototype,"centerY",{get:function(){return this.getBounds(this.parent).centerY},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.halfHeight}}),Object.defineProperty(i.Group.prototype,"left",{get:function(){return this.getBounds(this.parent).left},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i}}),Object.defineProperty(i.Group.prototype,"right",{get:function(){return this.getBounds(this.parent).right},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.width}}),Object.defineProperty(i.Group.prototype,"top",{get:function(){return this.getBounds(this.parent).top},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i}}),Object.defineProperty(i.Group.prototype,"bottom",{get:function(){return this.getBounds(this.parent).bottom},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.height}}),i.World=function(t){i.Group.call(this,t,null,"__world",!1),this.bounds=new i.Rectangle(0,0,t.width,t.height),this.camera=null,this._definedSize=!1,this._width=t.width,this._height=t.height,this.game.state.onStateChange.add(this.stateChange,this)},i.World.prototype=Object.create(i.Group.prototype),i.World.prototype.constructor=i.World,i.World.prototype.boot=function(){this.camera=new i.Camera(this.game,0,0,0,this.game.width,this.game.height),this.game.stage.addChild(this),this.camera.boot()},i.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},i.World.prototype.setBounds=function(t,e,i,s){this._definedSize=!0,this._width=i,this._height=s,this.bounds.setTo(t,e,i,s),this.x=t,this.y=e,this.camera.bounds&&this.camera.bounds.setTo(t,e,Math.max(i,this.game.width),Math.max(s,this.game.height)),this.game.physics.setBoundsToWorld()},i.World.prototype.resize=function(t,e){this._definedSize&&(tthis.bounds.right&&(t.x=this.bounds.left)),n&&(t.y+t._currentBounds.heightthis.bounds.bottom&&(t.y=this.bounds.top))):(s&&t.x+ethis.bounds.right&&(t.x=this.bounds.left-e),n&&t.y+ethis.bounds.bottom&&(t.y=this.bounds.top-e))},i.World.prototype.wrapAll=function(t,e,i,s,n,r){t.forEach(this.wrap,this,e,i,s,n,r)},Object.defineProperty(i.World.prototype,"width",{get:function(){return this.bounds.width},set:function(t){t1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.dropFrames?this.rendersThisFrame=0:(this.updateRender(this.time.slowMotion*this.time.desiredFps),this.rendersThisFrame=1);else{var e=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*e,this.time.elapsed),0);var i=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/e),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame)),this.forceSingleRender?this.rendersThisFrame=1:this.rendersThisFrame=Math.min(1,this.updatesThisFrame);this._deltaTime>=e&&(this._deltaTime-=e,this.currentUpdateID=i,this.updateLogic(this.time.desiredFpsMult),i++,!this.forceSingleUpdate||1!==i);)this.time.refresh();i>this._lastCount?this._spiraling++:i0&&this.updateRender(this._deltaTime/e)}}},updateLogic:function(t){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(t),this.debug.preUpdate(),this.input.pauseUpdate()):(this.stepping&&(this.pendingStep=!0),this.time.countUpdate(),this.scale.preUpdate(),this.debug.preUpdate(),this.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(t),this.plugins.preUpdate(t),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(),this.sound.update(),this.input.update(),this.physics.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate()),this.stage.updateTransform()},updateRender:function(t){this.lockRender||(this.time.countRender(),this.state.preRender(t),this.renderType!==i.HEADLESS&&(this.renderer.render(this.stage),this.plugins.render(t),this.state.render(t)),this.plugins.postRender(t))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.debug.destroy&&this.debug.destroy(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.plugins.destroy(),this.debug=null,this.state=null,this.sound=null,this.scale=null,this.stage=null,this.input=null,this.physics=null,this.plugins=null,this.cache=null,this.load=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),i.Canvas.removeFromDOM(this.canvas),PIXI.defaultRenderer=null,i.GAMES[this.id]=null},gamePaused:function(t){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.muteOnPause&&this.sound.setMute(),this.onPause.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(t){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.muteOnPause&&this.sound.unsetMute(),this.onResume.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(t){this.onBlur.dispatch(t),this.stage.disableVisibilityChange||this.gamePaused(t)},focusGain:function(t){this.onFocus.dispatch(t),this.stage.disableVisibilityChange||this.gameResumed(t)}},i.Game.prototype.constructor=i.Game,Object.defineProperty(i.Game.prototype,"paused",{get:function(){return this._paused},set:function(t){!0===t?(!1===this._paused&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),i.Input=function(t){this.game=t,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.customCandidateHandler=null,this.customCandidateHandlerContext=null,this.pollRate=0,this.enabled=!0,this.multiInputOverride=i.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.touchLockCallbacks=[],this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new i.ArraySet,this._localPoint=new i.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},i.Input.MOUSE_OVERRIDES_TOUCH=0,i.Input.TOUCH_OVERRIDES_MOUSE=1,i.Input.MOUSE_TOUCH_COMBINE=2,i.Input.MAX_POINTERS=10,i.Input.prototype={boot:function(){this.mousePointer=new i.Pointer(this.game,0,i.PointerMode.CURSOR),this.addPointer(),this.addPointer(),this.mouse=new i.Mouse(this.game),this.touch=new i.Touch(this.game),this.mspointer=new i.MSPointer(this.game),i.Keyboard&&(this.keyboard=new i.Keyboard(this.game)),i.Gamepad&&(this.gamepad=new i.Gamepad(this.game)),this.onDown=new i.Signal,this.onUp=new i.Signal,this.onTap=new i.Signal,this.onHold=new i.Signal,this.scale=new i.Point(1,1),this.speed=new i.Point,this.position=new i.Point,this._oldPosition=new i.Point,this.circle=new i.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=i.CanvasPool.create(this,1,1),this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.game.device.mspointer||this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var t=this;this._onClickTrampoline=function(e){t.onClickTrampoline(e)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],i.CanvasPool.remove(this),this.game.canvas.removeEventListener("click",this._onClickTrampoline)},setInteractiveCandidateHandler:function(t,e){this.customCandidateHandler=t,this.customCandidateHandlerContext=e},addMoveCallback:function(t,e){this.moveCallbacks.push({callback:t,context:e})},addTouchLockCallback:function(t,e,i){void 0===i&&(i=!1),this.touchLockCallbacks.push({callback:t,context:e,onEnd:i})},removeTouchLockCallback:function(t,e){for(var i=this.touchLockCallbacks.length;i--;)if(this.touchLockCallbacks[i].callback===t&&this.touchLockCallbacks[i].context===e)return this.touchLockCallbacks.splice(i,1),!0;return!1},executeTouchLockCallbacks:function(t,e){for(var i=this.touchLockCallbacks.length;i--;){var s=this.touchLockCallbacks[i];s.onEnd===t&&s.callback.call(s.context,this,e)&&this.touchLockCallbacks.splice(i,1)}},deleteMoveCallback:function(t,e){for(var i=this.moveCallbacks.length;i--;)if(this.moveCallbacks[i].callback===t&&this.moveCallbacks[i].context===e)return void this.moveCallbacks.splice(i,1)},addPointer:function(){if(this.pointers.length>=i.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+i.Input.MAX_POINTERS+" pointers reached."),null;var t=this.pointers.length+1,e=new i.Pointer(this.game,t,i.PointerMode.CONTACT);return this.pointers.push(e),this["pointer"+t]=e,e},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(t);if(!this.pointer2.active)return this.pointer2.start(t);for(var e=2;e0;i++)this.pointers[i].active&&e--;return t-e},getPointer:function(t){void 0===t&&(t=!1);for(var e=0;e=o&&this.game.camera.x+e.x=a&&this.game.camera.y+e.y=o&&this._localPoint.x=a&&this._localPoint.y=o&&this._localPoint.x=a&&this._localPoint.y0&&this._pollCounterthis.game.time.time},justReleased:function(t){return t=t||250,this.isUp&&this.timeUp+t>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},i.DeviceButton.prototype.constructor=i.DeviceButton,Object.defineProperty(i.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),i.Pointer=function(t,e,s){this.game=t,this.id=e,this.type=i.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.pointerMode=s||i.PointerMode.CURSOR|i.PointerMode.CONTACT,this.target=null,this.button=null,this.leftButton=new i.DeviceButton(this,i.Pointer.LEFT_BUTTON),this.middleButton=new i.DeviceButton(this,i.Pointer.MIDDLE_BUTTON),this.rightButton=new i.DeviceButton(this,i.Pointer.RIGHT_BUTTON),this.backButton=new i.DeviceButton(this,i.Pointer.BACK_BUTTON),this.forwardButton=new i.DeviceButton(this,i.Pointer.FORWARD_BUTTON),this.eraserButton=new i.DeviceButton(this,i.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===e,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.interactiveCandidates=[],this.active=!1,this.dirty=!1,this.position=new i.Point,this.positionDown=new i.Point,this.positionUp=new i.Point,this.circle=new i.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},i.Pointer.NO_BUTTON=0,i.Pointer.LEFT_BUTTON=1,i.Pointer.RIGHT_BUTTON=2,i.Pointer.MIDDLE_BUTTON=4,i.Pointer.BACK_BUTTON=8,i.Pointer.FORWARD_BUTTON=16,i.Pointer.ERASER_BUTTON=32,i.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.start(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.start(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.start(e),t===i.Mouse.BACK_BUTTON&&this.backButton.start(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.start(e)},processButtonsUp:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.stop(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.stop(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(e),t===i.Mouse.BACK_BUTTON&&this.backButton.stop(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(e)},processButtonsUpDown:function(t,e){var s="down"===e.type.toLowerCase().substr(-4),n="move"===e.type.toLowerCase().substr(-4);void 0!==t?(s&&1===t&&e.ctrlKey&&(t=2),this.leftButton.startStop(i.Pointer.LEFT_BUTTON&t,e),this.rightButton.startStop(i.Pointer.RIGHT_BUTTON&t,e),this.middleButton.startStop(i.Pointer.MIDDLE_BUTTON&t,e),this.backButton.startStop(i.Pointer.BACK_BUTTON&t,e),this.forwardButton.startStop(i.Pointer.FORWARD_BUTTON&t,e),this.eraserButton.startStop(i.Pointer.ERASER_BUTTON&t,e)):void 0!==e.button?s&&e.ctrlKey&&0===e.button?this.rightButton.start(e):s?this.processButtonsDown(e.button,e):n||this.processButtonsUp(e.button,e):s?e.ctrlKey?this.rightButton.start(e):this.leftButton.start(e):(this.leftButton.stop(e),this.rightButton.stop(e))},updateButtons:function(t){this.button=t.button,this.processButtonsUpDown(t.buttons,t),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(t){var e=this.game.input;return t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.isMouse?this.updateButtons(t):(this.isDown=!0,this.isUp=!1),this.active=!0,this.withinGame=!0,this.dirty=!1,this._history=[],this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(t,!0),this.positionDown.setTo(this.x,this.y),(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.x=this.x,e.y=this.y,e.position.setTo(this.x,this.y),e.onDown.dispatch(this,t),e.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){var t=this.game.input;this.active&&(this.dirty&&(t.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),!1===this._holdSent&&this.duration>=t.holdRate&&((t.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||t.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||t.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===t.totalActivePointers)&&t.onHold.dispatch(this),this._holdSent=!0),t.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+t.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>t.recordLimit&&this._history.shift()))},move:function(t,e){var s=this.game.input;if(!s.pollLocked){void 0===e&&(e=!1),void 0!==t.button&&(this.button=t.button),this.isMouse&&this.updateButtons(t),this.clientX=t.clientX,this.clientY=t.clientY,this.pageX=t.pageX,this.pageY=t.pageY,this.screenX=t.screenX,this.screenY=t.screenY,this.isMouse&&s.mouse.locked&&!e&&(this.rawMovementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.rawMovementY=t.movementY||t.mozMovementY||t.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*s.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*s.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(s.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||s.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||s.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===s.totalActivePointers)&&(s.activePointer=this,s.x=this.x,s.y=this.y,s.position.setTo(s.x,s.y),s.circle.x=s.x,s.circle.y=s.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY);for(var n=s.moveCallbacks.length;n--;)s.moveCallbacks[n].callback.call(s.moveCallbacks[n].context,this,this.x,this.y,e);return null===this.targetObject||this.game.paused&&!this.targetObject.noPause||!0!==this.targetObject.isDragged?s.interactiveItems.total>0&&this.processInteractiveObjects(e):!1===this.targetObject.update(this)&&(this.targetObject=null),this}},processInteractiveObjects:function(t){var e=0,i=-1,s=null,n=this.game.input.interactiveItems.first;for(this.interactiveCandidates=[];n;)n.checked=!1,!n.validForInput(i,e,!1)||this.game.paused&&!n.sprite.noPause||(n.checked=!0,(t&&n.checkPointerDown(this,!0)||!t&&n.checkPointerOver(this,!0))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n))),n=this.game.input.interactiveItems.next;for(n=this.game.input.interactiveItems.first;n;)!n.checked&&n.validForInput(i,e,!0)&&(t&&n.checkPointerDown(this,!1)||!t&&n.checkPointerOver(this,!1))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n)),n=this.game.input.interactiveItems.next;return this.game.input.customCandidateHandler&&(s=this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext,this,this.interactiveCandidates,s)),this.swapTarget(s,!1),null!==this.targetObject},swapTarget:function(t,e){void 0===e&&(e=!1),null===t?this.targetObject&&(this.targetObject._pointerOutHandler(this,e),this.targetObject=null):null===this.targetObject?(this.targetObject=t,t._pointerOverHandler(this,e)):this.targetObject===t?!1===t.update(this)&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this,e),this.targetObject=t,this.targetObject._pointerOverHandler(this,e))},leave:function(t){this.withinGame=!1,this.move(t,!1)},stop:function(t){var e=this.game.input;{if(!this._stateReset||!this.withinGame)return this.timeUp=this.game.time.time,(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.onUp.dispatch(this,t),this.duration>=0&&this.duration<=e.tapRate&&(this.timeUp-this.previousTapTime0&&(this.active=!1),this.withinGame=this.game.scale.bounds.contains(t.pageX,t.pageY),this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),!1===this.isMouse&&e.currentPointers--,e.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this;t.preventDefault()}},justPressed:function(t){return t=t||this.game.input.justPressedRate,!0===this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||this.game.input.justReleasedRate,this.isUp&&this.timeUp+t>this.game.time.time},addClickTrampoline:function(t,e,i,s){if(this.isDown){for(var n=this._clickTrampolines=this._clickTrampolines||[],r=0;rt||this.priorityID===t&&this.sprite.renderOrderID>e))},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(t){return t=t||0,this._pointerData[t].x},pointerY:function(t){return t=t||0,this._pointerData[t].y},pointerDown:function(t){return t=t||0,this._pointerData[t].isDown},pointerUp:function(t){return t=t||0,this._pointerData[t].isUp},pointerTimeDown:function(t){return t=t||0,this._pointerData[t].timeDown},pointerTimeUp:function(t){return t=t||0,this._pointerData[t].timeUp},pointerOver:function(t){if(!this.enabled)return!1;if(void 0===t){for(var e=0;e<10;e++)if(this._pointerData[e].isOver)return!0;return!1}return this._pointerData[t].isOver},pointerOut:function(t){if(!this.enabled)return!1;if(void 0!==t)return this._pointerData[t].isOut;for(var e=0;e<10;e++)if(this._pointerData[e].isOut)return!0},pointerTimeOver:function(t){return t=t||0,this._pointerData[t].timeOver},pointerTimeOut:function(t){return t=t||0,this._pointerData[t].timeOut},pointerDragged:function(t){return t=t||0,this._pointerData[t].isDragged},checkPointerDown:function(t,e){return!!(t.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectClick)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPointerOver:function(t,e){return!!(this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectOver)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPixel:function(t,e,i){if(this.sprite.texture.baseTexture.source){if(null===t&&null===e){this.game.input.getLocalPosition(this.sprite,i,this._tempPoint);var t=this._tempPoint.x,e=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(t-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(e-=-this.sprite.texture.frame.height*this.sprite.anchor.y),t+=this.sprite.texture.frame.x,e+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(t-=this.sprite.texture.trim.x,e-=this.sprite.texture.trim.y,tthis.sprite.texture.crop.right||ethis.sprite.texture.crop.bottom))return this._dx=t,this._dy=e,!1;if(this._dx=t,this._dy=e,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,t,e,1,1,0,0,1,1),this.game.input.hitContext.getImageData(0,0,1,1).data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(t){if(null!==this.sprite&&void 0!==this.sprite.parent)return this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this._pendingDrag?(this._dragDistancePass||(this._dragDistancePass=i.Math.distance(t.x,t.y,this.downPoint.x,this.downPoint.y)>=this.dragDistanceThreshold),this._dragDistancePass&&this._dragTimePass&&this.startDrag(t),!0):this.draggable&&this._draggedPointerID===t.id?this.updateDrag(t,!1):this._pointerData[t.id].isOver?this.checkPointerOver(t)?(this._pointerData[t.id].x=t.x-this.sprite.x,this._pointerData[t.id].y=t.y-this.sprite.y,!0):(this._pointerOutHandler(t),!1):void 0:(this._pointerOutHandler(t),!1)},_pointerOverHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];if(!1===i.isOver||t.dirty){var s=!1===i.isOver;i.isOver=!0,i.isOut=!1,i.timeOver=this.game.time.time,i.x=t.x-this.sprite.x,i.y=t.y-this.sprite.y,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),!e&&s&&this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,t),this.sprite.parent&&this.sprite.parent.onChildInputOver&&this.sprite.parent.onChildInputOver.dispatch(this.sprite,t)}}},_pointerOutHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];i.isOver=!1,i.isOut=!0,i.timeOut=this.game.time.time,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="",this._setHandCursor=!1),!e&&this.sprite&&this.sprite.events&&(this.sprite.events.onInputOut$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputOut&&this.sprite.parent.onChildInputOut.dispatch(this.sprite,t))}},_touchedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(!e.isDown&&e.isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,t))return;if(e.isDown=!0,e.isUp=!1,e.timeDown=this.game.time.time,this.downPoint.set(t.x,t.y),t.dirty=!0,this.sprite&&this.sprite.events&&(this.sprite.events.onInputDown$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputDown&&this.sprite.parent.onChildInputDown.dispatch(this.sprite,t),null===this.sprite))return;this.draggable&&!1===this.isDragged&&(0===this.dragTimeThreshold&&0===this.dragDistanceThreshold?this.startDrag(t):(this._pendingDrag=!0,this._dragDistancePass=0===this.dragDistanceThreshold,this.dragTimeThreshold>0?(this._dragTimePass=!1,this.game.time.events.add(this.dragTimeThreshold,this.dragTimeElapsed,this,t)):this._dragTimePass=!0)),this.bringToTop&&this.sprite.bringToTop()}}},dragTimeElapsed:function(t){this._dragTimePass=!0,this._pendingDrag&&this.sprite&&this._dragDistancePass&&this.startDrag(t)},_releasedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(e.isDown&&t.isUp){e.isDown=!1,e.isUp=!0,e.timeUp=this.game.time.time,e.downDuration=e.timeUp-e.timeDown;var i=this.checkPointerOver(t);this.sprite&&this.sprite.events&&(this.dragStopBlocksInputUp&&(!this.dragStopBlocksInputUp||this.draggable&&this.isDragged&&this._draggedPointerID===t.id)||this.sprite.events.onInputUp$dispatch(this.sprite,t,i),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputUp&&this.sprite.parent.onChildInputUp.dispatch(this.sprite,t,i),i&&(i=this.checkPointerOver(t))),e.isOver=i,!i&&this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),t.dirty=!0,this._pendingDrag=!1,this.draggable&&this.isDragged&&this._draggedPointerID===t.id&&this.stopDrag(t)}}},updateDrag:function(t,e){if(void 0===e&&(e=!1),t.isUp)return this.stopDrag(t),!1;var i=this.globalToLocal(t);if(this.sprite.fixedToCamera)var s=this.game.camera.scale.x*i.x+this._dragPoint.x+this.dragOffset.x,n=this.game.camera.scale.y*i.y+this._dragPoint.y+this.dragOffset.y;else var s=i.x+this._dragPoint.x+this.dragOffset.x,n=i.y+this._dragPoint.y+this.dragOffset.y;if(this.sprite.fixedToCamera)this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=s-this.game.camera.x),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=n-this.game.camera.y),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y));else{var r=this.game.camera.x-this._pointerData[t.id].camX,o=this.game.camera.y-this._pointerData[t.id].camY;this.allowHorizontalDrag&&(this.sprite.x=s+r),this.allowVerticalDrag&&(this.sprite.y=n+o),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.x,this.sprite.y))}return this.sprite.events.onDragUpdate.dispatch(this.sprite,t,s,n,this.snapPoint,e),!0},justOver:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOver&&this.overDuration(t)this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.ythis.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.leftthis.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.xthis.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.ythis.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.leftthis.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},i.InputHandler.prototype.constructor=i.InputHandler,i.Gamepad=function(t){this.game=t,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!==navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this)]},i.Gamepad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},start:function(){if(!this._active){this._active=!0;var t=this;this._onGamepadConnected=function(e){return t.onGamepadConnected(e)},this._onGamepadDisconnected=function(e){return t.onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(t){var e=t.gamepad;this._rawPads.push(e),this._gamepads[e.index].connect(e)},onGamepadDisconnected:function(t){var e=t.gamepad;for(var i in this._rawPads)this._rawPads[i].index===e.index&&this._rawPads.splice(i,1);this._gamepads[e.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(this._active){if(navigator.getGamepads)t=navigator.getGamepads();else if(navigator.webkitGetGamepads)t=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var t=navigator.webkitGamepads();if(t){this._rawPads=[];for(var e=!1,i=0;i0&&s>this.deadZone||s<0&&s<-this.deadZone?this.processAxisChange(i,s):this.processAxisChange(i,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(t){var e=!this.connected;this.connected=!0,this.index=t.index,this._rawPad=t,this._buttons=[],this._buttonsLen=t.buttons.length,this._axes=[],this._axesLen=t.axes.length;for(var s=0;sthis.maxHealth&&(this.health=this.maxHealth),this},heal:function(t){return this.alive&&(this.health+=t,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},i.Component.InCamera=function(){},i.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},i.Component.InputEnabled=function(){},i.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(t){t?null===this.input?(this.input=new i.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},i.Component.InWorld=function(){},i.Component.InWorld.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(this.autoCull||this.checkWorldBounds){if(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull)if(this.game.world.camera.view.intersects(this._bounds))this.renderable=!0,this.game.world.camera.totalInView++;else if(this.renderable=!1,this.outOfCameraBoundsKill)return this.kill(),!1;if(this.checkWorldBounds)if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1}return!0},i.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,outOfCameraBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},i.Component.LifeSpan=function(){},i.Component.LifeSpan.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):!(this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0))||(this.kill(),!1)},i.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(t){return void 0===t&&(t=100),this.alive=!0,this.exists=!0,this.visible=!0,"function"==typeof this.setHealth&&this.setHealth(t),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},i.Component.LoadTexture=function(){},i.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(t,e,s){t===i.PENDING_ATLAS?(t=e,e=0):e=e||0,(s||void 0===s)&&this.animations&&this.animations.stop(),this.key=t,this.customRender=!1;var n=this.game.cache,r=!0,o=!this.texture.baseTexture.scaleMode;if(i.RenderTexture&&t instanceof i.RenderTexture)this.key=t.key,this.setTexture(t);else if(i.BitmapData&&t instanceof i.BitmapData)this.customRender=!0,this.setTexture(t.texture),r=n.hasFrameData(t.key,i.Cache.BITMAPDATA)?!this.animations.loadFrameData(n.getFrameData(t.key,i.Cache.BITMAPDATA),e):!this.animations.loadFrameData(t.frameData,0);else if(i.Video&&t instanceof i.Video){this.customRender=!0;var a=t.texture.valid;this.setTexture(t.texture),this.setFrame(t.texture.frame.clone()),t.onChangeSource.add(this.resizeFrame,this),this.texture.valid=a}else if(i.Tilemap&&t instanceof i.TilemapLayer)this.setTexture(PIXI.Texture.fromCanvas(t.canvas));else if(t instanceof PIXI.Texture)this.setTexture(t);else{var h=n.getImage(t,!0);this.key=h.key,this.setTexture(new PIXI.Texture(h.base)),this.texture.baseTexture.skipRender="__default"===t,r=!this.animations.loadFrameData(h.frameData,e)}r&&(this._frame=i.Rectangle.clone(this.texture.frame)),o||(this.texture.baseTexture.scaleMode=1)},setFrame:function(t){this._frame=t,this.texture.frame.x=t.x,this.texture.frame.y=t.y,this.texture.frame.width=t.width,this.texture.frame.height=t.height,this.texture.crop.x=t.x,this.texture.crop.y=t.y,this.texture.crop.width=t.width,this.texture.crop.height=t.height,t.trimmed?(this.texture.trim?(this.texture.trim.x=t.spriteSourceSizeX,this.texture.trim.y=t.spriteSourceSizeY,this.texture.trim.width=t.sourceSizeW,this.texture.trim.height=t.sourceSizeH):this.texture.trim={x:t.spriteSourceSizeX,y:t.spriteSourceSizeY,width:t.sourceSizeW,height:t.sourceSizeH},this.texture.width=t.sourceSizeW,this.texture.height=t.sourceSizeH,this.texture.frame.width=t.sourceSizeW,this.texture.frame.height=t.sourceSizeH):!t.trimmed&&this.texture.trim&&(this.texture.trim=null),t.rotated&&(this.texture.rotated=!0),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(t,e,i){this.texture.frame.resize(e,i),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(t){this.animations.frame=t}},frameName:{get:function(){return this.animations.frameName},set:function(t){this.animations.frameName=t}}},i.Component.Overlap=function(){},i.Component.Overlap.prototype={overlap:function(t){return i.Rectangle.intersects(this.getBounds(),t.getBounds())}},i.Component.PhysicsBody=function(){},i.Component.PhysicsBody.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):this.fresh&&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.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,this.preUpdateChildren(),!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!(!this._exists||!this.parent.exists)||(this.renderOrderID=-1,!1))},i.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},i.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(t){this.position.x=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},i.Component.Reset=function(){},i.Component.Reset.prototype.reset=function(t,e,i){return void 0===i&&(i=1),this.world.set(t,e),this.position.set(t,e),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=i),this.components.PhysicsBody&&this.body&&this.body.reset(t,e,!1,!1),this},i.Component.ScaleMinMax=function(){},i.Component.ScaleMinMax.prototype={transformCallback:null,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(t){this.scaleMin&&(t.athis.scaleMax.x&&(t.a=this.scaleMax.x),t.d>this.scaleMax.y&&(t.d=this.scaleMax.y))},setScaleMinMax:function(t,e,s,n){void 0===e?e=s=n=t:void 0===s&&(s=n=e,e=t),null===t?this.scaleMin=null:this.scaleMin?this.scaleMin.set(t,e):this.scaleMin=new i.Point(t,e),null===s?this.scaleMax=null:this.scaleMax?this.scaleMax.set(s,n):this.scaleMax=new i.Point(s,n),null===this.scaleMin?this.transformCallback=null:(this.transformCallback=this.checkTransform,this.transformCallbackContext=this)}},i.Component.Smoothed=function(){},i.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(t){t?this.texture&&(this.texture.baseTexture.scaleMode=0,this.texture.baseTexture.dirty()):this.texture&&(this.texture.baseTexture.scaleMode=1,this.texture.baseTexture.dirty())}}},i.GameObjectFactory=function(t){this.game=t,this.world=this.game.world},i.GameObjectFactory.prototype={existing:function(t){return this.world.add(t)},weapon:function(t,e,s,n,r){var o=this.game.plugins.add(i.Weapon);return r&&(o.bulletClass=r),o.createBullets(t,e,s,n),o},image:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Image(this.game,t,e,s,n))},sprite:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Sprite(this.game,t,e,s,n))},creature:function(t,e,s,n,r){void 0===r&&(r=this.world);var o=new i.Creature(this.game,t,e,s,n);return r.add(o),o},tween:function(t){return this.game.tweens.create(t)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},physicsGroup:function(t,e,s,n){return new i.Group(this.game,e,s,n,!0,t)},spriteBatch:function(t,e,s){return void 0===t&&(t=null),void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},tileSprite:function(t,e,s,n,r,o,a){return void 0===a&&(a=this.world),a.add(new i.TileSprite(this.game,t,e,s,n,r,o))},rope:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.Rope(this.game,t,e,s,n,r))},text:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Text(this.game,t,e,s,n))},button:function(t,e,s,n,r,o,a,h,l,c){return void 0===c&&(c=this.world),c.add(new i.Button(this.game,t,e,s,n,r,o,a,h,l))},graphics:function(t,e,s){return void 0===s&&(s=this.world),s.add(new i.Graphics(this.game,t,e))},emitter:function(t,e,s){return this.game.particles.add(new i.Particles.Arcade.Emitter(this.game,t,e,s))},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.BitmapText(this.game,t,e,s,n,r))},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},video:function(t,e){return new i.Video(this.game,t,e)},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t},plugin:function(t){return this.game.plugins.add(t)}},i.GameObjectFactory.prototype.constructor=i.GameObjectFactory,i.GameObjectCreator=function(t){this.game=t,this.world=this.game.world},i.GameObjectCreator.prototype={image:function(t,e,s,n){return new i.Image(this.game,t,e,s,n)},sprite:function(t,e,s,n){return new i.Sprite(this.game,t,e,s,n)},tween:function(t){return new i.Tween(t,this.game,this.game.tweens)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},spriteBatch:function(t,e,s){return void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},tileSprite:function(t,e,s,n,r,o){return new i.TileSprite(this.game,t,e,s,n,r,o)},rope:function(t,e,s,n,r){return new i.Rope(this.game,t,e,s,n,r)},text:function(t,e,s,n){return new i.Text(this.game,t,e,s,n)},button:function(t,e,s,n,r,o,a,h,l){return new i.Button(this.game,t,e,s,n,r,o,a,h,l)},graphics:function(t,e){return new i.Graphics(this.game,t,e)},emitter:function(t,e,s){return new i.Particles.Arcade.Emitter(this.game,t,e,s)},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return new i.BitmapText(this.game,t,e,s,n,r,o)},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t}},i.GameObjectCreator.prototype.constructor=i.GameObjectCreator,i.Sprite=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.SPRITE,this.physicsType=i.SPRITE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Sprite.prototype=Object.create(PIXI.Sprite.prototype),i.Sprite.prototype.constructor=i.Sprite,i.Component.Core.install.call(i.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Sprite.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Sprite.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Sprite.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Sprite.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Sprite.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Image=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.IMAGE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Image.prototype=Object.create(PIXI.Sprite.prototype),i.Image.prototype.constructor=i.Image,i.Component.Core.install.call(i.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","ScaleMinMax","Smoothed"]),i.Image.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Image.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Image.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Image.prototype.preUpdate=function(){return!(!this.preUpdateInWorld()||!this.preUpdateLifeSpan())&&this.preUpdateCore()},i.Button=function(t,e,s,n,r,o,a,h,l,c){e=e||0,s=s||0,n=n||null,r=r||null,o=o||this,i.Image.call(this,t,e,s,n,h),this.type=i.BUTTON,this.physicsType=i.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new i.Signal,this.onInputOut=new i.Signal,this.onInputDown=new i.Signal,this.onInputUp=new i.Signal,this.onOverMouseOnly=!0,this.justReleasedPreventsOver=i.PointerMode.CONTACT,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(a,h,l,c),null!==r&&this.onInputUp.add(r,o),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this)},i.Button.prototype=Object.create(i.Image.prototype),i.Button.prototype.constructor=i.Button;return i.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},i.Button.prototype.setStateFrame=function(t,e,i){var s="_on"+t+"Frame";null!==e?(this[s]=e,i&&this.changeStateFrame(t)):this[s]=null},i.Button.prototype.changeStateFrame=function(t){if(this.freezeFrames)return!1;var e=this["_on"+t+"Frame"];return"string"==typeof e?(this.frameName=e,!0):"number"==typeof e&&(this.frame=e,!0)},i.Button.prototype.setFrames=function(t,e,i,s){this.setStateFrame("Over",t,this.input.pointerOver()),this.setStateFrame("Out",e,!this.input.pointerOver()),this.setStateFrame("Down",i,this.input.pointerDown()),this.setStateFrame("Up",s,this.input.pointerUp())},i.Button.prototype.setStateSound=function(t,e,s){var n="on"+t+"Sound",r="on"+t+"SoundMarker";e instanceof i.Sound||e instanceof i.AudioSprite?(this[n]=e,this[r]="string"==typeof s?s:""):(this[n]=null,this[r]="")},i.Button.prototype.playStateSound=function(t){var e=this["on"+t+"Sound"];if(e){var i=this["on"+t+"SoundMarker"];return e.play(i),!0}return!1},i.Button.prototype.setSounds=function(t,e,i,s,n,r,o,a){this.setStateSound("Over",t,e),this.setStateSound("Out",n,r),this.setStateSound("Down",i,s),this.setStateSound("Up",o,a)},i.Button.prototype.setOverSound=function(t,e){this.setStateSound("Over",t,e)},i.Button.prototype.setOutSound=function(t,e){this.setStateSound("Out",t,e)},i.Button.prototype.setDownSound=function(t,e){this.setStateSound("Down",t,e)},i.Button.prototype.setUpSound=function(t,e){this.setStateSound("Up",t,e)},i.Button.prototype.onInputOverHandler=function(t,e){e.justReleased()&&(this.justReleasedPreventsOver&e.pointerMode)===e.pointerMode||(this.changeStateFrame("Over"),this.onOverMouseOnly&&!e.isMouse||(this.playStateSound("Over"),this.onInputOver&&this.onInputOver.dispatch(this,e)))},i.Button.prototype.onInputOutHandler=function(t,e){this.changeStateFrame("Out"),this.playStateSound("Out"),this.onInputOut&&this.onInputOut.dispatch(this,e)},i.Button.prototype.onInputDownHandler=function(t,e){this.changeStateFrame("Down"),this.playStateSound("Down"),this.onInputDown&&this.onInputDown.dispatch(this,e)},i.Button.prototype.onInputUpHandler=function(t,e,i){this.playStateSound("Up"),this.onInputUp&&this.onInputUp.dispatch(this,e,i),this.freezeFrames||(!0===this.forceOut||(this.forceOut&e.pointerMode)===e.pointerMode?this.changeStateFrame("Out"):this.changeStateFrame("Up")||(i?this.changeStateFrame("Over"):this.changeStateFrame("Out")))},i.SpriteBatch=function(t,e,s,n){void 0!==e&&null!==e||(e=t.world),i.Group.call(this,t,e,s,n),this.type=i.SPRITEBATCH,this.fastSpriteBatch=null,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.Group.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||(this.fastSpriteBatch=new PIXI.WebGLFastSpriteBatch(t.gl),this.ready=!0),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n=0&&t<=this.width&&e>=0&&e<=this.height&&(i.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|n<<8|s:this.pixels[e*this.width+t]=s<<24|n<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,s){s||(s=i.Color.createColor());var n=~~(t+e*this.width);return n*=4,s.r=this.data[n],s.g=this.data[++n],s.b=this.data[++n],s.a=this.data[++n],s},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,s,n,r){return i.Color.unpackPixel(this.getPixel32(t,e),s,n,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=i.Color.createColor(),s=0,n=0,r=1,o=!1;1===t?(r=-1,n=this.height):3===t&&(r=-1,s=this.width);do{i.Color.unpackPixel(this.getPixel32(s,n),e),0===t||1===t?++s===this.width&&(s=0,((n+=r)>=this.height||n<=0)&&(o=!0)):2!==t&&3!==t||++n===this.height&&(n=0,((s+=r)>=this.width||s<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=s,e.y=n,e},getBounds:function(t){return void 0===t&&(t=new i.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,s,n,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),t instanceof i.RenderTexture&&(t=t.getCanvas()),this._image=t,t instanceof i.Sprite||t instanceof i.Image||t instanceof i.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof i.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==s&&null!==s||(s=0),n&&(this._size.x=n),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=s),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+s,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var n=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===n.a||0===n.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=n.tx,o=n.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),s&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(n.a,n.b,n.c,n.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,s){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,s),t.type===i.GROUP&&t.exists)this.drawGroup(t,e,s);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var n=0;ne.width&&(n=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,s),this._circle=new i.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,n,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),i.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this},copyBitmapData:function(t,e,i){t.update();for(var s,n=0;n80*s){h=c=t[0],l=u=t[1];for(var g=s;gc&&(c=d),p>u&&(u=p);f=Math.max(c-h,u-l)}return i.EarCut.earcutLinked(o,a,s,h,l,f),a},i.EarCut.linkedList=function(t,e,s,n,r){var o,a,h,l=0;for(o=e,a=s-n;o0)for(o=e;o=e;o-=n)h=i.EarCut.insertNode(o,t[o],t[o+1],h);return h},i.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var s,n=t;do{if(s=!1,n.steiner||!i.EarCut.equals(n,n.next)&&0!==i.EarCut.area(n.prev,n,n.next))n=n.next;else{if(i.EarCut.removeNode(n),(n=e=n.prev)===n.next)return null;s=!0}}while(s||n!==e);return e},i.EarCut.earcutLinked=function(t,e,s,n,r,o,a){if(t){!a&&o&&i.EarCut.indexCurve(t,n,r,o);for(var h,l,c=t;t.prev!==t.next;)if(h=t.prev,l=t.next,o?i.EarCut.isEarHashed(t,n,r,o):i.EarCut.isEar(t))e.push(h.i/s),e.push(t.i/s),e.push(l.i/s),i.EarCut.removeNode(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?(t=i.EarCut.cureLocalIntersections(t,e,s),i.EarCut.earcutLinked(t,e,s,n,r,o,2)):2===a&&i.EarCut.splitEarcut(t,e,s,n,r,o):i.EarCut.earcutLinked(i.EarCut.filterPoints(t),e,s,n,r,o,1);break}}},i.EarCut.isEar=function(t){var e=t.prev,s=t,n=t.next;if(i.EarCut.area(e,s,n)>=0)return!1;for(var r=t.next.next;r!==t.prev;){if(i.EarCut.pointInTriangle(e.x,e.y,s.x,s.y,n.x,n.y,r.x,r.y)&&i.EarCut.area(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},i.EarCut.isEarHashed=function(t,e,s,n){var r=t.prev,o=t,a=t.next;if(i.EarCut.area(r,o,a)>=0)return!1;for(var h=r.xo.x?r.x>a.x?r.x:a.x:o.x>a.x?o.x:a.x,u=r.y>o.y?r.y>a.y?r.y:a.y:o.y>a.y?o.y:a.y,d=i.EarCut.zOrder(h,l,e,s,n),p=i.EarCut.zOrder(c,u,e,s,n),f=t.nextZ;f&&f.z<=p;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=d;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0},i.EarCut.cureLocalIntersections=function(t,e,s){var n=t;do{var r=n.prev,o=n.next.next;i.EarCut.intersects(r,n,n.next,o)&&i.EarCut.locallyInside(r,o)&&i.EarCut.locallyInside(o,r)&&(e.push(r.i/s),e.push(n.i/s),e.push(o.i/s),i.EarCut.removeNode(n),i.EarCut.removeNode(n.next),n=t=o),n=n.next}while(n!==t);return n},i.EarCut.splitEarcut=function(t,e,s,n,r,o){var a=t;do{for(var h=a.next.next;h!==a.prev;){if(a.i!==h.i&&i.EarCut.isValidDiagonal(a,h)){var l=i.EarCut.splitPolygon(a,h);return a=i.EarCut.filterPoints(a,a.next),l=i.EarCut.filterPoints(l,l.next),i.EarCut.earcutLinked(a,e,s,n,r,o),void i.EarCut.earcutLinked(l,e,s,n,r,o)}h=h.next}a=a.next}while(a!==t)},i.EarCut.eliminateHoles=function(t,e,s,n){var r,o,a,h,l,c=[];for(r=0,o=e.length;r=n.next.y){var h=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);h<=r&&h>a&&(a=h,s=n.x=n.x&&n.x>=s.x&&i.EarCut.pointInTriangle(os.x)&&i.EarCut.locallyInside(n,t)&&(s=n,u=l),n=n.next;return s},i.EarCut.indexCurve=function(t,e,s,n){var r=t;do{null===r.z&&(r.z=i.EarCut.zOrder(r.x,r.y,e,s,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,i.EarCut.sortLinked(r)},i.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},i.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},i.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},i.EarCut.isValidDiagonal=function(t,e){return i.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!i.EarCut.intersectsPolygon(t,e)&&i.EarCut.locallyInside(t,e)&&i.EarCut.locallyInside(e,t)&&i.EarCut.middleInside(t,e)},i.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},i.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},i.EarCut.intersects=function(t,e,s,n){return i.EarCut.area(t,e,s)>0!=i.EarCut.area(t,e,n)>0&&i.EarCut.area(s,n,t)>0!=i.EarCut.area(s,n,e)>0},i.EarCut.intersectsPolygon=function(t,e){var s=t;do{if(s.i!==t.i&&s.next.i!==t.i&&s.i!==e.i&&s.next.i!==e.i&&i.EarCut.intersects(s,s.next,t,e))return!0;s=s.next}while(s!==t);return!1},i.EarCut.locallyInside=function(t,e){return i.EarCut.area(t.prev,t,t.next)<0?i.EarCut.area(t,e,t.next)>=0&&i.EarCut.area(t,t.prev,e)>=0:i.EarCut.area(t,e,t.prev)<0||i.EarCut.area(t,t.next,e)<0},i.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},i.EarCut.splitPolygon=function(t,e){var s=new i.EarCut.Node(t.i,t.x,t.y),n=new i.EarCut.Node(e.i,e.x,e.y),r=t.next,o=e.prev;return t.next=e,e.prev=t,s.next=r,r.prev=s,n.next=s,s.prev=n,o.next=n,n.prev=o,n},i.EarCut.insertNode=function(t,e,s,n){var r=new i.EarCut.Node(t,e,s);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r},i.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},i.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var s,n=e.gl,r=e.projection,o=e.offset,a=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,n);var h=t._webGL[n.id];if(h)for(var l=0;l=PIXI.WebGLGraphics.stencilBufferLimit&&(a.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit?(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildPoly(a,o)||(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))),a.lineWidth>0&&(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildLine(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,0),a.type===i.RECTANGLE?PIXI.WebGLGraphics.buildRectangle(a,o):a.type===i.CIRCLE||a.type===i.ELLIPSE?PIXI.WebGLGraphics.buildCircle(a,o):a.type===i.ROUNDEDRECTANGLE&&PIXI.WebGLGraphics.buildRoundedRectangle(a,o)),s.lastIndex++}for(n=0;n19600?(_=y-x,w=v-b,_/=R=Math.sqrt(_*_+w*w),w/=R,_*=F,w*=F,L.push(p-_,f-w),L.push(G,N,X,U),L.push(p+_,f+w),L.push(G,N,X,U),L.push(p-_,f-w),L.push(G,N,X,U),O++):(L.push(l,c),L.push(G,N,X,U),L.push(p-(l-p),f-(c-f)),L.push(G,N,X,U));for(u=n[2*(I-2)],d=n[2*(I-2)+1],p=n[2*(I-1)],y=-(d-(f=n[2*(I-1)+1])),v=u-p,y/=R=Math.sqrt(y*y+v*v),v/=R,y*=F,v*=F,L.push(p-y,f-v),L.push(G,N,X,U),L.push(p+y,f+v),L.push(G,N,X,U),B.push(k),s=0;sh?r:h,l=oc?o:c;s.push(a,l,h,l,h,c,a,c);var d=s.length/2;for(u=0;uS?S:C,e.beginPath(),e.moveTo(_,w+C),e.lineTo(_,w+P-C),e.quadraticCurveTo(_,w+P,_+C,w+P),e.lineTo(_+T-C,w+P),e.quadraticCurveTo(_+T,w+P,_+T,w+P-C),e.lineTo(_+T,w+C),e.quadraticCurveTo(_+T,w,_+T-C,w),e.lineTo(_+C,w),e.quadraticCurveTo(_,w,_,w+C),e.closePath(),(r.fillColor||0===r.fillColor)&&(e.globalAlpha=r.fillAlpha*s,e.fillStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.fill()),r.lineWidth&&(e.globalAlpha=r.lineAlpha*s,e.strokeStyle="#"+("00000"+(0|h).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var s=t.graphicsData.length;if(0!==s){e.beginPath();for(var n=0;nP?P:T,e.moveTo(x,b+T),e.lineTo(x,b+w-T),e.quadraticCurveTo(x,b+w,x+T,b+w),e.lineTo(x+_-T,b+w),e.quadraticCurveTo(x+_,b+w,x+_,b+w-T),e.lineTo(x+_,b+T),e.quadraticCurveTo(x+_,b,x+_-T,b),e.lineTo(x+T,b),e.quadraticCurveTo(x,b,x,b+T),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},i.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},i.GraphicsData.prototype.constructor=i.GraphicsData,i.GraphicsData.prototype.clone=function(){return new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},i.Graphics=function(t,e,s){void 0===e&&(e=0),void 0===s&&(s=0),this.type=i.GRAPHICS,this.physicsType=i.SPRITE,this.anchor=new i.Point,PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new i.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1,i.Component.Core.init.call(this,t,e,s,"",null)},i.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Graphics.prototype.constructor=i.Graphics,i.Component.Core.install.call(i.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),i.Graphics.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Graphics.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Graphics.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Graphics.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Graphics.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Graphics.prototype.postUpdate=function(){i.Component.PhysicsBody.postUpdate.call(this),i.Component.FixedToCamera.postUpdate.call(this),this._boundsDirty&&(this.updateLocalBounds(),this._boundsDirty=!1);for(var t=0;t0&&this.drawPolygon(s)}else this.drawPolygon(s)},i.Graphics.prototype.drawTriangles=function(t,e,s){void 0===s&&(s=!1);var n,r=new i.Point,o=new i.Point,a=new i.Point,h=[];if(e)if(t[0]instanceof i.Point)for(n=0;nc*a)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var x=d+s+p*(v+y*v),b=Math.cos(x),_=-Math.sin(x);u.push((f*b+g*_)*i+t,(f*-_+g*b)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},i.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},i.Graphics.prototype.drawRect=function(t,e,s,n){return this.drawShape(new i.Rectangle(t,e,s,n)),this},i.Graphics.prototype.drawRoundedRect=function(t,e,s,n,r){return this.drawShape(new i.RoundedRectangle(t,e,s,n,r)),this},i.Graphics.prototype.drawCircle=function(t,e,s){return this.drawShape(new i.Circle(t,e,s)),this},i.Graphics.prototype.drawEllipse=function(t,e,s,n){return this.drawShape(new i.Ellipse(t,e,s,n)),this},i.Graphics.prototype.drawPolygon=function(t){t instanceof i.Polygon&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var s=0;sw?m:w,w=v>w?v:w,w=b>w?b:w,T=y>T?y:T,T=x>T?x:T,T=_>T?_:T,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=C,this._bounds.height=T-C,this._currentBounds=this._bounds,this._currentBounds},i.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;ee?a+l:e,s=hn?h+c:n;else if(p===i.CIRCLE)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else if(p===i.ELLIPSE)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else{o=r.points;for(var g=0;ge?a+f:e,s=h-fn?h+f:n}}else t=0,e=0,s=0,n=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=s-m,this._localBounds.height=n-s+2*m},i.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},i.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},i.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},i.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof i.Polygon&&(t=t.clone()).flatten();var e=new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===i.POLYGON&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(i.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),i.RenderTexture=function(t,e,s,n,r,o,a,h){if(void 0===e&&(e=100),void 0===s&&(s=100),void 0===n&&(n=""),void 0===r&&(r=i.scaleModes.DEFAULT),void 0===o&&(o=1),void 0===a&&(a=PIXI.defaultRenderer),void 0===h&&(h=0),this.game=t,this.key=n,this.type=i.RENDERTEXTURE,this._tempMatrix=new i.Matrix,this.width=e,this.height=s,this.resolution=o,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=this.frame.clone(),this.baseTexture=new PIXI.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=r,this.baseTexture.hasLoaded=!0,PIXI.Texture.call(this,this.baseTexture,this.frame.clone()),this.renderer=a,this.renderer.type===i.WEBGL){var l=this.renderer.gl;this.baseTexture.textureIndex=h,this.baseTexture._dirty[l.id]=!1,this.textureBuffer=new PIXI.FilterTexture(l,this.width,this.height,this.baseTexture.scaleMode,h),this.baseTexture._glTextures[l.id]=this.textureBuffer.texture,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.textureBuffer=new PIXI.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new i.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(PIXI.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.renderXY=function(t,e,s,n){t.updateTransform(),this._tempMatrix.copyFrom(t.worldTransform),this._tempMatrix.tx=e,this._tempMatrix.ty=s,this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.renderRawXY=function(t,e,s,n){this._tempMatrix.identity().translate(e,s),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.render=function(t,e,s){void 0===e||null===e?this._tempMatrix.copyFrom(t.worldTransform):this._tempMatrix.copyFrom(e),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,s):this._renderCanvas(t,this._tempMatrix,s)},i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype._renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n-1&&this.characterLimitSize0&&this.style.maxLines0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(e[a]):l+=this.context.measureText(e[a]).width,this.style.wordWrap&&(l-=this.context.measureText(" ").width)}else{var h=e[a].split(/(?:\t)/),l=this.padding.x+this.style.strokeThickness;if(Array.isArray(i))for(var c=0,u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.measureLine(h[u]):Math.ceil(this.context.measureText(h[u]).width),u>0&&(c+=i[u-1]),l=c+d}else for(u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(h[u]):l+=Math.ceil(this.context.measureText(h[u]).width),l+=this.game.math.snapToCeil(l,i)-l}s[a]=Math.ceil(l),n=Math.max(n,s[a])}this.canvas.width=n*this._res;var p=r.fontSize+this.style.strokeThickness+this.padding.y,f=p*o,g=this._lineSpacing;g<0&&Math.abs(g)>p&&(g=-p),0!==g&&(f+=g>0?g*e.length:g*(e.length-1)),this.canvas.height=f*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var m,y;for(this._charCount=0,a=0;a0&&(y+=g*a),"right"===this.style.align?m+=n-s[a]:"center"===this.style.align&&(m+=(n-s[a])/2),this.autoRound&&(m=Math.round(m),y=Math.round(y)),this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.updateLine(e[a],m,y):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===i?this.context.strokeText(e[a],m,y):this.renderTabLine(e[a],m,y,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===i?this.context.fillText(e[a],m,y):this.renderTabLine(e[a],m,y,!0)));this.updateTexture(),this.dirty=!1},i.Text.prototype.renderTabLine=function(t,e,i,s){var n=t.split(/(?:\t)/),r=this.style.tabs,o=0;if(Array.isArray(r))for(var a=0,h=0;h0&&(a+=r[h-1]),o=e+a,s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i);else for(h=0;h0||this.fontStyles.length>0){var n=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(n.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(n.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(n)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill)),e+=this.context.measureText(s).width,this._charCount++}return Math.ceil(e)},i.Text.prototype.updateLine=function(t,e,i){for(var s=0;s0||this.fontStyles.length>0){var r=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(r.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(r.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(r)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(n,e,i)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(n,e,i)),e+=this.context.measureText(n).width,this._charCount++}},i.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},i.Text.prototype.clearFontValues=function(){return this.fontStyles=[],this.fontWeights=[],this.dirty=!0,this},i.Text.prototype.addColor=function(t,e){return this.colors[e]=t,this.dirty=!0,this},i.Text.prototype.addStrokeColor=function(t,e){return this.strokeColors[e]=t,this.dirty=!0,this},i.Text.prototype.addFontStyle=function(t,e){return this.fontStyles[e]=t,this.dirty=!0,this},i.Text.prototype.addFontWeight=function(t,e){return this.fontWeights[e]=t,this.dirty=!0,this},i.Text.prototype.precalculateWordWrap=function(t){return this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font,this.runWordWrap(t).split(/(?:\r\n|\r|\n)/)},i.Text.prototype.runWordWrap=function(t){return this.useAdvancedWrap?this.advancedWordWrap(t):this.basicWordWrap(t)},i.Text.prototype.advancedWordWrap=function(t){for(var e=this.context,i=this.style.wordWrapWidth,s="",n=t.replace(/ +/gi," ").split(/\r?\n/gi),r=n.length,o=0;ol){if(0===u){for(var g=p;g.length&&(g=g.slice(0,-1),!((f=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var m=d.substr(g.length);c[u]=m,h+=g}var y=c[u].length?u:u+1,v=c.slice(y).join(" ").replace(/[ \n]*$/gi,"");n[o+1]=v+" "+(n[o+1]||""),r=n.length;break}h+=p,l-=f}s+=h.replace(/[ \n]*$/gi,"")+"\n"}}return s=s.replace(/[\s|\n]*$/gi,"")},i.Text.prototype.basicWordWrap=function(t){for(var e="",i=t.split("\n"),s=0;sn?(o>0&&(e+="\n"),e+=r[o]+" ",n=this.style.wordWrapWidth-a):(n-=h,e+=r[o]+" ")}ss&&(this.style.wordWrapWidth=s)),this.updateTexture(),this},i.Text.prototype.updateTexture=function(){var t=this.texture.baseTexture,e=this.texture.crop,i=this.texture.frame,s=this.canvas.width,n=this.canvas.height;if(t.width=s,t.height=n,e.width=s,e.height=n,i.width=s,i.height=n,this.texture.width=s,this.texture.height=n,this._width=s,this._height=n,this.textBounds){var r=this.textBounds.x,o=this.textBounds.y;"right"===this.style.boundsAlignH?r+=this.textBounds.width-this.canvas.width/this.resolution:"center"===this.style.boundsAlignH&&(r+=this.textBounds.halfWidth-this.canvas.width/this.resolution/2),"bottom"===this.style.boundsAlignV?o+=this.textBounds.height-this.canvas.height/this.resolution:"middle"===this.style.boundsAlignV&&(o+=this.textBounds.halfHeight-this.canvas.height/this.resolution/2),this.pivot.x=-r,this.pivot.y=-o}this.renderable=0!==s&&0!==n,this.texture.requiresReTint=!0,this.texture.baseTexture.dirty()},i.Text.prototype._renderWebGL=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.Text.prototype._renderCanvas=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.Text.prototype.determineFontProperties=function(t){var e=i.Text.fontPropertiesCache[t];if(!e){e={};var s=i.Text.fontPropertiesCanvas,n=i.Text.fontPropertiesContext;n.font=t;var r=Math.ceil(n.measureText("|MÉq").width),o=Math.ceil(n.measureText("|MÉq").width),a=2*o;if(o=1.4*o|0,s.width=r,s.height=a,n.fillStyle="#f00",n.fillRect(0,0,r,a),n.font=t,n.textBaseline="alphabetic",n.fillStyle="#000",n.fillText("|MÉq",0,o),!n.getImageData(0,0,r,a))return e.ascent=o,e.descent=o+6,e.fontSize=e.ascent+e.descent,i.Text.fontPropertiesCache[t]=e,e;var h,l,c=n.getImageData(0,0,r,a).data,u=c.length,d=4*r,p=0,f=!1;for(h=0;ho;h--){for(l=0;l0?this._maxWidth:null,l=[],c=0;c=h&&r>-1)return{width:o||n,text:i.substr(0,c-(c-r)),end:!1,chars:l};n+=(p.xAdvance+g)*e,l.push(s+(p.xOffset+g)*e),s+=(p.xAdvance+g)*e,a=d}return{width:n,text:i,end:u,chars:l}},i.BitmapText.prototype.cleanText=function(t,e){void 0===e&&(e="");var i=this._data.font;if(!i)return"";for(var s=/\r\n|\n\r|\n|\r/g,n=t.replace(s,"\n").split("\n"),r=0;rthis.textWidth&&(this.textWidth=c.width),n+=t.lineHeight*i,e=e.substr(c.text.length+1)}while(!1===c.end);this.textHeight=n;for(var r=0,o=0,a=this.textWidth*this.anchor.x,h=this.textHeight*this.anchor.y,l=0;l0&&(this._fontSize=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"smoothed",{get:function(){return!this._data.base.scaleMode},set:function(t){this._data.base.scaleMode=t?0:1,this._data.base.dirty()}}),i.RetroFont=function(t,e,s,n,r,o,a,h,l,c){if(!t.cache.checkImageKey(e))return!1;void 0!==o&&null!==o||(o=t.cache.getImage(e).width/s),this.characterWidth=s,this.characterHeight=n,this.characterSpacingX=a||0,this.characterSpacingY=h||0,this.characterPerRow=o,this.offsetX=l||0,this.offsetY=c||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=t.cache.getImage(e),this._text="",this.grabData=[],this.frameData=new i.FrameData;for(var u=this.offsetX,d=this.offsetY,p=0,f=0;f?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",i.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",i.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",i.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",i.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",i.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",i.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",i.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",i.RetroFont.prototype.setFixedWidth=function(t,e){void 0===e&&(e="left"),this.fixedWidth=t,this.align=e},i.RetroFont.prototype.setText=function(t,e,i,s,n,r){this.multiLine=e||!1,this.customSpacingX=i||0,this.customSpacingY=s||0,this.align=n||"left",this.autoUpperCase=!r,t.length>0&&(this.text=t)},i.RetroFont.prototype.buildRetroFontText=function(){var t=0,e=0;if(this.clear(),this.multiLine){var s=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var n=0;n0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),t=0,this.align===i.RetroFont.ALIGN_RIGHT?t=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===i.RetroFont.ALIGN_CENTER&&(t=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(this._text,t,0,this.customSpacingX);this.requiresReTint=!0},i.RetroFont.prototype.pasteLine=function(t,e,i,s){for(var n=0;n=0&&(this.stamp.frame=this.grabData[t.charCodeAt(n)],this.renderXY(this.stamp,e,i,!1),(e+=this.characterWidth+s)>this.width))break},i.RetroFont.prototype.getLongestLine=function(){var t=0;if(this._text.length>0)for(var e=this._text.split("\n"),i=0;it&&(t=e[i].length);return t},i.RetroFont.prototype.removeUnsupportedCharacters=function(t){for(var e="",i=0;i=0||!t&&"\n"===s)&&(e=e.concat(s))}return e},i.RetroFont.prototype.updateOffset=function(t,e){if(this.offsetX!==t||this.offsetY!==e){for(var i=t-this.offsetX,s=e-this.offsetY,n=this.game.cache.getFrameData(this.stamp.key).getFrames(),r=n.length;r--;)n[r].x+=i,n[r].y+=s;this.buildRetroFontText()}},Object.defineProperty(i.RetroFont.prototype,"text",{get:function(){return this._text},set:function(t){var e;(e=this.autoUpperCase?t.toUpperCase():t)!==this._text&&(this._text=e,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(i.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(t){this.stamp.smoothed=t,this.buildRetroFontText()}}),i.Rope=function(t,e,s,n,r,o){this.points=o||[],this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.ROPE,PIXI.DisplayObjectContainer.call(this),this.texture=i.Cache.DEFAULT,this.uvs=new Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new Float32Array([0,0,100,0,100,100,0,100]),this.colors=new Float32Array([1,1,1,1]),this.indices=new Uint16Array([0,1,2,3]),o&&(this.vertices=new Float32Array(4*o.length),this.uvs=new Float32Array(4*o.length),this.colors=new Float32Array(2*o.length),this.indices=new Uint16Array(2*o.length)),this.dirty=!0,this.canvasPadding=0,this.drawMode=i.Rope.TRIANGLE_STRIP,i.Component.Core.init.call(this,t,e,s,n,r),this.refresh()},i.Rope.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Rope.prototype.constructor=i.Rope,i.Component.Core.install.call(i.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Rope.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Rope.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Rope.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Rope.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Rope.TRIANGLE_STRIP=0,i.Rope.TRIANGLES=1,i.Rope.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},i.Rope.prototype.reset=function(t,e){return i.Component.Reset.prototype.reset.call(this,t,e),this},i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=this.indices,s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o=t.length,a=1;a1&&1,o=Math.sqrt(s.x*s.x+s.y*s.y),a=this.texture.height/2,s.x/=o,s.y/=o,s.x*=a,s.y*=a,h[r]=n.x+s.x,h[r+1]=n.y+s.y,h[r+2]=n.x-s.x,h[r+3]=n.y-s.y,i=n;PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.Rope.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Rope.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Rope.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Rope.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Rope.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Rope.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Rope.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n0){var _=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,T=(l+c+u)/3,P=(d+p+f)/3,C=l-T,S=d-P,A=Math.sqrt(C*C+S*S);l=T+C/A*(A+_),d=P+S/A*(A+w),S=p-P,c=T+(C=c-T)/(A=Math.sqrt(C*C+S*S))*(A+_),p=P+S/A*(A+w),S=f-P,u=T+(C=u-T)/(A=Math.sqrt(C*C+S*S))*(A+_),f=P+S/A*(A+w)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*x+v*y+m*b-x*y-v*m-g*b,M=l*x+v*u+c*b-x*u-v*c-l*b,R=g*c+l*y+m*u-c*y-l*m-g*u,L=g*x*u+v*c*y+l*m*b-l*x*y-v*m*u-g*c*b,B=d*x+v*f+p*b-x*f-v*p-d*b,I=g*p+d*y+m*f-p*y-d*m-g*f,O=g*x*f+v*p*y+d*m*b-d*x*y-v*m*f-g*p*b;t.transform(M/E,B/E,R/E,I/E,L/E,O/E),t.drawImage(o,0,0),t.restore()},i.Rope.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;nh?m:h,l=y>l?y:l}if(c===-1/0||l===1/0)return PIXI.EmptyRectangle;var v=this._bounds;return v.x=c,v.width=h-c,v.y=u,v.height=l-u,this._currentBounds=v,v},Object.defineProperty(i.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(t){t&&"function"==typeof t?(this._hasUpdateAnimation=!0,this._updateAnimation=t):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(i.Rope.prototype,"segments",{get:function(){for(var t,e,s,n,r,o,a,h,l=[],c=0;c(_=y>(_=g>(_=p>_?p:_)?g:_)?y:_)?x:_,w=b>(w=v>(w=m>(w=f>w?f:w)?m:w)?v:w)?b:w;var C=this._bounds;return C.x=T,C.width=_-T,C.y=P,C.height=w-P,this._currentBounds=C,C},Object.defineProperty(i.TileSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TileSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var e=parseInt(RegExp.$1,10),i=parseInt(RegExp.$2,10);(10===e&&i>=11||e>10)&&(s.dolby=!0)}}catch(t){}}(),function(){var t=document.createElement("video");try{!!t.canPlayType&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(s.oggVideo=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.h264Video=!0,s.mp4Video=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(s.webmVideo=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(s.vp9Video=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.hlsVideo=!0))}catch(t){}}(),function(){var t,e=document.createElement("p"),i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var n in i)void 0!==e.style[n]&&(e.style[n]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(i[n]));document.body.removeChild(e),s.css3D=void 0!==t&&t.length>0&&"none"!==t}(),s.pixelRatio=window.devicePixelRatio||1,s.iPhone=-1!==navigator.userAgent.toLowerCase().indexOf("iphone"),s.iPhone4=2===s.pixelRatio&&s.iPhone,s.iPad=-1!==navigator.userAgent.toLowerCase().indexOf("ipad"),"undefined"!=typeof Int8Array?s.typedArray=!0:s.typedArray=!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(s.littleEndian=t(),s.LITTLE_ENDIAN=s.littleEndian),s.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==s.littleEndian&&e(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(s.vibration=!0),function(){s.canvas=!!window.CanvasRenderingContext2D||s.cocoonJS;try{s.localStorage=!!localStorage.getItem}catch(t){s.localStorage=!1}s.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),s.fileSystem=!!window.requestFileSystem,s.webGL=!!window.WebGLRenderingContext,s.worker=!!window.Worker,s.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,s.quirksMode="CSS1Compat"!==document.compatMode,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,s.getUserMedia=s.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,s.firefox&&s.firefoxVersion<21&&(s.getUserMedia=!1),!s.iOS&&(s.ie||s.firefox||s.chrome)&&(s.canvasBitBltShift=!0),(s.safari||s.mobileSafari)&&(s.canvasBitBltShift=!1)}(),function(){var t=i.CanvasPool.create(this,6,1),e=t.getContext("2d");e.fillStyle="rgba(10, 20, 30, 0.5)",e.fillRect(0,0,1,1);var n=e.getImageData(0,0,1,1);if(n){e.putImageData(n,1,0);var r=e.getImageData(1,0,1,1);s.canHandleAlpha=r.data[0]===n.data[0]&&r.data[1]===n.data[1]&&r.data[2]===n.data[2]&&r.data[3]===n.data[3]}e.globalCompositeOperation="multiply",s.canUseMultiply="multiply"===e.globalCompositeOperation,i.CanvasPool.removeByCanvas(t),PIXI.CanvasTinter.tintMethod=s.canUseMultiply?PIXI.CanvasTinter.tintWithMultiply:PIXI.CanvasTinter.tintWithPerPixel}(),function(){for(var t=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],e=document.createElement("div"),i=0;i=1)&&(s.touch=!0),(window.PointerEvent||window.MSPointerEvent||window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(s.mspointer=!0),s.cocoonJS||("onwheel"in window||s.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":s.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"))},i.Device.canPlayAudio=function(t){return!("mp3"!==t||!this.mp3)||(!("ogg"!==t||!this.ogg&&!this.opus)||(!("m4a"!==t||!this.m4a)||(!("opus"!==t||!this.opus)||(!("wav"!==t||!this.wav)||(!("webm"!==t||!this.webm)||!("mp4"!==t||!this.dolby))))))},i.Device.canPlayVideo=function(t){return!("webm"!==t||!this.webmVideo&&!this.vp9Video)||(!("mp4"!==t||!this.mp4Video&&!this.h264Video)||(!("ogg"!==t&&"ogv"!==t||!this.oggVideo)||!("mpeg"!==t||!this.hlsVideo)))},i.Device.needsTouchUnlock=function(){return!!(!this.cocoonJS&&(this.iOS||this.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)},i.Device.isAndroidStockBrowser=function(){var t=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return t&&t[1]<537},i.Canvas={create:function(t,e,s,n,r){e=e||256,s=s||256;var o=r?document.createElement("canvas"):i.CanvasPool.create(t,e,s);return"string"==typeof n&&""!==n&&(o.id=n),o.width=e,o.height=s,o.style.display="block",o},setBackgroundColor:function(t,e){return e=e||"rgb(0,0,0)",t.style.backgroundColor=e,t},setTouchAction:function(t,e){return e=e||"none",t.style.msTouchAction=e,t.style["ms-touch-action"]=e,t.style["touch-action"]=e,t},setUserSelect:function(t,e){return e=e||"none",t.style["-webkit-touch-callout"]=e,t.style["-webkit-user-select"]=e,t.style["-khtml-user-select"]=e,t.style["-moz-user-select"]=e,t.style["-ms-user-select"]=e,t.style["user-select"]=e,t.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",t},addToDOM:function(t,e,i){var s;return void 0===i&&(i=!0),e&&("string"==typeof e?s=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(s=e)),s||(s=document.body),i&&s.style&&(s.style.overflow="hidden"),s.appendChild(t),t},removeFromDOM:function(t){t.parentNode&&t.parentNode.removeChild(t)},setTransform:function(t,e,i,s,n,r,o){return t.setTransform(s,r,o,n,e,i),t},setSmoothingEnabled:function(t,e){var s=i.Canvas.getSmoothingPrefix(t);return s&&(t[s]=e),t},getSmoothingPrefix:function(t){var e=["i","webkitI","msI","mozI","oI"];for(var i in e){var s=e[i]+"mageSmoothingEnabled";if(s in t)return s}return null},getSmoothingEnabled:function(t){var e=i.Canvas.getSmoothingPrefix(t);if(e)return t[e]},setImageRenderingCrisp:function(t){for(var e=["-webkit-optimize-contrast","-moz-crisp-edges","crisp-edges","pixelated"],i=0;i0&&0==(t&t-1))return t;for(var e=1;e0&&0==(t&t-1)&&e>0&&0==(e&e-1)},random:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return Math.random()*(e-t)+t},between:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t},fuzzyEqual:function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)e-i},fuzzyCeil:function(t,e){return void 0===e&&(e=1e-4),Math.ceil(t-e)},fuzzyFloor:function(t,e){return void 0===e&&(e=1e-4),Math.floor(t+e)},average:function(){for(var t=0,e=arguments.length,i=0;i=i.Math.PI2-s?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=s:e=0?t:t+2*Math.PI},maxAdd:function(t,e,i){return Math.min(t+e,i)},minSub:function(t,e,i){return Math.max(t-e,i)},wrap:function(t,e,i){var s=i-e;if(s<=0)return 0;var n=(t-e)%s;return n<0&&(n+=s),n+e},wrapValue:function(t,e,i){return t=Math.abs(t),e=Math.abs(e),i=Math.abs(i),(t+e)%i},isOdd:function(t){return!!(1&t)},isEven:function(t){return!(1&t)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;et[i]&&(i=e);return t[i]},minProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;ie[s][t]&&(s=i);return e[s][t]},wrapAngle:function(t,e){return e?this.wrap(t,-Math.PI,Math.PI):this.wrap(t,-180,180)},linearInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return e<0?this.linear(t[0],t[1],s):e>1?this.linear(t[i],t[i-1],i-s):this.linear(t[n],t[n+1>i?i:n+1],s-n)},bezierInterpolation:function(t,e){for(var i=0,s=t.length-1,n=0;n<=s;n++)i+=Math.pow(1-e,s-n)*Math.pow(e,n)*t[n]*this.bernstein(s,n);return i},catmullRomInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return t[0]===t[i]?(e<0&&(n=Math.floor(s=i*(1+e))),this.catmullRom(t[(n-1+i)%i],t[n],t[(n+1)%i],t[(n+2)%i],s-n)):e<0?t[0]-(this.catmullRom(t[0],t[0],t[1],t[1],-s)-t[0]):e>1?t[i]-(this.catmullRom(t[i],t[i],t[i-1],t[i-1],s-i)-t[i]):this.catmullRom(t[n?n-1:0],t[n],t[i0?Math.ceil(t):Math.floor(t)},sinCosGenerator:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1);for(var n=e,r=i,o=s*Math.PI/t,a=[],h=[],l=0;l0?1:0},percent:function(t,e,i){return void 0===i&&(i=0),t>e||i>e?1:tt?0:(t-i)/e}},i.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},i.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e>>0,s=(e*=s)>>>0,s+=4294967296*(e-=s);return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},i.RandomDataGenerator.prototype.constructor=i.RandomDataGenerator,i.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},i.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new i.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new i.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new i.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new i.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null==this.nodes[0]||-1===(e=this.getIndex(t))){if(this.objects.push(t),this.objects.length>this.maxObjects&&this.levelthis.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.ythis.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof i.Rectangle)var e=this.objects,s=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,s=this.getIndex(t.body)}return this.nodes[0]&&(e=-1!==s?e.concat(this.nodes[s].retrieve(t)):(e=(e=(e=e.concat(this.nodes[0].retrieve(t))).concat(this.nodes[1].retrieve(t))).concat(this.nodes[2].retrieve(t))).concat(this.nodes[3].retrieve(t))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},i.QuadTree.prototype.constructor=i.QuadTree,i.Net=function(t){this.game=t},i.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},i.Net.prototype.constructor=i.Net,i.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:i.Easing.Power0,Power1:i.Easing.Power1,Power2:i.Easing.Power2,Power3:i.Easing.Power3,Power4:i.Easing.Power4,Linear:i.Easing.Linear.None,Quad:i.Easing.Quadratic.Out,Cubic:i.Easing.Cubic.Out,Quart:i.Easing.Quartic.Out,Quint:i.Easing.Quintic.Out,Sine:i.Easing.Sinusoidal.Out,Expo:i.Easing.Exponential.Out,Circ:i.Easing.Circular.Out,Elastic:i.Easing.Elastic.Out,Back:i.Easing.Back.Out,Bounce:i.Easing.Bounce.Out,"Quad.easeIn":i.Easing.Quadratic.In,"Cubic.easeIn":i.Easing.Cubic.In,"Quart.easeIn":i.Easing.Quartic.In,"Quint.easeIn":i.Easing.Quintic.In,"Sine.easeIn":i.Easing.Sinusoidal.In,"Expo.easeIn":i.Easing.Exponential.In,"Circ.easeIn":i.Easing.Circular.In,"Elastic.easeIn":i.Easing.Elastic.In,"Back.easeIn":i.Easing.Back.In,"Bounce.easeIn":i.Easing.Bounce.In,"Quad.easeOut":i.Easing.Quadratic.Out,"Cubic.easeOut":i.Easing.Cubic.Out,"Quart.easeOut":i.Easing.Quartic.Out,"Quint.easeOut":i.Easing.Quintic.Out,"Sine.easeOut":i.Easing.Sinusoidal.Out,"Expo.easeOut":i.Easing.Exponential.Out,"Circ.easeOut":i.Easing.Circular.Out,"Elastic.easeOut":i.Easing.Elastic.Out,"Back.easeOut":i.Easing.Back.Out,"Bounce.easeOut":i.Easing.Bounce.Out,"Quad.easeInOut":i.Easing.Quadratic.InOut,"Cubic.easeInOut":i.Easing.Cubic.InOut,"Quart.easeInOut":i.Easing.Quartic.InOut,"Quint.easeInOut":i.Easing.Quintic.InOut,"Sine.easeInOut":i.Easing.Sinusoidal.InOut,"Expo.easeInOut":i.Easing.Exponential.InOut,"Circ.easeInOut":i.Easing.Circular.InOut,"Elastic.easeInOut":i.Easing.Elastic.InOut,"Back.easeInOut":i.Easing.Back.InOut,"Bounce.easeInOut":i.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},i.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t,e){return e||(e=!1),this._tweens.some(function(i){return i.target===t&&(!e||i.isRunning&&!i.pendingDelete)})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},i.TweenManager.prototype.constructor=i.TweenManager,i.Tween=function(t,e,s){this.game=e,this.target=t,this.manager=s,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new i.Signal,this.onLoop=new i.Signal,this.onRepeat=new i.Signal,this.onChildComplete=new i.Signal,this.onComplete=new i.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=s.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},i.Tween.updateColor=function(t){i.Color.updateColor(t.target)},i.Tween.prototype={to:function(t,e,s,n,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).to(t,e,s,r,o,a)),n&&this.start(),this)},from:function(t,e,s,n,r,o,a){return void 0===e&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).from(t,e,s,r,o,a)),n&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),this.pendingDelete)return console.warn("Phaser.Tween.start cannot be called after Tween.stop"),this;if(null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(i=0;ithis.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(s=0;s0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t=this.startTime))return i.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var s in this.vEnd){var n=this.vStart[s],r=this.vEnd[s];Array.isArray(r)?this.parent.target[s]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[s]=n+(r-n)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():i.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction.call(this.interpolationContext,a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,i.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return i.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,i.TweenData.LOOPED}},i.TweenData.prototype.constructor=i.TweenData,i.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-i.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*i.Easing.Bounce.In(2*t):.5*i.Easing.Bounce.Out(2*t-1)+.5}}},i.Easing.Default=i.Easing.Linear.None,i.Easing.Power0=i.Easing.Linear.None,i.Easing.Power1=i.Easing.Quadratic.Out,i.Easing.Power2=i.Easing.Cubic.Out,i.Easing.Power3=i.Easing.Quartic.Out,i.Easing.Power4=i.Easing.Quintic.Out,i.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.updates=0,this.renders=0,this.fps=0,this.ups=0,this.rps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new i.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},i.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new i.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3){var t=this.now-this._timeLastSecond;this.fps=Math.round(1e3*this.frames/t),this.ups=Math.round(1e3*this.updates/t),this.rps=Math.round(1e3*this.renders/t),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0,this.updates=0,this.renders=0}},countUpdate:function(){this.advancedTiming&&this.updates++},countRender:function(){this.advancedTiming&&this.renders++},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(i.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),i.Time.prototype.constructor=i.Time,i.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new i.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},i.Timer.MINUTE=6e4,i.Timer.SECOND=1e3,i.Timer.HALF=500,i.Timer.QUARTER=250,i.Timer.prototype={create:function(t,e,s,n,r,o){var a=t=Math.round(t);0===this._now?a+=this.game.time.time:a+=this._now;var h=new i.TimerEvent(this,t,a,s,e,n,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.ticke.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i=e.tick)||e.pendingDelete)break;this._newTick=this._now+e.delay-(this._now-e.tick),this._newTick<0&&(this._newTick=this._now+e.delay),!0===e.loop?(e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):e.repeatCount>0?(e.repeatCount--,e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):(this._marked++,e.pendingDelete=!0,e.callback.apply(e.callbackContext,e.args)),this._i++}this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;ethis._now?this.nextTick-this._now:0}}),Object.defineProperty(i.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(i.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(i.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),i.Timer.prototype.constructor=i.Timer,i.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},i.TimerEvent.prototype.constructor=i.TimerEvent,i.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},i.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,s,n,r){return e=e||[],s=s||60,void 0===n&&(n=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new i.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,s,n),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;ithis._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},i.AnimationManager.prototype.constructor=i.AnimationManager,Object.defineProperty(i.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(i.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(i.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(i.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(i.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){var e;"number"==typeof t&&this._frameData&&(e=this._frameData.getFrame(t))&&(this.currentFrame=e,this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(i.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){var e;"string"==typeof t&&this._frameData&&(e=this._frameData.getFrameByName(t))?(this.currentFrame=e,this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame)):console.warn("Cannot set frameName: "+t)}}),i.Animation=function(t,e,s,n,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=n,this.name=s,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new i.Signal,this.onUpdate=null,this.onComplete=new i.Signal,this.onLoop=new i.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},i.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(s=0;s=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay?(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay):this._frameDiff=0,this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(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=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},i.Animation.prototype.constructor=i.Animation,Object.defineProperty(i.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(i.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(i.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(i.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(i.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(i.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new i.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),i.Animation.generateFrameNames=function(t,e,s,n,r){void 0===n&&(n="");var o=[],a="";if(e=s;h--)a=t+(a="number"==typeof r?i.Utils.pad(h.toString(),r,"0",1):h.toString())+n,o.push(a);return o},i.Frame=function(t,e,s,n,r,o){this.index=t,this.x=e,this.y=s,this.width=n,this.height=r,0!==this.width&&0!==this.height||console.warn('Phaser.Frame: Frame "'+this.name+'" has a width or height of zero'),this.name=o,this.centerX=Math.floor(n/2),this.centerY=Math.floor(r/2),this.distance=i.Math.distance(0,0,n,r),this.rotated=!1,this.trimmed=!1,this.sourceSizeW=n,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},i.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=i.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new i.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new i.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},i.Frame.prototype.constructor=i.Frame,i.FrameData=function(){this._frames=[],this._frameNames=[]},i.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new i.FrameData,e=0;ed||h<-d)return console.warn("Phaser.AnimationParser.spriteSheet: skipFrames = "+h.toString()+" is larger than total sprite number "+d.toString()),null;if(h<0&&(h=d+h),-1!==r&&(d=h+r),0===c||0===u||cc&&(f=o,g+=n+a);return p},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var s,n=new i.FrameData,r=e.frames,o=0;o tag")}},i.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{},compressedTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new i.Signal,this._cacheMap=[],this._cacheMap[i.Cache.CANVAS]=this._cache.canvas,this._cacheMap[i.Cache.IMAGE]=this._cache.image,this._cacheMap[i.Cache.TEXTURE]=this._cache.texture,this._cacheMap[i.Cache.SOUND]=this._cache.sound,this._cacheMap[i.Cache.TEXT]=this._cache.text,this._cacheMap[i.Cache.PHYSICS]=this._cache.physics,this._cacheMap[i.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[i.Cache.BINARY]=this._cache.binary,this._cacheMap[i.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[i.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[i.Cache.JSON]=this._cache.json,this._cacheMap[i.Cache.XML]=this._cache.xml,this._cacheMap[i.Cache.VIDEO]=this._cache.video,this._cacheMap[i.Cache.SHADER]=this._cache.shader,this._cacheMap[i.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this._pendingCount=0,this.onReady=new i.Signal,this._addImages()},i.Cache.CANVAS=1,i.Cache.IMAGE=2,i.Cache.TEXTURE=3,i.Cache.SOUND=4,i.Cache.TEXT=5,i.Cache.PHYSICS=6,i.Cache.TILEMAP=7,i.Cache.BINARY=8,i.Cache.BITMAPDATA=9,i.Cache.BITMAPFONT=10,i.Cache.JSON=11,i.Cache.XML=12,i.Cache.VIDEO=13,i.Cache.SHADER=14,i.Cache.RENDER_TEXTURE=15,i.Cache.DEFAULT=null,i.Cache.DEFAULT_KEY="__default",i.Cache.DEFAULT_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==",i.Cache.MISSING=null,i.Cache.MISSING_KEY="__missing",i.Cache.MISSING_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==",i.Cache.READY_TIMEOUT=1e3,i.Cache.prototype={addCompressedTextureMetaData:function(t,e,s,n){this.checkImageKey(t)&&this.removeImage(t);var r=s in i.LoaderParser?i.LoaderParser[s](n):n,o={key:t,url:e,data:r,base:new PIXI.BaseTexture(r,null,this.game.resolution),frame:new i.Frame(0,0,0,r.width,r.height,t),frameData:new i.FrameData,fileFormat:s};return o.frameData.addFrame(new i.Frame(0,0,0,r.width,r.height,e)),this._cache.image[t]=o,this._resolveURL(e,o),o},addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,s){this.checkImageKey(t)&&this.removeImage(t),!1===s.complete&&console.warn('Phaser.Cache.addImage: Image "'+t+"\" hasn't been retrieved yet");var n={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution),frame:new i.Frame(0,0,0,s.width,s.height,t),frameData:new i.FrameData};return n.frameData.addFrame(new i.Frame(0,0,0,s.width,s.height,e)),this._cache.image[t]=n,this._resolveURL(e,n),"__default"===t?i.Cache.DEFAULT=new PIXI.Texture(n.base):"__missing"===t&&(i.Cache.MISSING=new PIXI.Texture(n.base)),n},addImageAsync:function(t,e,i){var s=this,n=new Image;n.onload=function(){i.call(this,s.addImage(t,null,n)),s._removePending(),n.onload=null},this._addPending(),n.src=e},addDefaultImage:function(){this.addImageAsync(i.Cache.DEFAULT_KEY,i.Cache.DEFAULT_SRC,function(t){t.base.skipRender=!0,i.Cache.DEFAULT=new PIXI.Texture(t.base)})},addMissingImage:function(){this.addImageAsync(i.Cache.MISSING_KEY,i.Cache.MISSING_SRC,function(t){i.Cache.MISSING=new PIXI.Texture(t.base)})},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,s){return e.key=t,void 0===s&&(s=new i.FrameData).addFrame(e.textureFrame),this._cache.bitmapData[t]={data:e,frameData:s},e},addBitmapFont:function(t,e,s,n,r,o,a){var h={url:e,data:s,font:null,base:new PIXI.BaseTexture(s,null,this.game.resolution)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?i.LoaderParser.jsonBitmapFont(n,h.base,o,a,!1,this.game.resolution):i.LoaderParser.xmlBitmapFont(n,h.base,o,a,!1,this.game.resolution),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addBitmapFontFromAtlas:function(t,e,s,n,r,o,a){var h=this.getFrameByName(e,s);if(h){var l={font:null,base:this.getBaseTexture(e),frame:h};void 0===o&&(o=0),void 0===a&&(a=0);var c;"json"===r?(c=this.getJSON(n),l.font=i.LoaderParser.jsonBitmapFont(c,l.base,o,a,h,this.game.resolution)):(c=this.getXML(n),l.font=i.LoaderParser.xmlBitmapFont(c,l.base,o,a,h,this.game.resolution)),this._cache.bitmapFont[t]=l}},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new i.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,s,n,r,o,a,h,l){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var c={key:t,url:e,data:s,frameWidth:n,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(s,null,this.game.resolution),frameData:i.AnimationParser.spriteSheet(this.game,s,n,r,o,a,h,l)};this._cache.image[t]=c,this._resolveURL(e,c)},addTextureAtlas:function(t,e,s,n,r){var o={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution)};r===i.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=i.AnimationParser.XMLData(this.game,n,t):r===i.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=i.AnimationParser.JSONDataPyxel(this.game,n,t):Array.isArray(n.frames)?o.frameData=i.AnimationParser.JSONData(this.game,n,t):o.frameData=i.AnimationParser.JSONDataHash(this.game,n,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(i.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(i.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(i.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(i.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(i.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(i.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(i.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(i.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(i.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(i.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(i.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(i.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(i.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(i.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(i.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,i.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var s=this.getItem(t,i.Cache.IMAGE,"getImage");return null===s&&(s=this.getItem("__missing",i.Cache.IMAGE,"getImage")),e?s:s.data},getTextureFrame:function(t){return this.getItem(t,i.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,i.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,i.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,i.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,s){var n=this.getItem(t,i.Cache.PHYSICS,"getPhysicsData","data");if(null===n||void 0===e||null===e)return n;if(n[e]){var r=n[e];if(!r||!s)return r;for(var o in r)if((o=r[o]).fixtureKey===s)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+s+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,i.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,i.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,i.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,i.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var s=this.getItem(t,i.Cache.JSON,"getJSON","data");return s?e?i.Utils.extend(!0,Array.isArray(s)?[]:{},s):s:null},getXML:function(t){return this.getItem(t,i.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,i.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,i.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,i.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,s){void 0===s&&(s=i.Cache.IMAGE),this._cacheMap[s][t]&&(this._cacheMap[s][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){return(t=this._resolveURL(t))?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=i.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var s in this._cacheMap[t])"__default"!==s&&"__missing"!==s&&e.push(s);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.image[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t0?setTimeout(function(){t.isReady||(console.warn("Phaser.Cache: Still waiting for images after %s ms.",e),t._ready())},i.Cache.READY_TIMEOUT):this._ready()},_addPending:function(){this._pendingCount+=1},_removePending:function(){this._pendingCount-=1,this._checkReady()},_checkReady:function(){this.isReady&&this._ready()},_ready:function(){this._pendingCount=0,this.onReady.dispatch(this)}},i.Cache.prototype.constructor=i.Cache,Object.defineProperty(i.Cache.prototype,"isReady",{get:function(){return this._pendingCount<=0}}),i.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new i.Signal,this.onLoadComplete=new i.Signal,this.onPackComplete=new i.Signal,this.onFileStart=new i.Signal,this.onFileComplete=new i.Signal,this.onFileError=new i.Signal,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},i.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,i.Loader.TEXTURE_ATLAS_JSON_HASH=1,i.Loader.TEXTURE_ATLAS_XML_STARLING=2,i.Loader.PHYSICS_LIME_CORONA_JSON=3,i.Loader.PHYSICS_PHASER_JSON=4,i.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,i.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new i.Rectangle(0,0,1,t.height):new i.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r=e||t&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var n=this;setTimeout(function(){n.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.reset(),this.onLoadComplete.dispatch(),this.game.state&&this.game.state.loadComplete())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(e)for(var s=0;s=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},getVideoURL:function(t){for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s="error loading asset from URL "+(t.requestUrl||this.transformUrl(t.url,t));!i&&e&&(i=e.status),i&&(s=s+" ("+i+")"),this.asyncComplete(t,s)},fileComplete:function(t,e){var s=!0;switch(t.type){case"packfile":r=JSON.parse(e.responseText);t.data=r||{};break;case"texture":var n=/\.([^.]+)$/.exec(t.url.split("?",1)[0])[1].toLowerCase();null!==t.data?this.cache.addCompressedTextureMetaData(t.key,t.url,n,t.data):this.cache.addCompressedTextureMetaData(t.key,t.url,n,e.response);break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing,t.skipFrames);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(s=!1,t.format===i.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===i.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===i.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==i.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(s=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var r=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,r,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}s&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else(e=new ActiveXObject("Microsoft.XMLDOM")).async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(i.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return i.Math.clamp(t||0,0,100)}}),Object.defineProperty(i.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),i.Loader.prototype.constructor=i.Loader,i.LoaderParser={bitmapFont:function(t,e,i,s,n,r){return this.xmlBitmapFont(t,e,i,s,n,r)},xmlBitmapFont:function(t,e,i,s,n,r){null==r&&(r=1);var o={},a=t.getElementsByTagName("info")[0],h=t.getElementsByTagName("common")[0];o.font=a.getAttribute("face"),o.size=parseInt(a.getAttribute("size"),10),o.lineHeight=parseInt(h.getAttribute("lineHeight"),10)+s,o.chars={};for(var l=t.getElementsByTagName("char"),c=n?n.x:0,u=n?n.y:0,d=0;d=0){switch(r>=0&&r<=3?e="PVRTC":r>=7&&r<=11?e="S3TC":6===r&&(e="ETC1"),r){case 0:o=35841;break;case 1:o=35843;break;case 2:o=35840;break;case 3:o=35842;break;case 6:o=36196;break;case 7:o=33777;break;case 9:o=33778;break;case 11:o=33779;break;default:o=-1}n={complete:!0,fileFormat:"PVR",compressionAlgorithm:e,flags:i[1],pixelFormat:r,colorSpace:i[4],channelType:i[5],height:i[6],width:i[7],depth:i[8],numberOfSurfaces:i[9],numberOfFaces:i[10],numberOfMipmaps:i[11],metaDataSize:i[12],textureData:s.subarray(52+i[12],s.byteLength),glExtensionFormat:o}}return n},dds:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null;return 68===e[0]&&68===e[1]&&83===e[2]&&32===e[3]&&"DX10"===(s={complete:!0,fileFormat:"DDS",compressionAlgorithm:"S3TC",size:i[1],flags:i[2],height:i[3],width:i[4],pitch:i[5],depth:i[6],mipmapCount:i[7],formatSize:i[19],formatFlag:i[19],formatFourCC:[String.fromCharCode(e[84]),String.fromCharCode(e[85]),String.fromCharCode(e[86]),String.fromCharCode(e[87])].join(""),formatBitCount:i[21],formatRBitMask:i[22],formatGBitMask:i[23],formatBBitMask:i[24],formatABitMask:i[25],caps1:i[26],caps2:i[27],caps3:i[28],caps4:i[29],reserved2:i[30],DXGIFormat:null,resourceDimension:null,miscFlag:null,arraySize:null,textureData:e.subarray(i[1]+4,e.byteLength)}).formatFourCC&&(s.DXGIFormat=i[31],s.resourceDimension=i[32],s.miscFlag=i[33],s.arraySize=i[34],s.miscFlag=i[35]),s},ktx:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null,n=16+i[15]/4|0,r=i[n],o=i[7],a=0;if(171===e[0]&&75===e[1]&&84===e[2]&&88===e[3]&&32===e[4]&&49===e[5]&&49===e[6]&&187===e[7]&&13===e[8]&&10===e[9]&&26===e[10]&&10===e[11]&&[36196,35840,35841,35842,35843,33776,33777,33778,33779].indexOf(o)>=0){switch(o){case 36196:a="ETC1";break;case 35840:case 35841:case 35842:case 35843:a="PVRTC";break;case 33776:case 33777:case 33778:case 33779:a="S3TC"}s={complete:!0,fileFormat:"KTX",compressionAlgorithm:a,endianness:i[3],glType:i[4],glTypeSize:i[5],glFormat:i[6],glInternalFormat:i[7],glBaseInternalFormat:i[8],width:i[9],height:i[10],pixelDepth:i[11],numberOfArrayElements:i[12],numberOfFaces:i[13],numberOfMipmapLevels:i[14],bytesOfKeyValueData:i[15],keyAndValueByteSize:i[16],imageSize:r,textureData:e.subarray(4*(n+1),r+100)}}return s},pkm:function(t){var e=new Uint8Array(t),i=null;return 80===e[0]&&75===e[1]&&77===e[2]&&32===e[3]&&(i={complete:!0,fileFormat:"PKM",compressionAlgorithm:"ETC1",format:65535&(e[6]<<8|e[7]),width:65535&(e[8]<<8|e[9]),height:65535&(e[10]<<8|e[11]),originalWidth:65535&(e[12]<<8|e[13]),originalHeight:65535&(e[14]<<8|e[15]),textureData:e.subarray(16,e.length)}),i}},i.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},i.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},i.AudioSprite.prototype.constructor=i.AudioSprite,i.Sound=function(t,e,s,n,r){void 0===s&&(s=1),void 0===n&&(n=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=n,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this._globalVolume=1,this._markedToDelete=!1,this._removeFromSoundManager=!1,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=s,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new i.Signal,this.onPlay=new i.Signal,this.onPause=new i.Signal,this.onResume=new i.Signal,this.onLoop=new i.Signal,this.onStop=new i.Signal,this.onMute=new i.Signal,this.onMarkerComplete=new i.Signal,this.onFadeComplete=new i.Signal,this._volume=s,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},i.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop(),this._markedToDelete&&(this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode),this._removeFromSoundManager?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()))},update:function(){this.game.cache.checkSoundKey(this.key)?(this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))):this.destroy()},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){this.isPlaying&&!this.paused&&e!==this.volume&&(void 0===t&&(t=1e3),void 0!==e?(this.fadeTween=this.game.add.tween(this).to({volume:e},t,i.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)):console.warn("Phaser.Sound.fadeTo: No Volume Specified."))},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._globalVolume=t,this._sound.volume=this._globalVolume*this._volume)},destroy:function(t){void 0===t&&(t=!0),this._markedToDelete=!0,this._removeFromSoundManager=t,this.stop(),t?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())}},i.Sound.prototype.constructor=i.Sound,Object.defineProperty(i.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(i.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(i.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(i.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted?this._muteVolume=t:(this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=this._globalVolume*t))}}),i.SoundManager=function(t){this.game=t,this.onSoundDecode=new i.Signal,this.onVolumeChange=new i.Signal,this.onMute=new i.Signal,this.onUnMute=new i.Signal,this.onTouchUnlock=new i.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new i.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},i.SoundManager.prototype={boot:function(){var t=this.game.device,e=window.PhaserGlobal;if(t.iOS&&!1===t.webAudio&&(this.channels=1),e){if(!0===e.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===e.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(e&&e.audioContext)this.context=e.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||t.needsTouchUnlock()&&this.setTouchLock(),this.usingWebAudio&&t.chrome&&t.chromeVersion<=65&&console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. ')},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0)},setTouchUnlock:function(){this.touchLocked=!1,this._unlockSource=null,this.onTouchUnlock.dispatch()},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.setTouchUnlock();else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0),"suspended"===this._unlockSource.context.state&&this._unlockSource.context.resume()}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,s=this._parentBounds.height,n=this.getParentBounds(this._parentBounds),r=n.width!==e||n.height!==s,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,n),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottlee;return(h=h?s:!s)?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},i.ScaleManager.prototype.constructor=i.ScaleManager,Object.defineProperty(i.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(i.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(i.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(i.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),i.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.lineWidth=1,this.renderShadow=!0,this.currentColor=null,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1,this.isDisabled=!1,this._line=null,this._rect=null},i.Utils.Debug.prototype={boot:function(){this.game.renderType===i.CANVAS?this.context=this.game.context:(this.bmd=new i.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=i.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d")),this._line=new i.Line,this._rect=new i.Rectangle},resize:function(){this.bmd.resize(this.game.width,this.game.height),this.canvas.width=this.game.width,this.canvas.height=this.game.height},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e0)for(var e=0;e=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new i.Rectangle,layoutBounds:new i.Rectangle,documentBounds:new i.Rectangle},i.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},s=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(i.DOM,"scrollX",{get:e}),Object.defineProperty(i.DOM,"scrollY",{get:s}),Object.defineProperty(i.DOM.visualBounds,"x",{get:e}),Object.defineProperty(i.DOM.visualBounds,"y",{get:s}),Object.defineProperty(i.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(i.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var n=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(i.DOM.visualBounds,"width",{get:n}),Object.defineProperty(i.DOM.visualBounds,"height",{get:r}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:n}),Object.defineProperty(i.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(i.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(i.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(i.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(i.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(i.ArraySet.prototype,"next",{get:function(){return this.position=s||0===i)){null==i&&(i=1);for(var n=s-i,r=e;r0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=(t=i.ArrayUtils.transposeMatrix(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=i.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var s=0;s>>0:(t<<24|e<<16|s<<8|n)>>>0},unpackPixel:function(t,e,s,n){return void 0!==e&&null!==e||(e=i.Color.createColor()),void 0!==s&&null!==s||(s=!1),void 0!==n&&null!==n||(n=!1),i.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",s&&i.Color.RGBtoHSL(e.r,e.g,e.b,e),n&&i.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=i.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},hexToRGBArray:function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},RGBArrayToHex:function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},RGBtoHSL:function(t,e,s,n){n||(n=i.Color.createColor(t,e,s,1)),t/=255,e/=255,s/=255;var r=Math.min(t,e,s),o=Math.max(t,e,s);if(n.h=0,n.s=0,n.l=(o+r)/2,o!==r){var a=o-r;n.s=n.l>.5?a/(2-o-r):a/(o+r),o===t?n.h=(e-s)/a+(e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,s,n,r,o,a,h){var l={r:t||0,g:e||0,b:s||0,a:n||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return i.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toFixed()+","+t.g.toFixed()+","+t.b.toFixed()+","+t.a.toString()+")",t.color=i.Color.getColor(t.r,t.g,t.b),t.color32=i.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,s,n,r){return void 0===n&&(n=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+s).toString(16).slice(1):"0x"+i.Color.componentToHex(n)+i.Color.componentToHex(t)+i.Color.componentToHex(e)+i.Color.componentToHex(s)},hexToRGB:function(t){var e=i.Color.hexToColor(t);if(e)return i.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var s=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(s){var n=parseInt(s[1],16),r=parseInt(s[2],16),o=parseInt(s[3],16);e?(e.r=n,e.g=r,e.b=o):e=i.Color.createColor(n,r,o)}return e},webToColor:function(t,e){e||(e=i.Color.createColor());var s=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return s&&(e.r=~~Number(s[1]),e.g=~~Number(s[2]),e.b=~~Number(s[3]),e.a=void 0!==s[4]?Number(s[4]):1,i.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=i.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?i.Color.webToColor(t,e):(e.a=1,i.Color.hexToColor(t,e));if("number"==typeof t){var s=i.Color.getRGB(t);return e.r=s.r,e.g=s.g,e.b=s.b,e.a=s.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSVtoRGB(n/359,t,e));return s},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSLtoRGB(n/359,t,e));return s},interpolateColor:function(t,e,s,n,r,o){void 0===r&&(r=255),void 0===o&&(o=0);var a=i.Color.getRGB(t),h=i.Color.getRGB(e);if(0===o)var l=(h.red-a.red)*n/s+a.red,c=(h.green-a.green)*n/s+a.green,u=(h.blue-a.blue)*n/s+a.blue;if(1===o){var d,p=i.Color.RGBtoHSV(a.r,a.g,a.b),f=i.Color.RGBtoHSV(h.r,h.g,h.b),g=f.h-p.h;if(p.h>f.h){var m=f.h;f.h=p.h,p.h=m,g=-g,n=s-n}g>.5&&(p.h=p.h+1,d=((f.h-p.h)*n/s+p.h)%1),g<=.5&&(d=(f.h-p.h)*n/s+p.h);var y=(f.s-p.s)*n/s+p.s,v=(f.v-p.v)*n/s+p.v,x=i.Color.HSVtoRGB(d,y,v,x),l=x.r,c=x.g,u=x.b}return i.Color.getColor32(r,l,c,u)},interpolateColorWithRGB:function(t,e,s,n,r,o){var a=i.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(s-a.green)*o/r+a.green,c=(n-a.blue)*o/r+a.blue;return i.Color.getColor(h,l,c)},interpolateRGB:function(t,e,s,n,r,o,a,h){var l=(n-t)*h/a+t,c=(r-e)*h/a+e,u=(o-s)*h/a+s;return i.Color.getColor(l,c,u)},linear:function(t,e,i){return this.interpolateColor(t,e,1,i)},linearInterpolation:function(t,e){var s=i.Math.linear(0,t.length-1,e),n=t[Math.floor(s)],r=t[Math.ceil(s)];return this.linear(n,r,s%1)},getRandomColor:function(t,e,s){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===s&&(s=255),e>255||t>e)return i.Color.getColor(255,255,255);var n=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return i.Color.getColor32(s,n,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=i.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return i.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return i.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return i.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?i.Color.blendLinearBurn(t,2*e):i.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?i.Color.blendColorBurn(t,2*e):i.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?i.Color.blendDarken(t,2*e):i.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return i.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return i.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},i.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},i.Physics.ARCADE=0,i.Physics.P2JS=1,i.Physics.NINJA=2,i.Physics.BOX2D=3,i.Physics.CHIPMUNK=4,i.Physics.MATTERJS=5,i.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!i.Physics.hasOwnProperty("Arcade")||(this.arcade=new i.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&i.Physics.hasOwnProperty("Ninja")&&(this.ninja=new i.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&i.Physics.hasOwnProperty("P2")&&(this.p2=new i.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&i.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new i.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&i.Physics.hasOwnProperty("Matter")&&(this.matter=new i.Physics.Matter(this.game,this.config))},startSystem:function(t){t===i.Physics.ARCADE?this.arcade=new i.Physics.Arcade(this.game):t===i.Physics.P2JS?null===this.p2?this.p2=new i.Physics.P2(this.game,this.config):this.p2.reset():t===i.Physics.NINJA?this.ninja=new i.Physics.Ninja(this.game):t===i.Physics.BOX2D?null===this.box2d?this.box2d=new i.Physics.Box2D(this.game,this.config):this.box2d.reset():t===i.Physics.MATTERJS&&(null===this.matter?this.matter=new i.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,s){void 0===e&&(e=i.Physics.ARCADE),void 0===s&&(s=!1),e===i.Physics.ARCADE?this.arcade.enable(t):e===i.Physics.P2JS&&this.p2?this.p2.enable(t,s):e===i.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===i.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===i.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},i.Physics.prototype.constructor=i.Physics,i.Physics.Arcade=function(t){this.game=t,this.gravity=new i.Point,this.bounds=new i.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=i.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new i.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._total=0,this.setBoundsToWorld()},i.Physics.Arcade.prototype.constructor=i.Physics.Arcade,i.Physics.Arcade.SORT_NONE=0,i.Physics.Arcade.LEFT_RIGHT=1,i.Physics.Arcade.RIGHT_LEFT=2,i.Physics.Arcade.TOP_BOTTOM=3,i.Physics.Arcade.BOTTOM_TOP=4,i.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof i.Group?this.enable(t[s].children,e):(this.enableBody(t[s]),e&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],!0));else t instanceof i.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.Arcade.Body(t),t.parent&&t.parent instanceof i.Group&&t.parent.addToHash(t))},updateMotion:function(t){if(t.allowRotation){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed}t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&e.allowDrag&&(i-(n*=this.game.time.physicsElapsed)>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!0),this._total>0},collide:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!1),this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===i.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===i.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===i.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===i.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideObjects:function(t,e,i,s,n,r){if(!Array.isArray(t)&&Array.isArray(e))for(o=0;oa.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(t.body.bottoma.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,s,n,r,o)}}else{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(e);for(var c=this.quadTree.retrieve(t),h=0;hc.right)continue;if(c.x>a.right)break}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(a.bottomc.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,s,n,r)}}}}},collideGroupVsGroup:function(t,e,s,n,r,o){if(0!==t.length&&0!==e.length)for(var a=0;aa.bottom)&&(h.xa.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var s=i.Math.clamp(t.center.x,e.left,e.right),n=i.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-s)*(t.center.x-s)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},separateCircle:function(t,e,s){this.getOverlapX(t,e),this.getOverlapY(t,e);var n=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,n),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.center.x:e.center.x,y:t.isCircle?t.center.y:e.center.y,radius:t.isCircle?t.halfWidth:e.halfWidth};l.yh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.xh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.halfWidth+e.halfWidth-i.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(s||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.yMath.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x)>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0):t.deltaX()n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y)>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0):t.deltaY()n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,s,n,r,o){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(s);for(var a=new i.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c0&&(s=this.distanceBetween(t,e)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.setToPolar(n,e),n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},velocityFromAngle:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e,!0)},velocityFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerationFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(o,s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i,s){void 0===i&&(i=!1);var n,r;return s?(n=t.centerX-e.centerX,r=t.centerY-e.centerY):i?(n=t.world.x-e.world.x,r=t.world.y-e.world.y):(n=t.x-e.x,r=t.y-e.y),Math.sqrt(n*n+r*r)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},closest:function(t,e,i,s){for(var n=1/0,r=null,o=0,a=e.length;on&&(r=h,n=l)}return r},angleBetween:function(t,e,s){return void 0===s&&(s=!1),s?i.Point.angle(e.world,t.world):i.Point.angle(e,t)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},i.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=i.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new i.Point,this.position=new i.Point(t.x,t.y),this.prev=new i.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new i.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new i.Point,this.newVelocity=new i.Point,this.deltaMax=new i.Point,this.acceleration=new i.Point,this.allowDrag=!0,this.drag=new i.Point,this.allowGravity=!0,this.gravity=new i.Point,this.bounce=new i.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new i.Point(1e4,1e4),this.friction=new i.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=i.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.tilePadding=new i.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new i.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},i.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter())},updateCenter:function(){this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,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=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.none=!0,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.overlapR=0,this.overlapX=0,this.overlapY=0,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.updateCenter(),this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),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,this.updateCenter(),this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=this.velocity.atan()),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=i.LEFT:this.deltaX()>0&&(this.facing=i.RIGHT),this.deltaY()<0?this.facing=i.UP:this.deltaY()>0&&(this.facing=i.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.updateCenter(),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0,this.blocked.none=!1),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0,this.blocked.none=!1),!this.blocked.none},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.setToPolar(s,e),this.isMoving=!0,!0},moveTo:function(t,e,s){var n=e/(t/1e3);if(0===n)return!1;var r;return void 0===s?(r=this.angle,s=this.game.math.radToDeg(r)):r=this.game.math.degToRad(s),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new i.Line,this.moveEnd=new i.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===s||180===s?this.velocity.set(Math.cos(r)*n,0):90===s||270===s?this.velocity.set(0,Math.sin(r)*n):this.velocity.setToPolar(r,n),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,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(i,s),this.updateCenter(),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,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(e,i),this.updateCenter()):this.isCircle=!1},reset:function(t,e){this.stop(),this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this.updateBounds(),this.updateCenter()},stop:function(){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?i.Circle.contains(this,t,e):i.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},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},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof i.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(i.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),i.Physics.Arcade.Body.render=function(t,e,i,s,n){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,t.lineWidth=n||1,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.halfWidth,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},i.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},i.Physics.Arcade.Body.prototype.constructor=i.Physics.Arcade.Body,i.Physics.Arcade.TilemapCollision=function(){},i.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x-e.getTileOffsetX(),t.body.position.y-t.body.tilePadding.y-e.getTileOffsetY(),t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;ae.deltaAbsY()?l=-1:e.deltaAbsX()0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.getTileOffsetY();return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?(t.blocked.left=!0,t.blocked.none=!1):e>0&&(t.blocked.right=!0,t.blocked.none=!1),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?(t.blocked.up=!0,t.blocked.none=!1):e>0&&(t.blocked.down=!0,t.blocked.none=!1),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},i.Utils.mixinPrototype(i.Physics.Arcade.prototype,i.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,i.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new i.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new i.Signal,this.onBodyRemoved=new i.Signal,this.onSpringAdded=new i.Signal,this.onSpringRemoved=new i.Signal,this.onConstraintAdded=new i.Signal,this.onConstraintRemoved=new i.Signal,this.onContactMaterialAdded=new i.Signal,this.onContactMaterialRemoved=new i.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},i.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,s){void 0===e&&(e=!1),void 0===s&&(s=!0);var n=1;if(Array.isArray(t))for(n=t.length;n--;)t[n]instanceof i.Group?this.enable(t[n].children,e,s):(this.enableBody(t[n],e),s&&t[n].hasOwnProperty("children")&&t[n].children.length>0&&this.enable(t[n],e,!0));else t instanceof i.Group?this.enable(t.children,e,s):(this.enableBody(t,e),s&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);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.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.DistanceConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,s,n){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.GearConstraint(this,t,e,s,n));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),s=this.getBody(s),t&&s)return this.addConstraint(new i.Physics.P2.RevoluteConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,s,n,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.LockConstraint(this,t,e,s,n,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,s,n,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.PrismaticConstraint(this,t,e,s,n,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var s=new i.Physics.P2.Material(t);return this.materials.push(s),void 0!==e&&e.setMaterial(s),s},createContactMaterial:function(t,e,s){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var n=new i.Physics.P2.ContactMaterial(t,e,s);return this.addContactMaterial(n)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof i.Physics.P2.Body?t.data:t.body&&t.body.type===i.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,s,n){void 0===e&&(e=this.world.bodies),void 0===s&&(s=5),void 0===n&&(n=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof i.Physics.P2.Body&&(!n||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!n||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof i.Sprite&&e[a].hasOwnProperty("body")&&(!n||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,s)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var s=new i.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(s),t&&this.setCollisionGroup(t,s),s},setCollisionGroup:function(t,e){if(t instanceof i.Group)for(var s=0;s-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides?n+=u.width:((p=this.createBody(r,o,0,!1)).addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0)}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(i.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(i.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(i.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(i.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(i.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(i.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(i.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(i.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(i.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),i.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},i.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionGroup=t})},setMask:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionMask=t})},setSensor:function(t,e){this.getFixtures(e).forEach(function(e){e.sensor=t})},setMaterial:function(t,e){this.getFixtures(e).forEach(function(e){e.material=t})},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},i.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.PointProxy.prototype.constructor=i.Physics.P2.PointProxy,Object.defineProperty(i.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),i.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.InversePointProxy.prototype.constructor=i.Physics.P2.InversePointProxy,Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),i.Physics.P2.Body=function(t,e,s,n,r){e=e||null,s=s||0,n=n||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=i.Physics.P2JS,this.offset=new i.Point,this.data=new p2.Body({position:[this.world.pxmi(s),this.world.pxmi(n)],mass:r}),this.data.parent=this,this.velocity=new i.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new i.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new i.Point,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},i.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(r=0;r-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var n=this.getCollisionMask();if(void 0===i)for(var r=this.data.shapes.length-1;r>=0;r--)this.data.shapes[r].collisionMask=n;else i.collisionMask=n},collides:function(t,e,i,s){if(Array.isArray(t))for(r=0;r=0;r--)this.data.shapes[r].collisionMask=n;else s.collisionMask=n},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},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(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;np;n=0<=p?++d:--d)l=e.vertices[n],p2.vec2.rotate(u,l,t),c.push([(u[0]+a[0])*this.ppu,-(u[1]+a[1])*this.ppu]);this.drawConvex(h,c,e.triangles,16711680,i,r,this.settings.debugPolygons,[a[0]*this.ppu,-a[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)p=(c=e[l])[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return 2===(e=t.toString(16)).length?e:e+"0"}}),i.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1);var c={restLength:s=t.pxm(s),stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},i.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),i.Physics.P2.Material.prototype.constructor=i.Physics.P2.Material,i.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},i.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),i.Physics.P2.ContactMaterial.prototype.constructor=i.Physics.P2.ContactMaterial,i.Physics.P2.CollisionGroup=function(t){this.mask=t},i.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t;var a={distance:s=t.pxm(s),localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},i.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),i.Physics.P2.DistanceConstraint.prototype.constructor=i.Physics.P2.DistanceConstraint,i.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},i.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),i.Physics.P2.GearConstraint.prototype.constructor=i.Physics.P2.GearConstraint,i.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t;var o={localOffsetB:s=[t.pxm(s[0]),t.pxm(s[1])],localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},i.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),i.Physics.P2.LockConstraint.prototype.constructor=i.Physics.P2.LockConstraint,i.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t;var h={localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},i.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),i.Physics.P2.PrismaticConstraint.prototype.constructor=i.Physics.P2.PrismaticConstraint,i.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},i.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),i.Physics.P2.RevoluteConstraint.prototype.constructor=i.Physics.P2.RevoluteConstraint,i.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},i.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&tthis.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},i.Tile.prototype.constructor=i.Tile,Object.defineProperty(i.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(i.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(i.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(i.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(i.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(i.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),i.Tilemap=function(t,e,s,n,r,o){this.game=t,this.key=e;var a=i.TilemapParser.parse(this.game,e,s,n,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},i.Tilemap.CSV=0,i.Tilemap.TILED_JSON=1,i.Tilemap.NORTH=0,i.Tilemap.EAST=1,i.Tilemap.SOUTH=2,i.Tilemap.WEST=3,i.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,s,n,r,o,a){if(void 0===t)return null;void 0===s&&(s=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===s&&(s=32),0===n&&(n=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof i.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===i.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),console.log("Tilesets: ",this.tilesets),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new i.Tileset(t,a,s,n,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y1)for(u=0;uthis.layers.length)return console.warn('Tilemap.createLayer: Invalid layer ID given: "'+t+'"'),void console.log("Layers: ",this.layers);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===s||s<=0?s=Math.min(this.game.height,this.layers[r].heightInPixels):s>this.game.height&&(s=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",s),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=n.add(new i.TilemapLayer(this.game,this,r,e,s));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,s,n,r,o){void 0===o&&(o=this.game.world);{if(null===this.getLayerIndex(t)){for(var a,h={name:t,x:0,y:0,width:e,height:s,widthInPixels:e*n,heightInPixels:s*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;cthis.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height),(l=new i.TilemapLayer(this.game,this,this.layers.length-1,d,p)).name=t,o.add(l)}console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t)}},getIndex:function(t,e){for(var i=0;ie)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n-1&&this.collideIndexes.splice(n,1)}for(var r=0;r0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e-1},removeTile:function(t,e,s){if(s=this.getLayer(s),t>=0&&t=0&&e=0&&e=0&&s-1?this.layers[n].data[s][e].setCollision(!0,!0,!0,!0):this.layers[n].data[s][e].resetCollision(),this.layers[n].dirty=!0,this.calculateFaces(n),this.layers[n].data[s][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(r=this.layers[s].height-1;r>=0;r--)for(o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r=0&&t=0&&ethis.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},i.Tilemap.prototype.constructor=i.Tilemap,Object.defineProperty(i.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),i.TilemapLayer=function(t,e,s,n,r){n|=0,r|=0,i.Sprite.call(this,t,0,0),this.map=e,this.index=s,this.layer=e.layers[s],this.canvas=i.CanvasPool.create(this,n,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas,null,this.game.resolution))),this.type=i.TILEMAPLAYER,this.physicsType=i.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!0,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this.tileOffset=new i.Point(this.layer.offsetX||0,this.layer.offsetY||0),this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=i.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},i.TilemapLayer.prototype=Object.create(i.Sprite.prototype),i.TilemapLayer.prototype.constructor=i.TilemapLayer,i.TilemapLayer.prototype.preUpdateCore=i.Component.Core.preUpdate,i.TilemapLayer.sharedCopyCanvas=null,i.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=i.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},i.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},i.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y},i.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.TilemapLayer.prototype.destroy=function(){i.CanvasPool.remove(this),i.Component.Destroy.prototype.destroy.call(this)},i.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},i.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},i.TilemapLayer.prototype.getTileOffsetX=function(){return this.tileOffset.x||(this.fixedToCamera?0:this.position.x)},i.TilemapLayer.prototype.getTileOffsetY=function(){return this.tileOffset.y||(this.fixedToCamera?0:this.position.y)},i.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},i.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},i.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},i.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},i.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},i.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},i.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},i.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a=0;m++,v--,f+=c){m>=h&&(m-=h);var _=this.layer.data[m];for(g=b,y=n-i,p=x;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var w=_[g];if(w&&!(w.index<0)){var T=w.index,P=u[T];void 0===P&&(P=this.resolveTileset(T)),w.alpha===d||this.debug||(o.globalAlpha=w.alpha,d=w.alpha),P?w.rotation||w.flipped?(o.save(),o.translate(p+w.centerX,f+w.centerY),o.rotate(w.rotation),w.flipped&&o.scale(-1,1),P.draw(o,-w.centerX,-w.centerY,T),o.restore()):P.draw(o,p,f,T):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),w.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},i.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},i.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},i.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)=0;s++,r--,e+=f){s>=d&&(s-=d);var T=this.layer.data[s];for(i=_,n=m-g,t=x;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var P=T[i];!P||P.index<0||!P.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),P.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),P.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),P.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),P.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(i.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),i.TilemapParser={INSERT_NULL:!1,parse:function(t,e,s,n,r,o){if(void 0===s&&(s=32),void 0===n&&(n=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(s,n,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===i.Tilemap.CSV)return this.parseCSV(e,a.data,s,n);if(!a.format||a.format===i.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,s,n){for(var r=this.getEmptyData(),o=[],a=(e=e.trim()).split("\n"),h=a.length,l=0,c=0;c>>0;r.data=h,delete r.encoding}else if(r.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+r.name+"'");continue}k={name:r.name,x:r.x,y:r.y,width:r.width,height:r.height,widthInPixels:r.width*t.tilewidth,heightInPixels:r.height*t.tileheight,alpha:r.opacity,offsetX:r.offsetx,offsetY:r.offsety,visible:r.visible,properties:{},indexes:[],callbacks:[],bodies:[]};r.properties&&(k.properties=r.properties);for(var c,u,d,p=0,f=[],g=[],m=0,a=r.data.length;m536870912)switch(A>2147483648&&(A-=2147483648,d+=4),A>1073741824&&(A-=1073741824,d+=2),A>536870912&&(A-=536870912,d+=1),d){case 5:c=Math.PI/2;break;case 6:c=Math.PI;break;case 3:c=3*Math.PI/2;break;case 4:c=0,u=!0;break;case 7:c=Math.PI/2,u=!0;break;case 2:c=Math.PI,u=!0;break;case 1:c=3*Math.PI/2,u=!0}A>0?((F=new i.Tile(k,A,p,g.length,t.tilewidth,t.tileheight)).rotation=c,F.flipped=u,0!==d&&(F.flippedVal=d),f.push(F)):i.TilemapParser.INSERT_NULL?f.push(null):f.push(new i.Tile(k,-1,p,g.length,t.tilewidth,t.tileheight)),++p===r.width&&(g.push(f),p=0,f=[])}k.data=g,s.push(k)}e.layers=s;for(var y=[],n=0;n=0&&n+1=this.firstgid&&t=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(t=0;t=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._total>0&&this._counter>=this._total&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},i.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1),void 0===r&&(r=null);var o,a=0,h=t,l=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);athis.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},i.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),this.resetParticle(n,o,a),!0},i.Particles.Arcade.Emitter.prototype.getNextParticle=function(){for(var t=this.length;t--;){var e=this.next();if(!e.exists)return e}return null},i.Particles.Arcade.Emitter.prototype.resetParticle=function(t,e,i){var s=this.game.rnd;t.reset(e,i),t.angle=0,t.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(t):this.particleSendToBack&&this.sendToBack(t),this.autoScale?t.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?t.scale.set(s.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y?t.scale.set(s.realInRange(this._minParticleScale.x,this._maxParticleScale.x),s.realInRange(this._minParticleScale.y,this._maxParticleScale.y)):t.scale.set(this._minParticleScale.x,this._minParticleScale.y),this.autoAlpha?t.setAlphaData(this.alphaData):t.alpha=s.realInRange(this.minParticleAlpha,this.maxParticleAlpha),t.blendMode=this.blendMode;var n=t.body;n.updateBounds(),n.bounce.copyFrom(this.bounce),n.drag.copyFrom(this.particleDrag),null!=this.minAngle&&null!=this.maxAngle?this.game.physics.arcade.velocityFromAngle(this.minAngle===this.maxAngle?this.minAngle:s.between(this.minAngle,this.maxAngle),this.minSpeed===this.maxSpeed?this.minSpeed:s.between(this.minSpeed,this.maxSpeed),n.velocity):(n.velocity.x=s.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),n.velocity.y=s.between(this.minParticleSpeed.y,this.maxParticleSpeed.y)),n.angularVelocity=s.between(this.minRotation,this.maxRotation),n.gravity.copyFrom(this.gravity),n.angularDrag=this.angularDrag,t.onEmit()},i.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),i.Group.prototype.destroy.call(this,!0,!1)},i.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},i.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},i.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},i.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},i.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,s,n,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=0),void 0===n&&(n=i.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,s>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},s,n);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},i.Particles.Arcade.Emitter.prototype.setScale=function(t,e,s,n,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=1),void 0===n&&(n=1),void 0===r&&(r=0),void 0===o&&(o=i.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,s),this._maxParticleScale.set(e,n),this.autoScale=!1,r>0&&(t!==e||s!==n)){var h={x:t,y:s},l=this.game.make.tween(h).to({x:e,y:n},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},i.Particles.Arcade.Emitter.prototype.setAngle=function(t,e,i,s){return this.minAngle=t,this.maxAngle=e,null!=i&&(this.minSpeed=i),null!=s&&(this.maxSpeed=s),this},i.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"gravity",{get:function(){return this._gravity},set:function(t){"number"==typeof t?this._gravity.y=t:this._gravity=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"id",{get:function(){return this._id}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"output",{get:function(){return 1e3*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"lifespanOutput",{get:function(){return(0===this.lifespan?1/0:this.lifespan)*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"remainder",{get:function(){return this.maxParticles-this.lifespanOutput}}),i.Weapon=function(t,e){i.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new i.Rectangle(0,0,1,1),this.fireAngle=i.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new i.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=i.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=i.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new i.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new i.Signal,this.onKill=new i.Signal,this.onFireLimit=new i.Signal,this.trackedSprite=null,this.trackedPointer=null,this.multiFire=!1,this._hasFired=!1,this.trackRotation=!1,this.trackOffset=new i.Point,this._nextFire=0,this._tempNextFire=0,this._rotatedPoint=new i.Point},i.Weapon.prototype=Object.create(i.Plugin.prototype),i.Weapon.prototype.constructor=i.Weapon,i.Weapon.KILL_NEVER=0,i.Weapon.KILL_LIFESPAN=1,i.Weapon.KILL_DISTANCE=2,i.Weapon.KILL_WEAPON_BOUNDS=3,i.Weapon.KILL_CAMERA_BOUNDS=4,i.Weapon.KILL_WORLD_BOUNDS=5,i.Weapon.KILL_STATIC_BOUNDS=6,i.Weapon.prototype.createBullets=function(t,e,s,n){return void 0===t&&(t=1),void 0===n&&(n=this.game.world),this.bullets&&!this.bullets.game&&(this.bullets=null),this.bullets||(this.bullets=this.game.add.physicsGroup(i.Physics.ARCADE,n),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,s),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=s),this},i.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},i.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},i.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},i.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},i.Weapon.prototype.update=function(){this._bulletKillType===i.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},i.Weapon.prototype.postRender=function(){this.multiFire&&this._hasFired&&(this._hasFired=!1,this._nextFire=this._tempNextFire)},i.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},i.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},i.Weapon.prototype.fireMany=function(t,e){this.multiFire=!0;var i=[],s=this;return e||this.trackedSprite||this.trackedPointer?t.forEach(function(t){i.push(s.fire(e,null,null,t.x,t.y))}):t.forEach(function(t){i.push(s.fire(t))}),i},i.Weapon.prototype.fireOffset=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.fire(null,null,null,t,e)},i.Weapon.prototype.fire=function(t,e,s,n,r){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game.time.now0&&this.shots===this.fireLimit)return null;var o=this.bulletSpeed;0!==this.bulletSpeedVariance&&(o+=i.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.worldRotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(o+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y)),void 0!==n&&(this.fireFrom.x+=n),void 0!==r&&(this.fireFrom.y+=r);var a=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,h=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,l=this.trackRotation?this.trackedSprite.angle:this.fireAngle;null!==e&&null!==s&&(l=this.game.math.radToDeg(Math.atan2(s-h,e-a))),0!==this.bulletAngleVariance&&(l+=i.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var c=0,u=0;0===l||180===l?c=Math.cos(this.game.math.degToRad(l))*o:90===l||270===l?u=Math.sin(this.game.math.degToRad(l))*o:(c=Math.cos(this.game.math.degToRad(l))*o,u=Math.sin(this.game.math.degToRad(l))*o);var d=null;if(this.autoExpandBulletsGroup?(d=this.bullets.getFirstExists(!1,!0,a,h,this.bulletKey,this.bulletFrame)).data.bulletManager=this:d=this.bullets.getFirstExists(!1),d){if(d.reset(a,h),d.data.fromX=a,d.data.fromY=h,d.data.killType=this.bulletKillType,d.data.killDistance=this.bulletKillDistance,d.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===i.Weapon.KILL_LIFESPAN&&(d.lifespan=this.bulletLifespan),d.angle=l+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===d.animations.getAnimation(this.bulletAnimation)){var p=this.anims[this.bulletAnimation];d.animations.add(p.name,p.frames,p.frameRate,p.loop,p.useNumericIndex)}d.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(d.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(d.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);d.data.bodyDirty&&(this._data.customBody&&d.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),d.body.collideWorldBounds=this.bulletCollideWorldBounds,d.data.bodyDirty=!1),d.body.velocity.set(c,u),d.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y);var f=0;if(0!==this.bulletSpeedVariance){var g=this.fireRate;(g+=i.Math.between(-this.fireRateVariance,this.fireRateVariance))<0&&(g=0),f=this.game.time.now+g}else f=this.game.time.now+this.fireRate;this.multiFire?this._hasFired||(this._hasFired=!0,this._tempNextFire=f,this.shots++):(this._nextFire=f,this.shots++),this.onFire.dispatch(d,this,o),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return d},i.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},i.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},i.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},i.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},i.Weapon.prototype.setBulletFrames=function(t,e,s,n){return void 0===s&&(s=!0),void 0===n&&(n=!1),this.bulletFrames=i.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=s,this.bulletFrameRandom=n,this},i.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},i.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(i.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets&&(this.bullets.classType=this._bulletClass)}}),Object.defineProperty(i.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case i.Weapon.KILL_STATIC_BOUNDS:case i.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case i.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case i.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(i.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(i.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(i.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),i.Bullet=function(t,e,s,n,r){i.Sprite.call(this,t,e,s,n,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},i.Bullet.prototype=Object.create(i.Sprite.prototype),i.Bullet.prototype.constructor=i.Bullet,i.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},i.Bullet.prototype.update=function(){this.exists&&(this.data.killType>i.Weapon.KILL_LIFESPAN&&(this.data.killType===i.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=this.body.velocity.atan()),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},i.Video=function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=i.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new i.Signal,this.onChangeSource=new i.Signal,this.onComplete=new i.Signal,this.onAccess=new i.Signal,this.onError=new i.Signal,this.onTimeout=new i.Signal,this.onTouchUnlock=new i.Signal,this.playWhenUnlocked=!0,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._pendingChangeSource=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var n=this.game.cache.getVideo(e);n.isBlob?this.createVideoFromBlob(n.data):this.video=n.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else s&&this.createVideoFromURL(s,!1);this.video&&!s?(this.baseTexture=new PIXI.BaseTexture(this.video,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(i.Cache.DEFAULT.baseTexture.source,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new i.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,i.BitmapData&&(this.snapshot=new i.BitmapData(this.game,"",this.width,this.height)),this.game.device.needsTouchUnlock()?this.setTouchLock():n&&(n.locked=!1)},i.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return this._pendingChangeSource?this:(void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this)},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming)},setTouchLock:function(){this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.playWhenUnlocked&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return this.onTouchUnlock.dispatch(this),!0},grab:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null!==this.snapshot)return t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot;console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable")},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(i.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(i.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(i.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(i.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(i.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(i.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(i.Video.prototype,"playing",{get:function(){return!!this.video&&!(this.video.paused&&this.video.ended)}}),i.Video.prototype.constructor=i.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=i.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=i.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new i.Matrix),PIXI.TextureSilentFail=!0,PIXI.canUseNewCanvasBlendModes=function(){return i.Device.canUseMultiply},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=i),exports.Phaser=i):"undefined"!=typeof define&&define.amd?define("Phaser",e.Phaser=i):e.Phaser=i,i}.call(this); +//# sourceMappingURL=phaser.map \ No newline at end of file diff --git a/Digital Assignment 4/sources.txt b/Digital Assignment 4/sources.txt new file mode 100644 index 000000000..0e9d99690 --- /dev/null +++ b/Digital Assignment 4/sources.txt @@ -0,0 +1,8 @@ +https://phaser.io/examples/v2/buttons/action-on-click +https://phaser.io/examples/v2/camera/smooth-follow +https://phaser.io/examples/v2/arcade-physics/bounce-accelerator +https://phaser.io/examples/v2/arcade-physics/on-collide-event +https://phaser.io/examples/v2/input/bounds-rect + + +https://www.leshylabs.com/apps/sstool/ diff --git a/Digital Assignment 5/assets/Arrow.png b/Digital Assignment 5/assets/Arrow.png new file mode 100644 index 000000000..47ac1568c Binary files /dev/null and b/Digital Assignment 5/assets/Arrow.png differ diff --git a/Digital Assignment 5/assets/Background.png b/Digital Assignment 5/assets/Background.png new file mode 100644 index 000000000..67728fb77 Binary files /dev/null and b/Digital Assignment 5/assets/Background.png differ diff --git a/Digital Assignment 5/assets/Border.png b/Digital Assignment 5/assets/Border.png new file mode 100644 index 000000000..af310ead3 Binary files /dev/null and b/Digital Assignment 5/assets/Border.png differ diff --git a/Digital Assignment 5/assets/Husky.png b/Digital Assignment 5/assets/Husky.png new file mode 100644 index 000000000..971469cf0 Binary files /dev/null and b/Digital Assignment 5/assets/Husky.png differ diff --git a/Digital Assignment 5/assets/Play.png b/Digital Assignment 5/assets/Play.png new file mode 100644 index 000000000..ba386c357 Binary files /dev/null and b/Digital Assignment 5/assets/Play.png differ diff --git a/Digital Assignment 5/index.html b/Digital Assignment 5/index.html new file mode 100644 index 000000000..c3870f468 --- /dev/null +++ b/Digital Assignment 5/index.html @@ -0,0 +1,138 @@ + + + + + Digital Assignment 5 + + + + + +
+
+

Digital Assignment 5

+
    +
  • Originality: + What is original about your game? +
  • +
      +
    • + It is a racing game but the player can change their character mid game. +
    • +
    +
  • Technical Merit: + What is interesting about your game technology? +
  • +
      +
    • + Can select a character and have camera focus on the character. +
    • +
    +
  • Prototype Postmortem: + What did you learn from this prototype? What was the easiest or hardest part of making it? +
  • +
      +
    • + I learned how to use spritesheets and tilemaps. Also learned how to use the camera in Phaser. +
    • +
    +
  • Prototype Assets: + Did you make your prototype assets from scratch? Did you borrow them? Cite your sources here. + + + + + +
      +
    • Husky Sprite: Husky
    • +
    +
  • Prototype Closest Other Game: + Which other game most closely resembles your game? If you are borrowing code from a Phaser Example, you must say so here. If you borrow code from elsewhere, you must say so here. +
  • +
      +
    • This game resembles a lot of concept from other racing games but the code itself is original.
    • +
    +
  • High Concept: + A one-sentence summary of your game. +
  • +
      +
    • Select a character and race to the finish line.
    • +
    +
  • Theme: + State which of the Storymatic themes you used. +
  • +
      +
    • Used the Ice theme from assignment 4
    • +
    +
  • Mandated Variety: + State which input, randomness, genre, and play style you used in this prototype. +
  • +
      +
    • User input from mouse clicks as well as arrow keys. The track is randomly generated. Genre would be racing/action.
    • +
    +
  • Prototype Goal: + What game mechanic is this prototype evaluating? +
  • +
      +
    • This prototype is evaluating whether randomness is appropriate for a racing game.
    • +
    +
  • Player Experience Goals: + What experience do you want players to have when playing your game? +
  • +
      +
    • Satisfaction for making the right decision.
    • +
    +
  • Gameplay: + A paragraph describing the actions the player can perform, the system dynamics, and the core mechanic. Include a concise explanation of the prototype’s inputs and their expected effects (how to play). You can also describe game play that is not in the prototype. You may include mock-up images for parts of the game not in the prototype. +
  • +
      +
    • The player choses a character before the game begins. Once the game begins, the player has to move their character along the track without colliding to the walls.
    • +
    +
  • Strategies: + What player strategies do you expect will be effective at playing this game? +
  • +
      +
    • Players need to be good at moving their character without crashing.
    • +
    +
  • Story/Setting/Premise: + A paragraph about the world your game is set in and who the characters are. What makes the game world and its occupants unique and interesting? Do the tokens represent something? If the game has a backstory, mention it here. If the game is abstract, then say so. + How will the dramatic tension interact with the gameplay tension? +
  • +
      +
    • No Story for this game.
    • +
    +
  • Target Audience: + A single sentence that describes the demographic you're trying to reach. +
  • +
      +
    • Preferably all ages.
    • +
    +
  • Play Time: + How long does your game take to play? +
  • +
      +
    • This prototype should take less than a minute.
    • +
    +
+ + \ No newline at end of file diff --git a/Digital Assignment 5/js/main.js b/Digital Assignment 5/js/main.js new file mode 100644 index 000000000..ed2ba59ed --- /dev/null +++ b/Digital Assignment 5/js/main.js @@ -0,0 +1,526 @@ +"use strict"; + +window.onload = function() +{ + // You can copy-and-paste the code from any of the examples at http://examples.phaser.io here. + // You will need to change the fourth parameter to "new Phaser.Game()" from + // 'phaser-example' to 'game', which is the id of the HTML element where we + // want the game to go. + // The assets (and code) can be found at: https://github.com/photonstorm/phaser/tree/master/examples/assets + // You will need to change the paths you pass to "game.load.image()" or any other + // loading functions to reflect where you are putting the assets. + // All loading functions will typically all be found inside "preload()". + + // mods by Patrick OReilly + // twitter: @pato_reilly + + var game = new Phaser.Game(900, 600, Phaser.CANVAS, 'game', { preload: preload, create: create, update: update, render: render }); + + function preload() + { + game.load.spritesheet('button', 'assets/Play.png', 200, 90); + game.load.spritesheet('arrow', 'assets/Arrow.png', 101, 50); + game.load.image('background','assets/Background.png'); + game.load.spritesheet('husky','assets/Husky.png', 90, 58, 3); + game.load.spritesheet('border','assets/Border.png', 500, 2); + + } + + var button1; + var button2; + var button3; + var button4; + var button5; + var button_play; + + var text; + var text2; + + var husky1; + var husky2; + var husky3; + var husky4; + var husky5; + + var boundaries; + var huskies; + + var bound1; + var bound2; + var bound3; + var bound4; + var bound5; + var bound6; + + var bound7; + var bound8; + var finish; + + var player; + var cursors; + var input = -1; + var rng = Math.floor(Math.random() * 5) + 1; + + function create() + { + game.add.tileSprite(0, 0, 1800, 600, 'background'); + game.world.setBounds(0, 0, 1800, 500); + game.physics.startSystem(Phaser.Physics.P2JS); + game.physics.p2.setImpactEvents(true); + + boundaries = game.physics.p2.createCollisionGroup(); + huskies = game.physics.p2.createCollisionGroup(); + game.physics.p2.updateBoundsCollisionGroup(); + + var boundary = game.add.group(); + boundary.enableBody = true; + boundary.physicsBodyType = Phaser.Physics.P2JS; + + bound1 = boundary.create(100, 0, 'border'); + bound1.body.setRectangle(500, 2); + bound2 = boundary.create(100, 100, 'border'); + bound2.body.setRectangle(500, 2); + bound3 = boundary.create(100, 200, 'border'); + bound3.body.setRectangle(500, 2); + bound4 = boundary.create(100, 300, 'border'); + bound4.body.setRectangle(500, 2); + bound5 = boundary.create(100, 400, 'border'); + bound5.body.setRectangle(500, 2); + bound6 = boundary.create(100, 500, 'border'); + bound6.body.setRectangle(500, 2); + + bound1.body.setCollisionGroup(boundaries); + bound2.body.setCollisionGroup(boundaries); + bound3.body.setCollisionGroup(boundaries); + bound4.body.setCollisionGroup(boundaries); + bound5.body.setCollisionGroup(boundaries); + bound6.body.setCollisionGroup(boundaries); + + bound1.body.collides([boundaries, huskies]); + bound2.body.collides([boundaries, huskies]); + bound3.body.collides([boundaries, huskies]); + bound4.body.collides([boundaries, huskies]); + bound5.body.collides([boundaries, huskies]); + bound6.body.collides([boundaries, huskies]); + + var husky = game.add.group(); + husky.enableBody = true; + husky.physicsBodyType = Phaser.Physics.P2JS; + + husky1 = husky.create(150, 30, 'husky', 10); + husky1.body.setRectangle(90, 40); + husky2 = husky.create(150, 130, 'husky', 10); + husky2.body.setRectangle(90, 40); + husky3 = husky.create(150, 230, 'husky', 10); + husky3.body.setRectangle(90, 40); + husky4 = husky.create(150, 330, 'husky', 10); + husky4.body.setRectangle(90, 40); + husky5 = husky.create(150, 430, 'husky', 10); + husky5.body.setRectangle(90, 40); + + + /* + husky1 = game.add.sprite(150, 30, 'husky', 10); + husky2 = game.add.sprite(150, 130, 'husky', 10); + husky3 = game.add.sprite(150, 230, 'husky', 10); + husky4 = game.add.sprite(150, 330, 'husky', 10); + husky5 = game.add.sprite(150, 430, 'husky', 10); + */ + + /* + husky1.animations.add('wag'); + husky1.animations.play('wag', 8, true); + husky2.animations.add('wag'); + husky2.animations.play('wag', 8, true); + husky3.animations.add('wag'); + husky3.animations.play('wag', 8, true); + husky4.animations.add('wag'); + husky4.animations.play('wag', 8, true); + husky5.animations.add('wag'); + husky5.animations.play('wag', 8, true); + */ + + /* + huskies = game.add.group(); + huskies.add(husky1); + huskies.add(husky2); + huskies.add(husky3); + huskies.add(husky4); + huskies.add(husky5); + */ + husky1.body.setCollisionGroup(huskies); + husky2.body.setCollisionGroup(huskies); + husky3.body.setCollisionGroup(huskies); + husky4.body.setCollisionGroup(huskies); + husky5.body.setCollisionGroup(huskies); + + husky1.body.collides(boundaries, slow_down, this); + husky2.body.collides(boundaries, slow_down, this); + husky3.body.collides(boundaries, slow_down, this); + husky4.body.collides(boundaries, slow_down, this); + husky5.body.collides(boundaries, slow_down, this); + + //game.physics.p2.enable(huskies); + + //game.physics.arcade.enable(boundaries); + + //game.physics.p2.enable(bound1); + + + //game.physics.p2.enable(bound2); + + //bound2.body.kinematic = false; + //game.physics.p2.enable(bound3); + //game.physics.p2.enable(bound4); + //game.physics.p2.enable(bound5); + //game.physics.p2.enable(bound6); + + + /* + bound1.enableBody = true; + bound2.enableBody = true; + bound3.enableBody = true; + bound4.enableBody = true; + bound5.enableBody = true; + bound6.enableBody = true; + */ + + /* + bound1.body.immovable = true; + bound2.body.immovable = true; + bound3.body.immovable = true; + bound4.body.immovable = true; + bound5.body.immovable = true; + bound6.body.immovable = true; + + bound1.body.moves = false; + bound2.body.moves = false; + bound3.body.moves = false; + bound4.body.moves = false; + bound5.body.moves = false; + bound6.body.moves = false; + + bound1.body.allowGravity = false; + bound2.body.allowGravity = false; + bound3.body.allowGravity = false; + bound4.body.allowGravity = false; + bound5.body.allowGravity = false; + bound6.body.allowGravity = false; + */ + + cursors = game.input.keyboard.createCursorKeys(); + + // new Button(game [, x] [, y] [, key] [, callback] [, callbackContext] [, overFrame] [, outFrame] [, downFrame] [, upFrame]) + button1 = game.add.button(0, 25, 'arrow', actionOnClick1, this, 0, 1, 0); + button2 = game.add.button(0, 125, 'arrow', actionOnClick2, this, 0, 1, 0); + button3 = game.add.button(0, 225, 'arrow', actionOnClick3, this, 0, 1, 0); + button4 = game.add.button(0, 325, 'arrow', actionOnClick4, this, 0, 1, 0); + button5 = game.add.button(0, 425, 'arrow', actionOnClick5, this, 0, 1, 0); + button_play = game.add.button(150, 510, 'button', click_play, this, 0, 0, 1, 0); + button_play.visible = false; + + + + button1.onInputOver.add(over, this); + button1.onInputOut.add(out, this); + button1.onInputUp.add(up, this); + + button2.onInputOver.add(over, this); + button2.onInputOut.add(out, this); + button2.onInputUp.add(up, this); + + button3.onInputOver.add(over, this); + button3.onInputOut.add(out, this); + button3.onInputUp.add(up, this); + + button4.onInputOver.add(over, this); + button4.onInputOut.add(out, this); + button4.onInputUp.add(up, this); + + button5.onInputOver.add(over, this); + button5.onInputOut.add(out, this); + button5.onInputUp.add(up, this); + + text = game.add.text(100, 520, 'Select one of the 5 Arrows to choose your character.'); + text.font = 'Arial Black'; + text.fill = '#000000'; + + text2 = game.add.text(100, 520, 'Use the arrow keys to move your character'); + text2.visible = false; + text2.font = 'Arial Black'; + text2.fill = '#000000'; + } + + function update() + { + if (player != null) + { + player.body.setZeroVelocity(); + + if (cursors.up.isDown) + { + player.body.moveUp(300) + } + else if (cursors.down.isDown) + { + player.body.moveDown(300); + } + + if (cursors.left.isDown) + { + player.body.velocity.x = -300; + } + else if (cursors.right.isDown) + { + player.body.moveRight(300); + } + } + + game.physics.arcade.collide(huskies, boundaries, slow_down, null, this); + } + + function render() + { + //game.debug.cameraInfo(game.camera, 32, 32); + } + + function up() + { + console.log('button up', arguments); + } + + function over() + { + console.log('button over'); + } + + function out() + { + console.log('button out'); + } + + function actionOnClick1() + { + console.log('click 1'); + + button1.setFrames(1, 0, 0, 0); + + switch (input) + { + case 2: + button2.setFrames(0, 1, 0); + button2.inputEnabled = true; + break; + case 3: + button3.setFrames(0, 1, 0); + button3.inputEnabled = true; + break; + case 4: + button4.setFrames(0, 1, 0); + button4.inputEnabled = true; + break; + case 5: + button5.setFrames(0, 1, 0); + button5.inputEnabled = true; + break; + default: + break; + } + + button1.inputEnabled = false; + input = 1; + text.visible = false; + button_play.visible = true; + + } + + function actionOnClick2() + { + console.log('click 2'); + + button2.setFrames(1, 0, 0, 0); + + switch (input) + { + case 1: + button1.setFrames(0, 1, 0); + button1.inputEnabled = true; + break; + case 3: + button3.setFrames(0, 1, 0); + button3.inputEnabled = true; + break; + case 4: + button4.setFrames(0, 1, 0); + button4.inputEnabled = true; + break; + case 5: + button5.setFrames(0, 1, 0); + button5.inputEnabled = true; + break; + default: + break; + } + + button2.inputEnabled = false; + input = 2; + text.visible = false; + button_play.visible = true; + } + + function actionOnClick3() + { + console.log('click 3'); + + button3.setFrames(1, 0, 0, 0); + + switch (input) + { + case 1: + button1.setFrames(0, 1, 0); + button1.inputEnabled = true; + break; + case 2: + button2.setFrames(0, 1, 0); + button2.inputEnabled = true; + break; + case 4: + button4.setFrames(0, 1, 0); + button4.inputEnabled = true; + break; + case 5: + button5.setFrames(0, 1, 0); + button5.inputEnabled = true; + break; + default: + break; + } + + button3.inputEnabled = false; + input = 3; + text.visible = false; + button_play.visible = true; + } + + function actionOnClick4() + { + console.log('click 4'); + + button4.setFrames(1, 0, 0, 0); + + switch (input) + { + case 1: + button1.setFrames(0, 1, 0); + button1.inputEnabled = true; + break; + case 2: + button2.setFrames(0, 1, 0); + button2.inputEnabled = true; + break; + case 3: + button3.setFrames(0, 1, 0); + button3.inputEnabled = true; + break; + case 5: + button5.setFrames(0, 1, 0); + button5.inputEnabled = true; + break; + default: + break; + } + + button4.inputEnabled = false; + input = 4; + text.visible = false; + button_play.visible = true; + } + + function actionOnClick5() + { + console.log('click 5'); + + button5.setFrames(1, 0, 0, 0); + + switch (input) + { + case 1: + button1.setFrames(0, 1, 0); + button1.inputEnabled = true; + break; + case 2: + button2.setFrames(0, 1, 0); + button2.inputEnabled = true; + break; + case 3: + button3.setFrames(0, 1, 0); + button3.inputEnabled = true; + break; + case 4: + button4.setFrames(0, 1, 0); + button4.inputEnabled = true; + break; + default: + break; + } + + button5.inputEnabled = false; + input = 5; + text.visible = false; + button_play.visible = true; + } + + function click_play() + { + console.log("Play"); + + if (input == -1) + { + //Do nothing. + } + else + { + switch (input) + { + case 1: + player = husky1; + break; + case 2: + player = husky2; + break; + case 3: + player = husky3; + break; + case 4: + player = husky4; + break; + case 5: + player = husky5; + break; + default: + break; + } + + button_play.inputEnabled = false; + button_play.visible = false; + text2.visible = true; + // Notice that the sprite doesn't have any momentum at all, + // it's all just set by the camera follow type. + // 0.1 is the amount of linear interpolation to use. + // The smaller the value, the smooth the camera (and the longer it takes to catch up) + game.camera.follow(player, Phaser.Camera.FOLLOW_LOCKON, 0.1, 0.1); + player.body.fixedRotation = true; + + husky1.body.moveRight(300); + husky2.body.moveRight(300); + husky3.body.moveRight(300); + husky4.body.moveRight(300); + husky5.body.moveRight(300); + } + } + + function slow_down() + { + console.log('Collision'); + } +}; \ No newline at end of file diff --git a/Digital Assignment 5/js/phaser.js b/Digital Assignment 5/js/phaser.js new file mode 100644 index 000000000..3bac171a7 --- /dev/null +++ b/Digital Assignment 5/js/phaser.js @@ -0,0 +1,107825 @@ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +* +* @overview +* +* Phaser - http://phaser.io +* +* v2.10.0 "2018-01-18" - Built: Thu Jan 18 2018 16:35:03 +* +* By Richard Davey http://www.photonstorm.com @photonstorm +* +* Phaser is a fun, free and fast 2D game framework for making HTML5 games +* for desktop and mobile web browsers, supporting Canvas and WebGL rendering. +* +* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23 +* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe +* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com +* +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate. +* +* Follow development at http://phaser.io and on our forum +* +* "If you want your children to be intelligent, read them fairy tales." +* "If you want them to be more intelligent, read them more fairy tales." +* -- Albert Einstein +*/ + +/** + * The MIT License (MIT) + * + * Copyright (c) 2015 p2.js authors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=0 && s<=1 && t>=0 && t<=1); +}; + + +},{"./Scalar":4}],2:[function(_dereq_,module,exports){ +module.exports = Point; + +/** + * Point related functions + * @class Point + */ +function Point(){}; + +/** + * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. + * @static + * @method area + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +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 = []; + +/** + * Check if three points are collinear + * @method collinear + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. + * @return {Boolean} + */ +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 angle < thresholdAngle; + } +}; + +Point.sqdist = function(a,b){ + var dx = b[0] - a[0]; + var dy = b[1] - a[1]; + return dx * dx + dy * dy; +}; + +},{}],3:[function(_dereq_,module,exports){ +var Line = _dereq_("./Line") +, Point = _dereq_("./Point") +, Scalar = _dereq_("./Scalar") + +module.exports = Polygon; + +/** + * Polygon class. + * @class Polygon + * @constructor + */ +function Polygon(){ + + /** + * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] + * @property vertices + * @type {Array} + */ + this.vertices = []; +} + +/** + * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. + * @method at + * @param {Number} i + * @return {Array} + */ +Polygon.prototype.at = function(i){ + var v = this.vertices, + s = v.length; + return v[i < 0 ? i % s + s : i % s]; +}; + +/** + * Get first vertex + * @method first + * @return {Array} + */ +Polygon.prototype.first = function(){ + return this.vertices[0]; +}; + +/** + * Get last vertex + * @method last + * @return {Array} + */ +Polygon.prototype.last = function(){ + return this.vertices[this.vertices.length-1]; +}; + +/** + * Clear the polygon data + * @method clear + * @return {Array} + */ +Polygon.prototype.clear = function(){ + this.vertices.length = 0; +}; + +/** + * Append points "from" to "to"-1 from an other polygon "poly" onto this one. + * @method append + * @param {Polygon} poly The polygon to get points from. + * @param {Number} from The vertex index in "poly". + * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. + * @return {Array} + */ +Polygon.prototype.append = function(poly,from,to){ + if(typeof(from) == "undefined") throw new Error("From is not given!"); + if(typeof(to) == "undefined") throw new Error("To is not given!"); + + if(to-1 < from) throw new Error("lol1"); + if(to > poly.vertices.length) throw new Error("lol2"); + if(from < 0) throw new Error("lol3"); + + for(var i=from; i v[br][0])) { + br = i; + } + } + + // reverse poly if clockwise + if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { + this.reverse(); + } +}; + +/** + * Reverse the vertices in the polygon + * @method 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; +}; + +/** + * Check if a point in the polygon is a reflex point + * @method isReflex + * @param {Number} i + * @return {Boolean} + */ +Polygon.prototype.isReflex = function(i){ + return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); +}; + +var tmpLine1=[], + tmpLine2=[]; + +/** + * Check if two vertices in the polygon can see each other + * @method canSee + * @param {Number} a Vertex index 1 + * @param {Number} b Vertex index 2 + * @return {Boolean} + */ +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) { // for each edge + if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges + 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))) { // if diag intersects an edge + 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) < dist) { // if edge is blocking visibility to b + return false; + } + } + } + + return true; +}; + +/** + * Copy the polygon from vertex i to vertex j. + * @method copy + * @param {Number} i + * @param {Number} j + * @param {Polygon} [targetPoly] Optional target polygon to save in. + * @return {Polygon} The resulting copy. + */ +Polygon.prototype.copy = function(i,j,targetPoly){ + var p = targetPoly || new Polygon(); + p.clear(); + if (i < j) { + // Insert all vertices from i to j + for(var k=i; k<=j; k++) + p.vertices.push(this.vertices[k]); + + } else { + + // Insert vertices 0 to j + for(var k=0; k<=j; k++) + p.vertices.push(this.vertices[k]); + + // Insert vertices i to end + for(var k=i; k 0) + return this.slice(edges); + else + return [this]; +}; + +/** + * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. + * @method slice + * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() + * @return {Array} + */ +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; i maxlevel){ + console.warn("quickDecomp: max level ("+maxlevel+") reached."); + return result; + } + + for (var i = 0; i < this.vertices.length; ++i) { + if (poly.isReflex(i)) { + reflexVertices.push(poly.vertices[i]); + upperDist = lowerDist = Number.MAX_VALUE; + + + for (var j = 0; j < this.vertices.length; ++j) { + if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge + p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection + if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly + d = Point.sqdist(poly.vertices[i], p); + if (d < lowerDist) { // keep only the closest intersection + lowerDist = d; + lowerInt = p; + lowerIndex = j; + } + } + } + if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); + if (Point.left(poly.at(i - 1), poly.at(i), p)) { + d = Point.sqdist(poly.vertices[i], p); + if (d < upperDist) { + upperDist = d; + upperInt = p; + upperIndex = j; + } + } + } + } + + // if there are no vertices to connect to, choose a point in the middle + if (lowerIndex == (upperIndex + 1) % this.vertices.length) { + //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); + p[0] = (lowerInt[0] + upperInt[0]) / 2; + p[1] = (lowerInt[1] + upperInt[1]) / 2; + steinerPoints.push(p); + + if (i < upperIndex) { + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); + lowerPoly.append(poly, i, upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + if (lowerIndex != 0){ + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); + upperPoly.append(poly,lowerIndex,poly.vertices.length); + } + //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); + lowerPoly.append(poly,i,poly.vertices.length); + } + //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); + lowerPoly.append(poly,0,upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); + upperPoly.append(poly,lowerIndex,i+1); + } + } else { + // connect to the closest point within the triangle + //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); + + if (lowerIndex > upperIndex) { + upperIndex += this.vertices.length; + } + closestDist = Number.MAX_VALUE; + + if(upperIndex < lowerIndex){ + return result; + } + + for (var j = lowerIndex; j <= upperIndex; ++j) { + if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + d = Point.sqdist(poly.at(i), poly.at(j)); + if (d < closestDist) { + closestDist = d; + closestIndex = j % this.vertices.length; + } + } + } + + if (i < closestIndex) { + lowerPoly.append(poly,i,closestIndex+1); + if (closestIndex != 0){ + upperPoly.append(poly,closestIndex,v.length); + } + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + lowerPoly.append(poly,i,v.length); + } + lowerPoly.append(poly,0,closestIndex+1); + upperPoly.append(poly,closestIndex,i+1); + } + } + + // solve smallest poly first + if (lowerPoly.vertices.length < upperPoly.vertices.length) { + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } else { + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } + + return result; + } + } + result.push(this); + + return result; +}; + +/** + * Remove collinear points in the polygon. + * @method removeCollinearPoints + * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. + * @return {Number} The number of points removed + */ +Polygon.prototype.removeCollinearPoints = function(precision){ + var num = 0; + for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ + if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ + // Remove the middle point + this.vertices.splice(i%this.vertices.length,1); + i--; // Jump one point forward. Otherwise we may get a chain removal + num++; + } + } + return num; +}; + +},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){ +module.exports = Scalar; + +/** + * Scalar functions + * @class Scalar + */ +function Scalar(){} + +/** + * Check if two scalars are equal + * @static + * @method eq + * @param {Number} a + * @param {Number} b + * @param {Number} [precision] + * @return {Boolean} + */ +Scalar.eq = function(a,b,precision){ + precision = precision || 0; + return Math.abs(a-b) < precision; +}; + +},{}],5:[function(_dereq_,module,exports){ +module.exports = { + Polygon : _dereq_("./Polygon"), + Point : _dereq_("./Point"), +}; + +},{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){ +module.exports={ + "name": "p2", + "version": "0.7.1", + "description": "A JavaScript 2D physics engine.", + "author": "Stefan Hedman (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.5", + "grunt-contrib-jshint": "^0.11.2", + "grunt-contrib-nodeunit": "^0.4.1", + "grunt-contrib-uglify": "~0.4.0", + "grunt-contrib-watch": "~0.5.0", + "grunt-browserify": "~2.0.1", + "grunt-contrib-concat": "^0.4.0" + }, + "dependencies": { + "poly-decomp": "0.1.1" + } +} + +},{}],7:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = AABB; + +/** + * Axis aligned bounding box class. + * @class AABB + * @constructor + * @param {Object} [options] + * @param {Array} [options.upperBound] + * @param {Array} [options.lowerBound] + */ +function AABB(options){ + + /** + * The lower bound of the bounding box. + * @property lowerBound + * @type {Array} + */ + this.lowerBound = vec2.create(); + if(options && options.lowerBound){ + vec2.copy(this.lowerBound, options.lowerBound); + } + + /** + * The upper bound of the bounding box. + * @property upperBound + * @type {Array} + */ + this.upperBound = vec2.create(); + if(options && options.upperBound){ + vec2.copy(this.upperBound, options.upperBound); + } +} + +var tmp = vec2.create(); + +/** + * Set the AABB bounds from a set of points, transformed by the given position and angle. + * @method setFromPoints + * @param {Array} points An array of vec2's. + * @param {Array} position + * @param {number} angle + * @param {number} skinSize Some margin to be added to the AABB. + */ +AABB.prototype.setFromPoints = function(points, position, angle, skinSize){ + var l = this.lowerBound, + u = this.upperBound; + + if(typeof(angle) !== "number"){ + angle = 0; + } + + // Set to the first point + if(angle !== 0){ + vec2.rotate(l, points[0], angle); + } else { + vec2.copy(l, points[0]); + } + vec2.copy(u, l); + + // Compute cosines and sines just once + var cosAngle = Math.cos(angle), + sinAngle = Math.sin(angle); + for(var i = 1; i u[j]){ + u[j] = p[j]; + } + if(p[j] < l[j]){ + l[j] = p[j]; + } + } + } + + // Add offset + if(position){ + vec2.add(this.lowerBound, this.lowerBound, position); + vec2.add(this.upperBound, this.upperBound, position); + } + + if(skinSize){ + this.lowerBound[0] -= skinSize; + this.lowerBound[1] -= skinSize; + this.upperBound[0] += skinSize; + this.upperBound[1] += skinSize; + } +}; + +/** + * Copy bounds from an AABB to this AABB + * @method copy + * @param {AABB} aabb + */ +AABB.prototype.copy = function(aabb){ + vec2.copy(this.lowerBound, aabb.lowerBound); + vec2.copy(this.upperBound, aabb.upperBound); +}; + +/** + * Extend this AABB so that it covers the given AABB too. + * @method extend + * @param {AABB} aabb + */ +AABB.prototype.extend = function(aabb){ + // Loop over x and y + var i = 2; + while(i--){ + // Extend lower bound + var l = aabb.lowerBound[i]; + if(this.lowerBound[i] > l){ + this.lowerBound[i] = l; + } + + // Upper + var u = aabb.upperBound[i]; + if(this.upperBound[i] < u){ + this.upperBound[i] = u; + } + } +}; + +/** + * Returns true if the given AABB overlaps this AABB. + * @method overlaps + * @param {AABB} aabb + * @return {Boolean} + */ +AABB.prototype.overlaps = function(aabb){ + var l1 = this.lowerBound, + u1 = this.upperBound, + l2 = aabb.lowerBound, + u2 = aabb.upperBound; + + // l2 u2 + // |---------| + // |--------| + // l1 u1 + + 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])); +}; + +/** + * @method containsPoint + * @param {Array} point + * @return {boolean} + */ +AABB.prototype.containsPoint = function(point){ + var l = this.lowerBound, + u = this.upperBound; + return l[0] <= point[0] && point[0] <= u[0] && l[1] <= point[1] && point[1] <= u[1]; +}; + +/** + * Check if the AABB is hit by a ray. + * @method overlapsRay + * @param {Ray} ray + * @return {number} -1 if no hit, a number between 0 and 1 if hit. + */ +AABB.prototype.overlapsRay = function(ray){ + var t = 0; + + // ray.direction is unit direction vector of ray + var dirFracX = 1 / ray.direction[0]; + var dirFracY = 1 / ray.direction[1]; + + // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner + var t1 = (this.lowerBound[0] - ray.from[0]) * dirFracX; + var t2 = (this.upperBound[0] - ray.from[0]) * dirFracX; + var t3 = (this.lowerBound[1] - ray.from[1]) * dirFracY; + var t4 = (this.upperBound[1] - ray.from[1]) * dirFracY; + + var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4))); + var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4))); + + // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us + if (tmax < 0){ + //t = tmax; + return -1; + } + + // if tmin > tmax, ray doesn't intersect AABB + if (tmin > tmax){ + //t = tmax; + return -1; + } + + return tmin; +}; +},{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Body = _dereq_('../objects/Body'); + +module.exports = Broadphase; + +/** + * Base class for broadphase implementations. + * @class Broadphase + * @constructor + */ +function Broadphase(type){ + + this.type = type; + + /** + * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). + * @property result + * @type {Array} + */ + this.result = []; + + /** + * The world to search for collision pairs in. To change it, use .setWorld() + * @property world + * @type {World} + * @readOnly + */ + this.world = null; + + /** + * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE. + * @property {Number} boundingVolumeType + */ + this.boundingVolumeType = Broadphase.AABB; +} + +/** + * Axis aligned bounding box type. + * @static + * @property {Number} AABB + */ +Broadphase.AABB = 1; + +/** + * Bounding circle type. + * @static + * @property {Number} BOUNDING_CIRCLE + */ +Broadphase.BOUNDING_CIRCLE = 2; + +/** + * Set the world that we are searching for collision pairs in. + * @method setWorld + * @param {World} world + */ +Broadphase.prototype.setWorld = function(world){ + this.world = world; +}; + +/** + * Get all potential intersecting body pairs. + * @method getCollisionPairs + * @param {World} world The world to search in. + * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). + */ +Broadphase.prototype.getCollisionPairs = function(world){}; + +var dist = vec2.create(); + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.aabbCheck = function(bodyA, bodyB){ + return bodyA.getAABB().overlaps(bodyB.getAABB()); +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether two bodies are allowed to collide at all. + * @method canCollide + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.canCollide = function(bodyA, bodyB){ + var KINEMATIC = Body.KINEMATIC; + var STATIC = Body.STATIC; + + // Cannot collide static bodies + if(bodyA.type === STATIC && bodyB.type === STATIC){ + return false; + } + + // Cannot collide static vs kinematic bodies + if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) || + (bodyA.type === STATIC && bodyB.type === KINEMATIC)){ + return false; + } + + // Cannot collide kinematic vs kinematic + if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){ + return false; + } + + // Cannot collide both sleeping bodies + if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ + return false; + } + + // Cannot collide if one is static and the other is sleeping + if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === STATIC) || + (bodyB.sleepState === Body.SLEEPING && bodyA.type === STATIC)){ + return false; + } + + return true; +}; + +Broadphase.NAIVE = 1; +Broadphase.SAP = 2; + +},{"../math/vec2":30,"../objects/Body":31}],9:[function(_dereq_,module,exports){ +var Circle = _dereq_('../shapes/Circle'), + Plane = _dereq_('../shapes/Plane'), + Shape = _dereq_('../shapes/Shape'), + Particle = _dereq_('../shapes/Particle'), + Broadphase = _dereq_('../collision/Broadphase'), + vec2 = _dereq_('../math/vec2'); + +module.exports = NaiveBroadphase; + +/** + * Naive broadphase implementation. Does N^2 tests. + * + * @class NaiveBroadphase + * @constructor + * @extends Broadphase + */ +function NaiveBroadphase(){ + Broadphase.call(this, Broadphase.NAIVE); +} +NaiveBroadphase.prototype = new Broadphase(); +NaiveBroadphase.prototype.constructor = NaiveBroadphase; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +NaiveBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = world.bodies, + result = this.result; + + result.length = 0; + + for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ + var bi = bodies[i]; + + for(var j=0; j pos0 && pos < pos1){ + // We got contact! + + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape); + + vec2.scale(c.normalA, orthoDist, -1); + vec2.normalize(c.normalA, c.normalA); + + vec2.scale( c.contactPointA, c.normalA, circleRadius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + sub(c.contactPointB, projectedPoint, lineOffset); + add(c.contactPointB, c.contactPointB, lineOffset); + sub(c.contactPointB, c.contactPointB, lineBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; + } + } + + // Add corner + verts[0] = worldVertex0; + verts[1] = worldVertex1; + + for(var i=0; i 0){ + for(var i=0; i Math.pow(r,2)){ + return 0; + } + + if(justTest){ + return true; + } + + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + 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; +}; + +/** + * Plane/Convex Narrowphase + * @method planeConvex + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} convexBody + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = +Narrowphase.prototype[Shape.PLANE | Shape.BOX] = +Narrowphase.prototype.planeConvex = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + convexBody, + convexShape, + convexOffset, + convexAngle, + justTest +){ + var worldVertex = tmp1, + worldNormal = tmp2, + dist = tmp3; + + var numReported = 0; + vec2.rotate(worldNormal, yAxis, planeAngle); + + for(var i=0; i!==convexShape.vertices.length; i++){ + var v = convexShape.vertices[i]; + vec2.rotate(worldVertex, v, convexAngle); + add(worldVertex, worldVertex, convexOffset); + + sub(dist, worldVertex, planeOffset); + + if(dot(dist,worldNormal) <= 0){ + + if(justTest){ + return true; + } + + // Found vertex + numReported++; + + var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); + + sub(dist, worldVertex, planeOffset); + + vec2.copy(c.normalA, worldNormal); + + var d = dot(dist, c.normalA); + vec2.scale(dist, c.normalA, d); + + // rj is from convex center to contact + sub(c.contactPointB, worldVertex, convexBody.position); + + + // ri is from plane center to contact + sub( c.contactPointA, worldVertex, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + this.contactEquations.push(c); + + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numReported){ + this.frictionEquations.push(this.createFrictionFromAverage(numReported)); + } + } + + return numReported; +}; + +/** + * Narrowphase for particle vs plane + * @method particlePlane + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = +Narrowphase.prototype.particlePlane = function( + particleBody, + particleShape, + particleOffset, + particleAngle, + planeBody, + planeShape, + planeOffset, + planeAngle, + justTest +){ + var dist = tmp1, + worldNormal = tmp2; + + planeAngle = planeAngle || 0; + + sub(dist, particleOffset, planeOffset); + vec2.rotate(worldNormal, yAxis, planeAngle); + + var d = dot(dist, worldNormal); + + if(d > 0){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape); + + vec2.copy(c.normalA, worldNormal); + vec2.scale( dist, c.normalA, d ); + // dist is now the distance vector in the normal direction + + // ri is the particle position projected down onto the plane, from the plane center + sub( c.contactPointA, particleOffset, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + // rj is from the body center to the particle center + sub( c.contactPointB, particleOffset, particleBody.position ); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + return 1; +}; + +/** + * Circle/Particle Narrowphase + * @method circleParticle + * @param {Body} circleBody + * @param {Circle} circleShape + * @param {Array} circleOffset + * @param {Number} circleAngle + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = +Narrowphase.prototype.circleParticle = function( + circleBody, + circleShape, + circleOffset, + circleAngle, + particleBody, + particleShape, + particleOffset, + particleAngle, + justTest +){ + var dist = tmp1; + + sub(dist, particleOffset, circleOffset); + if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape); + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + // Vector from circle to contact point is the normal times the circle radius + vec2.scale(c.contactPointA, c.normalA, circleShape.radius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + // Vector from particle center to contact point is zero + sub(c.contactPointB, particleOffset, particleBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; +}; + +var planeCapsule_tmpCircle = new Circle({ radius: 1 }), + planeCapsule_tmp1 = vec2.create(), + planeCapsule_tmp2 = vec2.create(), + planeCapsule_tmp3 = vec2.create(); + +/** + * @method planeCapsule + * @param {Body} planeBody + * @param {Circle} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} capsuleBody + * @param {Particle} capsuleShape + * @param {Array} capsuleOffset + * @param {Number} capsuleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = +Narrowphase.prototype.planeCapsule = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + capsuleBody, + capsuleShape, + capsuleOffset, + capsuleAngle, + justTest +){ + var end1 = planeCapsule_tmp1, + end2 = planeCapsule_tmp2, + circle = planeCapsule_tmpCircle, + dst = planeCapsule_tmp3; + + // Compute world end positions + vec2.set(end1, -capsuleShape.length/2, 0); + vec2.rotate(end1,end1,capsuleAngle); + add(end1,end1,capsuleOffset); + + vec2.set(end2, capsuleShape.length/2, 0); + vec2.rotate(end2,end2,capsuleAngle); + add(end2,end2,capsuleOffset); + + circle.radius = capsuleShape.radius; + + var enableFrictionBefore; + + // Temporarily turn off friction + if(this.enableFrictionReduction){ + enableFrictionBefore = this.enableFriction; + this.enableFriction = false; + } + + // Do Narrowphase as two circles + var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest), + numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest); + + // Restore friction + if(this.enableFrictionReduction){ + this.enableFriction = enableFrictionBefore; + } + + if(justTest){ + return numContacts1 || numContacts2; + } else { + var numTotal = numContacts1 + numContacts2; + if(this.enableFrictionReduction){ + if(numTotal){ + this.frictionEquations.push(this.createFrictionFromAverage(numTotal)); + } + } + return numTotal; + } +}; + +/** + * Creates ContactEquations and FrictionEquations for a collision. + * @method circlePlane + * @param {Body} bi The first body that should be connected to the equations. + * @param {Circle} si The circle shape participating in the collision. + * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. + * @param {Body} bj The second body that should be connected to the equations. + * @param {Plane} sj The Plane shape that is participating + * @param {Array} xj Extra offset for the plane shape. + * @param {Number} aj Extra angle to apply to the plane + */ +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, // Offset from body center, rotated! + planeBody = bj, + shapeB = sj, + planeOffset = xj, + planeAngle = aj; + + planeAngle = planeAngle || 0; + + // Vector from plane to circle + var planeToCircle = tmp1, + worldNormal = tmp2, + temp = tmp3; + + sub(planeToCircle, circleOffset, planeOffset); + + // World plane normal + vec2.rotate(worldNormal, yAxis, planeAngle); + + // Normal direction distance + var d = dot(worldNormal, planeToCircle); + + if(d > circleShape.radius){ + return 0; // No overlap. Abort. + } + + if(justTest){ + return true; + } + + // Create contact + var contact = this.createContactEquation(planeBody,circleBody,sj,si); + + // ni is the plane world normal + vec2.copy(contact.normalA, worldNormal); + + // rj is the vector from circle center to the contact point + vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); + add(contact.contactPointB, contact.contactPointB, circleOffset); + sub(contact.contactPointB, contact.contactPointB, circleBody.position); + + // ri is the distance from plane center to contact. + vec2.scale(temp, contact.normalA, d); + sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector + 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; +}; + +/** + * Convex/convex Narrowphase.See this article for more info. + * @method convexConvex + * @param {Body} bi + * @param {Convex} si + * @param {Array} xi + * @param {Number} ai + * @param {Body} bj + * @param {Convex} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CONVEX] = +Narrowphase.prototype[Shape.CONVEX | Shape.BOX] = +Narrowphase.prototype[Shape.BOX] = +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 = typeof(precision) === 'number' ? precision : 0; + + var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); + if(!found){ + return 0; + } + + // Make sure the separating axis is directed from shape i to shape j + sub(dist,xj,xi); + if(dot(sepAxis,dist) > 0){ + vec2.scale(sepAxis,sepAxis,-1); + } + + // Find edges with normals closest to the separating axis + var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis + closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); + + if(closestEdge1 === -1 || closestEdge2 === -1){ + return 0; + } + + // Loop over the shapes + 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){ + // Swap! + 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; + } + + // Loop over 2 points in convex B + for(var j=closestEdgeB; j= 3){ + + if(justTest){ + return true; + } + + // worldPoint was on the "inside" side of each of the 3 checked edges. + // Project it to the center edge and use the projection direction as normal + + // Create contact + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + numContacts++; + + // Get center edge from body A + var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], + v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; + + // Construct the edge + 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); // Normal points out of convex A + vec2.normalize(c.normalA,c.normalA); + + sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point + var d = dot(c.normalA,dist); // Penetration + vec2.scale(penetrationVec, c.normalA, d); // Vector penetration + + 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); + + // Todo reduce to 1 friction equation if we have 2 contact points + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numContacts){ + this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); + } + } + + return numContacts; +}; + +// .projectConvex is called by other functions, need local tmp vectors +var pcoa_tmp1 = vec2.fromValues(0,0); + +/** + * Project a Convex onto a world-oriented axis + * @method projectConvexOntoAxis + * @static + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Array} worldAxis + * @param {Array} result + */ +Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = pcoa_tmp1; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, worldAxis, -convexAngle); + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + // Project the position of the body onto the axis - need to add this to the result + var offset = dot(convexOffset, worldAxis); + + vec2.set( result, min + offset, max + offset); +}; + +// .findSeparatingAxis is called by other functions, need local tmp vectors +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); + +/** + * Find a separating axis between the shapes, that maximizes the separating distance between them. + * @method findSeparatingAxis + * @static + * @param {Convex} c1 + * @param {Array} offset1 + * @param {Number} angle1 + * @param {Convex} c2 + * @param {Array} offset2 + * @param {Number} angle2 + * @param {Array} sepAxis The resulting axis + * @return {Boolean} Whether the axis could be found. + */ +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; + + if(c1 instanceof Box && c2 instanceof Box){ + + for(var j=0; j!==2; j++){ + var c = c1, + angle = angle1; + if(j===1){ + c = c2; + angle = angle2; + } + + for(var i=0; i!==2; i++){ + + // Get the world edge + if(i === 0){ + vec2.set(normal, 0, 1); + } else if(i === 1) { + vec2.set(normal, 1, 0); + } + if(angle !== 0){ + vec2.rotate(normal, normal, angle); + } + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + + } else { + + 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++){ + // Get the world edge + vec2.rotate(worldPoint0, c.vertices[i], angle); + vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); + + sub(edge, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, edge); + vec2.normalize(normal,normal); + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + } + + + /* + // Needs to be tested some more + 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.axes.length; i++){ + + var normal = c.axes[i]; + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1); + Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + 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; +}; + +// .getClosestEdge is called by other functions, need local tmp vectors +var gce_tmp1 = vec2.fromValues(0,0) +, gce_tmp2 = vec2.fromValues(0,0) +, gce_tmp3 = vec2.fromValues(0,0); + +/** + * Get the edge that has a normal closest to an axis. + * @method getClosestEdge + * @static + * @param {Convex} c + * @param {Number} angle + * @param {Array} axis + * @param {Boolean} flip + * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. + */ +Narrowphase.getClosestEdge = function(c,angle,axis,flip){ + var localAxis = gce_tmp1, + edge = gce_tmp2, + normal = gce_tmp3; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, axis, -angle); + if(flip){ + vec2.scale(localAxis,localAxis,-1); + } + + var closestEdge = -1, + N = c.vertices.length, + maxDot = -1; + for(var i=0; i!==N; i++){ + // Get the edge + sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + 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(); + +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = +Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, + hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ + var data = hfShape.heights, + 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; + + // Get the index of the points to test against + var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), + idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); + + /*if(idxB < 0 || idxA >= data.length) + return justTest ? false : 0;*/ + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(circlePos[1]-radius > max){ + return justTest ? false : 0; + } + + /* + if(circlePos[1]+radius < min){ + // Below the minimum point... We can just guess. + // TODO + } + */ + + // 1. Check so center of circle is not inside the field. If it is, this wont work... + // 2. For each edge + // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) + // 2. 2. Check if point is inside. + + var found = false; + + // Check all edges first + for(var i=idxA; i= v0[0] && candidate[0] < v1[0] && d <= 0){ + + if(justTest){ + return true; + } + + found = true; + + // Store the candidate point, projected to the edge + vec2.scale(dist,worldNormal,-d); + vec2.add(minCandidate,candidate,dist); + vec2.copy(minCandidateNormal,worldNormal); + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Normal is out of the heightfield + vec2.copy(c.normalA, minCandidateNormal); + + // Vector from circle to heightfield + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + vec2.copy(c.contactPointA, minCandidate); + vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push( this.createFrictionFromContact(c) ); + } + } + } + + // Check all vertices + found = false; + if(radius > 0){ + for(var i=idxA; i<=idxB; i++){ + + // Get point + vec2.set(v0, i*w, data[i]); + vec2.add(v0,v0,hfPos); + + vec2.sub(dist, circlePos, v0); + + if(vec2.squaredLength(dist) < Math.pow(radius, 2)){ + + if(justTest){ + return true; + } + + found = true; + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Construct normal - out of heightfield + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + sub(c.contactPointA, v0, hfPos); + add(c.contactPointA, c.contactPointA, hfPos); + sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(found){ + return 1; + } + + return 0; + +}; + +var convexHeightfield_v0 = vec2.create(), + convexHeightfield_v1 = vec2.create(), + convexHeightfield_tilePos = vec2.create(), + convexHeightfield_tempConvexShape = new Convex({ vertices: [vec2.create(),vec2.create(),vec2.create(),vec2.create()] }); +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.BOX | Shape.HEIGHTFIELD] = +Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = +Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, + hfBody,hfShape,hfPos,hfAngle, justTest ){ + var data = hfShape.heights, + w = hfShape.elementWidth, + v0 = convexHeightfield_v0, + v1 = convexHeightfield_v1, + tilePos = convexHeightfield_tilePos, + tileConvex = convexHeightfield_tempConvexShape; + + // Get the index of the points to test against + var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), + idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(convexBody.aabb.lowerBound[1] > max){ + return justTest ? false : 0; + } + + var found = false; + var numContacts = 0; + + // Loop over all edges + // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape) + for(var i=idxA; i= 0 || aabb.containsPoint(this.from)){ + this.intersectBody(result, body); + } + } +}; + +var intersectBody_worldPosition = vec2.create(); + +/** + * Shoot a ray at a body, get back information about the hit. + * @method intersectBody + * @private + * @param {Body} body + */ +Ray.prototype.intersectBody = function (result, body) { + var checkCollisionResponse = this.checkCollisionResponse; + + if(checkCollisionResponse && !body.collisionResponse){ + return; + } + + var worldPosition = intersectBody_worldPosition; + + for (var i = 0, N = body.shapes.length; i < N; i++) { + var shape = body.shapes[i]; + + if(checkCollisionResponse && !shape.collisionResponse){ + continue; // Skip + } + + if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){ + continue; + } + + // Get world angle and position of the shape + vec2.rotate(worldPosition, shape.position, body.angle); + vec2.add(worldPosition, worldPosition, body.position); + var worldAngle = shape.angle + body.angle; + + this.intersectShape( + result, + shape, + worldAngle, + worldPosition, + body + ); + + if(result.shouldStop(this)){ + break; + } + } +}; + +/** + * @method intersectShape + * @private + * @param {Shape} shape + * @param {number} angle + * @param {array} position + * @param {Body} body + */ +Ray.prototype.intersectShape = function(result, shape, angle, position, body){ + var from = this.from; + + // Checking radius + var distance = distanceFromIntersectionSquared(from, this.direction, position); + if (distance > shape.boundingRadius * shape.boundingRadius) { + return; + } + + this._currentBody = body; + this._currentShape = shape; + + shape.raycast(result, this, position, angle); + + this._currentBody = this._currentShape = null; +}; + +/** + * Get the AABB of the ray. + * @method getAABB + * @param {AABB} aabb + */ +Ray.prototype.getAABB = function(result){ + var to = this.to; + var from = this.from; + vec2.set( + result.lowerBound, + Math.min(to[0], from[0]), + Math.min(to[1], from[1]) + ); + vec2.set( + result.upperBound, + Math.max(to[0], from[0]), + Math.max(to[1], from[1]) + ); +}; + +var hitPointWorld = vec2.create(); + +/** + * @method reportIntersection + * @private + * @param {number} fraction + * @param {array} normal + * @param {number} [faceIndex=-1] + * @return {boolean} True if the intersections should continue + */ +Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){ + var from = this.from; + var to = this.to; + var shape = this._currentShape; + var body = this._currentBody; + + // Skip back faces? + if(this.skipBackfaces && vec2.dot(normal, this.direction) > 0){ + return; + } + + switch(this.mode){ + + case Ray.ALL: + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + this.callback(result); + break; + + case Ray.CLOSEST: + + // Store if closer than current closest + if(fraction < result.fraction || !result.hasHit()){ + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + } + break; + + case Ray.ANY: + + // Report and stop. + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + break; + } +}; + +var v0 = vec2.create(), + intersect = vec2.create(); +function distanceFromIntersectionSquared(from, direction, position) { + + // v0 is vector from from to position + vec2.sub(v0, position, from); + var dot = vec2.dot(v0, direction); + + // intersect = direction * dot + from + vec2.scale(intersect, direction, dot); + vec2.add(intersect, intersect, from); + + return vec2.squaredDistance(position, intersect); +} + + +},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Ray = _dereq_('../collision/Ray'); + +module.exports = RaycastResult; + +/** + * Storage for Ray casting hit data. + * @class RaycastResult + * @constructor + */ +function RaycastResult(){ + + /** + * The normal of the hit, oriented in world space. + * @property {array} normal + */ + this.normal = vec2.create(); + + /** + * The hit shape, or null. + * @property {Shape} shape + */ + this.shape = null; + + /** + * The hit body, or null. + * @property {Body} body + */ + this.body = null; + + /** + * The index of the hit triangle, if the hit shape was indexable. + * @property {number} faceIndex + * @default -1 + */ + this.faceIndex = -1; + + /** + * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet. + * @property {number} fraction + * @default -1 + */ + this.fraction = -1; + + /** + * If the ray should stop traversing. + * @readonly + * @property {Boolean} isStopped + */ + this.isStopped = false; +} + +/** + * Reset all result data. Must be done before re-using the result object. + * @method reset + */ +RaycastResult.prototype.reset = function () { + vec2.set(this.normal, 0, 0); + this.shape = null; + this.body = null; + this.faceIndex = -1; + this.fraction = -1; + this.isStopped = false; +}; + +/** + * Get the distance to the hit point. + * @method getHitDistance + * @param {Ray} ray + */ +RaycastResult.prototype.getHitDistance = function (ray) { + return vec2.distance(ray.from, ray.to) * this.fraction; +}; + +/** + * Returns true if the ray hit something since the last reset(). + * @method hasHit + */ +RaycastResult.prototype.hasHit = function () { + return this.fraction !== -1; +}; + +/** + * Get world hit point. + * @method getHitPoint + * @param {array} out + * @param {Ray} ray + */ +RaycastResult.prototype.getHitPoint = function (out, ray) { + vec2.lerp(out, ray.from, ray.to, this.fraction); +}; + +/** + * Can be called while iterating over hits to stop searching for hit points. + * @method stop + */ +RaycastResult.prototype.stop = function(){ + this.isStopped = true; +}; + +/** + * @method shouldStop + * @private + * @param {Ray} ray + * @return {boolean} + */ +RaycastResult.prototype.shouldStop = function(ray){ + return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY); +}; + +/** + * @method set + * @private + * @param {array} normal + * @param {Shape} shape + * @param {Body} body + * @param {number} fraction + */ +RaycastResult.prototype.set = function( + normal, + shape, + body, + fraction, + faceIndex +){ + vec2.copy(this.normal, normal); + this.shape = shape; + this.body = body; + this.fraction = fraction; + this.faceIndex = faceIndex; +}; +},{"../collision/Ray":11,"../math/vec2":30}],13:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, Broadphase = _dereq_('../collision/Broadphase'); + +module.exports = SAPBroadphase; + +/** + * Sweep and prune broadphase along one axis. + * + * @class SAPBroadphase + * @constructor + * @extends Broadphase + */ +function SAPBroadphase(){ + Broadphase.call(this,Broadphase.SAP); + + /** + * List of bodies currently in the broadphase. + * @property axisList + * @type {Array} + */ + this.axisList = []; + + /** + * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance. + * @property axisIndex + * @type {Number} + */ + this.axisIndex = 0; + + var that = this; + this._addBodyHandler = function(e){ + that.axisList.push(e.body); + }; + + this._removeBodyHandler = function(e){ + // Remove from list + var idx = that.axisList.indexOf(e.body); + if(idx !== -1){ + that.axisList.splice(idx,1); + } + }; +} +SAPBroadphase.prototype = new Broadphase(); +SAPBroadphase.prototype.constructor = SAPBroadphase; + +/** + * Change the world + * @method setWorld + * @param {World} world + */ +SAPBroadphase.prototype.setWorld = function(world){ + // Clear the old axis array + this.axisList.length = 0; + + // Add all bodies from the new world + Utils.appendArray(this.axisList, world.bodies); + + // Remove old handlers, if any + world + .off("addBody",this._addBodyHandler) + .off("removeBody",this._removeBodyHandler); + + // Add handlers to update the list of bodies. + world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); + + this.world = world; +}; + +/** + * Sorts bodies along an axis. + * @method sortAxisList + * @param {Array} a + * @param {number} axisIndex + * @return {Array} + */ +SAPBroadphase.sortAxisList = function(a, axisIndex){ + axisIndex = axisIndex|0; + for(var i=1,l=a.length; 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.sortList = function(){ + var bodies = this.axisList, + axisIndex = this.axisIndex; + + // Sort the lists + SAPBroadphase.sortAxisList(bodies, axisIndex); +}; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +SAPBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = this.axisList, + result = this.result, + axisIndex = this.axisIndex; + + result.length = 0; + + // Update all AABBs if needed + var l = bodies.length; + while(l--){ + var b = bodies[l]; + if(b.aabbNeedsUpdate){ + b.updateAABB(); + } + } + + // Sort the lists + this.sortList(); + + // Look through the X list + for(var i=0, N=bodies.length|0; i!==N; i++){ + var bi = bodies[i]; + + for(var j=i+1; j G = [-n -rixn n rjxn] + + var r = vec2.create(); + var ri = vec2.create(); // worldAnchorA + var rj = vec2.create(); // worldAnchorB + var that = this; + normal.computeGq = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + xi = bodyA.position, + xj = bodyB.position; + + // Transform local anchors to world + vec2.rotate(ri, localAnchorA, bodyA.angle); + vec2.rotate(rj, localAnchorB, bodyB.angle); + + vec2.add(r, xj, rj); + vec2.sub(r, r, ri); + vec2.sub(r, r, xi); + + //vec2.sub(r, bodyB.position, bodyA.position); + return vec2.length(r) - that.distance; + }; + + // Make the contact constraint bilateral + this.setMaxForce(maxForce); + + /** + * If the upper limit is enabled or not. + * @property {Boolean} upperLimitEnabled + */ + this.upperLimitEnabled = false; + + /** + * The upper constraint limit. + * @property {number} upperLimit + */ + this.upperLimit = 1; + + /** + * If the lower limit is enabled or not. + * @property {Boolean} lowerLimitEnabled + */ + this.lowerLimitEnabled = false; + + /** + * The lower constraint limit. + * @property {number} lowerLimit + */ + this.lowerLimit = 0; + + /** + * Current constraint position. This is equal to the current distance between the world anchor points. + * @property {number} position + */ + this.position = 0; +} +DistanceConstraint.prototype = new Constraint(); +DistanceConstraint.prototype.constructor = DistanceConstraint; + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +var n = vec2.create(); +var ri = vec2.create(); // worldAnchorA +var rj = vec2.create(); // worldAnchorB +DistanceConstraint.prototype.update = function(){ + var normal = this.equations[0], + bodyA = this.bodyA, + bodyB = this.bodyB, + distance = this.distance, + xi = bodyA.position, + xj = bodyB.position, + normalEquation = this.equations[0], + G = normal.G; + + // Transform local anchors to world + vec2.rotate(ri, this.localAnchorA, bodyA.angle); + vec2.rotate(rj, this.localAnchorB, bodyB.angle); + + // Get world anchor points and normal + vec2.add(n, xj, rj); + vec2.sub(n, n, ri); + vec2.sub(n, n, xi); + this.position = vec2.length(n); + + var violating = false; + if(this.upperLimitEnabled){ + if(this.position > this.upperLimit){ + normalEquation.maxForce = 0; + normalEquation.minForce = -this.maxForce; + this.distance = this.upperLimit; + violating = true; + } + } + + if(this.lowerLimitEnabled){ + if(this.position < this.lowerLimit){ + normalEquation.maxForce = this.maxForce; + normalEquation.minForce = 0; + this.distance = this.lowerLimit; + violating = true; + } + } + + if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){ + // No constraint needed. + normalEquation.enabled = false; + return; + } + + normalEquation.enabled = true; + + vec2.normalize(n,n); + + // Caluclate cross products + var rixn = vec2.crossLength(ri, n), + rjxn = vec2.crossLength(rj, n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; +}; + +/** + * Set the max force to be used + * @method setMaxForce + * @param {Number} maxForce + */ +DistanceConstraint.prototype.setMaxForce = function(maxForce){ + var normal = this.equations[0]; + normal.minForce = -maxForce; + normal.maxForce = maxForce; +}; + +/** + * Get the max force + * @method getMaxForce + * @return {Number} + */ +DistanceConstraint.prototype.getMaxForce = function(){ + var normal = this.equations[0]; + return normal.maxForce; +}; + +},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, AngleLockEquation = _dereq_('../equations/AngleLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = GearConstraint; + +/** + * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB. + * @class GearConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for). + * @param {Number} [options.ratio=1] Gear ratio. + * @param {Number} [options.maxTorque] Maximum torque to apply. + * @extends Constraint + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB, { + * ratio: 2, + * maxTorque: 1000 + * }); + * world.addConstraint(constraint); + */ +function GearConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); + + /** + * The gear ratio. + * @property ratio + * @type {Number} + */ + this.ratio = options.ratio !== undefined ? options.ratio : 1; + + /** + * The relative angle + * @property angle + * @type {Number} + */ + this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle; + + // Send same parameters to the equation + options.angle = this.angle; + options.ratio = this.ratio; + + this.equations = [ + new AngleLockEquation(bodyA,bodyB,options), + ]; + + // Set max torque + if(options.maxTorque !== undefined){ + this.setMaxTorque(options.maxTorque); + } +} +GearConstraint.prototype = new Constraint(); +GearConstraint.prototype.constructor = GearConstraint; + +GearConstraint.prototype.update = function(){ + var eq = this.equations[0]; + if(eq.ratio !== this.ratio){ + eq.setRatio(this.ratio); + } + eq.angle = this.angle; +}; + +/** + * Set the max torque for the constraint. + * @method setMaxTorque + * @param {Number} torque + */ +GearConstraint.prototype.setMaxTorque = function(torque){ + this.equations[0].setMaxTorque(torque); +}; + +/** + * Get the max torque for the constraint. + * @method getMaxTorque + * @return {Number} + */ +GearConstraint.prototype.getMaxTorque = function(torque){ + return this.equations[0].maxForce; +}; +},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('../equations/Equation'); + +module.exports = LockConstraint; + +/** + * Locks the relative position and rotation between two bodies. + * + * @class LockConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions. + * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles. + * @param {number} [options.maxForce] + * @extends Constraint + * + * @example + * // Locks the relative position and rotation between bodyA and bodyB + * var constraint = new LockConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + */ +function LockConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); + + var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); + + var localAngleB = options.localAngleB || 0; + + // Use 3 equations: + // gx = (xj - xi - l) * xhat = 0 + // gy = (xj - xi - l) * yhat = 0 + // gr = (xi - xj + r) * that = 0 + // + // ...where: + // l is the localOffsetB vector rotated to world in bodyA frame + // r is the same vector but reversed and rotated from bodyB frame + // xhat, yhat are world axis vectors + // that is the tangent of r + // + // For the first two constraints, we get + // G*W = (vj - vi - ldot ) * xhat + // = (vj - vi - wi x l) * xhat + // + // Since (wi x l) * xhat = (l x xhat) * wi, we get + // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] + // + // The last constraint gives + // GW = (vi - vj + wj x r) * that + // = [ that 0 -that (r x t) ] + + var x = new Equation(bodyA,bodyB,-maxForce,maxForce), + y = new Equation(bodyA,bodyB,-maxForce,maxForce), + rot = new Equation(bodyA,bodyB,-maxForce,maxForce); + + var l = vec2.create(), + g = vec2.create(), + that = this; + x.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[0]; + }; + y.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[1]; + }; + var r = vec2.create(), + t = vec2.create(); + rot.computeGq = function(){ + vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); + vec2.scale(r,r,-1); + vec2.sub(g,bodyA.position,bodyB.position); + vec2.add(g,g,r); + vec2.rotate(t,r,-Math.PI/2); + vec2.normalize(t,t); + return vec2.dot(g,t); + }; + + /** + * The offset of bodyB in bodyA's frame. + * @property {Array} localOffsetB + */ + this.localOffsetB = vec2.create(); + if(options.localOffsetB){ + vec2.copy(this.localOffsetB, options.localOffsetB); + } else { + // Construct from current positions + vec2.sub(this.localOffsetB, bodyB.position, bodyA.position); + vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle); + } + + /** + * The offset angle of bodyB in bodyA's frame. + * @property {Number} localAngleB + */ + this.localAngleB = 0; + if(typeof(options.localAngleB) === 'number'){ + this.localAngleB = options.localAngleB; + } else { + // Construct + this.localAngleB = bodyB.angle - bodyA.angle; + } + + this.equations.push(x, y, rot); + this.setMaxForce(maxForce); +} +LockConstraint.prototype = new Constraint(); +LockConstraint.prototype.constructor = LockConstraint; + +/** + * Set the maximum force to be applied. + * @method setMaxForce + * @param {Number} force + */ +LockConstraint.prototype.setMaxForce = function(force){ + var eqs = this.equations; + for(var i=0; ithis tutorial. Also called "slider constraint". + * + * @class PrismaticConstraint + * @constructor + * @extends Constraint + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.maxForce] Max force to be applied by the constraint + * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. + * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. + * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. + * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. + * @param {Number} [options.upperLimit] + * @param {Number} [options.lowerLimit] + * @todo Ability to create using only a point and a worldAxis + */ +function PrismaticConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); + + // Get anchors + var localAnchorA = vec2.fromValues(0,0), + localAxisA = vec2.fromValues(1,0), + localAnchorB = vec2.fromValues(0,0); + if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); } + if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); } + if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); } + + /** + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = localAnchorA; + + /** + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = localAnchorB; + + /** + * @property localAxisA + * @type {Array} + */ + this.localAxisA = localAxisA; + + /* + + The constraint violation for the common axis point is + + g = ( xj + rj - xi - ri ) * t := gg*t + + where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. + + gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) + + Note the use of the chain rule. Now we identify the jacobian + + G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] + + The rotational part is just a rotation lock. + + */ + + var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE; + + // Translational part + var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); + var ri = new vec2.create(), + rj = new vec2.create(), + gg = new vec2.create(), + t = new vec2.create(); + trans.computeGq = function(){ + // g = ( xj + rj - xi - ri ) * t + return vec2.dot(gg,t); + }; + trans.updateJacobian = function(){ + var G = this.G, + xi = bodyA.position, + xj = bodyB.position; + vec2.rotate(ri,localAnchorA,bodyA.angle); + vec2.rotate(rj,localAnchorB,bodyB.angle); + vec2.add(gg,xj,rj); + vec2.sub(gg,gg,xi); + vec2.sub(gg,gg,ri); + vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); + + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + }; + this.equations.push(trans); + + // Rotational part + if(!options.disableRotationalLock){ + var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); + this.equations.push(rot); + } + + /** + * The position of anchor A relative to anchor B, along the constraint axis. + * @property position + * @type {Number} + */ + this.position = 0; + + // Is this one used at all? + this.velocity = 0; + + /** + * Set to true to enable lower limit. + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; + + /** + * Set to true to enable upper limit. + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; + + /** + * Lower constraint limit. The constraint position is forced to be larger than this value. + * @property lowerLimit + * @type {Number} + */ + this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; + + /** + * Upper constraint limit. The constraint position is forced to be smaller than this value. + * @property upperLimit + * @type {Number} + */ + this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; + + // Equations used for limits + this.upperLimitEquation = new ContactEquation(bodyA,bodyB); + this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); + + // Set max/min forces + this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; + this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; + + /** + * Equation used for the motor. + * @property motorEquation + * @type {Equation} + */ + this.motorEquation = new Equation(bodyA,bodyB); + + /** + * The current motor state. Enable or disable the motor using .enableMotor + * @property motorEnabled + * @type {Boolean} + */ + this.motorEnabled = false; + + /** + * Set the target speed for the motor. + * @property motorSpeed + * @type {Number} + */ + this.motorSpeed = 0; + + var that = this; + var motorEquation = this.motorEquation; + var old = motorEquation.computeGW; + motorEquation.computeGq = function(){ return 0; }; + motorEquation.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed; + }; +} + +PrismaticConstraint.prototype = new Constraint(); +PrismaticConstraint.prototype.constructor = PrismaticConstraint; + +var worldAxisA = vec2.create(), + worldAnchorA = vec2.create(), + worldAnchorB = vec2.create(), + orientedAnchorA = vec2.create(), + orientedAnchorB = vec2.create(), + tmp = vec2.create(); + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +PrismaticConstraint.prototype.update = function(){ + var eqs = this.equations, + trans = eqs[0], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation, + bodyA = this.bodyA, + bodyB = this.bodyB, + localAxisA = this.localAxisA, + localAnchorA = this.localAnchorA, + localAnchorB = this.localAnchorB; + + trans.updateJacobian(); + + // Transform local things to world + vec2.rotate(worldAxisA, localAxisA, bodyA.angle); + vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); + vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); + vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); + vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); + + var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); + + // Motor + if(this.motorEnabled){ + // G = [ a a x ri -a -a x rj ] + var G = this.motorEquation.G; + G[0] = worldAxisA[0]; + G[1] = worldAxisA[1]; + G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); + G[3] = -worldAxisA[0]; + G[4] = -worldAxisA[1]; + G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); + } + + /* + Limits strategy: + Add contact equation, with normal along the constraint axis. + min/maxForce is set so the constraint is repulsive in the correct direction. + Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. + + ^ + | + upperLimit x + | ------ + anchorB x<---| B | + | | | + ------ | ------ + | | | + | A |-->x anchorA + ------ | + x lowerLimit + | + axis + */ + + + if(this.upperLimitEnabled && relPosition > upperLimit){ + // Update contact constraint normal, etc + 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 && relPosition < lowerLimit){ + // Update contact constraint normal, etc + vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); + vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); + vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); + vec2.scale(tmp,worldAxisA,lowerLimit); + vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } +}; + +/** + * Enable the motor + * @method enableMotor + */ +PrismaticConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +PrismaticConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the constraint limits. + * @method setLimits + * @param {number} lower Lower limit. + * @param {number} upper Upper limit. + */ +PrismaticConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + + +},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation') +, RotationalLockEquation = _dereq_('../equations/RotationalLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = RevoluteConstraint; + +var worldPivotA = vec2.create(), + worldPivotB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1), + g = vec2.create(); + +/** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * @class RevoluteConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to. + * @param {Array} [options.localPivotB] See localPivotA. + * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. + * @extends Constraint + * + * @example + * // This will create a revolute constraint between two bodies with pivot point in between them. + * var bodyA = new Body({ mass: 1, position: [-1, 0] }); + * var bodyB = new Body({ mass: 1, position: [1, 0] }); + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * worldPivot: [0, 0] + * }); + * world.addConstraint(constraint); + * + * // Using body-local pivot points, the constraint could have been constructed like this: + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * localPivotA: [1, 0], + * localPivotB: [-1, 0] + * }); + */ +function RevoluteConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); + + var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; + + /** + * @property {Array} pivotA + */ + this.pivotA = vec2.create(); + + /** + * @property {Array} pivotB + */ + this.pivotB = vec2.create(); + + if(options.worldPivot){ + // Compute pivotA and pivotB + vec2.sub(this.pivotA, options.worldPivot, bodyA.position); + vec2.sub(this.pivotB, options.worldPivot, bodyB.position); + // Rotate to local coordinate system + vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle); + vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle); + } else { + // Get pivotA and pivotB + vec2.copy(this.pivotA, options.localPivotA); + vec2.copy(this.pivotB, options.localPivotB); + } + + // Equations to be fed to the solver + var eqs = this.equations = [ + new Equation(bodyA,bodyB,-maxForce,maxForce), + new Equation(bodyA,bodyB,-maxForce,maxForce), + ]; + + var x = eqs[0]; + var y = eqs[1]; + var that = this; + + x.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,xAxis); + }; + + y.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,yAxis); + }; + + y.minForce = x.minForce = -maxForce; + y.maxForce = x.maxForce = maxForce; + + this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); + + /** + * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. + * @property {Boolean} motorEnabled + * @readOnly + */ + this.motorEnabled = false; + + /** + * The constraint position. + * @property angle + * @type {Number} + * @readOnly + */ + this.angle = 0; + + /** + * Set to true to enable lower limit + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = false; + + /** + * Set to true to enable upper limit + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = false; + + /** + * The lower limit on the constraint angle. + * @property lowerLimit + * @type {Boolean} + */ + this.lowerLimit = 0; + + /** + * The upper limit on the constraint angle. + * @property upperLimit + * @type {Boolean} + */ + this.upperLimit = 0; + + this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.upperLimitEquation.minForce = 0; + this.lowerLimitEquation.maxForce = 0; +} +RevoluteConstraint.prototype = new Constraint(); +RevoluteConstraint.prototype.constructor = RevoluteConstraint; + +/** + * Set the constraint angle limits. + * @method setLimits + * @param {number} lower Lower angle limit. + * @param {number} upper Upper angle limit. + */ +RevoluteConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + +RevoluteConstraint.prototype.update = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + pivotA = this.pivotA, + pivotB = this.pivotB, + eqs = this.equations, + normal = eqs[0], + tangent= eqs[1], + x = eqs[0], + y = eqs[1], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation; + + var relAngle = this.angle = bodyB.angle - bodyA.angle; + + if(this.upperLimitEnabled && relAngle > upperLimit){ + 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 < lowerLimit){ + lowerLimitEquation.angle = lowerLimit; + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } + + /* + + The constraint violation is + + g = xj + rj - xi - ri + + ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: + + gdot = vj + wj x rj - vi - wi x ri + + We split this into x and y directions. (let x and y be unit vectors along the respective axes) + + gdot * x = ( vj + wj x rj - vi - wi x ri ) * x + = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x + = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi + = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] + = G*W + + ...and similar for y. We have then identified the jacobian entries for x and y directions: + + Gx = [ x (rj x x) -x -(ri x x)] + Gy = [ y (rj x y) -y -(ri x y)] + + */ + + vec2.rotate(worldPivotA, pivotA, bodyA.angle); + vec2.rotate(worldPivotB, pivotB, bodyB.angle); + + // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc + + x.G[0] = -1; + x.G[1] = 0; + x.G[2] = -vec2.crossLength(worldPivotA,xAxis); + x.G[3] = 1; + x.G[4] = 0; + x.G[5] = vec2.crossLength(worldPivotB,xAxis); + + y.G[0] = 0; + y.G[1] = -1; + y.G[2] = -vec2.crossLength(worldPivotA,yAxis); + y.G[3] = 0; + y.G[4] = 1; + y.G[5] = vec2.crossLength(worldPivotB,yAxis); +}; + +/** + * Enable the rotational motor + * @method enableMotor + */ +RevoluteConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +RevoluteConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the speed of the rotational constraint motor + * @method setMotorSpeed + * @param {Number} speed + */ +RevoluteConstraint.prototype.setMotorSpeed = function(speed){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations[i].relativeVelocity = speed; +}; + +/** + * Get the speed of the rotational constraint motor + * @method getMotorSpeed + * @return {Number} The current speed, or false if the motor is not enabled. + */ +RevoluteConstraint.prototype.getMotorSpeed = function(){ + if(!this.motorEnabled){ + return false; + } + return this.motorEquation.relativeVelocity; +}; + +},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = AngleLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class AngleLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in body A. + * @param {Number} [options.ratio] Gear ratio + */ +function AngleLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); + this.angle = options.angle || 0; + + /** + * The gear ratio. + * @property {Number} ratio + * @private + * @see setRatio + */ + this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; + + this.setRatio(this.ratio); +} +AngleLockEquation.prototype = new Equation(); +AngleLockEquation.prototype.constructor = AngleLockEquation; + +AngleLockEquation.prototype.computeGq = function(){ + return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; +}; + +/** + * Set the gear ratio for this equation + * @method setRatio + * @param {Number} ratio + */ +AngleLockEquation.prototype.setRatio = function(ratio){ + var G = this.G; + G[2] = ratio; + G[5] = -1; + this.ratio = ratio; +}; + +/** + * Set the max force for the equation. + * @method setMaxTorque + * @param {Number} torque + */ +AngleLockEquation.prototype.setMaxTorque = function(torque){ + this.maxForce = torque; + this.minForce = -torque; +}; + +},{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = ContactEquation; + +/** + * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive. + * + * @class ContactEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function ContactEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); + + /** + * Vector from body i center of mass to the contact point. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + this.penetrationVec = vec2.create(); + + /** + * World-oriented vector from body A center of mass to the contact point. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * The normal vector, pointing out of body i + * @property normalA + * @type {Array} + */ + this.normalA = vec2.create(); + + /** + * The restitution to use (0=no bounciness, 1=max bounciness). + * @property restitution + * @type {Number} + */ + this.restitution = 0; + + /** + * This property is set to true if this is the first impact between the bodies (not persistant contact). + * @property firstImpact + * @type {Boolean} + * @readOnly + */ + this.firstImpact = false; + + /** + * The shape in body i that triggered this contact. + * @property shapeA + * @type {Shape} + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this contact. + * @property shapeB + * @type {Shape} + */ + this.shapeB = null; +} +ContactEquation.prototype = new Equation(); +ContactEquation.prototype.constructor = ContactEquation; +ContactEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + xi = bi.position, + xj = bj.position; + + var penetrationVec = this.penetrationVec, + n = this.normalA, + G = this.G; + + // Caluclate cross products + var rixn = vec2.crossLength(ri,n), + rjxn = vec2.crossLength(rj,n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; + + // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector + vec2.add(penetrationVec,xj,rj); + vec2.sub(penetrationVec,penetrationVec,xi); + vec2.sub(penetrationVec,penetrationVec,ri); + + // Compute iteration + var GW, Gq; + if(this.firstImpact && this.restitution !== 0){ + Gq = 0; + GW = (1/b)*(1+this.restitution) * this.computeGW(); + } else { + Gq = vec2.dot(n,penetrationVec) + this.offset; + GW = this.computeGW(); + } + + var GiMf = this.computeGiMf(); + var B = - Gq * a - GW * b - h*GiMf; + + return B; +}; + +var vi = vec2.create(); +var vj = vec2.create(); +var relVel = vec2.create(); + +/** + * Get the relative velocity along the normal vector. + * @return {number} + */ +ContactEquation.prototype.getVelocityAlongNormal = function(){ + + this.bodyA.getVelocityAtPoint(vi, this.contactPointA); + this.bodyB.getVelocityAtPoint(vj, this.contactPointB); + + vec2.subtract(relVel, vi, vj); + + return vec2.dot(this.normalA, relVel); +}; +},{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){ +module.exports = Equation; + +var vec2 = _dereq_('../math/vec2'), + Utils = _dereq_('../utils/Utils'), + Body = _dereq_('../objects/Body'); + +/** + * Base class for constraint equations. + * @class Equation + * @constructor + * @param {Body} bodyA First body participating in the equation + * @param {Body} bodyB Second body participating in the equation + * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE + * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE + */ +function Equation(bodyA, bodyB, minForce, maxForce){ + + /** + * Minimum force to apply when solving. + * @property minForce + * @type {Number} + */ + this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; + + /** + * Max force to apply when solving. + * @property maxForce + * @type {Number} + */ + this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; + + /** + * First body participating in the constraint + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second body participating in the constraint + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; + + /** + * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. + * @property stiffness + * @type {Number} + */ + this.stiffness = Equation.DEFAULT_STIFFNESS; + + /** + * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. + * @property relaxation + * @type {Number} + */ + this.relaxation = Equation.DEFAULT_RELAXATION; + + /** + * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). + * @property G + * @type {Array} + */ + this.G = new Utils.ARRAY_TYPE(6); + for(var i=0; i<6; i++){ + this.G[i]=0; + } + + this.offset = 0; + + this.a = 0; + this.b = 0; + this.epsilon = 0; + this.timeStep = 1/60; + + /** + * Indicates if stiffness or relaxation was changed. + * @property {Boolean} needsUpdate + */ + this.needsUpdate = true; + + /** + * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. + * @property multiplier + * @type {Number} + */ + this.multiplier = 0; + + /** + * Relative velocity. + * @property {Number} relativeVelocity + */ + this.relativeVelocity = 0; + + /** + * Whether this equation is enabled or not. If true, it will be added to the solver. + * @property {Boolean} enabled + */ + this.enabled = true; +} +Equation.prototype.constructor = Equation; + +/** + * The default stiffness when creating a new Equation. + * @static + * @property {Number} DEFAULT_STIFFNESS + * @default 1e6 + */ +Equation.DEFAULT_STIFFNESS = 1e6; + +/** + * The default relaxation when creating a new Equation. + * @static + * @property {Number} DEFAULT_RELAXATION + * @default 4 + */ +Equation.DEFAULT_RELAXATION = 4; + +/** + * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the SPOOK notes. + * @method update + */ +Equation.prototype.update = function(){ + var k = this.stiffness, + d = this.relaxation, + h = this.timeStep; + + this.a = 4.0 / (h * (1 + 4 * d)); + this.b = (4.0 * d) / (1 + 4 * d); + this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); + + this.needsUpdate = false; +}; + +/** + * Multiply a jacobian entry with corresponding positions or velocities + * @method gmult + * @return {Number} + */ +Equation.prototype.gmult = function(G,vi,wi,vj,wj){ + return G[0] * vi[0] + + G[1] * vi[1] + + G[2] * wi + + G[3] * vj[0] + + G[4] * vj[1] + + G[5] * wj; +}; + +/** + * Computes the RHS of the SPOOK equation + * @method computeB + * @return {Number} + */ +Equation.prototype.computeB = function(a,b,h){ + var GW = this.computeGW(); + var Gq = this.computeGq(); + var GiMf = this.computeGiMf(); + return - Gq * a - GW * b - GiMf*h; +}; + +/** + * Computes G\*q, where q are the generalized body coordinates + * @method computeGq + * @return {Number} + */ +var qi = vec2.create(), + qj = vec2.create(); +Equation.prototype.computeGq = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + xi = bi.position, + xj = bj.position, + ai = bi.angle, + aj = bj.angle; + + return this.gmult(G, qi, ai, qj, aj) + this.offset; +}; + +/** + * Computes G\*W, where W are the body velocities + * @method computeGW + * @return {Number} + */ +Equation.prototype.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity; +}; + +/** + * Computes G\*Wlambda, where W are the body velocities + * @method computeGWlambda + * @return {Number} + */ +Equation.prototype.computeGWlambda = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.vlambda, + vj = bj.vlambda, + wi = bi.wlambda, + wj = bj.wlambda; + return this.gmult(G,vi,wi,vj,wj); +}; + +/** + * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. + * @method computeGiMf + * @return {Number} + */ +var iMfi = vec2.create(), + iMfj = vec2.create(); +Equation.prototype.computeGiMf = function(){ + var bi = this.bodyA, + bj = this.bodyB, + fi = bi.force, + ti = bi.angularForce, + fj = bj.force, + tj = bj.angularForce, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + vec2.scale(iMfi, fi, invMassi); + vec2.multiply(iMfi, bi.massMultiplier, iMfi); + vec2.scale(iMfj, fj,invMassj); + vec2.multiply(iMfj, bj.massMultiplier, iMfj); + + return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); +}; + +/** + * Computes G\*inv(M)\*G' + * @method computeGiMGt + * @return {Number} + */ +Equation.prototype.computeGiMGt = function(){ + var bi = this.bodyA, + bj = this.bodyB, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + return G[0] * G[0] * invMassi * bi.massMultiplier[0] + + G[1] * G[1] * invMassi * bi.massMultiplier[1] + + G[2] * G[2] * invIi + + G[3] * G[3] * invMassj * bj.massMultiplier[0] + + G[4] * G[4] * invMassj * bj.massMultiplier[1] + + G[5] * G[5] * invIj; +}; + +var addToWlambda_temp = vec2.create(), + addToWlambda_Gi = vec2.create(), + addToWlambda_Gj = vec2.create(), + addToWlambda_ri = vec2.create(), + addToWlambda_rj = vec2.create(), + addToWlambda_Mdiag = vec2.create(); + +/** + * Add constraint velocity to the bodies. + * @method addToWlambda + * @param {Number} deltalambda + */ +Equation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bodyA, + bj = this.bodyB, + temp = addToWlambda_temp, + Gi = addToWlambda_Gi, + Gj = addToWlambda_Gj, + ri = addToWlambda_ri, + rj = addToWlambda_rj, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + Mdiag = addToWlambda_Mdiag, + G = this.G; + + Gi[0] = G[0]; + Gi[1] = G[1]; + Gj[0] = G[3]; + Gj[1] = G[4]; + + // Add to linear velocity + // v_lambda += inv(M) * delta_lamba * G + vec2.scale(temp, Gi, invMassi*deltalambda); + vec2.multiply(temp, temp, bi.massMultiplier); + vec2.add( bi.vlambda, bi.vlambda, temp); + // This impulse is in the offset frame + // Also add contribution to angular + //bi.wlambda -= vec2.crossLength(temp,ri); + bi.wlambda += invIi * G[2] * deltalambda; + + + vec2.scale(temp, Gj, invMassj*deltalambda); + vec2.multiply(temp, temp, bj.massMultiplier); + vec2.add( bj.vlambda, bj.vlambda, temp); + //bj.wlambda -= vec2.crossLength(temp,rj); + bj.wlambda += invIj * G[5] * deltalambda; +}; + +/** + * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps + * @method computeInvC + * @param {Number} eps + * @return {Number} + */ +Equation.prototype.computeInvC = function(eps){ + return 1.0 / (this.computeGiMGt() + eps); +}; + +},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('./Equation') +, Utils = _dereq_('../utils/Utils'); + +module.exports = FrictionEquation; + +/** + * Constrains the slipping in a contact along a tangent + * + * @class FrictionEquation + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Number} slipForce + * @extends Equation + */ +function FrictionEquation(bodyA, bodyB, slipForce){ + Equation.call(this, bodyA, bodyB, -slipForce, slipForce); + + /** + * Relative vector from center of body A to the contact point, world oriented. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + + /** + * Relative vector from center of body B to the contact point, world oriented. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * Tangent vector that the friction force will act along. World oriented. + * @property t + * @type {Array} + */ + this.t = vec2.create(); + + /** + * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average. + * @property contactEquations + * @type {ContactEquation} + */ + this.contactEquations = []; + + /** + * The shape in body i that triggered this friction. + * @property shapeA + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeA... + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this friction. + * @property shapeB + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeB... + */ + this.shapeB = null; + + /** + * The friction coefficient to use. + * @property frictionCoefficient + * @type {Number} + */ + this.frictionCoefficient = 0.3; +} +FrictionEquation.prototype = new Equation(); +FrictionEquation.prototype.constructor = FrictionEquation; + +/** + * Set the slipping condition for the constraint. The friction force cannot be + * larger than this value. + * @method setSlipForce + * @param {Number} slipForce + */ +FrictionEquation.prototype.setSlipForce = function(slipForce){ + this.maxForce = slipForce; + this.minForce = -slipForce; +}; + +/** + * Get the max force for the constraint. + * @method getSlipForce + * @return {Number} + */ +FrictionEquation.prototype.getSlipForce = function(){ + return this.maxForce; +}; + +FrictionEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + t = this.t, + G = this.G; + + // G = [-t -rixt t rjxt] + // And remember, this is a pure velocity constraint, g is always zero! + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + + var GW = this.computeGW(), + GiMf = this.computeGiMf(); + + var B = /* - g * a */ - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class RotationalLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in bodyA. + */ +function RotationalLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + + /** + * @property {number} angle + */ + this.angle = options.angle || 0; + + var G = this.G; + G[2] = 1; + G[5] = -1; +} +RotationalLockEquation.prototype = new Equation(); +RotationalLockEquation.prototype.constructor = RotationalLockEquation; + +var worldVectorA = vec2.create(), + worldVectorB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1); +RotationalLockEquation.prototype.computeGq = function(){ + vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); + vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); + return vec2.dot(worldVectorA,worldVectorB); +}; + +},{"../math/vec2":30,"./Equation":22}],25:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalVelocityEquation; + +/** + * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). + * + * @class RotationalVelocityEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function RotationalVelocityEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + this.relativeVelocity = 1; + this.ratio = 1; +} +RotationalVelocityEquation.prototype = new Equation(); +RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; +RotationalVelocityEquation.prototype.computeB = function(a,b,h){ + var G = this.G; + G[2] = -1; + G[5] = this.ratio; + + var GiMf = this.computeGiMf(); + var GW = this.computeGW(); + var B = - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"./Equation":22}],26:[function(_dereq_,module,exports){ +/** + * Base class for objects that dispatches events. + * @class EventEmitter + * @constructor + */ +var EventEmitter = function () {}; + +module.exports = EventEmitter; + +EventEmitter.prototype = { + constructor: EventEmitter, + + /** + * Add an event listener + * @method on + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + on: function ( type, listener, context ) { + listener.context = context || this; + if ( this._listeners === undefined ){ + this._listeners = {}; + } + var listeners = this._listeners; + if ( listeners[ type ] === undefined ) { + listeners[ type ] = []; + } + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + listeners[ type ].push( listener ); + } + return this; + }, + + /** + * Check if an event listener is added + * @method has + * @param {String} type + * @param {Function} listener + * @return {Boolean} + */ + has: function ( type, listener ) { + if ( this._listeners === undefined ){ + return false; + } + var listeners = this._listeners; + if(listener){ + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + return true; + } + } else { + if ( listeners[ type ] !== undefined ) { + return true; + } + } + + return false; + }, + + /** + * Remove an event listener + * @method off + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + off: function ( type, listener ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var index = listeners[ type ].indexOf( listener ); + if ( index !== - 1 ) { + listeners[ type ].splice( index, 1 ); + } + return this; + }, + + /** + * Emit an event. + * @method emit + * @param {Object} event + * @param {String} event.type + * @return {EventEmitter} The self object, for chainability. + */ + emit: function ( event ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; + if ( listenerArray !== undefined ) { + event.target = this; + for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { + var listener = listenerArray[ i ]; + listener.call( listener.context, event ); + } + } + return this; + } +}; + +},{}],27:[function(_dereq_,module,exports){ +var Material = _dereq_('./Material'); +var Equation = _dereq_('../equations/Equation'); + +module.exports = ContactMaterial; + +/** + * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. + * @class ContactMaterial + * @constructor + * @param {Material} materialA + * @param {Material} materialB + * @param {Object} [options] + * @param {Number} [options.friction=0.3] Friction coefficient. + * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". + * @param {Number} [options.stiffness] ContactEquation stiffness. + * @param {Number} [options.relaxation] ContactEquation relaxation. + * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. + * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. + * @param {Number} [options.surfaceVelocity=0] Surface velocity. + * @author schteppe + */ +function ContactMaterial(materialA, materialB, options){ + options = options || {}; + + if(!(materialA instanceof Material) || !(materialB instanceof Material)){ + throw new Error("First two arguments must be Material instances."); + } + + /** + * The contact material identifier + * @property id + * @type {Number} + */ + this.id = ContactMaterial.idCounter++; + + /** + * First material participating in the contact material + * @property materialA + * @type {Material} + */ + this.materialA = materialA; + + /** + * Second material participating in the contact material + * @property materialB + * @type {Material} + */ + this.materialB = materialB; + + /** + * Friction coefficient to use in the contact of these two materials. Friction = 0 will make the involved objects super slippery, and friction = 1 will make it much less slippery. A friction coefficient larger than 1 will allow for very large friction forces, which can be convenient for preventing car tires not slip on the ground. + * @property friction + * @type {Number} + * @default 0.3 + */ + this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; + + /** + * Restitution, or "bounciness" to use in the contact of these two materials. A restitution of 0 will make no bounce, while restitution=1 will approximately bounce back with the same velocity the object came with. + * @property restitution + * @type {Number} + * @default 0 + */ + this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0; + + /** + * Hardness of the contact. Less stiffness will make the objects penetrate more, and will make the contact act more like a spring than a contact force. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property stiffness + * @type {Number} + */ + this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting ContactEquation that this ContactMaterial generate. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property relaxation + * @type {Number} + */ + this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Stiffness of the resulting friction force. For most cases, the value of this property should be a large number. I cannot think of any case where you would want less frictionStiffness. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property frictionStiffness + * @type {Number} + */ + this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting friction force. The default value should be good for most simulations. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property frictionRelaxation + * @type {Number} + */ + this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + * @property {Number} surfaceVelocity + * @default 0 + */ + this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; + + /** + * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts". + * @property contactSkinSize + * @type {Number} + */ + this.contactSkinSize = 0.005; +} + +ContactMaterial.idCounter = 0; + +},{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){ +module.exports = Material; + +/** + * Defines a physics material. + * @class Material + * @constructor + * @param {number} id Material identifier + * @author schteppe + */ +function Material(id){ + /** + * The material identifier + * @property id + * @type {Number} + */ + this.id = id || Material.idCounter++; +} + +Material.idCounter = 0; + +},{}],29:[function(_dereq_,module,exports){ + + /* + PolyK library + url: http://polyk.ivank.net + Released under MIT licence. + + Copyright (c) 2012 Ivan Kuckir + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + */ + + var PolyK = {}; + + /* + Is Polygon self-intersecting? + + O(n^2) + */ + /* + PolyK.IsSimple = function(p) + { + var n = p.length>>1; + if(n<4) return true; + var a1 = new PolyK._P(), a2 = new PolyK._P(); + var b1 = new PolyK._P(), b2 = new PolyK._P(); + var c = new PolyK._P(); + + for(var i=0; i>1; + if(n<3) return []; + var tgs = []; + var avl = []; + for(var i=0; i 3) + { + 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; j 3*al) break; // no convex angles :( + } + tgs.push(avl[0], avl[1], avl[2]); + return tgs; + } + /* + PolyK.ContainsPoint = function(p, px, py) + { + var n = p.length>>1; + var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; + var depth = 0; + for(var i=0; i=0 && by>=0) continue; // both "up" or both "donw" + if(ax< 0 && bx< 0) continue; + + var lx = ax + (bx-ax)*(-ay)/(by-ay); + if(lx>0) depth++; + } + return (depth & 1) == 1; + } + + PolyK.Slice = function(p, ax, ay, bx, by) + { + if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; + + var a = new PolyK._P(ax, ay); + var b = new PolyK._P(bx, by); + var iscs = []; // intersections + var ps = []; // points + for(var i=0; i 0) + { + var n = ps.length; + var i0 = iscs[0]; + var i1 = iscs[1]; + var ind0 = ps.indexOf(i0); + var ind1 = ps.indexOf(i1); + var solved = false; + + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + else + { + i0 = iscs[1]; + i1 = iscs[0]; + ind0 = ps.indexOf(i0); + ind1 = ps.indexOf(i1); + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + } + if(solved) + { + dir--; + var pgn = PolyK._getPoints(ps, ind0, ind1); + pgs.push(pgn); + ps = PolyK._getPoints(ps, ind1, ind0); + i0.flag = i1.flag = false; + iscs.splice(0,2); + if(iscs.length == 0) pgs.push(ps); + } + else { dir++; iscs.reverse(); } + if(dir>1) break; + } + var result = []; + for(var i=0; i>1, isc); + } + b1.x = b2.x; b1.y = b2.y; + b2.x = p[0]; b2.y = p[1]; + PolyK._pointLineDist(a1, b1, b2, l>>1, isc); + + var idst = 1/isc.dist; + isc.norm.x = (x-isc.point.x)*idst; + isc.norm.y = (y-isc.point.y)*idst; + return isc; + } + + PolyK._pointLineDist = function(p, a, b, edge, isc) + { + var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; + + var A = x - x1; + var B = y - y1; + var C = x2 - x1; + var D = y2 - y1; + + var dot = A * C + B * D; + var len_sq = C * C + D * D; + var param = dot / len_sq; + + var xx, yy; + + if (param < 0 || (x1 == x2 && y1 == y2)) { + xx = x1; + yy = y1; + } + else if (param > 1) { + xx = x2; + yy = y2; + } + else { + xx = x1 + param * C; + yy = y1 + param * D; + } + + var dx = x - xx; + var dy = y - yy; + var dst = Math.sqrt(dx * dx + dy * dy); + if(dst= 0) && (v >= 0) && (u + v < 1); + } + /* + PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) + { + var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); + var day = (a1.y-a2.y), dby = (b1.y-b2.y); + + var Den = dax*dby - day*dbx; + if (Den == 0) return null; // parallel + + var A = (a1.x * a2.y - a1.y * a2.x); + var B = (b1.x * b2.y - b1.y * b2.x); + + var I = c; + var iDen = 1/Den; + I.x = ( A*dbx - dax*B ) * iDen; + I.y = ( A*dby - day*B ) * iDen; + + if(!PolyK._InRect(I, b1, b2)) return null; + if((day>0 && I.y>a1.y) || (day<0 && I.y0 && I.x>a1.x) || (dax<0 && I.x=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); + if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); + + if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) + && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) + return true; + return false; + } + */ + PolyK._convex = function(ax, ay, bx, by, cx, cy) + { + return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; + } + /* + PolyK._P = function(x,y) + { + this.x = x; + this.y = y; + this.flag = false; + } + PolyK._P.prototype.toString = function() + { + return "Point ["+this.x+", "+this.y+"]"; + } + PolyK._P.dist = function(a,b) + { + var dx = b.x-a.x; + var dy = b.y-a.y; + return Math.sqrt(dx*dx + dy*dy); + } + + PolyK._tp = []; + for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); + */ + +module.exports = PolyK; + +},{}],30:[function(_dereq_,module,exports){ +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. + * @class vec2 + */ + +var vec2 = module.exports = {}; + +var Utils = _dereq_('../utils/Utils'); + +/** + * Make a cross product and only return the z component + * @method crossLength + * @static + * @param {Array} a + * @param {Array} b + * @return {Number} + */ +vec2.crossLength = function(a,b){ + return a[0] * b[1] - a[1] * b[0]; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossVZ + * @static + * @param {Array} out + * @param {Array} vec + * @param {Number} zcomp + * @return {Number} + */ +vec2.crossVZ = function(out, vec, zcomp){ + vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossZV + * @static + * @param {Array} out + * @param {Number} zcomp + * @param {Array} vec + * @return {Number} + */ +vec2.crossZV = function(out, zcomp, vec){ + vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Rotate a vector by an angle + * @method rotate + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate = function(out,a,angle){ + if(angle !== 0){ + 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; + } else { + out[0] = a[0]; + out[1] = a[1]; + } +}; + +/** + * Rotate a vector 90 degrees clockwise + * @method rotate90cw + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate90cw = function(out, a) { + var x = a[0]; + var y = a[1]; + out[0] = y; + out[1] = -x; +}; + +/** + * Transform a point position to local frame. + * @method toLocalFrame + * @param {Array} out + * @param {Array} worldPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ + vec2.copy(out, worldPoint); + vec2.sub(out, out, framePosition); + vec2.rotate(out, out, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ + vec2.copy(out, localPoint); + vec2.rotate(out, out, frameAngle); + vec2.add(out, out, framePosition); +}; + +/** + * Transform a vector to local frame. + * @method vectorToLocalFrame + * @param {Array} out + * @param {Array} worldVector + * @param {Number} frameAngle + */ +vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ + vec2.rotate(out, worldVector, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localVector + * @param {Number} frameAngle + */ +vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){ + vec2.rotate(out, localVector, frameAngle); +}; + +/** + * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php + * @method centroid + * @static + * @param {Array} out + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Array} The out object + */ +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; +}; + +/** + * Creates a new, empty vec2 + * @static + * @method create + * @return {Array} a new 2D vector + */ +vec2.create = function() { + var out = new Utils.ARRAY_TYPE(2); + out[0] = 0; + out[1] = 0; + return out; +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * @static + * @method clone + * @param {Array} a vector to clone + * @return {Array} a new 2D vector + */ +vec2.clone = function(a) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Creates a new vec2 initialized with the given values + * @static + * @method fromValues + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} a new 2D vector + */ +vec2.fromValues = function(x, y) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Copy the values from one vec2 to another + * @static + * @method copy + * @param {Array} out the receiving vector + * @param {Array} a the source vector + * @return {Array} out + */ +vec2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * @static + * @method set + * @param {Array} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} out + */ +vec2.set = function(out, x, y) { + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Adds two vec2's + * @static + * @method add + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +}; + +/** + * Subtracts two vec2's + * @static + * @method subtract + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +}; + +/** + * Alias for vec2.subtract + * @static + * @method sub + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * @static + * @method multiply + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +}; + +/** + * Alias for vec2.multiply + * @static + * @method mul + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * @static + * @method divide + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +}; + +/** + * Alias for vec2.divide + * @static + * @method div + */ +vec2.div = vec2.divide; + +/** + * Scales a vec2 by a scalar number + * @static + * @method scale + * @param {Array} out the receiving vector + * @param {Array} a the vector to scale + * @param {Number} b amount to scale the vector by + * @return {Array} out + */ +vec2.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * @static + * @method distance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} distance between a and b + */ +vec2.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.distance + * @static + * @method dist + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * @static + * @method squaredDistance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} squared distance between a and b + */ +vec2.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredDistance + * @static + * @method sqrDist + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * @static + * @method length + * @param {Array} a vector to calculate length of + * @return {Number} length of a + */ +vec2.length = function (a) { + var x = a[0], + y = a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.length + * @method len + * @static + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * @static + * @method squaredLength + * @param {Array} a vector to calculate squared length of + * @return {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a[0], + y = a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredLength + * @static + * @method sqrLen + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * @static + * @method negate + * @param {Array} out the receiving vector + * @param {Array} a vector to negate + * @return {Array} out + */ +vec2.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +}; + +/** + * Normalize a vec2 + * @static + * @method normalize + * @param {Array} out the receiving vector + * @param {Array} a vector to normalize + * @return {Array} out + */ +vec2.normalize = function(out, a) { + var x = a[0], + y = a[1]; + var len = x*x + y*y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * @static + * @method dot + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1]; +}; + +/** + * Returns a string representation of a vector + * @static + * @method str + * @param {Array} vec vector to represent as a string + * @return {String} string representation of the vector + */ +vec2.str = function (a) { + return 'vec2(' + a[0] + ', ' + a[1] + ')'; +}; + +/** + * Linearly interpolate/mix two vectors. + * @static + * @method lerp + * @param {Array} out + * @param {Array} a First vector + * @param {Array} b Second vector + * @param {number} t Lerp factor + */ +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; +}; + +/** + * Reflect a vector along a normal. + * @static + * @method reflect + * @param {Array} out + * @param {Array} vector + * @param {Array} normal + */ +vec2.reflect = function(out, vector, normal){ + var dot = vector[0] * normal[0] + vector[1] * normal[1]; + out[0] = vector[0] - 2 * normal[0] * dot; + out[1] = vector[1] - 2 * normal[1] * dot; +}; + +/** + * Get the intersection point between two line segments. + * @static + * @method getLineSegmentsIntersection + * @param {Array} out + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {boolean} True if there was an intersection, otherwise false. + */ +vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { + var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); + if(t < 0){ + return false; + } else { + out[0] = p0[0] + (t * (p1[0] - p0[0])); + out[1] = p0[1] + (t * (p1[1] - p0[1])); + return true; + } +}; + +/** + * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) + * @static + * @method getLineSegmentsIntersectionFraction + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. + */ +vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { + var s1_x = p1[0] - p0[0]; + var s1_y = p1[1] - p0[1]; + var s2_x = p3[0] - p2[0]; + var s2_y = p3[1] - p2[1]; + + var s, t; + s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); + t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); + if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + return t; + } + return -1; // No collision +}; + +},{"../utils/Utils":57}],31:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, decomp = _dereq_('poly-decomp') +, Convex = _dereq_('../shapes/Convex') +, RaycastResult = _dereq_('../collision/RaycastResult') +, Ray = _dereq_('../collision/Ray') +, AABB = _dereq_('../collision/AABB') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Body; + +/** + * A rigid body. Has got a center of mass, position, velocity and a number of + * shapes that are used for collisions. + * + * @class Body + * @constructor + * @extends EventEmitter + * @param {Array} [options.force] + * @param {Array} [options.position] + * @param {Array} [options.velocity] + * @param {Boolean} [options.allowSleep] + * @param {Boolean} [options.collisionResponse] + * @param {Number} [options.angle=0] + * @param {Number} [options.angularForce=0] + * @param {Number} [options.angularVelocity=0] + * @param {Number} [options.ccdIterations=10] + * @param {Number} [options.ccdSpeedThreshold=-1] + * @param {Number} [options.fixedRotation=false] + * @param {Number} [options.gravityScale] + * @param {Number} [options.id] + * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. + * @param {Number} [options.sleepSpeedLimit] + * @param {Number} [options.sleepTimeLimit] + * @param {Object} [options] + * + * @example + * + * // Create a typical dynamic body + * var body = new Body({ + * mass: 1, + * position: [0, 0], + * angle: 0, + * velocity: [0, 0], + * angularVelocity: 0 + * }); + * + * // Add a circular shape to the body + * body.addShape(new Circle({ radius: 1 })); + * + * // Add the body to the world + * world.addBody(body); + */ +function Body(options){ + options = options || {}; + + EventEmitter.call(this); + + /** + * The body identifyer + * @property id + * @type {Number} + */ + this.id = options.id || ++Body._idCounter; + + /** + * The world that this body is added to. This property is set to NULL if the body is not added to any world. + * @property world + * @type {World} + */ + this.world = null; + + /** + * The shapes of the body. + * + * @property shapes + * @type {Array} + */ + this.shapes = []; + + /** + * The mass of the body. + * @property mass + * @type {number} + */ + this.mass = options.mass || 0; + + /** + * The inverse mass of the body. + * @property invMass + * @type {number} + */ + this.invMass = 0; + + /** + * The inertia of the body around the Z axis. + * @property inertia + * @type {number} + */ + this.inertia = 0; + + /** + * The inverse inertia of the body. + * @property invInertia + * @type {number} + */ + this.invInertia = 0; + + this.invMassSolve = 0; + this.invInertiaSolve = 0; + + /** + * Set to true if you want to fix the rotation of the body. + * @property fixedRotation + * @type {Boolean} + */ + this.fixedRotation = !!options.fixedRotation; + + /** + * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y. + * @property {Boolean} fixedX + */ + this.fixedX = !!options.fixedX; + + /** + * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X. + * @property {Boolean} fixedY + */ + this.fixedY = !!options.fixedY; + + /** + * @private + * @property {array} massMultiplier + */ + this.massMultiplier = vec2.create(); + + /** + * The position of the body + * @property position + * @type {Array} + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * The interpolated position of the body. Use this for rendering. + * @property interpolatedPosition + * @type {Array} + */ + this.interpolatedPosition = vec2.fromValues(0,0); + + /** + * The interpolated angle of the body. Use this for rendering. + * @property interpolatedAngle + * @type {Number} + */ + this.interpolatedAngle = 0; + + /** + * The previous position of the body. + * @property previousPosition + * @type {Array} + */ + this.previousPosition = vec2.fromValues(0,0); + + /** + * The previous angle of the body. + * @property previousAngle + * @type {Number} + */ + this.previousAngle = 0; + + /** + * The current velocity of the body. + * @property velocity + * @type {Array} + */ + this.velocity = vec2.fromValues(0,0); + if(options.velocity){ + vec2.copy(this.velocity, options.velocity); + } + + /** + * Constraint velocity that was added to the body during the last step. + * @property vlambda + * @type {Array} + */ + this.vlambda = vec2.fromValues(0,0); + + /** + * Angular constraint velocity that was added to the body during last step. + * @property wlambda + * @type {Array} + */ + this.wlambda = 0; + + /** + * The angle of the body, in radians. + * @property angle + * @type {number} + * @example + * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. + * // If you need a value between 0 and 2*pi, use the following function to normalize it. + * function normalizeAngle(angle){ + * angle = angle % (2*Math.PI); + * if(angle < 0){ + * angle += (2*Math.PI); + * } + * return angle; + * } + */ + this.angle = options.angle || 0; + + /** + * The angular velocity of the body, in radians per second. + * @property angularVelocity + * @type {number} + */ + this.angularVelocity = options.angularVelocity || 0; + + /** + * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. + * @property force + * @type {Array} + * + * @example + * // This produces a forcefield of 1 Newton in the positive x direction. + * for(var i=0; i radius){ + radius = offset + r; + } + } + + this.boundingRadius = radius; +}; + +/** + * Add a shape to the body. You can pass a local transform when adding a shape, + * so that the shape gets an offset and angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * + * @method addShape + * @param {Shape} shape + * @param {Array} [offset] Local body offset of the shape. + * @param {Number} [angle] Local body angle. + * + * @example + * var body = new Body(), + * shape = new Circle({ radius: 1 }); + * + * // Add the shape to the body, positioned in the center + * body.addShape(shape); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. + * body.addShape(shape,[1,0]); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. + * body.addShape(shape,[0,1],Math.PI/2); + */ +Body.prototype.addShape = function(shape, offset, angle){ + if(shape.body){ + throw new Error('A shape can only be added to one body.'); + } + shape.body = this; + + // Copy the offset vector + if(offset){ + vec2.copy(shape.position, offset); + } else { + vec2.set(shape.position, 0, 0); + } + + shape.angle = angle || 0; + + this.shapes.push(shape); + this.updateMassProperties(); + this.updateBoundingRadius(); + + this.aabbNeedsUpdate = true; +}; + +/** + * Remove a shape + * @method removeShape + * @param {Shape} shape + * @return {Boolean} True if the shape was found and removed, else false. + */ +Body.prototype.removeShape = function(shape){ + var idx = this.shapes.indexOf(shape); + + if(idx !== -1){ + this.shapes.splice(idx,1); + this.aabbNeedsUpdate = true; + shape.body = null; + return true; + } else { + return false; + } +}; + +/** + * Updates .inertia, .invMass, .invInertia for this Body. Should be called when + * changing the structure or mass of the Body. + * + * @method updateMassProperties + * + * @example + * body.mass += 1; + * body.updateMassProperties(); + */ +Body.prototype.updateMassProperties = function(){ + if(this.type === Body.STATIC || this.type === 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; + } + + // Inverse mass properties are easy + this.invMass = 1 / this.mass; + + vec2.set( + this.massMultiplier, + this.fixedX ? 0 : 1, + this.fixedY ? 0 : 1 + ); + } +}; + +var Body_applyForce_r = vec2.create(); + +/** + * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero. + * @method applyForce + * @param {Array} force The force to add. + * @param {Array} [relativePoint] A world point to apply the force on. + */ +Body.prototype.applyForce = function(force, relativePoint){ + + // Add linear force + vec2.add(this.force, this.force, force); + + if(relativePoint){ + + // Compute produced rotational force + var rotForce = vec2.crossLength(relativePoint,force); + + // Add rotational force + this.angularForce += rotForce; + } +}; + +/** + * Apply force to a body-local point. + * @method applyForceLocal + * @param {Array} localForce The force vector to add, oriented in local body space. + * @param {Array} [localPoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyForce_forceWorld = vec2.create(); +var Body_applyForce_pointWorld = vec2.create(); +var Body_applyForce_pointLocal = vec2.create(); +Body.prototype.applyForceLocal = function(localForce, localPoint){ + localPoint = localPoint || Body_applyForce_pointLocal; + var worldForce = Body_applyForce_forceWorld; + var worldPoint = Body_applyForce_pointWorld; + this.vectorToWorldFrame(worldForce, localForce); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyForce(worldForce, worldPoint); +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulse + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_velo = vec2.create(); +Body.prototype.applyImpulse = function(impulseVector, relativePoint){ + if(this.type !== Body.DYNAMIC){ + return; + } + + // Compute produced central impulse velocity + var velo = Body_applyImpulse_velo; + vec2.scale(velo, impulseVector, this.invMass); + vec2.multiply(velo, this.massMultiplier, velo); + + // Add linear impulse + vec2.add(this.velocity, velo, this.velocity); + + if(relativePoint){ + // Compute produced rotational impulse velocity + var rotVelo = vec2.crossLength(relativePoint, impulseVector); + rotVelo *= this.invInertia; + + // Add rotational Impulse + this.angularVelocity += rotVelo; + } +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulseLocal + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_impulseWorld = vec2.create(); +var Body_applyImpulse_pointWorld = vec2.create(); +var Body_applyImpulse_pointLocal = vec2.create(); +Body.prototype.applyImpulseLocal = function(localImpulse, localPoint){ + localPoint = localPoint || Body_applyImpulse_pointLocal; + var worldImpulse = Body_applyImpulse_impulseWorld; + var worldPoint = Body_applyImpulse_pointWorld; + this.vectorToWorldFrame(worldImpulse, localImpulse); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyImpulse(worldImpulse, worldPoint); +}; + +/** + * Transform a world point to local body frame. + * @method toLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldPoint The input world point + */ +Body.prototype.toLocalFrame = function(out, worldPoint){ + vec2.toLocalFrame(out, worldPoint, this.position, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method toWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localPoint The input local point + */ +Body.prototype.toWorldFrame = function(out, localPoint){ + vec2.toGlobalFrame(out, localPoint, this.position, this.angle); +}; + +/** + * Transform a world point to local body frame. + * @method vectorToLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldVector The input world vector + */ +Body.prototype.vectorToLocalFrame = function(out, worldVector){ + vec2.vectorToLocalFrame(out, worldVector, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method vectorToWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localVector The input local vector + */ +Body.prototype.vectorToWorldFrame = function(out, localVector){ + vec2.vectorToGlobalFrame(out, localVector, this.angle); +}; + +/** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. + * @method fromPolygon + * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. + * @param {Object} [options] + * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. + * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @return {Boolean} True on success, else false. + */ +Body.prototype.fromPolygon = function(path,options){ + options = options || {}; + + // Remove all shapes + for(var i=this.shapes.length; i>=0; --i){ + this.removeShape(this.shapes[i]); + } + + var p = new decomp.Polygon(); + p.vertices = path; + + // Make it counter-clockwise + p.makeCCW(); + + if(typeof(options.removeCollinearPoints) === "number"){ + p.removeCollinearPoints(options.removeCollinearPoints); + } + + // Check if any line segment intersects the path itself + if(typeof(options.skipSimpleCheck) === "undefined"){ + if(!p.isSimple()){ + return false; + } + } + + // Save this path for later + this.concavePath = p.vertices.slice(0); + for(var i=0; ithis for details. + * @method applyDamping + * @param {number} dt Current time step + */ +Body.prototype.applyDamping = function(dt){ + if(this.type === Body.DYNAMIC){ // Only for dynamic bodies + var v = this.velocity; + vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); + this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); + } +}; + +/** + * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. + * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. + * @method wakeUp + */ +Body.prototype.wakeUp = function(){ + var s = this.sleepState; + this.sleepState = Body.AWAKE; + this.idleTime = 0; + if(s !== Body.AWAKE){ + this.emit(Body.wakeUpEvent); + } +}; + +/** + * Force body sleep + * @method sleep + */ +Body.prototype.sleep = function(){ + this.sleepState = Body.SLEEPING; + this.angularVelocity = 0; + this.angularForce = 0; + vec2.set(this.velocity,0,0); + vec2.set(this.force,0,0); + this.emit(Body.sleepEvent); +}; + +/** + * Called every timestep to update internal sleep timer and change sleep state if needed. + * @method sleepTick + * @param {number} time The world time in seconds + * @param {boolean} dontSleep + * @param {number} dt + */ +Body.prototype.sleepTick = function(time, dontSleep, dt){ + if(!this.allowSleep || this.type === Body.SLEEPING){ + return; + } + + this.wantsToSleep = false; + + var sleepState = this.sleepState, + speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), + speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); + + // Add to idle time + if(speedSquared >= 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; + } + } +}; + +/** + * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. + * @method overlaps + * @param {Body} body + * @return {boolean} + */ +Body.prototype.overlaps = function(body){ + return this.world.overlapKeeper.bodiesAreOverlapping(this, body); +}; + +var integrate_fhMinv = vec2.create(); +var integrate_velodt = vec2.create(); + +/** + * Move the body forward in time given its current velocity. + * @method integrate + * @param {Number} dt + */ +Body.prototype.integrate = function(dt){ + var minv = this.invMass, + f = this.force, + pos = this.position, + velo = this.velocity; + + // Save old position + vec2.copy(this.previousPosition, this.position); + this.previousAngle = this.angle; + + // Velocity update + if(!this.fixedRotation){ + this.angularVelocity += this.angularForce * this.invInertia * dt; + } + vec2.scale(integrate_fhMinv, f, dt * minv); + vec2.multiply(integrate_fhMinv, this.massMultiplier, integrate_fhMinv); + vec2.add(velo, integrate_fhMinv, velo); + + // CCD + if(!this.integrateToTimeOfImpact(dt)){ + + // Regular position update + vec2.scale(integrate_velodt, velo, dt); + vec2.add(pos, pos, integrate_velodt); + if(!this.fixedRotation){ + this.angle += this.angularVelocity * dt; + } + } + + this.aabbNeedsUpdate = true; +}; + +var result = new RaycastResult(); +var ray = new Ray({ + mode: Ray.ALL +}); +var direction = vec2.create(); +var end = vec2.create(); +var startToEnd = vec2.create(); +var rememberPosition = vec2.create(); +Body.prototype.integrateToTimeOfImpact = function(dt){ + + if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){ + return false; + } + + vec2.normalize(direction, this.velocity); + + vec2.scale(end, this.velocity, dt); + vec2.add(end, end, this.position); + + vec2.sub(startToEnd, end, this.position); + var startToEndAngle = this.angularVelocity * dt; + var len = vec2.length(startToEnd); + + var timeOfImpact = 1; + + var hit; + var that = this; + result.reset(); + ray.callback = function (result) { + if(result.body === that){ + return; + } + hit = result.body; + result.getHitPoint(end, ray); + vec2.sub(startToEnd, end, that.position); + timeOfImpact = vec2.length(startToEnd) / len; + result.stop(); + }; + vec2.copy(ray.from, this.position); + vec2.copy(ray.to, end); + ray.update(); + this.world.raycast(result, ray); + + if(!hit){ + return false; + } + + var rememberAngle = this.angle; + vec2.copy(rememberPosition, this.position); + + // Got a start and end point. Approximate time of impact using binary search + var iter = 0; + var tmin = 0; + var tmid = 0; + var tmax = timeOfImpact; + while (tmax >= tmin && iter < this.ccdIterations) { + iter++; + + // calculate the midpoint + tmid = (tmax - tmin) / 2; + + // Move the body to that point + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, rememberPosition, integrate_velodt); + this.angle = rememberAngle + startToEndAngle * timeOfImpact; + this.updateAABB(); + + // check overlap + var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit); + + if (overlaps) { + // change min to search upper interval + tmin = tmid; + } else { + // change max to search lower interval + tmax = tmid; + } + } + + timeOfImpact = tmid; + + vec2.copy(this.position, rememberPosition); + this.angle = rememberAngle; + + // move to TOI + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, this.position, integrate_velodt); + if(!this.fixedRotation){ + this.angle += startToEndAngle * timeOfImpact; + } + + return true; +}; + +/** + * Get velocity of a point in the body. + * @method getVelocityAtPoint + * @param {Array} result A vector to store the result in + * @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from + * @return {Array} The result vector + */ +Body.prototype.getVelocityAtPoint = function(result, relativePoint){ + vec2.crossVZ(result, relativePoint, this.angularVelocity); + vec2.subtract(result, this.velocity, result); + return result; +}; + +/** + * @event sleepy + */ +Body.sleepyEvent = { + type: "sleepy" +}; + +/** + * @event sleep + */ +Body.sleepEvent = { + type: "sleep" +}; + +/** + * @event wakeup + */ +Body.wakeUpEvent = { + type: "wakeup" +}; + +/** + * Dynamic body. + * @property DYNAMIC + * @type {Number} + * @static + */ +Body.DYNAMIC = 1; + +/** + * Static body. + * @property STATIC + * @type {Number} + * @static + */ +Body.STATIC = 2; + +/** + * Kinematic body. + * @property KINEMATIC + * @type {Number} + * @static + */ +Body.KINEMATIC = 4; + +/** + * @property AWAKE + * @type {Number} + * @static + */ +Body.AWAKE = 0; + +/** + * @property SLEEPY + * @type {Number} + * @static + */ +Body.SLEEPY = 1; + +/** + * @property SLEEPING + * @type {Number} + * @static + */ +Body.SLEEPING = 2; + + +},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = LinearSpring; + +/** + * A spring, connecting two bodies. + * + * The Spring explicitly adds force and angularForce to the bodies. + * + * @class LinearSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + */ +function LinearSpring(bodyA,bodyB,options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Anchor for bodyA in local bodyA coordinates. + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = vec2.fromValues(0,0); + + /** + * Anchor for bodyB in local bodyB coordinates. + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = vec2.fromValues(0,0); + + if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); } + if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); } + if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } + if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } + + var worldAnchorA = vec2.create(); + var worldAnchorB = vec2.create(); + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + var worldDistance = vec2.distance(worldAnchorA, worldAnchorB); + + /** + * Rest length of the spring. + * @property restLength + * @type {number} + */ + this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance; +} +LinearSpring.prototype = new Spring(); +LinearSpring.prototype.constructor = LinearSpring; + +/** + * Set the anchor point on body A, using world coordinates. + * @method setWorldAnchorA + * @param {Array} worldAnchorA + */ +LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){ + this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); +}; + +/** + * Set the anchor point on body B, using world coordinates. + * @method setWorldAnchorB + * @param {Array} worldAnchorB + */ +LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){ + this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); +}; + +/** + * Get the anchor point on body A, in world coordinates. + * @method getWorldAnchorA + * @param {Array} result The vector to store the result in. + */ +LinearSpring.prototype.getWorldAnchorA = function(result){ + this.bodyA.toWorldFrame(result, this.localAnchorA); +}; + +/** + * Get the anchor point on body B, in world coordinates. + * @method getWorldAnchorB + * @param {Array} result The vector to store the result in. + */ +LinearSpring.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(); + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +LinearSpring.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; + + // Get world anchors + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + + // Get offset points + vec2.sub(ri, worldAnchorA, bodyA.position); + vec2.sub(rj, worldAnchorB, bodyB.position); + + // Compute distance vector between world anchor points + vec2.sub(r, worldAnchorB, worldAnchorA); + var rlen = vec2.len(r); + vec2.normalize(r_unit,r); + + //console.log(rlen) + //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) + + // Compute relative velocity of the anchor points, u + 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); + + // F = - k * ( x - L ) - D * ( u ) + vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); + + // Add forces to bodies + vec2.sub( bodyA.force, bodyA.force, f); + vec2.add( bodyB.force, bodyB.force, f); + + // Angular force + 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":57,"./Spring":34}],33:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); + +module.exports = RotationalSpring; + +/** + * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies. + * + * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap. + * + * @class RotationalSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. + */ +function RotationalSpring(bodyA, bodyB, options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Rest angle of the spring. + * @property restAngle + * @type {number} + */ + this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle; +} +RotationalSpring.prototype = new Spring(); +RotationalSpring.prototype.constructor = RotationalSpring; + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +RotationalSpring.prototype.applyForce = function(){ + var k = this.stiffness, + d = this.damping, + l = this.restAngle, + bodyA = this.bodyA, + bodyB = this.bodyB, + x = bodyB.angle - bodyA.angle, + u = bodyB.angularVelocity - bodyA.angularVelocity; + + var torque = - k * (x - l) - d * u * 0; + + bodyA.angularForce -= torque; + bodyB.angularForce += torque; +}; + +},{"../math/vec2":30,"./Spring":34}],34:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = Spring; + +/** + * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver. + * + * @class Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + */ +function Spring(bodyA, bodyB, options){ + options = Utils.defaults(options,{ + stiffness: 100, + damping: 1, + }); + + /** + * Stiffness of the spring. + * @property stiffness + * @type {number} + */ + this.stiffness = options.stiffness; + + /** + * Damping of the spring. + * @property damping + * @type {number} + */ + this.damping = options.damping; + + /** + * First connected body. + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second connected body. + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; +} + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +Spring.prototype.applyForce = function(){ + // To be implemented by subclasses +}; + +},{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); +var Constraint = _dereq_('../constraints/Constraint'); +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Body = _dereq_('../objects/Body'); + +module.exports = TopDownVehicle; + +/** + * @class TopDownVehicle + * @constructor + * @param {Body} chassisBody A dynamic body, already added to the world. + * @param {Object} [options] + * + * @example + * + * // Create a dynamic body for the chassis + * var chassisBody = new Body({ + * mass: 1 + * }); + * var boxShape = new Box({ width: 0.5, height: 1 }); + * chassisBody.addShape(boxShape); + * world.addBody(chassisBody); + * + * // Create the vehicle + * var vehicle = new TopDownVehicle(chassisBody); + * + * // Add one front wheel and one back wheel - we don't actually need four :) + * var frontWheel = vehicle.addWheel({ + * localPosition: [0, 0.5] // front + * }); + * frontWheel.setSideFriction(4); + * + * // Back wheel + * var backWheel = vehicle.addWheel({ + * localPosition: [0, -0.5] // back + * }); + * backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift + * vehicle.addToWorld(world); + * + * // Steer value zero means straight forward. Positive is left and negative right. + * frontWheel.steerValue = Math.PI / 16; + * + * // Engine force forward + * backWheel.engineForce = 10; + * backWheel.setBrakeForce(0); + */ +function TopDownVehicle(chassisBody, options){ + options = options || {}; + + /** + * @property {Body} chassisBody + */ + this.chassisBody = chassisBody; + + /** + * @property {Array} wheels + */ + this.wheels = []; + + // A dummy body to constrain the chassis to + this.groundBody = new Body({ mass: 0 }); + + this.world = null; + + var that = this; + this.preStepCallback = function(){ + that.update(); + }; +} + +/** + * @method addToWorld + * @param {World} world + */ +TopDownVehicle.prototype.addToWorld = function(world){ + this.world = world; + world.addBody(this.groundBody); + world.on('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.addConstraint(wheel); + } +}; + +/** + * @method removeFromWorld + * @param {World} world + */ +TopDownVehicle.prototype.removeFromWorld = function(){ + var world = this.world; + world.removeBody(this.groundBody); + world.off('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.removeConstraint(wheel); + } + this.world = null; +}; + +/** + * @method addWheel + * @param {object} [wheelOptions] + * @return {WheelConstraint} + */ +TopDownVehicle.prototype.addWheel = function(wheelOptions){ + var wheel = new WheelConstraint(this,wheelOptions); + this.wheels.push(wheel); + return wheel; +}; + +/** + * @method update + */ +TopDownVehicle.prototype.update = function(){ + for (var i = 0; i < this.wheels.length; i++) { + this.wheels[i].update(); + } +}; + +/** + * @class WheelConstraint + * @constructor + * @extends {Constraint} + * @param {Vehicle} vehicle + * @param {object} [options] + * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero. + * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body. + * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction. + */ +function WheelConstraint(vehicle, options){ + options = options || {}; + + this.vehicle = vehicle; + + this.forwardEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + this.sideEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + /** + * @property {number} steerValue + */ + this.steerValue = 0; + + /** + * @property {number} engineForce + */ + this.engineForce = 0; + + this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5); + + /** + * @property {Array} localForwardVector + */ + this.localForwardVector = vec2.fromValues(0, 1); + if(options.localForwardVector){ + vec2.copy(this.localForwardVector, options.localForwardVector); + } + + /** + * @property {Array} localPosition + */ + this.localPosition = vec2.fromValues(0, 0); + if(options.localPosition){ + vec2.copy(this.localPosition, options.localPosition); + } + + Constraint.apply(this, vehicle.chassisBody, vehicle.groundBody); + + this.equations.push( + this.forwardEquation, + this.sideEquation + ); + + this.setBrakeForce(0); +} +WheelConstraint.prototype = new Constraint(); + +/** + * @method setForwardFriction + */ +WheelConstraint.prototype.setBrakeForce = function(force){ + this.forwardEquation.setSlipForce(force); +}; + +/** + * @method setSideFriction + */ +WheelConstraint.prototype.setSideFriction = function(force){ + this.sideEquation.setSlipForce(force); +}; + +var worldVelocity = vec2.create(); +var relativePoint = vec2.create(); + +/** + * @method getSpeed + */ +WheelConstraint.prototype.getSpeed = function(){ + this.vehicle.chassisBody.vectorToWorldFrame(relativePoint, this.localForwardVector); + this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity, relativePoint); + return vec2.dot(worldVelocity, relativePoint); +}; + +var tmpVec = vec2.create(); + +/** + * @method update + */ +WheelConstraint.prototype.update = function(){ + + // Directional + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t, this.localForwardVector); + vec2.rotate(this.sideEquation.t, this.localForwardVector, Math.PI / 2); + this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t, this.sideEquation.t); + + vec2.rotate(this.forwardEquation.t, this.forwardEquation.t, this.steerValue); + vec2.rotate(this.sideEquation.t, this.sideEquation.t, this.steerValue); + + // Attachment point + this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB, this.localPosition); + vec2.copy(this.sideEquation.contactPointB, this.forwardEquation.contactPointB); + + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA, this.localPosition); + vec2.copy(this.sideEquation.contactPointA, this.forwardEquation.contactPointA); + + // Add engine force + vec2.normalize(tmpVec, this.forwardEquation.t); + vec2.scale(tmpVec, tmpVec, this.engineForce); + + this.vehicle.chassisBody.applyForce(tmpVec, this.forwardEquation.contactPointA); +}; +},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(_dereq_,module,exports){ +// Export p2 classes +var p2 = module.exports = { + AABB : _dereq_('./collision/AABB'), + AngleLockEquation : _dereq_('./equations/AngleLockEquation'), + Body : _dereq_('./objects/Body'), + Broadphase : _dereq_('./collision/Broadphase'), + Capsule : _dereq_('./shapes/Capsule'), + Circle : _dereq_('./shapes/Circle'), + Constraint : _dereq_('./constraints/Constraint'), + ContactEquation : _dereq_('./equations/ContactEquation'), + ContactEquationPool : _dereq_('./utils/ContactEquationPool'), + ContactMaterial : _dereq_('./material/ContactMaterial'), + Convex : _dereq_('./shapes/Convex'), + DistanceConstraint : _dereq_('./constraints/DistanceConstraint'), + Equation : _dereq_('./equations/Equation'), + EventEmitter : _dereq_('./events/EventEmitter'), + FrictionEquation : _dereq_('./equations/FrictionEquation'), + FrictionEquationPool : _dereq_('./utils/FrictionEquationPool'), + GearConstraint : _dereq_('./constraints/GearConstraint'), + GSSolver : _dereq_('./solver/GSSolver'), + Heightfield : _dereq_('./shapes/Heightfield'), + Line : _dereq_('./shapes/Line'), + LockConstraint : _dereq_('./constraints/LockConstraint'), + Material : _dereq_('./material/Material'), + Narrowphase : _dereq_('./collision/Narrowphase'), + NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'), + Particle : _dereq_('./shapes/Particle'), + Plane : _dereq_('./shapes/Plane'), + Pool : _dereq_('./utils/Pool'), + RevoluteConstraint : _dereq_('./constraints/RevoluteConstraint'), + PrismaticConstraint : _dereq_('./constraints/PrismaticConstraint'), + Ray : _dereq_('./collision/Ray'), + RaycastResult : _dereq_('./collision/RaycastResult'), + Box : _dereq_('./shapes/Box'), + RotationalVelocityEquation : _dereq_('./equations/RotationalVelocityEquation'), + SAPBroadphase : _dereq_('./collision/SAPBroadphase'), + Shape : _dereq_('./shapes/Shape'), + Solver : _dereq_('./solver/Solver'), + Spring : _dereq_('./objects/Spring'), + TopDownVehicle : _dereq_('./objects/TopDownVehicle'), + LinearSpring : _dereq_('./objects/LinearSpring'), + RotationalSpring : _dereq_('./objects/RotationalSpring'), + Utils : _dereq_('./utils/Utils'), + World : _dereq_('./world/World'), + vec2 : _dereq_('./math/vec2'), + version : _dereq_('../package.json').version, +}; + +Object.defineProperty(p2, 'Rectangle', { + get: function() { + console.warn('The Rectangle class has been renamed to Box.'); + return this.Box; + } +}); +},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":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/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Shape = _dereq_('./Shape') +, Convex = _dereq_('./Convex'); + +module.exports = Box; + +/** + * Box shape class. + * @class Box + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.width=1] Total width of the box + * @param {Number} [options.height=1] Total height of the box + * @extends Convex + */ +function Box(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + width: arguments[0], + height: arguments[1] + }; + console.warn('The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })'); + } + options = options || {}; + + /** + * Total width of the box + * @property width + * @type {Number} + */ + var width = this.width = options.width || 1; + + /** + * Total height of the box + * @property height + * @type {Number} + */ + var height = this.height = options.height || 1; + + var verts = [ + vec2.fromValues(-width/2, -height/2), + vec2.fromValues( width/2, -height/2), + vec2.fromValues( width/2, height/2), + vec2.fromValues(-width/2, height/2) + ]; + var axes = [ + vec2.fromValues(1, 0), + vec2.fromValues(0, 1) + ]; + + options.vertices = verts; + options.axes = axes; + options.type = Shape.BOX; + Convex.call(this, options); +} +Box.prototype = new Convex(); +Box.prototype.constructor = Box; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Box.prototype.computeMomentOfInertia = function(mass){ + var w = this.width, + h = this.height; + return mass * (h*h + w*w) / 12; +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Box.prototype.updateBoundingRadius = function(){ + var w = this.width, + h = this.height; + this.boundingRadius = Math.sqrt(w*w + h*h) / 2; +}; + +var corner1 = vec2.create(), + corner2 = vec2.create(), + corner3 = vec2.create(), + corner4 = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Box.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices,position,angle,0); +}; + +Box.prototype.updateArea = function(){ + this.area = this.width * this.height; +}; + + +},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Capsule; + +/** + * Capsule shape class. + * @class Capsule + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The distance between the end points + * @param {Number} [options.radius=1] Radius of the capsule + * @example + * var capsuleShape = new Capsule({ + * length: 1, + * radius: 2 + * }); + * body.addShape(capsuleShape); + */ +function Capsule(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + length: arguments[0], + radius: arguments[1] + }; + console.warn('The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })'); + } + options = options || {}; + + /** + * The distance between the end points. + * @property {Number} length + */ + this.length = options.length || 1; + + /** + * The radius of the capsule. + * @property {Number} radius + */ + this.radius = options.radius || 1; + + options.type = Shape.CAPSULE; + Shape.call(this, options); +} +Capsule.prototype = new Shape(); +Capsule.prototype.constructor = Capsule; + +/** + * Compute the mass moment of inertia of the Capsule. + * @method conputeMomentOfInertia + * @param {Number} mass + * @return {Number} + * @todo + */ +Capsule.prototype.computeMomentOfInertia = function(mass){ + // Approximate with rectangle + var r = this.radius, + w = this.length + r, // 2*r is too much, 0 is too little + h = r*2; + return mass * (h*h + w*w) / 12; +}; + +/** + * @method updateBoundingRadius + */ +Capsule.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius + this.length/2; +}; + +/** + * @method updateArea + */ +Capsule.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; +}; + +var r = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Capsule.prototype.computeAABB = function(out, position, angle){ + var radius = this.radius; + + // Compute center position of one of the the circles, world oriented, but with local offset + vec2.set(r,this.length / 2,0); + if(angle !== 0){ + vec2.rotate(r,r,angle); + } + + // Get bounds + 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)); + + // Add offset + vec2.add(out.lowerBound, out.lowerBound, position); + vec2.add(out.upperBound, out.upperBound, position); +}; + +var intersectCapsule_hitPointWorld = vec2.create(); +var intersectCapsule_normal = vec2.create(); +var intersectCapsule_l0 = vec2.create(); +var intersectCapsule_l1 = vec2.create(); +var intersectCapsule_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Capsule.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectCapsule_hitPointWorld; + var normal = intersectCapsule_normal; + var l0 = intersectCapsule_l0; + var l1 = intersectCapsule_l1; + + // The sides + var halfLen = this.length / 2; + for(var i=0; i<2; i++){ + + // get start and end of the line + var y = this.radius * (i*2-1); + vec2.set(l0, -halfLen, y); + vec2.set(l1, halfLen, y); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var delta = vec2.getLineSegmentsIntersectionFraction(from, to, l0, l1); + if(delta >= 0){ + vec2.rotate(normal, intersectCapsule_unit_y, angle); + vec2.scale(normal, normal, (i*2-1)); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + // Circles + var diagonalLengthSquared = Math.pow(this.radius, 2) + Math.pow(halfLen, 2); + for(var i=0; i<2; i++){ + vec2.set(l0, halfLen * (i*2-1), 0); + vec2.toGlobalFrame(l0, l0, position, angle); + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - l0[0]) + (to[1] - from[1]) * (from[1] - l0[1])); + var c = Math.pow(from[0] - l0[0], 2) + Math.pow(from[1] - l0[1], 2) - Math.pow(this.radius, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + if(delta < 0){ + // No intersection + continue; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(hitPointWorld, from, to, delta); + + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(hitPointWorld, from, to, d1); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d1, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(hitPointWorld, from, to, d2); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d2, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + } + } +}; +},{"../math/vec2":30,"./Shape":45}],39:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Circle; + +/** + * Circle shape class. + * @class Circle + * @extends Shape + * @constructor + * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {number} [options.radius=1] The radius of this circle + * + * @example + * var circleShape = new Circle({ radius: 1 }); + * body.addShape(circleShape); + */ +function Circle(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + radius: arguments[0] + }; + console.warn('The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })'); + } + options = options || {}; + + /** + * The radius of the circle. + * @property radius + * @type {number} + */ + this.radius = options.radius || 1; + + options.type = Shape.CIRCLE; + Shape.call(this, options); +} +Circle.prototype = new Shape(); +Circle.prototype.constructor = Circle; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Circle.prototype.computeMomentOfInertia = function(mass){ + var r = this.radius; + return mass * r * r / 2; +}; + +/** + * @method updateBoundingRadius + * @return {Number} + */ +Circle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius; +}; + +/** + * @method updateArea + * @return {Number} + */ +Circle.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius; +}; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +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); + } +}; + +var Ray_intersectSphere_intersectionPoint = vec2.create(); +var Ray_intersectSphere_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Circle.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from, + to = ray.to, + r = this.radius; + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1])); + var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + var intersectionPoint = Ray_intersectSphere_intersectionPoint; + var normal = Ray_intersectSphere_normal; + + if(delta < 0){ + // No intersection + return; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(intersectionPoint, from, to, delta); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, delta, normal, -1); + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(intersectionPoint, from, to, d1); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d1, normal, -1); + + if(result.shouldStop(ray)){ + return; + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(intersectionPoint, from, to, d2); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d2, normal, -1); + } + } +}; +},{"../math/vec2":30,"./Shape":45}],40:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, polyk = _dereq_('../math/polyk') +, decomp = _dereq_('poly-decomp'); + +module.exports = Convex; + +/** + * Convex shape class. + * @class Convex + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. + * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex. + * @example + * // Create a box + * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]]; + * var convexShape = new Convex({ vertices: vertices }); + * body.addShape(convexShape); + */ +function Convex(options){ + if(Array.isArray(arguments[0])){ + options = { + vertices: arguments[0], + axes: arguments[1] + }; + console.warn('The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })'); + } + options = options || {}; + + /** + * Vertices defined in the local frame. + * @property vertices + * @type {Array} + */ + this.vertices = []; + + // Copy the verts + var vertices = options.vertices !== undefined ? options.vertices : []; + for(var i=0; i < vertices.length; i++){ + var v = vec2.create(); + vec2.copy(v, vertices[i]); + this.vertices.push(v); + } + + /** + * Axes defined in the local frame. + * @property axes + * @type {Array} + */ + this.axes = []; + + if(options.axes){ + + // Copy the axes + for(var i=0; i < options.axes.length; i++){ + var axis = vec2.create(); + vec2.copy(axis, options.axes[i]); + this.axes.push(axis); + } + + } else { + + // Construct axes from the vertex data + for(var i = 0; i < this.vertices.length; i++){ + // Get the world edge + var worldPoint0 = this.vertices[i]; + var worldPoint1 = this.vertices[(i+1) % this.vertices.length]; + + var normal = vec2.create(); + vec2.sub(normal, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, normal); + vec2.normalize(normal, normal); + + this.axes.push(normal); + } + + } + + /** + * The center of mass of the Convex + * @property centerOfMass + * @type {Array} + */ + this.centerOfMass = vec2.fromValues(0,0); + + /** + * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. + * @property triangles + * @type {Array} + */ + this.triangles = []; + + if(this.vertices.length){ + this.updateTriangles(); + this.updateCenterOfMass(); + } + + /** + * The bounding radius of the convex + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + options.type = Shape.CONVEX; + Shape.call(this, options); + + this.updateBoundingRadius(); + this.updateArea(); + if(this.area < 0){ + throw new Error("Convex vertices must be given in conter-clockwise winding."); + } +} +Convex.prototype = new Shape(); +Convex.prototype.constructor = Convex; + +var tmpVec1 = vec2.create(); +var tmpVec2 = vec2.create(); + +/** + * Project a Convex onto a world-oriented axis + * @method projectOntoAxis + * @static + * @param {Array} offset + * @param {Array} localAxis + * @param {Array} result + */ +Convex.prototype.projectOntoLocalAxis = function(localAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = tmpVec1; + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + vec2.set(result, min, max); +}; + +Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){ + var worldAxis = tmpVec2; + + this.projectOntoLocalAxis(localAxis, result); + + // Project the position of the body onto the axis - need to add this to the result + if(shapeAngle !== 0){ + vec2.rotate(worldAxis, localAxis, shapeAngle); + } else { + worldAxis = localAxis; + } + var offset = vec2.dot(shapeOffset, worldAxis); + + vec2.set(result, result[0] + offset, result[1] + offset); +}; + + +/** + * Update the .triangles property + * @method updateTriangles + */ +Convex.prototype.updateTriangles = function(){ + + this.triangles.length = 0; + + // Rewrite on polyk notation, array of numbers + var polykVerts = []; + for(var i=0; i r2){ + r2 = l2; + } + } + + this.boundingRadius = Math.sqrt(r2); +}; + +/** + * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. + * @static + * @method triangleArea + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +Convex.triangleArea = function(a,b,c){ + return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; +}; + +/** + * Update the .area + * @method updateArea + */ +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]]; + + // Get mass for the triangle (density=1 in this case) + var m = Convex.triangleArea(a,b,c); + this.area += m; + } +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Convex.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices, position, angle, 0); +}; + +var intersectConvex_rayStart = vec2.create(); +var intersectConvex_rayEnd = vec2.create(); +var intersectConvex_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Convex.prototype.raycast = function(result, ray, position, angle){ + var rayStart = intersectConvex_rayStart; + var rayEnd = intersectConvex_rayEnd; + var normal = intersectConvex_normal; + var vertices = this.vertices; + + // Transform to local shape space + vec2.toLocalFrame(rayStart, ray.from, position, angle); + vec2.toLocalFrame(rayEnd, ray.to, position, angle); + + var n = vertices.length; + + for (var i = 0; i < n && !result.shouldStop(ray); i++) { + var q1 = vertices[i]; + var q2 = vertices[(i+1) % n]; + var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2); + + if(delta >= 0){ + vec2.sub(normal, q2, q1); + vec2.rotate(normal, normal, -Math.PI / 2 + angle); + vec2.normalize(normal, normal); + ray.reportIntersection(result, delta, normal, i); + } + } +}; + +},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Heightfield; + +/** + * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". + * @class Heightfield + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {array} [options.heights] An array of Y values that will be used to construct the terrain. + * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given. + * @param {Number} [options.maxValue] Maximum value. + * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction. + * + * @example + * // Generate some height data (y-values). + * var heights = []; + * for(var i = 0; i < 1000; i++){ + * var y = 0.5 * Math.cos(0.2 * i); + * heights.push(y); + * } + * + * // Create the heightfield shape + * var heightfieldShape = new Heightfield({ + * heights: heights, + * elementWidth: 1 // Distance between the data points in X direction + * }); + * var heightfieldBody = new Body(); + * heightfieldBody.addShape(heightfieldShape); + * world.addBody(heightfieldBody); + * + * @todo Should use a scale property with X and Y direction instead of just elementWidth + */ +function Heightfield(options){ + if(Array.isArray(arguments[0])){ + options = { + heights: arguments[0] + }; + + if(typeof(arguments[1]) === 'object'){ + for(var key in arguments[1]){ + options[key] = arguments[1][key]; + } + } + + console.warn('The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })'); + } + options = options || {}; + + /** + * An array of numbers, or height values, that are spread out along the x axis. + * @property {array} heights + */ + this.heights = options.heights ? options.heights.slice(0) : []; + + /** + * Max value of the heights + * @property {number} maxValue + */ + this.maxValue = options.maxValue || null; + + /** + * Max value of the heights + * @property {number} minValue + */ + this.minValue = options.minValue || null; + + /** + * The width of each element + * @property {number} elementWidth + */ + this.elementWidth = options.elementWidth || 0.1; + + if(options.maxValue === undefined || options.minValue === undefined){ + this.updateMaxMinValues(); + } + + options.type = Shape.HEIGHTFIELD; + Shape.call(this, options); +} +Heightfield.prototype = new Shape(); +Heightfield.prototype.constructor = Heightfield; + +/** + * Update the .minValue and the .maxValue + * @method updateMaxMinValues + */ +Heightfield.prototype.updateMaxMinValues = function(){ + var data = this.heights; + var maxValue = data[0]; + var minValue = data[0]; + for(var i=0; i !== data.length; i++){ + var v = data[i]; + if(v > maxValue){ + maxValue = v; + } + if(v < minValue){ + minValue = v; + } + } + this.maxValue = maxValue; + this.minValue = minValue; +}; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Heightfield.prototype.computeMomentOfInertia = function(mass){ + return Number.MAX_VALUE; +}; + +Heightfield.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +Heightfield.prototype.updateArea = function(){ + var data = this.heights, + area = 0; + for(var i=0; i= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + var intX = p0[0] + (t * s1_x); + var intY = p0[1] + (t * s1_y); + out[0] = intX; + out[1] = intY; + return t; + } + return -1; // No collision +} + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Heightfield.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectHeightfield_hitPointWorld; + var worldNormal = intersectHeightfield_worldNormal; + var l0 = intersectHeightfield_l0; + var l1 = intersectHeightfield_l1; + var localFrom = intersectHeightfield_localFrom; + var localTo = intersectHeightfield_localTo; + + // get local ray start and end + vec2.toLocalFrame(localFrom, from, position, angle); + vec2.toLocalFrame(localTo, to, position, angle); + + // Get the segment range + var i0 = this.getClampedSegmentIndex(localFrom); + var i1 = this.getClampedSegmentIndex(localTo); + if(i0 > i1){ + var tmp = i0; + i0 = i1; + i1 = tmp; + } + + // The segments + for(var i=0; i= 0){ + vec2.sub(worldNormal, l1, l0); + vec2.rotate(worldNormal, worldNormal, angle + Math.PI / 2); + vec2.normalize(worldNormal, worldNormal); + ray.reportIntersection(result, t, worldNormal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Line; + +/** + * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * @class Line + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The total length of the line + * @extends Shape + * @constructor + */ +function Line(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + length: arguments[0] + }; + console.warn('The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })'); + } + options = options || {}; + + /** + * Length of this line + * @property {Number} length + * @default 1 + */ + this.length = options.length || 1; + + options.type = Shape.LINE; + Shape.call(this, options); +} +Line.prototype = new Shape(); +Line.prototype.constructor = Line; + +Line.prototype.computeMomentOfInertia = function(mass){ + return mass * Math.pow(this.length,2) / 12; +}; + +Line.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.length/2; +}; + +var points = [vec2.create(),vec2.create()]; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Line.prototype.computeAABB = function(out, position, angle){ + var l2 = this.length / 2; + vec2.set(points[0], -l2, 0); + vec2.set(points[1], l2, 0); + out.setFromPoints(points,position,angle,0); +}; + +var raycast_hitPoint = vec2.create(); +var raycast_normal = vec2.create(); +var raycast_l0 = vec2.create(); +var raycast_l1 = vec2.create(); +var raycast_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {number} angle + * @param {array} position + */ +Line.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + + var l0 = raycast_l0; + var l1 = raycast_l1; + + // get start and end of the line + var halfLen = this.length / 2; + vec2.set(l0, -halfLen, 0); + vec2.set(l1, halfLen, 0); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to); + if(fraction >= 0){ + var normal = raycast_normal; + vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from + ray.reportIntersection(result, fraction, normal, -1); + } +}; +},{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Particle; + +/** + * Particle shape class. + * @class Particle + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @extends Shape + */ +function Particle(options){ + options = options || {}; + options.type = Shape.PARTICLE; + Shape.call(this, options); +} +Particle.prototype = new Shape(); +Particle.prototype.constructor = Particle; + +Particle.prototype.computeMomentOfInertia = function(mass){ + return 0; // Can't rotate a particle +}; + +Particle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = 0; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Particle.prototype.computeAABB = function(out, position, angle){ + vec2.copy(out.lowerBound, position); + vec2.copy(out.upperBound, position); +}; + +},{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Plane; + +/** + * Plane shape class. The plane is facing in the Y direction. + * @class Plane + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + */ +function Plane(options){ + options = options || {}; + options.type = Shape.PLANE; + Shape.call(this, options); +} +Plane.prototype = new Shape(); +Plane.prototype.constructor = Plane; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + */ +Plane.prototype.computeMomentOfInertia = function(mass){ + return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Plane.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Plane.prototype.computeAABB = function(out, position, angle){ + var a = angle % (2 * Math.PI); + var set = vec2.set; + var max = 1e7; + var lowerBound = out.lowerBound; + var upperBound = out.upperBound; + + // Set max bounds + set(lowerBound, -max, -max); + set(upperBound, max, max); + + if(a === 0){ + // y goes from -inf to 0 + upperBound[1] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, max, 0); + + } else if(a === Math.PI / 2){ + + // x goes from 0 to inf + lowerBound[0] = 0; + // set(lowerBound, 0, -max); + // set(upperBound, max, max); + + } else if(a === Math.PI){ + + // y goes from 0 to inf + lowerBound[1] = 0; + // set(lowerBound, -max, 0); + // set(upperBound, max, max); + + } else if(a === 3*Math.PI/2){ + + // x goes from -inf to 0 + upperBound[0] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, 0, max); + + } +}; + +Plane.prototype.updateArea = function(){ + this.area = Number.MAX_VALUE; +}; + +var intersectPlane_planePointToFrom = vec2.create(); +var intersectPlane_dir_scaled_with_t = vec2.create(); +var intersectPlane_hitPoint = vec2.create(); +var intersectPlane_normal = vec2.create(); +var intersectPlane_len = vec2.create(); + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Plane.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + var planePointToFrom = intersectPlane_planePointToFrom; + var dir_scaled_with_t = intersectPlane_dir_scaled_with_t; + var hitPoint = intersectPlane_hitPoint; + var normal = intersectPlane_normal; + var len = intersectPlane_len; + + // Get plane normal + vec2.set(normal, 0, 1); + vec2.rotate(normal, normal, angle); + + vec2.sub(len, from, position); + var planeToFrom = vec2.dot(len, normal); + vec2.sub(len, to, position); + var planeToTo = vec2.dot(len, normal); + + if(planeToFrom * planeToTo > 0){ + // "from" and "to" are on the same side of the plane... bail out + return; + } + + if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){ + return; + } + + var n_dot_dir = vec2.dot(normal, direction); + + vec2.sub(planePointToFrom, from, position); + var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length; + + ray.reportIntersection(result, t, normal, -1); +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(_dereq_,module,exports){ +module.exports = Shape; + +var vec2 = _dereq_('../math/vec2'); + +/** + * Base class for shapes. + * @class Shape + * @constructor + * @param {object} [options] + * @param {array} [options.position] + * @param {number} [options.angle=0] + * @param {number} [options.collisionGroup=1] + * @param {number} [options.collisionMask=1] + * @param {boolean} [options.sensor=false] + * @param {boolean} [options.collisionResponse=true] + * @param {object} [options.type=0] + */ +function Shape(options){ + options = options || {}; + + /** + * The body this shape is attached to. A shape can only be attached to a single body. + * @property {Body} body + */ + this.body = null; + + /** + * Body-local position of the shape. + * @property {Array} position + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * Body-local angle of the shape. + * @property {number} angle + */ + this.angle = options.angle || 0; + + /** + * The type of the shape. One of: + * + * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} + * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} + * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} + * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} + * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} + * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}} + * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} + * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} + * + * @property {number} type + */ + this.type = options.type || 0; + + /** + * Shape object identifier. + * @type {Number} + * @property id + */ + this.id = Shape.idCounter++; + + /** + * Bounding circle radius of this shape + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + /** + * Collision group that this shape belongs to (bit mask). See this tutorial. + * @property collisionGroup + * @type {Number} + * @example + * // Setup bits for each available group + * var PLAYER = Math.pow(2,0), + * ENEMY = Math.pow(2,1), + * GROUND = Math.pow(2,2) + * + * // Put shapes into their groups + * player1Shape.collisionGroup = PLAYER; + * player2Shape.collisionGroup = PLAYER; + * enemyShape .collisionGroup = ENEMY; + * groundShape .collisionGroup = GROUND; + * + * // Assign groups that each shape collide with. + * // Note that the players can collide with ground and enemies, but not with other players. + * player1Shape.collisionMask = ENEMY | GROUND; + * player2Shape.collisionMask = ENEMY | GROUND; + * enemyShape .collisionMask = PLAYER | GROUND; + * groundShape .collisionMask = PLAYER | ENEMY; + * + * @example + * // How collision check is done + * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ + * // The shapes will collide + * } + */ + this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. + * @property {Boolean} collisionResponse + */ + this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; + + /** + * Collision mask of this shape. See .collisionGroup. + * @property collisionMask + * @type {Number} + */ + this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; + + /** + * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. + * @property material + * @type {Material} + */ + this.material = options.material || null; + + /** + * Area of this shape. + * @property area + * @type {Number} + */ + this.area = 0; + + /** + * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. + * @property {Boolean} sensor + */ + this.sensor = options.sensor !== undefined ? options.sensor : false; + + if(this.type){ + this.updateBoundingRadius(); + } + + this.updateArea(); +} + +Shape.idCounter = 0; + +/** + * @static + * @property {Number} CIRCLE + */ +Shape.CIRCLE = 1; + +/** + * @static + * @property {Number} PARTICLE + */ +Shape.PARTICLE = 2; + +/** + * @static + * @property {Number} PLANE + */ +Shape.PLANE = 4; + +/** + * @static + * @property {Number} CONVEX + */ +Shape.CONVEX = 8; + +/** + * @static + * @property {Number} LINE + */ +Shape.LINE = 16; + +/** + * @static + * @property {Number} BOX + */ +Shape.BOX = 32; + +/** + * @static + * @property {Number} CAPSULE + */ +Shape.CAPSULE = 64; + +/** + * @static + * @property {Number} HEIGHTFIELD + */ +Shape.HEIGHTFIELD = 128; + +/** + * Should return the moment of inertia around the Z axis of the body given the total mass. See Wikipedia's list of moments of inertia. + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. + */ +Shape.prototype.computeMomentOfInertia = function(mass){}; + +/** + * Returns the bounding circle radius of this shape. + * @method updateBoundingRadius + * @return {Number} + */ +Shape.prototype.updateBoundingRadius = function(){}; + +/** + * Update the .area property of the shape. + * @method updateArea + */ +Shape.prototype.updateArea = function(){ + // To be implemented in all subclasses +}; + +/** + * Compute the world axis-aligned bounding box (AABB) of this shape. + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position World position of the shape. + * @param {Number} angle World angle of the shape. + */ +Shape.prototype.computeAABB = function(out, position, angle){ + // To be implemented in each subclass +}; + +/** + * Perform raycasting on this shape. + * @method raycast + * @param {RayResult} result Where to store the resulting data. + * @param {Ray} ray The Ray that you want to use for raycasting. + * @param {array} position World position of the shape (the .position property will be ignored). + * @param {number} angle World angle of the shape (the .angle property will be ignored). + */ +Shape.prototype.raycast = function(result, ray, position, angle){ + // To be implemented in each subclass +}; +},{"../math/vec2":30}],46:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Solver = _dereq_('./Solver') +, Utils = _dereq_('../utils/Utils') +, FrictionEquation = _dereq_('../equations/FrictionEquation'); + +module.exports = GSSolver; + +/** + * Iterative Gauss-Seidel constraint equation solver. + * + * @class GSSolver + * @constructor + * @extends Solver + * @param {Object} [options] + * @param {Number} [options.iterations=10] + * @param {Number} [options.tolerance=0] + */ +function GSSolver(options){ + Solver.call(this,options,Solver.GS); + options = options || {}; + + /** + * The max number of iterations to do when solving. More gives better results, but is more expensive. + * @property iterations + * @type {Number} + */ + this.iterations = options.iterations || 10; + + /** + * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. + * @property tolerance + * @type {Number} + * @default 1e-7 + */ + this.tolerance = options.tolerance || 1e-7; + + this.arrayStep = 30; + this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); + + /** + * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. + * @property useZeroRHS + * @type {Boolean} + * @todo Remove, not used + */ + this.useZeroRHS = false; + + /** + * Number of solver iterations that are used to approximate normal forces used for friction (F_friction = mu * F_normal). These friction forces will override any other friction forces that are set. If you set frictionIterations = 0, then this feature will be disabled. + * + * Use only frictionIterations > 0 if the approximated normal force (F_normal = mass * gravity) is not good enough. Examples of where it can happen is in space games where gravity is zero, or in tall stacks where the normal force is large at bottom but small at top. + * + * @property frictionIterations + * @type {Number} + * @default 0 + */ + this.frictionIterations = options.frictionIterations !== undefined ? 0 : options.frictionIterations; + + /** + * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. + * @property {Number} usedIterations + */ + this.usedIterations = 0; +} +GSSolver.prototype = new Solver(); +GSSolver.prototype.constructor = GSSolver; + +function setArrayZero(array){ + var l = array.length; + while(l--){ + array[l] = +0.0; + } +} + +/** + * Solve the system of equations + * @method solve + * @param {Number} h Time step + * @param {World} world World to solve + */ +GSSolver.prototype.solve = function(h, world){ + + this.sortEquations(); + + var iter = 0, + maxIter = this.iterations, + maxFrictionIter = this.frictionIterations, + equations = this.equations, + Neq = equations.length, + tolSquared = Math.pow(this.tolerance*Neq, 2), + bodies = world.bodies, + Nbodies = world.bodies.length, + add = vec2.add, + set = vec2.set, + useZeroRHS = this.useZeroRHS, + lambda = this.lambda; + + this.usedIterations = 0; + + if(Neq){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Update solve mass + b.updateSolveMassProperties(); + } + } + + // Things that does not change during iteration can be computed once + if(lambda.length < Neq){ + lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + } + setArrayZero(lambda); + var invCs = this.invCs, + Bs = this.Bs, + lambda = this.lambda; + + for(var i=0; i!==equations.length; i++){ + var c = equations[i]; + if(c.timeStep !== h || c.needsUpdate){ + c.timeStep = h; + c.update(); + } + Bs[i] = c.computeB(c.a,c.b,h); + invCs[i] = c.computeInvC(c.epsilon); + } + + var q, B, c, deltalambdaTot,i,j; + + if(Neq !== 0){ + + for(i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Reset vlambda + b.resetConstraintVelocity(); + } + + if(maxFrictionIter){ + // Iterate over contact equations to get normal forces + for(iter=0; iter!==maxFrictionIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + + // Set computed friction force + for(j=0; j!==Neq; j++){ + var eq = equations[j]; + if(eq instanceof FrictionEquation){ + var f = 0.0; + for(var k=0; k!==eq.contactEquations.length; k++){ + f += eq.contactEquations[k].multiplier; + } + f *= eq.frictionCoefficient / eq.contactEquations.length; + eq.maxForce = f; + eq.minForce = -f; + } + } + } + + // Iterate over all equations + for(iter=0; iter!==maxIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + // Add result to velocity + for(i=0; i!==Nbodies; i++){ + bodies[i].addConstraintVelocity(); + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + } +}; + +// Sets the .multiplier property of each equation +GSSolver.updateMultipliers = function(equations, lambda, invDt){ + // Set the .multiplier property of each equation + var l = equations.length; + while(l--){ + equations[l].multiplier = lambda[l] * invDt; + } +}; + +GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ + // Compute iteration + var B = Bs[j], + invC = invCs[j], + lambdaj = lambda[j], + GWlambda = eq.computeGWlambda(); + + var maxForce = eq.maxForce, + minForce = eq.minForce; + + if(useZeroRHS){ + B = 0; + } + + var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); + + // Clamp if we are not within the min/max interval + var lambdaj_plus_deltalambda = lambdaj + deltalambda; + if(lambdaj_plus_deltalambda < minForce*dt){ + deltalambda = minForce*dt - lambdaj; + } else if(lambdaj_plus_deltalambda > maxForce*dt){ + deltalambda = maxForce*dt - lambdaj; + } + lambda[j] += deltalambda; + eq.addToWlambda(deltalambda); + + return deltalambda; +}; + +},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Solver; + +/** + * Base class for constraint solvers. + * @class Solver + * @constructor + * @extends EventEmitter + */ +function Solver(options,type){ + options = options || {}; + + EventEmitter.call(this); + + this.type = type; + + /** + * Current equations in the solver. + * + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Function that is used to sort all equations before each solve. + * @property equationSortFunction + * @type {function|boolean} + */ + this.equationSortFunction = options.equationSortFunction || false; +} +Solver.prototype = new EventEmitter(); +Solver.prototype.constructor = Solver; + +/** + * Method to be implemented in each subclass + * @method solve + * @param {Number} dt + * @param {World} world + */ +Solver.prototype.solve = function(dt,world){ + throw new Error("Solver.solve should be implemented by subclasses!"); +}; + +var mockWorld = {bodies:[]}; + +/** + * Solves all constraints in an island. + * @method solveIsland + * @param {Number} dt + * @param {Island} island + */ +Solver.prototype.solveIsland = function(dt,island){ + + this.removeAllEquations(); + + if(island.equations.length){ + // Add equations to solver + this.addEquations(island.equations); + mockWorld.bodies.length = 0; + island.getBodies(mockWorld.bodies); + + // Solve + if(mockWorld.bodies.length){ + this.solve(dt,mockWorld); + } + } +}; + +/** + * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. + * @method sortEquations + */ +Solver.prototype.sortEquations = function(){ + if(this.equationSortFunction){ + this.equations.sort(this.equationSortFunction); + } +}; + +/** + * Add an equation to be solved. + * + * @method addEquation + * @param {Equation} eq + */ +Solver.prototype.addEquation = function(eq){ + if(eq.enabled){ + this.equations.push(eq); + } +}; + +/** + * Add equations. Same as .addEquation, but this time the argument is an array of Equations + * + * @method addEquations + * @param {Array} eqs + */ +Solver.prototype.addEquations = function(eqs){ + //Utils.appendArray(this.equations,eqs); + for(var i=0, N=eqs.length; i!==N; i++){ + var eq = eqs[i]; + if(eq.enabled){ + this.equations.push(eq); + } + } +}; + +/** + * Remove an equation. + * + * @method removeEquation + * @param {Equation} eq + */ +Solver.prototype.removeEquation = function(eq){ + var i = this.equations.indexOf(eq); + if(i !== -1){ + this.equations.splice(i,1); + } +}; + +/** + * Remove all currently added equations. + * + * @method removeAllEquations + */ +Solver.prototype.removeAllEquations = function(){ + this.equations.length=0; +}; + +Solver.GS = 1; +Solver.ISLAND = 2; + +},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){ +var ContactEquation = _dereq_('../equations/ContactEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = ContactEquationPool; + +/** + * @class + */ +function ContactEquationPool() { + Pool.apply(this, arguments); +} +ContactEquationPool.prototype = new Pool(); +ContactEquationPool.prototype.constructor = ContactEquationPool; + +/** + * @method create + * @return {ContactEquation} + */ +ContactEquationPool.prototype.create = function () { + return new ContactEquation(); +}; + +/** + * @method destroy + * @param {ContactEquation} equation + * @return {ContactEquationPool} + */ +ContactEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){ +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = FrictionEquationPool; + +/** + * @class + */ +function FrictionEquationPool() { + Pool.apply(this, arguments); +} +FrictionEquationPool.prototype = new Pool(); +FrictionEquationPool.prototype.constructor = FrictionEquationPool; + +/** + * @method create + * @return {FrictionEquation} + */ +FrictionEquationPool.prototype.create = function () { + return new FrictionEquation(); +}; + +/** + * @method destroy + * @param {FrictionEquation} equation + * @return {FrictionEquationPool} + */ +FrictionEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){ +var IslandNode = _dereq_('../world/IslandNode'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandNodePool; + +/** + * @class + */ +function IslandNodePool() { + Pool.apply(this, arguments); +} +IslandNodePool.prototype = new Pool(); +IslandNodePool.prototype.constructor = IslandNodePool; + +/** + * @method create + * @return {IslandNode} + */ +IslandNodePool.prototype.create = function () { + return new IslandNode(); +}; + +/** + * @method destroy + * @param {IslandNode} node + * @return {IslandNodePool} + */ +IslandNodePool.prototype.destroy = function (node) { + node.reset(); + return this; +}; + +},{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){ +var Island = _dereq_('../world/Island'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandPool; + +/** + * @class + */ +function IslandPool() { + Pool.apply(this, arguments); +} +IslandPool.prototype = new Pool(); +IslandPool.prototype.constructor = IslandPool; + +/** + * @method create + * @return {Island} + */ +IslandPool.prototype.create = function () { + return new Island(); +}; + +/** + * @method destroy + * @param {Island} island + * @return {IslandPool} + */ +IslandPool.prototype.destroy = function (island) { + island.reset(); + return this; +}; + +},{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){ +var TupleDictionary = _dereq_('./TupleDictionary'); +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool'); +var Utils = _dereq_('./Utils'); + +module.exports = OverlapKeeper; + +/** + * Keeps track of overlaps in the current state and the last step state. + * @class OverlapKeeper + * @constructor + */ +function OverlapKeeper() { + this.overlappingShapesLastState = new TupleDictionary(); + this.overlappingShapesCurrentState = new TupleDictionary(); + this.recordPool = new OverlapKeeperRecordPool({ size: 16 }); + this.tmpDict = new TupleDictionary(); + this.tmpArray1 = []; +} + +/** + * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current. + * @method tick + */ +OverlapKeeper.prototype.tick = function() { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Save old objects into pool + var l = last.keys.length; + while(l--){ + var key = last.keys[l]; + var lastObject = last.getByKey(key); + var currentObject = current.getByKey(key); + if(lastObject){ + // The record is only used in the "last" dict, and will be removed. We might as well pool it. + this.recordPool.release(lastObject); + } + } + + // Clear last object + last.reset(); + + // Transfer from new object to old + last.copy(current); + + // Clear current object + current.reset(); +}; + +/** + * @method setOverlapping + * @param {Body} bodyA + * @param {Body} shapeA + * @param {Body} bodyB + * @param {Body} shapeB + */ +OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Store current contact state + if(!current.get(shapeA.id, shapeB.id)){ + var data = this.recordPool.get(); + data.set(bodyA, shapeA, bodyB, shapeB); + current.set(shapeA.id, shapeB.id, data); + } +}; + +OverlapKeeper.prototype.getNewOverlaps = function(result){ + return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result); +}; + +OverlapKeeper.prototype.getEndOverlaps = function(result){ + return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result); +}; + +/** + * Checks if two bodies are currently overlapping. + * @method bodiesAreOverlapping + * @param {Body} bodyA + * @param {Body} bodyB + * @return {boolean} + */ +OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){ + var current = this.overlappingShapesCurrentState; + var l = current.keys.length; + while(l--){ + var key = current.keys[l]; + var data = current.data[key]; + if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){ + return true; + } + } + return false; +}; + +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){ + // Not overlapping in last state, but in current. + result.push(data); + } + } + + return result; +}; + +OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ + var idA = shapeA.id|0, + idB = shapeB.id|0; + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + // Not in last but in new + return !!!last.get(idA, idB) && !!current.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]; + + // Since we use body id's for the accumulator, these will be a subset of the original one + accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); + } + + l = accumulator.keys.length; + while(l--){ + var data = accumulator.getByKey(accumulator.keys[l]); + if(data){ + result.push(data.bodyA, data.bodyB); + } + } + + accumulator.reset(); + + return result; +}; + +},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){ +module.exports = OverlapKeeperRecord; + +/** + * Overlap data container for the OverlapKeeper + * @class OverlapKeeperRecord + * @constructor + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ + /** + * @property {Shape} shapeA + */ + this.shapeA = shapeA; + /** + * @property {Shape} shapeB + */ + this.shapeB = shapeB; + /** + * @property {Body} bodyA + */ + this.bodyA = bodyA; + /** + * @property {Body} bodyB + */ + this.bodyB = bodyB; +} + +/** + * Set the data for the record + * @method set + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ + OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); +}; + +},{}],54:[function(_dereq_,module,exports){ +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var Pool = _dereq_('./Pool'); + +module.exports = OverlapKeeperRecordPool; + +/** + * @class + */ +function OverlapKeeperRecordPool() { + Pool.apply(this, arguments); +} +OverlapKeeperRecordPool.prototype = new Pool(); +OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool; + +/** + * @method create + * @return {OverlapKeeperRecord} + */ +OverlapKeeperRecordPool.prototype.create = function () { + return new OverlapKeeperRecord(); +}; + +/** + * @method destroy + * @param {OverlapKeeperRecord} record + * @return {OverlapKeeperRecordPool} + */ +OverlapKeeperRecordPool.prototype.destroy = function (record) { + record.bodyA = record.bodyB = record.shapeA = record.shapeB = null; + return this; +}; + +},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){ +module.exports = Pool; + +/** + * @class Object pooling utility. + */ +function Pool(options) { + options = options || {}; + + /** + * @property {Array} objects + * @type {Array} + */ + this.objects = []; + + if(options.size !== undefined){ + this.resize(options.size); + } +} + +/** + * @method resize + * @param {number} size + * @return {Pool} Self, for chaining + */ +Pool.prototype.resize = function (size) { + var objects = this.objects; + + while (objects.length > size) { + objects.pop(); + } + + while (objects.length < size) { + objects.push(this.create()); + } + + return this; +}; + +/** + * Get an object from the pool or create a new instance. + * @method get + * @return {Object} + */ +Pool.prototype.get = function () { + var objects = this.objects; + return objects.length ? objects.pop() : this.create(); +}; + +/** + * Clean up and put the object back into the pool for later use. + * @method release + * @param {Object} object + * @return {Pool} Self for chaining + */ +Pool.prototype.release = function (object) { + this.destroy(object); + this.objects.push(object); + return this; +}; + +},{}],56:[function(_dereq_,module,exports){ +var Utils = _dereq_('./Utils'); + +module.exports = TupleDictionary; + +/** + * @class TupleDictionary + * @constructor + */ +function TupleDictionary() { + + /** + * The data storage + * @property data + * @type {Object} + */ + this.data = {}; + + /** + * Keys that are currently used. + * @property {Array} keys + */ + this.keys = []; +} + +/** + * Generate a key given two integers + * @method getKey + * @param {number} i + * @param {number} j + * @return {string} + */ +TupleDictionary.prototype.getKey = function(id1, id2) { + id1 = id1|0; + id2 = id2|0; + + if ( (id1|0) === (id2|0) ){ + return -1; + } + + // valid for values < 2^16 + return ((id1|0) > (id2|0) ? + (id1 << 16) | (id2 & 0xFFFF) : + (id2 << 16) | (id1 & 0xFFFF))|0 + ; +}; + +/** + * @method getByKey + * @param {Number} key + * @return {Object} + */ +TupleDictionary.prototype.getByKey = function(key) { + key = key|0; + return this.data[key]; +}; + +/** + * @method get + * @param {Number} i + * @param {Number} j + * @return {Number} + */ +TupleDictionary.prototype.get = function(i, j) { + return this.data[this.getKey(i, j)]; +}; + +/** + * Set a value. + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +TupleDictionary.prototype.set = function(i, j, value) { + if(!value){ + throw new Error("No data!"); + } + + var key = this.getKey(i, j); + + // Check if key already exists + if(!this.data[key]){ + this.keys.push(key); + } + + this.data[key] = value; + + return key; +}; + +/** + * Remove all data. + * @method reset + */ +TupleDictionary.prototype.reset = function() { + var data = this.data, + keys = this.keys; + + var l = keys.length; + while(l--) { + delete data[keys[l]]; + } + + keys.length = 0; +}; + +/** + * Copy another TupleDictionary. Note that all data in this dictionary will be removed. + * @method copy + * @param {TupleDictionary} dict The TupleDictionary to copy into this one. + */ +TupleDictionary.prototype.copy = function(dict) { + this.reset(); + Utils.appendArray(this.keys, dict.keys); + var l = dict.keys.length; + while(l--){ + var key = dict.keys[l]; + this.data[key] = dict.data[key]; + } +}; + +},{"./Utils":57}],57:[function(_dereq_,module,exports){ +/* global P2_ARRAY_TYPE */ + +module.exports = Utils; + +/** + * Misc utility functions + * @class Utils + * @constructor + */ +function Utils(){} + +/** + * Append the values in array b to the array a. See this for an explanation. + * @method appendArray + * @static + * @param {Array} a + * @param {Array} b + */ +Utils.appendArray = function(a,b){ + if (b.length < 150000) { + a.push.apply(a, b); + } else { + for (var i = 0, len = b.length; i !== len; ++i) { + a.push(b[i]); + } + } +}; + +/** + * Garbage free Array.splice(). Does not allocate a new array. + * @method splice + * @static + * @param {Array} array + * @param {Number} index + * @param {Number} howmany + */ +Utils.splice = function(array,index,howmany){ + howmany = howmany || 1; + for (var i=index, len=array.length-howmany; i < len; i++){ + array[i] = array[i + howmany]; + } + array.length = len; +}; + +/** + * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. + * @static + * @property {function} ARRAY_TYPE + * @example + * + * + */ +if(typeof P2_ARRAY_TYPE !== 'undefined') { + Utils.ARRAY_TYPE = P2_ARRAY_TYPE; +} else if (typeof Float32Array !== 'undefined'){ + Utils.ARRAY_TYPE = Float32Array; +} else { + Utils.ARRAY_TYPE = Array; +} + +/** + * Extend an object with the properties of another + * @static + * @method extend + * @param {object} a + * @param {object} b + */ +Utils.extend = function(a,b){ + for(var key in b){ + a[key] = b[key]; + } +}; + +/** + * Extend an options object with default values. + * @static + * @method defaults + * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. + * @param {object} defaults An object containing default values. + * @return {object} The modified options object. + */ +Utils.defaults = function(options, defaults){ + options = options || {}; + for(var key in defaults){ + if(!(key in options)){ + options[key] = defaults[key]; + } + } + return options; +}; + +},{}],58:[function(_dereq_,module,exports){ +var Body = _dereq_('../objects/Body'); + +module.exports = Island; + +/** + * An island of bodies connected with equations. + * @class Island + * @constructor + */ +function Island(){ + + /** + * Current equations in this island. + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Current bodies in this island. + * @property bodies + * @type {Array} + */ + this.bodies = []; +} + +/** + * Clean this island from bodies and equations. + * @method reset + */ +Island.prototype.reset = function(){ + this.equations.length = this.bodies.length = 0; +}; + +var bodyIds = []; + +/** + * Get all unique bodies in this island. + * @method getBodies + * @return {Array} An array of Body + */ +Island.prototype.getBodies = function(result){ + var bodies = result || [], + eqs = this.equations; + bodyIds.length = 0; + for(var i=0; i!==eqs.length; i++){ + var eq = eqs[i]; + if(bodyIds.indexOf(eq.bodyA.id)===-1){ + bodies.push(eq.bodyA); + bodyIds.push(eq.bodyA.id); + } + if(bodyIds.indexOf(eq.bodyB.id)===-1){ + bodies.push(eq.bodyB); + bodyIds.push(eq.bodyB.id); + } + } + return bodies; +}; + +/** + * Check if the entire island wants to sleep. + * @method wantsToSleep + * @return {Boolean} + */ +Island.prototype.wantsToSleep = function(){ + for(var i=0; i= dt && substeps < maxSubSteps) { + // Do fixed steps to catch up + this.internalStep(dt); + this.time += dt; + this.accumulator -= dt; + substeps++; + } + + var t = (this.accumulator % dt) / dt; + for(var j=0; j!==this.bodies.length; j++){ + var b = this.bodies[j]; + vec2.lerp(b.interpolatedPosition, b.previousPosition, b.position, t); + b.interpolatedAngle = b.previousAngle + t * (b.angle - b.previousAngle); + } + } +}; + +var endOverlaps = []; + +/** + * Make a fixed step. + * @method internalStep + * @param {number} dt + * @private + */ +World.prototype.internalStep = function(dt){ + this.stepping = true; + + var that = this, + Nsprings = this.springs.length, + springs = this.springs, + bodies = this.bodies, + g = this.gravity, + solver = this.solver, + Nbodies = this.bodies.length, + broadphase = this.broadphase, + np = this.narrowphase, + constraints = this.constraints, + t0, t1, + fhMinv = step_fhMinv, + velodt = step_velodt, + mg = step_mg, + scale = vec2.scale, + add = vec2.add, + rotate = vec2.rotate, + islandManager = this.islandManager; + + this.overlapKeeper.tick(); + + this.lastTimeStep = dt; + + // Update approximate friction gravity. + if(this.useWorldGravityAsFrictionGravity){ + var gravityLen = vec2.length(this.gravity); + if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){ + // Nonzero gravity. Use it. + this.frictionGravity = gravityLen; + } + } + + // Add gravity to bodies + if(this.applyGravity){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i], + fi = b.force; + if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ + continue; + } + vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g + add(fi,fi,mg); + } + } + + // Add spring forces + if(this.applySpringForces){ + for(var i=0; i!==Nsprings; i++){ + var s = springs[i]; + s.applyForce(); + } + } + + if(this.applyDamping){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + if(b.type === Body.DYNAMIC){ + b.applyDamping(dt); + } + } + } + + // Broadphase + var result = broadphase.getCollisionPairs(this); + + // Remove ignored collision pairs + var ignoredPairs = this.disabledBodyCollisionPairs; + for(var i=ignoredPairs.length-2; 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); + } + } + } + + // Remove constrained pairs with collideConnected == false + 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); + } + } + } + } + + // postBroadphase event + this.postBroadphaseEvent.pairs = result; + this.emit(this.postBroadphaseEvent); + this.postBroadphaseEvent.pairs = null; + + // Narrowphase + np.reset(this); + for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ + var bi = result[i], + bj = result[i+1]; + + // Loop over all shapes of body i + for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ + var si = bi.shapes[k], + xi = si.position, + ai = si.angle; + + // All shapes of body j + for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ + var sj = bj.shapes[l], + xj = sj.position, + aj = sj.angle; + + 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); + } + } + } + + // Wake up bodies + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + if(body._wakeUpAfterNarrowphase){ + body.wakeUp(); + body._wakeUpAfterNarrowphase = false; + } + } + + // Emit end overlap events + 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.bodyB; + this.emit(e); + } + endOverlaps.length = 0; + } + + var preSolveEvent = this.preSolveEvent; + preSolveEvent.contactEquations = np.contactEquations; + preSolveEvent.frictionEquations = np.frictionEquations; + this.emit(preSolveEvent); + preSolveEvent.contactEquations = preSolveEvent.frictionEquations = null; + + // update constraint equations + var Nconstraints = constraints.length; + for(i=0; i!==Nconstraints; i++){ + constraints[i].update(); + } + + if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){ + if(this.islandSplit){ + // Split into islands + 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 { + + // Add contact equations to solver + solver.addEquations(np.contactEquations); + solver.addEquations(np.frictionEquations); + + // Add user-defined constraint equations + for(i=0; i!==Nconstraints; i++){ + solver.addEquations(constraints[i].equations); + } + + if(this.solveConstraints){ + solver.solve(dt,this); + } + + solver.removeAllEquations(); + } + } + + // Step forward + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + + // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){ + body.integrate(dt); + // } + } + + // Reset force + for(var i=0; i!==Nbodies; i++){ + bodies[i].setZeroForce(); + } + + // Emit impact event + 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); + } + } + } + + // Sleeping update + if(this.sleepMode === World.BODY_SLEEPING){ + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, false, dt); + } + } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){ + + // Tell all bodies to sleep tick but dont sleep yet + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, true, dt); + } + + // Sleep islands + for(var i=0; i 0; + np.frictionCoefficient = cm.friction; + var reducedMass; + if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){ + reducedMass = bj.mass; + } else if(bj.type === Body.STATIC || bj.type === 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; + np.contactSkinSize = cm.contactSkinSize; + np.enabledEquations = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse; + + 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 < sj.type) { + numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); + } else { + numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); + } + var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; + + if(numContacts){ + + if( bi.allowSleep && + bi.type === Body.DYNAMIC && + bi.sleepState === Body.SLEEPING && + bj.sleepState === Body.AWAKE && + bj.type !== Body.STATIC + ){ + var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); + var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); + if(speedSquaredB >= speedLimitSquaredB*2){ + bi._wakeUpAfterNarrowphase = true; + } + } + + if( bj.allowSleep && + bj.type === Body.DYNAMIC && + bj.sleepState === Body.SLEEPING && + bi.sleepState === Body.AWAKE && + bi.type !== 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)){ + + // Report new shape overlap + var e = this.beginContactEvent; + e.shapeA = si; + e.shapeB = sj; + e.bodyA = bi; + e.bodyB = bj; + + // Reset contact equations + e.contactEquations.length = 0; + + if(typeof(numContacts)==="number"){ + for(var i=np.contactEquations.length-numContacts; i 1){ // Why divide by 1? + for(var i=np.frictionEquations.length-numFrictionEquations; i=0; i--){ + this.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.bodies; + for(var i=bodies.length-1; i>=0; i--){ + this.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.springs; + for(var i=springs.length-1; i>=0; i--){ + this.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.contactMaterials; + for(var i=cms.length-1; i>=0; i--){ + this.removeContactMaterial(cms[i]); + } + + World.apply(this); +}; + +var hitTest_tmp1 = vec2.create(), + hitTest_zero = vec2.fromValues(0,0), + hitTest_tmp2 = vec2.fromValues(0,0); + +/** + * Test if a world point overlaps bodies + * @method hitTest + * @param {Array} worldPoint Point to use for intersection tests + * @param {Array} bodies A list of objects to check for intersection + * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @return {Array} Array of bodies that overlap the point + * @todo Should use an api similar to the raycast function + * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient + * @todo Should use the broadphase + */ +World.prototype.hitTest = function(worldPoint,bodies,precision){ + precision = precision || 0; + + // Create a dummy particle body with a particle shape to test against the bodies + 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 = []; + + // Check bodies + 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]; + + // Get shape world position + angle + vec2.rotate(x, s.position, b.angle); + vec2.add(x, x, b.position); + var a = s.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)) < precision*precision) + ){ + result.push(b); + } + } + } + + return result; +}; + +/** + * Set the stiffness for all equations and contact materials. + * @method setGlobalStiffness + * @param {Number} stiffness + */ +World.prototype.setGlobalStiffness = function(stiffness){ + + // Set for all constraints + var constraints = this.constraints; + for(var i=0; i !== constraints.length; i++){ + var c = constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.stiffness = stiffness; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + var contactMaterials = this.contactMaterials; + for(var i=0; i !== contactMaterials.length; i++){ + var c = contactMaterials[i]; + c.stiffness = c.frictionStiffness = stiffness; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.stiffness = c.frictionStiffness = stiffness; +}; + +/** + * Set the relaxation for all equations and contact materials. + * @method setGlobalRelaxation + * @param {Number} relaxation + */ +World.prototype.setGlobalRelaxation = function(relaxation){ + + // Set for all constraints + for(var i=0; i !== this.constraints.length; i++){ + var c = this.constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.relaxation = relaxation; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + for(var i=0; i !== this.contactMaterials.length; i++){ + var c = this.contactMaterials[i]; + c.relaxation = c.frictionRelaxation = relaxation; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.relaxation = c.frictionRelaxation = relaxation; +}; + +var tmpAABB = new AABB(); +var tmpArray = []; + +/** + * Ray cast against all bodies in the world. + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @return {boolean} True if any body was hit. + * + * @example + * var ray = new Ray({ + * mode: Ray.CLOSEST, // or ANY + * from: [0, 0], + * to: [10, 0], + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * @example + * var ray = new Ray({ + * mode: Ray.ALL, + * from: [0, 0], + * to: [10, 0], + * callback: function(result){ + * + * // Print some info about the hit + * console.log('Hit body and shape: ', result.body, result.shape); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * // If you are happy with the hits you got this far, you can stop the traversal here: + * result.stop(); + * } + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + */ +World.prototype.raycast = function(result, ray){ + + // Get all bodies within the ray AABB + ray.getAABB(tmpAABB); + this.broadphase.aabbQuery(this, tmpAABB, tmpArray); + ray.intersectBodies(result, tmpArray); + tmpArray.length = 0; + + return result.hasHit(); +}; + +},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36]) +(36) +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +(function(){ + + var root = this; + +/** + * Namespace-class for [pixi.js](http://www.pixijs.com/). + * + * Contains assorted static properties and enumerations. + * + * @namespace PIXI + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ +var PIXI = PIXI || {}; + +/** +* @author Mat Groves http://matgroves.com @Doormat23 +* @author Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The base class for all objects that are rendered. Contains properties for position, scaling, +* rotation, masks and cache handling. +* +* This is an abstract class and should not be used on its own, rather it should be extended. +* +* It is used internally by the likes of PIXI.Sprite. +* +* @class PIXI.DisplayObject +* @constructor +*/ +PIXI.DisplayObject = function () { + + /** + * The coordinates, in pixels, of this DisplayObject, relative to its parent container. + * + * The value of this property does not reflect any positioning happening further up the display list. + * To obtain that value please see the `worldPosition` property. + * + * @property {PIXI.Point} position + * @default + */ + this.position = new PIXI.Point(0, 0); + + /** + * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject + * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on. + * + * The value of this property does not reflect any scaling happening further up the display list. + * To obtain that value please see the `worldScale` property. + * + * @property {PIXI.Point} scale + * @default + */ + this.scale = new PIXI.Point(1, 1); + + /** + * The pivot point of this DisplayObject that it rotates around. The values are expressed + * in pixel values. + * @property {PIXI.Point} pivot + * @default + */ + this.pivot = new PIXI.Point(0, 0); + + /** + * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on + * a right-handed orientation. + * + * The value of this property does not reflect any rotation happening further up the display list. + * To obtain that value please see the `worldRotation` property. + * + * @property {number} rotation + * @default + */ + this.rotation = 0; + + /** + * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * Please note that an object with an alpha value of 0 is skipped during the render pass. + * + * The value of this property does not reflect any alpha values set further up the display list. + * To obtain that value please see the `worldAlpha` property. + * + * @property {number} alpha + * @default + */ + this.alpha = 1; + + /** + * The visibility of this DisplayObject. A value of `false` makes the object invisible. + * A value of `true` makes it visible. Please note that an object with a visible value of + * `false` is skipped during the render pass. Equally a DisplayObject with visible false will + * not render any of its children. + * + * The value of this property does not reflect any visible values set further up the display list. + * To obtain that value please see the `worldVisible` property. + * + * @property {boolean} visible + * @default + */ + this.visible = true; + + /** + * This is the defined area that will pick up mouse / touch events. It is null by default. + * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children) + * + * @property hitArea + * @type Rectangle|Circle|Ellipse|Polygon + */ + this.hitArea = null; + + /** + * Should this DisplayObject be rendered by the renderer? An object with a renderable value of + * `false` is skipped during the render pass. + * + * @property {boolean} renderable + * @default + */ + this.renderable = false; + + /** + * The parent DisplayObjectContainer that this DisplayObject is a child of. + * All DisplayObjects must belong to a parent in order to be rendered. + * The root parent is the Stage object. This property is set automatically when the + * DisplayObject is added to, or removed from, a DisplayObjectContainer. + * + * @property {PIXI.DisplayObjectContainer} parent + * @default + * @readOnly + */ + this.parent = null; + + /** + * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects + * in the display list. + * + * To obtain, and set, the local alpha value, see the `alpha` property. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldAlpha + * @readOnly + */ + this.worldAlpha = 1; + + /** + * The current transform of this DisplayObject. + * + * This property contains the calculated total, based on the transforms of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {Phaser.Matrix} worldTransform + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * The coordinates, in pixels, of this DisplayObject within the world. + * + * This property contains the calculated total, based on the positions of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldPosition + * @readOnly + */ + this.worldPosition = new PIXI.Point(0, 0); + + /** + * The global scale of this DisplayObject. + * + * This property contains the calculated total, based on the scales of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldScale + * @readOnly + */ + this.worldScale = new PIXI.Point(1, 1); + + /** + * The rotation, in radians, of this DisplayObject. + * + * This property contains the calculated total, based on the rotations of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldRotation + * @readOnly + */ + this.worldRotation = 0; + + /** + * The rectangular area used by filters when rendering a shader for this DisplayObject. + * + * @property {PIXI.Rectangle} filterArea + * @type Rectangle + * @default + */ + this.filterArea = null; + + /** + * @property {number} _sr - Cached rotation value. + * @private + */ + this._sr = 0; + + /** + * @property {number} _cr - Cached rotation value. + * @private + */ + this._cr = 1; + + /** + * @property {PIXI.Rectangle} _bounds - The cached bounds of this object. + * @private + */ + this._bounds = new PIXI.Rectangle(0, 0, 0, 0); + + /** + * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object. + * @private + */ + this._currentBounds = null; + + /** + * @property {PIXI.Rectangle} _mask - The cached mask of this object. + * @private + */ + this._mask = null; + + /** + * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag. + * @private + */ + this._cacheAsBitmap = false; + + /** + * @property {boolean} _cacheIsDirty - Internal dirty cache flag. + * @private + */ + this._cacheIsDirty = false; + +}; + +PIXI.DisplayObject.prototype = { + + constructor: PIXI.DisplayObject, + + /** + * Destroy this DisplayObject. + * + * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask. + * + * Also iteratively calls `destroy` on any children. + * + * @method PIXI.DisplayObject#destroy + */ + destroy: function () { + + if (this.children) + { + var i = this.children.length; + + while (i--) + { + this.children[i].destroy(); + } + + this.children = []; + } + + this.hitArea = null; + this.parent = null; + this.worldTransform = null; + this.filterArea = null; + this.renderable = false; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + }, + + /** + * Updates the transform matrix this DisplayObject uses for rendering. + * + * If the object has no parent, and no parent parameter is provided, it will default to + * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place. + * + * The `parent` parameter has priority over the actual parent. Use it as a parent override. + * Setting it does **not** change the actual parent of this DisplayObject. + * + * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale` + * and `worldRotation` properties. + * + * If a `transformCallback` has been specified, it is called at the end of this method, and is passed + * the new, updated, worldTransform property, along with the parent transform used. + * + * @method PIXI.DisplayObject#updateTransform + * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from. + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateTransform: function (parent) { + + if (!parent && !this.parent && !this.game) + { + return this; + } + + var p = this.parent; + + if (parent) + { + p = parent; + } + else if (!this.parent) + { + p = this.game.world; + } + + // create some matrix refs for easy access + var pt = p.worldTransform; + var wt = this.worldTransform; + + // temporary matrix variables + var a, b, c, d, tx, ty; + + // so if rotation is between 0 then we can simplify the multiplication process.. + if (this.rotation % Phaser.Math.PI2) + { + // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes + if (this.rotation !== this.rotationCache) + { + this.rotationCache = this.rotation; + this._sr = Math.sin(this.rotation); + this._cr = Math.cos(this.rotation); + } + + // get the matrix values of the displayobject based on its transform properties.. + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + tx = this.position.x; + ty = this.position.y; + + // check for pivot.. not often used so geared towards that fact! + if (this.pivot.x || this.pivot.y) + { + tx -= this.pivot.x * a + this.pivot.y * c; + ty -= this.pivot.x * b + this.pivot.y * d; + } + + // concat the parent matrix with the objects transform. + wt.a = a * pt.a + b * pt.c; + wt.b = a * pt.b + b * pt.d; + wt.c = c * pt.a + d * pt.c; + wt.d = c * pt.b + d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + else + { + // lets do the fast version as we know there is no rotation.. + a = this.scale.x; + b = 0; + c = 0; + d = this.scale.y; + tx = this.position.x - this.pivot.x * a; + ty = this.position.y - this.pivot.y * d; + + wt.a = a * pt.a; + wt.b = a * pt.b; + wt.c = d * pt.c; + wt.d = d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + + a = wt.a; + b = wt.b; + c = wt.c; + d = wt.d; + + var determ = (a * d) - (b * c); + + if (a || b) + { + var r = Math.sqrt((a * a) + (b * b)); + + this.worldRotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); + this.worldScale.x = r; + this.worldScale.y = determ / r; + } + else if (c || d) + { + var s = Math.sqrt((c * c) + (d * d)); + + this.worldRotation = Phaser.Math.HALF_PI - ((d > 0) ? Math.acos(-c / s) : -Math.acos(c / s)); + this.worldScale.x = determ / s; + this.worldScale.y = s; + } + else + { + this.worldScale.x = 0; + this.worldScale.y = 0; + } + + // Set the World values + this.worldAlpha = this.alpha * p.worldAlpha; + this.worldPosition.x = wt.tx; + this.worldPosition.y = wt.ty; + + // reset the bounds each time this is called! + this._currentBounds = null; + + // Custom callback? + if (this.transformCallback) + { + this.transformCallback.call(this.transformCallbackContext, wt, pt); + } + + return this; + + }, + + /** + * To be overridden by classes that require it. + * + * @method PIXI.DisplayObject#preUpdate + */ + preUpdate: function () { + + }, + + /** + * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites. + * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times. + * + * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures, + * and references to them, so they don't linger in memory. + * + * @method PIXI.DisplayObject#generateTexture + * @param {number} [resolution=1] - The resolution of the texture being generated. + * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values. + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture. + * @return {Phaser.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked. + */ + generateTexture: function (resolution, scaleMode, renderer) { + + var bounds = this.getLocalBounds(); + + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + + renderTexture.render(this, PIXI.DisplayObject._tempMatrix); + + return renderTexture; + + }, + + /** + * If this DisplayObject has a cached Sprite, this method generates and updates it. + * + * @method PIXI.DisplayObject#updateCache + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateCache: function () { + + this._generateCachedSprite(); + + return this; + + }, + + /** + * Calculates the global position of this DisplayObject, based on the position given. + * + * @method PIXI.DisplayObject#toGlobal + * @param {PIXI.Point} position - The global position to calculate from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toGlobal: function (position) { + + this.updateTransform(); + + return this.worldTransform.apply(position); + + }, + + /** + * Calculates the local position of this DisplayObject, relative to another point. + * + * @method PIXI.DisplayObject#toLocal + * @param {PIXI.Point} position - The world origin to calculate from. + * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toLocal: function (position, from) { + + if (from) + { + position = from.toGlobal(position); + } + + this.updateTransform(); + + return this.worldTransform.applyInverse(position); + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_renderCachedSprite + * @private + * @param {Object} renderSession - The render session + */ + _renderCachedSprite: function (renderSession) { + + this._cachedSprite.worldAlpha = this.worldAlpha; + + if (renderSession.gl) + { + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + } + else + { + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + } + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_generateCachedSprite + * @private + */ + _generateCachedSprite: function () { + + this._cacheAsBitmap = false; + + var bounds = this.getLocalBounds(); + + // Round it off and force non-zero dimensions + bounds.width = Math.max(1, Math.ceil(bounds.width)); + bounds.height = Math.max(1, Math.ceil(bounds.height)); + + this.updateTransform(); + + if (!this._cachedSprite) + { + var textureUnit = 0; + if (this.texture && this.texture.baseTexture && PIXI._enableMultiTextureToggle) + { + textureUnit = this.texture.baseTexture.textureIndex; + } + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width, bounds.height, undefined, undefined, undefined, undefined, textureUnit); + this._cachedSprite = new PIXI.Sprite(renderTexture); + this._cachedSprite.worldTransform = this.worldTransform; + } + else + { + this._cachedSprite.texture.resize(bounds.width, bounds.height); + } + + // Remove filters + var tempFilters = this._filters; + + this._filters = null; + this._cachedSprite.filters = tempFilters; + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true); + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + this._filters = tempFilters; + + this._cacheAsBitmap = true; + + }, + + /** + * Destroys a cached Sprite. + * + * @method PIXI.DisplayObject#_destroyCachedSprite + * @private + */ + _destroyCachedSprite: function () { + + if (!this._cachedSprite) + { + return; + } + + this._cachedSprite.texture.destroy(true); + + this._cachedSprite = null; + + } + +}; + +// Alias for updateTransform. As used in DisplayObject container, etc. +PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform; + +Object.defineProperties(PIXI.DisplayObject.prototype, { + + /** + * The horizontal position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#x + * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent. + */ + 'x': { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + } + + }, + + /** + * The vertical position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#y + * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent. + */ + 'y': { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + + }, + + /** + * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + * @name PIXI.DisplayObject#worldVisible + * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + */ + 'worldVisible': { + + get: function () { + + if (!this.visible) + { + return false; + } + else + { + var item = this.parent; + + if (!item) + { + return this.visible; + } + else + { + do + { + if (!item.visible) + { + return false; + } + + item = item.parent; + } + while (item); + + } + + return true; + } + + } + + }, + + /** + * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object. + * When applied it limits the visible area of this DisplayObject to the shape of the mask. + * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer. + * To remove a mask, set this property to `null`. + * + * @name PIXI.DisplayObject#mask + * @property {Phaser.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask. + */ + 'mask': { + + get: function () { + + return this._mask; + + }, + + set: function (value) { + + if (this._mask) + { + this._mask.isMask = false; + } + + this._mask = value; + + if (value) + { + this._mask.isMask = true; + } + + } + + }, + + /** + * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas + * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter + * using `DisplayObject.filterArea`. + * + * To remove filters, set this property to `null`. + * + * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a + * filter will reset this DisplayObjects blend mode to NORMAL. + * + * @name PIXI.DisplayObject#filters + * @property {Array} filters - An Array of Phaser.Filter objects, or objects that extend them. + */ + 'filters': { + + get: function () { + + return this._filters; + + }, + + set: function (value) { + + if (Array.isArray(value)) + { + // Put all the passes in one place. + var passes = []; + + for (var i = 0; i < value.length; i++) + { + var filterPasses = value[i].passes; + + for (var j = 0; j < filterPasses.length; j++) + { + passes.push(filterPasses[j]); + } + } + + // Needed any more? + this._filterBlock = { target: this, filterPasses: passes }; + } + + this._filters = value; + + if (this.blendMode && this.blendMode === PIXI.blendModes.MULTIPLY) + { + this.blendMode = PIXI.blendModes.NORMAL; + } + + } + + }, + + /** + * Sets if this DisplayObject should be cached as a bitmap. + * + * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it + * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a + * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not + * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`. + * + * To remove a cached bitmap, set this property to `null`. + * + * @name PIXI.DisplayObject#cacheAsBitmap + * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap. + */ + 'cacheAsBitmap': { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + if (this._cacheAsBitmap === value) + { + return; + } + + if (value) + { + this._generateCachedSprite(); + } + else + { + this._destroyCachedSprite(); + } + + this._cacheAsBitmap = value; + + } + + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A DisplayObjectContainer represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + * @class PIXI.DisplayObjectContainer + * @extends PIXI.DisplayObject + * @constructor + */ +PIXI.DisplayObjectContainer = function () { + + PIXI.DisplayObject.call(this); + + /** + * [read-only] The array of children of this container. + * + * @property children + * @type Array(DisplayObject) + * @readOnly + */ + this.children = []; + + /** + * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events. + * + * If this property is `true` then the children will _not_ be considered as valid for Input events. + * + * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. + * @property {boolean} ignoreChildInput + * @default + */ + this.ignoreChildInput = false; + +}; + +PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); +PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; + +/** + * Adds a child to the container. + * + * @method PIXI.DisplayObjectContainer#addChild + * @param child {DisplayObject} The DisplayObject to add to the container + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChild = function (child) { + + return this.addChildAt(child, this.children.length); + +}; + +/** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @method PIXI.DisplayObjectContainer#addChildAt + * @param child {DisplayObject} The child to add + * @param index {Number} The index to place the child in + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) { + + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + return child; + } + else + { + throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); + } + +}; + +/** + * Swaps the position of 2 Display Objects within this container. + * + * @method PIXI.DisplayObjectContainer#swapChildren + * @param child {DisplayObject} + * @param child2 {DisplayObject} + */ +PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) { + + if (child === child2) + { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(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; + +}; + +/** + * Returns the index position of a child DisplayObject instance + * + * @method PIXI.DisplayObjectContainer#getChildIndex + * @param child {DisplayObject} The DisplayObject instance to identify + * @return {Number} The index position of the child display object to identify + */ +PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + +}; + +/** + * Changes the position of an existing child in the display object container + * + * @method PIXI.DisplayObjectContainer#setChildIndex + * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number + * @param index {Number} The resulting index number for the child display object + */ +PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + this.children.splice(currentIndex, 1); //remove from old position + this.children.splice(index, 0, child); //add at new position + +}; + +/** + * Returns the child at the specified index + * + * @method PIXI.DisplayObjectContainer#getChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child at the given index, if any. + */ +PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller'); + } + + return this.children[index]; + +}; + +/** + * Removes a child from the container. + * + * @method PIXI.DisplayObjectContainer#removeChild + * @param child {DisplayObject} The DisplayObject to remove + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChild = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + return; + } + + return this.removeChildAt(index); + +}; + +/** + * Removes a child from the specified index position. + * + * @method PIXI.DisplayObjectContainer#removeChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) { + + var child = this.getChildAt(index); + + if (child) + { + child.parent = undefined; + + this.children.splice(index, 1); + } + + return child; + +}; + +/** +* Removes all children from this container that are within the begin and end indexes. +* +* @method PIXI.DisplayObjectContainer#removeChildren +* @param beginIndex {Number} The beginning position. Default value is 0. +* @param endIndex {Number} The ending position. Default value is size of the container. +*/ +PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { + + if (beginIndex === undefined) { beginIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var range = endIndex - beginIndex; + + if (range > 0 && range <= endIndex) + { + var removed = this.children.splice(beginIndex, range); + + for (var i = 0; i < removed.length; i++) + { + var child = removed[i]; + child.parent = undefined; + } + + return removed; + } + else if (range === 0 && this.children.length === 0) + { + return []; + } + else + { + throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' ); + } + +}; + +/* + * Updates the transform on all children of this container for rendering + * + * @method PIXI.DisplayObjectContainer#updateTransform + * @private + */ +PIXI.DisplayObjectContainer.prototype.updateTransform = function () { + + if (!this.visible) + { + return; + } + + this.displayObjectUpdateTransform(); + + if (this._cacheAsBitmap) + { + return; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +// performance increase to avoid using call.. (10x faster) +PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform; + +/** + * Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getBounds + * @param {PIXI.DisplayObject|Phaser.Matrix} [targetCoordinateSpace] Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpace) { + + var isTargetCoordinateSpaceDisplayObject = (targetCoordinateSpace && targetCoordinateSpace instanceof PIXI.DisplayObject); + var isTargetCoordinateSpaceThisOrParent = true; + + if (!isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace = this; + } + else if (targetCoordinateSpace instanceof PIXI.DisplayObjectContainer) + { + isTargetCoordinateSpaceThisOrParent = targetCoordinateSpace.contains(this); + } + else + { + isTargetCoordinateSpaceThisOrParent = false; + } + + var i; + + if (isTargetCoordinateSpaceDisplayObject) + { + var matrixCache = targetCoordinateSpace.worldTransform; + + targetCoordinateSpace.worldTransform = Phaser.identityMatrix; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + var minX = Infinity; + var minY = Infinity; + + var maxX = -Infinity; + var maxY = -Infinity; + + var childBounds; + var childMaxX; + var childMaxY; + + var childVisible = false; + + for (i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + childVisible = true; + + childBounds = this.children[i].getBounds(); + + minX = (minX < childBounds.x) ? minX : childBounds.x; + minY = (minY < childBounds.y) ? minY : childBounds.y; + + childMaxX = childBounds.width + childBounds.x; + childMaxY = childBounds.height + childBounds.y; + + maxX = (maxX > childMaxX) ? maxX : childMaxX; + maxY = (maxY > childMaxY) ? maxY : childMaxY; + } + + var bounds = this._bounds; + + if (!childVisible) + { + bounds = new PIXI.Rectangle(); + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + maxX = x1; + maxY = y1; + + minX = x1; + minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + } + + bounds.x = minX; + bounds.y = minY; + bounds.width = maxX - minX; + bounds.height = maxY - minY; + + if (isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace.worldTransform = matrixCache; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + if (!isTargetCoordinateSpaceThisOrParent) + { + var targetCoordinateSpaceBounds = targetCoordinateSpace.getBounds(); + + bounds.x -= targetCoordinateSpaceBounds.x; + bounds.y -= targetCoordinateSpaceBounds.y; + } + + return bounds; + +}; + +/** + * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getLocalBounds = function () { + + return this.getBounds(this); + +}; + +/** +* Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. +* +* @method PIXI.DisplayObjectContainer#contains +* @param {DisplayObject} child +* @returns {boolean} +*/ +PIXI.DisplayObjectContainer.prototype.contains = function (child) { + + if (!child) + { + return false; + } + else if (child === this) + { + return true; + } + else + { + return this.contains(child.parent); + } +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.DisplayObjectContainer#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + var i; + + if (this._mask || this._filters) + { + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + renderSession.spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + renderSession.spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + renderSession.spriteBatch.start(); + } + + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + renderSession.spriteBatch.start(); + } + else + { + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.DisplayObjectContainer#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) { + + if (this.visible === false || this.alpha === 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', { + + get: function() { + return this.getLocalBounds().width * this.scale.x; + }, + + set: function(value) { + + var width = this.getLocalBounds().width; + + if (width !== 0) + { + this.scale.x = value / width; + } + else + { + this.scale.x = 1; + } + + this._width = value; + } +}); + +/** + * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', { + + get: function() { + return this.getLocalBounds().height * this.scale.y; + }, + + set: function(value) { + + var height = this.getLocalBounds().height; + + if (height !== 0) + { + this.scale.y = value / height; + } + else + { + this.scale.y = 1; + } + + this._height = value; + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * @class PIXI.Sprite + * @extends PIXI.DisplayObjectContainer + * @constructor + * @param texture {Texture} The texture for this sprite + */ +PIXI.Sprite = function (texture) { + + PIXI.DisplayObjectContainer.call(this); + + /** + * The anchor sets the origin point of the texture. + * The default (0, 0) is the top left. + * (0.5, 0.5) is the center. + * (1, 1) is the bottom right. + * + * You can modify the default values in PIXI.Sprite.defaultAnchor. + * + * @property anchor + * @type Point + */ + this.anchor = new PIXI.Point(PIXI.Sprite.defaultAnchor.x, PIXI.Sprite.defaultAnchor.y); + + /** + * The texture that the sprite is using + * + * @property texture + * @type Texture + */ + this.texture = texture || PIXI.Texture.emptyTexture; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @property _width + * @type Number + * @private + */ + this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @property _height + * @type Number + * @private + */ + this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF (Phaser.Color.WHITE) will remove any tint effect. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @property cachedTint + * @private + * @type Number + * @default -1 + */ + this.cachedTint = -1; + + /** + * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) + * + * @property tintedTexture + * @type Canvas + * @default null + */ + this.tintedTexture = null; + + /** + * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. + * + * Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * The shader that will be used to render this Sprite. + * Set to null to remove a current shader. + * + * @property shader + * @type Phaser.Filter + * @default null + */ + this.shader = null; + + /** + * Controls if this Sprite is processed by the core Phaser game loops and Group loops (except {@link Phaser.Group#update}). + * + * @property exists + * @type Boolean + * @default true + */ + this.exists = true; + + if (this.texture.baseTexture.hasLoaded) + { + this.onTextureUpdate(); + } + + this.renderable = true; + +}; + +/** + * @property PIXI.Sprite.defaultAnchor - A Point-like object. + * @type {{x: number, y: number}} + * @default + */ +PIXI.Sprite.defaultAnchor = {x: 0, y: 0}; + +// constructor +PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +PIXI.Sprite.prototype.constructor = PIXI.Sprite; + +/** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'width', { + + get: function() { + return this.scale.x * this.texture.frame.width; + }, + + set: function(value) { + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'height', { + + get: function() { + return this.scale.y * this.texture.frame.height; + }, + + set: function(value) { + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +/** + * Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous + * texture this Sprite was using. + * + * @method PIXI.Sprite#setTexture + * @param texture {Texture} The PIXI texture that is displayed by the sprite + * @param [destroy=false] {boolean} Call Texture.destroy on the current texture before replacing it with the new one? + */ +PIXI.Sprite.prototype.setTexture = function(texture, destroyBase) +{ + if (destroyBase) + { + this.texture.baseTexture.destroy(); + } + + // Over-ridden by loadTexture as needed + this.texture.baseTexture.skipRender = false; + this.texture = texture; + this.texture.valid = true; + this.cachedTint = -1; +}; + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @method PIXI.Sprite#onTextureUpdate + * @param event + * @private + */ +PIXI.Sprite.prototype.onTextureUpdate = function() +{ + // so if _width is 0 then width was not set.. + if (this._width) this.scale.x = this._width / this.texture.frame.width; + if (this._height) this.scale.y = this._height / this.texture.frame.height; +}; + +/** +* Returns the bounds of the Sprite as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* It is important to note that the transform is not updated when you call this method. +* So if this Sprite is the child of a Display Object which has had its transform +* updated since the last render pass, those changes will not yet have been applied +* to this Sprites worldTransform. If you need to ensure that all parent transforms +* are factored into this getBounds operation then you should call `updateTransform` +* on the root most object in this Sprites display list first. +* +* @method PIXI.Sprite#getBounds +* @param matrix {Matrix} the transformation matrix of the sprite +* @return {Rectangle} the framing rectangle +*/ +PIXI.Sprite.prototype.getBounds = function(matrix) +{ + var width = this.texture.frame.width; + var height = this.texture.frame.height; + + var w0 = width * (1-this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1-this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + if (b === 0 && c === 0) + { + // scale may be negative! + if (a < 0) + { + a *= -1; + var temp = w0; + w0 = -w1; + w1 = -temp; + } + + if (d < 0) + { + d *= -1; + var temp = h0; + h0 = -h1; + h1 = -temp; + } + + // this means there is no rotation going on right? RIGHT? + // if thats the case then we can avoid checking the bound values! yay + minX = a * w1 + tx; + maxX = a * w0 + tx; + minY = d * h1 + ty; + maxY = d * h0 + ty; + } + else + { + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; +}; + +/** + * Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. + * + * @method PIXI.Sprite#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.Sprite.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.Sprite#_renderWebGL +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix) +{ + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha <= 0 || !this.renderable) return; + + // They provided an alternative rendering matrix, so use it + var wt = this.worldTransform; + + if (matrix) + { + wt = matrix; + } + + // A quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) + { + var spriteBatch = renderSession.spriteBatch; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + spriteBatch.start(); + } + + // add this sprite to the batch + spriteBatch.render(this); + + // now loop through the children and make sure they get rendered + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + // time to stop the sprite batch as either a mask element or a filter draw will happen next + spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + spriteBatch.start(); + } + else + { + renderSession.spriteBatch.render(this); + + // Render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession, wt); + } + + } +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.Sprite#_renderCanvas +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix) +{ + // If the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha === 0 || !this.renderable || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { + return; + } + + var wt = this.worldTransform; + + // If they provided an alternative rendering matrix then use it + if (matrix) + { + wt = matrix; + } + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + // Ignore null sources + if (!this.texture.valid) + { + // Update the children and leave + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + return; + } + + var resolution = this.texture.baseTexture.resolution / renderSession.resolution; + + renderSession.context.globalAlpha = this.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for this texture + if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode) + { + renderSession.scaleMode = this.texture.baseTexture.scaleMode; + renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + + // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions + var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width; + var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height; + + var tx = (wt.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (wt.ty * renderSession.resolution) + renderSession.shakeY; + + var cw = this.texture.crop.width; + var ch = this.texture.crop.height; + + if (this.texture.rotated) + { + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var e = cw; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + wt.a = a * 6.123233995736766e-17 + -c; + wt.b = b * 6.123233995736766e-17 + -d; + wt.c = a + c * 6.123233995736766e-17; + wt.d = b + d * 6.123233995736766e-17; + + // Update cropping dimensions. + cw = ch; + ch = e; + } + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx | 0, ty | 0); + dx |= 0; + dy |= 0; + } + else + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + } + + dx /= resolution; + dy /= resolution; + + if (this.tint !== 0xFFFFFF) + { + if (this.texture.requiresReTint || this.cachedTint !== this.tint) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + } + + renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + else + { + var cx = this.texture.crop.x; + var cy = this.texture.crop.y; + + cw = Math.floor(cw) + ch = Math.floor(ch) + + renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @method PIXI.initDefaultShaders +* @static +* @private +*/ +PIXI.initDefaultShaders = function() +{ +}; + +/** +* @method PIXI.CompileVertexShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileVertexShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); +}; + +/** +* @method PIXI.CompileFragmentShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileFragmentShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); +}; + +/** +* @method PIXI._CompileShader +* @static +* @private +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @param shaderType {Number} +* @return {Any} +*/ +PIXI._CompileShader = function(gl, shaderSrc, shaderType) +{ + var src = shaderSrc; + + if (Array.isArray(shaderSrc)) + { + 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; +}; + +/** +* @method PIXI.compileProgram +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param vertexSrc {Array} +* @param fragmentSrc {Array} +* @return {Any} +*/ +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(gl.getProgramInfoLog(shaderProgram)); + window.console.log("Could not initialise shaders"); + } + + return shaderProgram; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + * @author Richard Davey http://www.photonstorm.com @photonstorm + */ + +/** +* @class PIXI.PixiShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PixiShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = null; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + /** + * A local flag + * @property firstRun + * @type Boolean + * @private + */ + this.firstRun = true; + + /** + * A dirty flag + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Uniform attributes cache. + * @property attributes + * @type Array + * @private + */ + this.attributes = []; + + this.init(); +}; + +PIXI.PixiShader.prototype.constructor = PIXI.PixiShader; + +PIXI.PixiShader.prototype.initMultitexShader = function () { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.fragmentSrc = [ + '// PixiShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}', + '}' + ]; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + //this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.uSamplerArray = gl.getUniformLocation(program, 'uSamplerArray[0]'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSamplerArray, indices); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; + +PIXI.PixiShader.prototype.initDefaultShader = function () { + + if (this.fragmentSrc === null) { + this.fragmentSrc = [ + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', + '}' + ]; + } + + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; +/** +* Initialises the shader. +* +* @method PIXI.PixiShader#init +*/ +PIXI.PixiShader.prototype.init = function(usingFilter) +{ + if (PIXI._enableMultiTextureToggle && !usingFilter) { + this.initMultitexShader(); + } else { + this.initDefaultShader(); + } +}; + +/** +* Initialises the shader uniform values. +* +* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ +* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf +* +* @method PIXI.PixiShader#initUniforms +*/ +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') + { + // These require special handling + 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 + { + // GL function reference + 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; + } + } + } + +}; + +/** +* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) +* +* @method PIXI.PixiShader#initSampler2D +*/ +PIXI.PixiShader.prototype.initSampler2D = function(uniform) +{ + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { + return; + } + + var gl = this.gl; + + // No need to do string manipulation for this. + gl.activeTexture(gl.TEXTURE0 + this.textureCount); + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + + // Extended texture data + if (uniform.textureData) + { + var data = uniform.textureData; + + // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); + // GLTextureLinear = mag/min linear, wrap clamp + // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat + // GLTextureNearest = mag/min nearest, wrap clamp + // AudioTexture = whatever + luminance + width 512, height 2, border 0 + // KeyTexture = whatever + luminance + width 256, height 2, border 0 + + // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + + 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; + + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels); + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); + } + else + { + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels); + 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++; + +}; + +/** +* Updates the shader uniform values. +* +* @method PIXI.PixiShader#syncUniforms +*/ +PIXI.PixiShader.prototype.syncUniforms = function() +{ + this.textureCount = 1; + var uniform; + var gl = this.gl; + + // This would probably be faster in an array and it would guarantee key order + 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]); + + if(uniform.value.baseTexture._dirty[gl.id]) + { + PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + } + + // 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); + } + } + } + +}; + +/** +* Destroys the shader. +* +* @method PIXI.PixiShader#destroy +*/ +PIXI.PixiShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** +* The Default Vertex shader source. +* +* @property defaultVertexSrc +* @type String +*/ +PIXI.PixiShader.defaultVertexSrc = [ + '// PixiShader Vertex Shader', + '// With multi-texture rendering', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute vec4 aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + + 'const vec2 center = vec2(-1.0, 1.0);', + + 'void main(void) {', + ' if (aTextureIndex > 0.0) gl_Position = vec4(0.0);', + ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', + ' vTextureCoord = aTextureCoord;', + ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', + ' vTextureIndex = aTextureIndex;', + '}' +]; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @class PIXI.PixiFastShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.PixiFastShader = function (gl) { + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '// PixiFastShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aPositionCoord;', + 'attribute vec2 aScale;', + 'attribute float aRotation;', + 'attribute vec2 aTextureCoord;', + 'attribute float aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform mat3 uMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + + '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;', + ' vTextureIndex = aTextureIndex;', + // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;', + ' vColor = aColor;', + '}' + ]; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + this.init(); +}; + +PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader; + +/** + * Initialises the shader. + * + * @method PIXI.PixiFastShader#init + */ +PIXI.PixiFastShader.prototype.init = function () { + + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + this.uMatrix = gl.getUniformLocation(program, 'uMatrix'); + + // get and store the attributes + 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'); + + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its somthing to do with the current state of the gl context. + // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if (this.colorAttribute === -1) { + this.colorAttribute = 2; + } + + this.attributes = [ + this.aVertexPosition, + this.aPositionCoord, + this.aScale, + this.aRotation, + this.aTextureCoord, + this.colorAttribute, + this.aTextureIndex + ]; + + // End worst hack eva // + + this.program = program; +}; + +/** + * Destroys the shader. + * + * @method PIXI.PixiFastShader#destroy + */ +PIXI.PixiFastShader.prototype.destroy = function () { + this.gl.deleteProgram(this.program); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.StripShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.StripShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord);return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) ;return;}\n' + } + + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord);', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '//StripShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute float aTextureIndex;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + // 'uniform float alpha;', + // 'uniform vec3 tint;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // '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);', + ' vTextureCoord = aTextureCoord;', + ' vTextureIndex = aTextureIndex;', + // ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.StripShader.prototype.constructor = PIXI.StripShader; + +/** +* Initialises the shader. +* +* @method PIXI.StripShader#init +*/ +PIXI.StripShader.prototype.init = function() +{ + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + //this.dimensions = gl.getUniformLocation(this.program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.aTextureIndex]; + + this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix'); + this.alpha = gl.getUniformLocation(program, 'alpha'); + + this.program = program; +}; + +/** +* Destroys the shader. +* +* @method PIXI.StripShader#destroy +*/ +PIXI.StripShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.PrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + 'precision mediump float;', + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform float alpha;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.PrimitiveShader#init +*/ +PIXI.PrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.PrimitiveShader#destroy +*/ +PIXI.PrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.ComplexPrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.ComplexPrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + + 'precision mediump float;', + + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + //'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 color;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.ComplexPrimitiveShader#init +*/ +PIXI.ComplexPrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.color = gl.getUniformLocation(program, 'color'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.ComplexPrimitiveShader#destroy +*/ +PIXI.ComplexPrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +PIXI.glContexts = []; // this is where we store the webGL contexts for easy access. +PIXI.instances = []; +PIXI._enableMultiTextureToggle = false; + +/** + * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class PIXI.WebGLRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.WebGLRenderer = function(game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + this.extensions = {}; + + /** + * @property type + * @type Number + */ + this.type = Phaser.WEBGL; + + /** + * The resolution of the renderer + * + * @property resolution + * @type Number + * @default 1 + */ + this.resolution = game.resolution; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * + * @property preserveDrawingBuffer + * @type Boolean + */ + this.preserveDrawingBuffer = game.preserveDrawingBuffer; + + /** + * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true: + * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0). + * If the Stage is transparent, Pixi will clear to the target Stage's background color. + * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * The width of the canvas view + * + * @property width + * @type Number + */ + this.width = game.width; + + /** + * The height of the canvas view + * + * @property height + * @type Number + */ + this.height = game.height; + + /** + * The canvas element that everything is drawn to + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * @property _contextOptions + * @type Object + * @private + */ + this._contextOptions = { + alpha: this.transparent, + antialias: game.antialias, + failIfMajorPerformanceCaveat: config.failIfMajorPerformanceCaveat, + premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: this.preserveDrawingBuffer + }; + + /** + * @property projection + * @type Point + */ + this.projection = new PIXI.Point(); + + /** + * @property offset + * @type Point + */ + this.offset = new PIXI.Point(); + + // time to create the render managers! each one focuses on managing a state in webGL + + /** + * Deals with managing the shader programs and their attribs + * @property shaderManager + * @type WebGLShaderManager + */ + this.shaderManager = new PIXI.WebGLShaderManager(); + + /** + * Manages the rendering of sprites + * @property spriteBatch + * @type WebGLSpriteBatch + */ + this.spriteBatch = new PIXI.WebGLSpriteBatch(game); + + /** + * Manages the masks using the stencil buffer + * @property maskManager + * @type WebGLMaskManager + */ + this.maskManager = new PIXI.WebGLMaskManager(); + + /** + * Manages the filters + * @property filterManager + * @type WebGLFilterManager + */ + this.filterManager = new PIXI.WebGLFilterManager(); + + /** + * Manages the stencil buffer + * @property stencilManager + * @type WebGLStencilManager + */ + this.stencilManager = new PIXI.WebGLStencilManager(); + + /** + * Manages the blendModes + * @property blendModeManager + * @type WebGLBlendModeManager + */ + this.blendModeManager = new PIXI.WebGLBlendModeManager(); + + /** + * @property renderSession + * @type Object + */ + this.renderSession = {}; + + /** + * @property currentBatchedTextures + * @type Array + */ + this.currentBatchedTextures = []; + + // Needed? + this.renderSession.game = this.game; + this.renderSession.gl = this.gl; + this.renderSession.drawCount = 0; + this.renderSession.shaderManager = this.shaderManager; + this.renderSession.maskManager = this.maskManager; + this.renderSession.filterManager = this.filterManager; + this.renderSession.blendModeManager = this.blendModeManager; + this.renderSession.spriteBatch = this.spriteBatch; + this.renderSession.stencilManager = this.stencilManager; + this.renderSession.renderer = this; + this.renderSession.resolution = this.resolution; + this.renderSession.roundPixels = config.roundPixels || false; + this.renderSession.maxTextureAvailableSpace = null; // filled in setTexturePriority() + + // time init the context.. + this.initContext(); + + // map some webGL blend modes.. + this.mapBlendModes(); + +}; + +// constructor +PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer; + +/** +* @method PIXI.WebGLRenderer#initContext +*/ +PIXI.WebGLRenderer.prototype.initContext = function() +{ + var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); + + this.gl = gl; + + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + this.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.maxTextureSize = this.gl.getParameter(gl.MAX_TEXTURE_SIZE); + + this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++; + + PIXI.glContexts[this.glContextId] = gl; + + PIXI.instances[this.glContextId] = this; + + // set up the default pixi settings.. + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + gl.enable(gl.BLEND); + + // need to set the context for all the managers... + this.shaderManager.setContext(gl); + this.spriteBatch.setContext(gl); + this.maskManager.setContext(gl); + this.filterManager.setContext(gl); + this.blendModeManager.setContext(gl); + this.stencilManager.setContext(gl); + + this.renderSession.gl = this.gl; + + // now resize and we are good to go! + this.resize(this.width, this.height); + + // Load WebGL extension + this.extensions.compression = {}; + + var etc1 = gl.getExtension('WEBGL_compressed_texture_etc1') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'); + var pvrtc = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); + var s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); + + if (etc1) { this.extensions.compression.ETC1 = etc1; } + if (pvrtc) { this.extensions.compression.PVRTC = pvrtc; } + if (s3tc) { this.extensions.compression.S3TC = s3tc; } +}; + +/** +* If Multi Texture support has been enabled, then calling this method will enable batching on the given +* textures. The texture collection is an array of keys, that map to Phaser.Cache image entries. +* +* The number of textures that can be batched is dependent on hardware. If you provide more textures +* than can be batched by the GPU, then only those at the start of the array will be used. Generally +* you shouldn't provide more than 16 textures to this method. You can check the hardware limit via the +* `maxTextures` property. +* +* You can also check the property `currentBatchedTextures` at any time, to see which textures are currently +* being batched. +* +* To stop all textures from being batched, call this method again with an empty array. +* +* To change the textures being batched, call this method with a new array of image keys. The old ones +* will all be purged out and no-longer batched, and the new ones enabled. +* +* Note: Throws a warning if you haven't enabled Multiple Texture batching support in the Phaser Game config. +* +* @method PIXI.WebGLRenderer#setTexturePriority +* @param textureNameCollection {Array} An Array of Texture Cache keys to use for multi-texture batching. +* @return {Array} An array containing the texture keys that were enabled for batching. +*/ +PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + if (!PIXI._enableMultiTextureToggle) + { + console.warn('setTexturePriority error: Multi Texture support hasn\'t been enabled in the Phaser Game Config.'); + return; + } + var clampPot = function (potSize) { + --potSize; + potSize |= potSize >> 1; + potSize |= potSize >> 2; + potSize |= potSize >> 4; + potSize |= potSize >> 8; + potSize |= potSize >> 16; + return ++potSize; + }; + var gl = this.gl; + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + var imageCache = this.game.cache._cache.image; + var imageName = null; + + // Clear out all previously batched textures and reset their flags. + // If the array has been modified, then the developer will have to + // deal with that in their own way. + for (var i = 0; i < this.currentBatchedTextures.length; i++) + { + imageName = this.currentBatchedTextures[i]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + + imageCache[imageName].base.textureIndex = 0; + } + var maxTextureAvailableSpace = (maxTextureSize) - clampPot(Math.max(this.width, this.height)); + this.currentBatchedTextures.length = 0; + // We start from 1 because framebuffer texture uses unit 0. + for (var j = 0; j < textureNameCollection.length; ++j) + { + imageName = textureNameCollection[j]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + // Unit 0 is reserved for Pixi's framebuffer + var base = imageCache[imageName].base; + maxTextureAvailableSpace -= clampPot(Math.max(base.width, base.height)); + if (maxTextureAvailableSpace <= 0) { + base.textureIndex = 0; + console.warn('setTexturePriority: Image "%s" was given textureIndex=0 because there is no available texture space (%s).', + imageName, maxTextureAvailableSpace); + } else { + base.textureIndex = (1 + (j % (maxTextures - 1))); + } + this.currentBatchedTextures.push(imageName); + } + + this.renderSession.maxTextureAvailableSpace = maxTextureAvailableSpace; + + return this.currentBatchedTextures; + +}; + +/** + * Renders the stage to its webGL view + * + * @method PIXI.WebGLRenderer#render + * @param stage {Stage} the Stage element to be rendered + */ +PIXI.WebGLRenderer.prototype.render = function(stage) +{ + // no point rendering if our context has been blown up! + if (this.contextLost) + { + return; + } + + var gl = this.gl; + + // -- Does this need to be set every frame? -- // + gl.viewport(0, 0, this.width, this.height); + + // make sure we are bound to the main frame buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + if (this.game.clearBeforeRender) + { + gl.clearColor(stage._bgColor.r, stage._bgColor.g, stage._bgColor.b, stage._bgColor.a); + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + this.offset.x = this.game.camera._shake.x; + this.offset.y = this.game.camera._shake.y; + + this.renderDisplayObject(stage, this.projection); +}; + +/** + * Renders a Display Object. + * + * @method PIXI.WebGLRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The DisplayObject to render + * @param projection {Point} The projection + * @param buffer {Array} a standard WebGL buffer + */ +PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix) +{ + this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL); + + // reset the render session data.. + this.renderSession.drawCount = 0; + + // make sure to flip the Y if using a render texture.. + this.renderSession.flipY = buffer ? -1 : 1; + + // set the default projection + this.renderSession.projection = projection; + + //set the default offset + this.renderSession.offset = this.offset; + + // start the sprite batch + this.spriteBatch.begin(this.renderSession); + + // start the filter manager + this.filterManager.begin(this.renderSession, buffer); + + // render the scene! + displayObject._renderWebGL(this.renderSession, matrix); + + // finish the sprite batch + this.spriteBatch.end(); +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @method PIXI.WebGLRenderer#resize + * @param width {Number} the new width of the webGL view + * @param height {Number} the new height of the webGL view + */ +PIXI.WebGLRenderer.prototype.resize = function(width, height) +{ + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } + + this.gl.viewport(0, 0, this.width, this.height); + + this.projection.x = this.width / 2 / this.resolution; + this.projection.y = -this.height / 2 / this.resolution; +}; + +/** + * Updates and creates a WebGL compressed texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateCompressedTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateCompressedTexture = function (texture) { + if (!texture.hasLoaded) + { + return false; + } + var gl = this.gl; + var textureMetaData = texture.source; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + textureMetaData.glExtensionFormat, + textureMetaData.width, + textureMetaData.height, + 0, + textureMetaData.textureData + ); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + texture._dirty[gl.id] = false; + return true; +}; + +/** + * Updates and Creates a WebGL texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateTexture = function(texture) +{ + if (!texture.hasLoaded) + { + return false; + } + if (texture.source.compressionAlgorithm) { + return this.updateCompressedTexture(texture); + } + + var gl = this.gl; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha); + + 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); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + + texture._dirty[gl.id] = false; + + // return texture._glTextures[gl.id]; + return true; + +}; + +/** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @method PIXI.WebGLRenderer#destroy + */ +PIXI.WebGLRenderer.prototype.destroy = function() +{ + 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; + + Phaser.CanvasPool.remove(this); + + PIXI.instances[this.glContextId] = null; + + PIXI.WebGLRenderer.glContextId--; +}; + +/** + * Maps Pixi blend modes to WebGL blend modes. + * + * @method PIXI.WebGLRenderer#mapBlendModes + */ +PIXI.WebGLRenderer.prototype.mapBlendModes = function() +{ + var gl = this.gl; + + if (!PIXI.blendModesWebGL) + { + var b = []; + var modes = PIXI.blendModes; + + b[modes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA]; + b[modes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SCREEN] = [gl.SRC_ALPHA, gl.ONE]; + b[modes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + PIXI.blendModesWebGL = b; + } +}; + +PIXI.WebGLRenderer.prototype.getMaxTextureUnit = function() { + var gl = this.gl; + return gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); +}; + +PIXI.enableMultiTexture = function() { + PIXI._enableMultiTextureToggle = true; +}; + +PIXI.WebGLRenderer.glContextId = 0; +PIXI.WebGLRenderer.textureArray = []; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLBlendModeManager +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLBlendModeManager = function() +{ + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 99999; +}; + +PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLBlendModeManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLBlendModeManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Sets-up the given blendMode from WebGL's point of view. +* +* @method PIXI.WebGLBlendModeManager#setBlendMode +* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD +*/ +PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode) +{ + if(this.currentBlendMode === blendMode)return false; + + this.currentBlendMode = blendMode; + + var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode]; + + if (blendModeWebGL) + { + this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLBlendModeManager#destroy +*/ +PIXI.WebGLBlendModeManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLMaskManager +* @constructor +* @private +*/ +PIXI.WebGLMaskManager = function() +{ +}; + +PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLMaskManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLMaskManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLMaskManager#pushMask +* @param maskData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession) +{ + var gl = renderSession.gl; + + if (maskData.dirty) + { + PIXI.WebGLGraphics.updateGraphics(maskData, gl); + } + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLMaskManager#popMask +* @param maskData {Array} +* @param renderSession {Object} an object containing all the useful parameters +*/ +PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession) +{ + var gl = this.gl; + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); + +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLMaskManager#destroy +*/ +PIXI.WebGLMaskManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLStencilManager +* @constructor +* @private +*/ +PIXI.WebGLStencilManager = function() +{ + this.stencilStack = []; + this.reverse = true; + this.count = 0; +}; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLStencilManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLStencilManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLStencilManager#pushMask +* @param graphics {Graphics} +* @param webGLData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.bindGraphics(graphics, webGLData, renderSession); + + if(this.stencilStack.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + this.reverse = true; + this.count = 0; + } + + this.stencilStack.push(webGLData); + + var level = this.count; + + gl.colorMask(false, false, false, false); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + + if(webGLData.mode === 1) + { + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + + this.reverse = !this.reverse; + } + else + { + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + this.count++; +}; + +/** + * TODO this does not belong here! + * + * @method PIXI.WebGLStencilManager#bindGraphics + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession) +{ + //if(this._currentGraphics === graphics)return; + this._currentGraphics = graphics; + + var gl = this.gl; + + // bind the graphics object.. + var projection = renderSession.projection, + offset = renderSession.offset, + shader;// = renderSession.shaderManager.primitiveShader; + + if(webGLData.mode === 1) + { + shader = renderSession.shaderManager.complexPrimitiveShader; + + renderSession.shaderManager.setShader( shader ); + + gl.uniform1f(shader.flipY, renderSession.flipY); + + 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, Phaser.Color.hexToRGBArray(graphics.tint)); + gl.uniform3fv(shader.color, webGLData.color); + + gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0); + + + // now do the rest.. + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } + else + { + //renderSession.shaderManager.activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + renderSession.shaderManager.setShader( shader ); + + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, renderSession.flipY); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } +}; + +/** + * @method PIXI.WebGLStencilManager#popStencil + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.stencilStack.pop(); + + this.count--; + + if(this.stencilStack.length === 0) + { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + + } + else + { + + var level = this.count; + + this.bindGraphics(graphics, webGLData, renderSession); + + gl.colorMask(false, false, false, false); + + if(webGLData.mode === 1) + { + this.reverse = !this.reverse; + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + + } + else + { + // console.log("<<>>") + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + + } +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLStencilManager#destroy +*/ +PIXI.WebGLStencilManager.prototype.destroy = function() +{ + this.stencilStack = null; + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLShaderManager +* @constructor +* @private +*/ +PIXI.WebGLShaderManager = function() +{ + /** + * @property maxAttibs + * @type Number + */ + this.maxAttibs = 10; + + /** + * @property attribState + * @type Array + */ + this.attribState = []; + + /** + * @property tempAttribState + * @type Array + */ + this.tempAttribState = []; + + for (var i = 0; i < this.maxAttibs; i++) + { + this.attribState[i] = false; + } + + /** + * @property stack + * @type Array + */ + this.stack = []; + +}; + +PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLShaderManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLShaderManager.prototype.setContext = function(gl) +{ + this.gl = gl; + + // the next one is used for rendering primitives + this.primitiveShader = new PIXI.PrimitiveShader(gl); + + // the next one is used for rendering triangle strips + this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl); + + // this shader is used for the default sprite rendering + this.defaultShader = new PIXI.PixiShader(gl); + + // this shader is used for the fast sprite rendering + this.fastShader = new PIXI.PixiFastShader(gl); + + // the next one is used for rendering triangle strips + this.stripShader = new PIXI.StripShader(gl); + + // the next one is used for rendering creature meshes + this.creatureShader = PIXI.CreatureShader ? new PIXI.CreatureShader(gl) : null; + + this.setShader(this.defaultShader); +}; + +/** +* Takes the attributes given in parameters. +* +* @method PIXI.WebGLShaderManager#setAttribs +* @param attribs {Array} attribs +*/ +PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs) +{ + // reset temp state + var i; + + for (i = 0; i < this.tempAttribState.length; i++) + { + this.tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + var attribId = attribs[i]; + this.tempAttribState[attribId] = true; + } + + var gl = this.gl; + + for (i = 0; i < this.attribState.length; i++) + { + if(this.attribState[i] !== this.tempAttribState[i]) + { + this.attribState[i] = this.tempAttribState[i]; + + if(this.tempAttribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } +}; + +/** +* Sets the current shader. +* +* @method PIXI.WebGLShaderManager#setShader +* @param shader {Any} +*/ +PIXI.WebGLShaderManager.prototype.setShader = function(shader) +{ + if(this._currentId === shader._UID)return false; + + this._currentId = shader._UID; + + this.currentShader = shader; + + this.gl.useProgram(shader.program); + this.setAttribs(shader.attributes); + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLShaderManager#destroy +*/ +PIXI.WebGLShaderManager.prototype.destroy = function() +{ + this.attribState = null; + + this.tempAttribState = null; + + this.primitiveShader.destroy(); + + this.complexPrimitiveShader.destroy(); + + this.defaultShader.destroy(); + + this.fastShader.destroy(); + + this.stripShader.destroy(); + + if (this.creatureShader) { + this.creatureShader.destroy(); + } + + this.gl = null; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** + * + * @class PIXI.WebGLSpriteBatch + * @private + * @constructor + */ +PIXI.WebGLSpriteBatch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 5; + + /** + * The number of images in the SpriteBatch before it flushes + * @property size + * @type Number + */ + this.size = 2000; //Math.pow(2, 16) / this.vertSize; + + //the total number of bytes in our batch + // Including texture index: + // position + uv + color + textureIndex + // vec2 + vec2 + (char * 4) + float + this.vertexSize = (4 * 2) + (4 * 2) + (4) + (4); + var numVerts = this.vertexSize * this.size * 4; + //this.size * 4 * 4 * this.vertSize; + //the total number of indices in our batch + var numIndices = this.size * 6; + + /** + * Holds the vertices + * + * @property vertices + * @type ArrayBuffer + */ + this.vertices = new ArrayBuffer(numVerts); + + /** + * View on the vertices as a Float32Array + * + * @property positions + * @type Float32Array + */ + this.positions = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array + * + * @property colors + * @type Uint32Array + */ + this.colors = new Uint32Array(this.vertices); + + /** + * Holds the indices + * + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * @property textures + * @type Array + */ + this.textures = []; + + /** + * @property blendModes + * @type Array + */ + this.blendModes = []; + + /** + * @property shaders + * @type Array + */ + this.shaders = []; + + /** + * @property sprites + * @type Array + */ + this.sprites = []; + + /** + * @property defaultShader + * @type Phaser.Filter + */ + this.defaultShader = null; +}; + +/** + * @method PIXI.WebGLSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLSpriteBatch.prototype.setContext = function (gl) { + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.gl = gl; + if (PIXI._enableMultiTextureToggle) { + var dynamicIfs = '\tif (vTextureIndex == 0.0) {gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + 'void main(void) {', + dynamicIfs, + '\tgl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;', + '}' + ]); + } + else + { + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]); + } + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + this.currentBlendMode = 99999; + + var shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = this.defaultShader.fragmentSrc; + shader.uniforms = {}; + shader.init(); + + this.defaultShader.shaders[gl.id] = shader; +}; + +/** + * @method PIXI.WebGLSpriteBatch#begin + * @param renderSession {Object} The RenderSession object + */ +PIXI.WebGLSpriteBatch.prototype.begin = function (renderSession) { + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.defaultShader; + + this.start(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#end + */ +PIXI.WebGLSpriteBatch.prototype.end = function () { + this.flush(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#render + * @param sprite {Sprite} the sprite to render when using this spritebatch + * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. + */ +PIXI.WebGLSpriteBatch.prototype.render = function (sprite, matrix) { + var texture = sprite.texture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + if (PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + baseTexture.textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] = baseTexture; + } + + // They provided an alternative rendering matrix, so use it + var wt = sprite.worldTransform; + + if (matrix) { + wt = matrix; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // get the uvs for the texture + var uvs = texture._uvs; + + // if the uvs have not updated then no point rendering just yet! + if (!uvs) { + return; + } + + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + + var w0, w1, h0, h1; + + if (texture.trim) { + // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords. + var trim = texture.trim; + + w1 = trim.x - aX * trim.width; + w0 = w1 + texture.crop.width; + + h1 = trim.y - aY * trim.height; + h0 = h1 + texture.crop.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 i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + var tiOffset = this.currentBatchSize * 4; + var resolution = texture.baseTexture.resolution; + var textureIndex = texture.baseTexture.textureIndex; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + + var cw = texture.crop.width; + var ch = texture.crop.height; + + if (texture.rotated) + { + var a0 = wt.a; + var b0 = wt.b; + var c0 = wt.c; + var d0 = wt.d; + var _w1 = w1; + var _w0 = w0; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + a = a0 * 6.123233995736766e-17 + -c0; + b = b0 * 6.123233995736766e-17 + -d0; + c = a0 + c0 * 6.123233995736766e-17; + d = b0 + d0 * 6.123233995736766e-17; + + // Update UV coordinates + texture._updateUvsInverted(); + + // Rotate dimensions + w0 = h0; + w1 = h1; + h0 = _w0; + h1 = _w1; + } + + var colors = this.colors; + var positions = this.positions; + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + if (this.renderSession.roundPixels) { + positions[i++] = a * w1 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w1 + ty | 0; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w0 + ty | 0; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w0 + ty | 0; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w1 + ty | 0; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } else { + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx; + positions[i++] = d * h1 + b * w0 + ty; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders a TilingSprite using the spriteBatch. + * + * @method PIXI.WebGLSpriteBatch#renderTilingSprite + * @param sprite {TilingSprite} the sprite to render + */ +PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function (sprite) { + var texture = sprite.tilingTexture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + var textureIndex = sprite.texture.baseTexture.textureIndex; + if (PIXI.WebGLRenderer.textureArray[textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[textureIndex] = baseTexture; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // set the textures uvs temporarily + if (!sprite._uvs) { + sprite._uvs = new PIXI.TextureUvs(); + } + + var uvs = sprite._uvs; + + var w = texture.baseTexture.width; + var h = texture.baseTexture.height; + + // var w = sprite._frame.sourceSizeW; + // var h = sprite._frame.sourceSizeH; + + // w = 16; + // h = 16; + + sprite.tilePosition.x %= w * sprite.tileScaleOffset.x; + sprite.tilePosition.y %= h * sprite.tileScaleOffset.y; + + var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x); + var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y); + + var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x); + var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.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; + + // Get the sprites current alpha and tint and combine them into a single color + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + var positions = this.positions; + var colors = this.colors; + + var width = sprite.width; + var height = sprite.height; + + // TODO trim?? + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + var w0 = width * (1 - aX); + var w1 = width * -aX; + + var h0 = height * (1 - aY); + var h1 = height * -aY; + + var i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + + var resolution = texture.baseTexture.resolution; + + var wt = sprite.worldTransform; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + // xy + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + // uv + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = (a * w0 + c * h1 + tx); + positions[i++] = d * h1 + b * w0 + ty; + // uv + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + // uv + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + // uv + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders the content and empties the current batch. + * + * @method PIXI.WebGLSpriteBatch#flush + */ +PIXI.WebGLSpriteBatch.prototype.flush = function () { + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize === 0) { + return; + } + + var gl = this.gl; + var shader; + + if (this.dirty) { + this.dirty = false; + + shader = this.defaultShader.shaders[gl.id]; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + // this is the same for each shader? + var stride = this.vertexSize; //this.vertSize * 4; + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 8); + + // color attributes will be interpreted as unsigned bytes and normalized + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 16); + + // Texture index + gl.vertexAttribPointer(shader.aTextureIndex, 1, gl.FLOAT, false, stride, 20); + } + + // upload the verts to the buffer + if (this.currentBatchSize > (this.size * 0.5)) { + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + } else { + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + var view = this.positions.subarray(0, this.currentBatchSize * this.vertexSize); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); + } + + var nextTexture, nextBlendMode, nextShader; + var batchSize = 0; + var start = 0; + + var currentBaseTexture = null; + var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode; + var currentShader = null; + + var blendSwap = false; + var shaderSwap = false; + var sprite; + var textureIndex = 0; + + for (var i = 0, j = this.currentBatchSize; i < j; i++) { + + sprite = this.sprites[i]; + + if (sprite.tilingTexture) { + nextTexture = sprite.tilingTexture.baseTexture; + } else { + nextTexture = sprite.texture.baseTexture; + } + + nextBlendMode = sprite.blendMode; + nextShader = sprite.shader || this.defaultShader; + + blendSwap = currentBlendMode !== nextBlendMode; + shaderSwap = currentShader !== nextShader; // should I use _UIDS??? + + var skip = nextTexture.skipRender; + + if (skip && sprite.children.length > 0) { + skip = false; + } + // + if (/*(currentBaseTexture != nextTexture && !skip) ||*/ + blendSwap || + shaderSwap) { + this.renderBatch(currentBaseTexture, batchSize, start); + + start = i; + batchSize = 0; + currentBaseTexture = nextTexture; + + if (blendSwap) { + currentBlendMode = nextBlendMode; + this.renderSession.blendModeManager.setBlendMode(currentBlendMode); + } + + if (shaderSwap) { + currentShader = nextShader; + + shader = currentShader.shaders[gl.id]; + + if (!shader) { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = currentShader.fragmentSrc; + shader.uniforms = currentShader.uniforms; + shader.init(); + + currentShader.shaders[gl.id] = shader; + } + + // set shader function??? + this.renderSession.shaderManager.setShader(shader); + + if (shader.dirty) { + shader.syncUniforms(); + } + + // both these only need to be set if they are changing.. + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(shader.projectionVector, projection.x, projection.y); + + // TODO - this is temporary! + var offsetVector = this.renderSession.offset; + gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y); + + // set the pointers + } + } + + batchSize++; + } + + this.renderBatch(currentBaseTexture, batchSize, start); + + // then reset the batch! + this.currentBatchSize = 0; +}; + +/** + * @method PIXI.WebGLSpriteBatch#renderBatch + * @param texture {Texture} + * @param size {Number} + * @param startIndex {Number} + */ +PIXI.WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { + if (size === 0) { + return; + } + + var gl = this.gl; + + // check if a texture is dirty.. + if (texture._dirty[gl.id]) { + if (!this.renderSession.renderer.updateTexture(texture)) { + // If updateTexture returns false then we cannot render it, so bail out now + return; + } + }else { + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + } + + gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2); + // increment the draw count + this.renderSession.drawCount++; +}; + +/** + * @method PIXI.WebGLSpriteBatch#stop + */ +PIXI.WebGLSpriteBatch.prototype.stop = function () { + this.flush(); + this.dirty = true; +}; + +/** + * @method PIXI.WebGLSpriteBatch#start + */ +PIXI.WebGLSpriteBatch.prototype.start = function () { + this.dirty = true; +}; + +/** + * Destroys the SpriteBatch. + * + * @method PIXI.WebGLSpriteBatch#destroy + */ +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; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** +* @class PIXI.WebGLFastSpriteBatch +* @constructor +*/ +PIXI.WebGLFastSpriteBatch = function(gl) +{ + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 11; + + /** + * @property maxSize + * @type Number + */ + this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize; + + /** + * @property size + * @type Number + */ + this.size = this.maxSize; + + //the total number of floats in our batch + var numVerts = this.size * 4 * this.vertSize; + + //the total number of indices in our batch + var numIndices = this.maxSize * 6; + + /** + * Vertex data + * @property vertices + * @type Float32Array + */ + this.vertices = new Float32Array(numVerts); + + /** + * Index data + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property vertexBuffer + * @type Object + */ + this.vertexBuffer = null; + + /** + * @property indexBuffer + * @type Object + */ + this.indexBuffer = null; + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i=0, j=0; i < numIndices; i += 6, j += 4) + { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 0; + + /** + * @property renderSession + * @type Object + */ + this.renderSession = null; + + /** + * @property shader + * @type Object + */ + this.shader = null; + + /** + * @property matrix + * @type Matrix + */ + this.matrix = null; + + this.setContext(gl); +}; + +PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLFastSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl) +{ + this.gl = gl; + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#begin + * @param spriteBatch {WebGLSpriteBatch} + * @param renderSession {Object} + */ +PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession) +{ + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.fastShader; + + this.matrix = spriteBatch.worldTransform.toArray(true); + + this.start(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#end + */ +PIXI.WebGLFastSpriteBatch.prototype.end = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#render + * @param spriteBatch {WebGLSpriteBatch} + */ +PIXI.WebGLFastSpriteBatch.prototype.render = function (spriteBatch) +{ + var children = spriteBatch.children; + var sprite = children[0]; + + // if the uvs have not updated then no point rendering just yet! + + // check texture. + if(!sprite.texture._uvs)return; + + this.currentBaseTexture = sprite.texture.baseTexture; + + // check blend mode + if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode) + { + this.flush(); + this.renderSession.blendModeManager.setBlendMode(sprite.blendMode); + } + + for(var i=0,j= children.length; i= this.size) + { + this.flush(); + } +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#flush + */ +PIXI.WebGLFastSpriteBatch.prototype.flush = function() +{ + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize===0)return; + + var gl = this.gl; + + // bind the current texture + + if(!this.currentBaseTexture._glTextures[gl.id]) { + this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl); + return; + } + + //gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); + + // upload the verts to the buffer + + if(this.currentBatchSize > ( this.size * 0.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); + } + + // now draw those suckas! + gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0); + + // then reset the batch! + this.currentBatchSize = 0; + + // increment the draw count + this.renderSession.drawCount++; + +}; + + +/** + * @method PIXI.WebGLFastSpriteBatch#stop + */ +PIXI.WebGLFastSpriteBatch.prototype.stop = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#start + */ +PIXI.WebGLFastSpriteBatch.prototype.start = function() +{ + var gl = this.gl; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(this.shader.projectionVector, projection.x, projection.y); + + // set the matrix + gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix); + + // set the pointers + 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); + gl.vertexAttribPointer(this.shader.aTextureIndex, 1, gl.FLOAT, false, stride, 10 * 4); + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLFilterManager +* @constructor +*/ +PIXI.WebGLFilterManager = function() +{ + /** + * @property filterStack + * @type Array + */ + this.filterStack = []; + + /** + * @property offsetX + * @type Number + */ + this.offsetX = 0; + + /** + * @property offsetY + * @type Number + */ + this.offsetY = 0; +}; + +PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLFilterManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLFilterManager.prototype.setContext = function(gl) +{ + this.gl = gl; + this.texturePool = []; + + this.initShaderBuffers(); +}; + +/** +* @method PIXI.WebGLFilterManager#begin +* @param renderSession {RenderSession} +* @param buffer {ArrayBuffer} +*/ +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; +}; + +/** +* Applies the filter and adds it to the current filter stack. +* +* @method PIXI.WebGLFilterManager#pushFilter +* @param filterBlock {Object} the filter that will be pushed to the current filter stack +*/ +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(); + + // >>> modify by nextht + filterBlock._previous_stencil_mgr = this.renderSession.stencilManager; + this.renderSession.stencilManager = new PIXI.WebGLStencilManager(); + this.renderSession.stencilManager.setContext(gl); + gl.disable(gl.STENCIL_TEST); + // <<< modify by nextht + + // filter program + // OPTIMISATION - the first filter is free if its a simple color change? + 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.renderSession.resolution, this.height * this.renderSession.resolution); + } + else + { + texture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + } + + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea; + + var padding = filter.padding; + filterArea.x -= padding; + filterArea.y -= padding; + filterArea.width += padding * 2; + filterArea.height += padding * 2; + + // cap filter to screen size.. + 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer); + + // set view port + gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + projection.x = filterArea.width/2; + projection.y = -filterArea.height/2; + + offset.x = -filterArea.x; + offset.y = -filterArea.y; + + // update projection + // now restore the regular shader.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + //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; + +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLFilterManager#popFilter +*/ +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 * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + 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); + // now set the uvs.. + 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.renderSession.resolution, this.height * this.renderSession.resolution); + outputTexture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + + // need to clear this FBO as it may have some left over elements from a previous filter. + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + gl.clear(gl.COLOR_BUFFER_BIT); + + gl.disable(gl.BLEND); + + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { + var filterPass = filterBlock.filterPasses[i]; + + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture); + + // draw texture.. + //filterPass.applyFilterPass(filterArea.width, filterArea.height); + this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height); + + // swap the textures.. + var temp = inputTexture; + inputTexture = outputTexture; + outputTexture = temp; + } + + gl.enable(gl.BLEND); + + texture = inputTexture; + this.texturePool.push(outputTexture); + } + + var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1]; + + this.offsetX -= filterArea.x; + this.offsetY -= filterArea.y; + + var sizeX = this.width; + var sizeY = this.height; + + var offsetX = 0; + var offsetY = 0; + + var buffer = this.buffer; + + // time to render the filters texture to the previous scene + if(this.filterStack.length === 0) + { + gl.colorMask(true, true, true, true);//this.transparent); + } + else + { + var currentFilter = this.filterStack[this.filterStack.length-1]; + filterArea = currentFilter._filterArea; + + sizeX = filterArea.width; + sizeY = filterArea.height; + + offsetX = filterArea.x; + offsetY = filterArea.y; + + buffer = currentFilter._glFilterTexture.frameBuffer; + } + + // TODO need to remove these global elements.. + projection.x = sizeX/2; + projection.y = -sizeY/2; + + offset.x = offsetX; + offset.y = offsetY; + + filterArea = filterBlock._filterArea; + + var x = filterArea.x-offsetX; + var y = filterArea.y-offsetY; + + // update the buffers.. + // make sure to flip the y! + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + + this.vertexArray[0] = x; + this.vertexArray[1] = y + filterArea.height; + + this.vertexArray[2] = x + filterArea.width; + this.vertexArray[3] = y + filterArea.height; + + this.vertexArray[4] = x; + this.vertexArray[5] = y; + + this.vertexArray[6] = x + filterArea.width; + this.vertexArray[7] = y; + + 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); + + gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution); + + // bind the buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, buffer ); + + // set the blend mode! + //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + // >>> modify by nextht + if (this.renderSession.stencilManager) { + this.renderSession.stencilManager.destroy(); + } + this.renderSession.stencilManager = filterBlock._previous_stencil_mgr; + filterBlock._previous_stencil_mgr = null; + if (this.renderSession.stencilManager.count > 0) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + // <<< modify by nextht + + // apply! + this.applyFilterPass(filter, filterArea, sizeX, sizeY); + + // now restore the regular shader.. should happen automatically now.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2); + // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY); + + // return the texture to the pool + this.texturePool.push(texture); + filterBlock._glFilterTexture = null; +}; + + +/** +* Applies the filter to the specified area. +* +* @method PIXI.WebGLFilterManager#applyFilterPass +* @param filter {Phaser.Filter} the filter that needs to be applied +* @param filterArea {Texture} TODO - might need an update +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +*/ +PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height) +{ + // use program + var gl = this.gl; + var shader = filter.shaders[gl.id]; + + if(!shader) + { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = filter.fragmentSrc; + shader.uniforms = filter.uniforms; + shader.init(true); + + filter.shaders[gl.id] = shader; + } + + // set the shader + this.renderSession.shaderManager.setShader(shader); + +// gl.useProgram(shader.program); + + gl.uniform2f(shader.projectionVector, width/2, -height/2); + gl.uniform2f(shader.offsetVector, 0,0); + + if(filter.uniforms.dimensions) + { + filter.uniforms.dimensions.value[0] = this.width;//width; + filter.uniforms.dimensions.value[1] = this.height;//height; + filter.uniforms.dimensions.value[2] = this.vertexArray[0]; + filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height; + } + + shader.syncUniforms(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // draw the filter... + gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + + this.renderSession.drawCount++; +}; + +/** +* Initialises the shader buffers. +* +* @method PIXI.WebGLFilterManager#initShaderBuffers +*/ +PIXI.WebGLFilterManager.prototype.initShaderBuffers = function() +{ + var gl = this.gl; + + // create some buffers + this.vertexBuffer = gl.createBuffer(); + this.uvBuffer = gl.createBuffer(); + this.colorBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // bind and upload the vertexs.. + // keep a reference to the vertexFloatData.. + this.vertexArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW); + + // bind and upload the uv buffer + this.uvArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW); + + this.colorArray = new Float32Array([1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW); + + // bind and upload the index + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW); + +}; + +/** +* Destroys the filter and removes it from the filter stack. +* +* @method PIXI.WebGLFilterManager#destroy +*/ +PIXI.WebGLFilterManager.prototype.destroy = function() +{ + var gl = this.gl; + + this.filterStack = null; + + this.offsetX = 0; + this.offsetY = 0; + + // destroy textures + for (var i = 0; i < this.texturePool.length; i++) { + this.texturePool[i].destroy(); + } + + this.texturePool = null; + + //destroy buffers.. + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.uvBuffer); + gl.deleteBuffer(this.colorBuffer); + gl.deleteBuffer(this.indexBuffer); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @private + */ +function _CreateEmptyTexture(gl, width, height, scaleMode) { + var texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + return texture; +} + +/** + * @private + */ +var _fbErrors = { + 36054: 'Incomplete attachment', + 36055: 'Missing attachment', + 36057: 'Incomplete dimensions', + 36061: 'Framebuffer unsupported' +}; + +/** + * @private + */ +function _CreateFramebuffer(gl, width, height, scaleMode, textureUnit) { + var framebuffer = gl.createFramebuffer(); + var depthStencilBuffer = gl.createRenderbuffer(); + var colorBuffer = null; + var fbStatus = 0; + + gl.activeTexture(gl.TEXTURE0 + textureUnit); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer); + colorBuffer = _CreateEmptyTexture(gl, width, height, scaleMode); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorBuffer, 0); + fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + if(fbStatus !== gl.FRAMEBUFFER_COMPLETE) { + console.error('Incomplete GL framebuffer. ', _fbErrors[fbStatus]); + } + framebuffer.width = width; + framebuffer.height = height; + framebuffer.targetTexture = colorBuffer; + framebuffer.renderBuffer = depthStencilBuffer; + return framebuffer; +} + +/** +* @class PIXI.FilterTexture +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +* @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values +*/ +PIXI.FilterTexture = function(gl, width, height, scaleMode, textureUnit) +{ + textureUnit = typeof textureUnit === 'number' ? textureUnit : 0; + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + // next time to create a frame buffer and texture + + /** + * @property frameBuffer + * @type Any + */ + this.frameBuffer = _CreateFramebuffer(gl, width, height, scaleMode || PIXI.scaleModes.DEFAULT, textureUnit); + /** + * @property texture + * @type Any + */ + this.texture = this.frameBuffer.targetTexture; + this.width = width; + this.height = height; + this.renderBuffer = this.frameBuffer.renderBuffer; +}; + +PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture; + +/** +* Clears the filter texture. +* +* @method PIXI.FilterTexture#clear +*/ +PIXI.FilterTexture.prototype.clear = function() +{ + var gl = this.gl; + + gl.clearColor(0,0,0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Resizes the texture to the specified width and height + * + * @method PIXI.FilterTexture#resize + * @param width {Number} the new width of the texture + * @param height {Number} the new height of the texture + */ +PIXI.FilterTexture.prototype.resize = function(width, height) +{ + if(this.width === width && this.height === height) return; + + this.width = width; + this.height = height; + + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height ); +}; + +/** +* Destroys the filter texture. +* +* @method PIXI.FilterTexture#destroy +*/ +PIXI.FilterTexture.prototype.destroy = function() +{ + var gl = this.gl; + gl.deleteFramebuffer( this.frameBuffer ); + gl.deleteTexture( this.texture ); + + this.frameBuffer = null; + this.texture = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Creates a Canvas element of the given size. + * + * @class PIXI.CanvasBuffer + * @constructor + * @param width {Number} the width for the newly created canvas + * @param height {Number} the height for the newly created canvas + */ +PIXI.CanvasBuffer = function(width, height) +{ + /** + * The width of the Canvas in pixels. + * + * @property width + * @type Number + */ + this.width = width; + + /** + * The height of the Canvas in pixels. + * + * @property height + * @type Number + */ + this.height = height; + + /** + * The Canvas object that belongs to this CanvasBuffer. + * + * @property canvas + * @type HTMLCanvasElement + */ + this.canvas = Phaser.CanvasPool.create(this, this.width, this.height); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.canvas.getContext("2d"); + + this.canvas.width = width; + this.canvas.height = height; +}; + +PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer; + +/** + * Clears the canvas that was created by the CanvasBuffer class. + * + * @method PIXI.CanvasBuffer#clear + * @private + */ +PIXI.CanvasBuffer.prototype.clear = function() +{ + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0,0, this.width, this.height); +}; + +/** + * Resizes the canvas to the specified width and height. + * + * @method PIXI.CanvasBuffer#resize + * @param width {Number} the new width of the canvas + * @param height {Number} the new height of the canvas + */ +PIXI.CanvasBuffer.prototype.resize = function(width, height) +{ + this.width = this.canvas.width = width; + this.height = this.canvas.height = height; +}; + +/** + * Frees the canvas up for use again. + * + * @method PIXI.CanvasBuffer#destroy + */ +PIXI.CanvasBuffer.prototype.destroy = function() +{ + Phaser.CanvasPool.remove(this); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used to handle masking. + * + * @class PIXI.CanvasMaskManager + * @constructor + */ +PIXI.CanvasMaskManager = function() +{ +}; + +PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; + +/** + * This method adds it to the current stack of masks. + * + * @method PIXI.CanvasMaskManager#pushMask + * @param maskData {Object} the maskData that will be pushed + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) { + + var context = renderSession.context; + + context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.worldTransform; + + var resolution = renderSession.resolution; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution); + + PIXI.CanvasGraphics.renderGraphicsMask(maskData, context); + + context.clip(); + + maskData.worldAlpha = cacheAlpha; +}; + +/** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @method PIXI.CanvasMaskManager#popMask + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.popMask = function(renderSession) +{ + renderSession.context.restore(); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class PIXI.CanvasTinter + * @static + */ +PIXI.CanvasTinter = function() {}; + +/** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @method PIXI.CanvasTinter#getTintedTexture + * @static + * @param sprite {Sprite} the sprite to tint + * @param color {Number} the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ +PIXI.CanvasTinter.getTintedTexture = function(sprite, color) +{ + var canvas = sprite.tintedTexture || Phaser.CanvasPool.create(this); + + PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas); + + return canvas; +}; + +/** + * Tint a texture using the "multiply" operation. + * + * @method PIXI.CanvasTinter#tintWithMultiply + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.clearRect(0, 0, w, h); + + context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, w, h); + + context.globalCompositeOperation = "multiply"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + context.globalCompositeOperation = "destination-atop"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + +}; + +/** + * Tint a texture pixel per pixel. + * + * @method PIXI.CanvasTinter#tintPerPixel + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.globalCompositeOperation = "copy"; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + var rgbValues = Phaser.Color.hexToRGBArray(color); + var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, w, h); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) + { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + + if (!PIXI.CanvasTinter.canHandleAlpha) + { + var alpha = pixels[i + 3]; + + pixels[i + 0] /= 255 / alpha; + pixels[i + 1] /= 255 / alpha; + pixels[i + 2] /= 255 / alpha; + } + } + + context.putImageData(pixelData, 0, 0); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class PIXI.CanvasRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.CanvasRenderer = function (game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + /** + * The renderer type. + * + * @property type + * @type Number + */ + this.type = Phaser.CANVAS; + + /** + * The resolution of the canvas. + * + * @property resolution + * @type Number + */ + this.resolution = game.resolution; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. + * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame. + * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The width of the canvas view + * + * @property width + * @type Number + * @default 800 + */ + this.width = game.width * this.resolution; + + /** + * The height of the canvas view + * + * @property height + * @type Number + * @default 600 + */ + this.height = game.height * this.resolution; + + /** + * The canvas element that everything is drawn to. + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * The canvas 2d context that everything is drawn with + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.view.getContext("2d", { alpha: this.transparent } ); + + /** + * Boolean flag controlling canvas refresh. + * + * @property refresh + * @type Boolean + */ + this.refresh = true; + + /** + * Internal var. + * + * @property count + * @type Number + */ + this.count = 0; + + /** + * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer + * @property CanvasMaskManager + * @type CanvasMaskManager + */ + this.maskManager = new PIXI.CanvasMaskManager(); + + /** + * The render session is just a bunch of parameter used for rendering + * @property renderSession + * @type Object + */ + this.renderSession = { + context: this.context, + maskManager: this.maskManager, + scaleMode: null, + smoothProperty: Phaser.Canvas.getSmoothingPrefix(this.context), + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + */ + roundPixels: config.roundPixels || false + }; + + this.mapBlendModes(); + + this.resize(this.width, this.height); + +}; + +// constructor +PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer; + +/** + * Renders the DisplayObjectContainer, usually the Phaser.Stage, to this canvas view. + * + * @method PIXI.CanvasRenderer#render + * @param root {Phaser.Stage|PIXI.DisplayObjectContainer} The root element to be rendered. + */ +PIXI.CanvasRenderer.prototype.render = function (root) { + + this.context.setTransform(1, 0, 0, 1, 0, 0); + + this.context.globalAlpha = 1; + + this.renderSession.currentBlendMode = 0; + this.renderSession.shakeX = this.game.camera._shake.x; + this.renderSession.shakeY = this.game.camera._shake.y; + + this.context.globalCompositeOperation = 'source-over'; + + if (navigator.isCocoonJS && this.view.screencanvas) + { + this.context.fillStyle = "black"; + this.context.clear(); + } + + if (this.clearBeforeRender) + { + if (this.transparent) + { + this.context.clearRect(0, 0, this.width, this.height); + } + else if (root._bgColor) + { + this.context.fillStyle = root._bgColor.rgba; + this.context.fillRect(0, 0, this.width , this.height); + } + } + + this.renderDisplayObject(root); + +}; + +PIXI.CanvasRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + // Does nothing on Canvas, but here to allow you to simply set + // `game.renderer.setTexturePriority()` without having to worry about + // running in WebGL or not. + +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @method PIXI.CanvasRenderer#destroy + * @param [removeView=true] {boolean} Removes the Canvas element from the DOM. + */ +PIXI.CanvasRenderer.prototype.destroy = function (removeView) { + + if (removeView === undefined) { removeView = true; } + + if (removeView && this.view.parent) + { + this.view.parent.removeChild(this.view); + } + + this.view = null; + this.context = null; + this.maskManager = null; + this.renderSession = null; + +}; + +/** + * Resizes the canvas view to the specified width and height + * + * @method PIXI.CanvasRenderer#resize + * @param width {Number} the new width of the canvas view + * @param height {Number} the new height of the canvas view + */ +PIXI.CanvasRenderer.prototype.resize = function (width, height) { + + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) + { + this.view.style.width = this.width / this.resolution + "px"; + this.view.style.height = this.height / this.resolution + "px"; + } + + if (this.renderSession.smoothProperty) + { + this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + +}; + +/** + * Renders a display object + * + * @method PIXI.CanvasRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The displayObject to render + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. + * @private + */ +PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) { + + this.renderSession.context = context || this.context; + this.renderSession.resolution = this.resolution; + displayObject._renderCanvas(this.renderSession, matrix); + +}; + +/** + * Maps Pixi blend modes to canvas blend modes. + * + * @method PIXI.CanvasRenderer#mapBlendModes + * @private + */ +PIXI.CanvasRenderer.prototype.mapBlendModes = function () { + + if (!PIXI.blendModesCanvas) + { + var b = []; + var modes = PIXI.blendModes; + var useNew = this.game.device.canUseMultiply; + + b[modes.NORMAL] = 'source-over'; + b[modes.ADD] = 'lighter'; + b[modes.MULTIPLY] = (useNew) ? 'multiply' : 'source-over'; + b[modes.SCREEN] = (useNew) ? 'screen' : 'source-over'; + b[modes.OVERLAY] = (useNew) ? 'overlay' : 'source-over'; + b[modes.DARKEN] = (useNew) ? 'darken' : 'source-over'; + b[modes.LIGHTEN] = (useNew) ? 'lighten' : 'source-over'; + b[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : 'source-over'; + b[modes.COLOR_BURN] = (useNew) ? 'color-burn' : 'source-over'; + b[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : 'source-over'; + b[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : 'source-over'; + b[modes.DIFFERENCE] = (useNew) ? 'difference' : 'source-over'; + b[modes.EXCLUSION] = (useNew) ? 'exclusion' : 'source-over'; + b[modes.HUE] = (useNew) ? 'hue' : 'source-over'; + b[modes.SATURATION] = (useNew) ? 'saturation' : 'source-over'; + b[modes.COLOR] = (useNew) ? 'color' : 'source-over'; + b[modes.LUMINOSITY] = (useNew) ? 'luminosity' : 'source-over'; + + PIXI.blendModesCanvas = b; + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class PIXI.BaseTexture + * @constructor + * @param source {String|Canvas} the source object (image or canvas) + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + */ +PIXI.BaseTexture = function(source, scaleMode, resolution) +{ + /** + * The Resolution of the texture. + * + * @property resolution + * @type Number + */ + this.resolution = resolution || 1; + + /** + * [read-only] The width of the base texture set when the image has loaded + * + * @property width + * @type Number + * @readOnly + */ + this.width = 100; + + /** + * [read-only] The height of the base texture set when the image has loaded + * + * @property height + * @type Number + * @readOnly + */ + this.height = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @property scaleMode + * @type {Number} + * @default PIXI.scaleModes.LINEAR + */ + this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT; + + /** + * [read-only] Set to true once the base texture has loaded + * + * @property hasLoaded + * @type Boolean + * @readOnly + */ + this.hasLoaded = false; + + /** + * The image source that is used to create the texture. + * + * @property source + * @type Image + */ + this.source = source; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * + * @property premultipliedAlpha + * @type Boolean + * @default true + */ + this.premultipliedAlpha = true; + + // used for webGL + + /** + * @property _glTextures + * @type Array + * @private + */ + this._glTextures = []; + + /** + * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @property mipmap + * @type {Boolean} + */ + this.mipmap = false; + + /** + * The multi texture batching index number. + * @property textureIndex + * @type Number + */ + this.textureIndex = 0; + + /** + * @property _dirty + * @type Array + * @private + */ + this._dirty = [true, true, true, true]; + + if (!source) + { + return; + } + + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { + this.hasLoaded = true; + this.width = this.source.naturalWidth || this.source.width; + this.height = this.source.naturalHeight || this.source.height; + this.dirty(); + } + + /** + * A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch. + * + * You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture) + * that has children that you do want to render, without causing a batch flush in the process. + * + * @property skipRender + * @type Boolean + */ + this.skipRender = false; + + /** + * @property _powerOf2 + * @type Boolean + * @private + */ + this._powerOf2 = false; + +}; + +PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture; + +/** + * Forces this BaseTexture to be set as loaded, with the given width and height. + * Then calls BaseTexture.dirty. + * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have. + * + * @method PIXI.BaseTexture#forceLoaded + * @param {number} width - The new width to force the BaseTexture to be. + * @param {number} height - The new height to force the BaseTexture to be. + */ +PIXI.BaseTexture.prototype.forceLoaded = function(width, height) +{ + this.hasLoaded = true; + this.width = width; + this.height = height; + this.dirty(); +}; + +/** + * Destroys this base texture + * + * @method PIXI.BaseTexture#destroy + */ +PIXI.BaseTexture.prototype.destroy = function() +{ + if (this.source) + { + Phaser.CanvasPool.removeByCanvas(this.source); + } + + this.source = null; + + this.unloadFromGPU(); +}; + +/** + * Sets all glTextures to be dirty. + * + * @method PIXI.BaseTexture#dirty + */ +PIXI.BaseTexture.prototype.dirty = function() +{ + for (var i = 0; i < this._glTextures.length; i++) + { + this._dirty[i] = true; + } +}; + +/** + * Removes the base texture from the GPU, useful for managing resources on the GPU. + * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it. + * + * @method PIXI.BaseTexture#unloadFromGPU + */ +PIXI.BaseTexture.prototype.unloadFromGPU = function() +{ + this.dirty(); + + // delete the webGL textures if any. + for (var i = this._glTextures.length - 1; i >= 0; i--) + { + var glTexture = this._glTextures[i]; + var gl = PIXI.glContexts[i]; + + if(gl && glTexture) + { + gl.deleteTexture(glTexture); + } + + } + + this._glTextures.length = 0; + + this.dirty(); +}; + +/** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @method PIXI.BaseTexture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + * @return {BaseTexture} + */ +PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode, resolution) +{ + if (canvas.width === 0) + { + canvas.width = 1; + } + + if (canvas.height === 0) + { + canvas.height = 1; + } + + resolution = resolution || 1; + + return new PIXI.BaseTexture(canvas, scaleMode, resolution); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * TextureSilentFail is a boolean that defaults to `false`. + * If `true` then {@link PIXI.Texture#setFrame} will no longer throw an error if the texture dimensions are incorrect. + * Instead {@link PIXI.Texture#valid} will be set to `false` (#1556) + * + * @type {boolean} + */ +PIXI.TextureSilentFail = false; + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used. + * + * @class PIXI.Texture + * @constructor + * @param baseTexture {BaseTexture} The base texture source to create the texture from + * @param frame {Rectangle} The rectangle frame of the texture to show + * @param [crop] {Rectangle} The area of original texture + * @param [trim] {Rectangle} Trimmed texture rectangle + */ +PIXI.Texture = function(baseTexture, frame, crop, trim) +{ + /** + * Does this Texture have any frame data assigned to it? + * + * @property noFrame + * @type Boolean + */ + this.noFrame = false; + + if (!frame) + { + this.noFrame = true; + frame = new PIXI.Rectangle(0,0,1,1); + } + + if (baseTexture instanceof PIXI.Texture) + { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = baseTexture; + + /** + * The frame specifies the region of the base texture that this texture uses + * + * @property frame + * @type Rectangle + */ + this.frame = frame; + + /** + * The texture trim data. + * + * @property trim + * @type Rectangle + */ + this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @property valid + * @type Boolean + */ + this.valid = false; + + /** + * Is this a tiling texture? As used by the likes of a TilingSprite. + * + * @property isTiling + * @type Boolean + */ + this.isTiling = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @property requiresUpdate + * @type Boolean + */ + this.requiresUpdate = false; + + /** + * This will let a renderer know that a tinted parent has updated its texture. + * + * @property requiresReTint + * @type Boolean + */ + this.requiresReTint = false; + + /** + * The WebGL UV data cache. + * + * @property _uvs + * @type Object + * @private + */ + this._uvs = null; + + /** + * The width of the Texture in pixels. + * + * @property width + * @type Number + */ + this.width = 0; + + /** + * The height of the Texture in pixels. + * + * @property height + * @type Number + */ + this.height = 0; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @property crop + * @type Rectangle + */ + this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1); + + /** + * A flag that controls if this frame is rotated or not. + * Rotation allows you to use rotated frames in texture atlas packing, it has nothing to do with + * Sprite rotation. + * + * @property rotated + * @type Boolean + */ + this.rotated = false; + + if (baseTexture.hasLoaded) + { + if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + this.setFrame(frame); + } + +}; + +PIXI.Texture.prototype.constructor = PIXI.Texture; + +/** + * Called when the base texture is loaded + * + * @method PIXI.Texture#onBaseTextureLoaded + * @private + */ +PIXI.Texture.prototype.onBaseTextureLoaded = function() +{ + var baseTexture = this.baseTexture; + + if (this.noFrame) + { + this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } + + this.setFrame(this.frame); +}; + +/** + * Destroys this texture + * + * @method PIXI.Texture#destroy + * @param destroyBase {Boolean} Whether to destroy the base texture as well + */ +PIXI.Texture.prototype.destroy = function(destroyBase) +{ + if (destroyBase) this.baseTexture.destroy(); + + this.valid = false; +}; + +/** + * Specifies the region of the baseTexture that this texture will use. + * + * @method PIXI.Texture#setFrame + * @param frame {Rectangle} The frame of the texture to set it to + */ +PIXI.Texture.prototype.setFrame = function(frame) +{ + this.noFrame = false; + + this.frame = frame; + this.width = frame.width; + this.height = frame.height; + + this.crop.x = frame.x; + this.crop.y = frame.y; + this.crop.width = frame.width; + this.crop.height = frame.height; + + if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { + if (!PIXI.TextureSilentFail) + { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + this.valid = false; + return; + } + + this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + + if (this.trim) + { + this.width = this.trim.width; + this.height = this.trim.height; + this.frame.width = this.trim.width; + this.frame.height = this.trim.height; + } + + if (this.valid) this._updateUvs(); + +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvs + * @private + */ +PIXI.Texture.prototype._updateUvs = function() +{ + if(!this._uvs)this._uvs = new PIXI.TextureUvs(); + + var frame = this.crop; + 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; +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvsInverted + * @private + */ +PIXI.Texture.prototype._updateUvsInverted = function () { + + if (!this._uvs) { this._uvs = new PIXI.TextureUvs(); } + + var frame = this.crop; + 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.height) / tw; + this._uvs.y1 = frame.y / th; + + this._uvs.x2 = (frame.x + frame.height) / tw; + this._uvs.y2 = (frame.y + frame.width) / th; + + this._uvs.x3 = frame.x / tw; + this._uvs.y3 = (frame.y + frame.width) / th; + +}; + +/** + * Helper function that creates a new a Texture based on the given canvas element. + * + * @static + * @method PIXI.Texture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @return {Texture} + */ +PIXI.Texture.fromCanvas = function(canvas, scaleMode) +{ + var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode); + + return new PIXI.Texture(baseTexture); +}; + +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.y3 = 0; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = PIXI; + } + exports.PIXI = PIXI; + } else if (typeof define !== 'undefined' && define.amd) { + define('PIXI', (function() { return root.PIXI = PIXI; })() ); + } else { + root.PIXI = PIXI; + } + + return PIXI; +}).call(this); +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +(function(){ + + var root = this; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @namespace Phaser +*/ +var Phaser = Phaser || { // jshint ignore:line + + /** + * The Phaser version number. + * @constant Phaser.VERSION + * @type {string} + */ + VERSION: '2.10.0', + + /** + * An array of Phaser game instances. + * @constant Phaser.GAMES + * @type {array} + */ + GAMES: [], + + /** + * AUTO renderer - picks between WebGL or Canvas based on device. + * @constant Phaser.AUTO + * @type {integer} + */ + AUTO: 0, + + /** + * Canvas Renderer. + * @constant Phaser.CANVAS + * @type {integer} + */ + CANVAS: 1, + + /** + * WebGL Renderer. + * @constant Phaser.WEBGL + * @type {integer} + */ + WEBGL: 2, + + /** + * Headless renderer (not visual output) + * @constant Phaser.HEADLESS + * @type {integer} + */ + HEADLESS: 3, + + /** + * WebGL Renderer with MultiTexture support enabled. + * @constant Phaser.WEBGL_MULTI + * @type {integer} + */ + WEBGL_MULTI: 4, + + /** + * Direction constant. + * @constant Phaser.NONE + * @type {integer} + */ + NONE: 0, + + /** + * Direction constant. + * @constant Phaser.LEFT + * @type {integer} + */ + LEFT: 1, + + /** + * Direction constant. + * @constant Phaser.RIGHT + * @type {integer} + */ + RIGHT: 2, + + /** + * Direction constant. + * @constant Phaser.UP + * @type {integer} + */ + UP: 3, + + /** + * Direction constant. + * @constant Phaser.DOWN + * @type {integer} + */ + DOWN: 4, + + /** + * Game Object type. + * @constant Phaser.SPRITE + * @type {integer} + */ + SPRITE: 0, + + /** + * Game Object type. + * @constant Phaser.BUTTON + * @type {integer} + */ + BUTTON: 1, + + /** + * Game Object type. + * @constant Phaser.IMAGE + * @type {integer} + */ + IMAGE: 2, + + /** + * Game Object type. + * @constant Phaser.GRAPHICS + * @type {integer} + */ + GRAPHICS: 3, + + /** + * Game Object type. + * @constant Phaser.TEXT + * @type {integer} + */ + TEXT: 4, + + /** + * Game Object type. + * @constant Phaser.TILESPRITE + * @type {integer} + */ + TILESPRITE: 5, + + /** + * Game Object type. + * @constant Phaser.BITMAPTEXT + * @type {integer} + */ + BITMAPTEXT: 6, + + /** + * Game Object type. + * @constant Phaser.GROUP + * @type {integer} + */ + GROUP: 7, + + /** + * Game Object type. + * @constant Phaser.RENDERTEXTURE + * @type {integer} + */ + RENDERTEXTURE: 8, + + /** + * Game Object type. + * @constant Phaser.TILEMAP + * @type {integer} + */ + TILEMAP: 9, + + /** + * Game Object type. + * @constant Phaser.TILEMAPLAYER + * @type {integer} + */ + TILEMAPLAYER: 10, + + /** + * Game Object type. + * @constant Phaser.EMITTER + * @type {integer} + */ + EMITTER: 11, + + /** + * Game Object type. + * @constant Phaser.POLYGON + * @type {integer} + */ + POLYGON: 12, + + /** + * Game Object type. + * @constant Phaser.BITMAPDATA + * @type {integer} + */ + BITMAPDATA: 13, + + /** + * Game Object type. + * @constant Phaser.CANVAS_FILTER + * @type {integer} + */ + CANVAS_FILTER: 14, + + /** + * Game Object type. + * @constant Phaser.WEBGL_FILTER + * @type {integer} + */ + WEBGL_FILTER: 15, + + /** + * Game Object type. + * @constant Phaser.ELLIPSE + * @type {integer} + */ + ELLIPSE: 16, + + /** + * Game Object type. + * @constant Phaser.SPRITEBATCH + * @type {integer} + */ + SPRITEBATCH: 17, + + /** + * Game Object type. + * @constant Phaser.RETROFONT + * @type {integer} + */ + RETROFONT: 18, + + /** + * Game Object type. + * @constant Phaser.POINTER + * @type {integer} + */ + POINTER: 19, + + /** + * Game Object type. + * @constant Phaser.ROPE + * @type {integer} + */ + ROPE: 20, + + /** + * Game Object type. + * @constant Phaser.CIRCLE + * @type {integer} + */ + CIRCLE: 21, + + /** + * Game Object type. + * @constant Phaser.RECTANGLE + * @type {integer} + */ + RECTANGLE: 22, + + /** + * Game Object type. + * @constant Phaser.LINE + * @type {integer} + */ + LINE: 23, + + /** + * Game Object type. + * @constant Phaser.MATRIX + * @type {integer} + */ + MATRIX: 24, + + /** + * Game Object type. + * @constant Phaser.POINT + * @type {integer} + */ + POINT: 25, + + /** + * Game Object type. + * @constant Phaser.ROUNDEDRECTANGLE + * @type {integer} + */ + ROUNDEDRECTANGLE: 26, + + /** + * Game Object type. + * @constant Phaser.CREATURE + * @type {integer} + */ + CREATURE: 27, + + /** + * Game Object type. + * @constant Phaser.VIDEO + * @type {integer} + */ + VIDEO: 28, + + /** + * Game Object type. + * @constant Phaser.PENDING_ATLAS + * @type {integer} + */ + PENDING_ATLAS: -1, + + /** + * A horizontal orientation + * @constant Phaser.HORIZONTAL + * @type {integer} + */ + HORIZONTAL: 0, + + /** + * A vertical orientation + * @constant Phaser.VERTICAL + * @type {integer} + */ + VERTICAL: 1, + + /** + * A landscape orientation + * @constant Phaser.LANDSCAPE + * @type {integer} + */ + LANDSCAPE: 0, + + /** + * A portrait orientation + * @constant Phaser.PORTRAIT + * @type {integer} + */ + PORTRAIT: 1, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face up. + * @constant Phaser.ANGLE_UP + * @type {integer} + */ + ANGLE_UP: 270, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face down. + * @constant Phaser.ANGLE_DOWN + * @type {integer} + */ + ANGLE_DOWN: 90, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face left. + * @constant Phaser.ANGLE_LEFT + * @type {integer} + */ + ANGLE_LEFT: 180, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face right. + * @constant Phaser.ANGLE_RIGHT + * @type {integer} + */ + ANGLE_RIGHT: 0, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north east. + * @constant Phaser.ANGLE_NORTH_EAST + * @type {integer} + */ + ANGLE_NORTH_EAST: 315, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north west. + * @constant Phaser.ANGLE_NORTH_WEST + * @type {integer} + */ + ANGLE_NORTH_WEST: 225, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south east. + * @constant Phaser.ANGLE_SOUTH_EAST + * @type {integer} + */ + ANGLE_SOUTH_EAST: 45, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south west. + * @constant Phaser.ANGLE_SOUTH_WEST + * @type {integer} + */ + ANGLE_SOUTH_WEST: 135, + + /** + * A constant representing a top-left alignment or position. + * @constant Phaser.TOP_LEFT + * @type {integer} + */ + TOP_LEFT: 0, + + /** + * A constant representing a top-center alignment or position. + * @constant Phaser.TOP_CENTER + * @type {integer} + */ + TOP_CENTER: 1, + + /** + * A constant representing a top-right alignment or position. + * @constant Phaser.TOP_RIGHT + * @type {integer} + */ + TOP_RIGHT: 2, + + /** + * A constant representing a left-top alignment or position. + * @constant Phaser.Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_TOP: 3, + + /** + * A constant representing a left-center alignment or position. + * @constant Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_CENTER: 4, + + /** + * A constant representing a left-bottom alignment or position. + * @constant Phaser.LEFT_BOTTOM + * @type {integer} + */ + LEFT_BOTTOM: 5, + + /** + * A constant representing a center alignment or position. + * @constant Phaser.CENTER + * @type {integer} + */ + CENTER: 6, + + /** + * A constant representing a right-top alignment or position. + * @constant Phaser.RIGHT_TOP + * @type {integer} + */ + RIGHT_TOP: 7, + + /** + * A constant representing a right-center alignment or position. + * @constant Phaser.RIGHT_CENTER + * @type {integer} + */ + RIGHT_CENTER: 8, + + /** + * A constant representing a right-bottom alignment or position. + * @constant Phaser.RIGHT_BOTTOM + * @type {integer} + */ + RIGHT_BOTTOM: 9, + + /** + * A constant representing a bottom-left alignment or position. + * @constant Phaser.BOTTOM_LEFT + * @type {integer} + */ + BOTTOM_LEFT: 10, + + /** + * A constant representing a bottom-center alignment or position. + * @constant Phaser.BOTTOM_CENTER + * @type {integer} + */ + BOTTOM_CENTER: 11, + + /** + * A constant representing a bottom-right alignment or position. + * @constant Phaser.BOTTOM_RIGHT + * @type {integer} + */ + BOTTOM_RIGHT: 12, + + /** + * Various blend modes supported by Pixi. See the samples in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing Canvas Tutorial: Compositing}. + * + * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * + * @constant {Object} Phaser.blendModes + * @property {Number} blendModes.NORMAL - Draws new shapes on top of the existing content. This is the default setting. + * @property {Number} blendModes.ADD - Where both shapes overlap the color is determined by adding color values. + * @property {Number} blendModes.MULTIPLY - The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer, making a darker picture. + * @property {Number} blendModes.SCREEN - The pixels are inverted, multiplied, and inverted again, making a lighter picture. + * @property {Number} blendModes.OVERLAY + * @property {Number} blendModes.DARKEN + * @property {Number} blendModes.LIGHTEN + * @property {Number} blendModes.COLOR_DODGE + * @property {Number} blendModes.COLOR_BURN + * @property {Number} blendModes.HARD_LIGHT + * @property {Number} blendModes.SOFT_LIGHT + * @property {Number} blendModes.DIFFERENCE + * @property {Number} blendModes.EXCLUSION + * @property {Number} blendModes.HUE + * @property {Number} blendModes.SATURATION + * @property {Number} blendModes.COLOR + * @property {Number} blendModes.LUMINOSITY + * @static + */ + 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 + }, + + /** + * The scale modes that are supported by Pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @constant {Object} Phaser.scaleModes + * @property {Number} Phaser.scaleModes.DEFAULT=LINEAR + * @property {Number} Phaser.scaleModes.LINEAR Smooth scaling + * @property {Number} Phaser.scaleModes.NEAREST Pixelating scaling + * @static + */ + scaleModes: { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 + }, + + PIXI: PIXI || {}, + + // Used to create IDs for various Pixi objects. + _UID: 0 + +}; + +/** +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc +if (!Math.trunc) { + Math.trunc = function trunc(x) { + return x < 0 ? Math.ceil(x) : Math.floor(x); + }; +} + +/** +* A polyfill for Function.prototype.bind +*/ +if (!Function.prototype.bind) { + + /* jshint freeze: false */ + 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)) + { + /* jshint supernew: true */ + return new F; + } + })(target.prototype); + + return bound; + }; + })(); +} + +/** +* A polyfill for Array.isArray +*/ +if (!Array.isArray) +{ + Array.isArray = function (arg) + { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + +/** +* A polyfill for Array.forEach +* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach +*/ +if (!Array.prototype.forEach) +{ + Array.prototype.forEach = function(fun /*, thisArg */) + { + "use strict"; + + if (this === void 0 || this === null) + { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + if (typeof fun !== "function") + { + throw new TypeError(); + } + + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + + for (var i = 0; i < len; i++) + { + if (i in t) + { + fun.call(thisArg, t[i], i, t); + } + } + }; +} + +/** +* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 +* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ +* Cameron Foale (http://www.kibibu.com) +*/ +if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object") +{ + var CheapArray = function(type) + { + var proto = new Array(); // jshint ignore:line + + window[type] = function(arg) { + + if (typeof(arg) === "number") + { + Array.call(this, arg); + this.length = arg; + + for (var i = 0; i < this.length; i++) + { + this[i] = 0; + } + } + else + { + Array.call(this, arg.length); + + this.length = arg.length; + + for (var i = 0; i < this.length; i++) + { + this[i] = arg[i]; + } + } + }; + + window[type].prototype = proto; + window[type].constructor = window[type]; + }; + + CheapArray('Float32Array'); // jshint ignore:line + CheapArray('Uint32Array'); // jshint ignore:line + CheapArray('Uint16Array'); // jshint ignore:line + CheapArray('Int16Array'); // jshint ignore:line + CheapArray('ArrayBuffer'); // jshint ignore:line +} + +/** + * Also fix for the absent console in IE9 + */ +if (!window.console) +{ + window.console = {}; + window.console.log = window.console.assert = function(){}; + window.console.warn = window.console.assert = function(){}; +} + +/** + * Fix for Object.assign not existing on older devices + */ + +if (!Object.assign) { + /* jshint -W098 */ + // We include `varArgs` (unused) to ensure Object.assign.length === 2 + Object.assign = function(target, varArgs) { + /* jshint +W098 */ + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + var hasOwn = Object.prototype.hasOwnProperty; + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (hasOwn.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @class Phaser.Utils +* @static +*/ +Phaser.Utils = { + + /** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @method Phaser.Utils.reverseString + * @param {string} string - The string to be reversed. + * @return {string} The reversed string. + */ + reverseString: function (string) { + + return string.split('').reverse().join(''); + + }, + + /** + * Gets an object's property by string. + * + * @method Phaser.Utils.getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + getProperty: function(obj, name) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + return obj[name]; + case 2: + return obj[parts[0]][parts[1]]; + case 3: + return obj[parts[0]][parts[1]][parts[2]]; + case 4: + return obj[parts[0]][parts[1]][parts[2]][parts[3]]; + default: + return this._getProperty(obj, name); + } + + }, + + /** + * Sets an object's properties from a map of property names and values. + * + * ```javascript + * Phaser.Utils.setProperties(sprite, { + * 'animations.paused': true, + * 'body.enable': false, + * 'input.draggable': true, + * }); + * ``` + * + * @method Phaser.Utils.setProperties + * @param {object} obj - The object to modify. + * @param {object} props - The property names and values to set on the object (see {@link #setProperty}). + * @return {object} The modified object. + */ + setProperties: function(obj, props) { + + for (var name in props) + { + this.setProperty(obj, name, props[name]); + } + + return obj; + + }, + + /** + * Sets an object's property by name and value. + * + * ```javascript + * Phaser.Utils.setProperty(sprite, 'body.velocity.x', 60); + * ``` + * + * @method Phaser.Utils.setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + + setProperty: function(obj, name, value) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + obj[name] = value; + break; + case 2: + obj[parts[0]][parts[1]] = value; + break; + case 3: + obj[parts[0]][parts[1]][parts[2]] = value; + break; + case 4: + obj[parts[0]][parts[1]][parts[2]][parts[3]] = value; + break; + default: + this._setProperty(obj, name, value); + } + }, + + /** + * Gets an object's property by string. + * + * @private + * @method Phaser.Utils._getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property whose value will be returned. + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + _getProperty: function(obj, name) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + val = obj; + + while (i < len) + { + var key = parts[i]; + + if (val != null) + { + val = val[key]; + i++; + } + else + { + return undefined; + } + } + + return val; + + }, + + /** + * Sets an object's property by name and value. + * + * @private + * @method Phaser.Utils._setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + _setProperty: function(obj, name, value) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + currentObj = obj, + key = parts[0]; + + if (len === 1) + { + obj[name] = value; + } + else + { + while (i < (len - 1)) + { + currentObj = currentObj[key]; + i++; + key = parts[i]; + } + + currentObj[key] = value; + } + + return obj; + + }, + + /** + * Generate a random bool result based on the chance value. + * + * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance + * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. + * + * @method Phaser.Utils#chanceRoll + * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). + * @return {boolean} True if the roll passed, or false otherwise. + */ + chanceRoll: function (chance) { + if (chance === undefined) { chance = 50; } + return chance > 0 && (Math.random() * 100 <= chance); + }, + + /** + * Choose between one of two values randomly. + * + * @method Phaser.Utils#randomChoice + * @param {any} choice1 + * @param {any} choice2 + * @return {any} The randomly selected choice + */ + randomChoice: function (choice1, choice2) { + return (Math.random() < 0.5) ? choice1 : choice2; + }, + + /** + * Get a unit dimension from a string. + * + * @method Phaser.Utils.parseDimension + * @param {string|number} size - The size to parse. + * @param {number} dimension - The window dimension to check. + * @return {number} The parsed dimension. + */ + parseDimension: function (size, dimension) { + + var f = 0; + var px = 0; + + if (typeof size === 'string') + { + // %? + if (size.substr(-1) === '%') + { + f = parseInt(size, 10) / 100; + + if (dimension === 0) + { + px = window.innerWidth * f; + } + else + { + px = window.innerHeight * f; + } + } + else + { + px = parseInt(size, 10); + } + } + else + { + px = size; + } + + return px; + + }, + + /** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @method Phaser.Utils.pad + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * @return {string} The padded string. + */ + pad: function (str, len, pad, dir) { + + if (len === undefined) { var len = 0; } + if (pad === undefined) { var pad = ' '; } + if (dir === undefined) { var dir = 3; } + + str = str.toString(); + + 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; + + }, + + /** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * @method Phaser.Utils.isPlainObject + * @param {object} obj - The object to inspect. + * @return {boolean} - true if the object is plain, otherwise false. + */ + isPlainObject: function (obj) { + + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) + { + return false; + } + + // Support: Firefox <20 + // The try/catch suppresses exceptions thrown when attempting to access + // the "constructor" property of certain host objects, ie. |window.location| + // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + try { + if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) + { + return false; + } + } catch (e) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + /** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @method Phaser.Utils.extend + * @param {boolean} deep - Perform a deep copy? + * @param {object} target - The target object to copy to. + * @return {object} The extended object. + */ + extend: function () { + + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if (typeof target === "boolean") + { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } + + for (; i < length; i++) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) + { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = Phaser.Utils.extend(deep, clone, copy); + + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; + + }, + + /** + * Mixes in an existing mixin object with the target. + * + * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` + * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and + * the result is assigned directly. + * + * @method Phaser.Utils.mixinPrototype + * @param {object} target - The target object to receive the new functions. + * @param {object} mixin - The object to copy the functions from. + * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not? + */ + mixinPrototype: function (target, mixin, replace) { + + if (replace === undefined) { replace = false; } + + var mixinKeys = Object.keys(mixin); + + for (var i = 0; i < mixinKeys.length; i++) + { + var key = mixinKeys[i]; + var value = mixin[key]; + + if (!replace && (key in target)) + { + // Not overwriting existing property + continue; + } + else + { + if (value && + (typeof value.get === 'function' || typeof value.set === 'function')) + { + // Special case for classes like Phaser.Point which has a 'set' function! + if (typeof value.clone === 'function') + { + target[key] = value.clone(); + } + else + { + Object.defineProperty(target, key, value); + } + } + else + { + target[key] = value; + } + } + } + + }, + + /** + * Mixes the source object into the destination object, returning the newly modified destination object. + * Based on original code by @mudcube + * + * @method Phaser.Utils.mixin + * @param {object} from - The object to copy (the source object). + * @param {object} to - The object to copy to (the destination object). + * @return {object} The modified destination object. + */ + mixin: function (from, to) { + + if (!from || typeof (from) !== "object") + { + return to; + } + + for (var key in from) + { + var o = from[key]; + + if (o.childNodes || o.cloneNode) + { + continue; + } + + var type = typeof (from[key]); + + if (!from[key] || type !== "object") + { + to[key] = from[key]; + } + else + { + // Clone sub-object + if (typeof (to[key]) === type) + { + to[key] = Phaser.Utils.mixin(from[key], to[key]); + } + else + { + to[key] = Phaser.Utils.mixin(from[key], new o.constructor()); + } + } + } + + return to; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. +* If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. +* +* @class Phaser.Circle +* @constructor +* @param {number} [x=0] - The x coordinate of the center of the circle. +* @param {number} [y=0] - The y coordinate of the center of the circle. +* @param {number} [diameter=0] - The diameter of the circle. +*/ +Phaser.Circle = function (x, y, diameter) { + + x = x || 0; + y = y || 0; + diameter = diameter || 0; + + /** + * @property {number} x - The x coordinate of the center of the circle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the center of the circle. + */ + this.y = y; + + /** + * @property {number} _diameter - The diameter of the circle. + * @private + */ + this._diameter = diameter; + + /** + * @property {number} _radius - The radius of the circle. + * @private + */ + this._radius = 0; + + if (diameter > 0) + { + this._radius = diameter * 0.5; + } + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.CIRCLE; + +}; + +Phaser.Circle.prototype = { + + /** + * The circumference of the circle. + * + * @method Phaser.Circle#circumference + * @return {number} The circumference of the circle. + */ + circumference: function () { + + return 2 * (Math.PI * this._radius); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Circle. + * + * @method Phaser.Circle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = 2 * Math.PI * Math.random(); + var u = Math.random() + Math.random(); + var r = (u > 1) ? 2 - u : u; + var x = r * Math.cos(t); + var y = r * Math.sin(t); + + out.x = this.x + (x * this.radius); + out.y = this.y + (y * this.radius); + + return out; + + }, + + /** + * Returns the framing rectangle of the circle as a Phaser.Rectangle object. + * + * @method Phaser.Circle#getBounds + * @return {Phaser.Rectangle} The bounds of the Circle. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter); + + }, + + /** + * Sets the members of Circle to the specified values. + * @method Phaser.Circle#setTo + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} diameter - The diameter of the circle. + * @return {Circle} This circle object. + */ + setTo: function (x, y, diameter) { + + this.x = x; + this.y = y; + this._diameter = diameter; + this._radius = diameter * 0.5; + + return this; + + }, + + /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method Phaser.Circle#copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.diameter); + + }, + + /** + * Copies the x, y and diameter properties from this Circle to any given object. + * @method Phaser.Circle#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.diameter = this._diameter; + + return dest; + + }, + + /** + * Returns the distance from the center of the Circle object to the given object + * (can be Circle, Point or anything with x/y properties) + * @method Phaser.Circle#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round=false] - Round the distance to the nearest integer. + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y); + return round ? Math.round(distance) : distance; + + }, + + /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. + * @method Phaser.Circle#clone + * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} The cloned Circle object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Circle(this.x, this.y, this.diameter); + } + else + { + output.setTo(this.x, this.y, this.diameter); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Circle object. + * @method Phaser.Circle#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this circle, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Circle.contains(this, x, y); + + }, + + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method Phaser.Circle#circumferencePoint + * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ + circumferencePoint: function (angle, asDegrees, out) { + + return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out); + + }, + + + /** + * Creates or positions points on the circle. + * + * The points are equally distributed in the half-closed interval [startAngle, endAngle). The default arc is the entire circle. + * + * If the `out` argument is omitted, this method creates and returns an array of {@link Phaser.Point points}. If an array is passed as `out`, its items are treated as points and placed in the same way. + * + * @param {type} [steps=60] - The number of points to place. + * @param {type} [startAngle=0] - The starting angle in radians (unless asDegrees is true). + * @param {type} [endAngle=Phaser.Math.PI2] - The end angle in radians (unless asDegrees is true). + * @param {type} [asDegrees=false] - Are the given angles in radians (false) or degrees (true)? + * @param {any[]} [out] - An array of points or point-like objects (e.g., sprites). It should start at index 0 and its length should be equal to or greater than `steps`. + * @return {any[]} - The modified `out` argument or a new array of points. + */ + sample: function (steps, startAngle, endAngle, asDegrees, out) { + + if (!steps) { steps = 60; } + if (startAngle == null) { startAngle = 0; } + if (endAngle == null) { endAngle = Phaser.Math.PI2; } + if (!out) { out = []; } + + var i = 0; + + while (i < steps) + { + this.circumferencePoint( + Phaser.Math.linear(startAngle, endAngle, i / steps), + asDegrees, + out[i] || (out[i] = new Phaser.Point()) + ); + + i += 1; + } + + return out; + + }, + + /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method Phaser.Circle#offset + * @param {number} dx - Moves the x value of the Circle object by this amount. + * @param {number} dy - Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Circle#offsetPoint + * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). + * @return {Circle} This Circle object. + */ + offsetPoint: function (point) { + return this.offset(point.x, point.y); + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Circle#toString + * @return {string} a string representation of the instance. + */ + toString: function () { + return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; + } + +}; + +Phaser.Circle.prototype.constructor = Phaser.Circle; + +/** +* The largest distance between any two points on the circle. The same as the radius * 2. +* +* @name Phaser.Circle#diameter +* @property {number} diameter - Gets or sets the diameter of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "diameter", { + + get: function () { + return this._diameter; + }, + + set: function (value) { + + if (value > 0) + { + this._diameter = value; + this._radius = value * 0.5; + } + } + +}); + +/** +* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. +* @name Phaser.Circle#radius +* @property {number} radius - Gets or sets the radius of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "radius", { + + get: function () { + return this._radius; + }, + + set: function (value) { + + if (value > 0) + { + this._radius = value; + this._diameter = value * 2; + } + + } + +}); + +/** +* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#left +* @propety {number} left - Gets or sets the value of the leftmost point of the circle. +*/ +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; + } + + } + +}); + +/** +* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#right +* @property {number} right - Gets or sets the value of the rightmost point of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "right", { + + get: function () { + return this.x + this._radius; + }, + + set: function (value) { + + if (value < this.x) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.x; + } + + } + +}); + +/** +* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#top +* @property {number} top - Gets or sets the top of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "top", { + + get: function () { + return this.y - this._radius; + }, + + set: function (value) { + + if (value > this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = this.y - value; + } + + } + +}); + +/** +* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#bottom +* @property {number} bottom - Gets or sets the bottom of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "bottom", { + + get: function () { + return this.y + this._radius; + }, + + set: function (value) { + + if (value < this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.y; + } + + } + +}); + +/** +* The area of this Circle. +* @name Phaser.Circle#area +* @property {number} area - The area of this circle. +* @readonly +*/ +Object.defineProperty(Phaser.Circle.prototype, "area", { + + get: function () { + + if (this._radius > 0) + { + return Math.PI * this._radius * this._radius; + } + else + { + return 0; + } + + } + +}); + +/** +* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. +* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. +* @name Phaser.Circle#empty +* @property {boolean} empty - Gets or sets the empty state of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "empty", { + + get: function () { + return (this._diameter === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Circle object. +* @method Phaser.Circle.contains +* @param {Phaser.Circle} a - The Circle to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this circle, otherwise false. +*/ +Phaser.Circle.contains = function (a, x, y) { + + // Check if x/y are within the bounds first + 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; + } + +}; + +/** +* Determines whether the two Circle objects match. This method compares the x, y and diameter properties. +* @method Phaser.Circle.equals +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. +*/ +Phaser.Circle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.diameter === b.diameter); + +}; + +/** +* Determines whether the two Circle objects intersect. +* This method checks the radius distances between the two Circle objects to see if they intersect. +* @method Phaser.Circle.intersects +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. +*/ +Phaser.Circle.intersects = function (a, b) { + + return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius)); + +}; + +/** +* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. +* @method Phaser.Circle.circumferencePoint +* @param {Phaser.Circle} a - The first Circle object. +* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. +* @return {Phaser.Point} The Point object holding the result. +*/ +Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) { + + if (asDegrees === undefined) { asDegrees = false; } + if (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; + +}; + +/** +* Checks if the given Circle and Rectangle objects intersect. +* @method Phaser.Circle.intersectsRectangle +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Rectangle} r - The Rectangle object to test. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +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; + +}; + +/** +* Checks if the given Circle and Line objects intersect. +* @method Phaser.Circle.intersectsLine +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnpoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Circle.intersectsLine = function (c, l, returnPoints) { + var h = c.x; + var k = c.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = c.radius; + var b = c.radius; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Circle = Phaser.Circle; + +/** +* @author Richard Davey +* @author Chad Engler +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a Ellipse object. A curve on a plane surrounding two focal points. +* +* @class Phaser.Ellipse +* @constructor +* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [width=0] - The overall width of this ellipse. +* @param {number} [height=0] - The overall height of this ellipse. +*/ +Phaser.Ellipse = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.x = x; + + /** + * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.y = y; + + /** + * @property {number} width - The overall width of this ellipse. + */ + this.width = width; + + /** + * @property {number} height - The overall height of this ellipse. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ELLIPSE; + +}; + +Phaser.Ellipse.prototype = { + + /** + * Sets the members of the Ellipse to the specified values. + * @method Phaser.Ellipse#setTo + * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} width - The overall width of this ellipse. + * @param {number} height - The overall height of this ellipse. + * @return {Phaser.Ellipse} This Ellipse object. + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. + * + * @method Phaser.Ellipse#getBounds + * @return {Phaser.Rectangle} The bounds of the Ellipse. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Ellipse. + * + * @method Phaser.Ellipse#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Ellipse} This Ellipse object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Ellipse to any given object. + * @method Phaser.Ellipse#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function(dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. + * @method Phaser.Ellipse#clone + * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. + * @return {Phaser.Ellipse} The cloned Ellipse object. + */ + clone: function(output) { + + if (output === undefined || output === null) + { + output = new Phaser.Ellipse(this.x, this.y, this.width, this.height); + } + else + { + output.setTo(this.x, this.y, this.width, this.height); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Ellipse object. + * + * @method Phaser.Ellipse#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this ellipse, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Ellipse.contains(this, x, y); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Ellipse. + * + * @method Phaser.Ellipse#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var p = Math.random() * Math.PI * 2; + var r = Math.random(); + + out.x = Math.sqrt(r) * Math.cos(p); + out.y = Math.sqrt(r) * Math.sin(p); + + out.x = this.x + (out.x * this.width / 2.0); + out.y = this.y + (out.y * this.height / 2.0); + + return out; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Ellipse#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]"; + } + +}; + +Phaser.Ellipse.prototype.constructor = Phaser.Ellipse; + +/** +* The left coordinate of the Ellipse. The same as the X coordinate. +* @name Phaser.Ellipse#left +* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + + this.x = value; + + } + +}); + +/** +* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. +* @name Phaser.Ellipse#right +* @property {number} right - Gets or sets the value of the rightmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "right", { + + get: function () { + return this.x + this.width; + }, + + set: function (value) { + + if (value < this.x) + { + this.width = 0; + } + else + { + this.width = value - this.x; + } + } + +}); + +/** +* The top of the Ellipse. The same as its y property. +* @name Phaser.Ellipse#top +* @property {number} top - Gets or sets the top of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "top", { + + get: function () { + return this.y; + }, + + set: function (value) { + this.y = value; + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. +* @name Phaser.Ellipse#bottom +* @property {number} bottom - Gets or sets the bottom of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value < this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + } + +}); + +/** +* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. +* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. +* @name Phaser.Ellipse#empty +* @property {boolean} empty - Gets or sets the empty state of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "empty", { + + get: function () { + return (this.width === 0 || this.height === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Ellipse object. +* +* @method Phaser.Ellipse.contains +* @param {Phaser.Ellipse} a - The Ellipse to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this ellipse, otherwise false. +*/ +Phaser.Ellipse.contains = function (a, x, y) { + + if (a.width <= 0 || a.height <= 0) { + return false; + } + + // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 + var normx = ((x - a.x) / a.width) - 0.5; + var normy = ((y - a.y) / a.height) - 0.5; + + normx *= normx; + normy *= normy; + + return (normx + normy < 0.25); + +}; + +/** +* Checks if the given Ellipse and Line objects intersect. +* @method Phaser.Ellipse.intersectsLine +* @param {Phaser.Ellipse} e - The Ellipse object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnPoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Ellipse.intersectsLine = function (e, l, returnPoints) { + var h = e.x; + var k = e.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = e.width / 2; + var b = e.height / 2; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Ellipse = Phaser.Ellipse; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Line object with a start and an end point. +* +* @class Phaser.Line +* @constructor +* @param {number} [x1=0] - The x coordinate of the start of the line. +* @param {number} [y1=0] - The y coordinate of the start of the line. +* @param {number} [x2=0] - The x coordinate of the end of the line. +* @param {number} [y2=0] - The y coordinate of the end of the line. +*/ +Phaser.Line = function (x1, y1, x2, y2) { + + x1 = x1 || 0; + y1 = y1 || 0; + x2 = x2 || 0; + y2 = y2 || 0; + + /** + * @property {Phaser.Point} start - The start point of the line. + */ + this.start = new Phaser.Point(x1, y1); + + /** + * @property {Phaser.Point} end - The end point of the line. + */ + this.end = new Phaser.Point(x2, y2); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.LINE; + +}; + +Phaser.Line.prototype = { + + /** + * Sets the components of the Line to the specified values. + * + * @method Phaser.Line#setTo + * @param {number} [x1=0] - The x coordinate of the start of the line. + * @param {number} [y1=0] - The y coordinate of the start of the line. + * @param {number} [x2=0] - The x coordinate of the end of the line. + * @param {number} [y2=0] - The y coordinate of the end of the line. + * @return {Phaser.Line} This line object + */ + setTo: function (x1, y1, x2, y2) { + + this.start.setTo(x1, y1); + this.end.setTo(x2, y2); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given points. + * + * @param {any} start - A {@link Phaser.Point} or point-like object. + * @param {any} end - A {@link Phaser.Point} or point-like object. + * @return {Phaser.Line} - This line object. + */ + fromPoints: function (start, end) { + + this.setTo(start.x, start.y, end.x, end.y); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given sprites. + * Can optionally be calculated from their center coordinates. + * + * @method Phaser.Line#fromSprite + * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {boolean} [useCenter=false] - If true it will use startSprite.centerX, if false startSprite.x. + * @return {Phaser.Line} This line object + */ + fromSprite: function (startSprite, endSprite, useCenter) { + + if (useCenter === undefined) { useCenter = false; } + + if (useCenter) + { + return this.setTo(startSprite.centerX, startSprite.centerY, endSprite.centerX, endSprite.centerY); + } + + return this.fromPoints(startSprite, endSprite); + + }, + + /** + * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. + * + * @method Phaser.Line#fromAngle + * @param {number} x - The x coordinate of the start of the line. + * @param {number} y - The y coordinate of the start of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line in pixels. + * @return {Phaser.Line} This line object + */ + fromAngle: function (x, y, angle, length) { + + this.start.setTo(x, y); + this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length)); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place from the center of the line. + * If you wish to rotate around a different point see Line.rotateAround. + * + * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. + * + * @method Phaser.Line#rotate + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotate: function (angle, asDegrees) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + this.start.rotate(cx, cy, angle, asDegrees); + this.end.rotate(cx, cy, angle, asDegrees); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place around the coordinates given. + * + * @method Phaser.Line#rotateAround + * @param {number} x - The x coordinate to offset the rotation from. + * @param {number} y - The y coordinate to offset the rotation from. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotateAround: function (x, y, angle, asDegrees) { + + this.start.rotate(x, y, angle, asDegrees); + this.end.rotate(x, y, angle, asDegrees); + + return this; + + }, + + /** + * Checks for intersection between this line and another Line. + * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * + * @method Phaser.Line#intersects + * @param {Phaser.Line} line - The line to check against this one. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ + intersects: function (line, asSegment, result) { + + return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result); + + }, + + /** + * Returns the reflected angle between two lines. + * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. + * + * @method Phaser.Line#reflect + * @param {Phaser.Line} line - The line to reflect off this line. + * @return {number} The reflected angle in radians. + */ + reflect: function (line) { + + return Phaser.Line.reflect(this, line); + + }, + + /** + * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. + * + * @method Phaser.Line#midPoint + * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. + * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. + */ + midPoint: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = (this.start.x + this.end.x) / 2; + out.y = (this.start.y + this.end.y) / 2; + + return out; + + }, + + /** + * Centers this Line on the given coordinates. + * + * The line is centered by positioning the start and end points so that the lines midpoint matches + * the coordinates given. + * + * @method Phaser.Line#centerOn + * @param {number} x - The x position to center the line on. + * @param {number} y - The y position to center the line on. + * @return {Phaser.Line} This line object + */ + centerOn: function (x, y) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + var tx = x - cx; + var ty = y - cy; + + this.start.add(tx, ty); + this.end.add(tx, ty); + + }, + + /** + * Tests if the given coordinates fall on this line. See {@link #pointOnSegment} to test against just the line segment. + * + * @method Phaser.Line#pointOnLine + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line, false if not. + */ + pointOnLine: function (x, y, epsilon) { + + return Phaser.Math.fuzzyEqual((x - this.start.x) * (this.end.y - this.start.y), (this.end.x - this.start.x) * (y - this.start.y), epsilon || 0); + + }, + + /** + * Tests if the given coordinates fall on this line and within the segment. See {@link #pointOnLine} to test against just the line. + * + * @method Phaser.Line#pointOnSegment + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line and segment, false if not. + */ + pointOnSegment: function (x, y, epsilon) { + + var xMin = Math.min(this.start.x, this.end.x); + var xMax = Math.max(this.start.x, this.end.x); + var yMin = Math.min(this.start.y, this.end.y); + var yMax = Math.max(this.start.y, this.end.y); + + return (this.pointOnLine(x, y, epsilon) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)); + + }, + + /** + * Picks a random point from anywhere on the Line segment and returns it. + * + * @method Phaser.Line#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = Math.random(); + + out.x = this.start.x + t * (this.end.x - this.start.x); + out.y = this.start.y + t * (this.end.y - this.start.y); + + return out; + + }, + + /** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * The start and end points are rounded before this runs as the algorithm works on integers. + * + * @method Phaser.Line#coordinatesOnLine + * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. + * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. + * @return {array} An array of coordinates. + */ + coordinatesOnLine: function (stepRate, results) { + + if (stepRate === undefined) { stepRate = 1; } + if (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 < x2) ? 1 : -1; + var sy = (y1 < y2) ? 1 : -1; + var err = dx - dy; + + results.push([x1, y1]); + + var i = 1; + + while (!((x1 === x2) && (y1 === y2))) + { + var e2 = err << 1; + + if (e2 > -dy) + { + err -= dy; + x1 += sx; + } + + if (e2 < dx) + { + err += dx; + y1 += sy; + } + + if (i % stepRate === 0) + { + results.push([x1, y1]); + } + + i++; + + } + + return results; + + }, + + /** + * Returns a new Line object with the same values for the start and end properties as this Line object. + * @method Phaser.Line#clone + * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned. + * @return {Phaser.Line} The cloned Line object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y); + } + else + { + output.setTo(this.start.x, this.start.y, this.end.x, this.end.y); + } + + return output; + + } + +}; + +/** +* @name Phaser.Line#length +* @property {number} length - Gets the length of the line segment. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "length", { + + get: function () { + return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#angle +* @property {number} angle - Gets the angle of the line in radians. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "angle", { + + get: function () { + return Phaser.Point.angle(this.end, this.start); + } + +}); + +/** +* @name Phaser.Line#slope +* @property {number} slope - Gets the slope of the line (y/x). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "slope", { + + get: function () { + return (this.end.y - this.start.y) / (this.end.x - this.start.x); + } + +}); + +/** +* @name Phaser.Line#perpSlope +* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "perpSlope", { + + get: function () { + return -((this.end.x - this.start.x) / (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#x +* @property {number} x - Gets the x coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "x", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#y +* @property {number} y - Gets the y coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "y", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#left +* @property {number} left - Gets the left-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "left", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#right +* @property {number} right - Gets the right-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "right", { + + get: function () { + return Math.max(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#top +* @property {number} top - Gets the top-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "top", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#bottom +* @property {number} bottom - Gets the bottom-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "bottom", { + + get: function () { + return Math.max(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#width +* @property {number} width - Gets the width of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "width", { + + get: function () { + return Math.abs(this.start.x - this.end.x); + } + +}); + +/** +* @name Phaser.Line#height +* @property {number} height - Gets the height of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "height", { + + get: function () { + return Math.abs(this.start.y - this.end.y); + } + +}); + +/** +* @name Phaser.Line#normalX +* @property {number} normalX - Gets the x component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalX", { + + get: function () { + return Math.cos(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalY +* @property {number} normalY - Gets the y component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalY", { + + get: function () { + return Math.sin(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalAngle +* @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalAngle", { + + get: function () { + return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI); + } + +}); + +/** +* Checks for intersection between two lines as defined by the given start and end points. +* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersectsPoints +* @param {Phaser.Point} a - The start of the first Line to be checked. +* @param {Phaser.Point} b - The end of the first line to be checked. +* @param {Phaser.Point} e - The start of the second Line to be checked. +* @param {Phaser.Point} f - The end of the second line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) { + + if (asSegment === undefined) { asSegment = true; } + if (result === undefined) { result = new Phaser.Point(); } + + var a1 = b.y - a.y; + var a2 = f.y - e.y; + var b1 = a.x - b.x; + var b2 = e.x - f.x; + var c1 = (b.x * a.y) - (a.x * b.y); + var c2 = (f.x * e.y) - (e.x * f.y); + var denom = (a1 * b2) - (a2 * b1); + + if (denom === 0) + { + return null; + } + + result.x = ((b1 * c2) - (b2 * c1)) / denom; + result.y = ((a2 * c1) - (a1 * c2)) / denom; + + if (asSegment) + { + var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y)); + var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc; + var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc; + + if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) + { + return result; + } + else + { + return null; + } + } + + return result; + +}; + +/** +* Checks for intersection between two lines. +* If asSegment is true it will check for segment intersection. +* If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersects +* @param {Phaser.Line} a - The first Line to be checked. +* @param {Phaser.Line} b - The second Line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersects = function (a, b, asSegment, result) { + + return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result); + +}; + +/** +* Checks for intersection between the Line and a Rectangle shape, or a rectangle-like +* object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. +* +* An intersection is considered valid if: +* +* The line starts within or ends within the rectangle; or +* The line segment intersects one of the 4 rectangle edges; and +* The line has a non-zero length; and +* The rectangle is not empty. +* +* For the purposes of this function rectangles are considered 'solid'. +* +* @method Phaser.Line.intersectsRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle. +*/ +Phaser.Line.intersectsRectangle = function (line, rect) { + + // Quick bail out + if (line.length === 0 || rect.empty) + { + return false; + } + + var x1 = line.start.x; + var y1 = line.start.y; + + var x2 = line.end.x; + var y2 = line.end.y; + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + + var t = 0; + + // If the start or end of the line is inside the rect then we assume + // collision, as rects are solid for our use-case. + + if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || + (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) + { + return true; + } + + if (x1 < bx1 && x2 >= bx1) + { + // Left edge + t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); + + if (t > by1 && t <= by2) + { + return true; + } + } + else if (x1 > bx2 && x2 <= bx2) + { + // Right edge + t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); + + if (t >= by1 && t <= by2) + { + return true; + } + } + + if (y1 < by1 && y2 >= by1) + { + // Top edge + t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + else if (y1 > by2 && y2 <= by2) + { + // Bottom edge + t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + + return false; + +}; + +/** +* Finds the closest intersection between the Line and a Rectangle shape, or a rectangle-like +* object, such as a Sprite or Body. +* +* @method Phaser.Line.intersectionWithRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @param {Phaser.Point} [result] - A Point object to store the result in. +* @return {?Phaser.Point} - The intersection closest to the Line's start, or null if there is no intersection. +*/ +Phaser.Line.intersectionWithRectangle = function (line, rect, result) { + + var self = Phaser.Line.intersectionWithRectangle; + + if (!result) + { + result = new Phaser.Point(); + } + + if (!self.edges) + { + self.edges = [new Phaser.Line(), new Phaser.Line(), new Phaser.Line(), new Phaser.Line()]; + } + + if (!self.edgeIntersection) + { + self.edgeIntersection = new Phaser.Point(); + } + + var edges = self.edges; + var edgeIntersection = self.edgeIntersection.set(0); + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + var closestDistance = Infinity; + + edges[0].setTo(bx1, by1, bx2, by1); + edges[1].setTo(bx1, by2, bx2, by2); + edges[2].setTo(bx1, by1, bx1, by2); + edges[3].setTo(bx2, by1, bx2, by2); + + for (var edge, i = 0; (edge = edges[i]); i++) + { + if (line.intersects(edge, true, edgeIntersection)) + { + var distance = line.start.distance(edgeIntersection); + + if (distance < closestDistance) + { + closestDistance = distance; + result.copyFrom(edgeIntersection); + } + } + } + + if (distance != null) + { + return result; + } + + return null; + +}; + +/** +* Returns the reflected angle between two lines. +* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. +* +* @method Phaser.Line.reflect +* @param {Phaser.Line} a - The base line. +* @param {Phaser.Line} b - The line to be reflected from the base line. +* @return {number} The reflected angle in radians. +*/ +Phaser.Line.reflect = function (a, b) { + + return 2 * b.normalAngle - 3.141592653589793 - a.angle; + +}; + +/** +* @author Mat Groves http://matgroves.com/ @Doormat23 +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. +* +* It is represented like so: +* +* | a | b | tx | +* | c | d | ty | +* | 0 | 0 | 1 | +* +* @class Phaser.Matrix +* @constructor +* @param {number} [a=1] - Horizontal scaling +* @param {number} [b=0] - Horizontal skewing +* @param {number} [c=0] - Vertical skewing +* @param {number} [d=1] - Vertical scaling +* @param {number} [tx=0] - Horizontal translation +* @param {number} [ty=0] - Vertical translation +*/ +Phaser.Matrix = function (a, b, c, d, tx, ty) { + + if (a === undefined || a === null) { a = 1; } + if (b === undefined || b === null) { b = 0; } + if (c === undefined || c === null) { c = 0; } + if (d === undefined || d === null) { d = 1; } + if (tx === undefined || tx === null) { tx = 0; } + if (ty === undefined || ty === null) { ty = 0; } + + /** + * @property {number} a + * @default 1 + */ + this.a = a; + + /** + * @property {number} b + * @default 0 + */ + this.b = b; + + /** + * @property {number} c + * @default 0 + */ + this.c = c; + + /** + * @property {number} d + * @default 1 + */ + this.d = d; + + /** + * @property {number} tx + * @default 0 + */ + this.tx = tx; + + /** + * @property {number} ty + * @default 0 + */ + this.ty = ty; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.MATRIX; + +}; + +Phaser.Matrix.prototype = { + + /** + * Sets the values of this Matrix to the values in the given array. + * + * The Array elements should be set as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @method Phaser.Matrix#fromArray + * @param {Array} array - The array to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + fromArray: function (array) { + + return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]); + + }, + + /** + * Sets the values of this Matrix to the given values. + * + * @method Phaser.Matrix#setTo + * @param {number} a - Horizontal scaling + * @param {number} b - Horizontal skewing + * @param {number} c - Vertical skewing + * @param {number} d - Vertical scaling + * @param {number} tx - Horizontal translation + * @param {number} ty - Vertical translation + * @return {Phaser.Matrix} This Matrix object. + */ + setTo: function (a, b, c, d, tx, ty) { + + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + + }, + + /** + * Creates a new Matrix object based on the values of this Matrix. + * If you provide the output parameter the values of this Matrix will be copied over to it. + * If the output parameter is blank a new Matrix object will be created. + * + * @method Phaser.Matrix#clone + * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created. + * @return {Phaser.Matrix} A clone of this Matrix. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); + } + else + { + output.a = this.a; + output.b = this.b; + output.c = this.c; + output.d = this.d; + output.tx = this.tx; + output.ty = this.ty; + } + + return output; + + }, + + /** + * Copies the properties from this Matrix to the given Matrix. + * + * @method Phaser.Matrix#copyTo + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} The destination Matrix object. + */ + copyTo: function (matrix) { + + matrix.copyFrom(this); + + return matrix; + + }, + + /** + * Copies the properties from the given Matrix into this Matrix. + * + * @method Phaser.Matrix#copyFrom + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + copyFrom: function (matrix) { + + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + + return this; + + }, + + /** + * Creates a Float32 Array with values populated from this Matrix object. + * + * @method Phaser.Matrix#toArray + * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not. + * @param {Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created. + * @return {Float32Array} The newly created array which contains the matrix. + */ + toArray: function (transpose, array) { + + if (array === undefined) { array = new Float32Array(9); } + + if (transpose) + { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else + { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + + }, + + /** + * Get a new position with the current transformation applied. + * + * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) + * + * @method Phaser.Matrix#apply + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, transformed through this matrix. + */ + apply: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + newPos.x = this.a * pos.x + this.c * pos.y + this.tx; + newPos.y = this.b * pos.x + this.d * pos.y + this.ty; + + return newPos; + + }, + + /** + * Get a new position with the inverse of the current transformation applied. + * + * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) + * + * @method Phaser.Matrix#applyInverse + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, inverse transformed through this matrix. + */ + applyInverse: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + var id = 1 / (this.a * this.d + this.c * -this.b); + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + + }, + + /** + * Translates the matrix on the x and y. + * This is the same as Matrix.tx += x. + * + * @method Phaser.Matrix#translate + * @param {number} x - The x value to translate on. + * @param {number} y - The y value to translate on. + * @return {Phaser.Matrix} This Matrix object. + */ + translate: function (x, y) { + + this.tx += x; + this.ty += y; + + return this; + + }, + + /** + * Applies a scale transformation to this matrix. + * + * @method Phaser.Matrix#scale + * @param {number} x - The amount to scale horizontally. + * @param {number} y - The amount to scale vertically. + * @return {Phaser.Matrix} This Matrix object. + */ + scale: function (x, y) { + + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + + }, + + /** + * Applies a rotation transformation to this matrix. + * + * @method Phaser.Matrix#rotate + * @param {number} angle - The angle to rotate by, given in radians. + * @return {Phaser.Matrix} This Matrix object. + */ + rotate: function (angle) { + + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos-this.b * sin; + this.b = a1 * sin+this.b * cos; + this.c = c1 * cos-this.d * sin; + this.d = c1 * sin+this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + + }, + + /** + * Appends the given Matrix to this Matrix. + * + * @method Phaser.Matrix#append + * @param {Phaser.Matrix} matrix - The matrix to append to this one. + * @return {Phaser.Matrix} This Matrix object. + */ + append: function (matrix) { + + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + + }, + + /** + * Resets this Matrix to an identity (default) matrix. + * + * @method Phaser.Matrix#identity + * @return {Phaser.Matrix} This Matrix object. + */ + identity: function () { + + return this.setTo(1, 0, 0, 1, 0, 0); + + } + +}; + +Phaser.identityMatrix = new Phaser.Matrix(); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. +* The following code creates a point at (0,0): +* `var myPoint = new Phaser.Point();` +* You can also use them as 2D Vectors and you'll find different vector related methods in this class. +* +* @class Phaser.Point +* @constructor +* @param {number} [x=0] - The horizontal position of this Point. +* @param {number} [y=0] - The vertical position of this Point. +*/ +Phaser.Point = function (x, y) { + + x = x || 0; + y = y || 0; + + /** + * @property {number} x - The x value of the point. + */ + this.x = x; + + /** + * @property {number} y - The y value of the point. + */ + this.y = y; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINT; + +}; + +Phaser.Point.prototype = { + + /** + * Copies the x and y properties from any given object to this Point. + * + * @method Phaser.Point#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Point} This Point object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y); + + }, + + /** + * Inverts the x and y values of this Point + * + * @method Phaser.Point#invert + * @return {Phaser.Point} This Point object. + */ + invert: function () { + + return this.setTo(this.y, this.x); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.setTo(2)` is the same as `Point.setTo(2, 2)` + * + * Identical to {@link #set}. + * + * @method Phaser.Point#setTo + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setTo: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.set(2)` is the same as `Point.set(2, 2)` + * + * Identical to {@link #setTo}. + * + * @method Phaser.Point#set + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + set: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object from a given polar coordinate. + * + * @method Phaser.Point#setToPolar + * @param {number} azimuth - The angular coordinate, in radians (unless `asDegrees`). + * @param {number} [radius=1] - The radial coordinate (length). + * @param {boolean} [asDegrees=false] - True if `azimuth` is in degrees. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setToPolar: function(azimuth, radius, asDegrees) { + + if (radius == null) { radius = 1; } + if (asDegrees) { azimuth = Phaser.Math.degToRad(azimuth); } + + return this.setTo(Math.cos(azimuth) * radius, Math.sin(azimuth) * radius); + + }, + + /** + * Adds the given x and y values to this Point. + * + * @method Phaser.Point#add + * @param {number} x - The value to add to Point.x. + * @param {number} y - The value to add to Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + add: function (x, y) { + + this.x += x; + this.y += y; + return this; + + }, + + /** + * Subtracts the given x and y values from this Point. + * + * @method Phaser.Point#subtract + * @param {number} x - The value to subtract from Point.x. + * @param {number} y - The value to subtract from Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + subtract: function (x, y) { + + this.x -= x; + this.y -= y; + return this; + + }, + + /** + * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. + * + * @method Phaser.Point#multiply + * @param {number} x - The value to multiply Point.x by. + * @param {number} y - The value to multiply Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + multiply: function (x, y) { + + this.x *= x; + this.y *= y; + return this; + + }, + + /** + * Divides Point.x and Point.y by the given x and y values. + * + * @method Phaser.Point#divide + * @param {number} x - The value to divide Point.x by. + * @param {number} y - The value to divide Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + divide: function (x, y) { + + this.x /= x; + this.y /= y; + return this; + + }, + + /** + * Clamps the x value of this Point to be between the given min and max. + * + * @method Phaser.Point#clampX + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampX: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + return this; + + }, + + /** + * Clamps the y value of this Point to be between the given min and max + * + * @method Phaser.Point#clampY + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampY: function (min, max) { + + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * Clamps this Point object values to be between the given min and max. + * + * @method Phaser.Point#clamp + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clamp: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * If this Point is not within the given object, moves it inside (at the nearest edge). + * + * @method Phaser.Point#clip + * @param {any} rect - A {@link Phaser.Rectangle} or any object with left, top, right, and bottom properties. + * @return {Phaser.Point} This Point object. + */ + clip: function (rect) { + + var left = rect.left, top = rect.top, right = rect.right, bottom = rect.bottom; + + if (this.x < left ) { this.x = left; } + else if (this.x > right) { this.x = right; } + if (this.y < top) { this.y = top; } + else if (this.y > bottom) { this.y = bottom; } + + return this; + + }, + + /** + * Creates a copy of the given Point. + * + * @method Phaser.Point#clone + * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The new Point object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(this.x, this.y); + } + else + { + output.setTo(this.x, this.y); + } + + return output; + + }, + + /** + * Copies the x and y properties from this Point to any given object. + * + * @method Phaser.Point#copyTo + * @param {any} dest - The object to copy to. + * @return {object} The dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + + return dest; + + }, + + /** + * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) + * + * @method Phaser.Point#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round] - Round the distance to the nearest integer (default false). + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + return Phaser.Point.distance(this, dest, round); + + }, + + /** + * Determines whether the given objects x/y values are equal to this Point object. + * + * @method Phaser.Point#equals + * @param {Phaser.Point|any} a - The object to compare with this Point. + * @return {boolean} A value of true if the x and y points are equal, otherwise false. + */ + equals: function (a) { + + return a.x === this.x && a.y === this.y; + + }, + + /** + * Determines whether a set of x-y coordinates are equal to this Point's. + * + * @method Phaser.Point#equalsXY + * @param {number} x - The x-coordinate to compare with this Point. + * @param {number} y - The y-coordinate to compare with this Point. + * @return {boolean} A value of true if the Point's coordinates are identical to the arguments, otherwise false. + */ + equalsXY: function (x, y) { + + return this.x === x && this.y === y; + + }, + + fuzzyEquals: function (a, epsilon) { + + return Phaser.Point.fuzzyEquals(this, a, epsilon); + + }, + + fuzzyEqualsXY: function (x, y, epsilon) { + + return Phaser.Point.fuzzyEqualsXY(this, x, y, epsilon); + + }, + + /** + * Returns the angle between this Point object and another object with public x and y properties. + * + * @method Phaser.Point#angle + * @param {Phaser.Point|any} a - The object to get the angle from this Point to. + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angle: function (a, asDegrees) { + + return this.angleXY(a.x, a.y, asDegrees); + + }, + + /** + * Returns the angle between this Point object and an x-y coordinate pair. + * + * @method Phaser.Point#angleXY + * @param {number} x - The x-coordinate + * @param {number} y - The y-coordinate + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angleXY: function (x, y, asDegrees) { + + var angle = Math.atan2(y - this.y, x - this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Returns the arctangent of this Point. + * + * @method Phaser.Point#atan + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where the vertex is (0, 0). Within [-pi, pi] or [-180deg, 180deg]. + */ + atan: function (asDegrees) { + + var angle = Math.atan2(this.y, this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Rotates this Point around the x/y coordinates given to the desired angle. + * + * @method Phaser.Point#rotate + * @param {number} x - The x coordinate of the anchor point. + * @param {number} y - The y coordinate of the anchor point. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {number} [distance] - An optional distance constraint between the Point and the anchor. + * @return {Phaser.Point} The modified point object. + */ + rotate: function (x, y, angle, asDegrees, distance) { + + return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance); + + }, + + /** + * Calculates the length of the Point object. + * + * @method Phaser.Point#getMagnitude + * @return {number} The length of the Point. + */ + getMagnitude: function () { + + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + + }, + + /** + * Calculates the length squared of the Point object. + * + * @method Phaser.Point#getMagnitudeSq + * @return {number} The length ^ 2 of the Point. + */ + getMagnitudeSq: function () { + + return (this.x * this.x) + (this.y * this.y); + + }, + + /** + * Alters the length of the Point without changing the direction. + * + * @method Phaser.Point#setMagnitude + * @param {number} magnitude - The desired magnitude of the resulting Point. + * @return {Phaser.Point} This Point object. + */ + setMagnitude: function (magnitude) { + + return this.normalize().multiply(magnitude, magnitude); + + }, + + /** + * Alters the Point object so that its length is 1, but it retains the same direction. + * + * @method Phaser.Point#normalize + * @return {Phaser.Point} This Point object. + */ + normalize: function () { + + if (!this.isZero()) + { + var m = this.getMagnitude(); + this.x /= m; + this.y /= m; + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at most the max value. + * + * @method Phaser.Point#limit + * @param {number} max - The maximum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#expand + */ + limit: function (max) { + + if (this.getMagnitudeSq() > max * max) + { + this.setMagnitude(max); + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at least the min value. + * + * @method Phaser.Point#expand + * @param {number} min - The minimum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#limit + */ + expand: function (min) { + + if (this.getMagnitudeSq() < min * min) + { + this.setMagnitude(min); + } + + return this; + + }, + + /** + * Determine if this point is at 0,0. + * + * @method Phaser.Point#isZero + * @return {boolean} True if this Point is 0,0, otherwise false. + */ + isZero: function () { + + return (this.x === 0 && this.y === 0); + + }, + + /** + * The dot product of this and another Point object. + * + * @method Phaser.Point#dot + * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point. + * @return {number} The result. + */ + dot: function (a) { + + return ((this.x * a.x) + (this.y * a.y)); + + }, + + /** + * The cross product of this and another Point object. + * + * @method Phaser.Point#cross + * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point. + * @return {number} The result. + */ + cross: function (a) { + + return ((this.x * a.y) - (this.y * a.x)); + + }, + + /** + * Make this Point perpendicular (90 degrees rotation) + * + * @method Phaser.Point#perp + * @return {Phaser.Point} This Point object. + */ + perp: function () { + + return this.setTo(-this.y, this.x); + + }, + + /** + * Make this Point perpendicular (-90 degrees rotation) + * + * @method Phaser.Point#rperp + * @return {Phaser.Point} This Point object. + */ + rperp: function () { + + return this.setTo(this.y, -this.x); + + }, + + /** + * Right-hand normalize (make unit length) this Point. + * + * @method Phaser.Point#normalRightHand + * @return {Phaser.Point} This Point object. + */ + normalRightHand: function () { + + return this.setTo(this.y * -1, this.x); + + }, + + /** + * Math.floor() both the x and y properties of this Point. + * + * @method Phaser.Point#floor + * @return {Phaser.Point} This Point object. + */ + floor: function () { + + return this.setTo(Math.floor(this.x), Math.floor(this.y)); + + }, + + /** + * Math.ceil() both the x and y properties of this Point. + * + * @method Phaser.Point#ceil + * @return {Phaser.Point} This Point object. + */ + ceil: function () { + + return this.setTo(Math.ceil(this.x), Math.ceil(this.y)); + + }, + + /** + * Math.round() both the x and y properties of this Point. + * + * @method Phaser.Point#round + * @return {Phaser.Point} This Point object. + */ + round: function () { + + return this.setTo(Math.round(this.x), Math.round(this.y)); + + }, + + /** + * Returns a string representation of this object. + * + * @method Phaser.Point#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; + + } + +}; + +Phaser.Point.prototype.constructor = Phaser.Point; + +/** +* Adds the coordinates of two points together to create a new point. +* +* @method Phaser.Point.add +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.add = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x + b.x; + out.y = a.y + b.y; + + return out; + +}; + +/** +* Subtracts the coordinates of two points to create a new point. +* +* @method Phaser.Point.subtract +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.subtract = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x - b.x; + out.y = a.y - b.y; + + return out; + +}; + +/** +* Multiplies the coordinates of two points to create a new point. +* +* @method Phaser.Point.multiply +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiply = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x * b.x; + out.y = a.y * b.y; + + return out; + +}; + +/** +* Divides the coordinates of two points to create a new point. +* +* @method Phaser.Point.divide +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.divide = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x / b.x; + out.y = a.y / b.y; + + return out; + +}; + +/** +* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. +* +* @method Phaser.Point.equals +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {boolean} A value of true if the Points are equal, otherwise false. +*/ +Phaser.Point.equals = function (a, b) { + + return a.x === b.x && a.y === b.y; + +}; + +Phaser.Point.equalsXY = function (a, x, y) { + + return a.x === x && a.y === y; + +}; + +Phaser.Point.fuzzyEquals = function (a, b, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, b.x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, b.y, epsilon); + +}; + +Phaser.Point.fuzzyEqualsXY = function (a, x, y, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, y, epsilon); + +}; + +/** +* Returns the angle between two Point objects. +* +* @method Phaser.Point.angle +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {number} The angle, where b is the vertex. Within [-pi, pi]. +*/ +Phaser.Point.angle = function (a, b) { + + return Math.atan2(a.y - b.y, a.x - b.x); + +}; + +/** +* Creates a negative Point. +* +* @method Phaser.Point.negative +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.negative = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.x, -a.y); + +}; + +/** +* Adds two 2D Points together and multiplies the result by the given scalar. +* +* @method Phaser.Point.multiplyAdd +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} s - The scaling value. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiplyAdd = function (a, b, s, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + b.x * s, a.y + b.y * s); + +}; + +/** +* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. +* +* @method Phaser.Point.interpolate +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.interpolate = function (a, b, f, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f); + +}; + +/** +* Return a perpendicular vector (90 degrees rotation) +* +* @method Phaser.Point.perp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.perp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.y, a.x); + +}; + +/** +* Return a perpendicular vector (-90 degrees rotation) +* +* @method Phaser.Point.rperp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.rperp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y, -a.x); + +}; + +/** +* Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). +* +* @method Phaser.Point.distance +* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. +* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. +* @param {boolean} [round=false] - Round the distance to the nearest integer. +* @return {number} The distance between this Point object and the destination Point object. +*/ +Phaser.Point.distance = function (a, b, round) { + + var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y); + return round ? Math.round(distance) : distance; + +}; + +/** +* Project two Points onto another Point. +* +* @method Phaser.Point.project +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.project = function (a, b, out) { + + if (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; + +}; + +/** +* Project two Points onto a Point of unit length. +* +* @method Phaser.Point.projectUnit +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.projectUnit = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var amt = a.dot(b); + + if (amt !== 0) + { + out.setTo(amt * b.x, amt * b.y); + } + + return out; + +}; + +/** +* Right-hand normalize (make unit length) a Point. +* +* @method Phaser.Point.normalRightHand +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalRightHand = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y * -1, a.x); + +}; + +/** +* Normalize (make unit length) a Point. +* +* @method Phaser.Point.normalize +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalize = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var m = a.getMagnitude(); + + if (m !== 0) + { + out.setTo(a.x / m, a.y / m); + } + + return out; + +}; + +/** +* Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by +* the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument +* is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. +* +* The distance allows you to specify a distance constraint for the rotation between the point and the +* coordinates. If none is given the distance between the two is calculated and used. +* +* @method Phaser.Point.rotate +* @param {Phaser.Point} a - The Point object to rotate. +* @param {number} x - The x coordinate of the anchor point +* @param {number} y - The y coordinate of the anchor point +* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {number} [distance] - An optional distance constraint between the Point and the anchor. +* @return {Phaser.Point} The modified point object. +*/ +Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) { + + if (asDegrees) { angle = Phaser.Math.degToRad(angle); } + + if (distance === undefined) + { + a.subtract(x, y); + + var s = Math.sin(angle); + var c = Math.cos(angle); + + var tx = c * a.x - s * a.y; + var ty = s * a.x + c * a.y; + + a.x = tx + x; + a.y = ty + y; + } + else + { + var t = angle + Math.atan2(a.y - y, a.x - x); + a.x = x + distance * Math.cos(t); + a.y = y + distance * Math.sin(t); + } + + return a; + +}; + +/** +* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. +* +* @method Phaser.Point.centroid +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.centroid = function (points, out) { + + if (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 < pointslength; i++) + { + Phaser.Point.add(out, points[i], out); + } + + out.divide(pointslength, pointslength); + + return out; + +}; + +/** +* Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. +* If the object doesn't contain those properties a Point with x/y of zero will be returned. +* +* @method Phaser.Point.parse +* @static +* @param {object} obj - The object to parse. +* @param {string} [xProp='x'] - The property used to set the Point.x value. +* @param {string} [yProp='y'] - The property used to set the Point.y value. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.parse = function(obj, xProp, yProp) { + + xProp = xProp || 'x'; + yProp = yProp || 'y'; + + var point = new Phaser.Point(); + + if (obj[xProp]) + { + point.x = parseInt(obj[xProp], 10); + } + + if (obj[yProp]) + { + point.y = parseInt(obj[yProp], 10); + } + + return point; + +}; + +/** + * Tests a Point or Point-like object. + * + * @method Phaser.Point.isPoint + * @static + * @return {boolean} - True if the object has numeric x and y properties. + */ +Phaser.Point.isPoint = function(obj) { + + return (obj != null) && (typeof obj.x === 'number') && (typeof obj.y === 'number'); + +}; + +/** +* Sets the `x` and `y` values of an object and returns the object. +* +* @method Phaser.Point#set +* @static +* @param {object} obj - An object with numeric x and y properties. +* @param {number} x - The x value. +* @param {number} [y] - The y value. If not given the x value will be used in its place. +* @return {object} The object. Useful for chaining method calls. +*/ +Phaser.Point.set = function(obj, x, y) { + + obj.x = x || 0; + obj.y = y || ( (y !== 0) ? obj.x : 0 ); + + return obj; + +}; + +/** +* Sorts an array of points in a clockwise direction, relative to a reference point. +* +* The sort is clockwise relative to the display, starting from a 12 o'clock position. +* (In the Cartesian plane, it is anticlockwise, starting from the -y direction.) +* +* Example sequence: (0, -1), (1, 0), (0, 1), (-1, 0) +* +* @method Phaser.Point#sortClockwise +* @static +* @param {array} points - An array of Points or point-like objects (e.g., sprites). +* @param {object|Phaser.Point} [center] - The reference point. If omitted, the {@link #centroid} (midpoint) of the points is used. +* @return {array} The sorted array. +*/ +Phaser.Point.sortClockwise = function(points, center) { + + // Adapted from (ciamej) + + if (!center) + { + center = this.centroid(points); + } + + var cx = center.x; + var cy = center.y; + + var sort = function(a, b) { + if (a.x - cx >= 0 && b.x - cx < 0) + { + return -1; + } + + if (a.x - cx < 0 && b.x - cx >= 0) + { + return 1; + } + + if (a.x - cx === 0 && b.x - cx === 0) + { + if (a.y - cy >= 0 || b.y - cy >= 0) + { + return (a.y > b.y) ? 1 : -1; + } + + return (b.y > a.y) ? 1 : -1; + } + + // Compute the cross product of vectors (center -> a) * (center -> b) + var det = (a.x - cx) * -(b.y - cy) - (b.x - cx) * -(a.y - cy); + + if (det < 0) + { + return -1; + } + + if (det > 0) + { + return 1; + } + + // Points a and b are on the same line from the center + // Check which point is closer to the center + var d1 = (a.x - cx) * (a.x - cx) + (a.y - cy) * (a.y - cy); + var d2 = (b.x - cx) * (b.x - cx) + (b.y - cy) * (b.y - cy); + + return (d1 > d2) ? -1 : 1; + }; + + return points.sort(sort); + +}; + + +// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Point = Phaser.Point; + +/** +* @author Richard Davey +* @author Adrien Brault +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Polygon. +* +* The points can be set from a variety of formats: +* +* - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` +* - An array of objects with public x/y properties: `[obj1, obj2, ...]` +* - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` +* - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` +* - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` +* - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` +* +* @class Phaser.Polygon +* @constructor +* @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. +*/ +Phaser.Polygon = function () { + + /** + * @property {number} area - The area of this Polygon. + */ + this.area = 0; + + /** + * @property {array} _points - An array of Points that make up this Polygon. + * @private + */ + this._points = []; + + if (arguments.length > 0) + { + this.setTo.apply(this, arguments); + } + + /** + * @property {boolean} closed - Is the Polygon closed or not? + */ + this.closed = true; + + /** + * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ? + */ + this.flattened = false; + + /** + * @property {number} type - The base object type. + */ + this.type = Phaser.POLYGON; + +}; + +Phaser.Polygon.prototype = { + + /** + * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] + * + * @method Phaser.Polygon#toNumberArray + * @param {array} [output] - The array to append the points to. If not specified a new array will be created. + * @return {array} The flattened array. + */ + toNumberArray: function (output) { + + if (output === undefined) { output = []; } + + for (var i = 0; i < this._points.length; i++) + { + if (typeof this._points[i] === 'number') + { + output.push(this._points[i]); + output.push(this._points[i + 1]); + i++; + } + else + { + output.push(this._points[i].x); + output.push(this._points[i].y); + } + } + + return output; + + }, + + /** + * Flattens this Polygon so the points are a sequence of numbers. + * Any Point objects found are removed and replaced with two numbers. + * Also sets the Polygon.flattened property to `true`. + * + * @method Phaser.Polygon#flatten + * @return {Phaser.Polygon} This Polygon object + */ + flatten: function () { + + this._points = this.toNumberArray(); + + this.flattened = true; + + return this; + + }, + + /** + * Creates a copy of the given Polygon. + * This is a deep clone, the resulting copy contains new Phaser.Point objects + * + * @method Phaser.Polygon#clone + * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created. + * @return {Phaser.Polygon} The cloned (`output`) polygon object. + */ + clone: function (output) { + + var points = this._points.slice(); + + if (output === undefined || output === null) + { + output = new Phaser.Polygon(points); + } + else + { + output.setTo(points); + } + + return output; + + }, + + /** + * Checks whether the x and y coordinates are contained within this polygon. + * + * @method Phaser.Polygon#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this polygon, otherwise false. + */ + contains: function (x, y) { + + // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva + + var inside = false; + + if (this.flattened) + { + for (var i = -2, j = this._points.length - 2; (i += 2) < this._points.length; j = i) + { + var ix = this._points[i]; + var iy = this._points[i + 1]; + + var jx = this._points[j]; + var jy = this._points[j + 1]; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + + } + else + { + for (var i = -1, j = this._points.length - 1; ++i < this._points.length; j = i) + { + var ix = this._points[i].x; + var iy = this._points[i].y; + + var jx = this._points[j].x; + var jy = this._points[j].y; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + } + + return inside; + + }, + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` + * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` + * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` + * + * `setTo` may also be called without any arguments to remove all points. + * + * @method Phaser.Polygon#setTo + * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. + * @return {Phaser.Polygon} This Polygon object + */ + setTo: function (points) { + + this.area = 0; + this._points = []; + + if (arguments.length > 0) + { + // If points isn't an array, use arguments as the array + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments); + } + + var y0 = Number.MAX_VALUE; + + // Allows for mixed-type arguments + for (var i = 0, len = points.length; i < len; i++) + { + if (typeof points[i] === 'number') + { + var p = new PIXI.Point(points[i], points[i + 1]); + i++; + } + else if (Array.isArray(points[i])) + { + var p = new PIXI.Point(points[i][0], points[i][1]); + } + else + { + var p = new PIXI.Point(points[i].x, points[i].y); + } + + this._points.push(p); + + // Lowest boundary + if (p.y < y0) + { + y0 = p.y; + } + } + + this.calculateArea(y0); + } + + return this; + + }, + + /** + * Calcuates the area of the Polygon. This is available in the property Polygon.area + * + * @method Phaser.Polygon#calculateArea + * @private + * @param {number} y0 - The lowest boundary + * @return {number} The area of the Polygon. + */ + calculateArea: function (y0) { + + var p1; + var p2; + var avgHeight; + var width; + + for (var i = 0, len = this._points.length; i < len; i++) + { + p1 = this._points[i]; + + if (i === len - 1) + { + p2 = this._points[0]; + } + else + { + p2 = this._points[i + 1]; + } + + avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2; + width = p1.x - p2.x; + this.area += avgHeight * width; + } + + return this.area; + + } + +}; + +Phaser.Polygon.prototype.constructor = Phaser.Polygon; + +/** +* The points of this polygon. +* +* You can modify these with {@link Phaser.Polygon#setTo setTo}. +* +* @name Phaser.Polygon#points +* @property {Phaser.Point[]} points - The array of vertex points. +* @readonly +*/ +Object.defineProperty(Phaser.Polygon.prototype, 'points', { + + get: function() { + return this._points; + } + +}); + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Polygon = Phaser.Polygon; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. +* If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. +* +* @class Phaser.Rectangle +* @constructor +* @param {number} x - The x coordinate of the top-left corner of the Rectangle. +* @param {number} y - The y coordinate of the top-left corner of the Rectangle. +* @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. +*/ +Phaser.Rectangle = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.RECTANGLE; + +}; + +Phaser.Rectangle.prototype = { + + /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method Phaser.Rectangle#offset + * @param {number} dx - Moves the x value of the Rectangle object by this amount. + * @param {number} dy - Moves the y value of the Rectangle object by this amount. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Rectangle#offsetPoint + * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offsetPoint: function (point) { + + return this.offset(point.x, point.y); + + }, + + /** + * Sets the members of Rectangle to the specified values. + * @method Phaser.Rectangle#setTo + * @param {number} x - The x coordinate of the top-left corner of the Rectangle. + * @param {number} y - The y coordinate of the top-left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Scales the width and height of this Rectangle by the given amounts. + * + * @method Phaser.Rectangle#scale + * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. + * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. + * @return {Phaser.Rectangle} This Rectangle object + */ + scale: function (x, y) { + + if (y === undefined) { y = x; } + + this.width *= x; + this.height *= y; + + return this; + + }, + + /** + * Centers this Rectangle so that the center coordinates match the given x and y values. + * + * @method Phaser.Rectangle#centerOn + * @param {number} x - The x coordinate to place the center of the Rectangle at. + * @param {number} y - The y coordinate to place the center of the Rectangle at. + * @return {Phaser.Rectangle} This Rectangle object + */ + centerOn: function (x, y) { + + this.centerX = x; + this.centerY = y; + + return this; + + }, + + /** + * Runs Math.floor() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#floor + */ + floor: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + + }, + + /** + * Runs Math.floor() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#floorAll + */ + floorAll: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.width = Math.floor(this.width); + this.height = Math.floor(this.height); + + }, + + /** + * Runs Math.ceil() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#ceil + */ + ceil: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + + }, + + /** + * Runs Math.ceil() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#ceilAll + */ + ceilAll: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.width = Math.ceil(this.width); + this.height = Math.ceil(this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the left, top, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFromBounds + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFromBounds: function(source) { + + return this.setTo(source.left, source.top, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Rectangle to any given object. + * @method Phaser.Rectangle#copyTo + * @param {any} source - The object to copy to. + * @return {object} This object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method Phaser.Rectangle#inflate + * @param {number} dx - The amount to be added to the left side of the Rectangle. + * @param {number} dy - The amount to be added to the bottom side of the Rectangle. + * @return {Phaser.Rectangle} This Rectangle object. + */ + inflate: function (dx, dy) { + + return Phaser.Rectangle.inflate(this, dx, dy); + + }, + + /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method Phaser.Rectangle#size + * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object. + */ + size: function (output) { + + return Phaser.Rectangle.size(this, output); + + }, + + /** + * Resize the Rectangle by providing a new width and height. + * The x and y positions remain unchanged. + * + * @method Phaser.Rectangle#resize + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method Phaser.Rectangle#clone + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ + clone: function (output) { + + return Phaser.Rectangle.clone(this, output); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method Phaser.Rectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + contains: function (x, y) { + + return Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method Phaser.Rectangle#containsRect + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + containsRect: function (b) { + + return Phaser.Rectangle.containsRect(b, this); + + }, + + /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method Phaser.Rectangle#equals + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + */ + equals: function (b) { + + return Phaser.Rectangle.equals(this, b); + + }, + + /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method Phaser.Rectangle#intersection + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ + intersection: function (b, out) { + + return Phaser.Rectangle.intersection(this, b, out); + + }, + + /** + * Determines whether this Rectangle and another given Rectangle intersect with each other. + * This method checks the x, y, width, and height properties of the two Rectangles. + * + * @method Phaser.Rectangle#intersects + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + */ + intersects: function (b) { + + return Phaser.Rectangle.intersects(this, b); + + }, + + /** + * Determines whether the coordinates given intersects (overlaps) with this Rectangle. + * + * @method Phaser.Rectangle#intersectsRaw + * @param {number} left - The x coordinate of the left of the area. + * @param {number} right - The right coordinate of the area. + * @param {number} top - The y coordinate of the area. + * @param {number} bottom - The bottom coordinate of the area. + * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 + * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + */ + intersectsRaw: function (left, right, top, bottom, tolerance) { + + return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance); + + }, + + /** + * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. + * @method Phaser.Rectangle#union + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ + union: function (b, out) { + + return Phaser.Rectangle.union(this, b, out); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Rectangle. + * + * @method Phaser.Rectangle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = this.randomX; + out.y = this.randomY; + + return out; + + }, + + /** + * Returns a point based on the given position constant, which can be one of: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * This method returns the same values as calling Rectangle.bottomLeft, etc, but those + * calls always create a new Point object, where-as this one allows you to use your own. + * + * @method Phaser.Rectangle#getPoint + * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. + * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the point in its `x` and `y` properties. + */ + getPoint: function (position, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + return out.set(this.x, this.y); + + case Phaser.TOP_CENTER: + return out.set(this.centerX, this.y); + + case Phaser.TOP_RIGHT: + return out.set(this.right, this.y); + + case Phaser.LEFT_CENTER: + return out.set(this.x, this.centerY); + + case Phaser.CENTER: + return out.set(this.centerX, this.centerY); + + case Phaser.RIGHT_CENTER: + return out.set(this.right, this.centerY); + + case Phaser.BOTTOM_LEFT: + return out.set(this.x, this.bottom); + + case Phaser.BOTTOM_CENTER: + return out.set(this.centerX, this.bottom); + + case Phaser.BOTTOM_RIGHT: + return out.set(this.right, this.bottom); + } + + }, + + /** + * Creates or positions four {@link Phaser.Line} lines representing the Rectangle's sides. + * + * @method Phaser.Rectangle#sides + * @param {Phaser.Line} [top] + * @param {Phaser.Line} [right] + * @param {Phaser.Line} [bottom] + * @param {Phaser.Line} [left] + * @return {?Phaser.Line[]} - An array containing four lines (if no arguments were given), or null. + */ + sides: function (top, right, bottom, left) { + + if (!arguments.length) { + top = new Phaser.Line(); + right = new Phaser.Line(); + bottom = new Phaser.Line(); + left = new Phaser.Line(); + } + + var x1 = this.x; + var y1 = this.y; + var x2 = this.right; + var y2 = this.bottom; + + top.setTo(x1, y1, x2, y1); + right.setTo(x2, y1, x2, y2); + bottom.setTo(x1, y2, x2, y2); + left.setTo(x1, y1, x1, y2); + + if (!arguments.length) { + return [top, right, bottom, left]; + } + + return null; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Rectangle#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + + } + +}; + +/** +* @name Phaser.Rectangle#halfWidth +* @property {number} halfWidth - Half of the width of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", { + + get: function () { + return Math.round(this.width / 2); + } + +}); + +/** +* @name Phaser.Rectangle#halfHeight +* @property {number} halfHeight - Half of the height of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", { + + get: function () { + return Math.round(this.height / 2); + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. +* @name Phaser.Rectangle#bottom +* @property {number} bottom - The sum of the y and height properties. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value <= this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + + } + +}); + +/** +* The location of the Rectangles bottom left corner as a Point object. +* @name Phaser.Rectangle#bottomLeft +* @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", { + + get: function () { + return new Phaser.Point(this.x, this.bottom); + }, + + set: function (value) { + this.x = value.x; + this.bottom = value.y; + } + +}); + +/** +* The location of the Rectangles bottom right corner as a Point object. +* @name Phaser.Rectangle#bottomRight +* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", { + + get: function () { + return new Phaser.Point(this.right, this.bottom); + }, + + set: function (value) { + this.right = value.x; + this.bottom = value.y; + } + +}); + +/** +* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. +* @name Phaser.Rectangle#left +* @property {number} left - The x coordinate of the left of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + if (value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + } + +}); + +/** +* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. +* @name Phaser.Rectangle#right +* @property {number} right - The sum of the x and width properties. +*/ +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 = value - this.x; + } + } + +}); + +/** +* The volume of the Rectangle derived from width * height. +* @name Phaser.Rectangle#volume +* @property {number} volume - The volume of the Rectangle derived from width * height. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "volume", { + + get: function () { + return this.width * this.height; + } + +}); + +/** +* The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @name Phaser.Rectangle#perimeter +* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", { + + get: function () { + return (this.width * 2) + (this.height * 2); + } + +}); + +/** +* The x coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerX +* @property {number} centerX - The x coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerX", { + + get: function () { + return this.x + this.halfWidth; + }, + + set: function (value) { + this.x = value - this.halfWidth; + } + +}); + +/** +* The y coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerY +* @property {number} centerY - The y coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerY", { + + get: function () { + return this.y + this.halfHeight; + }, + + set: function (value) { + this.y = value - this.halfHeight; + } + +}); + +/** +* A random value between the left and right values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomX +* @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomX", { + + get: function () { + + return this.x + (Math.random() * this.width); + + } + +}); + +/** +* A random value between the top and bottom values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomY +* @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomY", { + + get: function () { + + return this.y + (Math.random() * this.height); + + } + +}); + +/** +* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. +* However it does affect the height property, whereas changing the y value does not affect the height property. +* @name Phaser.Rectangle#top +* @property {number} top - The y coordinate of the top of the Rectangle. +*/ +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); + } + } + +}); + +/** +* The location of the Rectangles top left corner as a Point object. +* @name Phaser.Rectangle#topLeft +* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. +*/ +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; + } + +}); + +/** +* The location of the Rectangles top right corner as a Point object. +* @name Phaser.Rectangle#topRight +* @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "topRight", { + + get: function () { + return new Phaser.Point(this.x + this.width, this.y); + }, + + set: function (value) { + this.right = value.x; + this.y = value.y; + } + +}); + +/** +* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. +* If set to true then all of the Rectangle properties are set to 0. +* @name Phaser.Rectangle#empty +* @property {boolean} empty - Gets or sets the Rectangles empty state. +*/ +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; + +/** +* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. +* @method Phaser.Rectangle.inflate +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} dx - The amount to be added to the left side of the Rectangle. +* @param {number} dy - The amount to be added to the bottom side of the Rectangle. +* @return {Phaser.Rectangle} This Rectangle object. +*/ +Phaser.Rectangle.inflate = function (a, dx, dy) { + + a.x -= dx; + a.width += 2 * dx; + a.y -= dy; + a.height += 2 * dy; + + return a; + +}; + +/** +* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. +* @method Phaser.Rectangle.inflatePoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. +* @return {Phaser.Rectangle} The Rectangle object. +*/ +Phaser.Rectangle.inflatePoint = function (a, point) { + + return Phaser.Rectangle.inflate(a, point.x, point.y); + +}; + +/** +* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. +* @method Phaser.Rectangle.size +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. +* @return {Phaser.Point} The size of the Rectangle object +*/ +Phaser.Rectangle.size = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(a.width, a.height); + } + else + { + output.setTo(a.width, a.height); + } + + return output; + +}; + +/** +* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. +* @method Phaser.Rectangle.clone +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.clone = function (a, output) { + + if (output === undefined || output === null) + { + 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; + +}; + +/** +* Returns a new Rectangle object with the same values for the left, top, width, and height properties as the original object. +* @method Phaser.Rectangle.createFromBounds +* @param {any} a - An object with `left`, `top`, `width`, and `height` properties. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.createFromBounds = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Rectangle(a.x, a.y, a.width, a.height); + } + + return output.copyFromBounds(a); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by this Rectangle object. +* @method Phaser.Rectangle.contains +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +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); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by the given raw values. +* @method Phaser.Rectangle.containsRaw +* @param {number} rx - The x coordinate of the top left of the area. +* @param {number} ry - The y coordinate of the top left of the area. +* @param {number} rw - The width of the area. +* @param {number} rh - The height of the area. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) { + + return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh)); + +}; + +/** +* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. +* @method Phaser.Rectangle.containsPoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsPoint = function (a, point) { + + return Phaser.Rectangle.contains(a, point.x, point.y); + +}; + +/** +* Determines whether the first Rectangle object is fully contained within the second Rectangle object. +* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. +* @method Phaser.Rectangle.containsRect +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRect = function (a, b) { + + // If the given rect has a larger volume than this one then it can never contain it + if (a.volume > b.volume) + { + return false; + } + + return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom); + +}; + +/** +* Determines whether the two Rectangles are equal. +* This method compares the x, y, width and height properties of each Rectangle. +* @method Phaser.Rectangle.equals +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. +*/ +Phaser.Rectangle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height); + +}; + +/** +* Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. +* @method Phaser.Rectangle.sameDimensions +* @param {Rectangle-like} a - The first Rectangle object. +* @param {Rectangle-like} b - The second Rectangle object. +* @return {boolean} True if the object have equivalent values for the width and height properties. +*/ +Phaser.Rectangle.sameDimensions = function (a, b) { + + return (a.width === b.width && a.height === b.height); + +}; + +/** +* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. +* @method Phaser.Rectangle.intersection +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. +*/ +Phaser.Rectangle.intersection = function (a, b, output) { + + if (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; + +}; + +/** +* Determines whether the two Rectangles intersect with each other. +* This method checks the x, y, width, and height properties of the Rectangles. +* @method Phaser.Rectangle.intersects +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. +*/ +Phaser.Rectangle.intersects = function (a, b) { + + if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) + { + return false; + } + + return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom); + +}; + +/** +* Determines whether the object specified intersects (overlaps) with the given values. +* @method Phaser.Rectangle.intersectsRaw +* @param {number} left - The x coordinate of the left of the area. +* @param {number} right - The right coordinate of the area. +* @param {number} top - The y coordinate of the area. +* @param {number} bottom - The bottom coordinate of the area. +* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 +* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. +*/ +Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) { + + if (tolerance === undefined) { tolerance = 0; } + + return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); + +}; + +/** +* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. +* @method Phaser.Rectangle.union +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. +*/ +Phaser.Rectangle.union = function (a, b, output) { + + if (output === undefined) + { + output = new Phaser.Rectangle(); + } + + return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top)); + +}; + +/** +* Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. +* +* @method Phaser.Rectangle#aabb +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. +* @return {Phaser.Rectangle} The new Rectangle object. +* @static +*/ +Phaser.Rectangle.aabb = function(points, out) { + + if (out === undefined) { + out = new Phaser.Rectangle(); + } + + var xMax = Number.NEGATIVE_INFINITY, + xMin = Number.POSITIVE_INFINITY, + yMax = Number.NEGATIVE_INFINITY, + yMin = Number.POSITIVE_INFINITY; + + points.forEach(function(point) { + if (point.x > xMax) { + xMax = point.x; + } + if (point.x < xMin) { + xMin = point.x; + } + + if (point.y > yMax) { + yMax = point.y; + } + if (point.y < yMin) { + yMin = point.y; + } + }); + + out.setTo(xMin, yMin, xMax - xMin, yMax - yMin); + + return out; +}; + +// Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Rectangle = Phaser.Rectangle; +PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0); + +/** +* @author Mat Groves http://matgroves.com/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Rounded Rectangle object is an area defined by its position and has nice rounded corners, +* as indicated by its top-left corner point (x, y) and by its width and its height. +* +* @class Phaser.RoundedRectangle +* @constructor +* @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle. +* @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle. +* @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value. +* @param {number} [radius=20] - Controls the radius of the rounded corners. +*/ +Phaser.RoundedRectangle = function(x, y, width, height, radius) +{ + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + if (radius === undefined) { radius = 20; } + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} radius - The radius of the rounded corners. + */ + this.radius = radius || 20; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROUNDEDRECTANGLE; +}; + +Phaser.RoundedRectangle.prototype = { + + /** + * Returns a new RoundedRectangle object with the same values for the x, y, width, height and + * radius properties as this RoundedRectangle object. + * + * @method Phaser.RoundedRectangle#clone + * @return {Phaser.RoundedRectangle} + */ + clone: function () { + + return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. + * + * @method Phaser.RoundedRectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. + */ + 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; + + } + +}; + +Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle; + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.RoundedRectangle = Phaser.RoundedRectangle; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. +* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y +* +* @class Phaser.Camera +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera +* @param {number} x - Position of the camera on the X axis +* @param {number} y - Position of the camera on the Y axis +* @param {number} width - The width of the view rectangle +* @param {number} height - The height of the view rectangle +*/ +Phaser.Camera = function (game, id, x, y, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + */ + this.world = game.world; + + /** + * @property {number} id - Reserved for future multiple camera set-ups. + * @default + */ + this.id = 0; + + /** + * Camera view. + * The view into the world we wish to render (by default the game dimensions). + * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. + * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. + * @property {Phaser.Rectangle} view + */ + this.view = new Phaser.Rectangle(x, y, width, height); + + /** + * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. + * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound + * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. + * + * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. + */ + this.bounds = new Phaser.Rectangle(x, y, width, height); + + /** + * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move. + */ + this.deadzone = null; + + /** + * @property {boolean} visible - Whether this camera is visible or not. + * @default + */ + this.visible = true; + + /** + * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. + * @default + */ + this.roundPx = true; + + /** + * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. + */ + this.atLimit = { x: false, y: false }; + + /** + * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. + * @default + */ + this.target = null; + + /** + * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot. + */ + this.displayObject = null; + + /** + * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot. + */ + this.scale = null; + + /** + * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. + * @readonly + */ + this.totalInView = 0; + + /** + * The linear interpolation value to use when following a target. + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * @property {Phaser.Point} lerp + * @default + */ + this.lerp = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes. + */ + this.onShakeComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes. + */ + this.onFlashComplete = new Phaser.Signal(); + + /** + * This signal is dispatched when the camera fade effect completes. + * When the fade effect completes you will be left with the screen black (or whatever + * color you faded to). In order to reset this call `Camera.resetFX`. This is called + * automatically when you change State. + * @property {Phaser.Signal} onFadeComplete + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * The Graphics object used to handle camera fx such as fade and flash. + * @property {Phaser.Graphics} fx + * @protected + */ + this.fx = null; + + /** + * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position. + * @private + */ + this._targetPosition = new Phaser.Point(); + + /** + * @property {number} edge - Edge property. + * @private + * @default + */ + this._edge = 0; + + /** + * @property {Phaser.Point} position - Current position of the camera in world. + * @private + * @default + */ + this._position = new Phaser.Point(); + + /** + * @property {Object} _shake - The shake effect container. + * @private + */ + this._shake = { + intensity: 0, + duration: 0, + horizontal: false, + vertical: false, + shakeBounds: true, + x: 0, + y: 0 + }; + + /** + * @property {number} _fxDuration - FX duration timer. + * @private + */ + this._fxDuration = 0; + + /** + * @property {number} _fxType - The FX type running. + * @private + */ + this._fxType = 0; + + /** + * @property {Phaser.Rectangle} + * @private + */ + this._fixedView = new Phaser.Rectangle(); + +}; + +/** +* A follow style that uses no deadzone. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_LOCKON = 0; + +/** +* A follow style that uses a tall, narrow deadzone (0.33 x 0.125) with a center slightly above the view center. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_PLATFORMER = 1; + +/** +* A follow style that uses a square deadzone (0.25 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN = 2; + +/** +* A follow style that uses a small square deadzone (0.125 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_BOTH = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_HORIZONTAL = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_VERTICAL = 6; + +/** +* @constant +* @type {boolean} +*/ +Phaser.Camera.ENABLE_FX = true; + +Phaser.Camera.prototype = { + + /** + * Called automatically by Phaser.World. + * + * @method Phaser.Camera#boot + * @private + */ + boot: function () { + + this.displayObject = this.game.world; + + this.scale = this.game.world.scale; + + this.game.camera = this; + + if (Phaser.Graphics && Phaser.Camera.ENABLE_FX) + { + this.fx = new Phaser.Graphics(this.game); + + this.game.stage.addChild(this.fx); + } + + }, + + /** + * Camera preUpdate. Sets the total view counter to zero. + * + * @method Phaser.Camera#preUpdate + */ + preUpdate: function () { + + this.totalInView = 0; + + }, + + /** + * Tell the camera which sprite to follow. + * + * You can set the follow type and a linear interpolation value. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. + * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. + * + * @method Phaser.Camera#follow + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything. + * @param {number} [style] - Leverage one of the existing {@link deadzone} presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + */ + follow: function (target, style, lerpX, lerpY) { + + if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; } + if (lerpX === undefined) { lerpX = 1; } + if (lerpY === undefined) { lerpY = 1; } + + this.target = target; + this.lerp.set(lerpX, lerpY); + + var helper; + + switch (style) { + + case Phaser.Camera.FOLLOW_PLATFORMER: + var w = this.width / 8; + var h = this.height / 3; + this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN: + helper = Math.max(this.width, this.height) / 4; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT: + helper = Math.max(this.width, this.height) / 8; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_LOCKON: + this.deadzone = null; + break; + + default: + this.deadzone = null; + break; + } + + }, + + /** + * Sets the Camera follow target to null, stopping it from following an object if it's doing so. + * + * @method Phaser.Camera#unfollow + */ + unfollow: function () { + + this.target = null; + + }, + + /** + * Move the camera focus on a display object instantly. + * @method Phaser.Camera#focusOn + * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. + */ + focusOn: function (displayObject) { + + this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight)); + + }, + + /** + * Move the camera focus on a location instantly. + * @method Phaser.Camera#focusOnXY + * @param {number} x - X position. + * @param {number} y - Y position. + */ + focusOnXY: function (x, y) { + + this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight)); + + }, + + /** + * This creates a camera shake effect. It works by applying a random amount of additional + * spacing on the x and y axis each frame. You can control the intensity and duration + * of the effect, and if it should effect both axis or just one. + * + * When the shake effect ends the signal Camera.onShakeComplete is dispatched. + * + * @method Phaser.Camera#shake + * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. + * @param {number} [duration=500] - The duration of the shake effect in milliseconds. + * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL. + * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?). + * @return {boolean} True if the shake effect was started, otherwise false. + */ + shake: function (intensity, duration, force, direction, shakeBounds) { + + if (intensity === undefined) { intensity = 0.05; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = true; } + if (direction === undefined) { direction = Phaser.Camera.SHAKE_BOTH; } + if (shakeBounds === undefined) { shakeBounds = true; } + + if (!force && this._shake.duration > 0) + { + // Can't reset an already running shake + return false; + } + + this._shake.intensity = intensity; + this._shake.duration = duration; + this._shake.shakeBounds = shakeBounds; + + this._shake.x = 0; + this._shake.y = 0; + + this._shake.horizontal = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_HORIZONTAL); + this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL); + + return true; + + }, + + /** + * This creates a camera flash effect. It works by filling the game with the solid fill + * color specified, and then fading it away to alpha 0 over the duration given. + * + * You can use this for things such as hit feedback effects. + * + * When the effect ends the signal Camera.onFlashComplete is dispatched. + * + * @method Phaser.Camera#flash + * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the flash effect in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the flash effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + flash: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0xffffff; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 1; + + this._fxDuration = duration; + this._fxType = 0; + + return true; + + }, + + /** + * This creates a camera fade effect. It works by filling the game with the + * color specified, over the duration given, ending with a solid fill. + * + * You can use this for things such as transitioning to a new scene. + * + * The game will be left 'filled' at the end of this effect, likely obscuring + * everything. In order to reset it you can call `Camera.resetFX` and it will clear the + * fade. Or you can call `Camera.flash` with the same color as the fade, and it will + * reverse the process, bringing the game back into view again. + * + * When the effect ends the signal Camera.onFadeComplete is dispatched. + * + * @method Phaser.Camera#fade + * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the fade in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the fade effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + fade: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0x000000; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 0; + + this._fxDuration = duration; + this._fxType = 1; + + return true; + + }, + + /** + * The camera update loop. This is called automatically by the core game loop. + * + * @method Phaser.Camera#update + * @protected + */ + update: function () { + + if (this._fxDuration > 0) + { + this.updateFX(); + } + + if (this._shake.duration > 0) + { + this.updateShake(); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + this._shake.x = Math.floor(this._shake.x); + this._shake.y = Math.floor(this._shake.y); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the camera flash and fade effects. + * + * @method Phaser.Camera#updateFX + * @private + */ + updateFX: function () { + + if (this._fxType === 0) + { + // flash + this.fx.alpha -= this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha <= 0) + { + this._fxDuration = 0; + this.fx.alpha = 0; + this.onFlashComplete.dispatch(); + } + } + else + { + // fade + this.fx.alpha += this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha >= 1) + { + this._fxDuration = 0; + this.fx.alpha = 1; + this.onFadeComplete.dispatch(); + } + } + + }, + + /** + * Update the camera shake effect. + * + * @method Phaser.Camera#updateShake + * @private + */ + updateShake: function () { + + this._shake.duration -= this.game.time.elapsedMS; + + if (this._shake.duration <= 0) + { + this.onShakeComplete.dispatch(); + this._shake.x = 0; + this._shake.y = 0; + } + else + { + if (this._shake.horizontal) + { + this._shake.x = this.game.rnd.frac() * this._shake.intensity * this.view.width * 2 - this._shake.intensity * this.view.width; + } + + if (this._shake.vertical) + { + this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height; + } + } + + }, + + /** + * Internal method that handles tracking a sprite. + * + * @method Phaser.Camera#updateTarget + * @private + */ + updateTarget: function () { + + this._targetPosition.x = this.view.x + this.target.worldPosition.x; + this._targetPosition.y = this.view.y + this.target.worldPosition.y; + + if (this.deadzone) + { + this._edge = this._targetPosition.x - this.view.x; + + if (this._edge < this.deadzone.left) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.left, this.lerp.x); + } + else if (this._edge > this.deadzone.right) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.right, this.lerp.x); + } + + this._edge = this._targetPosition.y - this.view.y; + + if (this._edge < this.deadzone.top) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.top, this.lerp.y); + } + else if (this._edge > this.deadzone.bottom) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.bottom, this.lerp.y); + } + } + else + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.view.halfWidth, this.lerp.x); + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.view.halfHeight, this.lerp.y); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the Camera bounds to match the game world. + * + * @method Phaser.Camera#setBoundsToWorld + */ + setBoundsToWorld: function () { + + if (this.bounds) + { + this.bounds.copyFrom(this.game.world.bounds); + } + + }, + + /** + * Method called to ensure the camera doesn't venture outside of the game world. + * Called automatically by Camera.update. + * + * @method Phaser.Camera#checkBounds + * @protected + */ + checkBounds: function () { + + this.atLimit.x = false; + this.atLimit.y = false; + + var vx = this.view.x + this._shake.x; + var vw = this.view.right + this._shake.x; + var vy = this.view.y + this._shake.y; + var vh = this.view.bottom + this._shake.y; + + // Make sure we didn't go outside the cameras bounds + if (vx <= this.bounds.x * this.scale.x) + { + this.atLimit.x = true; + this.view.x = this.bounds.x * this.scale.x; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + else if (vw >= this.bounds.right * this.scale.x) + { + this.atLimit.x = true; + this.view.x = (this.bounds.right * this.scale.x) - this.width; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + + if (vy <= this.bounds.top * this.scale.y) + { + this.atLimit.y = true; + this.view.y = this.bounds.top * this.scale.y; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + else if (vh >= this.bounds.bottom * this.scale.y) + { + this.atLimit.y = true; + this.view.y = (this.bounds.bottom * this.scale.y) - this.height; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + + }, + + /** + * A helper function to set both the X and Y properties of the camera at once + * without having to use game.camera.x and game.camera.y. + * + * @method Phaser.Camera#setPosition + * @param {number} x - X position. + * @param {number} y - Y position. + */ + setPosition: function (x, y) { + + this.view.x = x; + this.view.y = y; + + if (this.bounds) + { + this.checkBounds(); + } + + }, + + /** + * Sets the size of the view rectangle given the width and height in parameters. + * + * @method Phaser.Camera#setSize + * @param {number} width - The desired width. + * @param {number} height - The desired height. + */ + setSize: function (width, height) { + + this.view.width = width; + this.view.height = height; + + }, + + /** + * Resets the camera back to 0,0 and un-follows any object it may have been tracking. + * Also immediately resets any camera effects that may have been running such as + * shake, flash or fade. + * + * @method Phaser.Camera#reset + */ + reset: function () { + + this.target = null; + + this.view.x = 0; + this.view.y = 0; + + this._shake.duration = 0; + this._shake.x = 0; + this._shake.y = 0; + + this.resetFX(); + + }, + + /** + * Resets any active FX, such as a fade or flash and immediately clears it. + * Useful to calling after a fade in order to remove the fade from the Stage. + * + * @method Phaser.Camera#resetFX + */ + resetFX: function () { + + if (this.fx) + { + this.fx.clear(); + this.fx.alpha = 0; + } + + this._fxDuration = 0; + + } + +}; + +Phaser.Camera.prototype.constructor = Phaser.Camera; + +/** +* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#x +* @property {number} x - Gets or sets the cameras x position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "x", { + + get: function () { + + return this.view.x; + + }, + + set: function (value) { + + this.view.x = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#y +* @property {number} y - Gets or sets the cameras y position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "y", { + + get: function () { + + return this.view.y; + + }, + + set: function (value) { + + this.view.y = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras position. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#position +* @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object. +*/ +Object.defineProperty(Phaser.Camera.prototype, "position", { + + get: function () { + + this._position.set(this.view.x, this.view.y); + + return this._position; + + }, + + set: function (value) { + + if (typeof value.x !== "undefined") { this.view.x = value.x; } + if (typeof value.y !== "undefined") { this.view.y = value.y; } + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras width. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#width +* @property {number} width - Gets or sets the cameras width. +*/ +Object.defineProperty(Phaser.Camera.prototype, "width", { + + get: function () { + + return this.view.width; + + }, + + set: function (value) { + + this.view.width = value; + + } + +}); + +/** +* The Cameras height. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#height +* @property {number} height - Gets or sets the cameras height. +*/ +Object.defineProperty(Phaser.Camera.prototype, "height", { + + get: function () { + + return this.view.height; + + }, + + set: function (value) { + + this.view.height = value; + + } + +}); + + +/** +* The Cameras shake intensity. +* @name Phaser.Camera#shakeIntensity +* @property {number} shakeIntensity - Gets or sets the cameras shake intensity. +*/ +Object.defineProperty(Phaser.Camera.prototype, "shakeIntensity", { + + get: function () { + + return this._shake.intensity; + + }, + + set: function (value) { + + this._shake.intensity = value; + + } + +}); + + +/** + * Immobile {@link #view} rectangle. Its top-left is always (0, 0). You can use this align fixedToCamera objects. + * @name Phaser.Camera#fixedView + * @property {Phaser.Rectangle} fixedView + * @readonly + */ +Object.defineProperty(Phaser.Camera.prototype, "fixedView", { + + get: function () { + + this._fixedView.setTo(0, 0, this.view.width, this.view.height); + + return this._fixedView; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base State class which can be extended if you are creating your own game. +* It provides quick access to common functions such as the camera, cache, input, match, sound and more. +* +* #### Callbacks +* +* | start | preload | loaded | paused | stop | +* |-------|-------------|------------|--------------|----------| +* | init | | | | | +* | | preload | create | paused | | +* | | loadUpdate* | update* | pauseUpdate* | | +* | | | preRender* | | | +* | | loadRender* | render* | render* | | +* | | | | resumed | | +* | | | | | shutdown | +* +* Update and render calls (*) are repeated. +* +* If your State has a constructor, it will be invoked exactly once, during {@link {@link Phaser.StateManager#add}. +* +* @class Phaser.State +* @constructor +*/ +Phaser.State = function () { + + /** + * @property {Phaser.Game} game - This is a reference to the currently running Game. + */ + this.game = null; + + /** + * @property {string} key - The string based identifier given to the State when added into the State Manager. + */ + this.key = ''; + + /** + * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects. + */ + this.make = null; + + /** + * @property {Phaser.Camera} camera - A handy reference to World.camera. + */ + this.camera = null; + + /** + * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - A reference to the Input Manager. + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions. + */ + this.math = null; + + /** + * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. + */ + this.sound = null; + + /** + * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays. + */ + this.scale = null; + + /** + * @property {Phaser.Stage} stage - A reference to the Stage. + */ + this.stage = null; + + /** + * @property {Phaser.StateManager} stage - A reference to the State Manager, which controls state changes. + */ + this.state = null; + + /** + * @property {Phaser.Time} time - A reference to the game clock and timed events system. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - A reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. + */ + this.world = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. + */ + this.particles = null; + + /** + * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser. + */ + this.physics = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator. + */ + this.rnd = null; + +}; + +Phaser.State.prototype = { + + /** + * init is the very first function called when your State starts up. It's called before preload, create or anything else. + * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables + * or objects before the preloading starts. + * + * @method Phaser.State#init + * @param {...any} args - Any extra arguments passed to {@link Phaser.StateManager#start} or {@link Phaser.StateManager#restart}. + */ + init: function () { + }, + + /** + * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) + * You shouldn't create any objects in this method that require assets that you're also loading in this method, as + * they won't yet be available. + * + * @method Phaser.State#preload + * @param {Phaser.Game} game + */ + preload: function () { + }, + + /** + * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * + * @method Phaser.State#loadUpdate + * @param {Phaser.Game} game + */ + loadUpdate: function () { + }, + + /** + * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. + * + * @method Phaser.State#loadRender + * @param {Phaser.Game} game + */ + loadRender: function () { + }, + + /** + * create is called once preload has completed, this includes the loading of any assets from the Loader. + * If you don't have a preload method then create is the first method called in your State. + * + * @method Phaser.State#create + * @param {Phaser.Game} game + */ + create: function () { + }, + + /** + * The update method is left empty for your own use. + * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. + * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. + * + * @method Phaser.State#update + * @param {Phaser.Game} game + */ + update: function () { + }, + + /** + * The preRender method is called after all Game Objects have been updated, but before any rendering takes place. + * + * @method Phaser.State#preRender + * @param {Phaser.Game} game + * @param {number} elapsedTime + */ + preRender: function () { + }, + + /** + * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. + * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any + * final post-processing style effects here. Note that this happens before plugins postRender takes place. + * + * @method Phaser.State#render + * @param {Phaser.Game} game + */ + render: function () { + }, + + /** + * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. + * + * @method Phaser.State#resize + * @param {number} width + * @param {number} height + */ + resize: function () { + }, + + /** + * This method will be called if the core game loop is paused. + * + * @method Phaser.State#paused + * @param {Phaser.Game} game + */ + paused: function () { + }, + + /** + * This method will be called when the core game loop resumes from a paused state. + * + * @method Phaser.State#resumed + * @param {Phaser.Game} game + */ + resumed: function () { + }, + + /** + * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. + * + * @method Phaser.State#pauseUpdate + * @param {Phaser.Game} game + */ + pauseUpdate: function () { + }, + + /** + * This method will be called when the State is shutdown (i.e. you switch to another state from this one). + * + * @method Phaser.State#shutdown + * @param {Phaser.Game} game + */ + shutdown: function () { + } + +}; + +Phaser.State.prototype.constructor = Phaser.State; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The State Manager is responsible for loading, setting up and switching game states. +* +* @class Phaser.StateManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. +*/ +Phaser.StateManager = function (game, pendingState) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {object} states - The object containing Phaser.States. + */ + this.states = {}; + + /** + * @property {Phaser.State} _pendingState - The state to be switched to in the next frame. + * @private + */ + this._pendingState = null; + + if (typeof pendingState !== 'undefined' && pendingState !== null) + { + this._pendingState = pendingState; + } + + /** + * @property {boolean} _clearWorld - Clear the world when we switch state? + * @private + */ + this._clearWorld = false; + + /** + * @property {boolean} _clearCache - Clear the cache when we switch state? + * @private + */ + this._clearCache = false; + + /** + * @property {boolean} _created - Flag that sets if the State has been created or not. + * @private + */ + this._created = false; + + /** + * @property {any[]} _args - Temporary container when you pass vars from one State to another. + * @private + */ + this._args = []; + + /** + * @property {string} current - The current active State object. + * @default + */ + this.current = ''; + + /** + * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. + * + * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start + * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states + * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. + * + * The callback you specify is sent two parameters: the string based key of the new state, + * and the second parameter is the string based key of the old / previous state. + * + * @property {Phaser.Signal} onStateChange + */ + this.onStateChange = new Phaser.Signal(); + + /** + * @property {function} onInitCallback - This is called when the state is set as the active state. + * @default + */ + this.onInitCallback = null; + + /** + * @property {function} onPreloadCallback - This is called when the state starts to load assets. + * @default + */ + this.onPreloadCallback = null; + + /** + * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins. + * @default + */ + this.onCreateCallback = null; + + /** + * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). + * @default + */ + this.onUpdateCallback = null; + + /** + * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). + * @default + */ + this.onRenderCallback = null; + + /** + * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. + * @default + */ + this.onResizeCallback = null; + + /** + * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. + * @default + */ + this.onPreRenderCallback = null; + + /** + * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase. + * @default + */ + this.onLoadUpdateCallback = null; + + /** + * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase. + * @default + */ + this.onLoadRenderCallback = null; + + /** + * @property {function} onPausedCallback - This is called when the game is paused. + * @default + */ + this.onPausedCallback = null; + + /** + * @property {function} onResumedCallback - This is called when the game is resumed from a paused state. + * @default + */ + this.onResumedCallback = null; + + /** + * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused. + * @default + */ + this.onPauseUpdateCallback = null; + + /** + * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state). + * @default + */ + this.onShutDownCallback = null; + +}; + +Phaser.StateManager.prototype = { + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * @method Phaser.StateManager#boot + * @private + */ + boot: function () { + + this.game.onPause.add(this.pause, this); + this.game.onResume.add(this.resume, this); + + if (this._pendingState !== null && typeof this._pendingState !== 'string') + { + this.add('default', this._pendingState, true); + } + + }, + + /** + * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. + * + * The State can be any of + * + * - a plain JavaScript object containing at least one required callback (see {@link #checkState}) + * - an instance of {@link Phaser.State} + * - an instance of a class extending Phaser.State + * - a constructor function (class) + * + * If a function is given a new state object will be created by calling it, passing the current {@link Phaser.Game game} as the first argument. + * + * @method Phaser.StateManager#add + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + * @param {Phaser.State|object|function} state - The state you want to switch to. + * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it. + */ + add: function (key, state, autoStart) { + + if (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; + + }, + + /** + * Delete the given state. + * @method Phaser.StateManager#remove + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + */ + 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.onPreRenderCallback = null; + this.onRenderCallback = null; + this.onResizeCallback = null; + this.onPausedCallback = null; + this.onResumedCallback = null; + this.onPauseUpdateCallback = null; + } + + delete this.states[key]; + + }, + + /** + * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. + * + * @method Phaser.StateManager#start + * @param {string} key - The key of the state you want to start. + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one). + */ + start: function (key, clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + if (this.checkState(key)) + { + // Place the state in the queue. It will be started the next time the game loop begins. + this._pendingState = key; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 3) + { + this._args = Array.prototype.splice.call(arguments, 3); + } + } + + }, + + /** + * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. + * + * @method Phaser.StateManager#restart + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one. + */ + restart: function (clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + // Place the state in the queue. It will be started the next time the game loop starts. + this._pendingState = this.current; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 2) + { + this._args = Array.prototype.slice.call(arguments, 2); + } + + }, + + /** + * Used by onInit and onShutdown when those functions don't exist on the state + * @method Phaser.StateManager#dummy + * @private + */ + dummy: function () { + }, + + /** + * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. + * + * @method Phaser.StateManager#preUpdate + */ + preUpdate: function () { + + if (this._pendingState && this.game.isBooted) + { + var previousStateKey = this.current; + + // Already got a state running? + this.clearCurrentState(); + + this.setCurrentState(this._pendingState); + + this.onStateChange.dispatch(this.current, previousStateKey); + + if (this.current !== this._pendingState) + { + return; + } + else + { + this._pendingState = null; + } + + // If StateManager.start has been called from the init of a State that ALSO has a preload, then + // onPreloadCallback will be set, but must be ignored + if (this.onPreloadCallback) + { + this.game.load.reset(true); + this.onPreloadCallback.call(this.callbackContext, this.game); + + // Is the loader empty? + if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0) + { + this.loadComplete(); + } + else + { + // Start the loader going as we have something in the queue + this.game.load.start(); + } + } + else + { + // No init? Then there was nothing to load either + this.loadComplete(); + } + } + + }, + + /** + * This method clears the current State, calling its shutdown callback. The process also removes any active tweens, + * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. + * + * @method Phaser.StateManager#clearCurrentState + */ + clearCurrentState: function () { + + if (this.current) + { + if (this.onShutDownCallback) + { + 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(); + + this.game.scale.reset(this._clearWorld); + + if (this.game.debug) + { + this.game.debug.reset(); + } + + if (this._clearWorld) + { + this.game.world.shutdown(); + + if (this._clearCache) + { + this.game.cache.destroy(); + } + } + } + + }, + + /** + * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. + * + * @method Phaser.StateManager#checkState + * @param {string} key - The key of the state you want to check. + * @return {boolean} true if the State has the required functions, otherwise false. + */ + checkState: function (key) { + + var state = this.states[key]; + + if (state) + { + if (state.preload || state.create || state.update || state.render) + { + return true; + } + else + { + console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"); + return false; + } + } + else + { + console.warn("Phaser.StateManager - No state found with the key: " + key); + return false; + } + + }, + + /** + * Links game properties to the State given by the key. + * + * @method Phaser.StateManager#link + * @param {string} key - State key. + * @protected + */ + link: function (key) { + + var state = this.states[key]; + + state.game = this.game; + state.add = this.game.add; + state.make = this.game.make; + state.camera = this.game.camera; + state.cache = this.game.cache; + state.input = this.game.input; + state.load = this.game.load; + state.math = this.game.math; + state.sound = this.game.sound; + state.scale = this.game.scale; + state.state = this; + state.stage = this.game.stage; + state.time = this.game.time; + state.tweens = this.game.tweens; + state.world = this.game.world; + state.particles = this.game.particles; + state.rnd = this.game.rnd; + state.physics = this.game.physics; + state.key = key; + + }, + + /** + * Nulls all State level Phaser properties, including a reference to Game. + * + * @method Phaser.StateManager#unlink + * @param {string} key - State key. + * @protected + */ + unlink: function (key) { + + var state = this.states[key]; + + if (state) + { + state.game = null; + state.add = null; + state.make = null; + state.camera = null; + state.cache = null; + state.input = null; + state.load = null; + state.math = null; + state.sound = null; + state.scale = null; + state.state = null; + state.stage = null; + state.time = null; + state.tweens = null; + state.world = null; + state.particles = null; + state.rnd = null; + state.physics = null; + } + + }, + + /** + * Sets the current State. Should not be called directly (use StateManager.start) + * + * @method Phaser.StateManager#setCurrentState + * @param {string} key - State key. + * @private + */ + setCurrentState: function (key) { + + var state = this.states[key]; + + this.callbackContext = state; + + this.link(key); + + // Used when the state is set as being the current active state + this.onInitCallback = state['init'] || this.dummy; + + this.onPreloadCallback = state['preload'] || null; + this.onLoadRenderCallback = state['loadRender'] || null; + this.onLoadUpdateCallback = state['loadUpdate'] || null; + this.onCreateCallback = state['create'] || null; + this.onUpdateCallback = state['update'] || null; + this.onPreRenderCallback = state['preRender'] || null; + this.onRenderCallback = state['render'] || null; + this.onResizeCallback = state['resize'] || null; + this.onPausedCallback = state['paused'] || null; + this.onResumedCallback = state['resumed'] || null; + this.onPauseUpdateCallback = state['pauseUpdate'] || null; + + // Used when the state is no longer the current active state + this.onShutDownCallback = state['shutdown'] || this.dummy; + + // Reset the physics system, but not on the first state start + if (this.current !== '') + { + this.game.physics.reset(); + } + + this.current = key; + this._created = false; + + // At this point key and pendingState should equal each other + this.onInitCallback.apply(this.callbackContext, this._args); + + // If they no longer do then the init callback hit StateManager.start + if (key === this._pendingState) + { + this._args = []; + } + + this.game._kickstart = true; + + }, + + /** + * Gets the current State. + * + * @method Phaser.StateManager#getCurrentState + * @return {Phaser.State} + * @public + */ + getCurrentState: function() { + return this.states[this.current]; + }, + + /** + * @method Phaser.StateManager#loadComplete + * @protected + */ + loadComplete: function () { + + // Make sure to do load-update one last time before state is set to _created + if (this._created === false && this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + + if (this._created === false && this.onCreateCallback) + { + this._created = true; + this.onCreateCallback.call(this.callbackContext, this.game); + } + else + { + this._created = true; + } + + }, + + /** + * @method Phaser.StateManager#pause + * @protected + */ + pause: function () { + + if (this._created && this.onPausedCallback) + { + this.onPausedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#resume + * @protected + */ + resume: function () { + + if (this._created && this.onResumedCallback) + { + this.onResumedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#update + * @protected + */ + update: function () { + + if (this._created) + { + if (this.onUpdateCallback) + { + this.onUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#pauseUpdate + * @protected + */ + pauseUpdate: function () { + + if (this._created) + { + if (this.onPauseUpdateCallback) + { + this.onPauseUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#preRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + preRender: function (elapsedTime) { + + if (this._created && this.onPreRenderCallback) + { + this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime); + } + + }, + + /** + * @method Phaser.StateManager#resize + * @protected + */ + resize: function (width, height) { + + if (this.onResizeCallback) + { + this.onResizeCallback.call(this.callbackContext, width, height); + } + + }, + + /** + * @method Phaser.StateManager#render + * @protected + */ + render: function () { + + if (this._created) + { + if (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); + this.game.context.restore(); + } + else + { + this.onRenderCallback.call(this.callbackContext, this.game); + } + } + } + else + { + if (this.onLoadRenderCallback) + { + this.onLoadRenderCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. + * You don't recover from this without rebuilding the Phaser instance again. + * @method Phaser.StateManager#destroy + */ + destroy: function () { + + this._clearWorld = true; + this._clearCache = true; + + this.clearCurrentState(); + + 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; + this.current = ''; + + } + +}; + +Phaser.StateManager.prototype.constructor = Phaser.StateManager; + +/** +* @name Phaser.StateManager#created +* @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default). +* @readOnly +*/ +Object.defineProperty(Phaser.StateManager.prototype, "created", { + + get: function () { + + return this._created; + + } + +}); + +/** +* "It's like nailing jelly to a kitten" - Gary Penn +*/ + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Signals are what Phaser uses to handle events and event dispatching. +* You can listen for a Signal by binding a callback / function to it. +* This is done by using either `Signal.add` or `Signal.addOnce`. +* +* For example you can listen for a touch or click event from the Input Manager +* by using its `onDown` Signal: +* +* `game.input.onDown.add(function() { ... });` +* +* Rather than inline your function, you can pass a reference: +* +* `game.input.onDown.add(clicked, this);` +* `function clicked () { ... }` +* +* In this case the second argument (`this`) is the context in which your function should be called. +* +* Now every time the InputManager dispatches the `onDown` signal (or event), your function +* will be called. +* +* Multiple callbacks can be bound to the same signal. +* They're ordered first by their `priority` arguments and then by the order in which they were added. +* If a callback calls {@link #halt} or returns `false`, any remaining callbacks are skipped. +* +* Very often a Signal will send arguments to your function. +* This is specific to the Signal itself. +* If you're unsure then check the documentation, or failing that simply do: +* +* `Signal.add(function() { console.log(arguments); })` +* +* and it will log all of the arguments your function received from the Signal. +* +* Sprites have lots of default signals you can listen to in their Events class, such as: +* +* `sprite.events.onKilled` +* +* Which is called automatically whenever the Sprite is killed. +* There are lots of other events, see the Events component for a list. +* +* As well as listening to pre-defined Signals you can also create your own: +* +* `var mySignal = new Phaser.Signal();` +* +* This creates a new Signal. You can bind a callback to it: +* +* `mySignal.add(myCallback, this);` +* +* and then finally when ready you can dispatch the Signal: +* +* `mySignal.dispatch(your arguments);` +* +* And your callback will be invoked. See the dispatch method for more details. +* +* @class Phaser.Signal +* @constructor +*/ +Phaser.Signal = function () {}; + +Phaser.Signal.prototype = { + + /** + * @property {?Array.} _bindings - Internal variable. + * @private + */ + _bindings: null, + + /** + * @property {any} _prevParams - Internal variable. + * @private + */ + _prevParams: null, + + /** + * Memorize the previously dispatched event? + * + * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}. + * Use {@link #forget} to clear any currently memorized event. + * + * @property {boolean} memorize + */ + memorize: false, + + /** + * @property {boolean} _shouldPropagate + * @private + */ + _shouldPropagate: true, + + /** + * Is the Signal active? Only active signals will broadcast dispatched events. + * + * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}. + * + * @property {boolean} active + * @default + */ + active: true, + + /** + * @property {function} _boundDispatch - The bound dispatch function, if any. + * @private + */ + _boundDispatch: false, + + /** + * @method Phaser.Signal#validateListener + * @param {function} listener - Signal handler function. + * @param {string} fnName - Function name. + * @private + */ + validateListener: function (listener, fnName) { + + if (typeof listener !== 'function') + { + throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); + } + + }, + + /** + * @method Phaser.Signal#_registerListener + * @private + * @param {function} listener - Signal handler function. + * @param {boolean} isOnce - Should the listener only be called once? + * @param {object} [listenerContext] - The context under which the listener is invoked. + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + _registerListener: function (listener, isOnce, listenerContext, priority, args) { + + var prevIndex = this._indexOfListener(listener, listenerContext); + var binding; + + if (prevIndex !== -1) + { + binding = this._bindings[prevIndex]; + + if (binding.isOnce() !== isOnce) + { + throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); + } + } + else + { + binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args); + this._addBinding(binding); + } + + if (this.memorize && this._prevParams) + { + binding.execute(this._prevParams); + } + + return binding; + + }, + + /** + * @method Phaser.Signal#_addBinding + * @private + * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. + */ + _addBinding: function (binding) { + + if (!this._bindings) + { + this._bindings = []; + } + + // Simplified insertion sort + var n = this._bindings.length; + + do { + n--; + } + while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); + + this._bindings.splice(n + 1, 0, binding); + + }, + + /** + * @method Phaser.Signal#_indexOfListener + * @private + * @param {function} listener - Signal handler function. + * @param {object} [context=null] - Signal handler function. + * @return {number} The index of the listener within the private bindings array. + */ + _indexOfListener: function (listener, context) { + + if (!this._bindings) + { + return -1; + } + + if (context === undefined) { context = null; } + + var n = this._bindings.length; + var cur; + + while (n--) + { + cur = this._bindings[n]; + + if (cur._listener === listener && cur.context === context) + { + return n; + } + } + + return -1; + + }, + + /** + * Check if a specific listener is attached. + * + * @method Phaser.Signal#has + * @param {function} listener - Signal handler function. + * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @return {boolean} If Signal has the specified listener. + */ + has: function (listener, context) { + + return this._indexOfListener(listener, context) !== -1; + + }, + + /** + * Add an event listener for this signal. + * + * An event listener is a callback with a related context and priority. + * + * You can optionally provide extra arguments which will be passed to the callback after any internal parameters. + * + * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. + * Any arguments you've specified after `priority` will be sent as well: + * + * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` + * + * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. + * + * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', + * and the value 100 were the custom arguments given in the call to 'add'. + * + * If the callback calls {@link #halt} or returns `false`, any remaining callbacks bound to this Signal are skipped. + * + * @method Phaser.Signal#add + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + add: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'add'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, false, listenerContext, priority, args); + + }, + + /** + * Add a one-time listener - the listener is automatically removed after the first execution. + * + * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and + * the listener will be removed immediately. + * + * @method Phaser.Signal#addOnce + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + addOnce: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'addOnce'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, true, listenerContext, priority, args); + + }, + + /** + * Remove a single event listener. + * + * @method Phaser.Signal#remove + * @param {function} listener - Handler function that should be removed. + * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {function} Listener handler function. + */ + remove: function (listener, context) { + + this.validateListener(listener, 'remove'); + + var i = this._indexOfListener(listener, context); + + if (i !== -1) + { + this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal + this._bindings.splice(i, 1); + } + + return listener; + + }, + + /** + * Remove all event listeners. + * + * @method Phaser.Signal#removeAll + * @param {object} [context=null] - If specified only listeners for the given context will be removed. + */ + removeAll: function (context) { + + if (context === undefined) { context = null; } + + if (!this._bindings) + { + return; + } + + var n = this._bindings.length; + + while (n--) + { + if (context) + { + if (this._bindings[n].context === context) + { + this._bindings[n]._destroy(); + this._bindings.splice(n, 1); + } + } + else + { + this._bindings[n]._destroy(); + } + } + + if (!context) + { + this._bindings.length = 0; + } + + }, + + /** + * Gets the total number of listeners attached to this Signal. + * + * @method Phaser.Signal#getNumListeners + * @return {integer} Number of listeners attached to the Signal. + */ + getNumListeners: function () { + + return this._bindings ? this._bindings.length : 0; + + }, + + /** + * Stop propagation of the event, blocking the dispatch to next listener on the queue. + * + * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. + * See {@link #active} to enable/disable the signal entirely. + * + * @method Phaser.Signal#halt + */ + halt: function () { + + this._shouldPropagate = false; + + }, + + /** + * Dispatch / broadcast the event to all listeners. + * + * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}. + * + * @method Phaser.Signal#dispatch + * @param {any} [params] - Parameters that should be passed to each handler. + */ + dispatch: function () { + + if (!this.active || !this._bindings) + { + return; + } + + var paramsArr = Array.prototype.slice.call(arguments); + var n = this._bindings.length; + var bindings; + + if (this.memorize) + { + this._prevParams = paramsArr; + } + + if (!n) + { + // Should come after memorize + return; + } + + bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch + this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. + + //execute all callbacks until end of the list or until a callback returns `false` or stops propagation + //reverse loop since listeners with higher priority will be added at the end of the list + do { + n--; + } + while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); + + }, + + /** + * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any. + * + * @method Phaser.Signal#forget + */ + forget: function() { + + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * Dispose the signal - no more events can be dispatched. + * + * This removes all event listeners and clears references to external objects. + * Calling methods on a disposed objects results in undefined behavior. + * + * @method Phaser.Signal#dispose + */ + dispose: function () { + + this.removeAll(); + + this._bindings = null; + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * A string representation of the object. + * + * @method Phaser.Signal#toString + * @return {string} String representation of the object. + */ + toString: function () { + + return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']'; + + } + +}; + +/** +* Create a `dispatch` function that maintains a binding to the original Signal context. +* +* Use the resulting value if the dispatch function needs to be passed somewhere +* or called independently of the Signal object. +* +* @memberof Phaser.Signal +* @property {function} boundDispatch +*/ +Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", { + + get: function () { + var _this = this; + return this._boundDispatch || (this._boundDispatch = function () { + return _this.dispatch.apply(_this, arguments); + }); + } + +}); + +Phaser.Signal.prototype.constructor = Phaser.Signal; + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Object that represents a binding between a Signal and a listener function. +* This is an internal constructor and shouldn't be created directly. +* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. +* +* @class Phaser.SignalBinding +* @constructor +* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to. +* @param {function} listener - Handler function bound to the signal. +* @param {boolean} isOnce - If binding should be executed just once. +* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). +* @param {number} [priority] - The priority level of the event listener. (default = 0). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. +*/ +Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) { + + /** + * @property {Phaser.Game} _listener - Handler function bound to the signal. + * @private + */ + this._listener = listener; + + if (isOnce) + { + this._isOnce = true; + } + + if (listenerContext != null) /* not null/undefined */ + { + this.context = listenerContext; + } + + /** + * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to. + * @private + */ + this._signal = signal; + + if (priority) + { + this._priority = priority; + } + + if (args && args.length) + { + this._args = args; + } + +}; + +Phaser.SignalBinding.prototype = { + + /** + * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + */ + context: null, + + /** + * @property {boolean} _isOnce - If binding should be executed just once. + * @private + */ + _isOnce: false, + + /** + * @property {number} _priority - Listener priority. + * @private + */ + _priority: 0, + + /** + * @property {array} _args - Listener arguments. + * @private + */ + _args: null, + + /** + * @property {number} callCount - The number of times the handler function has been called. + */ + callCount: 0, + + /** + * If binding is active and should be executed. + * @property {boolean} active + * @default + */ + active: true, + + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). + * @property {array|null} params + * @default + */ + params: null, + + /** + * Call listener passing arbitrary parameters. + * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. + * @method Phaser.SignalBinding#execute + * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener. + * @return {any} Value returned by the listener. + */ + execute: function(paramsArr) { + + var handlerReturn, params; + + if (this.active && !!this._listener) + { + params = this.params ? this.params.concat(paramsArr) : paramsArr; + + if (this._args) + { + params = params.concat(this._args); + } + + handlerReturn = this._listener.apply(this.context, params); + + this.callCount++; + + if (this._isOnce) + { + this.detach(); + } + } + + return handlerReturn; + + }, + + /** + * Detach binding from signal. + * alias to: @see mySignal.remove(myBinding.getListener()); + * @method Phaser.SignalBinding#detach + * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ + detach: function () { + return this.isBound() ? this._signal.remove(this._listener, this.context) : null; + }, + + /** + * @method Phaser.SignalBinding#isBound + * @return {boolean} True if binding is still bound to the signal and has a listener. + */ + isBound: function () { + return (!!this._signal && !!this._listener); + }, + + /** + * @method Phaser.SignalBinding#isOnce + * @return {boolean} If SignalBinding will only be executed once. + */ + isOnce: function () { + return this._isOnce; + }, + + /** + * @method Phaser.SignalBinding#getListener + * @return {function} Handler function bound to the signal. + */ + getListener: function () { + return this._listener; + }, + + /** + * @method Phaser.SignalBinding#getSignal + * @return {Phaser.Signal} Signal that listener is currently bound to. + */ + getSignal: function () { + return this._signal; + }, + + /** + * Delete instance properties + * @method Phaser.SignalBinding#_destroy + * @private + */ + _destroy: function () { + delete this._signal; + delete this._listener; + delete this.context; + }, + + /** + * @method Phaser.SignalBinding#toString + * @return {string} String representation of the object. + */ + toString: function () { + return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']'; + } + +}; + +Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding; + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Filter class to use for any Phaser filter development. +* If you want to make a custom filter, this should be your base class. +* +* The default uniforms, types and values for all Filters are: +* +* ```javascript +* resolution: { type: '2f', value: { x: 256, y: 256 }} +* time: { type: '1f', value: 0 } +* mouse: { type: '2f', value: { x: 0.0, y: 0.0 } } +* date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] } +* sampleRate: { type: '1f', value: 44100.0 } +* iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* ``` +* +* The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and +* therefore only work in WebGL and are not supported by Canvas at all. +* +* @class Phaser.Filter +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [uniforms] - Uniform mappings object. The uniforms are added on the default uniforms, or replace them if the keys are the same. +* @param {Array|string} [fragmentSrc] - The fragment shader code. Either an array, one element per line of code, or a string. +*/ +Phaser.Filter = function (game, uniforms, fragmentSrc) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. + * @default + */ + this.type = Phaser.WEBGL_FILTER; + + /** + * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. + * For example the blur filter has two passes blurX and blurY. + * @property {array} passes - An array of filter objects. + * @private + */ + this.passes = [ this ]; + + /** + * @property {array} shaders - Array an array of shaders. + * @private + */ + this.shaders = []; + + /** + * @property {boolean} dirty - Internal PIXI var. + * @default + */ + this.dirty = true; + + /** + * @property {number} padding - Internal PIXI var. + * @default + */ + this.padding = 0; + + /** + * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same) + */ + this.prevPoint = new Phaser.Point(); + + /* + * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D. + */ + + var d = new Date(); + + /** + * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. + */ + this.uniforms = { + + resolution: { type: '2f', value: { x: 256, y: 256 }}, + time: { type: '1f', value: 0 }, + mouse: { type: '2f', value: { x: 0.0, y: 0.0 } }, + date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, + sampleRate: { type: '1f', value: 44100.0 }, + iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + + }; + + // Copy over / replace any passed in the constructor + if (uniforms) + { + for (var key in uniforms) + { + this.uniforms[key] = uniforms[key]; + } + } + + // If fragmentSrc is a string, split it based on new-lines into an array + if (typeof fragmentSrc === 'string') + { + fragmentSrc = fragmentSrc.split('\n'); + } + + /** + * @property {array|string} fragmentSrc - The fragment shader code. + */ + this.fragmentSrc = fragmentSrc || []; + +}; + +Phaser.Filter.prototype = { + + /** + * This should be over-ridden. Will receive a variable number of arguments. + * + * @method Phaser.Filter#init + */ + init: function () { + + // This should be over-ridden. Will receive a variable number of arguments. + + }, + + /** + * Set the resolution uniforms on the filter. + * + * @method Phaser.Filter#setResolution + * @param {number} width - The width of the display. + * @param {number} height - The height of the display. + */ + setResolution: function (width, height) { + + this.uniforms.resolution.value.x = width; + this.uniforms.resolution.value.y = height; + + }, + + /** + * Updates the filter. + * + * @method Phaser.Filter#update + * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. + */ + update: function (pointer) { + + if (pointer) + { + var x = pointer.x / this.game.width; + var y = 1 - pointer.y / this.game.height; + + if (x !== this.prevPoint.x || y !== this.prevPoint.y) + { + this.uniforms.mouse.value.x = x.toFixed(2); + this.uniforms.mouse.value.y = y.toFixed(2); + this.prevPoint.set(x, y); + } + } + + this.uniforms.time.value = this.game.time.totalElapsedSeconds(); + + }, + + /** + * Creates a new Phaser.Image object using a blank texture and assigns + * this Filter to it. The image is then added to the world. + * + * If you don't provide width and height values then Filter.width and Filter.height are used. + * + * If you do provide width and height values then this filter will be resized to match those + * values. + * + * @method Phaser.Filter#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. + * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, width, height, anchorX, anchorY) { + + if (anchorX === undefined) { anchorX = 0; } + if (anchorY === undefined) { anchorY = 0; } + + if (width !== undefined && width !== null) + { + this.width = width; + } + else + { + width = this.width; + } + + if (height !== undefined && height !== null) + { + this.height = height; + } + else + { + height = this.height; + } + + var image = this.game.add.image(x, y, Phaser.Cache.DEFAULT); + + image.width = width; + image.height = height; + + image.anchor.set(anchorX, anchorY); + + image.filters = [ this ]; + + return image; + + }, + + /** + * Syncs the uniforms between the class object and the shaders. + * + * @method Phaser.Filter#syncUniforms + */ + syncUniforms: function () { + + for (var i = 0; i < this.shaders.length; i++) + { + this.shaders[i].dirty = true; + } + + }, + + /** + * Clear down this Filter and null out references to game. + * + * @method Phaser.Filter#destroy + */ + destroy: function () { + + this.passes.length = 0; + this.shaders.length = 0; + this.fragmentSrc.length = 0; + + this.game = null; + this.uniforms = null; + this.prevPoint = null; + + } + +}; + +Phaser.Filter.prototype.constructor = Phaser.Filter; + +/** +* @name Phaser.Filter#width +* @property {number} width - The width (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'width', { + + get: function () { + + return this.uniforms.resolution.value.x; + + }, + + set: function (value) { + + this.uniforms.resolution.value.x = value; + + } + +}); + +/** +* @name Phaser.Filter#height +* @property {number} height - The height (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'height', { + + get: function () { + + return this.uniforms.resolution.value.y; + + }, + + set: function (value) { + + this.uniforms.resolution.value.y = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Plugin template to use for any Phaser plugin development. +* +* ##### Callbacks +* +* add | active | visible | remove +* -----|-------------|-------------|-------- +* init | | | +* | preUpdate* | | +* | update* | render* | +* | postUpdate* | postRender* | +* | | | destroy +* +* Update and render calls are repeated (*). +* +* @class Phaser.Plugin +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager. +*/ +Phaser.Plugin = function (game, parent) { + + if (parent === undefined) { parent = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. + */ + this.parent = parent; + + /** + * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. + * @default + */ + this.active = false; + + /** + * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. + * @default + */ + this.visible = false; + + /** + * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. + * @default + */ + this.hasPreUpdate = false; + + /** + * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. + * @default + */ + this.hasUpdate = false; + + /** + * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. + * @default + */ + this.hasPostUpdate = false; + + /** + * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. + * @default + */ + this.hasRender = false; + + /** + * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. + * @default + */ + this.hasPostRender = false; + +}; + +Phaser.Plugin.prototype = { + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It is only called if active is set to true. + * @method Phaser.Plugin#preUpdate + */ + preUpdate: function () { + }, + + /** + * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It is only called if active is set to true. + * @method Phaser.Plugin#update + */ + update: function () { + }, + + /** + * Render is called right after the Game Renderer completes, but before the State.render. + * It is only called if visible is set to true. + * @method Phaser.Plugin#render + */ + render: function () { + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It is only called if visible is set to true. + * @method Phaser.Plugin#postRender + */ + postRender: function () { + }, + + /** + * Clear down this Plugin and null out references + * @method Phaser.Plugin#destroy + */ + destroy: function () { + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + + } + +}; + +Phaser.Plugin.prototype.constructor = Phaser.Plugin; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. +* +* @class Phaser.PluginManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.PluginManager = function(game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager. + */ + this.plugins = []; + + /** + * @property {number} _len - Internal cache var. + * @private + */ + this._len = 0; + + /** + * @property {number} _i - Internal cache var. + * @private + */ + this._i = 0; + +}; + +Phaser.PluginManager.prototype = { + + /** + * Add a new Plugin into the PluginManager. + * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.PluginManager#add + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + add: function (plugin) { + + var args = Array.prototype.slice.call(arguments, 1); + var result = false; + + // Prototype? + if (typeof plugin === 'function') + { + plugin = new plugin(this.game, this); + } + else + { + plugin.game = this.game; + plugin.parent = this; + } + + // Check for methods now to avoid having to do this every loop + 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; + } + + // The plugin must have at least one of the above functions to be added to the PluginManager. + 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); + + // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager + if (typeof plugin['init'] === 'function') + { + plugin.init.apply(plugin, args); + } + + return plugin; + } + else + { + return null; + } + }, + + /** + * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. + * + * @method Phaser.PluginManager#remove + * @param {Phaser.Plugin} plugin - The plugin to be removed. + * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed? + */ + remove: function (plugin, destroy) { + + if (destroy === undefined) { destroy = true; } + + this._i = this._len; + + while (this._i--) + { + if (this.plugins[this._i] === plugin) + { + if (destroy) + { + plugin.destroy(); + } + + this.plugins.splice(this._i, 1); + this._len--; + return; + } + } + + }, + + /** + * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. + * + * @method Phaser.PluginManager#removeAll + */ + removeAll: function() { + + this._i = this._len; + + while (this._i--) + { + this.plugins[this._i].destroy(); + } + + this.plugins.length = 0; + this._len = 0; + + }, + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#preUpdate + */ + 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 is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#update + */ + 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 is the last thing to be called before the world render. + * In particular, it is called after the world postUpdate, which means the camera has been adjusted. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#postUpdate + */ + 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 is called right after the Game Renderer completes, but before the State.render. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#render + */ + 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(); + } + } + + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#postRender + */ + 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(); + } + } + + }, + + /** + * Clear down this PluginManager, calls destroy on every plugin and nulls out references. + * + * @method Phaser.PluginManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.game = null; + + } + +}; + +Phaser.PluginManager.prototype.constructor = Phaser.PluginManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Stage controls root level display objects upon which everything is displayed. +* It also handles browser visibility handling and the pausing due to loss of focus. +* +* @class Phaser.Stage +* @extends PIXI.DisplayObjectContainer +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Stage = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {string} name - The name of this object. + * @default + */ + this.name = '_stage_root'; + + /** + * By default if the browser tab loses focus the game will pause. + * You can stop that behavior by setting this property to true. + * Note that the browser can still elect to pause your game if it wishes to do so, + * for example swapping to another browser tab. This will cause the RAF callback to halt, + * effectively pausing your game, even though no in-game pause event is triggered if you enable this property. + * @property {boolean} disableVisibilityChange + * @default + */ + this.disableVisibilityChange = false; + + /** + * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. + * @default + */ + this.exists = true; + + /** + * @property {Phaser.Matrix} worldTransform - Current transform of the object based on world (parent) factors + * @private + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage) + * @private + * @readOnly + */ + this.stage = this; + + /** + * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. + */ + this.currentRenderOrderID = 0; + + /** + * @property {string} hiddenVar - The page visibility API event name. + * @private + */ + this._hiddenVar = 'hidden'; + + /** + * @property {function} _onChange - The blur/focus event handler. + * @private + */ + this._onChange = null; + + /** + * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor. + * @private + */ + this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' }; + + if (!this.game.transparent) + { + // transparent = 0,0,0,0 - otherwise r,g,b,1 + this._bgColor.a = 1; + } + + if (game.config) + { + this.parseConfig(game.config); + } + +}; + +Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Stage.prototype.constructor = Phaser.Stage; + +/** +* Parses a Game configuration object. +* +* @method Phaser.Stage#parseConfig +* @protected +* @param {object} config -The configuration object to parse. +*/ +Phaser.Stage.prototype.parseConfig = function (config) { + + if (config['disableVisibilityChange']) + { + this.disableVisibilityChange = config['disableVisibilityChange']; + } + + if (config['backgroundColor']) + { + this.setBackgroundColor(config['backgroundColor']); + } + +}; + +/** +* Initialises the stage and adds the event listeners. +* @method Phaser.Stage#boot +* @private +*/ +Phaser.Stage.prototype.boot = function () { + + Phaser.DOM.getOffset(this.game.canvas, this.offset); + + Phaser.Canvas.setUserSelect(this.game.canvas, 'none'); + Phaser.Canvas.setTouchAction(this.game.canvas, 'none'); + + this.checkVisibility(); + +}; + +/** +* This is called automatically after the plugins preUpdate and before the State.update. +* Most objects have preUpdate methods and it's where initial movement and positioning is done. +* +* @method Phaser.Stage#preUpdate +*/ +Phaser.Stage.prototype.preUpdate = function () { + + this.currentRenderOrderID = 0; + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + +}; + +/** +* This is called automatically after the State.update, but before particles or plugins update. +* +* @method Phaser.Stage#update +*/ +Phaser.Stage.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + this.children[i].update(); + } + +}; + +/** +* This is called automatically before the renderer runs and after the plugins have updated. +* In postUpdate this is where all the final physics calculations and object positioning happens. +* The objects are processed in the order of the display list. +* +* @method Phaser.Stage#postUpdate +*/ +Phaser.Stage.prototype.postUpdate = function () { + + // Apply the camera shake, fade, bounds, etc + this.game.camera.update(); + + // Camera target first? + if (this.game.camera.target) + { + this.game.camera.target.postUpdate(); + + this.updateTransform(); + + this.game.camera.updateTarget(); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + this.updateTransform(); + +}; + +/** +* Updates the transforms for all objects on the display list. +* This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. +* +* @method Phaser.Stage#updateTransform +*/ +Phaser.Stage.prototype.updateTransform = function () { + + this.worldAlpha = 1; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +/** +* Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. +* Also listens for window.onblur and window.onfocus. +* +* @method Phaser.Stage#checkVisibility +*/ +Phaser.Stage.prototype.checkVisibility = function () { + + if (document.hidden !== undefined) + { + this._hiddenVar = 'visibilitychange'; + } + else if (document.webkitHidden !== undefined) + { + this._hiddenVar = 'webkitvisibilitychange'; + } + else if (document.mozHidden !== undefined) + { + this._hiddenVar = 'mozvisibilitychange'; + } + else if (document.msHidden !== undefined) + { + this._hiddenVar = 'msvisibilitychange'; + } + else + { + this._hiddenVar = null; + } + + var _this = this; + + this._onChange = function (event) { + return _this.visibilityChange(event); + }; + + this._onClick = function (event) { + if ((document.hasFocus !== undefined) && !document.hasFocus()) + { + _this.visibilityChange(event); + } + }; + + // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus + if (this._hiddenVar) + { + document.addEventListener(this._hiddenVar, this._onChange, false); + } + + window.onblur = this._onChange; + window.onfocus = this._onChange; + + window.onpagehide = this._onChange; + window.onpageshow = this._onChange; + + window.addEventListener('click', this._onClick); + + if (this.game.device.cocoonJSApp) + { + CocoonJS.App.onSuspended.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" }); + }); + + CocoonJS.App.onActivated.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" }); + }); + } + +}; + +/** +* This method is called when the document visibility is changed. +* +* - `blur` and `pagehide` events trigger {@link Phaser.Game#onBlur}. They {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `click`, `focus`, and `pageshow` trigger {@link Phaser.Game#onFocus}. They {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (hidden) and CocoonJS's `onSuspended` {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (visible) and CocoonJS's `onActivated` {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* +* @method Phaser.Stage#visibilityChange +* @param {Event} event - Its type will be used to decide whether the game should be paused or not. +*/ +Phaser.Stage.prototype.visibilityChange = function (event) { + + // These events always trigger the Game#onBlur or Game#onFocus signals. + + switch (event.type) + { + case 'blur': + case 'pagehide': + this.game.focusLoss(event); + return; + case 'click': + case 'focus': + case 'pageshow': + this.game.focusGain(event); + return; + } + + if (this.disableVisibilityChange) + { + return; + } + + if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause") + { + this.game.gamePaused(event); + } + else + { + this.game.gameResumed(event); + } + +}; + +/** +* Sets the background color for the Stage. +* +* The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). +* +* An alpha channel is _not_ supported and will be ignored. +* +* If you've set your game to be {@link Phaser.Game#transparent transparent} then calls to setBackgroundColor are ignored. +* +* If {@link Phaser.Game#clearBeforeRender} is off then the background color won't appear. +* +* @method Phaser.Stage#setBackgroundColor +* @param {number|string} color - The color of the background. +*/ +Phaser.Stage.prototype.setBackgroundColor = function (color) { + + if (this.game.transparent) { return; } + + Phaser.Color.valueToColor(color, this._bgColor); + Phaser.Color.updateColor(this._bgColor); + + // For gl.clearColor (canvas uses _bgColor.rgba) + this._bgColor.r /= 255; + this._bgColor.g /= 255; + this._bgColor.b /= 255; + this._bgColor.a = 1; + +}; + +/** +* Destroys the Stage and removes event listeners. +* +* @method Phaser.Stage#destroy +*/ +Phaser.Stage.prototype.destroy = function () { + + if (this._hiddenVar) + { + document.removeEventListener(this._hiddenVar, this._onChange, false); + } + + window.onpagehide = null; + window.onpageshow = null; + + window.onblur = null; + window.onfocus = null; + + window.removeEventListener('click', this._onClick); + +}; + +/** +* Adds an existing object to the Stage. +* +* The child is automatically added to the front of the Stage, and is displayed above every previous child. +* Or if the _optional_ `index` is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the object was already on the Stage, it is simply returned, and nothing else happens to it. +* +* @method Phaser.Stage#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent] - Unused. Kept for compatibility with {@link Phaser.Group#add}. +* @param {integer} [index] - The index to insert the object to. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Stage.prototype.add = function (child, silent, index) { + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + this.addChild(child); + } + else + { + this.addChildAt(child, index); + } + + return child; + +}; + +/** +* @name Phaser.Stage#backgroundColor +* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' +* @see Phaser.Stage#setBackgroundColor +*/ +Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", { + + get: function () { + + return this._bgColor.color; + + }, + + set: function (color) { + + this.setBackgroundColor(color); + + } + +}); + +/** +* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. +* +* @name Phaser.Stage#smoothed +* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) +*/ +Object.defineProperty(Phaser.Stage.prototype, "smoothed", { + + get: function () { + + return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR; + + }, + + set: function (value) { + + if (value) + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR; + } + else + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}. +* +* Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. +* For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. +* +* In addition, Groups provides support for fast pooling and object recycling. +* +* Groups are also display objects and can be nested as children within other Groups. +* +* @class Phaser.Group +* @extends PIXI.DisplayObjectContainer +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to. +* If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent. +* @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World. +* @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}. +* @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values. +*/ +Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) { + + if (addToStage === undefined) { addToStage = false; } + if (enableBody === undefined) { enableBody = false; } + if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + if (parent === undefined) + { + parent = game.world; + } + + /** + * A name for this group. Not used internally but useful for debugging. + * @property {string} name + */ + this.name = name || 'group'; + + /** + * The z-depth value of this object within its parent container/Group - the World is a Group as well. + * This value must be unique for each child in a Group. + * @property {integer} z + * @readOnly + */ + this.z = 0; + + PIXI.DisplayObjectContainer.call(this); + + if (addToStage) + { + this.game.stage.addChild(this); + this.z = this.game.stage.children.length; + } + else + { + if (parent) + { + parent.addChild(this); + this.z = parent.children.length; + } + } + + /** + * Internal Phaser Type value. + * @property {integer} type + * @protected + */ + this.type = Phaser.GROUP; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. + * @property {boolean} alive + * @default + */ + this.alive = true; + + /** + * If exists is false the group will be excluded from collision checks and filters such as {@link #forEachExists}. The group will not call `preUpdate` and `postUpdate` on its children and the children will not receive physics updates or camera/world boundary checks. The group will still be {@link #visible} and will still call `update` on its children (unless {@link #updateOnlyExistingChildren} is true). + * @property {boolean} exists + * @default + */ + this.exists = true; + + /** + * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. + * @property {boolean} ignoreDestroy + * @default + */ + this.ignoreDestroy = false; + + /** + * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method + * called on the next logic update. + * You can set it directly to flag the Group to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy a Group from within one of its own callbacks + * or a callback of one of its children. + * + * @property {boolean} pendingDestroy + */ + this.pendingDestroy = false; + + /** + * The type of objects that will be created when using {@link #create} or {@link #createMultiple}. + * + * It should extend either Sprite or Image and accept the same constructor arguments: `(game, x, y, key, frame)`. + * + * @property {function} classType + * @default {@link Phaser.Sprite} + */ + this.classType = Phaser.Sprite; + + /** + * The current display object that the group cursor is pointing to, if any. (Can be set manually.) + * + * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}. + * @property {?DisplayObject} cursor + */ + this.cursor = null; + + /** + * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` + * on any children _added_ to, or _created by_, this Group. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * @property {boolean} inputEnableChildren + * @default + */ + this.inputEnableChildren = false; + + /** + * Skip children with `exists = false` in {@link #update}. + * + * @property {boolean} updateOnlyExistingChildren + * @default + */ + this.updateOnlyExistingChildren = false; + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputDown + */ + this.onChildInputDown = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, + * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer + * is still over the Sprite or not. + * + * @property {Phaser.Signal} onChildInputUp + */ + this.onChildInputUp = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOver + */ + this.onChildInputOver = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOut + */ + this.onChildInputOut = new Phaser.Signal(); + + /** + * If true all Sprites created by, or added to this group, will have a physics body enabled on them. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * The default body type is controlled with {@link #physicsBodyType}. + * @property {boolean} enableBody + */ + this.enableBody = enableBody; + + /** + * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well. + * + * This only works for P2 bodies. + * @property {boolean} enableBodyDebug + * @default + */ + this.enableBodyDebug = false; + + /** + * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites. + * + * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc. + * @property {integer} physicsBodyType + */ + this.physicsBodyType = physicsBodyType; + + /** + * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. + * + * It should be set to one of the Phaser.Physics.Arcade sort direction constants: + * + * Phaser.Physics.Arcade.SORT_NONE + * Phaser.Physics.Arcade.LEFT_RIGHT + * Phaser.Physics.Arcade.RIGHT_LEFT + * Phaser.Physics.Arcade.TOP_BOTTOM + * Phaser.Physics.Arcade.BOTTOM_TOP + * + * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. + * + * @property {integer} physicsSortDirection + * @default + */ + this.physicsSortDirection = null; + + /** + * This signal is dispatched when the group is destroyed. + * @property {Phaser.Signal} onDestroy + */ + this.onDestroy = new Phaser.Signal(); + + /** + * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next. + * @readOnly + */ + this.cursorIndex = 0; + + /** + * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. + * + * Note that the cameraOffset values are in addition to any parent in the display list. + * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x + * + * @property {boolean} fixedToCamera + */ + this.fixedToCamera = false; + + /** + * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view. + * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. + * @property {Phaser.Point} cameraOffset + */ + this.cameraOffset = new Phaser.Point(); + + /** + * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. + * + * Only children of this Group can be added to and removed from the hash. + * + * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. + * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own + * sorting and filtering of Group children without touching their z-index (and therefore display draw order) + * + * @property {array} hash + */ + this.hash = []; + + /** + * The property on which children are sorted. + * @property {string} _sortProperty + * @private + */ + this._sortProperty = 'z'; + +}; + +Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Group.prototype.constructor = Phaser.Group; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_NONE = 0; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_TOTAL = 1; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_CHILD = 2; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_ALL = 3; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_ASCENDING = -1; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_DESCENDING = 1; + +/** +* Adds an existing object as the top child in this group. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the child was already in this Group, it is simply returned, and nothing else happens to it. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* Use {@link #create} to create and add a new child. +* +* @method Phaser.Group#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.add = function (child, silent, index) { + + if (silent === undefined) { silent = false; } + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + child.z = this.children.length; + + this.addChild(child); + } + else + { + this.addChildAt(child, index); + + this.updateZ(); + } + + if (this.enableBody && child.hasOwnProperty('body') && child.body === null) + { + this.game.physics.enable(child, this.physicsBodyType); + } + else if (child.body) + { + this.addToHash(child); + } + + if (this.inputEnableChildren && (!child.input || child.inputEnabled)) + { + child.inputEnabled = true; + } + + if (!silent && child.events) + { + child.events.onAddedToGroup$dispatch(child, this); + } + + if (this.cursor === null) + { + this.cursor = child; + } + + return child; + +}; + +/** +* Adds an existing object to this group. +* +* The child is added to the group at the location specified by the index value, this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#addAt +* @param {DisplayObject} child - The display object to add as a child. +* @param {integer} [index=0] - The index within the group to insert the child to. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.addAt = function (child, index, silent) { + + return this.add(child, silent, index); + +}; + +/** +* Adds a child of this Group into the hash array. +* This call will return false if the child is not a child of this Group, or is already in the hash. +* +* @method Phaser.Group#addToHash +* @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. +* @return {boolean} True if the child was successfully added to the hash, otherwise false. +*/ +Phaser.Group.prototype.addToHash = function (child) { + + if (child.parent === this) + { + var index = this.hash.indexOf(child); + + if (index === -1) + { + this.hash.push(child); + return true; + } + } + + return false; + +}; + +/** +* Removes a child of this Group from the hash array. +* This call will return false if the child is not in the hash. +* +* @method Phaser.Group#removeFromHash +* @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash. +* @return {boolean} True if the child was successfully removed from the hash, otherwise false. +*/ +Phaser.Group.prototype.removeFromHash = function (child) { + + if (child) + { + var index = this.hash.indexOf(child); + + if (index !== -1) + { + this.hash.splice(index, 1); + return true; + } + } + + return false; + +}; + +/** +* Adds an array of existing Display Objects to this Group. +* +* The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. +* +* As well as an array you can also pass another Group as the first argument. In this case all of the children from that +* Group will be removed from it and added into this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#addMultiple +* @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group. +*/ +Phaser.Group.prototype.addMultiple = function (children, silent) { + + if (children instanceof Phaser.Group) + { + children.moveAll(this, silent); + } + else if (Array.isArray(children)) + { + for (var i = 0; i < children.length; i++) + { + this.add(children[i], silent); + } + } + + return children; + +}; + +/** +* Returns the child found at the given index within this group. +* +* @method Phaser.Group#getAt +* @param {integer} index - The index to return the child from. +* @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index. +*/ +Phaser.Group.prototype.getAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + return -1; + } + else + { + return this.getChildAt(index); + } + +}; + +/** +* Creates a new Phaser.Sprite object and adds it to the top of this group. +* +* Use {@link #classType} to change the type of object created. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#create +* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. +* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {boolean} [exists=true] - The default exists state of the Sprite. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed. +*/ +Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) { + + if (exists === undefined) { exists = true; } + + var child = new this.classType(this.game, x, y, key, frame); + + child.exists = exists; + child.visible = exists; + child.alive = exists; + + return this.add(child, false, index); + +}; + +/** +* Creates multiple Phaser.Sprite objects and adds them to the top of this Group. +* +* This method is useful if you need to quickly generate a pool of sprites, such as bullets. +* +* Use {@link #classType} to change the type of object created. +* +* You can provide an array as the `key` and / or `frame` arguments. When you do this +* it will create `quantity` Sprites for every key (and frame) in the arrays. +* +* For example: +* +* `createMultiple(25, ['ball', 'carrot'])` +* +* In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be +* created in total, 25 of each. You can also have the `frame` as an array: +* +* `createMultiple(5, 'bricks', [0, 1, 2, 3])` +* +* In the above there is one key (bricks), which is a sprite sheet. The frames array tells +* this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because +* the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with +* frame 1, and so on. +* +* If you set both the key and frame arguments to be arrays then understand it will create +* a total quantity of sprites equal to the size of both arrays times each other. I.e.: +* +* `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` +* +* The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. +* It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. +* In total it will have created 120 sprites. +* +* By default the Sprites will have their `exists` property set to `false`, and they will be +* positioned at 0x0, relative to the `Group.x / y` values. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#createMultiple +* @param {integer} quantity - The number of Sprites to create. +* @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. +* @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. +* @param {boolean} [exists=false] - The default exists state of the Sprite. +* @param {function} [callback] - The function that will be called for each applicable child. It will be passed the new child and the loop index (0 through quantity - 1). +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). The default context is the new child. +* @return {array} An array containing all of the Sprites that were created. +*/ +Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, callback, callbackContext) { + + if (frame === undefined) { frame = 0; } + if (exists === undefined) { exists = false; } + + if (!Array.isArray(key)) + { + key = [ key ]; + } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + + var _this = this; + var children = []; + + key.forEach(function(singleKey) { + + frame.forEach(function(singleFrame) { + + for (var i = 0; i < quantity; i++) + { + var child = _this.create(0, 0, singleKey, singleFrame, exists); + + if (callback) { callback.call(callbackContext || child, child, i); } + + children.push(child); + } + + }); + + }); + + return children; + +}; + +/** +* Internal method that re-applies all of the children's Z values. +* +* This must be called whenever children ordering is altered so that their `z` indices are correctly updated. +* +* @method Phaser.Group#updateZ +* @protected +*/ +Phaser.Group.prototype.updateZ = function () { + + var i = this.children.length; + + while (i--) + { + this.children[i].z = i; + } + +}; + +/** +* This method iterates through all children in the Group (regardless if they are visible or exist) +* and then changes their position so they are arranged in a Grid formation. Children must have +* the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have +* this. +* +* The grid dimensions are determined by the first four arguments. The `width` and `height` arguments +* relate to the width and height of the grid respectively. +* +* For example if the Group had 100 children in it: +* +* `Group.align(10, 10, 32, 32)` +* +* This will align all of the children into a grid formation of 10x10, using 32 pixels per +* grid cell. If you want a wider grid, you could do: +* +* `Group.align(25, 4, 32, 32)` +* +* This will align the children into a grid of 25x4, again using 32 pixels per grid cell. +* +* You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method +* to keep on aligning children until there are no children left. For example if this Group had +* 48 children in it, the following: +* +* `Group.align(-1, 8, 32, 32)` +* +* ... will align the children so that there are 8 children vertically (the second argument), +* and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) +* +* You can also do: +* +* `Group.align(10, -1, 32, 32)` +* +* In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit +* all of the children in. +* +* The `position` property allows you to control where in each grid cell the child is positioned. +* This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, +* `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, +* `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* +* The final argument; `offset` lets you start the alignment from a specific child index. +* +* @method Phaser.Group#align +* @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. +* @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. +* @param {integer} cellWidth - The width of each grid cell, in pixels. +* @param {integer} cellHeight - The height of each grid cell, in pixels. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. +* @return {boolean} True if the Group children were aligned, otherwise false. +*/ +Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, position, offset) { + + if (position === undefined) { position = Phaser.TOP_LEFT; } + if (offset === undefined) { offset = 0; } + + if (this.children.length === 0 || offset > this.children.length || (width === -1 && height === -1)) + { + return false; + } + + var r = new Phaser.Rectangle(0, 0, cellWidth, cellHeight); + var w = (width * cellWidth); + var h = (height * cellHeight); + + for (var i = offset; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child['alignIn']) + { + child.alignIn(r, position); + } + else + { + continue; + } + + if (width === -1) + { + // We keep laying them out horizontally until we've done them all + r.y += cellHeight; + + if (r.y === h) + { + r.x += cellWidth; + r.y = 0; + } + } + else if (height === -1) + { + // We keep laying them out vertically until we've done them all + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + } + } + else + { + // We keep laying them out until we hit the column limit + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + + if (r.y === h) + { + // We've hit the column limit, so return, even if there are children left + return true; + } + } + } + } + + return true; + +}; + +/** +* Sets the group cursor to the first child in the group. +* +* If the optional index parameter is given it sets the cursor to the object at that index instead. +* +* @method Phaser.Group#resetCursor +* @param {integer} [index=0] - Set the cursor to point to a specific index. +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.resetCursor = function (index) { + + if (index === undefined) { index = 0; } + + if (index > this.children.length - 1) + { + index = 0; + } + + if (this.cursor) + { + this.cursorIndex = index; + this.cursor = this.children[this.cursorIndex]; + return this.cursor; + } + +}; + +/** +* Advances the group cursor to the next (higher) object in the group. +* +* If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). +* +* @method Phaser.Group#next +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.next = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex >= this.children.length - 1) + { + this.cursorIndex = 0; + } + else + { + this.cursorIndex++; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Moves the group cursor to the previous (lower) child in the group. +* +* If the cursor is at the start of the group (bottom child) it is moved to the end (top child). +* +* @method Phaser.Group#previous +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.previous = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex === 0) + { + this.cursorIndex = this.children.length - 1; + } + else + { + this.cursorIndex--; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Swaps the position of two children in this group. +* +* Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. +* +* @method Phaser.Group#swap +* @param {any} child1 - The first child to swap. +* @param {any} child2 - The second child to swap. +*/ +Phaser.Group.prototype.swap = function (child1, child2) { + + this.swapChildren(child1, child2); + this.updateZ(); + +}; + +/** +* Brings the given child to the top of this group so it renders above all other children. +* +* @method Phaser.Group#bringToTop +* @param {any} child - The child to bring to the top of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.bringToTop = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length) + { + this.remove(child, false, true); + this.add(child, true); + } + + return child; + +}; + +/** +* Sends the given child to the bottom of this group so it renders below all other children. +* +* @method Phaser.Group#sendToBack +* @param {any} child - The child to send to the bottom of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.sendToBack = function (child) { + + if (child.parent === this && this.getIndex(child) > 0) + { + this.remove(child, false, true); + this.addAt(child, 0, true); + } + + return child; + +}; + +/** +* Moves the given child up one place in this group unless it's already at the top. +* +* @method Phaser.Group#moveUp +* @param {any} child - The child to move up in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveUp = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length - 1) + { + var a = this.getIndex(child); + var b = this.getAt(a + 1); + + if (b) + { + this.swap(child, b); + } + } + + return child; + +}; + +/** +* Moves the given child down one place in this group unless it's already at the bottom. +* +* @method Phaser.Group#moveDown +* @param {any} child - The child to move down in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveDown = 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; + +}; + +/** +* Positions the child found at the given index within this group to the given x and y coordinates. +* +* @method Phaser.Group#xy +* @param {integer} index - The index of the child in the group to set the position of. +* @param {number} x - The new x position of the child. +* @param {number} y - The new y position of the 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; + } + +}; + +/** +* Reverses all children in this group. +* +* This operation applies only to immediate children and does not propagate to subgroups. +* +* @method Phaser.Group#reverse +*/ +Phaser.Group.prototype.reverse = function () { + + this.children.reverse(); + this.updateZ(); + +}; + +/** +* Get the index position of the given child in this group, which should match the child's `z` property. +* +* @method Phaser.Group#getIndex +* @param {any} child - The child to get the index for. +* @return {integer} The index of the child or -1 if it's not a member of this group. +*/ +Phaser.Group.prototype.getIndex = function (child) { + + return this.children.indexOf(child); + +}; + +/** +* Searches the Group for the first instance of a child with the `name` +* property matching the given argument. Should more than one child have +* the same name only the first instance is returned. +* +* @method Phaser.Group#getByName +* @param {string} name - The name to search for. +* @return {any} The first child with a matching name, or null if none were found. +*/ +Phaser.Group.prototype.getByName = function (name) { + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].name === name) + { + return this.children[i]; + } + } + + return null; + +}; + +/** +* Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#replace +* @param {any} oldChild - The child in this group that will be replaced. +* @param {any} newChild - The child to be inserted into this group. +* @return {any} Returns the oldChild that was replaced within this group. +*/ +Phaser.Group.prototype.replace = function (oldChild, newChild) { + + var index = this.getIndex(oldChild); + + if (index !== -1) + { + if (newChild.parent) + { + if (newChild.parent instanceof Phaser.Group) + { + newChild.parent.remove(newChild); + } + else + { + newChild.parent.removeChild(newChild); + } + } + + this.remove(oldChild); + + this.addAt(newChild, index); + + return oldChild; + } + +}; + +/** +* Checks if the child has the given property. +* +* Will scan up to 4 levels deep only. +* +* @method Phaser.Group#hasProperty +* @param {any} child - The child to check for the existence of the property on. +* @param {string[]} key - An array of strings that make up the property. +* @return {boolean} True if the child has the property, otherwise false. +*/ +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; + +}; + +/** +* Sets a property to the given value on the child. The operation parameter controls how the value is set. +* +* The operations are: +* - 0: set the existing value to the given value; if force is `true` a new property will be created if needed +* - 1: will add the given value to the value already present. +* - 2: will subtract the given value from the value already present. +* - 3: will multiply the value already present by the given value. +* - 4: will divide the value already present by the given value. +* +* @method Phaser.Group#setProperty +* @param {any} child - The child to set the property value on. +* @param {array} key - An array of strings that make up the property that will be set. +* @param {any} value - The value that will be set. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) { + + if (force === undefined) { force = false; } + + operation = operation || 0; + + // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration. + + // 0 = Equals + // 1 = Add + // 2 = Subtract + // 3 = Multiply + // 4 = Divide + + // We can't force a property in and the child doesn't have it, so abort. + // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too. + 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; + +}; + +/** +* Checks a property for the given value on the child. +* +* @method Phaser.Group#checkProperty +* @param {any} child - The child to check the property value on. +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} True if `child` is a child of this Group and the property was equal to value, false if not. +*/ +Phaser.Group.prototype.checkProperty = function (child, key, value, force) { + + if (force === undefined) { force = false; } + + if (this !== child.parent) + { + return false; + } + + var result = Phaser.Utils.getProperty(child, key); + + if (((result === undefined) && force) || (result !== value)) + { + return false; + } + + return true; + +}; + +/** +* Quickly set a property on a single child of this group to a new value. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#set +* @param {Phaser.Sprite} child - The child to set the property on. +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true. +* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) { + + if (force === undefined) { force = false; } + + key = key.split('.'); + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible))) + { + return this.setProperty(child, key, value, operation, force); + } + +}; + +/** +* Quickly set the same property across all children of this group to a new value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. +* If you need that ability please see `Group.setAllChildren`. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAll +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + key = key.split('.'); + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + this.setProperty(this.children[i], key, value, operation, force); + } + } + +}; + +/** +* Quickly set the same property across all children of this group, and any child Groups, to a new value. +* +* If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. +* Unlike with `setAll` the property is NOT set on child Groups itself. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAllChildren +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + if (this.children[i] instanceof Phaser.Group) + { + this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force); + } + else + { + this.setProperty(this.children[i], key.split('.'), value, operation, force); + } + } + } + +}; + +/** +* Test that the same property across all children of this group is equal to the given value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAll +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} - True if all eligible children have the given property value (but see `force`); otherwise false. +*/ +Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (!this.checkProperty(child, key, value, force)) + { + return false; + } + } + } + + return true; + +}; + +/** +* Test that at least one child of this group has the given property value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAny +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @return {boolean} - True if at least one eligible child has the given property value; otherwise false. +*/ +Phaser.Group.prototype.checkAny = function (key, value, checkAlive, checkVisible) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (this.checkProperty(child, key, value)) + { + return true; + } + } + } + + return false; + +}; + +/** +* Adds the amount to the given property on all children in this group. +* +* `Group.addAll('x', 10)` will add 10 to the child.x value for each child. +* +* @method Phaser.Group#addAll +* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. +* @param {boolean} [checkAlive] - If true the property will only be changed if the child is alive. +* @param {boolean} [checkVisible] - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 1); + +}; + +/** +* Subtracts the amount from the given property on all children in this group. +* +* `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. +* +* @method Phaser.Group#subAll +* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 2); + +}; + +/** +* Multiplies the given property by the amount on all children in this group. +* +* `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. +* +* @method Phaser.Group#multiplyAll +* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 3); + +}; + +/** +* Divides the given property by the amount on all children in this group. +* +* `Group.divideAll('x', 2)` will half the child.x value for each child. +* +* @method Phaser.Group#divideAll +* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 4); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to false. + * + * @method Phaser.Group#kill + */ +Phaser.Group.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + +}; + +/** + * Kills all children having exists=true. + * + * @method Phaser.Group#killAll + */ +Phaser.Group.prototype.killAll = function () { + + this.callAllExists('kill', true); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to true. + * + * @method Phaser.Group#revive + */ +Phaser.Group.prototype.revive = function () { + + this.alive = true; + this.exists = true; + this.visible = true; + +}; + +/** + * Revives all children having exists=false. + * + * @method Phaser.Group#reviveAll + */ +Phaser.Group.prototype.reviveAll = function () { + + this.callAllExists('revive', false); + +}; + +/** +* Calls {@link #resetChild} on each child (or each existing child). +* +* @method Phaser.Group#resetAll +* @param {number} [x] - The x coordinate to reset each child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset each child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image or texture used by the Sprite during rendering. +* @param {string|number} [frame] - The frame of a sprite sheet or texture atlas. +* @param {boolean} [checkExists=false] - Reset only existing children. +*/ +Phaser.Group.prototype.resetAll = function (x, y, key, frame, checkExists) { + + this.forEach(this.resetChild, this, checkExists, x, y, key, frame); + +}; + +/** +* Calls a function, specified by name, on all children in the group who exist (or do not exist). +* +* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. +* +* @method Phaser.Group#callAllExists +* @param {string} callback - Name of the function on the children to call. +* @param {boolean} existsValue - Only children with exists=existsValue will be called. +* @param {...any} parameter - Additional parameters that will be passed to the callback. +*/ +Phaser.Group.prototype.callAllExists = function (callback, existsValue) { + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].exists === existsValue && this.children[i][callback]) + { + this.children[i][callback].apply(this.children[i], args); + } + } + +}; + +/** +* Returns a reference to a function that exists on a child of the group based on the given callback array. +* +* @method Phaser.Group#callbackFromArray +* @param {object} child - The object to inspect. +* @param {array} callback - The array of function names. +* @param {integer} length - The size of the array (pre-calculated in callAll). +* @protected +*/ +Phaser.Group.prototype.callbackFromArray = function (child, callback, length) { + + // Kinda looks like a Christmas tree + + if (length === 1) + { + if (child[callback[0]]) + { + return child[callback[0]]; + } + } + else if (length === 2) + { + if (child[callback[0]][callback[1]]) + { + return child[callback[0]][callback[1]]; + } + } + else if (length === 3) + { + if (child[callback[0]][callback[1]][callback[2]]) + { + return child[callback[0]][callback[1]][callback[2]]; + } + } + else if (length === 4) + { + if (child[callback[0]][callback[1]][callback[2]][callback[3]]) + { + return child[callback[0]][callback[1]][callback[2]][callback[3]]; + } + } + else if (child[callback]) + { + return child[callback]; + } + + return false; + +}; + +/** +* Calls a function, specified by name, on all on children. +* +* The function is called for all children regardless if they are dead or alive (see callAllExists for different options). +* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. +* +* @method Phaser.Group#callAll +* @param {string} method - Name of the function on the child to call. Deep property lookup is supported. +* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child. +* @param {...any} args - Additional parameters that will be passed to the method. +*/ +Phaser.Group.prototype.callAll = function (method, context) { + + if (method === undefined) + { + return; + } + + // Extract the method into an array + method = method.split('.'); + + var methodLength = method.length; + + if (context === undefined || context === null || context === '') + { + context = null; + } + else + { + // Extract the context into an array + if (typeof context === 'string') + { + context = context.split('.'); + var contextLength = context.length; + } + } + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + var callback = null; + var callbackContext = null; + + for (var i = 0; i < this.children.length; i++) + { + callback = this.callbackFromArray(this.children[i], method, methodLength); + + if (context && callback) + { + callbackContext = this.callbackFromArray(this.children[i], context, contextLength); + + if (callback) + { + callback.apply(callbackContext, args); + } + } + else if (callback) + { + callback.apply(this.children[i], args); + } + } + +}; + +/** +* The core preUpdate - as called by World. +* @method Phaser.Group#preUpdate +* @protected +*/ +Phaser.Group.prototype.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + // This chunk is identical to Phaser.Component.Core.prototype.preUpdateChildren, which is not yet defined. + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + return true; + +}; + +/** +* The core update - as called by World. +* +* Children with `exists = false` are updated unless {@link #updateOnlyExistingChildren} is true. +* +* @method Phaser.Group#update +* @protected +*/ +Phaser.Group.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + var len = this.children.length; + + if (i >= len) { i = len - 1; } + + var child = this.children[i]; + + if (!this.updateOnlyExistingChildren || child.exists) { + child.update(); + } + } + +}; + +/** +* The core postUpdate - as called by World. +* @method Phaser.Group#postUpdate +* @protected +*/ +Phaser.Group.prototype.postUpdate = function () { + + // Fixed to Camera? + if (this.fixedToCamera) + { + this.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; + this.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Find children matching a certain predicate. +* +* For example: +* +* var healthyList = Group.filter(function(child, index, children) { +* return child.health > 10 ? true : false; +* }, true); +* healthyList.callAll('attack'); +* +* Note: Currently this will skip any children which are Groups themselves. +* +* @method Phaser.Group#filter +* @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third +* @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. +* @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for +*/ +Phaser.Group.prototype.filter = function (predicate, checkExists) { + + var index = -1; + var length = this.children.length; + var results = []; + + while (++index < length) + { + var child = this.children[index]; + + if (!checkExists || (checkExists && child.exists)) + { + if (predicate(child, index, this.children)) + { + results.push(child); + } + } + } + + return new Phaser.ArraySet(results); + +}; + +/** +* Call a function on each child in this group. +* +* Additional arguments for the callback can be specified after the `checkExists` parameter. For example, +* +* Group.forEach(awardBonusGold, this, true, 100, 500) +* +* would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. +* +* Note: This check will skip any children which are Groups themselves. +* +* @method Phaser.Group#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) { + + if (checkExists === undefined) { checkExists = false; } + + if (arguments.length <= 3) + { + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + callback.call(callbackContext, this.children[i]); + } + } + } + else + { + // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE. + // Using an array and pushing each element (not a slice!) is _significantly_ faster. + var args = [null]; + + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + } + } + +}; + +/** +* Call a function on each existing child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachExists +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachExists = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each alive child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachAlive +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each dead child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachDead +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachDead = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Sort the children in the group according to a particular key and ordering. +* +* Call this function to sort the group according to a particular key value and order. +* +* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. +* +* Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including +* alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. +* +* @method Phaser.Group#sort +* @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value. +* @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}). +*/ +Phaser.Group.prototype.sort = function (key, order) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + if (key === undefined) { key = 'z'; } + if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; } + + this._sortProperty = key; + + if (order === Phaser.Group.SORT_ASCENDING) + { + this.children.sort(this.ascendingSortHandler.bind(this)); + } + else + { + this.children.sort(this.descendingSortHandler.bind(this)); + } + + this.updateZ(); + +}; + +/** +* Sort the children in the group according to custom sort function. +* +* The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). +* It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. +* +* @method Phaser.Group#customSort +* @param {function} sortHandler - The custom sort function. +* @param {object} [context=undefined] - The context in which the sortHandler is called. +*/ +Phaser.Group.prototype.customSort = function (sortHandler, context) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + this.children.sort(sortHandler.bind(context)); + + this.updateZ(); + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#ascendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.ascendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return -1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return 1; + } + else + { + if (a.z < b.z) + { + return -1; + } + else + { + return 1; + } + } + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#descendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.descendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return 1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return -1; + } + else + { + return 0; + } + +}; + +/** +* Iterates over the children of the group performing one of several actions for matched children. +* +* A child is considered a match when it has a property, named `key`, whose value is equal to `value` +* according to a strict equality comparison. +* +* The result depends on the `returnType`: +* +* - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}: +* The callback, if any, is applied to all matching children. The number of matched children is returned. +* - {@link Phaser.Group.RETURN_NONE RETURN_NONE}: +* The callback, if any, is applied to all matching children. No value is returned. +* - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}: +* The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. +* If there is no matching child then null is returned. +* +* If `args` is specified it must be an array. The matched child will be assigned to the first +* element and the entire array will be applied to the callback function. +* +* @method Phaser.Group#iterate +* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' +* @param {any} value - A child matches if `child[key] === value` is true. +* @param {integer} returnType - How to iterate the children and what to return. +* @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. +* @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null. +*/ +Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) { + + if (this.children.length === 0) + { + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return 0; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return []; + } + } + + var total = 0; + + if (returnType === Phaser.Group.RETURN_ALL) + { + var output = []; + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i][key] === value) + { + total++; + + if (callback) + { + if (args) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + else + { + callback.call(callbackContext, this.children[i]); + } + } + + if (returnType === Phaser.Group.RETURN_CHILD) + { + return this.children[i]; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + output.push(this.children[i]); + } + } + } + + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return total; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return output; + } + else + { + // RETURN_CHILD or RETURN_NONE + return null; + } + +}; + +/** +* Get the first display object with the given property name and value. +* +* @method Phaser.Group#getFirst +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {DisplayObject} The first child matching the query, or `null` if none were found. +*/ +Phaser.Group.prototype.getFirst = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_CHILD); + +}; + +/** +* Get the first display object that exists, or doesn't exist. +* +* You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstExists +* @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child. +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + if (typeof exists !== 'boolean') + { + exists = true; + } + + var child = this.getFirst('exists', exists); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is alive (`child.alive === true`). +* +* This is handy for choosing a squad leader, etc. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstAlive +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', true); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is dead (`child.alive === false`). +* +* This is handy for checking if everything has been wiped out and adding to the pool as needed. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstDead +* @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', false); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. +* +* If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. +* +* The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. +* +* @method Phaser.Group#resetChild +* @param {DisplayObject} child - The child to reset and/or load the texture on. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}. +*/ +Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) { + + if (child === null) + { + return null; + } + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (x !== null && y !== null) + { + child.reset(x, y); + } + + if (key !== undefined) + { + child.loadTexture(key, frame); + } + + return child; + +}; + +/** +* Return the child at the top of this group. +* +* The top child is the child displayed (rendered) above every other child. +* +* @method Phaser.Group#getTop +* @return {any} The child at the top of the Group. +*/ +Phaser.Group.prototype.getTop = function () { + + if (this.children.length > 0) + { + return this.children[this.children.length - 1]; + } + +}; + +/** +* Returns the child at the bottom of this group. +* +* The bottom child the child being displayed (rendered) below every other child. +* +* @method Phaser.Group#getBottom +* @return {any} The child at the bottom of the Group. +*/ +Phaser.Group.prototype.getBottom = function () { + + if (this.children.length > 0) + { + return this.children[0]; + } + +}; + +/** +* Get the closest child to given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getClosestTo +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child closest to given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContext) { + + var distance = Number.MAX_VALUE; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance < distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the child furthest away from the given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getFurthestFrom +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child furthest from the given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackContext) { + + var distance = 0; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance > distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the number of children with the given property name and value. +* +* @method Phaser.Group#count +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {integer} The number of children matching the query. +*/ +Phaser.Group.prototype.count = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_TOTAL); + +}; + +/** +* Get the number of living children in this group. +* +* @method Phaser.Group#countLiving +* @return {integer} The number of children flagged as alive. +*/ +Phaser.Group.prototype.countLiving = function () { + + return this.count('alive', true); + +}; + +/** +* Get the number of dead children in this group. +* +* @method Phaser.Group#countDead +* @return {integer} The number of children flagged as dead. +*/ +Phaser.Group.prototype.countDead = function () { + + return this.count('alive', false); + +}; + +/** +* Returns a random child from the group. +* +* @method Phaser.Group#getRandom +* @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). +* @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. +* @return {any} A random child of this Group. +*/ +Phaser.Group.prototype.getRandom = function (startIndex, length) { + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = this.children.length; } + + if (length === 0) + { + return null; + } + + return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length); + +}; + +/** +* Returns a random child from the Group that has `exists` set to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only +* the first 50 children in the Group. +* +* @method Phaser.Group#getRandomExists +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up to. +* @return {any} A random child of this Group that exists. +*/ +Phaser.Group.prototype.getRandomExists = function (startIndex, endIndex) { + + var list = this.getAll('exists', true, startIndex, endIndex); + + return this.game.rnd.pick(list); + +}; + +/** +* Returns all children in this Group. +* +* You can optionally specify a matching criteria using the `property` and `value` arguments. +* +* For example: `getAll('exists', true)` would return only children that have an `exists` property equal to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return the first 50 children in the Group. +* If `property` and `value` are also specified, only children within the given index range are searched. +* +* @method Phaser.Group#getAll +* @param {string} [property] - An optional property to test against the value argument. +* @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results. +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up until. +* @return {array} - An array containing all, some, or none of the Children of this Group. +*/ +Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) { + + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var output = []; + + for (var i = startIndex; i < endIndex; i++) + { + var child = this.children[i]; + + if (property) + { + if (child[property] === value) + { + output.push(child); + } + } + else + { + output.push(child); + } + } + + return output; + +}; + +/** +* Removes the given child from this group. +* +* This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. +* +* If the group cursor was referring to the removed child it is updated to refer to the next child. +* +* @method Phaser.Group#remove +* @param {any} child - The child to remove. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child. +* @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event. +* @return {boolean} true if the child was removed from this group, otherwise false. +*/ +Phaser.Group.prototype.remove = function (child, destroy, silent) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + + if (this.children.length === 0 || this.children.indexOf(child) === -1) + { + return false; + } + + if (!silent && child.events && !child.destroyPhase) + { + child.events.onRemovedFromGroup$dispatch(child, this); + } + + var removed = this.removeChild(child); + + this.removeFromHash(child); + + this.updateZ(); + + if (this.cursor === child) + { + this.next(); + } + + if (destroy && removed) + { + removed.destroy(true); + } + + return true; + +}; + +/** +* Moves all children from this Group to the Group given. +* +* @method Phaser.Group#moveAll +* @param {Phaser.Group} group - The new Group to which the children will be moved to. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group. +* @return {Phaser.Group} The Group to which all the children were moved. +*/ +Phaser.Group.prototype.moveAll = function (group, silent) { + + if (silent === undefined) { silent = false; } + + if (this.children.length > 0 && group instanceof Phaser.Group) + { + do + { + group.add(this.children[0], silent); + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + } + + return group; + +}; + +/** +* Removes all children from this Group, but does not remove the group from its parent. +* +* The children can be optionally destroyed as they are removed. +* +* You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've +* more than one Game Object sharing the same BaseTexture. +* +* @method Phaser.Group#removeAll +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +* @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. +*/ +Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + if (destroyTexture === undefined) { destroyTexture = false; } + + if (this.children.length === 0) + { + return; + } + + do + { + if (!silent && this.children[0].events) + { + this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this); + } + + var removed = this.removeChild(this.children[0]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true, destroyTexture); + } + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + +}; + +/** +* Removes all children from this group whose index falls beteen the given startIndex and endIndex values. +* +* @method Phaser.Group#removeBetween +* @param {integer} startIndex - The index to start removing children from. +* @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +*/ +Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) { + + if (endIndex === undefined) { endIndex = this.children.length - 1; } + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = 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 (!silent && this.children[i].events) + { + this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this); + } + + var removed = this.removeChild(this.children[i]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true); + } + + if (this.cursor === this.children[i]) + { + this.cursor = null; + } + + i--; + } + + this.updateZ(); + +}; + +/** + * Places each child at a random position within the given Rectangle (or the {@link Phaser.World#bounds World bounds}). + * + * @method Phaser.Group#scatter + * @param {Phaser.Rectangle} [rect=this.game.world.bounds] - A Rectangle. If omitted {@link Phaser.World#bounds} is used. + * @param {boolean} [checkExists=false] - Place only children with exists=true. + */ +Phaser.Group.prototype.scatter = function (rect, checkExists) { + + if (rect == null) { rect = this.game.world.bounds; } + + this.forEach(function (child) { + + child.position.set(rect.randomX, rect.randomY); + + }, null, checkExists); + +}; + +/** + * Orders this Group's children randomly. + * + * This can be more efficient than calling {@link #getRandom} repeatedly. + * + * @method Phaser.Group#shuffle + */ +Phaser.Group.prototype.shuffle = function () { + + Phaser.ArrayUtils.shuffle(this.children); + this.updateZ(); + +}; + +/** +* Destroys this group. +* +* Removes all children, then removes this group from its parent and nulls references. +* +* @method Phaser.Group#destroy +* @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. +*/ +Phaser.Group.prototype.destroy = function (destroyChildren, soft) { + + if (this.game === null || this.ignoreDestroy) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (soft === undefined) { soft = false; } + + this.onDestroy.dispatch(this, destroyChildren, soft); + + this.removeAll(destroyChildren); + + this.cursor = null; + this.filters = null; + this.pendingDestroy = false; + + if (!soft) + { + if (this.parent) + { + this.parent.removeChild(this); + } + + this.game = null; + this.exists = false; + } + +}; + +/** +* Total number of existing children in the group. +* +* @name Phaser.Group#total +* @property {integer} total +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "total", { + + get: function () { + + return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); + + } + +}); + +/** +* Total number of children in this group, regardless of exists/alive status. +* +* @name Phaser.Group#length +* @property {integer} length +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "length", { + + get: function () { + + return this.children.length; + + } + +}); + +/** +* The angle of rotation of the group container, in degrees. +* +* This adjusts the group itself by modifying its local rotation transform. +* +* This has no impact on the rotation/angle properties of the children, but it will update their worldTransform +* and on-screen orientation and position. +* +* @name Phaser.Group#angle +* @property {number} angle +*/ +Object.defineProperty(Phaser.Group.prototype, "angle", { + + get: function() { + return Phaser.Math.radToDeg(this.rotation); + }, + + set: function(value) { + this.rotation = Phaser.Math.degToRad(value); + } + +}); + +/** +* The center x coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerX +* @property {number} centerX +*/ +Object.defineProperty(Phaser.Group.prototype, "centerX", { + + get: function () { + + return this.getBounds(this.parent).centerX; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.halfWidth; + + } + +}); + +/** +* The center y coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerY +* @property {number} centerY +*/ +Object.defineProperty(Phaser.Group.prototype, "centerY", { + + get: function () { + + return this.getBounds(this.parent).centerY; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.halfHeight; + + } + +}); + +/** +* The left coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#left +* @property {number} left +*/ +Object.defineProperty(Phaser.Group.prototype, "left", { + + get: function () { + + return this.getBounds(this.parent).left; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = value + offset; + + } + +}); + +/** +* The right coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#right +* @property {number} right +*/ +Object.defineProperty(Phaser.Group.prototype, "right", { + + get: function () { + + return this.getBounds(this.parent).right; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.width; + + } + +}); + +/** +* The top coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#top +* @property {number} top +*/ +Object.defineProperty(Phaser.Group.prototype, "top", { + + get: function () { + + return this.getBounds(this.parent).top; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset); + + } + +}); + +/** +* The bottom coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#bottom +* @property {number} bottom +*/ +Object.defineProperty(Phaser.Group.prototype, "bottom", { + + get: function () { + + return this.getBounds(this.parent).bottom; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.height; + + } + +}); + +/** +* Aligns this Group within another Game Object, or Rectangle, known as the +* 'container', to one of 9 possible positions. +* +* The container must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the container. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, +* `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, +* `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* container, taking into consideration rotation and scale of its children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignIn +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* Aligns this Group to the side of another Game Object, or Rectangle, known as the +* 'parent', in one of 11 possible positions. +* +* The parent must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the parent. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, +* `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, +* `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` +* and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* parent, taking into consideration rotation and scale of the children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignTo +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* A display object is any object that can be rendered in the Phaser/pixi.js scene graph: +* +* - {@link PIXI.DisplayObject} +* - {@link PIXI.DisplayObjectContainer} +* - {@link Phaser.BitmapText} +* - {@link Phaser.Creature} +* - {@link Phaser.Graphics} +* - {@link Phaser.Group} +* - {@link Phaser.FlexLayer} +* - {@link Phaser.Particles.Arcade.Emitter} +* - {@link Phaser.Physics.P2.BodyDebug} +* - {@link Phaser.SpriteBatch} +* - {@link Phaser.World} +* - {@link Phaser.Rope} +* - {@link Phaser.Stage} +* - {@link PIXI.Sprite} +* - {@link Phaser.Image} +* - {@link Phaser.Button} +* - {@link Phaser.Sprite} +* - {@link Phaser.Bullet} +* - {@link Phaser.Particle} +* - {@link Phaser.Text} +* - {@link Phaser.TilemapLayer} +* - {@link Phaser.TileSprite} +* +* @typedef {object} DisplayObject +*/ +// Documentation stub for linking. + +/** +* The x coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#x +* @property {number} x +*/ + +/** +* The y coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#y +* @property {number} y +*/ + +/** +* The angle of rotation of the group container, in radians. +* +* This will adjust the group container itself by modifying its rotation. +* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#rotation +* @property {number} rotation +*/ + +/** +* The visible state of the group. Non-visible Groups and all of their children are not rendered. +* +* @name Phaser.Group#visible +* @property {boolean} visible +*/ + +/** +* The alpha value of the group container. +* +* @name Phaser.Group#alpha +* @property {number} alpha +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* "This world is but a canvas to our imagination." - Henry David Thoreau +* +* A game has only one world. The world is an abstract place in which all game objects live. It is not bound +* by stage limits and can be any size. You look into the world via cameras. All game objects live within +* the world at world-based coordinates. By default a world is created the same size as your Stage. +* +* @class Phaser.World +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.World = function (game) { + + Phaser.Group.call(this, game, null, '__world', false); + + /** + * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. + * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. + * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. + * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. + * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height); + + /** + * @property {Phaser.Camera} camera - Camera instance. + */ + this.camera = null; + + /** + * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. + * @readonly + */ + this._definedSize = false; + + /** + * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._width = game.width; + + /** + * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._height = game.height; + + this.game.state.onStateChange.add(this.stateChange, this); + +}; + +Phaser.World.prototype = Object.create(Phaser.Group.prototype); +Phaser.World.prototype.constructor = Phaser.World; + +/** +* Initialises the game world. +* +* @method Phaser.World#boot +* @protected +*/ +Phaser.World.prototype.boot = function () { + + this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height); + + this.game.stage.addChild(this); + + this.camera.boot(); + +}; + +/** +* Called whenever the State changes or resets. +* +* It resets the world.x and world.y coordinates back to zero, +* then resets the Camera. +* +* @method Phaser.World#stateChange +* @protected +*/ +Phaser.World.prototype.stateChange = function () { + + this.x = 0; + this.y = 0; + + this.camera.reset(); + +}; + +/** +* Updates the size of this world and sets World.x/y to the given values +* The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. +* +* @method Phaser.World#setBounds +* @param {number} x - Top left most corner of the world. +* @param {number} y - Top left most corner of the world. +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.setBounds = function (x, y, width, height) { + + this._definedSize = true; + this._width = width; + this._height = height; + + this.bounds.setTo(x, y, width, height); + + this.x = x; + this.y = y; + + if (this.camera.bounds) + { + // The Camera can never be smaller than the game size + this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height)); + } + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Updates this world's width and height (but not smaller than any previous {@link #setBounds defined size}). +* +* Phaser uses this to adapt to {@link Phaser.ScaleManager#updateDimensions layout changes}. +* You probably want to use {@link #setBounds} instead. +* +* @method Phaser.World#resize +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.resize = function (width, height) { + + // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size + + if (this._definedSize) + { + if (width < this._width) + { + width = this._width; + } + + if (height < this._height) + { + height = this._height; + } + } + + this.bounds.width = width; + this.bounds.height = height; + + this.game.camera.setBoundsToWorld(); + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Destroyer of worlds. +* +* @method Phaser.World#shutdown +*/ +Phaser.World.prototype.shutdown = function () { + + // World is a Group, so run a soft destruction on this and all children. + this.destroy(true, true); + +}; + +/** +* This will take the given game object and check if its x/y coordinates fall outside of the world bounds. +* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. +* If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. +* +* Please understand there are limitations to this method. For example if you have scaled the World +* then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. +* +* @method Phaser.World#wrap +* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) { + + if (padding === undefined) { padding = 0; } + if (useBounds === undefined) { useBounds = false; } + if (horizontal === undefined) { horizontal = true; } + if (vertical === undefined) { vertical = true; } + + if (!useBounds) + { + if (horizontal && sprite.x + padding < this.bounds.x) + { + sprite.x = this.bounds.right + padding; + } + else if (horizontal && sprite.x - padding > this.bounds.right) + { + sprite.x = this.bounds.left - padding; + } + + if (vertical && sprite.y + padding < this.bounds.top) + { + sprite.y = this.bounds.bottom + padding; + } + else if (vertical && sprite.y - padding > this.bounds.bottom) + { + sprite.y = this.bounds.top - padding; + } + } + else + { + sprite.getBounds(); + + if (horizontal) + { + if ((sprite.x + sprite._currentBounds.width) < this.bounds.x) + { + sprite.x = this.bounds.right; + } + else if (sprite.x > this.bounds.right) + { + sprite.x = this.bounds.left; + } + } + + if (vertical) + { + if ((sprite.y + sprite._currentBounds.height) < this.bounds.top) + { + sprite.y = this.bounds.bottom; + } + else if (sprite.y > this.bounds.bottom) + { + sprite.y = this.bounds.top; + } + } + } + +}; + +/** +* @method Phaser.World#wrapAll +* @param {Phaser.Group} group - A group of sprites. +* @param {boolean} [checkExists=false] - Wrap only sprites having `exists=true`. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrapAll = function (group, checkExists, padding, useBounds, horizontal, vertical) { + + group.forEach(this.wrap, this, checkExists, padding, useBounds, horizontal, vertical); + +}; + +/** +* @name Phaser.World#width +* @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "width", { + + get: function () { + return this.bounds.width; + }, + + set: function (value) { + + if (value < this.game.width) + { + value = this.game.width; + } + + this.bounds.width = value; + this._width = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#height +* @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "height", { + + get: function () { + return this.bounds.height; + }, + + set: function (value) { + + if (value < this.game.height) + { + value = this.game.height; + } + + this.bounds.height = value; + this._height = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#centerX +* @property {number} centerX - Gets the X position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerX", { + + get: function () { + return this.bounds.halfWidth + this.bounds.x; + } + +}); + +/** +* @name Phaser.World#centerY +* @property {number} centerY - Gets the Y position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerY", { + + get: function () { + return this.bounds.halfHeight + this.bounds.y; + } + +}); + +/** +* @name Phaser.World#randomX +* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomX", { + + get: function () { + + if (this.bounds.x < 0) + { + return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x))); + } + else + { + return this.game.rnd.between(this.bounds.x, this.bounds.width); + } + + } + +}); + +/** +* @name Phaser.World#randomY +* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomY", { + + get: function () { + + if (this.bounds.y < 0) + { + return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y))); + } + else + { + return this.game.rnd.between(this.bounds.y, this.bounds.height); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Game object is the main controller for the entire Phaser game. It is responsible +* for handling the boot process, parsing the configuration values, creating the renderer, +* and setting-up all of the Phaser systems, such as physics, sound and input. +* Once that is complete it will start the default State, and then begin the main game loop. +* +* You can access lots of the Phaser systems via the properties on the `game` object. For +* example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on. +* +* Anywhere you can access the `game` property, you can access all of these core systems. +* For example a Sprite has a `game` property, allowing you to talk to the various parts +* of Phaser directly, without having to look after your own references. +* +* In it's most simplest form, a Phaser game can be created by providing the arguments +* to the constructor: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create }); +* ``` +* +* In the example above it is passing in a State object directly. You can also use the State +* Manager to do this: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO); +* game.state.add('Boot', BasicGame.Boot); +* game.state.add('Preloader', BasicGame.Preloader); +* game.state.add('MainMenu', BasicGame.MainMenu); +* game.state.add('Game', BasicGame.Game); +* game.state.start('Boot'); +* ``` +* +* In the example above, 4 States are added to the State Manager, and Phaser is told to +* start running the `Boot` state when it has finished initializing. There are example +* project templates you can use in the Phaser GitHub repo, inside the `resources` folder. +* +* Instead of specifying arguments you can also pass {@link GameConfig a single object} instead: +* +* ```javascript +* var config = { +* width: 800, +* height: 600, +* renderer: Phaser.AUTO, +* antialias: true, +* multiTexture: true, +* state: { +* preload: preload, +* create: create, +* update: update +* } +* } +* +* var game = new Phaser.Game(config); +* ``` +* +* @class Phaser.Game +* @constructor +* @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. +* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. +* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). +* @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body. +* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. +* @param {boolean} [transparent=false] - Use a transparent canvas background or not. +* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) { + + /** + * @property {number} id - Phaser Game ID + * @readonly + */ + this.id = Phaser.GAMES.push(this) - 1; + + /** + * @property {object} config - The Phaser.Game configuration object. + */ + this.config = null; + + /** + * @property {object} physicsConfig - The Phaser.Physics.World configuration object. + */ + this.physicsConfig = physicsConfig; + + /** + * @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted. + * @readonly + * @default + */ + this.parent = ''; + + /** + * The current Game Width in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} width + * @readonly + * @default + */ + this.width = 800; + + /** + * The current Game Height in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} height + * @readonly + * @default + */ + this.height = 600; + + /** + * The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object. + * + * @property {integer} resolution + * @readonly + * @default + */ + this.resolution = 1; + + /** + * @property {integer} _width - Private internal var. + * @private + */ + this._width = 800; + + /** + * @property {integer} _height - Private internal var. + * @private + */ + this._height = 600; + + /** + * @property {boolean} transparent - Use a transparent canvas background or not. + * @default + */ + this.transparent = false; + + /** + * @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead. + * @readonly + * @default + */ + this.antialias = true; + + /** + * Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property. + * To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game + * Configuration object with the property `multiTexture` set to true. It has to be enabled before + * Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it + * via the `game.renderer.setTexturePriority` method. + * + * @property {boolean} multiTexture + * @readonly + * @default + */ + this.multiTexture = false; + + /** + * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * @default + */ + this.preserveDrawingBuffer = false; + + /** + * Clear the Canvas each frame before rendering the display list. + * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. + * This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage. + * @property {boolean} clearBeforeRender + * @default + */ + this.clearBeforeRender = true; + + /** + * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. + * @protected + */ + this.renderer = null; + + /** + * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `render` hooks but not `preRender` or `postRender`; set {@link lockRender} to skip those as well. + * @readonly + */ + this.renderType = Phaser.AUTO; + + /** + * @property {Phaser.StateManager} state - The StateManager. + */ + this.state = null; + + /** + * @property {boolean} isBooted - Whether the game engine is booted, aka available. + * @readonly + */ + this.isBooted = false; + + /** + * @property {boolean} isRunning - Is game running or paused? + * @readonly + */ + this.isRunning = false; + + /** + * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout + * @protected + */ + this.raf = null; + + /** + * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. + */ + this.make = null; + + /** + * @property {Phaser.Cache} cache - Reference to the assets cache. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - Reference to the input manager + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - Reference to the assets loader. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - Reference to the math helper. + */ + this.math = null; + + /** + * @property {Phaser.Net} net - Reference to the network class. + */ + this.net = null; + + /** + * @property {Phaser.ScaleManager} scale - The game scale manager. + */ + this.scale = null; + + /** + * @property {Phaser.SoundManager} sound - Reference to the sound manager. + */ + this.sound = null; + + /** + * @property {Phaser.Stage} stage - Reference to the stage. + */ + this.stage = null; + + /** + * @property {Phaser.Time} time - Reference to the core game clock. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - Reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - Reference to the world. + */ + this.world = null; + + /** + * @property {Phaser.Physics} physics - Reference to the physics manager. + */ + this.physics = null; + + /** + * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. + */ + this.plugins = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. + */ + this.rnd = null; + + /** + * @property {Phaser.Device} device - Contains device information and capabilities. + */ + this.device = Phaser.Device; + + /** + * @property {Phaser.Camera} camera - A handy reference to world.camera. + */ + this.camera = null; + + /** + * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) + */ + this.context = null; + + /** + * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. + */ + this.debug = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. + */ + this.particles = null; + + /** + * @property {Phaser.Create} create - The Asset Generator. + */ + this.create = null; + + /** + * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. + * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. + * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. + * @property {boolean} lockRender + * @default + */ + this.lockRender = false; + + /** + * @property {boolean} pendingDestroy - Destroy the game at the next update. + * @default + */ + this.pendingDestroy = false; + + /** + * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). + * @default + * @readonly + */ + this.stepping = false; + + /** + * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. + * @default + * @readonly + */ + this.pendingStep = false; + + /** + * @property {number} stepCount - When stepping is enabled this contains the current step cycle. + * @default + * @readonly + */ + this.stepCount = 0; + + /** + * @property {Phaser.Signal} onPause - This event is fired when the game pauses. + */ + this.onPause = null; + + /** + * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. + */ + this.onResume = null; + + /** + * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). + */ + this.onBlur = null; + + /** + * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). + */ + this.onFocus = null; + + /** + * @property {boolean} _paused - Is game paused? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _codePaused - Was the game paused via code or a visibility change? + * @private + */ + this._codePaused = false; + + /** + * The ID of the current/last logic update applied this animation frame, starting from 0. + * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` + * @property {integer} currentUpdateID + * @protected + */ + this.currentUpdateID = 0; + + /** + * Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed). + * @property {integer} updatesThisFrame + * @protected + */ + this.updatesThisFrame = 1; + + /** + * Number of renders expected to occur this animation frame. May be 0 if {@link #dropFrames is on} or {@link #forceSingleRender} is off; otherwise it will be 1. + * @property {integer} updatesThisFrame + * @protected + */ + this.rendersThisFrame = 1; + + /** + * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. + * @private + */ + this._deltaTime = 0; + + /** + * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. + * @private + */ + this._lastCount = 0; + + /** + * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. + * @private + */ + this._spiraling = 0; + + /** + * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) + * @private + */ + this._kickstart = true; + + /** + * If the game is struggling to maintain the desired FPS, this signal will be dispatched. + * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. + * @property {Phaser.Signal} fpsProblemNotifier + * @public + */ + this.fpsProblemNotifier = new Phaser.Signal(); + + /** + * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? You can toggle it on the fly. + */ + this.forceSingleUpdate = true; + + /** + * @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update? (During spiraling conditions, {@link #dropFrames} is used instead.) + */ + this.forceSingleRender = true; + + /** + * @property {boolean} dropFrames - When {@link #forceSingleUpdate} is off, skip {@link #updateRender rendering} if logic updates are spiraling upwards. + */ + this.dropFrames = false; + + /** + * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. + * @private + */ + this._nextFpsNotification = 0; + + // Parse the configuration object (if any) + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + this.parseConfig(arguments[0]); + } + else + { + this.config = { enableDebug: true }; + + if (typeof width !== 'undefined') + { + this._width = width; + } + + if (typeof height !== 'undefined') + { + this._height = height; + } + + if (typeof renderer !== 'undefined') + { + 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); + } + + this.device.whenReady(this.boot, this); + + return this; + +}; + +/** +* A configuration object for {@link Phaser.Game}. +* +* @typedef {object} GameConfig +* @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}. +* @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}. +* @property {number|string} [GameConfig.antialias=true] +* @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}. +* @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in. +* @property {string} [GameConfig.canvasId] - `id` attribute value to assign to the game canvas. +* @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas. +* @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}. +* @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange} +* @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing. +* @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production. +* @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO. +* @property {boolean} [GameConfig.forceSetTimeout] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeOut} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available. +* @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen. +* @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked. +* @property {number|string} [GameConfig.height=600] +* @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`. +* @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected. +* @property {object} [GameConfig.physicsConfig] +* @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering. +* @property {number} [GameConfig.renderer=Phaser.AUTO] +* @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels. +* @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices. +* @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen. +* @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}. +* @property {object} [GameConfig.state] +* @property {boolean} [GameConfig.transparent=false] +* @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode. +* @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode. +* @property {number|string} [GameConfig.width=800] +*/ +// Documentation stub for linking. + +Phaser.Game.prototype = { + + /** + * Parses a Game configuration object. + * + * @method Phaser.Game#parseConfig + * @protected + */ + parseConfig: function (config) { + + this.config = config; + + if (config['enableDebug'] === undefined) + { + this.config.enableDebug = true; + } + + if (config['width']) + { + this._width = config['width']; + } + + if (config['height']) + { + this._height = config['height']; + } + + if (config['renderer']) + { + this.renderType = config['renderer']; + } + + if (config['parent']) + { + this.parent = config['parent']; + } + + if (config['transparent'] !== undefined) + { + this.transparent = config['transparent']; + } + + if (config['antialias'] !== undefined) + { + this.antialias = config['antialias']; + } + + if (config['multiTexture'] !== undefined) + { + this.multiTexture = config['multiTexture']; + } + + if (config['resolution']) + { + this.resolution = config['resolution']; + } + + if (config['preserveDrawingBuffer'] !== undefined) + { + this.preserveDrawingBuffer = config['preserveDrawingBuffer']; + } + + 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); + + }, + + /** + * Initialize engine sub modules and start the game. + * + * @method Phaser.Game#boot + * @protected + */ + boot: function () { + + if (this.isBooted) + { + return; + } + + this.onPause = new Phaser.Signal(); + this.onResume = new Phaser.Signal(); + this.onBlur = new Phaser.Signal(); + this.onFocus = new Phaser.Signal(); + + this.isBooted = true; + + PIXI.game = this; + + this.math = Phaser.Math; + + this.scale = new Phaser.ScaleManager(this, this._width, this._height); + this.stage = new Phaser.Stage(this); + + this.setUpRenderer(); + + 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.create = new Phaser.Create(this); + this.plugins = new Phaser.PluginManager(this); + this.net = new Phaser.Net(this); + + this.time.boot(); + this.stage.boot(); + this.world.boot(); + this.scale.boot(); + this.input.boot(); + this.sound.boot(); + this.state.boot(); + + if (this.config['enableDebug']) + { + this.debug = new Phaser.Utils.Debug(this); + this.debug.boot(); + } + else + { + this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {}, isDisabled: true }; + } + + 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._kickstart = true; + + if (window['focus']) + { + if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus)) + { + window.focus(); + } + } + + if (this.config['disableStart']) + { + return; + } + + if (this.cache.isReady) + { + this.raf.start(); + } + else + { + this.cache.onReady.addOnce(function () { + this.raf.start(); + }, this); + } + + }, + + /** + * Displays a Phaser version debug header in the console. + * + * @method Phaser.Game#showDebugHeader + * @protected + */ + showDebugHeader: function () { + + if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner) + { + return; + } + + 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.ie) // https://developer.mozilla.org/en-US/docs/Web/API/Console/log#Browser_compatibility + { + var args = [ + '%c %c %c Phaser CE v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665', + 'background: #fb8cb3', + 'background: #d44a52', + 'color: #ffffff; background: #871905;', + 'background: #d44a52', + 'background: #fb8cb3', + 'background: #ffffff' + ]; + + for (var i = 0; i < 3; i++) + { + if (i < c) + { + args.push('color: #ff2424; background: #fff'); + } + else + { + args.push('color: #959595; background: #fff'); + } + } + + console.log.apply(console, args); + } + else if (window['console']) + { + console.log('Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' | http://phaser.io'); + } + + }, + + /** + * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. + * + * @method Phaser.Game#setUpRenderer + * @protected + */ + setUpRenderer: function () { + + if (!this.device.canvas) + { + // Nothing else to do + throw new Error('Phaser.Game - Cannot create Canvas 2d context, aborting.'); + } + + if (this.config['canvas']) + { + this.canvas = this.config['canvas']; + } + else + { + this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true); + } + + if (this.config['canvasStyle']) + { + this.canvas.style = this.config['canvasStyle']; + } + else + { + this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; + } + + if (this.config['crisp']) + { + Phaser.Canvas.setImageRenderingCrisp(this.canvas); + } + + if ((this.renderType === Phaser.WEBGL) || + (this.renderType === Phaser.WEBGL_MULTI) || + (this.renderType === Phaser.AUTO && this.device.webGL)) + { + if (this.multiTexture || this.renderType === Phaser.WEBGL_MULTI) + { + PIXI.enableMultiTexture(); + this.multiTexture = true; + } + + try + { + this.renderer = new PIXI.WebGLRenderer(this, this.config); + this.renderType = Phaser.WEBGL; + this.context = null; + this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); + this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); + } + catch (webGLRendererError) + { + this.renderer = null; + this.multiTexture = false; + PIXI._enableMultiTextureToggle = false; + + if (this.renderType === Phaser.WEBGL) + { + // No fallback + throw webGLRendererError; + } + } + } + + if (!this.renderer) + { + this.renderer = new PIXI.CanvasRenderer(this, this.config); + this.context = this.renderer.context; + + if (this.renderType === Phaser.AUTO) + { + this.renderType = Phaser.CANVAS; + } + } + + if (this.device.cocoonJS) + { + this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false; + } + + if (this.renderType !== Phaser.HEADLESS) + { + this.stage.smoothed = this.antialias; + + Phaser.Canvas.addToDOM(this.canvas, this.parent, false); + Phaser.Canvas.setTouchAction(this.canvas); + } + + }, + + /** + * Handles WebGL context loss. + * + * @method Phaser.Game#contextLost + * @private + * @param {Event} event - The webglcontextlost event. + */ + contextLost: function (event) { + + event.preventDefault(); + + this.renderer.contextLost = true; + + }, + + /** + * Handles WebGL context restoration. + * + * @method Phaser.Game#contextRestored + * @private + */ + contextRestored: function () { + + this.renderer.initContext(); + + this.cache.clearGLTextures(); + + this.renderer.contextLost = false; + + }, + + /** + * The core game loop. + * + * @method Phaser.Game#update + * @protected + * @param {number} time - The current time as provided by RequestAnimationFrame. + */ + update: function (time) { + + if (this.pendingDestroy) + { + this.destroy(); + return; + } + + this.time.update(time); + + if (this._kickstart) + { + this.updateLogic(this.time.desiredFpsMult); + + // call the game render update exactly once every frame + this.updateRender(this.time.slowMotion * this.time.desiredFps); + + this._kickstart = false; + + return; + } + + // if the logic time is spiraling upwards, skip a frame entirely + if (this._spiraling > 1 && !this.forceSingleUpdate) + { + // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate + if (this.time.time > this._nextFpsNotification) + { + // only permit one fps notification per 10 seconds + this._nextFpsNotification = this.time.time + 10000; + + // dispatch the notification signal + this.fpsProblemNotifier.dispatch(); + } + + // reset the _deltaTime accumulator which will cause all pending late updates to be permanently skipped + this._deltaTime = 0; + this._spiraling = 0; + + if (this.dropFrames) + { + this.rendersThisFrame = 0; + } + else + { + this.updateRender(this.time.slowMotion * this.time.desiredFps); + this.rendersThisFrame = 1; + } + } + else + { + // step size taking into account the slow motion speed + var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps; + + // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals + this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0); + + // call the game update logic multiple times if necessary to "catch up" with dropped frames + // unless forceSingleUpdate is true + var count = 0; + + this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); + + if (this.forceSingleUpdate) + { + this.updatesThisFrame = Math.min(1, this.updatesThisFrame); + } + + if (this.forceSingleRender) + { + this.rendersThisFrame = 1; + } + else + { + this.rendersThisFrame = Math.min(1, this.updatesThisFrame); + } + + while (this._deltaTime >= slowStep) + { + this._deltaTime -= slowStep; + this.currentUpdateID = count; + + this.updateLogic(this.time.desiredFpsMult); + + count++; + + if (this.forceSingleUpdate && count === 1) + { + break; + } + else + { + this.time.refresh(); + } + } + + // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly) + if (count > this._lastCount) + { + this._spiraling++; + } + else if (count < this._lastCount) + { + // looks like it caught up successfully, reset the spiral alert counter + this._spiraling = 0; + } + + this._lastCount = count; + + if (this.rendersThisFrame > 0) + { + this.updateRender(this._deltaTime / slowStep); + } + } + + }, + + /** + * Updates all logic subsystems in Phaser. Called automatically by Game.update. + * + * @method Phaser.Game#updateLogic + * @protected + * @param {number} timeStep - The current timeStep value as determined by Game.update. + */ + updateLogic: function (timeStep) { + + if (!this._paused && !this.pendingStep) + { + if (this.stepping) + { + this.pendingStep = true; + } + + this.time.countUpdate(); + + this.scale.preUpdate(); + this.debug.preUpdate(); + this.camera.preUpdate(); + this.physics.preUpdate(); + this.state.preUpdate(timeStep); + this.plugins.preUpdate(timeStep); + this.stage.preUpdate(); + + this.state.update(); + this.stage.update(); + this.tweens.update(); + this.sound.update(); + this.input.update(); + this.physics.update(); + this.plugins.update(); + + this.stage.postUpdate(); + this.plugins.postUpdate(); + } + else + { + // Scaling and device orientation changes are still reflected when paused. + this.scale.pauseUpdate(); + this.state.pauseUpdate(timeStep); + this.debug.preUpdate(); + this.input.pauseUpdate(); + } + + this.stage.updateTransform(); + + }, + + /** + * Runs the Render cycle. + * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. + * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. + * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. + * After this State.render is called. Any rendering that happens here will take place on-top of the display list. + * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. + * This method is called automatically by Game.update, you don't need to call it directly. + * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. + * Phaser will only render when this boolean is `false`. + * + * @method Phaser.Game#updateRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + updateRender: function (elapsedTime) { + + if (this.lockRender) + { + return; + } + + this.time.countRender(); + + this.state.preRender(elapsedTime); + + if (this.renderType !== Phaser.HEADLESS) + { + this.renderer.render(this.stage); + + this.plugins.render(elapsedTime); + + this.state.render(elapsedTime); + } + + this.plugins.postRender(elapsedTime); + + }, + + /** + * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) + * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! + * + * @method Phaser.Game#enableStep + */ + enableStep: function () { + + this.stepping = true; + this.pendingStep = false; + this.stepCount = 0; + + }, + + /** + * Disables core game loop stepping. + * + * @method Phaser.Game#disableStep + */ + disableStep: function () { + + this.stepping = false; + this.pendingStep = false; + + }, + + /** + * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. + * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. + * + * @method Phaser.Game#step + */ + step: function () { + + this.pendingStep = false; + this.stepCount++; + + }, + + /** + * Nukes the entire game from orbit. + * + * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. + * + * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM + * and resets the PIXI default renderer. + * + * To destroy the game during an update callback, set {@link #pendingDestroy} instead. + * + * @method Phaser.Game#destroy + */ + destroy: function () { + + this.raf.stop(); + + if (this.debug.destroy) + { + this.debug.destroy(); + } + + this.state.destroy(); + this.sound.destroy(); + this.scale.destroy(); + this.stage.destroy(); + this.input.destroy(); + this.physics.destroy(); + this.plugins.destroy(); + + this.debug = null; + this.state = null; + this.sound = null; + this.scale = null; + this.stage = null; + this.input = null; + this.physics = null; + this.plugins = null; + + this.cache = null; + this.load = null; + this.time = null; + this.world = null; + + this.isBooted = false; + + this.renderer.destroy(false); + + Phaser.Canvas.removeFromDOM(this.canvas); + + PIXI.defaultRenderer = null; + + Phaser.GAMES[this.id] = null; + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gamePaused + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gamePaused: function (event) { + + // If the game is already paused it was done via game code, so don't re-pause it + if (!this._paused) + { + this._paused = true; + + this.time.gamePaused(); + + if (this.sound.muteOnPause) + { + this.sound.setMute(); + } + + this.onPause.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = true; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gameResumed + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gameResumed: function (event) { + + // Game is paused, but wasn't paused via code, so resume it + if (this._paused && !this._codePaused) + { + this._paused = false; + + this.time.gameResumed(); + + this.input.reset(); + + if (this.sound.muteOnPause) + { + this.sound.unsetMute(); + } + + this.onResume.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = false; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusLoss + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusLoss: function (event) { + + this.onBlur.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gamePaused(event); + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusGain + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusGain: function (event) { + + this.onFocus.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gameResumed(event); + } + + } + +}; + +Phaser.Game.prototype.constructor = Phaser.Game; + +/** +* The paused state of the Game. A paused game doesn't update any of its subsystems. +* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. +* @name Phaser.Game#paused +* @property {boolean} paused - Gets and sets the paused state of the Game. +*/ +Object.defineProperty(Phaser.Game.prototype, "paused", { + + get: function () { + return this._paused; + }, + + set: function (value) { + + if (value === true) + { + if (this._paused === false) + { + this._paused = true; + this.sound.setMute(); + this.time.gamePaused(); + this.onPause.dispatch(this); + } + this._codePaused = true; + } + else + { + if (this._paused) + { + this._paused = false; + this.input.reset(); + this.sound.unsetMute(); + this.time.gameResumed(); + this.onResume.dispatch(this); + } + this._codePaused = false; + } + + } + +}); + +/** + * + * "Deleted code is debugged code." - Jeff Sickel + * + * ヽ(〃^▽^〃)ノ + * +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. +* The Input manager is updated automatically by the core game loop. +* +* @class Phaser.Input +* @constructor +* @param {Phaser.Game} game - Current game instance. +*/ +Phaser.Input = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. + * @default + */ + this.hitCanvas = null; + + /** + * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. + * @default + */ + this.hitContext = null; + + /** + * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. + * To add a callback to this array please use `Input.addMoveCallback`. + * @property {array} moveCallbacks + * @protected + */ + this.moveCallbacks = []; + + /** + * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandler = null; + + /** + * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandlerContext = null; + + /** + * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. + * @default + */ + this.pollRate = 0; + + /** + * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. + * + * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. + * @default + */ + this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE; + + /** + * @property {Phaser.Point} position - A point object representing the current position of the Pointer. + * @default + */ + this.position = null; + + /** + * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. + */ + this.speed = null; + + /** + * A Circle object centered on the x/y screen coordinates of the Input. + * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. + * @property {Phaser.Circle} circle + */ + this.circle = null; + + /** + * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. + */ + this.scale = null; + + /** + * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1. + * @default -1 (Limited by total pointers.) + */ + this.maxPointers = -1; + + /** + * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. + * @default + */ + this.tapRate = 200; + + /** + * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. + * @default + */ + this.doubleTapRate = 300; + + /** + * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. + * @default + */ + this.holdRate = 2000; + + /** + * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. + * @default + */ + this.justPressedRate = 200; + + /** + * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . + * @default + */ + this.justReleasedRate = 200; + + /** + * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. + * The history is cleared each time the Pointer is pressed down. + * The history is updated at the rate specified in Input.pollRate + * @property {boolean} recordPointerHistory + * @default + */ + this.recordPointerHistory = false; + + /** + * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. + * @default + */ + this.recordRate = 100; + + /** + * The total number of entries that can be recorded into the Pointer objects tracking history. + * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. + * @property {number} recordLimit + * @default + */ + this.recordLimit = 100; + + /** + * An array of callbacks that will be fired every time a native touch start or touch end event (pointerdown or pointerup when using Pointer events) is received from the browser. + * This is used internally to handle audio and video unlocking on mobile devices. + * To add a callback to this array please use `Input.addTouchLockCallback`. + * @property {array} touchLockCallbacks + * @protected + */ + this.touchLockCallbacks = []; + + /** + * @property {Phaser.Pointer} pointer1 - A Pointer object. + */ + this.pointer1 = null; + + /** + * @property {Phaser.Pointer} pointer2 - A Pointer object. + */ + this.pointer2 = null; + + /** + * @property {Phaser.Pointer} pointer3 - A Pointer object. + */ + this.pointer3 = null; + + /** + * @property {Phaser.Pointer} pointer4 - A Pointer object. + */ + this.pointer4 = null; + + /** + * @property {Phaser.Pointer} pointer5 - A Pointer object. + */ + this.pointer5 = null; + + /** + * @property {Phaser.Pointer} pointer6 - A Pointer object. + */ + this.pointer6 = null; + + /** + * @property {Phaser.Pointer} pointer7 - A Pointer object. + */ + this.pointer7 = null; + + /** + * @property {Phaser.Pointer} pointer8 - A Pointer object. + */ + this.pointer8 = null; + + /** + * @property {Phaser.Pointer} pointer9 - A Pointer object. + */ + this.pointer9 = null; + + /** + * @property {Phaser.Pointer} pointer10 - A Pointer object. + */ + this.pointer10 = null; + + /** + * An array of non-mouse pointers that have been added to the game. + * The properties `pointer1..N` are aliases for `pointers[0..N-1]`. + * @property {Phaser.Pointer[]} pointers + * @public + * @readonly + */ + this.pointers = []; + + /** + * The most recently active Pointer object. + * + * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. + * + * @property {Phaser.Pointer} activePointer + */ + this.activePointer = null; + + /** + * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. + * + * @property {Pointer} mousePointer + */ + this.mousePointer = null; + + /** + * The Mouse Input manager. + * + * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Mouse} mouse + */ + this.mouse = null; + + /** + * The Keyboard Input manager. + * + * @property {Phaser.Keyboard} keyboard + */ + this.keyboard = null; + + /** + * The Touch Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Touch} touch + */ + this.touch = null; + + /** + * The MSPointer Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.MSPointer} mspointer + */ + this.mspointer = null; + + /** + * The Gamepad Input manager. + * + * @property {Phaser.Gamepad} gamepad + */ + this.gamepad = null; + + /** + * If the Input Manager has been reset locked then all calls made to InputManager.reset, + * such as from a State change, are ignored. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is pressed down. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onDown + */ + this.onDown = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is released. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onUp + */ + this.onUp = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is tapped. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {boolean} True if this was a double tap. + * + * @property {Phaser.Signal} onTap + */ + this.onTap = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is held down. + * It is sent one argument: + * + * - {Phaser.Pointer} The pointer that caused the event. + * + * @property {Phaser.Signal} onHold + */ + this.onHold = null; + + /** + * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. + * This is useful when stacking UI layers. Set to zero to disable. + * @property {number} minPriorityID + * @default + */ + this.minPriorityID = 0; + + /** + * A list of interactive objects. The InputHandler components add and remove themselves from this list. + * @property {Phaser.ArraySet} interactiveItems + */ + this.interactiveItems = new Phaser.ArraySet(); + + /** + * @property {Phaser.Point} _localPoint - Internal cache var. + * @private + */ + this._localPoint = new Phaser.Point(); + + /** + * @property {number} _pollCounter - Internal var holding the current poll counter. + * @private + */ + this._pollCounter = 0; + + /** + * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. + * @private + */ + this._oldPosition = null; + + /** + * @property {number} _x - x coordinate of the most recent Pointer event + * @private + */ + this._x = 0; + + /** + * @property {number} _y - Y coordinate of the most recent Pointer event + * @private + */ + this._y = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_TOUCH_COMBINE = 2; + +/** +* The maximum number of pointers that can be added. This excludes the mouse pointer. +* @constant +* @type {integer} +*/ +Phaser.Input.MAX_POINTERS = 10; + +Phaser.Input.prototype = { + + /** + * Starts the Input Manager running. + * + * @method Phaser.Input#boot + * @protected + */ + boot: function () { + + this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR); + this.addPointer(); + this.addPointer(); + + this.mouse = new Phaser.Mouse(this.game); + this.touch = new Phaser.Touch(this.game); + this.mspointer = new Phaser.MSPointer(this.game); + + if (Phaser.Keyboard) + { + this.keyboard = new Phaser.Keyboard(this.game); + } + + if (Phaser.Gamepad) + { + this.gamepad = new Phaser.Gamepad(this.game); + } + + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + + this.scale = new Phaser.Point(1, 1); + this.speed = new Phaser.Point(); + this.position = new Phaser.Point(); + this._oldPosition = new Phaser.Point(); + + this.circle = new Phaser.Circle(0, 0, 44); + + this.activePointer = this.mousePointer; + + this.hitCanvas = Phaser.CanvasPool.create(this, 1, 1); + this.hitContext = this.hitCanvas.getContext('2d'); + + this.mouse.start(); + if (!this.game.device.mspointer) + { + // Chrome >= 55 fires both PointerEvent and TouchEvent. + // Pick only one. + this.touch.start(); + } + this.mspointer.start(); + this.mousePointer.active = true; + + if (this.keyboard) + { + this.keyboard.start(); + } + + var _this = this; + + this._onClickTrampoline = function (event) { + _this.onClickTrampoline(event); + }; + + this.game.canvas.addEventListener('click', this._onClickTrampoline, false); + + }, + + /** + * Stops all of the Input Managers from running. + * + * @method Phaser.Input#destroy + */ + destroy: function () { + + this.mouse.stop(); + this.touch.stop(); + this.mspointer.stop(); + + if (this.keyboard) + { + this.keyboard.stop(); + } + + if (this.gamepad) + { + this.gamepad.stop(); + } + + this.moveCallbacks = []; + + Phaser.CanvasPool.remove(this); + + this.game.canvas.removeEventListener('click', this._onClickTrampoline); + + }, + + /** + * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. + * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to + * interact with. It works by polling all of the valid game objects, and then slowly discounting those + * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). + * + * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid + * for input and overlap with the Pointer. If you need fine-grained control over which of the items is + * selected then you can use this callback to do so. + * + * The callback will be sent 3 parameters: + * + * 1) A reference to the Phaser.Pointer object that is processing the Items. + * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. + * 3) The current 'favorite' candidate, based on its priorityID and position in the display list. + * + * Your callback MUST return one of the candidates sent to it. + * + * @method Phaser.Input#setInteractiveCandidateHandler + * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. + * @param {object} context - The context in which the callback will be called. + */ + setInteractiveCandidateHandler: function (callback, context) { + + this.customCandidateHandler = callback; + this.customCandidateHandlerContext = context; + + }, + + /** + * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. + * + * The callback will be sent 4 parameters: + * + * A reference to the Phaser.Pointer object that moved, + * The x position of the pointer, + * The y position, + * A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down). + * + * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best + * to only use if you've limited input to a single pointer (i.e. mouse or touch). + * + * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. + * + * @method Phaser.Input#addMoveCallback + * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. + * @param {object} context - The context in which the callback will be called. + */ + addMoveCallback: function (callback, context) { + + this.moveCallbacks.push({ callback: callback, context: context }); + + }, + + + /** + * Adds a callback that is fired when a browser touchstart/pointerdown or touchend/pointerup event is received. + * + * This is used internally to handle audio and video unlocking on mobile devices. + * + * If the callback returns 'true' then the callback is automatically deleted once invoked. + * + * The callback is added to the {@link #touchLockCallbacks} array and should be removed with {@link #removeTouchLockCallback}. + * + * @method Phaser.Input#addTouchLockCallback + * @param {function} callback - The callback that will be called when a touchstart event is received. + * @param {object} context - The context in which the callback will be called. + * @param {boolean} [onEnd=false] - Will the callback fire on a touchstart/pointerdown (default) or touchend/pointerup event? + */ + addTouchLockCallback: function (callback, context, onEnd) { + + if (onEnd === undefined) { onEnd = false; } + + this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd }); + + }, + + /** + * Removes the callback at the defined index from the {@link #touchLockCallbacks} array + * + * @method Phaser.Input#removeTouchLockCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + * @return {boolean} True if the callback was deleted, otherwise false. + */ + removeTouchLockCallback: function (callback, context) { + + var i = this.touchLockCallbacks.length; + + while (i--) + { + if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context) + { + this.touchLockCallbacks.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Execute any {@link #touchLockCallbacks} of the given type. + * + * @method Phaser.Input#executeTouchLockCallbacks + * @private + * @param {boolean} onEnd - Execute the touchend/pointerup callbacks (true) or the touchstart/pointerdown callbacks (false). Required! + * @param {Event} event - The native event from the browser. + */ + executeTouchLockCallbacks: function (onEnd, event) { + var i = this.touchLockCallbacks.length; + + while (i--) + { + var cb = this.touchLockCallbacks[i]; + + if (cb.onEnd === onEnd && cb.callback.call(cb.context, this, event)) + { + this.touchLockCallbacks.splice(i, 1); + } + } + }, + + /** + * Removes the callback from the Phaser.Input.moveCallbacks array. + * + * @method Phaser.Input#deleteMoveCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + */ + deleteMoveCallback: function (callback, context) { + + var i = this.moveCallbacks.length; + + while (i--) + { + if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context) + { + this.moveCallbacks.splice(i, 1); + return; + } + } + + }, + + /** + * Add a new Pointer object to the Input Manager. + * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. + * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). + * + * @method Phaser.Input#addPointer + * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. + */ + addPointer: function () { + + if (this.pointers.length >= Phaser.Input.MAX_POINTERS) + { + console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached."); + return null; + } + + var id = this.pointers.length + 1; + var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.CONTACT); + + this.pointers.push(pointer); + this['pointer' + id] = pointer; + + return pointer; + + }, + + /** + * Updates the Input Manager. Called by the core Game loop. + * + * @method Phaser.Input#update + * @protected + */ + update: function () { + + if (this.keyboard) + { + this.keyboard.update(); + } + + if (this.pollRate > 0 && this._pollCounter < this.pollRate) + { + this._pollCounter++; + return; + } + + this.speed.x = this.position.x - this._oldPosition.x; + this.speed.y = this.position.y - this._oldPosition.y; + + this._oldPosition.copyFrom(this.position); + this.mousePointer.update(); + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].update(); + } + + this._pollCounter = 0; + + }, + + /** + * Update method while paused. + * + * @method Phaser.Input#pauseUpdate + * @private + */ + pauseUpdate: function () { + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + }, + + /** + * Reset all of the Pointers and Input states. + * + * The optional `hard` parameter will reset any events or callbacks that may be bound. + * Input.reset is called automatically during a State change or if a game loses focus / visibility. + * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. + * + * @method Phaser.Input#reset + * @public + * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. + */ + reset: function (hard) { + + if (!this.game.isBooted || this.resetLocked) + { + return; + } + + if (hard === undefined) { hard = false; } + + this.mousePointer.reset(); + + if (this.keyboard) + { + this.keyboard.reset(hard); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].reset(); + } + + if (this.game.canvas.style.cursor !== 'none') + { + this.game.canvas.style.cursor = ''; + } + + if (hard) + { + this.onDown.dispose(); + this.onUp.dispose(); + this.onTap.dispose(); + this.onHold.dispose(); + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + this.moveCallbacks = []; + } + + this._pollCounter = 0; + + }, + + /** + * Resets the speed and old position properties. + * + * @method Phaser.Input#resetSpeed + * @param {number} x - Sets the oldPosition.x value. + * @param {number} y - Sets the oldPosition.y value. + */ + resetSpeed: function (x, y) { + + this._oldPosition.setTo(x, y); + this.speed.setTo(0, 0); + + }, + + /** + * Find the first free Pointer object and start it, passing in the event data. + * This is called automatically by Phaser.Touch and Phaser.MSPointer. + * + * @method Phaser.Input#startPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. + */ + startPointer: function (event) { + + if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers) + { + return null; + } + + if (!this.pointer1.active) + { + return this.pointer1.start(event); + } + + if (!this.pointer2.active) + { + return this.pointer2.start(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (!pointer.active) + { + return pointer.start(event); + } + } + + return null; + + }, + + /** + * Updates the matching Pointer object, passing in the event data. + * This is called automatically and should not normally need to be invoked. + * + * @method Phaser.Input#updatePointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. + */ + updatePointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.move(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.move(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.move(event); + } + } + + return null; + + }, + + /** + * Stops the matching Pointer object, passing in the event data. + * + * @method Phaser.Input#stopPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. + */ + stopPointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.stop(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.stop(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.stop(event); + } + } + + return null; + + }, + + /** + * Returns the total number of active pointers, not exceeding the specified limit + * + * @name Phaser.Input#countActivePointers + * @private + * @property {integer} [limit=(max pointers)] - Stop counting after this. + * @return {integer} The number of active pointers, or limit - whichever is less. + */ + countActivePointers: function (limit) { + + if (limit === undefined) { limit = this.pointers.length; } + + var count = limit; + + for (var i = 0; i < this.pointers.length && count > 0; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active) + { + count--; + } + } + + return (limit - count); + + }, + + /** + * Get the first Pointer with the given active state. + * + * @method Phaser.Input#getPointer + * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. + */ + getPointer: function (isActive) { + + if (isActive === undefined) { isActive = false; } + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active === isActive) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `identifier` property matches the given identifier value. + * + * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down, and is not fixed once set. + * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. + * + * @method Phaser.Input#getPointerFromIdentifier + * @param {number} identifier - The Pointer.identifier value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromIdentifier: function (identifier) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.identifier === identifier) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `pointerId` property matches the given value. + * + * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down if the browser recycles it. + * + * @method Phaser.Input#getPointerFromId + * @param {number} pointerId - The `pointerId` (not 'id') value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromId: function (pointerId) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.pointerId === pointerId) + { + return pointer; + } + } + + return null; + + }, + + /** + * This will return the local coordinates of the specified displayObject based on the given Pointer. + * + * @method Phaser.Input#getLocalPosition + * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. + * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. + * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. + */ + getLocalPosition: function (displayObject, pointer, output) { + + if (output === undefined) { output = new Phaser.Point(); } + + var wt = displayObject.worldTransform; + var id = 1 / (wt.a * wt.d + wt.c * -wt.b); + + return output.setTo( + wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id, + wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id + ); + + }, + + /** + * Tests if the pointer hits the given object. + * + * @method Phaser.Input#hitTest + * @param {DisplayObject} displayObject - The displayObject to test for a hit. + * @param {Phaser.Pointer} pointer - The pointer to use for the test. + * @param {Phaser.Point} localPoint - The local translated point. + */ + hitTest: function (displayObject, pointer, localPoint) { + + if (!displayObject.worldVisible) + { + return false; + } + + this.getLocalPosition(displayObject, pointer, this._localPoint); + + localPoint.copyFrom(this._localPoint); + + if (displayObject.hitArea && displayObject.hitArea.contains) + { + return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y)); + } + else if (Phaser.Creature && displayObject instanceof Phaser.Creature) { + var width = Math.abs(displayObject.width); + var height = Math.abs(displayObject.height); + var x1 = displayObject.x - (width * displayObject.anchorX); + + if (this.game.camera.x + pointer.x >= x1 && this.game.camera.x + pointer.x < x1 + width) + { + var y1 = displayObject.y - (height * displayObject.anchorY); + + if (this.game.camera.y + pointer.y >= y1 && this.game.camera.y + pointer.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.TileSprite) + { + var width = displayObject.width; + var height = displayObject.height; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof PIXI.Sprite) + { + var width = displayObject.texture.frame.width / displayObject.texture.baseTexture.resolution; + var height = displayObject.texture.frame.height / displayObject.texture.baseTexture.resolution; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.Graphics) + { + for (var i = 0; i < displayObject.graphicsData.length; i++) + { + var data = displayObject.graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // Only deal with fills.. + if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y)) + { + return true; + } + } + } + + // Didn't hit the parent, does it have any children? + + for (var i = 0; i < displayObject.children.length; i++) + { + if (this.hitTest(displayObject.children[i], pointer, localPoint)) + { + return true; + } + } + + return false; + }, + + /** + * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. + * + * @method Phaser.Input#onClickTrampoline + * @private + */ + onClickTrampoline: function () { + + // It might not always be the active pointer, but this does work on + // Desktop browsers (read: IE) with Mouse or MSPointer input. + this.activePointer.processClickTrampolines(); + + } + +}; + +Phaser.Input.prototype.constructor = Phaser.Input; + +/** +* The X coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. +* @name Phaser.Input#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Input.prototype, "x", { + + get: function () { + return this._x; + }, + + set: function (value) { + this._x = Math.floor(value); + } + +}); + +/** +* The Y coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. +* @name Phaser.Input#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Input.prototype, "y", { + + get: function () { + return this._y; + }, + + set: function (value) { + this._y = Math.floor(value); + } + +}); + +/** +* True if the Input is currently poll rate locked. +* @name Phaser.Input#pollLocked +* @property {boolean} pollLocked +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "pollLocked", { + + get: function () { + return (this.pollRate > 0 && this._pollCounter < this.pollRate); + } + +}); + +/** +* The total number of inactive Pointers. +* @name Phaser.Input#totalInactivePointers +* @property {number} totalInactivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", { + + get: function () { + return this.pointers.length - this.countActivePointers(); + } + +}); + +/** +* The total number of active Pointers, not counting the mouse pointer. +* @name Phaser.Input#totalActivePointers +* @property {integers} totalActivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", { + + get: function () { + return this.countActivePointers(); + } + +}); + +/** +* The world X coordinate of the most recently active pointer. +* @name Phaser.Input#worldX +* @property {number} worldX - The world X coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldX", { + + get: function () { + return this.game.camera.view.x + this.x; + } + +}); + +/** +* The world Y coordinate of the most recently active pointer. +* @name Phaser.Input#worldY +* @property {number} worldY - The world Y coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldY", { + + get: function () { + return this.game.camera.view.y + this.y; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Mouse class is responsible for handling all aspects of mouse interaction with the browser. +* +* It captures and processes mouse events that happen on the game canvas object. +* It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released +* when not over the game. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object +* which normalises all game input for you, including accurate button handling. +* +* @class Phaser.Mouse +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Mouse = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down. + */ + this.mouseDownCallback = null; + + /** + * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state. + */ + this.mouseUpCallback = null; + + /** + * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas. + */ + this.mouseOutCallback = null; + + /** + * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). + */ + this.mouseOverCallback = null; + + /** + * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used. + */ + this.mouseWheelCallback = null; + + /** + * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + */ + this.capture = false; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + * @default + */ + this.button = -1; + + /** + * The direction of the _last_ mousewheel usage 1 for up -1 for down. + * @property {number} wheelDelta + */ + this.wheelDelta = 0; + + /** + * Mouse input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true. + * @default + */ + this.locked = false; + + /** + * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas. + * @default + */ + this.stopOnGameOut = false; + + /** + * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state. + * @default + */ + this.pointerLock = new Phaser.Signal(); + + /** + * The browser mouse DOM event. Will be null if no mouse event has ever been received. + * Access this property only inside a Mouse event handler and do not keep references to it. + * @property {MouseEvent|null} event + * @default + */ + this.event = null; + + /** + * @property {function} _onMouseDown - Internal event handler reference. + * @private + */ + this._onMouseDown = null; + + /** + * @property {function} _onMouseMove - Internal event handler reference. + * @private + */ + this._onMouseMove = null; + + /** + * @property {function} _onMouseUp - Internal event handler reference. + * @private + */ + this._onMouseUp = null; + + /** + * @property {function} _onMouseOut - Internal event handler reference. + * @private + */ + this._onMouseOut = null; + + /** + * @property {function} _onMouseOver - Internal event handler reference. + * @private + */ + this._onMouseOver = null; + + /** + * @property {function} _onMouseWheel - Internal event handler reference. + * @private + */ + this._onMouseWheel = null; + + /** + * Wheel proxy event object, if required. Shared for all wheel events for this mouse. + * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent + * @private + */ + this._wheelEvent = null; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.NO_BUTTON = -1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.LEFT_BUTTON = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.MIDDLE_BUTTON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.RIGHT_BUTTON = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.BACK_BUTTON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.FORWARD_BUTTON = 4; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_UP = 1; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_DOWN = -1; + +Phaser.Mouse.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Mouse#start + */ + start: function () { + + if (this.game.device.android && this.game.device.chrome === false) + { + // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ... + return; + } + + if (this._onMouseDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onMouseDown = function (event) { + return _this.onMouseDown(event); + }; + + this._onMouseMove = function (event) { + return _this.onMouseMove(event); + }; + + this._onMouseUp = function (event) { + return _this.onMouseUp(event); + }; + + this._onMouseUpGlobal = function (event) { + return _this.onMouseUpGlobal(event); + }; + + this._onMouseOutGlobal = function (event) { + return _this.onMouseOutGlobal(event); + }; + + this._onMouseOut = function (event) { + return _this.onMouseOut(event); + }; + + this._onMouseOver = function (event) { + return _this.onMouseOver(event); + }; + + this._onMouseWheel = function (event) { + return _this.onMouseWheel(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('mousedown', this._onMouseDown, true); + canvas.addEventListener('mousemove', this._onMouseMove, true); + canvas.addEventListener('mouseup', this._onMouseUp, true); + + if (!this.game.device.cocoonJS) + { + window.addEventListener('mouseup', this._onMouseUpGlobal, true); + window.addEventListener('mouseout', this._onMouseOutGlobal, true); + canvas.addEventListener('mouseover', this._onMouseOver, true); + canvas.addEventListener('mouseout', this._onMouseOut, true); + } + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.addEventListener(wheelEvent, this._onMouseWheel, true); + + if (wheelEvent === 'mousewheel') + { + this._wheelEvent = new WheelEventProxy(-1/40, 1); + } + else if (wheelEvent === 'DOMMouseScroll') + { + this._wheelEvent = new WheelEventProxy(1, 1); + } + } + + }, + + /** + * The internal method that handles the mouse down event from the browser. + * @method Phaser.Mouse#onMouseDown + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseDown: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseDownCallback) + { + this.mouseDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.start(event); + + }, + + /** + * The internal method that handles the mouse move event from the browser. + * @method Phaser.Mouse#onMouseMove + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseMoveCallback) + { + this.mouseMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.move(event); + + }, + + /** + * The internal method that handles the mouse up event from the browser. + * @method Phaser.Mouse#onMouseUp + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUp: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.Mouse#onMouseUpGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUpGlobal: function (event) { + + if (!this.input.mousePointer.withinGame) + { + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + }, + + /** + * The internal method that handles the mouse out event from the window. + * + * @method Phaser.Mouse#onMouseOutGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOutGlobal: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (!this.input.enabled || !this.enabled) + { + return; + } + + // If we get a mouseout event from the window then basically + // something serious has gone down, usually along the lines of + // the browser opening a context-menu or similar. + // On OS X Chrome especially this is bad news, as it blocks + // us then getting a mouseup event, so we need to force that through. + // + // No matter what, we must cancel the left and right buttons + + this.input.mousePointer.stop(event); + + // Clear the button states (again?) + this.input.mousePointer.resetButtons(); + + }, + + /** + * The internal method that handles the mouse out event from the browser. + * + * @method Phaser.Mouse#onMouseOut + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (this.mouseOutCallback) + { + this.mouseOutCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.stopOnGameOut) + { + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + this.input.interactiveItems.callAll('_pointerOutHandler', this.input.mousePointer); + + }, + + /** + * The internal method that handles the mouse over event from the browser. + * + * @method Phaser.Mouse#onMouseOver + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = true; + + if (this.mouseOverCallback) + { + this.mouseOverCallback.call(this.callbackContext, event); + } + + }, + + /** + * The internal method that handles the mouse wheel event from the browser. + * + * @method Phaser.Mouse#onMouseWheel + * @param {MouseEvent} event - The native event from the browser. + */ + onMouseWheel: function (event) { + + if (this._wheelEvent) { + event = this._wheelEvent.bindEvent(event); + } + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + // reverse detail for firefox + this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1); + + if (this.mouseWheelCallback) + { + this.mouseWheelCallback.call(this.callbackContext, event); + } + + }, + + /** + * If the browser supports it you can request that the pointer be locked to the browser window. + * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key. + * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'. + * @method Phaser.Mouse#requestPointerLock + */ + requestPointerLock: function () { + + if (this.game.device.pointerLock) + { + var element = this.game.canvas; + + element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; + + element.requestPointerLock(); + + var _this = this; + + this._pointerLockChange = function (event) { + return _this.pointerLockChange(event); + }; + + document.addEventListener('pointerlockchange', this._pointerLockChange, true); + document.addEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true); + } + + }, + + /** + * Internal pointerLockChange handler. + * + * @method Phaser.Mouse#pointerLockChange + * @param {Event} event - The native event from the browser. This gets stored in Mouse.event. + */ + pointerLockChange: function (event) { + + var element = this.game.canvas; + + if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) + { + // Pointer was successfully locked + this.locked = true; + this.pointerLock.dispatch(true, event); + } + else + { + // Pointer was unlocked + this.locked = false; + this.pointerLock.dispatch(false, event); + } + + }, + + /** + * Internal release pointer lock handler. + * @method Phaser.Mouse#releasePointerLock + */ + releasePointerLock: function () { + + document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; + + document.exitPointerLock(); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + }, + + /** + * Stop the event listeners. + * @method Phaser.Mouse#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('mousedown', this._onMouseDown, true); + canvas.removeEventListener('mousemove', this._onMouseMove, true); + canvas.removeEventListener('mouseup', this._onMouseUp, true); + canvas.removeEventListener('mouseover', this._onMouseOver, true); + canvas.removeEventListener('mouseout', this._onMouseOut, true); + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.removeEventListener(wheelEvent, this._onMouseWheel, true); + } + + window.removeEventListener('mouseup', this._onMouseUpGlobal, true); + window.removeEventListener('mouseout', this._onMouseOutGlobal, true); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + } + +}; + +Phaser.Mouse.prototype.constructor = Phaser.Mouse; + +/* jshint latedef:nofunc */ +/** +* A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel' +* events to 'wheel'-like events. +* +* See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode. +* +* @method Phaser.Mouse#WheelEventProxy +* @private +* @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. +* @param {integer} deltaMode - The reported delta mode. +*/ +function WheelEventProxy (scaleFactor, deltaMode) { + + /** + * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. + * @private + */ + this._scaleFactor = scaleFactor; + + /** + * @property {number} _deltaMode - The reported delta mode. + * @private + */ + this._deltaMode = deltaMode; + + /** + * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit. + * @private + */ + this.originalEvent = null; + +} + +WheelEventProxy.prototype = {}; +WheelEventProxy.prototype.constructor = WheelEventProxy; + +WheelEventProxy.prototype.bindEvent = function (event) { + + // Generate stubs automatically + if (!WheelEventProxy._stubsGenerated && event) + { + var makeBinder = function (name) { + + return function () { + var v = this.originalEvent[name]; + return typeof v !== 'function' ? v : v.bind(this.originalEvent); + }; + + }; + + for (var prop in event) + { + if (!(prop in WheelEventProxy.prototype)) + { + Object.defineProperty(WheelEventProxy.prototype, prop, { + get: makeBinder(prop) + }); + } + } + WheelEventProxy._stubsGenerated = true; + } + + this.originalEvent = event; + return this; + +}; + +Object.defineProperties(WheelEventProxy.prototype, { + "type": { value: "wheel" }, + "deltaMode": { get: function () { return this._deltaMode; } }, + "deltaY": { + get: function () { + return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0; + } + }, + "deltaX": { + get: function () { + return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0; + } + }, + "deltaZ": { value: 0 } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The MSPointer class handles {@link https://developers.google.com/web/updates/2016/10/pointer-events Pointer-event} interactions with the game via a dedicated {@link Phaser.Pointer}. (It's named after the nonstandard {@link https://msdn.microsoft.com/library/hh673557(v=vs.85).aspx MSPointerEvent} since that was the first browser implementation.) +* +* It's {@link http://caniuse.com/#feat=pointer currently supported in IE 10+, Edge, Chrome (including Android), and Opera}. +* +* You should not normally access this class directly, but instead use a {@link Phaser.Pointer} object which +* normalises all game input for you including accurate button handling. +* +* Please note that at the current time of writing Phaser does not yet support chorded button interactions: +* http://www.w3.org/TR/pointerevents/#chorded-button-interactions +* +* You can disable Phaser's use of Pointer Events by either of two ways: +* +* ```javascript +* // **Before** `new Phaser.Game(…)`: +* Phaser.Device.onInitialized.add(function () { +* this.mspointer = false; +* }); +* ``` +* +* ```javascript +* // Once, in the earliest State `init` or `create` callback (e.g., Boot): +* this.input.mspointer.stop(); +* ``` +* +* @class Phaser.MSPointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.MSPointer = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called (defaults to game). + */ + this.callbackContext = this.game; + + /** + * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event. + */ + this.pointerDownCallback = null; + + /** + * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event. + */ + this.pointerMoveCallback = null; + + /** + * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event. + */ + this.pointerUpCallback = null; + + /** + * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, canceling the corresponding MouseEvent or TouchEvent. + */ + this.capture = true; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + */ + this.button = -1; + + /** + * The most recent PointerEvent from the browser. Will be null if no event has ever been received. + * Access this property only inside a Pointer event handler and do not keep references to it. + * @property {MSPointerEvent|PointerEvent|null} event + * @default + */ + this.event = null; + + /** + * PointerEvent input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {function} _onMSPointerDown - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerDown = null; + + /** + * @property {function} _onMSPointerMove - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerMove = null; + + /** + * @property {function} _onMSPointerUp - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUp = null; + + /** + * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUpGlobal = null; + + /** + * @property {function} _onMSPointerOut - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOut = null; + + /** + * @property {function} _onMSPointerOver - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOver = null; + +}; + +Phaser.MSPointer.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.MSPointer#start + */ + start: function () { + + if (this._onMSPointerDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + if (this.game.device.mspointer) + { + this._onMSPointerDown = function (event) { + return _this.onPointerDown(event); + }; + + this._onMSPointerMove = function (event) { + return _this.onPointerMove(event); + }; + + this._onMSPointerUp = function (event) { + return _this.onPointerUp(event); + }; + + this._onMSPointerUpGlobal = function (event) { + return _this.onPointerUpGlobal(event); + }; + + this._onMSPointerOut = function (event) { + return _this.onPointerOut(event); + }; + + this._onMSPointerOver = function (event) { + return _this.onPointerOver(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.addEventListener('pointerdown', this._onMSPointerDown, false); + canvas.addEventListener('pointermove', this._onMSPointerMove, false); + canvas.addEventListener('pointerup', this._onMSPointerUp, false); + + canvas.style['-ms-content-zooming'] = 'none'; + canvas.style['-ms-touch-action'] = 'none'; + + if (!this.game.device.cocoonJS) + { + window.addEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.addEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.addEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.addEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.addEventListener('pointerover', this._onMSPointerOver, true); + canvas.addEventListener('pointerout', this._onMSPointerOut, true); + } + } + + }, + + /** + * The function that handles the PointerDown event. + * + * @method Phaser.MSPointer#onPointerDown + * @param {PointerEvent} event - The native DOM event. + */ + onPointerDown: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerDownCallback) + { + this.pointerDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.start(event); + } + else + { + this.input.startPointer(event); + } + + }, + + /** + * The function that handles the PointerMove event. + * @method Phaser.MSPointer#onPointerMove + * @param {PointerEvent} event - The native DOM event. + */ + onPointerMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerMoveCallback) + { + this.pointerMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.move(event); + } + else + { + this.input.updatePointer(event); + } + + }, + + /** + * The function that handles the PointerUp event. + * @method Phaser.MSPointer#onPointerUp + * @param {PointerEvent} event - The native DOM event. + */ + onPointerUp: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerUpCallback) + { + this.pointerUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.stop(event); + } + else + { + this.input.stopPointer(event); + } + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.MSPointer#onPointerUpGlobal + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerUpGlobal: function (event) { + + if ((event.pointerType === 'mouse' || event.pointerType === 0x00000004) && !this.input.mousePointer.withinGame) + { + this.onPointerUp(event); + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer && pointer.withinGame) + { + this.onPointerUp(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = false; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = false; + } + } + + if (this.input.mouse.mouseOutCallback) + { + this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.input.mouse.stopOnGameOut) + { + event['identifier'] = 0; + + if (pointer) + { + pointer.stop(event); + } + else + { + this.input.mousePointer.stop(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = true; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = true; + } + } + + if (this.input.mouse.mouseOverCallback) + { + this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext, event); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.MSPointer#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.removeEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.removeEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.removeEventListener('pointerdown', this._onMSPointerDown, false); + canvas.removeEventListener('pointermove', this._onMSPointerMove, false); + canvas.removeEventListener('pointerup', this._onMSPointerUp, false); + + window.removeEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.removeEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.removeEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('pointerover', this._onMSPointerOver, true); + canvas.removeEventListener('pointerout', this._onMSPointerOut, true); + + } + +}; + +Phaser.MSPointer.prototype.constructor = Phaser.MSPointer; + +/** +* @author Richard Davey +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. +* +* For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, +* middle button and advanced buttons like back and forward. +* +* Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. +* +* On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. +* +* At the time of writing this there are device limitations you should be aware of: +* +* - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions +* (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, +* even when they are pressed. +* - On Linux (GTK), the 4th button and the 5th button are not supported. +* - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. +* +* @class Phaser.DeviceButton +* @constructor +* @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad. +* @param {number} buttonCode - The button code this DeviceButton is responsible for. +*/ +Phaser.DeviceButton = function (parent, buttonCode) { + + /** + * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = parent.game; + + /** + * @property {object} event - The DOM event that caused the change in button state. + * @default + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the button. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the button. + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - The timestamp when the button was last pressed down. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - The timestamp when the button was last released. + * @default + */ + this.timeUp = 0; + + /** + * Gamepad only. + * If a button is held down this holds down the number of times the button has 'repeated'. + * @property {number} repeats + * @default + */ + this.repeats = 0; + + /** + * True if the alt key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} altKey + * @default + */ + this.altKey = false; + + /** + * True if the shift key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} shiftKey + * @default + */ + this.shiftKey = false; + + /** + * True if the control key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} ctrlKey + * @default + */ + this.ctrlKey = false; + + /** + * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. + * @default + */ + this.value = 0; + + /** + * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. + */ + this.buttonCode = buttonCode; + + /** + * This Signal is dispatched every time this DeviceButton is pressed down. + * It is only dispatched once (until the button is released again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onDown + */ + this.onDown = new Phaser.Signal(); + + /** + * This Signal is dispatched every time this DeviceButton is released from a down state. + * It is only dispatched once (until the button is pressed again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onUp + */ + this.onUp = new Phaser.Signal(); + + /** + * Gamepad only. + * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onFloat + */ + this.onFloat = new Phaser.Signal(); + +}; + +Phaser.DeviceButton.prototype = { + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button down state. + * + * @method Phaser.DeviceButton#start + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + start: function (event, value) { + + if (this.isDown) + { + return; + } + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onDown.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button up state. + * + * @method Phaser.DeviceButton#stop + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + stop: function (event, value) { + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onUp.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer. + * Starts or stops button based on condition. + * + * @method Phaser.DeviceButton#startStop + * @protected + * @param {boolean} [condition] - The condition that decides between start or stop. + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + startStop: function (condition, event, value) { + + if (condition) + { + this.start(event, value); + } + else + { + this.stop(event, value); + } + + }, + + /** + * Called automatically by Phaser.SinglePad. + * + * @method Phaser.DeviceButton#padFloat + * @protected + * @param {number} value - Button value + */ + padFloat: function (value) { + + this.isDown = false; + this.isUp = false; + + this.value = value; + + this.onFloat.dispatch(this, value); + + }, + + /** + * Returns the "just pressed" state of this button. + * Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justPressed + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (duration) { + + duration = duration || 250; + + return (this.isDown && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * Returns the "just released" state of this button. + * Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justReleased + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (duration) { + + duration = duration || 250; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. + * + * @method Phaser.DeviceButton#reset + */ + reset: function () { + + this.isDown = false; + this.isUp = true; + + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.altKey = false; + this.shiftKey = false; + this.ctrlKey = false; + + }, + + /** + * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals + * and clears the parent and game references. + * + * @method Phaser.DeviceButton#destroy + */ + destroy: function () { + + this.onDown.dispose(); + this.onUp.dispose(); + this.onFloat.dispose(); + + this.parent = null; + this.game = null; + + } + +}; + +Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton; + +/** +* How long the button has been held down for in milliseconds. +* If not currently down it returns -1. +* +* @name Phaser.DeviceButton#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.DeviceButton.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. +* +* @class Phaser.Pointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. +* @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or CONTACT. +*/ +Phaser.Pointer = function (game, id, pointerMode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. + */ + this.id = id; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINTER; + + /** + * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps. + * @default + */ + this.exists = true; + + /** + * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.identifier = 0; + + /** + * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. + * @default + */ + this.pointerId = null; + + /** + * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer. + */ + this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT); + + /** + * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.target = null; + + /** + * The button property of the most recent DOM event when this Pointer is started. + * You should not rely on this value for accurate button detection, instead use the Pointer properties + * `leftButton`, `rightButton`, `middleButton` and so on. + * @property {any} button + * @default + */ + this.button = null; + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * @property {Phaser.DeviceButton} leftButton + * @default + */ + this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} middleButton + * @default + */ + this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} rightButton + * @default + */ + this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} backButton + * @default + */ + this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} forwardButton + * @default + */ + this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON); + + /** + * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} eraserButton + * @default + */ + this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON); + + /** + * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event. + * @private + * @default + */ + this._holdSent = false; + + /** + * @property {array} _history - Local private variable storing the short-term history of pointer movements. + * @private + */ + this._history = []; + + /** + * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur. + * @private + */ + this._nextDrop = 0; + + /** + * @property {boolean} _stateReset - Monitor events outside of a state reset loop. + * @private + */ + this._stateReset = false; + + /** + * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false. + */ + this.withinGame = false; + + /** + * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientX = -1; + + /** + * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientY = -1; + + /** + * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document. + */ + this.pageX = -1; + + /** + * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document. + */ + this.pageY = -1; + + /** + * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen. + */ + this.screenX = -1; + + /** + * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen. + */ + this.screenY = -1; + + /** + * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementX = 0; + + /** + * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementY = 0; + + /** + * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementX = 0; + + /** + * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementY = 0; + + /** + * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.x = -1; + + /** + * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.y = -1; + + /** + * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false. + */ + this.isMouse = (id === 0); + + /** + * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. + * @property {boolean} isDown + * @default + */ + this.isDown = false; + + /** + * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. + * @property {boolean} isUp + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen. + * @default + */ + this.timeUp = 0; + + /** + * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked. + * @default + */ + this.previousTapTime = 0; + + /** + * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen. + * @default + */ + this.totalTouches = 0; + + /** + * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event. + * @default + */ + this.msSinceLastClick = Number.MAX_VALUE; + + /** + * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging. + * @default + */ + this.targetObject = null; + + /** + * This array is erased and re-populated every time this Pointer is updated. It contains references to all + * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be + * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over + * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset + * every frame. + * @property {array} interactiveCandidates + * @default + */ + this.interactiveCandidates = []; + + /** + * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active. + * @default + */ + this.active = false; + + /** + * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. + * @default + */ + this.dirty = false; + + /** + * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display. + */ + this.position = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. + */ + this.positionDown = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released. + */ + this.positionUp = new Phaser.Point(); + + /** + * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. + * The Circle size is 44px (Apples recommended "finger tip" size). + * @property {Phaser.Circle} circle + */ + this.circle = new Phaser.Circle(0, 0, 44); + + /** + * Click trampolines associated with this pointer. See `addClickTrampoline`. + * @property {object[]|null} _clickTrampolines + * @private + */ + this._clickTrampolines = null; + + /** + * When the Pointer has click trampolines the last target object is stored here + * so it can be used to check for validity of the trampoline in a post-Up/'stop'. + * @property {object} _trampolineTargetObject + * @private + */ + this._trampolineTargetObject = null; + +}; + +/** +* No buttons at all. +* @constant +* @type {number} +*/ +Phaser.Pointer.NO_BUTTON = 0; + +/** +* The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. +* @constant +* @type {number} +*/ +Phaser.Pointer.LEFT_BUTTON = 1; + +/** +* The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. +* @constant +* @type {number} +*/ +Phaser.Pointer.RIGHT_BUTTON = 2; + +/** +* The Middle Mouse button. +* @constant +* @type {number} +*/ +Phaser.Pointer.MIDDLE_BUTTON = 4; + +/** +* The X1 button. This is typically the mouse Back button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.BACK_BUTTON = 8; + +/** +* The X2 button. This is typically the mouse Forward button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.FORWARD_BUTTON = 16; + +/** +* The Eraser pen button on PointerEvent supported devices only. +* @constant +* @type {number} +*/ +Phaser.Pointer.ERASER_BUTTON = 32; + +Phaser.Pointer.prototype = { + + /** + * Resets the states of all the button booleans. + * + * @method Phaser.Pointer#resetButtons + * @protected + */ + resetButtons: function () { + + this.isDown = false; + this.isUp = true; + + if (this.isMouse) + { + this.leftButton.reset(); + this.middleButton.reset(); + this.rightButton.reset(); + this.backButton.reset(); + this.forwardButton.reset(); + this.eraserButton.reset(); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsDown + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsDown: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.start(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.start(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.start(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.start(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.start(event); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsUp + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUp: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.stop(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.stop(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.stop(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.stop(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.stop(event); + } + + }, + + /** + * Called by updateButtons. + * + * @method Phaser.Pointer#processButtonsUpDown + * @private + * @param {integer} buttons - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons MouseEvent#buttons} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUpDown: function (buttons, event) { + + var down = (event.type.toLowerCase().substr(-4) === 'down'); + var move = (event.type.toLowerCase().substr(-4) === 'move'); + + if (buttons !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && buttons === 1 && event.ctrlKey) + { + buttons = 2; + } + + // Note: These are bitwise checks, not booleans + this.leftButton.startStop(Phaser.Pointer.LEFT_BUTTON & buttons, event); + this.rightButton.startStop(Phaser.Pointer.RIGHT_BUTTON & buttons, event); + this.middleButton.startStop(Phaser.Pointer.MIDDLE_BUTTON & buttons, event); + this.backButton.startStop(Phaser.Pointer.BACK_BUTTON & buttons, event); + this.forwardButton.startStop(Phaser.Pointer.FORWARD_BUTTON & buttons, event); + this.eraserButton.startStop(Phaser.Pointer.ERASER_BUTTON & buttons, event); + } + else + { + // No buttons property (like Safari on OSX when using a trackpad) + // Attempt to use event.button property or fallback to default + if (event.button !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && event.ctrlKey && event.button === 0) + { + this.rightButton.start(event); + } + else + { + if (down) + { + this.processButtonsDown(event.button, event); + } + else if (!move) + { + this.processButtonsUp(event.button, event); + } + } + } + else + { + if (down) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (event.ctrlKey) + { + this.rightButton.start(event); + } + else + { + this.leftButton.start(event); + } + } + else + { + this.leftButton.stop(event); + this.rightButton.stop(event); + } + } + } + + }, + + /** + * Called when the event.buttons property changes from zero. + * Contains a button bitmask. + * + * @method Phaser.Pointer#updateButtons + * @protected + * @param {MouseEvent} event - The DOM event. + */ + updateButtons: function (event) { + + this.button = event.button; + this.processButtonsUpDown(event.buttons, event); + + this.isUp = true; + this.isDown = false; + + if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown) + { + this.isUp = false; + this.isDown = true; + } + + }, + + /** + * Called when the Pointer is pressed onto the touchscreen. + * @method Phaser.Pointer#start + * @param {any} event - The DOM event from the browser. + */ + start: function (event) { + + var input = this.game.input; + + if (event['pointerId']) + { + this.pointerId = event.pointerId; + } + + this.identifier = event.identifier; + this.target = event.target; + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = true; + this.isUp = false; + } + + this.active = true; + this.withinGame = true; + this.dirty = false; + + this._history = []; + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + // Work out how long it has been since the last click + this.msSinceLastClick = this.game.time.time - this.timeDown; + this.timeDown = this.game.time.time; + this._holdSent = false; + + // This sets the x/y and other local values + this.move(event, true); + + // x and y are the old values here? + this.positionDown.setTo(this.x, this.y); + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.x = this.x; + input.y = this.y; + input.position.setTo(this.x, this.y); + input.onDown.dispatch(this, event); + input.resetSpeed(this.x, this.y); + } + + this._stateReset = false; + + this.totalTouches++; + + if (this.targetObject !== null) + { + this.targetObject._touchedHandler(this); + } + + return this; + + }, + + /** + * Called by the Input Manager. + * @method Phaser.Pointer#update + */ + update: function () { + + var input = this.game.input; + + if (this.active) + { + // Force a check? + if (this.dirty) + { + if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(false); + } + + this.dirty = false; + } + + if (this._holdSent === false && this.duration >= input.holdRate) + { + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onHold.dispatch(this); + } + + this._holdSent = true; + } + + // Update the droppings history + if (input.recordPointerHistory && this.game.time.time >= this._nextDrop) + { + this._nextDrop = this.game.time.time + input.recordRate; + + this._history.push({ + x: this.position.x, + y: this.position.y + }); + + if (this._history.length > input.recordLimit) + { + this._history.shift(); + } + } + } + + }, + + /** + * Called when the Pointer is moved. + * + * @method Phaser.Pointer#move + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + * @param {boolean} [fromClick=false] - Was this called from the click event? + */ + move: function (event, fromClick) { + + var input = this.game.input; + + if (input.pollLocked) + { + return; + } + + if (fromClick === undefined) { fromClick = false; } + + if (event.button !== undefined) + { + this.button = event.button; + } + + if (this.isMouse) + { + this.updateButtons(event); + } + + 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 && 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.scale.offset.x) * input.scale.x; + this.y = (this.pageY - this.game.scale.offset.y) * input.scale.y; + + this.position.setTo(this.x, this.y); + this.circle.x = this.x; + this.circle.y = this.y; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.activePointer = this; + input.x = this.x; + input.y = this.y; + input.position.setTo(input.x, input.y); + input.circle.x = input.x; + input.circle.y = input.y; + } + + this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY); + + var i = input.moveCallbacks.length; + + while (i--) + { + input.moveCallbacks[i].callback.call(input.moveCallbacks[i].context, this, this.x, this.y, fromClick); + } + + // Easy out if we're dragging something and it still exists + if (this.targetObject !== null && (!this.game.paused || this.targetObject.noPause) && this.targetObject.isDragged === true) + { + if (this.targetObject.update(this) === false) + { + this.targetObject = null; + } + } + else if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(fromClick); + } + + return this; + + }, + + /** + * Process all interactive objects to find out which ones were updated in the recent Pointer move. + * + * @method Phaser.Pointer#processInteractiveObjects + * @protected + * @param {boolean} [fromClick=false] - Was this called from the click event? + * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. + */ + processInteractiveObjects: function (fromClick) { + + // Work out which object is on the top + var highestRenderOrderID = 0; + var highestInputPriorityID = -1; + var candidateTarget = null; + + // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID + // We know they'll be valid for input detection but not which is the top just yet + + var currentNode = this.game.input.interactiveItems.first; + + this.interactiveCandidates = []; + + while (currentNode) + { + // Reset checked status + currentNode.checked = false; + + if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false) && (!this.game.paused || currentNode.sprite.noPause)) + { + // Flag it as checked so we don't re-scan it on the next phase + currentNode.checked = true; + + if ((fromClick && currentNode.checkPointerDown(this, true)) || + (!fromClick && currentNode.checkPointerOver(this, true))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID + // because if their ID is lower anyway then we can just automatically discount them + // (A node that was previously checked did not request a pixel-perfect check.) + + currentNode = this.game.input.interactiveItems.first; + + while (currentNode) + { + if (!currentNode.checked && + currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true)) + { + if ((fromClick && currentNode.checkPointerDown(this, false)) || + (!fromClick && currentNode.checkPointerOver(this, false))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + if (this.game.input.customCandidateHandler) + { + candidateTarget = this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext, this, this.interactiveCandidates, candidateTarget); + } + + this.swapTarget(candidateTarget, false); + + return (this.targetObject !== null); + + }, + + /** + * This will change the `Pointer.targetObject` object to be the one provided. + * + * This allows you to have fine-grained control over which object the Pointer is targeting. + * + * Note that even if you set a new Target here, it is still able to be replaced by any other valid + * target during the next Pointer update. + * + * @method Phaser.Pointer#swapTarget + * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. + * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. + */ + swapTarget: function (newTarget, silent) { + + if (silent === undefined) { silent = false; } + + // Now we know the top-most item (if any) we can process it + if (newTarget === null) + { + // The pointer isn't currently over anything, check if we've got a lingering previous target + if (this.targetObject) + { + this.targetObject._pointerOutHandler(this, silent); + this.targetObject = null; + } + } + else + { + if (this.targetObject === null) + { + // And now set the new one + this.targetObject = newTarget; + newTarget._pointerOverHandler(this, silent); + } + else + { + // We've got a target from the last update + if (this.targetObject === newTarget) + { + // Same target as before, so update it + if (newTarget.update(this) === false) + { + this.targetObject = null; + } + } + else + { + // The target has changed, so tell the old one we've left it + this.targetObject._pointerOutHandler(this, silent); + + // And now set the new one + this.targetObject = newTarget; + this.targetObject._pointerOverHandler(this, silent); + } + } + } + + }, + + /** + * Called when the Pointer leaves the target area. + * + * @method Phaser.Pointer#leave + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + leave: function (event) { + + this.withinGame = false; + this.move(event, false); + + }, + + /** + * Called when the Pointer leaves the touchscreen. + * + * @method Phaser.Pointer#stop + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + stop: function (event) { + + var input = this.game.input; + + if (this._stateReset && this.withinGame) + { + event.preventDefault(); + return; + } + + this.timeUp = this.game.time.time; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onUp.dispatch(this, event); + + // Was it a tap? + if (this.duration >= 0 && this.duration <= input.tapRate) + { + // Was it a double-tap? + if (this.timeUp - this.previousTapTime < input.doubleTapRate) + { + // Yes, let's dispatch the signal then with the 2nd parameter set to true + input.onTap.dispatch(this, true); + } + else + { + // Wasn't a double-tap, so dispatch a single tap signal + input.onTap.dispatch(this, false); + } + + this.previousTapTime = this.timeUp; + } + } + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = false; + this.isUp = true; + } + + // Mouse is always active + if (this.id > 0) + { + this.active = false; + } + + this.withinGame = this.game.scale.bounds.contains(event.pageX, event.pageY); + this.pointerId = null; + this.identifier = null; + + this.positionUp.setTo(this.x, this.y); + + if (this.isMouse === false) + { + input.currentPointers--; + } + + input.interactiveItems.callAll('_releasedHandler', this); + + if (this._clickTrampolines) + { + this._trampolineTargetObject = this.targetObject; + } + + this.targetObject = null; + + return this; + + }, + + /** + * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. + * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. + * @method Phaser.Pointer#justPressed + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate. + * @return {boolean} true if the Pointer was pressed down within the duration given. + */ + justPressed: function (duration) { + + duration = duration || this.game.input.justPressedRate; + + return (this.isDown === true && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. + * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. + * @method Phaser.Pointer#justReleased + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate. + * @return {boolean} true if the Pointer was released within the duration given. + */ + justReleased: function (duration) { + + duration = duration || this.game.input.justReleasedRate; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Add a click trampoline to this pointer. + * + * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily + * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen + * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. + * + * This is used internally by the ScaleManager; click trampoline usage is uncommon. + * Click trampolines can only be added to pointers that are currently down. + * + * @method Phaser.Pointer#addClickTrampoline + * @protected + * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer. + * @param {function} callback - Callback to run/trampoline. + * @param {object} callbackContext - Context of the callback. + * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array. + */ + addClickTrampoline: function (name, callback, callbackContext, callbackArgs) { + + if (!this.isDown) + { + return; + } + + var trampolines = (this._clickTrampolines = this._clickTrampolines || []); + + for (var i = 0; i < trampolines.length; i++) + { + if (trampolines[i].name === name) + { + trampolines.splice(i, 1); + break; + } + } + + trampolines.push({ + name: name, + targetObject: this.targetObject, + callback: callback, + callbackContext: callbackContext, + callbackArgs: callbackArgs + }); + + }, + + /** + * Fire all click trampolines for which the pointers are still referring to the registered object. + * @method Phaser.Pointer#processClickTrampolines + * @private + */ + processClickTrampolines: function () { + + var trampolines = this._clickTrampolines; + + if (!trampolines) + { + return; + } + + for (var i = 0; i < trampolines.length; i++) + { + var trampoline = trampolines[i]; + + if (trampoline.targetObject === this._trampolineTargetObject) + { + trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs); + } + } + + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + }, + + /** + * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. + * @method Phaser.Pointer#reset + */ + reset: function () { + + if (this.isMouse === false) + { + this.active = false; + } + + this.pointerId = null; + this.identifier = null; + this.dirty = false; + this.totalTouches = 0; + this._holdSent = false; + this._history.length = 0; + this._stateReset = true; + + this.resetButtons(); + + if (this.targetObject) + { + this.targetObject._releasedHandler(this); + } + + this.targetObject = null; + + }, + + /** + * Resets the movementX and movementY properties. Use in your update handler after retrieving the values. + * @method Phaser.Pointer#resetMovement + */ + resetMovement: function() { + + this.movementX = 0; + this.movementY = 0; + + } + +}; + +Phaser.Pointer.prototype.constructor = Phaser.Pointer; + +/** +* How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. +* If not currently down it returns -1. +* If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. +* +* @name Phaser.Pointer#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* Gets the X value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldX +* @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldX", { + + get: function () { + + return this.game.world.camera.x + this.x; + + } + +}); + +/** +* Gets the Y value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldY +* @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldY", { + + get: function () { + + return this.game.world.camera.y + this.y; + + } + +}); + +/** +* Enumeration categorizing operational modes of pointers. +* +* PointerType values represent valid bitmasks. +* For example, a value representing both Mouse and Touch devices +* can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. +* +* Values may be added for future mode categorizations. +* @class Phaser.PointerMode +*/ +Phaser.PointerMode = { + + /** + * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. + * + * It has the property that a cursor is passively moved without activating the input. + * This currently corresponds with {@link Phaser.Pointer#isMouse} property. + * @constant + */ + CURSOR: 1 << 0, + + /** + * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. + * @constant + */ + CONTACT: 1 << 1 + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. +* +* @class Phaser.Touch +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Touch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * Touch events will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} touchStartCallback - A callback that can be fired on a touchStart event. + */ + this.touchStartCallback = null; + + /** + * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event. + */ + this.touchMoveCallback = null; + + /** + * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event. + */ + this.touchEndCallback = null; + + /** + * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event. + */ + this.touchEnterCallback = null; + + /** + * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event. + */ + this.touchLeaveCallback = null; + + /** + * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event. + */ + this.touchCancelCallback = null; + + /** + * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it. + * @default + */ + this.preventDefault = true; + + /** + * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received. + * @default + */ + this.event = null; + + /** + * @property {function} _onTouchStart - Internal event handler reference. + * @private + */ + this._onTouchStart = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + + /** + * @property {function} _onTouchEnd - Internal event handler reference. + * @private + */ + this._onTouchEnd = null; + + /** + * @property {function} _onTouchEnter - Internal event handler reference. + * @private + */ + this._onTouchEnter = null; + + /** + * @property {function} _onTouchLeave - Internal event handler reference. + * @private + */ + this._onTouchLeave = null; + + /** + * @property {function} _onTouchCancel - Internal event handler reference. + * @private + */ + this._onTouchCancel = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + +}; + +Phaser.Touch.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Touch#start + */ + start: function () { + + if (this._onTouchStart !== null) + { + // Avoid setting multiple listeners + 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('touchcancel', this._onTouchCancel, false); + + if (!this.game.device.cocoonJS) + { + this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false); + this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false); + } + } + + }, + + /** + * Consumes all touchmove events on the document (only enable this if you know you need it!). + * @method Phaser.Touch#consumeTouchMove + */ + consumeDocumentTouches: function () { + + this._documentTouchMove = function (event) { + event.preventDefault(); + }; + + document.addEventListener('touchmove', this._documentTouchMove, false); + + }, + + /** + * The internal method that handles the touchstart event from the browser. + * @method Phaser.Touch#onTouchStart + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchStart: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.touchStartCallback) + { + this.touchStartCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.startPointer(event.changedTouches[i]); + } + + }, + + /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. + * @method Phaser.Touch#onTouchCancel + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchCancel: function (event) { + + this.event = event; + + if (this.touchCancelCallback) + { + this.touchCancelCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchEnter + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnter: function (event) { + + this.event = event; + + if (this.touchEnterCallback) + { + this.touchEnterCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchLeave + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchLeave: function (event) { + + this.event = event; + + if (this.touchLeaveCallback) + { + this.touchLeaveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * The handler for the touchmove events. + * @method Phaser.Touch#onTouchMove + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchMove: function (event) { + + this.event = event; + + if (this.touchMoveCallback) + { + this.touchMoveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.updatePointer(event.changedTouches[i]); + } + + }, + + /** + * The handler for the touchend events. + * @method Phaser.Touch#onTouchEnd + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnd: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.touchEndCallback) + { + this.touchEndCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.Touch#stop + */ + stop: function () { + + if (this.game.device.touch) + { + this.game.canvas.removeEventListener('touchstart', this._onTouchStart); + this.game.canvas.removeEventListener('touchmove', this._onTouchMove); + this.game.canvas.removeEventListener('touchend', this._onTouchEnd); + this.game.canvas.removeEventListener('touchenter', this._onTouchEnter); + this.game.canvas.removeEventListener('touchleave', this._onTouchLeave); + this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel); + } + + } + +}; + +Phaser.Touch.prototype.constructor = Phaser.Touch; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. +* +* @class Phaser.InputHandler +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. +*/ +Phaser.InputHandler = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = sprite.game; + + /** + * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity. + * @default + */ + this.enabled = false; + + /** + * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks. + * @protected + */ + this.checked = false; + + /** + * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have + * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can + * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. + * @property {number} priorityID + * @default + */ + this.priorityID = 0; + + /** + * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. + * @default + */ + this.useHandCursor = false; + + /** + * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor? + * @private + */ + this._setHandCursor = false; + + /** + * @property {boolean} isDragged - true if the Sprite is being currently dragged. + * @default + */ + this.isDragged = false; + + /** + * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally. + * @default + */ + this.allowHorizontalDrag = true; + + /** + * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically. + * @default + */ + this.allowVerticalDrag = true; + + /** + * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. + * @default + */ + this.bringToTop = false; + + /** + * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset. + * @default + */ + this.snapOffset = null; + + /** + * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. + * @default + */ + this.snapOnDrag = false; + + /** + * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release. + * @default + */ + this.snapOnRelease = false; + + /** + * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid. + * @default + */ + this.snapX = 0; + + /** + * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid. + * @default + */ + this.snapY = 0; + + /** + * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid. + * @default + */ + this.snapOffsetX = 0; + + /** + * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid.. + * @default + */ + this.snapOffsetY = 0; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. + * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over. + * @default + */ + this.pixelPerfectOver = false; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive so only enable if you really need it. + * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite. + * @default + */ + this.pixelPerfectClick = false; + + /** + * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. + * @default + */ + this.pixelPerfectAlpha = 255; + + /** + * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no + * @default + */ + this.draggable = false; + + /** + * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag. + * @default + */ + this.boundsRect = null; + + /** + * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. + * @default + */ + this.boundsSprite = null; + + /** + * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. + */ + this.scaleLayer = false; + + /** + * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from. + */ + this.dragOffset = new Phaser.Point(); + + /** + * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? + */ + this.dragFromCenter = false; + + /** + * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. + */ + this.dragStopBlocksInputUp = false; + + /** + * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. + */ + this.dragStartPoint = new Phaser.Point(); + + /** + * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. + */ + this.dragDistanceThreshold = 0; + + /** + * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. + */ + this.dragTimeThreshold = 0; + + /** + * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. + */ + this.downPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. + */ + this.snapPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} _dragPoint - Internal cache var. + * @private + */ + this._dragPoint = new Phaser.Point(); + + /** + * @property {boolean} _dragPhase - Internal cache var. + * @private + */ + this._dragPhase = false; + + /** + * @property {boolean} _pendingDrag - Internal cache var. + * @private + */ + this._pendingDrag = false; + + /** + * @property {boolean} _dragTimePass - Internal cache var. + * @private + */ + this._dragTimePass = false; + + /** + * @property {boolean} _dragDistancePass - Internal cache var. + * @private + */ + this._dragDistancePass = false; + + /** + * @property {boolean} _wasEnabled - Internal cache var. + * @private + */ + this._wasEnabled = false; + + /** + * @property {Phaser.Point} _tempPoint - Internal cache var. + * @private + */ + this._tempPoint = new Phaser.Point(); + + /** + * @property {array} _pointerData - Internal cache var. + * @private + */ + this._pointerData = []; + + this._pointerData.push({ + id: 0, + x: 0, + y: 0, + camX: 0, + camY: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }); + +}; + +Phaser.InputHandler.prototype = { + + /** + * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. + * + * @method Phaser.InputHandler#start + * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. + * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) + * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound. + */ + start: function (priority, useHandCursor) { + + priority = priority || 0; + if (useHandCursor === undefined) { useHandCursor = false; } + + // Turning on + if (this.enabled === false) + { + // Register, etc + this.game.input.interactiveItems.add(this); + this.useHandCursor = useHandCursor; + this.priorityID = priority; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + + this.snapOffset = new Phaser.Point(); + this.enabled = true; + this._wasEnabled = true; + + } + + this.sprite.events.onAddedToGroup.add(this.addedToGroup, this); + this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this); + + return this.sprite; + + }, + + /** + * Handles when the parent Sprite is added to a new Group. + * + * @method Phaser.InputHandler#addedToGroup + * @private + */ + addedToGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this._wasEnabled && !this.enabled) + { + this.start(); + } + + }, + + /** + * Handles when the parent Sprite is removed from a Group. + * + * @method Phaser.InputHandler#removedFromGroup + * @private + */ + removedFromGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this.enabled) + { + this._wasEnabled = true; + this.stop(); + } + else + { + this._wasEnabled = false; + } + + }, + + /** + * Resets the Input Handler and disables it. + * @method Phaser.InputHandler#reset + */ + reset: function () { + + this.enabled = false; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + }, + + /** + * Stops the Input Handler from running. + * @method Phaser.InputHandler#stop + */ + stop: function () { + + // Turning off + if (this.enabled === false) + { + return; + } + else + { + // De-register, etc + this.enabled = false; + this.game.input.interactiveItems.remove(this); + } + + }, + + /** + * Clean up memory. + * @method Phaser.InputHandler#destroy + */ + destroy: function () { + + if (this.sprite) + { + if (this._setHandCursor) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + this.enabled = false; + + this.game.input.interactiveItems.remove(this); + + this._pointerData.length = 0; + this.boundsRect = null; + this.boundsSprite = null; + this.sprite = null; + } + + }, + + /** + * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. + * This is called by Phaser.Pointer and shouldn't typically be called directly. + * + * @method Phaser.InputHandler#validForInput + * @protected + * @param {number} highestID - The highest ID currently processed by the Pointer. + * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer. + * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? + * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection. + */ + validForInput: function (highestID, highestRenderID, includePixelPerfect) { + + if (includePixelPerfect === undefined) { includePixelPerfect = true; } + + if (!this.enabled || + this.sprite.scale.x === 0 || + this.sprite.scale.y === 0 || + this.priorityID < this.game.input.minPriorityID || + (this.sprite.parent && this.sprite.parent.ignoreChildInput)) + { + return false; + } + + // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it + if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver)) + { + return false; + } + + if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID > highestRenderID)) + { + return true; + } + + return false; + + }, + + /** + * Is this object using pixel perfect checking? + * + * @method Phaser.InputHandler#isPixelPerfect + * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. + */ + isPixelPerfect: function () { + + return (this.pixelPerfectClick || this.pixelPerfectOver); + + }, + + /** + * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerX + * @param {integer} [pointerId=0] + * @return {number} The x coordinate of the Input pointer. + */ + pointerX: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].x; + + }, + + /** + * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerY + * @param {integer} [pointerId=0] + * @return {number} The y coordinate of the Input pointer. + */ + pointerY: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].y; + + }, + + /** + * If the Pointer is down this returns true. + * This *only* checks if the Pointer is down, not if it's down over any specific Sprite. + * + * @method Phaser.InputHandler#pointerDown + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is down, otherwise false. + */ + pointerDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDown; + + }, + + /** + * If the Pointer is up this returns true. + * This *only* checks if the Pointer is up, not if it's up over any specific Sprite. + * + * @method Phaser.InputHandler#pointerUp + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is up, otherwise false. + */ + pointerUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isUp; + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeDown + * @param {integer} [pointerId=(check all)] + * @return {number} + */ + pointerTimeDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeDown; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeUp + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeUp; + + }, + + /** + * Is the Pointer over this Sprite? + * + * @method Phaser.InputHandler#pointerOver + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object. + */ + pointerOver: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOver) + { + return true; + } + } + + return false; + } + else + { + return this._pointerData[pointerId].isOver; + } + + }, + + /** + * Is the Pointer outside of this Sprite? + * + * @method Phaser.InputHandler#pointerOut + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. + */ + pointerOut: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOut) + { + return true; + } + } + } + else + { + return this._pointerData[pointerId].isOut; + } + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOver + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOver: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOver; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOut + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOut: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOut; + + }, + + /** + * Is this sprite being dragged by the mouse or not? + * + * @method Phaser.InputHandler#pointerDragged + * @param {integer} [pointerId=0] + * @return {boolean} True if the pointer is dragging an object, otherwise false. + */ + pointerDragged: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDragged; + + }, + + /** + * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerDown + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} True if the pointer is down, otherwise false. + */ + checkPointerDown: function (pointer, fastTest) { + + if (!pointer.isDown || + !this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectClick) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Checks if the given pointer is over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerOver + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} + */ + checkPointerOver: function (pointer, fastTest) { + + if (!this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectOver) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. + * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. + * + * @method Phaser.InputHandler#checkPixel + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters. + * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha + */ + checkPixel: function (x, y, pointer) { + + // Grab a pixel from our image into the hitCanvas and then test it + if (this.sprite.texture.baseTexture.source) + { + if (x === null && y === null) + { + // Use the pointer parameter + this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint); + + var x = this._tempPoint.x; + var y = this._tempPoint.y; + } + + if (this.sprite.anchor.x !== 0) + { + x -= -this.sprite.texture.frame.width * this.sprite.anchor.x; + } + + if (this.sprite.anchor.y !== 0) + { + y -= -this.sprite.texture.frame.height * this.sprite.anchor.y; + } + + x += this.sprite.texture.frame.x; + y += this.sprite.texture.frame.y; + + if (this.sprite.texture.trim) + { + x -= this.sprite.texture.trim.x; + y -= this.sprite.texture.trim.y; + + // If the coordinates are outside the trim area we return false immediately, to save doing a draw call + if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom) + { + this._dx = x; + this._dy = y; + return false; + } + } + + this._dx = x; + this._dy = y; + + this.game.input.hitContext.clearRect(0, 0, 1, 1); + this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1); + + if (rgb.data[3] >= this.pixelPerfectAlpha) + { + return true; + } + } + + return false; + + }, + + /** + * Internal Update method. This is called automatically and handles the Pointer + * and drag update loops. + * + * @method Phaser.InputHandler#update + * @protected + * @param {Phaser.Pointer} pointer + * @return {boolean} True if the pointer is still active, otherwise false. + */ + update: function (pointer) { + + if (this.sprite === null || this.sprite.parent === undefined) + { + // Abort. We've been destroyed. + return; + } + + if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible) + { + this._pointerOutHandler(pointer); + return false; + } + + if (this._pendingDrag) + { + if (!this._dragDistancePass) + { + this._dragDistancePass = (Phaser.Math.distance(pointer.x, pointer.y, this.downPoint.x, this.downPoint.y) >= this.dragDistanceThreshold); + } + + if (this._dragDistancePass && this._dragTimePass) + { + this.startDrag(pointer); + } + + return true; + } + else if (this.draggable && this._draggedPointerID === pointer.id) + { + return this.updateDrag(pointer, false); + } + else if (this._pointerData[pointer.id].isOver) + { + 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; + } + } + }, + + /** + * Internal method handling the pointer over event. + * + * @method Phaser.InputHandler#_pointerOverHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOverHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (data.isOver === false || pointer.dirty) + { + var sendEvent = (data.isOver === false); + + data.isOver = true; + data.isOut = false; + data.timeOver = this.game.time.time; + data.x = pointer.x - this.sprite.x; + data.y = pointer.y - this.sprite.y; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = "pointer"; + this._setHandCursor = true; + } + + if (!silent && sendEvent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOver$dispatch(this.sprite, pointer); + } + + if (this.sprite.parent && this.sprite.parent.onChildInputOver) + { + this.sprite.parent.onChildInputOver.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the pointer out event. + * + * @method Phaser.InputHandler#_pointerOutHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOutHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + data.isOver = false; + data.isOut = true; + data.timeOut = this.game.time.time; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + if (!silent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOut$dispatch(this.sprite, pointer); + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputOut) + { + this.sprite.parent.onChildInputOut.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the touched / clicked event. + * + * @method Phaser.InputHandler#_touchedHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + */ + _touchedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (!data.isDown && data.isOver) + { + if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer)) + { + return; + } + + data.isDown = true; + data.isUp = false; + data.timeDown = this.game.time.time; + + this.downPoint.set(pointer.x, pointer.y); + + // It's possible the onInputDown event creates a new Sprite that is on-top of this one, so we ought to force a Pointer update + pointer.dirty = true; + + if (this.sprite && this.sprite.events) + { + this.sprite.events.onInputDown$dispatch(this.sprite, pointer); + + // The event above might have destroyed this sprite. + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputDown) + { + this.sprite.parent.onChildInputDown.dispatch(this.sprite, pointer); + } + + // The events might have destroyed this sprite. + if (this.sprite === null) + { + return; + } + } + + // Start drag + if (this.draggable && this.isDragged === false) + { + if (this.dragTimeThreshold === 0 && this.dragDistanceThreshold === 0) + { + this.startDrag(pointer); + } + else + { + this._pendingDrag = true; + + this._dragDistancePass = (this.dragDistanceThreshold === 0); + + if (this.dragTimeThreshold > 0) + { + this._dragTimePass = false; + this.game.time.events.add(this.dragTimeThreshold, this.dragTimeElapsed, this, pointer); + } + else + { + this._dragTimePass = true; + } + } + } + + if (this.bringToTop) + { + this.sprite.bringToTop(); + } + } + + }, + + /** + * Internal method handling the drag threshold timer. + * + * @method Phaser.InputHandler#dragTimeElapsed + * @private + * @param {Phaser.Pointer} pointer + */ + dragTimeElapsed: function (pointer) { + + this._dragTimePass = true; + + if (this._pendingDrag && this.sprite) + { + if (this._dragDistancePass) + { + this.startDrag(pointer); + } + } + + }, + + /** + * Internal method handling the pointer released event. + * @method Phaser.InputHandler#_releasedHandler + * @private + * @param {Phaser.Pointer} pointer + */ + _releasedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + // If was previously touched by this Pointer, check if still is AND still over this item + if (data.isDown && pointer.isUp) + { + data.isDown = false; + data.isUp = true; + data.timeUp = this.game.time.time; + data.downDuration = data.timeUp - data.timeDown; + + // Only release the InputUp signal if the pointer is still over this sprite + var isOver = this.checkPointerOver(pointer); + + if (this.sprite && this.sprite.events) + { + if (!this.dragStopBlocksInputUp || + this.dragStopBlocksInputUp && !(this.draggable && this.isDragged && this._draggedPointerID === pointer.id)) + { + this.sprite.events.onInputUp$dispatch(this.sprite, pointer, isOver); + } + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputUp) + { + this.sprite.parent.onChildInputUp.dispatch(this.sprite, pointer, isOver); + } + + // The onInputUp event may have changed the sprite so that checkPointerOver is no longer true, so update it. + if (isOver) + { + isOver = this.checkPointerOver(pointer); + } + } + + data.isOver = isOver; + + if (!isOver && this.useHandCursor) + { + this.game.canvas.style.cursor = "default"; + this._setHandCursor = false; + } + + // It's possible the onInputUp event created a new Sprite that is on-top of this one, so force a Pointer update + pointer.dirty = true; + + this._pendingDrag = false; + + // Stop drag + if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id) + { + this.stopDrag(pointer); + } + } + + }, + + /** + * Called as a Pointer actively drags this Game Object. + * + * @method Phaser.InputHandler#updateDrag + * @private + * @param {Phaser.Pointer} pointer - The Pointer causing the drag update. + * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started. + * @return {boolean} + */ + updateDrag: function (pointer, fromStart) { + + if (fromStart === undefined) { fromStart = false; } + + if (pointer.isUp) + { + this.stopDrag(pointer); + return false; + } + + var pointerLocalCoord = this.globalToLocal(pointer); + + if (this.sprite.fixedToCamera) + { + var px = this.game.camera.scale.x * pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = this.game.camera.scale.y * pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + else + { + var px = pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + + if (this.sprite.fixedToCamera) + { + if (this.allowHorizontalDrag) + { + this.sprite.cameraOffset.x = px - this.game.camera.x; + } + + if (this.allowVerticalDrag) + { + this.sprite.cameraOffset.y = py - this.game.camera.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); + this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y); + } + } + else + { + var cx = this.game.camera.x - this._pointerData[pointer.id].camX; + var cy = this.game.camera.y - this._pointerData[pointer.id].camY; + + if (this.allowHorizontalDrag) + { + this.sprite.x = px + cx; + } + + if (this.allowVerticalDrag) + { + this.sprite.y = py + cy; + } + + 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); + this.snapPoint.set(this.sprite.x, this.sprite.y); + } + } + + this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint, fromStart); + + return true; + + }, + + /** + * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOver + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justOver: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOut + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justOut: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay)); + + }, + + /** + * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justPressed + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justPressed: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justReleased + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justReleased: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay)); + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#overDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. + */ + overDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isOver) + { + return this.game.time.time - this._pointerData[pointerId].timeOver; + } + + return -1; + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#downDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. + */ + downDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isDown) + { + return this.game.time.time - this._pointerData[pointerId].timeDown; + } + + return -1; + + }, + + /** + * Allow this Sprite to be dragged by any valid pointer. + * + * When the drag begins the Sprite.events.onDragStart event will be dispatched. + * + * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. + * + * You can control the thresholds over when a drag starts via the properties: + * + * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move + * before the drag will start. + * + * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on + * the Sprite before the drag will start. + * + * You can set either (or both) of these properties after enabling a Sprite for drag. + * + * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually + * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`. + * + * @method Phaser.InputHandler#enableDrag + * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. + * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group. + * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. + * @param {integer} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. + * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. + * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. + */ + enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) { + + if (lockCenter === undefined) { lockCenter = false; } + if (bringToTop === undefined) { bringToTop = false; } + if (pixelPerfect === undefined) { pixelPerfect = false; } + if (alphaThreshold === undefined) { alphaThreshold = 255; } + if (boundsRect === undefined) { boundsRect = null; } + if (boundsSprite === undefined) { boundsSprite = null; } + + this._dragPoint = new Phaser.Point(); + this.draggable = true; + this.bringToTop = bringToTop; + this.dragOffset = new Phaser.Point(); + this.dragFromCenter = lockCenter; + + this.pixelPerfectClick = pixelPerfect; + this.pixelPerfectAlpha = alphaThreshold; + + if (boundsRect) + { + this.boundsRect = boundsRect; + } + + if (boundsSprite) + { + this.boundsSprite = boundsSprite; + } + + }, + + /** + * Stops this sprite from being able to be dragged. + * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. + * + * @method Phaser.InputHandler#disableDrag + */ + disableDrag: function () { + + if (this._pointerData) + { + for (var i = 0; i < 10; i++) + { + this._pointerData[i].isDragged = false; + } + } + + this.draggable = false; + this.isDragged = false; + this._draggedPointerID = -1; + this._pendingDrag = false; + + }, + + /** + * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#startDrag + * @param {Phaser.Pointer} pointer + */ + startDrag: function (pointer) { + + var x = this.sprite.x; + var y = this.sprite.y; + var pointerLocalCoord = this.globalToLocal(pointer); + + this.isDragged = true; + this._draggedPointerID = pointer.id; + + this._pointerData[pointer.id].camX = this.game.camera.x; + this._pointerData[pointer.id].camY = this.game.camera.y; + + this._pointerData[pointer.id].isDragged = true; + + if (this.sprite.fixedToCamera) + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.cameraOffset.x = pointerLocalCoord.x + (this.sprite.cameraOffset.x - boundsCenterLocalCoord.x); + this.sprite.cameraOffset.y = pointerLocalCoord.y + (this.sprite.cameraOffset.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y); + } + else + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.x = pointerLocalCoord.x + (this.sprite.x - boundsCenterLocalCoord.x); + this.sprite.y = pointerLocalCoord.y + (this.sprite.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.x - pointerLocalCoord.x, this.sprite.y - pointerLocalCoord.y); + } + + this.updateDrag(pointer, true); + + if (this.bringToTop) + { + this._dragPhase = true; + this.sprite.bringToTop(); + } + + this.dragStartPoint.set(x, y); + + this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y); + + this._pendingDrag = false; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalX + * @param {number} x + */ + globalToLocalX: function (x) { + + if (this.scaleLayer) + { + x -= this.game.scale.grid.boundsFluid.x; + x *= this.game.scale.grid.scaleFluidInversed.x; + } + + return x; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalY + * @param {number} y + */ + globalToLocalY: function (y) { + + if (this.scaleLayer) + { + y -= this.game.scale.grid.boundsFluid.y; + y *= this.game.scale.grid.scaleFluidInversed.y; + } + + return y; + + }, + + /** + * Convert global coordinates to local sprite coordinates + * + * @method Phaser.InputHandler#globalToLocal + * @param {Phaser.Point} globalCoord - The global coordinates to convert. + * @return {Phaser.Point} A point containing the local coordinates. + */ + globalToLocal: function (globalCoord) { + + if (this.sprite.parent) + { + return this.game.input.getLocalPosition(this.sprite.parent, {x: globalCoord.x, y: globalCoord.y}); + } + else + { + return globalCoord; + } + + }, + + /** + * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#stopDrag + * @param {Phaser.Pointer} pointer + */ + stopDrag: function (pointer) { + + this.isDragged = false; + this._draggedPointerID = -1; + this._pointerData[pointer.id].isDragged = false; + this._dragPhase = false; + this._pendingDrag = false; + + if (this.snapOnRelease) + { + if (this.sprite.fixedToCamera) + { + 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 + { + 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); + } + } + + this.sprite.events.onDragStop$dispatch(this.sprite, pointer); + + if (this.checkPointerOver(pointer) === false) + { + this._pointerOutHandler(pointer); + } + + }, + + /** + * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! + * + * @method Phaser.InputHandler#setDragLock + * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false. + * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false. + */ + setDragLock: function (allowHorizontal, allowVertical) { + + if (allowHorizontal === undefined) { allowHorizontal = true; } + if (allowVertical === undefined) { allowVertical = true; } + + this.allowHorizontalDrag = allowHorizontal; + this.allowVerticalDrag = allowVertical; + + }, + + /** + * Make this Sprite snap to the given grid either during drag or when it's released. + * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. + * + * @method Phaser.InputHandler#enableSnap + * @param {number} snapX - The width of the grid cell to snap to. + * @param {number} snapY - The height of the grid cell to snap to. + * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged. + * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released. + * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid. + * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid. + */ + enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) { + + if (onDrag === undefined) { onDrag = true; } + if (onRelease === undefined) { onRelease = false; } + if (snapOffsetX === undefined) { snapOffsetX = 0; } + if (snapOffsetY === undefined) { snapOffsetY = 0; } + + this.snapX = snapX; + this.snapY = snapY; + this.snapOffsetX = snapOffsetX; + this.snapOffsetY = snapOffsetY; + this.snapOnDrag = onDrag; + this.snapOnRelease = onRelease; + + }, + + /** + * Stops the sprite from snapping to a grid during drag or release. + * + * @method Phaser.InputHandler#disableSnap + */ + disableSnap: function () { + + this.snapOnDrag = false; + this.snapOnRelease = false; + + }, + + /** + * Bounds Rect check for the sprite drag + * + * @method Phaser.InputHandler#checkBoundsRect + */ + checkBoundsRect: function () { + + if (this.sprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsRect.left) + { + this.sprite.cameraOffset.x = this.boundsRect.left; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right) + { + this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsRect.top) + { + this.sprite.cameraOffset.y = this.boundsRect.top; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom) + { + this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsRect.left) + { + this.sprite.x = this.boundsRect.x + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsRect.right) + { + this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsRect.top) + { + this.sprite.y = this.boundsRect.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsRect.bottom) + { + this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + }, + + /** + * Parent Sprite Bounds check for the sprite drag. + * + * @method Phaser.InputHandler#checkBoundsSprite + */ + checkBoundsSprite: function () { + + if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x) + { + this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width)) + { + this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y) + { + this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height)) + { + this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsSprite.left) + { + this.sprite.x = this.boundsSprite.left + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsSprite.right) + { + this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsSprite.top) + { + this.sprite.y = this.boundsSprite.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsSprite.bottom) + { + this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + } + +}; + +Phaser.InputHandler.prototype.constructor = Phaser.InputHandler; + +/** +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Gamepad class handles gamepad input and dispatches gamepad events. +* +* Remember to call `gamepad.start()`. +* +* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! +* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it +* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. +* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. +* +* @class Phaser.Gamepad +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Gamepad = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads + * @private + */ + this._gamepadIndexMap = {}; + + /** + * @property {Array} _rawPads - The raw state of the gamepads from the browser + * @private + */ + this._rawPads = []; + + /** + * @property {boolean} _active - Private flag for whether or not the API is polled + * @private + * @default + */ + this._active = false; + + /** + * Gamepad input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation. + * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not? + * @private + */ + this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') !== -1) || !!navigator.getGamepads; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevRawGamepadTypes + * @private + * @default + */ + this._prevRawGamepadTypes = []; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevTimestamps + * @private + * @default + */ + this._prevTimestamps = []; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._ongamepadconnected = null; + + /** + * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._gamepaddisconnected = null; + + /** + * @property {Array} _gamepads - The four Phaser Gamepads. + * @private + */ + this._gamepads = [ + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this) + ]; + +}; + +Phaser.Gamepad.prototype = { + + /** + * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. + * + * @method Phaser.Gamepad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callback methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + this.callbackContext = context; + } + + }, + + /** + * Starts the Gamepad event handling. + * This MUST be called manually before Phaser will start polling the Gamepad API. + * + * @method Phaser.Gamepad#start + */ + start: function () { + + if (this._active) + { + // Avoid setting multiple listeners + return; + } + + this._active = true; + + var _this = this; + + this._onGamepadConnected = function (event) { + return _this.onGamepadConnected(event); + }; + + this._onGamepadDisconnected = function (event) { + return _this.onGamepadDisconnected(event); + }; + + window.addEventListener('gamepadconnected', this._onGamepadConnected, false); + window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false); + + }, + + /** + * Handles the connection of a Gamepad. + * + * @method onGamepadConnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadConnected: function (event) { + + var newPad = event.gamepad; + this._rawPads.push(newPad); + this._gamepads[newPad.index].connect(newPad); + + }, + + /** + * Handles the disconnection of a Gamepad. + * + * @method onGamepadDisconnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadDisconnected: function (event) { + + var removedPad = event.gamepad; + + for (var i in this._rawPads) + { + if (this._rawPads[i].index === removedPad.index) + { + this._rawPads.splice(i,1); + } + } + + this._gamepads[removedPad.index].disconnect(); + + }, + + /** + * Main gamepad update loop. Should not be called manually. + * @method Phaser.Gamepad#update + * @protected + */ + update: function () { + + this._pollGamepads(); + + this.pad1.pollStatus(); + this.pad2.pollStatus(); + this.pad3.pollStatus(); + this.pad4.pollStatus(); + + }, + + /** + * Updating connected gamepads (for Google Chrome). Should not be called manually. + * + * @method Phaser.Gamepad#_pollGamepads + * @private + */ + _pollGamepads: function () { + + if (!this._active) + { + return; + } + + if (navigator['getGamepads']) + { + var rawGamepads = navigator.getGamepads(); + } + else if (navigator['webkitGetGamepads']) + { + var rawGamepads = navigator.webkitGetGamepads(); + } + else if (navigator['webkitGamepads']) + { + var rawGamepads = navigator.webkitGamepads(); + } + + if (rawGamepads) + { + this._rawPads = []; + + var gamepadsChanged = false; + + for (var i = 0; i < rawGamepads.length; i++) + { + if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i]) + { + gamepadsChanged = true; + this._prevRawGamepadTypes[i] = typeof rawGamepads[i]; + } + + if (rawGamepads[i]) + { + this._rawPads.push(rawGamepads[i]); + } + + // Support max 4 pads at the moment + if (i === 3) + { + break; + } + } + + for (var g = 0; g < this._gamepads.length; g++) + { + this._gamepads[g]._rawPad = this._rawPads[g]; + } + + if (gamepadsChanged) + { + var validConnections = { rawIndices: {}, padIndices: {} }; + var singlePad; + + for (var j = 0; j < this._gamepads.length; j++) + { + singlePad = this._gamepads[j]; + + if (singlePad.connected) + { + for (var k = 0; k < this._rawPads.length; k++) + { + if (this._rawPads[k].index === singlePad.index) + { + validConnections.rawIndices[singlePad.index] = true; + validConnections.padIndices[j] = true; + } + } + } + } + + for (var l = 0; l < this._gamepads.length; l++) + { + singlePad = this._gamepads[l]; + + if (validConnections.padIndices[l]) + { + continue; + } + + if (this._rawPads.length < 1) + { + singlePad.disconnect(); + } + + for (var m = 0; m < this._rawPads.length; m++) + { + if (validConnections.padIndices[l]) + { + break; + } + + var rawPad = this._rawPads[m]; + + if (rawPad) + { + if (validConnections.rawIndices[rawPad.index]) + { + singlePad.disconnect(); + continue; + } + else + { + singlePad.connect(rawPad); + validConnections.rawIndices[rawPad.index] = true; + validConnections.padIndices[l] = true; + } + } + else + { + singlePad.disconnect(); + } + } + } + } + } + }, + + /** + * Sets the deadZone variable for all four gamepads + * @method Phaser.Gamepad#setDeadZones + */ + setDeadZones: function (value) { + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].deadZone = value; + } + + }, + + /** + * Stops the Gamepad event handling. + * + * @method Phaser.Gamepad#stop + */ + stop: function () { + + this._active = false; + + window.removeEventListener('gamepadconnected', this._onGamepadConnected); + window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected); + + }, + + /** + * Reset all buttons/axes of all gamepads + * @method Phaser.Gamepad#reset + */ + reset: function () { + + this.update(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].reset(); + } + + }, + + /** + * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justPressed(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justReleased(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns true if the button is currently pressed down, on ANY gamepad. + * @method Phaser.Gamepad#isDown + * @param {number} buttonCode - The buttonCode of the button to check for. + * @return {boolean} True if a button is currently down. + */ + isDown: function (buttonCode) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].isDown(buttonCode) === true) + { + return true; + } + } + + return false; + }, + + /** + * Destroys this object and the associated event listeners. + * + * @method Phaser.Gamepad#destroy + */ + destroy: function () { + + this.stop(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].destroy(); + } + + } + +}; + +Phaser.Gamepad.prototype.constructor = Phaser.Gamepad; + +/** +* If the gamepad input is active or not - if not active it should not be updated from Input.js +* @name Phaser.Gamepad#active +* @property {boolean} active - If the gamepad input is active or not. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "active", { + + get: function () { + return this._active; + } + +}); + +/** +* Whether or not gamepads are supported in current browser. +* @name Phaser.Gamepad#supported +* @property {boolean} supported - Whether or not gamepads are supported in current browser. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "supported", { + + get: function () { + return this._gamepadSupportAvailable; + } + +}); + +/** +* How many live gamepads are currently connected. +* @name Phaser.Gamepad#padsConnected +* @property {number} padsConnected - How many live gamepads are currently connected. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", { + + get: function () { + return this._rawPads.length; + } + +}); + +/** +* Gamepad #1 +* @name Phaser.Gamepad#pad1 +* @property {Phaser.SinglePad} pad1 - Gamepad #1; +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad1", { + + get: function () { + return this._gamepads[0]; + } + +}); + +/** +* Gamepad #2 +* @name Phaser.Gamepad#pad2 +* @property {Phaser.SinglePad} pad2 - Gamepad #2 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad2", { + + get: function () { + return this._gamepads[1]; + } + +}); + +/** +* Gamepad #3 +* @name Phaser.Gamepad#pad3 +* @property {Phaser.SinglePad} pad3 - Gamepad #3 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad3", { + + get: function () { + return this._gamepads[2]; + } + +}); + +/** +* Gamepad #4 +* @name Phaser.Gamepad#pad4 +* @property {Phaser.SinglePad} pad4 - Gamepad #4 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad4", { + + get: function () { + return this._gamepads[3]; + } + +}); + +Phaser.Gamepad.BUTTON_0 = 0; +Phaser.Gamepad.BUTTON_1 = 1; +Phaser.Gamepad.BUTTON_2 = 2; +Phaser.Gamepad.BUTTON_3 = 3; +Phaser.Gamepad.BUTTON_4 = 4; +Phaser.Gamepad.BUTTON_5 = 5; +Phaser.Gamepad.BUTTON_6 = 6; +Phaser.Gamepad.BUTTON_7 = 7; +Phaser.Gamepad.BUTTON_8 = 8; +Phaser.Gamepad.BUTTON_9 = 9; +Phaser.Gamepad.BUTTON_10 = 10; +Phaser.Gamepad.BUTTON_11 = 11; +Phaser.Gamepad.BUTTON_12 = 12; +Phaser.Gamepad.BUTTON_13 = 13; +Phaser.Gamepad.BUTTON_14 = 14; +Phaser.Gamepad.BUTTON_15 = 15; + +Phaser.Gamepad.AXIS_0 = 0; +Phaser.Gamepad.AXIS_1 = 1; +Phaser.Gamepad.AXIS_2 = 2; +Phaser.Gamepad.AXIS_3 = 3; +Phaser.Gamepad.AXIS_4 = 4; +Phaser.Gamepad.AXIS_5 = 5; +Phaser.Gamepad.AXIS_6 = 6; +Phaser.Gamepad.AXIS_7 = 7; +Phaser.Gamepad.AXIS_8 = 8; +Phaser.Gamepad.AXIS_9 = 9; + +// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7). +// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button. +// In other words - discrepancies when using gamepads. + +Phaser.Gamepad.XBOX360_A = 0; +Phaser.Gamepad.XBOX360_B = 1; +Phaser.Gamepad.XBOX360_X = 2; +Phaser.Gamepad.XBOX360_Y = 3; +Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4; +Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5; +Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6; +Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7; +Phaser.Gamepad.XBOX360_BACK = 8; +Phaser.Gamepad.XBOX360_START = 9; +Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11; + +Phaser.Gamepad.XBOX360_DPAD_LEFT = 14; +Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15; +Phaser.Gamepad.XBOX360_DPAD_UP = 12; +Phaser.Gamepad.XBOX360_DPAD_DOWN = 13; + +// On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right +Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0; +Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1; +Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2; +Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3; + +// PlayStation 3 controller (masquerading as xbox360 controller) button mappings + +Phaser.Gamepad.PS3XC_X = 0; +Phaser.Gamepad.PS3XC_CIRCLE = 1; +Phaser.Gamepad.PS3XC_SQUARE = 2; +Phaser.Gamepad.PS3XC_TRIANGLE = 3; +Phaser.Gamepad.PS3XC_L1 = 4; +Phaser.Gamepad.PS3XC_R1 = 5; +Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_SELECT = 8; +Phaser.Gamepad.PS3XC_START = 9; +Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11; +Phaser.Gamepad.PS3XC_DPAD_UP = 12; +Phaser.Gamepad.PS3XC_DPAD_DOWN = 13; +Phaser.Gamepad.PS3XC_DPAD_LEFT = 14; +Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15; +Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1 + +/** +* @author @karlmacklin +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A single Phaser Gamepad +* +* @class Phaser.SinglePad +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this) +*/ +Phaser.SinglePad = function (game, padParent) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {number} index - The gamepad index as per browsers data + * @readonly + */ + this.index = null; + + /** + * @property {boolean} connected - Whether or not this particular gamepad is connected or not. + * @readonly + */ + this.connected = false; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time a button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time an axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates. + */ + this.deadZone = 0.26; + + /** + * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object + * @private + */ + this._padParent = padParent; + + /** + * @property {object} _rawPad - The 'raw' gamepad data. + * @private + */ + this._rawPad = null; + + /** + * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads. + * @private + */ + this._prevTimestamp = null; + + /** + * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected. + * @private + */ + this._buttons = []; + + /** + * @property {number} _buttonsLen - Length of the _buttons array. + * @private + */ + this._buttonsLen = 0; + + /** + * @property {Array} _axes - Current axes state. + * @private + */ + this._axes = []; + + /** + * @property {number} _axesLen - Length of the _axes array. + * @private + */ + this._axesLen = 0; + +}; + +Phaser.SinglePad.prototype = { + + /** + * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. + * + * @method Phaser.SinglePad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callbak methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + + this.callbackContext = context; + } + }, + + /** + * Gets a DeviceButton object from this controller to be stored and referenced locally. + * The DeviceButton object can then be polled, have events attached to it, etc. + * + * @method Phaser.SinglePad#getButton + * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc. + * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly. + */ + getButton: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode]; + } + else + { + return null; + } + + }, + + /** + * Main update function called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#pollStatus + */ + pollStatus: function () { + + if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp))) + { + return; + } + + for (var i = 0; i < this._buttonsLen; i++) + { + var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i]; + + if (rawButtonVal !== this._buttons[i].value) + { + if (rawButtonVal === 1) + { + this.processButtonDown(i, rawButtonVal); + } + else if (rawButtonVal === 0) + { + this.processButtonUp(i, rawButtonVal); + } + else + { + this.processButtonFloat(i, rawButtonVal); + } + } + } + + for (var index = 0; index < this._axesLen; index++) + { + var value = this._rawPad.axes[index]; + + if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone)) + { + this.processAxisChange(index, value); + } + else + { + this.processAxisChange(index, 0); + } + } + + this._prevTimestamp = this._rawPad.timestamp; + + }, + + /** + * Gamepad connect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#connect + * @param {object} rawPad - The raw gamepad object + */ + connect: function (rawPad) { + + var triggerCallback = !this.connected; + + this.connected = true; + this.index = rawPad.index; + + this._rawPad = rawPad; + + this._buttons = []; + this._buttonsLen = rawPad.buttons.length; + + this._axes = []; + this._axesLen = rawPad.axes.length; + + for (var a = 0; a < this._axesLen; a++) + { + this._axes[a] = rawPad.axes[a]; + } + + for (var buttonCode in rawPad.buttons) + { + buttonCode = parseInt(buttonCode, 10); + this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode); + } + + if (triggerCallback && this._padParent.onConnectCallback) + { + this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index); + } + + if (triggerCallback && this.onConnectCallback) + { + this.onConnectCallback.call(this.callbackContext); + } + + }, + + /** + * Gamepad disconnect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#disconnect + */ + disconnect: function () { + + var triggerCallback = this.connected; + var disconnectingIndex = this.index; + + this.connected = false; + this.index = null; + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + if (triggerCallback && this._padParent.onDisconnectCallback) + { + this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex); + } + + if (triggerCallback && this.onDisconnectCallback) + { + this.onDisconnectCallback.call(this.callbackContext); + } + + }, + + /** + * Destroys this object and associated callback references. + * + * @method Phaser.SinglePad#destroy + */ + destroy: function () { + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + this.onConnectCallback = null; + this.onDisconnectCallback = null; + this.onDownCallback = null; + this.onUpCallback = null; + this.onAxisCallback = null; + this.onFloatCallback = null; + + }, + + /** + * Handles changes in axis. + * + * @method Phaser.SinglePad#processAxisChange + * @param {object} axisState - State of the relevant axis + */ + processAxisChange: function (index, value) { + + if (this._axes[index] === value) + { + return; + } + + this._axes[index] = value; + + if (this._padParent.onAxisCallback) + { + this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value); + } + + if (this.onAxisCallback) + { + this.onAxisCallback.call(this.callbackContext, this, index, value); + } + + }, + + /** + * Handles button down press. + * + * @method Phaser.SinglePad#processButtonDown + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonDown: function (buttonCode, value) { + + if (this._buttons[buttonCode]) + { + this._buttons[buttonCode].start(null, value); + } + + 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); + } + + }, + + /** + * Handles button release. + * + * @method Phaser.SinglePad#processButtonUp + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonUp: function (buttonCode, value) { + + 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._buttons[buttonCode]) + { + this._buttons[buttonCode].stop(null, value); + } + + }, + + /** + * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) + * + * @method Phaser.SinglePad#processButtonFloat + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. + */ + processButtonFloat: function (buttonCode, value) { + + 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].padFloat(value); + } + + }, + + /** + * Returns value of requested axis. + * + * @method Phaser.SinglePad#axis + * @param {number} axisCode - The index of the axis to check + * @return {number} Axis value if available otherwise false + */ + axis: function (axisCode) { + + if (this._axes[axisCode]) + { + return this._axes[axisCode]; + } + + return false; + + }, + + /** + * Returns true if the button is pressed down. + * + * @method Phaser.SinglePad#isDown + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is pressed down. + */ + isDown: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isDown; + } + + return false; + + }, + + /** + * Returns true if the button is not currently pressed. + * + * @method Phaser.SinglePad#isUp + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is not currently pressed down. + */ + isUp: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isUp; + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justReleased + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justReleased(duration); + } + + }, + + /** + * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justPressed(duration); + } + + }, + + /** + * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example + * analog trigger buttons on the XBOX 360 controller. + * + * @method Phaser.SinglePad#buttonValue + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. + */ + buttonValue: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].value; + } + + return null; + + }, + + /** + * Reset all buttons/axes of this gamepad. + * + * @method Phaser.SinglePad#reset + */ + reset: function () { + + for (var j = 0; j < this._axes.length; j++) + { + this._axes[j] = 0; + } + + } + +}; + +Phaser.SinglePad.prototype.constructor = Phaser.SinglePad; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. +* +* @class Phaser.Key +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}. +*/ +Phaser.Key = function (game, keycode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * The enabled state of the key - see `enabled`. + * @property {boolean} _enabled + * @private + */ + this._enabled = true; + + /** + * @property {object} event - Stores the most recent DOM event. + * @readonly + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * @default + */ + this.isUp = true; + + /** + * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. + * @default + */ + this.altKey = false; + + /** + * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. + * @default + */ + this.ctrlKey = false; + + /** + * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. + * @default + */ + this.shiftKey = false; + + /** + * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now. + */ + this.timeDown = 0; + + /** + * If the key is down this value holds the duration of that key press and is constantly updated. + * If the key is up it holds the duration of the previous down session. + * @property {number} duration - The number of milliseconds this key has been held down for. + * @default + */ + this.duration = 0; + + /** + * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now. + * @default + */ + this.timeUp = -2500; + + /** + * If the key is up this value holds the duration of that key release and is constantly updated. + * If the key is down it holds the duration of the previous up session. + * @property {number} duration - The number of milliseconds this key has been up for. + * @default + */ + this.durationUp = -2500; + + /** + * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. + * @default + */ + this.repeats = 0; + + /** + * @property {number} keyCode - The keycode of this key. + */ + this.keyCode = keycode; + + /** + * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). + */ + this.onDown = new Phaser.Signal(); + + /** + * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. + */ + this.onHoldCallback = null; + + /** + * @property {object} onHoldContext - The context under which the onHoldCallback will be called. + */ + this.onHoldContext = null; + + /** + * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). + */ + this.onUp = new Phaser.Signal(); + + /** + * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justDown = false; + + /** + * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justUp = false; + +}; + +Phaser.Key.prototype = { + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#update + * @protected + */ + update: function () { + + if (!this._enabled) { return; } + + if (this.isDown) + { + this.duration = this.game.time.time - this.timeDown; + this.repeats++; + + if (this.onHoldCallback) + { + this.onHoldCallback.call(this.onHoldContext, this); + } + } + else + { + this.durationUp = this.game.time.time - this.timeUp; + } + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyDown + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyDown: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + // exit if this key down is from auto-repeat + if (this.isDown) + { + return; + } + + this.altKey = event.altKey; + this.ctrlKey = event.ctrlKey; + this.shiftKey = event.shiftKey; + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.duration = 0; + this.durationUp = this.game.time.time - this.timeUp; + this.repeats = 0; + + // _justDown will remain true until it is read via the justDown Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justDown = true; + + this.onDown.dispatch(this); + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyUp + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyUp: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = this.game.time.time - this.timeDown; + this.durationUp = 0; + + // _justUp will remain true until it is read via the justUp Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justUp = true; + + this.onUp.dispatch(this); + + }, + + /** + * Resets the state of this Key. + * + * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key. + * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. + * + * @method Phaser.Key#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = 0; + this.durationUp = -2500; + this._enabled = true; // .enabled causes reset(false) + this._justDown = false; + this._justUp = false; + + if (hard) + { + this.onDown.removeAll(); + this.onUp.removeAll(); + this.onHoldCallback = null; + this.onHoldContext = null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#downDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration. + */ + downDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (this.isDown && this.duration < duration); + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#upDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration. + */ + upDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (!this.isDown && ((this.game.time.time - this.timeUp) < duration)); + + }, + + /** + * Returns `true` if the Key was just pressed down this update tick, or `false` if it either isn't down, + * or was pressed down on a previous update tick. + * + * @method Phaser.Key#justPressed + * @return {boolean} True if the key was just pressed down this update tick. + */ + justPressed: function () { + + return (this.isDown && this.duration === 0); + + }, + + /** + * Returns `true` if the Key was just released this update tick, or `false` if it either isn't up, + * or was released on a previous update tick. + * + * @method Phaser.Key#justReleased + * @return {boolean} True if the key was just released this update tick. + */ + justReleased: function () { + + return (!this.isDown && this.durationUp === 0); + + } + +}; + +/** +* The justDown value allows you to test if this Key has just been pressed down or not. +* When you check this value it will return `true` if the Key is down, otherwise `false`. +* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. +* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justDown +* @property {boolean} justDown +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justDown", { + + get: function () { + + var current = this._justDown; + this._justDown = false; + return current; + + } + +}); + +/** +* The justUp value allows you to test if this Key has just been released or not. +* When you check this value it will return `true` if the Key is up, otherwise `false`. +* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again. +* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justUp +* @property {boolean} justUp +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justUp", { + + get: function () { + + var current = this._justUp; + this._justUp = false; + return current; + + } + +}); + +/** +* An enabled key processes its update and dispatches events. +* A key can be disabled momentarily at runtime instead of deleting it. +* @name Phaser.Key#enabled +* @property {boolean} enabled +* @memberof Phaser.Key +* @default true +*/ +Object.defineProperty(Phaser.Key.prototype, "enabled", { + + get: function () { + + return this._enabled; + + }, + + set: function (value) { + + value = !!value; + + if (value !== this._enabled) + { + if (!value) + { + this.reset(false); + } + + this._enabled = value; + } + } + +}); + +Phaser.Key.prototype.constructor = Phaser.Key; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Keyboard class monitors keyboard input and dispatches keyboard events. +* +* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. +* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. +* +* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. +* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. +* So please check your extensions before opening Phaser issues. +* +* @class Phaser.Keyboard +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Keyboard = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Keyboard input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. + */ + this.event = null; + + /** + * @property {object} pressEvent - The most recent DOM event from keypress. + */ + this.pressEvent = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. + */ + this.onDownCallback = null; + + /** + * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. + */ + this.onPressCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a key is released. + */ + this.onUpCallback = null; + + /** + * @property {array} _keys - The array the Phaser.Key objects are stored in. + * @private + */ + this._keys = []; + + /** + * @property {array} _capture - The array the key capture values are stored in. + * @private + */ + this._capture = []; + + /** + * @property {function} _onKeyDown + * @private + * @default + */ + this._onKeyDown = null; + + /** + * @property {function} _onKeyPress + * @private + * @default + */ + this._onKeyPress = null; + + /** + * @property {function} _onKeyUp + * @private + * @default + */ + this._onKeyUp = null; + + /** + * @property {number} _i - Internal cache var + * @private + */ + this._i = 0; + + /** + * @property {number} _k - Internal cache var + * @private + */ + this._k = 0; + +}; + +Phaser.Keyboard.prototype = { + + /** + * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. + * + * @method Phaser.Keyboard#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down. + * @param {function} [onUp=null] - This callback is invoked every time a key is released. + * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised. + */ + addCallbacks: function (context, onDown, onUp, onPress) { + + this.callbackContext = context; + + if (onDown !== undefined && onDown !== null) + { + this.onDownCallback = onDown; + } + + if (onUp !== undefined && onUp !== null) + { + this.onUpCallback = onUp; + } + + if (onPress !== undefined && onPress !== null) + { + this.onPressCallback = onPress; + } + + }, + + /** + * Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}. + * + * @method Phaser.Keyboard#removeCallbacks + */ + removeCallbacks: function () { + + this.callbackContext = this; + this.onDownCallback = null; + this.onUpCallback = null; + this.onPressCallback = null; + + }, + + /** + * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. + * The Key object can then be polled, have events attached to it, etc. + * + * @method Phaser.Keyboard#addKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key. + * @return {Phaser.Key} The Key object which you can store locally and reference directly. + */ + addKey: function (keycode) { + + if (!this._keys[keycode]) + { + this._keys[keycode] = new Phaser.Key(this.game, keycode); + + this.addKeyCapture(keycode); + } + + return this._keys[keycode]; + + }, + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example, + * + * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); + * + * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object. + * + * @method Phaser.Keyboard#addKeys + * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. + * @return {object} An object containing the properties mapped to {@link Phaser.Key} values. + */ + addKeys: function (keys) { + + var output = {}; + + for (var key in keys) + { + output[key] = this.addKey(keys[key]); + } + + return output; + + }, + + /** + * Removes a Key object from the Keyboard manager. + * + * @method Phaser.Keyboard#removeKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove. + */ + removeKey: function (keycode) { + + if (this._keys[keycode]) + { + this._keys[keycode] = null; + + this.removeKeyCapture(keycode); + } + + }, + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. + * + * @method Phaser.Keyboard#createCursorKeys + * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects. + */ + createCursorKeys: function () { + + return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT }); + + }, + + /** + * Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window. + * This is called automatically by Phaser.Input and should not normally be invoked directly. + * + * @method Phaser.Keyboard#start + * @protected + */ + start: function () { + + if (this.game.device.cocoonJS) + { + return; + } + + if (this._onKeyDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onKeyDown = function (event) { + return _this.processKeyDown(event); + }; + + this._onKeyUp = function (event) { + return _this.processKeyUp(event); + }; + + this._onKeyPress = function (event) { + return _this.processKeyPress(event); + }; + + window.addEventListener('keydown', this._onKeyDown, false); + window.addEventListener('keyup', this._onKeyUp, false); + window.addEventListener('keypress', this._onKeyPress, false); + + }, + + /** + * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. + * + * @method Phaser.Keyboard#stop + */ + stop: function () { + + window.removeEventListener('keydown', this._onKeyDown); + window.removeEventListener('keyup', this._onKeyUp); + window.removeEventListener('keypress', this._onKeyPress); + + this._onKeyDown = null; + this._onKeyUp = null; + this._onKeyPress = null; + + }, + + /** + * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. + * Also clears all key captures and currently created Key objects. + * + * @method Phaser.Keyboard#destroy + */ + destroy: function () { + + this.stop(); + + this.clearCaptures(); + + this._keys.length = 0; + this._i = 0; + + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Pass in either a single keycode or an array/hash of keycodes. + * + * @method Phaser.Keyboard#addKeyCapture + * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`. + */ + addKeyCapture: function (keycode) { + + if (typeof keycode === 'object') + { + for (var key in keycode) + { + this._capture[keycode[key]] = true; + } + } + else + { + this._capture[keycode] = true; + } + }, + + /** + * Removes an existing key capture. + * + * @method Phaser.Keyboard#removeKeyCapture + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of. + */ + removeKeyCapture: function (keycode) { + + delete this._capture[keycode]; + + }, + + /** + * Clear all set key captures. + * + * @method Phaser.Keyboard#clearCaptures + */ + clearCaptures: function () { + + this._capture = {}; + + }, + + /** + * Updates all currently defined keys. + * + * @method Phaser.Keyboard#update + */ + update: function () { + + this._i = this._keys.length; + + while (this._i--) + { + if (this._keys[this._i]) + { + this._keys[this._i].update(); + } + } + + }, + + /** + * Process the keydown event. + * + * @method Phaser.Keyboard#processKeyDown + * @param {KeyboardEvent} event + * @protected + */ + processKeyDown: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + // The event is being captured but another hotkey may need it + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyDown(event); + + this._k = key; + + if (this.onDownCallback) + { + this.onDownCallback.call(this.callbackContext, event); + } + + }, + + /** + * Process the keypress event. + * + * @method Phaser.Keyboard#processKeyPress + * @param {KeyboardEvent} event + * @protected + */ + processKeyPress: function (event) { + + this.pressEvent = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.onPressCallback) + { + this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event); + } + + }, + + /** + * Process the keyup event. + * + * @method Phaser.Keyboard#processKeyUp + * @param {KeyboardEvent} event + * @protected + */ + processKeyUp: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyUp(event); + + if (this.onUpCallback) + { + this.onUpCallback.call(this.callbackContext, event); + } + + }, + + /** + * Resets all Keys. + * + * @method Phaser.Keyboard#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.event = null; + + var i = this._keys.length; + + while (i--) + { + if (this._keys[i]) + { + this._keys[i].reset(hard); + } + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#downDuration + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. + */ + downDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].downDuration(duration); + } + else + { + return null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#upDuration + * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found. + */ + upDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].upDuration(duration); + } + else + { + return null; + } + + }, + + justPressed: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justPressed(); + } + else + { + return null; + } + + }, + + justReleased: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justReleased(); + } + else + { + return null; + } + + }, + + /** + * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. + * + * @method Phaser.Keyboard#isDown + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found. + */ + isDown: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].isDown; + } + else + { + return null; + } + + } + +}; + +/** +* Returns the string value of the most recently pressed key. +* @name Phaser.Keyboard#lastChar +* @property {string} lastChar - The string value of the most recently pressed key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", { + + get: function () { + + if (this.event && this.event.charCode === 32) + { + return ''; + } + else if (this.pressEvent) + { + return String.fromCharCode(this.pressEvent.charCode); + } + else + { + return null; + } + + } + +}); + +/** +* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. +* @name Phaser.Keyboard#lastKey +* @property {Phaser.Key} lastKey - The most recently pressed Key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", { + + get: function () { + + return this._keys[this._k]; + + } + +}); + +Phaser.Keyboard.prototype.constructor = Phaser.Keyboard; + +/** +* A key code represents a physical key on a keyboard. +* +* The KeyCode class contains commonly supported keyboard key codes which can be used +* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods. +* +* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. +* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. +* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property. +* +* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; +* the latter approach is supported for compatibility. +* +* @class Phaser.KeyCode +*/ +Phaser.KeyCode = { + /** @static */ + A: "A".charCodeAt(0), + /** @static */ + B: "B".charCodeAt(0), + /** @static */ + C: "C".charCodeAt(0), + /** @static */ + D: "D".charCodeAt(0), + /** @static */ + E: "E".charCodeAt(0), + /** @static */ + F: "F".charCodeAt(0), + /** @static */ + G: "G".charCodeAt(0), + /** @static */ + H: "H".charCodeAt(0), + /** @static */ + I: "I".charCodeAt(0), + /** @static */ + J: "J".charCodeAt(0), + /** @static */ + K: "K".charCodeAt(0), + /** @static */ + L: "L".charCodeAt(0), + /** @static */ + M: "M".charCodeAt(0), + /** @static */ + N: "N".charCodeAt(0), + /** @static */ + O: "O".charCodeAt(0), + /** @static */ + P: "P".charCodeAt(0), + /** @static */ + Q: "Q".charCodeAt(0), + /** @static */ + R: "R".charCodeAt(0), + /** @static */ + S: "S".charCodeAt(0), + /** @static */ + T: "T".charCodeAt(0), + /** @static */ + U: "U".charCodeAt(0), + /** @static */ + V: "V".charCodeAt(0), + /** @static */ + W: "W".charCodeAt(0), + /** @static */ + X: "X".charCodeAt(0), + /** @static */ + Y: "Y".charCodeAt(0), + /** @static */ + Z: "Z".charCodeAt(0), + /** @static */ + ZERO: "0".charCodeAt(0), + /** @static */ + ONE: "1".charCodeAt(0), + /** @static */ + TWO: "2".charCodeAt(0), + /** @static */ + THREE: "3".charCodeAt(0), + /** @static */ + FOUR: "4".charCodeAt(0), + /** @static */ + FIVE: "5".charCodeAt(0), + /** @static */ + SIX: "6".charCodeAt(0), + /** @static */ + SEVEN: "7".charCodeAt(0), + /** @static */ + EIGHT: "8".charCodeAt(0), + /** @static */ + NINE: "9".charCodeAt(0), + /** @static */ + NUMPAD_0: 96, + /** @static */ + NUMPAD_1: 97, + /** @static */ + NUMPAD_2: 98, + /** @static */ + NUMPAD_3: 99, + /** @static */ + NUMPAD_4: 100, + /** @static */ + NUMPAD_5: 101, + /** @static */ + NUMPAD_6: 102, + /** @static */ + NUMPAD_7: 103, + /** @static */ + NUMPAD_8: 104, + /** @static */ + NUMPAD_9: 105, + /** @static */ + NUMPAD_MULTIPLY: 106, + /** @static */ + NUMPAD_ADD: 107, + /** @static */ + NUMPAD_ENTER: 108, + /** @static */ + NUMPAD_SUBTRACT: 109, + /** @static */ + NUMPAD_DECIMAL: 110, + /** @static */ + NUMPAD_DIVIDE: 111, + /** @static */ + F1: 112, + /** @static */ + F2: 113, + /** @static */ + F3: 114, + /** @static */ + F4: 115, + /** @static */ + F5: 116, + /** @static */ + F6: 117, + /** @static */ + F7: 118, + /** @static */ + F8: 119, + /** @static */ + F9: 120, + /** @static */ + F10: 121, + /** @static */ + F11: 122, + /** @static */ + F12: 123, + /** @static */ + F13: 124, + /** @static */ + F14: 125, + /** @static */ + F15: 126, + /** @static */ + COLON: 186, + /** @static */ + EQUALS: 187, + /** @static */ + COMMA: 188, + /** @static */ + UNDERSCORE: 189, + /** @static */ + PERIOD: 190, + /** @static */ + QUESTION_MARK: 191, + /** @static */ + TILDE: 192, + /** @static */ + OPEN_BRACKET: 219, + /** @static */ + BACKWARD_SLASH: 220, + /** @static */ + CLOSED_BRACKET: 221, + /** @static */ + QUOTES: 222, + /** @static */ + BACKSPACE: 8, + /** @static */ + TAB: 9, + /** @static */ + CLEAR: 12, + /** @static */ + ENTER: 13, + /** @static */ + SHIFT: 16, + /** @static */ + CONTROL: 17, + /** @static */ + ALT: 18, + /** @static */ + CAPS_LOCK: 20, + /** @static */ + ESC: 27, + /** @static */ + SPACEBAR: 32, + /** @static */ + PAGE_UP: 33, + /** @static */ + PAGE_DOWN: 34, + /** @static */ + END: 35, + /** @static */ + HOME: 36, + /** @static */ + LEFT: 37, + /** @static */ + UP: 38, + /** @static */ + RIGHT: 39, + /** @static */ + DOWN: 40, + /** @static */ + PLUS: 43, + /** @static */ + MINUS: 44, + /** @static */ + INSERT: 45, + /** @static */ + DELETE: 46, + /** @static */ + HELP: 47, + /** @static */ + NUM_LOCK: 144 +}; + +// Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility +for (var key in Phaser.KeyCode) +{ + if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/)) + { + Phaser.Keyboard[key] = Phaser.KeyCode[key]; + } +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +Phaser.Component = function () {}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. +* +* @class +*/ +Phaser.Component.Angle = function () {}; + +Phaser.Component.Angle.prototype = { + + /** + * The angle property is the rotation of the Game Object in *degrees* from its original orientation. + * + * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. + * + * Values outside this range are added to or subtracted from 360 to obtain a value within the range. + * For example, the statement player.angle = 450 is the same as player.angle = 90. + * + * If you wish to work in radians instead of degrees you can use the property `rotation` instead. + * Working in radians is slightly faster as it doesn't have to perform any calculations. + * + * @property {number} angle + */ + angle: { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); + + }, + + set: function(value) { + + this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. +* +* @class +*/ +Phaser.Component.Animation = function () {}; + +Phaser.Component.Animation.prototype = { + + /** + * Plays an Animation. + * + * The animation should have previously been created via `animations.add`. + * + * If the animation is already playing calling this again won't do anything. + * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. + * + * @method + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation. + */ + play: function (name, frameRate, loop, killOnComplete) { + + if (this.animations) + { + return this.animations.play(name, frameRate, loop, killOnComplete); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. +* It is used by the InWorld component. +* +* @class +*/ +Phaser.Component.AutoCull = function () {}; + +Phaser.Component.AutoCull.prototype = { + + /** + * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. + * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. + * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} autoCull + * @default + */ + autoCull: false, + + /** + * Checks if the Game Objects bounds intersect with the Game Camera bounds. + * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + if (!this.autoCull && !this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + } + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Bounds component contains properties related to the bounds of the Game Object. +* +* @class +*/ +Phaser.Component.Bounds = function () {}; + +Phaser.Component.Bounds.prototype = { + + /** + * The amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * anchor.x`. + * It will only be > 0 if anchor.x is not equal to zero. + * + * @property {number} offsetX + * @readOnly + */ + offsetX: { + + get: function () { + + return this.anchor.x * this.width; + + } + + }, + + /** + * The amount the Game Object is visually offset from its y coordinate. + * This is the same as `height * anchor.y`. + * It will only be > 0 if anchor.y is not equal to zero. + * + * @property {number} offsetY + * @readOnly + */ + offsetY: { + + get: function () { + + return this.anchor.y * this.height; + + } + + }, + + /** + * The local center x coordinate of the Game Object. + * This is the same as `(x - offsetX) + (width / 2)`. + * + * @property {number} centerX + */ + centerX: { + + get: function () { + + return (this.x - this.offsetX) + (this.width * 0.5); + + }, + + set: function (value) { + + this.x = (value + this.offsetX) - (this.width * 0.5); + + } + + }, + + /** + * The local center y coordinate of the Game Object. + * This is the same as `(y - offsetY) + (height / 2)`. + * + * @property {number} centerY + */ + centerY: { + + get: function () { + + return (this.y - this.offsetY) + (this.height * 0.5); + + }, + + set: function (value) { + + this.y = (value + this.offsetY) - (this.height * 0.5); + + } + + }, + + /** + * The left coordinate of the Game Object. + * This is the same as `x - offsetX`. + * + * @property {number} left + */ + left: { + + get: function () { + + return this.x - this.offsetX; + + }, + + set: function (value) { + + this.x = value + this.offsetX; + + } + + }, + + /** + * The right coordinate of the Game Object. + * This is the same as `x + width - offsetX`. + * + * @property {number} right + */ + right: { + + get: function () { + + return (this.x + this.width) - this.offsetX; + + }, + + set: function (value) { + + this.x = value - (this.width) + this.offsetX; + + } + + }, + + /** + * The y coordinate of the Game Object. + * This is the same as `y - offsetY`. + * + * @property {number} top + */ + top: { + + get: function () { + + return this.y - this.offsetY; + + }, + + set: function (value) { + + this.y = value + this.offsetY; + + } + + }, + + /** + * The sum of the y and height properties. + * This is the same as `y + height - offsetY`. + * + * @property {number} bottom + */ + bottom: { + + get: function () { + + return (this.y + this.height) - this.offsetY; + + }, + + set: function (value) { + + this.y = value - (this.height) + this.offsetY; + + } + + }, + + /** + * Aligns this Game Object within another Game Object, or Rectangle, known as the + * 'container', to one of 9 possible positions. + * + * The container must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the container. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, + * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * container, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignIn: function (container, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = container.left - offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = container.centerX + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = container.right + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.left = container.left - offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.CENTER: + this.centerX = container.centerX + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.right = container.right + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = container.left - offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = container.centerX + offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = container.right + offsetX; + this.bottom = container.bottom + offsetY; + break; + } + + return this; + + }, + + /** + * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the + * 'parent', in one of 11 possible positions. + * + * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the parent. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, + * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, + * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * parent, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignTo: function (parent, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = parent.left - offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = parent.centerX + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = parent.right + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.LEFT_TOP: + this.right = parent.left - offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.right = parent.left - offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.LEFT_BOTTOM: + this.right = parent.left - offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.RIGHT_TOP: + this.left = parent.right + offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.left = parent.right + offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.RIGHT_BOTTOM: + this.left = parent.right + offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = parent.left - offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = parent.centerX + offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = parent.right + offsetX; + this.top = parent.bottom + offsetY; + break; + } + + return this; + + } + +}; + +// Phaser.Group extensions + +Phaser.Group.prototype.alignIn = Phaser.Component.Bounds.prototype.alignIn; +Phaser.Group.prototype.alignTo = Phaser.Component.Bounds.prototype.alignTo; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The BringToTop Component features quick access to Group sorting related methods. +* +* @class +*/ +Phaser.Component.BringToTop = function () {}; + +/** +* Brings this Game Object to the top of its parents display list. +* Visually this means it will render over the top of any old child in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.bringToTop = function() { + + if (this.parent) + { + this.parent.bringToTop(this); + } + + return this; + +}; + +/** +* Sends this Game Object to the bottom of its parents display list. +* Visually this means it will render below all other children in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.sendToBack = function() { + + if (this.parent) + { + this.parent.sendToBack(this); + } + + return this; + +}; + +/** +* Moves this Game Object up one place in its parents display list. +* This call has no effect if the Game Object is already at the top of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveUp = function () { + + if (this.parent) + { + this.parent.moveUp(this); + } + + return this; + +}; + +/** +* Moves this Game Object down one place in its parents display list. +* This call has no effect if the Game Object is already at the bottom of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveDown = function () { + + if (this.parent) + { + this.parent.moveDown(this); + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Core Component Features. +* +* @class +*/ +Phaser.Component.Core = function () {}; + +/** + * @property {boolean} skipTypeChecks - Skip type checks in {@link #init}. + * @static + * @default + */ +Phaser.Component.Core.skipTypeChecks = false; + +/** +* Installs / registers mixin components. +* +* The `this` context should be that of the applicable object instance or prototype. +* +* @method +* @protected +*/ +Phaser.Component.Core.install = function (components) { + + // Always install 'Core' first + Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype); + + this.components = {}; + + for (var i = 0; i < components.length; i++) + { + var id = components[i]; + var replace = false; + + if (id === 'Destroy') + { + replace = true; + } + + Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace); + + this.components[id] = true; + } + +}; + +/** +* Initializes the mixin components. +* +* The `this` context should be an instance of the component mixin target. +* +* @method +* @protected +*/ +Phaser.Component.Core.init = function (game, x, y, key, frame) { + + if (!Phaser.Component.Core.skipTypeChecks) + { + if (!(game instanceof Phaser.Game)) + { + throw new Error('The value passed as the `game` argument (' + game + ') is not an instance of Phaser.Game.'); + } + + if (typeof x !== 'number') + { + console.warn('The `x` argument value (%s) should be a number.', x); + x = 0; // This would be done implicitly in position.set(). + } + + if (typeof y !== 'number') + { + console.warn('The `y` argument value (%s) should be a number.', y); + y = 0; // This would be done implicitly in position.set(). + } + } + + this.game = game; + this.key = key; + this.data = {}; + + this.position.set(x, y); + this.world = new Phaser.Point(x, y); + this.previousPosition = new Phaser.Point(x, y); + + this.events = new Phaser.Events(this); + + this._bounds = new Phaser.Rectangle(); + + if (this.components.PhysicsBody) + { + // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype. + this.body = this.body; + } + + if (this.components.Animation) + { + this.animations = new Phaser.AnimationManager(this); + } + + if (this.components.LoadTexture && key !== null) + { + this.loadTexture(key, frame); + } + + if (this.components.FixedToCamera) + { + this.cameraOffset = new Phaser.Point(x, y); + } + +}; + +Phaser.Component.Core.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty); + + if (this.visible) + { + this.renderOrderID = this.game.stage.currentRenderOrderID++; + } + + if (this.animations) + { + this.animations.update(); + } + + if (this.body) + { + this.body.preUpdate(); + } + + this.preUpdateChildren(); + + return true; + +}; + +Phaser.Component.Core.prototype = { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + game: null, + + /** + * A user defined name given to this Game Object. + * This value isn't ever used internally by Phaser, it is meant as a game level property. + * @property {string} name + * @default + */ + name: '', + + /** + * An empty Object that belongs to this Game Object. + * This value isn't ever used internally by Phaser, but may be used by your own code, or + * by Phaser Plugins, to store data that needs to be associated with the Game Object, + * without polluting the Game Object directly. + * @property {Object} data + * @default + */ + data: {}, + + /** + * The components this Game Object has installed. + * @property {object} components + * @protected + */ + components: {}, + + /** + * The z depth of this Game Object within its parent Group. + * No two objects in a Group can have the same z value. + * This value is adjusted automatically whenever the Group hierarchy changes. + * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. + * @property {number} z + * @readOnly + */ + z: 0, + + /** + * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this + * Game Object, or any of its components. + * @see Phaser.Events + * @property {Phaser.Events} events + */ + events: undefined, + + /** + * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. + * Through it you can create, play, pause and stop animations. + * @see Phaser.AnimationManager + * @property {Phaser.AnimationManager} animations + */ + animations: undefined, + + /** + * The key of the image or texture used by this Game Object during rendering. + * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. + * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. + * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. + * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key + */ + key: '', + + /** + * The world coordinates of this Game Object in pixels. + * Depending on where in the display list this Game Object is placed this value can differ from `position`, + * which contains the x/y coordinates relative to the Game Objects parent. + * @property {Phaser.Point} world + */ + world: null, + + /** + * A debug flag designed for use with `Game.enableStep`. + * @property {boolean} debug + * @default + */ + debug: false, + + /** + * The position the Game Object was located in the previous frame. + * @property {Phaser.Point} previousPosition + * @readOnly + */ + previousPosition: null, + + /** + * The rotation the Game Object was in set to in the previous frame. Value is in radians. + * @property {number} previousRotation + * @readOnly + */ + previousRotation: 0, + + /** + * The render order ID is used internally by the renderer and Input Manager and should not be modified. + * This property is mostly used internally by the renderers, but is exposed for the use of plugins. + * @property {number} renderOrderID + * @readOnly + */ + renderOrderID: 0, + + /** + * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. + * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. + * @property {boolean} fresh + * @readOnly + */ + fresh: true, + + /** + * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. + * You can set it directly to allow you to flag an object to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy an object from within one of its own callbacks + * such as with Buttons or other Input events. + * + * @property {boolean} pendingDestroy + */ + pendingDestroy: false, + + /** + * @property {Phaser.Rectangle} _bounds - Internal cache var. + * @private + */ + _bounds: null, + + /** + * @property {boolean} _exists - Internal cache var. + * @private + */ + _exists: true, + + /** + * Controls if this Game Object is processed by the core game loop. + * If this Game Object has a physics body it also controls if its physics body is updated or not. + * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. + * It also toggles the `visible` property to false as well. + * + * Setting `exists` to true will add its physics body back in to the physics world, if it has one. + * It will also set the `visible` property to `true`. + * + * @property {boolean} exists + */ + exists: { + + get: function () { + + return this._exists; + + }, + + set: function (value) { + + if (value) + { + this._exists = true; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.addToWorld(); + } + + this.visible = true; + } + else + { + this._exists = false; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.removeFromWorld(); + } + + this.visible = false; + } + + } + + }, + + /** + * Internal method called by preUpdate. + * + * @method + * @protected + */ + preUpdateChildren: function() { + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + }, + + /** + * Override this method in your own custom objects to handle any update requirements. + * It is called immediately after `preUpdate` and before `postUpdate`. + * Remember if this Game Object has any children you should call update on those too. + * + * @method + */ + update: function() { + + }, + + /** + * Internal method called by the World postUpdate cycle. + * + * @method + * @protected + */ + postUpdate: function() { + + if (this.customRender) + { + this.key.render(); + } + + if (this.components.PhysicsBody) + { + Phaser.Component.PhysicsBody.postUpdate.call(this); + } + + if (this.components.FixedToCamera) + { + Phaser.Component.FixedToCamera.postUpdate.call(this); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, +* which can be updated in real-time. +* +* @class +*/ +Phaser.Component.Crop = function () {}; + +Phaser.Component.Crop.prototype = { + + /** + * The Rectangle used to crop the texture this Game Object uses. + * Set this property via `crop`. + * If you modify this property directly you must call `updateCrop` in order to have the change take effect. + * @property {Phaser.Rectangle} cropRect + * @default + */ + cropRect: null, + + /** + * @property {Phaser.Rectangle} _crop - Internal cache var. + * @private + */ + _crop: null, + + /** + * Crop allows you to crop the texture being used to display this Game Object. + * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. + * + * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, + * or by modifying `cropRect` property directly and then calling `updateCrop`. + * + * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object + * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. + * + * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, + * in which case the values are duplicated to a local object. + * + * @method + * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. + * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. + */ + crop: function (rect, copy) { + + if (copy === undefined) { copy = false; } + + if (rect) + { + if (copy && this.cropRect !== null) + { + this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height); + } + else if (copy && this.cropRect === null) + { + this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height); + } + else + { + this.cropRect = rect; + } + + this.updateCrop(); + } + else + { + this._crop = null; + this.cropRect = null; + + this.resetFrame(); + } + + }, + + /** + * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, + * or the rectangle it references, then you need to update the crop frame by calling this method. + * + * @method + */ + updateCrop: function () { + + if (!this.cropRect) + { + return; + } + + var oldX = this.texture.crop.x; + var oldY = this.texture.crop.y; + var oldW = this.texture.crop.width; + var oldH = this.texture.crop.height; + + this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop); + this._crop.x += this._frame.x; + this._crop.y += this._frame.y; + + var cx = Math.max(this._frame.x, this._crop.x); + var cy = Math.max(this._frame.y, this._crop.y); + var cw = Math.min(this._frame.right, this._crop.right) - cx; + var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy; + + this.texture.crop.x = cx; + this.texture.crop.y = cy; + this.texture.crop.width = cw; + this.texture.crop.height = ch; + + this.texture.frame.width = Math.min(cw, this.cropRect.width); + this.texture.frame.height = Math.min(ch, this.cropRect.height); + + this.texture.width = this.texture.frame.width; + this.texture.height = this.texture.frame.height; + + this.texture._updateUvs(); + + if (this.tint !== 0xffffff && (oldX !== cx || oldY !== cy || oldW !== cw || oldH !== ch)) + { + this.texture.requiresReTint = true; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Delta component provides access to delta values between the Game Objects current and previous position. +* +* @class +*/ +Phaser.Component.Delta = function () {}; + +Phaser.Component.Delta.prototype = { + + /** + * Returns the delta x value. The difference between world.x now and in the previous frame. + * + * The value will be positive if the Game Object has moved to the right or negative if to the left. + * + * @property {number} deltaX + * @readonly + */ + deltaX: { + + get: function() { + + return this.world.x - this.previousPosition.x; + + } + + }, + + /** + * Returns the delta y value. The difference between world.y now and in the previous frame. + * + * The value will be positive if the Game Object has moved down or negative if up. + * + * @property {number} deltaY + * @readonly + */ + deltaY: { + + get: function() { + + return this.world.y - this.previousPosition.y; + + } + + }, + + /** + * Returns the delta z value. The difference between rotation now and in the previous frame. + * + * @property {number} deltaZ - The delta value. + * @readonly + */ + deltaZ: { + + get: function() { + + return this.rotation - this.previousRotation; + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Destroy component is responsible for destroying a Game Object. +* +* @class +*/ +Phaser.Component.Destroy = function () {}; + +Phaser.Component.Destroy.prototype = { + + /** + * As a Game Object runs through its destroy method this flag is set to true, + * and can be checked in any sub-systems or plugins it is being destroyed from. + * @property {boolean} destroyPhase + * @readOnly + */ + destroyPhase: false, + + /** + * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present + * and nulls its reference to `game`, freeing it up for garbage collection. + * + * If this Game Object has the Events component it will also dispatch the `onDestroy` event. + * + * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've + * more than one Game Object sharing the same BaseTexture. + * + * @method + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? + * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. + */ + destroy: function (destroyChildren, destroyTexture) { + + if (this.game === null || this.destroyPhase) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (destroyTexture === undefined) { destroyTexture = false; } + + this.destroyPhase = true; + + if (this.events) + { + this.events.onDestroy$dispatch(this); + } + + if (this.parent) + { + if (this.parent instanceof Phaser.Group) + { + this.parent.remove(this); + } + else + { + this.parent.removeChild(this); + } + } + + if (this.input) + { + this.input.destroy(); + } + + if (this.animations) + { + this.animations.destroy(); + } + + if (this.body) + { + this.body.destroy(); + } + + if (this.events) + { + this.events.destroy(); + } + + this.game.tweens.removeFrom(this); + + var i = this.children.length; + + if (destroyChildren) + { + while (i--) + { + this.children[i].destroy(destroyChildren); + } + } + else + { + while (i--) + { + this.removeChild(this.children[i]); + } + } + + if (this._crop) + { + this._crop = null; + this.cropRect = null; + } + + if (this._frame) + { + this._frame = null; + } + + if (Phaser.Video && this.key instanceof Phaser.Video) + { + this.key.onChangeSource.remove(this.resizeFrame, this); + } + + if (Phaser.BitmapText && this._glyphs) + { + this._glyphs = []; + } + + this.alive = false; + this.exists = false; + this.visible = false; + + this.filters = null; + this.mask = null; + this.game = null; + + this.data = {}; + + // In case Pixi is still going to try and render it even though destroyed + this.renderable = false; + + if (this.transformCallback) + { + this.transformCallback = null; + this.transformCallbackContext = null; + } + + // Pixi level DisplayObject destroy + this.hitArea = null; + this.parent = null; + this.stage = null; + this.worldTransform = null; + this.filterArea = null; + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + // Texture? + if (destroyTexture) + { + this.texture.destroy(true); + } + + this.destroyPhase = false; + this.pendingDestroy = false; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Events component is a collection of events fired by the parent Game Object. +* +* Phaser uses what are known as 'Signals' for all event handling. All of the events in +* this class are signals you can subscribe to, much in the same way you'd "listen" for +* an event. +* +* For example to tell when a Sprite has been added to a new group, you can bind a function +* to the {@link #onAddedToGroup} signal: +* +* `sprite.events.onAddedToGroup.add(yourFunction, this);` +* +* Where `yourFunction` is the function you want called when this event occurs. +* +* For more details about how signals work please see the {@link Phaser.Signal} class. +* +* The Input-related events will only be dispatched if the Sprite has had {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true` +* and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. +* +* @class Phaser.Events +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. +*/ +Phaser.Events = function (sprite) { + + /** + * @property {Phaser.Sprite} parent - The Sprite that owns these events. + */ + this.parent = sprite; + + // The signals are automatically added by the corresponding proxy properties + +}; + +Phaser.Events.prototype = { + + /** + * Removes all events. + * + * @method Phaser.Events#destroy + */ + destroy: function () { + + this._parent = null; + + if (this._onDestroy) { this._onDestroy.dispose(); } + if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } + if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } + if (this._onKilled) { this._onKilled.dispose(); } + if (this._onRevived) { this._onRevived.dispose(); } + if (this._onEnterBounds) { this._onEnterBounds.dispose(); } + if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } + + if (this._onInputOver) { this._onInputOver.dispose(); } + if (this._onInputOut) { this._onInputOut.dispose(); } + if (this._onInputDown) { this._onInputDown.dispose(); } + if (this._onInputUp) { this._onInputUp.dispose(); } + if (this._onDragStart) { this._onDragStart.dispose(); } + if (this._onDragUpdate) { this._onDragUpdate.dispose(); } + if (this._onDragStop) { this._onDragStop.dispose(); } + + if (this._onAnimationStart) { this._onAnimationStart.dispose(); } + if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } + if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } + + }, + + // The following properties are sentinels that will be replaced with getters + + /** + * This signal is dispatched when this Game Object is added to a new {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was added to the Group. + * - {Phaser.Group} The Group it was added to. + * + * @property {Phaser.Signal} onAddedToGroup + */ + onAddedToGroup: null, + + /** + * This signal is dispatched when the Game Object is removed from a {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was removed from the Group. + * - {Phaser.Group} The Group it was removed from. + * + * @property {Phaser.Signal} onRemovedFromGroup + */ + onRemovedFromGroup: null, + + /** + * This signal is dispatched when the Game Object is destroyed. + * This happens when {@link Phaser.Sprite#destroy Sprite.destroy()} is called, or {@link Phaser.Group#destroy Group.destroy()} with `destroyChildren` set to true. + * It is sent one argument: + * + * - {any} The Game Object that was destroyed. + * + * @property {Phaser.Signal} onDestroy + */ + onDestroy: null, + + /** + * This signal is dispatched when the Game Object is killed. + * This happens when {@link Phaser.Sprite#kill Sprite.kill()} is called. + * Please understand the difference between {@link Phaser.Sprite#kill kill} and {@link Phaser.Sprite#destroy destroy} by looking at their respective methods. + * It is sent one argument: + * + * - {any} The Game Object that was killed. + * + * @property {Phaser.Signal} onKilled + */ + onKilled: null, + + /** + * This signal is dispatched when the Game Object is revived from a previously killed state. + * This happens when {@link Phaser.Sprite#revive Sprite.revive()} is called. + * It is sent one argument: + * + * - {any} The Game Object that was revived. + * + * @property {Phaser.Signal} onRevived + */ + onRevived: null, + + /** + * This signal is dispatched when the Game Object leaves the Phaser.World {@link Phaser.World#bounds bounds}. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that left the World bounds. + * + * @property {Phaser.Signal} onOutOfBounds + */ + onOutOfBounds: null, + + /** + * This signal is dispatched when the Game Object returns within the Phaser.World {@link Phaser.World#bounds bounds}, having previously been outside of them. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that entered the World bounds. + * + * @property {Phaser.Signal} onEnterBounds + */ + onEnterBounds: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an over event from a {@link Phaser.Pointer}. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOver + */ + onInputOver: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an out event from a {@link Phaser.Pointer}, which was previously over it. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOut + */ + onInputOut: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives a down event from a {@link Phaser.Pointer}. This effectively means the Pointer has been + * pressed down (but not yet released) on the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputDown + */ + onInputDown: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an up event from a {@link Phaser.Pointer}. This effectively means the Pointer had been + * pressed down, and was then released on the Game Object. + * It is sent three arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {boolean} isOver - Is the Pointer still over the Game Object? + * + * @property {Phaser.Signal} onInputUp + */ + onInputUp: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} starts to drag the Game Object, taking into consideration the various + * drag limitations that may be set. + * It is sent four arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The x coordinate that the drag started from. + * - {number} The y coordinate that the drag started from. + * + * @property {Phaser.Signal} onDragStart + */ + onDragStart: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} is actively dragging the Game Object. + * Be warned: This is a high volume Signal. Be careful what you bind to it. + * It is sent six arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The new x coordinate of the Game Object. + * - {number} The new y coordinate of the Game Object. + * - {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. + * - {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. + * + * @property {Phaser.Signal} onDragUpdate + */ + onDragUpdate: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} stops dragging the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onDragStop + */ + onDragStop: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been played. + * You can also listen to {@link Phaser.Animation#onStart} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was started. + * + * @property {Phaser.Signal} onAnimationStart + */ + onAnimationStart: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been stopped (via {@link Phaser.AnimationManager#stop animation.stop()} and the `dispatchComplete` argument has been set. + * You can also listen to {@link Phaser.Animation#onComplete} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was stopped. + * + * @property {Phaser.Signal} onAnimationComplete + */ + onAnimationComplete: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has looped playback. + * You can also listen to {@link Phaser.Animation#onLoop} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that looped. + * + * @property {Phaser.Signal} onAnimationLoop + */ + onAnimationLoop: null + +}; + +Phaser.Events.prototype.constructor = Phaser.Events; + +// Create an auto-create proxy getter and dispatch method for all events. +// The backing property is the same as the event name, prefixed with '_' +// and the dispatch method is the same as the event name postfixed with '$dispatch'. +for (var prop in Phaser.Events.prototype) +{ + if (!Phaser.Events.prototype.hasOwnProperty(prop) || + prop.indexOf('on') !== 0 || + Phaser.Events.prototype[prop] !== null) + { + continue; + } + + (function (prop, backing) { + 'use strict'; + + // The accessor creates a new Signal; and so it should only be used from user-code. + Object.defineProperty(Phaser.Events.prototype, prop, { + get: function () { + return this[backing] || (this[backing] = new Phaser.Signal()); + } + }); + + // The dispatcher will only broadcast on an already-created signal; call this internally. + Phaser.Events.prototype[prop + '$dispatch'] = function () { + return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; + }; + + })(prop, '_' + prop); + +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless +* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. +* +* @class +*/ +Phaser.Component.FixedToCamera = function () {}; + +/** + * The FixedToCamera component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.FixedToCamera.postUpdate = function () { + + if (this.fixedToCamera) + { + 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.Component.FixedToCamera.prototype = { + + /** + * @property {boolean} _fixedToCamera + * @private + */ + _fixedToCamera: false, + + /** + * A Game Object that is "fixed" to the camera is rendered at a given x/y offsets from the top left of the camera. The offsets + * are stored in the `cameraOffset` property, which is initialized with the current object coordinates. + * + * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. + * + * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world + * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times + * regardless where in the world the camera is. + * + * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. + * + * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. + * + * @property {boolean} fixedToCamera + */ + fixedToCamera: { + + get: function () { + + return this._fixedToCamera; + + }, + + set: function (value) { + + if (value) + { + this._fixedToCamera = true; + this.cameraOffset.set(this.x, this.y); + } + else + { + this._fixedToCamera = false; + } + + } + + }, + + /** + * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. + * + * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. + * @property {Phaser.Point} cameraOffset + */ + cameraOffset: new Phaser.Point() + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Health component provides the ability for Game Objects to have a `health` property +* that can be damaged and reset through game code. +* Requires the LifeSpan component. +* +* @class +*/ +Phaser.Component.Health = function () {}; + +Phaser.Component.Health.prototype = { + + /** + * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. + * + * It can be used in combination with the `damage` method or modified directly. + * + * @property {number} health + * @default + */ + health: 1, + + /** + * The Game Objects maximum health value. This works in combination with the `heal` method to ensure + * the health value never exceeds the maximum. + * + * @property {number} maxHealth + * @default + */ + maxHealth: 100, + + /** + * Damages the Game Object. This removes the given amount of health from the `health` property. + * + * If health is taken below or is equal to zero then the `kill` method is called. + * + * @method + * @param {number} amount - The amount to subtract from the current `health` value. + * @return {Phaser.Sprite} This instance. + */ + damage: function (amount) { + + if (this.alive) + { + this.health -= amount; + + if (this.health <= 0) + { + this.kill(); + } + } + + return this; + + }, + + /** + * Sets the health property of the Game Object to the given amount. + * Will never exceed the `maxHealth` value. + * + * @method + * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + setHealth: function (amount) { + + this.health = amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + + return this; + + }, + + /** + * Heal the Game Object. This adds the given amount of health to the `health` property. + * + * @method + * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + heal: function (amount) { + + if (this.alive) + { + this.health += amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InCamera component checks if the Game Object intersects with the Game Camera. +* +* @class +*/ +Phaser.Component.InCamera = function () {}; + +Phaser.Component.InCamera.prototype = { + + /** + * Checks if this Game Objects bounds intersects with the Game Cameras bounds. + * + * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. + * + * An object outside the bounds can be considered for camera culling if it has the AutoCull component. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. +* +* @class +*/ +Phaser.Component.InputEnabled = function () {}; + +Phaser.Component.InputEnabled.prototype = { + + /** + * The Input Handler for this Game Object. + * + * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. + * + * After you have done this, this property will be a reference to the Phaser InputHandler. + * @property {Phaser.InputHandler|null} input + */ + input: null, + + /** + * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created + * for this Game Object and it will then start to process click / touch events and more. + * + * You can then access the Input Handler via `this.input`. + * + * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. + * + * If you set this property to false it will stop the Input Handler from processing any more input events. + * + * If you want to _temporarily_ disable input for a Game Object, then it's better to set + * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. + * You can then toggle this back on as needed. + * + * @property {boolean} inputEnabled + */ + inputEnabled: { + + get: function () { + + return (this.input && this.input.enabled); + + }, + + set: function (value) { + + if (value) + { + if (this.input === null) + { + this.input = new Phaser.InputHandler(this); + this.input.start(); + } + else if (this.input && !this.input.enabled) + { + this.input.start(); + } + } + else + { + if (this.input && this.input.enabled) + { + this.input.stop(); + } + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InWorld component checks if a Game Object is within the Game World Bounds. +* An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. +* If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. +* +* @class +*/ +Phaser.Component.InWorld = function () {}; + +/** + * The InWorld component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.InWorld.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + // Cache the bounds if we need it + if (this.autoCull || this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + + if (this.autoCull) + { + // Won't get rendered but will still get its transform updated + if (this.game.world.camera.view.intersects(this._bounds)) + { + this.renderable = true; + this.game.world.camera.totalInView++; + } + else + { + this.renderable = false; + + if (this.outOfCameraBoundsKill) + { + this.kill(); + return false; + } + } + } + + if (this.checkWorldBounds) + { + // The Sprite is already out of the world bounds, so let's check to see if it has come back again + if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds)) + { + this._outOfBoundsFired = false; + this.events.onEnterBounds$dispatch(this); + } + else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds)) + { + // The Sprite WAS in the screen, but has now left. + this._outOfBoundsFired = true; + this.events.onOutOfBounds$dispatch(this); + + if (this.outOfBoundsKill) + { + this.kill(); + return false; + } + } + } + } + + return true; + +}; + +Phaser.Component.InWorld.prototype = { + + /** + * If this is set to `true` the Game Object checks if it is within the World bounds each frame. + * + * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. + * + * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. + * + * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. + * + * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} checkWorldBounds + * @default + */ + checkWorldBounds: false, + + /** + * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. + * + * @property {boolean} outOfBoundsKill + * @default + */ + outOfBoundsKill: false, + + /** + * If this and the `autoCull` property are both set to `true`, then the `kill` method + * is called as soon as the Game Object leaves the camera bounds. + * + * @property {boolean} outOfCameraBoundsKill + * @default + */ + outOfCameraBoundsKill: false, + + /** + * @property {boolean} _outOfBoundsFired - Internal state var. + * @private + */ + _outOfBoundsFired: false, + + /** + * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. + * + * @property {boolean} inWorld + * @readonly + */ + inWorld: { + + get: function () { + + return this.game.world.bounds.intersects(this.getBounds()); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* LifeSpan Component Features. +* +* @class +*/ +Phaser.Component.LifeSpan = function () {}; + +/** + * The LifeSpan component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.LifeSpan.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.lifespan > 0) + { + this.lifespan -= this.game.time.physicsElapsedMS; + + if (this.lifespan <= 0) + { + this.kill(); + return false; + } + } + + return true; + +}; + +Phaser.Component.LifeSpan.prototype = { + + /** + * A useful flag to control if the Game Object is alive or dead. + * + * This is set automatically by the Health components `damage` method should the object run out of health. + * Or you can toggle it via your game code. + * + * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. + * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. + * @property {boolean} alive + * @default + */ + alive: true, + + /** + * The lifespan allows you to give a Game Object a lifespan in milliseconds. + * + * Once the Game Object is 'born' you can set this to a positive value. + * + * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. + * When it reaches zero it will call the `kill` method. + * + * Very handy for particles, bullets, collectibles, or any other short-lived entity. + * + * @property {number} lifespan + * @default + */ + lifespan: 0, + + /** + * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. + * + * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. + * + * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. + * + * @method + * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. + * @return {PIXI.DisplayObject} This instance. + */ + revive: function (health) { + + if (health === undefined) { health = 100; } + + this.alive = true; + this.exists = true; + this.visible = true; + + if (typeof this.setHealth === 'function') + { + this.setHealth(health); + } + + if (this.events) + { + this.events.onRevived$dispatch(this); + } + + return this; + + }, + + /** + * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. + * + * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. + * + * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, + * it doesn't destroy the object or free it up from memory. + * + * If you don't need this Game Object any more you should call `destroy` instead. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ + kill: function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + if (this.events) + { + this.events.onKilled$dispatch(this); + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. +* +* @class +*/ +Phaser.Component.LoadTexture = function () {}; + +Phaser.Component.LoadTexture.prototype = { + + /** + * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) + * @private + */ + customRender: false, + + /** + * @property {Phaser.Rectangle} _frame - Internal cache var. + * @private + */ + _frame: null, + + /** + * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. + * + * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. + * + * You should only use `loadTexture` if you want to replace the base texture entirely. + * + * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. + * + * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. + * Doing this then sets the key to be the `frame` argument (the frame is set to zero). + * + * This allows you to create sprites using `load.image` during development, and then change them + * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' + * and swapping it to be the key of the atlas data. + * + * Note: You cannot use a RenderTexture as a texture for a TileSprite. + * + * @method + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. + */ + loadTexture: function (key, frame, stopAnimation) { + + if (key === Phaser.PENDING_ATLAS) + { + key = frame; + frame = 0; + } + else + { + frame = frame || 0; + } + + if ((stopAnimation || stopAnimation === undefined) && this.animations) + { + this.animations.stop(); + } + + this.key = key; + this.customRender = false; + var cache = this.game.cache; + + var setFrame = true; + var smoothed = !this.texture.baseTexture.scaleMode; + + if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture) + { + this.key = key.key; + this.setTexture(key); + } + else if (Phaser.BitmapData && key instanceof Phaser.BitmapData) + { + this.customRender = true; + + this.setTexture(key.texture); + + if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA)) + { + setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame); + } + else + { + setFrame = !this.animations.loadFrameData(key.frameData, 0); + } + } + else if (Phaser.Video && key instanceof Phaser.Video) + { + this.customRender = true; + + // This works from a reference, which probably isn't what we need here + var valid = key.texture.valid; + this.setTexture(key.texture); + this.setFrame(key.texture.frame.clone()); + key.onChangeSource.add(this.resizeFrame, this); + this.texture.valid = valid; + } + else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer) + { + // this.customRender = true; + + this.setTexture(PIXI.Texture.fromCanvas(key.canvas)); + } + else if (key instanceof PIXI.Texture) + { + this.setTexture(key); + } + else + { + var img = cache.getImage(key, true); + + this.key = img.key; + this.setTexture(new PIXI.Texture(img.base)); + + if (key === '__default') + { + this.texture.baseTexture.skipRender = true; + } + else + { + this.texture.baseTexture.skipRender = false; + } + + setFrame = !this.animations.loadFrameData(img.frameData, frame); + } + + if (setFrame) + { + this._frame = Phaser.Rectangle.clone(this.texture.frame); + } + + if (!smoothed) + { + this.texture.baseTexture.scaleMode = 1; + } + + }, + + /** + * Sets the texture frame the Game Object uses for rendering. + * + * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. + * + * @method + * @param {Phaser.Frame} frame - The Frame to be used by the texture. + */ + setFrame: function (frame) { + + this._frame = frame; + + this.texture.frame.x = frame.x; + this.texture.frame.y = frame.y; + this.texture.frame.width = frame.width; + this.texture.frame.height = frame.height; + + this.texture.crop.x = frame.x; + this.texture.crop.y = frame.y; + this.texture.crop.width = frame.width; + this.texture.crop.height = frame.height; + + if (frame.trimmed) + { + if (this.texture.trim) + { + this.texture.trim.x = frame.spriteSourceSizeX; + this.texture.trim.y = frame.spriteSourceSizeY; + this.texture.trim.width = frame.sourceSizeW; + this.texture.trim.height = frame.sourceSizeH; + } + else + { + this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH }; + } + + this.texture.width = frame.sourceSizeW; + this.texture.height = frame.sourceSizeH; + this.texture.frame.width = frame.sourceSizeW; + this.texture.frame.height = frame.sourceSizeH; + } + else if (!frame.trimmed && this.texture.trim) + { + this.texture.trim = null; + } + + if (frame.rotated) + { + this.texture.rotated = true; + } + + if (this.cropRect) + { + this.updateCrop(); + } + + this.texture.requiresReTint = true; + + this.texture._updateUvs(); + + if (this.tilingTexture) + { + this.refreshTexture = true; + } + + }, + + /** + * Resizes the Frame dimensions that the Game Object uses for rendering. + * + * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData + * it can be useful to adjust the dimensions directly in this way. + * + * @method + * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. + * @param {integer} width - The new width of the texture. + * @param {integer} height - The new height of the texture. + */ + resizeFrame: function (parent, width, height) { + + this.texture.frame.resize(width, height); + this.texture.setFrame(this.texture.frame); + + }, + + /** + * Resets the texture frame dimensions that the Game Object uses for rendering. + * + * @method + */ + resetFrame: function () { + + if (this._frame) + { + this.setFrame(this._frame); + } + + }, + + /** + * Gets or sets the current frame index of the texture being used to render this Game Object. + * + * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, + * for example: `player.frame = 4`. + * + * If the frame index given doesn't exist it will revert to the first frame found in the texture. + * + * If you are using a texture atlas then you should use the `frameName` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {integer} frame + */ + frame: { + + get: function () { + return this.animations.frame; + }, + + set: function (value) { + this.animations.frame = value; + } + + }, + + /** + * Gets or sets the current frame name of the texture being used to render this Game Object. + * + * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, + * for example: `player.frameName = "idle"`. + * + * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. + * + * If you are using a sprite sheet then you should use the `frame` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {string} frameName + */ + frameName: { + + get: function () { + return this.animations.frameName; + }, + + set: function (value) { + this.animations.frameName = value; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. +* +* @class +*/ +Phaser.Component.Overlap = function () {}; + +Phaser.Component.Overlap.prototype = { + + /** + * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, + * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. + * + * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. + * + * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. + * It should be fine for low-volume testing where physics isn't required. + * + * @method + * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. + * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. + */ + overlap: function (displayObject) { + + return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds()); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The PhysicsBody component manages the Game Objects physics body and physics enabling. +* It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. +* +* @class +*/ +Phaser.Component.PhysicsBody = function () {}; + +/** + * The PhysicsBody component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.fresh && 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.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (this.body) + { + this.body.preUpdate(); + } + + this.fresh = false; + + this.preUpdateChildren(); + + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this._exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + return true; + +}; + +/** + * The PhysicsBody component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.postUpdate = function () { + + if (this.exists && this.body) + { + this.body.postUpdate(); + } + +}; + +Phaser.Component.PhysicsBody.prototype = { + + /** + * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated + * properties and methods via it. + * + * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. + * + * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object + * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. + * + * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. + * + * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, + * so the physics body is centered on the Game Object. + * + * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. + * + * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body + * @default + */ + body: null, + + /** + * The position of the Game Object on the x axis relative to the local coordinates of the parent. + * + * @property {number} x + */ + x: { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + }, + + /** + * The position of the Game Object on the y axis relative to the local coordinates of the parent. + * + * @property {number} y + */ + y: { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Reset component allows a Game Object to be reset and repositioned to a new location. +* +* @class +*/ +Phaser.Component.Reset = function () {}; + +/** +* Resets the Game Object. +* +* This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, +* `visible` and `renderable` to true. +* +* If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. +* +* If this Game Object has a Physics Body it will reset the Body. +* +* @method +* @param {number} x - The x coordinate (in world space) to position the Game Object at. +* @param {number} y - The y coordinate (in world space) to position the Game Object at. +* @param {number} [health=1] - The health to give the Game Object if it has the Health component. +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.Reset.prototype.reset = function (x, y, health) { + + if (health === undefined) { health = 1; } + + this.world.set(x, y); + this.position.set(x, y); + + this.fresh = true; + this.exists = true; + this.visible = true; + this.renderable = true; + + if (this.components.InWorld) + { + this._outOfBoundsFired = false; + } + + if (this.components.LifeSpan) + { + this.alive = true; + this.health = health; + } + + if (this.components.PhysicsBody) + { + if (this.body) + { + this.body.reset(x, y, false, false); + } + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. +* +* @class +*/ +Phaser.Component.ScaleMinMax = function () {}; + +Phaser.Component.ScaleMinMax.prototype = { + + /** + * The callback that will apply any scale limiting to the worldTransform. + * @property {function} transformCallback + */ + transformCallback: null, + + /** + * The context under which `transformCallback` is called. + * @property {object} transformCallbackContext + */ + transformCallbackContext: this, + + /** + * The minimum scale this Game Object will scale down to. + * + * It allows you to prevent a parent from scaling this Game Object lower than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMin + */ + scaleMin: null, + + /** + * The maximum scale this Game Object will scale up to. + * + * It allows you to prevent a parent from scaling this Game Object higher than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMax + */ + scaleMax: null, + + /** + * Adjust scaling limits, if set, to this Game Object. + * + * @method + * @private + * @param {Phaser.Matrix} wt - The updated worldTransform matrix. + */ + checkTransform: function (wt) { + + if (this.scaleMin) + { + if (wt.a < this.scaleMin.x) + { + wt.a = this.scaleMin.x; + } + + if (wt.d < this.scaleMin.y) + { + wt.d = this.scaleMin.y; + } + } + + if (this.scaleMax) + { + if (wt.a > this.scaleMax.x) + { + wt.a = this.scaleMax.x; + } + + if (wt.d > this.scaleMax.y) + { + wt.d = this.scaleMax.y; + } + } + + }, + + /** + * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. + * + * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored + * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. + * + * By setting these values you can carefully control how Game Objects deal with responsive scaling. + * + * If only one parameter is given then that value will be used for both scaleMin and scaleMax: + * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 + * + * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: + * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 + * + * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, + * or pass `null` for the `maxX` and `maxY` parameters. + * + * Call `setScaleMinMax(null)` to clear all previously set values. + * + * @method + * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to. + * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to. + * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to. + * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to. + */ + setScaleMinMax: function (minX, minY, maxX, maxY) { + + if (minY === undefined) + { + // 1 parameter, set all to it + minY = maxX = maxY = minX; + } + else if (maxX === undefined) + { + // 2 parameters, the first is min, the second max + maxX = maxY = minY; + minY = minX; + } + + if (minX === null) + { + this.scaleMin = null; + } + else + { + if (this.scaleMin) + { + this.scaleMin.set(minX, minY); + } + else + { + this.scaleMin = new Phaser.Point(minX, minY); + } + } + + if (maxX === null) + { + this.scaleMax = null; + } + else + { + if (this.scaleMax) + { + this.scaleMax.set(maxX, maxY); + } + else + { + this.scaleMax = new Phaser.Point(maxX, maxY); + } + } + + if (this.scaleMin === null) + { + this.transformCallback = null; + } + else + { + this.transformCallback = this.checkTransform; + this.transformCallbackContext = this; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. +* +* @class +*/ +Phaser.Component.Smoothed = function () {}; + +Phaser.Component.Smoothed.prototype = { + + /** + * Enable or disable texture smoothing for this Game Object. + * + * It only takes effect if the Game Object is using an image based texture. + * + * Smoothing is enabled by default. + * + * @property {boolean} smoothed + */ + smoothed: { + + get: function () { + + return !this.texture.baseTexture.scaleMode; + + }, + + set: function (value) { + + if (value) + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 0; + this.texture.baseTexture.dirty(); + } + } + else + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 1; + this.texture.baseTexture.dirty(); + } + } + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectFactory is a quick way to create many common game objects +* using {@linkcode Phaser.Game#add `game.add`}. +* +* Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group. +* +* @class Phaser.GameObjectFactory +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectFactory = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectFactory.prototype = { + + /** + * Adds an existing display object to the game world. + * + * @method Phaser.GameObjectFactory#existing + * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object. + * @return {any} The child that was added to the World. + */ + existing: function (object) { + + return this.world.add(object); + + }, + + /** + * Weapons provide the ability to easily create a bullet pool and manager. + * + * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. + * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. + * + * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you + * can usually do with a Group, such as move it around the display list, iterate it, etc can be done + * to the bullets Group too. + * + * Bullets can have textures and even animations. You can control the speed at which they are fired, + * the firing rate, the firing angle, and even set things like gravity for them. + * + * @method Phaser.GameObjectFactory#weapon + * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group. + * @param {function} [bulletClass] - The Class of the bullets that are launched by this Weapon. See {@link Phaser.Weapon#bulletClass} + * @returns {Phaser.Weapon} A Weapon instance. + */ + weapon: function (quantity, key, frame, group, bulletClass) { + + var weapon = this.game.plugins.add(Phaser.Weapon); + + if (bulletClass) + { + weapon.bulletClass = bulletClass; + } + + weapon.createBullets(quantity, key, frame, group); + + return weapon; + + }, + + /** + * Create a new `Image` object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * + * It can still rotate, scale, crop and receive input events. + * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectFactory#image + * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Image} The newly created Image object. + */ + image: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Image(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. + * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), + * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. + * + * @method Phaser.GameObjectFactory#sprite + * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Sprite} The newly created Sprite object. + */ + sprite: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Sprite(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Creature Animation object. + * + * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. + * + * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). + * + * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. + * + * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them + * loaded before your Phaser game boots. + * + * See the Phaser custom build process for more details. + * + * @method Phaser.GameObjectFactory#creature + * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Creature} The newly created Creature object. + */ + creature: function (x, y, key, mesh, group) { + + if (group === undefined) { group = this.world; } + + var obj = new Phaser.Creature(this.game, x, y, key, mesh); + + group.add(obj); + + return obj; + + }, + + /** + * Create a tween on a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectFactory#tween + * @param {object} object - Object the tween will be run on. + * @return {Phaser.Tween} The newly created Phaser.Tween object. + */ + tween: function (object) { + + return this.game.tweens.create(object); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectFactory#group + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates + * are automatically given a physics body. + * + * @method Phaser.GameObjectFactory#physicsGroup + * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc. + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.Group} The newly created Group. + */ + physicsGroup: function (physicsBodyType, parent, name, addToStage) { + + return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType); + + }, + + /** + * A SpriteBatch is a really fast version of a Phaser Group built solely for speed. + * Use when you need a lot of sprites or particles all sharing the same texture. + * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. + * + * @method Phaser.GameObjectFactory#spriteBatch + * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. + * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. + * @return {Phaser.SpriteBatch} The newly created Sprite Batch. + */ + spriteBatch: function (parent, name, addToStage) { + + if (parent === undefined) { parent = null; } + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectFactory#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectFactory#tileSprite + * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TileSprite} The newly created TileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); + + }, + + /** + * Creates a new Rope object. + * + * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js + * + * @method Phaser.GameObjectFactory#rope + * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Array} points - An array of {Phaser.Point}. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Rope} The newly created Rope object. + */ + rope: function (x, y, key, frame, points, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Rope(this.game, x, y, key, frame, points)); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectFactory#text + * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {string} [text=''] - The text string that will be displayed. + * @param {object} [style] - The style object containing style attributes like font, font size , etc. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Text(this.game, x, y, text, style)); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectFactory#button + * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] - The function to call when this button is pressed + * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Button} The newly created Button object. + */ + button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectFactory#graphics + * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Graphics(this.game, x, y)); + + }, + + /** + * Create a new Emitter. + * + * A particle emitter can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accordingly. + * + * @method Phaser.GameObjectFactory#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles)); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectFactory#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectFactory#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size)); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectFactory#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {Phaser.Tilemap} The newly created tilemap object. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectFactory#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a Video object. + * + * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. + * + * @method Phaser.GameObjectFactory#video + * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. + * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) + * @return {Phaser.Video} The newly created Video object. + */ + video: function (key, url) { + + return new Phaser.Video(this.game, key, url); + + }, + + /** + * Create a BitmapData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectFactory#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectFactory#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + }, + + /** + * Add a new Plugin into the PluginManager. + * + * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.GameObjectFactory#plugin + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + plugin: function (plugin) { + + return this.game.plugins.add(plugin); + + } + +}; + +Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world. +* The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}. +* +* @class Phaser.GameObjectCreator +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectCreator = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectCreator.prototype = { + + /** + * Create a new Image object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectCreator#image + * @param {number} x - X position of the image. + * @param {number} y - Y position of the image. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Image} the newly created sprite object. + */ + image: function (x, y, key, frame) { + + return new Phaser.Image(this.game, x, y, key, frame); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * @method Phaser.GameObjectCreator#sprite + * @param {number} x - X position of the new sprite. + * @param {number} y - Y position of the new sprite. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Sprite} the newly created sprite object. + */ + sprite: function (x, y, key, frame) { + + return new Phaser.Sprite(this.game, x, y, key, frame); + + }, + + /** + * Create a tween object for a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectCreator#tween + * @param {object} obj - Object the tween will be run on. + * @return {Phaser.Tween} The Tween object. + */ + tween: function (obj) { + + return new Phaser.Tween(obj, this.game, this.game.tweens); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectCreator#group + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * Create a new SpriteBatch. + * + * @method Phaser.GameObjectCreator#spriteBatch + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.SpriteBatch} The newly created group. + */ + spriteBatch: function (parent, name, addToStage) { + + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectCreator#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectCreator#tileSprite + * @param {number} x - The x coordinate (in world space) to position the TileSprite at. + * @param {number} y - The y coordinate (in world space) to position the TileSprite at. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.TileSprite} The newly created tileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame) { + + return new Phaser.TileSprite(this.game, x, y, width, height, key, frame); + + }, + + /** + * Creates a new Rope object. + * + * @method Phaser.GameObjectCreator#rope + * @param {number} x - The x coordinate (in world space) to position the Rope at. + * @param {number} y - The y coordinate (in world space) to position the Rope at. + * @param {number} width - The width of the Rope. + * @param {number} height - The height of the Rope. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.Rope} The newly created rope object. + */ + rope: function (x, y, key, frame, points) { + + return new Phaser.Rope(this.game, x, y, key, frame, points); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectCreator#text + * @param {number} x - X position of the new text object. + * @param {number} y - Y position of the new text object. + * @param {string} text - The actual text that will be written. + * @param {object} style - The style object containing style attributes like font, font size , etc. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style) { + + return new Phaser.Text(this.game, x, y, text, style); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectCreator#button + * @param {number} [x] X position of the new button object. + * @param {number} [y] Y position of the new button object. + * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] The function to call when this button is pressed + * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @return {Phaser.Button} The newly created button object. + */ + 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); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectCreator#graphics + * @param {number} [x=0] - X position of the new graphics object. + * @param {number} [y=0] - Y position of the new graphics object. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y) { + + return new Phaser.Graphics(this.game, x, y); + + }, + + /** + * Creat a new Emitter. + * + * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accorindgly. + * + * @method Phaser.GameObjectCreator#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectCreator#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectCreator#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, align) { + + return new Phaser.BitmapText(this.game, x, y, font, text, size, align); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectCreator#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectCreator#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a BitmpaData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectCreator#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectCreator#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + } + +}; + +Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Sprites are the lifeblood of your game, used for nearly everything visual. +* +* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. +* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), +* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. +* +* @class Phaser.Sprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. If this argument is omitted, the sprite will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Sprite = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.SPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Sprite.prototype.constructor = Phaser.Sprite; + +Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.Sprite +* @return {boolean} True if the Sprite was rendered, otherwise false. +*/ +Phaser.Sprite.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image is a light-weight object you can use to display anything that doesn't need health, physics, or complex position monitoring. +* +* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. +* +* @class Phaser.Image +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. If this argument is omitted, the image will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Image = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.IMAGE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Image.prototype.constructor = Phaser.Image; + +Phaser.Component.Core.install.call(Phaser.Image.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Image.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Image#preUpdate +* @memberof Phaser.Image +*/ +Phaser.Image.prototype.preUpdate = function() { + + if (!this.preUpdateInWorld() || !this.preUpdateLifeSpan()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. +* +* The four states a Button responds to are: +* +* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. +* * 'Out' - when the Pointer that was previously over the Button moves out of it. +* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. +* * 'Up' - when the Pointer that was pressed down on the Button is released again. +* +* A different texture/frame and activation sound can be specified for any of the states. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. +* +* @class Phaser.Button +* @constructor +* @extends Phaser.Image +* @param {Phaser.Game} game Current game instance. +* @param {number} [x=0] - X position of the Button. +* @param {number} [y=0] - Y position of the Button. +* @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button. +* @param {function} [callback] - The function to call when this Button is pressed, receiving `this` (the Button), `pointer`, and `isOver` (see {@link Phaser.Events#onInputUp}.) +* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) { + + x = x || 0; + y = y || 0; + key = key || null; + callback = callback || null; + callbackContext = callbackContext || this; + + Phaser.Image.call(this, game, x, y, key, outFrame); + + /** + * The Phaser Object Type. + * @property {number} type + * @readonly + */ + this.type = Phaser.BUTTON; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * The name or ID of the Over state frame. + * @property {string|integer} onOverFrame + * @private + */ + this._onOverFrame = null; + + /** + * The name or ID of the Out state frame. + * @property {string|integer} onOutFrame + * @private + */ + this._onOutFrame = null; + + /** + * The name or ID of the Down state frame. + * @property {string|integer} onDownFrame + * @private + */ + this._onDownFrame = null; + + /** + * The name or ID of the Up state frame. + * @property {string|integer} onUpFrame + * @private + */ + this._onUpFrame = null; + + /** + * The Sound to be played when this Buttons Over state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound + * @readonly + */ + this.onOverSound = null; + + /** + * The Sound to be played when this Buttons Out state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound + * @readonly + */ + this.onOutSound = null; + + /** + * The Sound to be played when this Buttons Down state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound + * @readonly + */ + this.onDownSound = null; + + /** + * The Sound to be played when this Buttons Up state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound + * @readonly + */ + this.onUpSound = null; + + /** + * The Sound Marker used in conjunction with the onOverSound. + * @property {string} onOverSoundMarker + * @readonly + */ + this.onOverSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onOutSound. + * @property {string} onOutSoundMarker + * @readonly + */ + this.onOutSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onDownSound. + * @property {string} onDownSoundMarker + * @readonly + */ + this.onDownSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onUpSound. + * @property {string} onUpSoundMarker + * @readonly + */ + this.onUpSoundMarker = ''; + + /** + * The Signal (or event) dispatched when this Button is in an Over state. + * @property {Phaser.Signal} onInputOver + */ + this.onInputOver = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Out state. + * @property {Phaser.Signal} onInputOut + */ + this.onInputOut = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Down state. + * @property {Phaser.Signal} onInputDown + */ + this.onInputDown = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Up state. + * @property {Phaser.Signal} onInputUp + */ + this.onInputUp = new Phaser.Signal(); + + /** + * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. + * The frame will still be changed as applicable. + * + * @property {boolean} onOverMouseOnly + * @default + */ + this.onOverMouseOnly = true; + + /** + * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}. + * + * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. + * + * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR + */ + this.justReleasedPreventsOver = Phaser.PointerMode.CONTACT; + + /** + * When true the the texture frame will not be automatically switched on up/down/over/out events. + * @property {boolean} freezeFrames + * @default + */ + this.freezeFrames = false; + + /** + * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". + * + * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control. + * + * @property {boolean|Phaser.PointerMode} forceOut=false + * @default + */ + this.forceOut = false; + + this.inputEnabled = true; + + this.input.start(0, true); + + this.input.useHandCursor = true; + + this.setFrames(overFrame, outFrame, downFrame, upFrame); + + if (callback !== null) + { + this.onInputUp.add(callback, callbackContext); + } + + // Redirect the input events to here so we can handle animation updates, etc + this.events.onInputOver.add(this.onInputOverHandler, this); + this.events.onInputOut.add(this.onInputOutHandler, this); + this.events.onInputDown.add(this.onInputDownHandler, this); + this.events.onInputUp.add(this.onInputUpHandler, this); + +}; + +Phaser.Button.prototype = Object.create(Phaser.Image.prototype); +Phaser.Button.prototype.constructor = Phaser.Button; + +// State constants; local only. These are tied to property names in Phaser.Button. +var STATE_OVER = 'Over'; +var STATE_OUT = 'Out'; +var STATE_DOWN = 'Down'; +var STATE_UP = 'Up'; + +/** +* Clears all of the frames set on this Button. +* +* @method Phaser.Button#clearFrames +*/ +Phaser.Button.prototype.clearFrames = function () { + + this.setFrames(null, null, null, null); + +}; + +/** +* Set the frame name/ID for the given state. +* +* @method Phaser.Button#setStateFrame +* @private +* @param {object} state - See `STATE_*` +* @param {number|string} frame - The number or string representing the frame. +* @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true. +*/ +Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately) +{ + var frameKey = '_on' + state + 'Frame'; + + if (frame !== null) // not null or undefined + { + this[frameKey] = frame; + + if (switchImmediately) + { + this.changeStateFrame(state); + } + } + else + { + this[frameKey] = null; + } + +}; + +/** +* Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen". +* +* @method Phaser.Button#changeStateFrame +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if the frame was assigned a value, possibly the same one it already had. +*/ +Phaser.Button.prototype.changeStateFrame = function (state) { + + if (this.freezeFrames) + { + return false; + } + + var frameKey = '_on' + state + 'Frame'; + var frame = this[frameKey]; + + if (typeof frame === 'string') + { + this.frameName = frame; + return true; + } + else if (typeof frame === 'number') + { + this.frame = frame; + return true; + } + else + { + return false; + } + +}; + +/** +* Used to manually set the frames that will be used for the different states of the Button. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. +* +* @method Phaser.Button#setFrames +* @public +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) { + + this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver()); + this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver()); + this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown()); + this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp()); + +}; + +/** +* Set the sound/marker for the given state. +* +* @method Phaser.Button#setStateSound +* @private +* @param {object} state - See `STATE_*` +* @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound. +* @param {string} [marker=''] - Sound marker. +*/ +Phaser.Button.prototype.setStateSound = function (state, sound, marker) { + + var soundKey = 'on' + state + 'Sound'; + var markerKey = 'on' + state + 'SoundMarker'; + + if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite) + { + this[soundKey] = sound; + this[markerKey] = typeof marker === 'string' ? marker : ''; + } + else + { + this[soundKey] = null; + this[markerKey] = ''; + } + +}; + +/** +* Play the sound for the given state, _if_ the state has a sound assigned. +* +* @method Phaser.Button#playStateSound +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if a sound was played. +*/ +Phaser.Button.prototype.playStateSound = function (state) { + + var soundKey = 'on' + state + 'Sound'; + var sound = this[soundKey]; + + if (sound) + { + var markerKey = 'on' + state + 'SoundMarker'; + var marker = this[markerKey]; + + sound.play(marker); + return true; + } + else + { + return false; + } + +}; + +/** +* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. +* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. +* +* Call this function with no parameters to reset all sounds on this Button. +* +* @method Phaser.Button#setSounds +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound. +* @param {string} [overMarker] - Over Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound. +* @param {string} [downMarker] - Down Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound. +* @param {string} [outMarker] - Out Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound. +* @param {string} [upMarker] - Up Button Sound Marker. +*/ +Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) { + + this.setStateSound(STATE_OVER, overSound, overMarker); + this.setStateSound(STATE_OUT, outSound, outMarker); + this.setStateSound(STATE_DOWN, downSound, downMarker); + this.setStateSound(STATE_UP, upSound, upMarker); + +}; + +/** +* The Sound to be played when a Pointer moves over this Button. +* +* @method Phaser.Button#setOverSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOverSound = function (sound, marker) { + + this.setStateSound(STATE_OVER, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer moves out of this Button. +* +* @method Phaser.Button#setOutSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOutSound = function (sound, marker) { + + this.setStateSound(STATE_OUT, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer presses down on this Button. +* +* @method Phaser.Button#setDownSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setDownSound = function (sound, marker) { + + this.setStateSound(STATE_DOWN, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer has pressed down and is released from this Button. +* +* @method Phaser.Button#setUpSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setUpSound = function (sound, marker) { + + this.setStateSound(STATE_UP, sound, marker); + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOverHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) { + + if (pointer.justReleased() && + (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode) + { + // If the Pointer was only just released then we don't fire an over event + return; + } + + this.changeStateFrame(STATE_OVER); + + if (this.onOverMouseOnly && !pointer.isMouse) + { + return; + } + + this.playStateSound(STATE_OVER); + + if (this.onInputOver) + { + this.onInputOver.dispatch(this, pointer); + } + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOutHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_OUT); + + this.playStateSound(STATE_OUT); + + if (this.onInputOut) + { + this.onInputOut.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputDownHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_DOWN); + + this.playStateSound(STATE_DOWN); + + if (this.onInputDown) + { + this.onInputDown.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputUpHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) { + + this.playStateSound(STATE_UP); + + // Input dispatched early, before state change (but after sound) + if (this.onInputUp) + { + this.onInputUp.dispatch(this, pointer, isOver); + } + + if (this.freezeFrames) + { + return; + } + + if (this.forceOut === true || (this.forceOut & pointer.pointerMode) === pointer.pointerMode) + { + this.changeStateFrame(STATE_OUT); + } + else + { + var changedUp = this.changeStateFrame(STATE_UP); + if (!changedUp) + { + // No Up frame to show.. + if (isOver) + { + this.changeStateFrame(STATE_OVER); + } + else + { + this.changeStateFrame(STATE_OUT); + } + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. +* It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over +* 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled +* Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. +* +* Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. +* +* @class Phaser.SpriteBatch +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. +* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. +*/ +Phaser.SpriteBatch = function (game, parent, name, addToStage) { + + if (parent === undefined || parent === null) { parent = game.world; } + + Phaser.Group.call(this, game, parent, name, addToStage); + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.SPRITEBATCH; + + /** + * @property {Object} fastSpriteBatch - WebGL Batch Shader. + * @private + */ + this.fastSpriteBatch = null; + + /** + * @property {boolean} ready - Internal flag. + * @private + */ + this.ready = false; + +}; + +Phaser.SpriteBatch.prototype = Object.create(Phaser.Group.prototype); + +Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch; + +/** +* Renders the Sprite Batch using the WebGL renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + if (!this.ready) + { + this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(renderSession.gl); + + this.ready = true; + } + + if (this.fastSpriteBatch.gl !== renderSession.gl) + { + this.fastSpriteBatch.setContext(renderSession.gl); + } + + renderSession.spriteBatch.stop(); + + renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader); + + this.fastSpriteBatch.begin(this, renderSession); + this.fastSpriteBatch.render(this); + + renderSession.spriteBatch.start(); + +}; + +/** +* Renders the Sprite Batch using the Canvas renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + var context = renderSession.context; + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + var transform = this.worldTransform; + + var isRotated = true; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + var texture = child.texture; + var frame = texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) + { + // If rotation === 0 we can avoid setTransform + + if (isRotated) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); + isRotated = false; + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5 + renderSession.shakeX) | 0, + ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5 + renderSession.shakeY) | 0, + frame.width * child.scale.x, + frame.height * child.scale.y); + } + else + { + if (!isRotated) + { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + var tx = (childTransform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (childTransform.ty * renderSession.resolution) + renderSession.shakeY; + + // allow for trimming + + if (renderSession.roundPixels) + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx, ty); + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width) + 0.5) | 0, + ((child.anchor.y) * (-frame.height) + 0.5) | 0, + frame.width, + frame.height); + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. +* A single BitmapData can be used as the texture for one or many Images / Sprites. +* So if you need to dynamically create a Sprite texture then they are a good choice. +* +* Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't +* live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy +* in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. +* +* @class Phaser.BitmapData +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string} key - Internal Phaser reference key for the BitmapData. +* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. +*/ +Phaser.BitmapData = function (game, key, width, height, skipPool) { + + if (width === undefined || width === 0) { width = 256; } + if (height === undefined || height === 0) { height = 256; } + if (skipPool === undefined) { skipPool = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the BitmapData in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} width - The width of the BitmapData in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the BitmapData in pixels. + */ + this.height = height; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. + * @default + */ + this.canvas = Phaser.Canvas.create(this, width, height, null, skipPool); + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + * @default + */ + this.context = this.canvas.getContext('2d', { alpha: true }); + + /** + * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context. + */ + this.ctx = this.context; + + /** + * @property {string} smoothProperty - The context property needed for smoothing this Canvas. + */ + this.smoothProperty = (game.renderType === Phaser.CANVAS) ? game.renderer.renderSession.smoothProperty : Phaser.Canvas.getSmoothingPrefix(this.context); + + /** + * @property {ImageData} imageData - The context image data. + * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. + * This property is updated automatically after the first game loop, according to the dirty flag property. + */ + this.imageData = this.context.getImageData(0, 0, width, height); + + /** + * A Uint8ClampedArray view into BitmapData.buffer. + * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) + * @property {Uint8ClampedArray} data + */ + this.data = null; + + if (this.imageData) + { + this.data = this.imageData.data; + } + + /** + * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer. + */ + this.pixels = null; + + /** + * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData. + */ + if (this.data) + { + 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; + } + } + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + this.baseTexture = new PIXI.BaseTexture(this.canvas, null, this.game.resolution); + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering. + */ + this.frameData = new Phaser.FrameData(); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. + * @default + */ + this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData')); + + this.texture.frame = this.textureFrame; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.BITMAPDATA; + + /** + * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} dirty - If dirty this BitmapData will be re-rendered. + */ + this.dirty = false; + + // Aliases + this.cls = this.clear; + + /** + * @property {number} _image - Internal cache var. + * @private + */ + this._image = null; + + /** + * @property {Phaser.Point} _pos - Internal cache var. + * @private + */ + this._pos = new Phaser.Point(); + + /** + * @property {Phaser.Point} _size - Internal cache var. + * @private + */ + this._size = new Phaser.Point(); + + /** + * @property {Phaser.Point} _scale - Internal cache var. + * @private + */ + this._scale = new Phaser.Point(); + + /** + * @property {number} _rotate - Internal cache var. + * @private + */ + this._rotate = 0; + + /** + * @property {object} _alpha - Internal cache var. + * @private + */ + this._alpha = { prev: 1, current: 1 }; + + /** + * @property {Phaser.Point} _anchor - Internal cache var. + * @private + */ + this._anchor = new Phaser.Point(); + + /** + * @property {number} _tempR - Internal cache var. + * @private + */ + this._tempR = 0; + + /** + * @property {number} _tempG - Internal cache var. + * @private + */ + this._tempG = 0; + + /** + * @property {number} _tempB - Internal cache var. + * @private + */ + this._tempB = 0; + + /** + * @property {Phaser.Circle} _circle - Internal cache var. + * @private + */ + this._circle = new Phaser.Circle(); + + /** + * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods. + * @private + */ + this._swapCanvas = undefined; + +}; + +Phaser.BitmapData.prototype = { + + /** + * Shifts the contents of this BitmapData by the distances given. + * + * The image will wrap-around the edges on all sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#move + * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + move: function (x, y, wrap) { + + if (x !== 0) + { + this.moveH(x, wrap); + } + + if (y !== 0) + { + this.moveV(y, wrap); + } + + return this; + + }, + + /** + * Shifts the contents of this BitmapData horizontally. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveH + * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveH: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var h = this.height; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving to the left + var w = this.width - distance; + + // Left-hand chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h); + } + else + { + // Moving to the right + var w = this.width - distance; + + // Right-hand chunk + if (wrap) + { + ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Shifts the contents of this BitmapData vertically. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveV + * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveV: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var w = this.width; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving up + var h = this.height - distance; + + // Top chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h); + } + else + { + // Moving down + var h = this.height - distance; + + // Bottom chunk + if (wrap) + { + ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Updates the given objects so that they use this BitmapData as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.BitmapData#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. + * The source game object is not modified by this operation. + * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. + * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. + * + * @method Phaser.BitmapData#load + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + load: function (source) { + + if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + } + + if (source) + { + this.resize(source.width, source.height); + this.cls(); + } + else + { + return; + } + + this.draw(source); + + this.update(); + + return this; + + }, + + /** + * Clears the BitmapData context using a clearRect. + * + * @method Phaser.BitmapData#cls + */ + + /** + * Clears the BitmapData context using a clearRect. + * + * You can optionally define the area to clear. + * If the arguments are left empty it will clear the entire canvas. + * + * You may need to call BitmapData.update after this in order to clear out the pixel data, + * but Phaser will not do this automatically for you. + * + * @method Phaser.BitmapData#clear + * @param {number} [x=0] - The x coordinate of the top-left of the area to clear. + * @param {number} [y=0] - The y coordinate of the top-left of the area to clear. + * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width. + * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + clear: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + this.context.clearRect(x, y, width, height); + + this.dirty = true; + + return this; + + }, + + /** + * Fills the BitmapData with the given color. + * + * @method Phaser.BitmapData#fill + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} [a=1] - The alpha color value, between 0 and 1. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + fill: function (r, g, b, a) { + + if (a === undefined) { a = 1; } + + this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; + this.context.fillRect(0, 0, this.width, this.height); + this.dirty = true; + + return this; + + }, + + /** + * Creates a new {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image} element by converting this BitmapDatas canvas into a dataURL. + * + * The image is then stored in the {@link Phaser.Cache image Cache} using the key given. + * + * Finally a {@link PIXI.Texture} is created based on the image and returned. + * + * You can apply the texture to a sprite or any other supporting object by using either the + * key or the texture. First call `generateTexture`: + * + * ```javascript + * var texture = bitmapdata.generateTexture('ball'); + * ``` + * + * Then you can either apply the texture to a sprite: + * + * ```javascript + * game.add.sprite(0, 0, texture); + * ``` + * + * or by using the string based key: + * + * ```javascript + * game.add.sprite(0, 0, 'ball'); + * ``` + * + * Most browsers now load the image data asynchronously, so you should use a callback: + * + * ```javascript + * bitmapdata.generateTexture('ball', function (texture) { + * game.add.sprite(0, 0, texture); + * // or + * game.add.sprite(0, 0, 'ball'); + * }); + * ``` + * + * If this BitmapData is available during preload, you can use {@link Phaser.Loader#imageFromBitmapData} instead. + * + * @method Phaser.BitmapData#generateTexture + * @param {string} key - The key which will be used to store the image in the Cache. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {PIXI.Texture|null} The newly generated texture, or `null` if a callback was passed and the texture isn't available yet. + */ + generateTexture: function (key, callback, callbackContext) { + + var cache = this.game.cache; + var image = new Image(); + + if (callback) + { + image.onload = function () { + var obj = cache.addImage(key, '', image); + var texture = new PIXI.Texture(obj.base); + + callback.call(callbackContext || null, texture); + + image.onload = null; + }; + } + + image.src = this.canvas.toDataURL("image/png"); + + if (!callback) + { + var obj = cache.addImage(key, '', image); + + return new PIXI.Texture(obj.base); + } + + return null; + + }, + + /** + * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. + * + * @method Phaser.BitmapData#resize + * @param {integer} width - The new width of the BitmapData. + * @param {integer} height - The new height of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + resize: function (width, height) { + + if (width !== this.width || height !== this.height) + { + this.width = width; + this.height = height; + + this.canvas.width = width; + this.canvas.height = height; + + if (this._swapCanvas !== undefined) + { + this._swapCanvas.width = width; + this._swapCanvas.height = height; + } + + this.baseTexture.width = width; + this.baseTexture.height = height; + + this.textureFrame.width = width; + this.textureFrame.height = height; + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.update(); + this.dirty = true; + } + + return this; + + }, + + /** + * This re-creates the BitmapData.imageData from the current context. + * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. + * If not given the dimensions defaults to the full size of the context. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.BitmapData#update + * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from. + * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from. + * @param {number} [width=1] - The width of the image data area. + * @param {number} [height=1] - The height of the image data area. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + update: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = Math.max(1, this.width); } + if (height === undefined) { height = Math.max(1, this.height); } + + this.imageData = this.context.getImageData(x, y, width, height); + this.data = this.imageData.data; + + 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; + } + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. + * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. + * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. + * The `color` property is an Int32 of the full color. Note the endianess of this will change per system. + * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. + * The callback will also be sent the pixels x and y coordinates respectively. + * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. + * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. + * + * @method Phaser.BitmapData#processPixelRGB + * @param {function} callback - The callback that will be sent each pixel color object to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixelRGB: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = Phaser.Color.createColor(); + var result = { r: 0, g: 0, b: 0, a: 0 }; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel); + + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== false && result !== null && result !== undefined) + { + this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false); + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. + * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. + * Note that the format of the color received will be different depending on if the system is big or little endian. + * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. + * The callback will also be sent the pixels x and y coordinates respectively. + * + * @method Phaser.BitmapData#processPixel + * @param {function} callback - The callback that will be sent each pixel color to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixel: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = 0; + var result = 0; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + pixel = this.getPixel32(tx, ty); + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== pixel) + { + this.pixels[ty * this.width + tx] = result; + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. + * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. + * + * @method Phaser.BitmapData#replaceRGB + * @param {number} r1 - The red color value to be replaced. Between 0 and 255. + * @param {number} g1 - The green color value to be replaced. Between 0 and 255. + * @param {number} b1 - The blue color value to be replaced. Between 0 and 255. + * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255. + * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255. + * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255. + * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255. + * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255. + * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) { + + var sx = 0; + var sy = 0; + var w = this.width; + var h = this.height; + var source = Phaser.Color.packPixel(r1, g1, b1, a1); + + if (region !== undefined && region instanceof Phaser.Rectangle) + { + sx = region.x; + sy = region.y; + w = region.width; + h = region.height; + } + + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + if (this.getPixel32(sx + x, sy + y) === source) + { + this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false); + } + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * + * @method Phaser.BitmapData#setHSL + * @param {number} [h=null] - The hue, in the range 0 - 1. + * @param {number} [s=null] - The saturation, in the range 0 - 1. + * @param {number} [l=null] - The lightness, in the range 0 - 1. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setHSL: function (h, s, l, region) { + + var bHaveH = h || h === 0; + var bHaveS = s || s === 0; + var bHaveL = l || l === 0; + + if (!bHaveH && !bHaveS && !bHaveL) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (bHaveH) + { + pixel.h = h; + } + + if (bHaveS) + { + pixel.s = s; + } + + if (bHaveL) + { + pixel.l = l; + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * Shifting will add the given value onto the current h, s and l values, not replace them. + * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. + * + * @method Phaser.BitmapData#shiftHSL + * @param {number} [h=null] - The amount to shift the hue by. Within [-1, 1]. + * @param {number} [s=null] - The amount to shift the saturation by. Within [-1, 1]. + * @param {number} [l=null] - The amount to shift the lightness by. Within [-1, 1]. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shiftHSL: function (h, s, l, region) { + + if (h === undefined || h === null) { h = false; } + if (s === undefined || s === null) { s = false; } + if (l === undefined || l === null) { l = false; } + + if (!h && !s && !l) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (h) + { + pixel.h = this.game.math.wrap(pixel.h + h, 0, 1); + } + + if (s) + { + pixel.s = this.game.math.clamp(pixel.s + s, 0, 1); + } + + if (l) + { + pixel.l = this.game.math.clamp(pixel.l + l, 0, 1); + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green, blue and alpha values. + * + * @method Phaser.BitmapData#setPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel32: function (x, y, red, green, blue, alpha, immediate) { + + if (immediate === undefined) { immediate = true; } + + if (x >= 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; + } + } + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green and blue values. + * + * @method Phaser.BitmapData#setPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel: function (x, y, red, green, blue, immediate) { + + return this.setPixel32(x, y, red, green, blue, 255, immediate); + + }, + + /** + * Get the color of a specific pixel in the context into a color object. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + getPixel: function (x, y, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var index = ~~(x + (y * this.width)); + + index *= 4; + + out.r = this.data[index]; + out.g = this.data[++index]; + out.b = this.data[++index]; + out.a = this.data[++index]; + + return out; + + }, + + /** + * Get the color of a specific pixel including its alpha value. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. + * + * @method Phaser.BitmapData#getPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @return {number} A native color value integer (format: 0xAARRGGBB) + */ + getPixel32: function (x, y) { + + if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) + { + return this.pixels[y * this.width + x]; + } + + }, + + /** + * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixelRGB + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + getPixelRGB: function (x, y, out, hsl, hsv) { + + return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv); + + }, + + /** + * Gets all the pixels from the region specified by the given Rectangle object. + * + * @method Phaser.BitmapData#getPixels + * @param {Phaser.Rectangle} rect - The Rectangle region to get. + * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property. + */ + getPixels: function (rect) { + + return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); + + }, + + /** + * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). + * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. + * + * The direction parameter controls from which direction it should start the scan: + * + * 0 = top to bottom + * 1 = bottom to top + * 2 = left to right + * 3 = right to left + * + * @method Phaser.BitmapData#getFirstPixel + * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. + * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. + */ + getFirstPixel: function (direction) { + + if (direction === undefined) { direction = 0; } + + var pixel = Phaser.Color.createColor(); + + var x = 0; + var y = 0; + var v = 1; + var scan = false; + + if (direction === 1) + { + v = -1; + y = this.height; + } + else if (direction === 3) + { + v = -1; + x = this.width; + } + + do { + + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel); + + if (direction === 0 || direction === 1) + { + // Top to Bottom / Bottom to Top + x++; + + if (x === this.width) + { + x = 0; + y += v; + + if (y >= this.height || y <= 0) + { + scan = true; + } + } + } + else if (direction === 2 || direction === 3) + { + // Left to Right / Right to Left + y++; + + if (y === this.height) + { + y = 0; + x += v; + + if (x >= this.width || x <= 0) + { + scan = true; + } + } + } + } + while (pixel.a === 0 && !scan); + + pixel.x = x; + pixel.y = y; + + return pixel; + + }, + + /** + * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. + * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. + * + * @method Phaser.BitmapData#getBounds + * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. + * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. + */ + getBounds: function (rect) { + + if (rect === undefined) { rect = new Phaser.Rectangle(); } + + rect.x = this.getFirstPixel(2).x; + + // If we hit this, there's no point scanning any more, the image is empty + if (rect.x === this.width) + { + return rect.setTo(0, 0, 0, 0); + } + + rect.y = this.getFirstPixel(0).y; + rect.width = (this.getFirstPixel(3).x - rect.x) + 1; + rect.height = (this.getFirstPixel(1).y - rect.y) + 1; + + return rect; + + }, + + /** + * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. + * + * @method Phaser.BitmapData#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself. + * + * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn. + * + * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters. + * + * Note that the source image can also be this BitmapData, which can create some interesting effects. + * + * This method has a lot of parameters for maximum control. + * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all. + * + * You may prefer to use `copyTransform` if you're simply trying to draw a Sprite to this BitmapData, + * and don't wish to translate, scale or rotate it from its original values. + * + * @method Phaser.BitmapData#copy + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image. + * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image. + * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width. + * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height. + * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`. + * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`. + * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter. + * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter. + * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters. + * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) { + + if (source === undefined || source === null) { source = this; } + + if (source instanceof Phaser.RenderTexture) + { + source = source.getCanvas(); + } + + this._image = source; + + if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text || source instanceof PIXI.Sprite) + { + // Copy over sprite values + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + this._scale.set(source.scale.x, source.scale.y); + this._anchor.set(source.anchor.x, source.anchor.y); + this._rotate = source.rotation; + this._alpha.current = source.alpha; + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + if (tx === undefined || tx === null) { tx = source.x; } + if (ty === undefined || ty === null) { ty = source.y; } + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + } + else + { + // Reset + this._pos.set(0); + this._scale.set(1); + this._anchor.set(0); + this._rotate = 0; + this._alpha.current = 1; + + if (source instanceof Phaser.BitmapData) + { + this._image = source.canvas; + } + else if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + + if (source === null) + { + return; + } + else + { + this._image = source; + } + } + + this._size.set(this._image.width, this._image.height); + } + + // The source region to copy from + if (x === undefined || x === null) { x = 0; } + if (y === undefined || y === null) { y = 0; } + + // If they set a width/height then we override the frame values with them + if (width) + { + this._size.x = width; + } + + if (height) + { + this._size.y = height; + } + + // The destination region to copy to + if (tx === undefined || tx === null) { tx = x; } + if (ty === undefined || ty === null) { ty = y; } + if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; } + if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; } + + // Rotation - if set this will override any potential Sprite value + if (typeof rotate === 'number') + { + this._rotate = rotate; + } + + // Anchor - if set this will override any potential Sprite value + if (typeof anchorX === 'number') + { + this._anchor.x = anchorX; + } + + if (typeof anchorY === 'number') + { + this._anchor.y = anchorY; + } + + // Scaling - if set this will override any potential Sprite value + if (typeof scaleX === 'number') + { + this._scale.x = scaleX; + } + + if (typeof scaleY === 'number') + { + this._scale.y = scaleY; + } + + // Effects + if (typeof alpha === 'number') + { + this._alpha.current = alpha; + } + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + // Doesn't work fully with children, or nested scale + rotation transforms (see copyTransform) + ctx.translate(tx, ty); + + ctx.scale(this._scale.x, this._scale.y); + + ctx.rotate(this._rotate); + + ctx.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight); + + // Carry on ... + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the + * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. + * It takes the objects tint and scale mode into consideration before drawing. + * + * You can optionally specify Blend Mode and Round Pixels arguments. + * + * @method Phaser.BitmapData#copyTransform + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyTransform: function (source, blendMode, roundPx) { + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (!source.hasOwnProperty('worldTransform') || !source.worldVisible || source.worldAlpha === 0) + { + return this; + } + + var wt = source.worldTransform; + + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + + if (wt.a === 0 || wt.d === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return this; + } + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + var tx = wt.tx; + var ty = wt.ty; + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + ctx[this.smoothProperty] = (source.texture.baseTexture.scaleMode === PIXI.scaleModes.LINEAR); + + ctx.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + + ctx.drawImage(this._image, + this._pos.x, + this._pos.y, + this._size.x, + this._size.y, + -this._size.x * source.anchor.x, + -this._size.y * source.anchor.y, + this._size.x, + this._size.y); + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. + * + * @method Phaser.BitmapData#copyRect + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. + * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image. + * @param {number} x - The destination x coordinate to copy the image to. + * @param {number} y - The destination y coordinate to copy the image to. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyRect: function (source, area, x, y, alpha, blendMode, roundPx) { + + return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx); + + }, + + /** + * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. + * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. + * + * @method Phaser.BitmapData#draw + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData. + * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`. + * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`. + * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`. + * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + draw: function (source, x, y, width, height, blendMode, roundPx) { + + // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here + return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx); + + }, + + /** + * Draws the immediate children of a Phaser.Group to this BitmapData. + * + * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. + * + * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. + * + * @method Phaser.BitmapData#drawGroup + * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawGroup: function (group, blendMode, roundPx) { + + if (group.total > 0) + { + group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx); + } + + return this; + + }, + + /** + * A proxy for drawGroup that handles child iteration for more complex Game Objects. + * + * @method Phaser.BitmapData#drawGroupProxy + * @private + * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + */ + drawGroupProxy: function (child, blendMode, roundPx) { + + if (child.hasOwnProperty('texture')) + { + this.copyTransform(child, blendMode, roundPx); + } + + if (child.type === Phaser.GROUP && child.exists) + { + this.drawGroup(child, blendMode, roundPx); + } + else + { + if (child.hasOwnProperty('children') && child.children.length > 0) + { + for (var i = 0; i < child.children.length; i++) + { + if (child.children[i].exists) + { + this.copyTransform(child.children[i], blendMode, roundPx); + } + } + } + } + + }, + + /** + * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. + * + * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData + * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the + * bounds of the top-level Game Object. + * + * When drawing it will take into account the child's world rotation, scale and alpha values. + * + * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. + * + * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update + * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can + * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. + * + * @method Phaser.BitmapData#drawFull + * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawFull: function (parent, blendMode, roundPx) { + + if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false)) + { + return this; + } + + if (parent.type !== Phaser.GROUP && parent.type !== Phaser.EMITTER && parent.type !== Phaser.BITMAPTEXT) + { + if (parent.type === Phaser.GRAPHICS) + { + var bounds = parent.getBounds(); + this.ctx.save(); + this.ctx.translate(bounds.x, bounds.y); + PIXI.CanvasGraphics.renderGraphics(parent, this.ctx); + this.ctx.restore(); + } + else + { + this.copy(parent, null, null, null, null, parent.worldPosition.x, parent.worldPosition.y, null, null, parent.worldRotation, null, null, parent.worldScale.x, parent.worldScale.y, parent.worldAlpha, blendMode, roundPx); + } + } + + if (parent.children) + { + for (var i = 0; i < parent.children.length; i++) + { + this.drawFull(parent.children[i], blendMode, roundPx); + } + } + + return this; + + }, + + /** + * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. + * You can cancel an existing shadow by calling this method and passing no parameters. + * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. + * + * @method Phaser.BitmapData#shadow + * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. + * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. + * @param {number} [x=10] - The horizontal offset of the shadow in pixels. + * @param {number} [y=10] - The vertical offset of the shadow in pixels. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shadow: function (color, blur, x, y) { + + var ctx = this.context; + + if (color === undefined || color === null) + { + ctx.shadowColor = 'rgba(0,0,0,0)'; + } + else + { + ctx.shadowColor = color; + ctx.shadowBlur = blur || 5; + ctx.shadowOffsetX = x || 10; + ctx.shadowOffsetY = y || 10; + } + + return this; + + }, + + /** + * Draws the image onto this BitmapData using an image as an alpha mask. + * + * @method Phaser.BitmapData#alphaMask + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. + * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. + * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + alphaMask: function (source, mask, sourceRect, maskRect) { + + if (maskRect === undefined || maskRect === null) + { + this.draw(mask).blendSourceAtop(); + } + else + { + this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop(); + } + + if (sourceRect === undefined || sourceRect === null) + { + this.draw(source).blendReset(); + } + else + { + this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset(); + } + + return this; + + }, + + /** + * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. + * The original BitmapData remains unchanged. + * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. + * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: + * `picture.extract(mask, r, g, b)` + * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. + * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint + * the color during extraction. + * + * @method Phaser.BitmapData#extract + * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. + * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied? + * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255. + * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255. + * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255. + * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on. + */ + extract: function (destination, r, g, b, a, resize, r2, g2, b2) { + + if (a === undefined) { a = 255; } + if (resize === undefined) { resize = false; } + if (r2 === undefined) { r2 = r; } + if (g2 === undefined) { g2 = g; } + if (b2 === undefined) { b2 = b; } + + if (resize) + { + destination.resize(this.width, this.height); + } + + this.processPixelRGB( + function (pixel, x, y) + { + if (pixel.r === r && pixel.g === g && pixel.b === b) + { + destination.setPixel32(x, y, r2, g2, b2, a, false); + } + return false; + }, + this); + + destination.context.putImageData(destination.imageData, 0, 0); + destination.dirty = true; + + return destination; + + }, + + /** + * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. + * + * @method Phaser.BitmapData#rect + * @param {number} x - The x coordinate of the top-left of the Rectangle. + * @param {number} y - The y coordinate of the top-left of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + rect: function (x, y, width, height, fillStyle) { + + if (typeof fillStyle !== 'undefined') + { + this.context.fillStyle = fillStyle; + } + + this.context.fillRect(x, y, width, height); + + return this; + + }, + + /** + * Draws text to the BitmapData in the given font and color. + * The default font is 14px Courier, so useful for quickly drawing debug text. + * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. + * + * @method Phaser.BitmapData#text + * @param {string} text - The text to write to the BitmapData. + * @param {number} x - The x coordinate of the top-left of the text string. + * @param {number} y - The y coordinate of the top-left of the text string. + * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can. + * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in. + * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1) + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + text: function (text, x, y, font, color, shadow) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (font === undefined) { font = '14px Courier'; } + if (color === undefined) { color = 'rgb(255,255,255)'; } + if (shadow === undefined) { shadow = true; } + + var ctx = this.context; + var prevFont = ctx.font; + + ctx.font = font; + + if (shadow) + { + ctx.fillStyle = 'rgb(0,0,0)'; + ctx.fillText(text, x + 1, y + 1); + } + + ctx.fillStyle = color; + ctx.fillText(text, x, y); + + ctx.font = prevFont; + + return this; + + }, + + /** + * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. + * + * @method Phaser.BitmapData#circle + * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle. + * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle. + * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + circle: function (x, y, radius, fillStyle) { + + var ctx = this.context; + + if (fillStyle !== undefined) + { + ctx.fillStyle = fillStyle; + } + + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2, false); + ctx.closePath(); + + ctx.fill(); + + return this; + + }, + + /** + * Draws a line between the coordinates given in the color and thickness specified. + * + * @method Phaser.BitmapData#line + * @param {number} x1 - The x coordinate to start the line from. + * @param {number} y1 - The y coordinate to start the line from. + * @param {number} x2 - The x coordinate to draw the line to. + * @param {number} y2 - The y coordinate to draw the line to. + * @param {string} [color='#fff'] - The stroke color that the line will be drawn in. + * @param {number} [width=1] - The line thickness. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + line: function (x1, y1, x2, y2, color, width) { + + if (color === undefined) { color = '#fff'; } + if (width === undefined) { width = 1; } + + var ctx = this.context; + + ctx.beginPath(); + + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); + + ctx.closePath(); + + return this; + + }, + + /** + * Draws a polygon. + * + * @method Phaser.BitmapData#polygon + * @param {object[]} points - An array of {@link Phaser.Point} or point-like objects. + * @param {CanvasGradient|CanvasPattern|string} [fillStyle] - A color, gradient, or pattern. + * @param {number} [lineWidth=0] - The line thickness. + * @param {CanvasGradient|CanvasPattern|string} [strokeStyle='#fff'] - The line color, gradient, or pattern (when `lineWidth` > 0). + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + polygon: function (points, fillStyle, lineWidth, strokeStyle) { + + // Could reject points.length < 3 + + if (strokeStyle === undefined) { strokeStyle = '#fff'; } + if (lineWidth === undefined) { lineWidth = 0; } + + var ctx = this.context; + + if (fillStyle) + { + ctx.fillStyle = fillStyle; + } + + if (lineWidth) + { + ctx.lineWidth = lineWidth; + ctx.strokeStyle = strokeStyle; + } + + ctx.beginPath(); + + ctx.moveTo(points[0].x, points[0].y); + + for (var i = 1, len = points.length; i < len; i++) + { + var point = points[i]; + ctx.lineTo(point.x, point.y); + } + + ctx.closePath(); + + if (fillStyle) { ctx.fill(); } + if (lineWidth) { ctx.stroke(); } + + return this; + + }, + + /** + * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. + * + * @method Phaser.BitmapData#textureLine + * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line. + * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. + * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + textureLine: function (line, image, repeat) { + + if (repeat === undefined) { repeat = 'repeat-x'; } + + if (typeof image === 'string') + { + image = this.game.cache.getImage(image); + + if (!image) + { + return; + } + } + + var width = line.length; + + if (repeat === 'no-repeat' && width > image.width) + { + width = image.width; + } + + var ctx = this.context; + + ctx.fillStyle = ctx.createPattern(image, repeat); + + this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height); + + this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos); + + ctx.save(); + ctx.translate(this._pos.x, this._pos.y); + ctx.rotate(line.angle); + ctx.fillRect(0, 0, width, image.height); + ctx.restore(); + + this.dirty = true; + + return this; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. + * + * @method Phaser.BitmapData#render + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + render: function () { + + if (!this.disableTextureUpload && this.dirty) + { + this.baseTexture.dirty(); + this.dirty = false; + } + + return this; + + }, + + /** + * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. + * + * @method Phaser.BitmapData#destroy + */ + destroy: function () { + + this.frameData.destroy(); + + this.texture.destroy(true); + + Phaser.CanvasPool.remove(this); + + }, + + /** + * Resets the blend mode (effectively sets it to 'source-over') + * + * @method Phaser.BitmapData#blendReset + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendReset: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-over' + * + * @method Phaser.BitmapData#blendSourceOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOver: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-in' + * + * @method Phaser.BitmapData#blendSourceIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceIn: function () { + + this.op = 'source-in'; + return this; + + }, + + /** + * Sets the blend mode to 'source-out' + * + * @method Phaser.BitmapData#blendSourceOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOut: function () { + + this.op = 'source-out'; + return this; + + }, + + /** + * Sets the blend mode to 'source-atop' + * + * @method Phaser.BitmapData#blendSourceAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceAtop: function () { + + this.op = 'source-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-over' + * + * @method Phaser.BitmapData#blendDestinationOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOver: function () { + + this.op = 'destination-over'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-in' + * + * @method Phaser.BitmapData#blendDestinationIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationIn: function () { + + this.op = 'destination-in'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-out' + * + * @method Phaser.BitmapData#blendDestinationOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOut: function () { + + this.op = 'destination-out'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-atop' + * + * @method Phaser.BitmapData#blendDestinationAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationAtop: function () { + + this.op = 'destination-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'xor' + * + * @method Phaser.BitmapData#blendXor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendXor: function () { + + this.op = 'xor'; + return this; + + }, + + /** + * Sets the blend mode to 'lighter' + * + * @method Phaser.BitmapData#blendAdd + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendAdd: function () { + + this.op = 'lighter'; + return this; + + }, + + /** + * Sets the blend mode to 'multiply' + * + * @method Phaser.BitmapData#blendMultiply + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendMultiply: function () { + + this.op = 'multiply'; + return this; + + }, + + /** + * Sets the blend mode to 'screen' + * + * @method Phaser.BitmapData#blendScreen + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendScreen: function () { + + this.op = 'screen'; + return this; + + }, + + /** + * Sets the blend mode to 'overlay' + * + * @method Phaser.BitmapData#blendOverlay + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendOverlay: function () { + + this.op = 'overlay'; + return this; + + }, + + /** + * Sets the blend mode to 'darken' + * + * @method Phaser.BitmapData#blendDarken + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDarken: function () { + + this.op = 'darken'; + return this; + + }, + + /** + * Sets the blend mode to 'lighten' + * + * @method Phaser.BitmapData#blendLighten + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLighten: function () { + + this.op = 'lighten'; + return this; + + }, + + /** + * Sets the blend mode to 'color-dodge' + * + * @method Phaser.BitmapData#blendColorDodge + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorDodge: function () { + + this.op = 'color-dodge'; + return this; + + }, + + /** + * Sets the blend mode to 'color-burn' + * + * @method Phaser.BitmapData#blendColorBurn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorBurn: function () { + + this.op = 'color-burn'; + return this; + + }, + + /** + * Sets the blend mode to 'hard-light' + * + * @method Phaser.BitmapData#blendHardLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHardLight: function () { + + this.op = 'hard-light'; + return this; + + }, + + /** + * Sets the blend mode to 'soft-light' + * + * @method Phaser.BitmapData#blendSoftLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSoftLight: function () { + + this.op = 'soft-light'; + return this; + + }, + + /** + * Sets the blend mode to 'difference' + * + * @method Phaser.BitmapData#blendDifference + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDifference: function () { + + this.op = 'difference'; + return this; + + }, + + /** + * Sets the blend mode to 'exclusion' + * + * @method Phaser.BitmapData#blendExclusion + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendExclusion: function () { + + this.op = 'exclusion'; + return this; + + }, + + /** + * Sets the blend mode to 'hue' + * + * @method Phaser.BitmapData#blendHue + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHue: function () { + + this.op = 'hue'; + return this; + + }, + + /** + * Sets the blend mode to 'saturation' + * + * @method Phaser.BitmapData#blendSaturation + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSaturation: function () { + + this.op = 'saturation'; + return this; + + }, + + /** + * Sets the blend mode to 'color' + * + * @method Phaser.BitmapData#blendColor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColor: function () { + + this.op = 'color'; + return this; + + }, + + /** + * Sets the blend mode to 'luminosity' + * + * @method Phaser.BitmapData#blendLuminosity + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLuminosity: function () { + + this.op = 'luminosity'; + return this; + + }, + + /** + * Updates a portion of the BitmapData from a source Bitmap. + * This optimization is important if calling update() on a large Bitmap is causing performance issues. + * Make sure you use getPixel32() instead of getPixel(). + * This does not work with floating point numbers for x and y. + * + * @method Phaser.BitmapData#copyBitmapData + * @param {Phaser.BitmapData} [source] - The BitmapData you wish to copy. + * @param {number} [x] - The x coordinate of the top-left of the area to copy. + * @param {number} [y] - The y coordinate of the top-left of the area to copy. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyBitmapData: function(source, x, y) { + + source.update(); + for (var i = 0, destRowStart; i < source.height; i++) { + destRowStart = (y + i) * this.width + x; + for (var j = 0; j < source.width; j++) { + this.pixels[destRowStart + j] = source.pixels[i * source.width + j]; + } + } + return this; + + } + +}; + +/** +* @memberof Phaser.BitmapData +* @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", { + + get: function () { + + Phaser.Canvas.getSmoothingEnabled(this.context); + + }, + + set: function (value) { + + Phaser.Canvas.setSmoothingEnabled(this.context, value); + + } + +}); + +/** +* @memberof Phaser.BitmapData +* @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "op", { + + get: function () { + + return this.context.globalCompositeOperation; + + }, + + set: function (value) { + + this.context.globalCompositeOperation = value; + + } + +}); + +/** + * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform. + * + * @method Phaser.BitmapData.getTransform + * @param {number} translateX - The x translate value. + * @param {number} translateY - The y translate value. + * @param {number} scaleX - The scale x value. + * @param {number} scaleY - The scale y value. + * @param {number} skewX - The skew x value. + * @param {number} skewY - The skew y value. + * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms. + */ +Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) { + + if (typeof translateX !== 'number') { translateX = 0; } + if (typeof translateY !== 'number') { translateY = 0; } + if (typeof scaleX !== 'number') { scaleX = 1; } + if (typeof scaleY !== 'number') { scaleY = 1; } + if (typeof skewX !== 'number') { skewX = 0; } + if (typeof skewY !== 'number') { skewY = 0; } + + return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY }; + +}; + +Phaser.BitmapData.prototype.constructor = Phaser.BitmapData; + +/* jshint ignore:start */ + +/* +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ + +/** +* @class EarCut +*/ +Phaser.EarCut = {}; + +Phaser.EarCut.Triangulate = function (data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = Phaser.EarCut.linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = Phaser.EarCut.eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + Phaser.EarCut.earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +}; + +// create a circular doubly linked list from polygon points in the specified winding order + +Phaser.EarCut.linkedList = function (data, start, end, dim, clockwise) { + var sum = 0, + i, j, last; + + // calculate original winding order of a polygon ring + for (i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + + // link points into circular doubly-linked list in the specified winding order + if (clockwise === (sum > 0)) { + for (i = start; i < end; i += dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } + + return last; +}; + +// eliminate colinear or duplicate points + +Phaser.EarCut.filterPoints = function (start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (Phaser.EarCut.equals(p, p.next) || Phaser.EarCut.area(p.prev, p, p.next) === 0)) { + Phaser.EarCut.removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +}; + +// main ear slicing loop which triangulates a polygon (given as a linked list) + +Phaser.EarCut.earcutLinked = function (ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) Phaser.EarCut.indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? Phaser.EarCut.isEarHashed(ear, minX, minY, size) : Phaser.EarCut.isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + Phaser.EarCut.removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + Phaser.EarCut.earcutLinked(Phaser.EarCut.filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = Phaser.EarCut.cureLocalIntersections(ear, triangles, dim); + Phaser.EarCut.earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + Phaser.EarCut.splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +}; + +// check whether a polygon node forms a valid ear with adjacent nodes + +Phaser.EarCut.isEar = function (ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +}; + +Phaser.EarCut.isEarHashed = function (ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = Phaser.EarCut.zOrder(minTX, minTY, minX, minY, size), + maxZ = Phaser.EarCut.zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +}; + +// go through all polygon nodes and cure small local self-intersections + +Phaser.EarCut.cureLocalIntersections = function (start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) + if (Phaser.EarCut.intersects(a, p, p.next, b) && Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + Phaser.EarCut.removeNode(p); + Phaser.EarCut.removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +}; + +// try splitting polygon into two and triangulate them independently + +Phaser.EarCut.splitEarcut = function (start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && Phaser.EarCut.isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = Phaser.EarCut.splitPolygon(a, b); + + // filter colinear points around the cuts + a = Phaser.EarCut.filterPoints(a, a.next); + c = Phaser.EarCut.filterPoints(c, c.next); + + // run earcut on each half + Phaser.EarCut.earcutLinked(a, triangles, dim, minX, minY, size); + Phaser.EarCut.earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +}; + +// link every hole into the outer loop, producing a single-ring polygon without holes + +Phaser.EarCut.eliminateHoles = function (data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = Phaser.EarCut.linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(Phaser.EarCut.getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + Phaser.EarCut.eliminateHole(queue[i], outerNode); + outerNode = Phaser.EarCut.filterPoints(outerNode, outerNode.next); + } + + return outerNode; +}; + +Phaser.EarCut.compareX = function (a, b) { + return a.x - b.x; +}; + +// find a bridge between vertices that connects hole with an outer ring and and link it + +Phaser.EarCut.eliminateHole = function (hole, outerNode) { + outerNode = Phaser.EarCut.findHoleBridge(hole, outerNode); + if (outerNode) { + var b = Phaser.EarCut.splitPolygon(outerNode, hole); + Phaser.EarCut.filterPoints(b, b.next); + } +}; + +// David Eberly's algorithm for finding a bridge between hole and outer polygon + +Phaser.EarCut.findHoleBridge = function (hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hole.x === m.x) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= m.x && + Phaser.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && Phaser.EarCut.locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +}; + +// interlink polygon nodes in z-order + +Phaser.EarCut.indexCurve = function (start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = Phaser.EarCut.zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + Phaser.EarCut.sortLinked(p); +}; + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + +Phaser.EarCut.sortLinked = function (list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +}; + +// z-order of a point given coords and size of the data bounding box + +Phaser.EarCut.zOrder = function (x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +}; + +// find the leftmost node of a polygon ring + +Phaser.EarCut.getLeftmost = function (start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +}; + +// check if a point lies within a convex triangle + +Phaser.EarCut.pointInTriangle = function (ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +}; + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) + +Phaser.EarCut.isValidDiagonal = function (a, b) { + return Phaser.EarCut.equals(a, b) || a.next.i !== b.i && a.prev.i !== b.i && !Phaser.EarCut.intersectsPolygon(a, b) && + Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a) && Phaser.EarCut.middleInside(a, b); +}; + +// signed area of a triangle + +Phaser.EarCut.area = function (p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +}; + +// check if two points are equal + +Phaser.EarCut.equals = function (p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +}; + +// check if two segments intersect + +Phaser.EarCut.intersects = function (p1, q1, p2, q2) { + return Phaser.EarCut.area(p1, q1, p2) > 0 !== Phaser.EarCut.area(p1, q1, q2) > 0 && + Phaser.EarCut.area(p2, q2, p1) > 0 !== Phaser.EarCut.area(p2, q2, q1) > 0; +}; + +// check if a polygon diagonal intersects any polygon segments + +Phaser.EarCut.intersectsPolygon = function (a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + Phaser.EarCut.intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +}; + +// check if a polygon diagonal is locally inside the polygon + +Phaser.EarCut.locallyInside = function (a, b) { + return Phaser.EarCut.area(a.prev, a, a.next) < 0 ? + Phaser.EarCut.area(a, b, a.next) >= 0 && Phaser.EarCut.area(a, a.prev, b) >= 0 : + Phaser.EarCut.area(a, b, a.prev) < 0 || Phaser.EarCut.area(a, a.next, b) < 0; +}; + +// check if the middle point of a polygon diagonal is inside the polygon + +Phaser.EarCut.middleInside = function (a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +}; + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring + +Phaser.EarCut.splitPolygon = function (a, b) { + var a2 = new Phaser.EarCut.Node(a.i, a.x, a.y), + b2 = new Phaser.EarCut.Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +}; + +// create a node and optionally link it with previous one (in a circular doubly linked list) + +Phaser.EarCut.insertNode = function (i, x, y, last) { + var p = new Phaser.EarCut.Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +}; + +Phaser.EarCut.removeNode = function (p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +}; + +Phaser.EarCut.Node = function (i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +}; + +/* jshint ignore:end */ + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used by the webGL renderer to draw the primitive graphics data + * + * @class PIXI.WebGLGraphics + * @private + * @static + */ +PIXI.WebGLGraphics = function() +{ +}; + +/** + * The number of points beyond which Pixi swaps to using the Stencil Buffer to render the Graphics. + * + * @type {number} + */ +PIXI.WebGLGraphics.stencilBufferLimit = 6; + +/** + * Renders the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.renderGraphics + * @param graphics {Graphics} + * @param renderSession {Object} + */ +PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset) +{ + var gl = renderSession.gl; + var projection = renderSession.projection, + offset = renderSession.offset, + shader = renderSession.shaderManager.primitiveShader, + webGLData; + + if(graphics.dirty) + { + PIXI.WebGLGraphics.updateGraphics(graphics, gl); + } + + var webGL = graphics._webGL[gl.id]; + + // if the graphics object does not exist in the webGL context skip rendering! + if(!webGL) + { + return; + } + + // This could be speeded up for sure! + + for (var i = 0; i < webGL.data.length; i++) + { + if(webGL.data[i].mode === 1) + { + webGLData = webGL.data[i]; + + renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession); + + // render quad.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + renderSession.stencilManager.popStencil(graphics, webGLData, renderSession); + } + else + { + webGLData = webGL.data[i]; + + + renderSession.shaderManager.setShader( shader );//activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, 1); + + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + } + } +}; + +/** + * Updates the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.updateGraphics + * @param graphicsData {Graphics} The graphics object to update + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLGraphics.updateGraphics = function(graphics, gl) +{ + // get the contexts graphics object + var webGL = graphics._webGL[gl.id]; + // if the graphics object does not exist in the webGL context time to create it! + if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; + + // flag the graphics as not dirty as we are about to update it... + graphics.dirty = false; + + var i; + + // if the user cleared the graphics object we will need to clear every object + if(graphics.clearDirty) + { + graphics.clearDirty = false; + + // lop through and return all the webGLDatas to the object pool so than can be reused later on + for (i = 0; i < webGL.data.length; i++) + { + var graphicsData = webGL.data[i]; + graphicsData.reset(); + PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData ); + } + + // clear the array and reset the index.. + webGL.data = []; + webGL.lastIndex = 0; + } + + var webGLData; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + if (data.type === Phaser.POLYGON) + { + // need to add the points the the graphics object.. + data.points = data.shape.points.slice(); + if(data.shape.closed) + { + // close the poly if the value is true! + if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { + data.points.push(data.points[0], data.points[1]); + } + } + + // MAKE SURE WE HAVE THE CORRECT TYPE.. + if(data.fill) + { + if(data.points.length >= PIXI.WebGLGraphics.stencilBufferLimit) + { + if(data.points.length < PIXI.WebGLGraphics.stencilBufferLimit * 2) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData); + // console.log(canDrawUsingSimple); + + if(!canDrawUsingSimple) + { + // console.log("<>>>") + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + } + } + + if(data.lineWidth > 0) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + PIXI.WebGLGraphics.buildLine(data, webGLData); + + } + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + if (data.type === Phaser.RECTANGLE) + { + PIXI.WebGLGraphics.buildRectangle(data, webGLData); + } + else if (data.type === Phaser.CIRCLE || data.type === Phaser.ELLIPSE) + { + PIXI.WebGLGraphics.buildCircle(data, webGLData); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData); + } + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (i = 0; i < webGL.data.length; i++) + { + webGLData = webGL.data[i]; + if(webGLData.dirty)webGLData.upload(); + } +}; + +/** + * @static + * @private + * @method PIXI.WebGLGraphics.switchMode + * @param webGL {WebGLContext} + * @param type {Number} + */ +PIXI.WebGLGraphics.switchMode = function(webGL, type) +{ + var webGLData; + + if(!webGL.data.length) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + else + { + webGLData = webGL.data[webGL.data.length-1]; + + if(webGLData.mode !== type || type === 1) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + } + + webGLData.dirty = true; + + return webGLData; +}; + +/** + * Builds a rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData) +{ + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; + + // start + 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); + + // insert 2 dead triangles.. + 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; + } +}; + +/** + * Builds a rounded rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRoundedRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData) +{ + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + recPoints.push(x, y + radius); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); + + if (graphicsData.fill) { + var color = Phaser.Color.hexToRGBArray(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; + + var triangles = Phaser.EarCut.Triangulate(recPoints, null, 2); + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i+1] + vecPos); + indices.push(triangles[i+2] + vecPos); + indices.push(triangles[i+2] + vecPos); + } + + + for (i = 0; i < recPoints.length; i++) + { + verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @static + * @private + * @method PIXI.WebGLGraphics.quadraticBezierCurve + * @param fromX {Number} Origin point x + * @param fromY {Number} Origin point x + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Array(Number)} + */ +PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) { + + var xa, + ya, + xb, + yb, + x, + y, + n = 20, + points = []; + + function getPt(n1 , n2, perc) { + var diff = n2 - n1; + + return n1 + ( diff * perc ); + } + + var j = 0; + for (var i = 0; i <= n; i++ ) + { + j = i / n; + + // The Green Line + xa = getPt( fromX , cpX , j ); + ya = getPt( fromY , cpY , j ); + xb = getPt( cpX , toX , j ); + yb = getPt( cpY , toY , j ); + + // The Black Dot + x = getPt( xa , xb , j ); + y = getPt( ya , yb , j ); + + points.push(x, y); + } + return points; +}; + +/** + * Builds a circle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildCircle + * @param graphicsData {Graphics} The graphics object to draw + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData) +{ + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + + // TODO - bit hacky?? + if (graphicsData.type === Phaser.CIRCLE) + { + width = circleData.radius; + height = circleData.radius; + } + else + { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = 40; + var seg = (Math.PI * 2) / totalSegs ; + + var i = 0; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; i < totalSegs + 1 ; i++) + { + verts.push(x,y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos-1); + } + + if(graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (i = 0; i < totalSegs + 1; i++) + { + graphicsData.points.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height); + } + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Builds a line to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildLine + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData) +{ + // TODO OPTIMISE! + var i = 0; + var points = graphicsData.points; + if(points.length === 0)return; + + // if the line width is an odd number add 0.5 to align to a whole pixel + if(graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) { + points[i] += 0.5; + } + } + + // get first and last point.. figure out the middle! + var firstPoint = new PIXI.Point( points[0], points[1] ); + var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + // if the first point is the last point - gonna have issues :) + if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length/6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var px, py, p1x, p1y, p2x, p2y, p3x, p3y; + var perpx, perpy, perp2x, perp2y, perp3x, perp3y; + var a1, b1, c1, a2, b2, c2; + var denom, pdist, dist; + + p1x = points[0]; + p1y = points[1]; + + p2x = points[2]; + p2y = points[3]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx , p1y - perpy, + r, g, b, alpha); + + verts.push(p1x + perpx , p1y + perpy, + r, g, b, alpha); + + for (i = 1; i < length-1; i++) + { + p1x = points[(i-1)*2]; + p1y = points[(i-1)*2 + 1]; + + p2x = points[(i)*2]; + p2y = points[(i)*2 + 1]; + + p3x = points[(i+1)*2]; + p3y = points[(i+1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + a1 = (-perpy + p1y) - (-perpy + p2y); + b1 = (-perpx + p2x) - (-perpx + p1x); + c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + a2 = (-perp2y + p3y) - (-perp2y + p2y); + b2 = (-perp2x + p2x) - (-perp2x + p3x); + c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + denom = a1*b2 - a2*b1; + + if(Math.abs(denom) < 0.1 ) + { + + denom+=10.1; + verts.push(p2x - perpx , p2y - perpy, + r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy, + r, g, b, alpha); + + continue; + } + + px = (b1*c2 - b2*c1)/denom; + py = (a2*c1 - a1*c2)/denom; + + + pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); + + + if(pdist > 140 * 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 < indexCount; i++) + { + indices.push(indexStart++); + } + + indices.push(indexStart-1); +}; + +/** + * Builds a complex polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildComplexPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData) +{ + //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. + var points = graphicsData.points.slice(); + if(points.length < 6)return; + + // get first and last point.. figure out the middle! + var indices = webGLData.indices; + webGLData.points = points; + webGLData.alpha = graphicsData.fillAlpha; + webGLData.color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + + /* + calclate the bounds.. + */ + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + var x,y; + + // get size.. + for (var i = 0; i < points.length; i+=2) + { + x = points[i]; + y = points[i+1]; + + minX = x < minX ? x : minX; + maxX = x > maxX ? x : maxX; + + minY = y < minY ? y : minY; + maxY = y > maxY ? y : maxY; + } + + // add a quad to the end cos there is no point making another buffer! + points.push(minX, minY, + maxX, minY, + maxX, maxY, + minX, maxY); + + // push a quad onto the end.. + + //TODO - this aint needed! + var length = points.length / 2; + for (i = 0; i < length; i++) + { + indices.push( i ); + } + +}; + +/** + * Builds a polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData) +{ + var points = graphicsData.points; + + if(points.length < 6)return; + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = Phaser.EarCut.Triangulate(points, null, 2); + + if(!triangles)return false; + + var vertPos = verts.length / 6; + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i] + vertPos); + indices.push(triangles[i+1] + vertPos); + indices.push(triangles[i+2] +vertPos); + indices.push(triangles[i+2] + vertPos); + } + + for (i = 0; i < length; i++) + { + verts.push(points[i * 2], points[i * 2 + 1], + r, g, b, alpha); + } + + return true; +}; + +PIXI.WebGLGraphics.graphicsDataPool = []; + +/** + * @class WebGLGraphicsData + * @private + * @static + */ +PIXI.WebGLGraphicsData = function(gl) +{ + this.gl = gl; + + //TODO does this need to be split before uploding?? + this.color = [0,0,0]; // color split! + this.points = []; + this.indices = []; + this.buffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + this.mode = 1; + this.alpha = 1; + this.dirty = true; +}; + +/** + * @method PIXI.WebGLGraphics.reset + */ +PIXI.WebGLGraphicsData.prototype.reset = function() +{ + this.points = []; + this.indices = []; +}; + +/** + * @method PIXI.WebGLGraphics.upload + */ +PIXI.WebGLGraphicsData.prototype.upload = function() +{ + var gl = this.gl; + +// this.lastIndex = graphics.graphicsData.length; + this.glPoints = new Float32Array(this.points); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW); + + this.glIndicies = new Uint16Array(this.indices); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW); + + this.dirty = false; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + +/** + * A set of functions used by the canvas renderer to draw the primitive graphics data. + * + * @class PIXI.CanvasGraphics + * @static + */ +PIXI.CanvasGraphics = function() +{ +}; + +/** + * Renders a {@link Phaser.Graphics} object to a canvas. + * + * @method PIXI.CanvasGraphics.renderGraphics + * @static + * @param graphics {Graphics} the actual graphics object to render + * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas + */ +PIXI.CanvasGraphics.renderGraphics = function(graphics, context) +{ + var worldAlpha = graphics.worldAlpha; + + if (graphics.dirty) + { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === Phaser.POLYGON) + { + context.beginPath(); + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (shape.closed) + { + context.lineTo(points[0], points[1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.RECTANGLE) + { + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ELLIPSE) + { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + context.beginPath(); + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + +}; + +/** + * Renders a graphics mask + * + * @static + * @private + * @method PIXI.CanvasGraphics.renderGraphicsMask + * @param graphics {Graphics} the graphics which will be used as a mask + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + */ +PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context) +{ + var len = graphics.graphicsData.length; + + if (len === 0) + { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === Phaser.POLYGON) + { + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + } + else if (data.type === Phaser.RECTANGLE) + { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } + else if (data.type === Phaser.ELLIPSE) + { + + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } +}; + +PIXI.CanvasGraphics.updateGraphicsTint = function(graphics) +{ + if (graphics.tint === 0xFFFFFF) + { + return; + } + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF)/ 255; + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255); + data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255); + + } + +}; + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + * @param lineWidth {number} the width of the line to draw + * @param lineColor {number} the color of the line to draw + * @param lineAlpha {number} the alpha of the line to draw + * @param fillColor {number} the color of the fill + * @param fillAlpha {number} the alpha of the fill + * @param fill {boolean} whether or not the shape is filled with a colour + * @param shape {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + +Phaser.GraphicsData = function (lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { + + /* + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /* + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /* + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /* + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /* + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /* + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /* + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /* + * @member {boolean} whether or not the shape is filled with a color + */ + this.fill = fill; + + /* + * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + this.shape = shape; + + /* + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + +}; + +Phaser.GraphicsData.prototype.constructor = Phaser.GraphicsData; + +/** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {GraphicsData} + */ +Phaser.GraphicsData.prototype.clone = function () { + + return new Phaser.GraphicsData( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.fill, + this.shape + ); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, +* Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will +* be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: +* +* ```javascript +* graphics.beginFill(0xff0000); +* graphics.drawCircle(50, 50, 100); +* graphics.endFill(); +* ``` +* +* This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. +* +* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or +* WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the +* graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. +* +* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help +* performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. +* You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then +* you should avoid doing this, as it will constantly generate new textures, which will consume memory. +* +* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful +* in their complexity and quantity of them in your game. +* +* @class Phaser.Graphics +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - X position of the new graphics object. +* @param {number} [y=0] - Y position of the new graphics object. +*/ +Phaser.Graphics = function (game, x, y) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.GRAPHICS; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value. + * @private + */ + this.anchor = new Phaser.Point(); + + PIXI.DisplayObjectContainer.call(this); + + this.renderable = true; + + /** + * The alpha value used when filling the Graphics object. + * + * @property fillAlpha + * @type Number + */ + this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @property lineWidth + * @type Number + */ + this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @property lineColor + * @type String + * @default 0 + */ + this.lineColor = 0; + + /** + * Graphics data + * + * @property graphicsData + * @type Array + * @private + */ + this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF (Phaser.Color.WHITE) to reset the tint. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * Current path + * + * @property currentPath + * @type Object + * @private + */ + this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @property _webGL + * @type Array + * @private + */ + this._webGL = []; + + /** + * Whether this shape is being used as a mask. + * + * @property isMask + * @type Boolean + */ + this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @property boundsPadding + * @type Number + */ + this.boundsPadding = 0; + + this._localBounds = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property dirty + * @type Boolean + * @private + */ + this.dirty = true; + + /** + * Used to detect if the bounds have been invalidated, by this Graphics being cleared or drawn to. + * If this is set to true then the updateLocalBounds is called once in the postUpdate method. + * + * @property _boundsDirty + * @type Boolean + * @private + */ + this._boundsDirty = false; + + /** + * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property webGLDirty + * @type Boolean + * @private + */ + this.webGLDirty = false; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @property cachedSpriteDirty + * @type Boolean + * @private + */ + this.cachedSpriteDirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.Graphics.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Graphics.prototype.constructor = Phaser.Graphics; + +Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Graphics#preUpdate +*/ +Phaser.Graphics.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World +* +* @method Phaser.Graphics#postUpdate +*/ +Phaser.Graphics.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this._boundsDirty) + { + this.updateLocalBounds(); + this._boundsDirty = false; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Destroy this Graphics instance. +* +* @method Phaser.Graphics#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Graphics.prototype.destroy = function (destroyChildren) { + + this.clear(); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Draws a single {@link Phaser.Polygon} triangle from a {@link Phaser.Point} array +* +* @method Phaser.Graphics#drawTriangle +* @param {Array} points - An array of Phaser.Points that make up the three vertices of this triangle +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangle = function (points, cull) { + + if (cull === undefined) { cull = false; } + + var triangle = new Phaser.Polygon(points); + + if (cull) + { + var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y); + var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y); + var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y); + var faceNormal = cb.cross(ab); + + if (cameraToFace.dot(faceNormal) > 0) + { + this.drawPolygon(triangle); + } + } + else + { + this.drawPolygon(triangle); + } + +}; + +/** +* Draws {@link Phaser.Polygon} triangles +* +* @method Phaser.Graphics#drawTriangles +* @param {Array|Array} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles +* @param {Array} [indices=null] - An array of numbers that describe what order to draw the vertices in +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) { + + if (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 < vertices.length / 3; i++) + { + this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull); + } + } + else + { + for (i = 0; i < vertices.length / 6; i++) + { + point1.x = vertices[i * 6 + 0]; + point1.y = vertices[i * 6 + 1]; + point2.x = vertices[i * 6 + 2]; + point2.y = vertices[i * 6 + 3]; + point3.x = vertices[i * 6 + 4]; + point3.y = vertices[i * 6 + 5]; + this.drawTriangle([point1, point2, point3], cull); + } + } + } + else + { + if (vertices[0] instanceof Phaser.Point) + { + for (i = 0; i < indices.length /3; i++) + { + points.push(vertices[indices[i * 3 ]]); + points.push(vertices[indices[i * 3 + 1]]); + points.push(vertices[indices[i * 3 + 2]]); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + else + { + for (i = 0; i < indices.length; i++) + { + point1.x = vertices[indices[i] * 2]; + point1.y = vertices[indices[i] * 2 + 1]; + points.push(point1.copyTo({})); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + } +}; + +/** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. + * + * @method Phaser.Graphics#lineStyle + * @param lineWidth {Number} width of the line to draw, will update the objects stored style + * @param color {Number} color of the line to draw, will update the objects stored style + * @param alpha {Number} alpha of the line to draw, will update the objects stored style + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { + + this.lineWidth = lineWidth || 0; + this.lineColor = color || 0; + this.lineAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { + // halfway through a line? start a new one! + this.drawShape(new Phaser.Polygon(this.currentPath.shape.points.slice(-2))); + } + else + { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + +}; + +/** + * Moves the current drawing position to x, y. + * + * @method Phaser.Graphics#moveTo + * @param x {Number} the X coordinate to move to + * @param y {Number} the Y coordinate to move to + * @return {Graphics} + */ +Phaser.Graphics.prototype.moveTo = function (x, y) { + + this.drawShape(new Phaser.Polygon([ x, y ])); + + return this; + +}; + +/** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @method Phaser.Graphics#lineTo + * @param x {Number} the X coordinate to draw to + * @param y {Number} the Y coordinate to draw to + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineTo = function (x, y) { + + if (!this.currentPath) + { + this.moveTo(0, 0); + } + + this.currentPath.shape.points.push(x, y); + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @method Phaser.Graphics#quadraticCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [ 0, 0 ]; + } + } + else + { + this.moveTo(0,0); + } + + var xa, + ya, + n = 20, + points = this.currentPath.shape.points; + + if (points.length === 0) + { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var j = 0; + for (var i = 1; i <= n; ++i) + { + j = i / n; + + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + + points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), + ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a bezier curve and then draws it. + * + * @method Phaser.Graphics#bezierCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param cpX2 {Number} Second Control point x + * @param cpY2 {Number} Second Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + var n = 20, + dt, + dt2, + dt3, + t2, + t3, + points = this.currentPath.shape.points; + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + var j = 0; + + for (var i = 1; i <= n; ++i) + { + j = i / n; + + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, + dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @method Phaser.Graphics#arcTo + * @param x1 {Number} The x-coordinate of the beginning of the arc + * @param y1 {Number} The y-coordinate of the beginning of the arc + * @param x2 {Number} The x-coordinate of the end of the arc + * @param y2 {Number} The y-coordinate of the end of the arc + * @param radius {Number} The radius of the arc + * @return {Graphics} + */ +Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points.push(x1, y1); + } + } + else + { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points, + fromX = points[points.length-2], + fromY = points[points.length-1], + a1 = fromY - y1, + b1 = fromX - x1, + a2 = y2 - y1, + b2 = x2 - x1, + mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { + points.push(x1, y1); + } + } + else + { + var dd = a1 * a1 + b1 * b1, + cc = a2 * a2 + b2 * b2, + tt = a1 * a2 + b1 * b2, + k1 = radius * Math.sqrt(dd) / mm, + k2 = radius * Math.sqrt(cc) / mm, + j1 = k1 * tt / dd, + j2 = k2 * tt / cc, + cx = k1 * b2 + k2 * b1, + cy = k1 * a2 + k2 * a1, + px = b1 * (k2 + j1), + py = a1 * (k2 + j1), + qx = b2 * (k1 + j2), + qy = a2 * (k1 + j2), + startAngle = Math.atan2(py - cy, px - cx), + endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @method Phaser.Graphics#arc + * @param cx {Number} The x-coordinate of the center of the circle + * @param cy {Number} The y-coordinate of the center of the circle + * @param radius {Number} The radius of the circle + * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) + * @param endAngle {Number} The ending angle, in radians + * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. + * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. + * @return {Graphics} + */ +Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise, segments) { + + // If we do this we can never draw a full circle + if (startAngle === endAngle) + { + return this; + } + + if (anticlockwise === undefined) { anticlockwise = false; } + if (segments === undefined) { segments = 40; } + + if (!anticlockwise && endAngle <= startAngle) + { + endAngle += Math.PI * 2; + } + else if (anticlockwise && startAngle <= endAngle) + { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments; + + // Sweep check - moved here because we don't want to do the moveTo below if the arc fails + if (sweep === 0) + { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (anticlockwise && this.filling) + { + this.moveTo(cx, cy); + } + else + { + this.moveTo(startX, startY); + } + + // currentPath will always exist after calling a moveTo + var points = this.currentPath.shape.points; + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = (segMinus % 1) / segMinus; + + for (var i = 0; i <= segMinus; i++) + { + var real = i + remainder * i; + + var angle = ((theta) + startAngle + (theta2 * real)); + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, + ( (cTheta * -s) + (sTheta * c) ) * radius + cy); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @method Phaser.Graphics#beginFill + * @param color {Number} the color of the fill + * @param alpha {Number} the alpha of the fill + * @return {Graphics} + */ +Phaser.Graphics.prototype.beginFill = function (color, alpha) { + + this.filling = true; + this.fillColor = color || 0; + this.fillAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + +}; + +/** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @method Phaser.Graphics#endFill + * @return {Graphics} + */ +Phaser.Graphics.prototype.endFill = function () { + + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRect + * + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawRect = function (x, y, width, height) { + + this.drawShape(new Phaser.Rectangle(x, y, width, height)); + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRoundedRect + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. + */ +Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + + this.drawShape(new Phaser.RoundedRectangle(x, y, width, height, radius)); + + return this; + +}; + +/** + * Draws a circle. + * + * @method Phaser.Graphics#drawCircle + * @param x {Number} The X coordinate of the center of the circle + * @param y {Number} The Y coordinate of the center of the circle + * @param diameter {Number} The diameter of the circle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) { + + this.drawShape(new Phaser.Circle(x, y, diameter)); + + return this; + +}; + +/** + * Draws an ellipse. + * + * @method Phaser.Graphics#drawEllipse + * @param x {Number} The X coordinate of the center of the ellipse + * @param y {Number} The Y coordinate of the center of the ellipse + * @param width {Number} The half width of the ellipse + * @param height {Number} The half height of the ellipse + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawEllipse = function (x, y, width, height) { + + this.drawShape(new Phaser.Ellipse(x, y, width, height)); + + return this; + +}; + +/** + * Draws a polygon using the given path. + * + * @method Phaser.Graphics#drawPolygon + * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawPolygon = function (path) { + + if (path instanceof Phaser.Polygon) + { + path = path.points; + } + + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) + { + points[i] = arguments[i]; + } + } + + this.drawShape(new Phaser.Polygon(points)); + + return this; + +}; + +/** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @method Phaser.Graphics#clear + * @return {Graphics} + */ +Phaser.Graphics.prototype.clear = function () { + + this.lineWidth = 0; + this.filling = false; + + this.dirty = true; + this._boundsDirty = true; + this.clearDirty = true; + this.graphicsData = []; + + this.updateLocalBounds(); + + return this; + +}; + +/** + * Useful function that returns a texture of the graphics object that can then be used to create sprites + * This can be quite useful if your geometry is complicated and needs to be reused multiple times. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * @method Phaser.Graphics#generateTexture + * @param [resolution=1] {Number} The resolution of the texture being generated + * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts + * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0) + * @return {Texture} a texture of the graphics object + */ +Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, padding) { + + if (resolution === undefined) { resolution = 1; } + if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; } + if (padding === undefined) { padding = 0; } + + var bounds = this.getBounds(); + + bounds.width += padding; + bounds.height += padding; + + var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution); + + var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + + canvasBuffer.context.scale(resolution, resolution); + + canvasBuffer.context.translate(-bounds.x, -bounds.y); + + PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context); + + return texture; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Graphics#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderWebGL = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture on the gpu too! + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.worldAlpha = this.worldAlpha; + + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + + return; + } + else + { + renderSession.spriteBatch.stop(); + renderSession.blendModeManager.setBlendMode(this.blendMode); + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + if (this._filters) + { + renderSession.filterManager.pushFilter(this._filterBlock); + } + + // check blend mode + if (this.blendMode !== renderSession.spriteBatch.currentBlendMode) + { + renderSession.spriteBatch.currentBlendMode = this.blendMode; + var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode]; + renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + // check if the webgl graphic needs to be updated + if (this.webGLDirty) + { + this.dirty = true; + this.webGLDirty = false; + } + + PIXI.WebGLGraphics.renderGraphics(this, renderSession); + + // only render if it has children! + if (this.children.length) + { + renderSession.spriteBatch.start(); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + } + + if (this._filters) + { + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + renderSession.maskManager.popMask(this.mask, renderSession); + } + + renderSession.drawCount++; + + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method Phaser.Graphics#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderCanvas = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) + { + this.dirty = true; + this._prevTint = this.tint; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.alpha = this.alpha; + + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + + return; + } + else + { + var context = renderSession.context; + var transform = this.worldTransform; + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + var resolution = renderSession.resolution; + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + tx, + ty); + + PIXI.CanvasGraphics.renderGraphics(this, context); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + } + +}; + +/** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @method Phaser.Graphics#getBounds + * @return {Rectangle} the rectangular bounding area + */ +Phaser.Graphics.prototype.getBounds = function (matrix) { + + if (this._currentBounds) + { + return this._currentBounds; + } + + // Return an empty object if the item is a mask! + if (!this.renderable) + { + return Phaser.EmptyRectangle; + } + + if (this.dirty) + { + this.updateLocalBounds(); + this.webGLDirty = true; + this.cachedSpriteDirty = true; + this.dirty = false; + } + + var bounds = this._localBounds; + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = x1; + var maxY = y1; + + var minX = x1; + var minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + + this._bounds.x = minX; + this._bounds.width = maxX - minX; + + this._bounds.y = minY; + this._bounds.height = maxY - minY; + + this._currentBounds = this._bounds; + + return this._currentBounds; + +}; + +/** + * Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration. + * + * @method Phaser.Graphics#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +Phaser.Graphics.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Tests if a point is inside this graphics object +* +* @param point {Point} the point to test +* @return {boolean} the result of the test +*/ +Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) { + + if (tempPoint === undefined) { tempPoint = new Phaser.Point(); } + + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; i++) + { + var data = graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // only deal with fills.. + if (data.shape) + { + if (data.shape.contains(tempPoint.x, tempPoint.y)) + { + return true; + } + } + } + + return false; + +}; + +/** + * Update the bounds of the object + * + * @method Phaser.Graphics#updateLocalBounds + */ +Phaser.Graphics.prototype.updateLocalBounds = function () { + + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) + { + var shape, points, x, y, w, h; + + for (var i = 0; i < this.graphicsData.length; i++) + { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + shape = data.shape; + + if (type === Phaser.RECTANGLE || type === Phaser.ROUNDEDRECTANGLE) + { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.CIRCLE) + { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.ELLIPSE) + { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else + { + // POLY - assumes points are sequential, not Point objects + points = shape.points; + + for (var j = 0; j < points.length; j++) + { + if (points[j] instanceof Phaser.Point) + { + x = points[j].x; + y = points[j].y; + } + else + { + x = points[j]; + y = points[j + 1]; + + if (j < points.length - 1) + { + j++; + } + } + + minX = x - lineWidth < minX ? x - lineWidth : minX; + maxX = x + lineWidth > maxX ? x + lineWidth : maxX; + + minY = y - lineWidth < minY ? y - lineWidth : minY; + maxY = y + lineWidth > maxY ? y + lineWidth : maxY; + } + } + } + } + else + { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.x = minX - padding; + this._localBounds.width = (maxX - minX) + padding * 2; + + this._localBounds.y = minY - padding; + this._localBounds.height = (maxY - minY) + padding * 2; + +}; + +/** + * Generates the cached sprite when the sprite has cacheAsBitmap = true + * + * @method Phaser.Graphics#_generateCachedSprite + * @private + */ +Phaser.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); + } + + // leverage the anchor to account for the offset of the element + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + // this._cachedSprite.buffer.context.save(); + this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y); + + // make sure we set the alpha of the graphics to 1 for the render.. + this.worldAlpha = 1; + + // now render the graphic.. + PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context); + this._cachedSprite.alpha = this.alpha; + +}; + +/** + * Updates texture size based on canvas size + * + * @method Phaser.Graphics#updateCachedSpriteTexture + * @private + */ +Phaser.Graphics.prototype.updateCachedSpriteTexture = function () { + + var cachedSprite = this._cachedSprite; + var texture = cachedSprite.texture; + var canvas = cachedSprite.buffer.canvas; + + texture.baseTexture.width = canvas.width; + texture.baseTexture.height = canvas.height; + texture.crop.width = texture.frame.width = canvas.width; + texture.crop.height = texture.frame.height = canvas.height; + + cachedSprite._width = canvas.width; + cachedSprite._height = canvas.height; + + // update the dirty base textures + texture.baseTexture.dirty(); + +}; + +/** + * Destroys a previous cached sprite. + * + * @method Phaser.Graphics#destroyCachedSprite + */ +Phaser.Graphics.prototype.destroyCachedSprite = function () { + + this._cachedSprite.texture.destroy(true); + this._cachedSprite = null; + +}; + +/** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @method Phaser.Graphics#drawShape + * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. + * @return {GraphicsData} The generated GraphicsData object. + */ +Phaser.Graphics.prototype.drawShape = function (shape) { + + if (this.currentPath) + { + // check current path! + if (this.currentPath.shape.points.length <= 2) + { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + // Handle mixed-type polygons + if (shape instanceof Phaser.Polygon) + { + shape = shape.clone(); + shape.flatten(); + } + + var data = new Phaser.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === Phaser.POLYGON) + { + data.shape.closed = this.filling; + this.currentPath = data; + } + + this.dirty = true; + this._boundsDirty = true; + + return data; + +}; + +/** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory. + * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas. + * This is not recommended if you are constantly redrawing the graphics element. + * + * @property cacheAsBitmap + * @type Boolean + * @default false + * @private + */ +Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + this._cacheAsBitmap = value; + + if (this._cacheAsBitmap) + { + this._generateCachedSprite(); + } + else + { + this.destroyCachedSprite(); + } + + this.dirty = true; + this.webGLDirty = true; + + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and +* render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. +* +* @class Phaser.RenderTexture +* @constructor +* @extends PIXI.Texture +* @param {Phaser.Game} game - Current game instance. +* @param {number} [width=100] - The width of the render texture. +* @param {number} [height=100] - The height of the render texture. +* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there. +* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts. +* @param {number} [resolution=1] - The resolution of the texture being generated. +*/ +Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution, renderer, textureUnit) { + + if (width === undefined) { width = 100; } + if (height === undefined) { height = 100; } + if (key === undefined) { key = ''; } + if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; } + if (resolution === undefined) { resolution = 1; } + if (renderer === undefined) { renderer = PIXI.defaultRenderer; } + if (textureUnit === undefined) { textureUnit = 0; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the RenderTexture in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RENDERTEXTURE; + + /** + * @property {Phaser.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture. + * @private + */ + this._tempMatrix = new Phaser.Matrix(); + + this.width = width; + this.height = height; + this.resolution = resolution; + + this.frame = new Phaser.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); + + this.crop = this.frame.clone(); + + /** + * The base texture object that this texture uses + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = new PIXI.BaseTexture(); + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + this.baseTexture._glTextures = []; + this.baseTexture.resolution = this.resolution; + + this.baseTexture.scaleMode = scaleMode; + + this.baseTexture.hasLoaded = true; + + PIXI.Texture.call(this, this.baseTexture, this.frame.clone()); + + /** + * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. + * + * @property renderer + * @type CanvasRenderer|WebGLRenderer + */ + this.renderer = renderer; + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + this.baseTexture.textureIndex = textureUnit; + this.baseTexture._dirty[gl.id] = false; + + this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode, textureUnit); + this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; + + this.projection = new Phaser.Point(this.width * 0.5, -this.height * 0.5); + } + else + { + this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution); + this.baseTexture.source = this.textureBuffer.canvas; + } + + /** + * @property valid + * @type Boolean + */ + this.valid = true; + + this.tempMatrix = new Phaser.Matrix(); + + this._updateUvs(); + +}; + +Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype); +Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it takes into account scale and rotation. +* +* If you don't want those then use RenderTexture.renderRawXY instead. +* +* @method Phaser.RenderTexture.prototype.renderXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) { + + displayObject.updateTransform(); + + this._tempMatrix.copyFrom(displayObject.worldTransform); + this._tempMatrix.tx = x; + this._tempMatrix.ty = y; + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it doesn't take into account scale, rotation or translation. +* +* If you need those then use RenderTexture.renderXY instead. +* +* @method Phaser.RenderTexture.prototype.renderRawXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) { + + this._tempMatrix.identity().translate(x, y); + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture. +* +* In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. +* This is now a Matrix allowing you much more control over how the Display Object is rendered. +* If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. +* +* If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either +* pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. +* +* @method Phaser.RenderTexture.prototype.render +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) { + + if (matrix === undefined || matrix === null) + { + this._tempMatrix.copyFrom(displayObject.worldTransform); + } + else + { + this._tempMatrix.copyFrom(matrix); + } + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* Resizes the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.resize +* @param {number} width - The width to resize to. +* @param {number} height - The height to resize to. +* @param {boolean} updateBase - Should the baseTexture.width and height values be resized as well? +*/ +Phaser.RenderTexture.prototype.resize = function (width, height, updateBase) { + + if (width === this.width && height === this.height) + { + return; + } + + this.valid = (width > 0 && height > 0); + + this.width = width; + this.height = height; + this.frame.width = this.crop.width = width * this.resolution; + this.frame.height = this.crop.height = height * this.resolution; + + if (updateBase) + { + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.projection.x = this.width / 2; + this.projection.y = -this.height / 2; + } + + if (!this.valid) + { + return; + } + + this.textureBuffer.resize(this.width, this.height); + +}; + +/** +* Clears the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.clear +*/ +Phaser.RenderTexture.prototype.clear = function () { + + if (!this.valid) + { + return; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + } + + this.textureBuffer.clear(); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderWebGL +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +* @private +*/ +Phaser.RenderTexture.prototype._renderWebGL = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + wt.translate(0, this.projection.y * 2); + + if (matrix) + { + wt.append(matrix); + } + + wt.scale(1, -1); + + // Time to update all the children of the displayObject with the new matrix. + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + // Time for the webGL fun stuff! + var gl = this.renderer.gl; + + gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + + if (clear) + { + this.textureBuffer.clear(); + } + + this.renderer.spriteBatch.dirty = true; + + this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix); + + this.renderer.spriteBatch.dirty = true; + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderCanvas +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +*/ +Phaser.RenderTexture.prototype._renderCanvas = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + + if (matrix) + { + wt.append(matrix); + } + + // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!) + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + if (clear) + { + this.textureBuffer.clear(); + } + + var realResolution = this.renderer.resolution; + + this.renderer.resolution = this.resolution; + + this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix); + + this.renderer.resolution = realResolution; + +}; + +/** +* Will return a HTML Image of the texture +* +* @method Phaser.RenderTexture.prototype.getImage +* @return {Image} +*/ +Phaser.RenderTexture.prototype.getImage = function () { + + var image = new Image(); + image.src = this.getBase64(); + + return image; + +}; + +/** +* Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. +* +* @method Phaser.RenderTexture.prototype.getBase64 +* @return {String} A base64 encoded string of the texture. +*/ +Phaser.RenderTexture.prototype.getBase64 = function () { + + return this.getCanvas().toDataURL(); + +}; + +/** +* Creates a Canvas element, renders this RenderTexture to it and then returns it. +* +* @method Phaser.RenderTexture.prototype.getCanvas +* @return {HTMLCanvasElement} A Canvas element with the texture rendered on. +*/ +Phaser.RenderTexture.prototype.getCanvas = function () { + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + var width = this.textureBuffer.width; + var height = this.textureBuffer.height; + + var webGLPixels = new Uint8Array(4 * width * height); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + var tempCanvas = new PIXI.CanvasBuffer(width, height); + var canvasData = tempCanvas.context.getImageData(0, 0, width, height); + canvasData.data.set(webGLPixels); + + tempCanvas.context.putImageData(canvasData, 0, 0); + + return tempCanvas.canvas; + } + else + { + return this.textureBuffer.canvas; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new game object for displaying Text. +* +* This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. +* Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. +* +* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers. +* +* @class Phaser.Text +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {number} x - X position of the new text object. +* @param {number} y - Y position of the new text object. +* @param {string} text - The actual text that will be written. +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +*/ +Phaser.Text = function (game, x, y, text, style) { + + x = x || 0; + y = y || 0; + + if (text === undefined || text === null) + { + text = ''; + } + else + { + text = text.toString(); + } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.TEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. + * @property {Phaser.Point} padding + */ + this.padding = new Phaser.Point(); + + /** + * The textBounds property allows you to specify a rectangular region upon which text alignment is based. + * See `Text.setTextBounds` for more details. + * @property {Phaser.Rectangle} textBounds + * @readOnly + */ + this.textBounds = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. + */ + this.canvas = Phaser.CanvasPool.create(this); + + /** + * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. + */ + this.context = this.canvas.getContext('2d'); + + /** + * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}. + */ + this.colors = []; + + /** + * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}. + */ + this.strokeColors = []; + + /** + * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}. + */ + this.fontStyles = []; + + /** + * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}. + */ + this.fontWeights = []; + + /** + * Should the linePositionX and Y values be automatically rounded before rendering the Text? + * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. + * @property {boolean} autoRound + * @default + */ + this.autoRound = false; + + /** + * Will this Text object use Basic or Advanced Word Wrapping? + * + * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. + * White space is condensed (e.g., consecutive spaces are replaced with one). + * Lines are trimmed of white space before processing. + * + * It throws an error if wordWrapWidth is less than a single character. + * @property {boolean} useAdvancedWrap + * @default + */ + this.useAdvancedWrap = false; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + * @property {Object} splitRegExp + */ + this.splitRegExp = /(?:\r\n|\r|\n)/; + + + /** The maximum number of characters that can be set. + * @property {number} characterLimitSize + */ + this.characterLimitSize = -1; + + /** The suffix that is applied to truncated text that is longer than the + * characterLimitSize. + * @property {string} characterLimitSuffix + */ + this.characterLimitSuffix = ''; + + /** + * @property {number} _res - Internal canvas resolution var. + * @private + */ + this._res = game.renderer.resolution; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text; + + /** + * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`. + * @private + */ + this._fontComponents = null; + + /** + * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. + * @private + */ + this._lineSpacing = 0; + + /** + * @property {number} _charCount - Internal character counter used by the text coloring. + * @private + */ + this._charCount = 0; + + /** + * @property {number} _width - Internal width var. + * @private + */ + this._width = 0; + + /** + * @property {number} _height - Internal height var. + * @private + */ + this._height = 0; + + Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas)); + + /** + * @property {object} style + * @private + */ + this.style = {}; + + this.setStyle(style || {}); + + if (text !== '') + { + this.updateText(); + } + +}; + +Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Text.prototype.constructor = Phaser.Text; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Text#preUpdate +* @protected +*/ +Phaser.Text.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override this function to handle any special update requirements. +* +* @method Phaser.Text#update +* @protected +*/ +Phaser.Text.prototype.update = function() { + +}; + +/** +* Destroy this Text object, removing it from the group it belongs to. +* +* @method Phaser.Text#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Text.prototype.destroy = function (destroyChildren) { + + this.texture.destroy(true); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. +* The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. +* The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. +* To remove a shadow already in place you can call this method with no parameters set. +* +* @method Phaser.Text#setShadow +* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +* @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. +* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +* @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set). +* @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; } + if (blur === undefined) { blur = 0; } + if (shadowStroke === undefined) { shadowStroke = true; } + if (shadowFill === undefined) { shadowFill = true; } + + this.style.shadowOffsetX = x; + this.style.shadowOffsetY = y; + this.style.shadowColor = color; + this.style.shadowBlur = blur; + this.style.shadowStroke = shadowStroke; + this.style.shadowFill = shadowFill; + this.dirty = true; + + return this; + +}; + +/** +* Set the style of the text by passing a single style object to it. +* +* @method Phaser.Text#setStyle +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +* @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setStyle = function (style, update) { + + if (update === undefined) { update = false; } + + var newStyle = Object.assign({}, style); + newStyle.font = style.font || 'bold 20pt Arial'; + newStyle.backgroundColor = style.backgroundColor || null; + newStyle.fill = style.fill || 'black'; + newStyle.align = (style.align || 'left').toLowerCase(); + newStyle.boundsAlignH = (style.boundsAlignH || 'left').toLowerCase(); + newStyle.boundsAlignV = (style.boundsAlignV || 'top').toLowerCase(); + newStyle.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136 + newStyle.strokeThickness = Number(style.strokeThickness) || 0; + newStyle.wordWrap = style.wordWrap || false; + newStyle.wordWrapWidth = style.wordWrapWidth || 100; + newStyle.maxLines = style.maxLines || 0; + newStyle.shadowOffsetX = style.shadowOffsetX || 0; + newStyle.shadowOffsetY = style.shadowOffsetY || 0; + newStyle.shadowColor = style.shadowColor || 'rgba(0,0,0,0)'; + newStyle.shadowBlur = style.shadowBlur || 0; + newStyle.tabs = style.tabs || 0; + + var components = this.fontToComponents(newStyle.font); + + if (newStyle.fontStyle) + { + components.fontStyle = newStyle.fontStyle; + } + + if (newStyle.fontVariant) + { + components.fontVariant = newStyle.fontVariant; + } + + if (newStyle.fontWeight) + { + components.fontWeight = newStyle.fontWeight; + } + + if (newStyle.fontSize) + { + if (typeof newStyle.fontSize === 'number') + { + newStyle.fontSize = newStyle.fontSize + 'px'; + } + + components.fontSize = newStyle.fontSize; + } + + this._fontComponents = components; + + newStyle.font = this.componentsToFont(this._fontComponents); + + this.style = newStyle; + this.dirty = true; + + if (update) + { + this.updateText(); + } + + return this; + +}; + +/** +* Renders text to the internal canvas. +* +* @method Phaser.Text#updateText +* @private +*/ +Phaser.Text.prototype.updateText = function () { + + this.texture.baseTexture.resolution = this._res; + + this.context.font = this.style.font; + + var outputText = this.text; + + if (this.characterLimitSize > -1 && this.characterLimitSize < outputText.length) { + outputText = this.text.substring(0, this.characterLimitSize) + this.characterLimitSuffix; + } + + if (this.style.wordWrap) + { + outputText = this.runWordWrap(this.text); + } + + // Split text into lines + var lines = outputText.split(this.splitRegExp); + + // Calculate text width + var tabs = this.style.tabs; + var lineWidths = []; + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this.style.font); + + var drawnLines = lines.length; + + if (this.style.maxLines > 0 && this.style.maxLines < lines.length) + { + drawnLines = this.style.maxLines; + } + + this._charCount = 0; + + for (var i = 0; i < drawnLines; i++) + { + if (tabs === 0) + { + // Simple layout (no tabs) + var lineWidth = this.style.strokeThickness + this.padding.x; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(lines[i]); + } + else + { + lineWidth += this.context.measureText(lines[i]).width; + } + + // Adjust for wrapped text + if (this.style.wordWrap) + { + lineWidth -= this.context.measureText(' ').width; + } + } + else + { + // Complex layout (tabs) + var line = lines[i].split(/(?:\t)/); + var lineWidth = this.padding.x + this.style.strokeThickness; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < line.length; c++) + { + var section = 0; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + section = this.measureLine(line[c]); + } + else + { + section = Math.ceil(this.context.measureText(line[c]).width); + } + + if (c > 0) + { + tab += tabs[c - 1]; + } + + lineWidth = tab + section; + } + } + else + { + for (var c = 0; c < line.length; c++) + { + // How far to the next tab? + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(line[c]); + } + else + { + lineWidth += Math.ceil(this.context.measureText(line[c]).width); + } + + var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth; + + lineWidth += diff; + } + } + } + + lineWidths[i] = Math.ceil(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); + } + + this.canvas.width = maxLineWidth * this._res; + + // Calculate text height + var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y; + var height = lineHeight * drawnLines; + var lineSpacing = this._lineSpacing; + + if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight) + { + lineSpacing = -lineHeight; + } + + // Adjust for line spacing + if (lineSpacing !== 0) + { + height += (lineSpacing > 0) ? lineSpacing * lines.length : lineSpacing * (lines.length - 1); + } + + this.canvas.height = height * this._res; + + this.context.scale(this._res, this._res); + + if (navigator.isCocoonJS) + { + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + } + + if (this.style.backgroundColor) + { + this.context.fillStyle = this.style.backgroundColor; + this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); + } + + this.context.fillStyle = this.style.fill; + this.context.font = this.style.font; + this.context.strokeStyle = this.style.stroke; + this.context.textBaseline = 'alphabetic'; + + this.context.lineWidth = this.style.strokeThickness; + this.context.lineCap = 'round'; + this.context.lineJoin = 'round'; + + var linePositionX; + var linePositionY; + + this._charCount = 0; + + // Draw text line by line + for (i = 0; i < drawnLines; i++) + { + // Split the line by + + linePositionX = this.style.strokeThickness / 2; + linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (i > 0) + { + linePositionY += (lineSpacing * i); + } + + if (this.style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (this.style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (this.autoRound) + { + linePositionX = Math.round(linePositionX); + linePositionY = Math.round(linePositionY); + } + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + this.updateLine(lines[i], linePositionX, linePositionY); + } + else + { + if (this.style.stroke && this.style.strokeThickness) + { + this.updateShadow(this.style.shadowStroke); + + if (tabs === 0) + { + this.context.strokeText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, false); + } + } + + if (this.style.fill) + { + this.updateShadow(this.style.shadowFill); + + if (tabs === 0) + { + this.context.fillText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, true); + } + } + } + } + + this.updateTexture(); + + this.dirty = false; + +}; + +/** +* Renders a line of text that contains tab characters if Text.tab > 0. +* Called automatically by updateText. +* +* @method Phaser.Text#renderTabLine +* @private +* @param {string} line - The line of text to render. +* @param {integer} x - The x position to start rendering from. +* @param {integer} y - The y position to start rendering from. +* @param {boolean} fill - If true uses fillText, if false uses strokeText. +*/ +Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) { + + var text = line.split(/(?:\t)/); + var tabs = this.style.tabs; + var snap = 0; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < text.length; c++) + { + if (c > 0) + { + tab += tabs[c - 1]; + } + + snap = x + tab; + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + } + } + else + { + for (var c = 0; c < text.length; c++) + { + var section = Math.ceil(this.context.measureText(text[c]).width); + + // How far to the next tab? + snap = this.game.math.snapToCeil(x, tabs); + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + + x = snap + section; + } + } + +}; + +/** +* Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. +* This is called automatically by Text.updateText. +* +* @method Phaser.Text#updateShadow +* @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero. +*/ +Phaser.Text.prototype.updateShadow = function (state) { + + if (state) + { + this.context.shadowOffsetX = this.style.shadowOffsetX; + this.context.shadowOffsetY = this.style.shadowOffsetY; + this.context.shadowColor = this.style.shadowColor; + this.context.shadowBlur = this.style.shadowBlur; + } + else + { + this.context.shadowOffsetX = 0; + this.context.shadowOffsetY = 0; + this.context.shadowColor = 0; + this.context.shadowBlur = 0; + } + +}; + +/** +* Measures a line of text character by character taking into the account the specified character styles. +* +* @method Phaser.Text#measureLine +* @private +* @param {string} line - The line of text to measure. +* @return {integer} length of the line. +*/ +Phaser.Text.prototype.measureLine = function (line) { + + var lineLength = 0; + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + } + + lineLength += this.context.measureText(letter).width; + + this._charCount++; + } + + return Math.ceil(lineLength); +}; + +/** +* Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable. +* +* @method Phaser.Text#updateLine +* @private +*/ +Phaser.Text.prototype.updateLine = function (line, x, y) { + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + this.context.strokeText(letter, x, y); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + this.context.fillText(letter, x, y); + } + + x += this.context.measureText(letter).width; + + this._charCount++; + } + +}; + +/** +* Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. +* +* @method Phaser.Text#clearColors +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearColors = function () { + + this.colors = []; + this.strokeColors = []; + this.dirty = true; + + return this; + +}; + +/** +* Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. +* +* @method Phaser.Text#clearFontValues +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearFontValues = function () { + + this.fontStyles = []; + this.fontWeights = []; + this.dirty = true; + + return this; + +}; + +/** +* Set specific colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* If you wish to change the stroke color see addStrokeColor instead. +* +* @method Phaser.Text#addColor +* @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addColor = function (color, position) { + + this.colors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific stroke colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* This has no effect if stroke is disabled or has a thickness of 0. +* +* If you wish to change the text fill color see addColor instead. +* +* @method Phaser.Text#addStrokeColor +* @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addStrokeColor = function (color, position) { + + this.strokeColors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font styles for certain characters within the Text. +* +* It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. +* The position value is the index of the character in the Text string to start applying this font style to. +* Once set the font style remains in use until either another font style or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. +* +* If you wish to change the text font weight see addFontWeight instead. +* +* @method Phaser.Text#addFontStyle +* @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. +* @param {number} position - The index of the character in the string to start applying this font style value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontStyle = function (style, position) { + + this.fontStyles[position] = style; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font weights for certain characters within the Text. +* +* It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. +* The position value is the index of the character in the Text string to start applying this font weight to. +* Once set the font weight remains in use until either another font weight or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. +* +* If you wish to change the text font style see addFontStyle instead. +* +* @method Phaser.Text#addFontWeight +* @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. +* @param {number} position - The index of the character in the string to start applying this font weight value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontWeight = function (weight, position) { + + this.fontWeights[position] = weight; + this.dirty = true; + + return this; + +}; + +/** +* Runs the given text through the Text.runWordWrap function and returns +* the results as an array, where each element of the array corresponds to a wrapped +* line of text. +* +* Useful if you wish to control pagination on long pieces of content. +* +* @method Phaser.Text#precalculateWordWrap +* @param {string} text - The text for which the wrapping will be calculated. +* @return {array} An array of strings with the pieces of wrapped text. +*/ +Phaser.Text.prototype.precalculateWordWrap = function (text) { + + this.texture.baseTexture.resolution = this._res; + this.context.font = this.style.font; + + var wrappedLines = this.runWordWrap(text); + + return wrappedLines.split(/(?:\r\n|\r|\n)/); + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#runWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.runWordWrap = function (text) { + + if (this.useAdvancedWrap) + { + return this.advancedWordWrap(text); + } + else + { + return this.basicWordWrap(text); + } + +}; + +/** +* Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* White space is condensed (e.g., consecutive spaces are replaced with one). +* Lines are trimmed of white space before processing. +* Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character. +* +* @method Phaser.Text#advancedWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.advancedWordWrap = function (text) { + + var context = this.context; + var wordWrapWidth = this.style.wordWrapWidth; + + var output = ''; + + // (1) condense whitespace + // (2) split into lines + var lines = text + .replace(/ +/gi, ' ') + .split(/\r?\n/gi); + + var linesCount = lines.length; + + for (var i = 0; i < linesCount; i++) + { + var line = lines[i]; + var out = ''; + + // trim whitespace + line = line.replace(/^ *|\s*$/gi, ''); + + // if entire line is less than wordWrapWidth + // append the entire line and exit early + var lineWidth = context.measureText(line).width; + + if (lineWidth < wordWrapWidth) + { + output += line + '\n'; + continue; + } + + // otherwise, calculate new lines + var currentLineWidth = wordWrapWidth; + + // split into words + var words = line.split(' '); + + for (var j = 0; j < words.length; j++) + { + var word = words[j]; + var wordWithSpace = word + ' '; + var wordWidth = context.measureText(wordWithSpace).width; + + if (wordWidth > currentLineWidth) + { + // break word + if (j === 0) + { + // shave off letters from word until it's small enough + var newWord = wordWithSpace; + + while (newWord.length) + { + newWord = newWord.slice(0, -1); + wordWidth = context.measureText(newWord).width; + + if (wordWidth <= currentLineWidth) + { + break; + } + } + + // if wordWrapWidth is too small for even a single + // letter, shame user failure with a fatal error + if (!newWord.length) + { + throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); + } + + // replace current word in array with remainder + var secondPart = word.substr(newWord.length); + + words[j] = secondPart; + + // append first piece to output + out += newWord; + } + + // if existing word length is 0, don't include it + var offset = (words[j].length) ? j : j + 1; + + // collapse rest of sentence + var remainder = words.slice(offset).join(' ') + // remove any trailing white space + .replace(/[ \n]*$/gi, ''); + + // prepend remainder to next line + lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); + linesCount = lines.length; + + break; // processing on this line + + // append word with space to output + } + else + { + out += wordWithSpace; + currentLineWidth -= wordWidth; + } + } + + // append processed line to output + output += out.replace(/[ \n]*$/gi, '') + '\n'; + } + + // trim the end of the string + output = output.replace(/[\s|\n]*$/gi, ''); + + return output; + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#basicWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.basicWordWrap = function (text) { + + var result = ''; + var lines = text.split('\n'); + + for (var i = 0; i < lines.length; i++) + { + var spaceLeft = this.style.wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) + { + var wordWidth = this.context.measureText(words[j]).width; + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is greater than the word wrap width. + if (j > 0) + { + result += '\n'; + } + result += words[j] + ' '; + spaceLeft = this.style.wordWrapWidth - wordWidth; + } + else + { + spaceLeft -= wordWidthWithSpace; + result += words[j] + ' '; + } + } + + if (i < lines.length-1) + { + result += '\n'; + } + } + + return result; + +}; + +/** +* Updates the internal `style.font` if it now differs according to generation from components. +* +* @method Phaser.Text#updateFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.updateFont = function (components) { + + var font = this.componentsToFont(components); + + if (this.style.font !== font) + { + this.style.font = font; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + +}; + +/** +* Converting a short CSS-font string into the relevant components. +* +* @method Phaser.Text#fontToComponents +* @private +* @param {string} font - a CSS font string +*/ +Phaser.Text.prototype.fontToComponents = function (font) { + + // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand: + // style - normal | italic | oblique | inherit + // variant - normal | small-caps | inherit + // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit + // size - xx-small | x-small | small | medium | large | x-large | xx-large, + // larger | smaller + // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %) + // font-family - rest (but identifiers or quoted with comma separation) + var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/); + + if (m) + { + var family = m[5].trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(family) && !/['",]/.exec(family)) + { + family = "'" + family + "'"; + } + + return { + font: font, + fontStyle: m[1] || 'normal', + fontVariant: m[2] || 'normal', + fontWeight: m[3] || 'normal', + fontSize: m[4] || 'medium', + fontFamily: family + }; + } + else + { + console.warn("Phaser.Text - unparsable CSS font: " + font); + + return { + font: font + }; + } + +}; + +/** +* Converts individual font components (see `fontToComponents`) to a short CSS font string. +* +* @method Phaser.Text#componentsToFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.componentsToFont = function (components) { + + var parts = []; + var v; + + v = components.fontStyle; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontVariant; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontWeight; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontSize; + if (v && v !== 'medium') { parts.push(v); } + + v = components.fontFamily; + if (v) { parts.push(v); } + + if (!parts.length) + { + // Fallback to whatever value the 'font' was + parts.push(components.font); + } + + return parts.join(" "); + +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* Use the optional `immediate` argument if you need the Text display to update immediately. +* +* If not it will re-create the texture of this Text object during the next time the render +* loop is called. +* +* @method Phaser.Text#setText +* @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present. +* @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setText = function (text, immediate) { + + if (immediate === undefined) { immediate = false; } + + this.text = text.toString() || ''; + + if (immediate) + { + this.updateText(); + } + else + { + this.dirty = true; + } + + return this; + +}; + +/** + * Converts the given array into a tab delimited string and then updates this Text object. + * This is mostly used when you want to display external data using tab stops. + * + * The array can be either single or multi dimensional depending on the result you need: + * + * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`. + * + * Where as: + * + * `[ + * [ 'a', 'b', 'c' ], + * [ 'd', 'e', 'f'] + * ]` + * + * would convert in to: `"a\tb\tc\nd\te\tf"` + * + * @method Phaser.Text#parseList + * @param {array} list - The array of data to convert into a string. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.parseList = function (list) { + + if (!Array.isArray(list)) + { + return this; + } + else + { + var s = ""; + + for (var i = 0; i < list.length; i++) + { + if (Array.isArray(list[i])) + { + s += list[i].join("\t"); + + if (i < list.length - 1) + { + s += "\n"; + } + } + else + { + s += list[i]; + + if (i < list.length - 1) + { + s += "\t"; + } + } + } + } + + this.text = s; + this.dirty = true; + + return this; + +}; + +/** + * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned, + * regardless of the number of lines in the text, the font size or any other attribute. + * + * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly + * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment. + * + * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to + * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of + * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center + * of the text bounds. + * + * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions + * may vary based on font (say for multi-lingual games). + * + * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width. + * + * Call this method with no arguments given to reset an existing textBounds. + * + * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts + * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot` + * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then + * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot. + * + * @method Phaser.Text#setTextBounds + * @param {number} [x] - The x coordinate of the Text Bounds region. + * @param {number} [y] - The y coordinate of the Text Bounds region. + * @param {number} [width] - The width of the Text Bounds region. + * @param {number} [height] - The height of the Text Bounds region. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.setTextBounds = function (x, y, width, height) { + + if (x === undefined) + { + this.textBounds = null; + } + else + { + if (!this.textBounds) + { + this.textBounds = new Phaser.Rectangle(x, y, width, height); + } + else + { + this.textBounds.setTo(x, y, width, height); + } + + if (this.style.wordWrapWidth > width) + { + this.style.wordWrapWidth = width; + } + } + + this.updateTexture(); + + return this; + +}; + +/** + * Updates the texture based on the canvas dimensions. + * + * @method Phaser.Text#updateTexture + * @private + */ +Phaser.Text.prototype.updateTexture = function () { + + var base = this.texture.baseTexture; + var crop = this.texture.crop; + var frame = this.texture.frame; + + var w = this.canvas.width; + var h = this.canvas.height; + + base.width = w; + base.height = h; + + crop.width = w; + crop.height = h; + + frame.width = w; + frame.height = h; + + this.texture.width = w; + this.texture.height = h; + + this._width = w; + this._height = h; + + if (this.textBounds) + { + var x = this.textBounds.x; + var y = this.textBounds.y; + + // Align the canvas based on the bounds + if (this.style.boundsAlignH === 'right') + { + x += this.textBounds.width - this.canvas.width / this.resolution; + } + else if (this.style.boundsAlignH === 'center') + { + x += this.textBounds.halfWidth - (this.canvas.width / this.resolution / 2); + } + + if (this.style.boundsAlignV === 'bottom') + { + y += this.textBounds.height - this.canvas.height / this.resolution; + } + else if (this.style.boundsAlignV === 'middle') + { + y += this.textBounds.halfHeight - (this.canvas.height / this.resolution / 2); + } + + this.pivot.x = -x; + this.pivot.y = -y; + } + + // Can't render something with a zero sized dimension + this.renderable = (w !== 0 && h !== 0); + + this.texture.requiresReTint = true; + + this.texture.baseTexture.dirty(); + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Text#_renderWebGL +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderWebGL = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Renders the object using the Canvas renderer. +* +* @method Phaser.Text#_renderCanvas +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderCanvas = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Calculates the ascent, descent and fontSize of a given font style. +* +* @method Phaser.Text#determineFontProperties +* @private +* @param {object} fontStyle +*/ +Phaser.Text.prototype.determineFontProperties = function (fontStyle) { + + var properties = Phaser.Text.fontPropertiesCache[fontStyle]; + + if (!properties) + { + properties = {}; + + var canvas = Phaser.Text.fontPropertiesCanvas; + var context = Phaser.Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('|MÉq').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + if (!context.getImageData(0, 0, width, height)) + { + properties.ascent = baseline; + properties.descent = baseline + 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + } + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i, j; + + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + properties.descent = i - baseline; + //TODO might need a tweak. kind of a temp fix! + properties.descent += 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; + +}; + +/** +* Returns the bounds of the Text as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Text#getBounds +* @param {Phaser.Matrix} matrix - The transformation matrix of the Text. +* @return {Phaser.Rectangle} The framing rectangle +*/ +Phaser.Text.prototype.getBounds = function (matrix) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return PIXI.Sprite.prototype.getBounds.call(this, matrix); + +}; + +/** +* Sets the character limit of the text, with a suffix. +* If the text is longer than this limit, it is truncated and the suffix is appended. +* +* @method Phaser.Text#setCharacterLimit +* @param {number} [characterLimit] - The x coordinate of the Text Bounds region. +* @param {string} [suffix] - The suffix to append to the truncated text. +*/ +Phaser.Text.prototype.setCharacterLimit = function (characterLimit, suffix) { + + this.characterLimitSuffix = (suffix === undefined) ? '' : suffix; + this.characterLimitSize = characterLimit; + + this.updateText(); +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* @name Phaser.Text#text +* @property {string} text +*/ +Object.defineProperty(Phaser.Text.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* Change the font used. +* +* This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except +* that unlike using `setStyle` this will not change any current font fill/color settings. +* +* The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. +* +* @name Phaser.Text#cssFont +* @property {string} cssFont +*/ +Object.defineProperty(Phaser.Text.prototype, 'cssFont', { + + get: function() { + return this.componentsToFont(this._fontComponents); + }, + + set: function (value) + { + value = value || 'bold 20pt Arial'; + this._fontComponents = this.fontToComponents(value); + this.updateFont(this._fontComponents); + } + +}); + +/** +* Change the font family that the text will be rendered in, such as 'Arial'. +* +* Multiple CSS font families and generic fallbacks can be specified as long as +* {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed. +* +* To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`. +* +* @name Phaser.Text#font +* @property {string} font +*/ +Object.defineProperty(Phaser.Text.prototype, 'font', { + + get: function() { + return this._fontComponents.fontFamily; + }, + + set: function(value) { + + value = value || 'Arial'; + value = value.trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value)) + { + value = "'" + value + "'"; + } + + this._fontComponents.fontFamily = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The size of the font. +* +* If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing +* the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). +* +* @name Phaser.Text#fontSize +* @property {number|string} fontSize +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontSize', { + + get: function() { + + var size = this._fontComponents.fontSize; + + if (size && /(?:^0$|px$)/.exec(size)) + { + return parseInt(size, 10); + } + else + { + return size; + } + + }, + + set: function(value) { + + value = value || '0'; + + if (typeof value === 'number') + { + value = value + 'px'; + } + + this._fontComponents.fontSize = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}. +* @name Phaser.Text#fontWeight +* @property {string} fontWeight +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontWeight', { + + get: function() { + return this._fontComponents.fontWeight || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontWeight = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The style of the font: 'normal', 'italic', 'oblique' +* @name Phaser.Text#fontStyle +* @property {string} fontStyle +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontStyle', { + + get: function() { + return this._fontComponents.fontStyle || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontStyle = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The variant the font: 'normal', 'small-caps' +* @name Phaser.Text#fontVariant +* @property {string} fontVariant +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontVariant', { + + get: function() { + return this._fontComponents.fontVariant || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontVariant = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* @name Phaser.Text#fill +* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'fill', { + + get: function() { + return this.style.fill; + }, + + set: function(value) { + + if (value !== this.style.fill) + { + this.style.fill = value; + this.dirty = true; + } + + } + +}); + +/** +* Controls the horizontal alignment for multiline text. +* Can be: 'left', 'center' or 'right'. +* Does not affect single lines of text. For that please see `setTextBounds`. +* @name Phaser.Text#align +* @property {string} align +*/ +Object.defineProperty(Phaser.Text.prototype, 'align', { + + get: function() { + return this.style.align; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.align) + { + this.style.align = value; + this.dirty = true; + } + + } + +}); + +/** +* The resolution of the canvas the text is rendered to. +* This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. +* @name Phaser.Text#resolution +* @property {integer} resolution +*/ +Object.defineProperty(Phaser.Text.prototype, 'resolution', { + + get: function() { + return this._res; + }, + + set: function(value) { + + if (value !== this._res) + { + this._res = value; + this.dirty = true; + } + + } + +}); + +/** +* The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. +* Can be an integer or an array of varying tab sizes, one tab per element. +* For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. +* If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. +* +* @name Phaser.Text#tabs +* @property {integer|array} tabs +*/ +Object.defineProperty(Phaser.Text.prototype, 'tabs', { + + get: function() { + return this.style.tabs; + }, + + set: function(value) { + + if (value !== this.style.tabs) + { + this.style.tabs = value; + this.dirty = true; + } + + } + +}); + +/** +* Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @name Phaser.Text#boundsAlignH +* @property {string} boundsAlignH +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', { + + get: function() { + return this.style.boundsAlignH; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignH) + { + this.style.boundsAlignH = value; + this.dirty = true; + } + + } + +}); + +/** +* Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @name Phaser.Text#boundsAlignV +* @property {string} boundsAlignV +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', { + + get: function() { + return this.style.boundsAlignV; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignV) + { + this.style.boundsAlignV = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#stroke +* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'stroke', { + + get: function() { + return this.style.stroke; + }, + + set: function(value) { + + if (value !== this.style.stroke) + { + this.style.stroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#strokeThickness +* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke) +*/ +Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', { + + get: function() { + return this.style.strokeThickness; + }, + + set: function(value) { + + if (value !== this.style.strokeThickness) + { + this.style.strokeThickness = Number(value); + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrap +* @property {boolean} wordWrap - Indicates if word wrap should be used. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrap', { + + get: function() { + return this.style.wordWrap; + }, + + set: function(value) { + + if (value !== this.style.wordWrap) + { + this.style.wordWrap = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrapWidth +* @property {number} wordWrapWidth - The width at which text will wrap. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', { + + get: function() { + return this.style.wordWrapWidth; + }, + + set: function(value) { + + if (value !== this.style.wordWrapWidth) + { + this.style.wordWrapWidth = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#lineSpacing +* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. +*/ +Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { + + get: function() { + return this._lineSpacing; + }, + + set: function(value) { + + if (value !== this._lineSpacing) + { + this._lineSpacing = parseFloat(value); + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetX +* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', { + + get: function() { + return this.style.shadowOffsetX; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetX) + { + this.style.shadowOffsetX = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetY +* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', { + + get: function() { + return this.style.shadowOffsetY; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetY) + { + this.style.shadowOffsetY = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowColor +* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowColor', { + + get: function() { + return this.style.shadowColor; + }, + + set: function(value) { + + if (value !== this.style.shadowColor) + { + this.style.shadowColor = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowBlur +* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', { + + get: function() { + return this.style.shadowBlur; + }, + + set: function(value) { + + if (value !== this.style.shadowBlur) + { + this.style.shadowBlur = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowStroke +* @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', { + + get: function() { + return this.style.shadowStroke; + }, + + set: function(value) { + + if (value !== this.style.shadowStroke) + { + this.style.shadowStroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowFill +* @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowFill', { + + get: function() { + return this.style.shadowFill; + }, + + set: function(value) { + + if (value !== this.style.shadowFill) + { + this.style.shadowFill = value; + this.dirty = true; + } + + } + +}); + +/** +* The width of the Text object in pixels. This is width of the Texture frame / the Text.resolution. +* @name Phaser.Text#width +* @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'width', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.x * (this.texture.frame.width / this.resolution); + }, + + set: function(value) { + + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** +* The height of the Text object in pixels. This is height of the Texture frame / the Text.resolution. +* @name Phaser.Text#height +* @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'height', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.y * (this.texture.frame.height / this.resolution); + }, + + set: function(value) { + + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +Phaser.Text.fontPropertiesCache = {}; + +Phaser.Text.fontPropertiesCanvas = document.createElement('canvas'); +Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d'); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. +* It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to +* match the font structure. +* +* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability +* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by +* processing the font texture in an image editor, applying fills and any other effects required. +* +* To create multi-line text insert \r, \n or \r\n escape codes into the text string. +* +* If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly +* updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. +* +* To create a BitmapText data files you can use: +* +* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ +* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner +* Littera (Web-based, free): http://kvazars.com/littera/ +* +* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of +* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson +* +* If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. +* +* @class Phaser.BitmapText +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - X coordinate to display the BitmapText object at. +* @param {number} y - Y coordinate to display the BitmapText object at. +* @param {string} font - The key of the BitmapText as stored in Phaser.Cache. +* @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. +* @param {number} [size=32] - The size the font will be rendered at in pixels. +* @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. +*/ +Phaser.BitmapText = function (game, x, y, font, text, size, align) { + + x = x || 0; + y = y || 0; + font = font || ''; + text = text || ''; + size = size || 32; + align = align || 'left'; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.BITMAPTEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textWidth = 0; + + /** + * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textHeight = 0; + + /** + * @property {Phaser.Point} anchor - The anchor value of this BitmapText. + */ + this.anchor = new Phaser.Point(); + + /** + * @property {Phaser.Point} _prevAnchor - The previous anchor value. + * @private + */ + this._prevAnchor = new Phaser.Point(); + + /** + * @property {array} _glyphs - Private tracker for the letter sprite pool. + * @private + */ + this._glyphs = []; + + /** + * @property {number} _maxWidth - Internal cache var. + * @private + */ + this._maxWidth = 0; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text.toString() || ''; + + /** + * @property {string} _data - Internal cache var. + * @private + */ + this._data = game.cache.getBitmapFont(font); + + /** + * @property {string} _font - Internal cache var. + * @private + */ + this._font = font; + + /** + * @property {number} _fontSize - Internal cache var. + * @private + */ + this._fontSize = size; + + /** + * @property {string} _align - Internal cache var. + * @private + */ + this._align = align; + + /** + * @property {number} _tint - Internal cache var. + * @private + */ + this._tint = 0xFFFFFF; + + this.updateText(); + + /** + * @property {boolean} dirty - The dirty state of this object. + */ + this.dirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.BitmapText.prototype.constructor = Phaser.BitmapText; + +Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.BitmapText +* @return {boolean} True if the BitmapText was rendered, otherwise false. +*/ +Phaser.BitmapText.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.preUpdate. +* @method Phaser.BitmapText.prototype.postUpdate +*/ +Phaser.BitmapText.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this.body && this.body.type === Phaser.Physics.ARCADE) + { + if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight)) + { + this.body.setSize(this.textWidth, this.textHeight); + } + } + +}; + +/** +* The text to be displayed by this BitmapText object. +* +* It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. +* +* @method Phaser.BitmapText.prototype.setText +* @param {string} text - The text to be displayed by this BitmapText object. +*/ +Phaser.BitmapText.prototype.setText = function (text) { + + this.text = text; + +}; + +/** +* Given the input text this will scan the characters until either a newline is encountered, +* or the line exceeds maxWidth, taking into account kerning, character widths and scaling. +* +* @method Phaser.BitmapText.prototype.scanLine +* @private +* @param {object} data - A reference to the font object in the Phaser.Cache. +* @param {float} scale - The scale of the font in relation to the texture. +* @param {string} text - The text to parse. +* @return {object} An object containing the parsed characters, total pixel width and x offsets. +*/ +Phaser.BitmapText.prototype.scanLine = function (data, scale, text) { + + var x = 0; + var w = 0; + var lastSpace = -1; + var wrappedWidth = 0; + var prevCharCode = null; + var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null; + var chars = []; + + // Let's scan the text and work out if any of the lines are > maxWidth + for (var i = 0; i < text.length; i++) + { + var end = (i === text.length - 1) ? true : false; + + if (/(?:\r\n|\r|\n)/.test(text.charAt(i))) + { + return { width: w, text: text.substr(0, i), end: end, chars: chars }; + } + else + { + var charCode = text.charCodeAt(i); + var charData = data.chars[charCode]; + + var c = 0; + + // If the character data isn't found in the data array + // then we replace it with a blank space + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + // Adjust for kerning from previous character to this one + var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0; + + // Record the last space in the string and the current width + if (/(\s)/.test(text.charAt(i))) + { + lastSpace = i; + wrappedWidth = w; + } + + // What will the line width be if we add this character to it? + c = (kerning + charData.texture.width + charData.xOffset) * scale; + + // Do we need to line-wrap? + if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1) + { + // The last space was at "lastSpace" which was "i - lastSpace" characters ago + return { width: wrappedWidth || w, text: text.substr(0, i - (i - lastSpace)), end: false, chars: chars }; + } + else + { + w += (charData.xAdvance + kerning) * scale; + + chars.push(x + (charData.xOffset + kerning) * scale); + + x += (charData.xAdvance + kerning) * scale; + + prevCharCode = charCode; + } + } + } + + return { width: w, text: text, end: end, chars: chars }; + +}; + +/** +* Given a text string this will scan each character in the string to ensure it exists +* in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. +* +* If no font data has been loaded at all this returns an empty string, as nothing can be rendered. +* +* @method Phaser.BitmapText.prototype.cleanText +* @param {string} text - The text to parse. +* @param {string} [replace=''] - The replacement string for any missing characters. +* @return {string} The cleaned text string. +*/ +Phaser.BitmapText.prototype.cleanText = function (text, replace) { + + if (replace === undefined) + { + replace = ''; + } + + var data = this._data.font; + + if (!data) + { + return ''; + } + + var re = /\r\n|\n\r|\n|\r/g; + var lines = text.replace(re, "\n").split("\n"); + + for (var i = 0; i < lines.length; i++) + { + var output = ''; + var line = lines[i]; + + for (var c = 0; c < line.length; c++) + { + if (data.chars[line.charCodeAt(c)]) + { + output = output.concat(line[c]); + } + else + { + output = output.concat(replace); + } + } + + lines[i] = output; + } + + return lines.join("\n"); + +}; + +/** +* Renders text and updates it when needed. +* +* @method Phaser.BitmapText.prototype.updateText +* @private +*/ +Phaser.BitmapText.prototype.updateText = function () { + + var data = this._data.font; + + if (!data) + { + return; + } + + var text = this.text; + var scale = this._fontSize / data.size; + var lines = []; + + var y = 0; + + this.textWidth = 0; + + do + { + var line = this.scanLine(data, scale, text); + + line.y = y; + + lines.push(line); + + if (line.width > this.textWidth) + { + this.textWidth = line.width; + } + + y += (data.lineHeight * scale); + + text = text.substr(line.text.length + 1); + + } while (line.end === false); + + this.textHeight = y; + + var t = 0; + var align = 0; + var ax = this.textWidth * this.anchor.x; + var ay = this.textHeight * this.anchor.y; + + for (var i = 0; i < lines.length; i++) + { + var line = lines[i]; + + if (this._align === 'right') + { + align = this.textWidth - line.width; + } + else if (this._align === 'center') + { + align = (this.textWidth - line.width) / 2; + } + + for (var c = 0; c < line.text.length; c++) + { + var charCode = line.text.charCodeAt(c); + var charData = data.chars[charCode]; + + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + var g = this._glyphs[t]; + + if (g) + { + // Sprite already exists in the glyphs pool, so we'll reuse it for this letter + g.texture = charData.texture; + } + else + { + // We need a new sprite as the pool is empty or exhausted + g = new PIXI.Sprite(charData.texture); + g.name = line.text[c]; + this._glyphs.push(g); + } + + g.position.x = (line.chars[c] + align) - ax; + g.position.y = (line.y + (charData.yOffset * scale)) - ay; + + g.scale.set(scale); + g.tint = this.tint; + g.texture.requiresReTint = true; + g.cachedTint = 0xFFFFFF; + + if (!g.parent) + { + this.addChild(g); + } + + t++; + } + } + + // Remove unnecessary children + // This moves them from the display list (children array) but retains them in the _glyphs pool + for (i = t; i < this._glyphs.length; i++) + { + this.removeChild(this._glyphs[i]); + } + +}; + +/** +* If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of +* Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they +* still take up memory while sat in the glyphs pool waiting to be re-used in the future. +* +* If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool +* by calling this method. +* +* Calling this doesn't prevent you from increasing the length of the text again in the future. +* +* @method Phaser.BitmapText.prototype.purgeGlyphs +* @return {integer} The amount of glyphs removed from the pool. +*/ +Phaser.BitmapText.prototype.purgeGlyphs = function () { + + var len = this._glyphs.length; + var kept = []; + + for (var i = 0; i < this._glyphs.length; i++) + { + if (this._glyphs[i].parent !== this) + { + this._glyphs[i].destroy(); + } + else + { + kept.push(this._glyphs[i]); + } + } + + this._glyphs = []; + this._glyphs = kept; + + this.updateText(); + + return len - kept.length; + +}; + +/** +* Updates the transform of this object. +* +* @method Phaser.BitmapText.prototype.updateTransform +* @private +*/ +Phaser.BitmapText.prototype.updateTransform = function () { + + if (this.dirty || !this.anchor.equals(this._prevAnchor)) + { + this.updateText(); + this.dirty = false; + this._prevAnchor.copyFrom(this.anchor); + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/** +* @name Phaser.BitmapText#align +* @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'align', { + + get: function() { + return this._align; + }, + + set: function(value) { + + if (value !== this._align && (value === 'left' || value === 'center' || value === 'right')) + { + this._align = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#tint +* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'tint', { + + get: function() { + return this._tint; + }, + + set: function(value) { + + if (value !== this._tint) + { + this._tint = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#font +* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'font', { + + get: function() { + return this._font; + }, + + set: function(value) { + + if (value !== this._font) + { + this._font = value.trim(); + this._data = this.game.cache.getBitmapFont(this._font); + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#fontSize +* @property {number} fontSize - The size of the font in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { + + get: function() { + return this._fontSize; + }, + + set: function(value) { + + value = parseInt(value, 10); + + if (value !== this._fontSize && value > 0) + { + this._fontSize = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#text +* @property {string} text - The text to be displayed by this BitmapText object. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.updateText(); + } + + } + +}); + +/** +* The maximum display width of this BitmapText in pixels. +* +* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped +* based on the last whitespace character found in the line. +* +* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. +* +* Disable maxWidth by setting the value to 0. +* +* @name Phaser.BitmapText#maxWidth +* @property {number} maxWidth - The maximum width of this BitmapText in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', { + + get: function() { + + return this._maxWidth; + + }, + + set: function(value) { + + if (value !== this._maxWidth) + { + this._maxWidth = value; + this.updateText(); + } + + } + +}); + +/** +* Enable or disable texture smoothing for this BitmapText. +* +* The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. +* +* Smoothing is enabled by default. +* +* @name Phaser.BitmapText#smoothed +* @property {boolean} smoothed +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', { + + get: function() { + + return !this._data.base.scaleMode; + + }, + + set: function(value) { + + if (value) + { + this._data.base.scaleMode = 0; + } + else + { + this._data.base.scaleMode = 1; + } + this._data.base.dirty(); + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont +* is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. +* +* @class Phaser.RetroFont +* @extends Phaser.RenderTexture +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {string} key - The font set graphic set as stored in the Game.Cache. +* @param {number} characterWidth - The width of each character in the font set. +* @param {number} characterHeight - The height of each character in the font set. +* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. +* @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. +* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. +* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { + + if (!game.cache.checkImageKey(key)) + { + return false; + } + + if (charsPerRow === undefined || charsPerRow === null) + { + charsPerRow = game.cache.getImage(key).width / characterWidth; + } + + /** + * @property {number} characterWidth - The width of each character in the font set. + */ + this.characterWidth = characterWidth; + + /** + * @property {number} characterHeight - The height of each character in the font set. + */ + this.characterHeight = characterHeight; + + /** + * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here. + */ + this.characterSpacingX = xSpacing || 0; + + /** + * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here. + */ + this.characterSpacingY = ySpacing || 0; + + /** + * @property {number} characterPerRow - The number of characters per row in the font set. + */ + this.characterPerRow = charsPerRow; + + /** + * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @readonly + */ + this.offsetX = xOffset || 0; + + /** + * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @readonly + */ + this.offsetY = yOffset || 0; + + /** + * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + */ + this.align = "left"; + + /** + * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) + * @default + */ + this.multiLine = false; + + /** + * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. + * @default + */ + this.autoUpperCase = true; + + /** + * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels. + * @default + */ + this.customSpacingX = 0; + + /** + * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels. + * @default + */ + this.customSpacingY = 0; + + /** + * If you need this RetroFont image to have a fixed width you can set the width in this value. + * If text is wider than the width specified it will be cropped off. + * @property {number} fixedWidth + */ + this.fixedWidth = 0; + + /** + * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font. + */ + this.fontSet = game.cache.getImage(key); + + /** + * @property {string} _text - The text of the font image. + * @private + */ + this._text = ''; + + /** + * @property {array} grabData - An array of rects for faster character pasting. + * @private + */ + this.grabData = []; + + /** + * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font. + */ + this.frameData = new Phaser.FrameData(); + + // Now generate our rects for faster copying later on + var currentX = this.offsetX; + var currentY = this.offsetY; + var r = 0; + + for (var c = 0; c < chars.length; c++) + { + var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight)); + + this.grabData[chars.charCodeAt(c)] = frame.index; + + r++; + + if (r === this.characterPerRow) + { + r = 0; + currentX = this.offsetX; + currentY += this.characterHeight + this.characterSpacingY; + } + else + { + currentX += this.characterWidth + this.characterSpacingX; + } + } + + game.cache.updateFrameData(key, this.frameData); + + /** + * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font. + * @readonly + */ + this.stamp = new Phaser.Image(game, 0, 0, key, 0); + + Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST); + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RETROFONT; + +}; + +Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype); +Phaser.RetroFont.prototype.constructor = Phaser.RetroFont; + +/** +* Align each line of multi-line text to the left. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_LEFT = "left"; + +/** +* Align each line of multi-line text to the right. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_RIGHT = "right"; + +/** +* Align each line of multi-line text in the center. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_CENTER = "center"; + +/** +* Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + +/** +* Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "; + +/** +* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789"; + +/** +* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789"; + +/** +* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' "; + +/** +* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39"; + +/** +* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!"; + +/** +* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"; + +/** +* If you need this RetroFont to have a fixed width and custom alignment you can set the width here. +* If text is wider than the width specified it will be cropped off. +* +* @method Phaser.RetroFont#setFixedWidth +* @memberof Phaser.RetroFont +* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. +* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +*/ +Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) { + + if (lineAlignment === undefined) { lineAlignment = 'left'; } + + this.fixedWidth = width; + this.align = lineAlignment; + +}; + +/** +* A helper function that quickly sets lots of variables at once, and then updates the text. +* +* @method Phaser.RetroFont#setText +* @memberof Phaser.RetroFont +* @param {string} content - The text of this sprite. +* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. +* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels. +* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels. +* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. +*/ +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; + } + +}; + +/** +* Updates the texture with the new text. +* +* @method Phaser.RetroFont#buildRetroFontText +* @memberof Phaser.RetroFont +*/ +Phaser.RetroFont.prototype.buildRetroFontText = function () { + + var cx = 0; + var cy = 0; + + // Clears the textureBuffer + 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); + } + + // Loop through each line of text + for (var i = 0; i < lines.length; i++) + { + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + // This line of text is held in lines[i] - need to work out the alignment + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(lines[i], cx, cy, this.customSpacingX); + + cy += this.characterHeight + this.customSpacingY; + } + } + else + { + if (this.fixedWidth > 0) + { + this.resize(this.fixedWidth, this.characterHeight, true); + } + else + { + this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true); + } + + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(this._text, cx, 0, this.customSpacingX); + } + + this.requiresReTint = true; + +}; + +/** +* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. +* Used by getLine and getMultiLine +* +* @method Phaser.RetroFont#pasteLine +* @memberof Phaser.RetroFont +* @param {string} line - The single line of text to paste. +* @param {number} x - The x coordinate. +* @param {number} y - The y coordinate. +* @param {number} customSpacingX - Custom X spacing. +*/ +Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) { + + for (var c = 0; c < line.length; c++) + { + // If it's a space then there is no point copying, so leave a blank space + if (line.charAt(c) === " ") + { + x += this.characterWidth + customSpacingX; + } + else + { + // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it + if (this.grabData[line.charCodeAt(c)] >= 0) + { + this.stamp.frame = this.grabData[line.charCodeAt(c)]; + this.renderXY(this.stamp, x, y, false); + + x += this.characterWidth + customSpacingX; + + if (x > this.width) + { + break; + } + } + } + } +}; + +/** +* Works out the longest line of text in _text and returns its length +* +* @method Phaser.RetroFont#getLongestLine +* @memberof Phaser.RetroFont +* @return {number} The length of the longest line of text. +*/ +Phaser.RetroFont.prototype.getLongestLine = function () { + + var longestLine = 0; + + if (this._text.length > 0) + { + var lines = this._text.split("\n"); + + for (var i = 0; i < lines.length; i++) + { + if (lines[i].length > longestLine) + { + longestLine = lines[i].length; + } + } + } + + return longestLine; +}; + +/** +* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set. +* +* @method Phaser.RetroFont#removeUnsupportedCharacters +* @memberof Phaser.RetroFont +* @protected +* @param {boolean} [stripCR=true] - Should it strip carriage returns as well? +* @return {string} A clean version of the string. +*/ +Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) { + + var newString = ""; + + for (var c = 0; c < this._text.length; c++) + { + var aChar = this._text[c]; + var code = aChar.charCodeAt(0); + + if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n")) + { + newString = newString.concat(aChar); + } + } + + return newString; + +}; + +/** +* Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. +* Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. +* So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. +* +* @method Phaser.RetroFont#updateOffset +* @memberof Phaser.RetroFont +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont.prototype.updateOffset = function (x, y) { + + if (this.offsetX === x && this.offsetY === y) + { + return; + } + + var diffX = x - this.offsetX; + var diffY = y - this.offsetY; + + var frames = this.game.cache.getFrameData(this.stamp.key).getFrames(); + var i = frames.length; + + while (i--) + { + frames[i].x += diffX; + frames[i].y += diffY; + } + + this.buildRetroFontText(); + +}; + +/** +* @name Phaser.RetroFont#text +* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. +*/ +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(); + } + + } + +}); + +/** +* @name Phaser.RetroFont#smoothed +* @property {boolean} smoothed - Sets if the stamp is smoothed or not. +*/ +Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", { + + get: function () { + + return this.stamp.smoothed; + + }, + + set: function (value) { + + this.stamp.smoothed = value; + this.buildRetroFontText(); + + } + +}); + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @author Rovanion Luckey +* @copyright 2016 Photon Storm Ltd, Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Rope is a Sprite that has a repeating texture. +* +* The texture will automatically wrap on the edges as it moves. +* +* Please note that Ropes cannot have an input handler. +* +* @class Phaser.Rope +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Rope at. +* @param {number} y - The y coordinate (in world space) to position the Rope at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {Array} points - An array of {Phaser.Point}. +*/ +Phaser.Rope = function (game, x, y, key, frame, points) { + + this.points = points || []; + this._hasUpdateAnimation = false; + this._updateAnimationCallback = null; + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROPE; + + PIXI.DisplayObjectContainer.call(this); + + this.texture = Phaser.Cache.DEFAULT; + + // set up the main bits.. + this.uvs = new Float32Array([0, 1, + 1, 1, + 1, 0, + 0, 1]); + + this.vertices = new Float32Array([0, 0, + 100, 0, + 100, 100, + 0, 100]); + + this.colors = new Float32Array([1, 1, 1, 1]); + + this.indices = new Uint16Array([0, 1, 2, 3]); + + if (points) + { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + /** + * Whether the strip is dirty or not + * + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. + * + * @property canvasPadding + * @type Number + */ + this.canvasPadding = 0; + + this.drawMode = Phaser.Rope.TRIANGLE_STRIP; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + + this.refresh(); + +}; + +Phaser.Rope.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Rope.prototype.constructor = Phaser.Rope; + +Phaser.Component.Core.install.call(Phaser.Rope.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +Phaser.Rope.TRIANGLE_STRIP = 0; +Phaser.Rope.TRIANGLES = 1; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Rope#preUpdate +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override and use this function in your own custom objects to handle any update requirements you may have. +* +* @method Phaser.Rope#update +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.update = function() { + + if (this._hasUpdateAnimation) + { + this.updateAnimation.call(this); + } + +}; + +/** +* Resets the Rope. This places the Rope at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the Rope has a physics body that too is reset. +* +* @method Phaser.Rope#reset +* @memberof Phaser.Rope +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.Rope} This instance. +*/ +Phaser.Rope.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + return this; + +}; + +/* +* Refreshes the rope texture and UV coordinates. +* +* @method Phaser.Rope#refresh +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.refresh = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + this.count -= 0.2; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + var index; + var amount; + + for (var i = 1; i < total; i++) + { + index = i * 4; + + // time to do some smart drawing! + amount = i / (total - 1); + + if (i % 2) + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + else + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + +}; + +/* +* Updates the Ropes transform ready for rendering. +* +* @method Phaser.Rope#updateTransform +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.updateTransform = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var lastPoint = points[0]; + var nextPoint; + var perp = { x:0, y:0 }; + + this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + var point; + var index; + var ratio; + var perpLength; + var num; + + for (var i = 0; i < total; i++) + { + point = points[i]; + index = i * 4; + + if(i < points.length - 1) + { + nextPoint = points[i + 1]; + } + else + { + nextPoint = point; + } + + perp.y = -(nextPoint.x - lastPoint.x); + perp.x = nextPoint.y - lastPoint.y; + + ratio = (1 - (i / (total - 1))) * 10; + + if (ratio > 1) + { + ratio = 1; + } + + perpLength = Math.sqrt((perp.x * perp.x) + (perp.y * perp.y)); + num = this.texture.height / 2; + perp.x /= perpLength; + perp.y /= perpLength; + + perp.x *= num; + perp.y *= num; + + vertices[index] = point.x + perp.x; + vertices[index + 1] = point.y + perp.y; + vertices[index + 2] = point.x - perp.x; + vertices[index + 3] = point.y - perp.y; + + lastPoint = point; + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/* +* Sets the Texture this Rope uses for rendering. +* +* @method Phaser.Rope#setTexture +* @memberof Phaser.Rope +* @param {Texture} texture - The texture that will be used. +*/ +Phaser.Rope.prototype.setTexture = function (texture) { + + this.texture = texture; + +}; + +/* +* Renders the Rope to WebGL. +* +* @private +* @method Phaser.Rope#_renderWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + renderSession.spriteBatch.stop(); + + if (!this._vertexBuffer) + { + this._initWebGL(renderSession); + } + + renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader); + + this._renderStrip(renderSession); + + renderSession.spriteBatch.start(); + +}; + +/* +* Builds the Strip. +* +* @private +* @method Phaser.Rope#_initWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._initWebGL = function (renderSession) { + + // build the strip! + var gl = renderSession.gl; + + this._vertexBuffer = gl.createBuffer(); + this._indexBuffer = gl.createBuffer(); + this._uvBuffer = gl.createBuffer(); + this._colorBuffer = gl.createBuffer(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + +}; + +/* +* Renders the Strip to WebGL. +* +* @private +* @method Phaser.Rope#_renderStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderStrip = function (renderSession) { + + var gl = renderSession.gl; + var projection = renderSession.projection; + var offset = renderSession.offset; + var shader = renderSession.shaderManager.stripShader; + + var drawMode = (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + renderSession.blendModeManager.setBlendMode(this.blendMode); + + // set uniforms + gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true)); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + gl.uniform1f(shader.alpha, this.worldAlpha); + + if (!this.dirty) + { + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + } + else + { + this.dirty = false; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + } + + gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0); + +}; + +/* +* Renders the Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvas +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvas = function (renderSession) { + + var context = renderSession.context; + + var transform = this.worldTransform; + + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + if (renderSession.roundPixels) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx, ty); + } + + if (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) + { + this._renderCanvasTriangleStrip(context); + } + else + { + this._renderCanvasTriangles(context); + } + +}; + +/* +* Renders a Triangle Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangleStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangleStrip = function (context) { + + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + + var length = vertices.length / 2; + + this.count++; + + for (var i = 0; i < length - 2; i++) + { + var index = i * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangles +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangles = function (context) { + + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + + var length = indices.length; + + this.count++; + + for (var i = 0; i < length; i += 3) + { + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasDrawTriangle +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { + + var textureSource = this.texture.baseTexture.source; + var textureWidth = this.texture.width; + var textureHeight = this.texture.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var u0 = uvs[index0] * textureWidth; + var u1 = uvs[index1] * textureWidth; + var u2 = uvs[index2] * textureWidth; + var v0 = uvs[index0 + 1] * textureHeight; + var v1 = uvs[index1 + 1] * textureHeight; + var v2 = uvs[index2 + 1] * textureHeight; + + if (this.canvasPadding > 0) + { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt((normX * normX) + (normY * normY)); + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2); + var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2); + var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2); + var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2); + var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2); + var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2); + var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2); + + context.transform( + deltaA / delta, + deltaD / delta, + deltaB / delta, + deltaE / delta, + deltaC / delta, + deltaF / delta); + + context.drawImage(textureSource, 0, 0); + context.restore(); + +}; + +/* +* Renders a flat strip. +* +* @method Phaser.Rope#renderStripFlat +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.renderStripFlat = function (strip) { + + var context = this.context; + var vertices = strip.vertices; + + var length = vertices.length / 2; + + this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; i++) + { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var x1 = vertices[index + 2]; + var x2 = vertices[index + 4]; + var y0 = vertices[index + 1]; + var y1 = vertices[index + 3]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + +}; + +/* +* Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Rope#getBounds +* @memberof Phaser.Rope +* @param {Matrix} matrix - The transformation matrix of the Sprite. +* @return {Rectangle} The framing rectangle. +*/ +Phaser.Rope.prototype.getBounds = function (matrix) { + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + var vertices = this.vertices; + + for (var i = 0; i < vertices.length; i += 2) + { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + if (minX === -Infinity || maxY === Infinity) + { + return PIXI.EmptyRectangle; + } + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // Store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* A Rope will call its updateAnimation function on each update loop if it has one. +* +* @name Phaser.Rope#updateAnimation +* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. +*/ +Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", { + + get: function () { + + return this._updateAnimation; + + }, + + set: function (value) { + + if (value && typeof value === 'function') + { + this._hasUpdateAnimation = true; + this._updateAnimation = value; + } + else + { + this._hasUpdateAnimation = false; + this._updateAnimation = null; + } + + } + +}); + +/** +* The segments that make up the rope body as an array of Phaser.Rectangles +* +* @name Phaser.Rope#segments +* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope +*/ +Object.defineProperty(Phaser.Rope.prototype, "segments", { + + get: function () { + + var segments = []; + var index, x1, y1, x2, y2, width, height, rect; + + for (var i = 0; i < this.points.length; i++) + { + index = i * 4; + + x1 = this.vertices[index] * this.scale.x; + y1 = this.vertices[index + 1] * this.scale.y; + x2 = this.vertices[index + 4] * this.scale.x; + y2 = this.vertices[index + 3] * this.scale.y; + + width = Phaser.Math.difference(x1, x2); + height = Phaser.Math.difference(y1, y2); + + x1 += this.world.x; + y1 += this.world.y; + rect = new Phaser.Rectangle(x1, y1, width, height); + segments.push(rect); + } + + return segments; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. +* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. +* +* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. +* +* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background +* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` +* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will +* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to +* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. +* +* An important note about texture dimensions: +* +* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be +* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two +* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and +* bottom of your frame. To avoid this ensure your textures are perfect powers of two. +* +* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However +* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive +* additional padding to enforce it to be so. +* +* @class Phaser.TileSprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate (in world space) to position the TileSprite at. +* @param {number} [y=0] - The y coordinate (in world space) to position the TileSprite at. +* @param {number} [width=256] - The width of the TileSprite. +* @param {number} [height=256] - The height of the TileSprite. +* @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. +* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.TileSprite = function (game, x, y, width, height, key, frame) { + + x = x || 0; + y = y || 0; + width = width || 256; + height = height || 256; + key = key || null; + frame = frame || null; + + PIXI.Sprite.call(this, new PIXI.Texture(Phaser.Cache.DEFAULT.baseTexture), width, height); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.TILESPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} _scroll - Internal cache var. + * @private + */ + this._scroll = new Phaser.Point(); + + /** + * @property {Phaser.Point} tileScale - The scale applied to the image being tiled. + */ + this.tileScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tileScaleOffset - The scale offset applied to the image being tiled. + */ + this.tileScaleOffset = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tilePosition - The offset position of the image being tiled. + */ + this.tilePosition = new Phaser.Point(); + + /** + * If enabled a green rectangle will be drawn behind the generated tiling texture, + * allowing you to visually debug the texture being used. + * + * @property {boolean} textureDebug + */ + this.textureDebug = false; + + /** + * The CanvasBuffer object that the tiled texture is drawn to. + * + * @property {PIXI.CanvasBuffer} canvasBuffer + */ + this.canvasBuffer = null; + + /** + * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. + * + * @property {PIXI.Texture} tilingTexture + */ + this.tilingTexture = null; + + /** + * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). + * + * @property {object} tilePattern + */ + this.tilePattern = null; + + /** + * If true the TileSprite will run `generateTexture` on its **next** render pass. + * This is set by the likes of Phaser.LoadTexture.setFrame. + * + * @property {boolean} refreshTexture + */ + this.refreshTexture = true; + + this.frameWidth = 0; + this.frameHeight = 0; + + this._width = width; + this._height = height; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.TileSprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.TileSprite.prototype.constructor = Phaser.TileSprite; + +Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'Smoothed' +]); + +Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TileSprite#preUpdate +* @memberof Phaser.TileSprite +* @return {boolean} +*/ +Phaser.TileSprite.prototype.preUpdate = function () { + + if (this._scroll.x !== 0) + { + this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed; + } + + if (this._scroll.y !== 0) + { + this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed; + } + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). +* The scroll speed is specified in pixels per second. +* A negative x value will scroll to the left. A positive x value will scroll to the right. +* A negative y value will scroll up. A positive y value will scroll down. +* +* @method Phaser.TileSprite#autoScroll +* @memberof Phaser.TileSprite +* @param {number} x - Horizontal scroll speed in pixels per second. +* @param {number} y - Vertical scroll speed in pixels per second. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.autoScroll = function (x, y) { + + this._scroll.set(x, y); + + return this; + +}; + +/** +* Stops an automatically scrolling TileSprite. +* +* @method Phaser.TileSprite#stopScroll +* @memberof Phaser.TileSprite +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.stopScroll = function () { + + this._scroll.set(0, 0); + + return this; + +}; + +/** +* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present +* and nulls its reference to game, freeing it up for garbage collection. +* +* @method Phaser.TileSprite#destroy +* @memberof Phaser.TileSprite +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.TileSprite.prototype.destroy = function (destroyChildren) { + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + + PIXI.Sprite.prototype.destroy.call(this); + + if (this.canvasBuffer) + { + this.canvasBuffer.destroy(); + this.canvasBuffer = null; + } + + this.tileScale = null; + this.tileScaleOffset = null; + this.tilePosition = null; + + if (this.tilingTexture) + { + this.tilingTexture.destroy(true); + this.tilingTexture = null; + } + +}; + +/** +* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the TileSprite has a physics body that too is reset. +* +* @method Phaser.TileSprite#reset +* @memberof Phaser.TileSprite +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + this.tilePosition.x = 0; + this.tilePosition.y = 0; + + return this; + +}; + +/** +* Changes the texture being rendered by this TileSprite. +* Causes a texture refresh to take place on the next render. +* +* @method Phaser.TileSprite#setTexture +* @memberof Phaser.TileSprite +* @param {PIXI.Texture} texture - The texture to apply to this TileSprite. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.setTexture = function (texture) { + + if (this.texture !== texture) + { + this.texture = texture; + this.refreshTexture = true; + this.cachedTint = 0xFFFFFF; + } + + return this; + +}; + +/** +* Renders the TileSprite using the WebGL Renderer. +* +* @private +* @method Phaser.TileSprite#_renderWebGL +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + 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.refreshTexture) + { + this.generateTilingTexture(true, renderSession); + + if (this.tilingTexture) + { + if (this.tilingTexture.needsUpdate) + { + this.tilingTexture.baseTexture.textureIndex = this.texture.baseTexture.textureIndex; + renderSession.renderer.updateTexture(this.tilingTexture.baseTexture); + this.tilingTexture.needsUpdate = false; + } + } + else + { + return; + } + } + + renderSession.spriteBatch.renderTilingSprite(this); + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + var restartBatch = false; + + if (this._filters) + { + restartBatch = true; + renderSession.spriteBatch.stop(); + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + if (!restartBatch) + { + renderSession.spriteBatch.stop(); + } + + renderSession.maskManager.popMask(this._mask, renderSession); + } + + if (restartBatch) + { + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the TileSprite using the Canvas Renderer. +* +* @private +* @method Phaser.TileSprite#_renderCanvas +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + var context = renderSession.context; + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + context.globalAlpha = this.worldAlpha; + + var wt = this.worldTransform; + var resolution = renderSession.resolution; + var tx = (wt.tx * resolution) + renderSession.shakeX; + var ty = (wt.ty * resolution) + renderSession.shakeY; + + context.setTransform(wt.a * resolution, wt.b * resolution, wt.c * resolution, wt.d * resolution, tx, ty); + + if (this.tint !== 0xFFFFFF && (this.texture.requiresReTint || this.cachedTint !== this.tint)) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + this.refreshTexture = true; + } + + if (this.refreshTexture) + { + this.generateTilingTexture(false, renderSession); + + if (this.tilingTexture) + { + this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat'); + } + else + { + return; + } + } + + var sessionBlendMode = renderSession.currentBlendMode; + + // Check blend mode + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + var tilePosition = this.tilePosition; + var tileScale = this.tileScale; + + tilePosition.x %= this.tilingTexture.baseTexture.width; + tilePosition.y %= this.tilingTexture.baseTexture.height; + + // Translate + context.scale(tileScale.x, tileScale.y); + context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height)); + + context.fillStyle = this.tilePattern; + + tx = -tilePosition.x; + ty = -tilePosition.y; + + var tw = this._width / tileScale.x; + var th = this._height / tileScale.y; + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + tx |= 0; + ty |= 0; + tw |= 0; + th |= 0; + } + + context.fillRect(tx, ty, tw, th); + + // Translate back again + context.scale(1 / tileScale.x, 1 / tileScale.y); + context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height)); + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + // Reset blend mode + if (sessionBlendMode !== this.blendMode) + { + renderSession.currentBlendMode = sessionBlendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode]; + } + +}; + +/** +* Override the Sprite method. +* +* @private +* @method Phaser.TileSprite#onTextureUpdate +* @memberof Phaser.TileSprite +*/ +Phaser.TileSprite.prototype.onTextureUpdate = function () { + + // overriding the sprite version of this! + +}; + +/** +* Internal method that generates a new tiling texture. +* +* @method Phaser.TileSprite#generateTilingTexture +* @memberof Phaser.TileSprite +* @param {boolean} forcePowerOfTwo - Whether we want to force the texture to be a power of two +*/ +Phaser.TileSprite.prototype.generateTilingTexture = function (forcePowerOfTwo) { + + if (!this.texture.baseTexture.hasLoaded) + { + return; + } + + var texture = this.texture; + var frame = texture.frame; + + var targetWidth = this._frame.sourceSizeW || this._frame.width; + var targetHeight = this._frame.sourceSizeH || this._frame.height; + + var dx = 0; + var dy = 0; + + if (this._frame.trimmed) + { + dx = this._frame.spriteSourceSizeX; + dy = this._frame.spriteSourceSizeY; + } + + if (forcePowerOfTwo) + { + targetWidth = Phaser.Math.getNextPowerOfTwo(targetWidth); + targetHeight = Phaser.Math.getNextPowerOfTwo(targetHeight); + } + + if (this.canvasBuffer) + { + this.canvasBuffer.resize(targetWidth, targetHeight); + this.tilingTexture.baseTexture.width = targetWidth; + this.tilingTexture.baseTexture.height = targetHeight; + this.tilingTexture.needsUpdate = true; + } + else + { + this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight); + this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas); + this.tilingTexture.isTiling = true; + this.tilingTexture.needsUpdate = true; + } + + if (this.textureDebug) + { + this.canvasBuffer.context.strokeStyle = '#00ff00'; + this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight); + } + + // If a sprite sheet we need this: + var w = texture.crop.width; + var h = texture.crop.height; + + if (w !== targetWidth || h !== targetHeight) + { + w = targetWidth; + h = targetHeight; + } + + var targetTexture = this.tintedTexture ? this.tintedTexture : texture.baseTexture.source; + + this.canvasBuffer.context.drawImage( + targetTexture, + texture.crop.x, + texture.crop.y, + texture.crop.width, + texture.crop.height, + dx, + dy, + w, + h + ); + + this.tileScaleOffset.x = frame.width / targetWidth; + this.tileScaleOffset.y = frame.height / targetHeight; + + this.refreshTexture = false; + + this.tilingTexture.baseTexture._powerOf2 = true; + +}; + +/** +* Returns the framing rectangle of the Tile Sprite. +* +* @method Phaser.TileSprite#getBounds +* @memberof Phaser.TileSprite +* @return {Phaser.Rectangle} The bounds of the Tile Sprite. +*/ +Phaser.TileSprite.prototype.getBounds = function () { + + var width = this._width; + var height = this._height; + + var w0 = width * (1 - this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1 - this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = (a * w1) + (c * h1) + tx; + var y1 = (d * h1) + (b * w1) + ty; + + var x2 = (a * w0) + (c * h1) + tx; + var y2 = (d * h1) + (b * w0) + ty; + + var x3 = (a * w0) + (c * h0) + tx; + var y3 = (d * h0) + (b * w0) + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // TODO: This is surely always undefined? As it's not set anywhere in the parent objects + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* The width of the sprite, setting this will actually modify the scale to achieve the value set +* +* @property width +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'width', { + + get: function () { + + return this._width; + + }, + + set: function (value) { + + this._width = value; + + } + +}); + +/** +* The height of the TilingSprite, setting this will actually modify the scale to achieve the value set +* +* @property height +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'height', { + + get: function () { + + return this._height; + + }, + + set: function (value) { + + this._height = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The CanvasPool is a global static object, that allows Phaser to recycle and pool Canvas DOM elements. +* +* @class Phaser.CanvasPool +* @static +*/ +Phaser.CanvasPool = { + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @method Phaser.CanvasPool.create + * @static + * @param {any} parent - The parent of the canvas element. + * @param {number} width - The width of the canvas element. + * @param {number} height - The height of the canvas element. + * @return {HTMLCanvasElement} The canvas element. + */ + create: function (parent, width, height) { + + var idx = Phaser.CanvasPool.getFirst(); + var canvas; + + if (idx === -1) + { + var container = { + parent: parent, + canvas: document.createElement('canvas') + }; + + Phaser.CanvasPool.pool.push(container); + + canvas = container.canvas; + } + else + { + Phaser.CanvasPool.pool[idx].parent = parent; + + canvas = Phaser.CanvasPool.pool[idx].canvas; + } + + if (width !== undefined) + { + canvas.width = width; + canvas.height = height; + } + + return canvas; + + }, + + /** + * Gets the first free canvas index from the pool. + * + * @static + * @method Phaser.CanvasPool.getFirst + * @return {number} + */ + getFirst: function () { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + return i; + } + } + + return -1; + + }, + + /** + * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.remove + * @param {any} parent - The parent of the canvas element. + */ + remove: function (parent) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent === parent) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Looks up a canvas based on its type, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.removeByCanvas + * @param {HTMLCanvasElement} canvas - The canvas element to remove. + */ + removeByCanvas: function (canvas) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].canvas === canvas) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Gets the total number of used canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getTotal + * @return {number} The number of in-use (parented) canvas elements in the pool. + */ + getTotal: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent) + { + c++; + } + } + + return c; + + }, + + /** + * Gets the total number of free canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getFree + * @return {number} The number of free (un-parented) canvas elements in the pool. + */ + getFree: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + c++; + } + } + + return c; + + }, + + + /** + * Prints in-use, free, and total counts to console.log. + * + * @static + * @method Phaser.CanvasPool.log + */ + log: function () { + + console.log('CanvasPool: %s used, %s free, %s total', this.getTotal(), this.getFree(), this.pool.length); + + } + +}; + +/** + * The pool into which the canvas elements are placed. + * + * @property pool + * @type Array + * @static + */ +Phaser.CanvasPool.pool = []; + + +/** + * The total number of canvas elements in the {@link Phaser.CanvasPool.pool pool}. + * + * @property length + * @type number + * @static + * @readonly + */ +Object.defineProperty(Phaser.CanvasPool, 'length', { + get: function () { + return this.pool.length; + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}. +* +* This class represents a singleton object that can be accessed directly as `game.device` +* (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it. +* +* Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization +* occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase. +* Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal, e.g., +* +* ```javascript +* Phaser.Device.onInitialized.add(function (device) { +* +* device.canvasBitBltShift = true; +* device.mspointer = false; +* +* }); +* +* var game = new Phaser.Game(); +* ``` +* +* When checking features using the exposed properties only the *truth-iness* of the value should be relied upon +* unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined` +* when indicating the lack of a feature. +* +* Uses elements from System.js by MrDoob and Modernizr +* +* @description +* It is not possible to instantiate the Device class manually. +* +* @class +* @protected +*/ +Phaser.Device = function () { + + /** + * The time the device became ready. + * @property {integer} deviceReadyAt + * @protected + */ + this.deviceReadyAt = 0; + + /** + * The time as which initialization has completed. + * @property {boolean} initialized + * @protected + */ + this.initialized = false; + + // Browser / Host / Operating System + + /** + * @property {boolean} desktop - Is running on a desktop? + * @default + */ + this.desktop = false; + + /** + * @property {boolean} iOS - Is running on iOS? + * @default + */ + this.iOS = false; + + /** + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @default + */ + this.iOSVersion = 0; + + /** + * @property {boolean} cocoonJS - Is the game running under CocoonJS? + * @default + */ + this.cocoonJS = false; + + /** + * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App? + * @default + */ + this.cocoonJSApp = false; + + /** + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @default + */ + this.cordova = false; + + /** + * @property {boolean} node - Is the game running under Node.js? + * @default + */ + this.node = false; + + /** + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @default + */ + this.nodeWebkit = false; + + /** + * @property {boolean} electron - Is the game running under GitHub Electron? + * @default + */ + this.electron = false; + + /** + * @property {boolean} ejecta - Is the game running under Ejecta? + * @default + */ + this.ejecta = false; + + /** + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @default + */ + this.crosswalk = false; + + /** + * @property {boolean} android - Is running on android? + * @default + */ + this.android = false; + + /** + * @property {boolean} chromeOS - Is running on chromeOS? + * @default + */ + this.chromeOS = false; + + /** + * @property {boolean} linux - Is running on linux? + * @default + */ + this.linux = false; + + /** + * @property {boolean} macOS - Is running on macOS? + * @default + */ + this.macOS = false; + + /** + * @property {boolean} windows - Is running on windows? + * @default + */ + this.windows = false; + + /** + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @default + */ + this.windowsPhone = false; + + // Features + + /** + * @property {boolean} canvas - Is canvas available? + * @default + */ + this.canvas = false; + + /** + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @default + */ + this.canvasBitBltShift = null; + + /** + * If the browser isn't capable of handling tinting with alpha this will be false. + * @property {boolean} canHandleAlpha + * @default + */ + this.canHandleAlpha = false; + + /** + * Whether or not the {@link http://caniuse.com/#feat=canvas-blending Canvas Blend Modes} are supported, consequently the ability to tint using the multiply method. + * + * Expect `false` in Internet Explorer <= 11. + * + * @property {boolean} canUseMultiply + * @default + */ + this.canUseMultiply = false; + + /** + * @property {boolean} webGL - Is webGL available? + * @default + */ + this.webGL = false; + + /** + * @property {boolean} file - Is file available? + * @default + */ + this.file = false; + + /** + * @property {boolean} fileSystem - Is fileSystem available? + * @default + */ + this.fileSystem = false; + + /** + * @property {boolean} localStorage - Is localStorage available? + * @default + */ + this.localStorage = false; + + /** + * @property {boolean} worker - Is worker available? + * @default + */ + this.worker = false; + + /** + * @property {boolean} css3D - Is css3D available? + * @default + */ + this.css3D = false; + + /** + * @property {boolean} pointerLock - Is Pointer Lock available? + * @default + */ + this.pointerLock = false; + + /** + * @property {boolean} typedArray - Does the browser support TypedArrays? + * @default + */ + this.typedArray = false; + + /** + * @property {boolean} vibration - Does the device support the Vibration API? + * @default + */ + this.vibration = false; + + /** + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @default + */ + this.getUserMedia = true; + + /** + * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true) + * @default + */ + this.quirksMode = false; + + // Input + + /** + * @property {boolean} touch - Is touch available? + * @default + */ + this.touch = false; + + /** + * @property {boolean} mspointer - Is mspointer available? + * @default + */ + this.mspointer = false; + + /** + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @default + * @protected + */ + this.wheelEvent = null; + + // Browser + + /** + * @property {boolean} arora - Set to true if running in Arora. + * @default + */ + this.arora = false; + + /** + * @property {boolean} chrome - Set to true if running in Chrome. + * @default + */ + this.chrome = false; + + /** + * @property {number} chromeVersion - If running in Chrome this will contain the major version number. + * @default + */ + this.chromeVersion = 0; + + /** + * @property {boolean} epiphany - Set to true if running in Epiphany. + * @default + */ + this.epiphany = false; + + /** + * @property {boolean} firefox - Set to true if running in Firefox. + * @default + */ + this.firefox = false; + + /** + * @property {number} firefoxVersion - If running in Firefox this will contain the major version number. + * @default + */ + this.firefoxVersion = 0; + + /** + * @property {boolean} ie - Set to true if running in Internet Explorer. + * @default + */ + this.ie = false; + + /** + * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. + * @default + */ + this.ieVersion = 0; + + /** + * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+) + * @default + */ + this.trident = false; + + /** + * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx} + * @default + */ + this.tridentVersion = 0; + + /** + * @property {boolean} edge - Set to true if running in Microsoft Edge browser. + * @default + */ + this.edge = false; + + /** + * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. + * @default + */ + this.mobileSafari = false; + + /** + * @property {boolean} midori - Set to true if running in Midori. + * @default + */ + this.midori = false; + + /** + * @property {boolean} opera - Set to true if running in Opera. + * @default + */ + this.opera = false; + + /** + * @property {boolean} safari - Set to true if running in Safari. + * @default + */ + this.safari = false; + + /** + * @property {number} safariVersion - If running in Safari this will contain the major version number. + * @default + */ + this.safariVersion = 0; + + /** + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @default + */ + this.webApp = false; + + /** + * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle) + * @default + */ + this.silk = false; + + // Audio + + /** + * @property {boolean} audioData - Are Audio tags available? + * @default + */ + this.audioData = false; + + /** + * @property {boolean} webAudio - Is the WebAudio API available? + * @default + */ + this.webAudio = false; + + /** + * @property {boolean} ogg - Can this device play ogg files? + * @default + */ + this.ogg = false; + + /** + * @property {boolean} opus - Can this device play opus files? + * @default + */ + this.opus = false; + + /** + * @property {boolean} mp3 - Can this device play mp3 files? + * @default + */ + this.mp3 = false; + + /** + * @property {boolean} wav - Can this device play wav files? + * @default + */ + this.wav = false; + + /** + * Can this device play m4a files? + * @property {boolean} m4a - True if this device can play m4a files. + * @default + */ + this.m4a = false; + + /** + * @property {boolean} webm - Can this device play webm files? + * @default + */ + this.webm = false; + + /** + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @default + */ + this.dolby = false; + + // Video + + /** + * @property {boolean} oggVideo - Can this device play ogg video files? + * @default + */ + this.oggVideo = false; + + /** + * @property {boolean} h264Video - Can this device play h264 mp4 video files? + * @default + */ + this.h264Video = false; + + /** + * @property {boolean} mp4Video - Can this device play h264 mp4 video files? + * @default + */ + this.mp4Video = false; + + /** + * @property {boolean} webmVideo - Can this device play webm video files? + * @default + */ + this.webmVideo = false; + + /** + * @property {boolean} vp9Video - Can this device play vp9 video files? + * @default + */ + this.vp9Video = false; + + /** + * @property {boolean} hlsVideo - Can this device play hls video files? + * @default + */ + this.hlsVideo = false; + + // Device + + /** + * @property {boolean} iPhone - Is running on iPhone? + * @default + */ + this.iPhone = false; + + /** + * @property {boolean} iPhone4 - Is running on iPhone4? + * @default + */ + this.iPhone4 = false; + + /** + * @property {boolean} iPad - Is running on iPad? + * @default + */ + this.iPad = false; + + // Device features + + /** + * @property {number} pixelRatio - PixelRatio of the host device? + * @default + */ + this.pixelRatio = 0; + + /** + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @default + */ + this.littleEndian = false; + + /** + * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`. + * @default + */ + this.LITTLE_ENDIAN = false; + + /** + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @default + */ + this.support32bit = false; + + /** + * @property {boolean} fullscreen - Does the browser support the Full Screen API? + * @default + */ + this.fullscreen = false; + + /** + * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it. + * @default + */ + this.requestFullscreen = ''; + + /** + * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @default + */ + this.cancelFullscreen = ''; + + /** + * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @default + */ + this.fullscreenKeyboard = false; + +}; + +// Device is really a singleton/static entity; instantiate it +// and add new methods directly sans-prototype. +Phaser.Device = new Phaser.Device(); + +/** +* This signal is dispatched after device initialization occurs but before any of the ready +* callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked. +* +* Local "patching" for a particular device can/should be done in this event. +* +* _Note_: This signal is removed after the device has been readied; if a handler has not been +* added _before_ `new Phaser.Game(..)` it is probably too late. +* +* @type {?Phaser.Signal} +* @static +*/ +Phaser.Device.onInitialized = new Phaser.Signal(); + +/** +* Add a device-ready handler and ensure the device ready sequence is started. +* +* Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added, +* which is normally done automatically be calling `new Phaser.Game(..)`. +* +* The handler is invoked when the device is considered "ready", which may be immediately +* if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}. +* +* @method +* @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. +* @param {object} [context] - Context in which to invoke the handler +* @param {boolean} [nonPrimer=false] - If true the device ready check will not be started. +*/ +Phaser.Device.whenReady = function (callback, context, nonPrimer) { + + var readyCheck = this._readyCheck; + + if (this.deviceReadyAt || !readyCheck) + { + callback.call(context, this); + } + else if (readyCheck._monitor || nonPrimer) + { + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + } + else + { + readyCheck._monitor = readyCheck.bind(this); + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + + var cordova = typeof window.cordova !== 'undefined'; + var cocoonJS = navigator['isCocoonJS']; + + if (document.readyState === 'complete' || document.readyState === 'interactive') + { + // Why is there an additional timeout here? + window.setTimeout(readyCheck._monitor, 0); + } + else if (cordova && !cocoonJS) + { + // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + // Cordova, but NOT Cocoon? + document.addEventListener('deviceready', readyCheck._monitor, false); + } + else + { + document.addEventListener('DOMContentLoaded', readyCheck._monitor, false); + window.addEventListener('load', readyCheck._monitor, false); + } + } + +}; + +/** +* Internal method used for checking when the device is ready. +* This function is removed from Phaser.Device when the device becomes ready. +* +* @method +* @private +*/ +Phaser.Device._readyCheck = function () { + + var readyCheck = this._readyCheck; + + if (!document.body) + { + window.setTimeout(readyCheck._monitor, 20); + } + else if (!this.deviceReadyAt) + { + this.deviceReadyAt = Date.now(); + + document.removeEventListener('deviceready', readyCheck._monitor); + document.removeEventListener('DOMContentLoaded', readyCheck._monitor); + window.removeEventListener('load', readyCheck._monitor); + + this._initialize(); + this.initialized = true; + + this.onInitialized.dispatch(this); + + var item; + while ((item = readyCheck._queue.shift())) + { + var callback = item[0]; + var context = item[1]; + callback.call(context, this); + } + + // Remove no longer useful methods and properties. + this._readyCheck = null; + this._initialize = null; + this.onInitialized = null; + } + +}; + +/** +* Internal method to initialize the capability checks. +* This function is removed from Phaser.Device once the device is initialized. +* +* @method +* @private +*/ +Phaser.Device._initialize = function () { + + var device = this; + + /** + * Check which OS is game running on. + */ + function _checkOS () { + + var ua = navigator.userAgent; + + if (/Playstation Vita/.test(ua)) + { + device.vita = true; + } + else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua)) + { + device.kindle = true; + // This will NOT detect early generations of Kindle Fire, I think there is no reliable way... + // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true" + } + else if (/Android/.test(ua)) + { + device.android = true; + } + else if (/CrOS/.test(ua)) + { + device.chromeOS = true; + } + else if (/iP[ao]d|iPhone/i.test(ua)) + { + device.iOS = true; + (navigator.appVersion).match(/OS (\d+)/); + device.iOSVersion = parseInt(RegExp.$1, 10); + } + else if (/Linux/.test(ua)) + { + device.linux = true; + } + else if (/Mac OS/.test(ua)) + { + device.macOS = true; + } + else if (/Windows/.test(ua)) + { + device.windows = true; + } + + if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua)) + { + device.android = false; + device.iOS = false; + device.macOS = false; + device.windows = true; + device.windowsPhone = true; + } + + var silk = /Silk/.test(ua); // detected in browsers + + if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS) + { + device.desktop = true; + } + + // Windows Phone / Table reset + if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) + { + device.desktop = false; + } + + } + + /** + * Checks if the browser correctly supports putImageData alpha channels. + * If the browser isn't capable of handling tinting with alpha, `Device.canHandleAlpha` will be false. + * Also checks whether the Canvas BlendModes are supported by the current browser for drawImage. + */ + function _checkCanvasFeatures () { + + var canvas = Phaser.CanvasPool.create(this, 6, 1); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgba(10, 20, 30, 0.5)'; + + // Draw a single pixel + context.fillRect(0, 0, 1, 1); + + // Get the color values + var s1 = context.getImageData(0, 0, 1, 1); + + if (s1) + { + // Plot them to x2 + context.putImageData(s1, 1, 0); + + // Get those values + var s2 = context.getImageData(1, 0, 1, 1); + + // Compare and set + device.canHandleAlpha = ( + s2.data[0] === s1.data[0] && + s2.data[1] === s1.data[1] && + s2.data[2] === s1.data[2] && + s2.data[3] === s1.data[3] + ); + } + + // Checks whether the Canvas BlendModes are supported by the current browser for drawImage. + context.globalCompositeOperation = 'multiply'; + device.canUseMultiply = (context.globalCompositeOperation === 'multiply'); + + Phaser.CanvasPool.removeByCanvas(canvas); + + PIXI.CanvasTinter.tintMethod = (device.canUseMultiply) ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel; + + } + + /** + * Check HTML5 features of the host environment. + */ + function _checkFeatures () { + + device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS; + + try { + device.localStorage = !!localStorage.getItem; + } catch (error) { + device.localStorage = false; + } + + device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; + device.fileSystem = !!window['requestFileSystem']; + + device.webGL = !!window.WebGLRenderingContext; + + device.worker = !!window['Worker']; + + device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; + + device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL; + + // Older versions of firefox (< 21) apparently claim support but user media does not actually work + if (device.firefox && device.firefoxVersion < 21) + { + device.getUserMedia = false; + } + + // TODO: replace canvasBitBltShift detection with actual feature check + + // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it + // is safer to not try and use the fast copy-over method. + if (!device.iOS && (device.ie || device.firefox || device.chrome)) + { + device.canvasBitBltShift = true; + } + + // Known not to work + if (device.safari || device.mobileSafari) + { + device.canvasBitBltShift = false; + } + + } + + /** + * Checks/configures various input. + */ + function _checkInput () { + + if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1)) + { + device.touch = true; + } + + if (window.PointerEvent || window.MSPointerEvent || window.navigator.msPointerEnabled || window.navigator.pointerEnabled) + { + device.mspointer = true; + } + + if (!device.cocoonJS) + { + // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel + if ('onwheel' in window || (device.ie && 'WheelEvent' in window)) + { + // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ + device.wheelEvent = 'wheel'; + } + else if ('onmousewheel' in window) + { + // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. + device.wheelEvent = 'mousewheel'; + } + else if (device.firefox && 'MouseScrollEvent' in window) + { + // FF prior to 17. This should probably be scrubbed. + device.wheelEvent = 'DOMMouseScroll'; + } + } + + } + + /** + * Checks for support of the Full Screen API. + */ + function _checkFullScreenSupport () { + + var fs = [ + 'requestFullscreen', + 'requestFullScreen', + 'webkitRequestFullscreen', + 'webkitRequestFullScreen', + 'msRequestFullscreen', + 'msRequestFullScreen', + 'mozRequestFullScreen', + 'mozRequestFullscreen' + ]; + + var element = document.createElement('div'); + + for (var i = 0; i < fs.length; i++) + { + if (element[fs[i]]) + { + device.fullscreen = true; + device.requestFullscreen = fs[i]; + break; + } + } + + var cfs = [ + 'cancelFullScreen', + 'exitFullscreen', + 'webkitCancelFullScreen', + 'webkitExitFullscreen', + 'msCancelFullScreen', + 'msExitFullscreen', + 'mozCancelFullScreen', + 'mozExitFullscreen' + ]; + + if (device.fullscreen) + { + for (var i = 0; i < cfs.length; i++) + { + if (document[cfs[i]]) + { + device.cancelFullscreen = cfs[i]; + break; + } + } + } + + // Keyboard Input? + if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT']) + { + device.fullscreenKeyboard = true; + } + + } + + /** + * Check what browser is game running in. + */ + function _checkBrowser () { + + var ua = navigator.userAgent; + + if (/Arora/.test(ua)) + { + device.arora = true; + } + else if (/Edge\/\d+/.test(ua)) + { + device.edge = true; + } + else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.chrome = true; + device.chromeVersion = parseInt(RegExp.$1, 10); + } + else if (/Epiphany/.test(ua)) + { + device.epiphany = true; + } + else if (/Firefox\D+(\d+)/.test(ua)) + { + device.firefox = true; + device.firefoxVersion = parseInt(RegExp.$1, 10); + } + else if (/AppleWebKit/.test(ua) && device.iOS) + { + device.mobileSafari = true; + } + else if (/MSIE (\d+\.\d+);/.test(ua)) + { + device.ie = true; + device.ieVersion = parseInt(RegExp.$1, 10); + } + else if (/Midori/.test(ua)) + { + device.midori = true; + } + else if (/Opera/.test(ua)) + { + device.opera = true; + } + else if (/Safari\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.safari = true; + + if (/Version\/(\d+)\./.test(ua)) + { + device.safariVersion = parseInt(RegExp.$1, 10); + } + } + else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua)) + { + device.ie = true; + device.trident = true; + device.tridentVersion = parseInt(RegExp.$1, 10); + device.ieVersion = parseInt(RegExp.$3, 10); + } + + // Silk gets its own if clause because its ua also contains 'Safari' + if (/Silk/.test(ua)) + { + device.silk = true; + } + + // WebApp mode in iOS + if (navigator['standalone']) + { + device.webApp = true; + } + + if (typeof window.cordova !== 'undefined') + { + device.cordova = true; + } + + if (typeof process !== 'undefined' && typeof require !== 'undefined') + { + device.node = true; + } + + if (device.node && typeof process.versions === 'object') + { + device.nodeWebkit = !!process.versions['node-webkit']; + + device.electron = !!process.versions.electron; + } + + if (navigator['isCocoonJS']) + { + device.cocoonJS = true; + } + + if (device.cocoonJS) + { + try { + device.cocoonJSApp = (typeof CocoonJS !== 'undefined'); + } + catch(error) + { + device.cocoonJSApp = false; + } + } + + if (typeof window.ejecta !== 'undefined') + { + device.ejecta = true; + } + + if (/Crosswalk/.test(ua)) + { + device.crosswalk = true; + } + + } + + /** + * Check video support. + */ + function _checkVideo () { + + var videoElement = document.createElement("video"); + var result = false; + + try { + if (result = !!videoElement.canPlayType) + { + if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) + { + device.oggVideo = true; + } + + if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + device.h264Video = true; + device.mp4Video = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) + { + device.webmVideo = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) + { + device.vp9Video = true; + } + + if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + device.hlsVideo = true; + } + } + } catch (e) {} + } + + /** + * Check audio support. + */ + function _checkAudio () { + + device.audioData = !!(window['Audio']); + device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); + var audioElement = document.createElement('audio'); + var result = false; + + try { + if (result = !!audioElement.canPlayType) + { + if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) + { + device.ogg = true; + } + + if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) + { + device.opus = true; + } + + if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) + { + device.mp3 = true; + } + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) + { + device.wav = true; + } + + if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) + { + device.m4a = true; + } + + if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) + { + device.webm = true; + } + + if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') + { + if (device.edge) + { + device.dolby = true; + } + else if (device.safari && device.safariVersion >= 9) + { + if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)) + { + var major = parseInt(RegExp.$1, 10); + var minor = parseInt(RegExp.$2, 10); + + if ((major === 10 && minor >= 11) || major > 10) + { + device.dolby = true; + } + } + } + } + } + } catch (e) { + } + + } + + /** + * Check Little or Big Endian system. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsLittleEndian () { + + var a = new ArrayBuffer(4); + var b = new Uint8Array(a); + var c = new Uint32Array(a); + + b[0] = 0xa1; + b[1] = 0xb2; + b[2] = 0xc3; + b[3] = 0xd4; + + if (c[0] === 0xd4c3b2a1) + { + return true; + } + + if (c[0] === 0xa1b2c3d4) + { + return false; + } + else + { + // Could not determine endianness + return null; + } + + } + + /** + * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsUint8ClampedImageData () { + + if (Uint8ClampedArray === undefined) + { + return false; + } + + var elem = Phaser.CanvasPool.create(this, 1, 1); + var ctx = elem.getContext('2d'); + + if (!ctx) + { + return false; + } + + var image = ctx.createImageData(1, 1); + + Phaser.CanvasPool.remove(this); + + return image.data instanceof Uint8ClampedArray; + + } + + /** + * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess. + */ + function _checkDevice () { + + device.pixelRatio = window['devicePixelRatio'] || 1; + device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1; + device.iPhone4 = (device.pixelRatio === 2 && device.iPhone); + device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') !== -1; + + if (typeof Int8Array !== 'undefined') + { + device.typedArray = true; + } + else + { + device.typedArray = false; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') + { + device.littleEndian = _checkIsLittleEndian(); + device.LITTLE_ENDIAN = device.littleEndian; + } + + device.support32bit = (typeof ArrayBuffer !== 'undefined' && typeof Uint8ClampedArray !== 'undefined' && typeof Int32Array !== 'undefined' && device.littleEndian !== null && _checkIsUint8ClampedImageData()); + + navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; + + if (navigator.vibrate) + { + device.vibration = true; + } + + } + + /** + * Check whether the host environment support 3D CSS. + */ + function _checkCSS3D () { + + var el = document.createElement('p'); + var has3d; + var transforms = { + 'webkitTransform': '-webkit-transform', + 'OTransform': '-o-transform', + 'msTransform': '-ms-transform', + 'MozTransform': '-moz-transform', + 'transform': 'transform' + }; + + // Add it to the body to get the computed style. + document.body.insertBefore(el, null); + + for (var t in transforms) + { + if (el.style[t] !== undefined) + { + el.style[t] = "translate3d(1px,1px,1px)"; + has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]); + } + } + + document.body.removeChild(el); + device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none"); + + } + + // Run the checks + _checkOS(); + _checkBrowser(); + _checkAudio(); + _checkVideo(); + _checkCSS3D(); + _checkDevice(); + _checkFeatures(); + _checkCanvasFeatures(); + _checkFullScreenSupport(); + _checkInput(); + +}; + +/** +* Check whether the host environment can play audio. +* +* @method canPlayAudio +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.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 === 'opus' && this.opus) + { + return true; + } + else if (type === 'wav' && this.wav) + { + return true; + } + else if (type === 'webm' && this.webm) + { + return true; + } + else if (type === 'mp4' && this.dolby) + { + return true; + } + + return false; + +}; + +/** +* Check whether the host environment can play video files. +* +* @method canPlayVideo +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.canPlayVideo = function (type) { + + if (type === 'webm' && (this.webmVideo || this.vp9Video)) + { + return true; + } + else if (type === 'mp4' && (this.mp4Video || this.h264Video)) + { + return true; + } + else if ((type === 'ogg' || type === 'ogv') && this.oggVideo) + { + return true; + } + else if (type === 'mpeg' && this.hlsVideo) + { + return true; + } + + return false; + +}; + +/** + * Whether the device plays audio/video only in response to a user touch event. + * + * @method needsTouchUnlock + * @memberof Phaser.Device.prototype + * @return {boolean} + */ +Phaser.Device.needsTouchUnlock = function () { + return !!(!this.cocoonJS && (this.iOS || this.android) || (window.PhaserGlobal && window.PhaserGlobal.fakeiOSTouchLock)); +}; + +/** +* Detect if the host is a an Android Stock browser. +* This is available before the device "ready" event. +* +* Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. +* +* @example +* var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; +* +* @method isAndroidStockBrowser +* @memberof Phaser.Device.prototype +*/ +Phaser.Device.isAndroidStockBrowser = function () { + + var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/); + return matches && matches[1] < 537; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, +* including styles, offset and aspect ratio. +* +* @class Phaser.Canvas +* @static +*/ +Phaser.Canvas = { + + /** + * Creates a `canvas` DOM element. The element is not automatically added to the document. + * + * @method Phaser.Canvas.create + * @param {object} parent - The object that will own the canvas that is created. + * @param {number} [width=256] - The width of the canvas element. + * @param {number} [height=256] - The height of the canvas element.. + * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. + * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global. + * @return {HTMLCanvasElement} The newly created canvas element. + */ + create: function (parent, width, height, id, skipPool) { + + width = width || 256; + height = height || 256; + + var canvas = (skipPool) ? document.createElement('canvas') : Phaser.CanvasPool.create(parent, width, height); + + if (typeof id === 'string' && id !== '') + { + canvas.id = id; + } + + canvas.width = width; + canvas.height = height; + canvas.style.display = 'block'; + + return canvas; + + }, + + /** + * Sets the background color behind the canvas. This changes the canvas style property. + * + * @method Phaser.Canvas.setBackgroundColor + * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. + * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setBackgroundColor: function (canvas, color) { + + color = color || 'rgb(0,0,0)'; + + canvas.style.backgroundColor = color; + + return canvas; + + }, + + /** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @method Phaser.Canvas.setTouchAction + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @method Phaser.Canvas.setUserSelect + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. + * If no parent is given it will be added as a child of the document.body. + * + * @method Phaser.Canvas.addToDOM + * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM. + * @param {string|HTMLElement} parent - The DOM element to add the canvas to. + * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + addToDOM: function (canvas, parent, overflowHidden) { + + var target; + + if (overflowHidden === undefined) { overflowHidden = true; } + + if (parent) + { + if (typeof parent === 'string') + { + // hopefully an element ID + target = document.getElementById(parent); + } + else if (typeof parent === 'object' && parent.nodeType === 1) + { + // quick test for a HTMLelement + target = parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + target = document.body; + } + + if (overflowHidden && target.style) + { + target.style.overflow = 'hidden'; + } + + target.appendChild(canvas); + + return canvas; + + }, + + /** + * Removes the given canvas element from the DOM. + * + * @method Phaser.Canvas.removeFromDOM + * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM. + */ + removeFromDOM: function (canvas) { + + if (canvas.parentNode) + { + canvas.parentNode.removeChild(canvas); + } + + }, + + /** + * Sets the transform of the given canvas to the matrix values provided. + * + * @method Phaser.Canvas.setTransform + * @param {CanvasRenderingContext2D} context - The context to set the transform on. + * @param {number} translateX - The value to translate horizontally by. + * @param {number} translateY - The value to translate vertically by. + * @param {number} scaleX - The value to scale horizontally by. + * @param {number} scaleY - The value to scale vertically by. + * @param {number} skewX - The value to skew horizontaly by. + * @param {number} skewY - The value to skew vertically by. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) { + + context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); + + return context; + + }, + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @method Phaser.Canvas.setSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setSmoothingEnabled: function (context, value) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + context[s] = value; + } + + return context; + + }, + + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @method Phaser.Canvas.getSmoothingPrefix + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context. + */ + getSmoothingPrefix: function (context) { + + var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; + + for (var prefix in vendor) + { + var s = vendor[prefix] + 'mageSmoothingEnabled'; + + if (s in context) + { + return s; + } + } + + return null; + + }, + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * + * @method Phaser.Canvas.getSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to check for smoothing on. + * @return {boolean} True if the given context has image smoothing enabled, otherwise false. + */ + getSmoothingEnabled: function (context) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + return context[s]; + } + + }, + + /** + * Sets the CSS image-rendering property to `pixelated` or `crisp-edges`. + * This can remove blurring when the game canvas is scaled up. + * In some browsers this has no visible effect in WEBGL mode. + * Note that if this doesn't given the desired result then see the setSmoothingEnabled. + * + * @method Phaser.Canvas.setImageRenderingCrisp + * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. + * @return {HTMLCanvasElement} Returns the source canvas. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering + * @see https://caniuse.com/#feat=css-crisp-edges + */ + setImageRenderingCrisp: function (canvas) { + + var types = [ '-webkit-optimize-contrast', '-moz-crisp-edges', 'crisp-edges', 'pixelated' ]; + + for (var i = 0; i < types.length; i++) + { + canvas.style['image-rendering'] = types[i]; + } + + canvas.style.msInterpolationMode = 'nearest-neighbor'; + + return canvas; + + }, + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method Phaser.Canvas.setImageRenderingBicubic + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setImageRenderingBicubic: function (canvas) { + + canvas.style['image-rendering'] = 'auto'; + canvas.style.msInterpolationMode = 'bicubic'; + + return canvas; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Abstracts away the use of RAF or setTimeOut for the core game update loop. +* +* @class Phaser.RequestAnimationFrame +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available. +*/ +Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) { + + if (forceSetTimeOut === undefined) { forceSetTimeOut = false; } + + /** + * @property {Phaser.Game} game - The currently running game. + */ + this.game = game; + + /** + * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available. + */ + this.forceSetTimeOut = forceSetTimeOut; + + var vendors = [ + 'ms', + 'moz', + 'webkit', + 'o' + ]; + + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) + { + window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; + } + + /** + * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. + * @private + */ + this._isSetTimeOut = false; + + /** + * @property {function} _onLoop - The function called by the update. + * @private + */ + this._onLoop = null; + + /** + * @property {number} _timeOutID - The callback ID used when calling cancel. + * @private + */ + this._timeOutID = null; + +}; + +Phaser.RequestAnimationFrame.prototype = { + + /** + * Starts the requestAnimationFrame running or setTimeout if unavailable in browser + * @method Phaser.RequestAnimationFrame#start + */ + start: function () { + + this.isRunning = true; + + var _this = this; + + if (!window.requestAnimationFrame || this.forceSetTimeOut) + { + this._isSetTimeOut = true; + + this._onLoop = function () { + return _this.updateSetTimeout(); + }; + + this._timeOutID = window.setTimeout(this._onLoop, 0); + } + else + { + this._isSetTimeOut = false; + + this._onLoop = function (time) { + return _this.updateRAF(time); + }; + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the requestAnimationFrame + * @method Phaser.RequestAnimationFrame#updateRAF + */ + updateRAF: function (rafTime) { + + if (this.isRunning) + { + // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below) + this.game.update(Math.floor(rafTime)); + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the setTimeout. + * @method Phaser.RequestAnimationFrame#updateSetTimeout + */ + updateSetTimeout: function () { + + if (this.isRunning) + { + this.game.update(Date.now()); + + this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); + } + + }, + + /** + * Stops the requestAnimationFrame from running. + * @method Phaser.RequestAnimationFrame#stop + */ + stop: function () { + + if (this._isSetTimeOut) + { + clearTimeout(this._timeOutID); + } + else + { + window.cancelAnimationFrame(this._timeOutID); + } + + this.isRunning = false; + + }, + + /** + * Is the browser using setTimeout? + * @method Phaser.RequestAnimationFrame#isSetTimeOut + * @return {boolean} + */ + isSetTimeOut: function () { + return this._isSetTimeOut; + }, + + /** + * Is the browser using requestAnimationFrame? + * @method Phaser.RequestAnimationFrame#isRAF + * @return {boolean} + */ + isRAF: function () { + return (this._isSetTimeOut === false); + } + +}; + +Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of useful mathematical functions. +* +* These are normally accessed through `game.math`. +* +* @class Phaser.Math +* @static +* @see {@link Phaser.Utils} +* @see {@link Phaser.ArrayUtils} +*/ +Phaser.Math = { + + /** + * Twice PI. + * @property {number} Phaser.Math#PI2 + * @default ~6.283 + */ + PI2: Math.PI * 2, + + /** + * Half PI. + * @property {number} Phaser.Math#HALF_PI + * @default ~1.570 + */ + HALF_PI: Math.PI * 0.5, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#DEG_TO_RAD + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#RAD_TO_DEG + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * Convert degrees to radians. + * + * @method Phaser.Math#degToRad + * @param {number} degrees - Angle in degrees. + * @return {number} Angle in radians. + */ + degToRad: function (degrees) { + + return degrees * Phaser.Math.DEG_TO_RAD; + + }, + + /** + * Convert radians to degrees. + * + * @method Phaser.Math#radToDeg + * @param {number} radians - Angle in radians. + * @return {number} Angle in degrees + */ + radToDeg: function (radians) { + + return radians * Phaser.Math.RAD_TO_DEG; + + }, + + /** + * Given a number, this function returns the closest number that is a power of two. + * This function is from the Starling Framework. + * + * @method Phaser.Math#getNextPowerOfTwo + * @param {number} value - The value to get the closest power of two from. + * @return {number} The closest number that is a power of two. + */ + getNextPowerOfTwo: function (value) { + + if (value > 0 && (value & (value - 1)) === 0) + { + // http://goo.gl/D9kPj + return value; + } + else + { + var result = 1; + + while (result < value) + { + result <<= 1; + } + + return result; + } + + }, + + /** + * Checks if the given dimensions make a power of two texture. + * + * @method Phaser.Math#isPowerOfTwo + * @param {number} width - The width to check. + * @param {number} height - The height to check. + * @return {boolean} True if the width and height are a power of two. + */ + isPowerOfTwo: function (width, height) { + + return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); + + }, + + /** + * Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#random + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} A floating point number between min (inclusive) and max (exclusive). + */ + random: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + return (Math.random() * (max - min) + min); + + }, + + /** + * Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#between + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} An integer between min (inclusive) and max (inclusive). + */ + between: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + min = Math.ceil(min); + max = Math.floor(max); + + return Math.floor(Math.random() * (max - min + 1)) + min; + + }, + + /** + * Two number are fuzzyEqual if their difference is less than epsilon. + * + * @method Phaser.Math#fuzzyEqual + * @param {number} a - The first number to compare. + * @param {number} b - The second number to compare. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {boolean} True if |a-b|b+epsilon + */ + fuzzyGreaterThan: function (a, b, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return a > b - epsilon; + + }, + + /** + * Applies a fuzzy ceil to the given value. + * + * @method Phaser.Math#fuzzyCeil + * @param {number} val - The value to ceil. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} ceiling(val-epsilon) + */ + fuzzyCeil: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.ceil(val - epsilon); + + }, + + /** + * Applies a fuzzy floor to the given value. + * + * @method Phaser.Math#fuzzyFloor + * @param {number} val - The value to floor. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} floor(val+epsilon) + */ + fuzzyFloor: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.floor(val + epsilon); + + }, + + /** + * Averages all values passed to the function and returns the result. + * + * @method Phaser.Math#average + * @params {...number} The numbers to average + * @return {number} The average of all given values. + */ + average: function () { + + var sum = 0; + var len = arguments.length; + + for (var i = 0; i < len; i++) + { + sum += (+arguments[i]); + } + + return sum / len; + + }, + + /** + * @method Phaser.Math#shear + * @param {number} n + * @return {number} n mod 1 + */ + shear: function (n) { + + return n % 1; + + }, + + /** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. + * + * @method Phaser.Math#snapTo + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapTo: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.round(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. + * As will 14 snap to 10... but 16 will snap to 15. + * + * @method Phaser.Math#snapToFloor + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToFloor: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.floor(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. + * As will 14 will snap to 15... but 16 will snap to 20. + * + * @method Phaser.Math#snapToCeil + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToCeil: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.ceil(input / gap); + + return start + input; + + }, + + /** + * Round to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) === 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + * + * @method Phaser.Math#roundTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + roundTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.round(value * p) / p; + + }, + + /** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#floorTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + floorTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.floor(value * p) / p; + + }, + + /** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#ceilTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + ceilTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.ceil(value * p) / p; + + }, + + /** + * Rotates currentAngle towards targetAngle, taking the shortest rotation distance. + * The lerp argument is the amount to rotate by in this call. + * + * @method Phaser.Math#rotateToAngle + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * @return {number} The adjusted angle. + */ + rotateToAngle: function (currentAngle, targetAngle, lerp) { + + if (lerp === undefined) { lerp = 0.05; } + + if (currentAngle === targetAngle) + { + return currentAngle; + } + + if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (Phaser.Math.PI2 - lerp)) + { + currentAngle = targetAngle; + } + else + { + if (Math.abs(targetAngle - currentAngle) > Math.PI) + { + if (targetAngle < currentAngle) + { + targetAngle += Phaser.Math.PI2; + } + else + { + targetAngle -= Phaser.Math.PI2; + } + } + + if (targetAngle > currentAngle) + { + currentAngle += lerp; + } + else if (targetAngle < currentAngle) + { + currentAngle -= lerp; + } + } + + return currentAngle; + + }, + + /** + * Gets the shortest angle between `angle1` and `angle2`. + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method, and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * @method Phaser.Math#getShortestAngle + * @param {number} angle1 - The first angle. In the range -180 to 180. + * @param {number} angle2 - The second angle. In the range -180 to 180. + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ + getShortestAngle: function (angle1, angle2) { + + var difference = angle2 - angle1; + + if (difference === 0) + { + return 0; + } + + var times = Math.floor((difference - (-180)) / 360); + + return difference - (times * 360); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @method Phaser.Math#angleBetween + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetween: function (x1, y1, x2, y2) { + + return Math.atan2(y2 - y1, x2 - x1); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels + * down the screen. + * + * @method Phaser.Math#angleBetweenY + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetweenY: function (x1, y1, x2, y2) { + + return Math.atan2(x2 - x1, y2 - y1); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * @method Phaser.Math#angleBetweenPoints + * @param {Phaser.Point} point1 - The first point. + * @param {Phaser.Point} point2 - The second point. + * @return {number} The angle between the two points, in radians. + */ + angleBetweenPoints: function (point1, point2) { + + return Math.atan2(point2.y - point1.y, point2.x - point1.x); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * @method Phaser.Math#angleBetweenPointsY + * @param {Phaser.Point} point1 + * @param {Phaser.Point} point2 + * @return {number} The angle, in radians. + */ + angleBetweenPointsY: function (point1, point2) { + + return Math.atan2(point2.x - point1.x, point2.y - point1.y); + + }, + + /** + * Reverses an angle. + * @method Phaser.Math#reverseAngle + * @param {number} angleRad - The angle to reverse, in radians. + * @return {number} The reverse angle, in radians. + */ + reverseAngle: function (angleRad) { + + return this.normalizeAngle(angleRad + Math.PI, true); + + }, + + /** + * Normalizes an angle to the [0,2pi) range. + * @method Phaser.Math#normalizeAngle + * @param {number} angleRad - The angle to normalize, in radians. + * @return {number} The angle, fit within the [0,2pi] range, in radians. + */ + normalizeAngle: function (angleRad) { + + angleRad = angleRad % (2 * Math.PI); + return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI; + + }, + + /** + * Adds the given amount to the value, but never lets the value go over the specified maximum. + * + * @method Phaser.Math#maxAdd + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The new value. + */ + maxAdd: function (value, amount, max) { + + return Math.min(value + amount, max); + + }, + + /** + * Subtracts the given amount from the value, but never lets the value go below the specified minimum. + * + * @method Phaser.Math#minSub + * @param {number} value - The base value. + * @param {number} amount - The amount to subtract from the base value. + * @param {number} min - The minimum the value is allowed to be. + * @return {number} The new value. + */ + minSub: function (value, amount, min) { + + return Math.max(value - amount, min); + + }, + + /** + * Ensures that the value always stays between min and max, by wrapping the value around. + * + * If `max` is not larger than `min` the result is 0. + * + * @method Phaser.Math#wrap + * @param {number} value - The value to wrap. + * @param {number} min - The minimum the value is allowed to be. + * @param {number} max - The maximum the value is allowed to be, should be larger than `min`. + * @return {number} The wrapped value. + */ + wrap: function (value, min, max) { + + var range = max - min; + + if (range <= 0) + { + return 0; + } + + var result = (value - min) % range; + + if (result < 0) + { + result += range; + } + + return result + min; + + }, + + /** + * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. + * + * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. + * + * @method Phaser.Math#wrapValue + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The wrapped value. + */ + wrapValue: function (value, amount, max) { + + var diff; + value = Math.abs(value); + amount = Math.abs(amount); + max = Math.abs(max); + diff = (value + amount) % max; + + return diff; + + }, + + /** + * Returns true if the number given is odd. + * + * @method Phaser.Math#isOdd + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is odd. False if the given number is even. + */ + isOdd: function (n) { + + // Does not work with extremely large values + return !!(n & 1); + + }, + + /** + * Returns true if the number given is even. + * + * @method Phaser.Math#isEven + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is even. False if the given number is odd. + */ + isEven: function (n) { + + // Does not work with extremely large values + return !(n & 1); + + }, + + /** + * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.min` function when appropriate. + * + * @method Phaser.Math#min + * @return {number} The lowest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + 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; i < len; i++) + { + if (data[i] < data[min]) + { + min = i; + } + } + + return data[min]; + + }, + + /** + * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.max` function when appropriate. + * + * @method Phaser.Math#max + * @return {number} The largest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + max: function () { + + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + var data = arguments[0]; + } + else + { + var data = arguments; + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i] > data[max]) + { + max = i; + } + } + + return data[max]; + + }, + + /** + * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. + * It will find the lowest matching property value from the given objects. + * + * @method Phaser.Math#minProperty + * @return {number} The lowest value from those given. + */ + 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; i < len; i++) + { + if (data[i][property] < data[min][property]) + { + min = i; + } + } + + return data[min][property]; + + }, + + /** + * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. + * It will find the largest matching property value from the given objects. + * + * @method Phaser.Math#maxProperty + * @return {number} The largest value from those given. + */ + maxProperty: function (property) { + + if (arguments.length === 2 && typeof arguments[1] === 'object') + { + var data = arguments[1]; + } + else + { + var data = arguments.slice(1); + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i][property] > data[max][property]) + { + max = i; + } + } + + return data[max][property]; + + }, + + /** + * Keeps an angle value between -180 and +180; or -PI and PI if radians. + * + * @method Phaser.Math#wrapAngle + * @param {number} angle - The angle value to wrap + * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected. + * @return {number} The new angle value; will be the same as the input angle if it was within bounds. + */ + wrapAngle: function (angle, radians) { + + return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180); + + }, + + /** + * A Linear Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#linearInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + linearInterpolation: function (v, k) { + + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (k < 0) + { + return this.linear(v[0], v[1], f); + } + + if (k > 1) + { + return this.linear(v[m], v[m - 1], m - f); + } + + return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); + + }, + + /** + * A Bezier Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#bezierInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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; + + }, + + /** + * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#catmullRomInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + } + + }, + + /** + * Calculates a linear (interpolation) value over t. + * + * @method Phaser.Math#linear + * @param {number} p0 + * @param {number} p1 + * @param {number} t - A value between 0 and 1. + * @return {number} + */ + linear: function (p0, p1, t) { + + return (p1 - p0) * t + p0; + + }, + + /** + * @method Phaser.Math#bernstein + * @protected + * @param {number} n + * @param {number} i + * @return {number} + */ + bernstein: function (n, i) { + + return this.factorial(n) / this.factorial(i) / this.factorial(n - i); + + }, + + /** + * @method Phaser.Math#factorial + * @param {number} value - the number you want to evaluate + * @return {number} + */ + factorial: function (value) { + + if (value === 0) + { + return 1; + } + + var res = value; + + while(--value) + { + res *= value; + } + + return res; + + }, + + /** + * Calculates a catmum rom value. + * + * @method Phaser.Math#catmullRom + * @protected + * @param {number} p0 + * @param {number} p1 + * @param {number} p2 + * @param {number} p3 + * @param {number} t + * @return {number} + */ + catmullRom: function (p0, p1, p2, p3, t) { + + var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + + }, + + /** + * The absolute difference between two values. + * + * @method Phaser.Math#difference + * @param {number} a - The first value to check. + * @param {number} b - The second value to check. + * @return {number} The absolute difference between the two values. + */ + difference: function (a, b) { + + return Math.abs(a - b); + + }, + + /** + * Round to the next whole number _away_ from zero. + * + * @method Phaser.Math#roundAwayFromZero + * @param {number} value - Any number. + * @return {integer} The rounded value of that number. + */ + roundAwayFromZero: function (value) { + + // "Opposite" of truncate. + return (value > 0) ? Math.ceil(value) : Math.floor(value); + + }, + + /** + * Generate a sine and cosine table simultaneously and extremely quickly. + * The parameters allow you to specify the length, amplitude and frequency of the wave. + * This generator is fast enough to be used in real-time. + * Code based on research by Franky of scene.at + * + * @method Phaser.Math#sinCosGenerator + * @param {number} length - The length of the wave + * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} frequency - The frequency of the sine and cosine table data + * @return {{sin:number[], cos:number[]}} Returns the table data. + */ + sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) { + + if (sinAmplitude === undefined) { sinAmplitude = 1.0; } + if (cosAmplitude === undefined) { cosAmplitude = 1.0; } + if (frequency === undefined) { frequency = 1.0; } + + var sin = sinAmplitude; + var cos = cosAmplitude; + var frq = frequency * Math.PI / length; + + var cosTable = []; + var sinTable = []; + + for (var c = 0; c < length; c++) { + + cos -= sin * frq; + sin += cos * frq; + + cosTable[c] = cos; + sinTable[c] = sin; + + } + + return { sin: sinTable, cos: cosTable, length: length }; + + }, + + /** + * Returns the length of the hypotenuse connecting two segments of given lengths. + * + * @method Phaser.Math#hypot + * @param {number} a + * @param {number} b + * @return {number} The length of the hypotenuse connecting the given lengths. + */ + hypot: function (a, b) { + + return Math.sqrt(a * a + b * b); + + }, + + /** + * Returns the euclidian distance between the two given set of coordinates. + * + * @method Phaser.Math#distance + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance between the two sets of coordinates. + */ + distance: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Returns the euclidean distance squared between the two given set of + * coordinates (cuts out a square root operation before returning). + * + * @method Phaser.Math#distanceSq + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance squared between the two sets of coordinates. + */ + distanceSq: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return dx * dx + dy * dy; + + }, + + /** + * Returns the distance between the two given set of coordinates at the power given. + * + * @method Phaser.Math#distancePow + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} [pow=2] + * @return {number} The distance between the two sets of coordinates. + */ + distancePow: function (x1, y1, x2, y2, pow) { + + if (pow === undefined) { pow = 2; } + + return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); + + }, + + /** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @method Phaser.Math#clamp + * @param {float} v - The value to be clamped. + * @param {float} min - The minimum bounds. + * @param {float} max - The maximum bounds. + * @return {number} The clamped value. + */ + clamp: function (v, min, max) { + + if (v < min) + { + return min; + } + else if (max < v) + { + return max; + } + else + { + return v; + } + + }, + + /** + * Clamp `x` to the range `[a, Infinity)`. + * Roughly the same as `Math.max(x, a)`, except for NaN handling. + * + * @method Phaser.Math#clampBottom + * @param {number} x + * @param {number} a + * @return {number} + */ + clampBottom: function (x, a) { + + return x < a ? a : x; + + }, + + /** + * Checks if two values are within the given tolerance of each other. + * + * @method Phaser.Math#within + * @param {number} a - The first number to check + * @param {number} b - The second number to check + * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range. + * @return {boolean} True if a is <= tolerance of b. + * @see {@link Phaser.Math.fuzzyEqual} + */ + within: function (a, b, tolerance) { + + return (Math.abs(a - b) <= tolerance); + + }, + + /** + * Linear mapping from range to range + * + * @method Phaser.Math#mapLinear + * @param {number} x - The value to map + * @param {number} a1 - First endpoint of the range + * @param {number} a2 - Final endpoint of the range + * @param {number} b1 - First endpoint of the range + * @param {number} b2 - Final endpoint of the range + * @return {number} + */ + mapLinear: function (x, a1, a2, b1, b2) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + + }, + + /** + * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smoothstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smoothstep: function (x, min, max) { + + // Scale, bias and saturate x to 0..1 range + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + // Evaluate polynomial + return x * x * (3 - 2 * x); + + }, + + /** + * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smootherstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smootherstep: function (x, min, max) { + + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + return x * x * x * (x * (x * 6 - 15) + 10); + + }, + + /** + * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. + * + * This works differently from `Math.sign` for values of NaN and -0, etc. + * + * @method Phaser.Math#sign + * @param {number} x + * @return {integer} An integer in {-1, 0, 1} + */ + sign: function (x) { + + return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); + + }, + + /** + * Work out what percentage value `a` is of value `b` using the given base. + * + * @method Phaser.Math#percent + * @param {number} a - The value to work out the percentage for. + * @param {number} b - The value you wish to get the percentage of. + * @param {number} [base=0] - The base value. + * @return {number} The percentage a is of b, between 0 and 1. + */ + percent: function (a, b, base) { + + if (base === undefined) { base = 0; } + + if (a > b || base > b) + { + return 1; + } + else if (a < base || base > a) + { + return 0; + } + else + { + return (a - base) / b; + } + + } + +}; + +/* jshint noempty: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An extremely useful repeatable random data generator. +* +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. +* +* The random number genererator is based on the Alea PRNG, but is modified. +* - https://github.com/coverslide/node-alea +* - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror +* - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404) +* +* @class Phaser.RandomDataGenerator +* @constructor +* @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}). +*/ +Phaser.RandomDataGenerator = function (seeds) { + + if (seeds === undefined) { seeds = []; } + + /** + * @property {number} c - Internal var. + * @private + */ + this.c = 1; + + /** + * @property {number} s0 - Internal var. + * @private + */ + this.s0 = 0; + + /** + * @property {number} s1 - Internal var. + * @private + */ + this.s1 = 0; + + /** + * @property {number} s2 - Internal var. + * @private + */ + this.s2 = 0; + + if (typeof seeds === 'string') + { + this.state(seeds); + } + else + { + this.sow(seeds); + } + +}; + +Phaser.RandomDataGenerator.prototype = { + + /** + * Private random helper. + * + * @method Phaser.RandomDataGenerator#rnd + * @private + * @return {number} + */ + rnd: function () { + + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + + return this.s2; + }, + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.RandomDataGenerator#sow + * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used. + */ + sow: function (seeds) { + + // Always reset to default seed + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + this.c = 1; + + if (!seeds) + { + return; + } + + // Apply any seeds + for (var i = 0; i < seeds.length && (seeds[i] != null); i++) + { + var 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); + } + + }, + + /** + * Internal method that creates a seed hash. + * + * @method Phaser.RandomDataGenerator#hash + * @private + * @param {any} data + * @return {number} hashed value. + */ + hash: function (data) { + + var h, i, n; + n = 0xefc8249d; + data = data.toString(); + + for (i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } + + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + + }, + + /** + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#integer + * @return {number} A random integer between 0 and 2^32. + */ + integer: function() { + + return this.rnd.apply(this) * 0x100000000;// 2^32 + + }, + + /** + * Returns a random real number between 0 and 1. + * + * @method Phaser.RandomDataGenerator#frac + * @return {number} A random real number between 0 and 1. + */ + frac: function() { + + return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 + + }, + + /** + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#real + * @return {number} A random real number between 0 and 2^32. + */ + real: function() { + + return this.integer() + this.frac(); + + }, + + /** + * Returns a random integer between and including min and max. + * + * @method Phaser.RandomDataGenerator#integerInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + integerInRange: function (min, max) { + + return Math.floor(this.realInRange(0, max - min + 1) + min); + + }, + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.RandomDataGenerator#between + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + between: function (min, max) { + + return this.integerInRange(min, max); + + }, + + /** + * Returns a random real number between min and max. + * + * @method Phaser.RandomDataGenerator#realInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + realInRange: function (min, max) { + + return this.frac() * (max - min) + min; + + }, + + /** + * Returns a random real number between -1 and 1. + * + * @method Phaser.RandomDataGenerator#normal + * @return {number} A random real number between -1 and 1. + */ + normal: function () { + + return 1 - 2 * this.frac(); + + }, + + /** + * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 + * + * @method Phaser.RandomDataGenerator#uuid + * @return {string} A valid RFC4122 version4 ID hex string + */ + 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; + + }, + + /** + * Returns a random member of `array`. + * + * @method Phaser.RandomDataGenerator#pick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + pick: function (ary) { + + return ary[this.integerInRange(0, ary.length - 1)]; + + }, + + /** + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.RandomDataGenerator#sign + * @return {number} -1 or +1. + */ + sign: function () { + + return this.pick([-1, 1]); + + }, + + /** + * Returns a random member of `array`, favoring the earlier entries. + * + * @method Phaser.RandomDataGenerator#weightedPick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + weightedPick: function (ary) { + + return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)]; + + }, + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.RandomDataGenerator#timestamp + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random timestamp between min and max. + */ + timestamp: function (min, max) { + + return this.realInRange(min || 946684800000, max || 1577862000000); + + }, + + /** + * Returns a random angle between -180 and 180. + * + * @method Phaser.RandomDataGenerator#angle + * @return {number} A random number between -180 and 180. + */ + angle: function() { + + return this.integerInRange(-180, 180); + + }, + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.RandomDataGenerator#state + * @param {string} [state] - Generator state to be set. + * @return {string} The current state of the generator. + */ + state: function (state) { + + if (typeof state === 'string' && state.match(/^!rnd/)) + { + state = state.split(','); + + this.c = parseFloat(state[1]); + this.s0 = parseFloat(state[2]); + this.s1 = parseFloat(state[3]); + this.s2 = parseFloat(state[4]); + } + + return ['!rnd', this.c, this.s0, this.s1, this.s2].join(','); + + } + +}; + +Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator; + +/** + * @author Timo Hausmann + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** +* A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. +* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. +* Original version at https://github.com/timohausmann/quadtree-js/ +* +* @class Phaser.QuadTree +* @constructor +* @param {number} x - The top left coordinate of the quadtree. +* @param {number} y - The top left coordinate of the quadtree. +* @param {number} width - The width of the quadtree in pixels. +* @param {number} height - The height of the quadtree in pixels. +* @param {number} [maxObjects=10] - The maximum number of objects per node. +* @param {number} [maxLevels=4] - The maximum number of levels to iterate to. +* @param {number} [level=0] - Which level is this? +*/ +Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) { + + /** + * @property {number} maxObjects - The maximum number of objects per node. + * @default + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - The maximum number of levels to break down to. + * @default + */ + this.maxLevels = 4; + + /** + * @property {number} level - The current level. + */ + this.level = 0; + + /** + * @property {object} bounds - Object that contains the quadtree bounds. + */ + this.bounds = {}; + + /** + * @property {array} objects - Array of quadtree children. + */ + this.objects = []; + + /** + * @property {array} nodes - Array of associated child nodes. + */ + this.nodes = []; + + /** + * @property {array} _empty - Internal empty array. + * @private + */ + this._empty = []; + + this.reset(x, y, width, height, maxObjects, maxLevels, level); + +}; + +Phaser.QuadTree.prototype = { + + /** + * Resets the QuadTree. + * + * @method Phaser.QuadTree#reset + * @param {number} x - The top left coordinate of the quadtree. + * @param {number} y - The top left coordinate of the quadtree. + * @param {number} width - The width of the quadtree in pixels. + * @param {number} height - The height of the quadtree in pixels. + * @param {number} [maxObjects=10] - The maximum number of objects per node. + * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. + * @param {number} [level=0] - Which level is this? + */ + 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; + + }, + + /** + * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. + * + * @method Phaser.QuadTree#populate + * @param {Phaser.Group} group - The Group to add to the quadtree. + */ + populate: function (group) { + + group.forEach(this.populateHandler, this, true); + + }, + + /** + * Handler for the populate method. + * + * @method Phaser.QuadTree#populateHandler + * @param {Phaser.Sprite|object} sprite - The Sprite to check. + */ + populateHandler: function (sprite) { + + if (sprite.body && sprite.exists) + { + this.insert(sprite.body); + } + + }, + + /** + * Split the node into 4 subnodes + * + * @method Phaser.QuadTree#split + */ + split: function () { + + // top right node + this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // top left node + this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom left node + this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom right node + this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + }, + + /** + * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. + * + * @method Phaser.QuadTree#insert + * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. + */ + insert: function (body) { + + var i = 0; + var index; + + // if we have subnodes ... + 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.level < this.maxLevels) + { + // Split if we don't already have subnodes + if (this.nodes[0] == null) + { + this.split(); + } + + // Add objects to subnodes + while (i < this.objects.length) + { + index = this.getIndex(this.objects[i]); + + if (index !== -1) + { + // this is expensive - see what we can do about it + this.nodes[index].insert(this.objects.splice(i, 1)[0]); + } + else + { + i++; + } + } + } + + }, + + /** + * Determine which node the object belongs to. + * + * @method Phaser.QuadTree#getIndex + * @param {Phaser.Rectangle|object} rect - The bounds in which to check. + * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. + */ + getIndex: function (rect) { + + // default is that rect doesn't fit, i.e. it straddles the internal quadrants + var index = -1; + + if (rect.x < this.bounds.right && rect.right < this.bounds.right) + { + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-left quadrant of this quadtree + index = 1; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-left quadrant of this quadtree + index = 2; + } + } + else if (rect.x > this.bounds.right) + { + // rect can completely fit within the right quadrants + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-right quadrant of this quadtree + index = 0; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-right quadrant of this quadtree + index = 3; + } + } + + return index; + + }, + + /** + * Return all objects that could collide with the given Sprite or Rectangle. + * + * @method Phaser.QuadTree#retrieve + * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle. + * @return {array} - Array with all detected objects. + */ + 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 rect fits into a subnode .. + if (index !== -1) + { + returnObjects = returnObjects.concat(this.nodes[index].retrieve(source)); + } + else + { + // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed) + 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 the quadtree. + * @method Phaser.QuadTree#clear + */ + 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; + +/** +* Javascript QuadTree +* @version 1.0 +* +* @version 1.3, March 11th 2014 +* @author Richard Davey +* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked +* it massively to add node indexing, removed lots of temp. var creation and significantly +* increased performance as a result. +* +* Original version at https://github.com/timohausmann/quadtree-js/ +*/ + +/** +* @copyright © 2012 Timo Hausmann +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. +* +* @class Phaser.Net +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Net = function (game) { + + this.game = game; + +}; + +Phaser.Net.prototype = { + + /** + * Returns the hostname given by the browser. + * + * @method Phaser.Net#getHostName + * @return {string} + */ + getHostName: function () { + + if (window.location && window.location.hostname) { + return window.location.hostname; + } + + return null; + + }, + + /** + * Compares the given domain name against the hostname of the browser containing the game. + * If the domain name is found it returns true. + * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. + * Do not include 'http://' at the start. + * + * @method Phaser.Net#checkDomainName + * @param {string} domain + * @return {boolean} true if the given domain fragment can be found in the window.location.hostname + */ + checkDomainName: function (domain) { + return window.location.hostname.indexOf(domain) !== -1; + }, + + /** + * Updates a value on the Query String and returns it in full. + * If the value doesn't already exist it is set. + * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. + * Optionally you can redirect to the new url, or just return it as a string. + * + * @method Phaser.Net#updateQueryString + * @param {string} key - The querystring key to update. + * @param {string} value - The new value to be set. If it already exists it will be replaced. + * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. + * @param {string} url - The URL to modify. If none is given it uses window.location.href. + * @return {string} If redirect is false then the modified url and query string is returned. + */ + updateQueryString: function (key, value, redirect, url) { + + if (redirect === undefined) { redirect = false; } + if (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; + } + + }, + + /** + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#getQueryString + * @param {string} [parameter=''] - If specified this will return just the value for that key. + * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. + */ + getQueryString: function (parameter) { + + if (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 && parameter === this.decodeURI(key[0])) + { + return this.decodeURI(key[1]); + } + else + { + output[this.decodeURI(key[0])] = this.decodeURI(key[1]); + } + } + } + + return output; + + }, + + /** + * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and + * decodes it, replacing \ with spaces in the return. Used internally by the Net classes. + * + * @method Phaser.Net#decodeURI + * @param {string} value - The URI component to be decoded. + * @return {string} The decoded value. + */ + decodeURI: function (value) { + return decodeURIComponent(value.replace(/\+/g, " ")); + } + +}; + +Phaser.Net.prototype.constructor = Phaser.Net; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. +* Tweens are hooked into the game clock and pause system, adjusting based on the game state. +* +* TweenManager is based heavily on tween.js by http://soledadpenades.com. +* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. +* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. +* Please see https://github.com/sole/tween.js for a full list of contributors. +* +* @class Phaser.TweenManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.TweenManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * @property {boolean} frameBased + * @default + */ + this.frameBased = false; + + /** + * @property {array} _tweens - All of the currently running tweens. + * @private + */ + this._tweens = []; + + /** + * @property {array} _add - All of the tweens queued to be added in the next update. + * @private + */ + this._add = []; + + this.easeMap = { + + "Power0": Phaser.Easing.Power0, + "Power1": Phaser.Easing.Power1, + "Power2": Phaser.Easing.Power2, + "Power3": Phaser.Easing.Power3, + "Power4": Phaser.Easing.Power4, + + "Linear": Phaser.Easing.Linear.None, + "Quad": Phaser.Easing.Quadratic.Out, + "Cubic": Phaser.Easing.Cubic.Out, + "Quart": Phaser.Easing.Quartic.Out, + "Quint": Phaser.Easing.Quintic.Out, + "Sine": Phaser.Easing.Sinusoidal.Out, + "Expo": Phaser.Easing.Exponential.Out, + "Circ": Phaser.Easing.Circular.Out, + "Elastic": Phaser.Easing.Elastic.Out, + "Back": Phaser.Easing.Back.Out, + "Bounce": Phaser.Easing.Bounce.Out, + + "Quad.easeIn": Phaser.Easing.Quadratic.In, + "Cubic.easeIn": Phaser.Easing.Cubic.In, + "Quart.easeIn": Phaser.Easing.Quartic.In, + "Quint.easeIn": Phaser.Easing.Quintic.In, + "Sine.easeIn": Phaser.Easing.Sinusoidal.In, + "Expo.easeIn": Phaser.Easing.Exponential.In, + "Circ.easeIn": Phaser.Easing.Circular.In, + "Elastic.easeIn": Phaser.Easing.Elastic.In, + "Back.easeIn": Phaser.Easing.Back.In, + "Bounce.easeIn": Phaser.Easing.Bounce.In, + + "Quad.easeOut": Phaser.Easing.Quadratic.Out, + "Cubic.easeOut": Phaser.Easing.Cubic.Out, + "Quart.easeOut": Phaser.Easing.Quartic.Out, + "Quint.easeOut": Phaser.Easing.Quintic.Out, + "Sine.easeOut": Phaser.Easing.Sinusoidal.Out, + "Expo.easeOut": Phaser.Easing.Exponential.Out, + "Circ.easeOut": Phaser.Easing.Circular.Out, + "Elastic.easeOut": Phaser.Easing.Elastic.Out, + "Back.easeOut": Phaser.Easing.Back.Out, + "Bounce.easeOut": Phaser.Easing.Bounce.Out, + + "Quad.easeInOut": Phaser.Easing.Quadratic.InOut, + "Cubic.easeInOut": Phaser.Easing.Cubic.InOut, + "Quart.easeInOut": Phaser.Easing.Quartic.InOut, + "Quint.easeInOut": Phaser.Easing.Quintic.InOut, + "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut, + "Expo.easeInOut": Phaser.Easing.Exponential.InOut, + "Circ.easeInOut": Phaser.Easing.Circular.InOut, + "Elastic.easeInOut": Phaser.Easing.Elastic.InOut, + "Back.easeInOut": Phaser.Easing.Back.InOut, + "Bounce.easeInOut": Phaser.Easing.Bounce.InOut + + }; + + this.game.onPause.add(this._pauseAll, this); + this.game.onResume.add(this._resumeAll, this); + +}; + +Phaser.TweenManager.prototype = { + + /** + * Get all the tween objects in an array. + * @method Phaser.TweenManager#getAll + * @returns {Phaser.Tween[]} Array with all tween objects. + */ + getAll: function () { + + return this._tweens; + + }, + + /** + * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. + * @method Phaser.TweenManager#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._tweens.length; i++) + { + this._tweens[i].pendingDelete = true; + } + + this._add = []; + + }, + + /** + * Remove all tweens from a specific object, array of objects or Group. + * + * @method Phaser.TweenManager#removeFrom + * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. + * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. + */ + removeFrom: function (obj, children) { + + if (children === undefined) { children = true; } + + var i; + var len; + + if (Array.isArray(obj)) + { + for (i = 0, len = obj.length; i < len; i++) + { + this.removeFrom(obj[i]); + } + } + else if (obj.type === Phaser.GROUP && children) + { + for (var i = 0, len = obj.children.length; i < len; i++) + { + this.removeFrom(obj.children[i]); + } + } + else + { + for (i = 0, len = this._tweens.length; i < len; i++) + { + if (obj === this._tweens[i].target) + { + this.remove(this._tweens[i]); + } + } + + for (i = 0, len = this._add.length; i < len; i++) + { + if (obj === this._add[i].target) + { + this.remove(this._add[i]); + } + } + } + + }, + + /** + * Add a new tween into the TweenManager. + * + * @method Phaser.TweenManager#add + * @param {Phaser.Tween} tween - The tween object you want to add. + * @returns {Phaser.Tween} The tween object you added to the manager. + */ + add: function (tween) { + + tween._manager = this; + this._add.push(tween); + + }, + + /** + * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.TweenManager#create + * @param {object} object - Object the tween will be run on. + * @returns {Phaser.Tween} The newly created tween object. + */ + create: function (object) { + + return new Phaser.Tween(object, this.game, this); + + }, + + /** + * Remove a tween from this manager. + * + * @method Phaser.TweenManager#remove + * @param {Phaser.Tween} tween - The tween object you want to remove. + */ + remove: function (tween) { + + var i = this._tweens.indexOf(tween); + + if (i !== -1) + { + this._tweens[i].pendingDelete = true; + } + else + { + i = this._add.indexOf(tween); + + if (i !== -1) + { + this._add[i].pendingDelete = true; + } + } + + }, + + /** + * Update all the tween objects you added to this manager. + * + * @method Phaser.TweenManager#update + * @returns {boolean} Return false if there's no tween to update, otherwise return true. + */ + update: function () { + + var addTweens = this._add.length; + var numTweens = this._tweens.length; + + if (numTweens === 0 && addTweens === 0) + { + return false; + } + + var i = 0; + + while (i < numTweens) + { + if (this._tweens[i].update(this.game.time.time)) + { + i++; + } + else + { + this._tweens.splice(i, 1); + + numTweens--; + } + } + + // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running + if (addTweens > 0) + { + this._tweens = this._tweens.concat(this._add); + this._add.length = 0; + } + + return true; + + }, + + /** + * Checks to see if a particular Sprite is currently being tweened. + * + * The `checkIsRunning` parameter will exclude tweens that have **just** completed or been stopped but haven't yet been removed from the manager. + * + * @method Phaser.TweenManager#isTweening + * @param {object} object - The object to check for tweens against. + * @param {boolean} [checkIsRunning=false] - Also check that the tween is running and is not marked for deletion. + * @returns {boolean} Returns true if the object is currently being tweened, false if not. + */ + isTweening: function(object, checkIsRunning) { + + if (!checkIsRunning) { checkIsRunning = false; } + + return this._tweens.some(function(tween) { + return (tween.target === object) && (!checkIsRunning || (tween.isRunning && !tween.pendingDelete)); + }); + + }, + + /** + * Private. Called by game focus loss. Pauses all currently running tweens. + * + * @method Phaser.TweenManager#_pauseAll + * @private + */ + _pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._pause(); + } + + }, + + /** + * Private. Called by game focus loss. Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#_resumeAll + * @private + */ + _resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._resume(); + } + + }, + + /** + * Pauses all currently running tweens. + * + * @method Phaser.TweenManager#pauseAll + */ + pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].pause(); + } + + }, + + /** + * Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#resumeAll + */ + resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].resume(true); + } + + } + +}; + +Phaser.TweenManager.prototype.constructor = Phaser.TweenManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tween allows you to alter one or more properties of a target object over a defined period of time. +* This can be used for things such as alpha fading Sprites, scaling them or motion. +* Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object +* by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and +* are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. +* +* @class Phaser.Tween +* @constructor +* @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. +* @param {Phaser.Game} game - Current game instance. +* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. +*/ +Phaser.Tween = function (target, game, manager) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. + */ + this.target = target; + + /** + * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween. + */ + this.manager = manager; + + /** + * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween. + */ + this.timeline = []; + + /** + * If set to `true` the current tween will play in reverse. + * If the tween hasn't yet started this has no effect. + * If there are child tweens then all child tweens will play in reverse from the current point. + * @property {boolean} reverse + * @default + */ + this.reverse = false; + + /** + * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. + * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. + * + * @property {number} timeScale + * @default + */ + this.timeScale = 1; + + /** + * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count. + */ + this.repeatCounter = 0; + + /** + * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager. + * @default + * @readonly + */ + this.pendingDelete = false; + + /** + * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onStart + */ + this.onStart = new Phaser.Signal(); + + /** + * The onLoop event is fired if the Tween, or any child tweens loop. + * It will be sent 2 parameters: the target object and this tween. + * + * @property {Phaser.Signal} onLoop + */ + this.onLoop = new Phaser.Signal(); + + /** + * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onRepeat + */ + this.onRepeat = new Phaser.Signal(); + + /** + * The onChildComplete event is fired when the Tween or any of its children completes. + * Fires every time a child completes unless a child is set to repeat forever. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onChildComplete + */ + this.onChildComplete = new Phaser.Signal(); + + /** + * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. + * @default + */ + this.isRunning = false; + + /** + * @property {number} current - The current Tween child being run. + * @default + * @readonly + */ + this.current = 0; + + /** + * @property {object} properties - Target property cache used when building the child data values. + */ + this.properties = {}; + + /** + * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it. + */ + this.chainedTween = null; + + /** + * @property {boolean} isPaused - Is this Tween paused or not? + * @default + */ + this.isPaused = false; + + /** + * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * + * The default value is whatever you've set in TweenManager.frameBased. + * + * @property {boolean} frameBased + * @default + */ + this.frameBased = manager.frameBased; + + /** + * @property {function} _onUpdateCallback - An onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallback = null; + + /** + * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallbackContext = null; + + /** + * @property {number} _pausedTime - Private pause timer. + * @private + * @default + */ + this._pausedTime = 0; + + /** + * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not. + * @private + */ + this._hasStarted = false; +}; + +/** +* A helper for tweening {@link Phaser.Color.createColor color objects}. +* +* It can be passed to {@link #onUpdateCallback}. +* +* ```javascript +* var color = Phaser.Color.createColor(255, 0, 0); // red +* +* var tween = game.add.tween(color).to({ +* r: 0, g: 0, b: 255 // blue +* }); +* +* tween.onUpdateCallback(Phaser.Tween.updateColor); +* +* tween.start(); +* ``` +* +* @method Phaser.Tween.updateColor +* @static +* @param {Phaser.Tween} tween - A Tween with a {@link #target} that is a {@link Phaser.Color.createColor color object}. +*/ +Phaser.Tween.updateColor = function (tween) { + + Phaser.Color.updateColor(tween.target); + +}; + +Phaser.Tween.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#to + * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined || duration <= 0) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.to cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#from + * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.from cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Starts the tween running. Can also be called by the `autoStart` parameter of {@link #to} or {@link #from}. + * This sets the {@link #isRunning} property to `true` and dispatches the {@link #onStart} signal. + * If the tween has a delay set then nothing will start tweening until the delay has expired. + * If the tween is already running, is flagged for deletion (such as after {@link #stop}), + * or has an empty timeline, calling start has no effect and the `onStart` signal is not dispatched. + * + * @method Phaser.Tween#start + * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + start: function (index) { + + if (index === undefined) { index = 0; } + + if (this.pendingDelete) + { + console.warn('Phaser.Tween.start cannot be called after Tween.stop'); + return this; + } + + if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning) + { + return this; + } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + this.manager.add(this); + + this.isRunning = true; + + if (index < 0 || index > this.timeline.length - 1) + { + index = 0; + } + + this.current = index; + + this.timeline[this.current].start(); + + return this; + + }, + + /** + * Stops the tween if running and flags it for deletion from the TweenManager. The tween can't be {@link #start restarted} after this. + * The {@link #onComplete} signal is not dispatched and no chained tweens are started unless the `complete` parameter is set to `true`. + * If you just wish to pause a tween then use {@link #pause} instead. + * If the tween is not running, it is **not** flagged for deletion and can be started again. + * + * @method Phaser.Tween#stop + * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + stop: function (complete) { + + if (complete === undefined) { complete = false; } + + this.isRunning = false; + + this._onUpdateCallback = null; + this._onUpdateCallbackContext = null; + + if (complete) + { + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + } + + this.manager.remove(this); + + return this; + + }, + + /** + * Updates either a single TweenData or all TweenData objects properties to the given value. + * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. + * The property is not checked, so if you pass an invalid one you'll generate a run-time error. + * + * @method Phaser.Tween#updateTweenData + * @param {string} property - The property to update. + * @param {number|function} value - The value to set the property to. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + updateTweenData: function (property, value, index) { + + if (this.timeline.length === 0) { return this; } + + if (index === undefined) { index = 0; } + + if (index === -1) + { + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i][property] = value; + } + } + else + { + this.timeline[index][property] = value; + } + + return this; + + }, + + /** + * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. + * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. + * If you have child tweens and pass -1 as the index value it sets the delay across all of them. + * + * @method Phaser.Tween#delay + * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + delay: function (duration, index) { + + return this.updateTweenData('delay', duration, index); + + }, + + /** + * Sets the number of times this tween will repeat. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. + * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. + * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. + * + * @method Phaser.Tween#repeat + * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeat: function (total, repeatDelay, index) { + + if (repeatDelay === undefined) { repeatDelay = 0; } + + this.updateTweenData('repeatCounter', total, index); + this.updateTweenData('repeatTotal', total, index); + + return this.updateTweenData('repeatDelay', repeatDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will repeat itself. + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#repeatDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatDelay: function (duration, index) { + + return this.updateTweenData('repeatDelay', duration, index); + + }, + + /** + * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. + * Used in combination with repeat you can create endless loops. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. + * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. + * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. + * + * @method Phaser.Tween#yoyo + * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo. + * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyo: function(enable, yoyoDelay, index) { + + if (yoyoDelay === undefined) { yoyoDelay = 0; } + + this.updateTweenData('yoyo', enable, index); + + return this.updateTweenData('yoyoDelay', yoyoDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#yoyoDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyoDelay: function (duration, index) { + + return this.updateTweenData('yoyoDelay', duration, index); + + }, + + /** + * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. + * + * @method Phaser.Tween#easing + * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + easing: function (ease, index) { + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + return this.updateTweenData('easingFunction', ease, index); + + }, + + /** + * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. + * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. + * The interpolation function is only used if the target properties is an array. + * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. + * + * @method Phaser.Tween#interpolation + * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) + * @param {object} [context] - The context under which the interpolation function will be run. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + interpolation: function (interpolation, context, index) { + + if (context === undefined) { context = Phaser.Math; } + + this.updateTweenData('interpolationFunction', interpolation, index); + + return this.updateTweenData('interpolationContext', context, index); + + }, + + /** + * Set how many times this tween and all of its children will repeat. + * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. + * + * @method Phaser.Tween#repeatAll + * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatAll: function (total) { + + if (total === undefined) { total = 0; } + + this.repeatCounter = total; + + return this; + + }, + + /** + * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called + * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. + * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. + * For that you should listen to `onComplete` on the final tween in your chain. + * + * If you pass multiple tweens to this method they will be joined into a single long chain. + * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. + * Any previously chained tweens that may have been set will be overwritten. + * + * @method Phaser.Tween#chain + * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + chain: function () { + + var i = arguments.length; + + while (i--) + { + if (i > 0) + { + arguments[i - 1].chainedTween = arguments[i]; + } + else + { + this.chainedTween = arguments[i]; + } + } + + return this; + + }, + + /** + * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. + * + * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. + * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. + * + * Usage: + * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) + * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) + * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) + * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) + * .loop(); + * @method Phaser.Tween#loop + * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + loop: function (value) { + + if (value === undefined) { value = true; } + + this.repeatCounter = (value) ? -1 : 0; + + return this; + + }, + + /** + * Sets a callback to be fired each time this tween updates. + * + * The callback receives the current Tween, the {@link Phaser.TweenData#value 'value' of the current TweenData}, and the current {@link Phaser.TweenData TweenData}. The second parameter is most useful. + * + * ```javascript + * tween.onUpdateCallback(function (tween, value, tweenData) { + * console.log('Tween running -- percent: %.2f value: %.2f', tweenData.percent, value); + * }); + * ``` + * + * @method Phaser.Tween#onUpdateCallback + * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. + * @param {object} callbackContext - The context in which to call the onUpdate callback. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + onUpdateCallback: function (callback, callbackContext) { + + this._onUpdateCallback = callback; + this._onUpdateCallbackContext = callbackContext; + + return this; + + }, + + /** + * Pauses the tween. Resume playback with Tween.resume. + * + * @method Phaser.Tween#pause + */ + pause: function () { + + this.isPaused = true; + + this._codePaused = true; + + this._pausedTime = this.game.time.time; + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * + * @private + * @method Phaser.Tween#_pause + */ + _pause: function () { + + if (!this._codePaused) + { + this.isPaused = true; + + this._pausedTime = this.game.time.time; + } + + }, + + /** + * Resumes a paused tween. + * + * @method Phaser.Tween#resume + */ + resume: function () { + + if (this.isPaused) + { + this.isPaused = false; + + this._codePaused = false; + + for (var i = 0; i < this.timeline.length; i++) + { + if (!this.timeline[i].isRunning) + { + this.timeline[i].startTime += (this.game.time.time - this._pausedTime); + } + } + } + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * @method Phaser.Tween#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Core tween update function called by the TweenManager. Does not need to be invoked directly. + * + * @method Phaser.Tween#update + * @param {number} time - A timestamp passed in by the TweenManager. + * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). + */ + update: function (time) { + + if (this.pendingDelete || !this.target) + { + return false; + } + + if (this.isPaused) + { + return true; + } + + var status = this.timeline[this.current].update(time); + + if (status === Phaser.TweenData.PENDING) + { + return true; + } + else if (status === Phaser.TweenData.RUNNING) + { + if (!this._hasStarted) + { + this.onStart.dispatch(this.target, this); + this._hasStarted = true; + } + + if (this._onUpdateCallback !== null) + { + this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]); + } + + // In case the update callback modifies this tween + return this.isRunning; + } + else if (status === Phaser.TweenData.LOOPED) + { + if (this.timeline[this.current].repeatCounter === -1) + { + this.onLoop.dispatch(this.target, this); + } + else + { + this.onRepeat.dispatch(this.target, this); + } + + return true; + } + else if (status === Phaser.TweenData.COMPLETE) + { + var complete = false; + + // What now? + if (this.reverse) + { + this.current--; + + if (this.current < 0) + { + this.current = this.timeline.length - 1; + complete = true; + } + } + else + { + this.current++; + + if (this.current === this.timeline.length) + { + this.current = 0; + complete = true; + } + } + + if (complete) + { + // We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it? + if (this.repeatCounter === -1) + { + this.timeline[this.current].start(); + this.onLoop.dispatch(this.target, this); + return true; + } + else if (this.repeatCounter > 0) + { + this.repeatCounter--; + + this.timeline[this.current].start(); + this.onRepeat.dispatch(this.target, this); + return true; + } + else + { + // No more repeats and no more children, so we're done + this.isRunning = false; + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + + return false; + } + } + else + { + // We've still got some children to go + this.onChildComplete.dispatch(this.target, this); + this.timeline[this.current].start(); + return true; + } + } + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * It ignores delay and repeat counts and any chained tweens, but does include child tweens. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.Tween#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate, data) { + + if (this.game === null || this.target === null) + { + return null; + } + + if (frameRate === undefined) { frameRate = 60; } + if (data === undefined) { data = []; } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + for (var i = 0; i < this.timeline.length; i++) + { + data = data.concat(this.timeline[i].generateData(frameRate)); + } + + return data; + + } + +}; + +/** +* @name Phaser.Tween#totalDuration +* @property {number} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds. +*/ +Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', { + + get: function () { + + var total = 0; + + for (var i = 0; i < this.timeline.length; i++) + { + total += this.timeline[i].duration; + } + + return total; + + } + +}); + +Phaser.Tween.prototype.constructor = Phaser.Tween; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the +* starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for +* TweenData objects and can contain multiple TweenData objects. +* +* @class Phaser.TweenData +* @constructor +* @param {Phaser.Tween} parent - The Tween that owns this TweenData object. +*/ +Phaser.TweenData = function (parent) { + + /** + * @property {Phaser.Tween} parent - The Tween which owns this TweenData. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = parent.game; + + /** + * @property {object} vStart - An object containing the values at the start of the tween. + * @private + */ + this.vStart = {}; + + /** + * @property {object} vStartCache - Cached starting values. + * @private + */ + this.vStartCache = {}; + + /** + * @property {object} vEnd - An object containing the values at the end of the tween. + * @private + */ + this.vEnd = {}; + + /** + * @property {object} vEndCache - Cached ending values. + * @private + */ + this.vEndCache = {}; + + /** + * @property {number} duration - The duration of the tween in ms. + * @default + */ + this.duration = 1000; + + /** + * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is. + * @readonly + */ + this.percent = 0; + + /** + * @property {number} value - The output of the easing function for the current {@link #percent}. Depending on the easing function, this will be within [0, 1] or a slightly larger range (e.g., Bounce). When easing is Linear, this will be identical to {@link #percent}. + * @readonly + */ + this.value = 0; + + /** + * @property {number} repeatCounter - If the Tween is set to repeat this is the number of repeats remaining (and `repeatTotal - repeatCounter` is the number of repeats completed). + */ + this.repeatCounter = 0; + + /** + * @property {number} repeatDelay - The amount of time in ms between repeats of this tween. + */ + this.repeatDelay = 0; + + /** + * @property {number} repeatTotal - The total number of times this Tween will repeat. + * @readonly + */ + this.repeatTotal = 0; + + /** + * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween) + * @default + * @todo Appears unused. + */ + this.interpolate = false; + + /** + * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false. + * @default + */ + this.yoyo = false; + + /** + * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween. + */ + this.yoyoDelay = 0; + + /** + * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). + * @default + */ + this.inReverse = false; + + /** + * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. + * @default + */ + this.delay = 0; + + /** + * @property {number} dt - Current time value. + */ + this.dt = 0; + + /** + * @property {number} startTime - The time the Tween started or null if it hasn't yet started. + */ + this.startTime = null; + + /** + * @property {function} easingFunction - The easing function used for the Tween. + * @default Phaser.Easing.Default + */ + this.easingFunction = Phaser.Easing.Default; + + /** + * @property {function} interpolationFunction - The interpolation function used for Array-based Tween. + * @default Phaser.Math.linearInterpolation + */ + this.interpolationFunction = Phaser.Math.linearInterpolation; + + /** + * @property {object} interpolationContext - The interpolation function context used for the Tween. + * @default Phaser.Math + */ + this.interpolationContext = Phaser.Math; + + /** + * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} isFrom - Is this a from tween or a to tween? + * @default + */ + this.isFrom = false; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.PENDING = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.RUNNING = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.LOOPED = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.COMPLETE = 3; + +Phaser.TweenData.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * + * @method Phaser.TweenData#to + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + to: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = false; + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * + * @method Phaser.TweenData#from + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + from: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = true; + + return this; + + }, + + /** + * Starts the Tween running. + * + * @method Phaser.TweenData#start + * @return {Phaser.TweenData} This Tween object. + */ + start: function () { + + this.startTime = this.game.time.time + this.delay; + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + if (this.delay > 0) + { + this.isRunning = false; + } + else + { + this.isRunning = true; + } + + if (this.isFrom) + { + // Reverse them all and instant set them + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + this.parent.target[property] = this.vStart[property]; + } + } + + this.value = 0; + this.repeatCounter = this.repeatTotal; + + return this; + + }, + + /** + * Loads the values from the target object into this Tween. + * + * @private + * @method Phaser.TweenData#loadValues + * @return {Phaser.TweenData} This Tween object. + */ + loadValues: function () { + + for (var property in this.parent.properties) + { + // Load the property from the parent object + this.vStart[property] = this.parent.properties[property]; + + // Check if an Array was provided as property value + if (Array.isArray(this.vEnd[property])) + { + if (this.vEnd[property].length === 0) + { + continue; + } + + if (this.percent === 0) + { + // Put the start value at the beginning of the array + // but we only want to do this once, if the Tween hasn't run before + this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]); + } + } + + if (typeof this.vEnd[property] !== 'undefined') + { + if (typeof this.vEnd[property] === 'string') + { + // Parses relative end values with start as base (e.g.: +10, -3) + this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10); + } + + this.parent.properties[property] = this.vEnd[property]; + } + else + { + // Null tween + this.vEnd[property] = this.vStart[property]; + } + + this.vStartCache[property] = this.vStart[property]; + this.vEndCache[property] = this.vEnd[property]; + } + + return this; + + }, + + /** + * Updates this Tween. This is called automatically by Phaser.Tween. + * + * @protected + * @method Phaser.TweenData#update + * @param {number} time - A timestamp passed in by the Tween parent. + * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. + */ + update: function (time) { + + if (!this.isRunning) + { + if (time >= this.startTime) + { + this.isRunning = true; + } + else + { + return Phaser.TweenData.PENDING; + } + } + else + { + // Is Running, but is waiting to repeat + if (time < this.startTime) + { + return Phaser.TweenData.RUNNING; + } + } + + var ms = (this.parent.frameBased) ? this.game.time.physicsElapsedMS : this.game.time.elapsedMS; + + if (this.parent.reverse) + { + this.dt -= ms * this.parent.timeScale; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += ms * this.parent.timeScale; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + this.parent.target[property] = start + ((end - start) * this.value); + } + } + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + return this.repeat(); + } + + return Phaser.TweenData.RUNNING; + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.TweenData#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate) { + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + var data = []; + var complete = false; + var fps = (1 / frameRate) * 1000; + + do + { + if (this.parent.reverse) + { + this.dt -= fps; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += fps; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + var blob = {}; + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + blob[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + blob[property] = start + ((end - start) * this.value); + } + } + + data.push(blob); + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + complete = true; + } + + } while (!complete); + + if (this.yoyo) + { + var reversed = data.slice(); + reversed.reverse(); + data = data.concat(reversed); + } + + return data; + + }, + + /** + * Checks if this Tween is meant to repeat or yoyo and handles doing so. + * + * @private + * @method Phaser.TweenData#repeat + * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE. + */ + repeat: function () { + + // If not a yoyo and repeatCounter = 0 then we're done + if (this.yoyo) + { + // We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end + if (this.inReverse && this.repeatCounter === 0) + { + // Restore the properties + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + this.inReverse = false; + + return Phaser.TweenData.COMPLETE; + } + + this.inReverse = !this.inReverse; + } + else + { + if (this.repeatCounter === 0) + { + return Phaser.TweenData.COMPLETE; + } + } + + if (this.inReverse) + { + // If inReverse we're going from vEnd to vStartCache + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + } + } + else + { + // If not inReverse we're just repopulating the cache again + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + // -1 means repeat forever, otherwise decrement the repeatCounter + // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total + if (this.repeatCounter > 0) + { + this.repeatCounter--; + } + } + + this.startTime = this.game.time.time; + + if (this.yoyo && this.inReverse) + { + this.startTime += this.yoyoDelay; + } + else if (!this.inReverse) + { + this.startTime += this.repeatDelay; + } + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + return Phaser.TweenData.LOOPED; + + } + +}; + +Phaser.TweenData.prototype.constructor = Phaser.TweenData; + +/* jshint curly: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of easing methods defining ease-in and ease-out curves. +* +* @class Phaser.Easing +*/ +Phaser.Easing = { + + /** + * Linear easing. + * + * @class Phaser.Easing.Linear + */ + Linear: { + + /** + * Linear Easing (no variation). + * + * @method Phaser.Easing.Linear#None + * @param {number} k - The value to be tweened. + * @returns {number} k. + */ + None: function ( k ) { + + return k; + + } + + }, + + /** + * Quadratic easing. + * + * @class Phaser.Easing.Quadratic + */ + Quadratic: { + + /** + * Ease-in. + * + * @method Phaser.Easing.Quadratic#In + * @param {number} k - The value to be tweened. + * @returns {number} k^2. + */ + In: function ( k ) { + + return k * k; + + }, + + /** + * Ease-out. + * + * @method Phaser.Easing.Quadratic#Out + * @param {number} k - The value to be tweened. + * @returns {number} k* (2-k). + */ + Out: function ( k ) { + + return k * ( 2 - k ); + + }, + + /** + * Ease-in/out. + * + * @method Phaser.Easing.Quadratic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; + return - 0.5 * ( --k * ( k - 2 ) - 1 ); + + } + + }, + + /** + * Cubic easing. + * + * @class Phaser.Easing.Cubic + */ + Cubic: { + + /** + * Cubic ease-in. + * + * @method Phaser.Easing.Cubic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k; + + }, + + /** + * Cubic ease-out. + * + * @method Phaser.Easing.Cubic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k + 1; + + }, + + /** + * Cubic ease-in/out. + * + * @method Phaser.Easing.Cubic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k + 2 ); + + } + + }, + + /** + * Quartic easing. + * + * @class Phaser.Easing.Quartic + */ + Quartic: { + + /** + * Quartic ease-in. + * + * @method Phaser.Easing.Quartic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k; + + }, + + /** + * Quartic ease-out. + * + * @method Phaser.Easing.Quartic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return 1 - ( --k * k * k * k ); + + }, + + /** + * Quartic ease-in/out. + * + * @method Phaser.Easing.Quartic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; + return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); + + } + + }, + + /** + * Quintic easing. + * + * @class Phaser.Easing.Quintic + */ + Quintic: { + + /** + * Quintic ease-in. + * + * @method Phaser.Easing.Quintic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k * k; + + }, + + /** + * Quintic ease-out. + * + * @method Phaser.Easing.Quintic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k * k * k + 1; + + }, + + /** + * Quintic ease-in/out. + * + * @method Phaser.Easing.Quintic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); + + } + + }, + + /** + * Sinusoidal easing. + * + * @class Phaser.Easing.Sinusoidal + */ + Sinusoidal: { + + /** + * Sinusoidal ease-in. + * + * @method Phaser.Easing.Sinusoidal#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 1 - Math.cos( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-out. + * + * @method Phaser.Easing.Sinusoidal#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return Math.sin( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-in/out. + * + * @method Phaser.Easing.Sinusoidal#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); + + } + + }, + + /** + * Exponential easing. + * + * @class Phaser.Easing.Exponential + */ + Exponential: { + + /** + * Exponential ease-in. + * + * @method Phaser.Easing.Exponential#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k === 0 ? 0 : Math.pow( 1024, k - 1 ); + + }, + + /** + * Exponential ease-out. + * + * @method Phaser.Easing.Exponential#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); + + }, + + /** + * Exponential ease-in/out. + * + * @method Phaser.Easing.Exponential#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); + return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); + + } + + }, + + /** + * Circular easing. + * + * @class Phaser.Easing.Circular + */ + Circular: { + + /** + * Circular ease-in. + * + * @method Phaser.Easing.Circular#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Math.sqrt( 1 - k * k ); + + }, + + /** + * Circular ease-out. + * + * @method Phaser.Easing.Circular#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return Math.sqrt( 1 - ( --k * k ) ); + + }, + + /** + * Circular ease-in/out. + * + * @method Phaser.Easing.Circular#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); + return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); + + } + + }, + + /** + * Elastic easing. + * + * @class Phaser.Easing.Elastic + */ + Elastic: { + + /** + * Elastic ease-in. + * + * @method Phaser.Easing.Elastic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + + }, + + /** + * Elastic ease-out. + * + * @method Phaser.Easing.Elastic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); + + }, + + /** + * Elastic ease-in/out. + * + * @method Phaser.Easing.Elastic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; + + } + + }, + + /** + * Back easing. + * + * @class Phaser.Easing.Back + */ + Back: { + + /** + * Back ease-in. + * + * @method Phaser.Easing.Back#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s = 1.70158; + return k * k * ( ( s + 1 ) * k - s ); + + }, + + /** + * Back ease-out. + * + * @method Phaser.Easing.Back#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s = 1.70158; + return --k * k * ( ( s + 1 ) * k + s ) + 1; + + }, + + /** + * Back ease-in/out. + * + * @method Phaser.Easing.Back#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s = 1.70158 * 1.525; + if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); + return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); + + } + + }, + + /** + * Bounce easing. + * + * @class Phaser.Easing.Bounce + */ + Bounce: { + + /** + * Bounce ease-in. + * + * @method Phaser.Easing.Bounce#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Phaser.Easing.Bounce.Out( 1 - k ); + + }, + + /** + * Bounce ease-out. + * + * @method Phaser.Easing.Bounce#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if ( k < ( 1 / 2.75 ) ) { + + return 7.5625 * k * k; + + } else if ( k < ( 2 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; + + } else if ( k < ( 2.5 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; + + } else { + + return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; + + } + + }, + + /** + * Bounce ease-in/out. + * + * @method Phaser.Easing.Bounce#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5; + return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5; + + } + + } + +}; + +Phaser.Easing.Default = Phaser.Easing.Linear.None; +Phaser.Easing.Power0 = Phaser.Easing.Linear.None; +Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out; +Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out; +Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out; +Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is the core internal game clock. +* +* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, +* and also handles the standard Timer pool. +* +* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}. +* +* There are different *types* of time in Phaser: +* +* - ***Game time*** always runs at the speed of time in real life. +* +* Unlike wall-clock time, *game time stops when Phaser is paused*. +* +* Game time is used for {@link Phaser.Timer timer events}. +* +* - ***Physics time*** represents the amount of time given to physics calculations. +* +* *When {@link #slowMotion} is in effect physics time runs slower than game time.* +* Like game time, physics time stops when Phaser is paused. +* +* Physics time is used for physics calculations and {@link Phaser.Tween tweens}. +* +* - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time. +* +* This time is independent of Phaser and always progresses, regardless of if Phaser is paused. +* +* @class Phaser.Time +* @constructor +* @param {Phaser.Game} game A reference to the currently running game. +*/ +Phaser.Time = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * The `Date.now()` value when the time was last updated. + * @property {integer} time + * @protected + */ + this.time = 0; + + /** + * The `now` when the previous update occurred. + * @property {number} prevTime + * @protected + */ + this.prevTime = 0; + + /** + * An increasing value representing cumulative milliseconds since an undisclosed epoch. + * + * While this value is in milliseconds and can be used to compute time deltas, + * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference. + * + * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; + * the value can only be relied upon within a particular game instance. + * + * @property {number} now + * @protected + */ + this.now = 0; + + /** + * Elapsed time since the last time update, in milliseconds, based on `now`. + * + * This value _may_ include time that the game is paused/inactive. + * + * While the game is active, this will be similar to (1000 / {@link #fps}). + * + * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {number} elapsed + * @see Phaser.Time.time + * @protected + */ + this.elapsed = 0; + + /** + * The time in ms since the last time update, in milliseconds, based on `time`. + * + * This value is corrected for game pauses and will be "about zero" after a game is resumed. + * + * _Note:_ This is updated once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {integer} elapsedMS + * @protected + */ + this.elapsedMS = 0; + + /** + * The physics update delta, in fractional seconds. + * + * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) + * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system + * is unable to consistently maintain the desired FPS. + * + * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. + * + * @property {number} physicsElapsed + */ + this.physicsElapsed = 1 / 60; + + /** + * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. + * + * @property {number} physicsElapsedMS + */ + this.physicsElapsedMS = (1 / 60) * 1000; + + /** + * The desiredFps multiplier as used by Game.update. + * @property {integer} desiredFpsMult + * @protected + */ + this.desiredFpsMult = 1.0 / 60; + + /** + * The desired frame rate of the game. + * + * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates. + * + * @property {number} _desiredFps + * @private + * @default + */ + this._desiredFps = 60; + + /** + * The suggested frame rate for your game, based on an averaged real frame rate. + * This value is only populated if `Time.advancedTiming` is enabled. + * + * _Note:_ This is not available until after a few frames have passed; until then + * it's set to the same value as desiredFps. + * + * @property {number} suggestedFps + * @default + */ + this.suggestedFps = this.desiredFps; + + /** + * Scaling factor to make the game move smoothly in slow motion (or fast motion) + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * You likely need to adjust {@link #desiredFps} as well such that `desiredFps / slowMotion === 60`. + * + * @property {number} slowMotion + * @default + */ + this.slowMotion = 1.0; + + /** + * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. This isn't expensive, but displaying it with {@link Phaser.Utils.Debug#text} can be, especially in WebGL mode. + * @property {boolean} advancedTiming + * @default + */ + this.advancedTiming = false; + + /** + * Advanced timing result: The number of animation frames received from the browser in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} frames + * @readonly + */ + this.frames = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateLogic logic updates} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} updates + * @readonly + */ + this.updates = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateRender renders} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} renders + * @readonly + */ + this.renders = 0; + + /** + * Advanced timing result: Frames per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} fps + * @readonly + */ + this.fps = 0; + + /** + * Advanced timing result: Logic updates per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} ups + * @readonly + */ + this.ups = 0; + + /** + * Advanced timing result: Renders per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} rps + * @readonly + */ + this.rps = 0; + + /** + * Advanced timing result: The lowest rate the fps has dropped to. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMin + */ + this.fpsMin = 1000; + + /** + * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMax + */ + this.fpsMax = 0; + + /** + * Advanced timing result: The minimum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMin + * @default + */ + this.msMin = 1000; + + /** + * Advanced timing result: The maximum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMax + */ + this.msMax = 0; + + /** + * Records how long the game was last paused, in milliseconds. + * (This is not updated until the game is resumed.) + * @property {number} pauseDuration + */ + this.pauseDuration = 0; + + /** + * @property {number} timeToCall - The value that setTimeout needs to work out when to next update + * @protected + */ + this.timeToCall = 0; + + /** + * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop + * @protected + */ + this.timeExpected = 0; + + /** + * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to. + * @property {Phaser.Timer} events + */ + this.events = new Phaser.Timer(this.game, false); + + /** + * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated + * @private + */ + this._frameCount = 0; + + /** + * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated + * @private + */ + this._elapsedAccumulator = 0; + + /** + * @property {number} _started - The time at which the Game instance started. + * @private + */ + this._started = 0; + + /** + * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. + * @private + */ + this._timeLastSecond = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {boolean} _justResumed - Internal value used to recover from the game pause state. + * @private + */ + this._justResumed = false; + + /** + * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects. + * @private + */ + this._timers = []; + +}; + +Phaser.Time.prototype = { + + /** + * Called automatically by Phaser.Game after boot. Should not be called directly. + * + * @method Phaser.Time#boot + * @protected + */ + boot: function () { + + this._started = Date.now(); + this.time = Date.now(); + this.events.start(); + this.timeExpected = this.time; + + }, + + /** + * Adds an existing Phaser.Timer object to the Timer pool. + * + * @method Phaser.Time#add + * @param {Phaser.Timer} timer - An existing Phaser.Timer object. + * @return {Phaser.Timer} The given Phaser.Timer object. + */ + add: function (timer) { + + this._timers.push(timer); + + return timer; + + }, + + /** + * Creates a new stand-alone Phaser.Timer object. + * + * @method Phaser.Time#create + * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). + * @return {Phaser.Timer} The Timer object that was created. + */ + create: function (autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + var timer = new Phaser.Timer(this.game, autoDestroy); + + this._timers.push(timer); + + return timer; + + }, + + /** + * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer. + * + * @method Phaser.Time#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._timers.length; i++) + { + this._timers[i].destroy(); + } + + this._timers = []; + + this.events.removeAll(); + + }, + + /** + * Refreshes the Time.time and Time.elapsedMS properties from the system clock. + * + * @method Phaser.Time#refresh + */ + refresh: function () { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + }, + + /** + * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. + * + * @method Phaser.Time#update + * @protected + * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}. + */ + update: function (time) { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + // 'now' is currently still holding the time of the last call, move it into prevTime + this.prevTime = this.now; + + // update 'now' to hold the current time + // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now) + this.now = time; + + // elapsed time between previous call and now - this could be a high resolution value + this.elapsed = this.now - this.prevTime; + + if (this.game.raf._isSetTimeOut) + { + // console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time); + + // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game + this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time))); + + // time when the next call is expected if using timers + this.timeExpected = time + this.timeToCall; + + // console.log('Time expect', this.timeExpected); + } + + if (this.advancedTiming) + { + this.updateAdvancedTiming(); + } + + // Paused but still running? + if (!this.game.paused) + { + // Our internal Phaser.Timer + this.events.update(this.time); + + if (this._timers.length) + { + this.updateTimers(); + } + } + + }, + + /** + * Handles the updating of the Phaser.Timers (if any) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateTimers + * @private + */ + updateTimers: function () { + + // Any game level timers + var i = 0; + var len = this._timers.length; + + while (i < len) + { + if (this._timers[i].update(this.time)) + { + i++; + } + else + { + // Timer requests to be removed + this._timers.splice(i, 1); + len--; + } + } + + }, + + /** + * Handles the updating of the advanced timing values (if enabled) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateAdvancedTiming + * @private + */ + updateAdvancedTiming: function () { + + // count the number of time.update calls + this._frameCount++; + this._elapsedAccumulator += this.elapsed; + + // occasionally recalculate the suggestedFps based on the accumulated elapsed time + if (this._frameCount >= this._desiredFps * 2) + { + // this formula calculates suggestedFps in multiples of 5 fps + this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5; + this._frameCount = 0; + this._elapsedAccumulator = 0; + } + + this.msMin = Math.min(this.msMin, this.elapsed); + this.msMax = Math.max(this.msMax, this.elapsed); + + this.frames++; + + if (this.now > this._timeLastSecond + 1000) + { + var interval = this.now - this._timeLastSecond; + this.fps = Math.round((this.frames * 1000) / interval); + this.ups = Math.round((this.updates * 1000) / interval); + this.rps = Math.round((this.renders * 1000) / interval); + this.fpsMin = Math.min(this.fpsMin, this.fps); + this.fpsMax = Math.max(this.fpsMax, this.fps); + this._timeLastSecond = this.now; + this.frames = 0; + this.updates = 0; + this.renders = 0; + } + + }, + + /** + * Counts one logic update (if advanced timing is enabled). + * + * @method Phaser.Time#countUpdate + * @private + */ + countUpdate: function () { + + if (this.advancedTiming) + { + this.updates++; + } + + }, + + /** + * Counts one render (if advanced timing is enabled). + * + * @method Phaser.Time#countRender + * @private + */ + countRender: function () { + + if (this.advancedTiming) + { + this.renders++; + } + + }, + + /** + * Called when the game enters a paused state. + * + * @method Phaser.Time#gamePaused + * @private + */ + gamePaused: function () { + + this._pauseStarted = Date.now(); + + this.events.pause(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._pause(); + } + + }, + + /** + * Called when the game resumes from a paused state. + * + * @method Phaser.Time#gameResumed + * @private + */ + gameResumed: function () { + + // Set the parameter which stores Date.now() to make sure it's correct on resume + this.time = Date.now(); + + this.pauseDuration = this.time - this._pauseStarted; + + this.events.resume(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._resume(); + } + + }, + + /** + * The number of seconds that have elapsed since the game was started. + * + * @method Phaser.Time#totalElapsedSeconds + * @return {number} The number of seconds that have elapsed since the game was started. + */ + totalElapsedSeconds: function() { + return (this.time - this._started) * 0.001; + }, + + /** + * How long has passed since the given time. + * + * @method Phaser.Time#elapsedSince + * @param {number} since - The time you want to measure against. + * @return {number} The difference between the given time and now. + */ + elapsedSince: function (since) { + return this.time - since; + }, + + /** + * How long has passed since the given time (in seconds). + * + * @method Phaser.Time#elapsedSecondsSince + * @param {number} since - The time you want to measure (in seconds). + * @return {number} Duration between given time and now (in seconds). + */ + elapsedSecondsSince: function (since) { + return (this.time - since) * 0.001; + }, + + /** + * Resets the private _started value to now and removes all currently running Timers. + * + * @method Phaser.Time#reset + */ + reset: function () { + + this._started = this.time; + this.removeAll(); + + } + +}; + +/** +* The number of logic updates per second. +* +* This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. +* +* The render rate is unaffected unless you also turn off {@link Phaser.Game#forceSingleRender}. +* +* @name Phaser.Time#desiredFps +* @type {integer} +* @default 60 +*/ +Object.defineProperty(Phaser.Time.prototype, "desiredFps", { + + get: function () { + + return this._desiredFps; + + }, + + set: function (value) { + + this._desiredFps = value; + + // Set the physics elapsed time... this will always be 1 / this.desiredFps + // because we're using fixed time steps in game.update + this.physicsElapsed = 1 / value; + + this.physicsElapsedMS = this.physicsElapsed * 1000; + + this.desiredFpsMult = 1.0 / value; + + } + +}); + +Phaser.Time.prototype.constructor = Phaser.Time; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback. +* Many different timer events, with individual delays, can be added to the same Timer. +* +* All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. +* +* Timers are based on real life time, adjusted for game pause durations. +* That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account. +* +* @class Phaser.Timer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). +*/ +Phaser.Timer = function (game, autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * True if the Timer is actively running. + * + * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer. + * @property {boolean} running + * @default + * @readonly + */ + this.running = false; + + /** + * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). + * @property {boolean} autoDestroy + */ + this.autoDestroy = autoDestroy; + + /** + * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending. + * @readonly + * @default + */ + this.expired = false; + + /** + * @property {number} elapsed - Elapsed time since the last frame (in ms). + * @protected + */ + this.elapsed = 0; + + /** + * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. + */ + this.events = []; + + /** + * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. + * + * The signal is supplied with one argument, `timer`, which is this Timer object. + * + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {number} nextTick - The time the next tick will occur. + * @readonly + * @protected + */ + this.nextTick = 0; + + /** + * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. + */ + this.timeCap = 1000; + + /** + * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. + * @readonly + * @default + */ + this.paused = false; + + /** + * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {number} _started - The time at which this Timer instance started running. + * @private + * @default + */ + this._started = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {number} _pauseTotal - Total paused time. + * @private + */ + this._pauseTotal = 0; + + /** + * @property {number} _now - The current start-time adjusted time. + * @private + */ + this._now = Date.now(); + + /** + * @property {number} _len - Temp. array length variable. + * @private + */ + this._len = 0; + + /** + * @property {number} _marked - Temp. counter variable. + * @private + */ + this._marked = 0; + + /** + * @property {number} _i - Temp. array counter variable. + * @private + */ + this._i = 0; + + /** + * @property {number} _diff - Internal cache var. + * @private + */ + this._diff = 0; + + /** + * @property {number} _newTick - Internal cache var. + * @private + */ + this._newTick = 0; + +}; + +/** +* Number of milliseconds in a minute. +* @constant +* @type {integer} +*/ +Phaser.Timer.MINUTE = 60000; + +/** +* Number of milliseconds in a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.SECOND = 1000; + +/** +* Number of milliseconds in half a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.HALF = 500; + +/** +* Number of milliseconds in a quarter of a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.QUARTER = 250; + +Phaser.Timer.prototype = { + + /** + * Creates a new TimerEvent on this Timer. + * + * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. + * + * @method Phaser.Timer#create + * @private + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {boolean} loop - Should the event loop or not? + * @param {number} repeatCount - The number of times the event will repeat. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {any[]} arguments - The values to be sent to your callback function when it is called. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + create: function (delay, loop, repeatCount, callback, callbackContext, args) { + + delay = Math.round(delay); + + var tick = delay; + + if (this._now === 0) + { + tick += this.game.time.time; + } + else + { + tick += this._now; + } + + var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args); + + this.events.push(event); + + this.order(); + + this.expired = false; + + return event; + + }, + + /** + * Adds a new Event to this Timer. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#add + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + add: function (delay, callback, callbackContext) { + + return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. + * If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#repeat + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + repeat: function (delay, repeatCount, callback, callbackContext) { + + return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4)); + + }, + + /** + * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#loop + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + loop: function (delay, callback, callbackContext) { + + return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Starts this Timer running. + * @method Phaser.Timer#start + * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start. + */ + start: function (delay) { + + if (this.running) + { + return; + } + + this._started = this.game.time.time + (delay || 0); + + this.running = true; + + for (var i = 0; i < this.events.length; i++) + { + this.events[i].tick = this.events[i].delay + this._started; + } + + }, + + /** + * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. + * @method Phaser.Timer#stop + * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain. + */ + stop: function (clearEvents) { + + this.running = false; + + if (clearEvents === undefined) { clearEvents = true; } + + if (clearEvents) + { + this.events.length = 0; + } + + }, + + /** + * Removes a pending TimerEvent from the queue. + * @param {Phaser.TimerEvent} event - The event to remove from the queue. + * @method Phaser.Timer#remove + */ + remove: function (event) { + + for (var i = 0; i < this.events.length; i++) + { + if (this.events[i] === event) + { + this.events[i].pendingDelete = true; + return true; + } + } + + return false; + + }, + + /** + * Orders the events on this Timer so they are in tick order. + * This is called automatically when new events are created. + * @method Phaser.Timer#order + * @protected + */ + order: function () { + + if (this.events.length > 0) + { + // Sort the events so the one with the lowest tick is first + this.events.sort(this.sortHandler); + + this.nextTick = this.events[0].tick; + } + + }, + + /** + * Sort handler used by Phaser.Timer.order. + * @method Phaser.Timer#sortHandler + * @private + */ + sortHandler: function (a, b) { + + if (a.tick < b.tick) + { + return -1; + } + else if (a.tick > b.tick) + { + return 1; + } + + return 0; + + }, + + /** + * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values. + * + * @method Phaser.Timer#clearPendingEvents + * @protected + */ + 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; + + }, + + /** + * The main Timer update event, called automatically by Phaser.Time.update. + * + * @method Phaser.Timer#update + * @protected + * @param {number} time - The time from the core game clock. + * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. + */ + update: function (time) { + + if (this.paused) + { + return true; + } + + this.elapsed = time - this._now; + this._now = time; + + // spike-dislike + if (this.elapsed > this.timeCap) + { + // For some reason the time between now and the last time the game was updated was larger than our timeCap. + // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause. + // In this case we need to adjust the TimerEvents and nextTick. + this.adjustEvents(time - this.elapsed); + } + + this._marked = 0; + + // Clears events marked for deletion and resets _len and _i to 0. + this.clearPendingEvents(); + + if (this.running && this._now >= this.nextTick && this._len > 0) + { + while (this._i < this._len && this.running) + { + var event = this.events[this._i]; + + if (this._now >= event.tick && !event.pendingDelete) + { + // (now + delay) - (time difference from last tick to now) + this._newTick = (this._now + event.delay) - (this._now - event.tick); + + if (this._newTick < 0) + { + this._newTick = this._now + event.delay; + } + + if (event.loop === true) + { + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else if (event.repeatCount > 0) + { + event.repeatCount--; + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else + { + this._marked++; + event.pendingDelete = true; + event.callback.apply(event.callbackContext, event.args); + } + + this._i++; + } + else + { + break; + } + } + + // Are there any events left? + 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; + } + + }, + + /** + * Pauses the Timer and all events in the queue. + * @method Phaser.Timer#pause + */ + pause: function () { + + if (!this.running) + { + return; + } + + this._codePaused = true; + + if (this.paused) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Internal pause/resume control - user code should use Timer.pause instead. + * @method Phaser.Timer#_pause + * @private + */ + _pause: function () { + + if (this.paused || !this.running) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Adjusts the time of all pending events and the nextTick by the given baseTime. + * + * @method Phaser.Timer#adjustEvents + * @protected + */ + adjustEvents: function (baseTime) { + + for (var i = 0; i < this.events.length; i++) + { + if (!this.events[i].pendingDelete) + { + // Work out how long there would have been from when the game paused until the events next tick + var t = this.events[i].tick - baseTime; + + if (t < 0) + { + t = 0; + } + + // Add the difference on to the time now + this.events[i].tick = this._now + t; + } + } + + var d = this.nextTick - baseTime; + + if (d < 0) + { + this.nextTick = this._now; + } + else + { + this.nextTick = this._now + d; + } + + }, + + /** + * Resumes the Timer and updates all pending events. + * + * @method Phaser.Timer#resume + */ + resume: function () { + + if (!this.paused) + { + return; + } + + var now = this.game.time.time; + this._pauseTotal += now - this._now; + this._now = now; + + this.adjustEvents(this._pauseStarted); + + this.paused = false; + this._codePaused = false; + + }, + + /** + * Internal pause/resume control - user code should use Timer.resume instead. + * @method Phaser.Timer#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#removeAll + */ + removeAll: function () { + + this.onComplete.removeAll(); + this.events.length = 0; + this._len = 0; + this._i = 0; + + }, + + /** + * Destroys this Timer. Any pending Events are not dispatched. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#destroy + */ + destroy: function () { + + this.onComplete.removeAll(); + this.running = false; + this.expired = true; + this.events = []; + this._len = 0; + this._i = 0; + + } + +}; + +/** +* @name Phaser.Timer#next +* @property {number} next - The time at which the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "next", { + + get: function () { + return this.nextTick; + } + +}); + +/** +* @name Phaser.Timer#duration +* @property {number} duration - The duration in ms remaining until the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "duration", { + + get: function () { + + if (this.running && this.nextTick > this._now) + { + return this.nextTick - this._now; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#length +* @property {number} length - The number of pending events in the queue. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "length", { + + get: function () { + return this.events.length; + } + +}); + +/** +* @name Phaser.Timer#ms +* @property {number} ms - The duration in milliseconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "ms", { + + get: function () { + + if (this.running) + { + return this._now - this._started - this._pauseTotal; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#seconds +* @property {number} seconds - The duration in seconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "seconds", { + + get: function () { + + if (this.running) + { + return this.ms * 0.001; + } + else + { + return 0; + } + + } + +}); + +Phaser.Timer.prototype.constructor = Phaser.Timer; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TimerEvent is a single event that is processed by a Phaser.Timer. +* +* It consists of a delay, which is a value in milliseconds after which the event will fire. +* When the event fires it calls a specific callback with the specified arguments. +* +* TimerEvents are removed by their parent timer once finished firing or repeating. +* +* Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. +* +* @class Phaser.TimerEvent +* @constructor +* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. +* @param {number} delay - The delay in ms at which this TimerEvent fires. +* @param {number} tick - The tick is the next game clock time that this event will fire at. +* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times. +* @param {boolean} loop - True if this TimerEvent loops, otherwise false. +* @param {function} callback - The callback that will be called when the TimerEvent occurs. +* @param {object} callbackContext - The context in which the callback will be called. +* @param {any[]} arguments - Additional arguments to be passed to the callback. +*/ +Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) { + + /** + * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. + * @protected + * @readonly + */ + this.timer = timer; + + /** + * @property {number} delay - The delay in ms at which this TimerEvent fires. + */ + this.delay = delay; + + /** + * @property {number} tick - The tick is the next game clock time that this event will fire at. + */ + this.tick = tick; + + /** + * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times. + */ + this.repeatCount = repeatCount - 1; + + /** + * @property {boolean} loop - True if this TimerEvent loops, otherwise false. + */ + this.loop = loop; + + /** + * @property {function} callback - The callback that will be called when the TimerEvent occurs. + */ + this.callback = callback; + + /** + * @property {object} callbackContext - The context in which the callback will be called. + */ + this.callbackContext = callbackContext; + + /** + * @property {any[]} arguments - Additional arguments to be passed to the callback. + */ + this.args = args; + + /** + * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion. + * @protected + */ + this.pendingDelete = false; + +}; + +Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Manager is used to add, play and update Phaser Animations. +* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. +* +* @class Phaser.AnimationManager +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. +*/ +Phaser.AnimationManager = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = sprite.game; + + /** + * The currently displayed Frame of animation, if any. + * This property is only set once an Animation starts playing. Until that point it remains set as `null`. + * + * @property {Phaser.Frame} currentFrame + * @default + */ + this.currentFrame = null; + + /** + * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any. + * @default + */ + this.currentAnim = null; + + /** + * @property {boolean} updateIfVisible - Update the animation data only while the the sprite is {@link Phaser.Sprite#visible}. Set to `false` to continue updating while the sprite is invisible. + * @default + */ + this.updateIfVisible = true; + + /** + * @property {boolean} isLoaded - Set to true once animation data has been loaded. + * @default + */ + this.isLoaded = false; + + /** + * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. + * @private + * @default + */ + this._frameData = null; + + /** + * @property {object} _anims - An internal object that stores all of the Animation instances. + * @private + */ + this._anims = {}; + + /** + * @property {object} _outputFrames - An internal object to help avoid gc. + * @private + */ + this._outputFrames = []; + +}; + +Phaser.AnimationManager.prototype = { + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#loadFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + loadFrameData: function (frameData, frame) { + + if (frameData === undefined) + { + return false; + } + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(frameData); + } + } + + this._frameData = frameData; + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#copyFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + copyFrameData: function (frameData, frame) { + + this._frameData = frameData.clone(); + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(this._frameData); + } + } + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. + * Animations added in this way are played back with the play function. + * + * @method Phaser.AnimationManager#add + * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". + * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. + * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. + * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? + * @return {Phaser.Animation} The Animation object that was created. + */ + add: function (name, frames, frameRate, loop, useNumericIndex) { + + frames = frames || []; + frameRate = frameRate || 60; + + if (loop === undefined) { loop = false; } + + // If they didn't set the useNumericIndex then let's at least try and guess it + if (useNumericIndex === undefined) + { + if (frames && typeof frames[0] === 'number') + { + useNumericIndex = true; + } + else + { + useNumericIndex = false; + } + } + + this._outputFrames = []; + + 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]; + + if (this.sprite.tilingTexture) + { + this.sprite.refreshTexture = true; + } + + return this._anims[name]; + + }, + + /** + * Check whether the frames in the given array are valid and exist. + * + * @method Phaser.AnimationManager#validateFrames + * @param {Array} frames - An array of frames to be validated. + * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) + * @return {boolean} True if all given Frames are valid, otherwise false. + */ + validateFrames: function (frames, useNumericIndex) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + + for (var i = 0; i < frames.length; i++) + { + if (useNumericIndex === true) + { + if (frames[i] > this._frameData.total) + { + return false; + } + } + else + { + if (this._frameData.checkFrameName(frames[i]) === false) + { + return false; + } + } + } + + return true; + + }, + + /** + * Play an animation based on the given key. The animation should previously have been added via `animations.add` + * + * If the requested animation is already playing this request will be ignored. + * If you need to reset an already running animation do so directly on the Animation object itself. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.AnimationManager#play + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation instance. + */ + 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); + } + + return this.currentAnim; + } + else + { + if (this.currentAnim && this.currentAnim.isPlaying) + { + this.currentAnim.stop(); + } + + this.currentAnim = this._anims[name]; + this.currentAnim.paused = false; + this.currentFrame = this.currentAnim.currentFrame; + return this.currentAnim.play(frameRate, loop, killOnComplete); + } + } + + }, + + /** + * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. + * The currentAnim property of the AnimationManager is automatically set to the animation given. + * + * @method Phaser.AnimationManager#stop + * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. + * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) + */ + stop: function (name, resetFrame) { + + if (resetFrame === undefined) { resetFrame = false; } + + if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name)) + { + this.currentAnim.stop(resetFrame); + } + + }, + + /** + * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. + * + * @method Phaser.AnimationManager#update + * @protected + * @return {boolean} True if a new animation frame has been set, otherwise false. + */ + update: function () { + + if (this.updateIfVisible && !this.sprite.visible) + { + return false; + } + + if (this.currentAnim && this.currentAnim.update()) + { + this.currentFrame = this.currentAnim.currentFrame; + return true; + } + + return false; + + }, + + /** + * Advances by the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.next(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Moves backwards the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.previous(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Returns an animation that was previously added by name. + * + * @method Phaser.AnimationManager#getAnimation + * @param {string} name - The name of the animation to be returned, e.g. "fire". + * @return {Phaser.Animation} The Animation instance, if found, otherwise null. + */ + getAnimation: function (name) { + + if (typeof name === 'string') + { + if (this._anims[name]) + { + return this._anims[name]; + } + } + + return null; + + }, + + /** + * Refreshes the current frame data back to the parent Sprite and also resets the texture data. + * + * @method Phaser.AnimationManager#refreshFrame + */ + refreshFrame: function () { + + // TODO + // this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); + + }, + + /** + * Destroys all references this AnimationManager contains. + * Iterates through the list of animations stored in this manager and calls destroy on each of them. + * + * @method Phaser.AnimationManager#destroy + */ + destroy: function () { + + var anim = null; + + for (var anim in this._anims) + { + if (this._anims.hasOwnProperty(anim)) + { + this._anims[anim].destroy(); + } + } + + this._anims = {}; + this._outputFrames = []; + this._frameData = null; + this.currentAnim = null; + this.currentFrame = null; + this.sprite = null; + this.game = null; + + } + +}; + +Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager; + +/** +* @name Phaser.AnimationManager#frameData +* @property {Phaser.FrameData} frameData - The current animations FrameData. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', { + + get: function () { + return this._frameData; + } + +}); + +/** +* @name Phaser.AnimationManager#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', { + + get: function () { + + return this._frameData.total; + } + +}); + +/** +* @name Phaser.AnimationManager#paused +* @property {boolean} paused - Gets and sets the paused state of the current animation. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', { + + get: function () { + + return this.currentAnim.isPaused; + + }, + + set: function (value) { + + this.currentAnim.paused = value; + + } + +}); + +/** +* @name Phaser.AnimationManager#name +* @property {string} name - Gets the current animation name, if set. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'name', { + + get: function () { + + if (this.currentAnim) + { + return this.currentAnim.name; + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.index; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'number' && this._frameData && (gotFrame = this._frameData.getFrame(value))) + { + this.currentFrame = gotFrame; + this.sprite.setFrame(this.currentFrame); + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frameName +* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.name; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'string' && this._frameData && (gotFrame = this._frameData.getFrameByName(value))) + { + this.currentFrame = gotFrame; + this._frameIndex = this.currentFrame.index; + this.sprite.setFrame(this.currentFrame); + } + else + { + console.warn('Cannot set frameName: ' + value); + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Animation instance contains a single animation and the controls to play it. +* +* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. +* +* @class Phaser.Animation +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Sprite} parent - A reference to the owner of this Animation. +* @param {string} name - The unique name for this animation, used in playback commands. +* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. +* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +*/ +Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) { + + if (loop === undefined) { loop = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. + * @private + */ + this._parent = parent; + + /** + * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. + * @private + */ + this._frameData = frameData; + + /** + * @property {string} name - The user defined name given to this Animation. + */ + this.name = name; + + /** + * @property {array} _frames + * @private + */ + this._frames = []; + this._frames = this._frames.concat(frames); + + /** + * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. + */ + this.delay = 1000 / frameRate; + + /** + * @property {boolean} loop - The loop state of the Animation. + */ + this.loop = loop; + + /** + * @property {number} loopCount - The number of times the animation has looped since it was last started. + */ + this.loopCount = 0; + + /** + * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? + * @default + */ + this.killOnComplete = false; + + /** + * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. + * @default + */ + this.isFinished = false; + + /** + * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. + * @default + */ + this.isPlaying = false; + + /** + * @property {boolean} isPaused - The paused state of the Animation. + * @default + */ + this.isPaused = false; + + /** + * @property {boolean} _pauseStartTime - The time the animation paused. + * @private + * @default + */ + this._pauseStartTime = 0; + + /** + * @property {number} _frameIndex + * @private + * @default + */ + this._frameIndex = 0; + + /** + * @property {number} _frameDiff + * @private + * @default + */ + this._frameDiff = 0; + + /** + * @property {number} _frameSkip + * @private + * @default + */ + this._frameSkip = 1; + + /** + * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. + */ + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + /** + * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. + */ + this.onStart = new Phaser.Signal(); + + /** + * This event is dispatched when the Animation changes frame. + * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. + * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations + * will automatically frame-skip to try and claw back time, so do not base your code on expecting to + * receive a perfectly sequential set of frames from this event. + * @property {Phaser.Signal|null} onUpdate + * @default + */ + this.onUpdate = null; + + /** + * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {boolean} isReversed - Indicates if the animation will play backwards. + * @default + */ + this.isReversed = false; + + // Set-up some event listeners + this.game.onPause.add(this.onPause, this); + this.game.onResume.add(this.onResume, this); + +}; + +Phaser.Animation.prototype = { + + /** + * Plays this animation. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.Animation#play + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} - A reference to this Animation instance. + */ + play: function (frameRate, loop, killOnComplete) { + + if (typeof frameRate === 'number') + { + // If they set a new frame rate then use it, otherwise use the one set on creation + this.delay = 1000 / frameRate; + } + + if (typeof loop === 'boolean') + { + // If they set a new loop value then use it, otherwise use the one set on creation + this.loop = loop; + } + + if (typeof killOnComplete !== 'undefined') + { + // Remove the parent sprite once the animation has finished? + this.killOnComplete = killOnComplete; + } + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = this.isReversed ? this._frames.length - 1 : 0; + this.updateCurrentFrame(false, true); + + this._parent.events.onAnimationStart$dispatch(this._parent, this); + + this.onStart.dispatch(this._parent, this); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + return this; + + }, + + /** + * Sets this animation back to the first frame and restarts the animation. + * + * @method Phaser.Animation#restart + */ + restart: function () { + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = 0; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + this._parent.setFrame(this.currentFrame); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + this.onStart.dispatch(this._parent, this); + + }, + + /** + * Reverses the animation direction. + * + * @method Phaser.Animation#reverse + * @return {Phaser.Animation} The animation instance. + */ + reverse: function () { + + this.reversed = !this.reversed; + + return this; + + }, + + /** + * Reverses the animation direction for the current/next animation only + * Once the onComplete event is called this method will be called again and revert + * the reversed state. + * + * @method Phaser.Animation#reverseOnce + * @return {Phaser.Animation} The animation instance. + */ + reverseOnce: function () { + + this.onComplete.addOnce(this.reverse, this); + + return this.reverse(); + + }, + + /** + * Sets this animations playback to a given frame with the given ID. + * + * @method Phaser.Animation#setFrame + * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. + * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. + */ + setFrame: function(frameId, useLocalFrameIndex) { + + var frameIndex; + + if (useLocalFrameIndex === undefined) + { + useLocalFrameIndex = false; + } + + // Find the index to the desired frame. + if (typeof frameId === "string") + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frameData.getFrame(this._frames[i]).name === frameId) + { + frameIndex = i; + } + } + } + else if (typeof frameId === "number") + { + if (useLocalFrameIndex) + { + frameIndex = frameId; + } + else + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frames[i] === frameId) + { + frameIndex = i; + } + } + } + } + + if (frameIndex) + { + // Set the current frame index to the found index. Subtract a directional offset so that it animates to the desired frame on update. + var directionalOffset = this.isReversed ? -1 : 1; + this._frameIndex = frameIndex - directionalOffset; + + // Make the animation update at next update + this._timeNextFrame = this.game.time.time; + + this.update(); + } + + }, + + /** + * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. + * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. + * + * @method Phaser.Animation#stop + * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. + * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? + */ + stop: function (resetFrame, dispatchComplete) { + + if (resetFrame === undefined) { resetFrame = false; } + if (dispatchComplete === undefined) { dispatchComplete = false; } + + this.isPlaying = false; + this.isFinished = true; + this.paused = false; + + if (resetFrame) + { + this.currentFrame = this._frameData.getFrame(this._frames[0]); + this._parent.setFrame(this.currentFrame); + } + + if (dispatchComplete) + { + this._parent.events.onAnimationComplete$dispatch(this._parent, this); + this.onComplete.dispatch(this._parent, this); + } + + }, + + /** + * Called when the Game enters a paused state. + * + * @method Phaser.Animation#onPause + */ + onPause: function () { + + if (this.isPlaying) + { + this._frameDiff = this._timeNextFrame - this.game.time.time; + } + + }, + + /** + * Called when the Game resumes from a paused state. + * + * @method Phaser.Animation#onResume + */ + onResume: function () { + + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this._frameDiff; + } + + }, + + /** + * Updates this animation. Called automatically by the AnimationManager. + * + * @method Phaser.Animation#update + */ + update: function () { + + if (this.isPaused) + { + return false; + } + + if (this.isPlaying && this.game.time.time >= this._timeNextFrame) + { + this._frameSkip = 1; + + // Lagging? + this._frameDiff = this.game.time.time - this._timeNextFrame; + + this._timeLastFrame = this.game.time.time; + + if (this._frameDiff > this.delay) + { + // We need to skip a frame, work out how many + this._frameSkip = Math.floor(this._frameDiff / this.delay); + this._frameDiff -= (this._frameSkip * this.delay); + } + else + { + this._frameDiff = 0; + } + + // And what's left now? + this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff); + + if (this.isReversed) + { + this._frameIndex -= this._frameSkip; + } + else + { + this._frameIndex += this._frameSkip; + } + + if (!this.isReversed && this._frameIndex >= this._frames.length || this.isReversed && this._frameIndex <= -1) + { + if (this.loop) + { + // Update current state before event callback + this._frameIndex = Math.abs(this._frameIndex) % this._frames.length; + + if (this.isReversed) + { + this._frameIndex = this._frames.length - 1 - this._frameIndex; + } + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + // Instead of calling updateCurrentFrame we do it here instead + if (this.currentFrame) + { + this._parent.setFrame(this.currentFrame); + } + + this.loopCount++; + this._parent.events.onAnimationLoop$dispatch(this._parent, this); + this.onLoop.dispatch(this._parent, this); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + } + else + { + this.complete(); + return false; + } + } + else + { + return this.updateCurrentFrame(true); + } + } + + return false; + + }, + + /** + * Changes the currentFrame per the _frameIndex, updates the display state, + * and triggers the update signal. + * + * Returns true if the current frame update was 'successful', false otherwise. + * + * @method Phaser.Animation#updateCurrentFrame + * @private + * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. + * @param {boolean} fromPlay - Was this call made from the playing of a new animation? + * @return {boolean} True if the current frame was updated, otherwise false. + */ + updateCurrentFrame: function (signalUpdate, fromPlay) { + + if (fromPlay === undefined) { fromPlay = false; } + + if (!this._frameData) + { + // The animation is already destroyed, probably from a callback + return false; + } + + // Previous index + var idx = this.currentFrame.index; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index))) + { + this._parent.setFrame(this.currentFrame); + } + + if (this.onUpdate && signalUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + + }, + + /** + * Advances by the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex + quantity; + + if (frame >= this._frames.length) + { + if (this.loop) + { + frame %= this._frames.length; + } + else + { + frame = this._frames.length - 1; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex - quantity; + + if (frame < 0) + { + if (this.loop) + { + frame = this._frames.length + frame; + } + else + { + frame++; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Changes the FrameData object this Animation is using. + * + * @method Phaser.Animation#updateFrameData + * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. + */ + updateFrameData: function (frameData) { + + this._frameData = frameData; + this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null; + + }, + + /** + * Cleans up this animation ready for deletion. Nulls all values and references. + * + * @method Phaser.Animation#destroy + */ + destroy: function () { + + if (!this._frameData) + { + // Already destroyed + return; + } + + 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(); + + if (this.onUpdate) + { + this.onUpdate.dispose(); + } + + }, + + /** + * Called internally when the animation finishes playback. + * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. + * + * @method Phaser.Animation#complete + */ + complete: function () { + + this._frameIndex = this._frames.length - 1; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + 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; + +/** +* @name Phaser.Animation#paused +* @property {boolean} paused - Gets and sets the paused state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'paused', { + + get: function () { + + return this.isPaused; + + }, + + set: function (value) { + + this.isPaused = value; + + if (value) + { + // Paused + this._pauseStartTime = this.game.time.time; + } + else + { + // Un-paused + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this.delay; + } + } + + } + +}); + +/** +* @name Phaser.Animation#reversed +* @property {boolean} reversed - Gets and sets the isReversed state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'reversed', { + + get: function () { + + return this.isReversed; + + }, + + set: function (value) { + + this.isReversed = value; + + } + +}); + +/** +* @name Phaser.Animation#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @name Phaser.Animation#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +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.setFrame(this.currentFrame); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + } + } + + } + +}); + +/** +* @name Phaser.Animation#speed +* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'speed', { + + get: function () { + + return 1000 / this.delay; + + }, + + set: function (value) { + + if (value > 0) + { + this.delay = 1000 / value; + } + + } + +}); + +/** +* @name Phaser.Animation#enableUpdate +* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { + + get: function () { + + return (this.onUpdate !== null); + + }, + + set: function (value) { + + if (value && this.onUpdate === null) + { + this.onUpdate = new Phaser.Signal(); + } + else if (!value && this.onUpdate !== null) + { + this.onUpdate.dispose(); + this.onUpdate = null; + } + + } + +}); + +/** +* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. +* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' +* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); +* +* @method Phaser.Animation.generateFrameNames +* @static +* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. +* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. +* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. +* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'. +* @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. +* @return {string[]} An array of framenames. +*/ +Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { + + if (suffix === undefined) { suffix = ''; } + + var output = []; + var frame = ''; + + if (start < stop) + { + for (var i = start; i <= stop; i++) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + else + { + for (var i = start; i >= stop; i--) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + + return output; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Frame is a single frame of an animation and is part of a FrameData collection. +* +* @class Phaser.Frame +* @constructor +* @param {number} index - The index of this Frame within the FrameData set it is being added to. +* @param {number} x - X position of the frame within the texture image. +* @param {number} y - Y position of the frame within the texture image. +* @param {number} width - Width of the frame within the texture image. +* @param {number} height - Height of the frame within the texture image. +* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. +*/ +Phaser.Frame = function (index, x, y, width, height, name) { + + /** + * @property {number} index - The index of this Frame within the FrameData set it is being added to. + */ + this.index = index; + + /** + * @property {number} x - X position within the image to cut from. + */ + this.x = x; + + /** + * @property {number} y - Y position within the image to cut from. + */ + this.y = y; + + /** + * @property {number} width - Width of the frame. + */ + this.width = width; + + /** + * @property {number} height - Height of the frame. + */ + this.height = height; + + if (this.width === 0 || this.height === 0) + { + console.warn('Phaser.Frame: Frame "' + this.name + '" has a width or height of zero'); + } + + /** + * @property {string} name - Useful for Texture Atlas files (is set to the filename value). + */ + this.name = name; + + /** + * @property {number} centerX - Center X position within the image to cut from. + */ + this.centerX = Math.floor(width / 2); + + /** + * @property {number} centerY - Center Y position within the image to cut from. + */ + this.centerY = Math.floor(height / 2); + + /** + * @property {number} distance - The distance from the top left to the bottom-right of this Frame. + */ + this.distance = Phaser.Math.distance(0, 0, width, height); + + /** + * @property {boolean} rotated - Is the frame rotated in the source texture? + * @default + */ + this.rotated = false; + + /** + * @property {boolean} trimmed - Was it trimmed when packed? + * @default + */ + this.trimmed = false; + + /** + * @property {number} sourceSizeW - Width of the original sprite before it was trimmed. + */ + this.sourceSizeW = width; + + /** + * @property {number} sourceSizeH - Height of the original sprite before it was trimmed. + */ + this.sourceSizeH = height; + + /** + * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeX = 0; + + /** + * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeY = 0; + + /** + * @property {number} spriteSourceSizeW - Width of the trimmed sprite. + * @default + */ + this.spriteSourceSizeW = 0; + + /** + * @property {number} spriteSourceSizeH - Height of the trimmed sprite. + * @default + */ + this.spriteSourceSizeH = 0; + + /** + * @property {number} right - The right of the Frame (x + width). + */ + this.right = this.x + this.width; + + /** + * @property {number} bottom - The bottom of the frame (y + height). + */ + this.bottom = this.y + this.height; + +}; + +Phaser.Frame.prototype = { + + /** + * Adjusts of all the Frame properties based on the given width and height values. + * + * @method Phaser.Frame#resize + * @param {integer} width - The new width of the Frame. + * @param {integer} height - The new height of the Frame. + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + this.centerX = Math.floor(width / 2); + this.centerY = Math.floor(height / 2); + this.distance = Phaser.Math.distance(0, 0, width, height); + this.sourceSizeW = width; + this.sourceSizeH = height; + this.right = this.x + width; + this.bottom = this.y + height; + + }, + + /** + * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. + * + * @method Phaser.Frame#setTrim + * @param {boolean} trimmed - If this frame was trimmed or not. + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + */ + setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { + + this.trimmed = trimmed; + + if (trimmed) + { + 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; + } + + }, + + /** + * Clones this Frame into a new Phaser.Frame object and returns it. + * Note that all properties are cloned, including the name and index. + * + * @method Phaser.Frame#clone + * @return {Phaser.Frame} An exact copy of this Frame object. + */ + clone: function () { + + var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name); + + for (var prop in this) + { + if (this.hasOwnProperty(prop)) + { + output[prop] = this[prop]; + } + } + + return output; + + }, + + /** + * Returns a Rectangle set to the dimensions of this Frame. + * + * @method Phaser.Frame#getRect + * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to. + * @return {Phaser.Rectangle} A rectangle. + */ + getRect: function (out) { + + if (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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. +* +* @class Phaser.FrameData +* @constructor +*/ +Phaser.FrameData = function () { + + /** + * @property {Array} _frames - Local array of frames. + * @private + */ + this._frames = []; + + /** + * @property {Array} _frameNames - Local array of frame names for name to index conversions. + * @private + */ + this._frameNames = []; + +}; + +Phaser.FrameData.prototype = { + + /** + * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. + * + * @method Phaser.FrameData#addFrame + * @param {Phaser.Frame} frame - The frame to add to this FrameData set. + * @return {Phaser.Frame} The frame that was just added. + */ + addFrame: function (frame) { + + frame.index = this._frames.length; + + this._frames.push(frame); + + if (frame.name !== '') + { + this._frameNames[frame.name] = frame.index; + } + + return frame; + + }, + + /** + * Get a Frame by its numerical index. + * + * @method Phaser.FrameData#getFrame + * @param {number} index - The index of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or undefined. + */ + getFrame: function (index) { + + if (index >= this._frames.length) + { + index = 0; + } + + return this._frames[index]; + + }, + + /** + * Get a Frame by its frame name. + * + * @method Phaser.FrameData#getFrameByName + * @param {string} name - The name of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or null. + */ + getFrameByName: function (name) { + + if (typeof this._frameNames[name] === 'number') + { + return this._frames[this._frameNames[name]]; + } + + return null; + + }, + + /** + * Check if there is a Frame with the given name. + * + * @method Phaser.FrameData#checkFrameName + * @param {string} name - The name of the frame you want to check. + * @return {boolean} True if the frame is found, otherwise false. + */ + checkFrameName: function (name) { + + if (this._frameNames[name] == null) + { + return false; + } + + return true; + + }, + + /** + * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains. + * + * @method Phaser.FrameData#clone + * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains. + */ + clone: function () { + + var output = new Phaser.FrameData(); + + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output._frames.push(this._frames[i].clone()); + } + + for (var p in this._frameNames) + { + if (this._frameNames.hasOwnProperty(p)) + { + output._frameNames.push(this._frameNames[p]); + } + } + + return output; + + }, + + /** + * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. + * + * @method Phaser.FrameData#getFrameRange + * @param {number} start - The starting frame index. + * @param {number} end - The ending frame index. + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. + */ + getFrameRange: function (start, end, output) { + + if (output === undefined) { output = []; } + + for (var i = start; i <= end; i++) + { + output.push(this._frames[i]); + } + + return output; + + }, + + /** + * Returns all of the Frames in this FrameData set where the frame index is found in the input array. + * The frames are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrames + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. + */ + getFrames: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + // We only need the indexes + output.push(this._frames[i]); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the input array contain names or indexes? + if (useNumericIndex) + { + // The actual frame + output.push(this.getFrame(frames[i])); + } + else + { + // The actual frame + output.push(this.getFrameByName(frames[i])); + } + } + } + + return output; + + }, + + /** + * Returns all of the Frame indexes in this FrameData set. + * The frames indexes are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrameIndexes + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frame indexes matching the given names or IDs. + */ + getFrameIndexes: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No frames array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output.push(this._frames[i].index); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the frames array contain names or indexes? + if (useNumericIndex && this._frames[frames[i]]) + { + output.push(this._frames[frames[i]].index); + } + else + { + if (this.getFrameByName(frames[i])) + { + output.push(this.getFrameByName(frames[i]).index); + } + } + } + } + + return output; + + }, + + /** + * Destroys this FrameData collection by nulling the _frames and _frameNames arrays. + * + * @method Phaser.FrameData#destroy + */ + destroy: function () { + + this._frames = null; + this._frameNames = null; + + } + +}; + +Phaser.FrameData.prototype.constructor = Phaser.FrameData; + +/** +* @name Phaser.FrameData#total +* @property {number} total - The total number of frames in this FrameData set. +* @readonly +*/ +Object.defineProperty(Phaser.FrameData.prototype, "total", { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +* +* @class Phaser.AnimationParser +* @static +*/ +Phaser.AnimationParser = { + + /** + * Parse a Sprite Sheet and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.spriteSheet + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. + * @param {number} frameWidth - The fixed width of each frame of the animation. + * @param {number} frameHeight - The fixed height of each frame of the animation. + * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + var img = key; + + if (typeof key === 'string') + { + img = game.cache.getImage(key); + } + + if (img === null) + { + return null; + } + + var width = img.width; + var height = img.height; + + if (frameWidth <= 0) + { + frameWidth = Math.floor(-width / Math.min(-1, frameWidth)); + } + + if (frameHeight <= 0) + { + frameHeight = Math.floor(-height / Math.min(-1, frameHeight)); + } + + var row = Math.floor((width - margin) / (frameWidth + spacing)); + var column = Math.floor((height - margin) / (frameHeight + spacing)); + var total = row * column; + + if (skipFrames > total || skipFrames < -total) + { + console.warn( + "Phaser.AnimationParser.spriteSheet: skipFrames = " + + skipFrames.toString() + " is larger than total sprite number " + + total.toString()); + return null; + } + + if (skipFrames < 0) + { + // Allow negative skipframes. + skipFrames = total + skipFrames; + } + + if (frameMax !== -1) + { + total = skipFrames + frameMax; + } + + // Zero or smaller than frame sizes? + if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0) + { + console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight"); + return null; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var x = margin; + var y = margin; + + for (var i = 0; i < total; i++) + { + data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '')); + + x += frameWidth + spacing; + + if (x + frameWidth > width) + { + x = margin; + y += frameHeight + spacing; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONData: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].frame.x, + frames[i].frame.y, + frames[i].frame.w, + frames[i].frame.h, + frames[i].filename + )); + + if (frames[i].trimmed) + { + newFrame.setTrim( + frames[i].trimmed, + frames[i].sourceSize.w, + frames[i].sourceSize.h, + frames[i].spriteSourceSize.x, + frames[i].spriteSourceSize.y, + frames[i].spriteSourceSize.w, + frames[i].spriteSourceSize.h + ); + } + + if (frames[i].rotated) + { + newFrame.rotated = true; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataPyxel + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataPyxel: function (game, json) { + + // Malformed? There are a few keys to check here. + var signature = ['layers', 'tilewidth','tileheight','tileswide', 'tileshigh']; + + signature.forEach( function(key) { + if (!json[key]) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "' + key + '" key.'); + console.log(json); + return; + } + }); + + // For this purpose, I only care about parsing tilemaps with a single layer. + if (json['layers'].length !== 1) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps.'); + console.log(json); + return; + } + + var data = new Phaser.FrameData(); + + var tileheight = json['tileheight']; + var tilewidth = json['tilewidth']; + + var frames = json['layers'][0]['tiles']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].x, + frames[i].y, + tilewidth, + tileheight, + "frame_" + i // No names are included in pyxel tilemap data. + )); + + // No trim data is included. + newFrame.setTrim(false); + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataHash + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataHash: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + var i = 0; + + for (var key in frames) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[key].frame.x, + frames[key].frame.y, + frames[key].frame.w, + frames[key].frame.h, + key + )); + + if (frames[key].trimmed) + { + newFrame.setTrim( + frames[key].trimmed, + frames[key].sourceSize.w, + frames[key].sourceSize.h, + frames[key].spriteSourceSize.x, + frames[key].spriteSourceSize.y, + frames[key].spriteSourceSize.w, + frames[key].spriteSourceSize.h + ); + } + + if (frames[key].rotated) + { + newFrame.rotated = true; + } + + i++; + } + + return data; + + }, + + /** + * Parse the XML data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.XMLData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + XMLData: function (game, xml) { + + // Malformed? + if (!xml.getElementsByTagName('TextureAtlas')) + { + console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing tag"); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var frames = xml.getElementsByTagName('SubTexture'); + var newFrame; + + var name; + var frame; + var x; + var y; + var width; + var height; + var frameX; + var frameY; + var frameWidth; + var frameHeight; + + for (var i = 0; i < frames.length; i++) + { + frame = frames[i].attributes; + + name = frame.name.value; + x = parseInt(frame.x.value, 10); + y = parseInt(frame.y.value, 10); + width = parseInt(frame.width.value, 10); + height = parseInt(frame.height.value, 10); + + frameX = null; + frameY = null; + + if (frame.frameX) + { + frameX = Math.abs(parseInt(frame.frameX.value, 10)); + frameY = Math.abs(parseInt(frame.frameY.value, 10)); + frameWidth = parseInt(frame.frameWidth.value, 10); + frameHeight = parseInt(frame.frameHeight.value, 10); + } + + newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name)); + + // Trimmed? + if (frameX !== null || frameY !== null) + { + newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight); + } + } + + return data; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser has one single cache in which it stores all assets. +* +* The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using +* a unique string-based key as their identifier. Assets stored in different areas of the cache can have the +* same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, +* because they are unique data types. +* +* The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets +* such as images they are automatically placed into their respective cache. Most common Game Objects, such as +* Sprites and Videos automatically query the cache to extract the assets they need on instantiation. +* +* You can access the cache from within a State via `this.cache`. From here you can call any public method it has, +* including adding new entries to it, deleting them or querying them. +* +* Understand that almost without exception when you get an item from the cache it will return a reference to the +* item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original +* object in the cache will also be updated, even if you don't put it back into the cache again. +* +* By default when you change State the cache is _not_ cleared, although there is an option to clear it should +* your game require it. In a typical game set-up the cache is populated once after the main game has loaded and +* then used as an asset store. +* +* @class Phaser.Cache +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Cache = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. + * @property {boolean} autoResolveURL + */ + this.autoResolveURL = false; + + /** + * The main cache object into which all resources are placed. + * @property {object} _cache + * @private + */ + this._cache = { + canvas: {}, + image: {}, + texture: {}, + sound: {}, + video: {}, + text: {}, + json: {}, + xml: {}, + physics: {}, + tilemap: {}, + binary: {}, + bitmapData: {}, + bitmapFont: {}, + shader: {}, + renderTexture: {}, + compressedTexture: {} + }; + + /** + * @property {object} _urlMap - Maps URLs to resources. + * @private + */ + this._urlMap = {}; + + /** + * @property {Image} _urlResolver - Used to resolve URLs to the absolute path. + * @private + */ + this._urlResolver = new Image(); + + /** + * @property {string} _urlTemp - Temporary variable to hold a resolved url. + * @private + */ + this._urlTemp = null; + + /** + * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices. + */ + this.onSoundUnlock = new Phaser.Signal(); + + /** + * @property {array} _cacheMap - Const to cache object look-up array. + * @private + */ + this._cacheMap = []; + + this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas; + this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image; + this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture; + this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound; + this._cacheMap[Phaser.Cache.TEXT] = this._cache.text; + this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics; + this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap; + this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary; + this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData; + this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont; + this._cacheMap[Phaser.Cache.JSON] = this._cache.json; + this._cacheMap[Phaser.Cache.XML] = this._cache.xml; + this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video; + this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader; + this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture; + + /** + * @property {number} + * @private + */ + this._pendingCount = 0; + + /** + * Dispatched when the DEFAULT and MISSING images have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). + * + * @property {Phaser.Signal} onReady + */ + this.onReady = new Phaser.Signal(); + + this._addImages(); + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.CANVAS = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.IMAGE = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXTURE = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SOUND = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXT = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.PHYSICS = 6; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TILEMAP = 7; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BINARY = 8; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPDATA = 9; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPFONT = 10; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.JSON = 11; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.XML = 12; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.VIDEO = 13; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SHADER = 14; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.RENDER_TEXTURE = 15; + +/** +* The default image used for a texture when no other is specified. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.DEFAULT = null; + +/** + * Key for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_KEY = '__default'; + +/** + * URL for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='; + +/** +* The default image used for a texture when the source image is missing. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.MISSING = null; + +/** + * Key for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_KEY = '__missing'; + +/** + * URL for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='; + +/** +* The maximum amount of time (ms) to wait for the built-in DEFAULT and MISSING images to load. +* @static +* @type {number} +* @default +*/ +Phaser.Cache.READY_TIMEOUT = 1000; + +Phaser.Cache.prototype = { + + ////////////////// + // Add Methods // + ////////////////// + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCompressedTextureMetaData + * @private + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url + * @param {string} extension + * @param {array} arrayBuffer + * @return {object} The compressed texture entry. + */ + addCompressedTextureMetaData: function (key, url, extension, arrayBuffer) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + var data = (extension in Phaser.LoaderParser) ? Phaser.LoaderParser[extension](arrayBuffer) : arrayBuffer; + + var texture = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData(), + fileFormat: extension + }; + + texture.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = texture; + + this._resolveURL(url, texture); + + return texture; + + }, + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCanvas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {HTMLCanvasElement} canvas - The Canvas DOM element. + * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`. + */ + addCanvas: function (key, canvas, context) { + + if (context === undefined) { context = canvas.getContext('2d'); } + + this._cache.canvas[key] = { canvas: canvas, context: context }; + + }, + + /** + * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. + * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. + * + * If the image has not yet been fetched (successfully or not), a `console.warn` message will be displayed. + * + * @method Phaser.Cache#addImage + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra image data. + * @return {object} The full image object that was added to the cache. + */ + addImage: function (key, url, data) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + if (data.complete === false) + { + console.warn('Phaser.Cache.addImage: Image "' + key + '" hasn\'t been retrieved yet'); + } + + var img = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData() + }; + + img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = img; + + this._resolveURL(url, img); + + if (key === '__default') + { + Phaser.Cache.DEFAULT = new PIXI.Texture(img.base); + } + else if (key === '__missing') + { + Phaser.Cache.MISSING = new PIXI.Texture(img.base); + } + + return img; + + }, + + /** + * @method Phaser.Cache#addImageAsync + * @private + */ + addImageAsync: function (key, src, callback) { + + var self = this; + var img = new Image(); + + img.onload = function () { + callback.call(this, self.addImage(key, null, img)); + self._removePending(); + img.onload = null; + }; + + this._addPending(); + img.src = src; + + }, + + /** + * Adds a default image to be used in special cases such as WebGL Filters. + * It uses the special reserved key of `__default`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addDefaultImage + * @protected + */ + addDefaultImage: function () { + + this.addImageAsync(Phaser.Cache.DEFAULT_KEY, Phaser.Cache.DEFAULT_SRC, function (obj) { + // Because we don't want to invalidate the sprite batch for an invisible texture + obj.base.skipRender = true; + + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.DEFAULT = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds an image to be used when a key is wrong / missing. + * It uses the special reserved key of `__missing`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addMissingImage + * @protected + */ + addMissingImage: function () { + + this.addImageAsync(Phaser.Cache.MISSING_KEY, Phaser.Cache.MISSING_SRC, function (obj) { + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.MISSING = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addSound + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sound data. + * @param {boolean} webAudio - True if the file is using web audio. + * @param {boolean} audioTag - True if the file is using legacy HTML audio. + */ + addSound: function (key, url, data, webAudio, audioTag) { + + if (webAudio === undefined) { webAudio = true; audioTag = false; } + if (audioTag === undefined) { webAudio = false; audioTag = true; } + + var decoded = false; + + if (audioTag) + { + decoded = true; + } + + this._cache.sound[key] = { + url: url, + data: data, + isDecoding: false, + decoded: decoded, + webAudio: webAudio, + audioTag: audioTag, + locked: this.game.sound.touchLocked + }; + + this._resolveURL(url, this._cache.sound[key]); + + }, + + /** + * Add a new text data. + * + * @method Phaser.Cache#addText + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addText: function (key, url, data) { + + this._cache.text[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.text[key]); + + }, + + /** + * Add a new physics data object to the Cache. + * + * @method Phaser.Cache#addPhysicsData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} JSONData - The physics data object (a JSON file). + * @param {number} format - The format of the physics data. + */ + addPhysicsData: function (key, url, JSONData, format) { + + this._cache.physics[key] = { url: url, data: JSONData, format: format }; + + this._resolveURL(url, this._cache.physics[key]); + + }, + + /** + * Add a new tilemap to the Cache. + * + * @method Phaser.Cache#addTilemap + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} mapData - The tilemap data object (either a CSV or JSON file). + * @param {number} format - The format of the tilemap data. + */ + addTilemap: function (key, url, mapData, format) { + + this._cache.tilemap[key] = { url: url, data: mapData, format: format }; + + this._resolveURL(url, this._cache.tilemap[key]); + + }, + + /** + * Add a binary object in to the cache. + * + * @method Phaser.Cache#addBinary + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {object} binaryData - The binary object to be added to the cache. + */ + addBinary: function (key, binaryData) { + + this._cache.binary[key] = binaryData; + + }, + + /** + * Add a BitmapData object to the cache. + * + * @method Phaser.Cache#addBitmapData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. + * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. + * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. + */ + addBitmapData: function (key, bitmapData, frameData) { + + bitmapData.key = key; + + if (frameData === undefined) + { + frameData = new Phaser.FrameData(); + frameData.addFrame(bitmapData.textureFrame); + } + + this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData }; + + return bitmapData; + + }, + + /** + * Add a new Bitmap Font to the Cache. + * + * @method Phaser.Cache#addBitmapFont + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra font data. + * @param {object} atlasData - The Bitmap Font data. + * @param {string} [atlasType='xml'] - The format of the Bitmap Font data file: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) { + + var obj = { + url: url, + data: data, + font: null, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + if (atlasType === 'json') + { + obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + else + { + obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new Bitmap Font to the Cache, where the font texture is part of a Texture Atlas. + * + * The atlas must already exist in the cache, and be available based on the given `atlasKey`. + * + * The `atlasFrame` specifies the name of the frame within the atlas that the Bitmap Font is + * stored in. + * + * The `dataKey` is the key of the XML or JSON Bitmap Font Data, which must already be in + * the Cache. + * + * @method Phaser.Cache#addBitmapFontFromAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} atlasKey - The key of the Texture Atlas in the Cache. + * @param {string} atlasFrame - The frame of the Texture Atlas that the Bitmap Font is in. + * @param {string} dataKey - The key of the Bitmap Font data in the Cache + * @param {string} [dataType='xml'] - The format of the Bitmap Font data: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFontFromAtlas: function (key, atlasKey, atlasFrame, dataKey, dataType, xSpacing, ySpacing) { + + var frame = this.getFrameByName(atlasKey, atlasFrame); + + if (!frame) + { + return; + } + + var obj = { + font: null, + base: this.getBaseTexture(atlasKey), + frame: frame + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + var fontData; + + if (dataType === 'json') + { + fontData = this.getJSON(dataKey); + obj.font = Phaser.LoaderParser.jsonBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + else + { + fontData = this.getXML(dataKey); + obj.font = Phaser.LoaderParser.xmlBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + }, + + /** + * Add a new json object into the cache. + * + * @method Phaser.Cache#addJSON + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra json data. + */ + addJSON: function (key, url, data) { + + this._cache.json[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.json[key]); + + }, + + /** + * Add a new xml object into the cache. + * + * @method Phaser.Cache#addXML + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addXML: function (key, url, data) { + + this._cache.xml[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.xml[key]); + + }, + + /** + * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addVideo + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra video data. + * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. + */ + addVideo: function (key, url, data, isBlob) { + + this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true }; + + this._resolveURL(url, this._cache.video[key]); + + }, + + /** + * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addShader + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra shader data. + */ + addShader: function (key, url, data) { + + this._cache.shader[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.shader[key]); + + }, + + /** + * Add a new Phaser.RenderTexture in to the cache. + * + * @method Phaser.Cache#addRenderTexture + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture. + */ + addRenderTexture: function (key, texture) { + + this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') }; + + }, + + /** + * Add a new sprite sheet in to the cache. + * + * @method Phaser.Cache#addSpriteSheet + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sprite sheet data. + * @param {number} frameWidth - Width of the sprite sheet. + * @param {number} frameHeight - Height of the sprite sheet. + * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + */ + addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + var obj = { + key: key, + url: url, + data: data, + frameWidth: frameWidth, + frameHeight: frameHeight, + margin: margin, + spacing: spacing, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) + }; + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new texture atlas to the Cache. + * + * @method Phaser.Cache#addTextureAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra texture atlas data. + * @param {object} atlasData - Texture atlas frames data. + * @param {number} format - The format of the texture atlas. + */ + addTextureAtlas: function (key, url, data, atlasData, format) { + + var obj = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key); + } + else if (format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + obj.frameData = Phaser.AnimationParser.JSONDataPyxel(this.game, atlasData, key); + } + else + { + // Let's just work it out from the frames array + if (Array.isArray(atlasData.frames)) + { + obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key); + } + else + { + obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key); + } + } + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + //////////////////////////// + // Sound Related Methods // + //////////////////////////// + + /** + * Reload a Sound file from the server. + * + * @method Phaser.Cache#reloadSound + * @param {string} key - The key of the asset within the cache. + */ + reloadSound: function (key) { + + var _this = this; + + var sound = this.getSound(key); + + if (sound) + { + sound.data.src = sound.url; + + sound.data.addEventListener('canplaythrough', function () { + return _this.reloadSoundComplete(key); + }, false); + + sound.data.load(); + } + + }, + + /** + * Fires the onSoundUnlock event when the sound has completed reloading. + * + * @method Phaser.Cache#reloadSoundComplete + * @param {string} key - The key of the asset within the cache. + */ + reloadSoundComplete: function (key) { + + var sound = this.getSound(key); + + if (sound) + { + sound.locked = false; + this.onSoundUnlock.dispatch(key); + } + + }, + + /** + * Updates the sound object in the cache. + * + * @method Phaser.Cache#updateSound + * @param {string} key - The key of the asset within the cache. + */ + updateSound: function (key, property, value) { + + var sound = this.getSound(key); + + if (sound) + { + sound[property] = value; + } + + }, + + /** + * Add a new decoded sound. + * + * @method Phaser.Cache#decodedSound + * @param {string} key - The key of the asset within the cache. + * @param {object} data - Extra sound data. + */ + decodedSound: function (key, data) { + + var sound = this.getSound(key); + + sound.data = data; + sound.decoded = true; + sound.isDecoding = false; + + }, + + /** + * Check if the given sound has finished decoding. + * + * @method Phaser.Cache#isSoundDecoded + * @param {string} key - The key of the asset within the cache. + * @return {boolean} The decoded state of the Sound object. + */ + isSoundDecoded: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return sound.decoded; + } + + }, + + /** + * Check if the given sound is ready for playback. + * A sound is considered ready when it has finished decoding and the device is no longer touch locked. + * + * @method Phaser.Cache#isSoundReady + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the sound is decoded and the device is not touch locked. + */ + isSoundReady: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return (sound.decoded && !this.game.sound.touchLocked); + } + + }, + + //////////////////////// + // Check Key Methods // + //////////////////////// + + /** + * Checks if a key for the given cache object type exists. + * + * @method Phaser.Cache#checkKey + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists, otherwise false. + */ + checkKey: function (cache, key) { + + if (this._cacheMap[cache][key]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given URL has been loaded into the Cache. + * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. + * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox + * which may cause double-load instances. + * + * @method Phaser.Cache#checkURL + * @param {string} url - The url to check for in the cache. + * @return {boolean} True if the url exists, otherwise false. + */ + checkURL: function (url) { + + if (this._urlMap[this._resolveURL(url)]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given key exists in the Canvas Cache. + * + * @method Phaser.Cache#checkCanvasKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkCanvasKey: function (key) { + + return this.checkKey(Phaser.Cache.CANVAS, key); + + }, + + /** + * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. + * + * @method Phaser.Cache#checkImageKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkImageKey: function (key) { + + return this.checkKey(Phaser.Cache.IMAGE, key); + + }, + + /** + * Checks if the given key exists in the Texture Cache. + * + * @method Phaser.Cache#checkTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXTURE, key); + + }, + + /** + * Checks if the given key exists in the Sound Cache. + * + * @method Phaser.Cache#checkSoundKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkSoundKey: function (key) { + + return this.checkKey(Phaser.Cache.SOUND, key); + + }, + + /** + * Checks if the given key exists in the Text Cache. + * + * @method Phaser.Cache#checkTextKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXT, key); + + }, + + /** + * Checks if the given key exists in the Physics Cache. + * + * @method Phaser.Cache#checkPhysicsKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkPhysicsKey: function (key) { + + return this.checkKey(Phaser.Cache.PHYSICS, key); + + }, + + /** + * Checks if the given key exists in the Tilemap Cache. + * + * @method Phaser.Cache#checkTilemapKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTilemapKey: function (key) { + + return this.checkKey(Phaser.Cache.TILEMAP, key); + + }, + + /** + * Checks if the given key exists in the Binary Cache. + * + * @method Phaser.Cache#checkBinaryKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBinaryKey: function (key) { + + return this.checkKey(Phaser.Cache.BINARY, key); + + }, + + /** + * Checks if the given key exists in the BitmapData Cache. + * + * @method Phaser.Cache#checkBitmapDataKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapDataKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPDATA, key); + + }, + + /** + * Checks if the given key exists in the BitmapFont Cache. + * + * @method Phaser.Cache#checkBitmapFontKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapFontKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPFONT, key); + + }, + + /** + * Checks if the given key exists in the JSON Cache. + * + * @method Phaser.Cache#checkJSONKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkJSONKey: function (key) { + + return this.checkKey(Phaser.Cache.JSON, key); + + }, + + /** + * Checks if the given key exists in the XML Cache. + * + * @method Phaser.Cache#checkXMLKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkXMLKey: function (key) { + + return this.checkKey(Phaser.Cache.XML, key); + + }, + + /** + * Checks if the given key exists in the Video Cache. + * + * @method Phaser.Cache#checkVideoKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkVideoKey: function (key) { + + return this.checkKey(Phaser.Cache.VIDEO, key); + + }, + + /** + * Checks if the given key exists in the Fragment Shader Cache. + * + * @method Phaser.Cache#checkShaderKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkShaderKey: function (key) { + + return this.checkKey(Phaser.Cache.SHADER, key); + + }, + + /** + * Checks if the given key exists in the Render Texture Cache. + * + * @method Phaser.Cache#checkRenderTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkRenderTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key); + + }, + + //////////////// + // Get Items // + //////////////// + + /** + * Get an item from a cache based on the given key and property. + * + * This method is mostly used internally by other Cache methods such as `getImage` but is exposed + * publicly for your own use as well. + * + * @method Phaser.Cache#getItem + * @param {string} key - The key of the asset within the cache. + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output. + * @param {string} [property] - If you require a specific property from the cache item, specify it here. + * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. + */ + getItem: function (key, cache, method, property) { + + if (!this.checkKey(cache, key)) + { + if (method) + { + console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.'); + } + } + else + { + if (property === undefined) + { + return this._cacheMap[cache][key]; + } + else + { + return this._cacheMap[cache][key][property]; + } + } + + return null; + + }, + + /** + * Gets a Canvas object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getCanvas + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The canvas object or `null` if no item could be found matching the given key. + */ + getCanvas: function (key) { + + return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas'); + + }, + + /** + * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. + * + * If you need the image used by a bitmap font or similar then please use those respective 'get' methods. + * + * @method Phaser.Cache#getImage + * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. + * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned. + * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. + */ + getImage: function (key, full) { + + if (key === undefined || key === null) + { + key = '__default'; + } + + if (full === undefined) { full = false; } + + var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage'); + + if (img === null) + { + img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage'); + } + + if (full) + { + return img; + } + else + { + return img.data; + } + + }, + + /** + * Get a single texture frame by key. + * + * You'd only do this to get the default Frame created for a non-atlas / spritesheet image. + * + * @method Phaser.Cache#getTextureFrame + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Frame} The frame data. + */ + getTextureFrame: function (key) { + + return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame'); + + }, + + /** + * Gets a Phaser.Sound object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSound + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Sound} The sound object. + */ + getSound: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSound'); + + }, + + /** + * Gets a raw Sound data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSoundData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The sound data. + */ + getSoundData: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data'); + + }, + + /** + * Gets a Text object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getText + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The text data. + */ + getText: function (key) { + + return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data'); + + }, + + /** + * Gets a Physics Data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can get either the entire data set, a single object or a single fixture of an object from it. + * + * @method Phaser.Cache#getPhysicsData + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all. + * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. + * @return {object} The requested physics object data if found. + */ + getPhysicsData: function (key, object, fixtureKey) { + + var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data'); + + if (data === null || object === undefined || object === null) + { + return data; + } + else + { + if (data[object]) + { + var fixtures = data[object]; + + // Try to find a fixture by its fixture key if given + if (fixtures && fixtureKey) + { + for (var fixture in fixtures) + { + // This contains the fixture data of a polygon or a circle + fixture = fixtures[fixture]; + + // Test the key + if (fixture.fixtureKey === fixtureKey) + { + return fixture; + } + } + + // We did not find the requested fixture + console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"'); + } + else + { + return fixtures; + } + } + else + { + console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"'); + } + } + + return null; + + }, + + /** + * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getTilemapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The raw tilemap data in CSV or JSON format. + */ + getTilemapData: function (key) { + + return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData'); + + }, + + /** + * Gets a binary object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBinary + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The binary data object. + */ + getBinary: function (key) { + + return this.getItem(key, Phaser.Cache.BINARY, 'getBinary'); + + }, + + /** + * Gets a BitmapData object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. + */ + getBitmapData: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data'); + + }, + + /** + * Gets a Bitmap Font object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapFont + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not. + */ + getBitmapFont: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont'); + + }, + + /** + * Gets a JSON object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can either return the object by reference (the default), or return a clone + * of it by setting the `clone` argument to `true`. + * + * @method Phaser.Cache#getJSON + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false) + * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. + */ + getJSON: function (key, clone) { + + var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data'); + + if (data) + { + if (clone) + { + return Phaser.Utils.extend(true, Array.isArray(data) ? [] : {}, data); + } + else + { + return data; + } + } + else + { + return null; + } + + }, + + /** + * Gets an XML object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getXML + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The XML object. + */ + getXML: function (key) { + + return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data'); + + }, + + /** + * Gets a Phaser.Video object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getVideo + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Video} The video object. + */ + getVideo: function (key) { + + return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo'); + + }, + + /** + * Gets a fragment shader object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getShader + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {string} The shader object. + */ + getShader: function (key) { + + return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data'); + + }, + + /** + * Gets a RenderTexture object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getRenderTexture + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame. + */ + getRenderTexture: function (key) { + + return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture'); + + }, + + //////////////////////////// + // Frame Related Methods // + //////////////////////////// + + /** + * Gets a PIXI.BaseTexture by key from the given Cache. + * + * @method Phaser.Cache#getBaseTexture + * @param {string} key - Asset key of the image for which you want the BaseTexture for. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {PIXI.BaseTexture} The BaseTexture object. + */ + getBaseTexture: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getBaseTexture', 'base'); + + }, + + /** + * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. + * + * @method Phaser.Cache#getFrame + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.Frame} The frame data. + */ + getFrame: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrame', 'frame'); + + }, + + /** + * Get the total number of frames contained in the FrameData object specified by the given key. + * + * @method Phaser.Cache#getFrameCount + * @param {string} key - Asset key of the FrameData you want. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {number} Then number of frames. 0 if the image is not found. + */ + getFrameCount: function (key, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.total; + } + else + { + return 0; + } + + }, + + /** + * Gets a Phaser.FrameData object from the Image Cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.FrameData} The frame data. + */ + getFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrameData', 'frameData'); + + }, + + /** + * Check if the FrameData for the given key exists in the Image Cache. + * + * @method Phaser.Cache#hasFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {boolean} True if the given key has frameData in the cache, otherwise false. + */ + hasFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return (this.getItem(key, cache, '', 'frameData') !== null); + + }, + + /** + * Replaces a set of frameData with a new Phaser.FrameData object. + * + * @method Phaser.Cache#updateFrameData + * @param {string} key - The unique key by which you will reference this object. + * @param {number} frameData - The new FrameData. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + */ + updateFrameData: function (key, frameData, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + if (this._cacheMap[cache][key]) + { + this._cacheMap[cache][key].frameData = frameData; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByIndex + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {number} index - The index of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByIndex: function (key, index, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrame(index); + } + else + { + return null; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByName + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {string} name - The name of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByName: function (key, name, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrameByName(name); + } + else + { + return null; + } + + }, + + /** + * Get a cached object by the URL. + * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. + * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. + * + * @method Phaser.Cache#getURL + * @param {string} url - The url for the object loaded to get from the cache. + * @return {object} The cached object. + */ + getURL: function (url) { + + var url = this._resolveURL(url); + + if (url) + { + return this._urlMap[url]; + } + else + { + console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false'); + return null; + } + + }, + + /** + * Gets all keys used in the requested Cache. + * + * @method Phaser.Cache#getKeys + * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. + * @return {Array} The array of keys in the requested cache. + */ + getKeys: function (cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + var out = []; + + if (this._cacheMap[cache]) + { + for (var key in this._cacheMap[cache]) + { + if (key !== '__default' && key !== '__missing') + { + out.push(key); + } + } + } + + return out; + + }, + + ///////////////////// + // Remove Methods // + ///////////////////// + + /** + * Removes a canvas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeCanvas + * @param {string} key - Key of the asset you want to remove. + */ + removeCanvas: function (key) { + + delete this._cache.canvas[key]; + + }, + + /** + * Removes an image from the cache. + * + * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. + * + * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeImage + * @param {string} key - Key of the asset you want to remove. + * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed? + */ + removeImage: function (key, destroyBaseTexture) { + + if (destroyBaseTexture === undefined) { destroyBaseTexture = true; } + + var img = this.getImage(key, true); + + if (destroyBaseTexture && img.base) + { + img.base.destroy(); + } + + delete this._cache.image[key]; + + }, + + /** + * Removes a sound from the cache. + * + * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will + * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then + * you must finish your house-keeping and destroy them all yourself first, before calling this method. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSound + * @param {string} key - Key of the asset you want to remove. + */ + removeSound: function (key) { + + delete this._cache.sound[key]; + + }, + + /** + * Removes a text file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeText + * @param {string} key - Key of the asset you want to remove. + */ + removeText: function (key) { + + delete this._cache.text[key]; + + }, + + /** + * Removes a physics data file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removePhysics + * @param {string} key - Key of the asset you want to remove. + */ + removePhysics: function (key) { + + delete this._cache.physics[key]; + + }, + + /** + * Removes a tilemap from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTilemap + * @param {string} key - Key of the asset you want to remove. + */ + removeTilemap: function (key) { + + delete this._cache.tilemap[key]; + + }, + + /** + * Removes a binary file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBinary + * @param {string} key - Key of the asset you want to remove. + */ + removeBinary: function (key) { + + delete this._cache.binary[key]; + + }, + + /** + * Removes a bitmap data from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapData + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapData: function (key) { + + delete this._cache.bitmapData[key]; + + }, + + /** + * Removes a bitmap font from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapFont + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapFont: function (key) { + + delete this._cache.bitmapFont[key]; + + }, + + /** + * Removes a json object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeJSON + * @param {string} key - Key of the asset you want to remove. + */ + removeJSON: function (key) { + + delete this._cache.json[key]; + + }, + + /** + * Removes a xml object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeXML + * @param {string} key - Key of the asset you want to remove. + */ + removeXML: function (key) { + + delete this._cache.xml[key]; + + }, + + /** + * Removes a video from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeVideo + * @param {string} key - Key of the asset you want to remove. + */ + removeVideo: function (key) { + + delete this._cache.video[key]; + + }, + + /** + * Removes a shader from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeShader + * @param {string} key - Key of the asset you want to remove. + */ + removeShader: function (key) { + + delete this._cache.shader[key]; + + }, + + /** + * Removes a Render Texture from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeRenderTexture + * @param {string} key - Key of the asset you want to remove. + */ + removeRenderTexture: function (key) { + + delete this._cache.renderTexture[key]; + + }, + + /** + * Removes a Sprite Sheet from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSpriteSheet + * @param {string} key - Key of the asset you want to remove. + */ + removeSpriteSheet: function (key) { + + delete this._cache.spriteSheet[key]; + + }, + + /** + * Removes a Texture Atlas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTextureAtlas + * @param {string} key - Key of the asset you want to remove. + */ + removeTextureAtlas: function (key) { + + delete this._cache.image[key]; + + }, + + /** + * Empties out all of the GL Textures from Images stored in the cache. + * This is called automatically when the WebGL context is lost and then restored. + * + * @method Phaser.Cache#clearGLTextures + * @protected + */ + clearGLTextures: function () { + + for (var key in this._cache.image) + { + this._cache.image[key].base._glTextures = []; + } + + }, + + /** + * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`. + * This is then looked-up by the Cache.getURL and Cache.checkURL calls. + * + * @method Phaser.Cache#_resolveURL + * @private + * @param {string} url - The URL to resolve. This is appended to Loader.baseURL. + * @param {object} [data] - The data associated with the URL to be stored to the URL Map. + * @return {string} The resolved URL. + */ + _resolveURL: function (url, data) { + + if (!this.autoResolveURL) + { + return null; + } + + this._urlResolver.src = this.game.load.baseURL + url; + + this._urlTemp = this._urlResolver.src; + + // Ensure no request is actually made + this._urlResolver.src = ''; + + // Record the URL to the map + if (data) + { + this._urlMap[this._urlTemp] = data; + } + + return this._urlTemp; + + }, + + /** + * Clears the cache. Removes every local cache object reference. + * If an object in the cache has a `destroy` method it will be called; + * otherwise, `destroy` will be called on any of the object's `base`, `data`, + * `frameData`, or `texture` properties. + * + * @method Phaser.Cache#destroy + */ + destroy: function () { + + for (var i = 0; i < this._cacheMap.length; i++) + { + var cache = this._cacheMap[i]; + + for (var key in cache) + { + if (key !== '__default' && key !== '__missing') + { + this.destroyItem(cache[key]); + + delete cache[key]; + } + } + } + + this._urlMap = null; + this._urlResolver = null; + this._urlTemp = null; + + }, + + /** + * @method Phaser.Cache#destroyItem + * @protected + * @param {object} item + */ + destroyItem: function (item) { + + if (item.destroy) + { + item.destroy(); + } + else + { + if (item.base && item.base.destroy) + { + item.base.destroy(); + } + + if (item.data && item.data.destroy) + { + item.data.destroy(); + } + + if (item.frameData && item.frameData.destroy) + { + item.frameData.destroy(); + } + + if (item.texture && item.texture.destroy) + { + item.texture.destroy(true); + } + } + + }, + + /** + * Starts loading the DEFAULT and MISSING images. + * + * @private + */ + _addImages: function () { + + this._pendingCount = 0; + + this.addDefaultImage(); + this.addMissingImage(); + + var self = this; + var readyTimeout = Phaser.Cache.READY_TIMEOUT; + + if (Phaser.Cache.READY_TIMEOUT > 0) + { + setTimeout(function () { + if (!self.isReady) + { + console.warn('Phaser.Cache: Still waiting for images after %s ms.', readyTimeout); + + self._ready(); + } + }, Phaser.Cache.READY_TIMEOUT); + } + else + { + this._ready(); + } + + }, + + + /** + * Increments the pending count. + * + * @private + */ + _addPending: function () { + + this._pendingCount += 1; + + }, + + + /** + * Decrements the pending count and checks if complete. + * + * @private + */ + _removePending: function () { + + this._pendingCount -= 1; + this._checkReady(); + + }, + + + /** + * Calls {@link #_ready} if no pending items remain. + * + * @private + */ + _checkReady: function () { + + if (this.isReady) + { + this._ready(); + } + + }, + + + /** + * Resets pending count and triggers {@link #onReady}. + * + * @private + */ + _ready: function () { + + this._pendingCount = 0; + this.onReady.dispatch(this); + + } + +}; + +Phaser.Cache.prototype.constructor = Phaser.Cache; + +/** +* The DEFAULT and MISSING textures have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). +* +* @property {boolean} Phaser.Cache#isReady +*/ +Object.defineProperty(Phaser.Cache.prototype, 'isReady', { + get: function () { + return this._pendingCount <= 0; + } +}); + +/* jshint wsh:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* +* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. +* +* Parallel loading (see {@link #enableParallel}) is supported and enabled by default. +* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}. +* +* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and +* [Shoebox](http://renderhjs.net/shoebox/) +* +* @class Phaser.Loader +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Loader = function (game) { + + /** + * Local reference to game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + /** + * Local reference to the Phaser.Cache. + * @property {Phaser.Cache} cache + * @protected + */ + this.cache = game.cache; + + /** + * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * True if the Loader is in the process of loading the queue. + * @property {boolean} isLoading + * @default + */ + this.isLoading = false; + + /** + * True if all assets in the queue have finished loading. + * @property {boolean} hasLoaded + * @default + */ + this.hasLoaded = false; + + /** + * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}. + * + * This property is an object containing: sprite, rect, direction, width and height + * + * @property {?object} preloadSprite + * @protected + */ + this.preloadSprite = null; + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * @property {boolean|string} crossOrigin + * @default + */ + this.crossOrigin = false; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * Useful if allowing the asset base url to be configured outside of the game code. + * The string _must_ end with a "/". + * + * @property {string} baseURL + */ + this.baseURL = ''; + + /** + * The value of `path`, if set, is placed before any _relative_ file path given. For example: + * + * ```javascript + * load.path = "images/sprites/"; + * load.image("ball", "ball.png"); + * load.image("tree", "level1/oaktree.png"); + * load.image("boom", "http://server.com/explode.png"); + * ``` + * + * Would load the `ball` file from `images/sprites/ball.png` and the tree from + * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL + * given as it's an absolute URL. + * + * Please note that the path is added before the filename but *after* the baseURL (if set.) + * + * The string _must_ end with a "/". + * + * @property {string} path + */ + this.path = ''; + + /** + * Used to map the application mime-types to to the Accept header in XHR requests. + * If you don't require these mappings, or they cause problems on your server, then + * remove them from the headers object and the XHR request will not try to use them. + * + * This object can also be used to set the `X-Requested-With` header to + * `XMLHttpRequest` (or any other value you need). To enable this do: + * + * ```javascript + * this.load.headers.requestedWith = 'XMLHttpRequest' + * ``` + * + * before adding anything to the Loader. The XHR loader will then call: + * + * ```javascript + * setRequestHeader('X-Requested-With', this.headers['requestedWith']) + * ``` + * + * @property {object} headers + * @default + */ + this.headers = { + "requestedWith": false, + "json": "application/json", + "xml": "application/xml" + }; + + /** + * This event is dispatched when the loading process starts: before the first file has been requested, + * but after all the initial packs have been loaded. + * + * @property {Phaser.Signal} onLoadStart + */ + this.onLoadStart = new Phaser.Signal(); + + /** + * This event is dispatched when the final file in the load queue has either loaded or failed. + * + * @property {Phaser.Signal} onLoadComplete + */ + this.onLoadComplete = new Phaser.Signal(); + + /** + * This event is dispatched when an asset pack has either loaded or failed to load. + * + * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. + * + * Params: `(pack key, success?, total packs loaded, total packs)` + * + * @property {Phaser.Signal} onPackComplete + */ + this.onPackComplete = new Phaser.Signal(); + + /** + * This event is dispatched immediately before a file starts loading. + * It's possible the file may fail (eg. download error, invalid format) after this event is sent. + * + * Params: `(progress, file key, file url)` + * + * @property {Phaser.Signal} onFileStart + */ + this.onFileStart = new Phaser.Signal(); + + /** + * This event is dispatched when a file has either loaded or failed to load. + * + * Any function bound to this will receive the following parameters: + * + * progress, file key, success?, total loaded files, total files + * + * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. + * + * @property {Phaser.Signal} onFileComplete + */ + this.onFileComplete = new Phaser.Signal(); + + /** + * This event is dispatched when a file (or pack) errors as a result of the load request. + * + * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. + * + * Params: `(file key, file)` + * + * @property {Phaser.Signal} onFileError + */ + this.onFileError = new Phaser.Signal(); + + /** + * If true (the default) then parallel downloading will be enabled. + * + * To disable all parallel downloads this must be set to false prior to any resource being loaded. + * + * @property {boolean} enableParallel + */ + this.enableParallel = true; + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Many current browsers limit 6 requests per domain; this is slightly conservative. + * + * This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently. + * + * @property {integer} maxParallelDownloads + */ + this.maxParallelDownloads = 4; + + /** + * A counter: if more than zero, files will be automatically added as a synchronization point. + * @property {integer} _withSyncPointDepth; + */ + this._withSyncPointDepth = 0; + + /** + * Contains all the information for asset files (including packs) to load. + * + * File/assets are only removed from the list after all loading completes. + * + * @property {file[]} _fileList + * @private + */ + this._fileList = []; + + /** + * Inflight files (or packs) that are being fetched/processed. + * + * This means that if there are any files in the flight queue there should still be processing + * going on; it should only be empty before or after loading. + * + * The files in the queue may have additional properties added to them, + * including `requestObject` which is normally the associated XHR. + * + * @property {file[]} _flightQueue + * @private + */ + this._flightQueue = []; + + /** + * The offset into the fileList past all the complete (loaded or error) entries. + * + * @property {integer} _processingHead + * @private + */ + this._processingHead = 0; + + /** + * True when the first file (not pack) has loading started. + * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded. + * + * @property {boolean} _initialPacksLoaded + * @private + */ + this._fileLoadStarted = false; + + /** + * Total packs seen - adjusted when a pack is added. + * @property {integer} _totalPackCount + * @private + */ + this._totalPackCount = 0; + + /** + * Total files seen - adjusted when a file is added. + * @property {integer} _totalFileCount + * @private + */ + this._totalFileCount = 0; + + /** + * Total packs loaded - adjusted just prior to `onPackComplete`. + * @property {integer} _loadedPackCount + * @private + */ + this._loadedPackCount = 0; + + /** + * Total files loaded - adjusted just prior to `onFileComplete`. + * @property {integer} _loadedFileCount + * @private + */ + this._loadedFileCount = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_PHASER_JSON = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5; + +Phaser.Loader.prototype = { + + /** + * Set a Sprite to be a "preload" sprite by passing it to this method. + * + * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. + * This allows you to easily make loading bars for games. + * + * The sprite will automatically be made visible when calling this. + * + * @method Phaser.Loader#setPreloadSprite + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load. + * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. + */ + setPreloadSprite: function (sprite, direction) { + + direction = direction || 0; + + this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null }; + + if (direction === 0) + { + // Horizontal rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height); + } + else + { + // Vertical rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1); + } + + sprite.crop(this.preloadSprite.rect); + + sprite.visible = true; + + }, + + /** + * Called automatically by ScaleManager when the game resizes in RESIZE scalemode. + * + * This can be used to adjust the preloading sprite size, eg. + * + * @method Phaser.Loader#resize + * @protected + */ + resize: function () { + + if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height) + { + this.preloadSprite.rect.height = this.preloadSprite.sprite.height; + } + + }, + + /** + * Check whether a file/asset with a specific key is queued to be loaded. + * + * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey} + * + * @method Phaser.Loader#checkKeyExists + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ + checkKeyExists: function (type, key) { + + return this.getAssetIndex(type, key) > -1; + + }, + + /** + * Get the queue-index of the file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAssetIndex + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {number} The index of this key in the filelist, or -1 if not found. + * The index may change and should only be used immediately following this call + */ + getAssetIndex: function (type, key) { + + var bestFound = -1; + + for (var i = 0; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + if (file.type === type && file.key === key) + { + bestFound = i; + + // An already loaded/loading file may be superceded. + if (!file.loaded && !file.loading) + { + break; + } + } + } + + return bestFound; + + }, + + /** + * Find a file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAsset + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. + * The index may change and should only be used immediately following this call. + */ + getAsset: function (type, key) { + + var fileIndex = this.getAssetIndex(type, key); + + if (fileIndex > -1) + { + return { index: fileIndex, file: this._fileList[fileIndex] }; + } + + return false; + + }, + + /** + * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. + * + * This will abort any loading and clear any queued assets. + * + * Optionally you can clear any associated events. + * + * @method Phaser.Loader#reset + * @protected + * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared. + * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them. + */ + reset: function (hard, clearEvents) { + + if (clearEvents === undefined) { clearEvents = false; } + + if (this.resetLocked) + { + return; + } + + if (hard) + { + this.preloadSprite = null; + } + + this.isLoading = false; + + this._processingHead = 0; + this._fileList.length = 0; + this._flightQueue.length = 0; + + this._fileLoadStarted = false; + this._totalFileCount = 0; + this._totalPackCount = 0; + this._loadedPackCount = 0; + this._loadedFileCount = 0; + + if (clearEvents) + { + this.onLoadStart.removeAll(); + this.onLoadComplete.removeAll(); + this.onPackComplete.removeAll(); + this.onFileStart.removeAll(); + this.onFileComplete.removeAll(); + this.onFileError.removeAll(); + } + + }, + + /** + * Internal function that adds a new entry to the file list. Do not call directly. + * + * @method Phaser.Loader#addToFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} [url] - The URL the asset will be loaded from. + * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. + * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. + * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. + * @return {Phaser.Loader} This instance of the Phaser Loader. + */ + addToFileList: function (type, key, url, properties, overwrite, extension) { + + if (overwrite === undefined) { overwrite = false; } + + if (key === undefined || key === '') + { + console.warn("Phaser.Loader: Invalid or no key given of type " + type); + return this; + } + + if (url === undefined || url === null) + { + if (extension) + { + url = key + extension; + } + else + { + console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key); + return this; + } + } + + var file = { + type: type, + key: key, + path: this.path, + url: url, + syncPoint: this._withSyncPointDepth > 0, + data: null, + loading: false, + loaded: false, + error: false + }; + + if (properties) + { + for (var prop in properties) + { + file[prop] = properties[prop]; + } + } + + var fileIndex = this.getAssetIndex(type, key); + + if (overwrite && fileIndex > -1) + { + var currentFile = this._fileList[fileIndex]; + + if (!currentFile.loading && !currentFile.loaded) + { + this._fileList[fileIndex] = file; + } + else + { + this._fileList.push(file); + this._totalFileCount++; + } + } + else if (fileIndex === -1) + { + this._fileList.push(file); + this._totalFileCount++; + } + + return this; + + }, + + /** + * Internal function that replaces an existing entry in the file list with a new one. Do not call directly. + * + * @method Phaser.Loader#replaceInFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} url - The URL the asset will be loaded from. + * @param {object} properties - Any additional properties needed to load the file. + */ + replaceInFileList: function (type, key, url, properties) { + + return this.addToFileList(type, key, url, properties, true); + + }, + + /** + * Add a JSON resource pack ('packfile') to the Loader. + * + * A packfile is a JSON file that contains a list of assets to the be loaded. + * Please see the example 'loader/asset pack' in the Phaser Examples repository. + * + * Packs are always put before the first non-pack file that is not loaded / loading. + * + * This means that all packs added before any loading has started are added to the front + * of the file queue, in the order added. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#pack + * @param {string} key - Unique asset key of this resource pack. + * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. + * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO + * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. + * @return {Phaser.Loader} This Loader instance. + */ + pack: function (key, url, data, callbackContext) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (callbackContext === undefined) { callbackContext = null; } + + if (!url && !data) + { + console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.'); + + return this; + } + + var pack = { + type: 'packfile', + key: key, + url: url, + path: this.path, + syncPoint: true, + data: null, + loading: false, + loaded: false, + error: false, + callbackContext: callbackContext + }; + + // A data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + pack.data = data || {}; + + // Already consider 'loaded' + pack.loaded = true; + } + + // Add before first non-pack/no-loaded ~ last pack from start prior to loading + // (Read one past for splice-to-end) + for (var i = 0; i < this._fileList.length + 1; i++) + { + var file = this._fileList[i]; + + if (!file || (!file.loaded && !file.loading && file.type !== 'packfile')) + { + this._fileList.splice(i, 0, pack); + this._totalPackCount++; + break; + } + } + + return this; + + }, + + /** + * Adds an Image to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * This method also supports passing in a texture object as the `url` argument. This allows you to load + * compressed textures into Phaser. You can also use `Loader.texture` to do this. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.image('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * @method Phaser.Loader#image + * @param {string} key - Unique asset key of this image file. + * @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + image: function (key, url, overwrite) { + + if (typeof url === 'object') + { + return this.texture(key, url, overwrite); + } + else + { + return this.addToFileList('image', key, url, undefined, overwrite, '.png'); + } + + }, + + /** + * Generate an image from a BitmapData object and add it to the current load queue. + * + * @method Phaser.Loader#imageFromBitmapData + * @param {string} key - Unique asset key for the generated image. + * @param {Phaser.BitmapData} bitmapData + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + imageFromBitmapData: function (key, bitmapData, overwrite) { + + return this.image(key, bitmapData.canvas.toDataURL('image/png'), overwrite); + + }, + + /** + * Generate a grid image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromGrid + * @see Phaser.Create#grid + */ + imageFromGrid: function (key, width, height, cellWidth, cellHeight, color) { + + return this.imageFromBitmapData(key, this.game.create.grid(key, width, height, cellWidth, cellHeight, color, false)); + + }, + + /** + * Generate a texture image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromTexture + * @see Phaser.Create#texture + */ + imageFromTexture: function (key, data, pixelWidth, pixelHeight, palette) { + + return this.imageFromBitmapData(key, this.game.create.texture(key, data, pixelWidth, pixelHeight, palette, false)); + + }, + + /** + * Adds a Compressed Texture Image to the current load queue. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.texture('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#texture + * @param {string} key - Unique asset key of this image file. + * @param {object} object - The texture path data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + texture: function (key, object, overwrite) { + + if (this.game.renderType === Phaser.WEBGL) + { + var compression = this.game.renderer.extensions.compression; + var exkey; + + for (exkey in object) + { + if (exkey.toUpperCase() in compression) + { + return this.addToFileList('texture', key, object[exkey], undefined, overwrite, '.pvr'); + } + } + } + + // Check if we have a truecolor texture to fallback. + // Also catches calls to this function that are from a Canvas renderer + + if (object['truecolor']) + { + this.addToFileList('image', key, object['truecolor'], undefined, overwrite, '.png'); + } + + return this; + + }, + + /** + * Adds an array of images to the current load queue. + * + * It works by passing each element of the array to the Loader.image method. + * + * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. + * + * Retrieve the images via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#images + * @param {array} keys - An array of unique asset keys of the image files. + * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. + * @return {Phaser.Loader} This Loader instance. + */ + images: function (keys, urls) { + + if (Array.isArray(urls)) + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i], urls[i]); + } + } + else + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i]); + } + } + + return this; + + }, + + /** + * Adds a Text file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getText(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#text + * @param {string} key - Unique asset key of the text file. + * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + text: function (key, url, overwrite) { + + return this.addToFileList('text', key, url, undefined, overwrite, '.txt'); + + }, + + /** + * Adds a JSON file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#json + * @param {string} key - Unique asset key of the json file. + * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + json: function (key, url, overwrite) { + + return this.addToFileList('json', key, url, undefined, overwrite, '.json'); + + }, + + /** + * Adds a fragment shader file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getShader(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" + * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#shader + * @param {string} key - Unique asset key of the fragment file. + * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + shader: function (key, url, overwrite) { + + return this.addToFileList('shader', key, url, undefined, overwrite, '.frag'); + + }, + + /** + * Adds an XML file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getXML(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#xml + * @param {string} key - Unique asset key of the xml file. + * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + xml: function (key, url, overwrite) { + + return this.addToFileList('xml', key, url, undefined, overwrite, '.xml'); + + }, + + /** + * Adds a JavaScript file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. + * If you do not desire this action then provide a URL. + * + * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! + * + * A callback, which will be invoked as the script tag has been created, can also be specified. + * The callback must return relevant `data`. + * + * @method Phaser.Loader#script + * @param {string} key - Unique asset key of the script file. + * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing. + * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. + * @return {Phaser.Loader} This Loader instance. + */ + script: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + if (callback !== false && callbackContext === undefined) { callbackContext = this; } + + return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js'); + + }, + + /** + * Adds a binary file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBinary(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. + * If you do not desire this action then provide a URL. + * + * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. + * When the callback is called it will be passed 2 parameters: the key of the file and the file data. + * + * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. + * + * @method Phaser.Loader#binary + * @param {string} key - Unique asset key of the binary file. + * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it. + * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context. + * @return {Phaser.Loader} This Loader instance. + */ + binary: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + // Why is the default callback context the ..callback? + if (callback !== false && callbackContext === undefined) { callbackContext = callback; } + + return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin'); + + }, + + /** + * Adds a Sprite Sheet to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal + * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. + * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. + * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming + * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. + * If you've got an atlas then use `Loader.atlas` instead. + * + * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#spritesheet + * @param {string} key - Unique asset key of the sheet file. + * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet. + * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.Loader} This Loader instance. + */ + spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing, skipFrames: skipFrames }, false, '.png'); + + }, + + /** + * Adds an audio file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getSound(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. + * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. + * The solution is to use a lower encoding rate such as 44100 Hz. + * + * @method Phaser.Loader#audio + * @param {string} key - Unique asset key of the audio file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp3']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audio: function (key, urls, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (autoDecode === undefined) { autoDecode = true; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); + + }, + + /** + * Adds an audio sprite file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Audio Sprites are a combination of audio files and a JSON configuration. + * + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * Retrieve the file via `Cache.getSoundData(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#audioSprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (jsonURL === undefined) { jsonURL = null; } + if (jsonData === undefined) { jsonData = null; } + if (autoDecode === undefined) { autoDecode = true; } + + this.audio(key, urls, autoDecode); + + if (jsonURL) + { + this.json(key + '-audioatlas', jsonURL); + } + else if (jsonData) + { + if (typeof jsonData === 'string') + { + jsonData = JSON.parse(jsonData); + } + + this.cache.addJSON(key + '-audioatlas', '', jsonData); + } + else + { + console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object'); + } + + return this; + + }, + + /** + * A legacy alias for Loader.audioSprite. Please see that method for documentation. + * + * @method Phaser.Loader#audiosprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode); + + }, + + /** + * Adds a video file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getVideo(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. + * + * @method Phaser.Loader#video + * @param {string} key - Unique asset key of the video file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp4']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete. + * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. + * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. + * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the + * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. + * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set. + * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. + * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. + * @return {Phaser.Loader} This Loader instance. + */ + video: function (key, urls, loadEvent, asBlob) { + + if (loadEvent === undefined) + { + if (this.game.device.firefox) + { + loadEvent = 'loadeddata'; + } + else + { + loadEvent = 'canplaythrough'; + } + } + + if (asBlob === undefined) { asBlob = false; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent }); + + }, + + /** + * Adds a Tile Map data file to the current load queue. + * + * Phaser can load data in two different formats: CSV and Tiled JSON. + * + * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". + * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#tilemap + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. + * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + * @return {Phaser.Loader} This Loader instance. + */ + tilemap: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Tilemap.CSV; } + + if (!url && !data) + { + if (format === Phaser.Tilemap.CSV) + { + url = key + '.csv'; + } + else + { + url = key + '.json'; + } + } + + // A map data object has been given + if (data) + { + switch (format) + { + // A csv string or object has been given + case Phaser.Tilemap.CSV: + break; + + // A json string or object has been given + case Phaser.Tilemap.TILED_JSON: + + if (typeof data === 'string') + { + data = JSON.parse(data); + } + break; + } + + this.cache.addTilemap(key, null, data, format); + } + else + { + this.addToFileList('tilemap', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds a physics data file to the current load queue. + * + * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". + * It will always use `.json` as the extension. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#physics + * @param {string} key - Unique asset key of the physics json data. + * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. + * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data. + * @return {Phaser.Loader} This Loader instance. + */ + physics: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; } + + if (!url && !data) + { + url = key + '.json'; + } + + // A map data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + this.cache.addPhysicsData(key, null, data, format); + } + else + { + this.addToFileList('physics', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds Bitmap Font files to the current load queue. + * + * To create the Bitmap Font files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `xmlData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#bitmapFont + * @param {string} key - Unique asset key of the bitmap font. + * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". + * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". + * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json). + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + * @return {Phaser.Loader} This Loader instance. + */ + bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (atlasURL === null && atlasData === null) + { + atlasURL = key + '.xml'; + } + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + // A URL to a json/xml atlas has been given + if (atlasURL) + { + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing }); + } + else + { + // A stringified xml/json atlas has been given + if (typeof atlasData === 'string') + { + var json, xml; + + try + { + json = JSON.parse(atlasData); + } + catch ( e ) + { + xml = this.parseXml(atlasData); + } + + if (!xml && !json) + { + throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given"); + } + + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml, + atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing }); + } + } + + return this; + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONArray + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONHash + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * This call expects the atlas data to be in the Starling XML data format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasXML + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasXML: function (key, textureURL, atlasURL, atlasData) { + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (!atlasURL && !atlasData) + { + atlasURL = key + '.xml'; + } + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlas + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. + * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING. + * @return {Phaser.Loader} This Loader instance. + */ + atlas: function (key, textureURL, atlasURL, atlasData, format) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } + + if (!atlasURL && !atlasData) + { + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + atlasURL = key + '.xml'; + } + else + { + atlasURL = key + '.json'; + } + } + + // A URL to a json/xml file has been given + if (atlasURL) + { + this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); + } + else + { + switch (format) + { + // A json string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: + + if (typeof atlasData === 'string') + { + atlasData = JSON.parse(atlasData); + } + break; + + // An xml string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: + + if (typeof atlasData === 'string') + { + var xml = this.parseXml(atlasData); + + if (!xml) + { + throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); + } + + atlasData = xml; + } + break; + } + + this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); + + } + + return this; + + }, + + /** + * Add a synchronization point to the assets / files added within the supplied callback. + * + * A synchronization point denotes that an asset _must_ be completely loaded before + * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait + * for previous assets to load (unless they are sync-points). Resources, such as packs, may still + * be downloaded around sync-points, as long as they do not finalize loading. + * + * @method Phaser.Loader#withSyncPoint + * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader. + * @param {object} [callbackContext=(loader)] - Context for the callback. + * @return {Phaser.Loader} This Loader instance. + */ + withSyncPoint: function (callback, callbackContext) { + + this._withSyncPointDepth++; + + try { + callback.call(callbackContext || this, this); + } finally { + this._withSyncPointDepth--; + } + + return this; + }, + + /** + * Add a synchronization point to a specific file/asset in the load queue. + * + * This has no effect on already loaded assets. + * + * @method Phaser.Loader#addSyncPoint + * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc). + * @param {string} key - Key of the file you want to turn into a sync point. + * @return {Phaser.Loader} This Loader instance. + * @see {@link Phaser.Loader#withSyncPoint withSyncPoint} + */ + addSyncPoint: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + asset.file.syncPoint = true; + } + + return this; + }, + + /** + * Remove a file/asset from the loading queue. + * + * A file that is loaded or has started loading cannot be removed. + * + * @method Phaser.Loader#removeFile + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - Key of the file you want to remove. + */ + removeFile: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + if (!asset.loaded && !asset.loading) + { + this._fileList.splice(asset.index, 1); + } + } + + }, + + /** + * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead. + * + * @method Phaser.Loader#removeAll + * @protected + */ + removeAll: function () { + + this._fileList.length = 0; + this._flightQueue.length = 0; + + }, + + /** + * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. + * + * @method Phaser.Loader#start + */ + start: function () { + + if (this.isLoading) + { + return; + } + + this.hasLoaded = false; + this.isLoading = true; + + this.updateProgress(); + + this.processLoadQueue(); + + }, + + /** + * Process the next item(s) in the file/asset queue. + * + * Process the queue and start loading enough items to fill up the inflight queue. + * + * If a sync-file is encountered then subsequent asset processing is delayed until it completes. + * The exception to this rule is that packfiles can be downloaded (but not processed) even if + * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel. + * such as during the start phaser. + * + * @method Phaser.Loader#processLoadQueue + * @private + */ + processLoadQueue: function () { + + if (!this.isLoading) + { + console.warn('Phaser.Loader - active loading canceled / reset'); + this.finishedLoading(true); + return; + } + + // Empty the flight queue as applicable + for (var i = 0; i < this._flightQueue.length; i++) + { + var file = this._flightQueue[i]; + + if (file.loaded || file.error) + { + this._flightQueue.splice(i, 1); + i--; + + file.loading = false; + file.requestUrl = null; + file.requestObject = null; + + if (file.error) + { + this.onFileError.dispatch(file.key, file); + } + + if (file.type !== 'packfile') + { + this._loadedFileCount++; + this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount); + } + else if (file.type === 'packfile' && file.error) + { + // Non-error pack files are handled when processing the file queue + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + } + } + + // When true further non-pack file downloads are suppressed + var syncblock = false; + + var inflightLimit = this.enableParallel ? Math.max(1, this.maxParallelDownloads) : 1; + + for (var i = this._processingHead; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + // Pack is fetched (ie. has data) and is currently at the start of the process queue. + if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead) + { + // Processing the pack / adds more files + this.processPack(file); + + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + if (file.loaded || file.error) + { + // Item at the start of file list finished, can skip it in future + if (i === this._processingHead) + { + this._processingHead = i + 1; + } + } + else if (!file.loading && this._flightQueue.length < inflightLimit) + { + // -> not loaded/failed, not loading + if (file.type === 'packfile' && !file.data) + { + // Fetches the pack data: the pack is processed above as it reaches queue-start. + // (Packs do not trigger onLoadStart or onFileStart.) + this._flightQueue.push(file); + file.loading = true; + + this.loadFile(file); + } + else if (!syncblock) + { + if (!this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this._flightQueue.push(file); + file.loading = true; + this.onFileStart.dispatch(this.progress, file.key, file.url); + + this.loadFile(file); + } + } + + if (!file.loaded && file.syncPoint) + { + syncblock = true; + } + + // Stop looking if queue full - or if syncblocked and there are no more packs. + // (As only packs can be loaded around a syncblock) + if (this._flightQueue.length >= inflightLimit || + (syncblock && this._loadedPackCount === this._totalPackCount)) + { + break; + } + } + + this.updateProgress(); + + // True when all items in the queue have been advanced over + // (There should be no inflight items as they are complete - loaded/error.) + if (this._processingHead >= this._fileList.length) + { + this.finishedLoading(); + } + else if (!this._flightQueue.length) + { + // Flight queue is empty but file list is not done being processed. + // This indicates a critical internal error with no known recovery. + console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled"); + + var _this = this; + + setTimeout(function () { + _this.finishedLoading(true); + }, 2000); + } + + }, + + /** + * The loading is all finished. + * + * @method Phaser.Loader#finishedLoading + * @private + * @param {boolean} [abnormal=true] - True if the loading finished abnormally. + */ + finishedLoading: function (abnormal) { + + if (this.hasLoaded) + { + return; + } + + this.hasLoaded = true; + this.isLoading = false; + + // If there were no files make sure to trigger the event anyway, for consistency + if (!abnormal && !this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this.reset(); + + this.onLoadComplete.dispatch(); + + // Check if the state still exists since destroy could have occurred while loading + if (this.game.state) + { + this.game.state.loadComplete(); + } + + }, + + /** + * Informs the loader that the given file resource has been fetched and processed; + * or such a request has failed. + * + * @method Phaser.Loader#asyncComplete + * @private + * @param {object} file + * @param {string} [error=''] - The error message, if any. No message implies no error. + */ + asyncComplete: function (file, errorMessage) { + + if (errorMessage === undefined) { errorMessage = ''; } + + file.loaded = true; + file.error = !!errorMessage; + + if (errorMessage) + { + file.errorMessage = errorMessage; + + console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage); + } + + this.processLoadQueue(); + + }, + + /** + * Process pack data. This will usually modify the file list. + * + * @method Phaser.Loader#processPack + * @private + * @param {object} pack + */ + processPack: function (pack) { + + var packData = pack.data[pack.key]; + + if (!packData) + { + console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key'); + return; + } + + for (var i = 0; i < packData.length; i++) + { + var file = packData[i]; + + switch (file.type) + { + case "image": + this.image(file.key, file.url, file.overwrite); + break; + + case "text": + this.text(file.key, file.url, file.overwrite); + break; + + case "json": + this.json(file.key, file.url, file.overwrite); + break; + + case "xml": + this.xml(file.key, file.url, file.overwrite); + break; + + case "script": + this.script(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "binary": + this.binary(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "spritesheet": + this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case "video": + this.video(file.key, file.urls); + break; + + case "audio": + this.audio(file.key, file.urls, file.autoDecode); + break; + + case "audiosprite": + this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode); + break; + + case "tilemap": + this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]); + break; + + case "physics": + this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]); + break; + + case "bitmapFont": + this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing); + break; + + case "atlasJSONArray": + this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasJSONHash": + this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasXML": + this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlas": + this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]); + break; + + case "shader": + this.shader(file.key, file.url, file.overwrite); + break; + } + } + + }, + + /** + * Transforms the asset URL. + * + * The default implementation prepends the baseURL if the url doesn't begin with http or // + * + * @method Phaser.Loader#transformUrl + * @protected + * @param {string} url - The url to transform. + * @param {object} file - The file object being transformed. + * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead. + */ + transformUrl: function (url, file) { + + if (!url) + { + return false; + } + + if (url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) + { + return url; + } + else + { + return this.baseURL + file.path + url; + } + + }, + + /** + * Start fetching a resource. + * + * All code paths, async or otherwise, from this function must return to `asyncComplete`. + * + * @method Phaser.Loader#loadFile + * @private + * @param {object} file + */ + loadFile: function (file) { + + // Image or Data? + switch (file.type) + { + case 'packfile': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'image': + case 'spritesheet': + case 'textureatlas': + case 'bitmapfont': + this.loadImageTag(file); + break; + + case 'audio': + file.url = this.getAudioURL(file.url); + + if (file.url) + { + // WebAudio or Audio Tag? + if (this.game.sound.usingWebAudio) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + else if (this.game.sound.usingAudioTag) + { + this.loadAudioTag(file); + } + } + else + { + this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support'); + } + break; + + case 'video': + file.url = this.getVideoURL(file.url); + + if (file.url) + { + if (file.asBlob) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'blob', this.fileComplete); + } + else + { + this.loadVideoTag(file); + } + } + else + { + this.fileError(file, null, 'No supported video URL specified or device does not have video playback support'); + } + break; + + case 'json': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + break; + + case 'xml': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete); + break; + + case 'tilemap': + + if (file.format === Phaser.Tilemap.TILED_JSON) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Tilemap.CSV) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete); + } + else + { + this.asyncComplete(file, "invalid Tilemap format: " + file.format); + } + break; + + case 'text': + case 'script': + case 'shader': + case 'physics': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'texture': + + if (file.key.split('_').pop() === 'truecolor') + { + this.loadImageTag(file); + } + else + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + break; + + case 'binary': + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + break; + } + + }, + + /** + * Continue async loading through an Image tag. + * @private + */ + loadImageTag: function (file) { + var _this = this; + + file.data = new Image(); + file.data.name = file.key; + + if (this.crossOrigin) + { + file.data.crossOrigin = this.crossOrigin; + } + + file.data.onload = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileComplete(file); + } + }; + + file.data.onerror = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileError(file); + } + }; + + file.data.src = this.transformUrl(file.url, file); + + // Image is immediately-available/cached + // Special Firefox magic, exclude from cached reload + // More info here: https://github.com/photonstorm/phaser/issues/2534 + if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height) + { + file.data.onload = null; + file.data.onerror = null; + this.fileComplete(file); + } + + }, + + /** + * Continue async loading through a Video tag. + * @private + */ + loadVideoTag: function (file) { + + var _this = this; + + file.data = document.createElement("video"); + file.data.name = file.key; + file.data.controls = false; + file.data.autoplay = false; + + var videoLoadEvent = function () { + + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = true; + Phaser.GAMES[_this.game.id].load.fileComplete(file); + + }; + + file.data.onerror = function () { + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = false; + _this.fileError(file); + }; + + file.data.addEventListener(file.loadEvent, videoLoadEvent, false); + + file.data.src = this.transformUrl(file.url, file); + file.data.load(); + + }, + + /** + * Continue async loading through an Audio tag. + * @private + */ + loadAudioTag: function (file) { + + var _this = this; + + if (this.game.sound.touchLocked) + { + // If audio is locked we can't do this yet, so need to queue this load request. Bum. + file.data = new Audio(); + file.data.name = file.key; + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + + this.fileComplete(file); + } + else + { + file.data = new Audio(); + file.data.name = file.key; + + var playThroughEvent = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileComplete(file); + }; + + file.data.onerror = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileError(file); + }; + + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + file.data.addEventListener('canplaythrough', playThroughEvent, false); + file.data.load(); + } + + }, + + /** + * Starts the xhr loader. + * + * This is designed specifically to use with asset file processing. + * + * @method Phaser.Loader#xhrLoad + * @private + * @param {object} file - The file/pack to load. + * @param {string} url - The URL of the file. + * @param {string} type - The xhr responseType. + * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments. + * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments. + */ + xhrLoad: function (file, url, type, onload, onerror) { + + var xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = type; + + if (this.headers['requestedWith'] !== false) + { + xhr.setRequestHeader('X-Requested-With', this.headers['requestedWith']); + } + + if (this.headers[file.type]) + { + xhr.setRequestHeader('Accept', this.headers[file.type]); + } + + onerror = onerror || this.fileError; + + var _this = this; + + xhr.onload = function () { + + try { + if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. + return onerror.call(_this, file, xhr); + } + else { + return onload.call(_this, file, xhr); + } + } catch (e) { + + // If this was the last file in the queue and an error is thrown in the create method + // then it's caught here, so be sure we don't carry on processing it + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + } + }; + + xhr.onerror = function () { + + try { + + return onerror.call(_this, file, xhr); + + } catch (e) { + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + + } + }; + + file.requestObject = xhr; + file.requestUrl = url; + + xhr.send(); + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getVideoURL + * @private + * @param {object[]|string[]} urls - See {@link #video} for format. + * @return {string} The URL to try and fetch; or null. + */ + getVideoURL: function (urls) { + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var videoType; + + if (url.uri) // {uri: .., type: ..} pair + { + videoType = url.type; + url = url.uri; + + if (this.game.device.canPlayVideo(videoType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + videoType = extension.toLowerCase(); + + if (this.game.device.canPlayVideo(videoType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getAudioURL + * @private + * @param {object[]|string[]} urls - See {@link #audio} for format. + * @return {string} The URL to try and fetch; or null. + */ + getAudioURL: function (urls) { + + if (this.game.sound.noAudio) + { + return null; + } + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var audioType; + + if (url.uri) // {uri: .., type: ..} pair + { + audioType = url.type; + url = url.uri; + + if (this.game.device.canPlayAudio(audioType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + audioType = extension.toLowerCase(); + + if (this.game.device.canPlayAudio(audioType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Error occurred when loading a file. + * + * @method Phaser.Loader#fileError + * @private + * @param {object} file + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + * @param {string} reason + */ + fileError: function (file, xhr, reason) { + + var url = file.requestUrl || this.transformUrl(file.url, file); + var message = 'error loading asset from URL ' + url; + + if (!reason && xhr) + { + reason = xhr.status; + } + + if (reason) + { + message = message + ' (' + reason + ')'; + } + + this.asyncComplete(file, message); + + }, + + /** + * Called when a file has been downloaded and needs to be processed further. + * + * @method Phaser.Loader#fileComplete + * @private + * @param {object} file - File loaded + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + */ + fileComplete: function (file, xhr) { + + var loadNext = true; + + switch (file.type) + { + case 'packfile': + + // Pack data must never be false-ish after it is fetched without error + var data = JSON.parse(xhr.responseText); + file.data = data || {}; + break; + + case 'texture': + + var extension = /\.([^.]+)$/.exec(file.url.split('?', 1)[0])[1].toLowerCase(); + if (file.data !== null) + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, file.data); + } + else + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, xhr.response); + } + break; + + case 'image': + + this.cache.addImage(file.key, file.url, file.data); + break; + + case 'spritesheet': + + this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case 'textureatlas': + + if (file.atlasURL == null) + { + this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); + } + else + { + // Load the JSON or XML before carrying on with the next file + loadNext = false; + + if (file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_HASH || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete); + } + else + { + throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); + } + } + break; + + case 'bitmapfont': + + if (!file.atlasURL) + { + this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing); + } + else + { + // Load the XML before carrying on with the next file + loadNext = false; + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) { + var json; + + try + { + // Try to parse as JSON, if it fails, then it's hopefully XML + json = JSON.parse(xhr.responseText); + } + catch (e) {} + + if (!!json) + { + file.atlasType = 'json'; + this.jsonLoadComplete(file, xhr); + } + else + { + file.atlasType = 'xml'; + this.xmlLoadComplete(file, xhr); + } + }); + } + break; + + case 'video': + + if (file.asBlob) + { + try + { + file.data = xhr.response; + } + catch (e) + { + throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key); + } + } + + this.cache.addVideo(file.key, file.url, file.data, file.asBlob); + break; + + case 'audio': + + if (this.game.sound.usingWebAudio) + { + file.data = xhr.response; + + this.cache.addSound(file.key, file.url, file.data, true, false); + + if (file.autoDecode) + { + this.game.sound.decode(file.key); + } + } + else + { + this.cache.addSound(file.key, file.url, file.data, false, true); + } + break; + + case 'text': + file.data = xhr.responseText; + this.cache.addText(file.key, file.url, file.data); + break; + + case 'shader': + file.data = xhr.responseText; + this.cache.addShader(file.key, file.url, file.data); + break; + + case 'physics': + var data = JSON.parse(xhr.responseText); + this.cache.addPhysicsData(file.key, file.url, data, file.format); + break; + + case 'script': + file.data = document.createElement('script'); + file.data.language = 'javascript'; + file.data.type = 'text/javascript'; + file.data.defer = false; + file.data.text = xhr.responseText; + document.head.appendChild(file.data); + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText); + } + break; + + case 'binary': + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.response); + } + else + { + file.data = xhr.response; + } + + this.cache.addBinary(file.key, file.data); + + break; + } + + if (loadNext) + { + this.asyncComplete(file); + } + + }, + + /** + * Successfully loaded a JSON file - only used for certain types. + * + * @method Phaser.Loader#jsonLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + jsonLoadComplete: function (file, xhr) { + + var data = JSON.parse(xhr.responseText); + + if (file.type === 'tilemap') + { + this.cache.addTilemap(file.key, file.url, data, file.format); + } + else if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'json') + { + this.cache.addJSON(file.key, file.url, data); + } + else + { + this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); + } + + this.asyncComplete(file); + }, + + /** + * Successfully loaded a CSV file - only used for certain types. + * + * @method Phaser.Loader#csvLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + csvLoadComplete: function (file, xhr) { + + var data = xhr.responseText; + + this.cache.addTilemap(file.key, file.url, data, file.format); + + this.asyncComplete(file); + + }, + + /** + * Successfully loaded an XML file - only used for certain types. + * + * @method Phaser.Loader#xmlLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + xmlLoadComplete: function (file, xhr) { + + // Always try parsing the content as XML, regardless of actually response type + var data = xhr.responseText; + var xml = this.parseXml(data); + + if (!xml) + { + var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest + console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')'); + this.asyncComplete(file, "invalid XML"); + return; + } + + if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'textureatlas') + { + this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); + } + else if (file.type === 'xml') + { + this.cache.addXML(file.key, file.url, xml); + } + + this.asyncComplete(file); + + }, + + /** + * Parses string data as XML. + * + * @method Phaser.Loader#parseXml + * @private + * @param {string} data - The XML text to parse + * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document. + */ + parseXml: function (data) { + + var xml; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + // Why is this 'false'? + xml.async = 'false'; + xml.loadXML(data); + } + } + catch (e) + { + xml = null; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + return null; + } + else + { + return xml; + } + + }, + + /** + * Update the loading sprite progress. + * + * @method Phaser.Loader#updateProgress + * @private + */ + updateProgress: function () { + + if (this.preloadSprite) + { + if (this.preloadSprite.direction === 0) + { + this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress); + } + else + { + this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress); + } + + if (this.preloadSprite.sprite) + { + this.preloadSprite.sprite.updateCrop(); + } + else + { + // We seem to have lost our sprite - maybe it was destroyed? + this.preloadSprite = null; + } + } + + }, + + /** + * Returns the number of files that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedFiles + * @protected + * @return {number} The number of files that have already been loaded (even if they errored) + */ + totalLoadedFiles: function () { + + return this._loadedFileCount; + + }, + + /** + * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedFiles + * @protected + * @return {number} The number of files that still remain in the load queue. + */ + totalQueuedFiles: function () { + + return this._totalFileCount - this._loadedFileCount; + + }, + + /** + * Returns the number of asset packs that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedPacks + * @protected + * @return {number} The number of asset packs that have already been loaded (even if they errored) + */ + totalLoadedPacks: function () { + + return this._totalPackCount; + + }, + + /** + * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedPacks + * @protected + * @return {number} The number of asset packs that still remain in the load queue. + */ + totalQueuedPacks: function () { + + return this._totalPackCount - this._loadedPackCount; + + } + +}; + +/** +* The non-rounded load progress value (from 0.0 to 100.0). +* +* A general indicator of the progress. +* It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. +* +* @name Phaser.Loader#progressFloat +* @property {number} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progressFloat", { + + get: function () { + var progress = (this._loadedFileCount / this._totalFileCount) * 100; + return Phaser.Math.clamp(progress || 0, 0, 100); + } + +}); + +/** +* The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}. +* +* @name Phaser.Loader#progress +* @property {integer} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progress", { + + get: function () { + return Math.round(this.progressFloat); + } + +}); + +Phaser.Loader.prototype.constructor = Phaser.Loader; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. +* +* @class Phaser.LoaderParser +*/ +Phaser.LoaderParser = { + + /** + * Alias for xmlBitmapFont, for backwards compatibility. + * + * @method Phaser.LoaderParser.bitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + bitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing, frame, resolution); + + }, + + /** + * Parse a Bitmap Font from an XML file. + * + * @method Phaser.LoaderParser.xmlBitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing; + data.chars = {}; + + var letters = xml.getElementsByTagName('char'); + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + for (var i = 0; i < letters.length; i++) + { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + data.chars[charCode] = { + x: x + parseInt(letters[i].getAttribute('x'), 10), + y: y + parseInt(letters[i].getAttribute('y'), 10), + width: parseInt(letters[i].getAttribute('width'), 10), + height: parseInt(letters[i].getAttribute('height'), 10), + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10) / resolution, + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10) / resolution, + xAdvance: (parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing) / resolution, + kerning: {} + }; + } + + var kernings = xml.getElementsByTagName('kerning'); + + for (i = 0; i < kernings.length; i++) + { + var first = parseInt(kernings[i].getAttribute('first'), 10); + var second = parseInt(kernings[i].getAttribute('second'), 10); + var amount = parseInt(kernings[i].getAttribute('amount'), 10) / resolution; + + data.chars[second].kerning[first] = amount; + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Parse a Bitmap Font from a JSON file. + * + * @method Phaser.LoaderParser.jsonBitmapFont + * @param {object} json - JSON data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = { + font: json.font.info._face, + size: parseInt(json.font.info._size, 10), + lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing, + chars: {} + }; + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + json.font.chars["char"].forEach( + + function parseChar(letter) { + + var charCode = parseInt(letter._id, 10); + + data.chars[charCode] = { + x: x + parseInt(letter._x, 10), + y: y + parseInt(letter._y, 10), + width: parseInt(letter._width, 10), + height: parseInt(letter._height, 10), + xOffset: parseInt(letter._xoffset, 10) / resolution, + yOffset: parseInt(letter._yoffset, 10) / resolution, + xAdvance: (parseInt(letter._xadvance, 10) + xSpacing) / resolution, + kerning: {} + }; + } + + ); + + if (json.font.kernings && json.font.kernings.kerning) + { + json.font.kernings.kerning.forEach( + + function parseKerning(kerning) { + + data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10) / resolution; + + } + + ); + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Finalize Bitmap Font parsing. + * + * @method Phaser.LoaderParser.finalizeBitmapFont + * @private + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {object} bitmapFontData - Pre-parsed bitmap font data. + * @return {object} The parsed Bitmap Font data. + */ + finalizeBitmapFont: function (baseTexture, bitmapFontData) { + + Object.keys(bitmapFontData.chars).forEach( + + function addTexture(charCode) { + + var letter = bitmapFontData.chars[charCode]; + + letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height)); + + } + + ); + + return bitmapFontData; + + }, + + /** + * Extract PVR header from loaded binary + * + * @method Phaser.LoaderParser.pvr + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PVR file including texture data. + */ + pvr: function (arrayBuffer) { + + // Reference: http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf + // PVR 3 header structure + // --------------------------------------- + // address: 0, size: 4 bytes version + // address: 4, size: 4 bytes flags + // address: 8, size: 8 bytes pixel format + // address: 16, size: 4 bytes color space + // address: 20, size: 4 bytes channel type + // address: 24, size: 4 bytes height + // address: 28, size: 4 bytes width + // address: 32, size: 4 bytes depth + // address: 36, size: 4 bytes number of surfaces + // address: 40, size: 4 bytes number of faces + // address: 44, size: 4 bytes number of mipmaps + // address: 48, size: 4 bytes meta data size + // --------------------------------------- + var uintArray = new Uint32Array(arrayBuffer.slice(0, 52)), + byteArray = new Uint8Array(arrayBuffer), + pvrHeader = null, + pixelFormat = (uintArray[3] << 32 | uintArray[2]), + compressionAlgorithm, + glExtensionFormat = 0; + + if (uintArray[0] === 0x03525650 && + [ // Validate WebGL Pixel Format + 0, 1, 2, 3, + 6, 7, 9, 11 + ].indexOf(pixelFormat) >= 0 + ) { + if (pixelFormat >= 0 && pixelFormat <= 3) { + compressionAlgorithm = 'PVRTC'; + } else if (pixelFormat >= 7 && pixelFormat <= 11) { + compressionAlgorithm = 'S3TC'; + } else if (pixelFormat === 6) { + compressionAlgorithm = 'ETC1'; + } + + switch (pixelFormat) { + case 0: + glExtensionFormat = 0x8C01; + break; + case 1: + glExtensionFormat = 0x8C03; + break; + case 2: + glExtensionFormat = 0x8C00; + break; + case 3: + glExtensionFormat = 0x8C02; + break; + case 6: + glExtensionFormat = 0x8D64; + break; + case 7: + glExtensionFormat = 0x83F1; + break; + case 9: + glExtensionFormat = 0x83F2; + break; + case 11: + glExtensionFormat = 0x83F3; + break; + default: + glExtensionFormat = -1; + } + + pvrHeader = { + complete: true, + fileFormat: 'PVR', + compressionAlgorithm: compressionAlgorithm, + flags: uintArray[1], + pixelFormat: pixelFormat, + colorSpace: uintArray[4], + channelType: uintArray[5], + height: uintArray[6], + width: uintArray[7], + depth: uintArray[8], + numberOfSurfaces: uintArray[9], + numberOfFaces: uintArray[10], + numberOfMipmaps: uintArray[11], + metaDataSize: uintArray[12], + textureData: byteArray.subarray(52 + uintArray[12], byteArray.byteLength), + glExtensionFormat: glExtensionFormat + }; + } + + return pvrHeader; + + }, + + /** + * Extract DDS header from loaded binary + * + * @method Phaser.LoaderParser.dds + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed DDS file including texture data. + */ + dds: function (arrayBuffer) { + + // Reference at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx + // DDS header structure + // --------------------------------------- + // address: 0, size: 4 bytes Identifier 'DDS ' + // address: 4, size: 4 bytes size + // address: 8, size: 4 bytes flags + // address: 12, size: 4 bytes height + // address: 16, size: 4 bytes width + // address: 20, size: 4 bytes pitch or linear size + // address: 24, size: 4 bytes depth + // address: 28, size: 4 bytes mipmap count + // address: 32, size: 44 bytes reserved space 1 + // address: 76, size: 4 pixel format size + // address: 80, size: 4 pixel format flag + // address: 84, size: 4 pixel format four CC + // address: 88, size: 4 pixel format bit count + // address: 92, size: 4 pixel format R bit mask + // address: 96, size: 4 pixel format G bit mask + // address: 100, size: 4 pixel format B bit mask + // address: 104, size: 4 pixel format A bit mask + // address: 108, size: 4 caps 1 + // address: 112, size: 4 caps 2 + // address: 116, size: 4 caps 3 + // address: 120, size: 4 caps 4 + // address: 124, size: 4 reserved 2 + // -- DXT10 extension + // address: 130, size: 4 DXGI Format + // address: 134, size: 4 resource dimension + // address: 138, size: 4 misc flag + // address: 142, size: 4 array size + // address: 146, size: 4 misc flag 2 + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ddsHeader = null; + + if (byteArray[0] === 0x44 && + byteArray[1] === 0x44 && + byteArray[2] === 0x53 && + byteArray[3] === 0x20) { + ddsHeader = { + complete: true, + fileFormat: 'DDS', + compressionAlgorithm: 'S3TC', + size: uintArray[1], + flags: uintArray[2], + height: uintArray[3], + width: uintArray[4], + pitch: uintArray[5], + depth: uintArray[6], + mipmapCount: uintArray[7], + formatSize: uintArray[19], + formatFlag: uintArray[19], + formatFourCC: [ + String.fromCharCode(byteArray[84]), + String.fromCharCode(byteArray[85]), + String.fromCharCode(byteArray[86]), + String.fromCharCode(byteArray[87]) + ].join(''), + formatBitCount: uintArray[21], + formatRBitMask: uintArray[22], + formatGBitMask: uintArray[23], + formatBBitMask: uintArray[24], + formatABitMask: uintArray[25], + caps1: uintArray[26], + caps2: uintArray[27], + caps3: uintArray[28], + caps4: uintArray[29], + reserved2: uintArray[30], + DXGIFormat: null, + resourceDimension: null, + miscFlag: null, + arraySize: null, + textureData: byteArray.subarray(uintArray[1] + 4, byteArray.byteLength) + }; + if (ddsHeader.formatFourCC === 'DX10') { + ddsHeader.DXGIFormat = uintArray[31]; + ddsHeader.resourceDimension = uintArray[32]; + ddsHeader.miscFlag = uintArray[33]; + ddsHeader.arraySize = uintArray[34]; + ddsHeader.miscFlag = uintArray[35]; + } + } + + return ddsHeader; + + }, + + /** + * Extract KTX header from loaded binary + * + * @method Phaser.LoaderParser.ktx + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed KTX file including texture data. + */ + ktx: function (arrayBuffer) { + + // Reference: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + // KTX header structure + // --------------------------------------- + // address: 0, size 12 bytes: Identifier '«KTX 11»\r\n\x1A\n' + // address: 12, size 4 bytes: endianness + // address: 16, size 4 bytes: GL type + // address: 20, size 4 bytes: GL type size + // address: 24, size 4 bytes: GL format + // address: 28, size 4 bytes: GL internal format + // address: 32, size 4 bytes: GL base internal format + // address: 36, size 4 bytes: pixel width + // address: 40, size 4 bytes: pixel height + // address: 44, size 4 bytes: pixel depth + // address: 48, size 4 bytes: number of array elements + // address: 52, size 4 bytes: number of faces + // address: 56, size 4 bytes: number of mipmap levels + // address: 60, size 4 bytes: bytes of key value data + // address: 64, size 4 bytes: key and value bytes size + // address: X, size 1 byte : key and value + // address: X, size 1 byte : value padding + // address: X, size 4 byte : image size + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ktxHeader = null, + imageSizeOffset = 16 + (uintArray[15] / 4) | 0, + imageSize = uintArray[imageSizeOffset], + glInternalFormat = uintArray[7], + compressionAlgorithm = 0; + + if (byteArray[0] === 0xAB && byteArray[1] === 0x4B && + byteArray[2] === 0x54 && byteArray[3] === 0x58 && + byteArray[4] === 0x20 && byteArray[5] === 0x31 && + byteArray[6] === 0x31 && byteArray[7] === 0xBB && + byteArray[8] === 0x0D && byteArray[9] === 0x0A && + byteArray[10] === 0x1A && byteArray[11] === 0x0A && + //Check if internal GL format is supported by WebGL + [ + // ETC1 + 0x8D64, + // PVRTC + 0x8C00, 0x8C01, 0x8C02, 0x8C03, + // DXTC | S3TC + 0x83F0, 0x83F1, 0x83F2, 0x83F3 + ].indexOf(glInternalFormat) >= 0) { + switch (glInternalFormat) { + case 0x8D64: + compressionAlgorithm = 'ETC1'; + break; + case 0x8C00: + case 0x8C01: + case 0x8C02: + case 0x8C03: + compressionAlgorithm = 'PVRTC'; + break; + case 0x83F0: + case 0x83F1: + case 0x83F2: + case 0x83F3: + compressionAlgorithm = 'S3TC'; + break; + } + + ktxHeader = { + complete: true, + fileFormat: 'KTX', + compressionAlgorithm: compressionAlgorithm, + endianness: uintArray[3], + glType: uintArray[4], + glTypeSize: uintArray[5], + glFormat: uintArray[6], + glInternalFormat: uintArray[7], + glBaseInternalFormat: uintArray[8], + width: uintArray[9], + height: uintArray[10], + pixelDepth: uintArray[11], + numberOfArrayElements: uintArray[12], + numberOfFaces: uintArray[13], + numberOfMipmapLevels: uintArray[14], + bytesOfKeyValueData: uintArray[15], + keyAndValueByteSize: uintArray[16], + imageSize: imageSize, + textureData: byteArray.subarray((imageSizeOffset + 1) * 4, imageSize + 100) + }; + } + + return ktxHeader; + + }, + + /** + * Extract PKM header from loaded binary + * + * @method Phaser.LoaderParser.pkm + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PKM file including texture data. + */ + pkm: function (arrayBuffer) { + + // PKM header structure + // --------------------------------------- + // address: 0, size 4 bytes: for 'PKM ' + // address: 4, size 2 bytes: for version + // address: 6, size 2 bytes: for type + // address: 8, size 2 bytes: for extended width + // address: 10, size 2 bytes: for extended height + // address: 12, size 2 bytes: for original width + // address: 14, size 2 bytes: for original height + // address: 16, texture data + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + pkmHeader = null; + + if (byteArray[0] === 0x50 && + byteArray[1] === 0x4B && + byteArray[2] === 0x4D && + byteArray[3] === 0x20) { + + pkmHeader = { + complete: true, + fileFormat: 'PKM', + compressionAlgorithm: 'ETC1', + format: ((byteArray[6] << 8 | byteArray[7])) & 0xFFFF, + width: ((byteArray[8] << 8 | byteArray[9])) & 0xFFFF, + height: ((byteArray[10] << 8 | byteArray[11])) & 0xFFFF, + originalWidth: ((byteArray[12] << 8 | byteArray[13])) & 0xFFFF, + originalHeight: ((byteArray[14] << 8 | byteArray[15])) & 0xFFFF, + textureData: byteArray.subarray(16, byteArray.length) + }; + } + + return pkmHeader; + + } + +}; + +/** + * @author Jeremy Dowell + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * Audio Sprites are a combination of audio files and a JSON configuration. + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * @class Phaser.AudioSprite + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + * @param {string} key - Asset key for the sound. + */ +Phaser.AudioSprite = function (game, key) { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * Asset key for the Audio Sprite. + * @property {string} key + */ + this.key = key; + + /** + * JSON audio atlas object. + * @property {object} config + */ + this.config = this.game.cache.getJSON(key + '-audioatlas'); + + /** + * If a sound is set to auto play, this holds the marker key of it. + * @property {string} autoplayKey + */ + this.autoplayKey = null; + + /** + * Is a sound set to autoplay or not? + * @property {boolean} autoplay + * @default + */ + this.autoplay = false; + + /** + * An object containing the Phaser.Sound objects for the Audio Sprite. + * @property {object} sounds + */ + this.sounds = {}; + + for (var k in this.config.spritemap) + { + var marker = this.config.spritemap[k]; + var sound = this.game.add.sound(this.key); + + sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop); + + this.sounds[k] = sound; + } + + if (this.config.autoplay) + { + this.autoplayKey = this.config.autoplay; + this.play(this.autoplayKey); + this.autoplay = this.sounds[this.autoplayKey]; + } + +}; + +Phaser.AudioSprite.prototype = { + + /** + * Play a sound with the given name. + * + * @method Phaser.AudioSprite#play + * @param {string} [marker] - The name of sound to play + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, volume) { + + if (volume === undefined) { volume = 1; } + + return this.sounds[marker].play(marker, null, volume); + + }, + + /** + * Stop a sound with the given name. + * + * @method Phaser.AudioSprite#stop + * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite. + */ + stop: function (marker) { + + if (!marker) + { + for (var key in this.sounds) + { + this.sounds[key].stop(); + } + } + else + { + this.sounds[marker].stop(); + } + + }, + + /** + * Get a sound with the given name. + * + * @method Phaser.AudioSprite#get + * @param {string} marker - The name of sound to get. + * @return {Phaser.Sound} The sound instance. + */ + get: function(marker) { + + return this.sounds[marker]; + + } + +}; + +Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound class constructor. +* +* @class Phaser.Sound +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {string} key - Asset key for the sound. +* @param {number} [volume=1] - Default value for the volume, between 0 and 1. +* @param {boolean} [loop=false] - Whether or not the sound will loop. +*/ +Phaser.Sound = function (game, key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = game.sound.connectToMaster; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * @property {string} name - Name of the sound. + */ + this.name = key; + + /** + * @property {string} key - Asset key for the sound. + */ + this.key = key; + + /** + * @property {boolean} loop - Whether or not the sound or current sound marker will loop. + */ + this.loop = loop; + + /** + * @property {object} markers - The sound markers. + */ + this.markers = {}; + + /** + * @property {AudioContext} context - Reference to the AudioContext instance. + */ + this.context = null; + + /** + * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically. + */ + this.autoplay = false; + + /** + * @property {number} totalDuration - The total duration of the sound in seconds. + */ + this.totalDuration = 0; + + /** + * @property {number} startTime - The time the sound starts at in ms (typically 0 unless starting from a marker). + * @default + */ + this.startTime = 0; + + /** + * @property {number} currentTime - The current time of sound playback in ms. + */ + this.currentTime = 0; + + /** + * @property {number} duration - The duration of the current sound marker in seconds. + */ + this.duration = 0; + + /** + * @property {number} durationMS - The duration of the current sound marker in ms. + */ + this.durationMS = 0; + + /** + * @property {number} position - The position of the current sound marker in ms. + */ + this.position = 0; + + /** + * @property {number} stopTime - The time the sound stopped in ms. + */ + this.stopTime = 0; + + /** + * @property {boolean} paused - true if the sound is paused, otherwise false. + * @default + */ + this.paused = false; + + /** + * @property {number} pausedPosition - The position the sound had reached when it was paused in ms. + */ + this.pausedPosition = 0; + + /** + * @property {number} pausedTime - The game time (ms) at which the sound was paused. + */ + this.pausedTime = 0; + + /** + * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false. + * @default + */ + this.isPlaying = false; + + /** + * @property {string} currentMarker - The string ID of the currently playing marker, if any. + * @default + */ + this.currentMarker = ''; + + /** + * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. + */ + this.fadeTween = null; + + /** + * @property {boolean} pendingPlayback - true if the sound file is pending playback + * @readonly + */ + this.pendingPlayback = false; + + /** + * @property {boolean} override - if true when you play this sound it will always start from the beginning. + * @default + */ + this.override = false; + + /** + * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. + * @default + */ + this.allowMultiple = false; + + /** + * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio. + * @readonly + */ + this.usingWebAudio = this.game.sound.usingWebAudio; + + /** + * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag. + */ + this.usingAudioTag = this.game.sound.usingAudioTag; + + /** + * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. + */ + this.externalNode = null; + + /** + * @property {object} masterGainNode - The master gain node in a Web Audio system. + */ + this.masterGainNode = null; + + /** + * @property {object} gainNode - The gain node in a Web Audio system. + */ + this.gainNode = null; + + /** + * @property {object} _sound - Internal var. + * @private + */ + this._sound = null; + + /** + * @property {object} _globalVolume - Internal var for keeping track of global volume when using AudioTag + * @private + */ + this._globalVolume = 1; + + /** + * @property {boolean} _markedToDelete - When audio stops, disconnect Web Audio nodes. + * @private + */ + this._markedToDelete = false; + + /** + * @property {boolean} _removeFromSoundManager - When audio stops, remove it from the Sound Manager and destroy it. + * @private + */ + this._removeFromSoundManager = false; + + + + if (this.usingWebAudio) + { + this.context = this.game.sound.context; + this.masterGainNode = this.game.sound.masterGain; + + if (this.context.createGain === undefined) + { + this.gainNode = this.context.createGainNode(); + } + else + { + this.gainNode = this.context.createGain(); + } + + this.gainNode.gain.value = volume; + + if (connect) + { + this.gainNode.connect(this.masterGainNode); + } + } + else if (this.usingAudioTag) + { + if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key)) + { + this._sound = this.game.cache.getSoundData(key); + this.totalDuration = 0; + + if (this._sound.duration) + { + this.totalDuration = this._sound.duration; + } + } + else + { + this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this); + } + } + + /** + * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files). It passes one argument, this sound. + */ + this.onDecoded = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played or a looping marker is restarted. It passes one argument, this sound. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. It passes one argument, this sound. + */ + this.onPause = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. It passes one argument, this sound. + */ + this.onResume = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. It passes one argument, this sound. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback or when a non-looping marker completes. It passes two arguments: this sound and any {@link #currentMarker marker} that was playing. + */ + this.onStop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted. It passes one argument, this sound. + */ + this.onMute = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. It passes two arguments: the {@link #currentMarker} and this sound. + */ + this.onMarkerComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out. It passes two arguments: this sound and its current {@link #volume}. + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + */ + this._volume = volume; + + /** + * @property {any} _buffer - Decoded data buffer / Audio tag. + * @private + */ + this._buffer = null; + + /** + * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. + * @private + */ + this._muted = false; + + /** + * @property {number} _tempMarker - Internal marker var. + * @private + */ + this._tempMarker = 0; + + /** + * @property {number} _tempPosition - Internal marker var. + * @private + */ + this._tempPosition = 0; + + /** + * @property {number} _tempVolume - Internal marker var. + * @private + */ + this._tempVolume = 0; + + /** + * @property {number} _tempPause - Internal marker var. + * @private + */ + this._tempPause = 0; + + /** + * @property {number} _muteVolume - Internal cache var. + * @private + */ + this._muteVolume = 0; + + /** + * @property {boolean} _tempLoop - Internal cache var. + * @private + */ + this._tempLoop = 0; + + /** + * @property {boolean} _paused - Was this sound paused via code or a game event? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched? + * @private + */ + this._onDecodedEventDispatched = false; + +}; + +Phaser.Sound.prototype = { + + /** + * Called automatically when this sound is unlocked. + * @method Phaser.Sound#soundHasUnlocked + * @param {string} key - The Phaser.Cache key of the sound file to check for decoding. + * @protected + */ + soundHasUnlocked: function (key) { + + if (key === this.key) + { + this._sound = this.game.cache.getSoundData(this.key); + this.totalDuration = this._sound.duration; + } + + }, + + /** + * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound#addMarker + * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. + * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). + * @param {boolean} [loop=false] - Sets if the sound will loop or not. + */ + addMarker: function (name, start, duration, volume, loop) { + + if (duration === undefined || duration === null) { duration = 1; } + if (volume === undefined || volume === null) { volume = 1; } + if (loop === undefined) { loop = false; } + + this.markers[name] = { + name: name, + start: start, + stop: start + duration, + volume: volume, + duration: duration, + durationMS: duration * 1000, + loop: loop + }; + + }, + + /** + * Removes a marker from the sound. + * @method Phaser.Sound#removeMarker + * @param {string} name - The key of the marker to remove. + */ + removeMarker: function (name) { + + delete this.markers[name]; + + }, + + /** + * Called automatically by the AudioContext when the sound stops playing. + * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. + * + * @method Phaser.Sound#onEndedHandler + * @protected + */ + onEndedHandler: function () { + + this._sound.onended = null; + this.isPlaying = false; + this.currentTime = this.durationMS; + this.stop(); + + if (this._markedToDelete) + { + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + if (this._removeFromSoundManager) + { + this.game.sound.remove(this); + } + else + { + 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(); + } + } + }, + + /** + * Called automatically by Phaser.SoundManager. + * @method Phaser.Sound#update + * @protected + */ + update: function () { + + if (!this.game.cache.checkSoundKey(this.key)) + { + this.destroy(); + return; + } + + if (this.isDecoded && !this._onDecodedEventDispatched) + { + this.onDecoded.dispatch(this); + this._onDecodedEventDispatched = true; + } + + if (this.pendingPlayback && this.game.cache.isSoundReady(this.key)) + { + this.pendingPlayback = false; + this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop); + } + + if (this.isPlaying) + { + this.currentTime = this.game.time.time - this.startTime; + + if (this.currentTime >= this.durationMS) + { + if (this.usingWebAudio) + { + if (this.loop) + { + // won't work with markers, needs to reset the position + this.onLoop.dispatch(this); + + // Gets reset by the play function + this.isPlaying = false; + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + this.isPlaying = true; // play not called again in this case + } + else + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + this.play(this.currentMarker, 0, this.volume, true, true); + } + } + else + { + // Stop if we're using an audio marker, otherwise we let onended handle it + if (this.currentMarker !== '') + { + this.stop(); + } + } + } + else + { + if (this.loop) + { + this.onLoop.dispatch(this); + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + } + + // Gets reset by the play function + this.isPlaying = false; + + this.play(this.currentMarker, 0, this.volume, true, true); + } + else + { + this.stop(); + } + } + } + } + }, + + /** + * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters. + * + * @method Phaser.Sound#loopFull + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + loopFull: function (volume) { + + return this.play(null, 0, volume, true); + + }, + + /** + * Play this sound, or a marked section of it. + * + * @method Phaser.Sound#play + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. + * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, position, volume, loop, forceRestart) { + + if (marker === undefined || marker === false || marker === null) { marker = ''; } + if (forceRestart === undefined) { forceRestart = true; } + + if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override) + { + // Use Restart instead + return this; + } + + if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart)) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) { + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + + this.isPlaying = false; + } + + if (marker === '' && Object.keys(this.markers).length > 0) + { + // If they didn't specify a marker but this is an audio sprite, + // we should never play the entire thing + return this; + } + + if (marker !== '') + { + if (this.markers[marker]) + { + this.currentMarker = marker; + + // Playing a marker? Then we default to the marker values + 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 (volume === undefined) { volume = this._volume; } + if (loop === undefined) { loop = this.loop; } + + this.position = Math.max(0, 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) + { + // Does the sound need decoding? + if (this.game.cache.isSoundDecoded(this.key)) + { + this._sound = this.context.createBufferSource(); + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + this._buffer = this.game.cache.getSoundData(this.key); + this._sound.buffer = this._buffer; + + if (this.loop && marker === '') + { + this._sound.loop = true; + } + + if (!this.loop && marker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + this.totalDuration = this._sound.buffer.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = Math.ceil(this.totalDuration * 1000); + } + + // Useful to cache this somewhere perhaps? + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, this.position, this.duration); + } + else + { + if (this.loop && marker === '') + { + this._sound.start(0, 0); + } + else + { + this._sound.start(0, this.position, this.duration); + } + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + 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 doesn't become available until you call play(), wonderful ... + this.totalDuration = this._sound.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = this.totalDuration * 1000; + } + + this._sound.currentTime = this.position; + this._sound.muted = this._muted; + + if (this._muted || this.game.sound.mute) + { + this._sound.volume = 0; + } + else + { + this._sound.volume = this._volume; + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + this.currentTime = 0; + this.stopTime = this.startTime + this.durationMS; + + this.onPlay.dispatch(this); + } + else + { + this.pendingPlayback = true; + } + } + } + + return this; + + }, + + /** + * Restart the sound, or a marked section of it. + * + * @method Phaser.Sound#restart + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. + * @param {boolean} [loop=false] - Loop when it finished playing? + */ + restart: function (marker, position, volume, loop) { + + marker = marker || ''; + position = position || 0; + volume = volume || 1; + if (loop === undefined) { loop = false; } + + this.play(marker, position, volume, loop, true); + + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound#pause + */ + pause: function () { + + if (this.isPlaying && this._sound) + { + this.paused = true; + this.pausedPosition = this.currentTime; + this.pausedTime = this.game.time.time; + this._tempPause = this._sound.currentTime; + this.onPause.dispatch(this); + this.stop(); + } + + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound#resume + */ + resume: function () { + + if (this.paused && this._sound) + { + if (this.usingWebAudio) + { + var p = Math.max(0, this.position + (this.pausedPosition / 1000)); + + this._sound = this.context.createBufferSource(); + this._sound.buffer = this._buffer; + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + if (this.loop) + { + this._sound.loop = true; + } + + if (!this.loop && this.currentMarker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + var duration = this.duration - (this.pausedPosition / 1000); + + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, p, duration); + //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it + } + else + { + if (this.loop && this.game.device.chrome) + { + // Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099 + if (this.game.device.chromeVersion === 42) + { + this._sound.start(0); + } + else + { + this._sound.start(0, p); + } + } + else + { + this._sound.start(0, p, duration); + } + } + } + else + { + this._sound.currentTime = this._tempPause; + this._sound.play(); + } + + this.isPlaying = true; + this.paused = false; + this.startTime += (this.game.time.time - this.pausedTime); + this.onResume.dispatch(this); + } + + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound#stop + */ + stop: function () { + + if (this.isPlaying && this._sound) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) + { + // Thanks Android 4.4 + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + } + + this.pendingPlayback = false; + this.isPlaying = false; + + if (!this.paused) + { + var prevMarker = this.currentMarker; + + if (this.currentMarker !== '') + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + } + + this.currentMarker = ''; + + if (this.fadeTween !== null) + { + this.fadeTween.stop(); + } + + this.onStop.dispatch(this, prevMarker); + } + + }, + + /** + * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. + * Then increases the volume from 0 to 1 over the duration specified. + * + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (1) as the second parameter. + * + * @method Phaser.Sound#fadeIn + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in. + * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. + * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. + */ + fadeIn: function (duration, loop, marker) { + + if (loop === undefined) { loop = false; } + if (marker === undefined) { marker = this.currentMarker; } + + if (this.paused) + { + return; + } + + this.play(marker, 0, 0, loop); + + this.fadeTo(duration, 1); + + }, + + /** + * Decreases the volume of this Sound from its current value to 0 over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (0) as the second parameter. + * + * @method Phaser.Sound#fadeOut + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out. + */ + fadeOut: function (duration) { + + this.fadeTo(duration, 0); + + }, + + /** + * Fades the volume of this Sound from its current value to the given volume over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (volume) as the second parameter. + * + * @method Phaser.Sound#fadeTo + * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out. + * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1. + */ + fadeTo: function (duration, volume) { + + if (!this.isPlaying || this.paused || volume === this.volume) + { + return; + } + + if (duration === undefined) { duration = 1000; } + + if (volume === undefined) + { + console.warn("Phaser.Sound.fadeTo: No Volume Specified."); + return; + } + + this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true); + + this.fadeTween.onComplete.add(this.fadeComplete, this); + + }, + + /** + * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo. + * + * @method Phaser.Sound#fadeComplete + * @private + */ + fadeComplete: function () { + + this.onFadeComplete.dispatch(this, this.volume); + + if (this.volume === 0) + { + this.stop(); + } + + }, + + /** + * Called automatically by SoundManager.volume. + * + * Sets the volume of AudioTag Sounds as a percentage of the Global Volume. + * + * You should not normally call this directly. + * + * @method Phaser.Sound#updateGlobalVolume + * @protected + * @param {float} globalVolume - The global SoundManager volume. + */ + updateGlobalVolume: function (globalVolume) { + + // this._volume is the % of the global volume this sound should be played at + + if (this.usingAudioTag && this._sound) + { + this._globalVolume = globalVolume; + this._sound.volume = this._globalVolume * this._volume; + } + + }, + + /** + * Destroys this sound and all associated events and removes it from the SoundManager. + * + * @method Phaser.Sound#destroy + * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager. + */ + destroy: function (remove) { + + if (remove === undefined) { remove = true; } + + this._markedToDelete = true; + this._removeFromSoundManager = remove; + this.stop(); + + if (remove) + { + this.game.sound.remove(this); + } + else + { + 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; + +/** +* @name Phaser.Sound#isDecoding +* @property {boolean} isDecoding - Returns true if the sound file is still decoding. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoding", { + + get: function () { + return this.game.cache.getSound(this.key).isDecoding; + } + +}); + +/** +* @name Phaser.Sound#isDecoded +* @property {boolean} isDecoded - Returns true if the sound file has decoded. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoded", { + + get: function () { + return this.game.cache.isSoundDecoded(this.key); + } + +}); + +/** +* @name Phaser.Sound#mute +* @property {boolean} mute - Gets or sets the muted state of this sound. +*/ +Object.defineProperty(Phaser.Sound.prototype, "mute", { + + get: function () { + + return (this._muted || this.game.sound.mute); + + }, + + set: function (value) { + + value = value || false; + + if (value === this._muted) + { + return; + } + + if (value) + { + this._muted = true; + this._muteVolume = this._tempVolume; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = 0; + } + else if (this.usingAudioTag && this._sound) + { + 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); + + } + +}); + +/** +* @name Phaser.Sound#volume +* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Sound.prototype, "volume", { + + get: function () { + return this._volume; + }, + + set: function (value) { + + // Causes an Index size error if you don't clamp the value + if (this.usingAudioTag) + { + value = this.game.math.clamp(value, 0, 1); + } + + if (this._muted) + { + this._muteVolume = value; + return; + } + + this._tempVolume = value; + this._volume = value; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = value; + } + else if (this.usingAudioTag && this._sound) + { + this._sound.volume = this._globalVolume * value; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. +* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. +* The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. +* There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ +* +* If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out +* of AudioContext nodes. If this is the case create a global var called {@link PhaserGlobal} on the window object before creating the game. The active +* AudioContext will then be saved to `window.PhaserGlobal.audioContext` when the Phaser game is destroyed, and re-used when it starts again. +* +* Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. +* When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. +* The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will +* be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. +* +* @class Phaser.SoundManager +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.SoundManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) + */ + this.onSoundDecode = new Phaser.Signal(); + + /** + * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. + * @property {Phaser.Signal} onVolumeChange + */ + this.onVolumeChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. + * @property {Phaser.Signal} onMute + */ + this.onMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. + * @property {Phaser.Signal} onUnMute + */ + this.onUnMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is touch-unlocked. + * If the device doesn't {@link Phaser.Device.needsTouchUnlock need touch-unlocking}, the signal won't be dispatched. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * @property {AudioContext} context - The AudioContext being used for playback. + * @default + */ + this.context = null; + + /** + * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio. + * @readonly + */ + this.usingWebAudio = false; + + /** + * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio. + * @readonly + */ + this.usingAudioTag = false; + + /** + * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. + * @default + */ + this.noAudio = false; + + /** + * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. + * @default + */ + this.connectToMaster = true; + + /** + * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. + * @default + */ + this.touchLocked = false; + + /** + * @property {number} channels - The number of audio channels to use in playback. + * @default + */ + this.channels = 32; + + /** + * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), + * or set to false to keep audio playing, regardless of the game pause state. You may need to + * do this should you wish to control audio muting via external DOM buttons or similar. + * @property {boolean} muteOnPause + * @default + */ + this.muteOnPause = true; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {AudioContext} _unlockSource - Internal unlock tracking var. + * @private + * @default + */ + this._unlockSource = null; + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + * @default + */ + this._volume = 1; + + + /** + * @property {array} _sounds - An array containing all the sounds + * @private + */ + this._sounds = []; + + /** + * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status. + * @private + */ + this._watchList = new Phaser.ArraySet(); + + /** + * @property {boolean} _watching - Is the SoundManager monitoring the watchList? + * @private + */ + this._watching = false; + + /** + * @property {function} _watchCallback - The callback to invoke once the watchlist is clear. + * @private + */ + this._watchCallback = null; + + /** + * @property {object} _watchContext - The context in which to call the watchlist callback. + * @private + */ + this._watchContext = null; + +}; + +Phaser.SoundManager.prototype = { + + /** + * Initialises the sound manager. + * @method Phaser.SoundManager#boot + * @protected + */ + boot: function () { + + var device = this.game.device; + var PhaserGlobal = window.PhaserGlobal; + + if (device.iOS && device.webAudio === false) + { + this.channels = 1; + } + + // PhaserGlobal overrides + if (PhaserGlobal) + { + // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class) + if (PhaserGlobal.disableAudio === true) + { + this.noAudio = true; + this.touchLocked = false; + return; + } + + // Check if the Web Audio API is disabled (for testing Audio Tag playback during development) + if (PhaserGlobal.disableWebAudio === true) + { + this.usingAudioTag = true; + this.touchLocked = false; + return; + } + } + + if (PhaserGlobal && PhaserGlobal.audioContext) + { + this.context = PhaserGlobal.audioContext; + } + else + { + if (!!window['AudioContext']) + { + try { + this.context = new window['AudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + else if (!!window['webkitAudioContext']) + { + try { + this.context = new window['webkitAudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + } + + if (this.context === null) + { + // No Web Audio support - how about legacy Audio? + if (window['Audio'] === undefined) + { + this.noAudio = true; + return; + } + else + { + this.usingAudioTag = true; + } + } + else + { + this.usingWebAudio = true; + + if (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); + } + + if (!this.noAudio) + { + // On mobile we need a native touch event before we can play anything, so capture it here + if (device.needsTouchUnlock()) + { + this.setTouchLock(); + } + } + + if (this.usingWebAudio && device.chrome && device.chromeVersion <= 65) + { + console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. '); + } + + }, + + /** + * Sets the Input Manager touch callback to be SoundManager.unlock. + * Required for iOS audio device unlocking. Mostly just used internally. + * + * @method Phaser.SoundManager#setTouchLock + */ + setTouchLock: function () { + + if (this.noAudio || (window.PhaserGlobal && window.PhaserGlobal.disableAudio === true)) + { + return; + } + + this.game.input.addTouchLockCallback(this.unlock, this, true); + + this.touchLocked = true; + + }, + + /** + * Turns off {@link #touchLocked} and dispatches {@link #onTouchUnlock}. + * + * @method Phaser.SoundManager#setTouchUnlock + * @private + */ + setTouchUnlock: function () { + + this.touchLocked = false; + this._unlockSource = null; + this.onTouchUnlock.dispatch(); + + }, + + /** + * Enables the audio, usually after the first touch. + * + * @method Phaser.SoundManager#unlock + * @return {boolean} True if the callback should be removed, otherwise false. + */ + unlock: function () { + + if (this.noAudio || !this.touchLocked || this._unlockSource !== null) + { + return true; + } + + // Global override (mostly for Audio Tag testing) + if (this.usingAudioTag) + { + this.setTouchUnlock(); + } + else if (this.usingWebAudio) + { + // Create empty buffer and play it + // The SoundManager.update loop captures the state of it and then resets touchLocked to false + + var buffer = this.context.createBuffer(1, 1, 22050); + this._unlockSource = this.context.createBufferSource(); + this._unlockSource.buffer = buffer; + this._unlockSource.connect(this.context.destination); + + if (this._unlockSource.start === undefined) + { + this._unlockSource.noteOn(0); + } + else + { + this._unlockSource.start(0); + } + + //This fixes locked audio in Chrome > 55 cross origin iframes + if (this._unlockSource.context.state === 'suspended') { + this._unlockSource.context.resume(); + } + } + + // We can remove the event because we've done what we needed (started the unlock sound playing) + return true; + + }, + + /** + * Stops all the sounds in the game. + * + * @method Phaser.SoundManager#stopAll + */ + stopAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].stop(); + } + } + + }, + + /** + * Pauses all the sounds in the game. + * + * @method Phaser.SoundManager#pauseAll + */ + pauseAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].pause(); + } + } + + }, + + /** + * Resumes every sound in the game. + * + * @method Phaser.SoundManager#resumeAll + */ + resumeAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].resume(); + } + } + + }, + + /** + * Decode a sound by its asset key. + * + * @method Phaser.SoundManager#decode + * @param {string} key - Assets key of the sound to be decoded. + * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. + */ + decode: function (key, sound) { + + sound = sound || null; + + var soundData = this.game.cache.getSoundData(key); + + if (soundData) + { + if (this.game.cache.isSoundDecoded(key) === false) + { + this.game.cache.updateSound(key, 'isDecoding', true); + + var _this = this; + + try { + this.context.decodeAudioData(soundData, function (buffer) { + + if (buffer) + { + _this.game.cache.decodedSound(key, buffer); + _this.onSoundDecode.dispatch(key, sound); + } + }); + } + catch (e) {} + } + } + + }, + + /** + * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback. + * Once all of the Sound files have finished decoding the callback will be invoked. + * The amount of time spent decoding depends on the codec used and file size. + * If all of the files given have already decoded the callback is triggered immediately. + * + * @method Phaser.SoundManager#setDecodedCallback + * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache. + * @param {Function} callback - The callback which will be invoked once all files have finished decoding. + * @param {Object} callbackContext - The context in which the callback will run. + */ + setDecodedCallback: function (files, callback, callbackContext) { + + if (typeof files === 'string') + { + files = [ files ]; + } + + this._watchList.reset(); + + for (var i = 0; i < files.length; i++) + { + if (files[i] instanceof Phaser.Sound) + { + if (!this.game.cache.isSoundDecoded(files[i].key)) + { + this._watchList.add(files[i].key); + } + } + else if (!this.game.cache.isSoundDecoded(files[i])) + { + this._watchList.add(files[i]); + } + } + + // All decoded already? + if (this._watchList.total === 0) + { + this._watching = false; + callback.call(callbackContext); + } + else + { + this._watching = true; + this._watchCallback = callback; + this._watchContext = callbackContext; + } + + }, + + /** + * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. + * + * @method Phaser.SoundManager#update + * @protected + */ + update: function () { + + if (this.noAudio) + { + return; + } + + if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE)) + { + this.setTouchUnlock(); + } + + for (var i = 0; i < this._sounds.length; i++) + { + this._sounds[i].update(); + } + + if (this._watching) + { + var key = this._watchList.first; + + while (key) + { + if (this.game.cache.isSoundDecoded(key)) + { + this._watchList.remove(key); + } + + key = this._watchList.next; + } + + if (this._watchList.total === 0) + { + this._watching = false; + this._watchCallback.call(this._watchContext); + } + } + + }, + + /** + * Adds a new Sound into the SoundManager. + * + * @method Phaser.SoundManager#add + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The new sound instance. + */ + add: function (key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = this.connectToMaster; } + + var sound = new Phaser.Sound(this.game, key, volume, loop, connect); + + this._sounds.push(sound); + + return sound; + + }, + + /** + * Adds a new AudioSprite into the SoundManager. + * + * @method Phaser.SoundManager#addSprite + * @param {string} key - Asset key for the sound. + * @return {Phaser.AudioSprite} The new AudioSprite instance. + */ + addSprite: function(key) { + + var audioSprite = new Phaser.AudioSprite(this.game, key); + + return audioSprite; + + }, + + /** + * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. + * + * @method Phaser.SoundManager#remove + * @param {Phaser.Sound} sound - The sound object to remove. + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ + remove: function (sound) { + + var i = this._sounds.length; + + while (i--) + { + if (this._sounds[i] === sound) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Removes all Sounds from the SoundManager. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeAll + */ + removeAll: function () { + + this.stopAll(); + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].destroy(); + } + } + + this._sounds.length = 0; + + }, + + /** + * Removes all Sounds from the SoundManager that have an asset key matching the given value. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeByKey + * @param {string} key - The key to match when removing sound objects. + * @return {number} The number of matching sound objects that were removed. + */ + removeByKey: function (key) { + + var i = this._sounds.length; + var removed = 0; + + while (i--) + { + if (this._sounds[i].key === key) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + removed++; + } + } + + return removed; + + }, + + /** + * Adds a new Sound into the SoundManager and starts it playing. + * + * @method Phaser.SoundManager#play + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @return {Phaser.Sound} The new sound instance. + */ + play: function (key, volume, loop) { + + if (this.noAudio) + { + return; + } + + var sound = this.add(key, volume, loop); + + sound.play(); + + return sound; + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + if (this.usingWebAudio) + { + this._muteVolume = this.masterGain.gain.value; + this.masterGain.gain.value = 0; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = true; + } + } + + this.onMute.dispatch(); + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = this._muteVolume; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = false; + } + } + + this.onUnMute.dispatch(); + + }, + + /** + * Stops all the sounds in the game, then destroys them and finally clears up any callbacks. + * + * @method Phaser.SoundManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.onSoundDecode.dispose(); + + if (this.context) + { + if (window.PhaserGlobal) + { + // Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing + window.PhaserGlobal.audioContext = this.context; + } + else + { + if (this.context.close) + { + this.context.close(); + } + } + } + + } + +}; + +Phaser.SoundManager.prototype.constructor = Phaser.SoundManager; + +/** +* @name Phaser.SoundManager#mute +* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || false; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* @name Phaser.SoundManager#volume +* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "volume", { + + get: function () { + + return this._volume; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this._volume !== value) + { + this._volume = value; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = value; + } + else + { + // Loop through the sound cache and change the volume of all html audio tags + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].updateGlobalVolume(value); + } + } + } + + this.onVolumeChange.dispatch(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* The ScaleManager object handles the the scaling, resizing, and alignment of the +* Game size and the game Display canvas. +* +* The Game size is the logical size of the game; the Display canvas has size as an HTML element. +* +* The calculations of these are heavily influenced by the bounding Parent size which is the computed +* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the +* canvas's Parent element play an important role_ in the operation of the ScaleManager. +* +* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size. +* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}). +* +* #### Parent and Display canvas containment guidelines: +* +* - Style the Parent element (of the game canvas) to control the Parent size and +* thus the Display canvas's size and layout. +* +* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior. +* +* - The Parent element should _not_ apply a padding as this is not accounted for. +* If a padding is required apply it to the Parent's parent or apply a margin to the Parent. +* If you need to add a border, margin or any other CSS around your game container, then use a parent element and +* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container. +* +* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as +* they may be updated by the ScaleManager. +* +* #### Example Uses +* +* - ##### Fixed game size; scale canvas proportionally to fill its container +* +* Use `scaleMode` SHOW_ALL. +* +* - ##### Fixed game size; stretch canvas to fill its container (uncommon) +* +* Use `scaleMode` EXACT_FIT. +* +* - ##### Fixed game size; scale canvas proportionally by some other criteria +* +* Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary. +* +* - ##### Fluid game/canvas size +* +* Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary. +* +* - ##### Preferred orientation +* +* Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals. +* +* @description +* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game} +* +* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. +* +* @class +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number|string} width - The width of the game. See above. +* @param {number|string} height - The height of the game. See above. +*/ +Phaser.ScaleManager = function (game, width, height) { + + /** + * A reference to the currently running game. + * @property {Phaser.Game} game + * @protected + * @readonly + */ + this.game = game; + + /** + * Provides access to some cross-device DOM functions. + * @property {Phaser.DOM} dom + * @protected + * @readonly + */ + this.dom = Phaser.DOM; + + /** + * _EXPERIMENTAL:_ A responsive grid on which you can align game objects. + * @property {Phaser.FlexGrid} grid + * @public + */ + this.grid = null; + + /** + * Target width (in pixels) of the Display canvas. + * @property {number} width + * @readonly + */ + this.width = 0; + + /** + * Target height (in pixels) of the Display canvas. + * @property {number} height + * @readonly + */ + this.height = 0; + + /** + * Minimum width the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minWidth + * @readonly + * @protected + */ + this.minWidth = null; + + /** + * Maximum width the canvas should be scaled to (in pixels). + * If null it will scale to whatever width the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxWidth + * @readonly + * @protected + */ + this.maxWidth = null; + + /** + * Minimum height the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minHeight + * @readonly + * @protected + */ + this.minHeight = null; + + /** + * Maximum height the canvas should be scaled to (in pixels). + * If null it will scale to whatever height the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxHeight + * @readonly + * @protected + */ + this.maxHeight = null; + + /** + * The offset coordinates of the Display canvas from the top-left of the browser window. + * The is used internally by Phaser.Pointer (for Input) and possibly other types. + * @property {Phaser.Point} offset + * @readonly + * @protected + */ + this.offset = new Phaser.Point(); + + /** + * If true, the game should only run in a landscape orientation. + * Change with {@link #forceOrientation}. + * @property {boolean} forceLandscape + * @readonly + * @default + * @protected + */ + this.forceLandscape = false; + + /** + * If true, the game should only run in a portrait + * Change with {@link #forceOrientation}. + * @property {boolean} forcePortrait + * @readonly + * @default + * @protected + */ + this.forcePortrait = false; + + /** + * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation. + * + * This value is not updated immediately. + * + * @property {boolean} incorrectOrientation + * @readonly + * @protected + */ + this.incorrectOrientation = false; + + /** + * See {@link #pageAlignHorizontally}. + * @property {boolean} _pageAlignHorizontally + * @private + */ + this._pageAlignHorizontally = false; + + /** + * See {@link #pageAlignVertically}. + * @property {boolean} _pageAlignVertically + * @private + */ + this._pageAlignVertically = false; + + /** + * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes. + * + * The signal is supplied with the following arguments: + * - `scale` - the ScaleManager object + * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}. + * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. + * + * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. + * Thus the following tests can be done: + * + * // The orientation itself changed: + * scale.screenOrientation !== prevOrientation + * // The orientation just became incorrect: + * scale.incorrectOrientation && !wasIncorrect + * + * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation + * correctness changes even if the orientation itself does not change. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onOrientationChange + * @public + */ + this.onOrientationChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} enterIncorrectOrientation + * @public + */ + this.enterIncorrectOrientation = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} leaveIncorrectOrientation + * @public + */ + this.leaveIncorrectOrientation = new Phaser.Signal(); + + /** + * This boolean provides you with a way to determine if the browser is in Full Screen + * mode (via the Full Screen API), and Phaser was the one responsible for activating it. + * + * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the + * one that made the browser go full-screen, so this flag lets you determine that. + * + * @property {boolean} hasPhaserSetFullScreen + * @default + */ + this.hasPhaserSetFullScreen = false; + + /** + * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. + * The target element must have the correct CSS styling and contain the Display canvas. + * + * The elements style will be modified (ie. the width and height might be set to 100%) + * but it will not be added to, removed from, or repositioned within the DOM. + * An attempt is made to restore relevant style changes when fullscreen mode is left. + * + * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. + * + * @property {?DOMElement} fullScreenTarget + * @default + */ + this.fullScreenTarget = null; + + /** + * The fullscreen target, as created by {@link #createFullScreenTarget}. + * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends. + * @property {?DOMElement} _createdFullScreenTarget + * @private + */ + this._createdFullScreenTarget = null; + + /** + * This signal is dispatched when fullscreen mode is ready to be initialized but + * before the fullscreen request. + * + * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. + * + * The `targetElement` is the {@link #fullScreenTarget} element, + * if such is assigned, or a new element created by {@link #createFullScreenTarget}. + * + * Custom CSS styling or resets can be applied to `targetElement` as required. + * + * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}: + * - After initialization the Display canvas is moved onto the `targetElement` for + * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. + * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. + * + * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}. + * + * @property {Phaser.Signal} onFullScreenInit + * @public + */ + this.onFullScreenInit = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine + * if currently running in Fullscreen mode. + * + * @property {Phaser.Signal} onFullScreenChange + * @public + */ + this.onFullScreenChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser fails to enter fullscreen mode; + * or if the device does not support fullscreen mode and `startFullScreen` is invoked. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). + * + * @property {Phaser.Signal} onFullScreenError + * @public + */ + this.onFullScreenError = new Phaser.Signal(); + + /** + * The _last known_ orientation of the screen, as defined in the Window Screen Web API. + * See {@link Phaser.DOM.getScreenOrientation} for possible values. + * + * @property {string} screenOrientation + * @readonly + * @public + */ + this.screenOrientation = this.dom.getScreenOrientation(); + + /** + * The _current_ scale factor based on the game dimensions vs. the scaled dimensions. + * @property {Phaser.Point} scaleFactor + * @readonly + */ + this.scaleFactor = new Phaser.Point(1, 1); + + /** + * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions. + * @property {Phaser.Point} scaleFactorInversed + * @readonly + * @protected + */ + this.scaleFactorInversed = new Phaser.Point(1, 1); + + /** + * The Display canvas is aligned by adjusting the margins; the last margins are stored here. + * + * @property {Bounds-like} margin + * @readonly + * @protected + */ + this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0}; + + /** + * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. + * @property {Phaser.Rectangle} bounds + * @readonly + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The aspect ratio of the scaled Display canvas. + * @property {number} aspectRatio + * @readonly + */ + this.aspectRatio = 0; + + /** + * The aspect ratio of the original game dimensions. + * @property {number} sourceAspectRatio + * @readonly + */ + this.sourceAspectRatio = 0; + + /** + * The native browser events from Fullscreen API changes. + * @property {any} event + * @readonly + * @private + */ + this.event = null; + + /** + * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container. + * + * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. + * - If 'visual', the edge will be constrained to the Window / displayed screen area + * - If 'layout', the edge will be constrained to the CSS Layout bounds + * - An invalid value is treated as 'visual' + * + * @member + * @property {string} bottom + * @property {string} right + * @default + */ + this.windowConstraints = { + right: 'layout', + bottom: '' + }; + + /** + * Various compatibility settings. + * A value of "(auto)" indicates the setting is configured based on device and runtime information. + * + * A {@link #refresh} may need to be performed after making changes. + * + * @protected + * + * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.) + * + * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}. + * + * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. + * + * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh. + * + * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates. + * The height set varies by device and may either be the height of the window or the viewport. + * + * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. + * + * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. + * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. + * Any other string value (including the empty string) prevents using click trampolines. + * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}. + */ + this.compatibility = { + supportsFullScreen: false, + orientationFallback: null, + noMargins: false, + scrollTo: null, + forceMinimumDocumentHeight: false, + canExpandParent: true, + clickTrampoline: '' + }; + + /** + * Scale mode to be used when not in fullscreen. + * @property {number} _scaleMode + * @private + */ + this._scaleMode = Phaser.ScaleManager.NO_SCALE; + + /* + * Scale mode to be used in fullscreen. + * @property {number} _fullScreenScaleMode + * @private + */ + this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE; + + /** + * True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * The {@link #parentNode} property is generally ignored while this is in effect. + * + * @property {boolean} parentIsWindow + */ + this.parentIsWindow = false; + + /** + * The _original_ DOM element for the parent of the Display canvas. + * This may be different in fullscreen - see {@link #createFullScreenTarget}. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * This should only be changed after moving the Game canvas to a different DOM parent. + * + * @property {?DOMElement} parentNode + */ + this.parentNode = null; + + /** + * The scale of the game in relation to its parent container. + * @property {Phaser.Point} parentScaleFactor + * @readonly + */ + this.parentScaleFactor = new Phaser.Point(1, 1); + + /** + * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). + * Update checks normally happen quicker in response to other events. + * + * @property {integer} trackParentInterval + * @default + * @protected + * @see {@link Phaser.ScaleManager#refresh refresh} + */ + this.trackParentInterval = 2000; + + /** + * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. + * When invoked this is done _after_ the Canvas size/position have been updated. + * + * The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.) + * + * This signal is _only_ called when a change occurs and a reflow may be required. + * For example, if the canvas does not change sizes because of CSS settings (such as min-width) + * then this signal will _not_ be triggered. + * + * Use this to handle responsive game layout options. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onSizeChange + */ + this.onSizeChange = new Phaser.Signal(); + + /** + * The callback that will be called each the parent container resizes. + * @property {function} onResize + * @private + */ + this.onResize = null; + + /** + * The context in which the {@link #onResize} callback will be called. + * @property {object} onResizeContext + * @private + */ + this.onResizeContext = null; + + /** + * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot. + * @private + */ + this._pendingScaleMode = null; + + /** + * Information saved when fullscreen mode is started. + * @property {?object} _fullScreenRestore + * @private + */ + this._fullScreenRestore = null; + + /** + * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}. + * @property {Phaser.Rectangle} _gameSize + * @private + */ + this._gameSize = new Phaser.Rectangle(); + + /** + * The user-supplied scale factor, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleFactor + * @private + */ + this._userScaleFactor = new Phaser.Point(1, 1); + + /** + * The user-supplied scale trim, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleTrim + * @private + */ + this._userScaleTrim = new Phaser.Point(0, 0); + + /** + * The last time the bounds were checked in `preUpdate`. + * @property {number} _lastUpdate + * @private + */ + this._lastUpdate = 0; + + /** + * Size checks updates are delayed according to the throttle. + * The throttle increases to `trackParentInterval` over time and is used to more + * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety. + * @property {integer} _updateThrottle + * @private + */ + this._updateThrottle = 0; + + /** + * The minimum throttle allowed until it has slowed down sufficiently. + * @property {integer} _updateThrottleReset + * @private + */ + this._updateThrottleReset = 100; + + /** + * The cached result of the parent (possibly window) bounds; used to invalidate sizing. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._parentBounds = new Phaser.Rectangle(); + + /** + * Temporary bounds used for internal work to cut down on new objects created. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._tempBounds = new Phaser.Rectangle(); + + /** + * The Canvas size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedCanvasSize + * @private + */ + this._lastReportedCanvasSize = new Phaser.Rectangle(); + + /** + * The Game size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedGameSize + * @private + */ + this._lastReportedGameSize = new Phaser.Rectangle(); + + /** + * @property {boolean} _booted - ScaleManager booted state. + * @private + */ + this._booted = false; + + if (game.config) + { + this.parseConfig(game.config); + } + + this.setupScale(width, height); + +}; + +/** +* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.EXACT_FIT = 0; + +/** +* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.NO_SCALE = 1; + +/** +* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.SHOW_ALL = 2; + +/** +* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.RESIZE = 3; + +/** +* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.USER_SCALE = 4; + +/** +* Names of the scale modes, indexed by value. +* +* @constant +* @type {string[]} +*/ +Phaser.ScaleManager.MODES = [ + 'EXACT_FIT', + 'NO_SCALE', + 'SHOW_ALL', + 'RESIZE', + 'USER_SCALE' +]; + +Phaser.ScaleManager.prototype = { + + /** + * Start the ScaleManager. + * + * @method Phaser.ScaleManager#boot + * @protected + */ + boot: function () { + + // Configure device-dependent compatibility + + var compat = this.compatibility; + + compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS; + + // We can't do anything about the status bars in iPads, web apps or desktops + if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop) + { + if (this.game.device.android && !this.game.device.chrome) + { + compat.scrollTo = new Phaser.Point(0, 1); + } + else + { + compat.scrollTo = new Phaser.Point(0, 0); + } + } + + if (this.game.device.desktop) + { + compat.orientationFallback = 'screen'; + compat.clickTrampoline = 'when-not-mouse'; + } + else + { + compat.orientationFallback = ''; + compat.clickTrampoline = ''; + } + + // Configure event listeners + + var _this = this; + + this._orientationChange = function(event) { + return _this.orientationChange(event); + }; + + this._windowResize = function(event) { + return _this.windowResize(event); + }; + + // This does not appear to be on the standards track + window.addEventListener('orientationchange', this._orientationChange, false); + window.addEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + this._fullScreenChange = function(event) { + return _this.fullScreenChange(event); + }; + + this._fullScreenError = function(event) { + return _this.fullScreenError(event); + }; + + document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.addEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.addEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.addEventListener('fullscreenchange', this._fullScreenChange, false); + + document.addEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.addEventListener('mozfullscreenerror', this._fullScreenError, false); + document.addEventListener('MSFullscreenError', this._fullScreenError, false); + document.addEventListener('fullscreenerror', this._fullScreenError, false); + } + + this.game.onResume.add(this._gameResumed, this); + + // Initialize core bounds + + this.dom.getOffset(this.game.canvas, this.offset); + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + this.setGameSize(this.game.width, this.game.height); + + // Don't use updateOrientationState so events are not fired + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + if (Phaser.FlexGrid) + { + this.grid = new Phaser.FlexGrid(this, this.width, this.height); + } + + this._booted = true; + + if (this._pendingScaleMode !== null) + { + this.scaleMode = this._pendingScaleMode; + this._pendingScaleMode = null; + } + + }, + + /** + * Load configuration settings. + * + * @method Phaser.ScaleManager#parseConfig + * @protected + * @param {object} config - The game configuration object. + */ + parseConfig: function (config) { + + if (config['scaleMode'] !== undefined) + { + if (this._booted) + { + this.scaleMode = config['scaleMode']; + } + else + { + this._pendingScaleMode = config['scaleMode']; + } + } + + if (config['fullScreenScaleMode'] !== undefined) + { + this.fullScreenScaleMode = config['fullScreenScaleMode']; + } + + if (config['fullScreenTarget']) + { + this.fullScreenTarget = config['fullScreenTarget']; + } + + this.pageAlignHorizontally = config.alignH || false; + this.pageAlignVertically = config.alignV || false; + + if (config.scaleH && config.scaleV) + { + this.setUserScale(config.scaleH, config.scaleV, config.trimH, config.trimV); + } + + }, + + /** + * Calculates and sets the game dimensions based on the given width and height. + * + * This should _not_ be called when in fullscreen mode. + * + * @method Phaser.ScaleManager#setupScale + * @protected + * @param {number|string} width - The width of the game. + * @param {number|string} height - The height of the game. + */ + setupScale: function (width, height) { + + var target; + var rect = new Phaser.Rectangle(); + + if (this.game.parent !== '') + { + if (typeof this.game.parent === 'string') + { + // hopefully an element ID + target = document.getElementById(this.game.parent); + } + else if (this.game.parent && this.game.parent.nodeType === 1) + { + // quick test for a HTMLelement + target = this.game.parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + // Use the full window + this.parentNode = null; + this.parentIsWindow = true; + + rect.width = this.dom.visualBounds.width; + rect.height = this.dom.visualBounds.height; + + this.offset.set(0, 0); + } + else + { + this.parentNode = target; + this.parentIsWindow = false; + + this.getParentBounds(this._parentBounds); + + rect.width = this._parentBounds.width; + rect.height = this._parentBounds.height; + + this.offset.set(this._parentBounds.x, this._parentBounds.y); + } + + var newWidth = 0; + var newHeight = 0; + + if (typeof width === 'number') + { + newWidth = width; + } + else + { + // Percentage based + this.parentScaleFactor.x = parseInt(width, 10) / 100; + newWidth = rect.width * this.parentScaleFactor.x; + } + + if (typeof height === 'number') + { + newHeight = height; + } + else + { + // Percentage based + this.parentScaleFactor.y = parseInt(height, 10) / 100; + newHeight = rect.height * this.parentScaleFactor.y; + } + + newWidth = Math.floor(newWidth); + newHeight = Math.floor(newHeight); + + this._gameSize.setTo(0, 0, newWidth, newHeight); + + this.updateDimensions(newWidth, newHeight, false); + + }, + + /** + * Invoked when the game is resumed. + * + * @method Phaser.ScaleManager#_gameResumed + * @private + */ + _gameResumed: function () { + + this.queueUpdate(true); + + }, + + /** + * Set the actual Game size. + * Use this instead of directly changing `game.width` or `game.height`. + * + * The actual physical display (Canvas element size) depends on various settings including + * - Scale mode + * - Scaling factor + * - Size of Canvas's parent element or CSS rules such as min-height/max-height; + * - The size of the Window + * + * @method Phaser.ScaleManager#setGameSize + * @public + * @param {integer} width - _Game width_, in pixels. + * @param {integer} height - _Game height_, in pixels. + */ + setGameSize: function (width, height) { + + this._gameSize.setTo(0, 0, width, height); + + if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE) + { + this.updateDimensions(width, height, true); + } + + this.queueUpdate(true); + + }, + + /** + * Set a User scaling factor used in the USER_SCALE scaling mode. + * + * The target canvas size is computed by: + * + * canvas.width = (game.width * hScale) - hTrim + * canvas.height = (game.height * vScale) - vTrim + * + * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly. + * + * @method Phaser.ScaleManager#setUserScale + * @param {number} hScale - Horizontal scaling factor. + * @param {numer} vScale - Vertical scaling factor. + * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling. + * @param {integer} [vTrim=0] - Vertical trim, applied after scaling. + * @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate + * @param {boolean} [force=true] - Force a resize during the next preUpdate + */ + setUserScale: function (hScale, vScale, hTrim, vTrim, queueUpdate, force) { + + this._userScaleFactor.setTo(hScale, vScale); + this._userScaleTrim.setTo(hTrim | 0, vTrim | 0); + + if (queueUpdate === undefined) { queueUpdate = true; } + if (force === undefined) { force = true; } + + if (queueUpdate) + { + this.queueUpdate(force); + } + + }, + + /** + * Sets the callback that will be invoked before sizing calculations. + * + * Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries: + * the browser window has been resized, the device has been rotated, or the parent container's size has changed. + * At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all + * after it makes its sizing calculations). You can read the size of the parent container from the + * `parentBounds` argument to the callback. + * + * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling. + * + * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager + * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. + * + * This callback + * - May be invoked even though the parent container or canvas sizes have not changed + * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated + * - Will be invoked from `preUpdate`, _even when_ the game is paused + * + * See {@link #onSizeChange} for a better way of reacting to layout updates. + * + * @method Phaser.ScaleManager#setResizeCallback + * @public + * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes. + * @param {object} context - The context in which the callback will be called. + */ + setResizeCallback: function (callback, context) { + + this.onResize = callback; + this.onResizeContext = context; + + }, + + /** + * Signals a resize - IF the canvas or Game size differs from the last signal. + * + * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager). + * + * It dispatches the {@link #onSizeChange} signal. + * + * @method Phaser.ScaleManager#signalSizeChange + * @private + */ + signalSizeChange: function () { + + if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) || + !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize)) + { + var width = this.width; + var height = this.height; + + this._lastReportedCanvasSize.setTo(0, 0, width, height); + this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height); + + if (this.grid) + { + this.grid.onResize(width, height); + } + + this.onSizeChange.dispatch(this, width, height); + + // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode. + if (this.currentScaleMode === Phaser.ScaleManager.RESIZE) + { + this.game.state.resize(width, height); + this.game.load.resize(width, height); + } + } + + }, + + /** + * Set the min and max dimensions for the Display canvas. + * + * _Note:_ The min/max dimensions are only applied in some cases + * - When the device is not in an incorrect orientation; or + * - The scale mode is EXACT_FIT when not in fullscreen + * + * @method Phaser.ScaleManager#setMinMax + * @public + * @param {number} minWidth - The minimum width the game is allowed to scale down to. + * @param {number} minHeight - The minimum height the game is allowed to scale down to. + * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified. + * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified. + * @todo These values are only sometimes honored. + */ + setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) { + + this.minWidth = minWidth; + this.minHeight = minHeight; + + if (typeof maxWidth !== 'undefined') + { + this.maxWidth = maxWidth; + } + + if (typeof maxHeight !== 'undefined') + { + this.maxHeight = maxHeight; + } + + }, + + /** + * The ScaleManager.preUpdate is called automatically by the core Game loop. + * + * @method Phaser.ScaleManager#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.game.time.time < (this._lastUpdate + this._updateThrottle)) + { + return; + } + + var prevThrottle = this._updateThrottle; + this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100; + + this.dom.getOffset(this.game.canvas, this.offset); + + var prevWidth = this._parentBounds.width; + var prevHeight = this._parentBounds.height; + var bounds = this.getParentBounds(this._parentBounds); + + var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight; + + // Always invalidate on a newly detected orientation change + var orientationChanged = this.updateOrientationState(); + + if (boundsChanged || orientationChanged) + { + if (this.onResize) + { + this.onResize.call(this.onResizeContext, this, bounds); + } + + this.updateLayout(); + + this.signalSizeChange(); + } + + // Next throttle, eg. 25, 50, 100, 200.. + var throttle = this._updateThrottle * 2; + + // Don't let an update be too eager about resetting the throttle. + if (this._updateThrottle < prevThrottle) + { + throttle = Math.min(prevThrottle, this._updateThrottleReset); + } + + this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval); + this._lastUpdate = this.game.time.time; + + }, + + /** + * Update method while paused. + * + * @method Phaser.ScaleManager#pauseUpdate + * @private + */ + pauseUpdate: function () { + + this.preUpdate(); + + // Updates at slowest. + this._updateThrottle = this.trackParentInterval; + + }, + + /** + * Update the dimensions taking the parent scaling factor into account. + * + * @method Phaser.ScaleManager#updateDimensions + * @private + * @param {number} width - The new width of the parent container. + * @param {number} height - The new height of the parent container. + * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars. + */ + updateDimensions: function (width, height, resize) { + + this.width = width * this.parentScaleFactor.x; + this.height = height * this.parentScaleFactor.y; + + this.game.width = this.width; + this.game.height = this.height; + + this.sourceAspectRatio = this.width / this.height; + this.updateScalingAndBounds(); + + if (resize) + { + // Resize the renderer (which in turn resizes the Display canvas!) + this.game.renderer.resize(this.width, this.height); + + // The Camera can never be smaller than the Game size + this.game.camera.setSize(this.width, this.height); + + // This should only happen if the world is smaller than the new canvas size + this.game.world.resize(this.width, this.height); + } + + }, + + /** + * Update relevant scaling values based on the ScaleManager dimension and game dimensions, + * which should already be set. This does not change {@link #sourceAspectRatio}. + * + * @method Phaser.ScaleManager#updateScalingAndBounds + * @private + */ + updateScalingAndBounds: function () { + + this.scaleFactor.x = this.game.width / this.width; + this.scaleFactor.y = this.game.height / this.height; + + this.scaleFactorInversed.x = this.width / this.game.width; + this.scaleFactorInversed.y = this.height / this.game.height; + + this.aspectRatio = this.width / this.height; + + // This can be invoked in boot pre-canvas + if (this.game.canvas) + { + this.dom.getOffset(this.game.canvas, this.offset); + } + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + // Can be invoked in boot pre-input + if (this.game.input && this.game.input.scale) + { + this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y); + } + + }, + + /** + * Force the game to run in only one orientation. + * + * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. + * + * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor + * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the + * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` + * + * @method Phaser.ScaleManager#forceOrientation + * @public + * @param {boolean} forceLandscape - true if the game should run in landscape mode only. + * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. + */ + forceOrientation: function (forceLandscape, forcePortrait) { + + if (forcePortrait === undefined) { forcePortrait = false; } + + if (forceLandscape === true && forcePortrait === true) + { + console.warn('Phaser.ScaleManager: forceLandscape and forcePortrait cannot both be true.'); + return; + } + + this.forceLandscape = forceLandscape; + this.forcePortrait = forcePortrait; + + this.queueUpdate(true); + + }, + + /** + * Classify the orientation, per `getScreenOrientation`. + * + * @method Phaser.ScaleManager#classifyOrientation + * @private + * @param {string} orientation - The orientation string, e.g. 'portrait-primary'. + * @return {?string} The classified orientation: 'portrait', 'landscape`, or null. + */ + classifyOrientation: function (orientation) { + + if (orientation === 'portrait-primary' || orientation === 'portrait-secondary') + { + return 'portrait'; + } + else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary') + { + return 'landscape'; + } + else + { + return null; + } + + }, + + /** + * Updates the current orientation and dispatches orientation change events. + * + * @method Phaser.ScaleManager#updateOrientationState + * @private + * @return {boolean} True if the orientation state changed which means a forced update is likely required. + */ + updateOrientationState: function () { + + var previousOrientation = this.screenOrientation; + var previouslyIncorrect = this.incorrectOrientation; + + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) || + (this.forcePortrait && !this.isPortrait); + + var changed = previousOrientation !== this.screenOrientation; + var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation; + + if (correctnessChanged) + { + if (this.incorrectOrientation) + { + this.enterIncorrectOrientation.dispatch(); + } + else + { + this.leaveIncorrectOrientation.dispatch(); + } + } + + if (changed || correctnessChanged) + { + this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect); + } + + return changed || correctnessChanged; + + }, + + /** + * window.orientationchange event handler. + * + * @method Phaser.ScaleManager#orientationChange + * @private + * @param {Event} event - The orientationchange event data. + */ + orientationChange: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * window.resize event handler. + * + * @method Phaser.ScaleManager#windowResize + * @private + * @param {Event} event - The resize event data. + */ + windowResize: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * Scroll to the top - in some environments. See `compatibility.scrollTo`. + * + * @method Phaser.ScaleManager#scrollTop + * @private + */ + scrollTop: function () { + + var scrollTo = this.compatibility.scrollTo; + + if (scrollTo) + { + window.scrollTo(scrollTo.x, scrollTo.y); + } + + }, + + /** + * The "refresh" methods informs the ScaleManager that a layout refresh is required. + * + * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) + * when the browser is resized, the orientation changes, or when there is a detected change + * of the Parent size. Refreshing is also done automatically when public properties, + * such as {@link #scaleMode}, are updated or state-changing methods are invoked. + * + * The "refresh" method _may_ need to be used in a few (rare) situtations when + * + * - a device change event is not correctly detected; or + * - the Parent size changes (and an immediate reflow is desired); or + * - the ScaleManager state is updated by non-standard means; or + * - certain {@link #compatibility} properties are manually changed. + * + * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. + * + * @method Phaser.ScaleManager#refresh + * @public + */ + refresh: function () { + + this.scrollTop(); + this.queueUpdate(true); + + }, + + /** + * Updates the game / canvas position and size. + * + * @method Phaser.ScaleManager#updateLayout + * @private + */ + updateLayout: function () { + + var scaleMode = this.currentScaleMode; + + if (scaleMode === Phaser.ScaleManager.RESIZE) + { + this.reflowGame(); + return; + } + + this.scrollTop(); + + if (this.compatibility.forceMinimumDocumentHeight) + { + // (This came from older code, by why is it here?) + // Set minimum height of content to new window height + document.documentElement.style.minHeight = window.innerHeight + 'px'; + } + + if (this.incorrectOrientation) + { + this.setMaximum(); + } + else + { + if (scaleMode === Phaser.ScaleManager.EXACT_FIT) + { + this.setExactFit(); + } + else if (scaleMode === Phaser.ScaleManager.SHOW_ALL) + { + if (!this.isFullScreen && this.boundingParent && + this.compatibility.canExpandParent) + { + // Try to expand parent out, but choosing maximizing dimensions. + // Then select minimize dimensions which should then honor parent + // maximum bound applications. + this.setShowAll(true); + this.resetCanvas(); + this.setShowAll(); + } + else + { + this.setShowAll(); + } + } + else if (scaleMode === Phaser.ScaleManager.NO_SCALE) + { + this.width = this.game.width; + this.height = this.game.height; + } + else if (scaleMode === Phaser.ScaleManager.USER_SCALE) + { + this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x; + this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y; + } + } + + if (!this.compatibility.canExpandParent && + (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE)) + { + var bounds = this.getParentBounds(this._tempBounds); + this.width = Math.min(this.width, bounds.width); + this.height = Math.min(this.height, bounds.height); + } + + // Always truncate / force to integer + this.width = this.width | 0; + this.height = this.height | 0; + + this.reflowCanvas(); + + }, + + /** + * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. + * + * If in fullscreen mode or without parent (see {@link #parentIsWindow}), + * this will be the bounds of the visual viewport itself. + * + * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside + * the viewport then this function may return a smaller than expected size. + * + * Values are rounded to the nearest pixel. + * + * @method Phaser.ScaleManager#getParentBounds + * @protected + * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed. + * @return {Phaser.Rectangle} The established parent bounds. + */ + getParentBounds: function (target) { + + var bounds = target || new Phaser.Rectangle(); + var parentNode = this.boundingParent; + var visualBounds = this.dom.visualBounds; + var layoutBounds = this.dom.layoutBounds; + + if (!parentNode) + { + bounds.setTo(0, 0, visualBounds.width, visualBounds.height); + } + else + { + // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect + var clientRect = parentNode.getBoundingClientRect(); + var parentRect = (parentNode.offsetParent) ? parentNode.offsetParent.getBoundingClientRect() : parentNode.getBoundingClientRect(); + + bounds.setTo(clientRect.left - parentRect.left, clientRect.top - parentRect.top, clientRect.width, clientRect.height); + + var wc = this.windowConstraints; + + if (wc.right) + { + var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds; + bounds.right = Math.min(bounds.right, windowBounds.width); + } + + if (wc.bottom) + { + var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds; + bounds.bottom = Math.min(bounds.bottom, windowBounds.height); + } + } + + bounds.setTo( + Math.round(bounds.x), Math.round(bounds.y), + Math.round(bounds.width), Math.round(bounds.height)); + + return bounds; + + }, + + + /** + * Shorthand for setting {@link #pageAlignHorizontally} and {@link #pageAlignVertically}. + * + * @method Phaser.ScaleManager#align + * @param {boolean} [horizontal] - Value for {@link #pageAlignHorizontally}. Pass `null` to leave unchanged. + * @param {boolean} [vertical] - Value for {@link #pageAlignVertically}. Omit or pass `null` to leave unchanged. + */ + align: function (horizontal, vertical) { + + if (horizontal != null) + { + this.pageAlignHorizontally = horizontal; + } + + if (vertical != null) + { + this.pageAlignVertically = vertical; + } + + }, + + /** + * Update the canvas position/margins - for alignment within the parent container. + * + * The canvas margins _must_ be reset/cleared prior to invoking this. + * + * @method Phaser.ScaleManager#alignCanvas + * @private + * @param {boolean} horizontal - Align horizontally? + * @param {boolean} vertical - Align vertically? + */ + alignCanvas: function (horizontal, vertical) { + + var parentBounds = this.getParentBounds(this._tempBounds); + var canvas = this.game.canvas; + var margin = this.margin; + + if (horizontal) + { + margin.left = margin.right = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.width < parentBounds.width && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.left - parentBounds.x; + var targetEdge = (parentBounds.width / 2) - (this.width / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + + margin.left = Math.round(offset); + } + + canvas.style.marginLeft = margin.left + 'px'; + + if (margin.left !== 0) + { + margin.right = -(parentBounds.width - canvasBounds.width - margin.left); + canvas.style.marginRight = margin.right + 'px'; + } + } + + if (vertical) + { + margin.top = margin.bottom = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.height < parentBounds.height && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.top - parentBounds.y; + var targetEdge = (parentBounds.height / 2) - (this.height / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + margin.top = Math.round(offset); + } + + canvas.style.marginTop = margin.top + 'px'; + + if (margin.top !== 0) + { + margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top); + canvas.style.marginBottom = margin.bottom + 'px'; + } + } + + // Silly backwards compatibility.. + margin.x = margin.left; + margin.y = margin.top; + + }, + + /** + * Updates the Game state / size. + * + * The canvas margins may always be adjusted, even if alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowGame + * @private + */ + reflowGame: function () { + + this.resetCanvas('', ''); + + var bounds = this.getParentBounds(this._tempBounds); + this.updateDimensions(bounds.width, bounds.height, true); + + }, + + /** + * Updates the Display canvas size. + * + * The canvas margins may always be adjusted, even alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowCanvas + * @private + */ + reflowCanvas: function () { + + if (!this.incorrectOrientation) + { + this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width); + this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height); + } + + this.resetCanvas(); + + if (!this.compatibility.noMargins) + { + if (this.isFullScreen && this._createdFullScreenTarget) + { + this.alignCanvas(true, true); + } + else + { + this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically); + } + } + + this.updateScalingAndBounds(); + + }, + + /** + * "Reset" the Display canvas and set the specified width/height. + * + * @method Phaser.ScaleManager#resetCanvas + * @private + * @param {string} [cssWidth=(current width)] - The css width to set. + * @param {string} [cssHeight=(current height)] - The css height to set. + */ + resetCanvas: function (cssWidth, cssHeight) { + + if (cssWidth === undefined) { cssWidth = this.width + 'px'; } + if (cssHeight === undefined) { cssHeight = this.height + 'px'; } + + var canvas = this.game.canvas; + + if (!this.compatibility.noMargins) + { + canvas.style.marginLeft = ''; + canvas.style.marginTop = ''; + canvas.style.marginRight = ''; + canvas.style.marginBottom = ''; + } + + canvas.style.width = cssWidth; + canvas.style.height = cssHeight; + + }, + + /** + * Queues/marks a size/bounds check as needing to occur (from `preUpdate`). + * + * @method Phaser.ScaleManager#queueUpdate + * @private + * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty. + */ + queueUpdate: function (force) { + + if (force) + { + this._parentBounds.width = 0; + this._parentBounds.height = 0; + } + + this._updateThrottle = this._updateThrottleReset; + + }, + + /** + * Reset internal data/state. + * + * @method Phaser.ScaleManager#reset + * @private + */ + reset: function (clearWorld) { + + if (clearWorld && this.grid) + { + this.grid.reset(); + } + + }, + + /** + * Updates the width/height to that of the window. + * + * @method Phaser.ScaleManager#setMaximum + * @private + */ + setMaximum: function () { + + this.width = this.dom.visualBounds.width; + this.height = this.dom.visualBounds.height; + + }, + + /** + * Updates the width/height such that the game is scaled proportionally. + * + * @method Phaser.ScaleManager#setShowAll + * @private + * @param {boolean} expanding - If true then the maximizing dimension is chosen. + */ + setShowAll: function (expanding) { + + var bounds = this.getParentBounds(this._tempBounds); + var width = bounds.width; + var height = bounds.height; + + var multiplier; + + if (expanding) + { + multiplier = Math.max((height / this.game.height), (width / this.game.width)); + } + else + { + multiplier = Math.min((height / this.game.height), (width / this.game.width)); + } + + this.width = Math.round(this.game.width * multiplier); + this.height = Math.round(this.game.height * multiplier); + + }, + + /** + * Updates the width/height such that the game is stretched to the available size. + * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen. + * + * @method Phaser.ScaleManager#setExactFit + * @private + */ + setExactFit: function () { + + var bounds = this.getParentBounds(this._tempBounds); + + this.width = bounds.width; + this.height = bounds.height; + + if (this.isFullScreen) + { + // Max/min not honored fullscreen + return; + } + + if (this.maxWidth) + { + this.width = Math.min(this.width, this.maxWidth); + } + + if (this.maxHeight) + { + this.height = Math.min(this.height, this.maxHeight); + } + + }, + + /** + * Creates a fullscreen target. This is called automatically as as needed when entering + * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}. + * + * Use {@link #onFullScreenInit} to customize the created object. + * + * @method Phaser.ScaleManager#createFullScreenTarget + * @protected + */ + createFullScreenTarget: function () { + + var fsTarget = document.createElement('div'); + + fsTarget.style.margin = '0'; + fsTarget.style.padding = '0'; + fsTarget.style.background = '#000'; + + return fsTarget; + + }, + + /** + * Display the game in the browser's fullscreen mode. + * + * This _must_ be called from a user-input Pointer or Mouse event (and possibly a {@link https://www.chromestatus.com/feature/6131337345892352 "user gesture"}), e.g., + * + * - {@link Phaser.Events#onInputUp} + * - {@link Phaser.Input#onUp} or {@link Phaser.Input#onTap} + * - `click`, `mousedown`, `mouseup`, `pointerup`, or `touchend` + * + * Games within an iframe will also be blocked from fullscreen unless the iframe has the `allowfullscreen` attribute. + * + * The {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} must be {@link http://caniuse.com/#search=fullscreen supported by the browser} for this to work - it is not the same as setting + * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current + * device is reported to support fullscreen mode. + * + * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. + * + * Safari blocks access to keyboard events in fullscreen mode (as a security measure). + * + * @method Phaser.ScaleManager#startFullScreen + * @public + * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. + * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed. + * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) + */ + startFullScreen: function (antialias, allowTrampoline) { + + if (this.isFullScreen) + { + return false; + } + + if (!this.compatibility.supportsFullScreen) + { + // Error is called in timeout to emulate the real fullscreenerror event better + var _this = this; + + setTimeout(function () { + _this.fullScreenError(); + }, 10); + + return; + } + + if (this.compatibility.clickTrampoline === 'when-not-mouse') + { + var input = this.game.input; + + if (input.activePointer && + input.activePointer !== input.mousePointer && + (allowTrampoline || allowTrampoline !== false)) + { + input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]); + return; + } + } + + if (antialias !== undefined && this.game.renderType === Phaser.CANVAS) + { + this.game.stage.smoothed = antialias; + } + + var fsTarget = this.fullScreenTarget; + + if (!fsTarget) + { + this.cleanupCreatedTarget(); + + this._createdFullScreenTarget = this.createFullScreenTarget(); + fsTarget = this._createdFullScreenTarget; + } + + var initData = { + targetElement: fsTarget + }; + + this.hasPhaserSetFullScreen = true; + + this.onFullScreenInit.dispatch(this, initData); + + if (this._createdFullScreenTarget) + { + // Move the Display canvas inside of the target and add the target to the DOM + // (The target has to be added for the Fullscreen API to work.) + var canvas = this.game.canvas; + var parent = canvas.parentNode; + parent.insertBefore(fsTarget, canvas); + fsTarget.appendChild(canvas); + } + + if (this.game.device.fullscreenKeyboard) + { + fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT); + } + else + { + fsTarget[this.game.device.requestFullscreen](); + } + + return true; + + }, + + /** + * Stops / exits fullscreen mode, if active. + * + * @method Phaser.ScaleManager#stopFullScreen + * @public + * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. + */ + stopFullScreen: function () { + + if (!this.isFullScreen || !this.compatibility.supportsFullScreen) + { + return false; + } + + this.hasPhaserSetFullScreen = false; + + document[this.game.device.cancelFullscreen](); + + return true; + + }, + + /** + * Cleans up the previous fullscreen target, if such was automatically created. + * This ensures the canvas is restored to its former parent, assuming the target didn't move. + * + * @method Phaser.ScaleManager#cleanupCreatedTarget + * @private + */ + cleanupCreatedTarget: function () { + + var fsTarget = this._createdFullScreenTarget; + + if (fsTarget && fsTarget.parentNode) + { + // Make sure to cleanup synthetic target for sure; + // swap the canvas back to the parent. + var parent = fsTarget.parentNode; + parent.insertBefore(this.game.canvas, fsTarget); + parent.removeChild(fsTarget); + } + + this._createdFullScreenTarget = null; + + }, + + /** + * Used to prepare/restore extra fullscreen mode settings. + * (This does move any elements within the DOM tree.) + * + * @method Phaser.ScaleManager#prepScreenMode + * @private + * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_. + */ + prepScreenMode: function (enteringFullscreen) { + + var createdTarget = !!this._createdFullScreenTarget; + var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget; + + if (enteringFullscreen) + { + if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT) + { + // Resize target, as long as it's not the canvas + if (fsTarget !== this.game.canvas) + { + this._fullScreenRestore = { + targetWidth: fsTarget.style.width, + targetHeight: fsTarget.style.height + }; + + fsTarget.style.width = '100%'; + fsTarget.style.height = '100%'; + } + } + } + else + { + // Have restore information + if (this._fullScreenRestore) + { + fsTarget.style.width = this._fullScreenRestore.targetWidth; + fsTarget.style.height = this._fullScreenRestore.targetHeight; + + this._fullScreenRestore = null; + } + + // Always reset to game size + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.resetCanvas(); + } + + }, + + /** + * Called automatically when the browser enters of leaves fullscreen mode. + * + * @method Phaser.ScaleManager#fullScreenChange + * @private + * @param {Event} [event=undefined] - The fullscreenchange event + */ + fullScreenChange: function (event) { + + this.event = event; + + if (this.isFullScreen) + { + this.prepScreenMode(true); + + this.updateLayout(); + this.queueUpdate(true); + } + else + { + this.prepScreenMode(false); + + this.cleanupCreatedTarget(); + + this.updateLayout(); + this.queueUpdate(true); + } + + this.onFullScreenChange.dispatch(this, this.width, this.height); + + }, + + /** + * Called automatically when the browser fullscreen request fails; + * or called when a fullscreen request is made on a device for which it is not supported. + * + * @method Phaser.ScaleManager#fullScreenError + * @private + * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API. + */ + fullScreenError: function (event) { + + this.event = event; + + this.cleanupCreatedTarget(); + + console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API'); + + this.onFullScreenError.dispatch(this); + + }, + + /** + * Takes a Sprite or Image object and scales it to fit the given dimensions. + * Scaling happens proportionally without distortion to the sprites texture. + * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the + * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either + * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. + * + * @method Phaser.ScaleManager#scaleSprite + * @protected + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale. + * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. + * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. + * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. + * @return {Phaser.Sprite|Phaser.Image} The scaled sprite. + */ + scaleSprite: function (sprite, width, height, letterBox) { + + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + if (letterBox === undefined) { letterBox = false; } + + if (!sprite || !sprite['scale']) + { + return sprite; + } + + sprite.scale.x = 1; + sprite.scale.y = 1; + + if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0)) + { + return sprite; + } + + var scaleX1 = width; + var scaleY1 = (sprite.height * width) / sprite.width; + + var scaleX2 = (sprite.width * height) / sprite.height; + var scaleY2 = height; + + var scaleOnWidth = (scaleX2 > width); + + if (scaleOnWidth) + { + scaleOnWidth = letterBox; + } + else + { + scaleOnWidth = !letterBox; + } + + if (scaleOnWidth) + { + sprite.width = Math.floor(scaleX1); + sprite.height = Math.floor(scaleY1); + } + else + { + sprite.width = Math.floor(scaleX2); + sprite.height = Math.floor(scaleY2); + } + + // Enable at some point? + // sprite.x = Math.floor((width - sprite.width) / 2); + // sprite.y = Math.floor((height - sprite.height) / 2); + + return sprite; + + }, + + /** + * Destroys the ScaleManager and removes any event listeners. + * This should probably only be called when the game is destroyed. + * + * @method Phaser.ScaleManager#destroy + * @protected + */ + destroy: function () { + + this.game.onResume.remove(this._gameResumed, this); + + window.removeEventListener('orientationchange', this._orientationChange, false); + window.removeEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.removeEventListener('fullscreenchange', this._fullScreenChange, false); + + document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.removeEventListener('mozfullscreenerror', this._fullScreenError, false); + document.removeEventListener('MSFullscreenError', this._fullScreenError, false); + document.removeEventListener('fullscreenerror', this._fullScreenError, false); + } + + } + +}; + +Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager; + +/** +* The DOM element that is considered the Parent bounding element, if any. +* +* This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified. +* It will also be null if there is no game canvas or if the game canvas has no parent. +* +* @name Phaser.ScaleManager#boundingParent +* @property {?DOMElement} boundingParent +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", { + + get: function () { + + if (this.parentIsWindow || + (this.isFullScreen && this.hasPhaserSetFullScreen && !this._createdFullScreenTarget)) + { + return null; + } + + var parentNode = this.game.canvas && this.game.canvas.parentNode; + + return parentNode || null; + + } + +}); + +/** +* The scaling method used by the ScaleManager when not in fullscreen. +* +*
+*
{@link Phaser.ScaleManager.NO_SCALE}
+*
+* The Game display area will not be scaled - even if it is too large for the canvas/screen. +* This mode _ignores_ any applied scaling factor and displays the canvas at the Game size. +*
+*
{@link Phaser.ScaleManager.EXACT_FIT}
+*
+* The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen. +* Proportions are not maintained. +*
+*
{@link Phaser.ScaleManager.SHOW_ALL}
+*
+* Show the entire game display area while _maintaining_ the original aspect ratio. +*
+*
{@link Phaser.ScaleManager.RESIZE}
+*
+* The dimensions of the game display area are changed to match the size of the parent container. +* That is, this mode _changes the Game size_ to match the display size. +*

+* Any manually set Game size (see {@link #setGameSize}) is ignored while in effect. +*

+*
{@link Phaser.ScaleManager.USER_SCALE}
+*
+* The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}. +*

+* This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback} +* for flexible custom-sizing needs. +*

+*
+* +* @name Phaser.ScaleManager#scaleMode +* @property {integer} scaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", { + + get: function () { + + return this._scaleMode; + + }, + + set: function (value) { + + if (value !== this._scaleMode) + { + if (!this.isFullScreen) + { + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.queueUpdate(true); + } + + this._scaleMode = value; + } + + return this._scaleMode; + + } + +}); + +/** +* The scaling method used by the ScaleManager when in fullscreen. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#fullScreenScaleMode +* @property {integer} fullScreenScaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", { + + get: function () { + + return this._fullScreenScaleMode; + + }, + + set: function (value) { + + if (value !== this._fullScreenScaleMode) + { + // If in fullscreen then need a wee bit more work + if (this.isFullScreen) + { + this.prepScreenMode(false); + this._fullScreenScaleMode = value; + this.prepScreenMode(true); + + this.queueUpdate(true); + } + else + { + this._fullScreenScaleMode = value; + } + } + + return this._fullScreenScaleMode; + + } + +}); + +/** +* Returns the current scale mode - for normal or fullscreen operation. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#currentScaleMode +* @property {number} currentScaleMode +* @protected +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", { + + get: function () { + + return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode; + + } + +}); + +/** +* When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align horizontally across the page the Display canvas should be added directly to page; +* or the parent container should itself be horizontally aligned. +* +* Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignHorizontally +* @property {boolean} pageAlignHorizontally +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", { + + get: function () { + + return this._pageAlignHorizontally; + + }, + + set: function (value) { + + if (value !== this._pageAlignHorizontally) + { + this._pageAlignHorizontally = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain +* a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically +* _within_ the remaining available height dictated by the Parent element. +* +* One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. +* If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). +* +* _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height. +* To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true. +* +* Vertical alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignVertically +* @property {boolean} pageAlignVertically +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", { + + get: function () { + + return this._pageAlignVertically; + + }, + + set: function (value) { + + if (value !== this._pageAlignVertically) + { + this._pageAlignVertically = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* Returns true if the browser is in fullscreen mode, otherwise false. +* @name Phaser.ScaleManager#isFullScreen +* @property {boolean} isFullScreen +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", { + + get: function () { + return !!(document['fullscreenElement'] || + document['webkitFullscreenElement'] || + document['mozFullScreenElement'] || + document['msFullscreenElement']); + } + +}); + +/** +* Returns true if the screen orientation is in portrait mode. +* +* @name Phaser.ScaleManager#isPortrait +* @property {boolean} isPortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'portrait'; + } + +}); + +/** +* Returns true if the screen orientation is in landscape mode. +* +* @name Phaser.ScaleManager#isLandscape +* @property {boolean} isLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'landscape'; + } + +}); + +/** +* Returns true if the game dimensions are portrait (height > width). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGamePortrait +* @property {boolean} isGamePortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", { + + get: function () { + return (this.height > this.width); + } + +}); + +/** +* Returns true if the game dimensions are landscape (width > height). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGameLandscape +* @property {boolean} isGameLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", { + + get: function () { + return (this.width > this.height); + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of methods for displaying debug information about game objects. +* +* If your game is running in Canvas mode, then you should invoke all of the Debug methods from +* your games `render` function. This is because they are drawn directly onto the game canvas +* itself, so if you call any debug methods outside of `render` they are likely to be overwritten +* by the game itself. +* +* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture +* to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug +* in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! +* +* @class Phaser.Utils.Debug +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Utils.Debug = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Image} sprite - If debugging in WebGL mode, this is the Image displaying the debug {@link #bmd BitmapData}. + */ + this.sprite = null; + + /** + * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.context = null; + + /** + * @property {string} font - The font that the debug information is rendered in. + * @default + */ + this.font = '14px Courier'; + + /** + * @property {number} columnWidth - The spacing between columns. + * @default + */ + this.columnWidth = 100; + + /** + * @property {number} lineHeight - The line height between the debug text. + * @default + */ + this.lineHeight = 16; + + /** + * @property {number} lineWidth - The width of the stroke on lines and shapes. A positive number. + * @default + */ + this.lineWidth = 1; + + /** + * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. + * @default + */ + this.renderShadow = true; + + /** + * @property {string} currentColor - The color last set by {@link #start} or {@link #text}. + * @default + * @protected + */ + this.currentColor = null; + + /** + * @property {number} currentX - The current X position the debug information will be rendered at. + * @default + */ + this.currentX = 0; + + /** + * @property {number} currentY - The current Y position the debug information will be rendered at. + * @default + */ + this.currentY = 0; + + /** + * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it. + * @default + */ + this.currentAlpha = 1; + + /** + * @property {boolean} dirty - Does the canvas need re-rendering? + * @default + */ + this.dirty = false; + + /** + * @property {boolean} isDisabled - If `enableDebug: false` is passed to {@link Phaser.Game} or if Phaser is built without the Debug class, this will be true. + * @default + * @readonly + */ + this.isDisabled = false; + + /** + * @property {Phaser.Line} _line - A reusable rendering line. + * @private + */ + this._line = null; + + /** + * @property {Phaser.Rectangle} _rect - A reusable rendering rectangle. + * @private + */ + this._rect = null; + +}; + +Phaser.Utils.Debug.prototype = { + + /** + * Internal method that boots the debug displayer. + * + * @method Phaser.Utils.Debug#boot + * @protected + */ + boot: function () { + + if (this.game.renderType === Phaser.CANVAS) + { + this.context = this.game.context; + } + else + { + this.bmd = new Phaser.BitmapData(this.game, '__DEBUG', this.game.width, this.game.height, true); + this.sprite = this.game.make.image(0, 0, this.bmd); + this.game.stage.addChild(this.sprite); + + this.game.scale.onSizeChange.add(this.resize, this); + + this.canvas = Phaser.CanvasPool.create(this, this.game.width, this.game.height); + this.context = this.canvas.getContext('2d'); + } + + this._line = new Phaser.Line(); + this._rect = new Phaser.Rectangle(); + + }, + + /** + * Internal method that resizes the BitmapData and Canvas. + * Called by ScaleManager.onSizeChange only in WebGL mode. + * + * @method Phaser.Utils.Debug#resize + * @protected + */ + resize: function () { + + this.bmd.resize(this.game.width, this.game.height); + + this.canvas.width = this.game.width; + this.canvas.height = this.game.height; + + }, + + /** + * Internal method that clears the canvas (if a Sprite) ready for a new debug session. + * + * @method Phaser.Utils.Debug#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.dirty && this.sprite) + { + this.bmd.clear(); + this.bmd.draw(this.canvas, 0, 0); + + this.context.clearRect(0, 0, this.game.width, this.game.height); + this.dirty = false; + } + + }, + + /** + * Clears the Debug canvas. + * + * @method Phaser.Utils.Debug#reset + */ + reset: function () { + + if (this.context) + { + this.context.clearRect(0, 0, this.game.width, this.game.height); + } + + if (this.sprite) + { + this.bmd.clear(); + } + + }, + + /** + * Internal method that resets and starts the debug output values. + * + * @method Phaser.Utils.Debug#start + * @protected + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + * @param {number} [columnWidth=0] - The spacing between columns. + */ + start: function (x, y, color, columnWidth) { + + if (typeof x !== 'number') { x = 0; } + if (typeof y !== 'number') { y = 0; } + color = color || 'rgb(255,255,255)'; + if (columnWidth === undefined) { columnWidth = 0; } + + this.currentX = x; + this.currentY = y; + this.currentColor = color; + this.columnWidth = columnWidth; + + this.dirty = true; + + this.context.save(); + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.strokeStyle = color; + this.context.fillStyle = color; + this.context.font = this.font; + this.context.globalAlpha = this.currentAlpha; + + }, + + /** + * Internal method that stops the debug output. + * + * @method Phaser.Utils.Debug#stop + * @protected + */ + stop: function () { + + this.context.restore(); + + }, + + /** + * Internal method that outputs a single line of text split over as many columns as needed, one per parameter. + * + * @method Phaser.Utils.Debug#line + * @protected + */ + line: function () { + + var x = this.currentX; + + for (var i = 0; i < arguments.length; i++) + { + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(arguments[i], x + 1, this.currentY + 1); + this.context.fillStyle = this.currentColor; + } + + this.context.fillText(arguments[i], x, this.currentY); + + x += this.columnWidth; + } + + this.currentY += this.lineHeight; + + }, + + /** + * Render Sound Manager information, including volume, mute, audio mode, and locked status. + * + * @method Phaser.Utils.Debug#sound + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + sound: function (x, y, color) { + + var sound = this.game.sound; + + this.start(x, y, color); + + if (sound.noAudio) + { + this.line('Audio is disabled'); + } + else + { + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Mute on pause: ' + sound.muteOnPause); + this.line('Using: ' + (sound.usingWebAudio ? ('Web Audio - ' + sound.context.state) : 'Audio Tag')); + this.line('Touch locked: ' + sound.touchLocked); + } + + this.stop(); + + }, + + /** + * Render Sound information, including decoded state, duration, volume and more. + * + * @method Phaser.Utils.Debug#soundInfo + * @param {Phaser.Sound} sound - The sound object to debug. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + soundInfo: function (sound, x, y, color) { + + this.start(x, y, color); + this.line('Sound: ' + sound.key + ' Touch locked: ' + sound.game.sound.touchLocked); + this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback); + this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding); + this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying + ' Loop: ' + sound.loop); + this.line('Time: ' + sound.currentTime); + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Using: ' + (sound.usingWebAudio ? 'Web Audio' : 'Audio Tag')); + + if (sound.currentMarker !== '') + { + this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')'); + this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop); + this.line('Position: ' + sound.position); + } + + this.stop(); + + }, + + /** + * Marks the follow {@link #target} and {@link #deadzone}. + * + * @method Phaser.Utils.Debug#camera + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {string} [color] - Color of the debug shapes to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the shapes filled (default, true) or stroked (false). + */ + camera: function (camera, color, filled) { + + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + if (deadzone) + { + this._rect.setTo(view.x + deadzone.x, view.y + deadzone.y, deadzone.width, deadzone.height); + this.rectangle(this._rect, color, filled); + } + + if (target) + { + this._line.setTo(view.centerX, view.centerY, target.x, target.y); + this.geom(this._line, color, filled); + this.geom(target, color, false, 3); + } + + }, + + /** + * Render camera information including dimensions and location. + * + * @method Phaser.Utils.Debug#cameraInfo + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + cameraInfo: function (camera, x, y, color) { + + var bounds = camera.bounds; + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + this.start(x, y, color); + this.line('Camera (' + camera.width + ' x ' + camera.height + ')'); + this.line('x: ' + camera.x + ' y: ' + camera.y); + this.line('Bounds: ' + (bounds ? ('x: ' + bounds.x + ' y: ' + bounds.y + ' w: ' + bounds.width + ' h: ' + bounds.height) : 'none')); + this.line('View: x: ' + view.x + ' y: ' + view.y + ' w: ' + view.width + ' h: ' + view.height); + this.line('Deadzone: ' + (deadzone ? ('x: ' + deadzone.x + ' y: ' + deadzone.y + ' w: ' + deadzone.width + ' h: ' + deadzone.height) : deadzone)); + this.line('Total in view: ' + camera.totalInView); + this.line('At limit: x: ' + camera.atLimit.x + ' y: ' + camera.atLimit.y); + this.line('Target: ' + (target ? (target.name || target) : 'none')); + this.stop(); + + }, + + /** + * Render Timer information. + * + * @method Phaser.Utils.Debug#timer + * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + timer: function (timer, x, y, color) { + + this.start(x, y, color); + this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')'); + this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration); + this.line('Paused: ' + timer.paused + ' Length: ' + timer.length); + this.stop(); + + }, + + /** + * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text. + * + * @method Phaser.Utils.Debug#pointer + * @param {Phaser.Pointer} pointer - The Pointer you wish to display. + * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. + * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down. + * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false). + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + pointer: function (pointer, hideIfUp, downColor, upColor, color) { + + if (pointer == null) + { + return; + } + + if (hideIfUp === undefined) { hideIfUp = false; } + downColor = downColor || 'rgba(0,255,0,0.5)'; + upColor = upColor || 'rgba(255,0,0,0.5)'; + + if (hideIfUp === true && pointer.isUp === true) + { + return; + } + + this.start(pointer.x, pointer.y - 100, color); + this.context.beginPath(); + this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2); + + if (pointer.active) + { + this.context.fillStyle = downColor; + } + else + { + this.context.fillStyle = upColor; + } + + this.context.fill(); + this.context.closePath(); + + // Render the points + this.context.beginPath(); + this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y); + this.context.lineTo(pointer.position.x, pointer.position.y); + this.context.lineWidth = 2; + this.context.stroke(); + this.context.closePath(); + + // Render the text + this.line('ID: ' + pointer.id + " Active: " + pointer.active); + this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY); + this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y + " In: " + pointer.withinGame); + this.line('Duration: ' + pointer.duration + " ms"); + this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp); + this.stop(); + + }, + + /** + * Render Sprite Input Debug information. + * + * @method Phaser.Utils.Debug#spriteInputInfo + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInputInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')'); + this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1)); + this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0)); + this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0)); + this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut()); + this.stop(); + + }, + + /** + * Renders Phaser.Key object information. + * + * @method Phaser.Utils.Debug#key + * @param {Phaser.Key} key - The Key to render the information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + key: function (key, x, y, color) { + + this.start(x, y, color, 150); + + this.line('Key:', key.keyCode, 'isDown:', key.isDown); + this.line('justDown:', key.justDown, 'justUp:', key.justUp); + this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0)); + + this.stop(); + + }, + + /** + * Render debug information about the Input object. + * + * @method Phaser.Utils.Debug#inputInfo + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + inputInfo: function (x, y, color) { + + this.start(x, y, color); + this.line('Input'); + this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y); + this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY); + this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1)); + this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY); + this.stop(); + + }, + + /** + * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! + * + * @method Phaser.Utils.Debug#spriteBounds + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + spriteBounds: function (sprite, color, filled) { + + var bounds = sprite.getBounds(); + + bounds.x += this.game.camera.x; + bounds.y += this.game.camera.y; + + this.rectangle(bounds, color, filled); + + }, + + /** + * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it + * + * @method Phaser.Utils.Debug#ropeSegments + * @param {Phaser.Rope} rope - The rope to display the segments of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + ropeSegments: function (rope, color, filled) { + + var segments = rope.segments; + + var self = this; + + segments.forEach(function(segment) { + self.rectangle(segment, color, filled); + }, this); + + }, + + /** + * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. + * + * @method Phaser.Utils.Debug#spriteInfo + * @param {Phaser.Sprite} sprite - The Sprite to display the information of. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + + this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y); + this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1)); + this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1)); + this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera); + this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1)); + + this.stop(); + + }, + + /** + * Renders the sprite coordinates in local, positional and world space. + * + * @method Phaser.Utils.Debug#spriteCoords + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteCoords: function (sprite, x, y, color) { + + this.start(x, y, color, 100); + + if (sprite.name) + { + this.line(sprite.name); + } + + this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2)); + this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2)); + this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2)); + + this.stop(); + + }, + + /** + * Renders Line information in the given color. + * + * @method Phaser.Utils.Debug#lineInfo + * @param {Phaser.Line} line - The Line to display the data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + lineInfo: function (line, x, y, color) { + + this.start(x, y, color, 80); + this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2)); + this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2)); + this.line('length:', line.length.toFixed(2), 'angle:', line.angle); + this.stop(); + + }, + + /** + * Renders a single pixel at the given size. + * + * @method Phaser.Utils.Debug#pixel + * @param {number} x - X position of the pixel to be rendered. + * @param {number} y - Y position of the pixel to be rendered. + * @param {string} [color] - Color of the pixel (format is css color string). + * @param {number} [size=2] - The 'size' to render the pixel at. + */ + pixel: function (x, y, color, size) { + + size = size || 2; + + this.start(); + this.context.fillStyle = color; + this.context.fillRect(x, y, size, size); + this.stop(); + + }, + + /** + * Renders a Phaser geometry object including Rectangle, Circle, Ellipse, Point or Line. + * + * @method Phaser.Utils.Debug#geom + * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Ellipse|Phaser.Point|Phaser.Line} object - The geometry object to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) + * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle,3 = Point, 4 = Line and 5 = Ellipse. + */ + geom: function (object, color, filled, forceType) { + + if (filled === undefined) { filled = true; } + if (forceType === undefined) { forceType = 0; } + + color = color || 'rgba(0,255,0,0.4)'; + + this.start(); + + this.context.fillStyle = color; + this.context.strokeStyle = color; + this.context.lineWidth = this.lineWidth; + + if (object instanceof Phaser.Rectangle || forceType === 1) + { + if (filled) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + } + else if (object instanceof Phaser.Circle || forceType === 2) + { + this.context.beginPath(); + this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + else if (object instanceof Phaser.Point || forceType === 3) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4); + } + else if (object instanceof Phaser.Line || forceType === 4) + { + this.context.beginPath(); + this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y); + this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y); + this.context.closePath(); + this.context.stroke(); + } + else if (object instanceof Phaser.Ellipse || forceType === 5) + { + this.context.beginPath(); + this.context.ellipse(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width/2, object.height/2, 0,2 * Math.PI,false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + + this.stop(); + + }, + + /** + * Renders a Rectangle. + * + * @method Phaser.Utils.Debug#rectangle + * @param {Phaser.Rectangle|object} object - The rectangle to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as filled (default, true) or a stroked (false) + */ + rectangle: function (object, color, filled) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0, 255, 0, 0.4)'; + + this.start(); + + if (filled) + { + this.context.fillStyle = color; + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.lineWidth = this.lineWidth; + this.context.strokeStyle = color; + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + + this.stop(); + + }, + + /** + * Render a string of text. + * + * @method Phaser.Utils.Debug#text + * @param {string} text - The line of text to draw. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {string} [font] - The font of text to draw. + */ + text: function (text, x, y, color, font) { + + color = color || 'rgb(255,255,255)'; + font = font || '16px Courier'; + + this.start(); + this.context.font = font; + + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(text, x + 1, y + 1); + } + + this.context.fillStyle = color; + this.context.fillText(text, x, y); + + this.stop(); + + }, + + /** + * Visually renders a QuadTree to the display. + * + * @method Phaser.Utils.Debug#quadTree + * @param {Phaser.QuadTree} quadtree - The quadtree to render. + * @param {string} color - The color of the lines in the quadtree. + */ + quadTree: function (quadtree, color) { + + color = color || 'rgba(255,0,0,0.3)'; + + this.start(); + + var bounds = quadtree.bounds; + + if (quadtree.nodes.length === 0) + { + this.context.strokeStyle = color; + this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height); + this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier'); + + this.context.strokeStyle = 'rgb(0,255,0)'; + + for (var i = 0; i < quadtree.objects.length; i++) + { + this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height); + } + } + else + { + for (var i = 0; i < quadtree.nodes.length; i++) + { + this.quadTree(quadtree.nodes[i]); + } + } + + this.stop(); + + }, + + /** + * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. + * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. + * To display a P2 Physics body you should enable debug mode on the body when creating it. + * + * @method Phaser.Utils.Debug#body + * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false) + */ + body: function (sprite, color, filled) { + + if (sprite.body) + { + this.start(); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled, this.lineWidth); + } + else if (sprite.body.type === Phaser.Physics.NINJA) + { + Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color); + } + + this.stop(); + } + + }, + + /** + * Render a Sprites Physic Body information. + * + * @method Phaser.Utils.Debug#bodyInfo + * @param {Phaser.Sprite} sprite - The sprite to be rendered. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + bodyInfo: function (sprite, x, y, color) { + + if (sprite.body) + { + this.start(x, y, color, 210); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + this.game.physics.box2d.renderBodyInfo(this, sprite.body); + } + + this.stop(); + } + + }, + + /** + * Renders 'debug draw' data for the Box2D world if it exists. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by + * the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dWorld + */ + box2dWorld: function () { + + this.start(); + + this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0); + this.game.physics.box2d.renderDebugDraw(this.context); + + this.stop(); + + }, + + /** + * Renders 'debug draw' data for the given Box2D body. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dBody + * @param {Phaser.Physics.Box2D.Body} body - The body to be rendered. + * @param {string} [color='rgb(0,255,0)'] - Color of the rendering (format is css color string). + */ + box2dBody: function (body, color) { + + this.start(); + Phaser.Physics.Box2D.renderBody(this.context, body, color); + this.stop(); + + }, + + /** + * Call this function from the Dev Tools console. + * + * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. + * + * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) + * + * @method Phaser.Utils.Debug#displayList + * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World. + */ + displayList: function (displayObject) { + + if (displayObject === undefined) { displayObject = this.game.world; } + + if (displayObject.hasOwnProperty('renderOrderID')) + { + console.log('[' + displayObject.renderOrderID + ']', displayObject); + } + else + { + console.log('[]', displayObject); + } + + if (displayObject.children && displayObject.children.length > 0) + { + for (var i = 0; i < displayObject.children.length; i++) + { + this.game.debug.displayList(displayObject.children[i]); + } + } + + }, + + /** + * Prints a description of the {@link Phaser.Game#renderer renderer} and render session. + * + * @method Phaser.Utils.Debug#renderer + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + renderer: function (x, y, color) { + + var r = this.game.renderer; + var s = r.renderSession; + + this.start(x, y, color); + + this.line((r.gl ? 'WebGL' : 'Canvas') + ' Renderer (' + r.width + ' x ' + r.height + ')'); + this.line('autoResize: ' + r.autoResize); + this.line('clearBeforeRender: ' + r.clearBeforeRender); + this.line('resolution: ' + r.resolution); + this.line('transparent: ' + r.transparent); + this.line('renderSession:'); + + if (r.gl) + { + this.line(' currentBatchedTextures: ('+ r.currentBatchedTextures.length + ')'); + + for (var i = 0; i < r.currentBatchedTextures.length; i++) + { + this.line(' ' + r.currentBatchedTextures[i]); + } + + this.line(' drawCount: ' + s.drawCount); + this.line(' maxTextures: ' + r.maxTextures); + this.line(' maxTextureSize: ' + r.maxTextureSize); + this.line(' maxTextureAvailableSpace: ' + s.maxTextureAvailableSpace); + this.line(' roundPixels: ' + s.roundPixels); + } + else + { + this.line(' roundPixels: ' + s.roundPixels); + this.line(' scaleMode: ' + (s.scaleMode === 0 ? 'LINEAR' : (s.scaleMode === 1 ? 'NEAREST' : s.scaleMode))); + } + + this.stop(); + + }, + + canvasPool: function (x, y, color, columnWidth) { + var pool = Phaser.CanvasPool; + + this.start(x, y, color, columnWidth || 100); + this.line('Canvas Pool'); + this.line('Used:', pool.getTotal()); + this.line('Free:', pool.getFree()); + this.line('Total:', pool.length); + this.stop(); + }, + + /** + * Render each physics {@link #body} in a group. + * + * @method Phaser.Utils.Debug#physicsGroup + * @param {Phaser.Group} group - A group containing physics-enabled sprites. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false). + * @param {boolean} [checkExists=false] Render only children with `exists=true`. + */ + physicsGroup: function (group, color, filled, checkExists) { + + group.forEach(this.body, this, checkExists, color, filled); + + }, + + /** + * Prints Phaser {@link Phaser.VERSION version}, {@link Phaser.Game.#renderType rendering mode}, and {@link Phaser.Device#webAudio device audio support}. + * + * @method Phaser.Utils.Debug#phaser + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + phaser: function (x, y, color) { + + this.text('Phaser v' + Phaser.VERSION + ' ' + + (this.game.renderType === Phaser.WEBGL ? 'WebGL' : 'Canvas') + ' ' + + (this.game.device.webAudio ? 'WebAudio' : 'HTML Audio'), + x, y, color, this.font); + + }, + + /** + * Prints game/canvas dimensions and {@link Phaser.ScaleManager game scale} settings. + * + * @method Phaser.Utils.Debug#scale + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + scale: function (x, y, color) { + + this.start(x, y, color); + + var scale = this.game.scale; + var factor = scale.scaleFactorInversed; + var bounds = scale._parentBounds; + var x = ' x '; + + this.line('Game: ' + this.game.width + x + this.game.height); + this.line('Canvas: ' + scale.width + x + scale.height + + ' (' + factor.x.toFixed(2) + x + factor.y.toFixed(2) + ')' + + ' [' + scale.aspectRatio.toFixed(2) + ']'); + this.line('Mode: ' + Phaser.ScaleManager.MODES[scale.currentScaleMode] + + (scale.currentScaleMode === Phaser.ScaleManager.USER_SCALE ? + (' (' + scale._userScaleFactor.x + x + scale._userScaleFactor.y + ')') : + '')); + this.line('Parent: ' + (scale.parentIsWindow ? 'window' : scale.parentNode) + + (bounds.empty ? '' : (' (' + bounds.width + x + bounds.height + ')'))); + this.line('Screen: ' + scale.classifyOrientation(scale.screenOrientation) + + (scale.incorrectOrientation ? ' (incorrect)' : '')); + + this.stop(); + + }, + + /** + * Prints the progress of a {@link Phaser.Loader}. + * + * Typically you would call this within a {@link State#loadRender} callback and pass `game.load` ({@link Phaser.Game#load}). + * + * You can enable {@link Phaser.Loader#resetLocked} to temporarily hold the loader in its 'complete' state. + * Just remember to disable it before restarting the loader (such as when changing states). + * + * @method Phaser.Utils.Debug#loader + * @param {Phaser.Loader} loader - The loader. Usually `game.load` ({@link Phaser.Game#load}). + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + loader: function (loader, x, y, color) { + + var pad = Phaser.Utils.pad; + + this.start(x, y, color); + + if (loader.hasLoaded) + { + this.line('Complete' + (loader.resetLocked ? ' [locked]' : '')); + } + else if (loader.isLoading) + { + this.line('Loading'); + } + else + { + this.line('Not started'); + } + + if (!loader.hasLoaded || loader.resetLocked) + { + this.line('Progress: ' + (pad(loader.progress, 3) + '%')); + this.line('Files: ' + loader._loadedFileCount + ' of ' + + loader._totalFileCount); + this.line('Packs: ' + loader._loadedPackCount + ' of ' + + loader._loadedPackCount); + } + + this.stop(); + + }, + + /** + * Destroy this object. + * + * @method Phaser.Utils.Debug#destroy + */ + destroy: function () { + + Phaser.CanvasPool.remove(this); + + } + +}; + +Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DOM utility class. +* +* Provides a useful Window and Element functions as well as cross-browser compatibility buffer. +* +* Some code originally derived from {@link https://github.com/ryanve/verge verge}. +* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. +* +* @class Phaser.DOM +* @static +*/ +Phaser.DOM = { + + /** + * Get the [absolute] position of the element relative to the Document. + * + * The value may vary slightly as the page is scrolled due to rounding errors. + * + * @method Phaser.DOM.getOffset + * @param {DOMElement} element - The targeted element that we want to retrieve the offset. + * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. + * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. + */ + getOffset: function (element, point) { + + point = point || new Phaser.Point(); + + var box = element.getBoundingClientRect(); + + var scrollTop = Phaser.DOM.scrollY; + var scrollLeft = Phaser.DOM.scrollX; + var clientTop = document.documentElement.clientTop; + var clientLeft = document.documentElement.clientLeft; + + point.x = box.left + scrollLeft - clientLeft; + point.y = box.top + scrollTop - clientTop; + + return point; + + }, + + /** + * A cross-browser element.getBoundingClientRect method with optional cushion. + * + * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. + * Its properties match the native rectangle. + * The cushion parameter is an amount of pixels (+/-) to cushion the element. + * It adjusts the measurements such that it is possible to detect when an element is near the viewport. + * + * @method Phaser.DOM.getBounds + * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for. + * @param {number} [cushion] - A +/- pixel adjustment amount. + * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. + */ + getBounds: function (element, cushion) { + + if (cushion === undefined) { cushion = 0; } + + element = element && !element.nodeType ? element[0] : element; + + if (!element || element.nodeType !== 1) + { + return false; + } + else + { + return this.calibrate(element.getBoundingClientRect(), cushion); + } + + }, + + /** + * Calibrates element coordinates for `inLayoutViewport` checks. + * + * @method Phaser.DOM.calibrate + * @private + * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}` + * @param {number} [cushion] - A value to adjust the coordinates by. + * @return {object} The calibrated element coordinates + */ + calibrate: function (coords, cushion) { + + cushion = +cushion || 0; + + var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 }; + + output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion); + output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion); + + return output; + + }, + + /** + * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) + * + * @method Phaser.DOM.getAspectRatio + * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. + * @return {number} The aspect ratio. + */ + getAspectRatio: function (object) { + + object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object; + + var w = object['width']; + var h = object['height']; + + if (typeof w === 'function') + { + w = w.call(object); + } + + if (typeof h === 'function') + { + h = h.call(object); + } + + return w / h; + + }, + + /** + * Tests if the given DOM element is within the Layout viewport. + * + * The optional cushion parameter allows you to specify a distance. + * + * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. + * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. + * + * @method Phaser.DOM.inLayoutViewport + * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas. + * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport. + * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it. + */ + inLayoutViewport: function (element, cushion) { + + var r = this.getBounds(element, cushion); + + return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height; + + }, + + /** + * Returns the device screen orientation. + * + * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. + * + * Order of resolving: + * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. + * - Screen size ratio check - If fallback is 'screen', suited for desktops. + * - Viewport size ratio check - If fallback is 'viewport', suited for mobile. + * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. + * - Media query + * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..) + * + * See + * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) + * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) + * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx + * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries + * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation + * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation + * + * @method Phaser.DOM.getScreenOrientation + * @protected + * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'. + */ + getScreenOrientation: function (primaryFallback) { + + var screen = window.screen; + var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; + + if (orientation && typeof orientation.type === 'string') + { + // Screen Orientation API specification + return orientation.type; + } + else if (typeof orientation === 'string') + { + // moz/ms-orientation are strings + return orientation; + } + + var PORTRAIT = 'portrait-primary'; + var LANDSCAPE = 'landscape-primary'; + + if (primaryFallback === 'screen') + { + return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'viewport') + { + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number') + { + // This may change by device based on "natural" orientation. + return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE; + } + else if (window.matchMedia) + { + if (window.matchMedia("(orientation: portrait)").matches) + { + return PORTRAIT; + } + else if (window.matchMedia("(orientation: landscape)").matches) + { + return LANDSCAPE; + } + } + + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + + }, + + /** + * The bounds of the Visual viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one} + * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers. + * + * Supported mobile: + * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} x - Scroll, left offset - eg. "scrollX" + * @property {number} y - Scroll, top offset - eg. "scrollY" + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + visualBounds: new Phaser.Rectangle(), + + /** + * The bounds of the Layout viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two}; + * but honoring the constraints as specified applicable viewport meta-tag. + * + * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see + * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}). + * + * This is _not_ representative of the Visual bounds: in particular the non-primary axis will + * generally be significantly larger than the screen height on mobile devices when running with a + * constrained viewport. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + layoutBounds: new Phaser.Rectangle(), + + /** + * The size of the document / Layout viewport. + * + * This incorrectly reports the dimensions in IE. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Document width in pixels. + * @property {number} height - Document height in pixels. + * @readonly + */ + documentBounds: new Phaser.Rectangle() + +}; + +Phaser.Device.whenReady(function (device) { + + // All target browsers should support page[XY]Offset. + var scrollX = window && ('pageXOffset' in window) ? + function () { return window.pageXOffset; } : + function () { return document.documentElement.scrollLeft; }; + + var scrollY = window && ('pageYOffset' in window) ? + function () { return window.pageYOffset; } : + function () { return document.documentElement.scrollTop; }; + + /** + * A cross-browser window.scrollX. + * + * @name Phaser.DOM.scrollX + * @property {number} scrollX + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollX", { + get: scrollX + }); + + /** + * A cross-browser window.scrollY. + * + * @name Phaser.DOM.scrollY + * @property {number} scrollY + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollY", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "x", { + get: scrollX + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "y", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "y", { + value: 0 + }); + + var treatAsDesktop = device.desktop && + (document.documentElement.clientWidth <= window.innerWidth) && + (document.documentElement.clientHeight <= window.innerHeight); + + // Desktop browsers align the layout viewport with the visual viewport. + // This differs from mobile browsers with their zooming design. + // Ref. http://quirksmode.org/mobile/tableViewport.html + if (treatAsDesktop) + { + + // PST- When scrollbars are not included this causes upstream issues in ScaleManager. + // So reverted to the old "include scrollbars." + var clientWidth = function () { + return Math.max(window.innerWidth, document.documentElement.clientWidth); + }; + var clientHeight = function () { + return Math.max(window.innerHeight, document.documentElement.clientHeight); + }; + + // Interested in area sans-scrollbar + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: clientHeight + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + get: clientHeight + }); + + } else { + + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: function () { + return window.innerWidth; + } + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: function () { + return window.innerHeight; + } + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + + get: function () { + var a = document.documentElement.clientWidth; + var b = window.innerWidth; + + return a < b ? b : a; // max + } + + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + + get: function () { + var a = document.documentElement.clientHeight; + var b = window.innerHeight; + + return a < b ? b : a; // max + } + + }); + + } + + // For Phaser.DOM.documentBounds + // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html + + Object.defineProperty(Phaser.DOM.documentBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "y", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "width", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth); + } + + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "height", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight); + } + + }); + +}, null, true); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* ArraySet is a Set data structure (items must be unique within the set) that also maintains order. +* This allows specific items to be easily added or removed from the Set. +* +* Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. +* +* This used primarily by the Input subsystem. +* +* @class Phaser.ArraySet +* @constructor +* @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet. +*/ +Phaser.ArraySet = function (list) { + + /** + * Current cursor position as established by `first` and `next`. + * @property {integer} position + * @default + */ + this.position = 0; + + /** + * The backing array. + * @property {any[]} list + */ + this.list = list || []; + +}; + +Phaser.ArraySet.prototype = { + + /** + * Adds a new element to the end of the list. + * If the item already exists in the list it is not moved. + * + * @method Phaser.ArraySet#add + * @param {any} item - The element to add to this list. + * @return {any} The item that was added. + */ + add: function (item) { + + if (!this.exists(item)) + { + this.list.push(item); + } + + return item; + + }, + + /** + * Gets the index of the item in the list, or -1 if it isn't in the list. + * + * @method Phaser.ArraySet#getIndex + * @param {any} item - The element to get the list index for. + * @return {integer} The index of the item or -1 if not found. + */ + getIndex: function (item) { + + return this.list.indexOf(item); + + }, + + /** + * Gets an item from the set based on the property strictly equaling the value given. + * Returns null if not found. + * + * @method Phaser.ArraySet#getByKey + * @param {string} property - The property to check against the value. + * @param {any} value - The value to check if the property strictly equals. + * @return {any} The item that was found, or null if nothing matched. + */ + getByKey: function (property, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i][property] === value) + { + return this.list[i]; + } + } + + return null; + + }, + + /** + * Checks for the item within this list. + * + * @method Phaser.ArraySet#exists + * @param {any} item - The element to get the list index for. + * @return {boolean} True if the item is found in the list, otherwise false. + */ + exists: function (item) { + + return (this.list.indexOf(item) > -1); + + }, + + /** + * Removes all the items. + * + * @method Phaser.ArraySet#reset + */ + reset: function () { + + this.list.length = 0; + + }, + + /** + * Removes the given element from this list if it exists. + * + * @method Phaser.ArraySet#remove + * @param {any} item - The item to be removed from the list. + * @return {any} item - The item that was removed. + */ + remove: function (item) { + + var idx = this.list.indexOf(item); + + if (idx > -1) + { + this.list.splice(idx, 1); + return item; + } + + }, + + /** + * Sets the property `key` to the given value on all members of this list. + * + * @method Phaser.ArraySet#setAll + * @param {any} key - The property of the item to set. + * @param {any} value - The value to set the property to. + */ + setAll: function (key, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + this.list[i][key] = value; + } + } + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * + * If the `key` property is present it must be a function. + * The function is invoked using the item as the context. + * + * @method Phaser.ArraySet#callAll + * @param {string} key - The name of the property with the function to call. + * @param {...*} parameter - Additional parameters that will be passed to the callback. + */ + callAll: function (key) { + + var args = Array.prototype.slice.call(arguments, 1); + + var i = this.list.length; + + while (i--) + { + if (this.list[i] && this.list[i][key]) + { + this.list[i][key].apply(this.list[i], args); + } + } + + }, + + /** + * Removes every member from this ArraySet and optionally destroys it. + * + * @method Phaser.ArraySet#removeAll + * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set. + */ + removeAll: function (destroy) { + + if (destroy === undefined) { destroy = false; } + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + var item = this.remove(this.list[i]); + + if (destroy) + { + item.destroy(); + } + } + } + + this.position = 0; + this.list = []; + + } + +}; + +/** +* Number of items in the ArraySet. Same as `list.length`. +* +* @name Phaser.ArraySet#total +* @property {integer} total +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "total", { + + get: function () { + return this.list.length; + } + +}); + +/** +* Returns the first item and resets the cursor to the start. +* +* @name Phaser.ArraySet#first +* @property {any} first +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "first", { + + get: function () { + + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + + } + +}); + +/** +* Returns the the next item (based on the cursor) and advances the cursor. +* +* @name Phaser.ArraySet#next +* @property {any} next +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "next", { + + get: function () { + + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + + } + +}); + +Phaser.ArraySet.prototype.constructor = Phaser.ArraySet; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Utility functions for dealing with Arrays. +* +* @class Phaser.ArrayUtils +* @static +*/ +Phaser.ArrayUtils = { + + /** + * Fetch a random entry from the given array. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.getRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was selected. + */ + getRandomItem: function (objects, startIndex, length) { + + if (objects === null) { return null; } + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + + return objects[randomIndex] === undefined ? null : objects[randomIndex]; + + }, + + /** + * Removes a random object from the given array and returns it. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.removeRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was removed. + */ + removeRandomItem: function (objects, startIndex, length) { + + if (objects == null) { // undefined or null + return null; + } + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + if (randomIndex < objects.length) + { + var removed = objects.splice(randomIndex, 1); + return removed[0] === undefined ? null : removed[0]; + } + else + { + return null; + } + + }, + + /** + * Remove one or more items at the given index and reorder the array. + * + * The new array length will be `array.length - count`. + * + * This is an alternative to `array.splice(startIndex, count)`. + * + * @see https://github.com/mreinstein/remove-array-items + * @see https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ + * + * @method Phaser.ArrayUtils.remove + * @param {any[]} array + * @param {integer} startIndex + * @param {integer} [count=1] + * @return {any[]} The modified array. + */ + remove: function (array, startIndex, count) + { + var length = array.length; + + if (startIndex >= length || count === 0) { return; } + + if (count == null) { count = 1; } + + var newLength = length - count; + + for (var i = startIndex; i < newLength; ++i) + { + array[i] = array[i + count]; + } + + array.length = newLength; + }, + + /** + * A standard Fisher-Yates Array shuffle implementation which modifies the array in place. + * + * @method Phaser.ArrayUtils.shuffle + * @param {any[]} array - The array to shuffle. + * @return {any[]} The original array, now shuffled. + */ + shuffle: function (array) { + + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; + + }, + + /** + * Transposes the elements of the given matrix (array of arrays). + * + * @method Phaser.ArrayUtils.transposeMatrix + * @param {Array} array - The matrix to transpose. + * @return {Array} A new transposed matrix + */ + transposeMatrix: function (array) { + + var sourceRowCount = array.length; + var sourceColCount = array[0].length; + + var result = new Array(sourceColCount); + + for (var i = 0; i < sourceColCount; i++) + { + result[i] = new Array(sourceRowCount); + + for (var j = sourceRowCount - 1; j > -1; j--) + { + result[i][j] = array[j][i]; + } + } + + return result; + + }, + + /** + * Rotates the given matrix (array of arrays). + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @method Phaser.ArrayUtils.rotateMatrix + * @param {Array} matrix - The array to rotate; this matrix _may_ be altered. + * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). + * @return {Array} The rotated matrix. The source matrix should be discarded for the returned matrix. + */ + rotateMatrix: function (matrix, direction) { + + if (typeof direction !== 'string') + { + direction = ((direction % 360) + 360) % 360; + } + + if (direction === 90 || direction === -270 || direction === 'rotateLeft') + { + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + matrix = matrix.reverse(); + } + else if (direction === -90 || direction === 270 || direction === 'rotateRight') + { + matrix = matrix.reverse(); + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + } + else if (Math.abs(direction) === 180 || direction === 'rotate180') + { + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + matrix = matrix.reverse(); + } + + return matrix; + + }, + + /** + * Snaps a value to the nearest value in a sorted numeric array. + * The result will always be in the range `[first_value, last_value]`. + * + * @method Phaser.ArrayUtils.findClosest + * @param {number} value - The search value + * @param {number[]} arr - The input array which _must_ be sorted. + * @return {number} The nearest value found. + */ + findClosest: function (value, arr) { + + if (!arr.length) + { + return NaN; + } + else if (arr.length === 1 || value < arr[0]) + { + return arr[0]; + } + + var i = 1; + while (arr[i] < value) { + i++; + } + + var low = arr[i - 1]; + var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; + + return ((high - value) <= (value - low)) ? high : low; + + }, + + /** + * Moves the element from the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ F, A, B, C, D, E ]` + * + * See also Phaser.ArrayUtils.rotateLeft. + * + * @method Phaser.ArrayUtils.rotateRight + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The shifted value. + */ + rotateRight: function (array) { + + var s = array.pop(); + array.unshift(s); + + return s; + + }, + + /** + * Moves the element from the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ B, C, D, E, F, A ]` + * + * See also Phaser.ArrayUtils.rotateRight + * + * @method Phaser.ArrayUtils.rotateLeft + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The rotated value. + */ + rotateLeft: function (array) { + + var s = array.shift(); + array.push(s); + + return s; + + }, + + /** + * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]` (or `[0, start]`, if `end` is omitted). + * This is equivalent to `numberArrayStep(start, 1 + end, 1)`. + * + * When exactly one argument is passed, it's used as `end` and 0 is used as `start`. The length of the result is (1 + end). + * + * ##### Examples + * + * ```javascript + * numberArray(3); // -> [0, 1, 2, 3] + * numberArray(0, 3); // -> [0, 1, 2, 3] + * numberArray(1, 3); // -> [1, 2, 3] + * ``` + * + * @method Phaser.ArrayUtils.numberArray + * @param {number} start - The minimum value the array starts with. + * @param {number} [end] - The maximum value the array contains. + * @return {number[]} The array of number values. + */ + numberArray: function (start, end) { + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + var result = []; + + for (var i = start; i <= end; i++) + { + result.push(i); + } + + return result; + + }, + + /** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @method Phaser.ArrayUtils.numberArrayStep + * @param {number} start - The start of the range. + * @param {number} [end] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * @returns {Array} Returns the new array of numbers. + * @example + * Phaser.ArrayUtils.numberArrayStep(4); + * // => [0, 1, 2, 3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * Phaser.ArrayUtils.numberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * Phaser.ArrayUtils.numberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * Phaser.ArrayUtils.numberArrayStep(0); + * // => [] + */ + numberArrayStep: function (start, end, step) { + + if (start === undefined || start === null) { start = 0; } + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + if (step === undefined) { step = 1; } + + var result = []; + var total = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0); + + for (var i = 0; i < total; i++) + { + result.push(start); + start += step; + } + + return result; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A basic Linked List data structure. +* +* This implementation _modifies_ the `prev` and `next` properties of each item added: +* - The `prev` and `next` properties must be writable and should not be used for any other purpose. +* - Items _cannot_ be added to multiple LinkedLists at the same time. +* - Only objects can be added. +* +* @class Phaser.LinkedList +* @constructor +*/ +Phaser.LinkedList = function () { + + /** + * Next element in the list. + * @property {object} next + * @default + */ + this.next = null; + + /** + * Previous element in the list. + * @property {object} prev + * @default + */ + this.prev = null; + + /** + * First element in the list. + * @property {object} first + * @default + */ + this.first = null; + + /** + * Last element in the list. + * @property {object} last + * @default + */ + this.last = null; + + /** + * Number of elements in the list. + * @property {integer} total + * @default + */ + this.total = 0; + +}; + +Phaser.LinkedList.prototype = { + + /** + * Adds a new element to this linked list. + * + * @method Phaser.LinkedList#add + * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. + * @return {object} The item that was added. + */ + add: function (item) { + + // If the list is empty + if (this.total === 0 && this.first === null && this.last === null) + { + this.first = item; + this.last = item; + this.next = item; + item.prev = this; + this.total++; + return item; + } + + // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list) + this.last.next = item; + + item.prev = this.last; + + this.last = item; + + this.total++; + + return item; + + }, + + /** + * Resets the first, last, next and previous node pointers in this list. + * + * @method Phaser.LinkedList#reset + */ + reset: function () { + + this.first = null; + this.last = null; + this.next = null; + this.prev = null; + this.total = 0; + + }, + + /** + * Removes the given element from this linked list if it exists. + * + * @method Phaser.LinkedList#remove + * @param {object} item - The item to be removed from the list. + */ + remove: function (item) { + + if (this.total === 1) + { + this.reset(); + item.next = item.prev = null; + return; + } + + if (item === this.first) + { + // It was 'first', make 'first' point to first.next + this.first = this.first.next; + } + else if (item === this.last) + { + // It was 'last', make 'last' point to last.prev + this.last = this.last.prev; + } + + if (item.prev) + { + // make item.prev.next point to childs.next instead of item + item.prev.next = item.next; + } + + if (item.next) + { + // make item.next.prev point to item.prev instead of item + item.next.prev = item.prev; + } + + item.next = item.prev = null; + + if (this.first === null ) + { + this.last = null; + } + + this.total--; + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * The function must exist on the member. + * + * @method Phaser.LinkedList#callAll + * @param {function} callback - The function to call. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content +* quickly and easily, without the need for any external files. You can create textures for sprites and in +* coming releases we'll add dynamic sound effect generation support as well (like sfxr). +* +* Access this via `Game.create` (`this.game.create` from within a State object). +* +* @class Phaser.Create +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Create = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.ctx = null; + + /** + * @property {array} palettes - A range of 16 color palettes for use with sprite generation. + */ + this.palettes = [ + { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' }, + { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' }, + { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' } + ]; + +}; + +/** +* A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_ARNE = 0; + +/** +* A 16 color JMP inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JMP = 1; + +/** +* A 16 color CGA inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_CGA = 2; + +/** +* A 16 color C64 inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_C64 = 3; + +/** +* A 16 color palette inspired by Japanese computers like the MSX. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JAPANESE_MACHINE = 4; + +Phaser.Create.prototype = { + + /** + * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite. + * + * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images + * rather than Phaser.Graphics objects, which are expensive to render and limited in scope. + * + * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts. + * + * For example: + * + * `var data = [ + * ' 333 ', + * ' 777 ', + * 'E333E', + * ' 333 ', + * ' 3 3 ' + * ];` + * + * `game.create.texture('bob', data);` + * + * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it + * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');` + * + * Use {@link Phaser.Loader#imageFromTexture} to preload an image of the same. + * + * @method Phaser.Create#texture + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {array} data - An array of pixel data. + * @param {integer} [pixelWidth=8] - The width of each pixel. + * @param {integer} [pixelHeight=8] - The height of each pixel. + * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + texture: function (key, data, pixelWidth, pixelHeight, palette, generateTexture, callback, callbackContext) { + + if (pixelWidth === undefined) { pixelWidth = 8; } + if (pixelHeight === undefined) { pixelHeight = pixelWidth; } + if (palette === undefined) { palette = 0; } + if (generateTexture === undefined) { generateTexture = true; } + + var w = data[0].length * pixelWidth; + var h = data.length * pixelHeight; + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(w, h); + this.bmd.clear(); + + // Draw it + for (var y = 0; y < data.length; y++) + { + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var d = row[x]; + + if (d !== '.' && d !== ' ') + { + this.ctx.fillStyle = this.palettes[palette][d]; + this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); + } + } + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Creates a grid texture based on the given dimensions. + * + * Use {@link Phaser.Loader#imageFromGrid} to preload an image of the same. + * + * @method Phaser.Create#grid + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {integer} width - The width of the grid in pixels. + * @param {integer} height - The height of the grid in pixels. + * @param {integer} cellWidth - The width of the grid cells in pixels. + * @param {integer} cellHeight - The height of the grid cells in pixels. + * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + grid: function (key, width, height, cellWidth, cellHeight, color, generateTexture, callback, callbackContext) { + + if (generateTexture === undefined) { generateTexture = true; } + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(width, height); + + this.ctx.fillStyle = color; + + for (var y = 0; y < height; y += cellHeight) + { + this.ctx.fillRect(0, y, width, 1); + } + + for (var x = 0; x < width; x += cellWidth) + { + this.ctx.fillRect(x, 0, 1, height); + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Copies the contents of {@link bmd Create's canvas} to the given BitmapData object, or a new BitmapData object. + * + * @param {Phaser.BitmapData} [dest] - The BitmapData receiving the copied image. + * @param {number} [x=0] - The x coordinate to translate to before drawing. + * @param {number} [y=0] - The y coordinate to translate to before drawing. + * @param {number} [width] - The new width of the Sprite being copied. + * @param {number} [height] - The new height of the Sprite being copied. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} - The `dest` argument (if passed), or a new BitmapData object + */ + copy: function (dest, x, y, width, height, blendMode, roundPx) { + + if (dest == null) { dest = this.game.make.bitmapData(); } + + dest.resize(this.bmd.width, this.bmd.height); + + return dest.draw(this.bmd, x, y, width, height, blendMode, roundPx); + + } + +}; + +Phaser.Create.prototype.constructor = Phaser.Create; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers +* to provide for game object positioning in a responsive manner. +* +* @class Phaser.FlexGrid +* @constructor +* @param {Phaser.ScaleManager} manager - The ScaleManager. +* @param {number} width - The width of the game. +* @param {number} height - The height of the game. +*/ +Phaser.FlexGrid = function (manager, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = manager.game; + + /** + * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager. + */ + this.manager = manager; + + // The perfect dimensions on which everything else is based + this.width = width; + this.height = height; + + this.boundsCustom = new Phaser.Rectangle(0, 0, width, height); + this.boundsFluid = new Phaser.Rectangle(0, 0, width, height); + this.boundsFull = new Phaser.Rectangle(0, 0, width, height); + this.boundsNone = new Phaser.Rectangle(0, 0, width, height); + + /** + * @property {Phaser.Point} position - + * @readonly + */ + this.positionCustom = new Phaser.Point(0, 0); + this.positionFluid = new Phaser.Point(0, 0); + this.positionFull = new Phaser.Point(0, 0); + this.positionNone = new Phaser.Point(0, 0); + + /** + * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. + * @readonly + */ + this.scaleCustom = new Phaser.Point(1, 1); + this.scaleFluid = new Phaser.Point(1, 1); + this.scaleFluidInversed = new Phaser.Point(1, 1); + this.scaleFull = new Phaser.Point(1, 1); + this.scaleNone = new Phaser.Point(1, 1); + + this.customWidth = 0; + this.customHeight = 0; + this.customOffsetX = 0; + this.customOffsetY = 0; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.multiplier = 0; + + this.layers = []; + +}; + +Phaser.FlexGrid.prototype = { + + /** + * Sets the core game size. This resets the w/h parameters and bounds. + * + * @method Phaser.FlexGrid#setSize + * @param {number} width - The new dimensions. + * @param {number} height - The new dimensions. + */ + setSize: function (width, height) { + + // These are locked and don't change until setSize is called again + this.width = width; + this.height = height; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.scaleNone = new Phaser.Point(1, 1); + + this.boundsNone.width = this.width; + this.boundsNone.height = this.height; + + this.refresh(); + + }, + + // Need ability to create your own layers with custom scaling, etc. + + /** + * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createCustomLayer + * @param {number} width - Width of this layer in pixels. + * @param {number} height - Height of this layer in pixels. + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createCustomLayer: function (width, height, children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + this.customWidth = width; + this.customHeight = height; + + this.boundsCustom.width = width; + this.boundsCustom.height = height; + + var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createFluidLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFluidLayer: function (children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios. + * + * @method Phaser.FlexGrid#createFullLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFullLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled. + * + * @method Phaser.FlexGrid#createFixedLayer + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFixedLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * Resets the layer children references + * + * @method Phaser.FlexGrid#reset + */ + reset: function () { + + var i = this.layers.length; + + while (i--) + { + if (!this.layers[i].persist) + { + // Remove references to this class + this.layers[i].position = null; + this.layers[i].scale = null; + this.layers.slice(i, 1); + } + } + + }, + + /** + * Called when the game container changes dimensions. + * + * @method Phaser.FlexGrid#onResize + * @param {number} width - The new width of the game container. + * @param {number} height - The new height of the game container. + */ + onResize: function (width, height) { + + this.ratioH = width / height; + this.ratioV = height / width; + + this.refresh(width, height); + + }, + + /** + * Updates all internal vars such as the bounds and scale values. + * + * @method Phaser.FlexGrid#refresh + */ + refresh: function () { + + this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width)); + + this.boundsFluid.width = Math.round(this.width * this.multiplier); + this.boundsFluid.height = Math.round(this.height * this.multiplier); + + this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height); + this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height); + + this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height); + + this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x); + this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y); + + this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + + this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y); + this.positionNone.set(this.boundsNone.x, this.boundsNone.y); + + }, + + /** + * Fits a sprites width to the bounds. + * + * @method Phaser.FlexGrid#fitSprite + * @param {Phaser.Sprite} sprite - The Sprite to fit. + */ + fitSprite: function (sprite) { + + this.manager.scaleSprite(sprite); + + sprite.x = this.manager.bounds.centerX; + sprite.y = this.manager.bounds.centerY; + + }, + + /** + * Call in the render function to output the bounds rects. + * + * @method Phaser.FlexGrid#debug + */ + debug: function () { + + // for (var i = 0; i < this.layers.length; i++) + // { + // this.layers[i].debug(); + // } + + // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16); + // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false); + + this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16); + this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false); + + // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16); + // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false); + + // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16); + // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false); + + } + +}; + +Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* A responsive grid layer. +* +* @class Phaser.FlexLayer +* @extends Phaser.Group +* @constructor +* @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer. +* @param {Phaser.Point} position - A reference to the Point object used for positioning. +* @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds. +* @param {Phaser.Point} scale - A reference to the Point object used for layer scaling. +*/ +Phaser.FlexLayer = function (manager, position, bounds, scale) { + + Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false); + + /** + * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager. + */ + this.manager = manager.manager; + + /** + * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer. + */ + this.grid = manager; + + /** + * Should the FlexLayer remain through a State swap? + * + * @type {boolean} + */ + this.persist = false; + + /** + * @property {Phaser.Point} position + */ + this.position = position; + + /** + * @property {Phaser.Rectangle} bounds + */ + this.bounds = bounds; + + /** + * @property {Phaser.Point} scale + */ + this.scale = scale; + + /** + * @property {Phaser.Point} topLeft + */ + this.topLeft = bounds.topLeft; + + /** + * @property {Phaser.Point} topMiddle + */ + this.topMiddle = new Phaser.Point(bounds.halfWidth, 0); + + /** + * @property {Phaser.Point} topRight + */ + this.topRight = bounds.topRight; + + /** + * @property {Phaser.Point} bottomLeft + */ + this.bottomLeft = bounds.bottomLeft; + + /** + * @property {Phaser.Point} bottomMiddle + */ + this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom); + + /** + * @property {Phaser.Point} bottomRight + */ + this.bottomRight = bounds.bottomRight; + +}; + +Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype); +Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer; + +/** + * Resize. + * + * @method Phaser.FlexLayer#resize + */ +Phaser.FlexLayer.prototype.resize = function () { +}; + +/** + * Debug. + * + * @method Phaser.FlexLayer#debug + */ +Phaser.FlexLayer.prototype.debug = function () { + + this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16); + this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false); + + this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9'); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. +* +* @class Phaser.Color +*/ +Phaser.Color = { + + /** + * Red (0xff0000) + * + * @type number + * @constant + * @default + */ + RED: 0xff0000, + + /** + * Orange (0xff9900) + * + * @type number + * @constant + * @default + */ + ORANGE: 0xff9900, + + /** + * Yellow (0xffff00) + * + * @type number + * @constant + * @default + */ + YELLOW: 0xffff00, + + /** + * Green (0x00ff00) + * + * @type number + * @constant + * @default + */ + GREEN: 0x00ff00, + + /** + * Aqua (0x00ffff) + * + * @type number + * @constant + * @default + */ + AQUA: 0x00ffff, + + /** + * Blue (0x0000ff) + * + * @type number + * @constant + * @default + */ + BLUE: 0x0000ff, + + /** + * Violet/purple (0xff00ff) + * + * @type number + * @constant + * @default + */ + VIOLET: 0xff00ff, + + /** + * White (0xffffff) + * + * @type number + * @constant + * @default + */ + WHITE: 0xffffff, + + /** + * Black (0x000000) + * + * @type number + * @constant + * @default + */ + BLACK: 0, + + /** + * Gray (0x666666) + * + * @type number + * @constant + * @default + */ + GRAY: 0x666666, + + /** + * Packs the r, g, b, a components into a single integer, for use with Int32Array. + * If device is little endian then ABGR order is used. Otherwise RGBA order is used. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.packPixel + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} The packed color as uint32 + */ + packPixel: function (r, g, b, a) { + + if (Phaser.Device.LITTLE_ENDIAN) + { + return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0; + } + else + { + return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0; + } + + }, + + /** + * Unpacks the r, g, b, a components into the specified color object, or a new + * object, for use with Int32Array. If little endian, then ABGR order is used when + * unpacking, otherwise, RGBA order is used. The resulting color object has the + * `r, g, b, a` properties which are unrelated to endianness. + * + * Note that the integer is assumed to be packed in the correct endianness. On little-endian + * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a + * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.unpackPixel + * @static + * @param {number} rgba - The integer, packed in endian order by packPixel. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + unpackPixel: function (rgba, out, hsl, hsv) { + + if (out === undefined || out === null) { out = Phaser.Color.createColor(); } + if (hsl === undefined || hsl === null) { hsl = false; } + if (hsv === undefined || hsv === null) { hsv = false; } + + if (Phaser.Device.LITTLE_ENDIAN) + { + out.a = ((rgba & 0xff000000) >>> 24); + out.b = ((rgba & 0x00ff0000) >>> 16); + out.g = ((rgba & 0x0000ff00) >>> 8); + out.r = ((rgba & 0x000000ff)); + } + else + { + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + } + + 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; + + }, + + /** + * A utility to convert an integer in 0xRRGGBBAA format to a color object. + * This does not rely on endianness. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.fromRGBA + * @static + * @param {number} rgba - An RGBA hex + * @param {object} [out] - The object to use, optional. + * @return {object} A color object. + */ + fromRGBA: function (rgba, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + + out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')'; + + return out; + + }, + + /** + * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.toRGBA + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toRGBA: function (r, g, b, a) { + + return (r << 24) | (g << 16) | (b << 8) | a; + + }, + + /** + * Converts RGBA components to a 32 bit integer in AABBGGRR format. + * + * @method Phaser.Color.toABGR + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toABGR: function (r, g, b, a) { + + return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; + + }, + + /** + * Converts a hex color value to an [R, G, B] array. + * + * @static + * @method Phaser.Color.hexToRGBArray + * @param {number} color - The color to convert to an RGB array. In the format 0xRRGGBB. + * @return {array} An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + */ + hexToRGBArray: function (color) { + + return [ + (color >> 16 & 0xFF) / 255, + (color >> 8 & 0xFF) / 255, + (color & 0xFF) / 255 + ]; + + }, + + /** + * Converts an RGB color array, in the format: [R, G, B], to a hex color value. + * + * @static + * @method Phaser.Color.RGBArrayToHex + * @param {array} rgb - An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + * @return {number} The color value, in the format 0xRRGGBB. + */ + RGBArrayToHex: function (rgb) { + + return ((rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255); + + }, + + /** + * Converts an RGB color value to HSL (hue, saturation and lightness). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSL + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. + */ + 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); + + // achromatic by default + out.h = 0; + out.s = 0; + out.l = (max + min) / 2; + + if (max !== min) + { + var d = max - min; + + out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min); + + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSL (hue, saturation and lightness) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSLtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} l - The lightness, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSLtoRGB: function (h, s, l, out) { + + if (!out) + { + out = Phaser.Color.createColor(l, l, l); + } + else + { + // achromatic by default + out.r = l; + out.g = l; + out.b = l; + } + + if (s !== 0) + { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3); + out.g = Phaser.Color.hueToColor(p, q, h); + out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3); + } + + // out.r = (out.r * 255 | 0); + // out.g = (out.g * 255 | 0); + // out.b = (out.b * 255 | 0); + + out.r = Math.floor((out.r * 255 | 0)); + out.g = Math.floor((out.g * 255 | 0)); + out.b = Math.floor((out.b * 255 | 0)); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts an RGB color value to HSV (hue, saturation and value). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSV + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and value set in the h, s and v properties. + */ + RGBtoHSV: function (r, g, b, out) { + + if (!out) + { + out = Phaser.Color.createColor(r, g, b, 255); + } + + r /= 255; + g /= 255; + b /= 255; + + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var d = max - min; + + // achromatic by default + out.h = 0; + out.s = max === 0 ? 0 : d / max; + out.v = max; + + if (max !== min) + { + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSVtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} v - The value, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSVtoRGB: function (h, s, v, out) { + + if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); } + + var r, g, b; + var i = Math.floor(h * 6); + var f = h * 6 - i; + var p = v * (1 - s); + var q = v * (1 - f * s); + var t = v * (1 - (1 - f) * s); + + switch (i % 6) + { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } + + out.r = Math.floor(r * 255); + out.g = Math.floor(g * 255); + out.b = Math.floor(b * 255); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.hueToColor + * @static + * @param {number} p + * @param {number} q + * @param {number} t + * @return {number} The color component value. + */ + hueToColor: function (p, q, t) { + + if (t < 0) + { + t += 1; + } + + if (t > 1) + { + t -= 1; + } + + if (t < 1 / 6) + { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) + { + return q; + } + + if (t < 2 / 3) + { + return p + (q - p) * (2 / 3 - t) * 6; + } + + return p; + + }, + + /** + * A utility function to create a lightweight 'color' object with the default components. + * Any components that are not specified will default to zero. + * + * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.createColor + * @static + * @param {number} [r=0] - The red color component, in the range 0 - 255. + * @param {number} [g=0] - The green color component, in the range 0 - 255. + * @param {number} [b=0] - The blue color component, in the range 0 - 255. + * @param {number} [a=1] - The alpha color component, in the range 0 - 1. + * @param {number} [h=0] - The hue, in the range 0 - 1. + * @param {number} [s=0] - The saturation, in the range 0 - 1. + * @param {number} [l=0] - The lightness, in the range 0 - 1. + * @param {number} [v=0] - The value, in the range 0 - 1. + * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. + */ + 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, color32: 0, rgba: '' }; + + return Phaser.Color.updateColor(out); + + }, + + /** + * Takes a color object and updates the rgba, color and color32 properties. + * + * @method Phaser.Color.updateColor + * @static + * @param {object} out - The color object to update. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + updateColor: function (out) { + + out.rgba = 'rgba(' + out.r.toFixed() + ',' + out.g.toFixed() + ',' + out.b.toFixed() + ',' + out.a.toString() + ')'; + out.color = Phaser.Color.getColor(out.r, out.g, out.b); + out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b); + + return out; + + }, + + /** + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor32 + * @static + * @param {number} a - The alpha color component, in the range 0 - 255. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + getColor32: function (a, r, g, b) { + + return a << 24 | r << 16 | g << 8 | b; + + }, + + /** + * Given 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xRRGGBB). + */ + getColor: function (r, g, b) { + + return r << 16 | g << 8 | b; + + }, + + /** + * Converts the given color values into a string. + * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + * + * @method Phaser.Color.RGBtoString + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255. + * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. + * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + */ + RGBtoString: function (r, g, b, a, prefix) { + + if (a === undefined) { a = 255; } + if (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); + } + + }, + + /** + * Converts a hex string into an integer color value. + * + * @method Phaser.Color.hexToRGB + * @static + * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. + * @return {number} The rgb color value in the format 0xAARRGGBB. + */ + hexToRGB: function (hex) { + + var rgb = Phaser.Color.hexToColor(hex); + + if (rgb) + { + return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b); + } + + }, + + /** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @method Phaser.Color.hexToColor + * @static + * @param {string} hex - The color string in a hex format. + * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + hexToColor: function (hex, out) { + + // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") + hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { + return r + r + g + g + b + b; + }); + + var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + + if (result) + { + var r = parseInt(result[1], 16); + var g = parseInt(result[2], 16); + var b = parseInt(result[3], 16); + + if (!out) + { + out = Phaser.Color.createColor(r, g, b); + } + else + { + out.r = r; + out.g = g; + out.b = b; + } + } + + return out; + + }, + + /** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @method Phaser.Color.webToColor + * @static + * @param {string} web - The color string in CSS 'web' format. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + webToColor: function (web, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web); + + if (result) + { + out.r = ~~Number(result[1]); + out.g = ~~Number(result[2]); + out.b = ~~Number(result[3]); + out.a = result[4] !== undefined ? Number(result[4]) : 1; + Phaser.Color.updateColor(out); + } + + return out; + + }, + + /** + * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. + * + * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). + * + * An alpha channel is _not_ supported when specifying a hex string. + * + * @method Phaser.Color.valueToColor + * @static + * @param {string|number} value - The color expressed as a recognized string format or a packed integer. + * @param {object} [out] - The object to use for the output. If not provided a new object will be created. + * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. + */ + valueToColor: function (value, out) { + + // The behavior is not consistent between hexToColor/webToColor on invalid input. + // This unifies both by returning a new object, but returning null may be better. + if (!out) + { + out = Phaser.Color.createColor(); + } + + if (typeof value === 'string') + { + if (value.indexOf('rgb') === 0) + { + return Phaser.Color.webToColor(value, out); + } + else + { + // `hexToColor` does not support alpha; match `createColor`. + out.a = 1; + return Phaser.Color.hexToColor(value, out); + } + } + else if (typeof value === 'number') + { + // `getRGB` does not take optional object to modify; + // alpha is also adjusted to match `createColor`. + var tempColor = Phaser.Color.getRGB(value); + out.r = tempColor.r; + out.g = tempColor.g; + out.b = tempColor.b; + out.a = tempColor.a / 255; + return out; + } + else + { + return out; + } + + }, + + /** + * Return a string containing a hex representation of the given color component. + * + * @method Phaser.Color.componentToHex + * @static + * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. + * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ + componentToHex: function (color) { + + var hex = color.toString(16); + + return (hex.length === 1) ? '0' + hex : hex; + + }, + + /** + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSVColorWheel + * @static + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSV color wheel. + */ + HSVColorWheel: function (s, v) { + + if (s === undefined) { s = 1.0; } + if (v === undefined) { v = 1.0; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v)); + } + + return colors; + + }, + + /** + * Get HSL color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSLColorWheel + * @static + * @param {number} [s=0.5] - The saturation, in the range 0 - 1. + * @param {number} [l=0.5] - The lightness, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSL color wheel. + */ + HSLColorWheel: function (s, l) { + + if (s === undefined) { s = 0.5; } + if (l === undefined) { l = 0.5; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l)); + } + + return colors; + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColor + * @static + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @param {number} [alpha] - The alpha of the returned color. + * @param {number} [colorSpace=0] - The color space to interpolate in. 0 = RGB, 1 = HSV. + * @returns {number} The interpolated color value. + */ + interpolateColor: function (color1, color2, steps, currentStep, alpha, colorSpace) { + + if (alpha === undefined) { alpha = 255; } + if (colorSpace === undefined) { colorSpace = 0; } + + var src1 = Phaser.Color.getRGB(color1); + var src2 = Phaser.Color.getRGB(color2); + + if (colorSpace === 0) + { + 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; + } + + if (colorSpace === 1) + { + var hsv1 = Phaser.Color.RGBtoHSV(src1.r, src1.g, src1.b); + var hsv2 = Phaser.Color.RGBtoHSV(src2.r, src2.g, src2.b); + var dh = hsv2.h - hsv1.h; + var h; + + if (hsv1.h > hsv2.h) + { + var h3 = hsv2.h; + hsv2.h = hsv1.h; + hsv1.h = h3; + dh = -dh; + currentStep = steps - currentStep; + } + + if (dh > 0.5) + { + hsv1.h = hsv1.h + 1; + h = (((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h) % 1; + } + + if (dh <= 0.5) + { + h = ((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h; + } + + var s = (((hsv2.s - hsv1.s) * currentStep) / steps) + hsv1.s; + var v = (((hsv2.v - hsv1.v) * currentStep) / steps) + hsv1.v; + + var rgb = Phaser.Color.HSVtoRGB(h, s, v, rgb); + var r = rgb.r; + var g = rgb.g; + var b = rgb.b; + } + + return Phaser.Color.getColor32(alpha, r, g, b); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColorWithRGB + * @static + * @param {number} color - The first color value. + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * @method Phaser.Color.interpolateRGB + * @static + * @param {number} r1 - The red color value, between 0 and 0xFF (255). + * @param {number} g1 - The green color value, between 0 and 0xFF (255). + * @param {number} b1 - The blue color value, between 0 and 0xFF (255). + * @param {number} r2 - The red color value, between 0 and 0xFF (255). + * @param {number} g2 - The green color value, between 0 and 0xFF (255). + * @param {number} b2 - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + + /** + * Calculates a linear (interpolation) value of two colors over t. + * + * This is a slightly simpler interface to {@link Phaser.Color.interpolateColor}. + * + * The arguments are similar to {@link Phaser.Math.linear}. + * + * @method Phaser.Color.linear + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linear: function (color1, color2, t) { + + return this.interpolateColor(color1, color2, 1, t); + + }, + + /** + * Calculates a linear (interpolation) value of an array of colors over t. + * + * The arguments are similar to {@link Phaser.Math.linearInterpolation}. + * + * This can be used as a {@link Phaser.TweenData#interpolationFunction}. + * + * @method Phaser.Color.linearInterpolation + * @param {number[]} colors - The input array of color values to interpolate between. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linearInterpolation: function (colors, t) { + + var k = Phaser.Math.linear(0, colors.length - 1, t); + var color1 = colors[ Math.floor(k) ]; + var color2 = colors[ Math.ceil(k)] ; + + return this.linear(color1, color2, k % 1); + + }, + + /** + * Returns a random color value between black and white + * Set the min value to start each channel from the given offset. + * Set the max value to restrict the maximum color used per channel. + * + * @method Phaser.Color.getRandomColor + * @static + * @param {number} [min=0] - The lowest value to use for the color. + * @param {number} [max=255] - The highest value to use for the color. + * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). + * @returns {number} 32-bit color value with alpha. + */ + getRandomColor: function (min, max, alpha) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + if (alpha === undefined) { alpha = 255; } + + // Sanity checks + 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); + + }, + + /** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exist in the given color (0xAARRGGBB) + * + * @method Phaser.Color.getRGB + * @static + * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). + * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. + */ + getRGB: function (color) { + + if (color > 16777215) + { + // The color value has an alpha component + return { + alpha: color >>> 24, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: color >>> 24, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + else + { + return { + alpha: 255, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: 255, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + + }, + + /** + * Returns a CSS friendly string value from the given color. + * + * @method Phaser.Color.getWebRGB + * @static + * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. + * @returns {string} A string in the format: 'rgba(r,g,b,a)' + */ + getWebRGB: function (color) { + + if (typeof color === 'object') + { + return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')'; + } + else + { + var rgb = Phaser.Color.getRGB(color); + return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')'; + } + + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. + * + * @method Phaser.Color.getAlpha + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlpha: function (color) { + return color >>> 24; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. + * + * @method Phaser.Color.getAlphaFloat + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlphaFloat: function (color) { + return (color >>> 24) / 255; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. + * + * @method Phaser.Color.getRed + * @static + * @param {number} color In the format 0xAARRGGBB. + * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). + */ + getRed: function (color) { + return color >> 16 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. + * + * @method Phaser.Color.getGreen + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). + */ + getGreen: function (color) { + return color >> 8 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. + * + * @method Phaser.Color.getBlue + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). + */ + getBlue: function (color) { + return color & 0xFF; + }, + + /** + * Blends the source color, ignoring the backdrop. + * + * @method Phaser.Color.blendNormal + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNormal: function (a) { + return a; + }, + + /** + * Selects the lighter of the backdrop and source colors. + * + * @method Phaser.Color.blendLighten + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLighten: function (a, b) { + return (b > a) ? b : a; + }, + + /** + * Selects the darker of the backdrop and source colors. + * + * @method Phaser.Color.blendDarken + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDarken: function (a, b) { + return (b > a) ? a : b; + }, + + /** + * Multiplies the backdrop and source color values. + * The result color is always at least as dark as either of the two constituent + * colors. Multiplying any color with black produces black; + * multiplying with white leaves the original color unchanged. + * + * @method Phaser.Color.blendMultiply + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendMultiply: function (a, b) { + return (a * b) / 255; + }, + + /** + * Takes the average of the source and backdrop colors. + * + * @method Phaser.Color.blendAverage + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAverage: function (a, b) { + return (a + b) / 2; + }, + + /** + * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. + * + * @method Phaser.Color.blendAdd + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAdd: function (a, b) { + return Math.min(255, a + b); + }, + + /** + * Combines the source and backdrop colors and returns their value minus 255. + * + * @method Phaser.Color.blendSubtract + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSubtract: function (a, b) { + return Math.max(0, a + b - 255); + }, + + /** + * Subtracts the darker of the two constituent colors from the lighter. + * + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendDifference + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDifference: function (a, b) { + return Math.abs(a - b); + }, + + /** + * Negation blend mode. + * + * @method Phaser.Color.blendNegation + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNegation: function (a, b) { + return 255 - Math.abs(255 - a - b); + }, + + /** + * Multiplies the complements of the backdrop and source color values, then complements the result. + * The result color is always at least as light as either of the two constituent colors. + * Screening any color with white produces white; screening with black leaves the original color unchanged. + * + * @method Phaser.Color.blendScreen + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendScreen: function (a, b) { + return 255 - (((255 - a) * (255 - b)) >> 8); + }, + + /** + * Produces an effect similar to that of the Difference mode, but lower in contrast. + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendExclusion + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendExclusion: function (a, b) { + return a + b - 2 * a * b / 255; + }, + + /** + * Multiplies or screens the colors, depending on the backdrop color. + * Source colors overlay the backdrop while preserving its highlights and shadows. + * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. + * + * @method Phaser.Color.blendOverlay + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendOverlay: function (a, b) { + return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255); + }, + + /** + * Darkens or lightens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. + * The effect is similar to shining a diffused spotlight on the backdrop. + * + * @method Phaser.Color.blendSoftLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSoftLight: function (a, b) { + return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255); + }, + + /** + * Multiplies or screens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; + * this is useful for adding shadows to a scene. + * + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. + * + * @method Phaser.Color.blendHardLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardLight: function (a, b) { + return Phaser.Color.blendOverlay(b, a); + }, + + /** + * Brightens the backdrop color to reflect the source color. + * Painting with black produces no change. + * + * @method Phaser.Color.blendColorDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorDodge: function (a, b) { + return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b))); + }, + + /** + * Darkens the backdrop color to reflect the source color. + * Painting with white produces no change. + * + * @method Phaser.Color.blendColorBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorBurn: function (a, b) { + return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b)); + }, + + /** + * An alias for blendAdd, it simply sums the values of the two colors. + * + * @method Phaser.Color.blendLinearDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearDodge: function (a, b) { + return Phaser.Color.blendAdd(a, b); + }, + + /** + * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. + * + * @method Phaser.Color.blendLinearBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearBurn: function (a, b) { + return Phaser.Color.blendSubtract(a, b); + }, + + /** + * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). + * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. + * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. + * + * @method Phaser.Color.blendLinearLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearLight: function (a, b) { + return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128))); + }, + + /** + * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). + * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. + * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom + * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. + * + * @method Phaser.Color.blendVividLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendVividLight: function (a, b) { + return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128))); + }, + + /** + * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. + * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. + * + * @method Phaser.Color.blendPinLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPinLight: function (a, b) { + return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128))); + }, + + /** + * Runs blendVividLight on the source and backdrop colors. + * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. + * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. + * This changes all pixels to primary additive colors (red, green, or blue), white, or black. + * + * @method Phaser.Color.blendHardMix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardMix: function (a, b) { + return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255; + }, + + /** + * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. + * + * @method Phaser.Color.blendReflect + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendReflect: function (a, b) { + return b === 255 ? b : Math.min(255, (a * a / (255 - b))); + }, + + /** + * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. + * + * @method Phaser.Color.blendGlow + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendGlow: function (a, b) { + return Phaser.Color.blendReflect(b, a); + }, + + /** + * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. + * + * @method Phaser.Color.blendPhoenix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPhoenix: function (a, b) { + return Math.min(a, b) - Math.max(a, b) + 255; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Manager is responsible for looking after all of the running physics systems. +* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. +* +* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. +* +* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the +* faster (due to being much simpler) Arcade Physics system. +* +* @class Phaser.Physics +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Physics = function (game, config) { + + config = config || {}; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} config - The physics configuration object as passed to the game on creation. + */ + this.config = config; + + /** + * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. + */ + this.arcade = null; + + /** + * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. + */ + this.p2 = null; + + /** + * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. + */ + this.ninja = null; + + /** + * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. + */ + this.box2d = null; + + /** + * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). + */ + this.chipmunk = null; + + /** + * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). + */ + this.matter = null; + + this.parseConfig(); + +}; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.ARCADE = 0; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.P2JS = 1; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.NINJA = 2; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.BOX2D = 3; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.CHIPMUNK = 4; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.MATTERJS = 5; + +Phaser.Physics.prototype = { + + /** + * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. + * + * @method Phaser.Physics#parseConfig + */ + parseConfig: function () { + + if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade')) + { + // If Arcade isn't specified, we create it automatically if we can + this.arcade = new Phaser.Physics.Arcade(this.game); + } + + 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); + } + + if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D')) + { + this.box2d = new Phaser.Physics.BOX2D(this.game, this.config); + } + + if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter')) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + + }, + + /** + * This will create an instance of the requested physics simulation. + * Phaser.Physics.Arcade is running by default, but all others need activating directly. + * + * You can start the following physics systems: + * + * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. + * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) + * + * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. + * They are not bundled into the core Phaser library. + * + * If the physics world has already been created (i.e. in another state in your game) then + * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors + * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. + * + * @method Phaser.Physics#startSystem + * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. + */ + startSystem: function (system) { + + if (system === Phaser.Physics.ARCADE) + { + this.arcade = new Phaser.Physics.Arcade(this.game); + } + else if (system === Phaser.Physics.P2JS) + { + if (this.p2 === null) + { + this.p2 = new Phaser.Physics.P2(this.game, this.config); + } + else + { + this.p2.reset(); + } + } + else if (system === Phaser.Physics.NINJA) + { + this.ninja = new Phaser.Physics.Ninja(this.game); + } + else if (system === Phaser.Physics.BOX2D) + { + if (this.box2d === null) + { + this.box2d = new Phaser.Physics.Box2D(this.game, this.config); + } + else + { + this.box2d.reset(); + } + } + else if (system === Phaser.Physics.MATTERJS) + { + if (this.matter === null) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + else + { + this.matter.reset(); + } + } + + }, + + /** + * This will create a default physics body on the given game object or array of objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * It can be for any of the physics systems that have been started: + * + * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. + * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. + * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 + * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) + * Phaser.Physics.CHIPMUNK is still in development. + * + * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the + * individual physics systems `enable` methods instead of using this generic one. + * + * @method Phaser.Physics#enable + * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. + * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. + * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. + */ + enable: function (object, system, debug) { + + if (system === undefined) { system = Phaser.Physics.ARCADE; } + if (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); + } + else if (system === Phaser.Physics.BOX2D && this.box2d) + { + this.box2d.enable(object); + } + else if (system === Phaser.Physics.MATTERJS && this.matter) + { + this.matter.enable(object); + } + else + { + console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.'); + } + + }, + + /** + * preUpdate checks. + * + * @method Phaser.Physics#preUpdate + * @protected + */ + preUpdate: function () { + + // ArcadePhysics / Ninja don't have a core to preUpdate + + if (this.p2) + { + this.p2.preUpdate(); + } + + if (this.box2d) + { + this.box2d.preUpdate(); + } + + if (this.matter) + { + this.matter.preUpdate(); + } + + }, + + /** + * Updates all running physics systems. + * + * @method Phaser.Physics#update + * @protected + */ + update: function () { + + // ArcadePhysics / Ninja don't have a core to update + + if (this.p2) + { + this.p2.update(); + } + + if (this.box2d) + { + this.box2d.update(); + } + + if (this.matter) + { + this.matter.update(); + } + + }, + + /** + * Updates the physics bounds to match the world dimensions. + * + * @method Phaser.Physics#setBoundsToWorld + * @protected + */ + setBoundsToWorld: function () { + + if (this.arcade) + { + this.arcade.setBoundsToWorld(); + } + + if (this.ninja) + { + this.ninja.setBoundsToWorld(); + } + + if (this.p2) + { + this.p2.setBoundsToWorld(); + } + + if (this.box2d) + { + this.box2d.setBoundsToWorld(); + } + + if (this.matter) + { + this.matter.setBoundsToWorld(); + } + + }, + + /** + * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. + * + * @method Phaser.Physics#clear + * @protected + */ + clear: function () { + + if (this.p2) + { + this.p2.clear(); + } + + if (this.box2d) + { + this.box2d.clear(); + } + + if (this.matter) + { + this.matter.clear(); + } + + }, + + /** + * Resets the active physics system. Called automatically on a Phaser.State swap. + * + * @method Phaser.Physics#reset + * @protected + */ + reset: function () { + + if (this.p2) + { + this.p2.reset(); + } + + if (this.box2d) + { + this.box2d.reset(); + } + + if (this.matter) + { + this.matter.reset(); + } + + }, + + /** + * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. + * + * @method Phaser.Physics#destroy + */ + destroy: function () { + + if (this.p2) + { + this.p2.destroy(); + } + + if (this.box2d) + { + this.box2d.destroy(); + } + + if (this.matter) + { + this.matter.destroy(); + } + + this.arcade = null; + this.ninja = null; + this.p2 = null; + this.box2d = null; + this.matter = null; + + } + +}; + +Phaser.Physics.prototype.constructor = Phaser.Physics; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. +* +* @class Phaser.Physics.Arcade +* @constructor +* @param {Phaser.Game} game - reference to the current game instance. +*/ +Phaser.Physics.Arcade = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height); + + /** + * Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`. + * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. + * @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right). + */ + this.checkCollision = { up: true, down: true, left: true, right: true }; + + /** + * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. + */ + this.maxLevels = 4; + + /** + * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. + * @default + */ + this.OVERLAP_BIAS = 4; + + /** + * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. + */ + this.forceX = false; + + /** + * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT. + * @default + */ + this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT; + + /** + * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. + */ + this.skipQuadTree = true; + + /** + * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. + */ + this.isPaused = false; + + /** + * @property {Phaser.QuadTree} quadTree - The world QuadTree. + */ + 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); + + /** + * @property {number} _total - Internal cache var. + * @private + */ + this._total = 0; + + // By default we want the bounds the same size as the world bounds + this.setBoundsToWorld(); + +}; + +Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade; + +/** +* A constant used for the sortDirection value. +* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.SORT_NONE = 0; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.LEFT_RIGHT = 1; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.RIGHT_LEFT = 2; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.TOP_BOTTOM = 3; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.BOTTOM_TOP = 4; + +Phaser.Physics.Arcade.prototype = { + + /** + * Updates the size of this physics world. + * + * @method Phaser.Physics.Arcade#setBounds + * @param {number} x - Top left most corner of the world. + * @param {number} y - Top left most corner of the world. + * @param {number} width - New width of the world. Can never be smaller than the Game.width. + * @param {number} height - New height of the world. Can never be smaller than the Game.height. + */ + setBounds: function (x, y, width, height) { + + this.bounds.setTo(x, y, width, height); + + }, + + /** + * Updates the size of this physics world to match the size of the game world. + * + * @method Phaser.Physics.Arcade#setBoundsToWorld + */ + setBoundsToWorld: function () { + + this.bounds.copyFrom(this.game.world.bounds); + + }, + + /** + * This will create an Arcade Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * + * @method Phaser.Physics.Arcade#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, children) { + + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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) + { + // If it's a Group then we do it on the children regardless + this.enable(object.children, children); + } + else + { + this.enableBody(object); + + if (children && object.hasOwnProperty('children') && object.children.length > 0) + { + this.enable(object.children, true); + } + } + } + + }, + + /** + * Creates an Arcade Physics body on the given game object. + * + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. + * + * @method Phaser.Physics.Arcade#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + */ + enableBody: function (object) { + + if (object.hasOwnProperty('body') && object.body === null) + { + object.body = new Phaser.Physics.Arcade.Body(object); + + if (object.parent && object.parent instanceof Phaser.Group) + { + object.parent.addToHash(object); + } + } + + }, + + /** + * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. + * + * @method Phaser.Physics.Arcade#updateMotion + * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. + */ + updateMotion: function (body) { + + if (body.allowRotation) + { + var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity; + body.angularVelocity += 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); + + }, + + /** + * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * Based on a function in Flixel by @ADAMATOMIC + * + * @method Phaser.Physics.Arcade#computeVelocity + * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical. + * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. + * @param {number} velocity - Any component of velocity (e.g. 20). + * @param {number} acceleration - Rate at which the velocity is changing. + * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. + * @param {number} [max=10000] - An absolute value cap for the velocity. + * @return {number} The altered Velocity value. + */ + computeVelocity: function (axis, body, velocity, acceleration, drag, max) { + + if (max === undefined) { max = 10000; } + + 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 && body.allowDrag) + { + drag *= this.game.time.physicsElapsed; + + if (velocity - drag > 0) + { + velocity -= drag; + } + else if (velocity + drag < 0) + { + velocity += drag; + } + else + { + velocity = 0; + } + } + + if (velocity > max) + { + velocity = max; + } + else if (velocity < -max) + { + velocity = -max; + } + + return velocity; + + }, + + /** + * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. + * + * Unlike {@link #collide} the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. + * Both the first and second parameter can be arrays of objects, of differing types. + * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups within Groups). + * + * ##### Tilemaps + * + * Any overlapping tiles, including blank/null tiles, will give a positive result. Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) have no special status, and callbacks added via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} are not invoked. So calling this method without any callbacks isn't very useful. + * + * If you're interested only in whether an object overlaps a certain tile or class of tiles, filter the tiles with `processCallback` and then use the result returned by this method. Blank/null tiles can be excluded by their {@link Phaser.Tile#index index} (-1). + * + * If you want to take action on certain overlaps, examine the tiles in `collideCallback` and then handle as you like. + * + * @method Phaser.Physics.Arcade#overlap + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if an overlap occurred otherwise false. + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) { + + overlapCallback = overlapCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || overlapCallback; + + this._total = 0; + + this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + + return (this._total > 0); + + }, + + /** + * Checks for collision between two game objects and separates them if colliding ({@link https://gist.github.com/samme/cbb81dd19f564dcfe2232761e575063d details}). If you don't require separation then use {@link #overlap} instead. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. + * Both the `object1` and `object2` can be arrays of objects, of differing types. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If one Group **only** is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If either object is `null` the collision test will fail. + * + * Bodies with `enable = false` and Sprites with `exists = false` are skipped (ignored). + * + * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. + * + * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). + * + * ##### Examples + * + * ```javascript + * collide(group); + * collide(group, undefined); // equivalent + * + * collide(sprite1, sprite2); + * + * collide(sprite, group); + * + * collide(group1, group2); + * + * collide([sprite1, sprite2], [sprite3, sprite4]); // 1 vs. 3, 1 vs. 4, 2 vs. 3, 2 vs. 4 + * ``` + * + * ##### Tilemaps + * + * Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) are "solid". If a Sprite collides with one of these tiles, the two are separated by moving the Sprite outside the tile's edges. Enable {@link Phaser.TilemapLayer#debug} to see the colliding edges of the Tilemap. + * + * Tiles with a callback attached via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} invoke the callback if a Sprite collides with them. If a tile has a callback attached via both methods, only the location callback is invoked. The colliding Sprite is separated from the tile only if the callback returns `true`. + * + * @method Phaser.Physics.Arcade#collide + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. + * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if a collision occurred otherwise false. + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) { + + collideCallback = collideCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || collideCallback; + + this._total = 0; + + this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + + return (this._total > 0); + + }, + + /** + * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortLeftRight + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortLeftRight: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.x - b.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortRightLeft + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortRightLeft: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.x - a.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortTopBottom + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortTopBottom: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.y - b.body.y; + + }, + + /** + * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortBottomTop + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortBottomTop: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.y - a.body.y; + + }, + + /** + * This method will sort a Groups hash array. + * + * If the Group has `physicsSortDirection` set it will use the sort direction defined. + * + * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection. + * + * By changing Group.physicsSortDirection you can customise each Group to sort in a different order. + * + * @method Phaser.Physics.Arcade#sort + * @param {Phaser.Group} group - The Group to sort. + * @param {integer} [sortDirection] - The sort direction used to sort this Group. + */ + sort: function (group, sortDirection) { + + if (group.physicsSortDirection !== null) + { + sortDirection = group.physicsSortDirection; + } + else + { + if (sortDirection === undefined) { sortDirection = this.sortDirection; } + } + + if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + // Game world is say 2000x600 and you start at 0 + group.hash.sort(this.sortLeftRight); + } + else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + // Game world is say 2000x600 and you start at 2000 + group.hash.sort(this.sortRightLeft); + } + else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + // Game world is say 800x2000 and you start at 0 + group.hash.sort(this.sortTopBottom); + } + else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + // Game world is say 800x2000 and you start at 2000 + group.hash.sort(this.sortBottomTop); + } + + }, + + /** + * Internal collision handler. Extracts objects for {@link #collideHandler}. + * + * @method Phaser.Physics.Arcade#collideObjects + * @private + */ + collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object2.length; i++) + { + if (!object2[i]) { continue; } + + this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && !Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + for (var j = 0; j < object2.length; j++) + { + if (!object2[j]) { continue; } + + this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + + }, + + /** + * Internal collision handler. Matches arguments to other handlers. + * + * @method Phaser.Physics.Arcade#collideHandler + * @private + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + // Only collide valid objects + if (object2 === undefined && object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly); + return; + } + + // If neither of the objects are set or exist then bail out + if (!object1 || !object2 || !object1.exists || !object2.exists) + { + return; + } + + // Groups? Sort them + if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE) + { + if (object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + } + + if (object2.physicsType === Phaser.GROUP) + { + this.sort(object2); + } + } + + // SPRITES + if (object1.physicsType === Phaser.SPRITE) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // GROUPS + else if (object1.physicsType === Phaser.GROUP) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // TILEMAP LAYERS + else if (object1.physicsType === Phaser.TILEMAPLAYER) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsSprite + * @private + * @param {Phaser.Sprite} sprite1 - The first sprite to check. + * @param {Phaser.Sprite} sprite2 - The second sprite to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + 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; + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsGroup + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0 || !sprite.body) + { + return; + } + + if (this.skipQuadTree || sprite.body.skipQuadTree) + { + var bounds = {}; + + for (var i = 0; i < group.hash.length; i++) + { + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds object + bounds = object1.body.getBounds(bounds); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (sprite.body.right < bounds.x) + { + break; + } + else if (bounds.right < sprite.body.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (sprite.body.x > bounds.right) + { + break; + } + else if (bounds.x > sprite.body.right) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (sprite.body.bottom < bounds.y) + { + break; + } + else if (bounds.bottom < sprite.body.y) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (sprite.body.y > bounds.bottom) + { + break; + } + else if (bounds.y > sprite.body.bottom) + { + continue; + } + } + + this.collideSpriteVsSprite(sprite, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else + { + // What is the sprite colliding with in the quadtree? + 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 items = this.quadTree.retrieve(sprite); + + for (var i = 0; i < items.length; i++) + { + // We have our potential suspects, are they in this group? + if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, items[i].sprite); + } + + this._total++; + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsSelf + * @private + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.hash.length; i++) + { + var bounds1 = {}; + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds1 object + bounds1 = object1.body.getBounds(bounds1); + + for (var j = i + 1; j < group.hash.length; j++) + { + var bounds2 = {}; + var object2 = group.hash[j]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object2 || !object2.exists || !object2.body) + { + continue; + } + + // Inject the Body bounds data into the bounds2 object + bounds2 = object2.body.getBounds(bounds2); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (bounds1.right < bounds2.x) + { + break; + } + else if (bounds2.right < bounds1.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (bounds1.x > bounds2.right) + { + continue; + } + else if (bounds2.x > bounds1.right) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (bounds1.bottom < bounds2.y) + { + continue; + } + else if (bounds2.bottom < bounds1.y) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (bounds1.y > bounds2.bottom) + { + continue; + } + else if (bounds2.y > object1.body.bottom) + { + break; + } + } + + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsGroup + * @private + * @param {Phaser.Group} group1 - The first Group to check. + * @param {Phaser.Group} group2 - The second Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group1.length === 0 || group2.length === 0) + { + return; + } + + for (var i = 0; i < group1.children.length; i++) + { + if (group1.children[i].exists) + { + if (group1.children[i].physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else + { + this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + + }, + + /** + * The core separation function to separate two physics bodies. + * + * @private + * @method Phaser.Physics.Arcade#separate + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true. + * @param {object} [callbackContext] - The context in which to run the process callback. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} Returns true if the bodies collided, otherwise false. + */ + separate: function (body1, body2, processCallback, callbackContext, overlapOnly) { + + if ( + !body1.enable || + !body2.enable || + body1.checkCollision.none || + body2.checkCollision.none || + !this.intersects(body1, body2)) + { + return false; + } + + // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. + if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false) + { + return false; + } + + // Circle vs. Circle quick bail out + if (body1.isCircle && body2.isCircle) + { + return this.separateCircle(body1, body2, overlapOnly); + } + + // We define the behavior of bodies in a collision circle and rectangle + // If a collision occurs in the corner points of the rectangle, the body behave like circles + + // Either body1 or body2 is a circle + if (body1.isCircle !== body2.isCircle) + { + var bodyRect = (body1.isCircle) ? body2 : body1; + var bodyCircle = (body1.isCircle) ? body1 : body2; + + var rect = { + x: bodyRect.x, + y: bodyRect.y, + right: bodyRect.right, + bottom: bodyRect.bottom + }; + + var circle = bodyCircle.center; + + if (circle.y < rect.y || circle.y > rect.bottom) + { + if (circle.x < rect.x || circle.x > rect.right) + { + return this.separateCircle(body1, body2, overlapOnly); + } + } + } + + var resultX = false; + var resultY = false; + + // Do we separate on x or y first? + if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) + { + resultX = this.separateX(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultY = this.separateY(body1, body2, overlapOnly); + } + } + else + { + resultY = this.separateY(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultX = this.separateX(body1, body2, overlapOnly); + } + } + + var result = (resultX || resultY); + + if (result) + { + if (overlapOnly) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + else + { + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + } + } + + return result; + + }, + + /** + * Check for intersection against two bodies. + * + * @method Phaser.Physics.Arcade#intersects + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check. + * @return {boolean} True if they intersect, otherwise false. + */ + intersects: function (body1, body2) { + + if (body1 === body2) + { + return false; + } + + if (body1.isCircle) + { + if (body2.isCircle) + { + // Circle vs. Circle + return Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); + } + else + { + // Circle vs. Rect + return this.circleBodyIntersects(body1, body2); + } + } + else + { + if (body2.isCircle) + { + // Rect vs. Circle + return this.circleBodyIntersects(body2, body1); + } + else + { + // Rect vs. Rect + if (body1.right <= body2.position.x) + { + return false; + } + + if (body1.bottom <= body2.position.y) + { + return false; + } + + if (body1.position.x >= body2.right) + { + return false; + } + + if (body1.position.y >= body2.bottom) + { + return false; + } + + return true; + } + } + + }, + + /** + * Checks to see if a circular Body intersects with a Rectangular Body. + * + * @method Phaser.Physics.Arcade#circleBodyIntersects + * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set. + * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape) + * @return {boolean} Returns true if the bodies intersect, otherwise false. + */ + circleBodyIntersects: function (circle, body) { + + var x = Phaser.Math.clamp(circle.center.x, body.left, body.right); + var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom); + + var dx = (circle.center.x - x) * (circle.center.x - x); + var dy = (circle.center.y - y) * (circle.center.y - y); + + return (dx + dy) <= (circle.halfWidth * circle.halfWidth); + + }, + + /** + * The core separation function to separate two circular physics bodies. + * + * @method Phaser.Physics.Arcade#separateCircle + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateCircle: function (body1, body2, overlapOnly) { + + // Set the bounding box overlap values + this.getOverlapX(body1, body2); + this.getOverlapY(body1, body2); + + var dx = body2.center.x - body1.center.x; + var dy = body2.center.y - body1.center.y; + + var angleCollision = Math.atan2(dy, dx); + + var overlap = 0; + + if (body1.isCircle !== body2.isCircle) + { + var rect = { + x: (body2.isCircle) ? body1.position.x : body2.position.x, + y: (body2.isCircle) ? body1.position.y : body2.position.y, + right: (body2.isCircle) ? body1.right : body2.right, + bottom: (body2.isCircle) ? body1.bottom : body2.bottom + }; + + var circle = { + x: (body1.isCircle) ? body1.center.x : body2.center.x, + y: (body1.isCircle) ? body1.center.y : body2.center.y, + radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth + }; + + if (circle.y < rect.y) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.y) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.y) - circle.radius; + } + } + else if (circle.y > rect.bottom) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; + } + } + + overlap *= -1; + } + else + { + overlap = (body1.halfWidth + body2.halfWidth) - Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y); + } + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + if (overlap !== 0) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + + // return true if there was some overlap, otherwise false + return (overlap !== 0); + } + + // Transform the velocity vector to the coordinate system oriented along the direction of impact. + // This is done to eliminate the vertical component of the velocity + var v1 = { + x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision), + y: body1.velocity.x * Math.sin(angleCollision) - body1.velocity.y * Math.cos(angleCollision) + }; + + var v2 = { + x: body2.velocity.x * Math.cos(angleCollision) + body2.velocity.y * Math.sin(angleCollision), + y: body2.velocity.x * Math.sin(angleCollision) - body2.velocity.y * Math.cos(angleCollision) + }; + + // We expect the new velocity after impact + var tempVel1 = ((body1.mass - body2.mass) * v1.x + 2 * body2.mass * v2.x) / (body1.mass + body2.mass); + var tempVel2 = (2 * body1.mass * v1.x + (body2.mass - body1.mass) * v2.x) / (body1.mass + body2.mass); + + // We convert the vector to the original coordinate system and multiplied by factor of rebound + if (!body1.immovable) + { + body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x; + body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y; + } + + if (!body2.immovable) + { + body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x; + body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y; + } + + // When the collision angle is almost perpendicular to the total initial velocity vector + // (collision on a tangent) vector direction can be determined incorrectly. + // This code fixes the problem + + if (Math.abs(angleCollision) < Math.PI / 2) + { + if ((body1.velocity.x > 0) && !body1.immovable && (body2.velocity.x > body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x < 0) && !body2.immovable && (body1.velocity.x < body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y > 0) && !body1.immovable && (body2.velocity.y > body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y < 0) && !body2.immovable && (body1.velocity.y < body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + else if (Math.abs(angleCollision) > Math.PI / 2) + { + if ((body1.velocity.x < 0) && !body1.immovable && (body2.velocity.x < body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y < 0) && !body1.immovable && (body2.velocity.y < body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + + if (!body1.immovable) + { + body1.x += (body1.velocity.x * this.game.time.physicsElapsed) - overlap * Math.cos(angleCollision); + body1.y += (body1.velocity.y * this.game.time.physicsElapsed) - overlap * Math.sin(angleCollision); + } + + if (!body2.immovable) + { + body2.x += (body2.velocity.x * this.game.time.physicsElapsed) + overlap * Math.cos(angleCollision); + body2.y += (body2.velocity.y * this.game.time.physicsElapsed) + overlap * Math.sin(angleCollision); + } + + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + + return true; + + }, + + /** + * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: + * `touching.left`, `touching.right` and `overlapX`. + * + * @method Phaser.Physics.Arcade#getOverlapX + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of horizontal overlap between the two bodies. + */ + getOverlapX: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS; + + if (body1.deltaX() === 0 && body2.deltaX() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaX() > body2.deltaX()) + { + // Body1 is moving right and / or Body2 is moving left + overlap = body1.right - body2.x; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.right = true; + body2.touching.none = false; + body2.touching.left = true; + } + } + else if (body1.deltaX() < body2.deltaX()) + { + // Body1 is moving left and/or Body2 is moving right + overlap = body1.x - body2.width - body2.x; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.left = true; + body2.touching.none = false; + body2.touching.right = true; + } + } + + // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapX = overlap; + body2.overlapX = overlap; + + return overlap; + + }, + + /** + * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: + * `touching.up`, `touching.down` and `overlapY`. + * + * @method Phaser.Physics.Arcade#getOverlapY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of vertical overlap between the two bodies. + */ + getOverlapY: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS; + + if (body1.deltaY() === 0 && body2.deltaY() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaY() > body2.deltaY()) + { + // Body1 is moving down and/or Body2 is moving up + overlap = body1.bottom - body2.y; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.down = true; + body2.touching.none = false; + body2.touching.up = true; + } + } + else if (body1.deltaY() < body2.deltaY()) + { + // Body1 is moving up and/or Body2 is moving down + overlap = body1.y - body2.bottom; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.up = true; + body2.touching.none = false; + body2.touching.down = true; + } + } + + // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapY = overlap; + body2.overlapY = overlap; + + return overlap; + + }, + + /** + * The core separation function to separate two physics bodies on the x axis. + * + * @method Phaser.Physics.Arcade#separateX + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateX: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapX(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.x; + var v2 = body2.velocity.x; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.x -= overlap; + body2.x += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.x = avg + nv1 * body1.bounce.x; + body2.velocity.x = avg + nv2 * body2.bounce.x; + } + else if (!body1.immovable) + { + body1.x -= overlap; + body1.velocity.x = v2 - v1 * body1.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body2.moves) + { + body1.y += (body2.y - body2.prev.y) * body2.friction.y; + } + } + else + { + body2.x += overlap; + body2.velocity.x = v1 - v2 * body2.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body1.moves) + { + body2.y += (body1.y - body1.prev.y) * body1.friction.y; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * The core separation function to separate two physics bodies on the y axis. + * + * @private + * @method Phaser.Physics.Arcade#separateY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateY: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapY(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.y; + var v2 = body2.velocity.y; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.y -= overlap; + body2.y += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.y = avg + nv1 * body1.bounce.y; + body2.velocity.y = avg + nv2 * body2.bounce.y; + } + else if (!body1.immovable) + { + body1.y -= overlap; + body1.velocity.y = v2 - v1 * body1.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body2.moves) + { + body1.x += (body2.x - body2.prev.x) * body2.friction.x; + } + } + else + { + body2.y += overlap; + body2.velocity.y = v1 - v2 * body2.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body1.moves) + { + body2.x += (body1.x - body1.prev.x) * body1.friction.x; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. + * + * @method Phaser.Physics.Arcade#getObjectsUnderPointer + * @param {Phaser.Pointer} pointer - The Pointer to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. + * @param {object} [callbackContext] - The context in which to run the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates. + */ + getObjectsUnderPointer: function (pointer, group, callback, callbackContext) { + + if (group.length === 0 || !pointer.exists) + { + return; + } + + return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer); + + }, + + /** + * Given a Group and a location this will check to see which Group children overlap with the coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. + * + * @method Phaser.Physics.Arcade#getObjectsAtLocation + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. + * @param {object} [callbackContext] - The context in which to run the callback. + * @param {object} [callbackArg] - An argument to pass to the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates. + */ + getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) { + + 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(x, y, 1, 1); + var output = []; + + var items = this.quadTree.retrieve(rect); + + for (var i = 0; i < items.length; i++) + { + if (items[i].hitTest(x, y)) + { + if (callback) + { + callback.call(callbackContext, callbackArg, items[i].sprite); + } + + output.push(items[i].sprite); + } + } + + return output; + + }, + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToObject: function (displayObject, destination, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Phaser.Point.angle(destination, displayObject); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#moveToPointer + * @param {any} displayObject - The display object to move. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToPointer: function (displayObject, speed, pointer, maxTime) { + + if (speed === undefined) { speed = 60; } + pointer = pointer || this.game.input.activePointer; + if (maxTime === undefined) { maxTime = 0; } + + var angle = this.angleToPointer(displayObject, pointer); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToXY: function (displayObject, x, y, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Math.atan2(y - displayObject.y, x - displayObject.x); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromAngle + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromAngle: function (angle, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(angle, speed, true); + + }, + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. + * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. + * + * @method Phaser.Physics.Arcade#accelerationFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. + * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. + */ + accelerationFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleBetween(displayObject, destination); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToPointer + * @param {any} displayObject - The display object to move. + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToPointer(displayObject, pointer); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToXY(displayObject, x, y); + + displayObject.body.acceleration.setTo(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Find the distance between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * If you have nested objects and need to calculate the distance between their centers in World coordinates, + * set their anchors to (0.5, 0.5) and use the `world` argument. + * + * If objects aren't nested or they share a parent's offset, you can calculate the distance between their + * centers with the `useCenter` argument, regardless of their anchor values. + * + * @method Phaser.Physics.Arcade#distanceBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {number} The distance between the source and target objects. + */ + distanceBetween: function (source, target, world, useCenter) { + + if (world === undefined) { world = false; } + + var dx; + var dy; + + if (useCenter) + { + dx = source.centerX - target.centerX; + dy = source.centerY - target.centerY; + } + else if (world) + { + dx = source.world.x - target.world.x; + dy = source.world.y - target.world.y; + } + else + { + dx = source.x - target.x; + dy = source.y - target.y; + } + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and the given x/y coordinates. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the x/y coordinates. + */ + distanceToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - x : displayObject.x - x; + var dy = (world) ? displayObject.world.y - y : displayObject.y - y; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the Pointer. + */ + distanceToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.x - pointer.worldX; + var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + + /** + * From a set of points or display objects, find the one closest to a source point or object. + * + * @method Phaser.Physics.Arcade#closest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The first target closest to the origin. + */ + closest: function (source, targets, world, useCenter) { + var min = Infinity; + var closest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance < min) + { + closest = target; + min = distance; + } + } + + return closest; + }, + + /** + * From a set of points or display objects, find the one farthest from a source point or object. + * + * @method Phaser.Physics.Arcade#farthest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The target closest to the origin. + */ + farthest: function (source, targets, world, useCenter) { + var max = -1; + var farthest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance > max) + { + farthest = target; + max = distance; + } + } + + return farthest; + }, + + /** + * Find the angle in radians between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetween: function (source, target, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Phaser.Point.angle(target.world, source.world); + } + else + { + return Phaser.Point.angle(target, source); + } + + }, + + /** + * Find the angle in radians between centers of two display objects (like Sprites). + * + * @method Phaser.Physics.Arcade#angleBetweenCenters + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetweenCenters: function (source, target) { + + var dx = target.centerX - source.centerX; + var dy = target.centerY - source.centerY; + + return Math.atan2(dy, dx); + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to get the angle to. + * @param {number} y - The y coordinate to get the angle to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(y - displayObject.world.y, x - displayObject.world.x); + } + else + { + return Math.atan2(y - displayObject.y, x - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x); + } + else + { + return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, + * taking their x/y and center into account relative to the world. + * + * @method Phaser.Physics.Arcade#worldAngleToPointer + * @param {any} displayObject - The DisplayObjerct to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY + */ + worldAngleToPointer: function (displayObject, pointer) { + + return this.angleToPointer(displayObject, pointer, true); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than +* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. +* +* @class Phaser.Physics.Arcade.Body +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. +*/ +Phaser.Physics.Arcade.Body = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = sprite.game; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.ARCADE; + + /** + * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. + * @default + */ + this.enable = true; + + /** + * If `true` this Body is using circular collision detection. If `false` it is using rectangular. + * Use `Body.setCircle` to control the collision shape this Body uses. + * @property {boolean} isCircle + * @default + * @readOnly + */ + this.isCircle = false; + + /** + * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled, relative to the Sprite's _texture_. + * If you wish to change the radius then call {@link #setCircle} again with the new value. + * If you wish to stop the Body using a circle then call {@link #setCircle} with a radius of zero (or undefined). + * The actual radius of the Body (at any Sprite scale) is equal to {@link #halfWidth} and the diameter is equal to {@link #width}. + * @property {number} radius + * @default + * @readOnly + */ + this.radius = 0; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite's texture. + */ + this.offset = new Phaser.Point(); + + /** + * @property {Phaser.Point} position - The position of the physics body, equivalent to ({@link #left}, {@link #top}). + * @readonly + */ + this.position = new Phaser.Point(sprite.x, sprite.y); + + /** + * @property {Phaser.Point} prev - The previous position of the physics body. + * @readonly + */ + this.prev = new Phaser.Point(this.position.x, this.position.y); + + /** + * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) + * @default + */ + this.allowRotation = true; + + /** + * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body + * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. + * @property {number} rotation + */ + this.rotation = sprite.angle; + + /** + * @property {number} preRotation - The previous rotation of the physics body, in degrees. + * @readonly + */ + this.preRotation = sprite.angle; + + /** + * @property {number} width - The calculated width of the physics body. + * @readonly + */ + this.width = sprite.width; + + /** + * @property {number} height - The calculated height of the physics body. + * @readonly + */ + this.height = sprite.height; + + /** + * @property {number} sourceWidth - The un-scaled original size. + * @readonly + */ + this.sourceWidth = sprite.width; + + /** + * @property {number} sourceHeight - The un-scaled original size. + * @readonly + */ + this.sourceHeight = sprite.height; + + if (sprite.texture) + { + this.sourceWidth = sprite.texture.frame.width; + this.sourceHeight = sprite.texture.frame.height; + } + + /** + * @property {number} halfWidth - The calculated width / 2 of the physics body. + * @readonly + */ + this.halfWidth = Math.abs(sprite.width / 2); + + /** + * @property {number} halfHeight - The calculated height / 2 of the physics body. + * @readonly + */ + this.halfHeight = Math.abs(sprite.height / 2); + + /** + * @property {Phaser.Point} center - The center coordinate of the Physics Body. + * @readonly + */ + this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight); + + /** + * @property {Phaser.Point} velocity - The velocity, or rate of change the Body's position. Measured in pixels per second. + */ + this.velocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} newVelocity - The distanced traveled during the last update, equal to `velocity * physicsElapsed`. Calculated during the Body.preUpdate and applied to its position. + * @readonly + */ + this.newVelocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. + */ + this.deltaMax = new Phaser.Point(); + + /** + * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + */ + this.acceleration = new Phaser.Point(); + + /** + * @property {boolean} allowDrag - Allow this Body to be influenced by {@link #drag}? + * @default + */ + this.allowDrag = true; + + /** + * @property {Phaser.Point} drag - The drag applied to the motion of the Body (when {@link #allowDrag} is enabled). Measured in pixels per second squared. + */ + this.drag = new Phaser.Point(); + + /** + * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local. + * @default + */ + this.allowGravity = true; + + /** + * @property {Phaser.Point} gravity - This Body's local gravity, **added** to any world gravity, unless Body.allowGravity is set to false. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. + */ + this.bounce = new Phaser.Point(); + + /** + * The elasticity of the Body when colliding with the World bounds. + * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property + * to a Phaser.Point object in order to enable a World bounds specific bounce value. + * @property {Phaser.Point} worldBounce + */ + this.worldBounce = null; + + /** + * A Signal that is dispatched when this Body collides with the world bounds. + * Due to the potentially high volume of signals this could create it is disabled by default. + * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` + * and it will be called when a collision happens, passing five arguments: + * `onWorldBounds(sprite, up, down, left, right)` + * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans + * indicating on which side of the world the Body collided. + * @property {Phaser.Signal} onWorldBounds + */ + this.onWorldBounds = null; + + /** + * A Signal that is dispatched when this Body collides with another Body. + * + * You still need to call `game.physics.arcade.collide` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `collide` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onCollide + */ + this.onCollide = null; + + /** + * A Signal that is dispatched when this Body overlaps with another Body. + * + * You still need to call `game.physics.arcade.overlap` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `overlap` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onOverlap + */ + this.onOverlap = null; + + /** + * @property {Phaser.Point} maxVelocity - The maximum velocity (in pixels per second squared) that the Body can reach. + * @default + */ + this.maxVelocity = new Phaser.Point(10000, 10000); + + /** + * @property {Phaser.Point} friction - If this Body is {@link #immovable} and moving, and another Body is 'riding' this one, this is the amount of motion the riding Body receives on each axis. + */ + this.friction = new Phaser.Point(1, 0); + + /** + * @property {number} angularVelocity - The angular velocity is the rate of change of the Body's rotation. It is measured in degrees per second. + * @default + */ + this.angularVelocity = 0; + + /** + * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. + * @default + */ + this.angularAcceleration = 0; + + /** + * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach. + * @default + */ + this.maxAngular = 1000; + + /** + * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. + * @default + */ + this.mass = 1; + + /** + * @property {number} angle - The angle of the Body's **velocity** in radians. + * @readonly + */ + this.angle = 0; + + /** + * @property {number} speed - The speed of the Body in pixels per second, equal to the magnitude of the velocity. + * @readonly + */ + this.speed = 0; + + /** + * @property {number} facing - A const reference to the direction the Body is traveling or facing: Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.UP, or Phaser.DOWN. If the Body is moving on both axes, UP and DOWN take precedence. + * @default + */ + this.facing = Phaser.NONE; + + /** + * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. **Two** immovable Bodies can't separate or exchange momentum and will pass through each other. + * @default + */ + this.immovable = false; + + /** + * Whether the physics system should update the Body's position and rotation based on its velocity, acceleration, drag, and gravity. + * + * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never + * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. + * If you want the physics system to move the body around, then set moves to true. + * + * A Body with moves = false can still be moved slightly (but not accelerated) during collision separation unless you set {@link #immovable} as well. + * + * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually. + * @default + */ + this.moves = true; + + /** + * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateX = false; + + /** + * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateY = false; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapX - The amount of horizontal overlap during the collision. + */ + this.overlapX = 0; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapY - The amount of vertical overlap during the collision. + */ + this.overlapY = 0; + + /** + * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. + * @property {number} overlapR - The amount of overlap during the collision. + */ + this.overlapR = 0; + + /** + * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. + * @property {boolean} embedded - Body embed value. + */ + this.embedded = false; + + /** + * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. + * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? + */ + this.collideWorldBounds = false; + + /** + * Set the checkCollision properties to control which directions collision is processed for this Body. + * For example checkCollision.up = false means it won't collide when the collision happened while moving up. + * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. + * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. + * @property {object} checkCollision - An object containing allowed collision (none, up, down, left, right). + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * This object is populated with boolean values when the Body collides with another. + * touching.up = true means the collision happened to the top of this Body for example. + * @property {object} touching - An object containing touching results (none, up, down, left, right). + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with previous touching values from the bodies previous collision. + * @property {object} wasTouching - An object containing previous touching results (none, up, down, left, right). + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with boolean values when the Body collides with the World bounds or a Tile. + * For example if blocked.up is true then the Body cannot move up. + * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any (none, up, down, left, right). + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. + * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. + * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision. + */ + this.tilePadding = new Phaser.Point(); + + /** + * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state? + */ + this.dirty = false; + + /** + * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. + */ + this.skipQuadTree = false; + + /** + * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. + * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. + * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, + * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. + * @property {boolean} syncBounds + * @default + */ + this.syncBounds = false; + + /** + * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods. + */ + this.isMoving = false; + + /** + * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods. + */ + this.stopVelocityOnCollide = true; + + /** + * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveTimer = 0; + + /** + * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDistance = 0; + + /** + * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDuration = 0; + + /** + * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveTarget = null; + + /** + * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveEnd = null; + + /** + * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events. + */ + this.onMoveComplete = new Phaser.Signal(); + + /** + * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. + */ + this.movementCallback = null; + + /** + * @property {object} movementCallbackContext - Context in which to call the movementCallback. + */ + this.movementCallbackContext = null; + + /** + * @property {boolean} _reset - Internal cache var. + * @private + */ + this._reset = true; + + /** + * @property {number} _sx - Internal cache var. + * @private + */ + this._sx = sprite.scale.x; + + /** + * @property {number} _sy - Internal cache var. + * @private + */ + this._sy = sprite.scale.y; + + /** + * @property {number} _dx - Internal cache var. + * @private + */ + this._dx = 0; + + /** + * @property {number} _dy - Internal cache var. + * @private + */ + this._dy = 0; + +}; + +Phaser.Physics.Arcade.Body.prototype = { + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @protected + */ + updateBounds: function () { + + if (this.syncBounds) + { + var b = this.sprite.getBounds(); + b.ceilAll(); + + if (b.width !== this.width || b.height !== this.height) + { + this.width = b.width; + this.height = b.height; + this._reset = true; + } + } + else + { + 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._sx = asx; + this._sy = asy; + this._reset = true; + } + } + + if (this._reset) + { + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.updateCenter(); + } + + }, + + /** + * Update the Body's center from its position. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @protected + */ + updateCenter: function () { + + this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @protected + */ + preUpdate: function () { + + if (!this.enable || this.game.physics.arcade.isPaused) + { + return; + } + + this.dirty = true; + + // Store and reset collision flags + 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.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; + + this.overlapR = 0; + this.overlapX = 0; + this.overlapY = 0; + + this.embedded = false; + + this.updateBounds(); + + this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.updateCenter(); + + this.rotation = this.sprite.angle; + + this.preRotation = this.rotation; + + if (this._reset || this.sprite.fresh) + { + 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; + this.updateCenter(); + + if (this.position.x !== this.prev.x || this.position.y !== this.prev.y) + { + this.angle = this.velocity.atan(); + } + + this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); + + // Now the State update will throw collision checks at the Body + // And finally we'll integrate the new position back to the Sprite in postUpdate + + if (this.collideWorldBounds) + { + if (this.checkWorldBounds() && this.onWorldBounds) + { + this.onWorldBounds.dispatch(this.sprite, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); + } + } + } + + this._dx = this.deltaX(); + this._dy = this.deltaY(); + + this._reset = false; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateMovement + * @protected + */ + updateMovement: function () { + + var percent = 0; + var collided = (this.overlapX !== 0 || this.overlapY !== 0); + + // Duration or Distance based? + + if (this.moveDuration > 0) + { + this.moveTimer += this.game.time.elapsedMS; + + percent = this.moveTimer / this.moveDuration; + } + else + { + this.moveTarget.end.set(this.position.x, this.position.y); + + percent = this.moveTarget.length / this.moveDistance; + } + + if (this.movementCallback) + { + var result = this.movementCallback.call(this.movementCallbackContext, this, this.velocity, percent); + } + + if (collided || percent >= 1 || (result !== undefined && result !== true)) + { + this.stopMovement((percent >= 1) || (this.stopVelocityOnCollide && collided)); + return false; + } + + return true; + + }, + + /** + * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it + * has Body.isMoving true), then calling this method will stop the movement before + * either the duration or distance counters expire. + * + * The `onMoveComplete` signal is dispatched. + * + * @method Phaser.Physics.Arcade.Body#stopMovement + * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero? + */ + stopMovement: function (stopVelocity) { + + if (this.isMoving) + { + this.isMoving = false; + + if (stopVelocity) + { + this.velocity.set(0); + } + + // Send the Sprite this Body belongs to + // and a boolean indicating if it stopped because of a collision or not + this.onMoveComplete.dispatch(this.sprite, (this.overlapX !== 0 || this.overlapY !== 0)); + } + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @protected + */ + postUpdate: function () { + + // Only allow postUpdate to be called once per frame + if (!this.enable || !this.dirty) + { + return; + } + + // Moving? + if (this.isMoving) + { + this.updateMovement(); + } + + this.dirty = false; + + 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.position.x += this._dx; + this.sprite.position.y += this._dy; + this._reset = true; + } + + this.updateCenter(); + + if (this.allowRotation) + { + this.sprite.angle += this.deltaZ(); + } + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @protected + * @return {boolean} True if the Body collided with the world bounds, otherwise false. + */ + checkWorldBounds: function () { + + var pos = this.position; + var bounds = this.game.physics.arcade.bounds; + var check = this.game.physics.arcade.checkCollision; + + var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; + var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; + + if (pos.x < bounds.x && check.left) + { + pos.x = bounds.x; + this.velocity.x *= bx; + this.blocked.left = true; + this.blocked.none = false; + } + else if (this.right > bounds.right && check.right) + { + pos.x = bounds.right - this.width; + this.velocity.x *= bx; + this.blocked.right = true; + this.blocked.none = false; + } + + if (pos.y < bounds.y && check.up) + { + pos.y = bounds.y; + this.velocity.y *= by; + this.blocked.up = true; + this.blocked.none = false; + } + else if (this.bottom > bounds.bottom && check.down) + { + pos.y = bounds.bottom - this.height; + this.velocity.y *= by; + this.blocked.down = true; + this.blocked.none = false; + } + + return !this.blocked.none; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal timer, and then + * monitoring the duration each frame. When the duration is up the movement is + * stopped and the `Body.onMoveComplete` signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * You can optionally set a speed in pixels per second. If not specified it + * will use the current `Body.speed` value. If this is zero, the function will return false. + * + * Please note that due to browser timings you should allow for a variance in + * when the duration will actually expire. Depending on system it may be as much as + * +- 50ms. Also this method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveFrom + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveFrom: function (duration, speed, direction) { + + if (speed === undefined) { speed = this.speed; } + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + this.moveTimer = 0; + this.moveDuration = duration; + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal distance counter. + * The distance is monitored each frame. When the distance equals the distance + * specified in this call, the movement is stopped, and the `Body.onMoveComplete` + * signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * Please note that due to browser timings you should allow for a variance in + * when the distance will actually expire. + * + * Note: This method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveTo + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} distance - The distance, in pixels, the Body will move. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveTo: function (duration, distance, direction) { + + var speed = distance / (duration / 1000); + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + distance = Math.abs(distance); + + this.moveDuration = 0; + this.moveDistance = distance; + + if (this.moveTarget === null) + { + this.moveTarget = new Phaser.Line(); + this.moveEnd = new Phaser.Point(); + } + + this.moveTarget.fromAngle(this.x, this.y, angle, distance); + + this.moveEnd.set(this.moveTarget.end.x, this.moveTarget.end.y); + + this.moveTarget.setTo(this.x, this.y, this.x, this.y); + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * You can modify the size of the physics Body to be any dimension you need. + * This allows you to make it smaller, or larger, than the parent Sprite. You + * can also control the x and y offset of the Body. + * + * The width, height, and offset arguments are relative to the Sprite + * _texture_ and are scaled with the Sprite's {@link Phaser.Sprite#scale} + * (but **not** the scale of any ancestors or the {@link Phaser.Camera#scale + * Camera scale}). + * + * For example: If you have a Sprite with a texture that is 80x100 in size, + * and you want the physics body to be 32x32 pixels in the middle of the + * texture, you would do: + * + * `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, + * 34)` + * + * Where the first two parameters are the new Body size (32x32 pixels) + * relative to the Sprite's scale. 24 is the horizontal offset of the Body + * from the top-left of the Sprites texture, and 34 is the vertical offset. + * + * If you've scaled a Sprite by altering its `width`, `height`, or `scale` + * and you want to position the Body relative to the Sprite's dimensions + * (which will differ from its texture's dimensions), you should divide these + * arguments by the Sprite's current scale: + * + * `setSize(32 / sprite.scale.x, 32 / sprite.scale.y)` + * + * Calling `setSize` on a Body that has already had `setCircle` will reset + * all of the Circle properties, making this Body rectangular again. + * @method Phaser.Physics.Arcade.Body#setSize + * @param {number} width - The width of the Body, relative to the Sprite's + * texture. + * @param {number} height - The height of the Body, relative to the Sprite's + * texture. + * @param {number} [offsetX] - The X offset of the Body from the left of the + * Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the + * Sprite's texture. + */ + setSize: function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { 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.updateCenter(); + + this.isCircle = false; + this.radius = 0; + + }, + + /** + * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. + * The radius is given in pixels (relative to the Sprite's _texture_) and is the distance from the center of the circle to the edge. + * + * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite's texture. + * + * To change a Body back to being rectangular again call `Body.setSize`. + * + * Note: Circular collision only happens with other Arcade Physics bodies, it does not + * work against tile maps, where rectangular collision is the only method supported. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. + * @param {number} [offsetX] - The X offset of the Body from the left of the Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the Sprite's texture. + */ + setCircle: function (radius, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.isCircle = true; + this.radius = radius; + + this.sourceWidth = radius * 2; + this.sourceHeight = radius * 2; + + 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.updateCenter(); + } + else + { + this.isCircle = false; + } + + }, + + /** + * Resets all Body values (velocity, acceleration, rotation, etc) + * + * @method Phaser.Physics.Arcade.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new y position of the Body. + */ + reset: function (x, y) { + + this.stop(); + + this.position.x = (x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + this.rotation = this.sprite.angle; + this.preRotation = this.rotation; + + this.updateBounds(); + + this.updateCenter(); + + }, + + /** + * Sets acceleration, velocity, and {@link #speed} to 0. + * + * @method Phaser.Physics.Arcade.Body#stop + */ + stop: function () { + + this.velocity.set(0); + this.acceleration.set(0); + this.speed = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + + }, + + /** + * Returns the bounds of this physics body. + * + * Only used internally by the World collision methods. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @param {object} obj - The object in which to set the bounds values. + * @return {object} The object that was given to this method. + */ + getBounds: function (obj) { + + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + + }, + + /** + * Tests if a world point lies within this Body. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @param {number} x - The world x coordinate to test. + * @param {number} y - The world y coordinate to test. + * @return {boolean} True if the given coordinates are inside this Body, otherwise false. + */ + hitTest: function (x, y) { + + return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Returns true if the bottom of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onFloor: function () { + + return this.blocked.down; + + }, + + /** + * Returns true if the top of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onCeiling: function(){ + + return this.blocked.up; + + }, + + /** + * Returns true if either side of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onWall: function () { + + return (this.blocked.left || this.blocked.right); + + }, + + /** + * Returns the absolute delta x value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @return {number} The absolute delta value. + */ + deltaAbsX: function () { + + return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); + + }, + + /** + * Returns the absolute delta y value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @return {number} The absolute delta value. + */ + deltaAbsY: function () { + + return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); + + }, + + /** + * Returns the delta x value. The difference between Body.x now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. + */ + deltaX: function () { + + return this.position.x - this.prev.x; + + }, + + /** + * Returns the delta y value. The difference between Body.y now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. + */ + deltaY: function () { + + return this.position.y - this.prev.y; + + }, + + /** + * Returns the delta z value. The difference between Body.rotation now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise. + */ + deltaZ: function () { + + return this.rotation - this.preRotation; + + }, + + /** + * Destroys this Body. + * + * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. + * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. + * + * @method Phaser.Physics.Arcade.Body#destroy + */ + destroy: function () { + + if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group) + { + this.sprite.parent.removeFromHash(this.sprite); + } + + this.sprite.body = null; + this.sprite = null; + + } + +}; + +/** +* @name Phaser.Physics.Arcade.Body#left +* @property {number} left - The x position of the Body. The same as `Body.x`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "left", { + + get: function () { + + return this.position.x; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#right +* @property {number} right - The right value of this Body (same as Body.x + Body.width) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", { + + get: function () { + + return this.position.x + this.width; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#top +* @property {number} top - The y position of the Body. The same as `Body.y`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "top", { + + get: function () { + + return this.position.y; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#bottom +* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", { + + get: function () { + + return this.position.y + this.height; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#x +* @property {number} x - The x position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#y +* @property {number} y - The y position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + +}); + +/** +* Render Sprite Body. +* +* @method Phaser.Physics.Arcade.Body#render +* @param {object} context - The context to render to. +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string). +* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) +* @param {number} [lineWidth=1] - The width of the stroke when unfilled. +*/ +Phaser.Physics.Arcade.Body.render = function (context, body, color, filled, lineWidth) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0,255,0,0.4)'; + + context.fillStyle = color; + context.strokeStyle = color; + context.lineWidth = lineWidth || 1; + + if (body.isCircle) + { + context.beginPath(); + context.arc(body.center.x - body.game.camera.x, body.center.y - body.game.camera.y, body.halfWidth, 0, 2 * Math.PI); + + if (filled) + { + context.fill(); + } + else + { + context.stroke(); + } + } + else + { + if (filled) + { + context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + else + { + context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + } + +}; + +/** +* Render Sprite Body Physics Data as text. +* +* @method Phaser.Physics.Arcade.Body#renderBodyInfo +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {number} x - X position of the debug info to be rendered. +* @param {number} y - Y position of the debug info to be rendered. +* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). +*/ +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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics Tile map collision methods. +* +* @class Phaser.Physics.Arcade.TilemapCollision +* @constructor +*/ +Phaser.Physics.Arcade.TilemapCollision = function () {}; + +Phaser.Physics.Arcade.TilemapCollision.prototype = { + + /** + * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling. + */ + TILE_BIAS: 16, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!sprite.body) + { + return; + } + + var mapData = tilemapLayer.getTiles( + sprite.body.position.x - sprite.body.tilePadding.x - tilemapLayer.getTileOffsetX(), + sprite.body.position.y - sprite.body.tilePadding.y - tilemapLayer.getTileOffsetY(), + sprite.body.width + sprite.body.tilePadding.x, + sprite.body.height + sprite.body.tilePadding.y, + false, false); + + if (mapData.length === 0) + { + return; + } + + for (var i = 0; i < mapData.length; i++) + { + if (processCallback) + { + if (processCallback.call(callbackContext, sprite, mapData[i])) + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + else + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @private + * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer + * @param {Phaser.Group} group - The Group to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.children.length; i++) + { + if (group.children[i].exists) + { + this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * The core separation function to separate a physics body and a tile. + * + * @private + * @method Phaser.Physics.Arcade#separateTile + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to collide against. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {boolean} Returns true if the body was separated, otherwise false. + */ + separateTile: function (i, body, tile, tilemapLayer, overlapOnly) { + + if (!body.enable) + { + return false; + } + + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + // We re-check for collision in case body was separated in a previous step + if (!tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + // no collision so bail out (separated in a previous step) + return false; + } + else if (overlapOnly) + { + // There is an overlap, and we don't need to separate. Bail. + return true; + } + + // They overlap. Any custom callbacks? + + // A local callback always takes priority over a layer level callback + if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + else if (typeof tile.layer.callbacks !== 'undefined' && tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + + // We don't need to go any further if this tile doesn't actually separate + if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom) + { + // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation + return false; + } + + var ox = 0; + var oy = 0; + var minX = 0; + var minY = 1; + + if (body.deltaAbsX() > body.deltaAbsY()) + { + // Moving faster horizontally, check X axis first + minX = -1; + } + else if (body.deltaAbsX() < body.deltaAbsY()) + { + // Moving faster vertically, check Y axis first + minY = -1; + } + + if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom)) + { + // We only need do this if both axis have checking faces AND we're moving in both directions + minX = Math.min(Math.abs((body.position.x - tilemapLayerOffsetX) - tile.right), Math.abs((body.right - tilemapLayerOffsetX) - tile.left)); + minY = Math.min(Math.abs((body.position.y - tilemapLayerOffsetY) - tile.bottom), Math.abs((body.bottom - tilemapLayerOffsetY) - tile.top)); + } + + if (minX < minY) + { + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + + // That's horizontal done, check if we still intersects? If not then we can return now + if (ox !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + } + } + else + { + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + + // That's vertical done, check if we still intersects? If not then we can return now + if (oy !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + } + } + + return (ox !== 0 || oy !== 0); + + }, + + /** + * Check the body against the given tile on the X axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckX: function (body, tile, tilemapLayer) { + + var ox = 0; + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + + if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left) + { + // Body is moving LEFT + if (tile.faceRight && (body.x - tilemapLayerOffsetX) < tile.right) + { + ox = (body.x - tilemapLayerOffsetX) - tile.right; + + if (ox < -this.TILE_BIAS) + { + ox = 0; + } + } + } + else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right) + { + // Body is moving RIGHT + if (tile.faceLeft && (body.right - tilemapLayerOffsetX) > tile.left) + { + ox = (body.right - tilemapLayerOffsetX) - tile.left; + + if (ox > this.TILE_BIAS) + { + ox = 0; + } + } + } + + if (ox !== 0) + { + if (body.customSeparateX) + { + body.overlapX = ox; + } + else + { + this.processTileSeparationX(body, ox); + } + } + + return ox; + + }, + + /** + * Check the body against the given tile on the Y axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckY: function (body, tile, tilemapLayer) { + + var oy = 0; + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up) + { + // Body is moving UP + if (tile.faceBottom && (body.y - tilemapLayerOffsetY) < tile.bottom) + { + oy = (body.y - tilemapLayerOffsetY) - tile.bottom; + + if (oy < -this.TILE_BIAS) + { + oy = 0; + } + } + } + else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down) + { + // Body is moving DOWN + if (tile.faceTop && (body.bottom - tilemapLayerOffsetY) > tile.top) + { + oy = (body.bottom - tilemapLayerOffsetY) - tile.top; + + if (oy > this.TILE_BIAS) + { + oy = 0; + } + } + } + + if (oy !== 0) + { + if (body.customSeparateY) + { + body.overlapY = oy; + } + else + { + this.processTileSeparationY(body, oy); + } + } + + return oy; + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} x - The x separation amount. + */ + processTileSeparationX: function (body, x) { + + if (x < 0) + { + body.blocked.left = true; + body.blocked.none = false; + } + else if (x > 0) + { + body.blocked.right = true; + body.blocked.none = false; + } + + body.position.x -= x; + + if (body.bounce.x === 0) + { + body.velocity.x = 0; + } + else + { + body.velocity.x = -body.velocity.x * body.bounce.x; + } + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} y - The y separation amount. + */ + processTileSeparationY: function (body, y) { + + if (y < 0) + { + body.blocked.up = true; + body.blocked.none = false; + } + else if (y > 0) + { + body.blocked.down = true; + body.blocked.none = false; + } + + body.position.y -= y; + + if (body.bounce.y === 0) + { + body.velocity.y = 0; + } + else + { + body.velocity.y = -body.velocity.y * body.bounce.y; + } + + } + +}; + +// Merge this with the Arcade Physics prototype +Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Add an extra properties to p2 that we need +p2.Body.prototype.parent = null; +p2.Spring.prototype.parent = null; + +/** +* This is your main access to the P2 Physics World. +* From here you can create materials, listen for events and add bodies into the physics simulation. +* +* @class Phaser.Physics.P2 +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {object} [config] - Physics configuration object passed in from the game constructor. +*/ +Phaser.Physics.P2 = function (game, config) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + if (config === undefined) + { + config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; + } + else + { + if (!config.hasOwnProperty('gravity')) + { + config.gravity = [0, 0]; + } + + if (!config.hasOwnProperty('broadphase')) + { + config.broadphase = new p2.SAPBroadphase(); + } + } + + /** + * @property {object} config - The p2 World configuration object. + * @protected + */ + this.config = config; + + /** + * @property {p2.World} world - The p2 World in which the simulation is run. + * @protected + */ + this.world = new p2.World(this.config); + + /** + * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. + * @default + */ + this.frameRate = 1 / 60; + + /** + * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. + * @default + */ + this.useElapsedTime = false; + + /** + * @property {boolean} paused - The paused state of the P2 World. + * @default + */ + this.paused = false; + + /** + * @property {array} materials - A local array of all created Materials. + * @protected + */ + this.materials = []; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. + */ + this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); + + /** + * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * This signal is dispatched when a new Body is added to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world. + * + * @property {Phaser.Signal} onBodyAdded + */ + this.onBodyAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Body is removed to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world. + * + * @property {Phaser.Signal} onBodyRemoved + */ + this.onBodyRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is added to the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world. + * + * @property {Phaser.Signal} onSpringAdded + */ + this.onSpringAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is removed from the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world. + * + * @property {Phaser.Signal} onSpringRemoved + */ + this.onSpringRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is added to the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world. + * + * @property {Phaser.Signal} onConstraintAdded + */ + this.onConstraintAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is removed from the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world. + * + * @property {Phaser.Signal} onConstraintRemoved + */ + this.onConstraintRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is added to the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world. + * + * @property {Phaser.Signal} onContactMaterialAdded + */ + this.onContactMaterialAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is removed from the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world. + * + * @property {Phaser.Signal} onContactMaterialRemoved + */ + this.onContactMaterialRemoved = new Phaser.Signal(); + + /** + * @property {function} postBroadphaseCallback - A postBroadphase callback. + */ + this.postBroadphaseCallback = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are fired. + */ + this.callbackContext = null; + + /** + * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done. + * + * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done. + * + * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + // Pixel to meter function overrides + if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) + { + this.mpx = config.mpx; + this.mpxi = config.mpxi; + this.pxm = config.pxm; + this.pxmi = config.pxmi; + } + + // Hook into the World events + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + /** + * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. + */ + this.collisionGroups = []; + + /** + * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. + */ + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. + */ + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. + */ + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + /** + * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. + */ + this.boundsCollidesWith = []; + + /** + * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. + * @private + */ + this._toRemove = []; + + /** + * @property {number} _collisionGroupID - Internal var. + * @private + */ + this._collisionGroupID = 2; + + /** + * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsLeft = true; + + /** + * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsRight = true; + + /** + * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsTop = true; + + /** + * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsBottom = true; + + /** + * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsOwnGroup = false; + + // By default we want everything colliding with everything + this.setBoundsToWorld(true, true, true, true, false); + +}; + +Phaser.Physics.P2.prototype = { + + /** + * This will add a P2 Physics body into the removal list for the next step. + * + * @method Phaser.Physics.P2#removeBodyNextStep + * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. + */ + removeBodyNextStep: function (body) { + + this._toRemove.push(body); + + }, + + /** + * Called at the start of the core update loop. Purges flagged bodies from the world. + * + * @method Phaser.Physics.P2#preUpdate + */ + preUpdate: function () { + + var i = this._toRemove.length; + + while (i--) + { + this.removeBody(this._toRemove[i]); + } + + this._toRemove.length = 0; + + }, + + /** + * This will create a P2 Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. + * + * @method Phaser.Physics.P2#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [debug=false] - Create a debug object to go with this body? + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, debug, children) { + + if (debug === undefined) { debug = false; } + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + this.enable(object[i].children, debug, children); + } + else + { + this.enableBody(object[i], debug); + + if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) + { + this.enable(object[i], debug, true); + } + } + } + } + else + { + if (object instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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); + } + } + } + + }, + + /** + * Creates a P2 Physics body on the given game object. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * @method Phaser.Physics.P2#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + * @param {boolean} debug - Create a debug object to go with this body? + */ + 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; + if (typeof object.anchor !== 'undefined') { + object.anchor.set(0.5); + } + } + + }, + + /** + * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. + * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. + * + * @method Phaser.Physics.P2#setImpactEvents + * @param {boolean} state - Set to true to enable impact events, or false to disable. + */ + setImpactEvents: function (state) { + + if (state) + { + this.world.on("impact", this.impactHandler, this); + } + else + { + this.world.off("impact", this.impactHandler, this); + } + + }, + + /** + * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. + * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. + * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. + * Returning `true` from the callback will ensure they are checked in the narrowphase. + * + * @method Phaser.Physics.P2#setPostBroadphaseCallback + * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. + * @param {object} context - The context under which the callback will be fired. + */ + 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); + } + + }, + + /** + * Internal handler for the postBroadphase event. + * + * @method Phaser.Physics.P2#postBroadphaseHandler + * @private + * @param {object} event - The event data. + */ + postBroadphaseHandler: function (event) { + + if (!this.postBroadphaseCallback || event.pairs.length === 0) + { + return; + } + + for (var i = event.pairs.length - 2; i >= 0; 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); + } + } + + }, + + /** + * Handles a p2 impact event. + * + * @method Phaser.Physics.P2#impactHandler + * @private + * @param {object} event - The event data. + */ + impactHandler: function (event) { + + if (event.bodyA.parent && event.bodyB.parent) + { + // Body vs. Body callbacks + 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); + } + + // Body vs. Group callbacks + 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); + } + } + + }, + + /** + * Handles a p2 begin contact event. + * + * @method Phaser.Physics.P2#beginContactHandler + * @param {object} event - The event data. + */ + beginContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + 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.bodyB, event.shapeA, event.shapeB, event.contactEquations); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations); + } + } + + }, + + /** + * Handles a p2 end contact event. + * + * @method Phaser.Physics.P2#endContactHandler + * @param {object} event - The event data. + */ + endContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); + + if (event.bodyA.parent) + { + event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA); + } + } + + }, + + /** + * Sets the bounds of the Physics world to match the Game.World dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * + * @method Phaser.Physics#setBoundsToWorld + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + 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); + + }, + + /** + * Sets the given material against the 4 bounds of this World. + * + * @method Phaser.Physics#setWorldMaterial + * @param {Phaser.Physics.P2.Material} material - The material to set. + * @param {boolean} [left=true] - If true will set the material on the left bounds wall. + * @param {boolean} [right=true] - If true will set the material on the right bounds wall. + * @param {boolean} [top=true] - If true will set the material on the top bounds wall. + * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. + */ + setWorldMaterial: function (material, left, right, top, bottom) { + + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (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; + } + + }, + + /** + * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. + * If you start to use your own collision groups then your objects will no longer collide with the bounds. + * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. + * + * @method Phaser.Physics.P2#updateBoundsCollisionGroup + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + updateBoundsCollisionGroup: function (setCollisionGroup) { + + if (setCollisionGroup === undefined) { setCollisionGroup = true; } + + var mask = (setCollisionGroup) ? this.boundsCollisionGroup.mask : this.everythingCollisionGroup.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; + } + + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.P2#setBounds + * @param {number} x - The x coordinate of the top-left corner of the bounds. + * @param {number} y - The y coordinate of the top-left corner of the bounds. + * @param {number} width - The width of the bounds. + * @param {number} height - The height of the bounds. + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { + + if (left === undefined) { left = this._boundsLeft; } + if (right === undefined) { right = this._boundsRight; } + if (top === undefined) { top = this._boundsTop; } + if (bottom === undefined) { bottom = this._boundsBottom; } + if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; } + + this.setupWall(left, 'left', x, y, 1.5707963267948966, setCollisionGroup); + this.setupWall(right, 'right', x + width, y, -1.5707963267948966, setCollisionGroup); + this.setupWall(top, 'top', x, y, -3.141592653589793, setCollisionGroup); + this.setupWall(bottom, 'bottom', x, y + height, 0, setCollisionGroup); + + // Remember the bounds settings in case they change later on via World.setBounds + this._boundsLeft = left; + this._boundsRight = right; + this._boundsTop = top; + this._boundsBottom = bottom; + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Internal method called by setBounds. Responsible for creating, updating or + * removing the wall body shapes. + * + * @method Phaser.Physics.P2#setupWall + * @private + * @param {boolean} create - True to create the wall shape, false to remove it. + * @param {string} wall - The wall segment to update. + * @param {number} x - The x coordinate of the wall. + * @param {number} y - The y coordinate of the wall. + * @param {float} angle - The angle of the wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setupWall: function (create, wall, x, y, angle, setCollisionGroup) { + + if (create) + { + // We need a left wall. Do we have one already? + if (this.walls[wall]) + { + this.walls[wall].position = [ this.pxmi(x), this.pxmi(y) ]; + } + else + { + this.walls[wall] = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: angle }); + this.walls[wall].addShape(new p2.Plane()); + + this.world.addBody(this.walls[wall]); + } + + if (setCollisionGroup) + { + this.walls[wall].shapes[0].collisionGroup = this.boundsCollisionGroup.mask; + } + } + else + { + if (this.walls[wall]) + { + this.world.removeBody(this.walls[wall]); + this.walls[wall] = null; + } + } + + }, + + /** + * Pauses the P2 World independent of the game pause state. + * + * @method Phaser.Physics.P2#pause + */ + pause: function() { + + this.paused = true; + + }, + + /** + * Resumes a paused P2 World. + * + * @method Phaser.Physics.P2#resume + */ + resume: function() { + + this.paused = false; + + }, + + /** + * Internal P2 update loop. + * + * @method Phaser.Physics.P2#update + */ + update: function () { + + // Do nothing if the physics engine was paused before + if (this.paused) + { + return; + } + + if (this.useElapsedTime) + { + this.world.step(this.game.time.physicsElapsed); + } + else + { + this.world.step(this.frameRate); + } + + }, + + /** + * Called by Phaser.Physics when a State swap occurs. + * Starts the begin and end Contact listeners again. + * + * @method Phaser.Physics.P2#reset + */ + reset: function () { + + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + this._collisionGroupID = 2; + + this.setBoundsToWorld(true, true, true, true, false); + + }, + + /** + * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. + * + * The P2 world is also cleared: + * + * * Removes all solver equations + * * Removes all constraints + * * Removes all bodies + * * Removes all springs + * * Removes all contact materials + * + * This is called automatically when you switch state. + * + * @method Phaser.Physics.P2#clear + */ + clear: function () { + + this.world.time = 0; + this.world.fixedStepTime = 0; + + // Remove all solver equations + if (this.world.solver && this.world.solver.equations.length) + { + this.world.solver.removeAllEquations(); + } + + // Remove all constraints + var cs = this.world.constraints; + + for (var i = cs.length - 1; i >= 0; i--) + { + this.world.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.world.bodies; + + for (var i = bodies.length - 1; i >= 0; i--) + { + this.world.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.world.springs; + + for (var i = springs.length - 1; i >= 0; i--) + { + this.world.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.world.contactMaterials; + + for (var i = cms.length - 1; i >= 0; i--) + { + this.world.removeContactMaterial(cms[i]); + } + + 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.boundsCollidesWith = []; + + // Remove the world bounds + this.walls = { left: null, right: null, top: null, bottom: null }; + + }, + + /** + * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. + * + * @method Phaser.Physics.P2#destroy + */ + destroy: function () { + + this.clear(); + + this.game = null; + + }, + + /** + * Add a body to the world. + * + * @method Phaser.Physics.P2#addBody + * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. + * @return {boolean} True if the Body was added successfully, otherwise false. + */ + addBody: function (body) { + + if (body.data.world) + { + return false; + } + else + { + this.world.addBody(body.data); + + this.onBodyAdded.dispatch(body); + + return true; + } + + }, + + /** + * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. + * + * @method Phaser.Physics.P2#removeBody + * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. + * @return {Phaser.Physics.P2.Body} The Body that was removed. + */ + removeBody: function (body) { + + if (body.data.world === this.world) + { + this.world.removeBody(body.data); + + this.onBodyRemoved.dispatch(body); + } + + return body; + + }, + + /** + * Adds a Spring to the world. + * + * @method Phaser.Physics.P2#addSpring + * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was added. + */ + addSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.addSpring(spring.data); + } + else + { + this.world.addSpring(spring); + } + + this.onSpringAdded.dispatch(spring); + + return spring; + + }, + + /** + * Removes a Spring from the world. + * + * @method Phaser.Physics.P2#removeSpring + * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was removed. + */ + removeSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.removeSpring(spring.data); + } + else + { + this.world.removeSpring(spring); + } + + this.onSpringRemoved.dispatch(spring); + + return spring; + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createDistanceConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} distance - The distance to keep between the bodies. + * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. + * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.DistanceConstraint} The constraint + */ + createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, 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, localAnchorA, localAnchorB, maxForce)); + } + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createGearConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [angle=0] - The relative angle + * @param {number} [ratio=1] - The gear ratio. + * @return {Phaser.Physics.P2.GearConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * The pivot points are given in world (pixel) coordinates. + * + * @method Phaser.Physics.P2#createRevoluteConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. + * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint + */ + createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + 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, worldPivot)); + } + + }, + + /** + * Locks the relative position between two bodies. + * + * @method Phaser.Physics.P2#createLockConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.LockConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Constraint that only allows bodies to move along a line, relative to each other. + * See http://www.iforce2d.net/b2dtut/joints-prismatic + * + * @method Phaser.Physics.P2#createPrismaticConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. + * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Adds a Constraint to the world. + * + * @method Phaser.Physics.P2#addConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. + */ + addConstraint: function (constraint) { + + this.world.addConstraint(constraint); + + this.onConstraintAdded.dispatch(constraint); + + return constraint; + + }, + + /** + * Removes a Constraint from the world. + * + * @method Phaser.Physics.P2#removeConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. + */ + removeConstraint: function (constraint) { + + this.world.removeConstraint(constraint); + + this.onConstraintRemoved.dispatch(constraint); + + return constraint; + + }, + + /** + * Adds a Contact Material to the world. + * + * @method Phaser.Physics.P2#addContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. + */ + addContactMaterial: function (material) { + + this.world.addContactMaterial(material); + + this.onContactMaterialAdded.dispatch(material); + + return material; + + }, + + /** + * Removes a Contact Material from the world. + * + * @method Phaser.Physics.P2#removeContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. + */ + removeContactMaterial: function (material) { + + this.world.removeContactMaterial(material); + + this.onContactMaterialRemoved.dispatch(material); + + return material; + + }, + + /** + * Gets a Contact Material based on the two given Materials. + * + * @method Phaser.Physics.P2#getContactMaterial + * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. + * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. + * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. + */ + getContactMaterial: function (materialA, materialB) { + + return this.world.getContactMaterial(materialA, materialB); + + }, + + /** + * Sets the given Material against all Shapes owned by all the Bodies in the given array. + * + * @method Phaser.Physics.P2#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. + * @param {array} bodies - An Array of Body objects that the given Material will be set on. + */ + setMaterial: function (material, bodies) { + + var i = bodies.length; + + while (i--) + { + bodies[i].setMaterial(material); + } + + }, + + /** + * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). + * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. + * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. + * + * @method Phaser.Physics.P2#createMaterial + * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. + * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. + * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. + */ + 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; + + }, + + /** + * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. + * + * @method Phaser.Physics.P2#createContactMaterial + * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {object} [options] - Material options object. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. + */ + createContactMaterial: function (materialA, materialB, options) { + + if (materialA === undefined) { materialA = this.createMaterial(); } + if (materialB === undefined) { materialB = this.createMaterial(); } + + var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); + + return this.addContactMaterial(contact); + + }, + + /** + * Populates and returns an array with references to of all current Bodies in the world. + * + * @method Phaser.Physics.P2#getBodies + * @return {array} An array containing all current Bodies in the world. + */ + getBodies: function () { + + var output = []; + var i = this.world.bodies.length; + + while (i--) + { + output.push(this.world.bodies[i].parent); + } + + return output; + + }, + + /** + * Checks the given object to see if it has a p2.Body and if so returns it. + * + * @method Phaser.Physics.P2#getBody + * @param {object} object - The object to check for a p2.Body on. + * @return {p2.Body} The p2.Body, or null if not found. + */ + getBody: function (object) { + + if (object instanceof p2.Body) + { + // Native p2 body + return object; + } + else if (object instanceof Phaser.Physics.P2.Body) + { + // Phaser P2 Body + return object.data; + } + else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) + { + // Sprite, TileSprite, etc + return object.body.data; + } + + return null; + + }, + + /** + * Populates and returns an array of all current Springs in the world. + * + * @method Phaser.Physics.P2#getSprings + * @return {array} An array containing all current Springs in the world. + */ + getSprings: function () { + + var output = []; + var i = this.world.springs.length; + + while (i--) + { + output.push(this.world.springs[i].parent); + } + + return output; + + }, + + /** + * Populates and returns an array of all current Constraints in the world. + * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain + * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type. + * + * @method Phaser.Physics.P2#getConstraints + * @return {array} An array containing all current Constraints in the world. + */ + getConstraints: function () { + + var output = []; + var i = this.world.constraints.length; + + while (i--) + { + output.push(this.world.constraints[i]); + } + + return output; + + }, + + /** + * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to + * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. + * + * @method Phaser.Physics.P2#hitTest + * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. + * @param {Array} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) + * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. + * @return {Array} Array of bodies that overlap the point. + */ + hitTest: function (worldPoint, bodies, precision, filterStatic) { + + if (bodies === undefined) { bodies = this.world.bodies; } + if (precision === undefined) { precision = 5; } + if (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.type === p2.Body.STATIC)) + { + query.push(bodies[i].data); + } + else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC)) + { + query.push(bodies[i]); + } + else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC)) + { + query.push(bodies[i].body.data); + } + } + + return this.world.hitTest(physicsPosition, query, precision); + + }, + + /** + * Converts the current world into a JSON object. + * + * @method Phaser.Physics.P2#toJSON + * @return {object} A JSON representation of the world. + */ + toJSON: function () { + + return this.world.toJSON(); + + }, + + /** + * Creates a new Collision Group and optionally applies it to the given object. + * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. + * + * @method Phaser.Physics.P2#createCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + */ + 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; + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. + * + * @method Phaser.Physics.P2y#setCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + */ + setCollisionGroup: function (object, group) { + + if (object instanceof Phaser.Group) + { + for (var i = 0; i < object.total; i++) + { + if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) + { + object.children[i].body.setCollisionGroup(group); + } + } + } + else + { + object.body.setCollisionGroup(group); + } + + }, + + /** + * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restLength=1] - Rest length of the spring. A number > 0. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @return {Phaser.Physics.P2.Spring} The spring + */ + createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); + } + + }, + + /** + * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createRotationalSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @return {Phaser.Physics.P2.RotationalSpring} The spring + */ + createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Rotational Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping)); + } + + }, + + /** + * Creates a new Body and adds it to the World. + * + * @method Phaser.Physics.P2#createBody + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {Phaser.Physics.P2.Body} The body + */ + createBody: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Creates a new Particle and adds it to the World. + * + * @method Phaser.Physics.P2#createParticle + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + */ + createParticle: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Converts all of the polyline, polygon, and rectangle objects inside a Tiled ObjectGroup into physics bodies that are added to the world. + * Note that the polylines and polygons must be created in such a way that they can withstand polygon decomposition. + * + * @method Phaser.Physics.P2#convertCollisionObjects + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. + * @return {array} An array of the Phaser.Physics.Body objects that have been created. + */ + convertCollisionObjects: function (map, layer, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var output = []; + + for (var i = 0, len = map.collision[layer].length; i < len; i++) + { + // name: json.layers[i].objects[v].name, + // x: json.layers[i].objects[v].x, + // y: json.layers[i].objects[v].y, + // width: json.layers[i].objects[v].width, + // height: json.layers[i].objects[v].height, + // visible: json.layers[i].objects[v].visible, + // properties: json.layers[i].objects[v].properties, + // polyline: json.layers[i].objects[v].polyline + + var object = map.collision[layer][i]; + var shapeData = object.polyline || object.polygon; + + // polyline/polygon shape data present + if (shapeData) + { + var body = this.createBody(object.x, object.y, 0, addToWorld, {}, shapeData); + } + + // tilemap parser sets rectangle=true when parsing object groups + else if (object.rectangle) + { + var body = this.createBody(object.x, object.y, 0, addToWorld); + body.addRectangle(object.width, object.height, object.width / 2, object.height / 2); + } + + // ellipse could be added here, but Tiled ellipses use height/width instead of radius + // (to support oblong ellipses), which p2 doesn't currently support. + + if (body) + { + output.push(body); + } + } + + return output; + + }, + + /** + * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. + * + * @method Phaser.Physics.P2#clearTilemapLayerBodies + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + */ + 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 = 0; + + }, + + /** + * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. + * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. + * Every time you call this method it will destroy any previously created bodies and remove them from the world. + * Therefore understand it's a very expensive operation and not to be done in a core game update loop. + * + * @method Phaser.Physics.P2#convertTilemap + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. + * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. + * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. + */ + convertTilemap: function (map, layer, addToWorld, optimize) { + + layer = map.getLayer(layer); + + if (addToWorld === undefined) { addToWorld = true; } + if (optimize === undefined) { optimize = true; } + + // If the bodies array is already populated we need to nuke it + this.clearTilemapLayerBodies(map, layer); + + var width = 0; + var sx = 0; + var sy = 0; + + for (var y = 0, h = map.layers[layer].height; y < h; y++) + { + width = 0; + + for (var x = 0, w = map.layers[layer].width; x < w; x++) + { + var tile = map.layers[layer].data[y][x]; + + if (tile && tile.index > -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; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpx + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpx: function (v) { + + return v *= 20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters). + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxm + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxm: function (v) { + + return v * 0.05; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpxi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpxi: function (v) { + + return v *= -20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters) and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxmi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxmi: function (v) { + + return v * -0.05; + + } + +}; + +/** +* @name Phaser.Physics.P2#friction +* @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { + + get: function () { + + return this.world.defaultContactMaterial.friction; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.friction = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#restitution +* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { + + get: function () { + + return this.world.defaultContactMaterial.restitution; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.restitution = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#contactMaterial +* @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { + + get: function () { + + return this.world.defaultContactMaterial; + + }, + + set: function (value) { + + this.world.defaultContactMaterial = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applySpringForces +* @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { + + get: function () { + + return this.world.applySpringForces; + + }, + + set: function (value) { + + this.world.applySpringForces = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyDamping +* @property {boolean} applyDamping - Enable to automatically apply body damping each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { + + get: function () { + + return this.world.applyDamping; + + }, + + set: function (value) { + + this.world.applyDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyGravity +* @property {boolean} applyGravity - Enable to automatically apply gravity each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { + + get: function () { + + return this.world.applyGravity; + + }, + + set: function (value) { + + this.world.applyGravity = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#solveConstraints +* @property {boolean} solveConstraints - Enable/disable constraint solving in each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { + + get: function () { + + return this.world.solveConstraints; + + }, + + set: function (value) { + + this.world.solveConstraints = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#time +* @property {boolean} time - The World time. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "time", { + + get: function () { + + return this.world.time; + + } + +}); + +/** +* @name Phaser.Physics.P2#emitImpactEvent +* @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { + + get: function () { + + return this.world.emitImpactEvent; + + }, + + set: function (value) { + + this.world.emitImpactEvent = value; + + } + +}); + +/** +* How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. +* If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. +* @name Phaser.Physics.P2#sleepMode +* @property {number} sleepMode +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", { + + get: function () { + + return this.world.sleepMode; + + }, + + set: function (value) { + + this.world.sleepMode = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#total +* @property {number} total - The total number of bodies in the world. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "total", { + + get: function () { + + return this.world.bodies.length; + + } + +}); + +/* jshint noarg: false */ + +/** +* @author Georgios Kaleadis https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Allow to access a list of created fixture (coming from Body#addPhaserPolygon) +* which itself parse the input from PhysicsEditor with the custom phaser exporter. +* You can access fixtures of a Body by a group index or even by providing a fixture Key. + +* You can set the fixture key and also the group index for a fixture in PhysicsEditor. +* This gives you the power to create a complex body built of many fixtures and modify them +* during runtime (to remove parts, set masks, categories & sensor properties) +* +* @class Phaser.Physics.P2.FixtureList +* @constructor +* @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) +*/ +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 = { + + /** + * @method Phaser.Physics.P2.FixtureList#init + */ + init: function () { + + /** + * @property {object} namedFixtures - Collect all fixtures with a key + * @private + */ + this.namedFixtures = {}; + + /** + * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group + * @private + */ + this.groupedFixtures = []; + + /** + * @property {Array} allFixtures - This is a list of everything in this collection + * @private + */ + this.allFixtures = []; + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setCategory + * @param {number} bit - The bit to set as the collision group. + * @param {string} fixtureKey - Only apply to the fixture with the given key. + */ + setCategory: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionGroup = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMask + * @param {number} bit - The bit to set as the collision mask + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMask: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionMask = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setSensor + * @param {boolean} value - sensor true or false + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setSensor: function (value, fixtureKey) { + + var setter = function(fixture) { + fixture.sensor = value; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMaterial + * @param {Object} material - The contact material for a fixture + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMaterial: function (material, fixtureKey) { + + var setter = function(fixture) { + fixture.material = material; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * Accessor to get either a list of specified fixtures by key or the whole fixture list + * + * @method Phaser.Physics.P2.FixtureList#getFixtures + * @param {array} keys - A list of fixture keys + */ + 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; + } + + }, + + /** + * Accessor to get either a single fixture by its key. + * + * @method Phaser.Physics.P2.FixtureList#getFixtureByKey + * @param {string} key - The key of the fixture. + */ + getFixtureByKey: function (key) { + + return this.namedFixtures[key]; + + }, + + /** + * Accessor to get a group of fixtures by its group index. + * + * @method Phaser.Physics.P2.FixtureList#getGroup + * @param {number} groupID - The group index. + */ + getGroup: function (groupID) { + + return this.groupedFixtures[groupID]; + + }, + + /** + * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon + * + * @method Phaser.Physics.P2.FixtureList#parse + */ + 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)); + } + + }, + + /** + * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. + * + * @method Phaser.Physics.P2.FixtureList#flatten + * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. + */ + 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; + + } + +}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. +* +* @class Phaser.Physics.P2.PointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.PointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; + +/** +* @name Phaser.Physics.P2.PointProxy#x +* @property {number} x - The x property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { + + get: function () { + + return this.world.mpx(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#y +* @property {number} y - The y property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { + + get: function () { + + return this.world.mpx(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#mx +* @property {number} mx - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#my +* @property {number} my - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. +* +* @class Phaser.Physics.P2.InversePointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.InversePointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; + +/** +* @name Phaser.Physics.P2.InversePointProxy#x +* @property {number} x - The x property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#y +* @property {number} y - The y property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#mx +* @property {number} mx - The x property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = -value; + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#my +* @property {number} my - The y property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = -value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. +* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. +* In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. +* By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. +* Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. +* Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. +* +* @class Phaser.Physics.P2.Body +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. +* @param {number} [x=0] - The x coordinate of this Body. +* @param {number} [y=0] - The y coordinate of this Body. +* @param {number} [mass=1] - The default mass of this Body (0 = static). +*/ +Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { + + sprite = sprite || null; + x = x || 0; + y = y || 0; + if (mass === undefined) { mass = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to the P2 World. + */ + this.world = game.physics.p2; + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.P2JS; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. + */ + this.offset = new Phaser.Point(); + + /** + * @property {p2.Body} data - The p2 Body data. + * @protected + */ + this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); + + this.data.parent = this; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. + */ + this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); + + /** + * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body. + */ + this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); + + /** + * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. + */ + this.gravity = new Phaser.Point(); + + /** + * Dispatched when a first contact is created between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 5 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body is in contact with. + * The Shape from this body that caused the contact. + * The Shape from the contact body. + * The Contact Equation data array. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * Dispatched when contact ends between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 4 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body has ended contact with. + * The Shape from this body that caused the original contact. + * The Shape from the contact body. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + /** + * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. + */ + this.collidesWith = []; + + /** + * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. + */ + this.removeNextStep = false; + + /** + * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. + */ + this.debugBody = null; + + /** + * @property {boolean} dirty - Internally used by Sprite.x/y + */ + this.dirty = false; + + /** + * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. + * @private + */ + this._collideWorldBounds = true; + + /** + * @property {object} _bodyCallbacks - Array of Body callbacks. + * @private + */ + this._bodyCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Body callback contexts. + * @private + */ + this._bodyCallbackContext = {}; + + /** + * @property {object} _groupCallbacks - Array of Group callbacks. + * @private + */ + this._groupCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. + * @private + */ + this._groupCallbackContext = {}; + + /** + * @property {boolean} _reset - Internal var. + * @private + */ + this._reset = false; + + // Set-up the default shape + if (sprite) + { + this.setRectangleFromSprite(sprite); + + if (sprite.exists) + { + this.game.physics.p2.addBody(this); + } + } + +}; + +Phaser.Physics.P2.Body.prototype = { + + /** + * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createBodyCallback + * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + 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; + } + } + + }, + + /** + * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * This callback will only fire if this Body has been assigned a collision group. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createGroupCallback + * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + createGroupCallback: function (group, callback, callbackContext) { + + if (callback === null) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + else + { + this._groupCallbacks[group.mask] = callback; + this._groupCallbackContext[group.mask] = callbackContext; + } + + }, + + /** + * Gets the collision bitmask from the groups this body collides with. + * + * @method Phaser.Physics.P2.Body#getCollisionMask + * @return {number} The bitmask. + */ + getCollisionMask: function () { + + var mask = 0; + + if (this._collideWorldBounds) + { + mask = this.game.physics.p2.boundsCollisionGroup.mask; + } + + for (var i = 0; i < this.collidesWith.length; i++) + { + mask = mask | this.collidesWith[i].mask; + } + + return mask; + + }, + + /** + * Updates the collisionMask. + * + * @method Phaser.Physics.P2.Body#updateCollisionMask + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + updateCollisionMask: function (shape) { + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * This also resets the collisionMask. + * + * @method Phaser.Physics.P2.Body#setCollisionGroup + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + setCollisionGroup: function (group, shape) { + + var mask = this.getCollisionMask(); + + if (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; + } + + }, + + /** + * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. + * + * @method Phaser.Physics.P2.Body#clearCollision + * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? + * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. + */ + clearCollision: function (clearGroup, clearMask, shape) { + + if (clearGroup === undefined) { clearGroup = true; } + if (clearMask === undefined) { clearMask = true; } + + if (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; + } + + }, + + /** + * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#removeCollisionGroup + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore. + * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body. + */ + removeCollisionGroup: function (group, clearCallback, shape) { + + if (clearCallback === undefined) { clearCallback = true; } + + var index; + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + index = this.collidesWith.indexOf(group[i]); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + } + else + { + index = this.collidesWith.indexOf(group); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#collides + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. + * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. + * @param {object} [callbackContext] - The context under which the callback will be called. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. + */ + collides: function (group, callback, callbackContext, shape) { + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + if (this.collidesWith.indexOf(group[i]) === -1) + { + this.collidesWith.push(group[i]); + + if (callback) + { + this.createGroupCallback(group[i], callback, callbackContext); + } + } + } + } + else + { + if (this.collidesWith.indexOf(group) === -1) + { + this.collidesWith.push(group); + + if (callback) + { + this.createGroupCallback(group, callback, callbackContext); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Moves the shape offsets so their center of mass becomes the body center of mass. + * + * @method Phaser.Physics.P2.Body#adjustCenterOfMass + */ + adjustCenterOfMass: function () { + + this.data.adjustCenterOfMass(); + this.shapeChanged(); + + }, + + /** + * Gets the velocity of a point in the body. + * + * @method Phaser.Physics.P2.Body#getVelocityAtPoint + * @param {Array} result - A vector to store the result in. + * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from. + * @return {Array} The result vector. + */ + getVelocityAtPoint: function (result, relativePoint) { + + return this.data.getVelocityAtPoint(result, relativePoint); + + }, + + /** + * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. + * + * @method Phaser.Physics.P2.Body#applyDamping + * @param {number} dt - Current time step. + */ + applyDamping: function (dt) { + + this.data.applyDamping(dt); + + }, + + /** + * Apply impulse to a point relative to the body. + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulse + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space. + * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + */ + applyImpulse: function (impulse, worldX, worldY) { + + this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Apply impulse to a point local to the body. + * + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulseLocal + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space. + * @param {number} localX - A local point on the body. + * @param {number} localY - A local point on the body. + */ + applyImpulseLocal: function (impulse, localX, localY) { + + this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]); + + }, + + /** + * Apply force to a world point. + * + * This could for example be a point on the RigidBody surface. Applying force + * this way will add to Body.force and Body.angularForce. + * + * @method Phaser.Physics.P2.Body#applyForce + * @param {Float32Array|Array} force - The force vector to add. + * @param {number} worldX - The world x point to apply the force on. + * @param {number} worldY - The world y point to apply the force on. + */ + applyForce: function (force, worldX, worldY) { + + this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Sets the force on the body to zero. + * + * @method Phaser.Physics.P2.Body#setZeroForce + */ + setZeroForce: function () { + + this.data.setZeroForce(); + + }, + + /** + * If this Body is dynamic then this will zero its angular velocity. + * + * @method Phaser.Physics.P2.Body#setZeroRotation + */ + setZeroRotation: function () { + + this.data.angularVelocity = 0; + + }, + + /** + * If this Body is dynamic then this will zero its velocity on both axis. + * + * @method Phaser.Physics.P2.Body#setZeroVelocity + */ + setZeroVelocity: function () { + + this.data.velocity[0] = 0; + this.data.velocity[1] = 0; + + }, + + /** + * Sets the Body damping and angularDamping to zero. + * + * @method Phaser.Physics.P2.Body#setZeroDamping + */ + setZeroDamping: function () { + + this.data.damping = 0; + this.data.angularDamping = 0; + + }, + + /** + * Transform a world point to local body frame. + * + * @method Phaser.Physics.P2.Body#toLocalFrame + * @param {Float32Array|Array} out - The vector to store the result in. + * @param {Float32Array|Array} worldPoint - The input world vector. + */ + toLocalFrame: function (out, worldPoint) { + + return this.data.toLocalFrame(out, worldPoint); + + }, + + /** + * Transform a local point to world frame. + * + * @method Phaser.Physics.P2.Body#toWorldFrame + * @param {Array} out - The vector to store the result in. + * @param {Array} localPoint - The input local vector. + */ + toWorldFrame: function (out, localPoint) { + + return this.data.toWorldFrame(out, localPoint); + + }, + + /** + * This will rotate the Body by the given speed to the left (counter-clockwise). + * + * @method Phaser.Physics.P2.Body#rotateLeft + * @param {number} speed - The speed at which it should rotate. + */ + rotateLeft: function (speed) { + + this.data.angularVelocity = this.world.pxm(-speed); + + }, + + /** + * This will rotate the Body by the given speed to the left (clockwise). + * + * @method Phaser.Physics.P2.Body#rotateRight + * @param {number} speed - The speed at which it should rotate. + */ + rotateRight: function (speed) { + + this.data.angularVelocity = this.world.pxm(speed); + + }, + + /** + * Moves the Body forwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveForward + * @param {number} speed - The speed at which it should move forwards. + */ + 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); + + }, + + /** + * Moves the Body backwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveBackward + * @param {number} speed - The speed at which it should move backwards. + */ + 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)); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrust + * @param {number} speed - The speed at which it should thrust. + */ + 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); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustLeft + * @param {number} speed - The speed at which it should move to the left. + */ + thrustLeft: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] += magnitude * Math.cos(angle); + this.data.force[1] += magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustRight + * @param {number} speed - The speed at which it should move to the right. + */ + thrustRight: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] -= magnitude * Math.cos(angle); + this.data.force[1] -= magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#reverse + * @param {number} speed - The speed at which it should reverse. + */ + 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); + + }, + + /** + * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveLeft + * @param {number} speed - The speed at which it should move to the left, in pixels per second. + */ + moveLeft: function (speed) { + + this.data.velocity[0] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveRight + * @param {number} speed - The speed at which it should move to the right, in pixels per second. + */ + moveRight: function (speed) { + + this.data.velocity[0] = this.world.pxmi(speed); + + }, + + /** + * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveUp + * @param {number} speed - The speed at which it should move up, in pixels per second. + */ + moveUp: function (speed) { + + this.data.velocity[1] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveDown + * @param {number} speed - The speed at which it should move down, in pixels per second. + */ + moveDown: function (speed) { + + this.data.velocity[1] = this.world.pxmi(speed); + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#preUpdate + * @protected + */ + preUpdate: function () { + + this.dirty = true; + + if (this.removeNextStep) + { + this.removeFromWorld(); + this.removeNextStep = false; + } + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#postUpdate + * @protected + */ + postUpdate: function () { + + this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x; + this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y; + + if (!this.fixedRotation) + { + this.sprite.rotation = this.data.angle; + } + + if (this.debugBody) + { + this.debugBody.updateSpriteTransform(); + } + + this.dirty = false; + + }, + + /** + * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. + * + * @method Phaser.Physics.P2.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new x position of the Body. + * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. + * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. + */ + reset: function (x, y, resetDamping, resetMass) { + + if (resetDamping === undefined) { resetDamping = false; } + if (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; + + }, + + /** + * Adds this physics body to the world. + * + * @method Phaser.Physics.P2.Body#addToWorld + */ + addToWorld: function () { + + if (this.game.physics.p2._toRemove) + { + for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) + { + if (this.game.physics.p2._toRemove[i] === this) + { + this.game.physics.p2._toRemove.splice(i, 1); + } + } + } + + if (this.data.world !== this.game.physics.p2.world) + { + this.game.physics.p2.addBody(this); + } + + }, + + /** + * Removes this physics body from the world. + * + * @method Phaser.Physics.P2.Body#removeFromWorld + */ + removeFromWorld: function () { + + if (this.data.world === this.game.physics.p2.world) + { + this.game.physics.p2.removeBodyNextStep(this); + } + + }, + + /** + * Destroys this Body and all references it holds to other objects. + * + * @method Phaser.Physics.P2.Body#destroy + */ + destroy: function () { + + this.removeFromWorld(); + + this.clearShapes(); + + this._bodyCallbacks = {}; + this._bodyCallbackContext = {}; + this._groupCallbacks = {}; + this._groupCallbackContext = {}; + + if (this.debugBody) + { + this.debugBody.destroy(true, true); + } + + this.debugBody = null; + + if (this.sprite) + { + this.sprite.body = null; + this.sprite = null; + } + + }, + + /** + * Removes all Shapes from this Body. + * + * @method Phaser.Physics.P2.Body#clearShapes + */ + clearShapes: function () { + + var i = this.data.shapes.length; + + while (i--) + { + this.data.removeShape(this.data.shapes[i]); + } + + this.shapeChanged(); + + }, + + /** + * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#addShape + + * @param {p2.Shape} shape - The shape to add to the body. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Shape} The shape that was added to the body. + */ + addShape: function (shape, offsetX, offsetY, rotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (rotation === undefined) { rotation = 0; } + + this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); + this.shapeChanged(); + + return shape; + + }, + + /** + * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Circle} The Circle shape that was added to the Body. + */ + addCircle: function (radius, offsetX, offsetY, rotation) { + + var shape = new p2.Circle({ radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addRectangle + * @param {number} width - The width of the rectangle in pixels. + * @param {number} height - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Box} The shape that was added to the Body. + */ + addRectangle: function (width, height, offsetX, offsetY, rotation) { + + var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addPlane + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Plane} The Plane shape that was added to the Body. + */ + addPlane: function (offsetX, offsetY, rotation) { + + var shape = new p2.Plane(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addParticle + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Particle} The Particle shape that was added to the Body. + */ + addParticle: function (offsetX, offsetY, rotation) { + + var shape = new p2.Particle(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Line shape to this Body. + * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addLine + * @param {number} length - The length of this line (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Line} The Line shape that was added to the Body. + */ + addLine: function (length, offsetX, offsetY, rotation) { + + var shape = new p2.Line({ length: this.world.pxm(length)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Capsule shape to this Body. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCapsule + * @param {number} length - The distance between the end points in pixels. + * @param {number} radius - Radius of the capsule in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Capsule} The Capsule shape that was added to the Body. + */ + addCapsule: function (length, radius, offsetX, offsetY, rotation) { + + var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. + * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. + * + * @method Phaser.Physics.P2.Body#addPolygon + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...]. In the first form **the array will mutate**. + * Or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {boolean} True on success, else false. + */ + addPolygon: function (options, points) { + + options = options || {}; + + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments, 1); + } + + var path = []; + + // Did they pass in a single array of points? + if (points.length === 1 && Array.isArray(points[0])) + { + path = points[0].slice(0); + } + else if (Array.isArray(points[0])) + { + path = points.slice(); + } + else if (typeof points[0] === 'number') + { + // We've a list of numbers + for (var i = 0, len = points.length; i < len; i += 2) + { + path.push([points[i], points[i + 1]]); + } + } + + // top and tail + var idx = path.length - 1; + + if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) + { + path.pop(); + } + + // Now process them into p2 values + for (var p = 0; p < path.length; p++) + { + path[p][0] = this.world.pxmi(path[p][0]); + path[p][1] = this.world.pxmi(path[p][1]); + } + + var result = this.data.fromPolygon(path, options); + + this.shapeChanged(); + + return result; + + }, + + /** + * Remove a shape from the body. Will automatically update the mass properties and bounding radius. + * + * @method Phaser.Physics.P2.Body#removeShape + * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. + * @return {boolean} True if the shape was found and removed, else false. + */ + removeShape: function (shape) { + + var result = this.data.removeShape(shape); + + this.shapeChanged(); + + return result; + }, + + /** + * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + */ + setCircle: function (radius, offsetX, offsetY, rotation) { + + this.clearShapes(); + + return this.addCircle(radius, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. + * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangle + * @param {number} [width=16] - The width of the rectangle in pixels. + * @param {number} [height=16] - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangle: function (width, height, offsetX, offsetY, rotation) { + + if (width === undefined) { width = 16; } + if (height === undefined) { height = 16; } + + this.clearShapes(); + + return this.addRectangle(width, height, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. + * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. + * If no Sprite is given it defaults to using the parent of this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangleFromSprite + * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangleFromSprite: function (sprite) { + + if (sprite === undefined) { sprite = this.sprite; } + + this.clearShapes(); + + return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); + + }, + + /** + * Adds the given Material to all Shapes that belong to this Body. + * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. + * + * @method Phaser.Physics.P2.Body#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. + */ + setMaterial: function (material, shape) { + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].material = material; + } + } + else + { + shape.material = material; + } + + }, + + /** + * Updates the debug draw if any body shapes change. + * + * @method Phaser.Physics.P2.Body#shapeChanged + */ + shapeChanged: function() { + + if (this.debugBody) + { + this.debugBody.draw(); + } + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * The shape data format is based on the output of the + * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for + * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor} + * + * @method Phaser.Physics.P2.Body#addPhaserPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. + * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. + * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList + */ + addPhaserPolygon: function (key, object) { + + var data = this.game.cache.getPhysicsData(key, object); + var createdFixtures = []; + + // Cycle through the fixtures + for (var i = 0; i < data.length; i++) + { + var fixtureData = data[i]; + var shapesOfFixture = this.addFixture(fixtureData); + + // Always add to a group + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); + + // if (unique) fixture key is provided + if (fixtureData.fixtureKey) + { + createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; + } + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return createdFixtures; + + }, + + /** + * Add a polygon fixture. This is used during #loadPolygon. + * + * @method Phaser.Physics.P2.Body#addFixture + * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. + * @return {array} An array containing the generated shapes for the given polygon. + */ + addFixture: function (fixtureData) { + + var generatedShapes = []; + + if (fixtureData.circle) + { + var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) }); + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + var offset = p2.vec2.create(); + offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); + offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); + + this.data.addShape(shape, offset); + generatedShapes.push(shape); + } + else + { + var polygons = fixtureData.polygons; + var cm = p2.vec2.create(); + + for (var i = 0; i < polygons.length; i++) + { + var shapes = polygons[i]; + var vertices = []; + + for (var s = 0; s < shapes.length; s += 2) + { + vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); + } + + var shape = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== shape.vertices.length; j++) + { + var v = shape.vertices[j]; + p2.vec2.sub(v, v, shape.centerOfMass); + } + + p2.vec2.scale(cm, shape.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + shape.updateTriangles(); + shape.updateCenterOfMass(); + shape.updateBoundingRadius(); + + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + this.data.addShape(shape, cm); + + generatedShapes.push(shape); + } + } + + return generatedShapes; + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * + * As well as reading the data from the Cache you can also pass `null` as the first argument and a + * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance. + * + * For more details see the format of the Lime / Corona Physics Editor export. + * + * @method Phaser.Physics.P2.Body#loadPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the + * data as the 2nd argument. + * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from, + * or if key is null pass the actual physics data object itself as this parameter. + * @param {number} [scale=1] - Optionally resize the loaded polygon. + * @return {boolean} True on success, else false. + */ + loadPolygon: function (key, object, scale) { + + if (key === null) + { + var data = object; + } + else + { + var data = this.game.cache.getPhysicsData(key, object); + } + + if (typeof scale !== "number") + { + scale = 1; + } + + // We've multiple Convex shapes, they should be CCW automatically + var cm = p2.vec2.create(); + + for (var i = 0; i < data.length; i++) + { + var vertices = []; + + for (var s = 0; s < data[i].shape.length; s += 2) + { + vertices.push([ + this.world.pxmi(data[i].shape[s] * scale), + this.world.pxmi(data[i].shape[s + 1] * scale) + ]); + } + + var c = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== c.vertices.length; j++) + { + var v = c.vertices[j]; + p2.vec2.sub(v, v, c.centerOfMass); + } + + p2.vec2.scale(cm, c.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + c.updateTriangles(); + c.updateCenterOfMass(); + c.updateBoundingRadius(); + + this.data.addShape(c, cm); + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return true; + + } + +}; + +Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; + +/** + * Dynamic body. Dynamic bodies body can move and respond to collisions and forces. + * @property DYNAMIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.DYNAMIC = 1; + +/** + * Static body. Static bodies do not move, and they do not respond to forces or collision. + * @property STATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.STATIC = 2; + +/** + * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. + * @property KINEMATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.KINEMATIC = 4; + +/** +* @name Phaser.Physics.P2.Body#static +* @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.STATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#dynamic +* @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#kinematic +* @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.KINEMATIC; + this.mass = 4; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#allowSleep +* @property {boolean} allowSleep - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { + + get: function () { + + return this.data.allowSleep; + + }, + + set: function (value) { + + if (value !== this.data.allowSleep) + { + this.data.allowSleep = value; + } + + } + +}); + +/** +* The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. +* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. +* If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#angle +* @property {number} angle - The angle of this Body in degrees. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); + + }, + + set: function(value) { + + this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#angularDamping +* @property {number} angularDamping - The angular damping acting acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { + + get: function () { + + return this.data.angularDamping; + + }, + + set: function (value) { + + this.data.angularDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularForce +* @property {number} angularForce - The angular force acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { + + get: function () { + + return this.data.angularForce; + + }, + + set: function (value) { + + this.data.angularForce = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularVelocity +* @property {number} angularVelocity - The angular velocity of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { + + get: function () { + + return this.data.angularVelocity; + + }, + + set: function (value) { + + this.data.angularVelocity = value; + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#damping +* @property {number} damping - The linear damping acting on the body in the velocity direction. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { + + get: function () { + + return this.data.damping; + + }, + + set: function (value) { + + this.data.damping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#fixedRotation +* @property {boolean} fixedRotation - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { + + get: function () { + + return this.data.fixedRotation; + + }, + + set: function (value) { + + if (value !== this.data.fixedRotation) + { + this.data.fixedRotation = value; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#inertia +* @property {number} inertia - The inertia of the body around the Z axis.. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { + + get: function () { + + return this.data.inertia; + + }, + + set: function (value) { + + this.data.inertia = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#mass +* @property {number} mass - The mass of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { + + get: function () { + + return this.data.mass; + + }, + + set: function (value) { + + if (value !== this.data.mass) + { + this.data.mass = value; + this.data.updateMassProperties(); + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#motionState +* @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { + + get: function () { + + return this.data.type; + + }, + + set: function (value) { + + if (value !== this.data.type) + { + this.data.type = value; + } + + } + +}); + +/** +* The angle of the Body in radians. +* If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#rotation +* @property {number} rotation - The angle of this Body in radians. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { + + get: function() { + + return this.data.angle; + + }, + + set: function(value) { + + this.data.angle = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#sleepSpeedLimit +* @property {number} sleepSpeedLimit - . +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { + + get: function () { + + return this.data.sleepSpeedLimit; + + }, + + set: function (value) { + + this.data.sleepSpeedLimit = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#x +* @property {number} x - The x coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.data.position[0]); + + }, + + set: function (value) { + + this.data.position[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#y +* @property {number} y - The y coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.data.position[1]); + + }, + + set: function (value) { + + this.data.position[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#id +* @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { + + get: function () { + + return this.data.id; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#debug +* @property {boolean} debug - Enable or disable debug drawing of this body +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { + + get: function () { + + return (this.debugBody !== null); + + }, + + set: function (value) { + + if (value && !this.debugBody) + { + // This will be added to the global space + this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); + } + else if (!value && this.debugBody) + { + this.debugBody.destroy(); + this.debugBody = null; + } + + } + +}); + +/** +* A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. +* Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. +* Also note that when you set this it will only affect Body shapes that already exist. If you then add further shapes to your Body +* after setting this it will *not* proactively set them to collide with the bounds. +* +* @name Phaser.Physics.P2.Body#collideWorldBounds +* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? +* @default true +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { + + get: function () { + + return this._collideWorldBounds; + + }, + + set: function (value) { + + if (value && !this._collideWorldBounds) + { + this._collideWorldBounds = true; + this.updateCollisionMask(); + } + else if (!value && this._collideWorldBounds) + { + this._collideWorldBounds = false; + this.updateCollisionMask(); + } + + } + +}); + +/** +* @author George https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Draws a P2 Body to a Graphics instance for visual debugging. +* Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. +* So use sparingly and rarely (if ever) in production code. +* +* Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you +* manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will +* need to manually adjust its BodyDebug as well. +* +* @class Phaser.Physics.P2.BodyDebug +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. +* @param {object} settings - Settings object. +*/ +Phaser.Physics.P2.BodyDebug = function(game, body, settings) { + + Phaser.Group.call(this, game); + + /** + * @property {object} defaultSettings - Default debug settings. + * @private + */ + var defaultSettings = { + pixelsPerLengthUnit: game.physics.p2.mpx(1), + debugPolygons: false, + lineWidth: 1, + alpha: 0.5 + }; + + this.settings = Object.assign(defaultSettings, settings); + + /** + * @property {number} ppu - Pixels per Length Unit. + */ + this.ppu = this.settings.pixelsPerLengthUnit; + this.ppu = -1 * this.ppu; + + /** + * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. + */ + this.body = body; + + /** + * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. + */ + this.canvas = new Phaser.Graphics(game); + + this.canvas.alpha = this.settings.alpha; + + this.add(this.canvas); + + this.draw(); + + this.updateSpriteTransform(); + +}; + +Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); +Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; + +Object.assign(Phaser.Physics.P2.BodyDebug.prototype, { + + /** + * Core update. + * + * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform + */ + updateSpriteTransform: function() { + + this.position.x = this.body.position[0] * this.ppu; + this.position.y = this.body.position[1] * this.ppu; + this.rotation = this.body.angle; + + }, + + /** + * Draws the P2 shapes to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#draw + */ + draw: function() { + + var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; + + obj = this.body; + sprite = this.canvas; + sprite.clear(); + color = parseInt(this.randomPastelHex(), 16); + lineColor = 0xff0000; + lw = this.lineWidth; + + if (obj instanceof p2.Body && obj.shapes.length) + { + var l = obj.shapes.length; + + i = 0; + + while (i !== l) + { + child = obj.shapes[i]; + offset = child.position || 0; + angle = child.angle || 0; + + if (child instanceof p2.Circle) + { + this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); + } + else if (child instanceof p2.Capsule) + { + this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw); + } + 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.Box) + { + this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); + } + else if (child instanceof p2.Convex) + { + verts = []; + vrot = p2.vec2.create(); + + for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _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]); + } + + i++; + } + } + + }, + + /** + * Draws a p2.Box to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawRectangle + * @private + */ + drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + g.beginFill(fillColor); + g.drawRect(x - w / 2, y - h / 2, w, h); + + }, + + /** + * Draws a p2.Circle to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCircle + * @private + */ + drawCircle: function(g, x, y, angle, radius, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + g.lineStyle(lineWidth, 0x000000, 1); + g.beginFill(color, 1.0); + g.drawCircle(x, y, -radius*2); + g.endFill(); + g.moveTo(x, y); + g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); + + }, + + /** + * Draws a p2.Line to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawLine + * @private + */ + drawLine: function(g, len, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth * 5, color, 1); + g.moveTo(-len / 2, 0); + g.lineTo(len / 2, 0); + + }, + + /** + * Draws a p2.Convex to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawConvex + * @private + */ + drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { + + var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + 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 = [0xff0000, 0x00ff00, 0x0000ff]; + 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, 0x000000, 1); + return g.drawCircle(offset[0], offset[1], lineWidth * 2); + } + + }, + + /** + * Draws a p2.Path to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPath + * @private + */ + drawPath: function(g, path, color, fillColor, lineWidth) { + + var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + if (typeof fillColor === "number") + { + g.beginFill(fillColor); + } + + lastx = null; + lasty = null; + i = 0; + + while (i < path.length) + { + v = path[i]; + x = v[0]; + y = v[1]; + + if (x !== lastx || y !== lasty) + { + if (i === 0) + { + g.moveTo(x, y); + } + else + { + p1x = lastx; + p1y = lasty; + p2x = x; + p2y = y; + p3x = path[(i + 1) % path.length][0]; + p3y = path[(i + 1) % path.length][1]; + area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); + + if (area !== 0) + { + g.lineTo(x, y); + } + } + lastx = x; + lasty = y; + } + + i++; + + } + + if (typeof fillColor === "number") + { + g.endFill(); + } + + if (path.length > 2 && typeof fillColor === "number") + { + g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); + g.lineTo(path[0][0], path[0][1]); + } + + }, + + /** + * Draws a p2.Plane to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPlane + * @private + */ + drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { + + var max, xd, yd; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + + 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); + + }, + + /** + * Draws a p2.Capsule to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCapsule + * @private + */ + drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + // Draw circles at ends + var c = Math.cos(angle); + var s = Math.sin(angle); + + g.beginFill(fillColor, 1); + g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2); + g.drawCircle( len/2*c + x, len/2*s + y, -radius * 2); + g.endFill(); + + // Draw rectangle + g.lineStyle(lineWidth, color, 0); + g.beginFill(fillColor, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.endFill(); + + // Draw lines in between + g.lineStyle(lineWidth, color, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + + }, + + /** + * Picks a random pastel color. + * + * @method Phaser.Physics.P2.BodyDebug#randomPastelHex + * @private + */ + 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); + + }, + + /** + * Converts from RGB to Hex. + * + * @method Phaser.Physics.P2.BodyDebug#rgbToHex + * @private + */ + rgbToHex: function(r, g, b) { + return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); + }, + + /** + * Component to hex conversion. + * + * @method Phaser.Physics.P2.BodyDebug#componentToHex + * @private + */ + componentToHex: function(c) { + + var hex; + hex = c.toString(16); + + if (hex.length === 2) + { + return hex; + } + else + { + return hex + '0'; + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.Spring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restLength=1] - Rest length of the spring. A number > 0. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +*/ +Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restLength === undefined) { restLength = 1; } + if (stiffness === undefined) { stiffness = 100; } + if (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]) ]; + } + + /** + * @property {p2.LinearSpring} data - The actual p2 spring object. + */ + this.data = new p2.LinearSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.RotationalSpring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +*/ +Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restAngle === undefined) { restAngle = null; } + if (stiffness === undefined) { stiffness = 100; } + if (damping === undefined) { damping = 1; } + + if (restAngle) + { + restAngle = world.pxm(restAngle); + } + + var options = { + restAngle: restAngle, + stiffness: stiffness, + damping: damping + }; + + /** + * @property {p2.RotationalSpring} data - The actual p2 spring object. + */ + this.data = new p2.RotationalSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A P2 Material. +* +* \o/ ~ "Because I'm a Material girl" +* +* @class Phaser.Physics.P2.Material +* @constructor +* @param {string} name - The user defined name given to this Material. +*/ +Phaser.Physics.P2.Material = function (name) { + + /** + * @property {string} name - The user defined name given to this Material. + * @default + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Defines a physics material +* +* @class Phaser.Physics.P2.ContactMaterial +* @constructor +* @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. +* @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. +* @param {object} [options] - Additional configuration options. +*/ +Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { + + /** + * @property {number} id - The contact material identifier. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. + */ + + /** + * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. + */ + + /** + * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. + */ + + /** + * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + */ + + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Collision Group +* +* @class Phaser.Physics.P2.CollisionGroup +* @constructor +* @param {number} bitmask - The CollisionGroup bitmask. +*/ +Phaser.Physics.P2.CollisionGroup = function (bitmask) { + + /** + * @property {number} mask - The CollisionGroup bitmask. + */ + this.mask = bitmask; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A constraint that tries to keep the distance between two bodies constant. +* +* @class Phaser.Physics.P2.DistanceConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} distance - The distance to keep between the bodies. +* @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. +* @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. +* @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply. +*/ +Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { + + if (distance === undefined) { distance = 100; } + if (localAnchorA === undefined) { localAnchorA = [0, 0]; } + if (localAnchorB === undefined) { localAnchorB = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + distance = world.pxm(distance); + + localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ]; + localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ]; + + var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce }; + + p2.DistanceConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); +Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.GearConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [angle=0] - The relative angle +* @param {number} [ratio=1] - The gear ratio. +*/ +Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { + + if (angle === undefined) { angle = 0; } + if (ratio === undefined) { ratio = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Locks the relative position between two bodies. +* +* @class Phaser.Physics.P2.LockConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [angle=0] - The angle of bodyB in bodyA's frame. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { + + if (offset === undefined) { offset = [0, 0]; } + if (angle === undefined) { angle = 0; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.PrismaticConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. +* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { + + if (lockRotation === undefined) { lockRotation = true; } + if (anchorA === undefined) { anchorA = [0, 0]; } + if (anchorB === undefined) { anchorB = [0, 0]; } + if (axis === undefined) { axis = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* The pivot points are given in world (pixel) coordinates. +* +* @class Phaser.Physics.P2.RevoluteConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {p2.Body} bodyB - Second connected body. +* @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. +* @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. +*/ +Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + if (worldPivot === undefined) { worldPivot = null; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; + pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; + + if (worldPivot) + { + worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ]; + } + + var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce }; + + p2.RevoluteConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); +Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image Collection is a special tileset containing mulitple images, with no slicing into each image. +* +* Image Collections are normally created automatically when Tiled data is loaded. +* +* @class Phaser.ImageCollection +* @constructor +* @param {string} name - The name of the image collection in the map data. +* @param {integer} firstgid - The first image index this image collection contains. +* @param {integer} [width=32] - Width of widest image (in pixels). +* @param {integer} [height=32] - Height of tallest image (in pixels). +* @param {integer} [margin=0] - The margin around all images in the collection (in pixels). +* @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). +* @param {object} [properties={}] - Custom Image Collection properties. +*/ +Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Image Collection. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of the widest image (in pixels). + * @property {integer} imageWidth + * @readonly + */ + this.imageWidth = width | 0; + + /** + * The height of the tallest image (in pixels). + * @property {integer} imageHeight + * @readonly + */ + this.imageHeight = height | 0; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageMarge + * @readonly + */ + // Modified internally + this.imageMargin = margin | 0; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageSpacing + * @readonly + */ + this.imageSpacing = spacing | 0; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached images that are a part of this collection. + * @property {array} images + * @readonly + */ + // Modified internally + this.images = []; + + /** + * The total number of images in the image collection. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; +}; + +Phaser.ImageCollection.prototype = { + + /** + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.ImageCollection#containsImageIndex + * @param {integer} imageIndex - The image index to search for. + * @return {boolean} True if this Image Collection contains the given index. + */ + containsImageIndex: function (imageIndex) { + + return ( + imageIndex >= this.firstgid && + imageIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Add an image to this Image Collection. + * + * @method Phaser.ImageCollection#addImage + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + */ + addImage: function (gid, image) { + + this.images.push({ gid: gid, image: image }); + this.total++; + + } + +}; + +Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile is a representation of a single tile within the Tilemap. +* +* @class Phaser.Tile +* @constructor +* @param {object} layer - The layer in the Tilemap data that this tile belongs to. +* @param {number} index - The index of this tile type in the core map data. +* @param {number} x - The x coordinate of this tile. +* @param {number} y - The y coordinate of this tile. +* @param {number} width - Width of the tile. +* @param {number} height - Height of the tile. +*/ +Phaser.Tile = function (layer, index, x, y, width, height) { + + /** + * @property {object} layer - The layer in the Tilemap data that this tile belongs to. + */ + this.layer = layer; + + /** + * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. + */ + this.index = index; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.x = x; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.y = y; + + /** + * @property {number} rotation - The rotation angle of this tile. + */ + this.rotation = 0; + + /** + * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not. + */ + this.flipped = false; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.worldX = x * width; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.worldY = y * height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.height = height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.centerX = Math.abs(width / 2); + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.centerY = Math.abs(height / 2); + + /** + * @property {number} alpha - The alpha value at which this tile is drawn to the canvas. + */ + this.alpha = 1; + + /** + * @property {object} properties - Tile specific properties. + */ + this.properties = {}; + + /** + * @property {boolean} scanned - Has this tile been walked / turned into a poly? + */ + this.scanned = false; + + /** + * @property {boolean} faceTop - Is the top of this tile an interesting edge? + */ + this.faceTop = false; + + /** + * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge? + */ + this.faceBottom = false; + + /** + * @property {boolean} faceLeft - Is the left of this tile an interesting edge? + */ + this.faceLeft = false; + + /** + * @property {boolean} faceRight - Is the right of this tile an interesting edge? + */ + this.faceRight = false; + + /** + * @property {boolean} collideLeft - Indicating collide with any object on the left. + * @default + */ + this.collideLeft = false; + + /** + * @property {boolean} collideRight - Indicating collide with any object on the right. + * @default + */ + this.collideRight = false; + + /** + * @property {boolean} collideUp - Indicating collide with any object on the top. + * @default + */ + this.collideUp = false; + + /** + * @property {boolean} collideDown - Indicating collide with any object on the bottom. + * @default + */ + this.collideDown = false; + + /** + * @property {function} collisionCallback - Tile collision callback. + * @default + */ + this.collisionCallback = null; + + /** + * @property {object} collisionCallbackContext - The context in which the collision callback will be called. + * @default + */ + this.collisionCallbackContext = this; + + /** + * @property {boolean} debug + * @default + */ + this.debug = false; + +}; + +Phaser.Tile.prototype = { + + /** + * Check if the given x and y world coordinates are within this Tile. + * + * @method Phaser.Tile#containsPoint + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ + containsPoint: function (x, y) { + + return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom); + + }, + + /** + * Check for intersection with this tile. + * + * @method Phaser.Tile#intersects + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + */ + 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; + + }, + + /** + * Set a callback to be called when this tile is hit by an object. + * The callback must true true for collision processing to take place. + * + * @method Phaser.Tile#setCollisionCallback + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + */ + setCollisionCallback: function (callback, context) { + + this.collisionCallback = callback; + this.collisionCallbackContext = context; + + }, + + /** + * Clean up memory. + * + * @method Phaser.Tile#destroy + */ + destroy: function () { + + this.collisionCallback = null; + this.collisionCallbackContext = null; + this.properties = null; + + }, + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tile#setCollision + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} right - Indicating collide with any object on the right. + * @param {boolean} up - Indicating collide with any object on the top. + * @param {boolean} down - Indicating collide with any object on the bottom. + */ + setCollision: function (left, right, up, down) { + + this.collideLeft = left; + this.collideRight = right; + this.collideUp = up; + this.collideDown = down; + + this.faceLeft = left; + this.faceRight = right; + this.faceTop = up; + this.faceBottom = down; + + }, + + /** + * Reset collision status flags. + * + * @method Phaser.Tile#resetCollision + */ + 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; + + }, + + /** + * Is this tile interesting? + * + * @method Phaser.Tile#isInteresting + * @param {boolean} collides - If true will check any collides value. + * @param {boolean} faces - If true will check any face value. + * @return {boolean} True if the Tile is interesting, otherwise false. + */ + isInteresting: function (collides, faces) { + + if (collides && faces) + { + // Does this tile have any collide flags OR interesting face? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback); + } + else if (collides) + { + // Does this tile collide? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + else if (faces) + { + // Does this tile have an interesting face? + return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); + } + + return false; + + }, + + /** + * Copies the tile data and properties from the given tile to this tile. + * + * @method Phaser.Tile#copy + * @param {Phaser.Tile} tile - The tile to copy from. + */ + 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; + +/** +* @name Phaser.Tile#collides +* @property {boolean} collides - True if this tile can collide on any of its faces. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "collides", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + +}); + +/** +* @name Phaser.Tile#canCollide +* @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "canCollide", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); + } + +}); + +/** +* @name Phaser.Tile#left +* @property {number} left - The x value in pixels. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "left", { + + get: function () { + return this.worldX; + } + +}); + +/** +* @name Phaser.Tile#right +* @property {number} right - The sum of the x and width properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "right", { + + get: function () { + return this.worldX + this.width; + } + +}); + +/** +* @name Phaser.Tile#top +* @property {number} top - The y value. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "top", { + + get: function () { + return this.worldY; + } + +}); + +/** +* @name Phaser.Tile#bottom +* @property {number} bottom - The sum of the y and height properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "bottom", { + + get: function () { + return this.worldY + this.height; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. +* +* Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org +* +* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. +* When using CSV data you must provide the key and the tileWidth and tileHeight parameters. +* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. +* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. +* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. +* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. +* +* @class Phaser.Tilemap +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. +* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +*/ +Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {string} key - The key of this map data in the Phaser.Cache. + */ + this.key = key; + + var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height); + + if (data === null) + { + return; + } + + /** + * @property {number} width - The width of the map (in tiles). + */ + this.width = data.width; + + /** + * @property {number} height - The height of the map (in tiles). + */ + this.height = data.height; + + /** + * @property {number} tileWidth - The base width of the tiles in the map (in pixels). + */ + this.tileWidth = data.tileWidth; + + /** + * @property {number} tileHeight - The base height of the tiles in the map (in pixels). + */ + this.tileHeight = data.tileHeight; + + /** + * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + */ + this.orientation = data.orientation; + + /** + * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + */ + this.format = data.format; + + /** + * @property {number} version - The version of the map data (as specified in Tiled, usually 1). + */ + this.version = data.version; + + /** + * @property {object} properties - Map specific properties as specified in Tiled. + */ + this.properties = data.properties; + + /** + * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth. + */ + this.widthInPixels = data.widthInPixels; + + /** + * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight. + */ + this.heightInPixels = data.heightInPixels; + + /** + * @property {array} layers - An array of Tilemap layer data. + */ + this.layers = data.layers; + + /** + * @property {array} tilesets - An array of Tilesets. + */ + this.tilesets = data.tilesets; + + /** + * @property {array} imagecollections - An array of Image Collections. + */ + this.imagecollections = data.imagecollections; + + /** + * @property {array} tiles - The super array of Tiles. + */ + this.tiles = data.tiles; + + /** + * @property {array} objects - An array of Tiled Object Layers. + */ + this.objects = data.objects; + + /** + * @property {array} collideIndexes - An array of tile indexes that collide. + */ + this.collideIndexes = []; + + /** + * @property {array} collision - An array of collision data (polylines, etc). + */ + this.collision = data.collision; + + /** + * @property {array} images - An array of Tiled Image Layers. + */ + this.images = data.images; + + /** + * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data. + */ + this.enableDebug = false; + + /** + * @property {number} currentLayer - The current layer. + */ + this.currentLayer = 0; + + /** + * @property {array} debugMap - Map data used for debug values only. + */ + this.debugMap = []; + + /** + * @property {array} _results - Internal var. + * @private + */ + this._results = []; + + /** + * @property {number} _tempA - Internal var. + * @private + */ + this._tempA = 0; + + /** + * @property {number} _tempB - Internal var. + * @private + */ + this._tempB = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.CSV = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.TILED_JSON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.NORTH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.EAST = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.SOUTH = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.WEST = 3; + +Phaser.Tilemap.prototype = { + + /** + * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. + * + * @method Phaser.Tilemap#create + * @param {string} name - The name of the default layer of the map. + * @param {number} width - The width of the map in tiles. + * @param {number} height - The height of the map in tiles. + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + create: function (name, width, height, tileWidth, tileHeight, group) { + + if (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); + + }, + + /** + * Sets the base tile size for the map. + * + * @method Phaser.Tilemap#setTileSize + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + */ + setTileSize: function (tileWidth, tileHeight) { + + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.widthInPixels = this.width * tileWidth; + this.heightInPixels = this.height * tileHeight; + + }, + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. + * + * @method Phaser.Tilemap#addTilesetImage + * @param {string} tileset - The name of the tileset as specified in the map data. + * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset. + * If `undefined` or `null` it will look for an image with a key matching the tileset parameter. + * You can also pass in a BitmapData which can be used instead of an Image. + * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. + * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. + * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. + * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. + * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. + * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed. + */ + addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { + + if (tileset === undefined) { return null; } + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (gid === undefined) { gid = 0; } + + // In-case we're working from a blank map + if (tileWidth === 0) + { + tileWidth = 32; + } + + if (tileHeight === 0) + { + tileHeight = 32; + } + + var img = null; + + if (key === undefined || key === null) + { + key = tileset; + } + + if (key instanceof Phaser.BitmapData) + { + img = key.canvas; + } + else + { + if (!this.game.cache.checkImageKey(key)) + { + console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"'); + return null; + } + + img = this.game.cache.getImage(key); + } + + var idx = this.getTilesetIndex(tileset); + + if (idx === null && this.format === Phaser.Tilemap.TILED_JSON) + { + console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + tileset + '"'); + console.log('Tilesets: ', this.tilesets); + return null; + } + + if (this.tilesets[idx]) + { + this.tilesets[idx].setImage(img); + return this.tilesets[idx]; + } + else + { + var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {}); + + newSet.setImage(img); + + 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; t < gid + newSet.total; t++) + { + this.tiles[t] = [x, y, i]; + + x += tileWidth + tileSpacing; + + count++; + + if (count === newSet.total) + { + break; + } + + countX++; + + if (countX === newSet.columns) + { + x = tileMargin; + y += tileHeight + tileSpacing; + + countX = 0; + countY++; + + if (countY === newSet.rows) + { + break; + } + } + } + + return newSet; + + } + + return null; + + }, + + /** + * Creates a Sprite for every {@link http://doc.mapeditor.org/reference/tmx-map-format/#object object} matching the `gid` argument. You can optionally specify the group that the Sprite will be created in. If none is + * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to + * configure Sprite properties from within the map editor. For example giving an object a property of `alpha: 0.5` in the map editor will duplicate that when the + * Sprite is created. You could also give it a value like: `body.velocity.x: 100` to set it moving automatically. + * + * The `gid` argument is matched against: + * + * 1. For a tile object, the tile identifier (`gid`); or + * 2. The object's unique ID (`id`); or + * 3. The object's `name` (a string) + * + * @method Phaser.Tilemap#createFromObjects + * @param {string} name - The name of the Object Group to create Sprites from. + * @param {number|string} gid - The object's tile reference (gid), unique ID (id) or name. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. + * @param {boolean} [exists=true] - The default exists state of the Sprite. + * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. + * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. + * @param {boolean} [adjustSize=true] - By default the width and height of the objects are transferred to the sprite. This parameter controls that behavior. + */ + createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY, adjustSize) { + + if (exists === undefined) { exists = true; } + if (autoCull === undefined) { autoCull = false; } + if (group === undefined) { group = this.game.world; } + if (CustomClass === undefined) { CustomClass = Phaser.Sprite; } + if (adjustY === undefined) { adjustY = true; } + if (adjustSize === undefined) { adjustSize = true; } + + if (!this.objects[name]) + { + console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name); + console.log('Objects: ', this.objects); + return; + } + + for (var i = 0; i < this.objects[name].length; i++) + { + var found = false; + var obj = this.objects[name][i]; + + if (obj.gid !== undefined && typeof gid === 'number' && obj.gid === gid) + { + found = true; + } + else if (obj.id !== undefined && typeof gid === 'number' && obj.id === gid) + { + found = true; + } + else if (obj.name !== undefined && typeof gid === 'string' && obj.name === gid) + { + found = true; + } + + if (found) + { + var sprite = new CustomClass(this.game, parseFloat(obj.x, 10), parseFloat(obj.y, 10), key, frame); + + sprite.name = obj.name; + sprite.autoCull = autoCull; + sprite.exists = exists; + sprite.visible = obj.visible; + + if (adjustSize) + { + if (obj.width) + { + sprite.width = obj.width; + } + + if (obj.height) + { + sprite.height = obj.height; + } + } + + if (obj.rotation) + { + sprite.angle = obj.rotation; + } + + if (adjustY) + { + sprite.y -= sprite.height; + } + + group.add(sprite); + + for (var property in obj.properties) + { + group.set(sprite, property, obj.properties[property], false, false, 0, true); + } + } + } + + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the map data. + * You can specify the group that the Sprite will be created in. If none is given it will be created in the World. + * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special + * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemap#createFromTiles + * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from. + * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. + * @return {integer} The number of Sprites that were created. + */ + createFromTiles: function (tiles, replacements, key, layer, group, properties) { + + if (typeof tiles === 'number') { tiles = [tiles]; } + + if (replacements === undefined || replacements === null) + { + replacements = []; + } + else if (typeof replacements === 'number') + { + replacements = [replacements]; + } + + layer = this.getLayer(layer); + + if (group === undefined) { group = this.game.world; } + if (properties === undefined) { properties = {}; } + + if (properties.customClass === undefined) + { + properties.customClass = Phaser.Sprite; + } + + if (properties.adjustY === undefined) + { + properties.adjustY = true; + } + + var lw = this.layers[layer].width; + var lh = this.layers[layer].height; + + this.copy(0, 0, lw, lh, layer); + + if (this._results.length < 2) + { + return 0; + } + + var total = 0; + var sprite; + + for (var i = 1, len = this._results.length; i < len; i++) + { + if (tiles.indexOf(this._results[i].index) !== -1) + { + sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key); + + for (var property in properties) + { + sprite[property] = properties[property]; + } + + group.add(sprite); + total++; + } + + } + + if (replacements.length === 1) + { + // Assume 1 replacement for all types of tile given + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer); + } + } + else if (replacements.length > 1) + { + // Assume 1 for 1 mapping + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer); + } + } + + return total; + + }, + + /** + * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. + * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. + * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. + * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. + * + * @method Phaser.Tilemap#createLayer + * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. + * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. + * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. + * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. + */ + createLayer: function (layer, width, height, group) { + + // Add Buffer support for the left of the canvas + + if (width === undefined) { width = this.game.width; } + if (height === undefined) { height = this.game.height; } + if (group === undefined) { group = this.game.world; } + + var index = layer; + + if (typeof layer === 'string') + { + index = this.getLayerIndex(layer); + } + + if (index === null || index > this.layers.length) + { + console.warn('Tilemap.createLayer: Invalid layer ID given: "' + layer + '"'); + console.log('Layers: ', this.layers); + return; + } + + // Sort out the display dimensions, so they never render too much, or too little. + + if (width === undefined || width <= 0) + { + width = Math.min(this.game.width, this.layers[index].widthInPixels); + } + else if (width > this.game.width) + { + width = this.game.width; + } + + if (height === undefined || height <= 0) + { + height = Math.min(this.game.height, this.layers[index].heightInPixels); + } + else if (height > this.game.height) + { + height = this.game.height; + } + + if (this.enableDebug) + { + console.group('Tilemap.createLayer'); + console.log('Name:', this.layers[index].name); + console.log('Size:', width, 'x', height); + console.log('Tileset:', this.tilesets[0].name, 'index:', index); + } + + var rootLayer = group.add(new Phaser.TilemapLayer(this.game, this, index, width, height)); + + if (this.enableDebug) + { + console.groupEnd(); + } + + return rootLayer; + + }, + + + /** + * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. + * + * @method Phaser.Tilemap#createBlankLayer + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {number} width - The width of the layer in tiles. + * @param {number} height - The height of the layer in tiles. + * @param {number} tileWidth - The width of the tiles the layer uses for calculations. + * @param {number} tileHeight - The height of the tiles the layer uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) { + + if (group === undefined) { group = this.game.world; } + + if (this.getLayerIndex(name) !== null) + { + console.warn('Tilemap.createBlankLayer: Layer with matching name already exists: ' + name); + 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; y < height; y++) + { + row = []; + + for (var x = 0; x < width; x++) + { + row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight)); + } + + output.push(row); + } + + layer.data = output; + + this.layers.push(layer); + + this.currentLayer = this.layers.length - 1; + + var w = layer.widthInPixels; + var h = layer.heightInPixels; + + if (w > this.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); + + }, + + /** + * Gets the layer index based on the layers name. + * + * @method Phaser.Tilemap#getIndex + * @protected + * @param {array} location - The local array to search. + * @param {string} name - The name of the array element to get. + * @return {number} The index of the element in the array, or null if not found. + */ + getIndex: function (location, name) { + + for (var i = 0; i < location.length; i++) + { + if (location[i].name === name) + { + return i; + } + } + + return null; + + }, + + /** + * Gets the layer index based on its name. + * + * @method Phaser.Tilemap#getLayerIndex + * @param {string} name - The name of the layer to get. + * @return {number} The index of the layer in this tilemap, or null if not found. + */ + getLayerIndex: function (name) { + + return this.getIndex(this.layers, name); + + }, + + /** + * Gets the tileset index based on its name. + * + * @method Phaser.Tilemap#getTilesetIndex + * @param {string} name - The name of the tileset to get. + * @return {number} The index of the tileset in this tilemap, or null if not found. + */ + getTilesetIndex: function (name) { + + return this.getIndex(this.tilesets, name); + + }, + + /** + * Gets the image index based on its name. + * + * @method Phaser.Tilemap#getImageIndex + * @param {string} name - The name of the image to get. + * @return {number} The index of the image in this tilemap, or null if not found. + */ + getImageIndex: function (name) { + + return this.getIndex(this.images, name); + + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileIndexCallback + * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileIndexCallback: function (indexes, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes]; + } + else + { + // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much + // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit. + this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext }; + } + } + else + { + for (var i = 0, len = indexes.length; i < len; i++) + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes[i]]; + } + else + { + this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext }; + } + } + } + + }, + + /** + * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileLocationCallback + * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} width - The width of the area to copy (given in tiles, not pixels) + * @param {number} height - The height of the area to copy (given in tiles, not pixels) + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].setCollisionCallback(callback, callbackContext); + } + + }, + + /** + * Sets collision on the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [2, 3, 15, 20]. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * Collision-enabled tiles can be collided against Sprites using {@link Phaser.Physics.Arcade#collide}. + * + * You can verify the collision faces by enabling {@link Phaser.TilemapLayer#debug}. + * + * @method Phaser.Tilemap#setCollision + * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollision: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + return this.setCollisionByIndex(indexes, collides, layer, true); + } + else if (Array.isArray(indexes)) + { + // Collide all of the IDs given in the indexes array + for (var i = 0; i < indexes.length; i++) + { + this.setCollisionByIndex(indexes[i], collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + } + + }, + + /** + * Sets collision on a range of tiles where the tile IDs increment sequentially. + * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionBetween + * @param {number} start - The first index of the tile to be set for collision. + * @param {number} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionBetween: function (start, stop, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (start > stop) + { + return; + } + + for (var index = start; index <= stop; index++) + { + this.setCollisionByIndex(index, collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision on all tiles in the given layer, except for the IDs of those in the given array. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionByExclusion + * @param {array} indexes - An array of the tile IDs to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByExclusion: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + // Collide everything, except the IDs given in the indexes array + for (var i = 0, len = this.tiles.length; i < len; i++) + { + if (indexes.indexOf(i) === -1) + { + this.setCollisionByIndex(i, collides, layer, false); + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision values on a tile in the set. + * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. + * + * @method Phaser.Tilemap#setCollisionByIndex + * @protected + * @param {number} index - The index of the tile on the layer. + * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile. + * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByIndex: function (index, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (layer === undefined) { layer = this.currentLayer; } + if (recalculate === undefined) { recalculate = true; } + + if (collides) + { + this.collideIndexes.push(index); + } + else + { + var i = this.collideIndexes.indexOf(index); + + if (i > -1) + { + this.collideIndexes.splice(i, 1); + } + } + + for (var y = 0; y < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile && tile.index === index) + { + if (collides) + { + tile.setCollision(true, true, true, true); + } + else + { + tile.resetCollision(); + } + + tile.faceTop = collides; + tile.faceBottom = collides; + tile.faceLeft = collides; + tile.faceRight = collides; + } + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + return layer; + + }, + + /** + * Gets the TilemapLayer index as used in the setCollision calls. + * + * @method Phaser.Tilemap#getLayer + * @protected + * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer. + * @return {number} The TilemapLayer index. + */ + getLayer: function (layer) { + + if (layer === undefined) + { + layer = this.currentLayer; + } + else if (typeof layer === 'string') + { + var layerArg = layer; + + layer = this.getLayerIndex(layer); + + if (!layer) + { + console.warn('No such layer name: ' + layerArg); + } + } + else if (layer instanceof Phaser.TilemapLayer) + { + layer = layer.index; + } + + return layer; + + }, + + /** + * Turn off/on the recalculation of faces for tile or collision updates. + * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. + * + * @method Phaser.Tilemap#setPreventRecalculate + * @param {boolean} value - If true it will put the recalculation on hold. + */ + setPreventRecalculate: function (value) { + + if (value === true && this.preventingRecalculate !== true) + { + this.preventingRecalculate = true; + this.needToRecalculate = {}; + } + + if (value === false && this.preventingRecalculate === true) + { + this.preventingRecalculate = false; + + for (var i in this.needToRecalculate) + { + this.calculateFaces(i); + } + + this.needToRecalculate = false; + } + + }, + + /** + * Internal function. + * + * @method Phaser.Tilemap#calculateFaces + * @protected + * @param {number} layer - The index of the TilemapLayer to operate on. + */ + calculateFaces: function (layer) { + + if (this.preventingRecalculate) + { + this.needToRecalculate[layer] = true; + return; + } + + var above = null; + var below = null; + var left = null; + var right = null; + + for (var y = 0, h = this.layers[layer].height; y < h; y++) + { + for (var x = 0, w = this.layers[layer].width; x < w; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile) + { + above = this.getTileAbove(layer, x, y); + below = this.getTileBelow(layer, x, y); + left = this.getTileLeft(layer, x, y); + right = this.getTileRight(layer, x, y); + + if (tile.collides) + { + tile.faceTop = true; + tile.faceBottom = true; + tile.faceLeft = true; + tile.faceRight = true; + } + + if (above && above.collides) + { + // There is a tile above this one that also collides, so the top of this tile is no longer interesting + tile.faceTop = false; + } + + if (below && below.collides) + { + // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting + tile.faceBottom = false; + } + + if (left && left.collides) + { + // There is a tile left this one that also collides, so the left of this tile is no longer interesting + tile.faceLeft = false; + } + + if (right && right.collides) + { + // There is a tile right this one that also collides, so the right of this tile is no longer interesting + tile.faceRight = false; + } + } + } + } + + }, + + /** + * Gets the tile above the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileAbove + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileAbove: function (layer, x, y) { + + if (y > 0) + { + return this.layers[layer].data[y - 1][x]; + } + + return null; + + }, + + /** + * Gets the tile below the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileBelow + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileBelow: function (layer, x, y) { + + if (y < this.layers[layer].height - 1) + { + return this.layers[layer].data[y + 1][x]; + } + + return null; + + }, + + /** + * Gets the tile to the left of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileLeft + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileLeft: function (layer, x, y) { + + if (x > 0) + { + return this.layers[layer].data[y][x - 1]; + } + + return null; + + }, + + /** + * Gets the tile to the right of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileRight + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileRight: function (layer, x, y) { + + if (x < this.layers[layer].width - 1) + { + return this.layers[layer].data[y][x + 1]; + } + + return null; + + }, + + /** + * Sets the current layer to the given index. + * + * @method Phaser.Tilemap#setLayer + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + */ + setLayer: function (layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer]) + { + this.currentLayer = layer; + } + + }, + + /** + * Checks if there is a tile at the given location. + * + * @method Phaser.Tilemap#hasTile + * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels) + * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + * @return {boolean} True if there is a tile at the given location, otherwise false. + */ + hasTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined) + { + return false; + } + + return (this.layers[layer].data[y][x].index > -1); + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. + * + * @method Phaser.Tilemap#removeTile + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.hasTile(x, y, layer)) + { + var tile = this.layers[layer].data[y][x]; + + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight); + + this.layers[layer].dirty = true; + + this.calculateFaces(layer); + + return tile; + } + } + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#removeTileWorldXY + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTileWorldXY: function (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.removeTile(x, y, layer); + + }, + + /** + * Puts a tile of the given index value at the coordinate specified. + * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. + * + * @method Phaser.Tilemap#putTile + * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map. + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + putTile: function (tile, x, y, layer) { + + if (tile === null) + { + return this.removeTile(x, y, layer); + } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + var index; + + if (tile instanceof Phaser.Tile) + { + index = tile.index; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].copy(tile); + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height); + } + } + else + { + index = tile; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].index = index; + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight); + } + } + + if (this.collideIndexes.indexOf(index) > -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; + + }, + + /** + * Puts a tile into the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#putTileWorldXY + * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object. + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + 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); + + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. + * If no match is found it returns null. + * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. + * + * @method Phaser.Tilemap#searchTileIndex + * @param {number} index - The tile index value to search for. + * @param {number} [skip=0] - The number of times to skip a matching tile before returning. + * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @return {Phaser.Tile} The first (or n skipped) tile with the matching index. + */ + searchTileIndex: function (index, skip, reverse, layer) { + + if (skip === undefined) { skip = 0; } + if (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 < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + if (this.layers[layer].data[y][x].index === index) + { + if (c === skip) + { + return this.layers[layer].data[y][x]; + } + else + { + c++; + } + } + } + } + } + + return null; + + }, + + /** + * Gets a tile from the Tilemap Layer. The coordinates are given in tile values. + * + * @method Phaser.Tilemap#getTile + * @param {number} x - X position to get the tile from (given in tile units, not pixels) + * @param {number} y - Y position to get the tile from (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTile: function (x, y, layer, nonNull) { + + if (nonNull === undefined) { nonNull = false; } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.layers[layer].data[y][x].index === -1) + { + if (nonNull) + { + return this.layers[layer].data[y][x]; + } + else + { + return null; + } + } + else + { + return this.layers[layer].data[y][x]; + } + } + else + { + return null; + } + + }, + + /** + * Gets a tile from the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#getTileWorldXY + * @param {number} x - X position to get the tile from (given in pixels) + * @param {number} y - Y position to get the tile from (given in pixels) + * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used. + * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates. + */ + getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) { + + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + + layer = this.getLayer(layer); + + x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; + y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; + + return this.getTile(x, y, layer, nonNull); + + }, + + /** + * Copies all of the tiles in the given rectangular block into the tilemap data buffer. + * + * @method Phaser.Tilemap#copy + * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} width - The width of the area to copy (given in tiles, not pixels) + * @param {integer} height - The height of the area to copy (given in tiles, not pixels) + * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from. + * @return {array} An array of the tiles that were copied. + */ + copy: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + if (!this.layers[layer]) + { + this._results.length = 0; + return; + } + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.layers[layer].width; } + if (height === undefined) { height = this.layers[layer].height; } + + if (x < 0) + { + x = 0; + } + + if (y < 0) + { + y = 0; + } + + if (width > this.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; ty < y + height; ty++) + { + for (var tx = x; tx < x + width; tx++) + { + this._results.push(this.layers[layer].data[ty][tx]); + } + } + + return this._results; + + }, + + /** + * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. + * + * @method Phaser.Tilemap#paste + * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels) + * @param {array} tileblock - The block of tiles to paste. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into. + */ + paste: function (x, y, tileblock, layer) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + layer = this.getLayer(layer); + + if (!tileblock || tileblock.length < 2) + { + return; + } + + // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste + var diffX = x - tileblock[1].x; + var diffY = y - tileblock[1].y; + + for (var i = 1; i < tileblock.length; i++) + { + this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]); + } + + this.layers[layer].dirty = true; + this.calculateFaces(layer); + + }, + + /** + * Scans the given area for tiles with an index matching tileA and swaps them with tileB. + * + * @method Phaser.Tilemap#swap + * @param {number} tileA - First tile index. + * @param {number} tileB - Second tile index. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + swap: function (tileA, tileB, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._tempA = tileA; + this._tempB = tileB; + + this._results.forEach(this.swapHandler, this); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Internal function that handles the swapping of tiles. + * + * @method Phaser.Tilemap#swapHandler + * @private + * @param {number} value + */ + swapHandler: function (value) { + + if (value.index === this._tempA) + { + // Swap A with B + value.index = this._tempB; + } + else if (value.index === this._tempB) + { + // Swap B with A + value.index = this._tempA; + } + + }, + + /** + * For each tile in the given area defined by x/y and width/height run the given callback. + * + * @method Phaser.Tilemap#forEach + * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {number} context - The context under which the callback should be run. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + forEach: function (callback, context, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._results.forEach(callback, context); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. + * + * @method Phaser.Tilemap#replace + * @param {number} source - The tile index value to scan for. + * @param {number} dest - The tile index value to replace found tiles with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + replace: function (source, dest, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + if (this._results[i].index === source) + { + this._results[i].index = dest; + } + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Randomises a set of tiles in a given area. + * + * @method Phaser.Tilemap#random + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + random: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + var idx = this._results[t].index; + + if (indexes.indexOf(idx) === -1) + { + indexes.push(idx); + } + } + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = this.game.rnd.pick(indexes); + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! + * + * @method Phaser.Tilemap#shuffle + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + shuffle: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + indexes.push(this._results[t].index); + } + } + + Phaser.ArrayUtils.shuffle(indexes); + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = indexes[i - 1]; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Fills the given area with the specified tile. + * + * @method Phaser.Tilemap#fill + * @param {number} index - The index of the tile that the area will be filled with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + fill: function (index, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = index; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Removes all layers from this tile map. + * + * @method Phaser.Tilemap#removeAllLayers + */ + removeAllLayers: function () { + + this.layers.length = 0; + this.currentLayer = 0; + + }, + + /** + * Dumps the tilemap data out to the console. + * + * @method Phaser.Tilemap#dump + */ + dump: function () { + + var txt = ''; + var args = ['']; + + for (var y = 0; y < this.layers[this.currentLayer].height; y++) + { + for (var x = 0; x < this.layers[this.currentLayer].width; x++) + { + txt += "%c "; + + if (this.layers[this.currentLayer].data[y][x] > 1) + { + 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); + + }, + + /** + * Removes all layer data from this tile map and nulls the game reference. + * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. + * + * @method Phaser.Tilemap#destroy + */ + destroy: function () { + + this.removeAllLayers(); + this.data = []; + this.game = null; + + } + +}; + +Phaser.Tilemap.prototype.constructor = Phaser.Tilemap; + +/** +* @name Phaser.Tilemap#layer +* @property {number|string|Phaser.TilemapLayer} layer - The current layer object. +*/ +Object.defineProperty(Phaser.Tilemap.prototype, "layer", { + + get: function () { + + return this.layers[this.currentLayer]; + + }, + + set: function (value) { + + if (value !== this.currentLayer) + { + this.setLayer(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. +* +* Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. +* +* By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. +* +* @class Phaser.TilemapLayer +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs. +* @param {integer} index - The index of the TileLayer to render within the Tilemap. +* @param {integer} width - Width of the renderable area of the layer (in pixels). +* @param {integer} height - Height of the renderable area of the layer (in pixels). +*/ +Phaser.TilemapLayer = function (game, tilemap, index, width, height) { + + width |= 0; + height |= 0; + + Phaser.Sprite.call(this, game, 0, 0); + + /** + * The Tilemap to which this layer is bound. + * @property {Phaser.Tilemap} map + * @protected + * @readonly + */ + this.map = tilemap; + + /** + * The index of this layer within the Tilemap. + * @property {number} index + * @protected + * @readonly + */ + this.index = index; + + /** + * The layer object within the Tilemap that this layer represents. + * @property {object} layer + * @protected + * @readonly + */ + this.layer = tilemap.layers[index]; + + /** + * The canvas to which this TilemapLayer draws. + * @property {HTMLCanvasElement} canvas + * @protected + */ + this.canvas = Phaser.CanvasPool.create(this, width, height); + + /** + * The 2d context of the canvas. + * @property {CanvasRenderingContext2D} context + * @private + */ + this.context = this.canvas.getContext('2d'); + + this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas, null, this.game.resolution))); + + /** + * The const type of this object. + * @property {number} type + * @readonly + * @protected + * @default Phaser.TILEMAPLAYER + */ + this.type = Phaser.TILEMAPLAYER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.TILEMAPLAYER; + + /** + * Settings that control standard (non-diagnostic) rendering. + * + * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view. + * This can greatly improve scrolling rendering performance, especially when there are many small tiles. + * It should only be disabled in rare cases. + * + * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas. + * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior + * in some browsers, notably Safari. + * + * @default + */ + this.renderSettings = { + enableScrollDelta: true, + overdrawRatio: 0.20, + copyCanvas: null + }; + + /** + * Enable an additional "debug rendering" pass to display collision information. + * + * @property {boolean} debug + * @default + */ + this.debug = false; + + /** + * @property {boolean} exists - Controls if the core game loop and physics update this game object or not. + */ + this.exists = true; + + /** + * Settings used for debugging and diagnostics. + * + * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. + * + * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. + * + * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. + * + * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. + * + */ + this.debugSettings = { + + missingImageFill: 'rgb(255,255,255)', + debuggedTileOverfill: 'rgba(0,255,0,0.4)', + + forceFullRedraw: true, + + debugAlpha: 0.5, + facingEdgeStroke: 'rgba(0,255,0,1)', + collidingTileOverfill: 'rgba(0,255,0,0.2)' + + }; + + /** + * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). + * @property {number} scrollFactorX + * @public + * @default + */ + this.scrollFactorX = 1; + + /** + * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) + * @property {number} scrollFactorY + * @public + * @default + */ + this.scrollFactorY = 1; + + /** + * If true tiles will be force rendered, even if such is not believed to be required. + * @property {boolean} dirty + * @protected + */ + this.dirty = true; + + /** + * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. + * @property {integer} rayStepRate + * @default + */ + this.rayStepRate = 4; + + /** + * Flag controlling if the layer tiles wrap at the edges. + * @property {boolean} _wrap + * @private + */ + this._wrap = false; + + /** + * Local map data and calculation cache. + * @property {object} _mc + * @private + */ + this._mc = { + + // Used to bypass rendering without reliance on `dirty` and detect changes. + scrollX: 0, + scrollY: 0, + renderWidth: 0, + renderHeight: 0, + + tileWidth: tilemap.tileWidth, + tileHeight: tilemap.tileHeight, + + // Collision width/height (pixels) + // What purpose do these have? Most things use tile width/height directly. + // This also only extends collisions right and down. + cw: tilemap.tileWidth, + ch: tilemap.tileHeight, + + // Cached tilesets from index -> Tileset + tilesets: [] + + }; + + /** + * The current canvas left after scroll is applied. + * @property {number} _scrollX + * @private + */ + this._scrollX = 0; + + /** + * The current canvas top after scroll is applied. + * @property {number} _scrollY + * @private + */ + this._scrollY = 0; + + /** + * The position offset of the layer's tiles. + * @property {Phaser.Point} + */ + this.tileOffset = new Phaser.Point(this.layer.offsetX || 0, this.layer.offsetY || 0); + + /** + * Used for caching the tiles / array of tiles. + * @property {Phaser.Tile[]} _results + * @private + */ + this._results = []; + + if (!game.device.canvasBitBltShift) + { + this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas(); + } + + this.fixedToCamera = true; + +}; + +Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer; + +Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* The shared double-copy canvas, created as needed. +* +* @private +* @static +*/ +Phaser.TilemapLayer.sharedCopyCanvas = null; + +/** +* Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. +* +* Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. +* +* @method Phaser.TilemapLayer#ensureSharedCopyCanvas +* @protected +* @static +*/ +Phaser.TilemapLayer.ensureSharedCopyCanvas = function () { + + if (!this.sharedCopyCanvas) + { + this.sharedCopyCanvas = Phaser.CanvasPool.create(this, 2, 2); + } + + return this.sharedCopyCanvas; + +}; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TilemapLayer#preUpdate +*/ +Phaser.TilemapLayer.prototype.preUpdate = function() { + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.postUpdate. Handles cache updates. +* +* @method Phaser.TilemapLayer#postUpdate +* @protected +*/ +Phaser.TilemapLayer.prototype.postUpdate = function () { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderCanvas function. +* +* @method Phaser.TilemapLayer#_renderCanvas +* @private +*/ +Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderWebGL function. +* +* @method Phaser.TilemapLayer#_renderWebGL +* @private +*/ +Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Destroys this TilemapLayer. +* +* @method Phaser.TilemapLayer#destroy +*/ +Phaser.TilemapLayer.prototype.destroy = function() { + + Phaser.CanvasPool.remove(this); + + Phaser.Component.Destroy.prototype.destroy.call(this); + +}; + +/** +* Resizes the internal canvas and texture frame used by this TilemapLayer. +* +* This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully +* selected times. +* +* Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not +* modified either. You will have to handle both of these things from your game code if required. +* +* @method Phaser.TilemapLayer#resize +* @param {number} width - The new width of the TilemapLayer +* @param {number} height - The new height of the TilemapLayer +*/ +Phaser.TilemapLayer.prototype.resize = function (width, height) { + + this.canvas.width = width; + this.canvas.height = height; + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.texture.baseTexture.width = width; + this.texture.baseTexture.height = height; + + this.texture.baseTexture.dirty(); + this.texture.requiresUpdate = true; + + this.texture._updateUvs(); + + this.dirty = true; + +}; + +/** +* Sets the world size to match the size of this layer. +* +* @method Phaser.TilemapLayer#resizeWorld +* @public +*/ +Phaser.TilemapLayer.prototype.resizeWorld = function () { + + this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y); + +}; + +/** + * Get the X axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getLayerOffsetX + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetX = function () { + + return this.tileOffset.x || ((!this.fixedToCamera) ? this.position.x : 0); + +}; + +/** + * Get the Y axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getTileOffsetY + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetY = function () { + + return this.tileOffset.y || ((!this.fixedToCamera) ? this.position.y : 0); + +}; + +/** +* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixX +* @private +* @param {number} x - x coordinate in camera space +* @return {number} x coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixX = function (x) { + + if (this.scrollFactorX === 1 || (this.scrollFactorX === 0 && this.position.x === 0)) + { + return x; + } + + // This executes if the scrollFactorX is 0 and the x position of the tilemap is off from standard. + if (this.scrollFactorX === 0 && this.position.x !== 0) + { + return x - this.position.x; + } + + return this._scrollX + (x - (this._scrollX / this.scrollFactorX)); + +}; + +/** +* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixX +* @private +* @param {number} x - x coordinate in scrollFactor-adjusted dimensions +* @return {number} x coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixX = function (x) { + + if (this.scrollFactorX === 1) + { + return x; + } + + return (this._scrollX / this.scrollFactorX) + (x - this._scrollX); + +}; + +/** +* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixY +* @private +* @param {number} y - y coordinate in camera space +* @return {number} y coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixY = function (y) { + + if (this.scrollFactorY === 1 || (this.scrollFactorY === 0 && this.position.y === 0)) + { + return y; + } + + // This executes if the scrollFactorY is 0 and the y position of the tilemap is off from standard. + if (this.scrollFactorY === 0 && this.position.y !== 0) + { + return y - this.position.y; + } + + return this._scrollY + (y - (this._scrollY / this.scrollFactorY)); + +}; + +/** +* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixY +* @private +* @param {number} y - y coordinate in scrollFactor-adjusted dimensions +* @return {number} y coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixY = function (y) { + + if (this.scrollFactorY === 1) + { + return y; + } + + return (this._scrollY / this.scrollFactorY) + (y - this._scrollY); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileX +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @return {integer} The X map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileX = function (x) { + + // var tileWidth = this.tileWidth * this.scale.x; + return Math.floor(this._fixX(x) / this._mc.tileWidth); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileY +* @public +* @param {number} y - Y position of the point in target tile (in pixels). +* @return {integer} The Y map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileY = function (y) { + + // var tileHeight = this.tileHeight * this.scale.y; + return Math.floor(this._fixY(y) / this._mc.tileHeight); + +}; + +/** +* Convert a pixel coordinate to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileXY +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @param {number} y - Y position of the point in target tile (in pixels). +* @param {(Phaser.Point|object)} point - The Point/object to update. +* @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set. +*/ +Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) { + + point.x = this.getTileX(x); + point.y = this.getTileY(y); + + return point; + +}; + +/** +* Gets all tiles that intersect with the given line. +* +* @method Phaser.TilemapLayer#getRayCastTiles +* @public +* @param {Phaser.Line} line - The line used to determine which tiles to return. +* @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`. +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {Phaser.Tile[]} An array of Phaser.Tiles. +*/ +Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) { + + if (!stepRate) { stepRate = this.rayStepRate; } + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + // First get all tiles that touch the bounds of the line + var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace); + + if (tiles.length === 0) + { + return []; + } + + // Now we only want the tiles that intersect with the points on this line + var coords = line.coordinatesOnLine(stepRate); + var results = []; + + for (var i = 0; i < tiles.length; i++) + { + for (var t = 0; t < coords.length; t++) + { + var tile = tiles[i]; + var coord = coords[t]; + if (tile.containsPoint(coord[0], coord[1])) + { + results.push(tile); + break; + } + } + } + + return results; + +}; + +/** +* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. +* +* @method Phaser.TilemapLayer#getTiles +* @public +* @param {number} x - X position of the top left corner (in pixels). +* @param {number} y - Y position of the top left corner (in pixels). +* @param {number} width - Width of the area to get (in pixels). +* @param {number} height - Height of the area to get (in pixels). +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {array} An array of Tiles. +*/ +Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) { + + // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all) + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + var fetchAll = !(collides || interestingFace); + + // Adjust the x,y coordinates for scrollFactor + x = this._fixX(x); + y = this._fixY(y); + + // Convert the pixel values into tile coordinates + var tx = Math.floor(x / (this._mc.cw * this.scale.x)); + var ty = Math.floor(y / (this._mc.ch * this.scale.y)); + // Don't just use ceil(width/cw) to allow account for x/y diff within cell + var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx; + var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty; + + while (this._results.length) + { + this._results.pop(); + } + + for (var wy = ty; wy < ty + th; wy++) + { + for (var wx = tx; wx < tx + tw; wx++) + { + var row = this.layer.data[wy]; + + if (row && row[wx]) + { + if (fetchAll || row[wx].isInteresting(collides, interestingFace)) + { + this._results.push(row[wx]); + } + } + } + } + + return this._results.slice(); + +}; + +/** +* Returns the appropriate tileset for the index, updating the internal cache as required. +* This should only be called if `tilesets[index]` evaluates to undefined. +* +* @method Phaser.TilemapLayer#resolveTileset +* @private +* @param {integer} Tile index +* @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping. +*/ +Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) { + + var tilesets = this._mc.tilesets; + + // Try for dense array if reasonable + if (tileIndex < 2000) + { + while (tilesets.length < tileIndex) + { + tilesets.push(undefined); + } + } + + var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2]; + + if (setIndex !== null) + { + var tileset = this.map.tilesets[setIndex]; + + if (tileset && tileset.containsTileIndex(tileIndex)) + { + return (tilesets[tileIndex] = tileset); + } + } + + return (tilesets[tileIndex] = null); + +}; + +/** +* The TilemapLayer caches tileset look-ups. +* +* Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. +* +* @method Phaser.TilemapLayer#resetTilesetCache +* @public +*/ +Phaser.TilemapLayer.prototype.resetTilesetCache = function () { + + var tilesets = this._mc.tilesets; + + while (tilesets.length) + { + tilesets.pop(); + } + +}; + +/** + * This method will set the scale of the tilemap as well as update the underlying block data of this layer. + * + * @method Phaser.TilemapLayer#setScale + * @param {number} [xScale=1] - The scale factor along the X-plane + * @param {number} [yScale] - The scale factor along the Y-plane + */ +Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) { + + xScale = xScale || 1; + yScale = yScale || xScale; + + for (var y = 0; y < this.layer.data.length; y++) + { + var row = this.layer.data[y]; + + for (var x = 0; x < row.length; x++) + { + var tile = row[x]; + + tile.width = this.map.tileWidth * xScale; + tile.height = this.map.tileHeight * yScale; + + tile.worldX = tile.x * tile.width; + tile.worldY = tile.y * tile.height; + } + } + + this.scale.setTo(xScale, yScale); + +}; + +/** +* Shifts the contents of the canvas - does extra math so that different browsers agree on the result. +* +* The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in. +* +* @method Phaser.TilemapLayer#shiftCanvas +* @private +* @param {CanvasRenderingContext2D} context - The context to shift +* @param {integer} x +* @param {integer} y +*/ +Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) { + + var canvas = context.canvas; + var copyW = canvas.width - Math.abs(x); + var copyH = canvas.height - Math.abs(y); + + // When x/y non-negative + var dx = 0; + var dy = 0; + var sx = x; + var sy = y; + + if (x < 0) + { + dx = -x; + sx = 0; + } + + if (y < 0) + { + dy = -y; + sy = 0; + } + + var copyCanvas = this.renderSettings.copyCanvas; + + if (copyCanvas) + { + // Use a second copy buffer, without slice support, for Safari .. again. + // Ensure copy canvas is large enough + if (copyCanvas.width < copyW || copyCanvas.height < copyH) + { + copyCanvas.width = copyW; + copyCanvas.height = copyH; + } + + var copyContext = copyCanvas.getContext('2d'); + copyContext.clearRect(0, 0, copyW, copyH); + copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH); + // clear allows default 'source-over' semantics + context.clearRect(sx, sy, copyW, copyH); + context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH); + } + else + { + // Avoids a second copy but flickers in Safari / Safari Mobile + // Ref. https://github.com/photonstorm/phaser/issues/1439 + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH); + context.restore(); + } + +}; + +/** +* Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor. +* This will constrain the tile coordinates based on wrapping but not physical coordinates. +* +* @method Phaser.TilemapLayer#renderRegion +* @private +* @param {integer} scrollX - Render x offset/scroll. +* @param {integer} scrollY - Render y offset/scroll. +* @param {integer} left - Leftmost column to render. +* @param {integer} top - Topmost row to render. +* @param {integer} right - Rightmost column to render. +* @param {integer} bottom - Bottommost row to render. +*/ +Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) { + + var context = this.context; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var tilesets = this._mc.tilesets; + var lastAlpha = NaN; + + if (!this._wrap) + { + if (left <= right) // Only adjust if going to render + { + left = Math.max(0, left); + right = Math.min(width - 1, right); + } + if (top <= bottom) + { + top = Math.max(0, top); + bottom = Math.min(height - 1, bottom); + } + } + + // top-left pixel of top-left cell + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values. + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + // tx/ty - are pixel coordinates where tile is drawn + // x/y - is cell location, normalized [0..width/height) in loop + // xmax/ymax - remaining cells to render on column/row + var tx, ty, x, y, xmax, ymax; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + + if (!tile || tile.index < 0) + { + continue; + } + + var index = tile.index; + + var set = tilesets[index]; + + if (set === undefined) + { + set = this.resolveTileset(index); + } + + // Setting the globalAlpha is "surprisingly expensive" in Chrome (38) + if (tile.alpha !== lastAlpha && !this.debug) + { + context.globalAlpha = tile.alpha; + lastAlpha = tile.alpha; + } + + if (set) + { + if (tile.rotation || tile.flipped) + { + context.save(); + context.translate(tx + tile.centerX, ty + tile.centerY); + context.rotate(tile.rotation); + + if (tile.flipped) + { + context.scale(-1, 1); + } + + set.draw(context, -tile.centerX, -tile.centerY, index); + context.restore(); + } + else + { + set.draw(context, tx, ty, index); + } + } + else if (this.debugSettings.missingImageFill) + { + context.fillStyle = this.debugSettings.missingImageFill; + context.fillRect(tx, ty, tw, th); + } + + if (tile.debug && this.debugSettings.debuggedTileOverfill) + { + context.fillStyle = this.debugSettings.debuggedTileOverfill; + context.fillRect(tx, ty, tw, th); + } + + } + + } + +}; + +/** +* Shifts the canvas and render damaged edge tiles. +* +* @method Phaser.TilemapLayer#renderDeltaScroll +* @private +*/ +Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds. + + // Start in pixels + var left = 0; + var right = -tw; + var top = 0; + var bottom = -th; + + if (shiftX < 0) // layer moving left, damage right + { + left = renderW + shiftX; // shiftX neg. + right = renderW - 1; + } + else if (shiftX > 0) + { + // left -> 0 + right = shiftX; + } + + if (shiftY < 0) // layer moving down, damage top + { + top = renderH + shiftY; // shiftY neg. + bottom = renderH - 1; + } + else if (shiftY > 0) + { + // top -> 0 + bottom = shiftY; + } + + this.shiftCanvas(this.context, shiftX, shiftY); + + // Transform into tile-space + left = Math.floor((left + scrollX) / tw); + right = Math.floor((right + scrollX) / tw); + top = Math.floor((top + scrollY) / th); + bottom = Math.floor((bottom + scrollY) / th); + + if (left <= right) + { + // Clear left or right edge + this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH); + + var trueTop = Math.floor((0 + scrollY) / th); + var trueBottom = Math.floor((renderH - 1 + scrollY) / th); + this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom); + } + + if (top <= bottom) + { + // Clear top or bottom edge + this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th); + + var trueLeft = Math.floor((0 + scrollX) / tw); + var trueRight = Math.floor((renderW - 1 + scrollX) / tw); + this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom); + } + +}; + +/** +* Clear and render the entire canvas. +* +* @method Phaser.TilemapLayer#renderFull +* @private +*/ +Phaser.TilemapLayer.prototype.renderFull = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + this.context.clearRect(0, 0, renderW, renderH); + + this.renderRegion(scrollX, scrollY, left, top, right, bottom); + +}; + +/** +* Renders the tiles to the layer canvas and pushes to the display. +* +* @method Phaser.TilemapLayer#render +* @protected +*/ +Phaser.TilemapLayer.prototype.render = function () { + + var redrawAll = false; + + if (!this.visible) + { + return; + } + + if (this.dirty || this.layer.dirty) + { + this.layer.dirty = false; + redrawAll = true; + } + + var renderWidth = this.canvas.width; // Use Sprite.width/height? + var renderHeight = this.canvas.height; + + // Scrolling bias; whole pixels only + var scrollX = this._scrollX | 0; + var scrollY = this._scrollY | 0; + + var mc = this._mc; + var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down + var shiftY = mc.scrollY - scrollY; + + if (!redrawAll && + shiftX === 0 && shiftY === 0 && + mc.renderWidth === renderWidth && mc.renderHeight === renderHeight) + { + // No reason to redraw map, looking at same thing and not invalidated. + return; + } + + this.context.save(); + + mc.scrollX = scrollX; + mc.scrollY = scrollY; + + if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight) + { + // Could support automatic canvas resizing + mc.renderWidth = renderWidth; + mc.renderHeight = renderHeight; + } + + if (this.debug) + { + this.context.globalAlpha = this.debugSettings.debugAlpha; + + if (this.debugSettings.forceFullRedraw) + { + redrawAll = true; + } + } + + if (!redrawAll && + this.renderSettings.enableScrollDelta && + (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight)) + { + this.renderDeltaScroll(shiftX, shiftY); + } + else + { + // Too much change or otherwise requires full render + this.renderFull(); + } + + if (this.debug) + { + this.context.globalAlpha = 1; + this.renderDebug(); + } + + this.texture.baseTexture.dirty(); + + this.dirty = false; + + this.context.restore(); + + return true; + +}; + +/** +* Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true. +* +* See `debugSettings` for assorted configuration options. +* +* @method Phaser.TilemapLayer#renderDebug +* @private +*/ +Phaser.TilemapLayer.prototype.renderDebug = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var context = this.context; + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + var tx, ty, x, y, xmax, ymax; + + context.strokeStyle = this.debugSettings.facingEdgeStroke; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + if (!tile || tile.index < 0 || !tile.collides) + { + continue; + } + + if (this.debugSettings.collidingTileOverfill) + { + context.fillStyle = this.debugSettings.collidingTileOverfill; + context.fillRect(tx, ty, this._mc.cw, this._mc.ch); + } + + if (this.debugSettings.facingEdgeStroke) + { + context.beginPath(); + + if (tile.faceTop) + { + context.moveTo(tx, ty); + context.lineTo(tx + this._mc.cw, ty); + } + + if (tile.faceBottom) + { + context.moveTo(tx, ty + this._mc.ch); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + if (tile.faceLeft) + { + context.moveTo(tx, ty); + context.lineTo(tx, ty + this._mc.ch); + } + + if (tile.faceRight) + { + context.moveTo(tx + this._mc.cw, ty); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + context.closePath(); + + context.stroke(); + } + + } + + } + +}; + +/** +* Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size. +* +* @property {boolean} wrap +* @memberof Phaser.TilemapLayer +* @public +* @default false +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", { + + get: function () { + return this._wrap; + }, + + set: function (value) { + this._wrap = value; + this.dirty = true; + } + +}); + +/** +* Scrolls the map horizontally or returns the current x position. +* +* @property {number} scrollX +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", { + + get: function () { + return this._scrollX; + }, + + set: function (value) { + this._scrollX = value; + } + +}); + +/** +* Scrolls the map vertically or returns the current y position. +* +* @property {number} scrollY +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", { + + get: function () { + return this._scrollY; + }, + + set: function (value) { + this._scrollY = value; + } + +}); + +/** +* The width of the collision tiles (in pixels). +* +* @property {integer} collisionWidth +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", { + + get: function () { + return this._mc.cw; + }, + + set: function (value) { + this._mc.cw = value | 0; + this.dirty = true; + } + +}); + +/** +* The height of the collision tiles (in pixels). +* +* @property {integer} collisionHeight +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", { + + get: function () { + return this._mc.ch; + }, + + set: function (value) { + this._mc.ch = value | 0; + this.dirty = true; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. +* +* @class Phaser.TilemapParser +* @static +*/ +Phaser.TilemapParser = { + + /** + * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or + * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type + * depends how this should be configured. If you've a large sparsely populated map and the tile + * data doesn't need to change then setting this value to `true` will help with memory consumption. + * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes + * during the game) then leave the default value set. + * + * @constant + * @type {boolean} + */ + INSERT_NULL: false, + + /** + * Parse tilemap data from the cache and creates data for a Tilemap object. + * + * @method Phaser.TilemapParser.parse + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {string} key - The key of the tilemap in the Cache. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {object} The parsed map object. + */ + parse: function (game, key, tileWidth, tileHeight, width, height) { + + if (tileWidth === undefined) { tileWidth = 32; } + if (tileHeight === undefined) { tileHeight = 32; } + if (width === undefined) { width = 10; } + if (height === undefined) { height = 10; } + + if (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); + } + + }, + + /** + * Parses a CSV file into valid map data. + * + * @method Phaser.TilemapParser.parseCSV + * @param {string} key - The name you want to give the map data. + * @param {string} data - The CSV file data. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @return {object} Generated map data. + */ + parseCSV: function (key, data, tileWidth, tileHeight) { + + var map = this.getEmptyData(); + + // Trim any rogue whitespace from the data + data = data.trim(); + + var output = []; + var rows = data.split("\n"); + var height = rows.length; + var width = 0; + + for (var y = 0; y < rows.length; y++) + { + output[y] = []; + + var column = rows[y].split(","); + + for (var x = 0; x < column.length; x++) + { + output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight); + } + + if (width === 0) + { + width = column.length; + } + } + + map.format = Phaser.Tilemap.CSV; + map.name = key; + map.width = width; + map.height = height; + map.tileWidth = tileWidth; + map.tileHeight = tileHeight; + map.widthInPixels = width * tileWidth; + map.heightInPixels = height * tileHeight; + + map.layers[0].width = width; + map.layers[0].height = height; + map.layers[0].widthInPixels = map.widthInPixels; + map.layers[0].heightInPixels = map.heightInPixels; + map.layers[0].data = output; + + return map; + + }, + + /** + * Returns an empty map data object. + * + * @method Phaser.TilemapParser.getEmptyData + * @return {object} Generated map data. + */ + getEmptyData: function (tileWidth, tileHeight, width, height) { + + return { + width: (width !== undefined && width !== null) ? width : 0, + height: (height !== undefined && height !== null) ? height : 0, + tileWidth: (tileWidth !== undefined && tileWidth !== null) ? tileWidth : 0, + tileHeight: (tileHeight !== undefined && tileHeight !== null) ? tileHeight : 0, + orientation: 'orthogonal', + version: '1', + properties: {}, + widthInPixels: 0, + heightInPixels: 0, + layers: [ + { + name: 'layer', + x: 0, + y: 0, + width: 0, + height: 0, + widthInPixels: 0, + heightInPixels: 0, + alpha: 1, + visible: true, + properties: {}, + indexes: [], + callbacks: [], + bodies: [], + data: [] + } + ], + images: [], + objects: {}, + collision: {}, + tilesets: [], + tiles: [] + }; + + }, + + _slice: function(obj, fields) { + var sliced = {}; + + for (var k in fields) + { + var key = fields[k]; + + if (typeof obj[key] !== 'undefined') + { + sliced[key] = obj[key]; + } + } + + return sliced; + }, + + /** + * Parses an object group in Tiled JSON files. Object groups can be found in both layers and tilesets. Called internally in parseTiledJSON. + * @method Phaser.TilemapParser.parseObjectGroup + * @param {object} objectGroup - A JSON object group. + * @param {object} objectsCollection - An object into which new array of Tiled map objects will be added. + * @param {object} collisionCollection - An object into which new array of collision objects will be added. Currently only polylines are added. + * @param {string} [nameKey=objectGroup.name] - Key under which to store objects in collisions in objectsCollection and collisionCollection + * @param {object} [relativePosition={x: 0, y: 0}] - Coordinates the object group's position is relative to. + * @return {object} A object literal containing the objectsCollection and collisionCollection + */ + parseObjectGroup: function(objectGroup, objectsCollection, collisionCollection, nameKey, relativePosition) { + + var nameKey = nameKey || objectGroup.name; + var relativePosition = relativePosition || {x: 0, y: 0}; + var slice = this._slice; + + if (!nameKey) + { + console.warn('No name found for objectGroup', objectGroup); + } + + if (relativePosition.x === undefined || relativePosition.y === undefined) + { + console.warn('Malformed xy properties in relativePosition', relativePosition); + } + + objectsCollection[nameKey] = objectsCollection[nameKey] || []; + collisionCollection[nameKey] = collisionCollection[nameKey] || []; + + for (var v = 0, len = objectGroup.objects.length; v < len; v++) + { + var o = objectGroup.objects[v]; + + // Object Tiles + if (o.gid) + { + var object = { + gid: o.gid, + name: o.name, + type: o.type || '', + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + objectsCollection[nameKey].push(object); + } + else if (o.polyline) + { + var object = { + name: o.name, + type: o.type, + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + object.polyline = []; + + // Parse the polyline into an array + for (var p = 0; p < o.polyline.length; p++) + { + object.polyline.push([o.polyline[p].x, o.polyline[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // polygon + else if (o.polygon) + { + var object = slice(o, ['name', 'type', 'x', 'y', 'visible', 'rotation', 'properties']); + + object.x += relativePosition.x; + object.y += relativePosition.y; + + // Parse the polygon into an array + object.polygon = []; + + for (var p = 0; p < o.polygon.length; p++) + { + object.polygon.push([o.polygon[p].x, o.polygon[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // ellipse + else if (o.ellipse) + { + var object = slice(o, ['name', 'type', 'ellipse', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // otherwise it's a rectangle + else + { + var object = slice(o, ['name', 'type', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + object.rectangle = true; + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + } + + return { + objectsCollection: objectsCollection, + collisionCollection: collisionCollection + }; + }, + + /** + * Parses a Tiled JSON file into valid map data. + * @method Phaser.TilemapParser.parseTiledJSON + * @param {object} json - The JSON map data. + * @return {object} Generated and parsed map data. + */ + parseTiledJSON: function (json) { + + if (json.orientation !== 'orthogonal') + { + console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser'); + return null; + } + + // Map data will consist of: layers, objects, images, tilesets, sizes + var map = { + width: json.width, + height: json.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + orientation: json.orientation, + format: Phaser.Tilemap.TILED_JSON, + version: json.version, + properties: json.properties, + widthInPixels: json.width * json.tilewidth, + heightInPixels: json.height * json.tileheight + }; + + // Tile Layers + var layers = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'tilelayer') + { + continue; + } + + var curl = json.layers[i]; + + // Base64 decode data if necessary + // NOTE: uncompressed base64 only. + + if (!curl.compression && curl.encoding && curl.encoding === 'base64') + { + var binaryString = window.atob(curl.data); + var len = binaryString.length; + var bytes = new Array(len); + + // Interpret binaryString as an array of bytes representing + // little-endian encoded uint32 values. + for (var j = 0; j < len; j+=4) + { + bytes[j / 4] = ( + binaryString.charCodeAt(j) | + binaryString.charCodeAt(j + 1) << 8 | + binaryString.charCodeAt(j + 2) << 16 | + binaryString.charCodeAt(j + 3) << 24 + ) >>> 0; + } + + curl.data = bytes; + + delete curl.encoding; + } + else if (curl.compression) + { + console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\''); + continue; + } + + var layer = { + + name: curl.name, + x: curl.x, + y: curl.y, + width: curl.width, + height: curl.height, + widthInPixels: curl.width * json.tilewidth, + heightInPixels: curl.height * json.tileheight, + alpha: curl.opacity, + offsetX: curl.offsetx, + offsetY: curl.offsety, + visible: curl.visible, + properties: {}, + indexes: [], + callbacks: [], + bodies: [] + + }; + + if (curl.properties) + { + layer.properties = curl.properties; + } + + var x = 0; + var row = []; + var output = []; + var rotation, flipped, flippedVal, gid; + + // Loop through the data field in the JSON. + + // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV) + // If the map contains multiple tilesets then the indexes are relative to that which the set starts from. + // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset. + + for (var t = 0, len = curl.data.length; t < len; t++) + { + rotation = 0; + flipped = false; + gid = curl.data[t]; + flippedVal = 0; + + // If true the current tile is flipped or rotated (Tiled TMX format) + if (gid > 0x20000000) + { + // FlippedX + if (gid > 0x80000000) + { + gid -= 0x80000000; + flippedVal += 4; + } + + // FlippedY + if (gid > 0x40000000) + { + gid -= 0x40000000; + flippedVal += 2; + } + + // FlippedAD (anti-diagonal = top-right is swapped with bottom-left corners) + if (gid > 0x20000000) + { + gid -= 0x20000000; + flippedVal += 1; + } + + switch (flippedVal) + { + case 5: + rotation = Math.PI / 2; + break; + + case 6: + rotation = Math.PI; + break; + + case 3: + rotation = 3 * Math.PI / 2; + break; + + case 4: + rotation = 0; + flipped = true; + break; + + case 7: + rotation = Math.PI / 2; + flipped = true; + break; + + case 2: + rotation = Math.PI; + flipped = true; + break; + + case 1: + rotation = 3 * Math.PI / 2; + flipped = true; + break; + } + } + + // index, x, y, width, height + if (gid > 0) + { + var tile = new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight); + + tile.rotation = rotation; + tile.flipped = flipped; + + if (flippedVal !== 0) + { + // The WebGL renderer uses this to flip UV coordinates before drawing + tile.flippedVal = flippedVal; + } + + row.push(tile); + } + else + { + if (Phaser.TilemapParser.INSERT_NULL) + { + row.push(null); + } + else + { + row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight)); + } + } + + x++; + + if (x === curl.width) + { + output.push(row); + x = 0; + row = []; + } + } + + layer.data = output; + + layers.push(layer); + } + + map.layers = layers; + + // Images + var images = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'imagelayer') + { + continue; + } + + var curi = json.layers[i]; + + var image = { + + name: curi.name, + image: curi.image, + x: curi.x, + y: curi.y, + alpha: curi.opacity, + visible: curi.visible, + properties: {} + + }; + + if (curi.properties) + { + image.properties = curi.properties; + } + + images.push(image); + + } + + map.images = images; + + // Tilesets & Image Collections + var tilesets = []; + var tilesetGroupObjects = {}; + var imagecollections = []; + var lastSet = null; + + for (var i = 0; i < json.tilesets.length; i++) + { + // name, firstgid, width, height, margin, spacing, properties + var set = json.tilesets[i]; + + if (set.source) + { + console.warn('Phaser.TilemapParser - Phaser can\'t load external tilesets (%s). Use the Embed Tileset button and then export the map again.', set.source); + } + else if (set.image) + { + var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + if (set.tileproperties) + { + newSet.tileProperties = set.tileproperties; + } + + // For a normal sliced tileset the row/count/size information is computed when updated. + // This is done (again) after the image is set. + newSet.updateTileData(set.imagewidth, set.imageheight); + + tilesets.push(newSet); + } + else if (set.tiles) + { + var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + for (var ti in set.tiles) + { + var image = set.tiles[ti].image; + var gid = set.firstgid + parseInt(ti, 10); + newCollection.addImage(gid, image); + } + + imagecollections.push(newCollection); + } + else + { + throw new Error('Tileset ' + set.name + ' has no `image` or `tiles` property.'); + } + + // build a temporary object for objectgroups found in the tileset's tiles + for (var ti in set.tiles) + { + var objectGroup = set.tiles[ti].objectgroup; + + if (!objectGroup) + { + continue; + } + + tilesetGroupObjects[parseInt(ti, 10) + set.firstgid] = objectGroup; + } + + // We've got a new Tileset, so set the lastgid into the previous one + if (lastSet) + { + lastSet.lastgid = set.firstgid - 1; + } + + lastSet = set; + } + + if (tilesets.length === 0 && imagecollections.length === 0) + { + throw new Error('This tilemap has no tilesets.'); + } + + map.tilesets = tilesets; + map.imagecollections = imagecollections; + + // Objects & Collision Data (polylines, etc) + var objects = {}; + var collision = {}; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'objectgroup') + { + continue; + } + + var objectGroup = json.layers[i]; + this.parseObjectGroup(objectGroup, objects, collision); + } + + map.objects = objects; + map.collision = collision; + + map.tiles = []; + + // Finally lets build our super tileset index + for (var i = 0; i < map.tilesets.length; i++) + { + var set = map.tilesets[i]; + + var x = set.tileMargin; + var y = set.tileMargin; + + var count = 0; + var countX = 0; + var countY = 0; + + for (var t = set.firstgid; t < set.firstgid + set.total; t++) + { + // Can add extra properties here as needed + map.tiles[t] = [x, y, i]; + + x += set.tileWidth + set.tileSpacing; + + count++; + + if (count === set.total) + { + break; + } + + countX++; + + if (countX === set.columns) + { + x = set.tileMargin; + y += set.tileHeight + set.tileSpacing; + + countX = 0; + countY++; + + if (countY === set.rows) + { + break; + } + } + } + + } + + // assign tile properties + + var layer; + var tile; + var sid; + var set; + + // go through each of the map data layers + for (var i = 0; i < map.layers.length; i++) + { + layer = map.layers[i]; + collision[layer.name] = []; + set = null; + + // rows of tiles + for (var j = 0; j < layer.data.length; j++) + { + row = layer.data[j]; + + // individual tiles + for (var k = 0; k < row.length; k++) + { + tile = row[k]; + + if (tile === null || tile.index < 0) + { + continue; + } + + // find the relevant tileset + + sid = map.tiles[tile.index][2]; + set = map.tilesets[sid]; + + + // if that tile type has any properties, add them to the tile object + + if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) + { + tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties); + } + + var objectGroup = tilesetGroupObjects[tile.index]; + if (objectGroup) + { + // build collisions and objects for objectgroups found in the tileset's tiles + this.parseObjectGroup( + objectGroup, + map.objects, + map.collision, + tile.layer.name, + { + x: tile.worldX + objectGroup.x, + y: tile.worldY + objectGroup.y + }); + } + + } + } + } + + return map; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile set is a combination of an image containing the tiles and collision data per tile. +* +* Tilesets are normally created automatically when Tiled data is loaded. +* +* @class Phaser.Tileset +* @constructor +* @param {string} name - The name of the tileset in the map data. +* @param {integer} firstgid - The first tile index this tileset contains. +* @param {integer} [width=32] - Width of each tile (in pixels). +* @param {integer} [height=32] - Height of each tile (in pixels). +* @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels). +* @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels). +* @param {object} [properties={}] - Custom Tileset properties. +*/ +Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Tileset. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first tile index this Tileset contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of each tile (in pixels). + * @property {integer} tileWidth + * @readonly + */ + this.tileWidth = width | 0; + + /** + * The height of each tile (in pixels). + * @property {integer} tileHeight + * @readonly + */ + this.tileHeight = height | 0; + + /** + * The margin around the tiles in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileMarge + * @readonly + */ + // Modified internally + this.tileMargin = margin | 0; + + /** + * The spacing between each tile in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileSpacing + * @readonly + */ + this.tileSpacing = spacing | 0; + + /** + * Tileset-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set. + * @property {?object} image + * @readonly + */ + // Modified internally + this.image = null; + + /** + * The number of tile rows in the the tileset. + * @property {integer} + * @readonly + */ + // Modified internally + this.rows = 0; + + /** + * The number of tile columns in the tileset. + * @property {integer} columns + * @readonly + */ + // Modified internally + this.columns = 0; + + /** + * The total number of tiles in the tileset. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; + + /** + * The look-up table to specific tile image offsets. + * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1. + * @property {integer[]} drawCoords + * @private + */ + this.drawCoords = []; + +}; + +Phaser.Tileset.prototype = { + + /** + * Draws a tile from this Tileset at the given coordinates on the context. + * + * @method Phaser.Tileset#draw + * @public + * @param {CanvasRenderingContext2D} context - The context to draw the tile onto. + * @param {number} x - The x coordinate to draw to. + * @param {number} y - The y coordinate to draw to. + * @param {integer} index - The index of the tile within the set to draw. + */ + draw: function (context, x, y, index) { + + // Correct the tile index for the set and bias for interlacing + var coordIndex = (index - this.firstgid) << 1; + + if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length) + { + context.drawImage( + this.image, + this.drawCoords[coordIndex], + this.drawCoords[coordIndex + 1], + this.tileWidth, + this.tileHeight, + x, + y, + this.tileWidth, + this.tileHeight + ); + } + + }, + + /** + * Returns true if and only if this tileset contains the given tile index. + * + * @method Phaser.Tileset#containsTileIndex + * @public + * @param {number} tileIndex + * @return {boolean} True if this tileset contains the given index. + */ + containsTileIndex: function (tileIndex) { + + return ( + tileIndex >= this.firstgid && + tileIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Set the image associated with this Tileset and update the tile data. + * + * @method Phaser.Tileset#setImage + * @public + * @param {Image} image - The image that contains the tiles. + */ + setImage: function (image) { + + this.image = image; + this.updateTileData(image.width, image.height); + + }, + + /** + * Sets tile spacing and margins. + * + * @method Phaser.Tileset#setSpacing + * @public + * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels). + */ + setSpacing: function (margin, spacing) { + + this.tileMargin = margin | 0; + this.tileSpacing = spacing | 0; + + if (this.image) + { + this.updateTileData(this.image.width, this.image.height); + } + + }, + + /** + * Updates tile coordinates and tileset data. + * + * @method Phaser.Tileset#updateTileData + * @private + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + */ + updateTileData: function (imageWidth, imageHeight) { + + // May be fractional values + var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); + var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); + + if (rowCount % 1 !== 0 || colCount % 1 !== 0) + { + console.warn( + "Phaser.Tileset - '%s' image tile area (%s x %s) is not a whole multiple of tile size (%s x %s + %s + %s)", + this.name, imageWidth, imageHeight, this.tileWidth, this.tileHeight, this.tileMargin, this.tileSpacing + ); + } + + // In Tiled a tileset image that is not an even multiple of the tile dimensions + // is truncated - hence the floor when calculating the rows/columns. + rowCount = Math.floor(rowCount); + colCount = Math.floor(colCount); + + if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount)) + { + console.warn( + "Phaser.Tileset - Tile layout from image '%s' (%s rows by %s columns) differs from tileset '%s' (%s rows by %s columns)", + this.image.name, colCount, rowCount, this.name, this.columns, this.rows + ); + } + + this.rows = rowCount; + this.columns = colCount; + this.total = rowCount * colCount; + + this.drawCoords.length = 0; + + var tx = this.tileMargin; + var ty = this.tileMargin; + + for (var y = 0; y < this.rows; y++) + { + for (var x = 0; x < this.columns; x++) + { + this.drawCoords.push(tx); + this.drawCoords.push(ty); + tx += this.tileWidth + this.tileSpacing; + } + + tx = this.tileMargin; + ty += this.tileHeight + this.tileSpacing; + } + + } + +}; + +Phaser.Tileset.prototype.constructor = Phaser.Tileset; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. +* +* @class Phaser.Particle +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Particle = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + /** + * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData. + * @protected + */ + this.autoScale = false; + + /** + * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.scaleData = null; + + /** + * @property {number} _s - Internal cache var for tracking auto scale. + * @private + */ + this._s = 0; + + /** + * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. + * @protected + */ + this.autoAlpha = false; + + /** + * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.alphaData = null; + + /** + * @property {number} _a - Internal cache var for tracking auto alpha. + * @private + */ + this._a = 0; + +}; + +Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Particle.prototype.constructor = Phaser.Particle; + +/** +* Updates the Particle scale or alpha if autoScale and autoAlpha are set. +* +* @method Phaser.Particle#update +* @memberof 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; + } + } + +}; + +/** +* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. +* +* @method Phaser.Particle#onEmit +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.onEmit = function() { +}; + +/** +* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. +* +* @method Phaser.Particle#setAlphaData +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.setAlphaData = function(data) { + + this.alphaData = data; + this._a = data.length - 1; + this.alpha = this.alphaData[this._a].v; + this.autoAlpha = true; + +}; + +/** +* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. +* +* @method Phaser.Particle#setScaleData +* @memberof Phaser.Particle +*/ +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; + +}; + +/** +* Resets the Particle. This places the Particle at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. +* If the Particle has a physics body that too is reset. +* +* @method Phaser.Particle#reset +* @memberof Phaser.Particle +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {number} [health=1] - The health to give the Particle. +* @return {Phaser.Particle} This instance. +*/ +Phaser.Particle.prototype.reset = function(x, y, health) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y, health); + + this.alpha = 1; + this.scale.set(1); + + this.autoScale = false; + this.autoAlpha = false; + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Particles tracks any Emitters attached to it. +* +* @class Phaser.Particles +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Particles = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} emitters - Internal emitters store. + */ + this.emitters = {}; + + /** + * @property {number} ID - + * @default + */ + this.ID = 0; + +}; + +Phaser.Particles.prototype = { + + /** + * Adds a new Particle Emitter to the Particle Manager. + * @method Phaser.Particles#add + * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. + * @return {Phaser.Emitter} The emitter that was added. + */ + add: function (emitter) { + this.emitters[emitter.id] = emitter; + return emitter; + }, + + /** + * Removes an existing Particle Emitter from the Particle Manager. + * @method Phaser.Particles#remove + * @param {Phaser.Emitter} emitter - The emitter to remove. + */ + remove: function (emitter) { + delete this.emitters[emitter.id]; + } + +}; + +Phaser.Particles.prototype.constructor = Phaser.Particles; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Arcade Particles is a Particle System integrated with Arcade Physics. +* +* @class Phaser.Particles.Arcade +*/ +Phaser.Particles.Arcade = {}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Emitter is a lightweight particle emitter that uses Arcade Physics. +* It can be used for one-time explosions or for continuous effects like rain and fire. +* All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. +* +* @class Phaser.Particles.Arcade.Emitter +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. +* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. +* @param {number} [maxParticles=50] - The total number of particles in this emitter. +*/ +Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { + + /** + * @property {number} maxParticles - The total number of particles in this emitter. + * @default + */ + this.maxParticles = maxParticles || 50; + + Phaser.Group.call(this, game); + + /** + * @property {number} _id - Internal ID for this emitter -- only used by the Particle System in most cases + * @private + */ + this._id = this.game.particles.ID++; + + /** + * @property {string} name - A handy string name for this emitter. Can be set to anything. + */ + this.name = 'emitter' + this.id; + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.EMITTER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * @property {Phaser.Rectangle} area - The {@link #setSize size} of the emitter's emit area. The **actual** emit area is a rectangle of this size centered on (emitX, emitY): `{x: this.left, y: this.top, width: this.area.width, height: this.area.height}`. Particles are generated at a random position within this area. + * @default + */ + this.area = new Phaser.Rectangle(x, y, 1, 1); + + /** + * @property {?number} minAngle - The minimum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #maxAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.minAngle = null; + + /** + * @property {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #minAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.maxAngle = null; + + /** + * @property {number} minSpeed - The minimum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.minSpeed = 0; + + /** + * @property {number} maxSpeed - The maximum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.maxSpeed = 100; + + /** + * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle. + * @default + */ + this.minParticleSpeed = new Phaser.Point(-100, -100); + + /** + * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle. + * @default + */ + this.maxParticleSpeed = new Phaser.Point(100, 100); + + /** + * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. + * @default + */ + this.minParticleScale = 1; + + /** + * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. + * @default + */ + this.maxParticleScale = 1; + + /** + * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0. + */ + this.scaleData = null; + + /** + * @property {number} minRotation - The minimum possible angular velocity of a particle. + * @default + */ + this.minRotation = -360; + + /** + * @property {number} maxRotation - The maximum possible angular velocity of a particle. + * @default + */ + this.maxRotation = 360; + + /** + * @property {number} minParticleAlpha - The minimum possible alpha value of a particle. + * @default + */ + this.minParticleAlpha = 1; + + /** + * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle. + * @default + */ + this.maxParticleAlpha = 1; + + /** + * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0. + */ + this.alphaData = null; + + /** + * @property {function} particleClass - For emitting your own particle class types. They must extend Phaser.Particle. + * @default + */ + this.particleClass = Phaser.Particle; + + /** + * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter. + */ + this.particleDrag = new Phaser.Point(); + + /** + * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false). + * @default + */ + this.frequency = 100; + + /** + * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. + * @default + */ + this.lifespan = 2000; + + /** + * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. + */ + this.bounce = new Phaser.Point(); + + /** + * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. + * @default + */ + this.on = false; + + /** + * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) + * @default + */ + this.particleAnchor = new Phaser.Point(0.5, 0.5); + + /** + * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) + * @default + */ + this.blendMode = Phaser.blendModes.NORMAL; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitX + */ + this.emitX = x; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitY + */ + this.emitY = y; + + /** + * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. + */ + this.autoScale = false; + + /** + * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. + */ + this.autoAlpha = false; + + /** + * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. + * @default + */ + this.particleBringToTop = false; + + /** + * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. + * @default + */ + this.particleSendToBack = false; + + /** + * @property {object} counts - Records emitter activity. + * @property {number} counts.emitted - How many particles were emitted during the last update. + * @property {number} counts.failed - How many particles could not be emitted during the last update (because no particles were available). + * @property {number} counts.totalEmitted - How many particles have been emitted. + * @property {number} counts.totalFailed - How many particles could not be emitted when they were due (because no particles were available). + */ + this.counts = { + emitted: 0, + failed: 0, + totalEmitted: 0, + totalFailed: 0 + }; + + /** + * @property {Phaser.Point} _gravity - Internal gravity value. + * @private + */ + this._gravity = new Phaser.Point(0, 100); + + /** + * @property {Phaser.Point} _minParticleScale - Internal particle scale var. + * @private + */ + this._minParticleScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} _maxParticleScale - Internal particle scale var. + * @private + */ + this._maxParticleScale = new Phaser.Point(1, 1); + + /** + * @property {number} _total - Internal helper for deciding how many particles to launch (via {@link #start}). + * @private + */ + this._total = 0; + + /** + * @property {number} _timer - Internal helper for deciding when to launch particles or kill them. + * @private + */ + this._timer = 0; + + /** + * @property {number} _counter - Internal counter for figuring out how many particles to launch. + * @private + */ + this._counter = 0; + + /** + * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update. + * @private + */ + this._flowQuantity = 0; + + /** + * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total (via {@link #flow}). + * @private + */ + this._flowTotal = 0; + + /** + * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time). + * @private + */ + this._explode = true; + + /** + * @property {any} _frames - Internal helper for the particle frame. + * @private + */ + this._frames = null; + +}; + +Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); +Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter; + +/** +* Called automatically by the game loop, decides when to launch particles and when to "die". +* +* @method Phaser.Particles.Arcade.Emitter#update +*/ +Phaser.Particles.Arcade.Emitter.prototype.update = function () { + + this.counts.emitted = 0; + this.counts.failed = 0; + + if (this.on && this.game.time.time >= this._timer) + { + this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion; + + if (this._flowTotal !== 0) + { + if (this._flowQuantity > 0) + { + for (var i = 0; i < this._flowQuantity; i++) + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + break; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._total > 0 && this._counter >= this._total) + { + this.on = false; + } + } + } + + } + + var i = this.children.length; + + while (i--) + { + if (this.children[i].exists) + { + this.children[i].update(); + } + } + +}; + +/** +* This function generates a new set of particles for use by this emitter. +* The particles are stored internally waiting to be emitted via Emitter.start. +* +* @method Phaser.Particles.Arcade.Emitter#makeParticles +* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. +* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random. +* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. +* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. +* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. +* @param {object} [particleArguments=null] - Custom arguments to pass to your particle class +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds, particleArguments) { + + if (frames === undefined) { frames = 0; } + if (quantity === undefined) { quantity = this.maxParticles; } + if (collide === undefined) { collide = false; } + if (collideWorldBounds === undefined) { collideWorldBounds = false; } + if (particleArguments === undefined) { particleArguments = null; } + + var particle; + var i = 0; + var rndKey = keys; + var rndFrame = frames; + this._frames = frames; + + if (quantity > this.maxParticles) + { + this.maxParticles = quantity; + } + + while (i < quantity) + { + if (Array.isArray(keys)) + { + rndKey = this.game.rnd.pick(keys); + } + + if (Array.isArray(frames)) + { + rndFrame = this.game.rnd.pick(frames); + } + + particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame, particleArguments); + + this.game.physics.arcade.enable(particle, false); + + particle.body.checkCollision.none = !collide; + particle.body.collideWorldBounds = collideWorldBounds; + particle.body.skipQuadTree = true; + + particle.exists = false; + particle.visible = false; + particle.anchor.copyFrom(this.particleAnchor); + + this.add(particle); + + i++; + } + + return this; + +}; + +/** +* Call this function to turn off all the particles and the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#kill +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.kill = function () { + + this.on = false; + this.alive = false; + this.exists = false; + + return this; + +}; + +/** +* Handy for bringing game objects "back to life". Just sets alive and exists back to true. +* +* @method Phaser.Particles.Arcade.Emitter#revive +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.revive = function () { + + this.alive = true; + this.exists = true; + + return this; + +}; + +/** +* Call this function to emit the given quantity of particles at all once (an explosion) +* +* @method Phaser.Particles.Arcade.Emitter#explode +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [quantity=this.maxParticles] - How many particles to launch. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) { + + if (quantity === undefined) { + quantity = this.maxParticles; + } + + this._flowTotal = 0; + + this.start(true, lifespan, 0, quantity, false); + + return this; + +}; + +/** +* Call this function to start emitting a flow of particles. +* `quantity` particles are released every interval of `frequency` ms until `total` particles have been released (or forever). +* If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 × 5 = 20 total) and then turn {@link #on off}. +* If you set the total to be -1 then no quantity cap is used and it will keep emitting (as long as there are inactive particles available). +* +* {@link #output}, {@link #lifespanOutput}, and {@link #remainder} describe the particle flow rate. +* During a stable flow, the number of active particles approaches {@link #lifespanOutput} and the number of inactive particles approaches {@link #remainder}. +* If {@link #remainder} is less than 0, there will likely be no particles available for a portion of the flow (see {@link #count}). +* +* @method Phaser.Particles.Arcade.Emitter#flow +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of particles, given in ms. Values between 0 and 16.66 will behave the same (60 releases per second). +* @param {number} [quantity=1] - How many particles to launch at each interval. Not larger than {@link #maxParticles}. +* @param {number} [total=-1] - Turn {@link #on off} after launching this many particles in total. If -1 it will carry on indefinitely. +* @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) { + + if (frequency === undefined || frequency === null) { frequency = 250; } + if (quantity === undefined || quantity === 0) { quantity = 1; } + if (total === undefined) { total = -1; } + if (immediate === undefined) { immediate = true; } + + if (quantity > this.maxParticles) + { + quantity = this.maxParticles; + } + + this._counter = 0; + this._flowQuantity = quantity; + this._flowTotal = total; + + if (immediate) + { + this.start(true, lifespan, frequency, quantity); + + this._counter += quantity; + this.on = true; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + else + { + this.start(false, lifespan, frequency, quantity); + } + + return this; + +}; + +/** +* Start emitting particles. +* +* {@link #explode} and {@link #flow} are simpler methods. +* +* There are two patterns, based on the `explode` argument: +* +* ##### explode=true +* +* start(true, lifespan=0, null, total) +* +* When `explode` is true or `forceQuantity` is true, `start` emits `total` particles immediately. You should pass a nonzero `total`. +* +* ##### explode=false +* +* start(false, lifespan=0, frequency=250, total=0) +* +* When `explode` is false and `forceQuantity` is false, `start` emits 1 particle every interval of `frequency` ms. If `total` is not zero, the emitter turns itself off after `total` particles have been released. If `total` is zero, the emitter keeps emitting particles as long as they are available. To emit more than 1 particle per flow interval, use {@link #flow} instead. +* +* `forceQuantity` seems equivalent to `explode` and can probably be avoided. +* +* @method Phaser.Particles.Arcade.Emitter#start +* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false). +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of 1 particle, when `explode` is false. Value given in ms. Ignored if `explode` is set to true. +* @param {number} [total=0] - Turn {@link #on off} after launching this many particles in total. +* @param {number} [forceQuantity=false] - Equivalent to `explodes`. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, total, forceQuantity) { + + if (explode === undefined) { explode = true; } + if (lifespan === undefined) { lifespan = 0; } + if (frequency === undefined || frequency === null) { frequency = 250; } + if (total === undefined) { total = 0; } + if (forceQuantity === undefined) { forceQuantity = false; } + + if (total > this.maxParticles) + { + total = this.maxParticles; + } + + this.revive(); + + this.visible = true; + + this.lifespan = lifespan; + this.frequency = frequency; + + if (explode || forceQuantity) + { + for (var i = 0; i < total; i++) + { + this.emitParticle(); + } + } + else + { + this.on = true; + this._total = total; + this._counter = 0; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + + return this; + +}; + +/** +* This function is used internally to emit the next particle in the queue. +* +* However it can also be called externally to emit a particle. +* +* When called externally you can use the arguments to override any defaults the Emitter has set. +* +* The newly emitted particle is available in {@link Phaser.Particles.Arcade.Emitter#cursor}. +* +* @method Phaser.Particles.Arcade.Emitter#emitParticle +* @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. +* @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {boolean} True if a particle was emitted, otherwise false. +*/ +Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + var particle = this.getNextParticle(); + + if (particle === null) + { + this.counts.failed++; + this.counts.totalFailed++; + + return false; + } + + this.counts.emitted++; + this.counts.totalEmitted++; + + var rnd = this.game.rnd; + + if (key !== undefined && frame !== undefined) + { + particle.loadTexture(key, frame); + } + else if (key !== undefined) + { + particle.loadTexture(key); + particle.frame = Array.isArray(this._frames) ? rnd.pick(this._frames) : this._frames; + } + + var emitX = this.emitX; + var emitY = this.emitY; + + if (x !== null) + { + emitX = x; + } + else if (this.width > 1) + { + emitX = rnd.between(this.left, this.right); + } + + if (y !== null) + { + emitY = y; + } + else if (this.height > 1) + { + emitY = rnd.between(this.top, this.bottom); + } + + this.resetParticle(particle, emitX, emitY); + + return true; + +}; + + +/** +* Helper for {@link #emitParticle}. Gets the next available particle. +* +* @private +* @return {?Phaser.Particle} The first particle with exists=false, or null +*/ +Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () { + + var i = this.length; + + while (i--) + { + var next = this.next(); + + if (!next.exists) + { + return next; + } + } + + return null; + +}; + +/** + * Helper for {@link #emitParticle}. Sets particle properties and calls {@link Particle#onEmit}. + * + * @private + * @param {Phaser.Particle} particle + * @param {number} x + * @param {number} y + */ +Phaser.Particles.Arcade.Emitter.prototype.resetParticle = function (particle, x, y) { + + var rnd = this.game.rnd; + + particle.reset(x, y); + + 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(rnd.realInRange(this.minParticleScale, this.maxParticleScale)); + } + else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y)) + { + particle.scale.set(rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y)); + } + else + { + particle.scale.set(this._minParticleScale.x, this._minParticleScale.y); + } + + if (this.autoAlpha) + { + particle.setAlphaData(this.alphaData); + } + else + { + particle.alpha = rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha); + } + + particle.blendMode = this.blendMode; + + var body = particle.body; + + body.updateBounds(); + + body.bounce.copyFrom(this.bounce); + body.drag.copyFrom(this.particleDrag); + + if (this.minAngle != null && this.maxAngle != null) + { + this.game.physics.arcade.velocityFromAngle( + (this.minAngle === this.maxAngle) ? this.minAngle : rnd.between(this.minAngle, this.maxAngle), + (this.minSpeed === this.maxSpeed) ? this.minSpeed : rnd.between(this.minSpeed, this.maxSpeed), + body.velocity + ); + } + else + { + body.velocity.x = rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x); + body.velocity.y = rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y); + } + + body.angularVelocity = rnd.between(this.minRotation, this.maxRotation); + body.gravity.copyFrom(this.gravity); + body.angularDrag = this.angularDrag; + + particle.onEmit(); + +}; + +/** +* Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. +* +* @method Phaser.Particles.Arcade.Emitter#destroy +*/ +Phaser.Particles.Arcade.Emitter.prototype.destroy = function () { + + this.game.particles.remove(this); + + Phaser.Group.prototype.destroy.call(this, true, false); + +}; + +/** +* A more compact way of setting the width and height of the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#setSize +* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). +* @param {number} height - The desired height of the emitter. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { + + this.area.width = width; + this.area.height = height; + + return this; + +}; + +/** +* A more compact way of setting the X velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setXSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.x = min; + this.maxParticleSpeed.x = max; + + return this; + +}; + +/** +* A more compact way of setting the Y velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setYSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.y = min; + this.maxParticleSpeed.y = max; + + return this; + +}; + +/** +* A more compact way of setting the angular velocity constraints of the particles. +* +* @method Phaser.Particles.Arcade.Emitter#setRotation +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minRotation = min; + this.maxRotation = max; + + return this; + +}; + +/** +* A more compact way of setting the alpha constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. +* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setAlpha +* @param {number} [min=1] - The minimum value for this range. +* @param {number} [max=1] - The maximum value for this range. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) { + + if (min === undefined) { min = 1; } + if (max === undefined) { max = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.alphaData.reverse(); + this.autoAlpha = true; + } + + return this; + +}; + +/** +* A more compact way of setting the scale constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. +* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setScale +* @param {number} [minX=1] - The minimum value of Particle.scale.x. +* @param {number} [maxX=1] - The maximum value of Particle.scale.x. +* @param {number} [minY=1] - The minimum value of Particle.scale.y. +* @param {number} [maxY=1] - The maximum value of Particle.scale.y. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) { + + if (minX === undefined) { minX = 1; } + if (maxX === undefined) { maxX = 1; } + if (minY === undefined) { minY = 1; } + if (maxY === undefined) { maxY = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (yoyo === undefined) { yoyo = false; } + + // Reset these + 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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.scaleData.reverse(); + this.autoScale = true; + } + + return this; + +}; + +/** + * Sets a radial pattern for emitting particles. + * + * This is a shorthand for setting {@link #minAngle}, {@link #maxAngle}, {@link #minSpeed}, and {@link #maxSpeed}. + * + * To remove the radial pattern, use `setAngle(null, null)`. + * + * @method Phaser.Particles.Arcade.Emitter#setAngle + * @param {?number} minAngle - The minimum angle of initial particle velocities, in degrees. + * @param {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. + * @param {number} [minSpeed] - The minimum initial particle speed. + * @param {number} [maxSpeed] - The maximum initial particle speed. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ +Phaser.Particles.Arcade.Emitter.prototype.setAngle = function (minAngle, maxAngle, minSpeed, maxSpeed) { + + this.minAngle = minAngle; + this.maxAngle = maxAngle; + + if (minSpeed != null) { this.minSpeed = minSpeed; } + if (maxSpeed != null) { this.maxSpeed = maxSpeed; } + + return this; + +}; + +/** +* Change the emitter's center to match the center of any object with a `center` property, such as an Arcade Body. +* If the object doesn't have a `center` property it will be set to the object's anchor-adjusted world position (`object.world`). +* +* @method Phaser.Particles.Arcade.Emitter#at +* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +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); + } + + return this; + +}; + +/** + * @name Phaser.Particles.Arcade.Emitter#gravity + * @property {Phaser.Point} gravity - Sets the `body.gravity` of each particle sprite to this on launch. + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "gravity", { + + get: function () { + return this._gravity; + }, + + set: function (value) { + if (typeof value === "number") + { + this._gravity.y = value; + } + else + { + this._gravity = value; + } + } + +}); + + +/** +* @name Phaser.Particles.Arcade.Emitter#id +* @property {number} id - Gets the internal ID that represents this emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "id", { + get: function () { + return this._id; + } +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#width +* @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", { + + get: function () { + return this.area.width; + }, + + set: function (value) { + this.area.width = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#height +* @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", { + + get: function () { + return this.area.height; + }, + + set: function (value) { + this.area.height = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#x +* @property {number} x - Gets or sets the x position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", { + + get: function () { + return this.emitX; + }, + + set: function (value) { + this.emitX = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#y +* @property {number} y - Gets or sets the y position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", { + + get: function () { + return this.emitY; + }, + + set: function (value) { + this.emitY = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#left +* @property {number} left - Gets the left position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", { + + get: function () { + return Math.floor(this.x - (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#right +* @property {number} right - Gets the right position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", { + + get: function () { + return Math.floor(this.x + (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#top +* @property {number} top - Gets the top position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", { + + get: function () { + return Math.floor(this.y - (this.area.height / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#bottom +* @property {number} bottom - Gets the bottom position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", { + + get: function () { + return Math.floor(this.y + (this.area.height / 2)); + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#output + * @property {number} output - The number of particles released per second, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "output", { + + get: function () { + return 1000 * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#lifespanOutput + * @property {number} lifespanOutput - The number of particles released during one particle's {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "lifespanOutput", { + + get: function () { + return (this.lifespan === 0 ? Infinity : this.lifespan) * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#remainder + * @property {number} remainder - The expected number of unreleased particles after a flow interval of {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "remainder", { + + get: function () { + return this.maxParticles - this.lifespanOutput; + } + +}); + +/** +* The last particle released, if any. +* +* You should treat this as read-only (and also avoid {@link #next} and {@link #previous}) once the emitter is started. Phaser uses it internally to track particles. +* +* @name Phaser.Particles.Arcade.Emitter#cursor +* @property {?DisplayObject} cursor +* @readonly +*/ +// Inherited from Phaser.Group#cursor + +/** +* Advances the cursor to the next particle. +* +* @method Phaser.Particles.Arcade.Emitter#next +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#next + +/** +* Moves the group cursor to the previous particle. +* +* @method Phaser.Particles.Arcade.Emitter#previous +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#previous + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Weapon Plugin provides the ability to easily create a bullet pool and manager. +* +* Weapons fire {@link Phaser.Bullet} objects, which are essentially Sprites with a few extra properties. +* The Bullets are enabled for {@link Phaser.Physics.Arcade Arcade Physics}. They do not currently work with P2 Physics. +* +* The Bullets are created inside of {@link #bullets weapon.bullets}, which is a {@link Phaser.Group} instance. Anything you +* can usually do with a Group, such as move it around the display list, iterate it, etc can be done +* to the bullets Group too. +* +* Bullets can have textures and even animations. You can control the speed at which they are fired, +* the firing rate, the firing angle, and even set things like gravity for them. +* +* A small example, using {@link Phaser.GameObjectFactory#weapon add.weapon}, assumed to be running from within a {@link Phaser.State#create} method: +* +* ```javascript +* var weapon = this.add.weapon(10, 'bullet'); +* weapon.fireFrom.set(300, 300); +* this.input.onDown.add(weapon.fire, this); +* ``` +* +* If you want to (re)create the bullet pool separately, you can use: +* +* ```javascript +* var weapon = this.game.plugins.add(Phaser.Weapon); +* // … +* weapon.createBullets(10, 'bullet'); +* ``` +* +* @class Phaser.Weapon +* @constructor +* @param {Phaser.Game} game - A reference to the current Phaser.Game instance. +* @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin. +*/ +Phaser.Weapon = function (game, parent) { + + Phaser.Plugin.call(this, game, parent); + + /** + * This is the Phaser.Group that contains all of the bullets managed by this plugin. + * @type {Phaser.Group} + */ + this.bullets = null; + + /** + * Should the bullet pool run out of bullets (i.e. they are all in flight) then this + * boolean controls if the Group will create a brand new bullet object or not. + * @type {boolean} + * @default + */ + this.autoExpandBulletsGroup = false; + + /** + * Will this weapon auto fire? If set to true then a new bullet will be fired + * based on the {@link #fireRate} value. + * @type {boolean} + * @default + */ + this.autofire = false; + + /** + * The total number of bullets this Weapon has fired so far. + * You can limit the number of shots allowed (via {@link #fireLimit}), and reset + * this total via {@link #resetShots}. + * @type {number} + * @default + */ + this.shots = 0; + + /** + * The maximum number of shots that this Weapon is allowed to fire before it stops. + * When the limit is his the {@link #onFireLimit} Signal is dispatched. + * You can reset the shot counter via {@link #resetShots}. + * @type {number} + * @default + */ + this.fireLimit = 0; + + /** + * The minimum interval between shots, in milliseconds. + * @type {number} + * @default + */ + this.fireRate = 100; + + /** + * This is a modifier that is added to the {@link #fireRate} each update to add variety + * to the firing rate of the Weapon. The value is given in milliseconds. + * If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual + * firing rate of the Weapon will be between 150 and 250. + * @type {number} + * @default + */ + this.fireRateVariance = 0; + + /** + * This is a Rectangle from within which the bullets are fired. By default it's a 1x1 + * rectangle, the equivalent of a Point. But you can change the width and height, and if + * larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from. + * @type {Phaser.Rectangle} + */ + this.fireFrom = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE_UP + * or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right. + * @type {integer} + * @default + */ + this.fireAngle = Phaser.ANGLE_UP; + + /** + * When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set. + * @type {boolean} + * @default + */ + this.bulletInheritSpriteSpeed = false; + + /** + * The string based name of the animation that the Bullet will be given on launch. + * This is set via {@link #addBulletAnimation}. + * @type {string} + * @default + */ + this.bulletAnimation = ''; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to pick a random frame from the set. + * @type {boolean} + * @default + */ + this.bulletFrameRandom = false; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to use the next frame in the set. The frame index is then + * advanced one frame until it reaches the end of the set, then it starts from the start + * again. Cycling frames like this allows you to create varied bullet effects via + * sprite sheets. + * @type {boolean} + * @default + */ + this.bulletFrameCycle = false; + + /** + * Should the Bullets wrap around the world bounds? This automatically calls + * `World.wrap` on the Bullet each frame. See the docs for that method for details. + * @type {boolean} + * @default + */ + this.bulletWorldWrap = false; + + /** + * If `bulletWorldWrap` is true then you can provide an optional padding value with this + * property. It's added to the calculations determining when the Bullet should wrap around + * the world or not. The value is given in pixels. + * @type {integer} + * @default + */ + this.bulletWorldWrapPadding = 0; + + /** + * An optional angle offset applied to the Bullets when they are launched. + * This is useful if for example your bullet sprites have been drawn facing up, instead of + * to the right, and you want to fire them at an angle. In which case you can set the + * angle offset to be 90 and they'll be properly rotated when fired. + * @type {number} + * @default + */ + this.bulletAngleOffset = 0; + + /** + * This is a variance added to the angle of Bullets when they are fired. + * If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual + * angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a + * great 'spread' effect to a Weapon. + * @type {number} + * @default + */ + this.bulletAngleVariance = 0; + + /** + * The initial velocity of fired bullets, in pixels per second. + * @type {number} + * @default + */ + this.bulletSpeed = 200; + + /** + * This is a variance added to the speed of Bullets when they are fired. + * If bullets have a {@link #bulletSpeed} value of 200, and a `bulletSpeedVariance` of 50 + * then the actual speed of the Bullets will be between 150 and 250 pixels per second. + * @type {number} + * @default + */ + this.bulletSpeedVariance = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount + * of lifespan the Bullets have set on launch. The value is given in milliseconds. + * When a Bullet hits its lifespan limit it will be automatically killed. + * @type {number} + * @default + */ + this.bulletLifespan = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_DISTANCE` this controls the distance + * the Bullet can travel before it is automatically killed. The distance is given in pixels. + * @type {number} + * @default + */ + this.bulletKillDistance = 0; + + /** + * This is the amount of {@link Phaser.Physics.Arcade.Body#gravity} added to the Bullets physics body when fired. + * Gravity is expressed in pixels / second / second. + * @type {Phaser.Point} + */ + this.bulletGravity = new Phaser.Point(0, 0); + + /** + * Bullets can optionally adjust their rotation in-flight to match their velocity. + * This can create the effect of a bullet 'pointing' to the path it is following, for example + * an arrow being fired from a bow, and works especially well when added to {@link #bulletGravity}. + * @type {boolean} + * @default + */ + this.bulletRotateToVelocity = false; + + /** + * The Texture Key that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string} + * @default + */ + this.bulletKey = ''; + + /** + * The Texture Frame that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string|integer} + * @default + */ + this.bulletFrame = ''; + + /** + * Private var that holds the public `bulletClass` property. + * @type {function} + * @private + */ + this._bulletClass = Phaser.Bullet; + + /** + * Private var that holds the public `bulletCollideWorldBounds` property. + * @type {boolean} + * @private + */ + this._bulletCollideWorldBounds = false; + + /** + * Private var that holds the public `bulletKillType` property. + * @type {integer} + * @private + */ + this._bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; + + /** + * Holds internal data about custom bullet body sizes. + * + * @type {Object} + * @private + */ + this._data = { + customBody: false, + width: 0, + height: 0, + offsetX: 0, + offsetY: 0 + }; + + /** + * This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not. + * It's used in combination with {@link #bulletKillType} when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS` + * or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored. + * If you are tracking a Sprite or Point then the bounds are centered on that object every frame. + * + * @type {Phaser.Rectangle} + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The Rectangle used to calculate the bullet bounds from. + * + * @type {Phaser.Rectangle} + * @private + */ + this.bulletBounds = game.world.bounds; + + /** + * This array stores the frames added via @link #setBulletFrames. + * + * @type {Array} + * @protected + */ + this.bulletFrames = []; + + /** + * The index of the frame within {@link #bulletFrames} that is currently being used. + * This value is only used if {@link #bulletFrameCycle} is set to `true`. + * @type {number} + * @private + */ + this.bulletFrameIndex = 0; + + /** + * An internal object that stores the animation data added via {@link #addBulletAnimation}. + * @type {Object} + * @private + */ + this.anims = {}; + + /** + * The onFire Signal is dispatched each time {@link #fire} is called, and a Bullet is + * _successfully_ launched. The callback is set two arguments: a reference to the bullet sprite itself, + * and a reference to the Weapon that fired the bullet. + * + * @type {Phaser.Signal} + */ + this.onFire = new Phaser.Signal(); + + /** + * The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result + * of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance. + * The callback is sent one argument: A reference to the bullet sprite itself. + * + * @type {Phaser.Signal} + */ + this.onKill = new Phaser.Signal(); + + /** + * The onFireLimit Signal is dispatched if {@link #fireLimit} is > 0, and a bullet launch takes the number + * of shots fired to equal the fire limit. + * The callback is sent two arguments: A reference to this Weapon, and the value of + * {@link #fireLimit}. + * + * @type {Phaser.Signal} + */ + this.onFireLimit = new Phaser.Signal(); + + /** + * The Sprite currently being tracked by the Weapon, if any. + * This is set via the {@link #trackSprite} method. + * + * @type {Phaser.Sprite|Object} + */ + this.trackedSprite = null; + + /** + * The Pointer currently being tracked by the Weapon, if any. + * This is set via the {@link #trackPointer} method. + * + * @type {Phaser.Pointer} + */ + this.trackedPointer = null; + + /** + * If you want this Weapon to be able to fire more than 1 bullet in a single + * update, then set this property to `true`. When `true` the Weapon plugin won't + * set the shot / firing timers until the `postRender` phase of the game loop. + * This means you can call `fire` (and similar methods) as often as you like in one + * single game update. + * + * @type {boolean} + * @default + */ + this.multiFire = false; + + /** + * Internal multiFire test flag. + * + * @type {boolean} + */ + this._hasFired = false; + + /** + * If the Weapon is tracking a Sprite, should it also track the Sprites rotation? + * This is useful for a game such as Asteroids, where you want the weapon to fire based + * on the sprites rotation. + * + * @type {boolean} + * @default + */ + this.trackRotation = false; + + /** + * The Track Offset is a Point object that allows you to specify a pixel offset that bullets use + * when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels + * in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have + * the bullet launched from the center of the Sprite. + * + * @type {Phaser.Point} + */ + this.trackOffset = new Phaser.Point(); + + /** + * Internal firing rate time tracking variable. + * + * @type {number} + * @private + */ + this._nextFire = 0; + + /** + * Internal firing rate time tracking variable used by multiFire. + * + * @type {number} + * @private + */ + this._tempNextFire = 0; + + /** + * Internal firing rotation tracking point. + * + * @type {Phaser.Point} + * @private + */ + this._rotatedPoint = new Phaser.Point(); + +}; + +Phaser.Weapon.prototype = Object.create(Phaser.Plugin.prototype); +Phaser.Weapon.prototype.constructor = Phaser.Weapon; + +/** +* A {@link #bulletKillType} constant that stops the bullets from ever being destroyed automatically. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_NEVER = 0; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when their {@link #bulletLifespan} expires. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_LIFESPAN = 1; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets after they +* exceed the {@link #bulletDistance} from their original firing position. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_DISTANCE = 2; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WEAPON_BOUNDS = 3; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.Camera#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_CAMERA_BOUNDS = 4; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.World#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WORLD_BOUNDS = 5; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_STATIC_BOUNDS = 6; + +/** +* This method performs two actions: First it will check to see if the {@link #bullets} Group exists or not, +* and if not it creates it, adding it the `group` given as the 4th argument. +* +* Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame +* provided (if any). +* +* If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets +* in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of +* the in-flight bullets have been killed, freeing them up for use by the Weapon again. +* +* If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will +* keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however, +* so be careful it doesn't grow too large. +* +* You can either set the texture key and frame here, or via the {@link #bulletKey} and {@link #bulletFrame} +* properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a +* single Weapon instance must share the same texture key however. +* +* @method Phaser.Weapon#createBullets +* @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. +* @param {string} [key] - The Game.cache key of the image that this Sprite will use. +* @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. +* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.createBullets = function (quantity, key, frame, group) { + + if (quantity === undefined) { quantity = 1; } + if (group === undefined) { group = this.game.world; } + + if (this.bullets && !this.bullets.game) + { + this.bullets = null; + } + + if (!this.bullets) + { + this.bullets = this.game.add.physicsGroup(Phaser.Physics.ARCADE, group); + this.bullets.classType = this._bulletClass; + } + + if (quantity !== 0) + { + if (quantity === -1) + { + this.autoExpandBulletsGroup = true; + quantity = 1; + } + + this.bullets.createMultiple(quantity, key, frame); + + this.bullets.setAll('data.bulletManager', this); + + this.bulletKey = key; + this.bulletFrame = frame; + } + + return this; + +}; + +/** +* Call a function on each in-flight bullet in this Weapon. +* +* See {@link Phaser.Group#forEachExists forEachExists} for more details. +* +* @method Phaser.Weapon#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.forEach = function (callback, callbackContext) { + + this.bullets.forEachExists(callback, callbackContext, arguments); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `false` on each bullet in this Weapon. +* This has the effect of stopping them in-flight should they be moving. +* It also stops them being able to be checked for collision. +* +* @method Phaser.Weapon#pauseAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.pauseAll = function () { + + this.bullets.setAll('body.enable', false); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `true` on each bullet in this Weapon. +* This has the effect of resuming their motion should they be in-flight. +* It also enables them for collision checks again. +* +* @method Phaser.Weapon#resumeAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resumeAll = function () { + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Calls {@link Phaser.Bullet#kill} on every in-flight bullet in this Weapon. +* Also re-enables their physics bodies, should they have been disabled via {@link #pauseAll}. +* +* @method Phaser.Weapon#killAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.killAll = function () { + + this.bullets.callAllExists('kill', true); + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Resets the {@link #shots} counter back to zero. This is used when you've set +* {@link #fireLimit} and have hit (or just wish to reset) your limit. +* +* @method Phaser.Weapon#resetShots +* @param {integer} [newLimit] - Optionally set a new {@link #fireLimit}. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resetShots = function (newLimit) { + + this.shots = 0; + + if (newLimit !== undefined) + { + this.fireLimit = newLimit; + } + + return this; + +}; + +/** +* Destroys this Weapon. It removes itself from the PluginManager, destroys +* the {@link #bullets} Group, and nulls internal references. +* +* @method Phaser.Weapon#destroy +*/ +Phaser.Weapon.prototype.destroy = function () { + + this.parent.remove(this, false); + + this.bullets.destroy(); + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#update +* @protected +*/ +Phaser.Weapon.prototype.update = function () { + + if (this._bulletKillType === Phaser.Weapon.KILL_WEAPON_BOUNDS) + { + if (this.trackedSprite) + { + this.trackedSprite.updateTransform(); + this.bounds.centerOn(this.trackedSprite.worldPosition.x, this.trackedSprite.worldPosition.y); + } + else if (this.trackedPointer) + { + this.bounds.centerOn(this.trackedPointer.worldX, this.trackedPointer.worldY); + } + } + + if (this.autofire) + { + this.fire(); + } + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#postRender +* @protected +*/ +Phaser.Weapon.prototype.postRender = function () { + + if (!this.multiFire || !this._hasFired) + { + return; + } + + this._hasFired = false; + + this._nextFire = this._tempNextFire; + +}; + +/** +* Sets this Weapon to track the given Sprite, or any Object with a public {@link Phaser.Component.Core#world world} Point object. +* When a Weapon tracks a Sprite it will automatically update its {@link #fireFrom} value to match the Sprite's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location. +* +* Calling `trackSprite` will reset {@link #trackedPointer} to null, should it have been set, as you can +* only track _either_ a Sprite, or a Pointer, at once, but not both. +* +* @method Phaser.Weapon#trackSprite +* @param {Phaser.Sprite|Object} sprite - The Sprite to track the position of. +* @param {integer} [offsetX=0] - The horizontal offset from the Sprites position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Sprites position to be applied to the Weapon. +* @param {boolean} [trackRotation=false] - Should the Weapon also track the Sprites rotation? +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackSprite = function (sprite, offsetX, offsetY, trackRotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (trackRotation === undefined) { trackRotation = false; } + + this.trackedPointer = null; + this.trackedSprite = sprite; + this.trackRotation = trackRotation; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Sets this Weapon to track the given Pointer. +* When a Weapon tracks a Pointer it will automatically update its {@link #fireFrom} value to match the Pointer's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location. +* +* Calling `trackPointer` will reset {@link #trackedSprite} to null, should it have been set, as you can +* only track _either_ a Pointer, or a Sprite, at once, but not both. +* +* @method Phaser.Weapon#trackPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to track the position of. Defaults to `Input.activePointer` if not specified. +* @param {integer} [offsetX=0] - The horizontal offset from the Pointers position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Pointers position to be applied to the Weapon. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackPointer = function (pointer, offsetX, offsetY) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this.trackedPointer = pointer; + this.trackedSprite = null; + this.trackRotation = false; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Attempts to fire multiple bullets from the positions defined in the given array. +* +* If you provide a `from` argument, or if there is a tracked Sprite or Pointer, then +* the positions are treated as __offsets__ from the given objects position. +* +* If `from` is undefined, and there is no tracked object, then the bullets are fired +* from the given positions, as they exist in the world. +* +* Calling this method sets {@link #multiFire} to `true`. +* +* If there are not enough bullets available in the pool, and the pool cannot be extended, +* then this method may not fire from all of the given positions. +* +* When the bullets are launched they have their texture and frame updated, as required. +* The velocity of the bullets are calculated based on Weapon properties like {@link #bulletSpeed}. +* +* @method Phaser.Weapon#fireMany +* @param {array} positions - An array of positions. Each position can be any Object, as long as it has public `x` and `y` properties, such as Phaser.Point, { x: 0, y: 0 }, Phaser.Sprite, etc. +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullets **from** the `x` and `y` properties of this object, _instead_ of any {@link #trackedSprite} or `trackedPointer` that is set. +* @return {array} An array containing all of the fired Phaser.Bullet objects, if a launch was successful, otherwise an empty array. +*/ +Phaser.Weapon.prototype.fireMany = function (positions, from) { + + this.multiFire = true; + + var bullets = []; + + var _this = this; + + if (from || this.trackedSprite || this.trackedPointer) + { + positions.forEach(function(offset) { + + bullets.push(_this.fire(from, null, null, offset.x, offset.y)); + + }); + } + else + { + positions.forEach(function(position) { + + bullets.push(_this.fire(position)); + + }); + } + + return bullets; + +}; + +/** +* Attempts to fire a single Bullet from a tracked Sprite or Pointer, but applies an offset +* to the position first. This is the same as calling {@link #fire} and passing in the offset arguments. +* +* If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like {@link #bulletSpeed}. +* +* If you wish to fire multiple bullets in a single game update, then set {@link #multiFire} to `true` +* and you can call this method as many times as you like, per loop. See also {@link #fireMany}. +* +* @method Phaser.Weapon#fireOffset +* @param {number} [offsetX=0] - The horizontal offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @param {number} [offsetY=0] - The vertical offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fireOffset = function (offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + return this.fire(null, null, null, offsetX, offsetY); + +}; + +/** +* Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at. +* +* If you don't provide any of the arguments then it uses those set via properties such as {@link #trackedSprite}, +* {@link #bulletAngle} and so on. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like `bulletSpeed`. +* +* If you wish to fire multiple bullets in a single game update, then set `Weapon.multiFire = true` +* and you can call `fire` as many times as you like, per loop. Multiple fires in a single update +* only counts once towards the `shots` total, but you will still receive a Signal for each bullet. +* +* @method Phaser.Weapon#fire +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides {@link #trackedSprite} or `trackedPointer`. Pass `null` to ignore it. +* @param {number} [x] - The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [offsetX=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a horizontal offset from the launch position. +* @param {number} [offsetY=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a vertical offset from the launch position. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fire = function (from, x, y, offsetX, offsetY) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (this.game.time.now < this._nextFire || (this.fireLimit > 0 && this.shots === this.fireLimit)) + { + return null; + } + + var speed = this.bulletSpeed; + + // Apply +- speed variance + if (this.bulletSpeedVariance !== 0) + { + speed += Phaser.Math.between(-this.bulletSpeedVariance, this.bulletSpeedVariance); + } + + if (from) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(from.x, from.y); + } + else + { + this.fireFrom.x = from.x; + this.fireFrom.y = from.y; + } + } + else if (this.trackedSprite) + { + if (this.trackRotation) + { + this._rotatedPoint.set(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.worldRotation); + + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this._rotatedPoint.x, this._rotatedPoint.y); + } + else + { + this.fireFrom.x = this._rotatedPoint.x; + this.fireFrom.y = this._rotatedPoint.y; + } + } + else + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedSprite.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedSprite.world.y + this.trackOffset.y; + } + } + + if (this.bulletInheritSpriteSpeed) + { + speed += this.trackedSprite.body.speed; + } + } + else if (this.trackedPointer) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedPointer.world.x + this.trackOffset.x, this.trackedPointer.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedPointer.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedPointer.world.y + this.trackOffset.y; + } + } + + if (offsetX !== undefined) + { + this.fireFrom.x += offsetX; + } + + if (offsetY !== undefined) + { + this.fireFrom.y += offsetY; + } + + var fromX = (this.fireFrom.width > 1) ? this.fireFrom.randomX : this.fireFrom.x; + var fromY = (this.fireFrom.height > 1) ? this.fireFrom.randomY : this.fireFrom.y; + + var angle = (this.trackRotation) ? this.trackedSprite.angle : this.fireAngle; + + // The position (in world space) to fire the bullet towards, if set + if (x !== null && y !== null) + { + angle = this.game.math.radToDeg(Math.atan2(y - fromY, x - fromX)); + } + + // Apply +- angle variance + if (this.bulletAngleVariance !== 0) + { + angle += Phaser.Math.between(-this.bulletAngleVariance, this.bulletAngleVariance); + } + + var moveX = 0; + var moveY = 0; + + // Avoid sin/cos for right-angled shots + if (angle === 0 || angle === 180) + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + } + else if (angle === 90 || angle === 270) + { + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + else + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + + var bullet = null; + + if (this.autoExpandBulletsGroup) + { + bullet = this.bullets.getFirstExists(false, true, fromX, fromY, this.bulletKey, this.bulletFrame); + + bullet.data.bulletManager = this; + } + else + { + bullet = this.bullets.getFirstExists(false); + } + + if (bullet) + { + bullet.reset(fromX, fromY); + + bullet.data.fromX = fromX; + bullet.data.fromY = fromY; + bullet.data.killType = this.bulletKillType; + bullet.data.killDistance = this.bulletKillDistance; + bullet.data.rotateToVelocity = this.bulletRotateToVelocity; + + if (this.bulletKillType === Phaser.Weapon.KILL_LIFESPAN) + { + bullet.lifespan = this.bulletLifespan; + } + + bullet.angle = angle + this.bulletAngleOffset; + + // Frames and Animations + if (this.bulletAnimation !== '') + { + if (bullet.animations.getAnimation(this.bulletAnimation) === null) + { + var anim = this.anims[this.bulletAnimation]; + + bullet.animations.add(anim.name, anim.frames, anim.frameRate, anim.loop, anim.useNumericIndex); + } + + bullet.animations.play(this.bulletAnimation); + } + else + { + if (this.bulletFrameCycle) + { + bullet.frame = this.bulletFrames[this.bulletFrameIndex]; + + this.bulletFrameIndex++; + + if (this.bulletFrameIndex >= this.bulletFrames.length) + { + this.bulletFrameIndex = 0; + } + } + else if (this.bulletFrameRandom) + { + bullet.frame = this.bulletFrames[Math.floor(Math.random() * this.bulletFrames.length)]; + } + } + + if (bullet.data.bodyDirty) + { + if (this._data.customBody) + { + bullet.body.setSize(this._data.width, this._data.height, this._data.offsetX, this._data.offsetY); + } + + bullet.body.collideWorldBounds = this.bulletCollideWorldBounds; + + bullet.data.bodyDirty = false; + } + + bullet.body.velocity.set(moveX, moveY); + bullet.body.gravity.set(this.bulletGravity.x, this.bulletGravity.y); + + var next = 0; + + if (this.bulletSpeedVariance !== 0) + { + var rate = this.fireRate; + + rate += Phaser.Math.between(-this.fireRateVariance, this.fireRateVariance); + + if (rate < 0) + { + rate = 0; + } + + next = this.game.time.now + rate; + } + else + { + next = this.game.time.now + this.fireRate; + } + + if (this.multiFire) + { + if (!this._hasFired) + { + // We only add 1 to the 'shots' count for multiFire shots + this._hasFired = true; + this._tempNextFire = next; + this.shots++; + } + } + else + { + this._nextFire = next; + + this.shots++; + } + + this.onFire.dispatch(bullet, this, speed); + + if (this.fireLimit > 0 && this.shots === this.fireLimit) + { + this.onFireLimit.dispatch(this, this.fireLimit); + } + } + + return bullet; + +}; + +/** +* Fires a bullet **at** the given Pointer. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtPointer = function (pointer) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + + return this.fire(null, pointer.worldX, pointer.worldY); + +}; + +/** +* Fires a bullet **at** the given Sprite. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtSprite +* @param {Phaser.Sprite} [sprite] - The Sprite to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtSprite = function (sprite) { + + return this.fire(null, sprite.world.x, sprite.world.y); + +}; + +/** +* Fires a bullet **at** the given coordinates. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtXY +* @param {number} [x] - The x coordinate, in world space, to fire the bullet towards. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtXY = function (x, y) { + + return this.fire(null, x, y); + +}; + +/** +* You can modify the size of the physics Body the Bullets use to be any dimension you need. +* This allows you to make it smaller, or larger, than the parent Sprite. +* You can also control the x and y offset of the Body. This is the position of the +* Body relative to the top-left of the Sprite _texture_. +* +* For example: If you have a Sprite with a texture that is 80x100 in size, +* and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: +* +* `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, 34)` +* +* Where the first two parameters are the new Body size (32x32 pixels) relative to the Sprite's scale. +* 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 +* is the vertical offset. +* +* @method Phaser.Weapon#setBulletBodyOffset +* @param {number} width - The width of the Body. +* @param {number} height - The height of the Body. +* @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture. +* @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture. +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletBodyOffset = function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this._data.customBody = true; + this._data.width = width; + this._data.height = height; + this._data.offsetX = offsetX; + this._data.offsetY = offsetY; + + // Update all bullets in the pool + this.bullets.callAll('body.setSize', 'body', width, height, offsetX, offsetY); + this.bullets.setAll('data.bodyDirty', false); + + return this; + +}; + +/** +* Sets the texture frames that the bullets can use when being launched. +* +* This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet. +* +* It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values +* provided. Then it sets the frame index to be zero. +* +* You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames +* when they're fired, or pick one at random. +* +* @method Phaser.Weapon#setBulletFrames +* @param {integer} min - The minimum value the frame can be. Usually zero. +* @param {integer} max - The maximum value the frame can be. +* @param {boolean} [cycle=true] - Should the bullet frames cycle as they are fired? +* @param {boolean} [random=false] - Should the bullet frames be picked at random as they are fired? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletFrames = function (min, max, cycle, random) { + + if (cycle === undefined) { cycle = true; } + if (random === undefined) { random = false; } + + this.bulletFrames = Phaser.ArrayUtils.numberArray(min, max); + + this.bulletFrameIndex = 0; + + this.bulletFrameCycle = cycle; + this.bulletFrameRandom = random; + + return this; + +}; + +/** +* Adds a new animation under the given key. Optionally set the frames, frame rate and loop. +* The arguments are all the same as for `Animation.add`, and work in the same way. +* +* {@link #bulletAnimation} will be set to this animation after it's created. From that point on, all +* bullets fired will play using this animation. You can swap between animations by calling this method +* several times, and then just changing the {@link #bulletAnimation} property to the name of the animation +* you wish to play for the next launched bullet. +* +* If you wish to stop using animations at all, set {@link #bulletAnimation} to '' (an empty string). +* +* @method Phaser.Weapon#addBulletAnimation +* @param {string} name - The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast". +* @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.addBulletAnimation = function (name, frames, frameRate, loop, useNumericIndex) { + + this.anims[name] = { + name: name, + frames: frames, + frameRate: frameRate, + loop: loop, + useNumericIndex: useNumericIndex + }; + + // Add the animation to any existing bullets in the pool + this.bullets.callAll('animations.add', 'animations', name, frames, frameRate, loop, useNumericIndex); + + this.bulletAnimation = name; + + return this; + +}; + +/** +* Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets +* both in-flight, and available. And optionally the physics debug bodies of the bullets. +* +* @method Phaser.Weapon#debug +* @param {integer} [x=16] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {integer} [y=32] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {boolean} [debugBodies=false] - Optionally draw the physics body of every bullet in-flight. +*/ +Phaser.Weapon.prototype.debug = function (x, y, debugBodies) { + + if (x === undefined) { x = 16; } + if (y === undefined) { y = 32; } + if (debugBodies === undefined) { debugBodies = false; } + + this.game.debug.text("Weapon Plugin", x, y); + this.game.debug.text("Bullets Alive: " + this.bullets.total + " - Total: " + this.bullets.length, x, y + 24); + + if (debugBodies) + { + this.bullets.forEachExists(this.game.debug.body, this.game.debug, 'rgba(255, 0, 255, 0.8)'); + } + +}; + +/** +* The Class of the bullets that are launched by this Weapon. Defaults to {@link Phaser.Bullet}, but can be +* overridden before calling `createBullets` and set to your own class type. +* +* It should be a constructor function accepting `(game, x, y, key, frame)`. +* +* @name Phaser.Weapon#bulletClass +* @property {function} bulletClass +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletClass", { + + get: function () { + + return this._bulletClass; + + }, + + set: function (classType) { + + this._bulletClass = classType; + + // `this.bullets` exists only after createBullets() + if (this.bullets) { + this.bullets.classType = this._bulletClass; + } + } + +}); + +/** +* This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`. +* +* There are 7 different "kill types" available: +* +* * `Phaser.Weapon.KILL_NEVER` +* The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code. +* +* * `Phaser.Weapon.KILL_LIFESPAN` +* The bullets are automatically killed when their `bulletLifespan` amount expires. +* +* * `Phaser.Weapon.KILL_DISTANCE` +* The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position. +* +* * `Phaser.Weapon.KILL_WEAPON_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* +* * `Phaser.Weapon.KILL_CAMERA_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.Camera#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_WORLD_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.World#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_STATIC_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to +* match the position of a tracked sprite or pointer. +* +* @name Phaser.Weapon#bulletKillType +* @property {integer} bulletKillType +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletKillType", { + + get: function () { + + return this._bulletKillType; + + }, + + set: function (type) { + + switch (type) + { + case Phaser.Weapon.KILL_STATIC_BOUNDS: + case Phaser.Weapon.KILL_WEAPON_BOUNDS: + this.bulletBounds = this.bounds; + break; + + case Phaser.Weapon.KILL_CAMERA_BOUNDS: + this.bulletBounds = this.game.camera.view; + break; + + case Phaser.Weapon.KILL_WORLD_BOUNDS: + this.bulletBounds = this.game.world.bounds; + break; + } + + this._bulletKillType = type; + + } + +}); + +/** +* Should bullets collide with the World bounds or not? +* +* @name Phaser.Weapon#bulletCollideWorldBounds +* @property {boolean} bulletCollideWorldBounds +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletCollideWorldBounds", { + + get: function () { + + return this._bulletCollideWorldBounds; + + }, + + set: function (value) { + + this._bulletCollideWorldBounds = value; + + this.bullets.setAll('body.collideWorldBounds', value); + this.bullets.setAll('data.bodyDirty', false); + + } + +}); + +/** +* The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Weapon.prototype, "x", { + + get: function () { + + return this.fireFrom.x; + + }, + + set: function (value) { + + this.fireFrom.x = value; + } + +}); + +/** +* The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Weapon.prototype, "y", { + + get: function () { + + return this.fireFrom.y; + + }, + + set: function (value) { + + this.fireFrom.y = value; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites, +* with a few extra properties in the data object to handle Weapon specific features. +* +* @class Phaser.Bullet +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Bullet = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + this.anchor.set(0.5); + + this.data = { + bulletManager: null, + fromX: 0, + fromY: 0, + bodyDirty: true, + rotateToVelocity: false, + killType: 0, + killDistance: 0 + }; + +}; + +Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Bullet.prototype.constructor = Phaser.Bullet; + +/** +* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool. +* Also dispatches the `Weapon.onKill` signal. +* +* @method Phaser.Bullet#kill +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + this.data.bulletManager.onKill.dispatch(this); + + return this; + +}; + +/** +* Updates the Bullet, killing as required. +* +* @method Phaser.Bullet#update +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.update = function () { + + if (!this.exists) + { + return; + } + + if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN) + { + if (this.data.killType === Phaser.Weapon.KILL_DISTANCE) + { + if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance) + { + this.kill(); + } + } + else + { + if (!this.data.bulletManager.bulletBounds.intersects(this)) + { + this.kill(); + } + } + } + + if (this.data.rotateToVelocity) + { + this.rotation = this.body.velocity.atan(); + } + + if (this.data.bulletManager.bulletWorldWrap) + { + this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding); + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. +* +* Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to +* the Video instead (see `startMediaStream` method) +* +* The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback +* changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. +* +* Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. +* +* If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. +* Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. +* +* On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. +* This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio +* it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` +* method to try and work around this limitation, but see the method help for details. +* +* Small screen devices, especially iPod and iPhone will launch the video in its own native video player, +* outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. +* +* Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) +* then you need to add your own event listener +* +* @class Phaser.Video +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. +* @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) +*/ +Phaser.Video = function (game, key, url) { + + if (key === undefined) { key = null; } + if (url === undefined) { url = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. + * @default null + */ + this.key = key; + + /** + * @property {number} width - The width of the video in pixels. + * @default + */ + this.width = 0; + + /** + * @property {number} height - The height of the video in pixels. + * @default + */ + this.height = 0; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.VIDEO; + + /** + * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. + * @default + */ + this.touchLocked = false; + + /** + * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. + */ + this.onChangeSource = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam. + */ + this.onAccess = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. + */ + this.onError = new Phaser.Signal(); + + /** + * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. + * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. + * @property {Phaser.Signal} onTimeout + */ + this.onTimeout = new Phaser.Signal(); + + /** + * This signal is dispatched when the Video is unlocked. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * Start playing the video when it's unlocked. + * @property {boolean} playWhenUnlocked + * @default + */ + this.playWhenUnlocked = true; + + /** + * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. + * @default + */ + this.timeout = 15000; + + /** + * @property {integer} _timeOutID - setTimeout ID. + * @private + */ + this._timeOutID = null; + + /** + * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document. + */ + this.video = null; + + /** + * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. + */ + this.videoStream = null; + + /** + * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam. + */ + this.isStreaming = false; + + /** + * When starting playback of a video Phaser will monitor its readyState using a setTimeout call. + * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * @property {integer} retryLimit + * @default + */ + this.retryLimit = 20; + + /** + * @property {integer} retry - The current retry attempt. + * @default + */ + this.retry = 0; + + /** + * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video. + * @default + */ + this.retryInterval = 500; + + /** + * @property {integer} _retryID - The callback ID of the retry setTimeout. + * @private + */ + this._retryID = null; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {boolean} _codePaused - Internal paused tracking var. + * @private + * @default + */ + this._codePaused = false; + + /** + * @property {boolean} _paused - Internal paused tracking var. + * @private + * @default + */ + this._paused = false; + + /** + * @property {boolean} _pending - Internal var tracking play pending. + * @private + * @default + */ + this._pending = false; + + /** + * @property {boolean} _pendingChangeSource - Internal var tracking play pending. + * @private + * @default + */ + this._pendingChangeSource = false; + + /** + * @property {boolean} _autoplay - Internal var tracking autoplay when changing source. + * @private + * @default + */ + this._autoplay = false; + + /** + * @property {function} _endCallback - The addEventListener ended function. + * @private + */ + this._endCallback = null; + + /** + * @property {function} _playCallback - The addEventListener playing function. + * @private + */ + this._playCallback = null; + + if (key && this.game.cache.checkVideoKey(key)) + { + var _video = this.game.cache.getVideo(key); + + if (_video.isBlob) + { + this.createVideoFromBlob(_video.data); + } + else + { + this.video = _video.data; + } + + this.width = this.video.videoWidth; + this.height = this.video.videoHeight; + } + else if (url) + { + this.createVideoFromURL(url, false); + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + if (this.video && !url) + { + this.baseTexture = new PIXI.BaseTexture(this.video, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + else + { + this.baseTexture = new PIXI.BaseTexture(Phaser.Cache.DEFAULT.baseTexture.source, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering. + * @default + */ + this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video'); + + this.texture.setFrame(this.textureFrame); + + this.texture.valid = false; + + if (key !== null && this.video) + { + this.texture.valid = this.video.canplay; + } + + /** + * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). + * When called the BitmapData is updated with a grab taken from the current video playing or active video stream. + * If Phaser has been compiled without BitmapData support this property will always be `null`. + * + * @property {Phaser.BitmapData} snapshot + * @readOnly + */ + this.snapshot = null; + + if (Phaser.BitmapData) + { + this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height); + } + + if (this.game.device.needsTouchUnlock()) + { + this.setTouchLock(); + } + else + { + if (_video) + { + _video.locked = false; + } + } + +}; + +Phaser.Video.prototype = { + + /** + * Connects to an external media stream for the webcam, rather than using a local one. + * + * @method Phaser.Video#connectToMediaStream + * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses. + * @param {MediaStream} stream - The Video Stream data. + * @return {Phaser.Video} This Video object for method chaining. + */ + connectToMediaStream: function (video, stream) { + + if (video && stream) + { + this.video = video; + this.videoStream = stream; + + this.isStreaming = true; + this.baseTexture.source = this.video; + this.updateTexture(null, this.video.videoWidth, this.video.videoHeight); + + this.onAccess.dispatch(this); + } + + return this; + + }, + + /** + * Instead of playing a video file this method allows you to stream video data from an attached webcam. + * + * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam. + * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream. + * + * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError + * or MediaStreamError event. + * + * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions. + * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device. + * You can listen for this with the onChangeSource signal. + * + * @method Phaser.Video#startMediaStream + * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream. + * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source. + * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source. + * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia. + */ + startMediaStream: function (captureAudio, width, height) { + + if (captureAudio === undefined) { captureAudio = false; } + if (width === undefined) { width = null; } + if (height === undefined) { height = null; } + + if (!this.game.device.getUserMedia) + { + this.onError.dispatch(this, 'No getUserMedia'); + return false; + } + + if (this.videoStream !== null) + { + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + this.videoStream.stop(); + } + } + + this.removeVideoElement(); + + this.video = document.createElement("video"); + this.video.setAttribute('autoplay', 'autoplay'); + + if (width !== null) + { + this.video.width = width; + } + + if (height !== null) + { + this.video.height = height; + } + + // Request access to the webcam + + this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout); + + try { + navigator.getUserMedia( + { "audio": captureAudio, "video": true }, + this.getUserMediaSuccess.bind(this), + this.getUserMediaError.bind(this) + ); + } + catch (error) + { + this.getUserMediaError(error); + } + + return this; + + }, + + /** + * @method Phaser.Video#getUserMediaTimeout + * @private + */ + getUserMediaTimeout: function () { + + clearTimeout(this._timeOutID); + + this.onTimeout.dispatch(this); + + }, + + /** + * @method Phaser.Video#getUserMediaError + * @private + */ + getUserMediaError: function (event) { + + clearTimeout(this._timeOutID); + + this.onError.dispatch(this, event); + + }, + + /** + * @method Phaser.Video#getUserMediaSuccess + * @private + */ + getUserMediaSuccess: function (stream) { + + clearTimeout(this._timeOutID); + + // Attach the stream to the video + this.videoStream = stream; + + // Set the source of the video element with the stream from the camera + if (this.video.mozSrcObject !== undefined) + { + this.video.mozSrcObject = stream; + } + else + { + this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; + } + + var self = this; + + this.video.onloadeddata = function () { + + var retry = 10; + + function checkStream () { + + if (retry > 0) + { + if (self.video.videoWidth > 0) + { + // Patch for Firefox bug where the height can't be read from the video + var width = self.video.videoWidth; + var height = self.video.videoHeight; + + if (isNaN(self.video.videoHeight)) + { + height = width / (4/3); + } + + self.video.play(); + + self.isStreaming = true; + self.baseTexture.source = self.video; + self.updateTexture(null, width, height); + self.onAccess.dispatch(self); + } + else + { + window.setTimeout(checkStream, 500); + } + } + else + { + console.warn('Unable to connect to video stream. Webcam error?'); + } + + retry--; + } + + checkStream(); + + }; + + }, + + /** + * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format. + * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience. + * + * @method Phaser.Video#createVideoFromBlob + * @param {Blob} blob - The Blob containing the video data. + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromBlob: function (blob) { + + var _this = this; + + this.video = document.createElement("video"); + this.video.controls = false; + this.video.setAttribute('autoplay', 'autoplay'); + this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true); + this.video.src = window.URL.createObjectURL(blob); + this.video.canplay = true; + + return this; + + }, + + /** + * Creates a new Video element from the given URL. + * + * @method Phaser.Video#createVideoFromURL + * @param {string} url - The URL of the video. + * @param {boolean} [autoplay=false] - Automatically start the video? + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromURL: function (url, autoplay) { + + if (autoplay === undefined) { autoplay = false; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + if (this.texture) + { + this.texture.valid = false; + } + + this.video = document.createElement("video"); + this.video.controls = false; + + if (autoplay) + { + this.video.setAttribute('autoplay', 'autoplay'); + } + + this.video.src = url; + + this.video.canplay = true; + + this.video.load(); + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.key = url; + + return this; + + }, + + /** + * Called automatically if the video source changes and updates the internal texture dimensions. + * Then dispatches the onChangeSource signal. + * + * @method Phaser.Video#updateTexture + * @param {object} [event] - The event which triggered the texture update. + * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used. + * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used. + */ + updateTexture: function (event, width, height) { + + var change = false; + + if (width === undefined || width === null) { width = this.video.videoWidth; change = true; } + if (height === undefined || height === null) { height = this.video.videoHeight; } + + this.width = width; + this.height = height; + + if (this.baseTexture.source !== this.video) + { + this.baseTexture.source = this.video; + } + + this.baseTexture.forceLoaded(width, height); + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.valid = true; + + if (this.snapshot) + { + this.snapshot.resize(width, height); + } + + if (change && this.key !== null) + { + this.onChangeSource.dispatch(this, width, height); + + if (this._autoplay) + { + this.video.play(); + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + } + + }, + + /** + * Called when the video completes playback (reaches and ended state). + * Dispatches the Video.onComplete signal. + * + * @method Phaser.Video#complete + */ + complete: function () { + + this.onComplete.dispatch(this); + + }, + + /** + * Starts this video playing. + * + * If the video is already playing, or has been queued to play with `changeSource` then this method just returns. + * + * @method Phaser.Video#play + * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. + * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate. + * @return {Phaser.Video} This Video object for method chaining. + */ + play: function (loop, playbackRate) { + + if (this._pendingChangeSource) + { + return this; + } + + if (loop === undefined) { loop = false; } + if (playbackRate === undefined) { playbackRate = 1; } + + if (this.game.sound.onMute) + { + this.game.sound.onMute.add(this.setMute, this); + this.game.sound.onUnMute.add(this.unsetMute, this); + + if (this.game.sound.mute) + { + this.setMute(); + } + } + + this.game.onPause.add(this.setPause, this); + this.game.onResume.add(this.setResume, this); + + this._endCallback = this.complete.bind(this); + + this.video.addEventListener('ended', this._endCallback, true); + this.video.addEventListener('webkitendfullscreen', this._endCallback, true); + + if (loop) + { + this.video.loop = 'loop'; + } + else + { + this.video.loop = ''; + } + + this.video.playbackRate = playbackRate; + + if (this.touchLocked) + { + this._pending = true; + } + else + { + this._pending = false; + + if (this.key !== null) + { + if (this.video.readyState !== 4) + { + this.retry = this.retryLimit; + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + this._playCallback = this.playHandler.bind(this); + this.video.addEventListener('playing', this._playCallback, true); + } + } + + this.video.play(); + + this.onPlay.dispatch(this, loop, playbackRate); + } + + return this; + + }, + + /** + * Called when the video starts to play. Updates the texture. + * + * @method Phaser.Video#playHandler + * @private + */ + playHandler: function () { + + this.video.removeEventListener('playing', this._playCallback, true); + + this.updateTexture(); + + }, + + /** + * Stops the video playing. + * + * This removes all locally set signals. + * + * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead. + * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to + * call `Video.destroy` instead. + * + * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam. + * + * @method Phaser.Video#stop + * @return {Phaser.Video} This Video object for method chaining. + */ + stop: function () { + + if (this.game.sound.onMute) + { + this.game.sound.onMute.remove(this.setMute, this); + this.game.sound.onUnMute.remove(this.unsetMute, this); + } + + this.game.onPause.remove(this.setPause, this); + this.game.onResume.remove(this.setResume, this); + + // Stream or file? + + if (this.isStreaming) + { + if (this.video.mozSrcObject) + { + this.video.mozSrcObject.stop(); + this.video.src = null; + } + else + { + this.video.src = ''; + + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + if (this.videoStream.getTracks) + { + this.videoStream.getTracks().forEach(function (track) { + track.stop(); + }); + } + else + { + this.videoStream.stop(); + } + } + } + + this.videoStream = null; + this.isStreaming = false; + } + else + { + this.video.removeEventListener('ended', this._endCallback, true); + this.video.removeEventListener('webkitendfullscreen', this._endCallback, true); + this.video.removeEventListener('playing', this._playCallback, true); + + if (this.touchLocked) + { + this._pending = false; + } + else + { + this.video.pause(); + } + } + + return this; + + }, + + /** + * Updates the given Display Objects so they use this Video as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.Video#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.Video} This Video object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. + * + * @method Phaser.Video#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set Video.disableTextureUpload to `true`. + * + * @method Phaser.Video#render + */ + render: function () { + + if (!this.disableTextureUpload && this.playing) + { + this.baseTexture.dirty(); + } + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + this.video.muted = true; + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + this.video.muted = false; + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setPause + * @private + */ + setPause: function () { + + if (this._paused || this.touchLocked) + { + return; + } + + this._paused = true; + + this.video.pause(); + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setResume + * @private + */ + setResume: function () { + + if (!this._paused || this._codePaused || this.touchLocked) + { + return; + } + + this._paused = false; + + if (!this.video.ended) + { + this.video.play(); + } + + }, + + /** + * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it. + * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over" + * split into three different Video objects, then you will need the user to touch-unlock every single one of them. + * + * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains + * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again. + * + * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate. + * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it + * cannot render the new video on iOS (desktop browsers cope better). + * + * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know + * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state + * are adopted automatically by the new video. + * + * @method Phaser.Video#changeSource + * @param {string} src - The new URL to change the video.src to. + * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated? + * @return {Phaser.Video} This Video object for method chaining. + */ + changeSource: function (src, autoplay) { + + if (autoplay === undefined) { autoplay = true; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + this.texture.valid = false; + + this.video.pause(); + + this._pendingChangeSource = true; + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.video.src = src; + + this.video.load(); + + this._autoplay = autoplay; + + if (!autoplay) + { + this.paused = true; + } + + return this; + + }, + + /** + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.Video#checkVideoProgress + * @private + */ + checkVideoProgress: function () { + + // if (this.video.readyState === 2 || this.video.readyState === 4) + if (this.video.readyState === 4) + { + this._pendingChangeSource = false; + + // We've got enough data to update the texture for playback + this.updateTexture(); + } + else + { + this.retry--; + + if (this.retry > 0) + { + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming); + } + } + + }, + + /** + * Sets the Input Manager touch callback to be Video.unlock. + * Required for mobile video unlocking. Mostly just used internally. + * + * @method Phaser.Video#setTouchLock + */ + setTouchLock: function () { + + this.game.input.addTouchLockCallback(this.unlock, this, true); + this.touchLocked = true; + + }, + + /** + * Enables the video on mobile devices, usually after the first touch. + * If the SoundManager hasn't been unlocked then this will automatically unlock that as well. + * Only one video can be pending unlock at any one time. + * + * @method Phaser.Video#unlock + */ + unlock: function () { + + this.touchLocked = false; + + if (this.playWhenUnlocked) + { + this.video.play(); + + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + + if (this.key) + { + var _video = this.game.cache.getVideo(this.key); + + if (_video && !_video.isBlob) + { + _video.locked = false; + } + } + + this.onTouchUnlock.dispatch(this); + + return true; + + }, + + /** + * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData. + * + * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw. + * + * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy. + * + * @method Phaser.Video#grab + * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false. + * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining. + */ + grab: function (clear, alpha, blendMode) { + + if (clear === undefined) { clear = false; } + if (alpha === undefined) { alpha = 1; } + if (blendMode === undefined) { blendMode = null; } + + if (this.snapshot === null) + { + console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable'); + return; + } + + if (clear) + { + this.snapshot.cls(); + } + + this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode); + + return this.snapshot; + + }, + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * Also removes the autoplay and src attributes and nulls the reference. + * + * @method Phaser.Video#removeVideoElement + */ + removeVideoElement: function () { + + if (!this.video) + { + return; + } + + if (this.video.parentNode) + { + this.video.parentNode.removeChild(this.video); + } + + while (this.video.hasChildNodes()) + { + this.video.removeChild(this.video.firstChild); + } + + this.video.removeAttribute('autoplay'); + this.video.removeAttribute('src'); + + this.video = null; + + }, + + /** + * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`. + * If any Sprites are using this Video as their texture it is up to you to manage those. + * + * @method Phaser.Video#destroy + */ + destroy: function () { + + this.stop(); + + this.removeVideoElement(); + + if (this.touchLocked) + { + this.game.input.touch.removeTouchLockCallback(this.unlock, this); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + + } + +}; + +/** +* @name Phaser.Video#currentTime +* @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time. +*/ +Object.defineProperty(Phaser.Video.prototype, "currentTime", { + + get: function () { + + return (this.video) ? this.video.currentTime : 0; + + }, + + set: function (value) { + + this.video.currentTime = value; + + } + +}); + +/** +* @name Phaser.Video#duration +* @property {number} duration - The duration of the video in seconds. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "duration", { + + get: function () { + + return (this.video) ? this.video.duration : 0; + + } + +}); + +/** +* @name Phaser.Video#progress +* @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "progress", { + + get: function () { + + return (this.video) ? (this.video.currentTime / this.video.duration) : 0; + + } + +}); + +/** +* @name Phaser.Video#mute +* @property {boolean} mute - Gets or sets the muted state of the Video. +*/ +Object.defineProperty(Phaser.Video.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || null; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* Gets or sets the paused state of the Video. +* If the video is still touch locked (such as on iOS devices) this call has no effect. +* +* @name Phaser.Video#paused +* @property {boolean} paused +*/ +Object.defineProperty(Phaser.Video.prototype, "paused", { + + get: function () { + + return this._paused; + + }, + + set: function (value) { + + value = value || null; + + if (this.touchLocked) + { + return; + } + + if (value) + { + if (this._paused) + { + return; + } + + this._codePaused = true; + this.setPause(); + } + else + { + if (!this._paused) + { + return; + } + + this._codePaused = false; + this.setResume(); + } + } + +}); + +/** +* @name Phaser.Video#volume +* @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Video.prototype, "volume", { + + get: function () { + + return (this.video) ? this.video.volume : 1; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this.video) + { + this.video.volume = value; + } + + } + +}); + +/** +* @name Phaser.Video#playbackRate +* @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing. +*/ +Object.defineProperty(Phaser.Video.prototype, "playbackRate", { + + get: function () { + + return (this.video) ? this.video.playbackRate : 1; + + }, + + set: function (value) { + + if (this.video) + { + this.video.playbackRate = value; + } + + } + +}); + +/** +* Gets or sets if the Video is set to loop. +* Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. +* If the video isn't yet set this will always return false. +* +* @name Phaser.Video#loop +* @property {boolean} loop +*/ +Object.defineProperty(Phaser.Video.prototype, "loop", { + + get: function () { + + return (this.video) ? this.video.loop : false; + + }, + + set: function (value) { + + if (value && this.video) + { + this.video.loop = 'loop'; + } + else if (this.video) + { + this.video.loop = ''; + } + + } + +}); + +/** +* @name Phaser.Video#playing +* @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "playing", { + + get: function () { + + return (this.video) ? !(this.video.paused && this.video.ended) : false; + + } + +}); + +Phaser.Video.prototype.constructor = Phaser.Video; + +/* global Phaser:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Pixi expects these globals to exist + +if (PIXI.blendModes === undefined) +{ + PIXI.blendModes = Phaser.blendModes; +} + +if (PIXI.scaleModes === undefined) +{ + PIXI.scaleModes = Phaser.scaleModes; +} + +if (PIXI.Texture.emptyTexture === undefined) +{ + PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture()); +} + +if (PIXI.DisplayObject._tempMatrix === undefined) +{ + PIXI.DisplayObject._tempMatrix = new Phaser.Matrix(); +} + +PIXI.TextureSilentFail = true; + +// Required by Particle Storm +PIXI.canUseNewCanvasBlendModes = function () { + return Phaser.Device.canUseMultiply; +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = Phaser; + } + exports.Phaser = Phaser; + } else if (typeof define !== 'undefined' && define.amd) { + define('Phaser', (function() { return root.Phaser = Phaser; })() ); + } else { + root.Phaser = Phaser; + } + + return Phaser; +}).call(this); + +/* +* "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer +*/ diff --git a/Digital Assignment 5/js/phaser.map b/Digital Assignment 5/js/phaser.map new file mode 100644 index 000000000..70723bbf8 --- /dev/null +++ b/Digital Assignment 5/js/phaser.map @@ -0,0 +1 @@ +{"version":3,"sources":["phaser.js"],"names":["e","exports","module","f","window","global","self","p2","t","n","r","s","o","u","a","require","i","Error","call","length","1","_dereq_","Line","Scalar","lineInt","l1","l2","precision","a1","b1","c1","a2","b2","c2","det","eq","segmentsIntersect","p1","q1","q2","dx","dy","da","db","./Scalar","2","Point","area","b","c","left","leftOn","right","rightOn","tmpPoint1","tmpPoint2","collinear","thresholdAngle","ab","bc","dot","magA","Math","sqrt","magB","acos","sqdist","3","Polygon","this","vertices","getIntersectionPoint","delta","prototype","at","v","first","last","clear","append","poly","from","to","push","makeCCW","br","reverse","tmp","N","pop","isReflex","tmpLine1","tmpLine2","canSee","p","dist","copy","j","targetPoly","k","getCutEdges","min","tmp1","tmp2","tmpPoly","nDiags","Number","MAX_VALUE","decomp","edges","slice","cutEdges","Array","polys","cutEdge","result","splice","indexOf","isSimple","path","quickDecomp","reflexVertices","steinerPoints","maxlevel","level","upperInt","lowerInt","upperDist","lowerDist","d","closestDist","upperIndex","lowerIndex","closestIndex","lowerPoly","upperPoly","console","warn","removeCollinearPoints","num","./Line","./Point","4","abs","5","./Polygon","6","name","version","description","author","keywords","main","engines","node","repository","type","url","bugs","licenses","devDependencies","grunt","grunt-contrib-jshint","grunt-contrib-nodeunit","grunt-contrib-uglify","grunt-contrib-watch","grunt-browserify","grunt-contrib-concat","dependencies","poly-decomp","7","AABB","options","lowerBound","vec2","create","upperBound","setFromPoints","points","position","angle","skinSize","l","rotate","cosAngle","cos","sinAngle","sin","x","y","add","aabb","extend","overlaps","u1","u2","containsPoint","point","overlapsRay","ray","dirFracX","direction","dirFracY","t1","t2","t3","t4","tmin","max","tmax","../math/vec2","../utils/Utils","8","Broadphase","world","boundingVolumeType","Body","BOUNDING_CIRCLE","setWorld","getCollisionPairs","boundingRadiusCheck","bodyA","bodyB","sub","d2","squaredLength","boundingRadius","aabbCheck","getAABB","boundingVolumeCheck","canCollide","KINEMATIC","STATIC","sleepState","SLEEPING","NAIVE","SAP","../objects/Body","9","NaiveBroadphase","constructor","bodies","Ncolliding","bi","bj","aabbQuery","aabbNeedsUpdate","updateAABB","../collision/Broadphase","../shapes/Circle","../shapes/Particle","../shapes/Plane","../shapes/Shape","10","Narrowphase","contactEquations","frictionEquations","enableFriction","enabledEquations","slipForce","frictionCoefficient","surfaceVelocity","contactEquationPool","ContactEquationPool","size","frictionEquationPool","FrictionEquationPool","restitution","stiffness","Equation","DEFAULT_STIFFNESS","relaxation","DEFAULT_RELAXATION","frictionStiffness","frictionRelaxation","enableFrictionReduction","collidingBodiesLastStep","TupleDictionary","contactSkinSize","setConvexToCapsuleShapeMiddle","convexShape","capsuleShape","set","radius","pointInConvex","worldPoint","convexOffset","convexAngle","worldVertex0","pic_worldVertex0","worldVertex1","pic_worldVertex1","r0","pic_r0","r1","pic_r1","verts","lastCross","v0","v1","cross","crossLength","Circle","Convex","Shape","Box","yAxis","fromValues","tmp3","tmp4","tmp5","tmp6","tmp7","tmp8","tmp9","tmp10","tmp11","tmp12","tmp13","tmp14","tmp15","tmp16","tmp17","tmp18","tmpArray","bodiesOverlap_shapePositionA","bodiesOverlap_shapePositionB","bodiesOverlap","shapePositionA","shapePositionB","Nshapesi","shapes","shapeA","toWorldFrame","Nshapesj","shapeB","collidedLastStep","id1","id","id2","get","reset","eqs","ce","fe","release","createContactEquation","firstImpact","needsUpdate","enabled","offset","createFrictionEquation","setSlipForce","relativeVelocity","createFrictionFromContact","contactPointA","contactPointB","rotate90cw","normalA","createFrictionFromAverage","numContacts","invNumContacts","scale","normalize","LINE","CONVEX","convexLine","convexBody","lineBody","lineShape","lineOffset","lineAngle","justTest","BOX","lineBox","boxBody","boxShape","boxOffset","boxAngle","convexCapsule_tempRect","width","height","convexCapsule_tempVec","CAPSULE","convexCapsule","convexPosition","capsuleBody","capsulePosition","capsuleAngle","circlePos","result1","circleConvex","result2","convexConvex","lineCapsule","linePosition","capsuleCapsule_tempVec1","capsuleCapsule_tempVec2","capsuleCapsule_tempRect1","capsuleCapsule","si","xi","ai","sj","xj","aj","circlePosi","circlePosj","enableFrictionBefore","circleCircle","rect","lineLine","positionA","angleA","positionB","angleB","PLANE","planeLine","planeBody","planeShape","planeOffset","planeAngle","worldVertex01","worldVertex11","worldEdge","worldEdgeUnit","worldNormal","worldTangent","PARTICLE","particleCapsule","particleBody","particleShape","particlePosition","particleAngle","circleLine","CIRCLE","circleBody","circleShape","circleOffset","circleAngle","lineRadius","circleRadius","orthoDist","lineToCircleOrthoUnit","projectedPoint","centerDist","lineToCircle","lineEndToLineRadius","radiusSum","pos","pos0","pos1","pow","circleCapsule","worldVertex","closestEdgeProjectedPoint","candidate","candidateDist","minCandidate","found","minCandidateDistance","candidateDistance","localVertex","particleConvex","particleOffset","convexToparticle","minEdgeNormal","offsetA","offsetB","radiusA","radiusB","planeConvex","numReported","particlePlane","circleParticle","planeCapsule_tmpCircle","planeCapsule_tmp1","planeCapsule_tmp2","planeCapsule","capsuleOffset","end1","end2","circle","numContacts1","circlePlane","numContacts2","numTotal","planeToCircle","temp","contact","sepAxis","worldPoint0","worldPoint1","penetrationVec","findSeparatingAxis","closestEdge1","getClosestEdge","closestEdge2","closestEdgeA","closestEdgeB","insideNumEdges","pcoa_tmp1","projectConvexOntoAxis","worldAxis","value","localAxis","fsa_tmp1","fsa_tmp2","fsa_tmp3","fsa_tmp4","fsa_tmp5","fsa_tmp6","offset1","angle1","offset2","angle2","maxDist","overlap","edge","normal","span1","span2","gce_tmp1","gce_tmp2","gce_tmp3","axis","flip","closestEdge","maxDot","circleHeightfield_candidate","circleHeightfield_dist","circleHeightfield_v0","circleHeightfield_v1","circleHeightfield_minCandidate","circleHeightfield_worldNormal","circleHeightfield_minCandidateNormal","HEIGHTFIELD","circleHeightfield","hfBody","hfShape","hfPos","hfAngle","data","heights","w","elementWidth","minCandidateNormal","idxA","floor","idxB","ceil","PI","convexHeightfield_v0","convexHeightfield_v1","convexHeightfield_tilePos","convexHeightfield_tempConvexShape","convexHeightfield","convexPos","tilePos","tileConvex","../equations/ContactEquation","../equations/Equation","../equations/FrictionEquation","../shapes/Box","../shapes/Convex","../utils/ContactEquationPool","../utils/FrictionEquationPool","../utils/TupleDictionary","11","Ray","checkCollisionResponse","undefined","skipBackfaces","collisionMask","collisionGroup","mode","ANY","callback","update","distanceFromIntersectionSquared","intersect","squaredDistance","CLOSEST","ALL","intersectBodies","shouldStop","body","intersectBody","intersectBody_worldPosition","collisionResponse","worldPosition","shape","worldAngle","intersectShape","_currentBody","_currentShape","raycast","reportIntersection","fraction","faceIndex","hasHit","../collision/AABB","../collision/RaycastResult","12","RaycastResult","isStopped","getHitDistance","distance","getHitPoint","out","lerp","stop","../collision/Ray","13","SAPBroadphase","axisList","axisIndex","that","_addBodyHandler","_removeBodyHandler","idx","Utils","appendArray","off","on","sortAxisList","sortList","14","Constraint","defaults","collideConnected","wakeUpBodies","equations","wakeUp","DISTANCE","GEAR","LOCK","PRISMATIC","REVOLUTE","setStiffness","setRelaxation","15","DistanceConstraint","localAnchorA","localAnchorB","worldAnchorA","worldAnchorB","maxForce","ri","rj","computeGq","setMaxForce","upperLimitEnabled","upperLimit","lowerLimitEnabled","lowerLimit","normalEquation","G","violating","minForce","rixn","rjxn","getMaxForce","./Constraint","16","GearConstraint","ratio","AngleLockEquation","maxTorque","setMaxTorque","setRatio","torque","getMaxTorque","../equations/AngleLockEquation","17","LockConstraint","localAngleB","rot","g","localOffsetB","force","xAxis","18","PrismaticConstraint","localAxisA","trans","gg","updateJacobian","disableRotationalLock","RotationalLockEquation","velocity","upperLimitEquation","ContactEquation","lowerLimitEquation","motorEquation","motorEnabled","motorSpeed","computeGW","vi","vj","wi","angularVelocity","wj","gmult","worldAxisA","orientedAnchorA","orientedAnchorB","relPosition","enableMotor","disableMotor","setLimits","lower","upper","../equations/RotationalLockEquation","19","RevoluteConstraint","pivotA","pivotB","worldPivot","localPivotA","localPivotB","worldPivotA","worldPivotB","RotationalVelocityEquation","relAngle","setMotorSpeed","speed","getMotorSpeed","../equations/RotationalVelocityEquation","20","./Equation","21","computeB","h","GW","Gq","computeGiMf","relVel","getVelocityAlongNormal","getVelocityAtPoint","subtract","22","ARRAY_TYPE","epsilon","timeStep","multiplier","qi","qj","computeGWlambda","vlambda","wlambda","iMfi","iMfj","fi","ti","angularForce","fj","tj","invMassi","invMassSolve","invMassj","invIi","invInertiaSolve","invIj","multiply","massMultiplier","computeGiMGt","addToWlambda_temp","addToWlambda_Gi","addToWlambda_Gj","addToWlambda","deltalambda","Gi","Gj","computeInvC","eps","23","FrictionEquation","getSlipForce","24","worldVectorA","worldVectorB","25","GiMf","26","EventEmitter","listener","context","_listeners","listeners","has","index","emit","event","listenerArray","target","27","ContactMaterial","materialA","materialB","Material","idCounter","friction","./Material","28","29","PolyK","GetArea","sum","Triangulate","tgs","avl","al","i0","i1","i2","ax","ay","bx","by","cx","cy","earFound","_convex","_PointInTriangle","px","py","v0x","v0y","v1x","v1y","v2x","v2y","dot00","dot01","dot02","dot11","dot12","invDenom","30","crossVZ","vec","zcomp","crossZV","toLocalFrame","framePosition","frameAngle","toGlobalFrame","localPoint","vectorToLocalFrame","worldVector","vectorToGlobalFrame","localVector","centroid","clone","mul","divide","div","sqrDist","len","sqrLen","negate","str","reflect","vector","getLineSegmentsIntersection","p0","p3","getLineSegmentsIntersectionFraction","s1_x","s1_y","s2_x","s2_y","31","_idCounter","mass","invMass","inertia","invInertia","fixedRotation","fixedX","fixedY","interpolatedPosition","interpolatedAngle","previousPosition","previousAngle","damping","angularDamping","DYNAMIC","allowSleep","wantsToSleep","AWAKE","sleepSpeedLimit","sleepTimeLimit","gravityScale","idleTime","timeLastSleepy","ccdSpeedThreshold","ccdIterations","concavePath","_wakeUpAfterNarrowphase","updateMassProperties","updateSolveMassProperties","setDensity","density","totalArea","getArea","shapeAABB","bodyAngle","computeAABB","updateBoundingRadius","addShape","removeShape","m","I","r2","computeMomentOfInertia","applyForce","relativePoint","rotForce","Body_applyForce_forceWorld","Body_applyForce_pointWorld","Body_applyForce_pointLocal","applyForceLocal","localForce","worldForce","vectorToWorldFrame","Body_applyImpulse_velo","applyImpulse","impulseVector","velo","rotVelo","Body_applyImpulse_impulseWorld","Body_applyImpulse_pointWorld","Body_applyImpulse_pointLocal","applyImpulseLocal","localImpulse","worldImpulse","fromPolygon","convexes","optimalDecomp","cm","centerOfMass","updateTriangles","updateCenterOfMass","adjustCenterOfMass","adjustCenterOfMass_tmp2","adjustCenterOfMass_tmp3","adjustCenterOfMass_tmp4","offset_times_area","setZeroForce","resetConstraintVelocity","addConstraintVelocity","applyDamping","dt","wakeUpEvent","sleep","sleepEvent","sleepTick","time","dontSleep","SLEEPY","overlapKeeper","bodiesAreOverlapping","integrate_fhMinv","integrate_velodt","integrate","minv","integrateToTimeOfImpact","end","startToEnd","rememberPosition","hit","startToEndAngle","timeOfImpact","rememberAngle","iter","tmid","narrowphase","sleepyEvent","../events/EventEmitter","32","LinearSpring","Spring","setWorldAnchorA","setWorldAnchorB","getWorldAnchorA","getWorldAnchorB","worldDistance","restLength","applyForce_r","applyForce_r_unit","applyForce_u","applyForce_f","applyForce_worldAnchorA","applyForce_worldAnchorB","applyForce_ri","applyForce_rj","applyForce_tmp","r_unit","rlen","ri_x_f","rj_x_f","./Spring","33","RotationalSpring","restAngle","34","35","TopDownVehicle","chassisBody","wheels","groundBody","preStepCallback","WheelConstraint","vehicle","forwardEquation","sideEquation","steerValue","engineForce","setSideFriction","sideFriction","localForwardVector","localPosition","apply","setBrakeForce","addToWorld","addBody","wheel","addConstraint","removeFromWorld","removeBody","removeConstraint","addWheel","wheelOptions","worldVelocity","getSpeed","tmpVec","../constraints/Constraint","36","Capsule","GSSolver","Heightfield","Particle","Plane","Pool","Solver","World","Object","defineProperty","../package.json","./collision/AABB","./collision/Broadphase","./collision/NaiveBroadphase","./collision/Narrowphase","./collision/Ray","./collision/RaycastResult","./collision/SAPBroadphase","./constraints/Constraint","./constraints/DistanceConstraint","./constraints/GearConstraint","./constraints/LockConstraint","./constraints/PrismaticConstraint","./constraints/RevoluteConstraint","./equations/AngleLockEquation","./equations/ContactEquation","./equations/Equation","./equations/FrictionEquation","./equations/RotationalVelocityEquation","./events/EventEmitter","./material/ContactMaterial","./material/Material","./math/vec2","./objects/Body","./objects/LinearSpring","./objects/RotationalSpring","./objects/Spring","./objects/TopDownVehicle","./shapes/Box","./shapes/Capsule","./shapes/Circle","./shapes/Convex","./shapes/Heightfield","./shapes/Line","./shapes/Particle","./shapes/Plane","./shapes/Shape","./solver/GSSolver","./solver/Solver","./utils/ContactEquationPool","./utils/FrictionEquationPool","./utils/Pool","./utils/Utils","./world/World","37","arguments","axes","updateArea","./Convex","./Shape","38","intersectCapsule_hitPointWorld","intersectCapsule_normal","intersectCapsule_l0","intersectCapsule_l1","intersectCapsule_unit_y","hitPointWorld","l0","halfLen","diagonalLengthSquared","sqrtDelta","inv2a","d1","39","Ray_intersectSphere_intersectionPoint","Ray_intersectSphere_normal","intersectionPoint","40","isArray","triangles","polyk","tmpVec1","tmpVec2","projectOntoLocalAxis","projectOntoWorldAxis","shapeOffset","shapeAngle","polykVerts","id3","updateCenterOfMass_centroid","updateCenterOfMass_centroid_times_mass","updateCenterOfMass_a","updateCenterOfMass_b","updateCenterOfMass_c","centroid_times_mass","triangleArea","denom","numer","intersectConvex_rayStart","intersectConvex_rayEnd","intersectConvex_normal","rayStart","rayEnd","../math/polyk","41","key","maxValue","minValue","updateMaxMinValues","getLineSegment","start","getSegmentIndex","getClampedSegmentIndex","intersectHeightfield_worldNormal","intersectHeightfield_l0","intersectHeightfield_l1","intersectHeightfield_localFrom","intersectHeightfield_localTo","localFrom","localTo","42","raycast_normal","raycast_l0","raycast_l1","raycast_unit_y","43","44","intersectPlane_planePointToFrom","intersectPlane_normal","intersectPlane_len","planePointToFrom","planeToFrom","n_dot_dir","45","material","sensor","46","GS","iterations","tolerance","arrayStep","lambda","Bs","invCs","useZeroRHS","frictionIterations","usedIterations","setArrayZero","array","solve","sortEquations","maxIter","maxFrictionIter","Neq","tolSquared","Nbodies","deltalambdaTot","iterateEquation","updateMultipliers","invDt","B","invC","lambdaj","GWlambda","lambdaj_plus_deltalambda","./Solver","47","equationSortFunction","mockWorld","solveIsland","island","removeAllEquations","addEquations","getBodies","sort","addEquation","removeEquation","ISLAND","48","destroy","equation","./Pool","49","50","IslandNodePool","IslandNode","../world/IslandNode","51","IslandPool","Island","../world/Island","52","OverlapKeeper","overlappingShapesLastState","overlappingShapesCurrentState","recordPool","OverlapKeeperRecordPool","tmpDict","tmpArray1","tick","current","keys","lastObject","getByKey","setOverlapping","getNewOverlaps","getDiff","getEndOverlaps","dictA","dictB","isNewOverlap","idA","idB","getNewBodyOverlaps","getBodyDiff","getEndBodyOverlaps","accumulator","./OverlapKeeperRecord","./OverlapKeeperRecordPool","./TupleDictionary","./Utils","53","OverlapKeeperRecord","54","record","55","objects","resize","object","56","getKey","dict","57","howmany","P2_ARRAY_TYPE","Float32Array","58","bodyIds","59","IslandManager","nodePool","islandPool","islands","nodes","queue","getUnvisitedNode","Nnodes","visited","visit","bds","Neqs","bfs","root","child","neighbors","split","ni","nj","./../utils/IslandNodePool","./../utils/IslandPool","./Island","./IslandNode","60","61","springs","disabledBodyCollisionPairs","solver","islandManager","gravity","frictionGravity","useWorldGravityAsFrictionGravity","useFrictionGravityOnZeroGravity","broadphase","constraints","defaultMaterial","defaultContactMaterial","lastTimeStep","applySpringForces","applyGravity","solveConstraints","contactMaterials","stepping","bodiesToBeRemoved","islandSplit","emitImpactEvent","_constraintIdCounter","_bodyIdCounter","postStepEvent","addBodyEvent","removeBodyEvent","addSpringEvent","spring","impactEvent","contactEquation","postBroadphaseEvent","pairs","sleepMode","NO_SLEEPING","beginContactEvent","endContactEvent","preSolveEvent","BODY_SLEEPING","ISLAND_SLEEPING","constraint","addContactMaterial","contactMaterial","removeContactMaterial","getContactMaterial","cmats","step_mg","xiw","xjw","step","timeSinceLastCalled","maxSubSteps","internalStep","substeps","endOverlaps","Nsprings","np","mg","gravityLen","ignoredPairs","Nconstraints","Nresults","runNarrowphase","ev","glen","aiw","ajw","reducedMass","resolver","numFrictionBefore","numFrictionEquations","addSpring","evt","removeSpring","getBodyById","disableBodyCollision","enableBodyCollision","cs","cms","hitTest_tmp1","hitTest_tmp2","hitTest","pb","ps","NS","setGlobalStiffness","setGlobalRelaxation","tmpAABB","../../package.json","../collision/Narrowphase","../collision/SAPBroadphase","../constraints/DistanceConstraint","../constraints/GearConstraint","../constraints/LockConstraint","../constraints/PrismaticConstraint","../constraints/RevoluteConstraint","../material/ContactMaterial","../material/Material","../objects/LinearSpring","../objects/RotationalSpring","../shapes/Capsule","../shapes/Line","../solver/GSSolver","../solver/Solver","../utils/OverlapKeeper","./IslandManager","_CreateEmptyTexture","gl","scaleMode","texture","createTexture","bindTexture","TEXTURE_2D","texParameteri","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","TEXTURE_MAG_FILTER","PIXI","scaleModes","LINEAR","NEAREST","TEXTURE_MIN_FILTER","texImage2D","RGBA","UNSIGNED_BYTE","_CreateFramebuffer","textureUnit","framebuffer","createFramebuffer","depthStencilBuffer","createRenderbuffer","colorBuffer","fbStatus","activeTexture","TEXTURE0","bindFramebuffer","FRAMEBUFFER","bindRenderbuffer","RENDERBUFFER","framebufferRenderbuffer","DEPTH_STENCIL_ATTACHMENT","renderBuffer","framebufferTexture2D","COLOR_ATTACHMENT0","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","error","_fbErrors","targetTexture","DisplayObject","pivot","rotation","alpha","visible","hitArea","renderable","parent","worldAlpha","worldTransform","Phaser","Matrix","worldScale","worldRotation","filterArea","_sr","_cr","_bounds","Rectangle","_currentBounds","_mask","_cacheAsBitmap","_cacheIsDirty","children","_destroyCachedSprite","updateTransform","game","tx","ty","pt","wt","PI2","rotationCache","determ","HALF_PI","transformCallback","transformCallbackContext","preUpdate","generateTexture","resolution","renderer","bounds","getLocalBounds","renderTexture","RenderTexture","_tempMatrix","render","updateCache","_generateCachedSprite","toGlobal","toLocal","applyInverse","_renderCachedSprite","renderSession","_cachedSprite","Sprite","_renderWebGL","_renderCanvas","baseTexture","_enableMultiTextureToggle","textureIndex","tempFilters","_filters","filters","anchor","displayObjectUpdateTransform","defineProperties","worldVisible","item","mask","isMask","passes","filterPasses","_filterBlock","blendMode","blendModes","MULTIPLY","NORMAL","cacheAsBitmap","DisplayObjectContainer","ignoreChildInput","addChild","addChildAt","removeChild","swapChildren","child2","index1","getChildIndex","index2","setChildIndex","currentIndex","getChildAt","removeChildAt","removeChildren","beginIndex","endIndex","range","removed","displayObjectContainerUpdateTransform","getBounds","targetCoordinateSpace","isTargetCoordinateSpaceDisplayObject","isTargetCoordinateSpaceThisOrParent","contains","matrixCache","identityMatrix","childBounds","childMaxX","childMaxY","minX","Infinity","minY","maxX","maxY","childVisible","w0","w1","h0","h1","x1","y1","x2","y2","x3","y3","x4","y4","targetCoordinateSpaceBounds","spriteBatch","flush","filterManager","pushFilter","maskManager","pushMask","popMask","popFilter","_width","_height","defaultAnchor","Texture","emptyTexture","tint","cachedTint","tintedTexture","shader","exists","hasLoaded","onTextureUpdate","frame","setTexture","destroyBase","skipRender","valid","matrix","crop","currentBlendMode","globalCompositeOperation","blendModesCanvas","globalAlpha","smoothProperty","trim","shakeX","shakeY","cw","ch","rotated","roundPixels","setTransform","requiresReTint","CanvasTinter","getTintedTexture","drawImage","source","initDefaultShaders","CompileVertexShader","shaderSrc","_CompileShader","VERTEX_SHADER","CompileFragmentShader","FRAGMENT_SHADER","shaderType","src","join","createShader","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","log","getShaderInfoLog","compileProgram","vertexSrc","fragmentSrc","fragmentShader","vertexShader","shaderProgram","createProgram","attachShader","linkProgram","getProgramParameter","LINK_STATUS","getProgramInfoLog","PixiShader","_UID","program","textureCount","firstRun","dirty","attributes","init","initMultitexShader","MAX_TEXTURES","getParameter","MAX_TEXTURE_IMAGE_UNITS","dynamicIfs","defaultVertexSrc","useProgram","uSamplerArray","getUniformLocation","projectionVector","offsetVector","dimensions","aVertexPosition","getAttribLocation","aTextureCoord","colorAttribute","aTextureIndex","indices","tempTexture","RGB","uniform1iv","uniforms","uniformLocation","initUniforms","initDefaultShader","uSampler","usingFilter","uniform","_init","initSampler2D","glMatrix","glValueLength","glFunc","uniformMatrix2fv","uniformMatrix3fv","uniformMatrix4fv","_glTextures","textureData","magFilter","minFilter","wrapS","wrapT","format","LUMINANCE","repeat","REPEAT","pixelStorei","UNPACK_FLIP_Y_WEBGL","flipY","border","uniform1i","syncUniforms","transpose","z","_dirty","instances","updateTexture","deleteProgram","PixiFastShader","uMatrix","aPositionCoord","aScale","aRotation","StripShader","translationMatrix","attribute","PrimitiveShader","tintColor","ComplexPrimitiveShader","color","glContexts","WebGLRenderer","config","defaultRenderer","extensions","WEBGL","transparent","autoResize","preserveDrawingBuffer","clearBeforeRender","view","canvas","_contextOptions","antialias","failIfMajorPerformanceCaveat","premultipliedAlpha","stencil","projection","shaderManager","WebGLShaderManager","WebGLSpriteBatch","WebGLMaskManager","WebGLFilterManager","stencilManager","WebGLStencilManager","blendModeManager","WebGLBlendModeManager","currentBatchedTextures","drawCount","maxTextureAvailableSpace","initContext","mapBlendModes","getContext","maxTextures","maxTextureSize","MAX_TEXTURE_SIZE","glContextId","disable","DEPTH_TEST","CULL_FACE","enable","BLEND","setContext","compression","etc1","getExtension","pvrtc","s3tc","ETC1","PVRTC","S3TC","setTexturePriority","textureNameCollection","clampPot","potSize","imageCache","cache","_cache","image","imageName","base","stage","contextLost","viewport","clearColor","_bgColor","COLOR_BUFFER_BIT","camera","_shake","renderDisplayObject","displayObject","buffer","setBlendMode","begin","style","updateCompressedTexture","textureMetaData","compressedTexImage2D","glExtensionFormat","mipmap","isPowerOfTwo","LINEAR_MIPMAP_LINEAR","NEAREST_MIPMAP_NEAREST","generateMipmap","_powerOf2","compressionAlgorithm","UNPACK_PREMULTIPLY_ALPHA_WEBGL","CanvasPool","remove","blendModesWebGL","modes","ONE","ONE_MINUS_SRC_ALPHA","ADD","SRC_ALPHA","DST_ALPHA","DST_COLOR","SCREEN","OVERLAY","DARKEN","LIGHTEN","COLOR_DODGE","COLOR_BURN","HARD_LIGHT","SOFT_LIGHT","DIFFERENCE","EXCLUSION","HUE","SATURATION","COLOR","LUMINOSITY","getMaxTextureUnit","enableMultiTexture","textureArray","blendModeWebGL","blendFunc","maskData","WebGLGraphics","updateGraphics","_webGL","pushStencil","popStencil","stencilStack","count","graphics","webGLData","bindGraphics","STENCIL_TEST","STENCIL_BUFFER_BIT","colorMask","stencilFunc","ALWAYS","stencilOp","KEEP","INVERT","drawElements","TRIANGLE_FAN","UNSIGNED_SHORT","EQUAL","DECR","INCR","TRIANGLE_STRIP","_currentGraphics","complexPrimitiveShader","setShader","uniform1f","toArray","uniform2f","uniform3fv","Color","hexToRGBArray","bindBuffer","ARRAY_BUFFER","vertexAttribPointer","FLOAT","ELEMENT_ARRAY_BUFFER","indexBuffer","primitiveShader","maxAttibs","attribState","tempAttribState","stack","defaultShader","fastShader","stripShader","creatureShader","CreatureShader","setAttribs","attribs","attribId","enableVertexAttribArray","disableVertexAttribArray","_currentId","currentShader","vertSize","vertexSize","numVerts","numIndices","ArrayBuffer","positions","colors","Uint32Array","Uint16Array","lastIndexCount","drawing","currentBatchSize","currentBaseTexture","textures","shaders","sprites","Filter","vertexBuffer","createBuffer","bufferData","STATIC_DRAW","DYNAMIC_DRAW","sprite","uvs","_uvs","aX","aY","a0","b0","c0","d0","_w1","_w0","_updateUvsInverted","x0","y0","renderTilingSprite","tilingTexture","TextureUvs","tilePosition","tileScaleOffset","offsetX","offsetY","scaleX","tileScale","scaleY","stride","bufferSubData","subarray","nextTexture","nextBlendMode","nextShader","batchSize","blendSwap","shaderSwap","skip","renderBatch","startIndex","TRIANGLES","deleteBuffer","WebGLFastSpriteBatch","maxSize","renderSprite","filterStack","texturePool","initShaderBuffers","filterBlock","_filterArea","_previous_stencil_mgr","filter","FilterTexture","padding","frameBuffer","_glFilterTexture","vertexArray","uvBuffer","uvArray","inputTexture","outputTexture","filterPass","applyFilterPass","sizeX","sizeY","currentFilter","colorArray","36054","36055","36057","36061","DEFAULT","renderbufferStorage","DEPTH_STENCIL","deleteFramebuffer","deleteTexture","CanvasBuffer","clearRect","CanvasMaskManager","save","cacheAlpha","transform","CanvasGraphics","renderGraphicsMask","clip","restore","tintMethod","tintWithMultiply","fillStyle","toString","substr","fillRect","tintWithPerPixel","rgbValues","pixelData","getImageData","pixels","canHandleAlpha","putImageData","CanvasRenderer","CANVAS","refresh","Canvas","getSmoothingPrefix","navigator","isCocoonJS","screencanvas","rgba","removeView","useNew","device","canUseMultiply","BaseTexture","complete","naturalWidth","naturalHeight","forceLoaded","removeByCanvas","unloadFromGPU","glTexture","fromCanvas","TextureSilentFail","noFrame","isTiling","requiresUpdate","setFrame","onBaseTextureLoaded","_updateUvs","tw","th","define","amd","WheelEventProxy","scaleFactor","deltaMode","_scaleFactor","_deltaMode","originalEvent","VERSION","GAMES","AUTO","HEADLESS","WEBGL_MULTI","NONE","LEFT","RIGHT","UP","DOWN","SPRITE","BUTTON","IMAGE","GRAPHICS","TEXT","TILESPRITE","BITMAPTEXT","GROUP","RENDERTEXTURE","TILEMAP","TILEMAPLAYER","EMITTER","POLYGON","BITMAPDATA","CANVAS_FILTER","WEBGL_FILTER","ELLIPSE","SPRITEBATCH","RETROFONT","POINTER","ROPE","RECTANGLE","MATRIX","POINT","ROUNDEDRECTANGLE","CREATURE","VIDEO","PENDING_ATLAS","HORIZONTAL","VERTICAL","LANDSCAPE","PORTRAIT","ANGLE_UP","ANGLE_DOWN","ANGLE_LEFT","ANGLE_RIGHT","ANGLE_NORTH_EAST","ANGLE_NORTH_WEST","ANGLE_SOUTH_EAST","ANGLE_SOUTH_WEST","TOP_LEFT","TOP_CENTER","TOP_RIGHT","LEFT_TOP","LEFT_CENTER","LEFT_BOTTOM","CENTER","RIGHT_TOP","RIGHT_CENTER","RIGHT_BOTTOM","BOTTOM_LEFT","BOTTOM_CENTER","BOTTOM_RIGHT","trunc","Function","bind","thisArg","bound","args","boundArgs","concat","TypeError","F","proto","arg","forEach","fun","CheapArray","assert","assign","varArgs","hasOwn","hasOwnProperty","nextSource","nextKey","reverseString","string","getProperty","obj","parts","_getProperty","setProperties","props","setProperty","_setProperty","val","currentObj","chanceRoll","chance","random","randomChoice","choice1","choice2","parseDimension","dimension","parseInt","innerWidth","innerHeight","pad","dir","padlen","isPlainObject","nodeType","copyIsArray","deep","mixinPrototype","mixin","replace","mixinKeys","childNodes","cloneNode","diameter","_diameter","_radius","circumference","setTo","copyFrom","copyTo","dest","round","output","circumferencePoint","asDegrees","sample","steps","startAngle","endAngle","linear","offsetPoint","top","bottom","equals","intersects","degToRad","intersectsRectangle","halfWidth","halfHeight","xCornerDist","yCornerDist","intersectsLine","returnPoints","del","p0Exists","pointOnSegment","p1Exists","Ellipse","normx","normy","fromPoints","fromSprite","startSprite","endSprite","useCenter","centerX","centerY","fromAngle","rotateAround","line","asSegment","intersectsPoints","midPoint","centerOn","pointOnLine","fuzzyEqual","xMin","xMax","yMin","yMax","coordinatesOnLine","stepRate","results","sx","sy","err","e2","wrap","uc","ua","ub","empty","bx1","by1","bx2","by2","intersectionWithRectangle","edgeIntersection","closestDistance","normalAngle","fromArray","newPos","translate","tx1","identity","invert","setToPolar","azimuth","clampX","clamp","clampY","equalsXY","fuzzyEquals","fuzzyEqualsXY","angleXY","atan2","radToDeg","atan","getMagnitude","getMagnitudeSq","setMagnitude","magnitude","isZero","limit","expand","perp","rperp","normalRightHand","negative","multiplyAdd","interpolate","project","amt","projectUnit","pointslength","parse","xProp","yProp","isPoint","sortClockwise","center","_points","closed","flattened","toNumberArray","flatten","inside","ix","iy","jx","jy","calculateArea","avgHeight","floorAll","ceilAll","copyFromBounds","inflate","containsRect","intersection","intersectsRaw","union","randomX","randomY","getPoint","sides","inflatePoint","createFromBounds","containsRaw","rx","ry","rw","rh","volume","sameDimensions","NEGATIVE_INFINITY","POSITIVE_INFINITY","EmptyRectangle","RoundedRectangle","Camera","deadzone","roundPx","atLimit","totalInView","onShakeComplete","Signal","onFlashComplete","onFadeComplete","fx","_targetPosition","_edge","_position","intensity","duration","horizontal","vertical","shakeBounds","_fxDuration","_fxType","_fixedView","FOLLOW_LOCKON","FOLLOW_PLATFORMER","FOLLOW_TOPDOWN","FOLLOW_TOPDOWN_TIGHT","SHAKE_BOTH","SHAKE_HORIZONTAL","SHAKE_VERTICAL","ENABLE_FX","boot","Graphics","follow","lerpX","lerpY","helper","unfollow","focusOn","setPosition","focusOnXY","shake","flash","beginFill","drawRect","endFill","fade","updateFX","updateShake","checkBounds","elapsedMS","dispatch","rnd","frac","updateTarget","math","setBoundsToWorld","vx","vw","vy","vh","setSize","resetFX","State","make","input","load","sound","state","tweens","particles","physics","preload","loadUpdate","loadRender","preRender","paused","resumed","pauseUpdate","shutdown","StateManager","pendingState","states","_pendingState","_clearWorld","_clearCache","_created","_args","onStateChange","onInitCallback","onPreloadCallback","onCreateCallback","onUpdateCallback","onRenderCallback","onResizeCallback","onPreRenderCallback","onLoadUpdateCallback","onLoadRenderCallback","onPausedCallback","onResumedCallback","onPauseUpdateCallback","onShutDownCallback","onPause","pause","onResume","resume","autoStart","newState","isBooted","callbackContext","clearWorld","clearCache","checkState","restart","dummy","previousStateKey","clearCurrentState","setCurrentState","totalQueuedFiles","totalQueuedPacks","loadComplete","removeAll","debug","link","unlink","_kickstart","getCurrentState","elapsedTime","renderType","_bindings","_prevParams","memorize","_shouldPropagate","active","_boundDispatch","validateListener","fnName","_registerListener","isOnce","listenerContext","priority","binding","prevIndex","_indexOfListener","SignalBinding","_addBinding","execute","_priority","cur","_listener","addOnce","_destroy","getNumListeners","halt","bindings","paramsArr","forget","dispose","_this","signal","_isOnce","_signal","callCount","params","handlerReturn","detach","isBound","getListener","getSignal","prevPoint","Date","mouse","date","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","sampleRate","iChannel0","iChannel1","iChannel2","iChannel3","setResolution","pointer","toFixed","totalElapsedSeconds","anchorX","anchorY","Cache","Plugin","hasPreUpdate","hasUpdate","hasPostUpdate","hasRender","hasPostRender","postRender","PluginManager","plugins","_len","_i","plugin","postUpdate","Stage","disableVisibilityChange","currentRenderOrderID","_hiddenVar","_onChange","parseConfig","setBackgroundColor","DOM","getOffset","setUserSelect","setTouchAction","checkVisibility","document","hidden","webkitHidden","mozHidden","msHidden","visibilityChange","_onClick","hasFocus","addEventListener","onblur","onfocus","onpagehide","onpageshow","cocoonJSApp","CocoonJS","App","onSuspended","onActivated","focusLoss","focusGain","gamePaused","gameResumed","valueToColor","updateColor","removeEventListener","silent","hash","removeFromHash","Group","addToStage","enableBody","physicsBodyType","Physics","ARCADE","physicsType","alive","ignoreDestroy","pendingDestroy","classType","cursor","inputEnableChildren","updateOnlyExistingChildren","onChildInputDown","onChildInputUp","onChildInputOver","onChildInputOut","enableBodyDebug","physicsSortDirection","onDestroy","cursorIndex","fixedToCamera","cameraOffset","_sortProperty","RETURN_NONE","RETURN_TOTAL","RETURN_CHILD","RETURN_ALL","SORT_ASCENDING","SORT_DESCENDING","updateZ","addToHash","inputEnabled","events","onAddedToGroup$dispatch","addAt","addMultiple","moveAll","getAt","createMultiple","quantity","singleKey","singleFrame","align","cellWidth","cellHeight","alignIn","resetCursor","next","previous","swap","child1","bringToTop","getIndex","sendToBack","moveUp","moveDown","xy","getByName","oldChild","newChild","hasProperty","operation","checkProperty","checkAlive","checkVisible","setAll","setAllChildren","checkAll","checkAny","addAll","property","amount","subAll","multiplyAll","divideAll","kill","killAll","callAllExists","revive","reviveAll","resetAll","checkExists","resetChild","existsValue","callbackFromArray","callAll","method","methodLength","contextLength","renderOrderID","predicate","ArraySet","forEachExists","iterate","forEachAlive","forEachDead","order","ascendingSortHandler","descendingSortHandler","customSort","sortHandler","returnType","total","getFirst","getFirstExists","createIfNull","getFirstAlive","getFirstDead","loadTexture","getTop","getBottom","getClosestTo","tempDistance","getFurthestFrom","countLiving","countDead","getRandom","ArrayUtils","getRandomItem","getRandomExists","list","getAll","pick","destroyPhase","onRemovedFromGroup$dispatch","group","destroyTexture","removeBetween","scatter","shuffle","destroyChildren","soft","_definedSize","stateChange","setBounds","useBounds","wrapAll","between","Game","physicsConfig","multiTexture","isRunning","raf","net","Device","lockRender","pendingStep","stepCount","onBlur","onFocus","_paused","_codePaused","currentUpdateID","updatesThisFrame","rendersThisFrame","_deltaTime","_lastCount","_spiraling","fpsProblemNotifier","forceSingleUpdate","forceSingleRender","dropFrames","_nextFpsNotification","enableDebug","RandomDataGenerator","now","whenReady","seed","ScaleManager","setUpRenderer","GameObjectFactory","GameObjectCreator","Loader","Time","TweenManager","Input","SoundManager","Particles","Create","Net","Debug","isDisabled","showDebugHeader","RequestAnimationFrame","stopFocus","focus","isReady","onReady","hideBanner","webAudio","ie","setImageRenderingCrisp","webGL","contextRestored","webGLRendererError","cocoonJS","smoothed","addToDOM","preventDefault","clearGLTextures","updateLogic","desiredFpsMult","updateRender","slowMotion","desiredFps","slowStep","elapsed","countUpdate","countRender","enableStep","disableStep","removeFromDOM","muteOnPause","setMute","cordova","iOS","unsetMute","hitCanvas","hitContext","moveCallbacks","customCandidateHandler","customCandidateHandlerContext","pollRate","multiInputOverride","MOUSE_TOUCH_COMBINE","maxPointers","tapRate","doubleTapRate","holdRate","justPressedRate","justReleasedRate","recordPointerHistory","recordRate","recordLimit","touchLockCallbacks","pointer1","pointer2","pointer3","pointer4","pointer5","pointer6","pointer7","pointer8","pointer9","pointer10","pointers","activePointer","mousePointer","keyboard","touch","mspointer","gamepad","resetLocked","onDown","onUp","onTap","onHold","minPriorityID","interactiveItems","_localPoint","_pollCounter","_oldPosition","_x","_y","MOUSE_OVERRIDES_TOUCH","TOUCH_OVERRIDES_MOUSE","MAX_POINTERS","Pointer","PointerMode","CURSOR","addPointer","Mouse","Touch","MSPointer","Keyboard","Gamepad","_onClickTrampoline","onClickTrampoline","setInteractiveCandidateHandler","addMoveCallback","addTouchLockCallback","onEnd","removeTouchLockCallback","executeTouchLockCallbacks","cb","deleteMoveCallback","CONTACT","hard","resetSpeed","startPointer","countActivePointers","updatePointer","identifier","move","stopPointer","getPointer","isActive","getPointerFromIdentifier","getPointerFromId","pointerId","getLocalPosition","Creature","TileSprite","graphicsData","fill","processClickTrampolines","mouseDownCallback","mouseUpCallback","mouseOutCallback","mouseOverCallback","mouseWheelCallback","capture","button","wheelDelta","locked","stopOnGameOut","pointerLock","_onMouseDown","_onMouseMove","_onMouseUp","_onMouseOut","_onMouseOver","_onMouseWheel","_wheelEvent","NO_BUTTON","LEFT_BUTTON","MIDDLE_BUTTON","RIGHT_BUTTON","BACK_BUTTON","FORWARD_BUTTON","WHEEL_UP","WHEEL_DOWN","android","chrome","onMouseDown","onMouseMove","onMouseUp","_onMouseUpGlobal","onMouseUpGlobal","_onMouseOutGlobal","onMouseOutGlobal","onMouseOut","onMouseOver","onMouseWheel","wheelEvent","mouseMoveCallback","withinGame","resetButtons","bindEvent","deltaY","requestPointerLock","element","mozRequestPointerLock","webkitRequestPointerLock","_pointerLockChange","pointerLockChange","pointerLockElement","mozPointerLockElement","webkitPointerLockElement","releasePointerLock","exitPointerLock","mozExitPointerLock","webkitExitPointerLock","_stubsGenerated","prop","makeBinder","detail","deltaX","wheelDeltaX","deltaZ","pointerDownCallback","pointerMoveCallback","pointerUpCallback","_onMSPointerDown","_onMSPointerMove","_onMSPointerUp","_onMSPointerUpGlobal","_onMSPointerOut","_onMSPointerOver","onPointerDown","onPointerMove","onPointerUp","onPointerUpGlobal","onPointerOut","onPointerOver","pointerType","DeviceButton","buttonCode","isDown","isUp","timeDown","timeUp","repeats","altKey","shiftKey","ctrlKey","onFloat","startStop","condition","padFloat","justPressed","justReleased","pointerMode","leftButton","middleButton","rightButton","backButton","forwardButton","eraserButton","ERASER_BUTTON","_holdSent","_history","_nextDrop","_stateReset","clientX","clientY","pageX","pageY","screenX","screenY","rawMovementX","rawMovementY","movementX","movementY","isMouse","previousTapTime","totalTouches","msSinceLastClick","targetObject","interactiveCandidates","positionDown","positionUp","_clickTrampolines","_trampolineTargetObject","processButtonsDown","processButtonsUp","processButtonsUpDown","buttons","down","toLowerCase","updateButtons","totalActivePointers","_touchedHandler","processInteractiveObjects","shift","fromClick","pollLocked","mozMovementX","webkitMovementX","mozMovementY","webkitMovementY","noPause","isDragged","highestRenderOrderID","highestInputPriorityID","candidateTarget","currentNode","checked","validForInput","checkPointerDown","checkPointerOver","priorityID","swapTarget","newTarget","_pointerOutHandler","_pointerOverHandler","leave","currentPointers","addClickTrampoline","callbackArgs","trampolines","trampoline","_releasedHandler","resetMovement","touchStartCallback","touchMoveCallback","touchEndCallback","touchEnterCallback","touchLeaveCallback","touchCancelCallback","_onTouchStart","_onTouchMove","_onTouchEnd","_onTouchEnter","_onTouchLeave","_onTouchCancel","onTouchStart","onTouchMove","onTouchEnd","onTouchEnter","onTouchLeave","onTouchCancel","consumeDocumentTouches","_documentTouchMove","changedTouches","InputHandler","useHandCursor","_setHandCursor","allowHorizontalDrag","allowVerticalDrag","snapOffset","snapOnDrag","snapOnRelease","snapX","snapY","snapOffsetX","snapOffsetY","pixelPerfectOver","pixelPerfectClick","pixelPerfectAlpha","draggable","boundsRect","boundsSprite","scaleLayer","dragOffset","dragFromCenter","dragStopBlocksInputUp","dragStartPoint","dragDistanceThreshold","dragTimeThreshold","downPoint","snapPoint","_dragPoint","_dragPhase","_pendingDrag","_dragTimePass","_dragDistancePass","_wasEnabled","_tempPoint","_pointerData","camX","camY","isOver","isOut","timeOver","timeOut","downDuration","onAddedToGroup","addedToGroup","onRemovedFromGroup","removedFromGroup","highestID","highestRenderID","includePixelPerfect","isPixelPerfect","pointerX","pointerY","pointerDown","pointerUp","pointerTimeDown","pointerTimeUp","pointerOver","pointerOut","pointerTimeOver","pointerTimeOut","pointerDragged","fastTest","checkPixel","_dx","_dy","startDrag","_draggedPointerID","updateDrag","sendEvent","onInputOver$dispatch","onInputOut$dispatch","onInputDown$dispatch","dragTimeElapsed","onInputUp$dispatch","stopDrag","fromStart","pointerLocalCoord","globalToLocal","checkBoundsRect","checkBoundsSprite","onDragUpdate","justOver","delay","overDuration","justOut","enableDrag","lockCenter","pixelPerfect","alphaThreshold","disableDrag","boundsCenterLocalCoord","onDragStart$dispatch","globalToLocalX","grid","boundsFluid","scaleFluidInversed","globalToLocalY","globalCoord","onDragStop$dispatch","setDragLock","allowHorizontal","allowVertical","enableSnap","onDrag","onRelease","disableSnap","_gamepadIndexMap","_rawPads","_active","_gamepadSupportAvailable","webkitGetGamepads","webkitGamepads","userAgent","getGamepads","_prevRawGamepadTypes","_prevTimestamps","onConnectCallback","onDisconnectCallback","onDownCallback","onUpCallback","onAxisCallback","onFloatCallback","_ongamepadconnected","_gamepaddisconnected","_gamepads","SinglePad","addCallbacks","callbacks","onConnect","onDisconnect","onAxis","_onGamepadConnected","onGamepadConnected","_onGamepadDisconnected","onGamepadDisconnected","newPad","connect","removedPad","disconnect","_pollGamepads","pad1","pollStatus","pad2","pad3","pad4","rawGamepads","gamepadsChanged","_rawPad","singlePad","validConnections","rawIndices","padIndices","connected","rawPad","setDeadZones","deadZone","BUTTON_0","BUTTON_1","BUTTON_2","BUTTON_3","BUTTON_4","BUTTON_5","BUTTON_6","BUTTON_7","BUTTON_8","BUTTON_9","BUTTON_10","BUTTON_11","BUTTON_12","BUTTON_13","BUTTON_14","BUTTON_15","AXIS_0","AXIS_1","AXIS_2","AXIS_3","AXIS_4","AXIS_5","AXIS_6","AXIS_7","AXIS_8","AXIS_9","XBOX360_A","XBOX360_B","XBOX360_X","XBOX360_Y","XBOX360_LEFT_BUMPER","XBOX360_RIGHT_BUMPER","XBOX360_LEFT_TRIGGER","XBOX360_RIGHT_TRIGGER","XBOX360_BACK","XBOX360_START","XBOX360_STICK_LEFT_BUTTON","XBOX360_STICK_RIGHT_BUTTON","XBOX360_DPAD_LEFT","XBOX360_DPAD_RIGHT","XBOX360_DPAD_UP","XBOX360_DPAD_DOWN","XBOX360_STICK_LEFT_X","XBOX360_STICK_LEFT_Y","XBOX360_STICK_RIGHT_X","XBOX360_STICK_RIGHT_Y","PS3XC_X","PS3XC_CIRCLE","PS3XC_SQUARE","PS3XC_TRIANGLE","PS3XC_L1","PS3XC_R1","PS3XC_L2","PS3XC_R2","PS3XC_SELECT","PS3XC_START","PS3XC_STICK_LEFT_BUTTON","PS3XC_STICK_RIGHT_BUTTON","PS3XC_DPAD_UP","PS3XC_DPAD_DOWN","PS3XC_DPAD_LEFT","PS3XC_DPAD_RIGHT","PS3XC_STICK_LEFT_X","PS3XC_STICK_LEFT_Y","PS3XC_STICK_RIGHT_X","PS3XC_STICK_RIGHT_Y","padParent","_padParent","_prevTimestamp","_buttons","_buttonsLen","_axes","_axesLen","getButton","timestamp","rawButtonVal","isNaN","processButtonDown","processButtonUp","processButtonFloat","processAxisChange","triggerCallback","disconnectingIndex","axisCode","buttonValue","Key","keycode","_enabled","durationUp","keyCode","onHoldCallback","onHoldContext","_justDown","_justUp","processKeyDown","processKeyUp","upDuration","pressEvent","onPressCallback","_keys","_capture","_onKeyDown","_onKeyPress","_onKeyUp","_k","onPress","removeCallbacks","addKey","addKeyCapture","addKeys","removeKey","removeKeyCapture","createCursorKeys","up","KeyCode","processKeyPress","clearCaptures","String","fromCharCode","charCode","A","charCodeAt","C","D","E","H","J","K","L","M","O","P","Q","R","S","T","U","V","W","X","Y","Z","ZERO","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","NUMPAD_0","NUMPAD_1","NUMPAD_2","NUMPAD_3","NUMPAD_4","NUMPAD_5","NUMPAD_6","NUMPAD_7","NUMPAD_8","NUMPAD_9","NUMPAD_MULTIPLY","NUMPAD_ADD","NUMPAD_ENTER","NUMPAD_SUBTRACT","NUMPAD_DECIMAL","NUMPAD_DIVIDE","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","F13","F14","F15","COLON","EQUALS","COMMA","UNDERSCORE","PERIOD","QUESTION_MARK","TILDE","OPEN_BRACKET","BACKWARD_SLASH","CLOSED_BRACKET","QUOTES","BACKSPACE","TAB","CLEAR","ENTER","SHIFT","CONTROL","ALT","CAPS_LOCK","ESC","SPACEBAR","PAGE_UP","PAGE_DOWN","END","HOME","PLUS","MINUS","INSERT","DELETE","HELP","NUM_LOCK","match","Component","Angle","wrapAngle","Animation","play","frameRate","loop","killOnComplete","animations","AutoCull","autoCull","inCamera","checkWorldBounds","Bounds","container","alignTo","BringToTop","Core","skipTypeChecks","install","components","Events","PhysicsBody","AnimationManager","LoadTexture","FixedToCamera","previousRotation","preUpdateChildren","fresh","_exists","P2JS","customRender","Crop","cropRect","_crop","updateCrop","resetFrame","oldX","oldY","oldW","oldH","_frame","Delta","Destroy","onDestroy$dispatch","removeFrom","Video","onChangeSource","resizeFrame","BitmapText","_glyphs","_parent","_onDestroy","_onAddedToGroup","_onRemovedFromGroup","_onKilled","_onRevived","_onEnterBounds","_onOutOfBounds","_onInputOver","_onInputOut","_onInputDown","_onInputUp","_onDragStart","_onDragUpdate","_onDragStop","_onAnimationStart","_onAnimationComplete","_onAnimationLoop","onKilled","onRevived","onOutOfBounds","onEnterBounds","onInputOver","onInputOut","onInputDown","onInputUp","onDragStart","onDragStop","onAnimationStart","onAnimationComplete","onAnimationLoop","backing","_fixedToCamera","Health","health","maxHealth","damage","setHealth","heal","InCamera","InputEnabled","InWorld","outOfCameraBoundsKill","_outOfBoundsFired","onEnterBounds$dispatch","onOutOfBounds$dispatch","outOfBoundsKill","inWorld","LifeSpan","lifespan","physicsElapsedMS","onRevived$dispatch","onKilled$dispatch","stopAnimation","BitmapData","hasFrameData","loadFrameData","getFrameData","frameData","Tilemap","TilemapLayer","img","getImage","trimmed","spriteSourceSizeX","spriteSourceSizeY","sourceSizeW","sourceSizeH","refreshTexture","frameName","Overlap","_reset","Reset","ScaleMinMax","scaleMin","scaleMax","checkTransform","setScaleMinMax","Smoothed","existing","weapon","bulletClass","Weapon","createBullets","Image","creature","mesh","tween","physicsGroup","SpriteBatch","audio","audioSprite","addSprite","tileSprite","rope","Rope","text","Text","overFrame","outFrame","downFrame","upFrame","Button","emitter","maxParticles","Arcade","Emitter","retroFont","font","characterWidth","characterHeight","chars","charsPerRow","xSpacing","ySpacing","xOffset","yOffset","RetroFont","bitmapText","tilemap","tileWidth","tileHeight","addToCache","uuid","addRenderTexture","video","bitmapData","addBitmapData","Tween","preUpdatePhysics","preUpdateLifeSpan","preUpdateInWorld","preUpdateCore","_onOverFrame","_onOutFrame","_onDownFrame","_onUpFrame","onOverSound","onOutSound","onDownSound","onUpSound","onOverSoundMarker","onOutSoundMarker","onDownSoundMarker","onUpSoundMarker","onOverMouseOnly","justReleasedPreventsOver","freezeFrames","forceOut","setFrames","onInputOverHandler","onInputOutHandler","onInputDownHandler","onInputUpHandler","clearFrames","setStateFrame","switchImmediately","frameKey","changeStateFrame","setStateSound","marker","soundKey","markerKey","Sound","AudioSprite","playStateSound","setSounds","overSound","overMarker","downSound","downMarker","outSound","outMarker","upSound","upMarker","setOverSound","setOutSound","setDownSound","setUpSound","fastSpriteBatch","ready","isRotated","childTransform","skipPool","ctx","imageData","FrameData","textureFrame","addFrame","Frame","disableTextureUpload","cls","_image","_pos","_size","_scale","_rotate","_alpha","prev","_anchor","_tempR","_tempG","_tempB","_circle","_swapCanvas","moveH","moveV","draw","onload","addImage","toDataURL","processPixelRGB","pixel","createColor","unpackPixel","getPixel32","setPixel32","processPixel","replaceRGB","g1","g2","region","packPixel","setHSL","bHaveH","bHaveS","bHaveL","HSLtoRGB","shiftHSL","red","green","blue","immediate","LITTLE_ENDIAN","setPixel","getPixel","getPixelRGB","hsl","hsv","getPixels","getFirstPixel","scan","newWidth","newHeight","getCanvas","op","copyTransform","copyRect","drawGroup","drawGroupProxy","drawFull","renderGraphics","shadow","blur","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","alphaMask","sourceRect","maskRect","blendSourceAtop","blendReset","extract","destination","prevFont","fillText","beginPath","arc","closePath","moveTo","lineTo","lineWidth","strokeStyle","stroke","polygon","textureLine","createPattern","blendSourceOver","blendSourceIn","blendSourceOut","blendDestinationOver","blendDestinationIn","blendDestinationOut","blendDestinationAtop","blendXor","blendAdd","blendMultiply","blendScreen","blendOverlay","blendDarken","blendLighten","blendColorDodge","blendColorBurn","blendHardLight","blendSoftLight","blendDifference","blendExclusion","blendHue","blendSaturation","blendColor","blendLuminosity","copyBitmapData","destRowStart","getSmoothingEnabled","setSmoothingEnabled","getTransform","translateX","translateY","skewX","skewY","EarCut","holeIndices","dim","hasHoles","outerLen","outerNode","linkedList","eliminateHoles","earcutLinked","clockwise","insertNode","filterPoints","again","steiner","removeNode","ear","pass","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","minTX","minTY","maxTX","maxTY","minZ","zOrder","maxZ","nextZ","prevZ","locallyInside","isValidDiagonal","splitPolygon","getLeftmost","compareX","eliminateHole","hole","findHoleBridge","hx","hy","qx","tan","tanMin","sortLinked","q","tail","numMerges","pSize","qSize","inSize","leftmost","intersectsPolygon","middleInside","Node","an","bp","stencilBufferLimit","lastIndex","clearDirty","graphicsDataPool","switchMode","buildPoly","buildComplexPoly","buildLine","buildRectangle","buildCircle","buildRoundedRectangle","upload","WebGLGraphicsData","rectData","fillColor","fillAlpha","vertPos","tempPoints","rrectData","recPoints","quadraticBezierCurve","vecPos","fromX","fromY","cpX","cpY","toX","toY","getPt","n1","n2","perc","xa","ya","xb","yb","circleData","seg","totalSegs","firstPoint","lastPoint","midPointX","midPointY","unshift","p1x","p1y","p2x","p2y","p3x","p3y","perpx","perpy","perp2x","perp2y","perp3x","perp3y","indexCount","indexStart","lineColor","lineAlpha","glPoints","glIndicies","updateGraphicsTint","_fillTint","_lineTint","strokeRect","ox","oy","xe","ye","xm","ym","bezierCurveTo","maxRadius","quadraticCurveTo","tintR","tintG","tintB","GraphicsData","currentPath","boundsPadding","_localBounds","_boundsDirty","webGLDirty","cachedSpriteDirty","updateLocalBounds","drawTriangle","cull","triangle","cameraToFace","faceNormal","drawPolygon","drawTriangles","point1","point2","point3","lineStyle","drawShape","cpX2","cpY2","dt2","dt3","arcTo","mm","dd","cc","tt","k1","k2","j1","j2","qy","anticlockwise","segments","sweep","segs","startX","startY","filling","theta","theta2","cTheta","sTheta","segMinus","remainder","drawRoundedRect","drawCircle","drawEllipse","canvasBuffer","updateCachedSpriteTexture","_prevTint","tempPoint","cachedSprite","destroyCachedSprite","textureBuffer","tempMatrix","renderXY","renderRawXY","updateBase","realResolution","getBase64","webGLPixels","Uint8Array","readPixels","tempCanvas","canvasData","textBounds","strokeColors","fontStyles","fontWeights","autoRound","useAdvancedWrap","splitRegExp","characterLimitSize","characterLimitSuffix","_res","_text","_fontComponents","_lineSpacing","_charCount","setStyle","updateText","setShadow","shadowStroke","shadowFill","newStyle","backgroundColor","boundsAlignH","boundsAlignV","strokeThickness","wordWrap","wordWrapWidth","maxLines","tabs","fontToComponents","fontStyle","fontVariant","fontWeight","fontSize","componentsToFont","outputText","substring","runWordWrap","lines","lineWidths","maxLineWidth","fontProperties","determineFontProperties","drawnLines","measureLine","measureText","tab","section","snapToCeil","lineHeight","lineSpacing","textBaseline","lineCap","lineJoin","linePositionX","linePositionY","ascent","updateLine","updateShadow","strokeText","renderTabLine","snap","lineLength","letter","clearColors","clearFontValues","addColor","addStrokeColor","addFontStyle","addFontWeight","weight","precalculateWordWrap","advancedWordWrap","basicWordWrap","linesCount","currentLineWidth","words","word","wordWithSpace","wordWidth","newWord","secondPart","spaceLeft","wordWidthWithSpace","updateFont","family","exec","fontFamily","setText","parseList","setTextBounds","properties","fontPropertiesCache","fontPropertiesCanvas","fontPropertiesContext","baseline","descent","imagedata","setCharacterLimit","characterLimit","suffix","parseFloat","createElement","textWidth","textHeight","_prevAnchor","_maxWidth","_data","getBitmapFont","_font","_fontSize","_align","_tint","sourceWidth","sourceHeight","scanLine","lastSpace","wrappedWidth","prevCharCode","maxWidth","test","charAt","charData","kerning","xAdvance","cleanText","re","purgeGlyphs","kept","checkImageKey","characterSpacingX","characterSpacingY","characterPerRow","multiLine","autoUpperCase","customSpacingX","customSpacingY","fixedWidth","fontSet","grabData","currentX","currentY","updateFrameData","stamp","ALIGN_LEFT","ALIGN_RIGHT","ALIGN_CENTER","TEXT_SET1","TEXT_SET2","TEXT_SET3","TEXT_SET4","TEXT_SET5","TEXT_SET6","TEXT_SET7","TEXT_SET8","TEXT_SET9","TEXT_SET10","TEXT_SET11","setFixedWidth","lineAlignment","content","characterSpacing","allowLowerCase","buildRetroFontText","getLongestLine","pasteLine","longestLine","removeUnsupportedCharacters","stripCR","newString","aChar","code","updateOffset","diffX","diffY","frames","getFrames","newText","toUpperCase","_hasUpdateAnimation","_updateAnimationCallback","canvasPadding","drawMode","updateAnimation","nextPoint","perpLength","_vertexBuffer","_initWebGL","_renderStrip","_indexBuffer","_uvBuffer","_colorBuffer","_renderCanvasTriangleStrip","_renderCanvasTriangles","_renderCanvasDrawTriangle","index0","textureSource","textureWidth","textureHeight","u0","v2","paddingX","paddingY","normX","normY","deltaA","deltaB","deltaC","deltaD","deltaE","deltaF","renderStripFlat","strip","rawX","rawY","_updateAnimation","difference","_scroll","textureDebug","tilePattern","frameWidth","frameHeight","physicsElapsed","autoScroll","stopScroll","generateTilingTexture","restartBatch","sessionBlendMode","forcePowerOfTwo","targetWidth","targetHeight","getNextPowerOfTwo","pool","getTotal","getFree","deviceReadyAt","initialized","desktop","iOSVersion","nodeWebkit","electron","ejecta","crosswalk","chromeOS","linux","macOS","windows","windowsPhone","canvasBitBltShift","file","fileSystem","localStorage","worker","css3D","typedArray","vibration","getUserMedia","quirksMode","arora","chromeVersion","epiphany","firefox","firefoxVersion","ieVersion","trident","tridentVersion","mobileSafari","midori","opera","safari","safariVersion","webApp","silk","audioData","ogg","opus","mp3","wav","m4a","webm","dolby","oggVideo","h264Video","mp4Video","webmVideo","vp9Video","hlsVideo","iPhone","iPhone4","iPad","pixelRatio","littleEndian","support32bit","fullscreen","requestFullscreen","cancelFullscreen","fullscreenKeyboard","onInitialized","nonPrimer","readyCheck","_readyCheck","_monitor","_queue","readyState","setTimeout","_initialize","_checkIsLittleEndian","_checkIsUint8ClampedImageData","Uint8ClampedArray","createImageData","vita","kindle","RegExp","$1","_checkOS","$3","process","versions","_checkBrowser","audioElement","canPlayType","major","minor","$2","_checkAudio","videoElement","_checkVideo","has3d","el","transforms","webkitTransform","OTransform","msTransform","MozTransform","insertBefore","getComputedStyle","getPropertyValue","_checkCSS3D","Int8Array","Int32Array","vibrate","webkitVibrate","mozVibrate","msVibrate","getItem","WebGLRenderingContext","compatMode","webkitGetUserMedia","mozGetUserMedia","msGetUserMedia","oGetUserMedia","URL","webkitURL","mozURL","msURL","_checkFeatures","s1","s2","_checkCanvasFeatures","fs","cfs","Element","_checkFullScreenSupport","documentElement","maxTouchPoints","PointerEvent","MSPointerEvent","msPointerEnabled","pointerEnabled","canPlayAudio","canPlayVideo","needsTouchUnlock","PhaserGlobal","fakeiOSTouchLock","isAndroidStockBrowser","matches","display","msTouchAction","overflowHidden","getElementById","overflow","appendChild","parentNode","vendor","prefix","types","msInterpolationMode","setImageRenderingBicubic","forceSetTimeOut","vendors","requestAnimationFrame","cancelAnimationFrame","_isSetTimeOut","_onLoop","_timeOutID","updateSetTimeout","updateRAF","rafTime","timeToCall","clearTimeout","isSetTimeOut","isRAF","DEG_TO_RAD","RAD_TO_DEG","degrees","radians","fuzzyLessThan","fuzzyGreaterThan","fuzzyCeil","fuzzyFloor","average","shear","snapTo","gap","snapToFloor","roundTo","place","floorTo","ceilTo","rotateToAngle","currentAngle","targetAngle","getShortestAngle","angleBetween","angleBetweenY","angleBetweenPoints","angleBetweenPointsY","reverseAngle","angleRad","normalizeAngle","maxAdd","minSub","wrapValue","isOdd","isEven","minProperty","maxProperty","linearInterpolation","bezierInterpolation","bernstein","catmullRomInterpolation","catmullRom","factorial","res","roundAwayFromZero","sinCosGenerator","sinAmplitude","cosAmplitude","frequency","frq","cosTable","sinTable","hypot","distanceSq","distancePow","clampBottom","within","mapLinear","smoothstep","smootherstep","sign","percent","seeds","s0","sow","integer","real","integerInRange","realInRange","ary","weightedPick","QuadTree","maxObjects","maxLevels","_empty","subWidth","subHeight","populate","populateHandler","insert","retrieve","returnObjects","getHostName","location","hostname","checkDomainName","domain","updateQueryString","redirect","href","separator","getQueryString","parameter","keyValues","search","decodeURI","decodeURIComponent","frameBased","_tweens","_add","easeMap","Power0","Easing","Power1","Power2","Power3","Power4","Linear","None","Quad","Quadratic","Out","Cubic","Quart","Quartic","Quint","Quintic","Sine","Sinusoidal","Expo","Exponential","Circ","Circular","Elastic","Back","Bounce","Quad.easeIn","In","Cubic.easeIn","Quart.easeIn","Quint.easeIn","Sine.easeIn","Expo.easeIn","Circ.easeIn","Elastic.easeIn","Back.easeIn","Bounce.easeIn","Quad.easeOut","Cubic.easeOut","Quart.easeOut","Quint.easeOut","Sine.easeOut","Expo.easeOut","Circ.easeOut","Elastic.easeOut","Back.easeOut","Bounce.easeOut","Quad.easeInOut","InOut","Cubic.easeInOut","Quart.easeInOut","Quint.easeInOut","Sine.easeInOut","Expo.easeInOut","Circ.easeInOut","Elastic.easeInOut","Back.easeInOut","Bounce.easeInOut","_pauseAll","_resumeAll","pendingDelete","_manager","addTweens","numTweens","isTweening","checkIsRunning","some","_pause","_resume","pauseAll","resumeAll","manager","timeline","timeScale","repeatCounter","onStart","onLoop","onRepeat","onChildComplete","onComplete","chainedTween","isPaused","_onUpdateCallback","_onUpdateCallbackContext","_pausedTime","_hasStarted","ease","yoyo","Default","TweenData","vEnd","loadValues","updateTweenData","repeatDelay","yoyoDelay","easing","interpolation","repeatAll","chain","startTime","status","PENDING","RUNNING","LOOPED","COMPLETE","generateData","vStart","vStartCache","vEndCache","repeatTotal","inReverse","easingFunction","interpolationFunction","interpolationContext","isFrom","ms","fps","blob","reversed","asin","prevTime","_desiredFps","suggestedFps","advancedTiming","updates","renders","ups","rps","fpsMin","fpsMax","msMin","msMax","pauseDuration","timeExpected","Timer","_frameCount","_elapsedAccumulator","_started","_timeLastSecond","_pauseStarted","_justResumed","_timers","timer","autoDestroy","previousDateNow","updateAdvancedTiming","updateTimers","interval","elapsedSince","since","elapsedSecondsSince","running","expired","nextTick","timeCap","_pauseTotal","_now","_marked","_diff","_newTick","MINUTE","SECOND","HALF","QUARTER","repeatCount","TimerEvent","clearEvents","clearPendingEvents","adjustEvents","baseTime","currentFrame","currentAnim","updateIfVisible","isLoaded","_frameData","_anims","_outputFrames","anim","copyFrameData","useNumericIndex","getFrameIndexes","validateFrames","checkFrameName","isPlaying","getAnimation","refreshFrame","gotFrame","getFrame","getFrameByName","_frameIndex","_frames","loopCount","isFinished","_pauseStartTime","_frameDiff","_frameSkip","onUpdate","isReversed","_timeLastFrame","_timeNextFrame","updateCurrentFrame","onAnimationStart$dispatch","reverseOnce","frameId","useLocalFrameIndex","frameIndex","directionalOffset","dispatchComplete","onAnimationComplete$dispatch","onAnimationLoop$dispatch","signalUpdate","fromPlay","generateFrameNames","zeroPad","spriteSourceSizeW","spriteSourceSizeH","setTrim","actualWidth","actualHeight","destX","destY","destWidth","destHeight","getRect","_frameNames","getFrameRange","AnimationParser","spriteSheet","frameMax","margin","spacing","skipFrames","JSONData","json","newFrame","filename","sourceSize","spriteSourceSize","JSONDataPyxel","tileheight","tilewidth","JSONDataHash","XMLData","xml","getElementsByTagName","frameX","frameY","autoResolveURL","binary","bitmapFont","compressedTexture","_urlMap","_urlResolver","_urlTemp","onSoundUnlock","_cacheMap","TEXTURE","SOUND","PHYSICS","BINARY","BITMAPFONT","JSON","XML","SHADER","RENDER_TEXTURE","_pendingCount","_addImages","DEFAULT_KEY","DEFAULT_SRC","MISSING","MISSING_KEY","MISSING_SRC","READY_TIMEOUT","addCompressedTextureMetaData","extension","arrayBuffer","removeImage","LoaderParser","fileFormat","_resolveURL","addCanvas","addImageAsync","_removePending","_addPending","addDefaultImage","addMissingImage","addSound","audioTag","decoded","isDecoding","touchLocked","addText","addPhysicsData","addTilemap","mapData","addBinary","binaryData","addBitmapFont","atlasData","atlasType","jsonBitmapFont","xmlBitmapFont","addBitmapFontFromAtlas","atlasKey","atlasFrame","dataKey","dataType","getBaseTexture","fontData","getJSON","getXML","addJSON","addXML","addVideo","isBlob","addShader","addSpriteSheet","addTextureAtlas","TEXTURE_ATLAS_XML_STARLING","TEXTURE_ATLAS_JSON_PYXEL","reloadSound","getSound","reloadSoundComplete","updateSound","decodedSound","isSoundDecoded","isSoundReady","checkKey","checkURL","checkCanvasKey","checkTextureKey","checkSoundKey","checkTextKey","checkPhysicsKey","checkTilemapKey","checkBinaryKey","checkBitmapDataKey","checkBitmapFontKey","checkJSONKey","checkXMLKey","checkVideoKey","checkShaderKey","checkRenderTextureKey","full","getTextureFrame","getSoundData","getText","getPhysicsData","fixtureKey","fixtures","fixture","getTilemapData","getBinary","getBitmapData","getVideo","getShader","getRenderTexture","getFrameCount","getFrameByIndex","getURL","getKeys","removeCanvas","destroyBaseTexture","removeSound","removeText","removePhysics","removeTilemap","removeBinary","removeBitmapData","removeBitmapFont","removeJSON","removeXML","removeVideo","removeShader","removeRenderTexture","removeSpriteSheet","removeTextureAtlas","baseURL","destroyItem","readyTimeout","_ready","_checkReady","isLoading","preloadSprite","crossOrigin","headers","requestedWith","onLoadStart","onLoadComplete","onPackComplete","onFileStart","onFileComplete","onFileError","enableParallel","maxParallelDownloads","_withSyncPointDepth","_fileList","_flightQueue","_processingHead","_fileLoadStarted","_totalPackCount","_totalFileCount","_loadedPackCount","_loadedFileCount","TEXTURE_ATLAS_JSON_ARRAY","TEXTURE_ATLAS_JSON_HASH","PHYSICS_LIME_CORONA_JSON","PHYSICS_PHASER_JSON","setPreloadSprite","checkKeyExists","getAssetIndex","bestFound","loaded","loading","getAsset","fileIndex","addToFileList","overwrite","syncPoint","currentFile","replaceInFileList","pack","imageFromBitmapData","imageFromGrid","imageFromTexture","pixelWidth","pixelHeight","palette","exkey","images","urls","script","spritesheet","autoDecode","noAudio","jsonURL","jsonData","audiosprite","loadEvent","asBlob","CSV","TILED_JSON","LIME_CORONA_JSON","textureURL","atlasURL","parseXml","atlasJSONArray","atlas","atlasJSONHash","atlasXML","withSyncPoint","addSyncPoint","asset","removeFile","updateProgress","processLoadQueue","finishedLoading","requestUrl","requestObject","progress","syncblock","inflightLimit","processPack","loadFile","abnormal","asyncComplete","errorMessage","packData","transformUrl","xhrLoad","fileComplete","loadImageTag","getAudioURL","usingWebAudio","usingAudioTag","loadAudioTag","fileError","getVideoURL","loadVideoTag","jsonLoadComplete","xmlLoadComplete","csvLoadComplete","onerror","controls","autoplay","videoLoadEvent","canplay","Audio","playThroughEvent","xhr","XMLHttpRequest","open","responseType","setRequestHeader","message","send","videoType","uri","lastIndexOf","audioType","reason","loadNext","responseText","response","decode","language","defer","head","contentType","domparser","DOMParser","parseFromString","ActiveXObject","async","loadXML","totalLoadedFiles","totalLoadedPacks","progressFloat","info","common","getAttribute","letters","kernings","second","finalizeBitmapFont","_face","_lineHeight","_id","_xoffset","_yoffset","_xadvance","_second","_first","_amount","bitmapFontData","pvr","uintArray","byteArray","pvrHeader","pixelFormat","flags","colorSpace","channelType","depth","numberOfSurfaces","numberOfFaces","numberOfMipmaps","metaDataSize","byteLength","dds","ddsHeader","pitch","mipmapCount","formatSize","formatFlag","formatFourCC","formatBitCount","formatRBitMask","formatGBitMask","formatBBitMask","formatABitMask","caps1","caps2","caps3","caps4","reserved2","DXGIFormat","resourceDimension","miscFlag","arraySize","ktx","ktxHeader","imageSizeOffset","imageSize","glInternalFormat","endianness","glType","glTypeSize","glFormat","glBaseInternalFormat","pixelDepth","numberOfArrayElements","numberOfMipmapLevels","bytesOfKeyValueData","keyAndValueByteSize","pkm","pkmHeader","originalWidth","originalHeight","autoplayKey","sounds","spritemap","addMarker","connectToMaster","markers","totalDuration","currentTime","durationMS","stopTime","pausedPosition","pausedTime","currentMarker","fadeTween","pendingPlayback","override","allowMultiple","externalNode","masterGainNode","gainNode","_sound","_globalVolume","_markedToDelete","_removeFromSoundManager","masterGain","createGain","createGainNode","gain","soundHasUnlocked","onDecoded","onPlay","onStop","onMute","onMarkerComplete","_volume","_buffer","_muted","_tempMarker","_tempPosition","_tempVolume","_tempPause","_muteVolume","_tempLoop","_onDecodedEventDispatched","removeMarker","onEndedHandler","onended","isDecoded","loopFull","forceRestart","noteOff","createBufferSource","noteGrainOn","muted","mute","prevMarker","fadeIn","fadeTo","fadeOut","fadeComplete","updateGlobalVolume","globalVolume","onSoundDecode","onVolumeChange","onUnMute","onTouchUnlock","channels","_codeMuted","_unlockSource","_sounds","_watchList","_watching","_watchCallback","_watchContext","disableAudio","disableWebAudio","audioContext","setTouchLock","unlock","setTouchUnlock","noteOn","stopAll","soundData","decodeAudioData","setDecodedCallback","files","playbackState","PLAYING_STATE","FINISHED_STATE","removeByKey","close","dom","minWidth","minHeight","maxHeight","forceLandscape","forcePortrait","incorrectOrientation","_pageAlignHorizontally","_pageAlignVertically","onOrientationChange","enterIncorrectOrientation","leaveIncorrectOrientation","hasPhaserSetFullScreen","fullScreenTarget","_createdFullScreenTarget","onFullScreenInit","onFullScreenChange","onFullScreenError","screenOrientation","getScreenOrientation","scaleFactorInversed","aspectRatio","sourceAspectRatio","windowConstraints","compatibility","supportsFullScreen","orientationFallback","noMargins","scrollTo","forceMinimumDocumentHeight","canExpandParent","clickTrampoline","_scaleMode","NO_SCALE","_fullScreenScaleMode","parentIsWindow","parentScaleFactor","trackParentInterval","onSizeChange","onResize","onResizeContext","_pendingScaleMode","_fullScreenRestore","_gameSize","_userScaleFactor","_userScaleTrim","_lastUpdate","_updateThrottle","_updateThrottleReset","_parentBounds","_tempBounds","_lastReportedCanvasSize","_lastReportedGameSize","_booted","setupScale","EXACT_FIT","SHOW_ALL","RESIZE","USER_SCALE","MODES","compat","_orientationChange","orientationChange","_windowResize","windowResize","_fullScreenChange","fullScreenChange","_fullScreenError","fullScreenError","_gameResumed","setGameSize","FlexGrid","fullScreenScaleMode","pageAlignHorizontally","alignH","pageAlignVertically","alignV","scaleH","scaleV","setUserScale","trimH","trimV","getParentBounds","visualBounds","updateDimensions","queueUpdate","currentScaleMode","hScale","vScale","hTrim","vTrim","setResizeCallback","signalSizeChange","setMinMax","prevThrottle","prevWidth","prevHeight","boundsChanged","orientationChanged","updateOrientationState","updateLayout","throttle","updateScalingAndBounds","forceOrientation","classifyOrientation","orientation","previousOrientation","previouslyIncorrect","isLandscape","isPortrait","changed","correctnessChanged","scrollTop","setMaximum","setExactFit","isFullScreen","boundingParent","setShowAll","resetCanvas","reflowCanvas","reflowGame","layoutBounds","clientRect","getBoundingClientRect","parentRect","offsetParent","wc","windowBounds","alignCanvas","parentBounds","canvasBounds","currentEdge","targetEdge","marginLeft","marginRight","marginTop","marginBottom","cssWidth","cssHeight","expanding","createFullScreenTarget","fsTarget","background","startFullScreen","allowTrampoline","cleanupCreatedTarget","initData","targetElement","ALLOW_KEYBOARD_INPUT","stopFullScreen","prepScreenMode","enteringFullscreen","createdTarget","scaleSprite","letterBox","scaleX1","scaleY1","scaleX2","scaleY2","scaleOnWidth","bmd","columnWidth","renderShadow","currentColor","currentAlpha","_line","_rect","soundInfo","filled","rectangle","geom","cameraInfo","hideIfUp","downColor","upColor","worldX","worldY","spriteInputInfo","justDown","justUp","inputInfo","spriteBounds","ropeSegments","segment","spriteInfo","spriteCoords","lineInfo","forceType","ellipse","quadTree","quadtree","NINJA","Ninja","BOX2D","Box2D","renderBody","bodyInfo","renderBodyInfo","box2d","box2dWorld","renderDebugDraw","box2dBody","displayList","canvasPool","phaser","factor","loader","box","scrollY","scrollLeft","scrollX","clientTop","clientLeft","cushion","calibrate","coords","getAspectRatio","inLayoutViewport","primaryFallback","screen","mozOrientation","msOrientation","matchMedia","documentBounds","pageXOffset","pageYOffset","clientWidth","clientHeight","offsetWidth","scrollWidth","offsetHeight","scrollHeight","randomIndex","removeRandomItem","newLength","transposeMatrix","sourceRowCount","sourceColCount","rotateMatrix","findClosest","arr","NaN","low","high","rotateRight","rotateLeft","numberArray","numberArrayStep","LinkedList","entity","palettes","0","PALETTE_ARNE","PALETTE_JMP","PALETTE_CGA","PALETTE_C64","PALETTE_JAPANESE_MACHINE","row","boundsCustom","boundsFull","boundsNone","positionCustom","positionFluid","positionFull","positionNone","scaleCustom","scaleFluid","scaleFull","scaleNone","customWidth","customHeight","customOffsetX","customOffsetY","ratioH","ratioV","layers","createCustomLayer","layer","FlexLayer","createFluidLayer","createFullLayer","createFixedLayer","persist","fitSprite","topLeft","topMiddle","topRight","bottomLeft","bottomMiddle","bottomRight","RED","ORANGE","YELLOW","GREEN","AQUA","BLUE","VIOLET","WHITE","BLACK","GRAY","RGBtoHSL","RGBtoHSV","fromRGBA","toRGBA","toABGR","RGBArrayToHex","rgb","hueToColor","HSVtoRGB","color32","getColor","getColor32","RGBtoString","componentToHex","hexToRGB","hex","hexToColor","webToColor","web","tempColor","getRGB","HSVColorWheel","HSLColorWheel","interpolateColor","color1","color2","currentStep","src1","src2","hsv1","hsv2","dh","h3","interpolateColorWithRGB","or","og","ob","interpolateRGB","getRandomColor","getWebRGB","getAlpha","getAlphaFloat","getRed","getGreen","getBlue","blendNormal","blendAverage","blendSubtract","blendNegation","blendLinearDodge","blendLinearBurn","blendLinearLight","blendVividLight","blendPinLight","blendHardMix","blendReflect","blendGlow","blendPhoenix","arcade","ninja","chipmunk","matter","CHIPMUNK","MATTERJS","P2","Matter","startSystem","system","enableAABB","checkCollision","OVERLAP_BIAS","forceX","sortDirection","LEFT_RIGHT","skipQuadTree","_total","SORT_NONE","RIGHT_LEFT","TOP_BOTTOM","BOTTOM_TOP","updateMotion","allowRotation","velocityDelta","computeVelocity","angularAcceleration","angularDrag","maxAngular","acceleration","drag","maxVelocity","allowGravity","allowDrag","object1","object2","overlapCallback","processCallback","collideObjects","collide","collideCallback","sortLeftRight","sortRightLeft","sortTopBottom","sortBottomTop","overlapOnly","collideHandler","collideGroupVsSelf","collideSpriteVsSprite","collideSpriteVsGroup","collideSpriteVsTilemapLayer","collideGroupVsGroup","collideGroupVsTilemapLayer","sprite1","sprite2","separate","items","bounds1","bounds2","group1","group2","body1","body2","none","isCircle","separateCircle","bodyRect","bodyCircle","resultX","resultY","separateX","separateY","onOverlap","onCollide","circleBodyIntersects","getOverlapX","getOverlapY","angleCollision","immovable","customSeparateX","tempVel1","tempVel2","bounce","maxOverlap","deltaAbsX","embedded","touching","overlapX","deltaAbsY","overlapY","moves","nv1","nv2","avg","customSeparateY","getObjectsUnderPointer","getObjectsAtLocation","callbackArg","moveToObject","maxTime","distanceBetween","moveToPointer","angleToPointer","distanceToPointer","moveToXY","distanceToXY","velocityFromAngle","velocityFromRotation","accelerationFromRotation","accelerateToObject","xSpeedMax","ySpeedMax","accelerateToPointer","accelerateToXY","angleToXY","closest","targets","farthest","angleBetweenCenters","worldAngleToPointer","preRotation","newVelocity","deltaMax","worldBounce","onWorldBounds","facing","overlapR","collideWorldBounds","wasTouching","blocked","tilePadding","syncBounds","isMoving","stopVelocityOnCollide","moveTimer","moveDistance","moveDuration","moveTarget","moveEnd","onMoveComplete","movementCallback","movementCallbackContext","_sx","_sy","updateBounds","asx","asy","updateCenter","updateMovement","collided","stopMovement","stopVelocity","check","moveFrom","setCircle","onFloor","onCeiling","onWall","TilemapCollision","TILE_BIAS","tilemapLayer","getTiles","getTileOffsetX","getTileOffsetY","separateTile","tile","tilemapLayerOffsetX","tilemapLayerOffsetY","collisionCallback","collisionCallbackContext","faceLeft","faceRight","faceTop","faceBottom","tileCheckX","tileCheckY","collideRight","collideLeft","processTileSeparationX","collideDown","collideUp","processTileSeparationY","useElapsedTime","materials","InversePointProxy","walls","onBodyAdded","onBodyRemoved","onSpringAdded","onSpringRemoved","onConstraintAdded","onConstraintRemoved","onContactMaterialAdded","onContactMaterialRemoved","postBroadphaseCallback","onBeginContact","onEndContact","mpx","mpxi","pxm","pxmi","beginContactHandler","endContactHandler","collisionGroups","nothingCollisionGroup","CollisionGroup","boundsCollisionGroup","everythingCollisionGroup","boundsCollidesWith","_toRemove","_collisionGroupID","_boundsLeft","_boundsRight","_boundsTop","_boundsBottom","_boundsOwnGroup","removeBodyNextStep","setImpactEvents","impactHandler","setPostBroadphaseCallback","postBroadphaseHandler","_bodyCallbacks","_bodyCallbackContext","_groupCallbacks","_groupCallbackContext","setCollisionGroup","setWorldMaterial","updateBoundsCollisionGroup","setupWall","wall","fixedStepTime","impactCallback","createDistanceConstraint","getBody","createGearConstraint","createRevoluteConstraint","createLockConstraint","createPrismaticConstraint","lockRotation","anchorA","anchorB","setMaterial","createMaterial","createContactMaterial","getSprings","getConstraints","filterStatic","physicsPosition","query","toJSON","createCollisionGroup","bitmask","createSpring","worldA","worldB","localA","localB","createRotationalSpring","createBody","addPolygon","createParticle","convertCollisionObjects","map","collision","shapeData","polyline","addRectangle","clearTilemapLayerBodies","getLayer","convertTilemap","optimize","collides","getTileRight","FixtureList","rawList","namedFixtures","groupedFixtures","allFixtures","setCategory","bit","getFixtures","setMask","setSensor","getFixtureByKey","getGroup","groupID","_ref","_results","callee","PointProxy","collidesWith","removeNextStep","debugBody","_collideWorldBounds","setRectangleFromSprite","createBodyCallback","createGroupCallback","getCollisionMask","updateCollisionMask","clearCollision","clearGroup","clearMask","removeCollisionGroup","clearCallback","shapeChanged","impulse","localX","localY","setZeroRotation","setZeroVelocity","setZeroDamping","moveForward","moveBackward","thrust","thrustLeft","thrustRight","moveLeft","moveRight","updateSpriteTransform","resetDamping","resetMass","clearShapes","addCircle","addPlane","addParticle","addLine","addCapsule","setRectangle","addPhaserPolygon","createdFixtures","fixtureData","shapesOfFixture","addFixture","generatedShapes","categoryBits","maskBits","isSensor","polygons","loadPolygon","BodyDebug","settings","defaultSettings","pixelsPerLengthUnit","debugPolygons","ppu","lw","vrot","_j","_ref1","randomPastelHex","drawCapsule","drawPlane","drawLine","drawRectangle","drawConvex","drawPath","lastx","lasty","diagMargin","diagSize","maxLength","xd","yd","mix","rgbToHex","ImageCollection","firstgid","imageWidth","imageHeight","imageMargin","imageSpacing","containsImageIndex","imageIndex","gid","Tile","flipped","scanned","setCollisionCallback","setCollision","resetCollision","isInteresting","faces","TilemapParser","widthInPixels","heightInPixels","tilesets","imagecollections","tiles","collideIndexes","currentLayer","debugMap","_tempA","NORTH","EAST","SOUTH","WEST","setTileSize","createBlankLayer","addTilesetImage","tileset","tileMargin","tileSpacing","getTilesetIndex","setImage","newSet","Tileset","countX","countY","columns","rows","createFromObjects","CustomClass","adjustY","adjustSize","createFromTiles","replacements","customClass","lh","createLayer","getLayerIndex","rootLayer","groupEnd","indexes","getImageIndex","setTileIndexCallback","setTileLocationCallback","recalculate","setCollisionByIndex","calculateFaces","setCollisionBetween","setCollisionByExclusion","layerArg","setPreventRecalculate","preventingRecalculate","needToRecalculate","above","below","getTileAbove","getTileBelow","getTileLeft","setLayer","hasTile","removeTile","removeTileWorldXY","putTile","putTileWorldXY","searchTileIndex","getTile","nonNull","getTileWorldXY","paste","tileblock","tileA","tileB","swapHandler","removeAllLayers","dump","txt","renderSettings","enableScrollDelta","overdrawRatio","copyCanvas","debugSettings","missingImageFill","debuggedTileOverfill","forceFullRedraw","debugAlpha","facingEdgeStroke","collidingTileOverfill","scrollFactorX","scrollFactorY","rayStepRate","_wrap","_mc","renderWidth","renderHeight","_scrollX","_scrollY","tileOffset","ensureSharedCopyCanvas","sharedCopyCanvas","resizeWorld","_fixX","_unfixX","_fixY","_unfixY","getTileX","getTileY","getTileXY","getRayCastTiles","interestingFace","coord","fetchAll","wy","wx","resolveTileset","tileIndex","setIndex","containsTileIndex","resetTilesetCache","setScale","xScale","yScale","shiftCanvas","copyW","copyH","copyContext","renderRegion","lastAlpha","xmax","ymax","baseX","normStartX","renderDeltaScroll","shiftX","shiftY","renderW","renderH","trueTop","trueBottom","trueLeft","trueRight","renderFull","redrawAll","mc","renderDebug","baseY","normStartY","INSERT_NULL","getEmptyData","parseCSV","parseTiledJSON","column","_slice","fields","sliced","parseObjectGroup","objectGroup","objectsCollection","collisionCollection","nameKey","relativePosition","curl","encoding","binaryString","atob","bytes","opacity","offsetx","offsety","flippedVal","curi","tilesetGroupObjects","lastSet","tileproperties","tileProperties","updateTileData","imagewidth","imageheight","newCollection","objectgroup","lastgid","sid","drawCoords","coordIndex","setSpacing","rowCount","colCount","autoScale","scaleData","_s","autoAlpha","alphaData","_a","onEmit","setAlphaData","setScaleData","emitters","ID","minAngle","maxAngle","minSpeed","maxSpeed","minParticleSpeed","maxParticleSpeed","minParticleScale","maxParticleScale","minRotation","maxRotation","minParticleAlpha","maxParticleAlpha","particleClass","particleDrag","particleAnchor","emitX","emitY","particleBringToTop","particleSendToBack","counts","emitted","failed","totalEmitted","totalFailed","_gravity","_minParticleScale","_maxParticleScale","_timer","_counter","_flowQuantity","_flowTotal","_explode","emitParticle","makeParticles","particleArguments","particle","rndKey","rndFrame","explode","flow","forceQuantity","getNextParticle","resetParticle","setXSpeed","setYSpeed","setRotation","setAlpha","rate","tweenData","setAngle","lifespanOutput","bullets","autoExpandBulletsGroup","autofire","shots","fireLimit","fireRate","fireRateVariance","fireFrom","fireAngle","bulletInheritSpriteSpeed","bulletAnimation","bulletFrameRandom","bulletFrameCycle","bulletWorldWrap","bulletWorldWrapPadding","bulletAngleOffset","bulletAngleVariance","bulletSpeed","bulletSpeedVariance","bulletLifespan","bulletKillDistance","bulletGravity","bulletRotateToVelocity","bulletKey","bulletFrame","_bulletClass","Bullet","_bulletCollideWorldBounds","_bulletKillType","KILL_WORLD_BOUNDS","customBody","bulletBounds","bulletFrames","bulletFrameIndex","anims","onFire","onKill","onFireLimit","trackedSprite","trackedPointer","multiFire","_hasFired","trackRotation","trackOffset","_nextFire","_tempNextFire","_rotatedPoint","KILL_NEVER","KILL_LIFESPAN","KILL_DISTANCE","KILL_WEAPON_BOUNDS","KILL_CAMERA_BOUNDS","KILL_STATIC_BOUNDS","resetShots","newLimit","fire","trackSprite","trackPointer","fireMany","fireOffset","moveX","moveY","bullet","bulletManager","killType","bulletKillType","killDistance","rotateToVelocity","bodyDirty","bulletCollideWorldBounds","fireAtPointer","fireAtSprite","fireAtXY","setBulletBodyOffset","setBulletFrames","cycle","addBulletAnimation","debugBodies","onAccess","onError","onTimeout","playWhenUnlocked","timeout","videoStream","isStreaming","retryLimit","retry","retryInterval","_retryID","_pending","_pendingChangeSource","_autoplay","_endCallback","_playCallback","_video","createVideoFromBlob","videoWidth","videoHeight","createVideoFromURL","snapshot","connectToMediaStream","stream","startMediaStream","captureAudio","removeVideoElement","setAttribute","getUserMediaTimeout","getUserMediaSuccess","getUserMediaError","mozSrcObject","createObjectURL","onloadeddata","checkStream","checkVideoProgress","change","playbackRate","setPause","setResume","playHandler","getTracks","track","playing","ended","changeSource","grab","hasChildNodes","firstChild","removeAttribute","canUseNewCanvasBlendModes"],"mappings":";;CAoDC,SAASA,GAAG,GAAG,iBAAiBC,QAAQC,OAAOD,QAAQD,QAAS,CAAmD,IAAIG,EAAE,oBAAoBC,OAAOD,EAAEC,OAAO,oBAAoBC,OAAOF,EAAEE,OAAO,oBAAoBC,OAAOH,EAAEG,MAAMH,EAAEI,GAAGP,KAAzO,CAA+O,WAAqC,OAAO,SAAUA,EAAEQ,EAAEC,EAAEC,GAAG,SAASC,EAAEC,EAAEC,GAAG,IAAIJ,EAAEG,GAAG,CAAC,IAAIJ,EAAEI,GAAG,CAAC,IAAIE,EAAkB,mBAATC,SAAqBA,QAAQ,IAAIF,GAAGC,EAAE,OAAOA,EAAEF,GAAE,GAAI,GAAGI,EAAE,OAAOA,EAAEJ,GAAE,GAAI,MAAM,IAAIK,MAAM,uBAAuBL,EAAE,KAAK,IAAIT,EAAEM,EAAEG,IAAIX,YAAYO,EAAEI,GAAG,GAAGM,KAAKf,EAAEF,QAAQ,SAASD,GAAG,IAAIS,EAAED,EAAEI,GAAG,GAAGZ,GAAG,O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ACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAItW,GACxB99C,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAGpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIpW,GACxBh+C,EAASitB,KAAWmnC,EAAInW,GAExBj+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAKpBn6C,EAASitB,KAAW0wB,EACpB39C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIlW,GACxBl+C,EAASitB,KAAWmnC,EAAIjW,GAExBn+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,IAGpBp6C,KAAKyzD,kBAEuBzzD,KAAKmM,MAE7BnM,KAAKy+C,UAObjK,EAAKkiB,qBAAqBt2D,UAAUq+C,MAAQ,WAGxC,GAA4B,IAAxBz+C,KAAKyzD,iBAAT,CAEA,IAAI5f,EAAK7zC,KAAK6zC,GAId,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AELD,KAAKC,WAAayC,EAAOzC,iBAGKn1B,IAA9Bk1B,KAAK2K,QAAQC,eAEb5K,KAAK2K,QAAQC,aAAe,IAAI5K,KAAK2K,QAAQ,IAAI3K,KAAKwmB,mBAGnB17C,IAAnCk1B,KAAKgC,cAAc6C,cAEnB7E,KAAKgC,cAAc6C,YAAc,IAAInC,EAAOC,QAGhD3C,KAAKinB,mBAAoB,EAGzBjnB,KAAKwxJ,0BAA4B,WAC7B,OAAO9uJ,EAAOgvC,OAAOnrB,gBASE,oBAAZn/D,SACe,oBAAXC,QAA0BA,OAAOD,UACxCA,QAAUC,OAAOD,QAAUs7C,GAE/Bt7C,QAAQs7C,OAASA,GACQ,oBAAXglB,QAA0BA,OAAOC,IAC/CD,OAAO,SAA+B3vB,EAAK2K,OAASA,GAEpD3K,EAAK2K,OAASA,EAGXA,GACRr6C,KAAKmD","file":"phaser.min.js"} \ No newline at end of file diff --git a/Digital Assignment 5/js/phaser.min.js b/Digital Assignment 5/js/phaser.min.js new file mode 100644 index 000000000..6eb048b7a --- /dev/null +++ b/Digital Assignment 5/js/phaser.min.js @@ -0,0 +1,4 @@ +/* Phaser v2.10.0 - http://phaser.io - @photonstorm - (c) 2016 Photon Storm Ltd. */ + +!function(t){if("object"==typeof exports)module.exports=t();else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.p2=t()}}(function(){return function t(e,i,s){function n(o,a){if(!i[o]){if(!e[o]){var h="function"==typeof require&&require;if(!a&&h)return h(o,!0);if(r)return r(o,!0);throw new Error("Cannot find module '"+o+"'")}var l=i[o]={exports:{}};e[o][0].call(l.exports,function(t){var i=e[o][1][t];return n(i||t)},l,l.exports,t,e,i,s)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;se[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;ia)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var T=0;Tm&&(m+=this.vertices.length),g=Number.MAX_VALUE,m3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e) (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.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.1"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;ca[f]&&(a[f]=u[f]),u[f]i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle");var n=t("../collision/Broadphase");t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;az&&Y0)for(G=0;GMath.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=x,f=b,g=_,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var w=r.vertices[y];if(o.rotate(p,w,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var T=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(T.normalA,f);var P=l(g,T.normalA);o.scale(g,T.normalA,P),a(T.contactPointB,p,n.position),a(T.contactPointA,p,g),a(T.contactPointA,T.contactPointA,t.position),this.contactEquations.push(T),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(T))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=x,p=b;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=x;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,w=u;w=w||0;var T=x,P=b,C=_;a(T,g,y),o.rotate(P,v,w);var S=l(P,T);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,P),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,T,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=x,m=b,y=_,v=w,P=T,E=C,M=S,R=A,L=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(M,u,i),l(g,M)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),I=s.getClosestEdge(c,d,g);if(-1===B||-1===I)return 0;for(var O=0;O<2;O++){var k=B,F=I,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===O){var q;q=k,k=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H=3){if(p)return!0;var Z=this.createContactEquation(j,V,D,U);L++;var J=D.vertices[k%D.vertices.length],Q=D.vertices[(k+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(P,v,y),o.rotate90cw(Z.normalA,P),o.normalize(Z.normalA,Z.normalA),a(M,m,y);var $=l(Z.normalA,M);o.scale(E,Z.normalA,$),a(Z.contactPointA,m,G),a(Z.contactPointA,Z.contactPointA,E),h(Z.contactPointA,Z.contactPointA,G),a(Z.contactPointA,Z.contactPointA,j.position),a(Z.contactPointB,m,N),h(Z.contactPointB,Z.contactPointB,N),a(Z.contactPointB,Z.contactPointB,V.position),this.contactEquations.push(Z),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Z))}}}return this.enableFrictionReduction&&this.enableFriction&&L&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;dh)&&(h=a),(null===c||ah){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,x=nt;if(t instanceof y&&n instanceof y)for(P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(C=0;2!==C;C++){0===C?o.set(m,0,1):1===C&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0),u=(S=T[0]-w[1])<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(var C=0;C!==b.vertices.length;C++){o.rotate(f,b.vertices[C],_),o.rotate(g,b.vertices[(C+1)%b.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0);var S=T[0]-w[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,x=pt,b=ct,_=ut,w=Math.floor((i[0]-d-l[0])/f),T=Math.ceil((i[0]+d-l[0])/f);w<0&&(w=0),T>=p.length&&(T=p.length-1);for(var P=p[w],C=p[T],S=w;SP&&(P=p[S]);if(i[1]-d>P)return!u&&0;for(var A=!1,S=w;S=b[0]&&m[0]<_[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,x,-E),o.add(y,m,g),o.copy(v,x);M=this.createContactEquation(n,t,r,e);o.copy(M.normalA,v),o.scale(M.contactPointB,M.normalA,-d),h(M.contactPointB,M.contactPointB,i),a(M.contactPointB,M.contactPointB,t.position),o.copy(M.contactPointA,y),o.sub(M.contactPointA,M.contactPointA,n.position),this.contactEquations.push(M),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(M))}}if(A=!1,d>0)for(S=w;S<=T;S++)if(o.set(b,S*f,p[S]),o.add(b,b,l),o.sub(g,i,b),o.squaredLength(g)=c.length&&(y=c.length-1);for(var v=c[m],x=c[y],b=m;bv&&(v=c[b]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var _=0,b=m;b=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;ne.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){this.from,this.to;var o=this._currentShape,a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;cthis.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.positioni?(a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n)):-1!==(b=t.indexOf(n))&&t.splice(b,1),this.lowerLimitEnabled&&va?(f.angle=a,-1===n.indexOf(f)&&n.push(f)):-1!==(y=n.indexOf(f))&&n.splice(y,1),this.lowerLimitEnabled&&m>1;if(e<3)return[];for(var i=[],n=[],r=0;r3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,x=1/(f*y-g*g),b=(y*m-g*v)*x,_=(f*v-g*m)*x;return b>=0&&_>=0&&b+_<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;ei&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),x=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||x;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(h=this.shapes.length;h>=0;--h)this.removeShape(this.shapes[h]);var i=new r.Polygon;if(i.vertices=t,i.makeCCW(),"number"==typeof e.removeCollinearPoints&&i.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!i.isSimple())return!1;this.concavePath=i.vertices.slice(0);for(h=0;h=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var T=n.create(),P=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(T,i,t*e),n.multiply(T,this.massMultiplier,T),n.add(r,T,r),this.integrateToTimeOfImpact(t)||(n.scale(P,r,t),n.add(s,s,P),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),M=n.create(),R=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)=l&&h=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var b=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),w=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),T=Math.pow(_,2)-4*b*w;if(!(T<0))if(0===T){if(r.lerp(d,n,o,T),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}else{var P=Math.sqrt(T),C=1/(2*b),S=(-_-P)*C,A=(-_+P)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,x=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;x>=0&&x<=1&&(r.lerp(f,n,h,x),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,x,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;in)&&(n=s),(null===o||sn){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;ee&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),nv){var x=y;y=v,v=x}for(var b=0;b=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,_,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};r.create();var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){(t=t||{}).type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){(t=t||{}).type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=t.lowerBound,a=t.upperBound;n(o,-1e7,-1e7),n(a,1e7,1e7),0===s?a[1]=0:s===Math.PI/2?o[0]=0:s===Math.PI?o[1]=0:s===3*Math.PI/2&&(a[0]=0)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}t("../utils/Utils");var n=t("../events/EventEmitter");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){this.overlappingShapesLastState;var n=this.overlappingShapesCurrentState;if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var s=t,n=e;(i=i||[]).length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;)(n=i.getByKey(i.keys[s]))&&e.push(n.bodyA,n.bodyB);return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s=t&&s=0;T-=2)for(S=b.length-2;S>=0;S-=2)(w[T]===b[S]&&w[T+1]===b[S+1]||w[T+1]===b[S]&&w[T]===b[S+1])&&b.splice(S,2);q=u.length;for(T=0;T!==q;T++){var C=u[T];if(!C.collideConnected)for(var S=b.length-2;S>=0;S-=2)(C.bodyA===b[S]&&C.bodyB===b[S+1]||C.bodyB===b[S]&&C.bodyA===b[S+1])&&b.splice(S,2)}this.postBroadphaseEvent.pairs=b,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var T=0,A=b.length;T!==A;T+=2)for(var E=b[T],M=b[T+1],R=0,L=E.shapes.length;R!==L;R++)for(var B=E.shapes[R],I=B.position,O=B.angle,k=0,F=M.shapes.length;k!==F;k++){var D=M.shapes[k],U=D.position,G=D.angle,N=this.defaultContactMaterial;if(B.material&&D.material){var X=this.getContactMaterial(B.material,D.material);X&&(N=X)}this.runNarrowphase(c,E,B,I,O,M,D,U,G,N,this.frictionGravity)}for(T=0;T!==h;T++)(H=n[T])._wakeUpAfterNarrowphase&&(H.wakeUp(),H._wakeUpAfterNarrowphase=!1);if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(P);for(var W=this.endContactEvent,k=P.length;k--;){var j=P[k];W.shapeA=j.shapeA,W.shapeB=j.shapeB,W.bodyA=j.bodyA,W.bodyB=j.bodyB,this.emit(W)}P.length=0}var V=this.preSolveEvent;V.contactEquations=c.contactEquations,V.frictionEquations=c.frictionEquations,this.emit(V),V.contactEquations=V.frictionEquations=null;var q=u.length;for(T=0;T!==q;T++)u[T].update();if(c.contactEquations.length||c.frictionEquations.length||q)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),T=0;T!==q;T++)v.appendArray(g.equations,u[T].equations);g.split(this);for(T=0;T!==g.islands.length;T++)(K=g.islands[T]).equations.length&&a.solveIsland(t,K)}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),T=0;T!==q;T++)a.addEquations(u[T].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(T=0;T!==h;T++){var H=n[T];H.integrate(t)}for(T=0;T!==h;T++)n[T].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var Y=this.impactEvent,T=0;T!==c.contactEquations.length;T++){var z=c.contactEquations[T];z.firstImpact&&(Y.bodyA=z.bodyA,Y.bodyB=z.bodyB,Y.shapeA=z.shapeA,Y.shapeB=z.shapeB,Y.contactEquation=z,this.emit(Y))}if(this.sleepMode===s.BODY_SLEEPING)for(T=0;T!==h;T++)n[T].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(T=0;T!==h;T++)n[T].sleepTick(this.time,!0,t);for(T=0;T0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,x=t.frictionEquations.length;y=i.type=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0),o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC&&r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0),this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var _=this.beginContactEvent;if(_.shapeA=i,_.shapeB=a,_.bodyA=e,_.bodyB=o,_.contactEquations.length=0,"number"==typeof y)for(P=t.contactEquations.length-y;P1)for(var P=t.frictionEquations.length-b;P=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var x=e[y],b=0,_=x.shapes.length;b!==_;b++){var w=x.shapes[b];r.rotate(p,w.position,x.angle),r.add(p,p,x.position);var T=w.angle+x.angle;(w instanceof o&&g.circleParticle(x,w,p,T,s,n,u,0,!0)||w instanceof a&&g.particleConvex(s,n,u,0,x,w,p,T,!0)||w instanceof h&&g.particlePlane(s,n,u,0,x,w,p,T,!0)||w instanceof l&&g.particleCapsule(s,n,u,0,x,w,p,T,!0)||w instanceof c&&r.squaredLength(r.sub(f,p,t))0?Math.acos(i/u):-Math.acos(i/u),this.worldScale.x=u,this.worldScale.y=c/u}else if(n||r){var d=Math.sqrt(n*n+r*r);this.worldRotation=Phaser.Math.HALF_PI-(r>0?Math.acos(-n/d):-Math.acos(n/d)),this.worldScale.x=c/d,this.worldScale.y=d}else this.worldScale.x=0,this.worldScale.y=0;return this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.x=l.tx,this.worldPosition.y=l.ty,this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,l,h),this},preUpdate:function(){},generateTexture:function(t,e,i){var n=this.getLocalBounds(),r=new Phaser.RenderTexture(this.game,0|n.width,0|n.height,i,e,t);return s.DisplayObject._tempMatrix.tx=-n.x,s.DisplayObject._tempMatrix.ty=-n.y,r.render(this,s.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?s.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):s.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=0;this.texture&&this.texture.baseTexture&&s._enableMultiTextureToggle&&(e=this.texture.baseTexture.textureIndex);var i=new Phaser.RenderTexture(this.game,t.width,t.height,void 0,void 0,void 0,void 0,e);this._cachedSprite=new s.Sprite(i),this._cachedSprite.worldTransform=this.worldTransform}var n=this._filters;this._filters=null,this._cachedSprite.filters=n,s.DisplayObject._tempMatrix.tx=-t.x,s.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,s.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=n,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},s.DisplayObject.prototype.displayObjectUpdateTransform=s.DisplayObject.prototype.updateTransform,Object.defineProperties(s.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],i=0;i=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},s.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},s.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},s.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},s.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},s.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},s.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},s.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(t,i),n=0;na?u:a,d=d>h?d:h);var f=this._bounds;if(!p){var g=(f=new s.Rectangle).x,m=f.width+f.x,y=f.y,v=f.height+f.y,x=this.worldTransform,b=x.a,_=x.b,w=x.c,T=x.d,P=x.tx,C=x.ty,S=b*m+w*v+P,A=T*v+_*m+C,E=b*g+w*v+P,M=T*v+_*g+C,R=b*g+w*y+P,L=T*y+_*g+C,B=b*m+w*y+P,I=T*y+_*m+C;u=S,d=A,c=A,l=B<(l=R<(l=E<(l=S)?E:l)?R:l)?B:l,c=I<(c=L<(c=M(u=R>(u=E>u?E:u)?R:u)?B:u,d=I>(d=L>(d=M>d?M:d)?L:d)?I:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n(f=T>(f=_>(f=x>f?x:f)?_:f)?T:f)?C:f,g=S>(g=P>(g=w>(g=b>g?b:g)?w:g)?P:g)?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},s.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=Phaser.identityMatrix;for(var e=0;e= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}","}"];var n=s.compileProgram(t,this.vertexSrc||s.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(n),this.uSamplerArray=t.getUniformLocation(n,"uSamplerArray[0]"),this.projectionVector=t.getUniformLocation(n,"projectionVector"),this.offsetVector=t.getUniformLocation(n,"offsetVector"),this.dimensions=t.getUniformLocation(n,"dimensions"),this.aVertexPosition=t.getAttribLocation(n,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(n,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(n,"aColor"),this.aTextureIndex=t.getAttribLocation(n,"aTextureIndex");var r=[],o=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var a=0;a 0.0) gl_Position = vec4(0.0);"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);"," vTextureIndex = aTextureIndex;","}"],s.PixiFastShader=function(t){if(this._UID=Phaser._UID++,this.gl=t,this.program=null,s._enableMultiTextureToggle){var t=this.gl;this.MAX_TEXTURES=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(var e="\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n",i=1;i= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["// PixiFastShader Fragment Shader.","precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;","}"];this.vertexSrc=["// PixiFastShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","attribute float aTextureIndex;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;"," vColor = aColor;","}"],this.textureCount=0,this.init()},s.PixiFastShader.prototype.constructor=s.PixiFastShader,s.PixiFastShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["//StripShader Fragment Shader.","precision mediump float;","varying vec2 vTextureCoord;","varying float vTextureIndex;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord);","}"];this.vertexSrc=["//StripShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aTextureIndex;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;","}"],this.init()},s.StripShader.prototype.constructor=s.StripShader,s.StripShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t},i=this.gl,n=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),r=i.getParameter(i.MAX_TEXTURE_SIZE),o=this.game.cache._cache.image,a=null,h=0;h=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var a=i._uvs;if(a){var h,l,c,u,d=t.anchor.x,p=t.anchor.y;if(i.trim){var f=i.trim;h=(l=f.x-d*f.width)+i.crop.width,c=(u=f.y-p*f.height)+i.crop.height}else h=i.frame.width*(1-d),l=i.frame.width*-d,c=i.frame.height*(1-p),u=i.frame.height*-p;var g=this.currentBatchSize*this.vertexSize,m=(this.currentBatchSize,i.baseTexture.resolution),y=i.baseTexture.textureIndex,v=o.a/m,x=o.b/m,b=o.c/m,_=o.d/m,w=o.tx,T=o.ty,P=(i.crop.width,i.crop.height);if(i.rotated){var C=o.a,S=o.b,A=o.c,E=o.d,M=l,R=h;w=o.c*P+w,T=o.d*P+T,v=6.123233995736766e-17*C-A,x=6.123233995736766e-17*S-E,b=C+6.123233995736766e-17*A,_=S+6.123233995736766e-17*E,i._updateUvsInverted(),h=c,l=u,c=R,u=M}var L=this.colors,B=this.positions,I=t.tint,O=(I>>16)+(65280&I)+((255&I)<<16)+(255*t.worldAlpha<<24);this.renderSession.roundPixels?(B[g++]=v*l+b*u+w|0,B[g++]=_*u+x*l+T|0,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w|0,B[g++]=_*u+x*h+T|0,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w|0,B[g++]=_*c+x*h+T|0,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w|0,B[g++]=_*c+x*l+T|0,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y):(B[g++]=v*l+b*u+w,B[g++]=_*u+x*l+T,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w,B[g++]=_*u+x*h+T,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w,B[g++]=_*c+x*h+T,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w,B[g++]=_*c+x*l+T,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y),this.sprites[this.currentBatchSize++]=t}},s.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture,i=e.baseTexture,n=this.gl,r=t.texture.baseTexture.textureIndex;s.WebGLRenderer.textureArray[r]!=i&&(this.flush(),n.activeTexture(n.TEXTURE0+r),n.bindTexture(n.TEXTURE_2D,i._glTextures[n.id]),s.WebGLRenderer.textureArray[r]=i),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new s.TextureUvs);var o=t._uvs,a=e.baseTexture.width,h=e.baseTexture.height;t.tilePosition.x%=a*t.tileScaleOffset.x,t.tilePosition.y%=h*t.tileScaleOffset.y;var l=t.tilePosition.x/(a*t.tileScaleOffset.x),c=t.tilePosition.y/(h*t.tileScaleOffset.y),u=t.width/a/(t.tileScale.x*t.tileScaleOffset.x),d=t.height/h/(t.tileScale.y*t.tileScaleOffset.y);o.x0=0-l,o.y0=0-c,o.x1=1*u-l,o.y1=0-c,o.x2=1*u-l,o.y2=1*d-c,o.x3=0-l,o.y3=1*d-c;var p=t.tint,f=(p>>16)+(65280&p)+((255&p)<<16)+(255*t.worldAlpha<<24),g=this.positions,m=this.colors,y=t.width,v=t.height,x=t.anchor.x,b=t.anchor.y,_=y*(1-x),w=y*-x,T=v*(1-b),P=v*-b,C=this.currentBatchSize*this.vertexSize,S=e.baseTexture.resolution,A=t.worldTransform,E=A.a/S,M=A.b/S,R=A.c/S,L=A.d/S,B=A.tx,I=A.ty;g[C++]=E*w+R*P+B,g[C++]=L*P+M*w+I,g[C++]=o.x0,g[C++]=o.y0,m[C++]=f,g[C++]=r,g[C++]=E*_+R*P+B,g[C++]=L*P+M*_+I,g[C++]=o.x1,g[C++]=o.y1,m[C++]=f,g[C++]=r,g[C++]=E*_+R*T+B,g[C++]=L*T+M*_+I,g[C++]=o.x2,g[C++]=o.y2,m[C++]=f,g[C++]=r,g[C++]=E*w+R*T+B,g[C++]=L*T+M*w+I,g[C++]=o.x3,g[C++]=o.y3,m[C++]=f,g[C++]=r,this.sprites[this.currentBatchSize++]=t},s.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,t=this.defaultShader.shaders[e.id],e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var i=this.vertexSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,i,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,i,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,i,16),e.vertexAttribPointer(t.aTextureIndex,1,e.FLOAT,!1,i,20)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);var n=this.positions.subarray(0,this.currentBatchSize*this.vertexSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m0&&(v=!1),(f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){(t=(p=a).shaders[e.id])||((t=new s.PixiShader(e)).fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var x=this.renderSession.projection;e.uniform2f(t.projectionVector,x.x,x.y);var b=this.renderSession.offset;e.uniform2f(t.offsetVector,b.x,b.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},s.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},s.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},s.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},s.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},s.WebGLFastSpriteBatch=function(t){this.vertSize=11,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,i=6*this.maxSize;this.vertices=new Float32Array(e),this.indices=new Uint16Array(i),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var s=0,n=0;s=this.size&&this.flush()}},s.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]){if(this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}else this.renderSession.renderer.updateTexture(this.currentBaseTexture,t)}},s.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},s.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36),t.vertexAttribPointer(this.shader.aTextureIndex,1,t.FLOAT,!1,i,40)},s.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},s.WebGLFilterManager.prototype.constructor=s.WebGLFilterManager,s.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},s.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},s.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,i=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new s.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),i.x=a.width/2,i.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},s.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),i=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,i.width*this.renderSession.resolution,i.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=i.height,this.vertexArray[2]=i.width,this.vertexArray[3]=i.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=i.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=i.width/this.width,this.uvArray[5]=i.height/this.height,this.uvArray[6]=i.width/this.width,this.uvArray[7]=i.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,i,p,f),this.texturePool.push(n),e._glFilterTexture=null},s.WebGLFilterManager.prototype.applyFilterPass=function(t,e,i,n){var r=this.gl,o=t.shaders[r.id];o||((o=new s.PixiShader(r)).fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(!0),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,i/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},s.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},s.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e=0;t--){var e=this._glTextures[t],i=s.glContexts[t];i&&e&&i.deleteTexture(e)}this._glTextures.length=0,this.dirty()},s.BaseTexture.fromCanvas=function(t,e,i){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),i=i||1,new s.BaseTexture(t,e,i)},s.TextureSilentFail=!1,s.Texture=function(t,e,i,n){this.noFrame=!1,e||(this.noFrame=!0,e=new s.Rectangle(0,0,1,1)),t instanceof s.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=i||new s.Rectangle(0,0,1,1),this.rotated=!1,t.hasLoaded&&(this.noFrame&&(e=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},s.Texture.prototype.constructor=s.Texture,s.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},s.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},s.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,this.trim||!(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height))this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs();else{if(!s.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=!1}},s.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/i},s.Texture.prototype._updateUvsInverted=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.height)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.height)/e,this._uvs.y2=(t.y+t.width)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.width)/i},s.Texture.fromCanvas=function(t,e){var i=s.BaseTexture.fromCanvas(t,e);return new s.Texture(i)},s.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=s),exports.PIXI=s):"undefined"!=typeof define&&define.amd?define("PIXI",i.PIXI=s):i.PIXI=s,s}.call(this),function(){function t(t,e){this._scaleFactor=t,this._deltaMode=e,this.originalEvent=null}var e=this,i=i||{VERSION:"2.10.0",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,WEBGL_MULTI:4,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,PENDING_ATLAS:-1,HORIZONTAL:0,VERTICAL:1,LANDSCAPE:0,PORTRAIT:1,ANGLE_UP:270,ANGLE_DOWN:90,ANGLE_LEFT:180,ANGLE_RIGHT:0,ANGLE_NORTH_EAST:315,ANGLE_NORTH_WEST:225,ANGLE_SOUTH_EAST:45,ANGLE_SOUTH_WEST:135,TOP_LEFT:0,TOP_CENTER:1,TOP_RIGHT:2,LEFT_TOP:3,LEFT_CENTER:4,LEFT_BOTTOM:5,CENTER:6,RIGHT_TOP:7,RIGHT_CENTER:8,RIGHT_BOTTOM:9,BOTTOM_LEFT:10,BOTTOM_CENTER:11,BOTTOM_RIGHT:12,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},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{},_UID:0};if(Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Function.prototype.bind||(Function.prototype.bind=function(){var t=Array.prototype.slice;return function(e){function i(){var r=n.concat(t.call(arguments));s.apply(this instanceof i?this:e,r)}var s=this,n=t.call(arguments,1);if("function"!=typeof s)throw new TypeError;return i.prototype=function t(e){if(e&&(t.prototype=e),!(this instanceof t))return new t}(s.prototype),i}}()),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var s=arguments.length>=2?arguments[1]:void 0,n=0;n0&&100*Math.random()<=t},randomChoice:function(t,e){return Math.random()<.5?t:e},parseDimension:function(t,e){var i=0,s=0;return"string"==typeof t?"%"===t.substr(-1)?(i=parseInt(t,10)/100,s=0===e?window.innerWidth*i:window.innerHeight*i):s=parseInt(t,10):s=t,s},pad:function(t,e,i,s){if(void 0===e)var e=0;if(void 0===i)var i=" ";if(void 0===s)var s=3;var n=0;if(e+1>=(t=t.toString()).length)switch(s){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((n=e-t.length)/2),o=n-r;t=new Array(o+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t},isPlainObject:function(t){if("object"!=typeof t||t.nodeType||t===t.window)return!1;try{if(t.constructor&&!{}.hasOwnProperty.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},extend:function(){var t,e,s,n,r,o,a=arguments[0]||{},h=1,l=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[1]||{},h=2),l===h&&(a=this,--h);h0&&(this._radius=.5*s),this.type=i.CIRCLE},i.Circle.prototype={circumference:function(){return Math.PI*this._radius*2},random:function(t){void 0===t&&(t=new i.Point);var e=2*Math.PI*Math.random(),s=Math.random()+Math.random(),n=s>1?2-s:s,r=n*Math.cos(e),o=n*Math.sin(e);return t.x=this.x+r*this.radius,t.y=this.y+o*this.radius,t},getBounds:function(){return new i.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(t,e,i){return this.x=t,this.y=e,this._diameter=i,this._radius=.5*i,this},copyFrom:function(t){return this.setTo(t.x,t.y,t.diameter)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.diameter=this._diameter,t},distance:function(t,e){var s=i.Math.distance(this.x,this.y,t.x,t.y);return e?Math.round(s):s},clone:function(t){return void 0===t||null===t?t=new i.Circle(this.x,this.y,this.diameter):t.setTo(this.x,this.y,this.diameter),t},contains:function(t,e){return i.Circle.contains(this,t,e)},circumferencePoint:function(t,e,s){return i.Circle.circumferencePoint(this,t,e,s)},sample:function(t,e,s,n,r){t||(t=60),null==e&&(e=0),null==s&&(s=i.Math.PI2),r||(r=[]);for(var o=0;o0&&(this._diameter=t,this._radius=.5*t)}}),Object.defineProperty(i.Circle.prototype,"radius",{get:function(){return this._radius},set:function(t){t>0&&(this._radius=t,this._diameter=2*t)}}),Object.defineProperty(i.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(t){t>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-t}}),Object.defineProperty(i.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(t){tthis.y?(this._radius=0,this._diameter=0):this.radius=this.y-t}}),Object.defineProperty(i.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(t){t0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(i.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(t){!0===t&&this.setTo(0,0,0)}}),i.Circle.contains=function(t,e,i){return t.radius>0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius},i.Circle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.diameter===e.diameter},i.Circle.intersects=function(t,e){return i.Math.distance(t.x,t.y,e.x,e.y)<=t.radius+e.radius},i.Circle.circumferencePoint=function(t,e,s,n){return void 0===s&&(s=!1),void 0===n&&(n=new i.Point),!0===s&&(e=i.Math.degToRad(e)),n.x=t.x+t.radius*Math.cos(e),n.y=t.y+t.radius*Math.sin(e),n},i.Circle.intersectsRectangle=function(t,e){var i=Math.abs(t.x-e.x-e.halfWidth);if(i>e.halfWidth+t.radius)return!1;var s=Math.abs(t.y-e.y-e.halfHeight);if(s>e.halfHeight+t.radius)return!1;if(i<=e.halfWidth||s<=e.halfHeight)return!0;var n=i-e.halfWidth,r=s-e.halfHeight;return n*n+r*r<=t.radius*t.radius},i.Circle.intersectsLine=function(t,e,s){var n=t.x,r=t.y,o=(e.end.y-e.start.y)/(e.end.x-e.start.x),a=e.end.y-o*e.end.x,h=t.radius,l=t.radius,c=a+o*n,u=(n*(l*l)-o*(h*h)*(a-r)+h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),d=(n*(l*l)-o*(h*h)*(a-r)-h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),p=o*u+a,f=o*d+a,g=new i.Point(u,p),m=new i.Point(d,f),y=e.pointOnSegment(g.x,g.y,.01),v=e.pointOnSegment(m.x,m.y,.01);return y&&v?!s||[g,m]:y?!s||[g]:v?!s||[m]:!!s&&[]},PIXI.Circle=i.Circle,i.Ellipse=function(t,e,s,n){t=t||0,e=e||0,s=s||0,n=n||0,this.x=t,this.y=e,this.width=s,this.height=n,this.type=i.ELLIPSE},i.Ellipse.prototype={setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},getBounds:function(){return new i.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},clone:function(t){return void 0===t||null===t?t=new i.Ellipse(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t},contains:function(t,e){return i.Ellipse.contains(this,t,e)},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random()*Math.PI*2,s=Math.random();return t.x=Math.sqrt(s)*Math.cos(e),t.y=Math.sqrt(s)*Math.sin(e),t.x=this.x+t.x*this.width/2,t.y=this.y+t.y*this.height/2,t},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},i.Ellipse.prototype.constructor=i.Ellipse,Object.defineProperty(i.Ellipse.prototype,"left",{get:function(){return this.x},set:function(t){this.x=t}}),Object.defineProperty(i.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t=s&&t<=n&&e>=r&&e<=o},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random();return t.x=this.start.x+e*(this.end.x-this.start.x),t.y=this.start.y+e*(this.end.y-this.start.y),t},coordinatesOnLine:function(t,e){void 0===t&&(t=1),void 0===e&&(e=[]);var i=Math.round(this.start.x),s=Math.round(this.start.y),n=Math.round(this.end.x),r=Math.round(this.end.y),o=Math.abs(n-i),a=Math.abs(r-s),h=i-a&&(c-=a,i+=h),d=0&&g<=1&&m>=0&&m<=1?o:null}return o},i.Line.intersects=function(t,e,s,n){return i.Line.intersectsPoints(t.start,t.end,e.start,e.end,s,n)},i.Line.intersectsRectangle=function(t,e){if(0===t.length||e.empty)return!1;var i=t.start.x,s=t.start.y,n=t.end.x,r=t.end.y,o=e.x,a=e.y,h=e.right,l=e.bottom,c=0;if(i>=o&&i<=h&&s>=a&&s<=l||n>=o&&n<=h&&r>=a&&r<=l)return!0;if(i=o){if((c=s+(r-s)*(o-i)/(n-i))>a&&c<=l)return!0}else if(i>h&&n<=h&&(c=s+(r-s)*(h-i)/(n-i))>=a&&c<=l)return!0;if(s=a){if((c=i+(n-i)*(a-s)/(r-s))>=o&&c<=h)return!0}else if(s>l&&r<=l&&(c=i+(n-i)*(l-s)/(r-s))>=o&&c<=h)return!0;return!1},i.Line.intersectionWithRectangle=function(t,e,s){var n=i.Line.intersectionWithRectangle;s||(s=new i.Point),n.edges||(n.edges=[new i.Line,new i.Line,new i.Line,new i.Line]),n.edgeIntersection||(n.edgeIntersection=new i.Point);var r=n.edges,o=n.edgeIntersection.set(0),a=e.x,h=e.y,l=e.right,c=e.bottom,u=1/0;r[0].setTo(a,h,l,h),r[1].setTo(a,c,l,c),r[2].setTo(a,h,a,c),r[3].setTo(l,h,l,c);for(var d,p=0;d=r[p];p++)if(t.intersects(d,!0,o)){var f=t.start.distance(o);fs&&(this.x=s),this.yn&&(this.y=n),this},clone:function(t){return void 0===t||null===t?t=new i.Point(this.x,this.y):t.setTo(this.x,this.y),t},copyTo:function(t){return t.x=this.x,t.y=this.y,t},distance:function(t,e){return i.Point.distance(this,t,e)},equals:function(t){return t.x===this.x&&t.y===this.y},equalsXY:function(t,e){return this.x===t&&this.y===e},fuzzyEquals:function(t,e){return i.Point.fuzzyEquals(this,t,e)},fuzzyEqualsXY:function(t,e,s){return i.Point.fuzzyEqualsXY(this,t,e,s)},angle:function(t,e){return this.angleXY(t.x,t.y,e)},angleXY:function(t,e,s){var n=Math.atan2(e-this.y,t-this.x);return s?i.Math.radToDeg(n):n},atan:function(t){var e=Math.atan2(this.y,this.x);return t?i.Math.radToDeg(e):e},rotate:function(t,e,s,n,r){return i.Point.rotate(this,t,e,s,n,r)},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(t){return this.normalize().multiply(t,t)},normalize:function(){if(!this.isZero()){var t=this.getMagnitude();this.x/=t,this.y/=t}return this},limit:function(t){return this.getMagnitudeSq()>t*t&&this.setMagnitude(t),this},expand:function(t){return this.getMagnitudeSq()=0&&e.x-i<0)return-1;if(t.x-i<0&&e.x-i>=0)return 1;if(t.x-i==0&&e.x-i==0)return t.y-s>=0||e.y-s>=0?t.y>e.y?1:-1:e.y>t.y?1:-1;var n=(t.x-i)*-(e.y-s)-(e.x-i)*-(t.y-s);return n<0?-1:n>0?1:(t.x-i)*(t.x-i)+(t.y-s)*(t.y-s)>(e.x-i)*(e.x-i)+(e.y-s)*(e.y-s)?-1:1})},PIXI.Point=i.Point,i.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.flattened=!1,this.type=i.POLYGON},i.Polygon.prototype={toNumberArray:function(t){void 0===t&&(t=[]);for(var e=0;e0){Array.isArray(t)||(t=Array.prototype.slice.call(arguments));for(var e=Number.MAX_VALUE,i=0,s=t.length;i=this.right?this.width=0:this.width=this.right-t,this.x=t}}),Object.defineProperty(i.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(i.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(i.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(i.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(t){this.x=t-this.halfWidth}}),Object.defineProperty(i.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(t){this.y=t-this.halfHeight}}),Object.defineProperty(i.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(i.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(i.Rectangle.prototype,"top",{get:function(){return this.y},set:function(t){t>=this.bottom?(this.height=0,this.y=t):this.height=this.bottom-t}}),Object.defineProperty(i.Rectangle.prototype,"topLeft",{get:function(){return new i.Point(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"topRight",{get:function(){return new i.Point(this.x+this.width,this.y)},set:function(t){this.right=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),i.Rectangle.prototype.constructor=i.Rectangle,i.Rectangle.inflate=function(t,e,i){return t.x-=e,t.width+=2*e,t.y-=i,t.height+=2*i,t},i.Rectangle.inflatePoint=function(t,e){return i.Rectangle.inflate(t,e.x,e.y)},i.Rectangle.size=function(t,e){return void 0===e||null===e?e=new i.Point(t.width,t.height):e.setTo(t.width,t.height),e},i.Rectangle.clone=function(t,e){return void 0===e||null===e?e=new i.Rectangle(t.x,t.y,t.width,t.height):e.setTo(t.x,t.y,t.width,t.height),e},i.Rectangle.createFromBounds=function(t,e){return void 0!==e&&null!==e||(e=new i.Rectangle(t.x,t.y,t.width,t.height)),e.copyFromBounds(t)},i.Rectangle.contains=function(t,e,i){return!(t.width<=0||t.height<=0)&&(e>=t.x&&e=t.y&&i=t&&n=e&&re.volume)&&(t.x>=e.x&&t.y>=e.y&&t.righte.right||t.y>e.bottom)},i.Rectangle.intersectsRaw=function(t,e,i,s,n,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||ns&&(s=t.x),t.xr&&(r=t.y),t.y=i&&t<=i+this.width){var s=this.y;if(e>=s&&e<=s+this.height)return!0}return!1}},i.RoundedRectangle.prototype.constructor=i.RoundedRectangle,PIXI.RoundedRectangle=i.RoundedRectangle,i.Camera=function(t,e,s,n,r,o){this.game=t,this.world=t.world,this.id=0,this.view=new i.Rectangle(s,n,r,o),this.bounds=new i.Rectangle(s,n,r,o),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this.lerp=new i.Point(1,1),this.onShakeComplete=new i.Signal,this.onFlashComplete=new i.Signal,this.onFadeComplete=new i.Signal,this.fx=null,this._targetPosition=new i.Point,this._edge=0,this._position=new i.Point,this._shake={intensity:0,duration:0,horizontal:!1,vertical:!1,shakeBounds:!0,x:0,y:0},this._fxDuration=0,this._fxType=0,this._fixedView=new i.Rectangle},i.Camera.FOLLOW_LOCKON=0,i.Camera.FOLLOW_PLATFORMER=1,i.Camera.FOLLOW_TOPDOWN=2,i.Camera.FOLLOW_TOPDOWN_TIGHT=3,i.Camera.SHAKE_BOTH=4,i.Camera.SHAKE_HORIZONTAL=5,i.Camera.SHAKE_VERTICAL=6,i.Camera.ENABLE_FX=!0,i.Camera.prototype={boot:function(){this.displayObject=this.game.world,this.scale=this.game.world.scale,this.game.camera=this,i.Graphics&&i.Camera.ENABLE_FX&&(this.fx=new i.Graphics(this.game),this.game.stage.addChild(this.fx))},preUpdate:function(){this.totalInView=0},follow:function(t,e,s,n){void 0===e&&(e=i.Camera.FOLLOW_LOCKON),void 0===s&&(s=1),void 0===n&&(n=1),this.target=t,this.lerp.set(s,n);var r;switch(e){case i.Camera.FOLLOW_PLATFORMER:var o=this.width/8,a=this.height/3;this.deadzone=new i.Rectangle((this.width-o)/2,(this.height-a)/2-.25*a,o,a);break;case i.Camera.FOLLOW_TOPDOWN:r=Math.max(this.width,this.height)/4,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_TOPDOWN_TIGHT:r=Math.max(this.width,this.height)/8,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_LOCKON:default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(t){this.setPosition(Math.round(t.x-this.view.halfWidth),Math.round(t.y-this.view.halfHeight))},focusOnXY:function(t,e){this.setPosition(Math.round(t-this.view.halfWidth),Math.round(e-this.view.halfHeight))},shake:function(t,e,s,n,r){return void 0===t&&(t=.05),void 0===e&&(e=500),void 0===s&&(s=!0),void 0===n&&(n=i.Camera.SHAKE_BOTH),void 0===r&&(r=!0),!(!s&&this._shake.duration>0)&&(this._shake.intensity=t,this._shake.duration=e,this._shake.shakeBounds=r,this._shake.x=0,this._shake.y=0,this._shake.horizontal=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_HORIZONTAL,this._shake.vertical=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_VERTICAL,!0)},flash:function(t,e,i,s){return void 0===t&&(t=16777215),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=1,this._fxDuration=e,this._fxType=0,!0)},fade:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=0,this._fxDuration=e,this._fxType=1,!0)},update:function(){this._fxDuration>0&&this.updateFX(),this._shake.duration>0&&this.updateShake(),this.bounds&&this.checkBounds(),this.roundPx&&(this.view.floor(),this._shake.x=Math.floor(this._shake.x),this._shake.y=Math.floor(this._shake.y)),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateFX:function(){0===this._fxType?(this.fx.alpha-=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha<=0&&(this._fxDuration=0,this.fx.alpha=0,this.onFlashComplete.dispatch())):(this.fx.alpha+=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha>=1&&(this._fxDuration=0,this.fx.alpha=1,this.onFadeComplete.dispatch()))},updateShake:function(){this._shake.duration-=this.game.time.elapsedMS,this._shake.duration<=0?(this.onShakeComplete.dispatch(),this._shake.x=0,this._shake.y=0):(this._shake.horizontal&&(this._shake.x=this.game.rnd.frac()*this._shake.intensity*this.view.width*2-this._shake.intensity*this.view.width),this._shake.vertical&&(this._shake.y=this.game.rnd.frac()*this._shake.intensity*this.view.height*2-this._shake.intensity*this.view.height))},updateTarget:function(){this._targetPosition.x=this.view.x+this.target.worldPosition.x,this._targetPosition.y=this.view.y+this.target.worldPosition.y,this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edgethis.deadzone.right&&(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.right,this.lerp.x)),this._edge=this._targetPosition.y-this.view.y,this._edgethis.deadzone.bottom&&(this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.bottom,this.lerp.y))):(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.view.halfWidth,this.lerp.x),this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.view.halfHeight,this.lerp.y)),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},setBoundsToWorld:function(){this.bounds&&this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1;var t=this.view.x+this._shake.x,e=this.view.right+this._shake.x,i=this.view.y+this._shake.y,s=this.view.bottom+this._shake.y;t<=this.bounds.x*this.scale.x?(this.atLimit.x=!0,this.view.x=this.bounds.x*this.scale.x,this._shake.shakeBounds||(this._shake.x=0)):e>=this.bounds.right*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.right*this.scale.x-this.width,this._shake.shakeBounds||(this._shake.x=0)),i<=this.bounds.top*this.scale.y?(this.atLimit.y=!0,this.view.y=this.bounds.top*this.scale.y,this._shake.shakeBounds||(this._shake.y=0)):s>=this.bounds.bottom*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom*this.scale.y-this.height,this._shake.shakeBounds||(this._shake.y=0))},setPosition:function(t,e){this.view.x=t,this.view.y=e,this.bounds&&this.checkBounds()},setSize:function(t,e){this.view.width=t,this.view.height=e},reset:function(){this.target=null,this.view.x=0,this.view.y=0,this._shake.duration=0,this._shake.x=0,this._shake.y=0,this.resetFX()},resetFX:function(){this.fx&&(this.fx.clear(),this.fx.alpha=0),this._fxDuration=0}},i.Camera.prototype.constructor=i.Camera,Object.defineProperty(i.Camera.prototype,"x",{get:function(){return this.view.x},set:function(t){this.view.x=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"y",{get:function(){return this.view.y},set:function(t){this.view.y=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"position",{get:function(){return this._position.set(this.view.x,this.view.y),this._position},set:function(t){void 0!==t.x&&(this.view.x=t.x),void 0!==t.y&&(this.view.y=t.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"width",{get:function(){return this.view.width},set:function(t){this.view.width=t}}),Object.defineProperty(i.Camera.prototype,"height",{get:function(){return this.view.height},set:function(t){this.view.height=t}}),Object.defineProperty(i.Camera.prototype,"shakeIntensity",{get:function(){return this._shake.intensity},set:function(t){this._shake.intensity=t}}),Object.defineProperty(i.Camera.prototype,"fixedView",{get:function(){return this._fixedView.setTo(0,0,this.view.width,this.view.height),this._fixedView}}),i.State=function(){this.game=null,this.key="",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.state=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},i.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},i.State.prototype.constructor=i.State,i.StateManager=function(t,e){this.game=t,this.states={},this._pendingState=null,void 0!==e&&null!==e&&(this._pendingState=e),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new i.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},i.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(t,e,s){void 0===s&&(s=!1);var n;return e instanceof i.State?n=e:"object"==typeof e?(n=e).game=this.game:"function"==typeof e&&(n=new e(this.game)),this.states[t]=n,s&&(this.game.isBooted?this.start(t):this._pendingState=t),n},remove:function(t){this.current===t&&(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.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[t]},start:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1),this.checkState(t)&&(this._pendingState=t,this._clearWorld=e,this._clearCache=i,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!1),this._pendingState=this.current,this._clearWorld=t,this._clearCache=e,arguments.length>2&&(this._args=Array.prototype.slice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var t=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,t),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache&&this.game.cache.destroy()))},checkState:function(t){var e=this.states[t];return e?!!(e.preload||e.create||e.update||e.render)||(console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"),!1):(console.warn("Phaser.StateManager - No state found with the key: "+t),!1)},link:function(t){var e=this.states[t];e.game=this.game,e.add=this.game.add,e.make=this.game.make,e.camera=this.game.camera,e.cache=this.game.cache,e.input=this.game.input,e.load=this.game.load,e.math=this.game.math,e.sound=this.game.sound,e.scale=this.game.scale,e.state=this,e.stage=this.game.stage,e.time=this.game.time,e.tweens=this.game.tweens,e.world=this.game.world,e.particles=this.game.particles,e.rnd=this.game.rnd,e.physics=this.game.physics,e.key=t},unlink:function(t){var e=this.states[t];e&&(e.game=null,e.add=null,e.make=null,e.camera=null,e.cache=null,e.input=null,e.load=null,e.math=null,e.sound=null,e.scale=null,e.state=null,e.stage=null,e.time=null,e.tweens=null,e.world=null,e.particles=null,e.rnd=null,e.physics=null)},setCurrentState:function(t){var e=this.states[t];this.callbackContext=e,this.link(t),this.onInitCallback=e.init||this.dummy,this.onPreloadCallback=e.preload||null,this.onLoadRenderCallback=e.loadRender||null,this.onLoadUpdateCallback=e.loadUpdate||null,this.onCreateCallback=e.create||null,this.onUpdateCallback=e.update||null,this.onPreRenderCallback=e.preRender||null,this.onRenderCallback=e.render||null,this.onResizeCallback=e.resize||null,this.onPausedCallback=e.paused||null,this.onResumedCallback=e.resumed||null,this.onPauseUpdateCallback=e.pauseUpdate||null,this.onShutDownCallback=e.shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=t,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),t===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){!1===this._created&&this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game),!1===this._created&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(t){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,t)},resize:function(t,e){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,t,e)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===i.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this._clearWorld=!0,this._clearCache=!0,this.clearCurrentState(),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,this.current=""}},i.StateManager.prototype.constructor=i.StateManager,Object.defineProperty(i.StateManager.prototype,"created",{get:function(){return this._created}}),i.Signal=function(){},i.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!1,validateListener:function(t,e){if("function"!=typeof t)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",e))},_registerListener:function(t,e,s,n,r){var o,a=this._indexOfListener(t,s);if(-1!==a){if((o=this._bindings[a]).isOnce()!==e)throw new Error("You cannot add"+(e?"":"Once")+"() then add"+(e?"Once":"")+"() the same listener without removing the relationship first.")}else o=new i.SignalBinding(this,t,e,s,n,r),this._addBinding(o);return this.memorize&&this._prevParams&&o.execute(this._prevParams),o},_addBinding:function(t){this._bindings||(this._bindings=[]);var e=this._bindings.length;do{e--}while(this._bindings[e]&&t._priority<=this._bindings[e]._priority);this._bindings.splice(e+1,0,t)},_indexOfListener:function(t,e){if(!this._bindings)return-1;void 0===e&&(e=null);for(var i,s=this._bindings.length;s--;)if((i=this._bindings[s])._listener===t&&i.context===e)return s;return-1},has:function(t,e){return-1!==this._indexOfListener(t,e)},add:function(t,e,i){this.validateListener(t,"add");var s=[];if(arguments.length>3)for(var n=3;n3)for(var n=3;n=this.children.length?-1:this.getChildAt(t)},i.Group.prototype.create=function(t,e,i,s,n,r){void 0===n&&(n=!0);var o=new this.classType(this.game,t,e,i,s);return o.exists=n,o.visible=n,o.alive=n,this.add(o,!1,r)},i.Group.prototype.createMultiple=function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=!1),Array.isArray(e)||(e=[e]),Array.isArray(i)||(i=[i]);var o=this,a=[];return e.forEach(function(e){i.forEach(function(i){for(var h=0;hthis.children.length||-1===t&&-1===e)return!1;for(var a=new i.Rectangle(0,0,s,n),h=t*s,l=e*n,c=o;cthis.children.length-1&&(t=0),this.cursor)return this.cursorIndex=t,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.next=function(){if(this.cursor)return this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.previous=function(){if(this.cursor)return 0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.swap=function(t,e){this.swapChildren(t,e),this.updateZ()},i.Group.prototype.bringToTop=function(t){return t.parent===this&&this.getIndex(t)0&&(this.remove(t,!1,!0),this.addAt(t,0,!0)),t},i.Group.prototype.moveUp=function(t){if(t.parent===this&&this.getIndex(t)0){var e=this.getIndex(t),i=this.getAt(e-1);i&&this.swap(t,i)}return t},i.Group.prototype.xy=function(t,e,i){if(t<0||t>this.children.length)return-1;this.getChildAt(t).x=e,this.getChildAt(t).y=i},i.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},i.Group.prototype.getIndex=function(t){return this.children.indexOf(t)},i.Group.prototype.getByName=function(t){for(var e=0;e0))return!1;var r=e.length;return 1===r?0===s?t[e[0]]=i:1===s?t[e[0]]+=i:2===s?t[e[0]]-=i:3===s?t[e[0]]*=i:4===s&&(t[e[0]]/=i):2===r?0===s?t[e[0]][e[1]]=i:1===s?t[e[0]][e[1]]+=i:2===s?t[e[0]][e[1]]-=i:3===s?t[e[0]][e[1]]*=i:4===s&&(t[e[0]][e[1]]/=i):3===r?0===s?t[e[0]][e[1]][e[2]]=i:1===s?t[e[0]][e[1]][e[2]]+=i:2===s?t[e[0]][e[1]][e[2]]-=i:3===s?t[e[0]][e[1]][e[2]]*=i:4===s&&(t[e[0]][e[1]][e[2]]/=i):4===r&&(0===s?t[e[0]][e[1]][e[2]][e[3]]=i:1===s?t[e[0]][e[1]][e[2]][e[3]]+=i:2===s?t[e[0]][e[1]][e[2]][e[3]]-=i:3===s?t[e[0]][e[1]][e[2]][e[3]]*=i:4===s&&(t[e[0]][e[1]][e[2]][e[3]]/=i)),!0},i.Group.prototype.checkProperty=function(t,e,s,n){if(void 0===n&&(n=!1),this!==t.parent)return!1;var r=i.Utils.getProperty(t,e);return!(void 0===r&&n||r!==s)},i.Group.prototype.set=function(t,e,i,s,n,r,o){if(void 0===o&&(o=!1),e=e.split("."),void 0===s&&(s=!1),void 0===n&&(n=!1),(!1===s||s&&t.alive)&&(!1===n||n&&t.visible))return this.setProperty(t,e,i,r,o)},i.Group.prototype.setAll=function(t,e,i,s,n,r){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===r&&(r=!1),t=t.split("."),n=n||0;for(var o=0;o2){i=[];for(s=2;s2){n=[];for(a=2;a=e&&(t=e-1);var i=this.children[t];this.updateOnlyExistingChildren&&!i.exists||i.update()}},i.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y);for(var t=0;t2){s=[null];for(var n=2;n2){s=[null];for(var n=2;n2){s=[null];for(var n=2;ne[this._sortProperty]?1:t.ze[this._sortProperty]?-1:0},i.Group.prototype.iterate=function(t,e,s,n,r,o){if(0===this.children.length){if(s===i.Group.RETURN_TOTAL)return 0;if(s===i.Group.RETURN_ALL)return[]}var a=0;if(s===i.Group.RETURN_ALL)var h=[];for(var l=0;l0)return this.children[this.children.length-1]},i.Group.prototype.getBottom=function(){if(this.children.length>0)return this.children[0]},i.Group.prototype.getClosestTo=function(t,e,s){for(var n=Number.MAX_VALUE,r=0,o=null,a=0;an&&(!e||e.call(s,h,r))&&(n=r,o=h)}return o},i.Group.prototype.count=function(t,e){return this.iterate(t,e,i.Group.RETURN_TOTAL)},i.Group.prototype.countLiving=function(){return this.count("alive",!0)},i.Group.prototype.countDead=function(){return this.count("alive",!1)},i.Group.prototype.getRandom=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.children.length),0===e?null:i.ArrayUtils.getRandomItem(this.children,t,e)},i.Group.prototype.getRandomExists=function(t,e){var i=this.getAll("exists",!0,t,e);return this.game.rnd.pick(i)},i.Group.prototype.getAll=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=this.children.length);for(var n=[],r=i;r0&&t instanceof i.Group){do{t.add(this.children[0],e)}while(this.children.length>0);this.hash=[],this.cursor=null}return t},i.Group.prototype.removeAll=function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),0!==this.children.length){do{!e&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var s=this.removeChild(this.children[0]);this.removeFromHash(s),t&&s&&s.destroy(!0,i)}while(this.children.length>0);this.hash=[],this.cursor=null}},i.Group.prototype.removeBetween=function(t,e,i,s){if(void 0===e&&(e=this.children.length-1),void 0===i&&(i=!1),void 0===s&&(s=!1),0!==this.children.length){if(t>e||t<0||e>this.children.length)return!1;for(var n=e;n>=t;){!s&&this.children[n].events&&this.children[n].events.onRemovedFromGroup$dispatch(this.children[n],this);var r=this.removeChild(this.children[n]);this.removeFromHash(r),i&&r&&r.destroy(!0),this.cursor===this.children[n]&&(this.cursor=null),n--}this.updateZ()}},i.Group.prototype.scatter=function(t,e){null==t&&(t=this.game.world.bounds),this.forEach(function(e){e.position.set(t.randomX,t.randomY)},null,e)},i.Group.prototype.shuffle=function(){i.ArrayUtils.shuffle(this.children),this.updateZ()},i.Group.prototype.destroy=function(t,e){null===this.game||this.ignoreDestroy||(void 0===t&&(t=!0),void 0===e&&(e=!1),this.onDestroy.dispatch(this,t,e),this.removeAll(t),this.cursor=null,this.filters=null,this.pendingDestroy=!1,e||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(i.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,i.Group.RETURN_TOTAL)}}),Object.defineProperty(i.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(i.Group.prototype,"angle",{get:function(){return i.Math.radToDeg(this.rotation)},set:function(t){this.rotation=i.Math.degToRad(t)}}),Object.defineProperty(i.Group.prototype,"centerX",{get:function(){return this.getBounds(this.parent).centerX},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.halfWidth}}),Object.defineProperty(i.Group.prototype,"centerY",{get:function(){return this.getBounds(this.parent).centerY},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.halfHeight}}),Object.defineProperty(i.Group.prototype,"left",{get:function(){return this.getBounds(this.parent).left},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i}}),Object.defineProperty(i.Group.prototype,"right",{get:function(){return this.getBounds(this.parent).right},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.width}}),Object.defineProperty(i.Group.prototype,"top",{get:function(){return this.getBounds(this.parent).top},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i}}),Object.defineProperty(i.Group.prototype,"bottom",{get:function(){return this.getBounds(this.parent).bottom},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.height}}),i.World=function(t){i.Group.call(this,t,null,"__world",!1),this.bounds=new i.Rectangle(0,0,t.width,t.height),this.camera=null,this._definedSize=!1,this._width=t.width,this._height=t.height,this.game.state.onStateChange.add(this.stateChange,this)},i.World.prototype=Object.create(i.Group.prototype),i.World.prototype.constructor=i.World,i.World.prototype.boot=function(){this.camera=new i.Camera(this.game,0,0,0,this.game.width,this.game.height),this.game.stage.addChild(this),this.camera.boot()},i.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},i.World.prototype.setBounds=function(t,e,i,s){this._definedSize=!0,this._width=i,this._height=s,this.bounds.setTo(t,e,i,s),this.x=t,this.y=e,this.camera.bounds&&this.camera.bounds.setTo(t,e,Math.max(i,this.game.width),Math.max(s,this.game.height)),this.game.physics.setBoundsToWorld()},i.World.prototype.resize=function(t,e){this._definedSize&&(tthis.bounds.right&&(t.x=this.bounds.left)),n&&(t.y+t._currentBounds.heightthis.bounds.bottom&&(t.y=this.bounds.top))):(s&&t.x+ethis.bounds.right&&(t.x=this.bounds.left-e),n&&t.y+ethis.bounds.bottom&&(t.y=this.bounds.top-e))},i.World.prototype.wrapAll=function(t,e,i,s,n,r){t.forEach(this.wrap,this,e,i,s,n,r)},Object.defineProperty(i.World.prototype,"width",{get:function(){return this.bounds.width},set:function(t){t1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.dropFrames?this.rendersThisFrame=0:(this.updateRender(this.time.slowMotion*this.time.desiredFps),this.rendersThisFrame=1);else{var e=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*e,this.time.elapsed),0);var i=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/e),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame)),this.forceSingleRender?this.rendersThisFrame=1:this.rendersThisFrame=Math.min(1,this.updatesThisFrame);this._deltaTime>=e&&(this._deltaTime-=e,this.currentUpdateID=i,this.updateLogic(this.time.desiredFpsMult),i++,!this.forceSingleUpdate||1!==i);)this.time.refresh();i>this._lastCount?this._spiraling++:i0&&this.updateRender(this._deltaTime/e)}}},updateLogic:function(t){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(t),this.debug.preUpdate(),this.input.pauseUpdate()):(this.stepping&&(this.pendingStep=!0),this.time.countUpdate(),this.scale.preUpdate(),this.debug.preUpdate(),this.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(t),this.plugins.preUpdate(t),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(),this.sound.update(),this.input.update(),this.physics.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate()),this.stage.updateTransform()},updateRender:function(t){this.lockRender||(this.time.countRender(),this.state.preRender(t),this.renderType!==i.HEADLESS&&(this.renderer.render(this.stage),this.plugins.render(t),this.state.render(t)),this.plugins.postRender(t))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.debug.destroy&&this.debug.destroy(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.plugins.destroy(),this.debug=null,this.state=null,this.sound=null,this.scale=null,this.stage=null,this.input=null,this.physics=null,this.plugins=null,this.cache=null,this.load=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),i.Canvas.removeFromDOM(this.canvas),PIXI.defaultRenderer=null,i.GAMES[this.id]=null},gamePaused:function(t){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.muteOnPause&&this.sound.setMute(),this.onPause.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(t){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.muteOnPause&&this.sound.unsetMute(),this.onResume.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(t){this.onBlur.dispatch(t),this.stage.disableVisibilityChange||this.gamePaused(t)},focusGain:function(t){this.onFocus.dispatch(t),this.stage.disableVisibilityChange||this.gameResumed(t)}},i.Game.prototype.constructor=i.Game,Object.defineProperty(i.Game.prototype,"paused",{get:function(){return this._paused},set:function(t){!0===t?(!1===this._paused&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),i.Input=function(t){this.game=t,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.customCandidateHandler=null,this.customCandidateHandlerContext=null,this.pollRate=0,this.enabled=!0,this.multiInputOverride=i.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.touchLockCallbacks=[],this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new i.ArraySet,this._localPoint=new i.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},i.Input.MOUSE_OVERRIDES_TOUCH=0,i.Input.TOUCH_OVERRIDES_MOUSE=1,i.Input.MOUSE_TOUCH_COMBINE=2,i.Input.MAX_POINTERS=10,i.Input.prototype={boot:function(){this.mousePointer=new i.Pointer(this.game,0,i.PointerMode.CURSOR),this.addPointer(),this.addPointer(),this.mouse=new i.Mouse(this.game),this.touch=new i.Touch(this.game),this.mspointer=new i.MSPointer(this.game),i.Keyboard&&(this.keyboard=new i.Keyboard(this.game)),i.Gamepad&&(this.gamepad=new i.Gamepad(this.game)),this.onDown=new i.Signal,this.onUp=new i.Signal,this.onTap=new i.Signal,this.onHold=new i.Signal,this.scale=new i.Point(1,1),this.speed=new i.Point,this.position=new i.Point,this._oldPosition=new i.Point,this.circle=new i.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=i.CanvasPool.create(this,1,1),this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.game.device.mspointer||this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var t=this;this._onClickTrampoline=function(e){t.onClickTrampoline(e)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],i.CanvasPool.remove(this),this.game.canvas.removeEventListener("click",this._onClickTrampoline)},setInteractiveCandidateHandler:function(t,e){this.customCandidateHandler=t,this.customCandidateHandlerContext=e},addMoveCallback:function(t,e){this.moveCallbacks.push({callback:t,context:e})},addTouchLockCallback:function(t,e,i){void 0===i&&(i=!1),this.touchLockCallbacks.push({callback:t,context:e,onEnd:i})},removeTouchLockCallback:function(t,e){for(var i=this.touchLockCallbacks.length;i--;)if(this.touchLockCallbacks[i].callback===t&&this.touchLockCallbacks[i].context===e)return this.touchLockCallbacks.splice(i,1),!0;return!1},executeTouchLockCallbacks:function(t,e){for(var i=this.touchLockCallbacks.length;i--;){var s=this.touchLockCallbacks[i];s.onEnd===t&&s.callback.call(s.context,this,e)&&this.touchLockCallbacks.splice(i,1)}},deleteMoveCallback:function(t,e){for(var i=this.moveCallbacks.length;i--;)if(this.moveCallbacks[i].callback===t&&this.moveCallbacks[i].context===e)return void this.moveCallbacks.splice(i,1)},addPointer:function(){if(this.pointers.length>=i.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+i.Input.MAX_POINTERS+" pointers reached."),null;var t=this.pointers.length+1,e=new i.Pointer(this.game,t,i.PointerMode.CONTACT);return this.pointers.push(e),this["pointer"+t]=e,e},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(t);if(!this.pointer2.active)return this.pointer2.start(t);for(var e=2;e0;i++)this.pointers[i].active&&e--;return t-e},getPointer:function(t){void 0===t&&(t=!1);for(var e=0;e=o&&this.game.camera.x+e.x=a&&this.game.camera.y+e.y=o&&this._localPoint.x=a&&this._localPoint.y=o&&this._localPoint.x=a&&this._localPoint.y0&&this._pollCounterthis.game.time.time},justReleased:function(t){return t=t||250,this.isUp&&this.timeUp+t>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},i.DeviceButton.prototype.constructor=i.DeviceButton,Object.defineProperty(i.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),i.Pointer=function(t,e,s){this.game=t,this.id=e,this.type=i.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.pointerMode=s||i.PointerMode.CURSOR|i.PointerMode.CONTACT,this.target=null,this.button=null,this.leftButton=new i.DeviceButton(this,i.Pointer.LEFT_BUTTON),this.middleButton=new i.DeviceButton(this,i.Pointer.MIDDLE_BUTTON),this.rightButton=new i.DeviceButton(this,i.Pointer.RIGHT_BUTTON),this.backButton=new i.DeviceButton(this,i.Pointer.BACK_BUTTON),this.forwardButton=new i.DeviceButton(this,i.Pointer.FORWARD_BUTTON),this.eraserButton=new i.DeviceButton(this,i.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===e,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.interactiveCandidates=[],this.active=!1,this.dirty=!1,this.position=new i.Point,this.positionDown=new i.Point,this.positionUp=new i.Point,this.circle=new i.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},i.Pointer.NO_BUTTON=0,i.Pointer.LEFT_BUTTON=1,i.Pointer.RIGHT_BUTTON=2,i.Pointer.MIDDLE_BUTTON=4,i.Pointer.BACK_BUTTON=8,i.Pointer.FORWARD_BUTTON=16,i.Pointer.ERASER_BUTTON=32,i.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.start(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.start(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.start(e),t===i.Mouse.BACK_BUTTON&&this.backButton.start(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.start(e)},processButtonsUp:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.stop(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.stop(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(e),t===i.Mouse.BACK_BUTTON&&this.backButton.stop(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(e)},processButtonsUpDown:function(t,e){var s="down"===e.type.toLowerCase().substr(-4),n="move"===e.type.toLowerCase().substr(-4);void 0!==t?(s&&1===t&&e.ctrlKey&&(t=2),this.leftButton.startStop(i.Pointer.LEFT_BUTTON&t,e),this.rightButton.startStop(i.Pointer.RIGHT_BUTTON&t,e),this.middleButton.startStop(i.Pointer.MIDDLE_BUTTON&t,e),this.backButton.startStop(i.Pointer.BACK_BUTTON&t,e),this.forwardButton.startStop(i.Pointer.FORWARD_BUTTON&t,e),this.eraserButton.startStop(i.Pointer.ERASER_BUTTON&t,e)):void 0!==e.button?s&&e.ctrlKey&&0===e.button?this.rightButton.start(e):s?this.processButtonsDown(e.button,e):n||this.processButtonsUp(e.button,e):s?e.ctrlKey?this.rightButton.start(e):this.leftButton.start(e):(this.leftButton.stop(e),this.rightButton.stop(e))},updateButtons:function(t){this.button=t.button,this.processButtonsUpDown(t.buttons,t),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(t){var e=this.game.input;return t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.isMouse?this.updateButtons(t):(this.isDown=!0,this.isUp=!1),this.active=!0,this.withinGame=!0,this.dirty=!1,this._history=[],this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(t,!0),this.positionDown.setTo(this.x,this.y),(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.x=this.x,e.y=this.y,e.position.setTo(this.x,this.y),e.onDown.dispatch(this,t),e.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){var t=this.game.input;this.active&&(this.dirty&&(t.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),!1===this._holdSent&&this.duration>=t.holdRate&&((t.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||t.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||t.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===t.totalActivePointers)&&t.onHold.dispatch(this),this._holdSent=!0),t.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+t.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>t.recordLimit&&this._history.shift()))},move:function(t,e){var s=this.game.input;if(!s.pollLocked){void 0===e&&(e=!1),void 0!==t.button&&(this.button=t.button),this.isMouse&&this.updateButtons(t),this.clientX=t.clientX,this.clientY=t.clientY,this.pageX=t.pageX,this.pageY=t.pageY,this.screenX=t.screenX,this.screenY=t.screenY,this.isMouse&&s.mouse.locked&&!e&&(this.rawMovementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.rawMovementY=t.movementY||t.mozMovementY||t.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*s.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*s.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(s.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||s.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||s.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===s.totalActivePointers)&&(s.activePointer=this,s.x=this.x,s.y=this.y,s.position.setTo(s.x,s.y),s.circle.x=s.x,s.circle.y=s.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY);for(var n=s.moveCallbacks.length;n--;)s.moveCallbacks[n].callback.call(s.moveCallbacks[n].context,this,this.x,this.y,e);return null===this.targetObject||this.game.paused&&!this.targetObject.noPause||!0!==this.targetObject.isDragged?s.interactiveItems.total>0&&this.processInteractiveObjects(e):!1===this.targetObject.update(this)&&(this.targetObject=null),this}},processInteractiveObjects:function(t){var e=0,i=-1,s=null,n=this.game.input.interactiveItems.first;for(this.interactiveCandidates=[];n;)n.checked=!1,!n.validForInput(i,e,!1)||this.game.paused&&!n.sprite.noPause||(n.checked=!0,(t&&n.checkPointerDown(this,!0)||!t&&n.checkPointerOver(this,!0))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n))),n=this.game.input.interactiveItems.next;for(n=this.game.input.interactiveItems.first;n;)!n.checked&&n.validForInput(i,e,!0)&&(t&&n.checkPointerDown(this,!1)||!t&&n.checkPointerOver(this,!1))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n)),n=this.game.input.interactiveItems.next;return this.game.input.customCandidateHandler&&(s=this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext,this,this.interactiveCandidates,s)),this.swapTarget(s,!1),null!==this.targetObject},swapTarget:function(t,e){void 0===e&&(e=!1),null===t?this.targetObject&&(this.targetObject._pointerOutHandler(this,e),this.targetObject=null):null===this.targetObject?(this.targetObject=t,t._pointerOverHandler(this,e)):this.targetObject===t?!1===t.update(this)&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this,e),this.targetObject=t,this.targetObject._pointerOverHandler(this,e))},leave:function(t){this.withinGame=!1,this.move(t,!1)},stop:function(t){var e=this.game.input;{if(!this._stateReset||!this.withinGame)return this.timeUp=this.game.time.time,(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.onUp.dispatch(this,t),this.duration>=0&&this.duration<=e.tapRate&&(this.timeUp-this.previousTapTime0&&(this.active=!1),this.withinGame=this.game.scale.bounds.contains(t.pageX,t.pageY),this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),!1===this.isMouse&&e.currentPointers--,e.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this;t.preventDefault()}},justPressed:function(t){return t=t||this.game.input.justPressedRate,!0===this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||this.game.input.justReleasedRate,this.isUp&&this.timeUp+t>this.game.time.time},addClickTrampoline:function(t,e,i,s){if(this.isDown){for(var n=this._clickTrampolines=this._clickTrampolines||[],r=0;rt||this.priorityID===t&&this.sprite.renderOrderID>e))},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(t){return t=t||0,this._pointerData[t].x},pointerY:function(t){return t=t||0,this._pointerData[t].y},pointerDown:function(t){return t=t||0,this._pointerData[t].isDown},pointerUp:function(t){return t=t||0,this._pointerData[t].isUp},pointerTimeDown:function(t){return t=t||0,this._pointerData[t].timeDown},pointerTimeUp:function(t){return t=t||0,this._pointerData[t].timeUp},pointerOver:function(t){if(!this.enabled)return!1;if(void 0===t){for(var e=0;e<10;e++)if(this._pointerData[e].isOver)return!0;return!1}return this._pointerData[t].isOver},pointerOut:function(t){if(!this.enabled)return!1;if(void 0!==t)return this._pointerData[t].isOut;for(var e=0;e<10;e++)if(this._pointerData[e].isOut)return!0},pointerTimeOver:function(t){return t=t||0,this._pointerData[t].timeOver},pointerTimeOut:function(t){return t=t||0,this._pointerData[t].timeOut},pointerDragged:function(t){return t=t||0,this._pointerData[t].isDragged},checkPointerDown:function(t,e){return!!(t.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectClick)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPointerOver:function(t,e){return!!(this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectOver)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPixel:function(t,e,i){if(this.sprite.texture.baseTexture.source){if(null===t&&null===e){this.game.input.getLocalPosition(this.sprite,i,this._tempPoint);var t=this._tempPoint.x,e=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(t-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(e-=-this.sprite.texture.frame.height*this.sprite.anchor.y),t+=this.sprite.texture.frame.x,e+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(t-=this.sprite.texture.trim.x,e-=this.sprite.texture.trim.y,tthis.sprite.texture.crop.right||ethis.sprite.texture.crop.bottom))return this._dx=t,this._dy=e,!1;if(this._dx=t,this._dy=e,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,t,e,1,1,0,0,1,1),this.game.input.hitContext.getImageData(0,0,1,1).data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(t){if(null!==this.sprite&&void 0!==this.sprite.parent)return this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this._pendingDrag?(this._dragDistancePass||(this._dragDistancePass=i.Math.distance(t.x,t.y,this.downPoint.x,this.downPoint.y)>=this.dragDistanceThreshold),this._dragDistancePass&&this._dragTimePass&&this.startDrag(t),!0):this.draggable&&this._draggedPointerID===t.id?this.updateDrag(t,!1):this._pointerData[t.id].isOver?this.checkPointerOver(t)?(this._pointerData[t.id].x=t.x-this.sprite.x,this._pointerData[t.id].y=t.y-this.sprite.y,!0):(this._pointerOutHandler(t),!1):void 0:(this._pointerOutHandler(t),!1)},_pointerOverHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];if(!1===i.isOver||t.dirty){var s=!1===i.isOver;i.isOver=!0,i.isOut=!1,i.timeOver=this.game.time.time,i.x=t.x-this.sprite.x,i.y=t.y-this.sprite.y,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),!e&&s&&this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,t),this.sprite.parent&&this.sprite.parent.onChildInputOver&&this.sprite.parent.onChildInputOver.dispatch(this.sprite,t)}}},_pointerOutHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];i.isOver=!1,i.isOut=!0,i.timeOut=this.game.time.time,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="",this._setHandCursor=!1),!e&&this.sprite&&this.sprite.events&&(this.sprite.events.onInputOut$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputOut&&this.sprite.parent.onChildInputOut.dispatch(this.sprite,t))}},_touchedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(!e.isDown&&e.isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,t))return;if(e.isDown=!0,e.isUp=!1,e.timeDown=this.game.time.time,this.downPoint.set(t.x,t.y),t.dirty=!0,this.sprite&&this.sprite.events&&(this.sprite.events.onInputDown$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputDown&&this.sprite.parent.onChildInputDown.dispatch(this.sprite,t),null===this.sprite))return;this.draggable&&!1===this.isDragged&&(0===this.dragTimeThreshold&&0===this.dragDistanceThreshold?this.startDrag(t):(this._pendingDrag=!0,this._dragDistancePass=0===this.dragDistanceThreshold,this.dragTimeThreshold>0?(this._dragTimePass=!1,this.game.time.events.add(this.dragTimeThreshold,this.dragTimeElapsed,this,t)):this._dragTimePass=!0)),this.bringToTop&&this.sprite.bringToTop()}}},dragTimeElapsed:function(t){this._dragTimePass=!0,this._pendingDrag&&this.sprite&&this._dragDistancePass&&this.startDrag(t)},_releasedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(e.isDown&&t.isUp){e.isDown=!1,e.isUp=!0,e.timeUp=this.game.time.time,e.downDuration=e.timeUp-e.timeDown;var i=this.checkPointerOver(t);this.sprite&&this.sprite.events&&(this.dragStopBlocksInputUp&&(!this.dragStopBlocksInputUp||this.draggable&&this.isDragged&&this._draggedPointerID===t.id)||this.sprite.events.onInputUp$dispatch(this.sprite,t,i),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputUp&&this.sprite.parent.onChildInputUp.dispatch(this.sprite,t,i),i&&(i=this.checkPointerOver(t))),e.isOver=i,!i&&this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),t.dirty=!0,this._pendingDrag=!1,this.draggable&&this.isDragged&&this._draggedPointerID===t.id&&this.stopDrag(t)}}},updateDrag:function(t,e){if(void 0===e&&(e=!1),t.isUp)return this.stopDrag(t),!1;var i=this.globalToLocal(t);if(this.sprite.fixedToCamera)var s=this.game.camera.scale.x*i.x+this._dragPoint.x+this.dragOffset.x,n=this.game.camera.scale.y*i.y+this._dragPoint.y+this.dragOffset.y;else var s=i.x+this._dragPoint.x+this.dragOffset.x,n=i.y+this._dragPoint.y+this.dragOffset.y;if(this.sprite.fixedToCamera)this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=s-this.game.camera.x),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=n-this.game.camera.y),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y));else{var r=this.game.camera.x-this._pointerData[t.id].camX,o=this.game.camera.y-this._pointerData[t.id].camY;this.allowHorizontalDrag&&(this.sprite.x=s+r),this.allowVerticalDrag&&(this.sprite.y=n+o),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.x,this.sprite.y))}return this.sprite.events.onDragUpdate.dispatch(this.sprite,t,s,n,this.snapPoint,e),!0},justOver:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOver&&this.overDuration(t)this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.ythis.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.leftthis.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.xthis.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.ythis.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.leftthis.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},i.InputHandler.prototype.constructor=i.InputHandler,i.Gamepad=function(t){this.game=t,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!==navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this)]},i.Gamepad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},start:function(){if(!this._active){this._active=!0;var t=this;this._onGamepadConnected=function(e){return t.onGamepadConnected(e)},this._onGamepadDisconnected=function(e){return t.onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(t){var e=t.gamepad;this._rawPads.push(e),this._gamepads[e.index].connect(e)},onGamepadDisconnected:function(t){var e=t.gamepad;for(var i in this._rawPads)this._rawPads[i].index===e.index&&this._rawPads.splice(i,1);this._gamepads[e.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(this._active){if(navigator.getGamepads)t=navigator.getGamepads();else if(navigator.webkitGetGamepads)t=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var t=navigator.webkitGamepads();if(t){this._rawPads=[];for(var e=!1,i=0;i0&&s>this.deadZone||s<0&&s<-this.deadZone?this.processAxisChange(i,s):this.processAxisChange(i,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(t){var e=!this.connected;this.connected=!0,this.index=t.index,this._rawPad=t,this._buttons=[],this._buttonsLen=t.buttons.length,this._axes=[],this._axesLen=t.axes.length;for(var s=0;sthis.maxHealth&&(this.health=this.maxHealth),this},heal:function(t){return this.alive&&(this.health+=t,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},i.Component.InCamera=function(){},i.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},i.Component.InputEnabled=function(){},i.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(t){t?null===this.input?(this.input=new i.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},i.Component.InWorld=function(){},i.Component.InWorld.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(this.autoCull||this.checkWorldBounds){if(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull)if(this.game.world.camera.view.intersects(this._bounds))this.renderable=!0,this.game.world.camera.totalInView++;else if(this.renderable=!1,this.outOfCameraBoundsKill)return this.kill(),!1;if(this.checkWorldBounds)if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1}return!0},i.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,outOfCameraBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},i.Component.LifeSpan=function(){},i.Component.LifeSpan.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):!(this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0))||(this.kill(),!1)},i.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(t){return void 0===t&&(t=100),this.alive=!0,this.exists=!0,this.visible=!0,"function"==typeof this.setHealth&&this.setHealth(t),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},i.Component.LoadTexture=function(){},i.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(t,e,s){t===i.PENDING_ATLAS?(t=e,e=0):e=e||0,(s||void 0===s)&&this.animations&&this.animations.stop(),this.key=t,this.customRender=!1;var n=this.game.cache,r=!0,o=!this.texture.baseTexture.scaleMode;if(i.RenderTexture&&t instanceof i.RenderTexture)this.key=t.key,this.setTexture(t);else if(i.BitmapData&&t instanceof i.BitmapData)this.customRender=!0,this.setTexture(t.texture),r=n.hasFrameData(t.key,i.Cache.BITMAPDATA)?!this.animations.loadFrameData(n.getFrameData(t.key,i.Cache.BITMAPDATA),e):!this.animations.loadFrameData(t.frameData,0);else if(i.Video&&t instanceof i.Video){this.customRender=!0;var a=t.texture.valid;this.setTexture(t.texture),this.setFrame(t.texture.frame.clone()),t.onChangeSource.add(this.resizeFrame,this),this.texture.valid=a}else if(i.Tilemap&&t instanceof i.TilemapLayer)this.setTexture(PIXI.Texture.fromCanvas(t.canvas));else if(t instanceof PIXI.Texture)this.setTexture(t);else{var h=n.getImage(t,!0);this.key=h.key,this.setTexture(new PIXI.Texture(h.base)),this.texture.baseTexture.skipRender="__default"===t,r=!this.animations.loadFrameData(h.frameData,e)}r&&(this._frame=i.Rectangle.clone(this.texture.frame)),o||(this.texture.baseTexture.scaleMode=1)},setFrame:function(t){this._frame=t,this.texture.frame.x=t.x,this.texture.frame.y=t.y,this.texture.frame.width=t.width,this.texture.frame.height=t.height,this.texture.crop.x=t.x,this.texture.crop.y=t.y,this.texture.crop.width=t.width,this.texture.crop.height=t.height,t.trimmed?(this.texture.trim?(this.texture.trim.x=t.spriteSourceSizeX,this.texture.trim.y=t.spriteSourceSizeY,this.texture.trim.width=t.sourceSizeW,this.texture.trim.height=t.sourceSizeH):this.texture.trim={x:t.spriteSourceSizeX,y:t.spriteSourceSizeY,width:t.sourceSizeW,height:t.sourceSizeH},this.texture.width=t.sourceSizeW,this.texture.height=t.sourceSizeH,this.texture.frame.width=t.sourceSizeW,this.texture.frame.height=t.sourceSizeH):!t.trimmed&&this.texture.trim&&(this.texture.trim=null),t.rotated&&(this.texture.rotated=!0),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(t,e,i){this.texture.frame.resize(e,i),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(t){this.animations.frame=t}},frameName:{get:function(){return this.animations.frameName},set:function(t){this.animations.frameName=t}}},i.Component.Overlap=function(){},i.Component.Overlap.prototype={overlap:function(t){return i.Rectangle.intersects(this.getBounds(),t.getBounds())}},i.Component.PhysicsBody=function(){},i.Component.PhysicsBody.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):this.fresh&&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.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,this.preUpdateChildren(),!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!(!this._exists||!this.parent.exists)||(this.renderOrderID=-1,!1))},i.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},i.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(t){this.position.x=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},i.Component.Reset=function(){},i.Component.Reset.prototype.reset=function(t,e,i){return void 0===i&&(i=1),this.world.set(t,e),this.position.set(t,e),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=i),this.components.PhysicsBody&&this.body&&this.body.reset(t,e,!1,!1),this},i.Component.ScaleMinMax=function(){},i.Component.ScaleMinMax.prototype={transformCallback:null,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(t){this.scaleMin&&(t.athis.scaleMax.x&&(t.a=this.scaleMax.x),t.d>this.scaleMax.y&&(t.d=this.scaleMax.y))},setScaleMinMax:function(t,e,s,n){void 0===e?e=s=n=t:void 0===s&&(s=n=e,e=t),null===t?this.scaleMin=null:this.scaleMin?this.scaleMin.set(t,e):this.scaleMin=new i.Point(t,e),null===s?this.scaleMax=null:this.scaleMax?this.scaleMax.set(s,n):this.scaleMax=new i.Point(s,n),null===this.scaleMin?this.transformCallback=null:(this.transformCallback=this.checkTransform,this.transformCallbackContext=this)}},i.Component.Smoothed=function(){},i.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(t){t?this.texture&&(this.texture.baseTexture.scaleMode=0,this.texture.baseTexture.dirty()):this.texture&&(this.texture.baseTexture.scaleMode=1,this.texture.baseTexture.dirty())}}},i.GameObjectFactory=function(t){this.game=t,this.world=this.game.world},i.GameObjectFactory.prototype={existing:function(t){return this.world.add(t)},weapon:function(t,e,s,n,r){var o=this.game.plugins.add(i.Weapon);return r&&(o.bulletClass=r),o.createBullets(t,e,s,n),o},image:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Image(this.game,t,e,s,n))},sprite:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Sprite(this.game,t,e,s,n))},creature:function(t,e,s,n,r){void 0===r&&(r=this.world);var o=new i.Creature(this.game,t,e,s,n);return r.add(o),o},tween:function(t){return this.game.tweens.create(t)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},physicsGroup:function(t,e,s,n){return new i.Group(this.game,e,s,n,!0,t)},spriteBatch:function(t,e,s){return void 0===t&&(t=null),void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},tileSprite:function(t,e,s,n,r,o,a){return void 0===a&&(a=this.world),a.add(new i.TileSprite(this.game,t,e,s,n,r,o))},rope:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.Rope(this.game,t,e,s,n,r))},text:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Text(this.game,t,e,s,n))},button:function(t,e,s,n,r,o,a,h,l,c){return void 0===c&&(c=this.world),c.add(new i.Button(this.game,t,e,s,n,r,o,a,h,l))},graphics:function(t,e,s){return void 0===s&&(s=this.world),s.add(new i.Graphics(this.game,t,e))},emitter:function(t,e,s){return this.game.particles.add(new i.Particles.Arcade.Emitter(this.game,t,e,s))},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.BitmapText(this.game,t,e,s,n,r))},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},video:function(t,e){return new i.Video(this.game,t,e)},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t},plugin:function(t){return this.game.plugins.add(t)}},i.GameObjectFactory.prototype.constructor=i.GameObjectFactory,i.GameObjectCreator=function(t){this.game=t,this.world=this.game.world},i.GameObjectCreator.prototype={image:function(t,e,s,n){return new i.Image(this.game,t,e,s,n)},sprite:function(t,e,s,n){return new i.Sprite(this.game,t,e,s,n)},tween:function(t){return new i.Tween(t,this.game,this.game.tweens)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},spriteBatch:function(t,e,s){return void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},tileSprite:function(t,e,s,n,r,o){return new i.TileSprite(this.game,t,e,s,n,r,o)},rope:function(t,e,s,n,r){return new i.Rope(this.game,t,e,s,n,r)},text:function(t,e,s,n){return new i.Text(this.game,t,e,s,n)},button:function(t,e,s,n,r,o,a,h,l){return new i.Button(this.game,t,e,s,n,r,o,a,h,l)},graphics:function(t,e){return new i.Graphics(this.game,t,e)},emitter:function(t,e,s){return new i.Particles.Arcade.Emitter(this.game,t,e,s)},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return new i.BitmapText(this.game,t,e,s,n,r,o)},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t}},i.GameObjectCreator.prototype.constructor=i.GameObjectCreator,i.Sprite=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.SPRITE,this.physicsType=i.SPRITE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Sprite.prototype=Object.create(PIXI.Sprite.prototype),i.Sprite.prototype.constructor=i.Sprite,i.Component.Core.install.call(i.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Sprite.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Sprite.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Sprite.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Sprite.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Sprite.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Image=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.IMAGE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Image.prototype=Object.create(PIXI.Sprite.prototype),i.Image.prototype.constructor=i.Image,i.Component.Core.install.call(i.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","ScaleMinMax","Smoothed"]),i.Image.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Image.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Image.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Image.prototype.preUpdate=function(){return!(!this.preUpdateInWorld()||!this.preUpdateLifeSpan())&&this.preUpdateCore()},i.Button=function(t,e,s,n,r,o,a,h,l,c){e=e||0,s=s||0,n=n||null,r=r||null,o=o||this,i.Image.call(this,t,e,s,n,h),this.type=i.BUTTON,this.physicsType=i.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new i.Signal,this.onInputOut=new i.Signal,this.onInputDown=new i.Signal,this.onInputUp=new i.Signal,this.onOverMouseOnly=!0,this.justReleasedPreventsOver=i.PointerMode.CONTACT,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(a,h,l,c),null!==r&&this.onInputUp.add(r,o),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this)},i.Button.prototype=Object.create(i.Image.prototype),i.Button.prototype.constructor=i.Button;return i.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},i.Button.prototype.setStateFrame=function(t,e,i){var s="_on"+t+"Frame";null!==e?(this[s]=e,i&&this.changeStateFrame(t)):this[s]=null},i.Button.prototype.changeStateFrame=function(t){if(this.freezeFrames)return!1;var e=this["_on"+t+"Frame"];return"string"==typeof e?(this.frameName=e,!0):"number"==typeof e&&(this.frame=e,!0)},i.Button.prototype.setFrames=function(t,e,i,s){this.setStateFrame("Over",t,this.input.pointerOver()),this.setStateFrame("Out",e,!this.input.pointerOver()),this.setStateFrame("Down",i,this.input.pointerDown()),this.setStateFrame("Up",s,this.input.pointerUp())},i.Button.prototype.setStateSound=function(t,e,s){var n="on"+t+"Sound",r="on"+t+"SoundMarker";e instanceof i.Sound||e instanceof i.AudioSprite?(this[n]=e,this[r]="string"==typeof s?s:""):(this[n]=null,this[r]="")},i.Button.prototype.playStateSound=function(t){var e=this["on"+t+"Sound"];if(e){var i=this["on"+t+"SoundMarker"];return e.play(i),!0}return!1},i.Button.prototype.setSounds=function(t,e,i,s,n,r,o,a){this.setStateSound("Over",t,e),this.setStateSound("Out",n,r),this.setStateSound("Down",i,s),this.setStateSound("Up",o,a)},i.Button.prototype.setOverSound=function(t,e){this.setStateSound("Over",t,e)},i.Button.prototype.setOutSound=function(t,e){this.setStateSound("Out",t,e)},i.Button.prototype.setDownSound=function(t,e){this.setStateSound("Down",t,e)},i.Button.prototype.setUpSound=function(t,e){this.setStateSound("Up",t,e)},i.Button.prototype.onInputOverHandler=function(t,e){e.justReleased()&&(this.justReleasedPreventsOver&e.pointerMode)===e.pointerMode||(this.changeStateFrame("Over"),this.onOverMouseOnly&&!e.isMouse||(this.playStateSound("Over"),this.onInputOver&&this.onInputOver.dispatch(this,e)))},i.Button.prototype.onInputOutHandler=function(t,e){this.changeStateFrame("Out"),this.playStateSound("Out"),this.onInputOut&&this.onInputOut.dispatch(this,e)},i.Button.prototype.onInputDownHandler=function(t,e){this.changeStateFrame("Down"),this.playStateSound("Down"),this.onInputDown&&this.onInputDown.dispatch(this,e)},i.Button.prototype.onInputUpHandler=function(t,e,i){this.playStateSound("Up"),this.onInputUp&&this.onInputUp.dispatch(this,e,i),this.freezeFrames||(!0===this.forceOut||(this.forceOut&e.pointerMode)===e.pointerMode?this.changeStateFrame("Out"):this.changeStateFrame("Up")||(i?this.changeStateFrame("Over"):this.changeStateFrame("Out")))},i.SpriteBatch=function(t,e,s,n){void 0!==e&&null!==e||(e=t.world),i.Group.call(this,t,e,s,n),this.type=i.SPRITEBATCH,this.fastSpriteBatch=null,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.Group.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||(this.fastSpriteBatch=new PIXI.WebGLFastSpriteBatch(t.gl),this.ready=!0),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n=0&&t<=this.width&&e>=0&&e<=this.height&&(i.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|n<<8|s:this.pixels[e*this.width+t]=s<<24|n<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,s){s||(s=i.Color.createColor());var n=~~(t+e*this.width);return n*=4,s.r=this.data[n],s.g=this.data[++n],s.b=this.data[++n],s.a=this.data[++n],s},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,s,n,r){return i.Color.unpackPixel(this.getPixel32(t,e),s,n,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=i.Color.createColor(),s=0,n=0,r=1,o=!1;1===t?(r=-1,n=this.height):3===t&&(r=-1,s=this.width);do{i.Color.unpackPixel(this.getPixel32(s,n),e),0===t||1===t?++s===this.width&&(s=0,((n+=r)>=this.height||n<=0)&&(o=!0)):2!==t&&3!==t||++n===this.height&&(n=0,((s+=r)>=this.width||s<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=s,e.y=n,e},getBounds:function(t){return void 0===t&&(t=new i.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,s,n,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),t instanceof i.RenderTexture&&(t=t.getCanvas()),this._image=t,t instanceof i.Sprite||t instanceof i.Image||t instanceof i.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof i.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==s&&null!==s||(s=0),n&&(this._size.x=n),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=s),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+s,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var n=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===n.a||0===n.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=n.tx,o=n.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),s&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(n.a,n.b,n.c,n.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,s){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,s),t.type===i.GROUP&&t.exists)this.drawGroup(t,e,s);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var n=0;ne.width&&(n=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,s),this._circle=new i.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,n,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),i.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this},copyBitmapData:function(t,e,i){t.update();for(var s,n=0;n80*s){h=c=t[0],l=u=t[1];for(var g=s;gc&&(c=d),p>u&&(u=p);f=Math.max(c-h,u-l)}return i.EarCut.earcutLinked(o,a,s,h,l,f),a},i.EarCut.linkedList=function(t,e,s,n,r){var o,a,h,l=0;for(o=e,a=s-n;o0)for(o=e;o=e;o-=n)h=i.EarCut.insertNode(o,t[o],t[o+1],h);return h},i.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var s,n=t;do{if(s=!1,n.steiner||!i.EarCut.equals(n,n.next)&&0!==i.EarCut.area(n.prev,n,n.next))n=n.next;else{if(i.EarCut.removeNode(n),(n=e=n.prev)===n.next)return null;s=!0}}while(s||n!==e);return e},i.EarCut.earcutLinked=function(t,e,s,n,r,o,a){if(t){!a&&o&&i.EarCut.indexCurve(t,n,r,o);for(var h,l,c=t;t.prev!==t.next;)if(h=t.prev,l=t.next,o?i.EarCut.isEarHashed(t,n,r,o):i.EarCut.isEar(t))e.push(h.i/s),e.push(t.i/s),e.push(l.i/s),i.EarCut.removeNode(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?(t=i.EarCut.cureLocalIntersections(t,e,s),i.EarCut.earcutLinked(t,e,s,n,r,o,2)):2===a&&i.EarCut.splitEarcut(t,e,s,n,r,o):i.EarCut.earcutLinked(i.EarCut.filterPoints(t),e,s,n,r,o,1);break}}},i.EarCut.isEar=function(t){var e=t.prev,s=t,n=t.next;if(i.EarCut.area(e,s,n)>=0)return!1;for(var r=t.next.next;r!==t.prev;){if(i.EarCut.pointInTriangle(e.x,e.y,s.x,s.y,n.x,n.y,r.x,r.y)&&i.EarCut.area(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},i.EarCut.isEarHashed=function(t,e,s,n){var r=t.prev,o=t,a=t.next;if(i.EarCut.area(r,o,a)>=0)return!1;for(var h=r.xo.x?r.x>a.x?r.x:a.x:o.x>a.x?o.x:a.x,u=r.y>o.y?r.y>a.y?r.y:a.y:o.y>a.y?o.y:a.y,d=i.EarCut.zOrder(h,l,e,s,n),p=i.EarCut.zOrder(c,u,e,s,n),f=t.nextZ;f&&f.z<=p;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=d;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0},i.EarCut.cureLocalIntersections=function(t,e,s){var n=t;do{var r=n.prev,o=n.next.next;i.EarCut.intersects(r,n,n.next,o)&&i.EarCut.locallyInside(r,o)&&i.EarCut.locallyInside(o,r)&&(e.push(r.i/s),e.push(n.i/s),e.push(o.i/s),i.EarCut.removeNode(n),i.EarCut.removeNode(n.next),n=t=o),n=n.next}while(n!==t);return n},i.EarCut.splitEarcut=function(t,e,s,n,r,o){var a=t;do{for(var h=a.next.next;h!==a.prev;){if(a.i!==h.i&&i.EarCut.isValidDiagonal(a,h)){var l=i.EarCut.splitPolygon(a,h);return a=i.EarCut.filterPoints(a,a.next),l=i.EarCut.filterPoints(l,l.next),i.EarCut.earcutLinked(a,e,s,n,r,o),void i.EarCut.earcutLinked(l,e,s,n,r,o)}h=h.next}a=a.next}while(a!==t)},i.EarCut.eliminateHoles=function(t,e,s,n){var r,o,a,h,l,c=[];for(r=0,o=e.length;r=n.next.y){var h=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);h<=r&&h>a&&(a=h,s=n.x=n.x&&n.x>=s.x&&i.EarCut.pointInTriangle(os.x)&&i.EarCut.locallyInside(n,t)&&(s=n,u=l),n=n.next;return s},i.EarCut.indexCurve=function(t,e,s,n){var r=t;do{null===r.z&&(r.z=i.EarCut.zOrder(r.x,r.y,e,s,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,i.EarCut.sortLinked(r)},i.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},i.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},i.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},i.EarCut.isValidDiagonal=function(t,e){return i.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!i.EarCut.intersectsPolygon(t,e)&&i.EarCut.locallyInside(t,e)&&i.EarCut.locallyInside(e,t)&&i.EarCut.middleInside(t,e)},i.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},i.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},i.EarCut.intersects=function(t,e,s,n){return i.EarCut.area(t,e,s)>0!=i.EarCut.area(t,e,n)>0&&i.EarCut.area(s,n,t)>0!=i.EarCut.area(s,n,e)>0},i.EarCut.intersectsPolygon=function(t,e){var s=t;do{if(s.i!==t.i&&s.next.i!==t.i&&s.i!==e.i&&s.next.i!==e.i&&i.EarCut.intersects(s,s.next,t,e))return!0;s=s.next}while(s!==t);return!1},i.EarCut.locallyInside=function(t,e){return i.EarCut.area(t.prev,t,t.next)<0?i.EarCut.area(t,e,t.next)>=0&&i.EarCut.area(t,t.prev,e)>=0:i.EarCut.area(t,e,t.prev)<0||i.EarCut.area(t,t.next,e)<0},i.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},i.EarCut.splitPolygon=function(t,e){var s=new i.EarCut.Node(t.i,t.x,t.y),n=new i.EarCut.Node(e.i,e.x,e.y),r=t.next,o=e.prev;return t.next=e,e.prev=t,s.next=r,r.prev=s,n.next=s,s.prev=n,o.next=n,n.prev=o,n},i.EarCut.insertNode=function(t,e,s,n){var r=new i.EarCut.Node(t,e,s);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r},i.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},i.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var s,n=e.gl,r=e.projection,o=e.offset,a=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,n);var h=t._webGL[n.id];if(h)for(var l=0;l=PIXI.WebGLGraphics.stencilBufferLimit&&(a.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit?(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildPoly(a,o)||(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))),a.lineWidth>0&&(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildLine(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,0),a.type===i.RECTANGLE?PIXI.WebGLGraphics.buildRectangle(a,o):a.type===i.CIRCLE||a.type===i.ELLIPSE?PIXI.WebGLGraphics.buildCircle(a,o):a.type===i.ROUNDEDRECTANGLE&&PIXI.WebGLGraphics.buildRoundedRectangle(a,o)),s.lastIndex++}for(n=0;n19600?(_=y-x,w=v-b,_/=R=Math.sqrt(_*_+w*w),w/=R,_*=F,w*=F,L.push(p-_,f-w),L.push(G,N,X,U),L.push(p+_,f+w),L.push(G,N,X,U),L.push(p-_,f-w),L.push(G,N,X,U),O++):(L.push(l,c),L.push(G,N,X,U),L.push(p-(l-p),f-(c-f)),L.push(G,N,X,U));for(u=n[2*(I-2)],d=n[2*(I-2)+1],p=n[2*(I-1)],y=-(d-(f=n[2*(I-1)+1])),v=u-p,y/=R=Math.sqrt(y*y+v*v),v/=R,y*=F,v*=F,L.push(p-y,f-v),L.push(G,N,X,U),L.push(p+y,f+v),L.push(G,N,X,U),B.push(k),s=0;sh?r:h,l=oc?o:c;s.push(a,l,h,l,h,c,a,c);var d=s.length/2;for(u=0;uS?S:C,e.beginPath(),e.moveTo(_,w+C),e.lineTo(_,w+P-C),e.quadraticCurveTo(_,w+P,_+C,w+P),e.lineTo(_+T-C,w+P),e.quadraticCurveTo(_+T,w+P,_+T,w+P-C),e.lineTo(_+T,w+C),e.quadraticCurveTo(_+T,w,_+T-C,w),e.lineTo(_+C,w),e.quadraticCurveTo(_,w,_,w+C),e.closePath(),(r.fillColor||0===r.fillColor)&&(e.globalAlpha=r.fillAlpha*s,e.fillStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.fill()),r.lineWidth&&(e.globalAlpha=r.lineAlpha*s,e.strokeStyle="#"+("00000"+(0|h).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var s=t.graphicsData.length;if(0!==s){e.beginPath();for(var n=0;nP?P:T,e.moveTo(x,b+T),e.lineTo(x,b+w-T),e.quadraticCurveTo(x,b+w,x+T,b+w),e.lineTo(x+_-T,b+w),e.quadraticCurveTo(x+_,b+w,x+_,b+w-T),e.lineTo(x+_,b+T),e.quadraticCurveTo(x+_,b,x+_-T,b),e.lineTo(x+T,b),e.quadraticCurveTo(x,b,x,b+T),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},i.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},i.GraphicsData.prototype.constructor=i.GraphicsData,i.GraphicsData.prototype.clone=function(){return new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},i.Graphics=function(t,e,s){void 0===e&&(e=0),void 0===s&&(s=0),this.type=i.GRAPHICS,this.physicsType=i.SPRITE,this.anchor=new i.Point,PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new i.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1,i.Component.Core.init.call(this,t,e,s,"",null)},i.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Graphics.prototype.constructor=i.Graphics,i.Component.Core.install.call(i.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),i.Graphics.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Graphics.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Graphics.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Graphics.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Graphics.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Graphics.prototype.postUpdate=function(){i.Component.PhysicsBody.postUpdate.call(this),i.Component.FixedToCamera.postUpdate.call(this),this._boundsDirty&&(this.updateLocalBounds(),this._boundsDirty=!1);for(var t=0;t0&&this.drawPolygon(s)}else this.drawPolygon(s)},i.Graphics.prototype.drawTriangles=function(t,e,s){void 0===s&&(s=!1);var n,r=new i.Point,o=new i.Point,a=new i.Point,h=[];if(e)if(t[0]instanceof i.Point)for(n=0;nc*a)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var x=d+s+p*(v+y*v),b=Math.cos(x),_=-Math.sin(x);u.push((f*b+g*_)*i+t,(f*-_+g*b)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},i.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},i.Graphics.prototype.drawRect=function(t,e,s,n){return this.drawShape(new i.Rectangle(t,e,s,n)),this},i.Graphics.prototype.drawRoundedRect=function(t,e,s,n,r){return this.drawShape(new i.RoundedRectangle(t,e,s,n,r)),this},i.Graphics.prototype.drawCircle=function(t,e,s){return this.drawShape(new i.Circle(t,e,s)),this},i.Graphics.prototype.drawEllipse=function(t,e,s,n){return this.drawShape(new i.Ellipse(t,e,s,n)),this},i.Graphics.prototype.drawPolygon=function(t){t instanceof i.Polygon&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var s=0;sw?m:w,w=v>w?v:w,w=b>w?b:w,T=y>T?y:T,T=x>T?x:T,T=_>T?_:T,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=C,this._bounds.height=T-C,this._currentBounds=this._bounds,this._currentBounds},i.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;ee?a+l:e,s=hn?h+c:n;else if(p===i.CIRCLE)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else if(p===i.ELLIPSE)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else{o=r.points;for(var g=0;ge?a+f:e,s=h-fn?h+f:n}}else t=0,e=0,s=0,n=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=s-m,this._localBounds.height=n-s+2*m},i.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},i.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},i.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},i.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof i.Polygon&&(t=t.clone()).flatten();var e=new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===i.POLYGON&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(i.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),i.RenderTexture=function(t,e,s,n,r,o,a,h){if(void 0===e&&(e=100),void 0===s&&(s=100),void 0===n&&(n=""),void 0===r&&(r=i.scaleModes.DEFAULT),void 0===o&&(o=1),void 0===a&&(a=PIXI.defaultRenderer),void 0===h&&(h=0),this.game=t,this.key=n,this.type=i.RENDERTEXTURE,this._tempMatrix=new i.Matrix,this.width=e,this.height=s,this.resolution=o,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=this.frame.clone(),this.baseTexture=new PIXI.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=r,this.baseTexture.hasLoaded=!0,PIXI.Texture.call(this,this.baseTexture,this.frame.clone()),this.renderer=a,this.renderer.type===i.WEBGL){var l=this.renderer.gl;this.baseTexture.textureIndex=h,this.baseTexture._dirty[l.id]=!1,this.textureBuffer=new PIXI.FilterTexture(l,this.width,this.height,this.baseTexture.scaleMode,h),this.baseTexture._glTextures[l.id]=this.textureBuffer.texture,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.textureBuffer=new PIXI.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new i.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(PIXI.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.renderXY=function(t,e,s,n){t.updateTransform(),this._tempMatrix.copyFrom(t.worldTransform),this._tempMatrix.tx=e,this._tempMatrix.ty=s,this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.renderRawXY=function(t,e,s,n){this._tempMatrix.identity().translate(e,s),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.render=function(t,e,s){void 0===e||null===e?this._tempMatrix.copyFrom(t.worldTransform):this._tempMatrix.copyFrom(e),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,s):this._renderCanvas(t,this._tempMatrix,s)},i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype._renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n-1&&this.characterLimitSize0&&this.style.maxLines0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(e[a]):l+=this.context.measureText(e[a]).width,this.style.wordWrap&&(l-=this.context.measureText(" ").width)}else{var h=e[a].split(/(?:\t)/),l=this.padding.x+this.style.strokeThickness;if(Array.isArray(i))for(var c=0,u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.measureLine(h[u]):Math.ceil(this.context.measureText(h[u]).width),u>0&&(c+=i[u-1]),l=c+d}else for(u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(h[u]):l+=Math.ceil(this.context.measureText(h[u]).width),l+=this.game.math.snapToCeil(l,i)-l}s[a]=Math.ceil(l),n=Math.max(n,s[a])}this.canvas.width=n*this._res;var p=r.fontSize+this.style.strokeThickness+this.padding.y,f=p*o,g=this._lineSpacing;g<0&&Math.abs(g)>p&&(g=-p),0!==g&&(f+=g>0?g*e.length:g*(e.length-1)),this.canvas.height=f*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var m,y;for(this._charCount=0,a=0;a0&&(y+=g*a),"right"===this.style.align?m+=n-s[a]:"center"===this.style.align&&(m+=(n-s[a])/2),this.autoRound&&(m=Math.round(m),y=Math.round(y)),this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.updateLine(e[a],m,y):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===i?this.context.strokeText(e[a],m,y):this.renderTabLine(e[a],m,y,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===i?this.context.fillText(e[a],m,y):this.renderTabLine(e[a],m,y,!0)));this.updateTexture(),this.dirty=!1},i.Text.prototype.renderTabLine=function(t,e,i,s){var n=t.split(/(?:\t)/),r=this.style.tabs,o=0;if(Array.isArray(r))for(var a=0,h=0;h0&&(a+=r[h-1]),o=e+a,s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i);else for(h=0;h0||this.fontStyles.length>0){var n=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(n.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(n.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(n)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill)),e+=this.context.measureText(s).width,this._charCount++}return Math.ceil(e)},i.Text.prototype.updateLine=function(t,e,i){for(var s=0;s0||this.fontStyles.length>0){var r=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(r.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(r.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(r)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(n,e,i)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(n,e,i)),e+=this.context.measureText(n).width,this._charCount++}},i.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},i.Text.prototype.clearFontValues=function(){return this.fontStyles=[],this.fontWeights=[],this.dirty=!0,this},i.Text.prototype.addColor=function(t,e){return this.colors[e]=t,this.dirty=!0,this},i.Text.prototype.addStrokeColor=function(t,e){return this.strokeColors[e]=t,this.dirty=!0,this},i.Text.prototype.addFontStyle=function(t,e){return this.fontStyles[e]=t,this.dirty=!0,this},i.Text.prototype.addFontWeight=function(t,e){return this.fontWeights[e]=t,this.dirty=!0,this},i.Text.prototype.precalculateWordWrap=function(t){return this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font,this.runWordWrap(t).split(/(?:\r\n|\r|\n)/)},i.Text.prototype.runWordWrap=function(t){return this.useAdvancedWrap?this.advancedWordWrap(t):this.basicWordWrap(t)},i.Text.prototype.advancedWordWrap=function(t){for(var e=this.context,i=this.style.wordWrapWidth,s="",n=t.replace(/ +/gi," ").split(/\r?\n/gi),r=n.length,o=0;ol){if(0===u){for(var g=p;g.length&&(g=g.slice(0,-1),!((f=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var m=d.substr(g.length);c[u]=m,h+=g}var y=c[u].length?u:u+1,v=c.slice(y).join(" ").replace(/[ \n]*$/gi,"");n[o+1]=v+" "+(n[o+1]||""),r=n.length;break}h+=p,l-=f}s+=h.replace(/[ \n]*$/gi,"")+"\n"}}return s=s.replace(/[\s|\n]*$/gi,"")},i.Text.prototype.basicWordWrap=function(t){for(var e="",i=t.split("\n"),s=0;sn?(o>0&&(e+="\n"),e+=r[o]+" ",n=this.style.wordWrapWidth-a):(n-=h,e+=r[o]+" ")}ss&&(this.style.wordWrapWidth=s)),this.updateTexture(),this},i.Text.prototype.updateTexture=function(){var t=this.texture.baseTexture,e=this.texture.crop,i=this.texture.frame,s=this.canvas.width,n=this.canvas.height;if(t.width=s,t.height=n,e.width=s,e.height=n,i.width=s,i.height=n,this.texture.width=s,this.texture.height=n,this._width=s,this._height=n,this.textBounds){var r=this.textBounds.x,o=this.textBounds.y;"right"===this.style.boundsAlignH?r+=this.textBounds.width-this.canvas.width/this.resolution:"center"===this.style.boundsAlignH&&(r+=this.textBounds.halfWidth-this.canvas.width/this.resolution/2),"bottom"===this.style.boundsAlignV?o+=this.textBounds.height-this.canvas.height/this.resolution:"middle"===this.style.boundsAlignV&&(o+=this.textBounds.halfHeight-this.canvas.height/this.resolution/2),this.pivot.x=-r,this.pivot.y=-o}this.renderable=0!==s&&0!==n,this.texture.requiresReTint=!0,this.texture.baseTexture.dirty()},i.Text.prototype._renderWebGL=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.Text.prototype._renderCanvas=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.Text.prototype.determineFontProperties=function(t){var e=i.Text.fontPropertiesCache[t];if(!e){e={};var s=i.Text.fontPropertiesCanvas,n=i.Text.fontPropertiesContext;n.font=t;var r=Math.ceil(n.measureText("|MÉq").width),o=Math.ceil(n.measureText("|MÉq").width),a=2*o;if(o=1.4*o|0,s.width=r,s.height=a,n.fillStyle="#f00",n.fillRect(0,0,r,a),n.font=t,n.textBaseline="alphabetic",n.fillStyle="#000",n.fillText("|MÉq",0,o),!n.getImageData(0,0,r,a))return e.ascent=o,e.descent=o+6,e.fontSize=e.ascent+e.descent,i.Text.fontPropertiesCache[t]=e,e;var h,l,c=n.getImageData(0,0,r,a).data,u=c.length,d=4*r,p=0,f=!1;for(h=0;ho;h--){for(l=0;l0?this._maxWidth:null,l=[],c=0;c=h&&r>-1)return{width:o||n,text:i.substr(0,c-(c-r)),end:!1,chars:l};n+=(p.xAdvance+g)*e,l.push(s+(p.xOffset+g)*e),s+=(p.xAdvance+g)*e,a=d}return{width:n,text:i,end:u,chars:l}},i.BitmapText.prototype.cleanText=function(t,e){void 0===e&&(e="");var i=this._data.font;if(!i)return"";for(var s=/\r\n|\n\r|\n|\r/g,n=t.replace(s,"\n").split("\n"),r=0;rthis.textWidth&&(this.textWidth=c.width),n+=t.lineHeight*i,e=e.substr(c.text.length+1)}while(!1===c.end);this.textHeight=n;for(var r=0,o=0,a=this.textWidth*this.anchor.x,h=this.textHeight*this.anchor.y,l=0;l0&&(this._fontSize=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"smoothed",{get:function(){return!this._data.base.scaleMode},set:function(t){this._data.base.scaleMode=t?0:1,this._data.base.dirty()}}),i.RetroFont=function(t,e,s,n,r,o,a,h,l,c){if(!t.cache.checkImageKey(e))return!1;void 0!==o&&null!==o||(o=t.cache.getImage(e).width/s),this.characterWidth=s,this.characterHeight=n,this.characterSpacingX=a||0,this.characterSpacingY=h||0,this.characterPerRow=o,this.offsetX=l||0,this.offsetY=c||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=t.cache.getImage(e),this._text="",this.grabData=[],this.frameData=new i.FrameData;for(var u=this.offsetX,d=this.offsetY,p=0,f=0;f?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",i.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",i.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",i.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",i.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",i.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",i.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",i.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",i.RetroFont.prototype.setFixedWidth=function(t,e){void 0===e&&(e="left"),this.fixedWidth=t,this.align=e},i.RetroFont.prototype.setText=function(t,e,i,s,n,r){this.multiLine=e||!1,this.customSpacingX=i||0,this.customSpacingY=s||0,this.align=n||"left",this.autoUpperCase=!r,t.length>0&&(this.text=t)},i.RetroFont.prototype.buildRetroFontText=function(){var t=0,e=0;if(this.clear(),this.multiLine){var s=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var n=0;n0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),t=0,this.align===i.RetroFont.ALIGN_RIGHT?t=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===i.RetroFont.ALIGN_CENTER&&(t=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(this._text,t,0,this.customSpacingX);this.requiresReTint=!0},i.RetroFont.prototype.pasteLine=function(t,e,i,s){for(var n=0;n=0&&(this.stamp.frame=this.grabData[t.charCodeAt(n)],this.renderXY(this.stamp,e,i,!1),(e+=this.characterWidth+s)>this.width))break},i.RetroFont.prototype.getLongestLine=function(){var t=0;if(this._text.length>0)for(var e=this._text.split("\n"),i=0;it&&(t=e[i].length);return t},i.RetroFont.prototype.removeUnsupportedCharacters=function(t){for(var e="",i=0;i=0||!t&&"\n"===s)&&(e=e.concat(s))}return e},i.RetroFont.prototype.updateOffset=function(t,e){if(this.offsetX!==t||this.offsetY!==e){for(var i=t-this.offsetX,s=e-this.offsetY,n=this.game.cache.getFrameData(this.stamp.key).getFrames(),r=n.length;r--;)n[r].x+=i,n[r].y+=s;this.buildRetroFontText()}},Object.defineProperty(i.RetroFont.prototype,"text",{get:function(){return this._text},set:function(t){var e;(e=this.autoUpperCase?t.toUpperCase():t)!==this._text&&(this._text=e,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(i.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(t){this.stamp.smoothed=t,this.buildRetroFontText()}}),i.Rope=function(t,e,s,n,r,o){this.points=o||[],this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.ROPE,PIXI.DisplayObjectContainer.call(this),this.texture=i.Cache.DEFAULT,this.uvs=new Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new Float32Array([0,0,100,0,100,100,0,100]),this.colors=new Float32Array([1,1,1,1]),this.indices=new Uint16Array([0,1,2,3]),o&&(this.vertices=new Float32Array(4*o.length),this.uvs=new Float32Array(4*o.length),this.colors=new Float32Array(2*o.length),this.indices=new Uint16Array(2*o.length)),this.dirty=!0,this.canvasPadding=0,this.drawMode=i.Rope.TRIANGLE_STRIP,i.Component.Core.init.call(this,t,e,s,n,r),this.refresh()},i.Rope.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Rope.prototype.constructor=i.Rope,i.Component.Core.install.call(i.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Rope.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Rope.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Rope.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Rope.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Rope.TRIANGLE_STRIP=0,i.Rope.TRIANGLES=1,i.Rope.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},i.Rope.prototype.reset=function(t,e){return i.Component.Reset.prototype.reset.call(this,t,e),this},i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=this.indices,s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o=t.length,a=1;a1&&1,o=Math.sqrt(s.x*s.x+s.y*s.y),a=this.texture.height/2,s.x/=o,s.y/=o,s.x*=a,s.y*=a,h[r]=n.x+s.x,h[r+1]=n.y+s.y,h[r+2]=n.x-s.x,h[r+3]=n.y-s.y,i=n;PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.Rope.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Rope.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Rope.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Rope.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Rope.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Rope.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Rope.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n0){var _=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,T=(l+c+u)/3,P=(d+p+f)/3,C=l-T,S=d-P,A=Math.sqrt(C*C+S*S);l=T+C/A*(A+_),d=P+S/A*(A+w),S=p-P,c=T+(C=c-T)/(A=Math.sqrt(C*C+S*S))*(A+_),p=P+S/A*(A+w),S=f-P,u=T+(C=u-T)/(A=Math.sqrt(C*C+S*S))*(A+_),f=P+S/A*(A+w)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*x+v*y+m*b-x*y-v*m-g*b,M=l*x+v*u+c*b-x*u-v*c-l*b,R=g*c+l*y+m*u-c*y-l*m-g*u,L=g*x*u+v*c*y+l*m*b-l*x*y-v*m*u-g*c*b,B=d*x+v*f+p*b-x*f-v*p-d*b,I=g*p+d*y+m*f-p*y-d*m-g*f,O=g*x*f+v*p*y+d*m*b-d*x*y-v*m*f-g*p*b;t.transform(M/E,B/E,R/E,I/E,L/E,O/E),t.drawImage(o,0,0),t.restore()},i.Rope.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;nh?m:h,l=y>l?y:l}if(c===-1/0||l===1/0)return PIXI.EmptyRectangle;var v=this._bounds;return v.x=c,v.width=h-c,v.y=u,v.height=l-u,this._currentBounds=v,v},Object.defineProperty(i.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(t){t&&"function"==typeof t?(this._hasUpdateAnimation=!0,this._updateAnimation=t):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(i.Rope.prototype,"segments",{get:function(){for(var t,e,s,n,r,o,a,h,l=[],c=0;c(_=y>(_=g>(_=p>_?p:_)?g:_)?y:_)?x:_,w=b>(w=v>(w=m>(w=f>w?f:w)?m:w)?v:w)?b:w;var C=this._bounds;return C.x=T,C.width=_-T,C.y=P,C.height=w-P,this._currentBounds=C,C},Object.defineProperty(i.TileSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TileSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var e=parseInt(RegExp.$1,10),i=parseInt(RegExp.$2,10);(10===e&&i>=11||e>10)&&(s.dolby=!0)}}catch(t){}}(),function(){var t=document.createElement("video");try{!!t.canPlayType&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(s.oggVideo=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.h264Video=!0,s.mp4Video=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(s.webmVideo=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(s.vp9Video=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.hlsVideo=!0))}catch(t){}}(),function(){var t,e=document.createElement("p"),i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var n in i)void 0!==e.style[n]&&(e.style[n]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(i[n]));document.body.removeChild(e),s.css3D=void 0!==t&&t.length>0&&"none"!==t}(),s.pixelRatio=window.devicePixelRatio||1,s.iPhone=-1!==navigator.userAgent.toLowerCase().indexOf("iphone"),s.iPhone4=2===s.pixelRatio&&s.iPhone,s.iPad=-1!==navigator.userAgent.toLowerCase().indexOf("ipad"),"undefined"!=typeof Int8Array?s.typedArray=!0:s.typedArray=!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(s.littleEndian=t(),s.LITTLE_ENDIAN=s.littleEndian),s.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==s.littleEndian&&e(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(s.vibration=!0),function(){s.canvas=!!window.CanvasRenderingContext2D||s.cocoonJS;try{s.localStorage=!!localStorage.getItem}catch(t){s.localStorage=!1}s.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),s.fileSystem=!!window.requestFileSystem,s.webGL=!!window.WebGLRenderingContext,s.worker=!!window.Worker,s.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,s.quirksMode="CSS1Compat"!==document.compatMode,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,s.getUserMedia=s.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,s.firefox&&s.firefoxVersion<21&&(s.getUserMedia=!1),!s.iOS&&(s.ie||s.firefox||s.chrome)&&(s.canvasBitBltShift=!0),(s.safari||s.mobileSafari)&&(s.canvasBitBltShift=!1)}(),function(){var t=i.CanvasPool.create(this,6,1),e=t.getContext("2d");e.fillStyle="rgba(10, 20, 30, 0.5)",e.fillRect(0,0,1,1);var n=e.getImageData(0,0,1,1);if(n){e.putImageData(n,1,0);var r=e.getImageData(1,0,1,1);s.canHandleAlpha=r.data[0]===n.data[0]&&r.data[1]===n.data[1]&&r.data[2]===n.data[2]&&r.data[3]===n.data[3]}e.globalCompositeOperation="multiply",s.canUseMultiply="multiply"===e.globalCompositeOperation,i.CanvasPool.removeByCanvas(t),PIXI.CanvasTinter.tintMethod=s.canUseMultiply?PIXI.CanvasTinter.tintWithMultiply:PIXI.CanvasTinter.tintWithPerPixel}(),function(){for(var t=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],e=document.createElement("div"),i=0;i=1)&&(s.touch=!0),(window.PointerEvent||window.MSPointerEvent||window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(s.mspointer=!0),s.cocoonJS||("onwheel"in window||s.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":s.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"))},i.Device.canPlayAudio=function(t){return!("mp3"!==t||!this.mp3)||(!("ogg"!==t||!this.ogg&&!this.opus)||(!("m4a"!==t||!this.m4a)||(!("opus"!==t||!this.opus)||(!("wav"!==t||!this.wav)||(!("webm"!==t||!this.webm)||!("mp4"!==t||!this.dolby))))))},i.Device.canPlayVideo=function(t){return!("webm"!==t||!this.webmVideo&&!this.vp9Video)||(!("mp4"!==t||!this.mp4Video&&!this.h264Video)||(!("ogg"!==t&&"ogv"!==t||!this.oggVideo)||!("mpeg"!==t||!this.hlsVideo)))},i.Device.needsTouchUnlock=function(){return!!(!this.cocoonJS&&(this.iOS||this.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)},i.Device.isAndroidStockBrowser=function(){var t=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return t&&t[1]<537},i.Canvas={create:function(t,e,s,n,r){e=e||256,s=s||256;var o=r?document.createElement("canvas"):i.CanvasPool.create(t,e,s);return"string"==typeof n&&""!==n&&(o.id=n),o.width=e,o.height=s,o.style.display="block",o},setBackgroundColor:function(t,e){return e=e||"rgb(0,0,0)",t.style.backgroundColor=e,t},setTouchAction:function(t,e){return e=e||"none",t.style.msTouchAction=e,t.style["ms-touch-action"]=e,t.style["touch-action"]=e,t},setUserSelect:function(t,e){return e=e||"none",t.style["-webkit-touch-callout"]=e,t.style["-webkit-user-select"]=e,t.style["-khtml-user-select"]=e,t.style["-moz-user-select"]=e,t.style["-ms-user-select"]=e,t.style["user-select"]=e,t.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",t},addToDOM:function(t,e,i){var s;return void 0===i&&(i=!0),e&&("string"==typeof e?s=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(s=e)),s||(s=document.body),i&&s.style&&(s.style.overflow="hidden"),s.appendChild(t),t},removeFromDOM:function(t){t.parentNode&&t.parentNode.removeChild(t)},setTransform:function(t,e,i,s,n,r,o){return t.setTransform(s,r,o,n,e,i),t},setSmoothingEnabled:function(t,e){var s=i.Canvas.getSmoothingPrefix(t);return s&&(t[s]=e),t},getSmoothingPrefix:function(t){var e=["i","webkitI","msI","mozI","oI"];for(var i in e){var s=e[i]+"mageSmoothingEnabled";if(s in t)return s}return null},getSmoothingEnabled:function(t){var e=i.Canvas.getSmoothingPrefix(t);if(e)return t[e]},setImageRenderingCrisp:function(t){for(var e=["-webkit-optimize-contrast","-moz-crisp-edges","crisp-edges","pixelated"],i=0;i0&&0==(t&t-1))return t;for(var e=1;e0&&0==(t&t-1)&&e>0&&0==(e&e-1)},random:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return Math.random()*(e-t)+t},between:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t},fuzzyEqual:function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)e-i},fuzzyCeil:function(t,e){return void 0===e&&(e=1e-4),Math.ceil(t-e)},fuzzyFloor:function(t,e){return void 0===e&&(e=1e-4),Math.floor(t+e)},average:function(){for(var t=0,e=arguments.length,i=0;i=i.Math.PI2-s?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=s:e=0?t:t+2*Math.PI},maxAdd:function(t,e,i){return Math.min(t+e,i)},minSub:function(t,e,i){return Math.max(t-e,i)},wrap:function(t,e,i){var s=i-e;if(s<=0)return 0;var n=(t-e)%s;return n<0&&(n+=s),n+e},wrapValue:function(t,e,i){return t=Math.abs(t),e=Math.abs(e),i=Math.abs(i),(t+e)%i},isOdd:function(t){return!!(1&t)},isEven:function(t){return!(1&t)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;et[i]&&(i=e);return t[i]},minProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;ie[s][t]&&(s=i);return e[s][t]},wrapAngle:function(t,e){return e?this.wrap(t,-Math.PI,Math.PI):this.wrap(t,-180,180)},linearInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return e<0?this.linear(t[0],t[1],s):e>1?this.linear(t[i],t[i-1],i-s):this.linear(t[n],t[n+1>i?i:n+1],s-n)},bezierInterpolation:function(t,e){for(var i=0,s=t.length-1,n=0;n<=s;n++)i+=Math.pow(1-e,s-n)*Math.pow(e,n)*t[n]*this.bernstein(s,n);return i},catmullRomInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return t[0]===t[i]?(e<0&&(n=Math.floor(s=i*(1+e))),this.catmullRom(t[(n-1+i)%i],t[n],t[(n+1)%i],t[(n+2)%i],s-n)):e<0?t[0]-(this.catmullRom(t[0],t[0],t[1],t[1],-s)-t[0]):e>1?t[i]-(this.catmullRom(t[i],t[i],t[i-1],t[i-1],s-i)-t[i]):this.catmullRom(t[n?n-1:0],t[n],t[i0?Math.ceil(t):Math.floor(t)},sinCosGenerator:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1);for(var n=e,r=i,o=s*Math.PI/t,a=[],h=[],l=0;l0?1:0},percent:function(t,e,i){return void 0===i&&(i=0),t>e||i>e?1:tt?0:(t-i)/e}},i.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},i.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e>>0,s=(e*=s)>>>0,s+=4294967296*(e-=s);return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},i.RandomDataGenerator.prototype.constructor=i.RandomDataGenerator,i.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},i.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new i.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new i.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new i.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new i.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null==this.nodes[0]||-1===(e=this.getIndex(t))){if(this.objects.push(t),this.objects.length>this.maxObjects&&this.levelthis.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.ythis.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof i.Rectangle)var e=this.objects,s=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,s=this.getIndex(t.body)}return this.nodes[0]&&(e=-1!==s?e.concat(this.nodes[s].retrieve(t)):(e=(e=(e=e.concat(this.nodes[0].retrieve(t))).concat(this.nodes[1].retrieve(t))).concat(this.nodes[2].retrieve(t))).concat(this.nodes[3].retrieve(t))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},i.QuadTree.prototype.constructor=i.QuadTree,i.Net=function(t){this.game=t},i.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},i.Net.prototype.constructor=i.Net,i.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:i.Easing.Power0,Power1:i.Easing.Power1,Power2:i.Easing.Power2,Power3:i.Easing.Power3,Power4:i.Easing.Power4,Linear:i.Easing.Linear.None,Quad:i.Easing.Quadratic.Out,Cubic:i.Easing.Cubic.Out,Quart:i.Easing.Quartic.Out,Quint:i.Easing.Quintic.Out,Sine:i.Easing.Sinusoidal.Out,Expo:i.Easing.Exponential.Out,Circ:i.Easing.Circular.Out,Elastic:i.Easing.Elastic.Out,Back:i.Easing.Back.Out,Bounce:i.Easing.Bounce.Out,"Quad.easeIn":i.Easing.Quadratic.In,"Cubic.easeIn":i.Easing.Cubic.In,"Quart.easeIn":i.Easing.Quartic.In,"Quint.easeIn":i.Easing.Quintic.In,"Sine.easeIn":i.Easing.Sinusoidal.In,"Expo.easeIn":i.Easing.Exponential.In,"Circ.easeIn":i.Easing.Circular.In,"Elastic.easeIn":i.Easing.Elastic.In,"Back.easeIn":i.Easing.Back.In,"Bounce.easeIn":i.Easing.Bounce.In,"Quad.easeOut":i.Easing.Quadratic.Out,"Cubic.easeOut":i.Easing.Cubic.Out,"Quart.easeOut":i.Easing.Quartic.Out,"Quint.easeOut":i.Easing.Quintic.Out,"Sine.easeOut":i.Easing.Sinusoidal.Out,"Expo.easeOut":i.Easing.Exponential.Out,"Circ.easeOut":i.Easing.Circular.Out,"Elastic.easeOut":i.Easing.Elastic.Out,"Back.easeOut":i.Easing.Back.Out,"Bounce.easeOut":i.Easing.Bounce.Out,"Quad.easeInOut":i.Easing.Quadratic.InOut,"Cubic.easeInOut":i.Easing.Cubic.InOut,"Quart.easeInOut":i.Easing.Quartic.InOut,"Quint.easeInOut":i.Easing.Quintic.InOut,"Sine.easeInOut":i.Easing.Sinusoidal.InOut,"Expo.easeInOut":i.Easing.Exponential.InOut,"Circ.easeInOut":i.Easing.Circular.InOut,"Elastic.easeInOut":i.Easing.Elastic.InOut,"Back.easeInOut":i.Easing.Back.InOut,"Bounce.easeInOut":i.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},i.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t,e){return e||(e=!1),this._tweens.some(function(i){return i.target===t&&(!e||i.isRunning&&!i.pendingDelete)})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},i.TweenManager.prototype.constructor=i.TweenManager,i.Tween=function(t,e,s){this.game=e,this.target=t,this.manager=s,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new i.Signal,this.onLoop=new i.Signal,this.onRepeat=new i.Signal,this.onChildComplete=new i.Signal,this.onComplete=new i.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=s.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},i.Tween.updateColor=function(t){i.Color.updateColor(t.target)},i.Tween.prototype={to:function(t,e,s,n,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).to(t,e,s,r,o,a)),n&&this.start(),this)},from:function(t,e,s,n,r,o,a){return void 0===e&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).from(t,e,s,r,o,a)),n&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),this.pendingDelete)return console.warn("Phaser.Tween.start cannot be called after Tween.stop"),this;if(null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(i=0;ithis.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(s=0;s0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t=this.startTime))return i.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var s in this.vEnd){var n=this.vStart[s],r=this.vEnd[s];Array.isArray(r)?this.parent.target[s]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[s]=n+(r-n)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():i.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction.call(this.interpolationContext,a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,i.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return i.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,i.TweenData.LOOPED}},i.TweenData.prototype.constructor=i.TweenData,i.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-i.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*i.Easing.Bounce.In(2*t):.5*i.Easing.Bounce.Out(2*t-1)+.5}}},i.Easing.Default=i.Easing.Linear.None,i.Easing.Power0=i.Easing.Linear.None,i.Easing.Power1=i.Easing.Quadratic.Out,i.Easing.Power2=i.Easing.Cubic.Out,i.Easing.Power3=i.Easing.Quartic.Out,i.Easing.Power4=i.Easing.Quintic.Out,i.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.updates=0,this.renders=0,this.fps=0,this.ups=0,this.rps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new i.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},i.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new i.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3){var t=this.now-this._timeLastSecond;this.fps=Math.round(1e3*this.frames/t),this.ups=Math.round(1e3*this.updates/t),this.rps=Math.round(1e3*this.renders/t),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0,this.updates=0,this.renders=0}},countUpdate:function(){this.advancedTiming&&this.updates++},countRender:function(){this.advancedTiming&&this.renders++},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(i.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),i.Time.prototype.constructor=i.Time,i.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new i.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},i.Timer.MINUTE=6e4,i.Timer.SECOND=1e3,i.Timer.HALF=500,i.Timer.QUARTER=250,i.Timer.prototype={create:function(t,e,s,n,r,o){var a=t=Math.round(t);0===this._now?a+=this.game.time.time:a+=this._now;var h=new i.TimerEvent(this,t,a,s,e,n,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.ticke.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i=e.tick)||e.pendingDelete)break;this._newTick=this._now+e.delay-(this._now-e.tick),this._newTick<0&&(this._newTick=this._now+e.delay),!0===e.loop?(e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):e.repeatCount>0?(e.repeatCount--,e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):(this._marked++,e.pendingDelete=!0,e.callback.apply(e.callbackContext,e.args)),this._i++}this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;ethis._now?this.nextTick-this._now:0}}),Object.defineProperty(i.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(i.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(i.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),i.Timer.prototype.constructor=i.Timer,i.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},i.TimerEvent.prototype.constructor=i.TimerEvent,i.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},i.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,s,n,r){return e=e||[],s=s||60,void 0===n&&(n=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new i.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,s,n),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;ithis._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},i.AnimationManager.prototype.constructor=i.AnimationManager,Object.defineProperty(i.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(i.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(i.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(i.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(i.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){var e;"number"==typeof t&&this._frameData&&(e=this._frameData.getFrame(t))&&(this.currentFrame=e,this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(i.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){var e;"string"==typeof t&&this._frameData&&(e=this._frameData.getFrameByName(t))?(this.currentFrame=e,this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame)):console.warn("Cannot set frameName: "+t)}}),i.Animation=function(t,e,s,n,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=n,this.name=s,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new i.Signal,this.onUpdate=null,this.onComplete=new i.Signal,this.onLoop=new i.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},i.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(s=0;s=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay?(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay):this._frameDiff=0,this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(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=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},i.Animation.prototype.constructor=i.Animation,Object.defineProperty(i.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(i.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(i.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(i.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(i.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(i.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new i.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),i.Animation.generateFrameNames=function(t,e,s,n,r){void 0===n&&(n="");var o=[],a="";if(e=s;h--)a=t+(a="number"==typeof r?i.Utils.pad(h.toString(),r,"0",1):h.toString())+n,o.push(a);return o},i.Frame=function(t,e,s,n,r,o){this.index=t,this.x=e,this.y=s,this.width=n,this.height=r,0!==this.width&&0!==this.height||console.warn('Phaser.Frame: Frame "'+this.name+'" has a width or height of zero'),this.name=o,this.centerX=Math.floor(n/2),this.centerY=Math.floor(r/2),this.distance=i.Math.distance(0,0,n,r),this.rotated=!1,this.trimmed=!1,this.sourceSizeW=n,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},i.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=i.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new i.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new i.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},i.Frame.prototype.constructor=i.Frame,i.FrameData=function(){this._frames=[],this._frameNames=[]},i.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new i.FrameData,e=0;ed||h<-d)return console.warn("Phaser.AnimationParser.spriteSheet: skipFrames = "+h.toString()+" is larger than total sprite number "+d.toString()),null;if(h<0&&(h=d+h),-1!==r&&(d=h+r),0===c||0===u||cc&&(f=o,g+=n+a);return p},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var s,n=new i.FrameData,r=e.frames,o=0;o tag")}},i.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{},compressedTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new i.Signal,this._cacheMap=[],this._cacheMap[i.Cache.CANVAS]=this._cache.canvas,this._cacheMap[i.Cache.IMAGE]=this._cache.image,this._cacheMap[i.Cache.TEXTURE]=this._cache.texture,this._cacheMap[i.Cache.SOUND]=this._cache.sound,this._cacheMap[i.Cache.TEXT]=this._cache.text,this._cacheMap[i.Cache.PHYSICS]=this._cache.physics,this._cacheMap[i.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[i.Cache.BINARY]=this._cache.binary,this._cacheMap[i.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[i.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[i.Cache.JSON]=this._cache.json,this._cacheMap[i.Cache.XML]=this._cache.xml,this._cacheMap[i.Cache.VIDEO]=this._cache.video,this._cacheMap[i.Cache.SHADER]=this._cache.shader,this._cacheMap[i.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this._pendingCount=0,this.onReady=new i.Signal,this._addImages()},i.Cache.CANVAS=1,i.Cache.IMAGE=2,i.Cache.TEXTURE=3,i.Cache.SOUND=4,i.Cache.TEXT=5,i.Cache.PHYSICS=6,i.Cache.TILEMAP=7,i.Cache.BINARY=8,i.Cache.BITMAPDATA=9,i.Cache.BITMAPFONT=10,i.Cache.JSON=11,i.Cache.XML=12,i.Cache.VIDEO=13,i.Cache.SHADER=14,i.Cache.RENDER_TEXTURE=15,i.Cache.DEFAULT=null,i.Cache.DEFAULT_KEY="__default",i.Cache.DEFAULT_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==",i.Cache.MISSING=null,i.Cache.MISSING_KEY="__missing",i.Cache.MISSING_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==",i.Cache.READY_TIMEOUT=1e3,i.Cache.prototype={addCompressedTextureMetaData:function(t,e,s,n){this.checkImageKey(t)&&this.removeImage(t);var r=s in i.LoaderParser?i.LoaderParser[s](n):n,o={key:t,url:e,data:r,base:new PIXI.BaseTexture(r,null,this.game.resolution),frame:new i.Frame(0,0,0,r.width,r.height,t),frameData:new i.FrameData,fileFormat:s};return o.frameData.addFrame(new i.Frame(0,0,0,r.width,r.height,e)),this._cache.image[t]=o,this._resolveURL(e,o),o},addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,s){this.checkImageKey(t)&&this.removeImage(t),!1===s.complete&&console.warn('Phaser.Cache.addImage: Image "'+t+"\" hasn't been retrieved yet");var n={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution),frame:new i.Frame(0,0,0,s.width,s.height,t),frameData:new i.FrameData};return n.frameData.addFrame(new i.Frame(0,0,0,s.width,s.height,e)),this._cache.image[t]=n,this._resolveURL(e,n),"__default"===t?i.Cache.DEFAULT=new PIXI.Texture(n.base):"__missing"===t&&(i.Cache.MISSING=new PIXI.Texture(n.base)),n},addImageAsync:function(t,e,i){var s=this,n=new Image;n.onload=function(){i.call(this,s.addImage(t,null,n)),s._removePending(),n.onload=null},this._addPending(),n.src=e},addDefaultImage:function(){this.addImageAsync(i.Cache.DEFAULT_KEY,i.Cache.DEFAULT_SRC,function(t){t.base.skipRender=!0,i.Cache.DEFAULT=new PIXI.Texture(t.base)})},addMissingImage:function(){this.addImageAsync(i.Cache.MISSING_KEY,i.Cache.MISSING_SRC,function(t){i.Cache.MISSING=new PIXI.Texture(t.base)})},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,s){return e.key=t,void 0===s&&(s=new i.FrameData).addFrame(e.textureFrame),this._cache.bitmapData[t]={data:e,frameData:s},e},addBitmapFont:function(t,e,s,n,r,o,a){var h={url:e,data:s,font:null,base:new PIXI.BaseTexture(s,null,this.game.resolution)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?i.LoaderParser.jsonBitmapFont(n,h.base,o,a,!1,this.game.resolution):i.LoaderParser.xmlBitmapFont(n,h.base,o,a,!1,this.game.resolution),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addBitmapFontFromAtlas:function(t,e,s,n,r,o,a){var h=this.getFrameByName(e,s);if(h){var l={font:null,base:this.getBaseTexture(e),frame:h};void 0===o&&(o=0),void 0===a&&(a=0);var c;"json"===r?(c=this.getJSON(n),l.font=i.LoaderParser.jsonBitmapFont(c,l.base,o,a,h,this.game.resolution)):(c=this.getXML(n),l.font=i.LoaderParser.xmlBitmapFont(c,l.base,o,a,h,this.game.resolution)),this._cache.bitmapFont[t]=l}},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new i.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,s,n,r,o,a,h,l){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var c={key:t,url:e,data:s,frameWidth:n,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(s,null,this.game.resolution),frameData:i.AnimationParser.spriteSheet(this.game,s,n,r,o,a,h,l)};this._cache.image[t]=c,this._resolveURL(e,c)},addTextureAtlas:function(t,e,s,n,r){var o={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution)};r===i.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=i.AnimationParser.XMLData(this.game,n,t):r===i.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=i.AnimationParser.JSONDataPyxel(this.game,n,t):Array.isArray(n.frames)?o.frameData=i.AnimationParser.JSONData(this.game,n,t):o.frameData=i.AnimationParser.JSONDataHash(this.game,n,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(i.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(i.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(i.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(i.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(i.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(i.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(i.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(i.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(i.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(i.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(i.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(i.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(i.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(i.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(i.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,i.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var s=this.getItem(t,i.Cache.IMAGE,"getImage");return null===s&&(s=this.getItem("__missing",i.Cache.IMAGE,"getImage")),e?s:s.data},getTextureFrame:function(t){return this.getItem(t,i.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,i.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,i.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,i.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,s){var n=this.getItem(t,i.Cache.PHYSICS,"getPhysicsData","data");if(null===n||void 0===e||null===e)return n;if(n[e]){var r=n[e];if(!r||!s)return r;for(var o in r)if((o=r[o]).fixtureKey===s)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+s+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,i.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,i.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,i.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,i.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var s=this.getItem(t,i.Cache.JSON,"getJSON","data");return s?e?i.Utils.extend(!0,Array.isArray(s)?[]:{},s):s:null},getXML:function(t){return this.getItem(t,i.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,i.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,i.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,i.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,s){void 0===s&&(s=i.Cache.IMAGE),this._cacheMap[s][t]&&(this._cacheMap[s][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){return(t=this._resolveURL(t))?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=i.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var s in this._cacheMap[t])"__default"!==s&&"__missing"!==s&&e.push(s);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.image[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t0?setTimeout(function(){t.isReady||(console.warn("Phaser.Cache: Still waiting for images after %s ms.",e),t._ready())},i.Cache.READY_TIMEOUT):this._ready()},_addPending:function(){this._pendingCount+=1},_removePending:function(){this._pendingCount-=1,this._checkReady()},_checkReady:function(){this.isReady&&this._ready()},_ready:function(){this._pendingCount=0,this.onReady.dispatch(this)}},i.Cache.prototype.constructor=i.Cache,Object.defineProperty(i.Cache.prototype,"isReady",{get:function(){return this._pendingCount<=0}}),i.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new i.Signal,this.onLoadComplete=new i.Signal,this.onPackComplete=new i.Signal,this.onFileStart=new i.Signal,this.onFileComplete=new i.Signal,this.onFileError=new i.Signal,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},i.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,i.Loader.TEXTURE_ATLAS_JSON_HASH=1,i.Loader.TEXTURE_ATLAS_XML_STARLING=2,i.Loader.PHYSICS_LIME_CORONA_JSON=3,i.Loader.PHYSICS_PHASER_JSON=4,i.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,i.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new i.Rectangle(0,0,1,t.height):new i.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r=e||t&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var n=this;setTimeout(function(){n.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.reset(),this.onLoadComplete.dispatch(),this.game.state&&this.game.state.loadComplete())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(e)for(var s=0;s=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},getVideoURL:function(t){for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s="error loading asset from URL "+(t.requestUrl||this.transformUrl(t.url,t));!i&&e&&(i=e.status),i&&(s=s+" ("+i+")"),this.asyncComplete(t,s)},fileComplete:function(t,e){var s=!0;switch(t.type){case"packfile":r=JSON.parse(e.responseText);t.data=r||{};break;case"texture":var n=/\.([^.]+)$/.exec(t.url.split("?",1)[0])[1].toLowerCase();null!==t.data?this.cache.addCompressedTextureMetaData(t.key,t.url,n,t.data):this.cache.addCompressedTextureMetaData(t.key,t.url,n,e.response);break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing,t.skipFrames);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(s=!1,t.format===i.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===i.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===i.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==i.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(s=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var r=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,r,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}s&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else(e=new ActiveXObject("Microsoft.XMLDOM")).async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(i.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return i.Math.clamp(t||0,0,100)}}),Object.defineProperty(i.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),i.Loader.prototype.constructor=i.Loader,i.LoaderParser={bitmapFont:function(t,e,i,s,n,r){return this.xmlBitmapFont(t,e,i,s,n,r)},xmlBitmapFont:function(t,e,i,s,n,r){null==r&&(r=1);var o={},a=t.getElementsByTagName("info")[0],h=t.getElementsByTagName("common")[0];o.font=a.getAttribute("face"),o.size=parseInt(a.getAttribute("size"),10),o.lineHeight=parseInt(h.getAttribute("lineHeight"),10)+s,o.chars={};for(var l=t.getElementsByTagName("char"),c=n?n.x:0,u=n?n.y:0,d=0;d=0){switch(r>=0&&r<=3?e="PVRTC":r>=7&&r<=11?e="S3TC":6===r&&(e="ETC1"),r){case 0:o=35841;break;case 1:o=35843;break;case 2:o=35840;break;case 3:o=35842;break;case 6:o=36196;break;case 7:o=33777;break;case 9:o=33778;break;case 11:o=33779;break;default:o=-1}n={complete:!0,fileFormat:"PVR",compressionAlgorithm:e,flags:i[1],pixelFormat:r,colorSpace:i[4],channelType:i[5],height:i[6],width:i[7],depth:i[8],numberOfSurfaces:i[9],numberOfFaces:i[10],numberOfMipmaps:i[11],metaDataSize:i[12],textureData:s.subarray(52+i[12],s.byteLength),glExtensionFormat:o}}return n},dds:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null;return 68===e[0]&&68===e[1]&&83===e[2]&&32===e[3]&&"DX10"===(s={complete:!0,fileFormat:"DDS",compressionAlgorithm:"S3TC",size:i[1],flags:i[2],height:i[3],width:i[4],pitch:i[5],depth:i[6],mipmapCount:i[7],formatSize:i[19],formatFlag:i[19],formatFourCC:[String.fromCharCode(e[84]),String.fromCharCode(e[85]),String.fromCharCode(e[86]),String.fromCharCode(e[87])].join(""),formatBitCount:i[21],formatRBitMask:i[22],formatGBitMask:i[23],formatBBitMask:i[24],formatABitMask:i[25],caps1:i[26],caps2:i[27],caps3:i[28],caps4:i[29],reserved2:i[30],DXGIFormat:null,resourceDimension:null,miscFlag:null,arraySize:null,textureData:e.subarray(i[1]+4,e.byteLength)}).formatFourCC&&(s.DXGIFormat=i[31],s.resourceDimension=i[32],s.miscFlag=i[33],s.arraySize=i[34],s.miscFlag=i[35]),s},ktx:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null,n=16+i[15]/4|0,r=i[n],o=i[7],a=0;if(171===e[0]&&75===e[1]&&84===e[2]&&88===e[3]&&32===e[4]&&49===e[5]&&49===e[6]&&187===e[7]&&13===e[8]&&10===e[9]&&26===e[10]&&10===e[11]&&[36196,35840,35841,35842,35843,33776,33777,33778,33779].indexOf(o)>=0){switch(o){case 36196:a="ETC1";break;case 35840:case 35841:case 35842:case 35843:a="PVRTC";break;case 33776:case 33777:case 33778:case 33779:a="S3TC"}s={complete:!0,fileFormat:"KTX",compressionAlgorithm:a,endianness:i[3],glType:i[4],glTypeSize:i[5],glFormat:i[6],glInternalFormat:i[7],glBaseInternalFormat:i[8],width:i[9],height:i[10],pixelDepth:i[11],numberOfArrayElements:i[12],numberOfFaces:i[13],numberOfMipmapLevels:i[14],bytesOfKeyValueData:i[15],keyAndValueByteSize:i[16],imageSize:r,textureData:e.subarray(4*(n+1),r+100)}}return s},pkm:function(t){var e=new Uint8Array(t),i=null;return 80===e[0]&&75===e[1]&&77===e[2]&&32===e[3]&&(i={complete:!0,fileFormat:"PKM",compressionAlgorithm:"ETC1",format:65535&(e[6]<<8|e[7]),width:65535&(e[8]<<8|e[9]),height:65535&(e[10]<<8|e[11]),originalWidth:65535&(e[12]<<8|e[13]),originalHeight:65535&(e[14]<<8|e[15]),textureData:e.subarray(16,e.length)}),i}},i.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},i.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},i.AudioSprite.prototype.constructor=i.AudioSprite,i.Sound=function(t,e,s,n,r){void 0===s&&(s=1),void 0===n&&(n=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=n,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this._globalVolume=1,this._markedToDelete=!1,this._removeFromSoundManager=!1,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=s,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new i.Signal,this.onPlay=new i.Signal,this.onPause=new i.Signal,this.onResume=new i.Signal,this.onLoop=new i.Signal,this.onStop=new i.Signal,this.onMute=new i.Signal,this.onMarkerComplete=new i.Signal,this.onFadeComplete=new i.Signal,this._volume=s,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},i.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop(),this._markedToDelete&&(this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode),this._removeFromSoundManager?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()))},update:function(){this.game.cache.checkSoundKey(this.key)?(this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))):this.destroy()},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){this.isPlaying&&!this.paused&&e!==this.volume&&(void 0===t&&(t=1e3),void 0!==e?(this.fadeTween=this.game.add.tween(this).to({volume:e},t,i.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)):console.warn("Phaser.Sound.fadeTo: No Volume Specified."))},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._globalVolume=t,this._sound.volume=this._globalVolume*this._volume)},destroy:function(t){void 0===t&&(t=!0),this._markedToDelete=!0,this._removeFromSoundManager=t,this.stop(),t?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())}},i.Sound.prototype.constructor=i.Sound,Object.defineProperty(i.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(i.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(i.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(i.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted?this._muteVolume=t:(this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=this._globalVolume*t))}}),i.SoundManager=function(t){this.game=t,this.onSoundDecode=new i.Signal,this.onVolumeChange=new i.Signal,this.onMute=new i.Signal,this.onUnMute=new i.Signal,this.onTouchUnlock=new i.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new i.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},i.SoundManager.prototype={boot:function(){var t=this.game.device,e=window.PhaserGlobal;if(t.iOS&&!1===t.webAudio&&(this.channels=1),e){if(!0===e.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===e.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(e&&e.audioContext)this.context=e.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||t.needsTouchUnlock()&&this.setTouchLock(),this.usingWebAudio&&t.chrome&&t.chromeVersion<=65&&console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. ')},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0)},setTouchUnlock:function(){this.touchLocked=!1,this._unlockSource=null,this.onTouchUnlock.dispatch()},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.setTouchUnlock();else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0),"suspended"===this._unlockSource.context.state&&this._unlockSource.context.resume()}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,s=this._parentBounds.height,n=this.getParentBounds(this._parentBounds),r=n.width!==e||n.height!==s,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,n),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottlee;return(h=h?s:!s)?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},i.ScaleManager.prototype.constructor=i.ScaleManager,Object.defineProperty(i.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(i.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(i.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(i.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),i.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.lineWidth=1,this.renderShadow=!0,this.currentColor=null,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1,this.isDisabled=!1,this._line=null,this._rect=null},i.Utils.Debug.prototype={boot:function(){this.game.renderType===i.CANVAS?this.context=this.game.context:(this.bmd=new i.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=i.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d")),this._line=new i.Line,this._rect=new i.Rectangle},resize:function(){this.bmd.resize(this.game.width,this.game.height),this.canvas.width=this.game.width,this.canvas.height=this.game.height},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e0)for(var e=0;e=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new i.Rectangle,layoutBounds:new i.Rectangle,documentBounds:new i.Rectangle},i.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},s=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(i.DOM,"scrollX",{get:e}),Object.defineProperty(i.DOM,"scrollY",{get:s}),Object.defineProperty(i.DOM.visualBounds,"x",{get:e}),Object.defineProperty(i.DOM.visualBounds,"y",{get:s}),Object.defineProperty(i.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(i.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var n=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(i.DOM.visualBounds,"width",{get:n}),Object.defineProperty(i.DOM.visualBounds,"height",{get:r}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:n}),Object.defineProperty(i.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(i.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(i.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(i.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(i.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(i.ArraySet.prototype,"next",{get:function(){return this.position=s||0===i)){null==i&&(i=1);for(var n=s-i,r=e;r0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=(t=i.ArrayUtils.transposeMatrix(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=i.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var s=0;s>>0:(t<<24|e<<16|s<<8|n)>>>0},unpackPixel:function(t,e,s,n){return void 0!==e&&null!==e||(e=i.Color.createColor()),void 0!==s&&null!==s||(s=!1),void 0!==n&&null!==n||(n=!1),i.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",s&&i.Color.RGBtoHSL(e.r,e.g,e.b,e),n&&i.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=i.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},hexToRGBArray:function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},RGBArrayToHex:function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},RGBtoHSL:function(t,e,s,n){n||(n=i.Color.createColor(t,e,s,1)),t/=255,e/=255,s/=255;var r=Math.min(t,e,s),o=Math.max(t,e,s);if(n.h=0,n.s=0,n.l=(o+r)/2,o!==r){var a=o-r;n.s=n.l>.5?a/(2-o-r):a/(o+r),o===t?n.h=(e-s)/a+(e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,s,n,r,o,a,h){var l={r:t||0,g:e||0,b:s||0,a:n||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return i.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toFixed()+","+t.g.toFixed()+","+t.b.toFixed()+","+t.a.toString()+")",t.color=i.Color.getColor(t.r,t.g,t.b),t.color32=i.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,s,n,r){return void 0===n&&(n=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+s).toString(16).slice(1):"0x"+i.Color.componentToHex(n)+i.Color.componentToHex(t)+i.Color.componentToHex(e)+i.Color.componentToHex(s)},hexToRGB:function(t){var e=i.Color.hexToColor(t);if(e)return i.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var s=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(s){var n=parseInt(s[1],16),r=parseInt(s[2],16),o=parseInt(s[3],16);e?(e.r=n,e.g=r,e.b=o):e=i.Color.createColor(n,r,o)}return e},webToColor:function(t,e){e||(e=i.Color.createColor());var s=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return s&&(e.r=~~Number(s[1]),e.g=~~Number(s[2]),e.b=~~Number(s[3]),e.a=void 0!==s[4]?Number(s[4]):1,i.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=i.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?i.Color.webToColor(t,e):(e.a=1,i.Color.hexToColor(t,e));if("number"==typeof t){var s=i.Color.getRGB(t);return e.r=s.r,e.g=s.g,e.b=s.b,e.a=s.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSVtoRGB(n/359,t,e));return s},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSLtoRGB(n/359,t,e));return s},interpolateColor:function(t,e,s,n,r,o){void 0===r&&(r=255),void 0===o&&(o=0);var a=i.Color.getRGB(t),h=i.Color.getRGB(e);if(0===o)var l=(h.red-a.red)*n/s+a.red,c=(h.green-a.green)*n/s+a.green,u=(h.blue-a.blue)*n/s+a.blue;if(1===o){var d,p=i.Color.RGBtoHSV(a.r,a.g,a.b),f=i.Color.RGBtoHSV(h.r,h.g,h.b),g=f.h-p.h;if(p.h>f.h){var m=f.h;f.h=p.h,p.h=m,g=-g,n=s-n}g>.5&&(p.h=p.h+1,d=((f.h-p.h)*n/s+p.h)%1),g<=.5&&(d=(f.h-p.h)*n/s+p.h);var y=(f.s-p.s)*n/s+p.s,v=(f.v-p.v)*n/s+p.v,x=i.Color.HSVtoRGB(d,y,v,x),l=x.r,c=x.g,u=x.b}return i.Color.getColor32(r,l,c,u)},interpolateColorWithRGB:function(t,e,s,n,r,o){var a=i.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(s-a.green)*o/r+a.green,c=(n-a.blue)*o/r+a.blue;return i.Color.getColor(h,l,c)},interpolateRGB:function(t,e,s,n,r,o,a,h){var l=(n-t)*h/a+t,c=(r-e)*h/a+e,u=(o-s)*h/a+s;return i.Color.getColor(l,c,u)},linear:function(t,e,i){return this.interpolateColor(t,e,1,i)},linearInterpolation:function(t,e){var s=i.Math.linear(0,t.length-1,e),n=t[Math.floor(s)],r=t[Math.ceil(s)];return this.linear(n,r,s%1)},getRandomColor:function(t,e,s){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===s&&(s=255),e>255||t>e)return i.Color.getColor(255,255,255);var n=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return i.Color.getColor32(s,n,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=i.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return i.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return i.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return i.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?i.Color.blendLinearBurn(t,2*e):i.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?i.Color.blendColorBurn(t,2*e):i.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?i.Color.blendDarken(t,2*e):i.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return i.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return i.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},i.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},i.Physics.ARCADE=0,i.Physics.P2JS=1,i.Physics.NINJA=2,i.Physics.BOX2D=3,i.Physics.CHIPMUNK=4,i.Physics.MATTERJS=5,i.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!i.Physics.hasOwnProperty("Arcade")||(this.arcade=new i.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&i.Physics.hasOwnProperty("Ninja")&&(this.ninja=new i.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&i.Physics.hasOwnProperty("P2")&&(this.p2=new i.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&i.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new i.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&i.Physics.hasOwnProperty("Matter")&&(this.matter=new i.Physics.Matter(this.game,this.config))},startSystem:function(t){t===i.Physics.ARCADE?this.arcade=new i.Physics.Arcade(this.game):t===i.Physics.P2JS?null===this.p2?this.p2=new i.Physics.P2(this.game,this.config):this.p2.reset():t===i.Physics.NINJA?this.ninja=new i.Physics.Ninja(this.game):t===i.Physics.BOX2D?null===this.box2d?this.box2d=new i.Physics.Box2D(this.game,this.config):this.box2d.reset():t===i.Physics.MATTERJS&&(null===this.matter?this.matter=new i.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,s){void 0===e&&(e=i.Physics.ARCADE),void 0===s&&(s=!1),e===i.Physics.ARCADE?this.arcade.enable(t):e===i.Physics.P2JS&&this.p2?this.p2.enable(t,s):e===i.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===i.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===i.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},i.Physics.prototype.constructor=i.Physics,i.Physics.Arcade=function(t){this.game=t,this.gravity=new i.Point,this.bounds=new i.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=i.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new i.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._total=0,this.setBoundsToWorld()},i.Physics.Arcade.prototype.constructor=i.Physics.Arcade,i.Physics.Arcade.SORT_NONE=0,i.Physics.Arcade.LEFT_RIGHT=1,i.Physics.Arcade.RIGHT_LEFT=2,i.Physics.Arcade.TOP_BOTTOM=3,i.Physics.Arcade.BOTTOM_TOP=4,i.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof i.Group?this.enable(t[s].children,e):(this.enableBody(t[s]),e&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],!0));else t instanceof i.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.Arcade.Body(t),t.parent&&t.parent instanceof i.Group&&t.parent.addToHash(t))},updateMotion:function(t){if(t.allowRotation){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed}t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&e.allowDrag&&(i-(n*=this.game.time.physicsElapsed)>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!0),this._total>0},collide:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!1),this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===i.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===i.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===i.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===i.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideObjects:function(t,e,i,s,n,r){if(!Array.isArray(t)&&Array.isArray(e))for(o=0;oa.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(t.body.bottoma.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,s,n,r,o)}}else{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(e);for(var c=this.quadTree.retrieve(t),h=0;hc.right)continue;if(c.x>a.right)break}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(a.bottomc.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,s,n,r)}}}}},collideGroupVsGroup:function(t,e,s,n,r,o){if(0!==t.length&&0!==e.length)for(var a=0;aa.bottom)&&(h.xa.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var s=i.Math.clamp(t.center.x,e.left,e.right),n=i.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-s)*(t.center.x-s)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},separateCircle:function(t,e,s){this.getOverlapX(t,e),this.getOverlapY(t,e);var n=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,n),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.center.x:e.center.x,y:t.isCircle?t.center.y:e.center.y,radius:t.isCircle?t.halfWidth:e.halfWidth};l.yh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.xh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.halfWidth+e.halfWidth-i.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(s||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.yMath.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x)>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0):t.deltaX()n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y)>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0):t.deltaY()n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,s,n,r,o){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(s);for(var a=new i.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c0&&(s=this.distanceBetween(t,e)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.setToPolar(n,e),n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},velocityFromAngle:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e,!0)},velocityFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerationFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(o,s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i,s){void 0===i&&(i=!1);var n,r;return s?(n=t.centerX-e.centerX,r=t.centerY-e.centerY):i?(n=t.world.x-e.world.x,r=t.world.y-e.world.y):(n=t.x-e.x,r=t.y-e.y),Math.sqrt(n*n+r*r)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},closest:function(t,e,i,s){for(var n=1/0,r=null,o=0,a=e.length;on&&(r=h,n=l)}return r},angleBetween:function(t,e,s){return void 0===s&&(s=!1),s?i.Point.angle(e.world,t.world):i.Point.angle(e,t)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},i.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=i.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new i.Point,this.position=new i.Point(t.x,t.y),this.prev=new i.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new i.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new i.Point,this.newVelocity=new i.Point,this.deltaMax=new i.Point,this.acceleration=new i.Point,this.allowDrag=!0,this.drag=new i.Point,this.allowGravity=!0,this.gravity=new i.Point,this.bounce=new i.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new i.Point(1e4,1e4),this.friction=new i.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=i.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.tilePadding=new i.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new i.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},i.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter())},updateCenter:function(){this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,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=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.none=!0,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.overlapR=0,this.overlapX=0,this.overlapY=0,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.updateCenter(),this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),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,this.updateCenter(),this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=this.velocity.atan()),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=i.LEFT:this.deltaX()>0&&(this.facing=i.RIGHT),this.deltaY()<0?this.facing=i.UP:this.deltaY()>0&&(this.facing=i.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.updateCenter(),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0,this.blocked.none=!1),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0,this.blocked.none=!1),!this.blocked.none},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.setToPolar(s,e),this.isMoving=!0,!0},moveTo:function(t,e,s){var n=e/(t/1e3);if(0===n)return!1;var r;return void 0===s?(r=this.angle,s=this.game.math.radToDeg(r)):r=this.game.math.degToRad(s),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new i.Line,this.moveEnd=new i.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===s||180===s?this.velocity.set(Math.cos(r)*n,0):90===s||270===s?this.velocity.set(0,Math.sin(r)*n):this.velocity.setToPolar(r,n),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,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(i,s),this.updateCenter(),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,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(e,i),this.updateCenter()):this.isCircle=!1},reset:function(t,e){this.stop(),this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this.updateBounds(),this.updateCenter()},stop:function(){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?i.Circle.contains(this,t,e):i.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},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},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof i.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(i.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),i.Physics.Arcade.Body.render=function(t,e,i,s,n){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,t.lineWidth=n||1,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.halfWidth,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},i.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},i.Physics.Arcade.Body.prototype.constructor=i.Physics.Arcade.Body,i.Physics.Arcade.TilemapCollision=function(){},i.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x-e.getTileOffsetX(),t.body.position.y-t.body.tilePadding.y-e.getTileOffsetY(),t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;ae.deltaAbsY()?l=-1:e.deltaAbsX()0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.getTileOffsetY();return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?(t.blocked.left=!0,t.blocked.none=!1):e>0&&(t.blocked.right=!0,t.blocked.none=!1),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?(t.blocked.up=!0,t.blocked.none=!1):e>0&&(t.blocked.down=!0,t.blocked.none=!1),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},i.Utils.mixinPrototype(i.Physics.Arcade.prototype,i.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,i.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new i.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new i.Signal,this.onBodyRemoved=new i.Signal,this.onSpringAdded=new i.Signal,this.onSpringRemoved=new i.Signal,this.onConstraintAdded=new i.Signal,this.onConstraintRemoved=new i.Signal,this.onContactMaterialAdded=new i.Signal,this.onContactMaterialRemoved=new i.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},i.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,s){void 0===e&&(e=!1),void 0===s&&(s=!0);var n=1;if(Array.isArray(t))for(n=t.length;n--;)t[n]instanceof i.Group?this.enable(t[n].children,e,s):(this.enableBody(t[n],e),s&&t[n].hasOwnProperty("children")&&t[n].children.length>0&&this.enable(t[n],e,!0));else t instanceof i.Group?this.enable(t.children,e,s):(this.enableBody(t,e),s&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);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.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.DistanceConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,s,n){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.GearConstraint(this,t,e,s,n));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),s=this.getBody(s),t&&s)return this.addConstraint(new i.Physics.P2.RevoluteConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,s,n,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.LockConstraint(this,t,e,s,n,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,s,n,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.PrismaticConstraint(this,t,e,s,n,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var s=new i.Physics.P2.Material(t);return this.materials.push(s),void 0!==e&&e.setMaterial(s),s},createContactMaterial:function(t,e,s){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var n=new i.Physics.P2.ContactMaterial(t,e,s);return this.addContactMaterial(n)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof i.Physics.P2.Body?t.data:t.body&&t.body.type===i.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,s,n){void 0===e&&(e=this.world.bodies),void 0===s&&(s=5),void 0===n&&(n=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof i.Physics.P2.Body&&(!n||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!n||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof i.Sprite&&e[a].hasOwnProperty("body")&&(!n||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,s)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var s=new i.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(s),t&&this.setCollisionGroup(t,s),s},setCollisionGroup:function(t,e){if(t instanceof i.Group)for(var s=0;s-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides?n+=u.width:((p=this.createBody(r,o,0,!1)).addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0)}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(i.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(i.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(i.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(i.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(i.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(i.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(i.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(i.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(i.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),i.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},i.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionGroup=t})},setMask:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionMask=t})},setSensor:function(t,e){this.getFixtures(e).forEach(function(e){e.sensor=t})},setMaterial:function(t,e){this.getFixtures(e).forEach(function(e){e.material=t})},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},i.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.PointProxy.prototype.constructor=i.Physics.P2.PointProxy,Object.defineProperty(i.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),i.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.InversePointProxy.prototype.constructor=i.Physics.P2.InversePointProxy,Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),i.Physics.P2.Body=function(t,e,s,n,r){e=e||null,s=s||0,n=n||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=i.Physics.P2JS,this.offset=new i.Point,this.data=new p2.Body({position:[this.world.pxmi(s),this.world.pxmi(n)],mass:r}),this.data.parent=this,this.velocity=new i.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new i.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new i.Point,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},i.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(r=0;r-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var n=this.getCollisionMask();if(void 0===i)for(var r=this.data.shapes.length-1;r>=0;r--)this.data.shapes[r].collisionMask=n;else i.collisionMask=n},collides:function(t,e,i,s){if(Array.isArray(t))for(r=0;r=0;r--)this.data.shapes[r].collisionMask=n;else s.collisionMask=n},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},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(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;np;n=0<=p?++d:--d)l=e.vertices[n],p2.vec2.rotate(u,l,t),c.push([(u[0]+a[0])*this.ppu,-(u[1]+a[1])*this.ppu]);this.drawConvex(h,c,e.triangles,16711680,i,r,this.settings.debugPolygons,[a[0]*this.ppu,-a[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)p=(c=e[l])[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return 2===(e=t.toString(16)).length?e:e+"0"}}),i.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1);var c={restLength:s=t.pxm(s),stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},i.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),i.Physics.P2.Material.prototype.constructor=i.Physics.P2.Material,i.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},i.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),i.Physics.P2.ContactMaterial.prototype.constructor=i.Physics.P2.ContactMaterial,i.Physics.P2.CollisionGroup=function(t){this.mask=t},i.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t;var a={distance:s=t.pxm(s),localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},i.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),i.Physics.P2.DistanceConstraint.prototype.constructor=i.Physics.P2.DistanceConstraint,i.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},i.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),i.Physics.P2.GearConstraint.prototype.constructor=i.Physics.P2.GearConstraint,i.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t;var o={localOffsetB:s=[t.pxm(s[0]),t.pxm(s[1])],localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},i.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),i.Physics.P2.LockConstraint.prototype.constructor=i.Physics.P2.LockConstraint,i.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t;var h={localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},i.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),i.Physics.P2.PrismaticConstraint.prototype.constructor=i.Physics.P2.PrismaticConstraint,i.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},i.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),i.Physics.P2.RevoluteConstraint.prototype.constructor=i.Physics.P2.RevoluteConstraint,i.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},i.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&tthis.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},i.Tile.prototype.constructor=i.Tile,Object.defineProperty(i.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(i.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(i.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(i.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(i.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(i.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),i.Tilemap=function(t,e,s,n,r,o){this.game=t,this.key=e;var a=i.TilemapParser.parse(this.game,e,s,n,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},i.Tilemap.CSV=0,i.Tilemap.TILED_JSON=1,i.Tilemap.NORTH=0,i.Tilemap.EAST=1,i.Tilemap.SOUTH=2,i.Tilemap.WEST=3,i.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,s,n,r,o,a){if(void 0===t)return null;void 0===s&&(s=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===s&&(s=32),0===n&&(n=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof i.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===i.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),console.log("Tilesets: ",this.tilesets),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new i.Tileset(t,a,s,n,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y1)for(u=0;uthis.layers.length)return console.warn('Tilemap.createLayer: Invalid layer ID given: "'+t+'"'),void console.log("Layers: ",this.layers);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===s||s<=0?s=Math.min(this.game.height,this.layers[r].heightInPixels):s>this.game.height&&(s=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",s),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=n.add(new i.TilemapLayer(this.game,this,r,e,s));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,s,n,r,o){void 0===o&&(o=this.game.world);{if(null===this.getLayerIndex(t)){for(var a,h={name:t,x:0,y:0,width:e,height:s,widthInPixels:e*n,heightInPixels:s*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;cthis.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height),(l=new i.TilemapLayer(this.game,this,this.layers.length-1,d,p)).name=t,o.add(l)}console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t)}},getIndex:function(t,e){for(var i=0;ie)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n-1&&this.collideIndexes.splice(n,1)}for(var r=0;r0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e-1},removeTile:function(t,e,s){if(s=this.getLayer(s),t>=0&&t=0&&e=0&&e=0&&s-1?this.layers[n].data[s][e].setCollision(!0,!0,!0,!0):this.layers[n].data[s][e].resetCollision(),this.layers[n].dirty=!0,this.calculateFaces(n),this.layers[n].data[s][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(r=this.layers[s].height-1;r>=0;r--)for(o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r=0&&t=0&&ethis.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},i.Tilemap.prototype.constructor=i.Tilemap,Object.defineProperty(i.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),i.TilemapLayer=function(t,e,s,n,r){n|=0,r|=0,i.Sprite.call(this,t,0,0),this.map=e,this.index=s,this.layer=e.layers[s],this.canvas=i.CanvasPool.create(this,n,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas,null,this.game.resolution))),this.type=i.TILEMAPLAYER,this.physicsType=i.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!0,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this.tileOffset=new i.Point(this.layer.offsetX||0,this.layer.offsetY||0),this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=i.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},i.TilemapLayer.prototype=Object.create(i.Sprite.prototype),i.TilemapLayer.prototype.constructor=i.TilemapLayer,i.TilemapLayer.prototype.preUpdateCore=i.Component.Core.preUpdate,i.TilemapLayer.sharedCopyCanvas=null,i.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=i.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},i.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},i.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y},i.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.TilemapLayer.prototype.destroy=function(){i.CanvasPool.remove(this),i.Component.Destroy.prototype.destroy.call(this)},i.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},i.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},i.TilemapLayer.prototype.getTileOffsetX=function(){return this.tileOffset.x||(this.fixedToCamera?0:this.position.x)},i.TilemapLayer.prototype.getTileOffsetY=function(){return this.tileOffset.y||(this.fixedToCamera?0:this.position.y)},i.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},i.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},i.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},i.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},i.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},i.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},i.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},i.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a=0;m++,v--,f+=c){m>=h&&(m-=h);var _=this.layer.data[m];for(g=b,y=n-i,p=x;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var w=_[g];if(w&&!(w.index<0)){var T=w.index,P=u[T];void 0===P&&(P=this.resolveTileset(T)),w.alpha===d||this.debug||(o.globalAlpha=w.alpha,d=w.alpha),P?w.rotation||w.flipped?(o.save(),o.translate(p+w.centerX,f+w.centerY),o.rotate(w.rotation),w.flipped&&o.scale(-1,1),P.draw(o,-w.centerX,-w.centerY,T),o.restore()):P.draw(o,p,f,T):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),w.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},i.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},i.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},i.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)=0;s++,r--,e+=f){s>=d&&(s-=d);var T=this.layer.data[s];for(i=_,n=m-g,t=x;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var P=T[i];!P||P.index<0||!P.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),P.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),P.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),P.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),P.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(i.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),i.TilemapParser={INSERT_NULL:!1,parse:function(t,e,s,n,r,o){if(void 0===s&&(s=32),void 0===n&&(n=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(s,n,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===i.Tilemap.CSV)return this.parseCSV(e,a.data,s,n);if(!a.format||a.format===i.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,s,n){for(var r=this.getEmptyData(),o=[],a=(e=e.trim()).split("\n"),h=a.length,l=0,c=0;c>>0;r.data=h,delete r.encoding}else if(r.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+r.name+"'");continue}k={name:r.name,x:r.x,y:r.y,width:r.width,height:r.height,widthInPixels:r.width*t.tilewidth,heightInPixels:r.height*t.tileheight,alpha:r.opacity,offsetX:r.offsetx,offsetY:r.offsety,visible:r.visible,properties:{},indexes:[],callbacks:[],bodies:[]};r.properties&&(k.properties=r.properties);for(var c,u,d,p=0,f=[],g=[],m=0,a=r.data.length;m536870912)switch(A>2147483648&&(A-=2147483648,d+=4),A>1073741824&&(A-=1073741824,d+=2),A>536870912&&(A-=536870912,d+=1),d){case 5:c=Math.PI/2;break;case 6:c=Math.PI;break;case 3:c=3*Math.PI/2;break;case 4:c=0,u=!0;break;case 7:c=Math.PI/2,u=!0;break;case 2:c=Math.PI,u=!0;break;case 1:c=3*Math.PI/2,u=!0}A>0?((F=new i.Tile(k,A,p,g.length,t.tilewidth,t.tileheight)).rotation=c,F.flipped=u,0!==d&&(F.flippedVal=d),f.push(F)):i.TilemapParser.INSERT_NULL?f.push(null):f.push(new i.Tile(k,-1,p,g.length,t.tilewidth,t.tileheight)),++p===r.width&&(g.push(f),p=0,f=[])}k.data=g,s.push(k)}e.layers=s;for(var y=[],n=0;n=0&&n+1=this.firstgid&&t=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(t=0;t=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._total>0&&this._counter>=this._total&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},i.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1),void 0===r&&(r=null);var o,a=0,h=t,l=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);athis.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},i.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),this.resetParticle(n,o,a),!0},i.Particles.Arcade.Emitter.prototype.getNextParticle=function(){for(var t=this.length;t--;){var e=this.next();if(!e.exists)return e}return null},i.Particles.Arcade.Emitter.prototype.resetParticle=function(t,e,i){var s=this.game.rnd;t.reset(e,i),t.angle=0,t.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(t):this.particleSendToBack&&this.sendToBack(t),this.autoScale?t.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?t.scale.set(s.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y?t.scale.set(s.realInRange(this._minParticleScale.x,this._maxParticleScale.x),s.realInRange(this._minParticleScale.y,this._maxParticleScale.y)):t.scale.set(this._minParticleScale.x,this._minParticleScale.y),this.autoAlpha?t.setAlphaData(this.alphaData):t.alpha=s.realInRange(this.minParticleAlpha,this.maxParticleAlpha),t.blendMode=this.blendMode;var n=t.body;n.updateBounds(),n.bounce.copyFrom(this.bounce),n.drag.copyFrom(this.particleDrag),null!=this.minAngle&&null!=this.maxAngle?this.game.physics.arcade.velocityFromAngle(this.minAngle===this.maxAngle?this.minAngle:s.between(this.minAngle,this.maxAngle),this.minSpeed===this.maxSpeed?this.minSpeed:s.between(this.minSpeed,this.maxSpeed),n.velocity):(n.velocity.x=s.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),n.velocity.y=s.between(this.minParticleSpeed.y,this.maxParticleSpeed.y)),n.angularVelocity=s.between(this.minRotation,this.maxRotation),n.gravity.copyFrom(this.gravity),n.angularDrag=this.angularDrag,t.onEmit()},i.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),i.Group.prototype.destroy.call(this,!0,!1)},i.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},i.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},i.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},i.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},i.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,s,n,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=0),void 0===n&&(n=i.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,s>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},s,n);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},i.Particles.Arcade.Emitter.prototype.setScale=function(t,e,s,n,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=1),void 0===n&&(n=1),void 0===r&&(r=0),void 0===o&&(o=i.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,s),this._maxParticleScale.set(e,n),this.autoScale=!1,r>0&&(t!==e||s!==n)){var h={x:t,y:s},l=this.game.make.tween(h).to({x:e,y:n},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},i.Particles.Arcade.Emitter.prototype.setAngle=function(t,e,i,s){return this.minAngle=t,this.maxAngle=e,null!=i&&(this.minSpeed=i),null!=s&&(this.maxSpeed=s),this},i.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"gravity",{get:function(){return this._gravity},set:function(t){"number"==typeof t?this._gravity.y=t:this._gravity=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"id",{get:function(){return this._id}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"output",{get:function(){return 1e3*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"lifespanOutput",{get:function(){return(0===this.lifespan?1/0:this.lifespan)*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"remainder",{get:function(){return this.maxParticles-this.lifespanOutput}}),i.Weapon=function(t,e){i.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new i.Rectangle(0,0,1,1),this.fireAngle=i.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new i.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=i.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=i.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new i.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new i.Signal,this.onKill=new i.Signal,this.onFireLimit=new i.Signal,this.trackedSprite=null,this.trackedPointer=null,this.multiFire=!1,this._hasFired=!1,this.trackRotation=!1,this.trackOffset=new i.Point,this._nextFire=0,this._tempNextFire=0,this._rotatedPoint=new i.Point},i.Weapon.prototype=Object.create(i.Plugin.prototype),i.Weapon.prototype.constructor=i.Weapon,i.Weapon.KILL_NEVER=0,i.Weapon.KILL_LIFESPAN=1,i.Weapon.KILL_DISTANCE=2,i.Weapon.KILL_WEAPON_BOUNDS=3,i.Weapon.KILL_CAMERA_BOUNDS=4,i.Weapon.KILL_WORLD_BOUNDS=5,i.Weapon.KILL_STATIC_BOUNDS=6,i.Weapon.prototype.createBullets=function(t,e,s,n){return void 0===t&&(t=1),void 0===n&&(n=this.game.world),this.bullets&&!this.bullets.game&&(this.bullets=null),this.bullets||(this.bullets=this.game.add.physicsGroup(i.Physics.ARCADE,n),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,s),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=s),this},i.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},i.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},i.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},i.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},i.Weapon.prototype.update=function(){this._bulletKillType===i.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},i.Weapon.prototype.postRender=function(){this.multiFire&&this._hasFired&&(this._hasFired=!1,this._nextFire=this._tempNextFire)},i.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},i.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},i.Weapon.prototype.fireMany=function(t,e){this.multiFire=!0;var i=[],s=this;return e||this.trackedSprite||this.trackedPointer?t.forEach(function(t){i.push(s.fire(e,null,null,t.x,t.y))}):t.forEach(function(t){i.push(s.fire(t))}),i},i.Weapon.prototype.fireOffset=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.fire(null,null,null,t,e)},i.Weapon.prototype.fire=function(t,e,s,n,r){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game.time.now0&&this.shots===this.fireLimit)return null;var o=this.bulletSpeed;0!==this.bulletSpeedVariance&&(o+=i.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.worldRotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(o+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y)),void 0!==n&&(this.fireFrom.x+=n),void 0!==r&&(this.fireFrom.y+=r);var a=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,h=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,l=this.trackRotation?this.trackedSprite.angle:this.fireAngle;null!==e&&null!==s&&(l=this.game.math.radToDeg(Math.atan2(s-h,e-a))),0!==this.bulletAngleVariance&&(l+=i.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var c=0,u=0;0===l||180===l?c=Math.cos(this.game.math.degToRad(l))*o:90===l||270===l?u=Math.sin(this.game.math.degToRad(l))*o:(c=Math.cos(this.game.math.degToRad(l))*o,u=Math.sin(this.game.math.degToRad(l))*o);var d=null;if(this.autoExpandBulletsGroup?(d=this.bullets.getFirstExists(!1,!0,a,h,this.bulletKey,this.bulletFrame)).data.bulletManager=this:d=this.bullets.getFirstExists(!1),d){if(d.reset(a,h),d.data.fromX=a,d.data.fromY=h,d.data.killType=this.bulletKillType,d.data.killDistance=this.bulletKillDistance,d.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===i.Weapon.KILL_LIFESPAN&&(d.lifespan=this.bulletLifespan),d.angle=l+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===d.animations.getAnimation(this.bulletAnimation)){var p=this.anims[this.bulletAnimation];d.animations.add(p.name,p.frames,p.frameRate,p.loop,p.useNumericIndex)}d.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(d.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(d.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);d.data.bodyDirty&&(this._data.customBody&&d.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),d.body.collideWorldBounds=this.bulletCollideWorldBounds,d.data.bodyDirty=!1),d.body.velocity.set(c,u),d.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y);var f=0;if(0!==this.bulletSpeedVariance){var g=this.fireRate;(g+=i.Math.between(-this.fireRateVariance,this.fireRateVariance))<0&&(g=0),f=this.game.time.now+g}else f=this.game.time.now+this.fireRate;this.multiFire?this._hasFired||(this._hasFired=!0,this._tempNextFire=f,this.shots++):(this._nextFire=f,this.shots++),this.onFire.dispatch(d,this,o),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return d},i.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},i.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},i.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},i.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},i.Weapon.prototype.setBulletFrames=function(t,e,s,n){return void 0===s&&(s=!0),void 0===n&&(n=!1),this.bulletFrames=i.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=s,this.bulletFrameRandom=n,this},i.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},i.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(i.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets&&(this.bullets.classType=this._bulletClass)}}),Object.defineProperty(i.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case i.Weapon.KILL_STATIC_BOUNDS:case i.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case i.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case i.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(i.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(i.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(i.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),i.Bullet=function(t,e,s,n,r){i.Sprite.call(this,t,e,s,n,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},i.Bullet.prototype=Object.create(i.Sprite.prototype),i.Bullet.prototype.constructor=i.Bullet,i.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},i.Bullet.prototype.update=function(){this.exists&&(this.data.killType>i.Weapon.KILL_LIFESPAN&&(this.data.killType===i.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=this.body.velocity.atan()),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},i.Video=function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=i.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new i.Signal,this.onChangeSource=new i.Signal,this.onComplete=new i.Signal,this.onAccess=new i.Signal,this.onError=new i.Signal,this.onTimeout=new i.Signal,this.onTouchUnlock=new i.Signal,this.playWhenUnlocked=!0,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._pendingChangeSource=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var n=this.game.cache.getVideo(e);n.isBlob?this.createVideoFromBlob(n.data):this.video=n.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else s&&this.createVideoFromURL(s,!1);this.video&&!s?(this.baseTexture=new PIXI.BaseTexture(this.video,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(i.Cache.DEFAULT.baseTexture.source,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new i.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,i.BitmapData&&(this.snapshot=new i.BitmapData(this.game,"",this.width,this.height)),this.game.device.needsTouchUnlock()?this.setTouchLock():n&&(n.locked=!1)},i.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return this._pendingChangeSource?this:(void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this)},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming)},setTouchLock:function(){this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.playWhenUnlocked&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return this.onTouchUnlock.dispatch(this),!0},grab:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null!==this.snapshot)return t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot;console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable")},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(i.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(i.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(i.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(i.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(i.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(i.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(i.Video.prototype,"playing",{get:function(){return!!this.video&&!(this.video.paused&&this.video.ended)}}),i.Video.prototype.constructor=i.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=i.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=i.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new i.Matrix),PIXI.TextureSilentFail=!0,PIXI.canUseNewCanvasBlendModes=function(){return i.Device.canUseMultiply},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=i),exports.Phaser=i):"undefined"!=typeof define&&define.amd?define("Phaser",e.Phaser=i):e.Phaser=i,i}.call(this); +//# sourceMappingURL=phaser.map \ No newline at end of file diff --git a/Digital Assignment 5/sources.txt b/Digital Assignment 5/sources.txt new file mode 100644 index 000000000..0e3a6ebfd --- /dev/null +++ b/Digital Assignment 5/sources.txt @@ -0,0 +1,6 @@ +https://phaser.io/examples/v2/buttons/action-on-click +https://phaser.io/examples/v2/camera/smooth-follow +https://phaser.io/examples/v2/arcade-physics/bounce-accelerator +https://phaser.io/examples/v2/arcade-physics/on-collide-event +https://phaser.io/examples/v2/input/bounds-rect + diff --git a/Iteration Sequence 1.2/assets/Fire.png b/Iteration Sequence 1.2/assets/Fire.png new file mode 100644 index 000000000..2caa21c58 Binary files /dev/null and b/Iteration Sequence 1.2/assets/Fire.png differ diff --git a/Iteration Sequence 1.2/assets/Play.png b/Iteration Sequence 1.2/assets/Play.png new file mode 100644 index 000000000..32ec4a7a7 Binary files /dev/null and b/Iteration Sequence 1.2/assets/Play.png differ diff --git a/Iteration Sequence 1.2/assets/Poppers and Prosecco.mp3 b/Iteration Sequence 1.2/assets/Poppers and Prosecco.mp3 new file mode 100644 index 000000000..d55aef201 Binary files /dev/null and b/Iteration Sequence 1.2/assets/Poppers and Prosecco.mp3 differ diff --git a/Iteration Sequence 1.2/assets/adventurer_tilesheet.png b/Iteration Sequence 1.2/assets/adventurer_tilesheet.png new file mode 100644 index 000000000..6503a0d7e Binary files /dev/null and b/Iteration Sequence 1.2/assets/adventurer_tilesheet.png differ diff --git a/Iteration Sequence 1.2/assets/boss_bg.png b/Iteration Sequence 1.2/assets/boss_bg.png new file mode 100644 index 000000000..a1d1931a3 Binary files /dev/null and b/Iteration Sequence 1.2/assets/boss_bg.png differ diff --git a/Iteration Sequence 1.2/assets/boundaries.png b/Iteration Sequence 1.2/assets/boundaries.png new file mode 100644 index 000000000..df787f453 Binary files /dev/null and b/Iteration Sequence 1.2/assets/boundaries.png differ diff --git a/Iteration Sequence 1.2/assets/play_button.json b/Iteration Sequence 1.2/assets/play_button.json new file mode 100644 index 000000000..174926e9c --- /dev/null +++ b/Iteration Sequence 1.2/assets/play_button.json @@ -0,0 +1,36 @@ +{"frames": [ + +{ + "filename": "down", + "frame": {"x":0,"y":142,"w":193,"h":71}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":193,"h":71}, + "sourceSize": {"w":193,"h":71} +}, +{ + "filename": "out", + "frame": {"x":0,"y":71,"w":193,"h":71}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":193,"h":71}, + "sourceSize": {"w":193,"h":71} +}, +{ + "filename": "over", + "frame": {"x":0,"y":0,"w":193,"h":71}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":193,"h":71}, + "sourceSize": {"w":193,"h":71} +}], +"meta": { + "app": "http://www.texturepacker.com", + "version": "1.0", + "image": "button_texture_atlas.png", + "format": "RGBA8888", + "size": {"w":193,"h":213}, + "scale": "1", + "smartupdate": "$TexturePacker:SmartUpdate:94df81041404a206a4e9cd597a1e3495$" +} +} diff --git a/Iteration Sequence 1.2/assets/play_button.png b/Iteration Sequence 1.2/assets/play_button.png new file mode 100644 index 000000000..3cea4699b Binary files /dev/null and b/Iteration Sequence 1.2/assets/play_button.png differ diff --git a/Iteration Sequence 1.2/assets/preloader_background.jpg b/Iteration Sequence 1.2/assets/preloader_background.jpg new file mode 100644 index 000000000..feae1e6e1 Binary files /dev/null and b/Iteration Sequence 1.2/assets/preloader_background.jpg differ diff --git a/Iteration Sequence 1.2/assets/preloader_bar.png b/Iteration Sequence 1.2/assets/preloader_bar.png new file mode 100644 index 000000000..ee98e864e Binary files /dev/null and b/Iteration Sequence 1.2/assets/preloader_bar.png differ diff --git a/Iteration Sequence 1.2/assets/sheet.png b/Iteration Sequence 1.2/assets/sheet.png new file mode 100644 index 000000000..9932350f5 Binary files /dev/null and b/Iteration Sequence 1.2/assets/sheet.png differ diff --git a/Iteration Sequence 1.2/assets/stat.png b/Iteration Sequence 1.2/assets/stat.png new file mode 100644 index 000000000..e71ad26e7 Binary files /dev/null and b/Iteration Sequence 1.2/assets/stat.png differ diff --git a/Iteration Sequence 1.2/assets/temp_bg.jpg b/Iteration Sequence 1.2/assets/temp_bg.jpg new file mode 100644 index 000000000..b8b9f35af Binary files /dev/null and b/Iteration Sequence 1.2/assets/temp_bg.jpg differ diff --git a/Iteration Sequence 1.2/assets/test.json b/Iteration Sequence 1.2/assets/test.json new file mode 100644 index 000000000..428eed420 --- /dev/null +++ b/Iteration Sequence 1.2/assets/test.json @@ -0,0 +1,100 @@ +{"frames": [ + +{ + "filename": "run00", + "frame": {"x":34,"y":128,"w":56,"h":60}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":2,"w":56,"h":60}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run01", + "frame": {"x":54,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run02", + "frame": {"x":54,"y":58,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run03", + "frame": {"x":0,"y":192,"w":34,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":11,"y":0,"w":34,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run04", + "frame": {"x":0,"y":64,"w":54,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":1,"y":0,"w":54,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run05", + "frame": {"x":196,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run06", + "frame": {"x":0,"y":0,"w":54,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":1,"y":0,"w":54,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run07", + "frame": {"x":140,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run08", + "frame": {"x":34,"y":188,"w":50,"h":60}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":3,"y":2,"w":50,"h":60}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run09", + "frame": {"x":0,"y":128,"w":34,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":11,"y":0,"w":34,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run10", + "frame": {"x":84,"y":188,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}], +"meta": { + "app": "http://www.texturepacker.com", + "version": "1.0", + "image": "running_bot.png", + "format": "RGBA8888", + "size": {"w":252,"h":256}, + "scale": "0.2", + "smartupdate": "$TexturePacker:SmartUpdate:fb56f261b1eb04e3215824426595f64c$" +} +} diff --git a/Iteration Sequence 1.2/assets/title.jpg b/Iteration Sequence 1.2/assets/title.jpg new file mode 100644 index 000000000..d416d3bb1 Binary files /dev/null and b/Iteration Sequence 1.2/assets/title.jpg differ diff --git a/Iteration Sequence 1.2/assets/zombie_tilesheet.png b/Iteration Sequence 1.2/assets/zombie_tilesheet.png new file mode 100644 index 000000000..c74571f69 Binary files /dev/null and b/Iteration Sequence 1.2/assets/zombie_tilesheet.png differ diff --git a/Iteration Sequence 1.2/index.html b/Iteration Sequence 1.2/index.html new file mode 100644 index 000000000..7eff70e9f --- /dev/null +++ b/Iteration Sequence 1.2/index.html @@ -0,0 +1,140 @@ + + + + + Iteration Sequence 1.2 + + + + + + + + + + + + + + +
+
+

Iteration Sequence 1.2

+
    +
  • Originality: + What is original about your game? +
  • +
      +
    • + The final game (This is only a prototype) will be similar to super mario brothers but with additional powers from the pre-game phase. +
    • +
    +
  • Technical Merit: + What is interesting about your game technology? +
  • +
      +
    • Players will be able to attempt trials for additional abilities. (The trial itself will be a minigame for each category but not implemented for this prototype.)
    • +
    +
  • Prototype Postmortem: + What did you learn from this prototype? What was the easiest or hardest part of making it? +
  • +
      +
    • How to implement different states.
    • +
    • Learned more about arcade physics.
    • +
    • How to use different keyboard inputs.
    • +
    +
  • Prototype Assets: + Did you make your prototype assets from scratch? Did you borrow them? Cite your sources here. + + +
  • Prototype Closest Other Game: + Which other game most closely resembles your game? If you are borrowing code from a Phaser Example, you must say so here. If you borrow code from elsewhere, you must say so here. +
  • +
      +
    • Concept started from Super Mario Brothers but the end product should be completely different. Everything is original.
    • +
    +
  • High Concept: + A one-sentence summary of your game. +
  • +
      +
    • Make your character stronger during the power up phase and defeat the boss.
    • +
    +
  • Theme: + State which of the Storymatic themes you used. +
  • +
      +
    • N/A
    • +
    +
  • Mandated Variety: + State which input, randomness, genre, and play style you used in this prototype. +
  • +
      +
    • Input: keyboard + clickable buttons.
    • +
    • Randomness: A lot of randomness early. Some planning is possible. Once the boss fight starts most elements are deterministic.
    • +
    • Play style: Competitor. Could also be collector/achiever from the stat gaining phase.
    • +
    • Genre: Platformer / Mini RPG
    • +
    +
  • Prototype Goal: + What game mechanic is this prototype evaluating? +
  • +
      +
    • This prototype has only implemented the basic functions of my physical prototype.
    • +
    • This prototype will help me with balancing the stat gains and adjust the amount if needed
    • +
    +
  • Player Experience Goals: + What experience do you want players to have when playing your game? +
  • +
      +
    • Deciding which stats to upgrade with the limited amount of stat points.
    • +
    • Multiple replay value as players can attempt to beat the game with different stats / randomly gained stats.
    • +
    +
  • Gameplay: + A paragraph describing the actions the player can perform, the system dynamics, and the core mechanic. Include a concise explanation of the prototype’s inputs and their expected effects (how to play). You can also describe game play that is not in the prototype. You may include mock-up images for parts of the game not in the prototype. +
  • +
      +
    • The player enters a room to boost a stat of their choice. If they successfully complete it, they are granted a level in the stat point. With the earned stat points they can now attempt to clear the stage. All game instruction is listed directly in the game as I found it to be more helpful to find instrutions directly from the game rather than our evaluation html.
    • +
    +
  • Strategies: + What player strategies do you expect will be effective at playing this game? +
  • +
      +
    • Players have to think whether it is a good idea to upgrade a certain stat. For instance, a player can choose whether they like strength or resistance more.
    • +
    +
  • Story/Setting/Premise: + A paragraph about the world your game is set in and who the characters are. What makes the game world and its occupants unique and interesting? Do the tokens represent something? If the game has a backstory, mention it here. If the game is abstract, then say so. + How will the dramatic tension interact with the gameplay tension? +
  • +
      +
    • No Story for this game for now.
    • +
    +
  • Target Audience: + A single sentence that describes the demographic you're trying to reach. +
  • +
      +
    • Preferably all ages.
    • +
    +
  • Play Time: + How long does your game take to play? +
  • +
      +
    • This prototype should take about a minute or two.
    • +
    +
+ + \ No newline at end of file diff --git a/Iteration Sequence 1.2/js/Boot.js b/Iteration Sequence 1.2/js/Boot.js new file mode 100644 index 000000000..349a93294 --- /dev/null +++ b/Iteration Sequence 1.2/js/Boot.js @@ -0,0 +1,48 @@ +"use strict"; + +var GameStates = {}; + +GameStates.makeBoot = function( game ) { + return { + init: function () { + + // Unless you specifically know your game needs to support multi-touch I would recommend setting this to 1 + game.input.maxPointers = 1; + + // Phaser will automatically pause if the browser tab the game is in loses focus. You can disable that here: + game.stage.disableVisibilityChange = true; + + if (game.device.desktop) + { + // If you have any desktop specific settings, they can go in here + game.scale.pageAlignHorizontally = true; + } + else + { + // Same goes for mobile settings. + // In this case we're saying "scale the game, no lower than 480x260 and no higher than 1024x768" + game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; + game.scale.setMinMax(480, 260, 1024, 768); + game.scale.forceLandscape = true; + game.scale.pageAlignHorizontally = true; + } + + }, + + preload: function () { + + // Here we load the assets required for our Preloader state (in this case a background and a loading bar) + game.load.image('preloaderBackground', 'assets/preloader_background.jpg'); + game.load.image('preloaderBar', 'assets/preloader_bar.png'); + + }, + + create: function () { + + // By this point the preloader assets have loaded to the cache, we've set the game settings + // So now let's start the real preloader going + game.state.start('Preloader'); + + } + }; +}; diff --git a/Iteration Sequence 1.2/js/Game.js b/Iteration Sequence 1.2/js/Game.js new file mode 100644 index 000000000..4d34da614 --- /dev/null +++ b/Iteration Sequence 1.2/js/Game.js @@ -0,0 +1,342 @@ +"use strict"; + +GameStates.makeGame = function( game, shared ) { + // Create your own variables. + var button1; + var button2; + var button3; + var button4; + var button5; + + //var exit_button; + var esc_key; + var space_key; + + var player; + var cursors; + + var txt_style = {font: "20px Arial"}; + var stat_text; + var stat_text2; + + var stat_msg; + var stat_msg2 = ''; + var stat_change; + + var RNG; + + + function quitGame() { + // Here you should destroy anything you no longer need. + // Stop music, delete sprites, purge caches, free resources, all that good stuff. + + // Then let's go back to the main menu. + game.state.start('MainMenu'); + + } + + function bossFight() { + + if (shared.stat_remain == 0) + { + game.state.start('Boss'); + } + else + { + stat_msg2.setText("Consume all your stat points before\nfighting the boss.") + } + } + + + function pauseGame() { + console.log('pauseGame'); + // Here you should destroy anything you no longer need. + // Stop music, delete sprites, purge caches, free resources, all that good stuff. + + // Then let's go back to the main menu. + game.state.start('Pause'); + + } + + /* + function updateText() + { + stat_text2.setText(shared.stat_strength + '\n' + shared.stat_resist + '\n' + shared.stat_speed + '\n' + shared.stat_luck + '\n' + shared.stat_remain); + } + */ + + function updateSuccess() + { + stat_msg2.setText('Success. Remaining stat points: ' + shared.stat_remain); + } + + function updateFail() + { + stat_msg2.setText('Fail. Remaining stat points: ' + shared.stat_remain); + } + + function updateStatError() + { + stat_msg2.setText('Not enough Stat points. Click on the boss icon.'); + } + + function updateMaxStat() + { + stat_msg2.setText("This stat is already maxed."); + } + + function changeStats() + { + console.log('Change Stats'); + + if (shared.stat_remain > 0) + { + if (player.x >= 250 && player.x < 320) + { + shared.stat_type = 1; + } + else if (player.x >= 400 && player.x < 470) + { + shared.stat_type = 2; + } + else if (player.x >= 550 && player.x < 620) + { + shared.stat_type = 3; + } + else if (player.x >= 700 && player.x < 770) + { + shared.stat_type = 4; + } + else + { + shared.stat_type = -1; + } + + RNG = game.rnd.integerInRange(0, 99); + + + switch (shared.stat_type) + { + case 1: + if (shared.stat_strength == 0 && RNG > 19 - (shared.stat_luck * 5)) + { + shared.stat_strength++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_strength == 1 && RNG > 39 - (shared.stat_luck * 5)) + { + shared.stat_strength++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_strength == 2 && RNG > 59 - (shared.stat_luck * 5)) + { + shared.stat_strength++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_strength == 3) + { + updateMaxStat(); + } + else + { + shared.stat_remain--; + updateFail(); + } + break; + case 2: + if (shared.stat_resist == 0 && RNG > 19 - (shared.stat_luck * 5)) + { + shared.stat_resist++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_resist == 1 && RNG > 39 - (shared.stat_luck * 5)) + { + shared.stat_resist++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_resist == 2 && RNG > 59 - (shared.stat_luck * 5)) + { + shared.stat_resist++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_resist == 3) + { + updateMaxStat(); + } + else + { + shared.stat_remain--; + updateFail(); + } + break; + case 3: + if (shared.stat_speed == 0 && RNG > 19 - (shared.stat_luck * 5)) + { + shared.stat_speed++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_speed == 1 && RNG > 39 - (shared.stat_luck * 5)) + { + shared.stat_speed++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_speed == 2 && RNG > 59 - (shared.stat_luck * 5)) + { + shared.stat_speed++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_speed == 3) + { + updateMaxStat(); + } + else + { + shared.stat_remain--; + updateFail(); + } + break; + case 4: + if (shared.stat_luck == 0 && RNG > 19 - (shared.stat_luck * 5)) + { + shared.stat_luck++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_luck == 1 && RNG > 39 - (shared.stat_luck * 5)) + { + shared.stat_luck++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_luck == 2 && RNG > 59 - (shared.stat_luck * 5)) + { + shared.stat_luck++; + shared.stat_remain--; + updateSuccess(); + } + else if (shared.stat_luck == 3) + { + updateMaxStat(); + } + else + { + shared.stat_remain--; + updateFail(); + } + break; + default: + break; + } + } + else + { + updateStatError(); + } + } + + return { + + create: function () { + + console.log('Test Game'); + + // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! + game.add.tileSprite(0, 0, 1300, 650, 'background'); + //game.add.tileSprite(0, 0, 300, 200, 'stat'); + //game.add.tileSprite(400, 0, 500, 200, 'stat'); + game.world.setBounds(0, 0, 900, 600); + cursors = game.input.keyboard.createCursorKeys(); + + button1 = game.add.sprite(250, 500, 'tile', 1); + button1 = game.add.text(250, 500, 'STR', txt_style); + button2 = game.add.sprite(400, 500, 'tile', 1); + button2 = game.add.text(400, 500, 'Resist', txt_style); + button3 = game.add.sprite(550, 500, 'tile', 1); + button3 = game.add.text(550, 500, 'Speed', txt_style); + button4 = game.add.sprite(700, 500, 'tile', 1); + button4 = game.add.text(700, 500, 'Luck', txt_style); + button5 = game.add.sprite(850, 300, 'tile', 1); + button5 = game.add.text(850, 300, 'Boss'); + + //exit_button = game.add.sprite(0, 500, 'tile', 1); + //exit_button = game.add.text(0, 500, 'Exit'); + + //exit_button.inputEnabled = true; + //exit_button.events.onInputDown.add( function() { quitGame(); }, this ); + + button5.inputEnabled = true; + button5.events.onInputDown.add( function() { bossFight(); }, this ); + + + player = game.add.sprite(100, 500, 'man', 0); + player.anchor.setTo(0.5, 0.5); + player.scale.setTo(1, 1); + + player.animations.add('run', [0,9]); + player.animations.play('run', 8, true); + + esc_key = game.input.keyboard.addKey(Phaser.Keyboard.ESC); + esc_key.onDown.addOnce(pauseGame, this); + + space_key = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); + + /* + stat_text = game.add.text(0, 0, 'Strength: \nResistance: \nSpeed: \nLuck: \nStat Points: '); + stat_text2 = game.add.text(250, 0, shared.stat_strength + '\n' + shared.stat_resist + '\n' + shared.stat_speed + '\n' + shared.stat_luck + '\n' + shared.stat_remain); + */ + + stat_change = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); + + stat_msg = game.add.text(0, 0, 'Use the arrow keys to move.\nUse the space key to attempt a trial for a stat boost.\nOnce all the stat points are used, click on the boss button for a boss fight.\nClick the ESC key to check your stats.'); + stat_msg2 = game.add.text(0, 250 , 'Pick a stat of your choice to upgrade.'); + + // Add some text using a CSS style. + // Center it in X, and position its top 15 pixels from the top of the world. + //var style = { font: "25px Verdana", fill: "#9999ff", align: "center" }; + //var text = game.add.text( game.world.centerX, 15, "Build something amazing.", style ); + //text.anchor.setTo( 0.5, 0.0 ); + + // When you click on the sprite, you go back to the MainMenu. + //bouncy.inputEnabled = true; + //bouncy.events.onInputDown.add( function() { quitGame(); }, this ); + }, + + update: function () { + + // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! + + if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) + { + if (player.x > 40) + { + player.x -= 6; + } + } + else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) + { + if (player.x < 960) + { + player.x += 6; + } + } + + stat_change.onDown.add(changeStats, this); + + // Accelerate the 'logo' sprite towards the cursor, + // accelerating at 500 pixels/second and moving no faster than 500 pixels/second + // in X or Y. + // This function returns the rotation angle that makes it visually match its + // new trajectory. + + } + }; +}; diff --git a/Iteration Sequence 1.2/js/MainMenu.js b/Iteration Sequence 1.2/js/MainMenu.js new file mode 100644 index 000000000..456d25cf2 --- /dev/null +++ b/Iteration Sequence 1.2/js/MainMenu.js @@ -0,0 +1,44 @@ +"use strict"; + +GameStates.makeMainMenu = function( game, shared ) { + + var music = null; + var playButton = null; + + function startGame(pointer) { + + + // Ok, the Play Button has been clicked or touched, so let's stop the music (otherwise it'll carry on playing) + //music.stop(); + console.log('Starting game'); + // And start the actual game + game.state.start('Game'); + + } + + return { + + create: function () { + + // We've already preloaded our assets, so let's kick right into the Main Menu itself. + // Here all we're doing is playing some music and adding a picture and button + // Naturally I expect you to do something significantly better :) + + //music = game.add.audio('titleMusic'); + //music.play(); + + game.add.sprite(0, 0, 'titlePage'); + + playButton = game.add.button( 500, 300, 'playButton', startGame, null, 'out', 'over', 'down'); + playButton.anchor.setTo(0.5); + + }, + + update: function () { + + // Do some nice funky main menu effect here + + } + + }; +}; diff --git a/Iteration Sequence 1.2/js/Preloader.js b/Iteration Sequence 1.2/js/Preloader.js new file mode 100644 index 000000000..9bb7d9d5e --- /dev/null +++ b/Iteration Sequence 1.2/js/Preloader.js @@ -0,0 +1,79 @@ +"use strict"; + +GameStates.makePreloader = function( game ) +{ + + var background = null; + var preloadBar = null; + + var ready = false; + + return { + + preload: function () { + + // These are the assets we loaded in Boot.js + // A nice sparkly background and a loading progress bar + background = game.add.sprite(0, 0, 'preloaderBackground'); + preloadBar = game.add.sprite(500, 300, 'preloaderBar'); + preloadBar.anchor.setTo(0.5); + + // This sets the preloadBar sprite as a loader sprite. + // What that does is automatically crop the sprite from 0 to full-width + // as the files below are loaded in. + game.load.setPreloadSprite(preloadBar); + + // Here we load the rest of the assets our game needs. + // As this is just a Project Template I've not provided these assets, swap them for your own. + game.load.image('titlePage', 'assets/title.jpg'); + game.load.atlas('playButton', 'assets/Play.png', 'assets/play_button.json'); + // + lots of other required assets here + + // My Assets + game.load.image('background','assets/temp_bg.jpg'); + game.load.image('boss_bg', 'assets/boss_bg.png'); + game.load.image('stat','assets/stat.png'); + game.load.spritesheet('fire','assets/Fire.png', 76, 74); + + game.load.spritesheet('boundaries', 'assets/boundaries.png', 1000, 100); + game.load.spritesheet('tile','assets/sheet.png', 70, 70); + game.load.spritesheet('man','assets/adventurer_tilesheet.png', 80, 110); + game.load.spritesheet('zombie','assets/zombie_tilesheet.png', 80, 110); + }, + + create: function () + { + + // Once the load has finished we disable the crop because we're going to sit in the update loop for a short while as the music decodes + preloadBar.cropEnabled = false; + + }, + + update: function () + { + + // You don't actually need to do this, but I find it gives a much smoother game experience. + // Basically it will wait for our audio file to be decoded before proceeding to the MainMenu. + // You can jump right into the menu if you want and still play the music, but you'll have a few + // seconds of delay while the mp3 decodes - so if you need your music to be in-sync with your menu + // it's best to wait for it to decode here first, then carry on. + + // If you don't have any music in your game then put the game.state.start line into the create function and delete + // the update function completely. + + + if (ready == false) + { + ready = true; + game.state.start('MainMenu'); + } + /* + if (ready == false) + { + ready = true; + game.state.start('MainMenu'); + }*/ + } + + }; +}; diff --git a/Iteration Sequence 1.2/js/game_boss.js b/Iteration Sequence 1.2/js/game_boss.js new file mode 100644 index 000000000..be45a9ec9 --- /dev/null +++ b/Iteration Sequence 1.2/js/game_boss.js @@ -0,0 +1,259 @@ +"use strict"; + +GameStates.makeBoss = function( game, shared ) { + // Create your own variables. + var boss_bg; + + var player; + var zombie; + var fire; + var boundaries; + + var stat_text; + var stat_text2; + var stat_text3; + var tip_text; + + var player_hp = 50; + var enemy_hp = 100; + var tookDamage = false; + var inputEnabled = false; + + /* + var timer; + var fire_group; + function Fire(game) { + + var x = 600; + var y = game.rnd.between(400, 600); + + Phaser.Sprite.call(this, game, x, y, 'fire', 1); + + game.physics.arcade.enable(this); + }*/ + + function returnMenu() { + + shared.stat_strength = 0; + shared.stat_resist = 0; + shared.stat_speed = 0; + shared.stat_luck = 0; + shared.stat_remain = 7; + + player_hp = 50; + enemy_hp = 100; + tookDamage = false; + inputEnabled = false; + + game.state.start('MainMenu'); + } + + function stopGravity(obj1, obj2) + { + obj1.body.gravity.y = 0; + //console.log(obj1.y); + } + + function dealDamage(obj1, obj2) + { + var bonusDamage; + switch (shared.stat_strength) + { + case 1: + bonusDamage = 1; + break; + case 2: + bonusDamage = 2; + break; + case 3: + bonusDamage = 4; + break; + default: + bonusDamage = 0; + break; + } + + enemy_hp = enemy_hp - 5 - bonusDamage; + + stat_text3.setText(enemy_hp); + zombieAttack(); + } + + function zombieAttack() + { + player.x = 100; + } + + function takeDamage(obj1, obj2) + { + var bonusResist; + + //console.log('TD: ' + tookDamage); + if (tookDamage == false) + { + //console.log('SSR: ' + shared.stat_resist); + switch (shared.stat_resist) + { + case 1: + bonusResist = 1; + break; + case 2: + bonusResist = 2; + break; + case 3: + bonusResist = 4; + break; + default: + bonusResist = 0; + break; + } + + //console.log('Player hp = ' + player_hp); + player_hp = player_hp - (8 - bonusResist); + //console.log('Collision: hp = ' + player_hp); + stat_text2.setText(player_hp); + tookDamage = true; + fire.body.checkCollision.none = true; + } + + } + + /* + function spawnFire() + { + fire_group.add(new Fire(game)); + } + */ + + return { + + create: function () { + + boss_bg = game.add.tileSprite(0, 0, 1000, 600, 'boss_bg'); + //game.add.tileSprite(0, 0, 300, 250, 'stat'); + //game.add.tileSprite(400, 0, 300, 250, 'stat'); + //stat_text = game.add.text(0, 0, 'Hit Points:\nStrength: \nResistance: \nSpeed: \nLuck: '); + //stat_text2 = game.add.text(250, 0, player_hp + '\n' + shared.stat_strength + '\n' + shared.stat_resist + '\n' + shared.stat_speed + '\n' + shared.stat_luck); + stat_text = game.add.text(0, 0, 'Hit Points: '); + stat_text2 = game.add.text(250, 0, player_hp); + tip_text = game.add.text(0, 150, 'Use the arrow keys to move and jump.\nCollide with the zombie to deal damage.\nPlayers will lose hp if they collide with the fire.'); + + game.add.text(600, 0, 'Hit Points: '); + stat_text3 = game.add.text(750, 0, enemy_hp); + + zombie = game.add.sprite(700, 450, 'zombie', 0); + zombie.anchor.setTo(0.5, 0.5); + zombie.scale.setTo(1, 1); + + player = game.add.sprite(100, 450, 'man', 0); + player.anchor.setTo(0.5, 0.5); + player.scale.setTo(1, 1); + + zombie.animations.add('run', [6,7,8,12,13,14]) + zombie.animations.play('run', 8, true); + + player.animations.add('run', [0,9]); + player.animations.play('run', 8, true); + + boundaries = game.add.sprite(0, 510, 'boundaries', 0); + + fire = game.add.sprite(600, 450, 'fire', 0); + + game.physics.startSystem(Phaser.Physics.ARCADE); + + // Set the world (global) gravity + game.physics.arcade.gravity.y = 1500; + + // Enable physics on those sprites + game.physics.enable( [ player, zombie, boundaries, fire ], Phaser.Physics.ARCADE); + + player.body.collideWorldBounds = true; + player.body.bounce.y = 0; + + zombie.body.allowGravity = false; + zombie.body.immovable = true; + zombie.body.collideWorldBounds = true; + //zombie.body.bounce.y = 0; + zombie.body.setSize(60, 85, 10, 25); + + + boundaries.body.allowGravity = false; + boundaries.body.collideWolrdBounds = true; + boundaries.visible = false; + boundaries.body.immovable = true; + + /* + timer = game.time.create(); + timer.loop(2000, spawnFire(), this); + fire_group = game.add.group(); + timer.start(); + */ + + fire.body.gravity.y = 0; + fire.body.allowGravity = false; + fire.body.velocity.x = -200; + fire.body.checkCollision.up = false; + fire.body.checkCollision.down = false; + + }, + + update: function () { + + player.body.velocity.x = 0; + fire.body.velocity.x = -200; + + game.physics.arcade.collide(player, boundaries, stopGravity, null, this); + game.physics.arcade.collide(zombie, boundaries, stopGravity, null, this); + game.physics.arcade.collide(player, fire, takeDamage, null, this); + game.physics.arcade.collide(player, zombie, dealDamage, null, this); + + + if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) + { + player.body.velocity.x = -(150 * (1 + shared.stat_speed)); + } + else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) + { + player.body.velocity.x = 150 * (1 + shared.stat_speed); + } + + if (game.input.keyboard.isDown(Phaser.Keyboard.UP) && player.y >= 455) + { + //player.body.gravity.y; + player.body.velocity.y = -500 - 50 * shared.stat_speed; + } + + if (fire.x < -200) + { + fire.x = 600; + tookDamage = false; + fire.body.checkCollision.none = false; + } + + if (player_hp <= 0 && inputEnabled == false) + { + tip_text.setText('You lose. Click ESC to return to main menu.'); + inputEnabled = true; + + } + else if (enemy_hp <= 0 && inputEnabled == false) + { + tip_text.setText('You win. Click ESC to return to main menu.'); + inputEnabled = true; + + } + + if (inputEnabled == true && game.input.keyboard.isDown(Phaser.Keyboard.ESC)) + { + returnMenu(); + } + + if (inputEnabled == true) + { + player.body.moves = false; + fire.body.moves = false; + } + + } + }; +}; diff --git a/Iteration Sequence 1.2/js/main.js b/Iteration Sequence 1.2/js/main.js new file mode 100644 index 000000000..19d1a8a1f --- /dev/null +++ b/Iteration Sequence 1.2/js/main.js @@ -0,0 +1,36 @@ +"use strict"; + +window.onload = function() +{ + + // Create your Phaser game and inject it into the 'game' div. + // We did it in a window.onload event, but you can do it anywhere (requireJS load, anonymous function, jQuery dom ready, - whatever floats your boat) + var game = new Phaser.Game( 1000, 600, Phaser.AUTO, 'game' ); + + // Add the States your game has. + // You don't have to do this in the html, it could be done in your Boot state too, but for simplicity I'll keep it here. + + // An object for shared variables, so that them main menu can show + // the high score if you want. + var shared = { + stat_type: -1, + stat_strength: 0, + stat_resist: 0, + stat_speed: 0, + stat_luck: 0, + stat_remain: 7 + } + + + game.state.add( 'Boot', GameStates.makeBoot( game ) ); + game.state.add( 'Preloader', GameStates.makePreloader( game ) ); + game.state.add( 'MainMenu', GameStates.makeMainMenu( game, shared ) ); + game.state.add( 'Game', GameStates.makeGame( game, shared ) ); + game.state.add( 'Boss', GameStates.makeBoss( game, shared ) ); + game.state.add( 'Pause', GameStates.makePause( game, shared ) ); + + + // Now start the Boot state. + game.state.start('Boot'); + +}; diff --git a/Iteration Sequence 1.2/js/pause.js b/Iteration Sequence 1.2/js/pause.js new file mode 100644 index 000000000..a5dfd1841 --- /dev/null +++ b/Iteration Sequence 1.2/js/pause.js @@ -0,0 +1,42 @@ +"use strict"; + +GameStates.makePause = function( game, shared ) { + // Create your own variables. + var stat_text; + var stat_text2; + var instruction; + var txt_style = {fill: "#ffffff"}; + var tip_text; + + var esc_key; + + function returnGame() { + // Here you should destroy anything you no longer need. + // Stop music, delete sprites, purge caches, free resources, all that good stuff. + + // Then let's go back to the main menu. + game.state.start('Game'); + + } + + + + return { + + create: function () { + + stat_text = game.add.text(0, 0, 'Strength: \nResistance: \nSpeed: \nLuck: \nStat Points: ', txt_style); + stat_text2 = game.add.text(250, 0, shared.stat_strength + '\n' + shared.stat_resist + '\n' + shared.stat_speed + '\n' + shared.stat_luck + '\n' + shared.stat_remain, txt_style); + instruction = game.add.text(300, 0, 'Click ESC to return to Game.', txt_style); + tip_text = game.add.text(0, 300, 'TIPS\nStrength increases your damage dealt in boss fights.\nResistance decreases the damage you take in boss fights.\nSpeed allows you to move faster and jump higher.\nLuck increases the success rate of the trials.' , txt_style); + + + esc_key = game.input.keyboard.addKey(Phaser.Keyboard.ESC); + esc_key.onDown.addOnce(returnGame, this); + }, + + update: function () { + + } + }; +}; diff --git a/Iteration Sequence 1.2/js/phaser.js b/Iteration Sequence 1.2/js/phaser.js new file mode 100644 index 000000000..3bac171a7 --- /dev/null +++ b/Iteration Sequence 1.2/js/phaser.js @@ -0,0 +1,107825 @@ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +* +* @overview +* +* Phaser - http://phaser.io +* +* v2.10.0 "2018-01-18" - Built: Thu Jan 18 2018 16:35:03 +* +* By Richard Davey http://www.photonstorm.com @photonstorm +* +* Phaser is a fun, free and fast 2D game framework for making HTML5 games +* for desktop and mobile web browsers, supporting Canvas and WebGL rendering. +* +* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23 +* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe +* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com +* +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate. +* +* Follow development at http://phaser.io and on our forum +* +* "If you want your children to be intelligent, read them fairy tales." +* "If you want them to be more intelligent, read them more fairy tales." +* -- Albert Einstein +*/ + +/** + * The MIT License (MIT) + * + * Copyright (c) 2015 p2.js authors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=0 && s<=1 && t>=0 && t<=1); +}; + + +},{"./Scalar":4}],2:[function(_dereq_,module,exports){ +module.exports = Point; + +/** + * Point related functions + * @class Point + */ +function Point(){}; + +/** + * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. + * @static + * @method area + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +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 = []; + +/** + * Check if three points are collinear + * @method collinear + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. + * @return {Boolean} + */ +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 angle < thresholdAngle; + } +}; + +Point.sqdist = function(a,b){ + var dx = b[0] - a[0]; + var dy = b[1] - a[1]; + return dx * dx + dy * dy; +}; + +},{}],3:[function(_dereq_,module,exports){ +var Line = _dereq_("./Line") +, Point = _dereq_("./Point") +, Scalar = _dereq_("./Scalar") + +module.exports = Polygon; + +/** + * Polygon class. + * @class Polygon + * @constructor + */ +function Polygon(){ + + /** + * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] + * @property vertices + * @type {Array} + */ + this.vertices = []; +} + +/** + * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. + * @method at + * @param {Number} i + * @return {Array} + */ +Polygon.prototype.at = function(i){ + var v = this.vertices, + s = v.length; + return v[i < 0 ? i % s + s : i % s]; +}; + +/** + * Get first vertex + * @method first + * @return {Array} + */ +Polygon.prototype.first = function(){ + return this.vertices[0]; +}; + +/** + * Get last vertex + * @method last + * @return {Array} + */ +Polygon.prototype.last = function(){ + return this.vertices[this.vertices.length-1]; +}; + +/** + * Clear the polygon data + * @method clear + * @return {Array} + */ +Polygon.prototype.clear = function(){ + this.vertices.length = 0; +}; + +/** + * Append points "from" to "to"-1 from an other polygon "poly" onto this one. + * @method append + * @param {Polygon} poly The polygon to get points from. + * @param {Number} from The vertex index in "poly". + * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. + * @return {Array} + */ +Polygon.prototype.append = function(poly,from,to){ + if(typeof(from) == "undefined") throw new Error("From is not given!"); + if(typeof(to) == "undefined") throw new Error("To is not given!"); + + if(to-1 < from) throw new Error("lol1"); + if(to > poly.vertices.length) throw new Error("lol2"); + if(from < 0) throw new Error("lol3"); + + for(var i=from; i v[br][0])) { + br = i; + } + } + + // reverse poly if clockwise + if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { + this.reverse(); + } +}; + +/** + * Reverse the vertices in the polygon + * @method 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; +}; + +/** + * Check if a point in the polygon is a reflex point + * @method isReflex + * @param {Number} i + * @return {Boolean} + */ +Polygon.prototype.isReflex = function(i){ + return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); +}; + +var tmpLine1=[], + tmpLine2=[]; + +/** + * Check if two vertices in the polygon can see each other + * @method canSee + * @param {Number} a Vertex index 1 + * @param {Number} b Vertex index 2 + * @return {Boolean} + */ +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) { // for each edge + if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges + 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))) { // if diag intersects an edge + 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) < dist) { // if edge is blocking visibility to b + return false; + } + } + } + + return true; +}; + +/** + * Copy the polygon from vertex i to vertex j. + * @method copy + * @param {Number} i + * @param {Number} j + * @param {Polygon} [targetPoly] Optional target polygon to save in. + * @return {Polygon} The resulting copy. + */ +Polygon.prototype.copy = function(i,j,targetPoly){ + var p = targetPoly || new Polygon(); + p.clear(); + if (i < j) { + // Insert all vertices from i to j + for(var k=i; k<=j; k++) + p.vertices.push(this.vertices[k]); + + } else { + + // Insert vertices 0 to j + for(var k=0; k<=j; k++) + p.vertices.push(this.vertices[k]); + + // Insert vertices i to end + for(var k=i; k 0) + return this.slice(edges); + else + return [this]; +}; + +/** + * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. + * @method slice + * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() + * @return {Array} + */ +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; i maxlevel){ + console.warn("quickDecomp: max level ("+maxlevel+") reached."); + return result; + } + + for (var i = 0; i < this.vertices.length; ++i) { + if (poly.isReflex(i)) { + reflexVertices.push(poly.vertices[i]); + upperDist = lowerDist = Number.MAX_VALUE; + + + for (var j = 0; j < this.vertices.length; ++j) { + if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge + p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection + if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly + d = Point.sqdist(poly.vertices[i], p); + if (d < lowerDist) { // keep only the closest intersection + lowerDist = d; + lowerInt = p; + lowerIndex = j; + } + } + } + if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); + if (Point.left(poly.at(i - 1), poly.at(i), p)) { + d = Point.sqdist(poly.vertices[i], p); + if (d < upperDist) { + upperDist = d; + upperInt = p; + upperIndex = j; + } + } + } + } + + // if there are no vertices to connect to, choose a point in the middle + if (lowerIndex == (upperIndex + 1) % this.vertices.length) { + //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); + p[0] = (lowerInt[0] + upperInt[0]) / 2; + p[1] = (lowerInt[1] + upperInt[1]) / 2; + steinerPoints.push(p); + + if (i < upperIndex) { + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); + lowerPoly.append(poly, i, upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + if (lowerIndex != 0){ + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); + upperPoly.append(poly,lowerIndex,poly.vertices.length); + } + //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); + lowerPoly.append(poly,i,poly.vertices.length); + } + //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); + lowerPoly.append(poly,0,upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); + upperPoly.append(poly,lowerIndex,i+1); + } + } else { + // connect to the closest point within the triangle + //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); + + if (lowerIndex > upperIndex) { + upperIndex += this.vertices.length; + } + closestDist = Number.MAX_VALUE; + + if(upperIndex < lowerIndex){ + return result; + } + + for (var j = lowerIndex; j <= upperIndex; ++j) { + if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + d = Point.sqdist(poly.at(i), poly.at(j)); + if (d < closestDist) { + closestDist = d; + closestIndex = j % this.vertices.length; + } + } + } + + if (i < closestIndex) { + lowerPoly.append(poly,i,closestIndex+1); + if (closestIndex != 0){ + upperPoly.append(poly,closestIndex,v.length); + } + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + lowerPoly.append(poly,i,v.length); + } + lowerPoly.append(poly,0,closestIndex+1); + upperPoly.append(poly,closestIndex,i+1); + } + } + + // solve smallest poly first + if (lowerPoly.vertices.length < upperPoly.vertices.length) { + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } else { + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } + + return result; + } + } + result.push(this); + + return result; +}; + +/** + * Remove collinear points in the polygon. + * @method removeCollinearPoints + * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. + * @return {Number} The number of points removed + */ +Polygon.prototype.removeCollinearPoints = function(precision){ + var num = 0; + for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ + if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ + // Remove the middle point + this.vertices.splice(i%this.vertices.length,1); + i--; // Jump one point forward. Otherwise we may get a chain removal + num++; + } + } + return num; +}; + +},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){ +module.exports = Scalar; + +/** + * Scalar functions + * @class Scalar + */ +function Scalar(){} + +/** + * Check if two scalars are equal + * @static + * @method eq + * @param {Number} a + * @param {Number} b + * @param {Number} [precision] + * @return {Boolean} + */ +Scalar.eq = function(a,b,precision){ + precision = precision || 0; + return Math.abs(a-b) < precision; +}; + +},{}],5:[function(_dereq_,module,exports){ +module.exports = { + Polygon : _dereq_("./Polygon"), + Point : _dereq_("./Point"), +}; + +},{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){ +module.exports={ + "name": "p2", + "version": "0.7.1", + "description": "A JavaScript 2D physics engine.", + "author": "Stefan Hedman (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.5", + "grunt-contrib-jshint": "^0.11.2", + "grunt-contrib-nodeunit": "^0.4.1", + "grunt-contrib-uglify": "~0.4.0", + "grunt-contrib-watch": "~0.5.0", + "grunt-browserify": "~2.0.1", + "grunt-contrib-concat": "^0.4.0" + }, + "dependencies": { + "poly-decomp": "0.1.1" + } +} + +},{}],7:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = AABB; + +/** + * Axis aligned bounding box class. + * @class AABB + * @constructor + * @param {Object} [options] + * @param {Array} [options.upperBound] + * @param {Array} [options.lowerBound] + */ +function AABB(options){ + + /** + * The lower bound of the bounding box. + * @property lowerBound + * @type {Array} + */ + this.lowerBound = vec2.create(); + if(options && options.lowerBound){ + vec2.copy(this.lowerBound, options.lowerBound); + } + + /** + * The upper bound of the bounding box. + * @property upperBound + * @type {Array} + */ + this.upperBound = vec2.create(); + if(options && options.upperBound){ + vec2.copy(this.upperBound, options.upperBound); + } +} + +var tmp = vec2.create(); + +/** + * Set the AABB bounds from a set of points, transformed by the given position and angle. + * @method setFromPoints + * @param {Array} points An array of vec2's. + * @param {Array} position + * @param {number} angle + * @param {number} skinSize Some margin to be added to the AABB. + */ +AABB.prototype.setFromPoints = function(points, position, angle, skinSize){ + var l = this.lowerBound, + u = this.upperBound; + + if(typeof(angle) !== "number"){ + angle = 0; + } + + // Set to the first point + if(angle !== 0){ + vec2.rotate(l, points[0], angle); + } else { + vec2.copy(l, points[0]); + } + vec2.copy(u, l); + + // Compute cosines and sines just once + var cosAngle = Math.cos(angle), + sinAngle = Math.sin(angle); + for(var i = 1; i u[j]){ + u[j] = p[j]; + } + if(p[j] < l[j]){ + l[j] = p[j]; + } + } + } + + // Add offset + if(position){ + vec2.add(this.lowerBound, this.lowerBound, position); + vec2.add(this.upperBound, this.upperBound, position); + } + + if(skinSize){ + this.lowerBound[0] -= skinSize; + this.lowerBound[1] -= skinSize; + this.upperBound[0] += skinSize; + this.upperBound[1] += skinSize; + } +}; + +/** + * Copy bounds from an AABB to this AABB + * @method copy + * @param {AABB} aabb + */ +AABB.prototype.copy = function(aabb){ + vec2.copy(this.lowerBound, aabb.lowerBound); + vec2.copy(this.upperBound, aabb.upperBound); +}; + +/** + * Extend this AABB so that it covers the given AABB too. + * @method extend + * @param {AABB} aabb + */ +AABB.prototype.extend = function(aabb){ + // Loop over x and y + var i = 2; + while(i--){ + // Extend lower bound + var l = aabb.lowerBound[i]; + if(this.lowerBound[i] > l){ + this.lowerBound[i] = l; + } + + // Upper + var u = aabb.upperBound[i]; + if(this.upperBound[i] < u){ + this.upperBound[i] = u; + } + } +}; + +/** + * Returns true if the given AABB overlaps this AABB. + * @method overlaps + * @param {AABB} aabb + * @return {Boolean} + */ +AABB.prototype.overlaps = function(aabb){ + var l1 = this.lowerBound, + u1 = this.upperBound, + l2 = aabb.lowerBound, + u2 = aabb.upperBound; + + // l2 u2 + // |---------| + // |--------| + // l1 u1 + + 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])); +}; + +/** + * @method containsPoint + * @param {Array} point + * @return {boolean} + */ +AABB.prototype.containsPoint = function(point){ + var l = this.lowerBound, + u = this.upperBound; + return l[0] <= point[0] && point[0] <= u[0] && l[1] <= point[1] && point[1] <= u[1]; +}; + +/** + * Check if the AABB is hit by a ray. + * @method overlapsRay + * @param {Ray} ray + * @return {number} -1 if no hit, a number between 0 and 1 if hit. + */ +AABB.prototype.overlapsRay = function(ray){ + var t = 0; + + // ray.direction is unit direction vector of ray + var dirFracX = 1 / ray.direction[0]; + var dirFracY = 1 / ray.direction[1]; + + // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner + var t1 = (this.lowerBound[0] - ray.from[0]) * dirFracX; + var t2 = (this.upperBound[0] - ray.from[0]) * dirFracX; + var t3 = (this.lowerBound[1] - ray.from[1]) * dirFracY; + var t4 = (this.upperBound[1] - ray.from[1]) * dirFracY; + + var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4))); + var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4))); + + // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us + if (tmax < 0){ + //t = tmax; + return -1; + } + + // if tmin > tmax, ray doesn't intersect AABB + if (tmin > tmax){ + //t = tmax; + return -1; + } + + return tmin; +}; +},{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Body = _dereq_('../objects/Body'); + +module.exports = Broadphase; + +/** + * Base class for broadphase implementations. + * @class Broadphase + * @constructor + */ +function Broadphase(type){ + + this.type = type; + + /** + * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). + * @property result + * @type {Array} + */ + this.result = []; + + /** + * The world to search for collision pairs in. To change it, use .setWorld() + * @property world + * @type {World} + * @readOnly + */ + this.world = null; + + /** + * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE. + * @property {Number} boundingVolumeType + */ + this.boundingVolumeType = Broadphase.AABB; +} + +/** + * Axis aligned bounding box type. + * @static + * @property {Number} AABB + */ +Broadphase.AABB = 1; + +/** + * Bounding circle type. + * @static + * @property {Number} BOUNDING_CIRCLE + */ +Broadphase.BOUNDING_CIRCLE = 2; + +/** + * Set the world that we are searching for collision pairs in. + * @method setWorld + * @param {World} world + */ +Broadphase.prototype.setWorld = function(world){ + this.world = world; +}; + +/** + * Get all potential intersecting body pairs. + * @method getCollisionPairs + * @param {World} world The world to search in. + * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). + */ +Broadphase.prototype.getCollisionPairs = function(world){}; + +var dist = vec2.create(); + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.aabbCheck = function(bodyA, bodyB){ + return bodyA.getAABB().overlaps(bodyB.getAABB()); +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether two bodies are allowed to collide at all. + * @method canCollide + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.canCollide = function(bodyA, bodyB){ + var KINEMATIC = Body.KINEMATIC; + var STATIC = Body.STATIC; + + // Cannot collide static bodies + if(bodyA.type === STATIC && bodyB.type === STATIC){ + return false; + } + + // Cannot collide static vs kinematic bodies + if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) || + (bodyA.type === STATIC && bodyB.type === KINEMATIC)){ + return false; + } + + // Cannot collide kinematic vs kinematic + if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){ + return false; + } + + // Cannot collide both sleeping bodies + if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ + return false; + } + + // Cannot collide if one is static and the other is sleeping + if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === STATIC) || + (bodyB.sleepState === Body.SLEEPING && bodyA.type === STATIC)){ + return false; + } + + return true; +}; + +Broadphase.NAIVE = 1; +Broadphase.SAP = 2; + +},{"../math/vec2":30,"../objects/Body":31}],9:[function(_dereq_,module,exports){ +var Circle = _dereq_('../shapes/Circle'), + Plane = _dereq_('../shapes/Plane'), + Shape = _dereq_('../shapes/Shape'), + Particle = _dereq_('../shapes/Particle'), + Broadphase = _dereq_('../collision/Broadphase'), + vec2 = _dereq_('../math/vec2'); + +module.exports = NaiveBroadphase; + +/** + * Naive broadphase implementation. Does N^2 tests. + * + * @class NaiveBroadphase + * @constructor + * @extends Broadphase + */ +function NaiveBroadphase(){ + Broadphase.call(this, Broadphase.NAIVE); +} +NaiveBroadphase.prototype = new Broadphase(); +NaiveBroadphase.prototype.constructor = NaiveBroadphase; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +NaiveBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = world.bodies, + result = this.result; + + result.length = 0; + + for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ + var bi = bodies[i]; + + for(var j=0; j pos0 && pos < pos1){ + // We got contact! + + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape); + + vec2.scale(c.normalA, orthoDist, -1); + vec2.normalize(c.normalA, c.normalA); + + vec2.scale( c.contactPointA, c.normalA, circleRadius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + sub(c.contactPointB, projectedPoint, lineOffset); + add(c.contactPointB, c.contactPointB, lineOffset); + sub(c.contactPointB, c.contactPointB, lineBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; + } + } + + // Add corner + verts[0] = worldVertex0; + verts[1] = worldVertex1; + + for(var i=0; i 0){ + for(var i=0; i Math.pow(r,2)){ + return 0; + } + + if(justTest){ + return true; + } + + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + 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; +}; + +/** + * Plane/Convex Narrowphase + * @method planeConvex + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} convexBody + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = +Narrowphase.prototype[Shape.PLANE | Shape.BOX] = +Narrowphase.prototype.planeConvex = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + convexBody, + convexShape, + convexOffset, + convexAngle, + justTest +){ + var worldVertex = tmp1, + worldNormal = tmp2, + dist = tmp3; + + var numReported = 0; + vec2.rotate(worldNormal, yAxis, planeAngle); + + for(var i=0; i!==convexShape.vertices.length; i++){ + var v = convexShape.vertices[i]; + vec2.rotate(worldVertex, v, convexAngle); + add(worldVertex, worldVertex, convexOffset); + + sub(dist, worldVertex, planeOffset); + + if(dot(dist,worldNormal) <= 0){ + + if(justTest){ + return true; + } + + // Found vertex + numReported++; + + var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); + + sub(dist, worldVertex, planeOffset); + + vec2.copy(c.normalA, worldNormal); + + var d = dot(dist, c.normalA); + vec2.scale(dist, c.normalA, d); + + // rj is from convex center to contact + sub(c.contactPointB, worldVertex, convexBody.position); + + + // ri is from plane center to contact + sub( c.contactPointA, worldVertex, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + this.contactEquations.push(c); + + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numReported){ + this.frictionEquations.push(this.createFrictionFromAverage(numReported)); + } + } + + return numReported; +}; + +/** + * Narrowphase for particle vs plane + * @method particlePlane + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = +Narrowphase.prototype.particlePlane = function( + particleBody, + particleShape, + particleOffset, + particleAngle, + planeBody, + planeShape, + planeOffset, + planeAngle, + justTest +){ + var dist = tmp1, + worldNormal = tmp2; + + planeAngle = planeAngle || 0; + + sub(dist, particleOffset, planeOffset); + vec2.rotate(worldNormal, yAxis, planeAngle); + + var d = dot(dist, worldNormal); + + if(d > 0){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape); + + vec2.copy(c.normalA, worldNormal); + vec2.scale( dist, c.normalA, d ); + // dist is now the distance vector in the normal direction + + // ri is the particle position projected down onto the plane, from the plane center + sub( c.contactPointA, particleOffset, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + // rj is from the body center to the particle center + sub( c.contactPointB, particleOffset, particleBody.position ); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + return 1; +}; + +/** + * Circle/Particle Narrowphase + * @method circleParticle + * @param {Body} circleBody + * @param {Circle} circleShape + * @param {Array} circleOffset + * @param {Number} circleAngle + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = +Narrowphase.prototype.circleParticle = function( + circleBody, + circleShape, + circleOffset, + circleAngle, + particleBody, + particleShape, + particleOffset, + particleAngle, + justTest +){ + var dist = tmp1; + + sub(dist, particleOffset, circleOffset); + if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape); + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + // Vector from circle to contact point is the normal times the circle radius + vec2.scale(c.contactPointA, c.normalA, circleShape.radius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + // Vector from particle center to contact point is zero + sub(c.contactPointB, particleOffset, particleBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; +}; + +var planeCapsule_tmpCircle = new Circle({ radius: 1 }), + planeCapsule_tmp1 = vec2.create(), + planeCapsule_tmp2 = vec2.create(), + planeCapsule_tmp3 = vec2.create(); + +/** + * @method planeCapsule + * @param {Body} planeBody + * @param {Circle} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} capsuleBody + * @param {Particle} capsuleShape + * @param {Array} capsuleOffset + * @param {Number} capsuleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = +Narrowphase.prototype.planeCapsule = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + capsuleBody, + capsuleShape, + capsuleOffset, + capsuleAngle, + justTest +){ + var end1 = planeCapsule_tmp1, + end2 = planeCapsule_tmp2, + circle = planeCapsule_tmpCircle, + dst = planeCapsule_tmp3; + + // Compute world end positions + vec2.set(end1, -capsuleShape.length/2, 0); + vec2.rotate(end1,end1,capsuleAngle); + add(end1,end1,capsuleOffset); + + vec2.set(end2, capsuleShape.length/2, 0); + vec2.rotate(end2,end2,capsuleAngle); + add(end2,end2,capsuleOffset); + + circle.radius = capsuleShape.radius; + + var enableFrictionBefore; + + // Temporarily turn off friction + if(this.enableFrictionReduction){ + enableFrictionBefore = this.enableFriction; + this.enableFriction = false; + } + + // Do Narrowphase as two circles + var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest), + numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest); + + // Restore friction + if(this.enableFrictionReduction){ + this.enableFriction = enableFrictionBefore; + } + + if(justTest){ + return numContacts1 || numContacts2; + } else { + var numTotal = numContacts1 + numContacts2; + if(this.enableFrictionReduction){ + if(numTotal){ + this.frictionEquations.push(this.createFrictionFromAverage(numTotal)); + } + } + return numTotal; + } +}; + +/** + * Creates ContactEquations and FrictionEquations for a collision. + * @method circlePlane + * @param {Body} bi The first body that should be connected to the equations. + * @param {Circle} si The circle shape participating in the collision. + * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. + * @param {Body} bj The second body that should be connected to the equations. + * @param {Plane} sj The Plane shape that is participating + * @param {Array} xj Extra offset for the plane shape. + * @param {Number} aj Extra angle to apply to the plane + */ +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, // Offset from body center, rotated! + planeBody = bj, + shapeB = sj, + planeOffset = xj, + planeAngle = aj; + + planeAngle = planeAngle || 0; + + // Vector from plane to circle + var planeToCircle = tmp1, + worldNormal = tmp2, + temp = tmp3; + + sub(planeToCircle, circleOffset, planeOffset); + + // World plane normal + vec2.rotate(worldNormal, yAxis, planeAngle); + + // Normal direction distance + var d = dot(worldNormal, planeToCircle); + + if(d > circleShape.radius){ + return 0; // No overlap. Abort. + } + + if(justTest){ + return true; + } + + // Create contact + var contact = this.createContactEquation(planeBody,circleBody,sj,si); + + // ni is the plane world normal + vec2.copy(contact.normalA, worldNormal); + + // rj is the vector from circle center to the contact point + vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); + add(contact.contactPointB, contact.contactPointB, circleOffset); + sub(contact.contactPointB, contact.contactPointB, circleBody.position); + + // ri is the distance from plane center to contact. + vec2.scale(temp, contact.normalA, d); + sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector + 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; +}; + +/** + * Convex/convex Narrowphase.See this article for more info. + * @method convexConvex + * @param {Body} bi + * @param {Convex} si + * @param {Array} xi + * @param {Number} ai + * @param {Body} bj + * @param {Convex} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CONVEX] = +Narrowphase.prototype[Shape.CONVEX | Shape.BOX] = +Narrowphase.prototype[Shape.BOX] = +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 = typeof(precision) === 'number' ? precision : 0; + + var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); + if(!found){ + return 0; + } + + // Make sure the separating axis is directed from shape i to shape j + sub(dist,xj,xi); + if(dot(sepAxis,dist) > 0){ + vec2.scale(sepAxis,sepAxis,-1); + } + + // Find edges with normals closest to the separating axis + var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis + closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); + + if(closestEdge1 === -1 || closestEdge2 === -1){ + return 0; + } + + // Loop over the shapes + 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){ + // Swap! + 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; + } + + // Loop over 2 points in convex B + for(var j=closestEdgeB; j= 3){ + + if(justTest){ + return true; + } + + // worldPoint was on the "inside" side of each of the 3 checked edges. + // Project it to the center edge and use the projection direction as normal + + // Create contact + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + numContacts++; + + // Get center edge from body A + var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], + v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; + + // Construct the edge + 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); // Normal points out of convex A + vec2.normalize(c.normalA,c.normalA); + + sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point + var d = dot(c.normalA,dist); // Penetration + vec2.scale(penetrationVec, c.normalA, d); // Vector penetration + + 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); + + // Todo reduce to 1 friction equation if we have 2 contact points + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numContacts){ + this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); + } + } + + return numContacts; +}; + +// .projectConvex is called by other functions, need local tmp vectors +var pcoa_tmp1 = vec2.fromValues(0,0); + +/** + * Project a Convex onto a world-oriented axis + * @method projectConvexOntoAxis + * @static + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Array} worldAxis + * @param {Array} result + */ +Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = pcoa_tmp1; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, worldAxis, -convexAngle); + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + // Project the position of the body onto the axis - need to add this to the result + var offset = dot(convexOffset, worldAxis); + + vec2.set( result, min + offset, max + offset); +}; + +// .findSeparatingAxis is called by other functions, need local tmp vectors +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); + +/** + * Find a separating axis between the shapes, that maximizes the separating distance between them. + * @method findSeparatingAxis + * @static + * @param {Convex} c1 + * @param {Array} offset1 + * @param {Number} angle1 + * @param {Convex} c2 + * @param {Array} offset2 + * @param {Number} angle2 + * @param {Array} sepAxis The resulting axis + * @return {Boolean} Whether the axis could be found. + */ +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; + + if(c1 instanceof Box && c2 instanceof Box){ + + for(var j=0; j!==2; j++){ + var c = c1, + angle = angle1; + if(j===1){ + c = c2; + angle = angle2; + } + + for(var i=0; i!==2; i++){ + + // Get the world edge + if(i === 0){ + vec2.set(normal, 0, 1); + } else if(i === 1) { + vec2.set(normal, 1, 0); + } + if(angle !== 0){ + vec2.rotate(normal, normal, angle); + } + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + + } else { + + 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++){ + // Get the world edge + vec2.rotate(worldPoint0, c.vertices[i], angle); + vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); + + sub(edge, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, edge); + vec2.normalize(normal,normal); + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + } + + + /* + // Needs to be tested some more + 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.axes.length; i++){ + + var normal = c.axes[i]; + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1); + Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + 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; +}; + +// .getClosestEdge is called by other functions, need local tmp vectors +var gce_tmp1 = vec2.fromValues(0,0) +, gce_tmp2 = vec2.fromValues(0,0) +, gce_tmp3 = vec2.fromValues(0,0); + +/** + * Get the edge that has a normal closest to an axis. + * @method getClosestEdge + * @static + * @param {Convex} c + * @param {Number} angle + * @param {Array} axis + * @param {Boolean} flip + * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. + */ +Narrowphase.getClosestEdge = function(c,angle,axis,flip){ + var localAxis = gce_tmp1, + edge = gce_tmp2, + normal = gce_tmp3; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, axis, -angle); + if(flip){ + vec2.scale(localAxis,localAxis,-1); + } + + var closestEdge = -1, + N = c.vertices.length, + maxDot = -1; + for(var i=0; i!==N; i++){ + // Get the edge + sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + 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(); + +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = +Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, + hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ + var data = hfShape.heights, + 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; + + // Get the index of the points to test against + var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), + idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); + + /*if(idxB < 0 || idxA >= data.length) + return justTest ? false : 0;*/ + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(circlePos[1]-radius > max){ + return justTest ? false : 0; + } + + /* + if(circlePos[1]+radius < min){ + // Below the minimum point... We can just guess. + // TODO + } + */ + + // 1. Check so center of circle is not inside the field. If it is, this wont work... + // 2. For each edge + // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) + // 2. 2. Check if point is inside. + + var found = false; + + // Check all edges first + for(var i=idxA; i= v0[0] && candidate[0] < v1[0] && d <= 0){ + + if(justTest){ + return true; + } + + found = true; + + // Store the candidate point, projected to the edge + vec2.scale(dist,worldNormal,-d); + vec2.add(minCandidate,candidate,dist); + vec2.copy(minCandidateNormal,worldNormal); + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Normal is out of the heightfield + vec2.copy(c.normalA, minCandidateNormal); + + // Vector from circle to heightfield + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + vec2.copy(c.contactPointA, minCandidate); + vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push( this.createFrictionFromContact(c) ); + } + } + } + + // Check all vertices + found = false; + if(radius > 0){ + for(var i=idxA; i<=idxB; i++){ + + // Get point + vec2.set(v0, i*w, data[i]); + vec2.add(v0,v0,hfPos); + + vec2.sub(dist, circlePos, v0); + + if(vec2.squaredLength(dist) < Math.pow(radius, 2)){ + + if(justTest){ + return true; + } + + found = true; + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Construct normal - out of heightfield + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + sub(c.contactPointA, v0, hfPos); + add(c.contactPointA, c.contactPointA, hfPos); + sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(found){ + return 1; + } + + return 0; + +}; + +var convexHeightfield_v0 = vec2.create(), + convexHeightfield_v1 = vec2.create(), + convexHeightfield_tilePos = vec2.create(), + convexHeightfield_tempConvexShape = new Convex({ vertices: [vec2.create(),vec2.create(),vec2.create(),vec2.create()] }); +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.BOX | Shape.HEIGHTFIELD] = +Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = +Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, + hfBody,hfShape,hfPos,hfAngle, justTest ){ + var data = hfShape.heights, + w = hfShape.elementWidth, + v0 = convexHeightfield_v0, + v1 = convexHeightfield_v1, + tilePos = convexHeightfield_tilePos, + tileConvex = convexHeightfield_tempConvexShape; + + // Get the index of the points to test against + var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), + idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(convexBody.aabb.lowerBound[1] > max){ + return justTest ? false : 0; + } + + var found = false; + var numContacts = 0; + + // Loop over all edges + // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape) + for(var i=idxA; i= 0 || aabb.containsPoint(this.from)){ + this.intersectBody(result, body); + } + } +}; + +var intersectBody_worldPosition = vec2.create(); + +/** + * Shoot a ray at a body, get back information about the hit. + * @method intersectBody + * @private + * @param {Body} body + */ +Ray.prototype.intersectBody = function (result, body) { + var checkCollisionResponse = this.checkCollisionResponse; + + if(checkCollisionResponse && !body.collisionResponse){ + return; + } + + var worldPosition = intersectBody_worldPosition; + + for (var i = 0, N = body.shapes.length; i < N; i++) { + var shape = body.shapes[i]; + + if(checkCollisionResponse && !shape.collisionResponse){ + continue; // Skip + } + + if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){ + continue; + } + + // Get world angle and position of the shape + vec2.rotate(worldPosition, shape.position, body.angle); + vec2.add(worldPosition, worldPosition, body.position); + var worldAngle = shape.angle + body.angle; + + this.intersectShape( + result, + shape, + worldAngle, + worldPosition, + body + ); + + if(result.shouldStop(this)){ + break; + } + } +}; + +/** + * @method intersectShape + * @private + * @param {Shape} shape + * @param {number} angle + * @param {array} position + * @param {Body} body + */ +Ray.prototype.intersectShape = function(result, shape, angle, position, body){ + var from = this.from; + + // Checking radius + var distance = distanceFromIntersectionSquared(from, this.direction, position); + if (distance > shape.boundingRadius * shape.boundingRadius) { + return; + } + + this._currentBody = body; + this._currentShape = shape; + + shape.raycast(result, this, position, angle); + + this._currentBody = this._currentShape = null; +}; + +/** + * Get the AABB of the ray. + * @method getAABB + * @param {AABB} aabb + */ +Ray.prototype.getAABB = function(result){ + var to = this.to; + var from = this.from; + vec2.set( + result.lowerBound, + Math.min(to[0], from[0]), + Math.min(to[1], from[1]) + ); + vec2.set( + result.upperBound, + Math.max(to[0], from[0]), + Math.max(to[1], from[1]) + ); +}; + +var hitPointWorld = vec2.create(); + +/** + * @method reportIntersection + * @private + * @param {number} fraction + * @param {array} normal + * @param {number} [faceIndex=-1] + * @return {boolean} True if the intersections should continue + */ +Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){ + var from = this.from; + var to = this.to; + var shape = this._currentShape; + var body = this._currentBody; + + // Skip back faces? + if(this.skipBackfaces && vec2.dot(normal, this.direction) > 0){ + return; + } + + switch(this.mode){ + + case Ray.ALL: + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + this.callback(result); + break; + + case Ray.CLOSEST: + + // Store if closer than current closest + if(fraction < result.fraction || !result.hasHit()){ + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + } + break; + + case Ray.ANY: + + // Report and stop. + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + break; + } +}; + +var v0 = vec2.create(), + intersect = vec2.create(); +function distanceFromIntersectionSquared(from, direction, position) { + + // v0 is vector from from to position + vec2.sub(v0, position, from); + var dot = vec2.dot(v0, direction); + + // intersect = direction * dot + from + vec2.scale(intersect, direction, dot); + vec2.add(intersect, intersect, from); + + return vec2.squaredDistance(position, intersect); +} + + +},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Ray = _dereq_('../collision/Ray'); + +module.exports = RaycastResult; + +/** + * Storage for Ray casting hit data. + * @class RaycastResult + * @constructor + */ +function RaycastResult(){ + + /** + * The normal of the hit, oriented in world space. + * @property {array} normal + */ + this.normal = vec2.create(); + + /** + * The hit shape, or null. + * @property {Shape} shape + */ + this.shape = null; + + /** + * The hit body, or null. + * @property {Body} body + */ + this.body = null; + + /** + * The index of the hit triangle, if the hit shape was indexable. + * @property {number} faceIndex + * @default -1 + */ + this.faceIndex = -1; + + /** + * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet. + * @property {number} fraction + * @default -1 + */ + this.fraction = -1; + + /** + * If the ray should stop traversing. + * @readonly + * @property {Boolean} isStopped + */ + this.isStopped = false; +} + +/** + * Reset all result data. Must be done before re-using the result object. + * @method reset + */ +RaycastResult.prototype.reset = function () { + vec2.set(this.normal, 0, 0); + this.shape = null; + this.body = null; + this.faceIndex = -1; + this.fraction = -1; + this.isStopped = false; +}; + +/** + * Get the distance to the hit point. + * @method getHitDistance + * @param {Ray} ray + */ +RaycastResult.prototype.getHitDistance = function (ray) { + return vec2.distance(ray.from, ray.to) * this.fraction; +}; + +/** + * Returns true if the ray hit something since the last reset(). + * @method hasHit + */ +RaycastResult.prototype.hasHit = function () { + return this.fraction !== -1; +}; + +/** + * Get world hit point. + * @method getHitPoint + * @param {array} out + * @param {Ray} ray + */ +RaycastResult.prototype.getHitPoint = function (out, ray) { + vec2.lerp(out, ray.from, ray.to, this.fraction); +}; + +/** + * Can be called while iterating over hits to stop searching for hit points. + * @method stop + */ +RaycastResult.prototype.stop = function(){ + this.isStopped = true; +}; + +/** + * @method shouldStop + * @private + * @param {Ray} ray + * @return {boolean} + */ +RaycastResult.prototype.shouldStop = function(ray){ + return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY); +}; + +/** + * @method set + * @private + * @param {array} normal + * @param {Shape} shape + * @param {Body} body + * @param {number} fraction + */ +RaycastResult.prototype.set = function( + normal, + shape, + body, + fraction, + faceIndex +){ + vec2.copy(this.normal, normal); + this.shape = shape; + this.body = body; + this.fraction = fraction; + this.faceIndex = faceIndex; +}; +},{"../collision/Ray":11,"../math/vec2":30}],13:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, Broadphase = _dereq_('../collision/Broadphase'); + +module.exports = SAPBroadphase; + +/** + * Sweep and prune broadphase along one axis. + * + * @class SAPBroadphase + * @constructor + * @extends Broadphase + */ +function SAPBroadphase(){ + Broadphase.call(this,Broadphase.SAP); + + /** + * List of bodies currently in the broadphase. + * @property axisList + * @type {Array} + */ + this.axisList = []; + + /** + * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance. + * @property axisIndex + * @type {Number} + */ + this.axisIndex = 0; + + var that = this; + this._addBodyHandler = function(e){ + that.axisList.push(e.body); + }; + + this._removeBodyHandler = function(e){ + // Remove from list + var idx = that.axisList.indexOf(e.body); + if(idx !== -1){ + that.axisList.splice(idx,1); + } + }; +} +SAPBroadphase.prototype = new Broadphase(); +SAPBroadphase.prototype.constructor = SAPBroadphase; + +/** + * Change the world + * @method setWorld + * @param {World} world + */ +SAPBroadphase.prototype.setWorld = function(world){ + // Clear the old axis array + this.axisList.length = 0; + + // Add all bodies from the new world + Utils.appendArray(this.axisList, world.bodies); + + // Remove old handlers, if any + world + .off("addBody",this._addBodyHandler) + .off("removeBody",this._removeBodyHandler); + + // Add handlers to update the list of bodies. + world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); + + this.world = world; +}; + +/** + * Sorts bodies along an axis. + * @method sortAxisList + * @param {Array} a + * @param {number} axisIndex + * @return {Array} + */ +SAPBroadphase.sortAxisList = function(a, axisIndex){ + axisIndex = axisIndex|0; + for(var i=1,l=a.length; 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.sortList = function(){ + var bodies = this.axisList, + axisIndex = this.axisIndex; + + // Sort the lists + SAPBroadphase.sortAxisList(bodies, axisIndex); +}; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +SAPBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = this.axisList, + result = this.result, + axisIndex = this.axisIndex; + + result.length = 0; + + // Update all AABBs if needed + var l = bodies.length; + while(l--){ + var b = bodies[l]; + if(b.aabbNeedsUpdate){ + b.updateAABB(); + } + } + + // Sort the lists + this.sortList(); + + // Look through the X list + for(var i=0, N=bodies.length|0; i!==N; i++){ + var bi = bodies[i]; + + for(var j=i+1; j G = [-n -rixn n rjxn] + + var r = vec2.create(); + var ri = vec2.create(); // worldAnchorA + var rj = vec2.create(); // worldAnchorB + var that = this; + normal.computeGq = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + xi = bodyA.position, + xj = bodyB.position; + + // Transform local anchors to world + vec2.rotate(ri, localAnchorA, bodyA.angle); + vec2.rotate(rj, localAnchorB, bodyB.angle); + + vec2.add(r, xj, rj); + vec2.sub(r, r, ri); + vec2.sub(r, r, xi); + + //vec2.sub(r, bodyB.position, bodyA.position); + return vec2.length(r) - that.distance; + }; + + // Make the contact constraint bilateral + this.setMaxForce(maxForce); + + /** + * If the upper limit is enabled or not. + * @property {Boolean} upperLimitEnabled + */ + this.upperLimitEnabled = false; + + /** + * The upper constraint limit. + * @property {number} upperLimit + */ + this.upperLimit = 1; + + /** + * If the lower limit is enabled or not. + * @property {Boolean} lowerLimitEnabled + */ + this.lowerLimitEnabled = false; + + /** + * The lower constraint limit. + * @property {number} lowerLimit + */ + this.lowerLimit = 0; + + /** + * Current constraint position. This is equal to the current distance between the world anchor points. + * @property {number} position + */ + this.position = 0; +} +DistanceConstraint.prototype = new Constraint(); +DistanceConstraint.prototype.constructor = DistanceConstraint; + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +var n = vec2.create(); +var ri = vec2.create(); // worldAnchorA +var rj = vec2.create(); // worldAnchorB +DistanceConstraint.prototype.update = function(){ + var normal = this.equations[0], + bodyA = this.bodyA, + bodyB = this.bodyB, + distance = this.distance, + xi = bodyA.position, + xj = bodyB.position, + normalEquation = this.equations[0], + G = normal.G; + + // Transform local anchors to world + vec2.rotate(ri, this.localAnchorA, bodyA.angle); + vec2.rotate(rj, this.localAnchorB, bodyB.angle); + + // Get world anchor points and normal + vec2.add(n, xj, rj); + vec2.sub(n, n, ri); + vec2.sub(n, n, xi); + this.position = vec2.length(n); + + var violating = false; + if(this.upperLimitEnabled){ + if(this.position > this.upperLimit){ + normalEquation.maxForce = 0; + normalEquation.minForce = -this.maxForce; + this.distance = this.upperLimit; + violating = true; + } + } + + if(this.lowerLimitEnabled){ + if(this.position < this.lowerLimit){ + normalEquation.maxForce = this.maxForce; + normalEquation.minForce = 0; + this.distance = this.lowerLimit; + violating = true; + } + } + + if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){ + // No constraint needed. + normalEquation.enabled = false; + return; + } + + normalEquation.enabled = true; + + vec2.normalize(n,n); + + // Caluclate cross products + var rixn = vec2.crossLength(ri, n), + rjxn = vec2.crossLength(rj, n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; +}; + +/** + * Set the max force to be used + * @method setMaxForce + * @param {Number} maxForce + */ +DistanceConstraint.prototype.setMaxForce = function(maxForce){ + var normal = this.equations[0]; + normal.minForce = -maxForce; + normal.maxForce = maxForce; +}; + +/** + * Get the max force + * @method getMaxForce + * @return {Number} + */ +DistanceConstraint.prototype.getMaxForce = function(){ + var normal = this.equations[0]; + return normal.maxForce; +}; + +},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, AngleLockEquation = _dereq_('../equations/AngleLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = GearConstraint; + +/** + * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB. + * @class GearConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for). + * @param {Number} [options.ratio=1] Gear ratio. + * @param {Number} [options.maxTorque] Maximum torque to apply. + * @extends Constraint + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB, { + * ratio: 2, + * maxTorque: 1000 + * }); + * world.addConstraint(constraint); + */ +function GearConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); + + /** + * The gear ratio. + * @property ratio + * @type {Number} + */ + this.ratio = options.ratio !== undefined ? options.ratio : 1; + + /** + * The relative angle + * @property angle + * @type {Number} + */ + this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle; + + // Send same parameters to the equation + options.angle = this.angle; + options.ratio = this.ratio; + + this.equations = [ + new AngleLockEquation(bodyA,bodyB,options), + ]; + + // Set max torque + if(options.maxTorque !== undefined){ + this.setMaxTorque(options.maxTorque); + } +} +GearConstraint.prototype = new Constraint(); +GearConstraint.prototype.constructor = GearConstraint; + +GearConstraint.prototype.update = function(){ + var eq = this.equations[0]; + if(eq.ratio !== this.ratio){ + eq.setRatio(this.ratio); + } + eq.angle = this.angle; +}; + +/** + * Set the max torque for the constraint. + * @method setMaxTorque + * @param {Number} torque + */ +GearConstraint.prototype.setMaxTorque = function(torque){ + this.equations[0].setMaxTorque(torque); +}; + +/** + * Get the max torque for the constraint. + * @method getMaxTorque + * @return {Number} + */ +GearConstraint.prototype.getMaxTorque = function(torque){ + return this.equations[0].maxForce; +}; +},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('../equations/Equation'); + +module.exports = LockConstraint; + +/** + * Locks the relative position and rotation between two bodies. + * + * @class LockConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions. + * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles. + * @param {number} [options.maxForce] + * @extends Constraint + * + * @example + * // Locks the relative position and rotation between bodyA and bodyB + * var constraint = new LockConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + */ +function LockConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); + + var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); + + var localAngleB = options.localAngleB || 0; + + // Use 3 equations: + // gx = (xj - xi - l) * xhat = 0 + // gy = (xj - xi - l) * yhat = 0 + // gr = (xi - xj + r) * that = 0 + // + // ...where: + // l is the localOffsetB vector rotated to world in bodyA frame + // r is the same vector but reversed and rotated from bodyB frame + // xhat, yhat are world axis vectors + // that is the tangent of r + // + // For the first two constraints, we get + // G*W = (vj - vi - ldot ) * xhat + // = (vj - vi - wi x l) * xhat + // + // Since (wi x l) * xhat = (l x xhat) * wi, we get + // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] + // + // The last constraint gives + // GW = (vi - vj + wj x r) * that + // = [ that 0 -that (r x t) ] + + var x = new Equation(bodyA,bodyB,-maxForce,maxForce), + y = new Equation(bodyA,bodyB,-maxForce,maxForce), + rot = new Equation(bodyA,bodyB,-maxForce,maxForce); + + var l = vec2.create(), + g = vec2.create(), + that = this; + x.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[0]; + }; + y.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[1]; + }; + var r = vec2.create(), + t = vec2.create(); + rot.computeGq = function(){ + vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); + vec2.scale(r,r,-1); + vec2.sub(g,bodyA.position,bodyB.position); + vec2.add(g,g,r); + vec2.rotate(t,r,-Math.PI/2); + vec2.normalize(t,t); + return vec2.dot(g,t); + }; + + /** + * The offset of bodyB in bodyA's frame. + * @property {Array} localOffsetB + */ + this.localOffsetB = vec2.create(); + if(options.localOffsetB){ + vec2.copy(this.localOffsetB, options.localOffsetB); + } else { + // Construct from current positions + vec2.sub(this.localOffsetB, bodyB.position, bodyA.position); + vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle); + } + + /** + * The offset angle of bodyB in bodyA's frame. + * @property {Number} localAngleB + */ + this.localAngleB = 0; + if(typeof(options.localAngleB) === 'number'){ + this.localAngleB = options.localAngleB; + } else { + // Construct + this.localAngleB = bodyB.angle - bodyA.angle; + } + + this.equations.push(x, y, rot); + this.setMaxForce(maxForce); +} +LockConstraint.prototype = new Constraint(); +LockConstraint.prototype.constructor = LockConstraint; + +/** + * Set the maximum force to be applied. + * @method setMaxForce + * @param {Number} force + */ +LockConstraint.prototype.setMaxForce = function(force){ + var eqs = this.equations; + for(var i=0; ithis tutorial. Also called "slider constraint". + * + * @class PrismaticConstraint + * @constructor + * @extends Constraint + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.maxForce] Max force to be applied by the constraint + * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. + * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. + * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. + * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. + * @param {Number} [options.upperLimit] + * @param {Number} [options.lowerLimit] + * @todo Ability to create using only a point and a worldAxis + */ +function PrismaticConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); + + // Get anchors + var localAnchorA = vec2.fromValues(0,0), + localAxisA = vec2.fromValues(1,0), + localAnchorB = vec2.fromValues(0,0); + if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); } + if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); } + if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); } + + /** + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = localAnchorA; + + /** + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = localAnchorB; + + /** + * @property localAxisA + * @type {Array} + */ + this.localAxisA = localAxisA; + + /* + + The constraint violation for the common axis point is + + g = ( xj + rj - xi - ri ) * t := gg*t + + where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. + + gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) + + Note the use of the chain rule. Now we identify the jacobian + + G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] + + The rotational part is just a rotation lock. + + */ + + var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE; + + // Translational part + var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); + var ri = new vec2.create(), + rj = new vec2.create(), + gg = new vec2.create(), + t = new vec2.create(); + trans.computeGq = function(){ + // g = ( xj + rj - xi - ri ) * t + return vec2.dot(gg,t); + }; + trans.updateJacobian = function(){ + var G = this.G, + xi = bodyA.position, + xj = bodyB.position; + vec2.rotate(ri,localAnchorA,bodyA.angle); + vec2.rotate(rj,localAnchorB,bodyB.angle); + vec2.add(gg,xj,rj); + vec2.sub(gg,gg,xi); + vec2.sub(gg,gg,ri); + vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); + + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + }; + this.equations.push(trans); + + // Rotational part + if(!options.disableRotationalLock){ + var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); + this.equations.push(rot); + } + + /** + * The position of anchor A relative to anchor B, along the constraint axis. + * @property position + * @type {Number} + */ + this.position = 0; + + // Is this one used at all? + this.velocity = 0; + + /** + * Set to true to enable lower limit. + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; + + /** + * Set to true to enable upper limit. + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; + + /** + * Lower constraint limit. The constraint position is forced to be larger than this value. + * @property lowerLimit + * @type {Number} + */ + this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; + + /** + * Upper constraint limit. The constraint position is forced to be smaller than this value. + * @property upperLimit + * @type {Number} + */ + this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; + + // Equations used for limits + this.upperLimitEquation = new ContactEquation(bodyA,bodyB); + this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); + + // Set max/min forces + this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; + this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; + + /** + * Equation used for the motor. + * @property motorEquation + * @type {Equation} + */ + this.motorEquation = new Equation(bodyA,bodyB); + + /** + * The current motor state. Enable or disable the motor using .enableMotor + * @property motorEnabled + * @type {Boolean} + */ + this.motorEnabled = false; + + /** + * Set the target speed for the motor. + * @property motorSpeed + * @type {Number} + */ + this.motorSpeed = 0; + + var that = this; + var motorEquation = this.motorEquation; + var old = motorEquation.computeGW; + motorEquation.computeGq = function(){ return 0; }; + motorEquation.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed; + }; +} + +PrismaticConstraint.prototype = new Constraint(); +PrismaticConstraint.prototype.constructor = PrismaticConstraint; + +var worldAxisA = vec2.create(), + worldAnchorA = vec2.create(), + worldAnchorB = vec2.create(), + orientedAnchorA = vec2.create(), + orientedAnchorB = vec2.create(), + tmp = vec2.create(); + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +PrismaticConstraint.prototype.update = function(){ + var eqs = this.equations, + trans = eqs[0], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation, + bodyA = this.bodyA, + bodyB = this.bodyB, + localAxisA = this.localAxisA, + localAnchorA = this.localAnchorA, + localAnchorB = this.localAnchorB; + + trans.updateJacobian(); + + // Transform local things to world + vec2.rotate(worldAxisA, localAxisA, bodyA.angle); + vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); + vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); + vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); + vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); + + var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); + + // Motor + if(this.motorEnabled){ + // G = [ a a x ri -a -a x rj ] + var G = this.motorEquation.G; + G[0] = worldAxisA[0]; + G[1] = worldAxisA[1]; + G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); + G[3] = -worldAxisA[0]; + G[4] = -worldAxisA[1]; + G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); + } + + /* + Limits strategy: + Add contact equation, with normal along the constraint axis. + min/maxForce is set so the constraint is repulsive in the correct direction. + Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. + + ^ + | + upperLimit x + | ------ + anchorB x<---| B | + | | | + ------ | ------ + | | | + | A |-->x anchorA + ------ | + x lowerLimit + | + axis + */ + + + if(this.upperLimitEnabled && relPosition > upperLimit){ + // Update contact constraint normal, etc + 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 && relPosition < lowerLimit){ + // Update contact constraint normal, etc + vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); + vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); + vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); + vec2.scale(tmp,worldAxisA,lowerLimit); + vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } +}; + +/** + * Enable the motor + * @method enableMotor + */ +PrismaticConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +PrismaticConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the constraint limits. + * @method setLimits + * @param {number} lower Lower limit. + * @param {number} upper Upper limit. + */ +PrismaticConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + + +},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation') +, RotationalLockEquation = _dereq_('../equations/RotationalLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = RevoluteConstraint; + +var worldPivotA = vec2.create(), + worldPivotB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1), + g = vec2.create(); + +/** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * @class RevoluteConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to. + * @param {Array} [options.localPivotB] See localPivotA. + * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. + * @extends Constraint + * + * @example + * // This will create a revolute constraint between two bodies with pivot point in between them. + * var bodyA = new Body({ mass: 1, position: [-1, 0] }); + * var bodyB = new Body({ mass: 1, position: [1, 0] }); + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * worldPivot: [0, 0] + * }); + * world.addConstraint(constraint); + * + * // Using body-local pivot points, the constraint could have been constructed like this: + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * localPivotA: [1, 0], + * localPivotB: [-1, 0] + * }); + */ +function RevoluteConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); + + var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; + + /** + * @property {Array} pivotA + */ + this.pivotA = vec2.create(); + + /** + * @property {Array} pivotB + */ + this.pivotB = vec2.create(); + + if(options.worldPivot){ + // Compute pivotA and pivotB + vec2.sub(this.pivotA, options.worldPivot, bodyA.position); + vec2.sub(this.pivotB, options.worldPivot, bodyB.position); + // Rotate to local coordinate system + vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle); + vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle); + } else { + // Get pivotA and pivotB + vec2.copy(this.pivotA, options.localPivotA); + vec2.copy(this.pivotB, options.localPivotB); + } + + // Equations to be fed to the solver + var eqs = this.equations = [ + new Equation(bodyA,bodyB,-maxForce,maxForce), + new Equation(bodyA,bodyB,-maxForce,maxForce), + ]; + + var x = eqs[0]; + var y = eqs[1]; + var that = this; + + x.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,xAxis); + }; + + y.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,yAxis); + }; + + y.minForce = x.minForce = -maxForce; + y.maxForce = x.maxForce = maxForce; + + this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); + + /** + * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. + * @property {Boolean} motorEnabled + * @readOnly + */ + this.motorEnabled = false; + + /** + * The constraint position. + * @property angle + * @type {Number} + * @readOnly + */ + this.angle = 0; + + /** + * Set to true to enable lower limit + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = false; + + /** + * Set to true to enable upper limit + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = false; + + /** + * The lower limit on the constraint angle. + * @property lowerLimit + * @type {Boolean} + */ + this.lowerLimit = 0; + + /** + * The upper limit on the constraint angle. + * @property upperLimit + * @type {Boolean} + */ + this.upperLimit = 0; + + this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.upperLimitEquation.minForce = 0; + this.lowerLimitEquation.maxForce = 0; +} +RevoluteConstraint.prototype = new Constraint(); +RevoluteConstraint.prototype.constructor = RevoluteConstraint; + +/** + * Set the constraint angle limits. + * @method setLimits + * @param {number} lower Lower angle limit. + * @param {number} upper Upper angle limit. + */ +RevoluteConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + +RevoluteConstraint.prototype.update = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + pivotA = this.pivotA, + pivotB = this.pivotB, + eqs = this.equations, + normal = eqs[0], + tangent= eqs[1], + x = eqs[0], + y = eqs[1], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation; + + var relAngle = this.angle = bodyB.angle - bodyA.angle; + + if(this.upperLimitEnabled && relAngle > upperLimit){ + 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 < lowerLimit){ + lowerLimitEquation.angle = lowerLimit; + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } + + /* + + The constraint violation is + + g = xj + rj - xi - ri + + ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: + + gdot = vj + wj x rj - vi - wi x ri + + We split this into x and y directions. (let x and y be unit vectors along the respective axes) + + gdot * x = ( vj + wj x rj - vi - wi x ri ) * x + = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x + = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi + = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] + = G*W + + ...and similar for y. We have then identified the jacobian entries for x and y directions: + + Gx = [ x (rj x x) -x -(ri x x)] + Gy = [ y (rj x y) -y -(ri x y)] + + */ + + vec2.rotate(worldPivotA, pivotA, bodyA.angle); + vec2.rotate(worldPivotB, pivotB, bodyB.angle); + + // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc + + x.G[0] = -1; + x.G[1] = 0; + x.G[2] = -vec2.crossLength(worldPivotA,xAxis); + x.G[3] = 1; + x.G[4] = 0; + x.G[5] = vec2.crossLength(worldPivotB,xAxis); + + y.G[0] = 0; + y.G[1] = -1; + y.G[2] = -vec2.crossLength(worldPivotA,yAxis); + y.G[3] = 0; + y.G[4] = 1; + y.G[5] = vec2.crossLength(worldPivotB,yAxis); +}; + +/** + * Enable the rotational motor + * @method enableMotor + */ +RevoluteConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +RevoluteConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the speed of the rotational constraint motor + * @method setMotorSpeed + * @param {Number} speed + */ +RevoluteConstraint.prototype.setMotorSpeed = function(speed){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations[i].relativeVelocity = speed; +}; + +/** + * Get the speed of the rotational constraint motor + * @method getMotorSpeed + * @return {Number} The current speed, or false if the motor is not enabled. + */ +RevoluteConstraint.prototype.getMotorSpeed = function(){ + if(!this.motorEnabled){ + return false; + } + return this.motorEquation.relativeVelocity; +}; + +},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = AngleLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class AngleLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in body A. + * @param {Number} [options.ratio] Gear ratio + */ +function AngleLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); + this.angle = options.angle || 0; + + /** + * The gear ratio. + * @property {Number} ratio + * @private + * @see setRatio + */ + this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; + + this.setRatio(this.ratio); +} +AngleLockEquation.prototype = new Equation(); +AngleLockEquation.prototype.constructor = AngleLockEquation; + +AngleLockEquation.prototype.computeGq = function(){ + return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; +}; + +/** + * Set the gear ratio for this equation + * @method setRatio + * @param {Number} ratio + */ +AngleLockEquation.prototype.setRatio = function(ratio){ + var G = this.G; + G[2] = ratio; + G[5] = -1; + this.ratio = ratio; +}; + +/** + * Set the max force for the equation. + * @method setMaxTorque + * @param {Number} torque + */ +AngleLockEquation.prototype.setMaxTorque = function(torque){ + this.maxForce = torque; + this.minForce = -torque; +}; + +},{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = ContactEquation; + +/** + * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive. + * + * @class ContactEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function ContactEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); + + /** + * Vector from body i center of mass to the contact point. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + this.penetrationVec = vec2.create(); + + /** + * World-oriented vector from body A center of mass to the contact point. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * The normal vector, pointing out of body i + * @property normalA + * @type {Array} + */ + this.normalA = vec2.create(); + + /** + * The restitution to use (0=no bounciness, 1=max bounciness). + * @property restitution + * @type {Number} + */ + this.restitution = 0; + + /** + * This property is set to true if this is the first impact between the bodies (not persistant contact). + * @property firstImpact + * @type {Boolean} + * @readOnly + */ + this.firstImpact = false; + + /** + * The shape in body i that triggered this contact. + * @property shapeA + * @type {Shape} + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this contact. + * @property shapeB + * @type {Shape} + */ + this.shapeB = null; +} +ContactEquation.prototype = new Equation(); +ContactEquation.prototype.constructor = ContactEquation; +ContactEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + xi = bi.position, + xj = bj.position; + + var penetrationVec = this.penetrationVec, + n = this.normalA, + G = this.G; + + // Caluclate cross products + var rixn = vec2.crossLength(ri,n), + rjxn = vec2.crossLength(rj,n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; + + // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector + vec2.add(penetrationVec,xj,rj); + vec2.sub(penetrationVec,penetrationVec,xi); + vec2.sub(penetrationVec,penetrationVec,ri); + + // Compute iteration + var GW, Gq; + if(this.firstImpact && this.restitution !== 0){ + Gq = 0; + GW = (1/b)*(1+this.restitution) * this.computeGW(); + } else { + Gq = vec2.dot(n,penetrationVec) + this.offset; + GW = this.computeGW(); + } + + var GiMf = this.computeGiMf(); + var B = - Gq * a - GW * b - h*GiMf; + + return B; +}; + +var vi = vec2.create(); +var vj = vec2.create(); +var relVel = vec2.create(); + +/** + * Get the relative velocity along the normal vector. + * @return {number} + */ +ContactEquation.prototype.getVelocityAlongNormal = function(){ + + this.bodyA.getVelocityAtPoint(vi, this.contactPointA); + this.bodyB.getVelocityAtPoint(vj, this.contactPointB); + + vec2.subtract(relVel, vi, vj); + + return vec2.dot(this.normalA, relVel); +}; +},{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){ +module.exports = Equation; + +var vec2 = _dereq_('../math/vec2'), + Utils = _dereq_('../utils/Utils'), + Body = _dereq_('../objects/Body'); + +/** + * Base class for constraint equations. + * @class Equation + * @constructor + * @param {Body} bodyA First body participating in the equation + * @param {Body} bodyB Second body participating in the equation + * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE + * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE + */ +function Equation(bodyA, bodyB, minForce, maxForce){ + + /** + * Minimum force to apply when solving. + * @property minForce + * @type {Number} + */ + this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; + + /** + * Max force to apply when solving. + * @property maxForce + * @type {Number} + */ + this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; + + /** + * First body participating in the constraint + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second body participating in the constraint + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; + + /** + * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. + * @property stiffness + * @type {Number} + */ + this.stiffness = Equation.DEFAULT_STIFFNESS; + + /** + * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. + * @property relaxation + * @type {Number} + */ + this.relaxation = Equation.DEFAULT_RELAXATION; + + /** + * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). + * @property G + * @type {Array} + */ + this.G = new Utils.ARRAY_TYPE(6); + for(var i=0; i<6; i++){ + this.G[i]=0; + } + + this.offset = 0; + + this.a = 0; + this.b = 0; + this.epsilon = 0; + this.timeStep = 1/60; + + /** + * Indicates if stiffness or relaxation was changed. + * @property {Boolean} needsUpdate + */ + this.needsUpdate = true; + + /** + * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. + * @property multiplier + * @type {Number} + */ + this.multiplier = 0; + + /** + * Relative velocity. + * @property {Number} relativeVelocity + */ + this.relativeVelocity = 0; + + /** + * Whether this equation is enabled or not. If true, it will be added to the solver. + * @property {Boolean} enabled + */ + this.enabled = true; +} +Equation.prototype.constructor = Equation; + +/** + * The default stiffness when creating a new Equation. + * @static + * @property {Number} DEFAULT_STIFFNESS + * @default 1e6 + */ +Equation.DEFAULT_STIFFNESS = 1e6; + +/** + * The default relaxation when creating a new Equation. + * @static + * @property {Number} DEFAULT_RELAXATION + * @default 4 + */ +Equation.DEFAULT_RELAXATION = 4; + +/** + * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the SPOOK notes. + * @method update + */ +Equation.prototype.update = function(){ + var k = this.stiffness, + d = this.relaxation, + h = this.timeStep; + + this.a = 4.0 / (h * (1 + 4 * d)); + this.b = (4.0 * d) / (1 + 4 * d); + this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); + + this.needsUpdate = false; +}; + +/** + * Multiply a jacobian entry with corresponding positions or velocities + * @method gmult + * @return {Number} + */ +Equation.prototype.gmult = function(G,vi,wi,vj,wj){ + return G[0] * vi[0] + + G[1] * vi[1] + + G[2] * wi + + G[3] * vj[0] + + G[4] * vj[1] + + G[5] * wj; +}; + +/** + * Computes the RHS of the SPOOK equation + * @method computeB + * @return {Number} + */ +Equation.prototype.computeB = function(a,b,h){ + var GW = this.computeGW(); + var Gq = this.computeGq(); + var GiMf = this.computeGiMf(); + return - Gq * a - GW * b - GiMf*h; +}; + +/** + * Computes G\*q, where q are the generalized body coordinates + * @method computeGq + * @return {Number} + */ +var qi = vec2.create(), + qj = vec2.create(); +Equation.prototype.computeGq = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + xi = bi.position, + xj = bj.position, + ai = bi.angle, + aj = bj.angle; + + return this.gmult(G, qi, ai, qj, aj) + this.offset; +}; + +/** + * Computes G\*W, where W are the body velocities + * @method computeGW + * @return {Number} + */ +Equation.prototype.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity; +}; + +/** + * Computes G\*Wlambda, where W are the body velocities + * @method computeGWlambda + * @return {Number} + */ +Equation.prototype.computeGWlambda = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.vlambda, + vj = bj.vlambda, + wi = bi.wlambda, + wj = bj.wlambda; + return this.gmult(G,vi,wi,vj,wj); +}; + +/** + * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. + * @method computeGiMf + * @return {Number} + */ +var iMfi = vec2.create(), + iMfj = vec2.create(); +Equation.prototype.computeGiMf = function(){ + var bi = this.bodyA, + bj = this.bodyB, + fi = bi.force, + ti = bi.angularForce, + fj = bj.force, + tj = bj.angularForce, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + vec2.scale(iMfi, fi, invMassi); + vec2.multiply(iMfi, bi.massMultiplier, iMfi); + vec2.scale(iMfj, fj,invMassj); + vec2.multiply(iMfj, bj.massMultiplier, iMfj); + + return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); +}; + +/** + * Computes G\*inv(M)\*G' + * @method computeGiMGt + * @return {Number} + */ +Equation.prototype.computeGiMGt = function(){ + var bi = this.bodyA, + bj = this.bodyB, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + return G[0] * G[0] * invMassi * bi.massMultiplier[0] + + G[1] * G[1] * invMassi * bi.massMultiplier[1] + + G[2] * G[2] * invIi + + G[3] * G[3] * invMassj * bj.massMultiplier[0] + + G[4] * G[4] * invMassj * bj.massMultiplier[1] + + G[5] * G[5] * invIj; +}; + +var addToWlambda_temp = vec2.create(), + addToWlambda_Gi = vec2.create(), + addToWlambda_Gj = vec2.create(), + addToWlambda_ri = vec2.create(), + addToWlambda_rj = vec2.create(), + addToWlambda_Mdiag = vec2.create(); + +/** + * Add constraint velocity to the bodies. + * @method addToWlambda + * @param {Number} deltalambda + */ +Equation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bodyA, + bj = this.bodyB, + temp = addToWlambda_temp, + Gi = addToWlambda_Gi, + Gj = addToWlambda_Gj, + ri = addToWlambda_ri, + rj = addToWlambda_rj, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + Mdiag = addToWlambda_Mdiag, + G = this.G; + + Gi[0] = G[0]; + Gi[1] = G[1]; + Gj[0] = G[3]; + Gj[1] = G[4]; + + // Add to linear velocity + // v_lambda += inv(M) * delta_lamba * G + vec2.scale(temp, Gi, invMassi*deltalambda); + vec2.multiply(temp, temp, bi.massMultiplier); + vec2.add( bi.vlambda, bi.vlambda, temp); + // This impulse is in the offset frame + // Also add contribution to angular + //bi.wlambda -= vec2.crossLength(temp,ri); + bi.wlambda += invIi * G[2] * deltalambda; + + + vec2.scale(temp, Gj, invMassj*deltalambda); + vec2.multiply(temp, temp, bj.massMultiplier); + vec2.add( bj.vlambda, bj.vlambda, temp); + //bj.wlambda -= vec2.crossLength(temp,rj); + bj.wlambda += invIj * G[5] * deltalambda; +}; + +/** + * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps + * @method computeInvC + * @param {Number} eps + * @return {Number} + */ +Equation.prototype.computeInvC = function(eps){ + return 1.0 / (this.computeGiMGt() + eps); +}; + +},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('./Equation') +, Utils = _dereq_('../utils/Utils'); + +module.exports = FrictionEquation; + +/** + * Constrains the slipping in a contact along a tangent + * + * @class FrictionEquation + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Number} slipForce + * @extends Equation + */ +function FrictionEquation(bodyA, bodyB, slipForce){ + Equation.call(this, bodyA, bodyB, -slipForce, slipForce); + + /** + * Relative vector from center of body A to the contact point, world oriented. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + + /** + * Relative vector from center of body B to the contact point, world oriented. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * Tangent vector that the friction force will act along. World oriented. + * @property t + * @type {Array} + */ + this.t = vec2.create(); + + /** + * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average. + * @property contactEquations + * @type {ContactEquation} + */ + this.contactEquations = []; + + /** + * The shape in body i that triggered this friction. + * @property shapeA + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeA... + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this friction. + * @property shapeB + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeB... + */ + this.shapeB = null; + + /** + * The friction coefficient to use. + * @property frictionCoefficient + * @type {Number} + */ + this.frictionCoefficient = 0.3; +} +FrictionEquation.prototype = new Equation(); +FrictionEquation.prototype.constructor = FrictionEquation; + +/** + * Set the slipping condition for the constraint. The friction force cannot be + * larger than this value. + * @method setSlipForce + * @param {Number} slipForce + */ +FrictionEquation.prototype.setSlipForce = function(slipForce){ + this.maxForce = slipForce; + this.minForce = -slipForce; +}; + +/** + * Get the max force for the constraint. + * @method getSlipForce + * @return {Number} + */ +FrictionEquation.prototype.getSlipForce = function(){ + return this.maxForce; +}; + +FrictionEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + t = this.t, + G = this.G; + + // G = [-t -rixt t rjxt] + // And remember, this is a pure velocity constraint, g is always zero! + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + + var GW = this.computeGW(), + GiMf = this.computeGiMf(); + + var B = /* - g * a */ - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class RotationalLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in bodyA. + */ +function RotationalLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + + /** + * @property {number} angle + */ + this.angle = options.angle || 0; + + var G = this.G; + G[2] = 1; + G[5] = -1; +} +RotationalLockEquation.prototype = new Equation(); +RotationalLockEquation.prototype.constructor = RotationalLockEquation; + +var worldVectorA = vec2.create(), + worldVectorB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1); +RotationalLockEquation.prototype.computeGq = function(){ + vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); + vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); + return vec2.dot(worldVectorA,worldVectorB); +}; + +},{"../math/vec2":30,"./Equation":22}],25:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalVelocityEquation; + +/** + * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). + * + * @class RotationalVelocityEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function RotationalVelocityEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + this.relativeVelocity = 1; + this.ratio = 1; +} +RotationalVelocityEquation.prototype = new Equation(); +RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; +RotationalVelocityEquation.prototype.computeB = function(a,b,h){ + var G = this.G; + G[2] = -1; + G[5] = this.ratio; + + var GiMf = this.computeGiMf(); + var GW = this.computeGW(); + var B = - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"./Equation":22}],26:[function(_dereq_,module,exports){ +/** + * Base class for objects that dispatches events. + * @class EventEmitter + * @constructor + */ +var EventEmitter = function () {}; + +module.exports = EventEmitter; + +EventEmitter.prototype = { + constructor: EventEmitter, + + /** + * Add an event listener + * @method on + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + on: function ( type, listener, context ) { + listener.context = context || this; + if ( this._listeners === undefined ){ + this._listeners = {}; + } + var listeners = this._listeners; + if ( listeners[ type ] === undefined ) { + listeners[ type ] = []; + } + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + listeners[ type ].push( listener ); + } + return this; + }, + + /** + * Check if an event listener is added + * @method has + * @param {String} type + * @param {Function} listener + * @return {Boolean} + */ + has: function ( type, listener ) { + if ( this._listeners === undefined ){ + return false; + } + var listeners = this._listeners; + if(listener){ + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + return true; + } + } else { + if ( listeners[ type ] !== undefined ) { + return true; + } + } + + return false; + }, + + /** + * Remove an event listener + * @method off + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + off: function ( type, listener ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var index = listeners[ type ].indexOf( listener ); + if ( index !== - 1 ) { + listeners[ type ].splice( index, 1 ); + } + return this; + }, + + /** + * Emit an event. + * @method emit + * @param {Object} event + * @param {String} event.type + * @return {EventEmitter} The self object, for chainability. + */ + emit: function ( event ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; + if ( listenerArray !== undefined ) { + event.target = this; + for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { + var listener = listenerArray[ i ]; + listener.call( listener.context, event ); + } + } + return this; + } +}; + +},{}],27:[function(_dereq_,module,exports){ +var Material = _dereq_('./Material'); +var Equation = _dereq_('../equations/Equation'); + +module.exports = ContactMaterial; + +/** + * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. + * @class ContactMaterial + * @constructor + * @param {Material} materialA + * @param {Material} materialB + * @param {Object} [options] + * @param {Number} [options.friction=0.3] Friction coefficient. + * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". + * @param {Number} [options.stiffness] ContactEquation stiffness. + * @param {Number} [options.relaxation] ContactEquation relaxation. + * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. + * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. + * @param {Number} [options.surfaceVelocity=0] Surface velocity. + * @author schteppe + */ +function ContactMaterial(materialA, materialB, options){ + options = options || {}; + + if(!(materialA instanceof Material) || !(materialB instanceof Material)){ + throw new Error("First two arguments must be Material instances."); + } + + /** + * The contact material identifier + * @property id + * @type {Number} + */ + this.id = ContactMaterial.idCounter++; + + /** + * First material participating in the contact material + * @property materialA + * @type {Material} + */ + this.materialA = materialA; + + /** + * Second material participating in the contact material + * @property materialB + * @type {Material} + */ + this.materialB = materialB; + + /** + * Friction coefficient to use in the contact of these two materials. Friction = 0 will make the involved objects super slippery, and friction = 1 will make it much less slippery. A friction coefficient larger than 1 will allow for very large friction forces, which can be convenient for preventing car tires not slip on the ground. + * @property friction + * @type {Number} + * @default 0.3 + */ + this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; + + /** + * Restitution, or "bounciness" to use in the contact of these two materials. A restitution of 0 will make no bounce, while restitution=1 will approximately bounce back with the same velocity the object came with. + * @property restitution + * @type {Number} + * @default 0 + */ + this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0; + + /** + * Hardness of the contact. Less stiffness will make the objects penetrate more, and will make the contact act more like a spring than a contact force. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property stiffness + * @type {Number} + */ + this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting ContactEquation that this ContactMaterial generate. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property relaxation + * @type {Number} + */ + this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Stiffness of the resulting friction force. For most cases, the value of this property should be a large number. I cannot think of any case where you would want less frictionStiffness. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property frictionStiffness + * @type {Number} + */ + this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting friction force. The default value should be good for most simulations. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property frictionRelaxation + * @type {Number} + */ + this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + * @property {Number} surfaceVelocity + * @default 0 + */ + this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; + + /** + * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts". + * @property contactSkinSize + * @type {Number} + */ + this.contactSkinSize = 0.005; +} + +ContactMaterial.idCounter = 0; + +},{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){ +module.exports = Material; + +/** + * Defines a physics material. + * @class Material + * @constructor + * @param {number} id Material identifier + * @author schteppe + */ +function Material(id){ + /** + * The material identifier + * @property id + * @type {Number} + */ + this.id = id || Material.idCounter++; +} + +Material.idCounter = 0; + +},{}],29:[function(_dereq_,module,exports){ + + /* + PolyK library + url: http://polyk.ivank.net + Released under MIT licence. + + Copyright (c) 2012 Ivan Kuckir + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + */ + + var PolyK = {}; + + /* + Is Polygon self-intersecting? + + O(n^2) + */ + /* + PolyK.IsSimple = function(p) + { + var n = p.length>>1; + if(n<4) return true; + var a1 = new PolyK._P(), a2 = new PolyK._P(); + var b1 = new PolyK._P(), b2 = new PolyK._P(); + var c = new PolyK._P(); + + for(var i=0; i>1; + if(n<3) return []; + var tgs = []; + var avl = []; + for(var i=0; i 3) + { + 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; j 3*al) break; // no convex angles :( + } + tgs.push(avl[0], avl[1], avl[2]); + return tgs; + } + /* + PolyK.ContainsPoint = function(p, px, py) + { + var n = p.length>>1; + var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; + var depth = 0; + for(var i=0; i=0 && by>=0) continue; // both "up" or both "donw" + if(ax< 0 && bx< 0) continue; + + var lx = ax + (bx-ax)*(-ay)/(by-ay); + if(lx>0) depth++; + } + return (depth & 1) == 1; + } + + PolyK.Slice = function(p, ax, ay, bx, by) + { + if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; + + var a = new PolyK._P(ax, ay); + var b = new PolyK._P(bx, by); + var iscs = []; // intersections + var ps = []; // points + for(var i=0; i 0) + { + var n = ps.length; + var i0 = iscs[0]; + var i1 = iscs[1]; + var ind0 = ps.indexOf(i0); + var ind1 = ps.indexOf(i1); + var solved = false; + + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + else + { + i0 = iscs[1]; + i1 = iscs[0]; + ind0 = ps.indexOf(i0); + ind1 = ps.indexOf(i1); + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + } + if(solved) + { + dir--; + var pgn = PolyK._getPoints(ps, ind0, ind1); + pgs.push(pgn); + ps = PolyK._getPoints(ps, ind1, ind0); + i0.flag = i1.flag = false; + iscs.splice(0,2); + if(iscs.length == 0) pgs.push(ps); + } + else { dir++; iscs.reverse(); } + if(dir>1) break; + } + var result = []; + for(var i=0; i>1, isc); + } + b1.x = b2.x; b1.y = b2.y; + b2.x = p[0]; b2.y = p[1]; + PolyK._pointLineDist(a1, b1, b2, l>>1, isc); + + var idst = 1/isc.dist; + isc.norm.x = (x-isc.point.x)*idst; + isc.norm.y = (y-isc.point.y)*idst; + return isc; + } + + PolyK._pointLineDist = function(p, a, b, edge, isc) + { + var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; + + var A = x - x1; + var B = y - y1; + var C = x2 - x1; + var D = y2 - y1; + + var dot = A * C + B * D; + var len_sq = C * C + D * D; + var param = dot / len_sq; + + var xx, yy; + + if (param < 0 || (x1 == x2 && y1 == y2)) { + xx = x1; + yy = y1; + } + else if (param > 1) { + xx = x2; + yy = y2; + } + else { + xx = x1 + param * C; + yy = y1 + param * D; + } + + var dx = x - xx; + var dy = y - yy; + var dst = Math.sqrt(dx * dx + dy * dy); + if(dst= 0) && (v >= 0) && (u + v < 1); + } + /* + PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) + { + var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); + var day = (a1.y-a2.y), dby = (b1.y-b2.y); + + var Den = dax*dby - day*dbx; + if (Den == 0) return null; // parallel + + var A = (a1.x * a2.y - a1.y * a2.x); + var B = (b1.x * b2.y - b1.y * b2.x); + + var I = c; + var iDen = 1/Den; + I.x = ( A*dbx - dax*B ) * iDen; + I.y = ( A*dby - day*B ) * iDen; + + if(!PolyK._InRect(I, b1, b2)) return null; + if((day>0 && I.y>a1.y) || (day<0 && I.y0 && I.x>a1.x) || (dax<0 && I.x=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); + if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); + + if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) + && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) + return true; + return false; + } + */ + PolyK._convex = function(ax, ay, bx, by, cx, cy) + { + return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; + } + /* + PolyK._P = function(x,y) + { + this.x = x; + this.y = y; + this.flag = false; + } + PolyK._P.prototype.toString = function() + { + return "Point ["+this.x+", "+this.y+"]"; + } + PolyK._P.dist = function(a,b) + { + var dx = b.x-a.x; + var dy = b.y-a.y; + return Math.sqrt(dx*dx + dy*dy); + } + + PolyK._tp = []; + for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); + */ + +module.exports = PolyK; + +},{}],30:[function(_dereq_,module,exports){ +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. + * @class vec2 + */ + +var vec2 = module.exports = {}; + +var Utils = _dereq_('../utils/Utils'); + +/** + * Make a cross product and only return the z component + * @method crossLength + * @static + * @param {Array} a + * @param {Array} b + * @return {Number} + */ +vec2.crossLength = function(a,b){ + return a[0] * b[1] - a[1] * b[0]; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossVZ + * @static + * @param {Array} out + * @param {Array} vec + * @param {Number} zcomp + * @return {Number} + */ +vec2.crossVZ = function(out, vec, zcomp){ + vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossZV + * @static + * @param {Array} out + * @param {Number} zcomp + * @param {Array} vec + * @return {Number} + */ +vec2.crossZV = function(out, zcomp, vec){ + vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Rotate a vector by an angle + * @method rotate + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate = function(out,a,angle){ + if(angle !== 0){ + 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; + } else { + out[0] = a[0]; + out[1] = a[1]; + } +}; + +/** + * Rotate a vector 90 degrees clockwise + * @method rotate90cw + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate90cw = function(out, a) { + var x = a[0]; + var y = a[1]; + out[0] = y; + out[1] = -x; +}; + +/** + * Transform a point position to local frame. + * @method toLocalFrame + * @param {Array} out + * @param {Array} worldPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ + vec2.copy(out, worldPoint); + vec2.sub(out, out, framePosition); + vec2.rotate(out, out, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ + vec2.copy(out, localPoint); + vec2.rotate(out, out, frameAngle); + vec2.add(out, out, framePosition); +}; + +/** + * Transform a vector to local frame. + * @method vectorToLocalFrame + * @param {Array} out + * @param {Array} worldVector + * @param {Number} frameAngle + */ +vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ + vec2.rotate(out, worldVector, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localVector + * @param {Number} frameAngle + */ +vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){ + vec2.rotate(out, localVector, frameAngle); +}; + +/** + * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php + * @method centroid + * @static + * @param {Array} out + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Array} The out object + */ +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; +}; + +/** + * Creates a new, empty vec2 + * @static + * @method create + * @return {Array} a new 2D vector + */ +vec2.create = function() { + var out = new Utils.ARRAY_TYPE(2); + out[0] = 0; + out[1] = 0; + return out; +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * @static + * @method clone + * @param {Array} a vector to clone + * @return {Array} a new 2D vector + */ +vec2.clone = function(a) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Creates a new vec2 initialized with the given values + * @static + * @method fromValues + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} a new 2D vector + */ +vec2.fromValues = function(x, y) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Copy the values from one vec2 to another + * @static + * @method copy + * @param {Array} out the receiving vector + * @param {Array} a the source vector + * @return {Array} out + */ +vec2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * @static + * @method set + * @param {Array} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} out + */ +vec2.set = function(out, x, y) { + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Adds two vec2's + * @static + * @method add + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +}; + +/** + * Subtracts two vec2's + * @static + * @method subtract + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +}; + +/** + * Alias for vec2.subtract + * @static + * @method sub + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * @static + * @method multiply + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +}; + +/** + * Alias for vec2.multiply + * @static + * @method mul + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * @static + * @method divide + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +}; + +/** + * Alias for vec2.divide + * @static + * @method div + */ +vec2.div = vec2.divide; + +/** + * Scales a vec2 by a scalar number + * @static + * @method scale + * @param {Array} out the receiving vector + * @param {Array} a the vector to scale + * @param {Number} b amount to scale the vector by + * @return {Array} out + */ +vec2.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * @static + * @method distance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} distance between a and b + */ +vec2.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.distance + * @static + * @method dist + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * @static + * @method squaredDistance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} squared distance between a and b + */ +vec2.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredDistance + * @static + * @method sqrDist + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * @static + * @method length + * @param {Array} a vector to calculate length of + * @return {Number} length of a + */ +vec2.length = function (a) { + var x = a[0], + y = a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.length + * @method len + * @static + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * @static + * @method squaredLength + * @param {Array} a vector to calculate squared length of + * @return {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a[0], + y = a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredLength + * @static + * @method sqrLen + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * @static + * @method negate + * @param {Array} out the receiving vector + * @param {Array} a vector to negate + * @return {Array} out + */ +vec2.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +}; + +/** + * Normalize a vec2 + * @static + * @method normalize + * @param {Array} out the receiving vector + * @param {Array} a vector to normalize + * @return {Array} out + */ +vec2.normalize = function(out, a) { + var x = a[0], + y = a[1]; + var len = x*x + y*y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * @static + * @method dot + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1]; +}; + +/** + * Returns a string representation of a vector + * @static + * @method str + * @param {Array} vec vector to represent as a string + * @return {String} string representation of the vector + */ +vec2.str = function (a) { + return 'vec2(' + a[0] + ', ' + a[1] + ')'; +}; + +/** + * Linearly interpolate/mix two vectors. + * @static + * @method lerp + * @param {Array} out + * @param {Array} a First vector + * @param {Array} b Second vector + * @param {number} t Lerp factor + */ +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; +}; + +/** + * Reflect a vector along a normal. + * @static + * @method reflect + * @param {Array} out + * @param {Array} vector + * @param {Array} normal + */ +vec2.reflect = function(out, vector, normal){ + var dot = vector[0] * normal[0] + vector[1] * normal[1]; + out[0] = vector[0] - 2 * normal[0] * dot; + out[1] = vector[1] - 2 * normal[1] * dot; +}; + +/** + * Get the intersection point between two line segments. + * @static + * @method getLineSegmentsIntersection + * @param {Array} out + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {boolean} True if there was an intersection, otherwise false. + */ +vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { + var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); + if(t < 0){ + return false; + } else { + out[0] = p0[0] + (t * (p1[0] - p0[0])); + out[1] = p0[1] + (t * (p1[1] - p0[1])); + return true; + } +}; + +/** + * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) + * @static + * @method getLineSegmentsIntersectionFraction + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. + */ +vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { + var s1_x = p1[0] - p0[0]; + var s1_y = p1[1] - p0[1]; + var s2_x = p3[0] - p2[0]; + var s2_y = p3[1] - p2[1]; + + var s, t; + s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); + t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); + if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + return t; + } + return -1; // No collision +}; + +},{"../utils/Utils":57}],31:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, decomp = _dereq_('poly-decomp') +, Convex = _dereq_('../shapes/Convex') +, RaycastResult = _dereq_('../collision/RaycastResult') +, Ray = _dereq_('../collision/Ray') +, AABB = _dereq_('../collision/AABB') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Body; + +/** + * A rigid body. Has got a center of mass, position, velocity and a number of + * shapes that are used for collisions. + * + * @class Body + * @constructor + * @extends EventEmitter + * @param {Array} [options.force] + * @param {Array} [options.position] + * @param {Array} [options.velocity] + * @param {Boolean} [options.allowSleep] + * @param {Boolean} [options.collisionResponse] + * @param {Number} [options.angle=0] + * @param {Number} [options.angularForce=0] + * @param {Number} [options.angularVelocity=0] + * @param {Number} [options.ccdIterations=10] + * @param {Number} [options.ccdSpeedThreshold=-1] + * @param {Number} [options.fixedRotation=false] + * @param {Number} [options.gravityScale] + * @param {Number} [options.id] + * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. + * @param {Number} [options.sleepSpeedLimit] + * @param {Number} [options.sleepTimeLimit] + * @param {Object} [options] + * + * @example + * + * // Create a typical dynamic body + * var body = new Body({ + * mass: 1, + * position: [0, 0], + * angle: 0, + * velocity: [0, 0], + * angularVelocity: 0 + * }); + * + * // Add a circular shape to the body + * body.addShape(new Circle({ radius: 1 })); + * + * // Add the body to the world + * world.addBody(body); + */ +function Body(options){ + options = options || {}; + + EventEmitter.call(this); + + /** + * The body identifyer + * @property id + * @type {Number} + */ + this.id = options.id || ++Body._idCounter; + + /** + * The world that this body is added to. This property is set to NULL if the body is not added to any world. + * @property world + * @type {World} + */ + this.world = null; + + /** + * The shapes of the body. + * + * @property shapes + * @type {Array} + */ + this.shapes = []; + + /** + * The mass of the body. + * @property mass + * @type {number} + */ + this.mass = options.mass || 0; + + /** + * The inverse mass of the body. + * @property invMass + * @type {number} + */ + this.invMass = 0; + + /** + * The inertia of the body around the Z axis. + * @property inertia + * @type {number} + */ + this.inertia = 0; + + /** + * The inverse inertia of the body. + * @property invInertia + * @type {number} + */ + this.invInertia = 0; + + this.invMassSolve = 0; + this.invInertiaSolve = 0; + + /** + * Set to true if you want to fix the rotation of the body. + * @property fixedRotation + * @type {Boolean} + */ + this.fixedRotation = !!options.fixedRotation; + + /** + * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y. + * @property {Boolean} fixedX + */ + this.fixedX = !!options.fixedX; + + /** + * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X. + * @property {Boolean} fixedY + */ + this.fixedY = !!options.fixedY; + + /** + * @private + * @property {array} massMultiplier + */ + this.massMultiplier = vec2.create(); + + /** + * The position of the body + * @property position + * @type {Array} + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * The interpolated position of the body. Use this for rendering. + * @property interpolatedPosition + * @type {Array} + */ + this.interpolatedPosition = vec2.fromValues(0,0); + + /** + * The interpolated angle of the body. Use this for rendering. + * @property interpolatedAngle + * @type {Number} + */ + this.interpolatedAngle = 0; + + /** + * The previous position of the body. + * @property previousPosition + * @type {Array} + */ + this.previousPosition = vec2.fromValues(0,0); + + /** + * The previous angle of the body. + * @property previousAngle + * @type {Number} + */ + this.previousAngle = 0; + + /** + * The current velocity of the body. + * @property velocity + * @type {Array} + */ + this.velocity = vec2.fromValues(0,0); + if(options.velocity){ + vec2.copy(this.velocity, options.velocity); + } + + /** + * Constraint velocity that was added to the body during the last step. + * @property vlambda + * @type {Array} + */ + this.vlambda = vec2.fromValues(0,0); + + /** + * Angular constraint velocity that was added to the body during last step. + * @property wlambda + * @type {Array} + */ + this.wlambda = 0; + + /** + * The angle of the body, in radians. + * @property angle + * @type {number} + * @example + * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. + * // If you need a value between 0 and 2*pi, use the following function to normalize it. + * function normalizeAngle(angle){ + * angle = angle % (2*Math.PI); + * if(angle < 0){ + * angle += (2*Math.PI); + * } + * return angle; + * } + */ + this.angle = options.angle || 0; + + /** + * The angular velocity of the body, in radians per second. + * @property angularVelocity + * @type {number} + */ + this.angularVelocity = options.angularVelocity || 0; + + /** + * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. + * @property force + * @type {Array} + * + * @example + * // This produces a forcefield of 1 Newton in the positive x direction. + * for(var i=0; i radius){ + radius = offset + r; + } + } + + this.boundingRadius = radius; +}; + +/** + * Add a shape to the body. You can pass a local transform when adding a shape, + * so that the shape gets an offset and angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * + * @method addShape + * @param {Shape} shape + * @param {Array} [offset] Local body offset of the shape. + * @param {Number} [angle] Local body angle. + * + * @example + * var body = new Body(), + * shape = new Circle({ radius: 1 }); + * + * // Add the shape to the body, positioned in the center + * body.addShape(shape); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. + * body.addShape(shape,[1,0]); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. + * body.addShape(shape,[0,1],Math.PI/2); + */ +Body.prototype.addShape = function(shape, offset, angle){ + if(shape.body){ + throw new Error('A shape can only be added to one body.'); + } + shape.body = this; + + // Copy the offset vector + if(offset){ + vec2.copy(shape.position, offset); + } else { + vec2.set(shape.position, 0, 0); + } + + shape.angle = angle || 0; + + this.shapes.push(shape); + this.updateMassProperties(); + this.updateBoundingRadius(); + + this.aabbNeedsUpdate = true; +}; + +/** + * Remove a shape + * @method removeShape + * @param {Shape} shape + * @return {Boolean} True if the shape was found and removed, else false. + */ +Body.prototype.removeShape = function(shape){ + var idx = this.shapes.indexOf(shape); + + if(idx !== -1){ + this.shapes.splice(idx,1); + this.aabbNeedsUpdate = true; + shape.body = null; + return true; + } else { + return false; + } +}; + +/** + * Updates .inertia, .invMass, .invInertia for this Body. Should be called when + * changing the structure or mass of the Body. + * + * @method updateMassProperties + * + * @example + * body.mass += 1; + * body.updateMassProperties(); + */ +Body.prototype.updateMassProperties = function(){ + if(this.type === Body.STATIC || this.type === 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; + } + + // Inverse mass properties are easy + this.invMass = 1 / this.mass; + + vec2.set( + this.massMultiplier, + this.fixedX ? 0 : 1, + this.fixedY ? 0 : 1 + ); + } +}; + +var Body_applyForce_r = vec2.create(); + +/** + * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero. + * @method applyForce + * @param {Array} force The force to add. + * @param {Array} [relativePoint] A world point to apply the force on. + */ +Body.prototype.applyForce = function(force, relativePoint){ + + // Add linear force + vec2.add(this.force, this.force, force); + + if(relativePoint){ + + // Compute produced rotational force + var rotForce = vec2.crossLength(relativePoint,force); + + // Add rotational force + this.angularForce += rotForce; + } +}; + +/** + * Apply force to a body-local point. + * @method applyForceLocal + * @param {Array} localForce The force vector to add, oriented in local body space. + * @param {Array} [localPoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyForce_forceWorld = vec2.create(); +var Body_applyForce_pointWorld = vec2.create(); +var Body_applyForce_pointLocal = vec2.create(); +Body.prototype.applyForceLocal = function(localForce, localPoint){ + localPoint = localPoint || Body_applyForce_pointLocal; + var worldForce = Body_applyForce_forceWorld; + var worldPoint = Body_applyForce_pointWorld; + this.vectorToWorldFrame(worldForce, localForce); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyForce(worldForce, worldPoint); +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulse + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_velo = vec2.create(); +Body.prototype.applyImpulse = function(impulseVector, relativePoint){ + if(this.type !== Body.DYNAMIC){ + return; + } + + // Compute produced central impulse velocity + var velo = Body_applyImpulse_velo; + vec2.scale(velo, impulseVector, this.invMass); + vec2.multiply(velo, this.massMultiplier, velo); + + // Add linear impulse + vec2.add(this.velocity, velo, this.velocity); + + if(relativePoint){ + // Compute produced rotational impulse velocity + var rotVelo = vec2.crossLength(relativePoint, impulseVector); + rotVelo *= this.invInertia; + + // Add rotational Impulse + this.angularVelocity += rotVelo; + } +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulseLocal + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_impulseWorld = vec2.create(); +var Body_applyImpulse_pointWorld = vec2.create(); +var Body_applyImpulse_pointLocal = vec2.create(); +Body.prototype.applyImpulseLocal = function(localImpulse, localPoint){ + localPoint = localPoint || Body_applyImpulse_pointLocal; + var worldImpulse = Body_applyImpulse_impulseWorld; + var worldPoint = Body_applyImpulse_pointWorld; + this.vectorToWorldFrame(worldImpulse, localImpulse); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyImpulse(worldImpulse, worldPoint); +}; + +/** + * Transform a world point to local body frame. + * @method toLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldPoint The input world point + */ +Body.prototype.toLocalFrame = function(out, worldPoint){ + vec2.toLocalFrame(out, worldPoint, this.position, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method toWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localPoint The input local point + */ +Body.prototype.toWorldFrame = function(out, localPoint){ + vec2.toGlobalFrame(out, localPoint, this.position, this.angle); +}; + +/** + * Transform a world point to local body frame. + * @method vectorToLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldVector The input world vector + */ +Body.prototype.vectorToLocalFrame = function(out, worldVector){ + vec2.vectorToLocalFrame(out, worldVector, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method vectorToWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localVector The input local vector + */ +Body.prototype.vectorToWorldFrame = function(out, localVector){ + vec2.vectorToGlobalFrame(out, localVector, this.angle); +}; + +/** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. + * @method fromPolygon + * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. + * @param {Object} [options] + * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. + * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @return {Boolean} True on success, else false. + */ +Body.prototype.fromPolygon = function(path,options){ + options = options || {}; + + // Remove all shapes + for(var i=this.shapes.length; i>=0; --i){ + this.removeShape(this.shapes[i]); + } + + var p = new decomp.Polygon(); + p.vertices = path; + + // Make it counter-clockwise + p.makeCCW(); + + if(typeof(options.removeCollinearPoints) === "number"){ + p.removeCollinearPoints(options.removeCollinearPoints); + } + + // Check if any line segment intersects the path itself + if(typeof(options.skipSimpleCheck) === "undefined"){ + if(!p.isSimple()){ + return false; + } + } + + // Save this path for later + this.concavePath = p.vertices.slice(0); + for(var i=0; ithis for details. + * @method applyDamping + * @param {number} dt Current time step + */ +Body.prototype.applyDamping = function(dt){ + if(this.type === Body.DYNAMIC){ // Only for dynamic bodies + var v = this.velocity; + vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); + this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); + } +}; + +/** + * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. + * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. + * @method wakeUp + */ +Body.prototype.wakeUp = function(){ + var s = this.sleepState; + this.sleepState = Body.AWAKE; + this.idleTime = 0; + if(s !== Body.AWAKE){ + this.emit(Body.wakeUpEvent); + } +}; + +/** + * Force body sleep + * @method sleep + */ +Body.prototype.sleep = function(){ + this.sleepState = Body.SLEEPING; + this.angularVelocity = 0; + this.angularForce = 0; + vec2.set(this.velocity,0,0); + vec2.set(this.force,0,0); + this.emit(Body.sleepEvent); +}; + +/** + * Called every timestep to update internal sleep timer and change sleep state if needed. + * @method sleepTick + * @param {number} time The world time in seconds + * @param {boolean} dontSleep + * @param {number} dt + */ +Body.prototype.sleepTick = function(time, dontSleep, dt){ + if(!this.allowSleep || this.type === Body.SLEEPING){ + return; + } + + this.wantsToSleep = false; + + var sleepState = this.sleepState, + speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), + speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); + + // Add to idle time + if(speedSquared >= 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; + } + } +}; + +/** + * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. + * @method overlaps + * @param {Body} body + * @return {boolean} + */ +Body.prototype.overlaps = function(body){ + return this.world.overlapKeeper.bodiesAreOverlapping(this, body); +}; + +var integrate_fhMinv = vec2.create(); +var integrate_velodt = vec2.create(); + +/** + * Move the body forward in time given its current velocity. + * @method integrate + * @param {Number} dt + */ +Body.prototype.integrate = function(dt){ + var minv = this.invMass, + f = this.force, + pos = this.position, + velo = this.velocity; + + // Save old position + vec2.copy(this.previousPosition, this.position); + this.previousAngle = this.angle; + + // Velocity update + if(!this.fixedRotation){ + this.angularVelocity += this.angularForce * this.invInertia * dt; + } + vec2.scale(integrate_fhMinv, f, dt * minv); + vec2.multiply(integrate_fhMinv, this.massMultiplier, integrate_fhMinv); + vec2.add(velo, integrate_fhMinv, velo); + + // CCD + if(!this.integrateToTimeOfImpact(dt)){ + + // Regular position update + vec2.scale(integrate_velodt, velo, dt); + vec2.add(pos, pos, integrate_velodt); + if(!this.fixedRotation){ + this.angle += this.angularVelocity * dt; + } + } + + this.aabbNeedsUpdate = true; +}; + +var result = new RaycastResult(); +var ray = new Ray({ + mode: Ray.ALL +}); +var direction = vec2.create(); +var end = vec2.create(); +var startToEnd = vec2.create(); +var rememberPosition = vec2.create(); +Body.prototype.integrateToTimeOfImpact = function(dt){ + + if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){ + return false; + } + + vec2.normalize(direction, this.velocity); + + vec2.scale(end, this.velocity, dt); + vec2.add(end, end, this.position); + + vec2.sub(startToEnd, end, this.position); + var startToEndAngle = this.angularVelocity * dt; + var len = vec2.length(startToEnd); + + var timeOfImpact = 1; + + var hit; + var that = this; + result.reset(); + ray.callback = function (result) { + if(result.body === that){ + return; + } + hit = result.body; + result.getHitPoint(end, ray); + vec2.sub(startToEnd, end, that.position); + timeOfImpact = vec2.length(startToEnd) / len; + result.stop(); + }; + vec2.copy(ray.from, this.position); + vec2.copy(ray.to, end); + ray.update(); + this.world.raycast(result, ray); + + if(!hit){ + return false; + } + + var rememberAngle = this.angle; + vec2.copy(rememberPosition, this.position); + + // Got a start and end point. Approximate time of impact using binary search + var iter = 0; + var tmin = 0; + var tmid = 0; + var tmax = timeOfImpact; + while (tmax >= tmin && iter < this.ccdIterations) { + iter++; + + // calculate the midpoint + tmid = (tmax - tmin) / 2; + + // Move the body to that point + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, rememberPosition, integrate_velodt); + this.angle = rememberAngle + startToEndAngle * timeOfImpact; + this.updateAABB(); + + // check overlap + var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit); + + if (overlaps) { + // change min to search upper interval + tmin = tmid; + } else { + // change max to search lower interval + tmax = tmid; + } + } + + timeOfImpact = tmid; + + vec2.copy(this.position, rememberPosition); + this.angle = rememberAngle; + + // move to TOI + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, this.position, integrate_velodt); + if(!this.fixedRotation){ + this.angle += startToEndAngle * timeOfImpact; + } + + return true; +}; + +/** + * Get velocity of a point in the body. + * @method getVelocityAtPoint + * @param {Array} result A vector to store the result in + * @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from + * @return {Array} The result vector + */ +Body.prototype.getVelocityAtPoint = function(result, relativePoint){ + vec2.crossVZ(result, relativePoint, this.angularVelocity); + vec2.subtract(result, this.velocity, result); + return result; +}; + +/** + * @event sleepy + */ +Body.sleepyEvent = { + type: "sleepy" +}; + +/** + * @event sleep + */ +Body.sleepEvent = { + type: "sleep" +}; + +/** + * @event wakeup + */ +Body.wakeUpEvent = { + type: "wakeup" +}; + +/** + * Dynamic body. + * @property DYNAMIC + * @type {Number} + * @static + */ +Body.DYNAMIC = 1; + +/** + * Static body. + * @property STATIC + * @type {Number} + * @static + */ +Body.STATIC = 2; + +/** + * Kinematic body. + * @property KINEMATIC + * @type {Number} + * @static + */ +Body.KINEMATIC = 4; + +/** + * @property AWAKE + * @type {Number} + * @static + */ +Body.AWAKE = 0; + +/** + * @property SLEEPY + * @type {Number} + * @static + */ +Body.SLEEPY = 1; + +/** + * @property SLEEPING + * @type {Number} + * @static + */ +Body.SLEEPING = 2; + + +},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = LinearSpring; + +/** + * A spring, connecting two bodies. + * + * The Spring explicitly adds force and angularForce to the bodies. + * + * @class LinearSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + */ +function LinearSpring(bodyA,bodyB,options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Anchor for bodyA in local bodyA coordinates. + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = vec2.fromValues(0,0); + + /** + * Anchor for bodyB in local bodyB coordinates. + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = vec2.fromValues(0,0); + + if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); } + if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); } + if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } + if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } + + var worldAnchorA = vec2.create(); + var worldAnchorB = vec2.create(); + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + var worldDistance = vec2.distance(worldAnchorA, worldAnchorB); + + /** + * Rest length of the spring. + * @property restLength + * @type {number} + */ + this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance; +} +LinearSpring.prototype = new Spring(); +LinearSpring.prototype.constructor = LinearSpring; + +/** + * Set the anchor point on body A, using world coordinates. + * @method setWorldAnchorA + * @param {Array} worldAnchorA + */ +LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){ + this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); +}; + +/** + * Set the anchor point on body B, using world coordinates. + * @method setWorldAnchorB + * @param {Array} worldAnchorB + */ +LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){ + this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); +}; + +/** + * Get the anchor point on body A, in world coordinates. + * @method getWorldAnchorA + * @param {Array} result The vector to store the result in. + */ +LinearSpring.prototype.getWorldAnchorA = function(result){ + this.bodyA.toWorldFrame(result, this.localAnchorA); +}; + +/** + * Get the anchor point on body B, in world coordinates. + * @method getWorldAnchorB + * @param {Array} result The vector to store the result in. + */ +LinearSpring.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(); + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +LinearSpring.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; + + // Get world anchors + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + + // Get offset points + vec2.sub(ri, worldAnchorA, bodyA.position); + vec2.sub(rj, worldAnchorB, bodyB.position); + + // Compute distance vector between world anchor points + vec2.sub(r, worldAnchorB, worldAnchorA); + var rlen = vec2.len(r); + vec2.normalize(r_unit,r); + + //console.log(rlen) + //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) + + // Compute relative velocity of the anchor points, u + 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); + + // F = - k * ( x - L ) - D * ( u ) + vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); + + // Add forces to bodies + vec2.sub( bodyA.force, bodyA.force, f); + vec2.add( bodyB.force, bodyB.force, f); + + // Angular force + 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":57,"./Spring":34}],33:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); + +module.exports = RotationalSpring; + +/** + * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies. + * + * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap. + * + * @class RotationalSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. + */ +function RotationalSpring(bodyA, bodyB, options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Rest angle of the spring. + * @property restAngle + * @type {number} + */ + this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle; +} +RotationalSpring.prototype = new Spring(); +RotationalSpring.prototype.constructor = RotationalSpring; + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +RotationalSpring.prototype.applyForce = function(){ + var k = this.stiffness, + d = this.damping, + l = this.restAngle, + bodyA = this.bodyA, + bodyB = this.bodyB, + x = bodyB.angle - bodyA.angle, + u = bodyB.angularVelocity - bodyA.angularVelocity; + + var torque = - k * (x - l) - d * u * 0; + + bodyA.angularForce -= torque; + bodyB.angularForce += torque; +}; + +},{"../math/vec2":30,"./Spring":34}],34:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = Spring; + +/** + * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver. + * + * @class Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + */ +function Spring(bodyA, bodyB, options){ + options = Utils.defaults(options,{ + stiffness: 100, + damping: 1, + }); + + /** + * Stiffness of the spring. + * @property stiffness + * @type {number} + */ + this.stiffness = options.stiffness; + + /** + * Damping of the spring. + * @property damping + * @type {number} + */ + this.damping = options.damping; + + /** + * First connected body. + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second connected body. + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; +} + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +Spring.prototype.applyForce = function(){ + // To be implemented by subclasses +}; + +},{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); +var Constraint = _dereq_('../constraints/Constraint'); +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Body = _dereq_('../objects/Body'); + +module.exports = TopDownVehicle; + +/** + * @class TopDownVehicle + * @constructor + * @param {Body} chassisBody A dynamic body, already added to the world. + * @param {Object} [options] + * + * @example + * + * // Create a dynamic body for the chassis + * var chassisBody = new Body({ + * mass: 1 + * }); + * var boxShape = new Box({ width: 0.5, height: 1 }); + * chassisBody.addShape(boxShape); + * world.addBody(chassisBody); + * + * // Create the vehicle + * var vehicle = new TopDownVehicle(chassisBody); + * + * // Add one front wheel and one back wheel - we don't actually need four :) + * var frontWheel = vehicle.addWheel({ + * localPosition: [0, 0.5] // front + * }); + * frontWheel.setSideFriction(4); + * + * // Back wheel + * var backWheel = vehicle.addWheel({ + * localPosition: [0, -0.5] // back + * }); + * backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift + * vehicle.addToWorld(world); + * + * // Steer value zero means straight forward. Positive is left and negative right. + * frontWheel.steerValue = Math.PI / 16; + * + * // Engine force forward + * backWheel.engineForce = 10; + * backWheel.setBrakeForce(0); + */ +function TopDownVehicle(chassisBody, options){ + options = options || {}; + + /** + * @property {Body} chassisBody + */ + this.chassisBody = chassisBody; + + /** + * @property {Array} wheels + */ + this.wheels = []; + + // A dummy body to constrain the chassis to + this.groundBody = new Body({ mass: 0 }); + + this.world = null; + + var that = this; + this.preStepCallback = function(){ + that.update(); + }; +} + +/** + * @method addToWorld + * @param {World} world + */ +TopDownVehicle.prototype.addToWorld = function(world){ + this.world = world; + world.addBody(this.groundBody); + world.on('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.addConstraint(wheel); + } +}; + +/** + * @method removeFromWorld + * @param {World} world + */ +TopDownVehicle.prototype.removeFromWorld = function(){ + var world = this.world; + world.removeBody(this.groundBody); + world.off('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.removeConstraint(wheel); + } + this.world = null; +}; + +/** + * @method addWheel + * @param {object} [wheelOptions] + * @return {WheelConstraint} + */ +TopDownVehicle.prototype.addWheel = function(wheelOptions){ + var wheel = new WheelConstraint(this,wheelOptions); + this.wheels.push(wheel); + return wheel; +}; + +/** + * @method update + */ +TopDownVehicle.prototype.update = function(){ + for (var i = 0; i < this.wheels.length; i++) { + this.wheels[i].update(); + } +}; + +/** + * @class WheelConstraint + * @constructor + * @extends {Constraint} + * @param {Vehicle} vehicle + * @param {object} [options] + * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero. + * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body. + * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction. + */ +function WheelConstraint(vehicle, options){ + options = options || {}; + + this.vehicle = vehicle; + + this.forwardEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + this.sideEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + /** + * @property {number} steerValue + */ + this.steerValue = 0; + + /** + * @property {number} engineForce + */ + this.engineForce = 0; + + this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5); + + /** + * @property {Array} localForwardVector + */ + this.localForwardVector = vec2.fromValues(0, 1); + if(options.localForwardVector){ + vec2.copy(this.localForwardVector, options.localForwardVector); + } + + /** + * @property {Array} localPosition + */ + this.localPosition = vec2.fromValues(0, 0); + if(options.localPosition){ + vec2.copy(this.localPosition, options.localPosition); + } + + Constraint.apply(this, vehicle.chassisBody, vehicle.groundBody); + + this.equations.push( + this.forwardEquation, + this.sideEquation + ); + + this.setBrakeForce(0); +} +WheelConstraint.prototype = new Constraint(); + +/** + * @method setForwardFriction + */ +WheelConstraint.prototype.setBrakeForce = function(force){ + this.forwardEquation.setSlipForce(force); +}; + +/** + * @method setSideFriction + */ +WheelConstraint.prototype.setSideFriction = function(force){ + this.sideEquation.setSlipForce(force); +}; + +var worldVelocity = vec2.create(); +var relativePoint = vec2.create(); + +/** + * @method getSpeed + */ +WheelConstraint.prototype.getSpeed = function(){ + this.vehicle.chassisBody.vectorToWorldFrame(relativePoint, this.localForwardVector); + this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity, relativePoint); + return vec2.dot(worldVelocity, relativePoint); +}; + +var tmpVec = vec2.create(); + +/** + * @method update + */ +WheelConstraint.prototype.update = function(){ + + // Directional + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t, this.localForwardVector); + vec2.rotate(this.sideEquation.t, this.localForwardVector, Math.PI / 2); + this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t, this.sideEquation.t); + + vec2.rotate(this.forwardEquation.t, this.forwardEquation.t, this.steerValue); + vec2.rotate(this.sideEquation.t, this.sideEquation.t, this.steerValue); + + // Attachment point + this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB, this.localPosition); + vec2.copy(this.sideEquation.contactPointB, this.forwardEquation.contactPointB); + + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA, this.localPosition); + vec2.copy(this.sideEquation.contactPointA, this.forwardEquation.contactPointA); + + // Add engine force + vec2.normalize(tmpVec, this.forwardEquation.t); + vec2.scale(tmpVec, tmpVec, this.engineForce); + + this.vehicle.chassisBody.applyForce(tmpVec, this.forwardEquation.contactPointA); +}; +},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(_dereq_,module,exports){ +// Export p2 classes +var p2 = module.exports = { + AABB : _dereq_('./collision/AABB'), + AngleLockEquation : _dereq_('./equations/AngleLockEquation'), + Body : _dereq_('./objects/Body'), + Broadphase : _dereq_('./collision/Broadphase'), + Capsule : _dereq_('./shapes/Capsule'), + Circle : _dereq_('./shapes/Circle'), + Constraint : _dereq_('./constraints/Constraint'), + ContactEquation : _dereq_('./equations/ContactEquation'), + ContactEquationPool : _dereq_('./utils/ContactEquationPool'), + ContactMaterial : _dereq_('./material/ContactMaterial'), + Convex : _dereq_('./shapes/Convex'), + DistanceConstraint : _dereq_('./constraints/DistanceConstraint'), + Equation : _dereq_('./equations/Equation'), + EventEmitter : _dereq_('./events/EventEmitter'), + FrictionEquation : _dereq_('./equations/FrictionEquation'), + FrictionEquationPool : _dereq_('./utils/FrictionEquationPool'), + GearConstraint : _dereq_('./constraints/GearConstraint'), + GSSolver : _dereq_('./solver/GSSolver'), + Heightfield : _dereq_('./shapes/Heightfield'), + Line : _dereq_('./shapes/Line'), + LockConstraint : _dereq_('./constraints/LockConstraint'), + Material : _dereq_('./material/Material'), + Narrowphase : _dereq_('./collision/Narrowphase'), + NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'), + Particle : _dereq_('./shapes/Particle'), + Plane : _dereq_('./shapes/Plane'), + Pool : _dereq_('./utils/Pool'), + RevoluteConstraint : _dereq_('./constraints/RevoluteConstraint'), + PrismaticConstraint : _dereq_('./constraints/PrismaticConstraint'), + Ray : _dereq_('./collision/Ray'), + RaycastResult : _dereq_('./collision/RaycastResult'), + Box : _dereq_('./shapes/Box'), + RotationalVelocityEquation : _dereq_('./equations/RotationalVelocityEquation'), + SAPBroadphase : _dereq_('./collision/SAPBroadphase'), + Shape : _dereq_('./shapes/Shape'), + Solver : _dereq_('./solver/Solver'), + Spring : _dereq_('./objects/Spring'), + TopDownVehicle : _dereq_('./objects/TopDownVehicle'), + LinearSpring : _dereq_('./objects/LinearSpring'), + RotationalSpring : _dereq_('./objects/RotationalSpring'), + Utils : _dereq_('./utils/Utils'), + World : _dereq_('./world/World'), + vec2 : _dereq_('./math/vec2'), + version : _dereq_('../package.json').version, +}; + +Object.defineProperty(p2, 'Rectangle', { + get: function() { + console.warn('The Rectangle class has been renamed to Box.'); + return this.Box; + } +}); +},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":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/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Shape = _dereq_('./Shape') +, Convex = _dereq_('./Convex'); + +module.exports = Box; + +/** + * Box shape class. + * @class Box + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.width=1] Total width of the box + * @param {Number} [options.height=1] Total height of the box + * @extends Convex + */ +function Box(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + width: arguments[0], + height: arguments[1] + }; + console.warn('The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })'); + } + options = options || {}; + + /** + * Total width of the box + * @property width + * @type {Number} + */ + var width = this.width = options.width || 1; + + /** + * Total height of the box + * @property height + * @type {Number} + */ + var height = this.height = options.height || 1; + + var verts = [ + vec2.fromValues(-width/2, -height/2), + vec2.fromValues( width/2, -height/2), + vec2.fromValues( width/2, height/2), + vec2.fromValues(-width/2, height/2) + ]; + var axes = [ + vec2.fromValues(1, 0), + vec2.fromValues(0, 1) + ]; + + options.vertices = verts; + options.axes = axes; + options.type = Shape.BOX; + Convex.call(this, options); +} +Box.prototype = new Convex(); +Box.prototype.constructor = Box; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Box.prototype.computeMomentOfInertia = function(mass){ + var w = this.width, + h = this.height; + return mass * (h*h + w*w) / 12; +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Box.prototype.updateBoundingRadius = function(){ + var w = this.width, + h = this.height; + this.boundingRadius = Math.sqrt(w*w + h*h) / 2; +}; + +var corner1 = vec2.create(), + corner2 = vec2.create(), + corner3 = vec2.create(), + corner4 = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Box.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices,position,angle,0); +}; + +Box.prototype.updateArea = function(){ + this.area = this.width * this.height; +}; + + +},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Capsule; + +/** + * Capsule shape class. + * @class Capsule + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The distance between the end points + * @param {Number} [options.radius=1] Radius of the capsule + * @example + * var capsuleShape = new Capsule({ + * length: 1, + * radius: 2 + * }); + * body.addShape(capsuleShape); + */ +function Capsule(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + length: arguments[0], + radius: arguments[1] + }; + console.warn('The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })'); + } + options = options || {}; + + /** + * The distance between the end points. + * @property {Number} length + */ + this.length = options.length || 1; + + /** + * The radius of the capsule. + * @property {Number} radius + */ + this.radius = options.radius || 1; + + options.type = Shape.CAPSULE; + Shape.call(this, options); +} +Capsule.prototype = new Shape(); +Capsule.prototype.constructor = Capsule; + +/** + * Compute the mass moment of inertia of the Capsule. + * @method conputeMomentOfInertia + * @param {Number} mass + * @return {Number} + * @todo + */ +Capsule.prototype.computeMomentOfInertia = function(mass){ + // Approximate with rectangle + var r = this.radius, + w = this.length + r, // 2*r is too much, 0 is too little + h = r*2; + return mass * (h*h + w*w) / 12; +}; + +/** + * @method updateBoundingRadius + */ +Capsule.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius + this.length/2; +}; + +/** + * @method updateArea + */ +Capsule.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; +}; + +var r = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Capsule.prototype.computeAABB = function(out, position, angle){ + var radius = this.radius; + + // Compute center position of one of the the circles, world oriented, but with local offset + vec2.set(r,this.length / 2,0); + if(angle !== 0){ + vec2.rotate(r,r,angle); + } + + // Get bounds + 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)); + + // Add offset + vec2.add(out.lowerBound, out.lowerBound, position); + vec2.add(out.upperBound, out.upperBound, position); +}; + +var intersectCapsule_hitPointWorld = vec2.create(); +var intersectCapsule_normal = vec2.create(); +var intersectCapsule_l0 = vec2.create(); +var intersectCapsule_l1 = vec2.create(); +var intersectCapsule_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Capsule.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectCapsule_hitPointWorld; + var normal = intersectCapsule_normal; + var l0 = intersectCapsule_l0; + var l1 = intersectCapsule_l1; + + // The sides + var halfLen = this.length / 2; + for(var i=0; i<2; i++){ + + // get start and end of the line + var y = this.radius * (i*2-1); + vec2.set(l0, -halfLen, y); + vec2.set(l1, halfLen, y); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var delta = vec2.getLineSegmentsIntersectionFraction(from, to, l0, l1); + if(delta >= 0){ + vec2.rotate(normal, intersectCapsule_unit_y, angle); + vec2.scale(normal, normal, (i*2-1)); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + // Circles + var diagonalLengthSquared = Math.pow(this.radius, 2) + Math.pow(halfLen, 2); + for(var i=0; i<2; i++){ + vec2.set(l0, halfLen * (i*2-1), 0); + vec2.toGlobalFrame(l0, l0, position, angle); + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - l0[0]) + (to[1] - from[1]) * (from[1] - l0[1])); + var c = Math.pow(from[0] - l0[0], 2) + Math.pow(from[1] - l0[1], 2) - Math.pow(this.radius, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + if(delta < 0){ + // No intersection + continue; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(hitPointWorld, from, to, delta); + + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(hitPointWorld, from, to, d1); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d1, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(hitPointWorld, from, to, d2); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d2, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + } + } +}; +},{"../math/vec2":30,"./Shape":45}],39:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Circle; + +/** + * Circle shape class. + * @class Circle + * @extends Shape + * @constructor + * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {number} [options.radius=1] The radius of this circle + * + * @example + * var circleShape = new Circle({ radius: 1 }); + * body.addShape(circleShape); + */ +function Circle(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + radius: arguments[0] + }; + console.warn('The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })'); + } + options = options || {}; + + /** + * The radius of the circle. + * @property radius + * @type {number} + */ + this.radius = options.radius || 1; + + options.type = Shape.CIRCLE; + Shape.call(this, options); +} +Circle.prototype = new Shape(); +Circle.prototype.constructor = Circle; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Circle.prototype.computeMomentOfInertia = function(mass){ + var r = this.radius; + return mass * r * r / 2; +}; + +/** + * @method updateBoundingRadius + * @return {Number} + */ +Circle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius; +}; + +/** + * @method updateArea + * @return {Number} + */ +Circle.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius; +}; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +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); + } +}; + +var Ray_intersectSphere_intersectionPoint = vec2.create(); +var Ray_intersectSphere_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Circle.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from, + to = ray.to, + r = this.radius; + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1])); + var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + var intersectionPoint = Ray_intersectSphere_intersectionPoint; + var normal = Ray_intersectSphere_normal; + + if(delta < 0){ + // No intersection + return; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(intersectionPoint, from, to, delta); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, delta, normal, -1); + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(intersectionPoint, from, to, d1); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d1, normal, -1); + + if(result.shouldStop(ray)){ + return; + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(intersectionPoint, from, to, d2); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d2, normal, -1); + } + } +}; +},{"../math/vec2":30,"./Shape":45}],40:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, polyk = _dereq_('../math/polyk') +, decomp = _dereq_('poly-decomp'); + +module.exports = Convex; + +/** + * Convex shape class. + * @class Convex + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. + * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex. + * @example + * // Create a box + * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]]; + * var convexShape = new Convex({ vertices: vertices }); + * body.addShape(convexShape); + */ +function Convex(options){ + if(Array.isArray(arguments[0])){ + options = { + vertices: arguments[0], + axes: arguments[1] + }; + console.warn('The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })'); + } + options = options || {}; + + /** + * Vertices defined in the local frame. + * @property vertices + * @type {Array} + */ + this.vertices = []; + + // Copy the verts + var vertices = options.vertices !== undefined ? options.vertices : []; + for(var i=0; i < vertices.length; i++){ + var v = vec2.create(); + vec2.copy(v, vertices[i]); + this.vertices.push(v); + } + + /** + * Axes defined in the local frame. + * @property axes + * @type {Array} + */ + this.axes = []; + + if(options.axes){ + + // Copy the axes + for(var i=0; i < options.axes.length; i++){ + var axis = vec2.create(); + vec2.copy(axis, options.axes[i]); + this.axes.push(axis); + } + + } else { + + // Construct axes from the vertex data + for(var i = 0; i < this.vertices.length; i++){ + // Get the world edge + var worldPoint0 = this.vertices[i]; + var worldPoint1 = this.vertices[(i+1) % this.vertices.length]; + + var normal = vec2.create(); + vec2.sub(normal, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, normal); + vec2.normalize(normal, normal); + + this.axes.push(normal); + } + + } + + /** + * The center of mass of the Convex + * @property centerOfMass + * @type {Array} + */ + this.centerOfMass = vec2.fromValues(0,0); + + /** + * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. + * @property triangles + * @type {Array} + */ + this.triangles = []; + + if(this.vertices.length){ + this.updateTriangles(); + this.updateCenterOfMass(); + } + + /** + * The bounding radius of the convex + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + options.type = Shape.CONVEX; + Shape.call(this, options); + + this.updateBoundingRadius(); + this.updateArea(); + if(this.area < 0){ + throw new Error("Convex vertices must be given in conter-clockwise winding."); + } +} +Convex.prototype = new Shape(); +Convex.prototype.constructor = Convex; + +var tmpVec1 = vec2.create(); +var tmpVec2 = vec2.create(); + +/** + * Project a Convex onto a world-oriented axis + * @method projectOntoAxis + * @static + * @param {Array} offset + * @param {Array} localAxis + * @param {Array} result + */ +Convex.prototype.projectOntoLocalAxis = function(localAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = tmpVec1; + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + vec2.set(result, min, max); +}; + +Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){ + var worldAxis = tmpVec2; + + this.projectOntoLocalAxis(localAxis, result); + + // Project the position of the body onto the axis - need to add this to the result + if(shapeAngle !== 0){ + vec2.rotate(worldAxis, localAxis, shapeAngle); + } else { + worldAxis = localAxis; + } + var offset = vec2.dot(shapeOffset, worldAxis); + + vec2.set(result, result[0] + offset, result[1] + offset); +}; + + +/** + * Update the .triangles property + * @method updateTriangles + */ +Convex.prototype.updateTriangles = function(){ + + this.triangles.length = 0; + + // Rewrite on polyk notation, array of numbers + var polykVerts = []; + for(var i=0; i r2){ + r2 = l2; + } + } + + this.boundingRadius = Math.sqrt(r2); +}; + +/** + * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. + * @static + * @method triangleArea + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +Convex.triangleArea = function(a,b,c){ + return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; +}; + +/** + * Update the .area + * @method updateArea + */ +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]]; + + // Get mass for the triangle (density=1 in this case) + var m = Convex.triangleArea(a,b,c); + this.area += m; + } +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Convex.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices, position, angle, 0); +}; + +var intersectConvex_rayStart = vec2.create(); +var intersectConvex_rayEnd = vec2.create(); +var intersectConvex_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Convex.prototype.raycast = function(result, ray, position, angle){ + var rayStart = intersectConvex_rayStart; + var rayEnd = intersectConvex_rayEnd; + var normal = intersectConvex_normal; + var vertices = this.vertices; + + // Transform to local shape space + vec2.toLocalFrame(rayStart, ray.from, position, angle); + vec2.toLocalFrame(rayEnd, ray.to, position, angle); + + var n = vertices.length; + + for (var i = 0; i < n && !result.shouldStop(ray); i++) { + var q1 = vertices[i]; + var q2 = vertices[(i+1) % n]; + var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2); + + if(delta >= 0){ + vec2.sub(normal, q2, q1); + vec2.rotate(normal, normal, -Math.PI / 2 + angle); + vec2.normalize(normal, normal); + ray.reportIntersection(result, delta, normal, i); + } + } +}; + +},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Heightfield; + +/** + * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". + * @class Heightfield + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {array} [options.heights] An array of Y values that will be used to construct the terrain. + * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given. + * @param {Number} [options.maxValue] Maximum value. + * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction. + * + * @example + * // Generate some height data (y-values). + * var heights = []; + * for(var i = 0; i < 1000; i++){ + * var y = 0.5 * Math.cos(0.2 * i); + * heights.push(y); + * } + * + * // Create the heightfield shape + * var heightfieldShape = new Heightfield({ + * heights: heights, + * elementWidth: 1 // Distance between the data points in X direction + * }); + * var heightfieldBody = new Body(); + * heightfieldBody.addShape(heightfieldShape); + * world.addBody(heightfieldBody); + * + * @todo Should use a scale property with X and Y direction instead of just elementWidth + */ +function Heightfield(options){ + if(Array.isArray(arguments[0])){ + options = { + heights: arguments[0] + }; + + if(typeof(arguments[1]) === 'object'){ + for(var key in arguments[1]){ + options[key] = arguments[1][key]; + } + } + + console.warn('The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })'); + } + options = options || {}; + + /** + * An array of numbers, or height values, that are spread out along the x axis. + * @property {array} heights + */ + this.heights = options.heights ? options.heights.slice(0) : []; + + /** + * Max value of the heights + * @property {number} maxValue + */ + this.maxValue = options.maxValue || null; + + /** + * Max value of the heights + * @property {number} minValue + */ + this.minValue = options.minValue || null; + + /** + * The width of each element + * @property {number} elementWidth + */ + this.elementWidth = options.elementWidth || 0.1; + + if(options.maxValue === undefined || options.minValue === undefined){ + this.updateMaxMinValues(); + } + + options.type = Shape.HEIGHTFIELD; + Shape.call(this, options); +} +Heightfield.prototype = new Shape(); +Heightfield.prototype.constructor = Heightfield; + +/** + * Update the .minValue and the .maxValue + * @method updateMaxMinValues + */ +Heightfield.prototype.updateMaxMinValues = function(){ + var data = this.heights; + var maxValue = data[0]; + var minValue = data[0]; + for(var i=0; i !== data.length; i++){ + var v = data[i]; + if(v > maxValue){ + maxValue = v; + } + if(v < minValue){ + minValue = v; + } + } + this.maxValue = maxValue; + this.minValue = minValue; +}; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Heightfield.prototype.computeMomentOfInertia = function(mass){ + return Number.MAX_VALUE; +}; + +Heightfield.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +Heightfield.prototype.updateArea = function(){ + var data = this.heights, + area = 0; + for(var i=0; i= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + var intX = p0[0] + (t * s1_x); + var intY = p0[1] + (t * s1_y); + out[0] = intX; + out[1] = intY; + return t; + } + return -1; // No collision +} + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Heightfield.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectHeightfield_hitPointWorld; + var worldNormal = intersectHeightfield_worldNormal; + var l0 = intersectHeightfield_l0; + var l1 = intersectHeightfield_l1; + var localFrom = intersectHeightfield_localFrom; + var localTo = intersectHeightfield_localTo; + + // get local ray start and end + vec2.toLocalFrame(localFrom, from, position, angle); + vec2.toLocalFrame(localTo, to, position, angle); + + // Get the segment range + var i0 = this.getClampedSegmentIndex(localFrom); + var i1 = this.getClampedSegmentIndex(localTo); + if(i0 > i1){ + var tmp = i0; + i0 = i1; + i1 = tmp; + } + + // The segments + for(var i=0; i= 0){ + vec2.sub(worldNormal, l1, l0); + vec2.rotate(worldNormal, worldNormal, angle + Math.PI / 2); + vec2.normalize(worldNormal, worldNormal); + ray.reportIntersection(result, t, worldNormal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Line; + +/** + * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * @class Line + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The total length of the line + * @extends Shape + * @constructor + */ +function Line(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + length: arguments[0] + }; + console.warn('The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })'); + } + options = options || {}; + + /** + * Length of this line + * @property {Number} length + * @default 1 + */ + this.length = options.length || 1; + + options.type = Shape.LINE; + Shape.call(this, options); +} +Line.prototype = new Shape(); +Line.prototype.constructor = Line; + +Line.prototype.computeMomentOfInertia = function(mass){ + return mass * Math.pow(this.length,2) / 12; +}; + +Line.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.length/2; +}; + +var points = [vec2.create(),vec2.create()]; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Line.prototype.computeAABB = function(out, position, angle){ + var l2 = this.length / 2; + vec2.set(points[0], -l2, 0); + vec2.set(points[1], l2, 0); + out.setFromPoints(points,position,angle,0); +}; + +var raycast_hitPoint = vec2.create(); +var raycast_normal = vec2.create(); +var raycast_l0 = vec2.create(); +var raycast_l1 = vec2.create(); +var raycast_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {number} angle + * @param {array} position + */ +Line.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + + var l0 = raycast_l0; + var l1 = raycast_l1; + + // get start and end of the line + var halfLen = this.length / 2; + vec2.set(l0, -halfLen, 0); + vec2.set(l1, halfLen, 0); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to); + if(fraction >= 0){ + var normal = raycast_normal; + vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from + ray.reportIntersection(result, fraction, normal, -1); + } +}; +},{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Particle; + +/** + * Particle shape class. + * @class Particle + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @extends Shape + */ +function Particle(options){ + options = options || {}; + options.type = Shape.PARTICLE; + Shape.call(this, options); +} +Particle.prototype = new Shape(); +Particle.prototype.constructor = Particle; + +Particle.prototype.computeMomentOfInertia = function(mass){ + return 0; // Can't rotate a particle +}; + +Particle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = 0; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Particle.prototype.computeAABB = function(out, position, angle){ + vec2.copy(out.lowerBound, position); + vec2.copy(out.upperBound, position); +}; + +},{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Plane; + +/** + * Plane shape class. The plane is facing in the Y direction. + * @class Plane + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + */ +function Plane(options){ + options = options || {}; + options.type = Shape.PLANE; + Shape.call(this, options); +} +Plane.prototype = new Shape(); +Plane.prototype.constructor = Plane; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + */ +Plane.prototype.computeMomentOfInertia = function(mass){ + return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Plane.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Plane.prototype.computeAABB = function(out, position, angle){ + var a = angle % (2 * Math.PI); + var set = vec2.set; + var max = 1e7; + var lowerBound = out.lowerBound; + var upperBound = out.upperBound; + + // Set max bounds + set(lowerBound, -max, -max); + set(upperBound, max, max); + + if(a === 0){ + // y goes from -inf to 0 + upperBound[1] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, max, 0); + + } else if(a === Math.PI / 2){ + + // x goes from 0 to inf + lowerBound[0] = 0; + // set(lowerBound, 0, -max); + // set(upperBound, max, max); + + } else if(a === Math.PI){ + + // y goes from 0 to inf + lowerBound[1] = 0; + // set(lowerBound, -max, 0); + // set(upperBound, max, max); + + } else if(a === 3*Math.PI/2){ + + // x goes from -inf to 0 + upperBound[0] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, 0, max); + + } +}; + +Plane.prototype.updateArea = function(){ + this.area = Number.MAX_VALUE; +}; + +var intersectPlane_planePointToFrom = vec2.create(); +var intersectPlane_dir_scaled_with_t = vec2.create(); +var intersectPlane_hitPoint = vec2.create(); +var intersectPlane_normal = vec2.create(); +var intersectPlane_len = vec2.create(); + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Plane.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + var planePointToFrom = intersectPlane_planePointToFrom; + var dir_scaled_with_t = intersectPlane_dir_scaled_with_t; + var hitPoint = intersectPlane_hitPoint; + var normal = intersectPlane_normal; + var len = intersectPlane_len; + + // Get plane normal + vec2.set(normal, 0, 1); + vec2.rotate(normal, normal, angle); + + vec2.sub(len, from, position); + var planeToFrom = vec2.dot(len, normal); + vec2.sub(len, to, position); + var planeToTo = vec2.dot(len, normal); + + if(planeToFrom * planeToTo > 0){ + // "from" and "to" are on the same side of the plane... bail out + return; + } + + if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){ + return; + } + + var n_dot_dir = vec2.dot(normal, direction); + + vec2.sub(planePointToFrom, from, position); + var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length; + + ray.reportIntersection(result, t, normal, -1); +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(_dereq_,module,exports){ +module.exports = Shape; + +var vec2 = _dereq_('../math/vec2'); + +/** + * Base class for shapes. + * @class Shape + * @constructor + * @param {object} [options] + * @param {array} [options.position] + * @param {number} [options.angle=0] + * @param {number} [options.collisionGroup=1] + * @param {number} [options.collisionMask=1] + * @param {boolean} [options.sensor=false] + * @param {boolean} [options.collisionResponse=true] + * @param {object} [options.type=0] + */ +function Shape(options){ + options = options || {}; + + /** + * The body this shape is attached to. A shape can only be attached to a single body. + * @property {Body} body + */ + this.body = null; + + /** + * Body-local position of the shape. + * @property {Array} position + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * Body-local angle of the shape. + * @property {number} angle + */ + this.angle = options.angle || 0; + + /** + * The type of the shape. One of: + * + * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} + * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} + * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} + * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} + * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} + * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}} + * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} + * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} + * + * @property {number} type + */ + this.type = options.type || 0; + + /** + * Shape object identifier. + * @type {Number} + * @property id + */ + this.id = Shape.idCounter++; + + /** + * Bounding circle radius of this shape + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + /** + * Collision group that this shape belongs to (bit mask). See this tutorial. + * @property collisionGroup + * @type {Number} + * @example + * // Setup bits for each available group + * var PLAYER = Math.pow(2,0), + * ENEMY = Math.pow(2,1), + * GROUND = Math.pow(2,2) + * + * // Put shapes into their groups + * player1Shape.collisionGroup = PLAYER; + * player2Shape.collisionGroup = PLAYER; + * enemyShape .collisionGroup = ENEMY; + * groundShape .collisionGroup = GROUND; + * + * // Assign groups that each shape collide with. + * // Note that the players can collide with ground and enemies, but not with other players. + * player1Shape.collisionMask = ENEMY | GROUND; + * player2Shape.collisionMask = ENEMY | GROUND; + * enemyShape .collisionMask = PLAYER | GROUND; + * groundShape .collisionMask = PLAYER | ENEMY; + * + * @example + * // How collision check is done + * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ + * // The shapes will collide + * } + */ + this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. + * @property {Boolean} collisionResponse + */ + this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; + + /** + * Collision mask of this shape. See .collisionGroup. + * @property collisionMask + * @type {Number} + */ + this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; + + /** + * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. + * @property material + * @type {Material} + */ + this.material = options.material || null; + + /** + * Area of this shape. + * @property area + * @type {Number} + */ + this.area = 0; + + /** + * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. + * @property {Boolean} sensor + */ + this.sensor = options.sensor !== undefined ? options.sensor : false; + + if(this.type){ + this.updateBoundingRadius(); + } + + this.updateArea(); +} + +Shape.idCounter = 0; + +/** + * @static + * @property {Number} CIRCLE + */ +Shape.CIRCLE = 1; + +/** + * @static + * @property {Number} PARTICLE + */ +Shape.PARTICLE = 2; + +/** + * @static + * @property {Number} PLANE + */ +Shape.PLANE = 4; + +/** + * @static + * @property {Number} CONVEX + */ +Shape.CONVEX = 8; + +/** + * @static + * @property {Number} LINE + */ +Shape.LINE = 16; + +/** + * @static + * @property {Number} BOX + */ +Shape.BOX = 32; + +/** + * @static + * @property {Number} CAPSULE + */ +Shape.CAPSULE = 64; + +/** + * @static + * @property {Number} HEIGHTFIELD + */ +Shape.HEIGHTFIELD = 128; + +/** + * Should return the moment of inertia around the Z axis of the body given the total mass. See Wikipedia's list of moments of inertia. + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. + */ +Shape.prototype.computeMomentOfInertia = function(mass){}; + +/** + * Returns the bounding circle radius of this shape. + * @method updateBoundingRadius + * @return {Number} + */ +Shape.prototype.updateBoundingRadius = function(){}; + +/** + * Update the .area property of the shape. + * @method updateArea + */ +Shape.prototype.updateArea = function(){ + // To be implemented in all subclasses +}; + +/** + * Compute the world axis-aligned bounding box (AABB) of this shape. + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position World position of the shape. + * @param {Number} angle World angle of the shape. + */ +Shape.prototype.computeAABB = function(out, position, angle){ + // To be implemented in each subclass +}; + +/** + * Perform raycasting on this shape. + * @method raycast + * @param {RayResult} result Where to store the resulting data. + * @param {Ray} ray The Ray that you want to use for raycasting. + * @param {array} position World position of the shape (the .position property will be ignored). + * @param {number} angle World angle of the shape (the .angle property will be ignored). + */ +Shape.prototype.raycast = function(result, ray, position, angle){ + // To be implemented in each subclass +}; +},{"../math/vec2":30}],46:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Solver = _dereq_('./Solver') +, Utils = _dereq_('../utils/Utils') +, FrictionEquation = _dereq_('../equations/FrictionEquation'); + +module.exports = GSSolver; + +/** + * Iterative Gauss-Seidel constraint equation solver. + * + * @class GSSolver + * @constructor + * @extends Solver + * @param {Object} [options] + * @param {Number} [options.iterations=10] + * @param {Number} [options.tolerance=0] + */ +function GSSolver(options){ + Solver.call(this,options,Solver.GS); + options = options || {}; + + /** + * The max number of iterations to do when solving. More gives better results, but is more expensive. + * @property iterations + * @type {Number} + */ + this.iterations = options.iterations || 10; + + /** + * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. + * @property tolerance + * @type {Number} + * @default 1e-7 + */ + this.tolerance = options.tolerance || 1e-7; + + this.arrayStep = 30; + this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); + + /** + * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. + * @property useZeroRHS + * @type {Boolean} + * @todo Remove, not used + */ + this.useZeroRHS = false; + + /** + * Number of solver iterations that are used to approximate normal forces used for friction (F_friction = mu * F_normal). These friction forces will override any other friction forces that are set. If you set frictionIterations = 0, then this feature will be disabled. + * + * Use only frictionIterations > 0 if the approximated normal force (F_normal = mass * gravity) is not good enough. Examples of where it can happen is in space games where gravity is zero, or in tall stacks where the normal force is large at bottom but small at top. + * + * @property frictionIterations + * @type {Number} + * @default 0 + */ + this.frictionIterations = options.frictionIterations !== undefined ? 0 : options.frictionIterations; + + /** + * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. + * @property {Number} usedIterations + */ + this.usedIterations = 0; +} +GSSolver.prototype = new Solver(); +GSSolver.prototype.constructor = GSSolver; + +function setArrayZero(array){ + var l = array.length; + while(l--){ + array[l] = +0.0; + } +} + +/** + * Solve the system of equations + * @method solve + * @param {Number} h Time step + * @param {World} world World to solve + */ +GSSolver.prototype.solve = function(h, world){ + + this.sortEquations(); + + var iter = 0, + maxIter = this.iterations, + maxFrictionIter = this.frictionIterations, + equations = this.equations, + Neq = equations.length, + tolSquared = Math.pow(this.tolerance*Neq, 2), + bodies = world.bodies, + Nbodies = world.bodies.length, + add = vec2.add, + set = vec2.set, + useZeroRHS = this.useZeroRHS, + lambda = this.lambda; + + this.usedIterations = 0; + + if(Neq){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Update solve mass + b.updateSolveMassProperties(); + } + } + + // Things that does not change during iteration can be computed once + if(lambda.length < Neq){ + lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + } + setArrayZero(lambda); + var invCs = this.invCs, + Bs = this.Bs, + lambda = this.lambda; + + for(var i=0; i!==equations.length; i++){ + var c = equations[i]; + if(c.timeStep !== h || c.needsUpdate){ + c.timeStep = h; + c.update(); + } + Bs[i] = c.computeB(c.a,c.b,h); + invCs[i] = c.computeInvC(c.epsilon); + } + + var q, B, c, deltalambdaTot,i,j; + + if(Neq !== 0){ + + for(i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Reset vlambda + b.resetConstraintVelocity(); + } + + if(maxFrictionIter){ + // Iterate over contact equations to get normal forces + for(iter=0; iter!==maxFrictionIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + + // Set computed friction force + for(j=0; j!==Neq; j++){ + var eq = equations[j]; + if(eq instanceof FrictionEquation){ + var f = 0.0; + for(var k=0; k!==eq.contactEquations.length; k++){ + f += eq.contactEquations[k].multiplier; + } + f *= eq.frictionCoefficient / eq.contactEquations.length; + eq.maxForce = f; + eq.minForce = -f; + } + } + } + + // Iterate over all equations + for(iter=0; iter!==maxIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + // Add result to velocity + for(i=0; i!==Nbodies; i++){ + bodies[i].addConstraintVelocity(); + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + } +}; + +// Sets the .multiplier property of each equation +GSSolver.updateMultipliers = function(equations, lambda, invDt){ + // Set the .multiplier property of each equation + var l = equations.length; + while(l--){ + equations[l].multiplier = lambda[l] * invDt; + } +}; + +GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ + // Compute iteration + var B = Bs[j], + invC = invCs[j], + lambdaj = lambda[j], + GWlambda = eq.computeGWlambda(); + + var maxForce = eq.maxForce, + minForce = eq.minForce; + + if(useZeroRHS){ + B = 0; + } + + var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); + + // Clamp if we are not within the min/max interval + var lambdaj_plus_deltalambda = lambdaj + deltalambda; + if(lambdaj_plus_deltalambda < minForce*dt){ + deltalambda = minForce*dt - lambdaj; + } else if(lambdaj_plus_deltalambda > maxForce*dt){ + deltalambda = maxForce*dt - lambdaj; + } + lambda[j] += deltalambda; + eq.addToWlambda(deltalambda); + + return deltalambda; +}; + +},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Solver; + +/** + * Base class for constraint solvers. + * @class Solver + * @constructor + * @extends EventEmitter + */ +function Solver(options,type){ + options = options || {}; + + EventEmitter.call(this); + + this.type = type; + + /** + * Current equations in the solver. + * + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Function that is used to sort all equations before each solve. + * @property equationSortFunction + * @type {function|boolean} + */ + this.equationSortFunction = options.equationSortFunction || false; +} +Solver.prototype = new EventEmitter(); +Solver.prototype.constructor = Solver; + +/** + * Method to be implemented in each subclass + * @method solve + * @param {Number} dt + * @param {World} world + */ +Solver.prototype.solve = function(dt,world){ + throw new Error("Solver.solve should be implemented by subclasses!"); +}; + +var mockWorld = {bodies:[]}; + +/** + * Solves all constraints in an island. + * @method solveIsland + * @param {Number} dt + * @param {Island} island + */ +Solver.prototype.solveIsland = function(dt,island){ + + this.removeAllEquations(); + + if(island.equations.length){ + // Add equations to solver + this.addEquations(island.equations); + mockWorld.bodies.length = 0; + island.getBodies(mockWorld.bodies); + + // Solve + if(mockWorld.bodies.length){ + this.solve(dt,mockWorld); + } + } +}; + +/** + * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. + * @method sortEquations + */ +Solver.prototype.sortEquations = function(){ + if(this.equationSortFunction){ + this.equations.sort(this.equationSortFunction); + } +}; + +/** + * Add an equation to be solved. + * + * @method addEquation + * @param {Equation} eq + */ +Solver.prototype.addEquation = function(eq){ + if(eq.enabled){ + this.equations.push(eq); + } +}; + +/** + * Add equations. Same as .addEquation, but this time the argument is an array of Equations + * + * @method addEquations + * @param {Array} eqs + */ +Solver.prototype.addEquations = function(eqs){ + //Utils.appendArray(this.equations,eqs); + for(var i=0, N=eqs.length; i!==N; i++){ + var eq = eqs[i]; + if(eq.enabled){ + this.equations.push(eq); + } + } +}; + +/** + * Remove an equation. + * + * @method removeEquation + * @param {Equation} eq + */ +Solver.prototype.removeEquation = function(eq){ + var i = this.equations.indexOf(eq); + if(i !== -1){ + this.equations.splice(i,1); + } +}; + +/** + * Remove all currently added equations. + * + * @method removeAllEquations + */ +Solver.prototype.removeAllEquations = function(){ + this.equations.length=0; +}; + +Solver.GS = 1; +Solver.ISLAND = 2; + +},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){ +var ContactEquation = _dereq_('../equations/ContactEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = ContactEquationPool; + +/** + * @class + */ +function ContactEquationPool() { + Pool.apply(this, arguments); +} +ContactEquationPool.prototype = new Pool(); +ContactEquationPool.prototype.constructor = ContactEquationPool; + +/** + * @method create + * @return {ContactEquation} + */ +ContactEquationPool.prototype.create = function () { + return new ContactEquation(); +}; + +/** + * @method destroy + * @param {ContactEquation} equation + * @return {ContactEquationPool} + */ +ContactEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){ +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = FrictionEquationPool; + +/** + * @class + */ +function FrictionEquationPool() { + Pool.apply(this, arguments); +} +FrictionEquationPool.prototype = new Pool(); +FrictionEquationPool.prototype.constructor = FrictionEquationPool; + +/** + * @method create + * @return {FrictionEquation} + */ +FrictionEquationPool.prototype.create = function () { + return new FrictionEquation(); +}; + +/** + * @method destroy + * @param {FrictionEquation} equation + * @return {FrictionEquationPool} + */ +FrictionEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){ +var IslandNode = _dereq_('../world/IslandNode'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandNodePool; + +/** + * @class + */ +function IslandNodePool() { + Pool.apply(this, arguments); +} +IslandNodePool.prototype = new Pool(); +IslandNodePool.prototype.constructor = IslandNodePool; + +/** + * @method create + * @return {IslandNode} + */ +IslandNodePool.prototype.create = function () { + return new IslandNode(); +}; + +/** + * @method destroy + * @param {IslandNode} node + * @return {IslandNodePool} + */ +IslandNodePool.prototype.destroy = function (node) { + node.reset(); + return this; +}; + +},{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){ +var Island = _dereq_('../world/Island'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandPool; + +/** + * @class + */ +function IslandPool() { + Pool.apply(this, arguments); +} +IslandPool.prototype = new Pool(); +IslandPool.prototype.constructor = IslandPool; + +/** + * @method create + * @return {Island} + */ +IslandPool.prototype.create = function () { + return new Island(); +}; + +/** + * @method destroy + * @param {Island} island + * @return {IslandPool} + */ +IslandPool.prototype.destroy = function (island) { + island.reset(); + return this; +}; + +},{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){ +var TupleDictionary = _dereq_('./TupleDictionary'); +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool'); +var Utils = _dereq_('./Utils'); + +module.exports = OverlapKeeper; + +/** + * Keeps track of overlaps in the current state and the last step state. + * @class OverlapKeeper + * @constructor + */ +function OverlapKeeper() { + this.overlappingShapesLastState = new TupleDictionary(); + this.overlappingShapesCurrentState = new TupleDictionary(); + this.recordPool = new OverlapKeeperRecordPool({ size: 16 }); + this.tmpDict = new TupleDictionary(); + this.tmpArray1 = []; +} + +/** + * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current. + * @method tick + */ +OverlapKeeper.prototype.tick = function() { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Save old objects into pool + var l = last.keys.length; + while(l--){ + var key = last.keys[l]; + var lastObject = last.getByKey(key); + var currentObject = current.getByKey(key); + if(lastObject){ + // The record is only used in the "last" dict, and will be removed. We might as well pool it. + this.recordPool.release(lastObject); + } + } + + // Clear last object + last.reset(); + + // Transfer from new object to old + last.copy(current); + + // Clear current object + current.reset(); +}; + +/** + * @method setOverlapping + * @param {Body} bodyA + * @param {Body} shapeA + * @param {Body} bodyB + * @param {Body} shapeB + */ +OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Store current contact state + if(!current.get(shapeA.id, shapeB.id)){ + var data = this.recordPool.get(); + data.set(bodyA, shapeA, bodyB, shapeB); + current.set(shapeA.id, shapeB.id, data); + } +}; + +OverlapKeeper.prototype.getNewOverlaps = function(result){ + return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result); +}; + +OverlapKeeper.prototype.getEndOverlaps = function(result){ + return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result); +}; + +/** + * Checks if two bodies are currently overlapping. + * @method bodiesAreOverlapping + * @param {Body} bodyA + * @param {Body} bodyB + * @return {boolean} + */ +OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){ + var current = this.overlappingShapesCurrentState; + var l = current.keys.length; + while(l--){ + var key = current.keys[l]; + var data = current.data[key]; + if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){ + return true; + } + } + return false; +}; + +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){ + // Not overlapping in last state, but in current. + result.push(data); + } + } + + return result; +}; + +OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ + var idA = shapeA.id|0, + idB = shapeB.id|0; + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + // Not in last but in new + return !!!last.get(idA, idB) && !!current.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]; + + // Since we use body id's for the accumulator, these will be a subset of the original one + accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); + } + + l = accumulator.keys.length; + while(l--){ + var data = accumulator.getByKey(accumulator.keys[l]); + if(data){ + result.push(data.bodyA, data.bodyB); + } + } + + accumulator.reset(); + + return result; +}; + +},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){ +module.exports = OverlapKeeperRecord; + +/** + * Overlap data container for the OverlapKeeper + * @class OverlapKeeperRecord + * @constructor + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ + /** + * @property {Shape} shapeA + */ + this.shapeA = shapeA; + /** + * @property {Shape} shapeB + */ + this.shapeB = shapeB; + /** + * @property {Body} bodyA + */ + this.bodyA = bodyA; + /** + * @property {Body} bodyB + */ + this.bodyB = bodyB; +} + +/** + * Set the data for the record + * @method set + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ + OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); +}; + +},{}],54:[function(_dereq_,module,exports){ +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var Pool = _dereq_('./Pool'); + +module.exports = OverlapKeeperRecordPool; + +/** + * @class + */ +function OverlapKeeperRecordPool() { + Pool.apply(this, arguments); +} +OverlapKeeperRecordPool.prototype = new Pool(); +OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool; + +/** + * @method create + * @return {OverlapKeeperRecord} + */ +OverlapKeeperRecordPool.prototype.create = function () { + return new OverlapKeeperRecord(); +}; + +/** + * @method destroy + * @param {OverlapKeeperRecord} record + * @return {OverlapKeeperRecordPool} + */ +OverlapKeeperRecordPool.prototype.destroy = function (record) { + record.bodyA = record.bodyB = record.shapeA = record.shapeB = null; + return this; +}; + +},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){ +module.exports = Pool; + +/** + * @class Object pooling utility. + */ +function Pool(options) { + options = options || {}; + + /** + * @property {Array} objects + * @type {Array} + */ + this.objects = []; + + if(options.size !== undefined){ + this.resize(options.size); + } +} + +/** + * @method resize + * @param {number} size + * @return {Pool} Self, for chaining + */ +Pool.prototype.resize = function (size) { + var objects = this.objects; + + while (objects.length > size) { + objects.pop(); + } + + while (objects.length < size) { + objects.push(this.create()); + } + + return this; +}; + +/** + * Get an object from the pool or create a new instance. + * @method get + * @return {Object} + */ +Pool.prototype.get = function () { + var objects = this.objects; + return objects.length ? objects.pop() : this.create(); +}; + +/** + * Clean up and put the object back into the pool for later use. + * @method release + * @param {Object} object + * @return {Pool} Self for chaining + */ +Pool.prototype.release = function (object) { + this.destroy(object); + this.objects.push(object); + return this; +}; + +},{}],56:[function(_dereq_,module,exports){ +var Utils = _dereq_('./Utils'); + +module.exports = TupleDictionary; + +/** + * @class TupleDictionary + * @constructor + */ +function TupleDictionary() { + + /** + * The data storage + * @property data + * @type {Object} + */ + this.data = {}; + + /** + * Keys that are currently used. + * @property {Array} keys + */ + this.keys = []; +} + +/** + * Generate a key given two integers + * @method getKey + * @param {number} i + * @param {number} j + * @return {string} + */ +TupleDictionary.prototype.getKey = function(id1, id2) { + id1 = id1|0; + id2 = id2|0; + + if ( (id1|0) === (id2|0) ){ + return -1; + } + + // valid for values < 2^16 + return ((id1|0) > (id2|0) ? + (id1 << 16) | (id2 & 0xFFFF) : + (id2 << 16) | (id1 & 0xFFFF))|0 + ; +}; + +/** + * @method getByKey + * @param {Number} key + * @return {Object} + */ +TupleDictionary.prototype.getByKey = function(key) { + key = key|0; + return this.data[key]; +}; + +/** + * @method get + * @param {Number} i + * @param {Number} j + * @return {Number} + */ +TupleDictionary.prototype.get = function(i, j) { + return this.data[this.getKey(i, j)]; +}; + +/** + * Set a value. + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +TupleDictionary.prototype.set = function(i, j, value) { + if(!value){ + throw new Error("No data!"); + } + + var key = this.getKey(i, j); + + // Check if key already exists + if(!this.data[key]){ + this.keys.push(key); + } + + this.data[key] = value; + + return key; +}; + +/** + * Remove all data. + * @method reset + */ +TupleDictionary.prototype.reset = function() { + var data = this.data, + keys = this.keys; + + var l = keys.length; + while(l--) { + delete data[keys[l]]; + } + + keys.length = 0; +}; + +/** + * Copy another TupleDictionary. Note that all data in this dictionary will be removed. + * @method copy + * @param {TupleDictionary} dict The TupleDictionary to copy into this one. + */ +TupleDictionary.prototype.copy = function(dict) { + this.reset(); + Utils.appendArray(this.keys, dict.keys); + var l = dict.keys.length; + while(l--){ + var key = dict.keys[l]; + this.data[key] = dict.data[key]; + } +}; + +},{"./Utils":57}],57:[function(_dereq_,module,exports){ +/* global P2_ARRAY_TYPE */ + +module.exports = Utils; + +/** + * Misc utility functions + * @class Utils + * @constructor + */ +function Utils(){} + +/** + * Append the values in array b to the array a. See this for an explanation. + * @method appendArray + * @static + * @param {Array} a + * @param {Array} b + */ +Utils.appendArray = function(a,b){ + if (b.length < 150000) { + a.push.apply(a, b); + } else { + for (var i = 0, len = b.length; i !== len; ++i) { + a.push(b[i]); + } + } +}; + +/** + * Garbage free Array.splice(). Does not allocate a new array. + * @method splice + * @static + * @param {Array} array + * @param {Number} index + * @param {Number} howmany + */ +Utils.splice = function(array,index,howmany){ + howmany = howmany || 1; + for (var i=index, len=array.length-howmany; i < len; i++){ + array[i] = array[i + howmany]; + } + array.length = len; +}; + +/** + * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. + * @static + * @property {function} ARRAY_TYPE + * @example + * + * + */ +if(typeof P2_ARRAY_TYPE !== 'undefined') { + Utils.ARRAY_TYPE = P2_ARRAY_TYPE; +} else if (typeof Float32Array !== 'undefined'){ + Utils.ARRAY_TYPE = Float32Array; +} else { + Utils.ARRAY_TYPE = Array; +} + +/** + * Extend an object with the properties of another + * @static + * @method extend + * @param {object} a + * @param {object} b + */ +Utils.extend = function(a,b){ + for(var key in b){ + a[key] = b[key]; + } +}; + +/** + * Extend an options object with default values. + * @static + * @method defaults + * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. + * @param {object} defaults An object containing default values. + * @return {object} The modified options object. + */ +Utils.defaults = function(options, defaults){ + options = options || {}; + for(var key in defaults){ + if(!(key in options)){ + options[key] = defaults[key]; + } + } + return options; +}; + +},{}],58:[function(_dereq_,module,exports){ +var Body = _dereq_('../objects/Body'); + +module.exports = Island; + +/** + * An island of bodies connected with equations. + * @class Island + * @constructor + */ +function Island(){ + + /** + * Current equations in this island. + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Current bodies in this island. + * @property bodies + * @type {Array} + */ + this.bodies = []; +} + +/** + * Clean this island from bodies and equations. + * @method reset + */ +Island.prototype.reset = function(){ + this.equations.length = this.bodies.length = 0; +}; + +var bodyIds = []; + +/** + * Get all unique bodies in this island. + * @method getBodies + * @return {Array} An array of Body + */ +Island.prototype.getBodies = function(result){ + var bodies = result || [], + eqs = this.equations; + bodyIds.length = 0; + for(var i=0; i!==eqs.length; i++){ + var eq = eqs[i]; + if(bodyIds.indexOf(eq.bodyA.id)===-1){ + bodies.push(eq.bodyA); + bodyIds.push(eq.bodyA.id); + } + if(bodyIds.indexOf(eq.bodyB.id)===-1){ + bodies.push(eq.bodyB); + bodyIds.push(eq.bodyB.id); + } + } + return bodies; +}; + +/** + * Check if the entire island wants to sleep. + * @method wantsToSleep + * @return {Boolean} + */ +Island.prototype.wantsToSleep = function(){ + for(var i=0; i= dt && substeps < maxSubSteps) { + // Do fixed steps to catch up + this.internalStep(dt); + this.time += dt; + this.accumulator -= dt; + substeps++; + } + + var t = (this.accumulator % dt) / dt; + for(var j=0; j!==this.bodies.length; j++){ + var b = this.bodies[j]; + vec2.lerp(b.interpolatedPosition, b.previousPosition, b.position, t); + b.interpolatedAngle = b.previousAngle + t * (b.angle - b.previousAngle); + } + } +}; + +var endOverlaps = []; + +/** + * Make a fixed step. + * @method internalStep + * @param {number} dt + * @private + */ +World.prototype.internalStep = function(dt){ + this.stepping = true; + + var that = this, + Nsprings = this.springs.length, + springs = this.springs, + bodies = this.bodies, + g = this.gravity, + solver = this.solver, + Nbodies = this.bodies.length, + broadphase = this.broadphase, + np = this.narrowphase, + constraints = this.constraints, + t0, t1, + fhMinv = step_fhMinv, + velodt = step_velodt, + mg = step_mg, + scale = vec2.scale, + add = vec2.add, + rotate = vec2.rotate, + islandManager = this.islandManager; + + this.overlapKeeper.tick(); + + this.lastTimeStep = dt; + + // Update approximate friction gravity. + if(this.useWorldGravityAsFrictionGravity){ + var gravityLen = vec2.length(this.gravity); + if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){ + // Nonzero gravity. Use it. + this.frictionGravity = gravityLen; + } + } + + // Add gravity to bodies + if(this.applyGravity){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i], + fi = b.force; + if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ + continue; + } + vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g + add(fi,fi,mg); + } + } + + // Add spring forces + if(this.applySpringForces){ + for(var i=0; i!==Nsprings; i++){ + var s = springs[i]; + s.applyForce(); + } + } + + if(this.applyDamping){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + if(b.type === Body.DYNAMIC){ + b.applyDamping(dt); + } + } + } + + // Broadphase + var result = broadphase.getCollisionPairs(this); + + // Remove ignored collision pairs + var ignoredPairs = this.disabledBodyCollisionPairs; + for(var i=ignoredPairs.length-2; 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); + } + } + } + + // Remove constrained pairs with collideConnected == false + 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); + } + } + } + } + + // postBroadphase event + this.postBroadphaseEvent.pairs = result; + this.emit(this.postBroadphaseEvent); + this.postBroadphaseEvent.pairs = null; + + // Narrowphase + np.reset(this); + for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ + var bi = result[i], + bj = result[i+1]; + + // Loop over all shapes of body i + for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ + var si = bi.shapes[k], + xi = si.position, + ai = si.angle; + + // All shapes of body j + for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ + var sj = bj.shapes[l], + xj = sj.position, + aj = sj.angle; + + 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); + } + } + } + + // Wake up bodies + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + if(body._wakeUpAfterNarrowphase){ + body.wakeUp(); + body._wakeUpAfterNarrowphase = false; + } + } + + // Emit end overlap events + 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.bodyB; + this.emit(e); + } + endOverlaps.length = 0; + } + + var preSolveEvent = this.preSolveEvent; + preSolveEvent.contactEquations = np.contactEquations; + preSolveEvent.frictionEquations = np.frictionEquations; + this.emit(preSolveEvent); + preSolveEvent.contactEquations = preSolveEvent.frictionEquations = null; + + // update constraint equations + var Nconstraints = constraints.length; + for(i=0; i!==Nconstraints; i++){ + constraints[i].update(); + } + + if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){ + if(this.islandSplit){ + // Split into islands + 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 { + + // Add contact equations to solver + solver.addEquations(np.contactEquations); + solver.addEquations(np.frictionEquations); + + // Add user-defined constraint equations + for(i=0; i!==Nconstraints; i++){ + solver.addEquations(constraints[i].equations); + } + + if(this.solveConstraints){ + solver.solve(dt,this); + } + + solver.removeAllEquations(); + } + } + + // Step forward + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + + // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){ + body.integrate(dt); + // } + } + + // Reset force + for(var i=0; i!==Nbodies; i++){ + bodies[i].setZeroForce(); + } + + // Emit impact event + 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); + } + } + } + + // Sleeping update + if(this.sleepMode === World.BODY_SLEEPING){ + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, false, dt); + } + } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){ + + // Tell all bodies to sleep tick but dont sleep yet + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, true, dt); + } + + // Sleep islands + for(var i=0; i 0; + np.frictionCoefficient = cm.friction; + var reducedMass; + if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){ + reducedMass = bj.mass; + } else if(bj.type === Body.STATIC || bj.type === 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; + np.contactSkinSize = cm.contactSkinSize; + np.enabledEquations = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse; + + 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 < sj.type) { + numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); + } else { + numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); + } + var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; + + if(numContacts){ + + if( bi.allowSleep && + bi.type === Body.DYNAMIC && + bi.sleepState === Body.SLEEPING && + bj.sleepState === Body.AWAKE && + bj.type !== Body.STATIC + ){ + var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); + var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); + if(speedSquaredB >= speedLimitSquaredB*2){ + bi._wakeUpAfterNarrowphase = true; + } + } + + if( bj.allowSleep && + bj.type === Body.DYNAMIC && + bj.sleepState === Body.SLEEPING && + bi.sleepState === Body.AWAKE && + bi.type !== 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)){ + + // Report new shape overlap + var e = this.beginContactEvent; + e.shapeA = si; + e.shapeB = sj; + e.bodyA = bi; + e.bodyB = bj; + + // Reset contact equations + e.contactEquations.length = 0; + + if(typeof(numContacts)==="number"){ + for(var i=np.contactEquations.length-numContacts; i 1){ // Why divide by 1? + for(var i=np.frictionEquations.length-numFrictionEquations; i=0; i--){ + this.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.bodies; + for(var i=bodies.length-1; i>=0; i--){ + this.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.springs; + for(var i=springs.length-1; i>=0; i--){ + this.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.contactMaterials; + for(var i=cms.length-1; i>=0; i--){ + this.removeContactMaterial(cms[i]); + } + + World.apply(this); +}; + +var hitTest_tmp1 = vec2.create(), + hitTest_zero = vec2.fromValues(0,0), + hitTest_tmp2 = vec2.fromValues(0,0); + +/** + * Test if a world point overlaps bodies + * @method hitTest + * @param {Array} worldPoint Point to use for intersection tests + * @param {Array} bodies A list of objects to check for intersection + * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @return {Array} Array of bodies that overlap the point + * @todo Should use an api similar to the raycast function + * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient + * @todo Should use the broadphase + */ +World.prototype.hitTest = function(worldPoint,bodies,precision){ + precision = precision || 0; + + // Create a dummy particle body with a particle shape to test against the bodies + 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 = []; + + // Check bodies + 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]; + + // Get shape world position + angle + vec2.rotate(x, s.position, b.angle); + vec2.add(x, x, b.position); + var a = s.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)) < precision*precision) + ){ + result.push(b); + } + } + } + + return result; +}; + +/** + * Set the stiffness for all equations and contact materials. + * @method setGlobalStiffness + * @param {Number} stiffness + */ +World.prototype.setGlobalStiffness = function(stiffness){ + + // Set for all constraints + var constraints = this.constraints; + for(var i=0; i !== constraints.length; i++){ + var c = constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.stiffness = stiffness; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + var contactMaterials = this.contactMaterials; + for(var i=0; i !== contactMaterials.length; i++){ + var c = contactMaterials[i]; + c.stiffness = c.frictionStiffness = stiffness; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.stiffness = c.frictionStiffness = stiffness; +}; + +/** + * Set the relaxation for all equations and contact materials. + * @method setGlobalRelaxation + * @param {Number} relaxation + */ +World.prototype.setGlobalRelaxation = function(relaxation){ + + // Set for all constraints + for(var i=0; i !== this.constraints.length; i++){ + var c = this.constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.relaxation = relaxation; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + for(var i=0; i !== this.contactMaterials.length; i++){ + var c = this.contactMaterials[i]; + c.relaxation = c.frictionRelaxation = relaxation; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.relaxation = c.frictionRelaxation = relaxation; +}; + +var tmpAABB = new AABB(); +var tmpArray = []; + +/** + * Ray cast against all bodies in the world. + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @return {boolean} True if any body was hit. + * + * @example + * var ray = new Ray({ + * mode: Ray.CLOSEST, // or ANY + * from: [0, 0], + * to: [10, 0], + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * @example + * var ray = new Ray({ + * mode: Ray.ALL, + * from: [0, 0], + * to: [10, 0], + * callback: function(result){ + * + * // Print some info about the hit + * console.log('Hit body and shape: ', result.body, result.shape); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * // If you are happy with the hits you got this far, you can stop the traversal here: + * result.stop(); + * } + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + */ +World.prototype.raycast = function(result, ray){ + + // Get all bodies within the ray AABB + ray.getAABB(tmpAABB); + this.broadphase.aabbQuery(this, tmpAABB, tmpArray); + ray.intersectBodies(result, tmpArray); + tmpArray.length = 0; + + return result.hasHit(); +}; + +},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36]) +(36) +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +(function(){ + + var root = this; + +/** + * Namespace-class for [pixi.js](http://www.pixijs.com/). + * + * Contains assorted static properties and enumerations. + * + * @namespace PIXI + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ +var PIXI = PIXI || {}; + +/** +* @author Mat Groves http://matgroves.com @Doormat23 +* @author Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The base class for all objects that are rendered. Contains properties for position, scaling, +* rotation, masks and cache handling. +* +* This is an abstract class and should not be used on its own, rather it should be extended. +* +* It is used internally by the likes of PIXI.Sprite. +* +* @class PIXI.DisplayObject +* @constructor +*/ +PIXI.DisplayObject = function () { + + /** + * The coordinates, in pixels, of this DisplayObject, relative to its parent container. + * + * The value of this property does not reflect any positioning happening further up the display list. + * To obtain that value please see the `worldPosition` property. + * + * @property {PIXI.Point} position + * @default + */ + this.position = new PIXI.Point(0, 0); + + /** + * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject + * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on. + * + * The value of this property does not reflect any scaling happening further up the display list. + * To obtain that value please see the `worldScale` property. + * + * @property {PIXI.Point} scale + * @default + */ + this.scale = new PIXI.Point(1, 1); + + /** + * The pivot point of this DisplayObject that it rotates around. The values are expressed + * in pixel values. + * @property {PIXI.Point} pivot + * @default + */ + this.pivot = new PIXI.Point(0, 0); + + /** + * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on + * a right-handed orientation. + * + * The value of this property does not reflect any rotation happening further up the display list. + * To obtain that value please see the `worldRotation` property. + * + * @property {number} rotation + * @default + */ + this.rotation = 0; + + /** + * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * Please note that an object with an alpha value of 0 is skipped during the render pass. + * + * The value of this property does not reflect any alpha values set further up the display list. + * To obtain that value please see the `worldAlpha` property. + * + * @property {number} alpha + * @default + */ + this.alpha = 1; + + /** + * The visibility of this DisplayObject. A value of `false` makes the object invisible. + * A value of `true` makes it visible. Please note that an object with a visible value of + * `false` is skipped during the render pass. Equally a DisplayObject with visible false will + * not render any of its children. + * + * The value of this property does not reflect any visible values set further up the display list. + * To obtain that value please see the `worldVisible` property. + * + * @property {boolean} visible + * @default + */ + this.visible = true; + + /** + * This is the defined area that will pick up mouse / touch events. It is null by default. + * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children) + * + * @property hitArea + * @type Rectangle|Circle|Ellipse|Polygon + */ + this.hitArea = null; + + /** + * Should this DisplayObject be rendered by the renderer? An object with a renderable value of + * `false` is skipped during the render pass. + * + * @property {boolean} renderable + * @default + */ + this.renderable = false; + + /** + * The parent DisplayObjectContainer that this DisplayObject is a child of. + * All DisplayObjects must belong to a parent in order to be rendered. + * The root parent is the Stage object. This property is set automatically when the + * DisplayObject is added to, or removed from, a DisplayObjectContainer. + * + * @property {PIXI.DisplayObjectContainer} parent + * @default + * @readOnly + */ + this.parent = null; + + /** + * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects + * in the display list. + * + * To obtain, and set, the local alpha value, see the `alpha` property. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldAlpha + * @readOnly + */ + this.worldAlpha = 1; + + /** + * The current transform of this DisplayObject. + * + * This property contains the calculated total, based on the transforms of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {Phaser.Matrix} worldTransform + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * The coordinates, in pixels, of this DisplayObject within the world. + * + * This property contains the calculated total, based on the positions of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldPosition + * @readOnly + */ + this.worldPosition = new PIXI.Point(0, 0); + + /** + * The global scale of this DisplayObject. + * + * This property contains the calculated total, based on the scales of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldScale + * @readOnly + */ + this.worldScale = new PIXI.Point(1, 1); + + /** + * The rotation, in radians, of this DisplayObject. + * + * This property contains the calculated total, based on the rotations of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldRotation + * @readOnly + */ + this.worldRotation = 0; + + /** + * The rectangular area used by filters when rendering a shader for this DisplayObject. + * + * @property {PIXI.Rectangle} filterArea + * @type Rectangle + * @default + */ + this.filterArea = null; + + /** + * @property {number} _sr - Cached rotation value. + * @private + */ + this._sr = 0; + + /** + * @property {number} _cr - Cached rotation value. + * @private + */ + this._cr = 1; + + /** + * @property {PIXI.Rectangle} _bounds - The cached bounds of this object. + * @private + */ + this._bounds = new PIXI.Rectangle(0, 0, 0, 0); + + /** + * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object. + * @private + */ + this._currentBounds = null; + + /** + * @property {PIXI.Rectangle} _mask - The cached mask of this object. + * @private + */ + this._mask = null; + + /** + * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag. + * @private + */ + this._cacheAsBitmap = false; + + /** + * @property {boolean} _cacheIsDirty - Internal dirty cache flag. + * @private + */ + this._cacheIsDirty = false; + +}; + +PIXI.DisplayObject.prototype = { + + constructor: PIXI.DisplayObject, + + /** + * Destroy this DisplayObject. + * + * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask. + * + * Also iteratively calls `destroy` on any children. + * + * @method PIXI.DisplayObject#destroy + */ + destroy: function () { + + if (this.children) + { + var i = this.children.length; + + while (i--) + { + this.children[i].destroy(); + } + + this.children = []; + } + + this.hitArea = null; + this.parent = null; + this.worldTransform = null; + this.filterArea = null; + this.renderable = false; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + }, + + /** + * Updates the transform matrix this DisplayObject uses for rendering. + * + * If the object has no parent, and no parent parameter is provided, it will default to + * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place. + * + * The `parent` parameter has priority over the actual parent. Use it as a parent override. + * Setting it does **not** change the actual parent of this DisplayObject. + * + * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale` + * and `worldRotation` properties. + * + * If a `transformCallback` has been specified, it is called at the end of this method, and is passed + * the new, updated, worldTransform property, along with the parent transform used. + * + * @method PIXI.DisplayObject#updateTransform + * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from. + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateTransform: function (parent) { + + if (!parent && !this.parent && !this.game) + { + return this; + } + + var p = this.parent; + + if (parent) + { + p = parent; + } + else if (!this.parent) + { + p = this.game.world; + } + + // create some matrix refs for easy access + var pt = p.worldTransform; + var wt = this.worldTransform; + + // temporary matrix variables + var a, b, c, d, tx, ty; + + // so if rotation is between 0 then we can simplify the multiplication process.. + if (this.rotation % Phaser.Math.PI2) + { + // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes + if (this.rotation !== this.rotationCache) + { + this.rotationCache = this.rotation; + this._sr = Math.sin(this.rotation); + this._cr = Math.cos(this.rotation); + } + + // get the matrix values of the displayobject based on its transform properties.. + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + tx = this.position.x; + ty = this.position.y; + + // check for pivot.. not often used so geared towards that fact! + if (this.pivot.x || this.pivot.y) + { + tx -= this.pivot.x * a + this.pivot.y * c; + ty -= this.pivot.x * b + this.pivot.y * d; + } + + // concat the parent matrix with the objects transform. + wt.a = a * pt.a + b * pt.c; + wt.b = a * pt.b + b * pt.d; + wt.c = c * pt.a + d * pt.c; + wt.d = c * pt.b + d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + else + { + // lets do the fast version as we know there is no rotation.. + a = this.scale.x; + b = 0; + c = 0; + d = this.scale.y; + tx = this.position.x - this.pivot.x * a; + ty = this.position.y - this.pivot.y * d; + + wt.a = a * pt.a; + wt.b = a * pt.b; + wt.c = d * pt.c; + wt.d = d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + + a = wt.a; + b = wt.b; + c = wt.c; + d = wt.d; + + var determ = (a * d) - (b * c); + + if (a || b) + { + var r = Math.sqrt((a * a) + (b * b)); + + this.worldRotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); + this.worldScale.x = r; + this.worldScale.y = determ / r; + } + else if (c || d) + { + var s = Math.sqrt((c * c) + (d * d)); + + this.worldRotation = Phaser.Math.HALF_PI - ((d > 0) ? Math.acos(-c / s) : -Math.acos(c / s)); + this.worldScale.x = determ / s; + this.worldScale.y = s; + } + else + { + this.worldScale.x = 0; + this.worldScale.y = 0; + } + + // Set the World values + this.worldAlpha = this.alpha * p.worldAlpha; + this.worldPosition.x = wt.tx; + this.worldPosition.y = wt.ty; + + // reset the bounds each time this is called! + this._currentBounds = null; + + // Custom callback? + if (this.transformCallback) + { + this.transformCallback.call(this.transformCallbackContext, wt, pt); + } + + return this; + + }, + + /** + * To be overridden by classes that require it. + * + * @method PIXI.DisplayObject#preUpdate + */ + preUpdate: function () { + + }, + + /** + * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites. + * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times. + * + * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures, + * and references to them, so they don't linger in memory. + * + * @method PIXI.DisplayObject#generateTexture + * @param {number} [resolution=1] - The resolution of the texture being generated. + * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values. + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture. + * @return {Phaser.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked. + */ + generateTexture: function (resolution, scaleMode, renderer) { + + var bounds = this.getLocalBounds(); + + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + + renderTexture.render(this, PIXI.DisplayObject._tempMatrix); + + return renderTexture; + + }, + + /** + * If this DisplayObject has a cached Sprite, this method generates and updates it. + * + * @method PIXI.DisplayObject#updateCache + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateCache: function () { + + this._generateCachedSprite(); + + return this; + + }, + + /** + * Calculates the global position of this DisplayObject, based on the position given. + * + * @method PIXI.DisplayObject#toGlobal + * @param {PIXI.Point} position - The global position to calculate from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toGlobal: function (position) { + + this.updateTransform(); + + return this.worldTransform.apply(position); + + }, + + /** + * Calculates the local position of this DisplayObject, relative to another point. + * + * @method PIXI.DisplayObject#toLocal + * @param {PIXI.Point} position - The world origin to calculate from. + * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toLocal: function (position, from) { + + if (from) + { + position = from.toGlobal(position); + } + + this.updateTransform(); + + return this.worldTransform.applyInverse(position); + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_renderCachedSprite + * @private + * @param {Object} renderSession - The render session + */ + _renderCachedSprite: function (renderSession) { + + this._cachedSprite.worldAlpha = this.worldAlpha; + + if (renderSession.gl) + { + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + } + else + { + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + } + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_generateCachedSprite + * @private + */ + _generateCachedSprite: function () { + + this._cacheAsBitmap = false; + + var bounds = this.getLocalBounds(); + + // Round it off and force non-zero dimensions + bounds.width = Math.max(1, Math.ceil(bounds.width)); + bounds.height = Math.max(1, Math.ceil(bounds.height)); + + this.updateTransform(); + + if (!this._cachedSprite) + { + var textureUnit = 0; + if (this.texture && this.texture.baseTexture && PIXI._enableMultiTextureToggle) + { + textureUnit = this.texture.baseTexture.textureIndex; + } + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width, bounds.height, undefined, undefined, undefined, undefined, textureUnit); + this._cachedSprite = new PIXI.Sprite(renderTexture); + this._cachedSprite.worldTransform = this.worldTransform; + } + else + { + this._cachedSprite.texture.resize(bounds.width, bounds.height); + } + + // Remove filters + var tempFilters = this._filters; + + this._filters = null; + this._cachedSprite.filters = tempFilters; + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true); + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + this._filters = tempFilters; + + this._cacheAsBitmap = true; + + }, + + /** + * Destroys a cached Sprite. + * + * @method PIXI.DisplayObject#_destroyCachedSprite + * @private + */ + _destroyCachedSprite: function () { + + if (!this._cachedSprite) + { + return; + } + + this._cachedSprite.texture.destroy(true); + + this._cachedSprite = null; + + } + +}; + +// Alias for updateTransform. As used in DisplayObject container, etc. +PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform; + +Object.defineProperties(PIXI.DisplayObject.prototype, { + + /** + * The horizontal position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#x + * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent. + */ + 'x': { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + } + + }, + + /** + * The vertical position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#y + * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent. + */ + 'y': { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + + }, + + /** + * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + * @name PIXI.DisplayObject#worldVisible + * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + */ + 'worldVisible': { + + get: function () { + + if (!this.visible) + { + return false; + } + else + { + var item = this.parent; + + if (!item) + { + return this.visible; + } + else + { + do + { + if (!item.visible) + { + return false; + } + + item = item.parent; + } + while (item); + + } + + return true; + } + + } + + }, + + /** + * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object. + * When applied it limits the visible area of this DisplayObject to the shape of the mask. + * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer. + * To remove a mask, set this property to `null`. + * + * @name PIXI.DisplayObject#mask + * @property {Phaser.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask. + */ + 'mask': { + + get: function () { + + return this._mask; + + }, + + set: function (value) { + + if (this._mask) + { + this._mask.isMask = false; + } + + this._mask = value; + + if (value) + { + this._mask.isMask = true; + } + + } + + }, + + /** + * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas + * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter + * using `DisplayObject.filterArea`. + * + * To remove filters, set this property to `null`. + * + * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a + * filter will reset this DisplayObjects blend mode to NORMAL. + * + * @name PIXI.DisplayObject#filters + * @property {Array} filters - An Array of Phaser.Filter objects, or objects that extend them. + */ + 'filters': { + + get: function () { + + return this._filters; + + }, + + set: function (value) { + + if (Array.isArray(value)) + { + // Put all the passes in one place. + var passes = []; + + for (var i = 0; i < value.length; i++) + { + var filterPasses = value[i].passes; + + for (var j = 0; j < filterPasses.length; j++) + { + passes.push(filterPasses[j]); + } + } + + // Needed any more? + this._filterBlock = { target: this, filterPasses: passes }; + } + + this._filters = value; + + if (this.blendMode && this.blendMode === PIXI.blendModes.MULTIPLY) + { + this.blendMode = PIXI.blendModes.NORMAL; + } + + } + + }, + + /** + * Sets if this DisplayObject should be cached as a bitmap. + * + * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it + * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a + * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not + * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`. + * + * To remove a cached bitmap, set this property to `null`. + * + * @name PIXI.DisplayObject#cacheAsBitmap + * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap. + */ + 'cacheAsBitmap': { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + if (this._cacheAsBitmap === value) + { + return; + } + + if (value) + { + this._generateCachedSprite(); + } + else + { + this._destroyCachedSprite(); + } + + this._cacheAsBitmap = value; + + } + + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A DisplayObjectContainer represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + * @class PIXI.DisplayObjectContainer + * @extends PIXI.DisplayObject + * @constructor + */ +PIXI.DisplayObjectContainer = function () { + + PIXI.DisplayObject.call(this); + + /** + * [read-only] The array of children of this container. + * + * @property children + * @type Array(DisplayObject) + * @readOnly + */ + this.children = []; + + /** + * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events. + * + * If this property is `true` then the children will _not_ be considered as valid for Input events. + * + * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. + * @property {boolean} ignoreChildInput + * @default + */ + this.ignoreChildInput = false; + +}; + +PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); +PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; + +/** + * Adds a child to the container. + * + * @method PIXI.DisplayObjectContainer#addChild + * @param child {DisplayObject} The DisplayObject to add to the container + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChild = function (child) { + + return this.addChildAt(child, this.children.length); + +}; + +/** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @method PIXI.DisplayObjectContainer#addChildAt + * @param child {DisplayObject} The child to add + * @param index {Number} The index to place the child in + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) { + + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + return child; + } + else + { + throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); + } + +}; + +/** + * Swaps the position of 2 Display Objects within this container. + * + * @method PIXI.DisplayObjectContainer#swapChildren + * @param child {DisplayObject} + * @param child2 {DisplayObject} + */ +PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) { + + if (child === child2) + { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(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; + +}; + +/** + * Returns the index position of a child DisplayObject instance + * + * @method PIXI.DisplayObjectContainer#getChildIndex + * @param child {DisplayObject} The DisplayObject instance to identify + * @return {Number} The index position of the child display object to identify + */ +PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + +}; + +/** + * Changes the position of an existing child in the display object container + * + * @method PIXI.DisplayObjectContainer#setChildIndex + * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number + * @param index {Number} The resulting index number for the child display object + */ +PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + this.children.splice(currentIndex, 1); //remove from old position + this.children.splice(index, 0, child); //add at new position + +}; + +/** + * Returns the child at the specified index + * + * @method PIXI.DisplayObjectContainer#getChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child at the given index, if any. + */ +PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller'); + } + + return this.children[index]; + +}; + +/** + * Removes a child from the container. + * + * @method PIXI.DisplayObjectContainer#removeChild + * @param child {DisplayObject} The DisplayObject to remove + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChild = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + return; + } + + return this.removeChildAt(index); + +}; + +/** + * Removes a child from the specified index position. + * + * @method PIXI.DisplayObjectContainer#removeChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) { + + var child = this.getChildAt(index); + + if (child) + { + child.parent = undefined; + + this.children.splice(index, 1); + } + + return child; + +}; + +/** +* Removes all children from this container that are within the begin and end indexes. +* +* @method PIXI.DisplayObjectContainer#removeChildren +* @param beginIndex {Number} The beginning position. Default value is 0. +* @param endIndex {Number} The ending position. Default value is size of the container. +*/ +PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { + + if (beginIndex === undefined) { beginIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var range = endIndex - beginIndex; + + if (range > 0 && range <= endIndex) + { + var removed = this.children.splice(beginIndex, range); + + for (var i = 0; i < removed.length; i++) + { + var child = removed[i]; + child.parent = undefined; + } + + return removed; + } + else if (range === 0 && this.children.length === 0) + { + return []; + } + else + { + throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' ); + } + +}; + +/* + * Updates the transform on all children of this container for rendering + * + * @method PIXI.DisplayObjectContainer#updateTransform + * @private + */ +PIXI.DisplayObjectContainer.prototype.updateTransform = function () { + + if (!this.visible) + { + return; + } + + this.displayObjectUpdateTransform(); + + if (this._cacheAsBitmap) + { + return; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +// performance increase to avoid using call.. (10x faster) +PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform; + +/** + * Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getBounds + * @param {PIXI.DisplayObject|Phaser.Matrix} [targetCoordinateSpace] Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpace) { + + var isTargetCoordinateSpaceDisplayObject = (targetCoordinateSpace && targetCoordinateSpace instanceof PIXI.DisplayObject); + var isTargetCoordinateSpaceThisOrParent = true; + + if (!isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace = this; + } + else if (targetCoordinateSpace instanceof PIXI.DisplayObjectContainer) + { + isTargetCoordinateSpaceThisOrParent = targetCoordinateSpace.contains(this); + } + else + { + isTargetCoordinateSpaceThisOrParent = false; + } + + var i; + + if (isTargetCoordinateSpaceDisplayObject) + { + var matrixCache = targetCoordinateSpace.worldTransform; + + targetCoordinateSpace.worldTransform = Phaser.identityMatrix; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + var minX = Infinity; + var minY = Infinity; + + var maxX = -Infinity; + var maxY = -Infinity; + + var childBounds; + var childMaxX; + var childMaxY; + + var childVisible = false; + + for (i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + childVisible = true; + + childBounds = this.children[i].getBounds(); + + minX = (minX < childBounds.x) ? minX : childBounds.x; + minY = (minY < childBounds.y) ? minY : childBounds.y; + + childMaxX = childBounds.width + childBounds.x; + childMaxY = childBounds.height + childBounds.y; + + maxX = (maxX > childMaxX) ? maxX : childMaxX; + maxY = (maxY > childMaxY) ? maxY : childMaxY; + } + + var bounds = this._bounds; + + if (!childVisible) + { + bounds = new PIXI.Rectangle(); + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + maxX = x1; + maxY = y1; + + minX = x1; + minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + } + + bounds.x = minX; + bounds.y = minY; + bounds.width = maxX - minX; + bounds.height = maxY - minY; + + if (isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace.worldTransform = matrixCache; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + if (!isTargetCoordinateSpaceThisOrParent) + { + var targetCoordinateSpaceBounds = targetCoordinateSpace.getBounds(); + + bounds.x -= targetCoordinateSpaceBounds.x; + bounds.y -= targetCoordinateSpaceBounds.y; + } + + return bounds; + +}; + +/** + * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getLocalBounds = function () { + + return this.getBounds(this); + +}; + +/** +* Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. +* +* @method PIXI.DisplayObjectContainer#contains +* @param {DisplayObject} child +* @returns {boolean} +*/ +PIXI.DisplayObjectContainer.prototype.contains = function (child) { + + if (!child) + { + return false; + } + else if (child === this) + { + return true; + } + else + { + return this.contains(child.parent); + } +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.DisplayObjectContainer#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + var i; + + if (this._mask || this._filters) + { + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + renderSession.spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + renderSession.spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + renderSession.spriteBatch.start(); + } + + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + renderSession.spriteBatch.start(); + } + else + { + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.DisplayObjectContainer#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) { + + if (this.visible === false || this.alpha === 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', { + + get: function() { + return this.getLocalBounds().width * this.scale.x; + }, + + set: function(value) { + + var width = this.getLocalBounds().width; + + if (width !== 0) + { + this.scale.x = value / width; + } + else + { + this.scale.x = 1; + } + + this._width = value; + } +}); + +/** + * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', { + + get: function() { + return this.getLocalBounds().height * this.scale.y; + }, + + set: function(value) { + + var height = this.getLocalBounds().height; + + if (height !== 0) + { + this.scale.y = value / height; + } + else + { + this.scale.y = 1; + } + + this._height = value; + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * @class PIXI.Sprite + * @extends PIXI.DisplayObjectContainer + * @constructor + * @param texture {Texture} The texture for this sprite + */ +PIXI.Sprite = function (texture) { + + PIXI.DisplayObjectContainer.call(this); + + /** + * The anchor sets the origin point of the texture. + * The default (0, 0) is the top left. + * (0.5, 0.5) is the center. + * (1, 1) is the bottom right. + * + * You can modify the default values in PIXI.Sprite.defaultAnchor. + * + * @property anchor + * @type Point + */ + this.anchor = new PIXI.Point(PIXI.Sprite.defaultAnchor.x, PIXI.Sprite.defaultAnchor.y); + + /** + * The texture that the sprite is using + * + * @property texture + * @type Texture + */ + this.texture = texture || PIXI.Texture.emptyTexture; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @property _width + * @type Number + * @private + */ + this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @property _height + * @type Number + * @private + */ + this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF (Phaser.Color.WHITE) will remove any tint effect. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @property cachedTint + * @private + * @type Number + * @default -1 + */ + this.cachedTint = -1; + + /** + * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) + * + * @property tintedTexture + * @type Canvas + * @default null + */ + this.tintedTexture = null; + + /** + * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. + * + * Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * The shader that will be used to render this Sprite. + * Set to null to remove a current shader. + * + * @property shader + * @type Phaser.Filter + * @default null + */ + this.shader = null; + + /** + * Controls if this Sprite is processed by the core Phaser game loops and Group loops (except {@link Phaser.Group#update}). + * + * @property exists + * @type Boolean + * @default true + */ + this.exists = true; + + if (this.texture.baseTexture.hasLoaded) + { + this.onTextureUpdate(); + } + + this.renderable = true; + +}; + +/** + * @property PIXI.Sprite.defaultAnchor - A Point-like object. + * @type {{x: number, y: number}} + * @default + */ +PIXI.Sprite.defaultAnchor = {x: 0, y: 0}; + +// constructor +PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +PIXI.Sprite.prototype.constructor = PIXI.Sprite; + +/** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'width', { + + get: function() { + return this.scale.x * this.texture.frame.width; + }, + + set: function(value) { + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'height', { + + get: function() { + return this.scale.y * this.texture.frame.height; + }, + + set: function(value) { + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +/** + * Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous + * texture this Sprite was using. + * + * @method PIXI.Sprite#setTexture + * @param texture {Texture} The PIXI texture that is displayed by the sprite + * @param [destroy=false] {boolean} Call Texture.destroy on the current texture before replacing it with the new one? + */ +PIXI.Sprite.prototype.setTexture = function(texture, destroyBase) +{ + if (destroyBase) + { + this.texture.baseTexture.destroy(); + } + + // Over-ridden by loadTexture as needed + this.texture.baseTexture.skipRender = false; + this.texture = texture; + this.texture.valid = true; + this.cachedTint = -1; +}; + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @method PIXI.Sprite#onTextureUpdate + * @param event + * @private + */ +PIXI.Sprite.prototype.onTextureUpdate = function() +{ + // so if _width is 0 then width was not set.. + if (this._width) this.scale.x = this._width / this.texture.frame.width; + if (this._height) this.scale.y = this._height / this.texture.frame.height; +}; + +/** +* Returns the bounds of the Sprite as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* It is important to note that the transform is not updated when you call this method. +* So if this Sprite is the child of a Display Object which has had its transform +* updated since the last render pass, those changes will not yet have been applied +* to this Sprites worldTransform. If you need to ensure that all parent transforms +* are factored into this getBounds operation then you should call `updateTransform` +* on the root most object in this Sprites display list first. +* +* @method PIXI.Sprite#getBounds +* @param matrix {Matrix} the transformation matrix of the sprite +* @return {Rectangle} the framing rectangle +*/ +PIXI.Sprite.prototype.getBounds = function(matrix) +{ + var width = this.texture.frame.width; + var height = this.texture.frame.height; + + var w0 = width * (1-this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1-this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + if (b === 0 && c === 0) + { + // scale may be negative! + if (a < 0) + { + a *= -1; + var temp = w0; + w0 = -w1; + w1 = -temp; + } + + if (d < 0) + { + d *= -1; + var temp = h0; + h0 = -h1; + h1 = -temp; + } + + // this means there is no rotation going on right? RIGHT? + // if thats the case then we can avoid checking the bound values! yay + minX = a * w1 + tx; + maxX = a * w0 + tx; + minY = d * h1 + ty; + maxY = d * h0 + ty; + } + else + { + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; +}; + +/** + * Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. + * + * @method PIXI.Sprite#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.Sprite.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.Sprite#_renderWebGL +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix) +{ + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha <= 0 || !this.renderable) return; + + // They provided an alternative rendering matrix, so use it + var wt = this.worldTransform; + + if (matrix) + { + wt = matrix; + } + + // A quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) + { + var spriteBatch = renderSession.spriteBatch; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + spriteBatch.start(); + } + + // add this sprite to the batch + spriteBatch.render(this); + + // now loop through the children and make sure they get rendered + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + // time to stop the sprite batch as either a mask element or a filter draw will happen next + spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + spriteBatch.start(); + } + else + { + renderSession.spriteBatch.render(this); + + // Render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession, wt); + } + + } +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.Sprite#_renderCanvas +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix) +{ + // If the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha === 0 || !this.renderable || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { + return; + } + + var wt = this.worldTransform; + + // If they provided an alternative rendering matrix then use it + if (matrix) + { + wt = matrix; + } + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + // Ignore null sources + if (!this.texture.valid) + { + // Update the children and leave + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + return; + } + + var resolution = this.texture.baseTexture.resolution / renderSession.resolution; + + renderSession.context.globalAlpha = this.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for this texture + if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode) + { + renderSession.scaleMode = this.texture.baseTexture.scaleMode; + renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + + // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions + var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width; + var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height; + + var tx = (wt.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (wt.ty * renderSession.resolution) + renderSession.shakeY; + + var cw = this.texture.crop.width; + var ch = this.texture.crop.height; + + if (this.texture.rotated) + { + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var e = cw; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + wt.a = a * 6.123233995736766e-17 + -c; + wt.b = b * 6.123233995736766e-17 + -d; + wt.c = a + c * 6.123233995736766e-17; + wt.d = b + d * 6.123233995736766e-17; + + // Update cropping dimensions. + cw = ch; + ch = e; + } + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx | 0, ty | 0); + dx |= 0; + dy |= 0; + } + else + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + } + + dx /= resolution; + dy /= resolution; + + if (this.tint !== 0xFFFFFF) + { + if (this.texture.requiresReTint || this.cachedTint !== this.tint) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + } + + renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + else + { + var cx = this.texture.crop.x; + var cy = this.texture.crop.y; + + cw = Math.floor(cw) + ch = Math.floor(ch) + + renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @method PIXI.initDefaultShaders +* @static +* @private +*/ +PIXI.initDefaultShaders = function() +{ +}; + +/** +* @method PIXI.CompileVertexShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileVertexShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); +}; + +/** +* @method PIXI.CompileFragmentShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileFragmentShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); +}; + +/** +* @method PIXI._CompileShader +* @static +* @private +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @param shaderType {Number} +* @return {Any} +*/ +PIXI._CompileShader = function(gl, shaderSrc, shaderType) +{ + var src = shaderSrc; + + if (Array.isArray(shaderSrc)) + { + 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; +}; + +/** +* @method PIXI.compileProgram +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param vertexSrc {Array} +* @param fragmentSrc {Array} +* @return {Any} +*/ +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(gl.getProgramInfoLog(shaderProgram)); + window.console.log("Could not initialise shaders"); + } + + return shaderProgram; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + * @author Richard Davey http://www.photonstorm.com @photonstorm + */ + +/** +* @class PIXI.PixiShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PixiShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = null; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + /** + * A local flag + * @property firstRun + * @type Boolean + * @private + */ + this.firstRun = true; + + /** + * A dirty flag + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Uniform attributes cache. + * @property attributes + * @type Array + * @private + */ + this.attributes = []; + + this.init(); +}; + +PIXI.PixiShader.prototype.constructor = PIXI.PixiShader; + +PIXI.PixiShader.prototype.initMultitexShader = function () { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.fragmentSrc = [ + '// PixiShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}', + '}' + ]; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + //this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.uSamplerArray = gl.getUniformLocation(program, 'uSamplerArray[0]'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSamplerArray, indices); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; + +PIXI.PixiShader.prototype.initDefaultShader = function () { + + if (this.fragmentSrc === null) { + this.fragmentSrc = [ + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', + '}' + ]; + } + + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; +/** +* Initialises the shader. +* +* @method PIXI.PixiShader#init +*/ +PIXI.PixiShader.prototype.init = function(usingFilter) +{ + if (PIXI._enableMultiTextureToggle && !usingFilter) { + this.initMultitexShader(); + } else { + this.initDefaultShader(); + } +}; + +/** +* Initialises the shader uniform values. +* +* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ +* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf +* +* @method PIXI.PixiShader#initUniforms +*/ +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') + { + // These require special handling + 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 + { + // GL function reference + 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; + } + } + } + +}; + +/** +* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) +* +* @method PIXI.PixiShader#initSampler2D +*/ +PIXI.PixiShader.prototype.initSampler2D = function(uniform) +{ + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { + return; + } + + var gl = this.gl; + + // No need to do string manipulation for this. + gl.activeTexture(gl.TEXTURE0 + this.textureCount); + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + + // Extended texture data + if (uniform.textureData) + { + var data = uniform.textureData; + + // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); + // GLTextureLinear = mag/min linear, wrap clamp + // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat + // GLTextureNearest = mag/min nearest, wrap clamp + // AudioTexture = whatever + luminance + width 512, height 2, border 0 + // KeyTexture = whatever + luminance + width 256, height 2, border 0 + + // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + + 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; + + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels); + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); + } + else + { + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels); + 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++; + +}; + +/** +* Updates the shader uniform values. +* +* @method PIXI.PixiShader#syncUniforms +*/ +PIXI.PixiShader.prototype.syncUniforms = function() +{ + this.textureCount = 1; + var uniform; + var gl = this.gl; + + // This would probably be faster in an array and it would guarantee key order + 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]); + + if(uniform.value.baseTexture._dirty[gl.id]) + { + PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + } + + // 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); + } + } + } + +}; + +/** +* Destroys the shader. +* +* @method PIXI.PixiShader#destroy +*/ +PIXI.PixiShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** +* The Default Vertex shader source. +* +* @property defaultVertexSrc +* @type String +*/ +PIXI.PixiShader.defaultVertexSrc = [ + '// PixiShader Vertex Shader', + '// With multi-texture rendering', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute vec4 aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + + 'const vec2 center = vec2(-1.0, 1.0);', + + 'void main(void) {', + ' if (aTextureIndex > 0.0) gl_Position = vec4(0.0);', + ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', + ' vTextureCoord = aTextureCoord;', + ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', + ' vTextureIndex = aTextureIndex;', + '}' +]; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @class PIXI.PixiFastShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.PixiFastShader = function (gl) { + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '// PixiFastShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aPositionCoord;', + 'attribute vec2 aScale;', + 'attribute float aRotation;', + 'attribute vec2 aTextureCoord;', + 'attribute float aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform mat3 uMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + + '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;', + ' vTextureIndex = aTextureIndex;', + // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;', + ' vColor = aColor;', + '}' + ]; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + this.init(); +}; + +PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader; + +/** + * Initialises the shader. + * + * @method PIXI.PixiFastShader#init + */ +PIXI.PixiFastShader.prototype.init = function () { + + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + this.uMatrix = gl.getUniformLocation(program, 'uMatrix'); + + // get and store the attributes + 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'); + + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its somthing to do with the current state of the gl context. + // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if (this.colorAttribute === -1) { + this.colorAttribute = 2; + } + + this.attributes = [ + this.aVertexPosition, + this.aPositionCoord, + this.aScale, + this.aRotation, + this.aTextureCoord, + this.colorAttribute, + this.aTextureIndex + ]; + + // End worst hack eva // + + this.program = program; +}; + +/** + * Destroys the shader. + * + * @method PIXI.PixiFastShader#destroy + */ +PIXI.PixiFastShader.prototype.destroy = function () { + this.gl.deleteProgram(this.program); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.StripShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.StripShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord);return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) ;return;}\n' + } + + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord);', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '//StripShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute float aTextureIndex;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + // 'uniform float alpha;', + // 'uniform vec3 tint;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // '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);', + ' vTextureCoord = aTextureCoord;', + ' vTextureIndex = aTextureIndex;', + // ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.StripShader.prototype.constructor = PIXI.StripShader; + +/** +* Initialises the shader. +* +* @method PIXI.StripShader#init +*/ +PIXI.StripShader.prototype.init = function() +{ + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + //this.dimensions = gl.getUniformLocation(this.program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.aTextureIndex]; + + this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix'); + this.alpha = gl.getUniformLocation(program, 'alpha'); + + this.program = program; +}; + +/** +* Destroys the shader. +* +* @method PIXI.StripShader#destroy +*/ +PIXI.StripShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.PrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + 'precision mediump float;', + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform float alpha;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.PrimitiveShader#init +*/ +PIXI.PrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.PrimitiveShader#destroy +*/ +PIXI.PrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.ComplexPrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.ComplexPrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + + 'precision mediump float;', + + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + //'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 color;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.ComplexPrimitiveShader#init +*/ +PIXI.ComplexPrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.color = gl.getUniformLocation(program, 'color'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.ComplexPrimitiveShader#destroy +*/ +PIXI.ComplexPrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +PIXI.glContexts = []; // this is where we store the webGL contexts for easy access. +PIXI.instances = []; +PIXI._enableMultiTextureToggle = false; + +/** + * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class PIXI.WebGLRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.WebGLRenderer = function(game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + this.extensions = {}; + + /** + * @property type + * @type Number + */ + this.type = Phaser.WEBGL; + + /** + * The resolution of the renderer + * + * @property resolution + * @type Number + * @default 1 + */ + this.resolution = game.resolution; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * + * @property preserveDrawingBuffer + * @type Boolean + */ + this.preserveDrawingBuffer = game.preserveDrawingBuffer; + + /** + * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true: + * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0). + * If the Stage is transparent, Pixi will clear to the target Stage's background color. + * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * The width of the canvas view + * + * @property width + * @type Number + */ + this.width = game.width; + + /** + * The height of the canvas view + * + * @property height + * @type Number + */ + this.height = game.height; + + /** + * The canvas element that everything is drawn to + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * @property _contextOptions + * @type Object + * @private + */ + this._contextOptions = { + alpha: this.transparent, + antialias: game.antialias, + failIfMajorPerformanceCaveat: config.failIfMajorPerformanceCaveat, + premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: this.preserveDrawingBuffer + }; + + /** + * @property projection + * @type Point + */ + this.projection = new PIXI.Point(); + + /** + * @property offset + * @type Point + */ + this.offset = new PIXI.Point(); + + // time to create the render managers! each one focuses on managing a state in webGL + + /** + * Deals with managing the shader programs and their attribs + * @property shaderManager + * @type WebGLShaderManager + */ + this.shaderManager = new PIXI.WebGLShaderManager(); + + /** + * Manages the rendering of sprites + * @property spriteBatch + * @type WebGLSpriteBatch + */ + this.spriteBatch = new PIXI.WebGLSpriteBatch(game); + + /** + * Manages the masks using the stencil buffer + * @property maskManager + * @type WebGLMaskManager + */ + this.maskManager = new PIXI.WebGLMaskManager(); + + /** + * Manages the filters + * @property filterManager + * @type WebGLFilterManager + */ + this.filterManager = new PIXI.WebGLFilterManager(); + + /** + * Manages the stencil buffer + * @property stencilManager + * @type WebGLStencilManager + */ + this.stencilManager = new PIXI.WebGLStencilManager(); + + /** + * Manages the blendModes + * @property blendModeManager + * @type WebGLBlendModeManager + */ + this.blendModeManager = new PIXI.WebGLBlendModeManager(); + + /** + * @property renderSession + * @type Object + */ + this.renderSession = {}; + + /** + * @property currentBatchedTextures + * @type Array + */ + this.currentBatchedTextures = []; + + // Needed? + this.renderSession.game = this.game; + this.renderSession.gl = this.gl; + this.renderSession.drawCount = 0; + this.renderSession.shaderManager = this.shaderManager; + this.renderSession.maskManager = this.maskManager; + this.renderSession.filterManager = this.filterManager; + this.renderSession.blendModeManager = this.blendModeManager; + this.renderSession.spriteBatch = this.spriteBatch; + this.renderSession.stencilManager = this.stencilManager; + this.renderSession.renderer = this; + this.renderSession.resolution = this.resolution; + this.renderSession.roundPixels = config.roundPixels || false; + this.renderSession.maxTextureAvailableSpace = null; // filled in setTexturePriority() + + // time init the context.. + this.initContext(); + + // map some webGL blend modes.. + this.mapBlendModes(); + +}; + +// constructor +PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer; + +/** +* @method PIXI.WebGLRenderer#initContext +*/ +PIXI.WebGLRenderer.prototype.initContext = function() +{ + var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); + + this.gl = gl; + + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + this.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.maxTextureSize = this.gl.getParameter(gl.MAX_TEXTURE_SIZE); + + this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++; + + PIXI.glContexts[this.glContextId] = gl; + + PIXI.instances[this.glContextId] = this; + + // set up the default pixi settings.. + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + gl.enable(gl.BLEND); + + // need to set the context for all the managers... + this.shaderManager.setContext(gl); + this.spriteBatch.setContext(gl); + this.maskManager.setContext(gl); + this.filterManager.setContext(gl); + this.blendModeManager.setContext(gl); + this.stencilManager.setContext(gl); + + this.renderSession.gl = this.gl; + + // now resize and we are good to go! + this.resize(this.width, this.height); + + // Load WebGL extension + this.extensions.compression = {}; + + var etc1 = gl.getExtension('WEBGL_compressed_texture_etc1') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'); + var pvrtc = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); + var s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); + + if (etc1) { this.extensions.compression.ETC1 = etc1; } + if (pvrtc) { this.extensions.compression.PVRTC = pvrtc; } + if (s3tc) { this.extensions.compression.S3TC = s3tc; } +}; + +/** +* If Multi Texture support has been enabled, then calling this method will enable batching on the given +* textures. The texture collection is an array of keys, that map to Phaser.Cache image entries. +* +* The number of textures that can be batched is dependent on hardware. If you provide more textures +* than can be batched by the GPU, then only those at the start of the array will be used. Generally +* you shouldn't provide more than 16 textures to this method. You can check the hardware limit via the +* `maxTextures` property. +* +* You can also check the property `currentBatchedTextures` at any time, to see which textures are currently +* being batched. +* +* To stop all textures from being batched, call this method again with an empty array. +* +* To change the textures being batched, call this method with a new array of image keys. The old ones +* will all be purged out and no-longer batched, and the new ones enabled. +* +* Note: Throws a warning if you haven't enabled Multiple Texture batching support in the Phaser Game config. +* +* @method PIXI.WebGLRenderer#setTexturePriority +* @param textureNameCollection {Array} An Array of Texture Cache keys to use for multi-texture batching. +* @return {Array} An array containing the texture keys that were enabled for batching. +*/ +PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + if (!PIXI._enableMultiTextureToggle) + { + console.warn('setTexturePriority error: Multi Texture support hasn\'t been enabled in the Phaser Game Config.'); + return; + } + var clampPot = function (potSize) { + --potSize; + potSize |= potSize >> 1; + potSize |= potSize >> 2; + potSize |= potSize >> 4; + potSize |= potSize >> 8; + potSize |= potSize >> 16; + return ++potSize; + }; + var gl = this.gl; + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + var imageCache = this.game.cache._cache.image; + var imageName = null; + + // Clear out all previously batched textures and reset their flags. + // If the array has been modified, then the developer will have to + // deal with that in their own way. + for (var i = 0; i < this.currentBatchedTextures.length; i++) + { + imageName = this.currentBatchedTextures[i]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + + imageCache[imageName].base.textureIndex = 0; + } + var maxTextureAvailableSpace = (maxTextureSize) - clampPot(Math.max(this.width, this.height)); + this.currentBatchedTextures.length = 0; + // We start from 1 because framebuffer texture uses unit 0. + for (var j = 0; j < textureNameCollection.length; ++j) + { + imageName = textureNameCollection[j]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + // Unit 0 is reserved for Pixi's framebuffer + var base = imageCache[imageName].base; + maxTextureAvailableSpace -= clampPot(Math.max(base.width, base.height)); + if (maxTextureAvailableSpace <= 0) { + base.textureIndex = 0; + console.warn('setTexturePriority: Image "%s" was given textureIndex=0 because there is no available texture space (%s).', + imageName, maxTextureAvailableSpace); + } else { + base.textureIndex = (1 + (j % (maxTextures - 1))); + } + this.currentBatchedTextures.push(imageName); + } + + this.renderSession.maxTextureAvailableSpace = maxTextureAvailableSpace; + + return this.currentBatchedTextures; + +}; + +/** + * Renders the stage to its webGL view + * + * @method PIXI.WebGLRenderer#render + * @param stage {Stage} the Stage element to be rendered + */ +PIXI.WebGLRenderer.prototype.render = function(stage) +{ + // no point rendering if our context has been blown up! + if (this.contextLost) + { + return; + } + + var gl = this.gl; + + // -- Does this need to be set every frame? -- // + gl.viewport(0, 0, this.width, this.height); + + // make sure we are bound to the main frame buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + if (this.game.clearBeforeRender) + { + gl.clearColor(stage._bgColor.r, stage._bgColor.g, stage._bgColor.b, stage._bgColor.a); + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + this.offset.x = this.game.camera._shake.x; + this.offset.y = this.game.camera._shake.y; + + this.renderDisplayObject(stage, this.projection); +}; + +/** + * Renders a Display Object. + * + * @method PIXI.WebGLRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The DisplayObject to render + * @param projection {Point} The projection + * @param buffer {Array} a standard WebGL buffer + */ +PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix) +{ + this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL); + + // reset the render session data.. + this.renderSession.drawCount = 0; + + // make sure to flip the Y if using a render texture.. + this.renderSession.flipY = buffer ? -1 : 1; + + // set the default projection + this.renderSession.projection = projection; + + //set the default offset + this.renderSession.offset = this.offset; + + // start the sprite batch + this.spriteBatch.begin(this.renderSession); + + // start the filter manager + this.filterManager.begin(this.renderSession, buffer); + + // render the scene! + displayObject._renderWebGL(this.renderSession, matrix); + + // finish the sprite batch + this.spriteBatch.end(); +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @method PIXI.WebGLRenderer#resize + * @param width {Number} the new width of the webGL view + * @param height {Number} the new height of the webGL view + */ +PIXI.WebGLRenderer.prototype.resize = function(width, height) +{ + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } + + this.gl.viewport(0, 0, this.width, this.height); + + this.projection.x = this.width / 2 / this.resolution; + this.projection.y = -this.height / 2 / this.resolution; +}; + +/** + * Updates and creates a WebGL compressed texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateCompressedTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateCompressedTexture = function (texture) { + if (!texture.hasLoaded) + { + return false; + } + var gl = this.gl; + var textureMetaData = texture.source; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + textureMetaData.glExtensionFormat, + textureMetaData.width, + textureMetaData.height, + 0, + textureMetaData.textureData + ); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + texture._dirty[gl.id] = false; + return true; +}; + +/** + * Updates and Creates a WebGL texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateTexture = function(texture) +{ + if (!texture.hasLoaded) + { + return false; + } + if (texture.source.compressionAlgorithm) { + return this.updateCompressedTexture(texture); + } + + var gl = this.gl; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha); + + 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); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + + texture._dirty[gl.id] = false; + + // return texture._glTextures[gl.id]; + return true; + +}; + +/** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @method PIXI.WebGLRenderer#destroy + */ +PIXI.WebGLRenderer.prototype.destroy = function() +{ + 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; + + Phaser.CanvasPool.remove(this); + + PIXI.instances[this.glContextId] = null; + + PIXI.WebGLRenderer.glContextId--; +}; + +/** + * Maps Pixi blend modes to WebGL blend modes. + * + * @method PIXI.WebGLRenderer#mapBlendModes + */ +PIXI.WebGLRenderer.prototype.mapBlendModes = function() +{ + var gl = this.gl; + + if (!PIXI.blendModesWebGL) + { + var b = []; + var modes = PIXI.blendModes; + + b[modes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA]; + b[modes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SCREEN] = [gl.SRC_ALPHA, gl.ONE]; + b[modes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + PIXI.blendModesWebGL = b; + } +}; + +PIXI.WebGLRenderer.prototype.getMaxTextureUnit = function() { + var gl = this.gl; + return gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); +}; + +PIXI.enableMultiTexture = function() { + PIXI._enableMultiTextureToggle = true; +}; + +PIXI.WebGLRenderer.glContextId = 0; +PIXI.WebGLRenderer.textureArray = []; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLBlendModeManager +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLBlendModeManager = function() +{ + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 99999; +}; + +PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLBlendModeManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLBlendModeManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Sets-up the given blendMode from WebGL's point of view. +* +* @method PIXI.WebGLBlendModeManager#setBlendMode +* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD +*/ +PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode) +{ + if(this.currentBlendMode === blendMode)return false; + + this.currentBlendMode = blendMode; + + var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode]; + + if (blendModeWebGL) + { + this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLBlendModeManager#destroy +*/ +PIXI.WebGLBlendModeManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLMaskManager +* @constructor +* @private +*/ +PIXI.WebGLMaskManager = function() +{ +}; + +PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLMaskManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLMaskManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLMaskManager#pushMask +* @param maskData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession) +{ + var gl = renderSession.gl; + + if (maskData.dirty) + { + PIXI.WebGLGraphics.updateGraphics(maskData, gl); + } + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLMaskManager#popMask +* @param maskData {Array} +* @param renderSession {Object} an object containing all the useful parameters +*/ +PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession) +{ + var gl = this.gl; + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); + +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLMaskManager#destroy +*/ +PIXI.WebGLMaskManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLStencilManager +* @constructor +* @private +*/ +PIXI.WebGLStencilManager = function() +{ + this.stencilStack = []; + this.reverse = true; + this.count = 0; +}; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLStencilManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLStencilManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLStencilManager#pushMask +* @param graphics {Graphics} +* @param webGLData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.bindGraphics(graphics, webGLData, renderSession); + + if(this.stencilStack.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + this.reverse = true; + this.count = 0; + } + + this.stencilStack.push(webGLData); + + var level = this.count; + + gl.colorMask(false, false, false, false); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + + if(webGLData.mode === 1) + { + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + + this.reverse = !this.reverse; + } + else + { + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + this.count++; +}; + +/** + * TODO this does not belong here! + * + * @method PIXI.WebGLStencilManager#bindGraphics + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession) +{ + //if(this._currentGraphics === graphics)return; + this._currentGraphics = graphics; + + var gl = this.gl; + + // bind the graphics object.. + var projection = renderSession.projection, + offset = renderSession.offset, + shader;// = renderSession.shaderManager.primitiveShader; + + if(webGLData.mode === 1) + { + shader = renderSession.shaderManager.complexPrimitiveShader; + + renderSession.shaderManager.setShader( shader ); + + gl.uniform1f(shader.flipY, renderSession.flipY); + + 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, Phaser.Color.hexToRGBArray(graphics.tint)); + gl.uniform3fv(shader.color, webGLData.color); + + gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0); + + + // now do the rest.. + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } + else + { + //renderSession.shaderManager.activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + renderSession.shaderManager.setShader( shader ); + + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, renderSession.flipY); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } +}; + +/** + * @method PIXI.WebGLStencilManager#popStencil + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.stencilStack.pop(); + + this.count--; + + if(this.stencilStack.length === 0) + { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + + } + else + { + + var level = this.count; + + this.bindGraphics(graphics, webGLData, renderSession); + + gl.colorMask(false, false, false, false); + + if(webGLData.mode === 1) + { + this.reverse = !this.reverse; + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + + } + else + { + // console.log("<<>>") + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + + } +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLStencilManager#destroy +*/ +PIXI.WebGLStencilManager.prototype.destroy = function() +{ + this.stencilStack = null; + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLShaderManager +* @constructor +* @private +*/ +PIXI.WebGLShaderManager = function() +{ + /** + * @property maxAttibs + * @type Number + */ + this.maxAttibs = 10; + + /** + * @property attribState + * @type Array + */ + this.attribState = []; + + /** + * @property tempAttribState + * @type Array + */ + this.tempAttribState = []; + + for (var i = 0; i < this.maxAttibs; i++) + { + this.attribState[i] = false; + } + + /** + * @property stack + * @type Array + */ + this.stack = []; + +}; + +PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLShaderManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLShaderManager.prototype.setContext = function(gl) +{ + this.gl = gl; + + // the next one is used for rendering primitives + this.primitiveShader = new PIXI.PrimitiveShader(gl); + + // the next one is used for rendering triangle strips + this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl); + + // this shader is used for the default sprite rendering + this.defaultShader = new PIXI.PixiShader(gl); + + // this shader is used for the fast sprite rendering + this.fastShader = new PIXI.PixiFastShader(gl); + + // the next one is used for rendering triangle strips + this.stripShader = new PIXI.StripShader(gl); + + // the next one is used for rendering creature meshes + this.creatureShader = PIXI.CreatureShader ? new PIXI.CreatureShader(gl) : null; + + this.setShader(this.defaultShader); +}; + +/** +* Takes the attributes given in parameters. +* +* @method PIXI.WebGLShaderManager#setAttribs +* @param attribs {Array} attribs +*/ +PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs) +{ + // reset temp state + var i; + + for (i = 0; i < this.tempAttribState.length; i++) + { + this.tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + var attribId = attribs[i]; + this.tempAttribState[attribId] = true; + } + + var gl = this.gl; + + for (i = 0; i < this.attribState.length; i++) + { + if(this.attribState[i] !== this.tempAttribState[i]) + { + this.attribState[i] = this.tempAttribState[i]; + + if(this.tempAttribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } +}; + +/** +* Sets the current shader. +* +* @method PIXI.WebGLShaderManager#setShader +* @param shader {Any} +*/ +PIXI.WebGLShaderManager.prototype.setShader = function(shader) +{ + if(this._currentId === shader._UID)return false; + + this._currentId = shader._UID; + + this.currentShader = shader; + + this.gl.useProgram(shader.program); + this.setAttribs(shader.attributes); + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLShaderManager#destroy +*/ +PIXI.WebGLShaderManager.prototype.destroy = function() +{ + this.attribState = null; + + this.tempAttribState = null; + + this.primitiveShader.destroy(); + + this.complexPrimitiveShader.destroy(); + + this.defaultShader.destroy(); + + this.fastShader.destroy(); + + this.stripShader.destroy(); + + if (this.creatureShader) { + this.creatureShader.destroy(); + } + + this.gl = null; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** + * + * @class PIXI.WebGLSpriteBatch + * @private + * @constructor + */ +PIXI.WebGLSpriteBatch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 5; + + /** + * The number of images in the SpriteBatch before it flushes + * @property size + * @type Number + */ + this.size = 2000; //Math.pow(2, 16) / this.vertSize; + + //the total number of bytes in our batch + // Including texture index: + // position + uv + color + textureIndex + // vec2 + vec2 + (char * 4) + float + this.vertexSize = (4 * 2) + (4 * 2) + (4) + (4); + var numVerts = this.vertexSize * this.size * 4; + //this.size * 4 * 4 * this.vertSize; + //the total number of indices in our batch + var numIndices = this.size * 6; + + /** + * Holds the vertices + * + * @property vertices + * @type ArrayBuffer + */ + this.vertices = new ArrayBuffer(numVerts); + + /** + * View on the vertices as a Float32Array + * + * @property positions + * @type Float32Array + */ + this.positions = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array + * + * @property colors + * @type Uint32Array + */ + this.colors = new Uint32Array(this.vertices); + + /** + * Holds the indices + * + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * @property textures + * @type Array + */ + this.textures = []; + + /** + * @property blendModes + * @type Array + */ + this.blendModes = []; + + /** + * @property shaders + * @type Array + */ + this.shaders = []; + + /** + * @property sprites + * @type Array + */ + this.sprites = []; + + /** + * @property defaultShader + * @type Phaser.Filter + */ + this.defaultShader = null; +}; + +/** + * @method PIXI.WebGLSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLSpriteBatch.prototype.setContext = function (gl) { + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.gl = gl; + if (PIXI._enableMultiTextureToggle) { + var dynamicIfs = '\tif (vTextureIndex == 0.0) {gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + 'void main(void) {', + dynamicIfs, + '\tgl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;', + '}' + ]); + } + else + { + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]); + } + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + this.currentBlendMode = 99999; + + var shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = this.defaultShader.fragmentSrc; + shader.uniforms = {}; + shader.init(); + + this.defaultShader.shaders[gl.id] = shader; +}; + +/** + * @method PIXI.WebGLSpriteBatch#begin + * @param renderSession {Object} The RenderSession object + */ +PIXI.WebGLSpriteBatch.prototype.begin = function (renderSession) { + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.defaultShader; + + this.start(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#end + */ +PIXI.WebGLSpriteBatch.prototype.end = function () { + this.flush(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#render + * @param sprite {Sprite} the sprite to render when using this spritebatch + * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. + */ +PIXI.WebGLSpriteBatch.prototype.render = function (sprite, matrix) { + var texture = sprite.texture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + if (PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + baseTexture.textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] = baseTexture; + } + + // They provided an alternative rendering matrix, so use it + var wt = sprite.worldTransform; + + if (matrix) { + wt = matrix; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // get the uvs for the texture + var uvs = texture._uvs; + + // if the uvs have not updated then no point rendering just yet! + if (!uvs) { + return; + } + + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + + var w0, w1, h0, h1; + + if (texture.trim) { + // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords. + var trim = texture.trim; + + w1 = trim.x - aX * trim.width; + w0 = w1 + texture.crop.width; + + h1 = trim.y - aY * trim.height; + h0 = h1 + texture.crop.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 i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + var tiOffset = this.currentBatchSize * 4; + var resolution = texture.baseTexture.resolution; + var textureIndex = texture.baseTexture.textureIndex; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + + var cw = texture.crop.width; + var ch = texture.crop.height; + + if (texture.rotated) + { + var a0 = wt.a; + var b0 = wt.b; + var c0 = wt.c; + var d0 = wt.d; + var _w1 = w1; + var _w0 = w0; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + a = a0 * 6.123233995736766e-17 + -c0; + b = b0 * 6.123233995736766e-17 + -d0; + c = a0 + c0 * 6.123233995736766e-17; + d = b0 + d0 * 6.123233995736766e-17; + + // Update UV coordinates + texture._updateUvsInverted(); + + // Rotate dimensions + w0 = h0; + w1 = h1; + h0 = _w0; + h1 = _w1; + } + + var colors = this.colors; + var positions = this.positions; + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + if (this.renderSession.roundPixels) { + positions[i++] = a * w1 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w1 + ty | 0; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w0 + ty | 0; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w0 + ty | 0; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w1 + ty | 0; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } else { + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx; + positions[i++] = d * h1 + b * w0 + ty; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders a TilingSprite using the spriteBatch. + * + * @method PIXI.WebGLSpriteBatch#renderTilingSprite + * @param sprite {TilingSprite} the sprite to render + */ +PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function (sprite) { + var texture = sprite.tilingTexture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + var textureIndex = sprite.texture.baseTexture.textureIndex; + if (PIXI.WebGLRenderer.textureArray[textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[textureIndex] = baseTexture; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // set the textures uvs temporarily + if (!sprite._uvs) { + sprite._uvs = new PIXI.TextureUvs(); + } + + var uvs = sprite._uvs; + + var w = texture.baseTexture.width; + var h = texture.baseTexture.height; + + // var w = sprite._frame.sourceSizeW; + // var h = sprite._frame.sourceSizeH; + + // w = 16; + // h = 16; + + sprite.tilePosition.x %= w * sprite.tileScaleOffset.x; + sprite.tilePosition.y %= h * sprite.tileScaleOffset.y; + + var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x); + var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y); + + var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x); + var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.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; + + // Get the sprites current alpha and tint and combine them into a single color + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + var positions = this.positions; + var colors = this.colors; + + var width = sprite.width; + var height = sprite.height; + + // TODO trim?? + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + var w0 = width * (1 - aX); + var w1 = width * -aX; + + var h0 = height * (1 - aY); + var h1 = height * -aY; + + var i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + + var resolution = texture.baseTexture.resolution; + + var wt = sprite.worldTransform; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + // xy + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + // uv + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = (a * w0 + c * h1 + tx); + positions[i++] = d * h1 + b * w0 + ty; + // uv + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + // uv + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + // uv + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders the content and empties the current batch. + * + * @method PIXI.WebGLSpriteBatch#flush + */ +PIXI.WebGLSpriteBatch.prototype.flush = function () { + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize === 0) { + return; + } + + var gl = this.gl; + var shader; + + if (this.dirty) { + this.dirty = false; + + shader = this.defaultShader.shaders[gl.id]; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + // this is the same for each shader? + var stride = this.vertexSize; //this.vertSize * 4; + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 8); + + // color attributes will be interpreted as unsigned bytes and normalized + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 16); + + // Texture index + gl.vertexAttribPointer(shader.aTextureIndex, 1, gl.FLOAT, false, stride, 20); + } + + // upload the verts to the buffer + if (this.currentBatchSize > (this.size * 0.5)) { + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + } else { + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + var view = this.positions.subarray(0, this.currentBatchSize * this.vertexSize); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); + } + + var nextTexture, nextBlendMode, nextShader; + var batchSize = 0; + var start = 0; + + var currentBaseTexture = null; + var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode; + var currentShader = null; + + var blendSwap = false; + var shaderSwap = false; + var sprite; + var textureIndex = 0; + + for (var i = 0, j = this.currentBatchSize; i < j; i++) { + + sprite = this.sprites[i]; + + if (sprite.tilingTexture) { + nextTexture = sprite.tilingTexture.baseTexture; + } else { + nextTexture = sprite.texture.baseTexture; + } + + nextBlendMode = sprite.blendMode; + nextShader = sprite.shader || this.defaultShader; + + blendSwap = currentBlendMode !== nextBlendMode; + shaderSwap = currentShader !== nextShader; // should I use _UIDS??? + + var skip = nextTexture.skipRender; + + if (skip && sprite.children.length > 0) { + skip = false; + } + // + if (/*(currentBaseTexture != nextTexture && !skip) ||*/ + blendSwap || + shaderSwap) { + this.renderBatch(currentBaseTexture, batchSize, start); + + start = i; + batchSize = 0; + currentBaseTexture = nextTexture; + + if (blendSwap) { + currentBlendMode = nextBlendMode; + this.renderSession.blendModeManager.setBlendMode(currentBlendMode); + } + + if (shaderSwap) { + currentShader = nextShader; + + shader = currentShader.shaders[gl.id]; + + if (!shader) { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = currentShader.fragmentSrc; + shader.uniforms = currentShader.uniforms; + shader.init(); + + currentShader.shaders[gl.id] = shader; + } + + // set shader function??? + this.renderSession.shaderManager.setShader(shader); + + if (shader.dirty) { + shader.syncUniforms(); + } + + // both these only need to be set if they are changing.. + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(shader.projectionVector, projection.x, projection.y); + + // TODO - this is temporary! + var offsetVector = this.renderSession.offset; + gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y); + + // set the pointers + } + } + + batchSize++; + } + + this.renderBatch(currentBaseTexture, batchSize, start); + + // then reset the batch! + this.currentBatchSize = 0; +}; + +/** + * @method PIXI.WebGLSpriteBatch#renderBatch + * @param texture {Texture} + * @param size {Number} + * @param startIndex {Number} + */ +PIXI.WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { + if (size === 0) { + return; + } + + var gl = this.gl; + + // check if a texture is dirty.. + if (texture._dirty[gl.id]) { + if (!this.renderSession.renderer.updateTexture(texture)) { + // If updateTexture returns false then we cannot render it, so bail out now + return; + } + }else { + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + } + + gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2); + // increment the draw count + this.renderSession.drawCount++; +}; + +/** + * @method PIXI.WebGLSpriteBatch#stop + */ +PIXI.WebGLSpriteBatch.prototype.stop = function () { + this.flush(); + this.dirty = true; +}; + +/** + * @method PIXI.WebGLSpriteBatch#start + */ +PIXI.WebGLSpriteBatch.prototype.start = function () { + this.dirty = true; +}; + +/** + * Destroys the SpriteBatch. + * + * @method PIXI.WebGLSpriteBatch#destroy + */ +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; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** +* @class PIXI.WebGLFastSpriteBatch +* @constructor +*/ +PIXI.WebGLFastSpriteBatch = function(gl) +{ + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 11; + + /** + * @property maxSize + * @type Number + */ + this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize; + + /** + * @property size + * @type Number + */ + this.size = this.maxSize; + + //the total number of floats in our batch + var numVerts = this.size * 4 * this.vertSize; + + //the total number of indices in our batch + var numIndices = this.maxSize * 6; + + /** + * Vertex data + * @property vertices + * @type Float32Array + */ + this.vertices = new Float32Array(numVerts); + + /** + * Index data + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property vertexBuffer + * @type Object + */ + this.vertexBuffer = null; + + /** + * @property indexBuffer + * @type Object + */ + this.indexBuffer = null; + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i=0, j=0; i < numIndices; i += 6, j += 4) + { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 0; + + /** + * @property renderSession + * @type Object + */ + this.renderSession = null; + + /** + * @property shader + * @type Object + */ + this.shader = null; + + /** + * @property matrix + * @type Matrix + */ + this.matrix = null; + + this.setContext(gl); +}; + +PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLFastSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl) +{ + this.gl = gl; + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#begin + * @param spriteBatch {WebGLSpriteBatch} + * @param renderSession {Object} + */ +PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession) +{ + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.fastShader; + + this.matrix = spriteBatch.worldTransform.toArray(true); + + this.start(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#end + */ +PIXI.WebGLFastSpriteBatch.prototype.end = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#render + * @param spriteBatch {WebGLSpriteBatch} + */ +PIXI.WebGLFastSpriteBatch.prototype.render = function (spriteBatch) +{ + var children = spriteBatch.children; + var sprite = children[0]; + + // if the uvs have not updated then no point rendering just yet! + + // check texture. + if(!sprite.texture._uvs)return; + + this.currentBaseTexture = sprite.texture.baseTexture; + + // check blend mode + if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode) + { + this.flush(); + this.renderSession.blendModeManager.setBlendMode(sprite.blendMode); + } + + for(var i=0,j= children.length; i= this.size) + { + this.flush(); + } +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#flush + */ +PIXI.WebGLFastSpriteBatch.prototype.flush = function() +{ + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize===0)return; + + var gl = this.gl; + + // bind the current texture + + if(!this.currentBaseTexture._glTextures[gl.id]) { + this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl); + return; + } + + //gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); + + // upload the verts to the buffer + + if(this.currentBatchSize > ( this.size * 0.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); + } + + // now draw those suckas! + gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0); + + // then reset the batch! + this.currentBatchSize = 0; + + // increment the draw count + this.renderSession.drawCount++; + +}; + + +/** + * @method PIXI.WebGLFastSpriteBatch#stop + */ +PIXI.WebGLFastSpriteBatch.prototype.stop = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#start + */ +PIXI.WebGLFastSpriteBatch.prototype.start = function() +{ + var gl = this.gl; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(this.shader.projectionVector, projection.x, projection.y); + + // set the matrix + gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix); + + // set the pointers + 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); + gl.vertexAttribPointer(this.shader.aTextureIndex, 1, gl.FLOAT, false, stride, 10 * 4); + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLFilterManager +* @constructor +*/ +PIXI.WebGLFilterManager = function() +{ + /** + * @property filterStack + * @type Array + */ + this.filterStack = []; + + /** + * @property offsetX + * @type Number + */ + this.offsetX = 0; + + /** + * @property offsetY + * @type Number + */ + this.offsetY = 0; +}; + +PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLFilterManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLFilterManager.prototype.setContext = function(gl) +{ + this.gl = gl; + this.texturePool = []; + + this.initShaderBuffers(); +}; + +/** +* @method PIXI.WebGLFilterManager#begin +* @param renderSession {RenderSession} +* @param buffer {ArrayBuffer} +*/ +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; +}; + +/** +* Applies the filter and adds it to the current filter stack. +* +* @method PIXI.WebGLFilterManager#pushFilter +* @param filterBlock {Object} the filter that will be pushed to the current filter stack +*/ +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(); + + // >>> modify by nextht + filterBlock._previous_stencil_mgr = this.renderSession.stencilManager; + this.renderSession.stencilManager = new PIXI.WebGLStencilManager(); + this.renderSession.stencilManager.setContext(gl); + gl.disable(gl.STENCIL_TEST); + // <<< modify by nextht + + // filter program + // OPTIMISATION - the first filter is free if its a simple color change? + 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.renderSession.resolution, this.height * this.renderSession.resolution); + } + else + { + texture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + } + + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea; + + var padding = filter.padding; + filterArea.x -= padding; + filterArea.y -= padding; + filterArea.width += padding * 2; + filterArea.height += padding * 2; + + // cap filter to screen size.. + 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer); + + // set view port + gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + projection.x = filterArea.width/2; + projection.y = -filterArea.height/2; + + offset.x = -filterArea.x; + offset.y = -filterArea.y; + + // update projection + // now restore the regular shader.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + //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; + +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLFilterManager#popFilter +*/ +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 * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + 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); + // now set the uvs.. + 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.renderSession.resolution, this.height * this.renderSession.resolution); + outputTexture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + + // need to clear this FBO as it may have some left over elements from a previous filter. + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + gl.clear(gl.COLOR_BUFFER_BIT); + + gl.disable(gl.BLEND); + + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { + var filterPass = filterBlock.filterPasses[i]; + + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture); + + // draw texture.. + //filterPass.applyFilterPass(filterArea.width, filterArea.height); + this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height); + + // swap the textures.. + var temp = inputTexture; + inputTexture = outputTexture; + outputTexture = temp; + } + + gl.enable(gl.BLEND); + + texture = inputTexture; + this.texturePool.push(outputTexture); + } + + var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1]; + + this.offsetX -= filterArea.x; + this.offsetY -= filterArea.y; + + var sizeX = this.width; + var sizeY = this.height; + + var offsetX = 0; + var offsetY = 0; + + var buffer = this.buffer; + + // time to render the filters texture to the previous scene + if(this.filterStack.length === 0) + { + gl.colorMask(true, true, true, true);//this.transparent); + } + else + { + var currentFilter = this.filterStack[this.filterStack.length-1]; + filterArea = currentFilter._filterArea; + + sizeX = filterArea.width; + sizeY = filterArea.height; + + offsetX = filterArea.x; + offsetY = filterArea.y; + + buffer = currentFilter._glFilterTexture.frameBuffer; + } + + // TODO need to remove these global elements.. + projection.x = sizeX/2; + projection.y = -sizeY/2; + + offset.x = offsetX; + offset.y = offsetY; + + filterArea = filterBlock._filterArea; + + var x = filterArea.x-offsetX; + var y = filterArea.y-offsetY; + + // update the buffers.. + // make sure to flip the y! + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + + this.vertexArray[0] = x; + this.vertexArray[1] = y + filterArea.height; + + this.vertexArray[2] = x + filterArea.width; + this.vertexArray[3] = y + filterArea.height; + + this.vertexArray[4] = x; + this.vertexArray[5] = y; + + this.vertexArray[6] = x + filterArea.width; + this.vertexArray[7] = y; + + 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); + + gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution); + + // bind the buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, buffer ); + + // set the blend mode! + //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + // >>> modify by nextht + if (this.renderSession.stencilManager) { + this.renderSession.stencilManager.destroy(); + } + this.renderSession.stencilManager = filterBlock._previous_stencil_mgr; + filterBlock._previous_stencil_mgr = null; + if (this.renderSession.stencilManager.count > 0) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + // <<< modify by nextht + + // apply! + this.applyFilterPass(filter, filterArea, sizeX, sizeY); + + // now restore the regular shader.. should happen automatically now.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2); + // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY); + + // return the texture to the pool + this.texturePool.push(texture); + filterBlock._glFilterTexture = null; +}; + + +/** +* Applies the filter to the specified area. +* +* @method PIXI.WebGLFilterManager#applyFilterPass +* @param filter {Phaser.Filter} the filter that needs to be applied +* @param filterArea {Texture} TODO - might need an update +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +*/ +PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height) +{ + // use program + var gl = this.gl; + var shader = filter.shaders[gl.id]; + + if(!shader) + { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = filter.fragmentSrc; + shader.uniforms = filter.uniforms; + shader.init(true); + + filter.shaders[gl.id] = shader; + } + + // set the shader + this.renderSession.shaderManager.setShader(shader); + +// gl.useProgram(shader.program); + + gl.uniform2f(shader.projectionVector, width/2, -height/2); + gl.uniform2f(shader.offsetVector, 0,0); + + if(filter.uniforms.dimensions) + { + filter.uniforms.dimensions.value[0] = this.width;//width; + filter.uniforms.dimensions.value[1] = this.height;//height; + filter.uniforms.dimensions.value[2] = this.vertexArray[0]; + filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height; + } + + shader.syncUniforms(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // draw the filter... + gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + + this.renderSession.drawCount++; +}; + +/** +* Initialises the shader buffers. +* +* @method PIXI.WebGLFilterManager#initShaderBuffers +*/ +PIXI.WebGLFilterManager.prototype.initShaderBuffers = function() +{ + var gl = this.gl; + + // create some buffers + this.vertexBuffer = gl.createBuffer(); + this.uvBuffer = gl.createBuffer(); + this.colorBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // bind and upload the vertexs.. + // keep a reference to the vertexFloatData.. + this.vertexArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW); + + // bind and upload the uv buffer + this.uvArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW); + + this.colorArray = new Float32Array([1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW); + + // bind and upload the index + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW); + +}; + +/** +* Destroys the filter and removes it from the filter stack. +* +* @method PIXI.WebGLFilterManager#destroy +*/ +PIXI.WebGLFilterManager.prototype.destroy = function() +{ + var gl = this.gl; + + this.filterStack = null; + + this.offsetX = 0; + this.offsetY = 0; + + // destroy textures + for (var i = 0; i < this.texturePool.length; i++) { + this.texturePool[i].destroy(); + } + + this.texturePool = null; + + //destroy buffers.. + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.uvBuffer); + gl.deleteBuffer(this.colorBuffer); + gl.deleteBuffer(this.indexBuffer); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @private + */ +function _CreateEmptyTexture(gl, width, height, scaleMode) { + var texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + return texture; +} + +/** + * @private + */ +var _fbErrors = { + 36054: 'Incomplete attachment', + 36055: 'Missing attachment', + 36057: 'Incomplete dimensions', + 36061: 'Framebuffer unsupported' +}; + +/** + * @private + */ +function _CreateFramebuffer(gl, width, height, scaleMode, textureUnit) { + var framebuffer = gl.createFramebuffer(); + var depthStencilBuffer = gl.createRenderbuffer(); + var colorBuffer = null; + var fbStatus = 0; + + gl.activeTexture(gl.TEXTURE0 + textureUnit); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer); + colorBuffer = _CreateEmptyTexture(gl, width, height, scaleMode); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorBuffer, 0); + fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + if(fbStatus !== gl.FRAMEBUFFER_COMPLETE) { + console.error('Incomplete GL framebuffer. ', _fbErrors[fbStatus]); + } + framebuffer.width = width; + framebuffer.height = height; + framebuffer.targetTexture = colorBuffer; + framebuffer.renderBuffer = depthStencilBuffer; + return framebuffer; +} + +/** +* @class PIXI.FilterTexture +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +* @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values +*/ +PIXI.FilterTexture = function(gl, width, height, scaleMode, textureUnit) +{ + textureUnit = typeof textureUnit === 'number' ? textureUnit : 0; + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + // next time to create a frame buffer and texture + + /** + * @property frameBuffer + * @type Any + */ + this.frameBuffer = _CreateFramebuffer(gl, width, height, scaleMode || PIXI.scaleModes.DEFAULT, textureUnit); + /** + * @property texture + * @type Any + */ + this.texture = this.frameBuffer.targetTexture; + this.width = width; + this.height = height; + this.renderBuffer = this.frameBuffer.renderBuffer; +}; + +PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture; + +/** +* Clears the filter texture. +* +* @method PIXI.FilterTexture#clear +*/ +PIXI.FilterTexture.prototype.clear = function() +{ + var gl = this.gl; + + gl.clearColor(0,0,0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Resizes the texture to the specified width and height + * + * @method PIXI.FilterTexture#resize + * @param width {Number} the new width of the texture + * @param height {Number} the new height of the texture + */ +PIXI.FilterTexture.prototype.resize = function(width, height) +{ + if(this.width === width && this.height === height) return; + + this.width = width; + this.height = height; + + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height ); +}; + +/** +* Destroys the filter texture. +* +* @method PIXI.FilterTexture#destroy +*/ +PIXI.FilterTexture.prototype.destroy = function() +{ + var gl = this.gl; + gl.deleteFramebuffer( this.frameBuffer ); + gl.deleteTexture( this.texture ); + + this.frameBuffer = null; + this.texture = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Creates a Canvas element of the given size. + * + * @class PIXI.CanvasBuffer + * @constructor + * @param width {Number} the width for the newly created canvas + * @param height {Number} the height for the newly created canvas + */ +PIXI.CanvasBuffer = function(width, height) +{ + /** + * The width of the Canvas in pixels. + * + * @property width + * @type Number + */ + this.width = width; + + /** + * The height of the Canvas in pixels. + * + * @property height + * @type Number + */ + this.height = height; + + /** + * The Canvas object that belongs to this CanvasBuffer. + * + * @property canvas + * @type HTMLCanvasElement + */ + this.canvas = Phaser.CanvasPool.create(this, this.width, this.height); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.canvas.getContext("2d"); + + this.canvas.width = width; + this.canvas.height = height; +}; + +PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer; + +/** + * Clears the canvas that was created by the CanvasBuffer class. + * + * @method PIXI.CanvasBuffer#clear + * @private + */ +PIXI.CanvasBuffer.prototype.clear = function() +{ + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0,0, this.width, this.height); +}; + +/** + * Resizes the canvas to the specified width and height. + * + * @method PIXI.CanvasBuffer#resize + * @param width {Number} the new width of the canvas + * @param height {Number} the new height of the canvas + */ +PIXI.CanvasBuffer.prototype.resize = function(width, height) +{ + this.width = this.canvas.width = width; + this.height = this.canvas.height = height; +}; + +/** + * Frees the canvas up for use again. + * + * @method PIXI.CanvasBuffer#destroy + */ +PIXI.CanvasBuffer.prototype.destroy = function() +{ + Phaser.CanvasPool.remove(this); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used to handle masking. + * + * @class PIXI.CanvasMaskManager + * @constructor + */ +PIXI.CanvasMaskManager = function() +{ +}; + +PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; + +/** + * This method adds it to the current stack of masks. + * + * @method PIXI.CanvasMaskManager#pushMask + * @param maskData {Object} the maskData that will be pushed + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) { + + var context = renderSession.context; + + context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.worldTransform; + + var resolution = renderSession.resolution; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution); + + PIXI.CanvasGraphics.renderGraphicsMask(maskData, context); + + context.clip(); + + maskData.worldAlpha = cacheAlpha; +}; + +/** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @method PIXI.CanvasMaskManager#popMask + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.popMask = function(renderSession) +{ + renderSession.context.restore(); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class PIXI.CanvasTinter + * @static + */ +PIXI.CanvasTinter = function() {}; + +/** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @method PIXI.CanvasTinter#getTintedTexture + * @static + * @param sprite {Sprite} the sprite to tint + * @param color {Number} the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ +PIXI.CanvasTinter.getTintedTexture = function(sprite, color) +{ + var canvas = sprite.tintedTexture || Phaser.CanvasPool.create(this); + + PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas); + + return canvas; +}; + +/** + * Tint a texture using the "multiply" operation. + * + * @method PIXI.CanvasTinter#tintWithMultiply + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.clearRect(0, 0, w, h); + + context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, w, h); + + context.globalCompositeOperation = "multiply"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + context.globalCompositeOperation = "destination-atop"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + +}; + +/** + * Tint a texture pixel per pixel. + * + * @method PIXI.CanvasTinter#tintPerPixel + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.globalCompositeOperation = "copy"; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + var rgbValues = Phaser.Color.hexToRGBArray(color); + var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, w, h); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) + { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + + if (!PIXI.CanvasTinter.canHandleAlpha) + { + var alpha = pixels[i + 3]; + + pixels[i + 0] /= 255 / alpha; + pixels[i + 1] /= 255 / alpha; + pixels[i + 2] /= 255 / alpha; + } + } + + context.putImageData(pixelData, 0, 0); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class PIXI.CanvasRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.CanvasRenderer = function (game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + /** + * The renderer type. + * + * @property type + * @type Number + */ + this.type = Phaser.CANVAS; + + /** + * The resolution of the canvas. + * + * @property resolution + * @type Number + */ + this.resolution = game.resolution; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. + * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame. + * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The width of the canvas view + * + * @property width + * @type Number + * @default 800 + */ + this.width = game.width * this.resolution; + + /** + * The height of the canvas view + * + * @property height + * @type Number + * @default 600 + */ + this.height = game.height * this.resolution; + + /** + * The canvas element that everything is drawn to. + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * The canvas 2d context that everything is drawn with + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.view.getContext("2d", { alpha: this.transparent } ); + + /** + * Boolean flag controlling canvas refresh. + * + * @property refresh + * @type Boolean + */ + this.refresh = true; + + /** + * Internal var. + * + * @property count + * @type Number + */ + this.count = 0; + + /** + * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer + * @property CanvasMaskManager + * @type CanvasMaskManager + */ + this.maskManager = new PIXI.CanvasMaskManager(); + + /** + * The render session is just a bunch of parameter used for rendering + * @property renderSession + * @type Object + */ + this.renderSession = { + context: this.context, + maskManager: this.maskManager, + scaleMode: null, + smoothProperty: Phaser.Canvas.getSmoothingPrefix(this.context), + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + */ + roundPixels: config.roundPixels || false + }; + + this.mapBlendModes(); + + this.resize(this.width, this.height); + +}; + +// constructor +PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer; + +/** + * Renders the DisplayObjectContainer, usually the Phaser.Stage, to this canvas view. + * + * @method PIXI.CanvasRenderer#render + * @param root {Phaser.Stage|PIXI.DisplayObjectContainer} The root element to be rendered. + */ +PIXI.CanvasRenderer.prototype.render = function (root) { + + this.context.setTransform(1, 0, 0, 1, 0, 0); + + this.context.globalAlpha = 1; + + this.renderSession.currentBlendMode = 0; + this.renderSession.shakeX = this.game.camera._shake.x; + this.renderSession.shakeY = this.game.camera._shake.y; + + this.context.globalCompositeOperation = 'source-over'; + + if (navigator.isCocoonJS && this.view.screencanvas) + { + this.context.fillStyle = "black"; + this.context.clear(); + } + + if (this.clearBeforeRender) + { + if (this.transparent) + { + this.context.clearRect(0, 0, this.width, this.height); + } + else if (root._bgColor) + { + this.context.fillStyle = root._bgColor.rgba; + this.context.fillRect(0, 0, this.width , this.height); + } + } + + this.renderDisplayObject(root); + +}; + +PIXI.CanvasRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + // Does nothing on Canvas, but here to allow you to simply set + // `game.renderer.setTexturePriority()` without having to worry about + // running in WebGL or not. + +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @method PIXI.CanvasRenderer#destroy + * @param [removeView=true] {boolean} Removes the Canvas element from the DOM. + */ +PIXI.CanvasRenderer.prototype.destroy = function (removeView) { + + if (removeView === undefined) { removeView = true; } + + if (removeView && this.view.parent) + { + this.view.parent.removeChild(this.view); + } + + this.view = null; + this.context = null; + this.maskManager = null; + this.renderSession = null; + +}; + +/** + * Resizes the canvas view to the specified width and height + * + * @method PIXI.CanvasRenderer#resize + * @param width {Number} the new width of the canvas view + * @param height {Number} the new height of the canvas view + */ +PIXI.CanvasRenderer.prototype.resize = function (width, height) { + + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) + { + this.view.style.width = this.width / this.resolution + "px"; + this.view.style.height = this.height / this.resolution + "px"; + } + + if (this.renderSession.smoothProperty) + { + this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + +}; + +/** + * Renders a display object + * + * @method PIXI.CanvasRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The displayObject to render + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. + * @private + */ +PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) { + + this.renderSession.context = context || this.context; + this.renderSession.resolution = this.resolution; + displayObject._renderCanvas(this.renderSession, matrix); + +}; + +/** + * Maps Pixi blend modes to canvas blend modes. + * + * @method PIXI.CanvasRenderer#mapBlendModes + * @private + */ +PIXI.CanvasRenderer.prototype.mapBlendModes = function () { + + if (!PIXI.blendModesCanvas) + { + var b = []; + var modes = PIXI.blendModes; + var useNew = this.game.device.canUseMultiply; + + b[modes.NORMAL] = 'source-over'; + b[modes.ADD] = 'lighter'; + b[modes.MULTIPLY] = (useNew) ? 'multiply' : 'source-over'; + b[modes.SCREEN] = (useNew) ? 'screen' : 'source-over'; + b[modes.OVERLAY] = (useNew) ? 'overlay' : 'source-over'; + b[modes.DARKEN] = (useNew) ? 'darken' : 'source-over'; + b[modes.LIGHTEN] = (useNew) ? 'lighten' : 'source-over'; + b[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : 'source-over'; + b[modes.COLOR_BURN] = (useNew) ? 'color-burn' : 'source-over'; + b[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : 'source-over'; + b[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : 'source-over'; + b[modes.DIFFERENCE] = (useNew) ? 'difference' : 'source-over'; + b[modes.EXCLUSION] = (useNew) ? 'exclusion' : 'source-over'; + b[modes.HUE] = (useNew) ? 'hue' : 'source-over'; + b[modes.SATURATION] = (useNew) ? 'saturation' : 'source-over'; + b[modes.COLOR] = (useNew) ? 'color' : 'source-over'; + b[modes.LUMINOSITY] = (useNew) ? 'luminosity' : 'source-over'; + + PIXI.blendModesCanvas = b; + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class PIXI.BaseTexture + * @constructor + * @param source {String|Canvas} the source object (image or canvas) + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + */ +PIXI.BaseTexture = function(source, scaleMode, resolution) +{ + /** + * The Resolution of the texture. + * + * @property resolution + * @type Number + */ + this.resolution = resolution || 1; + + /** + * [read-only] The width of the base texture set when the image has loaded + * + * @property width + * @type Number + * @readOnly + */ + this.width = 100; + + /** + * [read-only] The height of the base texture set when the image has loaded + * + * @property height + * @type Number + * @readOnly + */ + this.height = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @property scaleMode + * @type {Number} + * @default PIXI.scaleModes.LINEAR + */ + this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT; + + /** + * [read-only] Set to true once the base texture has loaded + * + * @property hasLoaded + * @type Boolean + * @readOnly + */ + this.hasLoaded = false; + + /** + * The image source that is used to create the texture. + * + * @property source + * @type Image + */ + this.source = source; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * + * @property premultipliedAlpha + * @type Boolean + * @default true + */ + this.premultipliedAlpha = true; + + // used for webGL + + /** + * @property _glTextures + * @type Array + * @private + */ + this._glTextures = []; + + /** + * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @property mipmap + * @type {Boolean} + */ + this.mipmap = false; + + /** + * The multi texture batching index number. + * @property textureIndex + * @type Number + */ + this.textureIndex = 0; + + /** + * @property _dirty + * @type Array + * @private + */ + this._dirty = [true, true, true, true]; + + if (!source) + { + return; + } + + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { + this.hasLoaded = true; + this.width = this.source.naturalWidth || this.source.width; + this.height = this.source.naturalHeight || this.source.height; + this.dirty(); + } + + /** + * A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch. + * + * You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture) + * that has children that you do want to render, without causing a batch flush in the process. + * + * @property skipRender + * @type Boolean + */ + this.skipRender = false; + + /** + * @property _powerOf2 + * @type Boolean + * @private + */ + this._powerOf2 = false; + +}; + +PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture; + +/** + * Forces this BaseTexture to be set as loaded, with the given width and height. + * Then calls BaseTexture.dirty. + * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have. + * + * @method PIXI.BaseTexture#forceLoaded + * @param {number} width - The new width to force the BaseTexture to be. + * @param {number} height - The new height to force the BaseTexture to be. + */ +PIXI.BaseTexture.prototype.forceLoaded = function(width, height) +{ + this.hasLoaded = true; + this.width = width; + this.height = height; + this.dirty(); +}; + +/** + * Destroys this base texture + * + * @method PIXI.BaseTexture#destroy + */ +PIXI.BaseTexture.prototype.destroy = function() +{ + if (this.source) + { + Phaser.CanvasPool.removeByCanvas(this.source); + } + + this.source = null; + + this.unloadFromGPU(); +}; + +/** + * Sets all glTextures to be dirty. + * + * @method PIXI.BaseTexture#dirty + */ +PIXI.BaseTexture.prototype.dirty = function() +{ + for (var i = 0; i < this._glTextures.length; i++) + { + this._dirty[i] = true; + } +}; + +/** + * Removes the base texture from the GPU, useful for managing resources on the GPU. + * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it. + * + * @method PIXI.BaseTexture#unloadFromGPU + */ +PIXI.BaseTexture.prototype.unloadFromGPU = function() +{ + this.dirty(); + + // delete the webGL textures if any. + for (var i = this._glTextures.length - 1; i >= 0; i--) + { + var glTexture = this._glTextures[i]; + var gl = PIXI.glContexts[i]; + + if(gl && glTexture) + { + gl.deleteTexture(glTexture); + } + + } + + this._glTextures.length = 0; + + this.dirty(); +}; + +/** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @method PIXI.BaseTexture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + * @return {BaseTexture} + */ +PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode, resolution) +{ + if (canvas.width === 0) + { + canvas.width = 1; + } + + if (canvas.height === 0) + { + canvas.height = 1; + } + + resolution = resolution || 1; + + return new PIXI.BaseTexture(canvas, scaleMode, resolution); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * TextureSilentFail is a boolean that defaults to `false`. + * If `true` then {@link PIXI.Texture#setFrame} will no longer throw an error if the texture dimensions are incorrect. + * Instead {@link PIXI.Texture#valid} will be set to `false` (#1556) + * + * @type {boolean} + */ +PIXI.TextureSilentFail = false; + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used. + * + * @class PIXI.Texture + * @constructor + * @param baseTexture {BaseTexture} The base texture source to create the texture from + * @param frame {Rectangle} The rectangle frame of the texture to show + * @param [crop] {Rectangle} The area of original texture + * @param [trim] {Rectangle} Trimmed texture rectangle + */ +PIXI.Texture = function(baseTexture, frame, crop, trim) +{ + /** + * Does this Texture have any frame data assigned to it? + * + * @property noFrame + * @type Boolean + */ + this.noFrame = false; + + if (!frame) + { + this.noFrame = true; + frame = new PIXI.Rectangle(0,0,1,1); + } + + if (baseTexture instanceof PIXI.Texture) + { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = baseTexture; + + /** + * The frame specifies the region of the base texture that this texture uses + * + * @property frame + * @type Rectangle + */ + this.frame = frame; + + /** + * The texture trim data. + * + * @property trim + * @type Rectangle + */ + this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @property valid + * @type Boolean + */ + this.valid = false; + + /** + * Is this a tiling texture? As used by the likes of a TilingSprite. + * + * @property isTiling + * @type Boolean + */ + this.isTiling = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @property requiresUpdate + * @type Boolean + */ + this.requiresUpdate = false; + + /** + * This will let a renderer know that a tinted parent has updated its texture. + * + * @property requiresReTint + * @type Boolean + */ + this.requiresReTint = false; + + /** + * The WebGL UV data cache. + * + * @property _uvs + * @type Object + * @private + */ + this._uvs = null; + + /** + * The width of the Texture in pixels. + * + * @property width + * @type Number + */ + this.width = 0; + + /** + * The height of the Texture in pixels. + * + * @property height + * @type Number + */ + this.height = 0; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @property crop + * @type Rectangle + */ + this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1); + + /** + * A flag that controls if this frame is rotated or not. + * Rotation allows you to use rotated frames in texture atlas packing, it has nothing to do with + * Sprite rotation. + * + * @property rotated + * @type Boolean + */ + this.rotated = false; + + if (baseTexture.hasLoaded) + { + if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + this.setFrame(frame); + } + +}; + +PIXI.Texture.prototype.constructor = PIXI.Texture; + +/** + * Called when the base texture is loaded + * + * @method PIXI.Texture#onBaseTextureLoaded + * @private + */ +PIXI.Texture.prototype.onBaseTextureLoaded = function() +{ + var baseTexture = this.baseTexture; + + if (this.noFrame) + { + this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } + + this.setFrame(this.frame); +}; + +/** + * Destroys this texture + * + * @method PIXI.Texture#destroy + * @param destroyBase {Boolean} Whether to destroy the base texture as well + */ +PIXI.Texture.prototype.destroy = function(destroyBase) +{ + if (destroyBase) this.baseTexture.destroy(); + + this.valid = false; +}; + +/** + * Specifies the region of the baseTexture that this texture will use. + * + * @method PIXI.Texture#setFrame + * @param frame {Rectangle} The frame of the texture to set it to + */ +PIXI.Texture.prototype.setFrame = function(frame) +{ + this.noFrame = false; + + this.frame = frame; + this.width = frame.width; + this.height = frame.height; + + this.crop.x = frame.x; + this.crop.y = frame.y; + this.crop.width = frame.width; + this.crop.height = frame.height; + + if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { + if (!PIXI.TextureSilentFail) + { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + this.valid = false; + return; + } + + this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + + if (this.trim) + { + this.width = this.trim.width; + this.height = this.trim.height; + this.frame.width = this.trim.width; + this.frame.height = this.trim.height; + } + + if (this.valid) this._updateUvs(); + +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvs + * @private + */ +PIXI.Texture.prototype._updateUvs = function() +{ + if(!this._uvs)this._uvs = new PIXI.TextureUvs(); + + var frame = this.crop; + 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; +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvsInverted + * @private + */ +PIXI.Texture.prototype._updateUvsInverted = function () { + + if (!this._uvs) { this._uvs = new PIXI.TextureUvs(); } + + var frame = this.crop; + 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.height) / tw; + this._uvs.y1 = frame.y / th; + + this._uvs.x2 = (frame.x + frame.height) / tw; + this._uvs.y2 = (frame.y + frame.width) / th; + + this._uvs.x3 = frame.x / tw; + this._uvs.y3 = (frame.y + frame.width) / th; + +}; + +/** + * Helper function that creates a new a Texture based on the given canvas element. + * + * @static + * @method PIXI.Texture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @return {Texture} + */ +PIXI.Texture.fromCanvas = function(canvas, scaleMode) +{ + var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode); + + return new PIXI.Texture(baseTexture); +}; + +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.y3 = 0; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = PIXI; + } + exports.PIXI = PIXI; + } else if (typeof define !== 'undefined' && define.amd) { + define('PIXI', (function() { return root.PIXI = PIXI; })() ); + } else { + root.PIXI = PIXI; + } + + return PIXI; +}).call(this); +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +(function(){ + + var root = this; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @namespace Phaser +*/ +var Phaser = Phaser || { // jshint ignore:line + + /** + * The Phaser version number. + * @constant Phaser.VERSION + * @type {string} + */ + VERSION: '2.10.0', + + /** + * An array of Phaser game instances. + * @constant Phaser.GAMES + * @type {array} + */ + GAMES: [], + + /** + * AUTO renderer - picks between WebGL or Canvas based on device. + * @constant Phaser.AUTO + * @type {integer} + */ + AUTO: 0, + + /** + * Canvas Renderer. + * @constant Phaser.CANVAS + * @type {integer} + */ + CANVAS: 1, + + /** + * WebGL Renderer. + * @constant Phaser.WEBGL + * @type {integer} + */ + WEBGL: 2, + + /** + * Headless renderer (not visual output) + * @constant Phaser.HEADLESS + * @type {integer} + */ + HEADLESS: 3, + + /** + * WebGL Renderer with MultiTexture support enabled. + * @constant Phaser.WEBGL_MULTI + * @type {integer} + */ + WEBGL_MULTI: 4, + + /** + * Direction constant. + * @constant Phaser.NONE + * @type {integer} + */ + NONE: 0, + + /** + * Direction constant. + * @constant Phaser.LEFT + * @type {integer} + */ + LEFT: 1, + + /** + * Direction constant. + * @constant Phaser.RIGHT + * @type {integer} + */ + RIGHT: 2, + + /** + * Direction constant. + * @constant Phaser.UP + * @type {integer} + */ + UP: 3, + + /** + * Direction constant. + * @constant Phaser.DOWN + * @type {integer} + */ + DOWN: 4, + + /** + * Game Object type. + * @constant Phaser.SPRITE + * @type {integer} + */ + SPRITE: 0, + + /** + * Game Object type. + * @constant Phaser.BUTTON + * @type {integer} + */ + BUTTON: 1, + + /** + * Game Object type. + * @constant Phaser.IMAGE + * @type {integer} + */ + IMAGE: 2, + + /** + * Game Object type. + * @constant Phaser.GRAPHICS + * @type {integer} + */ + GRAPHICS: 3, + + /** + * Game Object type. + * @constant Phaser.TEXT + * @type {integer} + */ + TEXT: 4, + + /** + * Game Object type. + * @constant Phaser.TILESPRITE + * @type {integer} + */ + TILESPRITE: 5, + + /** + * Game Object type. + * @constant Phaser.BITMAPTEXT + * @type {integer} + */ + BITMAPTEXT: 6, + + /** + * Game Object type. + * @constant Phaser.GROUP + * @type {integer} + */ + GROUP: 7, + + /** + * Game Object type. + * @constant Phaser.RENDERTEXTURE + * @type {integer} + */ + RENDERTEXTURE: 8, + + /** + * Game Object type. + * @constant Phaser.TILEMAP + * @type {integer} + */ + TILEMAP: 9, + + /** + * Game Object type. + * @constant Phaser.TILEMAPLAYER + * @type {integer} + */ + TILEMAPLAYER: 10, + + /** + * Game Object type. + * @constant Phaser.EMITTER + * @type {integer} + */ + EMITTER: 11, + + /** + * Game Object type. + * @constant Phaser.POLYGON + * @type {integer} + */ + POLYGON: 12, + + /** + * Game Object type. + * @constant Phaser.BITMAPDATA + * @type {integer} + */ + BITMAPDATA: 13, + + /** + * Game Object type. + * @constant Phaser.CANVAS_FILTER + * @type {integer} + */ + CANVAS_FILTER: 14, + + /** + * Game Object type. + * @constant Phaser.WEBGL_FILTER + * @type {integer} + */ + WEBGL_FILTER: 15, + + /** + * Game Object type. + * @constant Phaser.ELLIPSE + * @type {integer} + */ + ELLIPSE: 16, + + /** + * Game Object type. + * @constant Phaser.SPRITEBATCH + * @type {integer} + */ + SPRITEBATCH: 17, + + /** + * Game Object type. + * @constant Phaser.RETROFONT + * @type {integer} + */ + RETROFONT: 18, + + /** + * Game Object type. + * @constant Phaser.POINTER + * @type {integer} + */ + POINTER: 19, + + /** + * Game Object type. + * @constant Phaser.ROPE + * @type {integer} + */ + ROPE: 20, + + /** + * Game Object type. + * @constant Phaser.CIRCLE + * @type {integer} + */ + CIRCLE: 21, + + /** + * Game Object type. + * @constant Phaser.RECTANGLE + * @type {integer} + */ + RECTANGLE: 22, + + /** + * Game Object type. + * @constant Phaser.LINE + * @type {integer} + */ + LINE: 23, + + /** + * Game Object type. + * @constant Phaser.MATRIX + * @type {integer} + */ + MATRIX: 24, + + /** + * Game Object type. + * @constant Phaser.POINT + * @type {integer} + */ + POINT: 25, + + /** + * Game Object type. + * @constant Phaser.ROUNDEDRECTANGLE + * @type {integer} + */ + ROUNDEDRECTANGLE: 26, + + /** + * Game Object type. + * @constant Phaser.CREATURE + * @type {integer} + */ + CREATURE: 27, + + /** + * Game Object type. + * @constant Phaser.VIDEO + * @type {integer} + */ + VIDEO: 28, + + /** + * Game Object type. + * @constant Phaser.PENDING_ATLAS + * @type {integer} + */ + PENDING_ATLAS: -1, + + /** + * A horizontal orientation + * @constant Phaser.HORIZONTAL + * @type {integer} + */ + HORIZONTAL: 0, + + /** + * A vertical orientation + * @constant Phaser.VERTICAL + * @type {integer} + */ + VERTICAL: 1, + + /** + * A landscape orientation + * @constant Phaser.LANDSCAPE + * @type {integer} + */ + LANDSCAPE: 0, + + /** + * A portrait orientation + * @constant Phaser.PORTRAIT + * @type {integer} + */ + PORTRAIT: 1, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face up. + * @constant Phaser.ANGLE_UP + * @type {integer} + */ + ANGLE_UP: 270, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face down. + * @constant Phaser.ANGLE_DOWN + * @type {integer} + */ + ANGLE_DOWN: 90, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face left. + * @constant Phaser.ANGLE_LEFT + * @type {integer} + */ + ANGLE_LEFT: 180, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face right. + * @constant Phaser.ANGLE_RIGHT + * @type {integer} + */ + ANGLE_RIGHT: 0, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north east. + * @constant Phaser.ANGLE_NORTH_EAST + * @type {integer} + */ + ANGLE_NORTH_EAST: 315, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north west. + * @constant Phaser.ANGLE_NORTH_WEST + * @type {integer} + */ + ANGLE_NORTH_WEST: 225, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south east. + * @constant Phaser.ANGLE_SOUTH_EAST + * @type {integer} + */ + ANGLE_SOUTH_EAST: 45, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south west. + * @constant Phaser.ANGLE_SOUTH_WEST + * @type {integer} + */ + ANGLE_SOUTH_WEST: 135, + + /** + * A constant representing a top-left alignment or position. + * @constant Phaser.TOP_LEFT + * @type {integer} + */ + TOP_LEFT: 0, + + /** + * A constant representing a top-center alignment or position. + * @constant Phaser.TOP_CENTER + * @type {integer} + */ + TOP_CENTER: 1, + + /** + * A constant representing a top-right alignment or position. + * @constant Phaser.TOP_RIGHT + * @type {integer} + */ + TOP_RIGHT: 2, + + /** + * A constant representing a left-top alignment or position. + * @constant Phaser.Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_TOP: 3, + + /** + * A constant representing a left-center alignment or position. + * @constant Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_CENTER: 4, + + /** + * A constant representing a left-bottom alignment or position. + * @constant Phaser.LEFT_BOTTOM + * @type {integer} + */ + LEFT_BOTTOM: 5, + + /** + * A constant representing a center alignment or position. + * @constant Phaser.CENTER + * @type {integer} + */ + CENTER: 6, + + /** + * A constant representing a right-top alignment or position. + * @constant Phaser.RIGHT_TOP + * @type {integer} + */ + RIGHT_TOP: 7, + + /** + * A constant representing a right-center alignment or position. + * @constant Phaser.RIGHT_CENTER + * @type {integer} + */ + RIGHT_CENTER: 8, + + /** + * A constant representing a right-bottom alignment or position. + * @constant Phaser.RIGHT_BOTTOM + * @type {integer} + */ + RIGHT_BOTTOM: 9, + + /** + * A constant representing a bottom-left alignment or position. + * @constant Phaser.BOTTOM_LEFT + * @type {integer} + */ + BOTTOM_LEFT: 10, + + /** + * A constant representing a bottom-center alignment or position. + * @constant Phaser.BOTTOM_CENTER + * @type {integer} + */ + BOTTOM_CENTER: 11, + + /** + * A constant representing a bottom-right alignment or position. + * @constant Phaser.BOTTOM_RIGHT + * @type {integer} + */ + BOTTOM_RIGHT: 12, + + /** + * Various blend modes supported by Pixi. See the samples in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing Canvas Tutorial: Compositing}. + * + * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * + * @constant {Object} Phaser.blendModes + * @property {Number} blendModes.NORMAL - Draws new shapes on top of the existing content. This is the default setting. + * @property {Number} blendModes.ADD - Where both shapes overlap the color is determined by adding color values. + * @property {Number} blendModes.MULTIPLY - The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer, making a darker picture. + * @property {Number} blendModes.SCREEN - The pixels are inverted, multiplied, and inverted again, making a lighter picture. + * @property {Number} blendModes.OVERLAY + * @property {Number} blendModes.DARKEN + * @property {Number} blendModes.LIGHTEN + * @property {Number} blendModes.COLOR_DODGE + * @property {Number} blendModes.COLOR_BURN + * @property {Number} blendModes.HARD_LIGHT + * @property {Number} blendModes.SOFT_LIGHT + * @property {Number} blendModes.DIFFERENCE + * @property {Number} blendModes.EXCLUSION + * @property {Number} blendModes.HUE + * @property {Number} blendModes.SATURATION + * @property {Number} blendModes.COLOR + * @property {Number} blendModes.LUMINOSITY + * @static + */ + 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 + }, + + /** + * The scale modes that are supported by Pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @constant {Object} Phaser.scaleModes + * @property {Number} Phaser.scaleModes.DEFAULT=LINEAR + * @property {Number} Phaser.scaleModes.LINEAR Smooth scaling + * @property {Number} Phaser.scaleModes.NEAREST Pixelating scaling + * @static + */ + scaleModes: { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 + }, + + PIXI: PIXI || {}, + + // Used to create IDs for various Pixi objects. + _UID: 0 + +}; + +/** +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc +if (!Math.trunc) { + Math.trunc = function trunc(x) { + return x < 0 ? Math.ceil(x) : Math.floor(x); + }; +} + +/** +* A polyfill for Function.prototype.bind +*/ +if (!Function.prototype.bind) { + + /* jshint freeze: false */ + 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)) + { + /* jshint supernew: true */ + return new F; + } + })(target.prototype); + + return bound; + }; + })(); +} + +/** +* A polyfill for Array.isArray +*/ +if (!Array.isArray) +{ + Array.isArray = function (arg) + { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + +/** +* A polyfill for Array.forEach +* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach +*/ +if (!Array.prototype.forEach) +{ + Array.prototype.forEach = function(fun /*, thisArg */) + { + "use strict"; + + if (this === void 0 || this === null) + { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + if (typeof fun !== "function") + { + throw new TypeError(); + } + + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + + for (var i = 0; i < len; i++) + { + if (i in t) + { + fun.call(thisArg, t[i], i, t); + } + } + }; +} + +/** +* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 +* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ +* Cameron Foale (http://www.kibibu.com) +*/ +if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object") +{ + var CheapArray = function(type) + { + var proto = new Array(); // jshint ignore:line + + window[type] = function(arg) { + + if (typeof(arg) === "number") + { + Array.call(this, arg); + this.length = arg; + + for (var i = 0; i < this.length; i++) + { + this[i] = 0; + } + } + else + { + Array.call(this, arg.length); + + this.length = arg.length; + + for (var i = 0; i < this.length; i++) + { + this[i] = arg[i]; + } + } + }; + + window[type].prototype = proto; + window[type].constructor = window[type]; + }; + + CheapArray('Float32Array'); // jshint ignore:line + CheapArray('Uint32Array'); // jshint ignore:line + CheapArray('Uint16Array'); // jshint ignore:line + CheapArray('Int16Array'); // jshint ignore:line + CheapArray('ArrayBuffer'); // jshint ignore:line +} + +/** + * Also fix for the absent console in IE9 + */ +if (!window.console) +{ + window.console = {}; + window.console.log = window.console.assert = function(){}; + window.console.warn = window.console.assert = function(){}; +} + +/** + * Fix for Object.assign not existing on older devices + */ + +if (!Object.assign) { + /* jshint -W098 */ + // We include `varArgs` (unused) to ensure Object.assign.length === 2 + Object.assign = function(target, varArgs) { + /* jshint +W098 */ + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + var hasOwn = Object.prototype.hasOwnProperty; + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (hasOwn.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @class Phaser.Utils +* @static +*/ +Phaser.Utils = { + + /** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @method Phaser.Utils.reverseString + * @param {string} string - The string to be reversed. + * @return {string} The reversed string. + */ + reverseString: function (string) { + + return string.split('').reverse().join(''); + + }, + + /** + * Gets an object's property by string. + * + * @method Phaser.Utils.getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + getProperty: function(obj, name) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + return obj[name]; + case 2: + return obj[parts[0]][parts[1]]; + case 3: + return obj[parts[0]][parts[1]][parts[2]]; + case 4: + return obj[parts[0]][parts[1]][parts[2]][parts[3]]; + default: + return this._getProperty(obj, name); + } + + }, + + /** + * Sets an object's properties from a map of property names and values. + * + * ```javascript + * Phaser.Utils.setProperties(sprite, { + * 'animations.paused': true, + * 'body.enable': false, + * 'input.draggable': true, + * }); + * ``` + * + * @method Phaser.Utils.setProperties + * @param {object} obj - The object to modify. + * @param {object} props - The property names and values to set on the object (see {@link #setProperty}). + * @return {object} The modified object. + */ + setProperties: function(obj, props) { + + for (var name in props) + { + this.setProperty(obj, name, props[name]); + } + + return obj; + + }, + + /** + * Sets an object's property by name and value. + * + * ```javascript + * Phaser.Utils.setProperty(sprite, 'body.velocity.x', 60); + * ``` + * + * @method Phaser.Utils.setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + + setProperty: function(obj, name, value) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + obj[name] = value; + break; + case 2: + obj[parts[0]][parts[1]] = value; + break; + case 3: + obj[parts[0]][parts[1]][parts[2]] = value; + break; + case 4: + obj[parts[0]][parts[1]][parts[2]][parts[3]] = value; + break; + default: + this._setProperty(obj, name, value); + } + }, + + /** + * Gets an object's property by string. + * + * @private + * @method Phaser.Utils._getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property whose value will be returned. + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + _getProperty: function(obj, name) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + val = obj; + + while (i < len) + { + var key = parts[i]; + + if (val != null) + { + val = val[key]; + i++; + } + else + { + return undefined; + } + } + + return val; + + }, + + /** + * Sets an object's property by name and value. + * + * @private + * @method Phaser.Utils._setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + _setProperty: function(obj, name, value) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + currentObj = obj, + key = parts[0]; + + if (len === 1) + { + obj[name] = value; + } + else + { + while (i < (len - 1)) + { + currentObj = currentObj[key]; + i++; + key = parts[i]; + } + + currentObj[key] = value; + } + + return obj; + + }, + + /** + * Generate a random bool result based on the chance value. + * + * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance + * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. + * + * @method Phaser.Utils#chanceRoll + * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). + * @return {boolean} True if the roll passed, or false otherwise. + */ + chanceRoll: function (chance) { + if (chance === undefined) { chance = 50; } + return chance > 0 && (Math.random() * 100 <= chance); + }, + + /** + * Choose between one of two values randomly. + * + * @method Phaser.Utils#randomChoice + * @param {any} choice1 + * @param {any} choice2 + * @return {any} The randomly selected choice + */ + randomChoice: function (choice1, choice2) { + return (Math.random() < 0.5) ? choice1 : choice2; + }, + + /** + * Get a unit dimension from a string. + * + * @method Phaser.Utils.parseDimension + * @param {string|number} size - The size to parse. + * @param {number} dimension - The window dimension to check. + * @return {number} The parsed dimension. + */ + parseDimension: function (size, dimension) { + + var f = 0; + var px = 0; + + if (typeof size === 'string') + { + // %? + if (size.substr(-1) === '%') + { + f = parseInt(size, 10) / 100; + + if (dimension === 0) + { + px = window.innerWidth * f; + } + else + { + px = window.innerHeight * f; + } + } + else + { + px = parseInt(size, 10); + } + } + else + { + px = size; + } + + return px; + + }, + + /** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @method Phaser.Utils.pad + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * @return {string} The padded string. + */ + pad: function (str, len, pad, dir) { + + if (len === undefined) { var len = 0; } + if (pad === undefined) { var pad = ' '; } + if (dir === undefined) { var dir = 3; } + + str = str.toString(); + + 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; + + }, + + /** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * @method Phaser.Utils.isPlainObject + * @param {object} obj - The object to inspect. + * @return {boolean} - true if the object is plain, otherwise false. + */ + isPlainObject: function (obj) { + + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) + { + return false; + } + + // Support: Firefox <20 + // The try/catch suppresses exceptions thrown when attempting to access + // the "constructor" property of certain host objects, ie. |window.location| + // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + try { + if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) + { + return false; + } + } catch (e) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + /** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @method Phaser.Utils.extend + * @param {boolean} deep - Perform a deep copy? + * @param {object} target - The target object to copy to. + * @return {object} The extended object. + */ + extend: function () { + + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if (typeof target === "boolean") + { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } + + for (; i < length; i++) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) + { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = Phaser.Utils.extend(deep, clone, copy); + + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; + + }, + + /** + * Mixes in an existing mixin object with the target. + * + * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` + * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and + * the result is assigned directly. + * + * @method Phaser.Utils.mixinPrototype + * @param {object} target - The target object to receive the new functions. + * @param {object} mixin - The object to copy the functions from. + * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not? + */ + mixinPrototype: function (target, mixin, replace) { + + if (replace === undefined) { replace = false; } + + var mixinKeys = Object.keys(mixin); + + for (var i = 0; i < mixinKeys.length; i++) + { + var key = mixinKeys[i]; + var value = mixin[key]; + + if (!replace && (key in target)) + { + // Not overwriting existing property + continue; + } + else + { + if (value && + (typeof value.get === 'function' || typeof value.set === 'function')) + { + // Special case for classes like Phaser.Point which has a 'set' function! + if (typeof value.clone === 'function') + { + target[key] = value.clone(); + } + else + { + Object.defineProperty(target, key, value); + } + } + else + { + target[key] = value; + } + } + } + + }, + + /** + * Mixes the source object into the destination object, returning the newly modified destination object. + * Based on original code by @mudcube + * + * @method Phaser.Utils.mixin + * @param {object} from - The object to copy (the source object). + * @param {object} to - The object to copy to (the destination object). + * @return {object} The modified destination object. + */ + mixin: function (from, to) { + + if (!from || typeof (from) !== "object") + { + return to; + } + + for (var key in from) + { + var o = from[key]; + + if (o.childNodes || o.cloneNode) + { + continue; + } + + var type = typeof (from[key]); + + if (!from[key] || type !== "object") + { + to[key] = from[key]; + } + else + { + // Clone sub-object + if (typeof (to[key]) === type) + { + to[key] = Phaser.Utils.mixin(from[key], to[key]); + } + else + { + to[key] = Phaser.Utils.mixin(from[key], new o.constructor()); + } + } + } + + return to; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. +* If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. +* +* @class Phaser.Circle +* @constructor +* @param {number} [x=0] - The x coordinate of the center of the circle. +* @param {number} [y=0] - The y coordinate of the center of the circle. +* @param {number} [diameter=0] - The diameter of the circle. +*/ +Phaser.Circle = function (x, y, diameter) { + + x = x || 0; + y = y || 0; + diameter = diameter || 0; + + /** + * @property {number} x - The x coordinate of the center of the circle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the center of the circle. + */ + this.y = y; + + /** + * @property {number} _diameter - The diameter of the circle. + * @private + */ + this._diameter = diameter; + + /** + * @property {number} _radius - The radius of the circle. + * @private + */ + this._radius = 0; + + if (diameter > 0) + { + this._radius = diameter * 0.5; + } + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.CIRCLE; + +}; + +Phaser.Circle.prototype = { + + /** + * The circumference of the circle. + * + * @method Phaser.Circle#circumference + * @return {number} The circumference of the circle. + */ + circumference: function () { + + return 2 * (Math.PI * this._radius); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Circle. + * + * @method Phaser.Circle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = 2 * Math.PI * Math.random(); + var u = Math.random() + Math.random(); + var r = (u > 1) ? 2 - u : u; + var x = r * Math.cos(t); + var y = r * Math.sin(t); + + out.x = this.x + (x * this.radius); + out.y = this.y + (y * this.radius); + + return out; + + }, + + /** + * Returns the framing rectangle of the circle as a Phaser.Rectangle object. + * + * @method Phaser.Circle#getBounds + * @return {Phaser.Rectangle} The bounds of the Circle. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter); + + }, + + /** + * Sets the members of Circle to the specified values. + * @method Phaser.Circle#setTo + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} diameter - The diameter of the circle. + * @return {Circle} This circle object. + */ + setTo: function (x, y, diameter) { + + this.x = x; + this.y = y; + this._diameter = diameter; + this._radius = diameter * 0.5; + + return this; + + }, + + /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method Phaser.Circle#copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.diameter); + + }, + + /** + * Copies the x, y and diameter properties from this Circle to any given object. + * @method Phaser.Circle#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.diameter = this._diameter; + + return dest; + + }, + + /** + * Returns the distance from the center of the Circle object to the given object + * (can be Circle, Point or anything with x/y properties) + * @method Phaser.Circle#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round=false] - Round the distance to the nearest integer. + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y); + return round ? Math.round(distance) : distance; + + }, + + /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. + * @method Phaser.Circle#clone + * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} The cloned Circle object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Circle(this.x, this.y, this.diameter); + } + else + { + output.setTo(this.x, this.y, this.diameter); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Circle object. + * @method Phaser.Circle#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this circle, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Circle.contains(this, x, y); + + }, + + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method Phaser.Circle#circumferencePoint + * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ + circumferencePoint: function (angle, asDegrees, out) { + + return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out); + + }, + + + /** + * Creates or positions points on the circle. + * + * The points are equally distributed in the half-closed interval [startAngle, endAngle). The default arc is the entire circle. + * + * If the `out` argument is omitted, this method creates and returns an array of {@link Phaser.Point points}. If an array is passed as `out`, its items are treated as points and placed in the same way. + * + * @param {type} [steps=60] - The number of points to place. + * @param {type} [startAngle=0] - The starting angle in radians (unless asDegrees is true). + * @param {type} [endAngle=Phaser.Math.PI2] - The end angle in radians (unless asDegrees is true). + * @param {type} [asDegrees=false] - Are the given angles in radians (false) or degrees (true)? + * @param {any[]} [out] - An array of points or point-like objects (e.g., sprites). It should start at index 0 and its length should be equal to or greater than `steps`. + * @return {any[]} - The modified `out` argument or a new array of points. + */ + sample: function (steps, startAngle, endAngle, asDegrees, out) { + + if (!steps) { steps = 60; } + if (startAngle == null) { startAngle = 0; } + if (endAngle == null) { endAngle = Phaser.Math.PI2; } + if (!out) { out = []; } + + var i = 0; + + while (i < steps) + { + this.circumferencePoint( + Phaser.Math.linear(startAngle, endAngle, i / steps), + asDegrees, + out[i] || (out[i] = new Phaser.Point()) + ); + + i += 1; + } + + return out; + + }, + + /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method Phaser.Circle#offset + * @param {number} dx - Moves the x value of the Circle object by this amount. + * @param {number} dy - Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Circle#offsetPoint + * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). + * @return {Circle} This Circle object. + */ + offsetPoint: function (point) { + return this.offset(point.x, point.y); + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Circle#toString + * @return {string} a string representation of the instance. + */ + toString: function () { + return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; + } + +}; + +Phaser.Circle.prototype.constructor = Phaser.Circle; + +/** +* The largest distance between any two points on the circle. The same as the radius * 2. +* +* @name Phaser.Circle#diameter +* @property {number} diameter - Gets or sets the diameter of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "diameter", { + + get: function () { + return this._diameter; + }, + + set: function (value) { + + if (value > 0) + { + this._diameter = value; + this._radius = value * 0.5; + } + } + +}); + +/** +* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. +* @name Phaser.Circle#radius +* @property {number} radius - Gets or sets the radius of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "radius", { + + get: function () { + return this._radius; + }, + + set: function (value) { + + if (value > 0) + { + this._radius = value; + this._diameter = value * 2; + } + + } + +}); + +/** +* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#left +* @propety {number} left - Gets or sets the value of the leftmost point of the circle. +*/ +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; + } + + } + +}); + +/** +* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#right +* @property {number} right - Gets or sets the value of the rightmost point of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "right", { + + get: function () { + return this.x + this._radius; + }, + + set: function (value) { + + if (value < this.x) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.x; + } + + } + +}); + +/** +* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#top +* @property {number} top - Gets or sets the top of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "top", { + + get: function () { + return this.y - this._radius; + }, + + set: function (value) { + + if (value > this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = this.y - value; + } + + } + +}); + +/** +* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#bottom +* @property {number} bottom - Gets or sets the bottom of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "bottom", { + + get: function () { + return this.y + this._radius; + }, + + set: function (value) { + + if (value < this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.y; + } + + } + +}); + +/** +* The area of this Circle. +* @name Phaser.Circle#area +* @property {number} area - The area of this circle. +* @readonly +*/ +Object.defineProperty(Phaser.Circle.prototype, "area", { + + get: function () { + + if (this._radius > 0) + { + return Math.PI * this._radius * this._radius; + } + else + { + return 0; + } + + } + +}); + +/** +* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. +* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. +* @name Phaser.Circle#empty +* @property {boolean} empty - Gets or sets the empty state of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "empty", { + + get: function () { + return (this._diameter === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Circle object. +* @method Phaser.Circle.contains +* @param {Phaser.Circle} a - The Circle to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this circle, otherwise false. +*/ +Phaser.Circle.contains = function (a, x, y) { + + // Check if x/y are within the bounds first + 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; + } + +}; + +/** +* Determines whether the two Circle objects match. This method compares the x, y and diameter properties. +* @method Phaser.Circle.equals +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. +*/ +Phaser.Circle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.diameter === b.diameter); + +}; + +/** +* Determines whether the two Circle objects intersect. +* This method checks the radius distances between the two Circle objects to see if they intersect. +* @method Phaser.Circle.intersects +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. +*/ +Phaser.Circle.intersects = function (a, b) { + + return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius)); + +}; + +/** +* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. +* @method Phaser.Circle.circumferencePoint +* @param {Phaser.Circle} a - The first Circle object. +* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. +* @return {Phaser.Point} The Point object holding the result. +*/ +Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) { + + if (asDegrees === undefined) { asDegrees = false; } + if (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; + +}; + +/** +* Checks if the given Circle and Rectangle objects intersect. +* @method Phaser.Circle.intersectsRectangle +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Rectangle} r - The Rectangle object to test. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +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; + +}; + +/** +* Checks if the given Circle and Line objects intersect. +* @method Phaser.Circle.intersectsLine +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnpoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Circle.intersectsLine = function (c, l, returnPoints) { + var h = c.x; + var k = c.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = c.radius; + var b = c.radius; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Circle = Phaser.Circle; + +/** +* @author Richard Davey +* @author Chad Engler +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a Ellipse object. A curve on a plane surrounding two focal points. +* +* @class Phaser.Ellipse +* @constructor +* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [width=0] - The overall width of this ellipse. +* @param {number} [height=0] - The overall height of this ellipse. +*/ +Phaser.Ellipse = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.x = x; + + /** + * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.y = y; + + /** + * @property {number} width - The overall width of this ellipse. + */ + this.width = width; + + /** + * @property {number} height - The overall height of this ellipse. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ELLIPSE; + +}; + +Phaser.Ellipse.prototype = { + + /** + * Sets the members of the Ellipse to the specified values. + * @method Phaser.Ellipse#setTo + * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} width - The overall width of this ellipse. + * @param {number} height - The overall height of this ellipse. + * @return {Phaser.Ellipse} This Ellipse object. + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. + * + * @method Phaser.Ellipse#getBounds + * @return {Phaser.Rectangle} The bounds of the Ellipse. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Ellipse. + * + * @method Phaser.Ellipse#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Ellipse} This Ellipse object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Ellipse to any given object. + * @method Phaser.Ellipse#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function(dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. + * @method Phaser.Ellipse#clone + * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. + * @return {Phaser.Ellipse} The cloned Ellipse object. + */ + clone: function(output) { + + if (output === undefined || output === null) + { + output = new Phaser.Ellipse(this.x, this.y, this.width, this.height); + } + else + { + output.setTo(this.x, this.y, this.width, this.height); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Ellipse object. + * + * @method Phaser.Ellipse#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this ellipse, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Ellipse.contains(this, x, y); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Ellipse. + * + * @method Phaser.Ellipse#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var p = Math.random() * Math.PI * 2; + var r = Math.random(); + + out.x = Math.sqrt(r) * Math.cos(p); + out.y = Math.sqrt(r) * Math.sin(p); + + out.x = this.x + (out.x * this.width / 2.0); + out.y = this.y + (out.y * this.height / 2.0); + + return out; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Ellipse#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]"; + } + +}; + +Phaser.Ellipse.prototype.constructor = Phaser.Ellipse; + +/** +* The left coordinate of the Ellipse. The same as the X coordinate. +* @name Phaser.Ellipse#left +* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + + this.x = value; + + } + +}); + +/** +* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. +* @name Phaser.Ellipse#right +* @property {number} right - Gets or sets the value of the rightmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "right", { + + get: function () { + return this.x + this.width; + }, + + set: function (value) { + + if (value < this.x) + { + this.width = 0; + } + else + { + this.width = value - this.x; + } + } + +}); + +/** +* The top of the Ellipse. The same as its y property. +* @name Phaser.Ellipse#top +* @property {number} top - Gets or sets the top of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "top", { + + get: function () { + return this.y; + }, + + set: function (value) { + this.y = value; + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. +* @name Phaser.Ellipse#bottom +* @property {number} bottom - Gets or sets the bottom of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value < this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + } + +}); + +/** +* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. +* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. +* @name Phaser.Ellipse#empty +* @property {boolean} empty - Gets or sets the empty state of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "empty", { + + get: function () { + return (this.width === 0 || this.height === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Ellipse object. +* +* @method Phaser.Ellipse.contains +* @param {Phaser.Ellipse} a - The Ellipse to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this ellipse, otherwise false. +*/ +Phaser.Ellipse.contains = function (a, x, y) { + + if (a.width <= 0 || a.height <= 0) { + return false; + } + + // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 + var normx = ((x - a.x) / a.width) - 0.5; + var normy = ((y - a.y) / a.height) - 0.5; + + normx *= normx; + normy *= normy; + + return (normx + normy < 0.25); + +}; + +/** +* Checks if the given Ellipse and Line objects intersect. +* @method Phaser.Ellipse.intersectsLine +* @param {Phaser.Ellipse} e - The Ellipse object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnPoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Ellipse.intersectsLine = function (e, l, returnPoints) { + var h = e.x; + var k = e.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = e.width / 2; + var b = e.height / 2; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Ellipse = Phaser.Ellipse; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Line object with a start and an end point. +* +* @class Phaser.Line +* @constructor +* @param {number} [x1=0] - The x coordinate of the start of the line. +* @param {number} [y1=0] - The y coordinate of the start of the line. +* @param {number} [x2=0] - The x coordinate of the end of the line. +* @param {number} [y2=0] - The y coordinate of the end of the line. +*/ +Phaser.Line = function (x1, y1, x2, y2) { + + x1 = x1 || 0; + y1 = y1 || 0; + x2 = x2 || 0; + y2 = y2 || 0; + + /** + * @property {Phaser.Point} start - The start point of the line. + */ + this.start = new Phaser.Point(x1, y1); + + /** + * @property {Phaser.Point} end - The end point of the line. + */ + this.end = new Phaser.Point(x2, y2); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.LINE; + +}; + +Phaser.Line.prototype = { + + /** + * Sets the components of the Line to the specified values. + * + * @method Phaser.Line#setTo + * @param {number} [x1=0] - The x coordinate of the start of the line. + * @param {number} [y1=0] - The y coordinate of the start of the line. + * @param {number} [x2=0] - The x coordinate of the end of the line. + * @param {number} [y2=0] - The y coordinate of the end of the line. + * @return {Phaser.Line} This line object + */ + setTo: function (x1, y1, x2, y2) { + + this.start.setTo(x1, y1); + this.end.setTo(x2, y2); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given points. + * + * @param {any} start - A {@link Phaser.Point} or point-like object. + * @param {any} end - A {@link Phaser.Point} or point-like object. + * @return {Phaser.Line} - This line object. + */ + fromPoints: function (start, end) { + + this.setTo(start.x, start.y, end.x, end.y); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given sprites. + * Can optionally be calculated from their center coordinates. + * + * @method Phaser.Line#fromSprite + * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {boolean} [useCenter=false] - If true it will use startSprite.centerX, if false startSprite.x. + * @return {Phaser.Line} This line object + */ + fromSprite: function (startSprite, endSprite, useCenter) { + + if (useCenter === undefined) { useCenter = false; } + + if (useCenter) + { + return this.setTo(startSprite.centerX, startSprite.centerY, endSprite.centerX, endSprite.centerY); + } + + return this.fromPoints(startSprite, endSprite); + + }, + + /** + * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. + * + * @method Phaser.Line#fromAngle + * @param {number} x - The x coordinate of the start of the line. + * @param {number} y - The y coordinate of the start of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line in pixels. + * @return {Phaser.Line} This line object + */ + fromAngle: function (x, y, angle, length) { + + this.start.setTo(x, y); + this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length)); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place from the center of the line. + * If you wish to rotate around a different point see Line.rotateAround. + * + * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. + * + * @method Phaser.Line#rotate + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotate: function (angle, asDegrees) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + this.start.rotate(cx, cy, angle, asDegrees); + this.end.rotate(cx, cy, angle, asDegrees); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place around the coordinates given. + * + * @method Phaser.Line#rotateAround + * @param {number} x - The x coordinate to offset the rotation from. + * @param {number} y - The y coordinate to offset the rotation from. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotateAround: function (x, y, angle, asDegrees) { + + this.start.rotate(x, y, angle, asDegrees); + this.end.rotate(x, y, angle, asDegrees); + + return this; + + }, + + /** + * Checks for intersection between this line and another Line. + * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * + * @method Phaser.Line#intersects + * @param {Phaser.Line} line - The line to check against this one. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ + intersects: function (line, asSegment, result) { + + return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result); + + }, + + /** + * Returns the reflected angle between two lines. + * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. + * + * @method Phaser.Line#reflect + * @param {Phaser.Line} line - The line to reflect off this line. + * @return {number} The reflected angle in radians. + */ + reflect: function (line) { + + return Phaser.Line.reflect(this, line); + + }, + + /** + * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. + * + * @method Phaser.Line#midPoint + * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. + * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. + */ + midPoint: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = (this.start.x + this.end.x) / 2; + out.y = (this.start.y + this.end.y) / 2; + + return out; + + }, + + /** + * Centers this Line on the given coordinates. + * + * The line is centered by positioning the start and end points so that the lines midpoint matches + * the coordinates given. + * + * @method Phaser.Line#centerOn + * @param {number} x - The x position to center the line on. + * @param {number} y - The y position to center the line on. + * @return {Phaser.Line} This line object + */ + centerOn: function (x, y) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + var tx = x - cx; + var ty = y - cy; + + this.start.add(tx, ty); + this.end.add(tx, ty); + + }, + + /** + * Tests if the given coordinates fall on this line. See {@link #pointOnSegment} to test against just the line segment. + * + * @method Phaser.Line#pointOnLine + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line, false if not. + */ + pointOnLine: function (x, y, epsilon) { + + return Phaser.Math.fuzzyEqual((x - this.start.x) * (this.end.y - this.start.y), (this.end.x - this.start.x) * (y - this.start.y), epsilon || 0); + + }, + + /** + * Tests if the given coordinates fall on this line and within the segment. See {@link #pointOnLine} to test against just the line. + * + * @method Phaser.Line#pointOnSegment + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line and segment, false if not. + */ + pointOnSegment: function (x, y, epsilon) { + + var xMin = Math.min(this.start.x, this.end.x); + var xMax = Math.max(this.start.x, this.end.x); + var yMin = Math.min(this.start.y, this.end.y); + var yMax = Math.max(this.start.y, this.end.y); + + return (this.pointOnLine(x, y, epsilon) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)); + + }, + + /** + * Picks a random point from anywhere on the Line segment and returns it. + * + * @method Phaser.Line#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = Math.random(); + + out.x = this.start.x + t * (this.end.x - this.start.x); + out.y = this.start.y + t * (this.end.y - this.start.y); + + return out; + + }, + + /** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * The start and end points are rounded before this runs as the algorithm works on integers. + * + * @method Phaser.Line#coordinatesOnLine + * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. + * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. + * @return {array} An array of coordinates. + */ + coordinatesOnLine: function (stepRate, results) { + + if (stepRate === undefined) { stepRate = 1; } + if (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 < x2) ? 1 : -1; + var sy = (y1 < y2) ? 1 : -1; + var err = dx - dy; + + results.push([x1, y1]); + + var i = 1; + + while (!((x1 === x2) && (y1 === y2))) + { + var e2 = err << 1; + + if (e2 > -dy) + { + err -= dy; + x1 += sx; + } + + if (e2 < dx) + { + err += dx; + y1 += sy; + } + + if (i % stepRate === 0) + { + results.push([x1, y1]); + } + + i++; + + } + + return results; + + }, + + /** + * Returns a new Line object with the same values for the start and end properties as this Line object. + * @method Phaser.Line#clone + * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned. + * @return {Phaser.Line} The cloned Line object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y); + } + else + { + output.setTo(this.start.x, this.start.y, this.end.x, this.end.y); + } + + return output; + + } + +}; + +/** +* @name Phaser.Line#length +* @property {number} length - Gets the length of the line segment. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "length", { + + get: function () { + return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#angle +* @property {number} angle - Gets the angle of the line in radians. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "angle", { + + get: function () { + return Phaser.Point.angle(this.end, this.start); + } + +}); + +/** +* @name Phaser.Line#slope +* @property {number} slope - Gets the slope of the line (y/x). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "slope", { + + get: function () { + return (this.end.y - this.start.y) / (this.end.x - this.start.x); + } + +}); + +/** +* @name Phaser.Line#perpSlope +* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "perpSlope", { + + get: function () { + return -((this.end.x - this.start.x) / (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#x +* @property {number} x - Gets the x coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "x", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#y +* @property {number} y - Gets the y coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "y", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#left +* @property {number} left - Gets the left-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "left", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#right +* @property {number} right - Gets the right-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "right", { + + get: function () { + return Math.max(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#top +* @property {number} top - Gets the top-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "top", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#bottom +* @property {number} bottom - Gets the bottom-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "bottom", { + + get: function () { + return Math.max(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#width +* @property {number} width - Gets the width of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "width", { + + get: function () { + return Math.abs(this.start.x - this.end.x); + } + +}); + +/** +* @name Phaser.Line#height +* @property {number} height - Gets the height of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "height", { + + get: function () { + return Math.abs(this.start.y - this.end.y); + } + +}); + +/** +* @name Phaser.Line#normalX +* @property {number} normalX - Gets the x component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalX", { + + get: function () { + return Math.cos(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalY +* @property {number} normalY - Gets the y component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalY", { + + get: function () { + return Math.sin(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalAngle +* @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalAngle", { + + get: function () { + return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI); + } + +}); + +/** +* Checks for intersection between two lines as defined by the given start and end points. +* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersectsPoints +* @param {Phaser.Point} a - The start of the first Line to be checked. +* @param {Phaser.Point} b - The end of the first line to be checked. +* @param {Phaser.Point} e - The start of the second Line to be checked. +* @param {Phaser.Point} f - The end of the second line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) { + + if (asSegment === undefined) { asSegment = true; } + if (result === undefined) { result = new Phaser.Point(); } + + var a1 = b.y - a.y; + var a2 = f.y - e.y; + var b1 = a.x - b.x; + var b2 = e.x - f.x; + var c1 = (b.x * a.y) - (a.x * b.y); + var c2 = (f.x * e.y) - (e.x * f.y); + var denom = (a1 * b2) - (a2 * b1); + + if (denom === 0) + { + return null; + } + + result.x = ((b1 * c2) - (b2 * c1)) / denom; + result.y = ((a2 * c1) - (a1 * c2)) / denom; + + if (asSegment) + { + var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y)); + var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc; + var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc; + + if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) + { + return result; + } + else + { + return null; + } + } + + return result; + +}; + +/** +* Checks for intersection between two lines. +* If asSegment is true it will check for segment intersection. +* If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersects +* @param {Phaser.Line} a - The first Line to be checked. +* @param {Phaser.Line} b - The second Line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersects = function (a, b, asSegment, result) { + + return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result); + +}; + +/** +* Checks for intersection between the Line and a Rectangle shape, or a rectangle-like +* object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. +* +* An intersection is considered valid if: +* +* The line starts within or ends within the rectangle; or +* The line segment intersects one of the 4 rectangle edges; and +* The line has a non-zero length; and +* The rectangle is not empty. +* +* For the purposes of this function rectangles are considered 'solid'. +* +* @method Phaser.Line.intersectsRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle. +*/ +Phaser.Line.intersectsRectangle = function (line, rect) { + + // Quick bail out + if (line.length === 0 || rect.empty) + { + return false; + } + + var x1 = line.start.x; + var y1 = line.start.y; + + var x2 = line.end.x; + var y2 = line.end.y; + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + + var t = 0; + + // If the start or end of the line is inside the rect then we assume + // collision, as rects are solid for our use-case. + + if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || + (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) + { + return true; + } + + if (x1 < bx1 && x2 >= bx1) + { + // Left edge + t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); + + if (t > by1 && t <= by2) + { + return true; + } + } + else if (x1 > bx2 && x2 <= bx2) + { + // Right edge + t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); + + if (t >= by1 && t <= by2) + { + return true; + } + } + + if (y1 < by1 && y2 >= by1) + { + // Top edge + t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + else if (y1 > by2 && y2 <= by2) + { + // Bottom edge + t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + + return false; + +}; + +/** +* Finds the closest intersection between the Line and a Rectangle shape, or a rectangle-like +* object, such as a Sprite or Body. +* +* @method Phaser.Line.intersectionWithRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @param {Phaser.Point} [result] - A Point object to store the result in. +* @return {?Phaser.Point} - The intersection closest to the Line's start, or null if there is no intersection. +*/ +Phaser.Line.intersectionWithRectangle = function (line, rect, result) { + + var self = Phaser.Line.intersectionWithRectangle; + + if (!result) + { + result = new Phaser.Point(); + } + + if (!self.edges) + { + self.edges = [new Phaser.Line(), new Phaser.Line(), new Phaser.Line(), new Phaser.Line()]; + } + + if (!self.edgeIntersection) + { + self.edgeIntersection = new Phaser.Point(); + } + + var edges = self.edges; + var edgeIntersection = self.edgeIntersection.set(0); + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + var closestDistance = Infinity; + + edges[0].setTo(bx1, by1, bx2, by1); + edges[1].setTo(bx1, by2, bx2, by2); + edges[2].setTo(bx1, by1, bx1, by2); + edges[3].setTo(bx2, by1, bx2, by2); + + for (var edge, i = 0; (edge = edges[i]); i++) + { + if (line.intersects(edge, true, edgeIntersection)) + { + var distance = line.start.distance(edgeIntersection); + + if (distance < closestDistance) + { + closestDistance = distance; + result.copyFrom(edgeIntersection); + } + } + } + + if (distance != null) + { + return result; + } + + return null; + +}; + +/** +* Returns the reflected angle between two lines. +* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. +* +* @method Phaser.Line.reflect +* @param {Phaser.Line} a - The base line. +* @param {Phaser.Line} b - The line to be reflected from the base line. +* @return {number} The reflected angle in radians. +*/ +Phaser.Line.reflect = function (a, b) { + + return 2 * b.normalAngle - 3.141592653589793 - a.angle; + +}; + +/** +* @author Mat Groves http://matgroves.com/ @Doormat23 +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. +* +* It is represented like so: +* +* | a | b | tx | +* | c | d | ty | +* | 0 | 0 | 1 | +* +* @class Phaser.Matrix +* @constructor +* @param {number} [a=1] - Horizontal scaling +* @param {number} [b=0] - Horizontal skewing +* @param {number} [c=0] - Vertical skewing +* @param {number} [d=1] - Vertical scaling +* @param {number} [tx=0] - Horizontal translation +* @param {number} [ty=0] - Vertical translation +*/ +Phaser.Matrix = function (a, b, c, d, tx, ty) { + + if (a === undefined || a === null) { a = 1; } + if (b === undefined || b === null) { b = 0; } + if (c === undefined || c === null) { c = 0; } + if (d === undefined || d === null) { d = 1; } + if (tx === undefined || tx === null) { tx = 0; } + if (ty === undefined || ty === null) { ty = 0; } + + /** + * @property {number} a + * @default 1 + */ + this.a = a; + + /** + * @property {number} b + * @default 0 + */ + this.b = b; + + /** + * @property {number} c + * @default 0 + */ + this.c = c; + + /** + * @property {number} d + * @default 1 + */ + this.d = d; + + /** + * @property {number} tx + * @default 0 + */ + this.tx = tx; + + /** + * @property {number} ty + * @default 0 + */ + this.ty = ty; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.MATRIX; + +}; + +Phaser.Matrix.prototype = { + + /** + * Sets the values of this Matrix to the values in the given array. + * + * The Array elements should be set as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @method Phaser.Matrix#fromArray + * @param {Array} array - The array to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + fromArray: function (array) { + + return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]); + + }, + + /** + * Sets the values of this Matrix to the given values. + * + * @method Phaser.Matrix#setTo + * @param {number} a - Horizontal scaling + * @param {number} b - Horizontal skewing + * @param {number} c - Vertical skewing + * @param {number} d - Vertical scaling + * @param {number} tx - Horizontal translation + * @param {number} ty - Vertical translation + * @return {Phaser.Matrix} This Matrix object. + */ + setTo: function (a, b, c, d, tx, ty) { + + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + + }, + + /** + * Creates a new Matrix object based on the values of this Matrix. + * If you provide the output parameter the values of this Matrix will be copied over to it. + * If the output parameter is blank a new Matrix object will be created. + * + * @method Phaser.Matrix#clone + * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created. + * @return {Phaser.Matrix} A clone of this Matrix. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); + } + else + { + output.a = this.a; + output.b = this.b; + output.c = this.c; + output.d = this.d; + output.tx = this.tx; + output.ty = this.ty; + } + + return output; + + }, + + /** + * Copies the properties from this Matrix to the given Matrix. + * + * @method Phaser.Matrix#copyTo + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} The destination Matrix object. + */ + copyTo: function (matrix) { + + matrix.copyFrom(this); + + return matrix; + + }, + + /** + * Copies the properties from the given Matrix into this Matrix. + * + * @method Phaser.Matrix#copyFrom + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + copyFrom: function (matrix) { + + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + + return this; + + }, + + /** + * Creates a Float32 Array with values populated from this Matrix object. + * + * @method Phaser.Matrix#toArray + * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not. + * @param {Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created. + * @return {Float32Array} The newly created array which contains the matrix. + */ + toArray: function (transpose, array) { + + if (array === undefined) { array = new Float32Array(9); } + + if (transpose) + { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else + { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + + }, + + /** + * Get a new position with the current transformation applied. + * + * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) + * + * @method Phaser.Matrix#apply + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, transformed through this matrix. + */ + apply: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + newPos.x = this.a * pos.x + this.c * pos.y + this.tx; + newPos.y = this.b * pos.x + this.d * pos.y + this.ty; + + return newPos; + + }, + + /** + * Get a new position with the inverse of the current transformation applied. + * + * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) + * + * @method Phaser.Matrix#applyInverse + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, inverse transformed through this matrix. + */ + applyInverse: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + var id = 1 / (this.a * this.d + this.c * -this.b); + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + + }, + + /** + * Translates the matrix on the x and y. + * This is the same as Matrix.tx += x. + * + * @method Phaser.Matrix#translate + * @param {number} x - The x value to translate on. + * @param {number} y - The y value to translate on. + * @return {Phaser.Matrix} This Matrix object. + */ + translate: function (x, y) { + + this.tx += x; + this.ty += y; + + return this; + + }, + + /** + * Applies a scale transformation to this matrix. + * + * @method Phaser.Matrix#scale + * @param {number} x - The amount to scale horizontally. + * @param {number} y - The amount to scale vertically. + * @return {Phaser.Matrix} This Matrix object. + */ + scale: function (x, y) { + + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + + }, + + /** + * Applies a rotation transformation to this matrix. + * + * @method Phaser.Matrix#rotate + * @param {number} angle - The angle to rotate by, given in radians. + * @return {Phaser.Matrix} This Matrix object. + */ + rotate: function (angle) { + + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos-this.b * sin; + this.b = a1 * sin+this.b * cos; + this.c = c1 * cos-this.d * sin; + this.d = c1 * sin+this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + + }, + + /** + * Appends the given Matrix to this Matrix. + * + * @method Phaser.Matrix#append + * @param {Phaser.Matrix} matrix - The matrix to append to this one. + * @return {Phaser.Matrix} This Matrix object. + */ + append: function (matrix) { + + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + + }, + + /** + * Resets this Matrix to an identity (default) matrix. + * + * @method Phaser.Matrix#identity + * @return {Phaser.Matrix} This Matrix object. + */ + identity: function () { + + return this.setTo(1, 0, 0, 1, 0, 0); + + } + +}; + +Phaser.identityMatrix = new Phaser.Matrix(); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. +* The following code creates a point at (0,0): +* `var myPoint = new Phaser.Point();` +* You can also use them as 2D Vectors and you'll find different vector related methods in this class. +* +* @class Phaser.Point +* @constructor +* @param {number} [x=0] - The horizontal position of this Point. +* @param {number} [y=0] - The vertical position of this Point. +*/ +Phaser.Point = function (x, y) { + + x = x || 0; + y = y || 0; + + /** + * @property {number} x - The x value of the point. + */ + this.x = x; + + /** + * @property {number} y - The y value of the point. + */ + this.y = y; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINT; + +}; + +Phaser.Point.prototype = { + + /** + * Copies the x and y properties from any given object to this Point. + * + * @method Phaser.Point#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Point} This Point object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y); + + }, + + /** + * Inverts the x and y values of this Point + * + * @method Phaser.Point#invert + * @return {Phaser.Point} This Point object. + */ + invert: function () { + + return this.setTo(this.y, this.x); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.setTo(2)` is the same as `Point.setTo(2, 2)` + * + * Identical to {@link #set}. + * + * @method Phaser.Point#setTo + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setTo: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.set(2)` is the same as `Point.set(2, 2)` + * + * Identical to {@link #setTo}. + * + * @method Phaser.Point#set + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + set: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object from a given polar coordinate. + * + * @method Phaser.Point#setToPolar + * @param {number} azimuth - The angular coordinate, in radians (unless `asDegrees`). + * @param {number} [radius=1] - The radial coordinate (length). + * @param {boolean} [asDegrees=false] - True if `azimuth` is in degrees. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setToPolar: function(azimuth, radius, asDegrees) { + + if (radius == null) { radius = 1; } + if (asDegrees) { azimuth = Phaser.Math.degToRad(azimuth); } + + return this.setTo(Math.cos(azimuth) * radius, Math.sin(azimuth) * radius); + + }, + + /** + * Adds the given x and y values to this Point. + * + * @method Phaser.Point#add + * @param {number} x - The value to add to Point.x. + * @param {number} y - The value to add to Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + add: function (x, y) { + + this.x += x; + this.y += y; + return this; + + }, + + /** + * Subtracts the given x and y values from this Point. + * + * @method Phaser.Point#subtract + * @param {number} x - The value to subtract from Point.x. + * @param {number} y - The value to subtract from Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + subtract: function (x, y) { + + this.x -= x; + this.y -= y; + return this; + + }, + + /** + * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. + * + * @method Phaser.Point#multiply + * @param {number} x - The value to multiply Point.x by. + * @param {number} y - The value to multiply Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + multiply: function (x, y) { + + this.x *= x; + this.y *= y; + return this; + + }, + + /** + * Divides Point.x and Point.y by the given x and y values. + * + * @method Phaser.Point#divide + * @param {number} x - The value to divide Point.x by. + * @param {number} y - The value to divide Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + divide: function (x, y) { + + this.x /= x; + this.y /= y; + return this; + + }, + + /** + * Clamps the x value of this Point to be between the given min and max. + * + * @method Phaser.Point#clampX + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampX: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + return this; + + }, + + /** + * Clamps the y value of this Point to be between the given min and max + * + * @method Phaser.Point#clampY + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampY: function (min, max) { + + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * Clamps this Point object values to be between the given min and max. + * + * @method Phaser.Point#clamp + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clamp: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * If this Point is not within the given object, moves it inside (at the nearest edge). + * + * @method Phaser.Point#clip + * @param {any} rect - A {@link Phaser.Rectangle} or any object with left, top, right, and bottom properties. + * @return {Phaser.Point} This Point object. + */ + clip: function (rect) { + + var left = rect.left, top = rect.top, right = rect.right, bottom = rect.bottom; + + if (this.x < left ) { this.x = left; } + else if (this.x > right) { this.x = right; } + if (this.y < top) { this.y = top; } + else if (this.y > bottom) { this.y = bottom; } + + return this; + + }, + + /** + * Creates a copy of the given Point. + * + * @method Phaser.Point#clone + * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The new Point object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(this.x, this.y); + } + else + { + output.setTo(this.x, this.y); + } + + return output; + + }, + + /** + * Copies the x and y properties from this Point to any given object. + * + * @method Phaser.Point#copyTo + * @param {any} dest - The object to copy to. + * @return {object} The dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + + return dest; + + }, + + /** + * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) + * + * @method Phaser.Point#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round] - Round the distance to the nearest integer (default false). + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + return Phaser.Point.distance(this, dest, round); + + }, + + /** + * Determines whether the given objects x/y values are equal to this Point object. + * + * @method Phaser.Point#equals + * @param {Phaser.Point|any} a - The object to compare with this Point. + * @return {boolean} A value of true if the x and y points are equal, otherwise false. + */ + equals: function (a) { + + return a.x === this.x && a.y === this.y; + + }, + + /** + * Determines whether a set of x-y coordinates are equal to this Point's. + * + * @method Phaser.Point#equalsXY + * @param {number} x - The x-coordinate to compare with this Point. + * @param {number} y - The y-coordinate to compare with this Point. + * @return {boolean} A value of true if the Point's coordinates are identical to the arguments, otherwise false. + */ + equalsXY: function (x, y) { + + return this.x === x && this.y === y; + + }, + + fuzzyEquals: function (a, epsilon) { + + return Phaser.Point.fuzzyEquals(this, a, epsilon); + + }, + + fuzzyEqualsXY: function (x, y, epsilon) { + + return Phaser.Point.fuzzyEqualsXY(this, x, y, epsilon); + + }, + + /** + * Returns the angle between this Point object and another object with public x and y properties. + * + * @method Phaser.Point#angle + * @param {Phaser.Point|any} a - The object to get the angle from this Point to. + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angle: function (a, asDegrees) { + + return this.angleXY(a.x, a.y, asDegrees); + + }, + + /** + * Returns the angle between this Point object and an x-y coordinate pair. + * + * @method Phaser.Point#angleXY + * @param {number} x - The x-coordinate + * @param {number} y - The y-coordinate + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angleXY: function (x, y, asDegrees) { + + var angle = Math.atan2(y - this.y, x - this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Returns the arctangent of this Point. + * + * @method Phaser.Point#atan + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where the vertex is (0, 0). Within [-pi, pi] or [-180deg, 180deg]. + */ + atan: function (asDegrees) { + + var angle = Math.atan2(this.y, this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Rotates this Point around the x/y coordinates given to the desired angle. + * + * @method Phaser.Point#rotate + * @param {number} x - The x coordinate of the anchor point. + * @param {number} y - The y coordinate of the anchor point. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {number} [distance] - An optional distance constraint between the Point and the anchor. + * @return {Phaser.Point} The modified point object. + */ + rotate: function (x, y, angle, asDegrees, distance) { + + return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance); + + }, + + /** + * Calculates the length of the Point object. + * + * @method Phaser.Point#getMagnitude + * @return {number} The length of the Point. + */ + getMagnitude: function () { + + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + + }, + + /** + * Calculates the length squared of the Point object. + * + * @method Phaser.Point#getMagnitudeSq + * @return {number} The length ^ 2 of the Point. + */ + getMagnitudeSq: function () { + + return (this.x * this.x) + (this.y * this.y); + + }, + + /** + * Alters the length of the Point without changing the direction. + * + * @method Phaser.Point#setMagnitude + * @param {number} magnitude - The desired magnitude of the resulting Point. + * @return {Phaser.Point} This Point object. + */ + setMagnitude: function (magnitude) { + + return this.normalize().multiply(magnitude, magnitude); + + }, + + /** + * Alters the Point object so that its length is 1, but it retains the same direction. + * + * @method Phaser.Point#normalize + * @return {Phaser.Point} This Point object. + */ + normalize: function () { + + if (!this.isZero()) + { + var m = this.getMagnitude(); + this.x /= m; + this.y /= m; + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at most the max value. + * + * @method Phaser.Point#limit + * @param {number} max - The maximum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#expand + */ + limit: function (max) { + + if (this.getMagnitudeSq() > max * max) + { + this.setMagnitude(max); + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at least the min value. + * + * @method Phaser.Point#expand + * @param {number} min - The minimum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#limit + */ + expand: function (min) { + + if (this.getMagnitudeSq() < min * min) + { + this.setMagnitude(min); + } + + return this; + + }, + + /** + * Determine if this point is at 0,0. + * + * @method Phaser.Point#isZero + * @return {boolean} True if this Point is 0,0, otherwise false. + */ + isZero: function () { + + return (this.x === 0 && this.y === 0); + + }, + + /** + * The dot product of this and another Point object. + * + * @method Phaser.Point#dot + * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point. + * @return {number} The result. + */ + dot: function (a) { + + return ((this.x * a.x) + (this.y * a.y)); + + }, + + /** + * The cross product of this and another Point object. + * + * @method Phaser.Point#cross + * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point. + * @return {number} The result. + */ + cross: function (a) { + + return ((this.x * a.y) - (this.y * a.x)); + + }, + + /** + * Make this Point perpendicular (90 degrees rotation) + * + * @method Phaser.Point#perp + * @return {Phaser.Point} This Point object. + */ + perp: function () { + + return this.setTo(-this.y, this.x); + + }, + + /** + * Make this Point perpendicular (-90 degrees rotation) + * + * @method Phaser.Point#rperp + * @return {Phaser.Point} This Point object. + */ + rperp: function () { + + return this.setTo(this.y, -this.x); + + }, + + /** + * Right-hand normalize (make unit length) this Point. + * + * @method Phaser.Point#normalRightHand + * @return {Phaser.Point} This Point object. + */ + normalRightHand: function () { + + return this.setTo(this.y * -1, this.x); + + }, + + /** + * Math.floor() both the x and y properties of this Point. + * + * @method Phaser.Point#floor + * @return {Phaser.Point} This Point object. + */ + floor: function () { + + return this.setTo(Math.floor(this.x), Math.floor(this.y)); + + }, + + /** + * Math.ceil() both the x and y properties of this Point. + * + * @method Phaser.Point#ceil + * @return {Phaser.Point} This Point object. + */ + ceil: function () { + + return this.setTo(Math.ceil(this.x), Math.ceil(this.y)); + + }, + + /** + * Math.round() both the x and y properties of this Point. + * + * @method Phaser.Point#round + * @return {Phaser.Point} This Point object. + */ + round: function () { + + return this.setTo(Math.round(this.x), Math.round(this.y)); + + }, + + /** + * Returns a string representation of this object. + * + * @method Phaser.Point#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; + + } + +}; + +Phaser.Point.prototype.constructor = Phaser.Point; + +/** +* Adds the coordinates of two points together to create a new point. +* +* @method Phaser.Point.add +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.add = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x + b.x; + out.y = a.y + b.y; + + return out; + +}; + +/** +* Subtracts the coordinates of two points to create a new point. +* +* @method Phaser.Point.subtract +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.subtract = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x - b.x; + out.y = a.y - b.y; + + return out; + +}; + +/** +* Multiplies the coordinates of two points to create a new point. +* +* @method Phaser.Point.multiply +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiply = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x * b.x; + out.y = a.y * b.y; + + return out; + +}; + +/** +* Divides the coordinates of two points to create a new point. +* +* @method Phaser.Point.divide +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.divide = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x / b.x; + out.y = a.y / b.y; + + return out; + +}; + +/** +* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. +* +* @method Phaser.Point.equals +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {boolean} A value of true if the Points are equal, otherwise false. +*/ +Phaser.Point.equals = function (a, b) { + + return a.x === b.x && a.y === b.y; + +}; + +Phaser.Point.equalsXY = function (a, x, y) { + + return a.x === x && a.y === y; + +}; + +Phaser.Point.fuzzyEquals = function (a, b, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, b.x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, b.y, epsilon); + +}; + +Phaser.Point.fuzzyEqualsXY = function (a, x, y, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, y, epsilon); + +}; + +/** +* Returns the angle between two Point objects. +* +* @method Phaser.Point.angle +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {number} The angle, where b is the vertex. Within [-pi, pi]. +*/ +Phaser.Point.angle = function (a, b) { + + return Math.atan2(a.y - b.y, a.x - b.x); + +}; + +/** +* Creates a negative Point. +* +* @method Phaser.Point.negative +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.negative = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.x, -a.y); + +}; + +/** +* Adds two 2D Points together and multiplies the result by the given scalar. +* +* @method Phaser.Point.multiplyAdd +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} s - The scaling value. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiplyAdd = function (a, b, s, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + b.x * s, a.y + b.y * s); + +}; + +/** +* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. +* +* @method Phaser.Point.interpolate +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.interpolate = function (a, b, f, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f); + +}; + +/** +* Return a perpendicular vector (90 degrees rotation) +* +* @method Phaser.Point.perp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.perp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.y, a.x); + +}; + +/** +* Return a perpendicular vector (-90 degrees rotation) +* +* @method Phaser.Point.rperp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.rperp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y, -a.x); + +}; + +/** +* Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). +* +* @method Phaser.Point.distance +* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. +* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. +* @param {boolean} [round=false] - Round the distance to the nearest integer. +* @return {number} The distance between this Point object and the destination Point object. +*/ +Phaser.Point.distance = function (a, b, round) { + + var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y); + return round ? Math.round(distance) : distance; + +}; + +/** +* Project two Points onto another Point. +* +* @method Phaser.Point.project +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.project = function (a, b, out) { + + if (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; + +}; + +/** +* Project two Points onto a Point of unit length. +* +* @method Phaser.Point.projectUnit +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.projectUnit = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var amt = a.dot(b); + + if (amt !== 0) + { + out.setTo(amt * b.x, amt * b.y); + } + + return out; + +}; + +/** +* Right-hand normalize (make unit length) a Point. +* +* @method Phaser.Point.normalRightHand +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalRightHand = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y * -1, a.x); + +}; + +/** +* Normalize (make unit length) a Point. +* +* @method Phaser.Point.normalize +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalize = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var m = a.getMagnitude(); + + if (m !== 0) + { + out.setTo(a.x / m, a.y / m); + } + + return out; + +}; + +/** +* Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by +* the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument +* is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. +* +* The distance allows you to specify a distance constraint for the rotation between the point and the +* coordinates. If none is given the distance between the two is calculated and used. +* +* @method Phaser.Point.rotate +* @param {Phaser.Point} a - The Point object to rotate. +* @param {number} x - The x coordinate of the anchor point +* @param {number} y - The y coordinate of the anchor point +* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {number} [distance] - An optional distance constraint between the Point and the anchor. +* @return {Phaser.Point} The modified point object. +*/ +Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) { + + if (asDegrees) { angle = Phaser.Math.degToRad(angle); } + + if (distance === undefined) + { + a.subtract(x, y); + + var s = Math.sin(angle); + var c = Math.cos(angle); + + var tx = c * a.x - s * a.y; + var ty = s * a.x + c * a.y; + + a.x = tx + x; + a.y = ty + y; + } + else + { + var t = angle + Math.atan2(a.y - y, a.x - x); + a.x = x + distance * Math.cos(t); + a.y = y + distance * Math.sin(t); + } + + return a; + +}; + +/** +* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. +* +* @method Phaser.Point.centroid +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.centroid = function (points, out) { + + if (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 < pointslength; i++) + { + Phaser.Point.add(out, points[i], out); + } + + out.divide(pointslength, pointslength); + + return out; + +}; + +/** +* Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. +* If the object doesn't contain those properties a Point with x/y of zero will be returned. +* +* @method Phaser.Point.parse +* @static +* @param {object} obj - The object to parse. +* @param {string} [xProp='x'] - The property used to set the Point.x value. +* @param {string} [yProp='y'] - The property used to set the Point.y value. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.parse = function(obj, xProp, yProp) { + + xProp = xProp || 'x'; + yProp = yProp || 'y'; + + var point = new Phaser.Point(); + + if (obj[xProp]) + { + point.x = parseInt(obj[xProp], 10); + } + + if (obj[yProp]) + { + point.y = parseInt(obj[yProp], 10); + } + + return point; + +}; + +/** + * Tests a Point or Point-like object. + * + * @method Phaser.Point.isPoint + * @static + * @return {boolean} - True if the object has numeric x and y properties. + */ +Phaser.Point.isPoint = function(obj) { + + return (obj != null) && (typeof obj.x === 'number') && (typeof obj.y === 'number'); + +}; + +/** +* Sets the `x` and `y` values of an object and returns the object. +* +* @method Phaser.Point#set +* @static +* @param {object} obj - An object with numeric x and y properties. +* @param {number} x - The x value. +* @param {number} [y] - The y value. If not given the x value will be used in its place. +* @return {object} The object. Useful for chaining method calls. +*/ +Phaser.Point.set = function(obj, x, y) { + + obj.x = x || 0; + obj.y = y || ( (y !== 0) ? obj.x : 0 ); + + return obj; + +}; + +/** +* Sorts an array of points in a clockwise direction, relative to a reference point. +* +* The sort is clockwise relative to the display, starting from a 12 o'clock position. +* (In the Cartesian plane, it is anticlockwise, starting from the -y direction.) +* +* Example sequence: (0, -1), (1, 0), (0, 1), (-1, 0) +* +* @method Phaser.Point#sortClockwise +* @static +* @param {array} points - An array of Points or point-like objects (e.g., sprites). +* @param {object|Phaser.Point} [center] - The reference point. If omitted, the {@link #centroid} (midpoint) of the points is used. +* @return {array} The sorted array. +*/ +Phaser.Point.sortClockwise = function(points, center) { + + // Adapted from (ciamej) + + if (!center) + { + center = this.centroid(points); + } + + var cx = center.x; + var cy = center.y; + + var sort = function(a, b) { + if (a.x - cx >= 0 && b.x - cx < 0) + { + return -1; + } + + if (a.x - cx < 0 && b.x - cx >= 0) + { + return 1; + } + + if (a.x - cx === 0 && b.x - cx === 0) + { + if (a.y - cy >= 0 || b.y - cy >= 0) + { + return (a.y > b.y) ? 1 : -1; + } + + return (b.y > a.y) ? 1 : -1; + } + + // Compute the cross product of vectors (center -> a) * (center -> b) + var det = (a.x - cx) * -(b.y - cy) - (b.x - cx) * -(a.y - cy); + + if (det < 0) + { + return -1; + } + + if (det > 0) + { + return 1; + } + + // Points a and b are on the same line from the center + // Check which point is closer to the center + var d1 = (a.x - cx) * (a.x - cx) + (a.y - cy) * (a.y - cy); + var d2 = (b.x - cx) * (b.x - cx) + (b.y - cy) * (b.y - cy); + + return (d1 > d2) ? -1 : 1; + }; + + return points.sort(sort); + +}; + + +// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Point = Phaser.Point; + +/** +* @author Richard Davey +* @author Adrien Brault +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Polygon. +* +* The points can be set from a variety of formats: +* +* - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` +* - An array of objects with public x/y properties: `[obj1, obj2, ...]` +* - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` +* - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` +* - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` +* - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` +* +* @class Phaser.Polygon +* @constructor +* @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. +*/ +Phaser.Polygon = function () { + + /** + * @property {number} area - The area of this Polygon. + */ + this.area = 0; + + /** + * @property {array} _points - An array of Points that make up this Polygon. + * @private + */ + this._points = []; + + if (arguments.length > 0) + { + this.setTo.apply(this, arguments); + } + + /** + * @property {boolean} closed - Is the Polygon closed or not? + */ + this.closed = true; + + /** + * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ? + */ + this.flattened = false; + + /** + * @property {number} type - The base object type. + */ + this.type = Phaser.POLYGON; + +}; + +Phaser.Polygon.prototype = { + + /** + * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] + * + * @method Phaser.Polygon#toNumberArray + * @param {array} [output] - The array to append the points to. If not specified a new array will be created. + * @return {array} The flattened array. + */ + toNumberArray: function (output) { + + if (output === undefined) { output = []; } + + for (var i = 0; i < this._points.length; i++) + { + if (typeof this._points[i] === 'number') + { + output.push(this._points[i]); + output.push(this._points[i + 1]); + i++; + } + else + { + output.push(this._points[i].x); + output.push(this._points[i].y); + } + } + + return output; + + }, + + /** + * Flattens this Polygon so the points are a sequence of numbers. + * Any Point objects found are removed and replaced with two numbers. + * Also sets the Polygon.flattened property to `true`. + * + * @method Phaser.Polygon#flatten + * @return {Phaser.Polygon} This Polygon object + */ + flatten: function () { + + this._points = this.toNumberArray(); + + this.flattened = true; + + return this; + + }, + + /** + * Creates a copy of the given Polygon. + * This is a deep clone, the resulting copy contains new Phaser.Point objects + * + * @method Phaser.Polygon#clone + * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created. + * @return {Phaser.Polygon} The cloned (`output`) polygon object. + */ + clone: function (output) { + + var points = this._points.slice(); + + if (output === undefined || output === null) + { + output = new Phaser.Polygon(points); + } + else + { + output.setTo(points); + } + + return output; + + }, + + /** + * Checks whether the x and y coordinates are contained within this polygon. + * + * @method Phaser.Polygon#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this polygon, otherwise false. + */ + contains: function (x, y) { + + // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva + + var inside = false; + + if (this.flattened) + { + for (var i = -2, j = this._points.length - 2; (i += 2) < this._points.length; j = i) + { + var ix = this._points[i]; + var iy = this._points[i + 1]; + + var jx = this._points[j]; + var jy = this._points[j + 1]; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + + } + else + { + for (var i = -1, j = this._points.length - 1; ++i < this._points.length; j = i) + { + var ix = this._points[i].x; + var iy = this._points[i].y; + + var jx = this._points[j].x; + var jy = this._points[j].y; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + } + + return inside; + + }, + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` + * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` + * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` + * + * `setTo` may also be called without any arguments to remove all points. + * + * @method Phaser.Polygon#setTo + * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. + * @return {Phaser.Polygon} This Polygon object + */ + setTo: function (points) { + + this.area = 0; + this._points = []; + + if (arguments.length > 0) + { + // If points isn't an array, use arguments as the array + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments); + } + + var y0 = Number.MAX_VALUE; + + // Allows for mixed-type arguments + for (var i = 0, len = points.length; i < len; i++) + { + if (typeof points[i] === 'number') + { + var p = new PIXI.Point(points[i], points[i + 1]); + i++; + } + else if (Array.isArray(points[i])) + { + var p = new PIXI.Point(points[i][0], points[i][1]); + } + else + { + var p = new PIXI.Point(points[i].x, points[i].y); + } + + this._points.push(p); + + // Lowest boundary + if (p.y < y0) + { + y0 = p.y; + } + } + + this.calculateArea(y0); + } + + return this; + + }, + + /** + * Calcuates the area of the Polygon. This is available in the property Polygon.area + * + * @method Phaser.Polygon#calculateArea + * @private + * @param {number} y0 - The lowest boundary + * @return {number} The area of the Polygon. + */ + calculateArea: function (y0) { + + var p1; + var p2; + var avgHeight; + var width; + + for (var i = 0, len = this._points.length; i < len; i++) + { + p1 = this._points[i]; + + if (i === len - 1) + { + p2 = this._points[0]; + } + else + { + p2 = this._points[i + 1]; + } + + avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2; + width = p1.x - p2.x; + this.area += avgHeight * width; + } + + return this.area; + + } + +}; + +Phaser.Polygon.prototype.constructor = Phaser.Polygon; + +/** +* The points of this polygon. +* +* You can modify these with {@link Phaser.Polygon#setTo setTo}. +* +* @name Phaser.Polygon#points +* @property {Phaser.Point[]} points - The array of vertex points. +* @readonly +*/ +Object.defineProperty(Phaser.Polygon.prototype, 'points', { + + get: function() { + return this._points; + } + +}); + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Polygon = Phaser.Polygon; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. +* If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. +* +* @class Phaser.Rectangle +* @constructor +* @param {number} x - The x coordinate of the top-left corner of the Rectangle. +* @param {number} y - The y coordinate of the top-left corner of the Rectangle. +* @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. +*/ +Phaser.Rectangle = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.RECTANGLE; + +}; + +Phaser.Rectangle.prototype = { + + /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method Phaser.Rectangle#offset + * @param {number} dx - Moves the x value of the Rectangle object by this amount. + * @param {number} dy - Moves the y value of the Rectangle object by this amount. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Rectangle#offsetPoint + * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offsetPoint: function (point) { + + return this.offset(point.x, point.y); + + }, + + /** + * Sets the members of Rectangle to the specified values. + * @method Phaser.Rectangle#setTo + * @param {number} x - The x coordinate of the top-left corner of the Rectangle. + * @param {number} y - The y coordinate of the top-left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Scales the width and height of this Rectangle by the given amounts. + * + * @method Phaser.Rectangle#scale + * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. + * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. + * @return {Phaser.Rectangle} This Rectangle object + */ + scale: function (x, y) { + + if (y === undefined) { y = x; } + + this.width *= x; + this.height *= y; + + return this; + + }, + + /** + * Centers this Rectangle so that the center coordinates match the given x and y values. + * + * @method Phaser.Rectangle#centerOn + * @param {number} x - The x coordinate to place the center of the Rectangle at. + * @param {number} y - The y coordinate to place the center of the Rectangle at. + * @return {Phaser.Rectangle} This Rectangle object + */ + centerOn: function (x, y) { + + this.centerX = x; + this.centerY = y; + + return this; + + }, + + /** + * Runs Math.floor() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#floor + */ + floor: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + + }, + + /** + * Runs Math.floor() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#floorAll + */ + floorAll: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.width = Math.floor(this.width); + this.height = Math.floor(this.height); + + }, + + /** + * Runs Math.ceil() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#ceil + */ + ceil: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + + }, + + /** + * Runs Math.ceil() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#ceilAll + */ + ceilAll: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.width = Math.ceil(this.width); + this.height = Math.ceil(this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the left, top, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFromBounds + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFromBounds: function(source) { + + return this.setTo(source.left, source.top, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Rectangle to any given object. + * @method Phaser.Rectangle#copyTo + * @param {any} source - The object to copy to. + * @return {object} This object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method Phaser.Rectangle#inflate + * @param {number} dx - The amount to be added to the left side of the Rectangle. + * @param {number} dy - The amount to be added to the bottom side of the Rectangle. + * @return {Phaser.Rectangle} This Rectangle object. + */ + inflate: function (dx, dy) { + + return Phaser.Rectangle.inflate(this, dx, dy); + + }, + + /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method Phaser.Rectangle#size + * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object. + */ + size: function (output) { + + return Phaser.Rectangle.size(this, output); + + }, + + /** + * Resize the Rectangle by providing a new width and height. + * The x and y positions remain unchanged. + * + * @method Phaser.Rectangle#resize + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method Phaser.Rectangle#clone + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ + clone: function (output) { + + return Phaser.Rectangle.clone(this, output); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method Phaser.Rectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + contains: function (x, y) { + + return Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method Phaser.Rectangle#containsRect + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + containsRect: function (b) { + + return Phaser.Rectangle.containsRect(b, this); + + }, + + /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method Phaser.Rectangle#equals + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + */ + equals: function (b) { + + return Phaser.Rectangle.equals(this, b); + + }, + + /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method Phaser.Rectangle#intersection + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ + intersection: function (b, out) { + + return Phaser.Rectangle.intersection(this, b, out); + + }, + + /** + * Determines whether this Rectangle and another given Rectangle intersect with each other. + * This method checks the x, y, width, and height properties of the two Rectangles. + * + * @method Phaser.Rectangle#intersects + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + */ + intersects: function (b) { + + return Phaser.Rectangle.intersects(this, b); + + }, + + /** + * Determines whether the coordinates given intersects (overlaps) with this Rectangle. + * + * @method Phaser.Rectangle#intersectsRaw + * @param {number} left - The x coordinate of the left of the area. + * @param {number} right - The right coordinate of the area. + * @param {number} top - The y coordinate of the area. + * @param {number} bottom - The bottom coordinate of the area. + * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 + * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + */ + intersectsRaw: function (left, right, top, bottom, tolerance) { + + return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance); + + }, + + /** + * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. + * @method Phaser.Rectangle#union + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ + union: function (b, out) { + + return Phaser.Rectangle.union(this, b, out); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Rectangle. + * + * @method Phaser.Rectangle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = this.randomX; + out.y = this.randomY; + + return out; + + }, + + /** + * Returns a point based on the given position constant, which can be one of: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * This method returns the same values as calling Rectangle.bottomLeft, etc, but those + * calls always create a new Point object, where-as this one allows you to use your own. + * + * @method Phaser.Rectangle#getPoint + * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. + * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the point in its `x` and `y` properties. + */ + getPoint: function (position, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + return out.set(this.x, this.y); + + case Phaser.TOP_CENTER: + return out.set(this.centerX, this.y); + + case Phaser.TOP_RIGHT: + return out.set(this.right, this.y); + + case Phaser.LEFT_CENTER: + return out.set(this.x, this.centerY); + + case Phaser.CENTER: + return out.set(this.centerX, this.centerY); + + case Phaser.RIGHT_CENTER: + return out.set(this.right, this.centerY); + + case Phaser.BOTTOM_LEFT: + return out.set(this.x, this.bottom); + + case Phaser.BOTTOM_CENTER: + return out.set(this.centerX, this.bottom); + + case Phaser.BOTTOM_RIGHT: + return out.set(this.right, this.bottom); + } + + }, + + /** + * Creates or positions four {@link Phaser.Line} lines representing the Rectangle's sides. + * + * @method Phaser.Rectangle#sides + * @param {Phaser.Line} [top] + * @param {Phaser.Line} [right] + * @param {Phaser.Line} [bottom] + * @param {Phaser.Line} [left] + * @return {?Phaser.Line[]} - An array containing four lines (if no arguments were given), or null. + */ + sides: function (top, right, bottom, left) { + + if (!arguments.length) { + top = new Phaser.Line(); + right = new Phaser.Line(); + bottom = new Phaser.Line(); + left = new Phaser.Line(); + } + + var x1 = this.x; + var y1 = this.y; + var x2 = this.right; + var y2 = this.bottom; + + top.setTo(x1, y1, x2, y1); + right.setTo(x2, y1, x2, y2); + bottom.setTo(x1, y2, x2, y2); + left.setTo(x1, y1, x1, y2); + + if (!arguments.length) { + return [top, right, bottom, left]; + } + + return null; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Rectangle#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + + } + +}; + +/** +* @name Phaser.Rectangle#halfWidth +* @property {number} halfWidth - Half of the width of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", { + + get: function () { + return Math.round(this.width / 2); + } + +}); + +/** +* @name Phaser.Rectangle#halfHeight +* @property {number} halfHeight - Half of the height of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", { + + get: function () { + return Math.round(this.height / 2); + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. +* @name Phaser.Rectangle#bottom +* @property {number} bottom - The sum of the y and height properties. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value <= this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + + } + +}); + +/** +* The location of the Rectangles bottom left corner as a Point object. +* @name Phaser.Rectangle#bottomLeft +* @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", { + + get: function () { + return new Phaser.Point(this.x, this.bottom); + }, + + set: function (value) { + this.x = value.x; + this.bottom = value.y; + } + +}); + +/** +* The location of the Rectangles bottom right corner as a Point object. +* @name Phaser.Rectangle#bottomRight +* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", { + + get: function () { + return new Phaser.Point(this.right, this.bottom); + }, + + set: function (value) { + this.right = value.x; + this.bottom = value.y; + } + +}); + +/** +* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. +* @name Phaser.Rectangle#left +* @property {number} left - The x coordinate of the left of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + if (value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + } + +}); + +/** +* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. +* @name Phaser.Rectangle#right +* @property {number} right - The sum of the x and width properties. +*/ +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 = value - this.x; + } + } + +}); + +/** +* The volume of the Rectangle derived from width * height. +* @name Phaser.Rectangle#volume +* @property {number} volume - The volume of the Rectangle derived from width * height. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "volume", { + + get: function () { + return this.width * this.height; + } + +}); + +/** +* The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @name Phaser.Rectangle#perimeter +* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", { + + get: function () { + return (this.width * 2) + (this.height * 2); + } + +}); + +/** +* The x coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerX +* @property {number} centerX - The x coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerX", { + + get: function () { + return this.x + this.halfWidth; + }, + + set: function (value) { + this.x = value - this.halfWidth; + } + +}); + +/** +* The y coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerY +* @property {number} centerY - The y coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerY", { + + get: function () { + return this.y + this.halfHeight; + }, + + set: function (value) { + this.y = value - this.halfHeight; + } + +}); + +/** +* A random value between the left and right values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomX +* @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomX", { + + get: function () { + + return this.x + (Math.random() * this.width); + + } + +}); + +/** +* A random value between the top and bottom values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomY +* @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomY", { + + get: function () { + + return this.y + (Math.random() * this.height); + + } + +}); + +/** +* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. +* However it does affect the height property, whereas changing the y value does not affect the height property. +* @name Phaser.Rectangle#top +* @property {number} top - The y coordinate of the top of the Rectangle. +*/ +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); + } + } + +}); + +/** +* The location of the Rectangles top left corner as a Point object. +* @name Phaser.Rectangle#topLeft +* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. +*/ +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; + } + +}); + +/** +* The location of the Rectangles top right corner as a Point object. +* @name Phaser.Rectangle#topRight +* @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "topRight", { + + get: function () { + return new Phaser.Point(this.x + this.width, this.y); + }, + + set: function (value) { + this.right = value.x; + this.y = value.y; + } + +}); + +/** +* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. +* If set to true then all of the Rectangle properties are set to 0. +* @name Phaser.Rectangle#empty +* @property {boolean} empty - Gets or sets the Rectangles empty state. +*/ +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; + +/** +* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. +* @method Phaser.Rectangle.inflate +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} dx - The amount to be added to the left side of the Rectangle. +* @param {number} dy - The amount to be added to the bottom side of the Rectangle. +* @return {Phaser.Rectangle} This Rectangle object. +*/ +Phaser.Rectangle.inflate = function (a, dx, dy) { + + a.x -= dx; + a.width += 2 * dx; + a.y -= dy; + a.height += 2 * dy; + + return a; + +}; + +/** +* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. +* @method Phaser.Rectangle.inflatePoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. +* @return {Phaser.Rectangle} The Rectangle object. +*/ +Phaser.Rectangle.inflatePoint = function (a, point) { + + return Phaser.Rectangle.inflate(a, point.x, point.y); + +}; + +/** +* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. +* @method Phaser.Rectangle.size +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. +* @return {Phaser.Point} The size of the Rectangle object +*/ +Phaser.Rectangle.size = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(a.width, a.height); + } + else + { + output.setTo(a.width, a.height); + } + + return output; + +}; + +/** +* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. +* @method Phaser.Rectangle.clone +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.clone = function (a, output) { + + if (output === undefined || output === null) + { + 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; + +}; + +/** +* Returns a new Rectangle object with the same values for the left, top, width, and height properties as the original object. +* @method Phaser.Rectangle.createFromBounds +* @param {any} a - An object with `left`, `top`, `width`, and `height` properties. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.createFromBounds = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Rectangle(a.x, a.y, a.width, a.height); + } + + return output.copyFromBounds(a); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by this Rectangle object. +* @method Phaser.Rectangle.contains +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +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); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by the given raw values. +* @method Phaser.Rectangle.containsRaw +* @param {number} rx - The x coordinate of the top left of the area. +* @param {number} ry - The y coordinate of the top left of the area. +* @param {number} rw - The width of the area. +* @param {number} rh - The height of the area. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) { + + return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh)); + +}; + +/** +* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. +* @method Phaser.Rectangle.containsPoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsPoint = function (a, point) { + + return Phaser.Rectangle.contains(a, point.x, point.y); + +}; + +/** +* Determines whether the first Rectangle object is fully contained within the second Rectangle object. +* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. +* @method Phaser.Rectangle.containsRect +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRect = function (a, b) { + + // If the given rect has a larger volume than this one then it can never contain it + if (a.volume > b.volume) + { + return false; + } + + return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom); + +}; + +/** +* Determines whether the two Rectangles are equal. +* This method compares the x, y, width and height properties of each Rectangle. +* @method Phaser.Rectangle.equals +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. +*/ +Phaser.Rectangle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height); + +}; + +/** +* Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. +* @method Phaser.Rectangle.sameDimensions +* @param {Rectangle-like} a - The first Rectangle object. +* @param {Rectangle-like} b - The second Rectangle object. +* @return {boolean} True if the object have equivalent values for the width and height properties. +*/ +Phaser.Rectangle.sameDimensions = function (a, b) { + + return (a.width === b.width && a.height === b.height); + +}; + +/** +* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. +* @method Phaser.Rectangle.intersection +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. +*/ +Phaser.Rectangle.intersection = function (a, b, output) { + + if (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; + +}; + +/** +* Determines whether the two Rectangles intersect with each other. +* This method checks the x, y, width, and height properties of the Rectangles. +* @method Phaser.Rectangle.intersects +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. +*/ +Phaser.Rectangle.intersects = function (a, b) { + + if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) + { + return false; + } + + return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom); + +}; + +/** +* Determines whether the object specified intersects (overlaps) with the given values. +* @method Phaser.Rectangle.intersectsRaw +* @param {number} left - The x coordinate of the left of the area. +* @param {number} right - The right coordinate of the area. +* @param {number} top - The y coordinate of the area. +* @param {number} bottom - The bottom coordinate of the area. +* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 +* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. +*/ +Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) { + + if (tolerance === undefined) { tolerance = 0; } + + return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); + +}; + +/** +* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. +* @method Phaser.Rectangle.union +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. +*/ +Phaser.Rectangle.union = function (a, b, output) { + + if (output === undefined) + { + output = new Phaser.Rectangle(); + } + + return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top)); + +}; + +/** +* Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. +* +* @method Phaser.Rectangle#aabb +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. +* @return {Phaser.Rectangle} The new Rectangle object. +* @static +*/ +Phaser.Rectangle.aabb = function(points, out) { + + if (out === undefined) { + out = new Phaser.Rectangle(); + } + + var xMax = Number.NEGATIVE_INFINITY, + xMin = Number.POSITIVE_INFINITY, + yMax = Number.NEGATIVE_INFINITY, + yMin = Number.POSITIVE_INFINITY; + + points.forEach(function(point) { + if (point.x > xMax) { + xMax = point.x; + } + if (point.x < xMin) { + xMin = point.x; + } + + if (point.y > yMax) { + yMax = point.y; + } + if (point.y < yMin) { + yMin = point.y; + } + }); + + out.setTo(xMin, yMin, xMax - xMin, yMax - yMin); + + return out; +}; + +// Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Rectangle = Phaser.Rectangle; +PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0); + +/** +* @author Mat Groves http://matgroves.com/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Rounded Rectangle object is an area defined by its position and has nice rounded corners, +* as indicated by its top-left corner point (x, y) and by its width and its height. +* +* @class Phaser.RoundedRectangle +* @constructor +* @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle. +* @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle. +* @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value. +* @param {number} [radius=20] - Controls the radius of the rounded corners. +*/ +Phaser.RoundedRectangle = function(x, y, width, height, radius) +{ + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + if (radius === undefined) { radius = 20; } + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} radius - The radius of the rounded corners. + */ + this.radius = radius || 20; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROUNDEDRECTANGLE; +}; + +Phaser.RoundedRectangle.prototype = { + + /** + * Returns a new RoundedRectangle object with the same values for the x, y, width, height and + * radius properties as this RoundedRectangle object. + * + * @method Phaser.RoundedRectangle#clone + * @return {Phaser.RoundedRectangle} + */ + clone: function () { + + return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. + * + * @method Phaser.RoundedRectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. + */ + 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; + + } + +}; + +Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle; + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.RoundedRectangle = Phaser.RoundedRectangle; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. +* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y +* +* @class Phaser.Camera +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera +* @param {number} x - Position of the camera on the X axis +* @param {number} y - Position of the camera on the Y axis +* @param {number} width - The width of the view rectangle +* @param {number} height - The height of the view rectangle +*/ +Phaser.Camera = function (game, id, x, y, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + */ + this.world = game.world; + + /** + * @property {number} id - Reserved for future multiple camera set-ups. + * @default + */ + this.id = 0; + + /** + * Camera view. + * The view into the world we wish to render (by default the game dimensions). + * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. + * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. + * @property {Phaser.Rectangle} view + */ + this.view = new Phaser.Rectangle(x, y, width, height); + + /** + * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. + * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound + * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. + * + * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. + */ + this.bounds = new Phaser.Rectangle(x, y, width, height); + + /** + * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move. + */ + this.deadzone = null; + + /** + * @property {boolean} visible - Whether this camera is visible or not. + * @default + */ + this.visible = true; + + /** + * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. + * @default + */ + this.roundPx = true; + + /** + * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. + */ + this.atLimit = { x: false, y: false }; + + /** + * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. + * @default + */ + this.target = null; + + /** + * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot. + */ + this.displayObject = null; + + /** + * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot. + */ + this.scale = null; + + /** + * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. + * @readonly + */ + this.totalInView = 0; + + /** + * The linear interpolation value to use when following a target. + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * @property {Phaser.Point} lerp + * @default + */ + this.lerp = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes. + */ + this.onShakeComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes. + */ + this.onFlashComplete = new Phaser.Signal(); + + /** + * This signal is dispatched when the camera fade effect completes. + * When the fade effect completes you will be left with the screen black (or whatever + * color you faded to). In order to reset this call `Camera.resetFX`. This is called + * automatically when you change State. + * @property {Phaser.Signal} onFadeComplete + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * The Graphics object used to handle camera fx such as fade and flash. + * @property {Phaser.Graphics} fx + * @protected + */ + this.fx = null; + + /** + * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position. + * @private + */ + this._targetPosition = new Phaser.Point(); + + /** + * @property {number} edge - Edge property. + * @private + * @default + */ + this._edge = 0; + + /** + * @property {Phaser.Point} position - Current position of the camera in world. + * @private + * @default + */ + this._position = new Phaser.Point(); + + /** + * @property {Object} _shake - The shake effect container. + * @private + */ + this._shake = { + intensity: 0, + duration: 0, + horizontal: false, + vertical: false, + shakeBounds: true, + x: 0, + y: 0 + }; + + /** + * @property {number} _fxDuration - FX duration timer. + * @private + */ + this._fxDuration = 0; + + /** + * @property {number} _fxType - The FX type running. + * @private + */ + this._fxType = 0; + + /** + * @property {Phaser.Rectangle} + * @private + */ + this._fixedView = new Phaser.Rectangle(); + +}; + +/** +* A follow style that uses no deadzone. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_LOCKON = 0; + +/** +* A follow style that uses a tall, narrow deadzone (0.33 x 0.125) with a center slightly above the view center. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_PLATFORMER = 1; + +/** +* A follow style that uses a square deadzone (0.25 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN = 2; + +/** +* A follow style that uses a small square deadzone (0.125 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_BOTH = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_HORIZONTAL = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_VERTICAL = 6; + +/** +* @constant +* @type {boolean} +*/ +Phaser.Camera.ENABLE_FX = true; + +Phaser.Camera.prototype = { + + /** + * Called automatically by Phaser.World. + * + * @method Phaser.Camera#boot + * @private + */ + boot: function () { + + this.displayObject = this.game.world; + + this.scale = this.game.world.scale; + + this.game.camera = this; + + if (Phaser.Graphics && Phaser.Camera.ENABLE_FX) + { + this.fx = new Phaser.Graphics(this.game); + + this.game.stage.addChild(this.fx); + } + + }, + + /** + * Camera preUpdate. Sets the total view counter to zero. + * + * @method Phaser.Camera#preUpdate + */ + preUpdate: function () { + + this.totalInView = 0; + + }, + + /** + * Tell the camera which sprite to follow. + * + * You can set the follow type and a linear interpolation value. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. + * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. + * + * @method Phaser.Camera#follow + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything. + * @param {number} [style] - Leverage one of the existing {@link deadzone} presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + */ + follow: function (target, style, lerpX, lerpY) { + + if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; } + if (lerpX === undefined) { lerpX = 1; } + if (lerpY === undefined) { lerpY = 1; } + + this.target = target; + this.lerp.set(lerpX, lerpY); + + var helper; + + switch (style) { + + case Phaser.Camera.FOLLOW_PLATFORMER: + var w = this.width / 8; + var h = this.height / 3; + this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN: + helper = Math.max(this.width, this.height) / 4; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT: + helper = Math.max(this.width, this.height) / 8; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_LOCKON: + this.deadzone = null; + break; + + default: + this.deadzone = null; + break; + } + + }, + + /** + * Sets the Camera follow target to null, stopping it from following an object if it's doing so. + * + * @method Phaser.Camera#unfollow + */ + unfollow: function () { + + this.target = null; + + }, + + /** + * Move the camera focus on a display object instantly. + * @method Phaser.Camera#focusOn + * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. + */ + focusOn: function (displayObject) { + + this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight)); + + }, + + /** + * Move the camera focus on a location instantly. + * @method Phaser.Camera#focusOnXY + * @param {number} x - X position. + * @param {number} y - Y position. + */ + focusOnXY: function (x, y) { + + this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight)); + + }, + + /** + * This creates a camera shake effect. It works by applying a random amount of additional + * spacing on the x and y axis each frame. You can control the intensity and duration + * of the effect, and if it should effect both axis or just one. + * + * When the shake effect ends the signal Camera.onShakeComplete is dispatched. + * + * @method Phaser.Camera#shake + * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. + * @param {number} [duration=500] - The duration of the shake effect in milliseconds. + * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL. + * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?). + * @return {boolean} True if the shake effect was started, otherwise false. + */ + shake: function (intensity, duration, force, direction, shakeBounds) { + + if (intensity === undefined) { intensity = 0.05; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = true; } + if (direction === undefined) { direction = Phaser.Camera.SHAKE_BOTH; } + if (shakeBounds === undefined) { shakeBounds = true; } + + if (!force && this._shake.duration > 0) + { + // Can't reset an already running shake + return false; + } + + this._shake.intensity = intensity; + this._shake.duration = duration; + this._shake.shakeBounds = shakeBounds; + + this._shake.x = 0; + this._shake.y = 0; + + this._shake.horizontal = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_HORIZONTAL); + this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL); + + return true; + + }, + + /** + * This creates a camera flash effect. It works by filling the game with the solid fill + * color specified, and then fading it away to alpha 0 over the duration given. + * + * You can use this for things such as hit feedback effects. + * + * When the effect ends the signal Camera.onFlashComplete is dispatched. + * + * @method Phaser.Camera#flash + * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the flash effect in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the flash effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + flash: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0xffffff; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 1; + + this._fxDuration = duration; + this._fxType = 0; + + return true; + + }, + + /** + * This creates a camera fade effect. It works by filling the game with the + * color specified, over the duration given, ending with a solid fill. + * + * You can use this for things such as transitioning to a new scene. + * + * The game will be left 'filled' at the end of this effect, likely obscuring + * everything. In order to reset it you can call `Camera.resetFX` and it will clear the + * fade. Or you can call `Camera.flash` with the same color as the fade, and it will + * reverse the process, bringing the game back into view again. + * + * When the effect ends the signal Camera.onFadeComplete is dispatched. + * + * @method Phaser.Camera#fade + * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the fade in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the fade effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + fade: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0x000000; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 0; + + this._fxDuration = duration; + this._fxType = 1; + + return true; + + }, + + /** + * The camera update loop. This is called automatically by the core game loop. + * + * @method Phaser.Camera#update + * @protected + */ + update: function () { + + if (this._fxDuration > 0) + { + this.updateFX(); + } + + if (this._shake.duration > 0) + { + this.updateShake(); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + this._shake.x = Math.floor(this._shake.x); + this._shake.y = Math.floor(this._shake.y); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the camera flash and fade effects. + * + * @method Phaser.Camera#updateFX + * @private + */ + updateFX: function () { + + if (this._fxType === 0) + { + // flash + this.fx.alpha -= this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha <= 0) + { + this._fxDuration = 0; + this.fx.alpha = 0; + this.onFlashComplete.dispatch(); + } + } + else + { + // fade + this.fx.alpha += this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha >= 1) + { + this._fxDuration = 0; + this.fx.alpha = 1; + this.onFadeComplete.dispatch(); + } + } + + }, + + /** + * Update the camera shake effect. + * + * @method Phaser.Camera#updateShake + * @private + */ + updateShake: function () { + + this._shake.duration -= this.game.time.elapsedMS; + + if (this._shake.duration <= 0) + { + this.onShakeComplete.dispatch(); + this._shake.x = 0; + this._shake.y = 0; + } + else + { + if (this._shake.horizontal) + { + this._shake.x = this.game.rnd.frac() * this._shake.intensity * this.view.width * 2 - this._shake.intensity * this.view.width; + } + + if (this._shake.vertical) + { + this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height; + } + } + + }, + + /** + * Internal method that handles tracking a sprite. + * + * @method Phaser.Camera#updateTarget + * @private + */ + updateTarget: function () { + + this._targetPosition.x = this.view.x + this.target.worldPosition.x; + this._targetPosition.y = this.view.y + this.target.worldPosition.y; + + if (this.deadzone) + { + this._edge = this._targetPosition.x - this.view.x; + + if (this._edge < this.deadzone.left) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.left, this.lerp.x); + } + else if (this._edge > this.deadzone.right) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.right, this.lerp.x); + } + + this._edge = this._targetPosition.y - this.view.y; + + if (this._edge < this.deadzone.top) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.top, this.lerp.y); + } + else if (this._edge > this.deadzone.bottom) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.bottom, this.lerp.y); + } + } + else + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.view.halfWidth, this.lerp.x); + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.view.halfHeight, this.lerp.y); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the Camera bounds to match the game world. + * + * @method Phaser.Camera#setBoundsToWorld + */ + setBoundsToWorld: function () { + + if (this.bounds) + { + this.bounds.copyFrom(this.game.world.bounds); + } + + }, + + /** + * Method called to ensure the camera doesn't venture outside of the game world. + * Called automatically by Camera.update. + * + * @method Phaser.Camera#checkBounds + * @protected + */ + checkBounds: function () { + + this.atLimit.x = false; + this.atLimit.y = false; + + var vx = this.view.x + this._shake.x; + var vw = this.view.right + this._shake.x; + var vy = this.view.y + this._shake.y; + var vh = this.view.bottom + this._shake.y; + + // Make sure we didn't go outside the cameras bounds + if (vx <= this.bounds.x * this.scale.x) + { + this.atLimit.x = true; + this.view.x = this.bounds.x * this.scale.x; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + else if (vw >= this.bounds.right * this.scale.x) + { + this.atLimit.x = true; + this.view.x = (this.bounds.right * this.scale.x) - this.width; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + + if (vy <= this.bounds.top * this.scale.y) + { + this.atLimit.y = true; + this.view.y = this.bounds.top * this.scale.y; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + else if (vh >= this.bounds.bottom * this.scale.y) + { + this.atLimit.y = true; + this.view.y = (this.bounds.bottom * this.scale.y) - this.height; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + + }, + + /** + * A helper function to set both the X and Y properties of the camera at once + * without having to use game.camera.x and game.camera.y. + * + * @method Phaser.Camera#setPosition + * @param {number} x - X position. + * @param {number} y - Y position. + */ + setPosition: function (x, y) { + + this.view.x = x; + this.view.y = y; + + if (this.bounds) + { + this.checkBounds(); + } + + }, + + /** + * Sets the size of the view rectangle given the width and height in parameters. + * + * @method Phaser.Camera#setSize + * @param {number} width - The desired width. + * @param {number} height - The desired height. + */ + setSize: function (width, height) { + + this.view.width = width; + this.view.height = height; + + }, + + /** + * Resets the camera back to 0,0 and un-follows any object it may have been tracking. + * Also immediately resets any camera effects that may have been running such as + * shake, flash or fade. + * + * @method Phaser.Camera#reset + */ + reset: function () { + + this.target = null; + + this.view.x = 0; + this.view.y = 0; + + this._shake.duration = 0; + this._shake.x = 0; + this._shake.y = 0; + + this.resetFX(); + + }, + + /** + * Resets any active FX, such as a fade or flash and immediately clears it. + * Useful to calling after a fade in order to remove the fade from the Stage. + * + * @method Phaser.Camera#resetFX + */ + resetFX: function () { + + if (this.fx) + { + this.fx.clear(); + this.fx.alpha = 0; + } + + this._fxDuration = 0; + + } + +}; + +Phaser.Camera.prototype.constructor = Phaser.Camera; + +/** +* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#x +* @property {number} x - Gets or sets the cameras x position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "x", { + + get: function () { + + return this.view.x; + + }, + + set: function (value) { + + this.view.x = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#y +* @property {number} y - Gets or sets the cameras y position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "y", { + + get: function () { + + return this.view.y; + + }, + + set: function (value) { + + this.view.y = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras position. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#position +* @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object. +*/ +Object.defineProperty(Phaser.Camera.prototype, "position", { + + get: function () { + + this._position.set(this.view.x, this.view.y); + + return this._position; + + }, + + set: function (value) { + + if (typeof value.x !== "undefined") { this.view.x = value.x; } + if (typeof value.y !== "undefined") { this.view.y = value.y; } + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras width. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#width +* @property {number} width - Gets or sets the cameras width. +*/ +Object.defineProperty(Phaser.Camera.prototype, "width", { + + get: function () { + + return this.view.width; + + }, + + set: function (value) { + + this.view.width = value; + + } + +}); + +/** +* The Cameras height. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#height +* @property {number} height - Gets or sets the cameras height. +*/ +Object.defineProperty(Phaser.Camera.prototype, "height", { + + get: function () { + + return this.view.height; + + }, + + set: function (value) { + + this.view.height = value; + + } + +}); + + +/** +* The Cameras shake intensity. +* @name Phaser.Camera#shakeIntensity +* @property {number} shakeIntensity - Gets or sets the cameras shake intensity. +*/ +Object.defineProperty(Phaser.Camera.prototype, "shakeIntensity", { + + get: function () { + + return this._shake.intensity; + + }, + + set: function (value) { + + this._shake.intensity = value; + + } + +}); + + +/** + * Immobile {@link #view} rectangle. Its top-left is always (0, 0). You can use this align fixedToCamera objects. + * @name Phaser.Camera#fixedView + * @property {Phaser.Rectangle} fixedView + * @readonly + */ +Object.defineProperty(Phaser.Camera.prototype, "fixedView", { + + get: function () { + + this._fixedView.setTo(0, 0, this.view.width, this.view.height); + + return this._fixedView; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base State class which can be extended if you are creating your own game. +* It provides quick access to common functions such as the camera, cache, input, match, sound and more. +* +* #### Callbacks +* +* | start | preload | loaded | paused | stop | +* |-------|-------------|------------|--------------|----------| +* | init | | | | | +* | | preload | create | paused | | +* | | loadUpdate* | update* | pauseUpdate* | | +* | | | preRender* | | | +* | | loadRender* | render* | render* | | +* | | | | resumed | | +* | | | | | shutdown | +* +* Update and render calls (*) are repeated. +* +* If your State has a constructor, it will be invoked exactly once, during {@link {@link Phaser.StateManager#add}. +* +* @class Phaser.State +* @constructor +*/ +Phaser.State = function () { + + /** + * @property {Phaser.Game} game - This is a reference to the currently running Game. + */ + this.game = null; + + /** + * @property {string} key - The string based identifier given to the State when added into the State Manager. + */ + this.key = ''; + + /** + * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects. + */ + this.make = null; + + /** + * @property {Phaser.Camera} camera - A handy reference to World.camera. + */ + this.camera = null; + + /** + * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - A reference to the Input Manager. + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions. + */ + this.math = null; + + /** + * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. + */ + this.sound = null; + + /** + * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays. + */ + this.scale = null; + + /** + * @property {Phaser.Stage} stage - A reference to the Stage. + */ + this.stage = null; + + /** + * @property {Phaser.StateManager} stage - A reference to the State Manager, which controls state changes. + */ + this.state = null; + + /** + * @property {Phaser.Time} time - A reference to the game clock and timed events system. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - A reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. + */ + this.world = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. + */ + this.particles = null; + + /** + * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser. + */ + this.physics = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator. + */ + this.rnd = null; + +}; + +Phaser.State.prototype = { + + /** + * init is the very first function called when your State starts up. It's called before preload, create or anything else. + * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables + * or objects before the preloading starts. + * + * @method Phaser.State#init + * @param {...any} args - Any extra arguments passed to {@link Phaser.StateManager#start} or {@link Phaser.StateManager#restart}. + */ + init: function () { + }, + + /** + * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) + * You shouldn't create any objects in this method that require assets that you're also loading in this method, as + * they won't yet be available. + * + * @method Phaser.State#preload + * @param {Phaser.Game} game + */ + preload: function () { + }, + + /** + * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * + * @method Phaser.State#loadUpdate + * @param {Phaser.Game} game + */ + loadUpdate: function () { + }, + + /** + * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. + * + * @method Phaser.State#loadRender + * @param {Phaser.Game} game + */ + loadRender: function () { + }, + + /** + * create is called once preload has completed, this includes the loading of any assets from the Loader. + * If you don't have a preload method then create is the first method called in your State. + * + * @method Phaser.State#create + * @param {Phaser.Game} game + */ + create: function () { + }, + + /** + * The update method is left empty for your own use. + * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. + * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. + * + * @method Phaser.State#update + * @param {Phaser.Game} game + */ + update: function () { + }, + + /** + * The preRender method is called after all Game Objects have been updated, but before any rendering takes place. + * + * @method Phaser.State#preRender + * @param {Phaser.Game} game + * @param {number} elapsedTime + */ + preRender: function () { + }, + + /** + * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. + * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any + * final post-processing style effects here. Note that this happens before plugins postRender takes place. + * + * @method Phaser.State#render + * @param {Phaser.Game} game + */ + render: function () { + }, + + /** + * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. + * + * @method Phaser.State#resize + * @param {number} width + * @param {number} height + */ + resize: function () { + }, + + /** + * This method will be called if the core game loop is paused. + * + * @method Phaser.State#paused + * @param {Phaser.Game} game + */ + paused: function () { + }, + + /** + * This method will be called when the core game loop resumes from a paused state. + * + * @method Phaser.State#resumed + * @param {Phaser.Game} game + */ + resumed: function () { + }, + + /** + * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. + * + * @method Phaser.State#pauseUpdate + * @param {Phaser.Game} game + */ + pauseUpdate: function () { + }, + + /** + * This method will be called when the State is shutdown (i.e. you switch to another state from this one). + * + * @method Phaser.State#shutdown + * @param {Phaser.Game} game + */ + shutdown: function () { + } + +}; + +Phaser.State.prototype.constructor = Phaser.State; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The State Manager is responsible for loading, setting up and switching game states. +* +* @class Phaser.StateManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. +*/ +Phaser.StateManager = function (game, pendingState) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {object} states - The object containing Phaser.States. + */ + this.states = {}; + + /** + * @property {Phaser.State} _pendingState - The state to be switched to in the next frame. + * @private + */ + this._pendingState = null; + + if (typeof pendingState !== 'undefined' && pendingState !== null) + { + this._pendingState = pendingState; + } + + /** + * @property {boolean} _clearWorld - Clear the world when we switch state? + * @private + */ + this._clearWorld = false; + + /** + * @property {boolean} _clearCache - Clear the cache when we switch state? + * @private + */ + this._clearCache = false; + + /** + * @property {boolean} _created - Flag that sets if the State has been created or not. + * @private + */ + this._created = false; + + /** + * @property {any[]} _args - Temporary container when you pass vars from one State to another. + * @private + */ + this._args = []; + + /** + * @property {string} current - The current active State object. + * @default + */ + this.current = ''; + + /** + * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. + * + * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start + * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states + * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. + * + * The callback you specify is sent two parameters: the string based key of the new state, + * and the second parameter is the string based key of the old / previous state. + * + * @property {Phaser.Signal} onStateChange + */ + this.onStateChange = new Phaser.Signal(); + + /** + * @property {function} onInitCallback - This is called when the state is set as the active state. + * @default + */ + this.onInitCallback = null; + + /** + * @property {function} onPreloadCallback - This is called when the state starts to load assets. + * @default + */ + this.onPreloadCallback = null; + + /** + * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins. + * @default + */ + this.onCreateCallback = null; + + /** + * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). + * @default + */ + this.onUpdateCallback = null; + + /** + * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). + * @default + */ + this.onRenderCallback = null; + + /** + * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. + * @default + */ + this.onResizeCallback = null; + + /** + * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. + * @default + */ + this.onPreRenderCallback = null; + + /** + * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase. + * @default + */ + this.onLoadUpdateCallback = null; + + /** + * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase. + * @default + */ + this.onLoadRenderCallback = null; + + /** + * @property {function} onPausedCallback - This is called when the game is paused. + * @default + */ + this.onPausedCallback = null; + + /** + * @property {function} onResumedCallback - This is called when the game is resumed from a paused state. + * @default + */ + this.onResumedCallback = null; + + /** + * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused. + * @default + */ + this.onPauseUpdateCallback = null; + + /** + * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state). + * @default + */ + this.onShutDownCallback = null; + +}; + +Phaser.StateManager.prototype = { + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * @method Phaser.StateManager#boot + * @private + */ + boot: function () { + + this.game.onPause.add(this.pause, this); + this.game.onResume.add(this.resume, this); + + if (this._pendingState !== null && typeof this._pendingState !== 'string') + { + this.add('default', this._pendingState, true); + } + + }, + + /** + * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. + * + * The State can be any of + * + * - a plain JavaScript object containing at least one required callback (see {@link #checkState}) + * - an instance of {@link Phaser.State} + * - an instance of a class extending Phaser.State + * - a constructor function (class) + * + * If a function is given a new state object will be created by calling it, passing the current {@link Phaser.Game game} as the first argument. + * + * @method Phaser.StateManager#add + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + * @param {Phaser.State|object|function} state - The state you want to switch to. + * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it. + */ + add: function (key, state, autoStart) { + + if (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; + + }, + + /** + * Delete the given state. + * @method Phaser.StateManager#remove + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + */ + 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.onPreRenderCallback = null; + this.onRenderCallback = null; + this.onResizeCallback = null; + this.onPausedCallback = null; + this.onResumedCallback = null; + this.onPauseUpdateCallback = null; + } + + delete this.states[key]; + + }, + + /** + * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. + * + * @method Phaser.StateManager#start + * @param {string} key - The key of the state you want to start. + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one). + */ + start: function (key, clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + if (this.checkState(key)) + { + // Place the state in the queue. It will be started the next time the game loop begins. + this._pendingState = key; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 3) + { + this._args = Array.prototype.splice.call(arguments, 3); + } + } + + }, + + /** + * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. + * + * @method Phaser.StateManager#restart + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one. + */ + restart: function (clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + // Place the state in the queue. It will be started the next time the game loop starts. + this._pendingState = this.current; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 2) + { + this._args = Array.prototype.slice.call(arguments, 2); + } + + }, + + /** + * Used by onInit and onShutdown when those functions don't exist on the state + * @method Phaser.StateManager#dummy + * @private + */ + dummy: function () { + }, + + /** + * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. + * + * @method Phaser.StateManager#preUpdate + */ + preUpdate: function () { + + if (this._pendingState && this.game.isBooted) + { + var previousStateKey = this.current; + + // Already got a state running? + this.clearCurrentState(); + + this.setCurrentState(this._pendingState); + + this.onStateChange.dispatch(this.current, previousStateKey); + + if (this.current !== this._pendingState) + { + return; + } + else + { + this._pendingState = null; + } + + // If StateManager.start has been called from the init of a State that ALSO has a preload, then + // onPreloadCallback will be set, but must be ignored + if (this.onPreloadCallback) + { + this.game.load.reset(true); + this.onPreloadCallback.call(this.callbackContext, this.game); + + // Is the loader empty? + if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0) + { + this.loadComplete(); + } + else + { + // Start the loader going as we have something in the queue + this.game.load.start(); + } + } + else + { + // No init? Then there was nothing to load either + this.loadComplete(); + } + } + + }, + + /** + * This method clears the current State, calling its shutdown callback. The process also removes any active tweens, + * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. + * + * @method Phaser.StateManager#clearCurrentState + */ + clearCurrentState: function () { + + if (this.current) + { + if (this.onShutDownCallback) + { + 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(); + + this.game.scale.reset(this._clearWorld); + + if (this.game.debug) + { + this.game.debug.reset(); + } + + if (this._clearWorld) + { + this.game.world.shutdown(); + + if (this._clearCache) + { + this.game.cache.destroy(); + } + } + } + + }, + + /** + * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. + * + * @method Phaser.StateManager#checkState + * @param {string} key - The key of the state you want to check. + * @return {boolean} true if the State has the required functions, otherwise false. + */ + checkState: function (key) { + + var state = this.states[key]; + + if (state) + { + if (state.preload || state.create || state.update || state.render) + { + return true; + } + else + { + console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"); + return false; + } + } + else + { + console.warn("Phaser.StateManager - No state found with the key: " + key); + return false; + } + + }, + + /** + * Links game properties to the State given by the key. + * + * @method Phaser.StateManager#link + * @param {string} key - State key. + * @protected + */ + link: function (key) { + + var state = this.states[key]; + + state.game = this.game; + state.add = this.game.add; + state.make = this.game.make; + state.camera = this.game.camera; + state.cache = this.game.cache; + state.input = this.game.input; + state.load = this.game.load; + state.math = this.game.math; + state.sound = this.game.sound; + state.scale = this.game.scale; + state.state = this; + state.stage = this.game.stage; + state.time = this.game.time; + state.tweens = this.game.tweens; + state.world = this.game.world; + state.particles = this.game.particles; + state.rnd = this.game.rnd; + state.physics = this.game.physics; + state.key = key; + + }, + + /** + * Nulls all State level Phaser properties, including a reference to Game. + * + * @method Phaser.StateManager#unlink + * @param {string} key - State key. + * @protected + */ + unlink: function (key) { + + var state = this.states[key]; + + if (state) + { + state.game = null; + state.add = null; + state.make = null; + state.camera = null; + state.cache = null; + state.input = null; + state.load = null; + state.math = null; + state.sound = null; + state.scale = null; + state.state = null; + state.stage = null; + state.time = null; + state.tweens = null; + state.world = null; + state.particles = null; + state.rnd = null; + state.physics = null; + } + + }, + + /** + * Sets the current State. Should not be called directly (use StateManager.start) + * + * @method Phaser.StateManager#setCurrentState + * @param {string} key - State key. + * @private + */ + setCurrentState: function (key) { + + var state = this.states[key]; + + this.callbackContext = state; + + this.link(key); + + // Used when the state is set as being the current active state + this.onInitCallback = state['init'] || this.dummy; + + this.onPreloadCallback = state['preload'] || null; + this.onLoadRenderCallback = state['loadRender'] || null; + this.onLoadUpdateCallback = state['loadUpdate'] || null; + this.onCreateCallback = state['create'] || null; + this.onUpdateCallback = state['update'] || null; + this.onPreRenderCallback = state['preRender'] || null; + this.onRenderCallback = state['render'] || null; + this.onResizeCallback = state['resize'] || null; + this.onPausedCallback = state['paused'] || null; + this.onResumedCallback = state['resumed'] || null; + this.onPauseUpdateCallback = state['pauseUpdate'] || null; + + // Used when the state is no longer the current active state + this.onShutDownCallback = state['shutdown'] || this.dummy; + + // Reset the physics system, but not on the first state start + if (this.current !== '') + { + this.game.physics.reset(); + } + + this.current = key; + this._created = false; + + // At this point key and pendingState should equal each other + this.onInitCallback.apply(this.callbackContext, this._args); + + // If they no longer do then the init callback hit StateManager.start + if (key === this._pendingState) + { + this._args = []; + } + + this.game._kickstart = true; + + }, + + /** + * Gets the current State. + * + * @method Phaser.StateManager#getCurrentState + * @return {Phaser.State} + * @public + */ + getCurrentState: function() { + return this.states[this.current]; + }, + + /** + * @method Phaser.StateManager#loadComplete + * @protected + */ + loadComplete: function () { + + // Make sure to do load-update one last time before state is set to _created + if (this._created === false && this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + + if (this._created === false && this.onCreateCallback) + { + this._created = true; + this.onCreateCallback.call(this.callbackContext, this.game); + } + else + { + this._created = true; + } + + }, + + /** + * @method Phaser.StateManager#pause + * @protected + */ + pause: function () { + + if (this._created && this.onPausedCallback) + { + this.onPausedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#resume + * @protected + */ + resume: function () { + + if (this._created && this.onResumedCallback) + { + this.onResumedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#update + * @protected + */ + update: function () { + + if (this._created) + { + if (this.onUpdateCallback) + { + this.onUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#pauseUpdate + * @protected + */ + pauseUpdate: function () { + + if (this._created) + { + if (this.onPauseUpdateCallback) + { + this.onPauseUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#preRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + preRender: function (elapsedTime) { + + if (this._created && this.onPreRenderCallback) + { + this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime); + } + + }, + + /** + * @method Phaser.StateManager#resize + * @protected + */ + resize: function (width, height) { + + if (this.onResizeCallback) + { + this.onResizeCallback.call(this.callbackContext, width, height); + } + + }, + + /** + * @method Phaser.StateManager#render + * @protected + */ + render: function () { + + if (this._created) + { + if (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); + this.game.context.restore(); + } + else + { + this.onRenderCallback.call(this.callbackContext, this.game); + } + } + } + else + { + if (this.onLoadRenderCallback) + { + this.onLoadRenderCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. + * You don't recover from this without rebuilding the Phaser instance again. + * @method Phaser.StateManager#destroy + */ + destroy: function () { + + this._clearWorld = true; + this._clearCache = true; + + this.clearCurrentState(); + + 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; + this.current = ''; + + } + +}; + +Phaser.StateManager.prototype.constructor = Phaser.StateManager; + +/** +* @name Phaser.StateManager#created +* @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default). +* @readOnly +*/ +Object.defineProperty(Phaser.StateManager.prototype, "created", { + + get: function () { + + return this._created; + + } + +}); + +/** +* "It's like nailing jelly to a kitten" - Gary Penn +*/ + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Signals are what Phaser uses to handle events and event dispatching. +* You can listen for a Signal by binding a callback / function to it. +* This is done by using either `Signal.add` or `Signal.addOnce`. +* +* For example you can listen for a touch or click event from the Input Manager +* by using its `onDown` Signal: +* +* `game.input.onDown.add(function() { ... });` +* +* Rather than inline your function, you can pass a reference: +* +* `game.input.onDown.add(clicked, this);` +* `function clicked () { ... }` +* +* In this case the second argument (`this`) is the context in which your function should be called. +* +* Now every time the InputManager dispatches the `onDown` signal (or event), your function +* will be called. +* +* Multiple callbacks can be bound to the same signal. +* They're ordered first by their `priority` arguments and then by the order in which they were added. +* If a callback calls {@link #halt} or returns `false`, any remaining callbacks are skipped. +* +* Very often a Signal will send arguments to your function. +* This is specific to the Signal itself. +* If you're unsure then check the documentation, or failing that simply do: +* +* `Signal.add(function() { console.log(arguments); })` +* +* and it will log all of the arguments your function received from the Signal. +* +* Sprites have lots of default signals you can listen to in their Events class, such as: +* +* `sprite.events.onKilled` +* +* Which is called automatically whenever the Sprite is killed. +* There are lots of other events, see the Events component for a list. +* +* As well as listening to pre-defined Signals you can also create your own: +* +* `var mySignal = new Phaser.Signal();` +* +* This creates a new Signal. You can bind a callback to it: +* +* `mySignal.add(myCallback, this);` +* +* and then finally when ready you can dispatch the Signal: +* +* `mySignal.dispatch(your arguments);` +* +* And your callback will be invoked. See the dispatch method for more details. +* +* @class Phaser.Signal +* @constructor +*/ +Phaser.Signal = function () {}; + +Phaser.Signal.prototype = { + + /** + * @property {?Array.} _bindings - Internal variable. + * @private + */ + _bindings: null, + + /** + * @property {any} _prevParams - Internal variable. + * @private + */ + _prevParams: null, + + /** + * Memorize the previously dispatched event? + * + * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}. + * Use {@link #forget} to clear any currently memorized event. + * + * @property {boolean} memorize + */ + memorize: false, + + /** + * @property {boolean} _shouldPropagate + * @private + */ + _shouldPropagate: true, + + /** + * Is the Signal active? Only active signals will broadcast dispatched events. + * + * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}. + * + * @property {boolean} active + * @default + */ + active: true, + + /** + * @property {function} _boundDispatch - The bound dispatch function, if any. + * @private + */ + _boundDispatch: false, + + /** + * @method Phaser.Signal#validateListener + * @param {function} listener - Signal handler function. + * @param {string} fnName - Function name. + * @private + */ + validateListener: function (listener, fnName) { + + if (typeof listener !== 'function') + { + throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); + } + + }, + + /** + * @method Phaser.Signal#_registerListener + * @private + * @param {function} listener - Signal handler function. + * @param {boolean} isOnce - Should the listener only be called once? + * @param {object} [listenerContext] - The context under which the listener is invoked. + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + _registerListener: function (listener, isOnce, listenerContext, priority, args) { + + var prevIndex = this._indexOfListener(listener, listenerContext); + var binding; + + if (prevIndex !== -1) + { + binding = this._bindings[prevIndex]; + + if (binding.isOnce() !== isOnce) + { + throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); + } + } + else + { + binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args); + this._addBinding(binding); + } + + if (this.memorize && this._prevParams) + { + binding.execute(this._prevParams); + } + + return binding; + + }, + + /** + * @method Phaser.Signal#_addBinding + * @private + * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. + */ + _addBinding: function (binding) { + + if (!this._bindings) + { + this._bindings = []; + } + + // Simplified insertion sort + var n = this._bindings.length; + + do { + n--; + } + while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); + + this._bindings.splice(n + 1, 0, binding); + + }, + + /** + * @method Phaser.Signal#_indexOfListener + * @private + * @param {function} listener - Signal handler function. + * @param {object} [context=null] - Signal handler function. + * @return {number} The index of the listener within the private bindings array. + */ + _indexOfListener: function (listener, context) { + + if (!this._bindings) + { + return -1; + } + + if (context === undefined) { context = null; } + + var n = this._bindings.length; + var cur; + + while (n--) + { + cur = this._bindings[n]; + + if (cur._listener === listener && cur.context === context) + { + return n; + } + } + + return -1; + + }, + + /** + * Check if a specific listener is attached. + * + * @method Phaser.Signal#has + * @param {function} listener - Signal handler function. + * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @return {boolean} If Signal has the specified listener. + */ + has: function (listener, context) { + + return this._indexOfListener(listener, context) !== -1; + + }, + + /** + * Add an event listener for this signal. + * + * An event listener is a callback with a related context and priority. + * + * You can optionally provide extra arguments which will be passed to the callback after any internal parameters. + * + * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. + * Any arguments you've specified after `priority` will be sent as well: + * + * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` + * + * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. + * + * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', + * and the value 100 were the custom arguments given in the call to 'add'. + * + * If the callback calls {@link #halt} or returns `false`, any remaining callbacks bound to this Signal are skipped. + * + * @method Phaser.Signal#add + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + add: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'add'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, false, listenerContext, priority, args); + + }, + + /** + * Add a one-time listener - the listener is automatically removed after the first execution. + * + * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and + * the listener will be removed immediately. + * + * @method Phaser.Signal#addOnce + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + addOnce: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'addOnce'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, true, listenerContext, priority, args); + + }, + + /** + * Remove a single event listener. + * + * @method Phaser.Signal#remove + * @param {function} listener - Handler function that should be removed. + * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {function} Listener handler function. + */ + remove: function (listener, context) { + + this.validateListener(listener, 'remove'); + + var i = this._indexOfListener(listener, context); + + if (i !== -1) + { + this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal + this._bindings.splice(i, 1); + } + + return listener; + + }, + + /** + * Remove all event listeners. + * + * @method Phaser.Signal#removeAll + * @param {object} [context=null] - If specified only listeners for the given context will be removed. + */ + removeAll: function (context) { + + if (context === undefined) { context = null; } + + if (!this._bindings) + { + return; + } + + var n = this._bindings.length; + + while (n--) + { + if (context) + { + if (this._bindings[n].context === context) + { + this._bindings[n]._destroy(); + this._bindings.splice(n, 1); + } + } + else + { + this._bindings[n]._destroy(); + } + } + + if (!context) + { + this._bindings.length = 0; + } + + }, + + /** + * Gets the total number of listeners attached to this Signal. + * + * @method Phaser.Signal#getNumListeners + * @return {integer} Number of listeners attached to the Signal. + */ + getNumListeners: function () { + + return this._bindings ? this._bindings.length : 0; + + }, + + /** + * Stop propagation of the event, blocking the dispatch to next listener on the queue. + * + * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. + * See {@link #active} to enable/disable the signal entirely. + * + * @method Phaser.Signal#halt + */ + halt: function () { + + this._shouldPropagate = false; + + }, + + /** + * Dispatch / broadcast the event to all listeners. + * + * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}. + * + * @method Phaser.Signal#dispatch + * @param {any} [params] - Parameters that should be passed to each handler. + */ + dispatch: function () { + + if (!this.active || !this._bindings) + { + return; + } + + var paramsArr = Array.prototype.slice.call(arguments); + var n = this._bindings.length; + var bindings; + + if (this.memorize) + { + this._prevParams = paramsArr; + } + + if (!n) + { + // Should come after memorize + return; + } + + bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch + this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. + + //execute all callbacks until end of the list or until a callback returns `false` or stops propagation + //reverse loop since listeners with higher priority will be added at the end of the list + do { + n--; + } + while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); + + }, + + /** + * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any. + * + * @method Phaser.Signal#forget + */ + forget: function() { + + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * Dispose the signal - no more events can be dispatched. + * + * This removes all event listeners and clears references to external objects. + * Calling methods on a disposed objects results in undefined behavior. + * + * @method Phaser.Signal#dispose + */ + dispose: function () { + + this.removeAll(); + + this._bindings = null; + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * A string representation of the object. + * + * @method Phaser.Signal#toString + * @return {string} String representation of the object. + */ + toString: function () { + + return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']'; + + } + +}; + +/** +* Create a `dispatch` function that maintains a binding to the original Signal context. +* +* Use the resulting value if the dispatch function needs to be passed somewhere +* or called independently of the Signal object. +* +* @memberof Phaser.Signal +* @property {function} boundDispatch +*/ +Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", { + + get: function () { + var _this = this; + return this._boundDispatch || (this._boundDispatch = function () { + return _this.dispatch.apply(_this, arguments); + }); + } + +}); + +Phaser.Signal.prototype.constructor = Phaser.Signal; + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Object that represents a binding between a Signal and a listener function. +* This is an internal constructor and shouldn't be created directly. +* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. +* +* @class Phaser.SignalBinding +* @constructor +* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to. +* @param {function} listener - Handler function bound to the signal. +* @param {boolean} isOnce - If binding should be executed just once. +* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). +* @param {number} [priority] - The priority level of the event listener. (default = 0). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. +*/ +Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) { + + /** + * @property {Phaser.Game} _listener - Handler function bound to the signal. + * @private + */ + this._listener = listener; + + if (isOnce) + { + this._isOnce = true; + } + + if (listenerContext != null) /* not null/undefined */ + { + this.context = listenerContext; + } + + /** + * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to. + * @private + */ + this._signal = signal; + + if (priority) + { + this._priority = priority; + } + + if (args && args.length) + { + this._args = args; + } + +}; + +Phaser.SignalBinding.prototype = { + + /** + * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + */ + context: null, + + /** + * @property {boolean} _isOnce - If binding should be executed just once. + * @private + */ + _isOnce: false, + + /** + * @property {number} _priority - Listener priority. + * @private + */ + _priority: 0, + + /** + * @property {array} _args - Listener arguments. + * @private + */ + _args: null, + + /** + * @property {number} callCount - The number of times the handler function has been called. + */ + callCount: 0, + + /** + * If binding is active and should be executed. + * @property {boolean} active + * @default + */ + active: true, + + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). + * @property {array|null} params + * @default + */ + params: null, + + /** + * Call listener passing arbitrary parameters. + * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. + * @method Phaser.SignalBinding#execute + * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener. + * @return {any} Value returned by the listener. + */ + execute: function(paramsArr) { + + var handlerReturn, params; + + if (this.active && !!this._listener) + { + params = this.params ? this.params.concat(paramsArr) : paramsArr; + + if (this._args) + { + params = params.concat(this._args); + } + + handlerReturn = this._listener.apply(this.context, params); + + this.callCount++; + + if (this._isOnce) + { + this.detach(); + } + } + + return handlerReturn; + + }, + + /** + * Detach binding from signal. + * alias to: @see mySignal.remove(myBinding.getListener()); + * @method Phaser.SignalBinding#detach + * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ + detach: function () { + return this.isBound() ? this._signal.remove(this._listener, this.context) : null; + }, + + /** + * @method Phaser.SignalBinding#isBound + * @return {boolean} True if binding is still bound to the signal and has a listener. + */ + isBound: function () { + return (!!this._signal && !!this._listener); + }, + + /** + * @method Phaser.SignalBinding#isOnce + * @return {boolean} If SignalBinding will only be executed once. + */ + isOnce: function () { + return this._isOnce; + }, + + /** + * @method Phaser.SignalBinding#getListener + * @return {function} Handler function bound to the signal. + */ + getListener: function () { + return this._listener; + }, + + /** + * @method Phaser.SignalBinding#getSignal + * @return {Phaser.Signal} Signal that listener is currently bound to. + */ + getSignal: function () { + return this._signal; + }, + + /** + * Delete instance properties + * @method Phaser.SignalBinding#_destroy + * @private + */ + _destroy: function () { + delete this._signal; + delete this._listener; + delete this.context; + }, + + /** + * @method Phaser.SignalBinding#toString + * @return {string} String representation of the object. + */ + toString: function () { + return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']'; + } + +}; + +Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding; + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Filter class to use for any Phaser filter development. +* If you want to make a custom filter, this should be your base class. +* +* The default uniforms, types and values for all Filters are: +* +* ```javascript +* resolution: { type: '2f', value: { x: 256, y: 256 }} +* time: { type: '1f', value: 0 } +* mouse: { type: '2f', value: { x: 0.0, y: 0.0 } } +* date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] } +* sampleRate: { type: '1f', value: 44100.0 } +* iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* ``` +* +* The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and +* therefore only work in WebGL and are not supported by Canvas at all. +* +* @class Phaser.Filter +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [uniforms] - Uniform mappings object. The uniforms are added on the default uniforms, or replace them if the keys are the same. +* @param {Array|string} [fragmentSrc] - The fragment shader code. Either an array, one element per line of code, or a string. +*/ +Phaser.Filter = function (game, uniforms, fragmentSrc) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. + * @default + */ + this.type = Phaser.WEBGL_FILTER; + + /** + * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. + * For example the blur filter has two passes blurX and blurY. + * @property {array} passes - An array of filter objects. + * @private + */ + this.passes = [ this ]; + + /** + * @property {array} shaders - Array an array of shaders. + * @private + */ + this.shaders = []; + + /** + * @property {boolean} dirty - Internal PIXI var. + * @default + */ + this.dirty = true; + + /** + * @property {number} padding - Internal PIXI var. + * @default + */ + this.padding = 0; + + /** + * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same) + */ + this.prevPoint = new Phaser.Point(); + + /* + * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D. + */ + + var d = new Date(); + + /** + * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. + */ + this.uniforms = { + + resolution: { type: '2f', value: { x: 256, y: 256 }}, + time: { type: '1f', value: 0 }, + mouse: { type: '2f', value: { x: 0.0, y: 0.0 } }, + date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, + sampleRate: { type: '1f', value: 44100.0 }, + iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + + }; + + // Copy over / replace any passed in the constructor + if (uniforms) + { + for (var key in uniforms) + { + this.uniforms[key] = uniforms[key]; + } + } + + // If fragmentSrc is a string, split it based on new-lines into an array + if (typeof fragmentSrc === 'string') + { + fragmentSrc = fragmentSrc.split('\n'); + } + + /** + * @property {array|string} fragmentSrc - The fragment shader code. + */ + this.fragmentSrc = fragmentSrc || []; + +}; + +Phaser.Filter.prototype = { + + /** + * This should be over-ridden. Will receive a variable number of arguments. + * + * @method Phaser.Filter#init + */ + init: function () { + + // This should be over-ridden. Will receive a variable number of arguments. + + }, + + /** + * Set the resolution uniforms on the filter. + * + * @method Phaser.Filter#setResolution + * @param {number} width - The width of the display. + * @param {number} height - The height of the display. + */ + setResolution: function (width, height) { + + this.uniforms.resolution.value.x = width; + this.uniforms.resolution.value.y = height; + + }, + + /** + * Updates the filter. + * + * @method Phaser.Filter#update + * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. + */ + update: function (pointer) { + + if (pointer) + { + var x = pointer.x / this.game.width; + var y = 1 - pointer.y / this.game.height; + + if (x !== this.prevPoint.x || y !== this.prevPoint.y) + { + this.uniforms.mouse.value.x = x.toFixed(2); + this.uniforms.mouse.value.y = y.toFixed(2); + this.prevPoint.set(x, y); + } + } + + this.uniforms.time.value = this.game.time.totalElapsedSeconds(); + + }, + + /** + * Creates a new Phaser.Image object using a blank texture and assigns + * this Filter to it. The image is then added to the world. + * + * If you don't provide width and height values then Filter.width and Filter.height are used. + * + * If you do provide width and height values then this filter will be resized to match those + * values. + * + * @method Phaser.Filter#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. + * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, width, height, anchorX, anchorY) { + + if (anchorX === undefined) { anchorX = 0; } + if (anchorY === undefined) { anchorY = 0; } + + if (width !== undefined && width !== null) + { + this.width = width; + } + else + { + width = this.width; + } + + if (height !== undefined && height !== null) + { + this.height = height; + } + else + { + height = this.height; + } + + var image = this.game.add.image(x, y, Phaser.Cache.DEFAULT); + + image.width = width; + image.height = height; + + image.anchor.set(anchorX, anchorY); + + image.filters = [ this ]; + + return image; + + }, + + /** + * Syncs the uniforms between the class object and the shaders. + * + * @method Phaser.Filter#syncUniforms + */ + syncUniforms: function () { + + for (var i = 0; i < this.shaders.length; i++) + { + this.shaders[i].dirty = true; + } + + }, + + /** + * Clear down this Filter and null out references to game. + * + * @method Phaser.Filter#destroy + */ + destroy: function () { + + this.passes.length = 0; + this.shaders.length = 0; + this.fragmentSrc.length = 0; + + this.game = null; + this.uniforms = null; + this.prevPoint = null; + + } + +}; + +Phaser.Filter.prototype.constructor = Phaser.Filter; + +/** +* @name Phaser.Filter#width +* @property {number} width - The width (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'width', { + + get: function () { + + return this.uniforms.resolution.value.x; + + }, + + set: function (value) { + + this.uniforms.resolution.value.x = value; + + } + +}); + +/** +* @name Phaser.Filter#height +* @property {number} height - The height (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'height', { + + get: function () { + + return this.uniforms.resolution.value.y; + + }, + + set: function (value) { + + this.uniforms.resolution.value.y = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Plugin template to use for any Phaser plugin development. +* +* ##### Callbacks +* +* add | active | visible | remove +* -----|-------------|-------------|-------- +* init | | | +* | preUpdate* | | +* | update* | render* | +* | postUpdate* | postRender* | +* | | | destroy +* +* Update and render calls are repeated (*). +* +* @class Phaser.Plugin +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager. +*/ +Phaser.Plugin = function (game, parent) { + + if (parent === undefined) { parent = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. + */ + this.parent = parent; + + /** + * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. + * @default + */ + this.active = false; + + /** + * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. + * @default + */ + this.visible = false; + + /** + * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. + * @default + */ + this.hasPreUpdate = false; + + /** + * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. + * @default + */ + this.hasUpdate = false; + + /** + * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. + * @default + */ + this.hasPostUpdate = false; + + /** + * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. + * @default + */ + this.hasRender = false; + + /** + * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. + * @default + */ + this.hasPostRender = false; + +}; + +Phaser.Plugin.prototype = { + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It is only called if active is set to true. + * @method Phaser.Plugin#preUpdate + */ + preUpdate: function () { + }, + + /** + * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It is only called if active is set to true. + * @method Phaser.Plugin#update + */ + update: function () { + }, + + /** + * Render is called right after the Game Renderer completes, but before the State.render. + * It is only called if visible is set to true. + * @method Phaser.Plugin#render + */ + render: function () { + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It is only called if visible is set to true. + * @method Phaser.Plugin#postRender + */ + postRender: function () { + }, + + /** + * Clear down this Plugin and null out references + * @method Phaser.Plugin#destroy + */ + destroy: function () { + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + + } + +}; + +Phaser.Plugin.prototype.constructor = Phaser.Plugin; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. +* +* @class Phaser.PluginManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.PluginManager = function(game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager. + */ + this.plugins = []; + + /** + * @property {number} _len - Internal cache var. + * @private + */ + this._len = 0; + + /** + * @property {number} _i - Internal cache var. + * @private + */ + this._i = 0; + +}; + +Phaser.PluginManager.prototype = { + + /** + * Add a new Plugin into the PluginManager. + * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.PluginManager#add + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + add: function (plugin) { + + var args = Array.prototype.slice.call(arguments, 1); + var result = false; + + // Prototype? + if (typeof plugin === 'function') + { + plugin = new plugin(this.game, this); + } + else + { + plugin.game = this.game; + plugin.parent = this; + } + + // Check for methods now to avoid having to do this every loop + 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; + } + + // The plugin must have at least one of the above functions to be added to the PluginManager. + 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); + + // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager + if (typeof plugin['init'] === 'function') + { + plugin.init.apply(plugin, args); + } + + return plugin; + } + else + { + return null; + } + }, + + /** + * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. + * + * @method Phaser.PluginManager#remove + * @param {Phaser.Plugin} plugin - The plugin to be removed. + * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed? + */ + remove: function (plugin, destroy) { + + if (destroy === undefined) { destroy = true; } + + this._i = this._len; + + while (this._i--) + { + if (this.plugins[this._i] === plugin) + { + if (destroy) + { + plugin.destroy(); + } + + this.plugins.splice(this._i, 1); + this._len--; + return; + } + } + + }, + + /** + * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. + * + * @method Phaser.PluginManager#removeAll + */ + removeAll: function() { + + this._i = this._len; + + while (this._i--) + { + this.plugins[this._i].destroy(); + } + + this.plugins.length = 0; + this._len = 0; + + }, + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#preUpdate + */ + 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 is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#update + */ + 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 is the last thing to be called before the world render. + * In particular, it is called after the world postUpdate, which means the camera has been adjusted. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#postUpdate + */ + 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 is called right after the Game Renderer completes, but before the State.render. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#render + */ + 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(); + } + } + + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#postRender + */ + 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(); + } + } + + }, + + /** + * Clear down this PluginManager, calls destroy on every plugin and nulls out references. + * + * @method Phaser.PluginManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.game = null; + + } + +}; + +Phaser.PluginManager.prototype.constructor = Phaser.PluginManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Stage controls root level display objects upon which everything is displayed. +* It also handles browser visibility handling and the pausing due to loss of focus. +* +* @class Phaser.Stage +* @extends PIXI.DisplayObjectContainer +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Stage = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {string} name - The name of this object. + * @default + */ + this.name = '_stage_root'; + + /** + * By default if the browser tab loses focus the game will pause. + * You can stop that behavior by setting this property to true. + * Note that the browser can still elect to pause your game if it wishes to do so, + * for example swapping to another browser tab. This will cause the RAF callback to halt, + * effectively pausing your game, even though no in-game pause event is triggered if you enable this property. + * @property {boolean} disableVisibilityChange + * @default + */ + this.disableVisibilityChange = false; + + /** + * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. + * @default + */ + this.exists = true; + + /** + * @property {Phaser.Matrix} worldTransform - Current transform of the object based on world (parent) factors + * @private + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage) + * @private + * @readOnly + */ + this.stage = this; + + /** + * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. + */ + this.currentRenderOrderID = 0; + + /** + * @property {string} hiddenVar - The page visibility API event name. + * @private + */ + this._hiddenVar = 'hidden'; + + /** + * @property {function} _onChange - The blur/focus event handler. + * @private + */ + this._onChange = null; + + /** + * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor. + * @private + */ + this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' }; + + if (!this.game.transparent) + { + // transparent = 0,0,0,0 - otherwise r,g,b,1 + this._bgColor.a = 1; + } + + if (game.config) + { + this.parseConfig(game.config); + } + +}; + +Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Stage.prototype.constructor = Phaser.Stage; + +/** +* Parses a Game configuration object. +* +* @method Phaser.Stage#parseConfig +* @protected +* @param {object} config -The configuration object to parse. +*/ +Phaser.Stage.prototype.parseConfig = function (config) { + + if (config['disableVisibilityChange']) + { + this.disableVisibilityChange = config['disableVisibilityChange']; + } + + if (config['backgroundColor']) + { + this.setBackgroundColor(config['backgroundColor']); + } + +}; + +/** +* Initialises the stage and adds the event listeners. +* @method Phaser.Stage#boot +* @private +*/ +Phaser.Stage.prototype.boot = function () { + + Phaser.DOM.getOffset(this.game.canvas, this.offset); + + Phaser.Canvas.setUserSelect(this.game.canvas, 'none'); + Phaser.Canvas.setTouchAction(this.game.canvas, 'none'); + + this.checkVisibility(); + +}; + +/** +* This is called automatically after the plugins preUpdate and before the State.update. +* Most objects have preUpdate methods and it's where initial movement and positioning is done. +* +* @method Phaser.Stage#preUpdate +*/ +Phaser.Stage.prototype.preUpdate = function () { + + this.currentRenderOrderID = 0; + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + +}; + +/** +* This is called automatically after the State.update, but before particles or plugins update. +* +* @method Phaser.Stage#update +*/ +Phaser.Stage.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + this.children[i].update(); + } + +}; + +/** +* This is called automatically before the renderer runs and after the plugins have updated. +* In postUpdate this is where all the final physics calculations and object positioning happens. +* The objects are processed in the order of the display list. +* +* @method Phaser.Stage#postUpdate +*/ +Phaser.Stage.prototype.postUpdate = function () { + + // Apply the camera shake, fade, bounds, etc + this.game.camera.update(); + + // Camera target first? + if (this.game.camera.target) + { + this.game.camera.target.postUpdate(); + + this.updateTransform(); + + this.game.camera.updateTarget(); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + this.updateTransform(); + +}; + +/** +* Updates the transforms for all objects on the display list. +* This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. +* +* @method Phaser.Stage#updateTransform +*/ +Phaser.Stage.prototype.updateTransform = function () { + + this.worldAlpha = 1; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +/** +* Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. +* Also listens for window.onblur and window.onfocus. +* +* @method Phaser.Stage#checkVisibility +*/ +Phaser.Stage.prototype.checkVisibility = function () { + + if (document.hidden !== undefined) + { + this._hiddenVar = 'visibilitychange'; + } + else if (document.webkitHidden !== undefined) + { + this._hiddenVar = 'webkitvisibilitychange'; + } + else if (document.mozHidden !== undefined) + { + this._hiddenVar = 'mozvisibilitychange'; + } + else if (document.msHidden !== undefined) + { + this._hiddenVar = 'msvisibilitychange'; + } + else + { + this._hiddenVar = null; + } + + var _this = this; + + this._onChange = function (event) { + return _this.visibilityChange(event); + }; + + this._onClick = function (event) { + if ((document.hasFocus !== undefined) && !document.hasFocus()) + { + _this.visibilityChange(event); + } + }; + + // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus + if (this._hiddenVar) + { + document.addEventListener(this._hiddenVar, this._onChange, false); + } + + window.onblur = this._onChange; + window.onfocus = this._onChange; + + window.onpagehide = this._onChange; + window.onpageshow = this._onChange; + + window.addEventListener('click', this._onClick); + + if (this.game.device.cocoonJSApp) + { + CocoonJS.App.onSuspended.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" }); + }); + + CocoonJS.App.onActivated.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" }); + }); + } + +}; + +/** +* This method is called when the document visibility is changed. +* +* - `blur` and `pagehide` events trigger {@link Phaser.Game#onBlur}. They {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `click`, `focus`, and `pageshow` trigger {@link Phaser.Game#onFocus}. They {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (hidden) and CocoonJS's `onSuspended` {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (visible) and CocoonJS's `onActivated` {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* +* @method Phaser.Stage#visibilityChange +* @param {Event} event - Its type will be used to decide whether the game should be paused or not. +*/ +Phaser.Stage.prototype.visibilityChange = function (event) { + + // These events always trigger the Game#onBlur or Game#onFocus signals. + + switch (event.type) + { + case 'blur': + case 'pagehide': + this.game.focusLoss(event); + return; + case 'click': + case 'focus': + case 'pageshow': + this.game.focusGain(event); + return; + } + + if (this.disableVisibilityChange) + { + return; + } + + if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause") + { + this.game.gamePaused(event); + } + else + { + this.game.gameResumed(event); + } + +}; + +/** +* Sets the background color for the Stage. +* +* The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). +* +* An alpha channel is _not_ supported and will be ignored. +* +* If you've set your game to be {@link Phaser.Game#transparent transparent} then calls to setBackgroundColor are ignored. +* +* If {@link Phaser.Game#clearBeforeRender} is off then the background color won't appear. +* +* @method Phaser.Stage#setBackgroundColor +* @param {number|string} color - The color of the background. +*/ +Phaser.Stage.prototype.setBackgroundColor = function (color) { + + if (this.game.transparent) { return; } + + Phaser.Color.valueToColor(color, this._bgColor); + Phaser.Color.updateColor(this._bgColor); + + // For gl.clearColor (canvas uses _bgColor.rgba) + this._bgColor.r /= 255; + this._bgColor.g /= 255; + this._bgColor.b /= 255; + this._bgColor.a = 1; + +}; + +/** +* Destroys the Stage and removes event listeners. +* +* @method Phaser.Stage#destroy +*/ +Phaser.Stage.prototype.destroy = function () { + + if (this._hiddenVar) + { + document.removeEventListener(this._hiddenVar, this._onChange, false); + } + + window.onpagehide = null; + window.onpageshow = null; + + window.onblur = null; + window.onfocus = null; + + window.removeEventListener('click', this._onClick); + +}; + +/** +* Adds an existing object to the Stage. +* +* The child is automatically added to the front of the Stage, and is displayed above every previous child. +* Or if the _optional_ `index` is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the object was already on the Stage, it is simply returned, and nothing else happens to it. +* +* @method Phaser.Stage#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent] - Unused. Kept for compatibility with {@link Phaser.Group#add}. +* @param {integer} [index] - The index to insert the object to. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Stage.prototype.add = function (child, silent, index) { + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + this.addChild(child); + } + else + { + this.addChildAt(child, index); + } + + return child; + +}; + +/** +* @name Phaser.Stage#backgroundColor +* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' +* @see Phaser.Stage#setBackgroundColor +*/ +Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", { + + get: function () { + + return this._bgColor.color; + + }, + + set: function (color) { + + this.setBackgroundColor(color); + + } + +}); + +/** +* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. +* +* @name Phaser.Stage#smoothed +* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) +*/ +Object.defineProperty(Phaser.Stage.prototype, "smoothed", { + + get: function () { + + return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR; + + }, + + set: function (value) { + + if (value) + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR; + } + else + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}. +* +* Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. +* For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. +* +* In addition, Groups provides support for fast pooling and object recycling. +* +* Groups are also display objects and can be nested as children within other Groups. +* +* @class Phaser.Group +* @extends PIXI.DisplayObjectContainer +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to. +* If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent. +* @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World. +* @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}. +* @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values. +*/ +Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) { + + if (addToStage === undefined) { addToStage = false; } + if (enableBody === undefined) { enableBody = false; } + if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + if (parent === undefined) + { + parent = game.world; + } + + /** + * A name for this group. Not used internally but useful for debugging. + * @property {string} name + */ + this.name = name || 'group'; + + /** + * The z-depth value of this object within its parent container/Group - the World is a Group as well. + * This value must be unique for each child in a Group. + * @property {integer} z + * @readOnly + */ + this.z = 0; + + PIXI.DisplayObjectContainer.call(this); + + if (addToStage) + { + this.game.stage.addChild(this); + this.z = this.game.stage.children.length; + } + else + { + if (parent) + { + parent.addChild(this); + this.z = parent.children.length; + } + } + + /** + * Internal Phaser Type value. + * @property {integer} type + * @protected + */ + this.type = Phaser.GROUP; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. + * @property {boolean} alive + * @default + */ + this.alive = true; + + /** + * If exists is false the group will be excluded from collision checks and filters such as {@link #forEachExists}. The group will not call `preUpdate` and `postUpdate` on its children and the children will not receive physics updates or camera/world boundary checks. The group will still be {@link #visible} and will still call `update` on its children (unless {@link #updateOnlyExistingChildren} is true). + * @property {boolean} exists + * @default + */ + this.exists = true; + + /** + * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. + * @property {boolean} ignoreDestroy + * @default + */ + this.ignoreDestroy = false; + + /** + * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method + * called on the next logic update. + * You can set it directly to flag the Group to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy a Group from within one of its own callbacks + * or a callback of one of its children. + * + * @property {boolean} pendingDestroy + */ + this.pendingDestroy = false; + + /** + * The type of objects that will be created when using {@link #create} or {@link #createMultiple}. + * + * It should extend either Sprite or Image and accept the same constructor arguments: `(game, x, y, key, frame)`. + * + * @property {function} classType + * @default {@link Phaser.Sprite} + */ + this.classType = Phaser.Sprite; + + /** + * The current display object that the group cursor is pointing to, if any. (Can be set manually.) + * + * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}. + * @property {?DisplayObject} cursor + */ + this.cursor = null; + + /** + * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` + * on any children _added_ to, or _created by_, this Group. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * @property {boolean} inputEnableChildren + * @default + */ + this.inputEnableChildren = false; + + /** + * Skip children with `exists = false` in {@link #update}. + * + * @property {boolean} updateOnlyExistingChildren + * @default + */ + this.updateOnlyExistingChildren = false; + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputDown + */ + this.onChildInputDown = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, + * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer + * is still over the Sprite or not. + * + * @property {Phaser.Signal} onChildInputUp + */ + this.onChildInputUp = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOver + */ + this.onChildInputOver = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOut + */ + this.onChildInputOut = new Phaser.Signal(); + + /** + * If true all Sprites created by, or added to this group, will have a physics body enabled on them. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * The default body type is controlled with {@link #physicsBodyType}. + * @property {boolean} enableBody + */ + this.enableBody = enableBody; + + /** + * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well. + * + * This only works for P2 bodies. + * @property {boolean} enableBodyDebug + * @default + */ + this.enableBodyDebug = false; + + /** + * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites. + * + * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc. + * @property {integer} physicsBodyType + */ + this.physicsBodyType = physicsBodyType; + + /** + * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. + * + * It should be set to one of the Phaser.Physics.Arcade sort direction constants: + * + * Phaser.Physics.Arcade.SORT_NONE + * Phaser.Physics.Arcade.LEFT_RIGHT + * Phaser.Physics.Arcade.RIGHT_LEFT + * Phaser.Physics.Arcade.TOP_BOTTOM + * Phaser.Physics.Arcade.BOTTOM_TOP + * + * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. + * + * @property {integer} physicsSortDirection + * @default + */ + this.physicsSortDirection = null; + + /** + * This signal is dispatched when the group is destroyed. + * @property {Phaser.Signal} onDestroy + */ + this.onDestroy = new Phaser.Signal(); + + /** + * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next. + * @readOnly + */ + this.cursorIndex = 0; + + /** + * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. + * + * Note that the cameraOffset values are in addition to any parent in the display list. + * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x + * + * @property {boolean} fixedToCamera + */ + this.fixedToCamera = false; + + /** + * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view. + * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. + * @property {Phaser.Point} cameraOffset + */ + this.cameraOffset = new Phaser.Point(); + + /** + * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. + * + * Only children of this Group can be added to and removed from the hash. + * + * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. + * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own + * sorting and filtering of Group children without touching their z-index (and therefore display draw order) + * + * @property {array} hash + */ + this.hash = []; + + /** + * The property on which children are sorted. + * @property {string} _sortProperty + * @private + */ + this._sortProperty = 'z'; + +}; + +Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Group.prototype.constructor = Phaser.Group; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_NONE = 0; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_TOTAL = 1; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_CHILD = 2; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_ALL = 3; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_ASCENDING = -1; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_DESCENDING = 1; + +/** +* Adds an existing object as the top child in this group. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the child was already in this Group, it is simply returned, and nothing else happens to it. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* Use {@link #create} to create and add a new child. +* +* @method Phaser.Group#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.add = function (child, silent, index) { + + if (silent === undefined) { silent = false; } + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + child.z = this.children.length; + + this.addChild(child); + } + else + { + this.addChildAt(child, index); + + this.updateZ(); + } + + if (this.enableBody && child.hasOwnProperty('body') && child.body === null) + { + this.game.physics.enable(child, this.physicsBodyType); + } + else if (child.body) + { + this.addToHash(child); + } + + if (this.inputEnableChildren && (!child.input || child.inputEnabled)) + { + child.inputEnabled = true; + } + + if (!silent && child.events) + { + child.events.onAddedToGroup$dispatch(child, this); + } + + if (this.cursor === null) + { + this.cursor = child; + } + + return child; + +}; + +/** +* Adds an existing object to this group. +* +* The child is added to the group at the location specified by the index value, this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#addAt +* @param {DisplayObject} child - The display object to add as a child. +* @param {integer} [index=0] - The index within the group to insert the child to. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.addAt = function (child, index, silent) { + + return this.add(child, silent, index); + +}; + +/** +* Adds a child of this Group into the hash array. +* This call will return false if the child is not a child of this Group, or is already in the hash. +* +* @method Phaser.Group#addToHash +* @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. +* @return {boolean} True if the child was successfully added to the hash, otherwise false. +*/ +Phaser.Group.prototype.addToHash = function (child) { + + if (child.parent === this) + { + var index = this.hash.indexOf(child); + + if (index === -1) + { + this.hash.push(child); + return true; + } + } + + return false; + +}; + +/** +* Removes a child of this Group from the hash array. +* This call will return false if the child is not in the hash. +* +* @method Phaser.Group#removeFromHash +* @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash. +* @return {boolean} True if the child was successfully removed from the hash, otherwise false. +*/ +Phaser.Group.prototype.removeFromHash = function (child) { + + if (child) + { + var index = this.hash.indexOf(child); + + if (index !== -1) + { + this.hash.splice(index, 1); + return true; + } + } + + return false; + +}; + +/** +* Adds an array of existing Display Objects to this Group. +* +* The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. +* +* As well as an array you can also pass another Group as the first argument. In this case all of the children from that +* Group will be removed from it and added into this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#addMultiple +* @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group. +*/ +Phaser.Group.prototype.addMultiple = function (children, silent) { + + if (children instanceof Phaser.Group) + { + children.moveAll(this, silent); + } + else if (Array.isArray(children)) + { + for (var i = 0; i < children.length; i++) + { + this.add(children[i], silent); + } + } + + return children; + +}; + +/** +* Returns the child found at the given index within this group. +* +* @method Phaser.Group#getAt +* @param {integer} index - The index to return the child from. +* @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index. +*/ +Phaser.Group.prototype.getAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + return -1; + } + else + { + return this.getChildAt(index); + } + +}; + +/** +* Creates a new Phaser.Sprite object and adds it to the top of this group. +* +* Use {@link #classType} to change the type of object created. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#create +* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. +* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {boolean} [exists=true] - The default exists state of the Sprite. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed. +*/ +Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) { + + if (exists === undefined) { exists = true; } + + var child = new this.classType(this.game, x, y, key, frame); + + child.exists = exists; + child.visible = exists; + child.alive = exists; + + return this.add(child, false, index); + +}; + +/** +* Creates multiple Phaser.Sprite objects and adds them to the top of this Group. +* +* This method is useful if you need to quickly generate a pool of sprites, such as bullets. +* +* Use {@link #classType} to change the type of object created. +* +* You can provide an array as the `key` and / or `frame` arguments. When you do this +* it will create `quantity` Sprites for every key (and frame) in the arrays. +* +* For example: +* +* `createMultiple(25, ['ball', 'carrot'])` +* +* In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be +* created in total, 25 of each. You can also have the `frame` as an array: +* +* `createMultiple(5, 'bricks', [0, 1, 2, 3])` +* +* In the above there is one key (bricks), which is a sprite sheet. The frames array tells +* this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because +* the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with +* frame 1, and so on. +* +* If you set both the key and frame arguments to be arrays then understand it will create +* a total quantity of sprites equal to the size of both arrays times each other. I.e.: +* +* `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` +* +* The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. +* It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. +* In total it will have created 120 sprites. +* +* By default the Sprites will have their `exists` property set to `false`, and they will be +* positioned at 0x0, relative to the `Group.x / y` values. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#createMultiple +* @param {integer} quantity - The number of Sprites to create. +* @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. +* @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. +* @param {boolean} [exists=false] - The default exists state of the Sprite. +* @param {function} [callback] - The function that will be called for each applicable child. It will be passed the new child and the loop index (0 through quantity - 1). +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). The default context is the new child. +* @return {array} An array containing all of the Sprites that were created. +*/ +Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, callback, callbackContext) { + + if (frame === undefined) { frame = 0; } + if (exists === undefined) { exists = false; } + + if (!Array.isArray(key)) + { + key = [ key ]; + } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + + var _this = this; + var children = []; + + key.forEach(function(singleKey) { + + frame.forEach(function(singleFrame) { + + for (var i = 0; i < quantity; i++) + { + var child = _this.create(0, 0, singleKey, singleFrame, exists); + + if (callback) { callback.call(callbackContext || child, child, i); } + + children.push(child); + } + + }); + + }); + + return children; + +}; + +/** +* Internal method that re-applies all of the children's Z values. +* +* This must be called whenever children ordering is altered so that their `z` indices are correctly updated. +* +* @method Phaser.Group#updateZ +* @protected +*/ +Phaser.Group.prototype.updateZ = function () { + + var i = this.children.length; + + while (i--) + { + this.children[i].z = i; + } + +}; + +/** +* This method iterates through all children in the Group (regardless if they are visible or exist) +* and then changes their position so they are arranged in a Grid formation. Children must have +* the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have +* this. +* +* The grid dimensions are determined by the first four arguments. The `width` and `height` arguments +* relate to the width and height of the grid respectively. +* +* For example if the Group had 100 children in it: +* +* `Group.align(10, 10, 32, 32)` +* +* This will align all of the children into a grid formation of 10x10, using 32 pixels per +* grid cell. If you want a wider grid, you could do: +* +* `Group.align(25, 4, 32, 32)` +* +* This will align the children into a grid of 25x4, again using 32 pixels per grid cell. +* +* You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method +* to keep on aligning children until there are no children left. For example if this Group had +* 48 children in it, the following: +* +* `Group.align(-1, 8, 32, 32)` +* +* ... will align the children so that there are 8 children vertically (the second argument), +* and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) +* +* You can also do: +* +* `Group.align(10, -1, 32, 32)` +* +* In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit +* all of the children in. +* +* The `position` property allows you to control where in each grid cell the child is positioned. +* This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, +* `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, +* `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* +* The final argument; `offset` lets you start the alignment from a specific child index. +* +* @method Phaser.Group#align +* @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. +* @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. +* @param {integer} cellWidth - The width of each grid cell, in pixels. +* @param {integer} cellHeight - The height of each grid cell, in pixels. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. +* @return {boolean} True if the Group children were aligned, otherwise false. +*/ +Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, position, offset) { + + if (position === undefined) { position = Phaser.TOP_LEFT; } + if (offset === undefined) { offset = 0; } + + if (this.children.length === 0 || offset > this.children.length || (width === -1 && height === -1)) + { + return false; + } + + var r = new Phaser.Rectangle(0, 0, cellWidth, cellHeight); + var w = (width * cellWidth); + var h = (height * cellHeight); + + for (var i = offset; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child['alignIn']) + { + child.alignIn(r, position); + } + else + { + continue; + } + + if (width === -1) + { + // We keep laying them out horizontally until we've done them all + r.y += cellHeight; + + if (r.y === h) + { + r.x += cellWidth; + r.y = 0; + } + } + else if (height === -1) + { + // We keep laying them out vertically until we've done them all + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + } + } + else + { + // We keep laying them out until we hit the column limit + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + + if (r.y === h) + { + // We've hit the column limit, so return, even if there are children left + return true; + } + } + } + } + + return true; + +}; + +/** +* Sets the group cursor to the first child in the group. +* +* If the optional index parameter is given it sets the cursor to the object at that index instead. +* +* @method Phaser.Group#resetCursor +* @param {integer} [index=0] - Set the cursor to point to a specific index. +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.resetCursor = function (index) { + + if (index === undefined) { index = 0; } + + if (index > this.children.length - 1) + { + index = 0; + } + + if (this.cursor) + { + this.cursorIndex = index; + this.cursor = this.children[this.cursorIndex]; + return this.cursor; + } + +}; + +/** +* Advances the group cursor to the next (higher) object in the group. +* +* If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). +* +* @method Phaser.Group#next +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.next = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex >= this.children.length - 1) + { + this.cursorIndex = 0; + } + else + { + this.cursorIndex++; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Moves the group cursor to the previous (lower) child in the group. +* +* If the cursor is at the start of the group (bottom child) it is moved to the end (top child). +* +* @method Phaser.Group#previous +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.previous = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex === 0) + { + this.cursorIndex = this.children.length - 1; + } + else + { + this.cursorIndex--; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Swaps the position of two children in this group. +* +* Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. +* +* @method Phaser.Group#swap +* @param {any} child1 - The first child to swap. +* @param {any} child2 - The second child to swap. +*/ +Phaser.Group.prototype.swap = function (child1, child2) { + + this.swapChildren(child1, child2); + this.updateZ(); + +}; + +/** +* Brings the given child to the top of this group so it renders above all other children. +* +* @method Phaser.Group#bringToTop +* @param {any} child - The child to bring to the top of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.bringToTop = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length) + { + this.remove(child, false, true); + this.add(child, true); + } + + return child; + +}; + +/** +* Sends the given child to the bottom of this group so it renders below all other children. +* +* @method Phaser.Group#sendToBack +* @param {any} child - The child to send to the bottom of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.sendToBack = function (child) { + + if (child.parent === this && this.getIndex(child) > 0) + { + this.remove(child, false, true); + this.addAt(child, 0, true); + } + + return child; + +}; + +/** +* Moves the given child up one place in this group unless it's already at the top. +* +* @method Phaser.Group#moveUp +* @param {any} child - The child to move up in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveUp = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length - 1) + { + var a = this.getIndex(child); + var b = this.getAt(a + 1); + + if (b) + { + this.swap(child, b); + } + } + + return child; + +}; + +/** +* Moves the given child down one place in this group unless it's already at the bottom. +* +* @method Phaser.Group#moveDown +* @param {any} child - The child to move down in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveDown = 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; + +}; + +/** +* Positions the child found at the given index within this group to the given x and y coordinates. +* +* @method Phaser.Group#xy +* @param {integer} index - The index of the child in the group to set the position of. +* @param {number} x - The new x position of the child. +* @param {number} y - The new y position of the 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; + } + +}; + +/** +* Reverses all children in this group. +* +* This operation applies only to immediate children and does not propagate to subgroups. +* +* @method Phaser.Group#reverse +*/ +Phaser.Group.prototype.reverse = function () { + + this.children.reverse(); + this.updateZ(); + +}; + +/** +* Get the index position of the given child in this group, which should match the child's `z` property. +* +* @method Phaser.Group#getIndex +* @param {any} child - The child to get the index for. +* @return {integer} The index of the child or -1 if it's not a member of this group. +*/ +Phaser.Group.prototype.getIndex = function (child) { + + return this.children.indexOf(child); + +}; + +/** +* Searches the Group for the first instance of a child with the `name` +* property matching the given argument. Should more than one child have +* the same name only the first instance is returned. +* +* @method Phaser.Group#getByName +* @param {string} name - The name to search for. +* @return {any} The first child with a matching name, or null if none were found. +*/ +Phaser.Group.prototype.getByName = function (name) { + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].name === name) + { + return this.children[i]; + } + } + + return null; + +}; + +/** +* Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#replace +* @param {any} oldChild - The child in this group that will be replaced. +* @param {any} newChild - The child to be inserted into this group. +* @return {any} Returns the oldChild that was replaced within this group. +*/ +Phaser.Group.prototype.replace = function (oldChild, newChild) { + + var index = this.getIndex(oldChild); + + if (index !== -1) + { + if (newChild.parent) + { + if (newChild.parent instanceof Phaser.Group) + { + newChild.parent.remove(newChild); + } + else + { + newChild.parent.removeChild(newChild); + } + } + + this.remove(oldChild); + + this.addAt(newChild, index); + + return oldChild; + } + +}; + +/** +* Checks if the child has the given property. +* +* Will scan up to 4 levels deep only. +* +* @method Phaser.Group#hasProperty +* @param {any} child - The child to check for the existence of the property on. +* @param {string[]} key - An array of strings that make up the property. +* @return {boolean} True if the child has the property, otherwise false. +*/ +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; + +}; + +/** +* Sets a property to the given value on the child. The operation parameter controls how the value is set. +* +* The operations are: +* - 0: set the existing value to the given value; if force is `true` a new property will be created if needed +* - 1: will add the given value to the value already present. +* - 2: will subtract the given value from the value already present. +* - 3: will multiply the value already present by the given value. +* - 4: will divide the value already present by the given value. +* +* @method Phaser.Group#setProperty +* @param {any} child - The child to set the property value on. +* @param {array} key - An array of strings that make up the property that will be set. +* @param {any} value - The value that will be set. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) { + + if (force === undefined) { force = false; } + + operation = operation || 0; + + // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration. + + // 0 = Equals + // 1 = Add + // 2 = Subtract + // 3 = Multiply + // 4 = Divide + + // We can't force a property in and the child doesn't have it, so abort. + // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too. + 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; + +}; + +/** +* Checks a property for the given value on the child. +* +* @method Phaser.Group#checkProperty +* @param {any} child - The child to check the property value on. +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} True if `child` is a child of this Group and the property was equal to value, false if not. +*/ +Phaser.Group.prototype.checkProperty = function (child, key, value, force) { + + if (force === undefined) { force = false; } + + if (this !== child.parent) + { + return false; + } + + var result = Phaser.Utils.getProperty(child, key); + + if (((result === undefined) && force) || (result !== value)) + { + return false; + } + + return true; + +}; + +/** +* Quickly set a property on a single child of this group to a new value. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#set +* @param {Phaser.Sprite} child - The child to set the property on. +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true. +* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) { + + if (force === undefined) { force = false; } + + key = key.split('.'); + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible))) + { + return this.setProperty(child, key, value, operation, force); + } + +}; + +/** +* Quickly set the same property across all children of this group to a new value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. +* If you need that ability please see `Group.setAllChildren`. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAll +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + key = key.split('.'); + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + this.setProperty(this.children[i], key, value, operation, force); + } + } + +}; + +/** +* Quickly set the same property across all children of this group, and any child Groups, to a new value. +* +* If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. +* Unlike with `setAll` the property is NOT set on child Groups itself. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAllChildren +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + if (this.children[i] instanceof Phaser.Group) + { + this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force); + } + else + { + this.setProperty(this.children[i], key.split('.'), value, operation, force); + } + } + } + +}; + +/** +* Test that the same property across all children of this group is equal to the given value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAll +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} - True if all eligible children have the given property value (but see `force`); otherwise false. +*/ +Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (!this.checkProperty(child, key, value, force)) + { + return false; + } + } + } + + return true; + +}; + +/** +* Test that at least one child of this group has the given property value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAny +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @return {boolean} - True if at least one eligible child has the given property value; otherwise false. +*/ +Phaser.Group.prototype.checkAny = function (key, value, checkAlive, checkVisible) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (this.checkProperty(child, key, value)) + { + return true; + } + } + } + + return false; + +}; + +/** +* Adds the amount to the given property on all children in this group. +* +* `Group.addAll('x', 10)` will add 10 to the child.x value for each child. +* +* @method Phaser.Group#addAll +* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. +* @param {boolean} [checkAlive] - If true the property will only be changed if the child is alive. +* @param {boolean} [checkVisible] - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 1); + +}; + +/** +* Subtracts the amount from the given property on all children in this group. +* +* `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. +* +* @method Phaser.Group#subAll +* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 2); + +}; + +/** +* Multiplies the given property by the amount on all children in this group. +* +* `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. +* +* @method Phaser.Group#multiplyAll +* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 3); + +}; + +/** +* Divides the given property by the amount on all children in this group. +* +* `Group.divideAll('x', 2)` will half the child.x value for each child. +* +* @method Phaser.Group#divideAll +* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 4); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to false. + * + * @method Phaser.Group#kill + */ +Phaser.Group.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + +}; + +/** + * Kills all children having exists=true. + * + * @method Phaser.Group#killAll + */ +Phaser.Group.prototype.killAll = function () { + + this.callAllExists('kill', true); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to true. + * + * @method Phaser.Group#revive + */ +Phaser.Group.prototype.revive = function () { + + this.alive = true; + this.exists = true; + this.visible = true; + +}; + +/** + * Revives all children having exists=false. + * + * @method Phaser.Group#reviveAll + */ +Phaser.Group.prototype.reviveAll = function () { + + this.callAllExists('revive', false); + +}; + +/** +* Calls {@link #resetChild} on each child (or each existing child). +* +* @method Phaser.Group#resetAll +* @param {number} [x] - The x coordinate to reset each child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset each child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image or texture used by the Sprite during rendering. +* @param {string|number} [frame] - The frame of a sprite sheet or texture atlas. +* @param {boolean} [checkExists=false] - Reset only existing children. +*/ +Phaser.Group.prototype.resetAll = function (x, y, key, frame, checkExists) { + + this.forEach(this.resetChild, this, checkExists, x, y, key, frame); + +}; + +/** +* Calls a function, specified by name, on all children in the group who exist (or do not exist). +* +* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. +* +* @method Phaser.Group#callAllExists +* @param {string} callback - Name of the function on the children to call. +* @param {boolean} existsValue - Only children with exists=existsValue will be called. +* @param {...any} parameter - Additional parameters that will be passed to the callback. +*/ +Phaser.Group.prototype.callAllExists = function (callback, existsValue) { + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].exists === existsValue && this.children[i][callback]) + { + this.children[i][callback].apply(this.children[i], args); + } + } + +}; + +/** +* Returns a reference to a function that exists on a child of the group based on the given callback array. +* +* @method Phaser.Group#callbackFromArray +* @param {object} child - The object to inspect. +* @param {array} callback - The array of function names. +* @param {integer} length - The size of the array (pre-calculated in callAll). +* @protected +*/ +Phaser.Group.prototype.callbackFromArray = function (child, callback, length) { + + // Kinda looks like a Christmas tree + + if (length === 1) + { + if (child[callback[0]]) + { + return child[callback[0]]; + } + } + else if (length === 2) + { + if (child[callback[0]][callback[1]]) + { + return child[callback[0]][callback[1]]; + } + } + else if (length === 3) + { + if (child[callback[0]][callback[1]][callback[2]]) + { + return child[callback[0]][callback[1]][callback[2]]; + } + } + else if (length === 4) + { + if (child[callback[0]][callback[1]][callback[2]][callback[3]]) + { + return child[callback[0]][callback[1]][callback[2]][callback[3]]; + } + } + else if (child[callback]) + { + return child[callback]; + } + + return false; + +}; + +/** +* Calls a function, specified by name, on all on children. +* +* The function is called for all children regardless if they are dead or alive (see callAllExists for different options). +* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. +* +* @method Phaser.Group#callAll +* @param {string} method - Name of the function on the child to call. Deep property lookup is supported. +* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child. +* @param {...any} args - Additional parameters that will be passed to the method. +*/ +Phaser.Group.prototype.callAll = function (method, context) { + + if (method === undefined) + { + return; + } + + // Extract the method into an array + method = method.split('.'); + + var methodLength = method.length; + + if (context === undefined || context === null || context === '') + { + context = null; + } + else + { + // Extract the context into an array + if (typeof context === 'string') + { + context = context.split('.'); + var contextLength = context.length; + } + } + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + var callback = null; + var callbackContext = null; + + for (var i = 0; i < this.children.length; i++) + { + callback = this.callbackFromArray(this.children[i], method, methodLength); + + if (context && callback) + { + callbackContext = this.callbackFromArray(this.children[i], context, contextLength); + + if (callback) + { + callback.apply(callbackContext, args); + } + } + else if (callback) + { + callback.apply(this.children[i], args); + } + } + +}; + +/** +* The core preUpdate - as called by World. +* @method Phaser.Group#preUpdate +* @protected +*/ +Phaser.Group.prototype.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + // This chunk is identical to Phaser.Component.Core.prototype.preUpdateChildren, which is not yet defined. + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + return true; + +}; + +/** +* The core update - as called by World. +* +* Children with `exists = false` are updated unless {@link #updateOnlyExistingChildren} is true. +* +* @method Phaser.Group#update +* @protected +*/ +Phaser.Group.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + var len = this.children.length; + + if (i >= len) { i = len - 1; } + + var child = this.children[i]; + + if (!this.updateOnlyExistingChildren || child.exists) { + child.update(); + } + } + +}; + +/** +* The core postUpdate - as called by World. +* @method Phaser.Group#postUpdate +* @protected +*/ +Phaser.Group.prototype.postUpdate = function () { + + // Fixed to Camera? + if (this.fixedToCamera) + { + this.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; + this.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Find children matching a certain predicate. +* +* For example: +* +* var healthyList = Group.filter(function(child, index, children) { +* return child.health > 10 ? true : false; +* }, true); +* healthyList.callAll('attack'); +* +* Note: Currently this will skip any children which are Groups themselves. +* +* @method Phaser.Group#filter +* @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third +* @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. +* @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for +*/ +Phaser.Group.prototype.filter = function (predicate, checkExists) { + + var index = -1; + var length = this.children.length; + var results = []; + + while (++index < length) + { + var child = this.children[index]; + + if (!checkExists || (checkExists && child.exists)) + { + if (predicate(child, index, this.children)) + { + results.push(child); + } + } + } + + return new Phaser.ArraySet(results); + +}; + +/** +* Call a function on each child in this group. +* +* Additional arguments for the callback can be specified after the `checkExists` parameter. For example, +* +* Group.forEach(awardBonusGold, this, true, 100, 500) +* +* would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. +* +* Note: This check will skip any children which are Groups themselves. +* +* @method Phaser.Group#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) { + + if (checkExists === undefined) { checkExists = false; } + + if (arguments.length <= 3) + { + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + callback.call(callbackContext, this.children[i]); + } + } + } + else + { + // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE. + // Using an array and pushing each element (not a slice!) is _significantly_ faster. + var args = [null]; + + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + } + } + +}; + +/** +* Call a function on each existing child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachExists +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachExists = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each alive child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachAlive +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each dead child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachDead +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachDead = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Sort the children in the group according to a particular key and ordering. +* +* Call this function to sort the group according to a particular key value and order. +* +* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. +* +* Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including +* alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. +* +* @method Phaser.Group#sort +* @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value. +* @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}). +*/ +Phaser.Group.prototype.sort = function (key, order) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + if (key === undefined) { key = 'z'; } + if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; } + + this._sortProperty = key; + + if (order === Phaser.Group.SORT_ASCENDING) + { + this.children.sort(this.ascendingSortHandler.bind(this)); + } + else + { + this.children.sort(this.descendingSortHandler.bind(this)); + } + + this.updateZ(); + +}; + +/** +* Sort the children in the group according to custom sort function. +* +* The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). +* It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. +* +* @method Phaser.Group#customSort +* @param {function} sortHandler - The custom sort function. +* @param {object} [context=undefined] - The context in which the sortHandler is called. +*/ +Phaser.Group.prototype.customSort = function (sortHandler, context) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + this.children.sort(sortHandler.bind(context)); + + this.updateZ(); + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#ascendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.ascendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return -1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return 1; + } + else + { + if (a.z < b.z) + { + return -1; + } + else + { + return 1; + } + } + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#descendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.descendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return 1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return -1; + } + else + { + return 0; + } + +}; + +/** +* Iterates over the children of the group performing one of several actions for matched children. +* +* A child is considered a match when it has a property, named `key`, whose value is equal to `value` +* according to a strict equality comparison. +* +* The result depends on the `returnType`: +* +* - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}: +* The callback, if any, is applied to all matching children. The number of matched children is returned. +* - {@link Phaser.Group.RETURN_NONE RETURN_NONE}: +* The callback, if any, is applied to all matching children. No value is returned. +* - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}: +* The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. +* If there is no matching child then null is returned. +* +* If `args` is specified it must be an array. The matched child will be assigned to the first +* element and the entire array will be applied to the callback function. +* +* @method Phaser.Group#iterate +* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' +* @param {any} value - A child matches if `child[key] === value` is true. +* @param {integer} returnType - How to iterate the children and what to return. +* @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. +* @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null. +*/ +Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) { + + if (this.children.length === 0) + { + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return 0; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return []; + } + } + + var total = 0; + + if (returnType === Phaser.Group.RETURN_ALL) + { + var output = []; + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i][key] === value) + { + total++; + + if (callback) + { + if (args) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + else + { + callback.call(callbackContext, this.children[i]); + } + } + + if (returnType === Phaser.Group.RETURN_CHILD) + { + return this.children[i]; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + output.push(this.children[i]); + } + } + } + + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return total; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return output; + } + else + { + // RETURN_CHILD or RETURN_NONE + return null; + } + +}; + +/** +* Get the first display object with the given property name and value. +* +* @method Phaser.Group#getFirst +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {DisplayObject} The first child matching the query, or `null` if none were found. +*/ +Phaser.Group.prototype.getFirst = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_CHILD); + +}; + +/** +* Get the first display object that exists, or doesn't exist. +* +* You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstExists +* @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child. +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + if (typeof exists !== 'boolean') + { + exists = true; + } + + var child = this.getFirst('exists', exists); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is alive (`child.alive === true`). +* +* This is handy for choosing a squad leader, etc. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstAlive +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', true); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is dead (`child.alive === false`). +* +* This is handy for checking if everything has been wiped out and adding to the pool as needed. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstDead +* @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', false); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. +* +* If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. +* +* The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. +* +* @method Phaser.Group#resetChild +* @param {DisplayObject} child - The child to reset and/or load the texture on. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}. +*/ +Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) { + + if (child === null) + { + return null; + } + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (x !== null && y !== null) + { + child.reset(x, y); + } + + if (key !== undefined) + { + child.loadTexture(key, frame); + } + + return child; + +}; + +/** +* Return the child at the top of this group. +* +* The top child is the child displayed (rendered) above every other child. +* +* @method Phaser.Group#getTop +* @return {any} The child at the top of the Group. +*/ +Phaser.Group.prototype.getTop = function () { + + if (this.children.length > 0) + { + return this.children[this.children.length - 1]; + } + +}; + +/** +* Returns the child at the bottom of this group. +* +* The bottom child the child being displayed (rendered) below every other child. +* +* @method Phaser.Group#getBottom +* @return {any} The child at the bottom of the Group. +*/ +Phaser.Group.prototype.getBottom = function () { + + if (this.children.length > 0) + { + return this.children[0]; + } + +}; + +/** +* Get the closest child to given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getClosestTo +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child closest to given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContext) { + + var distance = Number.MAX_VALUE; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance < distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the child furthest away from the given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getFurthestFrom +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child furthest from the given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackContext) { + + var distance = 0; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance > distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the number of children with the given property name and value. +* +* @method Phaser.Group#count +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {integer} The number of children matching the query. +*/ +Phaser.Group.prototype.count = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_TOTAL); + +}; + +/** +* Get the number of living children in this group. +* +* @method Phaser.Group#countLiving +* @return {integer} The number of children flagged as alive. +*/ +Phaser.Group.prototype.countLiving = function () { + + return this.count('alive', true); + +}; + +/** +* Get the number of dead children in this group. +* +* @method Phaser.Group#countDead +* @return {integer} The number of children flagged as dead. +*/ +Phaser.Group.prototype.countDead = function () { + + return this.count('alive', false); + +}; + +/** +* Returns a random child from the group. +* +* @method Phaser.Group#getRandom +* @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). +* @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. +* @return {any} A random child of this Group. +*/ +Phaser.Group.prototype.getRandom = function (startIndex, length) { + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = this.children.length; } + + if (length === 0) + { + return null; + } + + return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length); + +}; + +/** +* Returns a random child from the Group that has `exists` set to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only +* the first 50 children in the Group. +* +* @method Phaser.Group#getRandomExists +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up to. +* @return {any} A random child of this Group that exists. +*/ +Phaser.Group.prototype.getRandomExists = function (startIndex, endIndex) { + + var list = this.getAll('exists', true, startIndex, endIndex); + + return this.game.rnd.pick(list); + +}; + +/** +* Returns all children in this Group. +* +* You can optionally specify a matching criteria using the `property` and `value` arguments. +* +* For example: `getAll('exists', true)` would return only children that have an `exists` property equal to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return the first 50 children in the Group. +* If `property` and `value` are also specified, only children within the given index range are searched. +* +* @method Phaser.Group#getAll +* @param {string} [property] - An optional property to test against the value argument. +* @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results. +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up until. +* @return {array} - An array containing all, some, or none of the Children of this Group. +*/ +Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) { + + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var output = []; + + for (var i = startIndex; i < endIndex; i++) + { + var child = this.children[i]; + + if (property) + { + if (child[property] === value) + { + output.push(child); + } + } + else + { + output.push(child); + } + } + + return output; + +}; + +/** +* Removes the given child from this group. +* +* This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. +* +* If the group cursor was referring to the removed child it is updated to refer to the next child. +* +* @method Phaser.Group#remove +* @param {any} child - The child to remove. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child. +* @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event. +* @return {boolean} true if the child was removed from this group, otherwise false. +*/ +Phaser.Group.prototype.remove = function (child, destroy, silent) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + + if (this.children.length === 0 || this.children.indexOf(child) === -1) + { + return false; + } + + if (!silent && child.events && !child.destroyPhase) + { + child.events.onRemovedFromGroup$dispatch(child, this); + } + + var removed = this.removeChild(child); + + this.removeFromHash(child); + + this.updateZ(); + + if (this.cursor === child) + { + this.next(); + } + + if (destroy && removed) + { + removed.destroy(true); + } + + return true; + +}; + +/** +* Moves all children from this Group to the Group given. +* +* @method Phaser.Group#moveAll +* @param {Phaser.Group} group - The new Group to which the children will be moved to. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group. +* @return {Phaser.Group} The Group to which all the children were moved. +*/ +Phaser.Group.prototype.moveAll = function (group, silent) { + + if (silent === undefined) { silent = false; } + + if (this.children.length > 0 && group instanceof Phaser.Group) + { + do + { + group.add(this.children[0], silent); + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + } + + return group; + +}; + +/** +* Removes all children from this Group, but does not remove the group from its parent. +* +* The children can be optionally destroyed as they are removed. +* +* You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've +* more than one Game Object sharing the same BaseTexture. +* +* @method Phaser.Group#removeAll +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +* @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. +*/ +Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + if (destroyTexture === undefined) { destroyTexture = false; } + + if (this.children.length === 0) + { + return; + } + + do + { + if (!silent && this.children[0].events) + { + this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this); + } + + var removed = this.removeChild(this.children[0]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true, destroyTexture); + } + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + +}; + +/** +* Removes all children from this group whose index falls beteen the given startIndex and endIndex values. +* +* @method Phaser.Group#removeBetween +* @param {integer} startIndex - The index to start removing children from. +* @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +*/ +Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) { + + if (endIndex === undefined) { endIndex = this.children.length - 1; } + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = 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 (!silent && this.children[i].events) + { + this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this); + } + + var removed = this.removeChild(this.children[i]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true); + } + + if (this.cursor === this.children[i]) + { + this.cursor = null; + } + + i--; + } + + this.updateZ(); + +}; + +/** + * Places each child at a random position within the given Rectangle (or the {@link Phaser.World#bounds World bounds}). + * + * @method Phaser.Group#scatter + * @param {Phaser.Rectangle} [rect=this.game.world.bounds] - A Rectangle. If omitted {@link Phaser.World#bounds} is used. + * @param {boolean} [checkExists=false] - Place only children with exists=true. + */ +Phaser.Group.prototype.scatter = function (rect, checkExists) { + + if (rect == null) { rect = this.game.world.bounds; } + + this.forEach(function (child) { + + child.position.set(rect.randomX, rect.randomY); + + }, null, checkExists); + +}; + +/** + * Orders this Group's children randomly. + * + * This can be more efficient than calling {@link #getRandom} repeatedly. + * + * @method Phaser.Group#shuffle + */ +Phaser.Group.prototype.shuffle = function () { + + Phaser.ArrayUtils.shuffle(this.children); + this.updateZ(); + +}; + +/** +* Destroys this group. +* +* Removes all children, then removes this group from its parent and nulls references. +* +* @method Phaser.Group#destroy +* @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. +*/ +Phaser.Group.prototype.destroy = function (destroyChildren, soft) { + + if (this.game === null || this.ignoreDestroy) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (soft === undefined) { soft = false; } + + this.onDestroy.dispatch(this, destroyChildren, soft); + + this.removeAll(destroyChildren); + + this.cursor = null; + this.filters = null; + this.pendingDestroy = false; + + if (!soft) + { + if (this.parent) + { + this.parent.removeChild(this); + } + + this.game = null; + this.exists = false; + } + +}; + +/** +* Total number of existing children in the group. +* +* @name Phaser.Group#total +* @property {integer} total +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "total", { + + get: function () { + + return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); + + } + +}); + +/** +* Total number of children in this group, regardless of exists/alive status. +* +* @name Phaser.Group#length +* @property {integer} length +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "length", { + + get: function () { + + return this.children.length; + + } + +}); + +/** +* The angle of rotation of the group container, in degrees. +* +* This adjusts the group itself by modifying its local rotation transform. +* +* This has no impact on the rotation/angle properties of the children, but it will update their worldTransform +* and on-screen orientation and position. +* +* @name Phaser.Group#angle +* @property {number} angle +*/ +Object.defineProperty(Phaser.Group.prototype, "angle", { + + get: function() { + return Phaser.Math.radToDeg(this.rotation); + }, + + set: function(value) { + this.rotation = Phaser.Math.degToRad(value); + } + +}); + +/** +* The center x coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerX +* @property {number} centerX +*/ +Object.defineProperty(Phaser.Group.prototype, "centerX", { + + get: function () { + + return this.getBounds(this.parent).centerX; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.halfWidth; + + } + +}); + +/** +* The center y coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerY +* @property {number} centerY +*/ +Object.defineProperty(Phaser.Group.prototype, "centerY", { + + get: function () { + + return this.getBounds(this.parent).centerY; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.halfHeight; + + } + +}); + +/** +* The left coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#left +* @property {number} left +*/ +Object.defineProperty(Phaser.Group.prototype, "left", { + + get: function () { + + return this.getBounds(this.parent).left; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = value + offset; + + } + +}); + +/** +* The right coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#right +* @property {number} right +*/ +Object.defineProperty(Phaser.Group.prototype, "right", { + + get: function () { + + return this.getBounds(this.parent).right; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.width; + + } + +}); + +/** +* The top coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#top +* @property {number} top +*/ +Object.defineProperty(Phaser.Group.prototype, "top", { + + get: function () { + + return this.getBounds(this.parent).top; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset); + + } + +}); + +/** +* The bottom coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#bottom +* @property {number} bottom +*/ +Object.defineProperty(Phaser.Group.prototype, "bottom", { + + get: function () { + + return this.getBounds(this.parent).bottom; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.height; + + } + +}); + +/** +* Aligns this Group within another Game Object, or Rectangle, known as the +* 'container', to one of 9 possible positions. +* +* The container must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the container. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, +* `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, +* `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* container, taking into consideration rotation and scale of its children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignIn +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* Aligns this Group to the side of another Game Object, or Rectangle, known as the +* 'parent', in one of 11 possible positions. +* +* The parent must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the parent. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, +* `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, +* `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` +* and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* parent, taking into consideration rotation and scale of the children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignTo +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* A display object is any object that can be rendered in the Phaser/pixi.js scene graph: +* +* - {@link PIXI.DisplayObject} +* - {@link PIXI.DisplayObjectContainer} +* - {@link Phaser.BitmapText} +* - {@link Phaser.Creature} +* - {@link Phaser.Graphics} +* - {@link Phaser.Group} +* - {@link Phaser.FlexLayer} +* - {@link Phaser.Particles.Arcade.Emitter} +* - {@link Phaser.Physics.P2.BodyDebug} +* - {@link Phaser.SpriteBatch} +* - {@link Phaser.World} +* - {@link Phaser.Rope} +* - {@link Phaser.Stage} +* - {@link PIXI.Sprite} +* - {@link Phaser.Image} +* - {@link Phaser.Button} +* - {@link Phaser.Sprite} +* - {@link Phaser.Bullet} +* - {@link Phaser.Particle} +* - {@link Phaser.Text} +* - {@link Phaser.TilemapLayer} +* - {@link Phaser.TileSprite} +* +* @typedef {object} DisplayObject +*/ +// Documentation stub for linking. + +/** +* The x coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#x +* @property {number} x +*/ + +/** +* The y coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#y +* @property {number} y +*/ + +/** +* The angle of rotation of the group container, in radians. +* +* This will adjust the group container itself by modifying its rotation. +* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#rotation +* @property {number} rotation +*/ + +/** +* The visible state of the group. Non-visible Groups and all of their children are not rendered. +* +* @name Phaser.Group#visible +* @property {boolean} visible +*/ + +/** +* The alpha value of the group container. +* +* @name Phaser.Group#alpha +* @property {number} alpha +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* "This world is but a canvas to our imagination." - Henry David Thoreau +* +* A game has only one world. The world is an abstract place in which all game objects live. It is not bound +* by stage limits and can be any size. You look into the world via cameras. All game objects live within +* the world at world-based coordinates. By default a world is created the same size as your Stage. +* +* @class Phaser.World +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.World = function (game) { + + Phaser.Group.call(this, game, null, '__world', false); + + /** + * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. + * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. + * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. + * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. + * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height); + + /** + * @property {Phaser.Camera} camera - Camera instance. + */ + this.camera = null; + + /** + * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. + * @readonly + */ + this._definedSize = false; + + /** + * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._width = game.width; + + /** + * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._height = game.height; + + this.game.state.onStateChange.add(this.stateChange, this); + +}; + +Phaser.World.prototype = Object.create(Phaser.Group.prototype); +Phaser.World.prototype.constructor = Phaser.World; + +/** +* Initialises the game world. +* +* @method Phaser.World#boot +* @protected +*/ +Phaser.World.prototype.boot = function () { + + this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height); + + this.game.stage.addChild(this); + + this.camera.boot(); + +}; + +/** +* Called whenever the State changes or resets. +* +* It resets the world.x and world.y coordinates back to zero, +* then resets the Camera. +* +* @method Phaser.World#stateChange +* @protected +*/ +Phaser.World.prototype.stateChange = function () { + + this.x = 0; + this.y = 0; + + this.camera.reset(); + +}; + +/** +* Updates the size of this world and sets World.x/y to the given values +* The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. +* +* @method Phaser.World#setBounds +* @param {number} x - Top left most corner of the world. +* @param {number} y - Top left most corner of the world. +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.setBounds = function (x, y, width, height) { + + this._definedSize = true; + this._width = width; + this._height = height; + + this.bounds.setTo(x, y, width, height); + + this.x = x; + this.y = y; + + if (this.camera.bounds) + { + // The Camera can never be smaller than the game size + this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height)); + } + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Updates this world's width and height (but not smaller than any previous {@link #setBounds defined size}). +* +* Phaser uses this to adapt to {@link Phaser.ScaleManager#updateDimensions layout changes}. +* You probably want to use {@link #setBounds} instead. +* +* @method Phaser.World#resize +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.resize = function (width, height) { + + // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size + + if (this._definedSize) + { + if (width < this._width) + { + width = this._width; + } + + if (height < this._height) + { + height = this._height; + } + } + + this.bounds.width = width; + this.bounds.height = height; + + this.game.camera.setBoundsToWorld(); + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Destroyer of worlds. +* +* @method Phaser.World#shutdown +*/ +Phaser.World.prototype.shutdown = function () { + + // World is a Group, so run a soft destruction on this and all children. + this.destroy(true, true); + +}; + +/** +* This will take the given game object and check if its x/y coordinates fall outside of the world bounds. +* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. +* If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. +* +* Please understand there are limitations to this method. For example if you have scaled the World +* then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. +* +* @method Phaser.World#wrap +* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) { + + if (padding === undefined) { padding = 0; } + if (useBounds === undefined) { useBounds = false; } + if (horizontal === undefined) { horizontal = true; } + if (vertical === undefined) { vertical = true; } + + if (!useBounds) + { + if (horizontal && sprite.x + padding < this.bounds.x) + { + sprite.x = this.bounds.right + padding; + } + else if (horizontal && sprite.x - padding > this.bounds.right) + { + sprite.x = this.bounds.left - padding; + } + + if (vertical && sprite.y + padding < this.bounds.top) + { + sprite.y = this.bounds.bottom + padding; + } + else if (vertical && sprite.y - padding > this.bounds.bottom) + { + sprite.y = this.bounds.top - padding; + } + } + else + { + sprite.getBounds(); + + if (horizontal) + { + if ((sprite.x + sprite._currentBounds.width) < this.bounds.x) + { + sprite.x = this.bounds.right; + } + else if (sprite.x > this.bounds.right) + { + sprite.x = this.bounds.left; + } + } + + if (vertical) + { + if ((sprite.y + sprite._currentBounds.height) < this.bounds.top) + { + sprite.y = this.bounds.bottom; + } + else if (sprite.y > this.bounds.bottom) + { + sprite.y = this.bounds.top; + } + } + } + +}; + +/** +* @method Phaser.World#wrapAll +* @param {Phaser.Group} group - A group of sprites. +* @param {boolean} [checkExists=false] - Wrap only sprites having `exists=true`. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrapAll = function (group, checkExists, padding, useBounds, horizontal, vertical) { + + group.forEach(this.wrap, this, checkExists, padding, useBounds, horizontal, vertical); + +}; + +/** +* @name Phaser.World#width +* @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "width", { + + get: function () { + return this.bounds.width; + }, + + set: function (value) { + + if (value < this.game.width) + { + value = this.game.width; + } + + this.bounds.width = value; + this._width = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#height +* @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "height", { + + get: function () { + return this.bounds.height; + }, + + set: function (value) { + + if (value < this.game.height) + { + value = this.game.height; + } + + this.bounds.height = value; + this._height = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#centerX +* @property {number} centerX - Gets the X position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerX", { + + get: function () { + return this.bounds.halfWidth + this.bounds.x; + } + +}); + +/** +* @name Phaser.World#centerY +* @property {number} centerY - Gets the Y position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerY", { + + get: function () { + return this.bounds.halfHeight + this.bounds.y; + } + +}); + +/** +* @name Phaser.World#randomX +* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomX", { + + get: function () { + + if (this.bounds.x < 0) + { + return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x))); + } + else + { + return this.game.rnd.between(this.bounds.x, this.bounds.width); + } + + } + +}); + +/** +* @name Phaser.World#randomY +* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomY", { + + get: function () { + + if (this.bounds.y < 0) + { + return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y))); + } + else + { + return this.game.rnd.between(this.bounds.y, this.bounds.height); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Game object is the main controller for the entire Phaser game. It is responsible +* for handling the boot process, parsing the configuration values, creating the renderer, +* and setting-up all of the Phaser systems, such as physics, sound and input. +* Once that is complete it will start the default State, and then begin the main game loop. +* +* You can access lots of the Phaser systems via the properties on the `game` object. For +* example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on. +* +* Anywhere you can access the `game` property, you can access all of these core systems. +* For example a Sprite has a `game` property, allowing you to talk to the various parts +* of Phaser directly, without having to look after your own references. +* +* In it's most simplest form, a Phaser game can be created by providing the arguments +* to the constructor: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create }); +* ``` +* +* In the example above it is passing in a State object directly. You can also use the State +* Manager to do this: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO); +* game.state.add('Boot', BasicGame.Boot); +* game.state.add('Preloader', BasicGame.Preloader); +* game.state.add('MainMenu', BasicGame.MainMenu); +* game.state.add('Game', BasicGame.Game); +* game.state.start('Boot'); +* ``` +* +* In the example above, 4 States are added to the State Manager, and Phaser is told to +* start running the `Boot` state when it has finished initializing. There are example +* project templates you can use in the Phaser GitHub repo, inside the `resources` folder. +* +* Instead of specifying arguments you can also pass {@link GameConfig a single object} instead: +* +* ```javascript +* var config = { +* width: 800, +* height: 600, +* renderer: Phaser.AUTO, +* antialias: true, +* multiTexture: true, +* state: { +* preload: preload, +* create: create, +* update: update +* } +* } +* +* var game = new Phaser.Game(config); +* ``` +* +* @class Phaser.Game +* @constructor +* @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. +* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. +* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). +* @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body. +* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. +* @param {boolean} [transparent=false] - Use a transparent canvas background or not. +* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) { + + /** + * @property {number} id - Phaser Game ID + * @readonly + */ + this.id = Phaser.GAMES.push(this) - 1; + + /** + * @property {object} config - The Phaser.Game configuration object. + */ + this.config = null; + + /** + * @property {object} physicsConfig - The Phaser.Physics.World configuration object. + */ + this.physicsConfig = physicsConfig; + + /** + * @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted. + * @readonly + * @default + */ + this.parent = ''; + + /** + * The current Game Width in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} width + * @readonly + * @default + */ + this.width = 800; + + /** + * The current Game Height in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} height + * @readonly + * @default + */ + this.height = 600; + + /** + * The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object. + * + * @property {integer} resolution + * @readonly + * @default + */ + this.resolution = 1; + + /** + * @property {integer} _width - Private internal var. + * @private + */ + this._width = 800; + + /** + * @property {integer} _height - Private internal var. + * @private + */ + this._height = 600; + + /** + * @property {boolean} transparent - Use a transparent canvas background or not. + * @default + */ + this.transparent = false; + + /** + * @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead. + * @readonly + * @default + */ + this.antialias = true; + + /** + * Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property. + * To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game + * Configuration object with the property `multiTexture` set to true. It has to be enabled before + * Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it + * via the `game.renderer.setTexturePriority` method. + * + * @property {boolean} multiTexture + * @readonly + * @default + */ + this.multiTexture = false; + + /** + * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * @default + */ + this.preserveDrawingBuffer = false; + + /** + * Clear the Canvas each frame before rendering the display list. + * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. + * This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage. + * @property {boolean} clearBeforeRender + * @default + */ + this.clearBeforeRender = true; + + /** + * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. + * @protected + */ + this.renderer = null; + + /** + * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `render` hooks but not `preRender` or `postRender`; set {@link lockRender} to skip those as well. + * @readonly + */ + this.renderType = Phaser.AUTO; + + /** + * @property {Phaser.StateManager} state - The StateManager. + */ + this.state = null; + + /** + * @property {boolean} isBooted - Whether the game engine is booted, aka available. + * @readonly + */ + this.isBooted = false; + + /** + * @property {boolean} isRunning - Is game running or paused? + * @readonly + */ + this.isRunning = false; + + /** + * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout + * @protected + */ + this.raf = null; + + /** + * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. + */ + this.make = null; + + /** + * @property {Phaser.Cache} cache - Reference to the assets cache. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - Reference to the input manager + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - Reference to the assets loader. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - Reference to the math helper. + */ + this.math = null; + + /** + * @property {Phaser.Net} net - Reference to the network class. + */ + this.net = null; + + /** + * @property {Phaser.ScaleManager} scale - The game scale manager. + */ + this.scale = null; + + /** + * @property {Phaser.SoundManager} sound - Reference to the sound manager. + */ + this.sound = null; + + /** + * @property {Phaser.Stage} stage - Reference to the stage. + */ + this.stage = null; + + /** + * @property {Phaser.Time} time - Reference to the core game clock. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - Reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - Reference to the world. + */ + this.world = null; + + /** + * @property {Phaser.Physics} physics - Reference to the physics manager. + */ + this.physics = null; + + /** + * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. + */ + this.plugins = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. + */ + this.rnd = null; + + /** + * @property {Phaser.Device} device - Contains device information and capabilities. + */ + this.device = Phaser.Device; + + /** + * @property {Phaser.Camera} camera - A handy reference to world.camera. + */ + this.camera = null; + + /** + * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) + */ + this.context = null; + + /** + * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. + */ + this.debug = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. + */ + this.particles = null; + + /** + * @property {Phaser.Create} create - The Asset Generator. + */ + this.create = null; + + /** + * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. + * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. + * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. + * @property {boolean} lockRender + * @default + */ + this.lockRender = false; + + /** + * @property {boolean} pendingDestroy - Destroy the game at the next update. + * @default + */ + this.pendingDestroy = false; + + /** + * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). + * @default + * @readonly + */ + this.stepping = false; + + /** + * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. + * @default + * @readonly + */ + this.pendingStep = false; + + /** + * @property {number} stepCount - When stepping is enabled this contains the current step cycle. + * @default + * @readonly + */ + this.stepCount = 0; + + /** + * @property {Phaser.Signal} onPause - This event is fired when the game pauses. + */ + this.onPause = null; + + /** + * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. + */ + this.onResume = null; + + /** + * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). + */ + this.onBlur = null; + + /** + * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). + */ + this.onFocus = null; + + /** + * @property {boolean} _paused - Is game paused? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _codePaused - Was the game paused via code or a visibility change? + * @private + */ + this._codePaused = false; + + /** + * The ID of the current/last logic update applied this animation frame, starting from 0. + * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` + * @property {integer} currentUpdateID + * @protected + */ + this.currentUpdateID = 0; + + /** + * Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed). + * @property {integer} updatesThisFrame + * @protected + */ + this.updatesThisFrame = 1; + + /** + * Number of renders expected to occur this animation frame. May be 0 if {@link #dropFrames is on} or {@link #forceSingleRender} is off; otherwise it will be 1. + * @property {integer} updatesThisFrame + * @protected + */ + this.rendersThisFrame = 1; + + /** + * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. + * @private + */ + this._deltaTime = 0; + + /** + * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. + * @private + */ + this._lastCount = 0; + + /** + * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. + * @private + */ + this._spiraling = 0; + + /** + * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) + * @private + */ + this._kickstart = true; + + /** + * If the game is struggling to maintain the desired FPS, this signal will be dispatched. + * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. + * @property {Phaser.Signal} fpsProblemNotifier + * @public + */ + this.fpsProblemNotifier = new Phaser.Signal(); + + /** + * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? You can toggle it on the fly. + */ + this.forceSingleUpdate = true; + + /** + * @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update? (During spiraling conditions, {@link #dropFrames} is used instead.) + */ + this.forceSingleRender = true; + + /** + * @property {boolean} dropFrames - When {@link #forceSingleUpdate} is off, skip {@link #updateRender rendering} if logic updates are spiraling upwards. + */ + this.dropFrames = false; + + /** + * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. + * @private + */ + this._nextFpsNotification = 0; + + // Parse the configuration object (if any) + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + this.parseConfig(arguments[0]); + } + else + { + this.config = { enableDebug: true }; + + if (typeof width !== 'undefined') + { + this._width = width; + } + + if (typeof height !== 'undefined') + { + this._height = height; + } + + if (typeof renderer !== 'undefined') + { + 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); + } + + this.device.whenReady(this.boot, this); + + return this; + +}; + +/** +* A configuration object for {@link Phaser.Game}. +* +* @typedef {object} GameConfig +* @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}. +* @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}. +* @property {number|string} [GameConfig.antialias=true] +* @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}. +* @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in. +* @property {string} [GameConfig.canvasId] - `id` attribute value to assign to the game canvas. +* @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas. +* @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}. +* @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange} +* @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing. +* @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production. +* @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO. +* @property {boolean} [GameConfig.forceSetTimeout] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeOut} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available. +* @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen. +* @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked. +* @property {number|string} [GameConfig.height=600] +* @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`. +* @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected. +* @property {object} [GameConfig.physicsConfig] +* @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering. +* @property {number} [GameConfig.renderer=Phaser.AUTO] +* @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels. +* @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices. +* @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen. +* @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}. +* @property {object} [GameConfig.state] +* @property {boolean} [GameConfig.transparent=false] +* @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode. +* @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode. +* @property {number|string} [GameConfig.width=800] +*/ +// Documentation stub for linking. + +Phaser.Game.prototype = { + + /** + * Parses a Game configuration object. + * + * @method Phaser.Game#parseConfig + * @protected + */ + parseConfig: function (config) { + + this.config = config; + + if (config['enableDebug'] === undefined) + { + this.config.enableDebug = true; + } + + if (config['width']) + { + this._width = config['width']; + } + + if (config['height']) + { + this._height = config['height']; + } + + if (config['renderer']) + { + this.renderType = config['renderer']; + } + + if (config['parent']) + { + this.parent = config['parent']; + } + + if (config['transparent'] !== undefined) + { + this.transparent = config['transparent']; + } + + if (config['antialias'] !== undefined) + { + this.antialias = config['antialias']; + } + + if (config['multiTexture'] !== undefined) + { + this.multiTexture = config['multiTexture']; + } + + if (config['resolution']) + { + this.resolution = config['resolution']; + } + + if (config['preserveDrawingBuffer'] !== undefined) + { + this.preserveDrawingBuffer = config['preserveDrawingBuffer']; + } + + 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); + + }, + + /** + * Initialize engine sub modules and start the game. + * + * @method Phaser.Game#boot + * @protected + */ + boot: function () { + + if (this.isBooted) + { + return; + } + + this.onPause = new Phaser.Signal(); + this.onResume = new Phaser.Signal(); + this.onBlur = new Phaser.Signal(); + this.onFocus = new Phaser.Signal(); + + this.isBooted = true; + + PIXI.game = this; + + this.math = Phaser.Math; + + this.scale = new Phaser.ScaleManager(this, this._width, this._height); + this.stage = new Phaser.Stage(this); + + this.setUpRenderer(); + + 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.create = new Phaser.Create(this); + this.plugins = new Phaser.PluginManager(this); + this.net = new Phaser.Net(this); + + this.time.boot(); + this.stage.boot(); + this.world.boot(); + this.scale.boot(); + this.input.boot(); + this.sound.boot(); + this.state.boot(); + + if (this.config['enableDebug']) + { + this.debug = new Phaser.Utils.Debug(this); + this.debug.boot(); + } + else + { + this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {}, isDisabled: true }; + } + + 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._kickstart = true; + + if (window['focus']) + { + if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus)) + { + window.focus(); + } + } + + if (this.config['disableStart']) + { + return; + } + + if (this.cache.isReady) + { + this.raf.start(); + } + else + { + this.cache.onReady.addOnce(function () { + this.raf.start(); + }, this); + } + + }, + + /** + * Displays a Phaser version debug header in the console. + * + * @method Phaser.Game#showDebugHeader + * @protected + */ + showDebugHeader: function () { + + if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner) + { + return; + } + + 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.ie) // https://developer.mozilla.org/en-US/docs/Web/API/Console/log#Browser_compatibility + { + var args = [ + '%c %c %c Phaser CE v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665', + 'background: #fb8cb3', + 'background: #d44a52', + 'color: #ffffff; background: #871905;', + 'background: #d44a52', + 'background: #fb8cb3', + 'background: #ffffff' + ]; + + for (var i = 0; i < 3; i++) + { + if (i < c) + { + args.push('color: #ff2424; background: #fff'); + } + else + { + args.push('color: #959595; background: #fff'); + } + } + + console.log.apply(console, args); + } + else if (window['console']) + { + console.log('Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' | http://phaser.io'); + } + + }, + + /** + * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. + * + * @method Phaser.Game#setUpRenderer + * @protected + */ + setUpRenderer: function () { + + if (!this.device.canvas) + { + // Nothing else to do + throw new Error('Phaser.Game - Cannot create Canvas 2d context, aborting.'); + } + + if (this.config['canvas']) + { + this.canvas = this.config['canvas']; + } + else + { + this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true); + } + + if (this.config['canvasStyle']) + { + this.canvas.style = this.config['canvasStyle']; + } + else + { + this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; + } + + if (this.config['crisp']) + { + Phaser.Canvas.setImageRenderingCrisp(this.canvas); + } + + if ((this.renderType === Phaser.WEBGL) || + (this.renderType === Phaser.WEBGL_MULTI) || + (this.renderType === Phaser.AUTO && this.device.webGL)) + { + if (this.multiTexture || this.renderType === Phaser.WEBGL_MULTI) + { + PIXI.enableMultiTexture(); + this.multiTexture = true; + } + + try + { + this.renderer = new PIXI.WebGLRenderer(this, this.config); + this.renderType = Phaser.WEBGL; + this.context = null; + this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); + this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); + } + catch (webGLRendererError) + { + this.renderer = null; + this.multiTexture = false; + PIXI._enableMultiTextureToggle = false; + + if (this.renderType === Phaser.WEBGL) + { + // No fallback + throw webGLRendererError; + } + } + } + + if (!this.renderer) + { + this.renderer = new PIXI.CanvasRenderer(this, this.config); + this.context = this.renderer.context; + + if (this.renderType === Phaser.AUTO) + { + this.renderType = Phaser.CANVAS; + } + } + + if (this.device.cocoonJS) + { + this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false; + } + + if (this.renderType !== Phaser.HEADLESS) + { + this.stage.smoothed = this.antialias; + + Phaser.Canvas.addToDOM(this.canvas, this.parent, false); + Phaser.Canvas.setTouchAction(this.canvas); + } + + }, + + /** + * Handles WebGL context loss. + * + * @method Phaser.Game#contextLost + * @private + * @param {Event} event - The webglcontextlost event. + */ + contextLost: function (event) { + + event.preventDefault(); + + this.renderer.contextLost = true; + + }, + + /** + * Handles WebGL context restoration. + * + * @method Phaser.Game#contextRestored + * @private + */ + contextRestored: function () { + + this.renderer.initContext(); + + this.cache.clearGLTextures(); + + this.renderer.contextLost = false; + + }, + + /** + * The core game loop. + * + * @method Phaser.Game#update + * @protected + * @param {number} time - The current time as provided by RequestAnimationFrame. + */ + update: function (time) { + + if (this.pendingDestroy) + { + this.destroy(); + return; + } + + this.time.update(time); + + if (this._kickstart) + { + this.updateLogic(this.time.desiredFpsMult); + + // call the game render update exactly once every frame + this.updateRender(this.time.slowMotion * this.time.desiredFps); + + this._kickstart = false; + + return; + } + + // if the logic time is spiraling upwards, skip a frame entirely + if (this._spiraling > 1 && !this.forceSingleUpdate) + { + // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate + if (this.time.time > this._nextFpsNotification) + { + // only permit one fps notification per 10 seconds + this._nextFpsNotification = this.time.time + 10000; + + // dispatch the notification signal + this.fpsProblemNotifier.dispatch(); + } + + // reset the _deltaTime accumulator which will cause all pending late updates to be permanently skipped + this._deltaTime = 0; + this._spiraling = 0; + + if (this.dropFrames) + { + this.rendersThisFrame = 0; + } + else + { + this.updateRender(this.time.slowMotion * this.time.desiredFps); + this.rendersThisFrame = 1; + } + } + else + { + // step size taking into account the slow motion speed + var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps; + + // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals + this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0); + + // call the game update logic multiple times if necessary to "catch up" with dropped frames + // unless forceSingleUpdate is true + var count = 0; + + this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); + + if (this.forceSingleUpdate) + { + this.updatesThisFrame = Math.min(1, this.updatesThisFrame); + } + + if (this.forceSingleRender) + { + this.rendersThisFrame = 1; + } + else + { + this.rendersThisFrame = Math.min(1, this.updatesThisFrame); + } + + while (this._deltaTime >= slowStep) + { + this._deltaTime -= slowStep; + this.currentUpdateID = count; + + this.updateLogic(this.time.desiredFpsMult); + + count++; + + if (this.forceSingleUpdate && count === 1) + { + break; + } + else + { + this.time.refresh(); + } + } + + // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly) + if (count > this._lastCount) + { + this._spiraling++; + } + else if (count < this._lastCount) + { + // looks like it caught up successfully, reset the spiral alert counter + this._spiraling = 0; + } + + this._lastCount = count; + + if (this.rendersThisFrame > 0) + { + this.updateRender(this._deltaTime / slowStep); + } + } + + }, + + /** + * Updates all logic subsystems in Phaser. Called automatically by Game.update. + * + * @method Phaser.Game#updateLogic + * @protected + * @param {number} timeStep - The current timeStep value as determined by Game.update. + */ + updateLogic: function (timeStep) { + + if (!this._paused && !this.pendingStep) + { + if (this.stepping) + { + this.pendingStep = true; + } + + this.time.countUpdate(); + + this.scale.preUpdate(); + this.debug.preUpdate(); + this.camera.preUpdate(); + this.physics.preUpdate(); + this.state.preUpdate(timeStep); + this.plugins.preUpdate(timeStep); + this.stage.preUpdate(); + + this.state.update(); + this.stage.update(); + this.tweens.update(); + this.sound.update(); + this.input.update(); + this.physics.update(); + this.plugins.update(); + + this.stage.postUpdate(); + this.plugins.postUpdate(); + } + else + { + // Scaling and device orientation changes are still reflected when paused. + this.scale.pauseUpdate(); + this.state.pauseUpdate(timeStep); + this.debug.preUpdate(); + this.input.pauseUpdate(); + } + + this.stage.updateTransform(); + + }, + + /** + * Runs the Render cycle. + * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. + * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. + * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. + * After this State.render is called. Any rendering that happens here will take place on-top of the display list. + * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. + * This method is called automatically by Game.update, you don't need to call it directly. + * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. + * Phaser will only render when this boolean is `false`. + * + * @method Phaser.Game#updateRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + updateRender: function (elapsedTime) { + + if (this.lockRender) + { + return; + } + + this.time.countRender(); + + this.state.preRender(elapsedTime); + + if (this.renderType !== Phaser.HEADLESS) + { + this.renderer.render(this.stage); + + this.plugins.render(elapsedTime); + + this.state.render(elapsedTime); + } + + this.plugins.postRender(elapsedTime); + + }, + + /** + * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) + * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! + * + * @method Phaser.Game#enableStep + */ + enableStep: function () { + + this.stepping = true; + this.pendingStep = false; + this.stepCount = 0; + + }, + + /** + * Disables core game loop stepping. + * + * @method Phaser.Game#disableStep + */ + disableStep: function () { + + this.stepping = false; + this.pendingStep = false; + + }, + + /** + * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. + * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. + * + * @method Phaser.Game#step + */ + step: function () { + + this.pendingStep = false; + this.stepCount++; + + }, + + /** + * Nukes the entire game from orbit. + * + * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. + * + * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM + * and resets the PIXI default renderer. + * + * To destroy the game during an update callback, set {@link #pendingDestroy} instead. + * + * @method Phaser.Game#destroy + */ + destroy: function () { + + this.raf.stop(); + + if (this.debug.destroy) + { + this.debug.destroy(); + } + + this.state.destroy(); + this.sound.destroy(); + this.scale.destroy(); + this.stage.destroy(); + this.input.destroy(); + this.physics.destroy(); + this.plugins.destroy(); + + this.debug = null; + this.state = null; + this.sound = null; + this.scale = null; + this.stage = null; + this.input = null; + this.physics = null; + this.plugins = null; + + this.cache = null; + this.load = null; + this.time = null; + this.world = null; + + this.isBooted = false; + + this.renderer.destroy(false); + + Phaser.Canvas.removeFromDOM(this.canvas); + + PIXI.defaultRenderer = null; + + Phaser.GAMES[this.id] = null; + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gamePaused + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gamePaused: function (event) { + + // If the game is already paused it was done via game code, so don't re-pause it + if (!this._paused) + { + this._paused = true; + + this.time.gamePaused(); + + if (this.sound.muteOnPause) + { + this.sound.setMute(); + } + + this.onPause.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = true; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gameResumed + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gameResumed: function (event) { + + // Game is paused, but wasn't paused via code, so resume it + if (this._paused && !this._codePaused) + { + this._paused = false; + + this.time.gameResumed(); + + this.input.reset(); + + if (this.sound.muteOnPause) + { + this.sound.unsetMute(); + } + + this.onResume.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = false; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusLoss + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusLoss: function (event) { + + this.onBlur.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gamePaused(event); + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusGain + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusGain: function (event) { + + this.onFocus.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gameResumed(event); + } + + } + +}; + +Phaser.Game.prototype.constructor = Phaser.Game; + +/** +* The paused state of the Game. A paused game doesn't update any of its subsystems. +* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. +* @name Phaser.Game#paused +* @property {boolean} paused - Gets and sets the paused state of the Game. +*/ +Object.defineProperty(Phaser.Game.prototype, "paused", { + + get: function () { + return this._paused; + }, + + set: function (value) { + + if (value === true) + { + if (this._paused === false) + { + this._paused = true; + this.sound.setMute(); + this.time.gamePaused(); + this.onPause.dispatch(this); + } + this._codePaused = true; + } + else + { + if (this._paused) + { + this._paused = false; + this.input.reset(); + this.sound.unsetMute(); + this.time.gameResumed(); + this.onResume.dispatch(this); + } + this._codePaused = false; + } + + } + +}); + +/** + * + * "Deleted code is debugged code." - Jeff Sickel + * + * ヽ(〃^▽^〃)ノ + * +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. +* The Input manager is updated automatically by the core game loop. +* +* @class Phaser.Input +* @constructor +* @param {Phaser.Game} game - Current game instance. +*/ +Phaser.Input = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. + * @default + */ + this.hitCanvas = null; + + /** + * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. + * @default + */ + this.hitContext = null; + + /** + * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. + * To add a callback to this array please use `Input.addMoveCallback`. + * @property {array} moveCallbacks + * @protected + */ + this.moveCallbacks = []; + + /** + * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandler = null; + + /** + * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandlerContext = null; + + /** + * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. + * @default + */ + this.pollRate = 0; + + /** + * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. + * + * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. + * @default + */ + this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE; + + /** + * @property {Phaser.Point} position - A point object representing the current position of the Pointer. + * @default + */ + this.position = null; + + /** + * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. + */ + this.speed = null; + + /** + * A Circle object centered on the x/y screen coordinates of the Input. + * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. + * @property {Phaser.Circle} circle + */ + this.circle = null; + + /** + * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. + */ + this.scale = null; + + /** + * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1. + * @default -1 (Limited by total pointers.) + */ + this.maxPointers = -1; + + /** + * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. + * @default + */ + this.tapRate = 200; + + /** + * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. + * @default + */ + this.doubleTapRate = 300; + + /** + * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. + * @default + */ + this.holdRate = 2000; + + /** + * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. + * @default + */ + this.justPressedRate = 200; + + /** + * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . + * @default + */ + this.justReleasedRate = 200; + + /** + * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. + * The history is cleared each time the Pointer is pressed down. + * The history is updated at the rate specified in Input.pollRate + * @property {boolean} recordPointerHistory + * @default + */ + this.recordPointerHistory = false; + + /** + * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. + * @default + */ + this.recordRate = 100; + + /** + * The total number of entries that can be recorded into the Pointer objects tracking history. + * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. + * @property {number} recordLimit + * @default + */ + this.recordLimit = 100; + + /** + * An array of callbacks that will be fired every time a native touch start or touch end event (pointerdown or pointerup when using Pointer events) is received from the browser. + * This is used internally to handle audio and video unlocking on mobile devices. + * To add a callback to this array please use `Input.addTouchLockCallback`. + * @property {array} touchLockCallbacks + * @protected + */ + this.touchLockCallbacks = []; + + /** + * @property {Phaser.Pointer} pointer1 - A Pointer object. + */ + this.pointer1 = null; + + /** + * @property {Phaser.Pointer} pointer2 - A Pointer object. + */ + this.pointer2 = null; + + /** + * @property {Phaser.Pointer} pointer3 - A Pointer object. + */ + this.pointer3 = null; + + /** + * @property {Phaser.Pointer} pointer4 - A Pointer object. + */ + this.pointer4 = null; + + /** + * @property {Phaser.Pointer} pointer5 - A Pointer object. + */ + this.pointer5 = null; + + /** + * @property {Phaser.Pointer} pointer6 - A Pointer object. + */ + this.pointer6 = null; + + /** + * @property {Phaser.Pointer} pointer7 - A Pointer object. + */ + this.pointer7 = null; + + /** + * @property {Phaser.Pointer} pointer8 - A Pointer object. + */ + this.pointer8 = null; + + /** + * @property {Phaser.Pointer} pointer9 - A Pointer object. + */ + this.pointer9 = null; + + /** + * @property {Phaser.Pointer} pointer10 - A Pointer object. + */ + this.pointer10 = null; + + /** + * An array of non-mouse pointers that have been added to the game. + * The properties `pointer1..N` are aliases for `pointers[0..N-1]`. + * @property {Phaser.Pointer[]} pointers + * @public + * @readonly + */ + this.pointers = []; + + /** + * The most recently active Pointer object. + * + * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. + * + * @property {Phaser.Pointer} activePointer + */ + this.activePointer = null; + + /** + * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. + * + * @property {Pointer} mousePointer + */ + this.mousePointer = null; + + /** + * The Mouse Input manager. + * + * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Mouse} mouse + */ + this.mouse = null; + + /** + * The Keyboard Input manager. + * + * @property {Phaser.Keyboard} keyboard + */ + this.keyboard = null; + + /** + * The Touch Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Touch} touch + */ + this.touch = null; + + /** + * The MSPointer Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.MSPointer} mspointer + */ + this.mspointer = null; + + /** + * The Gamepad Input manager. + * + * @property {Phaser.Gamepad} gamepad + */ + this.gamepad = null; + + /** + * If the Input Manager has been reset locked then all calls made to InputManager.reset, + * such as from a State change, are ignored. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is pressed down. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onDown + */ + this.onDown = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is released. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onUp + */ + this.onUp = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is tapped. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {boolean} True if this was a double tap. + * + * @property {Phaser.Signal} onTap + */ + this.onTap = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is held down. + * It is sent one argument: + * + * - {Phaser.Pointer} The pointer that caused the event. + * + * @property {Phaser.Signal} onHold + */ + this.onHold = null; + + /** + * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. + * This is useful when stacking UI layers. Set to zero to disable. + * @property {number} minPriorityID + * @default + */ + this.minPriorityID = 0; + + /** + * A list of interactive objects. The InputHandler components add and remove themselves from this list. + * @property {Phaser.ArraySet} interactiveItems + */ + this.interactiveItems = new Phaser.ArraySet(); + + /** + * @property {Phaser.Point} _localPoint - Internal cache var. + * @private + */ + this._localPoint = new Phaser.Point(); + + /** + * @property {number} _pollCounter - Internal var holding the current poll counter. + * @private + */ + this._pollCounter = 0; + + /** + * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. + * @private + */ + this._oldPosition = null; + + /** + * @property {number} _x - x coordinate of the most recent Pointer event + * @private + */ + this._x = 0; + + /** + * @property {number} _y - Y coordinate of the most recent Pointer event + * @private + */ + this._y = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_TOUCH_COMBINE = 2; + +/** +* The maximum number of pointers that can be added. This excludes the mouse pointer. +* @constant +* @type {integer} +*/ +Phaser.Input.MAX_POINTERS = 10; + +Phaser.Input.prototype = { + + /** + * Starts the Input Manager running. + * + * @method Phaser.Input#boot + * @protected + */ + boot: function () { + + this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR); + this.addPointer(); + this.addPointer(); + + this.mouse = new Phaser.Mouse(this.game); + this.touch = new Phaser.Touch(this.game); + this.mspointer = new Phaser.MSPointer(this.game); + + if (Phaser.Keyboard) + { + this.keyboard = new Phaser.Keyboard(this.game); + } + + if (Phaser.Gamepad) + { + this.gamepad = new Phaser.Gamepad(this.game); + } + + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + + this.scale = new Phaser.Point(1, 1); + this.speed = new Phaser.Point(); + this.position = new Phaser.Point(); + this._oldPosition = new Phaser.Point(); + + this.circle = new Phaser.Circle(0, 0, 44); + + this.activePointer = this.mousePointer; + + this.hitCanvas = Phaser.CanvasPool.create(this, 1, 1); + this.hitContext = this.hitCanvas.getContext('2d'); + + this.mouse.start(); + if (!this.game.device.mspointer) + { + // Chrome >= 55 fires both PointerEvent and TouchEvent. + // Pick only one. + this.touch.start(); + } + this.mspointer.start(); + this.mousePointer.active = true; + + if (this.keyboard) + { + this.keyboard.start(); + } + + var _this = this; + + this._onClickTrampoline = function (event) { + _this.onClickTrampoline(event); + }; + + this.game.canvas.addEventListener('click', this._onClickTrampoline, false); + + }, + + /** + * Stops all of the Input Managers from running. + * + * @method Phaser.Input#destroy + */ + destroy: function () { + + this.mouse.stop(); + this.touch.stop(); + this.mspointer.stop(); + + if (this.keyboard) + { + this.keyboard.stop(); + } + + if (this.gamepad) + { + this.gamepad.stop(); + } + + this.moveCallbacks = []; + + Phaser.CanvasPool.remove(this); + + this.game.canvas.removeEventListener('click', this._onClickTrampoline); + + }, + + /** + * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. + * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to + * interact with. It works by polling all of the valid game objects, and then slowly discounting those + * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). + * + * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid + * for input and overlap with the Pointer. If you need fine-grained control over which of the items is + * selected then you can use this callback to do so. + * + * The callback will be sent 3 parameters: + * + * 1) A reference to the Phaser.Pointer object that is processing the Items. + * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. + * 3) The current 'favorite' candidate, based on its priorityID and position in the display list. + * + * Your callback MUST return one of the candidates sent to it. + * + * @method Phaser.Input#setInteractiveCandidateHandler + * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. + * @param {object} context - The context in which the callback will be called. + */ + setInteractiveCandidateHandler: function (callback, context) { + + this.customCandidateHandler = callback; + this.customCandidateHandlerContext = context; + + }, + + /** + * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. + * + * The callback will be sent 4 parameters: + * + * A reference to the Phaser.Pointer object that moved, + * The x position of the pointer, + * The y position, + * A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down). + * + * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best + * to only use if you've limited input to a single pointer (i.e. mouse or touch). + * + * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. + * + * @method Phaser.Input#addMoveCallback + * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. + * @param {object} context - The context in which the callback will be called. + */ + addMoveCallback: function (callback, context) { + + this.moveCallbacks.push({ callback: callback, context: context }); + + }, + + + /** + * Adds a callback that is fired when a browser touchstart/pointerdown or touchend/pointerup event is received. + * + * This is used internally to handle audio and video unlocking on mobile devices. + * + * If the callback returns 'true' then the callback is automatically deleted once invoked. + * + * The callback is added to the {@link #touchLockCallbacks} array and should be removed with {@link #removeTouchLockCallback}. + * + * @method Phaser.Input#addTouchLockCallback + * @param {function} callback - The callback that will be called when a touchstart event is received. + * @param {object} context - The context in which the callback will be called. + * @param {boolean} [onEnd=false] - Will the callback fire on a touchstart/pointerdown (default) or touchend/pointerup event? + */ + addTouchLockCallback: function (callback, context, onEnd) { + + if (onEnd === undefined) { onEnd = false; } + + this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd }); + + }, + + /** + * Removes the callback at the defined index from the {@link #touchLockCallbacks} array + * + * @method Phaser.Input#removeTouchLockCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + * @return {boolean} True if the callback was deleted, otherwise false. + */ + removeTouchLockCallback: function (callback, context) { + + var i = this.touchLockCallbacks.length; + + while (i--) + { + if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context) + { + this.touchLockCallbacks.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Execute any {@link #touchLockCallbacks} of the given type. + * + * @method Phaser.Input#executeTouchLockCallbacks + * @private + * @param {boolean} onEnd - Execute the touchend/pointerup callbacks (true) or the touchstart/pointerdown callbacks (false). Required! + * @param {Event} event - The native event from the browser. + */ + executeTouchLockCallbacks: function (onEnd, event) { + var i = this.touchLockCallbacks.length; + + while (i--) + { + var cb = this.touchLockCallbacks[i]; + + if (cb.onEnd === onEnd && cb.callback.call(cb.context, this, event)) + { + this.touchLockCallbacks.splice(i, 1); + } + } + }, + + /** + * Removes the callback from the Phaser.Input.moveCallbacks array. + * + * @method Phaser.Input#deleteMoveCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + */ + deleteMoveCallback: function (callback, context) { + + var i = this.moveCallbacks.length; + + while (i--) + { + if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context) + { + this.moveCallbacks.splice(i, 1); + return; + } + } + + }, + + /** + * Add a new Pointer object to the Input Manager. + * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. + * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). + * + * @method Phaser.Input#addPointer + * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. + */ + addPointer: function () { + + if (this.pointers.length >= Phaser.Input.MAX_POINTERS) + { + console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached."); + return null; + } + + var id = this.pointers.length + 1; + var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.CONTACT); + + this.pointers.push(pointer); + this['pointer' + id] = pointer; + + return pointer; + + }, + + /** + * Updates the Input Manager. Called by the core Game loop. + * + * @method Phaser.Input#update + * @protected + */ + update: function () { + + if (this.keyboard) + { + this.keyboard.update(); + } + + if (this.pollRate > 0 && this._pollCounter < this.pollRate) + { + this._pollCounter++; + return; + } + + this.speed.x = this.position.x - this._oldPosition.x; + this.speed.y = this.position.y - this._oldPosition.y; + + this._oldPosition.copyFrom(this.position); + this.mousePointer.update(); + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].update(); + } + + this._pollCounter = 0; + + }, + + /** + * Update method while paused. + * + * @method Phaser.Input#pauseUpdate + * @private + */ + pauseUpdate: function () { + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + }, + + /** + * Reset all of the Pointers and Input states. + * + * The optional `hard` parameter will reset any events or callbacks that may be bound. + * Input.reset is called automatically during a State change or if a game loses focus / visibility. + * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. + * + * @method Phaser.Input#reset + * @public + * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. + */ + reset: function (hard) { + + if (!this.game.isBooted || this.resetLocked) + { + return; + } + + if (hard === undefined) { hard = false; } + + this.mousePointer.reset(); + + if (this.keyboard) + { + this.keyboard.reset(hard); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].reset(); + } + + if (this.game.canvas.style.cursor !== 'none') + { + this.game.canvas.style.cursor = ''; + } + + if (hard) + { + this.onDown.dispose(); + this.onUp.dispose(); + this.onTap.dispose(); + this.onHold.dispose(); + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + this.moveCallbacks = []; + } + + this._pollCounter = 0; + + }, + + /** + * Resets the speed and old position properties. + * + * @method Phaser.Input#resetSpeed + * @param {number} x - Sets the oldPosition.x value. + * @param {number} y - Sets the oldPosition.y value. + */ + resetSpeed: function (x, y) { + + this._oldPosition.setTo(x, y); + this.speed.setTo(0, 0); + + }, + + /** + * Find the first free Pointer object and start it, passing in the event data. + * This is called automatically by Phaser.Touch and Phaser.MSPointer. + * + * @method Phaser.Input#startPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. + */ + startPointer: function (event) { + + if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers) + { + return null; + } + + if (!this.pointer1.active) + { + return this.pointer1.start(event); + } + + if (!this.pointer2.active) + { + return this.pointer2.start(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (!pointer.active) + { + return pointer.start(event); + } + } + + return null; + + }, + + /** + * Updates the matching Pointer object, passing in the event data. + * This is called automatically and should not normally need to be invoked. + * + * @method Phaser.Input#updatePointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. + */ + updatePointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.move(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.move(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.move(event); + } + } + + return null; + + }, + + /** + * Stops the matching Pointer object, passing in the event data. + * + * @method Phaser.Input#stopPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. + */ + stopPointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.stop(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.stop(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.stop(event); + } + } + + return null; + + }, + + /** + * Returns the total number of active pointers, not exceeding the specified limit + * + * @name Phaser.Input#countActivePointers + * @private + * @property {integer} [limit=(max pointers)] - Stop counting after this. + * @return {integer} The number of active pointers, or limit - whichever is less. + */ + countActivePointers: function (limit) { + + if (limit === undefined) { limit = this.pointers.length; } + + var count = limit; + + for (var i = 0; i < this.pointers.length && count > 0; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active) + { + count--; + } + } + + return (limit - count); + + }, + + /** + * Get the first Pointer with the given active state. + * + * @method Phaser.Input#getPointer + * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. + */ + getPointer: function (isActive) { + + if (isActive === undefined) { isActive = false; } + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active === isActive) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `identifier` property matches the given identifier value. + * + * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down, and is not fixed once set. + * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. + * + * @method Phaser.Input#getPointerFromIdentifier + * @param {number} identifier - The Pointer.identifier value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromIdentifier: function (identifier) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.identifier === identifier) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `pointerId` property matches the given value. + * + * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down if the browser recycles it. + * + * @method Phaser.Input#getPointerFromId + * @param {number} pointerId - The `pointerId` (not 'id') value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromId: function (pointerId) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.pointerId === pointerId) + { + return pointer; + } + } + + return null; + + }, + + /** + * This will return the local coordinates of the specified displayObject based on the given Pointer. + * + * @method Phaser.Input#getLocalPosition + * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. + * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. + * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. + */ + getLocalPosition: function (displayObject, pointer, output) { + + if (output === undefined) { output = new Phaser.Point(); } + + var wt = displayObject.worldTransform; + var id = 1 / (wt.a * wt.d + wt.c * -wt.b); + + return output.setTo( + wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id, + wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id + ); + + }, + + /** + * Tests if the pointer hits the given object. + * + * @method Phaser.Input#hitTest + * @param {DisplayObject} displayObject - The displayObject to test for a hit. + * @param {Phaser.Pointer} pointer - The pointer to use for the test. + * @param {Phaser.Point} localPoint - The local translated point. + */ + hitTest: function (displayObject, pointer, localPoint) { + + if (!displayObject.worldVisible) + { + return false; + } + + this.getLocalPosition(displayObject, pointer, this._localPoint); + + localPoint.copyFrom(this._localPoint); + + if (displayObject.hitArea && displayObject.hitArea.contains) + { + return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y)); + } + else if (Phaser.Creature && displayObject instanceof Phaser.Creature) { + var width = Math.abs(displayObject.width); + var height = Math.abs(displayObject.height); + var x1 = displayObject.x - (width * displayObject.anchorX); + + if (this.game.camera.x + pointer.x >= x1 && this.game.camera.x + pointer.x < x1 + width) + { + var y1 = displayObject.y - (height * displayObject.anchorY); + + if (this.game.camera.y + pointer.y >= y1 && this.game.camera.y + pointer.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.TileSprite) + { + var width = displayObject.width; + var height = displayObject.height; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof PIXI.Sprite) + { + var width = displayObject.texture.frame.width / displayObject.texture.baseTexture.resolution; + var height = displayObject.texture.frame.height / displayObject.texture.baseTexture.resolution; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.Graphics) + { + for (var i = 0; i < displayObject.graphicsData.length; i++) + { + var data = displayObject.graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // Only deal with fills.. + if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y)) + { + return true; + } + } + } + + // Didn't hit the parent, does it have any children? + + for (var i = 0; i < displayObject.children.length; i++) + { + if (this.hitTest(displayObject.children[i], pointer, localPoint)) + { + return true; + } + } + + return false; + }, + + /** + * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. + * + * @method Phaser.Input#onClickTrampoline + * @private + */ + onClickTrampoline: function () { + + // It might not always be the active pointer, but this does work on + // Desktop browsers (read: IE) with Mouse or MSPointer input. + this.activePointer.processClickTrampolines(); + + } + +}; + +Phaser.Input.prototype.constructor = Phaser.Input; + +/** +* The X coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. +* @name Phaser.Input#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Input.prototype, "x", { + + get: function () { + return this._x; + }, + + set: function (value) { + this._x = Math.floor(value); + } + +}); + +/** +* The Y coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. +* @name Phaser.Input#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Input.prototype, "y", { + + get: function () { + return this._y; + }, + + set: function (value) { + this._y = Math.floor(value); + } + +}); + +/** +* True if the Input is currently poll rate locked. +* @name Phaser.Input#pollLocked +* @property {boolean} pollLocked +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "pollLocked", { + + get: function () { + return (this.pollRate > 0 && this._pollCounter < this.pollRate); + } + +}); + +/** +* The total number of inactive Pointers. +* @name Phaser.Input#totalInactivePointers +* @property {number} totalInactivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", { + + get: function () { + return this.pointers.length - this.countActivePointers(); + } + +}); + +/** +* The total number of active Pointers, not counting the mouse pointer. +* @name Phaser.Input#totalActivePointers +* @property {integers} totalActivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", { + + get: function () { + return this.countActivePointers(); + } + +}); + +/** +* The world X coordinate of the most recently active pointer. +* @name Phaser.Input#worldX +* @property {number} worldX - The world X coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldX", { + + get: function () { + return this.game.camera.view.x + this.x; + } + +}); + +/** +* The world Y coordinate of the most recently active pointer. +* @name Phaser.Input#worldY +* @property {number} worldY - The world Y coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldY", { + + get: function () { + return this.game.camera.view.y + this.y; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Mouse class is responsible for handling all aspects of mouse interaction with the browser. +* +* It captures and processes mouse events that happen on the game canvas object. +* It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released +* when not over the game. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object +* which normalises all game input for you, including accurate button handling. +* +* @class Phaser.Mouse +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Mouse = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down. + */ + this.mouseDownCallback = null; + + /** + * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state. + */ + this.mouseUpCallback = null; + + /** + * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas. + */ + this.mouseOutCallback = null; + + /** + * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). + */ + this.mouseOverCallback = null; + + /** + * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used. + */ + this.mouseWheelCallback = null; + + /** + * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + */ + this.capture = false; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + * @default + */ + this.button = -1; + + /** + * The direction of the _last_ mousewheel usage 1 for up -1 for down. + * @property {number} wheelDelta + */ + this.wheelDelta = 0; + + /** + * Mouse input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true. + * @default + */ + this.locked = false; + + /** + * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas. + * @default + */ + this.stopOnGameOut = false; + + /** + * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state. + * @default + */ + this.pointerLock = new Phaser.Signal(); + + /** + * The browser mouse DOM event. Will be null if no mouse event has ever been received. + * Access this property only inside a Mouse event handler and do not keep references to it. + * @property {MouseEvent|null} event + * @default + */ + this.event = null; + + /** + * @property {function} _onMouseDown - Internal event handler reference. + * @private + */ + this._onMouseDown = null; + + /** + * @property {function} _onMouseMove - Internal event handler reference. + * @private + */ + this._onMouseMove = null; + + /** + * @property {function} _onMouseUp - Internal event handler reference. + * @private + */ + this._onMouseUp = null; + + /** + * @property {function} _onMouseOut - Internal event handler reference. + * @private + */ + this._onMouseOut = null; + + /** + * @property {function} _onMouseOver - Internal event handler reference. + * @private + */ + this._onMouseOver = null; + + /** + * @property {function} _onMouseWheel - Internal event handler reference. + * @private + */ + this._onMouseWheel = null; + + /** + * Wheel proxy event object, if required. Shared for all wheel events for this mouse. + * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent + * @private + */ + this._wheelEvent = null; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.NO_BUTTON = -1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.LEFT_BUTTON = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.MIDDLE_BUTTON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.RIGHT_BUTTON = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.BACK_BUTTON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.FORWARD_BUTTON = 4; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_UP = 1; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_DOWN = -1; + +Phaser.Mouse.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Mouse#start + */ + start: function () { + + if (this.game.device.android && this.game.device.chrome === false) + { + // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ... + return; + } + + if (this._onMouseDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onMouseDown = function (event) { + return _this.onMouseDown(event); + }; + + this._onMouseMove = function (event) { + return _this.onMouseMove(event); + }; + + this._onMouseUp = function (event) { + return _this.onMouseUp(event); + }; + + this._onMouseUpGlobal = function (event) { + return _this.onMouseUpGlobal(event); + }; + + this._onMouseOutGlobal = function (event) { + return _this.onMouseOutGlobal(event); + }; + + this._onMouseOut = function (event) { + return _this.onMouseOut(event); + }; + + this._onMouseOver = function (event) { + return _this.onMouseOver(event); + }; + + this._onMouseWheel = function (event) { + return _this.onMouseWheel(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('mousedown', this._onMouseDown, true); + canvas.addEventListener('mousemove', this._onMouseMove, true); + canvas.addEventListener('mouseup', this._onMouseUp, true); + + if (!this.game.device.cocoonJS) + { + window.addEventListener('mouseup', this._onMouseUpGlobal, true); + window.addEventListener('mouseout', this._onMouseOutGlobal, true); + canvas.addEventListener('mouseover', this._onMouseOver, true); + canvas.addEventListener('mouseout', this._onMouseOut, true); + } + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.addEventListener(wheelEvent, this._onMouseWheel, true); + + if (wheelEvent === 'mousewheel') + { + this._wheelEvent = new WheelEventProxy(-1/40, 1); + } + else if (wheelEvent === 'DOMMouseScroll') + { + this._wheelEvent = new WheelEventProxy(1, 1); + } + } + + }, + + /** + * The internal method that handles the mouse down event from the browser. + * @method Phaser.Mouse#onMouseDown + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseDown: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseDownCallback) + { + this.mouseDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.start(event); + + }, + + /** + * The internal method that handles the mouse move event from the browser. + * @method Phaser.Mouse#onMouseMove + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseMoveCallback) + { + this.mouseMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.move(event); + + }, + + /** + * The internal method that handles the mouse up event from the browser. + * @method Phaser.Mouse#onMouseUp + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUp: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.Mouse#onMouseUpGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUpGlobal: function (event) { + + if (!this.input.mousePointer.withinGame) + { + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + }, + + /** + * The internal method that handles the mouse out event from the window. + * + * @method Phaser.Mouse#onMouseOutGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOutGlobal: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (!this.input.enabled || !this.enabled) + { + return; + } + + // If we get a mouseout event from the window then basically + // something serious has gone down, usually along the lines of + // the browser opening a context-menu or similar. + // On OS X Chrome especially this is bad news, as it blocks + // us then getting a mouseup event, so we need to force that through. + // + // No matter what, we must cancel the left and right buttons + + this.input.mousePointer.stop(event); + + // Clear the button states (again?) + this.input.mousePointer.resetButtons(); + + }, + + /** + * The internal method that handles the mouse out event from the browser. + * + * @method Phaser.Mouse#onMouseOut + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (this.mouseOutCallback) + { + this.mouseOutCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.stopOnGameOut) + { + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + this.input.interactiveItems.callAll('_pointerOutHandler', this.input.mousePointer); + + }, + + /** + * The internal method that handles the mouse over event from the browser. + * + * @method Phaser.Mouse#onMouseOver + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = true; + + if (this.mouseOverCallback) + { + this.mouseOverCallback.call(this.callbackContext, event); + } + + }, + + /** + * The internal method that handles the mouse wheel event from the browser. + * + * @method Phaser.Mouse#onMouseWheel + * @param {MouseEvent} event - The native event from the browser. + */ + onMouseWheel: function (event) { + + if (this._wheelEvent) { + event = this._wheelEvent.bindEvent(event); + } + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + // reverse detail for firefox + this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1); + + if (this.mouseWheelCallback) + { + this.mouseWheelCallback.call(this.callbackContext, event); + } + + }, + + /** + * If the browser supports it you can request that the pointer be locked to the browser window. + * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key. + * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'. + * @method Phaser.Mouse#requestPointerLock + */ + requestPointerLock: function () { + + if (this.game.device.pointerLock) + { + var element = this.game.canvas; + + element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; + + element.requestPointerLock(); + + var _this = this; + + this._pointerLockChange = function (event) { + return _this.pointerLockChange(event); + }; + + document.addEventListener('pointerlockchange', this._pointerLockChange, true); + document.addEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true); + } + + }, + + /** + * Internal pointerLockChange handler. + * + * @method Phaser.Mouse#pointerLockChange + * @param {Event} event - The native event from the browser. This gets stored in Mouse.event. + */ + pointerLockChange: function (event) { + + var element = this.game.canvas; + + if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) + { + // Pointer was successfully locked + this.locked = true; + this.pointerLock.dispatch(true, event); + } + else + { + // Pointer was unlocked + this.locked = false; + this.pointerLock.dispatch(false, event); + } + + }, + + /** + * Internal release pointer lock handler. + * @method Phaser.Mouse#releasePointerLock + */ + releasePointerLock: function () { + + document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; + + document.exitPointerLock(); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + }, + + /** + * Stop the event listeners. + * @method Phaser.Mouse#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('mousedown', this._onMouseDown, true); + canvas.removeEventListener('mousemove', this._onMouseMove, true); + canvas.removeEventListener('mouseup', this._onMouseUp, true); + canvas.removeEventListener('mouseover', this._onMouseOver, true); + canvas.removeEventListener('mouseout', this._onMouseOut, true); + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.removeEventListener(wheelEvent, this._onMouseWheel, true); + } + + window.removeEventListener('mouseup', this._onMouseUpGlobal, true); + window.removeEventListener('mouseout', this._onMouseOutGlobal, true); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + } + +}; + +Phaser.Mouse.prototype.constructor = Phaser.Mouse; + +/* jshint latedef:nofunc */ +/** +* A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel' +* events to 'wheel'-like events. +* +* See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode. +* +* @method Phaser.Mouse#WheelEventProxy +* @private +* @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. +* @param {integer} deltaMode - The reported delta mode. +*/ +function WheelEventProxy (scaleFactor, deltaMode) { + + /** + * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. + * @private + */ + this._scaleFactor = scaleFactor; + + /** + * @property {number} _deltaMode - The reported delta mode. + * @private + */ + this._deltaMode = deltaMode; + + /** + * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit. + * @private + */ + this.originalEvent = null; + +} + +WheelEventProxy.prototype = {}; +WheelEventProxy.prototype.constructor = WheelEventProxy; + +WheelEventProxy.prototype.bindEvent = function (event) { + + // Generate stubs automatically + if (!WheelEventProxy._stubsGenerated && event) + { + var makeBinder = function (name) { + + return function () { + var v = this.originalEvent[name]; + return typeof v !== 'function' ? v : v.bind(this.originalEvent); + }; + + }; + + for (var prop in event) + { + if (!(prop in WheelEventProxy.prototype)) + { + Object.defineProperty(WheelEventProxy.prototype, prop, { + get: makeBinder(prop) + }); + } + } + WheelEventProxy._stubsGenerated = true; + } + + this.originalEvent = event; + return this; + +}; + +Object.defineProperties(WheelEventProxy.prototype, { + "type": { value: "wheel" }, + "deltaMode": { get: function () { return this._deltaMode; } }, + "deltaY": { + get: function () { + return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0; + } + }, + "deltaX": { + get: function () { + return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0; + } + }, + "deltaZ": { value: 0 } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The MSPointer class handles {@link https://developers.google.com/web/updates/2016/10/pointer-events Pointer-event} interactions with the game via a dedicated {@link Phaser.Pointer}. (It's named after the nonstandard {@link https://msdn.microsoft.com/library/hh673557(v=vs.85).aspx MSPointerEvent} since that was the first browser implementation.) +* +* It's {@link http://caniuse.com/#feat=pointer currently supported in IE 10+, Edge, Chrome (including Android), and Opera}. +* +* You should not normally access this class directly, but instead use a {@link Phaser.Pointer} object which +* normalises all game input for you including accurate button handling. +* +* Please note that at the current time of writing Phaser does not yet support chorded button interactions: +* http://www.w3.org/TR/pointerevents/#chorded-button-interactions +* +* You can disable Phaser's use of Pointer Events by either of two ways: +* +* ```javascript +* // **Before** `new Phaser.Game(…)`: +* Phaser.Device.onInitialized.add(function () { +* this.mspointer = false; +* }); +* ``` +* +* ```javascript +* // Once, in the earliest State `init` or `create` callback (e.g., Boot): +* this.input.mspointer.stop(); +* ``` +* +* @class Phaser.MSPointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.MSPointer = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called (defaults to game). + */ + this.callbackContext = this.game; + + /** + * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event. + */ + this.pointerDownCallback = null; + + /** + * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event. + */ + this.pointerMoveCallback = null; + + /** + * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event. + */ + this.pointerUpCallback = null; + + /** + * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, canceling the corresponding MouseEvent or TouchEvent. + */ + this.capture = true; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + */ + this.button = -1; + + /** + * The most recent PointerEvent from the browser. Will be null if no event has ever been received. + * Access this property only inside a Pointer event handler and do not keep references to it. + * @property {MSPointerEvent|PointerEvent|null} event + * @default + */ + this.event = null; + + /** + * PointerEvent input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {function} _onMSPointerDown - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerDown = null; + + /** + * @property {function} _onMSPointerMove - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerMove = null; + + /** + * @property {function} _onMSPointerUp - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUp = null; + + /** + * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUpGlobal = null; + + /** + * @property {function} _onMSPointerOut - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOut = null; + + /** + * @property {function} _onMSPointerOver - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOver = null; + +}; + +Phaser.MSPointer.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.MSPointer#start + */ + start: function () { + + if (this._onMSPointerDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + if (this.game.device.mspointer) + { + this._onMSPointerDown = function (event) { + return _this.onPointerDown(event); + }; + + this._onMSPointerMove = function (event) { + return _this.onPointerMove(event); + }; + + this._onMSPointerUp = function (event) { + return _this.onPointerUp(event); + }; + + this._onMSPointerUpGlobal = function (event) { + return _this.onPointerUpGlobal(event); + }; + + this._onMSPointerOut = function (event) { + return _this.onPointerOut(event); + }; + + this._onMSPointerOver = function (event) { + return _this.onPointerOver(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.addEventListener('pointerdown', this._onMSPointerDown, false); + canvas.addEventListener('pointermove', this._onMSPointerMove, false); + canvas.addEventListener('pointerup', this._onMSPointerUp, false); + + canvas.style['-ms-content-zooming'] = 'none'; + canvas.style['-ms-touch-action'] = 'none'; + + if (!this.game.device.cocoonJS) + { + window.addEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.addEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.addEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.addEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.addEventListener('pointerover', this._onMSPointerOver, true); + canvas.addEventListener('pointerout', this._onMSPointerOut, true); + } + } + + }, + + /** + * The function that handles the PointerDown event. + * + * @method Phaser.MSPointer#onPointerDown + * @param {PointerEvent} event - The native DOM event. + */ + onPointerDown: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerDownCallback) + { + this.pointerDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.start(event); + } + else + { + this.input.startPointer(event); + } + + }, + + /** + * The function that handles the PointerMove event. + * @method Phaser.MSPointer#onPointerMove + * @param {PointerEvent} event - The native DOM event. + */ + onPointerMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerMoveCallback) + { + this.pointerMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.move(event); + } + else + { + this.input.updatePointer(event); + } + + }, + + /** + * The function that handles the PointerUp event. + * @method Phaser.MSPointer#onPointerUp + * @param {PointerEvent} event - The native DOM event. + */ + onPointerUp: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerUpCallback) + { + this.pointerUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.stop(event); + } + else + { + this.input.stopPointer(event); + } + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.MSPointer#onPointerUpGlobal + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerUpGlobal: function (event) { + + if ((event.pointerType === 'mouse' || event.pointerType === 0x00000004) && !this.input.mousePointer.withinGame) + { + this.onPointerUp(event); + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer && pointer.withinGame) + { + this.onPointerUp(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = false; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = false; + } + } + + if (this.input.mouse.mouseOutCallback) + { + this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.input.mouse.stopOnGameOut) + { + event['identifier'] = 0; + + if (pointer) + { + pointer.stop(event); + } + else + { + this.input.mousePointer.stop(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = true; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = true; + } + } + + if (this.input.mouse.mouseOverCallback) + { + this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext, event); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.MSPointer#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.removeEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.removeEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.removeEventListener('pointerdown', this._onMSPointerDown, false); + canvas.removeEventListener('pointermove', this._onMSPointerMove, false); + canvas.removeEventListener('pointerup', this._onMSPointerUp, false); + + window.removeEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.removeEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.removeEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('pointerover', this._onMSPointerOver, true); + canvas.removeEventListener('pointerout', this._onMSPointerOut, true); + + } + +}; + +Phaser.MSPointer.prototype.constructor = Phaser.MSPointer; + +/** +* @author Richard Davey +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. +* +* For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, +* middle button and advanced buttons like back and forward. +* +* Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. +* +* On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. +* +* At the time of writing this there are device limitations you should be aware of: +* +* - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions +* (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, +* even when they are pressed. +* - On Linux (GTK), the 4th button and the 5th button are not supported. +* - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. +* +* @class Phaser.DeviceButton +* @constructor +* @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad. +* @param {number} buttonCode - The button code this DeviceButton is responsible for. +*/ +Phaser.DeviceButton = function (parent, buttonCode) { + + /** + * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = parent.game; + + /** + * @property {object} event - The DOM event that caused the change in button state. + * @default + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the button. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the button. + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - The timestamp when the button was last pressed down. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - The timestamp when the button was last released. + * @default + */ + this.timeUp = 0; + + /** + * Gamepad only. + * If a button is held down this holds down the number of times the button has 'repeated'. + * @property {number} repeats + * @default + */ + this.repeats = 0; + + /** + * True if the alt key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} altKey + * @default + */ + this.altKey = false; + + /** + * True if the shift key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} shiftKey + * @default + */ + this.shiftKey = false; + + /** + * True if the control key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} ctrlKey + * @default + */ + this.ctrlKey = false; + + /** + * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. + * @default + */ + this.value = 0; + + /** + * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. + */ + this.buttonCode = buttonCode; + + /** + * This Signal is dispatched every time this DeviceButton is pressed down. + * It is only dispatched once (until the button is released again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onDown + */ + this.onDown = new Phaser.Signal(); + + /** + * This Signal is dispatched every time this DeviceButton is released from a down state. + * It is only dispatched once (until the button is pressed again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onUp + */ + this.onUp = new Phaser.Signal(); + + /** + * Gamepad only. + * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onFloat + */ + this.onFloat = new Phaser.Signal(); + +}; + +Phaser.DeviceButton.prototype = { + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button down state. + * + * @method Phaser.DeviceButton#start + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + start: function (event, value) { + + if (this.isDown) + { + return; + } + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onDown.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button up state. + * + * @method Phaser.DeviceButton#stop + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + stop: function (event, value) { + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onUp.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer. + * Starts or stops button based on condition. + * + * @method Phaser.DeviceButton#startStop + * @protected + * @param {boolean} [condition] - The condition that decides between start or stop. + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + startStop: function (condition, event, value) { + + if (condition) + { + this.start(event, value); + } + else + { + this.stop(event, value); + } + + }, + + /** + * Called automatically by Phaser.SinglePad. + * + * @method Phaser.DeviceButton#padFloat + * @protected + * @param {number} value - Button value + */ + padFloat: function (value) { + + this.isDown = false; + this.isUp = false; + + this.value = value; + + this.onFloat.dispatch(this, value); + + }, + + /** + * Returns the "just pressed" state of this button. + * Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justPressed + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (duration) { + + duration = duration || 250; + + return (this.isDown && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * Returns the "just released" state of this button. + * Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justReleased + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (duration) { + + duration = duration || 250; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. + * + * @method Phaser.DeviceButton#reset + */ + reset: function () { + + this.isDown = false; + this.isUp = true; + + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.altKey = false; + this.shiftKey = false; + this.ctrlKey = false; + + }, + + /** + * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals + * and clears the parent and game references. + * + * @method Phaser.DeviceButton#destroy + */ + destroy: function () { + + this.onDown.dispose(); + this.onUp.dispose(); + this.onFloat.dispose(); + + this.parent = null; + this.game = null; + + } + +}; + +Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton; + +/** +* How long the button has been held down for in milliseconds. +* If not currently down it returns -1. +* +* @name Phaser.DeviceButton#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.DeviceButton.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. +* +* @class Phaser.Pointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. +* @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or CONTACT. +*/ +Phaser.Pointer = function (game, id, pointerMode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. + */ + this.id = id; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINTER; + + /** + * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps. + * @default + */ + this.exists = true; + + /** + * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.identifier = 0; + + /** + * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. + * @default + */ + this.pointerId = null; + + /** + * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer. + */ + this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT); + + /** + * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.target = null; + + /** + * The button property of the most recent DOM event when this Pointer is started. + * You should not rely on this value for accurate button detection, instead use the Pointer properties + * `leftButton`, `rightButton`, `middleButton` and so on. + * @property {any} button + * @default + */ + this.button = null; + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * @property {Phaser.DeviceButton} leftButton + * @default + */ + this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} middleButton + * @default + */ + this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} rightButton + * @default + */ + this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} backButton + * @default + */ + this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} forwardButton + * @default + */ + this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON); + + /** + * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} eraserButton + * @default + */ + this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON); + + /** + * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event. + * @private + * @default + */ + this._holdSent = false; + + /** + * @property {array} _history - Local private variable storing the short-term history of pointer movements. + * @private + */ + this._history = []; + + /** + * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur. + * @private + */ + this._nextDrop = 0; + + /** + * @property {boolean} _stateReset - Monitor events outside of a state reset loop. + * @private + */ + this._stateReset = false; + + /** + * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false. + */ + this.withinGame = false; + + /** + * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientX = -1; + + /** + * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientY = -1; + + /** + * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document. + */ + this.pageX = -1; + + /** + * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document. + */ + this.pageY = -1; + + /** + * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen. + */ + this.screenX = -1; + + /** + * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen. + */ + this.screenY = -1; + + /** + * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementX = 0; + + /** + * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementY = 0; + + /** + * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementX = 0; + + /** + * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementY = 0; + + /** + * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.x = -1; + + /** + * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.y = -1; + + /** + * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false. + */ + this.isMouse = (id === 0); + + /** + * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. + * @property {boolean} isDown + * @default + */ + this.isDown = false; + + /** + * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. + * @property {boolean} isUp + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen. + * @default + */ + this.timeUp = 0; + + /** + * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked. + * @default + */ + this.previousTapTime = 0; + + /** + * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen. + * @default + */ + this.totalTouches = 0; + + /** + * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event. + * @default + */ + this.msSinceLastClick = Number.MAX_VALUE; + + /** + * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging. + * @default + */ + this.targetObject = null; + + /** + * This array is erased and re-populated every time this Pointer is updated. It contains references to all + * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be + * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over + * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset + * every frame. + * @property {array} interactiveCandidates + * @default + */ + this.interactiveCandidates = []; + + /** + * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active. + * @default + */ + this.active = false; + + /** + * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. + * @default + */ + this.dirty = false; + + /** + * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display. + */ + this.position = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. + */ + this.positionDown = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released. + */ + this.positionUp = new Phaser.Point(); + + /** + * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. + * The Circle size is 44px (Apples recommended "finger tip" size). + * @property {Phaser.Circle} circle + */ + this.circle = new Phaser.Circle(0, 0, 44); + + /** + * Click trampolines associated with this pointer. See `addClickTrampoline`. + * @property {object[]|null} _clickTrampolines + * @private + */ + this._clickTrampolines = null; + + /** + * When the Pointer has click trampolines the last target object is stored here + * so it can be used to check for validity of the trampoline in a post-Up/'stop'. + * @property {object} _trampolineTargetObject + * @private + */ + this._trampolineTargetObject = null; + +}; + +/** +* No buttons at all. +* @constant +* @type {number} +*/ +Phaser.Pointer.NO_BUTTON = 0; + +/** +* The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. +* @constant +* @type {number} +*/ +Phaser.Pointer.LEFT_BUTTON = 1; + +/** +* The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. +* @constant +* @type {number} +*/ +Phaser.Pointer.RIGHT_BUTTON = 2; + +/** +* The Middle Mouse button. +* @constant +* @type {number} +*/ +Phaser.Pointer.MIDDLE_BUTTON = 4; + +/** +* The X1 button. This is typically the mouse Back button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.BACK_BUTTON = 8; + +/** +* The X2 button. This is typically the mouse Forward button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.FORWARD_BUTTON = 16; + +/** +* The Eraser pen button on PointerEvent supported devices only. +* @constant +* @type {number} +*/ +Phaser.Pointer.ERASER_BUTTON = 32; + +Phaser.Pointer.prototype = { + + /** + * Resets the states of all the button booleans. + * + * @method Phaser.Pointer#resetButtons + * @protected + */ + resetButtons: function () { + + this.isDown = false; + this.isUp = true; + + if (this.isMouse) + { + this.leftButton.reset(); + this.middleButton.reset(); + this.rightButton.reset(); + this.backButton.reset(); + this.forwardButton.reset(); + this.eraserButton.reset(); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsDown + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsDown: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.start(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.start(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.start(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.start(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.start(event); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsUp + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUp: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.stop(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.stop(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.stop(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.stop(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.stop(event); + } + + }, + + /** + * Called by updateButtons. + * + * @method Phaser.Pointer#processButtonsUpDown + * @private + * @param {integer} buttons - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons MouseEvent#buttons} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUpDown: function (buttons, event) { + + var down = (event.type.toLowerCase().substr(-4) === 'down'); + var move = (event.type.toLowerCase().substr(-4) === 'move'); + + if (buttons !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && buttons === 1 && event.ctrlKey) + { + buttons = 2; + } + + // Note: These are bitwise checks, not booleans + this.leftButton.startStop(Phaser.Pointer.LEFT_BUTTON & buttons, event); + this.rightButton.startStop(Phaser.Pointer.RIGHT_BUTTON & buttons, event); + this.middleButton.startStop(Phaser.Pointer.MIDDLE_BUTTON & buttons, event); + this.backButton.startStop(Phaser.Pointer.BACK_BUTTON & buttons, event); + this.forwardButton.startStop(Phaser.Pointer.FORWARD_BUTTON & buttons, event); + this.eraserButton.startStop(Phaser.Pointer.ERASER_BUTTON & buttons, event); + } + else + { + // No buttons property (like Safari on OSX when using a trackpad) + // Attempt to use event.button property or fallback to default + if (event.button !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && event.ctrlKey && event.button === 0) + { + this.rightButton.start(event); + } + else + { + if (down) + { + this.processButtonsDown(event.button, event); + } + else if (!move) + { + this.processButtonsUp(event.button, event); + } + } + } + else + { + if (down) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (event.ctrlKey) + { + this.rightButton.start(event); + } + else + { + this.leftButton.start(event); + } + } + else + { + this.leftButton.stop(event); + this.rightButton.stop(event); + } + } + } + + }, + + /** + * Called when the event.buttons property changes from zero. + * Contains a button bitmask. + * + * @method Phaser.Pointer#updateButtons + * @protected + * @param {MouseEvent} event - The DOM event. + */ + updateButtons: function (event) { + + this.button = event.button; + this.processButtonsUpDown(event.buttons, event); + + this.isUp = true; + this.isDown = false; + + if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown) + { + this.isUp = false; + this.isDown = true; + } + + }, + + /** + * Called when the Pointer is pressed onto the touchscreen. + * @method Phaser.Pointer#start + * @param {any} event - The DOM event from the browser. + */ + start: function (event) { + + var input = this.game.input; + + if (event['pointerId']) + { + this.pointerId = event.pointerId; + } + + this.identifier = event.identifier; + this.target = event.target; + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = true; + this.isUp = false; + } + + this.active = true; + this.withinGame = true; + this.dirty = false; + + this._history = []; + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + // Work out how long it has been since the last click + this.msSinceLastClick = this.game.time.time - this.timeDown; + this.timeDown = this.game.time.time; + this._holdSent = false; + + // This sets the x/y and other local values + this.move(event, true); + + // x and y are the old values here? + this.positionDown.setTo(this.x, this.y); + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.x = this.x; + input.y = this.y; + input.position.setTo(this.x, this.y); + input.onDown.dispatch(this, event); + input.resetSpeed(this.x, this.y); + } + + this._stateReset = false; + + this.totalTouches++; + + if (this.targetObject !== null) + { + this.targetObject._touchedHandler(this); + } + + return this; + + }, + + /** + * Called by the Input Manager. + * @method Phaser.Pointer#update + */ + update: function () { + + var input = this.game.input; + + if (this.active) + { + // Force a check? + if (this.dirty) + { + if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(false); + } + + this.dirty = false; + } + + if (this._holdSent === false && this.duration >= input.holdRate) + { + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onHold.dispatch(this); + } + + this._holdSent = true; + } + + // Update the droppings history + if (input.recordPointerHistory && this.game.time.time >= this._nextDrop) + { + this._nextDrop = this.game.time.time + input.recordRate; + + this._history.push({ + x: this.position.x, + y: this.position.y + }); + + if (this._history.length > input.recordLimit) + { + this._history.shift(); + } + } + } + + }, + + /** + * Called when the Pointer is moved. + * + * @method Phaser.Pointer#move + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + * @param {boolean} [fromClick=false] - Was this called from the click event? + */ + move: function (event, fromClick) { + + var input = this.game.input; + + if (input.pollLocked) + { + return; + } + + if (fromClick === undefined) { fromClick = false; } + + if (event.button !== undefined) + { + this.button = event.button; + } + + if (this.isMouse) + { + this.updateButtons(event); + } + + 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 && 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.scale.offset.x) * input.scale.x; + this.y = (this.pageY - this.game.scale.offset.y) * input.scale.y; + + this.position.setTo(this.x, this.y); + this.circle.x = this.x; + this.circle.y = this.y; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.activePointer = this; + input.x = this.x; + input.y = this.y; + input.position.setTo(input.x, input.y); + input.circle.x = input.x; + input.circle.y = input.y; + } + + this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY); + + var i = input.moveCallbacks.length; + + while (i--) + { + input.moveCallbacks[i].callback.call(input.moveCallbacks[i].context, this, this.x, this.y, fromClick); + } + + // Easy out if we're dragging something and it still exists + if (this.targetObject !== null && (!this.game.paused || this.targetObject.noPause) && this.targetObject.isDragged === true) + { + if (this.targetObject.update(this) === false) + { + this.targetObject = null; + } + } + else if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(fromClick); + } + + return this; + + }, + + /** + * Process all interactive objects to find out which ones were updated in the recent Pointer move. + * + * @method Phaser.Pointer#processInteractiveObjects + * @protected + * @param {boolean} [fromClick=false] - Was this called from the click event? + * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. + */ + processInteractiveObjects: function (fromClick) { + + // Work out which object is on the top + var highestRenderOrderID = 0; + var highestInputPriorityID = -1; + var candidateTarget = null; + + // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID + // We know they'll be valid for input detection but not which is the top just yet + + var currentNode = this.game.input.interactiveItems.first; + + this.interactiveCandidates = []; + + while (currentNode) + { + // Reset checked status + currentNode.checked = false; + + if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false) && (!this.game.paused || currentNode.sprite.noPause)) + { + // Flag it as checked so we don't re-scan it on the next phase + currentNode.checked = true; + + if ((fromClick && currentNode.checkPointerDown(this, true)) || + (!fromClick && currentNode.checkPointerOver(this, true))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID + // because if their ID is lower anyway then we can just automatically discount them + // (A node that was previously checked did not request a pixel-perfect check.) + + currentNode = this.game.input.interactiveItems.first; + + while (currentNode) + { + if (!currentNode.checked && + currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true)) + { + if ((fromClick && currentNode.checkPointerDown(this, false)) || + (!fromClick && currentNode.checkPointerOver(this, false))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + if (this.game.input.customCandidateHandler) + { + candidateTarget = this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext, this, this.interactiveCandidates, candidateTarget); + } + + this.swapTarget(candidateTarget, false); + + return (this.targetObject !== null); + + }, + + /** + * This will change the `Pointer.targetObject` object to be the one provided. + * + * This allows you to have fine-grained control over which object the Pointer is targeting. + * + * Note that even if you set a new Target here, it is still able to be replaced by any other valid + * target during the next Pointer update. + * + * @method Phaser.Pointer#swapTarget + * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. + * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. + */ + swapTarget: function (newTarget, silent) { + + if (silent === undefined) { silent = false; } + + // Now we know the top-most item (if any) we can process it + if (newTarget === null) + { + // The pointer isn't currently over anything, check if we've got a lingering previous target + if (this.targetObject) + { + this.targetObject._pointerOutHandler(this, silent); + this.targetObject = null; + } + } + else + { + if (this.targetObject === null) + { + // And now set the new one + this.targetObject = newTarget; + newTarget._pointerOverHandler(this, silent); + } + else + { + // We've got a target from the last update + if (this.targetObject === newTarget) + { + // Same target as before, so update it + if (newTarget.update(this) === false) + { + this.targetObject = null; + } + } + else + { + // The target has changed, so tell the old one we've left it + this.targetObject._pointerOutHandler(this, silent); + + // And now set the new one + this.targetObject = newTarget; + this.targetObject._pointerOverHandler(this, silent); + } + } + } + + }, + + /** + * Called when the Pointer leaves the target area. + * + * @method Phaser.Pointer#leave + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + leave: function (event) { + + this.withinGame = false; + this.move(event, false); + + }, + + /** + * Called when the Pointer leaves the touchscreen. + * + * @method Phaser.Pointer#stop + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + stop: function (event) { + + var input = this.game.input; + + if (this._stateReset && this.withinGame) + { + event.preventDefault(); + return; + } + + this.timeUp = this.game.time.time; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onUp.dispatch(this, event); + + // Was it a tap? + if (this.duration >= 0 && this.duration <= input.tapRate) + { + // Was it a double-tap? + if (this.timeUp - this.previousTapTime < input.doubleTapRate) + { + // Yes, let's dispatch the signal then with the 2nd parameter set to true + input.onTap.dispatch(this, true); + } + else + { + // Wasn't a double-tap, so dispatch a single tap signal + input.onTap.dispatch(this, false); + } + + this.previousTapTime = this.timeUp; + } + } + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = false; + this.isUp = true; + } + + // Mouse is always active + if (this.id > 0) + { + this.active = false; + } + + this.withinGame = this.game.scale.bounds.contains(event.pageX, event.pageY); + this.pointerId = null; + this.identifier = null; + + this.positionUp.setTo(this.x, this.y); + + if (this.isMouse === false) + { + input.currentPointers--; + } + + input.interactiveItems.callAll('_releasedHandler', this); + + if (this._clickTrampolines) + { + this._trampolineTargetObject = this.targetObject; + } + + this.targetObject = null; + + return this; + + }, + + /** + * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. + * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. + * @method Phaser.Pointer#justPressed + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate. + * @return {boolean} true if the Pointer was pressed down within the duration given. + */ + justPressed: function (duration) { + + duration = duration || this.game.input.justPressedRate; + + return (this.isDown === true && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. + * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. + * @method Phaser.Pointer#justReleased + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate. + * @return {boolean} true if the Pointer was released within the duration given. + */ + justReleased: function (duration) { + + duration = duration || this.game.input.justReleasedRate; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Add a click trampoline to this pointer. + * + * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily + * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen + * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. + * + * This is used internally by the ScaleManager; click trampoline usage is uncommon. + * Click trampolines can only be added to pointers that are currently down. + * + * @method Phaser.Pointer#addClickTrampoline + * @protected + * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer. + * @param {function} callback - Callback to run/trampoline. + * @param {object} callbackContext - Context of the callback. + * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array. + */ + addClickTrampoline: function (name, callback, callbackContext, callbackArgs) { + + if (!this.isDown) + { + return; + } + + var trampolines = (this._clickTrampolines = this._clickTrampolines || []); + + for (var i = 0; i < trampolines.length; i++) + { + if (trampolines[i].name === name) + { + trampolines.splice(i, 1); + break; + } + } + + trampolines.push({ + name: name, + targetObject: this.targetObject, + callback: callback, + callbackContext: callbackContext, + callbackArgs: callbackArgs + }); + + }, + + /** + * Fire all click trampolines for which the pointers are still referring to the registered object. + * @method Phaser.Pointer#processClickTrampolines + * @private + */ + processClickTrampolines: function () { + + var trampolines = this._clickTrampolines; + + if (!trampolines) + { + return; + } + + for (var i = 0; i < trampolines.length; i++) + { + var trampoline = trampolines[i]; + + if (trampoline.targetObject === this._trampolineTargetObject) + { + trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs); + } + } + + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + }, + + /** + * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. + * @method Phaser.Pointer#reset + */ + reset: function () { + + if (this.isMouse === false) + { + this.active = false; + } + + this.pointerId = null; + this.identifier = null; + this.dirty = false; + this.totalTouches = 0; + this._holdSent = false; + this._history.length = 0; + this._stateReset = true; + + this.resetButtons(); + + if (this.targetObject) + { + this.targetObject._releasedHandler(this); + } + + this.targetObject = null; + + }, + + /** + * Resets the movementX and movementY properties. Use in your update handler after retrieving the values. + * @method Phaser.Pointer#resetMovement + */ + resetMovement: function() { + + this.movementX = 0; + this.movementY = 0; + + } + +}; + +Phaser.Pointer.prototype.constructor = Phaser.Pointer; + +/** +* How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. +* If not currently down it returns -1. +* If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. +* +* @name Phaser.Pointer#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* Gets the X value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldX +* @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldX", { + + get: function () { + + return this.game.world.camera.x + this.x; + + } + +}); + +/** +* Gets the Y value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldY +* @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldY", { + + get: function () { + + return this.game.world.camera.y + this.y; + + } + +}); + +/** +* Enumeration categorizing operational modes of pointers. +* +* PointerType values represent valid bitmasks. +* For example, a value representing both Mouse and Touch devices +* can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. +* +* Values may be added for future mode categorizations. +* @class Phaser.PointerMode +*/ +Phaser.PointerMode = { + + /** + * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. + * + * It has the property that a cursor is passively moved without activating the input. + * This currently corresponds with {@link Phaser.Pointer#isMouse} property. + * @constant + */ + CURSOR: 1 << 0, + + /** + * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. + * @constant + */ + CONTACT: 1 << 1 + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. +* +* @class Phaser.Touch +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Touch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * Touch events will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} touchStartCallback - A callback that can be fired on a touchStart event. + */ + this.touchStartCallback = null; + + /** + * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event. + */ + this.touchMoveCallback = null; + + /** + * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event. + */ + this.touchEndCallback = null; + + /** + * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event. + */ + this.touchEnterCallback = null; + + /** + * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event. + */ + this.touchLeaveCallback = null; + + /** + * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event. + */ + this.touchCancelCallback = null; + + /** + * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it. + * @default + */ + this.preventDefault = true; + + /** + * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received. + * @default + */ + this.event = null; + + /** + * @property {function} _onTouchStart - Internal event handler reference. + * @private + */ + this._onTouchStart = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + + /** + * @property {function} _onTouchEnd - Internal event handler reference. + * @private + */ + this._onTouchEnd = null; + + /** + * @property {function} _onTouchEnter - Internal event handler reference. + * @private + */ + this._onTouchEnter = null; + + /** + * @property {function} _onTouchLeave - Internal event handler reference. + * @private + */ + this._onTouchLeave = null; + + /** + * @property {function} _onTouchCancel - Internal event handler reference. + * @private + */ + this._onTouchCancel = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + +}; + +Phaser.Touch.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Touch#start + */ + start: function () { + + if (this._onTouchStart !== null) + { + // Avoid setting multiple listeners + 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('touchcancel', this._onTouchCancel, false); + + if (!this.game.device.cocoonJS) + { + this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false); + this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false); + } + } + + }, + + /** + * Consumes all touchmove events on the document (only enable this if you know you need it!). + * @method Phaser.Touch#consumeTouchMove + */ + consumeDocumentTouches: function () { + + this._documentTouchMove = function (event) { + event.preventDefault(); + }; + + document.addEventListener('touchmove', this._documentTouchMove, false); + + }, + + /** + * The internal method that handles the touchstart event from the browser. + * @method Phaser.Touch#onTouchStart + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchStart: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.touchStartCallback) + { + this.touchStartCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.startPointer(event.changedTouches[i]); + } + + }, + + /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. + * @method Phaser.Touch#onTouchCancel + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchCancel: function (event) { + + this.event = event; + + if (this.touchCancelCallback) + { + this.touchCancelCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchEnter + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnter: function (event) { + + this.event = event; + + if (this.touchEnterCallback) + { + this.touchEnterCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchLeave + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchLeave: function (event) { + + this.event = event; + + if (this.touchLeaveCallback) + { + this.touchLeaveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * The handler for the touchmove events. + * @method Phaser.Touch#onTouchMove + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchMove: function (event) { + + this.event = event; + + if (this.touchMoveCallback) + { + this.touchMoveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.updatePointer(event.changedTouches[i]); + } + + }, + + /** + * The handler for the touchend events. + * @method Phaser.Touch#onTouchEnd + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnd: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.touchEndCallback) + { + this.touchEndCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.Touch#stop + */ + stop: function () { + + if (this.game.device.touch) + { + this.game.canvas.removeEventListener('touchstart', this._onTouchStart); + this.game.canvas.removeEventListener('touchmove', this._onTouchMove); + this.game.canvas.removeEventListener('touchend', this._onTouchEnd); + this.game.canvas.removeEventListener('touchenter', this._onTouchEnter); + this.game.canvas.removeEventListener('touchleave', this._onTouchLeave); + this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel); + } + + } + +}; + +Phaser.Touch.prototype.constructor = Phaser.Touch; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. +* +* @class Phaser.InputHandler +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. +*/ +Phaser.InputHandler = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = sprite.game; + + /** + * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity. + * @default + */ + this.enabled = false; + + /** + * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks. + * @protected + */ + this.checked = false; + + /** + * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have + * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can + * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. + * @property {number} priorityID + * @default + */ + this.priorityID = 0; + + /** + * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. + * @default + */ + this.useHandCursor = false; + + /** + * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor? + * @private + */ + this._setHandCursor = false; + + /** + * @property {boolean} isDragged - true if the Sprite is being currently dragged. + * @default + */ + this.isDragged = false; + + /** + * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally. + * @default + */ + this.allowHorizontalDrag = true; + + /** + * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically. + * @default + */ + this.allowVerticalDrag = true; + + /** + * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. + * @default + */ + this.bringToTop = false; + + /** + * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset. + * @default + */ + this.snapOffset = null; + + /** + * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. + * @default + */ + this.snapOnDrag = false; + + /** + * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release. + * @default + */ + this.snapOnRelease = false; + + /** + * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid. + * @default + */ + this.snapX = 0; + + /** + * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid. + * @default + */ + this.snapY = 0; + + /** + * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid. + * @default + */ + this.snapOffsetX = 0; + + /** + * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid.. + * @default + */ + this.snapOffsetY = 0; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. + * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over. + * @default + */ + this.pixelPerfectOver = false; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive so only enable if you really need it. + * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite. + * @default + */ + this.pixelPerfectClick = false; + + /** + * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. + * @default + */ + this.pixelPerfectAlpha = 255; + + /** + * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no + * @default + */ + this.draggable = false; + + /** + * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag. + * @default + */ + this.boundsRect = null; + + /** + * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. + * @default + */ + this.boundsSprite = null; + + /** + * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. + */ + this.scaleLayer = false; + + /** + * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from. + */ + this.dragOffset = new Phaser.Point(); + + /** + * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? + */ + this.dragFromCenter = false; + + /** + * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. + */ + this.dragStopBlocksInputUp = false; + + /** + * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. + */ + this.dragStartPoint = new Phaser.Point(); + + /** + * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. + */ + this.dragDistanceThreshold = 0; + + /** + * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. + */ + this.dragTimeThreshold = 0; + + /** + * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. + */ + this.downPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. + */ + this.snapPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} _dragPoint - Internal cache var. + * @private + */ + this._dragPoint = new Phaser.Point(); + + /** + * @property {boolean} _dragPhase - Internal cache var. + * @private + */ + this._dragPhase = false; + + /** + * @property {boolean} _pendingDrag - Internal cache var. + * @private + */ + this._pendingDrag = false; + + /** + * @property {boolean} _dragTimePass - Internal cache var. + * @private + */ + this._dragTimePass = false; + + /** + * @property {boolean} _dragDistancePass - Internal cache var. + * @private + */ + this._dragDistancePass = false; + + /** + * @property {boolean} _wasEnabled - Internal cache var. + * @private + */ + this._wasEnabled = false; + + /** + * @property {Phaser.Point} _tempPoint - Internal cache var. + * @private + */ + this._tempPoint = new Phaser.Point(); + + /** + * @property {array} _pointerData - Internal cache var. + * @private + */ + this._pointerData = []; + + this._pointerData.push({ + id: 0, + x: 0, + y: 0, + camX: 0, + camY: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }); + +}; + +Phaser.InputHandler.prototype = { + + /** + * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. + * + * @method Phaser.InputHandler#start + * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. + * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) + * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound. + */ + start: function (priority, useHandCursor) { + + priority = priority || 0; + if (useHandCursor === undefined) { useHandCursor = false; } + + // Turning on + if (this.enabled === false) + { + // Register, etc + this.game.input.interactiveItems.add(this); + this.useHandCursor = useHandCursor; + this.priorityID = priority; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + + this.snapOffset = new Phaser.Point(); + this.enabled = true; + this._wasEnabled = true; + + } + + this.sprite.events.onAddedToGroup.add(this.addedToGroup, this); + this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this); + + return this.sprite; + + }, + + /** + * Handles when the parent Sprite is added to a new Group. + * + * @method Phaser.InputHandler#addedToGroup + * @private + */ + addedToGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this._wasEnabled && !this.enabled) + { + this.start(); + } + + }, + + /** + * Handles when the parent Sprite is removed from a Group. + * + * @method Phaser.InputHandler#removedFromGroup + * @private + */ + removedFromGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this.enabled) + { + this._wasEnabled = true; + this.stop(); + } + else + { + this._wasEnabled = false; + } + + }, + + /** + * Resets the Input Handler and disables it. + * @method Phaser.InputHandler#reset + */ + reset: function () { + + this.enabled = false; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + }, + + /** + * Stops the Input Handler from running. + * @method Phaser.InputHandler#stop + */ + stop: function () { + + // Turning off + if (this.enabled === false) + { + return; + } + else + { + // De-register, etc + this.enabled = false; + this.game.input.interactiveItems.remove(this); + } + + }, + + /** + * Clean up memory. + * @method Phaser.InputHandler#destroy + */ + destroy: function () { + + if (this.sprite) + { + if (this._setHandCursor) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + this.enabled = false; + + this.game.input.interactiveItems.remove(this); + + this._pointerData.length = 0; + this.boundsRect = null; + this.boundsSprite = null; + this.sprite = null; + } + + }, + + /** + * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. + * This is called by Phaser.Pointer and shouldn't typically be called directly. + * + * @method Phaser.InputHandler#validForInput + * @protected + * @param {number} highestID - The highest ID currently processed by the Pointer. + * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer. + * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? + * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection. + */ + validForInput: function (highestID, highestRenderID, includePixelPerfect) { + + if (includePixelPerfect === undefined) { includePixelPerfect = true; } + + if (!this.enabled || + this.sprite.scale.x === 0 || + this.sprite.scale.y === 0 || + this.priorityID < this.game.input.minPriorityID || + (this.sprite.parent && this.sprite.parent.ignoreChildInput)) + { + return false; + } + + // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it + if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver)) + { + return false; + } + + if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID > highestRenderID)) + { + return true; + } + + return false; + + }, + + /** + * Is this object using pixel perfect checking? + * + * @method Phaser.InputHandler#isPixelPerfect + * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. + */ + isPixelPerfect: function () { + + return (this.pixelPerfectClick || this.pixelPerfectOver); + + }, + + /** + * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerX + * @param {integer} [pointerId=0] + * @return {number} The x coordinate of the Input pointer. + */ + pointerX: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].x; + + }, + + /** + * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerY + * @param {integer} [pointerId=0] + * @return {number} The y coordinate of the Input pointer. + */ + pointerY: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].y; + + }, + + /** + * If the Pointer is down this returns true. + * This *only* checks if the Pointer is down, not if it's down over any specific Sprite. + * + * @method Phaser.InputHandler#pointerDown + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is down, otherwise false. + */ + pointerDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDown; + + }, + + /** + * If the Pointer is up this returns true. + * This *only* checks if the Pointer is up, not if it's up over any specific Sprite. + * + * @method Phaser.InputHandler#pointerUp + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is up, otherwise false. + */ + pointerUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isUp; + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeDown + * @param {integer} [pointerId=(check all)] + * @return {number} + */ + pointerTimeDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeDown; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeUp + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeUp; + + }, + + /** + * Is the Pointer over this Sprite? + * + * @method Phaser.InputHandler#pointerOver + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object. + */ + pointerOver: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOver) + { + return true; + } + } + + return false; + } + else + { + return this._pointerData[pointerId].isOver; + } + + }, + + /** + * Is the Pointer outside of this Sprite? + * + * @method Phaser.InputHandler#pointerOut + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. + */ + pointerOut: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOut) + { + return true; + } + } + } + else + { + return this._pointerData[pointerId].isOut; + } + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOver + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOver: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOver; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOut + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOut: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOut; + + }, + + /** + * Is this sprite being dragged by the mouse or not? + * + * @method Phaser.InputHandler#pointerDragged + * @param {integer} [pointerId=0] + * @return {boolean} True if the pointer is dragging an object, otherwise false. + */ + pointerDragged: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDragged; + + }, + + /** + * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerDown + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} True if the pointer is down, otherwise false. + */ + checkPointerDown: function (pointer, fastTest) { + + if (!pointer.isDown || + !this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectClick) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Checks if the given pointer is over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerOver + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} + */ + checkPointerOver: function (pointer, fastTest) { + + if (!this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectOver) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. + * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. + * + * @method Phaser.InputHandler#checkPixel + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters. + * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha + */ + checkPixel: function (x, y, pointer) { + + // Grab a pixel from our image into the hitCanvas and then test it + if (this.sprite.texture.baseTexture.source) + { + if (x === null && y === null) + { + // Use the pointer parameter + this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint); + + var x = this._tempPoint.x; + var y = this._tempPoint.y; + } + + if (this.sprite.anchor.x !== 0) + { + x -= -this.sprite.texture.frame.width * this.sprite.anchor.x; + } + + if (this.sprite.anchor.y !== 0) + { + y -= -this.sprite.texture.frame.height * this.sprite.anchor.y; + } + + x += this.sprite.texture.frame.x; + y += this.sprite.texture.frame.y; + + if (this.sprite.texture.trim) + { + x -= this.sprite.texture.trim.x; + y -= this.sprite.texture.trim.y; + + // If the coordinates are outside the trim area we return false immediately, to save doing a draw call + if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom) + { + this._dx = x; + this._dy = y; + return false; + } + } + + this._dx = x; + this._dy = y; + + this.game.input.hitContext.clearRect(0, 0, 1, 1); + this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1); + + if (rgb.data[3] >= this.pixelPerfectAlpha) + { + return true; + } + } + + return false; + + }, + + /** + * Internal Update method. This is called automatically and handles the Pointer + * and drag update loops. + * + * @method Phaser.InputHandler#update + * @protected + * @param {Phaser.Pointer} pointer + * @return {boolean} True if the pointer is still active, otherwise false. + */ + update: function (pointer) { + + if (this.sprite === null || this.sprite.parent === undefined) + { + // Abort. We've been destroyed. + return; + } + + if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible) + { + this._pointerOutHandler(pointer); + return false; + } + + if (this._pendingDrag) + { + if (!this._dragDistancePass) + { + this._dragDistancePass = (Phaser.Math.distance(pointer.x, pointer.y, this.downPoint.x, this.downPoint.y) >= this.dragDistanceThreshold); + } + + if (this._dragDistancePass && this._dragTimePass) + { + this.startDrag(pointer); + } + + return true; + } + else if (this.draggable && this._draggedPointerID === pointer.id) + { + return this.updateDrag(pointer, false); + } + else if (this._pointerData[pointer.id].isOver) + { + 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; + } + } + }, + + /** + * Internal method handling the pointer over event. + * + * @method Phaser.InputHandler#_pointerOverHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOverHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (data.isOver === false || pointer.dirty) + { + var sendEvent = (data.isOver === false); + + data.isOver = true; + data.isOut = false; + data.timeOver = this.game.time.time; + data.x = pointer.x - this.sprite.x; + data.y = pointer.y - this.sprite.y; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = "pointer"; + this._setHandCursor = true; + } + + if (!silent && sendEvent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOver$dispatch(this.sprite, pointer); + } + + if (this.sprite.parent && this.sprite.parent.onChildInputOver) + { + this.sprite.parent.onChildInputOver.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the pointer out event. + * + * @method Phaser.InputHandler#_pointerOutHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOutHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + data.isOver = false; + data.isOut = true; + data.timeOut = this.game.time.time; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + if (!silent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOut$dispatch(this.sprite, pointer); + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputOut) + { + this.sprite.parent.onChildInputOut.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the touched / clicked event. + * + * @method Phaser.InputHandler#_touchedHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + */ + _touchedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (!data.isDown && data.isOver) + { + if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer)) + { + return; + } + + data.isDown = true; + data.isUp = false; + data.timeDown = this.game.time.time; + + this.downPoint.set(pointer.x, pointer.y); + + // It's possible the onInputDown event creates a new Sprite that is on-top of this one, so we ought to force a Pointer update + pointer.dirty = true; + + if (this.sprite && this.sprite.events) + { + this.sprite.events.onInputDown$dispatch(this.sprite, pointer); + + // The event above might have destroyed this sprite. + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputDown) + { + this.sprite.parent.onChildInputDown.dispatch(this.sprite, pointer); + } + + // The events might have destroyed this sprite. + if (this.sprite === null) + { + return; + } + } + + // Start drag + if (this.draggable && this.isDragged === false) + { + if (this.dragTimeThreshold === 0 && this.dragDistanceThreshold === 0) + { + this.startDrag(pointer); + } + else + { + this._pendingDrag = true; + + this._dragDistancePass = (this.dragDistanceThreshold === 0); + + if (this.dragTimeThreshold > 0) + { + this._dragTimePass = false; + this.game.time.events.add(this.dragTimeThreshold, this.dragTimeElapsed, this, pointer); + } + else + { + this._dragTimePass = true; + } + } + } + + if (this.bringToTop) + { + this.sprite.bringToTop(); + } + } + + }, + + /** + * Internal method handling the drag threshold timer. + * + * @method Phaser.InputHandler#dragTimeElapsed + * @private + * @param {Phaser.Pointer} pointer + */ + dragTimeElapsed: function (pointer) { + + this._dragTimePass = true; + + if (this._pendingDrag && this.sprite) + { + if (this._dragDistancePass) + { + this.startDrag(pointer); + } + } + + }, + + /** + * Internal method handling the pointer released event. + * @method Phaser.InputHandler#_releasedHandler + * @private + * @param {Phaser.Pointer} pointer + */ + _releasedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + // If was previously touched by this Pointer, check if still is AND still over this item + if (data.isDown && pointer.isUp) + { + data.isDown = false; + data.isUp = true; + data.timeUp = this.game.time.time; + data.downDuration = data.timeUp - data.timeDown; + + // Only release the InputUp signal if the pointer is still over this sprite + var isOver = this.checkPointerOver(pointer); + + if (this.sprite && this.sprite.events) + { + if (!this.dragStopBlocksInputUp || + this.dragStopBlocksInputUp && !(this.draggable && this.isDragged && this._draggedPointerID === pointer.id)) + { + this.sprite.events.onInputUp$dispatch(this.sprite, pointer, isOver); + } + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputUp) + { + this.sprite.parent.onChildInputUp.dispatch(this.sprite, pointer, isOver); + } + + // The onInputUp event may have changed the sprite so that checkPointerOver is no longer true, so update it. + if (isOver) + { + isOver = this.checkPointerOver(pointer); + } + } + + data.isOver = isOver; + + if (!isOver && this.useHandCursor) + { + this.game.canvas.style.cursor = "default"; + this._setHandCursor = false; + } + + // It's possible the onInputUp event created a new Sprite that is on-top of this one, so force a Pointer update + pointer.dirty = true; + + this._pendingDrag = false; + + // Stop drag + if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id) + { + this.stopDrag(pointer); + } + } + + }, + + /** + * Called as a Pointer actively drags this Game Object. + * + * @method Phaser.InputHandler#updateDrag + * @private + * @param {Phaser.Pointer} pointer - The Pointer causing the drag update. + * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started. + * @return {boolean} + */ + updateDrag: function (pointer, fromStart) { + + if (fromStart === undefined) { fromStart = false; } + + if (pointer.isUp) + { + this.stopDrag(pointer); + return false; + } + + var pointerLocalCoord = this.globalToLocal(pointer); + + if (this.sprite.fixedToCamera) + { + var px = this.game.camera.scale.x * pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = this.game.camera.scale.y * pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + else + { + var px = pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + + if (this.sprite.fixedToCamera) + { + if (this.allowHorizontalDrag) + { + this.sprite.cameraOffset.x = px - this.game.camera.x; + } + + if (this.allowVerticalDrag) + { + this.sprite.cameraOffset.y = py - this.game.camera.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); + this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y); + } + } + else + { + var cx = this.game.camera.x - this._pointerData[pointer.id].camX; + var cy = this.game.camera.y - this._pointerData[pointer.id].camY; + + if (this.allowHorizontalDrag) + { + this.sprite.x = px + cx; + } + + if (this.allowVerticalDrag) + { + this.sprite.y = py + cy; + } + + 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); + this.snapPoint.set(this.sprite.x, this.sprite.y); + } + } + + this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint, fromStart); + + return true; + + }, + + /** + * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOver + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justOver: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOut + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justOut: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay)); + + }, + + /** + * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justPressed + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justPressed: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justReleased + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justReleased: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay)); + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#overDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. + */ + overDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isOver) + { + return this.game.time.time - this._pointerData[pointerId].timeOver; + } + + return -1; + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#downDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. + */ + downDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isDown) + { + return this.game.time.time - this._pointerData[pointerId].timeDown; + } + + return -1; + + }, + + /** + * Allow this Sprite to be dragged by any valid pointer. + * + * When the drag begins the Sprite.events.onDragStart event will be dispatched. + * + * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. + * + * You can control the thresholds over when a drag starts via the properties: + * + * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move + * before the drag will start. + * + * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on + * the Sprite before the drag will start. + * + * You can set either (or both) of these properties after enabling a Sprite for drag. + * + * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually + * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`. + * + * @method Phaser.InputHandler#enableDrag + * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. + * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group. + * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. + * @param {integer} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. + * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. + * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. + */ + enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) { + + if (lockCenter === undefined) { lockCenter = false; } + if (bringToTop === undefined) { bringToTop = false; } + if (pixelPerfect === undefined) { pixelPerfect = false; } + if (alphaThreshold === undefined) { alphaThreshold = 255; } + if (boundsRect === undefined) { boundsRect = null; } + if (boundsSprite === undefined) { boundsSprite = null; } + + this._dragPoint = new Phaser.Point(); + this.draggable = true; + this.bringToTop = bringToTop; + this.dragOffset = new Phaser.Point(); + this.dragFromCenter = lockCenter; + + this.pixelPerfectClick = pixelPerfect; + this.pixelPerfectAlpha = alphaThreshold; + + if (boundsRect) + { + this.boundsRect = boundsRect; + } + + if (boundsSprite) + { + this.boundsSprite = boundsSprite; + } + + }, + + /** + * Stops this sprite from being able to be dragged. + * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. + * + * @method Phaser.InputHandler#disableDrag + */ + disableDrag: function () { + + if (this._pointerData) + { + for (var i = 0; i < 10; i++) + { + this._pointerData[i].isDragged = false; + } + } + + this.draggable = false; + this.isDragged = false; + this._draggedPointerID = -1; + this._pendingDrag = false; + + }, + + /** + * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#startDrag + * @param {Phaser.Pointer} pointer + */ + startDrag: function (pointer) { + + var x = this.sprite.x; + var y = this.sprite.y; + var pointerLocalCoord = this.globalToLocal(pointer); + + this.isDragged = true; + this._draggedPointerID = pointer.id; + + this._pointerData[pointer.id].camX = this.game.camera.x; + this._pointerData[pointer.id].camY = this.game.camera.y; + + this._pointerData[pointer.id].isDragged = true; + + if (this.sprite.fixedToCamera) + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.cameraOffset.x = pointerLocalCoord.x + (this.sprite.cameraOffset.x - boundsCenterLocalCoord.x); + this.sprite.cameraOffset.y = pointerLocalCoord.y + (this.sprite.cameraOffset.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y); + } + else + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.x = pointerLocalCoord.x + (this.sprite.x - boundsCenterLocalCoord.x); + this.sprite.y = pointerLocalCoord.y + (this.sprite.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.x - pointerLocalCoord.x, this.sprite.y - pointerLocalCoord.y); + } + + this.updateDrag(pointer, true); + + if (this.bringToTop) + { + this._dragPhase = true; + this.sprite.bringToTop(); + } + + this.dragStartPoint.set(x, y); + + this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y); + + this._pendingDrag = false; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalX + * @param {number} x + */ + globalToLocalX: function (x) { + + if (this.scaleLayer) + { + x -= this.game.scale.grid.boundsFluid.x; + x *= this.game.scale.grid.scaleFluidInversed.x; + } + + return x; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalY + * @param {number} y + */ + globalToLocalY: function (y) { + + if (this.scaleLayer) + { + y -= this.game.scale.grid.boundsFluid.y; + y *= this.game.scale.grid.scaleFluidInversed.y; + } + + return y; + + }, + + /** + * Convert global coordinates to local sprite coordinates + * + * @method Phaser.InputHandler#globalToLocal + * @param {Phaser.Point} globalCoord - The global coordinates to convert. + * @return {Phaser.Point} A point containing the local coordinates. + */ + globalToLocal: function (globalCoord) { + + if (this.sprite.parent) + { + return this.game.input.getLocalPosition(this.sprite.parent, {x: globalCoord.x, y: globalCoord.y}); + } + else + { + return globalCoord; + } + + }, + + /** + * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#stopDrag + * @param {Phaser.Pointer} pointer + */ + stopDrag: function (pointer) { + + this.isDragged = false; + this._draggedPointerID = -1; + this._pointerData[pointer.id].isDragged = false; + this._dragPhase = false; + this._pendingDrag = false; + + if (this.snapOnRelease) + { + if (this.sprite.fixedToCamera) + { + 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 + { + 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); + } + } + + this.sprite.events.onDragStop$dispatch(this.sprite, pointer); + + if (this.checkPointerOver(pointer) === false) + { + this._pointerOutHandler(pointer); + } + + }, + + /** + * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! + * + * @method Phaser.InputHandler#setDragLock + * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false. + * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false. + */ + setDragLock: function (allowHorizontal, allowVertical) { + + if (allowHorizontal === undefined) { allowHorizontal = true; } + if (allowVertical === undefined) { allowVertical = true; } + + this.allowHorizontalDrag = allowHorizontal; + this.allowVerticalDrag = allowVertical; + + }, + + /** + * Make this Sprite snap to the given grid either during drag or when it's released. + * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. + * + * @method Phaser.InputHandler#enableSnap + * @param {number} snapX - The width of the grid cell to snap to. + * @param {number} snapY - The height of the grid cell to snap to. + * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged. + * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released. + * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid. + * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid. + */ + enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) { + + if (onDrag === undefined) { onDrag = true; } + if (onRelease === undefined) { onRelease = false; } + if (snapOffsetX === undefined) { snapOffsetX = 0; } + if (snapOffsetY === undefined) { snapOffsetY = 0; } + + this.snapX = snapX; + this.snapY = snapY; + this.snapOffsetX = snapOffsetX; + this.snapOffsetY = snapOffsetY; + this.snapOnDrag = onDrag; + this.snapOnRelease = onRelease; + + }, + + /** + * Stops the sprite from snapping to a grid during drag or release. + * + * @method Phaser.InputHandler#disableSnap + */ + disableSnap: function () { + + this.snapOnDrag = false; + this.snapOnRelease = false; + + }, + + /** + * Bounds Rect check for the sprite drag + * + * @method Phaser.InputHandler#checkBoundsRect + */ + checkBoundsRect: function () { + + if (this.sprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsRect.left) + { + this.sprite.cameraOffset.x = this.boundsRect.left; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right) + { + this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsRect.top) + { + this.sprite.cameraOffset.y = this.boundsRect.top; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom) + { + this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsRect.left) + { + this.sprite.x = this.boundsRect.x + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsRect.right) + { + this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsRect.top) + { + this.sprite.y = this.boundsRect.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsRect.bottom) + { + this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + }, + + /** + * Parent Sprite Bounds check for the sprite drag. + * + * @method Phaser.InputHandler#checkBoundsSprite + */ + checkBoundsSprite: function () { + + if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x) + { + this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width)) + { + this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y) + { + this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height)) + { + this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsSprite.left) + { + this.sprite.x = this.boundsSprite.left + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsSprite.right) + { + this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsSprite.top) + { + this.sprite.y = this.boundsSprite.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsSprite.bottom) + { + this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + } + +}; + +Phaser.InputHandler.prototype.constructor = Phaser.InputHandler; + +/** +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Gamepad class handles gamepad input and dispatches gamepad events. +* +* Remember to call `gamepad.start()`. +* +* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! +* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it +* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. +* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. +* +* @class Phaser.Gamepad +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Gamepad = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads + * @private + */ + this._gamepadIndexMap = {}; + + /** + * @property {Array} _rawPads - The raw state of the gamepads from the browser + * @private + */ + this._rawPads = []; + + /** + * @property {boolean} _active - Private flag for whether or not the API is polled + * @private + * @default + */ + this._active = false; + + /** + * Gamepad input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation. + * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not? + * @private + */ + this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') !== -1) || !!navigator.getGamepads; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevRawGamepadTypes + * @private + * @default + */ + this._prevRawGamepadTypes = []; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevTimestamps + * @private + * @default + */ + this._prevTimestamps = []; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._ongamepadconnected = null; + + /** + * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._gamepaddisconnected = null; + + /** + * @property {Array} _gamepads - The four Phaser Gamepads. + * @private + */ + this._gamepads = [ + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this) + ]; + +}; + +Phaser.Gamepad.prototype = { + + /** + * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. + * + * @method Phaser.Gamepad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callback methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + this.callbackContext = context; + } + + }, + + /** + * Starts the Gamepad event handling. + * This MUST be called manually before Phaser will start polling the Gamepad API. + * + * @method Phaser.Gamepad#start + */ + start: function () { + + if (this._active) + { + // Avoid setting multiple listeners + return; + } + + this._active = true; + + var _this = this; + + this._onGamepadConnected = function (event) { + return _this.onGamepadConnected(event); + }; + + this._onGamepadDisconnected = function (event) { + return _this.onGamepadDisconnected(event); + }; + + window.addEventListener('gamepadconnected', this._onGamepadConnected, false); + window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false); + + }, + + /** + * Handles the connection of a Gamepad. + * + * @method onGamepadConnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadConnected: function (event) { + + var newPad = event.gamepad; + this._rawPads.push(newPad); + this._gamepads[newPad.index].connect(newPad); + + }, + + /** + * Handles the disconnection of a Gamepad. + * + * @method onGamepadDisconnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadDisconnected: function (event) { + + var removedPad = event.gamepad; + + for (var i in this._rawPads) + { + if (this._rawPads[i].index === removedPad.index) + { + this._rawPads.splice(i,1); + } + } + + this._gamepads[removedPad.index].disconnect(); + + }, + + /** + * Main gamepad update loop. Should not be called manually. + * @method Phaser.Gamepad#update + * @protected + */ + update: function () { + + this._pollGamepads(); + + this.pad1.pollStatus(); + this.pad2.pollStatus(); + this.pad3.pollStatus(); + this.pad4.pollStatus(); + + }, + + /** + * Updating connected gamepads (for Google Chrome). Should not be called manually. + * + * @method Phaser.Gamepad#_pollGamepads + * @private + */ + _pollGamepads: function () { + + if (!this._active) + { + return; + } + + if (navigator['getGamepads']) + { + var rawGamepads = navigator.getGamepads(); + } + else if (navigator['webkitGetGamepads']) + { + var rawGamepads = navigator.webkitGetGamepads(); + } + else if (navigator['webkitGamepads']) + { + var rawGamepads = navigator.webkitGamepads(); + } + + if (rawGamepads) + { + this._rawPads = []; + + var gamepadsChanged = false; + + for (var i = 0; i < rawGamepads.length; i++) + { + if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i]) + { + gamepadsChanged = true; + this._prevRawGamepadTypes[i] = typeof rawGamepads[i]; + } + + if (rawGamepads[i]) + { + this._rawPads.push(rawGamepads[i]); + } + + // Support max 4 pads at the moment + if (i === 3) + { + break; + } + } + + for (var g = 0; g < this._gamepads.length; g++) + { + this._gamepads[g]._rawPad = this._rawPads[g]; + } + + if (gamepadsChanged) + { + var validConnections = { rawIndices: {}, padIndices: {} }; + var singlePad; + + for (var j = 0; j < this._gamepads.length; j++) + { + singlePad = this._gamepads[j]; + + if (singlePad.connected) + { + for (var k = 0; k < this._rawPads.length; k++) + { + if (this._rawPads[k].index === singlePad.index) + { + validConnections.rawIndices[singlePad.index] = true; + validConnections.padIndices[j] = true; + } + } + } + } + + for (var l = 0; l < this._gamepads.length; l++) + { + singlePad = this._gamepads[l]; + + if (validConnections.padIndices[l]) + { + continue; + } + + if (this._rawPads.length < 1) + { + singlePad.disconnect(); + } + + for (var m = 0; m < this._rawPads.length; m++) + { + if (validConnections.padIndices[l]) + { + break; + } + + var rawPad = this._rawPads[m]; + + if (rawPad) + { + if (validConnections.rawIndices[rawPad.index]) + { + singlePad.disconnect(); + continue; + } + else + { + singlePad.connect(rawPad); + validConnections.rawIndices[rawPad.index] = true; + validConnections.padIndices[l] = true; + } + } + else + { + singlePad.disconnect(); + } + } + } + } + } + }, + + /** + * Sets the deadZone variable for all four gamepads + * @method Phaser.Gamepad#setDeadZones + */ + setDeadZones: function (value) { + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].deadZone = value; + } + + }, + + /** + * Stops the Gamepad event handling. + * + * @method Phaser.Gamepad#stop + */ + stop: function () { + + this._active = false; + + window.removeEventListener('gamepadconnected', this._onGamepadConnected); + window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected); + + }, + + /** + * Reset all buttons/axes of all gamepads + * @method Phaser.Gamepad#reset + */ + reset: function () { + + this.update(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].reset(); + } + + }, + + /** + * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justPressed(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justReleased(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns true if the button is currently pressed down, on ANY gamepad. + * @method Phaser.Gamepad#isDown + * @param {number} buttonCode - The buttonCode of the button to check for. + * @return {boolean} True if a button is currently down. + */ + isDown: function (buttonCode) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].isDown(buttonCode) === true) + { + return true; + } + } + + return false; + }, + + /** + * Destroys this object and the associated event listeners. + * + * @method Phaser.Gamepad#destroy + */ + destroy: function () { + + this.stop(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].destroy(); + } + + } + +}; + +Phaser.Gamepad.prototype.constructor = Phaser.Gamepad; + +/** +* If the gamepad input is active or not - if not active it should not be updated from Input.js +* @name Phaser.Gamepad#active +* @property {boolean} active - If the gamepad input is active or not. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "active", { + + get: function () { + return this._active; + } + +}); + +/** +* Whether or not gamepads are supported in current browser. +* @name Phaser.Gamepad#supported +* @property {boolean} supported - Whether or not gamepads are supported in current browser. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "supported", { + + get: function () { + return this._gamepadSupportAvailable; + } + +}); + +/** +* How many live gamepads are currently connected. +* @name Phaser.Gamepad#padsConnected +* @property {number} padsConnected - How many live gamepads are currently connected. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", { + + get: function () { + return this._rawPads.length; + } + +}); + +/** +* Gamepad #1 +* @name Phaser.Gamepad#pad1 +* @property {Phaser.SinglePad} pad1 - Gamepad #1; +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad1", { + + get: function () { + return this._gamepads[0]; + } + +}); + +/** +* Gamepad #2 +* @name Phaser.Gamepad#pad2 +* @property {Phaser.SinglePad} pad2 - Gamepad #2 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad2", { + + get: function () { + return this._gamepads[1]; + } + +}); + +/** +* Gamepad #3 +* @name Phaser.Gamepad#pad3 +* @property {Phaser.SinglePad} pad3 - Gamepad #3 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad3", { + + get: function () { + return this._gamepads[2]; + } + +}); + +/** +* Gamepad #4 +* @name Phaser.Gamepad#pad4 +* @property {Phaser.SinglePad} pad4 - Gamepad #4 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad4", { + + get: function () { + return this._gamepads[3]; + } + +}); + +Phaser.Gamepad.BUTTON_0 = 0; +Phaser.Gamepad.BUTTON_1 = 1; +Phaser.Gamepad.BUTTON_2 = 2; +Phaser.Gamepad.BUTTON_3 = 3; +Phaser.Gamepad.BUTTON_4 = 4; +Phaser.Gamepad.BUTTON_5 = 5; +Phaser.Gamepad.BUTTON_6 = 6; +Phaser.Gamepad.BUTTON_7 = 7; +Phaser.Gamepad.BUTTON_8 = 8; +Phaser.Gamepad.BUTTON_9 = 9; +Phaser.Gamepad.BUTTON_10 = 10; +Phaser.Gamepad.BUTTON_11 = 11; +Phaser.Gamepad.BUTTON_12 = 12; +Phaser.Gamepad.BUTTON_13 = 13; +Phaser.Gamepad.BUTTON_14 = 14; +Phaser.Gamepad.BUTTON_15 = 15; + +Phaser.Gamepad.AXIS_0 = 0; +Phaser.Gamepad.AXIS_1 = 1; +Phaser.Gamepad.AXIS_2 = 2; +Phaser.Gamepad.AXIS_3 = 3; +Phaser.Gamepad.AXIS_4 = 4; +Phaser.Gamepad.AXIS_5 = 5; +Phaser.Gamepad.AXIS_6 = 6; +Phaser.Gamepad.AXIS_7 = 7; +Phaser.Gamepad.AXIS_8 = 8; +Phaser.Gamepad.AXIS_9 = 9; + +// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7). +// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button. +// In other words - discrepancies when using gamepads. + +Phaser.Gamepad.XBOX360_A = 0; +Phaser.Gamepad.XBOX360_B = 1; +Phaser.Gamepad.XBOX360_X = 2; +Phaser.Gamepad.XBOX360_Y = 3; +Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4; +Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5; +Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6; +Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7; +Phaser.Gamepad.XBOX360_BACK = 8; +Phaser.Gamepad.XBOX360_START = 9; +Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11; + +Phaser.Gamepad.XBOX360_DPAD_LEFT = 14; +Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15; +Phaser.Gamepad.XBOX360_DPAD_UP = 12; +Phaser.Gamepad.XBOX360_DPAD_DOWN = 13; + +// On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right +Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0; +Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1; +Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2; +Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3; + +// PlayStation 3 controller (masquerading as xbox360 controller) button mappings + +Phaser.Gamepad.PS3XC_X = 0; +Phaser.Gamepad.PS3XC_CIRCLE = 1; +Phaser.Gamepad.PS3XC_SQUARE = 2; +Phaser.Gamepad.PS3XC_TRIANGLE = 3; +Phaser.Gamepad.PS3XC_L1 = 4; +Phaser.Gamepad.PS3XC_R1 = 5; +Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_SELECT = 8; +Phaser.Gamepad.PS3XC_START = 9; +Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11; +Phaser.Gamepad.PS3XC_DPAD_UP = 12; +Phaser.Gamepad.PS3XC_DPAD_DOWN = 13; +Phaser.Gamepad.PS3XC_DPAD_LEFT = 14; +Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15; +Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1 + +/** +* @author @karlmacklin +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A single Phaser Gamepad +* +* @class Phaser.SinglePad +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this) +*/ +Phaser.SinglePad = function (game, padParent) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {number} index - The gamepad index as per browsers data + * @readonly + */ + this.index = null; + + /** + * @property {boolean} connected - Whether or not this particular gamepad is connected or not. + * @readonly + */ + this.connected = false; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time a button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time an axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates. + */ + this.deadZone = 0.26; + + /** + * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object + * @private + */ + this._padParent = padParent; + + /** + * @property {object} _rawPad - The 'raw' gamepad data. + * @private + */ + this._rawPad = null; + + /** + * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads. + * @private + */ + this._prevTimestamp = null; + + /** + * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected. + * @private + */ + this._buttons = []; + + /** + * @property {number} _buttonsLen - Length of the _buttons array. + * @private + */ + this._buttonsLen = 0; + + /** + * @property {Array} _axes - Current axes state. + * @private + */ + this._axes = []; + + /** + * @property {number} _axesLen - Length of the _axes array. + * @private + */ + this._axesLen = 0; + +}; + +Phaser.SinglePad.prototype = { + + /** + * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. + * + * @method Phaser.SinglePad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callbak methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + + this.callbackContext = context; + } + }, + + /** + * Gets a DeviceButton object from this controller to be stored and referenced locally. + * The DeviceButton object can then be polled, have events attached to it, etc. + * + * @method Phaser.SinglePad#getButton + * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc. + * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly. + */ + getButton: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode]; + } + else + { + return null; + } + + }, + + /** + * Main update function called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#pollStatus + */ + pollStatus: function () { + + if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp))) + { + return; + } + + for (var i = 0; i < this._buttonsLen; i++) + { + var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i]; + + if (rawButtonVal !== this._buttons[i].value) + { + if (rawButtonVal === 1) + { + this.processButtonDown(i, rawButtonVal); + } + else if (rawButtonVal === 0) + { + this.processButtonUp(i, rawButtonVal); + } + else + { + this.processButtonFloat(i, rawButtonVal); + } + } + } + + for (var index = 0; index < this._axesLen; index++) + { + var value = this._rawPad.axes[index]; + + if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone)) + { + this.processAxisChange(index, value); + } + else + { + this.processAxisChange(index, 0); + } + } + + this._prevTimestamp = this._rawPad.timestamp; + + }, + + /** + * Gamepad connect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#connect + * @param {object} rawPad - The raw gamepad object + */ + connect: function (rawPad) { + + var triggerCallback = !this.connected; + + this.connected = true; + this.index = rawPad.index; + + this._rawPad = rawPad; + + this._buttons = []; + this._buttonsLen = rawPad.buttons.length; + + this._axes = []; + this._axesLen = rawPad.axes.length; + + for (var a = 0; a < this._axesLen; a++) + { + this._axes[a] = rawPad.axes[a]; + } + + for (var buttonCode in rawPad.buttons) + { + buttonCode = parseInt(buttonCode, 10); + this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode); + } + + if (triggerCallback && this._padParent.onConnectCallback) + { + this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index); + } + + if (triggerCallback && this.onConnectCallback) + { + this.onConnectCallback.call(this.callbackContext); + } + + }, + + /** + * Gamepad disconnect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#disconnect + */ + disconnect: function () { + + var triggerCallback = this.connected; + var disconnectingIndex = this.index; + + this.connected = false; + this.index = null; + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + if (triggerCallback && this._padParent.onDisconnectCallback) + { + this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex); + } + + if (triggerCallback && this.onDisconnectCallback) + { + this.onDisconnectCallback.call(this.callbackContext); + } + + }, + + /** + * Destroys this object and associated callback references. + * + * @method Phaser.SinglePad#destroy + */ + destroy: function () { + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + this.onConnectCallback = null; + this.onDisconnectCallback = null; + this.onDownCallback = null; + this.onUpCallback = null; + this.onAxisCallback = null; + this.onFloatCallback = null; + + }, + + /** + * Handles changes in axis. + * + * @method Phaser.SinglePad#processAxisChange + * @param {object} axisState - State of the relevant axis + */ + processAxisChange: function (index, value) { + + if (this._axes[index] === value) + { + return; + } + + this._axes[index] = value; + + if (this._padParent.onAxisCallback) + { + this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value); + } + + if (this.onAxisCallback) + { + this.onAxisCallback.call(this.callbackContext, this, index, value); + } + + }, + + /** + * Handles button down press. + * + * @method Phaser.SinglePad#processButtonDown + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonDown: function (buttonCode, value) { + + if (this._buttons[buttonCode]) + { + this._buttons[buttonCode].start(null, value); + } + + 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); + } + + }, + + /** + * Handles button release. + * + * @method Phaser.SinglePad#processButtonUp + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonUp: function (buttonCode, value) { + + 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._buttons[buttonCode]) + { + this._buttons[buttonCode].stop(null, value); + } + + }, + + /** + * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) + * + * @method Phaser.SinglePad#processButtonFloat + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. + */ + processButtonFloat: function (buttonCode, value) { + + 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].padFloat(value); + } + + }, + + /** + * Returns value of requested axis. + * + * @method Phaser.SinglePad#axis + * @param {number} axisCode - The index of the axis to check + * @return {number} Axis value if available otherwise false + */ + axis: function (axisCode) { + + if (this._axes[axisCode]) + { + return this._axes[axisCode]; + } + + return false; + + }, + + /** + * Returns true if the button is pressed down. + * + * @method Phaser.SinglePad#isDown + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is pressed down. + */ + isDown: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isDown; + } + + return false; + + }, + + /** + * Returns true if the button is not currently pressed. + * + * @method Phaser.SinglePad#isUp + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is not currently pressed down. + */ + isUp: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isUp; + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justReleased + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justReleased(duration); + } + + }, + + /** + * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justPressed(duration); + } + + }, + + /** + * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example + * analog trigger buttons on the XBOX 360 controller. + * + * @method Phaser.SinglePad#buttonValue + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. + */ + buttonValue: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].value; + } + + return null; + + }, + + /** + * Reset all buttons/axes of this gamepad. + * + * @method Phaser.SinglePad#reset + */ + reset: function () { + + for (var j = 0; j < this._axes.length; j++) + { + this._axes[j] = 0; + } + + } + +}; + +Phaser.SinglePad.prototype.constructor = Phaser.SinglePad; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. +* +* @class Phaser.Key +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}. +*/ +Phaser.Key = function (game, keycode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * The enabled state of the key - see `enabled`. + * @property {boolean} _enabled + * @private + */ + this._enabled = true; + + /** + * @property {object} event - Stores the most recent DOM event. + * @readonly + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * @default + */ + this.isUp = true; + + /** + * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. + * @default + */ + this.altKey = false; + + /** + * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. + * @default + */ + this.ctrlKey = false; + + /** + * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. + * @default + */ + this.shiftKey = false; + + /** + * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now. + */ + this.timeDown = 0; + + /** + * If the key is down this value holds the duration of that key press and is constantly updated. + * If the key is up it holds the duration of the previous down session. + * @property {number} duration - The number of milliseconds this key has been held down for. + * @default + */ + this.duration = 0; + + /** + * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now. + * @default + */ + this.timeUp = -2500; + + /** + * If the key is up this value holds the duration of that key release and is constantly updated. + * If the key is down it holds the duration of the previous up session. + * @property {number} duration - The number of milliseconds this key has been up for. + * @default + */ + this.durationUp = -2500; + + /** + * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. + * @default + */ + this.repeats = 0; + + /** + * @property {number} keyCode - The keycode of this key. + */ + this.keyCode = keycode; + + /** + * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). + */ + this.onDown = new Phaser.Signal(); + + /** + * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. + */ + this.onHoldCallback = null; + + /** + * @property {object} onHoldContext - The context under which the onHoldCallback will be called. + */ + this.onHoldContext = null; + + /** + * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). + */ + this.onUp = new Phaser.Signal(); + + /** + * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justDown = false; + + /** + * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justUp = false; + +}; + +Phaser.Key.prototype = { + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#update + * @protected + */ + update: function () { + + if (!this._enabled) { return; } + + if (this.isDown) + { + this.duration = this.game.time.time - this.timeDown; + this.repeats++; + + if (this.onHoldCallback) + { + this.onHoldCallback.call(this.onHoldContext, this); + } + } + else + { + this.durationUp = this.game.time.time - this.timeUp; + } + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyDown + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyDown: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + // exit if this key down is from auto-repeat + if (this.isDown) + { + return; + } + + this.altKey = event.altKey; + this.ctrlKey = event.ctrlKey; + this.shiftKey = event.shiftKey; + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.duration = 0; + this.durationUp = this.game.time.time - this.timeUp; + this.repeats = 0; + + // _justDown will remain true until it is read via the justDown Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justDown = true; + + this.onDown.dispatch(this); + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyUp + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyUp: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = this.game.time.time - this.timeDown; + this.durationUp = 0; + + // _justUp will remain true until it is read via the justUp Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justUp = true; + + this.onUp.dispatch(this); + + }, + + /** + * Resets the state of this Key. + * + * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key. + * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. + * + * @method Phaser.Key#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = 0; + this.durationUp = -2500; + this._enabled = true; // .enabled causes reset(false) + this._justDown = false; + this._justUp = false; + + if (hard) + { + this.onDown.removeAll(); + this.onUp.removeAll(); + this.onHoldCallback = null; + this.onHoldContext = null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#downDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration. + */ + downDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (this.isDown && this.duration < duration); + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#upDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration. + */ + upDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (!this.isDown && ((this.game.time.time - this.timeUp) < duration)); + + }, + + /** + * Returns `true` if the Key was just pressed down this update tick, or `false` if it either isn't down, + * or was pressed down on a previous update tick. + * + * @method Phaser.Key#justPressed + * @return {boolean} True if the key was just pressed down this update tick. + */ + justPressed: function () { + + return (this.isDown && this.duration === 0); + + }, + + /** + * Returns `true` if the Key was just released this update tick, or `false` if it either isn't up, + * or was released on a previous update tick. + * + * @method Phaser.Key#justReleased + * @return {boolean} True if the key was just released this update tick. + */ + justReleased: function () { + + return (!this.isDown && this.durationUp === 0); + + } + +}; + +/** +* The justDown value allows you to test if this Key has just been pressed down or not. +* When you check this value it will return `true` if the Key is down, otherwise `false`. +* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. +* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justDown +* @property {boolean} justDown +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justDown", { + + get: function () { + + var current = this._justDown; + this._justDown = false; + return current; + + } + +}); + +/** +* The justUp value allows you to test if this Key has just been released or not. +* When you check this value it will return `true` if the Key is up, otherwise `false`. +* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again. +* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justUp +* @property {boolean} justUp +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justUp", { + + get: function () { + + var current = this._justUp; + this._justUp = false; + return current; + + } + +}); + +/** +* An enabled key processes its update and dispatches events. +* A key can be disabled momentarily at runtime instead of deleting it. +* @name Phaser.Key#enabled +* @property {boolean} enabled +* @memberof Phaser.Key +* @default true +*/ +Object.defineProperty(Phaser.Key.prototype, "enabled", { + + get: function () { + + return this._enabled; + + }, + + set: function (value) { + + value = !!value; + + if (value !== this._enabled) + { + if (!value) + { + this.reset(false); + } + + this._enabled = value; + } + } + +}); + +Phaser.Key.prototype.constructor = Phaser.Key; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Keyboard class monitors keyboard input and dispatches keyboard events. +* +* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. +* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. +* +* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. +* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. +* So please check your extensions before opening Phaser issues. +* +* @class Phaser.Keyboard +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Keyboard = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Keyboard input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. + */ + this.event = null; + + /** + * @property {object} pressEvent - The most recent DOM event from keypress. + */ + this.pressEvent = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. + */ + this.onDownCallback = null; + + /** + * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. + */ + this.onPressCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a key is released. + */ + this.onUpCallback = null; + + /** + * @property {array} _keys - The array the Phaser.Key objects are stored in. + * @private + */ + this._keys = []; + + /** + * @property {array} _capture - The array the key capture values are stored in. + * @private + */ + this._capture = []; + + /** + * @property {function} _onKeyDown + * @private + * @default + */ + this._onKeyDown = null; + + /** + * @property {function} _onKeyPress + * @private + * @default + */ + this._onKeyPress = null; + + /** + * @property {function} _onKeyUp + * @private + * @default + */ + this._onKeyUp = null; + + /** + * @property {number} _i - Internal cache var + * @private + */ + this._i = 0; + + /** + * @property {number} _k - Internal cache var + * @private + */ + this._k = 0; + +}; + +Phaser.Keyboard.prototype = { + + /** + * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. + * + * @method Phaser.Keyboard#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down. + * @param {function} [onUp=null] - This callback is invoked every time a key is released. + * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised. + */ + addCallbacks: function (context, onDown, onUp, onPress) { + + this.callbackContext = context; + + if (onDown !== undefined && onDown !== null) + { + this.onDownCallback = onDown; + } + + if (onUp !== undefined && onUp !== null) + { + this.onUpCallback = onUp; + } + + if (onPress !== undefined && onPress !== null) + { + this.onPressCallback = onPress; + } + + }, + + /** + * Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}. + * + * @method Phaser.Keyboard#removeCallbacks + */ + removeCallbacks: function () { + + this.callbackContext = this; + this.onDownCallback = null; + this.onUpCallback = null; + this.onPressCallback = null; + + }, + + /** + * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. + * The Key object can then be polled, have events attached to it, etc. + * + * @method Phaser.Keyboard#addKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key. + * @return {Phaser.Key} The Key object which you can store locally and reference directly. + */ + addKey: function (keycode) { + + if (!this._keys[keycode]) + { + this._keys[keycode] = new Phaser.Key(this.game, keycode); + + this.addKeyCapture(keycode); + } + + return this._keys[keycode]; + + }, + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example, + * + * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); + * + * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object. + * + * @method Phaser.Keyboard#addKeys + * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. + * @return {object} An object containing the properties mapped to {@link Phaser.Key} values. + */ + addKeys: function (keys) { + + var output = {}; + + for (var key in keys) + { + output[key] = this.addKey(keys[key]); + } + + return output; + + }, + + /** + * Removes a Key object from the Keyboard manager. + * + * @method Phaser.Keyboard#removeKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove. + */ + removeKey: function (keycode) { + + if (this._keys[keycode]) + { + this._keys[keycode] = null; + + this.removeKeyCapture(keycode); + } + + }, + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. + * + * @method Phaser.Keyboard#createCursorKeys + * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects. + */ + createCursorKeys: function () { + + return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT }); + + }, + + /** + * Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window. + * This is called automatically by Phaser.Input and should not normally be invoked directly. + * + * @method Phaser.Keyboard#start + * @protected + */ + start: function () { + + if (this.game.device.cocoonJS) + { + return; + } + + if (this._onKeyDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onKeyDown = function (event) { + return _this.processKeyDown(event); + }; + + this._onKeyUp = function (event) { + return _this.processKeyUp(event); + }; + + this._onKeyPress = function (event) { + return _this.processKeyPress(event); + }; + + window.addEventListener('keydown', this._onKeyDown, false); + window.addEventListener('keyup', this._onKeyUp, false); + window.addEventListener('keypress', this._onKeyPress, false); + + }, + + /** + * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. + * + * @method Phaser.Keyboard#stop + */ + stop: function () { + + window.removeEventListener('keydown', this._onKeyDown); + window.removeEventListener('keyup', this._onKeyUp); + window.removeEventListener('keypress', this._onKeyPress); + + this._onKeyDown = null; + this._onKeyUp = null; + this._onKeyPress = null; + + }, + + /** + * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. + * Also clears all key captures and currently created Key objects. + * + * @method Phaser.Keyboard#destroy + */ + destroy: function () { + + this.stop(); + + this.clearCaptures(); + + this._keys.length = 0; + this._i = 0; + + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Pass in either a single keycode or an array/hash of keycodes. + * + * @method Phaser.Keyboard#addKeyCapture + * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`. + */ + addKeyCapture: function (keycode) { + + if (typeof keycode === 'object') + { + for (var key in keycode) + { + this._capture[keycode[key]] = true; + } + } + else + { + this._capture[keycode] = true; + } + }, + + /** + * Removes an existing key capture. + * + * @method Phaser.Keyboard#removeKeyCapture + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of. + */ + removeKeyCapture: function (keycode) { + + delete this._capture[keycode]; + + }, + + /** + * Clear all set key captures. + * + * @method Phaser.Keyboard#clearCaptures + */ + clearCaptures: function () { + + this._capture = {}; + + }, + + /** + * Updates all currently defined keys. + * + * @method Phaser.Keyboard#update + */ + update: function () { + + this._i = this._keys.length; + + while (this._i--) + { + if (this._keys[this._i]) + { + this._keys[this._i].update(); + } + } + + }, + + /** + * Process the keydown event. + * + * @method Phaser.Keyboard#processKeyDown + * @param {KeyboardEvent} event + * @protected + */ + processKeyDown: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + // The event is being captured but another hotkey may need it + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyDown(event); + + this._k = key; + + if (this.onDownCallback) + { + this.onDownCallback.call(this.callbackContext, event); + } + + }, + + /** + * Process the keypress event. + * + * @method Phaser.Keyboard#processKeyPress + * @param {KeyboardEvent} event + * @protected + */ + processKeyPress: function (event) { + + this.pressEvent = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.onPressCallback) + { + this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event); + } + + }, + + /** + * Process the keyup event. + * + * @method Phaser.Keyboard#processKeyUp + * @param {KeyboardEvent} event + * @protected + */ + processKeyUp: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyUp(event); + + if (this.onUpCallback) + { + this.onUpCallback.call(this.callbackContext, event); + } + + }, + + /** + * Resets all Keys. + * + * @method Phaser.Keyboard#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.event = null; + + var i = this._keys.length; + + while (i--) + { + if (this._keys[i]) + { + this._keys[i].reset(hard); + } + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#downDuration + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. + */ + downDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].downDuration(duration); + } + else + { + return null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#upDuration + * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found. + */ + upDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].upDuration(duration); + } + else + { + return null; + } + + }, + + justPressed: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justPressed(); + } + else + { + return null; + } + + }, + + justReleased: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justReleased(); + } + else + { + return null; + } + + }, + + /** + * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. + * + * @method Phaser.Keyboard#isDown + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found. + */ + isDown: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].isDown; + } + else + { + return null; + } + + } + +}; + +/** +* Returns the string value of the most recently pressed key. +* @name Phaser.Keyboard#lastChar +* @property {string} lastChar - The string value of the most recently pressed key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", { + + get: function () { + + if (this.event && this.event.charCode === 32) + { + return ''; + } + else if (this.pressEvent) + { + return String.fromCharCode(this.pressEvent.charCode); + } + else + { + return null; + } + + } + +}); + +/** +* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. +* @name Phaser.Keyboard#lastKey +* @property {Phaser.Key} lastKey - The most recently pressed Key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", { + + get: function () { + + return this._keys[this._k]; + + } + +}); + +Phaser.Keyboard.prototype.constructor = Phaser.Keyboard; + +/** +* A key code represents a physical key on a keyboard. +* +* The KeyCode class contains commonly supported keyboard key codes which can be used +* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods. +* +* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. +* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. +* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property. +* +* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; +* the latter approach is supported for compatibility. +* +* @class Phaser.KeyCode +*/ +Phaser.KeyCode = { + /** @static */ + A: "A".charCodeAt(0), + /** @static */ + B: "B".charCodeAt(0), + /** @static */ + C: "C".charCodeAt(0), + /** @static */ + D: "D".charCodeAt(0), + /** @static */ + E: "E".charCodeAt(0), + /** @static */ + F: "F".charCodeAt(0), + /** @static */ + G: "G".charCodeAt(0), + /** @static */ + H: "H".charCodeAt(0), + /** @static */ + I: "I".charCodeAt(0), + /** @static */ + J: "J".charCodeAt(0), + /** @static */ + K: "K".charCodeAt(0), + /** @static */ + L: "L".charCodeAt(0), + /** @static */ + M: "M".charCodeAt(0), + /** @static */ + N: "N".charCodeAt(0), + /** @static */ + O: "O".charCodeAt(0), + /** @static */ + P: "P".charCodeAt(0), + /** @static */ + Q: "Q".charCodeAt(0), + /** @static */ + R: "R".charCodeAt(0), + /** @static */ + S: "S".charCodeAt(0), + /** @static */ + T: "T".charCodeAt(0), + /** @static */ + U: "U".charCodeAt(0), + /** @static */ + V: "V".charCodeAt(0), + /** @static */ + W: "W".charCodeAt(0), + /** @static */ + X: "X".charCodeAt(0), + /** @static */ + Y: "Y".charCodeAt(0), + /** @static */ + Z: "Z".charCodeAt(0), + /** @static */ + ZERO: "0".charCodeAt(0), + /** @static */ + ONE: "1".charCodeAt(0), + /** @static */ + TWO: "2".charCodeAt(0), + /** @static */ + THREE: "3".charCodeAt(0), + /** @static */ + FOUR: "4".charCodeAt(0), + /** @static */ + FIVE: "5".charCodeAt(0), + /** @static */ + SIX: "6".charCodeAt(0), + /** @static */ + SEVEN: "7".charCodeAt(0), + /** @static */ + EIGHT: "8".charCodeAt(0), + /** @static */ + NINE: "9".charCodeAt(0), + /** @static */ + NUMPAD_0: 96, + /** @static */ + NUMPAD_1: 97, + /** @static */ + NUMPAD_2: 98, + /** @static */ + NUMPAD_3: 99, + /** @static */ + NUMPAD_4: 100, + /** @static */ + NUMPAD_5: 101, + /** @static */ + NUMPAD_6: 102, + /** @static */ + NUMPAD_7: 103, + /** @static */ + NUMPAD_8: 104, + /** @static */ + NUMPAD_9: 105, + /** @static */ + NUMPAD_MULTIPLY: 106, + /** @static */ + NUMPAD_ADD: 107, + /** @static */ + NUMPAD_ENTER: 108, + /** @static */ + NUMPAD_SUBTRACT: 109, + /** @static */ + NUMPAD_DECIMAL: 110, + /** @static */ + NUMPAD_DIVIDE: 111, + /** @static */ + F1: 112, + /** @static */ + F2: 113, + /** @static */ + F3: 114, + /** @static */ + F4: 115, + /** @static */ + F5: 116, + /** @static */ + F6: 117, + /** @static */ + F7: 118, + /** @static */ + F8: 119, + /** @static */ + F9: 120, + /** @static */ + F10: 121, + /** @static */ + F11: 122, + /** @static */ + F12: 123, + /** @static */ + F13: 124, + /** @static */ + F14: 125, + /** @static */ + F15: 126, + /** @static */ + COLON: 186, + /** @static */ + EQUALS: 187, + /** @static */ + COMMA: 188, + /** @static */ + UNDERSCORE: 189, + /** @static */ + PERIOD: 190, + /** @static */ + QUESTION_MARK: 191, + /** @static */ + TILDE: 192, + /** @static */ + OPEN_BRACKET: 219, + /** @static */ + BACKWARD_SLASH: 220, + /** @static */ + CLOSED_BRACKET: 221, + /** @static */ + QUOTES: 222, + /** @static */ + BACKSPACE: 8, + /** @static */ + TAB: 9, + /** @static */ + CLEAR: 12, + /** @static */ + ENTER: 13, + /** @static */ + SHIFT: 16, + /** @static */ + CONTROL: 17, + /** @static */ + ALT: 18, + /** @static */ + CAPS_LOCK: 20, + /** @static */ + ESC: 27, + /** @static */ + SPACEBAR: 32, + /** @static */ + PAGE_UP: 33, + /** @static */ + PAGE_DOWN: 34, + /** @static */ + END: 35, + /** @static */ + HOME: 36, + /** @static */ + LEFT: 37, + /** @static */ + UP: 38, + /** @static */ + RIGHT: 39, + /** @static */ + DOWN: 40, + /** @static */ + PLUS: 43, + /** @static */ + MINUS: 44, + /** @static */ + INSERT: 45, + /** @static */ + DELETE: 46, + /** @static */ + HELP: 47, + /** @static */ + NUM_LOCK: 144 +}; + +// Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility +for (var key in Phaser.KeyCode) +{ + if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/)) + { + Phaser.Keyboard[key] = Phaser.KeyCode[key]; + } +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +Phaser.Component = function () {}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. +* +* @class +*/ +Phaser.Component.Angle = function () {}; + +Phaser.Component.Angle.prototype = { + + /** + * The angle property is the rotation of the Game Object in *degrees* from its original orientation. + * + * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. + * + * Values outside this range are added to or subtracted from 360 to obtain a value within the range. + * For example, the statement player.angle = 450 is the same as player.angle = 90. + * + * If you wish to work in radians instead of degrees you can use the property `rotation` instead. + * Working in radians is slightly faster as it doesn't have to perform any calculations. + * + * @property {number} angle + */ + angle: { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); + + }, + + set: function(value) { + + this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. +* +* @class +*/ +Phaser.Component.Animation = function () {}; + +Phaser.Component.Animation.prototype = { + + /** + * Plays an Animation. + * + * The animation should have previously been created via `animations.add`. + * + * If the animation is already playing calling this again won't do anything. + * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. + * + * @method + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation. + */ + play: function (name, frameRate, loop, killOnComplete) { + + if (this.animations) + { + return this.animations.play(name, frameRate, loop, killOnComplete); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. +* It is used by the InWorld component. +* +* @class +*/ +Phaser.Component.AutoCull = function () {}; + +Phaser.Component.AutoCull.prototype = { + + /** + * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. + * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. + * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} autoCull + * @default + */ + autoCull: false, + + /** + * Checks if the Game Objects bounds intersect with the Game Camera bounds. + * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + if (!this.autoCull && !this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + } + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Bounds component contains properties related to the bounds of the Game Object. +* +* @class +*/ +Phaser.Component.Bounds = function () {}; + +Phaser.Component.Bounds.prototype = { + + /** + * The amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * anchor.x`. + * It will only be > 0 if anchor.x is not equal to zero. + * + * @property {number} offsetX + * @readOnly + */ + offsetX: { + + get: function () { + + return this.anchor.x * this.width; + + } + + }, + + /** + * The amount the Game Object is visually offset from its y coordinate. + * This is the same as `height * anchor.y`. + * It will only be > 0 if anchor.y is not equal to zero. + * + * @property {number} offsetY + * @readOnly + */ + offsetY: { + + get: function () { + + return this.anchor.y * this.height; + + } + + }, + + /** + * The local center x coordinate of the Game Object. + * This is the same as `(x - offsetX) + (width / 2)`. + * + * @property {number} centerX + */ + centerX: { + + get: function () { + + return (this.x - this.offsetX) + (this.width * 0.5); + + }, + + set: function (value) { + + this.x = (value + this.offsetX) - (this.width * 0.5); + + } + + }, + + /** + * The local center y coordinate of the Game Object. + * This is the same as `(y - offsetY) + (height / 2)`. + * + * @property {number} centerY + */ + centerY: { + + get: function () { + + return (this.y - this.offsetY) + (this.height * 0.5); + + }, + + set: function (value) { + + this.y = (value + this.offsetY) - (this.height * 0.5); + + } + + }, + + /** + * The left coordinate of the Game Object. + * This is the same as `x - offsetX`. + * + * @property {number} left + */ + left: { + + get: function () { + + return this.x - this.offsetX; + + }, + + set: function (value) { + + this.x = value + this.offsetX; + + } + + }, + + /** + * The right coordinate of the Game Object. + * This is the same as `x + width - offsetX`. + * + * @property {number} right + */ + right: { + + get: function () { + + return (this.x + this.width) - this.offsetX; + + }, + + set: function (value) { + + this.x = value - (this.width) + this.offsetX; + + } + + }, + + /** + * The y coordinate of the Game Object. + * This is the same as `y - offsetY`. + * + * @property {number} top + */ + top: { + + get: function () { + + return this.y - this.offsetY; + + }, + + set: function (value) { + + this.y = value + this.offsetY; + + } + + }, + + /** + * The sum of the y and height properties. + * This is the same as `y + height - offsetY`. + * + * @property {number} bottom + */ + bottom: { + + get: function () { + + return (this.y + this.height) - this.offsetY; + + }, + + set: function (value) { + + this.y = value - (this.height) + this.offsetY; + + } + + }, + + /** + * Aligns this Game Object within another Game Object, or Rectangle, known as the + * 'container', to one of 9 possible positions. + * + * The container must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the container. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, + * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * container, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignIn: function (container, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = container.left - offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = container.centerX + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = container.right + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.left = container.left - offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.CENTER: + this.centerX = container.centerX + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.right = container.right + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = container.left - offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = container.centerX + offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = container.right + offsetX; + this.bottom = container.bottom + offsetY; + break; + } + + return this; + + }, + + /** + * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the + * 'parent', in one of 11 possible positions. + * + * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the parent. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, + * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, + * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * parent, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignTo: function (parent, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = parent.left - offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = parent.centerX + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = parent.right + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.LEFT_TOP: + this.right = parent.left - offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.right = parent.left - offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.LEFT_BOTTOM: + this.right = parent.left - offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.RIGHT_TOP: + this.left = parent.right + offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.left = parent.right + offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.RIGHT_BOTTOM: + this.left = parent.right + offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = parent.left - offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = parent.centerX + offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = parent.right + offsetX; + this.top = parent.bottom + offsetY; + break; + } + + return this; + + } + +}; + +// Phaser.Group extensions + +Phaser.Group.prototype.alignIn = Phaser.Component.Bounds.prototype.alignIn; +Phaser.Group.prototype.alignTo = Phaser.Component.Bounds.prototype.alignTo; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The BringToTop Component features quick access to Group sorting related methods. +* +* @class +*/ +Phaser.Component.BringToTop = function () {}; + +/** +* Brings this Game Object to the top of its parents display list. +* Visually this means it will render over the top of any old child in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.bringToTop = function() { + + if (this.parent) + { + this.parent.bringToTop(this); + } + + return this; + +}; + +/** +* Sends this Game Object to the bottom of its parents display list. +* Visually this means it will render below all other children in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.sendToBack = function() { + + if (this.parent) + { + this.parent.sendToBack(this); + } + + return this; + +}; + +/** +* Moves this Game Object up one place in its parents display list. +* This call has no effect if the Game Object is already at the top of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveUp = function () { + + if (this.parent) + { + this.parent.moveUp(this); + } + + return this; + +}; + +/** +* Moves this Game Object down one place in its parents display list. +* This call has no effect if the Game Object is already at the bottom of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveDown = function () { + + if (this.parent) + { + this.parent.moveDown(this); + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Core Component Features. +* +* @class +*/ +Phaser.Component.Core = function () {}; + +/** + * @property {boolean} skipTypeChecks - Skip type checks in {@link #init}. + * @static + * @default + */ +Phaser.Component.Core.skipTypeChecks = false; + +/** +* Installs / registers mixin components. +* +* The `this` context should be that of the applicable object instance or prototype. +* +* @method +* @protected +*/ +Phaser.Component.Core.install = function (components) { + + // Always install 'Core' first + Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype); + + this.components = {}; + + for (var i = 0; i < components.length; i++) + { + var id = components[i]; + var replace = false; + + if (id === 'Destroy') + { + replace = true; + } + + Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace); + + this.components[id] = true; + } + +}; + +/** +* Initializes the mixin components. +* +* The `this` context should be an instance of the component mixin target. +* +* @method +* @protected +*/ +Phaser.Component.Core.init = function (game, x, y, key, frame) { + + if (!Phaser.Component.Core.skipTypeChecks) + { + if (!(game instanceof Phaser.Game)) + { + throw new Error('The value passed as the `game` argument (' + game + ') is not an instance of Phaser.Game.'); + } + + if (typeof x !== 'number') + { + console.warn('The `x` argument value (%s) should be a number.', x); + x = 0; // This would be done implicitly in position.set(). + } + + if (typeof y !== 'number') + { + console.warn('The `y` argument value (%s) should be a number.', y); + y = 0; // This would be done implicitly in position.set(). + } + } + + this.game = game; + this.key = key; + this.data = {}; + + this.position.set(x, y); + this.world = new Phaser.Point(x, y); + this.previousPosition = new Phaser.Point(x, y); + + this.events = new Phaser.Events(this); + + this._bounds = new Phaser.Rectangle(); + + if (this.components.PhysicsBody) + { + // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype. + this.body = this.body; + } + + if (this.components.Animation) + { + this.animations = new Phaser.AnimationManager(this); + } + + if (this.components.LoadTexture && key !== null) + { + this.loadTexture(key, frame); + } + + if (this.components.FixedToCamera) + { + this.cameraOffset = new Phaser.Point(x, y); + } + +}; + +Phaser.Component.Core.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty); + + if (this.visible) + { + this.renderOrderID = this.game.stage.currentRenderOrderID++; + } + + if (this.animations) + { + this.animations.update(); + } + + if (this.body) + { + this.body.preUpdate(); + } + + this.preUpdateChildren(); + + return true; + +}; + +Phaser.Component.Core.prototype = { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + game: null, + + /** + * A user defined name given to this Game Object. + * This value isn't ever used internally by Phaser, it is meant as a game level property. + * @property {string} name + * @default + */ + name: '', + + /** + * An empty Object that belongs to this Game Object. + * This value isn't ever used internally by Phaser, but may be used by your own code, or + * by Phaser Plugins, to store data that needs to be associated with the Game Object, + * without polluting the Game Object directly. + * @property {Object} data + * @default + */ + data: {}, + + /** + * The components this Game Object has installed. + * @property {object} components + * @protected + */ + components: {}, + + /** + * The z depth of this Game Object within its parent Group. + * No two objects in a Group can have the same z value. + * This value is adjusted automatically whenever the Group hierarchy changes. + * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. + * @property {number} z + * @readOnly + */ + z: 0, + + /** + * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this + * Game Object, or any of its components. + * @see Phaser.Events + * @property {Phaser.Events} events + */ + events: undefined, + + /** + * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. + * Through it you can create, play, pause and stop animations. + * @see Phaser.AnimationManager + * @property {Phaser.AnimationManager} animations + */ + animations: undefined, + + /** + * The key of the image or texture used by this Game Object during rendering. + * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. + * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. + * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. + * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key + */ + key: '', + + /** + * The world coordinates of this Game Object in pixels. + * Depending on where in the display list this Game Object is placed this value can differ from `position`, + * which contains the x/y coordinates relative to the Game Objects parent. + * @property {Phaser.Point} world + */ + world: null, + + /** + * A debug flag designed for use with `Game.enableStep`. + * @property {boolean} debug + * @default + */ + debug: false, + + /** + * The position the Game Object was located in the previous frame. + * @property {Phaser.Point} previousPosition + * @readOnly + */ + previousPosition: null, + + /** + * The rotation the Game Object was in set to in the previous frame. Value is in radians. + * @property {number} previousRotation + * @readOnly + */ + previousRotation: 0, + + /** + * The render order ID is used internally by the renderer and Input Manager and should not be modified. + * This property is mostly used internally by the renderers, but is exposed for the use of plugins. + * @property {number} renderOrderID + * @readOnly + */ + renderOrderID: 0, + + /** + * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. + * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. + * @property {boolean} fresh + * @readOnly + */ + fresh: true, + + /** + * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. + * You can set it directly to allow you to flag an object to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy an object from within one of its own callbacks + * such as with Buttons or other Input events. + * + * @property {boolean} pendingDestroy + */ + pendingDestroy: false, + + /** + * @property {Phaser.Rectangle} _bounds - Internal cache var. + * @private + */ + _bounds: null, + + /** + * @property {boolean} _exists - Internal cache var. + * @private + */ + _exists: true, + + /** + * Controls if this Game Object is processed by the core game loop. + * If this Game Object has a physics body it also controls if its physics body is updated or not. + * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. + * It also toggles the `visible` property to false as well. + * + * Setting `exists` to true will add its physics body back in to the physics world, if it has one. + * It will also set the `visible` property to `true`. + * + * @property {boolean} exists + */ + exists: { + + get: function () { + + return this._exists; + + }, + + set: function (value) { + + if (value) + { + this._exists = true; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.addToWorld(); + } + + this.visible = true; + } + else + { + this._exists = false; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.removeFromWorld(); + } + + this.visible = false; + } + + } + + }, + + /** + * Internal method called by preUpdate. + * + * @method + * @protected + */ + preUpdateChildren: function() { + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + }, + + /** + * Override this method in your own custom objects to handle any update requirements. + * It is called immediately after `preUpdate` and before `postUpdate`. + * Remember if this Game Object has any children you should call update on those too. + * + * @method + */ + update: function() { + + }, + + /** + * Internal method called by the World postUpdate cycle. + * + * @method + * @protected + */ + postUpdate: function() { + + if (this.customRender) + { + this.key.render(); + } + + if (this.components.PhysicsBody) + { + Phaser.Component.PhysicsBody.postUpdate.call(this); + } + + if (this.components.FixedToCamera) + { + Phaser.Component.FixedToCamera.postUpdate.call(this); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, +* which can be updated in real-time. +* +* @class +*/ +Phaser.Component.Crop = function () {}; + +Phaser.Component.Crop.prototype = { + + /** + * The Rectangle used to crop the texture this Game Object uses. + * Set this property via `crop`. + * If you modify this property directly you must call `updateCrop` in order to have the change take effect. + * @property {Phaser.Rectangle} cropRect + * @default + */ + cropRect: null, + + /** + * @property {Phaser.Rectangle} _crop - Internal cache var. + * @private + */ + _crop: null, + + /** + * Crop allows you to crop the texture being used to display this Game Object. + * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. + * + * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, + * or by modifying `cropRect` property directly and then calling `updateCrop`. + * + * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object + * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. + * + * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, + * in which case the values are duplicated to a local object. + * + * @method + * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. + * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. + */ + crop: function (rect, copy) { + + if (copy === undefined) { copy = false; } + + if (rect) + { + if (copy && this.cropRect !== null) + { + this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height); + } + else if (copy && this.cropRect === null) + { + this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height); + } + else + { + this.cropRect = rect; + } + + this.updateCrop(); + } + else + { + this._crop = null; + this.cropRect = null; + + this.resetFrame(); + } + + }, + + /** + * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, + * or the rectangle it references, then you need to update the crop frame by calling this method. + * + * @method + */ + updateCrop: function () { + + if (!this.cropRect) + { + return; + } + + var oldX = this.texture.crop.x; + var oldY = this.texture.crop.y; + var oldW = this.texture.crop.width; + var oldH = this.texture.crop.height; + + this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop); + this._crop.x += this._frame.x; + this._crop.y += this._frame.y; + + var cx = Math.max(this._frame.x, this._crop.x); + var cy = Math.max(this._frame.y, this._crop.y); + var cw = Math.min(this._frame.right, this._crop.right) - cx; + var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy; + + this.texture.crop.x = cx; + this.texture.crop.y = cy; + this.texture.crop.width = cw; + this.texture.crop.height = ch; + + this.texture.frame.width = Math.min(cw, this.cropRect.width); + this.texture.frame.height = Math.min(ch, this.cropRect.height); + + this.texture.width = this.texture.frame.width; + this.texture.height = this.texture.frame.height; + + this.texture._updateUvs(); + + if (this.tint !== 0xffffff && (oldX !== cx || oldY !== cy || oldW !== cw || oldH !== ch)) + { + this.texture.requiresReTint = true; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Delta component provides access to delta values between the Game Objects current and previous position. +* +* @class +*/ +Phaser.Component.Delta = function () {}; + +Phaser.Component.Delta.prototype = { + + /** + * Returns the delta x value. The difference between world.x now and in the previous frame. + * + * The value will be positive if the Game Object has moved to the right or negative if to the left. + * + * @property {number} deltaX + * @readonly + */ + deltaX: { + + get: function() { + + return this.world.x - this.previousPosition.x; + + } + + }, + + /** + * Returns the delta y value. The difference between world.y now and in the previous frame. + * + * The value will be positive if the Game Object has moved down or negative if up. + * + * @property {number} deltaY + * @readonly + */ + deltaY: { + + get: function() { + + return this.world.y - this.previousPosition.y; + + } + + }, + + /** + * Returns the delta z value. The difference between rotation now and in the previous frame. + * + * @property {number} deltaZ - The delta value. + * @readonly + */ + deltaZ: { + + get: function() { + + return this.rotation - this.previousRotation; + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Destroy component is responsible for destroying a Game Object. +* +* @class +*/ +Phaser.Component.Destroy = function () {}; + +Phaser.Component.Destroy.prototype = { + + /** + * As a Game Object runs through its destroy method this flag is set to true, + * and can be checked in any sub-systems or plugins it is being destroyed from. + * @property {boolean} destroyPhase + * @readOnly + */ + destroyPhase: false, + + /** + * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present + * and nulls its reference to `game`, freeing it up for garbage collection. + * + * If this Game Object has the Events component it will also dispatch the `onDestroy` event. + * + * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've + * more than one Game Object sharing the same BaseTexture. + * + * @method + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? + * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. + */ + destroy: function (destroyChildren, destroyTexture) { + + if (this.game === null || this.destroyPhase) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (destroyTexture === undefined) { destroyTexture = false; } + + this.destroyPhase = true; + + if (this.events) + { + this.events.onDestroy$dispatch(this); + } + + if (this.parent) + { + if (this.parent instanceof Phaser.Group) + { + this.parent.remove(this); + } + else + { + this.parent.removeChild(this); + } + } + + if (this.input) + { + this.input.destroy(); + } + + if (this.animations) + { + this.animations.destroy(); + } + + if (this.body) + { + this.body.destroy(); + } + + if (this.events) + { + this.events.destroy(); + } + + this.game.tweens.removeFrom(this); + + var i = this.children.length; + + if (destroyChildren) + { + while (i--) + { + this.children[i].destroy(destroyChildren); + } + } + else + { + while (i--) + { + this.removeChild(this.children[i]); + } + } + + if (this._crop) + { + this._crop = null; + this.cropRect = null; + } + + if (this._frame) + { + this._frame = null; + } + + if (Phaser.Video && this.key instanceof Phaser.Video) + { + this.key.onChangeSource.remove(this.resizeFrame, this); + } + + if (Phaser.BitmapText && this._glyphs) + { + this._glyphs = []; + } + + this.alive = false; + this.exists = false; + this.visible = false; + + this.filters = null; + this.mask = null; + this.game = null; + + this.data = {}; + + // In case Pixi is still going to try and render it even though destroyed + this.renderable = false; + + if (this.transformCallback) + { + this.transformCallback = null; + this.transformCallbackContext = null; + } + + // Pixi level DisplayObject destroy + this.hitArea = null; + this.parent = null; + this.stage = null; + this.worldTransform = null; + this.filterArea = null; + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + // Texture? + if (destroyTexture) + { + this.texture.destroy(true); + } + + this.destroyPhase = false; + this.pendingDestroy = false; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Events component is a collection of events fired by the parent Game Object. +* +* Phaser uses what are known as 'Signals' for all event handling. All of the events in +* this class are signals you can subscribe to, much in the same way you'd "listen" for +* an event. +* +* For example to tell when a Sprite has been added to a new group, you can bind a function +* to the {@link #onAddedToGroup} signal: +* +* `sprite.events.onAddedToGroup.add(yourFunction, this);` +* +* Where `yourFunction` is the function you want called when this event occurs. +* +* For more details about how signals work please see the {@link Phaser.Signal} class. +* +* The Input-related events will only be dispatched if the Sprite has had {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true` +* and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. +* +* @class Phaser.Events +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. +*/ +Phaser.Events = function (sprite) { + + /** + * @property {Phaser.Sprite} parent - The Sprite that owns these events. + */ + this.parent = sprite; + + // The signals are automatically added by the corresponding proxy properties + +}; + +Phaser.Events.prototype = { + + /** + * Removes all events. + * + * @method Phaser.Events#destroy + */ + destroy: function () { + + this._parent = null; + + if (this._onDestroy) { this._onDestroy.dispose(); } + if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } + if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } + if (this._onKilled) { this._onKilled.dispose(); } + if (this._onRevived) { this._onRevived.dispose(); } + if (this._onEnterBounds) { this._onEnterBounds.dispose(); } + if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } + + if (this._onInputOver) { this._onInputOver.dispose(); } + if (this._onInputOut) { this._onInputOut.dispose(); } + if (this._onInputDown) { this._onInputDown.dispose(); } + if (this._onInputUp) { this._onInputUp.dispose(); } + if (this._onDragStart) { this._onDragStart.dispose(); } + if (this._onDragUpdate) { this._onDragUpdate.dispose(); } + if (this._onDragStop) { this._onDragStop.dispose(); } + + if (this._onAnimationStart) { this._onAnimationStart.dispose(); } + if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } + if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } + + }, + + // The following properties are sentinels that will be replaced with getters + + /** + * This signal is dispatched when this Game Object is added to a new {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was added to the Group. + * - {Phaser.Group} The Group it was added to. + * + * @property {Phaser.Signal} onAddedToGroup + */ + onAddedToGroup: null, + + /** + * This signal is dispatched when the Game Object is removed from a {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was removed from the Group. + * - {Phaser.Group} The Group it was removed from. + * + * @property {Phaser.Signal} onRemovedFromGroup + */ + onRemovedFromGroup: null, + + /** + * This signal is dispatched when the Game Object is destroyed. + * This happens when {@link Phaser.Sprite#destroy Sprite.destroy()} is called, or {@link Phaser.Group#destroy Group.destroy()} with `destroyChildren` set to true. + * It is sent one argument: + * + * - {any} The Game Object that was destroyed. + * + * @property {Phaser.Signal} onDestroy + */ + onDestroy: null, + + /** + * This signal is dispatched when the Game Object is killed. + * This happens when {@link Phaser.Sprite#kill Sprite.kill()} is called. + * Please understand the difference between {@link Phaser.Sprite#kill kill} and {@link Phaser.Sprite#destroy destroy} by looking at their respective methods. + * It is sent one argument: + * + * - {any} The Game Object that was killed. + * + * @property {Phaser.Signal} onKilled + */ + onKilled: null, + + /** + * This signal is dispatched when the Game Object is revived from a previously killed state. + * This happens when {@link Phaser.Sprite#revive Sprite.revive()} is called. + * It is sent one argument: + * + * - {any} The Game Object that was revived. + * + * @property {Phaser.Signal} onRevived + */ + onRevived: null, + + /** + * This signal is dispatched when the Game Object leaves the Phaser.World {@link Phaser.World#bounds bounds}. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that left the World bounds. + * + * @property {Phaser.Signal} onOutOfBounds + */ + onOutOfBounds: null, + + /** + * This signal is dispatched when the Game Object returns within the Phaser.World {@link Phaser.World#bounds bounds}, having previously been outside of them. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that entered the World bounds. + * + * @property {Phaser.Signal} onEnterBounds + */ + onEnterBounds: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an over event from a {@link Phaser.Pointer}. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOver + */ + onInputOver: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an out event from a {@link Phaser.Pointer}, which was previously over it. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOut + */ + onInputOut: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives a down event from a {@link Phaser.Pointer}. This effectively means the Pointer has been + * pressed down (but not yet released) on the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputDown + */ + onInputDown: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an up event from a {@link Phaser.Pointer}. This effectively means the Pointer had been + * pressed down, and was then released on the Game Object. + * It is sent three arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {boolean} isOver - Is the Pointer still over the Game Object? + * + * @property {Phaser.Signal} onInputUp + */ + onInputUp: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} starts to drag the Game Object, taking into consideration the various + * drag limitations that may be set. + * It is sent four arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The x coordinate that the drag started from. + * - {number} The y coordinate that the drag started from. + * + * @property {Phaser.Signal} onDragStart + */ + onDragStart: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} is actively dragging the Game Object. + * Be warned: This is a high volume Signal. Be careful what you bind to it. + * It is sent six arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The new x coordinate of the Game Object. + * - {number} The new y coordinate of the Game Object. + * - {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. + * - {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. + * + * @property {Phaser.Signal} onDragUpdate + */ + onDragUpdate: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} stops dragging the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onDragStop + */ + onDragStop: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been played. + * You can also listen to {@link Phaser.Animation#onStart} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was started. + * + * @property {Phaser.Signal} onAnimationStart + */ + onAnimationStart: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been stopped (via {@link Phaser.AnimationManager#stop animation.stop()} and the `dispatchComplete` argument has been set. + * You can also listen to {@link Phaser.Animation#onComplete} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was stopped. + * + * @property {Phaser.Signal} onAnimationComplete + */ + onAnimationComplete: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has looped playback. + * You can also listen to {@link Phaser.Animation#onLoop} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that looped. + * + * @property {Phaser.Signal} onAnimationLoop + */ + onAnimationLoop: null + +}; + +Phaser.Events.prototype.constructor = Phaser.Events; + +// Create an auto-create proxy getter and dispatch method for all events. +// The backing property is the same as the event name, prefixed with '_' +// and the dispatch method is the same as the event name postfixed with '$dispatch'. +for (var prop in Phaser.Events.prototype) +{ + if (!Phaser.Events.prototype.hasOwnProperty(prop) || + prop.indexOf('on') !== 0 || + Phaser.Events.prototype[prop] !== null) + { + continue; + } + + (function (prop, backing) { + 'use strict'; + + // The accessor creates a new Signal; and so it should only be used from user-code. + Object.defineProperty(Phaser.Events.prototype, prop, { + get: function () { + return this[backing] || (this[backing] = new Phaser.Signal()); + } + }); + + // The dispatcher will only broadcast on an already-created signal; call this internally. + Phaser.Events.prototype[prop + '$dispatch'] = function () { + return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; + }; + + })(prop, '_' + prop); + +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless +* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. +* +* @class +*/ +Phaser.Component.FixedToCamera = function () {}; + +/** + * The FixedToCamera component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.FixedToCamera.postUpdate = function () { + + if (this.fixedToCamera) + { + 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.Component.FixedToCamera.prototype = { + + /** + * @property {boolean} _fixedToCamera + * @private + */ + _fixedToCamera: false, + + /** + * A Game Object that is "fixed" to the camera is rendered at a given x/y offsets from the top left of the camera. The offsets + * are stored in the `cameraOffset` property, which is initialized with the current object coordinates. + * + * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. + * + * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world + * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times + * regardless where in the world the camera is. + * + * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. + * + * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. + * + * @property {boolean} fixedToCamera + */ + fixedToCamera: { + + get: function () { + + return this._fixedToCamera; + + }, + + set: function (value) { + + if (value) + { + this._fixedToCamera = true; + this.cameraOffset.set(this.x, this.y); + } + else + { + this._fixedToCamera = false; + } + + } + + }, + + /** + * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. + * + * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. + * @property {Phaser.Point} cameraOffset + */ + cameraOffset: new Phaser.Point() + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Health component provides the ability for Game Objects to have a `health` property +* that can be damaged and reset through game code. +* Requires the LifeSpan component. +* +* @class +*/ +Phaser.Component.Health = function () {}; + +Phaser.Component.Health.prototype = { + + /** + * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. + * + * It can be used in combination with the `damage` method or modified directly. + * + * @property {number} health + * @default + */ + health: 1, + + /** + * The Game Objects maximum health value. This works in combination with the `heal` method to ensure + * the health value never exceeds the maximum. + * + * @property {number} maxHealth + * @default + */ + maxHealth: 100, + + /** + * Damages the Game Object. This removes the given amount of health from the `health` property. + * + * If health is taken below or is equal to zero then the `kill` method is called. + * + * @method + * @param {number} amount - The amount to subtract from the current `health` value. + * @return {Phaser.Sprite} This instance. + */ + damage: function (amount) { + + if (this.alive) + { + this.health -= amount; + + if (this.health <= 0) + { + this.kill(); + } + } + + return this; + + }, + + /** + * Sets the health property of the Game Object to the given amount. + * Will never exceed the `maxHealth` value. + * + * @method + * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + setHealth: function (amount) { + + this.health = amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + + return this; + + }, + + /** + * Heal the Game Object. This adds the given amount of health to the `health` property. + * + * @method + * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + heal: function (amount) { + + if (this.alive) + { + this.health += amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InCamera component checks if the Game Object intersects with the Game Camera. +* +* @class +*/ +Phaser.Component.InCamera = function () {}; + +Phaser.Component.InCamera.prototype = { + + /** + * Checks if this Game Objects bounds intersects with the Game Cameras bounds. + * + * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. + * + * An object outside the bounds can be considered for camera culling if it has the AutoCull component. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. +* +* @class +*/ +Phaser.Component.InputEnabled = function () {}; + +Phaser.Component.InputEnabled.prototype = { + + /** + * The Input Handler for this Game Object. + * + * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. + * + * After you have done this, this property will be a reference to the Phaser InputHandler. + * @property {Phaser.InputHandler|null} input + */ + input: null, + + /** + * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created + * for this Game Object and it will then start to process click / touch events and more. + * + * You can then access the Input Handler via `this.input`. + * + * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. + * + * If you set this property to false it will stop the Input Handler from processing any more input events. + * + * If you want to _temporarily_ disable input for a Game Object, then it's better to set + * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. + * You can then toggle this back on as needed. + * + * @property {boolean} inputEnabled + */ + inputEnabled: { + + get: function () { + + return (this.input && this.input.enabled); + + }, + + set: function (value) { + + if (value) + { + if (this.input === null) + { + this.input = new Phaser.InputHandler(this); + this.input.start(); + } + else if (this.input && !this.input.enabled) + { + this.input.start(); + } + } + else + { + if (this.input && this.input.enabled) + { + this.input.stop(); + } + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InWorld component checks if a Game Object is within the Game World Bounds. +* An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. +* If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. +* +* @class +*/ +Phaser.Component.InWorld = function () {}; + +/** + * The InWorld component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.InWorld.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + // Cache the bounds if we need it + if (this.autoCull || this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + + if (this.autoCull) + { + // Won't get rendered but will still get its transform updated + if (this.game.world.camera.view.intersects(this._bounds)) + { + this.renderable = true; + this.game.world.camera.totalInView++; + } + else + { + this.renderable = false; + + if (this.outOfCameraBoundsKill) + { + this.kill(); + return false; + } + } + } + + if (this.checkWorldBounds) + { + // The Sprite is already out of the world bounds, so let's check to see if it has come back again + if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds)) + { + this._outOfBoundsFired = false; + this.events.onEnterBounds$dispatch(this); + } + else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds)) + { + // The Sprite WAS in the screen, but has now left. + this._outOfBoundsFired = true; + this.events.onOutOfBounds$dispatch(this); + + if (this.outOfBoundsKill) + { + this.kill(); + return false; + } + } + } + } + + return true; + +}; + +Phaser.Component.InWorld.prototype = { + + /** + * If this is set to `true` the Game Object checks if it is within the World bounds each frame. + * + * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. + * + * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. + * + * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. + * + * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} checkWorldBounds + * @default + */ + checkWorldBounds: false, + + /** + * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. + * + * @property {boolean} outOfBoundsKill + * @default + */ + outOfBoundsKill: false, + + /** + * If this and the `autoCull` property are both set to `true`, then the `kill` method + * is called as soon as the Game Object leaves the camera bounds. + * + * @property {boolean} outOfCameraBoundsKill + * @default + */ + outOfCameraBoundsKill: false, + + /** + * @property {boolean} _outOfBoundsFired - Internal state var. + * @private + */ + _outOfBoundsFired: false, + + /** + * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. + * + * @property {boolean} inWorld + * @readonly + */ + inWorld: { + + get: function () { + + return this.game.world.bounds.intersects(this.getBounds()); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* LifeSpan Component Features. +* +* @class +*/ +Phaser.Component.LifeSpan = function () {}; + +/** + * The LifeSpan component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.LifeSpan.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.lifespan > 0) + { + this.lifespan -= this.game.time.physicsElapsedMS; + + if (this.lifespan <= 0) + { + this.kill(); + return false; + } + } + + return true; + +}; + +Phaser.Component.LifeSpan.prototype = { + + /** + * A useful flag to control if the Game Object is alive or dead. + * + * This is set automatically by the Health components `damage` method should the object run out of health. + * Or you can toggle it via your game code. + * + * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. + * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. + * @property {boolean} alive + * @default + */ + alive: true, + + /** + * The lifespan allows you to give a Game Object a lifespan in milliseconds. + * + * Once the Game Object is 'born' you can set this to a positive value. + * + * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. + * When it reaches zero it will call the `kill` method. + * + * Very handy for particles, bullets, collectibles, or any other short-lived entity. + * + * @property {number} lifespan + * @default + */ + lifespan: 0, + + /** + * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. + * + * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. + * + * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. + * + * @method + * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. + * @return {PIXI.DisplayObject} This instance. + */ + revive: function (health) { + + if (health === undefined) { health = 100; } + + this.alive = true; + this.exists = true; + this.visible = true; + + if (typeof this.setHealth === 'function') + { + this.setHealth(health); + } + + if (this.events) + { + this.events.onRevived$dispatch(this); + } + + return this; + + }, + + /** + * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. + * + * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. + * + * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, + * it doesn't destroy the object or free it up from memory. + * + * If you don't need this Game Object any more you should call `destroy` instead. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ + kill: function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + if (this.events) + { + this.events.onKilled$dispatch(this); + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. +* +* @class +*/ +Phaser.Component.LoadTexture = function () {}; + +Phaser.Component.LoadTexture.prototype = { + + /** + * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) + * @private + */ + customRender: false, + + /** + * @property {Phaser.Rectangle} _frame - Internal cache var. + * @private + */ + _frame: null, + + /** + * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. + * + * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. + * + * You should only use `loadTexture` if you want to replace the base texture entirely. + * + * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. + * + * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. + * Doing this then sets the key to be the `frame` argument (the frame is set to zero). + * + * This allows you to create sprites using `load.image` during development, and then change them + * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' + * and swapping it to be the key of the atlas data. + * + * Note: You cannot use a RenderTexture as a texture for a TileSprite. + * + * @method + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. + */ + loadTexture: function (key, frame, stopAnimation) { + + if (key === Phaser.PENDING_ATLAS) + { + key = frame; + frame = 0; + } + else + { + frame = frame || 0; + } + + if ((stopAnimation || stopAnimation === undefined) && this.animations) + { + this.animations.stop(); + } + + this.key = key; + this.customRender = false; + var cache = this.game.cache; + + var setFrame = true; + var smoothed = !this.texture.baseTexture.scaleMode; + + if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture) + { + this.key = key.key; + this.setTexture(key); + } + else if (Phaser.BitmapData && key instanceof Phaser.BitmapData) + { + this.customRender = true; + + this.setTexture(key.texture); + + if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA)) + { + setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame); + } + else + { + setFrame = !this.animations.loadFrameData(key.frameData, 0); + } + } + else if (Phaser.Video && key instanceof Phaser.Video) + { + this.customRender = true; + + // This works from a reference, which probably isn't what we need here + var valid = key.texture.valid; + this.setTexture(key.texture); + this.setFrame(key.texture.frame.clone()); + key.onChangeSource.add(this.resizeFrame, this); + this.texture.valid = valid; + } + else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer) + { + // this.customRender = true; + + this.setTexture(PIXI.Texture.fromCanvas(key.canvas)); + } + else if (key instanceof PIXI.Texture) + { + this.setTexture(key); + } + else + { + var img = cache.getImage(key, true); + + this.key = img.key; + this.setTexture(new PIXI.Texture(img.base)); + + if (key === '__default') + { + this.texture.baseTexture.skipRender = true; + } + else + { + this.texture.baseTexture.skipRender = false; + } + + setFrame = !this.animations.loadFrameData(img.frameData, frame); + } + + if (setFrame) + { + this._frame = Phaser.Rectangle.clone(this.texture.frame); + } + + if (!smoothed) + { + this.texture.baseTexture.scaleMode = 1; + } + + }, + + /** + * Sets the texture frame the Game Object uses for rendering. + * + * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. + * + * @method + * @param {Phaser.Frame} frame - The Frame to be used by the texture. + */ + setFrame: function (frame) { + + this._frame = frame; + + this.texture.frame.x = frame.x; + this.texture.frame.y = frame.y; + this.texture.frame.width = frame.width; + this.texture.frame.height = frame.height; + + this.texture.crop.x = frame.x; + this.texture.crop.y = frame.y; + this.texture.crop.width = frame.width; + this.texture.crop.height = frame.height; + + if (frame.trimmed) + { + if (this.texture.trim) + { + this.texture.trim.x = frame.spriteSourceSizeX; + this.texture.trim.y = frame.spriteSourceSizeY; + this.texture.trim.width = frame.sourceSizeW; + this.texture.trim.height = frame.sourceSizeH; + } + else + { + this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH }; + } + + this.texture.width = frame.sourceSizeW; + this.texture.height = frame.sourceSizeH; + this.texture.frame.width = frame.sourceSizeW; + this.texture.frame.height = frame.sourceSizeH; + } + else if (!frame.trimmed && this.texture.trim) + { + this.texture.trim = null; + } + + if (frame.rotated) + { + this.texture.rotated = true; + } + + if (this.cropRect) + { + this.updateCrop(); + } + + this.texture.requiresReTint = true; + + this.texture._updateUvs(); + + if (this.tilingTexture) + { + this.refreshTexture = true; + } + + }, + + /** + * Resizes the Frame dimensions that the Game Object uses for rendering. + * + * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData + * it can be useful to adjust the dimensions directly in this way. + * + * @method + * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. + * @param {integer} width - The new width of the texture. + * @param {integer} height - The new height of the texture. + */ + resizeFrame: function (parent, width, height) { + + this.texture.frame.resize(width, height); + this.texture.setFrame(this.texture.frame); + + }, + + /** + * Resets the texture frame dimensions that the Game Object uses for rendering. + * + * @method + */ + resetFrame: function () { + + if (this._frame) + { + this.setFrame(this._frame); + } + + }, + + /** + * Gets or sets the current frame index of the texture being used to render this Game Object. + * + * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, + * for example: `player.frame = 4`. + * + * If the frame index given doesn't exist it will revert to the first frame found in the texture. + * + * If you are using a texture atlas then you should use the `frameName` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {integer} frame + */ + frame: { + + get: function () { + return this.animations.frame; + }, + + set: function (value) { + this.animations.frame = value; + } + + }, + + /** + * Gets or sets the current frame name of the texture being used to render this Game Object. + * + * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, + * for example: `player.frameName = "idle"`. + * + * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. + * + * If you are using a sprite sheet then you should use the `frame` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {string} frameName + */ + frameName: { + + get: function () { + return this.animations.frameName; + }, + + set: function (value) { + this.animations.frameName = value; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. +* +* @class +*/ +Phaser.Component.Overlap = function () {}; + +Phaser.Component.Overlap.prototype = { + + /** + * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, + * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. + * + * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. + * + * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. + * It should be fine for low-volume testing where physics isn't required. + * + * @method + * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. + * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. + */ + overlap: function (displayObject) { + + return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds()); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The PhysicsBody component manages the Game Objects physics body and physics enabling. +* It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. +* +* @class +*/ +Phaser.Component.PhysicsBody = function () {}; + +/** + * The PhysicsBody component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.fresh && 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.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (this.body) + { + this.body.preUpdate(); + } + + this.fresh = false; + + this.preUpdateChildren(); + + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this._exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + return true; + +}; + +/** + * The PhysicsBody component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.postUpdate = function () { + + if (this.exists && this.body) + { + this.body.postUpdate(); + } + +}; + +Phaser.Component.PhysicsBody.prototype = { + + /** + * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated + * properties and methods via it. + * + * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. + * + * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object + * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. + * + * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. + * + * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, + * so the physics body is centered on the Game Object. + * + * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. + * + * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body + * @default + */ + body: null, + + /** + * The position of the Game Object on the x axis relative to the local coordinates of the parent. + * + * @property {number} x + */ + x: { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + }, + + /** + * The position of the Game Object on the y axis relative to the local coordinates of the parent. + * + * @property {number} y + */ + y: { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Reset component allows a Game Object to be reset and repositioned to a new location. +* +* @class +*/ +Phaser.Component.Reset = function () {}; + +/** +* Resets the Game Object. +* +* This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, +* `visible` and `renderable` to true. +* +* If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. +* +* If this Game Object has a Physics Body it will reset the Body. +* +* @method +* @param {number} x - The x coordinate (in world space) to position the Game Object at. +* @param {number} y - The y coordinate (in world space) to position the Game Object at. +* @param {number} [health=1] - The health to give the Game Object if it has the Health component. +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.Reset.prototype.reset = function (x, y, health) { + + if (health === undefined) { health = 1; } + + this.world.set(x, y); + this.position.set(x, y); + + this.fresh = true; + this.exists = true; + this.visible = true; + this.renderable = true; + + if (this.components.InWorld) + { + this._outOfBoundsFired = false; + } + + if (this.components.LifeSpan) + { + this.alive = true; + this.health = health; + } + + if (this.components.PhysicsBody) + { + if (this.body) + { + this.body.reset(x, y, false, false); + } + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. +* +* @class +*/ +Phaser.Component.ScaleMinMax = function () {}; + +Phaser.Component.ScaleMinMax.prototype = { + + /** + * The callback that will apply any scale limiting to the worldTransform. + * @property {function} transformCallback + */ + transformCallback: null, + + /** + * The context under which `transformCallback` is called. + * @property {object} transformCallbackContext + */ + transformCallbackContext: this, + + /** + * The minimum scale this Game Object will scale down to. + * + * It allows you to prevent a parent from scaling this Game Object lower than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMin + */ + scaleMin: null, + + /** + * The maximum scale this Game Object will scale up to. + * + * It allows you to prevent a parent from scaling this Game Object higher than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMax + */ + scaleMax: null, + + /** + * Adjust scaling limits, if set, to this Game Object. + * + * @method + * @private + * @param {Phaser.Matrix} wt - The updated worldTransform matrix. + */ + checkTransform: function (wt) { + + if (this.scaleMin) + { + if (wt.a < this.scaleMin.x) + { + wt.a = this.scaleMin.x; + } + + if (wt.d < this.scaleMin.y) + { + wt.d = this.scaleMin.y; + } + } + + if (this.scaleMax) + { + if (wt.a > this.scaleMax.x) + { + wt.a = this.scaleMax.x; + } + + if (wt.d > this.scaleMax.y) + { + wt.d = this.scaleMax.y; + } + } + + }, + + /** + * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. + * + * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored + * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. + * + * By setting these values you can carefully control how Game Objects deal with responsive scaling. + * + * If only one parameter is given then that value will be used for both scaleMin and scaleMax: + * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 + * + * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: + * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 + * + * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, + * or pass `null` for the `maxX` and `maxY` parameters. + * + * Call `setScaleMinMax(null)` to clear all previously set values. + * + * @method + * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to. + * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to. + * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to. + * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to. + */ + setScaleMinMax: function (minX, minY, maxX, maxY) { + + if (minY === undefined) + { + // 1 parameter, set all to it + minY = maxX = maxY = minX; + } + else if (maxX === undefined) + { + // 2 parameters, the first is min, the second max + maxX = maxY = minY; + minY = minX; + } + + if (minX === null) + { + this.scaleMin = null; + } + else + { + if (this.scaleMin) + { + this.scaleMin.set(minX, minY); + } + else + { + this.scaleMin = new Phaser.Point(minX, minY); + } + } + + if (maxX === null) + { + this.scaleMax = null; + } + else + { + if (this.scaleMax) + { + this.scaleMax.set(maxX, maxY); + } + else + { + this.scaleMax = new Phaser.Point(maxX, maxY); + } + } + + if (this.scaleMin === null) + { + this.transformCallback = null; + } + else + { + this.transformCallback = this.checkTransform; + this.transformCallbackContext = this; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. +* +* @class +*/ +Phaser.Component.Smoothed = function () {}; + +Phaser.Component.Smoothed.prototype = { + + /** + * Enable or disable texture smoothing for this Game Object. + * + * It only takes effect if the Game Object is using an image based texture. + * + * Smoothing is enabled by default. + * + * @property {boolean} smoothed + */ + smoothed: { + + get: function () { + + return !this.texture.baseTexture.scaleMode; + + }, + + set: function (value) { + + if (value) + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 0; + this.texture.baseTexture.dirty(); + } + } + else + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 1; + this.texture.baseTexture.dirty(); + } + } + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectFactory is a quick way to create many common game objects +* using {@linkcode Phaser.Game#add `game.add`}. +* +* Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group. +* +* @class Phaser.GameObjectFactory +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectFactory = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectFactory.prototype = { + + /** + * Adds an existing display object to the game world. + * + * @method Phaser.GameObjectFactory#existing + * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object. + * @return {any} The child that was added to the World. + */ + existing: function (object) { + + return this.world.add(object); + + }, + + /** + * Weapons provide the ability to easily create a bullet pool and manager. + * + * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. + * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. + * + * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you + * can usually do with a Group, such as move it around the display list, iterate it, etc can be done + * to the bullets Group too. + * + * Bullets can have textures and even animations. You can control the speed at which they are fired, + * the firing rate, the firing angle, and even set things like gravity for them. + * + * @method Phaser.GameObjectFactory#weapon + * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group. + * @param {function} [bulletClass] - The Class of the bullets that are launched by this Weapon. See {@link Phaser.Weapon#bulletClass} + * @returns {Phaser.Weapon} A Weapon instance. + */ + weapon: function (quantity, key, frame, group, bulletClass) { + + var weapon = this.game.plugins.add(Phaser.Weapon); + + if (bulletClass) + { + weapon.bulletClass = bulletClass; + } + + weapon.createBullets(quantity, key, frame, group); + + return weapon; + + }, + + /** + * Create a new `Image` object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * + * It can still rotate, scale, crop and receive input events. + * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectFactory#image + * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Image} The newly created Image object. + */ + image: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Image(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. + * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), + * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. + * + * @method Phaser.GameObjectFactory#sprite + * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Sprite} The newly created Sprite object. + */ + sprite: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Sprite(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Creature Animation object. + * + * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. + * + * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). + * + * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. + * + * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them + * loaded before your Phaser game boots. + * + * See the Phaser custom build process for more details. + * + * @method Phaser.GameObjectFactory#creature + * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Creature} The newly created Creature object. + */ + creature: function (x, y, key, mesh, group) { + + if (group === undefined) { group = this.world; } + + var obj = new Phaser.Creature(this.game, x, y, key, mesh); + + group.add(obj); + + return obj; + + }, + + /** + * Create a tween on a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectFactory#tween + * @param {object} object - Object the tween will be run on. + * @return {Phaser.Tween} The newly created Phaser.Tween object. + */ + tween: function (object) { + + return this.game.tweens.create(object); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectFactory#group + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates + * are automatically given a physics body. + * + * @method Phaser.GameObjectFactory#physicsGroup + * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc. + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.Group} The newly created Group. + */ + physicsGroup: function (physicsBodyType, parent, name, addToStage) { + + return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType); + + }, + + /** + * A SpriteBatch is a really fast version of a Phaser Group built solely for speed. + * Use when you need a lot of sprites or particles all sharing the same texture. + * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. + * + * @method Phaser.GameObjectFactory#spriteBatch + * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. + * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. + * @return {Phaser.SpriteBatch} The newly created Sprite Batch. + */ + spriteBatch: function (parent, name, addToStage) { + + if (parent === undefined) { parent = null; } + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectFactory#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectFactory#tileSprite + * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TileSprite} The newly created TileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); + + }, + + /** + * Creates a new Rope object. + * + * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js + * + * @method Phaser.GameObjectFactory#rope + * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Array} points - An array of {Phaser.Point}. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Rope} The newly created Rope object. + */ + rope: function (x, y, key, frame, points, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Rope(this.game, x, y, key, frame, points)); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectFactory#text + * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {string} [text=''] - The text string that will be displayed. + * @param {object} [style] - The style object containing style attributes like font, font size , etc. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Text(this.game, x, y, text, style)); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectFactory#button + * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] - The function to call when this button is pressed + * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Button} The newly created Button object. + */ + button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectFactory#graphics + * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Graphics(this.game, x, y)); + + }, + + /** + * Create a new Emitter. + * + * A particle emitter can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accordingly. + * + * @method Phaser.GameObjectFactory#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles)); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectFactory#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectFactory#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size)); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectFactory#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {Phaser.Tilemap} The newly created tilemap object. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectFactory#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a Video object. + * + * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. + * + * @method Phaser.GameObjectFactory#video + * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. + * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) + * @return {Phaser.Video} The newly created Video object. + */ + video: function (key, url) { + + return new Phaser.Video(this.game, key, url); + + }, + + /** + * Create a BitmapData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectFactory#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectFactory#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + }, + + /** + * Add a new Plugin into the PluginManager. + * + * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.GameObjectFactory#plugin + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + plugin: function (plugin) { + + return this.game.plugins.add(plugin); + + } + +}; + +Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world. +* The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}. +* +* @class Phaser.GameObjectCreator +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectCreator = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectCreator.prototype = { + + /** + * Create a new Image object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectCreator#image + * @param {number} x - X position of the image. + * @param {number} y - Y position of the image. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Image} the newly created sprite object. + */ + image: function (x, y, key, frame) { + + return new Phaser.Image(this.game, x, y, key, frame); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * @method Phaser.GameObjectCreator#sprite + * @param {number} x - X position of the new sprite. + * @param {number} y - Y position of the new sprite. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Sprite} the newly created sprite object. + */ + sprite: function (x, y, key, frame) { + + return new Phaser.Sprite(this.game, x, y, key, frame); + + }, + + /** + * Create a tween object for a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectCreator#tween + * @param {object} obj - Object the tween will be run on. + * @return {Phaser.Tween} The Tween object. + */ + tween: function (obj) { + + return new Phaser.Tween(obj, this.game, this.game.tweens); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectCreator#group + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * Create a new SpriteBatch. + * + * @method Phaser.GameObjectCreator#spriteBatch + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.SpriteBatch} The newly created group. + */ + spriteBatch: function (parent, name, addToStage) { + + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectCreator#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectCreator#tileSprite + * @param {number} x - The x coordinate (in world space) to position the TileSprite at. + * @param {number} y - The y coordinate (in world space) to position the TileSprite at. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.TileSprite} The newly created tileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame) { + + return new Phaser.TileSprite(this.game, x, y, width, height, key, frame); + + }, + + /** + * Creates a new Rope object. + * + * @method Phaser.GameObjectCreator#rope + * @param {number} x - The x coordinate (in world space) to position the Rope at. + * @param {number} y - The y coordinate (in world space) to position the Rope at. + * @param {number} width - The width of the Rope. + * @param {number} height - The height of the Rope. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.Rope} The newly created rope object. + */ + rope: function (x, y, key, frame, points) { + + return new Phaser.Rope(this.game, x, y, key, frame, points); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectCreator#text + * @param {number} x - X position of the new text object. + * @param {number} y - Y position of the new text object. + * @param {string} text - The actual text that will be written. + * @param {object} style - The style object containing style attributes like font, font size , etc. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style) { + + return new Phaser.Text(this.game, x, y, text, style); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectCreator#button + * @param {number} [x] X position of the new button object. + * @param {number} [y] Y position of the new button object. + * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] The function to call when this button is pressed + * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @return {Phaser.Button} The newly created button object. + */ + 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); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectCreator#graphics + * @param {number} [x=0] - X position of the new graphics object. + * @param {number} [y=0] - Y position of the new graphics object. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y) { + + return new Phaser.Graphics(this.game, x, y); + + }, + + /** + * Creat a new Emitter. + * + * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accorindgly. + * + * @method Phaser.GameObjectCreator#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectCreator#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectCreator#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, align) { + + return new Phaser.BitmapText(this.game, x, y, font, text, size, align); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectCreator#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectCreator#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a BitmpaData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectCreator#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectCreator#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + } + +}; + +Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Sprites are the lifeblood of your game, used for nearly everything visual. +* +* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. +* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), +* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. +* +* @class Phaser.Sprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. If this argument is omitted, the sprite will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Sprite = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.SPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Sprite.prototype.constructor = Phaser.Sprite; + +Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.Sprite +* @return {boolean} True if the Sprite was rendered, otherwise false. +*/ +Phaser.Sprite.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image is a light-weight object you can use to display anything that doesn't need health, physics, or complex position monitoring. +* +* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. +* +* @class Phaser.Image +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. If this argument is omitted, the image will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Image = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.IMAGE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Image.prototype.constructor = Phaser.Image; + +Phaser.Component.Core.install.call(Phaser.Image.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Image.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Image#preUpdate +* @memberof Phaser.Image +*/ +Phaser.Image.prototype.preUpdate = function() { + + if (!this.preUpdateInWorld() || !this.preUpdateLifeSpan()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. +* +* The four states a Button responds to are: +* +* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. +* * 'Out' - when the Pointer that was previously over the Button moves out of it. +* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. +* * 'Up' - when the Pointer that was pressed down on the Button is released again. +* +* A different texture/frame and activation sound can be specified for any of the states. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. +* +* @class Phaser.Button +* @constructor +* @extends Phaser.Image +* @param {Phaser.Game} game Current game instance. +* @param {number} [x=0] - X position of the Button. +* @param {number} [y=0] - Y position of the Button. +* @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button. +* @param {function} [callback] - The function to call when this Button is pressed, receiving `this` (the Button), `pointer`, and `isOver` (see {@link Phaser.Events#onInputUp}.) +* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) { + + x = x || 0; + y = y || 0; + key = key || null; + callback = callback || null; + callbackContext = callbackContext || this; + + Phaser.Image.call(this, game, x, y, key, outFrame); + + /** + * The Phaser Object Type. + * @property {number} type + * @readonly + */ + this.type = Phaser.BUTTON; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * The name or ID of the Over state frame. + * @property {string|integer} onOverFrame + * @private + */ + this._onOverFrame = null; + + /** + * The name or ID of the Out state frame. + * @property {string|integer} onOutFrame + * @private + */ + this._onOutFrame = null; + + /** + * The name or ID of the Down state frame. + * @property {string|integer} onDownFrame + * @private + */ + this._onDownFrame = null; + + /** + * The name or ID of the Up state frame. + * @property {string|integer} onUpFrame + * @private + */ + this._onUpFrame = null; + + /** + * The Sound to be played when this Buttons Over state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound + * @readonly + */ + this.onOverSound = null; + + /** + * The Sound to be played when this Buttons Out state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound + * @readonly + */ + this.onOutSound = null; + + /** + * The Sound to be played when this Buttons Down state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound + * @readonly + */ + this.onDownSound = null; + + /** + * The Sound to be played when this Buttons Up state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound + * @readonly + */ + this.onUpSound = null; + + /** + * The Sound Marker used in conjunction with the onOverSound. + * @property {string} onOverSoundMarker + * @readonly + */ + this.onOverSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onOutSound. + * @property {string} onOutSoundMarker + * @readonly + */ + this.onOutSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onDownSound. + * @property {string} onDownSoundMarker + * @readonly + */ + this.onDownSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onUpSound. + * @property {string} onUpSoundMarker + * @readonly + */ + this.onUpSoundMarker = ''; + + /** + * The Signal (or event) dispatched when this Button is in an Over state. + * @property {Phaser.Signal} onInputOver + */ + this.onInputOver = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Out state. + * @property {Phaser.Signal} onInputOut + */ + this.onInputOut = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Down state. + * @property {Phaser.Signal} onInputDown + */ + this.onInputDown = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Up state. + * @property {Phaser.Signal} onInputUp + */ + this.onInputUp = new Phaser.Signal(); + + /** + * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. + * The frame will still be changed as applicable. + * + * @property {boolean} onOverMouseOnly + * @default + */ + this.onOverMouseOnly = true; + + /** + * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}. + * + * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. + * + * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR + */ + this.justReleasedPreventsOver = Phaser.PointerMode.CONTACT; + + /** + * When true the the texture frame will not be automatically switched on up/down/over/out events. + * @property {boolean} freezeFrames + * @default + */ + this.freezeFrames = false; + + /** + * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". + * + * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control. + * + * @property {boolean|Phaser.PointerMode} forceOut=false + * @default + */ + this.forceOut = false; + + this.inputEnabled = true; + + this.input.start(0, true); + + this.input.useHandCursor = true; + + this.setFrames(overFrame, outFrame, downFrame, upFrame); + + if (callback !== null) + { + this.onInputUp.add(callback, callbackContext); + } + + // Redirect the input events to here so we can handle animation updates, etc + this.events.onInputOver.add(this.onInputOverHandler, this); + this.events.onInputOut.add(this.onInputOutHandler, this); + this.events.onInputDown.add(this.onInputDownHandler, this); + this.events.onInputUp.add(this.onInputUpHandler, this); + +}; + +Phaser.Button.prototype = Object.create(Phaser.Image.prototype); +Phaser.Button.prototype.constructor = Phaser.Button; + +// State constants; local only. These are tied to property names in Phaser.Button. +var STATE_OVER = 'Over'; +var STATE_OUT = 'Out'; +var STATE_DOWN = 'Down'; +var STATE_UP = 'Up'; + +/** +* Clears all of the frames set on this Button. +* +* @method Phaser.Button#clearFrames +*/ +Phaser.Button.prototype.clearFrames = function () { + + this.setFrames(null, null, null, null); + +}; + +/** +* Set the frame name/ID for the given state. +* +* @method Phaser.Button#setStateFrame +* @private +* @param {object} state - See `STATE_*` +* @param {number|string} frame - The number or string representing the frame. +* @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true. +*/ +Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately) +{ + var frameKey = '_on' + state + 'Frame'; + + if (frame !== null) // not null or undefined + { + this[frameKey] = frame; + + if (switchImmediately) + { + this.changeStateFrame(state); + } + } + else + { + this[frameKey] = null; + } + +}; + +/** +* Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen". +* +* @method Phaser.Button#changeStateFrame +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if the frame was assigned a value, possibly the same one it already had. +*/ +Phaser.Button.prototype.changeStateFrame = function (state) { + + if (this.freezeFrames) + { + return false; + } + + var frameKey = '_on' + state + 'Frame'; + var frame = this[frameKey]; + + if (typeof frame === 'string') + { + this.frameName = frame; + return true; + } + else if (typeof frame === 'number') + { + this.frame = frame; + return true; + } + else + { + return false; + } + +}; + +/** +* Used to manually set the frames that will be used for the different states of the Button. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. +* +* @method Phaser.Button#setFrames +* @public +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) { + + this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver()); + this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver()); + this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown()); + this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp()); + +}; + +/** +* Set the sound/marker for the given state. +* +* @method Phaser.Button#setStateSound +* @private +* @param {object} state - See `STATE_*` +* @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound. +* @param {string} [marker=''] - Sound marker. +*/ +Phaser.Button.prototype.setStateSound = function (state, sound, marker) { + + var soundKey = 'on' + state + 'Sound'; + var markerKey = 'on' + state + 'SoundMarker'; + + if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite) + { + this[soundKey] = sound; + this[markerKey] = typeof marker === 'string' ? marker : ''; + } + else + { + this[soundKey] = null; + this[markerKey] = ''; + } + +}; + +/** +* Play the sound for the given state, _if_ the state has a sound assigned. +* +* @method Phaser.Button#playStateSound +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if a sound was played. +*/ +Phaser.Button.prototype.playStateSound = function (state) { + + var soundKey = 'on' + state + 'Sound'; + var sound = this[soundKey]; + + if (sound) + { + var markerKey = 'on' + state + 'SoundMarker'; + var marker = this[markerKey]; + + sound.play(marker); + return true; + } + else + { + return false; + } + +}; + +/** +* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. +* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. +* +* Call this function with no parameters to reset all sounds on this Button. +* +* @method Phaser.Button#setSounds +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound. +* @param {string} [overMarker] - Over Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound. +* @param {string} [downMarker] - Down Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound. +* @param {string} [outMarker] - Out Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound. +* @param {string} [upMarker] - Up Button Sound Marker. +*/ +Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) { + + this.setStateSound(STATE_OVER, overSound, overMarker); + this.setStateSound(STATE_OUT, outSound, outMarker); + this.setStateSound(STATE_DOWN, downSound, downMarker); + this.setStateSound(STATE_UP, upSound, upMarker); + +}; + +/** +* The Sound to be played when a Pointer moves over this Button. +* +* @method Phaser.Button#setOverSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOverSound = function (sound, marker) { + + this.setStateSound(STATE_OVER, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer moves out of this Button. +* +* @method Phaser.Button#setOutSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOutSound = function (sound, marker) { + + this.setStateSound(STATE_OUT, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer presses down on this Button. +* +* @method Phaser.Button#setDownSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setDownSound = function (sound, marker) { + + this.setStateSound(STATE_DOWN, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer has pressed down and is released from this Button. +* +* @method Phaser.Button#setUpSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setUpSound = function (sound, marker) { + + this.setStateSound(STATE_UP, sound, marker); + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOverHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) { + + if (pointer.justReleased() && + (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode) + { + // If the Pointer was only just released then we don't fire an over event + return; + } + + this.changeStateFrame(STATE_OVER); + + if (this.onOverMouseOnly && !pointer.isMouse) + { + return; + } + + this.playStateSound(STATE_OVER); + + if (this.onInputOver) + { + this.onInputOver.dispatch(this, pointer); + } + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOutHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_OUT); + + this.playStateSound(STATE_OUT); + + if (this.onInputOut) + { + this.onInputOut.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputDownHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_DOWN); + + this.playStateSound(STATE_DOWN); + + if (this.onInputDown) + { + this.onInputDown.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputUpHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) { + + this.playStateSound(STATE_UP); + + // Input dispatched early, before state change (but after sound) + if (this.onInputUp) + { + this.onInputUp.dispatch(this, pointer, isOver); + } + + if (this.freezeFrames) + { + return; + } + + if (this.forceOut === true || (this.forceOut & pointer.pointerMode) === pointer.pointerMode) + { + this.changeStateFrame(STATE_OUT); + } + else + { + var changedUp = this.changeStateFrame(STATE_UP); + if (!changedUp) + { + // No Up frame to show.. + if (isOver) + { + this.changeStateFrame(STATE_OVER); + } + else + { + this.changeStateFrame(STATE_OUT); + } + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. +* It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over +* 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled +* Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. +* +* Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. +* +* @class Phaser.SpriteBatch +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. +* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. +*/ +Phaser.SpriteBatch = function (game, parent, name, addToStage) { + + if (parent === undefined || parent === null) { parent = game.world; } + + Phaser.Group.call(this, game, parent, name, addToStage); + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.SPRITEBATCH; + + /** + * @property {Object} fastSpriteBatch - WebGL Batch Shader. + * @private + */ + this.fastSpriteBatch = null; + + /** + * @property {boolean} ready - Internal flag. + * @private + */ + this.ready = false; + +}; + +Phaser.SpriteBatch.prototype = Object.create(Phaser.Group.prototype); + +Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch; + +/** +* Renders the Sprite Batch using the WebGL renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + if (!this.ready) + { + this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(renderSession.gl); + + this.ready = true; + } + + if (this.fastSpriteBatch.gl !== renderSession.gl) + { + this.fastSpriteBatch.setContext(renderSession.gl); + } + + renderSession.spriteBatch.stop(); + + renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader); + + this.fastSpriteBatch.begin(this, renderSession); + this.fastSpriteBatch.render(this); + + renderSession.spriteBatch.start(); + +}; + +/** +* Renders the Sprite Batch using the Canvas renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + var context = renderSession.context; + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + var transform = this.worldTransform; + + var isRotated = true; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + var texture = child.texture; + var frame = texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) + { + // If rotation === 0 we can avoid setTransform + + if (isRotated) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); + isRotated = false; + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5 + renderSession.shakeX) | 0, + ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5 + renderSession.shakeY) | 0, + frame.width * child.scale.x, + frame.height * child.scale.y); + } + else + { + if (!isRotated) + { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + var tx = (childTransform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (childTransform.ty * renderSession.resolution) + renderSession.shakeY; + + // allow for trimming + + if (renderSession.roundPixels) + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx, ty); + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width) + 0.5) | 0, + ((child.anchor.y) * (-frame.height) + 0.5) | 0, + frame.width, + frame.height); + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. +* A single BitmapData can be used as the texture for one or many Images / Sprites. +* So if you need to dynamically create a Sprite texture then they are a good choice. +* +* Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't +* live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy +* in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. +* +* @class Phaser.BitmapData +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string} key - Internal Phaser reference key for the BitmapData. +* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. +*/ +Phaser.BitmapData = function (game, key, width, height, skipPool) { + + if (width === undefined || width === 0) { width = 256; } + if (height === undefined || height === 0) { height = 256; } + if (skipPool === undefined) { skipPool = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the BitmapData in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} width - The width of the BitmapData in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the BitmapData in pixels. + */ + this.height = height; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. + * @default + */ + this.canvas = Phaser.Canvas.create(this, width, height, null, skipPool); + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + * @default + */ + this.context = this.canvas.getContext('2d', { alpha: true }); + + /** + * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context. + */ + this.ctx = this.context; + + /** + * @property {string} smoothProperty - The context property needed for smoothing this Canvas. + */ + this.smoothProperty = (game.renderType === Phaser.CANVAS) ? game.renderer.renderSession.smoothProperty : Phaser.Canvas.getSmoothingPrefix(this.context); + + /** + * @property {ImageData} imageData - The context image data. + * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. + * This property is updated automatically after the first game loop, according to the dirty flag property. + */ + this.imageData = this.context.getImageData(0, 0, width, height); + + /** + * A Uint8ClampedArray view into BitmapData.buffer. + * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) + * @property {Uint8ClampedArray} data + */ + this.data = null; + + if (this.imageData) + { + this.data = this.imageData.data; + } + + /** + * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer. + */ + this.pixels = null; + + /** + * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData. + */ + if (this.data) + { + 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; + } + } + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + this.baseTexture = new PIXI.BaseTexture(this.canvas, null, this.game.resolution); + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering. + */ + this.frameData = new Phaser.FrameData(); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. + * @default + */ + this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData')); + + this.texture.frame = this.textureFrame; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.BITMAPDATA; + + /** + * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} dirty - If dirty this BitmapData will be re-rendered. + */ + this.dirty = false; + + // Aliases + this.cls = this.clear; + + /** + * @property {number} _image - Internal cache var. + * @private + */ + this._image = null; + + /** + * @property {Phaser.Point} _pos - Internal cache var. + * @private + */ + this._pos = new Phaser.Point(); + + /** + * @property {Phaser.Point} _size - Internal cache var. + * @private + */ + this._size = new Phaser.Point(); + + /** + * @property {Phaser.Point} _scale - Internal cache var. + * @private + */ + this._scale = new Phaser.Point(); + + /** + * @property {number} _rotate - Internal cache var. + * @private + */ + this._rotate = 0; + + /** + * @property {object} _alpha - Internal cache var. + * @private + */ + this._alpha = { prev: 1, current: 1 }; + + /** + * @property {Phaser.Point} _anchor - Internal cache var. + * @private + */ + this._anchor = new Phaser.Point(); + + /** + * @property {number} _tempR - Internal cache var. + * @private + */ + this._tempR = 0; + + /** + * @property {number} _tempG - Internal cache var. + * @private + */ + this._tempG = 0; + + /** + * @property {number} _tempB - Internal cache var. + * @private + */ + this._tempB = 0; + + /** + * @property {Phaser.Circle} _circle - Internal cache var. + * @private + */ + this._circle = new Phaser.Circle(); + + /** + * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods. + * @private + */ + this._swapCanvas = undefined; + +}; + +Phaser.BitmapData.prototype = { + + /** + * Shifts the contents of this BitmapData by the distances given. + * + * The image will wrap-around the edges on all sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#move + * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + move: function (x, y, wrap) { + + if (x !== 0) + { + this.moveH(x, wrap); + } + + if (y !== 0) + { + this.moveV(y, wrap); + } + + return this; + + }, + + /** + * Shifts the contents of this BitmapData horizontally. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveH + * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveH: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var h = this.height; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving to the left + var w = this.width - distance; + + // Left-hand chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h); + } + else + { + // Moving to the right + var w = this.width - distance; + + // Right-hand chunk + if (wrap) + { + ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Shifts the contents of this BitmapData vertically. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveV + * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveV: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var w = this.width; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving up + var h = this.height - distance; + + // Top chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h); + } + else + { + // Moving down + var h = this.height - distance; + + // Bottom chunk + if (wrap) + { + ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Updates the given objects so that they use this BitmapData as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.BitmapData#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. + * The source game object is not modified by this operation. + * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. + * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. + * + * @method Phaser.BitmapData#load + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + load: function (source) { + + if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + } + + if (source) + { + this.resize(source.width, source.height); + this.cls(); + } + else + { + return; + } + + this.draw(source); + + this.update(); + + return this; + + }, + + /** + * Clears the BitmapData context using a clearRect. + * + * @method Phaser.BitmapData#cls + */ + + /** + * Clears the BitmapData context using a clearRect. + * + * You can optionally define the area to clear. + * If the arguments are left empty it will clear the entire canvas. + * + * You may need to call BitmapData.update after this in order to clear out the pixel data, + * but Phaser will not do this automatically for you. + * + * @method Phaser.BitmapData#clear + * @param {number} [x=0] - The x coordinate of the top-left of the area to clear. + * @param {number} [y=0] - The y coordinate of the top-left of the area to clear. + * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width. + * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + clear: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + this.context.clearRect(x, y, width, height); + + this.dirty = true; + + return this; + + }, + + /** + * Fills the BitmapData with the given color. + * + * @method Phaser.BitmapData#fill + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} [a=1] - The alpha color value, between 0 and 1. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + fill: function (r, g, b, a) { + + if (a === undefined) { a = 1; } + + this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; + this.context.fillRect(0, 0, this.width, this.height); + this.dirty = true; + + return this; + + }, + + /** + * Creates a new {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image} element by converting this BitmapDatas canvas into a dataURL. + * + * The image is then stored in the {@link Phaser.Cache image Cache} using the key given. + * + * Finally a {@link PIXI.Texture} is created based on the image and returned. + * + * You can apply the texture to a sprite or any other supporting object by using either the + * key or the texture. First call `generateTexture`: + * + * ```javascript + * var texture = bitmapdata.generateTexture('ball'); + * ``` + * + * Then you can either apply the texture to a sprite: + * + * ```javascript + * game.add.sprite(0, 0, texture); + * ``` + * + * or by using the string based key: + * + * ```javascript + * game.add.sprite(0, 0, 'ball'); + * ``` + * + * Most browsers now load the image data asynchronously, so you should use a callback: + * + * ```javascript + * bitmapdata.generateTexture('ball', function (texture) { + * game.add.sprite(0, 0, texture); + * // or + * game.add.sprite(0, 0, 'ball'); + * }); + * ``` + * + * If this BitmapData is available during preload, you can use {@link Phaser.Loader#imageFromBitmapData} instead. + * + * @method Phaser.BitmapData#generateTexture + * @param {string} key - The key which will be used to store the image in the Cache. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {PIXI.Texture|null} The newly generated texture, or `null` if a callback was passed and the texture isn't available yet. + */ + generateTexture: function (key, callback, callbackContext) { + + var cache = this.game.cache; + var image = new Image(); + + if (callback) + { + image.onload = function () { + var obj = cache.addImage(key, '', image); + var texture = new PIXI.Texture(obj.base); + + callback.call(callbackContext || null, texture); + + image.onload = null; + }; + } + + image.src = this.canvas.toDataURL("image/png"); + + if (!callback) + { + var obj = cache.addImage(key, '', image); + + return new PIXI.Texture(obj.base); + } + + return null; + + }, + + /** + * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. + * + * @method Phaser.BitmapData#resize + * @param {integer} width - The new width of the BitmapData. + * @param {integer} height - The new height of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + resize: function (width, height) { + + if (width !== this.width || height !== this.height) + { + this.width = width; + this.height = height; + + this.canvas.width = width; + this.canvas.height = height; + + if (this._swapCanvas !== undefined) + { + this._swapCanvas.width = width; + this._swapCanvas.height = height; + } + + this.baseTexture.width = width; + this.baseTexture.height = height; + + this.textureFrame.width = width; + this.textureFrame.height = height; + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.update(); + this.dirty = true; + } + + return this; + + }, + + /** + * This re-creates the BitmapData.imageData from the current context. + * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. + * If not given the dimensions defaults to the full size of the context. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.BitmapData#update + * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from. + * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from. + * @param {number} [width=1] - The width of the image data area. + * @param {number} [height=1] - The height of the image data area. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + update: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = Math.max(1, this.width); } + if (height === undefined) { height = Math.max(1, this.height); } + + this.imageData = this.context.getImageData(x, y, width, height); + this.data = this.imageData.data; + + 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; + } + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. + * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. + * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. + * The `color` property is an Int32 of the full color. Note the endianess of this will change per system. + * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. + * The callback will also be sent the pixels x and y coordinates respectively. + * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. + * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. + * + * @method Phaser.BitmapData#processPixelRGB + * @param {function} callback - The callback that will be sent each pixel color object to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixelRGB: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = Phaser.Color.createColor(); + var result = { r: 0, g: 0, b: 0, a: 0 }; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel); + + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== false && result !== null && result !== undefined) + { + this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false); + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. + * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. + * Note that the format of the color received will be different depending on if the system is big or little endian. + * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. + * The callback will also be sent the pixels x and y coordinates respectively. + * + * @method Phaser.BitmapData#processPixel + * @param {function} callback - The callback that will be sent each pixel color to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixel: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = 0; + var result = 0; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + pixel = this.getPixel32(tx, ty); + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== pixel) + { + this.pixels[ty * this.width + tx] = result; + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. + * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. + * + * @method Phaser.BitmapData#replaceRGB + * @param {number} r1 - The red color value to be replaced. Between 0 and 255. + * @param {number} g1 - The green color value to be replaced. Between 0 and 255. + * @param {number} b1 - The blue color value to be replaced. Between 0 and 255. + * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255. + * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255. + * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255. + * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255. + * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255. + * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) { + + var sx = 0; + var sy = 0; + var w = this.width; + var h = this.height; + var source = Phaser.Color.packPixel(r1, g1, b1, a1); + + if (region !== undefined && region instanceof Phaser.Rectangle) + { + sx = region.x; + sy = region.y; + w = region.width; + h = region.height; + } + + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + if (this.getPixel32(sx + x, sy + y) === source) + { + this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false); + } + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * + * @method Phaser.BitmapData#setHSL + * @param {number} [h=null] - The hue, in the range 0 - 1. + * @param {number} [s=null] - The saturation, in the range 0 - 1. + * @param {number} [l=null] - The lightness, in the range 0 - 1. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setHSL: function (h, s, l, region) { + + var bHaveH = h || h === 0; + var bHaveS = s || s === 0; + var bHaveL = l || l === 0; + + if (!bHaveH && !bHaveS && !bHaveL) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (bHaveH) + { + pixel.h = h; + } + + if (bHaveS) + { + pixel.s = s; + } + + if (bHaveL) + { + pixel.l = l; + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * Shifting will add the given value onto the current h, s and l values, not replace them. + * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. + * + * @method Phaser.BitmapData#shiftHSL + * @param {number} [h=null] - The amount to shift the hue by. Within [-1, 1]. + * @param {number} [s=null] - The amount to shift the saturation by. Within [-1, 1]. + * @param {number} [l=null] - The amount to shift the lightness by. Within [-1, 1]. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shiftHSL: function (h, s, l, region) { + + if (h === undefined || h === null) { h = false; } + if (s === undefined || s === null) { s = false; } + if (l === undefined || l === null) { l = false; } + + if (!h && !s && !l) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (h) + { + pixel.h = this.game.math.wrap(pixel.h + h, 0, 1); + } + + if (s) + { + pixel.s = this.game.math.clamp(pixel.s + s, 0, 1); + } + + if (l) + { + pixel.l = this.game.math.clamp(pixel.l + l, 0, 1); + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green, blue and alpha values. + * + * @method Phaser.BitmapData#setPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel32: function (x, y, red, green, blue, alpha, immediate) { + + if (immediate === undefined) { immediate = true; } + + if (x >= 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; + } + } + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green and blue values. + * + * @method Phaser.BitmapData#setPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel: function (x, y, red, green, blue, immediate) { + + return this.setPixel32(x, y, red, green, blue, 255, immediate); + + }, + + /** + * Get the color of a specific pixel in the context into a color object. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + getPixel: function (x, y, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var index = ~~(x + (y * this.width)); + + index *= 4; + + out.r = this.data[index]; + out.g = this.data[++index]; + out.b = this.data[++index]; + out.a = this.data[++index]; + + return out; + + }, + + /** + * Get the color of a specific pixel including its alpha value. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. + * + * @method Phaser.BitmapData#getPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @return {number} A native color value integer (format: 0xAARRGGBB) + */ + getPixel32: function (x, y) { + + if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) + { + return this.pixels[y * this.width + x]; + } + + }, + + /** + * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixelRGB + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + getPixelRGB: function (x, y, out, hsl, hsv) { + + return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv); + + }, + + /** + * Gets all the pixels from the region specified by the given Rectangle object. + * + * @method Phaser.BitmapData#getPixels + * @param {Phaser.Rectangle} rect - The Rectangle region to get. + * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property. + */ + getPixels: function (rect) { + + return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); + + }, + + /** + * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). + * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. + * + * The direction parameter controls from which direction it should start the scan: + * + * 0 = top to bottom + * 1 = bottom to top + * 2 = left to right + * 3 = right to left + * + * @method Phaser.BitmapData#getFirstPixel + * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. + * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. + */ + getFirstPixel: function (direction) { + + if (direction === undefined) { direction = 0; } + + var pixel = Phaser.Color.createColor(); + + var x = 0; + var y = 0; + var v = 1; + var scan = false; + + if (direction === 1) + { + v = -1; + y = this.height; + } + else if (direction === 3) + { + v = -1; + x = this.width; + } + + do { + + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel); + + if (direction === 0 || direction === 1) + { + // Top to Bottom / Bottom to Top + x++; + + if (x === this.width) + { + x = 0; + y += v; + + if (y >= this.height || y <= 0) + { + scan = true; + } + } + } + else if (direction === 2 || direction === 3) + { + // Left to Right / Right to Left + y++; + + if (y === this.height) + { + y = 0; + x += v; + + if (x >= this.width || x <= 0) + { + scan = true; + } + } + } + } + while (pixel.a === 0 && !scan); + + pixel.x = x; + pixel.y = y; + + return pixel; + + }, + + /** + * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. + * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. + * + * @method Phaser.BitmapData#getBounds + * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. + * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. + */ + getBounds: function (rect) { + + if (rect === undefined) { rect = new Phaser.Rectangle(); } + + rect.x = this.getFirstPixel(2).x; + + // If we hit this, there's no point scanning any more, the image is empty + if (rect.x === this.width) + { + return rect.setTo(0, 0, 0, 0); + } + + rect.y = this.getFirstPixel(0).y; + rect.width = (this.getFirstPixel(3).x - rect.x) + 1; + rect.height = (this.getFirstPixel(1).y - rect.y) + 1; + + return rect; + + }, + + /** + * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. + * + * @method Phaser.BitmapData#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself. + * + * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn. + * + * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters. + * + * Note that the source image can also be this BitmapData, which can create some interesting effects. + * + * This method has a lot of parameters for maximum control. + * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all. + * + * You may prefer to use `copyTransform` if you're simply trying to draw a Sprite to this BitmapData, + * and don't wish to translate, scale or rotate it from its original values. + * + * @method Phaser.BitmapData#copy + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image. + * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image. + * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width. + * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height. + * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`. + * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`. + * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter. + * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter. + * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters. + * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) { + + if (source === undefined || source === null) { source = this; } + + if (source instanceof Phaser.RenderTexture) + { + source = source.getCanvas(); + } + + this._image = source; + + if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text || source instanceof PIXI.Sprite) + { + // Copy over sprite values + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + this._scale.set(source.scale.x, source.scale.y); + this._anchor.set(source.anchor.x, source.anchor.y); + this._rotate = source.rotation; + this._alpha.current = source.alpha; + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + if (tx === undefined || tx === null) { tx = source.x; } + if (ty === undefined || ty === null) { ty = source.y; } + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + } + else + { + // Reset + this._pos.set(0); + this._scale.set(1); + this._anchor.set(0); + this._rotate = 0; + this._alpha.current = 1; + + if (source instanceof Phaser.BitmapData) + { + this._image = source.canvas; + } + else if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + + if (source === null) + { + return; + } + else + { + this._image = source; + } + } + + this._size.set(this._image.width, this._image.height); + } + + // The source region to copy from + if (x === undefined || x === null) { x = 0; } + if (y === undefined || y === null) { y = 0; } + + // If they set a width/height then we override the frame values with them + if (width) + { + this._size.x = width; + } + + if (height) + { + this._size.y = height; + } + + // The destination region to copy to + if (tx === undefined || tx === null) { tx = x; } + if (ty === undefined || ty === null) { ty = y; } + if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; } + if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; } + + // Rotation - if set this will override any potential Sprite value + if (typeof rotate === 'number') + { + this._rotate = rotate; + } + + // Anchor - if set this will override any potential Sprite value + if (typeof anchorX === 'number') + { + this._anchor.x = anchorX; + } + + if (typeof anchorY === 'number') + { + this._anchor.y = anchorY; + } + + // Scaling - if set this will override any potential Sprite value + if (typeof scaleX === 'number') + { + this._scale.x = scaleX; + } + + if (typeof scaleY === 'number') + { + this._scale.y = scaleY; + } + + // Effects + if (typeof alpha === 'number') + { + this._alpha.current = alpha; + } + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + // Doesn't work fully with children, or nested scale + rotation transforms (see copyTransform) + ctx.translate(tx, ty); + + ctx.scale(this._scale.x, this._scale.y); + + ctx.rotate(this._rotate); + + ctx.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight); + + // Carry on ... + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the + * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. + * It takes the objects tint and scale mode into consideration before drawing. + * + * You can optionally specify Blend Mode and Round Pixels arguments. + * + * @method Phaser.BitmapData#copyTransform + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyTransform: function (source, blendMode, roundPx) { + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (!source.hasOwnProperty('worldTransform') || !source.worldVisible || source.worldAlpha === 0) + { + return this; + } + + var wt = source.worldTransform; + + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + + if (wt.a === 0 || wt.d === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return this; + } + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + var tx = wt.tx; + var ty = wt.ty; + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + ctx[this.smoothProperty] = (source.texture.baseTexture.scaleMode === PIXI.scaleModes.LINEAR); + + ctx.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + + ctx.drawImage(this._image, + this._pos.x, + this._pos.y, + this._size.x, + this._size.y, + -this._size.x * source.anchor.x, + -this._size.y * source.anchor.y, + this._size.x, + this._size.y); + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. + * + * @method Phaser.BitmapData#copyRect + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. + * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image. + * @param {number} x - The destination x coordinate to copy the image to. + * @param {number} y - The destination y coordinate to copy the image to. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyRect: function (source, area, x, y, alpha, blendMode, roundPx) { + + return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx); + + }, + + /** + * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. + * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. + * + * @method Phaser.BitmapData#draw + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData. + * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`. + * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`. + * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`. + * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + draw: function (source, x, y, width, height, blendMode, roundPx) { + + // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here + return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx); + + }, + + /** + * Draws the immediate children of a Phaser.Group to this BitmapData. + * + * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. + * + * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. + * + * @method Phaser.BitmapData#drawGroup + * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawGroup: function (group, blendMode, roundPx) { + + if (group.total > 0) + { + group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx); + } + + return this; + + }, + + /** + * A proxy for drawGroup that handles child iteration for more complex Game Objects. + * + * @method Phaser.BitmapData#drawGroupProxy + * @private + * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + */ + drawGroupProxy: function (child, blendMode, roundPx) { + + if (child.hasOwnProperty('texture')) + { + this.copyTransform(child, blendMode, roundPx); + } + + if (child.type === Phaser.GROUP && child.exists) + { + this.drawGroup(child, blendMode, roundPx); + } + else + { + if (child.hasOwnProperty('children') && child.children.length > 0) + { + for (var i = 0; i < child.children.length; i++) + { + if (child.children[i].exists) + { + this.copyTransform(child.children[i], blendMode, roundPx); + } + } + } + } + + }, + + /** + * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. + * + * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData + * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the + * bounds of the top-level Game Object. + * + * When drawing it will take into account the child's world rotation, scale and alpha values. + * + * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. + * + * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update + * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can + * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. + * + * @method Phaser.BitmapData#drawFull + * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawFull: function (parent, blendMode, roundPx) { + + if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false)) + { + return this; + } + + if (parent.type !== Phaser.GROUP && parent.type !== Phaser.EMITTER && parent.type !== Phaser.BITMAPTEXT) + { + if (parent.type === Phaser.GRAPHICS) + { + var bounds = parent.getBounds(); + this.ctx.save(); + this.ctx.translate(bounds.x, bounds.y); + PIXI.CanvasGraphics.renderGraphics(parent, this.ctx); + this.ctx.restore(); + } + else + { + this.copy(parent, null, null, null, null, parent.worldPosition.x, parent.worldPosition.y, null, null, parent.worldRotation, null, null, parent.worldScale.x, parent.worldScale.y, parent.worldAlpha, blendMode, roundPx); + } + } + + if (parent.children) + { + for (var i = 0; i < parent.children.length; i++) + { + this.drawFull(parent.children[i], blendMode, roundPx); + } + } + + return this; + + }, + + /** + * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. + * You can cancel an existing shadow by calling this method and passing no parameters. + * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. + * + * @method Phaser.BitmapData#shadow + * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. + * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. + * @param {number} [x=10] - The horizontal offset of the shadow in pixels. + * @param {number} [y=10] - The vertical offset of the shadow in pixels. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shadow: function (color, blur, x, y) { + + var ctx = this.context; + + if (color === undefined || color === null) + { + ctx.shadowColor = 'rgba(0,0,0,0)'; + } + else + { + ctx.shadowColor = color; + ctx.shadowBlur = blur || 5; + ctx.shadowOffsetX = x || 10; + ctx.shadowOffsetY = y || 10; + } + + return this; + + }, + + /** + * Draws the image onto this BitmapData using an image as an alpha mask. + * + * @method Phaser.BitmapData#alphaMask + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. + * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. + * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + alphaMask: function (source, mask, sourceRect, maskRect) { + + if (maskRect === undefined || maskRect === null) + { + this.draw(mask).blendSourceAtop(); + } + else + { + this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop(); + } + + if (sourceRect === undefined || sourceRect === null) + { + this.draw(source).blendReset(); + } + else + { + this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset(); + } + + return this; + + }, + + /** + * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. + * The original BitmapData remains unchanged. + * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. + * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: + * `picture.extract(mask, r, g, b)` + * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. + * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint + * the color during extraction. + * + * @method Phaser.BitmapData#extract + * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. + * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied? + * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255. + * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255. + * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255. + * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on. + */ + extract: function (destination, r, g, b, a, resize, r2, g2, b2) { + + if (a === undefined) { a = 255; } + if (resize === undefined) { resize = false; } + if (r2 === undefined) { r2 = r; } + if (g2 === undefined) { g2 = g; } + if (b2 === undefined) { b2 = b; } + + if (resize) + { + destination.resize(this.width, this.height); + } + + this.processPixelRGB( + function (pixel, x, y) + { + if (pixel.r === r && pixel.g === g && pixel.b === b) + { + destination.setPixel32(x, y, r2, g2, b2, a, false); + } + return false; + }, + this); + + destination.context.putImageData(destination.imageData, 0, 0); + destination.dirty = true; + + return destination; + + }, + + /** + * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. + * + * @method Phaser.BitmapData#rect + * @param {number} x - The x coordinate of the top-left of the Rectangle. + * @param {number} y - The y coordinate of the top-left of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + rect: function (x, y, width, height, fillStyle) { + + if (typeof fillStyle !== 'undefined') + { + this.context.fillStyle = fillStyle; + } + + this.context.fillRect(x, y, width, height); + + return this; + + }, + + /** + * Draws text to the BitmapData in the given font and color. + * The default font is 14px Courier, so useful for quickly drawing debug text. + * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. + * + * @method Phaser.BitmapData#text + * @param {string} text - The text to write to the BitmapData. + * @param {number} x - The x coordinate of the top-left of the text string. + * @param {number} y - The y coordinate of the top-left of the text string. + * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can. + * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in. + * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1) + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + text: function (text, x, y, font, color, shadow) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (font === undefined) { font = '14px Courier'; } + if (color === undefined) { color = 'rgb(255,255,255)'; } + if (shadow === undefined) { shadow = true; } + + var ctx = this.context; + var prevFont = ctx.font; + + ctx.font = font; + + if (shadow) + { + ctx.fillStyle = 'rgb(0,0,0)'; + ctx.fillText(text, x + 1, y + 1); + } + + ctx.fillStyle = color; + ctx.fillText(text, x, y); + + ctx.font = prevFont; + + return this; + + }, + + /** + * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. + * + * @method Phaser.BitmapData#circle + * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle. + * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle. + * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + circle: function (x, y, radius, fillStyle) { + + var ctx = this.context; + + if (fillStyle !== undefined) + { + ctx.fillStyle = fillStyle; + } + + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2, false); + ctx.closePath(); + + ctx.fill(); + + return this; + + }, + + /** + * Draws a line between the coordinates given in the color and thickness specified. + * + * @method Phaser.BitmapData#line + * @param {number} x1 - The x coordinate to start the line from. + * @param {number} y1 - The y coordinate to start the line from. + * @param {number} x2 - The x coordinate to draw the line to. + * @param {number} y2 - The y coordinate to draw the line to. + * @param {string} [color='#fff'] - The stroke color that the line will be drawn in. + * @param {number} [width=1] - The line thickness. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + line: function (x1, y1, x2, y2, color, width) { + + if (color === undefined) { color = '#fff'; } + if (width === undefined) { width = 1; } + + var ctx = this.context; + + ctx.beginPath(); + + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); + + ctx.closePath(); + + return this; + + }, + + /** + * Draws a polygon. + * + * @method Phaser.BitmapData#polygon + * @param {object[]} points - An array of {@link Phaser.Point} or point-like objects. + * @param {CanvasGradient|CanvasPattern|string} [fillStyle] - A color, gradient, or pattern. + * @param {number} [lineWidth=0] - The line thickness. + * @param {CanvasGradient|CanvasPattern|string} [strokeStyle='#fff'] - The line color, gradient, or pattern (when `lineWidth` > 0). + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + polygon: function (points, fillStyle, lineWidth, strokeStyle) { + + // Could reject points.length < 3 + + if (strokeStyle === undefined) { strokeStyle = '#fff'; } + if (lineWidth === undefined) { lineWidth = 0; } + + var ctx = this.context; + + if (fillStyle) + { + ctx.fillStyle = fillStyle; + } + + if (lineWidth) + { + ctx.lineWidth = lineWidth; + ctx.strokeStyle = strokeStyle; + } + + ctx.beginPath(); + + ctx.moveTo(points[0].x, points[0].y); + + for (var i = 1, len = points.length; i < len; i++) + { + var point = points[i]; + ctx.lineTo(point.x, point.y); + } + + ctx.closePath(); + + if (fillStyle) { ctx.fill(); } + if (lineWidth) { ctx.stroke(); } + + return this; + + }, + + /** + * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. + * + * @method Phaser.BitmapData#textureLine + * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line. + * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. + * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + textureLine: function (line, image, repeat) { + + if (repeat === undefined) { repeat = 'repeat-x'; } + + if (typeof image === 'string') + { + image = this.game.cache.getImage(image); + + if (!image) + { + return; + } + } + + var width = line.length; + + if (repeat === 'no-repeat' && width > image.width) + { + width = image.width; + } + + var ctx = this.context; + + ctx.fillStyle = ctx.createPattern(image, repeat); + + this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height); + + this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos); + + ctx.save(); + ctx.translate(this._pos.x, this._pos.y); + ctx.rotate(line.angle); + ctx.fillRect(0, 0, width, image.height); + ctx.restore(); + + this.dirty = true; + + return this; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. + * + * @method Phaser.BitmapData#render + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + render: function () { + + if (!this.disableTextureUpload && this.dirty) + { + this.baseTexture.dirty(); + this.dirty = false; + } + + return this; + + }, + + /** + * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. + * + * @method Phaser.BitmapData#destroy + */ + destroy: function () { + + this.frameData.destroy(); + + this.texture.destroy(true); + + Phaser.CanvasPool.remove(this); + + }, + + /** + * Resets the blend mode (effectively sets it to 'source-over') + * + * @method Phaser.BitmapData#blendReset + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendReset: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-over' + * + * @method Phaser.BitmapData#blendSourceOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOver: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-in' + * + * @method Phaser.BitmapData#blendSourceIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceIn: function () { + + this.op = 'source-in'; + return this; + + }, + + /** + * Sets the blend mode to 'source-out' + * + * @method Phaser.BitmapData#blendSourceOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOut: function () { + + this.op = 'source-out'; + return this; + + }, + + /** + * Sets the blend mode to 'source-atop' + * + * @method Phaser.BitmapData#blendSourceAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceAtop: function () { + + this.op = 'source-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-over' + * + * @method Phaser.BitmapData#blendDestinationOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOver: function () { + + this.op = 'destination-over'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-in' + * + * @method Phaser.BitmapData#blendDestinationIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationIn: function () { + + this.op = 'destination-in'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-out' + * + * @method Phaser.BitmapData#blendDestinationOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOut: function () { + + this.op = 'destination-out'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-atop' + * + * @method Phaser.BitmapData#blendDestinationAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationAtop: function () { + + this.op = 'destination-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'xor' + * + * @method Phaser.BitmapData#blendXor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendXor: function () { + + this.op = 'xor'; + return this; + + }, + + /** + * Sets the blend mode to 'lighter' + * + * @method Phaser.BitmapData#blendAdd + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendAdd: function () { + + this.op = 'lighter'; + return this; + + }, + + /** + * Sets the blend mode to 'multiply' + * + * @method Phaser.BitmapData#blendMultiply + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendMultiply: function () { + + this.op = 'multiply'; + return this; + + }, + + /** + * Sets the blend mode to 'screen' + * + * @method Phaser.BitmapData#blendScreen + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendScreen: function () { + + this.op = 'screen'; + return this; + + }, + + /** + * Sets the blend mode to 'overlay' + * + * @method Phaser.BitmapData#blendOverlay + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendOverlay: function () { + + this.op = 'overlay'; + return this; + + }, + + /** + * Sets the blend mode to 'darken' + * + * @method Phaser.BitmapData#blendDarken + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDarken: function () { + + this.op = 'darken'; + return this; + + }, + + /** + * Sets the blend mode to 'lighten' + * + * @method Phaser.BitmapData#blendLighten + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLighten: function () { + + this.op = 'lighten'; + return this; + + }, + + /** + * Sets the blend mode to 'color-dodge' + * + * @method Phaser.BitmapData#blendColorDodge + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorDodge: function () { + + this.op = 'color-dodge'; + return this; + + }, + + /** + * Sets the blend mode to 'color-burn' + * + * @method Phaser.BitmapData#blendColorBurn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorBurn: function () { + + this.op = 'color-burn'; + return this; + + }, + + /** + * Sets the blend mode to 'hard-light' + * + * @method Phaser.BitmapData#blendHardLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHardLight: function () { + + this.op = 'hard-light'; + return this; + + }, + + /** + * Sets the blend mode to 'soft-light' + * + * @method Phaser.BitmapData#blendSoftLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSoftLight: function () { + + this.op = 'soft-light'; + return this; + + }, + + /** + * Sets the blend mode to 'difference' + * + * @method Phaser.BitmapData#blendDifference + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDifference: function () { + + this.op = 'difference'; + return this; + + }, + + /** + * Sets the blend mode to 'exclusion' + * + * @method Phaser.BitmapData#blendExclusion + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendExclusion: function () { + + this.op = 'exclusion'; + return this; + + }, + + /** + * Sets the blend mode to 'hue' + * + * @method Phaser.BitmapData#blendHue + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHue: function () { + + this.op = 'hue'; + return this; + + }, + + /** + * Sets the blend mode to 'saturation' + * + * @method Phaser.BitmapData#blendSaturation + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSaturation: function () { + + this.op = 'saturation'; + return this; + + }, + + /** + * Sets the blend mode to 'color' + * + * @method Phaser.BitmapData#blendColor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColor: function () { + + this.op = 'color'; + return this; + + }, + + /** + * Sets the blend mode to 'luminosity' + * + * @method Phaser.BitmapData#blendLuminosity + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLuminosity: function () { + + this.op = 'luminosity'; + return this; + + }, + + /** + * Updates a portion of the BitmapData from a source Bitmap. + * This optimization is important if calling update() on a large Bitmap is causing performance issues. + * Make sure you use getPixel32() instead of getPixel(). + * This does not work with floating point numbers for x and y. + * + * @method Phaser.BitmapData#copyBitmapData + * @param {Phaser.BitmapData} [source] - The BitmapData you wish to copy. + * @param {number} [x] - The x coordinate of the top-left of the area to copy. + * @param {number} [y] - The y coordinate of the top-left of the area to copy. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyBitmapData: function(source, x, y) { + + source.update(); + for (var i = 0, destRowStart; i < source.height; i++) { + destRowStart = (y + i) * this.width + x; + for (var j = 0; j < source.width; j++) { + this.pixels[destRowStart + j] = source.pixels[i * source.width + j]; + } + } + return this; + + } + +}; + +/** +* @memberof Phaser.BitmapData +* @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", { + + get: function () { + + Phaser.Canvas.getSmoothingEnabled(this.context); + + }, + + set: function (value) { + + Phaser.Canvas.setSmoothingEnabled(this.context, value); + + } + +}); + +/** +* @memberof Phaser.BitmapData +* @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "op", { + + get: function () { + + return this.context.globalCompositeOperation; + + }, + + set: function (value) { + + this.context.globalCompositeOperation = value; + + } + +}); + +/** + * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform. + * + * @method Phaser.BitmapData.getTransform + * @param {number} translateX - The x translate value. + * @param {number} translateY - The y translate value. + * @param {number} scaleX - The scale x value. + * @param {number} scaleY - The scale y value. + * @param {number} skewX - The skew x value. + * @param {number} skewY - The skew y value. + * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms. + */ +Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) { + + if (typeof translateX !== 'number') { translateX = 0; } + if (typeof translateY !== 'number') { translateY = 0; } + if (typeof scaleX !== 'number') { scaleX = 1; } + if (typeof scaleY !== 'number') { scaleY = 1; } + if (typeof skewX !== 'number') { skewX = 0; } + if (typeof skewY !== 'number') { skewY = 0; } + + return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY }; + +}; + +Phaser.BitmapData.prototype.constructor = Phaser.BitmapData; + +/* jshint ignore:start */ + +/* +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ + +/** +* @class EarCut +*/ +Phaser.EarCut = {}; + +Phaser.EarCut.Triangulate = function (data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = Phaser.EarCut.linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = Phaser.EarCut.eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + Phaser.EarCut.earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +}; + +// create a circular doubly linked list from polygon points in the specified winding order + +Phaser.EarCut.linkedList = function (data, start, end, dim, clockwise) { + var sum = 0, + i, j, last; + + // calculate original winding order of a polygon ring + for (i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + + // link points into circular doubly-linked list in the specified winding order + if (clockwise === (sum > 0)) { + for (i = start; i < end; i += dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } + + return last; +}; + +// eliminate colinear or duplicate points + +Phaser.EarCut.filterPoints = function (start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (Phaser.EarCut.equals(p, p.next) || Phaser.EarCut.area(p.prev, p, p.next) === 0)) { + Phaser.EarCut.removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +}; + +// main ear slicing loop which triangulates a polygon (given as a linked list) + +Phaser.EarCut.earcutLinked = function (ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) Phaser.EarCut.indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? Phaser.EarCut.isEarHashed(ear, minX, minY, size) : Phaser.EarCut.isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + Phaser.EarCut.removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + Phaser.EarCut.earcutLinked(Phaser.EarCut.filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = Phaser.EarCut.cureLocalIntersections(ear, triangles, dim); + Phaser.EarCut.earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + Phaser.EarCut.splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +}; + +// check whether a polygon node forms a valid ear with adjacent nodes + +Phaser.EarCut.isEar = function (ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +}; + +Phaser.EarCut.isEarHashed = function (ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = Phaser.EarCut.zOrder(minTX, minTY, minX, minY, size), + maxZ = Phaser.EarCut.zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +}; + +// go through all polygon nodes and cure small local self-intersections + +Phaser.EarCut.cureLocalIntersections = function (start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) + if (Phaser.EarCut.intersects(a, p, p.next, b) && Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + Phaser.EarCut.removeNode(p); + Phaser.EarCut.removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +}; + +// try splitting polygon into two and triangulate them independently + +Phaser.EarCut.splitEarcut = function (start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && Phaser.EarCut.isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = Phaser.EarCut.splitPolygon(a, b); + + // filter colinear points around the cuts + a = Phaser.EarCut.filterPoints(a, a.next); + c = Phaser.EarCut.filterPoints(c, c.next); + + // run earcut on each half + Phaser.EarCut.earcutLinked(a, triangles, dim, minX, minY, size); + Phaser.EarCut.earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +}; + +// link every hole into the outer loop, producing a single-ring polygon without holes + +Phaser.EarCut.eliminateHoles = function (data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = Phaser.EarCut.linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(Phaser.EarCut.getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + Phaser.EarCut.eliminateHole(queue[i], outerNode); + outerNode = Phaser.EarCut.filterPoints(outerNode, outerNode.next); + } + + return outerNode; +}; + +Phaser.EarCut.compareX = function (a, b) { + return a.x - b.x; +}; + +// find a bridge between vertices that connects hole with an outer ring and and link it + +Phaser.EarCut.eliminateHole = function (hole, outerNode) { + outerNode = Phaser.EarCut.findHoleBridge(hole, outerNode); + if (outerNode) { + var b = Phaser.EarCut.splitPolygon(outerNode, hole); + Phaser.EarCut.filterPoints(b, b.next); + } +}; + +// David Eberly's algorithm for finding a bridge between hole and outer polygon + +Phaser.EarCut.findHoleBridge = function (hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hole.x === m.x) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= m.x && + Phaser.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && Phaser.EarCut.locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +}; + +// interlink polygon nodes in z-order + +Phaser.EarCut.indexCurve = function (start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = Phaser.EarCut.zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + Phaser.EarCut.sortLinked(p); +}; + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + +Phaser.EarCut.sortLinked = function (list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +}; + +// z-order of a point given coords and size of the data bounding box + +Phaser.EarCut.zOrder = function (x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +}; + +// find the leftmost node of a polygon ring + +Phaser.EarCut.getLeftmost = function (start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +}; + +// check if a point lies within a convex triangle + +Phaser.EarCut.pointInTriangle = function (ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +}; + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) + +Phaser.EarCut.isValidDiagonal = function (a, b) { + return Phaser.EarCut.equals(a, b) || a.next.i !== b.i && a.prev.i !== b.i && !Phaser.EarCut.intersectsPolygon(a, b) && + Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a) && Phaser.EarCut.middleInside(a, b); +}; + +// signed area of a triangle + +Phaser.EarCut.area = function (p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +}; + +// check if two points are equal + +Phaser.EarCut.equals = function (p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +}; + +// check if two segments intersect + +Phaser.EarCut.intersects = function (p1, q1, p2, q2) { + return Phaser.EarCut.area(p1, q1, p2) > 0 !== Phaser.EarCut.area(p1, q1, q2) > 0 && + Phaser.EarCut.area(p2, q2, p1) > 0 !== Phaser.EarCut.area(p2, q2, q1) > 0; +}; + +// check if a polygon diagonal intersects any polygon segments + +Phaser.EarCut.intersectsPolygon = function (a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + Phaser.EarCut.intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +}; + +// check if a polygon diagonal is locally inside the polygon + +Phaser.EarCut.locallyInside = function (a, b) { + return Phaser.EarCut.area(a.prev, a, a.next) < 0 ? + Phaser.EarCut.area(a, b, a.next) >= 0 && Phaser.EarCut.area(a, a.prev, b) >= 0 : + Phaser.EarCut.area(a, b, a.prev) < 0 || Phaser.EarCut.area(a, a.next, b) < 0; +}; + +// check if the middle point of a polygon diagonal is inside the polygon + +Phaser.EarCut.middleInside = function (a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +}; + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring + +Phaser.EarCut.splitPolygon = function (a, b) { + var a2 = new Phaser.EarCut.Node(a.i, a.x, a.y), + b2 = new Phaser.EarCut.Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +}; + +// create a node and optionally link it with previous one (in a circular doubly linked list) + +Phaser.EarCut.insertNode = function (i, x, y, last) { + var p = new Phaser.EarCut.Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +}; + +Phaser.EarCut.removeNode = function (p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +}; + +Phaser.EarCut.Node = function (i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +}; + +/* jshint ignore:end */ + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used by the webGL renderer to draw the primitive graphics data + * + * @class PIXI.WebGLGraphics + * @private + * @static + */ +PIXI.WebGLGraphics = function() +{ +}; + +/** + * The number of points beyond which Pixi swaps to using the Stencil Buffer to render the Graphics. + * + * @type {number} + */ +PIXI.WebGLGraphics.stencilBufferLimit = 6; + +/** + * Renders the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.renderGraphics + * @param graphics {Graphics} + * @param renderSession {Object} + */ +PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset) +{ + var gl = renderSession.gl; + var projection = renderSession.projection, + offset = renderSession.offset, + shader = renderSession.shaderManager.primitiveShader, + webGLData; + + if(graphics.dirty) + { + PIXI.WebGLGraphics.updateGraphics(graphics, gl); + } + + var webGL = graphics._webGL[gl.id]; + + // if the graphics object does not exist in the webGL context skip rendering! + if(!webGL) + { + return; + } + + // This could be speeded up for sure! + + for (var i = 0; i < webGL.data.length; i++) + { + if(webGL.data[i].mode === 1) + { + webGLData = webGL.data[i]; + + renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession); + + // render quad.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + renderSession.stencilManager.popStencil(graphics, webGLData, renderSession); + } + else + { + webGLData = webGL.data[i]; + + + renderSession.shaderManager.setShader( shader );//activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, 1); + + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + } + } +}; + +/** + * Updates the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.updateGraphics + * @param graphicsData {Graphics} The graphics object to update + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLGraphics.updateGraphics = function(graphics, gl) +{ + // get the contexts graphics object + var webGL = graphics._webGL[gl.id]; + // if the graphics object does not exist in the webGL context time to create it! + if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; + + // flag the graphics as not dirty as we are about to update it... + graphics.dirty = false; + + var i; + + // if the user cleared the graphics object we will need to clear every object + if(graphics.clearDirty) + { + graphics.clearDirty = false; + + // lop through and return all the webGLDatas to the object pool so than can be reused later on + for (i = 0; i < webGL.data.length; i++) + { + var graphicsData = webGL.data[i]; + graphicsData.reset(); + PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData ); + } + + // clear the array and reset the index.. + webGL.data = []; + webGL.lastIndex = 0; + } + + var webGLData; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + if (data.type === Phaser.POLYGON) + { + // need to add the points the the graphics object.. + data.points = data.shape.points.slice(); + if(data.shape.closed) + { + // close the poly if the value is true! + if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { + data.points.push(data.points[0], data.points[1]); + } + } + + // MAKE SURE WE HAVE THE CORRECT TYPE.. + if(data.fill) + { + if(data.points.length >= PIXI.WebGLGraphics.stencilBufferLimit) + { + if(data.points.length < PIXI.WebGLGraphics.stencilBufferLimit * 2) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData); + // console.log(canDrawUsingSimple); + + if(!canDrawUsingSimple) + { + // console.log("<>>>") + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + } + } + + if(data.lineWidth > 0) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + PIXI.WebGLGraphics.buildLine(data, webGLData); + + } + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + if (data.type === Phaser.RECTANGLE) + { + PIXI.WebGLGraphics.buildRectangle(data, webGLData); + } + else if (data.type === Phaser.CIRCLE || data.type === Phaser.ELLIPSE) + { + PIXI.WebGLGraphics.buildCircle(data, webGLData); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData); + } + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (i = 0; i < webGL.data.length; i++) + { + webGLData = webGL.data[i]; + if(webGLData.dirty)webGLData.upload(); + } +}; + +/** + * @static + * @private + * @method PIXI.WebGLGraphics.switchMode + * @param webGL {WebGLContext} + * @param type {Number} + */ +PIXI.WebGLGraphics.switchMode = function(webGL, type) +{ + var webGLData; + + if(!webGL.data.length) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + else + { + webGLData = webGL.data[webGL.data.length-1]; + + if(webGLData.mode !== type || type === 1) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + } + + webGLData.dirty = true; + + return webGLData; +}; + +/** + * Builds a rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData) +{ + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; + + // start + 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); + + // insert 2 dead triangles.. + 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; + } +}; + +/** + * Builds a rounded rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRoundedRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData) +{ + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + recPoints.push(x, y + radius); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); + + if (graphicsData.fill) { + var color = Phaser.Color.hexToRGBArray(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; + + var triangles = Phaser.EarCut.Triangulate(recPoints, null, 2); + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i+1] + vecPos); + indices.push(triangles[i+2] + vecPos); + indices.push(triangles[i+2] + vecPos); + } + + + for (i = 0; i < recPoints.length; i++) + { + verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @static + * @private + * @method PIXI.WebGLGraphics.quadraticBezierCurve + * @param fromX {Number} Origin point x + * @param fromY {Number} Origin point x + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Array(Number)} + */ +PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) { + + var xa, + ya, + xb, + yb, + x, + y, + n = 20, + points = []; + + function getPt(n1 , n2, perc) { + var diff = n2 - n1; + + return n1 + ( diff * perc ); + } + + var j = 0; + for (var i = 0; i <= n; i++ ) + { + j = i / n; + + // The Green Line + xa = getPt( fromX , cpX , j ); + ya = getPt( fromY , cpY , j ); + xb = getPt( cpX , toX , j ); + yb = getPt( cpY , toY , j ); + + // The Black Dot + x = getPt( xa , xb , j ); + y = getPt( ya , yb , j ); + + points.push(x, y); + } + return points; +}; + +/** + * Builds a circle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildCircle + * @param graphicsData {Graphics} The graphics object to draw + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData) +{ + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + + // TODO - bit hacky?? + if (graphicsData.type === Phaser.CIRCLE) + { + width = circleData.radius; + height = circleData.radius; + } + else + { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = 40; + var seg = (Math.PI * 2) / totalSegs ; + + var i = 0; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; i < totalSegs + 1 ; i++) + { + verts.push(x,y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos-1); + } + + if(graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (i = 0; i < totalSegs + 1; i++) + { + graphicsData.points.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height); + } + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Builds a line to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildLine + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData) +{ + // TODO OPTIMISE! + var i = 0; + var points = graphicsData.points; + if(points.length === 0)return; + + // if the line width is an odd number add 0.5 to align to a whole pixel + if(graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) { + points[i] += 0.5; + } + } + + // get first and last point.. figure out the middle! + var firstPoint = new PIXI.Point( points[0], points[1] ); + var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + // if the first point is the last point - gonna have issues :) + if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length/6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var px, py, p1x, p1y, p2x, p2y, p3x, p3y; + var perpx, perpy, perp2x, perp2y, perp3x, perp3y; + var a1, b1, c1, a2, b2, c2; + var denom, pdist, dist; + + p1x = points[0]; + p1y = points[1]; + + p2x = points[2]; + p2y = points[3]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx , p1y - perpy, + r, g, b, alpha); + + verts.push(p1x + perpx , p1y + perpy, + r, g, b, alpha); + + for (i = 1; i < length-1; i++) + { + p1x = points[(i-1)*2]; + p1y = points[(i-1)*2 + 1]; + + p2x = points[(i)*2]; + p2y = points[(i)*2 + 1]; + + p3x = points[(i+1)*2]; + p3y = points[(i+1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + a1 = (-perpy + p1y) - (-perpy + p2y); + b1 = (-perpx + p2x) - (-perpx + p1x); + c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + a2 = (-perp2y + p3y) - (-perp2y + p2y); + b2 = (-perp2x + p2x) - (-perp2x + p3x); + c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + denom = a1*b2 - a2*b1; + + if(Math.abs(denom) < 0.1 ) + { + + denom+=10.1; + verts.push(p2x - perpx , p2y - perpy, + r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy, + r, g, b, alpha); + + continue; + } + + px = (b1*c2 - b2*c1)/denom; + py = (a2*c1 - a1*c2)/denom; + + + pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); + + + if(pdist > 140 * 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 < indexCount; i++) + { + indices.push(indexStart++); + } + + indices.push(indexStart-1); +}; + +/** + * Builds a complex polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildComplexPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData) +{ + //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. + var points = graphicsData.points.slice(); + if(points.length < 6)return; + + // get first and last point.. figure out the middle! + var indices = webGLData.indices; + webGLData.points = points; + webGLData.alpha = graphicsData.fillAlpha; + webGLData.color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + + /* + calclate the bounds.. + */ + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + var x,y; + + // get size.. + for (var i = 0; i < points.length; i+=2) + { + x = points[i]; + y = points[i+1]; + + minX = x < minX ? x : minX; + maxX = x > maxX ? x : maxX; + + minY = y < minY ? y : minY; + maxY = y > maxY ? y : maxY; + } + + // add a quad to the end cos there is no point making another buffer! + points.push(minX, minY, + maxX, minY, + maxX, maxY, + minX, maxY); + + // push a quad onto the end.. + + //TODO - this aint needed! + var length = points.length / 2; + for (i = 0; i < length; i++) + { + indices.push( i ); + } + +}; + +/** + * Builds a polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData) +{ + var points = graphicsData.points; + + if(points.length < 6)return; + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = Phaser.EarCut.Triangulate(points, null, 2); + + if(!triangles)return false; + + var vertPos = verts.length / 6; + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i] + vertPos); + indices.push(triangles[i+1] + vertPos); + indices.push(triangles[i+2] +vertPos); + indices.push(triangles[i+2] + vertPos); + } + + for (i = 0; i < length; i++) + { + verts.push(points[i * 2], points[i * 2 + 1], + r, g, b, alpha); + } + + return true; +}; + +PIXI.WebGLGraphics.graphicsDataPool = []; + +/** + * @class WebGLGraphicsData + * @private + * @static + */ +PIXI.WebGLGraphicsData = function(gl) +{ + this.gl = gl; + + //TODO does this need to be split before uploding?? + this.color = [0,0,0]; // color split! + this.points = []; + this.indices = []; + this.buffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + this.mode = 1; + this.alpha = 1; + this.dirty = true; +}; + +/** + * @method PIXI.WebGLGraphics.reset + */ +PIXI.WebGLGraphicsData.prototype.reset = function() +{ + this.points = []; + this.indices = []; +}; + +/** + * @method PIXI.WebGLGraphics.upload + */ +PIXI.WebGLGraphicsData.prototype.upload = function() +{ + var gl = this.gl; + +// this.lastIndex = graphics.graphicsData.length; + this.glPoints = new Float32Array(this.points); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW); + + this.glIndicies = new Uint16Array(this.indices); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW); + + this.dirty = false; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + +/** + * A set of functions used by the canvas renderer to draw the primitive graphics data. + * + * @class PIXI.CanvasGraphics + * @static + */ +PIXI.CanvasGraphics = function() +{ +}; + +/** + * Renders a {@link Phaser.Graphics} object to a canvas. + * + * @method PIXI.CanvasGraphics.renderGraphics + * @static + * @param graphics {Graphics} the actual graphics object to render + * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas + */ +PIXI.CanvasGraphics.renderGraphics = function(graphics, context) +{ + var worldAlpha = graphics.worldAlpha; + + if (graphics.dirty) + { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === Phaser.POLYGON) + { + context.beginPath(); + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (shape.closed) + { + context.lineTo(points[0], points[1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.RECTANGLE) + { + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ELLIPSE) + { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + context.beginPath(); + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + +}; + +/** + * Renders a graphics mask + * + * @static + * @private + * @method PIXI.CanvasGraphics.renderGraphicsMask + * @param graphics {Graphics} the graphics which will be used as a mask + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + */ +PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context) +{ + var len = graphics.graphicsData.length; + + if (len === 0) + { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === Phaser.POLYGON) + { + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + } + else if (data.type === Phaser.RECTANGLE) + { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } + else if (data.type === Phaser.ELLIPSE) + { + + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } +}; + +PIXI.CanvasGraphics.updateGraphicsTint = function(graphics) +{ + if (graphics.tint === 0xFFFFFF) + { + return; + } + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF)/ 255; + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255); + data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255); + + } + +}; + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + * @param lineWidth {number} the width of the line to draw + * @param lineColor {number} the color of the line to draw + * @param lineAlpha {number} the alpha of the line to draw + * @param fillColor {number} the color of the fill + * @param fillAlpha {number} the alpha of the fill + * @param fill {boolean} whether or not the shape is filled with a colour + * @param shape {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + +Phaser.GraphicsData = function (lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { + + /* + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /* + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /* + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /* + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /* + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /* + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /* + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /* + * @member {boolean} whether or not the shape is filled with a color + */ + this.fill = fill; + + /* + * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + this.shape = shape; + + /* + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + +}; + +Phaser.GraphicsData.prototype.constructor = Phaser.GraphicsData; + +/** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {GraphicsData} + */ +Phaser.GraphicsData.prototype.clone = function () { + + return new Phaser.GraphicsData( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.fill, + this.shape + ); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, +* Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will +* be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: +* +* ```javascript +* graphics.beginFill(0xff0000); +* graphics.drawCircle(50, 50, 100); +* graphics.endFill(); +* ``` +* +* This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. +* +* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or +* WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the +* graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. +* +* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help +* performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. +* You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then +* you should avoid doing this, as it will constantly generate new textures, which will consume memory. +* +* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful +* in their complexity and quantity of them in your game. +* +* @class Phaser.Graphics +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - X position of the new graphics object. +* @param {number} [y=0] - Y position of the new graphics object. +*/ +Phaser.Graphics = function (game, x, y) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.GRAPHICS; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value. + * @private + */ + this.anchor = new Phaser.Point(); + + PIXI.DisplayObjectContainer.call(this); + + this.renderable = true; + + /** + * The alpha value used when filling the Graphics object. + * + * @property fillAlpha + * @type Number + */ + this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @property lineWidth + * @type Number + */ + this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @property lineColor + * @type String + * @default 0 + */ + this.lineColor = 0; + + /** + * Graphics data + * + * @property graphicsData + * @type Array + * @private + */ + this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF (Phaser.Color.WHITE) to reset the tint. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * Current path + * + * @property currentPath + * @type Object + * @private + */ + this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @property _webGL + * @type Array + * @private + */ + this._webGL = []; + + /** + * Whether this shape is being used as a mask. + * + * @property isMask + * @type Boolean + */ + this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @property boundsPadding + * @type Number + */ + this.boundsPadding = 0; + + this._localBounds = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property dirty + * @type Boolean + * @private + */ + this.dirty = true; + + /** + * Used to detect if the bounds have been invalidated, by this Graphics being cleared or drawn to. + * If this is set to true then the updateLocalBounds is called once in the postUpdate method. + * + * @property _boundsDirty + * @type Boolean + * @private + */ + this._boundsDirty = false; + + /** + * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property webGLDirty + * @type Boolean + * @private + */ + this.webGLDirty = false; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @property cachedSpriteDirty + * @type Boolean + * @private + */ + this.cachedSpriteDirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.Graphics.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Graphics.prototype.constructor = Phaser.Graphics; + +Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Graphics#preUpdate +*/ +Phaser.Graphics.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World +* +* @method Phaser.Graphics#postUpdate +*/ +Phaser.Graphics.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this._boundsDirty) + { + this.updateLocalBounds(); + this._boundsDirty = false; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Destroy this Graphics instance. +* +* @method Phaser.Graphics#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Graphics.prototype.destroy = function (destroyChildren) { + + this.clear(); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Draws a single {@link Phaser.Polygon} triangle from a {@link Phaser.Point} array +* +* @method Phaser.Graphics#drawTriangle +* @param {Array} points - An array of Phaser.Points that make up the three vertices of this triangle +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangle = function (points, cull) { + + if (cull === undefined) { cull = false; } + + var triangle = new Phaser.Polygon(points); + + if (cull) + { + var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y); + var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y); + var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y); + var faceNormal = cb.cross(ab); + + if (cameraToFace.dot(faceNormal) > 0) + { + this.drawPolygon(triangle); + } + } + else + { + this.drawPolygon(triangle); + } + +}; + +/** +* Draws {@link Phaser.Polygon} triangles +* +* @method Phaser.Graphics#drawTriangles +* @param {Array|Array} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles +* @param {Array} [indices=null] - An array of numbers that describe what order to draw the vertices in +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) { + + if (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 < vertices.length / 3; i++) + { + this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull); + } + } + else + { + for (i = 0; i < vertices.length / 6; i++) + { + point1.x = vertices[i * 6 + 0]; + point1.y = vertices[i * 6 + 1]; + point2.x = vertices[i * 6 + 2]; + point2.y = vertices[i * 6 + 3]; + point3.x = vertices[i * 6 + 4]; + point3.y = vertices[i * 6 + 5]; + this.drawTriangle([point1, point2, point3], cull); + } + } + } + else + { + if (vertices[0] instanceof Phaser.Point) + { + for (i = 0; i < indices.length /3; i++) + { + points.push(vertices[indices[i * 3 ]]); + points.push(vertices[indices[i * 3 + 1]]); + points.push(vertices[indices[i * 3 + 2]]); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + else + { + for (i = 0; i < indices.length; i++) + { + point1.x = vertices[indices[i] * 2]; + point1.y = vertices[indices[i] * 2 + 1]; + points.push(point1.copyTo({})); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + } +}; + +/** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. + * + * @method Phaser.Graphics#lineStyle + * @param lineWidth {Number} width of the line to draw, will update the objects stored style + * @param color {Number} color of the line to draw, will update the objects stored style + * @param alpha {Number} alpha of the line to draw, will update the objects stored style + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { + + this.lineWidth = lineWidth || 0; + this.lineColor = color || 0; + this.lineAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { + // halfway through a line? start a new one! + this.drawShape(new Phaser.Polygon(this.currentPath.shape.points.slice(-2))); + } + else + { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + +}; + +/** + * Moves the current drawing position to x, y. + * + * @method Phaser.Graphics#moveTo + * @param x {Number} the X coordinate to move to + * @param y {Number} the Y coordinate to move to + * @return {Graphics} + */ +Phaser.Graphics.prototype.moveTo = function (x, y) { + + this.drawShape(new Phaser.Polygon([ x, y ])); + + return this; + +}; + +/** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @method Phaser.Graphics#lineTo + * @param x {Number} the X coordinate to draw to + * @param y {Number} the Y coordinate to draw to + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineTo = function (x, y) { + + if (!this.currentPath) + { + this.moveTo(0, 0); + } + + this.currentPath.shape.points.push(x, y); + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @method Phaser.Graphics#quadraticCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [ 0, 0 ]; + } + } + else + { + this.moveTo(0,0); + } + + var xa, + ya, + n = 20, + points = this.currentPath.shape.points; + + if (points.length === 0) + { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var j = 0; + for (var i = 1; i <= n; ++i) + { + j = i / n; + + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + + points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), + ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a bezier curve and then draws it. + * + * @method Phaser.Graphics#bezierCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param cpX2 {Number} Second Control point x + * @param cpY2 {Number} Second Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + var n = 20, + dt, + dt2, + dt3, + t2, + t3, + points = this.currentPath.shape.points; + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + var j = 0; + + for (var i = 1; i <= n; ++i) + { + j = i / n; + + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, + dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @method Phaser.Graphics#arcTo + * @param x1 {Number} The x-coordinate of the beginning of the arc + * @param y1 {Number} The y-coordinate of the beginning of the arc + * @param x2 {Number} The x-coordinate of the end of the arc + * @param y2 {Number} The y-coordinate of the end of the arc + * @param radius {Number} The radius of the arc + * @return {Graphics} + */ +Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points.push(x1, y1); + } + } + else + { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points, + fromX = points[points.length-2], + fromY = points[points.length-1], + a1 = fromY - y1, + b1 = fromX - x1, + a2 = y2 - y1, + b2 = x2 - x1, + mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { + points.push(x1, y1); + } + } + else + { + var dd = a1 * a1 + b1 * b1, + cc = a2 * a2 + b2 * b2, + tt = a1 * a2 + b1 * b2, + k1 = radius * Math.sqrt(dd) / mm, + k2 = radius * Math.sqrt(cc) / mm, + j1 = k1 * tt / dd, + j2 = k2 * tt / cc, + cx = k1 * b2 + k2 * b1, + cy = k1 * a2 + k2 * a1, + px = b1 * (k2 + j1), + py = a1 * (k2 + j1), + qx = b2 * (k1 + j2), + qy = a2 * (k1 + j2), + startAngle = Math.atan2(py - cy, px - cx), + endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @method Phaser.Graphics#arc + * @param cx {Number} The x-coordinate of the center of the circle + * @param cy {Number} The y-coordinate of the center of the circle + * @param radius {Number} The radius of the circle + * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) + * @param endAngle {Number} The ending angle, in radians + * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. + * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. + * @return {Graphics} + */ +Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise, segments) { + + // If we do this we can never draw a full circle + if (startAngle === endAngle) + { + return this; + } + + if (anticlockwise === undefined) { anticlockwise = false; } + if (segments === undefined) { segments = 40; } + + if (!anticlockwise && endAngle <= startAngle) + { + endAngle += Math.PI * 2; + } + else if (anticlockwise && startAngle <= endAngle) + { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments; + + // Sweep check - moved here because we don't want to do the moveTo below if the arc fails + if (sweep === 0) + { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (anticlockwise && this.filling) + { + this.moveTo(cx, cy); + } + else + { + this.moveTo(startX, startY); + } + + // currentPath will always exist after calling a moveTo + var points = this.currentPath.shape.points; + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = (segMinus % 1) / segMinus; + + for (var i = 0; i <= segMinus; i++) + { + var real = i + remainder * i; + + var angle = ((theta) + startAngle + (theta2 * real)); + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, + ( (cTheta * -s) + (sTheta * c) ) * radius + cy); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @method Phaser.Graphics#beginFill + * @param color {Number} the color of the fill + * @param alpha {Number} the alpha of the fill + * @return {Graphics} + */ +Phaser.Graphics.prototype.beginFill = function (color, alpha) { + + this.filling = true; + this.fillColor = color || 0; + this.fillAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + +}; + +/** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @method Phaser.Graphics#endFill + * @return {Graphics} + */ +Phaser.Graphics.prototype.endFill = function () { + + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRect + * + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawRect = function (x, y, width, height) { + + this.drawShape(new Phaser.Rectangle(x, y, width, height)); + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRoundedRect + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. + */ +Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + + this.drawShape(new Phaser.RoundedRectangle(x, y, width, height, radius)); + + return this; + +}; + +/** + * Draws a circle. + * + * @method Phaser.Graphics#drawCircle + * @param x {Number} The X coordinate of the center of the circle + * @param y {Number} The Y coordinate of the center of the circle + * @param diameter {Number} The diameter of the circle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) { + + this.drawShape(new Phaser.Circle(x, y, diameter)); + + return this; + +}; + +/** + * Draws an ellipse. + * + * @method Phaser.Graphics#drawEllipse + * @param x {Number} The X coordinate of the center of the ellipse + * @param y {Number} The Y coordinate of the center of the ellipse + * @param width {Number} The half width of the ellipse + * @param height {Number} The half height of the ellipse + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawEllipse = function (x, y, width, height) { + + this.drawShape(new Phaser.Ellipse(x, y, width, height)); + + return this; + +}; + +/** + * Draws a polygon using the given path. + * + * @method Phaser.Graphics#drawPolygon + * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawPolygon = function (path) { + + if (path instanceof Phaser.Polygon) + { + path = path.points; + } + + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) + { + points[i] = arguments[i]; + } + } + + this.drawShape(new Phaser.Polygon(points)); + + return this; + +}; + +/** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @method Phaser.Graphics#clear + * @return {Graphics} + */ +Phaser.Graphics.prototype.clear = function () { + + this.lineWidth = 0; + this.filling = false; + + this.dirty = true; + this._boundsDirty = true; + this.clearDirty = true; + this.graphicsData = []; + + this.updateLocalBounds(); + + return this; + +}; + +/** + * Useful function that returns a texture of the graphics object that can then be used to create sprites + * This can be quite useful if your geometry is complicated and needs to be reused multiple times. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * @method Phaser.Graphics#generateTexture + * @param [resolution=1] {Number} The resolution of the texture being generated + * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts + * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0) + * @return {Texture} a texture of the graphics object + */ +Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, padding) { + + if (resolution === undefined) { resolution = 1; } + if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; } + if (padding === undefined) { padding = 0; } + + var bounds = this.getBounds(); + + bounds.width += padding; + bounds.height += padding; + + var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution); + + var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + + canvasBuffer.context.scale(resolution, resolution); + + canvasBuffer.context.translate(-bounds.x, -bounds.y); + + PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context); + + return texture; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Graphics#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderWebGL = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture on the gpu too! + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.worldAlpha = this.worldAlpha; + + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + + return; + } + else + { + renderSession.spriteBatch.stop(); + renderSession.blendModeManager.setBlendMode(this.blendMode); + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + if (this._filters) + { + renderSession.filterManager.pushFilter(this._filterBlock); + } + + // check blend mode + if (this.blendMode !== renderSession.spriteBatch.currentBlendMode) + { + renderSession.spriteBatch.currentBlendMode = this.blendMode; + var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode]; + renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + // check if the webgl graphic needs to be updated + if (this.webGLDirty) + { + this.dirty = true; + this.webGLDirty = false; + } + + PIXI.WebGLGraphics.renderGraphics(this, renderSession); + + // only render if it has children! + if (this.children.length) + { + renderSession.spriteBatch.start(); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + } + + if (this._filters) + { + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + renderSession.maskManager.popMask(this.mask, renderSession); + } + + renderSession.drawCount++; + + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method Phaser.Graphics#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderCanvas = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) + { + this.dirty = true; + this._prevTint = this.tint; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.alpha = this.alpha; + + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + + return; + } + else + { + var context = renderSession.context; + var transform = this.worldTransform; + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + var resolution = renderSession.resolution; + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + tx, + ty); + + PIXI.CanvasGraphics.renderGraphics(this, context); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + } + +}; + +/** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @method Phaser.Graphics#getBounds + * @return {Rectangle} the rectangular bounding area + */ +Phaser.Graphics.prototype.getBounds = function (matrix) { + + if (this._currentBounds) + { + return this._currentBounds; + } + + // Return an empty object if the item is a mask! + if (!this.renderable) + { + return Phaser.EmptyRectangle; + } + + if (this.dirty) + { + this.updateLocalBounds(); + this.webGLDirty = true; + this.cachedSpriteDirty = true; + this.dirty = false; + } + + var bounds = this._localBounds; + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = x1; + var maxY = y1; + + var minX = x1; + var minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + + this._bounds.x = minX; + this._bounds.width = maxX - minX; + + this._bounds.y = minY; + this._bounds.height = maxY - minY; + + this._currentBounds = this._bounds; + + return this._currentBounds; + +}; + +/** + * Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration. + * + * @method Phaser.Graphics#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +Phaser.Graphics.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Tests if a point is inside this graphics object +* +* @param point {Point} the point to test +* @return {boolean} the result of the test +*/ +Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) { + + if (tempPoint === undefined) { tempPoint = new Phaser.Point(); } + + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; i++) + { + var data = graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // only deal with fills.. + if (data.shape) + { + if (data.shape.contains(tempPoint.x, tempPoint.y)) + { + return true; + } + } + } + + return false; + +}; + +/** + * Update the bounds of the object + * + * @method Phaser.Graphics#updateLocalBounds + */ +Phaser.Graphics.prototype.updateLocalBounds = function () { + + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) + { + var shape, points, x, y, w, h; + + for (var i = 0; i < this.graphicsData.length; i++) + { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + shape = data.shape; + + if (type === Phaser.RECTANGLE || type === Phaser.ROUNDEDRECTANGLE) + { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.CIRCLE) + { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.ELLIPSE) + { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else + { + // POLY - assumes points are sequential, not Point objects + points = shape.points; + + for (var j = 0; j < points.length; j++) + { + if (points[j] instanceof Phaser.Point) + { + x = points[j].x; + y = points[j].y; + } + else + { + x = points[j]; + y = points[j + 1]; + + if (j < points.length - 1) + { + j++; + } + } + + minX = x - lineWidth < minX ? x - lineWidth : minX; + maxX = x + lineWidth > maxX ? x + lineWidth : maxX; + + minY = y - lineWidth < minY ? y - lineWidth : minY; + maxY = y + lineWidth > maxY ? y + lineWidth : maxY; + } + } + } + } + else + { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.x = minX - padding; + this._localBounds.width = (maxX - minX) + padding * 2; + + this._localBounds.y = minY - padding; + this._localBounds.height = (maxY - minY) + padding * 2; + +}; + +/** + * Generates the cached sprite when the sprite has cacheAsBitmap = true + * + * @method Phaser.Graphics#_generateCachedSprite + * @private + */ +Phaser.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); + } + + // leverage the anchor to account for the offset of the element + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + // this._cachedSprite.buffer.context.save(); + this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y); + + // make sure we set the alpha of the graphics to 1 for the render.. + this.worldAlpha = 1; + + // now render the graphic.. + PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context); + this._cachedSprite.alpha = this.alpha; + +}; + +/** + * Updates texture size based on canvas size + * + * @method Phaser.Graphics#updateCachedSpriteTexture + * @private + */ +Phaser.Graphics.prototype.updateCachedSpriteTexture = function () { + + var cachedSprite = this._cachedSprite; + var texture = cachedSprite.texture; + var canvas = cachedSprite.buffer.canvas; + + texture.baseTexture.width = canvas.width; + texture.baseTexture.height = canvas.height; + texture.crop.width = texture.frame.width = canvas.width; + texture.crop.height = texture.frame.height = canvas.height; + + cachedSprite._width = canvas.width; + cachedSprite._height = canvas.height; + + // update the dirty base textures + texture.baseTexture.dirty(); + +}; + +/** + * Destroys a previous cached sprite. + * + * @method Phaser.Graphics#destroyCachedSprite + */ +Phaser.Graphics.prototype.destroyCachedSprite = function () { + + this._cachedSprite.texture.destroy(true); + this._cachedSprite = null; + +}; + +/** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @method Phaser.Graphics#drawShape + * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. + * @return {GraphicsData} The generated GraphicsData object. + */ +Phaser.Graphics.prototype.drawShape = function (shape) { + + if (this.currentPath) + { + // check current path! + if (this.currentPath.shape.points.length <= 2) + { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + // Handle mixed-type polygons + if (shape instanceof Phaser.Polygon) + { + shape = shape.clone(); + shape.flatten(); + } + + var data = new Phaser.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === Phaser.POLYGON) + { + data.shape.closed = this.filling; + this.currentPath = data; + } + + this.dirty = true; + this._boundsDirty = true; + + return data; + +}; + +/** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory. + * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas. + * This is not recommended if you are constantly redrawing the graphics element. + * + * @property cacheAsBitmap + * @type Boolean + * @default false + * @private + */ +Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + this._cacheAsBitmap = value; + + if (this._cacheAsBitmap) + { + this._generateCachedSprite(); + } + else + { + this.destroyCachedSprite(); + } + + this.dirty = true; + this.webGLDirty = true; + + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and +* render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. +* +* @class Phaser.RenderTexture +* @constructor +* @extends PIXI.Texture +* @param {Phaser.Game} game - Current game instance. +* @param {number} [width=100] - The width of the render texture. +* @param {number} [height=100] - The height of the render texture. +* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there. +* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts. +* @param {number} [resolution=1] - The resolution of the texture being generated. +*/ +Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution, renderer, textureUnit) { + + if (width === undefined) { width = 100; } + if (height === undefined) { height = 100; } + if (key === undefined) { key = ''; } + if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; } + if (resolution === undefined) { resolution = 1; } + if (renderer === undefined) { renderer = PIXI.defaultRenderer; } + if (textureUnit === undefined) { textureUnit = 0; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the RenderTexture in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RENDERTEXTURE; + + /** + * @property {Phaser.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture. + * @private + */ + this._tempMatrix = new Phaser.Matrix(); + + this.width = width; + this.height = height; + this.resolution = resolution; + + this.frame = new Phaser.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); + + this.crop = this.frame.clone(); + + /** + * The base texture object that this texture uses + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = new PIXI.BaseTexture(); + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + this.baseTexture._glTextures = []; + this.baseTexture.resolution = this.resolution; + + this.baseTexture.scaleMode = scaleMode; + + this.baseTexture.hasLoaded = true; + + PIXI.Texture.call(this, this.baseTexture, this.frame.clone()); + + /** + * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. + * + * @property renderer + * @type CanvasRenderer|WebGLRenderer + */ + this.renderer = renderer; + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + this.baseTexture.textureIndex = textureUnit; + this.baseTexture._dirty[gl.id] = false; + + this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode, textureUnit); + this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; + + this.projection = new Phaser.Point(this.width * 0.5, -this.height * 0.5); + } + else + { + this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution); + this.baseTexture.source = this.textureBuffer.canvas; + } + + /** + * @property valid + * @type Boolean + */ + this.valid = true; + + this.tempMatrix = new Phaser.Matrix(); + + this._updateUvs(); + +}; + +Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype); +Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it takes into account scale and rotation. +* +* If you don't want those then use RenderTexture.renderRawXY instead. +* +* @method Phaser.RenderTexture.prototype.renderXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) { + + displayObject.updateTransform(); + + this._tempMatrix.copyFrom(displayObject.worldTransform); + this._tempMatrix.tx = x; + this._tempMatrix.ty = y; + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it doesn't take into account scale, rotation or translation. +* +* If you need those then use RenderTexture.renderXY instead. +* +* @method Phaser.RenderTexture.prototype.renderRawXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) { + + this._tempMatrix.identity().translate(x, y); + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture. +* +* In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. +* This is now a Matrix allowing you much more control over how the Display Object is rendered. +* If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. +* +* If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either +* pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. +* +* @method Phaser.RenderTexture.prototype.render +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) { + + if (matrix === undefined || matrix === null) + { + this._tempMatrix.copyFrom(displayObject.worldTransform); + } + else + { + this._tempMatrix.copyFrom(matrix); + } + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* Resizes the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.resize +* @param {number} width - The width to resize to. +* @param {number} height - The height to resize to. +* @param {boolean} updateBase - Should the baseTexture.width and height values be resized as well? +*/ +Phaser.RenderTexture.prototype.resize = function (width, height, updateBase) { + + if (width === this.width && height === this.height) + { + return; + } + + this.valid = (width > 0 && height > 0); + + this.width = width; + this.height = height; + this.frame.width = this.crop.width = width * this.resolution; + this.frame.height = this.crop.height = height * this.resolution; + + if (updateBase) + { + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.projection.x = this.width / 2; + this.projection.y = -this.height / 2; + } + + if (!this.valid) + { + return; + } + + this.textureBuffer.resize(this.width, this.height); + +}; + +/** +* Clears the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.clear +*/ +Phaser.RenderTexture.prototype.clear = function () { + + if (!this.valid) + { + return; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + } + + this.textureBuffer.clear(); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderWebGL +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +* @private +*/ +Phaser.RenderTexture.prototype._renderWebGL = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + wt.translate(0, this.projection.y * 2); + + if (matrix) + { + wt.append(matrix); + } + + wt.scale(1, -1); + + // Time to update all the children of the displayObject with the new matrix. + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + // Time for the webGL fun stuff! + var gl = this.renderer.gl; + + gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + + if (clear) + { + this.textureBuffer.clear(); + } + + this.renderer.spriteBatch.dirty = true; + + this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix); + + this.renderer.spriteBatch.dirty = true; + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderCanvas +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +*/ +Phaser.RenderTexture.prototype._renderCanvas = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + + if (matrix) + { + wt.append(matrix); + } + + // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!) + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + if (clear) + { + this.textureBuffer.clear(); + } + + var realResolution = this.renderer.resolution; + + this.renderer.resolution = this.resolution; + + this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix); + + this.renderer.resolution = realResolution; + +}; + +/** +* Will return a HTML Image of the texture +* +* @method Phaser.RenderTexture.prototype.getImage +* @return {Image} +*/ +Phaser.RenderTexture.prototype.getImage = function () { + + var image = new Image(); + image.src = this.getBase64(); + + return image; + +}; + +/** +* Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. +* +* @method Phaser.RenderTexture.prototype.getBase64 +* @return {String} A base64 encoded string of the texture. +*/ +Phaser.RenderTexture.prototype.getBase64 = function () { + + return this.getCanvas().toDataURL(); + +}; + +/** +* Creates a Canvas element, renders this RenderTexture to it and then returns it. +* +* @method Phaser.RenderTexture.prototype.getCanvas +* @return {HTMLCanvasElement} A Canvas element with the texture rendered on. +*/ +Phaser.RenderTexture.prototype.getCanvas = function () { + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + var width = this.textureBuffer.width; + var height = this.textureBuffer.height; + + var webGLPixels = new Uint8Array(4 * width * height); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + var tempCanvas = new PIXI.CanvasBuffer(width, height); + var canvasData = tempCanvas.context.getImageData(0, 0, width, height); + canvasData.data.set(webGLPixels); + + tempCanvas.context.putImageData(canvasData, 0, 0); + + return tempCanvas.canvas; + } + else + { + return this.textureBuffer.canvas; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new game object for displaying Text. +* +* This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. +* Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. +* +* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers. +* +* @class Phaser.Text +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {number} x - X position of the new text object. +* @param {number} y - Y position of the new text object. +* @param {string} text - The actual text that will be written. +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +*/ +Phaser.Text = function (game, x, y, text, style) { + + x = x || 0; + y = y || 0; + + if (text === undefined || text === null) + { + text = ''; + } + else + { + text = text.toString(); + } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.TEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. + * @property {Phaser.Point} padding + */ + this.padding = new Phaser.Point(); + + /** + * The textBounds property allows you to specify a rectangular region upon which text alignment is based. + * See `Text.setTextBounds` for more details. + * @property {Phaser.Rectangle} textBounds + * @readOnly + */ + this.textBounds = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. + */ + this.canvas = Phaser.CanvasPool.create(this); + + /** + * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. + */ + this.context = this.canvas.getContext('2d'); + + /** + * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}. + */ + this.colors = []; + + /** + * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}. + */ + this.strokeColors = []; + + /** + * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}. + */ + this.fontStyles = []; + + /** + * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}. + */ + this.fontWeights = []; + + /** + * Should the linePositionX and Y values be automatically rounded before rendering the Text? + * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. + * @property {boolean} autoRound + * @default + */ + this.autoRound = false; + + /** + * Will this Text object use Basic or Advanced Word Wrapping? + * + * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. + * White space is condensed (e.g., consecutive spaces are replaced with one). + * Lines are trimmed of white space before processing. + * + * It throws an error if wordWrapWidth is less than a single character. + * @property {boolean} useAdvancedWrap + * @default + */ + this.useAdvancedWrap = false; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + * @property {Object} splitRegExp + */ + this.splitRegExp = /(?:\r\n|\r|\n)/; + + + /** The maximum number of characters that can be set. + * @property {number} characterLimitSize + */ + this.characterLimitSize = -1; + + /** The suffix that is applied to truncated text that is longer than the + * characterLimitSize. + * @property {string} characterLimitSuffix + */ + this.characterLimitSuffix = ''; + + /** + * @property {number} _res - Internal canvas resolution var. + * @private + */ + this._res = game.renderer.resolution; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text; + + /** + * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`. + * @private + */ + this._fontComponents = null; + + /** + * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. + * @private + */ + this._lineSpacing = 0; + + /** + * @property {number} _charCount - Internal character counter used by the text coloring. + * @private + */ + this._charCount = 0; + + /** + * @property {number} _width - Internal width var. + * @private + */ + this._width = 0; + + /** + * @property {number} _height - Internal height var. + * @private + */ + this._height = 0; + + Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas)); + + /** + * @property {object} style + * @private + */ + this.style = {}; + + this.setStyle(style || {}); + + if (text !== '') + { + this.updateText(); + } + +}; + +Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Text.prototype.constructor = Phaser.Text; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Text#preUpdate +* @protected +*/ +Phaser.Text.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override this function to handle any special update requirements. +* +* @method Phaser.Text#update +* @protected +*/ +Phaser.Text.prototype.update = function() { + +}; + +/** +* Destroy this Text object, removing it from the group it belongs to. +* +* @method Phaser.Text#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Text.prototype.destroy = function (destroyChildren) { + + this.texture.destroy(true); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. +* The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. +* The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. +* To remove a shadow already in place you can call this method with no parameters set. +* +* @method Phaser.Text#setShadow +* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +* @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. +* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +* @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set). +* @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; } + if (blur === undefined) { blur = 0; } + if (shadowStroke === undefined) { shadowStroke = true; } + if (shadowFill === undefined) { shadowFill = true; } + + this.style.shadowOffsetX = x; + this.style.shadowOffsetY = y; + this.style.shadowColor = color; + this.style.shadowBlur = blur; + this.style.shadowStroke = shadowStroke; + this.style.shadowFill = shadowFill; + this.dirty = true; + + return this; + +}; + +/** +* Set the style of the text by passing a single style object to it. +* +* @method Phaser.Text#setStyle +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +* @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setStyle = function (style, update) { + + if (update === undefined) { update = false; } + + var newStyle = Object.assign({}, style); + newStyle.font = style.font || 'bold 20pt Arial'; + newStyle.backgroundColor = style.backgroundColor || null; + newStyle.fill = style.fill || 'black'; + newStyle.align = (style.align || 'left').toLowerCase(); + newStyle.boundsAlignH = (style.boundsAlignH || 'left').toLowerCase(); + newStyle.boundsAlignV = (style.boundsAlignV || 'top').toLowerCase(); + newStyle.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136 + newStyle.strokeThickness = Number(style.strokeThickness) || 0; + newStyle.wordWrap = style.wordWrap || false; + newStyle.wordWrapWidth = style.wordWrapWidth || 100; + newStyle.maxLines = style.maxLines || 0; + newStyle.shadowOffsetX = style.shadowOffsetX || 0; + newStyle.shadowOffsetY = style.shadowOffsetY || 0; + newStyle.shadowColor = style.shadowColor || 'rgba(0,0,0,0)'; + newStyle.shadowBlur = style.shadowBlur || 0; + newStyle.tabs = style.tabs || 0; + + var components = this.fontToComponents(newStyle.font); + + if (newStyle.fontStyle) + { + components.fontStyle = newStyle.fontStyle; + } + + if (newStyle.fontVariant) + { + components.fontVariant = newStyle.fontVariant; + } + + if (newStyle.fontWeight) + { + components.fontWeight = newStyle.fontWeight; + } + + if (newStyle.fontSize) + { + if (typeof newStyle.fontSize === 'number') + { + newStyle.fontSize = newStyle.fontSize + 'px'; + } + + components.fontSize = newStyle.fontSize; + } + + this._fontComponents = components; + + newStyle.font = this.componentsToFont(this._fontComponents); + + this.style = newStyle; + this.dirty = true; + + if (update) + { + this.updateText(); + } + + return this; + +}; + +/** +* Renders text to the internal canvas. +* +* @method Phaser.Text#updateText +* @private +*/ +Phaser.Text.prototype.updateText = function () { + + this.texture.baseTexture.resolution = this._res; + + this.context.font = this.style.font; + + var outputText = this.text; + + if (this.characterLimitSize > -1 && this.characterLimitSize < outputText.length) { + outputText = this.text.substring(0, this.characterLimitSize) + this.characterLimitSuffix; + } + + if (this.style.wordWrap) + { + outputText = this.runWordWrap(this.text); + } + + // Split text into lines + var lines = outputText.split(this.splitRegExp); + + // Calculate text width + var tabs = this.style.tabs; + var lineWidths = []; + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this.style.font); + + var drawnLines = lines.length; + + if (this.style.maxLines > 0 && this.style.maxLines < lines.length) + { + drawnLines = this.style.maxLines; + } + + this._charCount = 0; + + for (var i = 0; i < drawnLines; i++) + { + if (tabs === 0) + { + // Simple layout (no tabs) + var lineWidth = this.style.strokeThickness + this.padding.x; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(lines[i]); + } + else + { + lineWidth += this.context.measureText(lines[i]).width; + } + + // Adjust for wrapped text + if (this.style.wordWrap) + { + lineWidth -= this.context.measureText(' ').width; + } + } + else + { + // Complex layout (tabs) + var line = lines[i].split(/(?:\t)/); + var lineWidth = this.padding.x + this.style.strokeThickness; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < line.length; c++) + { + var section = 0; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + section = this.measureLine(line[c]); + } + else + { + section = Math.ceil(this.context.measureText(line[c]).width); + } + + if (c > 0) + { + tab += tabs[c - 1]; + } + + lineWidth = tab + section; + } + } + else + { + for (var c = 0; c < line.length; c++) + { + // How far to the next tab? + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(line[c]); + } + else + { + lineWidth += Math.ceil(this.context.measureText(line[c]).width); + } + + var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth; + + lineWidth += diff; + } + } + } + + lineWidths[i] = Math.ceil(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); + } + + this.canvas.width = maxLineWidth * this._res; + + // Calculate text height + var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y; + var height = lineHeight * drawnLines; + var lineSpacing = this._lineSpacing; + + if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight) + { + lineSpacing = -lineHeight; + } + + // Adjust for line spacing + if (lineSpacing !== 0) + { + height += (lineSpacing > 0) ? lineSpacing * lines.length : lineSpacing * (lines.length - 1); + } + + this.canvas.height = height * this._res; + + this.context.scale(this._res, this._res); + + if (navigator.isCocoonJS) + { + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + } + + if (this.style.backgroundColor) + { + this.context.fillStyle = this.style.backgroundColor; + this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); + } + + this.context.fillStyle = this.style.fill; + this.context.font = this.style.font; + this.context.strokeStyle = this.style.stroke; + this.context.textBaseline = 'alphabetic'; + + this.context.lineWidth = this.style.strokeThickness; + this.context.lineCap = 'round'; + this.context.lineJoin = 'round'; + + var linePositionX; + var linePositionY; + + this._charCount = 0; + + // Draw text line by line + for (i = 0; i < drawnLines; i++) + { + // Split the line by + + linePositionX = this.style.strokeThickness / 2; + linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (i > 0) + { + linePositionY += (lineSpacing * i); + } + + if (this.style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (this.style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (this.autoRound) + { + linePositionX = Math.round(linePositionX); + linePositionY = Math.round(linePositionY); + } + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + this.updateLine(lines[i], linePositionX, linePositionY); + } + else + { + if (this.style.stroke && this.style.strokeThickness) + { + this.updateShadow(this.style.shadowStroke); + + if (tabs === 0) + { + this.context.strokeText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, false); + } + } + + if (this.style.fill) + { + this.updateShadow(this.style.shadowFill); + + if (tabs === 0) + { + this.context.fillText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, true); + } + } + } + } + + this.updateTexture(); + + this.dirty = false; + +}; + +/** +* Renders a line of text that contains tab characters if Text.tab > 0. +* Called automatically by updateText. +* +* @method Phaser.Text#renderTabLine +* @private +* @param {string} line - The line of text to render. +* @param {integer} x - The x position to start rendering from. +* @param {integer} y - The y position to start rendering from. +* @param {boolean} fill - If true uses fillText, if false uses strokeText. +*/ +Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) { + + var text = line.split(/(?:\t)/); + var tabs = this.style.tabs; + var snap = 0; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < text.length; c++) + { + if (c > 0) + { + tab += tabs[c - 1]; + } + + snap = x + tab; + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + } + } + else + { + for (var c = 0; c < text.length; c++) + { + var section = Math.ceil(this.context.measureText(text[c]).width); + + // How far to the next tab? + snap = this.game.math.snapToCeil(x, tabs); + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + + x = snap + section; + } + } + +}; + +/** +* Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. +* This is called automatically by Text.updateText. +* +* @method Phaser.Text#updateShadow +* @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero. +*/ +Phaser.Text.prototype.updateShadow = function (state) { + + if (state) + { + this.context.shadowOffsetX = this.style.shadowOffsetX; + this.context.shadowOffsetY = this.style.shadowOffsetY; + this.context.shadowColor = this.style.shadowColor; + this.context.shadowBlur = this.style.shadowBlur; + } + else + { + this.context.shadowOffsetX = 0; + this.context.shadowOffsetY = 0; + this.context.shadowColor = 0; + this.context.shadowBlur = 0; + } + +}; + +/** +* Measures a line of text character by character taking into the account the specified character styles. +* +* @method Phaser.Text#measureLine +* @private +* @param {string} line - The line of text to measure. +* @return {integer} length of the line. +*/ +Phaser.Text.prototype.measureLine = function (line) { + + var lineLength = 0; + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + } + + lineLength += this.context.measureText(letter).width; + + this._charCount++; + } + + return Math.ceil(lineLength); +}; + +/** +* Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable. +* +* @method Phaser.Text#updateLine +* @private +*/ +Phaser.Text.prototype.updateLine = function (line, x, y) { + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + this.context.strokeText(letter, x, y); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + this.context.fillText(letter, x, y); + } + + x += this.context.measureText(letter).width; + + this._charCount++; + } + +}; + +/** +* Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. +* +* @method Phaser.Text#clearColors +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearColors = function () { + + this.colors = []; + this.strokeColors = []; + this.dirty = true; + + return this; + +}; + +/** +* Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. +* +* @method Phaser.Text#clearFontValues +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearFontValues = function () { + + this.fontStyles = []; + this.fontWeights = []; + this.dirty = true; + + return this; + +}; + +/** +* Set specific colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* If you wish to change the stroke color see addStrokeColor instead. +* +* @method Phaser.Text#addColor +* @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addColor = function (color, position) { + + this.colors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific stroke colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* This has no effect if stroke is disabled or has a thickness of 0. +* +* If you wish to change the text fill color see addColor instead. +* +* @method Phaser.Text#addStrokeColor +* @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addStrokeColor = function (color, position) { + + this.strokeColors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font styles for certain characters within the Text. +* +* It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. +* The position value is the index of the character in the Text string to start applying this font style to. +* Once set the font style remains in use until either another font style or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. +* +* If you wish to change the text font weight see addFontWeight instead. +* +* @method Phaser.Text#addFontStyle +* @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. +* @param {number} position - The index of the character in the string to start applying this font style value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontStyle = function (style, position) { + + this.fontStyles[position] = style; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font weights for certain characters within the Text. +* +* It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. +* The position value is the index of the character in the Text string to start applying this font weight to. +* Once set the font weight remains in use until either another font weight or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. +* +* If you wish to change the text font style see addFontStyle instead. +* +* @method Phaser.Text#addFontWeight +* @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. +* @param {number} position - The index of the character in the string to start applying this font weight value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontWeight = function (weight, position) { + + this.fontWeights[position] = weight; + this.dirty = true; + + return this; + +}; + +/** +* Runs the given text through the Text.runWordWrap function and returns +* the results as an array, where each element of the array corresponds to a wrapped +* line of text. +* +* Useful if you wish to control pagination on long pieces of content. +* +* @method Phaser.Text#precalculateWordWrap +* @param {string} text - The text for which the wrapping will be calculated. +* @return {array} An array of strings with the pieces of wrapped text. +*/ +Phaser.Text.prototype.precalculateWordWrap = function (text) { + + this.texture.baseTexture.resolution = this._res; + this.context.font = this.style.font; + + var wrappedLines = this.runWordWrap(text); + + return wrappedLines.split(/(?:\r\n|\r|\n)/); + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#runWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.runWordWrap = function (text) { + + if (this.useAdvancedWrap) + { + return this.advancedWordWrap(text); + } + else + { + return this.basicWordWrap(text); + } + +}; + +/** +* Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* White space is condensed (e.g., consecutive spaces are replaced with one). +* Lines are trimmed of white space before processing. +* Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character. +* +* @method Phaser.Text#advancedWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.advancedWordWrap = function (text) { + + var context = this.context; + var wordWrapWidth = this.style.wordWrapWidth; + + var output = ''; + + // (1) condense whitespace + // (2) split into lines + var lines = text + .replace(/ +/gi, ' ') + .split(/\r?\n/gi); + + var linesCount = lines.length; + + for (var i = 0; i < linesCount; i++) + { + var line = lines[i]; + var out = ''; + + // trim whitespace + line = line.replace(/^ *|\s*$/gi, ''); + + // if entire line is less than wordWrapWidth + // append the entire line and exit early + var lineWidth = context.measureText(line).width; + + if (lineWidth < wordWrapWidth) + { + output += line + '\n'; + continue; + } + + // otherwise, calculate new lines + var currentLineWidth = wordWrapWidth; + + // split into words + var words = line.split(' '); + + for (var j = 0; j < words.length; j++) + { + var word = words[j]; + var wordWithSpace = word + ' '; + var wordWidth = context.measureText(wordWithSpace).width; + + if (wordWidth > currentLineWidth) + { + // break word + if (j === 0) + { + // shave off letters from word until it's small enough + var newWord = wordWithSpace; + + while (newWord.length) + { + newWord = newWord.slice(0, -1); + wordWidth = context.measureText(newWord).width; + + if (wordWidth <= currentLineWidth) + { + break; + } + } + + // if wordWrapWidth is too small for even a single + // letter, shame user failure with a fatal error + if (!newWord.length) + { + throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); + } + + // replace current word in array with remainder + var secondPart = word.substr(newWord.length); + + words[j] = secondPart; + + // append first piece to output + out += newWord; + } + + // if existing word length is 0, don't include it + var offset = (words[j].length) ? j : j + 1; + + // collapse rest of sentence + var remainder = words.slice(offset).join(' ') + // remove any trailing white space + .replace(/[ \n]*$/gi, ''); + + // prepend remainder to next line + lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); + linesCount = lines.length; + + break; // processing on this line + + // append word with space to output + } + else + { + out += wordWithSpace; + currentLineWidth -= wordWidth; + } + } + + // append processed line to output + output += out.replace(/[ \n]*$/gi, '') + '\n'; + } + + // trim the end of the string + output = output.replace(/[\s|\n]*$/gi, ''); + + return output; + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#basicWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.basicWordWrap = function (text) { + + var result = ''; + var lines = text.split('\n'); + + for (var i = 0; i < lines.length; i++) + { + var spaceLeft = this.style.wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) + { + var wordWidth = this.context.measureText(words[j]).width; + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is greater than the word wrap width. + if (j > 0) + { + result += '\n'; + } + result += words[j] + ' '; + spaceLeft = this.style.wordWrapWidth - wordWidth; + } + else + { + spaceLeft -= wordWidthWithSpace; + result += words[j] + ' '; + } + } + + if (i < lines.length-1) + { + result += '\n'; + } + } + + return result; + +}; + +/** +* Updates the internal `style.font` if it now differs according to generation from components. +* +* @method Phaser.Text#updateFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.updateFont = function (components) { + + var font = this.componentsToFont(components); + + if (this.style.font !== font) + { + this.style.font = font; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + +}; + +/** +* Converting a short CSS-font string into the relevant components. +* +* @method Phaser.Text#fontToComponents +* @private +* @param {string} font - a CSS font string +*/ +Phaser.Text.prototype.fontToComponents = function (font) { + + // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand: + // style - normal | italic | oblique | inherit + // variant - normal | small-caps | inherit + // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit + // size - xx-small | x-small | small | medium | large | x-large | xx-large, + // larger | smaller + // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %) + // font-family - rest (but identifiers or quoted with comma separation) + var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/); + + if (m) + { + var family = m[5].trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(family) && !/['",]/.exec(family)) + { + family = "'" + family + "'"; + } + + return { + font: font, + fontStyle: m[1] || 'normal', + fontVariant: m[2] || 'normal', + fontWeight: m[3] || 'normal', + fontSize: m[4] || 'medium', + fontFamily: family + }; + } + else + { + console.warn("Phaser.Text - unparsable CSS font: " + font); + + return { + font: font + }; + } + +}; + +/** +* Converts individual font components (see `fontToComponents`) to a short CSS font string. +* +* @method Phaser.Text#componentsToFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.componentsToFont = function (components) { + + var parts = []; + var v; + + v = components.fontStyle; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontVariant; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontWeight; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontSize; + if (v && v !== 'medium') { parts.push(v); } + + v = components.fontFamily; + if (v) { parts.push(v); } + + if (!parts.length) + { + // Fallback to whatever value the 'font' was + parts.push(components.font); + } + + return parts.join(" "); + +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* Use the optional `immediate` argument if you need the Text display to update immediately. +* +* If not it will re-create the texture of this Text object during the next time the render +* loop is called. +* +* @method Phaser.Text#setText +* @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present. +* @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setText = function (text, immediate) { + + if (immediate === undefined) { immediate = false; } + + this.text = text.toString() || ''; + + if (immediate) + { + this.updateText(); + } + else + { + this.dirty = true; + } + + return this; + +}; + +/** + * Converts the given array into a tab delimited string and then updates this Text object. + * This is mostly used when you want to display external data using tab stops. + * + * The array can be either single or multi dimensional depending on the result you need: + * + * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`. + * + * Where as: + * + * `[ + * [ 'a', 'b', 'c' ], + * [ 'd', 'e', 'f'] + * ]` + * + * would convert in to: `"a\tb\tc\nd\te\tf"` + * + * @method Phaser.Text#parseList + * @param {array} list - The array of data to convert into a string. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.parseList = function (list) { + + if (!Array.isArray(list)) + { + return this; + } + else + { + var s = ""; + + for (var i = 0; i < list.length; i++) + { + if (Array.isArray(list[i])) + { + s += list[i].join("\t"); + + if (i < list.length - 1) + { + s += "\n"; + } + } + else + { + s += list[i]; + + if (i < list.length - 1) + { + s += "\t"; + } + } + } + } + + this.text = s; + this.dirty = true; + + return this; + +}; + +/** + * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned, + * regardless of the number of lines in the text, the font size or any other attribute. + * + * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly + * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment. + * + * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to + * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of + * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center + * of the text bounds. + * + * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions + * may vary based on font (say for multi-lingual games). + * + * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width. + * + * Call this method with no arguments given to reset an existing textBounds. + * + * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts + * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot` + * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then + * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot. + * + * @method Phaser.Text#setTextBounds + * @param {number} [x] - The x coordinate of the Text Bounds region. + * @param {number} [y] - The y coordinate of the Text Bounds region. + * @param {number} [width] - The width of the Text Bounds region. + * @param {number} [height] - The height of the Text Bounds region. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.setTextBounds = function (x, y, width, height) { + + if (x === undefined) + { + this.textBounds = null; + } + else + { + if (!this.textBounds) + { + this.textBounds = new Phaser.Rectangle(x, y, width, height); + } + else + { + this.textBounds.setTo(x, y, width, height); + } + + if (this.style.wordWrapWidth > width) + { + this.style.wordWrapWidth = width; + } + } + + this.updateTexture(); + + return this; + +}; + +/** + * Updates the texture based on the canvas dimensions. + * + * @method Phaser.Text#updateTexture + * @private + */ +Phaser.Text.prototype.updateTexture = function () { + + var base = this.texture.baseTexture; + var crop = this.texture.crop; + var frame = this.texture.frame; + + var w = this.canvas.width; + var h = this.canvas.height; + + base.width = w; + base.height = h; + + crop.width = w; + crop.height = h; + + frame.width = w; + frame.height = h; + + this.texture.width = w; + this.texture.height = h; + + this._width = w; + this._height = h; + + if (this.textBounds) + { + var x = this.textBounds.x; + var y = this.textBounds.y; + + // Align the canvas based on the bounds + if (this.style.boundsAlignH === 'right') + { + x += this.textBounds.width - this.canvas.width / this.resolution; + } + else if (this.style.boundsAlignH === 'center') + { + x += this.textBounds.halfWidth - (this.canvas.width / this.resolution / 2); + } + + if (this.style.boundsAlignV === 'bottom') + { + y += this.textBounds.height - this.canvas.height / this.resolution; + } + else if (this.style.boundsAlignV === 'middle') + { + y += this.textBounds.halfHeight - (this.canvas.height / this.resolution / 2); + } + + this.pivot.x = -x; + this.pivot.y = -y; + } + + // Can't render something with a zero sized dimension + this.renderable = (w !== 0 && h !== 0); + + this.texture.requiresReTint = true; + + this.texture.baseTexture.dirty(); + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Text#_renderWebGL +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderWebGL = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Renders the object using the Canvas renderer. +* +* @method Phaser.Text#_renderCanvas +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderCanvas = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Calculates the ascent, descent and fontSize of a given font style. +* +* @method Phaser.Text#determineFontProperties +* @private +* @param {object} fontStyle +*/ +Phaser.Text.prototype.determineFontProperties = function (fontStyle) { + + var properties = Phaser.Text.fontPropertiesCache[fontStyle]; + + if (!properties) + { + properties = {}; + + var canvas = Phaser.Text.fontPropertiesCanvas; + var context = Phaser.Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('|MÉq').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + if (!context.getImageData(0, 0, width, height)) + { + properties.ascent = baseline; + properties.descent = baseline + 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + } + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i, j; + + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + properties.descent = i - baseline; + //TODO might need a tweak. kind of a temp fix! + properties.descent += 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; + +}; + +/** +* Returns the bounds of the Text as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Text#getBounds +* @param {Phaser.Matrix} matrix - The transformation matrix of the Text. +* @return {Phaser.Rectangle} The framing rectangle +*/ +Phaser.Text.prototype.getBounds = function (matrix) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return PIXI.Sprite.prototype.getBounds.call(this, matrix); + +}; + +/** +* Sets the character limit of the text, with a suffix. +* If the text is longer than this limit, it is truncated and the suffix is appended. +* +* @method Phaser.Text#setCharacterLimit +* @param {number} [characterLimit] - The x coordinate of the Text Bounds region. +* @param {string} [suffix] - The suffix to append to the truncated text. +*/ +Phaser.Text.prototype.setCharacterLimit = function (characterLimit, suffix) { + + this.characterLimitSuffix = (suffix === undefined) ? '' : suffix; + this.characterLimitSize = characterLimit; + + this.updateText(); +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* @name Phaser.Text#text +* @property {string} text +*/ +Object.defineProperty(Phaser.Text.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* Change the font used. +* +* This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except +* that unlike using `setStyle` this will not change any current font fill/color settings. +* +* The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. +* +* @name Phaser.Text#cssFont +* @property {string} cssFont +*/ +Object.defineProperty(Phaser.Text.prototype, 'cssFont', { + + get: function() { + return this.componentsToFont(this._fontComponents); + }, + + set: function (value) + { + value = value || 'bold 20pt Arial'; + this._fontComponents = this.fontToComponents(value); + this.updateFont(this._fontComponents); + } + +}); + +/** +* Change the font family that the text will be rendered in, such as 'Arial'. +* +* Multiple CSS font families and generic fallbacks can be specified as long as +* {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed. +* +* To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`. +* +* @name Phaser.Text#font +* @property {string} font +*/ +Object.defineProperty(Phaser.Text.prototype, 'font', { + + get: function() { + return this._fontComponents.fontFamily; + }, + + set: function(value) { + + value = value || 'Arial'; + value = value.trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value)) + { + value = "'" + value + "'"; + } + + this._fontComponents.fontFamily = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The size of the font. +* +* If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing +* the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). +* +* @name Phaser.Text#fontSize +* @property {number|string} fontSize +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontSize', { + + get: function() { + + var size = this._fontComponents.fontSize; + + if (size && /(?:^0$|px$)/.exec(size)) + { + return parseInt(size, 10); + } + else + { + return size; + } + + }, + + set: function(value) { + + value = value || '0'; + + if (typeof value === 'number') + { + value = value + 'px'; + } + + this._fontComponents.fontSize = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}. +* @name Phaser.Text#fontWeight +* @property {string} fontWeight +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontWeight', { + + get: function() { + return this._fontComponents.fontWeight || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontWeight = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The style of the font: 'normal', 'italic', 'oblique' +* @name Phaser.Text#fontStyle +* @property {string} fontStyle +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontStyle', { + + get: function() { + return this._fontComponents.fontStyle || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontStyle = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The variant the font: 'normal', 'small-caps' +* @name Phaser.Text#fontVariant +* @property {string} fontVariant +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontVariant', { + + get: function() { + return this._fontComponents.fontVariant || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontVariant = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* @name Phaser.Text#fill +* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'fill', { + + get: function() { + return this.style.fill; + }, + + set: function(value) { + + if (value !== this.style.fill) + { + this.style.fill = value; + this.dirty = true; + } + + } + +}); + +/** +* Controls the horizontal alignment for multiline text. +* Can be: 'left', 'center' or 'right'. +* Does not affect single lines of text. For that please see `setTextBounds`. +* @name Phaser.Text#align +* @property {string} align +*/ +Object.defineProperty(Phaser.Text.prototype, 'align', { + + get: function() { + return this.style.align; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.align) + { + this.style.align = value; + this.dirty = true; + } + + } + +}); + +/** +* The resolution of the canvas the text is rendered to. +* This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. +* @name Phaser.Text#resolution +* @property {integer} resolution +*/ +Object.defineProperty(Phaser.Text.prototype, 'resolution', { + + get: function() { + return this._res; + }, + + set: function(value) { + + if (value !== this._res) + { + this._res = value; + this.dirty = true; + } + + } + +}); + +/** +* The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. +* Can be an integer or an array of varying tab sizes, one tab per element. +* For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. +* If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. +* +* @name Phaser.Text#tabs +* @property {integer|array} tabs +*/ +Object.defineProperty(Phaser.Text.prototype, 'tabs', { + + get: function() { + return this.style.tabs; + }, + + set: function(value) { + + if (value !== this.style.tabs) + { + this.style.tabs = value; + this.dirty = true; + } + + } + +}); + +/** +* Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @name Phaser.Text#boundsAlignH +* @property {string} boundsAlignH +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', { + + get: function() { + return this.style.boundsAlignH; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignH) + { + this.style.boundsAlignH = value; + this.dirty = true; + } + + } + +}); + +/** +* Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @name Phaser.Text#boundsAlignV +* @property {string} boundsAlignV +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', { + + get: function() { + return this.style.boundsAlignV; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignV) + { + this.style.boundsAlignV = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#stroke +* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'stroke', { + + get: function() { + return this.style.stroke; + }, + + set: function(value) { + + if (value !== this.style.stroke) + { + this.style.stroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#strokeThickness +* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke) +*/ +Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', { + + get: function() { + return this.style.strokeThickness; + }, + + set: function(value) { + + if (value !== this.style.strokeThickness) + { + this.style.strokeThickness = Number(value); + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrap +* @property {boolean} wordWrap - Indicates if word wrap should be used. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrap', { + + get: function() { + return this.style.wordWrap; + }, + + set: function(value) { + + if (value !== this.style.wordWrap) + { + this.style.wordWrap = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrapWidth +* @property {number} wordWrapWidth - The width at which text will wrap. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', { + + get: function() { + return this.style.wordWrapWidth; + }, + + set: function(value) { + + if (value !== this.style.wordWrapWidth) + { + this.style.wordWrapWidth = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#lineSpacing +* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. +*/ +Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { + + get: function() { + return this._lineSpacing; + }, + + set: function(value) { + + if (value !== this._lineSpacing) + { + this._lineSpacing = parseFloat(value); + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetX +* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', { + + get: function() { + return this.style.shadowOffsetX; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetX) + { + this.style.shadowOffsetX = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetY +* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', { + + get: function() { + return this.style.shadowOffsetY; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetY) + { + this.style.shadowOffsetY = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowColor +* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowColor', { + + get: function() { + return this.style.shadowColor; + }, + + set: function(value) { + + if (value !== this.style.shadowColor) + { + this.style.shadowColor = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowBlur +* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', { + + get: function() { + return this.style.shadowBlur; + }, + + set: function(value) { + + if (value !== this.style.shadowBlur) + { + this.style.shadowBlur = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowStroke +* @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', { + + get: function() { + return this.style.shadowStroke; + }, + + set: function(value) { + + if (value !== this.style.shadowStroke) + { + this.style.shadowStroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowFill +* @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowFill', { + + get: function() { + return this.style.shadowFill; + }, + + set: function(value) { + + if (value !== this.style.shadowFill) + { + this.style.shadowFill = value; + this.dirty = true; + } + + } + +}); + +/** +* The width of the Text object in pixels. This is width of the Texture frame / the Text.resolution. +* @name Phaser.Text#width +* @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'width', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.x * (this.texture.frame.width / this.resolution); + }, + + set: function(value) { + + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** +* The height of the Text object in pixels. This is height of the Texture frame / the Text.resolution. +* @name Phaser.Text#height +* @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'height', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.y * (this.texture.frame.height / this.resolution); + }, + + set: function(value) { + + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +Phaser.Text.fontPropertiesCache = {}; + +Phaser.Text.fontPropertiesCanvas = document.createElement('canvas'); +Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d'); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. +* It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to +* match the font structure. +* +* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability +* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by +* processing the font texture in an image editor, applying fills and any other effects required. +* +* To create multi-line text insert \r, \n or \r\n escape codes into the text string. +* +* If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly +* updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. +* +* To create a BitmapText data files you can use: +* +* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ +* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner +* Littera (Web-based, free): http://kvazars.com/littera/ +* +* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of +* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson +* +* If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. +* +* @class Phaser.BitmapText +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - X coordinate to display the BitmapText object at. +* @param {number} y - Y coordinate to display the BitmapText object at. +* @param {string} font - The key of the BitmapText as stored in Phaser.Cache. +* @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. +* @param {number} [size=32] - The size the font will be rendered at in pixels. +* @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. +*/ +Phaser.BitmapText = function (game, x, y, font, text, size, align) { + + x = x || 0; + y = y || 0; + font = font || ''; + text = text || ''; + size = size || 32; + align = align || 'left'; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.BITMAPTEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textWidth = 0; + + /** + * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textHeight = 0; + + /** + * @property {Phaser.Point} anchor - The anchor value of this BitmapText. + */ + this.anchor = new Phaser.Point(); + + /** + * @property {Phaser.Point} _prevAnchor - The previous anchor value. + * @private + */ + this._prevAnchor = new Phaser.Point(); + + /** + * @property {array} _glyphs - Private tracker for the letter sprite pool. + * @private + */ + this._glyphs = []; + + /** + * @property {number} _maxWidth - Internal cache var. + * @private + */ + this._maxWidth = 0; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text.toString() || ''; + + /** + * @property {string} _data - Internal cache var. + * @private + */ + this._data = game.cache.getBitmapFont(font); + + /** + * @property {string} _font - Internal cache var. + * @private + */ + this._font = font; + + /** + * @property {number} _fontSize - Internal cache var. + * @private + */ + this._fontSize = size; + + /** + * @property {string} _align - Internal cache var. + * @private + */ + this._align = align; + + /** + * @property {number} _tint - Internal cache var. + * @private + */ + this._tint = 0xFFFFFF; + + this.updateText(); + + /** + * @property {boolean} dirty - The dirty state of this object. + */ + this.dirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.BitmapText.prototype.constructor = Phaser.BitmapText; + +Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.BitmapText +* @return {boolean} True if the BitmapText was rendered, otherwise false. +*/ +Phaser.BitmapText.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.preUpdate. +* @method Phaser.BitmapText.prototype.postUpdate +*/ +Phaser.BitmapText.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this.body && this.body.type === Phaser.Physics.ARCADE) + { + if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight)) + { + this.body.setSize(this.textWidth, this.textHeight); + } + } + +}; + +/** +* The text to be displayed by this BitmapText object. +* +* It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. +* +* @method Phaser.BitmapText.prototype.setText +* @param {string} text - The text to be displayed by this BitmapText object. +*/ +Phaser.BitmapText.prototype.setText = function (text) { + + this.text = text; + +}; + +/** +* Given the input text this will scan the characters until either a newline is encountered, +* or the line exceeds maxWidth, taking into account kerning, character widths and scaling. +* +* @method Phaser.BitmapText.prototype.scanLine +* @private +* @param {object} data - A reference to the font object in the Phaser.Cache. +* @param {float} scale - The scale of the font in relation to the texture. +* @param {string} text - The text to parse. +* @return {object} An object containing the parsed characters, total pixel width and x offsets. +*/ +Phaser.BitmapText.prototype.scanLine = function (data, scale, text) { + + var x = 0; + var w = 0; + var lastSpace = -1; + var wrappedWidth = 0; + var prevCharCode = null; + var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null; + var chars = []; + + // Let's scan the text and work out if any of the lines are > maxWidth + for (var i = 0; i < text.length; i++) + { + var end = (i === text.length - 1) ? true : false; + + if (/(?:\r\n|\r|\n)/.test(text.charAt(i))) + { + return { width: w, text: text.substr(0, i), end: end, chars: chars }; + } + else + { + var charCode = text.charCodeAt(i); + var charData = data.chars[charCode]; + + var c = 0; + + // If the character data isn't found in the data array + // then we replace it with a blank space + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + // Adjust for kerning from previous character to this one + var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0; + + // Record the last space in the string and the current width + if (/(\s)/.test(text.charAt(i))) + { + lastSpace = i; + wrappedWidth = w; + } + + // What will the line width be if we add this character to it? + c = (kerning + charData.texture.width + charData.xOffset) * scale; + + // Do we need to line-wrap? + if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1) + { + // The last space was at "lastSpace" which was "i - lastSpace" characters ago + return { width: wrappedWidth || w, text: text.substr(0, i - (i - lastSpace)), end: false, chars: chars }; + } + else + { + w += (charData.xAdvance + kerning) * scale; + + chars.push(x + (charData.xOffset + kerning) * scale); + + x += (charData.xAdvance + kerning) * scale; + + prevCharCode = charCode; + } + } + } + + return { width: w, text: text, end: end, chars: chars }; + +}; + +/** +* Given a text string this will scan each character in the string to ensure it exists +* in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. +* +* If no font data has been loaded at all this returns an empty string, as nothing can be rendered. +* +* @method Phaser.BitmapText.prototype.cleanText +* @param {string} text - The text to parse. +* @param {string} [replace=''] - The replacement string for any missing characters. +* @return {string} The cleaned text string. +*/ +Phaser.BitmapText.prototype.cleanText = function (text, replace) { + + if (replace === undefined) + { + replace = ''; + } + + var data = this._data.font; + + if (!data) + { + return ''; + } + + var re = /\r\n|\n\r|\n|\r/g; + var lines = text.replace(re, "\n").split("\n"); + + for (var i = 0; i < lines.length; i++) + { + var output = ''; + var line = lines[i]; + + for (var c = 0; c < line.length; c++) + { + if (data.chars[line.charCodeAt(c)]) + { + output = output.concat(line[c]); + } + else + { + output = output.concat(replace); + } + } + + lines[i] = output; + } + + return lines.join("\n"); + +}; + +/** +* Renders text and updates it when needed. +* +* @method Phaser.BitmapText.prototype.updateText +* @private +*/ +Phaser.BitmapText.prototype.updateText = function () { + + var data = this._data.font; + + if (!data) + { + return; + } + + var text = this.text; + var scale = this._fontSize / data.size; + var lines = []; + + var y = 0; + + this.textWidth = 0; + + do + { + var line = this.scanLine(data, scale, text); + + line.y = y; + + lines.push(line); + + if (line.width > this.textWidth) + { + this.textWidth = line.width; + } + + y += (data.lineHeight * scale); + + text = text.substr(line.text.length + 1); + + } while (line.end === false); + + this.textHeight = y; + + var t = 0; + var align = 0; + var ax = this.textWidth * this.anchor.x; + var ay = this.textHeight * this.anchor.y; + + for (var i = 0; i < lines.length; i++) + { + var line = lines[i]; + + if (this._align === 'right') + { + align = this.textWidth - line.width; + } + else if (this._align === 'center') + { + align = (this.textWidth - line.width) / 2; + } + + for (var c = 0; c < line.text.length; c++) + { + var charCode = line.text.charCodeAt(c); + var charData = data.chars[charCode]; + + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + var g = this._glyphs[t]; + + if (g) + { + // Sprite already exists in the glyphs pool, so we'll reuse it for this letter + g.texture = charData.texture; + } + else + { + // We need a new sprite as the pool is empty or exhausted + g = new PIXI.Sprite(charData.texture); + g.name = line.text[c]; + this._glyphs.push(g); + } + + g.position.x = (line.chars[c] + align) - ax; + g.position.y = (line.y + (charData.yOffset * scale)) - ay; + + g.scale.set(scale); + g.tint = this.tint; + g.texture.requiresReTint = true; + g.cachedTint = 0xFFFFFF; + + if (!g.parent) + { + this.addChild(g); + } + + t++; + } + } + + // Remove unnecessary children + // This moves them from the display list (children array) but retains them in the _glyphs pool + for (i = t; i < this._glyphs.length; i++) + { + this.removeChild(this._glyphs[i]); + } + +}; + +/** +* If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of +* Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they +* still take up memory while sat in the glyphs pool waiting to be re-used in the future. +* +* If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool +* by calling this method. +* +* Calling this doesn't prevent you from increasing the length of the text again in the future. +* +* @method Phaser.BitmapText.prototype.purgeGlyphs +* @return {integer} The amount of glyphs removed from the pool. +*/ +Phaser.BitmapText.prototype.purgeGlyphs = function () { + + var len = this._glyphs.length; + var kept = []; + + for (var i = 0; i < this._glyphs.length; i++) + { + if (this._glyphs[i].parent !== this) + { + this._glyphs[i].destroy(); + } + else + { + kept.push(this._glyphs[i]); + } + } + + this._glyphs = []; + this._glyphs = kept; + + this.updateText(); + + return len - kept.length; + +}; + +/** +* Updates the transform of this object. +* +* @method Phaser.BitmapText.prototype.updateTransform +* @private +*/ +Phaser.BitmapText.prototype.updateTransform = function () { + + if (this.dirty || !this.anchor.equals(this._prevAnchor)) + { + this.updateText(); + this.dirty = false; + this._prevAnchor.copyFrom(this.anchor); + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/** +* @name Phaser.BitmapText#align +* @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'align', { + + get: function() { + return this._align; + }, + + set: function(value) { + + if (value !== this._align && (value === 'left' || value === 'center' || value === 'right')) + { + this._align = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#tint +* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'tint', { + + get: function() { + return this._tint; + }, + + set: function(value) { + + if (value !== this._tint) + { + this._tint = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#font +* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'font', { + + get: function() { + return this._font; + }, + + set: function(value) { + + if (value !== this._font) + { + this._font = value.trim(); + this._data = this.game.cache.getBitmapFont(this._font); + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#fontSize +* @property {number} fontSize - The size of the font in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { + + get: function() { + return this._fontSize; + }, + + set: function(value) { + + value = parseInt(value, 10); + + if (value !== this._fontSize && value > 0) + { + this._fontSize = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#text +* @property {string} text - The text to be displayed by this BitmapText object. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.updateText(); + } + + } + +}); + +/** +* The maximum display width of this BitmapText in pixels. +* +* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped +* based on the last whitespace character found in the line. +* +* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. +* +* Disable maxWidth by setting the value to 0. +* +* @name Phaser.BitmapText#maxWidth +* @property {number} maxWidth - The maximum width of this BitmapText in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', { + + get: function() { + + return this._maxWidth; + + }, + + set: function(value) { + + if (value !== this._maxWidth) + { + this._maxWidth = value; + this.updateText(); + } + + } + +}); + +/** +* Enable or disable texture smoothing for this BitmapText. +* +* The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. +* +* Smoothing is enabled by default. +* +* @name Phaser.BitmapText#smoothed +* @property {boolean} smoothed +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', { + + get: function() { + + return !this._data.base.scaleMode; + + }, + + set: function(value) { + + if (value) + { + this._data.base.scaleMode = 0; + } + else + { + this._data.base.scaleMode = 1; + } + this._data.base.dirty(); + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont +* is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. +* +* @class Phaser.RetroFont +* @extends Phaser.RenderTexture +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {string} key - The font set graphic set as stored in the Game.Cache. +* @param {number} characterWidth - The width of each character in the font set. +* @param {number} characterHeight - The height of each character in the font set. +* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. +* @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. +* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. +* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { + + if (!game.cache.checkImageKey(key)) + { + return false; + } + + if (charsPerRow === undefined || charsPerRow === null) + { + charsPerRow = game.cache.getImage(key).width / characterWidth; + } + + /** + * @property {number} characterWidth - The width of each character in the font set. + */ + this.characterWidth = characterWidth; + + /** + * @property {number} characterHeight - The height of each character in the font set. + */ + this.characterHeight = characterHeight; + + /** + * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here. + */ + this.characterSpacingX = xSpacing || 0; + + /** + * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here. + */ + this.characterSpacingY = ySpacing || 0; + + /** + * @property {number} characterPerRow - The number of characters per row in the font set. + */ + this.characterPerRow = charsPerRow; + + /** + * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @readonly + */ + this.offsetX = xOffset || 0; + + /** + * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @readonly + */ + this.offsetY = yOffset || 0; + + /** + * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + */ + this.align = "left"; + + /** + * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) + * @default + */ + this.multiLine = false; + + /** + * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. + * @default + */ + this.autoUpperCase = true; + + /** + * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels. + * @default + */ + this.customSpacingX = 0; + + /** + * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels. + * @default + */ + this.customSpacingY = 0; + + /** + * If you need this RetroFont image to have a fixed width you can set the width in this value. + * If text is wider than the width specified it will be cropped off. + * @property {number} fixedWidth + */ + this.fixedWidth = 0; + + /** + * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font. + */ + this.fontSet = game.cache.getImage(key); + + /** + * @property {string} _text - The text of the font image. + * @private + */ + this._text = ''; + + /** + * @property {array} grabData - An array of rects for faster character pasting. + * @private + */ + this.grabData = []; + + /** + * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font. + */ + this.frameData = new Phaser.FrameData(); + + // Now generate our rects for faster copying later on + var currentX = this.offsetX; + var currentY = this.offsetY; + var r = 0; + + for (var c = 0; c < chars.length; c++) + { + var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight)); + + this.grabData[chars.charCodeAt(c)] = frame.index; + + r++; + + if (r === this.characterPerRow) + { + r = 0; + currentX = this.offsetX; + currentY += this.characterHeight + this.characterSpacingY; + } + else + { + currentX += this.characterWidth + this.characterSpacingX; + } + } + + game.cache.updateFrameData(key, this.frameData); + + /** + * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font. + * @readonly + */ + this.stamp = new Phaser.Image(game, 0, 0, key, 0); + + Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST); + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RETROFONT; + +}; + +Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype); +Phaser.RetroFont.prototype.constructor = Phaser.RetroFont; + +/** +* Align each line of multi-line text to the left. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_LEFT = "left"; + +/** +* Align each line of multi-line text to the right. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_RIGHT = "right"; + +/** +* Align each line of multi-line text in the center. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_CENTER = "center"; + +/** +* Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + +/** +* Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "; + +/** +* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789"; + +/** +* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789"; + +/** +* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' "; + +/** +* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39"; + +/** +* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!"; + +/** +* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"; + +/** +* If you need this RetroFont to have a fixed width and custom alignment you can set the width here. +* If text is wider than the width specified it will be cropped off. +* +* @method Phaser.RetroFont#setFixedWidth +* @memberof Phaser.RetroFont +* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. +* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +*/ +Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) { + + if (lineAlignment === undefined) { lineAlignment = 'left'; } + + this.fixedWidth = width; + this.align = lineAlignment; + +}; + +/** +* A helper function that quickly sets lots of variables at once, and then updates the text. +* +* @method Phaser.RetroFont#setText +* @memberof Phaser.RetroFont +* @param {string} content - The text of this sprite. +* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. +* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels. +* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels. +* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. +*/ +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; + } + +}; + +/** +* Updates the texture with the new text. +* +* @method Phaser.RetroFont#buildRetroFontText +* @memberof Phaser.RetroFont +*/ +Phaser.RetroFont.prototype.buildRetroFontText = function () { + + var cx = 0; + var cy = 0; + + // Clears the textureBuffer + 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); + } + + // Loop through each line of text + for (var i = 0; i < lines.length; i++) + { + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + // This line of text is held in lines[i] - need to work out the alignment + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(lines[i], cx, cy, this.customSpacingX); + + cy += this.characterHeight + this.customSpacingY; + } + } + else + { + if (this.fixedWidth > 0) + { + this.resize(this.fixedWidth, this.characterHeight, true); + } + else + { + this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true); + } + + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(this._text, cx, 0, this.customSpacingX); + } + + this.requiresReTint = true; + +}; + +/** +* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. +* Used by getLine and getMultiLine +* +* @method Phaser.RetroFont#pasteLine +* @memberof Phaser.RetroFont +* @param {string} line - The single line of text to paste. +* @param {number} x - The x coordinate. +* @param {number} y - The y coordinate. +* @param {number} customSpacingX - Custom X spacing. +*/ +Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) { + + for (var c = 0; c < line.length; c++) + { + // If it's a space then there is no point copying, so leave a blank space + if (line.charAt(c) === " ") + { + x += this.characterWidth + customSpacingX; + } + else + { + // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it + if (this.grabData[line.charCodeAt(c)] >= 0) + { + this.stamp.frame = this.grabData[line.charCodeAt(c)]; + this.renderXY(this.stamp, x, y, false); + + x += this.characterWidth + customSpacingX; + + if (x > this.width) + { + break; + } + } + } + } +}; + +/** +* Works out the longest line of text in _text and returns its length +* +* @method Phaser.RetroFont#getLongestLine +* @memberof Phaser.RetroFont +* @return {number} The length of the longest line of text. +*/ +Phaser.RetroFont.prototype.getLongestLine = function () { + + var longestLine = 0; + + if (this._text.length > 0) + { + var lines = this._text.split("\n"); + + for (var i = 0; i < lines.length; i++) + { + if (lines[i].length > longestLine) + { + longestLine = lines[i].length; + } + } + } + + return longestLine; +}; + +/** +* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set. +* +* @method Phaser.RetroFont#removeUnsupportedCharacters +* @memberof Phaser.RetroFont +* @protected +* @param {boolean} [stripCR=true] - Should it strip carriage returns as well? +* @return {string} A clean version of the string. +*/ +Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) { + + var newString = ""; + + for (var c = 0; c < this._text.length; c++) + { + var aChar = this._text[c]; + var code = aChar.charCodeAt(0); + + if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n")) + { + newString = newString.concat(aChar); + } + } + + return newString; + +}; + +/** +* Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. +* Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. +* So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. +* +* @method Phaser.RetroFont#updateOffset +* @memberof Phaser.RetroFont +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont.prototype.updateOffset = function (x, y) { + + if (this.offsetX === x && this.offsetY === y) + { + return; + } + + var diffX = x - this.offsetX; + var diffY = y - this.offsetY; + + var frames = this.game.cache.getFrameData(this.stamp.key).getFrames(); + var i = frames.length; + + while (i--) + { + frames[i].x += diffX; + frames[i].y += diffY; + } + + this.buildRetroFontText(); + +}; + +/** +* @name Phaser.RetroFont#text +* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. +*/ +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(); + } + + } + +}); + +/** +* @name Phaser.RetroFont#smoothed +* @property {boolean} smoothed - Sets if the stamp is smoothed or not. +*/ +Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", { + + get: function () { + + return this.stamp.smoothed; + + }, + + set: function (value) { + + this.stamp.smoothed = value; + this.buildRetroFontText(); + + } + +}); + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @author Rovanion Luckey +* @copyright 2016 Photon Storm Ltd, Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Rope is a Sprite that has a repeating texture. +* +* The texture will automatically wrap on the edges as it moves. +* +* Please note that Ropes cannot have an input handler. +* +* @class Phaser.Rope +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Rope at. +* @param {number} y - The y coordinate (in world space) to position the Rope at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {Array} points - An array of {Phaser.Point}. +*/ +Phaser.Rope = function (game, x, y, key, frame, points) { + + this.points = points || []; + this._hasUpdateAnimation = false; + this._updateAnimationCallback = null; + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROPE; + + PIXI.DisplayObjectContainer.call(this); + + this.texture = Phaser.Cache.DEFAULT; + + // set up the main bits.. + this.uvs = new Float32Array([0, 1, + 1, 1, + 1, 0, + 0, 1]); + + this.vertices = new Float32Array([0, 0, + 100, 0, + 100, 100, + 0, 100]); + + this.colors = new Float32Array([1, 1, 1, 1]); + + this.indices = new Uint16Array([0, 1, 2, 3]); + + if (points) + { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + /** + * Whether the strip is dirty or not + * + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. + * + * @property canvasPadding + * @type Number + */ + this.canvasPadding = 0; + + this.drawMode = Phaser.Rope.TRIANGLE_STRIP; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + + this.refresh(); + +}; + +Phaser.Rope.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Rope.prototype.constructor = Phaser.Rope; + +Phaser.Component.Core.install.call(Phaser.Rope.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +Phaser.Rope.TRIANGLE_STRIP = 0; +Phaser.Rope.TRIANGLES = 1; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Rope#preUpdate +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override and use this function in your own custom objects to handle any update requirements you may have. +* +* @method Phaser.Rope#update +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.update = function() { + + if (this._hasUpdateAnimation) + { + this.updateAnimation.call(this); + } + +}; + +/** +* Resets the Rope. This places the Rope at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the Rope has a physics body that too is reset. +* +* @method Phaser.Rope#reset +* @memberof Phaser.Rope +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.Rope} This instance. +*/ +Phaser.Rope.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + return this; + +}; + +/* +* Refreshes the rope texture and UV coordinates. +* +* @method Phaser.Rope#refresh +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.refresh = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + this.count -= 0.2; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + var index; + var amount; + + for (var i = 1; i < total; i++) + { + index = i * 4; + + // time to do some smart drawing! + amount = i / (total - 1); + + if (i % 2) + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + else + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + +}; + +/* +* Updates the Ropes transform ready for rendering. +* +* @method Phaser.Rope#updateTransform +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.updateTransform = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var lastPoint = points[0]; + var nextPoint; + var perp = { x:0, y:0 }; + + this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + var point; + var index; + var ratio; + var perpLength; + var num; + + for (var i = 0; i < total; i++) + { + point = points[i]; + index = i * 4; + + if(i < points.length - 1) + { + nextPoint = points[i + 1]; + } + else + { + nextPoint = point; + } + + perp.y = -(nextPoint.x - lastPoint.x); + perp.x = nextPoint.y - lastPoint.y; + + ratio = (1 - (i / (total - 1))) * 10; + + if (ratio > 1) + { + ratio = 1; + } + + perpLength = Math.sqrt((perp.x * perp.x) + (perp.y * perp.y)); + num = this.texture.height / 2; + perp.x /= perpLength; + perp.y /= perpLength; + + perp.x *= num; + perp.y *= num; + + vertices[index] = point.x + perp.x; + vertices[index + 1] = point.y + perp.y; + vertices[index + 2] = point.x - perp.x; + vertices[index + 3] = point.y - perp.y; + + lastPoint = point; + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/* +* Sets the Texture this Rope uses for rendering. +* +* @method Phaser.Rope#setTexture +* @memberof Phaser.Rope +* @param {Texture} texture - The texture that will be used. +*/ +Phaser.Rope.prototype.setTexture = function (texture) { + + this.texture = texture; + +}; + +/* +* Renders the Rope to WebGL. +* +* @private +* @method Phaser.Rope#_renderWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + renderSession.spriteBatch.stop(); + + if (!this._vertexBuffer) + { + this._initWebGL(renderSession); + } + + renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader); + + this._renderStrip(renderSession); + + renderSession.spriteBatch.start(); + +}; + +/* +* Builds the Strip. +* +* @private +* @method Phaser.Rope#_initWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._initWebGL = function (renderSession) { + + // build the strip! + var gl = renderSession.gl; + + this._vertexBuffer = gl.createBuffer(); + this._indexBuffer = gl.createBuffer(); + this._uvBuffer = gl.createBuffer(); + this._colorBuffer = gl.createBuffer(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + +}; + +/* +* Renders the Strip to WebGL. +* +* @private +* @method Phaser.Rope#_renderStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderStrip = function (renderSession) { + + var gl = renderSession.gl; + var projection = renderSession.projection; + var offset = renderSession.offset; + var shader = renderSession.shaderManager.stripShader; + + var drawMode = (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + renderSession.blendModeManager.setBlendMode(this.blendMode); + + // set uniforms + gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true)); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + gl.uniform1f(shader.alpha, this.worldAlpha); + + if (!this.dirty) + { + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + } + else + { + this.dirty = false; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + } + + gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0); + +}; + +/* +* Renders the Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvas +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvas = function (renderSession) { + + var context = renderSession.context; + + var transform = this.worldTransform; + + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + if (renderSession.roundPixels) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx, ty); + } + + if (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) + { + this._renderCanvasTriangleStrip(context); + } + else + { + this._renderCanvasTriangles(context); + } + +}; + +/* +* Renders a Triangle Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangleStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangleStrip = function (context) { + + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + + var length = vertices.length / 2; + + this.count++; + + for (var i = 0; i < length - 2; i++) + { + var index = i * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangles +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangles = function (context) { + + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + + var length = indices.length; + + this.count++; + + for (var i = 0; i < length; i += 3) + { + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasDrawTriangle +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { + + var textureSource = this.texture.baseTexture.source; + var textureWidth = this.texture.width; + var textureHeight = this.texture.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var u0 = uvs[index0] * textureWidth; + var u1 = uvs[index1] * textureWidth; + var u2 = uvs[index2] * textureWidth; + var v0 = uvs[index0 + 1] * textureHeight; + var v1 = uvs[index1 + 1] * textureHeight; + var v2 = uvs[index2 + 1] * textureHeight; + + if (this.canvasPadding > 0) + { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt((normX * normX) + (normY * normY)); + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2); + var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2); + var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2); + var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2); + var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2); + var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2); + var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2); + + context.transform( + deltaA / delta, + deltaD / delta, + deltaB / delta, + deltaE / delta, + deltaC / delta, + deltaF / delta); + + context.drawImage(textureSource, 0, 0); + context.restore(); + +}; + +/* +* Renders a flat strip. +* +* @method Phaser.Rope#renderStripFlat +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.renderStripFlat = function (strip) { + + var context = this.context; + var vertices = strip.vertices; + + var length = vertices.length / 2; + + this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; i++) + { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var x1 = vertices[index + 2]; + var x2 = vertices[index + 4]; + var y0 = vertices[index + 1]; + var y1 = vertices[index + 3]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + +}; + +/* +* Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Rope#getBounds +* @memberof Phaser.Rope +* @param {Matrix} matrix - The transformation matrix of the Sprite. +* @return {Rectangle} The framing rectangle. +*/ +Phaser.Rope.prototype.getBounds = function (matrix) { + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + var vertices = this.vertices; + + for (var i = 0; i < vertices.length; i += 2) + { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + if (minX === -Infinity || maxY === Infinity) + { + return PIXI.EmptyRectangle; + } + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // Store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* A Rope will call its updateAnimation function on each update loop if it has one. +* +* @name Phaser.Rope#updateAnimation +* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. +*/ +Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", { + + get: function () { + + return this._updateAnimation; + + }, + + set: function (value) { + + if (value && typeof value === 'function') + { + this._hasUpdateAnimation = true; + this._updateAnimation = value; + } + else + { + this._hasUpdateAnimation = false; + this._updateAnimation = null; + } + + } + +}); + +/** +* The segments that make up the rope body as an array of Phaser.Rectangles +* +* @name Phaser.Rope#segments +* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope +*/ +Object.defineProperty(Phaser.Rope.prototype, "segments", { + + get: function () { + + var segments = []; + var index, x1, y1, x2, y2, width, height, rect; + + for (var i = 0; i < this.points.length; i++) + { + index = i * 4; + + x1 = this.vertices[index] * this.scale.x; + y1 = this.vertices[index + 1] * this.scale.y; + x2 = this.vertices[index + 4] * this.scale.x; + y2 = this.vertices[index + 3] * this.scale.y; + + width = Phaser.Math.difference(x1, x2); + height = Phaser.Math.difference(y1, y2); + + x1 += this.world.x; + y1 += this.world.y; + rect = new Phaser.Rectangle(x1, y1, width, height); + segments.push(rect); + } + + return segments; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. +* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. +* +* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. +* +* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background +* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` +* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will +* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to +* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. +* +* An important note about texture dimensions: +* +* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be +* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two +* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and +* bottom of your frame. To avoid this ensure your textures are perfect powers of two. +* +* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However +* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive +* additional padding to enforce it to be so. +* +* @class Phaser.TileSprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate (in world space) to position the TileSprite at. +* @param {number} [y=0] - The y coordinate (in world space) to position the TileSprite at. +* @param {number} [width=256] - The width of the TileSprite. +* @param {number} [height=256] - The height of the TileSprite. +* @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. +* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.TileSprite = function (game, x, y, width, height, key, frame) { + + x = x || 0; + y = y || 0; + width = width || 256; + height = height || 256; + key = key || null; + frame = frame || null; + + PIXI.Sprite.call(this, new PIXI.Texture(Phaser.Cache.DEFAULT.baseTexture), width, height); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.TILESPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} _scroll - Internal cache var. + * @private + */ + this._scroll = new Phaser.Point(); + + /** + * @property {Phaser.Point} tileScale - The scale applied to the image being tiled. + */ + this.tileScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tileScaleOffset - The scale offset applied to the image being tiled. + */ + this.tileScaleOffset = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tilePosition - The offset position of the image being tiled. + */ + this.tilePosition = new Phaser.Point(); + + /** + * If enabled a green rectangle will be drawn behind the generated tiling texture, + * allowing you to visually debug the texture being used. + * + * @property {boolean} textureDebug + */ + this.textureDebug = false; + + /** + * The CanvasBuffer object that the tiled texture is drawn to. + * + * @property {PIXI.CanvasBuffer} canvasBuffer + */ + this.canvasBuffer = null; + + /** + * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. + * + * @property {PIXI.Texture} tilingTexture + */ + this.tilingTexture = null; + + /** + * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). + * + * @property {object} tilePattern + */ + this.tilePattern = null; + + /** + * If true the TileSprite will run `generateTexture` on its **next** render pass. + * This is set by the likes of Phaser.LoadTexture.setFrame. + * + * @property {boolean} refreshTexture + */ + this.refreshTexture = true; + + this.frameWidth = 0; + this.frameHeight = 0; + + this._width = width; + this._height = height; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.TileSprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.TileSprite.prototype.constructor = Phaser.TileSprite; + +Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'Smoothed' +]); + +Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TileSprite#preUpdate +* @memberof Phaser.TileSprite +* @return {boolean} +*/ +Phaser.TileSprite.prototype.preUpdate = function () { + + if (this._scroll.x !== 0) + { + this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed; + } + + if (this._scroll.y !== 0) + { + this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed; + } + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). +* The scroll speed is specified in pixels per second. +* A negative x value will scroll to the left. A positive x value will scroll to the right. +* A negative y value will scroll up. A positive y value will scroll down. +* +* @method Phaser.TileSprite#autoScroll +* @memberof Phaser.TileSprite +* @param {number} x - Horizontal scroll speed in pixels per second. +* @param {number} y - Vertical scroll speed in pixels per second. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.autoScroll = function (x, y) { + + this._scroll.set(x, y); + + return this; + +}; + +/** +* Stops an automatically scrolling TileSprite. +* +* @method Phaser.TileSprite#stopScroll +* @memberof Phaser.TileSprite +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.stopScroll = function () { + + this._scroll.set(0, 0); + + return this; + +}; + +/** +* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present +* and nulls its reference to game, freeing it up for garbage collection. +* +* @method Phaser.TileSprite#destroy +* @memberof Phaser.TileSprite +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.TileSprite.prototype.destroy = function (destroyChildren) { + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + + PIXI.Sprite.prototype.destroy.call(this); + + if (this.canvasBuffer) + { + this.canvasBuffer.destroy(); + this.canvasBuffer = null; + } + + this.tileScale = null; + this.tileScaleOffset = null; + this.tilePosition = null; + + if (this.tilingTexture) + { + this.tilingTexture.destroy(true); + this.tilingTexture = null; + } + +}; + +/** +* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the TileSprite has a physics body that too is reset. +* +* @method Phaser.TileSprite#reset +* @memberof Phaser.TileSprite +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + this.tilePosition.x = 0; + this.tilePosition.y = 0; + + return this; + +}; + +/** +* Changes the texture being rendered by this TileSprite. +* Causes a texture refresh to take place on the next render. +* +* @method Phaser.TileSprite#setTexture +* @memberof Phaser.TileSprite +* @param {PIXI.Texture} texture - The texture to apply to this TileSprite. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.setTexture = function (texture) { + + if (this.texture !== texture) + { + this.texture = texture; + this.refreshTexture = true; + this.cachedTint = 0xFFFFFF; + } + + return this; + +}; + +/** +* Renders the TileSprite using the WebGL Renderer. +* +* @private +* @method Phaser.TileSprite#_renderWebGL +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + 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.refreshTexture) + { + this.generateTilingTexture(true, renderSession); + + if (this.tilingTexture) + { + if (this.tilingTexture.needsUpdate) + { + this.tilingTexture.baseTexture.textureIndex = this.texture.baseTexture.textureIndex; + renderSession.renderer.updateTexture(this.tilingTexture.baseTexture); + this.tilingTexture.needsUpdate = false; + } + } + else + { + return; + } + } + + renderSession.spriteBatch.renderTilingSprite(this); + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + var restartBatch = false; + + if (this._filters) + { + restartBatch = true; + renderSession.spriteBatch.stop(); + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + if (!restartBatch) + { + renderSession.spriteBatch.stop(); + } + + renderSession.maskManager.popMask(this._mask, renderSession); + } + + if (restartBatch) + { + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the TileSprite using the Canvas Renderer. +* +* @private +* @method Phaser.TileSprite#_renderCanvas +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + var context = renderSession.context; + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + context.globalAlpha = this.worldAlpha; + + var wt = this.worldTransform; + var resolution = renderSession.resolution; + var tx = (wt.tx * resolution) + renderSession.shakeX; + var ty = (wt.ty * resolution) + renderSession.shakeY; + + context.setTransform(wt.a * resolution, wt.b * resolution, wt.c * resolution, wt.d * resolution, tx, ty); + + if (this.tint !== 0xFFFFFF && (this.texture.requiresReTint || this.cachedTint !== this.tint)) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + this.refreshTexture = true; + } + + if (this.refreshTexture) + { + this.generateTilingTexture(false, renderSession); + + if (this.tilingTexture) + { + this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat'); + } + else + { + return; + } + } + + var sessionBlendMode = renderSession.currentBlendMode; + + // Check blend mode + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + var tilePosition = this.tilePosition; + var tileScale = this.tileScale; + + tilePosition.x %= this.tilingTexture.baseTexture.width; + tilePosition.y %= this.tilingTexture.baseTexture.height; + + // Translate + context.scale(tileScale.x, tileScale.y); + context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height)); + + context.fillStyle = this.tilePattern; + + tx = -tilePosition.x; + ty = -tilePosition.y; + + var tw = this._width / tileScale.x; + var th = this._height / tileScale.y; + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + tx |= 0; + ty |= 0; + tw |= 0; + th |= 0; + } + + context.fillRect(tx, ty, tw, th); + + // Translate back again + context.scale(1 / tileScale.x, 1 / tileScale.y); + context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height)); + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + // Reset blend mode + if (sessionBlendMode !== this.blendMode) + { + renderSession.currentBlendMode = sessionBlendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode]; + } + +}; + +/** +* Override the Sprite method. +* +* @private +* @method Phaser.TileSprite#onTextureUpdate +* @memberof Phaser.TileSprite +*/ +Phaser.TileSprite.prototype.onTextureUpdate = function () { + + // overriding the sprite version of this! + +}; + +/** +* Internal method that generates a new tiling texture. +* +* @method Phaser.TileSprite#generateTilingTexture +* @memberof Phaser.TileSprite +* @param {boolean} forcePowerOfTwo - Whether we want to force the texture to be a power of two +*/ +Phaser.TileSprite.prototype.generateTilingTexture = function (forcePowerOfTwo) { + + if (!this.texture.baseTexture.hasLoaded) + { + return; + } + + var texture = this.texture; + var frame = texture.frame; + + var targetWidth = this._frame.sourceSizeW || this._frame.width; + var targetHeight = this._frame.sourceSizeH || this._frame.height; + + var dx = 0; + var dy = 0; + + if (this._frame.trimmed) + { + dx = this._frame.spriteSourceSizeX; + dy = this._frame.spriteSourceSizeY; + } + + if (forcePowerOfTwo) + { + targetWidth = Phaser.Math.getNextPowerOfTwo(targetWidth); + targetHeight = Phaser.Math.getNextPowerOfTwo(targetHeight); + } + + if (this.canvasBuffer) + { + this.canvasBuffer.resize(targetWidth, targetHeight); + this.tilingTexture.baseTexture.width = targetWidth; + this.tilingTexture.baseTexture.height = targetHeight; + this.tilingTexture.needsUpdate = true; + } + else + { + this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight); + this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas); + this.tilingTexture.isTiling = true; + this.tilingTexture.needsUpdate = true; + } + + if (this.textureDebug) + { + this.canvasBuffer.context.strokeStyle = '#00ff00'; + this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight); + } + + // If a sprite sheet we need this: + var w = texture.crop.width; + var h = texture.crop.height; + + if (w !== targetWidth || h !== targetHeight) + { + w = targetWidth; + h = targetHeight; + } + + var targetTexture = this.tintedTexture ? this.tintedTexture : texture.baseTexture.source; + + this.canvasBuffer.context.drawImage( + targetTexture, + texture.crop.x, + texture.crop.y, + texture.crop.width, + texture.crop.height, + dx, + dy, + w, + h + ); + + this.tileScaleOffset.x = frame.width / targetWidth; + this.tileScaleOffset.y = frame.height / targetHeight; + + this.refreshTexture = false; + + this.tilingTexture.baseTexture._powerOf2 = true; + +}; + +/** +* Returns the framing rectangle of the Tile Sprite. +* +* @method Phaser.TileSprite#getBounds +* @memberof Phaser.TileSprite +* @return {Phaser.Rectangle} The bounds of the Tile Sprite. +*/ +Phaser.TileSprite.prototype.getBounds = function () { + + var width = this._width; + var height = this._height; + + var w0 = width * (1 - this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1 - this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = (a * w1) + (c * h1) + tx; + var y1 = (d * h1) + (b * w1) + ty; + + var x2 = (a * w0) + (c * h1) + tx; + var y2 = (d * h1) + (b * w0) + ty; + + var x3 = (a * w0) + (c * h0) + tx; + var y3 = (d * h0) + (b * w0) + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // TODO: This is surely always undefined? As it's not set anywhere in the parent objects + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* The width of the sprite, setting this will actually modify the scale to achieve the value set +* +* @property width +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'width', { + + get: function () { + + return this._width; + + }, + + set: function (value) { + + this._width = value; + + } + +}); + +/** +* The height of the TilingSprite, setting this will actually modify the scale to achieve the value set +* +* @property height +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'height', { + + get: function () { + + return this._height; + + }, + + set: function (value) { + + this._height = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The CanvasPool is a global static object, that allows Phaser to recycle and pool Canvas DOM elements. +* +* @class Phaser.CanvasPool +* @static +*/ +Phaser.CanvasPool = { + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @method Phaser.CanvasPool.create + * @static + * @param {any} parent - The parent of the canvas element. + * @param {number} width - The width of the canvas element. + * @param {number} height - The height of the canvas element. + * @return {HTMLCanvasElement} The canvas element. + */ + create: function (parent, width, height) { + + var idx = Phaser.CanvasPool.getFirst(); + var canvas; + + if (idx === -1) + { + var container = { + parent: parent, + canvas: document.createElement('canvas') + }; + + Phaser.CanvasPool.pool.push(container); + + canvas = container.canvas; + } + else + { + Phaser.CanvasPool.pool[idx].parent = parent; + + canvas = Phaser.CanvasPool.pool[idx].canvas; + } + + if (width !== undefined) + { + canvas.width = width; + canvas.height = height; + } + + return canvas; + + }, + + /** + * Gets the first free canvas index from the pool. + * + * @static + * @method Phaser.CanvasPool.getFirst + * @return {number} + */ + getFirst: function () { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + return i; + } + } + + return -1; + + }, + + /** + * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.remove + * @param {any} parent - The parent of the canvas element. + */ + remove: function (parent) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent === parent) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Looks up a canvas based on its type, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.removeByCanvas + * @param {HTMLCanvasElement} canvas - The canvas element to remove. + */ + removeByCanvas: function (canvas) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].canvas === canvas) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Gets the total number of used canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getTotal + * @return {number} The number of in-use (parented) canvas elements in the pool. + */ + getTotal: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent) + { + c++; + } + } + + return c; + + }, + + /** + * Gets the total number of free canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getFree + * @return {number} The number of free (un-parented) canvas elements in the pool. + */ + getFree: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + c++; + } + } + + return c; + + }, + + + /** + * Prints in-use, free, and total counts to console.log. + * + * @static + * @method Phaser.CanvasPool.log + */ + log: function () { + + console.log('CanvasPool: %s used, %s free, %s total', this.getTotal(), this.getFree(), this.pool.length); + + } + +}; + +/** + * The pool into which the canvas elements are placed. + * + * @property pool + * @type Array + * @static + */ +Phaser.CanvasPool.pool = []; + + +/** + * The total number of canvas elements in the {@link Phaser.CanvasPool.pool pool}. + * + * @property length + * @type number + * @static + * @readonly + */ +Object.defineProperty(Phaser.CanvasPool, 'length', { + get: function () { + return this.pool.length; + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}. +* +* This class represents a singleton object that can be accessed directly as `game.device` +* (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it. +* +* Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization +* occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase. +* Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal, e.g., +* +* ```javascript +* Phaser.Device.onInitialized.add(function (device) { +* +* device.canvasBitBltShift = true; +* device.mspointer = false; +* +* }); +* +* var game = new Phaser.Game(); +* ``` +* +* When checking features using the exposed properties only the *truth-iness* of the value should be relied upon +* unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined` +* when indicating the lack of a feature. +* +* Uses elements from System.js by MrDoob and Modernizr +* +* @description +* It is not possible to instantiate the Device class manually. +* +* @class +* @protected +*/ +Phaser.Device = function () { + + /** + * The time the device became ready. + * @property {integer} deviceReadyAt + * @protected + */ + this.deviceReadyAt = 0; + + /** + * The time as which initialization has completed. + * @property {boolean} initialized + * @protected + */ + this.initialized = false; + + // Browser / Host / Operating System + + /** + * @property {boolean} desktop - Is running on a desktop? + * @default + */ + this.desktop = false; + + /** + * @property {boolean} iOS - Is running on iOS? + * @default + */ + this.iOS = false; + + /** + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @default + */ + this.iOSVersion = 0; + + /** + * @property {boolean} cocoonJS - Is the game running under CocoonJS? + * @default + */ + this.cocoonJS = false; + + /** + * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App? + * @default + */ + this.cocoonJSApp = false; + + /** + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @default + */ + this.cordova = false; + + /** + * @property {boolean} node - Is the game running under Node.js? + * @default + */ + this.node = false; + + /** + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @default + */ + this.nodeWebkit = false; + + /** + * @property {boolean} electron - Is the game running under GitHub Electron? + * @default + */ + this.electron = false; + + /** + * @property {boolean} ejecta - Is the game running under Ejecta? + * @default + */ + this.ejecta = false; + + /** + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @default + */ + this.crosswalk = false; + + /** + * @property {boolean} android - Is running on android? + * @default + */ + this.android = false; + + /** + * @property {boolean} chromeOS - Is running on chromeOS? + * @default + */ + this.chromeOS = false; + + /** + * @property {boolean} linux - Is running on linux? + * @default + */ + this.linux = false; + + /** + * @property {boolean} macOS - Is running on macOS? + * @default + */ + this.macOS = false; + + /** + * @property {boolean} windows - Is running on windows? + * @default + */ + this.windows = false; + + /** + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @default + */ + this.windowsPhone = false; + + // Features + + /** + * @property {boolean} canvas - Is canvas available? + * @default + */ + this.canvas = false; + + /** + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @default + */ + this.canvasBitBltShift = null; + + /** + * If the browser isn't capable of handling tinting with alpha this will be false. + * @property {boolean} canHandleAlpha + * @default + */ + this.canHandleAlpha = false; + + /** + * Whether or not the {@link http://caniuse.com/#feat=canvas-blending Canvas Blend Modes} are supported, consequently the ability to tint using the multiply method. + * + * Expect `false` in Internet Explorer <= 11. + * + * @property {boolean} canUseMultiply + * @default + */ + this.canUseMultiply = false; + + /** + * @property {boolean} webGL - Is webGL available? + * @default + */ + this.webGL = false; + + /** + * @property {boolean} file - Is file available? + * @default + */ + this.file = false; + + /** + * @property {boolean} fileSystem - Is fileSystem available? + * @default + */ + this.fileSystem = false; + + /** + * @property {boolean} localStorage - Is localStorage available? + * @default + */ + this.localStorage = false; + + /** + * @property {boolean} worker - Is worker available? + * @default + */ + this.worker = false; + + /** + * @property {boolean} css3D - Is css3D available? + * @default + */ + this.css3D = false; + + /** + * @property {boolean} pointerLock - Is Pointer Lock available? + * @default + */ + this.pointerLock = false; + + /** + * @property {boolean} typedArray - Does the browser support TypedArrays? + * @default + */ + this.typedArray = false; + + /** + * @property {boolean} vibration - Does the device support the Vibration API? + * @default + */ + this.vibration = false; + + /** + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @default + */ + this.getUserMedia = true; + + /** + * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true) + * @default + */ + this.quirksMode = false; + + // Input + + /** + * @property {boolean} touch - Is touch available? + * @default + */ + this.touch = false; + + /** + * @property {boolean} mspointer - Is mspointer available? + * @default + */ + this.mspointer = false; + + /** + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @default + * @protected + */ + this.wheelEvent = null; + + // Browser + + /** + * @property {boolean} arora - Set to true if running in Arora. + * @default + */ + this.arora = false; + + /** + * @property {boolean} chrome - Set to true if running in Chrome. + * @default + */ + this.chrome = false; + + /** + * @property {number} chromeVersion - If running in Chrome this will contain the major version number. + * @default + */ + this.chromeVersion = 0; + + /** + * @property {boolean} epiphany - Set to true if running in Epiphany. + * @default + */ + this.epiphany = false; + + /** + * @property {boolean} firefox - Set to true if running in Firefox. + * @default + */ + this.firefox = false; + + /** + * @property {number} firefoxVersion - If running in Firefox this will contain the major version number. + * @default + */ + this.firefoxVersion = 0; + + /** + * @property {boolean} ie - Set to true if running in Internet Explorer. + * @default + */ + this.ie = false; + + /** + * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. + * @default + */ + this.ieVersion = 0; + + /** + * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+) + * @default + */ + this.trident = false; + + /** + * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx} + * @default + */ + this.tridentVersion = 0; + + /** + * @property {boolean} edge - Set to true if running in Microsoft Edge browser. + * @default + */ + this.edge = false; + + /** + * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. + * @default + */ + this.mobileSafari = false; + + /** + * @property {boolean} midori - Set to true if running in Midori. + * @default + */ + this.midori = false; + + /** + * @property {boolean} opera - Set to true if running in Opera. + * @default + */ + this.opera = false; + + /** + * @property {boolean} safari - Set to true if running in Safari. + * @default + */ + this.safari = false; + + /** + * @property {number} safariVersion - If running in Safari this will contain the major version number. + * @default + */ + this.safariVersion = 0; + + /** + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @default + */ + this.webApp = false; + + /** + * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle) + * @default + */ + this.silk = false; + + // Audio + + /** + * @property {boolean} audioData - Are Audio tags available? + * @default + */ + this.audioData = false; + + /** + * @property {boolean} webAudio - Is the WebAudio API available? + * @default + */ + this.webAudio = false; + + /** + * @property {boolean} ogg - Can this device play ogg files? + * @default + */ + this.ogg = false; + + /** + * @property {boolean} opus - Can this device play opus files? + * @default + */ + this.opus = false; + + /** + * @property {boolean} mp3 - Can this device play mp3 files? + * @default + */ + this.mp3 = false; + + /** + * @property {boolean} wav - Can this device play wav files? + * @default + */ + this.wav = false; + + /** + * Can this device play m4a files? + * @property {boolean} m4a - True if this device can play m4a files. + * @default + */ + this.m4a = false; + + /** + * @property {boolean} webm - Can this device play webm files? + * @default + */ + this.webm = false; + + /** + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @default + */ + this.dolby = false; + + // Video + + /** + * @property {boolean} oggVideo - Can this device play ogg video files? + * @default + */ + this.oggVideo = false; + + /** + * @property {boolean} h264Video - Can this device play h264 mp4 video files? + * @default + */ + this.h264Video = false; + + /** + * @property {boolean} mp4Video - Can this device play h264 mp4 video files? + * @default + */ + this.mp4Video = false; + + /** + * @property {boolean} webmVideo - Can this device play webm video files? + * @default + */ + this.webmVideo = false; + + /** + * @property {boolean} vp9Video - Can this device play vp9 video files? + * @default + */ + this.vp9Video = false; + + /** + * @property {boolean} hlsVideo - Can this device play hls video files? + * @default + */ + this.hlsVideo = false; + + // Device + + /** + * @property {boolean} iPhone - Is running on iPhone? + * @default + */ + this.iPhone = false; + + /** + * @property {boolean} iPhone4 - Is running on iPhone4? + * @default + */ + this.iPhone4 = false; + + /** + * @property {boolean} iPad - Is running on iPad? + * @default + */ + this.iPad = false; + + // Device features + + /** + * @property {number} pixelRatio - PixelRatio of the host device? + * @default + */ + this.pixelRatio = 0; + + /** + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @default + */ + this.littleEndian = false; + + /** + * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`. + * @default + */ + this.LITTLE_ENDIAN = false; + + /** + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @default + */ + this.support32bit = false; + + /** + * @property {boolean} fullscreen - Does the browser support the Full Screen API? + * @default + */ + this.fullscreen = false; + + /** + * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it. + * @default + */ + this.requestFullscreen = ''; + + /** + * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @default + */ + this.cancelFullscreen = ''; + + /** + * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @default + */ + this.fullscreenKeyboard = false; + +}; + +// Device is really a singleton/static entity; instantiate it +// and add new methods directly sans-prototype. +Phaser.Device = new Phaser.Device(); + +/** +* This signal is dispatched after device initialization occurs but before any of the ready +* callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked. +* +* Local "patching" for a particular device can/should be done in this event. +* +* _Note_: This signal is removed after the device has been readied; if a handler has not been +* added _before_ `new Phaser.Game(..)` it is probably too late. +* +* @type {?Phaser.Signal} +* @static +*/ +Phaser.Device.onInitialized = new Phaser.Signal(); + +/** +* Add a device-ready handler and ensure the device ready sequence is started. +* +* Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added, +* which is normally done automatically be calling `new Phaser.Game(..)`. +* +* The handler is invoked when the device is considered "ready", which may be immediately +* if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}. +* +* @method +* @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. +* @param {object} [context] - Context in which to invoke the handler +* @param {boolean} [nonPrimer=false] - If true the device ready check will not be started. +*/ +Phaser.Device.whenReady = function (callback, context, nonPrimer) { + + var readyCheck = this._readyCheck; + + if (this.deviceReadyAt || !readyCheck) + { + callback.call(context, this); + } + else if (readyCheck._monitor || nonPrimer) + { + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + } + else + { + readyCheck._monitor = readyCheck.bind(this); + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + + var cordova = typeof window.cordova !== 'undefined'; + var cocoonJS = navigator['isCocoonJS']; + + if (document.readyState === 'complete' || document.readyState === 'interactive') + { + // Why is there an additional timeout here? + window.setTimeout(readyCheck._monitor, 0); + } + else if (cordova && !cocoonJS) + { + // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + // Cordova, but NOT Cocoon? + document.addEventListener('deviceready', readyCheck._monitor, false); + } + else + { + document.addEventListener('DOMContentLoaded', readyCheck._monitor, false); + window.addEventListener('load', readyCheck._monitor, false); + } + } + +}; + +/** +* Internal method used for checking when the device is ready. +* This function is removed from Phaser.Device when the device becomes ready. +* +* @method +* @private +*/ +Phaser.Device._readyCheck = function () { + + var readyCheck = this._readyCheck; + + if (!document.body) + { + window.setTimeout(readyCheck._monitor, 20); + } + else if (!this.deviceReadyAt) + { + this.deviceReadyAt = Date.now(); + + document.removeEventListener('deviceready', readyCheck._monitor); + document.removeEventListener('DOMContentLoaded', readyCheck._monitor); + window.removeEventListener('load', readyCheck._monitor); + + this._initialize(); + this.initialized = true; + + this.onInitialized.dispatch(this); + + var item; + while ((item = readyCheck._queue.shift())) + { + var callback = item[0]; + var context = item[1]; + callback.call(context, this); + } + + // Remove no longer useful methods and properties. + this._readyCheck = null; + this._initialize = null; + this.onInitialized = null; + } + +}; + +/** +* Internal method to initialize the capability checks. +* This function is removed from Phaser.Device once the device is initialized. +* +* @method +* @private +*/ +Phaser.Device._initialize = function () { + + var device = this; + + /** + * Check which OS is game running on. + */ + function _checkOS () { + + var ua = navigator.userAgent; + + if (/Playstation Vita/.test(ua)) + { + device.vita = true; + } + else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua)) + { + device.kindle = true; + // This will NOT detect early generations of Kindle Fire, I think there is no reliable way... + // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true" + } + else if (/Android/.test(ua)) + { + device.android = true; + } + else if (/CrOS/.test(ua)) + { + device.chromeOS = true; + } + else if (/iP[ao]d|iPhone/i.test(ua)) + { + device.iOS = true; + (navigator.appVersion).match(/OS (\d+)/); + device.iOSVersion = parseInt(RegExp.$1, 10); + } + else if (/Linux/.test(ua)) + { + device.linux = true; + } + else if (/Mac OS/.test(ua)) + { + device.macOS = true; + } + else if (/Windows/.test(ua)) + { + device.windows = true; + } + + if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua)) + { + device.android = false; + device.iOS = false; + device.macOS = false; + device.windows = true; + device.windowsPhone = true; + } + + var silk = /Silk/.test(ua); // detected in browsers + + if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS) + { + device.desktop = true; + } + + // Windows Phone / Table reset + if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) + { + device.desktop = false; + } + + } + + /** + * Checks if the browser correctly supports putImageData alpha channels. + * If the browser isn't capable of handling tinting with alpha, `Device.canHandleAlpha` will be false. + * Also checks whether the Canvas BlendModes are supported by the current browser for drawImage. + */ + function _checkCanvasFeatures () { + + var canvas = Phaser.CanvasPool.create(this, 6, 1); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgba(10, 20, 30, 0.5)'; + + // Draw a single pixel + context.fillRect(0, 0, 1, 1); + + // Get the color values + var s1 = context.getImageData(0, 0, 1, 1); + + if (s1) + { + // Plot them to x2 + context.putImageData(s1, 1, 0); + + // Get those values + var s2 = context.getImageData(1, 0, 1, 1); + + // Compare and set + device.canHandleAlpha = ( + s2.data[0] === s1.data[0] && + s2.data[1] === s1.data[1] && + s2.data[2] === s1.data[2] && + s2.data[3] === s1.data[3] + ); + } + + // Checks whether the Canvas BlendModes are supported by the current browser for drawImage. + context.globalCompositeOperation = 'multiply'; + device.canUseMultiply = (context.globalCompositeOperation === 'multiply'); + + Phaser.CanvasPool.removeByCanvas(canvas); + + PIXI.CanvasTinter.tintMethod = (device.canUseMultiply) ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel; + + } + + /** + * Check HTML5 features of the host environment. + */ + function _checkFeatures () { + + device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS; + + try { + device.localStorage = !!localStorage.getItem; + } catch (error) { + device.localStorage = false; + } + + device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; + device.fileSystem = !!window['requestFileSystem']; + + device.webGL = !!window.WebGLRenderingContext; + + device.worker = !!window['Worker']; + + device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; + + device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL; + + // Older versions of firefox (< 21) apparently claim support but user media does not actually work + if (device.firefox && device.firefoxVersion < 21) + { + device.getUserMedia = false; + } + + // TODO: replace canvasBitBltShift detection with actual feature check + + // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it + // is safer to not try and use the fast copy-over method. + if (!device.iOS && (device.ie || device.firefox || device.chrome)) + { + device.canvasBitBltShift = true; + } + + // Known not to work + if (device.safari || device.mobileSafari) + { + device.canvasBitBltShift = false; + } + + } + + /** + * Checks/configures various input. + */ + function _checkInput () { + + if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1)) + { + device.touch = true; + } + + if (window.PointerEvent || window.MSPointerEvent || window.navigator.msPointerEnabled || window.navigator.pointerEnabled) + { + device.mspointer = true; + } + + if (!device.cocoonJS) + { + // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel + if ('onwheel' in window || (device.ie && 'WheelEvent' in window)) + { + // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ + device.wheelEvent = 'wheel'; + } + else if ('onmousewheel' in window) + { + // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. + device.wheelEvent = 'mousewheel'; + } + else if (device.firefox && 'MouseScrollEvent' in window) + { + // FF prior to 17. This should probably be scrubbed. + device.wheelEvent = 'DOMMouseScroll'; + } + } + + } + + /** + * Checks for support of the Full Screen API. + */ + function _checkFullScreenSupport () { + + var fs = [ + 'requestFullscreen', + 'requestFullScreen', + 'webkitRequestFullscreen', + 'webkitRequestFullScreen', + 'msRequestFullscreen', + 'msRequestFullScreen', + 'mozRequestFullScreen', + 'mozRequestFullscreen' + ]; + + var element = document.createElement('div'); + + for (var i = 0; i < fs.length; i++) + { + if (element[fs[i]]) + { + device.fullscreen = true; + device.requestFullscreen = fs[i]; + break; + } + } + + var cfs = [ + 'cancelFullScreen', + 'exitFullscreen', + 'webkitCancelFullScreen', + 'webkitExitFullscreen', + 'msCancelFullScreen', + 'msExitFullscreen', + 'mozCancelFullScreen', + 'mozExitFullscreen' + ]; + + if (device.fullscreen) + { + for (var i = 0; i < cfs.length; i++) + { + if (document[cfs[i]]) + { + device.cancelFullscreen = cfs[i]; + break; + } + } + } + + // Keyboard Input? + if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT']) + { + device.fullscreenKeyboard = true; + } + + } + + /** + * Check what browser is game running in. + */ + function _checkBrowser () { + + var ua = navigator.userAgent; + + if (/Arora/.test(ua)) + { + device.arora = true; + } + else if (/Edge\/\d+/.test(ua)) + { + device.edge = true; + } + else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.chrome = true; + device.chromeVersion = parseInt(RegExp.$1, 10); + } + else if (/Epiphany/.test(ua)) + { + device.epiphany = true; + } + else if (/Firefox\D+(\d+)/.test(ua)) + { + device.firefox = true; + device.firefoxVersion = parseInt(RegExp.$1, 10); + } + else if (/AppleWebKit/.test(ua) && device.iOS) + { + device.mobileSafari = true; + } + else if (/MSIE (\d+\.\d+);/.test(ua)) + { + device.ie = true; + device.ieVersion = parseInt(RegExp.$1, 10); + } + else if (/Midori/.test(ua)) + { + device.midori = true; + } + else if (/Opera/.test(ua)) + { + device.opera = true; + } + else if (/Safari\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.safari = true; + + if (/Version\/(\d+)\./.test(ua)) + { + device.safariVersion = parseInt(RegExp.$1, 10); + } + } + else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua)) + { + device.ie = true; + device.trident = true; + device.tridentVersion = parseInt(RegExp.$1, 10); + device.ieVersion = parseInt(RegExp.$3, 10); + } + + // Silk gets its own if clause because its ua also contains 'Safari' + if (/Silk/.test(ua)) + { + device.silk = true; + } + + // WebApp mode in iOS + if (navigator['standalone']) + { + device.webApp = true; + } + + if (typeof window.cordova !== 'undefined') + { + device.cordova = true; + } + + if (typeof process !== 'undefined' && typeof require !== 'undefined') + { + device.node = true; + } + + if (device.node && typeof process.versions === 'object') + { + device.nodeWebkit = !!process.versions['node-webkit']; + + device.electron = !!process.versions.electron; + } + + if (navigator['isCocoonJS']) + { + device.cocoonJS = true; + } + + if (device.cocoonJS) + { + try { + device.cocoonJSApp = (typeof CocoonJS !== 'undefined'); + } + catch(error) + { + device.cocoonJSApp = false; + } + } + + if (typeof window.ejecta !== 'undefined') + { + device.ejecta = true; + } + + if (/Crosswalk/.test(ua)) + { + device.crosswalk = true; + } + + } + + /** + * Check video support. + */ + function _checkVideo () { + + var videoElement = document.createElement("video"); + var result = false; + + try { + if (result = !!videoElement.canPlayType) + { + if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) + { + device.oggVideo = true; + } + + if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + device.h264Video = true; + device.mp4Video = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) + { + device.webmVideo = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) + { + device.vp9Video = true; + } + + if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + device.hlsVideo = true; + } + } + } catch (e) {} + } + + /** + * Check audio support. + */ + function _checkAudio () { + + device.audioData = !!(window['Audio']); + device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); + var audioElement = document.createElement('audio'); + var result = false; + + try { + if (result = !!audioElement.canPlayType) + { + if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) + { + device.ogg = true; + } + + if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) + { + device.opus = true; + } + + if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) + { + device.mp3 = true; + } + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) + { + device.wav = true; + } + + if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) + { + device.m4a = true; + } + + if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) + { + device.webm = true; + } + + if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') + { + if (device.edge) + { + device.dolby = true; + } + else if (device.safari && device.safariVersion >= 9) + { + if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)) + { + var major = parseInt(RegExp.$1, 10); + var minor = parseInt(RegExp.$2, 10); + + if ((major === 10 && minor >= 11) || major > 10) + { + device.dolby = true; + } + } + } + } + } + } catch (e) { + } + + } + + /** + * Check Little or Big Endian system. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsLittleEndian () { + + var a = new ArrayBuffer(4); + var b = new Uint8Array(a); + var c = new Uint32Array(a); + + b[0] = 0xa1; + b[1] = 0xb2; + b[2] = 0xc3; + b[3] = 0xd4; + + if (c[0] === 0xd4c3b2a1) + { + return true; + } + + if (c[0] === 0xa1b2c3d4) + { + return false; + } + else + { + // Could not determine endianness + return null; + } + + } + + /** + * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsUint8ClampedImageData () { + + if (Uint8ClampedArray === undefined) + { + return false; + } + + var elem = Phaser.CanvasPool.create(this, 1, 1); + var ctx = elem.getContext('2d'); + + if (!ctx) + { + return false; + } + + var image = ctx.createImageData(1, 1); + + Phaser.CanvasPool.remove(this); + + return image.data instanceof Uint8ClampedArray; + + } + + /** + * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess. + */ + function _checkDevice () { + + device.pixelRatio = window['devicePixelRatio'] || 1; + device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1; + device.iPhone4 = (device.pixelRatio === 2 && device.iPhone); + device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') !== -1; + + if (typeof Int8Array !== 'undefined') + { + device.typedArray = true; + } + else + { + device.typedArray = false; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') + { + device.littleEndian = _checkIsLittleEndian(); + device.LITTLE_ENDIAN = device.littleEndian; + } + + device.support32bit = (typeof ArrayBuffer !== 'undefined' && typeof Uint8ClampedArray !== 'undefined' && typeof Int32Array !== 'undefined' && device.littleEndian !== null && _checkIsUint8ClampedImageData()); + + navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; + + if (navigator.vibrate) + { + device.vibration = true; + } + + } + + /** + * Check whether the host environment support 3D CSS. + */ + function _checkCSS3D () { + + var el = document.createElement('p'); + var has3d; + var transforms = { + 'webkitTransform': '-webkit-transform', + 'OTransform': '-o-transform', + 'msTransform': '-ms-transform', + 'MozTransform': '-moz-transform', + 'transform': 'transform' + }; + + // Add it to the body to get the computed style. + document.body.insertBefore(el, null); + + for (var t in transforms) + { + if (el.style[t] !== undefined) + { + el.style[t] = "translate3d(1px,1px,1px)"; + has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]); + } + } + + document.body.removeChild(el); + device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none"); + + } + + // Run the checks + _checkOS(); + _checkBrowser(); + _checkAudio(); + _checkVideo(); + _checkCSS3D(); + _checkDevice(); + _checkFeatures(); + _checkCanvasFeatures(); + _checkFullScreenSupport(); + _checkInput(); + +}; + +/** +* Check whether the host environment can play audio. +* +* @method canPlayAudio +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.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 === 'opus' && this.opus) + { + return true; + } + else if (type === 'wav' && this.wav) + { + return true; + } + else if (type === 'webm' && this.webm) + { + return true; + } + else if (type === 'mp4' && this.dolby) + { + return true; + } + + return false; + +}; + +/** +* Check whether the host environment can play video files. +* +* @method canPlayVideo +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.canPlayVideo = function (type) { + + if (type === 'webm' && (this.webmVideo || this.vp9Video)) + { + return true; + } + else if (type === 'mp4' && (this.mp4Video || this.h264Video)) + { + return true; + } + else if ((type === 'ogg' || type === 'ogv') && this.oggVideo) + { + return true; + } + else if (type === 'mpeg' && this.hlsVideo) + { + return true; + } + + return false; + +}; + +/** + * Whether the device plays audio/video only in response to a user touch event. + * + * @method needsTouchUnlock + * @memberof Phaser.Device.prototype + * @return {boolean} + */ +Phaser.Device.needsTouchUnlock = function () { + return !!(!this.cocoonJS && (this.iOS || this.android) || (window.PhaserGlobal && window.PhaserGlobal.fakeiOSTouchLock)); +}; + +/** +* Detect if the host is a an Android Stock browser. +* This is available before the device "ready" event. +* +* Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. +* +* @example +* var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; +* +* @method isAndroidStockBrowser +* @memberof Phaser.Device.prototype +*/ +Phaser.Device.isAndroidStockBrowser = function () { + + var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/); + return matches && matches[1] < 537; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, +* including styles, offset and aspect ratio. +* +* @class Phaser.Canvas +* @static +*/ +Phaser.Canvas = { + + /** + * Creates a `canvas` DOM element. The element is not automatically added to the document. + * + * @method Phaser.Canvas.create + * @param {object} parent - The object that will own the canvas that is created. + * @param {number} [width=256] - The width of the canvas element. + * @param {number} [height=256] - The height of the canvas element.. + * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. + * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global. + * @return {HTMLCanvasElement} The newly created canvas element. + */ + create: function (parent, width, height, id, skipPool) { + + width = width || 256; + height = height || 256; + + var canvas = (skipPool) ? document.createElement('canvas') : Phaser.CanvasPool.create(parent, width, height); + + if (typeof id === 'string' && id !== '') + { + canvas.id = id; + } + + canvas.width = width; + canvas.height = height; + canvas.style.display = 'block'; + + return canvas; + + }, + + /** + * Sets the background color behind the canvas. This changes the canvas style property. + * + * @method Phaser.Canvas.setBackgroundColor + * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. + * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setBackgroundColor: function (canvas, color) { + + color = color || 'rgb(0,0,0)'; + + canvas.style.backgroundColor = color; + + return canvas; + + }, + + /** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @method Phaser.Canvas.setTouchAction + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @method Phaser.Canvas.setUserSelect + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. + * If no parent is given it will be added as a child of the document.body. + * + * @method Phaser.Canvas.addToDOM + * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM. + * @param {string|HTMLElement} parent - The DOM element to add the canvas to. + * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + addToDOM: function (canvas, parent, overflowHidden) { + + var target; + + if (overflowHidden === undefined) { overflowHidden = true; } + + if (parent) + { + if (typeof parent === 'string') + { + // hopefully an element ID + target = document.getElementById(parent); + } + else if (typeof parent === 'object' && parent.nodeType === 1) + { + // quick test for a HTMLelement + target = parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + target = document.body; + } + + if (overflowHidden && target.style) + { + target.style.overflow = 'hidden'; + } + + target.appendChild(canvas); + + return canvas; + + }, + + /** + * Removes the given canvas element from the DOM. + * + * @method Phaser.Canvas.removeFromDOM + * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM. + */ + removeFromDOM: function (canvas) { + + if (canvas.parentNode) + { + canvas.parentNode.removeChild(canvas); + } + + }, + + /** + * Sets the transform of the given canvas to the matrix values provided. + * + * @method Phaser.Canvas.setTransform + * @param {CanvasRenderingContext2D} context - The context to set the transform on. + * @param {number} translateX - The value to translate horizontally by. + * @param {number} translateY - The value to translate vertically by. + * @param {number} scaleX - The value to scale horizontally by. + * @param {number} scaleY - The value to scale vertically by. + * @param {number} skewX - The value to skew horizontaly by. + * @param {number} skewY - The value to skew vertically by. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) { + + context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); + + return context; + + }, + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @method Phaser.Canvas.setSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setSmoothingEnabled: function (context, value) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + context[s] = value; + } + + return context; + + }, + + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @method Phaser.Canvas.getSmoothingPrefix + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context. + */ + getSmoothingPrefix: function (context) { + + var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; + + for (var prefix in vendor) + { + var s = vendor[prefix] + 'mageSmoothingEnabled'; + + if (s in context) + { + return s; + } + } + + return null; + + }, + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * + * @method Phaser.Canvas.getSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to check for smoothing on. + * @return {boolean} True if the given context has image smoothing enabled, otherwise false. + */ + getSmoothingEnabled: function (context) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + return context[s]; + } + + }, + + /** + * Sets the CSS image-rendering property to `pixelated` or `crisp-edges`. + * This can remove blurring when the game canvas is scaled up. + * In some browsers this has no visible effect in WEBGL mode. + * Note that if this doesn't given the desired result then see the setSmoothingEnabled. + * + * @method Phaser.Canvas.setImageRenderingCrisp + * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. + * @return {HTMLCanvasElement} Returns the source canvas. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering + * @see https://caniuse.com/#feat=css-crisp-edges + */ + setImageRenderingCrisp: function (canvas) { + + var types = [ '-webkit-optimize-contrast', '-moz-crisp-edges', 'crisp-edges', 'pixelated' ]; + + for (var i = 0; i < types.length; i++) + { + canvas.style['image-rendering'] = types[i]; + } + + canvas.style.msInterpolationMode = 'nearest-neighbor'; + + return canvas; + + }, + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method Phaser.Canvas.setImageRenderingBicubic + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setImageRenderingBicubic: function (canvas) { + + canvas.style['image-rendering'] = 'auto'; + canvas.style.msInterpolationMode = 'bicubic'; + + return canvas; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Abstracts away the use of RAF or setTimeOut for the core game update loop. +* +* @class Phaser.RequestAnimationFrame +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available. +*/ +Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) { + + if (forceSetTimeOut === undefined) { forceSetTimeOut = false; } + + /** + * @property {Phaser.Game} game - The currently running game. + */ + this.game = game; + + /** + * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available. + */ + this.forceSetTimeOut = forceSetTimeOut; + + var vendors = [ + 'ms', + 'moz', + 'webkit', + 'o' + ]; + + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) + { + window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; + } + + /** + * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. + * @private + */ + this._isSetTimeOut = false; + + /** + * @property {function} _onLoop - The function called by the update. + * @private + */ + this._onLoop = null; + + /** + * @property {number} _timeOutID - The callback ID used when calling cancel. + * @private + */ + this._timeOutID = null; + +}; + +Phaser.RequestAnimationFrame.prototype = { + + /** + * Starts the requestAnimationFrame running or setTimeout if unavailable in browser + * @method Phaser.RequestAnimationFrame#start + */ + start: function () { + + this.isRunning = true; + + var _this = this; + + if (!window.requestAnimationFrame || this.forceSetTimeOut) + { + this._isSetTimeOut = true; + + this._onLoop = function () { + return _this.updateSetTimeout(); + }; + + this._timeOutID = window.setTimeout(this._onLoop, 0); + } + else + { + this._isSetTimeOut = false; + + this._onLoop = function (time) { + return _this.updateRAF(time); + }; + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the requestAnimationFrame + * @method Phaser.RequestAnimationFrame#updateRAF + */ + updateRAF: function (rafTime) { + + if (this.isRunning) + { + // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below) + this.game.update(Math.floor(rafTime)); + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the setTimeout. + * @method Phaser.RequestAnimationFrame#updateSetTimeout + */ + updateSetTimeout: function () { + + if (this.isRunning) + { + this.game.update(Date.now()); + + this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); + } + + }, + + /** + * Stops the requestAnimationFrame from running. + * @method Phaser.RequestAnimationFrame#stop + */ + stop: function () { + + if (this._isSetTimeOut) + { + clearTimeout(this._timeOutID); + } + else + { + window.cancelAnimationFrame(this._timeOutID); + } + + this.isRunning = false; + + }, + + /** + * Is the browser using setTimeout? + * @method Phaser.RequestAnimationFrame#isSetTimeOut + * @return {boolean} + */ + isSetTimeOut: function () { + return this._isSetTimeOut; + }, + + /** + * Is the browser using requestAnimationFrame? + * @method Phaser.RequestAnimationFrame#isRAF + * @return {boolean} + */ + isRAF: function () { + return (this._isSetTimeOut === false); + } + +}; + +Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of useful mathematical functions. +* +* These are normally accessed through `game.math`. +* +* @class Phaser.Math +* @static +* @see {@link Phaser.Utils} +* @see {@link Phaser.ArrayUtils} +*/ +Phaser.Math = { + + /** + * Twice PI. + * @property {number} Phaser.Math#PI2 + * @default ~6.283 + */ + PI2: Math.PI * 2, + + /** + * Half PI. + * @property {number} Phaser.Math#HALF_PI + * @default ~1.570 + */ + HALF_PI: Math.PI * 0.5, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#DEG_TO_RAD + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#RAD_TO_DEG + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * Convert degrees to radians. + * + * @method Phaser.Math#degToRad + * @param {number} degrees - Angle in degrees. + * @return {number} Angle in radians. + */ + degToRad: function (degrees) { + + return degrees * Phaser.Math.DEG_TO_RAD; + + }, + + /** + * Convert radians to degrees. + * + * @method Phaser.Math#radToDeg + * @param {number} radians - Angle in radians. + * @return {number} Angle in degrees + */ + radToDeg: function (radians) { + + return radians * Phaser.Math.RAD_TO_DEG; + + }, + + /** + * Given a number, this function returns the closest number that is a power of two. + * This function is from the Starling Framework. + * + * @method Phaser.Math#getNextPowerOfTwo + * @param {number} value - The value to get the closest power of two from. + * @return {number} The closest number that is a power of two. + */ + getNextPowerOfTwo: function (value) { + + if (value > 0 && (value & (value - 1)) === 0) + { + // http://goo.gl/D9kPj + return value; + } + else + { + var result = 1; + + while (result < value) + { + result <<= 1; + } + + return result; + } + + }, + + /** + * Checks if the given dimensions make a power of two texture. + * + * @method Phaser.Math#isPowerOfTwo + * @param {number} width - The width to check. + * @param {number} height - The height to check. + * @return {boolean} True if the width and height are a power of two. + */ + isPowerOfTwo: function (width, height) { + + return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); + + }, + + /** + * Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#random + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} A floating point number between min (inclusive) and max (exclusive). + */ + random: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + return (Math.random() * (max - min) + min); + + }, + + /** + * Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#between + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} An integer between min (inclusive) and max (inclusive). + */ + between: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + min = Math.ceil(min); + max = Math.floor(max); + + return Math.floor(Math.random() * (max - min + 1)) + min; + + }, + + /** + * Two number are fuzzyEqual if their difference is less than epsilon. + * + * @method Phaser.Math#fuzzyEqual + * @param {number} a - The first number to compare. + * @param {number} b - The second number to compare. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {boolean} True if |a-b|b+epsilon + */ + fuzzyGreaterThan: function (a, b, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return a > b - epsilon; + + }, + + /** + * Applies a fuzzy ceil to the given value. + * + * @method Phaser.Math#fuzzyCeil + * @param {number} val - The value to ceil. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} ceiling(val-epsilon) + */ + fuzzyCeil: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.ceil(val - epsilon); + + }, + + /** + * Applies a fuzzy floor to the given value. + * + * @method Phaser.Math#fuzzyFloor + * @param {number} val - The value to floor. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} floor(val+epsilon) + */ + fuzzyFloor: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.floor(val + epsilon); + + }, + + /** + * Averages all values passed to the function and returns the result. + * + * @method Phaser.Math#average + * @params {...number} The numbers to average + * @return {number} The average of all given values. + */ + average: function () { + + var sum = 0; + var len = arguments.length; + + for (var i = 0; i < len; i++) + { + sum += (+arguments[i]); + } + + return sum / len; + + }, + + /** + * @method Phaser.Math#shear + * @param {number} n + * @return {number} n mod 1 + */ + shear: function (n) { + + return n % 1; + + }, + + /** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. + * + * @method Phaser.Math#snapTo + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapTo: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.round(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. + * As will 14 snap to 10... but 16 will snap to 15. + * + * @method Phaser.Math#snapToFloor + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToFloor: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.floor(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. + * As will 14 will snap to 15... but 16 will snap to 20. + * + * @method Phaser.Math#snapToCeil + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToCeil: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.ceil(input / gap); + + return start + input; + + }, + + /** + * Round to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) === 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + * + * @method Phaser.Math#roundTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + roundTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.round(value * p) / p; + + }, + + /** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#floorTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + floorTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.floor(value * p) / p; + + }, + + /** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#ceilTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + ceilTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.ceil(value * p) / p; + + }, + + /** + * Rotates currentAngle towards targetAngle, taking the shortest rotation distance. + * The lerp argument is the amount to rotate by in this call. + * + * @method Phaser.Math#rotateToAngle + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * @return {number} The adjusted angle. + */ + rotateToAngle: function (currentAngle, targetAngle, lerp) { + + if (lerp === undefined) { lerp = 0.05; } + + if (currentAngle === targetAngle) + { + return currentAngle; + } + + if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (Phaser.Math.PI2 - lerp)) + { + currentAngle = targetAngle; + } + else + { + if (Math.abs(targetAngle - currentAngle) > Math.PI) + { + if (targetAngle < currentAngle) + { + targetAngle += Phaser.Math.PI2; + } + else + { + targetAngle -= Phaser.Math.PI2; + } + } + + if (targetAngle > currentAngle) + { + currentAngle += lerp; + } + else if (targetAngle < currentAngle) + { + currentAngle -= lerp; + } + } + + return currentAngle; + + }, + + /** + * Gets the shortest angle between `angle1` and `angle2`. + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method, and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * @method Phaser.Math#getShortestAngle + * @param {number} angle1 - The first angle. In the range -180 to 180. + * @param {number} angle2 - The second angle. In the range -180 to 180. + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ + getShortestAngle: function (angle1, angle2) { + + var difference = angle2 - angle1; + + if (difference === 0) + { + return 0; + } + + var times = Math.floor((difference - (-180)) / 360); + + return difference - (times * 360); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @method Phaser.Math#angleBetween + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetween: function (x1, y1, x2, y2) { + + return Math.atan2(y2 - y1, x2 - x1); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels + * down the screen. + * + * @method Phaser.Math#angleBetweenY + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetweenY: function (x1, y1, x2, y2) { + + return Math.atan2(x2 - x1, y2 - y1); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * @method Phaser.Math#angleBetweenPoints + * @param {Phaser.Point} point1 - The first point. + * @param {Phaser.Point} point2 - The second point. + * @return {number} The angle between the two points, in radians. + */ + angleBetweenPoints: function (point1, point2) { + + return Math.atan2(point2.y - point1.y, point2.x - point1.x); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * @method Phaser.Math#angleBetweenPointsY + * @param {Phaser.Point} point1 + * @param {Phaser.Point} point2 + * @return {number} The angle, in radians. + */ + angleBetweenPointsY: function (point1, point2) { + + return Math.atan2(point2.x - point1.x, point2.y - point1.y); + + }, + + /** + * Reverses an angle. + * @method Phaser.Math#reverseAngle + * @param {number} angleRad - The angle to reverse, in radians. + * @return {number} The reverse angle, in radians. + */ + reverseAngle: function (angleRad) { + + return this.normalizeAngle(angleRad + Math.PI, true); + + }, + + /** + * Normalizes an angle to the [0,2pi) range. + * @method Phaser.Math#normalizeAngle + * @param {number} angleRad - The angle to normalize, in radians. + * @return {number} The angle, fit within the [0,2pi] range, in radians. + */ + normalizeAngle: function (angleRad) { + + angleRad = angleRad % (2 * Math.PI); + return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI; + + }, + + /** + * Adds the given amount to the value, but never lets the value go over the specified maximum. + * + * @method Phaser.Math#maxAdd + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The new value. + */ + maxAdd: function (value, amount, max) { + + return Math.min(value + amount, max); + + }, + + /** + * Subtracts the given amount from the value, but never lets the value go below the specified minimum. + * + * @method Phaser.Math#minSub + * @param {number} value - The base value. + * @param {number} amount - The amount to subtract from the base value. + * @param {number} min - The minimum the value is allowed to be. + * @return {number} The new value. + */ + minSub: function (value, amount, min) { + + return Math.max(value - amount, min); + + }, + + /** + * Ensures that the value always stays between min and max, by wrapping the value around. + * + * If `max` is not larger than `min` the result is 0. + * + * @method Phaser.Math#wrap + * @param {number} value - The value to wrap. + * @param {number} min - The minimum the value is allowed to be. + * @param {number} max - The maximum the value is allowed to be, should be larger than `min`. + * @return {number} The wrapped value. + */ + wrap: function (value, min, max) { + + var range = max - min; + + if (range <= 0) + { + return 0; + } + + var result = (value - min) % range; + + if (result < 0) + { + result += range; + } + + return result + min; + + }, + + /** + * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. + * + * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. + * + * @method Phaser.Math#wrapValue + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The wrapped value. + */ + wrapValue: function (value, amount, max) { + + var diff; + value = Math.abs(value); + amount = Math.abs(amount); + max = Math.abs(max); + diff = (value + amount) % max; + + return diff; + + }, + + /** + * Returns true if the number given is odd. + * + * @method Phaser.Math#isOdd + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is odd. False if the given number is even. + */ + isOdd: function (n) { + + // Does not work with extremely large values + return !!(n & 1); + + }, + + /** + * Returns true if the number given is even. + * + * @method Phaser.Math#isEven + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is even. False if the given number is odd. + */ + isEven: function (n) { + + // Does not work with extremely large values + return !(n & 1); + + }, + + /** + * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.min` function when appropriate. + * + * @method Phaser.Math#min + * @return {number} The lowest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + 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; i < len; i++) + { + if (data[i] < data[min]) + { + min = i; + } + } + + return data[min]; + + }, + + /** + * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.max` function when appropriate. + * + * @method Phaser.Math#max + * @return {number} The largest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + max: function () { + + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + var data = arguments[0]; + } + else + { + var data = arguments; + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i] > data[max]) + { + max = i; + } + } + + return data[max]; + + }, + + /** + * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. + * It will find the lowest matching property value from the given objects. + * + * @method Phaser.Math#minProperty + * @return {number} The lowest value from those given. + */ + 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; i < len; i++) + { + if (data[i][property] < data[min][property]) + { + min = i; + } + } + + return data[min][property]; + + }, + + /** + * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. + * It will find the largest matching property value from the given objects. + * + * @method Phaser.Math#maxProperty + * @return {number} The largest value from those given. + */ + maxProperty: function (property) { + + if (arguments.length === 2 && typeof arguments[1] === 'object') + { + var data = arguments[1]; + } + else + { + var data = arguments.slice(1); + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i][property] > data[max][property]) + { + max = i; + } + } + + return data[max][property]; + + }, + + /** + * Keeps an angle value between -180 and +180; or -PI and PI if radians. + * + * @method Phaser.Math#wrapAngle + * @param {number} angle - The angle value to wrap + * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected. + * @return {number} The new angle value; will be the same as the input angle if it was within bounds. + */ + wrapAngle: function (angle, radians) { + + return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180); + + }, + + /** + * A Linear Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#linearInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + linearInterpolation: function (v, k) { + + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (k < 0) + { + return this.linear(v[0], v[1], f); + } + + if (k > 1) + { + return this.linear(v[m], v[m - 1], m - f); + } + + return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); + + }, + + /** + * A Bezier Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#bezierInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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; + + }, + + /** + * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#catmullRomInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + } + + }, + + /** + * Calculates a linear (interpolation) value over t. + * + * @method Phaser.Math#linear + * @param {number} p0 + * @param {number} p1 + * @param {number} t - A value between 0 and 1. + * @return {number} + */ + linear: function (p0, p1, t) { + + return (p1 - p0) * t + p0; + + }, + + /** + * @method Phaser.Math#bernstein + * @protected + * @param {number} n + * @param {number} i + * @return {number} + */ + bernstein: function (n, i) { + + return this.factorial(n) / this.factorial(i) / this.factorial(n - i); + + }, + + /** + * @method Phaser.Math#factorial + * @param {number} value - the number you want to evaluate + * @return {number} + */ + factorial: function (value) { + + if (value === 0) + { + return 1; + } + + var res = value; + + while(--value) + { + res *= value; + } + + return res; + + }, + + /** + * Calculates a catmum rom value. + * + * @method Phaser.Math#catmullRom + * @protected + * @param {number} p0 + * @param {number} p1 + * @param {number} p2 + * @param {number} p3 + * @param {number} t + * @return {number} + */ + catmullRom: function (p0, p1, p2, p3, t) { + + var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + + }, + + /** + * The absolute difference between two values. + * + * @method Phaser.Math#difference + * @param {number} a - The first value to check. + * @param {number} b - The second value to check. + * @return {number} The absolute difference between the two values. + */ + difference: function (a, b) { + + return Math.abs(a - b); + + }, + + /** + * Round to the next whole number _away_ from zero. + * + * @method Phaser.Math#roundAwayFromZero + * @param {number} value - Any number. + * @return {integer} The rounded value of that number. + */ + roundAwayFromZero: function (value) { + + // "Opposite" of truncate. + return (value > 0) ? Math.ceil(value) : Math.floor(value); + + }, + + /** + * Generate a sine and cosine table simultaneously and extremely quickly. + * The parameters allow you to specify the length, amplitude and frequency of the wave. + * This generator is fast enough to be used in real-time. + * Code based on research by Franky of scene.at + * + * @method Phaser.Math#sinCosGenerator + * @param {number} length - The length of the wave + * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} frequency - The frequency of the sine and cosine table data + * @return {{sin:number[], cos:number[]}} Returns the table data. + */ + sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) { + + if (sinAmplitude === undefined) { sinAmplitude = 1.0; } + if (cosAmplitude === undefined) { cosAmplitude = 1.0; } + if (frequency === undefined) { frequency = 1.0; } + + var sin = sinAmplitude; + var cos = cosAmplitude; + var frq = frequency * Math.PI / length; + + var cosTable = []; + var sinTable = []; + + for (var c = 0; c < length; c++) { + + cos -= sin * frq; + sin += cos * frq; + + cosTable[c] = cos; + sinTable[c] = sin; + + } + + return { sin: sinTable, cos: cosTable, length: length }; + + }, + + /** + * Returns the length of the hypotenuse connecting two segments of given lengths. + * + * @method Phaser.Math#hypot + * @param {number} a + * @param {number} b + * @return {number} The length of the hypotenuse connecting the given lengths. + */ + hypot: function (a, b) { + + return Math.sqrt(a * a + b * b); + + }, + + /** + * Returns the euclidian distance between the two given set of coordinates. + * + * @method Phaser.Math#distance + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance between the two sets of coordinates. + */ + distance: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Returns the euclidean distance squared between the two given set of + * coordinates (cuts out a square root operation before returning). + * + * @method Phaser.Math#distanceSq + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance squared between the two sets of coordinates. + */ + distanceSq: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return dx * dx + dy * dy; + + }, + + /** + * Returns the distance between the two given set of coordinates at the power given. + * + * @method Phaser.Math#distancePow + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} [pow=2] + * @return {number} The distance between the two sets of coordinates. + */ + distancePow: function (x1, y1, x2, y2, pow) { + + if (pow === undefined) { pow = 2; } + + return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); + + }, + + /** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @method Phaser.Math#clamp + * @param {float} v - The value to be clamped. + * @param {float} min - The minimum bounds. + * @param {float} max - The maximum bounds. + * @return {number} The clamped value. + */ + clamp: function (v, min, max) { + + if (v < min) + { + return min; + } + else if (max < v) + { + return max; + } + else + { + return v; + } + + }, + + /** + * Clamp `x` to the range `[a, Infinity)`. + * Roughly the same as `Math.max(x, a)`, except for NaN handling. + * + * @method Phaser.Math#clampBottom + * @param {number} x + * @param {number} a + * @return {number} + */ + clampBottom: function (x, a) { + + return x < a ? a : x; + + }, + + /** + * Checks if two values are within the given tolerance of each other. + * + * @method Phaser.Math#within + * @param {number} a - The first number to check + * @param {number} b - The second number to check + * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range. + * @return {boolean} True if a is <= tolerance of b. + * @see {@link Phaser.Math.fuzzyEqual} + */ + within: function (a, b, tolerance) { + + return (Math.abs(a - b) <= tolerance); + + }, + + /** + * Linear mapping from range to range + * + * @method Phaser.Math#mapLinear + * @param {number} x - The value to map + * @param {number} a1 - First endpoint of the range + * @param {number} a2 - Final endpoint of the range + * @param {number} b1 - First endpoint of the range + * @param {number} b2 - Final endpoint of the range + * @return {number} + */ + mapLinear: function (x, a1, a2, b1, b2) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + + }, + + /** + * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smoothstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smoothstep: function (x, min, max) { + + // Scale, bias and saturate x to 0..1 range + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + // Evaluate polynomial + return x * x * (3 - 2 * x); + + }, + + /** + * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smootherstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smootherstep: function (x, min, max) { + + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + return x * x * x * (x * (x * 6 - 15) + 10); + + }, + + /** + * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. + * + * This works differently from `Math.sign` for values of NaN and -0, etc. + * + * @method Phaser.Math#sign + * @param {number} x + * @return {integer} An integer in {-1, 0, 1} + */ + sign: function (x) { + + return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); + + }, + + /** + * Work out what percentage value `a` is of value `b` using the given base. + * + * @method Phaser.Math#percent + * @param {number} a - The value to work out the percentage for. + * @param {number} b - The value you wish to get the percentage of. + * @param {number} [base=0] - The base value. + * @return {number} The percentage a is of b, between 0 and 1. + */ + percent: function (a, b, base) { + + if (base === undefined) { base = 0; } + + if (a > b || base > b) + { + return 1; + } + else if (a < base || base > a) + { + return 0; + } + else + { + return (a - base) / b; + } + + } + +}; + +/* jshint noempty: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An extremely useful repeatable random data generator. +* +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. +* +* The random number genererator is based on the Alea PRNG, but is modified. +* - https://github.com/coverslide/node-alea +* - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror +* - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404) +* +* @class Phaser.RandomDataGenerator +* @constructor +* @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}). +*/ +Phaser.RandomDataGenerator = function (seeds) { + + if (seeds === undefined) { seeds = []; } + + /** + * @property {number} c - Internal var. + * @private + */ + this.c = 1; + + /** + * @property {number} s0 - Internal var. + * @private + */ + this.s0 = 0; + + /** + * @property {number} s1 - Internal var. + * @private + */ + this.s1 = 0; + + /** + * @property {number} s2 - Internal var. + * @private + */ + this.s2 = 0; + + if (typeof seeds === 'string') + { + this.state(seeds); + } + else + { + this.sow(seeds); + } + +}; + +Phaser.RandomDataGenerator.prototype = { + + /** + * Private random helper. + * + * @method Phaser.RandomDataGenerator#rnd + * @private + * @return {number} + */ + rnd: function () { + + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + + return this.s2; + }, + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.RandomDataGenerator#sow + * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used. + */ + sow: function (seeds) { + + // Always reset to default seed + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + this.c = 1; + + if (!seeds) + { + return; + } + + // Apply any seeds + for (var i = 0; i < seeds.length && (seeds[i] != null); i++) + { + var 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); + } + + }, + + /** + * Internal method that creates a seed hash. + * + * @method Phaser.RandomDataGenerator#hash + * @private + * @param {any} data + * @return {number} hashed value. + */ + hash: function (data) { + + var h, i, n; + n = 0xefc8249d; + data = data.toString(); + + for (i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } + + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + + }, + + /** + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#integer + * @return {number} A random integer between 0 and 2^32. + */ + integer: function() { + + return this.rnd.apply(this) * 0x100000000;// 2^32 + + }, + + /** + * Returns a random real number between 0 and 1. + * + * @method Phaser.RandomDataGenerator#frac + * @return {number} A random real number between 0 and 1. + */ + frac: function() { + + return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 + + }, + + /** + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#real + * @return {number} A random real number between 0 and 2^32. + */ + real: function() { + + return this.integer() + this.frac(); + + }, + + /** + * Returns a random integer between and including min and max. + * + * @method Phaser.RandomDataGenerator#integerInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + integerInRange: function (min, max) { + + return Math.floor(this.realInRange(0, max - min + 1) + min); + + }, + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.RandomDataGenerator#between + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + between: function (min, max) { + + return this.integerInRange(min, max); + + }, + + /** + * Returns a random real number between min and max. + * + * @method Phaser.RandomDataGenerator#realInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + realInRange: function (min, max) { + + return this.frac() * (max - min) + min; + + }, + + /** + * Returns a random real number between -1 and 1. + * + * @method Phaser.RandomDataGenerator#normal + * @return {number} A random real number between -1 and 1. + */ + normal: function () { + + return 1 - 2 * this.frac(); + + }, + + /** + * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 + * + * @method Phaser.RandomDataGenerator#uuid + * @return {string} A valid RFC4122 version4 ID hex string + */ + 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; + + }, + + /** + * Returns a random member of `array`. + * + * @method Phaser.RandomDataGenerator#pick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + pick: function (ary) { + + return ary[this.integerInRange(0, ary.length - 1)]; + + }, + + /** + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.RandomDataGenerator#sign + * @return {number} -1 or +1. + */ + sign: function () { + + return this.pick([-1, 1]); + + }, + + /** + * Returns a random member of `array`, favoring the earlier entries. + * + * @method Phaser.RandomDataGenerator#weightedPick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + weightedPick: function (ary) { + + return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)]; + + }, + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.RandomDataGenerator#timestamp + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random timestamp between min and max. + */ + timestamp: function (min, max) { + + return this.realInRange(min || 946684800000, max || 1577862000000); + + }, + + /** + * Returns a random angle between -180 and 180. + * + * @method Phaser.RandomDataGenerator#angle + * @return {number} A random number between -180 and 180. + */ + angle: function() { + + return this.integerInRange(-180, 180); + + }, + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.RandomDataGenerator#state + * @param {string} [state] - Generator state to be set. + * @return {string} The current state of the generator. + */ + state: function (state) { + + if (typeof state === 'string' && state.match(/^!rnd/)) + { + state = state.split(','); + + this.c = parseFloat(state[1]); + this.s0 = parseFloat(state[2]); + this.s1 = parseFloat(state[3]); + this.s2 = parseFloat(state[4]); + } + + return ['!rnd', this.c, this.s0, this.s1, this.s2].join(','); + + } + +}; + +Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator; + +/** + * @author Timo Hausmann + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** +* A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. +* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. +* Original version at https://github.com/timohausmann/quadtree-js/ +* +* @class Phaser.QuadTree +* @constructor +* @param {number} x - The top left coordinate of the quadtree. +* @param {number} y - The top left coordinate of the quadtree. +* @param {number} width - The width of the quadtree in pixels. +* @param {number} height - The height of the quadtree in pixels. +* @param {number} [maxObjects=10] - The maximum number of objects per node. +* @param {number} [maxLevels=4] - The maximum number of levels to iterate to. +* @param {number} [level=0] - Which level is this? +*/ +Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) { + + /** + * @property {number} maxObjects - The maximum number of objects per node. + * @default + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - The maximum number of levels to break down to. + * @default + */ + this.maxLevels = 4; + + /** + * @property {number} level - The current level. + */ + this.level = 0; + + /** + * @property {object} bounds - Object that contains the quadtree bounds. + */ + this.bounds = {}; + + /** + * @property {array} objects - Array of quadtree children. + */ + this.objects = []; + + /** + * @property {array} nodes - Array of associated child nodes. + */ + this.nodes = []; + + /** + * @property {array} _empty - Internal empty array. + * @private + */ + this._empty = []; + + this.reset(x, y, width, height, maxObjects, maxLevels, level); + +}; + +Phaser.QuadTree.prototype = { + + /** + * Resets the QuadTree. + * + * @method Phaser.QuadTree#reset + * @param {number} x - The top left coordinate of the quadtree. + * @param {number} y - The top left coordinate of the quadtree. + * @param {number} width - The width of the quadtree in pixels. + * @param {number} height - The height of the quadtree in pixels. + * @param {number} [maxObjects=10] - The maximum number of objects per node. + * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. + * @param {number} [level=0] - Which level is this? + */ + 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; + + }, + + /** + * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. + * + * @method Phaser.QuadTree#populate + * @param {Phaser.Group} group - The Group to add to the quadtree. + */ + populate: function (group) { + + group.forEach(this.populateHandler, this, true); + + }, + + /** + * Handler for the populate method. + * + * @method Phaser.QuadTree#populateHandler + * @param {Phaser.Sprite|object} sprite - The Sprite to check. + */ + populateHandler: function (sprite) { + + if (sprite.body && sprite.exists) + { + this.insert(sprite.body); + } + + }, + + /** + * Split the node into 4 subnodes + * + * @method Phaser.QuadTree#split + */ + split: function () { + + // top right node + this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // top left node + this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom left node + this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom right node + this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + }, + + /** + * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. + * + * @method Phaser.QuadTree#insert + * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. + */ + insert: function (body) { + + var i = 0; + var index; + + // if we have subnodes ... + 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.level < this.maxLevels) + { + // Split if we don't already have subnodes + if (this.nodes[0] == null) + { + this.split(); + } + + // Add objects to subnodes + while (i < this.objects.length) + { + index = this.getIndex(this.objects[i]); + + if (index !== -1) + { + // this is expensive - see what we can do about it + this.nodes[index].insert(this.objects.splice(i, 1)[0]); + } + else + { + i++; + } + } + } + + }, + + /** + * Determine which node the object belongs to. + * + * @method Phaser.QuadTree#getIndex + * @param {Phaser.Rectangle|object} rect - The bounds in which to check. + * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. + */ + getIndex: function (rect) { + + // default is that rect doesn't fit, i.e. it straddles the internal quadrants + var index = -1; + + if (rect.x < this.bounds.right && rect.right < this.bounds.right) + { + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-left quadrant of this quadtree + index = 1; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-left quadrant of this quadtree + index = 2; + } + } + else if (rect.x > this.bounds.right) + { + // rect can completely fit within the right quadrants + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-right quadrant of this quadtree + index = 0; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-right quadrant of this quadtree + index = 3; + } + } + + return index; + + }, + + /** + * Return all objects that could collide with the given Sprite or Rectangle. + * + * @method Phaser.QuadTree#retrieve + * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle. + * @return {array} - Array with all detected objects. + */ + 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 rect fits into a subnode .. + if (index !== -1) + { + returnObjects = returnObjects.concat(this.nodes[index].retrieve(source)); + } + else + { + // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed) + 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 the quadtree. + * @method Phaser.QuadTree#clear + */ + 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; + +/** +* Javascript QuadTree +* @version 1.0 +* +* @version 1.3, March 11th 2014 +* @author Richard Davey +* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked +* it massively to add node indexing, removed lots of temp. var creation and significantly +* increased performance as a result. +* +* Original version at https://github.com/timohausmann/quadtree-js/ +*/ + +/** +* @copyright © 2012 Timo Hausmann +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. +* +* @class Phaser.Net +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Net = function (game) { + + this.game = game; + +}; + +Phaser.Net.prototype = { + + /** + * Returns the hostname given by the browser. + * + * @method Phaser.Net#getHostName + * @return {string} + */ + getHostName: function () { + + if (window.location && window.location.hostname) { + return window.location.hostname; + } + + return null; + + }, + + /** + * Compares the given domain name against the hostname of the browser containing the game. + * If the domain name is found it returns true. + * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. + * Do not include 'http://' at the start. + * + * @method Phaser.Net#checkDomainName + * @param {string} domain + * @return {boolean} true if the given domain fragment can be found in the window.location.hostname + */ + checkDomainName: function (domain) { + return window.location.hostname.indexOf(domain) !== -1; + }, + + /** + * Updates a value on the Query String and returns it in full. + * If the value doesn't already exist it is set. + * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. + * Optionally you can redirect to the new url, or just return it as a string. + * + * @method Phaser.Net#updateQueryString + * @param {string} key - The querystring key to update. + * @param {string} value - The new value to be set. If it already exists it will be replaced. + * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. + * @param {string} url - The URL to modify. If none is given it uses window.location.href. + * @return {string} If redirect is false then the modified url and query string is returned. + */ + updateQueryString: function (key, value, redirect, url) { + + if (redirect === undefined) { redirect = false; } + if (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; + } + + }, + + /** + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#getQueryString + * @param {string} [parameter=''] - If specified this will return just the value for that key. + * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. + */ + getQueryString: function (parameter) { + + if (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 && parameter === this.decodeURI(key[0])) + { + return this.decodeURI(key[1]); + } + else + { + output[this.decodeURI(key[0])] = this.decodeURI(key[1]); + } + } + } + + return output; + + }, + + /** + * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and + * decodes it, replacing \ with spaces in the return. Used internally by the Net classes. + * + * @method Phaser.Net#decodeURI + * @param {string} value - The URI component to be decoded. + * @return {string} The decoded value. + */ + decodeURI: function (value) { + return decodeURIComponent(value.replace(/\+/g, " ")); + } + +}; + +Phaser.Net.prototype.constructor = Phaser.Net; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. +* Tweens are hooked into the game clock and pause system, adjusting based on the game state. +* +* TweenManager is based heavily on tween.js by http://soledadpenades.com. +* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. +* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. +* Please see https://github.com/sole/tween.js for a full list of contributors. +* +* @class Phaser.TweenManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.TweenManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * @property {boolean} frameBased + * @default + */ + this.frameBased = false; + + /** + * @property {array} _tweens - All of the currently running tweens. + * @private + */ + this._tweens = []; + + /** + * @property {array} _add - All of the tweens queued to be added in the next update. + * @private + */ + this._add = []; + + this.easeMap = { + + "Power0": Phaser.Easing.Power0, + "Power1": Phaser.Easing.Power1, + "Power2": Phaser.Easing.Power2, + "Power3": Phaser.Easing.Power3, + "Power4": Phaser.Easing.Power4, + + "Linear": Phaser.Easing.Linear.None, + "Quad": Phaser.Easing.Quadratic.Out, + "Cubic": Phaser.Easing.Cubic.Out, + "Quart": Phaser.Easing.Quartic.Out, + "Quint": Phaser.Easing.Quintic.Out, + "Sine": Phaser.Easing.Sinusoidal.Out, + "Expo": Phaser.Easing.Exponential.Out, + "Circ": Phaser.Easing.Circular.Out, + "Elastic": Phaser.Easing.Elastic.Out, + "Back": Phaser.Easing.Back.Out, + "Bounce": Phaser.Easing.Bounce.Out, + + "Quad.easeIn": Phaser.Easing.Quadratic.In, + "Cubic.easeIn": Phaser.Easing.Cubic.In, + "Quart.easeIn": Phaser.Easing.Quartic.In, + "Quint.easeIn": Phaser.Easing.Quintic.In, + "Sine.easeIn": Phaser.Easing.Sinusoidal.In, + "Expo.easeIn": Phaser.Easing.Exponential.In, + "Circ.easeIn": Phaser.Easing.Circular.In, + "Elastic.easeIn": Phaser.Easing.Elastic.In, + "Back.easeIn": Phaser.Easing.Back.In, + "Bounce.easeIn": Phaser.Easing.Bounce.In, + + "Quad.easeOut": Phaser.Easing.Quadratic.Out, + "Cubic.easeOut": Phaser.Easing.Cubic.Out, + "Quart.easeOut": Phaser.Easing.Quartic.Out, + "Quint.easeOut": Phaser.Easing.Quintic.Out, + "Sine.easeOut": Phaser.Easing.Sinusoidal.Out, + "Expo.easeOut": Phaser.Easing.Exponential.Out, + "Circ.easeOut": Phaser.Easing.Circular.Out, + "Elastic.easeOut": Phaser.Easing.Elastic.Out, + "Back.easeOut": Phaser.Easing.Back.Out, + "Bounce.easeOut": Phaser.Easing.Bounce.Out, + + "Quad.easeInOut": Phaser.Easing.Quadratic.InOut, + "Cubic.easeInOut": Phaser.Easing.Cubic.InOut, + "Quart.easeInOut": Phaser.Easing.Quartic.InOut, + "Quint.easeInOut": Phaser.Easing.Quintic.InOut, + "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut, + "Expo.easeInOut": Phaser.Easing.Exponential.InOut, + "Circ.easeInOut": Phaser.Easing.Circular.InOut, + "Elastic.easeInOut": Phaser.Easing.Elastic.InOut, + "Back.easeInOut": Phaser.Easing.Back.InOut, + "Bounce.easeInOut": Phaser.Easing.Bounce.InOut + + }; + + this.game.onPause.add(this._pauseAll, this); + this.game.onResume.add(this._resumeAll, this); + +}; + +Phaser.TweenManager.prototype = { + + /** + * Get all the tween objects in an array. + * @method Phaser.TweenManager#getAll + * @returns {Phaser.Tween[]} Array with all tween objects. + */ + getAll: function () { + + return this._tweens; + + }, + + /** + * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. + * @method Phaser.TweenManager#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._tweens.length; i++) + { + this._tweens[i].pendingDelete = true; + } + + this._add = []; + + }, + + /** + * Remove all tweens from a specific object, array of objects or Group. + * + * @method Phaser.TweenManager#removeFrom + * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. + * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. + */ + removeFrom: function (obj, children) { + + if (children === undefined) { children = true; } + + var i; + var len; + + if (Array.isArray(obj)) + { + for (i = 0, len = obj.length; i < len; i++) + { + this.removeFrom(obj[i]); + } + } + else if (obj.type === Phaser.GROUP && children) + { + for (var i = 0, len = obj.children.length; i < len; i++) + { + this.removeFrom(obj.children[i]); + } + } + else + { + for (i = 0, len = this._tweens.length; i < len; i++) + { + if (obj === this._tweens[i].target) + { + this.remove(this._tweens[i]); + } + } + + for (i = 0, len = this._add.length; i < len; i++) + { + if (obj === this._add[i].target) + { + this.remove(this._add[i]); + } + } + } + + }, + + /** + * Add a new tween into the TweenManager. + * + * @method Phaser.TweenManager#add + * @param {Phaser.Tween} tween - The tween object you want to add. + * @returns {Phaser.Tween} The tween object you added to the manager. + */ + add: function (tween) { + + tween._manager = this; + this._add.push(tween); + + }, + + /** + * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.TweenManager#create + * @param {object} object - Object the tween will be run on. + * @returns {Phaser.Tween} The newly created tween object. + */ + create: function (object) { + + return new Phaser.Tween(object, this.game, this); + + }, + + /** + * Remove a tween from this manager. + * + * @method Phaser.TweenManager#remove + * @param {Phaser.Tween} tween - The tween object you want to remove. + */ + remove: function (tween) { + + var i = this._tweens.indexOf(tween); + + if (i !== -1) + { + this._tweens[i].pendingDelete = true; + } + else + { + i = this._add.indexOf(tween); + + if (i !== -1) + { + this._add[i].pendingDelete = true; + } + } + + }, + + /** + * Update all the tween objects you added to this manager. + * + * @method Phaser.TweenManager#update + * @returns {boolean} Return false if there's no tween to update, otherwise return true. + */ + update: function () { + + var addTweens = this._add.length; + var numTweens = this._tweens.length; + + if (numTweens === 0 && addTweens === 0) + { + return false; + } + + var i = 0; + + while (i < numTweens) + { + if (this._tweens[i].update(this.game.time.time)) + { + i++; + } + else + { + this._tweens.splice(i, 1); + + numTweens--; + } + } + + // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running + if (addTweens > 0) + { + this._tweens = this._tweens.concat(this._add); + this._add.length = 0; + } + + return true; + + }, + + /** + * Checks to see if a particular Sprite is currently being tweened. + * + * The `checkIsRunning` parameter will exclude tweens that have **just** completed or been stopped but haven't yet been removed from the manager. + * + * @method Phaser.TweenManager#isTweening + * @param {object} object - The object to check for tweens against. + * @param {boolean} [checkIsRunning=false] - Also check that the tween is running and is not marked for deletion. + * @returns {boolean} Returns true if the object is currently being tweened, false if not. + */ + isTweening: function(object, checkIsRunning) { + + if (!checkIsRunning) { checkIsRunning = false; } + + return this._tweens.some(function(tween) { + return (tween.target === object) && (!checkIsRunning || (tween.isRunning && !tween.pendingDelete)); + }); + + }, + + /** + * Private. Called by game focus loss. Pauses all currently running tweens. + * + * @method Phaser.TweenManager#_pauseAll + * @private + */ + _pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._pause(); + } + + }, + + /** + * Private. Called by game focus loss. Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#_resumeAll + * @private + */ + _resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._resume(); + } + + }, + + /** + * Pauses all currently running tweens. + * + * @method Phaser.TweenManager#pauseAll + */ + pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].pause(); + } + + }, + + /** + * Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#resumeAll + */ + resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].resume(true); + } + + } + +}; + +Phaser.TweenManager.prototype.constructor = Phaser.TweenManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tween allows you to alter one or more properties of a target object over a defined period of time. +* This can be used for things such as alpha fading Sprites, scaling them or motion. +* Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object +* by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and +* are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. +* +* @class Phaser.Tween +* @constructor +* @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. +* @param {Phaser.Game} game - Current game instance. +* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. +*/ +Phaser.Tween = function (target, game, manager) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. + */ + this.target = target; + + /** + * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween. + */ + this.manager = manager; + + /** + * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween. + */ + this.timeline = []; + + /** + * If set to `true` the current tween will play in reverse. + * If the tween hasn't yet started this has no effect. + * If there are child tweens then all child tweens will play in reverse from the current point. + * @property {boolean} reverse + * @default + */ + this.reverse = false; + + /** + * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. + * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. + * + * @property {number} timeScale + * @default + */ + this.timeScale = 1; + + /** + * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count. + */ + this.repeatCounter = 0; + + /** + * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager. + * @default + * @readonly + */ + this.pendingDelete = false; + + /** + * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onStart + */ + this.onStart = new Phaser.Signal(); + + /** + * The onLoop event is fired if the Tween, or any child tweens loop. + * It will be sent 2 parameters: the target object and this tween. + * + * @property {Phaser.Signal} onLoop + */ + this.onLoop = new Phaser.Signal(); + + /** + * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onRepeat + */ + this.onRepeat = new Phaser.Signal(); + + /** + * The onChildComplete event is fired when the Tween or any of its children completes. + * Fires every time a child completes unless a child is set to repeat forever. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onChildComplete + */ + this.onChildComplete = new Phaser.Signal(); + + /** + * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. + * @default + */ + this.isRunning = false; + + /** + * @property {number} current - The current Tween child being run. + * @default + * @readonly + */ + this.current = 0; + + /** + * @property {object} properties - Target property cache used when building the child data values. + */ + this.properties = {}; + + /** + * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it. + */ + this.chainedTween = null; + + /** + * @property {boolean} isPaused - Is this Tween paused or not? + * @default + */ + this.isPaused = false; + + /** + * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * + * The default value is whatever you've set in TweenManager.frameBased. + * + * @property {boolean} frameBased + * @default + */ + this.frameBased = manager.frameBased; + + /** + * @property {function} _onUpdateCallback - An onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallback = null; + + /** + * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallbackContext = null; + + /** + * @property {number} _pausedTime - Private pause timer. + * @private + * @default + */ + this._pausedTime = 0; + + /** + * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not. + * @private + */ + this._hasStarted = false; +}; + +/** +* A helper for tweening {@link Phaser.Color.createColor color objects}. +* +* It can be passed to {@link #onUpdateCallback}. +* +* ```javascript +* var color = Phaser.Color.createColor(255, 0, 0); // red +* +* var tween = game.add.tween(color).to({ +* r: 0, g: 0, b: 255 // blue +* }); +* +* tween.onUpdateCallback(Phaser.Tween.updateColor); +* +* tween.start(); +* ``` +* +* @method Phaser.Tween.updateColor +* @static +* @param {Phaser.Tween} tween - A Tween with a {@link #target} that is a {@link Phaser.Color.createColor color object}. +*/ +Phaser.Tween.updateColor = function (tween) { + + Phaser.Color.updateColor(tween.target); + +}; + +Phaser.Tween.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#to + * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined || duration <= 0) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.to cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#from + * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.from cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Starts the tween running. Can also be called by the `autoStart` parameter of {@link #to} or {@link #from}. + * This sets the {@link #isRunning} property to `true` and dispatches the {@link #onStart} signal. + * If the tween has a delay set then nothing will start tweening until the delay has expired. + * If the tween is already running, is flagged for deletion (such as after {@link #stop}), + * or has an empty timeline, calling start has no effect and the `onStart` signal is not dispatched. + * + * @method Phaser.Tween#start + * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + start: function (index) { + + if (index === undefined) { index = 0; } + + if (this.pendingDelete) + { + console.warn('Phaser.Tween.start cannot be called after Tween.stop'); + return this; + } + + if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning) + { + return this; + } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + this.manager.add(this); + + this.isRunning = true; + + if (index < 0 || index > this.timeline.length - 1) + { + index = 0; + } + + this.current = index; + + this.timeline[this.current].start(); + + return this; + + }, + + /** + * Stops the tween if running and flags it for deletion from the TweenManager. The tween can't be {@link #start restarted} after this. + * The {@link #onComplete} signal is not dispatched and no chained tweens are started unless the `complete` parameter is set to `true`. + * If you just wish to pause a tween then use {@link #pause} instead. + * If the tween is not running, it is **not** flagged for deletion and can be started again. + * + * @method Phaser.Tween#stop + * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + stop: function (complete) { + + if (complete === undefined) { complete = false; } + + this.isRunning = false; + + this._onUpdateCallback = null; + this._onUpdateCallbackContext = null; + + if (complete) + { + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + } + + this.manager.remove(this); + + return this; + + }, + + /** + * Updates either a single TweenData or all TweenData objects properties to the given value. + * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. + * The property is not checked, so if you pass an invalid one you'll generate a run-time error. + * + * @method Phaser.Tween#updateTweenData + * @param {string} property - The property to update. + * @param {number|function} value - The value to set the property to. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + updateTweenData: function (property, value, index) { + + if (this.timeline.length === 0) { return this; } + + if (index === undefined) { index = 0; } + + if (index === -1) + { + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i][property] = value; + } + } + else + { + this.timeline[index][property] = value; + } + + return this; + + }, + + /** + * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. + * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. + * If you have child tweens and pass -1 as the index value it sets the delay across all of them. + * + * @method Phaser.Tween#delay + * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + delay: function (duration, index) { + + return this.updateTweenData('delay', duration, index); + + }, + + /** + * Sets the number of times this tween will repeat. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. + * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. + * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. + * + * @method Phaser.Tween#repeat + * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeat: function (total, repeatDelay, index) { + + if (repeatDelay === undefined) { repeatDelay = 0; } + + this.updateTweenData('repeatCounter', total, index); + this.updateTweenData('repeatTotal', total, index); + + return this.updateTweenData('repeatDelay', repeatDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will repeat itself. + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#repeatDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatDelay: function (duration, index) { + + return this.updateTweenData('repeatDelay', duration, index); + + }, + + /** + * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. + * Used in combination with repeat you can create endless loops. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. + * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. + * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. + * + * @method Phaser.Tween#yoyo + * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo. + * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyo: function(enable, yoyoDelay, index) { + + if (yoyoDelay === undefined) { yoyoDelay = 0; } + + this.updateTweenData('yoyo', enable, index); + + return this.updateTweenData('yoyoDelay', yoyoDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#yoyoDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyoDelay: function (duration, index) { + + return this.updateTweenData('yoyoDelay', duration, index); + + }, + + /** + * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. + * + * @method Phaser.Tween#easing + * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + easing: function (ease, index) { + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + return this.updateTweenData('easingFunction', ease, index); + + }, + + /** + * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. + * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. + * The interpolation function is only used if the target properties is an array. + * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. + * + * @method Phaser.Tween#interpolation + * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) + * @param {object} [context] - The context under which the interpolation function will be run. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + interpolation: function (interpolation, context, index) { + + if (context === undefined) { context = Phaser.Math; } + + this.updateTweenData('interpolationFunction', interpolation, index); + + return this.updateTweenData('interpolationContext', context, index); + + }, + + /** + * Set how many times this tween and all of its children will repeat. + * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. + * + * @method Phaser.Tween#repeatAll + * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatAll: function (total) { + + if (total === undefined) { total = 0; } + + this.repeatCounter = total; + + return this; + + }, + + /** + * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called + * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. + * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. + * For that you should listen to `onComplete` on the final tween in your chain. + * + * If you pass multiple tweens to this method they will be joined into a single long chain. + * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. + * Any previously chained tweens that may have been set will be overwritten. + * + * @method Phaser.Tween#chain + * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + chain: function () { + + var i = arguments.length; + + while (i--) + { + if (i > 0) + { + arguments[i - 1].chainedTween = arguments[i]; + } + else + { + this.chainedTween = arguments[i]; + } + } + + return this; + + }, + + /** + * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. + * + * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. + * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. + * + * Usage: + * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) + * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) + * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) + * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) + * .loop(); + * @method Phaser.Tween#loop + * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + loop: function (value) { + + if (value === undefined) { value = true; } + + this.repeatCounter = (value) ? -1 : 0; + + return this; + + }, + + /** + * Sets a callback to be fired each time this tween updates. + * + * The callback receives the current Tween, the {@link Phaser.TweenData#value 'value' of the current TweenData}, and the current {@link Phaser.TweenData TweenData}. The second parameter is most useful. + * + * ```javascript + * tween.onUpdateCallback(function (tween, value, tweenData) { + * console.log('Tween running -- percent: %.2f value: %.2f', tweenData.percent, value); + * }); + * ``` + * + * @method Phaser.Tween#onUpdateCallback + * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. + * @param {object} callbackContext - The context in which to call the onUpdate callback. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + onUpdateCallback: function (callback, callbackContext) { + + this._onUpdateCallback = callback; + this._onUpdateCallbackContext = callbackContext; + + return this; + + }, + + /** + * Pauses the tween. Resume playback with Tween.resume. + * + * @method Phaser.Tween#pause + */ + pause: function () { + + this.isPaused = true; + + this._codePaused = true; + + this._pausedTime = this.game.time.time; + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * + * @private + * @method Phaser.Tween#_pause + */ + _pause: function () { + + if (!this._codePaused) + { + this.isPaused = true; + + this._pausedTime = this.game.time.time; + } + + }, + + /** + * Resumes a paused tween. + * + * @method Phaser.Tween#resume + */ + resume: function () { + + if (this.isPaused) + { + this.isPaused = false; + + this._codePaused = false; + + for (var i = 0; i < this.timeline.length; i++) + { + if (!this.timeline[i].isRunning) + { + this.timeline[i].startTime += (this.game.time.time - this._pausedTime); + } + } + } + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * @method Phaser.Tween#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Core tween update function called by the TweenManager. Does not need to be invoked directly. + * + * @method Phaser.Tween#update + * @param {number} time - A timestamp passed in by the TweenManager. + * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). + */ + update: function (time) { + + if (this.pendingDelete || !this.target) + { + return false; + } + + if (this.isPaused) + { + return true; + } + + var status = this.timeline[this.current].update(time); + + if (status === Phaser.TweenData.PENDING) + { + return true; + } + else if (status === Phaser.TweenData.RUNNING) + { + if (!this._hasStarted) + { + this.onStart.dispatch(this.target, this); + this._hasStarted = true; + } + + if (this._onUpdateCallback !== null) + { + this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]); + } + + // In case the update callback modifies this tween + return this.isRunning; + } + else if (status === Phaser.TweenData.LOOPED) + { + if (this.timeline[this.current].repeatCounter === -1) + { + this.onLoop.dispatch(this.target, this); + } + else + { + this.onRepeat.dispatch(this.target, this); + } + + return true; + } + else if (status === Phaser.TweenData.COMPLETE) + { + var complete = false; + + // What now? + if (this.reverse) + { + this.current--; + + if (this.current < 0) + { + this.current = this.timeline.length - 1; + complete = true; + } + } + else + { + this.current++; + + if (this.current === this.timeline.length) + { + this.current = 0; + complete = true; + } + } + + if (complete) + { + // We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it? + if (this.repeatCounter === -1) + { + this.timeline[this.current].start(); + this.onLoop.dispatch(this.target, this); + return true; + } + else if (this.repeatCounter > 0) + { + this.repeatCounter--; + + this.timeline[this.current].start(); + this.onRepeat.dispatch(this.target, this); + return true; + } + else + { + // No more repeats and no more children, so we're done + this.isRunning = false; + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + + return false; + } + } + else + { + // We've still got some children to go + this.onChildComplete.dispatch(this.target, this); + this.timeline[this.current].start(); + return true; + } + } + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * It ignores delay and repeat counts and any chained tweens, but does include child tweens. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.Tween#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate, data) { + + if (this.game === null || this.target === null) + { + return null; + } + + if (frameRate === undefined) { frameRate = 60; } + if (data === undefined) { data = []; } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + for (var i = 0; i < this.timeline.length; i++) + { + data = data.concat(this.timeline[i].generateData(frameRate)); + } + + return data; + + } + +}; + +/** +* @name Phaser.Tween#totalDuration +* @property {number} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds. +*/ +Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', { + + get: function () { + + var total = 0; + + for (var i = 0; i < this.timeline.length; i++) + { + total += this.timeline[i].duration; + } + + return total; + + } + +}); + +Phaser.Tween.prototype.constructor = Phaser.Tween; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the +* starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for +* TweenData objects and can contain multiple TweenData objects. +* +* @class Phaser.TweenData +* @constructor +* @param {Phaser.Tween} parent - The Tween that owns this TweenData object. +*/ +Phaser.TweenData = function (parent) { + + /** + * @property {Phaser.Tween} parent - The Tween which owns this TweenData. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = parent.game; + + /** + * @property {object} vStart - An object containing the values at the start of the tween. + * @private + */ + this.vStart = {}; + + /** + * @property {object} vStartCache - Cached starting values. + * @private + */ + this.vStartCache = {}; + + /** + * @property {object} vEnd - An object containing the values at the end of the tween. + * @private + */ + this.vEnd = {}; + + /** + * @property {object} vEndCache - Cached ending values. + * @private + */ + this.vEndCache = {}; + + /** + * @property {number} duration - The duration of the tween in ms. + * @default + */ + this.duration = 1000; + + /** + * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is. + * @readonly + */ + this.percent = 0; + + /** + * @property {number} value - The output of the easing function for the current {@link #percent}. Depending on the easing function, this will be within [0, 1] or a slightly larger range (e.g., Bounce). When easing is Linear, this will be identical to {@link #percent}. + * @readonly + */ + this.value = 0; + + /** + * @property {number} repeatCounter - If the Tween is set to repeat this is the number of repeats remaining (and `repeatTotal - repeatCounter` is the number of repeats completed). + */ + this.repeatCounter = 0; + + /** + * @property {number} repeatDelay - The amount of time in ms between repeats of this tween. + */ + this.repeatDelay = 0; + + /** + * @property {number} repeatTotal - The total number of times this Tween will repeat. + * @readonly + */ + this.repeatTotal = 0; + + /** + * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween) + * @default + * @todo Appears unused. + */ + this.interpolate = false; + + /** + * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false. + * @default + */ + this.yoyo = false; + + /** + * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween. + */ + this.yoyoDelay = 0; + + /** + * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). + * @default + */ + this.inReverse = false; + + /** + * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. + * @default + */ + this.delay = 0; + + /** + * @property {number} dt - Current time value. + */ + this.dt = 0; + + /** + * @property {number} startTime - The time the Tween started or null if it hasn't yet started. + */ + this.startTime = null; + + /** + * @property {function} easingFunction - The easing function used for the Tween. + * @default Phaser.Easing.Default + */ + this.easingFunction = Phaser.Easing.Default; + + /** + * @property {function} interpolationFunction - The interpolation function used for Array-based Tween. + * @default Phaser.Math.linearInterpolation + */ + this.interpolationFunction = Phaser.Math.linearInterpolation; + + /** + * @property {object} interpolationContext - The interpolation function context used for the Tween. + * @default Phaser.Math + */ + this.interpolationContext = Phaser.Math; + + /** + * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} isFrom - Is this a from tween or a to tween? + * @default + */ + this.isFrom = false; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.PENDING = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.RUNNING = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.LOOPED = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.COMPLETE = 3; + +Phaser.TweenData.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * + * @method Phaser.TweenData#to + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + to: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = false; + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * + * @method Phaser.TweenData#from + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + from: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = true; + + return this; + + }, + + /** + * Starts the Tween running. + * + * @method Phaser.TweenData#start + * @return {Phaser.TweenData} This Tween object. + */ + start: function () { + + this.startTime = this.game.time.time + this.delay; + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + if (this.delay > 0) + { + this.isRunning = false; + } + else + { + this.isRunning = true; + } + + if (this.isFrom) + { + // Reverse them all and instant set them + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + this.parent.target[property] = this.vStart[property]; + } + } + + this.value = 0; + this.repeatCounter = this.repeatTotal; + + return this; + + }, + + /** + * Loads the values from the target object into this Tween. + * + * @private + * @method Phaser.TweenData#loadValues + * @return {Phaser.TweenData} This Tween object. + */ + loadValues: function () { + + for (var property in this.parent.properties) + { + // Load the property from the parent object + this.vStart[property] = this.parent.properties[property]; + + // Check if an Array was provided as property value + if (Array.isArray(this.vEnd[property])) + { + if (this.vEnd[property].length === 0) + { + continue; + } + + if (this.percent === 0) + { + // Put the start value at the beginning of the array + // but we only want to do this once, if the Tween hasn't run before + this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]); + } + } + + if (typeof this.vEnd[property] !== 'undefined') + { + if (typeof this.vEnd[property] === 'string') + { + // Parses relative end values with start as base (e.g.: +10, -3) + this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10); + } + + this.parent.properties[property] = this.vEnd[property]; + } + else + { + // Null tween + this.vEnd[property] = this.vStart[property]; + } + + this.vStartCache[property] = this.vStart[property]; + this.vEndCache[property] = this.vEnd[property]; + } + + return this; + + }, + + /** + * Updates this Tween. This is called automatically by Phaser.Tween. + * + * @protected + * @method Phaser.TweenData#update + * @param {number} time - A timestamp passed in by the Tween parent. + * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. + */ + update: function (time) { + + if (!this.isRunning) + { + if (time >= this.startTime) + { + this.isRunning = true; + } + else + { + return Phaser.TweenData.PENDING; + } + } + else + { + // Is Running, but is waiting to repeat + if (time < this.startTime) + { + return Phaser.TweenData.RUNNING; + } + } + + var ms = (this.parent.frameBased) ? this.game.time.physicsElapsedMS : this.game.time.elapsedMS; + + if (this.parent.reverse) + { + this.dt -= ms * this.parent.timeScale; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += ms * this.parent.timeScale; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + this.parent.target[property] = start + ((end - start) * this.value); + } + } + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + return this.repeat(); + } + + return Phaser.TweenData.RUNNING; + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.TweenData#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate) { + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + var data = []; + var complete = false; + var fps = (1 / frameRate) * 1000; + + do + { + if (this.parent.reverse) + { + this.dt -= fps; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += fps; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + var blob = {}; + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + blob[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + blob[property] = start + ((end - start) * this.value); + } + } + + data.push(blob); + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + complete = true; + } + + } while (!complete); + + if (this.yoyo) + { + var reversed = data.slice(); + reversed.reverse(); + data = data.concat(reversed); + } + + return data; + + }, + + /** + * Checks if this Tween is meant to repeat or yoyo and handles doing so. + * + * @private + * @method Phaser.TweenData#repeat + * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE. + */ + repeat: function () { + + // If not a yoyo and repeatCounter = 0 then we're done + if (this.yoyo) + { + // We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end + if (this.inReverse && this.repeatCounter === 0) + { + // Restore the properties + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + this.inReverse = false; + + return Phaser.TweenData.COMPLETE; + } + + this.inReverse = !this.inReverse; + } + else + { + if (this.repeatCounter === 0) + { + return Phaser.TweenData.COMPLETE; + } + } + + if (this.inReverse) + { + // If inReverse we're going from vEnd to vStartCache + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + } + } + else + { + // If not inReverse we're just repopulating the cache again + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + // -1 means repeat forever, otherwise decrement the repeatCounter + // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total + if (this.repeatCounter > 0) + { + this.repeatCounter--; + } + } + + this.startTime = this.game.time.time; + + if (this.yoyo && this.inReverse) + { + this.startTime += this.yoyoDelay; + } + else if (!this.inReverse) + { + this.startTime += this.repeatDelay; + } + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + return Phaser.TweenData.LOOPED; + + } + +}; + +Phaser.TweenData.prototype.constructor = Phaser.TweenData; + +/* jshint curly: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of easing methods defining ease-in and ease-out curves. +* +* @class Phaser.Easing +*/ +Phaser.Easing = { + + /** + * Linear easing. + * + * @class Phaser.Easing.Linear + */ + Linear: { + + /** + * Linear Easing (no variation). + * + * @method Phaser.Easing.Linear#None + * @param {number} k - The value to be tweened. + * @returns {number} k. + */ + None: function ( k ) { + + return k; + + } + + }, + + /** + * Quadratic easing. + * + * @class Phaser.Easing.Quadratic + */ + Quadratic: { + + /** + * Ease-in. + * + * @method Phaser.Easing.Quadratic#In + * @param {number} k - The value to be tweened. + * @returns {number} k^2. + */ + In: function ( k ) { + + return k * k; + + }, + + /** + * Ease-out. + * + * @method Phaser.Easing.Quadratic#Out + * @param {number} k - The value to be tweened. + * @returns {number} k* (2-k). + */ + Out: function ( k ) { + + return k * ( 2 - k ); + + }, + + /** + * Ease-in/out. + * + * @method Phaser.Easing.Quadratic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; + return - 0.5 * ( --k * ( k - 2 ) - 1 ); + + } + + }, + + /** + * Cubic easing. + * + * @class Phaser.Easing.Cubic + */ + Cubic: { + + /** + * Cubic ease-in. + * + * @method Phaser.Easing.Cubic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k; + + }, + + /** + * Cubic ease-out. + * + * @method Phaser.Easing.Cubic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k + 1; + + }, + + /** + * Cubic ease-in/out. + * + * @method Phaser.Easing.Cubic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k + 2 ); + + } + + }, + + /** + * Quartic easing. + * + * @class Phaser.Easing.Quartic + */ + Quartic: { + + /** + * Quartic ease-in. + * + * @method Phaser.Easing.Quartic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k; + + }, + + /** + * Quartic ease-out. + * + * @method Phaser.Easing.Quartic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return 1 - ( --k * k * k * k ); + + }, + + /** + * Quartic ease-in/out. + * + * @method Phaser.Easing.Quartic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; + return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); + + } + + }, + + /** + * Quintic easing. + * + * @class Phaser.Easing.Quintic + */ + Quintic: { + + /** + * Quintic ease-in. + * + * @method Phaser.Easing.Quintic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k * k; + + }, + + /** + * Quintic ease-out. + * + * @method Phaser.Easing.Quintic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k * k * k + 1; + + }, + + /** + * Quintic ease-in/out. + * + * @method Phaser.Easing.Quintic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); + + } + + }, + + /** + * Sinusoidal easing. + * + * @class Phaser.Easing.Sinusoidal + */ + Sinusoidal: { + + /** + * Sinusoidal ease-in. + * + * @method Phaser.Easing.Sinusoidal#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 1 - Math.cos( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-out. + * + * @method Phaser.Easing.Sinusoidal#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return Math.sin( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-in/out. + * + * @method Phaser.Easing.Sinusoidal#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); + + } + + }, + + /** + * Exponential easing. + * + * @class Phaser.Easing.Exponential + */ + Exponential: { + + /** + * Exponential ease-in. + * + * @method Phaser.Easing.Exponential#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k === 0 ? 0 : Math.pow( 1024, k - 1 ); + + }, + + /** + * Exponential ease-out. + * + * @method Phaser.Easing.Exponential#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); + + }, + + /** + * Exponential ease-in/out. + * + * @method Phaser.Easing.Exponential#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); + return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); + + } + + }, + + /** + * Circular easing. + * + * @class Phaser.Easing.Circular + */ + Circular: { + + /** + * Circular ease-in. + * + * @method Phaser.Easing.Circular#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Math.sqrt( 1 - k * k ); + + }, + + /** + * Circular ease-out. + * + * @method Phaser.Easing.Circular#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return Math.sqrt( 1 - ( --k * k ) ); + + }, + + /** + * Circular ease-in/out. + * + * @method Phaser.Easing.Circular#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); + return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); + + } + + }, + + /** + * Elastic easing. + * + * @class Phaser.Easing.Elastic + */ + Elastic: { + + /** + * Elastic ease-in. + * + * @method Phaser.Easing.Elastic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + + }, + + /** + * Elastic ease-out. + * + * @method Phaser.Easing.Elastic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); + + }, + + /** + * Elastic ease-in/out. + * + * @method Phaser.Easing.Elastic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; + + } + + }, + + /** + * Back easing. + * + * @class Phaser.Easing.Back + */ + Back: { + + /** + * Back ease-in. + * + * @method Phaser.Easing.Back#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s = 1.70158; + return k * k * ( ( s + 1 ) * k - s ); + + }, + + /** + * Back ease-out. + * + * @method Phaser.Easing.Back#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s = 1.70158; + return --k * k * ( ( s + 1 ) * k + s ) + 1; + + }, + + /** + * Back ease-in/out. + * + * @method Phaser.Easing.Back#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s = 1.70158 * 1.525; + if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); + return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); + + } + + }, + + /** + * Bounce easing. + * + * @class Phaser.Easing.Bounce + */ + Bounce: { + + /** + * Bounce ease-in. + * + * @method Phaser.Easing.Bounce#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Phaser.Easing.Bounce.Out( 1 - k ); + + }, + + /** + * Bounce ease-out. + * + * @method Phaser.Easing.Bounce#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if ( k < ( 1 / 2.75 ) ) { + + return 7.5625 * k * k; + + } else if ( k < ( 2 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; + + } else if ( k < ( 2.5 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; + + } else { + + return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; + + } + + }, + + /** + * Bounce ease-in/out. + * + * @method Phaser.Easing.Bounce#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5; + return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5; + + } + + } + +}; + +Phaser.Easing.Default = Phaser.Easing.Linear.None; +Phaser.Easing.Power0 = Phaser.Easing.Linear.None; +Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out; +Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out; +Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out; +Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is the core internal game clock. +* +* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, +* and also handles the standard Timer pool. +* +* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}. +* +* There are different *types* of time in Phaser: +* +* - ***Game time*** always runs at the speed of time in real life. +* +* Unlike wall-clock time, *game time stops when Phaser is paused*. +* +* Game time is used for {@link Phaser.Timer timer events}. +* +* - ***Physics time*** represents the amount of time given to physics calculations. +* +* *When {@link #slowMotion} is in effect physics time runs slower than game time.* +* Like game time, physics time stops when Phaser is paused. +* +* Physics time is used for physics calculations and {@link Phaser.Tween tweens}. +* +* - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time. +* +* This time is independent of Phaser and always progresses, regardless of if Phaser is paused. +* +* @class Phaser.Time +* @constructor +* @param {Phaser.Game} game A reference to the currently running game. +*/ +Phaser.Time = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * The `Date.now()` value when the time was last updated. + * @property {integer} time + * @protected + */ + this.time = 0; + + /** + * The `now` when the previous update occurred. + * @property {number} prevTime + * @protected + */ + this.prevTime = 0; + + /** + * An increasing value representing cumulative milliseconds since an undisclosed epoch. + * + * While this value is in milliseconds and can be used to compute time deltas, + * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference. + * + * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; + * the value can only be relied upon within a particular game instance. + * + * @property {number} now + * @protected + */ + this.now = 0; + + /** + * Elapsed time since the last time update, in milliseconds, based on `now`. + * + * This value _may_ include time that the game is paused/inactive. + * + * While the game is active, this will be similar to (1000 / {@link #fps}). + * + * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {number} elapsed + * @see Phaser.Time.time + * @protected + */ + this.elapsed = 0; + + /** + * The time in ms since the last time update, in milliseconds, based on `time`. + * + * This value is corrected for game pauses and will be "about zero" after a game is resumed. + * + * _Note:_ This is updated once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {integer} elapsedMS + * @protected + */ + this.elapsedMS = 0; + + /** + * The physics update delta, in fractional seconds. + * + * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) + * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system + * is unable to consistently maintain the desired FPS. + * + * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. + * + * @property {number} physicsElapsed + */ + this.physicsElapsed = 1 / 60; + + /** + * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. + * + * @property {number} physicsElapsedMS + */ + this.physicsElapsedMS = (1 / 60) * 1000; + + /** + * The desiredFps multiplier as used by Game.update. + * @property {integer} desiredFpsMult + * @protected + */ + this.desiredFpsMult = 1.0 / 60; + + /** + * The desired frame rate of the game. + * + * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates. + * + * @property {number} _desiredFps + * @private + * @default + */ + this._desiredFps = 60; + + /** + * The suggested frame rate for your game, based on an averaged real frame rate. + * This value is only populated if `Time.advancedTiming` is enabled. + * + * _Note:_ This is not available until after a few frames have passed; until then + * it's set to the same value as desiredFps. + * + * @property {number} suggestedFps + * @default + */ + this.suggestedFps = this.desiredFps; + + /** + * Scaling factor to make the game move smoothly in slow motion (or fast motion) + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * You likely need to adjust {@link #desiredFps} as well such that `desiredFps / slowMotion === 60`. + * + * @property {number} slowMotion + * @default + */ + this.slowMotion = 1.0; + + /** + * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. This isn't expensive, but displaying it with {@link Phaser.Utils.Debug#text} can be, especially in WebGL mode. + * @property {boolean} advancedTiming + * @default + */ + this.advancedTiming = false; + + /** + * Advanced timing result: The number of animation frames received from the browser in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} frames + * @readonly + */ + this.frames = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateLogic logic updates} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} updates + * @readonly + */ + this.updates = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateRender renders} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} renders + * @readonly + */ + this.renders = 0; + + /** + * Advanced timing result: Frames per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} fps + * @readonly + */ + this.fps = 0; + + /** + * Advanced timing result: Logic updates per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} ups + * @readonly + */ + this.ups = 0; + + /** + * Advanced timing result: Renders per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} rps + * @readonly + */ + this.rps = 0; + + /** + * Advanced timing result: The lowest rate the fps has dropped to. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMin + */ + this.fpsMin = 1000; + + /** + * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMax + */ + this.fpsMax = 0; + + /** + * Advanced timing result: The minimum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMin + * @default + */ + this.msMin = 1000; + + /** + * Advanced timing result: The maximum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMax + */ + this.msMax = 0; + + /** + * Records how long the game was last paused, in milliseconds. + * (This is not updated until the game is resumed.) + * @property {number} pauseDuration + */ + this.pauseDuration = 0; + + /** + * @property {number} timeToCall - The value that setTimeout needs to work out when to next update + * @protected + */ + this.timeToCall = 0; + + /** + * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop + * @protected + */ + this.timeExpected = 0; + + /** + * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to. + * @property {Phaser.Timer} events + */ + this.events = new Phaser.Timer(this.game, false); + + /** + * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated + * @private + */ + this._frameCount = 0; + + /** + * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated + * @private + */ + this._elapsedAccumulator = 0; + + /** + * @property {number} _started - The time at which the Game instance started. + * @private + */ + this._started = 0; + + /** + * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. + * @private + */ + this._timeLastSecond = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {boolean} _justResumed - Internal value used to recover from the game pause state. + * @private + */ + this._justResumed = false; + + /** + * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects. + * @private + */ + this._timers = []; + +}; + +Phaser.Time.prototype = { + + /** + * Called automatically by Phaser.Game after boot. Should not be called directly. + * + * @method Phaser.Time#boot + * @protected + */ + boot: function () { + + this._started = Date.now(); + this.time = Date.now(); + this.events.start(); + this.timeExpected = this.time; + + }, + + /** + * Adds an existing Phaser.Timer object to the Timer pool. + * + * @method Phaser.Time#add + * @param {Phaser.Timer} timer - An existing Phaser.Timer object. + * @return {Phaser.Timer} The given Phaser.Timer object. + */ + add: function (timer) { + + this._timers.push(timer); + + return timer; + + }, + + /** + * Creates a new stand-alone Phaser.Timer object. + * + * @method Phaser.Time#create + * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). + * @return {Phaser.Timer} The Timer object that was created. + */ + create: function (autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + var timer = new Phaser.Timer(this.game, autoDestroy); + + this._timers.push(timer); + + return timer; + + }, + + /** + * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer. + * + * @method Phaser.Time#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._timers.length; i++) + { + this._timers[i].destroy(); + } + + this._timers = []; + + this.events.removeAll(); + + }, + + /** + * Refreshes the Time.time and Time.elapsedMS properties from the system clock. + * + * @method Phaser.Time#refresh + */ + refresh: function () { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + }, + + /** + * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. + * + * @method Phaser.Time#update + * @protected + * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}. + */ + update: function (time) { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + // 'now' is currently still holding the time of the last call, move it into prevTime + this.prevTime = this.now; + + // update 'now' to hold the current time + // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now) + this.now = time; + + // elapsed time between previous call and now - this could be a high resolution value + this.elapsed = this.now - this.prevTime; + + if (this.game.raf._isSetTimeOut) + { + // console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time); + + // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game + this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time))); + + // time when the next call is expected if using timers + this.timeExpected = time + this.timeToCall; + + // console.log('Time expect', this.timeExpected); + } + + if (this.advancedTiming) + { + this.updateAdvancedTiming(); + } + + // Paused but still running? + if (!this.game.paused) + { + // Our internal Phaser.Timer + this.events.update(this.time); + + if (this._timers.length) + { + this.updateTimers(); + } + } + + }, + + /** + * Handles the updating of the Phaser.Timers (if any) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateTimers + * @private + */ + updateTimers: function () { + + // Any game level timers + var i = 0; + var len = this._timers.length; + + while (i < len) + { + if (this._timers[i].update(this.time)) + { + i++; + } + else + { + // Timer requests to be removed + this._timers.splice(i, 1); + len--; + } + } + + }, + + /** + * Handles the updating of the advanced timing values (if enabled) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateAdvancedTiming + * @private + */ + updateAdvancedTiming: function () { + + // count the number of time.update calls + this._frameCount++; + this._elapsedAccumulator += this.elapsed; + + // occasionally recalculate the suggestedFps based on the accumulated elapsed time + if (this._frameCount >= this._desiredFps * 2) + { + // this formula calculates suggestedFps in multiples of 5 fps + this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5; + this._frameCount = 0; + this._elapsedAccumulator = 0; + } + + this.msMin = Math.min(this.msMin, this.elapsed); + this.msMax = Math.max(this.msMax, this.elapsed); + + this.frames++; + + if (this.now > this._timeLastSecond + 1000) + { + var interval = this.now - this._timeLastSecond; + this.fps = Math.round((this.frames * 1000) / interval); + this.ups = Math.round((this.updates * 1000) / interval); + this.rps = Math.round((this.renders * 1000) / interval); + this.fpsMin = Math.min(this.fpsMin, this.fps); + this.fpsMax = Math.max(this.fpsMax, this.fps); + this._timeLastSecond = this.now; + this.frames = 0; + this.updates = 0; + this.renders = 0; + } + + }, + + /** + * Counts one logic update (if advanced timing is enabled). + * + * @method Phaser.Time#countUpdate + * @private + */ + countUpdate: function () { + + if (this.advancedTiming) + { + this.updates++; + } + + }, + + /** + * Counts one render (if advanced timing is enabled). + * + * @method Phaser.Time#countRender + * @private + */ + countRender: function () { + + if (this.advancedTiming) + { + this.renders++; + } + + }, + + /** + * Called when the game enters a paused state. + * + * @method Phaser.Time#gamePaused + * @private + */ + gamePaused: function () { + + this._pauseStarted = Date.now(); + + this.events.pause(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._pause(); + } + + }, + + /** + * Called when the game resumes from a paused state. + * + * @method Phaser.Time#gameResumed + * @private + */ + gameResumed: function () { + + // Set the parameter which stores Date.now() to make sure it's correct on resume + this.time = Date.now(); + + this.pauseDuration = this.time - this._pauseStarted; + + this.events.resume(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._resume(); + } + + }, + + /** + * The number of seconds that have elapsed since the game was started. + * + * @method Phaser.Time#totalElapsedSeconds + * @return {number} The number of seconds that have elapsed since the game was started. + */ + totalElapsedSeconds: function() { + return (this.time - this._started) * 0.001; + }, + + /** + * How long has passed since the given time. + * + * @method Phaser.Time#elapsedSince + * @param {number} since - The time you want to measure against. + * @return {number} The difference between the given time and now. + */ + elapsedSince: function (since) { + return this.time - since; + }, + + /** + * How long has passed since the given time (in seconds). + * + * @method Phaser.Time#elapsedSecondsSince + * @param {number} since - The time you want to measure (in seconds). + * @return {number} Duration between given time and now (in seconds). + */ + elapsedSecondsSince: function (since) { + return (this.time - since) * 0.001; + }, + + /** + * Resets the private _started value to now and removes all currently running Timers. + * + * @method Phaser.Time#reset + */ + reset: function () { + + this._started = this.time; + this.removeAll(); + + } + +}; + +/** +* The number of logic updates per second. +* +* This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. +* +* The render rate is unaffected unless you also turn off {@link Phaser.Game#forceSingleRender}. +* +* @name Phaser.Time#desiredFps +* @type {integer} +* @default 60 +*/ +Object.defineProperty(Phaser.Time.prototype, "desiredFps", { + + get: function () { + + return this._desiredFps; + + }, + + set: function (value) { + + this._desiredFps = value; + + // Set the physics elapsed time... this will always be 1 / this.desiredFps + // because we're using fixed time steps in game.update + this.physicsElapsed = 1 / value; + + this.physicsElapsedMS = this.physicsElapsed * 1000; + + this.desiredFpsMult = 1.0 / value; + + } + +}); + +Phaser.Time.prototype.constructor = Phaser.Time; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback. +* Many different timer events, with individual delays, can be added to the same Timer. +* +* All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. +* +* Timers are based on real life time, adjusted for game pause durations. +* That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account. +* +* @class Phaser.Timer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). +*/ +Phaser.Timer = function (game, autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * True if the Timer is actively running. + * + * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer. + * @property {boolean} running + * @default + * @readonly + */ + this.running = false; + + /** + * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). + * @property {boolean} autoDestroy + */ + this.autoDestroy = autoDestroy; + + /** + * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending. + * @readonly + * @default + */ + this.expired = false; + + /** + * @property {number} elapsed - Elapsed time since the last frame (in ms). + * @protected + */ + this.elapsed = 0; + + /** + * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. + */ + this.events = []; + + /** + * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. + * + * The signal is supplied with one argument, `timer`, which is this Timer object. + * + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {number} nextTick - The time the next tick will occur. + * @readonly + * @protected + */ + this.nextTick = 0; + + /** + * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. + */ + this.timeCap = 1000; + + /** + * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. + * @readonly + * @default + */ + this.paused = false; + + /** + * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {number} _started - The time at which this Timer instance started running. + * @private + * @default + */ + this._started = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {number} _pauseTotal - Total paused time. + * @private + */ + this._pauseTotal = 0; + + /** + * @property {number} _now - The current start-time adjusted time. + * @private + */ + this._now = Date.now(); + + /** + * @property {number} _len - Temp. array length variable. + * @private + */ + this._len = 0; + + /** + * @property {number} _marked - Temp. counter variable. + * @private + */ + this._marked = 0; + + /** + * @property {number} _i - Temp. array counter variable. + * @private + */ + this._i = 0; + + /** + * @property {number} _diff - Internal cache var. + * @private + */ + this._diff = 0; + + /** + * @property {number} _newTick - Internal cache var. + * @private + */ + this._newTick = 0; + +}; + +/** +* Number of milliseconds in a minute. +* @constant +* @type {integer} +*/ +Phaser.Timer.MINUTE = 60000; + +/** +* Number of milliseconds in a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.SECOND = 1000; + +/** +* Number of milliseconds in half a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.HALF = 500; + +/** +* Number of milliseconds in a quarter of a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.QUARTER = 250; + +Phaser.Timer.prototype = { + + /** + * Creates a new TimerEvent on this Timer. + * + * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. + * + * @method Phaser.Timer#create + * @private + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {boolean} loop - Should the event loop or not? + * @param {number} repeatCount - The number of times the event will repeat. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {any[]} arguments - The values to be sent to your callback function when it is called. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + create: function (delay, loop, repeatCount, callback, callbackContext, args) { + + delay = Math.round(delay); + + var tick = delay; + + if (this._now === 0) + { + tick += this.game.time.time; + } + else + { + tick += this._now; + } + + var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args); + + this.events.push(event); + + this.order(); + + this.expired = false; + + return event; + + }, + + /** + * Adds a new Event to this Timer. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#add + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + add: function (delay, callback, callbackContext) { + + return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. + * If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#repeat + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + repeat: function (delay, repeatCount, callback, callbackContext) { + + return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4)); + + }, + + /** + * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#loop + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + loop: function (delay, callback, callbackContext) { + + return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Starts this Timer running. + * @method Phaser.Timer#start + * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start. + */ + start: function (delay) { + + if (this.running) + { + return; + } + + this._started = this.game.time.time + (delay || 0); + + this.running = true; + + for (var i = 0; i < this.events.length; i++) + { + this.events[i].tick = this.events[i].delay + this._started; + } + + }, + + /** + * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. + * @method Phaser.Timer#stop + * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain. + */ + stop: function (clearEvents) { + + this.running = false; + + if (clearEvents === undefined) { clearEvents = true; } + + if (clearEvents) + { + this.events.length = 0; + } + + }, + + /** + * Removes a pending TimerEvent from the queue. + * @param {Phaser.TimerEvent} event - The event to remove from the queue. + * @method Phaser.Timer#remove + */ + remove: function (event) { + + for (var i = 0; i < this.events.length; i++) + { + if (this.events[i] === event) + { + this.events[i].pendingDelete = true; + return true; + } + } + + return false; + + }, + + /** + * Orders the events on this Timer so they are in tick order. + * This is called automatically when new events are created. + * @method Phaser.Timer#order + * @protected + */ + order: function () { + + if (this.events.length > 0) + { + // Sort the events so the one with the lowest tick is first + this.events.sort(this.sortHandler); + + this.nextTick = this.events[0].tick; + } + + }, + + /** + * Sort handler used by Phaser.Timer.order. + * @method Phaser.Timer#sortHandler + * @private + */ + sortHandler: function (a, b) { + + if (a.tick < b.tick) + { + return -1; + } + else if (a.tick > b.tick) + { + return 1; + } + + return 0; + + }, + + /** + * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values. + * + * @method Phaser.Timer#clearPendingEvents + * @protected + */ + 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; + + }, + + /** + * The main Timer update event, called automatically by Phaser.Time.update. + * + * @method Phaser.Timer#update + * @protected + * @param {number} time - The time from the core game clock. + * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. + */ + update: function (time) { + + if (this.paused) + { + return true; + } + + this.elapsed = time - this._now; + this._now = time; + + // spike-dislike + if (this.elapsed > this.timeCap) + { + // For some reason the time between now and the last time the game was updated was larger than our timeCap. + // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause. + // In this case we need to adjust the TimerEvents and nextTick. + this.adjustEvents(time - this.elapsed); + } + + this._marked = 0; + + // Clears events marked for deletion and resets _len and _i to 0. + this.clearPendingEvents(); + + if (this.running && this._now >= this.nextTick && this._len > 0) + { + while (this._i < this._len && this.running) + { + var event = this.events[this._i]; + + if (this._now >= event.tick && !event.pendingDelete) + { + // (now + delay) - (time difference from last tick to now) + this._newTick = (this._now + event.delay) - (this._now - event.tick); + + if (this._newTick < 0) + { + this._newTick = this._now + event.delay; + } + + if (event.loop === true) + { + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else if (event.repeatCount > 0) + { + event.repeatCount--; + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else + { + this._marked++; + event.pendingDelete = true; + event.callback.apply(event.callbackContext, event.args); + } + + this._i++; + } + else + { + break; + } + } + + // Are there any events left? + 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; + } + + }, + + /** + * Pauses the Timer and all events in the queue. + * @method Phaser.Timer#pause + */ + pause: function () { + + if (!this.running) + { + return; + } + + this._codePaused = true; + + if (this.paused) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Internal pause/resume control - user code should use Timer.pause instead. + * @method Phaser.Timer#_pause + * @private + */ + _pause: function () { + + if (this.paused || !this.running) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Adjusts the time of all pending events and the nextTick by the given baseTime. + * + * @method Phaser.Timer#adjustEvents + * @protected + */ + adjustEvents: function (baseTime) { + + for (var i = 0; i < this.events.length; i++) + { + if (!this.events[i].pendingDelete) + { + // Work out how long there would have been from when the game paused until the events next tick + var t = this.events[i].tick - baseTime; + + if (t < 0) + { + t = 0; + } + + // Add the difference on to the time now + this.events[i].tick = this._now + t; + } + } + + var d = this.nextTick - baseTime; + + if (d < 0) + { + this.nextTick = this._now; + } + else + { + this.nextTick = this._now + d; + } + + }, + + /** + * Resumes the Timer and updates all pending events. + * + * @method Phaser.Timer#resume + */ + resume: function () { + + if (!this.paused) + { + return; + } + + var now = this.game.time.time; + this._pauseTotal += now - this._now; + this._now = now; + + this.adjustEvents(this._pauseStarted); + + this.paused = false; + this._codePaused = false; + + }, + + /** + * Internal pause/resume control - user code should use Timer.resume instead. + * @method Phaser.Timer#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#removeAll + */ + removeAll: function () { + + this.onComplete.removeAll(); + this.events.length = 0; + this._len = 0; + this._i = 0; + + }, + + /** + * Destroys this Timer. Any pending Events are not dispatched. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#destroy + */ + destroy: function () { + + this.onComplete.removeAll(); + this.running = false; + this.expired = true; + this.events = []; + this._len = 0; + this._i = 0; + + } + +}; + +/** +* @name Phaser.Timer#next +* @property {number} next - The time at which the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "next", { + + get: function () { + return this.nextTick; + } + +}); + +/** +* @name Phaser.Timer#duration +* @property {number} duration - The duration in ms remaining until the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "duration", { + + get: function () { + + if (this.running && this.nextTick > this._now) + { + return this.nextTick - this._now; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#length +* @property {number} length - The number of pending events in the queue. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "length", { + + get: function () { + return this.events.length; + } + +}); + +/** +* @name Phaser.Timer#ms +* @property {number} ms - The duration in milliseconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "ms", { + + get: function () { + + if (this.running) + { + return this._now - this._started - this._pauseTotal; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#seconds +* @property {number} seconds - The duration in seconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "seconds", { + + get: function () { + + if (this.running) + { + return this.ms * 0.001; + } + else + { + return 0; + } + + } + +}); + +Phaser.Timer.prototype.constructor = Phaser.Timer; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TimerEvent is a single event that is processed by a Phaser.Timer. +* +* It consists of a delay, which is a value in milliseconds after which the event will fire. +* When the event fires it calls a specific callback with the specified arguments. +* +* TimerEvents are removed by their parent timer once finished firing or repeating. +* +* Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. +* +* @class Phaser.TimerEvent +* @constructor +* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. +* @param {number} delay - The delay in ms at which this TimerEvent fires. +* @param {number} tick - The tick is the next game clock time that this event will fire at. +* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times. +* @param {boolean} loop - True if this TimerEvent loops, otherwise false. +* @param {function} callback - The callback that will be called when the TimerEvent occurs. +* @param {object} callbackContext - The context in which the callback will be called. +* @param {any[]} arguments - Additional arguments to be passed to the callback. +*/ +Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) { + + /** + * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. + * @protected + * @readonly + */ + this.timer = timer; + + /** + * @property {number} delay - The delay in ms at which this TimerEvent fires. + */ + this.delay = delay; + + /** + * @property {number} tick - The tick is the next game clock time that this event will fire at. + */ + this.tick = tick; + + /** + * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times. + */ + this.repeatCount = repeatCount - 1; + + /** + * @property {boolean} loop - True if this TimerEvent loops, otherwise false. + */ + this.loop = loop; + + /** + * @property {function} callback - The callback that will be called when the TimerEvent occurs. + */ + this.callback = callback; + + /** + * @property {object} callbackContext - The context in which the callback will be called. + */ + this.callbackContext = callbackContext; + + /** + * @property {any[]} arguments - Additional arguments to be passed to the callback. + */ + this.args = args; + + /** + * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion. + * @protected + */ + this.pendingDelete = false; + +}; + +Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Manager is used to add, play and update Phaser Animations. +* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. +* +* @class Phaser.AnimationManager +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. +*/ +Phaser.AnimationManager = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = sprite.game; + + /** + * The currently displayed Frame of animation, if any. + * This property is only set once an Animation starts playing. Until that point it remains set as `null`. + * + * @property {Phaser.Frame} currentFrame + * @default + */ + this.currentFrame = null; + + /** + * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any. + * @default + */ + this.currentAnim = null; + + /** + * @property {boolean} updateIfVisible - Update the animation data only while the the sprite is {@link Phaser.Sprite#visible}. Set to `false` to continue updating while the sprite is invisible. + * @default + */ + this.updateIfVisible = true; + + /** + * @property {boolean} isLoaded - Set to true once animation data has been loaded. + * @default + */ + this.isLoaded = false; + + /** + * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. + * @private + * @default + */ + this._frameData = null; + + /** + * @property {object} _anims - An internal object that stores all of the Animation instances. + * @private + */ + this._anims = {}; + + /** + * @property {object} _outputFrames - An internal object to help avoid gc. + * @private + */ + this._outputFrames = []; + +}; + +Phaser.AnimationManager.prototype = { + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#loadFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + loadFrameData: function (frameData, frame) { + + if (frameData === undefined) + { + return false; + } + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(frameData); + } + } + + this._frameData = frameData; + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#copyFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + copyFrameData: function (frameData, frame) { + + this._frameData = frameData.clone(); + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(this._frameData); + } + } + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. + * Animations added in this way are played back with the play function. + * + * @method Phaser.AnimationManager#add + * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". + * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. + * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. + * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? + * @return {Phaser.Animation} The Animation object that was created. + */ + add: function (name, frames, frameRate, loop, useNumericIndex) { + + frames = frames || []; + frameRate = frameRate || 60; + + if (loop === undefined) { loop = false; } + + // If they didn't set the useNumericIndex then let's at least try and guess it + if (useNumericIndex === undefined) + { + if (frames && typeof frames[0] === 'number') + { + useNumericIndex = true; + } + else + { + useNumericIndex = false; + } + } + + this._outputFrames = []; + + 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]; + + if (this.sprite.tilingTexture) + { + this.sprite.refreshTexture = true; + } + + return this._anims[name]; + + }, + + /** + * Check whether the frames in the given array are valid and exist. + * + * @method Phaser.AnimationManager#validateFrames + * @param {Array} frames - An array of frames to be validated. + * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) + * @return {boolean} True if all given Frames are valid, otherwise false. + */ + validateFrames: function (frames, useNumericIndex) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + + for (var i = 0; i < frames.length; i++) + { + if (useNumericIndex === true) + { + if (frames[i] > this._frameData.total) + { + return false; + } + } + else + { + if (this._frameData.checkFrameName(frames[i]) === false) + { + return false; + } + } + } + + return true; + + }, + + /** + * Play an animation based on the given key. The animation should previously have been added via `animations.add` + * + * If the requested animation is already playing this request will be ignored. + * If you need to reset an already running animation do so directly on the Animation object itself. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.AnimationManager#play + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation instance. + */ + 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); + } + + return this.currentAnim; + } + else + { + if (this.currentAnim && this.currentAnim.isPlaying) + { + this.currentAnim.stop(); + } + + this.currentAnim = this._anims[name]; + this.currentAnim.paused = false; + this.currentFrame = this.currentAnim.currentFrame; + return this.currentAnim.play(frameRate, loop, killOnComplete); + } + } + + }, + + /** + * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. + * The currentAnim property of the AnimationManager is automatically set to the animation given. + * + * @method Phaser.AnimationManager#stop + * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. + * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) + */ + stop: function (name, resetFrame) { + + if (resetFrame === undefined) { resetFrame = false; } + + if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name)) + { + this.currentAnim.stop(resetFrame); + } + + }, + + /** + * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. + * + * @method Phaser.AnimationManager#update + * @protected + * @return {boolean} True if a new animation frame has been set, otherwise false. + */ + update: function () { + + if (this.updateIfVisible && !this.sprite.visible) + { + return false; + } + + if (this.currentAnim && this.currentAnim.update()) + { + this.currentFrame = this.currentAnim.currentFrame; + return true; + } + + return false; + + }, + + /** + * Advances by the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.next(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Moves backwards the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.previous(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Returns an animation that was previously added by name. + * + * @method Phaser.AnimationManager#getAnimation + * @param {string} name - The name of the animation to be returned, e.g. "fire". + * @return {Phaser.Animation} The Animation instance, if found, otherwise null. + */ + getAnimation: function (name) { + + if (typeof name === 'string') + { + if (this._anims[name]) + { + return this._anims[name]; + } + } + + return null; + + }, + + /** + * Refreshes the current frame data back to the parent Sprite and also resets the texture data. + * + * @method Phaser.AnimationManager#refreshFrame + */ + refreshFrame: function () { + + // TODO + // this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); + + }, + + /** + * Destroys all references this AnimationManager contains. + * Iterates through the list of animations stored in this manager and calls destroy on each of them. + * + * @method Phaser.AnimationManager#destroy + */ + destroy: function () { + + var anim = null; + + for (var anim in this._anims) + { + if (this._anims.hasOwnProperty(anim)) + { + this._anims[anim].destroy(); + } + } + + this._anims = {}; + this._outputFrames = []; + this._frameData = null; + this.currentAnim = null; + this.currentFrame = null; + this.sprite = null; + this.game = null; + + } + +}; + +Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager; + +/** +* @name Phaser.AnimationManager#frameData +* @property {Phaser.FrameData} frameData - The current animations FrameData. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', { + + get: function () { + return this._frameData; + } + +}); + +/** +* @name Phaser.AnimationManager#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', { + + get: function () { + + return this._frameData.total; + } + +}); + +/** +* @name Phaser.AnimationManager#paused +* @property {boolean} paused - Gets and sets the paused state of the current animation. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', { + + get: function () { + + return this.currentAnim.isPaused; + + }, + + set: function (value) { + + this.currentAnim.paused = value; + + } + +}); + +/** +* @name Phaser.AnimationManager#name +* @property {string} name - Gets the current animation name, if set. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'name', { + + get: function () { + + if (this.currentAnim) + { + return this.currentAnim.name; + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.index; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'number' && this._frameData && (gotFrame = this._frameData.getFrame(value))) + { + this.currentFrame = gotFrame; + this.sprite.setFrame(this.currentFrame); + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frameName +* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.name; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'string' && this._frameData && (gotFrame = this._frameData.getFrameByName(value))) + { + this.currentFrame = gotFrame; + this._frameIndex = this.currentFrame.index; + this.sprite.setFrame(this.currentFrame); + } + else + { + console.warn('Cannot set frameName: ' + value); + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Animation instance contains a single animation and the controls to play it. +* +* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. +* +* @class Phaser.Animation +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Sprite} parent - A reference to the owner of this Animation. +* @param {string} name - The unique name for this animation, used in playback commands. +* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. +* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +*/ +Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) { + + if (loop === undefined) { loop = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. + * @private + */ + this._parent = parent; + + /** + * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. + * @private + */ + this._frameData = frameData; + + /** + * @property {string} name - The user defined name given to this Animation. + */ + this.name = name; + + /** + * @property {array} _frames + * @private + */ + this._frames = []; + this._frames = this._frames.concat(frames); + + /** + * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. + */ + this.delay = 1000 / frameRate; + + /** + * @property {boolean} loop - The loop state of the Animation. + */ + this.loop = loop; + + /** + * @property {number} loopCount - The number of times the animation has looped since it was last started. + */ + this.loopCount = 0; + + /** + * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? + * @default + */ + this.killOnComplete = false; + + /** + * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. + * @default + */ + this.isFinished = false; + + /** + * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. + * @default + */ + this.isPlaying = false; + + /** + * @property {boolean} isPaused - The paused state of the Animation. + * @default + */ + this.isPaused = false; + + /** + * @property {boolean} _pauseStartTime - The time the animation paused. + * @private + * @default + */ + this._pauseStartTime = 0; + + /** + * @property {number} _frameIndex + * @private + * @default + */ + this._frameIndex = 0; + + /** + * @property {number} _frameDiff + * @private + * @default + */ + this._frameDiff = 0; + + /** + * @property {number} _frameSkip + * @private + * @default + */ + this._frameSkip = 1; + + /** + * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. + */ + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + /** + * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. + */ + this.onStart = new Phaser.Signal(); + + /** + * This event is dispatched when the Animation changes frame. + * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. + * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations + * will automatically frame-skip to try and claw back time, so do not base your code on expecting to + * receive a perfectly sequential set of frames from this event. + * @property {Phaser.Signal|null} onUpdate + * @default + */ + this.onUpdate = null; + + /** + * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {boolean} isReversed - Indicates if the animation will play backwards. + * @default + */ + this.isReversed = false; + + // Set-up some event listeners + this.game.onPause.add(this.onPause, this); + this.game.onResume.add(this.onResume, this); + +}; + +Phaser.Animation.prototype = { + + /** + * Plays this animation. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.Animation#play + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} - A reference to this Animation instance. + */ + play: function (frameRate, loop, killOnComplete) { + + if (typeof frameRate === 'number') + { + // If they set a new frame rate then use it, otherwise use the one set on creation + this.delay = 1000 / frameRate; + } + + if (typeof loop === 'boolean') + { + // If they set a new loop value then use it, otherwise use the one set on creation + this.loop = loop; + } + + if (typeof killOnComplete !== 'undefined') + { + // Remove the parent sprite once the animation has finished? + this.killOnComplete = killOnComplete; + } + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = this.isReversed ? this._frames.length - 1 : 0; + this.updateCurrentFrame(false, true); + + this._parent.events.onAnimationStart$dispatch(this._parent, this); + + this.onStart.dispatch(this._parent, this); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + return this; + + }, + + /** + * Sets this animation back to the first frame and restarts the animation. + * + * @method Phaser.Animation#restart + */ + restart: function () { + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = 0; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + this._parent.setFrame(this.currentFrame); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + this.onStart.dispatch(this._parent, this); + + }, + + /** + * Reverses the animation direction. + * + * @method Phaser.Animation#reverse + * @return {Phaser.Animation} The animation instance. + */ + reverse: function () { + + this.reversed = !this.reversed; + + return this; + + }, + + /** + * Reverses the animation direction for the current/next animation only + * Once the onComplete event is called this method will be called again and revert + * the reversed state. + * + * @method Phaser.Animation#reverseOnce + * @return {Phaser.Animation} The animation instance. + */ + reverseOnce: function () { + + this.onComplete.addOnce(this.reverse, this); + + return this.reverse(); + + }, + + /** + * Sets this animations playback to a given frame with the given ID. + * + * @method Phaser.Animation#setFrame + * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. + * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. + */ + setFrame: function(frameId, useLocalFrameIndex) { + + var frameIndex; + + if (useLocalFrameIndex === undefined) + { + useLocalFrameIndex = false; + } + + // Find the index to the desired frame. + if (typeof frameId === "string") + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frameData.getFrame(this._frames[i]).name === frameId) + { + frameIndex = i; + } + } + } + else if (typeof frameId === "number") + { + if (useLocalFrameIndex) + { + frameIndex = frameId; + } + else + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frames[i] === frameId) + { + frameIndex = i; + } + } + } + } + + if (frameIndex) + { + // Set the current frame index to the found index. Subtract a directional offset so that it animates to the desired frame on update. + var directionalOffset = this.isReversed ? -1 : 1; + this._frameIndex = frameIndex - directionalOffset; + + // Make the animation update at next update + this._timeNextFrame = this.game.time.time; + + this.update(); + } + + }, + + /** + * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. + * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. + * + * @method Phaser.Animation#stop + * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. + * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? + */ + stop: function (resetFrame, dispatchComplete) { + + if (resetFrame === undefined) { resetFrame = false; } + if (dispatchComplete === undefined) { dispatchComplete = false; } + + this.isPlaying = false; + this.isFinished = true; + this.paused = false; + + if (resetFrame) + { + this.currentFrame = this._frameData.getFrame(this._frames[0]); + this._parent.setFrame(this.currentFrame); + } + + if (dispatchComplete) + { + this._parent.events.onAnimationComplete$dispatch(this._parent, this); + this.onComplete.dispatch(this._parent, this); + } + + }, + + /** + * Called when the Game enters a paused state. + * + * @method Phaser.Animation#onPause + */ + onPause: function () { + + if (this.isPlaying) + { + this._frameDiff = this._timeNextFrame - this.game.time.time; + } + + }, + + /** + * Called when the Game resumes from a paused state. + * + * @method Phaser.Animation#onResume + */ + onResume: function () { + + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this._frameDiff; + } + + }, + + /** + * Updates this animation. Called automatically by the AnimationManager. + * + * @method Phaser.Animation#update + */ + update: function () { + + if (this.isPaused) + { + return false; + } + + if (this.isPlaying && this.game.time.time >= this._timeNextFrame) + { + this._frameSkip = 1; + + // Lagging? + this._frameDiff = this.game.time.time - this._timeNextFrame; + + this._timeLastFrame = this.game.time.time; + + if (this._frameDiff > this.delay) + { + // We need to skip a frame, work out how many + this._frameSkip = Math.floor(this._frameDiff / this.delay); + this._frameDiff -= (this._frameSkip * this.delay); + } + else + { + this._frameDiff = 0; + } + + // And what's left now? + this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff); + + if (this.isReversed) + { + this._frameIndex -= this._frameSkip; + } + else + { + this._frameIndex += this._frameSkip; + } + + if (!this.isReversed && this._frameIndex >= this._frames.length || this.isReversed && this._frameIndex <= -1) + { + if (this.loop) + { + // Update current state before event callback + this._frameIndex = Math.abs(this._frameIndex) % this._frames.length; + + if (this.isReversed) + { + this._frameIndex = this._frames.length - 1 - this._frameIndex; + } + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + // Instead of calling updateCurrentFrame we do it here instead + if (this.currentFrame) + { + this._parent.setFrame(this.currentFrame); + } + + this.loopCount++; + this._parent.events.onAnimationLoop$dispatch(this._parent, this); + this.onLoop.dispatch(this._parent, this); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + } + else + { + this.complete(); + return false; + } + } + else + { + return this.updateCurrentFrame(true); + } + } + + return false; + + }, + + /** + * Changes the currentFrame per the _frameIndex, updates the display state, + * and triggers the update signal. + * + * Returns true if the current frame update was 'successful', false otherwise. + * + * @method Phaser.Animation#updateCurrentFrame + * @private + * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. + * @param {boolean} fromPlay - Was this call made from the playing of a new animation? + * @return {boolean} True if the current frame was updated, otherwise false. + */ + updateCurrentFrame: function (signalUpdate, fromPlay) { + + if (fromPlay === undefined) { fromPlay = false; } + + if (!this._frameData) + { + // The animation is already destroyed, probably from a callback + return false; + } + + // Previous index + var idx = this.currentFrame.index; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index))) + { + this._parent.setFrame(this.currentFrame); + } + + if (this.onUpdate && signalUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + + }, + + /** + * Advances by the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex + quantity; + + if (frame >= this._frames.length) + { + if (this.loop) + { + frame %= this._frames.length; + } + else + { + frame = this._frames.length - 1; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex - quantity; + + if (frame < 0) + { + if (this.loop) + { + frame = this._frames.length + frame; + } + else + { + frame++; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Changes the FrameData object this Animation is using. + * + * @method Phaser.Animation#updateFrameData + * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. + */ + updateFrameData: function (frameData) { + + this._frameData = frameData; + this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null; + + }, + + /** + * Cleans up this animation ready for deletion. Nulls all values and references. + * + * @method Phaser.Animation#destroy + */ + destroy: function () { + + if (!this._frameData) + { + // Already destroyed + return; + } + + 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(); + + if (this.onUpdate) + { + this.onUpdate.dispose(); + } + + }, + + /** + * Called internally when the animation finishes playback. + * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. + * + * @method Phaser.Animation#complete + */ + complete: function () { + + this._frameIndex = this._frames.length - 1; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + 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; + +/** +* @name Phaser.Animation#paused +* @property {boolean} paused - Gets and sets the paused state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'paused', { + + get: function () { + + return this.isPaused; + + }, + + set: function (value) { + + this.isPaused = value; + + if (value) + { + // Paused + this._pauseStartTime = this.game.time.time; + } + else + { + // Un-paused + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this.delay; + } + } + + } + +}); + +/** +* @name Phaser.Animation#reversed +* @property {boolean} reversed - Gets and sets the isReversed state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'reversed', { + + get: function () { + + return this.isReversed; + + }, + + set: function (value) { + + this.isReversed = value; + + } + +}); + +/** +* @name Phaser.Animation#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @name Phaser.Animation#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +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.setFrame(this.currentFrame); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + } + } + + } + +}); + +/** +* @name Phaser.Animation#speed +* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'speed', { + + get: function () { + + return 1000 / this.delay; + + }, + + set: function (value) { + + if (value > 0) + { + this.delay = 1000 / value; + } + + } + +}); + +/** +* @name Phaser.Animation#enableUpdate +* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { + + get: function () { + + return (this.onUpdate !== null); + + }, + + set: function (value) { + + if (value && this.onUpdate === null) + { + this.onUpdate = new Phaser.Signal(); + } + else if (!value && this.onUpdate !== null) + { + this.onUpdate.dispose(); + this.onUpdate = null; + } + + } + +}); + +/** +* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. +* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' +* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); +* +* @method Phaser.Animation.generateFrameNames +* @static +* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. +* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. +* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. +* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'. +* @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. +* @return {string[]} An array of framenames. +*/ +Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { + + if (suffix === undefined) { suffix = ''; } + + var output = []; + var frame = ''; + + if (start < stop) + { + for (var i = start; i <= stop; i++) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + else + { + for (var i = start; i >= stop; i--) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + + return output; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Frame is a single frame of an animation and is part of a FrameData collection. +* +* @class Phaser.Frame +* @constructor +* @param {number} index - The index of this Frame within the FrameData set it is being added to. +* @param {number} x - X position of the frame within the texture image. +* @param {number} y - Y position of the frame within the texture image. +* @param {number} width - Width of the frame within the texture image. +* @param {number} height - Height of the frame within the texture image. +* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. +*/ +Phaser.Frame = function (index, x, y, width, height, name) { + + /** + * @property {number} index - The index of this Frame within the FrameData set it is being added to. + */ + this.index = index; + + /** + * @property {number} x - X position within the image to cut from. + */ + this.x = x; + + /** + * @property {number} y - Y position within the image to cut from. + */ + this.y = y; + + /** + * @property {number} width - Width of the frame. + */ + this.width = width; + + /** + * @property {number} height - Height of the frame. + */ + this.height = height; + + if (this.width === 0 || this.height === 0) + { + console.warn('Phaser.Frame: Frame "' + this.name + '" has a width or height of zero'); + } + + /** + * @property {string} name - Useful for Texture Atlas files (is set to the filename value). + */ + this.name = name; + + /** + * @property {number} centerX - Center X position within the image to cut from. + */ + this.centerX = Math.floor(width / 2); + + /** + * @property {number} centerY - Center Y position within the image to cut from. + */ + this.centerY = Math.floor(height / 2); + + /** + * @property {number} distance - The distance from the top left to the bottom-right of this Frame. + */ + this.distance = Phaser.Math.distance(0, 0, width, height); + + /** + * @property {boolean} rotated - Is the frame rotated in the source texture? + * @default + */ + this.rotated = false; + + /** + * @property {boolean} trimmed - Was it trimmed when packed? + * @default + */ + this.trimmed = false; + + /** + * @property {number} sourceSizeW - Width of the original sprite before it was trimmed. + */ + this.sourceSizeW = width; + + /** + * @property {number} sourceSizeH - Height of the original sprite before it was trimmed. + */ + this.sourceSizeH = height; + + /** + * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeX = 0; + + /** + * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeY = 0; + + /** + * @property {number} spriteSourceSizeW - Width of the trimmed sprite. + * @default + */ + this.spriteSourceSizeW = 0; + + /** + * @property {number} spriteSourceSizeH - Height of the trimmed sprite. + * @default + */ + this.spriteSourceSizeH = 0; + + /** + * @property {number} right - The right of the Frame (x + width). + */ + this.right = this.x + this.width; + + /** + * @property {number} bottom - The bottom of the frame (y + height). + */ + this.bottom = this.y + this.height; + +}; + +Phaser.Frame.prototype = { + + /** + * Adjusts of all the Frame properties based on the given width and height values. + * + * @method Phaser.Frame#resize + * @param {integer} width - The new width of the Frame. + * @param {integer} height - The new height of the Frame. + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + this.centerX = Math.floor(width / 2); + this.centerY = Math.floor(height / 2); + this.distance = Phaser.Math.distance(0, 0, width, height); + this.sourceSizeW = width; + this.sourceSizeH = height; + this.right = this.x + width; + this.bottom = this.y + height; + + }, + + /** + * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. + * + * @method Phaser.Frame#setTrim + * @param {boolean} trimmed - If this frame was trimmed or not. + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + */ + setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { + + this.trimmed = trimmed; + + if (trimmed) + { + 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; + } + + }, + + /** + * Clones this Frame into a new Phaser.Frame object and returns it. + * Note that all properties are cloned, including the name and index. + * + * @method Phaser.Frame#clone + * @return {Phaser.Frame} An exact copy of this Frame object. + */ + clone: function () { + + var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name); + + for (var prop in this) + { + if (this.hasOwnProperty(prop)) + { + output[prop] = this[prop]; + } + } + + return output; + + }, + + /** + * Returns a Rectangle set to the dimensions of this Frame. + * + * @method Phaser.Frame#getRect + * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to. + * @return {Phaser.Rectangle} A rectangle. + */ + getRect: function (out) { + + if (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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. +* +* @class Phaser.FrameData +* @constructor +*/ +Phaser.FrameData = function () { + + /** + * @property {Array} _frames - Local array of frames. + * @private + */ + this._frames = []; + + /** + * @property {Array} _frameNames - Local array of frame names for name to index conversions. + * @private + */ + this._frameNames = []; + +}; + +Phaser.FrameData.prototype = { + + /** + * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. + * + * @method Phaser.FrameData#addFrame + * @param {Phaser.Frame} frame - The frame to add to this FrameData set. + * @return {Phaser.Frame} The frame that was just added. + */ + addFrame: function (frame) { + + frame.index = this._frames.length; + + this._frames.push(frame); + + if (frame.name !== '') + { + this._frameNames[frame.name] = frame.index; + } + + return frame; + + }, + + /** + * Get a Frame by its numerical index. + * + * @method Phaser.FrameData#getFrame + * @param {number} index - The index of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or undefined. + */ + getFrame: function (index) { + + if (index >= this._frames.length) + { + index = 0; + } + + return this._frames[index]; + + }, + + /** + * Get a Frame by its frame name. + * + * @method Phaser.FrameData#getFrameByName + * @param {string} name - The name of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or null. + */ + getFrameByName: function (name) { + + if (typeof this._frameNames[name] === 'number') + { + return this._frames[this._frameNames[name]]; + } + + return null; + + }, + + /** + * Check if there is a Frame with the given name. + * + * @method Phaser.FrameData#checkFrameName + * @param {string} name - The name of the frame you want to check. + * @return {boolean} True if the frame is found, otherwise false. + */ + checkFrameName: function (name) { + + if (this._frameNames[name] == null) + { + return false; + } + + return true; + + }, + + /** + * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains. + * + * @method Phaser.FrameData#clone + * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains. + */ + clone: function () { + + var output = new Phaser.FrameData(); + + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output._frames.push(this._frames[i].clone()); + } + + for (var p in this._frameNames) + { + if (this._frameNames.hasOwnProperty(p)) + { + output._frameNames.push(this._frameNames[p]); + } + } + + return output; + + }, + + /** + * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. + * + * @method Phaser.FrameData#getFrameRange + * @param {number} start - The starting frame index. + * @param {number} end - The ending frame index. + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. + */ + getFrameRange: function (start, end, output) { + + if (output === undefined) { output = []; } + + for (var i = start; i <= end; i++) + { + output.push(this._frames[i]); + } + + return output; + + }, + + /** + * Returns all of the Frames in this FrameData set where the frame index is found in the input array. + * The frames are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrames + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. + */ + getFrames: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + // We only need the indexes + output.push(this._frames[i]); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the input array contain names or indexes? + if (useNumericIndex) + { + // The actual frame + output.push(this.getFrame(frames[i])); + } + else + { + // The actual frame + output.push(this.getFrameByName(frames[i])); + } + } + } + + return output; + + }, + + /** + * Returns all of the Frame indexes in this FrameData set. + * The frames indexes are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrameIndexes + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frame indexes matching the given names or IDs. + */ + getFrameIndexes: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No frames array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output.push(this._frames[i].index); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the frames array contain names or indexes? + if (useNumericIndex && this._frames[frames[i]]) + { + output.push(this._frames[frames[i]].index); + } + else + { + if (this.getFrameByName(frames[i])) + { + output.push(this.getFrameByName(frames[i]).index); + } + } + } + } + + return output; + + }, + + /** + * Destroys this FrameData collection by nulling the _frames and _frameNames arrays. + * + * @method Phaser.FrameData#destroy + */ + destroy: function () { + + this._frames = null; + this._frameNames = null; + + } + +}; + +Phaser.FrameData.prototype.constructor = Phaser.FrameData; + +/** +* @name Phaser.FrameData#total +* @property {number} total - The total number of frames in this FrameData set. +* @readonly +*/ +Object.defineProperty(Phaser.FrameData.prototype, "total", { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +* +* @class Phaser.AnimationParser +* @static +*/ +Phaser.AnimationParser = { + + /** + * Parse a Sprite Sheet and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.spriteSheet + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. + * @param {number} frameWidth - The fixed width of each frame of the animation. + * @param {number} frameHeight - The fixed height of each frame of the animation. + * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + var img = key; + + if (typeof key === 'string') + { + img = game.cache.getImage(key); + } + + if (img === null) + { + return null; + } + + var width = img.width; + var height = img.height; + + if (frameWidth <= 0) + { + frameWidth = Math.floor(-width / Math.min(-1, frameWidth)); + } + + if (frameHeight <= 0) + { + frameHeight = Math.floor(-height / Math.min(-1, frameHeight)); + } + + var row = Math.floor((width - margin) / (frameWidth + spacing)); + var column = Math.floor((height - margin) / (frameHeight + spacing)); + var total = row * column; + + if (skipFrames > total || skipFrames < -total) + { + console.warn( + "Phaser.AnimationParser.spriteSheet: skipFrames = " + + skipFrames.toString() + " is larger than total sprite number " + + total.toString()); + return null; + } + + if (skipFrames < 0) + { + // Allow negative skipframes. + skipFrames = total + skipFrames; + } + + if (frameMax !== -1) + { + total = skipFrames + frameMax; + } + + // Zero or smaller than frame sizes? + if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0) + { + console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight"); + return null; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var x = margin; + var y = margin; + + for (var i = 0; i < total; i++) + { + data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '')); + + x += frameWidth + spacing; + + if (x + frameWidth > width) + { + x = margin; + y += frameHeight + spacing; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONData: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].frame.x, + frames[i].frame.y, + frames[i].frame.w, + frames[i].frame.h, + frames[i].filename + )); + + if (frames[i].trimmed) + { + newFrame.setTrim( + frames[i].trimmed, + frames[i].sourceSize.w, + frames[i].sourceSize.h, + frames[i].spriteSourceSize.x, + frames[i].spriteSourceSize.y, + frames[i].spriteSourceSize.w, + frames[i].spriteSourceSize.h + ); + } + + if (frames[i].rotated) + { + newFrame.rotated = true; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataPyxel + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataPyxel: function (game, json) { + + // Malformed? There are a few keys to check here. + var signature = ['layers', 'tilewidth','tileheight','tileswide', 'tileshigh']; + + signature.forEach( function(key) { + if (!json[key]) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "' + key + '" key.'); + console.log(json); + return; + } + }); + + // For this purpose, I only care about parsing tilemaps with a single layer. + if (json['layers'].length !== 1) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps.'); + console.log(json); + return; + } + + var data = new Phaser.FrameData(); + + var tileheight = json['tileheight']; + var tilewidth = json['tilewidth']; + + var frames = json['layers'][0]['tiles']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].x, + frames[i].y, + tilewidth, + tileheight, + "frame_" + i // No names are included in pyxel tilemap data. + )); + + // No trim data is included. + newFrame.setTrim(false); + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataHash + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataHash: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + var i = 0; + + for (var key in frames) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[key].frame.x, + frames[key].frame.y, + frames[key].frame.w, + frames[key].frame.h, + key + )); + + if (frames[key].trimmed) + { + newFrame.setTrim( + frames[key].trimmed, + frames[key].sourceSize.w, + frames[key].sourceSize.h, + frames[key].spriteSourceSize.x, + frames[key].spriteSourceSize.y, + frames[key].spriteSourceSize.w, + frames[key].spriteSourceSize.h + ); + } + + if (frames[key].rotated) + { + newFrame.rotated = true; + } + + i++; + } + + return data; + + }, + + /** + * Parse the XML data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.XMLData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + XMLData: function (game, xml) { + + // Malformed? + if (!xml.getElementsByTagName('TextureAtlas')) + { + console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing tag"); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var frames = xml.getElementsByTagName('SubTexture'); + var newFrame; + + var name; + var frame; + var x; + var y; + var width; + var height; + var frameX; + var frameY; + var frameWidth; + var frameHeight; + + for (var i = 0; i < frames.length; i++) + { + frame = frames[i].attributes; + + name = frame.name.value; + x = parseInt(frame.x.value, 10); + y = parseInt(frame.y.value, 10); + width = parseInt(frame.width.value, 10); + height = parseInt(frame.height.value, 10); + + frameX = null; + frameY = null; + + if (frame.frameX) + { + frameX = Math.abs(parseInt(frame.frameX.value, 10)); + frameY = Math.abs(parseInt(frame.frameY.value, 10)); + frameWidth = parseInt(frame.frameWidth.value, 10); + frameHeight = parseInt(frame.frameHeight.value, 10); + } + + newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name)); + + // Trimmed? + if (frameX !== null || frameY !== null) + { + newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight); + } + } + + return data; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser has one single cache in which it stores all assets. +* +* The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using +* a unique string-based key as their identifier. Assets stored in different areas of the cache can have the +* same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, +* because they are unique data types. +* +* The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets +* such as images they are automatically placed into their respective cache. Most common Game Objects, such as +* Sprites and Videos automatically query the cache to extract the assets they need on instantiation. +* +* You can access the cache from within a State via `this.cache`. From here you can call any public method it has, +* including adding new entries to it, deleting them or querying them. +* +* Understand that almost without exception when you get an item from the cache it will return a reference to the +* item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original +* object in the cache will also be updated, even if you don't put it back into the cache again. +* +* By default when you change State the cache is _not_ cleared, although there is an option to clear it should +* your game require it. In a typical game set-up the cache is populated once after the main game has loaded and +* then used as an asset store. +* +* @class Phaser.Cache +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Cache = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. + * @property {boolean} autoResolveURL + */ + this.autoResolveURL = false; + + /** + * The main cache object into which all resources are placed. + * @property {object} _cache + * @private + */ + this._cache = { + canvas: {}, + image: {}, + texture: {}, + sound: {}, + video: {}, + text: {}, + json: {}, + xml: {}, + physics: {}, + tilemap: {}, + binary: {}, + bitmapData: {}, + bitmapFont: {}, + shader: {}, + renderTexture: {}, + compressedTexture: {} + }; + + /** + * @property {object} _urlMap - Maps URLs to resources. + * @private + */ + this._urlMap = {}; + + /** + * @property {Image} _urlResolver - Used to resolve URLs to the absolute path. + * @private + */ + this._urlResolver = new Image(); + + /** + * @property {string} _urlTemp - Temporary variable to hold a resolved url. + * @private + */ + this._urlTemp = null; + + /** + * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices. + */ + this.onSoundUnlock = new Phaser.Signal(); + + /** + * @property {array} _cacheMap - Const to cache object look-up array. + * @private + */ + this._cacheMap = []; + + this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas; + this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image; + this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture; + this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound; + this._cacheMap[Phaser.Cache.TEXT] = this._cache.text; + this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics; + this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap; + this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary; + this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData; + this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont; + this._cacheMap[Phaser.Cache.JSON] = this._cache.json; + this._cacheMap[Phaser.Cache.XML] = this._cache.xml; + this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video; + this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader; + this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture; + + /** + * @property {number} + * @private + */ + this._pendingCount = 0; + + /** + * Dispatched when the DEFAULT and MISSING images have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). + * + * @property {Phaser.Signal} onReady + */ + this.onReady = new Phaser.Signal(); + + this._addImages(); + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.CANVAS = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.IMAGE = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXTURE = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SOUND = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXT = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.PHYSICS = 6; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TILEMAP = 7; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BINARY = 8; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPDATA = 9; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPFONT = 10; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.JSON = 11; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.XML = 12; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.VIDEO = 13; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SHADER = 14; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.RENDER_TEXTURE = 15; + +/** +* The default image used for a texture when no other is specified. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.DEFAULT = null; + +/** + * Key for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_KEY = '__default'; + +/** + * URL for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='; + +/** +* The default image used for a texture when the source image is missing. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.MISSING = null; + +/** + * Key for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_KEY = '__missing'; + +/** + * URL for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='; + +/** +* The maximum amount of time (ms) to wait for the built-in DEFAULT and MISSING images to load. +* @static +* @type {number} +* @default +*/ +Phaser.Cache.READY_TIMEOUT = 1000; + +Phaser.Cache.prototype = { + + ////////////////// + // Add Methods // + ////////////////// + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCompressedTextureMetaData + * @private + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url + * @param {string} extension + * @param {array} arrayBuffer + * @return {object} The compressed texture entry. + */ + addCompressedTextureMetaData: function (key, url, extension, arrayBuffer) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + var data = (extension in Phaser.LoaderParser) ? Phaser.LoaderParser[extension](arrayBuffer) : arrayBuffer; + + var texture = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData(), + fileFormat: extension + }; + + texture.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = texture; + + this._resolveURL(url, texture); + + return texture; + + }, + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCanvas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {HTMLCanvasElement} canvas - The Canvas DOM element. + * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`. + */ + addCanvas: function (key, canvas, context) { + + if (context === undefined) { context = canvas.getContext('2d'); } + + this._cache.canvas[key] = { canvas: canvas, context: context }; + + }, + + /** + * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. + * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. + * + * If the image has not yet been fetched (successfully or not), a `console.warn` message will be displayed. + * + * @method Phaser.Cache#addImage + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra image data. + * @return {object} The full image object that was added to the cache. + */ + addImage: function (key, url, data) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + if (data.complete === false) + { + console.warn('Phaser.Cache.addImage: Image "' + key + '" hasn\'t been retrieved yet'); + } + + var img = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData() + }; + + img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = img; + + this._resolveURL(url, img); + + if (key === '__default') + { + Phaser.Cache.DEFAULT = new PIXI.Texture(img.base); + } + else if (key === '__missing') + { + Phaser.Cache.MISSING = new PIXI.Texture(img.base); + } + + return img; + + }, + + /** + * @method Phaser.Cache#addImageAsync + * @private + */ + addImageAsync: function (key, src, callback) { + + var self = this; + var img = new Image(); + + img.onload = function () { + callback.call(this, self.addImage(key, null, img)); + self._removePending(); + img.onload = null; + }; + + this._addPending(); + img.src = src; + + }, + + /** + * Adds a default image to be used in special cases such as WebGL Filters. + * It uses the special reserved key of `__default`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addDefaultImage + * @protected + */ + addDefaultImage: function () { + + this.addImageAsync(Phaser.Cache.DEFAULT_KEY, Phaser.Cache.DEFAULT_SRC, function (obj) { + // Because we don't want to invalidate the sprite batch for an invisible texture + obj.base.skipRender = true; + + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.DEFAULT = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds an image to be used when a key is wrong / missing. + * It uses the special reserved key of `__missing`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addMissingImage + * @protected + */ + addMissingImage: function () { + + this.addImageAsync(Phaser.Cache.MISSING_KEY, Phaser.Cache.MISSING_SRC, function (obj) { + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.MISSING = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addSound + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sound data. + * @param {boolean} webAudio - True if the file is using web audio. + * @param {boolean} audioTag - True if the file is using legacy HTML audio. + */ + addSound: function (key, url, data, webAudio, audioTag) { + + if (webAudio === undefined) { webAudio = true; audioTag = false; } + if (audioTag === undefined) { webAudio = false; audioTag = true; } + + var decoded = false; + + if (audioTag) + { + decoded = true; + } + + this._cache.sound[key] = { + url: url, + data: data, + isDecoding: false, + decoded: decoded, + webAudio: webAudio, + audioTag: audioTag, + locked: this.game.sound.touchLocked + }; + + this._resolveURL(url, this._cache.sound[key]); + + }, + + /** + * Add a new text data. + * + * @method Phaser.Cache#addText + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addText: function (key, url, data) { + + this._cache.text[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.text[key]); + + }, + + /** + * Add a new physics data object to the Cache. + * + * @method Phaser.Cache#addPhysicsData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} JSONData - The physics data object (a JSON file). + * @param {number} format - The format of the physics data. + */ + addPhysicsData: function (key, url, JSONData, format) { + + this._cache.physics[key] = { url: url, data: JSONData, format: format }; + + this._resolveURL(url, this._cache.physics[key]); + + }, + + /** + * Add a new tilemap to the Cache. + * + * @method Phaser.Cache#addTilemap + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} mapData - The tilemap data object (either a CSV or JSON file). + * @param {number} format - The format of the tilemap data. + */ + addTilemap: function (key, url, mapData, format) { + + this._cache.tilemap[key] = { url: url, data: mapData, format: format }; + + this._resolveURL(url, this._cache.tilemap[key]); + + }, + + /** + * Add a binary object in to the cache. + * + * @method Phaser.Cache#addBinary + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {object} binaryData - The binary object to be added to the cache. + */ + addBinary: function (key, binaryData) { + + this._cache.binary[key] = binaryData; + + }, + + /** + * Add a BitmapData object to the cache. + * + * @method Phaser.Cache#addBitmapData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. + * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. + * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. + */ + addBitmapData: function (key, bitmapData, frameData) { + + bitmapData.key = key; + + if (frameData === undefined) + { + frameData = new Phaser.FrameData(); + frameData.addFrame(bitmapData.textureFrame); + } + + this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData }; + + return bitmapData; + + }, + + /** + * Add a new Bitmap Font to the Cache. + * + * @method Phaser.Cache#addBitmapFont + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra font data. + * @param {object} atlasData - The Bitmap Font data. + * @param {string} [atlasType='xml'] - The format of the Bitmap Font data file: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) { + + var obj = { + url: url, + data: data, + font: null, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + if (atlasType === 'json') + { + obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + else + { + obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new Bitmap Font to the Cache, where the font texture is part of a Texture Atlas. + * + * The atlas must already exist in the cache, and be available based on the given `atlasKey`. + * + * The `atlasFrame` specifies the name of the frame within the atlas that the Bitmap Font is + * stored in. + * + * The `dataKey` is the key of the XML or JSON Bitmap Font Data, which must already be in + * the Cache. + * + * @method Phaser.Cache#addBitmapFontFromAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} atlasKey - The key of the Texture Atlas in the Cache. + * @param {string} atlasFrame - The frame of the Texture Atlas that the Bitmap Font is in. + * @param {string} dataKey - The key of the Bitmap Font data in the Cache + * @param {string} [dataType='xml'] - The format of the Bitmap Font data: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFontFromAtlas: function (key, atlasKey, atlasFrame, dataKey, dataType, xSpacing, ySpacing) { + + var frame = this.getFrameByName(atlasKey, atlasFrame); + + if (!frame) + { + return; + } + + var obj = { + font: null, + base: this.getBaseTexture(atlasKey), + frame: frame + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + var fontData; + + if (dataType === 'json') + { + fontData = this.getJSON(dataKey); + obj.font = Phaser.LoaderParser.jsonBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + else + { + fontData = this.getXML(dataKey); + obj.font = Phaser.LoaderParser.xmlBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + }, + + /** + * Add a new json object into the cache. + * + * @method Phaser.Cache#addJSON + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra json data. + */ + addJSON: function (key, url, data) { + + this._cache.json[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.json[key]); + + }, + + /** + * Add a new xml object into the cache. + * + * @method Phaser.Cache#addXML + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addXML: function (key, url, data) { + + this._cache.xml[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.xml[key]); + + }, + + /** + * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addVideo + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra video data. + * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. + */ + addVideo: function (key, url, data, isBlob) { + + this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true }; + + this._resolveURL(url, this._cache.video[key]); + + }, + + /** + * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addShader + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra shader data. + */ + addShader: function (key, url, data) { + + this._cache.shader[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.shader[key]); + + }, + + /** + * Add a new Phaser.RenderTexture in to the cache. + * + * @method Phaser.Cache#addRenderTexture + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture. + */ + addRenderTexture: function (key, texture) { + + this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') }; + + }, + + /** + * Add a new sprite sheet in to the cache. + * + * @method Phaser.Cache#addSpriteSheet + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sprite sheet data. + * @param {number} frameWidth - Width of the sprite sheet. + * @param {number} frameHeight - Height of the sprite sheet. + * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + */ + addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + var obj = { + key: key, + url: url, + data: data, + frameWidth: frameWidth, + frameHeight: frameHeight, + margin: margin, + spacing: spacing, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) + }; + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new texture atlas to the Cache. + * + * @method Phaser.Cache#addTextureAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra texture atlas data. + * @param {object} atlasData - Texture atlas frames data. + * @param {number} format - The format of the texture atlas. + */ + addTextureAtlas: function (key, url, data, atlasData, format) { + + var obj = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key); + } + else if (format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + obj.frameData = Phaser.AnimationParser.JSONDataPyxel(this.game, atlasData, key); + } + else + { + // Let's just work it out from the frames array + if (Array.isArray(atlasData.frames)) + { + obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key); + } + else + { + obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key); + } + } + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + //////////////////////////// + // Sound Related Methods // + //////////////////////////// + + /** + * Reload a Sound file from the server. + * + * @method Phaser.Cache#reloadSound + * @param {string} key - The key of the asset within the cache. + */ + reloadSound: function (key) { + + var _this = this; + + var sound = this.getSound(key); + + if (sound) + { + sound.data.src = sound.url; + + sound.data.addEventListener('canplaythrough', function () { + return _this.reloadSoundComplete(key); + }, false); + + sound.data.load(); + } + + }, + + /** + * Fires the onSoundUnlock event when the sound has completed reloading. + * + * @method Phaser.Cache#reloadSoundComplete + * @param {string} key - The key of the asset within the cache. + */ + reloadSoundComplete: function (key) { + + var sound = this.getSound(key); + + if (sound) + { + sound.locked = false; + this.onSoundUnlock.dispatch(key); + } + + }, + + /** + * Updates the sound object in the cache. + * + * @method Phaser.Cache#updateSound + * @param {string} key - The key of the asset within the cache. + */ + updateSound: function (key, property, value) { + + var sound = this.getSound(key); + + if (sound) + { + sound[property] = value; + } + + }, + + /** + * Add a new decoded sound. + * + * @method Phaser.Cache#decodedSound + * @param {string} key - The key of the asset within the cache. + * @param {object} data - Extra sound data. + */ + decodedSound: function (key, data) { + + var sound = this.getSound(key); + + sound.data = data; + sound.decoded = true; + sound.isDecoding = false; + + }, + + /** + * Check if the given sound has finished decoding. + * + * @method Phaser.Cache#isSoundDecoded + * @param {string} key - The key of the asset within the cache. + * @return {boolean} The decoded state of the Sound object. + */ + isSoundDecoded: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return sound.decoded; + } + + }, + + /** + * Check if the given sound is ready for playback. + * A sound is considered ready when it has finished decoding and the device is no longer touch locked. + * + * @method Phaser.Cache#isSoundReady + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the sound is decoded and the device is not touch locked. + */ + isSoundReady: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return (sound.decoded && !this.game.sound.touchLocked); + } + + }, + + //////////////////////// + // Check Key Methods // + //////////////////////// + + /** + * Checks if a key for the given cache object type exists. + * + * @method Phaser.Cache#checkKey + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists, otherwise false. + */ + checkKey: function (cache, key) { + + if (this._cacheMap[cache][key]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given URL has been loaded into the Cache. + * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. + * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox + * which may cause double-load instances. + * + * @method Phaser.Cache#checkURL + * @param {string} url - The url to check for in the cache. + * @return {boolean} True if the url exists, otherwise false. + */ + checkURL: function (url) { + + if (this._urlMap[this._resolveURL(url)]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given key exists in the Canvas Cache. + * + * @method Phaser.Cache#checkCanvasKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkCanvasKey: function (key) { + + return this.checkKey(Phaser.Cache.CANVAS, key); + + }, + + /** + * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. + * + * @method Phaser.Cache#checkImageKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkImageKey: function (key) { + + return this.checkKey(Phaser.Cache.IMAGE, key); + + }, + + /** + * Checks if the given key exists in the Texture Cache. + * + * @method Phaser.Cache#checkTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXTURE, key); + + }, + + /** + * Checks if the given key exists in the Sound Cache. + * + * @method Phaser.Cache#checkSoundKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkSoundKey: function (key) { + + return this.checkKey(Phaser.Cache.SOUND, key); + + }, + + /** + * Checks if the given key exists in the Text Cache. + * + * @method Phaser.Cache#checkTextKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXT, key); + + }, + + /** + * Checks if the given key exists in the Physics Cache. + * + * @method Phaser.Cache#checkPhysicsKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkPhysicsKey: function (key) { + + return this.checkKey(Phaser.Cache.PHYSICS, key); + + }, + + /** + * Checks if the given key exists in the Tilemap Cache. + * + * @method Phaser.Cache#checkTilemapKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTilemapKey: function (key) { + + return this.checkKey(Phaser.Cache.TILEMAP, key); + + }, + + /** + * Checks if the given key exists in the Binary Cache. + * + * @method Phaser.Cache#checkBinaryKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBinaryKey: function (key) { + + return this.checkKey(Phaser.Cache.BINARY, key); + + }, + + /** + * Checks if the given key exists in the BitmapData Cache. + * + * @method Phaser.Cache#checkBitmapDataKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapDataKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPDATA, key); + + }, + + /** + * Checks if the given key exists in the BitmapFont Cache. + * + * @method Phaser.Cache#checkBitmapFontKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapFontKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPFONT, key); + + }, + + /** + * Checks if the given key exists in the JSON Cache. + * + * @method Phaser.Cache#checkJSONKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkJSONKey: function (key) { + + return this.checkKey(Phaser.Cache.JSON, key); + + }, + + /** + * Checks if the given key exists in the XML Cache. + * + * @method Phaser.Cache#checkXMLKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkXMLKey: function (key) { + + return this.checkKey(Phaser.Cache.XML, key); + + }, + + /** + * Checks if the given key exists in the Video Cache. + * + * @method Phaser.Cache#checkVideoKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkVideoKey: function (key) { + + return this.checkKey(Phaser.Cache.VIDEO, key); + + }, + + /** + * Checks if the given key exists in the Fragment Shader Cache. + * + * @method Phaser.Cache#checkShaderKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkShaderKey: function (key) { + + return this.checkKey(Phaser.Cache.SHADER, key); + + }, + + /** + * Checks if the given key exists in the Render Texture Cache. + * + * @method Phaser.Cache#checkRenderTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkRenderTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key); + + }, + + //////////////// + // Get Items // + //////////////// + + /** + * Get an item from a cache based on the given key and property. + * + * This method is mostly used internally by other Cache methods such as `getImage` but is exposed + * publicly for your own use as well. + * + * @method Phaser.Cache#getItem + * @param {string} key - The key of the asset within the cache. + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output. + * @param {string} [property] - If you require a specific property from the cache item, specify it here. + * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. + */ + getItem: function (key, cache, method, property) { + + if (!this.checkKey(cache, key)) + { + if (method) + { + console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.'); + } + } + else + { + if (property === undefined) + { + return this._cacheMap[cache][key]; + } + else + { + return this._cacheMap[cache][key][property]; + } + } + + return null; + + }, + + /** + * Gets a Canvas object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getCanvas + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The canvas object or `null` if no item could be found matching the given key. + */ + getCanvas: function (key) { + + return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas'); + + }, + + /** + * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. + * + * If you need the image used by a bitmap font or similar then please use those respective 'get' methods. + * + * @method Phaser.Cache#getImage + * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. + * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned. + * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. + */ + getImage: function (key, full) { + + if (key === undefined || key === null) + { + key = '__default'; + } + + if (full === undefined) { full = false; } + + var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage'); + + if (img === null) + { + img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage'); + } + + if (full) + { + return img; + } + else + { + return img.data; + } + + }, + + /** + * Get a single texture frame by key. + * + * You'd only do this to get the default Frame created for a non-atlas / spritesheet image. + * + * @method Phaser.Cache#getTextureFrame + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Frame} The frame data. + */ + getTextureFrame: function (key) { + + return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame'); + + }, + + /** + * Gets a Phaser.Sound object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSound + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Sound} The sound object. + */ + getSound: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSound'); + + }, + + /** + * Gets a raw Sound data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSoundData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The sound data. + */ + getSoundData: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data'); + + }, + + /** + * Gets a Text object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getText + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The text data. + */ + getText: function (key) { + + return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data'); + + }, + + /** + * Gets a Physics Data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can get either the entire data set, a single object or a single fixture of an object from it. + * + * @method Phaser.Cache#getPhysicsData + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all. + * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. + * @return {object} The requested physics object data if found. + */ + getPhysicsData: function (key, object, fixtureKey) { + + var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data'); + + if (data === null || object === undefined || object === null) + { + return data; + } + else + { + if (data[object]) + { + var fixtures = data[object]; + + // Try to find a fixture by its fixture key if given + if (fixtures && fixtureKey) + { + for (var fixture in fixtures) + { + // This contains the fixture data of a polygon or a circle + fixture = fixtures[fixture]; + + // Test the key + if (fixture.fixtureKey === fixtureKey) + { + return fixture; + } + } + + // We did not find the requested fixture + console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"'); + } + else + { + return fixtures; + } + } + else + { + console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"'); + } + } + + return null; + + }, + + /** + * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getTilemapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The raw tilemap data in CSV or JSON format. + */ + getTilemapData: function (key) { + + return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData'); + + }, + + /** + * Gets a binary object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBinary + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The binary data object. + */ + getBinary: function (key) { + + return this.getItem(key, Phaser.Cache.BINARY, 'getBinary'); + + }, + + /** + * Gets a BitmapData object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. + */ + getBitmapData: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data'); + + }, + + /** + * Gets a Bitmap Font object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapFont + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not. + */ + getBitmapFont: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont'); + + }, + + /** + * Gets a JSON object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can either return the object by reference (the default), or return a clone + * of it by setting the `clone` argument to `true`. + * + * @method Phaser.Cache#getJSON + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false) + * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. + */ + getJSON: function (key, clone) { + + var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data'); + + if (data) + { + if (clone) + { + return Phaser.Utils.extend(true, Array.isArray(data) ? [] : {}, data); + } + else + { + return data; + } + } + else + { + return null; + } + + }, + + /** + * Gets an XML object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getXML + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The XML object. + */ + getXML: function (key) { + + return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data'); + + }, + + /** + * Gets a Phaser.Video object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getVideo + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Video} The video object. + */ + getVideo: function (key) { + + return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo'); + + }, + + /** + * Gets a fragment shader object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getShader + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {string} The shader object. + */ + getShader: function (key) { + + return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data'); + + }, + + /** + * Gets a RenderTexture object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getRenderTexture + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame. + */ + getRenderTexture: function (key) { + + return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture'); + + }, + + //////////////////////////// + // Frame Related Methods // + //////////////////////////// + + /** + * Gets a PIXI.BaseTexture by key from the given Cache. + * + * @method Phaser.Cache#getBaseTexture + * @param {string} key - Asset key of the image for which you want the BaseTexture for. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {PIXI.BaseTexture} The BaseTexture object. + */ + getBaseTexture: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getBaseTexture', 'base'); + + }, + + /** + * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. + * + * @method Phaser.Cache#getFrame + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.Frame} The frame data. + */ + getFrame: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrame', 'frame'); + + }, + + /** + * Get the total number of frames contained in the FrameData object specified by the given key. + * + * @method Phaser.Cache#getFrameCount + * @param {string} key - Asset key of the FrameData you want. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {number} Then number of frames. 0 if the image is not found. + */ + getFrameCount: function (key, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.total; + } + else + { + return 0; + } + + }, + + /** + * Gets a Phaser.FrameData object from the Image Cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.FrameData} The frame data. + */ + getFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrameData', 'frameData'); + + }, + + /** + * Check if the FrameData for the given key exists in the Image Cache. + * + * @method Phaser.Cache#hasFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {boolean} True if the given key has frameData in the cache, otherwise false. + */ + hasFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return (this.getItem(key, cache, '', 'frameData') !== null); + + }, + + /** + * Replaces a set of frameData with a new Phaser.FrameData object. + * + * @method Phaser.Cache#updateFrameData + * @param {string} key - The unique key by which you will reference this object. + * @param {number} frameData - The new FrameData. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + */ + updateFrameData: function (key, frameData, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + if (this._cacheMap[cache][key]) + { + this._cacheMap[cache][key].frameData = frameData; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByIndex + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {number} index - The index of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByIndex: function (key, index, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrame(index); + } + else + { + return null; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByName + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {string} name - The name of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByName: function (key, name, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrameByName(name); + } + else + { + return null; + } + + }, + + /** + * Get a cached object by the URL. + * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. + * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. + * + * @method Phaser.Cache#getURL + * @param {string} url - The url for the object loaded to get from the cache. + * @return {object} The cached object. + */ + getURL: function (url) { + + var url = this._resolveURL(url); + + if (url) + { + return this._urlMap[url]; + } + else + { + console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false'); + return null; + } + + }, + + /** + * Gets all keys used in the requested Cache. + * + * @method Phaser.Cache#getKeys + * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. + * @return {Array} The array of keys in the requested cache. + */ + getKeys: function (cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + var out = []; + + if (this._cacheMap[cache]) + { + for (var key in this._cacheMap[cache]) + { + if (key !== '__default' && key !== '__missing') + { + out.push(key); + } + } + } + + return out; + + }, + + ///////////////////// + // Remove Methods // + ///////////////////// + + /** + * Removes a canvas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeCanvas + * @param {string} key - Key of the asset you want to remove. + */ + removeCanvas: function (key) { + + delete this._cache.canvas[key]; + + }, + + /** + * Removes an image from the cache. + * + * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. + * + * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeImage + * @param {string} key - Key of the asset you want to remove. + * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed? + */ + removeImage: function (key, destroyBaseTexture) { + + if (destroyBaseTexture === undefined) { destroyBaseTexture = true; } + + var img = this.getImage(key, true); + + if (destroyBaseTexture && img.base) + { + img.base.destroy(); + } + + delete this._cache.image[key]; + + }, + + /** + * Removes a sound from the cache. + * + * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will + * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then + * you must finish your house-keeping and destroy them all yourself first, before calling this method. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSound + * @param {string} key - Key of the asset you want to remove. + */ + removeSound: function (key) { + + delete this._cache.sound[key]; + + }, + + /** + * Removes a text file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeText + * @param {string} key - Key of the asset you want to remove. + */ + removeText: function (key) { + + delete this._cache.text[key]; + + }, + + /** + * Removes a physics data file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removePhysics + * @param {string} key - Key of the asset you want to remove. + */ + removePhysics: function (key) { + + delete this._cache.physics[key]; + + }, + + /** + * Removes a tilemap from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTilemap + * @param {string} key - Key of the asset you want to remove. + */ + removeTilemap: function (key) { + + delete this._cache.tilemap[key]; + + }, + + /** + * Removes a binary file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBinary + * @param {string} key - Key of the asset you want to remove. + */ + removeBinary: function (key) { + + delete this._cache.binary[key]; + + }, + + /** + * Removes a bitmap data from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapData + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapData: function (key) { + + delete this._cache.bitmapData[key]; + + }, + + /** + * Removes a bitmap font from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapFont + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapFont: function (key) { + + delete this._cache.bitmapFont[key]; + + }, + + /** + * Removes a json object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeJSON + * @param {string} key - Key of the asset you want to remove. + */ + removeJSON: function (key) { + + delete this._cache.json[key]; + + }, + + /** + * Removes a xml object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeXML + * @param {string} key - Key of the asset you want to remove. + */ + removeXML: function (key) { + + delete this._cache.xml[key]; + + }, + + /** + * Removes a video from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeVideo + * @param {string} key - Key of the asset you want to remove. + */ + removeVideo: function (key) { + + delete this._cache.video[key]; + + }, + + /** + * Removes a shader from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeShader + * @param {string} key - Key of the asset you want to remove. + */ + removeShader: function (key) { + + delete this._cache.shader[key]; + + }, + + /** + * Removes a Render Texture from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeRenderTexture + * @param {string} key - Key of the asset you want to remove. + */ + removeRenderTexture: function (key) { + + delete this._cache.renderTexture[key]; + + }, + + /** + * Removes a Sprite Sheet from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSpriteSheet + * @param {string} key - Key of the asset you want to remove. + */ + removeSpriteSheet: function (key) { + + delete this._cache.spriteSheet[key]; + + }, + + /** + * Removes a Texture Atlas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTextureAtlas + * @param {string} key - Key of the asset you want to remove. + */ + removeTextureAtlas: function (key) { + + delete this._cache.image[key]; + + }, + + /** + * Empties out all of the GL Textures from Images stored in the cache. + * This is called automatically when the WebGL context is lost and then restored. + * + * @method Phaser.Cache#clearGLTextures + * @protected + */ + clearGLTextures: function () { + + for (var key in this._cache.image) + { + this._cache.image[key].base._glTextures = []; + } + + }, + + /** + * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`. + * This is then looked-up by the Cache.getURL and Cache.checkURL calls. + * + * @method Phaser.Cache#_resolveURL + * @private + * @param {string} url - The URL to resolve. This is appended to Loader.baseURL. + * @param {object} [data] - The data associated with the URL to be stored to the URL Map. + * @return {string} The resolved URL. + */ + _resolveURL: function (url, data) { + + if (!this.autoResolveURL) + { + return null; + } + + this._urlResolver.src = this.game.load.baseURL + url; + + this._urlTemp = this._urlResolver.src; + + // Ensure no request is actually made + this._urlResolver.src = ''; + + // Record the URL to the map + if (data) + { + this._urlMap[this._urlTemp] = data; + } + + return this._urlTemp; + + }, + + /** + * Clears the cache. Removes every local cache object reference. + * If an object in the cache has a `destroy` method it will be called; + * otherwise, `destroy` will be called on any of the object's `base`, `data`, + * `frameData`, or `texture` properties. + * + * @method Phaser.Cache#destroy + */ + destroy: function () { + + for (var i = 0; i < this._cacheMap.length; i++) + { + var cache = this._cacheMap[i]; + + for (var key in cache) + { + if (key !== '__default' && key !== '__missing') + { + this.destroyItem(cache[key]); + + delete cache[key]; + } + } + } + + this._urlMap = null; + this._urlResolver = null; + this._urlTemp = null; + + }, + + /** + * @method Phaser.Cache#destroyItem + * @protected + * @param {object} item + */ + destroyItem: function (item) { + + if (item.destroy) + { + item.destroy(); + } + else + { + if (item.base && item.base.destroy) + { + item.base.destroy(); + } + + if (item.data && item.data.destroy) + { + item.data.destroy(); + } + + if (item.frameData && item.frameData.destroy) + { + item.frameData.destroy(); + } + + if (item.texture && item.texture.destroy) + { + item.texture.destroy(true); + } + } + + }, + + /** + * Starts loading the DEFAULT and MISSING images. + * + * @private + */ + _addImages: function () { + + this._pendingCount = 0; + + this.addDefaultImage(); + this.addMissingImage(); + + var self = this; + var readyTimeout = Phaser.Cache.READY_TIMEOUT; + + if (Phaser.Cache.READY_TIMEOUT > 0) + { + setTimeout(function () { + if (!self.isReady) + { + console.warn('Phaser.Cache: Still waiting for images after %s ms.', readyTimeout); + + self._ready(); + } + }, Phaser.Cache.READY_TIMEOUT); + } + else + { + this._ready(); + } + + }, + + + /** + * Increments the pending count. + * + * @private + */ + _addPending: function () { + + this._pendingCount += 1; + + }, + + + /** + * Decrements the pending count and checks if complete. + * + * @private + */ + _removePending: function () { + + this._pendingCount -= 1; + this._checkReady(); + + }, + + + /** + * Calls {@link #_ready} if no pending items remain. + * + * @private + */ + _checkReady: function () { + + if (this.isReady) + { + this._ready(); + } + + }, + + + /** + * Resets pending count and triggers {@link #onReady}. + * + * @private + */ + _ready: function () { + + this._pendingCount = 0; + this.onReady.dispatch(this); + + } + +}; + +Phaser.Cache.prototype.constructor = Phaser.Cache; + +/** +* The DEFAULT and MISSING textures have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). +* +* @property {boolean} Phaser.Cache#isReady +*/ +Object.defineProperty(Phaser.Cache.prototype, 'isReady', { + get: function () { + return this._pendingCount <= 0; + } +}); + +/* jshint wsh:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* +* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. +* +* Parallel loading (see {@link #enableParallel}) is supported and enabled by default. +* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}. +* +* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and +* [Shoebox](http://renderhjs.net/shoebox/) +* +* @class Phaser.Loader +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Loader = function (game) { + + /** + * Local reference to game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + /** + * Local reference to the Phaser.Cache. + * @property {Phaser.Cache} cache + * @protected + */ + this.cache = game.cache; + + /** + * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * True if the Loader is in the process of loading the queue. + * @property {boolean} isLoading + * @default + */ + this.isLoading = false; + + /** + * True if all assets in the queue have finished loading. + * @property {boolean} hasLoaded + * @default + */ + this.hasLoaded = false; + + /** + * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}. + * + * This property is an object containing: sprite, rect, direction, width and height + * + * @property {?object} preloadSprite + * @protected + */ + this.preloadSprite = null; + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * @property {boolean|string} crossOrigin + * @default + */ + this.crossOrigin = false; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * Useful if allowing the asset base url to be configured outside of the game code. + * The string _must_ end with a "/". + * + * @property {string} baseURL + */ + this.baseURL = ''; + + /** + * The value of `path`, if set, is placed before any _relative_ file path given. For example: + * + * ```javascript + * load.path = "images/sprites/"; + * load.image("ball", "ball.png"); + * load.image("tree", "level1/oaktree.png"); + * load.image("boom", "http://server.com/explode.png"); + * ``` + * + * Would load the `ball` file from `images/sprites/ball.png` and the tree from + * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL + * given as it's an absolute URL. + * + * Please note that the path is added before the filename but *after* the baseURL (if set.) + * + * The string _must_ end with a "/". + * + * @property {string} path + */ + this.path = ''; + + /** + * Used to map the application mime-types to to the Accept header in XHR requests. + * If you don't require these mappings, or they cause problems on your server, then + * remove them from the headers object and the XHR request will not try to use them. + * + * This object can also be used to set the `X-Requested-With` header to + * `XMLHttpRequest` (or any other value you need). To enable this do: + * + * ```javascript + * this.load.headers.requestedWith = 'XMLHttpRequest' + * ``` + * + * before adding anything to the Loader. The XHR loader will then call: + * + * ```javascript + * setRequestHeader('X-Requested-With', this.headers['requestedWith']) + * ``` + * + * @property {object} headers + * @default + */ + this.headers = { + "requestedWith": false, + "json": "application/json", + "xml": "application/xml" + }; + + /** + * This event is dispatched when the loading process starts: before the first file has been requested, + * but after all the initial packs have been loaded. + * + * @property {Phaser.Signal} onLoadStart + */ + this.onLoadStart = new Phaser.Signal(); + + /** + * This event is dispatched when the final file in the load queue has either loaded or failed. + * + * @property {Phaser.Signal} onLoadComplete + */ + this.onLoadComplete = new Phaser.Signal(); + + /** + * This event is dispatched when an asset pack has either loaded or failed to load. + * + * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. + * + * Params: `(pack key, success?, total packs loaded, total packs)` + * + * @property {Phaser.Signal} onPackComplete + */ + this.onPackComplete = new Phaser.Signal(); + + /** + * This event is dispatched immediately before a file starts loading. + * It's possible the file may fail (eg. download error, invalid format) after this event is sent. + * + * Params: `(progress, file key, file url)` + * + * @property {Phaser.Signal} onFileStart + */ + this.onFileStart = new Phaser.Signal(); + + /** + * This event is dispatched when a file has either loaded or failed to load. + * + * Any function bound to this will receive the following parameters: + * + * progress, file key, success?, total loaded files, total files + * + * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. + * + * @property {Phaser.Signal} onFileComplete + */ + this.onFileComplete = new Phaser.Signal(); + + /** + * This event is dispatched when a file (or pack) errors as a result of the load request. + * + * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. + * + * Params: `(file key, file)` + * + * @property {Phaser.Signal} onFileError + */ + this.onFileError = new Phaser.Signal(); + + /** + * If true (the default) then parallel downloading will be enabled. + * + * To disable all parallel downloads this must be set to false prior to any resource being loaded. + * + * @property {boolean} enableParallel + */ + this.enableParallel = true; + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Many current browsers limit 6 requests per domain; this is slightly conservative. + * + * This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently. + * + * @property {integer} maxParallelDownloads + */ + this.maxParallelDownloads = 4; + + /** + * A counter: if more than zero, files will be automatically added as a synchronization point. + * @property {integer} _withSyncPointDepth; + */ + this._withSyncPointDepth = 0; + + /** + * Contains all the information for asset files (including packs) to load. + * + * File/assets are only removed from the list after all loading completes. + * + * @property {file[]} _fileList + * @private + */ + this._fileList = []; + + /** + * Inflight files (or packs) that are being fetched/processed. + * + * This means that if there are any files in the flight queue there should still be processing + * going on; it should only be empty before or after loading. + * + * The files in the queue may have additional properties added to them, + * including `requestObject` which is normally the associated XHR. + * + * @property {file[]} _flightQueue + * @private + */ + this._flightQueue = []; + + /** + * The offset into the fileList past all the complete (loaded or error) entries. + * + * @property {integer} _processingHead + * @private + */ + this._processingHead = 0; + + /** + * True when the first file (not pack) has loading started. + * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded. + * + * @property {boolean} _initialPacksLoaded + * @private + */ + this._fileLoadStarted = false; + + /** + * Total packs seen - adjusted when a pack is added. + * @property {integer} _totalPackCount + * @private + */ + this._totalPackCount = 0; + + /** + * Total files seen - adjusted when a file is added. + * @property {integer} _totalFileCount + * @private + */ + this._totalFileCount = 0; + + /** + * Total packs loaded - adjusted just prior to `onPackComplete`. + * @property {integer} _loadedPackCount + * @private + */ + this._loadedPackCount = 0; + + /** + * Total files loaded - adjusted just prior to `onFileComplete`. + * @property {integer} _loadedFileCount + * @private + */ + this._loadedFileCount = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_PHASER_JSON = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5; + +Phaser.Loader.prototype = { + + /** + * Set a Sprite to be a "preload" sprite by passing it to this method. + * + * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. + * This allows you to easily make loading bars for games. + * + * The sprite will automatically be made visible when calling this. + * + * @method Phaser.Loader#setPreloadSprite + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load. + * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. + */ + setPreloadSprite: function (sprite, direction) { + + direction = direction || 0; + + this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null }; + + if (direction === 0) + { + // Horizontal rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height); + } + else + { + // Vertical rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1); + } + + sprite.crop(this.preloadSprite.rect); + + sprite.visible = true; + + }, + + /** + * Called automatically by ScaleManager when the game resizes in RESIZE scalemode. + * + * This can be used to adjust the preloading sprite size, eg. + * + * @method Phaser.Loader#resize + * @protected + */ + resize: function () { + + if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height) + { + this.preloadSprite.rect.height = this.preloadSprite.sprite.height; + } + + }, + + /** + * Check whether a file/asset with a specific key is queued to be loaded. + * + * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey} + * + * @method Phaser.Loader#checkKeyExists + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ + checkKeyExists: function (type, key) { + + return this.getAssetIndex(type, key) > -1; + + }, + + /** + * Get the queue-index of the file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAssetIndex + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {number} The index of this key in the filelist, or -1 if not found. + * The index may change and should only be used immediately following this call + */ + getAssetIndex: function (type, key) { + + var bestFound = -1; + + for (var i = 0; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + if (file.type === type && file.key === key) + { + bestFound = i; + + // An already loaded/loading file may be superceded. + if (!file.loaded && !file.loading) + { + break; + } + } + } + + return bestFound; + + }, + + /** + * Find a file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAsset + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. + * The index may change and should only be used immediately following this call. + */ + getAsset: function (type, key) { + + var fileIndex = this.getAssetIndex(type, key); + + if (fileIndex > -1) + { + return { index: fileIndex, file: this._fileList[fileIndex] }; + } + + return false; + + }, + + /** + * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. + * + * This will abort any loading and clear any queued assets. + * + * Optionally you can clear any associated events. + * + * @method Phaser.Loader#reset + * @protected + * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared. + * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them. + */ + reset: function (hard, clearEvents) { + + if (clearEvents === undefined) { clearEvents = false; } + + if (this.resetLocked) + { + return; + } + + if (hard) + { + this.preloadSprite = null; + } + + this.isLoading = false; + + this._processingHead = 0; + this._fileList.length = 0; + this._flightQueue.length = 0; + + this._fileLoadStarted = false; + this._totalFileCount = 0; + this._totalPackCount = 0; + this._loadedPackCount = 0; + this._loadedFileCount = 0; + + if (clearEvents) + { + this.onLoadStart.removeAll(); + this.onLoadComplete.removeAll(); + this.onPackComplete.removeAll(); + this.onFileStart.removeAll(); + this.onFileComplete.removeAll(); + this.onFileError.removeAll(); + } + + }, + + /** + * Internal function that adds a new entry to the file list. Do not call directly. + * + * @method Phaser.Loader#addToFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} [url] - The URL the asset will be loaded from. + * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. + * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. + * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. + * @return {Phaser.Loader} This instance of the Phaser Loader. + */ + addToFileList: function (type, key, url, properties, overwrite, extension) { + + if (overwrite === undefined) { overwrite = false; } + + if (key === undefined || key === '') + { + console.warn("Phaser.Loader: Invalid or no key given of type " + type); + return this; + } + + if (url === undefined || url === null) + { + if (extension) + { + url = key + extension; + } + else + { + console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key); + return this; + } + } + + var file = { + type: type, + key: key, + path: this.path, + url: url, + syncPoint: this._withSyncPointDepth > 0, + data: null, + loading: false, + loaded: false, + error: false + }; + + if (properties) + { + for (var prop in properties) + { + file[prop] = properties[prop]; + } + } + + var fileIndex = this.getAssetIndex(type, key); + + if (overwrite && fileIndex > -1) + { + var currentFile = this._fileList[fileIndex]; + + if (!currentFile.loading && !currentFile.loaded) + { + this._fileList[fileIndex] = file; + } + else + { + this._fileList.push(file); + this._totalFileCount++; + } + } + else if (fileIndex === -1) + { + this._fileList.push(file); + this._totalFileCount++; + } + + return this; + + }, + + /** + * Internal function that replaces an existing entry in the file list with a new one. Do not call directly. + * + * @method Phaser.Loader#replaceInFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} url - The URL the asset will be loaded from. + * @param {object} properties - Any additional properties needed to load the file. + */ + replaceInFileList: function (type, key, url, properties) { + + return this.addToFileList(type, key, url, properties, true); + + }, + + /** + * Add a JSON resource pack ('packfile') to the Loader. + * + * A packfile is a JSON file that contains a list of assets to the be loaded. + * Please see the example 'loader/asset pack' in the Phaser Examples repository. + * + * Packs are always put before the first non-pack file that is not loaded / loading. + * + * This means that all packs added before any loading has started are added to the front + * of the file queue, in the order added. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#pack + * @param {string} key - Unique asset key of this resource pack. + * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. + * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO + * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. + * @return {Phaser.Loader} This Loader instance. + */ + pack: function (key, url, data, callbackContext) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (callbackContext === undefined) { callbackContext = null; } + + if (!url && !data) + { + console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.'); + + return this; + } + + var pack = { + type: 'packfile', + key: key, + url: url, + path: this.path, + syncPoint: true, + data: null, + loading: false, + loaded: false, + error: false, + callbackContext: callbackContext + }; + + // A data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + pack.data = data || {}; + + // Already consider 'loaded' + pack.loaded = true; + } + + // Add before first non-pack/no-loaded ~ last pack from start prior to loading + // (Read one past for splice-to-end) + for (var i = 0; i < this._fileList.length + 1; i++) + { + var file = this._fileList[i]; + + if (!file || (!file.loaded && !file.loading && file.type !== 'packfile')) + { + this._fileList.splice(i, 0, pack); + this._totalPackCount++; + break; + } + } + + return this; + + }, + + /** + * Adds an Image to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * This method also supports passing in a texture object as the `url` argument. This allows you to load + * compressed textures into Phaser. You can also use `Loader.texture` to do this. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.image('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * @method Phaser.Loader#image + * @param {string} key - Unique asset key of this image file. + * @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + image: function (key, url, overwrite) { + + if (typeof url === 'object') + { + return this.texture(key, url, overwrite); + } + else + { + return this.addToFileList('image', key, url, undefined, overwrite, '.png'); + } + + }, + + /** + * Generate an image from a BitmapData object and add it to the current load queue. + * + * @method Phaser.Loader#imageFromBitmapData + * @param {string} key - Unique asset key for the generated image. + * @param {Phaser.BitmapData} bitmapData + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + imageFromBitmapData: function (key, bitmapData, overwrite) { + + return this.image(key, bitmapData.canvas.toDataURL('image/png'), overwrite); + + }, + + /** + * Generate a grid image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromGrid + * @see Phaser.Create#grid + */ + imageFromGrid: function (key, width, height, cellWidth, cellHeight, color) { + + return this.imageFromBitmapData(key, this.game.create.grid(key, width, height, cellWidth, cellHeight, color, false)); + + }, + + /** + * Generate a texture image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromTexture + * @see Phaser.Create#texture + */ + imageFromTexture: function (key, data, pixelWidth, pixelHeight, palette) { + + return this.imageFromBitmapData(key, this.game.create.texture(key, data, pixelWidth, pixelHeight, palette, false)); + + }, + + /** + * Adds a Compressed Texture Image to the current load queue. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.texture('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#texture + * @param {string} key - Unique asset key of this image file. + * @param {object} object - The texture path data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + texture: function (key, object, overwrite) { + + if (this.game.renderType === Phaser.WEBGL) + { + var compression = this.game.renderer.extensions.compression; + var exkey; + + for (exkey in object) + { + if (exkey.toUpperCase() in compression) + { + return this.addToFileList('texture', key, object[exkey], undefined, overwrite, '.pvr'); + } + } + } + + // Check if we have a truecolor texture to fallback. + // Also catches calls to this function that are from a Canvas renderer + + if (object['truecolor']) + { + this.addToFileList('image', key, object['truecolor'], undefined, overwrite, '.png'); + } + + return this; + + }, + + /** + * Adds an array of images to the current load queue. + * + * It works by passing each element of the array to the Loader.image method. + * + * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. + * + * Retrieve the images via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#images + * @param {array} keys - An array of unique asset keys of the image files. + * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. + * @return {Phaser.Loader} This Loader instance. + */ + images: function (keys, urls) { + + if (Array.isArray(urls)) + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i], urls[i]); + } + } + else + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i]); + } + } + + return this; + + }, + + /** + * Adds a Text file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getText(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#text + * @param {string} key - Unique asset key of the text file. + * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + text: function (key, url, overwrite) { + + return this.addToFileList('text', key, url, undefined, overwrite, '.txt'); + + }, + + /** + * Adds a JSON file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#json + * @param {string} key - Unique asset key of the json file. + * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + json: function (key, url, overwrite) { + + return this.addToFileList('json', key, url, undefined, overwrite, '.json'); + + }, + + /** + * Adds a fragment shader file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getShader(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" + * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#shader + * @param {string} key - Unique asset key of the fragment file. + * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + shader: function (key, url, overwrite) { + + return this.addToFileList('shader', key, url, undefined, overwrite, '.frag'); + + }, + + /** + * Adds an XML file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getXML(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#xml + * @param {string} key - Unique asset key of the xml file. + * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + xml: function (key, url, overwrite) { + + return this.addToFileList('xml', key, url, undefined, overwrite, '.xml'); + + }, + + /** + * Adds a JavaScript file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. + * If you do not desire this action then provide a URL. + * + * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! + * + * A callback, which will be invoked as the script tag has been created, can also be specified. + * The callback must return relevant `data`. + * + * @method Phaser.Loader#script + * @param {string} key - Unique asset key of the script file. + * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing. + * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. + * @return {Phaser.Loader} This Loader instance. + */ + script: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + if (callback !== false && callbackContext === undefined) { callbackContext = this; } + + return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js'); + + }, + + /** + * Adds a binary file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBinary(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. + * If you do not desire this action then provide a URL. + * + * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. + * When the callback is called it will be passed 2 parameters: the key of the file and the file data. + * + * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. + * + * @method Phaser.Loader#binary + * @param {string} key - Unique asset key of the binary file. + * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it. + * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context. + * @return {Phaser.Loader} This Loader instance. + */ + binary: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + // Why is the default callback context the ..callback? + if (callback !== false && callbackContext === undefined) { callbackContext = callback; } + + return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin'); + + }, + + /** + * Adds a Sprite Sheet to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal + * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. + * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. + * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming + * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. + * If you've got an atlas then use `Loader.atlas` instead. + * + * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#spritesheet + * @param {string} key - Unique asset key of the sheet file. + * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet. + * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.Loader} This Loader instance. + */ + spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing, skipFrames: skipFrames }, false, '.png'); + + }, + + /** + * Adds an audio file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getSound(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. + * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. + * The solution is to use a lower encoding rate such as 44100 Hz. + * + * @method Phaser.Loader#audio + * @param {string} key - Unique asset key of the audio file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp3']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audio: function (key, urls, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (autoDecode === undefined) { autoDecode = true; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); + + }, + + /** + * Adds an audio sprite file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Audio Sprites are a combination of audio files and a JSON configuration. + * + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * Retrieve the file via `Cache.getSoundData(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#audioSprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (jsonURL === undefined) { jsonURL = null; } + if (jsonData === undefined) { jsonData = null; } + if (autoDecode === undefined) { autoDecode = true; } + + this.audio(key, urls, autoDecode); + + if (jsonURL) + { + this.json(key + '-audioatlas', jsonURL); + } + else if (jsonData) + { + if (typeof jsonData === 'string') + { + jsonData = JSON.parse(jsonData); + } + + this.cache.addJSON(key + '-audioatlas', '', jsonData); + } + else + { + console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object'); + } + + return this; + + }, + + /** + * A legacy alias for Loader.audioSprite. Please see that method for documentation. + * + * @method Phaser.Loader#audiosprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode); + + }, + + /** + * Adds a video file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getVideo(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. + * + * @method Phaser.Loader#video + * @param {string} key - Unique asset key of the video file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp4']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete. + * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. + * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. + * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the + * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. + * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set. + * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. + * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. + * @return {Phaser.Loader} This Loader instance. + */ + video: function (key, urls, loadEvent, asBlob) { + + if (loadEvent === undefined) + { + if (this.game.device.firefox) + { + loadEvent = 'loadeddata'; + } + else + { + loadEvent = 'canplaythrough'; + } + } + + if (asBlob === undefined) { asBlob = false; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent }); + + }, + + /** + * Adds a Tile Map data file to the current load queue. + * + * Phaser can load data in two different formats: CSV and Tiled JSON. + * + * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". + * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#tilemap + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. + * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + * @return {Phaser.Loader} This Loader instance. + */ + tilemap: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Tilemap.CSV; } + + if (!url && !data) + { + if (format === Phaser.Tilemap.CSV) + { + url = key + '.csv'; + } + else + { + url = key + '.json'; + } + } + + // A map data object has been given + if (data) + { + switch (format) + { + // A csv string or object has been given + case Phaser.Tilemap.CSV: + break; + + // A json string or object has been given + case Phaser.Tilemap.TILED_JSON: + + if (typeof data === 'string') + { + data = JSON.parse(data); + } + break; + } + + this.cache.addTilemap(key, null, data, format); + } + else + { + this.addToFileList('tilemap', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds a physics data file to the current load queue. + * + * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". + * It will always use `.json` as the extension. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#physics + * @param {string} key - Unique asset key of the physics json data. + * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. + * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data. + * @return {Phaser.Loader} This Loader instance. + */ + physics: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; } + + if (!url && !data) + { + url = key + '.json'; + } + + // A map data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + this.cache.addPhysicsData(key, null, data, format); + } + else + { + this.addToFileList('physics', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds Bitmap Font files to the current load queue. + * + * To create the Bitmap Font files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `xmlData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#bitmapFont + * @param {string} key - Unique asset key of the bitmap font. + * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". + * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". + * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json). + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + * @return {Phaser.Loader} This Loader instance. + */ + bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (atlasURL === null && atlasData === null) + { + atlasURL = key + '.xml'; + } + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + // A URL to a json/xml atlas has been given + if (atlasURL) + { + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing }); + } + else + { + // A stringified xml/json atlas has been given + if (typeof atlasData === 'string') + { + var json, xml; + + try + { + json = JSON.parse(atlasData); + } + catch ( e ) + { + xml = this.parseXml(atlasData); + } + + if (!xml && !json) + { + throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given"); + } + + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml, + atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing }); + } + } + + return this; + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONArray + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONHash + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * This call expects the atlas data to be in the Starling XML data format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasXML + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasXML: function (key, textureURL, atlasURL, atlasData) { + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (!atlasURL && !atlasData) + { + atlasURL = key + '.xml'; + } + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlas + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. + * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING. + * @return {Phaser.Loader} This Loader instance. + */ + atlas: function (key, textureURL, atlasURL, atlasData, format) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } + + if (!atlasURL && !atlasData) + { + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + atlasURL = key + '.xml'; + } + else + { + atlasURL = key + '.json'; + } + } + + // A URL to a json/xml file has been given + if (atlasURL) + { + this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); + } + else + { + switch (format) + { + // A json string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: + + if (typeof atlasData === 'string') + { + atlasData = JSON.parse(atlasData); + } + break; + + // An xml string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: + + if (typeof atlasData === 'string') + { + var xml = this.parseXml(atlasData); + + if (!xml) + { + throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); + } + + atlasData = xml; + } + break; + } + + this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); + + } + + return this; + + }, + + /** + * Add a synchronization point to the assets / files added within the supplied callback. + * + * A synchronization point denotes that an asset _must_ be completely loaded before + * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait + * for previous assets to load (unless they are sync-points). Resources, such as packs, may still + * be downloaded around sync-points, as long as they do not finalize loading. + * + * @method Phaser.Loader#withSyncPoint + * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader. + * @param {object} [callbackContext=(loader)] - Context for the callback. + * @return {Phaser.Loader} This Loader instance. + */ + withSyncPoint: function (callback, callbackContext) { + + this._withSyncPointDepth++; + + try { + callback.call(callbackContext || this, this); + } finally { + this._withSyncPointDepth--; + } + + return this; + }, + + /** + * Add a synchronization point to a specific file/asset in the load queue. + * + * This has no effect on already loaded assets. + * + * @method Phaser.Loader#addSyncPoint + * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc). + * @param {string} key - Key of the file you want to turn into a sync point. + * @return {Phaser.Loader} This Loader instance. + * @see {@link Phaser.Loader#withSyncPoint withSyncPoint} + */ + addSyncPoint: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + asset.file.syncPoint = true; + } + + return this; + }, + + /** + * Remove a file/asset from the loading queue. + * + * A file that is loaded or has started loading cannot be removed. + * + * @method Phaser.Loader#removeFile + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - Key of the file you want to remove. + */ + removeFile: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + if (!asset.loaded && !asset.loading) + { + this._fileList.splice(asset.index, 1); + } + } + + }, + + /** + * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead. + * + * @method Phaser.Loader#removeAll + * @protected + */ + removeAll: function () { + + this._fileList.length = 0; + this._flightQueue.length = 0; + + }, + + /** + * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. + * + * @method Phaser.Loader#start + */ + start: function () { + + if (this.isLoading) + { + return; + } + + this.hasLoaded = false; + this.isLoading = true; + + this.updateProgress(); + + this.processLoadQueue(); + + }, + + /** + * Process the next item(s) in the file/asset queue. + * + * Process the queue and start loading enough items to fill up the inflight queue. + * + * If a sync-file is encountered then subsequent asset processing is delayed until it completes. + * The exception to this rule is that packfiles can be downloaded (but not processed) even if + * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel. + * such as during the start phaser. + * + * @method Phaser.Loader#processLoadQueue + * @private + */ + processLoadQueue: function () { + + if (!this.isLoading) + { + console.warn('Phaser.Loader - active loading canceled / reset'); + this.finishedLoading(true); + return; + } + + // Empty the flight queue as applicable + for (var i = 0; i < this._flightQueue.length; i++) + { + var file = this._flightQueue[i]; + + if (file.loaded || file.error) + { + this._flightQueue.splice(i, 1); + i--; + + file.loading = false; + file.requestUrl = null; + file.requestObject = null; + + if (file.error) + { + this.onFileError.dispatch(file.key, file); + } + + if (file.type !== 'packfile') + { + this._loadedFileCount++; + this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount); + } + else if (file.type === 'packfile' && file.error) + { + // Non-error pack files are handled when processing the file queue + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + } + } + + // When true further non-pack file downloads are suppressed + var syncblock = false; + + var inflightLimit = this.enableParallel ? Math.max(1, this.maxParallelDownloads) : 1; + + for (var i = this._processingHead; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + // Pack is fetched (ie. has data) and is currently at the start of the process queue. + if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead) + { + // Processing the pack / adds more files + this.processPack(file); + + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + if (file.loaded || file.error) + { + // Item at the start of file list finished, can skip it in future + if (i === this._processingHead) + { + this._processingHead = i + 1; + } + } + else if (!file.loading && this._flightQueue.length < inflightLimit) + { + // -> not loaded/failed, not loading + if (file.type === 'packfile' && !file.data) + { + // Fetches the pack data: the pack is processed above as it reaches queue-start. + // (Packs do not trigger onLoadStart or onFileStart.) + this._flightQueue.push(file); + file.loading = true; + + this.loadFile(file); + } + else if (!syncblock) + { + if (!this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this._flightQueue.push(file); + file.loading = true; + this.onFileStart.dispatch(this.progress, file.key, file.url); + + this.loadFile(file); + } + } + + if (!file.loaded && file.syncPoint) + { + syncblock = true; + } + + // Stop looking if queue full - or if syncblocked and there are no more packs. + // (As only packs can be loaded around a syncblock) + if (this._flightQueue.length >= inflightLimit || + (syncblock && this._loadedPackCount === this._totalPackCount)) + { + break; + } + } + + this.updateProgress(); + + // True when all items in the queue have been advanced over + // (There should be no inflight items as they are complete - loaded/error.) + if (this._processingHead >= this._fileList.length) + { + this.finishedLoading(); + } + else if (!this._flightQueue.length) + { + // Flight queue is empty but file list is not done being processed. + // This indicates a critical internal error with no known recovery. + console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled"); + + var _this = this; + + setTimeout(function () { + _this.finishedLoading(true); + }, 2000); + } + + }, + + /** + * The loading is all finished. + * + * @method Phaser.Loader#finishedLoading + * @private + * @param {boolean} [abnormal=true] - True if the loading finished abnormally. + */ + finishedLoading: function (abnormal) { + + if (this.hasLoaded) + { + return; + } + + this.hasLoaded = true; + this.isLoading = false; + + // If there were no files make sure to trigger the event anyway, for consistency + if (!abnormal && !this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this.reset(); + + this.onLoadComplete.dispatch(); + + // Check if the state still exists since destroy could have occurred while loading + if (this.game.state) + { + this.game.state.loadComplete(); + } + + }, + + /** + * Informs the loader that the given file resource has been fetched and processed; + * or such a request has failed. + * + * @method Phaser.Loader#asyncComplete + * @private + * @param {object} file + * @param {string} [error=''] - The error message, if any. No message implies no error. + */ + asyncComplete: function (file, errorMessage) { + + if (errorMessage === undefined) { errorMessage = ''; } + + file.loaded = true; + file.error = !!errorMessage; + + if (errorMessage) + { + file.errorMessage = errorMessage; + + console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage); + } + + this.processLoadQueue(); + + }, + + /** + * Process pack data. This will usually modify the file list. + * + * @method Phaser.Loader#processPack + * @private + * @param {object} pack + */ + processPack: function (pack) { + + var packData = pack.data[pack.key]; + + if (!packData) + { + console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key'); + return; + } + + for (var i = 0; i < packData.length; i++) + { + var file = packData[i]; + + switch (file.type) + { + case "image": + this.image(file.key, file.url, file.overwrite); + break; + + case "text": + this.text(file.key, file.url, file.overwrite); + break; + + case "json": + this.json(file.key, file.url, file.overwrite); + break; + + case "xml": + this.xml(file.key, file.url, file.overwrite); + break; + + case "script": + this.script(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "binary": + this.binary(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "spritesheet": + this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case "video": + this.video(file.key, file.urls); + break; + + case "audio": + this.audio(file.key, file.urls, file.autoDecode); + break; + + case "audiosprite": + this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode); + break; + + case "tilemap": + this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]); + break; + + case "physics": + this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]); + break; + + case "bitmapFont": + this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing); + break; + + case "atlasJSONArray": + this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasJSONHash": + this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasXML": + this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlas": + this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]); + break; + + case "shader": + this.shader(file.key, file.url, file.overwrite); + break; + } + } + + }, + + /** + * Transforms the asset URL. + * + * The default implementation prepends the baseURL if the url doesn't begin with http or // + * + * @method Phaser.Loader#transformUrl + * @protected + * @param {string} url - The url to transform. + * @param {object} file - The file object being transformed. + * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead. + */ + transformUrl: function (url, file) { + + if (!url) + { + return false; + } + + if (url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) + { + return url; + } + else + { + return this.baseURL + file.path + url; + } + + }, + + /** + * Start fetching a resource. + * + * All code paths, async or otherwise, from this function must return to `asyncComplete`. + * + * @method Phaser.Loader#loadFile + * @private + * @param {object} file + */ + loadFile: function (file) { + + // Image or Data? + switch (file.type) + { + case 'packfile': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'image': + case 'spritesheet': + case 'textureatlas': + case 'bitmapfont': + this.loadImageTag(file); + break; + + case 'audio': + file.url = this.getAudioURL(file.url); + + if (file.url) + { + // WebAudio or Audio Tag? + if (this.game.sound.usingWebAudio) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + else if (this.game.sound.usingAudioTag) + { + this.loadAudioTag(file); + } + } + else + { + this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support'); + } + break; + + case 'video': + file.url = this.getVideoURL(file.url); + + if (file.url) + { + if (file.asBlob) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'blob', this.fileComplete); + } + else + { + this.loadVideoTag(file); + } + } + else + { + this.fileError(file, null, 'No supported video URL specified or device does not have video playback support'); + } + break; + + case 'json': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + break; + + case 'xml': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete); + break; + + case 'tilemap': + + if (file.format === Phaser.Tilemap.TILED_JSON) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Tilemap.CSV) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete); + } + else + { + this.asyncComplete(file, "invalid Tilemap format: " + file.format); + } + break; + + case 'text': + case 'script': + case 'shader': + case 'physics': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'texture': + + if (file.key.split('_').pop() === 'truecolor') + { + this.loadImageTag(file); + } + else + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + break; + + case 'binary': + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + break; + } + + }, + + /** + * Continue async loading through an Image tag. + * @private + */ + loadImageTag: function (file) { + var _this = this; + + file.data = new Image(); + file.data.name = file.key; + + if (this.crossOrigin) + { + file.data.crossOrigin = this.crossOrigin; + } + + file.data.onload = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileComplete(file); + } + }; + + file.data.onerror = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileError(file); + } + }; + + file.data.src = this.transformUrl(file.url, file); + + // Image is immediately-available/cached + // Special Firefox magic, exclude from cached reload + // More info here: https://github.com/photonstorm/phaser/issues/2534 + if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height) + { + file.data.onload = null; + file.data.onerror = null; + this.fileComplete(file); + } + + }, + + /** + * Continue async loading through a Video tag. + * @private + */ + loadVideoTag: function (file) { + + var _this = this; + + file.data = document.createElement("video"); + file.data.name = file.key; + file.data.controls = false; + file.data.autoplay = false; + + var videoLoadEvent = function () { + + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = true; + Phaser.GAMES[_this.game.id].load.fileComplete(file); + + }; + + file.data.onerror = function () { + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = false; + _this.fileError(file); + }; + + file.data.addEventListener(file.loadEvent, videoLoadEvent, false); + + file.data.src = this.transformUrl(file.url, file); + file.data.load(); + + }, + + /** + * Continue async loading through an Audio tag. + * @private + */ + loadAudioTag: function (file) { + + var _this = this; + + if (this.game.sound.touchLocked) + { + // If audio is locked we can't do this yet, so need to queue this load request. Bum. + file.data = new Audio(); + file.data.name = file.key; + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + + this.fileComplete(file); + } + else + { + file.data = new Audio(); + file.data.name = file.key; + + var playThroughEvent = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileComplete(file); + }; + + file.data.onerror = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileError(file); + }; + + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + file.data.addEventListener('canplaythrough', playThroughEvent, false); + file.data.load(); + } + + }, + + /** + * Starts the xhr loader. + * + * This is designed specifically to use with asset file processing. + * + * @method Phaser.Loader#xhrLoad + * @private + * @param {object} file - The file/pack to load. + * @param {string} url - The URL of the file. + * @param {string} type - The xhr responseType. + * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments. + * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments. + */ + xhrLoad: function (file, url, type, onload, onerror) { + + var xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = type; + + if (this.headers['requestedWith'] !== false) + { + xhr.setRequestHeader('X-Requested-With', this.headers['requestedWith']); + } + + if (this.headers[file.type]) + { + xhr.setRequestHeader('Accept', this.headers[file.type]); + } + + onerror = onerror || this.fileError; + + var _this = this; + + xhr.onload = function () { + + try { + if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. + return onerror.call(_this, file, xhr); + } + else { + return onload.call(_this, file, xhr); + } + } catch (e) { + + // If this was the last file in the queue and an error is thrown in the create method + // then it's caught here, so be sure we don't carry on processing it + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + } + }; + + xhr.onerror = function () { + + try { + + return onerror.call(_this, file, xhr); + + } catch (e) { + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + + } + }; + + file.requestObject = xhr; + file.requestUrl = url; + + xhr.send(); + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getVideoURL + * @private + * @param {object[]|string[]} urls - See {@link #video} for format. + * @return {string} The URL to try and fetch; or null. + */ + getVideoURL: function (urls) { + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var videoType; + + if (url.uri) // {uri: .., type: ..} pair + { + videoType = url.type; + url = url.uri; + + if (this.game.device.canPlayVideo(videoType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + videoType = extension.toLowerCase(); + + if (this.game.device.canPlayVideo(videoType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getAudioURL + * @private + * @param {object[]|string[]} urls - See {@link #audio} for format. + * @return {string} The URL to try and fetch; or null. + */ + getAudioURL: function (urls) { + + if (this.game.sound.noAudio) + { + return null; + } + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var audioType; + + if (url.uri) // {uri: .., type: ..} pair + { + audioType = url.type; + url = url.uri; + + if (this.game.device.canPlayAudio(audioType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + audioType = extension.toLowerCase(); + + if (this.game.device.canPlayAudio(audioType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Error occurred when loading a file. + * + * @method Phaser.Loader#fileError + * @private + * @param {object} file + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + * @param {string} reason + */ + fileError: function (file, xhr, reason) { + + var url = file.requestUrl || this.transformUrl(file.url, file); + var message = 'error loading asset from URL ' + url; + + if (!reason && xhr) + { + reason = xhr.status; + } + + if (reason) + { + message = message + ' (' + reason + ')'; + } + + this.asyncComplete(file, message); + + }, + + /** + * Called when a file has been downloaded and needs to be processed further. + * + * @method Phaser.Loader#fileComplete + * @private + * @param {object} file - File loaded + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + */ + fileComplete: function (file, xhr) { + + var loadNext = true; + + switch (file.type) + { + case 'packfile': + + // Pack data must never be false-ish after it is fetched without error + var data = JSON.parse(xhr.responseText); + file.data = data || {}; + break; + + case 'texture': + + var extension = /\.([^.]+)$/.exec(file.url.split('?', 1)[0])[1].toLowerCase(); + if (file.data !== null) + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, file.data); + } + else + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, xhr.response); + } + break; + + case 'image': + + this.cache.addImage(file.key, file.url, file.data); + break; + + case 'spritesheet': + + this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case 'textureatlas': + + if (file.atlasURL == null) + { + this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); + } + else + { + // Load the JSON or XML before carrying on with the next file + loadNext = false; + + if (file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_HASH || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete); + } + else + { + throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); + } + } + break; + + case 'bitmapfont': + + if (!file.atlasURL) + { + this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing); + } + else + { + // Load the XML before carrying on with the next file + loadNext = false; + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) { + var json; + + try + { + // Try to parse as JSON, if it fails, then it's hopefully XML + json = JSON.parse(xhr.responseText); + } + catch (e) {} + + if (!!json) + { + file.atlasType = 'json'; + this.jsonLoadComplete(file, xhr); + } + else + { + file.atlasType = 'xml'; + this.xmlLoadComplete(file, xhr); + } + }); + } + break; + + case 'video': + + if (file.asBlob) + { + try + { + file.data = xhr.response; + } + catch (e) + { + throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key); + } + } + + this.cache.addVideo(file.key, file.url, file.data, file.asBlob); + break; + + case 'audio': + + if (this.game.sound.usingWebAudio) + { + file.data = xhr.response; + + this.cache.addSound(file.key, file.url, file.data, true, false); + + if (file.autoDecode) + { + this.game.sound.decode(file.key); + } + } + else + { + this.cache.addSound(file.key, file.url, file.data, false, true); + } + break; + + case 'text': + file.data = xhr.responseText; + this.cache.addText(file.key, file.url, file.data); + break; + + case 'shader': + file.data = xhr.responseText; + this.cache.addShader(file.key, file.url, file.data); + break; + + case 'physics': + var data = JSON.parse(xhr.responseText); + this.cache.addPhysicsData(file.key, file.url, data, file.format); + break; + + case 'script': + file.data = document.createElement('script'); + file.data.language = 'javascript'; + file.data.type = 'text/javascript'; + file.data.defer = false; + file.data.text = xhr.responseText; + document.head.appendChild(file.data); + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText); + } + break; + + case 'binary': + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.response); + } + else + { + file.data = xhr.response; + } + + this.cache.addBinary(file.key, file.data); + + break; + } + + if (loadNext) + { + this.asyncComplete(file); + } + + }, + + /** + * Successfully loaded a JSON file - only used for certain types. + * + * @method Phaser.Loader#jsonLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + jsonLoadComplete: function (file, xhr) { + + var data = JSON.parse(xhr.responseText); + + if (file.type === 'tilemap') + { + this.cache.addTilemap(file.key, file.url, data, file.format); + } + else if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'json') + { + this.cache.addJSON(file.key, file.url, data); + } + else + { + this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); + } + + this.asyncComplete(file); + }, + + /** + * Successfully loaded a CSV file - only used for certain types. + * + * @method Phaser.Loader#csvLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + csvLoadComplete: function (file, xhr) { + + var data = xhr.responseText; + + this.cache.addTilemap(file.key, file.url, data, file.format); + + this.asyncComplete(file); + + }, + + /** + * Successfully loaded an XML file - only used for certain types. + * + * @method Phaser.Loader#xmlLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + xmlLoadComplete: function (file, xhr) { + + // Always try parsing the content as XML, regardless of actually response type + var data = xhr.responseText; + var xml = this.parseXml(data); + + if (!xml) + { + var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest + console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')'); + this.asyncComplete(file, "invalid XML"); + return; + } + + if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'textureatlas') + { + this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); + } + else if (file.type === 'xml') + { + this.cache.addXML(file.key, file.url, xml); + } + + this.asyncComplete(file); + + }, + + /** + * Parses string data as XML. + * + * @method Phaser.Loader#parseXml + * @private + * @param {string} data - The XML text to parse + * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document. + */ + parseXml: function (data) { + + var xml; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + // Why is this 'false'? + xml.async = 'false'; + xml.loadXML(data); + } + } + catch (e) + { + xml = null; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + return null; + } + else + { + return xml; + } + + }, + + /** + * Update the loading sprite progress. + * + * @method Phaser.Loader#updateProgress + * @private + */ + updateProgress: function () { + + if (this.preloadSprite) + { + if (this.preloadSprite.direction === 0) + { + this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress); + } + else + { + this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress); + } + + if (this.preloadSprite.sprite) + { + this.preloadSprite.sprite.updateCrop(); + } + else + { + // We seem to have lost our sprite - maybe it was destroyed? + this.preloadSprite = null; + } + } + + }, + + /** + * Returns the number of files that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedFiles + * @protected + * @return {number} The number of files that have already been loaded (even if they errored) + */ + totalLoadedFiles: function () { + + return this._loadedFileCount; + + }, + + /** + * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedFiles + * @protected + * @return {number} The number of files that still remain in the load queue. + */ + totalQueuedFiles: function () { + + return this._totalFileCount - this._loadedFileCount; + + }, + + /** + * Returns the number of asset packs that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedPacks + * @protected + * @return {number} The number of asset packs that have already been loaded (even if they errored) + */ + totalLoadedPacks: function () { + + return this._totalPackCount; + + }, + + /** + * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedPacks + * @protected + * @return {number} The number of asset packs that still remain in the load queue. + */ + totalQueuedPacks: function () { + + return this._totalPackCount - this._loadedPackCount; + + } + +}; + +/** +* The non-rounded load progress value (from 0.0 to 100.0). +* +* A general indicator of the progress. +* It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. +* +* @name Phaser.Loader#progressFloat +* @property {number} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progressFloat", { + + get: function () { + var progress = (this._loadedFileCount / this._totalFileCount) * 100; + return Phaser.Math.clamp(progress || 0, 0, 100); + } + +}); + +/** +* The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}. +* +* @name Phaser.Loader#progress +* @property {integer} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progress", { + + get: function () { + return Math.round(this.progressFloat); + } + +}); + +Phaser.Loader.prototype.constructor = Phaser.Loader; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. +* +* @class Phaser.LoaderParser +*/ +Phaser.LoaderParser = { + + /** + * Alias for xmlBitmapFont, for backwards compatibility. + * + * @method Phaser.LoaderParser.bitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + bitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing, frame, resolution); + + }, + + /** + * Parse a Bitmap Font from an XML file. + * + * @method Phaser.LoaderParser.xmlBitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing; + data.chars = {}; + + var letters = xml.getElementsByTagName('char'); + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + for (var i = 0; i < letters.length; i++) + { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + data.chars[charCode] = { + x: x + parseInt(letters[i].getAttribute('x'), 10), + y: y + parseInt(letters[i].getAttribute('y'), 10), + width: parseInt(letters[i].getAttribute('width'), 10), + height: parseInt(letters[i].getAttribute('height'), 10), + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10) / resolution, + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10) / resolution, + xAdvance: (parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing) / resolution, + kerning: {} + }; + } + + var kernings = xml.getElementsByTagName('kerning'); + + for (i = 0; i < kernings.length; i++) + { + var first = parseInt(kernings[i].getAttribute('first'), 10); + var second = parseInt(kernings[i].getAttribute('second'), 10); + var amount = parseInt(kernings[i].getAttribute('amount'), 10) / resolution; + + data.chars[second].kerning[first] = amount; + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Parse a Bitmap Font from a JSON file. + * + * @method Phaser.LoaderParser.jsonBitmapFont + * @param {object} json - JSON data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = { + font: json.font.info._face, + size: parseInt(json.font.info._size, 10), + lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing, + chars: {} + }; + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + json.font.chars["char"].forEach( + + function parseChar(letter) { + + var charCode = parseInt(letter._id, 10); + + data.chars[charCode] = { + x: x + parseInt(letter._x, 10), + y: y + parseInt(letter._y, 10), + width: parseInt(letter._width, 10), + height: parseInt(letter._height, 10), + xOffset: parseInt(letter._xoffset, 10) / resolution, + yOffset: parseInt(letter._yoffset, 10) / resolution, + xAdvance: (parseInt(letter._xadvance, 10) + xSpacing) / resolution, + kerning: {} + }; + } + + ); + + if (json.font.kernings && json.font.kernings.kerning) + { + json.font.kernings.kerning.forEach( + + function parseKerning(kerning) { + + data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10) / resolution; + + } + + ); + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Finalize Bitmap Font parsing. + * + * @method Phaser.LoaderParser.finalizeBitmapFont + * @private + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {object} bitmapFontData - Pre-parsed bitmap font data. + * @return {object} The parsed Bitmap Font data. + */ + finalizeBitmapFont: function (baseTexture, bitmapFontData) { + + Object.keys(bitmapFontData.chars).forEach( + + function addTexture(charCode) { + + var letter = bitmapFontData.chars[charCode]; + + letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height)); + + } + + ); + + return bitmapFontData; + + }, + + /** + * Extract PVR header from loaded binary + * + * @method Phaser.LoaderParser.pvr + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PVR file including texture data. + */ + pvr: function (arrayBuffer) { + + // Reference: http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf + // PVR 3 header structure + // --------------------------------------- + // address: 0, size: 4 bytes version + // address: 4, size: 4 bytes flags + // address: 8, size: 8 bytes pixel format + // address: 16, size: 4 bytes color space + // address: 20, size: 4 bytes channel type + // address: 24, size: 4 bytes height + // address: 28, size: 4 bytes width + // address: 32, size: 4 bytes depth + // address: 36, size: 4 bytes number of surfaces + // address: 40, size: 4 bytes number of faces + // address: 44, size: 4 bytes number of mipmaps + // address: 48, size: 4 bytes meta data size + // --------------------------------------- + var uintArray = new Uint32Array(arrayBuffer.slice(0, 52)), + byteArray = new Uint8Array(arrayBuffer), + pvrHeader = null, + pixelFormat = (uintArray[3] << 32 | uintArray[2]), + compressionAlgorithm, + glExtensionFormat = 0; + + if (uintArray[0] === 0x03525650 && + [ // Validate WebGL Pixel Format + 0, 1, 2, 3, + 6, 7, 9, 11 + ].indexOf(pixelFormat) >= 0 + ) { + if (pixelFormat >= 0 && pixelFormat <= 3) { + compressionAlgorithm = 'PVRTC'; + } else if (pixelFormat >= 7 && pixelFormat <= 11) { + compressionAlgorithm = 'S3TC'; + } else if (pixelFormat === 6) { + compressionAlgorithm = 'ETC1'; + } + + switch (pixelFormat) { + case 0: + glExtensionFormat = 0x8C01; + break; + case 1: + glExtensionFormat = 0x8C03; + break; + case 2: + glExtensionFormat = 0x8C00; + break; + case 3: + glExtensionFormat = 0x8C02; + break; + case 6: + glExtensionFormat = 0x8D64; + break; + case 7: + glExtensionFormat = 0x83F1; + break; + case 9: + glExtensionFormat = 0x83F2; + break; + case 11: + glExtensionFormat = 0x83F3; + break; + default: + glExtensionFormat = -1; + } + + pvrHeader = { + complete: true, + fileFormat: 'PVR', + compressionAlgorithm: compressionAlgorithm, + flags: uintArray[1], + pixelFormat: pixelFormat, + colorSpace: uintArray[4], + channelType: uintArray[5], + height: uintArray[6], + width: uintArray[7], + depth: uintArray[8], + numberOfSurfaces: uintArray[9], + numberOfFaces: uintArray[10], + numberOfMipmaps: uintArray[11], + metaDataSize: uintArray[12], + textureData: byteArray.subarray(52 + uintArray[12], byteArray.byteLength), + glExtensionFormat: glExtensionFormat + }; + } + + return pvrHeader; + + }, + + /** + * Extract DDS header from loaded binary + * + * @method Phaser.LoaderParser.dds + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed DDS file including texture data. + */ + dds: function (arrayBuffer) { + + // Reference at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx + // DDS header structure + // --------------------------------------- + // address: 0, size: 4 bytes Identifier 'DDS ' + // address: 4, size: 4 bytes size + // address: 8, size: 4 bytes flags + // address: 12, size: 4 bytes height + // address: 16, size: 4 bytes width + // address: 20, size: 4 bytes pitch or linear size + // address: 24, size: 4 bytes depth + // address: 28, size: 4 bytes mipmap count + // address: 32, size: 44 bytes reserved space 1 + // address: 76, size: 4 pixel format size + // address: 80, size: 4 pixel format flag + // address: 84, size: 4 pixel format four CC + // address: 88, size: 4 pixel format bit count + // address: 92, size: 4 pixel format R bit mask + // address: 96, size: 4 pixel format G bit mask + // address: 100, size: 4 pixel format B bit mask + // address: 104, size: 4 pixel format A bit mask + // address: 108, size: 4 caps 1 + // address: 112, size: 4 caps 2 + // address: 116, size: 4 caps 3 + // address: 120, size: 4 caps 4 + // address: 124, size: 4 reserved 2 + // -- DXT10 extension + // address: 130, size: 4 DXGI Format + // address: 134, size: 4 resource dimension + // address: 138, size: 4 misc flag + // address: 142, size: 4 array size + // address: 146, size: 4 misc flag 2 + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ddsHeader = null; + + if (byteArray[0] === 0x44 && + byteArray[1] === 0x44 && + byteArray[2] === 0x53 && + byteArray[3] === 0x20) { + ddsHeader = { + complete: true, + fileFormat: 'DDS', + compressionAlgorithm: 'S3TC', + size: uintArray[1], + flags: uintArray[2], + height: uintArray[3], + width: uintArray[4], + pitch: uintArray[5], + depth: uintArray[6], + mipmapCount: uintArray[7], + formatSize: uintArray[19], + formatFlag: uintArray[19], + formatFourCC: [ + String.fromCharCode(byteArray[84]), + String.fromCharCode(byteArray[85]), + String.fromCharCode(byteArray[86]), + String.fromCharCode(byteArray[87]) + ].join(''), + formatBitCount: uintArray[21], + formatRBitMask: uintArray[22], + formatGBitMask: uintArray[23], + formatBBitMask: uintArray[24], + formatABitMask: uintArray[25], + caps1: uintArray[26], + caps2: uintArray[27], + caps3: uintArray[28], + caps4: uintArray[29], + reserved2: uintArray[30], + DXGIFormat: null, + resourceDimension: null, + miscFlag: null, + arraySize: null, + textureData: byteArray.subarray(uintArray[1] + 4, byteArray.byteLength) + }; + if (ddsHeader.formatFourCC === 'DX10') { + ddsHeader.DXGIFormat = uintArray[31]; + ddsHeader.resourceDimension = uintArray[32]; + ddsHeader.miscFlag = uintArray[33]; + ddsHeader.arraySize = uintArray[34]; + ddsHeader.miscFlag = uintArray[35]; + } + } + + return ddsHeader; + + }, + + /** + * Extract KTX header from loaded binary + * + * @method Phaser.LoaderParser.ktx + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed KTX file including texture data. + */ + ktx: function (arrayBuffer) { + + // Reference: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + // KTX header structure + // --------------------------------------- + // address: 0, size 12 bytes: Identifier '«KTX 11»\r\n\x1A\n' + // address: 12, size 4 bytes: endianness + // address: 16, size 4 bytes: GL type + // address: 20, size 4 bytes: GL type size + // address: 24, size 4 bytes: GL format + // address: 28, size 4 bytes: GL internal format + // address: 32, size 4 bytes: GL base internal format + // address: 36, size 4 bytes: pixel width + // address: 40, size 4 bytes: pixel height + // address: 44, size 4 bytes: pixel depth + // address: 48, size 4 bytes: number of array elements + // address: 52, size 4 bytes: number of faces + // address: 56, size 4 bytes: number of mipmap levels + // address: 60, size 4 bytes: bytes of key value data + // address: 64, size 4 bytes: key and value bytes size + // address: X, size 1 byte : key and value + // address: X, size 1 byte : value padding + // address: X, size 4 byte : image size + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ktxHeader = null, + imageSizeOffset = 16 + (uintArray[15] / 4) | 0, + imageSize = uintArray[imageSizeOffset], + glInternalFormat = uintArray[7], + compressionAlgorithm = 0; + + if (byteArray[0] === 0xAB && byteArray[1] === 0x4B && + byteArray[2] === 0x54 && byteArray[3] === 0x58 && + byteArray[4] === 0x20 && byteArray[5] === 0x31 && + byteArray[6] === 0x31 && byteArray[7] === 0xBB && + byteArray[8] === 0x0D && byteArray[9] === 0x0A && + byteArray[10] === 0x1A && byteArray[11] === 0x0A && + //Check if internal GL format is supported by WebGL + [ + // ETC1 + 0x8D64, + // PVRTC + 0x8C00, 0x8C01, 0x8C02, 0x8C03, + // DXTC | S3TC + 0x83F0, 0x83F1, 0x83F2, 0x83F3 + ].indexOf(glInternalFormat) >= 0) { + switch (glInternalFormat) { + case 0x8D64: + compressionAlgorithm = 'ETC1'; + break; + case 0x8C00: + case 0x8C01: + case 0x8C02: + case 0x8C03: + compressionAlgorithm = 'PVRTC'; + break; + case 0x83F0: + case 0x83F1: + case 0x83F2: + case 0x83F3: + compressionAlgorithm = 'S3TC'; + break; + } + + ktxHeader = { + complete: true, + fileFormat: 'KTX', + compressionAlgorithm: compressionAlgorithm, + endianness: uintArray[3], + glType: uintArray[4], + glTypeSize: uintArray[5], + glFormat: uintArray[6], + glInternalFormat: uintArray[7], + glBaseInternalFormat: uintArray[8], + width: uintArray[9], + height: uintArray[10], + pixelDepth: uintArray[11], + numberOfArrayElements: uintArray[12], + numberOfFaces: uintArray[13], + numberOfMipmapLevels: uintArray[14], + bytesOfKeyValueData: uintArray[15], + keyAndValueByteSize: uintArray[16], + imageSize: imageSize, + textureData: byteArray.subarray((imageSizeOffset + 1) * 4, imageSize + 100) + }; + } + + return ktxHeader; + + }, + + /** + * Extract PKM header from loaded binary + * + * @method Phaser.LoaderParser.pkm + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PKM file including texture data. + */ + pkm: function (arrayBuffer) { + + // PKM header structure + // --------------------------------------- + // address: 0, size 4 bytes: for 'PKM ' + // address: 4, size 2 bytes: for version + // address: 6, size 2 bytes: for type + // address: 8, size 2 bytes: for extended width + // address: 10, size 2 bytes: for extended height + // address: 12, size 2 bytes: for original width + // address: 14, size 2 bytes: for original height + // address: 16, texture data + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + pkmHeader = null; + + if (byteArray[0] === 0x50 && + byteArray[1] === 0x4B && + byteArray[2] === 0x4D && + byteArray[3] === 0x20) { + + pkmHeader = { + complete: true, + fileFormat: 'PKM', + compressionAlgorithm: 'ETC1', + format: ((byteArray[6] << 8 | byteArray[7])) & 0xFFFF, + width: ((byteArray[8] << 8 | byteArray[9])) & 0xFFFF, + height: ((byteArray[10] << 8 | byteArray[11])) & 0xFFFF, + originalWidth: ((byteArray[12] << 8 | byteArray[13])) & 0xFFFF, + originalHeight: ((byteArray[14] << 8 | byteArray[15])) & 0xFFFF, + textureData: byteArray.subarray(16, byteArray.length) + }; + } + + return pkmHeader; + + } + +}; + +/** + * @author Jeremy Dowell + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * Audio Sprites are a combination of audio files and a JSON configuration. + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * @class Phaser.AudioSprite + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + * @param {string} key - Asset key for the sound. + */ +Phaser.AudioSprite = function (game, key) { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * Asset key for the Audio Sprite. + * @property {string} key + */ + this.key = key; + + /** + * JSON audio atlas object. + * @property {object} config + */ + this.config = this.game.cache.getJSON(key + '-audioatlas'); + + /** + * If a sound is set to auto play, this holds the marker key of it. + * @property {string} autoplayKey + */ + this.autoplayKey = null; + + /** + * Is a sound set to autoplay or not? + * @property {boolean} autoplay + * @default + */ + this.autoplay = false; + + /** + * An object containing the Phaser.Sound objects for the Audio Sprite. + * @property {object} sounds + */ + this.sounds = {}; + + for (var k in this.config.spritemap) + { + var marker = this.config.spritemap[k]; + var sound = this.game.add.sound(this.key); + + sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop); + + this.sounds[k] = sound; + } + + if (this.config.autoplay) + { + this.autoplayKey = this.config.autoplay; + this.play(this.autoplayKey); + this.autoplay = this.sounds[this.autoplayKey]; + } + +}; + +Phaser.AudioSprite.prototype = { + + /** + * Play a sound with the given name. + * + * @method Phaser.AudioSprite#play + * @param {string} [marker] - The name of sound to play + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, volume) { + + if (volume === undefined) { volume = 1; } + + return this.sounds[marker].play(marker, null, volume); + + }, + + /** + * Stop a sound with the given name. + * + * @method Phaser.AudioSprite#stop + * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite. + */ + stop: function (marker) { + + if (!marker) + { + for (var key in this.sounds) + { + this.sounds[key].stop(); + } + } + else + { + this.sounds[marker].stop(); + } + + }, + + /** + * Get a sound with the given name. + * + * @method Phaser.AudioSprite#get + * @param {string} marker - The name of sound to get. + * @return {Phaser.Sound} The sound instance. + */ + get: function(marker) { + + return this.sounds[marker]; + + } + +}; + +Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound class constructor. +* +* @class Phaser.Sound +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {string} key - Asset key for the sound. +* @param {number} [volume=1] - Default value for the volume, between 0 and 1. +* @param {boolean} [loop=false] - Whether or not the sound will loop. +*/ +Phaser.Sound = function (game, key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = game.sound.connectToMaster; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * @property {string} name - Name of the sound. + */ + this.name = key; + + /** + * @property {string} key - Asset key for the sound. + */ + this.key = key; + + /** + * @property {boolean} loop - Whether or not the sound or current sound marker will loop. + */ + this.loop = loop; + + /** + * @property {object} markers - The sound markers. + */ + this.markers = {}; + + /** + * @property {AudioContext} context - Reference to the AudioContext instance. + */ + this.context = null; + + /** + * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically. + */ + this.autoplay = false; + + /** + * @property {number} totalDuration - The total duration of the sound in seconds. + */ + this.totalDuration = 0; + + /** + * @property {number} startTime - The time the sound starts at in ms (typically 0 unless starting from a marker). + * @default + */ + this.startTime = 0; + + /** + * @property {number} currentTime - The current time of sound playback in ms. + */ + this.currentTime = 0; + + /** + * @property {number} duration - The duration of the current sound marker in seconds. + */ + this.duration = 0; + + /** + * @property {number} durationMS - The duration of the current sound marker in ms. + */ + this.durationMS = 0; + + /** + * @property {number} position - The position of the current sound marker in ms. + */ + this.position = 0; + + /** + * @property {number} stopTime - The time the sound stopped in ms. + */ + this.stopTime = 0; + + /** + * @property {boolean} paused - true if the sound is paused, otherwise false. + * @default + */ + this.paused = false; + + /** + * @property {number} pausedPosition - The position the sound had reached when it was paused in ms. + */ + this.pausedPosition = 0; + + /** + * @property {number} pausedTime - The game time (ms) at which the sound was paused. + */ + this.pausedTime = 0; + + /** + * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false. + * @default + */ + this.isPlaying = false; + + /** + * @property {string} currentMarker - The string ID of the currently playing marker, if any. + * @default + */ + this.currentMarker = ''; + + /** + * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. + */ + this.fadeTween = null; + + /** + * @property {boolean} pendingPlayback - true if the sound file is pending playback + * @readonly + */ + this.pendingPlayback = false; + + /** + * @property {boolean} override - if true when you play this sound it will always start from the beginning. + * @default + */ + this.override = false; + + /** + * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. + * @default + */ + this.allowMultiple = false; + + /** + * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio. + * @readonly + */ + this.usingWebAudio = this.game.sound.usingWebAudio; + + /** + * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag. + */ + this.usingAudioTag = this.game.sound.usingAudioTag; + + /** + * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. + */ + this.externalNode = null; + + /** + * @property {object} masterGainNode - The master gain node in a Web Audio system. + */ + this.masterGainNode = null; + + /** + * @property {object} gainNode - The gain node in a Web Audio system. + */ + this.gainNode = null; + + /** + * @property {object} _sound - Internal var. + * @private + */ + this._sound = null; + + /** + * @property {object} _globalVolume - Internal var for keeping track of global volume when using AudioTag + * @private + */ + this._globalVolume = 1; + + /** + * @property {boolean} _markedToDelete - When audio stops, disconnect Web Audio nodes. + * @private + */ + this._markedToDelete = false; + + /** + * @property {boolean} _removeFromSoundManager - When audio stops, remove it from the Sound Manager and destroy it. + * @private + */ + this._removeFromSoundManager = false; + + + + if (this.usingWebAudio) + { + this.context = this.game.sound.context; + this.masterGainNode = this.game.sound.masterGain; + + if (this.context.createGain === undefined) + { + this.gainNode = this.context.createGainNode(); + } + else + { + this.gainNode = this.context.createGain(); + } + + this.gainNode.gain.value = volume; + + if (connect) + { + this.gainNode.connect(this.masterGainNode); + } + } + else if (this.usingAudioTag) + { + if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key)) + { + this._sound = this.game.cache.getSoundData(key); + this.totalDuration = 0; + + if (this._sound.duration) + { + this.totalDuration = this._sound.duration; + } + } + else + { + this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this); + } + } + + /** + * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files). It passes one argument, this sound. + */ + this.onDecoded = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played or a looping marker is restarted. It passes one argument, this sound. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. It passes one argument, this sound. + */ + this.onPause = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. It passes one argument, this sound. + */ + this.onResume = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. It passes one argument, this sound. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback or when a non-looping marker completes. It passes two arguments: this sound and any {@link #currentMarker marker} that was playing. + */ + this.onStop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted. It passes one argument, this sound. + */ + this.onMute = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. It passes two arguments: the {@link #currentMarker} and this sound. + */ + this.onMarkerComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out. It passes two arguments: this sound and its current {@link #volume}. + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + */ + this._volume = volume; + + /** + * @property {any} _buffer - Decoded data buffer / Audio tag. + * @private + */ + this._buffer = null; + + /** + * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. + * @private + */ + this._muted = false; + + /** + * @property {number} _tempMarker - Internal marker var. + * @private + */ + this._tempMarker = 0; + + /** + * @property {number} _tempPosition - Internal marker var. + * @private + */ + this._tempPosition = 0; + + /** + * @property {number} _tempVolume - Internal marker var. + * @private + */ + this._tempVolume = 0; + + /** + * @property {number} _tempPause - Internal marker var. + * @private + */ + this._tempPause = 0; + + /** + * @property {number} _muteVolume - Internal cache var. + * @private + */ + this._muteVolume = 0; + + /** + * @property {boolean} _tempLoop - Internal cache var. + * @private + */ + this._tempLoop = 0; + + /** + * @property {boolean} _paused - Was this sound paused via code or a game event? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched? + * @private + */ + this._onDecodedEventDispatched = false; + +}; + +Phaser.Sound.prototype = { + + /** + * Called automatically when this sound is unlocked. + * @method Phaser.Sound#soundHasUnlocked + * @param {string} key - The Phaser.Cache key of the sound file to check for decoding. + * @protected + */ + soundHasUnlocked: function (key) { + + if (key === this.key) + { + this._sound = this.game.cache.getSoundData(this.key); + this.totalDuration = this._sound.duration; + } + + }, + + /** + * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound#addMarker + * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. + * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). + * @param {boolean} [loop=false] - Sets if the sound will loop or not. + */ + addMarker: function (name, start, duration, volume, loop) { + + if (duration === undefined || duration === null) { duration = 1; } + if (volume === undefined || volume === null) { volume = 1; } + if (loop === undefined) { loop = false; } + + this.markers[name] = { + name: name, + start: start, + stop: start + duration, + volume: volume, + duration: duration, + durationMS: duration * 1000, + loop: loop + }; + + }, + + /** + * Removes a marker from the sound. + * @method Phaser.Sound#removeMarker + * @param {string} name - The key of the marker to remove. + */ + removeMarker: function (name) { + + delete this.markers[name]; + + }, + + /** + * Called automatically by the AudioContext when the sound stops playing. + * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. + * + * @method Phaser.Sound#onEndedHandler + * @protected + */ + onEndedHandler: function () { + + this._sound.onended = null; + this.isPlaying = false; + this.currentTime = this.durationMS; + this.stop(); + + if (this._markedToDelete) + { + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + if (this._removeFromSoundManager) + { + this.game.sound.remove(this); + } + else + { + 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(); + } + } + }, + + /** + * Called automatically by Phaser.SoundManager. + * @method Phaser.Sound#update + * @protected + */ + update: function () { + + if (!this.game.cache.checkSoundKey(this.key)) + { + this.destroy(); + return; + } + + if (this.isDecoded && !this._onDecodedEventDispatched) + { + this.onDecoded.dispatch(this); + this._onDecodedEventDispatched = true; + } + + if (this.pendingPlayback && this.game.cache.isSoundReady(this.key)) + { + this.pendingPlayback = false; + this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop); + } + + if (this.isPlaying) + { + this.currentTime = this.game.time.time - this.startTime; + + if (this.currentTime >= this.durationMS) + { + if (this.usingWebAudio) + { + if (this.loop) + { + // won't work with markers, needs to reset the position + this.onLoop.dispatch(this); + + // Gets reset by the play function + this.isPlaying = false; + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + this.isPlaying = true; // play not called again in this case + } + else + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + this.play(this.currentMarker, 0, this.volume, true, true); + } + } + else + { + // Stop if we're using an audio marker, otherwise we let onended handle it + if (this.currentMarker !== '') + { + this.stop(); + } + } + } + else + { + if (this.loop) + { + this.onLoop.dispatch(this); + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + } + + // Gets reset by the play function + this.isPlaying = false; + + this.play(this.currentMarker, 0, this.volume, true, true); + } + else + { + this.stop(); + } + } + } + } + }, + + /** + * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters. + * + * @method Phaser.Sound#loopFull + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + loopFull: function (volume) { + + return this.play(null, 0, volume, true); + + }, + + /** + * Play this sound, or a marked section of it. + * + * @method Phaser.Sound#play + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. + * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, position, volume, loop, forceRestart) { + + if (marker === undefined || marker === false || marker === null) { marker = ''; } + if (forceRestart === undefined) { forceRestart = true; } + + if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override) + { + // Use Restart instead + return this; + } + + if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart)) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) { + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + + this.isPlaying = false; + } + + if (marker === '' && Object.keys(this.markers).length > 0) + { + // If they didn't specify a marker but this is an audio sprite, + // we should never play the entire thing + return this; + } + + if (marker !== '') + { + if (this.markers[marker]) + { + this.currentMarker = marker; + + // Playing a marker? Then we default to the marker values + 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 (volume === undefined) { volume = this._volume; } + if (loop === undefined) { loop = this.loop; } + + this.position = Math.max(0, 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) + { + // Does the sound need decoding? + if (this.game.cache.isSoundDecoded(this.key)) + { + this._sound = this.context.createBufferSource(); + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + this._buffer = this.game.cache.getSoundData(this.key); + this._sound.buffer = this._buffer; + + if (this.loop && marker === '') + { + this._sound.loop = true; + } + + if (!this.loop && marker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + this.totalDuration = this._sound.buffer.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = Math.ceil(this.totalDuration * 1000); + } + + // Useful to cache this somewhere perhaps? + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, this.position, this.duration); + } + else + { + if (this.loop && marker === '') + { + this._sound.start(0, 0); + } + else + { + this._sound.start(0, this.position, this.duration); + } + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + 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 doesn't become available until you call play(), wonderful ... + this.totalDuration = this._sound.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = this.totalDuration * 1000; + } + + this._sound.currentTime = this.position; + this._sound.muted = this._muted; + + if (this._muted || this.game.sound.mute) + { + this._sound.volume = 0; + } + else + { + this._sound.volume = this._volume; + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + this.currentTime = 0; + this.stopTime = this.startTime + this.durationMS; + + this.onPlay.dispatch(this); + } + else + { + this.pendingPlayback = true; + } + } + } + + return this; + + }, + + /** + * Restart the sound, or a marked section of it. + * + * @method Phaser.Sound#restart + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. + * @param {boolean} [loop=false] - Loop when it finished playing? + */ + restart: function (marker, position, volume, loop) { + + marker = marker || ''; + position = position || 0; + volume = volume || 1; + if (loop === undefined) { loop = false; } + + this.play(marker, position, volume, loop, true); + + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound#pause + */ + pause: function () { + + if (this.isPlaying && this._sound) + { + this.paused = true; + this.pausedPosition = this.currentTime; + this.pausedTime = this.game.time.time; + this._tempPause = this._sound.currentTime; + this.onPause.dispatch(this); + this.stop(); + } + + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound#resume + */ + resume: function () { + + if (this.paused && this._sound) + { + if (this.usingWebAudio) + { + var p = Math.max(0, this.position + (this.pausedPosition / 1000)); + + this._sound = this.context.createBufferSource(); + this._sound.buffer = this._buffer; + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + if (this.loop) + { + this._sound.loop = true; + } + + if (!this.loop && this.currentMarker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + var duration = this.duration - (this.pausedPosition / 1000); + + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, p, duration); + //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it + } + else + { + if (this.loop && this.game.device.chrome) + { + // Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099 + if (this.game.device.chromeVersion === 42) + { + this._sound.start(0); + } + else + { + this._sound.start(0, p); + } + } + else + { + this._sound.start(0, p, duration); + } + } + } + else + { + this._sound.currentTime = this._tempPause; + this._sound.play(); + } + + this.isPlaying = true; + this.paused = false; + this.startTime += (this.game.time.time - this.pausedTime); + this.onResume.dispatch(this); + } + + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound#stop + */ + stop: function () { + + if (this.isPlaying && this._sound) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) + { + // Thanks Android 4.4 + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + } + + this.pendingPlayback = false; + this.isPlaying = false; + + if (!this.paused) + { + var prevMarker = this.currentMarker; + + if (this.currentMarker !== '') + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + } + + this.currentMarker = ''; + + if (this.fadeTween !== null) + { + this.fadeTween.stop(); + } + + this.onStop.dispatch(this, prevMarker); + } + + }, + + /** + * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. + * Then increases the volume from 0 to 1 over the duration specified. + * + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (1) as the second parameter. + * + * @method Phaser.Sound#fadeIn + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in. + * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. + * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. + */ + fadeIn: function (duration, loop, marker) { + + if (loop === undefined) { loop = false; } + if (marker === undefined) { marker = this.currentMarker; } + + if (this.paused) + { + return; + } + + this.play(marker, 0, 0, loop); + + this.fadeTo(duration, 1); + + }, + + /** + * Decreases the volume of this Sound from its current value to 0 over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (0) as the second parameter. + * + * @method Phaser.Sound#fadeOut + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out. + */ + fadeOut: function (duration) { + + this.fadeTo(duration, 0); + + }, + + /** + * Fades the volume of this Sound from its current value to the given volume over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (volume) as the second parameter. + * + * @method Phaser.Sound#fadeTo + * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out. + * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1. + */ + fadeTo: function (duration, volume) { + + if (!this.isPlaying || this.paused || volume === this.volume) + { + return; + } + + if (duration === undefined) { duration = 1000; } + + if (volume === undefined) + { + console.warn("Phaser.Sound.fadeTo: No Volume Specified."); + return; + } + + this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true); + + this.fadeTween.onComplete.add(this.fadeComplete, this); + + }, + + /** + * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo. + * + * @method Phaser.Sound#fadeComplete + * @private + */ + fadeComplete: function () { + + this.onFadeComplete.dispatch(this, this.volume); + + if (this.volume === 0) + { + this.stop(); + } + + }, + + /** + * Called automatically by SoundManager.volume. + * + * Sets the volume of AudioTag Sounds as a percentage of the Global Volume. + * + * You should not normally call this directly. + * + * @method Phaser.Sound#updateGlobalVolume + * @protected + * @param {float} globalVolume - The global SoundManager volume. + */ + updateGlobalVolume: function (globalVolume) { + + // this._volume is the % of the global volume this sound should be played at + + if (this.usingAudioTag && this._sound) + { + this._globalVolume = globalVolume; + this._sound.volume = this._globalVolume * this._volume; + } + + }, + + /** + * Destroys this sound and all associated events and removes it from the SoundManager. + * + * @method Phaser.Sound#destroy + * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager. + */ + destroy: function (remove) { + + if (remove === undefined) { remove = true; } + + this._markedToDelete = true; + this._removeFromSoundManager = remove; + this.stop(); + + if (remove) + { + this.game.sound.remove(this); + } + else + { + 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; + +/** +* @name Phaser.Sound#isDecoding +* @property {boolean} isDecoding - Returns true if the sound file is still decoding. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoding", { + + get: function () { + return this.game.cache.getSound(this.key).isDecoding; + } + +}); + +/** +* @name Phaser.Sound#isDecoded +* @property {boolean} isDecoded - Returns true if the sound file has decoded. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoded", { + + get: function () { + return this.game.cache.isSoundDecoded(this.key); + } + +}); + +/** +* @name Phaser.Sound#mute +* @property {boolean} mute - Gets or sets the muted state of this sound. +*/ +Object.defineProperty(Phaser.Sound.prototype, "mute", { + + get: function () { + + return (this._muted || this.game.sound.mute); + + }, + + set: function (value) { + + value = value || false; + + if (value === this._muted) + { + return; + } + + if (value) + { + this._muted = true; + this._muteVolume = this._tempVolume; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = 0; + } + else if (this.usingAudioTag && this._sound) + { + 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); + + } + +}); + +/** +* @name Phaser.Sound#volume +* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Sound.prototype, "volume", { + + get: function () { + return this._volume; + }, + + set: function (value) { + + // Causes an Index size error if you don't clamp the value + if (this.usingAudioTag) + { + value = this.game.math.clamp(value, 0, 1); + } + + if (this._muted) + { + this._muteVolume = value; + return; + } + + this._tempVolume = value; + this._volume = value; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = value; + } + else if (this.usingAudioTag && this._sound) + { + this._sound.volume = this._globalVolume * value; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. +* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. +* The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. +* There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ +* +* If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out +* of AudioContext nodes. If this is the case create a global var called {@link PhaserGlobal} on the window object before creating the game. The active +* AudioContext will then be saved to `window.PhaserGlobal.audioContext` when the Phaser game is destroyed, and re-used when it starts again. +* +* Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. +* When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. +* The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will +* be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. +* +* @class Phaser.SoundManager +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.SoundManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) + */ + this.onSoundDecode = new Phaser.Signal(); + + /** + * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. + * @property {Phaser.Signal} onVolumeChange + */ + this.onVolumeChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. + * @property {Phaser.Signal} onMute + */ + this.onMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. + * @property {Phaser.Signal} onUnMute + */ + this.onUnMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is touch-unlocked. + * If the device doesn't {@link Phaser.Device.needsTouchUnlock need touch-unlocking}, the signal won't be dispatched. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * @property {AudioContext} context - The AudioContext being used for playback. + * @default + */ + this.context = null; + + /** + * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio. + * @readonly + */ + this.usingWebAudio = false; + + /** + * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio. + * @readonly + */ + this.usingAudioTag = false; + + /** + * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. + * @default + */ + this.noAudio = false; + + /** + * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. + * @default + */ + this.connectToMaster = true; + + /** + * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. + * @default + */ + this.touchLocked = false; + + /** + * @property {number} channels - The number of audio channels to use in playback. + * @default + */ + this.channels = 32; + + /** + * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), + * or set to false to keep audio playing, regardless of the game pause state. You may need to + * do this should you wish to control audio muting via external DOM buttons or similar. + * @property {boolean} muteOnPause + * @default + */ + this.muteOnPause = true; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {AudioContext} _unlockSource - Internal unlock tracking var. + * @private + * @default + */ + this._unlockSource = null; + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + * @default + */ + this._volume = 1; + + + /** + * @property {array} _sounds - An array containing all the sounds + * @private + */ + this._sounds = []; + + /** + * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status. + * @private + */ + this._watchList = new Phaser.ArraySet(); + + /** + * @property {boolean} _watching - Is the SoundManager monitoring the watchList? + * @private + */ + this._watching = false; + + /** + * @property {function} _watchCallback - The callback to invoke once the watchlist is clear. + * @private + */ + this._watchCallback = null; + + /** + * @property {object} _watchContext - The context in which to call the watchlist callback. + * @private + */ + this._watchContext = null; + +}; + +Phaser.SoundManager.prototype = { + + /** + * Initialises the sound manager. + * @method Phaser.SoundManager#boot + * @protected + */ + boot: function () { + + var device = this.game.device; + var PhaserGlobal = window.PhaserGlobal; + + if (device.iOS && device.webAudio === false) + { + this.channels = 1; + } + + // PhaserGlobal overrides + if (PhaserGlobal) + { + // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class) + if (PhaserGlobal.disableAudio === true) + { + this.noAudio = true; + this.touchLocked = false; + return; + } + + // Check if the Web Audio API is disabled (for testing Audio Tag playback during development) + if (PhaserGlobal.disableWebAudio === true) + { + this.usingAudioTag = true; + this.touchLocked = false; + return; + } + } + + if (PhaserGlobal && PhaserGlobal.audioContext) + { + this.context = PhaserGlobal.audioContext; + } + else + { + if (!!window['AudioContext']) + { + try { + this.context = new window['AudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + else if (!!window['webkitAudioContext']) + { + try { + this.context = new window['webkitAudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + } + + if (this.context === null) + { + // No Web Audio support - how about legacy Audio? + if (window['Audio'] === undefined) + { + this.noAudio = true; + return; + } + else + { + this.usingAudioTag = true; + } + } + else + { + this.usingWebAudio = true; + + if (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); + } + + if (!this.noAudio) + { + // On mobile we need a native touch event before we can play anything, so capture it here + if (device.needsTouchUnlock()) + { + this.setTouchLock(); + } + } + + if (this.usingWebAudio && device.chrome && device.chromeVersion <= 65) + { + console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. '); + } + + }, + + /** + * Sets the Input Manager touch callback to be SoundManager.unlock. + * Required for iOS audio device unlocking. Mostly just used internally. + * + * @method Phaser.SoundManager#setTouchLock + */ + setTouchLock: function () { + + if (this.noAudio || (window.PhaserGlobal && window.PhaserGlobal.disableAudio === true)) + { + return; + } + + this.game.input.addTouchLockCallback(this.unlock, this, true); + + this.touchLocked = true; + + }, + + /** + * Turns off {@link #touchLocked} and dispatches {@link #onTouchUnlock}. + * + * @method Phaser.SoundManager#setTouchUnlock + * @private + */ + setTouchUnlock: function () { + + this.touchLocked = false; + this._unlockSource = null; + this.onTouchUnlock.dispatch(); + + }, + + /** + * Enables the audio, usually after the first touch. + * + * @method Phaser.SoundManager#unlock + * @return {boolean} True if the callback should be removed, otherwise false. + */ + unlock: function () { + + if (this.noAudio || !this.touchLocked || this._unlockSource !== null) + { + return true; + } + + // Global override (mostly for Audio Tag testing) + if (this.usingAudioTag) + { + this.setTouchUnlock(); + } + else if (this.usingWebAudio) + { + // Create empty buffer and play it + // The SoundManager.update loop captures the state of it and then resets touchLocked to false + + var buffer = this.context.createBuffer(1, 1, 22050); + this._unlockSource = this.context.createBufferSource(); + this._unlockSource.buffer = buffer; + this._unlockSource.connect(this.context.destination); + + if (this._unlockSource.start === undefined) + { + this._unlockSource.noteOn(0); + } + else + { + this._unlockSource.start(0); + } + + //This fixes locked audio in Chrome > 55 cross origin iframes + if (this._unlockSource.context.state === 'suspended') { + this._unlockSource.context.resume(); + } + } + + // We can remove the event because we've done what we needed (started the unlock sound playing) + return true; + + }, + + /** + * Stops all the sounds in the game. + * + * @method Phaser.SoundManager#stopAll + */ + stopAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].stop(); + } + } + + }, + + /** + * Pauses all the sounds in the game. + * + * @method Phaser.SoundManager#pauseAll + */ + pauseAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].pause(); + } + } + + }, + + /** + * Resumes every sound in the game. + * + * @method Phaser.SoundManager#resumeAll + */ + resumeAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].resume(); + } + } + + }, + + /** + * Decode a sound by its asset key. + * + * @method Phaser.SoundManager#decode + * @param {string} key - Assets key of the sound to be decoded. + * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. + */ + decode: function (key, sound) { + + sound = sound || null; + + var soundData = this.game.cache.getSoundData(key); + + if (soundData) + { + if (this.game.cache.isSoundDecoded(key) === false) + { + this.game.cache.updateSound(key, 'isDecoding', true); + + var _this = this; + + try { + this.context.decodeAudioData(soundData, function (buffer) { + + if (buffer) + { + _this.game.cache.decodedSound(key, buffer); + _this.onSoundDecode.dispatch(key, sound); + } + }); + } + catch (e) {} + } + } + + }, + + /** + * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback. + * Once all of the Sound files have finished decoding the callback will be invoked. + * The amount of time spent decoding depends on the codec used and file size. + * If all of the files given have already decoded the callback is triggered immediately. + * + * @method Phaser.SoundManager#setDecodedCallback + * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache. + * @param {Function} callback - The callback which will be invoked once all files have finished decoding. + * @param {Object} callbackContext - The context in which the callback will run. + */ + setDecodedCallback: function (files, callback, callbackContext) { + + if (typeof files === 'string') + { + files = [ files ]; + } + + this._watchList.reset(); + + for (var i = 0; i < files.length; i++) + { + if (files[i] instanceof Phaser.Sound) + { + if (!this.game.cache.isSoundDecoded(files[i].key)) + { + this._watchList.add(files[i].key); + } + } + else if (!this.game.cache.isSoundDecoded(files[i])) + { + this._watchList.add(files[i]); + } + } + + // All decoded already? + if (this._watchList.total === 0) + { + this._watching = false; + callback.call(callbackContext); + } + else + { + this._watching = true; + this._watchCallback = callback; + this._watchContext = callbackContext; + } + + }, + + /** + * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. + * + * @method Phaser.SoundManager#update + * @protected + */ + update: function () { + + if (this.noAudio) + { + return; + } + + if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE)) + { + this.setTouchUnlock(); + } + + for (var i = 0; i < this._sounds.length; i++) + { + this._sounds[i].update(); + } + + if (this._watching) + { + var key = this._watchList.first; + + while (key) + { + if (this.game.cache.isSoundDecoded(key)) + { + this._watchList.remove(key); + } + + key = this._watchList.next; + } + + if (this._watchList.total === 0) + { + this._watching = false; + this._watchCallback.call(this._watchContext); + } + } + + }, + + /** + * Adds a new Sound into the SoundManager. + * + * @method Phaser.SoundManager#add + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The new sound instance. + */ + add: function (key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = this.connectToMaster; } + + var sound = new Phaser.Sound(this.game, key, volume, loop, connect); + + this._sounds.push(sound); + + return sound; + + }, + + /** + * Adds a new AudioSprite into the SoundManager. + * + * @method Phaser.SoundManager#addSprite + * @param {string} key - Asset key for the sound. + * @return {Phaser.AudioSprite} The new AudioSprite instance. + */ + addSprite: function(key) { + + var audioSprite = new Phaser.AudioSprite(this.game, key); + + return audioSprite; + + }, + + /** + * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. + * + * @method Phaser.SoundManager#remove + * @param {Phaser.Sound} sound - The sound object to remove. + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ + remove: function (sound) { + + var i = this._sounds.length; + + while (i--) + { + if (this._sounds[i] === sound) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Removes all Sounds from the SoundManager. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeAll + */ + removeAll: function () { + + this.stopAll(); + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].destroy(); + } + } + + this._sounds.length = 0; + + }, + + /** + * Removes all Sounds from the SoundManager that have an asset key matching the given value. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeByKey + * @param {string} key - The key to match when removing sound objects. + * @return {number} The number of matching sound objects that were removed. + */ + removeByKey: function (key) { + + var i = this._sounds.length; + var removed = 0; + + while (i--) + { + if (this._sounds[i].key === key) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + removed++; + } + } + + return removed; + + }, + + /** + * Adds a new Sound into the SoundManager and starts it playing. + * + * @method Phaser.SoundManager#play + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @return {Phaser.Sound} The new sound instance. + */ + play: function (key, volume, loop) { + + if (this.noAudio) + { + return; + } + + var sound = this.add(key, volume, loop); + + sound.play(); + + return sound; + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + if (this.usingWebAudio) + { + this._muteVolume = this.masterGain.gain.value; + this.masterGain.gain.value = 0; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = true; + } + } + + this.onMute.dispatch(); + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = this._muteVolume; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = false; + } + } + + this.onUnMute.dispatch(); + + }, + + /** + * Stops all the sounds in the game, then destroys them and finally clears up any callbacks. + * + * @method Phaser.SoundManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.onSoundDecode.dispose(); + + if (this.context) + { + if (window.PhaserGlobal) + { + // Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing + window.PhaserGlobal.audioContext = this.context; + } + else + { + if (this.context.close) + { + this.context.close(); + } + } + } + + } + +}; + +Phaser.SoundManager.prototype.constructor = Phaser.SoundManager; + +/** +* @name Phaser.SoundManager#mute +* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || false; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* @name Phaser.SoundManager#volume +* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "volume", { + + get: function () { + + return this._volume; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this._volume !== value) + { + this._volume = value; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = value; + } + else + { + // Loop through the sound cache and change the volume of all html audio tags + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].updateGlobalVolume(value); + } + } + } + + this.onVolumeChange.dispatch(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* The ScaleManager object handles the the scaling, resizing, and alignment of the +* Game size and the game Display canvas. +* +* The Game size is the logical size of the game; the Display canvas has size as an HTML element. +* +* The calculations of these are heavily influenced by the bounding Parent size which is the computed +* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the +* canvas's Parent element play an important role_ in the operation of the ScaleManager. +* +* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size. +* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}). +* +* #### Parent and Display canvas containment guidelines: +* +* - Style the Parent element (of the game canvas) to control the Parent size and +* thus the Display canvas's size and layout. +* +* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior. +* +* - The Parent element should _not_ apply a padding as this is not accounted for. +* If a padding is required apply it to the Parent's parent or apply a margin to the Parent. +* If you need to add a border, margin or any other CSS around your game container, then use a parent element and +* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container. +* +* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as +* they may be updated by the ScaleManager. +* +* #### Example Uses +* +* - ##### Fixed game size; scale canvas proportionally to fill its container +* +* Use `scaleMode` SHOW_ALL. +* +* - ##### Fixed game size; stretch canvas to fill its container (uncommon) +* +* Use `scaleMode` EXACT_FIT. +* +* - ##### Fixed game size; scale canvas proportionally by some other criteria +* +* Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary. +* +* - ##### Fluid game/canvas size +* +* Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary. +* +* - ##### Preferred orientation +* +* Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals. +* +* @description +* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game} +* +* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. +* +* @class +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number|string} width - The width of the game. See above. +* @param {number|string} height - The height of the game. See above. +*/ +Phaser.ScaleManager = function (game, width, height) { + + /** + * A reference to the currently running game. + * @property {Phaser.Game} game + * @protected + * @readonly + */ + this.game = game; + + /** + * Provides access to some cross-device DOM functions. + * @property {Phaser.DOM} dom + * @protected + * @readonly + */ + this.dom = Phaser.DOM; + + /** + * _EXPERIMENTAL:_ A responsive grid on which you can align game objects. + * @property {Phaser.FlexGrid} grid + * @public + */ + this.grid = null; + + /** + * Target width (in pixels) of the Display canvas. + * @property {number} width + * @readonly + */ + this.width = 0; + + /** + * Target height (in pixels) of the Display canvas. + * @property {number} height + * @readonly + */ + this.height = 0; + + /** + * Minimum width the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minWidth + * @readonly + * @protected + */ + this.minWidth = null; + + /** + * Maximum width the canvas should be scaled to (in pixels). + * If null it will scale to whatever width the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxWidth + * @readonly + * @protected + */ + this.maxWidth = null; + + /** + * Minimum height the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minHeight + * @readonly + * @protected + */ + this.minHeight = null; + + /** + * Maximum height the canvas should be scaled to (in pixels). + * If null it will scale to whatever height the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxHeight + * @readonly + * @protected + */ + this.maxHeight = null; + + /** + * The offset coordinates of the Display canvas from the top-left of the browser window. + * The is used internally by Phaser.Pointer (for Input) and possibly other types. + * @property {Phaser.Point} offset + * @readonly + * @protected + */ + this.offset = new Phaser.Point(); + + /** + * If true, the game should only run in a landscape orientation. + * Change with {@link #forceOrientation}. + * @property {boolean} forceLandscape + * @readonly + * @default + * @protected + */ + this.forceLandscape = false; + + /** + * If true, the game should only run in a portrait + * Change with {@link #forceOrientation}. + * @property {boolean} forcePortrait + * @readonly + * @default + * @protected + */ + this.forcePortrait = false; + + /** + * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation. + * + * This value is not updated immediately. + * + * @property {boolean} incorrectOrientation + * @readonly + * @protected + */ + this.incorrectOrientation = false; + + /** + * See {@link #pageAlignHorizontally}. + * @property {boolean} _pageAlignHorizontally + * @private + */ + this._pageAlignHorizontally = false; + + /** + * See {@link #pageAlignVertically}. + * @property {boolean} _pageAlignVertically + * @private + */ + this._pageAlignVertically = false; + + /** + * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes. + * + * The signal is supplied with the following arguments: + * - `scale` - the ScaleManager object + * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}. + * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. + * + * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. + * Thus the following tests can be done: + * + * // The orientation itself changed: + * scale.screenOrientation !== prevOrientation + * // The orientation just became incorrect: + * scale.incorrectOrientation && !wasIncorrect + * + * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation + * correctness changes even if the orientation itself does not change. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onOrientationChange + * @public + */ + this.onOrientationChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} enterIncorrectOrientation + * @public + */ + this.enterIncorrectOrientation = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} leaveIncorrectOrientation + * @public + */ + this.leaveIncorrectOrientation = new Phaser.Signal(); + + /** + * This boolean provides you with a way to determine if the browser is in Full Screen + * mode (via the Full Screen API), and Phaser was the one responsible for activating it. + * + * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the + * one that made the browser go full-screen, so this flag lets you determine that. + * + * @property {boolean} hasPhaserSetFullScreen + * @default + */ + this.hasPhaserSetFullScreen = false; + + /** + * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. + * The target element must have the correct CSS styling and contain the Display canvas. + * + * The elements style will be modified (ie. the width and height might be set to 100%) + * but it will not be added to, removed from, or repositioned within the DOM. + * An attempt is made to restore relevant style changes when fullscreen mode is left. + * + * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. + * + * @property {?DOMElement} fullScreenTarget + * @default + */ + this.fullScreenTarget = null; + + /** + * The fullscreen target, as created by {@link #createFullScreenTarget}. + * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends. + * @property {?DOMElement} _createdFullScreenTarget + * @private + */ + this._createdFullScreenTarget = null; + + /** + * This signal is dispatched when fullscreen mode is ready to be initialized but + * before the fullscreen request. + * + * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. + * + * The `targetElement` is the {@link #fullScreenTarget} element, + * if such is assigned, or a new element created by {@link #createFullScreenTarget}. + * + * Custom CSS styling or resets can be applied to `targetElement` as required. + * + * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}: + * - After initialization the Display canvas is moved onto the `targetElement` for + * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. + * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. + * + * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}. + * + * @property {Phaser.Signal} onFullScreenInit + * @public + */ + this.onFullScreenInit = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine + * if currently running in Fullscreen mode. + * + * @property {Phaser.Signal} onFullScreenChange + * @public + */ + this.onFullScreenChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser fails to enter fullscreen mode; + * or if the device does not support fullscreen mode and `startFullScreen` is invoked. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). + * + * @property {Phaser.Signal} onFullScreenError + * @public + */ + this.onFullScreenError = new Phaser.Signal(); + + /** + * The _last known_ orientation of the screen, as defined in the Window Screen Web API. + * See {@link Phaser.DOM.getScreenOrientation} for possible values. + * + * @property {string} screenOrientation + * @readonly + * @public + */ + this.screenOrientation = this.dom.getScreenOrientation(); + + /** + * The _current_ scale factor based on the game dimensions vs. the scaled dimensions. + * @property {Phaser.Point} scaleFactor + * @readonly + */ + this.scaleFactor = new Phaser.Point(1, 1); + + /** + * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions. + * @property {Phaser.Point} scaleFactorInversed + * @readonly + * @protected + */ + this.scaleFactorInversed = new Phaser.Point(1, 1); + + /** + * The Display canvas is aligned by adjusting the margins; the last margins are stored here. + * + * @property {Bounds-like} margin + * @readonly + * @protected + */ + this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0}; + + /** + * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. + * @property {Phaser.Rectangle} bounds + * @readonly + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The aspect ratio of the scaled Display canvas. + * @property {number} aspectRatio + * @readonly + */ + this.aspectRatio = 0; + + /** + * The aspect ratio of the original game dimensions. + * @property {number} sourceAspectRatio + * @readonly + */ + this.sourceAspectRatio = 0; + + /** + * The native browser events from Fullscreen API changes. + * @property {any} event + * @readonly + * @private + */ + this.event = null; + + /** + * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container. + * + * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. + * - If 'visual', the edge will be constrained to the Window / displayed screen area + * - If 'layout', the edge will be constrained to the CSS Layout bounds + * - An invalid value is treated as 'visual' + * + * @member + * @property {string} bottom + * @property {string} right + * @default + */ + this.windowConstraints = { + right: 'layout', + bottom: '' + }; + + /** + * Various compatibility settings. + * A value of "(auto)" indicates the setting is configured based on device and runtime information. + * + * A {@link #refresh} may need to be performed after making changes. + * + * @protected + * + * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.) + * + * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}. + * + * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. + * + * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh. + * + * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates. + * The height set varies by device and may either be the height of the window or the viewport. + * + * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. + * + * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. + * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. + * Any other string value (including the empty string) prevents using click trampolines. + * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}. + */ + this.compatibility = { + supportsFullScreen: false, + orientationFallback: null, + noMargins: false, + scrollTo: null, + forceMinimumDocumentHeight: false, + canExpandParent: true, + clickTrampoline: '' + }; + + /** + * Scale mode to be used when not in fullscreen. + * @property {number} _scaleMode + * @private + */ + this._scaleMode = Phaser.ScaleManager.NO_SCALE; + + /* + * Scale mode to be used in fullscreen. + * @property {number} _fullScreenScaleMode + * @private + */ + this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE; + + /** + * True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * The {@link #parentNode} property is generally ignored while this is in effect. + * + * @property {boolean} parentIsWindow + */ + this.parentIsWindow = false; + + /** + * The _original_ DOM element for the parent of the Display canvas. + * This may be different in fullscreen - see {@link #createFullScreenTarget}. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * This should only be changed after moving the Game canvas to a different DOM parent. + * + * @property {?DOMElement} parentNode + */ + this.parentNode = null; + + /** + * The scale of the game in relation to its parent container. + * @property {Phaser.Point} parentScaleFactor + * @readonly + */ + this.parentScaleFactor = new Phaser.Point(1, 1); + + /** + * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). + * Update checks normally happen quicker in response to other events. + * + * @property {integer} trackParentInterval + * @default + * @protected + * @see {@link Phaser.ScaleManager#refresh refresh} + */ + this.trackParentInterval = 2000; + + /** + * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. + * When invoked this is done _after_ the Canvas size/position have been updated. + * + * The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.) + * + * This signal is _only_ called when a change occurs and a reflow may be required. + * For example, if the canvas does not change sizes because of CSS settings (such as min-width) + * then this signal will _not_ be triggered. + * + * Use this to handle responsive game layout options. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onSizeChange + */ + this.onSizeChange = new Phaser.Signal(); + + /** + * The callback that will be called each the parent container resizes. + * @property {function} onResize + * @private + */ + this.onResize = null; + + /** + * The context in which the {@link #onResize} callback will be called. + * @property {object} onResizeContext + * @private + */ + this.onResizeContext = null; + + /** + * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot. + * @private + */ + this._pendingScaleMode = null; + + /** + * Information saved when fullscreen mode is started. + * @property {?object} _fullScreenRestore + * @private + */ + this._fullScreenRestore = null; + + /** + * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}. + * @property {Phaser.Rectangle} _gameSize + * @private + */ + this._gameSize = new Phaser.Rectangle(); + + /** + * The user-supplied scale factor, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleFactor + * @private + */ + this._userScaleFactor = new Phaser.Point(1, 1); + + /** + * The user-supplied scale trim, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleTrim + * @private + */ + this._userScaleTrim = new Phaser.Point(0, 0); + + /** + * The last time the bounds were checked in `preUpdate`. + * @property {number} _lastUpdate + * @private + */ + this._lastUpdate = 0; + + /** + * Size checks updates are delayed according to the throttle. + * The throttle increases to `trackParentInterval` over time and is used to more + * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety. + * @property {integer} _updateThrottle + * @private + */ + this._updateThrottle = 0; + + /** + * The minimum throttle allowed until it has slowed down sufficiently. + * @property {integer} _updateThrottleReset + * @private + */ + this._updateThrottleReset = 100; + + /** + * The cached result of the parent (possibly window) bounds; used to invalidate sizing. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._parentBounds = new Phaser.Rectangle(); + + /** + * Temporary bounds used for internal work to cut down on new objects created. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._tempBounds = new Phaser.Rectangle(); + + /** + * The Canvas size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedCanvasSize + * @private + */ + this._lastReportedCanvasSize = new Phaser.Rectangle(); + + /** + * The Game size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedGameSize + * @private + */ + this._lastReportedGameSize = new Phaser.Rectangle(); + + /** + * @property {boolean} _booted - ScaleManager booted state. + * @private + */ + this._booted = false; + + if (game.config) + { + this.parseConfig(game.config); + } + + this.setupScale(width, height); + +}; + +/** +* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.EXACT_FIT = 0; + +/** +* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.NO_SCALE = 1; + +/** +* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.SHOW_ALL = 2; + +/** +* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.RESIZE = 3; + +/** +* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.USER_SCALE = 4; + +/** +* Names of the scale modes, indexed by value. +* +* @constant +* @type {string[]} +*/ +Phaser.ScaleManager.MODES = [ + 'EXACT_FIT', + 'NO_SCALE', + 'SHOW_ALL', + 'RESIZE', + 'USER_SCALE' +]; + +Phaser.ScaleManager.prototype = { + + /** + * Start the ScaleManager. + * + * @method Phaser.ScaleManager#boot + * @protected + */ + boot: function () { + + // Configure device-dependent compatibility + + var compat = this.compatibility; + + compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS; + + // We can't do anything about the status bars in iPads, web apps or desktops + if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop) + { + if (this.game.device.android && !this.game.device.chrome) + { + compat.scrollTo = new Phaser.Point(0, 1); + } + else + { + compat.scrollTo = new Phaser.Point(0, 0); + } + } + + if (this.game.device.desktop) + { + compat.orientationFallback = 'screen'; + compat.clickTrampoline = 'when-not-mouse'; + } + else + { + compat.orientationFallback = ''; + compat.clickTrampoline = ''; + } + + // Configure event listeners + + var _this = this; + + this._orientationChange = function(event) { + return _this.orientationChange(event); + }; + + this._windowResize = function(event) { + return _this.windowResize(event); + }; + + // This does not appear to be on the standards track + window.addEventListener('orientationchange', this._orientationChange, false); + window.addEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + this._fullScreenChange = function(event) { + return _this.fullScreenChange(event); + }; + + this._fullScreenError = function(event) { + return _this.fullScreenError(event); + }; + + document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.addEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.addEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.addEventListener('fullscreenchange', this._fullScreenChange, false); + + document.addEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.addEventListener('mozfullscreenerror', this._fullScreenError, false); + document.addEventListener('MSFullscreenError', this._fullScreenError, false); + document.addEventListener('fullscreenerror', this._fullScreenError, false); + } + + this.game.onResume.add(this._gameResumed, this); + + // Initialize core bounds + + this.dom.getOffset(this.game.canvas, this.offset); + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + this.setGameSize(this.game.width, this.game.height); + + // Don't use updateOrientationState so events are not fired + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + if (Phaser.FlexGrid) + { + this.grid = new Phaser.FlexGrid(this, this.width, this.height); + } + + this._booted = true; + + if (this._pendingScaleMode !== null) + { + this.scaleMode = this._pendingScaleMode; + this._pendingScaleMode = null; + } + + }, + + /** + * Load configuration settings. + * + * @method Phaser.ScaleManager#parseConfig + * @protected + * @param {object} config - The game configuration object. + */ + parseConfig: function (config) { + + if (config['scaleMode'] !== undefined) + { + if (this._booted) + { + this.scaleMode = config['scaleMode']; + } + else + { + this._pendingScaleMode = config['scaleMode']; + } + } + + if (config['fullScreenScaleMode'] !== undefined) + { + this.fullScreenScaleMode = config['fullScreenScaleMode']; + } + + if (config['fullScreenTarget']) + { + this.fullScreenTarget = config['fullScreenTarget']; + } + + this.pageAlignHorizontally = config.alignH || false; + this.pageAlignVertically = config.alignV || false; + + if (config.scaleH && config.scaleV) + { + this.setUserScale(config.scaleH, config.scaleV, config.trimH, config.trimV); + } + + }, + + /** + * Calculates and sets the game dimensions based on the given width and height. + * + * This should _not_ be called when in fullscreen mode. + * + * @method Phaser.ScaleManager#setupScale + * @protected + * @param {number|string} width - The width of the game. + * @param {number|string} height - The height of the game. + */ + setupScale: function (width, height) { + + var target; + var rect = new Phaser.Rectangle(); + + if (this.game.parent !== '') + { + if (typeof this.game.parent === 'string') + { + // hopefully an element ID + target = document.getElementById(this.game.parent); + } + else if (this.game.parent && this.game.parent.nodeType === 1) + { + // quick test for a HTMLelement + target = this.game.parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + // Use the full window + this.parentNode = null; + this.parentIsWindow = true; + + rect.width = this.dom.visualBounds.width; + rect.height = this.dom.visualBounds.height; + + this.offset.set(0, 0); + } + else + { + this.parentNode = target; + this.parentIsWindow = false; + + this.getParentBounds(this._parentBounds); + + rect.width = this._parentBounds.width; + rect.height = this._parentBounds.height; + + this.offset.set(this._parentBounds.x, this._parentBounds.y); + } + + var newWidth = 0; + var newHeight = 0; + + if (typeof width === 'number') + { + newWidth = width; + } + else + { + // Percentage based + this.parentScaleFactor.x = parseInt(width, 10) / 100; + newWidth = rect.width * this.parentScaleFactor.x; + } + + if (typeof height === 'number') + { + newHeight = height; + } + else + { + // Percentage based + this.parentScaleFactor.y = parseInt(height, 10) / 100; + newHeight = rect.height * this.parentScaleFactor.y; + } + + newWidth = Math.floor(newWidth); + newHeight = Math.floor(newHeight); + + this._gameSize.setTo(0, 0, newWidth, newHeight); + + this.updateDimensions(newWidth, newHeight, false); + + }, + + /** + * Invoked when the game is resumed. + * + * @method Phaser.ScaleManager#_gameResumed + * @private + */ + _gameResumed: function () { + + this.queueUpdate(true); + + }, + + /** + * Set the actual Game size. + * Use this instead of directly changing `game.width` or `game.height`. + * + * The actual physical display (Canvas element size) depends on various settings including + * - Scale mode + * - Scaling factor + * - Size of Canvas's parent element or CSS rules such as min-height/max-height; + * - The size of the Window + * + * @method Phaser.ScaleManager#setGameSize + * @public + * @param {integer} width - _Game width_, in pixels. + * @param {integer} height - _Game height_, in pixels. + */ + setGameSize: function (width, height) { + + this._gameSize.setTo(0, 0, width, height); + + if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE) + { + this.updateDimensions(width, height, true); + } + + this.queueUpdate(true); + + }, + + /** + * Set a User scaling factor used in the USER_SCALE scaling mode. + * + * The target canvas size is computed by: + * + * canvas.width = (game.width * hScale) - hTrim + * canvas.height = (game.height * vScale) - vTrim + * + * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly. + * + * @method Phaser.ScaleManager#setUserScale + * @param {number} hScale - Horizontal scaling factor. + * @param {numer} vScale - Vertical scaling factor. + * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling. + * @param {integer} [vTrim=0] - Vertical trim, applied after scaling. + * @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate + * @param {boolean} [force=true] - Force a resize during the next preUpdate + */ + setUserScale: function (hScale, vScale, hTrim, vTrim, queueUpdate, force) { + + this._userScaleFactor.setTo(hScale, vScale); + this._userScaleTrim.setTo(hTrim | 0, vTrim | 0); + + if (queueUpdate === undefined) { queueUpdate = true; } + if (force === undefined) { force = true; } + + if (queueUpdate) + { + this.queueUpdate(force); + } + + }, + + /** + * Sets the callback that will be invoked before sizing calculations. + * + * Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries: + * the browser window has been resized, the device has been rotated, or the parent container's size has changed. + * At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all + * after it makes its sizing calculations). You can read the size of the parent container from the + * `parentBounds` argument to the callback. + * + * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling. + * + * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager + * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. + * + * This callback + * - May be invoked even though the parent container or canvas sizes have not changed + * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated + * - Will be invoked from `preUpdate`, _even when_ the game is paused + * + * See {@link #onSizeChange} for a better way of reacting to layout updates. + * + * @method Phaser.ScaleManager#setResizeCallback + * @public + * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes. + * @param {object} context - The context in which the callback will be called. + */ + setResizeCallback: function (callback, context) { + + this.onResize = callback; + this.onResizeContext = context; + + }, + + /** + * Signals a resize - IF the canvas or Game size differs from the last signal. + * + * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager). + * + * It dispatches the {@link #onSizeChange} signal. + * + * @method Phaser.ScaleManager#signalSizeChange + * @private + */ + signalSizeChange: function () { + + if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) || + !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize)) + { + var width = this.width; + var height = this.height; + + this._lastReportedCanvasSize.setTo(0, 0, width, height); + this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height); + + if (this.grid) + { + this.grid.onResize(width, height); + } + + this.onSizeChange.dispatch(this, width, height); + + // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode. + if (this.currentScaleMode === Phaser.ScaleManager.RESIZE) + { + this.game.state.resize(width, height); + this.game.load.resize(width, height); + } + } + + }, + + /** + * Set the min and max dimensions for the Display canvas. + * + * _Note:_ The min/max dimensions are only applied in some cases + * - When the device is not in an incorrect orientation; or + * - The scale mode is EXACT_FIT when not in fullscreen + * + * @method Phaser.ScaleManager#setMinMax + * @public + * @param {number} minWidth - The minimum width the game is allowed to scale down to. + * @param {number} minHeight - The minimum height the game is allowed to scale down to. + * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified. + * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified. + * @todo These values are only sometimes honored. + */ + setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) { + + this.minWidth = minWidth; + this.minHeight = minHeight; + + if (typeof maxWidth !== 'undefined') + { + this.maxWidth = maxWidth; + } + + if (typeof maxHeight !== 'undefined') + { + this.maxHeight = maxHeight; + } + + }, + + /** + * The ScaleManager.preUpdate is called automatically by the core Game loop. + * + * @method Phaser.ScaleManager#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.game.time.time < (this._lastUpdate + this._updateThrottle)) + { + return; + } + + var prevThrottle = this._updateThrottle; + this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100; + + this.dom.getOffset(this.game.canvas, this.offset); + + var prevWidth = this._parentBounds.width; + var prevHeight = this._parentBounds.height; + var bounds = this.getParentBounds(this._parentBounds); + + var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight; + + // Always invalidate on a newly detected orientation change + var orientationChanged = this.updateOrientationState(); + + if (boundsChanged || orientationChanged) + { + if (this.onResize) + { + this.onResize.call(this.onResizeContext, this, bounds); + } + + this.updateLayout(); + + this.signalSizeChange(); + } + + // Next throttle, eg. 25, 50, 100, 200.. + var throttle = this._updateThrottle * 2; + + // Don't let an update be too eager about resetting the throttle. + if (this._updateThrottle < prevThrottle) + { + throttle = Math.min(prevThrottle, this._updateThrottleReset); + } + + this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval); + this._lastUpdate = this.game.time.time; + + }, + + /** + * Update method while paused. + * + * @method Phaser.ScaleManager#pauseUpdate + * @private + */ + pauseUpdate: function () { + + this.preUpdate(); + + // Updates at slowest. + this._updateThrottle = this.trackParentInterval; + + }, + + /** + * Update the dimensions taking the parent scaling factor into account. + * + * @method Phaser.ScaleManager#updateDimensions + * @private + * @param {number} width - The new width of the parent container. + * @param {number} height - The new height of the parent container. + * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars. + */ + updateDimensions: function (width, height, resize) { + + this.width = width * this.parentScaleFactor.x; + this.height = height * this.parentScaleFactor.y; + + this.game.width = this.width; + this.game.height = this.height; + + this.sourceAspectRatio = this.width / this.height; + this.updateScalingAndBounds(); + + if (resize) + { + // Resize the renderer (which in turn resizes the Display canvas!) + this.game.renderer.resize(this.width, this.height); + + // The Camera can never be smaller than the Game size + this.game.camera.setSize(this.width, this.height); + + // This should only happen if the world is smaller than the new canvas size + this.game.world.resize(this.width, this.height); + } + + }, + + /** + * Update relevant scaling values based on the ScaleManager dimension and game dimensions, + * which should already be set. This does not change {@link #sourceAspectRatio}. + * + * @method Phaser.ScaleManager#updateScalingAndBounds + * @private + */ + updateScalingAndBounds: function () { + + this.scaleFactor.x = this.game.width / this.width; + this.scaleFactor.y = this.game.height / this.height; + + this.scaleFactorInversed.x = this.width / this.game.width; + this.scaleFactorInversed.y = this.height / this.game.height; + + this.aspectRatio = this.width / this.height; + + // This can be invoked in boot pre-canvas + if (this.game.canvas) + { + this.dom.getOffset(this.game.canvas, this.offset); + } + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + // Can be invoked in boot pre-input + if (this.game.input && this.game.input.scale) + { + this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y); + } + + }, + + /** + * Force the game to run in only one orientation. + * + * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. + * + * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor + * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the + * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` + * + * @method Phaser.ScaleManager#forceOrientation + * @public + * @param {boolean} forceLandscape - true if the game should run in landscape mode only. + * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. + */ + forceOrientation: function (forceLandscape, forcePortrait) { + + if (forcePortrait === undefined) { forcePortrait = false; } + + if (forceLandscape === true && forcePortrait === true) + { + console.warn('Phaser.ScaleManager: forceLandscape and forcePortrait cannot both be true.'); + return; + } + + this.forceLandscape = forceLandscape; + this.forcePortrait = forcePortrait; + + this.queueUpdate(true); + + }, + + /** + * Classify the orientation, per `getScreenOrientation`. + * + * @method Phaser.ScaleManager#classifyOrientation + * @private + * @param {string} orientation - The orientation string, e.g. 'portrait-primary'. + * @return {?string} The classified orientation: 'portrait', 'landscape`, or null. + */ + classifyOrientation: function (orientation) { + + if (orientation === 'portrait-primary' || orientation === 'portrait-secondary') + { + return 'portrait'; + } + else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary') + { + return 'landscape'; + } + else + { + return null; + } + + }, + + /** + * Updates the current orientation and dispatches orientation change events. + * + * @method Phaser.ScaleManager#updateOrientationState + * @private + * @return {boolean} True if the orientation state changed which means a forced update is likely required. + */ + updateOrientationState: function () { + + var previousOrientation = this.screenOrientation; + var previouslyIncorrect = this.incorrectOrientation; + + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) || + (this.forcePortrait && !this.isPortrait); + + var changed = previousOrientation !== this.screenOrientation; + var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation; + + if (correctnessChanged) + { + if (this.incorrectOrientation) + { + this.enterIncorrectOrientation.dispatch(); + } + else + { + this.leaveIncorrectOrientation.dispatch(); + } + } + + if (changed || correctnessChanged) + { + this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect); + } + + return changed || correctnessChanged; + + }, + + /** + * window.orientationchange event handler. + * + * @method Phaser.ScaleManager#orientationChange + * @private + * @param {Event} event - The orientationchange event data. + */ + orientationChange: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * window.resize event handler. + * + * @method Phaser.ScaleManager#windowResize + * @private + * @param {Event} event - The resize event data. + */ + windowResize: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * Scroll to the top - in some environments. See `compatibility.scrollTo`. + * + * @method Phaser.ScaleManager#scrollTop + * @private + */ + scrollTop: function () { + + var scrollTo = this.compatibility.scrollTo; + + if (scrollTo) + { + window.scrollTo(scrollTo.x, scrollTo.y); + } + + }, + + /** + * The "refresh" methods informs the ScaleManager that a layout refresh is required. + * + * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) + * when the browser is resized, the orientation changes, or when there is a detected change + * of the Parent size. Refreshing is also done automatically when public properties, + * such as {@link #scaleMode}, are updated or state-changing methods are invoked. + * + * The "refresh" method _may_ need to be used in a few (rare) situtations when + * + * - a device change event is not correctly detected; or + * - the Parent size changes (and an immediate reflow is desired); or + * - the ScaleManager state is updated by non-standard means; or + * - certain {@link #compatibility} properties are manually changed. + * + * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. + * + * @method Phaser.ScaleManager#refresh + * @public + */ + refresh: function () { + + this.scrollTop(); + this.queueUpdate(true); + + }, + + /** + * Updates the game / canvas position and size. + * + * @method Phaser.ScaleManager#updateLayout + * @private + */ + updateLayout: function () { + + var scaleMode = this.currentScaleMode; + + if (scaleMode === Phaser.ScaleManager.RESIZE) + { + this.reflowGame(); + return; + } + + this.scrollTop(); + + if (this.compatibility.forceMinimumDocumentHeight) + { + // (This came from older code, by why is it here?) + // Set minimum height of content to new window height + document.documentElement.style.minHeight = window.innerHeight + 'px'; + } + + if (this.incorrectOrientation) + { + this.setMaximum(); + } + else + { + if (scaleMode === Phaser.ScaleManager.EXACT_FIT) + { + this.setExactFit(); + } + else if (scaleMode === Phaser.ScaleManager.SHOW_ALL) + { + if (!this.isFullScreen && this.boundingParent && + this.compatibility.canExpandParent) + { + // Try to expand parent out, but choosing maximizing dimensions. + // Then select minimize dimensions which should then honor parent + // maximum bound applications. + this.setShowAll(true); + this.resetCanvas(); + this.setShowAll(); + } + else + { + this.setShowAll(); + } + } + else if (scaleMode === Phaser.ScaleManager.NO_SCALE) + { + this.width = this.game.width; + this.height = this.game.height; + } + else if (scaleMode === Phaser.ScaleManager.USER_SCALE) + { + this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x; + this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y; + } + } + + if (!this.compatibility.canExpandParent && + (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE)) + { + var bounds = this.getParentBounds(this._tempBounds); + this.width = Math.min(this.width, bounds.width); + this.height = Math.min(this.height, bounds.height); + } + + // Always truncate / force to integer + this.width = this.width | 0; + this.height = this.height | 0; + + this.reflowCanvas(); + + }, + + /** + * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. + * + * If in fullscreen mode or without parent (see {@link #parentIsWindow}), + * this will be the bounds of the visual viewport itself. + * + * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside + * the viewport then this function may return a smaller than expected size. + * + * Values are rounded to the nearest pixel. + * + * @method Phaser.ScaleManager#getParentBounds + * @protected + * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed. + * @return {Phaser.Rectangle} The established parent bounds. + */ + getParentBounds: function (target) { + + var bounds = target || new Phaser.Rectangle(); + var parentNode = this.boundingParent; + var visualBounds = this.dom.visualBounds; + var layoutBounds = this.dom.layoutBounds; + + if (!parentNode) + { + bounds.setTo(0, 0, visualBounds.width, visualBounds.height); + } + else + { + // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect + var clientRect = parentNode.getBoundingClientRect(); + var parentRect = (parentNode.offsetParent) ? parentNode.offsetParent.getBoundingClientRect() : parentNode.getBoundingClientRect(); + + bounds.setTo(clientRect.left - parentRect.left, clientRect.top - parentRect.top, clientRect.width, clientRect.height); + + var wc = this.windowConstraints; + + if (wc.right) + { + var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds; + bounds.right = Math.min(bounds.right, windowBounds.width); + } + + if (wc.bottom) + { + var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds; + bounds.bottom = Math.min(bounds.bottom, windowBounds.height); + } + } + + bounds.setTo( + Math.round(bounds.x), Math.round(bounds.y), + Math.round(bounds.width), Math.round(bounds.height)); + + return bounds; + + }, + + + /** + * Shorthand for setting {@link #pageAlignHorizontally} and {@link #pageAlignVertically}. + * + * @method Phaser.ScaleManager#align + * @param {boolean} [horizontal] - Value for {@link #pageAlignHorizontally}. Pass `null` to leave unchanged. + * @param {boolean} [vertical] - Value for {@link #pageAlignVertically}. Omit or pass `null` to leave unchanged. + */ + align: function (horizontal, vertical) { + + if (horizontal != null) + { + this.pageAlignHorizontally = horizontal; + } + + if (vertical != null) + { + this.pageAlignVertically = vertical; + } + + }, + + /** + * Update the canvas position/margins - for alignment within the parent container. + * + * The canvas margins _must_ be reset/cleared prior to invoking this. + * + * @method Phaser.ScaleManager#alignCanvas + * @private + * @param {boolean} horizontal - Align horizontally? + * @param {boolean} vertical - Align vertically? + */ + alignCanvas: function (horizontal, vertical) { + + var parentBounds = this.getParentBounds(this._tempBounds); + var canvas = this.game.canvas; + var margin = this.margin; + + if (horizontal) + { + margin.left = margin.right = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.width < parentBounds.width && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.left - parentBounds.x; + var targetEdge = (parentBounds.width / 2) - (this.width / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + + margin.left = Math.round(offset); + } + + canvas.style.marginLeft = margin.left + 'px'; + + if (margin.left !== 0) + { + margin.right = -(parentBounds.width - canvasBounds.width - margin.left); + canvas.style.marginRight = margin.right + 'px'; + } + } + + if (vertical) + { + margin.top = margin.bottom = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.height < parentBounds.height && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.top - parentBounds.y; + var targetEdge = (parentBounds.height / 2) - (this.height / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + margin.top = Math.round(offset); + } + + canvas.style.marginTop = margin.top + 'px'; + + if (margin.top !== 0) + { + margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top); + canvas.style.marginBottom = margin.bottom + 'px'; + } + } + + // Silly backwards compatibility.. + margin.x = margin.left; + margin.y = margin.top; + + }, + + /** + * Updates the Game state / size. + * + * The canvas margins may always be adjusted, even if alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowGame + * @private + */ + reflowGame: function () { + + this.resetCanvas('', ''); + + var bounds = this.getParentBounds(this._tempBounds); + this.updateDimensions(bounds.width, bounds.height, true); + + }, + + /** + * Updates the Display canvas size. + * + * The canvas margins may always be adjusted, even alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowCanvas + * @private + */ + reflowCanvas: function () { + + if (!this.incorrectOrientation) + { + this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width); + this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height); + } + + this.resetCanvas(); + + if (!this.compatibility.noMargins) + { + if (this.isFullScreen && this._createdFullScreenTarget) + { + this.alignCanvas(true, true); + } + else + { + this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically); + } + } + + this.updateScalingAndBounds(); + + }, + + /** + * "Reset" the Display canvas and set the specified width/height. + * + * @method Phaser.ScaleManager#resetCanvas + * @private + * @param {string} [cssWidth=(current width)] - The css width to set. + * @param {string} [cssHeight=(current height)] - The css height to set. + */ + resetCanvas: function (cssWidth, cssHeight) { + + if (cssWidth === undefined) { cssWidth = this.width + 'px'; } + if (cssHeight === undefined) { cssHeight = this.height + 'px'; } + + var canvas = this.game.canvas; + + if (!this.compatibility.noMargins) + { + canvas.style.marginLeft = ''; + canvas.style.marginTop = ''; + canvas.style.marginRight = ''; + canvas.style.marginBottom = ''; + } + + canvas.style.width = cssWidth; + canvas.style.height = cssHeight; + + }, + + /** + * Queues/marks a size/bounds check as needing to occur (from `preUpdate`). + * + * @method Phaser.ScaleManager#queueUpdate + * @private + * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty. + */ + queueUpdate: function (force) { + + if (force) + { + this._parentBounds.width = 0; + this._parentBounds.height = 0; + } + + this._updateThrottle = this._updateThrottleReset; + + }, + + /** + * Reset internal data/state. + * + * @method Phaser.ScaleManager#reset + * @private + */ + reset: function (clearWorld) { + + if (clearWorld && this.grid) + { + this.grid.reset(); + } + + }, + + /** + * Updates the width/height to that of the window. + * + * @method Phaser.ScaleManager#setMaximum + * @private + */ + setMaximum: function () { + + this.width = this.dom.visualBounds.width; + this.height = this.dom.visualBounds.height; + + }, + + /** + * Updates the width/height such that the game is scaled proportionally. + * + * @method Phaser.ScaleManager#setShowAll + * @private + * @param {boolean} expanding - If true then the maximizing dimension is chosen. + */ + setShowAll: function (expanding) { + + var bounds = this.getParentBounds(this._tempBounds); + var width = bounds.width; + var height = bounds.height; + + var multiplier; + + if (expanding) + { + multiplier = Math.max((height / this.game.height), (width / this.game.width)); + } + else + { + multiplier = Math.min((height / this.game.height), (width / this.game.width)); + } + + this.width = Math.round(this.game.width * multiplier); + this.height = Math.round(this.game.height * multiplier); + + }, + + /** + * Updates the width/height such that the game is stretched to the available size. + * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen. + * + * @method Phaser.ScaleManager#setExactFit + * @private + */ + setExactFit: function () { + + var bounds = this.getParentBounds(this._tempBounds); + + this.width = bounds.width; + this.height = bounds.height; + + if (this.isFullScreen) + { + // Max/min not honored fullscreen + return; + } + + if (this.maxWidth) + { + this.width = Math.min(this.width, this.maxWidth); + } + + if (this.maxHeight) + { + this.height = Math.min(this.height, this.maxHeight); + } + + }, + + /** + * Creates a fullscreen target. This is called automatically as as needed when entering + * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}. + * + * Use {@link #onFullScreenInit} to customize the created object. + * + * @method Phaser.ScaleManager#createFullScreenTarget + * @protected + */ + createFullScreenTarget: function () { + + var fsTarget = document.createElement('div'); + + fsTarget.style.margin = '0'; + fsTarget.style.padding = '0'; + fsTarget.style.background = '#000'; + + return fsTarget; + + }, + + /** + * Display the game in the browser's fullscreen mode. + * + * This _must_ be called from a user-input Pointer or Mouse event (and possibly a {@link https://www.chromestatus.com/feature/6131337345892352 "user gesture"}), e.g., + * + * - {@link Phaser.Events#onInputUp} + * - {@link Phaser.Input#onUp} or {@link Phaser.Input#onTap} + * - `click`, `mousedown`, `mouseup`, `pointerup`, or `touchend` + * + * Games within an iframe will also be blocked from fullscreen unless the iframe has the `allowfullscreen` attribute. + * + * The {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} must be {@link http://caniuse.com/#search=fullscreen supported by the browser} for this to work - it is not the same as setting + * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current + * device is reported to support fullscreen mode. + * + * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. + * + * Safari blocks access to keyboard events in fullscreen mode (as a security measure). + * + * @method Phaser.ScaleManager#startFullScreen + * @public + * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. + * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed. + * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) + */ + startFullScreen: function (antialias, allowTrampoline) { + + if (this.isFullScreen) + { + return false; + } + + if (!this.compatibility.supportsFullScreen) + { + // Error is called in timeout to emulate the real fullscreenerror event better + var _this = this; + + setTimeout(function () { + _this.fullScreenError(); + }, 10); + + return; + } + + if (this.compatibility.clickTrampoline === 'when-not-mouse') + { + var input = this.game.input; + + if (input.activePointer && + input.activePointer !== input.mousePointer && + (allowTrampoline || allowTrampoline !== false)) + { + input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]); + return; + } + } + + if (antialias !== undefined && this.game.renderType === Phaser.CANVAS) + { + this.game.stage.smoothed = antialias; + } + + var fsTarget = this.fullScreenTarget; + + if (!fsTarget) + { + this.cleanupCreatedTarget(); + + this._createdFullScreenTarget = this.createFullScreenTarget(); + fsTarget = this._createdFullScreenTarget; + } + + var initData = { + targetElement: fsTarget + }; + + this.hasPhaserSetFullScreen = true; + + this.onFullScreenInit.dispatch(this, initData); + + if (this._createdFullScreenTarget) + { + // Move the Display canvas inside of the target and add the target to the DOM + // (The target has to be added for the Fullscreen API to work.) + var canvas = this.game.canvas; + var parent = canvas.parentNode; + parent.insertBefore(fsTarget, canvas); + fsTarget.appendChild(canvas); + } + + if (this.game.device.fullscreenKeyboard) + { + fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT); + } + else + { + fsTarget[this.game.device.requestFullscreen](); + } + + return true; + + }, + + /** + * Stops / exits fullscreen mode, if active. + * + * @method Phaser.ScaleManager#stopFullScreen + * @public + * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. + */ + stopFullScreen: function () { + + if (!this.isFullScreen || !this.compatibility.supportsFullScreen) + { + return false; + } + + this.hasPhaserSetFullScreen = false; + + document[this.game.device.cancelFullscreen](); + + return true; + + }, + + /** + * Cleans up the previous fullscreen target, if such was automatically created. + * This ensures the canvas is restored to its former parent, assuming the target didn't move. + * + * @method Phaser.ScaleManager#cleanupCreatedTarget + * @private + */ + cleanupCreatedTarget: function () { + + var fsTarget = this._createdFullScreenTarget; + + if (fsTarget && fsTarget.parentNode) + { + // Make sure to cleanup synthetic target for sure; + // swap the canvas back to the parent. + var parent = fsTarget.parentNode; + parent.insertBefore(this.game.canvas, fsTarget); + parent.removeChild(fsTarget); + } + + this._createdFullScreenTarget = null; + + }, + + /** + * Used to prepare/restore extra fullscreen mode settings. + * (This does move any elements within the DOM tree.) + * + * @method Phaser.ScaleManager#prepScreenMode + * @private + * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_. + */ + prepScreenMode: function (enteringFullscreen) { + + var createdTarget = !!this._createdFullScreenTarget; + var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget; + + if (enteringFullscreen) + { + if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT) + { + // Resize target, as long as it's not the canvas + if (fsTarget !== this.game.canvas) + { + this._fullScreenRestore = { + targetWidth: fsTarget.style.width, + targetHeight: fsTarget.style.height + }; + + fsTarget.style.width = '100%'; + fsTarget.style.height = '100%'; + } + } + } + else + { + // Have restore information + if (this._fullScreenRestore) + { + fsTarget.style.width = this._fullScreenRestore.targetWidth; + fsTarget.style.height = this._fullScreenRestore.targetHeight; + + this._fullScreenRestore = null; + } + + // Always reset to game size + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.resetCanvas(); + } + + }, + + /** + * Called automatically when the browser enters of leaves fullscreen mode. + * + * @method Phaser.ScaleManager#fullScreenChange + * @private + * @param {Event} [event=undefined] - The fullscreenchange event + */ + fullScreenChange: function (event) { + + this.event = event; + + if (this.isFullScreen) + { + this.prepScreenMode(true); + + this.updateLayout(); + this.queueUpdate(true); + } + else + { + this.prepScreenMode(false); + + this.cleanupCreatedTarget(); + + this.updateLayout(); + this.queueUpdate(true); + } + + this.onFullScreenChange.dispatch(this, this.width, this.height); + + }, + + /** + * Called automatically when the browser fullscreen request fails; + * or called when a fullscreen request is made on a device for which it is not supported. + * + * @method Phaser.ScaleManager#fullScreenError + * @private + * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API. + */ + fullScreenError: function (event) { + + this.event = event; + + this.cleanupCreatedTarget(); + + console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API'); + + this.onFullScreenError.dispatch(this); + + }, + + /** + * Takes a Sprite or Image object and scales it to fit the given dimensions. + * Scaling happens proportionally without distortion to the sprites texture. + * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the + * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either + * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. + * + * @method Phaser.ScaleManager#scaleSprite + * @protected + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale. + * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. + * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. + * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. + * @return {Phaser.Sprite|Phaser.Image} The scaled sprite. + */ + scaleSprite: function (sprite, width, height, letterBox) { + + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + if (letterBox === undefined) { letterBox = false; } + + if (!sprite || !sprite['scale']) + { + return sprite; + } + + sprite.scale.x = 1; + sprite.scale.y = 1; + + if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0)) + { + return sprite; + } + + var scaleX1 = width; + var scaleY1 = (sprite.height * width) / sprite.width; + + var scaleX2 = (sprite.width * height) / sprite.height; + var scaleY2 = height; + + var scaleOnWidth = (scaleX2 > width); + + if (scaleOnWidth) + { + scaleOnWidth = letterBox; + } + else + { + scaleOnWidth = !letterBox; + } + + if (scaleOnWidth) + { + sprite.width = Math.floor(scaleX1); + sprite.height = Math.floor(scaleY1); + } + else + { + sprite.width = Math.floor(scaleX2); + sprite.height = Math.floor(scaleY2); + } + + // Enable at some point? + // sprite.x = Math.floor((width - sprite.width) / 2); + // sprite.y = Math.floor((height - sprite.height) / 2); + + return sprite; + + }, + + /** + * Destroys the ScaleManager and removes any event listeners. + * This should probably only be called when the game is destroyed. + * + * @method Phaser.ScaleManager#destroy + * @protected + */ + destroy: function () { + + this.game.onResume.remove(this._gameResumed, this); + + window.removeEventListener('orientationchange', this._orientationChange, false); + window.removeEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.removeEventListener('fullscreenchange', this._fullScreenChange, false); + + document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.removeEventListener('mozfullscreenerror', this._fullScreenError, false); + document.removeEventListener('MSFullscreenError', this._fullScreenError, false); + document.removeEventListener('fullscreenerror', this._fullScreenError, false); + } + + } + +}; + +Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager; + +/** +* The DOM element that is considered the Parent bounding element, if any. +* +* This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified. +* It will also be null if there is no game canvas or if the game canvas has no parent. +* +* @name Phaser.ScaleManager#boundingParent +* @property {?DOMElement} boundingParent +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", { + + get: function () { + + if (this.parentIsWindow || + (this.isFullScreen && this.hasPhaserSetFullScreen && !this._createdFullScreenTarget)) + { + return null; + } + + var parentNode = this.game.canvas && this.game.canvas.parentNode; + + return parentNode || null; + + } + +}); + +/** +* The scaling method used by the ScaleManager when not in fullscreen. +* +*
+*
{@link Phaser.ScaleManager.NO_SCALE}
+*
+* The Game display area will not be scaled - even if it is too large for the canvas/screen. +* This mode _ignores_ any applied scaling factor and displays the canvas at the Game size. +*
+*
{@link Phaser.ScaleManager.EXACT_FIT}
+*
+* The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen. +* Proportions are not maintained. +*
+*
{@link Phaser.ScaleManager.SHOW_ALL}
+*
+* Show the entire game display area while _maintaining_ the original aspect ratio. +*
+*
{@link Phaser.ScaleManager.RESIZE}
+*
+* The dimensions of the game display area are changed to match the size of the parent container. +* That is, this mode _changes the Game size_ to match the display size. +*

+* Any manually set Game size (see {@link #setGameSize}) is ignored while in effect. +*

+*
{@link Phaser.ScaleManager.USER_SCALE}
+*
+* The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}. +*

+* This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback} +* for flexible custom-sizing needs. +*

+*
+* +* @name Phaser.ScaleManager#scaleMode +* @property {integer} scaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", { + + get: function () { + + return this._scaleMode; + + }, + + set: function (value) { + + if (value !== this._scaleMode) + { + if (!this.isFullScreen) + { + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.queueUpdate(true); + } + + this._scaleMode = value; + } + + return this._scaleMode; + + } + +}); + +/** +* The scaling method used by the ScaleManager when in fullscreen. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#fullScreenScaleMode +* @property {integer} fullScreenScaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", { + + get: function () { + + return this._fullScreenScaleMode; + + }, + + set: function (value) { + + if (value !== this._fullScreenScaleMode) + { + // If in fullscreen then need a wee bit more work + if (this.isFullScreen) + { + this.prepScreenMode(false); + this._fullScreenScaleMode = value; + this.prepScreenMode(true); + + this.queueUpdate(true); + } + else + { + this._fullScreenScaleMode = value; + } + } + + return this._fullScreenScaleMode; + + } + +}); + +/** +* Returns the current scale mode - for normal or fullscreen operation. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#currentScaleMode +* @property {number} currentScaleMode +* @protected +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", { + + get: function () { + + return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode; + + } + +}); + +/** +* When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align horizontally across the page the Display canvas should be added directly to page; +* or the parent container should itself be horizontally aligned. +* +* Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignHorizontally +* @property {boolean} pageAlignHorizontally +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", { + + get: function () { + + return this._pageAlignHorizontally; + + }, + + set: function (value) { + + if (value !== this._pageAlignHorizontally) + { + this._pageAlignHorizontally = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain +* a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically +* _within_ the remaining available height dictated by the Parent element. +* +* One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. +* If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). +* +* _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height. +* To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true. +* +* Vertical alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignVertically +* @property {boolean} pageAlignVertically +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", { + + get: function () { + + return this._pageAlignVertically; + + }, + + set: function (value) { + + if (value !== this._pageAlignVertically) + { + this._pageAlignVertically = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* Returns true if the browser is in fullscreen mode, otherwise false. +* @name Phaser.ScaleManager#isFullScreen +* @property {boolean} isFullScreen +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", { + + get: function () { + return !!(document['fullscreenElement'] || + document['webkitFullscreenElement'] || + document['mozFullScreenElement'] || + document['msFullscreenElement']); + } + +}); + +/** +* Returns true if the screen orientation is in portrait mode. +* +* @name Phaser.ScaleManager#isPortrait +* @property {boolean} isPortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'portrait'; + } + +}); + +/** +* Returns true if the screen orientation is in landscape mode. +* +* @name Phaser.ScaleManager#isLandscape +* @property {boolean} isLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'landscape'; + } + +}); + +/** +* Returns true if the game dimensions are portrait (height > width). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGamePortrait +* @property {boolean} isGamePortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", { + + get: function () { + return (this.height > this.width); + } + +}); + +/** +* Returns true if the game dimensions are landscape (width > height). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGameLandscape +* @property {boolean} isGameLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", { + + get: function () { + return (this.width > this.height); + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of methods for displaying debug information about game objects. +* +* If your game is running in Canvas mode, then you should invoke all of the Debug methods from +* your games `render` function. This is because they are drawn directly onto the game canvas +* itself, so if you call any debug methods outside of `render` they are likely to be overwritten +* by the game itself. +* +* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture +* to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug +* in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! +* +* @class Phaser.Utils.Debug +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Utils.Debug = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Image} sprite - If debugging in WebGL mode, this is the Image displaying the debug {@link #bmd BitmapData}. + */ + this.sprite = null; + + /** + * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.context = null; + + /** + * @property {string} font - The font that the debug information is rendered in. + * @default + */ + this.font = '14px Courier'; + + /** + * @property {number} columnWidth - The spacing between columns. + * @default + */ + this.columnWidth = 100; + + /** + * @property {number} lineHeight - The line height between the debug text. + * @default + */ + this.lineHeight = 16; + + /** + * @property {number} lineWidth - The width of the stroke on lines and shapes. A positive number. + * @default + */ + this.lineWidth = 1; + + /** + * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. + * @default + */ + this.renderShadow = true; + + /** + * @property {string} currentColor - The color last set by {@link #start} or {@link #text}. + * @default + * @protected + */ + this.currentColor = null; + + /** + * @property {number} currentX - The current X position the debug information will be rendered at. + * @default + */ + this.currentX = 0; + + /** + * @property {number} currentY - The current Y position the debug information will be rendered at. + * @default + */ + this.currentY = 0; + + /** + * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it. + * @default + */ + this.currentAlpha = 1; + + /** + * @property {boolean} dirty - Does the canvas need re-rendering? + * @default + */ + this.dirty = false; + + /** + * @property {boolean} isDisabled - If `enableDebug: false` is passed to {@link Phaser.Game} or if Phaser is built without the Debug class, this will be true. + * @default + * @readonly + */ + this.isDisabled = false; + + /** + * @property {Phaser.Line} _line - A reusable rendering line. + * @private + */ + this._line = null; + + /** + * @property {Phaser.Rectangle} _rect - A reusable rendering rectangle. + * @private + */ + this._rect = null; + +}; + +Phaser.Utils.Debug.prototype = { + + /** + * Internal method that boots the debug displayer. + * + * @method Phaser.Utils.Debug#boot + * @protected + */ + boot: function () { + + if (this.game.renderType === Phaser.CANVAS) + { + this.context = this.game.context; + } + else + { + this.bmd = new Phaser.BitmapData(this.game, '__DEBUG', this.game.width, this.game.height, true); + this.sprite = this.game.make.image(0, 0, this.bmd); + this.game.stage.addChild(this.sprite); + + this.game.scale.onSizeChange.add(this.resize, this); + + this.canvas = Phaser.CanvasPool.create(this, this.game.width, this.game.height); + this.context = this.canvas.getContext('2d'); + } + + this._line = new Phaser.Line(); + this._rect = new Phaser.Rectangle(); + + }, + + /** + * Internal method that resizes the BitmapData and Canvas. + * Called by ScaleManager.onSizeChange only in WebGL mode. + * + * @method Phaser.Utils.Debug#resize + * @protected + */ + resize: function () { + + this.bmd.resize(this.game.width, this.game.height); + + this.canvas.width = this.game.width; + this.canvas.height = this.game.height; + + }, + + /** + * Internal method that clears the canvas (if a Sprite) ready for a new debug session. + * + * @method Phaser.Utils.Debug#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.dirty && this.sprite) + { + this.bmd.clear(); + this.bmd.draw(this.canvas, 0, 0); + + this.context.clearRect(0, 0, this.game.width, this.game.height); + this.dirty = false; + } + + }, + + /** + * Clears the Debug canvas. + * + * @method Phaser.Utils.Debug#reset + */ + reset: function () { + + if (this.context) + { + this.context.clearRect(0, 0, this.game.width, this.game.height); + } + + if (this.sprite) + { + this.bmd.clear(); + } + + }, + + /** + * Internal method that resets and starts the debug output values. + * + * @method Phaser.Utils.Debug#start + * @protected + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + * @param {number} [columnWidth=0] - The spacing between columns. + */ + start: function (x, y, color, columnWidth) { + + if (typeof x !== 'number') { x = 0; } + if (typeof y !== 'number') { y = 0; } + color = color || 'rgb(255,255,255)'; + if (columnWidth === undefined) { columnWidth = 0; } + + this.currentX = x; + this.currentY = y; + this.currentColor = color; + this.columnWidth = columnWidth; + + this.dirty = true; + + this.context.save(); + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.strokeStyle = color; + this.context.fillStyle = color; + this.context.font = this.font; + this.context.globalAlpha = this.currentAlpha; + + }, + + /** + * Internal method that stops the debug output. + * + * @method Phaser.Utils.Debug#stop + * @protected + */ + stop: function () { + + this.context.restore(); + + }, + + /** + * Internal method that outputs a single line of text split over as many columns as needed, one per parameter. + * + * @method Phaser.Utils.Debug#line + * @protected + */ + line: function () { + + var x = this.currentX; + + for (var i = 0; i < arguments.length; i++) + { + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(arguments[i], x + 1, this.currentY + 1); + this.context.fillStyle = this.currentColor; + } + + this.context.fillText(arguments[i], x, this.currentY); + + x += this.columnWidth; + } + + this.currentY += this.lineHeight; + + }, + + /** + * Render Sound Manager information, including volume, mute, audio mode, and locked status. + * + * @method Phaser.Utils.Debug#sound + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + sound: function (x, y, color) { + + var sound = this.game.sound; + + this.start(x, y, color); + + if (sound.noAudio) + { + this.line('Audio is disabled'); + } + else + { + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Mute on pause: ' + sound.muteOnPause); + this.line('Using: ' + (sound.usingWebAudio ? ('Web Audio - ' + sound.context.state) : 'Audio Tag')); + this.line('Touch locked: ' + sound.touchLocked); + } + + this.stop(); + + }, + + /** + * Render Sound information, including decoded state, duration, volume and more. + * + * @method Phaser.Utils.Debug#soundInfo + * @param {Phaser.Sound} sound - The sound object to debug. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + soundInfo: function (sound, x, y, color) { + + this.start(x, y, color); + this.line('Sound: ' + sound.key + ' Touch locked: ' + sound.game.sound.touchLocked); + this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback); + this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding); + this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying + ' Loop: ' + sound.loop); + this.line('Time: ' + sound.currentTime); + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Using: ' + (sound.usingWebAudio ? 'Web Audio' : 'Audio Tag')); + + if (sound.currentMarker !== '') + { + this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')'); + this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop); + this.line('Position: ' + sound.position); + } + + this.stop(); + + }, + + /** + * Marks the follow {@link #target} and {@link #deadzone}. + * + * @method Phaser.Utils.Debug#camera + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {string} [color] - Color of the debug shapes to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the shapes filled (default, true) or stroked (false). + */ + camera: function (camera, color, filled) { + + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + if (deadzone) + { + this._rect.setTo(view.x + deadzone.x, view.y + deadzone.y, deadzone.width, deadzone.height); + this.rectangle(this._rect, color, filled); + } + + if (target) + { + this._line.setTo(view.centerX, view.centerY, target.x, target.y); + this.geom(this._line, color, filled); + this.geom(target, color, false, 3); + } + + }, + + /** + * Render camera information including dimensions and location. + * + * @method Phaser.Utils.Debug#cameraInfo + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + cameraInfo: function (camera, x, y, color) { + + var bounds = camera.bounds; + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + this.start(x, y, color); + this.line('Camera (' + camera.width + ' x ' + camera.height + ')'); + this.line('x: ' + camera.x + ' y: ' + camera.y); + this.line('Bounds: ' + (bounds ? ('x: ' + bounds.x + ' y: ' + bounds.y + ' w: ' + bounds.width + ' h: ' + bounds.height) : 'none')); + this.line('View: x: ' + view.x + ' y: ' + view.y + ' w: ' + view.width + ' h: ' + view.height); + this.line('Deadzone: ' + (deadzone ? ('x: ' + deadzone.x + ' y: ' + deadzone.y + ' w: ' + deadzone.width + ' h: ' + deadzone.height) : deadzone)); + this.line('Total in view: ' + camera.totalInView); + this.line('At limit: x: ' + camera.atLimit.x + ' y: ' + camera.atLimit.y); + this.line('Target: ' + (target ? (target.name || target) : 'none')); + this.stop(); + + }, + + /** + * Render Timer information. + * + * @method Phaser.Utils.Debug#timer + * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + timer: function (timer, x, y, color) { + + this.start(x, y, color); + this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')'); + this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration); + this.line('Paused: ' + timer.paused + ' Length: ' + timer.length); + this.stop(); + + }, + + /** + * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text. + * + * @method Phaser.Utils.Debug#pointer + * @param {Phaser.Pointer} pointer - The Pointer you wish to display. + * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. + * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down. + * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false). + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + pointer: function (pointer, hideIfUp, downColor, upColor, color) { + + if (pointer == null) + { + return; + } + + if (hideIfUp === undefined) { hideIfUp = false; } + downColor = downColor || 'rgba(0,255,0,0.5)'; + upColor = upColor || 'rgba(255,0,0,0.5)'; + + if (hideIfUp === true && pointer.isUp === true) + { + return; + } + + this.start(pointer.x, pointer.y - 100, color); + this.context.beginPath(); + this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2); + + if (pointer.active) + { + this.context.fillStyle = downColor; + } + else + { + this.context.fillStyle = upColor; + } + + this.context.fill(); + this.context.closePath(); + + // Render the points + this.context.beginPath(); + this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y); + this.context.lineTo(pointer.position.x, pointer.position.y); + this.context.lineWidth = 2; + this.context.stroke(); + this.context.closePath(); + + // Render the text + this.line('ID: ' + pointer.id + " Active: " + pointer.active); + this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY); + this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y + " In: " + pointer.withinGame); + this.line('Duration: ' + pointer.duration + " ms"); + this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp); + this.stop(); + + }, + + /** + * Render Sprite Input Debug information. + * + * @method Phaser.Utils.Debug#spriteInputInfo + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInputInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')'); + this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1)); + this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0)); + this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0)); + this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut()); + this.stop(); + + }, + + /** + * Renders Phaser.Key object information. + * + * @method Phaser.Utils.Debug#key + * @param {Phaser.Key} key - The Key to render the information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + key: function (key, x, y, color) { + + this.start(x, y, color, 150); + + this.line('Key:', key.keyCode, 'isDown:', key.isDown); + this.line('justDown:', key.justDown, 'justUp:', key.justUp); + this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0)); + + this.stop(); + + }, + + /** + * Render debug information about the Input object. + * + * @method Phaser.Utils.Debug#inputInfo + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + inputInfo: function (x, y, color) { + + this.start(x, y, color); + this.line('Input'); + this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y); + this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY); + this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1)); + this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY); + this.stop(); + + }, + + /** + * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! + * + * @method Phaser.Utils.Debug#spriteBounds + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + spriteBounds: function (sprite, color, filled) { + + var bounds = sprite.getBounds(); + + bounds.x += this.game.camera.x; + bounds.y += this.game.camera.y; + + this.rectangle(bounds, color, filled); + + }, + + /** + * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it + * + * @method Phaser.Utils.Debug#ropeSegments + * @param {Phaser.Rope} rope - The rope to display the segments of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + ropeSegments: function (rope, color, filled) { + + var segments = rope.segments; + + var self = this; + + segments.forEach(function(segment) { + self.rectangle(segment, color, filled); + }, this); + + }, + + /** + * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. + * + * @method Phaser.Utils.Debug#spriteInfo + * @param {Phaser.Sprite} sprite - The Sprite to display the information of. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + + this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y); + this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1)); + this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1)); + this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera); + this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1)); + + this.stop(); + + }, + + /** + * Renders the sprite coordinates in local, positional and world space. + * + * @method Phaser.Utils.Debug#spriteCoords + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteCoords: function (sprite, x, y, color) { + + this.start(x, y, color, 100); + + if (sprite.name) + { + this.line(sprite.name); + } + + this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2)); + this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2)); + this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2)); + + this.stop(); + + }, + + /** + * Renders Line information in the given color. + * + * @method Phaser.Utils.Debug#lineInfo + * @param {Phaser.Line} line - The Line to display the data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + lineInfo: function (line, x, y, color) { + + this.start(x, y, color, 80); + this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2)); + this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2)); + this.line('length:', line.length.toFixed(2), 'angle:', line.angle); + this.stop(); + + }, + + /** + * Renders a single pixel at the given size. + * + * @method Phaser.Utils.Debug#pixel + * @param {number} x - X position of the pixel to be rendered. + * @param {number} y - Y position of the pixel to be rendered. + * @param {string} [color] - Color of the pixel (format is css color string). + * @param {number} [size=2] - The 'size' to render the pixel at. + */ + pixel: function (x, y, color, size) { + + size = size || 2; + + this.start(); + this.context.fillStyle = color; + this.context.fillRect(x, y, size, size); + this.stop(); + + }, + + /** + * Renders a Phaser geometry object including Rectangle, Circle, Ellipse, Point or Line. + * + * @method Phaser.Utils.Debug#geom + * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Ellipse|Phaser.Point|Phaser.Line} object - The geometry object to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) + * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle,3 = Point, 4 = Line and 5 = Ellipse. + */ + geom: function (object, color, filled, forceType) { + + if (filled === undefined) { filled = true; } + if (forceType === undefined) { forceType = 0; } + + color = color || 'rgba(0,255,0,0.4)'; + + this.start(); + + this.context.fillStyle = color; + this.context.strokeStyle = color; + this.context.lineWidth = this.lineWidth; + + if (object instanceof Phaser.Rectangle || forceType === 1) + { + if (filled) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + } + else if (object instanceof Phaser.Circle || forceType === 2) + { + this.context.beginPath(); + this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + else if (object instanceof Phaser.Point || forceType === 3) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4); + } + else if (object instanceof Phaser.Line || forceType === 4) + { + this.context.beginPath(); + this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y); + this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y); + this.context.closePath(); + this.context.stroke(); + } + else if (object instanceof Phaser.Ellipse || forceType === 5) + { + this.context.beginPath(); + this.context.ellipse(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width/2, object.height/2, 0,2 * Math.PI,false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + + this.stop(); + + }, + + /** + * Renders a Rectangle. + * + * @method Phaser.Utils.Debug#rectangle + * @param {Phaser.Rectangle|object} object - The rectangle to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as filled (default, true) or a stroked (false) + */ + rectangle: function (object, color, filled) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0, 255, 0, 0.4)'; + + this.start(); + + if (filled) + { + this.context.fillStyle = color; + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.lineWidth = this.lineWidth; + this.context.strokeStyle = color; + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + + this.stop(); + + }, + + /** + * Render a string of text. + * + * @method Phaser.Utils.Debug#text + * @param {string} text - The line of text to draw. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {string} [font] - The font of text to draw. + */ + text: function (text, x, y, color, font) { + + color = color || 'rgb(255,255,255)'; + font = font || '16px Courier'; + + this.start(); + this.context.font = font; + + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(text, x + 1, y + 1); + } + + this.context.fillStyle = color; + this.context.fillText(text, x, y); + + this.stop(); + + }, + + /** + * Visually renders a QuadTree to the display. + * + * @method Phaser.Utils.Debug#quadTree + * @param {Phaser.QuadTree} quadtree - The quadtree to render. + * @param {string} color - The color of the lines in the quadtree. + */ + quadTree: function (quadtree, color) { + + color = color || 'rgba(255,0,0,0.3)'; + + this.start(); + + var bounds = quadtree.bounds; + + if (quadtree.nodes.length === 0) + { + this.context.strokeStyle = color; + this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height); + this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier'); + + this.context.strokeStyle = 'rgb(0,255,0)'; + + for (var i = 0; i < quadtree.objects.length; i++) + { + this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height); + } + } + else + { + for (var i = 0; i < quadtree.nodes.length; i++) + { + this.quadTree(quadtree.nodes[i]); + } + } + + this.stop(); + + }, + + /** + * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. + * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. + * To display a P2 Physics body you should enable debug mode on the body when creating it. + * + * @method Phaser.Utils.Debug#body + * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false) + */ + body: function (sprite, color, filled) { + + if (sprite.body) + { + this.start(); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled, this.lineWidth); + } + else if (sprite.body.type === Phaser.Physics.NINJA) + { + Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color); + } + + this.stop(); + } + + }, + + /** + * Render a Sprites Physic Body information. + * + * @method Phaser.Utils.Debug#bodyInfo + * @param {Phaser.Sprite} sprite - The sprite to be rendered. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + bodyInfo: function (sprite, x, y, color) { + + if (sprite.body) + { + this.start(x, y, color, 210); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + this.game.physics.box2d.renderBodyInfo(this, sprite.body); + } + + this.stop(); + } + + }, + + /** + * Renders 'debug draw' data for the Box2D world if it exists. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by + * the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dWorld + */ + box2dWorld: function () { + + this.start(); + + this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0); + this.game.physics.box2d.renderDebugDraw(this.context); + + this.stop(); + + }, + + /** + * Renders 'debug draw' data for the given Box2D body. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dBody + * @param {Phaser.Physics.Box2D.Body} body - The body to be rendered. + * @param {string} [color='rgb(0,255,0)'] - Color of the rendering (format is css color string). + */ + box2dBody: function (body, color) { + + this.start(); + Phaser.Physics.Box2D.renderBody(this.context, body, color); + this.stop(); + + }, + + /** + * Call this function from the Dev Tools console. + * + * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. + * + * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) + * + * @method Phaser.Utils.Debug#displayList + * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World. + */ + displayList: function (displayObject) { + + if (displayObject === undefined) { displayObject = this.game.world; } + + if (displayObject.hasOwnProperty('renderOrderID')) + { + console.log('[' + displayObject.renderOrderID + ']', displayObject); + } + else + { + console.log('[]', displayObject); + } + + if (displayObject.children && displayObject.children.length > 0) + { + for (var i = 0; i < displayObject.children.length; i++) + { + this.game.debug.displayList(displayObject.children[i]); + } + } + + }, + + /** + * Prints a description of the {@link Phaser.Game#renderer renderer} and render session. + * + * @method Phaser.Utils.Debug#renderer + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + renderer: function (x, y, color) { + + var r = this.game.renderer; + var s = r.renderSession; + + this.start(x, y, color); + + this.line((r.gl ? 'WebGL' : 'Canvas') + ' Renderer (' + r.width + ' x ' + r.height + ')'); + this.line('autoResize: ' + r.autoResize); + this.line('clearBeforeRender: ' + r.clearBeforeRender); + this.line('resolution: ' + r.resolution); + this.line('transparent: ' + r.transparent); + this.line('renderSession:'); + + if (r.gl) + { + this.line(' currentBatchedTextures: ('+ r.currentBatchedTextures.length + ')'); + + for (var i = 0; i < r.currentBatchedTextures.length; i++) + { + this.line(' ' + r.currentBatchedTextures[i]); + } + + this.line(' drawCount: ' + s.drawCount); + this.line(' maxTextures: ' + r.maxTextures); + this.line(' maxTextureSize: ' + r.maxTextureSize); + this.line(' maxTextureAvailableSpace: ' + s.maxTextureAvailableSpace); + this.line(' roundPixels: ' + s.roundPixels); + } + else + { + this.line(' roundPixels: ' + s.roundPixels); + this.line(' scaleMode: ' + (s.scaleMode === 0 ? 'LINEAR' : (s.scaleMode === 1 ? 'NEAREST' : s.scaleMode))); + } + + this.stop(); + + }, + + canvasPool: function (x, y, color, columnWidth) { + var pool = Phaser.CanvasPool; + + this.start(x, y, color, columnWidth || 100); + this.line('Canvas Pool'); + this.line('Used:', pool.getTotal()); + this.line('Free:', pool.getFree()); + this.line('Total:', pool.length); + this.stop(); + }, + + /** + * Render each physics {@link #body} in a group. + * + * @method Phaser.Utils.Debug#physicsGroup + * @param {Phaser.Group} group - A group containing physics-enabled sprites. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false). + * @param {boolean} [checkExists=false] Render only children with `exists=true`. + */ + physicsGroup: function (group, color, filled, checkExists) { + + group.forEach(this.body, this, checkExists, color, filled); + + }, + + /** + * Prints Phaser {@link Phaser.VERSION version}, {@link Phaser.Game.#renderType rendering mode}, and {@link Phaser.Device#webAudio device audio support}. + * + * @method Phaser.Utils.Debug#phaser + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + phaser: function (x, y, color) { + + this.text('Phaser v' + Phaser.VERSION + ' ' + + (this.game.renderType === Phaser.WEBGL ? 'WebGL' : 'Canvas') + ' ' + + (this.game.device.webAudio ? 'WebAudio' : 'HTML Audio'), + x, y, color, this.font); + + }, + + /** + * Prints game/canvas dimensions and {@link Phaser.ScaleManager game scale} settings. + * + * @method Phaser.Utils.Debug#scale + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + scale: function (x, y, color) { + + this.start(x, y, color); + + var scale = this.game.scale; + var factor = scale.scaleFactorInversed; + var bounds = scale._parentBounds; + var x = ' x '; + + this.line('Game: ' + this.game.width + x + this.game.height); + this.line('Canvas: ' + scale.width + x + scale.height + + ' (' + factor.x.toFixed(2) + x + factor.y.toFixed(2) + ')' + + ' [' + scale.aspectRatio.toFixed(2) + ']'); + this.line('Mode: ' + Phaser.ScaleManager.MODES[scale.currentScaleMode] + + (scale.currentScaleMode === Phaser.ScaleManager.USER_SCALE ? + (' (' + scale._userScaleFactor.x + x + scale._userScaleFactor.y + ')') : + '')); + this.line('Parent: ' + (scale.parentIsWindow ? 'window' : scale.parentNode) + + (bounds.empty ? '' : (' (' + bounds.width + x + bounds.height + ')'))); + this.line('Screen: ' + scale.classifyOrientation(scale.screenOrientation) + + (scale.incorrectOrientation ? ' (incorrect)' : '')); + + this.stop(); + + }, + + /** + * Prints the progress of a {@link Phaser.Loader}. + * + * Typically you would call this within a {@link State#loadRender} callback and pass `game.load` ({@link Phaser.Game#load}). + * + * You can enable {@link Phaser.Loader#resetLocked} to temporarily hold the loader in its 'complete' state. + * Just remember to disable it before restarting the loader (such as when changing states). + * + * @method Phaser.Utils.Debug#loader + * @param {Phaser.Loader} loader - The loader. Usually `game.load` ({@link Phaser.Game#load}). + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + loader: function (loader, x, y, color) { + + var pad = Phaser.Utils.pad; + + this.start(x, y, color); + + if (loader.hasLoaded) + { + this.line('Complete' + (loader.resetLocked ? ' [locked]' : '')); + } + else if (loader.isLoading) + { + this.line('Loading'); + } + else + { + this.line('Not started'); + } + + if (!loader.hasLoaded || loader.resetLocked) + { + this.line('Progress: ' + (pad(loader.progress, 3) + '%')); + this.line('Files: ' + loader._loadedFileCount + ' of ' + + loader._totalFileCount); + this.line('Packs: ' + loader._loadedPackCount + ' of ' + + loader._loadedPackCount); + } + + this.stop(); + + }, + + /** + * Destroy this object. + * + * @method Phaser.Utils.Debug#destroy + */ + destroy: function () { + + Phaser.CanvasPool.remove(this); + + } + +}; + +Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DOM utility class. +* +* Provides a useful Window and Element functions as well as cross-browser compatibility buffer. +* +* Some code originally derived from {@link https://github.com/ryanve/verge verge}. +* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. +* +* @class Phaser.DOM +* @static +*/ +Phaser.DOM = { + + /** + * Get the [absolute] position of the element relative to the Document. + * + * The value may vary slightly as the page is scrolled due to rounding errors. + * + * @method Phaser.DOM.getOffset + * @param {DOMElement} element - The targeted element that we want to retrieve the offset. + * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. + * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. + */ + getOffset: function (element, point) { + + point = point || new Phaser.Point(); + + var box = element.getBoundingClientRect(); + + var scrollTop = Phaser.DOM.scrollY; + var scrollLeft = Phaser.DOM.scrollX; + var clientTop = document.documentElement.clientTop; + var clientLeft = document.documentElement.clientLeft; + + point.x = box.left + scrollLeft - clientLeft; + point.y = box.top + scrollTop - clientTop; + + return point; + + }, + + /** + * A cross-browser element.getBoundingClientRect method with optional cushion. + * + * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. + * Its properties match the native rectangle. + * The cushion parameter is an amount of pixels (+/-) to cushion the element. + * It adjusts the measurements such that it is possible to detect when an element is near the viewport. + * + * @method Phaser.DOM.getBounds + * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for. + * @param {number} [cushion] - A +/- pixel adjustment amount. + * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. + */ + getBounds: function (element, cushion) { + + if (cushion === undefined) { cushion = 0; } + + element = element && !element.nodeType ? element[0] : element; + + if (!element || element.nodeType !== 1) + { + return false; + } + else + { + return this.calibrate(element.getBoundingClientRect(), cushion); + } + + }, + + /** + * Calibrates element coordinates for `inLayoutViewport` checks. + * + * @method Phaser.DOM.calibrate + * @private + * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}` + * @param {number} [cushion] - A value to adjust the coordinates by. + * @return {object} The calibrated element coordinates + */ + calibrate: function (coords, cushion) { + + cushion = +cushion || 0; + + var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 }; + + output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion); + output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion); + + return output; + + }, + + /** + * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) + * + * @method Phaser.DOM.getAspectRatio + * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. + * @return {number} The aspect ratio. + */ + getAspectRatio: function (object) { + + object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object; + + var w = object['width']; + var h = object['height']; + + if (typeof w === 'function') + { + w = w.call(object); + } + + if (typeof h === 'function') + { + h = h.call(object); + } + + return w / h; + + }, + + /** + * Tests if the given DOM element is within the Layout viewport. + * + * The optional cushion parameter allows you to specify a distance. + * + * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. + * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. + * + * @method Phaser.DOM.inLayoutViewport + * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas. + * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport. + * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it. + */ + inLayoutViewport: function (element, cushion) { + + var r = this.getBounds(element, cushion); + + return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height; + + }, + + /** + * Returns the device screen orientation. + * + * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. + * + * Order of resolving: + * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. + * - Screen size ratio check - If fallback is 'screen', suited for desktops. + * - Viewport size ratio check - If fallback is 'viewport', suited for mobile. + * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. + * - Media query + * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..) + * + * See + * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) + * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) + * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx + * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries + * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation + * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation + * + * @method Phaser.DOM.getScreenOrientation + * @protected + * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'. + */ + getScreenOrientation: function (primaryFallback) { + + var screen = window.screen; + var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; + + if (orientation && typeof orientation.type === 'string') + { + // Screen Orientation API specification + return orientation.type; + } + else if (typeof orientation === 'string') + { + // moz/ms-orientation are strings + return orientation; + } + + var PORTRAIT = 'portrait-primary'; + var LANDSCAPE = 'landscape-primary'; + + if (primaryFallback === 'screen') + { + return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'viewport') + { + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number') + { + // This may change by device based on "natural" orientation. + return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE; + } + else if (window.matchMedia) + { + if (window.matchMedia("(orientation: portrait)").matches) + { + return PORTRAIT; + } + else if (window.matchMedia("(orientation: landscape)").matches) + { + return LANDSCAPE; + } + } + + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + + }, + + /** + * The bounds of the Visual viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one} + * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers. + * + * Supported mobile: + * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} x - Scroll, left offset - eg. "scrollX" + * @property {number} y - Scroll, top offset - eg. "scrollY" + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + visualBounds: new Phaser.Rectangle(), + + /** + * The bounds of the Layout viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two}; + * but honoring the constraints as specified applicable viewport meta-tag. + * + * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see + * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}). + * + * This is _not_ representative of the Visual bounds: in particular the non-primary axis will + * generally be significantly larger than the screen height on mobile devices when running with a + * constrained viewport. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + layoutBounds: new Phaser.Rectangle(), + + /** + * The size of the document / Layout viewport. + * + * This incorrectly reports the dimensions in IE. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Document width in pixels. + * @property {number} height - Document height in pixels. + * @readonly + */ + documentBounds: new Phaser.Rectangle() + +}; + +Phaser.Device.whenReady(function (device) { + + // All target browsers should support page[XY]Offset. + var scrollX = window && ('pageXOffset' in window) ? + function () { return window.pageXOffset; } : + function () { return document.documentElement.scrollLeft; }; + + var scrollY = window && ('pageYOffset' in window) ? + function () { return window.pageYOffset; } : + function () { return document.documentElement.scrollTop; }; + + /** + * A cross-browser window.scrollX. + * + * @name Phaser.DOM.scrollX + * @property {number} scrollX + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollX", { + get: scrollX + }); + + /** + * A cross-browser window.scrollY. + * + * @name Phaser.DOM.scrollY + * @property {number} scrollY + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollY", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "x", { + get: scrollX + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "y", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "y", { + value: 0 + }); + + var treatAsDesktop = device.desktop && + (document.documentElement.clientWidth <= window.innerWidth) && + (document.documentElement.clientHeight <= window.innerHeight); + + // Desktop browsers align the layout viewport with the visual viewport. + // This differs from mobile browsers with their zooming design. + // Ref. http://quirksmode.org/mobile/tableViewport.html + if (treatAsDesktop) + { + + // PST- When scrollbars are not included this causes upstream issues in ScaleManager. + // So reverted to the old "include scrollbars." + var clientWidth = function () { + return Math.max(window.innerWidth, document.documentElement.clientWidth); + }; + var clientHeight = function () { + return Math.max(window.innerHeight, document.documentElement.clientHeight); + }; + + // Interested in area sans-scrollbar + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: clientHeight + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + get: clientHeight + }); + + } else { + + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: function () { + return window.innerWidth; + } + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: function () { + return window.innerHeight; + } + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + + get: function () { + var a = document.documentElement.clientWidth; + var b = window.innerWidth; + + return a < b ? b : a; // max + } + + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + + get: function () { + var a = document.documentElement.clientHeight; + var b = window.innerHeight; + + return a < b ? b : a; // max + } + + }); + + } + + // For Phaser.DOM.documentBounds + // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html + + Object.defineProperty(Phaser.DOM.documentBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "y", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "width", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth); + } + + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "height", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight); + } + + }); + +}, null, true); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* ArraySet is a Set data structure (items must be unique within the set) that also maintains order. +* This allows specific items to be easily added or removed from the Set. +* +* Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. +* +* This used primarily by the Input subsystem. +* +* @class Phaser.ArraySet +* @constructor +* @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet. +*/ +Phaser.ArraySet = function (list) { + + /** + * Current cursor position as established by `first` and `next`. + * @property {integer} position + * @default + */ + this.position = 0; + + /** + * The backing array. + * @property {any[]} list + */ + this.list = list || []; + +}; + +Phaser.ArraySet.prototype = { + + /** + * Adds a new element to the end of the list. + * If the item already exists in the list it is not moved. + * + * @method Phaser.ArraySet#add + * @param {any} item - The element to add to this list. + * @return {any} The item that was added. + */ + add: function (item) { + + if (!this.exists(item)) + { + this.list.push(item); + } + + return item; + + }, + + /** + * Gets the index of the item in the list, or -1 if it isn't in the list. + * + * @method Phaser.ArraySet#getIndex + * @param {any} item - The element to get the list index for. + * @return {integer} The index of the item or -1 if not found. + */ + getIndex: function (item) { + + return this.list.indexOf(item); + + }, + + /** + * Gets an item from the set based on the property strictly equaling the value given. + * Returns null if not found. + * + * @method Phaser.ArraySet#getByKey + * @param {string} property - The property to check against the value. + * @param {any} value - The value to check if the property strictly equals. + * @return {any} The item that was found, or null if nothing matched. + */ + getByKey: function (property, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i][property] === value) + { + return this.list[i]; + } + } + + return null; + + }, + + /** + * Checks for the item within this list. + * + * @method Phaser.ArraySet#exists + * @param {any} item - The element to get the list index for. + * @return {boolean} True if the item is found in the list, otherwise false. + */ + exists: function (item) { + + return (this.list.indexOf(item) > -1); + + }, + + /** + * Removes all the items. + * + * @method Phaser.ArraySet#reset + */ + reset: function () { + + this.list.length = 0; + + }, + + /** + * Removes the given element from this list if it exists. + * + * @method Phaser.ArraySet#remove + * @param {any} item - The item to be removed from the list. + * @return {any} item - The item that was removed. + */ + remove: function (item) { + + var idx = this.list.indexOf(item); + + if (idx > -1) + { + this.list.splice(idx, 1); + return item; + } + + }, + + /** + * Sets the property `key` to the given value on all members of this list. + * + * @method Phaser.ArraySet#setAll + * @param {any} key - The property of the item to set. + * @param {any} value - The value to set the property to. + */ + setAll: function (key, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + this.list[i][key] = value; + } + } + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * + * If the `key` property is present it must be a function. + * The function is invoked using the item as the context. + * + * @method Phaser.ArraySet#callAll + * @param {string} key - The name of the property with the function to call. + * @param {...*} parameter - Additional parameters that will be passed to the callback. + */ + callAll: function (key) { + + var args = Array.prototype.slice.call(arguments, 1); + + var i = this.list.length; + + while (i--) + { + if (this.list[i] && this.list[i][key]) + { + this.list[i][key].apply(this.list[i], args); + } + } + + }, + + /** + * Removes every member from this ArraySet and optionally destroys it. + * + * @method Phaser.ArraySet#removeAll + * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set. + */ + removeAll: function (destroy) { + + if (destroy === undefined) { destroy = false; } + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + var item = this.remove(this.list[i]); + + if (destroy) + { + item.destroy(); + } + } + } + + this.position = 0; + this.list = []; + + } + +}; + +/** +* Number of items in the ArraySet. Same as `list.length`. +* +* @name Phaser.ArraySet#total +* @property {integer} total +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "total", { + + get: function () { + return this.list.length; + } + +}); + +/** +* Returns the first item and resets the cursor to the start. +* +* @name Phaser.ArraySet#first +* @property {any} first +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "first", { + + get: function () { + + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + + } + +}); + +/** +* Returns the the next item (based on the cursor) and advances the cursor. +* +* @name Phaser.ArraySet#next +* @property {any} next +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "next", { + + get: function () { + + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + + } + +}); + +Phaser.ArraySet.prototype.constructor = Phaser.ArraySet; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Utility functions for dealing with Arrays. +* +* @class Phaser.ArrayUtils +* @static +*/ +Phaser.ArrayUtils = { + + /** + * Fetch a random entry from the given array. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.getRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was selected. + */ + getRandomItem: function (objects, startIndex, length) { + + if (objects === null) { return null; } + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + + return objects[randomIndex] === undefined ? null : objects[randomIndex]; + + }, + + /** + * Removes a random object from the given array and returns it. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.removeRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was removed. + */ + removeRandomItem: function (objects, startIndex, length) { + + if (objects == null) { // undefined or null + return null; + } + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + if (randomIndex < objects.length) + { + var removed = objects.splice(randomIndex, 1); + return removed[0] === undefined ? null : removed[0]; + } + else + { + return null; + } + + }, + + /** + * Remove one or more items at the given index and reorder the array. + * + * The new array length will be `array.length - count`. + * + * This is an alternative to `array.splice(startIndex, count)`. + * + * @see https://github.com/mreinstein/remove-array-items + * @see https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ + * + * @method Phaser.ArrayUtils.remove + * @param {any[]} array + * @param {integer} startIndex + * @param {integer} [count=1] + * @return {any[]} The modified array. + */ + remove: function (array, startIndex, count) + { + var length = array.length; + + if (startIndex >= length || count === 0) { return; } + + if (count == null) { count = 1; } + + var newLength = length - count; + + for (var i = startIndex; i < newLength; ++i) + { + array[i] = array[i + count]; + } + + array.length = newLength; + }, + + /** + * A standard Fisher-Yates Array shuffle implementation which modifies the array in place. + * + * @method Phaser.ArrayUtils.shuffle + * @param {any[]} array - The array to shuffle. + * @return {any[]} The original array, now shuffled. + */ + shuffle: function (array) { + + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; + + }, + + /** + * Transposes the elements of the given matrix (array of arrays). + * + * @method Phaser.ArrayUtils.transposeMatrix + * @param {Array} array - The matrix to transpose. + * @return {Array} A new transposed matrix + */ + transposeMatrix: function (array) { + + var sourceRowCount = array.length; + var sourceColCount = array[0].length; + + var result = new Array(sourceColCount); + + for (var i = 0; i < sourceColCount; i++) + { + result[i] = new Array(sourceRowCount); + + for (var j = sourceRowCount - 1; j > -1; j--) + { + result[i][j] = array[j][i]; + } + } + + return result; + + }, + + /** + * Rotates the given matrix (array of arrays). + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @method Phaser.ArrayUtils.rotateMatrix + * @param {Array} matrix - The array to rotate; this matrix _may_ be altered. + * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). + * @return {Array} The rotated matrix. The source matrix should be discarded for the returned matrix. + */ + rotateMatrix: function (matrix, direction) { + + if (typeof direction !== 'string') + { + direction = ((direction % 360) + 360) % 360; + } + + if (direction === 90 || direction === -270 || direction === 'rotateLeft') + { + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + matrix = matrix.reverse(); + } + else if (direction === -90 || direction === 270 || direction === 'rotateRight') + { + matrix = matrix.reverse(); + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + } + else if (Math.abs(direction) === 180 || direction === 'rotate180') + { + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + matrix = matrix.reverse(); + } + + return matrix; + + }, + + /** + * Snaps a value to the nearest value in a sorted numeric array. + * The result will always be in the range `[first_value, last_value]`. + * + * @method Phaser.ArrayUtils.findClosest + * @param {number} value - The search value + * @param {number[]} arr - The input array which _must_ be sorted. + * @return {number} The nearest value found. + */ + findClosest: function (value, arr) { + + if (!arr.length) + { + return NaN; + } + else if (arr.length === 1 || value < arr[0]) + { + return arr[0]; + } + + var i = 1; + while (arr[i] < value) { + i++; + } + + var low = arr[i - 1]; + var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; + + return ((high - value) <= (value - low)) ? high : low; + + }, + + /** + * Moves the element from the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ F, A, B, C, D, E ]` + * + * See also Phaser.ArrayUtils.rotateLeft. + * + * @method Phaser.ArrayUtils.rotateRight + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The shifted value. + */ + rotateRight: function (array) { + + var s = array.pop(); + array.unshift(s); + + return s; + + }, + + /** + * Moves the element from the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ B, C, D, E, F, A ]` + * + * See also Phaser.ArrayUtils.rotateRight + * + * @method Phaser.ArrayUtils.rotateLeft + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The rotated value. + */ + rotateLeft: function (array) { + + var s = array.shift(); + array.push(s); + + return s; + + }, + + /** + * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]` (or `[0, start]`, if `end` is omitted). + * This is equivalent to `numberArrayStep(start, 1 + end, 1)`. + * + * When exactly one argument is passed, it's used as `end` and 0 is used as `start`. The length of the result is (1 + end). + * + * ##### Examples + * + * ```javascript + * numberArray(3); // -> [0, 1, 2, 3] + * numberArray(0, 3); // -> [0, 1, 2, 3] + * numberArray(1, 3); // -> [1, 2, 3] + * ``` + * + * @method Phaser.ArrayUtils.numberArray + * @param {number} start - The minimum value the array starts with. + * @param {number} [end] - The maximum value the array contains. + * @return {number[]} The array of number values. + */ + numberArray: function (start, end) { + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + var result = []; + + for (var i = start; i <= end; i++) + { + result.push(i); + } + + return result; + + }, + + /** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @method Phaser.ArrayUtils.numberArrayStep + * @param {number} start - The start of the range. + * @param {number} [end] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * @returns {Array} Returns the new array of numbers. + * @example + * Phaser.ArrayUtils.numberArrayStep(4); + * // => [0, 1, 2, 3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * Phaser.ArrayUtils.numberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * Phaser.ArrayUtils.numberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * Phaser.ArrayUtils.numberArrayStep(0); + * // => [] + */ + numberArrayStep: function (start, end, step) { + + if (start === undefined || start === null) { start = 0; } + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + if (step === undefined) { step = 1; } + + var result = []; + var total = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0); + + for (var i = 0; i < total; i++) + { + result.push(start); + start += step; + } + + return result; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A basic Linked List data structure. +* +* This implementation _modifies_ the `prev` and `next` properties of each item added: +* - The `prev` and `next` properties must be writable and should not be used for any other purpose. +* - Items _cannot_ be added to multiple LinkedLists at the same time. +* - Only objects can be added. +* +* @class Phaser.LinkedList +* @constructor +*/ +Phaser.LinkedList = function () { + + /** + * Next element in the list. + * @property {object} next + * @default + */ + this.next = null; + + /** + * Previous element in the list. + * @property {object} prev + * @default + */ + this.prev = null; + + /** + * First element in the list. + * @property {object} first + * @default + */ + this.first = null; + + /** + * Last element in the list. + * @property {object} last + * @default + */ + this.last = null; + + /** + * Number of elements in the list. + * @property {integer} total + * @default + */ + this.total = 0; + +}; + +Phaser.LinkedList.prototype = { + + /** + * Adds a new element to this linked list. + * + * @method Phaser.LinkedList#add + * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. + * @return {object} The item that was added. + */ + add: function (item) { + + // If the list is empty + if (this.total === 0 && this.first === null && this.last === null) + { + this.first = item; + this.last = item; + this.next = item; + item.prev = this; + this.total++; + return item; + } + + // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list) + this.last.next = item; + + item.prev = this.last; + + this.last = item; + + this.total++; + + return item; + + }, + + /** + * Resets the first, last, next and previous node pointers in this list. + * + * @method Phaser.LinkedList#reset + */ + reset: function () { + + this.first = null; + this.last = null; + this.next = null; + this.prev = null; + this.total = 0; + + }, + + /** + * Removes the given element from this linked list if it exists. + * + * @method Phaser.LinkedList#remove + * @param {object} item - The item to be removed from the list. + */ + remove: function (item) { + + if (this.total === 1) + { + this.reset(); + item.next = item.prev = null; + return; + } + + if (item === this.first) + { + // It was 'first', make 'first' point to first.next + this.first = this.first.next; + } + else if (item === this.last) + { + // It was 'last', make 'last' point to last.prev + this.last = this.last.prev; + } + + if (item.prev) + { + // make item.prev.next point to childs.next instead of item + item.prev.next = item.next; + } + + if (item.next) + { + // make item.next.prev point to item.prev instead of item + item.next.prev = item.prev; + } + + item.next = item.prev = null; + + if (this.first === null ) + { + this.last = null; + } + + this.total--; + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * The function must exist on the member. + * + * @method Phaser.LinkedList#callAll + * @param {function} callback - The function to call. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content +* quickly and easily, without the need for any external files. You can create textures for sprites and in +* coming releases we'll add dynamic sound effect generation support as well (like sfxr). +* +* Access this via `Game.create` (`this.game.create` from within a State object). +* +* @class Phaser.Create +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Create = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.ctx = null; + + /** + * @property {array} palettes - A range of 16 color palettes for use with sprite generation. + */ + this.palettes = [ + { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' }, + { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' }, + { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' } + ]; + +}; + +/** +* A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_ARNE = 0; + +/** +* A 16 color JMP inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JMP = 1; + +/** +* A 16 color CGA inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_CGA = 2; + +/** +* A 16 color C64 inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_C64 = 3; + +/** +* A 16 color palette inspired by Japanese computers like the MSX. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JAPANESE_MACHINE = 4; + +Phaser.Create.prototype = { + + /** + * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite. + * + * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images + * rather than Phaser.Graphics objects, which are expensive to render and limited in scope. + * + * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts. + * + * For example: + * + * `var data = [ + * ' 333 ', + * ' 777 ', + * 'E333E', + * ' 333 ', + * ' 3 3 ' + * ];` + * + * `game.create.texture('bob', data);` + * + * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it + * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');` + * + * Use {@link Phaser.Loader#imageFromTexture} to preload an image of the same. + * + * @method Phaser.Create#texture + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {array} data - An array of pixel data. + * @param {integer} [pixelWidth=8] - The width of each pixel. + * @param {integer} [pixelHeight=8] - The height of each pixel. + * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + texture: function (key, data, pixelWidth, pixelHeight, palette, generateTexture, callback, callbackContext) { + + if (pixelWidth === undefined) { pixelWidth = 8; } + if (pixelHeight === undefined) { pixelHeight = pixelWidth; } + if (palette === undefined) { palette = 0; } + if (generateTexture === undefined) { generateTexture = true; } + + var w = data[0].length * pixelWidth; + var h = data.length * pixelHeight; + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(w, h); + this.bmd.clear(); + + // Draw it + for (var y = 0; y < data.length; y++) + { + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var d = row[x]; + + if (d !== '.' && d !== ' ') + { + this.ctx.fillStyle = this.palettes[palette][d]; + this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); + } + } + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Creates a grid texture based on the given dimensions. + * + * Use {@link Phaser.Loader#imageFromGrid} to preload an image of the same. + * + * @method Phaser.Create#grid + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {integer} width - The width of the grid in pixels. + * @param {integer} height - The height of the grid in pixels. + * @param {integer} cellWidth - The width of the grid cells in pixels. + * @param {integer} cellHeight - The height of the grid cells in pixels. + * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + grid: function (key, width, height, cellWidth, cellHeight, color, generateTexture, callback, callbackContext) { + + if (generateTexture === undefined) { generateTexture = true; } + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(width, height); + + this.ctx.fillStyle = color; + + for (var y = 0; y < height; y += cellHeight) + { + this.ctx.fillRect(0, y, width, 1); + } + + for (var x = 0; x < width; x += cellWidth) + { + this.ctx.fillRect(x, 0, 1, height); + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Copies the contents of {@link bmd Create's canvas} to the given BitmapData object, or a new BitmapData object. + * + * @param {Phaser.BitmapData} [dest] - The BitmapData receiving the copied image. + * @param {number} [x=0] - The x coordinate to translate to before drawing. + * @param {number} [y=0] - The y coordinate to translate to before drawing. + * @param {number} [width] - The new width of the Sprite being copied. + * @param {number} [height] - The new height of the Sprite being copied. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} - The `dest` argument (if passed), or a new BitmapData object + */ + copy: function (dest, x, y, width, height, blendMode, roundPx) { + + if (dest == null) { dest = this.game.make.bitmapData(); } + + dest.resize(this.bmd.width, this.bmd.height); + + return dest.draw(this.bmd, x, y, width, height, blendMode, roundPx); + + } + +}; + +Phaser.Create.prototype.constructor = Phaser.Create; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers +* to provide for game object positioning in a responsive manner. +* +* @class Phaser.FlexGrid +* @constructor +* @param {Phaser.ScaleManager} manager - The ScaleManager. +* @param {number} width - The width of the game. +* @param {number} height - The height of the game. +*/ +Phaser.FlexGrid = function (manager, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = manager.game; + + /** + * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager. + */ + this.manager = manager; + + // The perfect dimensions on which everything else is based + this.width = width; + this.height = height; + + this.boundsCustom = new Phaser.Rectangle(0, 0, width, height); + this.boundsFluid = new Phaser.Rectangle(0, 0, width, height); + this.boundsFull = new Phaser.Rectangle(0, 0, width, height); + this.boundsNone = new Phaser.Rectangle(0, 0, width, height); + + /** + * @property {Phaser.Point} position - + * @readonly + */ + this.positionCustom = new Phaser.Point(0, 0); + this.positionFluid = new Phaser.Point(0, 0); + this.positionFull = new Phaser.Point(0, 0); + this.positionNone = new Phaser.Point(0, 0); + + /** + * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. + * @readonly + */ + this.scaleCustom = new Phaser.Point(1, 1); + this.scaleFluid = new Phaser.Point(1, 1); + this.scaleFluidInversed = new Phaser.Point(1, 1); + this.scaleFull = new Phaser.Point(1, 1); + this.scaleNone = new Phaser.Point(1, 1); + + this.customWidth = 0; + this.customHeight = 0; + this.customOffsetX = 0; + this.customOffsetY = 0; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.multiplier = 0; + + this.layers = []; + +}; + +Phaser.FlexGrid.prototype = { + + /** + * Sets the core game size. This resets the w/h parameters and bounds. + * + * @method Phaser.FlexGrid#setSize + * @param {number} width - The new dimensions. + * @param {number} height - The new dimensions. + */ + setSize: function (width, height) { + + // These are locked and don't change until setSize is called again + this.width = width; + this.height = height; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.scaleNone = new Phaser.Point(1, 1); + + this.boundsNone.width = this.width; + this.boundsNone.height = this.height; + + this.refresh(); + + }, + + // Need ability to create your own layers with custom scaling, etc. + + /** + * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createCustomLayer + * @param {number} width - Width of this layer in pixels. + * @param {number} height - Height of this layer in pixels. + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createCustomLayer: function (width, height, children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + this.customWidth = width; + this.customHeight = height; + + this.boundsCustom.width = width; + this.boundsCustom.height = height; + + var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createFluidLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFluidLayer: function (children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios. + * + * @method Phaser.FlexGrid#createFullLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFullLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled. + * + * @method Phaser.FlexGrid#createFixedLayer + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFixedLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * Resets the layer children references + * + * @method Phaser.FlexGrid#reset + */ + reset: function () { + + var i = this.layers.length; + + while (i--) + { + if (!this.layers[i].persist) + { + // Remove references to this class + this.layers[i].position = null; + this.layers[i].scale = null; + this.layers.slice(i, 1); + } + } + + }, + + /** + * Called when the game container changes dimensions. + * + * @method Phaser.FlexGrid#onResize + * @param {number} width - The new width of the game container. + * @param {number} height - The new height of the game container. + */ + onResize: function (width, height) { + + this.ratioH = width / height; + this.ratioV = height / width; + + this.refresh(width, height); + + }, + + /** + * Updates all internal vars such as the bounds and scale values. + * + * @method Phaser.FlexGrid#refresh + */ + refresh: function () { + + this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width)); + + this.boundsFluid.width = Math.round(this.width * this.multiplier); + this.boundsFluid.height = Math.round(this.height * this.multiplier); + + this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height); + this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height); + + this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height); + + this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x); + this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y); + + this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + + this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y); + this.positionNone.set(this.boundsNone.x, this.boundsNone.y); + + }, + + /** + * Fits a sprites width to the bounds. + * + * @method Phaser.FlexGrid#fitSprite + * @param {Phaser.Sprite} sprite - The Sprite to fit. + */ + fitSprite: function (sprite) { + + this.manager.scaleSprite(sprite); + + sprite.x = this.manager.bounds.centerX; + sprite.y = this.manager.bounds.centerY; + + }, + + /** + * Call in the render function to output the bounds rects. + * + * @method Phaser.FlexGrid#debug + */ + debug: function () { + + // for (var i = 0; i < this.layers.length; i++) + // { + // this.layers[i].debug(); + // } + + // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16); + // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false); + + this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16); + this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false); + + // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16); + // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false); + + // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16); + // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false); + + } + +}; + +Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* A responsive grid layer. +* +* @class Phaser.FlexLayer +* @extends Phaser.Group +* @constructor +* @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer. +* @param {Phaser.Point} position - A reference to the Point object used for positioning. +* @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds. +* @param {Phaser.Point} scale - A reference to the Point object used for layer scaling. +*/ +Phaser.FlexLayer = function (manager, position, bounds, scale) { + + Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false); + + /** + * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager. + */ + this.manager = manager.manager; + + /** + * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer. + */ + this.grid = manager; + + /** + * Should the FlexLayer remain through a State swap? + * + * @type {boolean} + */ + this.persist = false; + + /** + * @property {Phaser.Point} position + */ + this.position = position; + + /** + * @property {Phaser.Rectangle} bounds + */ + this.bounds = bounds; + + /** + * @property {Phaser.Point} scale + */ + this.scale = scale; + + /** + * @property {Phaser.Point} topLeft + */ + this.topLeft = bounds.topLeft; + + /** + * @property {Phaser.Point} topMiddle + */ + this.topMiddle = new Phaser.Point(bounds.halfWidth, 0); + + /** + * @property {Phaser.Point} topRight + */ + this.topRight = bounds.topRight; + + /** + * @property {Phaser.Point} bottomLeft + */ + this.bottomLeft = bounds.bottomLeft; + + /** + * @property {Phaser.Point} bottomMiddle + */ + this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom); + + /** + * @property {Phaser.Point} bottomRight + */ + this.bottomRight = bounds.bottomRight; + +}; + +Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype); +Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer; + +/** + * Resize. + * + * @method Phaser.FlexLayer#resize + */ +Phaser.FlexLayer.prototype.resize = function () { +}; + +/** + * Debug. + * + * @method Phaser.FlexLayer#debug + */ +Phaser.FlexLayer.prototype.debug = function () { + + this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16); + this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false); + + this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9'); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. +* +* @class Phaser.Color +*/ +Phaser.Color = { + + /** + * Red (0xff0000) + * + * @type number + * @constant + * @default + */ + RED: 0xff0000, + + /** + * Orange (0xff9900) + * + * @type number + * @constant + * @default + */ + ORANGE: 0xff9900, + + /** + * Yellow (0xffff00) + * + * @type number + * @constant + * @default + */ + YELLOW: 0xffff00, + + /** + * Green (0x00ff00) + * + * @type number + * @constant + * @default + */ + GREEN: 0x00ff00, + + /** + * Aqua (0x00ffff) + * + * @type number + * @constant + * @default + */ + AQUA: 0x00ffff, + + /** + * Blue (0x0000ff) + * + * @type number + * @constant + * @default + */ + BLUE: 0x0000ff, + + /** + * Violet/purple (0xff00ff) + * + * @type number + * @constant + * @default + */ + VIOLET: 0xff00ff, + + /** + * White (0xffffff) + * + * @type number + * @constant + * @default + */ + WHITE: 0xffffff, + + /** + * Black (0x000000) + * + * @type number + * @constant + * @default + */ + BLACK: 0, + + /** + * Gray (0x666666) + * + * @type number + * @constant + * @default + */ + GRAY: 0x666666, + + /** + * Packs the r, g, b, a components into a single integer, for use with Int32Array. + * If device is little endian then ABGR order is used. Otherwise RGBA order is used. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.packPixel + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} The packed color as uint32 + */ + packPixel: function (r, g, b, a) { + + if (Phaser.Device.LITTLE_ENDIAN) + { + return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0; + } + else + { + return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0; + } + + }, + + /** + * Unpacks the r, g, b, a components into the specified color object, or a new + * object, for use with Int32Array. If little endian, then ABGR order is used when + * unpacking, otherwise, RGBA order is used. The resulting color object has the + * `r, g, b, a` properties which are unrelated to endianness. + * + * Note that the integer is assumed to be packed in the correct endianness. On little-endian + * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a + * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.unpackPixel + * @static + * @param {number} rgba - The integer, packed in endian order by packPixel. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + unpackPixel: function (rgba, out, hsl, hsv) { + + if (out === undefined || out === null) { out = Phaser.Color.createColor(); } + if (hsl === undefined || hsl === null) { hsl = false; } + if (hsv === undefined || hsv === null) { hsv = false; } + + if (Phaser.Device.LITTLE_ENDIAN) + { + out.a = ((rgba & 0xff000000) >>> 24); + out.b = ((rgba & 0x00ff0000) >>> 16); + out.g = ((rgba & 0x0000ff00) >>> 8); + out.r = ((rgba & 0x000000ff)); + } + else + { + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + } + + 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; + + }, + + /** + * A utility to convert an integer in 0xRRGGBBAA format to a color object. + * This does not rely on endianness. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.fromRGBA + * @static + * @param {number} rgba - An RGBA hex + * @param {object} [out] - The object to use, optional. + * @return {object} A color object. + */ + fromRGBA: function (rgba, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + + out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')'; + + return out; + + }, + + /** + * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.toRGBA + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toRGBA: function (r, g, b, a) { + + return (r << 24) | (g << 16) | (b << 8) | a; + + }, + + /** + * Converts RGBA components to a 32 bit integer in AABBGGRR format. + * + * @method Phaser.Color.toABGR + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toABGR: function (r, g, b, a) { + + return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; + + }, + + /** + * Converts a hex color value to an [R, G, B] array. + * + * @static + * @method Phaser.Color.hexToRGBArray + * @param {number} color - The color to convert to an RGB array. In the format 0xRRGGBB. + * @return {array} An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + */ + hexToRGBArray: function (color) { + + return [ + (color >> 16 & 0xFF) / 255, + (color >> 8 & 0xFF) / 255, + (color & 0xFF) / 255 + ]; + + }, + + /** + * Converts an RGB color array, in the format: [R, G, B], to a hex color value. + * + * @static + * @method Phaser.Color.RGBArrayToHex + * @param {array} rgb - An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + * @return {number} The color value, in the format 0xRRGGBB. + */ + RGBArrayToHex: function (rgb) { + + return ((rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255); + + }, + + /** + * Converts an RGB color value to HSL (hue, saturation and lightness). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSL + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. + */ + 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); + + // achromatic by default + out.h = 0; + out.s = 0; + out.l = (max + min) / 2; + + if (max !== min) + { + var d = max - min; + + out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min); + + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSL (hue, saturation and lightness) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSLtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} l - The lightness, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSLtoRGB: function (h, s, l, out) { + + if (!out) + { + out = Phaser.Color.createColor(l, l, l); + } + else + { + // achromatic by default + out.r = l; + out.g = l; + out.b = l; + } + + if (s !== 0) + { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3); + out.g = Phaser.Color.hueToColor(p, q, h); + out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3); + } + + // out.r = (out.r * 255 | 0); + // out.g = (out.g * 255 | 0); + // out.b = (out.b * 255 | 0); + + out.r = Math.floor((out.r * 255 | 0)); + out.g = Math.floor((out.g * 255 | 0)); + out.b = Math.floor((out.b * 255 | 0)); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts an RGB color value to HSV (hue, saturation and value). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSV + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and value set in the h, s and v properties. + */ + RGBtoHSV: function (r, g, b, out) { + + if (!out) + { + out = Phaser.Color.createColor(r, g, b, 255); + } + + r /= 255; + g /= 255; + b /= 255; + + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var d = max - min; + + // achromatic by default + out.h = 0; + out.s = max === 0 ? 0 : d / max; + out.v = max; + + if (max !== min) + { + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSVtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} v - The value, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSVtoRGB: function (h, s, v, out) { + + if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); } + + var r, g, b; + var i = Math.floor(h * 6); + var f = h * 6 - i; + var p = v * (1 - s); + var q = v * (1 - f * s); + var t = v * (1 - (1 - f) * s); + + switch (i % 6) + { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } + + out.r = Math.floor(r * 255); + out.g = Math.floor(g * 255); + out.b = Math.floor(b * 255); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.hueToColor + * @static + * @param {number} p + * @param {number} q + * @param {number} t + * @return {number} The color component value. + */ + hueToColor: function (p, q, t) { + + if (t < 0) + { + t += 1; + } + + if (t > 1) + { + t -= 1; + } + + if (t < 1 / 6) + { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) + { + return q; + } + + if (t < 2 / 3) + { + return p + (q - p) * (2 / 3 - t) * 6; + } + + return p; + + }, + + /** + * A utility function to create a lightweight 'color' object with the default components. + * Any components that are not specified will default to zero. + * + * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.createColor + * @static + * @param {number} [r=0] - The red color component, in the range 0 - 255. + * @param {number} [g=0] - The green color component, in the range 0 - 255. + * @param {number} [b=0] - The blue color component, in the range 0 - 255. + * @param {number} [a=1] - The alpha color component, in the range 0 - 1. + * @param {number} [h=0] - The hue, in the range 0 - 1. + * @param {number} [s=0] - The saturation, in the range 0 - 1. + * @param {number} [l=0] - The lightness, in the range 0 - 1. + * @param {number} [v=0] - The value, in the range 0 - 1. + * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. + */ + 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, color32: 0, rgba: '' }; + + return Phaser.Color.updateColor(out); + + }, + + /** + * Takes a color object and updates the rgba, color and color32 properties. + * + * @method Phaser.Color.updateColor + * @static + * @param {object} out - The color object to update. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + updateColor: function (out) { + + out.rgba = 'rgba(' + out.r.toFixed() + ',' + out.g.toFixed() + ',' + out.b.toFixed() + ',' + out.a.toString() + ')'; + out.color = Phaser.Color.getColor(out.r, out.g, out.b); + out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b); + + return out; + + }, + + /** + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor32 + * @static + * @param {number} a - The alpha color component, in the range 0 - 255. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + getColor32: function (a, r, g, b) { + + return a << 24 | r << 16 | g << 8 | b; + + }, + + /** + * Given 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xRRGGBB). + */ + getColor: function (r, g, b) { + + return r << 16 | g << 8 | b; + + }, + + /** + * Converts the given color values into a string. + * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + * + * @method Phaser.Color.RGBtoString + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255. + * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. + * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + */ + RGBtoString: function (r, g, b, a, prefix) { + + if (a === undefined) { a = 255; } + if (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); + } + + }, + + /** + * Converts a hex string into an integer color value. + * + * @method Phaser.Color.hexToRGB + * @static + * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. + * @return {number} The rgb color value in the format 0xAARRGGBB. + */ + hexToRGB: function (hex) { + + var rgb = Phaser.Color.hexToColor(hex); + + if (rgb) + { + return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b); + } + + }, + + /** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @method Phaser.Color.hexToColor + * @static + * @param {string} hex - The color string in a hex format. + * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + hexToColor: function (hex, out) { + + // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") + hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { + return r + r + g + g + b + b; + }); + + var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + + if (result) + { + var r = parseInt(result[1], 16); + var g = parseInt(result[2], 16); + var b = parseInt(result[3], 16); + + if (!out) + { + out = Phaser.Color.createColor(r, g, b); + } + else + { + out.r = r; + out.g = g; + out.b = b; + } + } + + return out; + + }, + + /** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @method Phaser.Color.webToColor + * @static + * @param {string} web - The color string in CSS 'web' format. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + webToColor: function (web, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web); + + if (result) + { + out.r = ~~Number(result[1]); + out.g = ~~Number(result[2]); + out.b = ~~Number(result[3]); + out.a = result[4] !== undefined ? Number(result[4]) : 1; + Phaser.Color.updateColor(out); + } + + return out; + + }, + + /** + * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. + * + * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). + * + * An alpha channel is _not_ supported when specifying a hex string. + * + * @method Phaser.Color.valueToColor + * @static + * @param {string|number} value - The color expressed as a recognized string format or a packed integer. + * @param {object} [out] - The object to use for the output. If not provided a new object will be created. + * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. + */ + valueToColor: function (value, out) { + + // The behavior is not consistent between hexToColor/webToColor on invalid input. + // This unifies both by returning a new object, but returning null may be better. + if (!out) + { + out = Phaser.Color.createColor(); + } + + if (typeof value === 'string') + { + if (value.indexOf('rgb') === 0) + { + return Phaser.Color.webToColor(value, out); + } + else + { + // `hexToColor` does not support alpha; match `createColor`. + out.a = 1; + return Phaser.Color.hexToColor(value, out); + } + } + else if (typeof value === 'number') + { + // `getRGB` does not take optional object to modify; + // alpha is also adjusted to match `createColor`. + var tempColor = Phaser.Color.getRGB(value); + out.r = tempColor.r; + out.g = tempColor.g; + out.b = tempColor.b; + out.a = tempColor.a / 255; + return out; + } + else + { + return out; + } + + }, + + /** + * Return a string containing a hex representation of the given color component. + * + * @method Phaser.Color.componentToHex + * @static + * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. + * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ + componentToHex: function (color) { + + var hex = color.toString(16); + + return (hex.length === 1) ? '0' + hex : hex; + + }, + + /** + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSVColorWheel + * @static + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSV color wheel. + */ + HSVColorWheel: function (s, v) { + + if (s === undefined) { s = 1.0; } + if (v === undefined) { v = 1.0; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v)); + } + + return colors; + + }, + + /** + * Get HSL color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSLColorWheel + * @static + * @param {number} [s=0.5] - The saturation, in the range 0 - 1. + * @param {number} [l=0.5] - The lightness, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSL color wheel. + */ + HSLColorWheel: function (s, l) { + + if (s === undefined) { s = 0.5; } + if (l === undefined) { l = 0.5; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l)); + } + + return colors; + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColor + * @static + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @param {number} [alpha] - The alpha of the returned color. + * @param {number} [colorSpace=0] - The color space to interpolate in. 0 = RGB, 1 = HSV. + * @returns {number} The interpolated color value. + */ + interpolateColor: function (color1, color2, steps, currentStep, alpha, colorSpace) { + + if (alpha === undefined) { alpha = 255; } + if (colorSpace === undefined) { colorSpace = 0; } + + var src1 = Phaser.Color.getRGB(color1); + var src2 = Phaser.Color.getRGB(color2); + + if (colorSpace === 0) + { + 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; + } + + if (colorSpace === 1) + { + var hsv1 = Phaser.Color.RGBtoHSV(src1.r, src1.g, src1.b); + var hsv2 = Phaser.Color.RGBtoHSV(src2.r, src2.g, src2.b); + var dh = hsv2.h - hsv1.h; + var h; + + if (hsv1.h > hsv2.h) + { + var h3 = hsv2.h; + hsv2.h = hsv1.h; + hsv1.h = h3; + dh = -dh; + currentStep = steps - currentStep; + } + + if (dh > 0.5) + { + hsv1.h = hsv1.h + 1; + h = (((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h) % 1; + } + + if (dh <= 0.5) + { + h = ((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h; + } + + var s = (((hsv2.s - hsv1.s) * currentStep) / steps) + hsv1.s; + var v = (((hsv2.v - hsv1.v) * currentStep) / steps) + hsv1.v; + + var rgb = Phaser.Color.HSVtoRGB(h, s, v, rgb); + var r = rgb.r; + var g = rgb.g; + var b = rgb.b; + } + + return Phaser.Color.getColor32(alpha, r, g, b); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColorWithRGB + * @static + * @param {number} color - The first color value. + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * @method Phaser.Color.interpolateRGB + * @static + * @param {number} r1 - The red color value, between 0 and 0xFF (255). + * @param {number} g1 - The green color value, between 0 and 0xFF (255). + * @param {number} b1 - The blue color value, between 0 and 0xFF (255). + * @param {number} r2 - The red color value, between 0 and 0xFF (255). + * @param {number} g2 - The green color value, between 0 and 0xFF (255). + * @param {number} b2 - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + + /** + * Calculates a linear (interpolation) value of two colors over t. + * + * This is a slightly simpler interface to {@link Phaser.Color.interpolateColor}. + * + * The arguments are similar to {@link Phaser.Math.linear}. + * + * @method Phaser.Color.linear + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linear: function (color1, color2, t) { + + return this.interpolateColor(color1, color2, 1, t); + + }, + + /** + * Calculates a linear (interpolation) value of an array of colors over t. + * + * The arguments are similar to {@link Phaser.Math.linearInterpolation}. + * + * This can be used as a {@link Phaser.TweenData#interpolationFunction}. + * + * @method Phaser.Color.linearInterpolation + * @param {number[]} colors - The input array of color values to interpolate between. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linearInterpolation: function (colors, t) { + + var k = Phaser.Math.linear(0, colors.length - 1, t); + var color1 = colors[ Math.floor(k) ]; + var color2 = colors[ Math.ceil(k)] ; + + return this.linear(color1, color2, k % 1); + + }, + + /** + * Returns a random color value between black and white + * Set the min value to start each channel from the given offset. + * Set the max value to restrict the maximum color used per channel. + * + * @method Phaser.Color.getRandomColor + * @static + * @param {number} [min=0] - The lowest value to use for the color. + * @param {number} [max=255] - The highest value to use for the color. + * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). + * @returns {number} 32-bit color value with alpha. + */ + getRandomColor: function (min, max, alpha) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + if (alpha === undefined) { alpha = 255; } + + // Sanity checks + 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); + + }, + + /** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exist in the given color (0xAARRGGBB) + * + * @method Phaser.Color.getRGB + * @static + * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). + * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. + */ + getRGB: function (color) { + + if (color > 16777215) + { + // The color value has an alpha component + return { + alpha: color >>> 24, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: color >>> 24, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + else + { + return { + alpha: 255, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: 255, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + + }, + + /** + * Returns a CSS friendly string value from the given color. + * + * @method Phaser.Color.getWebRGB + * @static + * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. + * @returns {string} A string in the format: 'rgba(r,g,b,a)' + */ + getWebRGB: function (color) { + + if (typeof color === 'object') + { + return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')'; + } + else + { + var rgb = Phaser.Color.getRGB(color); + return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')'; + } + + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. + * + * @method Phaser.Color.getAlpha + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlpha: function (color) { + return color >>> 24; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. + * + * @method Phaser.Color.getAlphaFloat + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlphaFloat: function (color) { + return (color >>> 24) / 255; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. + * + * @method Phaser.Color.getRed + * @static + * @param {number} color In the format 0xAARRGGBB. + * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). + */ + getRed: function (color) { + return color >> 16 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. + * + * @method Phaser.Color.getGreen + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). + */ + getGreen: function (color) { + return color >> 8 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. + * + * @method Phaser.Color.getBlue + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). + */ + getBlue: function (color) { + return color & 0xFF; + }, + + /** + * Blends the source color, ignoring the backdrop. + * + * @method Phaser.Color.blendNormal + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNormal: function (a) { + return a; + }, + + /** + * Selects the lighter of the backdrop and source colors. + * + * @method Phaser.Color.blendLighten + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLighten: function (a, b) { + return (b > a) ? b : a; + }, + + /** + * Selects the darker of the backdrop and source colors. + * + * @method Phaser.Color.blendDarken + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDarken: function (a, b) { + return (b > a) ? a : b; + }, + + /** + * Multiplies the backdrop and source color values. + * The result color is always at least as dark as either of the two constituent + * colors. Multiplying any color with black produces black; + * multiplying with white leaves the original color unchanged. + * + * @method Phaser.Color.blendMultiply + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendMultiply: function (a, b) { + return (a * b) / 255; + }, + + /** + * Takes the average of the source and backdrop colors. + * + * @method Phaser.Color.blendAverage + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAverage: function (a, b) { + return (a + b) / 2; + }, + + /** + * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. + * + * @method Phaser.Color.blendAdd + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAdd: function (a, b) { + return Math.min(255, a + b); + }, + + /** + * Combines the source and backdrop colors and returns their value minus 255. + * + * @method Phaser.Color.blendSubtract + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSubtract: function (a, b) { + return Math.max(0, a + b - 255); + }, + + /** + * Subtracts the darker of the two constituent colors from the lighter. + * + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendDifference + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDifference: function (a, b) { + return Math.abs(a - b); + }, + + /** + * Negation blend mode. + * + * @method Phaser.Color.blendNegation + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNegation: function (a, b) { + return 255 - Math.abs(255 - a - b); + }, + + /** + * Multiplies the complements of the backdrop and source color values, then complements the result. + * The result color is always at least as light as either of the two constituent colors. + * Screening any color with white produces white; screening with black leaves the original color unchanged. + * + * @method Phaser.Color.blendScreen + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendScreen: function (a, b) { + return 255 - (((255 - a) * (255 - b)) >> 8); + }, + + /** + * Produces an effect similar to that of the Difference mode, but lower in contrast. + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendExclusion + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendExclusion: function (a, b) { + return a + b - 2 * a * b / 255; + }, + + /** + * Multiplies or screens the colors, depending on the backdrop color. + * Source colors overlay the backdrop while preserving its highlights and shadows. + * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. + * + * @method Phaser.Color.blendOverlay + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendOverlay: function (a, b) { + return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255); + }, + + /** + * Darkens or lightens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. + * The effect is similar to shining a diffused spotlight on the backdrop. + * + * @method Phaser.Color.blendSoftLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSoftLight: function (a, b) { + return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255); + }, + + /** + * Multiplies or screens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; + * this is useful for adding shadows to a scene. + * + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. + * + * @method Phaser.Color.blendHardLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardLight: function (a, b) { + return Phaser.Color.blendOverlay(b, a); + }, + + /** + * Brightens the backdrop color to reflect the source color. + * Painting with black produces no change. + * + * @method Phaser.Color.blendColorDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorDodge: function (a, b) { + return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b))); + }, + + /** + * Darkens the backdrop color to reflect the source color. + * Painting with white produces no change. + * + * @method Phaser.Color.blendColorBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorBurn: function (a, b) { + return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b)); + }, + + /** + * An alias for blendAdd, it simply sums the values of the two colors. + * + * @method Phaser.Color.blendLinearDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearDodge: function (a, b) { + return Phaser.Color.blendAdd(a, b); + }, + + /** + * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. + * + * @method Phaser.Color.blendLinearBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearBurn: function (a, b) { + return Phaser.Color.blendSubtract(a, b); + }, + + /** + * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). + * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. + * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. + * + * @method Phaser.Color.blendLinearLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearLight: function (a, b) { + return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128))); + }, + + /** + * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). + * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. + * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom + * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. + * + * @method Phaser.Color.blendVividLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendVividLight: function (a, b) { + return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128))); + }, + + /** + * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. + * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. + * + * @method Phaser.Color.blendPinLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPinLight: function (a, b) { + return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128))); + }, + + /** + * Runs blendVividLight on the source and backdrop colors. + * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. + * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. + * This changes all pixels to primary additive colors (red, green, or blue), white, or black. + * + * @method Phaser.Color.blendHardMix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardMix: function (a, b) { + return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255; + }, + + /** + * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. + * + * @method Phaser.Color.blendReflect + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendReflect: function (a, b) { + return b === 255 ? b : Math.min(255, (a * a / (255 - b))); + }, + + /** + * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. + * + * @method Phaser.Color.blendGlow + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendGlow: function (a, b) { + return Phaser.Color.blendReflect(b, a); + }, + + /** + * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. + * + * @method Phaser.Color.blendPhoenix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPhoenix: function (a, b) { + return Math.min(a, b) - Math.max(a, b) + 255; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Manager is responsible for looking after all of the running physics systems. +* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. +* +* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. +* +* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the +* faster (due to being much simpler) Arcade Physics system. +* +* @class Phaser.Physics +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Physics = function (game, config) { + + config = config || {}; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} config - The physics configuration object as passed to the game on creation. + */ + this.config = config; + + /** + * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. + */ + this.arcade = null; + + /** + * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. + */ + this.p2 = null; + + /** + * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. + */ + this.ninja = null; + + /** + * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. + */ + this.box2d = null; + + /** + * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). + */ + this.chipmunk = null; + + /** + * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). + */ + this.matter = null; + + this.parseConfig(); + +}; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.ARCADE = 0; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.P2JS = 1; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.NINJA = 2; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.BOX2D = 3; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.CHIPMUNK = 4; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.MATTERJS = 5; + +Phaser.Physics.prototype = { + + /** + * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. + * + * @method Phaser.Physics#parseConfig + */ + parseConfig: function () { + + if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade')) + { + // If Arcade isn't specified, we create it automatically if we can + this.arcade = new Phaser.Physics.Arcade(this.game); + } + + 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); + } + + if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D')) + { + this.box2d = new Phaser.Physics.BOX2D(this.game, this.config); + } + + if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter')) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + + }, + + /** + * This will create an instance of the requested physics simulation. + * Phaser.Physics.Arcade is running by default, but all others need activating directly. + * + * You can start the following physics systems: + * + * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. + * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) + * + * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. + * They are not bundled into the core Phaser library. + * + * If the physics world has already been created (i.e. in another state in your game) then + * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors + * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. + * + * @method Phaser.Physics#startSystem + * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. + */ + startSystem: function (system) { + + if (system === Phaser.Physics.ARCADE) + { + this.arcade = new Phaser.Physics.Arcade(this.game); + } + else if (system === Phaser.Physics.P2JS) + { + if (this.p2 === null) + { + this.p2 = new Phaser.Physics.P2(this.game, this.config); + } + else + { + this.p2.reset(); + } + } + else if (system === Phaser.Physics.NINJA) + { + this.ninja = new Phaser.Physics.Ninja(this.game); + } + else if (system === Phaser.Physics.BOX2D) + { + if (this.box2d === null) + { + this.box2d = new Phaser.Physics.Box2D(this.game, this.config); + } + else + { + this.box2d.reset(); + } + } + else if (system === Phaser.Physics.MATTERJS) + { + if (this.matter === null) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + else + { + this.matter.reset(); + } + } + + }, + + /** + * This will create a default physics body on the given game object or array of objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * It can be for any of the physics systems that have been started: + * + * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. + * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. + * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 + * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) + * Phaser.Physics.CHIPMUNK is still in development. + * + * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the + * individual physics systems `enable` methods instead of using this generic one. + * + * @method Phaser.Physics#enable + * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. + * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. + * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. + */ + enable: function (object, system, debug) { + + if (system === undefined) { system = Phaser.Physics.ARCADE; } + if (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); + } + else if (system === Phaser.Physics.BOX2D && this.box2d) + { + this.box2d.enable(object); + } + else if (system === Phaser.Physics.MATTERJS && this.matter) + { + this.matter.enable(object); + } + else + { + console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.'); + } + + }, + + /** + * preUpdate checks. + * + * @method Phaser.Physics#preUpdate + * @protected + */ + preUpdate: function () { + + // ArcadePhysics / Ninja don't have a core to preUpdate + + if (this.p2) + { + this.p2.preUpdate(); + } + + if (this.box2d) + { + this.box2d.preUpdate(); + } + + if (this.matter) + { + this.matter.preUpdate(); + } + + }, + + /** + * Updates all running physics systems. + * + * @method Phaser.Physics#update + * @protected + */ + update: function () { + + // ArcadePhysics / Ninja don't have a core to update + + if (this.p2) + { + this.p2.update(); + } + + if (this.box2d) + { + this.box2d.update(); + } + + if (this.matter) + { + this.matter.update(); + } + + }, + + /** + * Updates the physics bounds to match the world dimensions. + * + * @method Phaser.Physics#setBoundsToWorld + * @protected + */ + setBoundsToWorld: function () { + + if (this.arcade) + { + this.arcade.setBoundsToWorld(); + } + + if (this.ninja) + { + this.ninja.setBoundsToWorld(); + } + + if (this.p2) + { + this.p2.setBoundsToWorld(); + } + + if (this.box2d) + { + this.box2d.setBoundsToWorld(); + } + + if (this.matter) + { + this.matter.setBoundsToWorld(); + } + + }, + + /** + * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. + * + * @method Phaser.Physics#clear + * @protected + */ + clear: function () { + + if (this.p2) + { + this.p2.clear(); + } + + if (this.box2d) + { + this.box2d.clear(); + } + + if (this.matter) + { + this.matter.clear(); + } + + }, + + /** + * Resets the active physics system. Called automatically on a Phaser.State swap. + * + * @method Phaser.Physics#reset + * @protected + */ + reset: function () { + + if (this.p2) + { + this.p2.reset(); + } + + if (this.box2d) + { + this.box2d.reset(); + } + + if (this.matter) + { + this.matter.reset(); + } + + }, + + /** + * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. + * + * @method Phaser.Physics#destroy + */ + destroy: function () { + + if (this.p2) + { + this.p2.destroy(); + } + + if (this.box2d) + { + this.box2d.destroy(); + } + + if (this.matter) + { + this.matter.destroy(); + } + + this.arcade = null; + this.ninja = null; + this.p2 = null; + this.box2d = null; + this.matter = null; + + } + +}; + +Phaser.Physics.prototype.constructor = Phaser.Physics; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. +* +* @class Phaser.Physics.Arcade +* @constructor +* @param {Phaser.Game} game - reference to the current game instance. +*/ +Phaser.Physics.Arcade = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height); + + /** + * Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`. + * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. + * @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right). + */ + this.checkCollision = { up: true, down: true, left: true, right: true }; + + /** + * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. + */ + this.maxLevels = 4; + + /** + * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. + * @default + */ + this.OVERLAP_BIAS = 4; + + /** + * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. + */ + this.forceX = false; + + /** + * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT. + * @default + */ + this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT; + + /** + * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. + */ + this.skipQuadTree = true; + + /** + * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. + */ + this.isPaused = false; + + /** + * @property {Phaser.QuadTree} quadTree - The world QuadTree. + */ + 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); + + /** + * @property {number} _total - Internal cache var. + * @private + */ + this._total = 0; + + // By default we want the bounds the same size as the world bounds + this.setBoundsToWorld(); + +}; + +Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade; + +/** +* A constant used for the sortDirection value. +* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.SORT_NONE = 0; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.LEFT_RIGHT = 1; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.RIGHT_LEFT = 2; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.TOP_BOTTOM = 3; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.BOTTOM_TOP = 4; + +Phaser.Physics.Arcade.prototype = { + + /** + * Updates the size of this physics world. + * + * @method Phaser.Physics.Arcade#setBounds + * @param {number} x - Top left most corner of the world. + * @param {number} y - Top left most corner of the world. + * @param {number} width - New width of the world. Can never be smaller than the Game.width. + * @param {number} height - New height of the world. Can never be smaller than the Game.height. + */ + setBounds: function (x, y, width, height) { + + this.bounds.setTo(x, y, width, height); + + }, + + /** + * Updates the size of this physics world to match the size of the game world. + * + * @method Phaser.Physics.Arcade#setBoundsToWorld + */ + setBoundsToWorld: function () { + + this.bounds.copyFrom(this.game.world.bounds); + + }, + + /** + * This will create an Arcade Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * + * @method Phaser.Physics.Arcade#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, children) { + + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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) + { + // If it's a Group then we do it on the children regardless + this.enable(object.children, children); + } + else + { + this.enableBody(object); + + if (children && object.hasOwnProperty('children') && object.children.length > 0) + { + this.enable(object.children, true); + } + } + } + + }, + + /** + * Creates an Arcade Physics body on the given game object. + * + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. + * + * @method Phaser.Physics.Arcade#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + */ + enableBody: function (object) { + + if (object.hasOwnProperty('body') && object.body === null) + { + object.body = new Phaser.Physics.Arcade.Body(object); + + if (object.parent && object.parent instanceof Phaser.Group) + { + object.parent.addToHash(object); + } + } + + }, + + /** + * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. + * + * @method Phaser.Physics.Arcade#updateMotion + * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. + */ + updateMotion: function (body) { + + if (body.allowRotation) + { + var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity; + body.angularVelocity += 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); + + }, + + /** + * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * Based on a function in Flixel by @ADAMATOMIC + * + * @method Phaser.Physics.Arcade#computeVelocity + * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical. + * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. + * @param {number} velocity - Any component of velocity (e.g. 20). + * @param {number} acceleration - Rate at which the velocity is changing. + * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. + * @param {number} [max=10000] - An absolute value cap for the velocity. + * @return {number} The altered Velocity value. + */ + computeVelocity: function (axis, body, velocity, acceleration, drag, max) { + + if (max === undefined) { max = 10000; } + + 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 && body.allowDrag) + { + drag *= this.game.time.physicsElapsed; + + if (velocity - drag > 0) + { + velocity -= drag; + } + else if (velocity + drag < 0) + { + velocity += drag; + } + else + { + velocity = 0; + } + } + + if (velocity > max) + { + velocity = max; + } + else if (velocity < -max) + { + velocity = -max; + } + + return velocity; + + }, + + /** + * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. + * + * Unlike {@link #collide} the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. + * Both the first and second parameter can be arrays of objects, of differing types. + * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups within Groups). + * + * ##### Tilemaps + * + * Any overlapping tiles, including blank/null tiles, will give a positive result. Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) have no special status, and callbacks added via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} are not invoked. So calling this method without any callbacks isn't very useful. + * + * If you're interested only in whether an object overlaps a certain tile or class of tiles, filter the tiles with `processCallback` and then use the result returned by this method. Blank/null tiles can be excluded by their {@link Phaser.Tile#index index} (-1). + * + * If you want to take action on certain overlaps, examine the tiles in `collideCallback` and then handle as you like. + * + * @method Phaser.Physics.Arcade#overlap + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if an overlap occurred otherwise false. + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) { + + overlapCallback = overlapCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || overlapCallback; + + this._total = 0; + + this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + + return (this._total > 0); + + }, + + /** + * Checks for collision between two game objects and separates them if colliding ({@link https://gist.github.com/samme/cbb81dd19f564dcfe2232761e575063d details}). If you don't require separation then use {@link #overlap} instead. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. + * Both the `object1` and `object2` can be arrays of objects, of differing types. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If one Group **only** is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If either object is `null` the collision test will fail. + * + * Bodies with `enable = false` and Sprites with `exists = false` are skipped (ignored). + * + * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. + * + * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). + * + * ##### Examples + * + * ```javascript + * collide(group); + * collide(group, undefined); // equivalent + * + * collide(sprite1, sprite2); + * + * collide(sprite, group); + * + * collide(group1, group2); + * + * collide([sprite1, sprite2], [sprite3, sprite4]); // 1 vs. 3, 1 vs. 4, 2 vs. 3, 2 vs. 4 + * ``` + * + * ##### Tilemaps + * + * Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) are "solid". If a Sprite collides with one of these tiles, the two are separated by moving the Sprite outside the tile's edges. Enable {@link Phaser.TilemapLayer#debug} to see the colliding edges of the Tilemap. + * + * Tiles with a callback attached via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} invoke the callback if a Sprite collides with them. If a tile has a callback attached via both methods, only the location callback is invoked. The colliding Sprite is separated from the tile only if the callback returns `true`. + * + * @method Phaser.Physics.Arcade#collide + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. + * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if a collision occurred otherwise false. + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) { + + collideCallback = collideCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || collideCallback; + + this._total = 0; + + this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + + return (this._total > 0); + + }, + + /** + * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortLeftRight + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortLeftRight: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.x - b.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortRightLeft + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortRightLeft: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.x - a.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortTopBottom + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortTopBottom: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.y - b.body.y; + + }, + + /** + * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortBottomTop + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortBottomTop: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.y - a.body.y; + + }, + + /** + * This method will sort a Groups hash array. + * + * If the Group has `physicsSortDirection` set it will use the sort direction defined. + * + * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection. + * + * By changing Group.physicsSortDirection you can customise each Group to sort in a different order. + * + * @method Phaser.Physics.Arcade#sort + * @param {Phaser.Group} group - The Group to sort. + * @param {integer} [sortDirection] - The sort direction used to sort this Group. + */ + sort: function (group, sortDirection) { + + if (group.physicsSortDirection !== null) + { + sortDirection = group.physicsSortDirection; + } + else + { + if (sortDirection === undefined) { sortDirection = this.sortDirection; } + } + + if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + // Game world is say 2000x600 and you start at 0 + group.hash.sort(this.sortLeftRight); + } + else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + // Game world is say 2000x600 and you start at 2000 + group.hash.sort(this.sortRightLeft); + } + else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + // Game world is say 800x2000 and you start at 0 + group.hash.sort(this.sortTopBottom); + } + else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + // Game world is say 800x2000 and you start at 2000 + group.hash.sort(this.sortBottomTop); + } + + }, + + /** + * Internal collision handler. Extracts objects for {@link #collideHandler}. + * + * @method Phaser.Physics.Arcade#collideObjects + * @private + */ + collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object2.length; i++) + { + if (!object2[i]) { continue; } + + this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && !Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + for (var j = 0; j < object2.length; j++) + { + if (!object2[j]) { continue; } + + this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + + }, + + /** + * Internal collision handler. Matches arguments to other handlers. + * + * @method Phaser.Physics.Arcade#collideHandler + * @private + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + // Only collide valid objects + if (object2 === undefined && object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly); + return; + } + + // If neither of the objects are set or exist then bail out + if (!object1 || !object2 || !object1.exists || !object2.exists) + { + return; + } + + // Groups? Sort them + if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE) + { + if (object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + } + + if (object2.physicsType === Phaser.GROUP) + { + this.sort(object2); + } + } + + // SPRITES + if (object1.physicsType === Phaser.SPRITE) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // GROUPS + else if (object1.physicsType === Phaser.GROUP) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // TILEMAP LAYERS + else if (object1.physicsType === Phaser.TILEMAPLAYER) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsSprite + * @private + * @param {Phaser.Sprite} sprite1 - The first sprite to check. + * @param {Phaser.Sprite} sprite2 - The second sprite to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + 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; + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsGroup + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0 || !sprite.body) + { + return; + } + + if (this.skipQuadTree || sprite.body.skipQuadTree) + { + var bounds = {}; + + for (var i = 0; i < group.hash.length; i++) + { + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds object + bounds = object1.body.getBounds(bounds); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (sprite.body.right < bounds.x) + { + break; + } + else if (bounds.right < sprite.body.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (sprite.body.x > bounds.right) + { + break; + } + else if (bounds.x > sprite.body.right) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (sprite.body.bottom < bounds.y) + { + break; + } + else if (bounds.bottom < sprite.body.y) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (sprite.body.y > bounds.bottom) + { + break; + } + else if (bounds.y > sprite.body.bottom) + { + continue; + } + } + + this.collideSpriteVsSprite(sprite, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else + { + // What is the sprite colliding with in the quadtree? + 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 items = this.quadTree.retrieve(sprite); + + for (var i = 0; i < items.length; i++) + { + // We have our potential suspects, are they in this group? + if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, items[i].sprite); + } + + this._total++; + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsSelf + * @private + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.hash.length; i++) + { + var bounds1 = {}; + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds1 object + bounds1 = object1.body.getBounds(bounds1); + + for (var j = i + 1; j < group.hash.length; j++) + { + var bounds2 = {}; + var object2 = group.hash[j]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object2 || !object2.exists || !object2.body) + { + continue; + } + + // Inject the Body bounds data into the bounds2 object + bounds2 = object2.body.getBounds(bounds2); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (bounds1.right < bounds2.x) + { + break; + } + else if (bounds2.right < bounds1.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (bounds1.x > bounds2.right) + { + continue; + } + else if (bounds2.x > bounds1.right) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (bounds1.bottom < bounds2.y) + { + continue; + } + else if (bounds2.bottom < bounds1.y) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (bounds1.y > bounds2.bottom) + { + continue; + } + else if (bounds2.y > object1.body.bottom) + { + break; + } + } + + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsGroup + * @private + * @param {Phaser.Group} group1 - The first Group to check. + * @param {Phaser.Group} group2 - The second Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group1.length === 0 || group2.length === 0) + { + return; + } + + for (var i = 0; i < group1.children.length; i++) + { + if (group1.children[i].exists) + { + if (group1.children[i].physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else + { + this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + + }, + + /** + * The core separation function to separate two physics bodies. + * + * @private + * @method Phaser.Physics.Arcade#separate + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true. + * @param {object} [callbackContext] - The context in which to run the process callback. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} Returns true if the bodies collided, otherwise false. + */ + separate: function (body1, body2, processCallback, callbackContext, overlapOnly) { + + if ( + !body1.enable || + !body2.enable || + body1.checkCollision.none || + body2.checkCollision.none || + !this.intersects(body1, body2)) + { + return false; + } + + // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. + if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false) + { + return false; + } + + // Circle vs. Circle quick bail out + if (body1.isCircle && body2.isCircle) + { + return this.separateCircle(body1, body2, overlapOnly); + } + + // We define the behavior of bodies in a collision circle and rectangle + // If a collision occurs in the corner points of the rectangle, the body behave like circles + + // Either body1 or body2 is a circle + if (body1.isCircle !== body2.isCircle) + { + var bodyRect = (body1.isCircle) ? body2 : body1; + var bodyCircle = (body1.isCircle) ? body1 : body2; + + var rect = { + x: bodyRect.x, + y: bodyRect.y, + right: bodyRect.right, + bottom: bodyRect.bottom + }; + + var circle = bodyCircle.center; + + if (circle.y < rect.y || circle.y > rect.bottom) + { + if (circle.x < rect.x || circle.x > rect.right) + { + return this.separateCircle(body1, body2, overlapOnly); + } + } + } + + var resultX = false; + var resultY = false; + + // Do we separate on x or y first? + if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) + { + resultX = this.separateX(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultY = this.separateY(body1, body2, overlapOnly); + } + } + else + { + resultY = this.separateY(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultX = this.separateX(body1, body2, overlapOnly); + } + } + + var result = (resultX || resultY); + + if (result) + { + if (overlapOnly) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + else + { + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + } + } + + return result; + + }, + + /** + * Check for intersection against two bodies. + * + * @method Phaser.Physics.Arcade#intersects + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check. + * @return {boolean} True if they intersect, otherwise false. + */ + intersects: function (body1, body2) { + + if (body1 === body2) + { + return false; + } + + if (body1.isCircle) + { + if (body2.isCircle) + { + // Circle vs. Circle + return Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); + } + else + { + // Circle vs. Rect + return this.circleBodyIntersects(body1, body2); + } + } + else + { + if (body2.isCircle) + { + // Rect vs. Circle + return this.circleBodyIntersects(body2, body1); + } + else + { + // Rect vs. Rect + if (body1.right <= body2.position.x) + { + return false; + } + + if (body1.bottom <= body2.position.y) + { + return false; + } + + if (body1.position.x >= body2.right) + { + return false; + } + + if (body1.position.y >= body2.bottom) + { + return false; + } + + return true; + } + } + + }, + + /** + * Checks to see if a circular Body intersects with a Rectangular Body. + * + * @method Phaser.Physics.Arcade#circleBodyIntersects + * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set. + * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape) + * @return {boolean} Returns true if the bodies intersect, otherwise false. + */ + circleBodyIntersects: function (circle, body) { + + var x = Phaser.Math.clamp(circle.center.x, body.left, body.right); + var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom); + + var dx = (circle.center.x - x) * (circle.center.x - x); + var dy = (circle.center.y - y) * (circle.center.y - y); + + return (dx + dy) <= (circle.halfWidth * circle.halfWidth); + + }, + + /** + * The core separation function to separate two circular physics bodies. + * + * @method Phaser.Physics.Arcade#separateCircle + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateCircle: function (body1, body2, overlapOnly) { + + // Set the bounding box overlap values + this.getOverlapX(body1, body2); + this.getOverlapY(body1, body2); + + var dx = body2.center.x - body1.center.x; + var dy = body2.center.y - body1.center.y; + + var angleCollision = Math.atan2(dy, dx); + + var overlap = 0; + + if (body1.isCircle !== body2.isCircle) + { + var rect = { + x: (body2.isCircle) ? body1.position.x : body2.position.x, + y: (body2.isCircle) ? body1.position.y : body2.position.y, + right: (body2.isCircle) ? body1.right : body2.right, + bottom: (body2.isCircle) ? body1.bottom : body2.bottom + }; + + var circle = { + x: (body1.isCircle) ? body1.center.x : body2.center.x, + y: (body1.isCircle) ? body1.center.y : body2.center.y, + radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth + }; + + if (circle.y < rect.y) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.y) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.y) - circle.radius; + } + } + else if (circle.y > rect.bottom) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; + } + } + + overlap *= -1; + } + else + { + overlap = (body1.halfWidth + body2.halfWidth) - Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y); + } + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + if (overlap !== 0) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + + // return true if there was some overlap, otherwise false + return (overlap !== 0); + } + + // Transform the velocity vector to the coordinate system oriented along the direction of impact. + // This is done to eliminate the vertical component of the velocity + var v1 = { + x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision), + y: body1.velocity.x * Math.sin(angleCollision) - body1.velocity.y * Math.cos(angleCollision) + }; + + var v2 = { + x: body2.velocity.x * Math.cos(angleCollision) + body2.velocity.y * Math.sin(angleCollision), + y: body2.velocity.x * Math.sin(angleCollision) - body2.velocity.y * Math.cos(angleCollision) + }; + + // We expect the new velocity after impact + var tempVel1 = ((body1.mass - body2.mass) * v1.x + 2 * body2.mass * v2.x) / (body1.mass + body2.mass); + var tempVel2 = (2 * body1.mass * v1.x + (body2.mass - body1.mass) * v2.x) / (body1.mass + body2.mass); + + // We convert the vector to the original coordinate system and multiplied by factor of rebound + if (!body1.immovable) + { + body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x; + body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y; + } + + if (!body2.immovable) + { + body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x; + body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y; + } + + // When the collision angle is almost perpendicular to the total initial velocity vector + // (collision on a tangent) vector direction can be determined incorrectly. + // This code fixes the problem + + if (Math.abs(angleCollision) < Math.PI / 2) + { + if ((body1.velocity.x > 0) && !body1.immovable && (body2.velocity.x > body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x < 0) && !body2.immovable && (body1.velocity.x < body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y > 0) && !body1.immovable && (body2.velocity.y > body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y < 0) && !body2.immovable && (body1.velocity.y < body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + else if (Math.abs(angleCollision) > Math.PI / 2) + { + if ((body1.velocity.x < 0) && !body1.immovable && (body2.velocity.x < body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y < 0) && !body1.immovable && (body2.velocity.y < body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + + if (!body1.immovable) + { + body1.x += (body1.velocity.x * this.game.time.physicsElapsed) - overlap * Math.cos(angleCollision); + body1.y += (body1.velocity.y * this.game.time.physicsElapsed) - overlap * Math.sin(angleCollision); + } + + if (!body2.immovable) + { + body2.x += (body2.velocity.x * this.game.time.physicsElapsed) + overlap * Math.cos(angleCollision); + body2.y += (body2.velocity.y * this.game.time.physicsElapsed) + overlap * Math.sin(angleCollision); + } + + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + + return true; + + }, + + /** + * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: + * `touching.left`, `touching.right` and `overlapX`. + * + * @method Phaser.Physics.Arcade#getOverlapX + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of horizontal overlap between the two bodies. + */ + getOverlapX: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS; + + if (body1.deltaX() === 0 && body2.deltaX() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaX() > body2.deltaX()) + { + // Body1 is moving right and / or Body2 is moving left + overlap = body1.right - body2.x; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.right = true; + body2.touching.none = false; + body2.touching.left = true; + } + } + else if (body1.deltaX() < body2.deltaX()) + { + // Body1 is moving left and/or Body2 is moving right + overlap = body1.x - body2.width - body2.x; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.left = true; + body2.touching.none = false; + body2.touching.right = true; + } + } + + // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapX = overlap; + body2.overlapX = overlap; + + return overlap; + + }, + + /** + * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: + * `touching.up`, `touching.down` and `overlapY`. + * + * @method Phaser.Physics.Arcade#getOverlapY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of vertical overlap between the two bodies. + */ + getOverlapY: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS; + + if (body1.deltaY() === 0 && body2.deltaY() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaY() > body2.deltaY()) + { + // Body1 is moving down and/or Body2 is moving up + overlap = body1.bottom - body2.y; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.down = true; + body2.touching.none = false; + body2.touching.up = true; + } + } + else if (body1.deltaY() < body2.deltaY()) + { + // Body1 is moving up and/or Body2 is moving down + overlap = body1.y - body2.bottom; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.up = true; + body2.touching.none = false; + body2.touching.down = true; + } + } + + // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapY = overlap; + body2.overlapY = overlap; + + return overlap; + + }, + + /** + * The core separation function to separate two physics bodies on the x axis. + * + * @method Phaser.Physics.Arcade#separateX + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateX: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapX(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.x; + var v2 = body2.velocity.x; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.x -= overlap; + body2.x += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.x = avg + nv1 * body1.bounce.x; + body2.velocity.x = avg + nv2 * body2.bounce.x; + } + else if (!body1.immovable) + { + body1.x -= overlap; + body1.velocity.x = v2 - v1 * body1.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body2.moves) + { + body1.y += (body2.y - body2.prev.y) * body2.friction.y; + } + } + else + { + body2.x += overlap; + body2.velocity.x = v1 - v2 * body2.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body1.moves) + { + body2.y += (body1.y - body1.prev.y) * body1.friction.y; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * The core separation function to separate two physics bodies on the y axis. + * + * @private + * @method Phaser.Physics.Arcade#separateY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateY: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapY(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.y; + var v2 = body2.velocity.y; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.y -= overlap; + body2.y += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.y = avg + nv1 * body1.bounce.y; + body2.velocity.y = avg + nv2 * body2.bounce.y; + } + else if (!body1.immovable) + { + body1.y -= overlap; + body1.velocity.y = v2 - v1 * body1.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body2.moves) + { + body1.x += (body2.x - body2.prev.x) * body2.friction.x; + } + } + else + { + body2.y += overlap; + body2.velocity.y = v1 - v2 * body2.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body1.moves) + { + body2.x += (body1.x - body1.prev.x) * body1.friction.x; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. + * + * @method Phaser.Physics.Arcade#getObjectsUnderPointer + * @param {Phaser.Pointer} pointer - The Pointer to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. + * @param {object} [callbackContext] - The context in which to run the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates. + */ + getObjectsUnderPointer: function (pointer, group, callback, callbackContext) { + + if (group.length === 0 || !pointer.exists) + { + return; + } + + return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer); + + }, + + /** + * Given a Group and a location this will check to see which Group children overlap with the coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. + * + * @method Phaser.Physics.Arcade#getObjectsAtLocation + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. + * @param {object} [callbackContext] - The context in which to run the callback. + * @param {object} [callbackArg] - An argument to pass to the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates. + */ + getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) { + + 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(x, y, 1, 1); + var output = []; + + var items = this.quadTree.retrieve(rect); + + for (var i = 0; i < items.length; i++) + { + if (items[i].hitTest(x, y)) + { + if (callback) + { + callback.call(callbackContext, callbackArg, items[i].sprite); + } + + output.push(items[i].sprite); + } + } + + return output; + + }, + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToObject: function (displayObject, destination, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Phaser.Point.angle(destination, displayObject); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#moveToPointer + * @param {any} displayObject - The display object to move. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToPointer: function (displayObject, speed, pointer, maxTime) { + + if (speed === undefined) { speed = 60; } + pointer = pointer || this.game.input.activePointer; + if (maxTime === undefined) { maxTime = 0; } + + var angle = this.angleToPointer(displayObject, pointer); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToXY: function (displayObject, x, y, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Math.atan2(y - displayObject.y, x - displayObject.x); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromAngle + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromAngle: function (angle, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(angle, speed, true); + + }, + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. + * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. + * + * @method Phaser.Physics.Arcade#accelerationFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. + * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. + */ + accelerationFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleBetween(displayObject, destination); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToPointer + * @param {any} displayObject - The display object to move. + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToPointer(displayObject, pointer); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToXY(displayObject, x, y); + + displayObject.body.acceleration.setTo(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Find the distance between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * If you have nested objects and need to calculate the distance between their centers in World coordinates, + * set their anchors to (0.5, 0.5) and use the `world` argument. + * + * If objects aren't nested or they share a parent's offset, you can calculate the distance between their + * centers with the `useCenter` argument, regardless of their anchor values. + * + * @method Phaser.Physics.Arcade#distanceBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {number} The distance between the source and target objects. + */ + distanceBetween: function (source, target, world, useCenter) { + + if (world === undefined) { world = false; } + + var dx; + var dy; + + if (useCenter) + { + dx = source.centerX - target.centerX; + dy = source.centerY - target.centerY; + } + else if (world) + { + dx = source.world.x - target.world.x; + dy = source.world.y - target.world.y; + } + else + { + dx = source.x - target.x; + dy = source.y - target.y; + } + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and the given x/y coordinates. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the x/y coordinates. + */ + distanceToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - x : displayObject.x - x; + var dy = (world) ? displayObject.world.y - y : displayObject.y - y; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the Pointer. + */ + distanceToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.x - pointer.worldX; + var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + + /** + * From a set of points or display objects, find the one closest to a source point or object. + * + * @method Phaser.Physics.Arcade#closest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The first target closest to the origin. + */ + closest: function (source, targets, world, useCenter) { + var min = Infinity; + var closest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance < min) + { + closest = target; + min = distance; + } + } + + return closest; + }, + + /** + * From a set of points or display objects, find the one farthest from a source point or object. + * + * @method Phaser.Physics.Arcade#farthest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The target closest to the origin. + */ + farthest: function (source, targets, world, useCenter) { + var max = -1; + var farthest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance > max) + { + farthest = target; + max = distance; + } + } + + return farthest; + }, + + /** + * Find the angle in radians between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetween: function (source, target, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Phaser.Point.angle(target.world, source.world); + } + else + { + return Phaser.Point.angle(target, source); + } + + }, + + /** + * Find the angle in radians between centers of two display objects (like Sprites). + * + * @method Phaser.Physics.Arcade#angleBetweenCenters + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetweenCenters: function (source, target) { + + var dx = target.centerX - source.centerX; + var dy = target.centerY - source.centerY; + + return Math.atan2(dy, dx); + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to get the angle to. + * @param {number} y - The y coordinate to get the angle to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(y - displayObject.world.y, x - displayObject.world.x); + } + else + { + return Math.atan2(y - displayObject.y, x - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x); + } + else + { + return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, + * taking their x/y and center into account relative to the world. + * + * @method Phaser.Physics.Arcade#worldAngleToPointer + * @param {any} displayObject - The DisplayObjerct to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY + */ + worldAngleToPointer: function (displayObject, pointer) { + + return this.angleToPointer(displayObject, pointer, true); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than +* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. +* +* @class Phaser.Physics.Arcade.Body +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. +*/ +Phaser.Physics.Arcade.Body = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = sprite.game; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.ARCADE; + + /** + * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. + * @default + */ + this.enable = true; + + /** + * If `true` this Body is using circular collision detection. If `false` it is using rectangular. + * Use `Body.setCircle` to control the collision shape this Body uses. + * @property {boolean} isCircle + * @default + * @readOnly + */ + this.isCircle = false; + + /** + * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled, relative to the Sprite's _texture_. + * If you wish to change the radius then call {@link #setCircle} again with the new value. + * If you wish to stop the Body using a circle then call {@link #setCircle} with a radius of zero (or undefined). + * The actual radius of the Body (at any Sprite scale) is equal to {@link #halfWidth} and the diameter is equal to {@link #width}. + * @property {number} radius + * @default + * @readOnly + */ + this.radius = 0; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite's texture. + */ + this.offset = new Phaser.Point(); + + /** + * @property {Phaser.Point} position - The position of the physics body, equivalent to ({@link #left}, {@link #top}). + * @readonly + */ + this.position = new Phaser.Point(sprite.x, sprite.y); + + /** + * @property {Phaser.Point} prev - The previous position of the physics body. + * @readonly + */ + this.prev = new Phaser.Point(this.position.x, this.position.y); + + /** + * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) + * @default + */ + this.allowRotation = true; + + /** + * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body + * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. + * @property {number} rotation + */ + this.rotation = sprite.angle; + + /** + * @property {number} preRotation - The previous rotation of the physics body, in degrees. + * @readonly + */ + this.preRotation = sprite.angle; + + /** + * @property {number} width - The calculated width of the physics body. + * @readonly + */ + this.width = sprite.width; + + /** + * @property {number} height - The calculated height of the physics body. + * @readonly + */ + this.height = sprite.height; + + /** + * @property {number} sourceWidth - The un-scaled original size. + * @readonly + */ + this.sourceWidth = sprite.width; + + /** + * @property {number} sourceHeight - The un-scaled original size. + * @readonly + */ + this.sourceHeight = sprite.height; + + if (sprite.texture) + { + this.sourceWidth = sprite.texture.frame.width; + this.sourceHeight = sprite.texture.frame.height; + } + + /** + * @property {number} halfWidth - The calculated width / 2 of the physics body. + * @readonly + */ + this.halfWidth = Math.abs(sprite.width / 2); + + /** + * @property {number} halfHeight - The calculated height / 2 of the physics body. + * @readonly + */ + this.halfHeight = Math.abs(sprite.height / 2); + + /** + * @property {Phaser.Point} center - The center coordinate of the Physics Body. + * @readonly + */ + this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight); + + /** + * @property {Phaser.Point} velocity - The velocity, or rate of change the Body's position. Measured in pixels per second. + */ + this.velocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} newVelocity - The distanced traveled during the last update, equal to `velocity * physicsElapsed`. Calculated during the Body.preUpdate and applied to its position. + * @readonly + */ + this.newVelocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. + */ + this.deltaMax = new Phaser.Point(); + + /** + * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + */ + this.acceleration = new Phaser.Point(); + + /** + * @property {boolean} allowDrag - Allow this Body to be influenced by {@link #drag}? + * @default + */ + this.allowDrag = true; + + /** + * @property {Phaser.Point} drag - The drag applied to the motion of the Body (when {@link #allowDrag} is enabled). Measured in pixels per second squared. + */ + this.drag = new Phaser.Point(); + + /** + * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local. + * @default + */ + this.allowGravity = true; + + /** + * @property {Phaser.Point} gravity - This Body's local gravity, **added** to any world gravity, unless Body.allowGravity is set to false. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. + */ + this.bounce = new Phaser.Point(); + + /** + * The elasticity of the Body when colliding with the World bounds. + * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property + * to a Phaser.Point object in order to enable a World bounds specific bounce value. + * @property {Phaser.Point} worldBounce + */ + this.worldBounce = null; + + /** + * A Signal that is dispatched when this Body collides with the world bounds. + * Due to the potentially high volume of signals this could create it is disabled by default. + * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` + * and it will be called when a collision happens, passing five arguments: + * `onWorldBounds(sprite, up, down, left, right)` + * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans + * indicating on which side of the world the Body collided. + * @property {Phaser.Signal} onWorldBounds + */ + this.onWorldBounds = null; + + /** + * A Signal that is dispatched when this Body collides with another Body. + * + * You still need to call `game.physics.arcade.collide` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `collide` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onCollide + */ + this.onCollide = null; + + /** + * A Signal that is dispatched when this Body overlaps with another Body. + * + * You still need to call `game.physics.arcade.overlap` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `overlap` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onOverlap + */ + this.onOverlap = null; + + /** + * @property {Phaser.Point} maxVelocity - The maximum velocity (in pixels per second squared) that the Body can reach. + * @default + */ + this.maxVelocity = new Phaser.Point(10000, 10000); + + /** + * @property {Phaser.Point} friction - If this Body is {@link #immovable} and moving, and another Body is 'riding' this one, this is the amount of motion the riding Body receives on each axis. + */ + this.friction = new Phaser.Point(1, 0); + + /** + * @property {number} angularVelocity - The angular velocity is the rate of change of the Body's rotation. It is measured in degrees per second. + * @default + */ + this.angularVelocity = 0; + + /** + * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. + * @default + */ + this.angularAcceleration = 0; + + /** + * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach. + * @default + */ + this.maxAngular = 1000; + + /** + * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. + * @default + */ + this.mass = 1; + + /** + * @property {number} angle - The angle of the Body's **velocity** in radians. + * @readonly + */ + this.angle = 0; + + /** + * @property {number} speed - The speed of the Body in pixels per second, equal to the magnitude of the velocity. + * @readonly + */ + this.speed = 0; + + /** + * @property {number} facing - A const reference to the direction the Body is traveling or facing: Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.UP, or Phaser.DOWN. If the Body is moving on both axes, UP and DOWN take precedence. + * @default + */ + this.facing = Phaser.NONE; + + /** + * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. **Two** immovable Bodies can't separate or exchange momentum and will pass through each other. + * @default + */ + this.immovable = false; + + /** + * Whether the physics system should update the Body's position and rotation based on its velocity, acceleration, drag, and gravity. + * + * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never + * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. + * If you want the physics system to move the body around, then set moves to true. + * + * A Body with moves = false can still be moved slightly (but not accelerated) during collision separation unless you set {@link #immovable} as well. + * + * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually. + * @default + */ + this.moves = true; + + /** + * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateX = false; + + /** + * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateY = false; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapX - The amount of horizontal overlap during the collision. + */ + this.overlapX = 0; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapY - The amount of vertical overlap during the collision. + */ + this.overlapY = 0; + + /** + * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. + * @property {number} overlapR - The amount of overlap during the collision. + */ + this.overlapR = 0; + + /** + * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. + * @property {boolean} embedded - Body embed value. + */ + this.embedded = false; + + /** + * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. + * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? + */ + this.collideWorldBounds = false; + + /** + * Set the checkCollision properties to control which directions collision is processed for this Body. + * For example checkCollision.up = false means it won't collide when the collision happened while moving up. + * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. + * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. + * @property {object} checkCollision - An object containing allowed collision (none, up, down, left, right). + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * This object is populated with boolean values when the Body collides with another. + * touching.up = true means the collision happened to the top of this Body for example. + * @property {object} touching - An object containing touching results (none, up, down, left, right). + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with previous touching values from the bodies previous collision. + * @property {object} wasTouching - An object containing previous touching results (none, up, down, left, right). + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with boolean values when the Body collides with the World bounds or a Tile. + * For example if blocked.up is true then the Body cannot move up. + * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any (none, up, down, left, right). + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. + * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. + * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision. + */ + this.tilePadding = new Phaser.Point(); + + /** + * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state? + */ + this.dirty = false; + + /** + * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. + */ + this.skipQuadTree = false; + + /** + * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. + * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. + * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, + * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. + * @property {boolean} syncBounds + * @default + */ + this.syncBounds = false; + + /** + * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods. + */ + this.isMoving = false; + + /** + * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods. + */ + this.stopVelocityOnCollide = true; + + /** + * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveTimer = 0; + + /** + * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDistance = 0; + + /** + * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDuration = 0; + + /** + * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveTarget = null; + + /** + * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveEnd = null; + + /** + * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events. + */ + this.onMoveComplete = new Phaser.Signal(); + + /** + * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. + */ + this.movementCallback = null; + + /** + * @property {object} movementCallbackContext - Context in which to call the movementCallback. + */ + this.movementCallbackContext = null; + + /** + * @property {boolean} _reset - Internal cache var. + * @private + */ + this._reset = true; + + /** + * @property {number} _sx - Internal cache var. + * @private + */ + this._sx = sprite.scale.x; + + /** + * @property {number} _sy - Internal cache var. + * @private + */ + this._sy = sprite.scale.y; + + /** + * @property {number} _dx - Internal cache var. + * @private + */ + this._dx = 0; + + /** + * @property {number} _dy - Internal cache var. + * @private + */ + this._dy = 0; + +}; + +Phaser.Physics.Arcade.Body.prototype = { + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @protected + */ + updateBounds: function () { + + if (this.syncBounds) + { + var b = this.sprite.getBounds(); + b.ceilAll(); + + if (b.width !== this.width || b.height !== this.height) + { + this.width = b.width; + this.height = b.height; + this._reset = true; + } + } + else + { + 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._sx = asx; + this._sy = asy; + this._reset = true; + } + } + + if (this._reset) + { + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.updateCenter(); + } + + }, + + /** + * Update the Body's center from its position. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @protected + */ + updateCenter: function () { + + this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @protected + */ + preUpdate: function () { + + if (!this.enable || this.game.physics.arcade.isPaused) + { + return; + } + + this.dirty = true; + + // Store and reset collision flags + 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.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; + + this.overlapR = 0; + this.overlapX = 0; + this.overlapY = 0; + + this.embedded = false; + + this.updateBounds(); + + this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.updateCenter(); + + this.rotation = this.sprite.angle; + + this.preRotation = this.rotation; + + if (this._reset || this.sprite.fresh) + { + 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; + this.updateCenter(); + + if (this.position.x !== this.prev.x || this.position.y !== this.prev.y) + { + this.angle = this.velocity.atan(); + } + + this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); + + // Now the State update will throw collision checks at the Body + // And finally we'll integrate the new position back to the Sprite in postUpdate + + if (this.collideWorldBounds) + { + if (this.checkWorldBounds() && this.onWorldBounds) + { + this.onWorldBounds.dispatch(this.sprite, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); + } + } + } + + this._dx = this.deltaX(); + this._dy = this.deltaY(); + + this._reset = false; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateMovement + * @protected + */ + updateMovement: function () { + + var percent = 0; + var collided = (this.overlapX !== 0 || this.overlapY !== 0); + + // Duration or Distance based? + + if (this.moveDuration > 0) + { + this.moveTimer += this.game.time.elapsedMS; + + percent = this.moveTimer / this.moveDuration; + } + else + { + this.moveTarget.end.set(this.position.x, this.position.y); + + percent = this.moveTarget.length / this.moveDistance; + } + + if (this.movementCallback) + { + var result = this.movementCallback.call(this.movementCallbackContext, this, this.velocity, percent); + } + + if (collided || percent >= 1 || (result !== undefined && result !== true)) + { + this.stopMovement((percent >= 1) || (this.stopVelocityOnCollide && collided)); + return false; + } + + return true; + + }, + + /** + * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it + * has Body.isMoving true), then calling this method will stop the movement before + * either the duration or distance counters expire. + * + * The `onMoveComplete` signal is dispatched. + * + * @method Phaser.Physics.Arcade.Body#stopMovement + * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero? + */ + stopMovement: function (stopVelocity) { + + if (this.isMoving) + { + this.isMoving = false; + + if (stopVelocity) + { + this.velocity.set(0); + } + + // Send the Sprite this Body belongs to + // and a boolean indicating if it stopped because of a collision or not + this.onMoveComplete.dispatch(this.sprite, (this.overlapX !== 0 || this.overlapY !== 0)); + } + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @protected + */ + postUpdate: function () { + + // Only allow postUpdate to be called once per frame + if (!this.enable || !this.dirty) + { + return; + } + + // Moving? + if (this.isMoving) + { + this.updateMovement(); + } + + this.dirty = false; + + 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.position.x += this._dx; + this.sprite.position.y += this._dy; + this._reset = true; + } + + this.updateCenter(); + + if (this.allowRotation) + { + this.sprite.angle += this.deltaZ(); + } + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @protected + * @return {boolean} True if the Body collided with the world bounds, otherwise false. + */ + checkWorldBounds: function () { + + var pos = this.position; + var bounds = this.game.physics.arcade.bounds; + var check = this.game.physics.arcade.checkCollision; + + var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; + var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; + + if (pos.x < bounds.x && check.left) + { + pos.x = bounds.x; + this.velocity.x *= bx; + this.blocked.left = true; + this.blocked.none = false; + } + else if (this.right > bounds.right && check.right) + { + pos.x = bounds.right - this.width; + this.velocity.x *= bx; + this.blocked.right = true; + this.blocked.none = false; + } + + if (pos.y < bounds.y && check.up) + { + pos.y = bounds.y; + this.velocity.y *= by; + this.blocked.up = true; + this.blocked.none = false; + } + else if (this.bottom > bounds.bottom && check.down) + { + pos.y = bounds.bottom - this.height; + this.velocity.y *= by; + this.blocked.down = true; + this.blocked.none = false; + } + + return !this.blocked.none; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal timer, and then + * monitoring the duration each frame. When the duration is up the movement is + * stopped and the `Body.onMoveComplete` signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * You can optionally set a speed in pixels per second. If not specified it + * will use the current `Body.speed` value. If this is zero, the function will return false. + * + * Please note that due to browser timings you should allow for a variance in + * when the duration will actually expire. Depending on system it may be as much as + * +- 50ms. Also this method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveFrom + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveFrom: function (duration, speed, direction) { + + if (speed === undefined) { speed = this.speed; } + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + this.moveTimer = 0; + this.moveDuration = duration; + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal distance counter. + * The distance is monitored each frame. When the distance equals the distance + * specified in this call, the movement is stopped, and the `Body.onMoveComplete` + * signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * Please note that due to browser timings you should allow for a variance in + * when the distance will actually expire. + * + * Note: This method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveTo + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} distance - The distance, in pixels, the Body will move. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveTo: function (duration, distance, direction) { + + var speed = distance / (duration / 1000); + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + distance = Math.abs(distance); + + this.moveDuration = 0; + this.moveDistance = distance; + + if (this.moveTarget === null) + { + this.moveTarget = new Phaser.Line(); + this.moveEnd = new Phaser.Point(); + } + + this.moveTarget.fromAngle(this.x, this.y, angle, distance); + + this.moveEnd.set(this.moveTarget.end.x, this.moveTarget.end.y); + + this.moveTarget.setTo(this.x, this.y, this.x, this.y); + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * You can modify the size of the physics Body to be any dimension you need. + * This allows you to make it smaller, or larger, than the parent Sprite. You + * can also control the x and y offset of the Body. + * + * The width, height, and offset arguments are relative to the Sprite + * _texture_ and are scaled with the Sprite's {@link Phaser.Sprite#scale} + * (but **not** the scale of any ancestors or the {@link Phaser.Camera#scale + * Camera scale}). + * + * For example: If you have a Sprite with a texture that is 80x100 in size, + * and you want the physics body to be 32x32 pixels in the middle of the + * texture, you would do: + * + * `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, + * 34)` + * + * Where the first two parameters are the new Body size (32x32 pixels) + * relative to the Sprite's scale. 24 is the horizontal offset of the Body + * from the top-left of the Sprites texture, and 34 is the vertical offset. + * + * If you've scaled a Sprite by altering its `width`, `height`, or `scale` + * and you want to position the Body relative to the Sprite's dimensions + * (which will differ from its texture's dimensions), you should divide these + * arguments by the Sprite's current scale: + * + * `setSize(32 / sprite.scale.x, 32 / sprite.scale.y)` + * + * Calling `setSize` on a Body that has already had `setCircle` will reset + * all of the Circle properties, making this Body rectangular again. + * @method Phaser.Physics.Arcade.Body#setSize + * @param {number} width - The width of the Body, relative to the Sprite's + * texture. + * @param {number} height - The height of the Body, relative to the Sprite's + * texture. + * @param {number} [offsetX] - The X offset of the Body from the left of the + * Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the + * Sprite's texture. + */ + setSize: function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { 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.updateCenter(); + + this.isCircle = false; + this.radius = 0; + + }, + + /** + * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. + * The radius is given in pixels (relative to the Sprite's _texture_) and is the distance from the center of the circle to the edge. + * + * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite's texture. + * + * To change a Body back to being rectangular again call `Body.setSize`. + * + * Note: Circular collision only happens with other Arcade Physics bodies, it does not + * work against tile maps, where rectangular collision is the only method supported. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. + * @param {number} [offsetX] - The X offset of the Body from the left of the Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the Sprite's texture. + */ + setCircle: function (radius, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.isCircle = true; + this.radius = radius; + + this.sourceWidth = radius * 2; + this.sourceHeight = radius * 2; + + 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.updateCenter(); + } + else + { + this.isCircle = false; + } + + }, + + /** + * Resets all Body values (velocity, acceleration, rotation, etc) + * + * @method Phaser.Physics.Arcade.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new y position of the Body. + */ + reset: function (x, y) { + + this.stop(); + + this.position.x = (x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + this.rotation = this.sprite.angle; + this.preRotation = this.rotation; + + this.updateBounds(); + + this.updateCenter(); + + }, + + /** + * Sets acceleration, velocity, and {@link #speed} to 0. + * + * @method Phaser.Physics.Arcade.Body#stop + */ + stop: function () { + + this.velocity.set(0); + this.acceleration.set(0); + this.speed = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + + }, + + /** + * Returns the bounds of this physics body. + * + * Only used internally by the World collision methods. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @param {object} obj - The object in which to set the bounds values. + * @return {object} The object that was given to this method. + */ + getBounds: function (obj) { + + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + + }, + + /** + * Tests if a world point lies within this Body. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @param {number} x - The world x coordinate to test. + * @param {number} y - The world y coordinate to test. + * @return {boolean} True if the given coordinates are inside this Body, otherwise false. + */ + hitTest: function (x, y) { + + return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Returns true if the bottom of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onFloor: function () { + + return this.blocked.down; + + }, + + /** + * Returns true if the top of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onCeiling: function(){ + + return this.blocked.up; + + }, + + /** + * Returns true if either side of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onWall: function () { + + return (this.blocked.left || this.blocked.right); + + }, + + /** + * Returns the absolute delta x value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @return {number} The absolute delta value. + */ + deltaAbsX: function () { + + return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); + + }, + + /** + * Returns the absolute delta y value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @return {number} The absolute delta value. + */ + deltaAbsY: function () { + + return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); + + }, + + /** + * Returns the delta x value. The difference between Body.x now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. + */ + deltaX: function () { + + return this.position.x - this.prev.x; + + }, + + /** + * Returns the delta y value. The difference between Body.y now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. + */ + deltaY: function () { + + return this.position.y - this.prev.y; + + }, + + /** + * Returns the delta z value. The difference between Body.rotation now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise. + */ + deltaZ: function () { + + return this.rotation - this.preRotation; + + }, + + /** + * Destroys this Body. + * + * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. + * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. + * + * @method Phaser.Physics.Arcade.Body#destroy + */ + destroy: function () { + + if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group) + { + this.sprite.parent.removeFromHash(this.sprite); + } + + this.sprite.body = null; + this.sprite = null; + + } + +}; + +/** +* @name Phaser.Physics.Arcade.Body#left +* @property {number} left - The x position of the Body. The same as `Body.x`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "left", { + + get: function () { + + return this.position.x; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#right +* @property {number} right - The right value of this Body (same as Body.x + Body.width) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", { + + get: function () { + + return this.position.x + this.width; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#top +* @property {number} top - The y position of the Body. The same as `Body.y`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "top", { + + get: function () { + + return this.position.y; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#bottom +* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", { + + get: function () { + + return this.position.y + this.height; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#x +* @property {number} x - The x position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#y +* @property {number} y - The y position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + +}); + +/** +* Render Sprite Body. +* +* @method Phaser.Physics.Arcade.Body#render +* @param {object} context - The context to render to. +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string). +* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) +* @param {number} [lineWidth=1] - The width of the stroke when unfilled. +*/ +Phaser.Physics.Arcade.Body.render = function (context, body, color, filled, lineWidth) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0,255,0,0.4)'; + + context.fillStyle = color; + context.strokeStyle = color; + context.lineWidth = lineWidth || 1; + + if (body.isCircle) + { + context.beginPath(); + context.arc(body.center.x - body.game.camera.x, body.center.y - body.game.camera.y, body.halfWidth, 0, 2 * Math.PI); + + if (filled) + { + context.fill(); + } + else + { + context.stroke(); + } + } + else + { + if (filled) + { + context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + else + { + context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + } + +}; + +/** +* Render Sprite Body Physics Data as text. +* +* @method Phaser.Physics.Arcade.Body#renderBodyInfo +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {number} x - X position of the debug info to be rendered. +* @param {number} y - Y position of the debug info to be rendered. +* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). +*/ +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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics Tile map collision methods. +* +* @class Phaser.Physics.Arcade.TilemapCollision +* @constructor +*/ +Phaser.Physics.Arcade.TilemapCollision = function () {}; + +Phaser.Physics.Arcade.TilemapCollision.prototype = { + + /** + * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling. + */ + TILE_BIAS: 16, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!sprite.body) + { + return; + } + + var mapData = tilemapLayer.getTiles( + sprite.body.position.x - sprite.body.tilePadding.x - tilemapLayer.getTileOffsetX(), + sprite.body.position.y - sprite.body.tilePadding.y - tilemapLayer.getTileOffsetY(), + sprite.body.width + sprite.body.tilePadding.x, + sprite.body.height + sprite.body.tilePadding.y, + false, false); + + if (mapData.length === 0) + { + return; + } + + for (var i = 0; i < mapData.length; i++) + { + if (processCallback) + { + if (processCallback.call(callbackContext, sprite, mapData[i])) + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + else + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @private + * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer + * @param {Phaser.Group} group - The Group to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.children.length; i++) + { + if (group.children[i].exists) + { + this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * The core separation function to separate a physics body and a tile. + * + * @private + * @method Phaser.Physics.Arcade#separateTile + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to collide against. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {boolean} Returns true if the body was separated, otherwise false. + */ + separateTile: function (i, body, tile, tilemapLayer, overlapOnly) { + + if (!body.enable) + { + return false; + } + + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + // We re-check for collision in case body was separated in a previous step + if (!tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + // no collision so bail out (separated in a previous step) + return false; + } + else if (overlapOnly) + { + // There is an overlap, and we don't need to separate. Bail. + return true; + } + + // They overlap. Any custom callbacks? + + // A local callback always takes priority over a layer level callback + if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + else if (typeof tile.layer.callbacks !== 'undefined' && tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + + // We don't need to go any further if this tile doesn't actually separate + if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom) + { + // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation + return false; + } + + var ox = 0; + var oy = 0; + var minX = 0; + var minY = 1; + + if (body.deltaAbsX() > body.deltaAbsY()) + { + // Moving faster horizontally, check X axis first + minX = -1; + } + else if (body.deltaAbsX() < body.deltaAbsY()) + { + // Moving faster vertically, check Y axis first + minY = -1; + } + + if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom)) + { + // We only need do this if both axis have checking faces AND we're moving in both directions + minX = Math.min(Math.abs((body.position.x - tilemapLayerOffsetX) - tile.right), Math.abs((body.right - tilemapLayerOffsetX) - tile.left)); + minY = Math.min(Math.abs((body.position.y - tilemapLayerOffsetY) - tile.bottom), Math.abs((body.bottom - tilemapLayerOffsetY) - tile.top)); + } + + if (minX < minY) + { + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + + // That's horizontal done, check if we still intersects? If not then we can return now + if (ox !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + } + } + else + { + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + + // That's vertical done, check if we still intersects? If not then we can return now + if (oy !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + } + } + + return (ox !== 0 || oy !== 0); + + }, + + /** + * Check the body against the given tile on the X axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckX: function (body, tile, tilemapLayer) { + + var ox = 0; + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + + if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left) + { + // Body is moving LEFT + if (tile.faceRight && (body.x - tilemapLayerOffsetX) < tile.right) + { + ox = (body.x - tilemapLayerOffsetX) - tile.right; + + if (ox < -this.TILE_BIAS) + { + ox = 0; + } + } + } + else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right) + { + // Body is moving RIGHT + if (tile.faceLeft && (body.right - tilemapLayerOffsetX) > tile.left) + { + ox = (body.right - tilemapLayerOffsetX) - tile.left; + + if (ox > this.TILE_BIAS) + { + ox = 0; + } + } + } + + if (ox !== 0) + { + if (body.customSeparateX) + { + body.overlapX = ox; + } + else + { + this.processTileSeparationX(body, ox); + } + } + + return ox; + + }, + + /** + * Check the body against the given tile on the Y axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckY: function (body, tile, tilemapLayer) { + + var oy = 0; + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up) + { + // Body is moving UP + if (tile.faceBottom && (body.y - tilemapLayerOffsetY) < tile.bottom) + { + oy = (body.y - tilemapLayerOffsetY) - tile.bottom; + + if (oy < -this.TILE_BIAS) + { + oy = 0; + } + } + } + else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down) + { + // Body is moving DOWN + if (tile.faceTop && (body.bottom - tilemapLayerOffsetY) > tile.top) + { + oy = (body.bottom - tilemapLayerOffsetY) - tile.top; + + if (oy > this.TILE_BIAS) + { + oy = 0; + } + } + } + + if (oy !== 0) + { + if (body.customSeparateY) + { + body.overlapY = oy; + } + else + { + this.processTileSeparationY(body, oy); + } + } + + return oy; + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} x - The x separation amount. + */ + processTileSeparationX: function (body, x) { + + if (x < 0) + { + body.blocked.left = true; + body.blocked.none = false; + } + else if (x > 0) + { + body.blocked.right = true; + body.blocked.none = false; + } + + body.position.x -= x; + + if (body.bounce.x === 0) + { + body.velocity.x = 0; + } + else + { + body.velocity.x = -body.velocity.x * body.bounce.x; + } + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} y - The y separation amount. + */ + processTileSeparationY: function (body, y) { + + if (y < 0) + { + body.blocked.up = true; + body.blocked.none = false; + } + else if (y > 0) + { + body.blocked.down = true; + body.blocked.none = false; + } + + body.position.y -= y; + + if (body.bounce.y === 0) + { + body.velocity.y = 0; + } + else + { + body.velocity.y = -body.velocity.y * body.bounce.y; + } + + } + +}; + +// Merge this with the Arcade Physics prototype +Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Add an extra properties to p2 that we need +p2.Body.prototype.parent = null; +p2.Spring.prototype.parent = null; + +/** +* This is your main access to the P2 Physics World. +* From here you can create materials, listen for events and add bodies into the physics simulation. +* +* @class Phaser.Physics.P2 +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {object} [config] - Physics configuration object passed in from the game constructor. +*/ +Phaser.Physics.P2 = function (game, config) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + if (config === undefined) + { + config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; + } + else + { + if (!config.hasOwnProperty('gravity')) + { + config.gravity = [0, 0]; + } + + if (!config.hasOwnProperty('broadphase')) + { + config.broadphase = new p2.SAPBroadphase(); + } + } + + /** + * @property {object} config - The p2 World configuration object. + * @protected + */ + this.config = config; + + /** + * @property {p2.World} world - The p2 World in which the simulation is run. + * @protected + */ + this.world = new p2.World(this.config); + + /** + * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. + * @default + */ + this.frameRate = 1 / 60; + + /** + * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. + * @default + */ + this.useElapsedTime = false; + + /** + * @property {boolean} paused - The paused state of the P2 World. + * @default + */ + this.paused = false; + + /** + * @property {array} materials - A local array of all created Materials. + * @protected + */ + this.materials = []; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. + */ + this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); + + /** + * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * This signal is dispatched when a new Body is added to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world. + * + * @property {Phaser.Signal} onBodyAdded + */ + this.onBodyAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Body is removed to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world. + * + * @property {Phaser.Signal} onBodyRemoved + */ + this.onBodyRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is added to the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world. + * + * @property {Phaser.Signal} onSpringAdded + */ + this.onSpringAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is removed from the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world. + * + * @property {Phaser.Signal} onSpringRemoved + */ + this.onSpringRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is added to the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world. + * + * @property {Phaser.Signal} onConstraintAdded + */ + this.onConstraintAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is removed from the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world. + * + * @property {Phaser.Signal} onConstraintRemoved + */ + this.onConstraintRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is added to the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world. + * + * @property {Phaser.Signal} onContactMaterialAdded + */ + this.onContactMaterialAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is removed from the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world. + * + * @property {Phaser.Signal} onContactMaterialRemoved + */ + this.onContactMaterialRemoved = new Phaser.Signal(); + + /** + * @property {function} postBroadphaseCallback - A postBroadphase callback. + */ + this.postBroadphaseCallback = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are fired. + */ + this.callbackContext = null; + + /** + * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done. + * + * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done. + * + * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + // Pixel to meter function overrides + if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) + { + this.mpx = config.mpx; + this.mpxi = config.mpxi; + this.pxm = config.pxm; + this.pxmi = config.pxmi; + } + + // Hook into the World events + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + /** + * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. + */ + this.collisionGroups = []; + + /** + * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. + */ + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. + */ + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. + */ + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + /** + * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. + */ + this.boundsCollidesWith = []; + + /** + * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. + * @private + */ + this._toRemove = []; + + /** + * @property {number} _collisionGroupID - Internal var. + * @private + */ + this._collisionGroupID = 2; + + /** + * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsLeft = true; + + /** + * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsRight = true; + + /** + * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsTop = true; + + /** + * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsBottom = true; + + /** + * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsOwnGroup = false; + + // By default we want everything colliding with everything + this.setBoundsToWorld(true, true, true, true, false); + +}; + +Phaser.Physics.P2.prototype = { + + /** + * This will add a P2 Physics body into the removal list for the next step. + * + * @method Phaser.Physics.P2#removeBodyNextStep + * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. + */ + removeBodyNextStep: function (body) { + + this._toRemove.push(body); + + }, + + /** + * Called at the start of the core update loop. Purges flagged bodies from the world. + * + * @method Phaser.Physics.P2#preUpdate + */ + preUpdate: function () { + + var i = this._toRemove.length; + + while (i--) + { + this.removeBody(this._toRemove[i]); + } + + this._toRemove.length = 0; + + }, + + /** + * This will create a P2 Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. + * + * @method Phaser.Physics.P2#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [debug=false] - Create a debug object to go with this body? + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, debug, children) { + + if (debug === undefined) { debug = false; } + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + this.enable(object[i].children, debug, children); + } + else + { + this.enableBody(object[i], debug); + + if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) + { + this.enable(object[i], debug, true); + } + } + } + } + else + { + if (object instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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); + } + } + } + + }, + + /** + * Creates a P2 Physics body on the given game object. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * @method Phaser.Physics.P2#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + * @param {boolean} debug - Create a debug object to go with this body? + */ + 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; + if (typeof object.anchor !== 'undefined') { + object.anchor.set(0.5); + } + } + + }, + + /** + * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. + * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. + * + * @method Phaser.Physics.P2#setImpactEvents + * @param {boolean} state - Set to true to enable impact events, or false to disable. + */ + setImpactEvents: function (state) { + + if (state) + { + this.world.on("impact", this.impactHandler, this); + } + else + { + this.world.off("impact", this.impactHandler, this); + } + + }, + + /** + * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. + * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. + * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. + * Returning `true` from the callback will ensure they are checked in the narrowphase. + * + * @method Phaser.Physics.P2#setPostBroadphaseCallback + * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. + * @param {object} context - The context under which the callback will be fired. + */ + 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); + } + + }, + + /** + * Internal handler for the postBroadphase event. + * + * @method Phaser.Physics.P2#postBroadphaseHandler + * @private + * @param {object} event - The event data. + */ + postBroadphaseHandler: function (event) { + + if (!this.postBroadphaseCallback || event.pairs.length === 0) + { + return; + } + + for (var i = event.pairs.length - 2; i >= 0; 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); + } + } + + }, + + /** + * Handles a p2 impact event. + * + * @method Phaser.Physics.P2#impactHandler + * @private + * @param {object} event - The event data. + */ + impactHandler: function (event) { + + if (event.bodyA.parent && event.bodyB.parent) + { + // Body vs. Body callbacks + 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); + } + + // Body vs. Group callbacks + 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); + } + } + + }, + + /** + * Handles a p2 begin contact event. + * + * @method Phaser.Physics.P2#beginContactHandler + * @param {object} event - The event data. + */ + beginContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + 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.bodyB, event.shapeA, event.shapeB, event.contactEquations); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations); + } + } + + }, + + /** + * Handles a p2 end contact event. + * + * @method Phaser.Physics.P2#endContactHandler + * @param {object} event - The event data. + */ + endContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); + + if (event.bodyA.parent) + { + event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA); + } + } + + }, + + /** + * Sets the bounds of the Physics world to match the Game.World dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * + * @method Phaser.Physics#setBoundsToWorld + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + 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); + + }, + + /** + * Sets the given material against the 4 bounds of this World. + * + * @method Phaser.Physics#setWorldMaterial + * @param {Phaser.Physics.P2.Material} material - The material to set. + * @param {boolean} [left=true] - If true will set the material on the left bounds wall. + * @param {boolean} [right=true] - If true will set the material on the right bounds wall. + * @param {boolean} [top=true] - If true will set the material on the top bounds wall. + * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. + */ + setWorldMaterial: function (material, left, right, top, bottom) { + + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (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; + } + + }, + + /** + * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. + * If you start to use your own collision groups then your objects will no longer collide with the bounds. + * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. + * + * @method Phaser.Physics.P2#updateBoundsCollisionGroup + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + updateBoundsCollisionGroup: function (setCollisionGroup) { + + if (setCollisionGroup === undefined) { setCollisionGroup = true; } + + var mask = (setCollisionGroup) ? this.boundsCollisionGroup.mask : this.everythingCollisionGroup.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; + } + + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.P2#setBounds + * @param {number} x - The x coordinate of the top-left corner of the bounds. + * @param {number} y - The y coordinate of the top-left corner of the bounds. + * @param {number} width - The width of the bounds. + * @param {number} height - The height of the bounds. + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { + + if (left === undefined) { left = this._boundsLeft; } + if (right === undefined) { right = this._boundsRight; } + if (top === undefined) { top = this._boundsTop; } + if (bottom === undefined) { bottom = this._boundsBottom; } + if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; } + + this.setupWall(left, 'left', x, y, 1.5707963267948966, setCollisionGroup); + this.setupWall(right, 'right', x + width, y, -1.5707963267948966, setCollisionGroup); + this.setupWall(top, 'top', x, y, -3.141592653589793, setCollisionGroup); + this.setupWall(bottom, 'bottom', x, y + height, 0, setCollisionGroup); + + // Remember the bounds settings in case they change later on via World.setBounds + this._boundsLeft = left; + this._boundsRight = right; + this._boundsTop = top; + this._boundsBottom = bottom; + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Internal method called by setBounds. Responsible for creating, updating or + * removing the wall body shapes. + * + * @method Phaser.Physics.P2#setupWall + * @private + * @param {boolean} create - True to create the wall shape, false to remove it. + * @param {string} wall - The wall segment to update. + * @param {number} x - The x coordinate of the wall. + * @param {number} y - The y coordinate of the wall. + * @param {float} angle - The angle of the wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setupWall: function (create, wall, x, y, angle, setCollisionGroup) { + + if (create) + { + // We need a left wall. Do we have one already? + if (this.walls[wall]) + { + this.walls[wall].position = [ this.pxmi(x), this.pxmi(y) ]; + } + else + { + this.walls[wall] = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: angle }); + this.walls[wall].addShape(new p2.Plane()); + + this.world.addBody(this.walls[wall]); + } + + if (setCollisionGroup) + { + this.walls[wall].shapes[0].collisionGroup = this.boundsCollisionGroup.mask; + } + } + else + { + if (this.walls[wall]) + { + this.world.removeBody(this.walls[wall]); + this.walls[wall] = null; + } + } + + }, + + /** + * Pauses the P2 World independent of the game pause state. + * + * @method Phaser.Physics.P2#pause + */ + pause: function() { + + this.paused = true; + + }, + + /** + * Resumes a paused P2 World. + * + * @method Phaser.Physics.P2#resume + */ + resume: function() { + + this.paused = false; + + }, + + /** + * Internal P2 update loop. + * + * @method Phaser.Physics.P2#update + */ + update: function () { + + // Do nothing if the physics engine was paused before + if (this.paused) + { + return; + } + + if (this.useElapsedTime) + { + this.world.step(this.game.time.physicsElapsed); + } + else + { + this.world.step(this.frameRate); + } + + }, + + /** + * Called by Phaser.Physics when a State swap occurs. + * Starts the begin and end Contact listeners again. + * + * @method Phaser.Physics.P2#reset + */ + reset: function () { + + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + this._collisionGroupID = 2; + + this.setBoundsToWorld(true, true, true, true, false); + + }, + + /** + * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. + * + * The P2 world is also cleared: + * + * * Removes all solver equations + * * Removes all constraints + * * Removes all bodies + * * Removes all springs + * * Removes all contact materials + * + * This is called automatically when you switch state. + * + * @method Phaser.Physics.P2#clear + */ + clear: function () { + + this.world.time = 0; + this.world.fixedStepTime = 0; + + // Remove all solver equations + if (this.world.solver && this.world.solver.equations.length) + { + this.world.solver.removeAllEquations(); + } + + // Remove all constraints + var cs = this.world.constraints; + + for (var i = cs.length - 1; i >= 0; i--) + { + this.world.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.world.bodies; + + for (var i = bodies.length - 1; i >= 0; i--) + { + this.world.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.world.springs; + + for (var i = springs.length - 1; i >= 0; i--) + { + this.world.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.world.contactMaterials; + + for (var i = cms.length - 1; i >= 0; i--) + { + this.world.removeContactMaterial(cms[i]); + } + + 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.boundsCollidesWith = []; + + // Remove the world bounds + this.walls = { left: null, right: null, top: null, bottom: null }; + + }, + + /** + * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. + * + * @method Phaser.Physics.P2#destroy + */ + destroy: function () { + + this.clear(); + + this.game = null; + + }, + + /** + * Add a body to the world. + * + * @method Phaser.Physics.P2#addBody + * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. + * @return {boolean} True if the Body was added successfully, otherwise false. + */ + addBody: function (body) { + + if (body.data.world) + { + return false; + } + else + { + this.world.addBody(body.data); + + this.onBodyAdded.dispatch(body); + + return true; + } + + }, + + /** + * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. + * + * @method Phaser.Physics.P2#removeBody + * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. + * @return {Phaser.Physics.P2.Body} The Body that was removed. + */ + removeBody: function (body) { + + if (body.data.world === this.world) + { + this.world.removeBody(body.data); + + this.onBodyRemoved.dispatch(body); + } + + return body; + + }, + + /** + * Adds a Spring to the world. + * + * @method Phaser.Physics.P2#addSpring + * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was added. + */ + addSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.addSpring(spring.data); + } + else + { + this.world.addSpring(spring); + } + + this.onSpringAdded.dispatch(spring); + + return spring; + + }, + + /** + * Removes a Spring from the world. + * + * @method Phaser.Physics.P2#removeSpring + * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was removed. + */ + removeSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.removeSpring(spring.data); + } + else + { + this.world.removeSpring(spring); + } + + this.onSpringRemoved.dispatch(spring); + + return spring; + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createDistanceConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} distance - The distance to keep between the bodies. + * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. + * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.DistanceConstraint} The constraint + */ + createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, 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, localAnchorA, localAnchorB, maxForce)); + } + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createGearConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [angle=0] - The relative angle + * @param {number} [ratio=1] - The gear ratio. + * @return {Phaser.Physics.P2.GearConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * The pivot points are given in world (pixel) coordinates. + * + * @method Phaser.Physics.P2#createRevoluteConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. + * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint + */ + createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + 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, worldPivot)); + } + + }, + + /** + * Locks the relative position between two bodies. + * + * @method Phaser.Physics.P2#createLockConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.LockConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Constraint that only allows bodies to move along a line, relative to each other. + * See http://www.iforce2d.net/b2dtut/joints-prismatic + * + * @method Phaser.Physics.P2#createPrismaticConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. + * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Adds a Constraint to the world. + * + * @method Phaser.Physics.P2#addConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. + */ + addConstraint: function (constraint) { + + this.world.addConstraint(constraint); + + this.onConstraintAdded.dispatch(constraint); + + return constraint; + + }, + + /** + * Removes a Constraint from the world. + * + * @method Phaser.Physics.P2#removeConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. + */ + removeConstraint: function (constraint) { + + this.world.removeConstraint(constraint); + + this.onConstraintRemoved.dispatch(constraint); + + return constraint; + + }, + + /** + * Adds a Contact Material to the world. + * + * @method Phaser.Physics.P2#addContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. + */ + addContactMaterial: function (material) { + + this.world.addContactMaterial(material); + + this.onContactMaterialAdded.dispatch(material); + + return material; + + }, + + /** + * Removes a Contact Material from the world. + * + * @method Phaser.Physics.P2#removeContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. + */ + removeContactMaterial: function (material) { + + this.world.removeContactMaterial(material); + + this.onContactMaterialRemoved.dispatch(material); + + return material; + + }, + + /** + * Gets a Contact Material based on the two given Materials. + * + * @method Phaser.Physics.P2#getContactMaterial + * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. + * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. + * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. + */ + getContactMaterial: function (materialA, materialB) { + + return this.world.getContactMaterial(materialA, materialB); + + }, + + /** + * Sets the given Material against all Shapes owned by all the Bodies in the given array. + * + * @method Phaser.Physics.P2#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. + * @param {array} bodies - An Array of Body objects that the given Material will be set on. + */ + setMaterial: function (material, bodies) { + + var i = bodies.length; + + while (i--) + { + bodies[i].setMaterial(material); + } + + }, + + /** + * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). + * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. + * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. + * + * @method Phaser.Physics.P2#createMaterial + * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. + * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. + * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. + */ + 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; + + }, + + /** + * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. + * + * @method Phaser.Physics.P2#createContactMaterial + * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {object} [options] - Material options object. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. + */ + createContactMaterial: function (materialA, materialB, options) { + + if (materialA === undefined) { materialA = this.createMaterial(); } + if (materialB === undefined) { materialB = this.createMaterial(); } + + var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); + + return this.addContactMaterial(contact); + + }, + + /** + * Populates and returns an array with references to of all current Bodies in the world. + * + * @method Phaser.Physics.P2#getBodies + * @return {array} An array containing all current Bodies in the world. + */ + getBodies: function () { + + var output = []; + var i = this.world.bodies.length; + + while (i--) + { + output.push(this.world.bodies[i].parent); + } + + return output; + + }, + + /** + * Checks the given object to see if it has a p2.Body and if so returns it. + * + * @method Phaser.Physics.P2#getBody + * @param {object} object - The object to check for a p2.Body on. + * @return {p2.Body} The p2.Body, or null if not found. + */ + getBody: function (object) { + + if (object instanceof p2.Body) + { + // Native p2 body + return object; + } + else if (object instanceof Phaser.Physics.P2.Body) + { + // Phaser P2 Body + return object.data; + } + else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) + { + // Sprite, TileSprite, etc + return object.body.data; + } + + return null; + + }, + + /** + * Populates and returns an array of all current Springs in the world. + * + * @method Phaser.Physics.P2#getSprings + * @return {array} An array containing all current Springs in the world. + */ + getSprings: function () { + + var output = []; + var i = this.world.springs.length; + + while (i--) + { + output.push(this.world.springs[i].parent); + } + + return output; + + }, + + /** + * Populates and returns an array of all current Constraints in the world. + * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain + * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type. + * + * @method Phaser.Physics.P2#getConstraints + * @return {array} An array containing all current Constraints in the world. + */ + getConstraints: function () { + + var output = []; + var i = this.world.constraints.length; + + while (i--) + { + output.push(this.world.constraints[i]); + } + + return output; + + }, + + /** + * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to + * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. + * + * @method Phaser.Physics.P2#hitTest + * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. + * @param {Array} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) + * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. + * @return {Array} Array of bodies that overlap the point. + */ + hitTest: function (worldPoint, bodies, precision, filterStatic) { + + if (bodies === undefined) { bodies = this.world.bodies; } + if (precision === undefined) { precision = 5; } + if (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.type === p2.Body.STATIC)) + { + query.push(bodies[i].data); + } + else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC)) + { + query.push(bodies[i]); + } + else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC)) + { + query.push(bodies[i].body.data); + } + } + + return this.world.hitTest(physicsPosition, query, precision); + + }, + + /** + * Converts the current world into a JSON object. + * + * @method Phaser.Physics.P2#toJSON + * @return {object} A JSON representation of the world. + */ + toJSON: function () { + + return this.world.toJSON(); + + }, + + /** + * Creates a new Collision Group and optionally applies it to the given object. + * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. + * + * @method Phaser.Physics.P2#createCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + */ + 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; + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. + * + * @method Phaser.Physics.P2y#setCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + */ + setCollisionGroup: function (object, group) { + + if (object instanceof Phaser.Group) + { + for (var i = 0; i < object.total; i++) + { + if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) + { + object.children[i].body.setCollisionGroup(group); + } + } + } + else + { + object.body.setCollisionGroup(group); + } + + }, + + /** + * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restLength=1] - Rest length of the spring. A number > 0. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @return {Phaser.Physics.P2.Spring} The spring + */ + createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); + } + + }, + + /** + * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createRotationalSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @return {Phaser.Physics.P2.RotationalSpring} The spring + */ + createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Rotational Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping)); + } + + }, + + /** + * Creates a new Body and adds it to the World. + * + * @method Phaser.Physics.P2#createBody + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {Phaser.Physics.P2.Body} The body + */ + createBody: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Creates a new Particle and adds it to the World. + * + * @method Phaser.Physics.P2#createParticle + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + */ + createParticle: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Converts all of the polyline, polygon, and rectangle objects inside a Tiled ObjectGroup into physics bodies that are added to the world. + * Note that the polylines and polygons must be created in such a way that they can withstand polygon decomposition. + * + * @method Phaser.Physics.P2#convertCollisionObjects + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. + * @return {array} An array of the Phaser.Physics.Body objects that have been created. + */ + convertCollisionObjects: function (map, layer, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var output = []; + + for (var i = 0, len = map.collision[layer].length; i < len; i++) + { + // name: json.layers[i].objects[v].name, + // x: json.layers[i].objects[v].x, + // y: json.layers[i].objects[v].y, + // width: json.layers[i].objects[v].width, + // height: json.layers[i].objects[v].height, + // visible: json.layers[i].objects[v].visible, + // properties: json.layers[i].objects[v].properties, + // polyline: json.layers[i].objects[v].polyline + + var object = map.collision[layer][i]; + var shapeData = object.polyline || object.polygon; + + // polyline/polygon shape data present + if (shapeData) + { + var body = this.createBody(object.x, object.y, 0, addToWorld, {}, shapeData); + } + + // tilemap parser sets rectangle=true when parsing object groups + else if (object.rectangle) + { + var body = this.createBody(object.x, object.y, 0, addToWorld); + body.addRectangle(object.width, object.height, object.width / 2, object.height / 2); + } + + // ellipse could be added here, but Tiled ellipses use height/width instead of radius + // (to support oblong ellipses), which p2 doesn't currently support. + + if (body) + { + output.push(body); + } + } + + return output; + + }, + + /** + * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. + * + * @method Phaser.Physics.P2#clearTilemapLayerBodies + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + */ + 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 = 0; + + }, + + /** + * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. + * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. + * Every time you call this method it will destroy any previously created bodies and remove them from the world. + * Therefore understand it's a very expensive operation and not to be done in a core game update loop. + * + * @method Phaser.Physics.P2#convertTilemap + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. + * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. + * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. + */ + convertTilemap: function (map, layer, addToWorld, optimize) { + + layer = map.getLayer(layer); + + if (addToWorld === undefined) { addToWorld = true; } + if (optimize === undefined) { optimize = true; } + + // If the bodies array is already populated we need to nuke it + this.clearTilemapLayerBodies(map, layer); + + var width = 0; + var sx = 0; + var sy = 0; + + for (var y = 0, h = map.layers[layer].height; y < h; y++) + { + width = 0; + + for (var x = 0, w = map.layers[layer].width; x < w; x++) + { + var tile = map.layers[layer].data[y][x]; + + if (tile && tile.index > -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; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpx + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpx: function (v) { + + return v *= 20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters). + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxm + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxm: function (v) { + + return v * 0.05; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpxi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpxi: function (v) { + + return v *= -20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters) and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxmi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxmi: function (v) { + + return v * -0.05; + + } + +}; + +/** +* @name Phaser.Physics.P2#friction +* @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { + + get: function () { + + return this.world.defaultContactMaterial.friction; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.friction = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#restitution +* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { + + get: function () { + + return this.world.defaultContactMaterial.restitution; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.restitution = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#contactMaterial +* @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { + + get: function () { + + return this.world.defaultContactMaterial; + + }, + + set: function (value) { + + this.world.defaultContactMaterial = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applySpringForces +* @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { + + get: function () { + + return this.world.applySpringForces; + + }, + + set: function (value) { + + this.world.applySpringForces = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyDamping +* @property {boolean} applyDamping - Enable to automatically apply body damping each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { + + get: function () { + + return this.world.applyDamping; + + }, + + set: function (value) { + + this.world.applyDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyGravity +* @property {boolean} applyGravity - Enable to automatically apply gravity each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { + + get: function () { + + return this.world.applyGravity; + + }, + + set: function (value) { + + this.world.applyGravity = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#solveConstraints +* @property {boolean} solveConstraints - Enable/disable constraint solving in each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { + + get: function () { + + return this.world.solveConstraints; + + }, + + set: function (value) { + + this.world.solveConstraints = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#time +* @property {boolean} time - The World time. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "time", { + + get: function () { + + return this.world.time; + + } + +}); + +/** +* @name Phaser.Physics.P2#emitImpactEvent +* @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { + + get: function () { + + return this.world.emitImpactEvent; + + }, + + set: function (value) { + + this.world.emitImpactEvent = value; + + } + +}); + +/** +* How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. +* If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. +* @name Phaser.Physics.P2#sleepMode +* @property {number} sleepMode +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", { + + get: function () { + + return this.world.sleepMode; + + }, + + set: function (value) { + + this.world.sleepMode = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#total +* @property {number} total - The total number of bodies in the world. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "total", { + + get: function () { + + return this.world.bodies.length; + + } + +}); + +/* jshint noarg: false */ + +/** +* @author Georgios Kaleadis https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Allow to access a list of created fixture (coming from Body#addPhaserPolygon) +* which itself parse the input from PhysicsEditor with the custom phaser exporter. +* You can access fixtures of a Body by a group index or even by providing a fixture Key. + +* You can set the fixture key and also the group index for a fixture in PhysicsEditor. +* This gives you the power to create a complex body built of many fixtures and modify them +* during runtime (to remove parts, set masks, categories & sensor properties) +* +* @class Phaser.Physics.P2.FixtureList +* @constructor +* @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) +*/ +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 = { + + /** + * @method Phaser.Physics.P2.FixtureList#init + */ + init: function () { + + /** + * @property {object} namedFixtures - Collect all fixtures with a key + * @private + */ + this.namedFixtures = {}; + + /** + * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group + * @private + */ + this.groupedFixtures = []; + + /** + * @property {Array} allFixtures - This is a list of everything in this collection + * @private + */ + this.allFixtures = []; + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setCategory + * @param {number} bit - The bit to set as the collision group. + * @param {string} fixtureKey - Only apply to the fixture with the given key. + */ + setCategory: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionGroup = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMask + * @param {number} bit - The bit to set as the collision mask + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMask: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionMask = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setSensor + * @param {boolean} value - sensor true or false + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setSensor: function (value, fixtureKey) { + + var setter = function(fixture) { + fixture.sensor = value; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMaterial + * @param {Object} material - The contact material for a fixture + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMaterial: function (material, fixtureKey) { + + var setter = function(fixture) { + fixture.material = material; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * Accessor to get either a list of specified fixtures by key or the whole fixture list + * + * @method Phaser.Physics.P2.FixtureList#getFixtures + * @param {array} keys - A list of fixture keys + */ + 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; + } + + }, + + /** + * Accessor to get either a single fixture by its key. + * + * @method Phaser.Physics.P2.FixtureList#getFixtureByKey + * @param {string} key - The key of the fixture. + */ + getFixtureByKey: function (key) { + + return this.namedFixtures[key]; + + }, + + /** + * Accessor to get a group of fixtures by its group index. + * + * @method Phaser.Physics.P2.FixtureList#getGroup + * @param {number} groupID - The group index. + */ + getGroup: function (groupID) { + + return this.groupedFixtures[groupID]; + + }, + + /** + * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon + * + * @method Phaser.Physics.P2.FixtureList#parse + */ + 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)); + } + + }, + + /** + * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. + * + * @method Phaser.Physics.P2.FixtureList#flatten + * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. + */ + 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; + + } + +}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. +* +* @class Phaser.Physics.P2.PointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.PointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; + +/** +* @name Phaser.Physics.P2.PointProxy#x +* @property {number} x - The x property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { + + get: function () { + + return this.world.mpx(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#y +* @property {number} y - The y property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { + + get: function () { + + return this.world.mpx(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#mx +* @property {number} mx - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#my +* @property {number} my - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. +* +* @class Phaser.Physics.P2.InversePointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.InversePointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; + +/** +* @name Phaser.Physics.P2.InversePointProxy#x +* @property {number} x - The x property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#y +* @property {number} y - The y property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#mx +* @property {number} mx - The x property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = -value; + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#my +* @property {number} my - The y property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = -value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. +* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. +* In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. +* By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. +* Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. +* Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. +* +* @class Phaser.Physics.P2.Body +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. +* @param {number} [x=0] - The x coordinate of this Body. +* @param {number} [y=0] - The y coordinate of this Body. +* @param {number} [mass=1] - The default mass of this Body (0 = static). +*/ +Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { + + sprite = sprite || null; + x = x || 0; + y = y || 0; + if (mass === undefined) { mass = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to the P2 World. + */ + this.world = game.physics.p2; + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.P2JS; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. + */ + this.offset = new Phaser.Point(); + + /** + * @property {p2.Body} data - The p2 Body data. + * @protected + */ + this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); + + this.data.parent = this; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. + */ + this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); + + /** + * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body. + */ + this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); + + /** + * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. + */ + this.gravity = new Phaser.Point(); + + /** + * Dispatched when a first contact is created between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 5 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body is in contact with. + * The Shape from this body that caused the contact. + * The Shape from the contact body. + * The Contact Equation data array. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * Dispatched when contact ends between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 4 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body has ended contact with. + * The Shape from this body that caused the original contact. + * The Shape from the contact body. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + /** + * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. + */ + this.collidesWith = []; + + /** + * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. + */ + this.removeNextStep = false; + + /** + * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. + */ + this.debugBody = null; + + /** + * @property {boolean} dirty - Internally used by Sprite.x/y + */ + this.dirty = false; + + /** + * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. + * @private + */ + this._collideWorldBounds = true; + + /** + * @property {object} _bodyCallbacks - Array of Body callbacks. + * @private + */ + this._bodyCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Body callback contexts. + * @private + */ + this._bodyCallbackContext = {}; + + /** + * @property {object} _groupCallbacks - Array of Group callbacks. + * @private + */ + this._groupCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. + * @private + */ + this._groupCallbackContext = {}; + + /** + * @property {boolean} _reset - Internal var. + * @private + */ + this._reset = false; + + // Set-up the default shape + if (sprite) + { + this.setRectangleFromSprite(sprite); + + if (sprite.exists) + { + this.game.physics.p2.addBody(this); + } + } + +}; + +Phaser.Physics.P2.Body.prototype = { + + /** + * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createBodyCallback + * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + 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; + } + } + + }, + + /** + * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * This callback will only fire if this Body has been assigned a collision group. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createGroupCallback + * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + createGroupCallback: function (group, callback, callbackContext) { + + if (callback === null) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + else + { + this._groupCallbacks[group.mask] = callback; + this._groupCallbackContext[group.mask] = callbackContext; + } + + }, + + /** + * Gets the collision bitmask from the groups this body collides with. + * + * @method Phaser.Physics.P2.Body#getCollisionMask + * @return {number} The bitmask. + */ + getCollisionMask: function () { + + var mask = 0; + + if (this._collideWorldBounds) + { + mask = this.game.physics.p2.boundsCollisionGroup.mask; + } + + for (var i = 0; i < this.collidesWith.length; i++) + { + mask = mask | this.collidesWith[i].mask; + } + + return mask; + + }, + + /** + * Updates the collisionMask. + * + * @method Phaser.Physics.P2.Body#updateCollisionMask + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + updateCollisionMask: function (shape) { + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * This also resets the collisionMask. + * + * @method Phaser.Physics.P2.Body#setCollisionGroup + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + setCollisionGroup: function (group, shape) { + + var mask = this.getCollisionMask(); + + if (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; + } + + }, + + /** + * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. + * + * @method Phaser.Physics.P2.Body#clearCollision + * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? + * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. + */ + clearCollision: function (clearGroup, clearMask, shape) { + + if (clearGroup === undefined) { clearGroup = true; } + if (clearMask === undefined) { clearMask = true; } + + if (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; + } + + }, + + /** + * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#removeCollisionGroup + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore. + * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body. + */ + removeCollisionGroup: function (group, clearCallback, shape) { + + if (clearCallback === undefined) { clearCallback = true; } + + var index; + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + index = this.collidesWith.indexOf(group[i]); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + } + else + { + index = this.collidesWith.indexOf(group); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#collides + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. + * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. + * @param {object} [callbackContext] - The context under which the callback will be called. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. + */ + collides: function (group, callback, callbackContext, shape) { + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + if (this.collidesWith.indexOf(group[i]) === -1) + { + this.collidesWith.push(group[i]); + + if (callback) + { + this.createGroupCallback(group[i], callback, callbackContext); + } + } + } + } + else + { + if (this.collidesWith.indexOf(group) === -1) + { + this.collidesWith.push(group); + + if (callback) + { + this.createGroupCallback(group, callback, callbackContext); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Moves the shape offsets so their center of mass becomes the body center of mass. + * + * @method Phaser.Physics.P2.Body#adjustCenterOfMass + */ + adjustCenterOfMass: function () { + + this.data.adjustCenterOfMass(); + this.shapeChanged(); + + }, + + /** + * Gets the velocity of a point in the body. + * + * @method Phaser.Physics.P2.Body#getVelocityAtPoint + * @param {Array} result - A vector to store the result in. + * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from. + * @return {Array} The result vector. + */ + getVelocityAtPoint: function (result, relativePoint) { + + return this.data.getVelocityAtPoint(result, relativePoint); + + }, + + /** + * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. + * + * @method Phaser.Physics.P2.Body#applyDamping + * @param {number} dt - Current time step. + */ + applyDamping: function (dt) { + + this.data.applyDamping(dt); + + }, + + /** + * Apply impulse to a point relative to the body. + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulse + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space. + * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + */ + applyImpulse: function (impulse, worldX, worldY) { + + this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Apply impulse to a point local to the body. + * + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulseLocal + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space. + * @param {number} localX - A local point on the body. + * @param {number} localY - A local point on the body. + */ + applyImpulseLocal: function (impulse, localX, localY) { + + this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]); + + }, + + /** + * Apply force to a world point. + * + * This could for example be a point on the RigidBody surface. Applying force + * this way will add to Body.force and Body.angularForce. + * + * @method Phaser.Physics.P2.Body#applyForce + * @param {Float32Array|Array} force - The force vector to add. + * @param {number} worldX - The world x point to apply the force on. + * @param {number} worldY - The world y point to apply the force on. + */ + applyForce: function (force, worldX, worldY) { + + this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Sets the force on the body to zero. + * + * @method Phaser.Physics.P2.Body#setZeroForce + */ + setZeroForce: function () { + + this.data.setZeroForce(); + + }, + + /** + * If this Body is dynamic then this will zero its angular velocity. + * + * @method Phaser.Physics.P2.Body#setZeroRotation + */ + setZeroRotation: function () { + + this.data.angularVelocity = 0; + + }, + + /** + * If this Body is dynamic then this will zero its velocity on both axis. + * + * @method Phaser.Physics.P2.Body#setZeroVelocity + */ + setZeroVelocity: function () { + + this.data.velocity[0] = 0; + this.data.velocity[1] = 0; + + }, + + /** + * Sets the Body damping and angularDamping to zero. + * + * @method Phaser.Physics.P2.Body#setZeroDamping + */ + setZeroDamping: function () { + + this.data.damping = 0; + this.data.angularDamping = 0; + + }, + + /** + * Transform a world point to local body frame. + * + * @method Phaser.Physics.P2.Body#toLocalFrame + * @param {Float32Array|Array} out - The vector to store the result in. + * @param {Float32Array|Array} worldPoint - The input world vector. + */ + toLocalFrame: function (out, worldPoint) { + + return this.data.toLocalFrame(out, worldPoint); + + }, + + /** + * Transform a local point to world frame. + * + * @method Phaser.Physics.P2.Body#toWorldFrame + * @param {Array} out - The vector to store the result in. + * @param {Array} localPoint - The input local vector. + */ + toWorldFrame: function (out, localPoint) { + + return this.data.toWorldFrame(out, localPoint); + + }, + + /** + * This will rotate the Body by the given speed to the left (counter-clockwise). + * + * @method Phaser.Physics.P2.Body#rotateLeft + * @param {number} speed - The speed at which it should rotate. + */ + rotateLeft: function (speed) { + + this.data.angularVelocity = this.world.pxm(-speed); + + }, + + /** + * This will rotate the Body by the given speed to the left (clockwise). + * + * @method Phaser.Physics.P2.Body#rotateRight + * @param {number} speed - The speed at which it should rotate. + */ + rotateRight: function (speed) { + + this.data.angularVelocity = this.world.pxm(speed); + + }, + + /** + * Moves the Body forwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveForward + * @param {number} speed - The speed at which it should move forwards. + */ + 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); + + }, + + /** + * Moves the Body backwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveBackward + * @param {number} speed - The speed at which it should move backwards. + */ + 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)); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrust + * @param {number} speed - The speed at which it should thrust. + */ + 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); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustLeft + * @param {number} speed - The speed at which it should move to the left. + */ + thrustLeft: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] += magnitude * Math.cos(angle); + this.data.force[1] += magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustRight + * @param {number} speed - The speed at which it should move to the right. + */ + thrustRight: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] -= magnitude * Math.cos(angle); + this.data.force[1] -= magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#reverse + * @param {number} speed - The speed at which it should reverse. + */ + 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); + + }, + + /** + * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveLeft + * @param {number} speed - The speed at which it should move to the left, in pixels per second. + */ + moveLeft: function (speed) { + + this.data.velocity[0] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveRight + * @param {number} speed - The speed at which it should move to the right, in pixels per second. + */ + moveRight: function (speed) { + + this.data.velocity[0] = this.world.pxmi(speed); + + }, + + /** + * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveUp + * @param {number} speed - The speed at which it should move up, in pixels per second. + */ + moveUp: function (speed) { + + this.data.velocity[1] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveDown + * @param {number} speed - The speed at which it should move down, in pixels per second. + */ + moveDown: function (speed) { + + this.data.velocity[1] = this.world.pxmi(speed); + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#preUpdate + * @protected + */ + preUpdate: function () { + + this.dirty = true; + + if (this.removeNextStep) + { + this.removeFromWorld(); + this.removeNextStep = false; + } + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#postUpdate + * @protected + */ + postUpdate: function () { + + this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x; + this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y; + + if (!this.fixedRotation) + { + this.sprite.rotation = this.data.angle; + } + + if (this.debugBody) + { + this.debugBody.updateSpriteTransform(); + } + + this.dirty = false; + + }, + + /** + * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. + * + * @method Phaser.Physics.P2.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new x position of the Body. + * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. + * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. + */ + reset: function (x, y, resetDamping, resetMass) { + + if (resetDamping === undefined) { resetDamping = false; } + if (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; + + }, + + /** + * Adds this physics body to the world. + * + * @method Phaser.Physics.P2.Body#addToWorld + */ + addToWorld: function () { + + if (this.game.physics.p2._toRemove) + { + for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) + { + if (this.game.physics.p2._toRemove[i] === this) + { + this.game.physics.p2._toRemove.splice(i, 1); + } + } + } + + if (this.data.world !== this.game.physics.p2.world) + { + this.game.physics.p2.addBody(this); + } + + }, + + /** + * Removes this physics body from the world. + * + * @method Phaser.Physics.P2.Body#removeFromWorld + */ + removeFromWorld: function () { + + if (this.data.world === this.game.physics.p2.world) + { + this.game.physics.p2.removeBodyNextStep(this); + } + + }, + + /** + * Destroys this Body and all references it holds to other objects. + * + * @method Phaser.Physics.P2.Body#destroy + */ + destroy: function () { + + this.removeFromWorld(); + + this.clearShapes(); + + this._bodyCallbacks = {}; + this._bodyCallbackContext = {}; + this._groupCallbacks = {}; + this._groupCallbackContext = {}; + + if (this.debugBody) + { + this.debugBody.destroy(true, true); + } + + this.debugBody = null; + + if (this.sprite) + { + this.sprite.body = null; + this.sprite = null; + } + + }, + + /** + * Removes all Shapes from this Body. + * + * @method Phaser.Physics.P2.Body#clearShapes + */ + clearShapes: function () { + + var i = this.data.shapes.length; + + while (i--) + { + this.data.removeShape(this.data.shapes[i]); + } + + this.shapeChanged(); + + }, + + /** + * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#addShape + + * @param {p2.Shape} shape - The shape to add to the body. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Shape} The shape that was added to the body. + */ + addShape: function (shape, offsetX, offsetY, rotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (rotation === undefined) { rotation = 0; } + + this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); + this.shapeChanged(); + + return shape; + + }, + + /** + * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Circle} The Circle shape that was added to the Body. + */ + addCircle: function (radius, offsetX, offsetY, rotation) { + + var shape = new p2.Circle({ radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addRectangle + * @param {number} width - The width of the rectangle in pixels. + * @param {number} height - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Box} The shape that was added to the Body. + */ + addRectangle: function (width, height, offsetX, offsetY, rotation) { + + var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addPlane + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Plane} The Plane shape that was added to the Body. + */ + addPlane: function (offsetX, offsetY, rotation) { + + var shape = new p2.Plane(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addParticle + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Particle} The Particle shape that was added to the Body. + */ + addParticle: function (offsetX, offsetY, rotation) { + + var shape = new p2.Particle(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Line shape to this Body. + * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addLine + * @param {number} length - The length of this line (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Line} The Line shape that was added to the Body. + */ + addLine: function (length, offsetX, offsetY, rotation) { + + var shape = new p2.Line({ length: this.world.pxm(length)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Capsule shape to this Body. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCapsule + * @param {number} length - The distance between the end points in pixels. + * @param {number} radius - Radius of the capsule in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Capsule} The Capsule shape that was added to the Body. + */ + addCapsule: function (length, radius, offsetX, offsetY, rotation) { + + var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. + * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. + * + * @method Phaser.Physics.P2.Body#addPolygon + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...]. In the first form **the array will mutate**. + * Or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {boolean} True on success, else false. + */ + addPolygon: function (options, points) { + + options = options || {}; + + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments, 1); + } + + var path = []; + + // Did they pass in a single array of points? + if (points.length === 1 && Array.isArray(points[0])) + { + path = points[0].slice(0); + } + else if (Array.isArray(points[0])) + { + path = points.slice(); + } + else if (typeof points[0] === 'number') + { + // We've a list of numbers + for (var i = 0, len = points.length; i < len; i += 2) + { + path.push([points[i], points[i + 1]]); + } + } + + // top and tail + var idx = path.length - 1; + + if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) + { + path.pop(); + } + + // Now process them into p2 values + for (var p = 0; p < path.length; p++) + { + path[p][0] = this.world.pxmi(path[p][0]); + path[p][1] = this.world.pxmi(path[p][1]); + } + + var result = this.data.fromPolygon(path, options); + + this.shapeChanged(); + + return result; + + }, + + /** + * Remove a shape from the body. Will automatically update the mass properties and bounding radius. + * + * @method Phaser.Physics.P2.Body#removeShape + * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. + * @return {boolean} True if the shape was found and removed, else false. + */ + removeShape: function (shape) { + + var result = this.data.removeShape(shape); + + this.shapeChanged(); + + return result; + }, + + /** + * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + */ + setCircle: function (radius, offsetX, offsetY, rotation) { + + this.clearShapes(); + + return this.addCircle(radius, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. + * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangle + * @param {number} [width=16] - The width of the rectangle in pixels. + * @param {number} [height=16] - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangle: function (width, height, offsetX, offsetY, rotation) { + + if (width === undefined) { width = 16; } + if (height === undefined) { height = 16; } + + this.clearShapes(); + + return this.addRectangle(width, height, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. + * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. + * If no Sprite is given it defaults to using the parent of this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangleFromSprite + * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangleFromSprite: function (sprite) { + + if (sprite === undefined) { sprite = this.sprite; } + + this.clearShapes(); + + return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); + + }, + + /** + * Adds the given Material to all Shapes that belong to this Body. + * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. + * + * @method Phaser.Physics.P2.Body#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. + */ + setMaterial: function (material, shape) { + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].material = material; + } + } + else + { + shape.material = material; + } + + }, + + /** + * Updates the debug draw if any body shapes change. + * + * @method Phaser.Physics.P2.Body#shapeChanged + */ + shapeChanged: function() { + + if (this.debugBody) + { + this.debugBody.draw(); + } + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * The shape data format is based on the output of the + * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for + * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor} + * + * @method Phaser.Physics.P2.Body#addPhaserPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. + * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. + * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList + */ + addPhaserPolygon: function (key, object) { + + var data = this.game.cache.getPhysicsData(key, object); + var createdFixtures = []; + + // Cycle through the fixtures + for (var i = 0; i < data.length; i++) + { + var fixtureData = data[i]; + var shapesOfFixture = this.addFixture(fixtureData); + + // Always add to a group + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); + + // if (unique) fixture key is provided + if (fixtureData.fixtureKey) + { + createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; + } + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return createdFixtures; + + }, + + /** + * Add a polygon fixture. This is used during #loadPolygon. + * + * @method Phaser.Physics.P2.Body#addFixture + * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. + * @return {array} An array containing the generated shapes for the given polygon. + */ + addFixture: function (fixtureData) { + + var generatedShapes = []; + + if (fixtureData.circle) + { + var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) }); + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + var offset = p2.vec2.create(); + offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); + offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); + + this.data.addShape(shape, offset); + generatedShapes.push(shape); + } + else + { + var polygons = fixtureData.polygons; + var cm = p2.vec2.create(); + + for (var i = 0; i < polygons.length; i++) + { + var shapes = polygons[i]; + var vertices = []; + + for (var s = 0; s < shapes.length; s += 2) + { + vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); + } + + var shape = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== shape.vertices.length; j++) + { + var v = shape.vertices[j]; + p2.vec2.sub(v, v, shape.centerOfMass); + } + + p2.vec2.scale(cm, shape.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + shape.updateTriangles(); + shape.updateCenterOfMass(); + shape.updateBoundingRadius(); + + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + this.data.addShape(shape, cm); + + generatedShapes.push(shape); + } + } + + return generatedShapes; + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * + * As well as reading the data from the Cache you can also pass `null` as the first argument and a + * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance. + * + * For more details see the format of the Lime / Corona Physics Editor export. + * + * @method Phaser.Physics.P2.Body#loadPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the + * data as the 2nd argument. + * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from, + * or if key is null pass the actual physics data object itself as this parameter. + * @param {number} [scale=1] - Optionally resize the loaded polygon. + * @return {boolean} True on success, else false. + */ + loadPolygon: function (key, object, scale) { + + if (key === null) + { + var data = object; + } + else + { + var data = this.game.cache.getPhysicsData(key, object); + } + + if (typeof scale !== "number") + { + scale = 1; + } + + // We've multiple Convex shapes, they should be CCW automatically + var cm = p2.vec2.create(); + + for (var i = 0; i < data.length; i++) + { + var vertices = []; + + for (var s = 0; s < data[i].shape.length; s += 2) + { + vertices.push([ + this.world.pxmi(data[i].shape[s] * scale), + this.world.pxmi(data[i].shape[s + 1] * scale) + ]); + } + + var c = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== c.vertices.length; j++) + { + var v = c.vertices[j]; + p2.vec2.sub(v, v, c.centerOfMass); + } + + p2.vec2.scale(cm, c.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + c.updateTriangles(); + c.updateCenterOfMass(); + c.updateBoundingRadius(); + + this.data.addShape(c, cm); + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return true; + + } + +}; + +Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; + +/** + * Dynamic body. Dynamic bodies body can move and respond to collisions and forces. + * @property DYNAMIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.DYNAMIC = 1; + +/** + * Static body. Static bodies do not move, and they do not respond to forces or collision. + * @property STATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.STATIC = 2; + +/** + * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. + * @property KINEMATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.KINEMATIC = 4; + +/** +* @name Phaser.Physics.P2.Body#static +* @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.STATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#dynamic +* @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#kinematic +* @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.KINEMATIC; + this.mass = 4; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#allowSleep +* @property {boolean} allowSleep - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { + + get: function () { + + return this.data.allowSleep; + + }, + + set: function (value) { + + if (value !== this.data.allowSleep) + { + this.data.allowSleep = value; + } + + } + +}); + +/** +* The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. +* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. +* If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#angle +* @property {number} angle - The angle of this Body in degrees. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); + + }, + + set: function(value) { + + this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#angularDamping +* @property {number} angularDamping - The angular damping acting acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { + + get: function () { + + return this.data.angularDamping; + + }, + + set: function (value) { + + this.data.angularDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularForce +* @property {number} angularForce - The angular force acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { + + get: function () { + + return this.data.angularForce; + + }, + + set: function (value) { + + this.data.angularForce = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularVelocity +* @property {number} angularVelocity - The angular velocity of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { + + get: function () { + + return this.data.angularVelocity; + + }, + + set: function (value) { + + this.data.angularVelocity = value; + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#damping +* @property {number} damping - The linear damping acting on the body in the velocity direction. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { + + get: function () { + + return this.data.damping; + + }, + + set: function (value) { + + this.data.damping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#fixedRotation +* @property {boolean} fixedRotation - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { + + get: function () { + + return this.data.fixedRotation; + + }, + + set: function (value) { + + if (value !== this.data.fixedRotation) + { + this.data.fixedRotation = value; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#inertia +* @property {number} inertia - The inertia of the body around the Z axis.. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { + + get: function () { + + return this.data.inertia; + + }, + + set: function (value) { + + this.data.inertia = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#mass +* @property {number} mass - The mass of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { + + get: function () { + + return this.data.mass; + + }, + + set: function (value) { + + if (value !== this.data.mass) + { + this.data.mass = value; + this.data.updateMassProperties(); + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#motionState +* @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { + + get: function () { + + return this.data.type; + + }, + + set: function (value) { + + if (value !== this.data.type) + { + this.data.type = value; + } + + } + +}); + +/** +* The angle of the Body in radians. +* If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#rotation +* @property {number} rotation - The angle of this Body in radians. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { + + get: function() { + + return this.data.angle; + + }, + + set: function(value) { + + this.data.angle = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#sleepSpeedLimit +* @property {number} sleepSpeedLimit - . +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { + + get: function () { + + return this.data.sleepSpeedLimit; + + }, + + set: function (value) { + + this.data.sleepSpeedLimit = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#x +* @property {number} x - The x coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.data.position[0]); + + }, + + set: function (value) { + + this.data.position[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#y +* @property {number} y - The y coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.data.position[1]); + + }, + + set: function (value) { + + this.data.position[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#id +* @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { + + get: function () { + + return this.data.id; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#debug +* @property {boolean} debug - Enable or disable debug drawing of this body +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { + + get: function () { + + return (this.debugBody !== null); + + }, + + set: function (value) { + + if (value && !this.debugBody) + { + // This will be added to the global space + this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); + } + else if (!value && this.debugBody) + { + this.debugBody.destroy(); + this.debugBody = null; + } + + } + +}); + +/** +* A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. +* Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. +* Also note that when you set this it will only affect Body shapes that already exist. If you then add further shapes to your Body +* after setting this it will *not* proactively set them to collide with the bounds. +* +* @name Phaser.Physics.P2.Body#collideWorldBounds +* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? +* @default true +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { + + get: function () { + + return this._collideWorldBounds; + + }, + + set: function (value) { + + if (value && !this._collideWorldBounds) + { + this._collideWorldBounds = true; + this.updateCollisionMask(); + } + else if (!value && this._collideWorldBounds) + { + this._collideWorldBounds = false; + this.updateCollisionMask(); + } + + } + +}); + +/** +* @author George https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Draws a P2 Body to a Graphics instance for visual debugging. +* Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. +* So use sparingly and rarely (if ever) in production code. +* +* Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you +* manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will +* need to manually adjust its BodyDebug as well. +* +* @class Phaser.Physics.P2.BodyDebug +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. +* @param {object} settings - Settings object. +*/ +Phaser.Physics.P2.BodyDebug = function(game, body, settings) { + + Phaser.Group.call(this, game); + + /** + * @property {object} defaultSettings - Default debug settings. + * @private + */ + var defaultSettings = { + pixelsPerLengthUnit: game.physics.p2.mpx(1), + debugPolygons: false, + lineWidth: 1, + alpha: 0.5 + }; + + this.settings = Object.assign(defaultSettings, settings); + + /** + * @property {number} ppu - Pixels per Length Unit. + */ + this.ppu = this.settings.pixelsPerLengthUnit; + this.ppu = -1 * this.ppu; + + /** + * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. + */ + this.body = body; + + /** + * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. + */ + this.canvas = new Phaser.Graphics(game); + + this.canvas.alpha = this.settings.alpha; + + this.add(this.canvas); + + this.draw(); + + this.updateSpriteTransform(); + +}; + +Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); +Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; + +Object.assign(Phaser.Physics.P2.BodyDebug.prototype, { + + /** + * Core update. + * + * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform + */ + updateSpriteTransform: function() { + + this.position.x = this.body.position[0] * this.ppu; + this.position.y = this.body.position[1] * this.ppu; + this.rotation = this.body.angle; + + }, + + /** + * Draws the P2 shapes to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#draw + */ + draw: function() { + + var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; + + obj = this.body; + sprite = this.canvas; + sprite.clear(); + color = parseInt(this.randomPastelHex(), 16); + lineColor = 0xff0000; + lw = this.lineWidth; + + if (obj instanceof p2.Body && obj.shapes.length) + { + var l = obj.shapes.length; + + i = 0; + + while (i !== l) + { + child = obj.shapes[i]; + offset = child.position || 0; + angle = child.angle || 0; + + if (child instanceof p2.Circle) + { + this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); + } + else if (child instanceof p2.Capsule) + { + this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw); + } + 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.Box) + { + this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); + } + else if (child instanceof p2.Convex) + { + verts = []; + vrot = p2.vec2.create(); + + for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _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]); + } + + i++; + } + } + + }, + + /** + * Draws a p2.Box to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawRectangle + * @private + */ + drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + g.beginFill(fillColor); + g.drawRect(x - w / 2, y - h / 2, w, h); + + }, + + /** + * Draws a p2.Circle to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCircle + * @private + */ + drawCircle: function(g, x, y, angle, radius, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + g.lineStyle(lineWidth, 0x000000, 1); + g.beginFill(color, 1.0); + g.drawCircle(x, y, -radius*2); + g.endFill(); + g.moveTo(x, y); + g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); + + }, + + /** + * Draws a p2.Line to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawLine + * @private + */ + drawLine: function(g, len, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth * 5, color, 1); + g.moveTo(-len / 2, 0); + g.lineTo(len / 2, 0); + + }, + + /** + * Draws a p2.Convex to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawConvex + * @private + */ + drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { + + var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + 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 = [0xff0000, 0x00ff00, 0x0000ff]; + 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, 0x000000, 1); + return g.drawCircle(offset[0], offset[1], lineWidth * 2); + } + + }, + + /** + * Draws a p2.Path to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPath + * @private + */ + drawPath: function(g, path, color, fillColor, lineWidth) { + + var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + if (typeof fillColor === "number") + { + g.beginFill(fillColor); + } + + lastx = null; + lasty = null; + i = 0; + + while (i < path.length) + { + v = path[i]; + x = v[0]; + y = v[1]; + + if (x !== lastx || y !== lasty) + { + if (i === 0) + { + g.moveTo(x, y); + } + else + { + p1x = lastx; + p1y = lasty; + p2x = x; + p2y = y; + p3x = path[(i + 1) % path.length][0]; + p3y = path[(i + 1) % path.length][1]; + area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); + + if (area !== 0) + { + g.lineTo(x, y); + } + } + lastx = x; + lasty = y; + } + + i++; + + } + + if (typeof fillColor === "number") + { + g.endFill(); + } + + if (path.length > 2 && typeof fillColor === "number") + { + g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); + g.lineTo(path[0][0], path[0][1]); + } + + }, + + /** + * Draws a p2.Plane to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPlane + * @private + */ + drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { + + var max, xd, yd; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + + 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); + + }, + + /** + * Draws a p2.Capsule to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCapsule + * @private + */ + drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + // Draw circles at ends + var c = Math.cos(angle); + var s = Math.sin(angle); + + g.beginFill(fillColor, 1); + g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2); + g.drawCircle( len/2*c + x, len/2*s + y, -radius * 2); + g.endFill(); + + // Draw rectangle + g.lineStyle(lineWidth, color, 0); + g.beginFill(fillColor, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.endFill(); + + // Draw lines in between + g.lineStyle(lineWidth, color, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + + }, + + /** + * Picks a random pastel color. + * + * @method Phaser.Physics.P2.BodyDebug#randomPastelHex + * @private + */ + 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); + + }, + + /** + * Converts from RGB to Hex. + * + * @method Phaser.Physics.P2.BodyDebug#rgbToHex + * @private + */ + rgbToHex: function(r, g, b) { + return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); + }, + + /** + * Component to hex conversion. + * + * @method Phaser.Physics.P2.BodyDebug#componentToHex + * @private + */ + componentToHex: function(c) { + + var hex; + hex = c.toString(16); + + if (hex.length === 2) + { + return hex; + } + else + { + return hex + '0'; + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.Spring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restLength=1] - Rest length of the spring. A number > 0. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +*/ +Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restLength === undefined) { restLength = 1; } + if (stiffness === undefined) { stiffness = 100; } + if (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]) ]; + } + + /** + * @property {p2.LinearSpring} data - The actual p2 spring object. + */ + this.data = new p2.LinearSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.RotationalSpring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +*/ +Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restAngle === undefined) { restAngle = null; } + if (stiffness === undefined) { stiffness = 100; } + if (damping === undefined) { damping = 1; } + + if (restAngle) + { + restAngle = world.pxm(restAngle); + } + + var options = { + restAngle: restAngle, + stiffness: stiffness, + damping: damping + }; + + /** + * @property {p2.RotationalSpring} data - The actual p2 spring object. + */ + this.data = new p2.RotationalSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A P2 Material. +* +* \o/ ~ "Because I'm a Material girl" +* +* @class Phaser.Physics.P2.Material +* @constructor +* @param {string} name - The user defined name given to this Material. +*/ +Phaser.Physics.P2.Material = function (name) { + + /** + * @property {string} name - The user defined name given to this Material. + * @default + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Defines a physics material +* +* @class Phaser.Physics.P2.ContactMaterial +* @constructor +* @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. +* @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. +* @param {object} [options] - Additional configuration options. +*/ +Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { + + /** + * @property {number} id - The contact material identifier. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. + */ + + /** + * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. + */ + + /** + * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. + */ + + /** + * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + */ + + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Collision Group +* +* @class Phaser.Physics.P2.CollisionGroup +* @constructor +* @param {number} bitmask - The CollisionGroup bitmask. +*/ +Phaser.Physics.P2.CollisionGroup = function (bitmask) { + + /** + * @property {number} mask - The CollisionGroup bitmask. + */ + this.mask = bitmask; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A constraint that tries to keep the distance between two bodies constant. +* +* @class Phaser.Physics.P2.DistanceConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} distance - The distance to keep between the bodies. +* @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. +* @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. +* @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply. +*/ +Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { + + if (distance === undefined) { distance = 100; } + if (localAnchorA === undefined) { localAnchorA = [0, 0]; } + if (localAnchorB === undefined) { localAnchorB = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + distance = world.pxm(distance); + + localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ]; + localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ]; + + var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce }; + + p2.DistanceConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); +Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.GearConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [angle=0] - The relative angle +* @param {number} [ratio=1] - The gear ratio. +*/ +Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { + + if (angle === undefined) { angle = 0; } + if (ratio === undefined) { ratio = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Locks the relative position between two bodies. +* +* @class Phaser.Physics.P2.LockConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [angle=0] - The angle of bodyB in bodyA's frame. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { + + if (offset === undefined) { offset = [0, 0]; } + if (angle === undefined) { angle = 0; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.PrismaticConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. +* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { + + if (lockRotation === undefined) { lockRotation = true; } + if (anchorA === undefined) { anchorA = [0, 0]; } + if (anchorB === undefined) { anchorB = [0, 0]; } + if (axis === undefined) { axis = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* The pivot points are given in world (pixel) coordinates. +* +* @class Phaser.Physics.P2.RevoluteConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {p2.Body} bodyB - Second connected body. +* @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. +* @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. +*/ +Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + if (worldPivot === undefined) { worldPivot = null; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; + pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; + + if (worldPivot) + { + worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ]; + } + + var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce }; + + p2.RevoluteConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); +Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image Collection is a special tileset containing mulitple images, with no slicing into each image. +* +* Image Collections are normally created automatically when Tiled data is loaded. +* +* @class Phaser.ImageCollection +* @constructor +* @param {string} name - The name of the image collection in the map data. +* @param {integer} firstgid - The first image index this image collection contains. +* @param {integer} [width=32] - Width of widest image (in pixels). +* @param {integer} [height=32] - Height of tallest image (in pixels). +* @param {integer} [margin=0] - The margin around all images in the collection (in pixels). +* @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). +* @param {object} [properties={}] - Custom Image Collection properties. +*/ +Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Image Collection. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of the widest image (in pixels). + * @property {integer} imageWidth + * @readonly + */ + this.imageWidth = width | 0; + + /** + * The height of the tallest image (in pixels). + * @property {integer} imageHeight + * @readonly + */ + this.imageHeight = height | 0; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageMarge + * @readonly + */ + // Modified internally + this.imageMargin = margin | 0; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageSpacing + * @readonly + */ + this.imageSpacing = spacing | 0; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached images that are a part of this collection. + * @property {array} images + * @readonly + */ + // Modified internally + this.images = []; + + /** + * The total number of images in the image collection. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; +}; + +Phaser.ImageCollection.prototype = { + + /** + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.ImageCollection#containsImageIndex + * @param {integer} imageIndex - The image index to search for. + * @return {boolean} True if this Image Collection contains the given index. + */ + containsImageIndex: function (imageIndex) { + + return ( + imageIndex >= this.firstgid && + imageIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Add an image to this Image Collection. + * + * @method Phaser.ImageCollection#addImage + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + */ + addImage: function (gid, image) { + + this.images.push({ gid: gid, image: image }); + this.total++; + + } + +}; + +Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile is a representation of a single tile within the Tilemap. +* +* @class Phaser.Tile +* @constructor +* @param {object} layer - The layer in the Tilemap data that this tile belongs to. +* @param {number} index - The index of this tile type in the core map data. +* @param {number} x - The x coordinate of this tile. +* @param {number} y - The y coordinate of this tile. +* @param {number} width - Width of the tile. +* @param {number} height - Height of the tile. +*/ +Phaser.Tile = function (layer, index, x, y, width, height) { + + /** + * @property {object} layer - The layer in the Tilemap data that this tile belongs to. + */ + this.layer = layer; + + /** + * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. + */ + this.index = index; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.x = x; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.y = y; + + /** + * @property {number} rotation - The rotation angle of this tile. + */ + this.rotation = 0; + + /** + * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not. + */ + this.flipped = false; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.worldX = x * width; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.worldY = y * height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.height = height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.centerX = Math.abs(width / 2); + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.centerY = Math.abs(height / 2); + + /** + * @property {number} alpha - The alpha value at which this tile is drawn to the canvas. + */ + this.alpha = 1; + + /** + * @property {object} properties - Tile specific properties. + */ + this.properties = {}; + + /** + * @property {boolean} scanned - Has this tile been walked / turned into a poly? + */ + this.scanned = false; + + /** + * @property {boolean} faceTop - Is the top of this tile an interesting edge? + */ + this.faceTop = false; + + /** + * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge? + */ + this.faceBottom = false; + + /** + * @property {boolean} faceLeft - Is the left of this tile an interesting edge? + */ + this.faceLeft = false; + + /** + * @property {boolean} faceRight - Is the right of this tile an interesting edge? + */ + this.faceRight = false; + + /** + * @property {boolean} collideLeft - Indicating collide with any object on the left. + * @default + */ + this.collideLeft = false; + + /** + * @property {boolean} collideRight - Indicating collide with any object on the right. + * @default + */ + this.collideRight = false; + + /** + * @property {boolean} collideUp - Indicating collide with any object on the top. + * @default + */ + this.collideUp = false; + + /** + * @property {boolean} collideDown - Indicating collide with any object on the bottom. + * @default + */ + this.collideDown = false; + + /** + * @property {function} collisionCallback - Tile collision callback. + * @default + */ + this.collisionCallback = null; + + /** + * @property {object} collisionCallbackContext - The context in which the collision callback will be called. + * @default + */ + this.collisionCallbackContext = this; + + /** + * @property {boolean} debug + * @default + */ + this.debug = false; + +}; + +Phaser.Tile.prototype = { + + /** + * Check if the given x and y world coordinates are within this Tile. + * + * @method Phaser.Tile#containsPoint + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ + containsPoint: function (x, y) { + + return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom); + + }, + + /** + * Check for intersection with this tile. + * + * @method Phaser.Tile#intersects + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + */ + 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; + + }, + + /** + * Set a callback to be called when this tile is hit by an object. + * The callback must true true for collision processing to take place. + * + * @method Phaser.Tile#setCollisionCallback + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + */ + setCollisionCallback: function (callback, context) { + + this.collisionCallback = callback; + this.collisionCallbackContext = context; + + }, + + /** + * Clean up memory. + * + * @method Phaser.Tile#destroy + */ + destroy: function () { + + this.collisionCallback = null; + this.collisionCallbackContext = null; + this.properties = null; + + }, + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tile#setCollision + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} right - Indicating collide with any object on the right. + * @param {boolean} up - Indicating collide with any object on the top. + * @param {boolean} down - Indicating collide with any object on the bottom. + */ + setCollision: function (left, right, up, down) { + + this.collideLeft = left; + this.collideRight = right; + this.collideUp = up; + this.collideDown = down; + + this.faceLeft = left; + this.faceRight = right; + this.faceTop = up; + this.faceBottom = down; + + }, + + /** + * Reset collision status flags. + * + * @method Phaser.Tile#resetCollision + */ + 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; + + }, + + /** + * Is this tile interesting? + * + * @method Phaser.Tile#isInteresting + * @param {boolean} collides - If true will check any collides value. + * @param {boolean} faces - If true will check any face value. + * @return {boolean} True if the Tile is interesting, otherwise false. + */ + isInteresting: function (collides, faces) { + + if (collides && faces) + { + // Does this tile have any collide flags OR interesting face? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback); + } + else if (collides) + { + // Does this tile collide? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + else if (faces) + { + // Does this tile have an interesting face? + return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); + } + + return false; + + }, + + /** + * Copies the tile data and properties from the given tile to this tile. + * + * @method Phaser.Tile#copy + * @param {Phaser.Tile} tile - The tile to copy from. + */ + 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; + +/** +* @name Phaser.Tile#collides +* @property {boolean} collides - True if this tile can collide on any of its faces. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "collides", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + +}); + +/** +* @name Phaser.Tile#canCollide +* @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "canCollide", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); + } + +}); + +/** +* @name Phaser.Tile#left +* @property {number} left - The x value in pixels. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "left", { + + get: function () { + return this.worldX; + } + +}); + +/** +* @name Phaser.Tile#right +* @property {number} right - The sum of the x and width properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "right", { + + get: function () { + return this.worldX + this.width; + } + +}); + +/** +* @name Phaser.Tile#top +* @property {number} top - The y value. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "top", { + + get: function () { + return this.worldY; + } + +}); + +/** +* @name Phaser.Tile#bottom +* @property {number} bottom - The sum of the y and height properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "bottom", { + + get: function () { + return this.worldY + this.height; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. +* +* Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org +* +* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. +* When using CSV data you must provide the key and the tileWidth and tileHeight parameters. +* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. +* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. +* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. +* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. +* +* @class Phaser.Tilemap +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. +* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +*/ +Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {string} key - The key of this map data in the Phaser.Cache. + */ + this.key = key; + + var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height); + + if (data === null) + { + return; + } + + /** + * @property {number} width - The width of the map (in tiles). + */ + this.width = data.width; + + /** + * @property {number} height - The height of the map (in tiles). + */ + this.height = data.height; + + /** + * @property {number} tileWidth - The base width of the tiles in the map (in pixels). + */ + this.tileWidth = data.tileWidth; + + /** + * @property {number} tileHeight - The base height of the tiles in the map (in pixels). + */ + this.tileHeight = data.tileHeight; + + /** + * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + */ + this.orientation = data.orientation; + + /** + * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + */ + this.format = data.format; + + /** + * @property {number} version - The version of the map data (as specified in Tiled, usually 1). + */ + this.version = data.version; + + /** + * @property {object} properties - Map specific properties as specified in Tiled. + */ + this.properties = data.properties; + + /** + * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth. + */ + this.widthInPixels = data.widthInPixels; + + /** + * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight. + */ + this.heightInPixels = data.heightInPixels; + + /** + * @property {array} layers - An array of Tilemap layer data. + */ + this.layers = data.layers; + + /** + * @property {array} tilesets - An array of Tilesets. + */ + this.tilesets = data.tilesets; + + /** + * @property {array} imagecollections - An array of Image Collections. + */ + this.imagecollections = data.imagecollections; + + /** + * @property {array} tiles - The super array of Tiles. + */ + this.tiles = data.tiles; + + /** + * @property {array} objects - An array of Tiled Object Layers. + */ + this.objects = data.objects; + + /** + * @property {array} collideIndexes - An array of tile indexes that collide. + */ + this.collideIndexes = []; + + /** + * @property {array} collision - An array of collision data (polylines, etc). + */ + this.collision = data.collision; + + /** + * @property {array} images - An array of Tiled Image Layers. + */ + this.images = data.images; + + /** + * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data. + */ + this.enableDebug = false; + + /** + * @property {number} currentLayer - The current layer. + */ + this.currentLayer = 0; + + /** + * @property {array} debugMap - Map data used for debug values only. + */ + this.debugMap = []; + + /** + * @property {array} _results - Internal var. + * @private + */ + this._results = []; + + /** + * @property {number} _tempA - Internal var. + * @private + */ + this._tempA = 0; + + /** + * @property {number} _tempB - Internal var. + * @private + */ + this._tempB = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.CSV = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.TILED_JSON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.NORTH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.EAST = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.SOUTH = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.WEST = 3; + +Phaser.Tilemap.prototype = { + + /** + * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. + * + * @method Phaser.Tilemap#create + * @param {string} name - The name of the default layer of the map. + * @param {number} width - The width of the map in tiles. + * @param {number} height - The height of the map in tiles. + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + create: function (name, width, height, tileWidth, tileHeight, group) { + + if (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); + + }, + + /** + * Sets the base tile size for the map. + * + * @method Phaser.Tilemap#setTileSize + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + */ + setTileSize: function (tileWidth, tileHeight) { + + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.widthInPixels = this.width * tileWidth; + this.heightInPixels = this.height * tileHeight; + + }, + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. + * + * @method Phaser.Tilemap#addTilesetImage + * @param {string} tileset - The name of the tileset as specified in the map data. + * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset. + * If `undefined` or `null` it will look for an image with a key matching the tileset parameter. + * You can also pass in a BitmapData which can be used instead of an Image. + * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. + * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. + * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. + * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. + * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. + * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed. + */ + addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { + + if (tileset === undefined) { return null; } + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (gid === undefined) { gid = 0; } + + // In-case we're working from a blank map + if (tileWidth === 0) + { + tileWidth = 32; + } + + if (tileHeight === 0) + { + tileHeight = 32; + } + + var img = null; + + if (key === undefined || key === null) + { + key = tileset; + } + + if (key instanceof Phaser.BitmapData) + { + img = key.canvas; + } + else + { + if (!this.game.cache.checkImageKey(key)) + { + console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"'); + return null; + } + + img = this.game.cache.getImage(key); + } + + var idx = this.getTilesetIndex(tileset); + + if (idx === null && this.format === Phaser.Tilemap.TILED_JSON) + { + console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + tileset + '"'); + console.log('Tilesets: ', this.tilesets); + return null; + } + + if (this.tilesets[idx]) + { + this.tilesets[idx].setImage(img); + return this.tilesets[idx]; + } + else + { + var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {}); + + newSet.setImage(img); + + 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; t < gid + newSet.total; t++) + { + this.tiles[t] = [x, y, i]; + + x += tileWidth + tileSpacing; + + count++; + + if (count === newSet.total) + { + break; + } + + countX++; + + if (countX === newSet.columns) + { + x = tileMargin; + y += tileHeight + tileSpacing; + + countX = 0; + countY++; + + if (countY === newSet.rows) + { + break; + } + } + } + + return newSet; + + } + + return null; + + }, + + /** + * Creates a Sprite for every {@link http://doc.mapeditor.org/reference/tmx-map-format/#object object} matching the `gid` argument. You can optionally specify the group that the Sprite will be created in. If none is + * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to + * configure Sprite properties from within the map editor. For example giving an object a property of `alpha: 0.5` in the map editor will duplicate that when the + * Sprite is created. You could also give it a value like: `body.velocity.x: 100` to set it moving automatically. + * + * The `gid` argument is matched against: + * + * 1. For a tile object, the tile identifier (`gid`); or + * 2. The object's unique ID (`id`); or + * 3. The object's `name` (a string) + * + * @method Phaser.Tilemap#createFromObjects + * @param {string} name - The name of the Object Group to create Sprites from. + * @param {number|string} gid - The object's tile reference (gid), unique ID (id) or name. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. + * @param {boolean} [exists=true] - The default exists state of the Sprite. + * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. + * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. + * @param {boolean} [adjustSize=true] - By default the width and height of the objects are transferred to the sprite. This parameter controls that behavior. + */ + createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY, adjustSize) { + + if (exists === undefined) { exists = true; } + if (autoCull === undefined) { autoCull = false; } + if (group === undefined) { group = this.game.world; } + if (CustomClass === undefined) { CustomClass = Phaser.Sprite; } + if (adjustY === undefined) { adjustY = true; } + if (adjustSize === undefined) { adjustSize = true; } + + if (!this.objects[name]) + { + console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name); + console.log('Objects: ', this.objects); + return; + } + + for (var i = 0; i < this.objects[name].length; i++) + { + var found = false; + var obj = this.objects[name][i]; + + if (obj.gid !== undefined && typeof gid === 'number' && obj.gid === gid) + { + found = true; + } + else if (obj.id !== undefined && typeof gid === 'number' && obj.id === gid) + { + found = true; + } + else if (obj.name !== undefined && typeof gid === 'string' && obj.name === gid) + { + found = true; + } + + if (found) + { + var sprite = new CustomClass(this.game, parseFloat(obj.x, 10), parseFloat(obj.y, 10), key, frame); + + sprite.name = obj.name; + sprite.autoCull = autoCull; + sprite.exists = exists; + sprite.visible = obj.visible; + + if (adjustSize) + { + if (obj.width) + { + sprite.width = obj.width; + } + + if (obj.height) + { + sprite.height = obj.height; + } + } + + if (obj.rotation) + { + sprite.angle = obj.rotation; + } + + if (adjustY) + { + sprite.y -= sprite.height; + } + + group.add(sprite); + + for (var property in obj.properties) + { + group.set(sprite, property, obj.properties[property], false, false, 0, true); + } + } + } + + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the map data. + * You can specify the group that the Sprite will be created in. If none is given it will be created in the World. + * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special + * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemap#createFromTiles + * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from. + * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. + * @return {integer} The number of Sprites that were created. + */ + createFromTiles: function (tiles, replacements, key, layer, group, properties) { + + if (typeof tiles === 'number') { tiles = [tiles]; } + + if (replacements === undefined || replacements === null) + { + replacements = []; + } + else if (typeof replacements === 'number') + { + replacements = [replacements]; + } + + layer = this.getLayer(layer); + + if (group === undefined) { group = this.game.world; } + if (properties === undefined) { properties = {}; } + + if (properties.customClass === undefined) + { + properties.customClass = Phaser.Sprite; + } + + if (properties.adjustY === undefined) + { + properties.adjustY = true; + } + + var lw = this.layers[layer].width; + var lh = this.layers[layer].height; + + this.copy(0, 0, lw, lh, layer); + + if (this._results.length < 2) + { + return 0; + } + + var total = 0; + var sprite; + + for (var i = 1, len = this._results.length; i < len; i++) + { + if (tiles.indexOf(this._results[i].index) !== -1) + { + sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key); + + for (var property in properties) + { + sprite[property] = properties[property]; + } + + group.add(sprite); + total++; + } + + } + + if (replacements.length === 1) + { + // Assume 1 replacement for all types of tile given + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer); + } + } + else if (replacements.length > 1) + { + // Assume 1 for 1 mapping + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer); + } + } + + return total; + + }, + + /** + * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. + * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. + * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. + * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. + * + * @method Phaser.Tilemap#createLayer + * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. + * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. + * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. + * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. + */ + createLayer: function (layer, width, height, group) { + + // Add Buffer support for the left of the canvas + + if (width === undefined) { width = this.game.width; } + if (height === undefined) { height = this.game.height; } + if (group === undefined) { group = this.game.world; } + + var index = layer; + + if (typeof layer === 'string') + { + index = this.getLayerIndex(layer); + } + + if (index === null || index > this.layers.length) + { + console.warn('Tilemap.createLayer: Invalid layer ID given: "' + layer + '"'); + console.log('Layers: ', this.layers); + return; + } + + // Sort out the display dimensions, so they never render too much, or too little. + + if (width === undefined || width <= 0) + { + width = Math.min(this.game.width, this.layers[index].widthInPixels); + } + else if (width > this.game.width) + { + width = this.game.width; + } + + if (height === undefined || height <= 0) + { + height = Math.min(this.game.height, this.layers[index].heightInPixels); + } + else if (height > this.game.height) + { + height = this.game.height; + } + + if (this.enableDebug) + { + console.group('Tilemap.createLayer'); + console.log('Name:', this.layers[index].name); + console.log('Size:', width, 'x', height); + console.log('Tileset:', this.tilesets[0].name, 'index:', index); + } + + var rootLayer = group.add(new Phaser.TilemapLayer(this.game, this, index, width, height)); + + if (this.enableDebug) + { + console.groupEnd(); + } + + return rootLayer; + + }, + + + /** + * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. + * + * @method Phaser.Tilemap#createBlankLayer + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {number} width - The width of the layer in tiles. + * @param {number} height - The height of the layer in tiles. + * @param {number} tileWidth - The width of the tiles the layer uses for calculations. + * @param {number} tileHeight - The height of the tiles the layer uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) { + + if (group === undefined) { group = this.game.world; } + + if (this.getLayerIndex(name) !== null) + { + console.warn('Tilemap.createBlankLayer: Layer with matching name already exists: ' + name); + 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; y < height; y++) + { + row = []; + + for (var x = 0; x < width; x++) + { + row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight)); + } + + output.push(row); + } + + layer.data = output; + + this.layers.push(layer); + + this.currentLayer = this.layers.length - 1; + + var w = layer.widthInPixels; + var h = layer.heightInPixels; + + if (w > this.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); + + }, + + /** + * Gets the layer index based on the layers name. + * + * @method Phaser.Tilemap#getIndex + * @protected + * @param {array} location - The local array to search. + * @param {string} name - The name of the array element to get. + * @return {number} The index of the element in the array, or null if not found. + */ + getIndex: function (location, name) { + + for (var i = 0; i < location.length; i++) + { + if (location[i].name === name) + { + return i; + } + } + + return null; + + }, + + /** + * Gets the layer index based on its name. + * + * @method Phaser.Tilemap#getLayerIndex + * @param {string} name - The name of the layer to get. + * @return {number} The index of the layer in this tilemap, or null if not found. + */ + getLayerIndex: function (name) { + + return this.getIndex(this.layers, name); + + }, + + /** + * Gets the tileset index based on its name. + * + * @method Phaser.Tilemap#getTilesetIndex + * @param {string} name - The name of the tileset to get. + * @return {number} The index of the tileset in this tilemap, or null if not found. + */ + getTilesetIndex: function (name) { + + return this.getIndex(this.tilesets, name); + + }, + + /** + * Gets the image index based on its name. + * + * @method Phaser.Tilemap#getImageIndex + * @param {string} name - The name of the image to get. + * @return {number} The index of the image in this tilemap, or null if not found. + */ + getImageIndex: function (name) { + + return this.getIndex(this.images, name); + + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileIndexCallback + * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileIndexCallback: function (indexes, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes]; + } + else + { + // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much + // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit. + this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext }; + } + } + else + { + for (var i = 0, len = indexes.length; i < len; i++) + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes[i]]; + } + else + { + this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext }; + } + } + } + + }, + + /** + * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileLocationCallback + * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} width - The width of the area to copy (given in tiles, not pixels) + * @param {number} height - The height of the area to copy (given in tiles, not pixels) + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].setCollisionCallback(callback, callbackContext); + } + + }, + + /** + * Sets collision on the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [2, 3, 15, 20]. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * Collision-enabled tiles can be collided against Sprites using {@link Phaser.Physics.Arcade#collide}. + * + * You can verify the collision faces by enabling {@link Phaser.TilemapLayer#debug}. + * + * @method Phaser.Tilemap#setCollision + * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollision: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + return this.setCollisionByIndex(indexes, collides, layer, true); + } + else if (Array.isArray(indexes)) + { + // Collide all of the IDs given in the indexes array + for (var i = 0; i < indexes.length; i++) + { + this.setCollisionByIndex(indexes[i], collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + } + + }, + + /** + * Sets collision on a range of tiles where the tile IDs increment sequentially. + * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionBetween + * @param {number} start - The first index of the tile to be set for collision. + * @param {number} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionBetween: function (start, stop, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (start > stop) + { + return; + } + + for (var index = start; index <= stop; index++) + { + this.setCollisionByIndex(index, collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision on all tiles in the given layer, except for the IDs of those in the given array. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionByExclusion + * @param {array} indexes - An array of the tile IDs to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByExclusion: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + // Collide everything, except the IDs given in the indexes array + for (var i = 0, len = this.tiles.length; i < len; i++) + { + if (indexes.indexOf(i) === -1) + { + this.setCollisionByIndex(i, collides, layer, false); + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision values on a tile in the set. + * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. + * + * @method Phaser.Tilemap#setCollisionByIndex + * @protected + * @param {number} index - The index of the tile on the layer. + * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile. + * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByIndex: function (index, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (layer === undefined) { layer = this.currentLayer; } + if (recalculate === undefined) { recalculate = true; } + + if (collides) + { + this.collideIndexes.push(index); + } + else + { + var i = this.collideIndexes.indexOf(index); + + if (i > -1) + { + this.collideIndexes.splice(i, 1); + } + } + + for (var y = 0; y < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile && tile.index === index) + { + if (collides) + { + tile.setCollision(true, true, true, true); + } + else + { + tile.resetCollision(); + } + + tile.faceTop = collides; + tile.faceBottom = collides; + tile.faceLeft = collides; + tile.faceRight = collides; + } + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + return layer; + + }, + + /** + * Gets the TilemapLayer index as used in the setCollision calls. + * + * @method Phaser.Tilemap#getLayer + * @protected + * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer. + * @return {number} The TilemapLayer index. + */ + getLayer: function (layer) { + + if (layer === undefined) + { + layer = this.currentLayer; + } + else if (typeof layer === 'string') + { + var layerArg = layer; + + layer = this.getLayerIndex(layer); + + if (!layer) + { + console.warn('No such layer name: ' + layerArg); + } + } + else if (layer instanceof Phaser.TilemapLayer) + { + layer = layer.index; + } + + return layer; + + }, + + /** + * Turn off/on the recalculation of faces for tile or collision updates. + * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. + * + * @method Phaser.Tilemap#setPreventRecalculate + * @param {boolean} value - If true it will put the recalculation on hold. + */ + setPreventRecalculate: function (value) { + + if (value === true && this.preventingRecalculate !== true) + { + this.preventingRecalculate = true; + this.needToRecalculate = {}; + } + + if (value === false && this.preventingRecalculate === true) + { + this.preventingRecalculate = false; + + for (var i in this.needToRecalculate) + { + this.calculateFaces(i); + } + + this.needToRecalculate = false; + } + + }, + + /** + * Internal function. + * + * @method Phaser.Tilemap#calculateFaces + * @protected + * @param {number} layer - The index of the TilemapLayer to operate on. + */ + calculateFaces: function (layer) { + + if (this.preventingRecalculate) + { + this.needToRecalculate[layer] = true; + return; + } + + var above = null; + var below = null; + var left = null; + var right = null; + + for (var y = 0, h = this.layers[layer].height; y < h; y++) + { + for (var x = 0, w = this.layers[layer].width; x < w; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile) + { + above = this.getTileAbove(layer, x, y); + below = this.getTileBelow(layer, x, y); + left = this.getTileLeft(layer, x, y); + right = this.getTileRight(layer, x, y); + + if (tile.collides) + { + tile.faceTop = true; + tile.faceBottom = true; + tile.faceLeft = true; + tile.faceRight = true; + } + + if (above && above.collides) + { + // There is a tile above this one that also collides, so the top of this tile is no longer interesting + tile.faceTop = false; + } + + if (below && below.collides) + { + // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting + tile.faceBottom = false; + } + + if (left && left.collides) + { + // There is a tile left this one that also collides, so the left of this tile is no longer interesting + tile.faceLeft = false; + } + + if (right && right.collides) + { + // There is a tile right this one that also collides, so the right of this tile is no longer interesting + tile.faceRight = false; + } + } + } + } + + }, + + /** + * Gets the tile above the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileAbove + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileAbove: function (layer, x, y) { + + if (y > 0) + { + return this.layers[layer].data[y - 1][x]; + } + + return null; + + }, + + /** + * Gets the tile below the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileBelow + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileBelow: function (layer, x, y) { + + if (y < this.layers[layer].height - 1) + { + return this.layers[layer].data[y + 1][x]; + } + + return null; + + }, + + /** + * Gets the tile to the left of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileLeft + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileLeft: function (layer, x, y) { + + if (x > 0) + { + return this.layers[layer].data[y][x - 1]; + } + + return null; + + }, + + /** + * Gets the tile to the right of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileRight + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileRight: function (layer, x, y) { + + if (x < this.layers[layer].width - 1) + { + return this.layers[layer].data[y][x + 1]; + } + + return null; + + }, + + /** + * Sets the current layer to the given index. + * + * @method Phaser.Tilemap#setLayer + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + */ + setLayer: function (layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer]) + { + this.currentLayer = layer; + } + + }, + + /** + * Checks if there is a tile at the given location. + * + * @method Phaser.Tilemap#hasTile + * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels) + * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + * @return {boolean} True if there is a tile at the given location, otherwise false. + */ + hasTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined) + { + return false; + } + + return (this.layers[layer].data[y][x].index > -1); + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. + * + * @method Phaser.Tilemap#removeTile + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.hasTile(x, y, layer)) + { + var tile = this.layers[layer].data[y][x]; + + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight); + + this.layers[layer].dirty = true; + + this.calculateFaces(layer); + + return tile; + } + } + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#removeTileWorldXY + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTileWorldXY: function (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.removeTile(x, y, layer); + + }, + + /** + * Puts a tile of the given index value at the coordinate specified. + * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. + * + * @method Phaser.Tilemap#putTile + * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map. + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + putTile: function (tile, x, y, layer) { + + if (tile === null) + { + return this.removeTile(x, y, layer); + } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + var index; + + if (tile instanceof Phaser.Tile) + { + index = tile.index; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].copy(tile); + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height); + } + } + else + { + index = tile; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].index = index; + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight); + } + } + + if (this.collideIndexes.indexOf(index) > -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; + + }, + + /** + * Puts a tile into the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#putTileWorldXY + * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object. + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + 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); + + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. + * If no match is found it returns null. + * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. + * + * @method Phaser.Tilemap#searchTileIndex + * @param {number} index - The tile index value to search for. + * @param {number} [skip=0] - The number of times to skip a matching tile before returning. + * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @return {Phaser.Tile} The first (or n skipped) tile with the matching index. + */ + searchTileIndex: function (index, skip, reverse, layer) { + + if (skip === undefined) { skip = 0; } + if (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 < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + if (this.layers[layer].data[y][x].index === index) + { + if (c === skip) + { + return this.layers[layer].data[y][x]; + } + else + { + c++; + } + } + } + } + } + + return null; + + }, + + /** + * Gets a tile from the Tilemap Layer. The coordinates are given in tile values. + * + * @method Phaser.Tilemap#getTile + * @param {number} x - X position to get the tile from (given in tile units, not pixels) + * @param {number} y - Y position to get the tile from (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTile: function (x, y, layer, nonNull) { + + if (nonNull === undefined) { nonNull = false; } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.layers[layer].data[y][x].index === -1) + { + if (nonNull) + { + return this.layers[layer].data[y][x]; + } + else + { + return null; + } + } + else + { + return this.layers[layer].data[y][x]; + } + } + else + { + return null; + } + + }, + + /** + * Gets a tile from the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#getTileWorldXY + * @param {number} x - X position to get the tile from (given in pixels) + * @param {number} y - Y position to get the tile from (given in pixels) + * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used. + * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates. + */ + getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) { + + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + + layer = this.getLayer(layer); + + x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; + y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; + + return this.getTile(x, y, layer, nonNull); + + }, + + /** + * Copies all of the tiles in the given rectangular block into the tilemap data buffer. + * + * @method Phaser.Tilemap#copy + * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} width - The width of the area to copy (given in tiles, not pixels) + * @param {integer} height - The height of the area to copy (given in tiles, not pixels) + * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from. + * @return {array} An array of the tiles that were copied. + */ + copy: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + if (!this.layers[layer]) + { + this._results.length = 0; + return; + } + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.layers[layer].width; } + if (height === undefined) { height = this.layers[layer].height; } + + if (x < 0) + { + x = 0; + } + + if (y < 0) + { + y = 0; + } + + if (width > this.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; ty < y + height; ty++) + { + for (var tx = x; tx < x + width; tx++) + { + this._results.push(this.layers[layer].data[ty][tx]); + } + } + + return this._results; + + }, + + /** + * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. + * + * @method Phaser.Tilemap#paste + * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels) + * @param {array} tileblock - The block of tiles to paste. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into. + */ + paste: function (x, y, tileblock, layer) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + layer = this.getLayer(layer); + + if (!tileblock || tileblock.length < 2) + { + return; + } + + // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste + var diffX = x - tileblock[1].x; + var diffY = y - tileblock[1].y; + + for (var i = 1; i < tileblock.length; i++) + { + this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]); + } + + this.layers[layer].dirty = true; + this.calculateFaces(layer); + + }, + + /** + * Scans the given area for tiles with an index matching tileA and swaps them with tileB. + * + * @method Phaser.Tilemap#swap + * @param {number} tileA - First tile index. + * @param {number} tileB - Second tile index. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + swap: function (tileA, tileB, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._tempA = tileA; + this._tempB = tileB; + + this._results.forEach(this.swapHandler, this); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Internal function that handles the swapping of tiles. + * + * @method Phaser.Tilemap#swapHandler + * @private + * @param {number} value + */ + swapHandler: function (value) { + + if (value.index === this._tempA) + { + // Swap A with B + value.index = this._tempB; + } + else if (value.index === this._tempB) + { + // Swap B with A + value.index = this._tempA; + } + + }, + + /** + * For each tile in the given area defined by x/y and width/height run the given callback. + * + * @method Phaser.Tilemap#forEach + * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {number} context - The context under which the callback should be run. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + forEach: function (callback, context, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._results.forEach(callback, context); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. + * + * @method Phaser.Tilemap#replace + * @param {number} source - The tile index value to scan for. + * @param {number} dest - The tile index value to replace found tiles with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + replace: function (source, dest, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + if (this._results[i].index === source) + { + this._results[i].index = dest; + } + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Randomises a set of tiles in a given area. + * + * @method Phaser.Tilemap#random + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + random: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + var idx = this._results[t].index; + + if (indexes.indexOf(idx) === -1) + { + indexes.push(idx); + } + } + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = this.game.rnd.pick(indexes); + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! + * + * @method Phaser.Tilemap#shuffle + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + shuffle: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + indexes.push(this._results[t].index); + } + } + + Phaser.ArrayUtils.shuffle(indexes); + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = indexes[i - 1]; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Fills the given area with the specified tile. + * + * @method Phaser.Tilemap#fill + * @param {number} index - The index of the tile that the area will be filled with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + fill: function (index, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = index; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Removes all layers from this tile map. + * + * @method Phaser.Tilemap#removeAllLayers + */ + removeAllLayers: function () { + + this.layers.length = 0; + this.currentLayer = 0; + + }, + + /** + * Dumps the tilemap data out to the console. + * + * @method Phaser.Tilemap#dump + */ + dump: function () { + + var txt = ''; + var args = ['']; + + for (var y = 0; y < this.layers[this.currentLayer].height; y++) + { + for (var x = 0; x < this.layers[this.currentLayer].width; x++) + { + txt += "%c "; + + if (this.layers[this.currentLayer].data[y][x] > 1) + { + 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); + + }, + + /** + * Removes all layer data from this tile map and nulls the game reference. + * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. + * + * @method Phaser.Tilemap#destroy + */ + destroy: function () { + + this.removeAllLayers(); + this.data = []; + this.game = null; + + } + +}; + +Phaser.Tilemap.prototype.constructor = Phaser.Tilemap; + +/** +* @name Phaser.Tilemap#layer +* @property {number|string|Phaser.TilemapLayer} layer - The current layer object. +*/ +Object.defineProperty(Phaser.Tilemap.prototype, "layer", { + + get: function () { + + return this.layers[this.currentLayer]; + + }, + + set: function (value) { + + if (value !== this.currentLayer) + { + this.setLayer(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. +* +* Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. +* +* By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. +* +* @class Phaser.TilemapLayer +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs. +* @param {integer} index - The index of the TileLayer to render within the Tilemap. +* @param {integer} width - Width of the renderable area of the layer (in pixels). +* @param {integer} height - Height of the renderable area of the layer (in pixels). +*/ +Phaser.TilemapLayer = function (game, tilemap, index, width, height) { + + width |= 0; + height |= 0; + + Phaser.Sprite.call(this, game, 0, 0); + + /** + * The Tilemap to which this layer is bound. + * @property {Phaser.Tilemap} map + * @protected + * @readonly + */ + this.map = tilemap; + + /** + * The index of this layer within the Tilemap. + * @property {number} index + * @protected + * @readonly + */ + this.index = index; + + /** + * The layer object within the Tilemap that this layer represents. + * @property {object} layer + * @protected + * @readonly + */ + this.layer = tilemap.layers[index]; + + /** + * The canvas to which this TilemapLayer draws. + * @property {HTMLCanvasElement} canvas + * @protected + */ + this.canvas = Phaser.CanvasPool.create(this, width, height); + + /** + * The 2d context of the canvas. + * @property {CanvasRenderingContext2D} context + * @private + */ + this.context = this.canvas.getContext('2d'); + + this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas, null, this.game.resolution))); + + /** + * The const type of this object. + * @property {number} type + * @readonly + * @protected + * @default Phaser.TILEMAPLAYER + */ + this.type = Phaser.TILEMAPLAYER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.TILEMAPLAYER; + + /** + * Settings that control standard (non-diagnostic) rendering. + * + * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view. + * This can greatly improve scrolling rendering performance, especially when there are many small tiles. + * It should only be disabled in rare cases. + * + * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas. + * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior + * in some browsers, notably Safari. + * + * @default + */ + this.renderSettings = { + enableScrollDelta: true, + overdrawRatio: 0.20, + copyCanvas: null + }; + + /** + * Enable an additional "debug rendering" pass to display collision information. + * + * @property {boolean} debug + * @default + */ + this.debug = false; + + /** + * @property {boolean} exists - Controls if the core game loop and physics update this game object or not. + */ + this.exists = true; + + /** + * Settings used for debugging and diagnostics. + * + * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. + * + * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. + * + * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. + * + * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. + * + */ + this.debugSettings = { + + missingImageFill: 'rgb(255,255,255)', + debuggedTileOverfill: 'rgba(0,255,0,0.4)', + + forceFullRedraw: true, + + debugAlpha: 0.5, + facingEdgeStroke: 'rgba(0,255,0,1)', + collidingTileOverfill: 'rgba(0,255,0,0.2)' + + }; + + /** + * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). + * @property {number} scrollFactorX + * @public + * @default + */ + this.scrollFactorX = 1; + + /** + * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) + * @property {number} scrollFactorY + * @public + * @default + */ + this.scrollFactorY = 1; + + /** + * If true tiles will be force rendered, even if such is not believed to be required. + * @property {boolean} dirty + * @protected + */ + this.dirty = true; + + /** + * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. + * @property {integer} rayStepRate + * @default + */ + this.rayStepRate = 4; + + /** + * Flag controlling if the layer tiles wrap at the edges. + * @property {boolean} _wrap + * @private + */ + this._wrap = false; + + /** + * Local map data and calculation cache. + * @property {object} _mc + * @private + */ + this._mc = { + + // Used to bypass rendering without reliance on `dirty` and detect changes. + scrollX: 0, + scrollY: 0, + renderWidth: 0, + renderHeight: 0, + + tileWidth: tilemap.tileWidth, + tileHeight: tilemap.tileHeight, + + // Collision width/height (pixels) + // What purpose do these have? Most things use tile width/height directly. + // This also only extends collisions right and down. + cw: tilemap.tileWidth, + ch: tilemap.tileHeight, + + // Cached tilesets from index -> Tileset + tilesets: [] + + }; + + /** + * The current canvas left after scroll is applied. + * @property {number} _scrollX + * @private + */ + this._scrollX = 0; + + /** + * The current canvas top after scroll is applied. + * @property {number} _scrollY + * @private + */ + this._scrollY = 0; + + /** + * The position offset of the layer's tiles. + * @property {Phaser.Point} + */ + this.tileOffset = new Phaser.Point(this.layer.offsetX || 0, this.layer.offsetY || 0); + + /** + * Used for caching the tiles / array of tiles. + * @property {Phaser.Tile[]} _results + * @private + */ + this._results = []; + + if (!game.device.canvasBitBltShift) + { + this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas(); + } + + this.fixedToCamera = true; + +}; + +Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer; + +Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* The shared double-copy canvas, created as needed. +* +* @private +* @static +*/ +Phaser.TilemapLayer.sharedCopyCanvas = null; + +/** +* Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. +* +* Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. +* +* @method Phaser.TilemapLayer#ensureSharedCopyCanvas +* @protected +* @static +*/ +Phaser.TilemapLayer.ensureSharedCopyCanvas = function () { + + if (!this.sharedCopyCanvas) + { + this.sharedCopyCanvas = Phaser.CanvasPool.create(this, 2, 2); + } + + return this.sharedCopyCanvas; + +}; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TilemapLayer#preUpdate +*/ +Phaser.TilemapLayer.prototype.preUpdate = function() { + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.postUpdate. Handles cache updates. +* +* @method Phaser.TilemapLayer#postUpdate +* @protected +*/ +Phaser.TilemapLayer.prototype.postUpdate = function () { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderCanvas function. +* +* @method Phaser.TilemapLayer#_renderCanvas +* @private +*/ +Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderWebGL function. +* +* @method Phaser.TilemapLayer#_renderWebGL +* @private +*/ +Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Destroys this TilemapLayer. +* +* @method Phaser.TilemapLayer#destroy +*/ +Phaser.TilemapLayer.prototype.destroy = function() { + + Phaser.CanvasPool.remove(this); + + Phaser.Component.Destroy.prototype.destroy.call(this); + +}; + +/** +* Resizes the internal canvas and texture frame used by this TilemapLayer. +* +* This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully +* selected times. +* +* Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not +* modified either. You will have to handle both of these things from your game code if required. +* +* @method Phaser.TilemapLayer#resize +* @param {number} width - The new width of the TilemapLayer +* @param {number} height - The new height of the TilemapLayer +*/ +Phaser.TilemapLayer.prototype.resize = function (width, height) { + + this.canvas.width = width; + this.canvas.height = height; + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.texture.baseTexture.width = width; + this.texture.baseTexture.height = height; + + this.texture.baseTexture.dirty(); + this.texture.requiresUpdate = true; + + this.texture._updateUvs(); + + this.dirty = true; + +}; + +/** +* Sets the world size to match the size of this layer. +* +* @method Phaser.TilemapLayer#resizeWorld +* @public +*/ +Phaser.TilemapLayer.prototype.resizeWorld = function () { + + this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y); + +}; + +/** + * Get the X axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getLayerOffsetX + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetX = function () { + + return this.tileOffset.x || ((!this.fixedToCamera) ? this.position.x : 0); + +}; + +/** + * Get the Y axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getTileOffsetY + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetY = function () { + + return this.tileOffset.y || ((!this.fixedToCamera) ? this.position.y : 0); + +}; + +/** +* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixX +* @private +* @param {number} x - x coordinate in camera space +* @return {number} x coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixX = function (x) { + + if (this.scrollFactorX === 1 || (this.scrollFactorX === 0 && this.position.x === 0)) + { + return x; + } + + // This executes if the scrollFactorX is 0 and the x position of the tilemap is off from standard. + if (this.scrollFactorX === 0 && this.position.x !== 0) + { + return x - this.position.x; + } + + return this._scrollX + (x - (this._scrollX / this.scrollFactorX)); + +}; + +/** +* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixX +* @private +* @param {number} x - x coordinate in scrollFactor-adjusted dimensions +* @return {number} x coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixX = function (x) { + + if (this.scrollFactorX === 1) + { + return x; + } + + return (this._scrollX / this.scrollFactorX) + (x - this._scrollX); + +}; + +/** +* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixY +* @private +* @param {number} y - y coordinate in camera space +* @return {number} y coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixY = function (y) { + + if (this.scrollFactorY === 1 || (this.scrollFactorY === 0 && this.position.y === 0)) + { + return y; + } + + // This executes if the scrollFactorY is 0 and the y position of the tilemap is off from standard. + if (this.scrollFactorY === 0 && this.position.y !== 0) + { + return y - this.position.y; + } + + return this._scrollY + (y - (this._scrollY / this.scrollFactorY)); + +}; + +/** +* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixY +* @private +* @param {number} y - y coordinate in scrollFactor-adjusted dimensions +* @return {number} y coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixY = function (y) { + + if (this.scrollFactorY === 1) + { + return y; + } + + return (this._scrollY / this.scrollFactorY) + (y - this._scrollY); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileX +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @return {integer} The X map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileX = function (x) { + + // var tileWidth = this.tileWidth * this.scale.x; + return Math.floor(this._fixX(x) / this._mc.tileWidth); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileY +* @public +* @param {number} y - Y position of the point in target tile (in pixels). +* @return {integer} The Y map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileY = function (y) { + + // var tileHeight = this.tileHeight * this.scale.y; + return Math.floor(this._fixY(y) / this._mc.tileHeight); + +}; + +/** +* Convert a pixel coordinate to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileXY +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @param {number} y - Y position of the point in target tile (in pixels). +* @param {(Phaser.Point|object)} point - The Point/object to update. +* @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set. +*/ +Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) { + + point.x = this.getTileX(x); + point.y = this.getTileY(y); + + return point; + +}; + +/** +* Gets all tiles that intersect with the given line. +* +* @method Phaser.TilemapLayer#getRayCastTiles +* @public +* @param {Phaser.Line} line - The line used to determine which tiles to return. +* @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`. +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {Phaser.Tile[]} An array of Phaser.Tiles. +*/ +Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) { + + if (!stepRate) { stepRate = this.rayStepRate; } + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + // First get all tiles that touch the bounds of the line + var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace); + + if (tiles.length === 0) + { + return []; + } + + // Now we only want the tiles that intersect with the points on this line + var coords = line.coordinatesOnLine(stepRate); + var results = []; + + for (var i = 0; i < tiles.length; i++) + { + for (var t = 0; t < coords.length; t++) + { + var tile = tiles[i]; + var coord = coords[t]; + if (tile.containsPoint(coord[0], coord[1])) + { + results.push(tile); + break; + } + } + } + + return results; + +}; + +/** +* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. +* +* @method Phaser.TilemapLayer#getTiles +* @public +* @param {number} x - X position of the top left corner (in pixels). +* @param {number} y - Y position of the top left corner (in pixels). +* @param {number} width - Width of the area to get (in pixels). +* @param {number} height - Height of the area to get (in pixels). +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {array} An array of Tiles. +*/ +Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) { + + // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all) + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + var fetchAll = !(collides || interestingFace); + + // Adjust the x,y coordinates for scrollFactor + x = this._fixX(x); + y = this._fixY(y); + + // Convert the pixel values into tile coordinates + var tx = Math.floor(x / (this._mc.cw * this.scale.x)); + var ty = Math.floor(y / (this._mc.ch * this.scale.y)); + // Don't just use ceil(width/cw) to allow account for x/y diff within cell + var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx; + var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty; + + while (this._results.length) + { + this._results.pop(); + } + + for (var wy = ty; wy < ty + th; wy++) + { + for (var wx = tx; wx < tx + tw; wx++) + { + var row = this.layer.data[wy]; + + if (row && row[wx]) + { + if (fetchAll || row[wx].isInteresting(collides, interestingFace)) + { + this._results.push(row[wx]); + } + } + } + } + + return this._results.slice(); + +}; + +/** +* Returns the appropriate tileset for the index, updating the internal cache as required. +* This should only be called if `tilesets[index]` evaluates to undefined. +* +* @method Phaser.TilemapLayer#resolveTileset +* @private +* @param {integer} Tile index +* @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping. +*/ +Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) { + + var tilesets = this._mc.tilesets; + + // Try for dense array if reasonable + if (tileIndex < 2000) + { + while (tilesets.length < tileIndex) + { + tilesets.push(undefined); + } + } + + var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2]; + + if (setIndex !== null) + { + var tileset = this.map.tilesets[setIndex]; + + if (tileset && tileset.containsTileIndex(tileIndex)) + { + return (tilesets[tileIndex] = tileset); + } + } + + return (tilesets[tileIndex] = null); + +}; + +/** +* The TilemapLayer caches tileset look-ups. +* +* Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. +* +* @method Phaser.TilemapLayer#resetTilesetCache +* @public +*/ +Phaser.TilemapLayer.prototype.resetTilesetCache = function () { + + var tilesets = this._mc.tilesets; + + while (tilesets.length) + { + tilesets.pop(); + } + +}; + +/** + * This method will set the scale of the tilemap as well as update the underlying block data of this layer. + * + * @method Phaser.TilemapLayer#setScale + * @param {number} [xScale=1] - The scale factor along the X-plane + * @param {number} [yScale] - The scale factor along the Y-plane + */ +Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) { + + xScale = xScale || 1; + yScale = yScale || xScale; + + for (var y = 0; y < this.layer.data.length; y++) + { + var row = this.layer.data[y]; + + for (var x = 0; x < row.length; x++) + { + var tile = row[x]; + + tile.width = this.map.tileWidth * xScale; + tile.height = this.map.tileHeight * yScale; + + tile.worldX = tile.x * tile.width; + tile.worldY = tile.y * tile.height; + } + } + + this.scale.setTo(xScale, yScale); + +}; + +/** +* Shifts the contents of the canvas - does extra math so that different browsers agree on the result. +* +* The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in. +* +* @method Phaser.TilemapLayer#shiftCanvas +* @private +* @param {CanvasRenderingContext2D} context - The context to shift +* @param {integer} x +* @param {integer} y +*/ +Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) { + + var canvas = context.canvas; + var copyW = canvas.width - Math.abs(x); + var copyH = canvas.height - Math.abs(y); + + // When x/y non-negative + var dx = 0; + var dy = 0; + var sx = x; + var sy = y; + + if (x < 0) + { + dx = -x; + sx = 0; + } + + if (y < 0) + { + dy = -y; + sy = 0; + } + + var copyCanvas = this.renderSettings.copyCanvas; + + if (copyCanvas) + { + // Use a second copy buffer, without slice support, for Safari .. again. + // Ensure copy canvas is large enough + if (copyCanvas.width < copyW || copyCanvas.height < copyH) + { + copyCanvas.width = copyW; + copyCanvas.height = copyH; + } + + var copyContext = copyCanvas.getContext('2d'); + copyContext.clearRect(0, 0, copyW, copyH); + copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH); + // clear allows default 'source-over' semantics + context.clearRect(sx, sy, copyW, copyH); + context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH); + } + else + { + // Avoids a second copy but flickers in Safari / Safari Mobile + // Ref. https://github.com/photonstorm/phaser/issues/1439 + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH); + context.restore(); + } + +}; + +/** +* Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor. +* This will constrain the tile coordinates based on wrapping but not physical coordinates. +* +* @method Phaser.TilemapLayer#renderRegion +* @private +* @param {integer} scrollX - Render x offset/scroll. +* @param {integer} scrollY - Render y offset/scroll. +* @param {integer} left - Leftmost column to render. +* @param {integer} top - Topmost row to render. +* @param {integer} right - Rightmost column to render. +* @param {integer} bottom - Bottommost row to render. +*/ +Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) { + + var context = this.context; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var tilesets = this._mc.tilesets; + var lastAlpha = NaN; + + if (!this._wrap) + { + if (left <= right) // Only adjust if going to render + { + left = Math.max(0, left); + right = Math.min(width - 1, right); + } + if (top <= bottom) + { + top = Math.max(0, top); + bottom = Math.min(height - 1, bottom); + } + } + + // top-left pixel of top-left cell + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values. + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + // tx/ty - are pixel coordinates where tile is drawn + // x/y - is cell location, normalized [0..width/height) in loop + // xmax/ymax - remaining cells to render on column/row + var tx, ty, x, y, xmax, ymax; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + + if (!tile || tile.index < 0) + { + continue; + } + + var index = tile.index; + + var set = tilesets[index]; + + if (set === undefined) + { + set = this.resolveTileset(index); + } + + // Setting the globalAlpha is "surprisingly expensive" in Chrome (38) + if (tile.alpha !== lastAlpha && !this.debug) + { + context.globalAlpha = tile.alpha; + lastAlpha = tile.alpha; + } + + if (set) + { + if (tile.rotation || tile.flipped) + { + context.save(); + context.translate(tx + tile.centerX, ty + tile.centerY); + context.rotate(tile.rotation); + + if (tile.flipped) + { + context.scale(-1, 1); + } + + set.draw(context, -tile.centerX, -tile.centerY, index); + context.restore(); + } + else + { + set.draw(context, tx, ty, index); + } + } + else if (this.debugSettings.missingImageFill) + { + context.fillStyle = this.debugSettings.missingImageFill; + context.fillRect(tx, ty, tw, th); + } + + if (tile.debug && this.debugSettings.debuggedTileOverfill) + { + context.fillStyle = this.debugSettings.debuggedTileOverfill; + context.fillRect(tx, ty, tw, th); + } + + } + + } + +}; + +/** +* Shifts the canvas and render damaged edge tiles. +* +* @method Phaser.TilemapLayer#renderDeltaScroll +* @private +*/ +Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds. + + // Start in pixels + var left = 0; + var right = -tw; + var top = 0; + var bottom = -th; + + if (shiftX < 0) // layer moving left, damage right + { + left = renderW + shiftX; // shiftX neg. + right = renderW - 1; + } + else if (shiftX > 0) + { + // left -> 0 + right = shiftX; + } + + if (shiftY < 0) // layer moving down, damage top + { + top = renderH + shiftY; // shiftY neg. + bottom = renderH - 1; + } + else if (shiftY > 0) + { + // top -> 0 + bottom = shiftY; + } + + this.shiftCanvas(this.context, shiftX, shiftY); + + // Transform into tile-space + left = Math.floor((left + scrollX) / tw); + right = Math.floor((right + scrollX) / tw); + top = Math.floor((top + scrollY) / th); + bottom = Math.floor((bottom + scrollY) / th); + + if (left <= right) + { + // Clear left or right edge + this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH); + + var trueTop = Math.floor((0 + scrollY) / th); + var trueBottom = Math.floor((renderH - 1 + scrollY) / th); + this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom); + } + + if (top <= bottom) + { + // Clear top or bottom edge + this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th); + + var trueLeft = Math.floor((0 + scrollX) / tw); + var trueRight = Math.floor((renderW - 1 + scrollX) / tw); + this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom); + } + +}; + +/** +* Clear and render the entire canvas. +* +* @method Phaser.TilemapLayer#renderFull +* @private +*/ +Phaser.TilemapLayer.prototype.renderFull = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + this.context.clearRect(0, 0, renderW, renderH); + + this.renderRegion(scrollX, scrollY, left, top, right, bottom); + +}; + +/** +* Renders the tiles to the layer canvas and pushes to the display. +* +* @method Phaser.TilemapLayer#render +* @protected +*/ +Phaser.TilemapLayer.prototype.render = function () { + + var redrawAll = false; + + if (!this.visible) + { + return; + } + + if (this.dirty || this.layer.dirty) + { + this.layer.dirty = false; + redrawAll = true; + } + + var renderWidth = this.canvas.width; // Use Sprite.width/height? + var renderHeight = this.canvas.height; + + // Scrolling bias; whole pixels only + var scrollX = this._scrollX | 0; + var scrollY = this._scrollY | 0; + + var mc = this._mc; + var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down + var shiftY = mc.scrollY - scrollY; + + if (!redrawAll && + shiftX === 0 && shiftY === 0 && + mc.renderWidth === renderWidth && mc.renderHeight === renderHeight) + { + // No reason to redraw map, looking at same thing and not invalidated. + return; + } + + this.context.save(); + + mc.scrollX = scrollX; + mc.scrollY = scrollY; + + if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight) + { + // Could support automatic canvas resizing + mc.renderWidth = renderWidth; + mc.renderHeight = renderHeight; + } + + if (this.debug) + { + this.context.globalAlpha = this.debugSettings.debugAlpha; + + if (this.debugSettings.forceFullRedraw) + { + redrawAll = true; + } + } + + if (!redrawAll && + this.renderSettings.enableScrollDelta && + (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight)) + { + this.renderDeltaScroll(shiftX, shiftY); + } + else + { + // Too much change or otherwise requires full render + this.renderFull(); + } + + if (this.debug) + { + this.context.globalAlpha = 1; + this.renderDebug(); + } + + this.texture.baseTexture.dirty(); + + this.dirty = false; + + this.context.restore(); + + return true; + +}; + +/** +* Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true. +* +* See `debugSettings` for assorted configuration options. +* +* @method Phaser.TilemapLayer#renderDebug +* @private +*/ +Phaser.TilemapLayer.prototype.renderDebug = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var context = this.context; + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + var tx, ty, x, y, xmax, ymax; + + context.strokeStyle = this.debugSettings.facingEdgeStroke; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + if (!tile || tile.index < 0 || !tile.collides) + { + continue; + } + + if (this.debugSettings.collidingTileOverfill) + { + context.fillStyle = this.debugSettings.collidingTileOverfill; + context.fillRect(tx, ty, this._mc.cw, this._mc.ch); + } + + if (this.debugSettings.facingEdgeStroke) + { + context.beginPath(); + + if (tile.faceTop) + { + context.moveTo(tx, ty); + context.lineTo(tx + this._mc.cw, ty); + } + + if (tile.faceBottom) + { + context.moveTo(tx, ty + this._mc.ch); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + if (tile.faceLeft) + { + context.moveTo(tx, ty); + context.lineTo(tx, ty + this._mc.ch); + } + + if (tile.faceRight) + { + context.moveTo(tx + this._mc.cw, ty); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + context.closePath(); + + context.stroke(); + } + + } + + } + +}; + +/** +* Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size. +* +* @property {boolean} wrap +* @memberof Phaser.TilemapLayer +* @public +* @default false +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", { + + get: function () { + return this._wrap; + }, + + set: function (value) { + this._wrap = value; + this.dirty = true; + } + +}); + +/** +* Scrolls the map horizontally or returns the current x position. +* +* @property {number} scrollX +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", { + + get: function () { + return this._scrollX; + }, + + set: function (value) { + this._scrollX = value; + } + +}); + +/** +* Scrolls the map vertically or returns the current y position. +* +* @property {number} scrollY +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", { + + get: function () { + return this._scrollY; + }, + + set: function (value) { + this._scrollY = value; + } + +}); + +/** +* The width of the collision tiles (in pixels). +* +* @property {integer} collisionWidth +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", { + + get: function () { + return this._mc.cw; + }, + + set: function (value) { + this._mc.cw = value | 0; + this.dirty = true; + } + +}); + +/** +* The height of the collision tiles (in pixels). +* +* @property {integer} collisionHeight +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", { + + get: function () { + return this._mc.ch; + }, + + set: function (value) { + this._mc.ch = value | 0; + this.dirty = true; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. +* +* @class Phaser.TilemapParser +* @static +*/ +Phaser.TilemapParser = { + + /** + * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or + * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type + * depends how this should be configured. If you've a large sparsely populated map and the tile + * data doesn't need to change then setting this value to `true` will help with memory consumption. + * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes + * during the game) then leave the default value set. + * + * @constant + * @type {boolean} + */ + INSERT_NULL: false, + + /** + * Parse tilemap data from the cache and creates data for a Tilemap object. + * + * @method Phaser.TilemapParser.parse + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {string} key - The key of the tilemap in the Cache. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {object} The parsed map object. + */ + parse: function (game, key, tileWidth, tileHeight, width, height) { + + if (tileWidth === undefined) { tileWidth = 32; } + if (tileHeight === undefined) { tileHeight = 32; } + if (width === undefined) { width = 10; } + if (height === undefined) { height = 10; } + + if (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); + } + + }, + + /** + * Parses a CSV file into valid map data. + * + * @method Phaser.TilemapParser.parseCSV + * @param {string} key - The name you want to give the map data. + * @param {string} data - The CSV file data. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @return {object} Generated map data. + */ + parseCSV: function (key, data, tileWidth, tileHeight) { + + var map = this.getEmptyData(); + + // Trim any rogue whitespace from the data + data = data.trim(); + + var output = []; + var rows = data.split("\n"); + var height = rows.length; + var width = 0; + + for (var y = 0; y < rows.length; y++) + { + output[y] = []; + + var column = rows[y].split(","); + + for (var x = 0; x < column.length; x++) + { + output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight); + } + + if (width === 0) + { + width = column.length; + } + } + + map.format = Phaser.Tilemap.CSV; + map.name = key; + map.width = width; + map.height = height; + map.tileWidth = tileWidth; + map.tileHeight = tileHeight; + map.widthInPixels = width * tileWidth; + map.heightInPixels = height * tileHeight; + + map.layers[0].width = width; + map.layers[0].height = height; + map.layers[0].widthInPixels = map.widthInPixels; + map.layers[0].heightInPixels = map.heightInPixels; + map.layers[0].data = output; + + return map; + + }, + + /** + * Returns an empty map data object. + * + * @method Phaser.TilemapParser.getEmptyData + * @return {object} Generated map data. + */ + getEmptyData: function (tileWidth, tileHeight, width, height) { + + return { + width: (width !== undefined && width !== null) ? width : 0, + height: (height !== undefined && height !== null) ? height : 0, + tileWidth: (tileWidth !== undefined && tileWidth !== null) ? tileWidth : 0, + tileHeight: (tileHeight !== undefined && tileHeight !== null) ? tileHeight : 0, + orientation: 'orthogonal', + version: '1', + properties: {}, + widthInPixels: 0, + heightInPixels: 0, + layers: [ + { + name: 'layer', + x: 0, + y: 0, + width: 0, + height: 0, + widthInPixels: 0, + heightInPixels: 0, + alpha: 1, + visible: true, + properties: {}, + indexes: [], + callbacks: [], + bodies: [], + data: [] + } + ], + images: [], + objects: {}, + collision: {}, + tilesets: [], + tiles: [] + }; + + }, + + _slice: function(obj, fields) { + var sliced = {}; + + for (var k in fields) + { + var key = fields[k]; + + if (typeof obj[key] !== 'undefined') + { + sliced[key] = obj[key]; + } + } + + return sliced; + }, + + /** + * Parses an object group in Tiled JSON files. Object groups can be found in both layers and tilesets. Called internally in parseTiledJSON. + * @method Phaser.TilemapParser.parseObjectGroup + * @param {object} objectGroup - A JSON object group. + * @param {object} objectsCollection - An object into which new array of Tiled map objects will be added. + * @param {object} collisionCollection - An object into which new array of collision objects will be added. Currently only polylines are added. + * @param {string} [nameKey=objectGroup.name] - Key under which to store objects in collisions in objectsCollection and collisionCollection + * @param {object} [relativePosition={x: 0, y: 0}] - Coordinates the object group's position is relative to. + * @return {object} A object literal containing the objectsCollection and collisionCollection + */ + parseObjectGroup: function(objectGroup, objectsCollection, collisionCollection, nameKey, relativePosition) { + + var nameKey = nameKey || objectGroup.name; + var relativePosition = relativePosition || {x: 0, y: 0}; + var slice = this._slice; + + if (!nameKey) + { + console.warn('No name found for objectGroup', objectGroup); + } + + if (relativePosition.x === undefined || relativePosition.y === undefined) + { + console.warn('Malformed xy properties in relativePosition', relativePosition); + } + + objectsCollection[nameKey] = objectsCollection[nameKey] || []; + collisionCollection[nameKey] = collisionCollection[nameKey] || []; + + for (var v = 0, len = objectGroup.objects.length; v < len; v++) + { + var o = objectGroup.objects[v]; + + // Object Tiles + if (o.gid) + { + var object = { + gid: o.gid, + name: o.name, + type: o.type || '', + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + objectsCollection[nameKey].push(object); + } + else if (o.polyline) + { + var object = { + name: o.name, + type: o.type, + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + object.polyline = []; + + // Parse the polyline into an array + for (var p = 0; p < o.polyline.length; p++) + { + object.polyline.push([o.polyline[p].x, o.polyline[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // polygon + else if (o.polygon) + { + var object = slice(o, ['name', 'type', 'x', 'y', 'visible', 'rotation', 'properties']); + + object.x += relativePosition.x; + object.y += relativePosition.y; + + // Parse the polygon into an array + object.polygon = []; + + for (var p = 0; p < o.polygon.length; p++) + { + object.polygon.push([o.polygon[p].x, o.polygon[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // ellipse + else if (o.ellipse) + { + var object = slice(o, ['name', 'type', 'ellipse', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // otherwise it's a rectangle + else + { + var object = slice(o, ['name', 'type', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + object.rectangle = true; + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + } + + return { + objectsCollection: objectsCollection, + collisionCollection: collisionCollection + }; + }, + + /** + * Parses a Tiled JSON file into valid map data. + * @method Phaser.TilemapParser.parseTiledJSON + * @param {object} json - The JSON map data. + * @return {object} Generated and parsed map data. + */ + parseTiledJSON: function (json) { + + if (json.orientation !== 'orthogonal') + { + console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser'); + return null; + } + + // Map data will consist of: layers, objects, images, tilesets, sizes + var map = { + width: json.width, + height: json.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + orientation: json.orientation, + format: Phaser.Tilemap.TILED_JSON, + version: json.version, + properties: json.properties, + widthInPixels: json.width * json.tilewidth, + heightInPixels: json.height * json.tileheight + }; + + // Tile Layers + var layers = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'tilelayer') + { + continue; + } + + var curl = json.layers[i]; + + // Base64 decode data if necessary + // NOTE: uncompressed base64 only. + + if (!curl.compression && curl.encoding && curl.encoding === 'base64') + { + var binaryString = window.atob(curl.data); + var len = binaryString.length; + var bytes = new Array(len); + + // Interpret binaryString as an array of bytes representing + // little-endian encoded uint32 values. + for (var j = 0; j < len; j+=4) + { + bytes[j / 4] = ( + binaryString.charCodeAt(j) | + binaryString.charCodeAt(j + 1) << 8 | + binaryString.charCodeAt(j + 2) << 16 | + binaryString.charCodeAt(j + 3) << 24 + ) >>> 0; + } + + curl.data = bytes; + + delete curl.encoding; + } + else if (curl.compression) + { + console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\''); + continue; + } + + var layer = { + + name: curl.name, + x: curl.x, + y: curl.y, + width: curl.width, + height: curl.height, + widthInPixels: curl.width * json.tilewidth, + heightInPixels: curl.height * json.tileheight, + alpha: curl.opacity, + offsetX: curl.offsetx, + offsetY: curl.offsety, + visible: curl.visible, + properties: {}, + indexes: [], + callbacks: [], + bodies: [] + + }; + + if (curl.properties) + { + layer.properties = curl.properties; + } + + var x = 0; + var row = []; + var output = []; + var rotation, flipped, flippedVal, gid; + + // Loop through the data field in the JSON. + + // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV) + // If the map contains multiple tilesets then the indexes are relative to that which the set starts from. + // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset. + + for (var t = 0, len = curl.data.length; t < len; t++) + { + rotation = 0; + flipped = false; + gid = curl.data[t]; + flippedVal = 0; + + // If true the current tile is flipped or rotated (Tiled TMX format) + if (gid > 0x20000000) + { + // FlippedX + if (gid > 0x80000000) + { + gid -= 0x80000000; + flippedVal += 4; + } + + // FlippedY + if (gid > 0x40000000) + { + gid -= 0x40000000; + flippedVal += 2; + } + + // FlippedAD (anti-diagonal = top-right is swapped with bottom-left corners) + if (gid > 0x20000000) + { + gid -= 0x20000000; + flippedVal += 1; + } + + switch (flippedVal) + { + case 5: + rotation = Math.PI / 2; + break; + + case 6: + rotation = Math.PI; + break; + + case 3: + rotation = 3 * Math.PI / 2; + break; + + case 4: + rotation = 0; + flipped = true; + break; + + case 7: + rotation = Math.PI / 2; + flipped = true; + break; + + case 2: + rotation = Math.PI; + flipped = true; + break; + + case 1: + rotation = 3 * Math.PI / 2; + flipped = true; + break; + } + } + + // index, x, y, width, height + if (gid > 0) + { + var tile = new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight); + + tile.rotation = rotation; + tile.flipped = flipped; + + if (flippedVal !== 0) + { + // The WebGL renderer uses this to flip UV coordinates before drawing + tile.flippedVal = flippedVal; + } + + row.push(tile); + } + else + { + if (Phaser.TilemapParser.INSERT_NULL) + { + row.push(null); + } + else + { + row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight)); + } + } + + x++; + + if (x === curl.width) + { + output.push(row); + x = 0; + row = []; + } + } + + layer.data = output; + + layers.push(layer); + } + + map.layers = layers; + + // Images + var images = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'imagelayer') + { + continue; + } + + var curi = json.layers[i]; + + var image = { + + name: curi.name, + image: curi.image, + x: curi.x, + y: curi.y, + alpha: curi.opacity, + visible: curi.visible, + properties: {} + + }; + + if (curi.properties) + { + image.properties = curi.properties; + } + + images.push(image); + + } + + map.images = images; + + // Tilesets & Image Collections + var tilesets = []; + var tilesetGroupObjects = {}; + var imagecollections = []; + var lastSet = null; + + for (var i = 0; i < json.tilesets.length; i++) + { + // name, firstgid, width, height, margin, spacing, properties + var set = json.tilesets[i]; + + if (set.source) + { + console.warn('Phaser.TilemapParser - Phaser can\'t load external tilesets (%s). Use the Embed Tileset button and then export the map again.', set.source); + } + else if (set.image) + { + var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + if (set.tileproperties) + { + newSet.tileProperties = set.tileproperties; + } + + // For a normal sliced tileset the row/count/size information is computed when updated. + // This is done (again) after the image is set. + newSet.updateTileData(set.imagewidth, set.imageheight); + + tilesets.push(newSet); + } + else if (set.tiles) + { + var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + for (var ti in set.tiles) + { + var image = set.tiles[ti].image; + var gid = set.firstgid + parseInt(ti, 10); + newCollection.addImage(gid, image); + } + + imagecollections.push(newCollection); + } + else + { + throw new Error('Tileset ' + set.name + ' has no `image` or `tiles` property.'); + } + + // build a temporary object for objectgroups found in the tileset's tiles + for (var ti in set.tiles) + { + var objectGroup = set.tiles[ti].objectgroup; + + if (!objectGroup) + { + continue; + } + + tilesetGroupObjects[parseInt(ti, 10) + set.firstgid] = objectGroup; + } + + // We've got a new Tileset, so set the lastgid into the previous one + if (lastSet) + { + lastSet.lastgid = set.firstgid - 1; + } + + lastSet = set; + } + + if (tilesets.length === 0 && imagecollections.length === 0) + { + throw new Error('This tilemap has no tilesets.'); + } + + map.tilesets = tilesets; + map.imagecollections = imagecollections; + + // Objects & Collision Data (polylines, etc) + var objects = {}; + var collision = {}; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'objectgroup') + { + continue; + } + + var objectGroup = json.layers[i]; + this.parseObjectGroup(objectGroup, objects, collision); + } + + map.objects = objects; + map.collision = collision; + + map.tiles = []; + + // Finally lets build our super tileset index + for (var i = 0; i < map.tilesets.length; i++) + { + var set = map.tilesets[i]; + + var x = set.tileMargin; + var y = set.tileMargin; + + var count = 0; + var countX = 0; + var countY = 0; + + for (var t = set.firstgid; t < set.firstgid + set.total; t++) + { + // Can add extra properties here as needed + map.tiles[t] = [x, y, i]; + + x += set.tileWidth + set.tileSpacing; + + count++; + + if (count === set.total) + { + break; + } + + countX++; + + if (countX === set.columns) + { + x = set.tileMargin; + y += set.tileHeight + set.tileSpacing; + + countX = 0; + countY++; + + if (countY === set.rows) + { + break; + } + } + } + + } + + // assign tile properties + + var layer; + var tile; + var sid; + var set; + + // go through each of the map data layers + for (var i = 0; i < map.layers.length; i++) + { + layer = map.layers[i]; + collision[layer.name] = []; + set = null; + + // rows of tiles + for (var j = 0; j < layer.data.length; j++) + { + row = layer.data[j]; + + // individual tiles + for (var k = 0; k < row.length; k++) + { + tile = row[k]; + + if (tile === null || tile.index < 0) + { + continue; + } + + // find the relevant tileset + + sid = map.tiles[tile.index][2]; + set = map.tilesets[sid]; + + + // if that tile type has any properties, add them to the tile object + + if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) + { + tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties); + } + + var objectGroup = tilesetGroupObjects[tile.index]; + if (objectGroup) + { + // build collisions and objects for objectgroups found in the tileset's tiles + this.parseObjectGroup( + objectGroup, + map.objects, + map.collision, + tile.layer.name, + { + x: tile.worldX + objectGroup.x, + y: tile.worldY + objectGroup.y + }); + } + + } + } + } + + return map; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile set is a combination of an image containing the tiles and collision data per tile. +* +* Tilesets are normally created automatically when Tiled data is loaded. +* +* @class Phaser.Tileset +* @constructor +* @param {string} name - The name of the tileset in the map data. +* @param {integer} firstgid - The first tile index this tileset contains. +* @param {integer} [width=32] - Width of each tile (in pixels). +* @param {integer} [height=32] - Height of each tile (in pixels). +* @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels). +* @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels). +* @param {object} [properties={}] - Custom Tileset properties. +*/ +Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Tileset. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first tile index this Tileset contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of each tile (in pixels). + * @property {integer} tileWidth + * @readonly + */ + this.tileWidth = width | 0; + + /** + * The height of each tile (in pixels). + * @property {integer} tileHeight + * @readonly + */ + this.tileHeight = height | 0; + + /** + * The margin around the tiles in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileMarge + * @readonly + */ + // Modified internally + this.tileMargin = margin | 0; + + /** + * The spacing between each tile in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileSpacing + * @readonly + */ + this.tileSpacing = spacing | 0; + + /** + * Tileset-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set. + * @property {?object} image + * @readonly + */ + // Modified internally + this.image = null; + + /** + * The number of tile rows in the the tileset. + * @property {integer} + * @readonly + */ + // Modified internally + this.rows = 0; + + /** + * The number of tile columns in the tileset. + * @property {integer} columns + * @readonly + */ + // Modified internally + this.columns = 0; + + /** + * The total number of tiles in the tileset. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; + + /** + * The look-up table to specific tile image offsets. + * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1. + * @property {integer[]} drawCoords + * @private + */ + this.drawCoords = []; + +}; + +Phaser.Tileset.prototype = { + + /** + * Draws a tile from this Tileset at the given coordinates on the context. + * + * @method Phaser.Tileset#draw + * @public + * @param {CanvasRenderingContext2D} context - The context to draw the tile onto. + * @param {number} x - The x coordinate to draw to. + * @param {number} y - The y coordinate to draw to. + * @param {integer} index - The index of the tile within the set to draw. + */ + draw: function (context, x, y, index) { + + // Correct the tile index for the set and bias for interlacing + var coordIndex = (index - this.firstgid) << 1; + + if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length) + { + context.drawImage( + this.image, + this.drawCoords[coordIndex], + this.drawCoords[coordIndex + 1], + this.tileWidth, + this.tileHeight, + x, + y, + this.tileWidth, + this.tileHeight + ); + } + + }, + + /** + * Returns true if and only if this tileset contains the given tile index. + * + * @method Phaser.Tileset#containsTileIndex + * @public + * @param {number} tileIndex + * @return {boolean} True if this tileset contains the given index. + */ + containsTileIndex: function (tileIndex) { + + return ( + tileIndex >= this.firstgid && + tileIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Set the image associated with this Tileset and update the tile data. + * + * @method Phaser.Tileset#setImage + * @public + * @param {Image} image - The image that contains the tiles. + */ + setImage: function (image) { + + this.image = image; + this.updateTileData(image.width, image.height); + + }, + + /** + * Sets tile spacing and margins. + * + * @method Phaser.Tileset#setSpacing + * @public + * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels). + */ + setSpacing: function (margin, spacing) { + + this.tileMargin = margin | 0; + this.tileSpacing = spacing | 0; + + if (this.image) + { + this.updateTileData(this.image.width, this.image.height); + } + + }, + + /** + * Updates tile coordinates and tileset data. + * + * @method Phaser.Tileset#updateTileData + * @private + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + */ + updateTileData: function (imageWidth, imageHeight) { + + // May be fractional values + var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); + var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); + + if (rowCount % 1 !== 0 || colCount % 1 !== 0) + { + console.warn( + "Phaser.Tileset - '%s' image tile area (%s x %s) is not a whole multiple of tile size (%s x %s + %s + %s)", + this.name, imageWidth, imageHeight, this.tileWidth, this.tileHeight, this.tileMargin, this.tileSpacing + ); + } + + // In Tiled a tileset image that is not an even multiple of the tile dimensions + // is truncated - hence the floor when calculating the rows/columns. + rowCount = Math.floor(rowCount); + colCount = Math.floor(colCount); + + if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount)) + { + console.warn( + "Phaser.Tileset - Tile layout from image '%s' (%s rows by %s columns) differs from tileset '%s' (%s rows by %s columns)", + this.image.name, colCount, rowCount, this.name, this.columns, this.rows + ); + } + + this.rows = rowCount; + this.columns = colCount; + this.total = rowCount * colCount; + + this.drawCoords.length = 0; + + var tx = this.tileMargin; + var ty = this.tileMargin; + + for (var y = 0; y < this.rows; y++) + { + for (var x = 0; x < this.columns; x++) + { + this.drawCoords.push(tx); + this.drawCoords.push(ty); + tx += this.tileWidth + this.tileSpacing; + } + + tx = this.tileMargin; + ty += this.tileHeight + this.tileSpacing; + } + + } + +}; + +Phaser.Tileset.prototype.constructor = Phaser.Tileset; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. +* +* @class Phaser.Particle +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Particle = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + /** + * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData. + * @protected + */ + this.autoScale = false; + + /** + * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.scaleData = null; + + /** + * @property {number} _s - Internal cache var for tracking auto scale. + * @private + */ + this._s = 0; + + /** + * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. + * @protected + */ + this.autoAlpha = false; + + /** + * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.alphaData = null; + + /** + * @property {number} _a - Internal cache var for tracking auto alpha. + * @private + */ + this._a = 0; + +}; + +Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Particle.prototype.constructor = Phaser.Particle; + +/** +* Updates the Particle scale or alpha if autoScale and autoAlpha are set. +* +* @method Phaser.Particle#update +* @memberof 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; + } + } + +}; + +/** +* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. +* +* @method Phaser.Particle#onEmit +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.onEmit = function() { +}; + +/** +* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. +* +* @method Phaser.Particle#setAlphaData +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.setAlphaData = function(data) { + + this.alphaData = data; + this._a = data.length - 1; + this.alpha = this.alphaData[this._a].v; + this.autoAlpha = true; + +}; + +/** +* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. +* +* @method Phaser.Particle#setScaleData +* @memberof Phaser.Particle +*/ +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; + +}; + +/** +* Resets the Particle. This places the Particle at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. +* If the Particle has a physics body that too is reset. +* +* @method Phaser.Particle#reset +* @memberof Phaser.Particle +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {number} [health=1] - The health to give the Particle. +* @return {Phaser.Particle} This instance. +*/ +Phaser.Particle.prototype.reset = function(x, y, health) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y, health); + + this.alpha = 1; + this.scale.set(1); + + this.autoScale = false; + this.autoAlpha = false; + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Particles tracks any Emitters attached to it. +* +* @class Phaser.Particles +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Particles = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} emitters - Internal emitters store. + */ + this.emitters = {}; + + /** + * @property {number} ID - + * @default + */ + this.ID = 0; + +}; + +Phaser.Particles.prototype = { + + /** + * Adds a new Particle Emitter to the Particle Manager. + * @method Phaser.Particles#add + * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. + * @return {Phaser.Emitter} The emitter that was added. + */ + add: function (emitter) { + this.emitters[emitter.id] = emitter; + return emitter; + }, + + /** + * Removes an existing Particle Emitter from the Particle Manager. + * @method Phaser.Particles#remove + * @param {Phaser.Emitter} emitter - The emitter to remove. + */ + remove: function (emitter) { + delete this.emitters[emitter.id]; + } + +}; + +Phaser.Particles.prototype.constructor = Phaser.Particles; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Arcade Particles is a Particle System integrated with Arcade Physics. +* +* @class Phaser.Particles.Arcade +*/ +Phaser.Particles.Arcade = {}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Emitter is a lightweight particle emitter that uses Arcade Physics. +* It can be used for one-time explosions or for continuous effects like rain and fire. +* All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. +* +* @class Phaser.Particles.Arcade.Emitter +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. +* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. +* @param {number} [maxParticles=50] - The total number of particles in this emitter. +*/ +Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { + + /** + * @property {number} maxParticles - The total number of particles in this emitter. + * @default + */ + this.maxParticles = maxParticles || 50; + + Phaser.Group.call(this, game); + + /** + * @property {number} _id - Internal ID for this emitter -- only used by the Particle System in most cases + * @private + */ + this._id = this.game.particles.ID++; + + /** + * @property {string} name - A handy string name for this emitter. Can be set to anything. + */ + this.name = 'emitter' + this.id; + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.EMITTER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * @property {Phaser.Rectangle} area - The {@link #setSize size} of the emitter's emit area. The **actual** emit area is a rectangle of this size centered on (emitX, emitY): `{x: this.left, y: this.top, width: this.area.width, height: this.area.height}`. Particles are generated at a random position within this area. + * @default + */ + this.area = new Phaser.Rectangle(x, y, 1, 1); + + /** + * @property {?number} minAngle - The minimum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #maxAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.minAngle = null; + + /** + * @property {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #minAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.maxAngle = null; + + /** + * @property {number} minSpeed - The minimum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.minSpeed = 0; + + /** + * @property {number} maxSpeed - The maximum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.maxSpeed = 100; + + /** + * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle. + * @default + */ + this.minParticleSpeed = new Phaser.Point(-100, -100); + + /** + * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle. + * @default + */ + this.maxParticleSpeed = new Phaser.Point(100, 100); + + /** + * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. + * @default + */ + this.minParticleScale = 1; + + /** + * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. + * @default + */ + this.maxParticleScale = 1; + + /** + * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0. + */ + this.scaleData = null; + + /** + * @property {number} minRotation - The minimum possible angular velocity of a particle. + * @default + */ + this.minRotation = -360; + + /** + * @property {number} maxRotation - The maximum possible angular velocity of a particle. + * @default + */ + this.maxRotation = 360; + + /** + * @property {number} minParticleAlpha - The minimum possible alpha value of a particle. + * @default + */ + this.minParticleAlpha = 1; + + /** + * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle. + * @default + */ + this.maxParticleAlpha = 1; + + /** + * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0. + */ + this.alphaData = null; + + /** + * @property {function} particleClass - For emitting your own particle class types. They must extend Phaser.Particle. + * @default + */ + this.particleClass = Phaser.Particle; + + /** + * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter. + */ + this.particleDrag = new Phaser.Point(); + + /** + * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false). + * @default + */ + this.frequency = 100; + + /** + * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. + * @default + */ + this.lifespan = 2000; + + /** + * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. + */ + this.bounce = new Phaser.Point(); + + /** + * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. + * @default + */ + this.on = false; + + /** + * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) + * @default + */ + this.particleAnchor = new Phaser.Point(0.5, 0.5); + + /** + * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) + * @default + */ + this.blendMode = Phaser.blendModes.NORMAL; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitX + */ + this.emitX = x; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitY + */ + this.emitY = y; + + /** + * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. + */ + this.autoScale = false; + + /** + * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. + */ + this.autoAlpha = false; + + /** + * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. + * @default + */ + this.particleBringToTop = false; + + /** + * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. + * @default + */ + this.particleSendToBack = false; + + /** + * @property {object} counts - Records emitter activity. + * @property {number} counts.emitted - How many particles were emitted during the last update. + * @property {number} counts.failed - How many particles could not be emitted during the last update (because no particles were available). + * @property {number} counts.totalEmitted - How many particles have been emitted. + * @property {number} counts.totalFailed - How many particles could not be emitted when they were due (because no particles were available). + */ + this.counts = { + emitted: 0, + failed: 0, + totalEmitted: 0, + totalFailed: 0 + }; + + /** + * @property {Phaser.Point} _gravity - Internal gravity value. + * @private + */ + this._gravity = new Phaser.Point(0, 100); + + /** + * @property {Phaser.Point} _minParticleScale - Internal particle scale var. + * @private + */ + this._minParticleScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} _maxParticleScale - Internal particle scale var. + * @private + */ + this._maxParticleScale = new Phaser.Point(1, 1); + + /** + * @property {number} _total - Internal helper for deciding how many particles to launch (via {@link #start}). + * @private + */ + this._total = 0; + + /** + * @property {number} _timer - Internal helper for deciding when to launch particles or kill them. + * @private + */ + this._timer = 0; + + /** + * @property {number} _counter - Internal counter for figuring out how many particles to launch. + * @private + */ + this._counter = 0; + + /** + * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update. + * @private + */ + this._flowQuantity = 0; + + /** + * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total (via {@link #flow}). + * @private + */ + this._flowTotal = 0; + + /** + * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time). + * @private + */ + this._explode = true; + + /** + * @property {any} _frames - Internal helper for the particle frame. + * @private + */ + this._frames = null; + +}; + +Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); +Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter; + +/** +* Called automatically by the game loop, decides when to launch particles and when to "die". +* +* @method Phaser.Particles.Arcade.Emitter#update +*/ +Phaser.Particles.Arcade.Emitter.prototype.update = function () { + + this.counts.emitted = 0; + this.counts.failed = 0; + + if (this.on && this.game.time.time >= this._timer) + { + this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion; + + if (this._flowTotal !== 0) + { + if (this._flowQuantity > 0) + { + for (var i = 0; i < this._flowQuantity; i++) + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + break; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._total > 0 && this._counter >= this._total) + { + this.on = false; + } + } + } + + } + + var i = this.children.length; + + while (i--) + { + if (this.children[i].exists) + { + this.children[i].update(); + } + } + +}; + +/** +* This function generates a new set of particles for use by this emitter. +* The particles are stored internally waiting to be emitted via Emitter.start. +* +* @method Phaser.Particles.Arcade.Emitter#makeParticles +* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. +* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random. +* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. +* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. +* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. +* @param {object} [particleArguments=null] - Custom arguments to pass to your particle class +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds, particleArguments) { + + if (frames === undefined) { frames = 0; } + if (quantity === undefined) { quantity = this.maxParticles; } + if (collide === undefined) { collide = false; } + if (collideWorldBounds === undefined) { collideWorldBounds = false; } + if (particleArguments === undefined) { particleArguments = null; } + + var particle; + var i = 0; + var rndKey = keys; + var rndFrame = frames; + this._frames = frames; + + if (quantity > this.maxParticles) + { + this.maxParticles = quantity; + } + + while (i < quantity) + { + if (Array.isArray(keys)) + { + rndKey = this.game.rnd.pick(keys); + } + + if (Array.isArray(frames)) + { + rndFrame = this.game.rnd.pick(frames); + } + + particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame, particleArguments); + + this.game.physics.arcade.enable(particle, false); + + particle.body.checkCollision.none = !collide; + particle.body.collideWorldBounds = collideWorldBounds; + particle.body.skipQuadTree = true; + + particle.exists = false; + particle.visible = false; + particle.anchor.copyFrom(this.particleAnchor); + + this.add(particle); + + i++; + } + + return this; + +}; + +/** +* Call this function to turn off all the particles and the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#kill +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.kill = function () { + + this.on = false; + this.alive = false; + this.exists = false; + + return this; + +}; + +/** +* Handy for bringing game objects "back to life". Just sets alive and exists back to true. +* +* @method Phaser.Particles.Arcade.Emitter#revive +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.revive = function () { + + this.alive = true; + this.exists = true; + + return this; + +}; + +/** +* Call this function to emit the given quantity of particles at all once (an explosion) +* +* @method Phaser.Particles.Arcade.Emitter#explode +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [quantity=this.maxParticles] - How many particles to launch. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) { + + if (quantity === undefined) { + quantity = this.maxParticles; + } + + this._flowTotal = 0; + + this.start(true, lifespan, 0, quantity, false); + + return this; + +}; + +/** +* Call this function to start emitting a flow of particles. +* `quantity` particles are released every interval of `frequency` ms until `total` particles have been released (or forever). +* If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 × 5 = 20 total) and then turn {@link #on off}. +* If you set the total to be -1 then no quantity cap is used and it will keep emitting (as long as there are inactive particles available). +* +* {@link #output}, {@link #lifespanOutput}, and {@link #remainder} describe the particle flow rate. +* During a stable flow, the number of active particles approaches {@link #lifespanOutput} and the number of inactive particles approaches {@link #remainder}. +* If {@link #remainder} is less than 0, there will likely be no particles available for a portion of the flow (see {@link #count}). +* +* @method Phaser.Particles.Arcade.Emitter#flow +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of particles, given in ms. Values between 0 and 16.66 will behave the same (60 releases per second). +* @param {number} [quantity=1] - How many particles to launch at each interval. Not larger than {@link #maxParticles}. +* @param {number} [total=-1] - Turn {@link #on off} after launching this many particles in total. If -1 it will carry on indefinitely. +* @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) { + + if (frequency === undefined || frequency === null) { frequency = 250; } + if (quantity === undefined || quantity === 0) { quantity = 1; } + if (total === undefined) { total = -1; } + if (immediate === undefined) { immediate = true; } + + if (quantity > this.maxParticles) + { + quantity = this.maxParticles; + } + + this._counter = 0; + this._flowQuantity = quantity; + this._flowTotal = total; + + if (immediate) + { + this.start(true, lifespan, frequency, quantity); + + this._counter += quantity; + this.on = true; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + else + { + this.start(false, lifespan, frequency, quantity); + } + + return this; + +}; + +/** +* Start emitting particles. +* +* {@link #explode} and {@link #flow} are simpler methods. +* +* There are two patterns, based on the `explode` argument: +* +* ##### explode=true +* +* start(true, lifespan=0, null, total) +* +* When `explode` is true or `forceQuantity` is true, `start` emits `total` particles immediately. You should pass a nonzero `total`. +* +* ##### explode=false +* +* start(false, lifespan=0, frequency=250, total=0) +* +* When `explode` is false and `forceQuantity` is false, `start` emits 1 particle every interval of `frequency` ms. If `total` is not zero, the emitter turns itself off after `total` particles have been released. If `total` is zero, the emitter keeps emitting particles as long as they are available. To emit more than 1 particle per flow interval, use {@link #flow} instead. +* +* `forceQuantity` seems equivalent to `explode` and can probably be avoided. +* +* @method Phaser.Particles.Arcade.Emitter#start +* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false). +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of 1 particle, when `explode` is false. Value given in ms. Ignored if `explode` is set to true. +* @param {number} [total=0] - Turn {@link #on off} after launching this many particles in total. +* @param {number} [forceQuantity=false] - Equivalent to `explodes`. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, total, forceQuantity) { + + if (explode === undefined) { explode = true; } + if (lifespan === undefined) { lifespan = 0; } + if (frequency === undefined || frequency === null) { frequency = 250; } + if (total === undefined) { total = 0; } + if (forceQuantity === undefined) { forceQuantity = false; } + + if (total > this.maxParticles) + { + total = this.maxParticles; + } + + this.revive(); + + this.visible = true; + + this.lifespan = lifespan; + this.frequency = frequency; + + if (explode || forceQuantity) + { + for (var i = 0; i < total; i++) + { + this.emitParticle(); + } + } + else + { + this.on = true; + this._total = total; + this._counter = 0; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + + return this; + +}; + +/** +* This function is used internally to emit the next particle in the queue. +* +* However it can also be called externally to emit a particle. +* +* When called externally you can use the arguments to override any defaults the Emitter has set. +* +* The newly emitted particle is available in {@link Phaser.Particles.Arcade.Emitter#cursor}. +* +* @method Phaser.Particles.Arcade.Emitter#emitParticle +* @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. +* @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {boolean} True if a particle was emitted, otherwise false. +*/ +Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + var particle = this.getNextParticle(); + + if (particle === null) + { + this.counts.failed++; + this.counts.totalFailed++; + + return false; + } + + this.counts.emitted++; + this.counts.totalEmitted++; + + var rnd = this.game.rnd; + + if (key !== undefined && frame !== undefined) + { + particle.loadTexture(key, frame); + } + else if (key !== undefined) + { + particle.loadTexture(key); + particle.frame = Array.isArray(this._frames) ? rnd.pick(this._frames) : this._frames; + } + + var emitX = this.emitX; + var emitY = this.emitY; + + if (x !== null) + { + emitX = x; + } + else if (this.width > 1) + { + emitX = rnd.between(this.left, this.right); + } + + if (y !== null) + { + emitY = y; + } + else if (this.height > 1) + { + emitY = rnd.between(this.top, this.bottom); + } + + this.resetParticle(particle, emitX, emitY); + + return true; + +}; + + +/** +* Helper for {@link #emitParticle}. Gets the next available particle. +* +* @private +* @return {?Phaser.Particle} The first particle with exists=false, or null +*/ +Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () { + + var i = this.length; + + while (i--) + { + var next = this.next(); + + if (!next.exists) + { + return next; + } + } + + return null; + +}; + +/** + * Helper for {@link #emitParticle}. Sets particle properties and calls {@link Particle#onEmit}. + * + * @private + * @param {Phaser.Particle} particle + * @param {number} x + * @param {number} y + */ +Phaser.Particles.Arcade.Emitter.prototype.resetParticle = function (particle, x, y) { + + var rnd = this.game.rnd; + + particle.reset(x, y); + + 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(rnd.realInRange(this.minParticleScale, this.maxParticleScale)); + } + else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y)) + { + particle.scale.set(rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y)); + } + else + { + particle.scale.set(this._minParticleScale.x, this._minParticleScale.y); + } + + if (this.autoAlpha) + { + particle.setAlphaData(this.alphaData); + } + else + { + particle.alpha = rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha); + } + + particle.blendMode = this.blendMode; + + var body = particle.body; + + body.updateBounds(); + + body.bounce.copyFrom(this.bounce); + body.drag.copyFrom(this.particleDrag); + + if (this.minAngle != null && this.maxAngle != null) + { + this.game.physics.arcade.velocityFromAngle( + (this.minAngle === this.maxAngle) ? this.minAngle : rnd.between(this.minAngle, this.maxAngle), + (this.minSpeed === this.maxSpeed) ? this.minSpeed : rnd.between(this.minSpeed, this.maxSpeed), + body.velocity + ); + } + else + { + body.velocity.x = rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x); + body.velocity.y = rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y); + } + + body.angularVelocity = rnd.between(this.minRotation, this.maxRotation); + body.gravity.copyFrom(this.gravity); + body.angularDrag = this.angularDrag; + + particle.onEmit(); + +}; + +/** +* Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. +* +* @method Phaser.Particles.Arcade.Emitter#destroy +*/ +Phaser.Particles.Arcade.Emitter.prototype.destroy = function () { + + this.game.particles.remove(this); + + Phaser.Group.prototype.destroy.call(this, true, false); + +}; + +/** +* A more compact way of setting the width and height of the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#setSize +* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). +* @param {number} height - The desired height of the emitter. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { + + this.area.width = width; + this.area.height = height; + + return this; + +}; + +/** +* A more compact way of setting the X velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setXSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.x = min; + this.maxParticleSpeed.x = max; + + return this; + +}; + +/** +* A more compact way of setting the Y velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setYSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.y = min; + this.maxParticleSpeed.y = max; + + return this; + +}; + +/** +* A more compact way of setting the angular velocity constraints of the particles. +* +* @method Phaser.Particles.Arcade.Emitter#setRotation +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minRotation = min; + this.maxRotation = max; + + return this; + +}; + +/** +* A more compact way of setting the alpha constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. +* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setAlpha +* @param {number} [min=1] - The minimum value for this range. +* @param {number} [max=1] - The maximum value for this range. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) { + + if (min === undefined) { min = 1; } + if (max === undefined) { max = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.alphaData.reverse(); + this.autoAlpha = true; + } + + return this; + +}; + +/** +* A more compact way of setting the scale constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. +* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setScale +* @param {number} [minX=1] - The minimum value of Particle.scale.x. +* @param {number} [maxX=1] - The maximum value of Particle.scale.x. +* @param {number} [minY=1] - The minimum value of Particle.scale.y. +* @param {number} [maxY=1] - The maximum value of Particle.scale.y. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) { + + if (minX === undefined) { minX = 1; } + if (maxX === undefined) { maxX = 1; } + if (minY === undefined) { minY = 1; } + if (maxY === undefined) { maxY = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (yoyo === undefined) { yoyo = false; } + + // Reset these + 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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.scaleData.reverse(); + this.autoScale = true; + } + + return this; + +}; + +/** + * Sets a radial pattern for emitting particles. + * + * This is a shorthand for setting {@link #minAngle}, {@link #maxAngle}, {@link #minSpeed}, and {@link #maxSpeed}. + * + * To remove the radial pattern, use `setAngle(null, null)`. + * + * @method Phaser.Particles.Arcade.Emitter#setAngle + * @param {?number} minAngle - The minimum angle of initial particle velocities, in degrees. + * @param {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. + * @param {number} [minSpeed] - The minimum initial particle speed. + * @param {number} [maxSpeed] - The maximum initial particle speed. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ +Phaser.Particles.Arcade.Emitter.prototype.setAngle = function (minAngle, maxAngle, minSpeed, maxSpeed) { + + this.minAngle = minAngle; + this.maxAngle = maxAngle; + + if (minSpeed != null) { this.minSpeed = minSpeed; } + if (maxSpeed != null) { this.maxSpeed = maxSpeed; } + + return this; + +}; + +/** +* Change the emitter's center to match the center of any object with a `center` property, such as an Arcade Body. +* If the object doesn't have a `center` property it will be set to the object's anchor-adjusted world position (`object.world`). +* +* @method Phaser.Particles.Arcade.Emitter#at +* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +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); + } + + return this; + +}; + +/** + * @name Phaser.Particles.Arcade.Emitter#gravity + * @property {Phaser.Point} gravity - Sets the `body.gravity` of each particle sprite to this on launch. + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "gravity", { + + get: function () { + return this._gravity; + }, + + set: function (value) { + if (typeof value === "number") + { + this._gravity.y = value; + } + else + { + this._gravity = value; + } + } + +}); + + +/** +* @name Phaser.Particles.Arcade.Emitter#id +* @property {number} id - Gets the internal ID that represents this emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "id", { + get: function () { + return this._id; + } +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#width +* @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", { + + get: function () { + return this.area.width; + }, + + set: function (value) { + this.area.width = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#height +* @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", { + + get: function () { + return this.area.height; + }, + + set: function (value) { + this.area.height = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#x +* @property {number} x - Gets or sets the x position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", { + + get: function () { + return this.emitX; + }, + + set: function (value) { + this.emitX = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#y +* @property {number} y - Gets or sets the y position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", { + + get: function () { + return this.emitY; + }, + + set: function (value) { + this.emitY = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#left +* @property {number} left - Gets the left position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", { + + get: function () { + return Math.floor(this.x - (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#right +* @property {number} right - Gets the right position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", { + + get: function () { + return Math.floor(this.x + (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#top +* @property {number} top - Gets the top position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", { + + get: function () { + return Math.floor(this.y - (this.area.height / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#bottom +* @property {number} bottom - Gets the bottom position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", { + + get: function () { + return Math.floor(this.y + (this.area.height / 2)); + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#output + * @property {number} output - The number of particles released per second, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "output", { + + get: function () { + return 1000 * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#lifespanOutput + * @property {number} lifespanOutput - The number of particles released during one particle's {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "lifespanOutput", { + + get: function () { + return (this.lifespan === 0 ? Infinity : this.lifespan) * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#remainder + * @property {number} remainder - The expected number of unreleased particles after a flow interval of {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "remainder", { + + get: function () { + return this.maxParticles - this.lifespanOutput; + } + +}); + +/** +* The last particle released, if any. +* +* You should treat this as read-only (and also avoid {@link #next} and {@link #previous}) once the emitter is started. Phaser uses it internally to track particles. +* +* @name Phaser.Particles.Arcade.Emitter#cursor +* @property {?DisplayObject} cursor +* @readonly +*/ +// Inherited from Phaser.Group#cursor + +/** +* Advances the cursor to the next particle. +* +* @method Phaser.Particles.Arcade.Emitter#next +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#next + +/** +* Moves the group cursor to the previous particle. +* +* @method Phaser.Particles.Arcade.Emitter#previous +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#previous + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Weapon Plugin provides the ability to easily create a bullet pool and manager. +* +* Weapons fire {@link Phaser.Bullet} objects, which are essentially Sprites with a few extra properties. +* The Bullets are enabled for {@link Phaser.Physics.Arcade Arcade Physics}. They do not currently work with P2 Physics. +* +* The Bullets are created inside of {@link #bullets weapon.bullets}, which is a {@link Phaser.Group} instance. Anything you +* can usually do with a Group, such as move it around the display list, iterate it, etc can be done +* to the bullets Group too. +* +* Bullets can have textures and even animations. You can control the speed at which they are fired, +* the firing rate, the firing angle, and even set things like gravity for them. +* +* A small example, using {@link Phaser.GameObjectFactory#weapon add.weapon}, assumed to be running from within a {@link Phaser.State#create} method: +* +* ```javascript +* var weapon = this.add.weapon(10, 'bullet'); +* weapon.fireFrom.set(300, 300); +* this.input.onDown.add(weapon.fire, this); +* ``` +* +* If you want to (re)create the bullet pool separately, you can use: +* +* ```javascript +* var weapon = this.game.plugins.add(Phaser.Weapon); +* // … +* weapon.createBullets(10, 'bullet'); +* ``` +* +* @class Phaser.Weapon +* @constructor +* @param {Phaser.Game} game - A reference to the current Phaser.Game instance. +* @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin. +*/ +Phaser.Weapon = function (game, parent) { + + Phaser.Plugin.call(this, game, parent); + + /** + * This is the Phaser.Group that contains all of the bullets managed by this plugin. + * @type {Phaser.Group} + */ + this.bullets = null; + + /** + * Should the bullet pool run out of bullets (i.e. they are all in flight) then this + * boolean controls if the Group will create a brand new bullet object or not. + * @type {boolean} + * @default + */ + this.autoExpandBulletsGroup = false; + + /** + * Will this weapon auto fire? If set to true then a new bullet will be fired + * based on the {@link #fireRate} value. + * @type {boolean} + * @default + */ + this.autofire = false; + + /** + * The total number of bullets this Weapon has fired so far. + * You can limit the number of shots allowed (via {@link #fireLimit}), and reset + * this total via {@link #resetShots}. + * @type {number} + * @default + */ + this.shots = 0; + + /** + * The maximum number of shots that this Weapon is allowed to fire before it stops. + * When the limit is his the {@link #onFireLimit} Signal is dispatched. + * You can reset the shot counter via {@link #resetShots}. + * @type {number} + * @default + */ + this.fireLimit = 0; + + /** + * The minimum interval between shots, in milliseconds. + * @type {number} + * @default + */ + this.fireRate = 100; + + /** + * This is a modifier that is added to the {@link #fireRate} each update to add variety + * to the firing rate of the Weapon. The value is given in milliseconds. + * If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual + * firing rate of the Weapon will be between 150 and 250. + * @type {number} + * @default + */ + this.fireRateVariance = 0; + + /** + * This is a Rectangle from within which the bullets are fired. By default it's a 1x1 + * rectangle, the equivalent of a Point. But you can change the width and height, and if + * larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from. + * @type {Phaser.Rectangle} + */ + this.fireFrom = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE_UP + * or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right. + * @type {integer} + * @default + */ + this.fireAngle = Phaser.ANGLE_UP; + + /** + * When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set. + * @type {boolean} + * @default + */ + this.bulletInheritSpriteSpeed = false; + + /** + * The string based name of the animation that the Bullet will be given on launch. + * This is set via {@link #addBulletAnimation}. + * @type {string} + * @default + */ + this.bulletAnimation = ''; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to pick a random frame from the set. + * @type {boolean} + * @default + */ + this.bulletFrameRandom = false; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to use the next frame in the set. The frame index is then + * advanced one frame until it reaches the end of the set, then it starts from the start + * again. Cycling frames like this allows you to create varied bullet effects via + * sprite sheets. + * @type {boolean} + * @default + */ + this.bulletFrameCycle = false; + + /** + * Should the Bullets wrap around the world bounds? This automatically calls + * `World.wrap` on the Bullet each frame. See the docs for that method for details. + * @type {boolean} + * @default + */ + this.bulletWorldWrap = false; + + /** + * If `bulletWorldWrap` is true then you can provide an optional padding value with this + * property. It's added to the calculations determining when the Bullet should wrap around + * the world or not. The value is given in pixels. + * @type {integer} + * @default + */ + this.bulletWorldWrapPadding = 0; + + /** + * An optional angle offset applied to the Bullets when they are launched. + * This is useful if for example your bullet sprites have been drawn facing up, instead of + * to the right, and you want to fire them at an angle. In which case you can set the + * angle offset to be 90 and they'll be properly rotated when fired. + * @type {number} + * @default + */ + this.bulletAngleOffset = 0; + + /** + * This is a variance added to the angle of Bullets when they are fired. + * If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual + * angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a + * great 'spread' effect to a Weapon. + * @type {number} + * @default + */ + this.bulletAngleVariance = 0; + + /** + * The initial velocity of fired bullets, in pixels per second. + * @type {number} + * @default + */ + this.bulletSpeed = 200; + + /** + * This is a variance added to the speed of Bullets when they are fired. + * If bullets have a {@link #bulletSpeed} value of 200, and a `bulletSpeedVariance` of 50 + * then the actual speed of the Bullets will be between 150 and 250 pixels per second. + * @type {number} + * @default + */ + this.bulletSpeedVariance = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount + * of lifespan the Bullets have set on launch. The value is given in milliseconds. + * When a Bullet hits its lifespan limit it will be automatically killed. + * @type {number} + * @default + */ + this.bulletLifespan = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_DISTANCE` this controls the distance + * the Bullet can travel before it is automatically killed. The distance is given in pixels. + * @type {number} + * @default + */ + this.bulletKillDistance = 0; + + /** + * This is the amount of {@link Phaser.Physics.Arcade.Body#gravity} added to the Bullets physics body when fired. + * Gravity is expressed in pixels / second / second. + * @type {Phaser.Point} + */ + this.bulletGravity = new Phaser.Point(0, 0); + + /** + * Bullets can optionally adjust their rotation in-flight to match their velocity. + * This can create the effect of a bullet 'pointing' to the path it is following, for example + * an arrow being fired from a bow, and works especially well when added to {@link #bulletGravity}. + * @type {boolean} + * @default + */ + this.bulletRotateToVelocity = false; + + /** + * The Texture Key that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string} + * @default + */ + this.bulletKey = ''; + + /** + * The Texture Frame that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string|integer} + * @default + */ + this.bulletFrame = ''; + + /** + * Private var that holds the public `bulletClass` property. + * @type {function} + * @private + */ + this._bulletClass = Phaser.Bullet; + + /** + * Private var that holds the public `bulletCollideWorldBounds` property. + * @type {boolean} + * @private + */ + this._bulletCollideWorldBounds = false; + + /** + * Private var that holds the public `bulletKillType` property. + * @type {integer} + * @private + */ + this._bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; + + /** + * Holds internal data about custom bullet body sizes. + * + * @type {Object} + * @private + */ + this._data = { + customBody: false, + width: 0, + height: 0, + offsetX: 0, + offsetY: 0 + }; + + /** + * This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not. + * It's used in combination with {@link #bulletKillType} when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS` + * or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored. + * If you are tracking a Sprite or Point then the bounds are centered on that object every frame. + * + * @type {Phaser.Rectangle} + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The Rectangle used to calculate the bullet bounds from. + * + * @type {Phaser.Rectangle} + * @private + */ + this.bulletBounds = game.world.bounds; + + /** + * This array stores the frames added via @link #setBulletFrames. + * + * @type {Array} + * @protected + */ + this.bulletFrames = []; + + /** + * The index of the frame within {@link #bulletFrames} that is currently being used. + * This value is only used if {@link #bulletFrameCycle} is set to `true`. + * @type {number} + * @private + */ + this.bulletFrameIndex = 0; + + /** + * An internal object that stores the animation data added via {@link #addBulletAnimation}. + * @type {Object} + * @private + */ + this.anims = {}; + + /** + * The onFire Signal is dispatched each time {@link #fire} is called, and a Bullet is + * _successfully_ launched. The callback is set two arguments: a reference to the bullet sprite itself, + * and a reference to the Weapon that fired the bullet. + * + * @type {Phaser.Signal} + */ + this.onFire = new Phaser.Signal(); + + /** + * The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result + * of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance. + * The callback is sent one argument: A reference to the bullet sprite itself. + * + * @type {Phaser.Signal} + */ + this.onKill = new Phaser.Signal(); + + /** + * The onFireLimit Signal is dispatched if {@link #fireLimit} is > 0, and a bullet launch takes the number + * of shots fired to equal the fire limit. + * The callback is sent two arguments: A reference to this Weapon, and the value of + * {@link #fireLimit}. + * + * @type {Phaser.Signal} + */ + this.onFireLimit = new Phaser.Signal(); + + /** + * The Sprite currently being tracked by the Weapon, if any. + * This is set via the {@link #trackSprite} method. + * + * @type {Phaser.Sprite|Object} + */ + this.trackedSprite = null; + + /** + * The Pointer currently being tracked by the Weapon, if any. + * This is set via the {@link #trackPointer} method. + * + * @type {Phaser.Pointer} + */ + this.trackedPointer = null; + + /** + * If you want this Weapon to be able to fire more than 1 bullet in a single + * update, then set this property to `true`. When `true` the Weapon plugin won't + * set the shot / firing timers until the `postRender` phase of the game loop. + * This means you can call `fire` (and similar methods) as often as you like in one + * single game update. + * + * @type {boolean} + * @default + */ + this.multiFire = false; + + /** + * Internal multiFire test flag. + * + * @type {boolean} + */ + this._hasFired = false; + + /** + * If the Weapon is tracking a Sprite, should it also track the Sprites rotation? + * This is useful for a game such as Asteroids, where you want the weapon to fire based + * on the sprites rotation. + * + * @type {boolean} + * @default + */ + this.trackRotation = false; + + /** + * The Track Offset is a Point object that allows you to specify a pixel offset that bullets use + * when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels + * in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have + * the bullet launched from the center of the Sprite. + * + * @type {Phaser.Point} + */ + this.trackOffset = new Phaser.Point(); + + /** + * Internal firing rate time tracking variable. + * + * @type {number} + * @private + */ + this._nextFire = 0; + + /** + * Internal firing rate time tracking variable used by multiFire. + * + * @type {number} + * @private + */ + this._tempNextFire = 0; + + /** + * Internal firing rotation tracking point. + * + * @type {Phaser.Point} + * @private + */ + this._rotatedPoint = new Phaser.Point(); + +}; + +Phaser.Weapon.prototype = Object.create(Phaser.Plugin.prototype); +Phaser.Weapon.prototype.constructor = Phaser.Weapon; + +/** +* A {@link #bulletKillType} constant that stops the bullets from ever being destroyed automatically. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_NEVER = 0; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when their {@link #bulletLifespan} expires. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_LIFESPAN = 1; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets after they +* exceed the {@link #bulletDistance} from their original firing position. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_DISTANCE = 2; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WEAPON_BOUNDS = 3; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.Camera#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_CAMERA_BOUNDS = 4; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.World#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WORLD_BOUNDS = 5; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_STATIC_BOUNDS = 6; + +/** +* This method performs two actions: First it will check to see if the {@link #bullets} Group exists or not, +* and if not it creates it, adding it the `group` given as the 4th argument. +* +* Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame +* provided (if any). +* +* If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets +* in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of +* the in-flight bullets have been killed, freeing them up for use by the Weapon again. +* +* If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will +* keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however, +* so be careful it doesn't grow too large. +* +* You can either set the texture key and frame here, or via the {@link #bulletKey} and {@link #bulletFrame} +* properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a +* single Weapon instance must share the same texture key however. +* +* @method Phaser.Weapon#createBullets +* @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. +* @param {string} [key] - The Game.cache key of the image that this Sprite will use. +* @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. +* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.createBullets = function (quantity, key, frame, group) { + + if (quantity === undefined) { quantity = 1; } + if (group === undefined) { group = this.game.world; } + + if (this.bullets && !this.bullets.game) + { + this.bullets = null; + } + + if (!this.bullets) + { + this.bullets = this.game.add.physicsGroup(Phaser.Physics.ARCADE, group); + this.bullets.classType = this._bulletClass; + } + + if (quantity !== 0) + { + if (quantity === -1) + { + this.autoExpandBulletsGroup = true; + quantity = 1; + } + + this.bullets.createMultiple(quantity, key, frame); + + this.bullets.setAll('data.bulletManager', this); + + this.bulletKey = key; + this.bulletFrame = frame; + } + + return this; + +}; + +/** +* Call a function on each in-flight bullet in this Weapon. +* +* See {@link Phaser.Group#forEachExists forEachExists} for more details. +* +* @method Phaser.Weapon#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.forEach = function (callback, callbackContext) { + + this.bullets.forEachExists(callback, callbackContext, arguments); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `false` on each bullet in this Weapon. +* This has the effect of stopping them in-flight should they be moving. +* It also stops them being able to be checked for collision. +* +* @method Phaser.Weapon#pauseAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.pauseAll = function () { + + this.bullets.setAll('body.enable', false); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `true` on each bullet in this Weapon. +* This has the effect of resuming their motion should they be in-flight. +* It also enables them for collision checks again. +* +* @method Phaser.Weapon#resumeAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resumeAll = function () { + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Calls {@link Phaser.Bullet#kill} on every in-flight bullet in this Weapon. +* Also re-enables their physics bodies, should they have been disabled via {@link #pauseAll}. +* +* @method Phaser.Weapon#killAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.killAll = function () { + + this.bullets.callAllExists('kill', true); + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Resets the {@link #shots} counter back to zero. This is used when you've set +* {@link #fireLimit} and have hit (or just wish to reset) your limit. +* +* @method Phaser.Weapon#resetShots +* @param {integer} [newLimit] - Optionally set a new {@link #fireLimit}. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resetShots = function (newLimit) { + + this.shots = 0; + + if (newLimit !== undefined) + { + this.fireLimit = newLimit; + } + + return this; + +}; + +/** +* Destroys this Weapon. It removes itself from the PluginManager, destroys +* the {@link #bullets} Group, and nulls internal references. +* +* @method Phaser.Weapon#destroy +*/ +Phaser.Weapon.prototype.destroy = function () { + + this.parent.remove(this, false); + + this.bullets.destroy(); + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#update +* @protected +*/ +Phaser.Weapon.prototype.update = function () { + + if (this._bulletKillType === Phaser.Weapon.KILL_WEAPON_BOUNDS) + { + if (this.trackedSprite) + { + this.trackedSprite.updateTransform(); + this.bounds.centerOn(this.trackedSprite.worldPosition.x, this.trackedSprite.worldPosition.y); + } + else if (this.trackedPointer) + { + this.bounds.centerOn(this.trackedPointer.worldX, this.trackedPointer.worldY); + } + } + + if (this.autofire) + { + this.fire(); + } + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#postRender +* @protected +*/ +Phaser.Weapon.prototype.postRender = function () { + + if (!this.multiFire || !this._hasFired) + { + return; + } + + this._hasFired = false; + + this._nextFire = this._tempNextFire; + +}; + +/** +* Sets this Weapon to track the given Sprite, or any Object with a public {@link Phaser.Component.Core#world world} Point object. +* When a Weapon tracks a Sprite it will automatically update its {@link #fireFrom} value to match the Sprite's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location. +* +* Calling `trackSprite` will reset {@link #trackedPointer} to null, should it have been set, as you can +* only track _either_ a Sprite, or a Pointer, at once, but not both. +* +* @method Phaser.Weapon#trackSprite +* @param {Phaser.Sprite|Object} sprite - The Sprite to track the position of. +* @param {integer} [offsetX=0] - The horizontal offset from the Sprites position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Sprites position to be applied to the Weapon. +* @param {boolean} [trackRotation=false] - Should the Weapon also track the Sprites rotation? +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackSprite = function (sprite, offsetX, offsetY, trackRotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (trackRotation === undefined) { trackRotation = false; } + + this.trackedPointer = null; + this.trackedSprite = sprite; + this.trackRotation = trackRotation; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Sets this Weapon to track the given Pointer. +* When a Weapon tracks a Pointer it will automatically update its {@link #fireFrom} value to match the Pointer's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location. +* +* Calling `trackPointer` will reset {@link #trackedSprite} to null, should it have been set, as you can +* only track _either_ a Pointer, or a Sprite, at once, but not both. +* +* @method Phaser.Weapon#trackPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to track the position of. Defaults to `Input.activePointer` if not specified. +* @param {integer} [offsetX=0] - The horizontal offset from the Pointers position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Pointers position to be applied to the Weapon. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackPointer = function (pointer, offsetX, offsetY) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this.trackedPointer = pointer; + this.trackedSprite = null; + this.trackRotation = false; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Attempts to fire multiple bullets from the positions defined in the given array. +* +* If you provide a `from` argument, or if there is a tracked Sprite or Pointer, then +* the positions are treated as __offsets__ from the given objects position. +* +* If `from` is undefined, and there is no tracked object, then the bullets are fired +* from the given positions, as they exist in the world. +* +* Calling this method sets {@link #multiFire} to `true`. +* +* If there are not enough bullets available in the pool, and the pool cannot be extended, +* then this method may not fire from all of the given positions. +* +* When the bullets are launched they have their texture and frame updated, as required. +* The velocity of the bullets are calculated based on Weapon properties like {@link #bulletSpeed}. +* +* @method Phaser.Weapon#fireMany +* @param {array} positions - An array of positions. Each position can be any Object, as long as it has public `x` and `y` properties, such as Phaser.Point, { x: 0, y: 0 }, Phaser.Sprite, etc. +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullets **from** the `x` and `y` properties of this object, _instead_ of any {@link #trackedSprite} or `trackedPointer` that is set. +* @return {array} An array containing all of the fired Phaser.Bullet objects, if a launch was successful, otherwise an empty array. +*/ +Phaser.Weapon.prototype.fireMany = function (positions, from) { + + this.multiFire = true; + + var bullets = []; + + var _this = this; + + if (from || this.trackedSprite || this.trackedPointer) + { + positions.forEach(function(offset) { + + bullets.push(_this.fire(from, null, null, offset.x, offset.y)); + + }); + } + else + { + positions.forEach(function(position) { + + bullets.push(_this.fire(position)); + + }); + } + + return bullets; + +}; + +/** +* Attempts to fire a single Bullet from a tracked Sprite or Pointer, but applies an offset +* to the position first. This is the same as calling {@link #fire} and passing in the offset arguments. +* +* If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like {@link #bulletSpeed}. +* +* If you wish to fire multiple bullets in a single game update, then set {@link #multiFire} to `true` +* and you can call this method as many times as you like, per loop. See also {@link #fireMany}. +* +* @method Phaser.Weapon#fireOffset +* @param {number} [offsetX=0] - The horizontal offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @param {number} [offsetY=0] - The vertical offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fireOffset = function (offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + return this.fire(null, null, null, offsetX, offsetY); + +}; + +/** +* Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at. +* +* If you don't provide any of the arguments then it uses those set via properties such as {@link #trackedSprite}, +* {@link #bulletAngle} and so on. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like `bulletSpeed`. +* +* If you wish to fire multiple bullets in a single game update, then set `Weapon.multiFire = true` +* and you can call `fire` as many times as you like, per loop. Multiple fires in a single update +* only counts once towards the `shots` total, but you will still receive a Signal for each bullet. +* +* @method Phaser.Weapon#fire +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides {@link #trackedSprite} or `trackedPointer`. Pass `null` to ignore it. +* @param {number} [x] - The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [offsetX=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a horizontal offset from the launch position. +* @param {number} [offsetY=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a vertical offset from the launch position. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fire = function (from, x, y, offsetX, offsetY) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (this.game.time.now < this._nextFire || (this.fireLimit > 0 && this.shots === this.fireLimit)) + { + return null; + } + + var speed = this.bulletSpeed; + + // Apply +- speed variance + if (this.bulletSpeedVariance !== 0) + { + speed += Phaser.Math.between(-this.bulletSpeedVariance, this.bulletSpeedVariance); + } + + if (from) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(from.x, from.y); + } + else + { + this.fireFrom.x = from.x; + this.fireFrom.y = from.y; + } + } + else if (this.trackedSprite) + { + if (this.trackRotation) + { + this._rotatedPoint.set(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.worldRotation); + + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this._rotatedPoint.x, this._rotatedPoint.y); + } + else + { + this.fireFrom.x = this._rotatedPoint.x; + this.fireFrom.y = this._rotatedPoint.y; + } + } + else + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedSprite.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedSprite.world.y + this.trackOffset.y; + } + } + + if (this.bulletInheritSpriteSpeed) + { + speed += this.trackedSprite.body.speed; + } + } + else if (this.trackedPointer) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedPointer.world.x + this.trackOffset.x, this.trackedPointer.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedPointer.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedPointer.world.y + this.trackOffset.y; + } + } + + if (offsetX !== undefined) + { + this.fireFrom.x += offsetX; + } + + if (offsetY !== undefined) + { + this.fireFrom.y += offsetY; + } + + var fromX = (this.fireFrom.width > 1) ? this.fireFrom.randomX : this.fireFrom.x; + var fromY = (this.fireFrom.height > 1) ? this.fireFrom.randomY : this.fireFrom.y; + + var angle = (this.trackRotation) ? this.trackedSprite.angle : this.fireAngle; + + // The position (in world space) to fire the bullet towards, if set + if (x !== null && y !== null) + { + angle = this.game.math.radToDeg(Math.atan2(y - fromY, x - fromX)); + } + + // Apply +- angle variance + if (this.bulletAngleVariance !== 0) + { + angle += Phaser.Math.between(-this.bulletAngleVariance, this.bulletAngleVariance); + } + + var moveX = 0; + var moveY = 0; + + // Avoid sin/cos for right-angled shots + if (angle === 0 || angle === 180) + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + } + else if (angle === 90 || angle === 270) + { + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + else + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + + var bullet = null; + + if (this.autoExpandBulletsGroup) + { + bullet = this.bullets.getFirstExists(false, true, fromX, fromY, this.bulletKey, this.bulletFrame); + + bullet.data.bulletManager = this; + } + else + { + bullet = this.bullets.getFirstExists(false); + } + + if (bullet) + { + bullet.reset(fromX, fromY); + + bullet.data.fromX = fromX; + bullet.data.fromY = fromY; + bullet.data.killType = this.bulletKillType; + bullet.data.killDistance = this.bulletKillDistance; + bullet.data.rotateToVelocity = this.bulletRotateToVelocity; + + if (this.bulletKillType === Phaser.Weapon.KILL_LIFESPAN) + { + bullet.lifespan = this.bulletLifespan; + } + + bullet.angle = angle + this.bulletAngleOffset; + + // Frames and Animations + if (this.bulletAnimation !== '') + { + if (bullet.animations.getAnimation(this.bulletAnimation) === null) + { + var anim = this.anims[this.bulletAnimation]; + + bullet.animations.add(anim.name, anim.frames, anim.frameRate, anim.loop, anim.useNumericIndex); + } + + bullet.animations.play(this.bulletAnimation); + } + else + { + if (this.bulletFrameCycle) + { + bullet.frame = this.bulletFrames[this.bulletFrameIndex]; + + this.bulletFrameIndex++; + + if (this.bulletFrameIndex >= this.bulletFrames.length) + { + this.bulletFrameIndex = 0; + } + } + else if (this.bulletFrameRandom) + { + bullet.frame = this.bulletFrames[Math.floor(Math.random() * this.bulletFrames.length)]; + } + } + + if (bullet.data.bodyDirty) + { + if (this._data.customBody) + { + bullet.body.setSize(this._data.width, this._data.height, this._data.offsetX, this._data.offsetY); + } + + bullet.body.collideWorldBounds = this.bulletCollideWorldBounds; + + bullet.data.bodyDirty = false; + } + + bullet.body.velocity.set(moveX, moveY); + bullet.body.gravity.set(this.bulletGravity.x, this.bulletGravity.y); + + var next = 0; + + if (this.bulletSpeedVariance !== 0) + { + var rate = this.fireRate; + + rate += Phaser.Math.between(-this.fireRateVariance, this.fireRateVariance); + + if (rate < 0) + { + rate = 0; + } + + next = this.game.time.now + rate; + } + else + { + next = this.game.time.now + this.fireRate; + } + + if (this.multiFire) + { + if (!this._hasFired) + { + // We only add 1 to the 'shots' count for multiFire shots + this._hasFired = true; + this._tempNextFire = next; + this.shots++; + } + } + else + { + this._nextFire = next; + + this.shots++; + } + + this.onFire.dispatch(bullet, this, speed); + + if (this.fireLimit > 0 && this.shots === this.fireLimit) + { + this.onFireLimit.dispatch(this, this.fireLimit); + } + } + + return bullet; + +}; + +/** +* Fires a bullet **at** the given Pointer. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtPointer = function (pointer) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + + return this.fire(null, pointer.worldX, pointer.worldY); + +}; + +/** +* Fires a bullet **at** the given Sprite. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtSprite +* @param {Phaser.Sprite} [sprite] - The Sprite to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtSprite = function (sprite) { + + return this.fire(null, sprite.world.x, sprite.world.y); + +}; + +/** +* Fires a bullet **at** the given coordinates. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtXY +* @param {number} [x] - The x coordinate, in world space, to fire the bullet towards. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtXY = function (x, y) { + + return this.fire(null, x, y); + +}; + +/** +* You can modify the size of the physics Body the Bullets use to be any dimension you need. +* This allows you to make it smaller, or larger, than the parent Sprite. +* You can also control the x and y offset of the Body. This is the position of the +* Body relative to the top-left of the Sprite _texture_. +* +* For example: If you have a Sprite with a texture that is 80x100 in size, +* and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: +* +* `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, 34)` +* +* Where the first two parameters are the new Body size (32x32 pixels) relative to the Sprite's scale. +* 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 +* is the vertical offset. +* +* @method Phaser.Weapon#setBulletBodyOffset +* @param {number} width - The width of the Body. +* @param {number} height - The height of the Body. +* @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture. +* @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture. +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletBodyOffset = function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this._data.customBody = true; + this._data.width = width; + this._data.height = height; + this._data.offsetX = offsetX; + this._data.offsetY = offsetY; + + // Update all bullets in the pool + this.bullets.callAll('body.setSize', 'body', width, height, offsetX, offsetY); + this.bullets.setAll('data.bodyDirty', false); + + return this; + +}; + +/** +* Sets the texture frames that the bullets can use when being launched. +* +* This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet. +* +* It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values +* provided. Then it sets the frame index to be zero. +* +* You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames +* when they're fired, or pick one at random. +* +* @method Phaser.Weapon#setBulletFrames +* @param {integer} min - The minimum value the frame can be. Usually zero. +* @param {integer} max - The maximum value the frame can be. +* @param {boolean} [cycle=true] - Should the bullet frames cycle as they are fired? +* @param {boolean} [random=false] - Should the bullet frames be picked at random as they are fired? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletFrames = function (min, max, cycle, random) { + + if (cycle === undefined) { cycle = true; } + if (random === undefined) { random = false; } + + this.bulletFrames = Phaser.ArrayUtils.numberArray(min, max); + + this.bulletFrameIndex = 0; + + this.bulletFrameCycle = cycle; + this.bulletFrameRandom = random; + + return this; + +}; + +/** +* Adds a new animation under the given key. Optionally set the frames, frame rate and loop. +* The arguments are all the same as for `Animation.add`, and work in the same way. +* +* {@link #bulletAnimation} will be set to this animation after it's created. From that point on, all +* bullets fired will play using this animation. You can swap between animations by calling this method +* several times, and then just changing the {@link #bulletAnimation} property to the name of the animation +* you wish to play for the next launched bullet. +* +* If you wish to stop using animations at all, set {@link #bulletAnimation} to '' (an empty string). +* +* @method Phaser.Weapon#addBulletAnimation +* @param {string} name - The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast". +* @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.addBulletAnimation = function (name, frames, frameRate, loop, useNumericIndex) { + + this.anims[name] = { + name: name, + frames: frames, + frameRate: frameRate, + loop: loop, + useNumericIndex: useNumericIndex + }; + + // Add the animation to any existing bullets in the pool + this.bullets.callAll('animations.add', 'animations', name, frames, frameRate, loop, useNumericIndex); + + this.bulletAnimation = name; + + return this; + +}; + +/** +* Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets +* both in-flight, and available. And optionally the physics debug bodies of the bullets. +* +* @method Phaser.Weapon#debug +* @param {integer} [x=16] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {integer} [y=32] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {boolean} [debugBodies=false] - Optionally draw the physics body of every bullet in-flight. +*/ +Phaser.Weapon.prototype.debug = function (x, y, debugBodies) { + + if (x === undefined) { x = 16; } + if (y === undefined) { y = 32; } + if (debugBodies === undefined) { debugBodies = false; } + + this.game.debug.text("Weapon Plugin", x, y); + this.game.debug.text("Bullets Alive: " + this.bullets.total + " - Total: " + this.bullets.length, x, y + 24); + + if (debugBodies) + { + this.bullets.forEachExists(this.game.debug.body, this.game.debug, 'rgba(255, 0, 255, 0.8)'); + } + +}; + +/** +* The Class of the bullets that are launched by this Weapon. Defaults to {@link Phaser.Bullet}, but can be +* overridden before calling `createBullets` and set to your own class type. +* +* It should be a constructor function accepting `(game, x, y, key, frame)`. +* +* @name Phaser.Weapon#bulletClass +* @property {function} bulletClass +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletClass", { + + get: function () { + + return this._bulletClass; + + }, + + set: function (classType) { + + this._bulletClass = classType; + + // `this.bullets` exists only after createBullets() + if (this.bullets) { + this.bullets.classType = this._bulletClass; + } + } + +}); + +/** +* This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`. +* +* There are 7 different "kill types" available: +* +* * `Phaser.Weapon.KILL_NEVER` +* The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code. +* +* * `Phaser.Weapon.KILL_LIFESPAN` +* The bullets are automatically killed when their `bulletLifespan` amount expires. +* +* * `Phaser.Weapon.KILL_DISTANCE` +* The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position. +* +* * `Phaser.Weapon.KILL_WEAPON_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* +* * `Phaser.Weapon.KILL_CAMERA_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.Camera#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_WORLD_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.World#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_STATIC_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to +* match the position of a tracked sprite or pointer. +* +* @name Phaser.Weapon#bulletKillType +* @property {integer} bulletKillType +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletKillType", { + + get: function () { + + return this._bulletKillType; + + }, + + set: function (type) { + + switch (type) + { + case Phaser.Weapon.KILL_STATIC_BOUNDS: + case Phaser.Weapon.KILL_WEAPON_BOUNDS: + this.bulletBounds = this.bounds; + break; + + case Phaser.Weapon.KILL_CAMERA_BOUNDS: + this.bulletBounds = this.game.camera.view; + break; + + case Phaser.Weapon.KILL_WORLD_BOUNDS: + this.bulletBounds = this.game.world.bounds; + break; + } + + this._bulletKillType = type; + + } + +}); + +/** +* Should bullets collide with the World bounds or not? +* +* @name Phaser.Weapon#bulletCollideWorldBounds +* @property {boolean} bulletCollideWorldBounds +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletCollideWorldBounds", { + + get: function () { + + return this._bulletCollideWorldBounds; + + }, + + set: function (value) { + + this._bulletCollideWorldBounds = value; + + this.bullets.setAll('body.collideWorldBounds', value); + this.bullets.setAll('data.bodyDirty', false); + + } + +}); + +/** +* The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Weapon.prototype, "x", { + + get: function () { + + return this.fireFrom.x; + + }, + + set: function (value) { + + this.fireFrom.x = value; + } + +}); + +/** +* The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Weapon.prototype, "y", { + + get: function () { + + return this.fireFrom.y; + + }, + + set: function (value) { + + this.fireFrom.y = value; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites, +* with a few extra properties in the data object to handle Weapon specific features. +* +* @class Phaser.Bullet +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Bullet = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + this.anchor.set(0.5); + + this.data = { + bulletManager: null, + fromX: 0, + fromY: 0, + bodyDirty: true, + rotateToVelocity: false, + killType: 0, + killDistance: 0 + }; + +}; + +Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Bullet.prototype.constructor = Phaser.Bullet; + +/** +* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool. +* Also dispatches the `Weapon.onKill` signal. +* +* @method Phaser.Bullet#kill +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + this.data.bulletManager.onKill.dispatch(this); + + return this; + +}; + +/** +* Updates the Bullet, killing as required. +* +* @method Phaser.Bullet#update +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.update = function () { + + if (!this.exists) + { + return; + } + + if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN) + { + if (this.data.killType === Phaser.Weapon.KILL_DISTANCE) + { + if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance) + { + this.kill(); + } + } + else + { + if (!this.data.bulletManager.bulletBounds.intersects(this)) + { + this.kill(); + } + } + } + + if (this.data.rotateToVelocity) + { + this.rotation = this.body.velocity.atan(); + } + + if (this.data.bulletManager.bulletWorldWrap) + { + this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding); + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. +* +* Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to +* the Video instead (see `startMediaStream` method) +* +* The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback +* changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. +* +* Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. +* +* If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. +* Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. +* +* On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. +* This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio +* it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` +* method to try and work around this limitation, but see the method help for details. +* +* Small screen devices, especially iPod and iPhone will launch the video in its own native video player, +* outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. +* +* Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) +* then you need to add your own event listener +* +* @class Phaser.Video +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. +* @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) +*/ +Phaser.Video = function (game, key, url) { + + if (key === undefined) { key = null; } + if (url === undefined) { url = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. + * @default null + */ + this.key = key; + + /** + * @property {number} width - The width of the video in pixels. + * @default + */ + this.width = 0; + + /** + * @property {number} height - The height of the video in pixels. + * @default + */ + this.height = 0; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.VIDEO; + + /** + * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. + * @default + */ + this.touchLocked = false; + + /** + * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. + */ + this.onChangeSource = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam. + */ + this.onAccess = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. + */ + this.onError = new Phaser.Signal(); + + /** + * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. + * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. + * @property {Phaser.Signal} onTimeout + */ + this.onTimeout = new Phaser.Signal(); + + /** + * This signal is dispatched when the Video is unlocked. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * Start playing the video when it's unlocked. + * @property {boolean} playWhenUnlocked + * @default + */ + this.playWhenUnlocked = true; + + /** + * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. + * @default + */ + this.timeout = 15000; + + /** + * @property {integer} _timeOutID - setTimeout ID. + * @private + */ + this._timeOutID = null; + + /** + * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document. + */ + this.video = null; + + /** + * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. + */ + this.videoStream = null; + + /** + * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam. + */ + this.isStreaming = false; + + /** + * When starting playback of a video Phaser will monitor its readyState using a setTimeout call. + * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * @property {integer} retryLimit + * @default + */ + this.retryLimit = 20; + + /** + * @property {integer} retry - The current retry attempt. + * @default + */ + this.retry = 0; + + /** + * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video. + * @default + */ + this.retryInterval = 500; + + /** + * @property {integer} _retryID - The callback ID of the retry setTimeout. + * @private + */ + this._retryID = null; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {boolean} _codePaused - Internal paused tracking var. + * @private + * @default + */ + this._codePaused = false; + + /** + * @property {boolean} _paused - Internal paused tracking var. + * @private + * @default + */ + this._paused = false; + + /** + * @property {boolean} _pending - Internal var tracking play pending. + * @private + * @default + */ + this._pending = false; + + /** + * @property {boolean} _pendingChangeSource - Internal var tracking play pending. + * @private + * @default + */ + this._pendingChangeSource = false; + + /** + * @property {boolean} _autoplay - Internal var tracking autoplay when changing source. + * @private + * @default + */ + this._autoplay = false; + + /** + * @property {function} _endCallback - The addEventListener ended function. + * @private + */ + this._endCallback = null; + + /** + * @property {function} _playCallback - The addEventListener playing function. + * @private + */ + this._playCallback = null; + + if (key && this.game.cache.checkVideoKey(key)) + { + var _video = this.game.cache.getVideo(key); + + if (_video.isBlob) + { + this.createVideoFromBlob(_video.data); + } + else + { + this.video = _video.data; + } + + this.width = this.video.videoWidth; + this.height = this.video.videoHeight; + } + else if (url) + { + this.createVideoFromURL(url, false); + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + if (this.video && !url) + { + this.baseTexture = new PIXI.BaseTexture(this.video, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + else + { + this.baseTexture = new PIXI.BaseTexture(Phaser.Cache.DEFAULT.baseTexture.source, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering. + * @default + */ + this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video'); + + this.texture.setFrame(this.textureFrame); + + this.texture.valid = false; + + if (key !== null && this.video) + { + this.texture.valid = this.video.canplay; + } + + /** + * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). + * When called the BitmapData is updated with a grab taken from the current video playing or active video stream. + * If Phaser has been compiled without BitmapData support this property will always be `null`. + * + * @property {Phaser.BitmapData} snapshot + * @readOnly + */ + this.snapshot = null; + + if (Phaser.BitmapData) + { + this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height); + } + + if (this.game.device.needsTouchUnlock()) + { + this.setTouchLock(); + } + else + { + if (_video) + { + _video.locked = false; + } + } + +}; + +Phaser.Video.prototype = { + + /** + * Connects to an external media stream for the webcam, rather than using a local one. + * + * @method Phaser.Video#connectToMediaStream + * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses. + * @param {MediaStream} stream - The Video Stream data. + * @return {Phaser.Video} This Video object for method chaining. + */ + connectToMediaStream: function (video, stream) { + + if (video && stream) + { + this.video = video; + this.videoStream = stream; + + this.isStreaming = true; + this.baseTexture.source = this.video; + this.updateTexture(null, this.video.videoWidth, this.video.videoHeight); + + this.onAccess.dispatch(this); + } + + return this; + + }, + + /** + * Instead of playing a video file this method allows you to stream video data from an attached webcam. + * + * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam. + * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream. + * + * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError + * or MediaStreamError event. + * + * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions. + * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device. + * You can listen for this with the onChangeSource signal. + * + * @method Phaser.Video#startMediaStream + * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream. + * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source. + * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source. + * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia. + */ + startMediaStream: function (captureAudio, width, height) { + + if (captureAudio === undefined) { captureAudio = false; } + if (width === undefined) { width = null; } + if (height === undefined) { height = null; } + + if (!this.game.device.getUserMedia) + { + this.onError.dispatch(this, 'No getUserMedia'); + return false; + } + + if (this.videoStream !== null) + { + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + this.videoStream.stop(); + } + } + + this.removeVideoElement(); + + this.video = document.createElement("video"); + this.video.setAttribute('autoplay', 'autoplay'); + + if (width !== null) + { + this.video.width = width; + } + + if (height !== null) + { + this.video.height = height; + } + + // Request access to the webcam + + this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout); + + try { + navigator.getUserMedia( + { "audio": captureAudio, "video": true }, + this.getUserMediaSuccess.bind(this), + this.getUserMediaError.bind(this) + ); + } + catch (error) + { + this.getUserMediaError(error); + } + + return this; + + }, + + /** + * @method Phaser.Video#getUserMediaTimeout + * @private + */ + getUserMediaTimeout: function () { + + clearTimeout(this._timeOutID); + + this.onTimeout.dispatch(this); + + }, + + /** + * @method Phaser.Video#getUserMediaError + * @private + */ + getUserMediaError: function (event) { + + clearTimeout(this._timeOutID); + + this.onError.dispatch(this, event); + + }, + + /** + * @method Phaser.Video#getUserMediaSuccess + * @private + */ + getUserMediaSuccess: function (stream) { + + clearTimeout(this._timeOutID); + + // Attach the stream to the video + this.videoStream = stream; + + // Set the source of the video element with the stream from the camera + if (this.video.mozSrcObject !== undefined) + { + this.video.mozSrcObject = stream; + } + else + { + this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; + } + + var self = this; + + this.video.onloadeddata = function () { + + var retry = 10; + + function checkStream () { + + if (retry > 0) + { + if (self.video.videoWidth > 0) + { + // Patch for Firefox bug where the height can't be read from the video + var width = self.video.videoWidth; + var height = self.video.videoHeight; + + if (isNaN(self.video.videoHeight)) + { + height = width / (4/3); + } + + self.video.play(); + + self.isStreaming = true; + self.baseTexture.source = self.video; + self.updateTexture(null, width, height); + self.onAccess.dispatch(self); + } + else + { + window.setTimeout(checkStream, 500); + } + } + else + { + console.warn('Unable to connect to video stream. Webcam error?'); + } + + retry--; + } + + checkStream(); + + }; + + }, + + /** + * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format. + * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience. + * + * @method Phaser.Video#createVideoFromBlob + * @param {Blob} blob - The Blob containing the video data. + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromBlob: function (blob) { + + var _this = this; + + this.video = document.createElement("video"); + this.video.controls = false; + this.video.setAttribute('autoplay', 'autoplay'); + this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true); + this.video.src = window.URL.createObjectURL(blob); + this.video.canplay = true; + + return this; + + }, + + /** + * Creates a new Video element from the given URL. + * + * @method Phaser.Video#createVideoFromURL + * @param {string} url - The URL of the video. + * @param {boolean} [autoplay=false] - Automatically start the video? + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromURL: function (url, autoplay) { + + if (autoplay === undefined) { autoplay = false; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + if (this.texture) + { + this.texture.valid = false; + } + + this.video = document.createElement("video"); + this.video.controls = false; + + if (autoplay) + { + this.video.setAttribute('autoplay', 'autoplay'); + } + + this.video.src = url; + + this.video.canplay = true; + + this.video.load(); + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.key = url; + + return this; + + }, + + /** + * Called automatically if the video source changes and updates the internal texture dimensions. + * Then dispatches the onChangeSource signal. + * + * @method Phaser.Video#updateTexture + * @param {object} [event] - The event which triggered the texture update. + * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used. + * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used. + */ + updateTexture: function (event, width, height) { + + var change = false; + + if (width === undefined || width === null) { width = this.video.videoWidth; change = true; } + if (height === undefined || height === null) { height = this.video.videoHeight; } + + this.width = width; + this.height = height; + + if (this.baseTexture.source !== this.video) + { + this.baseTexture.source = this.video; + } + + this.baseTexture.forceLoaded(width, height); + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.valid = true; + + if (this.snapshot) + { + this.snapshot.resize(width, height); + } + + if (change && this.key !== null) + { + this.onChangeSource.dispatch(this, width, height); + + if (this._autoplay) + { + this.video.play(); + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + } + + }, + + /** + * Called when the video completes playback (reaches and ended state). + * Dispatches the Video.onComplete signal. + * + * @method Phaser.Video#complete + */ + complete: function () { + + this.onComplete.dispatch(this); + + }, + + /** + * Starts this video playing. + * + * If the video is already playing, or has been queued to play with `changeSource` then this method just returns. + * + * @method Phaser.Video#play + * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. + * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate. + * @return {Phaser.Video} This Video object for method chaining. + */ + play: function (loop, playbackRate) { + + if (this._pendingChangeSource) + { + return this; + } + + if (loop === undefined) { loop = false; } + if (playbackRate === undefined) { playbackRate = 1; } + + if (this.game.sound.onMute) + { + this.game.sound.onMute.add(this.setMute, this); + this.game.sound.onUnMute.add(this.unsetMute, this); + + if (this.game.sound.mute) + { + this.setMute(); + } + } + + this.game.onPause.add(this.setPause, this); + this.game.onResume.add(this.setResume, this); + + this._endCallback = this.complete.bind(this); + + this.video.addEventListener('ended', this._endCallback, true); + this.video.addEventListener('webkitendfullscreen', this._endCallback, true); + + if (loop) + { + this.video.loop = 'loop'; + } + else + { + this.video.loop = ''; + } + + this.video.playbackRate = playbackRate; + + if (this.touchLocked) + { + this._pending = true; + } + else + { + this._pending = false; + + if (this.key !== null) + { + if (this.video.readyState !== 4) + { + this.retry = this.retryLimit; + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + this._playCallback = this.playHandler.bind(this); + this.video.addEventListener('playing', this._playCallback, true); + } + } + + this.video.play(); + + this.onPlay.dispatch(this, loop, playbackRate); + } + + return this; + + }, + + /** + * Called when the video starts to play. Updates the texture. + * + * @method Phaser.Video#playHandler + * @private + */ + playHandler: function () { + + this.video.removeEventListener('playing', this._playCallback, true); + + this.updateTexture(); + + }, + + /** + * Stops the video playing. + * + * This removes all locally set signals. + * + * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead. + * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to + * call `Video.destroy` instead. + * + * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam. + * + * @method Phaser.Video#stop + * @return {Phaser.Video} This Video object for method chaining. + */ + stop: function () { + + if (this.game.sound.onMute) + { + this.game.sound.onMute.remove(this.setMute, this); + this.game.sound.onUnMute.remove(this.unsetMute, this); + } + + this.game.onPause.remove(this.setPause, this); + this.game.onResume.remove(this.setResume, this); + + // Stream or file? + + if (this.isStreaming) + { + if (this.video.mozSrcObject) + { + this.video.mozSrcObject.stop(); + this.video.src = null; + } + else + { + this.video.src = ''; + + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + if (this.videoStream.getTracks) + { + this.videoStream.getTracks().forEach(function (track) { + track.stop(); + }); + } + else + { + this.videoStream.stop(); + } + } + } + + this.videoStream = null; + this.isStreaming = false; + } + else + { + this.video.removeEventListener('ended', this._endCallback, true); + this.video.removeEventListener('webkitendfullscreen', this._endCallback, true); + this.video.removeEventListener('playing', this._playCallback, true); + + if (this.touchLocked) + { + this._pending = false; + } + else + { + this.video.pause(); + } + } + + return this; + + }, + + /** + * Updates the given Display Objects so they use this Video as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.Video#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.Video} This Video object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. + * + * @method Phaser.Video#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set Video.disableTextureUpload to `true`. + * + * @method Phaser.Video#render + */ + render: function () { + + if (!this.disableTextureUpload && this.playing) + { + this.baseTexture.dirty(); + } + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + this.video.muted = true; + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + this.video.muted = false; + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setPause + * @private + */ + setPause: function () { + + if (this._paused || this.touchLocked) + { + return; + } + + this._paused = true; + + this.video.pause(); + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setResume + * @private + */ + setResume: function () { + + if (!this._paused || this._codePaused || this.touchLocked) + { + return; + } + + this._paused = false; + + if (!this.video.ended) + { + this.video.play(); + } + + }, + + /** + * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it. + * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over" + * split into three different Video objects, then you will need the user to touch-unlock every single one of them. + * + * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains + * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again. + * + * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate. + * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it + * cannot render the new video on iOS (desktop browsers cope better). + * + * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know + * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state + * are adopted automatically by the new video. + * + * @method Phaser.Video#changeSource + * @param {string} src - The new URL to change the video.src to. + * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated? + * @return {Phaser.Video} This Video object for method chaining. + */ + changeSource: function (src, autoplay) { + + if (autoplay === undefined) { autoplay = true; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + this.texture.valid = false; + + this.video.pause(); + + this._pendingChangeSource = true; + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.video.src = src; + + this.video.load(); + + this._autoplay = autoplay; + + if (!autoplay) + { + this.paused = true; + } + + return this; + + }, + + /** + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.Video#checkVideoProgress + * @private + */ + checkVideoProgress: function () { + + // if (this.video.readyState === 2 || this.video.readyState === 4) + if (this.video.readyState === 4) + { + this._pendingChangeSource = false; + + // We've got enough data to update the texture for playback + this.updateTexture(); + } + else + { + this.retry--; + + if (this.retry > 0) + { + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming); + } + } + + }, + + /** + * Sets the Input Manager touch callback to be Video.unlock. + * Required for mobile video unlocking. Mostly just used internally. + * + * @method Phaser.Video#setTouchLock + */ + setTouchLock: function () { + + this.game.input.addTouchLockCallback(this.unlock, this, true); + this.touchLocked = true; + + }, + + /** + * Enables the video on mobile devices, usually after the first touch. + * If the SoundManager hasn't been unlocked then this will automatically unlock that as well. + * Only one video can be pending unlock at any one time. + * + * @method Phaser.Video#unlock + */ + unlock: function () { + + this.touchLocked = false; + + if (this.playWhenUnlocked) + { + this.video.play(); + + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + + if (this.key) + { + var _video = this.game.cache.getVideo(this.key); + + if (_video && !_video.isBlob) + { + _video.locked = false; + } + } + + this.onTouchUnlock.dispatch(this); + + return true; + + }, + + /** + * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData. + * + * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw. + * + * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy. + * + * @method Phaser.Video#grab + * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false. + * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining. + */ + grab: function (clear, alpha, blendMode) { + + if (clear === undefined) { clear = false; } + if (alpha === undefined) { alpha = 1; } + if (blendMode === undefined) { blendMode = null; } + + if (this.snapshot === null) + { + console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable'); + return; + } + + if (clear) + { + this.snapshot.cls(); + } + + this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode); + + return this.snapshot; + + }, + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * Also removes the autoplay and src attributes and nulls the reference. + * + * @method Phaser.Video#removeVideoElement + */ + removeVideoElement: function () { + + if (!this.video) + { + return; + } + + if (this.video.parentNode) + { + this.video.parentNode.removeChild(this.video); + } + + while (this.video.hasChildNodes()) + { + this.video.removeChild(this.video.firstChild); + } + + this.video.removeAttribute('autoplay'); + this.video.removeAttribute('src'); + + this.video = null; + + }, + + /** + * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`. + * If any Sprites are using this Video as their texture it is up to you to manage those. + * + * @method Phaser.Video#destroy + */ + destroy: function () { + + this.stop(); + + this.removeVideoElement(); + + if (this.touchLocked) + { + this.game.input.touch.removeTouchLockCallback(this.unlock, this); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + + } + +}; + +/** +* @name Phaser.Video#currentTime +* @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time. +*/ +Object.defineProperty(Phaser.Video.prototype, "currentTime", { + + get: function () { + + return (this.video) ? this.video.currentTime : 0; + + }, + + set: function (value) { + + this.video.currentTime = value; + + } + +}); + +/** +* @name Phaser.Video#duration +* @property {number} duration - The duration of the video in seconds. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "duration", { + + get: function () { + + return (this.video) ? this.video.duration : 0; + + } + +}); + +/** +* @name Phaser.Video#progress +* @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "progress", { + + get: function () { + + return (this.video) ? (this.video.currentTime / this.video.duration) : 0; + + } + +}); + +/** +* @name Phaser.Video#mute +* @property {boolean} mute - Gets or sets the muted state of the Video. +*/ +Object.defineProperty(Phaser.Video.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || null; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* Gets or sets the paused state of the Video. +* If the video is still touch locked (such as on iOS devices) this call has no effect. +* +* @name Phaser.Video#paused +* @property {boolean} paused +*/ +Object.defineProperty(Phaser.Video.prototype, "paused", { + + get: function () { + + return this._paused; + + }, + + set: function (value) { + + value = value || null; + + if (this.touchLocked) + { + return; + } + + if (value) + { + if (this._paused) + { + return; + } + + this._codePaused = true; + this.setPause(); + } + else + { + if (!this._paused) + { + return; + } + + this._codePaused = false; + this.setResume(); + } + } + +}); + +/** +* @name Phaser.Video#volume +* @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Video.prototype, "volume", { + + get: function () { + + return (this.video) ? this.video.volume : 1; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this.video) + { + this.video.volume = value; + } + + } + +}); + +/** +* @name Phaser.Video#playbackRate +* @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing. +*/ +Object.defineProperty(Phaser.Video.prototype, "playbackRate", { + + get: function () { + + return (this.video) ? this.video.playbackRate : 1; + + }, + + set: function (value) { + + if (this.video) + { + this.video.playbackRate = value; + } + + } + +}); + +/** +* Gets or sets if the Video is set to loop. +* Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. +* If the video isn't yet set this will always return false. +* +* @name Phaser.Video#loop +* @property {boolean} loop +*/ +Object.defineProperty(Phaser.Video.prototype, "loop", { + + get: function () { + + return (this.video) ? this.video.loop : false; + + }, + + set: function (value) { + + if (value && this.video) + { + this.video.loop = 'loop'; + } + else if (this.video) + { + this.video.loop = ''; + } + + } + +}); + +/** +* @name Phaser.Video#playing +* @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "playing", { + + get: function () { + + return (this.video) ? !(this.video.paused && this.video.ended) : false; + + } + +}); + +Phaser.Video.prototype.constructor = Phaser.Video; + +/* global Phaser:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Pixi expects these globals to exist + +if (PIXI.blendModes === undefined) +{ + PIXI.blendModes = Phaser.blendModes; +} + +if (PIXI.scaleModes === undefined) +{ + PIXI.scaleModes = Phaser.scaleModes; +} + +if (PIXI.Texture.emptyTexture === undefined) +{ + PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture()); +} + +if (PIXI.DisplayObject._tempMatrix === undefined) +{ + PIXI.DisplayObject._tempMatrix = new Phaser.Matrix(); +} + +PIXI.TextureSilentFail = true; + +// Required by Particle Storm +PIXI.canUseNewCanvasBlendModes = function () { + return Phaser.Device.canUseMultiply; +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = Phaser; + } + exports.Phaser = Phaser; + } else if (typeof define !== 'undefined' && define.amd) { + define('Phaser', (function() { return root.Phaser = Phaser; })() ); + } else { + root.Phaser = Phaser; + } + + return Phaser; +}).call(this); + +/* +* "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer +*/ diff --git a/Iteration Sequence 1.2/js/phaser.map b/Iteration Sequence 1.2/js/phaser.map new file mode 100644 index 000000000..70723bbf8 --- /dev/null +++ b/Iteration Sequence 1.2/js/phaser.map @@ -0,0 +1 @@ +{"version":3,"sources":["phaser.js"],"names":["e","exports","module","f","window","global","self","p2","t","n","r","s","o","u","a","require","i","Error","call","length","1","_dereq_","Line","Scalar","lineInt","l1","l2","precision","a1","b1","c1","a2","b2","c2","det","eq","segmentsIntersect","p1","q1","q2","dx","dy","da","db","./Scalar","2","Point","area","b","c","left","leftOn","right","rightOn","tmpPoint1","tmpPoint2","collinear","thresholdAngle","ab","bc","dot","magA","Math","sqrt","magB","acos","sqdist","3","Polygon","this","vertices","getIntersectionPoint","delta","prototype","at","v","first","last","clear","append","poly","from","to","push","makeCCW","br","reverse","tmp","N","pop","isReflex","tmpLine1","tmpLine2","canSee","p","dist","copy","j","targetPoly","k","getCutEdges","min","tmp1","tmp2","tmpPoly","nDiags","Number","MAX_VALUE","decomp","edges","slice","cutEdges","Array","polys","cutEdge","result","splice","indexOf","isSimple","path","quickDecomp","reflexVertices","steinerPoints","maxlevel","level","upperInt","lowerInt","upperDist","lowerDist","d","closestDist","upperIndex","lowerIndex","closestIndex","lowerPoly","upperPoly","console","warn","removeCollinearPoints","num","./Line","./Point","4","abs","5","./Polygon","6","name","version","description","author","keywords","main","engines","node","repository","type","url","bugs","licenses","devDependencies","grunt","grunt-contrib-jshint","grunt-contrib-nodeunit","grunt-contrib-uglify","grunt-contrib-watch","grunt-browserify","grunt-contrib-concat","dependencies","poly-decomp","7","AABB","options","lowerBound","vec2","create","upperBound","setFromPoints","points","position","angle","skinSize","l","rotate","cosAngle","cos","sinAngle","sin","x","y","add","aabb","extend","overlaps","u1","u2","containsPoint","point","overlapsRay","ray","dirFracX","direction","dirFracY","t1","t2","t3","t4","tmin","max","tmax","../math/vec2","../utils/Utils","8","Broadphase","world","boundingVolumeType","Body","BOUNDING_CIRCLE","setWorld","getCollisionPairs","boundingRadiusCheck","bodyA","bodyB","sub","d2","squaredLength","boundingRadius","aabbCheck","getAABB","boundingVolumeCheck","canCollide","KINEMATIC","STATIC","sleepState","SLEEPING","NAIVE","SAP","../objects/Body","9","NaiveBroadphase","constructor","bodies","Ncolliding","bi","bj","aabbQuery","aabbNeedsUpdate","updateAABB","../collision/Broadphase","../shapes/Circle","../shapes/Particle","../shapes/Plane","../shapes/Shape","10","Narrowphase","contactEquations","frictionEquations","enableFriction","enabledEquations","slipForce","frictionCoefficient","surfaceVelocity","contactEquationPool","ContactEquationPool","size","frictionEquationPool","FrictionEquationPool","restitution","stiffness","Equation","DEFAULT_STIFFNESS","relaxation","DEFAULT_RELAXATION","frictionStiffness","frictionRelaxation","enableFrictionReduction","collidingBodiesLastStep","TupleDictionary","contactSkinSize","setConvexToCapsuleShapeMiddle","convexShape","capsuleShape","set","radius","pointInConvex","worldPoint","convexOffset","convexAngle","worldVertex0","pic_worldVertex0","worldVertex1","pic_worldVertex1","r0","pic_r0","r1","pic_r1","verts","lastCross","v0","v1","cross","crossLength","Circle","Convex","Shape","Box","yAxis","fromValues","tmp3","tmp4","tmp5","tmp6","tmp7","tmp8","tmp9","tmp10","tmp11","tmp12","tmp13","tmp14","tmp15","tmp16","tmp17","tmp18","tmpArray","bodiesOverlap_shapePositionA","bodiesOverlap_shapePositionB","bodiesOverlap","shapePositionA","shapePositionB","Nshapesi","shapes","shapeA","toWorldFrame","Nshapesj","shapeB","collidedLastStep","id1","id","id2","get","reset","eqs","ce","fe","release","createContactEquation","firstImpact","needsUpdate","enabled","offset","createFrictionEquation","setSlipForce","relativeVelocity","createFrictionFromContact","contactPointA","contactPointB","rotate90cw","normalA","createFrictionFromAverage","numContacts","invNumContacts","scale","normalize","LINE","CONVEX","convexLine","convexBody","lineBody","lineShape","lineOffset","lineAngle","justTest","BOX","lineBox","boxBody","boxShape","boxOffset","boxAngle","convexCapsule_tempRect","width","height","convexCapsule_tempVec","CAPSULE","convexCapsule","convexPosition","capsuleBody","capsulePosition","capsuleAngle","circlePos","result1","circleConvex","result2","convexConvex","lineCapsule","linePosition","capsuleCapsule_tempVec1","capsuleCapsule_tempVec2","capsuleCapsule_tempRect1","capsuleCapsule","si","xi","ai","sj","xj","aj","circlePosi","circlePosj","enableFrictionBefore","circleCircle","rect","lineLine","positionA","angleA","positionB","angleB","PLANE","planeLine","planeBody","planeShape","planeOffset","planeAngle","worldVertex01","worldVertex11","worldEdge","worldEdgeUnit","worldNormal","worldTangent","PARTICLE","particleCapsule","particleBody","particleShape","particlePosition","particleAngle","circleLine","CIRCLE","circleBody","circleShape","circleOffset","circleAngle","lineRadius","circleRadius","orthoDist","lineToCircleOrthoUnit","projectedPoint","centerDist","lineToCircle","lineEndToLineRadius","radiusSum","pos","pos0","pos1","pow","circleCapsule","worldVertex","closestEdgeProjectedPoint","candidate","candidateDist","minCandidate","found","minCandidateDistance","candidateDistance","localVertex","particleConvex","particleOffset","convexToparticle","minEdgeNormal","offsetA","offsetB","radiusA","radiusB","planeConvex","numReported","particlePlane","circleParticle","planeCapsule_tmpCircle","planeCapsule_tmp1","planeCapsule_tmp2","planeCapsule","capsuleOffset","end1","end2","circle","numContacts1","circlePlane","numContacts2","numTotal","planeToCircle","temp","contact","sepAxis","worldPoint0","worldPoint1","penetrationVec","findSeparatingAxis","closestEdge1","getClosestEdge","closestEdge2","closestEdgeA","closestEdgeB","insideNumEdges","pcoa_tmp1","projectConvexOntoAxis","worldAxis","value","localAxis","fsa_tmp1","fsa_tmp2","fsa_tmp3","fsa_tmp4","fsa_tmp5","fsa_tmp6","offset1","angle1","offset2","angle2","maxDist","overlap","edge","normal","span1","span2","gce_tmp1","gce_tmp2","gce_tmp3","axis","flip","closestEdge","maxDot","circleHeightfield_candidate","circleHeightfield_dist","circleHeightfield_v0","circleHeightfield_v1","circleHeightfield_minCandidate","circleHeightfield_worldNormal","circleHeightfield_minCandidateNormal","HEIGHTFIELD","circleHeightfield","hfBody","hfShape","hfPos","hfAngle","data","heights","w","elementWidth","minCandidateNormal","idxA","floor","idxB","ceil","PI","convexHeightfield_v0","convexHeightfield_v1","convexHeightfield_tilePos","convexHeightfield_tempConvexShape","convexHeightfield","convexPos","tilePos","tileConvex","../equations/ContactEquation","../equations/Equation","../equations/FrictionEquation","../shapes/Box","../shapes/Convex","../utils/ContactEquationPool","../utils/FrictionEquationPool","../utils/TupleDictionary","11","Ray","checkCollisionResponse","undefined","skipBackfaces","collisionMask","collisionGroup","mode","ANY","callback","update","distanceFromIntersectionSquared","intersect","squaredDistance","CLOSEST","ALL","intersectBodies","shouldStop","body","intersectBody","intersectBody_worldPosition","collisionResponse","worldPosition","shape","worldAngle","intersectShape","_currentBody","_currentShape","raycast","reportIntersection","fraction","faceIndex","hasHit","../collision/AABB","../collision/RaycastResult","12","RaycastResult","isStopped","getHitDistance","distance","getHitPoint","out","lerp","stop","../collision/Ray","13","SAPBroadphase","axisList","axisIndex","that","_addBodyHandler","_removeBodyHandler","idx","Utils","appendArray","off","on","sortAxisList","sortList","14","Constraint","defaults","collideConnected","wakeUpBodies","equations","wakeUp","DISTANCE","GEAR","LOCK","PRISMATIC","REVOLUTE","setStiffness","setRelaxation","15","DistanceConstraint","localAnchorA","localAnchorB","worldAnchorA","worldAnchorB","maxForce","ri","rj","computeGq","setMaxForce","upperLimitEnabled","upperLimit","lowerLimitEnabled","lowerLimit","normalEquation","G","violating","minForce","rixn","rjxn","getMaxForce","./Constraint","16","GearConstraint","ratio","AngleLockEquation","maxTorque","setMaxTorque","setRatio","torque","getMaxTorque","../equations/AngleLockEquation","17","LockConstraint","localAngleB","rot","g","localOffsetB","force","xAxis","18","PrismaticConstraint","localAxisA","trans","gg","updateJacobian","disableRotationalLock","RotationalLockEquation","velocity","upperLimitEquation","ContactEquation","lowerLimitEquation","motorEquation","motorEnabled","motorSpeed","computeGW","vi","vj","wi","angularVelocity","wj","gmult","worldAxisA","orientedAnchorA","orientedAnchorB","relPosition","enableMotor","disableMotor","setLimits","lower","upper","../equations/RotationalLockEquation","19","RevoluteConstraint","pivotA","pivotB","worldPivot","localPivotA","localPivotB","worldPivotA","worldPivotB","RotationalVelocityEquation","relAngle","setMotorSpeed","speed","getMotorSpeed","../equations/RotationalVelocityEquation","20","./Equation","21","computeB","h","GW","Gq","computeGiMf","relVel","getVelocityAlongNormal","getVelocityAtPoint","subtract","22","ARRAY_TYPE","epsilon","timeStep","multiplier","qi","qj","computeGWlambda","vlambda","wlambda","iMfi","iMfj","fi","ti","angularForce","fj","tj","invMassi","invMassSolve","invMassj","invIi","invInertiaSolve","invIj","multiply","massMultiplier","computeGiMGt","addToWlambda_temp","addToWlambda_Gi","addToWlambda_Gj","addToWlambda","deltalambda","Gi","Gj","computeInvC","eps","23","FrictionEquation","getSlipForce","24","worldVectorA","worldVectorB","25","GiMf","26","EventEmitter","listener","context","_listeners","listeners","has","index","emit","event","listenerArray","target","27","ContactMaterial","materialA","materialB","Material","idCounter","friction","./Material","28","29","PolyK","GetArea","sum","Triangulate","tgs","avl","al","i0","i1","i2","ax","ay","bx","by","cx","cy","earFound","_convex","_PointInTriangle","px","py","v0x","v0y","v1x","v1y","v2x","v2y","dot00","dot01","dot02","dot11","dot12","invDenom","30","crossVZ","vec","zcomp","crossZV","toLocalFrame","framePosition","frameAngle","toGlobalFrame","localPoint","vectorToLocalFrame","worldVector","vectorToGlobalFrame","localVector","centroid","clone","mul","divide","div","sqrDist","len","sqrLen","negate","str","reflect","vector","getLineSegmentsIntersection","p0","p3","getLineSegmentsIntersectionFraction","s1_x","s1_y","s2_x","s2_y","31","_idCounter","mass","invMass","inertia","invInertia","fixedRotation","fixedX","fixedY","interpolatedPosition","interpolatedAngle","previousPosition","previousAngle","damping","angularDamping","DYNAMIC","allowSleep","wantsToSleep","AWAKE","sleepSpeedLimit","sleepTimeLimit","gravityScale","idleTime","timeLastSleepy","ccdSpeedThreshold","ccdIterations","concavePath","_wakeUpAfterNarrowphase","updateMassProperties","updateSolveMassProperties","setDensity","density","totalArea","getArea","shapeAABB","bodyAngle","computeAABB","updateBoundingRadius","addShape","removeShape","m","I","r2","computeMomentOfInertia","applyForce","relativePoint","rotForce","Body_applyForce_forceWorld","Body_applyForce_pointWorld","Body_applyForce_pointLocal","applyForceLocal","localForce","worldForce","vectorToWorldFrame","Body_applyImpulse_velo","applyImpulse","impulseVector","velo","rotVelo","Body_applyImpulse_impulseWorld","Body_applyImpulse_pointWorld","Body_applyImpulse_pointLocal","applyImpulseLocal","localImpulse","worldImpulse","fromPolygon","convexes","optimalDecomp","cm","centerOfMass","updateTriangles","updateCenterOfMass","adjustCenterOfMass","adjustCenterOfMass_tmp2","adjustCenterOfMass_tmp3","adjustCenterOfMass_tmp4","offset_times_area","setZeroForce","resetConstraintVelocity","addConstraintVelocity","applyDamping","dt","wakeUpEvent","sleep","sleepEvent","sleepTick","time","dontSleep","SLEEPY","overlapKeeper","bodiesAreOverlapping","integrate_fhMinv","integrate_velodt","integrate","minv","integrateToTimeOfImpact","end","startToEnd","rememberPosition","hit","startToEndAngle","timeOfImpact","rememberAngle","iter","tmid","narrowphase","sleepyEvent","../events/EventEmitter","32","LinearSpring","Spring","setWorldAnchorA","setWorldAnchorB","getWorldAnchorA","getWorldAnchorB","worldDistance","restLength","applyForce_r","applyForce_r_unit","applyForce_u","applyForce_f","applyForce_worldAnchorA","applyForce_worldAnchorB","applyForce_ri","applyForce_rj","applyForce_tmp","r_unit","rlen","ri_x_f","rj_x_f","./Spring","33","RotationalSpring","restAngle","34","35","TopDownVehicle","chassisBody","wheels","groundBody","preStepCallback","WheelConstraint","vehicle","forwardEquation","sideEquation","steerValue","engineForce","setSideFriction","sideFriction","localForwardVector","localPosition","apply","setBrakeForce","addToWorld","addBody","wheel","addConstraint","removeFromWorld","removeBody","removeConstraint","addWheel","wheelOptions","worldVelocity","getSpeed","tmpVec","../constraints/Constraint","36","Capsule","GSSolver","Heightfield","Particle","Plane","Pool","Solver","World","Object","defineProperty","../package.json","./collision/AABB","./collision/Broadphase","./collision/NaiveBroadphase","./collision/Narrowphase","./collision/Ray","./collision/RaycastResult","./collision/SAPBroadphase","./constraints/Constraint","./constraints/DistanceConstraint","./constraints/GearConstraint","./constraints/LockConstraint","./constraints/PrismaticConstraint","./constraints/RevoluteConstraint","./equations/AngleLockEquation","./equations/ContactEquation","./equations/Equation","./equations/FrictionEquation","./equations/RotationalVelocityEquation","./events/EventEmitter","./material/ContactMaterial","./material/Material","./math/vec2","./objects/Body","./objects/LinearSpring","./objects/RotationalSpring","./objects/Spring","./objects/TopDownVehicle","./shapes/Box","./shapes/Capsule","./shapes/Circle","./shapes/Convex","./shapes/Heightfield","./shapes/Line","./shapes/Particle","./shapes/Plane","./shapes/Shape","./solver/GSSolver","./solver/Solver","./utils/ContactEquationPool","./utils/FrictionEquationPool","./utils/Pool","./utils/Utils","./world/World","37","arguments","axes","updateArea","./Convex","./Shape","38","intersectCapsule_hitPointWorld","intersectCapsule_normal","intersectCapsule_l0","intersectCapsule_l1","intersectCapsule_unit_y","hitPointWorld","l0","halfLen","diagonalLengthSquared","sqrtDelta","inv2a","d1","39","Ray_intersectSphere_intersectionPoint","Ray_intersectSphere_normal","intersectionPoint","40","isArray","triangles","polyk","tmpVec1","tmpVec2","projectOntoLocalAxis","projectOntoWorldAxis","shapeOffset","shapeAngle","polykVerts","id3","updateCenterOfMass_centroid","updateCenterOfMass_centroid_times_mass","updateCenterOfMass_a","updateCenterOfMass_b","updateCenterOfMass_c","centroid_times_mass","triangleArea","denom","numer","intersectConvex_rayStart","intersectConvex_rayEnd","intersectConvex_normal","rayStart","rayEnd","../math/polyk","41","key","maxValue","minValue","updateMaxMinValues","getLineSegment","start","getSegmentIndex","getClampedSegmentIndex","intersectHeightfield_worldNormal","intersectHeightfield_l0","intersectHeightfield_l1","intersectHeightfield_localFrom","intersectHeightfield_localTo","localFrom","localTo","42","raycast_normal","raycast_l0","raycast_l1","raycast_unit_y","43","44","intersectPlane_planePointToFrom","intersectPlane_normal","intersectPlane_len","planePointToFrom","planeToFrom","n_dot_dir","45","material","sensor","46","GS","iterations","tolerance","arrayStep","lambda","Bs","invCs","useZeroRHS","frictionIterations","usedIterations","setArrayZero","array","solve","sortEquations","maxIter","maxFrictionIter","Neq","tolSquared","Nbodies","deltalambdaTot","iterateEquation","updateMultipliers","invDt","B","invC","lambdaj","GWlambda","lambdaj_plus_deltalambda","./Solver","47","equationSortFunction","mockWorld","solveIsland","island","removeAllEquations","addEquations","getBodies","sort","addEquation","removeEquation","ISLAND","48","destroy","equation","./Pool","49","50","IslandNodePool","IslandNode","../world/IslandNode","51","IslandPool","Island","../world/Island","52","OverlapKeeper","overlappingShapesLastState","overlappingShapesCurrentState","recordPool","OverlapKeeperRecordPool","tmpDict","tmpArray1","tick","current","keys","lastObject","getByKey","setOverlapping","getNewOverlaps","getDiff","getEndOverlaps","dictA","dictB","isNewOverlap","idA","idB","getNewBodyOverlaps","getBodyDiff","getEndBodyOverlaps","accumulator","./OverlapKeeperRecord","./OverlapKeeperRecordPool","./TupleDictionary","./Utils","53","OverlapKeeperRecord","54","record","55","objects","resize","object","56","getKey","dict","57","howmany","P2_ARRAY_TYPE","Float32Array","58","bodyIds","59","IslandManager","nodePool","islandPool","islands","nodes","queue","getUnvisitedNode","Nnodes","visited","visit","bds","Neqs","bfs","root","child","neighbors","split","ni","nj","./../utils/IslandNodePool","./../utils/IslandPool","./Island","./IslandNode","60","61","springs","disabledBodyCollisionPairs","solver","islandManager","gravity","frictionGravity","useWorldGravityAsFrictionGravity","useFrictionGravityOnZeroGravity","broadphase","constraints","defaultMaterial","defaultContactMaterial","lastTimeStep","applySpringForces","applyGravity","solveConstraints","contactMaterials","stepping","bodiesToBeRemoved","islandSplit","emitImpactEvent","_constraintIdCounter","_bodyIdCounter","postStepEvent","addBodyEvent","removeBodyEvent","addSpringEvent","spring","impactEvent","contactEquation","postBroadphaseEvent","pairs","sleepMode","NO_SLEEPING","beginContactEvent","endContactEvent","preSolveEvent","BODY_SLEEPING","ISLAND_SLEEPING","constraint","addContactMaterial","contactMaterial","removeContactMaterial","getContactMaterial","cmats","step_mg","xiw","xjw","step","timeSinceLastCalled","maxSubSteps","internalStep","substeps","endOverlaps","Nsprings","np","mg","gravityLen","ignoredPairs","Nconstraints","Nresults","runNarrowphase","ev","glen","aiw","ajw","reducedMass","resolver","numFrictionBefore","numFrictionEquations","addSpring","evt","removeSpring","getBodyById","disableBodyCollision","enableBodyCollision","cs","cms","hitTest_tmp1","hitTest_tmp2","hitTest","pb","ps","NS","setGlobalStiffness","setGlobalRelaxation","tmpAABB","../../package.json","../collision/Narrowphase","../collision/SAPBroadphase","../constraints/DistanceConstraint","../constraints/GearConstraint","../constraints/LockConstraint","../constraints/PrismaticConstraint","../constraints/RevoluteConstraint","../material/ContactMaterial","../material/Material","../objects/LinearSpring","../objects/RotationalSpring","../shapes/Capsule","../shapes/Line","../solver/GSSolver","../solver/Solver","../utils/OverlapKeeper","./IslandManager","_CreateEmptyTexture","gl","scaleMode","texture","createTexture","bindTexture","TEXTURE_2D","texParameteri","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","TEXTURE_MAG_FILTER","PIXI","scaleModes","LINEAR","NEAREST","TEXTURE_MIN_FILTER","texImage2D","RGBA","UNSIGNED_BYTE","_CreateFramebuffer","textureUnit","framebuffer","createFramebuffer","depthStencilBuffer","createRenderbuffer","colorBuffer","fbStatus","activeTexture","TEXTURE0","bindFramebuffer","FRAMEBUFFER","bindRenderbuffer","RENDERBUFFER","framebufferRenderbuffer","DEPTH_STENCIL_ATTACHMENT","renderBuffer","framebufferTexture2D","COLOR_ATTACHMENT0","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","error","_fbErrors","targetTexture","DisplayObject","pivot","rotation","alpha","visible","hitArea","renderable","parent","worldAlpha","worldTransform","Phaser","Matrix","worldScale","worldRotation","filterArea","_sr","_cr","_bounds","Rectangle","_currentBounds","_mask","_cacheAsBitmap","_cacheIsDirty","children","_destroyCachedSprite","updateTransform","game","tx","ty","pt","wt","PI2","rotationCache","determ","HALF_PI","transformCallback","transformCallbackContext","preUpdate","generateTexture","resolution","renderer","bounds","getLocalBounds","renderTexture","RenderTexture","_tempMatrix","render","updateCache","_generateCachedSprite","toGlobal","toLocal","applyInverse","_renderCachedSprite","renderSession","_cachedSprite","Sprite","_renderWebGL","_renderCanvas","baseTexture","_enableMultiTextureToggle","textureIndex","tempFilters","_filters","filters","anchor","displayObjectUpdateTransform","defineProperties","worldVisible","item","mask","isMask","passes","filterPasses","_filterBlock","blendMode","blendModes","MULTIPLY","NORMAL","cacheAsBitmap","DisplayObjectContainer","ignoreChildInput","addChild","addChildAt","removeChild","swapChildren","child2","index1","getChildIndex","index2","setChildIndex","currentIndex","getChildAt","removeChildAt","removeChildren","beginIndex","endIndex","range","removed","displayObjectContainerUpdateTransform","getBounds","targetCoordinateSpace","isTargetCoordinateSpaceDisplayObject","isTargetCoordinateSpaceThisOrParent","contains","matrixCache","identityMatrix","childBounds","childMaxX","childMaxY","minX","Infinity","minY","maxX","maxY","childVisible","w0","w1","h0","h1","x1","y1","x2","y2","x3","y3","x4","y4","targetCoordinateSpaceBounds","spriteBatch","flush","filterManager","pushFilter","maskManager","pushMask","popMask","popFilter","_width","_height","defaultAnchor","Texture","emptyTexture","tint","cachedTint","tintedTexture","shader","exists","hasLoaded","onTextureUpdate","frame","setTexture","destroyBase","skipRender","valid","matrix","crop","currentBlendMode","globalCompositeOperation","blendModesCanvas","globalAlpha","smoothProperty","trim","shakeX","shakeY","cw","ch","rotated","roundPixels","setTransform","requiresReTint","CanvasTinter","getTintedTexture","drawImage","source","initDefaultShaders","CompileVertexShader","shaderSrc","_CompileShader","VERTEX_SHADER","CompileFragmentShader","FRAGMENT_SHADER","shaderType","src","join","createShader","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","log","getShaderInfoLog","compileProgram","vertexSrc","fragmentSrc","fragmentShader","vertexShader","shaderProgram","createProgram","attachShader","linkProgram","getProgramParameter","LINK_STATUS","getProgramInfoLog","PixiShader","_UID","program","textureCount","firstRun","dirty","attributes","init","initMultitexShader","MAX_TEXTURES","getParameter","MAX_TEXTURE_IMAGE_UNITS","dynamicIfs","defaultVertexSrc","useProgram","uSamplerArray","getUniformLocation","projectionVector","offsetVector","dimensions","aVertexPosition","getAttribLocation","aTextureCoord","colorAttribute","aTextureIndex","indices","tempTexture","RGB","uniform1iv","uniforms","uniformLocation","initUniforms","initDefaultShader","uSampler","usingFilter","uniform","_init","initSampler2D","glMatrix","glValueLength","glFunc","uniformMatrix2fv","uniformMatrix3fv","uniformMatrix4fv","_glTextures","textureData","magFilter","minFilter","wrapS","wrapT","format","LUMINANCE","repeat","REPEAT","pixelStorei","UNPACK_FLIP_Y_WEBGL","flipY","border","uniform1i","syncUniforms","transpose","z","_dirty","instances","updateTexture","deleteProgram","PixiFastShader","uMatrix","aPositionCoord","aScale","aRotation","StripShader","translationMatrix","attribute","PrimitiveShader","tintColor","ComplexPrimitiveShader","color","glContexts","WebGLRenderer","config","defaultRenderer","extensions","WEBGL","transparent","autoResize","preserveDrawingBuffer","clearBeforeRender","view","canvas","_contextOptions","antialias","failIfMajorPerformanceCaveat","premultipliedAlpha","stencil","projection","shaderManager","WebGLShaderManager","WebGLSpriteBatch","WebGLMaskManager","WebGLFilterManager","stencilManager","WebGLStencilManager","blendModeManager","WebGLBlendModeManager","currentBatchedTextures","drawCount","maxTextureAvailableSpace","initContext","mapBlendModes","getContext","maxTextures","maxTextureSize","MAX_TEXTURE_SIZE","glContextId","disable","DEPTH_TEST","CULL_FACE","enable","BLEND","setContext","compression","etc1","getExtension","pvrtc","s3tc","ETC1","PVRTC","S3TC","setTexturePriority","textureNameCollection","clampPot","potSize","imageCache","cache","_cache","image","imageName","base","stage","contextLost","viewport","clearColor","_bgColor","COLOR_BUFFER_BIT","camera","_shake","renderDisplayObject","displayObject","buffer","setBlendMode","begin","style","updateCompressedTexture","textureMetaData","compressedTexImage2D","glExtensionFormat","mipmap","isPowerOfTwo","LINEAR_MIPMAP_LINEAR","NEAREST_MIPMAP_NEAREST","generateMipmap","_powerOf2","compressionAlgorithm","UNPACK_PREMULTIPLY_ALPHA_WEBGL","CanvasPool","remove","blendModesWebGL","modes","ONE","ONE_MINUS_SRC_ALPHA","ADD","SRC_ALPHA","DST_ALPHA","DST_COLOR","SCREEN","OVERLAY","DARKEN","LIGHTEN","COLOR_DODGE","COLOR_BURN","HARD_LIGHT","SOFT_LIGHT","DIFFERENCE","EXCLUSION","HUE","SATURATION","COLOR","LUMINOSITY","getMaxTextureUnit","enableMultiTexture","textureArray","blendModeWebGL","blendFunc","maskData","WebGLGraphics","updateGraphics","_webGL","pushStencil","popStencil","stencilStack","count","graphics","webGLData","bindGraphics","STENCIL_TEST","STENCIL_BUFFER_BIT","colorMask","stencilFunc","ALWAYS","stencilOp","KEEP","INVERT","drawElements","TRIANGLE_FAN","UNSIGNED_SHORT","EQUAL","DECR","INCR","TRIANGLE_STRIP","_currentGraphics","complexPrimitiveShader","setShader","uniform1f","toArray","uniform2f","uniform3fv","Color","hexToRGBArray","bindBuffer","ARRAY_BUFFER","vertexAttribPointer","FLOAT","ELEMENT_ARRAY_BUFFER","indexBuffer","primitiveShader","maxAttibs","attribState","tempAttribState","stack","defaultShader","fastShader","stripShader","creatureShader","CreatureShader","setAttribs","attribs","attribId","enableVertexAttribArray","disableVertexAttribArray","_currentId","currentShader","vertSize","vertexSize","numVerts","numIndices","ArrayBuffer","positions","colors","Uint32Array","Uint16Array","lastIndexCount","drawing","currentBatchSize","currentBaseTexture","textures","shaders","sprites","Filter","vertexBuffer","createBuffer","bufferData","STATIC_DRAW","DYNAMIC_DRAW","sprite","uvs","_uvs","aX","aY","a0","b0","c0","d0","_w1","_w0","_updateUvsInverted","x0","y0","renderTilingSprite","tilingTexture","TextureUvs","tilePosition","tileScaleOffset","offsetX","offsetY","scaleX","tileScale","scaleY","stride","bufferSubData","subarray","nextTexture","nextBlendMode","nextShader","batchSize","blendSwap","shaderSwap","skip","renderBatch","startIndex","TRIANGLES","deleteBuffer","WebGLFastSpriteBatch","maxSize","renderSprite","filterStack","texturePool","initShaderBuffers","filterBlock","_filterArea","_previous_stencil_mgr","filter","FilterTexture","padding","frameBuffer","_glFilterTexture","vertexArray","uvBuffer","uvArray","inputTexture","outputTexture","filterPass","applyFilterPass","sizeX","sizeY","currentFilter","colorArray","36054","36055","36057","36061","DEFAULT","renderbufferStorage","DEPTH_STENCIL","deleteFramebuffer","deleteTexture","CanvasBuffer","clearRect","CanvasMaskManager","save","cacheAlpha","transform","CanvasGraphics","renderGraphicsMask","clip","restore","tintMethod","tintWithMultiply","fillStyle","toString","substr","fillRect","tintWithPerPixel","rgbValues","pixelData","getImageData","pixels","canHandleAlpha","putImageData","CanvasRenderer","CANVAS","refresh","Canvas","getSmoothingPrefix","navigator","isCocoonJS","screencanvas","rgba","removeView","useNew","device","canUseMultiply","BaseTexture","complete","naturalWidth","naturalHeight","forceLoaded","removeByCanvas","unloadFromGPU","glTexture","fromCanvas","TextureSilentFail","noFrame","isTiling","requiresUpdate","setFrame","onBaseTextureLoaded","_updateUvs","tw","th","define","amd","WheelEventProxy","scaleFactor","deltaMode","_scaleFactor","_deltaMode","originalEvent","VERSION","GAMES","AUTO","HEADLESS","WEBGL_MULTI","NONE","LEFT","RIGHT","UP","DOWN","SPRITE","BUTTON","IMAGE","GRAPHICS","TEXT","TILESPRITE","BITMAPTEXT","GROUP","RENDERTEXTURE","TILEMAP","TILEMAPLAYER","EMITTER","POLYGON","BITMAPDATA","CANVAS_FILTER","WEBGL_FILTER","ELLIPSE","SPRITEBATCH","RETROFONT","POINTER","ROPE","RECTANGLE","MATRIX","POINT","ROUNDEDRECTANGLE","CREATURE","VIDEO","PENDING_ATLAS","HORIZONTAL","VERTICAL","LANDSCAPE","PORTRAIT","ANGLE_UP","ANGLE_DOWN","ANGLE_LEFT","ANGLE_RIGHT","ANGLE_NORTH_EAST","ANGLE_NORTH_WEST","ANGLE_SOUTH_EAST","ANGLE_SOUTH_WEST","TOP_LEFT","TOP_CENTER","TOP_RIGHT","LEFT_TOP","LEFT_CENTER","LEFT_BOTTOM","CENTER","RIGHT_TOP","RIGHT_CENTER","RIGHT_BOTTOM","BOTTOM_LEFT","BOTTOM_CENTER","BOTTOM_RIGHT","trunc","Function","bind","thisArg","bound","args","boundArgs","concat","TypeError","F","proto","arg","forEach","fun","CheapArray","assert","assign","varArgs","hasOwn","hasOwnProperty","nextSource","nextKey","reverseString","string","getProperty","obj","parts","_getProperty","setProperties","props","setProperty","_setProperty","val","currentObj","chanceRoll","chance","random","randomChoice","choice1","choice2","parseDimension","dimension","parseInt","innerWidth","innerHeight","pad","dir","padlen","isPlainObject","nodeType","copyIsArray","deep","mixinPrototype","mixin","replace","mixinKeys","childNodes","cloneNode","diameter","_diameter","_radius","circumference","setTo","copyFrom","copyTo","dest","round","output","circumferencePoint","asDegrees","sample","steps","startAngle","endAngle","linear","offsetPoint","top","bottom","equals","intersects","degToRad","intersectsRectangle","halfWidth","halfHeight","xCornerDist","yCornerDist","intersectsLine","returnPoints","del","p0Exists","pointOnSegment","p1Exists","Ellipse","normx","normy","fromPoints","fromSprite","startSprite","endSprite","useCenter","centerX","centerY","fromAngle","rotateAround","line","asSegment","intersectsPoints","midPoint","centerOn","pointOnLine","fuzzyEqual","xMin","xMax","yMin","yMax","coordinatesOnLine","stepRate","results","sx","sy","err","e2","wrap","uc","ua","ub","empty","bx1","by1","bx2","by2","intersectionWithRectangle","edgeIntersection","closestDistance","normalAngle","fromArray","newPos","translate","tx1","identity","invert","setToPolar","azimuth","clampX","clamp","clampY","equalsXY","fuzzyEquals","fuzzyEqualsXY","angleXY","atan2","radToDeg","atan","getMagnitude","getMagnitudeSq","setMagnitude","magnitude","isZero","limit","expand","perp","rperp","normalRightHand","negative","multiplyAdd","interpolate","project","amt","projectUnit","pointslength","parse","xProp","yProp","isPoint","sortClockwise","center","_points","closed","flattened","toNumberArray","flatten","inside","ix","iy","jx","jy","calculateArea","avgHeight","floorAll","ceilAll","copyFromBounds","inflate","containsRect","intersection","intersectsRaw","union","randomX","randomY","getPoint","sides","inflatePoint","createFromBounds","containsRaw","rx","ry","rw","rh","volume","sameDimensions","NEGATIVE_INFINITY","POSITIVE_INFINITY","EmptyRectangle","RoundedRectangle","Camera","deadzone","roundPx","atLimit","totalInView","onShakeComplete","Signal","onFlashComplete","onFadeComplete","fx","_targetPosition","_edge","_position","intensity","duration","horizontal","vertical","shakeBounds","_fxDuration","_fxType","_fixedView","FOLLOW_LOCKON","FOLLOW_PLATFORMER","FOLLOW_TOPDOWN","FOLLOW_TOPDOWN_TIGHT","SHAKE_BOTH","SHAKE_HORIZONTAL","SHAKE_VERTICAL","ENABLE_FX","boot","Graphics","follow","lerpX","lerpY","helper","unfollow","focusOn","setPosition","focusOnXY","shake","flash","beginFill","drawRect","endFill","fade","updateFX","updateShake","checkBounds","elapsedMS","dispatch","rnd","frac","updateTarget","math","setBoundsToWorld","vx","vw","vy","vh","setSize","resetFX","State","make","input","load","sound","state","tweens","particles","physics","preload","loadUpdate","loadRender","preRender","paused","resumed","pauseUpdate","shutdown","StateManager","pendingState","states","_pendingState","_clearWorld","_clearCache","_created","_args","onStateChange","onInitCallback","onPreloadCallback","onCreateCallback","onUpdateCallback","onRenderCallback","onResizeCallback","onPreRenderCallback","onLoadUpdateCallback","onLoadRenderCallback","onPausedCallback","onResumedCallback","onPauseUpdateCallback","onShutDownCallback","onPause","pause","onResume","resume","autoStart","newState","isBooted","callbackContext","clearWorld","clearCache","checkState","restart","dummy","previousStateKey","clearCurrentState","setCurrentState","totalQueuedFiles","totalQueuedPacks","loadComplete","removeAll","debug","link","unlink","_kickstart","getCurrentState","elapsedTime","renderType","_bindings","_prevParams","memorize","_shouldPropagate","active","_boundDispatch","validateListener","fnName","_registerListener","isOnce","listenerContext","priority","binding","prevIndex","_indexOfListener","SignalBinding","_addBinding","execute","_priority","cur","_listener","addOnce","_destroy","getNumListeners","halt","bindings","paramsArr","forget","dispose","_this","signal","_isOnce","_signal","callCount","params","handlerReturn","detach","isBound","getListener","getSignal","prevPoint","Date","mouse","date","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","sampleRate","iChannel0","iChannel1","iChannel2","iChannel3","setResolution","pointer","toFixed","totalElapsedSeconds","anchorX","anchorY","Cache","Plugin","hasPreUpdate","hasUpdate","hasPostUpdate","hasRender","hasPostRender","postRender","PluginManager","plugins","_len","_i","plugin","postUpdate","Stage","disableVisibilityChange","currentRenderOrderID","_hiddenVar","_onChange","parseConfig","setBackgroundColor","DOM","getOffset","setUserSelect","setTouchAction","checkVisibility","document","hidden","webkitHidden","mozHidden","msHidden","visibilityChange","_onClick","hasFocus","addEventListener","onblur","onfocus","onpagehide","onpageshow","cocoonJSApp","CocoonJS","App","onSuspended","onActivated","focusLoss","focusGain","gamePaused","gameResumed","valueToColor","updateColor","removeEventListener","silent","hash","removeFromHash","Group","addToStage","enableBody","physicsBodyType","Physics","ARCADE","physicsType","alive","ignoreDestroy","pendingDestroy","classType","cursor","inputEnableChildren","updateOnlyExistingChildren","onChildInputDown","onChildInputUp","onChildInputOver","onChildInputOut","enableBodyDebug","physicsSortDirection","onDestroy","cursorIndex","fixedToCamera","cameraOffset","_sortProperty","RETURN_NONE","RETURN_TOTAL","RETURN_CHILD","RETURN_ALL","SORT_ASCENDING","SORT_DESCENDING","updateZ","addToHash","inputEnabled","events","onAddedToGroup$dispatch","addAt","addMultiple","moveAll","getAt","createMultiple","quantity","singleKey","singleFrame","align","cellWidth","cellHeight","alignIn","resetCursor","next","previous","swap","child1","bringToTop","getIndex","sendToBack","moveUp","moveDown","xy","getByName","oldChild","newChild","hasProperty","operation","checkProperty","checkAlive","checkVisible","setAll","setAllChildren","checkAll","checkAny","addAll","property","amount","subAll","multiplyAll","divideAll","kill","killAll","callAllExists","revive","reviveAll","resetAll","checkExists","resetChild","existsValue","callbackFromArray","callAll","method","methodLength","contextLength","renderOrderID","predicate","ArraySet","forEachExists","iterate","forEachAlive","forEachDead","order","ascendingSortHandler","descendingSortHandler","customSort","sortHandler","returnType","total","getFirst","getFirstExists","createIfNull","getFirstAlive","getFirstDead","loadTexture","getTop","getBottom","getClosestTo","tempDistance","getFurthestFrom","countLiving","countDead","getRandom","ArrayUtils","getRandomItem","getRandomExists","list","getAll","pick","destroyPhase","onRemovedFromGroup$dispatch","group","destroyTexture","removeBetween","scatter","shuffle","destroyChildren","soft","_definedSize","stateChange","setBounds","useBounds","wrapAll","between","Game","physicsConfig","multiTexture","isRunning","raf","net","Device","lockRender","pendingStep","stepCount","onBlur","onFocus","_paused","_codePaused","currentUpdateID","updatesThisFrame","rendersThisFrame","_deltaTime","_lastCount","_spiraling","fpsProblemNotifier","forceSingleUpdate","forceSingleRender","dropFrames","_nextFpsNotification","enableDebug","RandomDataGenerator","now","whenReady","seed","ScaleManager","setUpRenderer","GameObjectFactory","GameObjectCreator","Loader","Time","TweenManager","Input","SoundManager","Particles","Create","Net","Debug","isDisabled","showDebugHeader","RequestAnimationFrame","stopFocus","focus","isReady","onReady","hideBanner","webAudio","ie","setImageRenderingCrisp","webGL","contextRestored","webGLRendererError","cocoonJS","smoothed","addToDOM","preventDefault","clearGLTextures","updateLogic","desiredFpsMult","updateRender","slowMotion","desiredFps","slowStep","elapsed","countUpdate","countRender","enableStep","disableStep","removeFromDOM","muteOnPause","setMute","cordova","iOS","unsetMute","hitCanvas","hitContext","moveCallbacks","customCandidateHandler","customCandidateHandlerContext","pollRate","multiInputOverride","MOUSE_TOUCH_COMBINE","maxPointers","tapRate","doubleTapRate","holdRate","justPressedRate","justReleasedRate","recordPointerHistory","recordRate","recordLimit","touchLockCallbacks","pointer1","pointer2","pointer3","pointer4","pointer5","pointer6","pointer7","pointer8","pointer9","pointer10","pointers","activePointer","mousePointer","keyboard","touch","mspointer","gamepad","resetLocked","onDown","onUp","onTap","onHold","minPriorityID","interactiveItems","_localPoint","_pollCounter","_oldPosition","_x","_y","MOUSE_OVERRIDES_TOUCH","TOUCH_OVERRIDES_MOUSE","MAX_POINTERS","Pointer","PointerMode","CURSOR","addPointer","Mouse","Touch","MSPointer","Keyboard","Gamepad","_onClickTrampoline","onClickTrampoline","setInteractiveCandidateHandler","addMoveCallback","addTouchLockCallback","onEnd","removeTouchLockCallback","executeTouchLockCallbacks","cb","deleteMoveCallback","CONTACT","hard","resetSpeed","startPointer","countActivePointers","updatePointer","identifier","move","stopPointer","getPointer","isActive","getPointerFromIdentifier","getPointerFromId","pointerId","getLocalPosition","Creature","TileSprite","graphicsData","fill","processClickTrampolines","mouseDownCallback","mouseUpCallback","mouseOutCallback","mouseOverCallback","mouseWheelCallback","capture","button","wheelDelta","locked","stopOnGameOut","pointerLock","_onMouseDown","_onMouseMove","_onMouseUp","_onMouseOut","_onMouseOver","_onMouseWheel","_wheelEvent","NO_BUTTON","LEFT_BUTTON","MIDDLE_BUTTON","RIGHT_BUTTON","BACK_BUTTON","FORWARD_BUTTON","WHEEL_UP","WHEEL_DOWN","android","chrome","onMouseDown","onMouseMove","onMouseUp","_onMouseUpGlobal","onMouseUpGlobal","_onMouseOutGlobal","onMouseOutGlobal","onMouseOut","onMouseOver","onMouseWheel","wheelEvent","mouseMoveCallback","withinGame","resetButtons","bindEvent","deltaY","requestPointerLock","element","mozRequestPointerLock","webkitRequestPointerLock","_pointerLockChange","pointerLockChange","pointerLockElement","mozPointerLockElement","webkitPointerLockElement","releasePointerLock","exitPointerLock","mozExitPointerLock","webkitExitPointerLock","_stubsGenerated","prop","makeBinder","detail","deltaX","wheelDeltaX","deltaZ","pointerDownCallback","pointerMoveCallback","pointerUpCallback","_onMSPointerDown","_onMSPointerMove","_onMSPointerUp","_onMSPointerUpGlobal","_onMSPointerOut","_onMSPointerOver","onPointerDown","onPointerMove","onPointerUp","onPointerUpGlobal","onPointerOut","onPointerOver","pointerType","DeviceButton","buttonCode","isDown","isUp","timeDown","timeUp","repeats","altKey","shiftKey","ctrlKey","onFloat","startStop","condition","padFloat","justPressed","justReleased","pointerMode","leftButton","middleButton","rightButton","backButton","forwardButton","eraserButton","ERASER_BUTTON","_holdSent","_history","_nextDrop","_stateReset","clientX","clientY","pageX","pageY","screenX","screenY","rawMovementX","rawMovementY","movementX","movementY","isMouse","previousTapTime","totalTouches","msSinceLastClick","targetObject","interactiveCandidates","positionDown","positionUp","_clickTrampolines","_trampolineTargetObject","processButtonsDown","processButtonsUp","processButtonsUpDown","buttons","down","toLowerCase","updateButtons","totalActivePointers","_touchedHandler","processInteractiveObjects","shift","fromClick","pollLocked","mozMovementX","webkitMovementX","mozMovementY","webkitMovementY","noPause","isDragged","highestRenderOrderID","highestInputPriorityID","candidateTarget","currentNode","checked","validForInput","checkPointerDown","checkPointerOver","priorityID","swapTarget","newTarget","_pointerOutHandler","_pointerOverHandler","leave","currentPointers","addClickTrampoline","callbackArgs","trampolines","trampoline","_releasedHandler","resetMovement","touchStartCallback","touchMoveCallback","touchEndCallback","touchEnterCallback","touchLeaveCallback","touchCancelCallback","_onTouchStart","_onTouchMove","_onTouchEnd","_onTouchEnter","_onTouchLeave","_onTouchCancel","onTouchStart","onTouchMove","onTouchEnd","onTouchEnter","onTouchLeave","onTouchCancel","consumeDocumentTouches","_documentTouchMove","changedTouches","InputHandler","useHandCursor","_setHandCursor","allowHorizontalDrag","allowVerticalDrag","snapOffset","snapOnDrag","snapOnRelease","snapX","snapY","snapOffsetX","snapOffsetY","pixelPerfectOver","pixelPerfectClick","pixelPerfectAlpha","draggable","boundsRect","boundsSprite","scaleLayer","dragOffset","dragFromCenter","dragStopBlocksInputUp","dragStartPoint","dragDistanceThreshold","dragTimeThreshold","downPoint","snapPoint","_dragPoint","_dragPhase","_pendingDrag","_dragTimePass","_dragDistancePass","_wasEnabled","_tempPoint","_pointerData","camX","camY","isOver","isOut","timeOver","timeOut","downDuration","onAddedToGroup","addedToGroup","onRemovedFromGroup","removedFromGroup","highestID","highestRenderID","includePixelPerfect","isPixelPerfect","pointerX","pointerY","pointerDown","pointerUp","pointerTimeDown","pointerTimeUp","pointerOver","pointerOut","pointerTimeOver","pointerTimeOut","pointerDragged","fastTest","checkPixel","_dx","_dy","startDrag","_draggedPointerID","updateDrag","sendEvent","onInputOver$dispatch","onInputOut$dispatch","onInputDown$dispatch","dragTimeElapsed","onInputUp$dispatch","stopDrag","fromStart","pointerLocalCoord","globalToLocal","checkBoundsRect","checkBoundsSprite","onDragUpdate","justOver","delay","overDuration","justOut","enableDrag","lockCenter","pixelPerfect","alphaThreshold","disableDrag","boundsCenterLocalCoord","onDragStart$dispatch","globalToLocalX","grid","boundsFluid","scaleFluidInversed","globalToLocalY","globalCoord","onDragStop$dispatch","setDragLock","allowHorizontal","allowVertical","enableSnap","onDrag","onRelease","disableSnap","_gamepadIndexMap","_rawPads","_active","_gamepadSupportAvailable","webkitGetGamepads","webkitGamepads","userAgent","getGamepads","_prevRawGamepadTypes","_prevTimestamps","onConnectCallback","onDisconnectCallback","onDownCallback","onUpCallback","onAxisCallback","onFloatCallback","_ongamepadconnected","_gamepaddisconnected","_gamepads","SinglePad","addCallbacks","callbacks","onConnect","onDisconnect","onAxis","_onGamepadConnected","onGamepadConnected","_onGamepadDisconnected","onGamepadDisconnected","newPad","connect","removedPad","disconnect","_pollGamepads","pad1","pollStatus","pad2","pad3","pad4","rawGamepads","gamepadsChanged","_rawPad","singlePad","validConnections","rawIndices","padIndices","connected","rawPad","setDeadZones","deadZone","BUTTON_0","BUTTON_1","BUTTON_2","BUTTON_3","BUTTON_4","BUTTON_5","BUTTON_6","BUTTON_7","BUTTON_8","BUTTON_9","BUTTON_10","BUTTON_11","BUTTON_12","BUTTON_13","BUTTON_14","BUTTON_15","AXIS_0","AXIS_1","AXIS_2","AXIS_3","AXIS_4","AXIS_5","AXIS_6","AXIS_7","AXIS_8","AXIS_9","XBOX360_A","XBOX360_B","XBOX360_X","XBOX360_Y","XBOX360_LEFT_BUMPER","XBOX360_RIGHT_BUMPER","XBOX360_LEFT_TRIGGER","XBOX360_RIGHT_TRIGGER","XBOX360_BACK","XBOX360_START","XBOX360_STICK_LEFT_BUTTON","XBOX360_STICK_RIGHT_BUTTON","XBOX360_DPAD_LEFT","XBOX360_DPAD_RIGHT","XBOX360_DPAD_UP","XBOX360_DPAD_DOWN","XBOX360_STICK_LEFT_X","XBOX360_STICK_LEFT_Y","XBOX360_STICK_RIGHT_X","XBOX360_STICK_RIGHT_Y","PS3XC_X","PS3XC_CIRCLE","PS3XC_SQUARE","PS3XC_TRIANGLE","PS3XC_L1","PS3XC_R1","PS3XC_L2","PS3XC_R2","PS3XC_SELECT","PS3XC_START","PS3XC_STICK_LEFT_BUTTON","PS3XC_STICK_RIGHT_BUTTON","PS3XC_DPAD_UP","PS3XC_DPAD_DOWN","PS3XC_DPAD_LEFT","PS3XC_DPAD_RIGHT","PS3XC_STICK_LEFT_X","PS3XC_STICK_LEFT_Y","PS3XC_STICK_RIGHT_X","PS3XC_STICK_RIGHT_Y","padParent","_padParent","_prevTimestamp","_buttons","_buttonsLen","_axes","_axesLen","getButton","timestamp","rawButtonVal","isNaN","processButtonDown","processButtonUp","processButtonFloat","processAxisChange","triggerCallback","disconnectingIndex","axisCode","buttonValue","Key","keycode","_enabled","durationUp","keyCode","onHoldCallback","onHoldContext","_justDown","_justUp","processKeyDown","processKeyUp","upDuration","pressEvent","onPressCallback","_keys","_capture","_onKeyDown","_onKeyPress","_onKeyUp","_k","onPress","removeCallbacks","addKey","addKeyCapture","addKeys","removeKey","removeKeyCapture","createCursorKeys","up","KeyCode","processKeyPress","clearCaptures","String","fromCharCode","charCode","A","charCodeAt","C","D","E","H","J","K","L","M","O","P","Q","R","S","T","U","V","W","X","Y","Z","ZERO","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","NUMPAD_0","NUMPAD_1","NUMPAD_2","NUMPAD_3","NUMPAD_4","NUMPAD_5","NUMPAD_6","NUMPAD_7","NUMPAD_8","NUMPAD_9","NUMPAD_MULTIPLY","NUMPAD_ADD","NUMPAD_ENTER","NUMPAD_SUBTRACT","NUMPAD_DECIMAL","NUMPAD_DIVIDE","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","F13","F14","F15","COLON","EQUALS","COMMA","UNDERSCORE","PERIOD","QUESTION_MARK","TILDE","OPEN_BRACKET","BACKWARD_SLASH","CLOSED_BRACKET","QUOTES","BACKSPACE","TAB","CLEAR","ENTER","SHIFT","CONTROL","ALT","CAPS_LOCK","ESC","SPACEBAR","PAGE_UP","PAGE_DOWN","END","HOME","PLUS","MINUS","INSERT","DELETE","HELP","NUM_LOCK","match","Component","Angle","wrapAngle","Animation","play","frameRate","loop","killOnComplete","animations","AutoCull","autoCull","inCamera","checkWorldBounds","Bounds","container","alignTo","BringToTop","Core","skipTypeChecks","install","components","Events","PhysicsBody","AnimationManager","LoadTexture","FixedToCamera","previousRotation","preUpdateChildren","fresh","_exists","P2JS","customRender","Crop","cropRect","_crop","updateCrop","resetFrame","oldX","oldY","oldW","oldH","_frame","Delta","Destroy","onDestroy$dispatch","removeFrom","Video","onChangeSource","resizeFrame","BitmapText","_glyphs","_parent","_onDestroy","_onAddedToGroup","_onRemovedFromGroup","_onKilled","_onRevived","_onEnterBounds","_onOutOfBounds","_onInputOver","_onInputOut","_onInputDown","_onInputUp","_onDragStart","_onDragUpdate","_onDragStop","_onAnimationStart","_onAnimationComplete","_onAnimationLoop","onKilled","onRevived","onOutOfBounds","onEnterBounds","onInputOver","onInputOut","onInputDown","onInputUp","onDragStart","onDragStop","onAnimationStart","onAnimationComplete","onAnimationLoop","backing","_fixedToCamera","Health","health","maxHealth","damage","setHealth","heal","InCamera","InputEnabled","InWorld","outOfCameraBoundsKill","_outOfBoundsFired","onEnterBounds$dispatch","onOutOfBounds$dispatch","outOfBoundsKill","inWorld","LifeSpan","lifespan","physicsElapsedMS","onRevived$dispatch","onKilled$dispatch","stopAnimation","BitmapData","hasFrameData","loadFrameData","getFrameData","frameData","Tilemap","TilemapLayer","img","getImage","trimmed","spriteSourceSizeX","spriteSourceSizeY","sourceSizeW","sourceSizeH","refreshTexture","frameName","Overlap","_reset","Reset","ScaleMinMax","scaleMin","scaleMax","checkTransform","setScaleMinMax","Smoothed","existing","weapon","bulletClass","Weapon","createBullets","Image","creature","mesh","tween","physicsGroup","SpriteBatch","audio","audioSprite","addSprite","tileSprite","rope","Rope","text","Text","overFrame","outFrame","downFrame","upFrame","Button","emitter","maxParticles","Arcade","Emitter","retroFont","font","characterWidth","characterHeight","chars","charsPerRow","xSpacing","ySpacing","xOffset","yOffset","RetroFont","bitmapText","tilemap","tileWidth","tileHeight","addToCache","uuid","addRenderTexture","video","bitmapData","addBitmapData","Tween","preUpdatePhysics","preUpdateLifeSpan","preUpdateInWorld","preUpdateCore","_onOverFrame","_onOutFrame","_onDownFrame","_onUpFrame","onOverSound","onOutSound","onDownSound","onUpSound","onOverSoundMarker","onOutSoundMarker","onDownSoundMarker","onUpSoundMarker","onOverMouseOnly","justReleasedPreventsOver","freezeFrames","forceOut","setFrames","onInputOverHandler","onInputOutHandler","onInputDownHandler","onInputUpHandler","clearFrames","setStateFrame","switchImmediately","frameKey","changeStateFrame","setStateSound","marker","soundKey","markerKey","Sound","AudioSprite","playStateSound","setSounds","overSound","overMarker","downSound","downMarker","outSound","outMarker","upSound","upMarker","setOverSound","setOutSound","setDownSound","setUpSound","fastSpriteBatch","ready","isRotated","childTransform","skipPool","ctx","imageData","FrameData","textureFrame","addFrame","Frame","disableTextureUpload","cls","_image","_pos","_size","_scale","_rotate","_alpha","prev","_anchor","_tempR","_tempG","_tempB","_circle","_swapCanvas","moveH","moveV","draw","onload","addImage","toDataURL","processPixelRGB","pixel","createColor","unpackPixel","getPixel32","setPixel32","processPixel","replaceRGB","g1","g2","region","packPixel","setHSL","bHaveH","bHaveS","bHaveL","HSLtoRGB","shiftHSL","red","green","blue","immediate","LITTLE_ENDIAN","setPixel","getPixel","getPixelRGB","hsl","hsv","getPixels","getFirstPixel","scan","newWidth","newHeight","getCanvas","op","copyTransform","copyRect","drawGroup","drawGroupProxy","drawFull","renderGraphics","shadow","blur","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","alphaMask","sourceRect","maskRect","blendSourceAtop","blendReset","extract","destination","prevFont","fillText","beginPath","arc","closePath","moveTo","lineTo","lineWidth","strokeStyle","stroke","polygon","textureLine","createPattern","blendSourceOver","blendSourceIn","blendSourceOut","blendDestinationOver","blendDestinationIn","blendDestinationOut","blendDestinationAtop","blendXor","blendAdd","blendMultiply","blendScreen","blendOverlay","blendDarken","blendLighten","blendColorDodge","blendColorBurn","blendHardLight","blendSoftLight","blendDifference","blendExclusion","blendHue","blendSaturation","blendColor","blendLuminosity","copyBitmapData","destRowStart","getSmoothingEnabled","setSmoothingEnabled","getTransform","translateX","translateY","skewX","skewY","EarCut","holeIndices","dim","hasHoles","outerLen","outerNode","linkedList","eliminateHoles","earcutLinked","clockwise","insertNode","filterPoints","again","steiner","removeNode","ear","pass","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","minTX","minTY","maxTX","maxTY","minZ","zOrder","maxZ","nextZ","prevZ","locallyInside","isValidDiagonal","splitPolygon","getLeftmost","compareX","eliminateHole","hole","findHoleBridge","hx","hy","qx","tan","tanMin","sortLinked","q","tail","numMerges","pSize","qSize","inSize","leftmost","intersectsPolygon","middleInside","Node","an","bp","stencilBufferLimit","lastIndex","clearDirty","graphicsDataPool","switchMode","buildPoly","buildComplexPoly","buildLine","buildRectangle","buildCircle","buildRoundedRectangle","upload","WebGLGraphicsData","rectData","fillColor","fillAlpha","vertPos","tempPoints","rrectData","recPoints","quadraticBezierCurve","vecPos","fromX","fromY","cpX","cpY","toX","toY","getPt","n1","n2","perc","xa","ya","xb","yb","circleData","seg","totalSegs","firstPoint","lastPoint","midPointX","midPointY","unshift","p1x","p1y","p2x","p2y","p3x","p3y","perpx","perpy","perp2x","perp2y","perp3x","perp3y","indexCount","indexStart","lineColor","lineAlpha","glPoints","glIndicies","updateGraphicsTint","_fillTint","_lineTint","strokeRect","ox","oy","xe","ye","xm","ym","bezierCurveTo","maxRadius","quadraticCurveTo","tintR","tintG","tintB","GraphicsData","currentPath","boundsPadding","_localBounds","_boundsDirty","webGLDirty","cachedSpriteDirty","updateLocalBounds","drawTriangle","cull","triangle","cameraToFace","faceNormal","drawPolygon","drawTriangles","point1","point2","point3","lineStyle","drawShape","cpX2","cpY2","dt2","dt3","arcTo","mm","dd","cc","tt","k1","k2","j1","j2","qy","anticlockwise","segments","sweep","segs","startX","startY","filling","theta","theta2","cTheta","sTheta","segMinus","remainder","drawRoundedRect","drawCircle","drawEllipse","canvasBuffer","updateCachedSpriteTexture","_prevTint","tempPoint","cachedSprite","destroyCachedSprite","textureBuffer","tempMatrix","renderXY","renderRawXY","updateBase","realResolution","getBase64","webGLPixels","Uint8Array","readPixels","tempCanvas","canvasData","textBounds","strokeColors","fontStyles","fontWeights","autoRound","useAdvancedWrap","splitRegExp","characterLimitSize","characterLimitSuffix","_res","_text","_fontComponents","_lineSpacing","_charCount","setStyle","updateText","setShadow","shadowStroke","shadowFill","newStyle","backgroundColor","boundsAlignH","boundsAlignV","strokeThickness","wordWrap","wordWrapWidth","maxLines","tabs","fontToComponents","fontStyle","fontVariant","fontWeight","fontSize","componentsToFont","outputText","substring","runWordWrap","lines","lineWidths","maxLineWidth","fontProperties","determineFontProperties","drawnLines","measureLine","measureText","tab","section","snapToCeil","lineHeight","lineSpacing","textBaseline","lineCap","lineJoin","linePositionX","linePositionY","ascent","updateLine","updateShadow","strokeText","renderTabLine","snap","lineLength","letter","clearColors","clearFontValues","addColor","addStrokeColor","addFontStyle","addFontWeight","weight","precalculateWordWrap","advancedWordWrap","basicWordWrap","linesCount","currentLineWidth","words","word","wordWithSpace","wordWidth","newWord","secondPart","spaceLeft","wordWidthWithSpace","updateFont","family","exec","fontFamily","setText","parseList","setTextBounds","properties","fontPropertiesCache","fontPropertiesCanvas","fontPropertiesContext","baseline","descent","imagedata","setCharacterLimit","characterLimit","suffix","parseFloat","createElement","textWidth","textHeight","_prevAnchor","_maxWidth","_data","getBitmapFont","_font","_fontSize","_align","_tint","sourceWidth","sourceHeight","scanLine","lastSpace","wrappedWidth","prevCharCode","maxWidth","test","charAt","charData","kerning","xAdvance","cleanText","re","purgeGlyphs","kept","checkImageKey","characterSpacingX","characterSpacingY","characterPerRow","multiLine","autoUpperCase","customSpacingX","customSpacingY","fixedWidth","fontSet","grabData","currentX","currentY","updateFrameData","stamp","ALIGN_LEFT","ALIGN_RIGHT","ALIGN_CENTER","TEXT_SET1","TEXT_SET2","TEXT_SET3","TEXT_SET4","TEXT_SET5","TEXT_SET6","TEXT_SET7","TEXT_SET8","TEXT_SET9","TEXT_SET10","TEXT_SET11","setFixedWidth","lineAlignment","content","characterSpacing","allowLowerCase","buildRetroFontText","getLongestLine","pasteLine","longestLine","removeUnsupportedCharacters","stripCR","newString","aChar","code","updateOffset","diffX","diffY","frames","getFrames","newText","toUpperCase","_hasUpdateAnimation","_updateAnimationCallback","canvasPadding","drawMode","updateAnimation","nextPoint","perpLength","_vertexBuffer","_initWebGL","_renderStrip","_indexBuffer","_uvBuffer","_colorBuffer","_renderCanvasTriangleStrip","_renderCanvasTriangles","_renderCanvasDrawTriangle","index0","textureSource","textureWidth","textureHeight","u0","v2","paddingX","paddingY","normX","normY","deltaA","deltaB","deltaC","deltaD","deltaE","deltaF","renderStripFlat","strip","rawX","rawY","_updateAnimation","difference","_scroll","textureDebug","tilePattern","frameWidth","frameHeight","physicsElapsed","autoScroll","stopScroll","generateTilingTexture","restartBatch","sessionBlendMode","forcePowerOfTwo","targetWidth","targetHeight","getNextPowerOfTwo","pool","getTotal","getFree","deviceReadyAt","initialized","desktop","iOSVersion","nodeWebkit","electron","ejecta","crosswalk","chromeOS","linux","macOS","windows","windowsPhone","canvasBitBltShift","file","fileSystem","localStorage","worker","css3D","typedArray","vibration","getUserMedia","quirksMode","arora","chromeVersion","epiphany","firefox","firefoxVersion","ieVersion","trident","tridentVersion","mobileSafari","midori","opera","safari","safariVersion","webApp","silk","audioData","ogg","opus","mp3","wav","m4a","webm","dolby","oggVideo","h264Video","mp4Video","webmVideo","vp9Video","hlsVideo","iPhone","iPhone4","iPad","pixelRatio","littleEndian","support32bit","fullscreen","requestFullscreen","cancelFullscreen","fullscreenKeyboard","onInitialized","nonPrimer","readyCheck","_readyCheck","_monitor","_queue","readyState","setTimeout","_initialize","_checkIsLittleEndian","_checkIsUint8ClampedImageData","Uint8ClampedArray","createImageData","vita","kindle","RegExp","$1","_checkOS","$3","process","versions","_checkBrowser","audioElement","canPlayType","major","minor","$2","_checkAudio","videoElement","_checkVideo","has3d","el","transforms","webkitTransform","OTransform","msTransform","MozTransform","insertBefore","getComputedStyle","getPropertyValue","_checkCSS3D","Int8Array","Int32Array","vibrate","webkitVibrate","mozVibrate","msVibrate","getItem","WebGLRenderingContext","compatMode","webkitGetUserMedia","mozGetUserMedia","msGetUserMedia","oGetUserMedia","URL","webkitURL","mozURL","msURL","_checkFeatures","s1","s2","_checkCanvasFeatures","fs","cfs","Element","_checkFullScreenSupport","documentElement","maxTouchPoints","PointerEvent","MSPointerEvent","msPointerEnabled","pointerEnabled","canPlayAudio","canPlayVideo","needsTouchUnlock","PhaserGlobal","fakeiOSTouchLock","isAndroidStockBrowser","matches","display","msTouchAction","overflowHidden","getElementById","overflow","appendChild","parentNode","vendor","prefix","types","msInterpolationMode","setImageRenderingBicubic","forceSetTimeOut","vendors","requestAnimationFrame","cancelAnimationFrame","_isSetTimeOut","_onLoop","_timeOutID","updateSetTimeout","updateRAF","rafTime","timeToCall","clearTimeout","isSetTimeOut","isRAF","DEG_TO_RAD","RAD_TO_DEG","degrees","radians","fuzzyLessThan","fuzzyGreaterThan","fuzzyCeil","fuzzyFloor","average","shear","snapTo","gap","snapToFloor","roundTo","place","floorTo","ceilTo","rotateToAngle","currentAngle","targetAngle","getShortestAngle","angleBetween","angleBetweenY","angleBetweenPoints","angleBetweenPointsY","reverseAngle","angleRad","normalizeAngle","maxAdd","minSub","wrapValue","isOdd","isEven","minProperty","maxProperty","linearInterpolation","bezierInterpolation","bernstein","catmullRomInterpolation","catmullRom","factorial","res","roundAwayFromZero","sinCosGenerator","sinAmplitude","cosAmplitude","frequency","frq","cosTable","sinTable","hypot","distanceSq","distancePow","clampBottom","within","mapLinear","smoothstep","smootherstep","sign","percent","seeds","s0","sow","integer","real","integerInRange","realInRange","ary","weightedPick","QuadTree","maxObjects","maxLevels","_empty","subWidth","subHeight","populate","populateHandler","insert","retrieve","returnObjects","getHostName","location","hostname","checkDomainName","domain","updateQueryString","redirect","href","separator","getQueryString","parameter","keyValues","search","decodeURI","decodeURIComponent","frameBased","_tweens","_add","easeMap","Power0","Easing","Power1","Power2","Power3","Power4","Linear","None","Quad","Quadratic","Out","Cubic","Quart","Quartic","Quint","Quintic","Sine","Sinusoidal","Expo","Exponential","Circ","Circular","Elastic","Back","Bounce","Quad.easeIn","In","Cubic.easeIn","Quart.easeIn","Quint.easeIn","Sine.easeIn","Expo.easeIn","Circ.easeIn","Elastic.easeIn","Back.easeIn","Bounce.easeIn","Quad.easeOut","Cubic.easeOut","Quart.easeOut","Quint.easeOut","Sine.easeOut","Expo.easeOut","Circ.easeOut","Elastic.easeOut","Back.easeOut","Bounce.easeOut","Quad.easeInOut","InOut","Cubic.easeInOut","Quart.easeInOut","Quint.easeInOut","Sine.easeInOut","Expo.easeInOut","Circ.easeInOut","Elastic.easeInOut","Back.easeInOut","Bounce.easeInOut","_pauseAll","_resumeAll","pendingDelete","_manager","addTweens","numTweens","isTweening","checkIsRunning","some","_pause","_resume","pauseAll","resumeAll","manager","timeline","timeScale","repeatCounter","onStart","onLoop","onRepeat","onChildComplete","onComplete","chainedTween","isPaused","_onUpdateCallback","_onUpdateCallbackContext","_pausedTime","_hasStarted","ease","yoyo","Default","TweenData","vEnd","loadValues","updateTweenData","repeatDelay","yoyoDelay","easing","interpolation","repeatAll","chain","startTime","status","PENDING","RUNNING","LOOPED","COMPLETE","generateData","vStart","vStartCache","vEndCache","repeatTotal","inReverse","easingFunction","interpolationFunction","interpolationContext","isFrom","ms","fps","blob","reversed","asin","prevTime","_desiredFps","suggestedFps","advancedTiming","updates","renders","ups","rps","fpsMin","fpsMax","msMin","msMax","pauseDuration","timeExpected","Timer","_frameCount","_elapsedAccumulator","_started","_timeLastSecond","_pauseStarted","_justResumed","_timers","timer","autoDestroy","previousDateNow","updateAdvancedTiming","updateTimers","interval","elapsedSince","since","elapsedSecondsSince","running","expired","nextTick","timeCap","_pauseTotal","_now","_marked","_diff","_newTick","MINUTE","SECOND","HALF","QUARTER","repeatCount","TimerEvent","clearEvents","clearPendingEvents","adjustEvents","baseTime","currentFrame","currentAnim","updateIfVisible","isLoaded","_frameData","_anims","_outputFrames","anim","copyFrameData","useNumericIndex","getFrameIndexes","validateFrames","checkFrameName","isPlaying","getAnimation","refreshFrame","gotFrame","getFrame","getFrameByName","_frameIndex","_frames","loopCount","isFinished","_pauseStartTime","_frameDiff","_frameSkip","onUpdate","isReversed","_timeLastFrame","_timeNextFrame","updateCurrentFrame","onAnimationStart$dispatch","reverseOnce","frameId","useLocalFrameIndex","frameIndex","directionalOffset","dispatchComplete","onAnimationComplete$dispatch","onAnimationLoop$dispatch","signalUpdate","fromPlay","generateFrameNames","zeroPad","spriteSourceSizeW","spriteSourceSizeH","setTrim","actualWidth","actualHeight","destX","destY","destWidth","destHeight","getRect","_frameNames","getFrameRange","AnimationParser","spriteSheet","frameMax","margin","spacing","skipFrames","JSONData","json","newFrame","filename","sourceSize","spriteSourceSize","JSONDataPyxel","tileheight","tilewidth","JSONDataHash","XMLData","xml","getElementsByTagName","frameX","frameY","autoResolveURL","binary","bitmapFont","compressedTexture","_urlMap","_urlResolver","_urlTemp","onSoundUnlock","_cacheMap","TEXTURE","SOUND","PHYSICS","BINARY","BITMAPFONT","JSON","XML","SHADER","RENDER_TEXTURE","_pendingCount","_addImages","DEFAULT_KEY","DEFAULT_SRC","MISSING","MISSING_KEY","MISSING_SRC","READY_TIMEOUT","addCompressedTextureMetaData","extension","arrayBuffer","removeImage","LoaderParser","fileFormat","_resolveURL","addCanvas","addImageAsync","_removePending","_addPending","addDefaultImage","addMissingImage","addSound","audioTag","decoded","isDecoding","touchLocked","addText","addPhysicsData","addTilemap","mapData","addBinary","binaryData","addBitmapFont","atlasData","atlasType","jsonBitmapFont","xmlBitmapFont","addBitmapFontFromAtlas","atlasKey","atlasFrame","dataKey","dataType","getBaseTexture","fontData","getJSON","getXML","addJSON","addXML","addVideo","isBlob","addShader","addSpriteSheet","addTextureAtlas","TEXTURE_ATLAS_XML_STARLING","TEXTURE_ATLAS_JSON_PYXEL","reloadSound","getSound","reloadSoundComplete","updateSound","decodedSound","isSoundDecoded","isSoundReady","checkKey","checkURL","checkCanvasKey","checkTextureKey","checkSoundKey","checkTextKey","checkPhysicsKey","checkTilemapKey","checkBinaryKey","checkBitmapDataKey","checkBitmapFontKey","checkJSONKey","checkXMLKey","checkVideoKey","checkShaderKey","checkRenderTextureKey","full","getTextureFrame","getSoundData","getText","getPhysicsData","fixtureKey","fixtures","fixture","getTilemapData","getBinary","getBitmapData","getVideo","getShader","getRenderTexture","getFrameCount","getFrameByIndex","getURL","getKeys","removeCanvas","destroyBaseTexture","removeSound","removeText","removePhysics","removeTilemap","removeBinary","removeBitmapData","removeBitmapFont","removeJSON","removeXML","removeVideo","removeShader","removeRenderTexture","removeSpriteSheet","removeTextureAtlas","baseURL","destroyItem","readyTimeout","_ready","_checkReady","isLoading","preloadSprite","crossOrigin","headers","requestedWith","onLoadStart","onLoadComplete","onPackComplete","onFileStart","onFileComplete","onFileError","enableParallel","maxParallelDownloads","_withSyncPointDepth","_fileList","_flightQueue","_processingHead","_fileLoadStarted","_totalPackCount","_totalFileCount","_loadedPackCount","_loadedFileCount","TEXTURE_ATLAS_JSON_ARRAY","TEXTURE_ATLAS_JSON_HASH","PHYSICS_LIME_CORONA_JSON","PHYSICS_PHASER_JSON","setPreloadSprite","checkKeyExists","getAssetIndex","bestFound","loaded","loading","getAsset","fileIndex","addToFileList","overwrite","syncPoint","currentFile","replaceInFileList","pack","imageFromBitmapData","imageFromGrid","imageFromTexture","pixelWidth","pixelHeight","palette","exkey","images","urls","script","spritesheet","autoDecode","noAudio","jsonURL","jsonData","audiosprite","loadEvent","asBlob","CSV","TILED_JSON","LIME_CORONA_JSON","textureURL","atlasURL","parseXml","atlasJSONArray","atlas","atlasJSONHash","atlasXML","withSyncPoint","addSyncPoint","asset","removeFile","updateProgress","processLoadQueue","finishedLoading","requestUrl","requestObject","progress","syncblock","inflightLimit","processPack","loadFile","abnormal","asyncComplete","errorMessage","packData","transformUrl","xhrLoad","fileComplete","loadImageTag","getAudioURL","usingWebAudio","usingAudioTag","loadAudioTag","fileError","getVideoURL","loadVideoTag","jsonLoadComplete","xmlLoadComplete","csvLoadComplete","onerror","controls","autoplay","videoLoadEvent","canplay","Audio","playThroughEvent","xhr","XMLHttpRequest","open","responseType","setRequestHeader","message","send","videoType","uri","lastIndexOf","audioType","reason","loadNext","responseText","response","decode","language","defer","head","contentType","domparser","DOMParser","parseFromString","ActiveXObject","async","loadXML","totalLoadedFiles","totalLoadedPacks","progressFloat","info","common","getAttribute","letters","kernings","second","finalizeBitmapFont","_face","_lineHeight","_id","_xoffset","_yoffset","_xadvance","_second","_first","_amount","bitmapFontData","pvr","uintArray","byteArray","pvrHeader","pixelFormat","flags","colorSpace","channelType","depth","numberOfSurfaces","numberOfFaces","numberOfMipmaps","metaDataSize","byteLength","dds","ddsHeader","pitch","mipmapCount","formatSize","formatFlag","formatFourCC","formatBitCount","formatRBitMask","formatGBitMask","formatBBitMask","formatABitMask","caps1","caps2","caps3","caps4","reserved2","DXGIFormat","resourceDimension","miscFlag","arraySize","ktx","ktxHeader","imageSizeOffset","imageSize","glInternalFormat","endianness","glType","glTypeSize","glFormat","glBaseInternalFormat","pixelDepth","numberOfArrayElements","numberOfMipmapLevels","bytesOfKeyValueData","keyAndValueByteSize","pkm","pkmHeader","originalWidth","originalHeight","autoplayKey","sounds","spritemap","addMarker","connectToMaster","markers","totalDuration","currentTime","durationMS","stopTime","pausedPosition","pausedTime","currentMarker","fadeTween","pendingPlayback","override","allowMultiple","externalNode","masterGainNode","gainNode","_sound","_globalVolume","_markedToDelete","_removeFromSoundManager","masterGain","createGain","createGainNode","gain","soundHasUnlocked","onDecoded","onPlay","onStop","onMute","onMarkerComplete","_volume","_buffer","_muted","_tempMarker","_tempPosition","_tempVolume","_tempPause","_muteVolume","_tempLoop","_onDecodedEventDispatched","removeMarker","onEndedHandler","onended","isDecoded","loopFull","forceRestart","noteOff","createBufferSource","noteGrainOn","muted","mute","prevMarker","fadeIn","fadeTo","fadeOut","fadeComplete","updateGlobalVolume","globalVolume","onSoundDecode","onVolumeChange","onUnMute","onTouchUnlock","channels","_codeMuted","_unlockSource","_sounds","_watchList","_watching","_watchCallback","_watchContext","disableAudio","disableWebAudio","audioContext","setTouchLock","unlock","setTouchUnlock","noteOn","stopAll","soundData","decodeAudioData","setDecodedCallback","files","playbackState","PLAYING_STATE","FINISHED_STATE","removeByKey","close","dom","minWidth","minHeight","maxHeight","forceLandscape","forcePortrait","incorrectOrientation","_pageAlignHorizontally","_pageAlignVertically","onOrientationChange","enterIncorrectOrientation","leaveIncorrectOrientation","hasPhaserSetFullScreen","fullScreenTarget","_createdFullScreenTarget","onFullScreenInit","onFullScreenChange","onFullScreenError","screenOrientation","getScreenOrientation","scaleFactorInversed","aspectRatio","sourceAspectRatio","windowConstraints","compatibility","supportsFullScreen","orientationFallback","noMargins","scrollTo","forceMinimumDocumentHeight","canExpandParent","clickTrampoline","_scaleMode","NO_SCALE","_fullScreenScaleMode","parentIsWindow","parentScaleFactor","trackParentInterval","onSizeChange","onResize","onResizeContext","_pendingScaleMode","_fullScreenRestore","_gameSize","_userScaleFactor","_userScaleTrim","_lastUpdate","_updateThrottle","_updateThrottleReset","_parentBounds","_tempBounds","_lastReportedCanvasSize","_lastReportedGameSize","_booted","setupScale","EXACT_FIT","SHOW_ALL","RESIZE","USER_SCALE","MODES","compat","_orientationChange","orientationChange","_windowResize","windowResize","_fullScreenChange","fullScreenChange","_fullScreenError","fullScreenError","_gameResumed","setGameSize","FlexGrid","fullScreenScaleMode","pageAlignHorizontally","alignH","pageAlignVertically","alignV","scaleH","scaleV","setUserScale","trimH","trimV","getParentBounds","visualBounds","updateDimensions","queueUpdate","currentScaleMode","hScale","vScale","hTrim","vTrim","setResizeCallback","signalSizeChange","setMinMax","prevThrottle","prevWidth","prevHeight","boundsChanged","orientationChanged","updateOrientationState","updateLayout","throttle","updateScalingAndBounds","forceOrientation","classifyOrientation","orientation","previousOrientation","previouslyIncorrect","isLandscape","isPortrait","changed","correctnessChanged","scrollTop","setMaximum","setExactFit","isFullScreen","boundingParent","setShowAll","resetCanvas","reflowCanvas","reflowGame","layoutBounds","clientRect","getBoundingClientRect","parentRect","offsetParent","wc","windowBounds","alignCanvas","parentBounds","canvasBounds","currentEdge","targetEdge","marginLeft","marginRight","marginTop","marginBottom","cssWidth","cssHeight","expanding","createFullScreenTarget","fsTarget","background","startFullScreen","allowTrampoline","cleanupCreatedTarget","initData","targetElement","ALLOW_KEYBOARD_INPUT","stopFullScreen","prepScreenMode","enteringFullscreen","createdTarget","scaleSprite","letterBox","scaleX1","scaleY1","scaleX2","scaleY2","scaleOnWidth","bmd","columnWidth","renderShadow","currentColor","currentAlpha","_line","_rect","soundInfo","filled","rectangle","geom","cameraInfo","hideIfUp","downColor","upColor","worldX","worldY","spriteInputInfo","justDown","justUp","inputInfo","spriteBounds","ropeSegments","segment","spriteInfo","spriteCoords","lineInfo","forceType","ellipse","quadTree","quadtree","NINJA","Ninja","BOX2D","Box2D","renderBody","bodyInfo","renderBodyInfo","box2d","box2dWorld","renderDebugDraw","box2dBody","displayList","canvasPool","phaser","factor","loader","box","scrollY","scrollLeft","scrollX","clientTop","clientLeft","cushion","calibrate","coords","getAspectRatio","inLayoutViewport","primaryFallback","screen","mozOrientation","msOrientation","matchMedia","documentBounds","pageXOffset","pageYOffset","clientWidth","clientHeight","offsetWidth","scrollWidth","offsetHeight","scrollHeight","randomIndex","removeRandomItem","newLength","transposeMatrix","sourceRowCount","sourceColCount","rotateMatrix","findClosest","arr","NaN","low","high","rotateRight","rotateLeft","numberArray","numberArrayStep","LinkedList","entity","palettes","0","PALETTE_ARNE","PALETTE_JMP","PALETTE_CGA","PALETTE_C64","PALETTE_JAPANESE_MACHINE","row","boundsCustom","boundsFull","boundsNone","positionCustom","positionFluid","positionFull","positionNone","scaleCustom","scaleFluid","scaleFull","scaleNone","customWidth","customHeight","customOffsetX","customOffsetY","ratioH","ratioV","layers","createCustomLayer","layer","FlexLayer","createFluidLayer","createFullLayer","createFixedLayer","persist","fitSprite","topLeft","topMiddle","topRight","bottomLeft","bottomMiddle","bottomRight","RED","ORANGE","YELLOW","GREEN","AQUA","BLUE","VIOLET","WHITE","BLACK","GRAY","RGBtoHSL","RGBtoHSV","fromRGBA","toRGBA","toABGR","RGBArrayToHex","rgb","hueToColor","HSVtoRGB","color32","getColor","getColor32","RGBtoString","componentToHex","hexToRGB","hex","hexToColor","webToColor","web","tempColor","getRGB","HSVColorWheel","HSLColorWheel","interpolateColor","color1","color2","currentStep","src1","src2","hsv1","hsv2","dh","h3","interpolateColorWithRGB","or","og","ob","interpolateRGB","getRandomColor","getWebRGB","getAlpha","getAlphaFloat","getRed","getGreen","getBlue","blendNormal","blendAverage","blendSubtract","blendNegation","blendLinearDodge","blendLinearBurn","blendLinearLight","blendVividLight","blendPinLight","blendHardMix","blendReflect","blendGlow","blendPhoenix","arcade","ninja","chipmunk","matter","CHIPMUNK","MATTERJS","P2","Matter","startSystem","system","enableAABB","checkCollision","OVERLAP_BIAS","forceX","sortDirection","LEFT_RIGHT","skipQuadTree","_total","SORT_NONE","RIGHT_LEFT","TOP_BOTTOM","BOTTOM_TOP","updateMotion","allowRotation","velocityDelta","computeVelocity","angularAcceleration","angularDrag","maxAngular","acceleration","drag","maxVelocity","allowGravity","allowDrag","object1","object2","overlapCallback","processCallback","collideObjects","collide","collideCallback","sortLeftRight","sortRightLeft","sortTopBottom","sortBottomTop","overlapOnly","collideHandler","collideGroupVsSelf","collideSpriteVsSprite","collideSpriteVsGroup","collideSpriteVsTilemapLayer","collideGroupVsGroup","collideGroupVsTilemapLayer","sprite1","sprite2","separate","items","bounds1","bounds2","group1","group2","body1","body2","none","isCircle","separateCircle","bodyRect","bodyCircle","resultX","resultY","separateX","separateY","onOverlap","onCollide","circleBodyIntersects","getOverlapX","getOverlapY","angleCollision","immovable","customSeparateX","tempVel1","tempVel2","bounce","maxOverlap","deltaAbsX","embedded","touching","overlapX","deltaAbsY","overlapY","moves","nv1","nv2","avg","customSeparateY","getObjectsUnderPointer","getObjectsAtLocation","callbackArg","moveToObject","maxTime","distanceBetween","moveToPointer","angleToPointer","distanceToPointer","moveToXY","distanceToXY","velocityFromAngle","velocityFromRotation","accelerationFromRotation","accelerateToObject","xSpeedMax","ySpeedMax","accelerateToPointer","accelerateToXY","angleToXY","closest","targets","farthest","angleBetweenCenters","worldAngleToPointer","preRotation","newVelocity","deltaMax","worldBounce","onWorldBounds","facing","overlapR","collideWorldBounds","wasTouching","blocked","tilePadding","syncBounds","isMoving","stopVelocityOnCollide","moveTimer","moveDistance","moveDuration","moveTarget","moveEnd","onMoveComplete","movementCallback","movementCallbackContext","_sx","_sy","updateBounds","asx","asy","updateCenter","updateMovement","collided","stopMovement","stopVelocity","check","moveFrom","setCircle","onFloor","onCeiling","onWall","TilemapCollision","TILE_BIAS","tilemapLayer","getTiles","getTileOffsetX","getTileOffsetY","separateTile","tile","tilemapLayerOffsetX","tilemapLayerOffsetY","collisionCallback","collisionCallbackContext","faceLeft","faceRight","faceTop","faceBottom","tileCheckX","tileCheckY","collideRight","collideLeft","processTileSeparationX","collideDown","collideUp","processTileSeparationY","useElapsedTime","materials","InversePointProxy","walls","onBodyAdded","onBodyRemoved","onSpringAdded","onSpringRemoved","onConstraintAdded","onConstraintRemoved","onContactMaterialAdded","onContactMaterialRemoved","postBroadphaseCallback","onBeginContact","onEndContact","mpx","mpxi","pxm","pxmi","beginContactHandler","endContactHandler","collisionGroups","nothingCollisionGroup","CollisionGroup","boundsCollisionGroup","everythingCollisionGroup","boundsCollidesWith","_toRemove","_collisionGroupID","_boundsLeft","_boundsRight","_boundsTop","_boundsBottom","_boundsOwnGroup","removeBodyNextStep","setImpactEvents","impactHandler","setPostBroadphaseCallback","postBroadphaseHandler","_bodyCallbacks","_bodyCallbackContext","_groupCallbacks","_groupCallbackContext","setCollisionGroup","setWorldMaterial","updateBoundsCollisionGroup","setupWall","wall","fixedStepTime","impactCallback","createDistanceConstraint","getBody","createGearConstraint","createRevoluteConstraint","createLockConstraint","createPrismaticConstraint","lockRotation","anchorA","anchorB","setMaterial","createMaterial","createContactMaterial","getSprings","getConstraints","filterStatic","physicsPosition","query","toJSON","createCollisionGroup","bitmask","createSpring","worldA","worldB","localA","localB","createRotationalSpring","createBody","addPolygon","createParticle","convertCollisionObjects","map","collision","shapeData","polyline","addRectangle","clearTilemapLayerBodies","getLayer","convertTilemap","optimize","collides","getTileRight","FixtureList","rawList","namedFixtures","groupedFixtures","allFixtures","setCategory","bit","getFixtures","setMask","setSensor","getFixtureByKey","getGroup","groupID","_ref","_results","callee","PointProxy","collidesWith","removeNextStep","debugBody","_collideWorldBounds","setRectangleFromSprite","createBodyCallback","createGroupCallback","getCollisionMask","updateCollisionMask","clearCollision","clearGroup","clearMask","removeCollisionGroup","clearCallback","shapeChanged","impulse","localX","localY","setZeroRotation","setZeroVelocity","setZeroDamping","moveForward","moveBackward","thrust","thrustLeft","thrustRight","moveLeft","moveRight","updateSpriteTransform","resetDamping","resetMass","clearShapes","addCircle","addPlane","addParticle","addLine","addCapsule","setRectangle","addPhaserPolygon","createdFixtures","fixtureData","shapesOfFixture","addFixture","generatedShapes","categoryBits","maskBits","isSensor","polygons","loadPolygon","BodyDebug","settings","defaultSettings","pixelsPerLengthUnit","debugPolygons","ppu","lw","vrot","_j","_ref1","randomPastelHex","drawCapsule","drawPlane","drawLine","drawRectangle","drawConvex","drawPath","lastx","lasty","diagMargin","diagSize","maxLength","xd","yd","mix","rgbToHex","ImageCollection","firstgid","imageWidth","imageHeight","imageMargin","imageSpacing","containsImageIndex","imageIndex","gid","Tile","flipped","scanned","setCollisionCallback","setCollision","resetCollision","isInteresting","faces","TilemapParser","widthInPixels","heightInPixels","tilesets","imagecollections","tiles","collideIndexes","currentLayer","debugMap","_tempA","NORTH","EAST","SOUTH","WEST","setTileSize","createBlankLayer","addTilesetImage","tileset","tileMargin","tileSpacing","getTilesetIndex","setImage","newSet","Tileset","countX","countY","columns","rows","createFromObjects","CustomClass","adjustY","adjustSize","createFromTiles","replacements","customClass","lh","createLayer","getLayerIndex","rootLayer","groupEnd","indexes","getImageIndex","setTileIndexCallback","setTileLocationCallback","recalculate","setCollisionByIndex","calculateFaces","setCollisionBetween","setCollisionByExclusion","layerArg","setPreventRecalculate","preventingRecalculate","needToRecalculate","above","below","getTileAbove","getTileBelow","getTileLeft","setLayer","hasTile","removeTile","removeTileWorldXY","putTile","putTileWorldXY","searchTileIndex","getTile","nonNull","getTileWorldXY","paste","tileblock","tileA","tileB","swapHandler","removeAllLayers","dump","txt","renderSettings","enableScrollDelta","overdrawRatio","copyCanvas","debugSettings","missingImageFill","debuggedTileOverfill","forceFullRedraw","debugAlpha","facingEdgeStroke","collidingTileOverfill","scrollFactorX","scrollFactorY","rayStepRate","_wrap","_mc","renderWidth","renderHeight","_scrollX","_scrollY","tileOffset","ensureSharedCopyCanvas","sharedCopyCanvas","resizeWorld","_fixX","_unfixX","_fixY","_unfixY","getTileX","getTileY","getTileXY","getRayCastTiles","interestingFace","coord","fetchAll","wy","wx","resolveTileset","tileIndex","setIndex","containsTileIndex","resetTilesetCache","setScale","xScale","yScale","shiftCanvas","copyW","copyH","copyContext","renderRegion","lastAlpha","xmax","ymax","baseX","normStartX","renderDeltaScroll","shiftX","shiftY","renderW","renderH","trueTop","trueBottom","trueLeft","trueRight","renderFull","redrawAll","mc","renderDebug","baseY","normStartY","INSERT_NULL","getEmptyData","parseCSV","parseTiledJSON","column","_slice","fields","sliced","parseObjectGroup","objectGroup","objectsCollection","collisionCollection","nameKey","relativePosition","curl","encoding","binaryString","atob","bytes","opacity","offsetx","offsety","flippedVal","curi","tilesetGroupObjects","lastSet","tileproperties","tileProperties","updateTileData","imagewidth","imageheight","newCollection","objectgroup","lastgid","sid","drawCoords","coordIndex","setSpacing","rowCount","colCount","autoScale","scaleData","_s","autoAlpha","alphaData","_a","onEmit","setAlphaData","setScaleData","emitters","ID","minAngle","maxAngle","minSpeed","maxSpeed","minParticleSpeed","maxParticleSpeed","minParticleScale","maxParticleScale","minRotation","maxRotation","minParticleAlpha","maxParticleAlpha","particleClass","particleDrag","particleAnchor","emitX","emitY","particleBringToTop","particleSendToBack","counts","emitted","failed","totalEmitted","totalFailed","_gravity","_minParticleScale","_maxParticleScale","_timer","_counter","_flowQuantity","_flowTotal","_explode","emitParticle","makeParticles","particleArguments","particle","rndKey","rndFrame","explode","flow","forceQuantity","getNextParticle","resetParticle","setXSpeed","setYSpeed","setRotation","setAlpha","rate","tweenData","setAngle","lifespanOutput","bullets","autoExpandBulletsGroup","autofire","shots","fireLimit","fireRate","fireRateVariance","fireFrom","fireAngle","bulletInheritSpriteSpeed","bulletAnimation","bulletFrameRandom","bulletFrameCycle","bulletWorldWrap","bulletWorldWrapPadding","bulletAngleOffset","bulletAngleVariance","bulletSpeed","bulletSpeedVariance","bulletLifespan","bulletKillDistance","bulletGravity","bulletRotateToVelocity","bulletKey","bulletFrame","_bulletClass","Bullet","_bulletCollideWorldBounds","_bulletKillType","KILL_WORLD_BOUNDS","customBody","bulletBounds","bulletFrames","bulletFrameIndex","anims","onFire","onKill","onFireLimit","trackedSprite","trackedPointer","multiFire","_hasFired","trackRotation","trackOffset","_nextFire","_tempNextFire","_rotatedPoint","KILL_NEVER","KILL_LIFESPAN","KILL_DISTANCE","KILL_WEAPON_BOUNDS","KILL_CAMERA_BOUNDS","KILL_STATIC_BOUNDS","resetShots","newLimit","fire","trackSprite","trackPointer","fireMany","fireOffset","moveX","moveY","bullet","bulletManager","killType","bulletKillType","killDistance","rotateToVelocity","bodyDirty","bulletCollideWorldBounds","fireAtPointer","fireAtSprite","fireAtXY","setBulletBodyOffset","setBulletFrames","cycle","addBulletAnimation","debugBodies","onAccess","onError","onTimeout","playWhenUnlocked","timeout","videoStream","isStreaming","retryLimit","retry","retryInterval","_retryID","_pending","_pendingChangeSource","_autoplay","_endCallback","_playCallback","_video","createVideoFromBlob","videoWidth","videoHeight","createVideoFromURL","snapshot","connectToMediaStream","stream","startMediaStream","captureAudio","removeVideoElement","setAttribute","getUserMediaTimeout","getUserMediaSuccess","getUserMediaError","mozSrcObject","createObjectURL","onloadeddata","checkStream","checkVideoProgress","change","playbackRate","setPause","setResume","playHandler","getTracks","track","playing","ended","changeSource","grab","hasChildNodes","firstChild","removeAttribute","canUseNewCanvasBlendModes"],"mappings":";;CAoDC,SAASA,GAAG,GAAG,iBAAiBC,QAAQC,OAAOD,QA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,QAAQ6L,MAAMpsC,QAAU4gD,EAAO5Z,OAAOhzC,EAGtD0lB,EAAgC,EAAxBltB,KAAKyzD,iBAAuBzzD,KAAK8yD,SAEzC7yD,EAASitB,KAAW0wB,EACpB39C,EAASitB,KAAW4wB,EAEpB79C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIW,GACxB/0D,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAIpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW4wB,EAEpB79C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAItW,GACxB99C,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAGpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIpW,GACxBh+C,EAASitB,KAAWmnC,EAAInW,GAExBj+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EA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,KAAKm+G,QAELn+G,KAAKm+G,MAAMgnF,aAAehqL,MAetCgiB,OAAOC,eAAe8Z,EAAO++D,MAAM71G,UAAW,QAE1C2Q,IAAK,WAED,QAAQ/Q,KAAU,OAAIA,KAAKm+G,MAAM1K,MAIrCpmG,IAAK,SAAU8N,GAEPA,GAASnb,KAAKm+G,MAEdn+G,KAAKm+G,MAAM1K,KAAO,OAEbzzG,KAAKm+G,QAEVn+G,KAAKm+G,MAAM1K,KAAO,OAY9Bt2E,OAAOC,eAAe8Z,EAAO++D,MAAM71G,UAAW,WAE1C2Q,IAAK,WAED,QAAQ/Q,KAAU,SAAMA,KAAKm+G,MAAM3rC,QAAUxyE,KAAKm+G,MAAMunF,UAMhExuJ,EAAO++D,MAAM71G,UAAUuK,YAAcusC,EAAO++D,WAWpB32F,IAApBk1B,KAAK2G,aAEL3G,KAAK2G,WAAajE,EAAOiE,iBAGL77B,IAApBk1B,KAAKC,aAELD,KAAKC,WAAayC,EAAOzC,iBAGKn1B,IAA9Bk1B,KAAK2K,QAAQC,eAEb5K,KAAK2K,QAAQC,aAAe,IAAI5K,KAAK2K,QAAQ,IAAI3K,KAAKwmB,mBAGnB17C,IAAnCk1B,KAAKgC,cAAc6C,cAEnB7E,KAAKgC,cAAc6C,YAAc,IAAInC,EAAOC,QAGhD3C,KAAKinB,mBAAoB,EAGzBjnB,KAAKwxJ,0BAA4B,WAC7B,OAAO9uJ,EAAOgvC,OAAOnrB,gBASE,oBAAZn/D,SACe,oBAAXC,QAA0BA,OAAOD,UACxCA,QAAUC,OAAOD,QAAUs7C,GAE/Bt7C,QAAQs7C,OAASA,GACQ,oBAAXglB,QAA0BA,OAAOC,IAC/CD,OAAO,SAA+B3vB,EAAK2K,OAASA,GAEpD3K,EAAK2K,OAASA,EAGXA,GACRr6C,KAAKmD","file":"phaser.min.js"} \ No newline at end of file diff --git a/Iteration Sequence 1.2/js/phaser.min.js b/Iteration Sequence 1.2/js/phaser.min.js new file mode 100644 index 000000000..6eb048b7a --- /dev/null +++ b/Iteration Sequence 1.2/js/phaser.min.js @@ -0,0 +1,4 @@ +/* Phaser v2.10.0 - http://phaser.io - @photonstorm - (c) 2016 Photon Storm Ltd. */ + +!function(t){if("object"==typeof exports)module.exports=t();else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.p2=t()}}(function(){return function t(e,i,s){function n(o,a){if(!i[o]){if(!e[o]){var h="function"==typeof require&&require;if(!a&&h)return h(o,!0);if(r)return r(o,!0);throw new Error("Cannot find module '"+o+"'")}var l=i[o]={exports:{}};e[o][0].call(l.exports,function(t){var i=e[o][1][t];return n(i||t)},l,l.exports,t,e,i,s)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;se[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;ia)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var T=0;Tm&&(m+=this.vertices.length),g=Number.MAX_VALUE,m3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e) (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.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.1"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;ca[f]&&(a[f]=u[f]),u[f]i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle");var n=t("../collision/Broadphase");t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;az&&Y0)for(G=0;GMath.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=x,f=b,g=_,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var w=r.vertices[y];if(o.rotate(p,w,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var T=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(T.normalA,f);var P=l(g,T.normalA);o.scale(g,T.normalA,P),a(T.contactPointB,p,n.position),a(T.contactPointA,p,g),a(T.contactPointA,T.contactPointA,t.position),this.contactEquations.push(T),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(T))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=x,p=b;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=x;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,w=u;w=w||0;var T=x,P=b,C=_;a(T,g,y),o.rotate(P,v,w);var S=l(P,T);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,P),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,T,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=x,m=b,y=_,v=w,P=T,E=C,M=S,R=A,L=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(M,u,i),l(g,M)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),I=s.getClosestEdge(c,d,g);if(-1===B||-1===I)return 0;for(var O=0;O<2;O++){var k=B,F=I,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===O){var q;q=k,k=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H=3){if(p)return!0;var Z=this.createContactEquation(j,V,D,U);L++;var J=D.vertices[k%D.vertices.length],Q=D.vertices[(k+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(P,v,y),o.rotate90cw(Z.normalA,P),o.normalize(Z.normalA,Z.normalA),a(M,m,y);var $=l(Z.normalA,M);o.scale(E,Z.normalA,$),a(Z.contactPointA,m,G),a(Z.contactPointA,Z.contactPointA,E),h(Z.contactPointA,Z.contactPointA,G),a(Z.contactPointA,Z.contactPointA,j.position),a(Z.contactPointB,m,N),h(Z.contactPointB,Z.contactPointB,N),a(Z.contactPointB,Z.contactPointB,V.position),this.contactEquations.push(Z),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Z))}}}return this.enableFrictionReduction&&this.enableFriction&&L&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;dh)&&(h=a),(null===c||ah){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,x=nt;if(t instanceof y&&n instanceof y)for(P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(C=0;2!==C;C++){0===C?o.set(m,0,1):1===C&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0),u=(S=T[0]-w[1])<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(var C=0;C!==b.vertices.length;C++){o.rotate(f,b.vertices[C],_),o.rotate(g,b.vertices[(C+1)%b.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0);var S=T[0]-w[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,x=pt,b=ct,_=ut,w=Math.floor((i[0]-d-l[0])/f),T=Math.ceil((i[0]+d-l[0])/f);w<0&&(w=0),T>=p.length&&(T=p.length-1);for(var P=p[w],C=p[T],S=w;SP&&(P=p[S]);if(i[1]-d>P)return!u&&0;for(var A=!1,S=w;S=b[0]&&m[0]<_[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,x,-E),o.add(y,m,g),o.copy(v,x);M=this.createContactEquation(n,t,r,e);o.copy(M.normalA,v),o.scale(M.contactPointB,M.normalA,-d),h(M.contactPointB,M.contactPointB,i),a(M.contactPointB,M.contactPointB,t.position),o.copy(M.contactPointA,y),o.sub(M.contactPointA,M.contactPointA,n.position),this.contactEquations.push(M),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(M))}}if(A=!1,d>0)for(S=w;S<=T;S++)if(o.set(b,S*f,p[S]),o.add(b,b,l),o.sub(g,i,b),o.squaredLength(g)=c.length&&(y=c.length-1);for(var v=c[m],x=c[y],b=m;bv&&(v=c[b]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var _=0,b=m;b=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;ne.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){this.from,this.to;var o=this._currentShape,a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;cthis.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.positioni?(a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n)):-1!==(b=t.indexOf(n))&&t.splice(b,1),this.lowerLimitEnabled&&va?(f.angle=a,-1===n.indexOf(f)&&n.push(f)):-1!==(y=n.indexOf(f))&&n.splice(y,1),this.lowerLimitEnabled&&m>1;if(e<3)return[];for(var i=[],n=[],r=0;r3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,x=1/(f*y-g*g),b=(y*m-g*v)*x,_=(f*v-g*m)*x;return b>=0&&_>=0&&b+_<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;ei&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),x=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||x;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(h=this.shapes.length;h>=0;--h)this.removeShape(this.shapes[h]);var i=new r.Polygon;if(i.vertices=t,i.makeCCW(),"number"==typeof e.removeCollinearPoints&&i.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!i.isSimple())return!1;this.concavePath=i.vertices.slice(0);for(h=0;h=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var T=n.create(),P=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(T,i,t*e),n.multiply(T,this.massMultiplier,T),n.add(r,T,r),this.integrateToTimeOfImpact(t)||(n.scale(P,r,t),n.add(s,s,P),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),M=n.create(),R=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)=l&&h=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var b=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),w=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),T=Math.pow(_,2)-4*b*w;if(!(T<0))if(0===T){if(r.lerp(d,n,o,T),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}else{var P=Math.sqrt(T),C=1/(2*b),S=(-_-P)*C,A=(-_+P)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,x=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;x>=0&&x<=1&&(r.lerp(f,n,h,x),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,x,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;in)&&(n=s),(null===o||sn){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;ee&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),nv){var x=y;y=v,v=x}for(var b=0;b=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,_,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};r.create();var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){(t=t||{}).type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){(t=t||{}).type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=t.lowerBound,a=t.upperBound;n(o,-1e7,-1e7),n(a,1e7,1e7),0===s?a[1]=0:s===Math.PI/2?o[0]=0:s===Math.PI?o[1]=0:s===3*Math.PI/2&&(a[0]=0)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}t("../utils/Utils");var n=t("../events/EventEmitter");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){this.overlappingShapesLastState;var n=this.overlappingShapesCurrentState;if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var s=t,n=e;(i=i||[]).length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;)(n=i.getByKey(i.keys[s]))&&e.push(n.bodyA,n.bodyB);return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s=t&&s=0;T-=2)for(S=b.length-2;S>=0;S-=2)(w[T]===b[S]&&w[T+1]===b[S+1]||w[T+1]===b[S]&&w[T]===b[S+1])&&b.splice(S,2);q=u.length;for(T=0;T!==q;T++){var C=u[T];if(!C.collideConnected)for(var S=b.length-2;S>=0;S-=2)(C.bodyA===b[S]&&C.bodyB===b[S+1]||C.bodyB===b[S]&&C.bodyA===b[S+1])&&b.splice(S,2)}this.postBroadphaseEvent.pairs=b,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var T=0,A=b.length;T!==A;T+=2)for(var E=b[T],M=b[T+1],R=0,L=E.shapes.length;R!==L;R++)for(var B=E.shapes[R],I=B.position,O=B.angle,k=0,F=M.shapes.length;k!==F;k++){var D=M.shapes[k],U=D.position,G=D.angle,N=this.defaultContactMaterial;if(B.material&&D.material){var X=this.getContactMaterial(B.material,D.material);X&&(N=X)}this.runNarrowphase(c,E,B,I,O,M,D,U,G,N,this.frictionGravity)}for(T=0;T!==h;T++)(H=n[T])._wakeUpAfterNarrowphase&&(H.wakeUp(),H._wakeUpAfterNarrowphase=!1);if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(P);for(var W=this.endContactEvent,k=P.length;k--;){var j=P[k];W.shapeA=j.shapeA,W.shapeB=j.shapeB,W.bodyA=j.bodyA,W.bodyB=j.bodyB,this.emit(W)}P.length=0}var V=this.preSolveEvent;V.contactEquations=c.contactEquations,V.frictionEquations=c.frictionEquations,this.emit(V),V.contactEquations=V.frictionEquations=null;var q=u.length;for(T=0;T!==q;T++)u[T].update();if(c.contactEquations.length||c.frictionEquations.length||q)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),T=0;T!==q;T++)v.appendArray(g.equations,u[T].equations);g.split(this);for(T=0;T!==g.islands.length;T++)(K=g.islands[T]).equations.length&&a.solveIsland(t,K)}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),T=0;T!==q;T++)a.addEquations(u[T].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(T=0;T!==h;T++){var H=n[T];H.integrate(t)}for(T=0;T!==h;T++)n[T].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var Y=this.impactEvent,T=0;T!==c.contactEquations.length;T++){var z=c.contactEquations[T];z.firstImpact&&(Y.bodyA=z.bodyA,Y.bodyB=z.bodyB,Y.shapeA=z.shapeA,Y.shapeB=z.shapeB,Y.contactEquation=z,this.emit(Y))}if(this.sleepMode===s.BODY_SLEEPING)for(T=0;T!==h;T++)n[T].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(T=0;T!==h;T++)n[T].sleepTick(this.time,!0,t);for(T=0;T0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,x=t.frictionEquations.length;y=i.type=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0),o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC&&r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0),this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var _=this.beginContactEvent;if(_.shapeA=i,_.shapeB=a,_.bodyA=e,_.bodyB=o,_.contactEquations.length=0,"number"==typeof y)for(P=t.contactEquations.length-y;P1)for(var P=t.frictionEquations.length-b;P=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var x=e[y],b=0,_=x.shapes.length;b!==_;b++){var w=x.shapes[b];r.rotate(p,w.position,x.angle),r.add(p,p,x.position);var T=w.angle+x.angle;(w instanceof o&&g.circleParticle(x,w,p,T,s,n,u,0,!0)||w instanceof a&&g.particleConvex(s,n,u,0,x,w,p,T,!0)||w instanceof h&&g.particlePlane(s,n,u,0,x,w,p,T,!0)||w instanceof l&&g.particleCapsule(s,n,u,0,x,w,p,T,!0)||w instanceof c&&r.squaredLength(r.sub(f,p,t))0?Math.acos(i/u):-Math.acos(i/u),this.worldScale.x=u,this.worldScale.y=c/u}else if(n||r){var d=Math.sqrt(n*n+r*r);this.worldRotation=Phaser.Math.HALF_PI-(r>0?Math.acos(-n/d):-Math.acos(n/d)),this.worldScale.x=c/d,this.worldScale.y=d}else this.worldScale.x=0,this.worldScale.y=0;return this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.x=l.tx,this.worldPosition.y=l.ty,this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,l,h),this},preUpdate:function(){},generateTexture:function(t,e,i){var n=this.getLocalBounds(),r=new Phaser.RenderTexture(this.game,0|n.width,0|n.height,i,e,t);return s.DisplayObject._tempMatrix.tx=-n.x,s.DisplayObject._tempMatrix.ty=-n.y,r.render(this,s.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?s.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):s.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=0;this.texture&&this.texture.baseTexture&&s._enableMultiTextureToggle&&(e=this.texture.baseTexture.textureIndex);var i=new Phaser.RenderTexture(this.game,t.width,t.height,void 0,void 0,void 0,void 0,e);this._cachedSprite=new s.Sprite(i),this._cachedSprite.worldTransform=this.worldTransform}var n=this._filters;this._filters=null,this._cachedSprite.filters=n,s.DisplayObject._tempMatrix.tx=-t.x,s.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,s.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=n,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},s.DisplayObject.prototype.displayObjectUpdateTransform=s.DisplayObject.prototype.updateTransform,Object.defineProperties(s.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],i=0;i=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},s.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},s.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},s.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},s.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},s.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},s.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},s.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(t,i),n=0;na?u:a,d=d>h?d:h);var f=this._bounds;if(!p){var g=(f=new s.Rectangle).x,m=f.width+f.x,y=f.y,v=f.height+f.y,x=this.worldTransform,b=x.a,_=x.b,w=x.c,T=x.d,P=x.tx,C=x.ty,S=b*m+w*v+P,A=T*v+_*m+C,E=b*g+w*v+P,M=T*v+_*g+C,R=b*g+w*y+P,L=T*y+_*g+C,B=b*m+w*y+P,I=T*y+_*m+C;u=S,d=A,c=A,l=B<(l=R<(l=E<(l=S)?E:l)?R:l)?B:l,c=I<(c=L<(c=M(u=R>(u=E>u?E:u)?R:u)?B:u,d=I>(d=L>(d=M>d?M:d)?L:d)?I:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n(f=T>(f=_>(f=x>f?x:f)?_:f)?T:f)?C:f,g=S>(g=P>(g=w>(g=b>g?b:g)?w:g)?P:g)?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},s.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=Phaser.identityMatrix;for(var e=0;e= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}","}"];var n=s.compileProgram(t,this.vertexSrc||s.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(n),this.uSamplerArray=t.getUniformLocation(n,"uSamplerArray[0]"),this.projectionVector=t.getUniformLocation(n,"projectionVector"),this.offsetVector=t.getUniformLocation(n,"offsetVector"),this.dimensions=t.getUniformLocation(n,"dimensions"),this.aVertexPosition=t.getAttribLocation(n,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(n,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(n,"aColor"),this.aTextureIndex=t.getAttribLocation(n,"aTextureIndex");var r=[],o=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var a=0;a 0.0) gl_Position = vec4(0.0);"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);"," vTextureIndex = aTextureIndex;","}"],s.PixiFastShader=function(t){if(this._UID=Phaser._UID++,this.gl=t,this.program=null,s._enableMultiTextureToggle){var t=this.gl;this.MAX_TEXTURES=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(var e="\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n",i=1;i= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["// PixiFastShader Fragment Shader.","precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;","}"];this.vertexSrc=["// PixiFastShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","attribute float aTextureIndex;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;"," vColor = aColor;","}"],this.textureCount=0,this.init()},s.PixiFastShader.prototype.constructor=s.PixiFastShader,s.PixiFastShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["//StripShader Fragment Shader.","precision mediump float;","varying vec2 vTextureCoord;","varying float vTextureIndex;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord);","}"];this.vertexSrc=["//StripShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aTextureIndex;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;","}"],this.init()},s.StripShader.prototype.constructor=s.StripShader,s.StripShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t},i=this.gl,n=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),r=i.getParameter(i.MAX_TEXTURE_SIZE),o=this.game.cache._cache.image,a=null,h=0;h=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var a=i._uvs;if(a){var h,l,c,u,d=t.anchor.x,p=t.anchor.y;if(i.trim){var f=i.trim;h=(l=f.x-d*f.width)+i.crop.width,c=(u=f.y-p*f.height)+i.crop.height}else h=i.frame.width*(1-d),l=i.frame.width*-d,c=i.frame.height*(1-p),u=i.frame.height*-p;var g=this.currentBatchSize*this.vertexSize,m=(this.currentBatchSize,i.baseTexture.resolution),y=i.baseTexture.textureIndex,v=o.a/m,x=o.b/m,b=o.c/m,_=o.d/m,w=o.tx,T=o.ty,P=(i.crop.width,i.crop.height);if(i.rotated){var C=o.a,S=o.b,A=o.c,E=o.d,M=l,R=h;w=o.c*P+w,T=o.d*P+T,v=6.123233995736766e-17*C-A,x=6.123233995736766e-17*S-E,b=C+6.123233995736766e-17*A,_=S+6.123233995736766e-17*E,i._updateUvsInverted(),h=c,l=u,c=R,u=M}var L=this.colors,B=this.positions,I=t.tint,O=(I>>16)+(65280&I)+((255&I)<<16)+(255*t.worldAlpha<<24);this.renderSession.roundPixels?(B[g++]=v*l+b*u+w|0,B[g++]=_*u+x*l+T|0,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w|0,B[g++]=_*u+x*h+T|0,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w|0,B[g++]=_*c+x*h+T|0,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w|0,B[g++]=_*c+x*l+T|0,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y):(B[g++]=v*l+b*u+w,B[g++]=_*u+x*l+T,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w,B[g++]=_*u+x*h+T,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w,B[g++]=_*c+x*h+T,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w,B[g++]=_*c+x*l+T,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y),this.sprites[this.currentBatchSize++]=t}},s.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture,i=e.baseTexture,n=this.gl,r=t.texture.baseTexture.textureIndex;s.WebGLRenderer.textureArray[r]!=i&&(this.flush(),n.activeTexture(n.TEXTURE0+r),n.bindTexture(n.TEXTURE_2D,i._glTextures[n.id]),s.WebGLRenderer.textureArray[r]=i),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new s.TextureUvs);var o=t._uvs,a=e.baseTexture.width,h=e.baseTexture.height;t.tilePosition.x%=a*t.tileScaleOffset.x,t.tilePosition.y%=h*t.tileScaleOffset.y;var l=t.tilePosition.x/(a*t.tileScaleOffset.x),c=t.tilePosition.y/(h*t.tileScaleOffset.y),u=t.width/a/(t.tileScale.x*t.tileScaleOffset.x),d=t.height/h/(t.tileScale.y*t.tileScaleOffset.y);o.x0=0-l,o.y0=0-c,o.x1=1*u-l,o.y1=0-c,o.x2=1*u-l,o.y2=1*d-c,o.x3=0-l,o.y3=1*d-c;var p=t.tint,f=(p>>16)+(65280&p)+((255&p)<<16)+(255*t.worldAlpha<<24),g=this.positions,m=this.colors,y=t.width,v=t.height,x=t.anchor.x,b=t.anchor.y,_=y*(1-x),w=y*-x,T=v*(1-b),P=v*-b,C=this.currentBatchSize*this.vertexSize,S=e.baseTexture.resolution,A=t.worldTransform,E=A.a/S,M=A.b/S,R=A.c/S,L=A.d/S,B=A.tx,I=A.ty;g[C++]=E*w+R*P+B,g[C++]=L*P+M*w+I,g[C++]=o.x0,g[C++]=o.y0,m[C++]=f,g[C++]=r,g[C++]=E*_+R*P+B,g[C++]=L*P+M*_+I,g[C++]=o.x1,g[C++]=o.y1,m[C++]=f,g[C++]=r,g[C++]=E*_+R*T+B,g[C++]=L*T+M*_+I,g[C++]=o.x2,g[C++]=o.y2,m[C++]=f,g[C++]=r,g[C++]=E*w+R*T+B,g[C++]=L*T+M*w+I,g[C++]=o.x3,g[C++]=o.y3,m[C++]=f,g[C++]=r,this.sprites[this.currentBatchSize++]=t},s.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,t=this.defaultShader.shaders[e.id],e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var i=this.vertexSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,i,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,i,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,i,16),e.vertexAttribPointer(t.aTextureIndex,1,e.FLOAT,!1,i,20)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);var n=this.positions.subarray(0,this.currentBatchSize*this.vertexSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m0&&(v=!1),(f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){(t=(p=a).shaders[e.id])||((t=new s.PixiShader(e)).fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var x=this.renderSession.projection;e.uniform2f(t.projectionVector,x.x,x.y);var b=this.renderSession.offset;e.uniform2f(t.offsetVector,b.x,b.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},s.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},s.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},s.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},s.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},s.WebGLFastSpriteBatch=function(t){this.vertSize=11,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,i=6*this.maxSize;this.vertices=new Float32Array(e),this.indices=new Uint16Array(i),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var s=0,n=0;s=this.size&&this.flush()}},s.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]){if(this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}else this.renderSession.renderer.updateTexture(this.currentBaseTexture,t)}},s.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},s.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36),t.vertexAttribPointer(this.shader.aTextureIndex,1,t.FLOAT,!1,i,40)},s.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},s.WebGLFilterManager.prototype.constructor=s.WebGLFilterManager,s.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},s.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},s.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,i=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new s.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),i.x=a.width/2,i.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},s.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),i=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,i.width*this.renderSession.resolution,i.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=i.height,this.vertexArray[2]=i.width,this.vertexArray[3]=i.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=i.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=i.width/this.width,this.uvArray[5]=i.height/this.height,this.uvArray[6]=i.width/this.width,this.uvArray[7]=i.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,i,p,f),this.texturePool.push(n),e._glFilterTexture=null},s.WebGLFilterManager.prototype.applyFilterPass=function(t,e,i,n){var r=this.gl,o=t.shaders[r.id];o||((o=new s.PixiShader(r)).fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(!0),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,i/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},s.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},s.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e=0;t--){var e=this._glTextures[t],i=s.glContexts[t];i&&e&&i.deleteTexture(e)}this._glTextures.length=0,this.dirty()},s.BaseTexture.fromCanvas=function(t,e,i){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),i=i||1,new s.BaseTexture(t,e,i)},s.TextureSilentFail=!1,s.Texture=function(t,e,i,n){this.noFrame=!1,e||(this.noFrame=!0,e=new s.Rectangle(0,0,1,1)),t instanceof s.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=i||new s.Rectangle(0,0,1,1),this.rotated=!1,t.hasLoaded&&(this.noFrame&&(e=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},s.Texture.prototype.constructor=s.Texture,s.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},s.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},s.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,this.trim||!(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height))this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs();else{if(!s.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=!1}},s.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/i},s.Texture.prototype._updateUvsInverted=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.height)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.height)/e,this._uvs.y2=(t.y+t.width)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.width)/i},s.Texture.fromCanvas=function(t,e){var i=s.BaseTexture.fromCanvas(t,e);return new s.Texture(i)},s.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=s),exports.PIXI=s):"undefined"!=typeof define&&define.amd?define("PIXI",i.PIXI=s):i.PIXI=s,s}.call(this),function(){function t(t,e){this._scaleFactor=t,this._deltaMode=e,this.originalEvent=null}var e=this,i=i||{VERSION:"2.10.0",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,WEBGL_MULTI:4,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,PENDING_ATLAS:-1,HORIZONTAL:0,VERTICAL:1,LANDSCAPE:0,PORTRAIT:1,ANGLE_UP:270,ANGLE_DOWN:90,ANGLE_LEFT:180,ANGLE_RIGHT:0,ANGLE_NORTH_EAST:315,ANGLE_NORTH_WEST:225,ANGLE_SOUTH_EAST:45,ANGLE_SOUTH_WEST:135,TOP_LEFT:0,TOP_CENTER:1,TOP_RIGHT:2,LEFT_TOP:3,LEFT_CENTER:4,LEFT_BOTTOM:5,CENTER:6,RIGHT_TOP:7,RIGHT_CENTER:8,RIGHT_BOTTOM:9,BOTTOM_LEFT:10,BOTTOM_CENTER:11,BOTTOM_RIGHT:12,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},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{},_UID:0};if(Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Function.prototype.bind||(Function.prototype.bind=function(){var t=Array.prototype.slice;return function(e){function i(){var r=n.concat(t.call(arguments));s.apply(this instanceof i?this:e,r)}var s=this,n=t.call(arguments,1);if("function"!=typeof s)throw new TypeError;return i.prototype=function t(e){if(e&&(t.prototype=e),!(this instanceof t))return new t}(s.prototype),i}}()),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var s=arguments.length>=2?arguments[1]:void 0,n=0;n0&&100*Math.random()<=t},randomChoice:function(t,e){return Math.random()<.5?t:e},parseDimension:function(t,e){var i=0,s=0;return"string"==typeof t?"%"===t.substr(-1)?(i=parseInt(t,10)/100,s=0===e?window.innerWidth*i:window.innerHeight*i):s=parseInt(t,10):s=t,s},pad:function(t,e,i,s){if(void 0===e)var e=0;if(void 0===i)var i=" ";if(void 0===s)var s=3;var n=0;if(e+1>=(t=t.toString()).length)switch(s){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((n=e-t.length)/2),o=n-r;t=new Array(o+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t},isPlainObject:function(t){if("object"!=typeof t||t.nodeType||t===t.window)return!1;try{if(t.constructor&&!{}.hasOwnProperty.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},extend:function(){var t,e,s,n,r,o,a=arguments[0]||{},h=1,l=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[1]||{},h=2),l===h&&(a=this,--h);h0&&(this._radius=.5*s),this.type=i.CIRCLE},i.Circle.prototype={circumference:function(){return Math.PI*this._radius*2},random:function(t){void 0===t&&(t=new i.Point);var e=2*Math.PI*Math.random(),s=Math.random()+Math.random(),n=s>1?2-s:s,r=n*Math.cos(e),o=n*Math.sin(e);return t.x=this.x+r*this.radius,t.y=this.y+o*this.radius,t},getBounds:function(){return new i.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(t,e,i){return this.x=t,this.y=e,this._diameter=i,this._radius=.5*i,this},copyFrom:function(t){return this.setTo(t.x,t.y,t.diameter)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.diameter=this._diameter,t},distance:function(t,e){var s=i.Math.distance(this.x,this.y,t.x,t.y);return e?Math.round(s):s},clone:function(t){return void 0===t||null===t?t=new i.Circle(this.x,this.y,this.diameter):t.setTo(this.x,this.y,this.diameter),t},contains:function(t,e){return i.Circle.contains(this,t,e)},circumferencePoint:function(t,e,s){return i.Circle.circumferencePoint(this,t,e,s)},sample:function(t,e,s,n,r){t||(t=60),null==e&&(e=0),null==s&&(s=i.Math.PI2),r||(r=[]);for(var o=0;o0&&(this._diameter=t,this._radius=.5*t)}}),Object.defineProperty(i.Circle.prototype,"radius",{get:function(){return this._radius},set:function(t){t>0&&(this._radius=t,this._diameter=2*t)}}),Object.defineProperty(i.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(t){t>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-t}}),Object.defineProperty(i.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(t){tthis.y?(this._radius=0,this._diameter=0):this.radius=this.y-t}}),Object.defineProperty(i.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(t){t0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(i.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(t){!0===t&&this.setTo(0,0,0)}}),i.Circle.contains=function(t,e,i){return t.radius>0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius},i.Circle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.diameter===e.diameter},i.Circle.intersects=function(t,e){return i.Math.distance(t.x,t.y,e.x,e.y)<=t.radius+e.radius},i.Circle.circumferencePoint=function(t,e,s,n){return void 0===s&&(s=!1),void 0===n&&(n=new i.Point),!0===s&&(e=i.Math.degToRad(e)),n.x=t.x+t.radius*Math.cos(e),n.y=t.y+t.radius*Math.sin(e),n},i.Circle.intersectsRectangle=function(t,e){var i=Math.abs(t.x-e.x-e.halfWidth);if(i>e.halfWidth+t.radius)return!1;var s=Math.abs(t.y-e.y-e.halfHeight);if(s>e.halfHeight+t.radius)return!1;if(i<=e.halfWidth||s<=e.halfHeight)return!0;var n=i-e.halfWidth,r=s-e.halfHeight;return n*n+r*r<=t.radius*t.radius},i.Circle.intersectsLine=function(t,e,s){var n=t.x,r=t.y,o=(e.end.y-e.start.y)/(e.end.x-e.start.x),a=e.end.y-o*e.end.x,h=t.radius,l=t.radius,c=a+o*n,u=(n*(l*l)-o*(h*h)*(a-r)+h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),d=(n*(l*l)-o*(h*h)*(a-r)-h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),p=o*u+a,f=o*d+a,g=new i.Point(u,p),m=new i.Point(d,f),y=e.pointOnSegment(g.x,g.y,.01),v=e.pointOnSegment(m.x,m.y,.01);return y&&v?!s||[g,m]:y?!s||[g]:v?!s||[m]:!!s&&[]},PIXI.Circle=i.Circle,i.Ellipse=function(t,e,s,n){t=t||0,e=e||0,s=s||0,n=n||0,this.x=t,this.y=e,this.width=s,this.height=n,this.type=i.ELLIPSE},i.Ellipse.prototype={setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},getBounds:function(){return new i.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},clone:function(t){return void 0===t||null===t?t=new i.Ellipse(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t},contains:function(t,e){return i.Ellipse.contains(this,t,e)},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random()*Math.PI*2,s=Math.random();return t.x=Math.sqrt(s)*Math.cos(e),t.y=Math.sqrt(s)*Math.sin(e),t.x=this.x+t.x*this.width/2,t.y=this.y+t.y*this.height/2,t},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},i.Ellipse.prototype.constructor=i.Ellipse,Object.defineProperty(i.Ellipse.prototype,"left",{get:function(){return this.x},set:function(t){this.x=t}}),Object.defineProperty(i.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t=s&&t<=n&&e>=r&&e<=o},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random();return t.x=this.start.x+e*(this.end.x-this.start.x),t.y=this.start.y+e*(this.end.y-this.start.y),t},coordinatesOnLine:function(t,e){void 0===t&&(t=1),void 0===e&&(e=[]);var i=Math.round(this.start.x),s=Math.round(this.start.y),n=Math.round(this.end.x),r=Math.round(this.end.y),o=Math.abs(n-i),a=Math.abs(r-s),h=i-a&&(c-=a,i+=h),d=0&&g<=1&&m>=0&&m<=1?o:null}return o},i.Line.intersects=function(t,e,s,n){return i.Line.intersectsPoints(t.start,t.end,e.start,e.end,s,n)},i.Line.intersectsRectangle=function(t,e){if(0===t.length||e.empty)return!1;var i=t.start.x,s=t.start.y,n=t.end.x,r=t.end.y,o=e.x,a=e.y,h=e.right,l=e.bottom,c=0;if(i>=o&&i<=h&&s>=a&&s<=l||n>=o&&n<=h&&r>=a&&r<=l)return!0;if(i=o){if((c=s+(r-s)*(o-i)/(n-i))>a&&c<=l)return!0}else if(i>h&&n<=h&&(c=s+(r-s)*(h-i)/(n-i))>=a&&c<=l)return!0;if(s=a){if((c=i+(n-i)*(a-s)/(r-s))>=o&&c<=h)return!0}else if(s>l&&r<=l&&(c=i+(n-i)*(l-s)/(r-s))>=o&&c<=h)return!0;return!1},i.Line.intersectionWithRectangle=function(t,e,s){var n=i.Line.intersectionWithRectangle;s||(s=new i.Point),n.edges||(n.edges=[new i.Line,new i.Line,new i.Line,new i.Line]),n.edgeIntersection||(n.edgeIntersection=new i.Point);var r=n.edges,o=n.edgeIntersection.set(0),a=e.x,h=e.y,l=e.right,c=e.bottom,u=1/0;r[0].setTo(a,h,l,h),r[1].setTo(a,c,l,c),r[2].setTo(a,h,a,c),r[3].setTo(l,h,l,c);for(var d,p=0;d=r[p];p++)if(t.intersects(d,!0,o)){var f=t.start.distance(o);fs&&(this.x=s),this.yn&&(this.y=n),this},clone:function(t){return void 0===t||null===t?t=new i.Point(this.x,this.y):t.setTo(this.x,this.y),t},copyTo:function(t){return t.x=this.x,t.y=this.y,t},distance:function(t,e){return i.Point.distance(this,t,e)},equals:function(t){return t.x===this.x&&t.y===this.y},equalsXY:function(t,e){return this.x===t&&this.y===e},fuzzyEquals:function(t,e){return i.Point.fuzzyEquals(this,t,e)},fuzzyEqualsXY:function(t,e,s){return i.Point.fuzzyEqualsXY(this,t,e,s)},angle:function(t,e){return this.angleXY(t.x,t.y,e)},angleXY:function(t,e,s){var n=Math.atan2(e-this.y,t-this.x);return s?i.Math.radToDeg(n):n},atan:function(t){var e=Math.atan2(this.y,this.x);return t?i.Math.radToDeg(e):e},rotate:function(t,e,s,n,r){return i.Point.rotate(this,t,e,s,n,r)},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(t){return this.normalize().multiply(t,t)},normalize:function(){if(!this.isZero()){var t=this.getMagnitude();this.x/=t,this.y/=t}return this},limit:function(t){return this.getMagnitudeSq()>t*t&&this.setMagnitude(t),this},expand:function(t){return this.getMagnitudeSq()=0&&e.x-i<0)return-1;if(t.x-i<0&&e.x-i>=0)return 1;if(t.x-i==0&&e.x-i==0)return t.y-s>=0||e.y-s>=0?t.y>e.y?1:-1:e.y>t.y?1:-1;var n=(t.x-i)*-(e.y-s)-(e.x-i)*-(t.y-s);return n<0?-1:n>0?1:(t.x-i)*(t.x-i)+(t.y-s)*(t.y-s)>(e.x-i)*(e.x-i)+(e.y-s)*(e.y-s)?-1:1})},PIXI.Point=i.Point,i.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.flattened=!1,this.type=i.POLYGON},i.Polygon.prototype={toNumberArray:function(t){void 0===t&&(t=[]);for(var e=0;e0){Array.isArray(t)||(t=Array.prototype.slice.call(arguments));for(var e=Number.MAX_VALUE,i=0,s=t.length;i=this.right?this.width=0:this.width=this.right-t,this.x=t}}),Object.defineProperty(i.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(i.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(i.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(i.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(t){this.x=t-this.halfWidth}}),Object.defineProperty(i.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(t){this.y=t-this.halfHeight}}),Object.defineProperty(i.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(i.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(i.Rectangle.prototype,"top",{get:function(){return this.y},set:function(t){t>=this.bottom?(this.height=0,this.y=t):this.height=this.bottom-t}}),Object.defineProperty(i.Rectangle.prototype,"topLeft",{get:function(){return new i.Point(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"topRight",{get:function(){return new i.Point(this.x+this.width,this.y)},set:function(t){this.right=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),i.Rectangle.prototype.constructor=i.Rectangle,i.Rectangle.inflate=function(t,e,i){return t.x-=e,t.width+=2*e,t.y-=i,t.height+=2*i,t},i.Rectangle.inflatePoint=function(t,e){return i.Rectangle.inflate(t,e.x,e.y)},i.Rectangle.size=function(t,e){return void 0===e||null===e?e=new i.Point(t.width,t.height):e.setTo(t.width,t.height),e},i.Rectangle.clone=function(t,e){return void 0===e||null===e?e=new i.Rectangle(t.x,t.y,t.width,t.height):e.setTo(t.x,t.y,t.width,t.height),e},i.Rectangle.createFromBounds=function(t,e){return void 0!==e&&null!==e||(e=new i.Rectangle(t.x,t.y,t.width,t.height)),e.copyFromBounds(t)},i.Rectangle.contains=function(t,e,i){return!(t.width<=0||t.height<=0)&&(e>=t.x&&e=t.y&&i=t&&n=e&&re.volume)&&(t.x>=e.x&&t.y>=e.y&&t.righte.right||t.y>e.bottom)},i.Rectangle.intersectsRaw=function(t,e,i,s,n,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||ns&&(s=t.x),t.xr&&(r=t.y),t.y=i&&t<=i+this.width){var s=this.y;if(e>=s&&e<=s+this.height)return!0}return!1}},i.RoundedRectangle.prototype.constructor=i.RoundedRectangle,PIXI.RoundedRectangle=i.RoundedRectangle,i.Camera=function(t,e,s,n,r,o){this.game=t,this.world=t.world,this.id=0,this.view=new i.Rectangle(s,n,r,o),this.bounds=new i.Rectangle(s,n,r,o),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this.lerp=new i.Point(1,1),this.onShakeComplete=new i.Signal,this.onFlashComplete=new i.Signal,this.onFadeComplete=new i.Signal,this.fx=null,this._targetPosition=new i.Point,this._edge=0,this._position=new i.Point,this._shake={intensity:0,duration:0,horizontal:!1,vertical:!1,shakeBounds:!0,x:0,y:0},this._fxDuration=0,this._fxType=0,this._fixedView=new i.Rectangle},i.Camera.FOLLOW_LOCKON=0,i.Camera.FOLLOW_PLATFORMER=1,i.Camera.FOLLOW_TOPDOWN=2,i.Camera.FOLLOW_TOPDOWN_TIGHT=3,i.Camera.SHAKE_BOTH=4,i.Camera.SHAKE_HORIZONTAL=5,i.Camera.SHAKE_VERTICAL=6,i.Camera.ENABLE_FX=!0,i.Camera.prototype={boot:function(){this.displayObject=this.game.world,this.scale=this.game.world.scale,this.game.camera=this,i.Graphics&&i.Camera.ENABLE_FX&&(this.fx=new i.Graphics(this.game),this.game.stage.addChild(this.fx))},preUpdate:function(){this.totalInView=0},follow:function(t,e,s,n){void 0===e&&(e=i.Camera.FOLLOW_LOCKON),void 0===s&&(s=1),void 0===n&&(n=1),this.target=t,this.lerp.set(s,n);var r;switch(e){case i.Camera.FOLLOW_PLATFORMER:var o=this.width/8,a=this.height/3;this.deadzone=new i.Rectangle((this.width-o)/2,(this.height-a)/2-.25*a,o,a);break;case i.Camera.FOLLOW_TOPDOWN:r=Math.max(this.width,this.height)/4,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_TOPDOWN_TIGHT:r=Math.max(this.width,this.height)/8,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_LOCKON:default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(t){this.setPosition(Math.round(t.x-this.view.halfWidth),Math.round(t.y-this.view.halfHeight))},focusOnXY:function(t,e){this.setPosition(Math.round(t-this.view.halfWidth),Math.round(e-this.view.halfHeight))},shake:function(t,e,s,n,r){return void 0===t&&(t=.05),void 0===e&&(e=500),void 0===s&&(s=!0),void 0===n&&(n=i.Camera.SHAKE_BOTH),void 0===r&&(r=!0),!(!s&&this._shake.duration>0)&&(this._shake.intensity=t,this._shake.duration=e,this._shake.shakeBounds=r,this._shake.x=0,this._shake.y=0,this._shake.horizontal=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_HORIZONTAL,this._shake.vertical=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_VERTICAL,!0)},flash:function(t,e,i,s){return void 0===t&&(t=16777215),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=1,this._fxDuration=e,this._fxType=0,!0)},fade:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=0,this._fxDuration=e,this._fxType=1,!0)},update:function(){this._fxDuration>0&&this.updateFX(),this._shake.duration>0&&this.updateShake(),this.bounds&&this.checkBounds(),this.roundPx&&(this.view.floor(),this._shake.x=Math.floor(this._shake.x),this._shake.y=Math.floor(this._shake.y)),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateFX:function(){0===this._fxType?(this.fx.alpha-=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha<=0&&(this._fxDuration=0,this.fx.alpha=0,this.onFlashComplete.dispatch())):(this.fx.alpha+=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha>=1&&(this._fxDuration=0,this.fx.alpha=1,this.onFadeComplete.dispatch()))},updateShake:function(){this._shake.duration-=this.game.time.elapsedMS,this._shake.duration<=0?(this.onShakeComplete.dispatch(),this._shake.x=0,this._shake.y=0):(this._shake.horizontal&&(this._shake.x=this.game.rnd.frac()*this._shake.intensity*this.view.width*2-this._shake.intensity*this.view.width),this._shake.vertical&&(this._shake.y=this.game.rnd.frac()*this._shake.intensity*this.view.height*2-this._shake.intensity*this.view.height))},updateTarget:function(){this._targetPosition.x=this.view.x+this.target.worldPosition.x,this._targetPosition.y=this.view.y+this.target.worldPosition.y,this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edgethis.deadzone.right&&(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.right,this.lerp.x)),this._edge=this._targetPosition.y-this.view.y,this._edgethis.deadzone.bottom&&(this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.bottom,this.lerp.y))):(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.view.halfWidth,this.lerp.x),this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.view.halfHeight,this.lerp.y)),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},setBoundsToWorld:function(){this.bounds&&this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1;var t=this.view.x+this._shake.x,e=this.view.right+this._shake.x,i=this.view.y+this._shake.y,s=this.view.bottom+this._shake.y;t<=this.bounds.x*this.scale.x?(this.atLimit.x=!0,this.view.x=this.bounds.x*this.scale.x,this._shake.shakeBounds||(this._shake.x=0)):e>=this.bounds.right*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.right*this.scale.x-this.width,this._shake.shakeBounds||(this._shake.x=0)),i<=this.bounds.top*this.scale.y?(this.atLimit.y=!0,this.view.y=this.bounds.top*this.scale.y,this._shake.shakeBounds||(this._shake.y=0)):s>=this.bounds.bottom*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom*this.scale.y-this.height,this._shake.shakeBounds||(this._shake.y=0))},setPosition:function(t,e){this.view.x=t,this.view.y=e,this.bounds&&this.checkBounds()},setSize:function(t,e){this.view.width=t,this.view.height=e},reset:function(){this.target=null,this.view.x=0,this.view.y=0,this._shake.duration=0,this._shake.x=0,this._shake.y=0,this.resetFX()},resetFX:function(){this.fx&&(this.fx.clear(),this.fx.alpha=0),this._fxDuration=0}},i.Camera.prototype.constructor=i.Camera,Object.defineProperty(i.Camera.prototype,"x",{get:function(){return this.view.x},set:function(t){this.view.x=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"y",{get:function(){return this.view.y},set:function(t){this.view.y=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"position",{get:function(){return this._position.set(this.view.x,this.view.y),this._position},set:function(t){void 0!==t.x&&(this.view.x=t.x),void 0!==t.y&&(this.view.y=t.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"width",{get:function(){return this.view.width},set:function(t){this.view.width=t}}),Object.defineProperty(i.Camera.prototype,"height",{get:function(){return this.view.height},set:function(t){this.view.height=t}}),Object.defineProperty(i.Camera.prototype,"shakeIntensity",{get:function(){return this._shake.intensity},set:function(t){this._shake.intensity=t}}),Object.defineProperty(i.Camera.prototype,"fixedView",{get:function(){return this._fixedView.setTo(0,0,this.view.width,this.view.height),this._fixedView}}),i.State=function(){this.game=null,this.key="",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.state=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},i.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},i.State.prototype.constructor=i.State,i.StateManager=function(t,e){this.game=t,this.states={},this._pendingState=null,void 0!==e&&null!==e&&(this._pendingState=e),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new i.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},i.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(t,e,s){void 0===s&&(s=!1);var n;return e instanceof i.State?n=e:"object"==typeof e?(n=e).game=this.game:"function"==typeof e&&(n=new e(this.game)),this.states[t]=n,s&&(this.game.isBooted?this.start(t):this._pendingState=t),n},remove:function(t){this.current===t&&(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.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[t]},start:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1),this.checkState(t)&&(this._pendingState=t,this._clearWorld=e,this._clearCache=i,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!1),this._pendingState=this.current,this._clearWorld=t,this._clearCache=e,arguments.length>2&&(this._args=Array.prototype.slice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var t=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,t),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache&&this.game.cache.destroy()))},checkState:function(t){var e=this.states[t];return e?!!(e.preload||e.create||e.update||e.render)||(console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"),!1):(console.warn("Phaser.StateManager - No state found with the key: "+t),!1)},link:function(t){var e=this.states[t];e.game=this.game,e.add=this.game.add,e.make=this.game.make,e.camera=this.game.camera,e.cache=this.game.cache,e.input=this.game.input,e.load=this.game.load,e.math=this.game.math,e.sound=this.game.sound,e.scale=this.game.scale,e.state=this,e.stage=this.game.stage,e.time=this.game.time,e.tweens=this.game.tweens,e.world=this.game.world,e.particles=this.game.particles,e.rnd=this.game.rnd,e.physics=this.game.physics,e.key=t},unlink:function(t){var e=this.states[t];e&&(e.game=null,e.add=null,e.make=null,e.camera=null,e.cache=null,e.input=null,e.load=null,e.math=null,e.sound=null,e.scale=null,e.state=null,e.stage=null,e.time=null,e.tweens=null,e.world=null,e.particles=null,e.rnd=null,e.physics=null)},setCurrentState:function(t){var e=this.states[t];this.callbackContext=e,this.link(t),this.onInitCallback=e.init||this.dummy,this.onPreloadCallback=e.preload||null,this.onLoadRenderCallback=e.loadRender||null,this.onLoadUpdateCallback=e.loadUpdate||null,this.onCreateCallback=e.create||null,this.onUpdateCallback=e.update||null,this.onPreRenderCallback=e.preRender||null,this.onRenderCallback=e.render||null,this.onResizeCallback=e.resize||null,this.onPausedCallback=e.paused||null,this.onResumedCallback=e.resumed||null,this.onPauseUpdateCallback=e.pauseUpdate||null,this.onShutDownCallback=e.shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=t,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),t===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){!1===this._created&&this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game),!1===this._created&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(t){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,t)},resize:function(t,e){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,t,e)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===i.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this._clearWorld=!0,this._clearCache=!0,this.clearCurrentState(),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,this.current=""}},i.StateManager.prototype.constructor=i.StateManager,Object.defineProperty(i.StateManager.prototype,"created",{get:function(){return this._created}}),i.Signal=function(){},i.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!1,validateListener:function(t,e){if("function"!=typeof t)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",e))},_registerListener:function(t,e,s,n,r){var o,a=this._indexOfListener(t,s);if(-1!==a){if((o=this._bindings[a]).isOnce()!==e)throw new Error("You cannot add"+(e?"":"Once")+"() then add"+(e?"Once":"")+"() the same listener without removing the relationship first.")}else o=new i.SignalBinding(this,t,e,s,n,r),this._addBinding(o);return this.memorize&&this._prevParams&&o.execute(this._prevParams),o},_addBinding:function(t){this._bindings||(this._bindings=[]);var e=this._bindings.length;do{e--}while(this._bindings[e]&&t._priority<=this._bindings[e]._priority);this._bindings.splice(e+1,0,t)},_indexOfListener:function(t,e){if(!this._bindings)return-1;void 0===e&&(e=null);for(var i,s=this._bindings.length;s--;)if((i=this._bindings[s])._listener===t&&i.context===e)return s;return-1},has:function(t,e){return-1!==this._indexOfListener(t,e)},add:function(t,e,i){this.validateListener(t,"add");var s=[];if(arguments.length>3)for(var n=3;n3)for(var n=3;n=this.children.length?-1:this.getChildAt(t)},i.Group.prototype.create=function(t,e,i,s,n,r){void 0===n&&(n=!0);var o=new this.classType(this.game,t,e,i,s);return o.exists=n,o.visible=n,o.alive=n,this.add(o,!1,r)},i.Group.prototype.createMultiple=function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=!1),Array.isArray(e)||(e=[e]),Array.isArray(i)||(i=[i]);var o=this,a=[];return e.forEach(function(e){i.forEach(function(i){for(var h=0;hthis.children.length||-1===t&&-1===e)return!1;for(var a=new i.Rectangle(0,0,s,n),h=t*s,l=e*n,c=o;cthis.children.length-1&&(t=0),this.cursor)return this.cursorIndex=t,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.next=function(){if(this.cursor)return this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.previous=function(){if(this.cursor)return 0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.swap=function(t,e){this.swapChildren(t,e),this.updateZ()},i.Group.prototype.bringToTop=function(t){return t.parent===this&&this.getIndex(t)0&&(this.remove(t,!1,!0),this.addAt(t,0,!0)),t},i.Group.prototype.moveUp=function(t){if(t.parent===this&&this.getIndex(t)0){var e=this.getIndex(t),i=this.getAt(e-1);i&&this.swap(t,i)}return t},i.Group.prototype.xy=function(t,e,i){if(t<0||t>this.children.length)return-1;this.getChildAt(t).x=e,this.getChildAt(t).y=i},i.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},i.Group.prototype.getIndex=function(t){return this.children.indexOf(t)},i.Group.prototype.getByName=function(t){for(var e=0;e0))return!1;var r=e.length;return 1===r?0===s?t[e[0]]=i:1===s?t[e[0]]+=i:2===s?t[e[0]]-=i:3===s?t[e[0]]*=i:4===s&&(t[e[0]]/=i):2===r?0===s?t[e[0]][e[1]]=i:1===s?t[e[0]][e[1]]+=i:2===s?t[e[0]][e[1]]-=i:3===s?t[e[0]][e[1]]*=i:4===s&&(t[e[0]][e[1]]/=i):3===r?0===s?t[e[0]][e[1]][e[2]]=i:1===s?t[e[0]][e[1]][e[2]]+=i:2===s?t[e[0]][e[1]][e[2]]-=i:3===s?t[e[0]][e[1]][e[2]]*=i:4===s&&(t[e[0]][e[1]][e[2]]/=i):4===r&&(0===s?t[e[0]][e[1]][e[2]][e[3]]=i:1===s?t[e[0]][e[1]][e[2]][e[3]]+=i:2===s?t[e[0]][e[1]][e[2]][e[3]]-=i:3===s?t[e[0]][e[1]][e[2]][e[3]]*=i:4===s&&(t[e[0]][e[1]][e[2]][e[3]]/=i)),!0},i.Group.prototype.checkProperty=function(t,e,s,n){if(void 0===n&&(n=!1),this!==t.parent)return!1;var r=i.Utils.getProperty(t,e);return!(void 0===r&&n||r!==s)},i.Group.prototype.set=function(t,e,i,s,n,r,o){if(void 0===o&&(o=!1),e=e.split("."),void 0===s&&(s=!1),void 0===n&&(n=!1),(!1===s||s&&t.alive)&&(!1===n||n&&t.visible))return this.setProperty(t,e,i,r,o)},i.Group.prototype.setAll=function(t,e,i,s,n,r){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===r&&(r=!1),t=t.split("."),n=n||0;for(var o=0;o2){i=[];for(s=2;s2){n=[];for(a=2;a=e&&(t=e-1);var i=this.children[t];this.updateOnlyExistingChildren&&!i.exists||i.update()}},i.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y);for(var t=0;t2){s=[null];for(var n=2;n2){s=[null];for(var n=2;n2){s=[null];for(var n=2;ne[this._sortProperty]?1:t.ze[this._sortProperty]?-1:0},i.Group.prototype.iterate=function(t,e,s,n,r,o){if(0===this.children.length){if(s===i.Group.RETURN_TOTAL)return 0;if(s===i.Group.RETURN_ALL)return[]}var a=0;if(s===i.Group.RETURN_ALL)var h=[];for(var l=0;l0)return this.children[this.children.length-1]},i.Group.prototype.getBottom=function(){if(this.children.length>0)return this.children[0]},i.Group.prototype.getClosestTo=function(t,e,s){for(var n=Number.MAX_VALUE,r=0,o=null,a=0;an&&(!e||e.call(s,h,r))&&(n=r,o=h)}return o},i.Group.prototype.count=function(t,e){return this.iterate(t,e,i.Group.RETURN_TOTAL)},i.Group.prototype.countLiving=function(){return this.count("alive",!0)},i.Group.prototype.countDead=function(){return this.count("alive",!1)},i.Group.prototype.getRandom=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.children.length),0===e?null:i.ArrayUtils.getRandomItem(this.children,t,e)},i.Group.prototype.getRandomExists=function(t,e){var i=this.getAll("exists",!0,t,e);return this.game.rnd.pick(i)},i.Group.prototype.getAll=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=this.children.length);for(var n=[],r=i;r0&&t instanceof i.Group){do{t.add(this.children[0],e)}while(this.children.length>0);this.hash=[],this.cursor=null}return t},i.Group.prototype.removeAll=function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),0!==this.children.length){do{!e&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var s=this.removeChild(this.children[0]);this.removeFromHash(s),t&&s&&s.destroy(!0,i)}while(this.children.length>0);this.hash=[],this.cursor=null}},i.Group.prototype.removeBetween=function(t,e,i,s){if(void 0===e&&(e=this.children.length-1),void 0===i&&(i=!1),void 0===s&&(s=!1),0!==this.children.length){if(t>e||t<0||e>this.children.length)return!1;for(var n=e;n>=t;){!s&&this.children[n].events&&this.children[n].events.onRemovedFromGroup$dispatch(this.children[n],this);var r=this.removeChild(this.children[n]);this.removeFromHash(r),i&&r&&r.destroy(!0),this.cursor===this.children[n]&&(this.cursor=null),n--}this.updateZ()}},i.Group.prototype.scatter=function(t,e){null==t&&(t=this.game.world.bounds),this.forEach(function(e){e.position.set(t.randomX,t.randomY)},null,e)},i.Group.prototype.shuffle=function(){i.ArrayUtils.shuffle(this.children),this.updateZ()},i.Group.prototype.destroy=function(t,e){null===this.game||this.ignoreDestroy||(void 0===t&&(t=!0),void 0===e&&(e=!1),this.onDestroy.dispatch(this,t,e),this.removeAll(t),this.cursor=null,this.filters=null,this.pendingDestroy=!1,e||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(i.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,i.Group.RETURN_TOTAL)}}),Object.defineProperty(i.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(i.Group.prototype,"angle",{get:function(){return i.Math.radToDeg(this.rotation)},set:function(t){this.rotation=i.Math.degToRad(t)}}),Object.defineProperty(i.Group.prototype,"centerX",{get:function(){return this.getBounds(this.parent).centerX},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.halfWidth}}),Object.defineProperty(i.Group.prototype,"centerY",{get:function(){return this.getBounds(this.parent).centerY},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.halfHeight}}),Object.defineProperty(i.Group.prototype,"left",{get:function(){return this.getBounds(this.parent).left},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i}}),Object.defineProperty(i.Group.prototype,"right",{get:function(){return this.getBounds(this.parent).right},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.width}}),Object.defineProperty(i.Group.prototype,"top",{get:function(){return this.getBounds(this.parent).top},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i}}),Object.defineProperty(i.Group.prototype,"bottom",{get:function(){return this.getBounds(this.parent).bottom},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.height}}),i.World=function(t){i.Group.call(this,t,null,"__world",!1),this.bounds=new i.Rectangle(0,0,t.width,t.height),this.camera=null,this._definedSize=!1,this._width=t.width,this._height=t.height,this.game.state.onStateChange.add(this.stateChange,this)},i.World.prototype=Object.create(i.Group.prototype),i.World.prototype.constructor=i.World,i.World.prototype.boot=function(){this.camera=new i.Camera(this.game,0,0,0,this.game.width,this.game.height),this.game.stage.addChild(this),this.camera.boot()},i.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},i.World.prototype.setBounds=function(t,e,i,s){this._definedSize=!0,this._width=i,this._height=s,this.bounds.setTo(t,e,i,s),this.x=t,this.y=e,this.camera.bounds&&this.camera.bounds.setTo(t,e,Math.max(i,this.game.width),Math.max(s,this.game.height)),this.game.physics.setBoundsToWorld()},i.World.prototype.resize=function(t,e){this._definedSize&&(tthis.bounds.right&&(t.x=this.bounds.left)),n&&(t.y+t._currentBounds.heightthis.bounds.bottom&&(t.y=this.bounds.top))):(s&&t.x+ethis.bounds.right&&(t.x=this.bounds.left-e),n&&t.y+ethis.bounds.bottom&&(t.y=this.bounds.top-e))},i.World.prototype.wrapAll=function(t,e,i,s,n,r){t.forEach(this.wrap,this,e,i,s,n,r)},Object.defineProperty(i.World.prototype,"width",{get:function(){return this.bounds.width},set:function(t){t1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.dropFrames?this.rendersThisFrame=0:(this.updateRender(this.time.slowMotion*this.time.desiredFps),this.rendersThisFrame=1);else{var e=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*e,this.time.elapsed),0);var i=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/e),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame)),this.forceSingleRender?this.rendersThisFrame=1:this.rendersThisFrame=Math.min(1,this.updatesThisFrame);this._deltaTime>=e&&(this._deltaTime-=e,this.currentUpdateID=i,this.updateLogic(this.time.desiredFpsMult),i++,!this.forceSingleUpdate||1!==i);)this.time.refresh();i>this._lastCount?this._spiraling++:i0&&this.updateRender(this._deltaTime/e)}}},updateLogic:function(t){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(t),this.debug.preUpdate(),this.input.pauseUpdate()):(this.stepping&&(this.pendingStep=!0),this.time.countUpdate(),this.scale.preUpdate(),this.debug.preUpdate(),this.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(t),this.plugins.preUpdate(t),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(),this.sound.update(),this.input.update(),this.physics.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate()),this.stage.updateTransform()},updateRender:function(t){this.lockRender||(this.time.countRender(),this.state.preRender(t),this.renderType!==i.HEADLESS&&(this.renderer.render(this.stage),this.plugins.render(t),this.state.render(t)),this.plugins.postRender(t))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.debug.destroy&&this.debug.destroy(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.plugins.destroy(),this.debug=null,this.state=null,this.sound=null,this.scale=null,this.stage=null,this.input=null,this.physics=null,this.plugins=null,this.cache=null,this.load=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),i.Canvas.removeFromDOM(this.canvas),PIXI.defaultRenderer=null,i.GAMES[this.id]=null},gamePaused:function(t){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.muteOnPause&&this.sound.setMute(),this.onPause.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(t){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.muteOnPause&&this.sound.unsetMute(),this.onResume.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(t){this.onBlur.dispatch(t),this.stage.disableVisibilityChange||this.gamePaused(t)},focusGain:function(t){this.onFocus.dispatch(t),this.stage.disableVisibilityChange||this.gameResumed(t)}},i.Game.prototype.constructor=i.Game,Object.defineProperty(i.Game.prototype,"paused",{get:function(){return this._paused},set:function(t){!0===t?(!1===this._paused&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),i.Input=function(t){this.game=t,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.customCandidateHandler=null,this.customCandidateHandlerContext=null,this.pollRate=0,this.enabled=!0,this.multiInputOverride=i.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.touchLockCallbacks=[],this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new i.ArraySet,this._localPoint=new i.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},i.Input.MOUSE_OVERRIDES_TOUCH=0,i.Input.TOUCH_OVERRIDES_MOUSE=1,i.Input.MOUSE_TOUCH_COMBINE=2,i.Input.MAX_POINTERS=10,i.Input.prototype={boot:function(){this.mousePointer=new i.Pointer(this.game,0,i.PointerMode.CURSOR),this.addPointer(),this.addPointer(),this.mouse=new i.Mouse(this.game),this.touch=new i.Touch(this.game),this.mspointer=new i.MSPointer(this.game),i.Keyboard&&(this.keyboard=new i.Keyboard(this.game)),i.Gamepad&&(this.gamepad=new i.Gamepad(this.game)),this.onDown=new i.Signal,this.onUp=new i.Signal,this.onTap=new i.Signal,this.onHold=new i.Signal,this.scale=new i.Point(1,1),this.speed=new i.Point,this.position=new i.Point,this._oldPosition=new i.Point,this.circle=new i.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=i.CanvasPool.create(this,1,1),this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.game.device.mspointer||this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var t=this;this._onClickTrampoline=function(e){t.onClickTrampoline(e)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],i.CanvasPool.remove(this),this.game.canvas.removeEventListener("click",this._onClickTrampoline)},setInteractiveCandidateHandler:function(t,e){this.customCandidateHandler=t,this.customCandidateHandlerContext=e},addMoveCallback:function(t,e){this.moveCallbacks.push({callback:t,context:e})},addTouchLockCallback:function(t,e,i){void 0===i&&(i=!1),this.touchLockCallbacks.push({callback:t,context:e,onEnd:i})},removeTouchLockCallback:function(t,e){for(var i=this.touchLockCallbacks.length;i--;)if(this.touchLockCallbacks[i].callback===t&&this.touchLockCallbacks[i].context===e)return this.touchLockCallbacks.splice(i,1),!0;return!1},executeTouchLockCallbacks:function(t,e){for(var i=this.touchLockCallbacks.length;i--;){var s=this.touchLockCallbacks[i];s.onEnd===t&&s.callback.call(s.context,this,e)&&this.touchLockCallbacks.splice(i,1)}},deleteMoveCallback:function(t,e){for(var i=this.moveCallbacks.length;i--;)if(this.moveCallbacks[i].callback===t&&this.moveCallbacks[i].context===e)return void this.moveCallbacks.splice(i,1)},addPointer:function(){if(this.pointers.length>=i.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+i.Input.MAX_POINTERS+" pointers reached."),null;var t=this.pointers.length+1,e=new i.Pointer(this.game,t,i.PointerMode.CONTACT);return this.pointers.push(e),this["pointer"+t]=e,e},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(t);if(!this.pointer2.active)return this.pointer2.start(t);for(var e=2;e0;i++)this.pointers[i].active&&e--;return t-e},getPointer:function(t){void 0===t&&(t=!1);for(var e=0;e=o&&this.game.camera.x+e.x=a&&this.game.camera.y+e.y=o&&this._localPoint.x=a&&this._localPoint.y=o&&this._localPoint.x=a&&this._localPoint.y0&&this._pollCounterthis.game.time.time},justReleased:function(t){return t=t||250,this.isUp&&this.timeUp+t>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},i.DeviceButton.prototype.constructor=i.DeviceButton,Object.defineProperty(i.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),i.Pointer=function(t,e,s){this.game=t,this.id=e,this.type=i.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.pointerMode=s||i.PointerMode.CURSOR|i.PointerMode.CONTACT,this.target=null,this.button=null,this.leftButton=new i.DeviceButton(this,i.Pointer.LEFT_BUTTON),this.middleButton=new i.DeviceButton(this,i.Pointer.MIDDLE_BUTTON),this.rightButton=new i.DeviceButton(this,i.Pointer.RIGHT_BUTTON),this.backButton=new i.DeviceButton(this,i.Pointer.BACK_BUTTON),this.forwardButton=new i.DeviceButton(this,i.Pointer.FORWARD_BUTTON),this.eraserButton=new i.DeviceButton(this,i.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===e,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.interactiveCandidates=[],this.active=!1,this.dirty=!1,this.position=new i.Point,this.positionDown=new i.Point,this.positionUp=new i.Point,this.circle=new i.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},i.Pointer.NO_BUTTON=0,i.Pointer.LEFT_BUTTON=1,i.Pointer.RIGHT_BUTTON=2,i.Pointer.MIDDLE_BUTTON=4,i.Pointer.BACK_BUTTON=8,i.Pointer.FORWARD_BUTTON=16,i.Pointer.ERASER_BUTTON=32,i.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.start(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.start(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.start(e),t===i.Mouse.BACK_BUTTON&&this.backButton.start(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.start(e)},processButtonsUp:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.stop(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.stop(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(e),t===i.Mouse.BACK_BUTTON&&this.backButton.stop(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(e)},processButtonsUpDown:function(t,e){var s="down"===e.type.toLowerCase().substr(-4),n="move"===e.type.toLowerCase().substr(-4);void 0!==t?(s&&1===t&&e.ctrlKey&&(t=2),this.leftButton.startStop(i.Pointer.LEFT_BUTTON&t,e),this.rightButton.startStop(i.Pointer.RIGHT_BUTTON&t,e),this.middleButton.startStop(i.Pointer.MIDDLE_BUTTON&t,e),this.backButton.startStop(i.Pointer.BACK_BUTTON&t,e),this.forwardButton.startStop(i.Pointer.FORWARD_BUTTON&t,e),this.eraserButton.startStop(i.Pointer.ERASER_BUTTON&t,e)):void 0!==e.button?s&&e.ctrlKey&&0===e.button?this.rightButton.start(e):s?this.processButtonsDown(e.button,e):n||this.processButtonsUp(e.button,e):s?e.ctrlKey?this.rightButton.start(e):this.leftButton.start(e):(this.leftButton.stop(e),this.rightButton.stop(e))},updateButtons:function(t){this.button=t.button,this.processButtonsUpDown(t.buttons,t),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(t){var e=this.game.input;return t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.isMouse?this.updateButtons(t):(this.isDown=!0,this.isUp=!1),this.active=!0,this.withinGame=!0,this.dirty=!1,this._history=[],this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(t,!0),this.positionDown.setTo(this.x,this.y),(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.x=this.x,e.y=this.y,e.position.setTo(this.x,this.y),e.onDown.dispatch(this,t),e.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){var t=this.game.input;this.active&&(this.dirty&&(t.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),!1===this._holdSent&&this.duration>=t.holdRate&&((t.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||t.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||t.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===t.totalActivePointers)&&t.onHold.dispatch(this),this._holdSent=!0),t.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+t.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>t.recordLimit&&this._history.shift()))},move:function(t,e){var s=this.game.input;if(!s.pollLocked){void 0===e&&(e=!1),void 0!==t.button&&(this.button=t.button),this.isMouse&&this.updateButtons(t),this.clientX=t.clientX,this.clientY=t.clientY,this.pageX=t.pageX,this.pageY=t.pageY,this.screenX=t.screenX,this.screenY=t.screenY,this.isMouse&&s.mouse.locked&&!e&&(this.rawMovementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.rawMovementY=t.movementY||t.mozMovementY||t.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*s.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*s.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(s.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||s.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||s.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===s.totalActivePointers)&&(s.activePointer=this,s.x=this.x,s.y=this.y,s.position.setTo(s.x,s.y),s.circle.x=s.x,s.circle.y=s.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY);for(var n=s.moveCallbacks.length;n--;)s.moveCallbacks[n].callback.call(s.moveCallbacks[n].context,this,this.x,this.y,e);return null===this.targetObject||this.game.paused&&!this.targetObject.noPause||!0!==this.targetObject.isDragged?s.interactiveItems.total>0&&this.processInteractiveObjects(e):!1===this.targetObject.update(this)&&(this.targetObject=null),this}},processInteractiveObjects:function(t){var e=0,i=-1,s=null,n=this.game.input.interactiveItems.first;for(this.interactiveCandidates=[];n;)n.checked=!1,!n.validForInput(i,e,!1)||this.game.paused&&!n.sprite.noPause||(n.checked=!0,(t&&n.checkPointerDown(this,!0)||!t&&n.checkPointerOver(this,!0))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n))),n=this.game.input.interactiveItems.next;for(n=this.game.input.interactiveItems.first;n;)!n.checked&&n.validForInput(i,e,!0)&&(t&&n.checkPointerDown(this,!1)||!t&&n.checkPointerOver(this,!1))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n)),n=this.game.input.interactiveItems.next;return this.game.input.customCandidateHandler&&(s=this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext,this,this.interactiveCandidates,s)),this.swapTarget(s,!1),null!==this.targetObject},swapTarget:function(t,e){void 0===e&&(e=!1),null===t?this.targetObject&&(this.targetObject._pointerOutHandler(this,e),this.targetObject=null):null===this.targetObject?(this.targetObject=t,t._pointerOverHandler(this,e)):this.targetObject===t?!1===t.update(this)&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this,e),this.targetObject=t,this.targetObject._pointerOverHandler(this,e))},leave:function(t){this.withinGame=!1,this.move(t,!1)},stop:function(t){var e=this.game.input;{if(!this._stateReset||!this.withinGame)return this.timeUp=this.game.time.time,(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.onUp.dispatch(this,t),this.duration>=0&&this.duration<=e.tapRate&&(this.timeUp-this.previousTapTime0&&(this.active=!1),this.withinGame=this.game.scale.bounds.contains(t.pageX,t.pageY),this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),!1===this.isMouse&&e.currentPointers--,e.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this;t.preventDefault()}},justPressed:function(t){return t=t||this.game.input.justPressedRate,!0===this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||this.game.input.justReleasedRate,this.isUp&&this.timeUp+t>this.game.time.time},addClickTrampoline:function(t,e,i,s){if(this.isDown){for(var n=this._clickTrampolines=this._clickTrampolines||[],r=0;rt||this.priorityID===t&&this.sprite.renderOrderID>e))},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(t){return t=t||0,this._pointerData[t].x},pointerY:function(t){return t=t||0,this._pointerData[t].y},pointerDown:function(t){return t=t||0,this._pointerData[t].isDown},pointerUp:function(t){return t=t||0,this._pointerData[t].isUp},pointerTimeDown:function(t){return t=t||0,this._pointerData[t].timeDown},pointerTimeUp:function(t){return t=t||0,this._pointerData[t].timeUp},pointerOver:function(t){if(!this.enabled)return!1;if(void 0===t){for(var e=0;e<10;e++)if(this._pointerData[e].isOver)return!0;return!1}return this._pointerData[t].isOver},pointerOut:function(t){if(!this.enabled)return!1;if(void 0!==t)return this._pointerData[t].isOut;for(var e=0;e<10;e++)if(this._pointerData[e].isOut)return!0},pointerTimeOver:function(t){return t=t||0,this._pointerData[t].timeOver},pointerTimeOut:function(t){return t=t||0,this._pointerData[t].timeOut},pointerDragged:function(t){return t=t||0,this._pointerData[t].isDragged},checkPointerDown:function(t,e){return!!(t.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectClick)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPointerOver:function(t,e){return!!(this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectOver)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPixel:function(t,e,i){if(this.sprite.texture.baseTexture.source){if(null===t&&null===e){this.game.input.getLocalPosition(this.sprite,i,this._tempPoint);var t=this._tempPoint.x,e=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(t-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(e-=-this.sprite.texture.frame.height*this.sprite.anchor.y),t+=this.sprite.texture.frame.x,e+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(t-=this.sprite.texture.trim.x,e-=this.sprite.texture.trim.y,tthis.sprite.texture.crop.right||ethis.sprite.texture.crop.bottom))return this._dx=t,this._dy=e,!1;if(this._dx=t,this._dy=e,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,t,e,1,1,0,0,1,1),this.game.input.hitContext.getImageData(0,0,1,1).data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(t){if(null!==this.sprite&&void 0!==this.sprite.parent)return this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this._pendingDrag?(this._dragDistancePass||(this._dragDistancePass=i.Math.distance(t.x,t.y,this.downPoint.x,this.downPoint.y)>=this.dragDistanceThreshold),this._dragDistancePass&&this._dragTimePass&&this.startDrag(t),!0):this.draggable&&this._draggedPointerID===t.id?this.updateDrag(t,!1):this._pointerData[t.id].isOver?this.checkPointerOver(t)?(this._pointerData[t.id].x=t.x-this.sprite.x,this._pointerData[t.id].y=t.y-this.sprite.y,!0):(this._pointerOutHandler(t),!1):void 0:(this._pointerOutHandler(t),!1)},_pointerOverHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];if(!1===i.isOver||t.dirty){var s=!1===i.isOver;i.isOver=!0,i.isOut=!1,i.timeOver=this.game.time.time,i.x=t.x-this.sprite.x,i.y=t.y-this.sprite.y,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),!e&&s&&this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,t),this.sprite.parent&&this.sprite.parent.onChildInputOver&&this.sprite.parent.onChildInputOver.dispatch(this.sprite,t)}}},_pointerOutHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];i.isOver=!1,i.isOut=!0,i.timeOut=this.game.time.time,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="",this._setHandCursor=!1),!e&&this.sprite&&this.sprite.events&&(this.sprite.events.onInputOut$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputOut&&this.sprite.parent.onChildInputOut.dispatch(this.sprite,t))}},_touchedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(!e.isDown&&e.isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,t))return;if(e.isDown=!0,e.isUp=!1,e.timeDown=this.game.time.time,this.downPoint.set(t.x,t.y),t.dirty=!0,this.sprite&&this.sprite.events&&(this.sprite.events.onInputDown$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputDown&&this.sprite.parent.onChildInputDown.dispatch(this.sprite,t),null===this.sprite))return;this.draggable&&!1===this.isDragged&&(0===this.dragTimeThreshold&&0===this.dragDistanceThreshold?this.startDrag(t):(this._pendingDrag=!0,this._dragDistancePass=0===this.dragDistanceThreshold,this.dragTimeThreshold>0?(this._dragTimePass=!1,this.game.time.events.add(this.dragTimeThreshold,this.dragTimeElapsed,this,t)):this._dragTimePass=!0)),this.bringToTop&&this.sprite.bringToTop()}}},dragTimeElapsed:function(t){this._dragTimePass=!0,this._pendingDrag&&this.sprite&&this._dragDistancePass&&this.startDrag(t)},_releasedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(e.isDown&&t.isUp){e.isDown=!1,e.isUp=!0,e.timeUp=this.game.time.time,e.downDuration=e.timeUp-e.timeDown;var i=this.checkPointerOver(t);this.sprite&&this.sprite.events&&(this.dragStopBlocksInputUp&&(!this.dragStopBlocksInputUp||this.draggable&&this.isDragged&&this._draggedPointerID===t.id)||this.sprite.events.onInputUp$dispatch(this.sprite,t,i),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputUp&&this.sprite.parent.onChildInputUp.dispatch(this.sprite,t,i),i&&(i=this.checkPointerOver(t))),e.isOver=i,!i&&this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),t.dirty=!0,this._pendingDrag=!1,this.draggable&&this.isDragged&&this._draggedPointerID===t.id&&this.stopDrag(t)}}},updateDrag:function(t,e){if(void 0===e&&(e=!1),t.isUp)return this.stopDrag(t),!1;var i=this.globalToLocal(t);if(this.sprite.fixedToCamera)var s=this.game.camera.scale.x*i.x+this._dragPoint.x+this.dragOffset.x,n=this.game.camera.scale.y*i.y+this._dragPoint.y+this.dragOffset.y;else var s=i.x+this._dragPoint.x+this.dragOffset.x,n=i.y+this._dragPoint.y+this.dragOffset.y;if(this.sprite.fixedToCamera)this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=s-this.game.camera.x),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=n-this.game.camera.y),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y));else{var r=this.game.camera.x-this._pointerData[t.id].camX,o=this.game.camera.y-this._pointerData[t.id].camY;this.allowHorizontalDrag&&(this.sprite.x=s+r),this.allowVerticalDrag&&(this.sprite.y=n+o),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.x,this.sprite.y))}return this.sprite.events.onDragUpdate.dispatch(this.sprite,t,s,n,this.snapPoint,e),!0},justOver:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOver&&this.overDuration(t)this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.ythis.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.leftthis.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.xthis.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.ythis.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.leftthis.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},i.InputHandler.prototype.constructor=i.InputHandler,i.Gamepad=function(t){this.game=t,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!==navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this)]},i.Gamepad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},start:function(){if(!this._active){this._active=!0;var t=this;this._onGamepadConnected=function(e){return t.onGamepadConnected(e)},this._onGamepadDisconnected=function(e){return t.onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(t){var e=t.gamepad;this._rawPads.push(e),this._gamepads[e.index].connect(e)},onGamepadDisconnected:function(t){var e=t.gamepad;for(var i in this._rawPads)this._rawPads[i].index===e.index&&this._rawPads.splice(i,1);this._gamepads[e.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(this._active){if(navigator.getGamepads)t=navigator.getGamepads();else if(navigator.webkitGetGamepads)t=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var t=navigator.webkitGamepads();if(t){this._rawPads=[];for(var e=!1,i=0;i0&&s>this.deadZone||s<0&&s<-this.deadZone?this.processAxisChange(i,s):this.processAxisChange(i,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(t){var e=!this.connected;this.connected=!0,this.index=t.index,this._rawPad=t,this._buttons=[],this._buttonsLen=t.buttons.length,this._axes=[],this._axesLen=t.axes.length;for(var s=0;sthis.maxHealth&&(this.health=this.maxHealth),this},heal:function(t){return this.alive&&(this.health+=t,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},i.Component.InCamera=function(){},i.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},i.Component.InputEnabled=function(){},i.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(t){t?null===this.input?(this.input=new i.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},i.Component.InWorld=function(){},i.Component.InWorld.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(this.autoCull||this.checkWorldBounds){if(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull)if(this.game.world.camera.view.intersects(this._bounds))this.renderable=!0,this.game.world.camera.totalInView++;else if(this.renderable=!1,this.outOfCameraBoundsKill)return this.kill(),!1;if(this.checkWorldBounds)if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1}return!0},i.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,outOfCameraBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},i.Component.LifeSpan=function(){},i.Component.LifeSpan.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):!(this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0))||(this.kill(),!1)},i.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(t){return void 0===t&&(t=100),this.alive=!0,this.exists=!0,this.visible=!0,"function"==typeof this.setHealth&&this.setHealth(t),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},i.Component.LoadTexture=function(){},i.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(t,e,s){t===i.PENDING_ATLAS?(t=e,e=0):e=e||0,(s||void 0===s)&&this.animations&&this.animations.stop(),this.key=t,this.customRender=!1;var n=this.game.cache,r=!0,o=!this.texture.baseTexture.scaleMode;if(i.RenderTexture&&t instanceof i.RenderTexture)this.key=t.key,this.setTexture(t);else if(i.BitmapData&&t instanceof i.BitmapData)this.customRender=!0,this.setTexture(t.texture),r=n.hasFrameData(t.key,i.Cache.BITMAPDATA)?!this.animations.loadFrameData(n.getFrameData(t.key,i.Cache.BITMAPDATA),e):!this.animations.loadFrameData(t.frameData,0);else if(i.Video&&t instanceof i.Video){this.customRender=!0;var a=t.texture.valid;this.setTexture(t.texture),this.setFrame(t.texture.frame.clone()),t.onChangeSource.add(this.resizeFrame,this),this.texture.valid=a}else if(i.Tilemap&&t instanceof i.TilemapLayer)this.setTexture(PIXI.Texture.fromCanvas(t.canvas));else if(t instanceof PIXI.Texture)this.setTexture(t);else{var h=n.getImage(t,!0);this.key=h.key,this.setTexture(new PIXI.Texture(h.base)),this.texture.baseTexture.skipRender="__default"===t,r=!this.animations.loadFrameData(h.frameData,e)}r&&(this._frame=i.Rectangle.clone(this.texture.frame)),o||(this.texture.baseTexture.scaleMode=1)},setFrame:function(t){this._frame=t,this.texture.frame.x=t.x,this.texture.frame.y=t.y,this.texture.frame.width=t.width,this.texture.frame.height=t.height,this.texture.crop.x=t.x,this.texture.crop.y=t.y,this.texture.crop.width=t.width,this.texture.crop.height=t.height,t.trimmed?(this.texture.trim?(this.texture.trim.x=t.spriteSourceSizeX,this.texture.trim.y=t.spriteSourceSizeY,this.texture.trim.width=t.sourceSizeW,this.texture.trim.height=t.sourceSizeH):this.texture.trim={x:t.spriteSourceSizeX,y:t.spriteSourceSizeY,width:t.sourceSizeW,height:t.sourceSizeH},this.texture.width=t.sourceSizeW,this.texture.height=t.sourceSizeH,this.texture.frame.width=t.sourceSizeW,this.texture.frame.height=t.sourceSizeH):!t.trimmed&&this.texture.trim&&(this.texture.trim=null),t.rotated&&(this.texture.rotated=!0),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(t,e,i){this.texture.frame.resize(e,i),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(t){this.animations.frame=t}},frameName:{get:function(){return this.animations.frameName},set:function(t){this.animations.frameName=t}}},i.Component.Overlap=function(){},i.Component.Overlap.prototype={overlap:function(t){return i.Rectangle.intersects(this.getBounds(),t.getBounds())}},i.Component.PhysicsBody=function(){},i.Component.PhysicsBody.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):this.fresh&&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.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,this.preUpdateChildren(),!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!(!this._exists||!this.parent.exists)||(this.renderOrderID=-1,!1))},i.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},i.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(t){this.position.x=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},i.Component.Reset=function(){},i.Component.Reset.prototype.reset=function(t,e,i){return void 0===i&&(i=1),this.world.set(t,e),this.position.set(t,e),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=i),this.components.PhysicsBody&&this.body&&this.body.reset(t,e,!1,!1),this},i.Component.ScaleMinMax=function(){},i.Component.ScaleMinMax.prototype={transformCallback:null,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(t){this.scaleMin&&(t.athis.scaleMax.x&&(t.a=this.scaleMax.x),t.d>this.scaleMax.y&&(t.d=this.scaleMax.y))},setScaleMinMax:function(t,e,s,n){void 0===e?e=s=n=t:void 0===s&&(s=n=e,e=t),null===t?this.scaleMin=null:this.scaleMin?this.scaleMin.set(t,e):this.scaleMin=new i.Point(t,e),null===s?this.scaleMax=null:this.scaleMax?this.scaleMax.set(s,n):this.scaleMax=new i.Point(s,n),null===this.scaleMin?this.transformCallback=null:(this.transformCallback=this.checkTransform,this.transformCallbackContext=this)}},i.Component.Smoothed=function(){},i.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(t){t?this.texture&&(this.texture.baseTexture.scaleMode=0,this.texture.baseTexture.dirty()):this.texture&&(this.texture.baseTexture.scaleMode=1,this.texture.baseTexture.dirty())}}},i.GameObjectFactory=function(t){this.game=t,this.world=this.game.world},i.GameObjectFactory.prototype={existing:function(t){return this.world.add(t)},weapon:function(t,e,s,n,r){var o=this.game.plugins.add(i.Weapon);return r&&(o.bulletClass=r),o.createBullets(t,e,s,n),o},image:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Image(this.game,t,e,s,n))},sprite:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Sprite(this.game,t,e,s,n))},creature:function(t,e,s,n,r){void 0===r&&(r=this.world);var o=new i.Creature(this.game,t,e,s,n);return r.add(o),o},tween:function(t){return this.game.tweens.create(t)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},physicsGroup:function(t,e,s,n){return new i.Group(this.game,e,s,n,!0,t)},spriteBatch:function(t,e,s){return void 0===t&&(t=null),void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},tileSprite:function(t,e,s,n,r,o,a){return void 0===a&&(a=this.world),a.add(new i.TileSprite(this.game,t,e,s,n,r,o))},rope:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.Rope(this.game,t,e,s,n,r))},text:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Text(this.game,t,e,s,n))},button:function(t,e,s,n,r,o,a,h,l,c){return void 0===c&&(c=this.world),c.add(new i.Button(this.game,t,e,s,n,r,o,a,h,l))},graphics:function(t,e,s){return void 0===s&&(s=this.world),s.add(new i.Graphics(this.game,t,e))},emitter:function(t,e,s){return this.game.particles.add(new i.Particles.Arcade.Emitter(this.game,t,e,s))},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.BitmapText(this.game,t,e,s,n,r))},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},video:function(t,e){return new i.Video(this.game,t,e)},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t},plugin:function(t){return this.game.plugins.add(t)}},i.GameObjectFactory.prototype.constructor=i.GameObjectFactory,i.GameObjectCreator=function(t){this.game=t,this.world=this.game.world},i.GameObjectCreator.prototype={image:function(t,e,s,n){return new i.Image(this.game,t,e,s,n)},sprite:function(t,e,s,n){return new i.Sprite(this.game,t,e,s,n)},tween:function(t){return new i.Tween(t,this.game,this.game.tweens)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},spriteBatch:function(t,e,s){return void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},tileSprite:function(t,e,s,n,r,o){return new i.TileSprite(this.game,t,e,s,n,r,o)},rope:function(t,e,s,n,r){return new i.Rope(this.game,t,e,s,n,r)},text:function(t,e,s,n){return new i.Text(this.game,t,e,s,n)},button:function(t,e,s,n,r,o,a,h,l){return new i.Button(this.game,t,e,s,n,r,o,a,h,l)},graphics:function(t,e){return new i.Graphics(this.game,t,e)},emitter:function(t,e,s){return new i.Particles.Arcade.Emitter(this.game,t,e,s)},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return new i.BitmapText(this.game,t,e,s,n,r,o)},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t}},i.GameObjectCreator.prototype.constructor=i.GameObjectCreator,i.Sprite=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.SPRITE,this.physicsType=i.SPRITE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Sprite.prototype=Object.create(PIXI.Sprite.prototype),i.Sprite.prototype.constructor=i.Sprite,i.Component.Core.install.call(i.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Sprite.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Sprite.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Sprite.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Sprite.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Sprite.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Image=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.IMAGE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Image.prototype=Object.create(PIXI.Sprite.prototype),i.Image.prototype.constructor=i.Image,i.Component.Core.install.call(i.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","ScaleMinMax","Smoothed"]),i.Image.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Image.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Image.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Image.prototype.preUpdate=function(){return!(!this.preUpdateInWorld()||!this.preUpdateLifeSpan())&&this.preUpdateCore()},i.Button=function(t,e,s,n,r,o,a,h,l,c){e=e||0,s=s||0,n=n||null,r=r||null,o=o||this,i.Image.call(this,t,e,s,n,h),this.type=i.BUTTON,this.physicsType=i.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new i.Signal,this.onInputOut=new i.Signal,this.onInputDown=new i.Signal,this.onInputUp=new i.Signal,this.onOverMouseOnly=!0,this.justReleasedPreventsOver=i.PointerMode.CONTACT,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(a,h,l,c),null!==r&&this.onInputUp.add(r,o),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this)},i.Button.prototype=Object.create(i.Image.prototype),i.Button.prototype.constructor=i.Button;return i.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},i.Button.prototype.setStateFrame=function(t,e,i){var s="_on"+t+"Frame";null!==e?(this[s]=e,i&&this.changeStateFrame(t)):this[s]=null},i.Button.prototype.changeStateFrame=function(t){if(this.freezeFrames)return!1;var e=this["_on"+t+"Frame"];return"string"==typeof e?(this.frameName=e,!0):"number"==typeof e&&(this.frame=e,!0)},i.Button.prototype.setFrames=function(t,e,i,s){this.setStateFrame("Over",t,this.input.pointerOver()),this.setStateFrame("Out",e,!this.input.pointerOver()),this.setStateFrame("Down",i,this.input.pointerDown()),this.setStateFrame("Up",s,this.input.pointerUp())},i.Button.prototype.setStateSound=function(t,e,s){var n="on"+t+"Sound",r="on"+t+"SoundMarker";e instanceof i.Sound||e instanceof i.AudioSprite?(this[n]=e,this[r]="string"==typeof s?s:""):(this[n]=null,this[r]="")},i.Button.prototype.playStateSound=function(t){var e=this["on"+t+"Sound"];if(e){var i=this["on"+t+"SoundMarker"];return e.play(i),!0}return!1},i.Button.prototype.setSounds=function(t,e,i,s,n,r,o,a){this.setStateSound("Over",t,e),this.setStateSound("Out",n,r),this.setStateSound("Down",i,s),this.setStateSound("Up",o,a)},i.Button.prototype.setOverSound=function(t,e){this.setStateSound("Over",t,e)},i.Button.prototype.setOutSound=function(t,e){this.setStateSound("Out",t,e)},i.Button.prototype.setDownSound=function(t,e){this.setStateSound("Down",t,e)},i.Button.prototype.setUpSound=function(t,e){this.setStateSound("Up",t,e)},i.Button.prototype.onInputOverHandler=function(t,e){e.justReleased()&&(this.justReleasedPreventsOver&e.pointerMode)===e.pointerMode||(this.changeStateFrame("Over"),this.onOverMouseOnly&&!e.isMouse||(this.playStateSound("Over"),this.onInputOver&&this.onInputOver.dispatch(this,e)))},i.Button.prototype.onInputOutHandler=function(t,e){this.changeStateFrame("Out"),this.playStateSound("Out"),this.onInputOut&&this.onInputOut.dispatch(this,e)},i.Button.prototype.onInputDownHandler=function(t,e){this.changeStateFrame("Down"),this.playStateSound("Down"),this.onInputDown&&this.onInputDown.dispatch(this,e)},i.Button.prototype.onInputUpHandler=function(t,e,i){this.playStateSound("Up"),this.onInputUp&&this.onInputUp.dispatch(this,e,i),this.freezeFrames||(!0===this.forceOut||(this.forceOut&e.pointerMode)===e.pointerMode?this.changeStateFrame("Out"):this.changeStateFrame("Up")||(i?this.changeStateFrame("Over"):this.changeStateFrame("Out")))},i.SpriteBatch=function(t,e,s,n){void 0!==e&&null!==e||(e=t.world),i.Group.call(this,t,e,s,n),this.type=i.SPRITEBATCH,this.fastSpriteBatch=null,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.Group.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||(this.fastSpriteBatch=new PIXI.WebGLFastSpriteBatch(t.gl),this.ready=!0),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n=0&&t<=this.width&&e>=0&&e<=this.height&&(i.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|n<<8|s:this.pixels[e*this.width+t]=s<<24|n<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,s){s||(s=i.Color.createColor());var n=~~(t+e*this.width);return n*=4,s.r=this.data[n],s.g=this.data[++n],s.b=this.data[++n],s.a=this.data[++n],s},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,s,n,r){return i.Color.unpackPixel(this.getPixel32(t,e),s,n,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=i.Color.createColor(),s=0,n=0,r=1,o=!1;1===t?(r=-1,n=this.height):3===t&&(r=-1,s=this.width);do{i.Color.unpackPixel(this.getPixel32(s,n),e),0===t||1===t?++s===this.width&&(s=0,((n+=r)>=this.height||n<=0)&&(o=!0)):2!==t&&3!==t||++n===this.height&&(n=0,((s+=r)>=this.width||s<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=s,e.y=n,e},getBounds:function(t){return void 0===t&&(t=new i.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,s,n,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),t instanceof i.RenderTexture&&(t=t.getCanvas()),this._image=t,t instanceof i.Sprite||t instanceof i.Image||t instanceof i.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof i.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==s&&null!==s||(s=0),n&&(this._size.x=n),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=s),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+s,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var n=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===n.a||0===n.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=n.tx,o=n.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),s&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(n.a,n.b,n.c,n.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,s){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,s),t.type===i.GROUP&&t.exists)this.drawGroup(t,e,s);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var n=0;ne.width&&(n=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,s),this._circle=new i.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,n,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),i.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this},copyBitmapData:function(t,e,i){t.update();for(var s,n=0;n80*s){h=c=t[0],l=u=t[1];for(var g=s;gc&&(c=d),p>u&&(u=p);f=Math.max(c-h,u-l)}return i.EarCut.earcutLinked(o,a,s,h,l,f),a},i.EarCut.linkedList=function(t,e,s,n,r){var o,a,h,l=0;for(o=e,a=s-n;o0)for(o=e;o=e;o-=n)h=i.EarCut.insertNode(o,t[o],t[o+1],h);return h},i.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var s,n=t;do{if(s=!1,n.steiner||!i.EarCut.equals(n,n.next)&&0!==i.EarCut.area(n.prev,n,n.next))n=n.next;else{if(i.EarCut.removeNode(n),(n=e=n.prev)===n.next)return null;s=!0}}while(s||n!==e);return e},i.EarCut.earcutLinked=function(t,e,s,n,r,o,a){if(t){!a&&o&&i.EarCut.indexCurve(t,n,r,o);for(var h,l,c=t;t.prev!==t.next;)if(h=t.prev,l=t.next,o?i.EarCut.isEarHashed(t,n,r,o):i.EarCut.isEar(t))e.push(h.i/s),e.push(t.i/s),e.push(l.i/s),i.EarCut.removeNode(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?(t=i.EarCut.cureLocalIntersections(t,e,s),i.EarCut.earcutLinked(t,e,s,n,r,o,2)):2===a&&i.EarCut.splitEarcut(t,e,s,n,r,o):i.EarCut.earcutLinked(i.EarCut.filterPoints(t),e,s,n,r,o,1);break}}},i.EarCut.isEar=function(t){var e=t.prev,s=t,n=t.next;if(i.EarCut.area(e,s,n)>=0)return!1;for(var r=t.next.next;r!==t.prev;){if(i.EarCut.pointInTriangle(e.x,e.y,s.x,s.y,n.x,n.y,r.x,r.y)&&i.EarCut.area(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},i.EarCut.isEarHashed=function(t,e,s,n){var r=t.prev,o=t,a=t.next;if(i.EarCut.area(r,o,a)>=0)return!1;for(var h=r.xo.x?r.x>a.x?r.x:a.x:o.x>a.x?o.x:a.x,u=r.y>o.y?r.y>a.y?r.y:a.y:o.y>a.y?o.y:a.y,d=i.EarCut.zOrder(h,l,e,s,n),p=i.EarCut.zOrder(c,u,e,s,n),f=t.nextZ;f&&f.z<=p;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=d;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0},i.EarCut.cureLocalIntersections=function(t,e,s){var n=t;do{var r=n.prev,o=n.next.next;i.EarCut.intersects(r,n,n.next,o)&&i.EarCut.locallyInside(r,o)&&i.EarCut.locallyInside(o,r)&&(e.push(r.i/s),e.push(n.i/s),e.push(o.i/s),i.EarCut.removeNode(n),i.EarCut.removeNode(n.next),n=t=o),n=n.next}while(n!==t);return n},i.EarCut.splitEarcut=function(t,e,s,n,r,o){var a=t;do{for(var h=a.next.next;h!==a.prev;){if(a.i!==h.i&&i.EarCut.isValidDiagonal(a,h)){var l=i.EarCut.splitPolygon(a,h);return a=i.EarCut.filterPoints(a,a.next),l=i.EarCut.filterPoints(l,l.next),i.EarCut.earcutLinked(a,e,s,n,r,o),void i.EarCut.earcutLinked(l,e,s,n,r,o)}h=h.next}a=a.next}while(a!==t)},i.EarCut.eliminateHoles=function(t,e,s,n){var r,o,a,h,l,c=[];for(r=0,o=e.length;r=n.next.y){var h=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);h<=r&&h>a&&(a=h,s=n.x=n.x&&n.x>=s.x&&i.EarCut.pointInTriangle(os.x)&&i.EarCut.locallyInside(n,t)&&(s=n,u=l),n=n.next;return s},i.EarCut.indexCurve=function(t,e,s,n){var r=t;do{null===r.z&&(r.z=i.EarCut.zOrder(r.x,r.y,e,s,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,i.EarCut.sortLinked(r)},i.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},i.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},i.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},i.EarCut.isValidDiagonal=function(t,e){return i.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!i.EarCut.intersectsPolygon(t,e)&&i.EarCut.locallyInside(t,e)&&i.EarCut.locallyInside(e,t)&&i.EarCut.middleInside(t,e)},i.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},i.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},i.EarCut.intersects=function(t,e,s,n){return i.EarCut.area(t,e,s)>0!=i.EarCut.area(t,e,n)>0&&i.EarCut.area(s,n,t)>0!=i.EarCut.area(s,n,e)>0},i.EarCut.intersectsPolygon=function(t,e){var s=t;do{if(s.i!==t.i&&s.next.i!==t.i&&s.i!==e.i&&s.next.i!==e.i&&i.EarCut.intersects(s,s.next,t,e))return!0;s=s.next}while(s!==t);return!1},i.EarCut.locallyInside=function(t,e){return i.EarCut.area(t.prev,t,t.next)<0?i.EarCut.area(t,e,t.next)>=0&&i.EarCut.area(t,t.prev,e)>=0:i.EarCut.area(t,e,t.prev)<0||i.EarCut.area(t,t.next,e)<0},i.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},i.EarCut.splitPolygon=function(t,e){var s=new i.EarCut.Node(t.i,t.x,t.y),n=new i.EarCut.Node(e.i,e.x,e.y),r=t.next,o=e.prev;return t.next=e,e.prev=t,s.next=r,r.prev=s,n.next=s,s.prev=n,o.next=n,n.prev=o,n},i.EarCut.insertNode=function(t,e,s,n){var r=new i.EarCut.Node(t,e,s);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r},i.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},i.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var s,n=e.gl,r=e.projection,o=e.offset,a=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,n);var h=t._webGL[n.id];if(h)for(var l=0;l=PIXI.WebGLGraphics.stencilBufferLimit&&(a.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit?(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildPoly(a,o)||(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))),a.lineWidth>0&&(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildLine(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,0),a.type===i.RECTANGLE?PIXI.WebGLGraphics.buildRectangle(a,o):a.type===i.CIRCLE||a.type===i.ELLIPSE?PIXI.WebGLGraphics.buildCircle(a,o):a.type===i.ROUNDEDRECTANGLE&&PIXI.WebGLGraphics.buildRoundedRectangle(a,o)),s.lastIndex++}for(n=0;n19600?(_=y-x,w=v-b,_/=R=Math.sqrt(_*_+w*w),w/=R,_*=F,w*=F,L.push(p-_,f-w),L.push(G,N,X,U),L.push(p+_,f+w),L.push(G,N,X,U),L.push(p-_,f-w),L.push(G,N,X,U),O++):(L.push(l,c),L.push(G,N,X,U),L.push(p-(l-p),f-(c-f)),L.push(G,N,X,U));for(u=n[2*(I-2)],d=n[2*(I-2)+1],p=n[2*(I-1)],y=-(d-(f=n[2*(I-1)+1])),v=u-p,y/=R=Math.sqrt(y*y+v*v),v/=R,y*=F,v*=F,L.push(p-y,f-v),L.push(G,N,X,U),L.push(p+y,f+v),L.push(G,N,X,U),B.push(k),s=0;sh?r:h,l=oc?o:c;s.push(a,l,h,l,h,c,a,c);var d=s.length/2;for(u=0;uS?S:C,e.beginPath(),e.moveTo(_,w+C),e.lineTo(_,w+P-C),e.quadraticCurveTo(_,w+P,_+C,w+P),e.lineTo(_+T-C,w+P),e.quadraticCurveTo(_+T,w+P,_+T,w+P-C),e.lineTo(_+T,w+C),e.quadraticCurveTo(_+T,w,_+T-C,w),e.lineTo(_+C,w),e.quadraticCurveTo(_,w,_,w+C),e.closePath(),(r.fillColor||0===r.fillColor)&&(e.globalAlpha=r.fillAlpha*s,e.fillStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.fill()),r.lineWidth&&(e.globalAlpha=r.lineAlpha*s,e.strokeStyle="#"+("00000"+(0|h).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var s=t.graphicsData.length;if(0!==s){e.beginPath();for(var n=0;nP?P:T,e.moveTo(x,b+T),e.lineTo(x,b+w-T),e.quadraticCurveTo(x,b+w,x+T,b+w),e.lineTo(x+_-T,b+w),e.quadraticCurveTo(x+_,b+w,x+_,b+w-T),e.lineTo(x+_,b+T),e.quadraticCurveTo(x+_,b,x+_-T,b),e.lineTo(x+T,b),e.quadraticCurveTo(x,b,x,b+T),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},i.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},i.GraphicsData.prototype.constructor=i.GraphicsData,i.GraphicsData.prototype.clone=function(){return new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},i.Graphics=function(t,e,s){void 0===e&&(e=0),void 0===s&&(s=0),this.type=i.GRAPHICS,this.physicsType=i.SPRITE,this.anchor=new i.Point,PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new i.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1,i.Component.Core.init.call(this,t,e,s,"",null)},i.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Graphics.prototype.constructor=i.Graphics,i.Component.Core.install.call(i.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),i.Graphics.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Graphics.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Graphics.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Graphics.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Graphics.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Graphics.prototype.postUpdate=function(){i.Component.PhysicsBody.postUpdate.call(this),i.Component.FixedToCamera.postUpdate.call(this),this._boundsDirty&&(this.updateLocalBounds(),this._boundsDirty=!1);for(var t=0;t0&&this.drawPolygon(s)}else this.drawPolygon(s)},i.Graphics.prototype.drawTriangles=function(t,e,s){void 0===s&&(s=!1);var n,r=new i.Point,o=new i.Point,a=new i.Point,h=[];if(e)if(t[0]instanceof i.Point)for(n=0;nc*a)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var x=d+s+p*(v+y*v),b=Math.cos(x),_=-Math.sin(x);u.push((f*b+g*_)*i+t,(f*-_+g*b)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},i.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},i.Graphics.prototype.drawRect=function(t,e,s,n){return this.drawShape(new i.Rectangle(t,e,s,n)),this},i.Graphics.prototype.drawRoundedRect=function(t,e,s,n,r){return this.drawShape(new i.RoundedRectangle(t,e,s,n,r)),this},i.Graphics.prototype.drawCircle=function(t,e,s){return this.drawShape(new i.Circle(t,e,s)),this},i.Graphics.prototype.drawEllipse=function(t,e,s,n){return this.drawShape(new i.Ellipse(t,e,s,n)),this},i.Graphics.prototype.drawPolygon=function(t){t instanceof i.Polygon&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var s=0;sw?m:w,w=v>w?v:w,w=b>w?b:w,T=y>T?y:T,T=x>T?x:T,T=_>T?_:T,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=C,this._bounds.height=T-C,this._currentBounds=this._bounds,this._currentBounds},i.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;ee?a+l:e,s=hn?h+c:n;else if(p===i.CIRCLE)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else if(p===i.ELLIPSE)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else{o=r.points;for(var g=0;ge?a+f:e,s=h-fn?h+f:n}}else t=0,e=0,s=0,n=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=s-m,this._localBounds.height=n-s+2*m},i.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},i.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},i.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},i.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof i.Polygon&&(t=t.clone()).flatten();var e=new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===i.POLYGON&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(i.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),i.RenderTexture=function(t,e,s,n,r,o,a,h){if(void 0===e&&(e=100),void 0===s&&(s=100),void 0===n&&(n=""),void 0===r&&(r=i.scaleModes.DEFAULT),void 0===o&&(o=1),void 0===a&&(a=PIXI.defaultRenderer),void 0===h&&(h=0),this.game=t,this.key=n,this.type=i.RENDERTEXTURE,this._tempMatrix=new i.Matrix,this.width=e,this.height=s,this.resolution=o,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=this.frame.clone(),this.baseTexture=new PIXI.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=r,this.baseTexture.hasLoaded=!0,PIXI.Texture.call(this,this.baseTexture,this.frame.clone()),this.renderer=a,this.renderer.type===i.WEBGL){var l=this.renderer.gl;this.baseTexture.textureIndex=h,this.baseTexture._dirty[l.id]=!1,this.textureBuffer=new PIXI.FilterTexture(l,this.width,this.height,this.baseTexture.scaleMode,h),this.baseTexture._glTextures[l.id]=this.textureBuffer.texture,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.textureBuffer=new PIXI.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new i.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(PIXI.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.renderXY=function(t,e,s,n){t.updateTransform(),this._tempMatrix.copyFrom(t.worldTransform),this._tempMatrix.tx=e,this._tempMatrix.ty=s,this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.renderRawXY=function(t,e,s,n){this._tempMatrix.identity().translate(e,s),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.render=function(t,e,s){void 0===e||null===e?this._tempMatrix.copyFrom(t.worldTransform):this._tempMatrix.copyFrom(e),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,s):this._renderCanvas(t,this._tempMatrix,s)},i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype._renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n-1&&this.characterLimitSize0&&this.style.maxLines0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(e[a]):l+=this.context.measureText(e[a]).width,this.style.wordWrap&&(l-=this.context.measureText(" ").width)}else{var h=e[a].split(/(?:\t)/),l=this.padding.x+this.style.strokeThickness;if(Array.isArray(i))for(var c=0,u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.measureLine(h[u]):Math.ceil(this.context.measureText(h[u]).width),u>0&&(c+=i[u-1]),l=c+d}else for(u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(h[u]):l+=Math.ceil(this.context.measureText(h[u]).width),l+=this.game.math.snapToCeil(l,i)-l}s[a]=Math.ceil(l),n=Math.max(n,s[a])}this.canvas.width=n*this._res;var p=r.fontSize+this.style.strokeThickness+this.padding.y,f=p*o,g=this._lineSpacing;g<0&&Math.abs(g)>p&&(g=-p),0!==g&&(f+=g>0?g*e.length:g*(e.length-1)),this.canvas.height=f*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var m,y;for(this._charCount=0,a=0;a0&&(y+=g*a),"right"===this.style.align?m+=n-s[a]:"center"===this.style.align&&(m+=(n-s[a])/2),this.autoRound&&(m=Math.round(m),y=Math.round(y)),this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.updateLine(e[a],m,y):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===i?this.context.strokeText(e[a],m,y):this.renderTabLine(e[a],m,y,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===i?this.context.fillText(e[a],m,y):this.renderTabLine(e[a],m,y,!0)));this.updateTexture(),this.dirty=!1},i.Text.prototype.renderTabLine=function(t,e,i,s){var n=t.split(/(?:\t)/),r=this.style.tabs,o=0;if(Array.isArray(r))for(var a=0,h=0;h0&&(a+=r[h-1]),o=e+a,s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i);else for(h=0;h0||this.fontStyles.length>0){var n=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(n.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(n.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(n)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill)),e+=this.context.measureText(s).width,this._charCount++}return Math.ceil(e)},i.Text.prototype.updateLine=function(t,e,i){for(var s=0;s0||this.fontStyles.length>0){var r=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(r.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(r.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(r)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(n,e,i)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(n,e,i)),e+=this.context.measureText(n).width,this._charCount++}},i.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},i.Text.prototype.clearFontValues=function(){return this.fontStyles=[],this.fontWeights=[],this.dirty=!0,this},i.Text.prototype.addColor=function(t,e){return this.colors[e]=t,this.dirty=!0,this},i.Text.prototype.addStrokeColor=function(t,e){return this.strokeColors[e]=t,this.dirty=!0,this},i.Text.prototype.addFontStyle=function(t,e){return this.fontStyles[e]=t,this.dirty=!0,this},i.Text.prototype.addFontWeight=function(t,e){return this.fontWeights[e]=t,this.dirty=!0,this},i.Text.prototype.precalculateWordWrap=function(t){return this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font,this.runWordWrap(t).split(/(?:\r\n|\r|\n)/)},i.Text.prototype.runWordWrap=function(t){return this.useAdvancedWrap?this.advancedWordWrap(t):this.basicWordWrap(t)},i.Text.prototype.advancedWordWrap=function(t){for(var e=this.context,i=this.style.wordWrapWidth,s="",n=t.replace(/ +/gi," ").split(/\r?\n/gi),r=n.length,o=0;ol){if(0===u){for(var g=p;g.length&&(g=g.slice(0,-1),!((f=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var m=d.substr(g.length);c[u]=m,h+=g}var y=c[u].length?u:u+1,v=c.slice(y).join(" ").replace(/[ \n]*$/gi,"");n[o+1]=v+" "+(n[o+1]||""),r=n.length;break}h+=p,l-=f}s+=h.replace(/[ \n]*$/gi,"")+"\n"}}return s=s.replace(/[\s|\n]*$/gi,"")},i.Text.prototype.basicWordWrap=function(t){for(var e="",i=t.split("\n"),s=0;sn?(o>0&&(e+="\n"),e+=r[o]+" ",n=this.style.wordWrapWidth-a):(n-=h,e+=r[o]+" ")}ss&&(this.style.wordWrapWidth=s)),this.updateTexture(),this},i.Text.prototype.updateTexture=function(){var t=this.texture.baseTexture,e=this.texture.crop,i=this.texture.frame,s=this.canvas.width,n=this.canvas.height;if(t.width=s,t.height=n,e.width=s,e.height=n,i.width=s,i.height=n,this.texture.width=s,this.texture.height=n,this._width=s,this._height=n,this.textBounds){var r=this.textBounds.x,o=this.textBounds.y;"right"===this.style.boundsAlignH?r+=this.textBounds.width-this.canvas.width/this.resolution:"center"===this.style.boundsAlignH&&(r+=this.textBounds.halfWidth-this.canvas.width/this.resolution/2),"bottom"===this.style.boundsAlignV?o+=this.textBounds.height-this.canvas.height/this.resolution:"middle"===this.style.boundsAlignV&&(o+=this.textBounds.halfHeight-this.canvas.height/this.resolution/2),this.pivot.x=-r,this.pivot.y=-o}this.renderable=0!==s&&0!==n,this.texture.requiresReTint=!0,this.texture.baseTexture.dirty()},i.Text.prototype._renderWebGL=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.Text.prototype._renderCanvas=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.Text.prototype.determineFontProperties=function(t){var e=i.Text.fontPropertiesCache[t];if(!e){e={};var s=i.Text.fontPropertiesCanvas,n=i.Text.fontPropertiesContext;n.font=t;var r=Math.ceil(n.measureText("|MÉq").width),o=Math.ceil(n.measureText("|MÉq").width),a=2*o;if(o=1.4*o|0,s.width=r,s.height=a,n.fillStyle="#f00",n.fillRect(0,0,r,a),n.font=t,n.textBaseline="alphabetic",n.fillStyle="#000",n.fillText("|MÉq",0,o),!n.getImageData(0,0,r,a))return e.ascent=o,e.descent=o+6,e.fontSize=e.ascent+e.descent,i.Text.fontPropertiesCache[t]=e,e;var h,l,c=n.getImageData(0,0,r,a).data,u=c.length,d=4*r,p=0,f=!1;for(h=0;ho;h--){for(l=0;l0?this._maxWidth:null,l=[],c=0;c=h&&r>-1)return{width:o||n,text:i.substr(0,c-(c-r)),end:!1,chars:l};n+=(p.xAdvance+g)*e,l.push(s+(p.xOffset+g)*e),s+=(p.xAdvance+g)*e,a=d}return{width:n,text:i,end:u,chars:l}},i.BitmapText.prototype.cleanText=function(t,e){void 0===e&&(e="");var i=this._data.font;if(!i)return"";for(var s=/\r\n|\n\r|\n|\r/g,n=t.replace(s,"\n").split("\n"),r=0;rthis.textWidth&&(this.textWidth=c.width),n+=t.lineHeight*i,e=e.substr(c.text.length+1)}while(!1===c.end);this.textHeight=n;for(var r=0,o=0,a=this.textWidth*this.anchor.x,h=this.textHeight*this.anchor.y,l=0;l0&&(this._fontSize=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"smoothed",{get:function(){return!this._data.base.scaleMode},set:function(t){this._data.base.scaleMode=t?0:1,this._data.base.dirty()}}),i.RetroFont=function(t,e,s,n,r,o,a,h,l,c){if(!t.cache.checkImageKey(e))return!1;void 0!==o&&null!==o||(o=t.cache.getImage(e).width/s),this.characterWidth=s,this.characterHeight=n,this.characterSpacingX=a||0,this.characterSpacingY=h||0,this.characterPerRow=o,this.offsetX=l||0,this.offsetY=c||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=t.cache.getImage(e),this._text="",this.grabData=[],this.frameData=new i.FrameData;for(var u=this.offsetX,d=this.offsetY,p=0,f=0;f?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",i.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",i.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",i.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",i.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",i.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",i.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",i.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",i.RetroFont.prototype.setFixedWidth=function(t,e){void 0===e&&(e="left"),this.fixedWidth=t,this.align=e},i.RetroFont.prototype.setText=function(t,e,i,s,n,r){this.multiLine=e||!1,this.customSpacingX=i||0,this.customSpacingY=s||0,this.align=n||"left",this.autoUpperCase=!r,t.length>0&&(this.text=t)},i.RetroFont.prototype.buildRetroFontText=function(){var t=0,e=0;if(this.clear(),this.multiLine){var s=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var n=0;n0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),t=0,this.align===i.RetroFont.ALIGN_RIGHT?t=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===i.RetroFont.ALIGN_CENTER&&(t=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(this._text,t,0,this.customSpacingX);this.requiresReTint=!0},i.RetroFont.prototype.pasteLine=function(t,e,i,s){for(var n=0;n=0&&(this.stamp.frame=this.grabData[t.charCodeAt(n)],this.renderXY(this.stamp,e,i,!1),(e+=this.characterWidth+s)>this.width))break},i.RetroFont.prototype.getLongestLine=function(){var t=0;if(this._text.length>0)for(var e=this._text.split("\n"),i=0;it&&(t=e[i].length);return t},i.RetroFont.prototype.removeUnsupportedCharacters=function(t){for(var e="",i=0;i=0||!t&&"\n"===s)&&(e=e.concat(s))}return e},i.RetroFont.prototype.updateOffset=function(t,e){if(this.offsetX!==t||this.offsetY!==e){for(var i=t-this.offsetX,s=e-this.offsetY,n=this.game.cache.getFrameData(this.stamp.key).getFrames(),r=n.length;r--;)n[r].x+=i,n[r].y+=s;this.buildRetroFontText()}},Object.defineProperty(i.RetroFont.prototype,"text",{get:function(){return this._text},set:function(t){var e;(e=this.autoUpperCase?t.toUpperCase():t)!==this._text&&(this._text=e,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(i.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(t){this.stamp.smoothed=t,this.buildRetroFontText()}}),i.Rope=function(t,e,s,n,r,o){this.points=o||[],this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.ROPE,PIXI.DisplayObjectContainer.call(this),this.texture=i.Cache.DEFAULT,this.uvs=new Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new Float32Array([0,0,100,0,100,100,0,100]),this.colors=new Float32Array([1,1,1,1]),this.indices=new Uint16Array([0,1,2,3]),o&&(this.vertices=new Float32Array(4*o.length),this.uvs=new Float32Array(4*o.length),this.colors=new Float32Array(2*o.length),this.indices=new Uint16Array(2*o.length)),this.dirty=!0,this.canvasPadding=0,this.drawMode=i.Rope.TRIANGLE_STRIP,i.Component.Core.init.call(this,t,e,s,n,r),this.refresh()},i.Rope.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Rope.prototype.constructor=i.Rope,i.Component.Core.install.call(i.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Rope.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Rope.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Rope.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Rope.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Rope.TRIANGLE_STRIP=0,i.Rope.TRIANGLES=1,i.Rope.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},i.Rope.prototype.reset=function(t,e){return i.Component.Reset.prototype.reset.call(this,t,e),this},i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=this.indices,s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o=t.length,a=1;a1&&1,o=Math.sqrt(s.x*s.x+s.y*s.y),a=this.texture.height/2,s.x/=o,s.y/=o,s.x*=a,s.y*=a,h[r]=n.x+s.x,h[r+1]=n.y+s.y,h[r+2]=n.x-s.x,h[r+3]=n.y-s.y,i=n;PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.Rope.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Rope.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Rope.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Rope.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Rope.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Rope.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Rope.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n0){var _=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,T=(l+c+u)/3,P=(d+p+f)/3,C=l-T,S=d-P,A=Math.sqrt(C*C+S*S);l=T+C/A*(A+_),d=P+S/A*(A+w),S=p-P,c=T+(C=c-T)/(A=Math.sqrt(C*C+S*S))*(A+_),p=P+S/A*(A+w),S=f-P,u=T+(C=u-T)/(A=Math.sqrt(C*C+S*S))*(A+_),f=P+S/A*(A+w)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*x+v*y+m*b-x*y-v*m-g*b,M=l*x+v*u+c*b-x*u-v*c-l*b,R=g*c+l*y+m*u-c*y-l*m-g*u,L=g*x*u+v*c*y+l*m*b-l*x*y-v*m*u-g*c*b,B=d*x+v*f+p*b-x*f-v*p-d*b,I=g*p+d*y+m*f-p*y-d*m-g*f,O=g*x*f+v*p*y+d*m*b-d*x*y-v*m*f-g*p*b;t.transform(M/E,B/E,R/E,I/E,L/E,O/E),t.drawImage(o,0,0),t.restore()},i.Rope.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;nh?m:h,l=y>l?y:l}if(c===-1/0||l===1/0)return PIXI.EmptyRectangle;var v=this._bounds;return v.x=c,v.width=h-c,v.y=u,v.height=l-u,this._currentBounds=v,v},Object.defineProperty(i.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(t){t&&"function"==typeof t?(this._hasUpdateAnimation=!0,this._updateAnimation=t):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(i.Rope.prototype,"segments",{get:function(){for(var t,e,s,n,r,o,a,h,l=[],c=0;c(_=y>(_=g>(_=p>_?p:_)?g:_)?y:_)?x:_,w=b>(w=v>(w=m>(w=f>w?f:w)?m:w)?v:w)?b:w;var C=this._bounds;return C.x=T,C.width=_-T,C.y=P,C.height=w-P,this._currentBounds=C,C},Object.defineProperty(i.TileSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TileSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var e=parseInt(RegExp.$1,10),i=parseInt(RegExp.$2,10);(10===e&&i>=11||e>10)&&(s.dolby=!0)}}catch(t){}}(),function(){var t=document.createElement("video");try{!!t.canPlayType&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(s.oggVideo=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.h264Video=!0,s.mp4Video=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(s.webmVideo=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(s.vp9Video=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.hlsVideo=!0))}catch(t){}}(),function(){var t,e=document.createElement("p"),i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var n in i)void 0!==e.style[n]&&(e.style[n]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(i[n]));document.body.removeChild(e),s.css3D=void 0!==t&&t.length>0&&"none"!==t}(),s.pixelRatio=window.devicePixelRatio||1,s.iPhone=-1!==navigator.userAgent.toLowerCase().indexOf("iphone"),s.iPhone4=2===s.pixelRatio&&s.iPhone,s.iPad=-1!==navigator.userAgent.toLowerCase().indexOf("ipad"),"undefined"!=typeof Int8Array?s.typedArray=!0:s.typedArray=!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(s.littleEndian=t(),s.LITTLE_ENDIAN=s.littleEndian),s.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==s.littleEndian&&e(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(s.vibration=!0),function(){s.canvas=!!window.CanvasRenderingContext2D||s.cocoonJS;try{s.localStorage=!!localStorage.getItem}catch(t){s.localStorage=!1}s.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),s.fileSystem=!!window.requestFileSystem,s.webGL=!!window.WebGLRenderingContext,s.worker=!!window.Worker,s.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,s.quirksMode="CSS1Compat"!==document.compatMode,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,s.getUserMedia=s.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,s.firefox&&s.firefoxVersion<21&&(s.getUserMedia=!1),!s.iOS&&(s.ie||s.firefox||s.chrome)&&(s.canvasBitBltShift=!0),(s.safari||s.mobileSafari)&&(s.canvasBitBltShift=!1)}(),function(){var t=i.CanvasPool.create(this,6,1),e=t.getContext("2d");e.fillStyle="rgba(10, 20, 30, 0.5)",e.fillRect(0,0,1,1);var n=e.getImageData(0,0,1,1);if(n){e.putImageData(n,1,0);var r=e.getImageData(1,0,1,1);s.canHandleAlpha=r.data[0]===n.data[0]&&r.data[1]===n.data[1]&&r.data[2]===n.data[2]&&r.data[3]===n.data[3]}e.globalCompositeOperation="multiply",s.canUseMultiply="multiply"===e.globalCompositeOperation,i.CanvasPool.removeByCanvas(t),PIXI.CanvasTinter.tintMethod=s.canUseMultiply?PIXI.CanvasTinter.tintWithMultiply:PIXI.CanvasTinter.tintWithPerPixel}(),function(){for(var t=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],e=document.createElement("div"),i=0;i=1)&&(s.touch=!0),(window.PointerEvent||window.MSPointerEvent||window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(s.mspointer=!0),s.cocoonJS||("onwheel"in window||s.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":s.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"))},i.Device.canPlayAudio=function(t){return!("mp3"!==t||!this.mp3)||(!("ogg"!==t||!this.ogg&&!this.opus)||(!("m4a"!==t||!this.m4a)||(!("opus"!==t||!this.opus)||(!("wav"!==t||!this.wav)||(!("webm"!==t||!this.webm)||!("mp4"!==t||!this.dolby))))))},i.Device.canPlayVideo=function(t){return!("webm"!==t||!this.webmVideo&&!this.vp9Video)||(!("mp4"!==t||!this.mp4Video&&!this.h264Video)||(!("ogg"!==t&&"ogv"!==t||!this.oggVideo)||!("mpeg"!==t||!this.hlsVideo)))},i.Device.needsTouchUnlock=function(){return!!(!this.cocoonJS&&(this.iOS||this.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)},i.Device.isAndroidStockBrowser=function(){var t=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return t&&t[1]<537},i.Canvas={create:function(t,e,s,n,r){e=e||256,s=s||256;var o=r?document.createElement("canvas"):i.CanvasPool.create(t,e,s);return"string"==typeof n&&""!==n&&(o.id=n),o.width=e,o.height=s,o.style.display="block",o},setBackgroundColor:function(t,e){return e=e||"rgb(0,0,0)",t.style.backgroundColor=e,t},setTouchAction:function(t,e){return e=e||"none",t.style.msTouchAction=e,t.style["ms-touch-action"]=e,t.style["touch-action"]=e,t},setUserSelect:function(t,e){return e=e||"none",t.style["-webkit-touch-callout"]=e,t.style["-webkit-user-select"]=e,t.style["-khtml-user-select"]=e,t.style["-moz-user-select"]=e,t.style["-ms-user-select"]=e,t.style["user-select"]=e,t.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",t},addToDOM:function(t,e,i){var s;return void 0===i&&(i=!0),e&&("string"==typeof e?s=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(s=e)),s||(s=document.body),i&&s.style&&(s.style.overflow="hidden"),s.appendChild(t),t},removeFromDOM:function(t){t.parentNode&&t.parentNode.removeChild(t)},setTransform:function(t,e,i,s,n,r,o){return t.setTransform(s,r,o,n,e,i),t},setSmoothingEnabled:function(t,e){var s=i.Canvas.getSmoothingPrefix(t);return s&&(t[s]=e),t},getSmoothingPrefix:function(t){var e=["i","webkitI","msI","mozI","oI"];for(var i in e){var s=e[i]+"mageSmoothingEnabled";if(s in t)return s}return null},getSmoothingEnabled:function(t){var e=i.Canvas.getSmoothingPrefix(t);if(e)return t[e]},setImageRenderingCrisp:function(t){for(var e=["-webkit-optimize-contrast","-moz-crisp-edges","crisp-edges","pixelated"],i=0;i0&&0==(t&t-1))return t;for(var e=1;e0&&0==(t&t-1)&&e>0&&0==(e&e-1)},random:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return Math.random()*(e-t)+t},between:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t},fuzzyEqual:function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)e-i},fuzzyCeil:function(t,e){return void 0===e&&(e=1e-4),Math.ceil(t-e)},fuzzyFloor:function(t,e){return void 0===e&&(e=1e-4),Math.floor(t+e)},average:function(){for(var t=0,e=arguments.length,i=0;i=i.Math.PI2-s?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=s:e=0?t:t+2*Math.PI},maxAdd:function(t,e,i){return Math.min(t+e,i)},minSub:function(t,e,i){return Math.max(t-e,i)},wrap:function(t,e,i){var s=i-e;if(s<=0)return 0;var n=(t-e)%s;return n<0&&(n+=s),n+e},wrapValue:function(t,e,i){return t=Math.abs(t),e=Math.abs(e),i=Math.abs(i),(t+e)%i},isOdd:function(t){return!!(1&t)},isEven:function(t){return!(1&t)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;et[i]&&(i=e);return t[i]},minProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;ie[s][t]&&(s=i);return e[s][t]},wrapAngle:function(t,e){return e?this.wrap(t,-Math.PI,Math.PI):this.wrap(t,-180,180)},linearInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return e<0?this.linear(t[0],t[1],s):e>1?this.linear(t[i],t[i-1],i-s):this.linear(t[n],t[n+1>i?i:n+1],s-n)},bezierInterpolation:function(t,e){for(var i=0,s=t.length-1,n=0;n<=s;n++)i+=Math.pow(1-e,s-n)*Math.pow(e,n)*t[n]*this.bernstein(s,n);return i},catmullRomInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return t[0]===t[i]?(e<0&&(n=Math.floor(s=i*(1+e))),this.catmullRom(t[(n-1+i)%i],t[n],t[(n+1)%i],t[(n+2)%i],s-n)):e<0?t[0]-(this.catmullRom(t[0],t[0],t[1],t[1],-s)-t[0]):e>1?t[i]-(this.catmullRom(t[i],t[i],t[i-1],t[i-1],s-i)-t[i]):this.catmullRom(t[n?n-1:0],t[n],t[i0?Math.ceil(t):Math.floor(t)},sinCosGenerator:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1);for(var n=e,r=i,o=s*Math.PI/t,a=[],h=[],l=0;l0?1:0},percent:function(t,e,i){return void 0===i&&(i=0),t>e||i>e?1:tt?0:(t-i)/e}},i.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},i.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e>>0,s=(e*=s)>>>0,s+=4294967296*(e-=s);return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},i.RandomDataGenerator.prototype.constructor=i.RandomDataGenerator,i.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},i.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new i.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new i.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new i.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new i.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null==this.nodes[0]||-1===(e=this.getIndex(t))){if(this.objects.push(t),this.objects.length>this.maxObjects&&this.levelthis.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.ythis.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof i.Rectangle)var e=this.objects,s=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,s=this.getIndex(t.body)}return this.nodes[0]&&(e=-1!==s?e.concat(this.nodes[s].retrieve(t)):(e=(e=(e=e.concat(this.nodes[0].retrieve(t))).concat(this.nodes[1].retrieve(t))).concat(this.nodes[2].retrieve(t))).concat(this.nodes[3].retrieve(t))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},i.QuadTree.prototype.constructor=i.QuadTree,i.Net=function(t){this.game=t},i.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},i.Net.prototype.constructor=i.Net,i.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:i.Easing.Power0,Power1:i.Easing.Power1,Power2:i.Easing.Power2,Power3:i.Easing.Power3,Power4:i.Easing.Power4,Linear:i.Easing.Linear.None,Quad:i.Easing.Quadratic.Out,Cubic:i.Easing.Cubic.Out,Quart:i.Easing.Quartic.Out,Quint:i.Easing.Quintic.Out,Sine:i.Easing.Sinusoidal.Out,Expo:i.Easing.Exponential.Out,Circ:i.Easing.Circular.Out,Elastic:i.Easing.Elastic.Out,Back:i.Easing.Back.Out,Bounce:i.Easing.Bounce.Out,"Quad.easeIn":i.Easing.Quadratic.In,"Cubic.easeIn":i.Easing.Cubic.In,"Quart.easeIn":i.Easing.Quartic.In,"Quint.easeIn":i.Easing.Quintic.In,"Sine.easeIn":i.Easing.Sinusoidal.In,"Expo.easeIn":i.Easing.Exponential.In,"Circ.easeIn":i.Easing.Circular.In,"Elastic.easeIn":i.Easing.Elastic.In,"Back.easeIn":i.Easing.Back.In,"Bounce.easeIn":i.Easing.Bounce.In,"Quad.easeOut":i.Easing.Quadratic.Out,"Cubic.easeOut":i.Easing.Cubic.Out,"Quart.easeOut":i.Easing.Quartic.Out,"Quint.easeOut":i.Easing.Quintic.Out,"Sine.easeOut":i.Easing.Sinusoidal.Out,"Expo.easeOut":i.Easing.Exponential.Out,"Circ.easeOut":i.Easing.Circular.Out,"Elastic.easeOut":i.Easing.Elastic.Out,"Back.easeOut":i.Easing.Back.Out,"Bounce.easeOut":i.Easing.Bounce.Out,"Quad.easeInOut":i.Easing.Quadratic.InOut,"Cubic.easeInOut":i.Easing.Cubic.InOut,"Quart.easeInOut":i.Easing.Quartic.InOut,"Quint.easeInOut":i.Easing.Quintic.InOut,"Sine.easeInOut":i.Easing.Sinusoidal.InOut,"Expo.easeInOut":i.Easing.Exponential.InOut,"Circ.easeInOut":i.Easing.Circular.InOut,"Elastic.easeInOut":i.Easing.Elastic.InOut,"Back.easeInOut":i.Easing.Back.InOut,"Bounce.easeInOut":i.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},i.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t,e){return e||(e=!1),this._tweens.some(function(i){return i.target===t&&(!e||i.isRunning&&!i.pendingDelete)})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},i.TweenManager.prototype.constructor=i.TweenManager,i.Tween=function(t,e,s){this.game=e,this.target=t,this.manager=s,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new i.Signal,this.onLoop=new i.Signal,this.onRepeat=new i.Signal,this.onChildComplete=new i.Signal,this.onComplete=new i.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=s.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},i.Tween.updateColor=function(t){i.Color.updateColor(t.target)},i.Tween.prototype={to:function(t,e,s,n,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).to(t,e,s,r,o,a)),n&&this.start(),this)},from:function(t,e,s,n,r,o,a){return void 0===e&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).from(t,e,s,r,o,a)),n&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),this.pendingDelete)return console.warn("Phaser.Tween.start cannot be called after Tween.stop"),this;if(null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(i=0;ithis.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(s=0;s0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t=this.startTime))return i.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var s in this.vEnd){var n=this.vStart[s],r=this.vEnd[s];Array.isArray(r)?this.parent.target[s]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[s]=n+(r-n)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():i.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction.call(this.interpolationContext,a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,i.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return i.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,i.TweenData.LOOPED}},i.TweenData.prototype.constructor=i.TweenData,i.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-i.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*i.Easing.Bounce.In(2*t):.5*i.Easing.Bounce.Out(2*t-1)+.5}}},i.Easing.Default=i.Easing.Linear.None,i.Easing.Power0=i.Easing.Linear.None,i.Easing.Power1=i.Easing.Quadratic.Out,i.Easing.Power2=i.Easing.Cubic.Out,i.Easing.Power3=i.Easing.Quartic.Out,i.Easing.Power4=i.Easing.Quintic.Out,i.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.updates=0,this.renders=0,this.fps=0,this.ups=0,this.rps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new i.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},i.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new i.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3){var t=this.now-this._timeLastSecond;this.fps=Math.round(1e3*this.frames/t),this.ups=Math.round(1e3*this.updates/t),this.rps=Math.round(1e3*this.renders/t),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0,this.updates=0,this.renders=0}},countUpdate:function(){this.advancedTiming&&this.updates++},countRender:function(){this.advancedTiming&&this.renders++},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(i.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),i.Time.prototype.constructor=i.Time,i.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new i.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},i.Timer.MINUTE=6e4,i.Timer.SECOND=1e3,i.Timer.HALF=500,i.Timer.QUARTER=250,i.Timer.prototype={create:function(t,e,s,n,r,o){var a=t=Math.round(t);0===this._now?a+=this.game.time.time:a+=this._now;var h=new i.TimerEvent(this,t,a,s,e,n,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.ticke.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i=e.tick)||e.pendingDelete)break;this._newTick=this._now+e.delay-(this._now-e.tick),this._newTick<0&&(this._newTick=this._now+e.delay),!0===e.loop?(e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):e.repeatCount>0?(e.repeatCount--,e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):(this._marked++,e.pendingDelete=!0,e.callback.apply(e.callbackContext,e.args)),this._i++}this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;ethis._now?this.nextTick-this._now:0}}),Object.defineProperty(i.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(i.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(i.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),i.Timer.prototype.constructor=i.Timer,i.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},i.TimerEvent.prototype.constructor=i.TimerEvent,i.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},i.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,s,n,r){return e=e||[],s=s||60,void 0===n&&(n=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new i.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,s,n),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;ithis._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},i.AnimationManager.prototype.constructor=i.AnimationManager,Object.defineProperty(i.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(i.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(i.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(i.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(i.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){var e;"number"==typeof t&&this._frameData&&(e=this._frameData.getFrame(t))&&(this.currentFrame=e,this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(i.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){var e;"string"==typeof t&&this._frameData&&(e=this._frameData.getFrameByName(t))?(this.currentFrame=e,this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame)):console.warn("Cannot set frameName: "+t)}}),i.Animation=function(t,e,s,n,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=n,this.name=s,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new i.Signal,this.onUpdate=null,this.onComplete=new i.Signal,this.onLoop=new i.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},i.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(s=0;s=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay?(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay):this._frameDiff=0,this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(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=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},i.Animation.prototype.constructor=i.Animation,Object.defineProperty(i.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(i.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(i.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(i.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(i.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(i.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new i.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),i.Animation.generateFrameNames=function(t,e,s,n,r){void 0===n&&(n="");var o=[],a="";if(e=s;h--)a=t+(a="number"==typeof r?i.Utils.pad(h.toString(),r,"0",1):h.toString())+n,o.push(a);return o},i.Frame=function(t,e,s,n,r,o){this.index=t,this.x=e,this.y=s,this.width=n,this.height=r,0!==this.width&&0!==this.height||console.warn('Phaser.Frame: Frame "'+this.name+'" has a width or height of zero'),this.name=o,this.centerX=Math.floor(n/2),this.centerY=Math.floor(r/2),this.distance=i.Math.distance(0,0,n,r),this.rotated=!1,this.trimmed=!1,this.sourceSizeW=n,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},i.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=i.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new i.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new i.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},i.Frame.prototype.constructor=i.Frame,i.FrameData=function(){this._frames=[],this._frameNames=[]},i.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new i.FrameData,e=0;ed||h<-d)return console.warn("Phaser.AnimationParser.spriteSheet: skipFrames = "+h.toString()+" is larger than total sprite number "+d.toString()),null;if(h<0&&(h=d+h),-1!==r&&(d=h+r),0===c||0===u||cc&&(f=o,g+=n+a);return p},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var s,n=new i.FrameData,r=e.frames,o=0;o tag")}},i.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{},compressedTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new i.Signal,this._cacheMap=[],this._cacheMap[i.Cache.CANVAS]=this._cache.canvas,this._cacheMap[i.Cache.IMAGE]=this._cache.image,this._cacheMap[i.Cache.TEXTURE]=this._cache.texture,this._cacheMap[i.Cache.SOUND]=this._cache.sound,this._cacheMap[i.Cache.TEXT]=this._cache.text,this._cacheMap[i.Cache.PHYSICS]=this._cache.physics,this._cacheMap[i.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[i.Cache.BINARY]=this._cache.binary,this._cacheMap[i.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[i.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[i.Cache.JSON]=this._cache.json,this._cacheMap[i.Cache.XML]=this._cache.xml,this._cacheMap[i.Cache.VIDEO]=this._cache.video,this._cacheMap[i.Cache.SHADER]=this._cache.shader,this._cacheMap[i.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this._pendingCount=0,this.onReady=new i.Signal,this._addImages()},i.Cache.CANVAS=1,i.Cache.IMAGE=2,i.Cache.TEXTURE=3,i.Cache.SOUND=4,i.Cache.TEXT=5,i.Cache.PHYSICS=6,i.Cache.TILEMAP=7,i.Cache.BINARY=8,i.Cache.BITMAPDATA=9,i.Cache.BITMAPFONT=10,i.Cache.JSON=11,i.Cache.XML=12,i.Cache.VIDEO=13,i.Cache.SHADER=14,i.Cache.RENDER_TEXTURE=15,i.Cache.DEFAULT=null,i.Cache.DEFAULT_KEY="__default",i.Cache.DEFAULT_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==",i.Cache.MISSING=null,i.Cache.MISSING_KEY="__missing",i.Cache.MISSING_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==",i.Cache.READY_TIMEOUT=1e3,i.Cache.prototype={addCompressedTextureMetaData:function(t,e,s,n){this.checkImageKey(t)&&this.removeImage(t);var r=s in i.LoaderParser?i.LoaderParser[s](n):n,o={key:t,url:e,data:r,base:new PIXI.BaseTexture(r,null,this.game.resolution),frame:new i.Frame(0,0,0,r.width,r.height,t),frameData:new i.FrameData,fileFormat:s};return o.frameData.addFrame(new i.Frame(0,0,0,r.width,r.height,e)),this._cache.image[t]=o,this._resolveURL(e,o),o},addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,s){this.checkImageKey(t)&&this.removeImage(t),!1===s.complete&&console.warn('Phaser.Cache.addImage: Image "'+t+"\" hasn't been retrieved yet");var n={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution),frame:new i.Frame(0,0,0,s.width,s.height,t),frameData:new i.FrameData};return n.frameData.addFrame(new i.Frame(0,0,0,s.width,s.height,e)),this._cache.image[t]=n,this._resolveURL(e,n),"__default"===t?i.Cache.DEFAULT=new PIXI.Texture(n.base):"__missing"===t&&(i.Cache.MISSING=new PIXI.Texture(n.base)),n},addImageAsync:function(t,e,i){var s=this,n=new Image;n.onload=function(){i.call(this,s.addImage(t,null,n)),s._removePending(),n.onload=null},this._addPending(),n.src=e},addDefaultImage:function(){this.addImageAsync(i.Cache.DEFAULT_KEY,i.Cache.DEFAULT_SRC,function(t){t.base.skipRender=!0,i.Cache.DEFAULT=new PIXI.Texture(t.base)})},addMissingImage:function(){this.addImageAsync(i.Cache.MISSING_KEY,i.Cache.MISSING_SRC,function(t){i.Cache.MISSING=new PIXI.Texture(t.base)})},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,s){return e.key=t,void 0===s&&(s=new i.FrameData).addFrame(e.textureFrame),this._cache.bitmapData[t]={data:e,frameData:s},e},addBitmapFont:function(t,e,s,n,r,o,a){var h={url:e,data:s,font:null,base:new PIXI.BaseTexture(s,null,this.game.resolution)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?i.LoaderParser.jsonBitmapFont(n,h.base,o,a,!1,this.game.resolution):i.LoaderParser.xmlBitmapFont(n,h.base,o,a,!1,this.game.resolution),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addBitmapFontFromAtlas:function(t,e,s,n,r,o,a){var h=this.getFrameByName(e,s);if(h){var l={font:null,base:this.getBaseTexture(e),frame:h};void 0===o&&(o=0),void 0===a&&(a=0);var c;"json"===r?(c=this.getJSON(n),l.font=i.LoaderParser.jsonBitmapFont(c,l.base,o,a,h,this.game.resolution)):(c=this.getXML(n),l.font=i.LoaderParser.xmlBitmapFont(c,l.base,o,a,h,this.game.resolution)),this._cache.bitmapFont[t]=l}},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new i.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,s,n,r,o,a,h,l){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var c={key:t,url:e,data:s,frameWidth:n,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(s,null,this.game.resolution),frameData:i.AnimationParser.spriteSheet(this.game,s,n,r,o,a,h,l)};this._cache.image[t]=c,this._resolveURL(e,c)},addTextureAtlas:function(t,e,s,n,r){var o={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution)};r===i.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=i.AnimationParser.XMLData(this.game,n,t):r===i.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=i.AnimationParser.JSONDataPyxel(this.game,n,t):Array.isArray(n.frames)?o.frameData=i.AnimationParser.JSONData(this.game,n,t):o.frameData=i.AnimationParser.JSONDataHash(this.game,n,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(i.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(i.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(i.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(i.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(i.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(i.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(i.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(i.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(i.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(i.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(i.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(i.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(i.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(i.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(i.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,i.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var s=this.getItem(t,i.Cache.IMAGE,"getImage");return null===s&&(s=this.getItem("__missing",i.Cache.IMAGE,"getImage")),e?s:s.data},getTextureFrame:function(t){return this.getItem(t,i.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,i.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,i.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,i.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,s){var n=this.getItem(t,i.Cache.PHYSICS,"getPhysicsData","data");if(null===n||void 0===e||null===e)return n;if(n[e]){var r=n[e];if(!r||!s)return r;for(var o in r)if((o=r[o]).fixtureKey===s)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+s+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,i.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,i.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,i.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,i.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var s=this.getItem(t,i.Cache.JSON,"getJSON","data");return s?e?i.Utils.extend(!0,Array.isArray(s)?[]:{},s):s:null},getXML:function(t){return this.getItem(t,i.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,i.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,i.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,i.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,s){void 0===s&&(s=i.Cache.IMAGE),this._cacheMap[s][t]&&(this._cacheMap[s][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){return(t=this._resolveURL(t))?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=i.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var s in this._cacheMap[t])"__default"!==s&&"__missing"!==s&&e.push(s);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.image[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t0?setTimeout(function(){t.isReady||(console.warn("Phaser.Cache: Still waiting for images after %s ms.",e),t._ready())},i.Cache.READY_TIMEOUT):this._ready()},_addPending:function(){this._pendingCount+=1},_removePending:function(){this._pendingCount-=1,this._checkReady()},_checkReady:function(){this.isReady&&this._ready()},_ready:function(){this._pendingCount=0,this.onReady.dispatch(this)}},i.Cache.prototype.constructor=i.Cache,Object.defineProperty(i.Cache.prototype,"isReady",{get:function(){return this._pendingCount<=0}}),i.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new i.Signal,this.onLoadComplete=new i.Signal,this.onPackComplete=new i.Signal,this.onFileStart=new i.Signal,this.onFileComplete=new i.Signal,this.onFileError=new i.Signal,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},i.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,i.Loader.TEXTURE_ATLAS_JSON_HASH=1,i.Loader.TEXTURE_ATLAS_XML_STARLING=2,i.Loader.PHYSICS_LIME_CORONA_JSON=3,i.Loader.PHYSICS_PHASER_JSON=4,i.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,i.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new i.Rectangle(0,0,1,t.height):new i.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r=e||t&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var n=this;setTimeout(function(){n.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.reset(),this.onLoadComplete.dispatch(),this.game.state&&this.game.state.loadComplete())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(e)for(var s=0;s=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},getVideoURL:function(t){for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s="error loading asset from URL "+(t.requestUrl||this.transformUrl(t.url,t));!i&&e&&(i=e.status),i&&(s=s+" ("+i+")"),this.asyncComplete(t,s)},fileComplete:function(t,e){var s=!0;switch(t.type){case"packfile":r=JSON.parse(e.responseText);t.data=r||{};break;case"texture":var n=/\.([^.]+)$/.exec(t.url.split("?",1)[0])[1].toLowerCase();null!==t.data?this.cache.addCompressedTextureMetaData(t.key,t.url,n,t.data):this.cache.addCompressedTextureMetaData(t.key,t.url,n,e.response);break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing,t.skipFrames);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(s=!1,t.format===i.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===i.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===i.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==i.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(s=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var r=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,r,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}s&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else(e=new ActiveXObject("Microsoft.XMLDOM")).async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(i.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return i.Math.clamp(t||0,0,100)}}),Object.defineProperty(i.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),i.Loader.prototype.constructor=i.Loader,i.LoaderParser={bitmapFont:function(t,e,i,s,n,r){return this.xmlBitmapFont(t,e,i,s,n,r)},xmlBitmapFont:function(t,e,i,s,n,r){null==r&&(r=1);var o={},a=t.getElementsByTagName("info")[0],h=t.getElementsByTagName("common")[0];o.font=a.getAttribute("face"),o.size=parseInt(a.getAttribute("size"),10),o.lineHeight=parseInt(h.getAttribute("lineHeight"),10)+s,o.chars={};for(var l=t.getElementsByTagName("char"),c=n?n.x:0,u=n?n.y:0,d=0;d=0){switch(r>=0&&r<=3?e="PVRTC":r>=7&&r<=11?e="S3TC":6===r&&(e="ETC1"),r){case 0:o=35841;break;case 1:o=35843;break;case 2:o=35840;break;case 3:o=35842;break;case 6:o=36196;break;case 7:o=33777;break;case 9:o=33778;break;case 11:o=33779;break;default:o=-1}n={complete:!0,fileFormat:"PVR",compressionAlgorithm:e,flags:i[1],pixelFormat:r,colorSpace:i[4],channelType:i[5],height:i[6],width:i[7],depth:i[8],numberOfSurfaces:i[9],numberOfFaces:i[10],numberOfMipmaps:i[11],metaDataSize:i[12],textureData:s.subarray(52+i[12],s.byteLength),glExtensionFormat:o}}return n},dds:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null;return 68===e[0]&&68===e[1]&&83===e[2]&&32===e[3]&&"DX10"===(s={complete:!0,fileFormat:"DDS",compressionAlgorithm:"S3TC",size:i[1],flags:i[2],height:i[3],width:i[4],pitch:i[5],depth:i[6],mipmapCount:i[7],formatSize:i[19],formatFlag:i[19],formatFourCC:[String.fromCharCode(e[84]),String.fromCharCode(e[85]),String.fromCharCode(e[86]),String.fromCharCode(e[87])].join(""),formatBitCount:i[21],formatRBitMask:i[22],formatGBitMask:i[23],formatBBitMask:i[24],formatABitMask:i[25],caps1:i[26],caps2:i[27],caps3:i[28],caps4:i[29],reserved2:i[30],DXGIFormat:null,resourceDimension:null,miscFlag:null,arraySize:null,textureData:e.subarray(i[1]+4,e.byteLength)}).formatFourCC&&(s.DXGIFormat=i[31],s.resourceDimension=i[32],s.miscFlag=i[33],s.arraySize=i[34],s.miscFlag=i[35]),s},ktx:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null,n=16+i[15]/4|0,r=i[n],o=i[7],a=0;if(171===e[0]&&75===e[1]&&84===e[2]&&88===e[3]&&32===e[4]&&49===e[5]&&49===e[6]&&187===e[7]&&13===e[8]&&10===e[9]&&26===e[10]&&10===e[11]&&[36196,35840,35841,35842,35843,33776,33777,33778,33779].indexOf(o)>=0){switch(o){case 36196:a="ETC1";break;case 35840:case 35841:case 35842:case 35843:a="PVRTC";break;case 33776:case 33777:case 33778:case 33779:a="S3TC"}s={complete:!0,fileFormat:"KTX",compressionAlgorithm:a,endianness:i[3],glType:i[4],glTypeSize:i[5],glFormat:i[6],glInternalFormat:i[7],glBaseInternalFormat:i[8],width:i[9],height:i[10],pixelDepth:i[11],numberOfArrayElements:i[12],numberOfFaces:i[13],numberOfMipmapLevels:i[14],bytesOfKeyValueData:i[15],keyAndValueByteSize:i[16],imageSize:r,textureData:e.subarray(4*(n+1),r+100)}}return s},pkm:function(t){var e=new Uint8Array(t),i=null;return 80===e[0]&&75===e[1]&&77===e[2]&&32===e[3]&&(i={complete:!0,fileFormat:"PKM",compressionAlgorithm:"ETC1",format:65535&(e[6]<<8|e[7]),width:65535&(e[8]<<8|e[9]),height:65535&(e[10]<<8|e[11]),originalWidth:65535&(e[12]<<8|e[13]),originalHeight:65535&(e[14]<<8|e[15]),textureData:e.subarray(16,e.length)}),i}},i.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},i.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},i.AudioSprite.prototype.constructor=i.AudioSprite,i.Sound=function(t,e,s,n,r){void 0===s&&(s=1),void 0===n&&(n=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=n,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this._globalVolume=1,this._markedToDelete=!1,this._removeFromSoundManager=!1,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=s,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new i.Signal,this.onPlay=new i.Signal,this.onPause=new i.Signal,this.onResume=new i.Signal,this.onLoop=new i.Signal,this.onStop=new i.Signal,this.onMute=new i.Signal,this.onMarkerComplete=new i.Signal,this.onFadeComplete=new i.Signal,this._volume=s,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},i.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop(),this._markedToDelete&&(this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode),this._removeFromSoundManager?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()))},update:function(){this.game.cache.checkSoundKey(this.key)?(this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))):this.destroy()},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){this.isPlaying&&!this.paused&&e!==this.volume&&(void 0===t&&(t=1e3),void 0!==e?(this.fadeTween=this.game.add.tween(this).to({volume:e},t,i.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)):console.warn("Phaser.Sound.fadeTo: No Volume Specified."))},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._globalVolume=t,this._sound.volume=this._globalVolume*this._volume)},destroy:function(t){void 0===t&&(t=!0),this._markedToDelete=!0,this._removeFromSoundManager=t,this.stop(),t?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())}},i.Sound.prototype.constructor=i.Sound,Object.defineProperty(i.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(i.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(i.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(i.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted?this._muteVolume=t:(this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=this._globalVolume*t))}}),i.SoundManager=function(t){this.game=t,this.onSoundDecode=new i.Signal,this.onVolumeChange=new i.Signal,this.onMute=new i.Signal,this.onUnMute=new i.Signal,this.onTouchUnlock=new i.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new i.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},i.SoundManager.prototype={boot:function(){var t=this.game.device,e=window.PhaserGlobal;if(t.iOS&&!1===t.webAudio&&(this.channels=1),e){if(!0===e.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===e.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(e&&e.audioContext)this.context=e.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||t.needsTouchUnlock()&&this.setTouchLock(),this.usingWebAudio&&t.chrome&&t.chromeVersion<=65&&console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. ')},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0)},setTouchUnlock:function(){this.touchLocked=!1,this._unlockSource=null,this.onTouchUnlock.dispatch()},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.setTouchUnlock();else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0),"suspended"===this._unlockSource.context.state&&this._unlockSource.context.resume()}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,s=this._parentBounds.height,n=this.getParentBounds(this._parentBounds),r=n.width!==e||n.height!==s,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,n),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottlee;return(h=h?s:!s)?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},i.ScaleManager.prototype.constructor=i.ScaleManager,Object.defineProperty(i.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(i.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(i.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(i.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),i.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.lineWidth=1,this.renderShadow=!0,this.currentColor=null,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1,this.isDisabled=!1,this._line=null,this._rect=null},i.Utils.Debug.prototype={boot:function(){this.game.renderType===i.CANVAS?this.context=this.game.context:(this.bmd=new i.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=i.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d")),this._line=new i.Line,this._rect=new i.Rectangle},resize:function(){this.bmd.resize(this.game.width,this.game.height),this.canvas.width=this.game.width,this.canvas.height=this.game.height},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e0)for(var e=0;e=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new i.Rectangle,layoutBounds:new i.Rectangle,documentBounds:new i.Rectangle},i.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},s=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(i.DOM,"scrollX",{get:e}),Object.defineProperty(i.DOM,"scrollY",{get:s}),Object.defineProperty(i.DOM.visualBounds,"x",{get:e}),Object.defineProperty(i.DOM.visualBounds,"y",{get:s}),Object.defineProperty(i.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(i.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var n=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(i.DOM.visualBounds,"width",{get:n}),Object.defineProperty(i.DOM.visualBounds,"height",{get:r}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:n}),Object.defineProperty(i.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(i.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(i.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(i.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(i.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(i.ArraySet.prototype,"next",{get:function(){return this.position=s||0===i)){null==i&&(i=1);for(var n=s-i,r=e;r0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=(t=i.ArrayUtils.transposeMatrix(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=i.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var s=0;s>>0:(t<<24|e<<16|s<<8|n)>>>0},unpackPixel:function(t,e,s,n){return void 0!==e&&null!==e||(e=i.Color.createColor()),void 0!==s&&null!==s||(s=!1),void 0!==n&&null!==n||(n=!1),i.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",s&&i.Color.RGBtoHSL(e.r,e.g,e.b,e),n&&i.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=i.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},hexToRGBArray:function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},RGBArrayToHex:function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},RGBtoHSL:function(t,e,s,n){n||(n=i.Color.createColor(t,e,s,1)),t/=255,e/=255,s/=255;var r=Math.min(t,e,s),o=Math.max(t,e,s);if(n.h=0,n.s=0,n.l=(o+r)/2,o!==r){var a=o-r;n.s=n.l>.5?a/(2-o-r):a/(o+r),o===t?n.h=(e-s)/a+(e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,s,n,r,o,a,h){var l={r:t||0,g:e||0,b:s||0,a:n||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return i.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toFixed()+","+t.g.toFixed()+","+t.b.toFixed()+","+t.a.toString()+")",t.color=i.Color.getColor(t.r,t.g,t.b),t.color32=i.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,s,n,r){return void 0===n&&(n=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+s).toString(16).slice(1):"0x"+i.Color.componentToHex(n)+i.Color.componentToHex(t)+i.Color.componentToHex(e)+i.Color.componentToHex(s)},hexToRGB:function(t){var e=i.Color.hexToColor(t);if(e)return i.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var s=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(s){var n=parseInt(s[1],16),r=parseInt(s[2],16),o=parseInt(s[3],16);e?(e.r=n,e.g=r,e.b=o):e=i.Color.createColor(n,r,o)}return e},webToColor:function(t,e){e||(e=i.Color.createColor());var s=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return s&&(e.r=~~Number(s[1]),e.g=~~Number(s[2]),e.b=~~Number(s[3]),e.a=void 0!==s[4]?Number(s[4]):1,i.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=i.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?i.Color.webToColor(t,e):(e.a=1,i.Color.hexToColor(t,e));if("number"==typeof t){var s=i.Color.getRGB(t);return e.r=s.r,e.g=s.g,e.b=s.b,e.a=s.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSVtoRGB(n/359,t,e));return s},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSLtoRGB(n/359,t,e));return s},interpolateColor:function(t,e,s,n,r,o){void 0===r&&(r=255),void 0===o&&(o=0);var a=i.Color.getRGB(t),h=i.Color.getRGB(e);if(0===o)var l=(h.red-a.red)*n/s+a.red,c=(h.green-a.green)*n/s+a.green,u=(h.blue-a.blue)*n/s+a.blue;if(1===o){var d,p=i.Color.RGBtoHSV(a.r,a.g,a.b),f=i.Color.RGBtoHSV(h.r,h.g,h.b),g=f.h-p.h;if(p.h>f.h){var m=f.h;f.h=p.h,p.h=m,g=-g,n=s-n}g>.5&&(p.h=p.h+1,d=((f.h-p.h)*n/s+p.h)%1),g<=.5&&(d=(f.h-p.h)*n/s+p.h);var y=(f.s-p.s)*n/s+p.s,v=(f.v-p.v)*n/s+p.v,x=i.Color.HSVtoRGB(d,y,v,x),l=x.r,c=x.g,u=x.b}return i.Color.getColor32(r,l,c,u)},interpolateColorWithRGB:function(t,e,s,n,r,o){var a=i.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(s-a.green)*o/r+a.green,c=(n-a.blue)*o/r+a.blue;return i.Color.getColor(h,l,c)},interpolateRGB:function(t,e,s,n,r,o,a,h){var l=(n-t)*h/a+t,c=(r-e)*h/a+e,u=(o-s)*h/a+s;return i.Color.getColor(l,c,u)},linear:function(t,e,i){return this.interpolateColor(t,e,1,i)},linearInterpolation:function(t,e){var s=i.Math.linear(0,t.length-1,e),n=t[Math.floor(s)],r=t[Math.ceil(s)];return this.linear(n,r,s%1)},getRandomColor:function(t,e,s){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===s&&(s=255),e>255||t>e)return i.Color.getColor(255,255,255);var n=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return i.Color.getColor32(s,n,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=i.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return i.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return i.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return i.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?i.Color.blendLinearBurn(t,2*e):i.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?i.Color.blendColorBurn(t,2*e):i.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?i.Color.blendDarken(t,2*e):i.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return i.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return i.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},i.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},i.Physics.ARCADE=0,i.Physics.P2JS=1,i.Physics.NINJA=2,i.Physics.BOX2D=3,i.Physics.CHIPMUNK=4,i.Physics.MATTERJS=5,i.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!i.Physics.hasOwnProperty("Arcade")||(this.arcade=new i.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&i.Physics.hasOwnProperty("Ninja")&&(this.ninja=new i.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&i.Physics.hasOwnProperty("P2")&&(this.p2=new i.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&i.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new i.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&i.Physics.hasOwnProperty("Matter")&&(this.matter=new i.Physics.Matter(this.game,this.config))},startSystem:function(t){t===i.Physics.ARCADE?this.arcade=new i.Physics.Arcade(this.game):t===i.Physics.P2JS?null===this.p2?this.p2=new i.Physics.P2(this.game,this.config):this.p2.reset():t===i.Physics.NINJA?this.ninja=new i.Physics.Ninja(this.game):t===i.Physics.BOX2D?null===this.box2d?this.box2d=new i.Physics.Box2D(this.game,this.config):this.box2d.reset():t===i.Physics.MATTERJS&&(null===this.matter?this.matter=new i.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,s){void 0===e&&(e=i.Physics.ARCADE),void 0===s&&(s=!1),e===i.Physics.ARCADE?this.arcade.enable(t):e===i.Physics.P2JS&&this.p2?this.p2.enable(t,s):e===i.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===i.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===i.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},i.Physics.prototype.constructor=i.Physics,i.Physics.Arcade=function(t){this.game=t,this.gravity=new i.Point,this.bounds=new i.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=i.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new i.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._total=0,this.setBoundsToWorld()},i.Physics.Arcade.prototype.constructor=i.Physics.Arcade,i.Physics.Arcade.SORT_NONE=0,i.Physics.Arcade.LEFT_RIGHT=1,i.Physics.Arcade.RIGHT_LEFT=2,i.Physics.Arcade.TOP_BOTTOM=3,i.Physics.Arcade.BOTTOM_TOP=4,i.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof i.Group?this.enable(t[s].children,e):(this.enableBody(t[s]),e&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],!0));else t instanceof i.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.Arcade.Body(t),t.parent&&t.parent instanceof i.Group&&t.parent.addToHash(t))},updateMotion:function(t){if(t.allowRotation){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed}t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&e.allowDrag&&(i-(n*=this.game.time.physicsElapsed)>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!0),this._total>0},collide:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!1),this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===i.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===i.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===i.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===i.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideObjects:function(t,e,i,s,n,r){if(!Array.isArray(t)&&Array.isArray(e))for(o=0;oa.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(t.body.bottoma.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,s,n,r,o)}}else{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(e);for(var c=this.quadTree.retrieve(t),h=0;hc.right)continue;if(c.x>a.right)break}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(a.bottomc.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,s,n,r)}}}}},collideGroupVsGroup:function(t,e,s,n,r,o){if(0!==t.length&&0!==e.length)for(var a=0;aa.bottom)&&(h.xa.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var s=i.Math.clamp(t.center.x,e.left,e.right),n=i.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-s)*(t.center.x-s)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},separateCircle:function(t,e,s){this.getOverlapX(t,e),this.getOverlapY(t,e);var n=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,n),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.center.x:e.center.x,y:t.isCircle?t.center.y:e.center.y,radius:t.isCircle?t.halfWidth:e.halfWidth};l.yh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.xh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.halfWidth+e.halfWidth-i.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(s||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.yMath.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x)>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0):t.deltaX()n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y)>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0):t.deltaY()n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,s,n,r,o){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(s);for(var a=new i.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c0&&(s=this.distanceBetween(t,e)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.setToPolar(n,e),n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},velocityFromAngle:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e,!0)},velocityFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerationFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(o,s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i,s){void 0===i&&(i=!1);var n,r;return s?(n=t.centerX-e.centerX,r=t.centerY-e.centerY):i?(n=t.world.x-e.world.x,r=t.world.y-e.world.y):(n=t.x-e.x,r=t.y-e.y),Math.sqrt(n*n+r*r)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},closest:function(t,e,i,s){for(var n=1/0,r=null,o=0,a=e.length;on&&(r=h,n=l)}return r},angleBetween:function(t,e,s){return void 0===s&&(s=!1),s?i.Point.angle(e.world,t.world):i.Point.angle(e,t)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},i.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=i.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new i.Point,this.position=new i.Point(t.x,t.y),this.prev=new i.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new i.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new i.Point,this.newVelocity=new i.Point,this.deltaMax=new i.Point,this.acceleration=new i.Point,this.allowDrag=!0,this.drag=new i.Point,this.allowGravity=!0,this.gravity=new i.Point,this.bounce=new i.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new i.Point(1e4,1e4),this.friction=new i.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=i.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.tilePadding=new i.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new i.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},i.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter())},updateCenter:function(){this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,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=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.none=!0,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.overlapR=0,this.overlapX=0,this.overlapY=0,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.updateCenter(),this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),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,this.updateCenter(),this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=this.velocity.atan()),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=i.LEFT:this.deltaX()>0&&(this.facing=i.RIGHT),this.deltaY()<0?this.facing=i.UP:this.deltaY()>0&&(this.facing=i.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.updateCenter(),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0,this.blocked.none=!1),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0,this.blocked.none=!1),!this.blocked.none},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.setToPolar(s,e),this.isMoving=!0,!0},moveTo:function(t,e,s){var n=e/(t/1e3);if(0===n)return!1;var r;return void 0===s?(r=this.angle,s=this.game.math.radToDeg(r)):r=this.game.math.degToRad(s),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new i.Line,this.moveEnd=new i.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===s||180===s?this.velocity.set(Math.cos(r)*n,0):90===s||270===s?this.velocity.set(0,Math.sin(r)*n):this.velocity.setToPolar(r,n),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,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(i,s),this.updateCenter(),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,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(e,i),this.updateCenter()):this.isCircle=!1},reset:function(t,e){this.stop(),this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this.updateBounds(),this.updateCenter()},stop:function(){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?i.Circle.contains(this,t,e):i.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},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},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof i.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(i.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),i.Physics.Arcade.Body.render=function(t,e,i,s,n){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,t.lineWidth=n||1,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.halfWidth,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},i.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},i.Physics.Arcade.Body.prototype.constructor=i.Physics.Arcade.Body,i.Physics.Arcade.TilemapCollision=function(){},i.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x-e.getTileOffsetX(),t.body.position.y-t.body.tilePadding.y-e.getTileOffsetY(),t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;ae.deltaAbsY()?l=-1:e.deltaAbsX()0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.getTileOffsetY();return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?(t.blocked.left=!0,t.blocked.none=!1):e>0&&(t.blocked.right=!0,t.blocked.none=!1),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?(t.blocked.up=!0,t.blocked.none=!1):e>0&&(t.blocked.down=!0,t.blocked.none=!1),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},i.Utils.mixinPrototype(i.Physics.Arcade.prototype,i.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,i.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new i.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new i.Signal,this.onBodyRemoved=new i.Signal,this.onSpringAdded=new i.Signal,this.onSpringRemoved=new i.Signal,this.onConstraintAdded=new i.Signal,this.onConstraintRemoved=new i.Signal,this.onContactMaterialAdded=new i.Signal,this.onContactMaterialRemoved=new i.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},i.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,s){void 0===e&&(e=!1),void 0===s&&(s=!0);var n=1;if(Array.isArray(t))for(n=t.length;n--;)t[n]instanceof i.Group?this.enable(t[n].children,e,s):(this.enableBody(t[n],e),s&&t[n].hasOwnProperty("children")&&t[n].children.length>0&&this.enable(t[n],e,!0));else t instanceof i.Group?this.enable(t.children,e,s):(this.enableBody(t,e),s&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);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.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.DistanceConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,s,n){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.GearConstraint(this,t,e,s,n));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),s=this.getBody(s),t&&s)return this.addConstraint(new i.Physics.P2.RevoluteConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,s,n,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.LockConstraint(this,t,e,s,n,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,s,n,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.PrismaticConstraint(this,t,e,s,n,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var s=new i.Physics.P2.Material(t);return this.materials.push(s),void 0!==e&&e.setMaterial(s),s},createContactMaterial:function(t,e,s){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var n=new i.Physics.P2.ContactMaterial(t,e,s);return this.addContactMaterial(n)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof i.Physics.P2.Body?t.data:t.body&&t.body.type===i.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,s,n){void 0===e&&(e=this.world.bodies),void 0===s&&(s=5),void 0===n&&(n=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof i.Physics.P2.Body&&(!n||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!n||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof i.Sprite&&e[a].hasOwnProperty("body")&&(!n||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,s)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var s=new i.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(s),t&&this.setCollisionGroup(t,s),s},setCollisionGroup:function(t,e){if(t instanceof i.Group)for(var s=0;s-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides?n+=u.width:((p=this.createBody(r,o,0,!1)).addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0)}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(i.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(i.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(i.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(i.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(i.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(i.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(i.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(i.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(i.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),i.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},i.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionGroup=t})},setMask:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionMask=t})},setSensor:function(t,e){this.getFixtures(e).forEach(function(e){e.sensor=t})},setMaterial:function(t,e){this.getFixtures(e).forEach(function(e){e.material=t})},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},i.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.PointProxy.prototype.constructor=i.Physics.P2.PointProxy,Object.defineProperty(i.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),i.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.InversePointProxy.prototype.constructor=i.Physics.P2.InversePointProxy,Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),i.Physics.P2.Body=function(t,e,s,n,r){e=e||null,s=s||0,n=n||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=i.Physics.P2JS,this.offset=new i.Point,this.data=new p2.Body({position:[this.world.pxmi(s),this.world.pxmi(n)],mass:r}),this.data.parent=this,this.velocity=new i.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new i.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new i.Point,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},i.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(r=0;r-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var n=this.getCollisionMask();if(void 0===i)for(var r=this.data.shapes.length-1;r>=0;r--)this.data.shapes[r].collisionMask=n;else i.collisionMask=n},collides:function(t,e,i,s){if(Array.isArray(t))for(r=0;r=0;r--)this.data.shapes[r].collisionMask=n;else s.collisionMask=n},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},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(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;np;n=0<=p?++d:--d)l=e.vertices[n],p2.vec2.rotate(u,l,t),c.push([(u[0]+a[0])*this.ppu,-(u[1]+a[1])*this.ppu]);this.drawConvex(h,c,e.triangles,16711680,i,r,this.settings.debugPolygons,[a[0]*this.ppu,-a[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)p=(c=e[l])[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return 2===(e=t.toString(16)).length?e:e+"0"}}),i.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1);var c={restLength:s=t.pxm(s),stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},i.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),i.Physics.P2.Material.prototype.constructor=i.Physics.P2.Material,i.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},i.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),i.Physics.P2.ContactMaterial.prototype.constructor=i.Physics.P2.ContactMaterial,i.Physics.P2.CollisionGroup=function(t){this.mask=t},i.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t;var a={distance:s=t.pxm(s),localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},i.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),i.Physics.P2.DistanceConstraint.prototype.constructor=i.Physics.P2.DistanceConstraint,i.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},i.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),i.Physics.P2.GearConstraint.prototype.constructor=i.Physics.P2.GearConstraint,i.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t;var o={localOffsetB:s=[t.pxm(s[0]),t.pxm(s[1])],localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},i.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),i.Physics.P2.LockConstraint.prototype.constructor=i.Physics.P2.LockConstraint,i.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t;var h={localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},i.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),i.Physics.P2.PrismaticConstraint.prototype.constructor=i.Physics.P2.PrismaticConstraint,i.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},i.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),i.Physics.P2.RevoluteConstraint.prototype.constructor=i.Physics.P2.RevoluteConstraint,i.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},i.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&tthis.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},i.Tile.prototype.constructor=i.Tile,Object.defineProperty(i.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(i.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(i.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(i.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(i.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(i.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),i.Tilemap=function(t,e,s,n,r,o){this.game=t,this.key=e;var a=i.TilemapParser.parse(this.game,e,s,n,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},i.Tilemap.CSV=0,i.Tilemap.TILED_JSON=1,i.Tilemap.NORTH=0,i.Tilemap.EAST=1,i.Tilemap.SOUTH=2,i.Tilemap.WEST=3,i.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,s,n,r,o,a){if(void 0===t)return null;void 0===s&&(s=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===s&&(s=32),0===n&&(n=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof i.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===i.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),console.log("Tilesets: ",this.tilesets),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new i.Tileset(t,a,s,n,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y1)for(u=0;uthis.layers.length)return console.warn('Tilemap.createLayer: Invalid layer ID given: "'+t+'"'),void console.log("Layers: ",this.layers);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===s||s<=0?s=Math.min(this.game.height,this.layers[r].heightInPixels):s>this.game.height&&(s=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",s),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=n.add(new i.TilemapLayer(this.game,this,r,e,s));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,s,n,r,o){void 0===o&&(o=this.game.world);{if(null===this.getLayerIndex(t)){for(var a,h={name:t,x:0,y:0,width:e,height:s,widthInPixels:e*n,heightInPixels:s*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;cthis.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height),(l=new i.TilemapLayer(this.game,this,this.layers.length-1,d,p)).name=t,o.add(l)}console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t)}},getIndex:function(t,e){for(var i=0;ie)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n-1&&this.collideIndexes.splice(n,1)}for(var r=0;r0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e-1},removeTile:function(t,e,s){if(s=this.getLayer(s),t>=0&&t=0&&e=0&&e=0&&s-1?this.layers[n].data[s][e].setCollision(!0,!0,!0,!0):this.layers[n].data[s][e].resetCollision(),this.layers[n].dirty=!0,this.calculateFaces(n),this.layers[n].data[s][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(r=this.layers[s].height-1;r>=0;r--)for(o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r=0&&t=0&&ethis.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},i.Tilemap.prototype.constructor=i.Tilemap,Object.defineProperty(i.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),i.TilemapLayer=function(t,e,s,n,r){n|=0,r|=0,i.Sprite.call(this,t,0,0),this.map=e,this.index=s,this.layer=e.layers[s],this.canvas=i.CanvasPool.create(this,n,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas,null,this.game.resolution))),this.type=i.TILEMAPLAYER,this.physicsType=i.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!0,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this.tileOffset=new i.Point(this.layer.offsetX||0,this.layer.offsetY||0),this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=i.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},i.TilemapLayer.prototype=Object.create(i.Sprite.prototype),i.TilemapLayer.prototype.constructor=i.TilemapLayer,i.TilemapLayer.prototype.preUpdateCore=i.Component.Core.preUpdate,i.TilemapLayer.sharedCopyCanvas=null,i.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=i.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},i.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},i.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y},i.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.TilemapLayer.prototype.destroy=function(){i.CanvasPool.remove(this),i.Component.Destroy.prototype.destroy.call(this)},i.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},i.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},i.TilemapLayer.prototype.getTileOffsetX=function(){return this.tileOffset.x||(this.fixedToCamera?0:this.position.x)},i.TilemapLayer.prototype.getTileOffsetY=function(){return this.tileOffset.y||(this.fixedToCamera?0:this.position.y)},i.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},i.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},i.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},i.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},i.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},i.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},i.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},i.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a=0;m++,v--,f+=c){m>=h&&(m-=h);var _=this.layer.data[m];for(g=b,y=n-i,p=x;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var w=_[g];if(w&&!(w.index<0)){var T=w.index,P=u[T];void 0===P&&(P=this.resolveTileset(T)),w.alpha===d||this.debug||(o.globalAlpha=w.alpha,d=w.alpha),P?w.rotation||w.flipped?(o.save(),o.translate(p+w.centerX,f+w.centerY),o.rotate(w.rotation),w.flipped&&o.scale(-1,1),P.draw(o,-w.centerX,-w.centerY,T),o.restore()):P.draw(o,p,f,T):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),w.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},i.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},i.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},i.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)=0;s++,r--,e+=f){s>=d&&(s-=d);var T=this.layer.data[s];for(i=_,n=m-g,t=x;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var P=T[i];!P||P.index<0||!P.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),P.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),P.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),P.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),P.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(i.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),i.TilemapParser={INSERT_NULL:!1,parse:function(t,e,s,n,r,o){if(void 0===s&&(s=32),void 0===n&&(n=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(s,n,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===i.Tilemap.CSV)return this.parseCSV(e,a.data,s,n);if(!a.format||a.format===i.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,s,n){for(var r=this.getEmptyData(),o=[],a=(e=e.trim()).split("\n"),h=a.length,l=0,c=0;c>>0;r.data=h,delete r.encoding}else if(r.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+r.name+"'");continue}k={name:r.name,x:r.x,y:r.y,width:r.width,height:r.height,widthInPixels:r.width*t.tilewidth,heightInPixels:r.height*t.tileheight,alpha:r.opacity,offsetX:r.offsetx,offsetY:r.offsety,visible:r.visible,properties:{},indexes:[],callbacks:[],bodies:[]};r.properties&&(k.properties=r.properties);for(var c,u,d,p=0,f=[],g=[],m=0,a=r.data.length;m536870912)switch(A>2147483648&&(A-=2147483648,d+=4),A>1073741824&&(A-=1073741824,d+=2),A>536870912&&(A-=536870912,d+=1),d){case 5:c=Math.PI/2;break;case 6:c=Math.PI;break;case 3:c=3*Math.PI/2;break;case 4:c=0,u=!0;break;case 7:c=Math.PI/2,u=!0;break;case 2:c=Math.PI,u=!0;break;case 1:c=3*Math.PI/2,u=!0}A>0?((F=new i.Tile(k,A,p,g.length,t.tilewidth,t.tileheight)).rotation=c,F.flipped=u,0!==d&&(F.flippedVal=d),f.push(F)):i.TilemapParser.INSERT_NULL?f.push(null):f.push(new i.Tile(k,-1,p,g.length,t.tilewidth,t.tileheight)),++p===r.width&&(g.push(f),p=0,f=[])}k.data=g,s.push(k)}e.layers=s;for(var y=[],n=0;n=0&&n+1=this.firstgid&&t=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(t=0;t=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._total>0&&this._counter>=this._total&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},i.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1),void 0===r&&(r=null);var o,a=0,h=t,l=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);athis.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},i.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),this.resetParticle(n,o,a),!0},i.Particles.Arcade.Emitter.prototype.getNextParticle=function(){for(var t=this.length;t--;){var e=this.next();if(!e.exists)return e}return null},i.Particles.Arcade.Emitter.prototype.resetParticle=function(t,e,i){var s=this.game.rnd;t.reset(e,i),t.angle=0,t.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(t):this.particleSendToBack&&this.sendToBack(t),this.autoScale?t.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?t.scale.set(s.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y?t.scale.set(s.realInRange(this._minParticleScale.x,this._maxParticleScale.x),s.realInRange(this._minParticleScale.y,this._maxParticleScale.y)):t.scale.set(this._minParticleScale.x,this._minParticleScale.y),this.autoAlpha?t.setAlphaData(this.alphaData):t.alpha=s.realInRange(this.minParticleAlpha,this.maxParticleAlpha),t.blendMode=this.blendMode;var n=t.body;n.updateBounds(),n.bounce.copyFrom(this.bounce),n.drag.copyFrom(this.particleDrag),null!=this.minAngle&&null!=this.maxAngle?this.game.physics.arcade.velocityFromAngle(this.minAngle===this.maxAngle?this.minAngle:s.between(this.minAngle,this.maxAngle),this.minSpeed===this.maxSpeed?this.minSpeed:s.between(this.minSpeed,this.maxSpeed),n.velocity):(n.velocity.x=s.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),n.velocity.y=s.between(this.minParticleSpeed.y,this.maxParticleSpeed.y)),n.angularVelocity=s.between(this.minRotation,this.maxRotation),n.gravity.copyFrom(this.gravity),n.angularDrag=this.angularDrag,t.onEmit()},i.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),i.Group.prototype.destroy.call(this,!0,!1)},i.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},i.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},i.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},i.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},i.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,s,n,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=0),void 0===n&&(n=i.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,s>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},s,n);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},i.Particles.Arcade.Emitter.prototype.setScale=function(t,e,s,n,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=1),void 0===n&&(n=1),void 0===r&&(r=0),void 0===o&&(o=i.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,s),this._maxParticleScale.set(e,n),this.autoScale=!1,r>0&&(t!==e||s!==n)){var h={x:t,y:s},l=this.game.make.tween(h).to({x:e,y:n},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},i.Particles.Arcade.Emitter.prototype.setAngle=function(t,e,i,s){return this.minAngle=t,this.maxAngle=e,null!=i&&(this.minSpeed=i),null!=s&&(this.maxSpeed=s),this},i.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"gravity",{get:function(){return this._gravity},set:function(t){"number"==typeof t?this._gravity.y=t:this._gravity=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"id",{get:function(){return this._id}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"output",{get:function(){return 1e3*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"lifespanOutput",{get:function(){return(0===this.lifespan?1/0:this.lifespan)*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"remainder",{get:function(){return this.maxParticles-this.lifespanOutput}}),i.Weapon=function(t,e){i.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new i.Rectangle(0,0,1,1),this.fireAngle=i.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new i.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=i.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=i.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new i.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new i.Signal,this.onKill=new i.Signal,this.onFireLimit=new i.Signal,this.trackedSprite=null,this.trackedPointer=null,this.multiFire=!1,this._hasFired=!1,this.trackRotation=!1,this.trackOffset=new i.Point,this._nextFire=0,this._tempNextFire=0,this._rotatedPoint=new i.Point},i.Weapon.prototype=Object.create(i.Plugin.prototype),i.Weapon.prototype.constructor=i.Weapon,i.Weapon.KILL_NEVER=0,i.Weapon.KILL_LIFESPAN=1,i.Weapon.KILL_DISTANCE=2,i.Weapon.KILL_WEAPON_BOUNDS=3,i.Weapon.KILL_CAMERA_BOUNDS=4,i.Weapon.KILL_WORLD_BOUNDS=5,i.Weapon.KILL_STATIC_BOUNDS=6,i.Weapon.prototype.createBullets=function(t,e,s,n){return void 0===t&&(t=1),void 0===n&&(n=this.game.world),this.bullets&&!this.bullets.game&&(this.bullets=null),this.bullets||(this.bullets=this.game.add.physicsGroup(i.Physics.ARCADE,n),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,s),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=s),this},i.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},i.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},i.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},i.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},i.Weapon.prototype.update=function(){this._bulletKillType===i.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},i.Weapon.prototype.postRender=function(){this.multiFire&&this._hasFired&&(this._hasFired=!1,this._nextFire=this._tempNextFire)},i.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},i.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},i.Weapon.prototype.fireMany=function(t,e){this.multiFire=!0;var i=[],s=this;return e||this.trackedSprite||this.trackedPointer?t.forEach(function(t){i.push(s.fire(e,null,null,t.x,t.y))}):t.forEach(function(t){i.push(s.fire(t))}),i},i.Weapon.prototype.fireOffset=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.fire(null,null,null,t,e)},i.Weapon.prototype.fire=function(t,e,s,n,r){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game.time.now0&&this.shots===this.fireLimit)return null;var o=this.bulletSpeed;0!==this.bulletSpeedVariance&&(o+=i.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.worldRotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(o+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y)),void 0!==n&&(this.fireFrom.x+=n),void 0!==r&&(this.fireFrom.y+=r);var a=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,h=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,l=this.trackRotation?this.trackedSprite.angle:this.fireAngle;null!==e&&null!==s&&(l=this.game.math.radToDeg(Math.atan2(s-h,e-a))),0!==this.bulletAngleVariance&&(l+=i.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var c=0,u=0;0===l||180===l?c=Math.cos(this.game.math.degToRad(l))*o:90===l||270===l?u=Math.sin(this.game.math.degToRad(l))*o:(c=Math.cos(this.game.math.degToRad(l))*o,u=Math.sin(this.game.math.degToRad(l))*o);var d=null;if(this.autoExpandBulletsGroup?(d=this.bullets.getFirstExists(!1,!0,a,h,this.bulletKey,this.bulletFrame)).data.bulletManager=this:d=this.bullets.getFirstExists(!1),d){if(d.reset(a,h),d.data.fromX=a,d.data.fromY=h,d.data.killType=this.bulletKillType,d.data.killDistance=this.bulletKillDistance,d.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===i.Weapon.KILL_LIFESPAN&&(d.lifespan=this.bulletLifespan),d.angle=l+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===d.animations.getAnimation(this.bulletAnimation)){var p=this.anims[this.bulletAnimation];d.animations.add(p.name,p.frames,p.frameRate,p.loop,p.useNumericIndex)}d.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(d.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(d.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);d.data.bodyDirty&&(this._data.customBody&&d.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),d.body.collideWorldBounds=this.bulletCollideWorldBounds,d.data.bodyDirty=!1),d.body.velocity.set(c,u),d.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y);var f=0;if(0!==this.bulletSpeedVariance){var g=this.fireRate;(g+=i.Math.between(-this.fireRateVariance,this.fireRateVariance))<0&&(g=0),f=this.game.time.now+g}else f=this.game.time.now+this.fireRate;this.multiFire?this._hasFired||(this._hasFired=!0,this._tempNextFire=f,this.shots++):(this._nextFire=f,this.shots++),this.onFire.dispatch(d,this,o),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return d},i.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},i.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},i.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},i.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},i.Weapon.prototype.setBulletFrames=function(t,e,s,n){return void 0===s&&(s=!0),void 0===n&&(n=!1),this.bulletFrames=i.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=s,this.bulletFrameRandom=n,this},i.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},i.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(i.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets&&(this.bullets.classType=this._bulletClass)}}),Object.defineProperty(i.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case i.Weapon.KILL_STATIC_BOUNDS:case i.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case i.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case i.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(i.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(i.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(i.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),i.Bullet=function(t,e,s,n,r){i.Sprite.call(this,t,e,s,n,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},i.Bullet.prototype=Object.create(i.Sprite.prototype),i.Bullet.prototype.constructor=i.Bullet,i.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},i.Bullet.prototype.update=function(){this.exists&&(this.data.killType>i.Weapon.KILL_LIFESPAN&&(this.data.killType===i.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=this.body.velocity.atan()),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},i.Video=function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=i.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new i.Signal,this.onChangeSource=new i.Signal,this.onComplete=new i.Signal,this.onAccess=new i.Signal,this.onError=new i.Signal,this.onTimeout=new i.Signal,this.onTouchUnlock=new i.Signal,this.playWhenUnlocked=!0,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._pendingChangeSource=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var n=this.game.cache.getVideo(e);n.isBlob?this.createVideoFromBlob(n.data):this.video=n.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else s&&this.createVideoFromURL(s,!1);this.video&&!s?(this.baseTexture=new PIXI.BaseTexture(this.video,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(i.Cache.DEFAULT.baseTexture.source,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new i.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,i.BitmapData&&(this.snapshot=new i.BitmapData(this.game,"",this.width,this.height)),this.game.device.needsTouchUnlock()?this.setTouchLock():n&&(n.locked=!1)},i.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return this._pendingChangeSource?this:(void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this)},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming)},setTouchLock:function(){this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.playWhenUnlocked&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return this.onTouchUnlock.dispatch(this),!0},grab:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null!==this.snapshot)return t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot;console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable")},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(i.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(i.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(i.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(i.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(i.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(i.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(i.Video.prototype,"playing",{get:function(){return!!this.video&&!(this.video.paused&&this.video.ended)}}),i.Video.prototype.constructor=i.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=i.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=i.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new i.Matrix),PIXI.TextureSilentFail=!0,PIXI.canUseNewCanvasBlendModes=function(){return i.Device.canUseMultiply},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=i),exports.Phaser=i):"undefined"!=typeof define&&define.amd?define("Phaser",e.Phaser=i):e.Phaser=i,i}.call(this); +//# sourceMappingURL=phaser.map \ No newline at end of file diff --git a/Iteration Sequence 1.2/sources.txt b/Iteration Sequence 1.2/sources.txt new file mode 100644 index 000000000..7e9bf5001 --- /dev/null +++ b/Iteration Sequence 1.2/sources.txt @@ -0,0 +1,7 @@ +https://www.123rf.com/photo_62999359_stock-vector-game-background-flat-style-2d-game-application.html +http://kenney.nl/assets +https://phaser.io/examples/v2/sprites/move-a-sprite + +http://www.emanueleferonato.com/2014/08/28/phaser-tutorial-understanding-phaser-states/ + +https://s3.envato.com/files/98082290/game-assets-for-mobile-games-flappy-dragon-attack-game-character-sprite-sheets-background.png diff --git a/Iteration Sequence 1/assets/adventurer_tilesheet.png b/Iteration Sequence 1/assets/adventurer_tilesheet.png new file mode 100644 index 000000000..6503a0d7e Binary files /dev/null and b/Iteration Sequence 1/assets/adventurer_tilesheet.png differ diff --git a/Iteration Sequence 1/assets/sheet.png b/Iteration Sequence 1/assets/sheet.png new file mode 100644 index 000000000..9932350f5 Binary files /dev/null and b/Iteration Sequence 1/assets/sheet.png differ diff --git a/Iteration Sequence 1/assets/stat.png b/Iteration Sequence 1/assets/stat.png new file mode 100644 index 000000000..e71ad26e7 Binary files /dev/null and b/Iteration Sequence 1/assets/stat.png differ diff --git a/Iteration Sequence 1/assets/temp_bg.jpg b/Iteration Sequence 1/assets/temp_bg.jpg new file mode 100644 index 000000000..b8b9f35af Binary files /dev/null and b/Iteration Sequence 1/assets/temp_bg.jpg differ diff --git a/Iteration Sequence 1/assets/test.json b/Iteration Sequence 1/assets/test.json new file mode 100644 index 000000000..428eed420 --- /dev/null +++ b/Iteration Sequence 1/assets/test.json @@ -0,0 +1,100 @@ +{"frames": [ + +{ + "filename": "run00", + "frame": {"x":34,"y":128,"w":56,"h":60}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":2,"w":56,"h":60}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run01", + "frame": {"x":54,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run02", + "frame": {"x":54,"y":58,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run03", + "frame": {"x":0,"y":192,"w":34,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":11,"y":0,"w":34,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run04", + "frame": {"x":0,"y":64,"w":54,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":1,"y":0,"w":54,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run05", + "frame": {"x":196,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run06", + "frame": {"x":0,"y":0,"w":54,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":1,"y":0,"w":54,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run07", + "frame": {"x":140,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run08", + "frame": {"x":34,"y":188,"w":50,"h":60}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":3,"y":2,"w":50,"h":60}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run09", + "frame": {"x":0,"y":128,"w":34,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":11,"y":0,"w":34,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run10", + "frame": {"x":84,"y":188,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}], +"meta": { + "app": "http://www.texturepacker.com", + "version": "1.0", + "image": "running_bot.png", + "format": "RGBA8888", + "size": {"w":252,"h":256}, + "scale": "0.2", + "smartupdate": "$TexturePacker:SmartUpdate:fb56f261b1eb04e3215824426595f64c$" +} +} diff --git a/Iteration Sequence 1/index.html b/Iteration Sequence 1/index.html new file mode 100644 index 000000000..54a4b8160 --- /dev/null +++ b/Iteration Sequence 1/index.html @@ -0,0 +1,129 @@ + + + + + Iteration Sequence 1 + + + + + +
+
+

Iteration Sequence 1

+
    +
  • Originality: + What is original about your game? +
  • +
      +
    • + The final game will be similar to super mario brothers but with additional powers from the pre-game phase. +
    • +
    +
  • Technical Merit: + What is interesting about your game technology? +
  • +
      +
    • + Players will be able to attempt trials for additional abilities. +
    • +
    +
  • Prototype Postmortem: + What did you learn from this prototype? What was the easiest or hardest part of making it? +
  • +
      +
    • + Currently in the process of learning different states in phaser. +
    • +
    +
  • Prototype Assets: + Did you make your prototype assets from scratch? Did you borrow them? Cite your sources here. + + + +
  • Prototype Closest Other Game: + Which other game most closely resembles your game? If you are borrowing code from a Phaser Example, you must say so here. If you borrow code from elsewhere, you must say so here. +
  • +
      +
    • Concept started from Super Mario Brothers but the end product should be completely different.
    • +
    +
  • High Concept: + A one-sentence summary of your game. +
  • +
      +
    • Make your character stronger and clear the obstacle stage
    • +
    +
  • Theme: + State which of the Storymatic themes you used. +
  • +
      +
    • N/A
    • +
    +
  • Mandated Variety: + State which input, randomness, genre, and play style you used in this prototype. +
  • +
      +
    • User input from keyboard. Stats are gained randomly.
    • +
    +
  • Prototype Goal: + What game mechanic is this prototype evaluating? +
  • +
      +
    • This prototype has only implemented the basic functions of my physical prototype.
    • +
    +
  • Player Experience Goals: + What experience do you want players to have when playing your game? +
  • +
      +
    • Deciding which stats to upgrade with the limited amount of stat points. Multiple replay value as players can attempt to beat the game with different stats.
    • +
    +
  • Gameplay: + A paragraph describing the actions the player can perform, the system dynamics, and the core mechanic. Include a concise explanation of the prototype’s inputs and their expected effects (how to play). You can also describe game play that is not in the prototype. You may include mock-up images for parts of the game not in the prototype. +
  • +
      +
    • The player enters a room to boost a stat of their choice. If they successfully complete it, they are granted a level in the stat point. With the earned stat point they can now attempt to clear the stage.
    • +
    +
  • Strategies: + What player strategies do you expect will be effective at playing this game? +
  • +
      +
    • Players have to think whether it is a good idea to upgrade a certain stat.
    • +
    +
  • Story/Setting/Premise: + A paragraph about the world your game is set in and who the characters are. What makes the game world and its occupants unique and interesting? Do the tokens represent something? If the game has a backstory, mention it here. If the game is abstract, then say so. + How will the dramatic tension interact with the gameplay tension? +
  • +
      +
    • No Story for this game for now.
    • +
    +
  • Target Audience: + A single sentence that describes the demographic you're trying to reach. +
  • +
      +
    • Preferably all ages.
    • +
    +
  • Play Time: + How long does your game take to play? +
  • +
      +
    • This prototype should take less than a minute.
    • +
    +
+ + \ No newline at end of file diff --git a/Iteration Sequence 1/js/game.js b/Iteration Sequence 1/js/game.js new file mode 100644 index 000000000..719b13eef --- /dev/null +++ b/Iteration Sequence 1/js/game.js @@ -0,0 +1,61 @@ +"use strict"; + +GameStates.makeGame = function( game, shared ) +{ + // Create your own variables. + var bouncy = null; + + + + function quitGame() + { + + // Here you should destroy anything you no longer need. + // Stop music, delete sprites, purge caches, free resources, all that good stuff. + + // Then let's go back to the main menu. + game.state.start('MainMenu'); + + } + + return { + + create: function () { + + // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! + + // Create a sprite at the center of the screen using the 'logo' image. + bouncy = game.add.sprite( game.world.centerX, game.world.centerY, 'logo' ); + // Anchor the sprite at its center, as opposed to its top-left corner. + // so it will be truly centered. + bouncy.anchor.setTo( 0.5, 0.5 ); + + // Turn on the arcade physics engine for this sprite. + game.physics.enable( bouncy, Phaser.Physics.ARCADE ); + // Make it bounce off of the world bounds. + bouncy.body.collideWorldBounds = true; + + // Add some text using a CSS style. + // Center it in X, and position its top 15 pixels from the top of the world. + var style = { font: "25px Verdana", fill: "#9999ff", align: "center" }; + var text = game.add.text( game.world.centerX, 15, "Build something amazing.", style ); + text.anchor.setTo( 0.5, 0.0 ); + + // When you click on the sprite, you go back to the MainMenu. + bouncy.inputEnabled = true; + bouncy.events.onInputDown.add( function() { quitGame(); }, this ); + }, + + update: function () { + + // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! + + // Accelerate the 'logo' sprite towards the cursor, + // accelerating at 500 pixels/second and moving no faster than 500 pixels/second + // in X or Y. + // This function returns the rotation angle that makes it visually match its + // new trajectory. + bouncy.rotation = game.physics.arcade.accelerateToPointer( bouncy, game.input.activePointer, 500, 500, 500 ); + } + }; +}; diff --git a/Iteration Sequence 1/js/main.js b/Iteration Sequence 1/js/main.js new file mode 100644 index 000000000..ab489eb0f --- /dev/null +++ b/Iteration Sequence 1/js/main.js @@ -0,0 +1,326 @@ +"use strict"; + +window.onload = function() +{ + var game = new Phaser.Game(900, 600, Phaser.CANVAS, 'game', { preload: preload, create: create, update: update, render: render }); + + function preload() + { + game.load.image('background','assets/temp_bg.jpg'); + game.load.image('stat','assets/stat.png'); + game.load.spritesheet('tile','assets/sheet.png', 70, 70); + game.load.spritesheet('man','assets/adventurer_tilesheet.png', 80, 110); + //game.load.atlasJSONHash('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json'); + } + + var button1; + var button2; + var button3; + var button4; + var button5; + var button6; + + var stat_text; + var stat_text2; + var stat_msg;; + + var stat_change; + + var stat_type = -1; + var stat_strength = 0; + var stat_resist = 0; + var stat_intuit = 0; + var stat_luck = 0; + var stat_remain = 7; + + var RNG; + + var player; + var cursors; + + function create() + { + game.add.tileSprite(0, 0, 1300, 650, 'background'); + game.add.tileSprite(0, 0, 300, 200, 'stat'); + game.add.tileSprite(400, 0, 500, 200, 'stat'); + game.world.setBounds(0, 0, 900, 600); + cursors = game.input.keyboard.createCursorKeys(); + + button1 = game.add.sprite(250, 500, 'tile', 1); + button1 = game.add.text(250, 500, 'S'); + button2 = game.add.sprite(400, 500, 'tile', 1); + button1 = game.add.text(400, 500, 'R'); + button3 = game.add.sprite(550, 500, 'tile', 1); + button1 = game.add.text(550, 500, 'I'); + button4 = game.add.sprite(700, 500, 'tile', 1); + button1 = game.add.text(700, 500, 'L'); + button5 = game.add.sprite(850, 500, 'tile', 1); + button6 = game.add.sprite(1000, 500, 'tile', 1); + + player = game.add.sprite(100, 500, 'man', 0); + player.anchor.setTo(0.5, 0.5); + player.scale.setTo(1, 1); + + player.animations.add('run', [0,9]); + player.animations.play('run', 8, true); + + this.game.input.keyboard.addKeyCapture(Phaser.Keyboard.SPACEBAR); + + stat_text = game.add.text(0, 0, 'Strength: \nResistance: \nIntuition: \nLuck: \nStat Points: '); + //stat_text.font = 'Arial Black'; + //stat_text.fill = '#000000'; + + stat_text2 = game.add.text(250, 0, stat_strength + '\n' + stat_resist + '\n' + stat_intuit + '\n' + stat_luck + '\n' + stat_remain); + + stat_change = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); + + stat_msg = game.add.text(450, 50, 'Use the arrow keys to move.\nUse the space key to attempt a trial for a stat boost.'); + } + + + function update() + { + if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) + { + if (player.x > 40) + { + player.x -= 6; + } + } + else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) + { + if (player.x < 860) + { + player.x += 6; + } + } + + stat_change.onDown.add(changeStats, this); + + /* + if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) + { + player.y -= 4; + } + else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) + { + player.y += 4; + } + */ + } + + function updateText() + { + stat_text2.setText(stat_strength + '\n' + stat_resist + '\n' + stat_intuit + '\n' + stat_luck + '\n' + stat_remain); + } + + function updateSuccess() + { + stat_msg.setText('Success'); + } + + function updateFail() + { + stat_msg.setText('Fail'); + } + + function updateStatError() + { + stat_msg.setText('Not enough Stat points'); + } + + function updateMaxStat() + { + stat_msg.setText("Stat is already maxed"); + } + + function changeStats() + { + console.log('Change Stats'); + + if (stat_remain > 0) + { + if (player.x >= 250 && player.x < 320) + { + stat_type = 1; + } + else if (player.x >= 400 && player.x < 470) + { + stat_type = 2; + } + else if (player.x >= 550 && player.x < 620) + { + stat_type = 3; + } + else if (player.x >= 700 && player.x < 770) + { + stat_type = 4; + } + else + { + stat_type = -1; + } + + RNG = game.rnd.integerInRange(0, 99); + + + switch (stat_type) + { + case 1: + if (stat_strength == 0 && RNG > 19) + { + stat_strength++; + stat_remain--; + updateSuccess(); + } + else if (stat_strength == 1 && RNG > 39) + { + stat_strength++; + stat_remain--; + updateSuccess(); + } + else if (stat_strength == 2 && RNG > 59) + { + stat_strength++; + stat_remain--; + updateSuccess(); + } + else if (stat_strength == 3) + { + updateMaxStat(); + } + else + { + stat_remain--; + updateFail(); + } + break; + case 2: + if (stat_resist == 0 && RNG > 19) + { + stat_resist++; + stat_remain--; + updateSuccess(); + } + else if (stat_resist == 1 && RNG > 39) + { + stat_resist++; + stat_remain--; + updateSuccess(); + } + else if (stat_resist == 2 && RNG > 59) + { + stat_resist++; + stat_remain--; + updateSuccess(); + } + else if (stat_resist == 3) + { + updateMaxStat(); + } + else + { + stat_remain--; + updateFail(); + } + break; + case 3: + if (stat_intuit == 0 && RNG > 19) + { + stat_intuit++; + stat_remain--; + updateSuccess(); + } + else if (stat_intuit == 1 && RNG > 39) + { + stat_intuit++; + stat_remain--; + updateSuccess(); + } + else if (stat_intuit == 2 && RNG > 59) + { + stat_intuit++; + stat_remain--; + updateSuccess(); + } + else if (stat_intuit == 3) + { + updateMaxStat(); + } + else + { + stat_remain--; + updateFail(); + } + break; + case 4: + if (stat_luck == 0 && RNG > 19) + { + stat_luck++; + stat_remain--; + updateSuccess(); + } + else if (stat_luck == 1 && RNG > 39) + { + stat_luck++; + stat_remain--; + updateSuccess(); + } + else if (stat_luck == 2 && RNG > 59) + { + stat_luck++; + stat_remain--; + updateSuccess(); + } + else if (stat_luck == 3) + { + updateMaxStat(); + } + else + { + stat_remain--; + updateFail(); + } + break; + default: + break; + } + updateText(); + } + else + { + updateStatError(); + } + } + + function render() + { + //game.debug.cameraInfo(game.camera, 32, 32); + } + + function up() + { + console.log('button up', arguments); + } + + function over() + { + console.log('button over'); + } + + function out() + { + console.log('button out'); + } + + function click_play() + { + console.log("Play"); + } + + function slow_down() + { + console.log('Collision'); + } + +}; \ No newline at end of file diff --git a/Iteration Sequence 1/js/phaser.js b/Iteration Sequence 1/js/phaser.js new file mode 100644 index 000000000..3bac171a7 --- /dev/null +++ b/Iteration Sequence 1/js/phaser.js @@ -0,0 +1,107825 @@ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +* +* @overview +* +* Phaser - http://phaser.io +* +* v2.10.0 "2018-01-18" - Built: Thu Jan 18 2018 16:35:03 +* +* By Richard Davey http://www.photonstorm.com @photonstorm +* +* Phaser is a fun, free and fast 2D game framework for making HTML5 games +* for desktop and mobile web browsers, supporting Canvas and WebGL rendering. +* +* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23 +* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe +* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com +* +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate. +* +* Follow development at http://phaser.io and on our forum +* +* "If you want your children to be intelligent, read them fairy tales." +* "If you want them to be more intelligent, read them more fairy tales." +* -- Albert Einstein +*/ + +/** + * The MIT License (MIT) + * + * Copyright (c) 2015 p2.js authors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=0 && s<=1 && t>=0 && t<=1); +}; + + +},{"./Scalar":4}],2:[function(_dereq_,module,exports){ +module.exports = Point; + +/** + * Point related functions + * @class Point + */ +function Point(){}; + +/** + * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. + * @static + * @method area + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +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 = []; + +/** + * Check if three points are collinear + * @method collinear + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. + * @return {Boolean} + */ +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 angle < thresholdAngle; + } +}; + +Point.sqdist = function(a,b){ + var dx = b[0] - a[0]; + var dy = b[1] - a[1]; + return dx * dx + dy * dy; +}; + +},{}],3:[function(_dereq_,module,exports){ +var Line = _dereq_("./Line") +, Point = _dereq_("./Point") +, Scalar = _dereq_("./Scalar") + +module.exports = Polygon; + +/** + * Polygon class. + * @class Polygon + * @constructor + */ +function Polygon(){ + + /** + * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] + * @property vertices + * @type {Array} + */ + this.vertices = []; +} + +/** + * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. + * @method at + * @param {Number} i + * @return {Array} + */ +Polygon.prototype.at = function(i){ + var v = this.vertices, + s = v.length; + return v[i < 0 ? i % s + s : i % s]; +}; + +/** + * Get first vertex + * @method first + * @return {Array} + */ +Polygon.prototype.first = function(){ + return this.vertices[0]; +}; + +/** + * Get last vertex + * @method last + * @return {Array} + */ +Polygon.prototype.last = function(){ + return this.vertices[this.vertices.length-1]; +}; + +/** + * Clear the polygon data + * @method clear + * @return {Array} + */ +Polygon.prototype.clear = function(){ + this.vertices.length = 0; +}; + +/** + * Append points "from" to "to"-1 from an other polygon "poly" onto this one. + * @method append + * @param {Polygon} poly The polygon to get points from. + * @param {Number} from The vertex index in "poly". + * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. + * @return {Array} + */ +Polygon.prototype.append = function(poly,from,to){ + if(typeof(from) == "undefined") throw new Error("From is not given!"); + if(typeof(to) == "undefined") throw new Error("To is not given!"); + + if(to-1 < from) throw new Error("lol1"); + if(to > poly.vertices.length) throw new Error("lol2"); + if(from < 0) throw new Error("lol3"); + + for(var i=from; i v[br][0])) { + br = i; + } + } + + // reverse poly if clockwise + if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { + this.reverse(); + } +}; + +/** + * Reverse the vertices in the polygon + * @method 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; +}; + +/** + * Check if a point in the polygon is a reflex point + * @method isReflex + * @param {Number} i + * @return {Boolean} + */ +Polygon.prototype.isReflex = function(i){ + return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); +}; + +var tmpLine1=[], + tmpLine2=[]; + +/** + * Check if two vertices in the polygon can see each other + * @method canSee + * @param {Number} a Vertex index 1 + * @param {Number} b Vertex index 2 + * @return {Boolean} + */ +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) { // for each edge + if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges + 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))) { // if diag intersects an edge + 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) < dist) { // if edge is blocking visibility to b + return false; + } + } + } + + return true; +}; + +/** + * Copy the polygon from vertex i to vertex j. + * @method copy + * @param {Number} i + * @param {Number} j + * @param {Polygon} [targetPoly] Optional target polygon to save in. + * @return {Polygon} The resulting copy. + */ +Polygon.prototype.copy = function(i,j,targetPoly){ + var p = targetPoly || new Polygon(); + p.clear(); + if (i < j) { + // Insert all vertices from i to j + for(var k=i; k<=j; k++) + p.vertices.push(this.vertices[k]); + + } else { + + // Insert vertices 0 to j + for(var k=0; k<=j; k++) + p.vertices.push(this.vertices[k]); + + // Insert vertices i to end + for(var k=i; k 0) + return this.slice(edges); + else + return [this]; +}; + +/** + * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. + * @method slice + * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() + * @return {Array} + */ +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; i maxlevel){ + console.warn("quickDecomp: max level ("+maxlevel+") reached."); + return result; + } + + for (var i = 0; i < this.vertices.length; ++i) { + if (poly.isReflex(i)) { + reflexVertices.push(poly.vertices[i]); + upperDist = lowerDist = Number.MAX_VALUE; + + + for (var j = 0; j < this.vertices.length; ++j) { + if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge + p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection + if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly + d = Point.sqdist(poly.vertices[i], p); + if (d < lowerDist) { // keep only the closest intersection + lowerDist = d; + lowerInt = p; + lowerIndex = j; + } + } + } + if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); + if (Point.left(poly.at(i - 1), poly.at(i), p)) { + d = Point.sqdist(poly.vertices[i], p); + if (d < upperDist) { + upperDist = d; + upperInt = p; + upperIndex = j; + } + } + } + } + + // if there are no vertices to connect to, choose a point in the middle + if (lowerIndex == (upperIndex + 1) % this.vertices.length) { + //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); + p[0] = (lowerInt[0] + upperInt[0]) / 2; + p[1] = (lowerInt[1] + upperInt[1]) / 2; + steinerPoints.push(p); + + if (i < upperIndex) { + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); + lowerPoly.append(poly, i, upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + if (lowerIndex != 0){ + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); + upperPoly.append(poly,lowerIndex,poly.vertices.length); + } + //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); + lowerPoly.append(poly,i,poly.vertices.length); + } + //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); + lowerPoly.append(poly,0,upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); + upperPoly.append(poly,lowerIndex,i+1); + } + } else { + // connect to the closest point within the triangle + //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); + + if (lowerIndex > upperIndex) { + upperIndex += this.vertices.length; + } + closestDist = Number.MAX_VALUE; + + if(upperIndex < lowerIndex){ + return result; + } + + for (var j = lowerIndex; j <= upperIndex; ++j) { + if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + d = Point.sqdist(poly.at(i), poly.at(j)); + if (d < closestDist) { + closestDist = d; + closestIndex = j % this.vertices.length; + } + } + } + + if (i < closestIndex) { + lowerPoly.append(poly,i,closestIndex+1); + if (closestIndex != 0){ + upperPoly.append(poly,closestIndex,v.length); + } + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + lowerPoly.append(poly,i,v.length); + } + lowerPoly.append(poly,0,closestIndex+1); + upperPoly.append(poly,closestIndex,i+1); + } + } + + // solve smallest poly first + if (lowerPoly.vertices.length < upperPoly.vertices.length) { + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } else { + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } + + return result; + } + } + result.push(this); + + return result; +}; + +/** + * Remove collinear points in the polygon. + * @method removeCollinearPoints + * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. + * @return {Number} The number of points removed + */ +Polygon.prototype.removeCollinearPoints = function(precision){ + var num = 0; + for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ + if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ + // Remove the middle point + this.vertices.splice(i%this.vertices.length,1); + i--; // Jump one point forward. Otherwise we may get a chain removal + num++; + } + } + return num; +}; + +},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){ +module.exports = Scalar; + +/** + * Scalar functions + * @class Scalar + */ +function Scalar(){} + +/** + * Check if two scalars are equal + * @static + * @method eq + * @param {Number} a + * @param {Number} b + * @param {Number} [precision] + * @return {Boolean} + */ +Scalar.eq = function(a,b,precision){ + precision = precision || 0; + return Math.abs(a-b) < precision; +}; + +},{}],5:[function(_dereq_,module,exports){ +module.exports = { + Polygon : _dereq_("./Polygon"), + Point : _dereq_("./Point"), +}; + +},{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){ +module.exports={ + "name": "p2", + "version": "0.7.1", + "description": "A JavaScript 2D physics engine.", + "author": "Stefan Hedman (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.5", + "grunt-contrib-jshint": "^0.11.2", + "grunt-contrib-nodeunit": "^0.4.1", + "grunt-contrib-uglify": "~0.4.0", + "grunt-contrib-watch": "~0.5.0", + "grunt-browserify": "~2.0.1", + "grunt-contrib-concat": "^0.4.0" + }, + "dependencies": { + "poly-decomp": "0.1.1" + } +} + +},{}],7:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = AABB; + +/** + * Axis aligned bounding box class. + * @class AABB + * @constructor + * @param {Object} [options] + * @param {Array} [options.upperBound] + * @param {Array} [options.lowerBound] + */ +function AABB(options){ + + /** + * The lower bound of the bounding box. + * @property lowerBound + * @type {Array} + */ + this.lowerBound = vec2.create(); + if(options && options.lowerBound){ + vec2.copy(this.lowerBound, options.lowerBound); + } + + /** + * The upper bound of the bounding box. + * @property upperBound + * @type {Array} + */ + this.upperBound = vec2.create(); + if(options && options.upperBound){ + vec2.copy(this.upperBound, options.upperBound); + } +} + +var tmp = vec2.create(); + +/** + * Set the AABB bounds from a set of points, transformed by the given position and angle. + * @method setFromPoints + * @param {Array} points An array of vec2's. + * @param {Array} position + * @param {number} angle + * @param {number} skinSize Some margin to be added to the AABB. + */ +AABB.prototype.setFromPoints = function(points, position, angle, skinSize){ + var l = this.lowerBound, + u = this.upperBound; + + if(typeof(angle) !== "number"){ + angle = 0; + } + + // Set to the first point + if(angle !== 0){ + vec2.rotate(l, points[0], angle); + } else { + vec2.copy(l, points[0]); + } + vec2.copy(u, l); + + // Compute cosines and sines just once + var cosAngle = Math.cos(angle), + sinAngle = Math.sin(angle); + for(var i = 1; i u[j]){ + u[j] = p[j]; + } + if(p[j] < l[j]){ + l[j] = p[j]; + } + } + } + + // Add offset + if(position){ + vec2.add(this.lowerBound, this.lowerBound, position); + vec2.add(this.upperBound, this.upperBound, position); + } + + if(skinSize){ + this.lowerBound[0] -= skinSize; + this.lowerBound[1] -= skinSize; + this.upperBound[0] += skinSize; + this.upperBound[1] += skinSize; + } +}; + +/** + * Copy bounds from an AABB to this AABB + * @method copy + * @param {AABB} aabb + */ +AABB.prototype.copy = function(aabb){ + vec2.copy(this.lowerBound, aabb.lowerBound); + vec2.copy(this.upperBound, aabb.upperBound); +}; + +/** + * Extend this AABB so that it covers the given AABB too. + * @method extend + * @param {AABB} aabb + */ +AABB.prototype.extend = function(aabb){ + // Loop over x and y + var i = 2; + while(i--){ + // Extend lower bound + var l = aabb.lowerBound[i]; + if(this.lowerBound[i] > l){ + this.lowerBound[i] = l; + } + + // Upper + var u = aabb.upperBound[i]; + if(this.upperBound[i] < u){ + this.upperBound[i] = u; + } + } +}; + +/** + * Returns true if the given AABB overlaps this AABB. + * @method overlaps + * @param {AABB} aabb + * @return {Boolean} + */ +AABB.prototype.overlaps = function(aabb){ + var l1 = this.lowerBound, + u1 = this.upperBound, + l2 = aabb.lowerBound, + u2 = aabb.upperBound; + + // l2 u2 + // |---------| + // |--------| + // l1 u1 + + 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])); +}; + +/** + * @method containsPoint + * @param {Array} point + * @return {boolean} + */ +AABB.prototype.containsPoint = function(point){ + var l = this.lowerBound, + u = this.upperBound; + return l[0] <= point[0] && point[0] <= u[0] && l[1] <= point[1] && point[1] <= u[1]; +}; + +/** + * Check if the AABB is hit by a ray. + * @method overlapsRay + * @param {Ray} ray + * @return {number} -1 if no hit, a number between 0 and 1 if hit. + */ +AABB.prototype.overlapsRay = function(ray){ + var t = 0; + + // ray.direction is unit direction vector of ray + var dirFracX = 1 / ray.direction[0]; + var dirFracY = 1 / ray.direction[1]; + + // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner + var t1 = (this.lowerBound[0] - ray.from[0]) * dirFracX; + var t2 = (this.upperBound[0] - ray.from[0]) * dirFracX; + var t3 = (this.lowerBound[1] - ray.from[1]) * dirFracY; + var t4 = (this.upperBound[1] - ray.from[1]) * dirFracY; + + var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4))); + var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4))); + + // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us + if (tmax < 0){ + //t = tmax; + return -1; + } + + // if tmin > tmax, ray doesn't intersect AABB + if (tmin > tmax){ + //t = tmax; + return -1; + } + + return tmin; +}; +},{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Body = _dereq_('../objects/Body'); + +module.exports = Broadphase; + +/** + * Base class for broadphase implementations. + * @class Broadphase + * @constructor + */ +function Broadphase(type){ + + this.type = type; + + /** + * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). + * @property result + * @type {Array} + */ + this.result = []; + + /** + * The world to search for collision pairs in. To change it, use .setWorld() + * @property world + * @type {World} + * @readOnly + */ + this.world = null; + + /** + * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE. + * @property {Number} boundingVolumeType + */ + this.boundingVolumeType = Broadphase.AABB; +} + +/** + * Axis aligned bounding box type. + * @static + * @property {Number} AABB + */ +Broadphase.AABB = 1; + +/** + * Bounding circle type. + * @static + * @property {Number} BOUNDING_CIRCLE + */ +Broadphase.BOUNDING_CIRCLE = 2; + +/** + * Set the world that we are searching for collision pairs in. + * @method setWorld + * @param {World} world + */ +Broadphase.prototype.setWorld = function(world){ + this.world = world; +}; + +/** + * Get all potential intersecting body pairs. + * @method getCollisionPairs + * @param {World} world The world to search in. + * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). + */ +Broadphase.prototype.getCollisionPairs = function(world){}; + +var dist = vec2.create(); + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.aabbCheck = function(bodyA, bodyB){ + return bodyA.getAABB().overlaps(bodyB.getAABB()); +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether two bodies are allowed to collide at all. + * @method canCollide + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.canCollide = function(bodyA, bodyB){ + var KINEMATIC = Body.KINEMATIC; + var STATIC = Body.STATIC; + + // Cannot collide static bodies + if(bodyA.type === STATIC && bodyB.type === STATIC){ + return false; + } + + // Cannot collide static vs kinematic bodies + if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) || + (bodyA.type === STATIC && bodyB.type === KINEMATIC)){ + return false; + } + + // Cannot collide kinematic vs kinematic + if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){ + return false; + } + + // Cannot collide both sleeping bodies + if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ + return false; + } + + // Cannot collide if one is static and the other is sleeping + if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === STATIC) || + (bodyB.sleepState === Body.SLEEPING && bodyA.type === STATIC)){ + return false; + } + + return true; +}; + +Broadphase.NAIVE = 1; +Broadphase.SAP = 2; + +},{"../math/vec2":30,"../objects/Body":31}],9:[function(_dereq_,module,exports){ +var Circle = _dereq_('../shapes/Circle'), + Plane = _dereq_('../shapes/Plane'), + Shape = _dereq_('../shapes/Shape'), + Particle = _dereq_('../shapes/Particle'), + Broadphase = _dereq_('../collision/Broadphase'), + vec2 = _dereq_('../math/vec2'); + +module.exports = NaiveBroadphase; + +/** + * Naive broadphase implementation. Does N^2 tests. + * + * @class NaiveBroadphase + * @constructor + * @extends Broadphase + */ +function NaiveBroadphase(){ + Broadphase.call(this, Broadphase.NAIVE); +} +NaiveBroadphase.prototype = new Broadphase(); +NaiveBroadphase.prototype.constructor = NaiveBroadphase; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +NaiveBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = world.bodies, + result = this.result; + + result.length = 0; + + for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ + var bi = bodies[i]; + + for(var j=0; j pos0 && pos < pos1){ + // We got contact! + + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape); + + vec2.scale(c.normalA, orthoDist, -1); + vec2.normalize(c.normalA, c.normalA); + + vec2.scale( c.contactPointA, c.normalA, circleRadius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + sub(c.contactPointB, projectedPoint, lineOffset); + add(c.contactPointB, c.contactPointB, lineOffset); + sub(c.contactPointB, c.contactPointB, lineBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; + } + } + + // Add corner + verts[0] = worldVertex0; + verts[1] = worldVertex1; + + for(var i=0; i 0){ + for(var i=0; i Math.pow(r,2)){ + return 0; + } + + if(justTest){ + return true; + } + + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + 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; +}; + +/** + * Plane/Convex Narrowphase + * @method planeConvex + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} convexBody + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = +Narrowphase.prototype[Shape.PLANE | Shape.BOX] = +Narrowphase.prototype.planeConvex = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + convexBody, + convexShape, + convexOffset, + convexAngle, + justTest +){ + var worldVertex = tmp1, + worldNormal = tmp2, + dist = tmp3; + + var numReported = 0; + vec2.rotate(worldNormal, yAxis, planeAngle); + + for(var i=0; i!==convexShape.vertices.length; i++){ + var v = convexShape.vertices[i]; + vec2.rotate(worldVertex, v, convexAngle); + add(worldVertex, worldVertex, convexOffset); + + sub(dist, worldVertex, planeOffset); + + if(dot(dist,worldNormal) <= 0){ + + if(justTest){ + return true; + } + + // Found vertex + numReported++; + + var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); + + sub(dist, worldVertex, planeOffset); + + vec2.copy(c.normalA, worldNormal); + + var d = dot(dist, c.normalA); + vec2.scale(dist, c.normalA, d); + + // rj is from convex center to contact + sub(c.contactPointB, worldVertex, convexBody.position); + + + // ri is from plane center to contact + sub( c.contactPointA, worldVertex, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + this.contactEquations.push(c); + + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numReported){ + this.frictionEquations.push(this.createFrictionFromAverage(numReported)); + } + } + + return numReported; +}; + +/** + * Narrowphase for particle vs plane + * @method particlePlane + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = +Narrowphase.prototype.particlePlane = function( + particleBody, + particleShape, + particleOffset, + particleAngle, + planeBody, + planeShape, + planeOffset, + planeAngle, + justTest +){ + var dist = tmp1, + worldNormal = tmp2; + + planeAngle = planeAngle || 0; + + sub(dist, particleOffset, planeOffset); + vec2.rotate(worldNormal, yAxis, planeAngle); + + var d = dot(dist, worldNormal); + + if(d > 0){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape); + + vec2.copy(c.normalA, worldNormal); + vec2.scale( dist, c.normalA, d ); + // dist is now the distance vector in the normal direction + + // ri is the particle position projected down onto the plane, from the plane center + sub( c.contactPointA, particleOffset, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + // rj is from the body center to the particle center + sub( c.contactPointB, particleOffset, particleBody.position ); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + return 1; +}; + +/** + * Circle/Particle Narrowphase + * @method circleParticle + * @param {Body} circleBody + * @param {Circle} circleShape + * @param {Array} circleOffset + * @param {Number} circleAngle + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = +Narrowphase.prototype.circleParticle = function( + circleBody, + circleShape, + circleOffset, + circleAngle, + particleBody, + particleShape, + particleOffset, + particleAngle, + justTest +){ + var dist = tmp1; + + sub(dist, particleOffset, circleOffset); + if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape); + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + // Vector from circle to contact point is the normal times the circle radius + vec2.scale(c.contactPointA, c.normalA, circleShape.radius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + // Vector from particle center to contact point is zero + sub(c.contactPointB, particleOffset, particleBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; +}; + +var planeCapsule_tmpCircle = new Circle({ radius: 1 }), + planeCapsule_tmp1 = vec2.create(), + planeCapsule_tmp2 = vec2.create(), + planeCapsule_tmp3 = vec2.create(); + +/** + * @method planeCapsule + * @param {Body} planeBody + * @param {Circle} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} capsuleBody + * @param {Particle} capsuleShape + * @param {Array} capsuleOffset + * @param {Number} capsuleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = +Narrowphase.prototype.planeCapsule = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + capsuleBody, + capsuleShape, + capsuleOffset, + capsuleAngle, + justTest +){ + var end1 = planeCapsule_tmp1, + end2 = planeCapsule_tmp2, + circle = planeCapsule_tmpCircle, + dst = planeCapsule_tmp3; + + // Compute world end positions + vec2.set(end1, -capsuleShape.length/2, 0); + vec2.rotate(end1,end1,capsuleAngle); + add(end1,end1,capsuleOffset); + + vec2.set(end2, capsuleShape.length/2, 0); + vec2.rotate(end2,end2,capsuleAngle); + add(end2,end2,capsuleOffset); + + circle.radius = capsuleShape.radius; + + var enableFrictionBefore; + + // Temporarily turn off friction + if(this.enableFrictionReduction){ + enableFrictionBefore = this.enableFriction; + this.enableFriction = false; + } + + // Do Narrowphase as two circles + var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest), + numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest); + + // Restore friction + if(this.enableFrictionReduction){ + this.enableFriction = enableFrictionBefore; + } + + if(justTest){ + return numContacts1 || numContacts2; + } else { + var numTotal = numContacts1 + numContacts2; + if(this.enableFrictionReduction){ + if(numTotal){ + this.frictionEquations.push(this.createFrictionFromAverage(numTotal)); + } + } + return numTotal; + } +}; + +/** + * Creates ContactEquations and FrictionEquations for a collision. + * @method circlePlane + * @param {Body} bi The first body that should be connected to the equations. + * @param {Circle} si The circle shape participating in the collision. + * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. + * @param {Body} bj The second body that should be connected to the equations. + * @param {Plane} sj The Plane shape that is participating + * @param {Array} xj Extra offset for the plane shape. + * @param {Number} aj Extra angle to apply to the plane + */ +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, // Offset from body center, rotated! + planeBody = bj, + shapeB = sj, + planeOffset = xj, + planeAngle = aj; + + planeAngle = planeAngle || 0; + + // Vector from plane to circle + var planeToCircle = tmp1, + worldNormal = tmp2, + temp = tmp3; + + sub(planeToCircle, circleOffset, planeOffset); + + // World plane normal + vec2.rotate(worldNormal, yAxis, planeAngle); + + // Normal direction distance + var d = dot(worldNormal, planeToCircle); + + if(d > circleShape.radius){ + return 0; // No overlap. Abort. + } + + if(justTest){ + return true; + } + + // Create contact + var contact = this.createContactEquation(planeBody,circleBody,sj,si); + + // ni is the plane world normal + vec2.copy(contact.normalA, worldNormal); + + // rj is the vector from circle center to the contact point + vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); + add(contact.contactPointB, contact.contactPointB, circleOffset); + sub(contact.contactPointB, contact.contactPointB, circleBody.position); + + // ri is the distance from plane center to contact. + vec2.scale(temp, contact.normalA, d); + sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector + 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; +}; + +/** + * Convex/convex Narrowphase.See this article for more info. + * @method convexConvex + * @param {Body} bi + * @param {Convex} si + * @param {Array} xi + * @param {Number} ai + * @param {Body} bj + * @param {Convex} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CONVEX] = +Narrowphase.prototype[Shape.CONVEX | Shape.BOX] = +Narrowphase.prototype[Shape.BOX] = +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 = typeof(precision) === 'number' ? precision : 0; + + var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); + if(!found){ + return 0; + } + + // Make sure the separating axis is directed from shape i to shape j + sub(dist,xj,xi); + if(dot(sepAxis,dist) > 0){ + vec2.scale(sepAxis,sepAxis,-1); + } + + // Find edges with normals closest to the separating axis + var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis + closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); + + if(closestEdge1 === -1 || closestEdge2 === -1){ + return 0; + } + + // Loop over the shapes + 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){ + // Swap! + 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; + } + + // Loop over 2 points in convex B + for(var j=closestEdgeB; j= 3){ + + if(justTest){ + return true; + } + + // worldPoint was on the "inside" side of each of the 3 checked edges. + // Project it to the center edge and use the projection direction as normal + + // Create contact + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + numContacts++; + + // Get center edge from body A + var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], + v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; + + // Construct the edge + 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); // Normal points out of convex A + vec2.normalize(c.normalA,c.normalA); + + sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point + var d = dot(c.normalA,dist); // Penetration + vec2.scale(penetrationVec, c.normalA, d); // Vector penetration + + 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); + + // Todo reduce to 1 friction equation if we have 2 contact points + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numContacts){ + this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); + } + } + + return numContacts; +}; + +// .projectConvex is called by other functions, need local tmp vectors +var pcoa_tmp1 = vec2.fromValues(0,0); + +/** + * Project a Convex onto a world-oriented axis + * @method projectConvexOntoAxis + * @static + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Array} worldAxis + * @param {Array} result + */ +Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = pcoa_tmp1; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, worldAxis, -convexAngle); + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + // Project the position of the body onto the axis - need to add this to the result + var offset = dot(convexOffset, worldAxis); + + vec2.set( result, min + offset, max + offset); +}; + +// .findSeparatingAxis is called by other functions, need local tmp vectors +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); + +/** + * Find a separating axis between the shapes, that maximizes the separating distance between them. + * @method findSeparatingAxis + * @static + * @param {Convex} c1 + * @param {Array} offset1 + * @param {Number} angle1 + * @param {Convex} c2 + * @param {Array} offset2 + * @param {Number} angle2 + * @param {Array} sepAxis The resulting axis + * @return {Boolean} Whether the axis could be found. + */ +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; + + if(c1 instanceof Box && c2 instanceof Box){ + + for(var j=0; j!==2; j++){ + var c = c1, + angle = angle1; + if(j===1){ + c = c2; + angle = angle2; + } + + for(var i=0; i!==2; i++){ + + // Get the world edge + if(i === 0){ + vec2.set(normal, 0, 1); + } else if(i === 1) { + vec2.set(normal, 1, 0); + } + if(angle !== 0){ + vec2.rotate(normal, normal, angle); + } + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + + } else { + + 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++){ + // Get the world edge + vec2.rotate(worldPoint0, c.vertices[i], angle); + vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); + + sub(edge, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, edge); + vec2.normalize(normal,normal); + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + } + + + /* + // Needs to be tested some more + 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.axes.length; i++){ + + var normal = c.axes[i]; + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1); + Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + 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; +}; + +// .getClosestEdge is called by other functions, need local tmp vectors +var gce_tmp1 = vec2.fromValues(0,0) +, gce_tmp2 = vec2.fromValues(0,0) +, gce_tmp3 = vec2.fromValues(0,0); + +/** + * Get the edge that has a normal closest to an axis. + * @method getClosestEdge + * @static + * @param {Convex} c + * @param {Number} angle + * @param {Array} axis + * @param {Boolean} flip + * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. + */ +Narrowphase.getClosestEdge = function(c,angle,axis,flip){ + var localAxis = gce_tmp1, + edge = gce_tmp2, + normal = gce_tmp3; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, axis, -angle); + if(flip){ + vec2.scale(localAxis,localAxis,-1); + } + + var closestEdge = -1, + N = c.vertices.length, + maxDot = -1; + for(var i=0; i!==N; i++){ + // Get the edge + sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + 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(); + +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = +Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, + hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ + var data = hfShape.heights, + 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; + + // Get the index of the points to test against + var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), + idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); + + /*if(idxB < 0 || idxA >= data.length) + return justTest ? false : 0;*/ + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(circlePos[1]-radius > max){ + return justTest ? false : 0; + } + + /* + if(circlePos[1]+radius < min){ + // Below the minimum point... We can just guess. + // TODO + } + */ + + // 1. Check so center of circle is not inside the field. If it is, this wont work... + // 2. For each edge + // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) + // 2. 2. Check if point is inside. + + var found = false; + + // Check all edges first + for(var i=idxA; i= v0[0] && candidate[0] < v1[0] && d <= 0){ + + if(justTest){ + return true; + } + + found = true; + + // Store the candidate point, projected to the edge + vec2.scale(dist,worldNormal,-d); + vec2.add(minCandidate,candidate,dist); + vec2.copy(minCandidateNormal,worldNormal); + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Normal is out of the heightfield + vec2.copy(c.normalA, minCandidateNormal); + + // Vector from circle to heightfield + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + vec2.copy(c.contactPointA, minCandidate); + vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push( this.createFrictionFromContact(c) ); + } + } + } + + // Check all vertices + found = false; + if(radius > 0){ + for(var i=idxA; i<=idxB; i++){ + + // Get point + vec2.set(v0, i*w, data[i]); + vec2.add(v0,v0,hfPos); + + vec2.sub(dist, circlePos, v0); + + if(vec2.squaredLength(dist) < Math.pow(radius, 2)){ + + if(justTest){ + return true; + } + + found = true; + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Construct normal - out of heightfield + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + sub(c.contactPointA, v0, hfPos); + add(c.contactPointA, c.contactPointA, hfPos); + sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(found){ + return 1; + } + + return 0; + +}; + +var convexHeightfield_v0 = vec2.create(), + convexHeightfield_v1 = vec2.create(), + convexHeightfield_tilePos = vec2.create(), + convexHeightfield_tempConvexShape = new Convex({ vertices: [vec2.create(),vec2.create(),vec2.create(),vec2.create()] }); +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.BOX | Shape.HEIGHTFIELD] = +Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = +Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, + hfBody,hfShape,hfPos,hfAngle, justTest ){ + var data = hfShape.heights, + w = hfShape.elementWidth, + v0 = convexHeightfield_v0, + v1 = convexHeightfield_v1, + tilePos = convexHeightfield_tilePos, + tileConvex = convexHeightfield_tempConvexShape; + + // Get the index of the points to test against + var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), + idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(convexBody.aabb.lowerBound[1] > max){ + return justTest ? false : 0; + } + + var found = false; + var numContacts = 0; + + // Loop over all edges + // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape) + for(var i=idxA; i= 0 || aabb.containsPoint(this.from)){ + this.intersectBody(result, body); + } + } +}; + +var intersectBody_worldPosition = vec2.create(); + +/** + * Shoot a ray at a body, get back information about the hit. + * @method intersectBody + * @private + * @param {Body} body + */ +Ray.prototype.intersectBody = function (result, body) { + var checkCollisionResponse = this.checkCollisionResponse; + + if(checkCollisionResponse && !body.collisionResponse){ + return; + } + + var worldPosition = intersectBody_worldPosition; + + for (var i = 0, N = body.shapes.length; i < N; i++) { + var shape = body.shapes[i]; + + if(checkCollisionResponse && !shape.collisionResponse){ + continue; // Skip + } + + if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){ + continue; + } + + // Get world angle and position of the shape + vec2.rotate(worldPosition, shape.position, body.angle); + vec2.add(worldPosition, worldPosition, body.position); + var worldAngle = shape.angle + body.angle; + + this.intersectShape( + result, + shape, + worldAngle, + worldPosition, + body + ); + + if(result.shouldStop(this)){ + break; + } + } +}; + +/** + * @method intersectShape + * @private + * @param {Shape} shape + * @param {number} angle + * @param {array} position + * @param {Body} body + */ +Ray.prototype.intersectShape = function(result, shape, angle, position, body){ + var from = this.from; + + // Checking radius + var distance = distanceFromIntersectionSquared(from, this.direction, position); + if (distance > shape.boundingRadius * shape.boundingRadius) { + return; + } + + this._currentBody = body; + this._currentShape = shape; + + shape.raycast(result, this, position, angle); + + this._currentBody = this._currentShape = null; +}; + +/** + * Get the AABB of the ray. + * @method getAABB + * @param {AABB} aabb + */ +Ray.prototype.getAABB = function(result){ + var to = this.to; + var from = this.from; + vec2.set( + result.lowerBound, + Math.min(to[0], from[0]), + Math.min(to[1], from[1]) + ); + vec2.set( + result.upperBound, + Math.max(to[0], from[0]), + Math.max(to[1], from[1]) + ); +}; + +var hitPointWorld = vec2.create(); + +/** + * @method reportIntersection + * @private + * @param {number} fraction + * @param {array} normal + * @param {number} [faceIndex=-1] + * @return {boolean} True if the intersections should continue + */ +Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){ + var from = this.from; + var to = this.to; + var shape = this._currentShape; + var body = this._currentBody; + + // Skip back faces? + if(this.skipBackfaces && vec2.dot(normal, this.direction) > 0){ + return; + } + + switch(this.mode){ + + case Ray.ALL: + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + this.callback(result); + break; + + case Ray.CLOSEST: + + // Store if closer than current closest + if(fraction < result.fraction || !result.hasHit()){ + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + } + break; + + case Ray.ANY: + + // Report and stop. + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + break; + } +}; + +var v0 = vec2.create(), + intersect = vec2.create(); +function distanceFromIntersectionSquared(from, direction, position) { + + // v0 is vector from from to position + vec2.sub(v0, position, from); + var dot = vec2.dot(v0, direction); + + // intersect = direction * dot + from + vec2.scale(intersect, direction, dot); + vec2.add(intersect, intersect, from); + + return vec2.squaredDistance(position, intersect); +} + + +},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Ray = _dereq_('../collision/Ray'); + +module.exports = RaycastResult; + +/** + * Storage for Ray casting hit data. + * @class RaycastResult + * @constructor + */ +function RaycastResult(){ + + /** + * The normal of the hit, oriented in world space. + * @property {array} normal + */ + this.normal = vec2.create(); + + /** + * The hit shape, or null. + * @property {Shape} shape + */ + this.shape = null; + + /** + * The hit body, or null. + * @property {Body} body + */ + this.body = null; + + /** + * The index of the hit triangle, if the hit shape was indexable. + * @property {number} faceIndex + * @default -1 + */ + this.faceIndex = -1; + + /** + * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet. + * @property {number} fraction + * @default -1 + */ + this.fraction = -1; + + /** + * If the ray should stop traversing. + * @readonly + * @property {Boolean} isStopped + */ + this.isStopped = false; +} + +/** + * Reset all result data. Must be done before re-using the result object. + * @method reset + */ +RaycastResult.prototype.reset = function () { + vec2.set(this.normal, 0, 0); + this.shape = null; + this.body = null; + this.faceIndex = -1; + this.fraction = -1; + this.isStopped = false; +}; + +/** + * Get the distance to the hit point. + * @method getHitDistance + * @param {Ray} ray + */ +RaycastResult.prototype.getHitDistance = function (ray) { + return vec2.distance(ray.from, ray.to) * this.fraction; +}; + +/** + * Returns true if the ray hit something since the last reset(). + * @method hasHit + */ +RaycastResult.prototype.hasHit = function () { + return this.fraction !== -1; +}; + +/** + * Get world hit point. + * @method getHitPoint + * @param {array} out + * @param {Ray} ray + */ +RaycastResult.prototype.getHitPoint = function (out, ray) { + vec2.lerp(out, ray.from, ray.to, this.fraction); +}; + +/** + * Can be called while iterating over hits to stop searching for hit points. + * @method stop + */ +RaycastResult.prototype.stop = function(){ + this.isStopped = true; +}; + +/** + * @method shouldStop + * @private + * @param {Ray} ray + * @return {boolean} + */ +RaycastResult.prototype.shouldStop = function(ray){ + return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY); +}; + +/** + * @method set + * @private + * @param {array} normal + * @param {Shape} shape + * @param {Body} body + * @param {number} fraction + */ +RaycastResult.prototype.set = function( + normal, + shape, + body, + fraction, + faceIndex +){ + vec2.copy(this.normal, normal); + this.shape = shape; + this.body = body; + this.fraction = fraction; + this.faceIndex = faceIndex; +}; +},{"../collision/Ray":11,"../math/vec2":30}],13:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, Broadphase = _dereq_('../collision/Broadphase'); + +module.exports = SAPBroadphase; + +/** + * Sweep and prune broadphase along one axis. + * + * @class SAPBroadphase + * @constructor + * @extends Broadphase + */ +function SAPBroadphase(){ + Broadphase.call(this,Broadphase.SAP); + + /** + * List of bodies currently in the broadphase. + * @property axisList + * @type {Array} + */ + this.axisList = []; + + /** + * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance. + * @property axisIndex + * @type {Number} + */ + this.axisIndex = 0; + + var that = this; + this._addBodyHandler = function(e){ + that.axisList.push(e.body); + }; + + this._removeBodyHandler = function(e){ + // Remove from list + var idx = that.axisList.indexOf(e.body); + if(idx !== -1){ + that.axisList.splice(idx,1); + } + }; +} +SAPBroadphase.prototype = new Broadphase(); +SAPBroadphase.prototype.constructor = SAPBroadphase; + +/** + * Change the world + * @method setWorld + * @param {World} world + */ +SAPBroadphase.prototype.setWorld = function(world){ + // Clear the old axis array + this.axisList.length = 0; + + // Add all bodies from the new world + Utils.appendArray(this.axisList, world.bodies); + + // Remove old handlers, if any + world + .off("addBody",this._addBodyHandler) + .off("removeBody",this._removeBodyHandler); + + // Add handlers to update the list of bodies. + world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); + + this.world = world; +}; + +/** + * Sorts bodies along an axis. + * @method sortAxisList + * @param {Array} a + * @param {number} axisIndex + * @return {Array} + */ +SAPBroadphase.sortAxisList = function(a, axisIndex){ + axisIndex = axisIndex|0; + for(var i=1,l=a.length; 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.sortList = function(){ + var bodies = this.axisList, + axisIndex = this.axisIndex; + + // Sort the lists + SAPBroadphase.sortAxisList(bodies, axisIndex); +}; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +SAPBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = this.axisList, + result = this.result, + axisIndex = this.axisIndex; + + result.length = 0; + + // Update all AABBs if needed + var l = bodies.length; + while(l--){ + var b = bodies[l]; + if(b.aabbNeedsUpdate){ + b.updateAABB(); + } + } + + // Sort the lists + this.sortList(); + + // Look through the X list + for(var i=0, N=bodies.length|0; i!==N; i++){ + var bi = bodies[i]; + + for(var j=i+1; j G = [-n -rixn n rjxn] + + var r = vec2.create(); + var ri = vec2.create(); // worldAnchorA + var rj = vec2.create(); // worldAnchorB + var that = this; + normal.computeGq = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + xi = bodyA.position, + xj = bodyB.position; + + // Transform local anchors to world + vec2.rotate(ri, localAnchorA, bodyA.angle); + vec2.rotate(rj, localAnchorB, bodyB.angle); + + vec2.add(r, xj, rj); + vec2.sub(r, r, ri); + vec2.sub(r, r, xi); + + //vec2.sub(r, bodyB.position, bodyA.position); + return vec2.length(r) - that.distance; + }; + + // Make the contact constraint bilateral + this.setMaxForce(maxForce); + + /** + * If the upper limit is enabled or not. + * @property {Boolean} upperLimitEnabled + */ + this.upperLimitEnabled = false; + + /** + * The upper constraint limit. + * @property {number} upperLimit + */ + this.upperLimit = 1; + + /** + * If the lower limit is enabled or not. + * @property {Boolean} lowerLimitEnabled + */ + this.lowerLimitEnabled = false; + + /** + * The lower constraint limit. + * @property {number} lowerLimit + */ + this.lowerLimit = 0; + + /** + * Current constraint position. This is equal to the current distance between the world anchor points. + * @property {number} position + */ + this.position = 0; +} +DistanceConstraint.prototype = new Constraint(); +DistanceConstraint.prototype.constructor = DistanceConstraint; + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +var n = vec2.create(); +var ri = vec2.create(); // worldAnchorA +var rj = vec2.create(); // worldAnchorB +DistanceConstraint.prototype.update = function(){ + var normal = this.equations[0], + bodyA = this.bodyA, + bodyB = this.bodyB, + distance = this.distance, + xi = bodyA.position, + xj = bodyB.position, + normalEquation = this.equations[0], + G = normal.G; + + // Transform local anchors to world + vec2.rotate(ri, this.localAnchorA, bodyA.angle); + vec2.rotate(rj, this.localAnchorB, bodyB.angle); + + // Get world anchor points and normal + vec2.add(n, xj, rj); + vec2.sub(n, n, ri); + vec2.sub(n, n, xi); + this.position = vec2.length(n); + + var violating = false; + if(this.upperLimitEnabled){ + if(this.position > this.upperLimit){ + normalEquation.maxForce = 0; + normalEquation.minForce = -this.maxForce; + this.distance = this.upperLimit; + violating = true; + } + } + + if(this.lowerLimitEnabled){ + if(this.position < this.lowerLimit){ + normalEquation.maxForce = this.maxForce; + normalEquation.minForce = 0; + this.distance = this.lowerLimit; + violating = true; + } + } + + if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){ + // No constraint needed. + normalEquation.enabled = false; + return; + } + + normalEquation.enabled = true; + + vec2.normalize(n,n); + + // Caluclate cross products + var rixn = vec2.crossLength(ri, n), + rjxn = vec2.crossLength(rj, n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; +}; + +/** + * Set the max force to be used + * @method setMaxForce + * @param {Number} maxForce + */ +DistanceConstraint.prototype.setMaxForce = function(maxForce){ + var normal = this.equations[0]; + normal.minForce = -maxForce; + normal.maxForce = maxForce; +}; + +/** + * Get the max force + * @method getMaxForce + * @return {Number} + */ +DistanceConstraint.prototype.getMaxForce = function(){ + var normal = this.equations[0]; + return normal.maxForce; +}; + +},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, AngleLockEquation = _dereq_('../equations/AngleLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = GearConstraint; + +/** + * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB. + * @class GearConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for). + * @param {Number} [options.ratio=1] Gear ratio. + * @param {Number} [options.maxTorque] Maximum torque to apply. + * @extends Constraint + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB, { + * ratio: 2, + * maxTorque: 1000 + * }); + * world.addConstraint(constraint); + */ +function GearConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); + + /** + * The gear ratio. + * @property ratio + * @type {Number} + */ + this.ratio = options.ratio !== undefined ? options.ratio : 1; + + /** + * The relative angle + * @property angle + * @type {Number} + */ + this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle; + + // Send same parameters to the equation + options.angle = this.angle; + options.ratio = this.ratio; + + this.equations = [ + new AngleLockEquation(bodyA,bodyB,options), + ]; + + // Set max torque + if(options.maxTorque !== undefined){ + this.setMaxTorque(options.maxTorque); + } +} +GearConstraint.prototype = new Constraint(); +GearConstraint.prototype.constructor = GearConstraint; + +GearConstraint.prototype.update = function(){ + var eq = this.equations[0]; + if(eq.ratio !== this.ratio){ + eq.setRatio(this.ratio); + } + eq.angle = this.angle; +}; + +/** + * Set the max torque for the constraint. + * @method setMaxTorque + * @param {Number} torque + */ +GearConstraint.prototype.setMaxTorque = function(torque){ + this.equations[0].setMaxTorque(torque); +}; + +/** + * Get the max torque for the constraint. + * @method getMaxTorque + * @return {Number} + */ +GearConstraint.prototype.getMaxTorque = function(torque){ + return this.equations[0].maxForce; +}; +},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('../equations/Equation'); + +module.exports = LockConstraint; + +/** + * Locks the relative position and rotation between two bodies. + * + * @class LockConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions. + * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles. + * @param {number} [options.maxForce] + * @extends Constraint + * + * @example + * // Locks the relative position and rotation between bodyA and bodyB + * var constraint = new LockConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + */ +function LockConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); + + var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); + + var localAngleB = options.localAngleB || 0; + + // Use 3 equations: + // gx = (xj - xi - l) * xhat = 0 + // gy = (xj - xi - l) * yhat = 0 + // gr = (xi - xj + r) * that = 0 + // + // ...where: + // l is the localOffsetB vector rotated to world in bodyA frame + // r is the same vector but reversed and rotated from bodyB frame + // xhat, yhat are world axis vectors + // that is the tangent of r + // + // For the first two constraints, we get + // G*W = (vj - vi - ldot ) * xhat + // = (vj - vi - wi x l) * xhat + // + // Since (wi x l) * xhat = (l x xhat) * wi, we get + // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] + // + // The last constraint gives + // GW = (vi - vj + wj x r) * that + // = [ that 0 -that (r x t) ] + + var x = new Equation(bodyA,bodyB,-maxForce,maxForce), + y = new Equation(bodyA,bodyB,-maxForce,maxForce), + rot = new Equation(bodyA,bodyB,-maxForce,maxForce); + + var l = vec2.create(), + g = vec2.create(), + that = this; + x.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[0]; + }; + y.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[1]; + }; + var r = vec2.create(), + t = vec2.create(); + rot.computeGq = function(){ + vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); + vec2.scale(r,r,-1); + vec2.sub(g,bodyA.position,bodyB.position); + vec2.add(g,g,r); + vec2.rotate(t,r,-Math.PI/2); + vec2.normalize(t,t); + return vec2.dot(g,t); + }; + + /** + * The offset of bodyB in bodyA's frame. + * @property {Array} localOffsetB + */ + this.localOffsetB = vec2.create(); + if(options.localOffsetB){ + vec2.copy(this.localOffsetB, options.localOffsetB); + } else { + // Construct from current positions + vec2.sub(this.localOffsetB, bodyB.position, bodyA.position); + vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle); + } + + /** + * The offset angle of bodyB in bodyA's frame. + * @property {Number} localAngleB + */ + this.localAngleB = 0; + if(typeof(options.localAngleB) === 'number'){ + this.localAngleB = options.localAngleB; + } else { + // Construct + this.localAngleB = bodyB.angle - bodyA.angle; + } + + this.equations.push(x, y, rot); + this.setMaxForce(maxForce); +} +LockConstraint.prototype = new Constraint(); +LockConstraint.prototype.constructor = LockConstraint; + +/** + * Set the maximum force to be applied. + * @method setMaxForce + * @param {Number} force + */ +LockConstraint.prototype.setMaxForce = function(force){ + var eqs = this.equations; + for(var i=0; ithis tutorial. Also called "slider constraint". + * + * @class PrismaticConstraint + * @constructor + * @extends Constraint + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.maxForce] Max force to be applied by the constraint + * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. + * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. + * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. + * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. + * @param {Number} [options.upperLimit] + * @param {Number} [options.lowerLimit] + * @todo Ability to create using only a point and a worldAxis + */ +function PrismaticConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); + + // Get anchors + var localAnchorA = vec2.fromValues(0,0), + localAxisA = vec2.fromValues(1,0), + localAnchorB = vec2.fromValues(0,0); + if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); } + if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); } + if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); } + + /** + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = localAnchorA; + + /** + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = localAnchorB; + + /** + * @property localAxisA + * @type {Array} + */ + this.localAxisA = localAxisA; + + /* + + The constraint violation for the common axis point is + + g = ( xj + rj - xi - ri ) * t := gg*t + + where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. + + gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) + + Note the use of the chain rule. Now we identify the jacobian + + G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] + + The rotational part is just a rotation lock. + + */ + + var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE; + + // Translational part + var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); + var ri = new vec2.create(), + rj = new vec2.create(), + gg = new vec2.create(), + t = new vec2.create(); + trans.computeGq = function(){ + // g = ( xj + rj - xi - ri ) * t + return vec2.dot(gg,t); + }; + trans.updateJacobian = function(){ + var G = this.G, + xi = bodyA.position, + xj = bodyB.position; + vec2.rotate(ri,localAnchorA,bodyA.angle); + vec2.rotate(rj,localAnchorB,bodyB.angle); + vec2.add(gg,xj,rj); + vec2.sub(gg,gg,xi); + vec2.sub(gg,gg,ri); + vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); + + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + }; + this.equations.push(trans); + + // Rotational part + if(!options.disableRotationalLock){ + var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); + this.equations.push(rot); + } + + /** + * The position of anchor A relative to anchor B, along the constraint axis. + * @property position + * @type {Number} + */ + this.position = 0; + + // Is this one used at all? + this.velocity = 0; + + /** + * Set to true to enable lower limit. + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; + + /** + * Set to true to enable upper limit. + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; + + /** + * Lower constraint limit. The constraint position is forced to be larger than this value. + * @property lowerLimit + * @type {Number} + */ + this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; + + /** + * Upper constraint limit. The constraint position is forced to be smaller than this value. + * @property upperLimit + * @type {Number} + */ + this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; + + // Equations used for limits + this.upperLimitEquation = new ContactEquation(bodyA,bodyB); + this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); + + // Set max/min forces + this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; + this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; + + /** + * Equation used for the motor. + * @property motorEquation + * @type {Equation} + */ + this.motorEquation = new Equation(bodyA,bodyB); + + /** + * The current motor state. Enable or disable the motor using .enableMotor + * @property motorEnabled + * @type {Boolean} + */ + this.motorEnabled = false; + + /** + * Set the target speed for the motor. + * @property motorSpeed + * @type {Number} + */ + this.motorSpeed = 0; + + var that = this; + var motorEquation = this.motorEquation; + var old = motorEquation.computeGW; + motorEquation.computeGq = function(){ return 0; }; + motorEquation.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed; + }; +} + +PrismaticConstraint.prototype = new Constraint(); +PrismaticConstraint.prototype.constructor = PrismaticConstraint; + +var worldAxisA = vec2.create(), + worldAnchorA = vec2.create(), + worldAnchorB = vec2.create(), + orientedAnchorA = vec2.create(), + orientedAnchorB = vec2.create(), + tmp = vec2.create(); + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +PrismaticConstraint.prototype.update = function(){ + var eqs = this.equations, + trans = eqs[0], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation, + bodyA = this.bodyA, + bodyB = this.bodyB, + localAxisA = this.localAxisA, + localAnchorA = this.localAnchorA, + localAnchorB = this.localAnchorB; + + trans.updateJacobian(); + + // Transform local things to world + vec2.rotate(worldAxisA, localAxisA, bodyA.angle); + vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); + vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); + vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); + vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); + + var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); + + // Motor + if(this.motorEnabled){ + // G = [ a a x ri -a -a x rj ] + var G = this.motorEquation.G; + G[0] = worldAxisA[0]; + G[1] = worldAxisA[1]; + G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); + G[3] = -worldAxisA[0]; + G[4] = -worldAxisA[1]; + G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); + } + + /* + Limits strategy: + Add contact equation, with normal along the constraint axis. + min/maxForce is set so the constraint is repulsive in the correct direction. + Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. + + ^ + | + upperLimit x + | ------ + anchorB x<---| B | + | | | + ------ | ------ + | | | + | A |-->x anchorA + ------ | + x lowerLimit + | + axis + */ + + + if(this.upperLimitEnabled && relPosition > upperLimit){ + // Update contact constraint normal, etc + 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 && relPosition < lowerLimit){ + // Update contact constraint normal, etc + vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); + vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); + vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); + vec2.scale(tmp,worldAxisA,lowerLimit); + vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } +}; + +/** + * Enable the motor + * @method enableMotor + */ +PrismaticConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +PrismaticConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the constraint limits. + * @method setLimits + * @param {number} lower Lower limit. + * @param {number} upper Upper limit. + */ +PrismaticConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + + +},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation') +, RotationalLockEquation = _dereq_('../equations/RotationalLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = RevoluteConstraint; + +var worldPivotA = vec2.create(), + worldPivotB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1), + g = vec2.create(); + +/** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * @class RevoluteConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to. + * @param {Array} [options.localPivotB] See localPivotA. + * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. + * @extends Constraint + * + * @example + * // This will create a revolute constraint between two bodies with pivot point in between them. + * var bodyA = new Body({ mass: 1, position: [-1, 0] }); + * var bodyB = new Body({ mass: 1, position: [1, 0] }); + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * worldPivot: [0, 0] + * }); + * world.addConstraint(constraint); + * + * // Using body-local pivot points, the constraint could have been constructed like this: + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * localPivotA: [1, 0], + * localPivotB: [-1, 0] + * }); + */ +function RevoluteConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); + + var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; + + /** + * @property {Array} pivotA + */ + this.pivotA = vec2.create(); + + /** + * @property {Array} pivotB + */ + this.pivotB = vec2.create(); + + if(options.worldPivot){ + // Compute pivotA and pivotB + vec2.sub(this.pivotA, options.worldPivot, bodyA.position); + vec2.sub(this.pivotB, options.worldPivot, bodyB.position); + // Rotate to local coordinate system + vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle); + vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle); + } else { + // Get pivotA and pivotB + vec2.copy(this.pivotA, options.localPivotA); + vec2.copy(this.pivotB, options.localPivotB); + } + + // Equations to be fed to the solver + var eqs = this.equations = [ + new Equation(bodyA,bodyB,-maxForce,maxForce), + new Equation(bodyA,bodyB,-maxForce,maxForce), + ]; + + var x = eqs[0]; + var y = eqs[1]; + var that = this; + + x.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,xAxis); + }; + + y.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,yAxis); + }; + + y.minForce = x.minForce = -maxForce; + y.maxForce = x.maxForce = maxForce; + + this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); + + /** + * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. + * @property {Boolean} motorEnabled + * @readOnly + */ + this.motorEnabled = false; + + /** + * The constraint position. + * @property angle + * @type {Number} + * @readOnly + */ + this.angle = 0; + + /** + * Set to true to enable lower limit + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = false; + + /** + * Set to true to enable upper limit + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = false; + + /** + * The lower limit on the constraint angle. + * @property lowerLimit + * @type {Boolean} + */ + this.lowerLimit = 0; + + /** + * The upper limit on the constraint angle. + * @property upperLimit + * @type {Boolean} + */ + this.upperLimit = 0; + + this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.upperLimitEquation.minForce = 0; + this.lowerLimitEquation.maxForce = 0; +} +RevoluteConstraint.prototype = new Constraint(); +RevoluteConstraint.prototype.constructor = RevoluteConstraint; + +/** + * Set the constraint angle limits. + * @method setLimits + * @param {number} lower Lower angle limit. + * @param {number} upper Upper angle limit. + */ +RevoluteConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + +RevoluteConstraint.prototype.update = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + pivotA = this.pivotA, + pivotB = this.pivotB, + eqs = this.equations, + normal = eqs[0], + tangent= eqs[1], + x = eqs[0], + y = eqs[1], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation; + + var relAngle = this.angle = bodyB.angle - bodyA.angle; + + if(this.upperLimitEnabled && relAngle > upperLimit){ + 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 < lowerLimit){ + lowerLimitEquation.angle = lowerLimit; + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } + + /* + + The constraint violation is + + g = xj + rj - xi - ri + + ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: + + gdot = vj + wj x rj - vi - wi x ri + + We split this into x and y directions. (let x and y be unit vectors along the respective axes) + + gdot * x = ( vj + wj x rj - vi - wi x ri ) * x + = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x + = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi + = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] + = G*W + + ...and similar for y. We have then identified the jacobian entries for x and y directions: + + Gx = [ x (rj x x) -x -(ri x x)] + Gy = [ y (rj x y) -y -(ri x y)] + + */ + + vec2.rotate(worldPivotA, pivotA, bodyA.angle); + vec2.rotate(worldPivotB, pivotB, bodyB.angle); + + // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc + + x.G[0] = -1; + x.G[1] = 0; + x.G[2] = -vec2.crossLength(worldPivotA,xAxis); + x.G[3] = 1; + x.G[4] = 0; + x.G[5] = vec2.crossLength(worldPivotB,xAxis); + + y.G[0] = 0; + y.G[1] = -1; + y.G[2] = -vec2.crossLength(worldPivotA,yAxis); + y.G[3] = 0; + y.G[4] = 1; + y.G[5] = vec2.crossLength(worldPivotB,yAxis); +}; + +/** + * Enable the rotational motor + * @method enableMotor + */ +RevoluteConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +RevoluteConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the speed of the rotational constraint motor + * @method setMotorSpeed + * @param {Number} speed + */ +RevoluteConstraint.prototype.setMotorSpeed = function(speed){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations[i].relativeVelocity = speed; +}; + +/** + * Get the speed of the rotational constraint motor + * @method getMotorSpeed + * @return {Number} The current speed, or false if the motor is not enabled. + */ +RevoluteConstraint.prototype.getMotorSpeed = function(){ + if(!this.motorEnabled){ + return false; + } + return this.motorEquation.relativeVelocity; +}; + +},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = AngleLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class AngleLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in body A. + * @param {Number} [options.ratio] Gear ratio + */ +function AngleLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); + this.angle = options.angle || 0; + + /** + * The gear ratio. + * @property {Number} ratio + * @private + * @see setRatio + */ + this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; + + this.setRatio(this.ratio); +} +AngleLockEquation.prototype = new Equation(); +AngleLockEquation.prototype.constructor = AngleLockEquation; + +AngleLockEquation.prototype.computeGq = function(){ + return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; +}; + +/** + * Set the gear ratio for this equation + * @method setRatio + * @param {Number} ratio + */ +AngleLockEquation.prototype.setRatio = function(ratio){ + var G = this.G; + G[2] = ratio; + G[5] = -1; + this.ratio = ratio; +}; + +/** + * Set the max force for the equation. + * @method setMaxTorque + * @param {Number} torque + */ +AngleLockEquation.prototype.setMaxTorque = function(torque){ + this.maxForce = torque; + this.minForce = -torque; +}; + +},{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = ContactEquation; + +/** + * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive. + * + * @class ContactEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function ContactEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); + + /** + * Vector from body i center of mass to the contact point. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + this.penetrationVec = vec2.create(); + + /** + * World-oriented vector from body A center of mass to the contact point. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * The normal vector, pointing out of body i + * @property normalA + * @type {Array} + */ + this.normalA = vec2.create(); + + /** + * The restitution to use (0=no bounciness, 1=max bounciness). + * @property restitution + * @type {Number} + */ + this.restitution = 0; + + /** + * This property is set to true if this is the first impact between the bodies (not persistant contact). + * @property firstImpact + * @type {Boolean} + * @readOnly + */ + this.firstImpact = false; + + /** + * The shape in body i that triggered this contact. + * @property shapeA + * @type {Shape} + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this contact. + * @property shapeB + * @type {Shape} + */ + this.shapeB = null; +} +ContactEquation.prototype = new Equation(); +ContactEquation.prototype.constructor = ContactEquation; +ContactEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + xi = bi.position, + xj = bj.position; + + var penetrationVec = this.penetrationVec, + n = this.normalA, + G = this.G; + + // Caluclate cross products + var rixn = vec2.crossLength(ri,n), + rjxn = vec2.crossLength(rj,n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; + + // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector + vec2.add(penetrationVec,xj,rj); + vec2.sub(penetrationVec,penetrationVec,xi); + vec2.sub(penetrationVec,penetrationVec,ri); + + // Compute iteration + var GW, Gq; + if(this.firstImpact && this.restitution !== 0){ + Gq = 0; + GW = (1/b)*(1+this.restitution) * this.computeGW(); + } else { + Gq = vec2.dot(n,penetrationVec) + this.offset; + GW = this.computeGW(); + } + + var GiMf = this.computeGiMf(); + var B = - Gq * a - GW * b - h*GiMf; + + return B; +}; + +var vi = vec2.create(); +var vj = vec2.create(); +var relVel = vec2.create(); + +/** + * Get the relative velocity along the normal vector. + * @return {number} + */ +ContactEquation.prototype.getVelocityAlongNormal = function(){ + + this.bodyA.getVelocityAtPoint(vi, this.contactPointA); + this.bodyB.getVelocityAtPoint(vj, this.contactPointB); + + vec2.subtract(relVel, vi, vj); + + return vec2.dot(this.normalA, relVel); +}; +},{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){ +module.exports = Equation; + +var vec2 = _dereq_('../math/vec2'), + Utils = _dereq_('../utils/Utils'), + Body = _dereq_('../objects/Body'); + +/** + * Base class for constraint equations. + * @class Equation + * @constructor + * @param {Body} bodyA First body participating in the equation + * @param {Body} bodyB Second body participating in the equation + * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE + * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE + */ +function Equation(bodyA, bodyB, minForce, maxForce){ + + /** + * Minimum force to apply when solving. + * @property minForce + * @type {Number} + */ + this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; + + /** + * Max force to apply when solving. + * @property maxForce + * @type {Number} + */ + this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; + + /** + * First body participating in the constraint + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second body participating in the constraint + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; + + /** + * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. + * @property stiffness + * @type {Number} + */ + this.stiffness = Equation.DEFAULT_STIFFNESS; + + /** + * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. + * @property relaxation + * @type {Number} + */ + this.relaxation = Equation.DEFAULT_RELAXATION; + + /** + * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). + * @property G + * @type {Array} + */ + this.G = new Utils.ARRAY_TYPE(6); + for(var i=0; i<6; i++){ + this.G[i]=0; + } + + this.offset = 0; + + this.a = 0; + this.b = 0; + this.epsilon = 0; + this.timeStep = 1/60; + + /** + * Indicates if stiffness or relaxation was changed. + * @property {Boolean} needsUpdate + */ + this.needsUpdate = true; + + /** + * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. + * @property multiplier + * @type {Number} + */ + this.multiplier = 0; + + /** + * Relative velocity. + * @property {Number} relativeVelocity + */ + this.relativeVelocity = 0; + + /** + * Whether this equation is enabled or not. If true, it will be added to the solver. + * @property {Boolean} enabled + */ + this.enabled = true; +} +Equation.prototype.constructor = Equation; + +/** + * The default stiffness when creating a new Equation. + * @static + * @property {Number} DEFAULT_STIFFNESS + * @default 1e6 + */ +Equation.DEFAULT_STIFFNESS = 1e6; + +/** + * The default relaxation when creating a new Equation. + * @static + * @property {Number} DEFAULT_RELAXATION + * @default 4 + */ +Equation.DEFAULT_RELAXATION = 4; + +/** + * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the SPOOK notes. + * @method update + */ +Equation.prototype.update = function(){ + var k = this.stiffness, + d = this.relaxation, + h = this.timeStep; + + this.a = 4.0 / (h * (1 + 4 * d)); + this.b = (4.0 * d) / (1 + 4 * d); + this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); + + this.needsUpdate = false; +}; + +/** + * Multiply a jacobian entry with corresponding positions or velocities + * @method gmult + * @return {Number} + */ +Equation.prototype.gmult = function(G,vi,wi,vj,wj){ + return G[0] * vi[0] + + G[1] * vi[1] + + G[2] * wi + + G[3] * vj[0] + + G[4] * vj[1] + + G[5] * wj; +}; + +/** + * Computes the RHS of the SPOOK equation + * @method computeB + * @return {Number} + */ +Equation.prototype.computeB = function(a,b,h){ + var GW = this.computeGW(); + var Gq = this.computeGq(); + var GiMf = this.computeGiMf(); + return - Gq * a - GW * b - GiMf*h; +}; + +/** + * Computes G\*q, where q are the generalized body coordinates + * @method computeGq + * @return {Number} + */ +var qi = vec2.create(), + qj = vec2.create(); +Equation.prototype.computeGq = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + xi = bi.position, + xj = bj.position, + ai = bi.angle, + aj = bj.angle; + + return this.gmult(G, qi, ai, qj, aj) + this.offset; +}; + +/** + * Computes G\*W, where W are the body velocities + * @method computeGW + * @return {Number} + */ +Equation.prototype.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity; +}; + +/** + * Computes G\*Wlambda, where W are the body velocities + * @method computeGWlambda + * @return {Number} + */ +Equation.prototype.computeGWlambda = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.vlambda, + vj = bj.vlambda, + wi = bi.wlambda, + wj = bj.wlambda; + return this.gmult(G,vi,wi,vj,wj); +}; + +/** + * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. + * @method computeGiMf + * @return {Number} + */ +var iMfi = vec2.create(), + iMfj = vec2.create(); +Equation.prototype.computeGiMf = function(){ + var bi = this.bodyA, + bj = this.bodyB, + fi = bi.force, + ti = bi.angularForce, + fj = bj.force, + tj = bj.angularForce, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + vec2.scale(iMfi, fi, invMassi); + vec2.multiply(iMfi, bi.massMultiplier, iMfi); + vec2.scale(iMfj, fj,invMassj); + vec2.multiply(iMfj, bj.massMultiplier, iMfj); + + return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); +}; + +/** + * Computes G\*inv(M)\*G' + * @method computeGiMGt + * @return {Number} + */ +Equation.prototype.computeGiMGt = function(){ + var bi = this.bodyA, + bj = this.bodyB, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + return G[0] * G[0] * invMassi * bi.massMultiplier[0] + + G[1] * G[1] * invMassi * bi.massMultiplier[1] + + G[2] * G[2] * invIi + + G[3] * G[3] * invMassj * bj.massMultiplier[0] + + G[4] * G[4] * invMassj * bj.massMultiplier[1] + + G[5] * G[5] * invIj; +}; + +var addToWlambda_temp = vec2.create(), + addToWlambda_Gi = vec2.create(), + addToWlambda_Gj = vec2.create(), + addToWlambda_ri = vec2.create(), + addToWlambda_rj = vec2.create(), + addToWlambda_Mdiag = vec2.create(); + +/** + * Add constraint velocity to the bodies. + * @method addToWlambda + * @param {Number} deltalambda + */ +Equation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bodyA, + bj = this.bodyB, + temp = addToWlambda_temp, + Gi = addToWlambda_Gi, + Gj = addToWlambda_Gj, + ri = addToWlambda_ri, + rj = addToWlambda_rj, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + Mdiag = addToWlambda_Mdiag, + G = this.G; + + Gi[0] = G[0]; + Gi[1] = G[1]; + Gj[0] = G[3]; + Gj[1] = G[4]; + + // Add to linear velocity + // v_lambda += inv(M) * delta_lamba * G + vec2.scale(temp, Gi, invMassi*deltalambda); + vec2.multiply(temp, temp, bi.massMultiplier); + vec2.add( bi.vlambda, bi.vlambda, temp); + // This impulse is in the offset frame + // Also add contribution to angular + //bi.wlambda -= vec2.crossLength(temp,ri); + bi.wlambda += invIi * G[2] * deltalambda; + + + vec2.scale(temp, Gj, invMassj*deltalambda); + vec2.multiply(temp, temp, bj.massMultiplier); + vec2.add( bj.vlambda, bj.vlambda, temp); + //bj.wlambda -= vec2.crossLength(temp,rj); + bj.wlambda += invIj * G[5] * deltalambda; +}; + +/** + * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps + * @method computeInvC + * @param {Number} eps + * @return {Number} + */ +Equation.prototype.computeInvC = function(eps){ + return 1.0 / (this.computeGiMGt() + eps); +}; + +},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('./Equation') +, Utils = _dereq_('../utils/Utils'); + +module.exports = FrictionEquation; + +/** + * Constrains the slipping in a contact along a tangent + * + * @class FrictionEquation + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Number} slipForce + * @extends Equation + */ +function FrictionEquation(bodyA, bodyB, slipForce){ + Equation.call(this, bodyA, bodyB, -slipForce, slipForce); + + /** + * Relative vector from center of body A to the contact point, world oriented. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + + /** + * Relative vector from center of body B to the contact point, world oriented. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * Tangent vector that the friction force will act along. World oriented. + * @property t + * @type {Array} + */ + this.t = vec2.create(); + + /** + * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average. + * @property contactEquations + * @type {ContactEquation} + */ + this.contactEquations = []; + + /** + * The shape in body i that triggered this friction. + * @property shapeA + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeA... + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this friction. + * @property shapeB + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeB... + */ + this.shapeB = null; + + /** + * The friction coefficient to use. + * @property frictionCoefficient + * @type {Number} + */ + this.frictionCoefficient = 0.3; +} +FrictionEquation.prototype = new Equation(); +FrictionEquation.prototype.constructor = FrictionEquation; + +/** + * Set the slipping condition for the constraint. The friction force cannot be + * larger than this value. + * @method setSlipForce + * @param {Number} slipForce + */ +FrictionEquation.prototype.setSlipForce = function(slipForce){ + this.maxForce = slipForce; + this.minForce = -slipForce; +}; + +/** + * Get the max force for the constraint. + * @method getSlipForce + * @return {Number} + */ +FrictionEquation.prototype.getSlipForce = function(){ + return this.maxForce; +}; + +FrictionEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + t = this.t, + G = this.G; + + // G = [-t -rixt t rjxt] + // And remember, this is a pure velocity constraint, g is always zero! + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + + var GW = this.computeGW(), + GiMf = this.computeGiMf(); + + var B = /* - g * a */ - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class RotationalLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in bodyA. + */ +function RotationalLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + + /** + * @property {number} angle + */ + this.angle = options.angle || 0; + + var G = this.G; + G[2] = 1; + G[5] = -1; +} +RotationalLockEquation.prototype = new Equation(); +RotationalLockEquation.prototype.constructor = RotationalLockEquation; + +var worldVectorA = vec2.create(), + worldVectorB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1); +RotationalLockEquation.prototype.computeGq = function(){ + vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); + vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); + return vec2.dot(worldVectorA,worldVectorB); +}; + +},{"../math/vec2":30,"./Equation":22}],25:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalVelocityEquation; + +/** + * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). + * + * @class RotationalVelocityEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function RotationalVelocityEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + this.relativeVelocity = 1; + this.ratio = 1; +} +RotationalVelocityEquation.prototype = new Equation(); +RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; +RotationalVelocityEquation.prototype.computeB = function(a,b,h){ + var G = this.G; + G[2] = -1; + G[5] = this.ratio; + + var GiMf = this.computeGiMf(); + var GW = this.computeGW(); + var B = - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"./Equation":22}],26:[function(_dereq_,module,exports){ +/** + * Base class for objects that dispatches events. + * @class EventEmitter + * @constructor + */ +var EventEmitter = function () {}; + +module.exports = EventEmitter; + +EventEmitter.prototype = { + constructor: EventEmitter, + + /** + * Add an event listener + * @method on + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + on: function ( type, listener, context ) { + listener.context = context || this; + if ( this._listeners === undefined ){ + this._listeners = {}; + } + var listeners = this._listeners; + if ( listeners[ type ] === undefined ) { + listeners[ type ] = []; + } + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + listeners[ type ].push( listener ); + } + return this; + }, + + /** + * Check if an event listener is added + * @method has + * @param {String} type + * @param {Function} listener + * @return {Boolean} + */ + has: function ( type, listener ) { + if ( this._listeners === undefined ){ + return false; + } + var listeners = this._listeners; + if(listener){ + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + return true; + } + } else { + if ( listeners[ type ] !== undefined ) { + return true; + } + } + + return false; + }, + + /** + * Remove an event listener + * @method off + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + off: function ( type, listener ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var index = listeners[ type ].indexOf( listener ); + if ( index !== - 1 ) { + listeners[ type ].splice( index, 1 ); + } + return this; + }, + + /** + * Emit an event. + * @method emit + * @param {Object} event + * @param {String} event.type + * @return {EventEmitter} The self object, for chainability. + */ + emit: function ( event ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; + if ( listenerArray !== undefined ) { + event.target = this; + for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { + var listener = listenerArray[ i ]; + listener.call( listener.context, event ); + } + } + return this; + } +}; + +},{}],27:[function(_dereq_,module,exports){ +var Material = _dereq_('./Material'); +var Equation = _dereq_('../equations/Equation'); + +module.exports = ContactMaterial; + +/** + * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. + * @class ContactMaterial + * @constructor + * @param {Material} materialA + * @param {Material} materialB + * @param {Object} [options] + * @param {Number} [options.friction=0.3] Friction coefficient. + * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". + * @param {Number} [options.stiffness] ContactEquation stiffness. + * @param {Number} [options.relaxation] ContactEquation relaxation. + * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. + * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. + * @param {Number} [options.surfaceVelocity=0] Surface velocity. + * @author schteppe + */ +function ContactMaterial(materialA, materialB, options){ + options = options || {}; + + if(!(materialA instanceof Material) || !(materialB instanceof Material)){ + throw new Error("First two arguments must be Material instances."); + } + + /** + * The contact material identifier + * @property id + * @type {Number} + */ + this.id = ContactMaterial.idCounter++; + + /** + * First material participating in the contact material + * @property materialA + * @type {Material} + */ + this.materialA = materialA; + + /** + * Second material participating in the contact material + * @property materialB + * @type {Material} + */ + this.materialB = materialB; + + /** + * Friction coefficient to use in the contact of these two materials. Friction = 0 will make the involved objects super slippery, and friction = 1 will make it much less slippery. A friction coefficient larger than 1 will allow for very large friction forces, which can be convenient for preventing car tires not slip on the ground. + * @property friction + * @type {Number} + * @default 0.3 + */ + this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; + + /** + * Restitution, or "bounciness" to use in the contact of these two materials. A restitution of 0 will make no bounce, while restitution=1 will approximately bounce back with the same velocity the object came with. + * @property restitution + * @type {Number} + * @default 0 + */ + this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0; + + /** + * Hardness of the contact. Less stiffness will make the objects penetrate more, and will make the contact act more like a spring than a contact force. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property stiffness + * @type {Number} + */ + this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting ContactEquation that this ContactMaterial generate. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property relaxation + * @type {Number} + */ + this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Stiffness of the resulting friction force. For most cases, the value of this property should be a large number. I cannot think of any case where you would want less frictionStiffness. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property frictionStiffness + * @type {Number} + */ + this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting friction force. The default value should be good for most simulations. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property frictionRelaxation + * @type {Number} + */ + this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + * @property {Number} surfaceVelocity + * @default 0 + */ + this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; + + /** + * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts". + * @property contactSkinSize + * @type {Number} + */ + this.contactSkinSize = 0.005; +} + +ContactMaterial.idCounter = 0; + +},{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){ +module.exports = Material; + +/** + * Defines a physics material. + * @class Material + * @constructor + * @param {number} id Material identifier + * @author schteppe + */ +function Material(id){ + /** + * The material identifier + * @property id + * @type {Number} + */ + this.id = id || Material.idCounter++; +} + +Material.idCounter = 0; + +},{}],29:[function(_dereq_,module,exports){ + + /* + PolyK library + url: http://polyk.ivank.net + Released under MIT licence. + + Copyright (c) 2012 Ivan Kuckir + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + */ + + var PolyK = {}; + + /* + Is Polygon self-intersecting? + + O(n^2) + */ + /* + PolyK.IsSimple = function(p) + { + var n = p.length>>1; + if(n<4) return true; + var a1 = new PolyK._P(), a2 = new PolyK._P(); + var b1 = new PolyK._P(), b2 = new PolyK._P(); + var c = new PolyK._P(); + + for(var i=0; i>1; + if(n<3) return []; + var tgs = []; + var avl = []; + for(var i=0; i 3) + { + 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; j 3*al) break; // no convex angles :( + } + tgs.push(avl[0], avl[1], avl[2]); + return tgs; + } + /* + PolyK.ContainsPoint = function(p, px, py) + { + var n = p.length>>1; + var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; + var depth = 0; + for(var i=0; i=0 && by>=0) continue; // both "up" or both "donw" + if(ax< 0 && bx< 0) continue; + + var lx = ax + (bx-ax)*(-ay)/(by-ay); + if(lx>0) depth++; + } + return (depth & 1) == 1; + } + + PolyK.Slice = function(p, ax, ay, bx, by) + { + if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; + + var a = new PolyK._P(ax, ay); + var b = new PolyK._P(bx, by); + var iscs = []; // intersections + var ps = []; // points + for(var i=0; i 0) + { + var n = ps.length; + var i0 = iscs[0]; + var i1 = iscs[1]; + var ind0 = ps.indexOf(i0); + var ind1 = ps.indexOf(i1); + var solved = false; + + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + else + { + i0 = iscs[1]; + i1 = iscs[0]; + ind0 = ps.indexOf(i0); + ind1 = ps.indexOf(i1); + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + } + if(solved) + { + dir--; + var pgn = PolyK._getPoints(ps, ind0, ind1); + pgs.push(pgn); + ps = PolyK._getPoints(ps, ind1, ind0); + i0.flag = i1.flag = false; + iscs.splice(0,2); + if(iscs.length == 0) pgs.push(ps); + } + else { dir++; iscs.reverse(); } + if(dir>1) break; + } + var result = []; + for(var i=0; i>1, isc); + } + b1.x = b2.x; b1.y = b2.y; + b2.x = p[0]; b2.y = p[1]; + PolyK._pointLineDist(a1, b1, b2, l>>1, isc); + + var idst = 1/isc.dist; + isc.norm.x = (x-isc.point.x)*idst; + isc.norm.y = (y-isc.point.y)*idst; + return isc; + } + + PolyK._pointLineDist = function(p, a, b, edge, isc) + { + var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; + + var A = x - x1; + var B = y - y1; + var C = x2 - x1; + var D = y2 - y1; + + var dot = A * C + B * D; + var len_sq = C * C + D * D; + var param = dot / len_sq; + + var xx, yy; + + if (param < 0 || (x1 == x2 && y1 == y2)) { + xx = x1; + yy = y1; + } + else if (param > 1) { + xx = x2; + yy = y2; + } + else { + xx = x1 + param * C; + yy = y1 + param * D; + } + + var dx = x - xx; + var dy = y - yy; + var dst = Math.sqrt(dx * dx + dy * dy); + if(dst= 0) && (v >= 0) && (u + v < 1); + } + /* + PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) + { + var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); + var day = (a1.y-a2.y), dby = (b1.y-b2.y); + + var Den = dax*dby - day*dbx; + if (Den == 0) return null; // parallel + + var A = (a1.x * a2.y - a1.y * a2.x); + var B = (b1.x * b2.y - b1.y * b2.x); + + var I = c; + var iDen = 1/Den; + I.x = ( A*dbx - dax*B ) * iDen; + I.y = ( A*dby - day*B ) * iDen; + + if(!PolyK._InRect(I, b1, b2)) return null; + if((day>0 && I.y>a1.y) || (day<0 && I.y0 && I.x>a1.x) || (dax<0 && I.x=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); + if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); + + if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) + && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) + return true; + return false; + } + */ + PolyK._convex = function(ax, ay, bx, by, cx, cy) + { + return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; + } + /* + PolyK._P = function(x,y) + { + this.x = x; + this.y = y; + this.flag = false; + } + PolyK._P.prototype.toString = function() + { + return "Point ["+this.x+", "+this.y+"]"; + } + PolyK._P.dist = function(a,b) + { + var dx = b.x-a.x; + var dy = b.y-a.y; + return Math.sqrt(dx*dx + dy*dy); + } + + PolyK._tp = []; + for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); + */ + +module.exports = PolyK; + +},{}],30:[function(_dereq_,module,exports){ +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. + * @class vec2 + */ + +var vec2 = module.exports = {}; + +var Utils = _dereq_('../utils/Utils'); + +/** + * Make a cross product and only return the z component + * @method crossLength + * @static + * @param {Array} a + * @param {Array} b + * @return {Number} + */ +vec2.crossLength = function(a,b){ + return a[0] * b[1] - a[1] * b[0]; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossVZ + * @static + * @param {Array} out + * @param {Array} vec + * @param {Number} zcomp + * @return {Number} + */ +vec2.crossVZ = function(out, vec, zcomp){ + vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossZV + * @static + * @param {Array} out + * @param {Number} zcomp + * @param {Array} vec + * @return {Number} + */ +vec2.crossZV = function(out, zcomp, vec){ + vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Rotate a vector by an angle + * @method rotate + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate = function(out,a,angle){ + if(angle !== 0){ + 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; + } else { + out[0] = a[0]; + out[1] = a[1]; + } +}; + +/** + * Rotate a vector 90 degrees clockwise + * @method rotate90cw + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate90cw = function(out, a) { + var x = a[0]; + var y = a[1]; + out[0] = y; + out[1] = -x; +}; + +/** + * Transform a point position to local frame. + * @method toLocalFrame + * @param {Array} out + * @param {Array} worldPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ + vec2.copy(out, worldPoint); + vec2.sub(out, out, framePosition); + vec2.rotate(out, out, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ + vec2.copy(out, localPoint); + vec2.rotate(out, out, frameAngle); + vec2.add(out, out, framePosition); +}; + +/** + * Transform a vector to local frame. + * @method vectorToLocalFrame + * @param {Array} out + * @param {Array} worldVector + * @param {Number} frameAngle + */ +vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ + vec2.rotate(out, worldVector, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localVector + * @param {Number} frameAngle + */ +vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){ + vec2.rotate(out, localVector, frameAngle); +}; + +/** + * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php + * @method centroid + * @static + * @param {Array} out + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Array} The out object + */ +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; +}; + +/** + * Creates a new, empty vec2 + * @static + * @method create + * @return {Array} a new 2D vector + */ +vec2.create = function() { + var out = new Utils.ARRAY_TYPE(2); + out[0] = 0; + out[1] = 0; + return out; +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * @static + * @method clone + * @param {Array} a vector to clone + * @return {Array} a new 2D vector + */ +vec2.clone = function(a) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Creates a new vec2 initialized with the given values + * @static + * @method fromValues + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} a new 2D vector + */ +vec2.fromValues = function(x, y) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Copy the values from one vec2 to another + * @static + * @method copy + * @param {Array} out the receiving vector + * @param {Array} a the source vector + * @return {Array} out + */ +vec2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * @static + * @method set + * @param {Array} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} out + */ +vec2.set = function(out, x, y) { + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Adds two vec2's + * @static + * @method add + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +}; + +/** + * Subtracts two vec2's + * @static + * @method subtract + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +}; + +/** + * Alias for vec2.subtract + * @static + * @method sub + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * @static + * @method multiply + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +}; + +/** + * Alias for vec2.multiply + * @static + * @method mul + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * @static + * @method divide + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +}; + +/** + * Alias for vec2.divide + * @static + * @method div + */ +vec2.div = vec2.divide; + +/** + * Scales a vec2 by a scalar number + * @static + * @method scale + * @param {Array} out the receiving vector + * @param {Array} a the vector to scale + * @param {Number} b amount to scale the vector by + * @return {Array} out + */ +vec2.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * @static + * @method distance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} distance between a and b + */ +vec2.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.distance + * @static + * @method dist + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * @static + * @method squaredDistance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} squared distance between a and b + */ +vec2.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredDistance + * @static + * @method sqrDist + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * @static + * @method length + * @param {Array} a vector to calculate length of + * @return {Number} length of a + */ +vec2.length = function (a) { + var x = a[0], + y = a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.length + * @method len + * @static + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * @static + * @method squaredLength + * @param {Array} a vector to calculate squared length of + * @return {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a[0], + y = a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredLength + * @static + * @method sqrLen + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * @static + * @method negate + * @param {Array} out the receiving vector + * @param {Array} a vector to negate + * @return {Array} out + */ +vec2.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +}; + +/** + * Normalize a vec2 + * @static + * @method normalize + * @param {Array} out the receiving vector + * @param {Array} a vector to normalize + * @return {Array} out + */ +vec2.normalize = function(out, a) { + var x = a[0], + y = a[1]; + var len = x*x + y*y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * @static + * @method dot + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1]; +}; + +/** + * Returns a string representation of a vector + * @static + * @method str + * @param {Array} vec vector to represent as a string + * @return {String} string representation of the vector + */ +vec2.str = function (a) { + return 'vec2(' + a[0] + ', ' + a[1] + ')'; +}; + +/** + * Linearly interpolate/mix two vectors. + * @static + * @method lerp + * @param {Array} out + * @param {Array} a First vector + * @param {Array} b Second vector + * @param {number} t Lerp factor + */ +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; +}; + +/** + * Reflect a vector along a normal. + * @static + * @method reflect + * @param {Array} out + * @param {Array} vector + * @param {Array} normal + */ +vec2.reflect = function(out, vector, normal){ + var dot = vector[0] * normal[0] + vector[1] * normal[1]; + out[0] = vector[0] - 2 * normal[0] * dot; + out[1] = vector[1] - 2 * normal[1] * dot; +}; + +/** + * Get the intersection point between two line segments. + * @static + * @method getLineSegmentsIntersection + * @param {Array} out + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {boolean} True if there was an intersection, otherwise false. + */ +vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { + var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); + if(t < 0){ + return false; + } else { + out[0] = p0[0] + (t * (p1[0] - p0[0])); + out[1] = p0[1] + (t * (p1[1] - p0[1])); + return true; + } +}; + +/** + * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) + * @static + * @method getLineSegmentsIntersectionFraction + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. + */ +vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { + var s1_x = p1[0] - p0[0]; + var s1_y = p1[1] - p0[1]; + var s2_x = p3[0] - p2[0]; + var s2_y = p3[1] - p2[1]; + + var s, t; + s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); + t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); + if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + return t; + } + return -1; // No collision +}; + +},{"../utils/Utils":57}],31:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, decomp = _dereq_('poly-decomp') +, Convex = _dereq_('../shapes/Convex') +, RaycastResult = _dereq_('../collision/RaycastResult') +, Ray = _dereq_('../collision/Ray') +, AABB = _dereq_('../collision/AABB') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Body; + +/** + * A rigid body. Has got a center of mass, position, velocity and a number of + * shapes that are used for collisions. + * + * @class Body + * @constructor + * @extends EventEmitter + * @param {Array} [options.force] + * @param {Array} [options.position] + * @param {Array} [options.velocity] + * @param {Boolean} [options.allowSleep] + * @param {Boolean} [options.collisionResponse] + * @param {Number} [options.angle=0] + * @param {Number} [options.angularForce=0] + * @param {Number} [options.angularVelocity=0] + * @param {Number} [options.ccdIterations=10] + * @param {Number} [options.ccdSpeedThreshold=-1] + * @param {Number} [options.fixedRotation=false] + * @param {Number} [options.gravityScale] + * @param {Number} [options.id] + * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. + * @param {Number} [options.sleepSpeedLimit] + * @param {Number} [options.sleepTimeLimit] + * @param {Object} [options] + * + * @example + * + * // Create a typical dynamic body + * var body = new Body({ + * mass: 1, + * position: [0, 0], + * angle: 0, + * velocity: [0, 0], + * angularVelocity: 0 + * }); + * + * // Add a circular shape to the body + * body.addShape(new Circle({ radius: 1 })); + * + * // Add the body to the world + * world.addBody(body); + */ +function Body(options){ + options = options || {}; + + EventEmitter.call(this); + + /** + * The body identifyer + * @property id + * @type {Number} + */ + this.id = options.id || ++Body._idCounter; + + /** + * The world that this body is added to. This property is set to NULL if the body is not added to any world. + * @property world + * @type {World} + */ + this.world = null; + + /** + * The shapes of the body. + * + * @property shapes + * @type {Array} + */ + this.shapes = []; + + /** + * The mass of the body. + * @property mass + * @type {number} + */ + this.mass = options.mass || 0; + + /** + * The inverse mass of the body. + * @property invMass + * @type {number} + */ + this.invMass = 0; + + /** + * The inertia of the body around the Z axis. + * @property inertia + * @type {number} + */ + this.inertia = 0; + + /** + * The inverse inertia of the body. + * @property invInertia + * @type {number} + */ + this.invInertia = 0; + + this.invMassSolve = 0; + this.invInertiaSolve = 0; + + /** + * Set to true if you want to fix the rotation of the body. + * @property fixedRotation + * @type {Boolean} + */ + this.fixedRotation = !!options.fixedRotation; + + /** + * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y. + * @property {Boolean} fixedX + */ + this.fixedX = !!options.fixedX; + + /** + * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X. + * @property {Boolean} fixedY + */ + this.fixedY = !!options.fixedY; + + /** + * @private + * @property {array} massMultiplier + */ + this.massMultiplier = vec2.create(); + + /** + * The position of the body + * @property position + * @type {Array} + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * The interpolated position of the body. Use this for rendering. + * @property interpolatedPosition + * @type {Array} + */ + this.interpolatedPosition = vec2.fromValues(0,0); + + /** + * The interpolated angle of the body. Use this for rendering. + * @property interpolatedAngle + * @type {Number} + */ + this.interpolatedAngle = 0; + + /** + * The previous position of the body. + * @property previousPosition + * @type {Array} + */ + this.previousPosition = vec2.fromValues(0,0); + + /** + * The previous angle of the body. + * @property previousAngle + * @type {Number} + */ + this.previousAngle = 0; + + /** + * The current velocity of the body. + * @property velocity + * @type {Array} + */ + this.velocity = vec2.fromValues(0,0); + if(options.velocity){ + vec2.copy(this.velocity, options.velocity); + } + + /** + * Constraint velocity that was added to the body during the last step. + * @property vlambda + * @type {Array} + */ + this.vlambda = vec2.fromValues(0,0); + + /** + * Angular constraint velocity that was added to the body during last step. + * @property wlambda + * @type {Array} + */ + this.wlambda = 0; + + /** + * The angle of the body, in radians. + * @property angle + * @type {number} + * @example + * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. + * // If you need a value between 0 and 2*pi, use the following function to normalize it. + * function normalizeAngle(angle){ + * angle = angle % (2*Math.PI); + * if(angle < 0){ + * angle += (2*Math.PI); + * } + * return angle; + * } + */ + this.angle = options.angle || 0; + + /** + * The angular velocity of the body, in radians per second. + * @property angularVelocity + * @type {number} + */ + this.angularVelocity = options.angularVelocity || 0; + + /** + * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. + * @property force + * @type {Array} + * + * @example + * // This produces a forcefield of 1 Newton in the positive x direction. + * for(var i=0; i radius){ + radius = offset + r; + } + } + + this.boundingRadius = radius; +}; + +/** + * Add a shape to the body. You can pass a local transform when adding a shape, + * so that the shape gets an offset and angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * + * @method addShape + * @param {Shape} shape + * @param {Array} [offset] Local body offset of the shape. + * @param {Number} [angle] Local body angle. + * + * @example + * var body = new Body(), + * shape = new Circle({ radius: 1 }); + * + * // Add the shape to the body, positioned in the center + * body.addShape(shape); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. + * body.addShape(shape,[1,0]); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. + * body.addShape(shape,[0,1],Math.PI/2); + */ +Body.prototype.addShape = function(shape, offset, angle){ + if(shape.body){ + throw new Error('A shape can only be added to one body.'); + } + shape.body = this; + + // Copy the offset vector + if(offset){ + vec2.copy(shape.position, offset); + } else { + vec2.set(shape.position, 0, 0); + } + + shape.angle = angle || 0; + + this.shapes.push(shape); + this.updateMassProperties(); + this.updateBoundingRadius(); + + this.aabbNeedsUpdate = true; +}; + +/** + * Remove a shape + * @method removeShape + * @param {Shape} shape + * @return {Boolean} True if the shape was found and removed, else false. + */ +Body.prototype.removeShape = function(shape){ + var idx = this.shapes.indexOf(shape); + + if(idx !== -1){ + this.shapes.splice(idx,1); + this.aabbNeedsUpdate = true; + shape.body = null; + return true; + } else { + return false; + } +}; + +/** + * Updates .inertia, .invMass, .invInertia for this Body. Should be called when + * changing the structure or mass of the Body. + * + * @method updateMassProperties + * + * @example + * body.mass += 1; + * body.updateMassProperties(); + */ +Body.prototype.updateMassProperties = function(){ + if(this.type === Body.STATIC || this.type === 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; + } + + // Inverse mass properties are easy + this.invMass = 1 / this.mass; + + vec2.set( + this.massMultiplier, + this.fixedX ? 0 : 1, + this.fixedY ? 0 : 1 + ); + } +}; + +var Body_applyForce_r = vec2.create(); + +/** + * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero. + * @method applyForce + * @param {Array} force The force to add. + * @param {Array} [relativePoint] A world point to apply the force on. + */ +Body.prototype.applyForce = function(force, relativePoint){ + + // Add linear force + vec2.add(this.force, this.force, force); + + if(relativePoint){ + + // Compute produced rotational force + var rotForce = vec2.crossLength(relativePoint,force); + + // Add rotational force + this.angularForce += rotForce; + } +}; + +/** + * Apply force to a body-local point. + * @method applyForceLocal + * @param {Array} localForce The force vector to add, oriented in local body space. + * @param {Array} [localPoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyForce_forceWorld = vec2.create(); +var Body_applyForce_pointWorld = vec2.create(); +var Body_applyForce_pointLocal = vec2.create(); +Body.prototype.applyForceLocal = function(localForce, localPoint){ + localPoint = localPoint || Body_applyForce_pointLocal; + var worldForce = Body_applyForce_forceWorld; + var worldPoint = Body_applyForce_pointWorld; + this.vectorToWorldFrame(worldForce, localForce); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyForce(worldForce, worldPoint); +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulse + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_velo = vec2.create(); +Body.prototype.applyImpulse = function(impulseVector, relativePoint){ + if(this.type !== Body.DYNAMIC){ + return; + } + + // Compute produced central impulse velocity + var velo = Body_applyImpulse_velo; + vec2.scale(velo, impulseVector, this.invMass); + vec2.multiply(velo, this.massMultiplier, velo); + + // Add linear impulse + vec2.add(this.velocity, velo, this.velocity); + + if(relativePoint){ + // Compute produced rotational impulse velocity + var rotVelo = vec2.crossLength(relativePoint, impulseVector); + rotVelo *= this.invInertia; + + // Add rotational Impulse + this.angularVelocity += rotVelo; + } +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulseLocal + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_impulseWorld = vec2.create(); +var Body_applyImpulse_pointWorld = vec2.create(); +var Body_applyImpulse_pointLocal = vec2.create(); +Body.prototype.applyImpulseLocal = function(localImpulse, localPoint){ + localPoint = localPoint || Body_applyImpulse_pointLocal; + var worldImpulse = Body_applyImpulse_impulseWorld; + var worldPoint = Body_applyImpulse_pointWorld; + this.vectorToWorldFrame(worldImpulse, localImpulse); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyImpulse(worldImpulse, worldPoint); +}; + +/** + * Transform a world point to local body frame. + * @method toLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldPoint The input world point + */ +Body.prototype.toLocalFrame = function(out, worldPoint){ + vec2.toLocalFrame(out, worldPoint, this.position, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method toWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localPoint The input local point + */ +Body.prototype.toWorldFrame = function(out, localPoint){ + vec2.toGlobalFrame(out, localPoint, this.position, this.angle); +}; + +/** + * Transform a world point to local body frame. + * @method vectorToLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldVector The input world vector + */ +Body.prototype.vectorToLocalFrame = function(out, worldVector){ + vec2.vectorToLocalFrame(out, worldVector, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method vectorToWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localVector The input local vector + */ +Body.prototype.vectorToWorldFrame = function(out, localVector){ + vec2.vectorToGlobalFrame(out, localVector, this.angle); +}; + +/** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. + * @method fromPolygon + * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. + * @param {Object} [options] + * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. + * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @return {Boolean} True on success, else false. + */ +Body.prototype.fromPolygon = function(path,options){ + options = options || {}; + + // Remove all shapes + for(var i=this.shapes.length; i>=0; --i){ + this.removeShape(this.shapes[i]); + } + + var p = new decomp.Polygon(); + p.vertices = path; + + // Make it counter-clockwise + p.makeCCW(); + + if(typeof(options.removeCollinearPoints) === "number"){ + p.removeCollinearPoints(options.removeCollinearPoints); + } + + // Check if any line segment intersects the path itself + if(typeof(options.skipSimpleCheck) === "undefined"){ + if(!p.isSimple()){ + return false; + } + } + + // Save this path for later + this.concavePath = p.vertices.slice(0); + for(var i=0; ithis for details. + * @method applyDamping + * @param {number} dt Current time step + */ +Body.prototype.applyDamping = function(dt){ + if(this.type === Body.DYNAMIC){ // Only for dynamic bodies + var v = this.velocity; + vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); + this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); + } +}; + +/** + * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. + * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. + * @method wakeUp + */ +Body.prototype.wakeUp = function(){ + var s = this.sleepState; + this.sleepState = Body.AWAKE; + this.idleTime = 0; + if(s !== Body.AWAKE){ + this.emit(Body.wakeUpEvent); + } +}; + +/** + * Force body sleep + * @method sleep + */ +Body.prototype.sleep = function(){ + this.sleepState = Body.SLEEPING; + this.angularVelocity = 0; + this.angularForce = 0; + vec2.set(this.velocity,0,0); + vec2.set(this.force,0,0); + this.emit(Body.sleepEvent); +}; + +/** + * Called every timestep to update internal sleep timer and change sleep state if needed. + * @method sleepTick + * @param {number} time The world time in seconds + * @param {boolean} dontSleep + * @param {number} dt + */ +Body.prototype.sleepTick = function(time, dontSleep, dt){ + if(!this.allowSleep || this.type === Body.SLEEPING){ + return; + } + + this.wantsToSleep = false; + + var sleepState = this.sleepState, + speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), + speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); + + // Add to idle time + if(speedSquared >= 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; + } + } +}; + +/** + * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. + * @method overlaps + * @param {Body} body + * @return {boolean} + */ +Body.prototype.overlaps = function(body){ + return this.world.overlapKeeper.bodiesAreOverlapping(this, body); +}; + +var integrate_fhMinv = vec2.create(); +var integrate_velodt = vec2.create(); + +/** + * Move the body forward in time given its current velocity. + * @method integrate + * @param {Number} dt + */ +Body.prototype.integrate = function(dt){ + var minv = this.invMass, + f = this.force, + pos = this.position, + velo = this.velocity; + + // Save old position + vec2.copy(this.previousPosition, this.position); + this.previousAngle = this.angle; + + // Velocity update + if(!this.fixedRotation){ + this.angularVelocity += this.angularForce * this.invInertia * dt; + } + vec2.scale(integrate_fhMinv, f, dt * minv); + vec2.multiply(integrate_fhMinv, this.massMultiplier, integrate_fhMinv); + vec2.add(velo, integrate_fhMinv, velo); + + // CCD + if(!this.integrateToTimeOfImpact(dt)){ + + // Regular position update + vec2.scale(integrate_velodt, velo, dt); + vec2.add(pos, pos, integrate_velodt); + if(!this.fixedRotation){ + this.angle += this.angularVelocity * dt; + } + } + + this.aabbNeedsUpdate = true; +}; + +var result = new RaycastResult(); +var ray = new Ray({ + mode: Ray.ALL +}); +var direction = vec2.create(); +var end = vec2.create(); +var startToEnd = vec2.create(); +var rememberPosition = vec2.create(); +Body.prototype.integrateToTimeOfImpact = function(dt){ + + if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){ + return false; + } + + vec2.normalize(direction, this.velocity); + + vec2.scale(end, this.velocity, dt); + vec2.add(end, end, this.position); + + vec2.sub(startToEnd, end, this.position); + var startToEndAngle = this.angularVelocity * dt; + var len = vec2.length(startToEnd); + + var timeOfImpact = 1; + + var hit; + var that = this; + result.reset(); + ray.callback = function (result) { + if(result.body === that){ + return; + } + hit = result.body; + result.getHitPoint(end, ray); + vec2.sub(startToEnd, end, that.position); + timeOfImpact = vec2.length(startToEnd) / len; + result.stop(); + }; + vec2.copy(ray.from, this.position); + vec2.copy(ray.to, end); + ray.update(); + this.world.raycast(result, ray); + + if(!hit){ + return false; + } + + var rememberAngle = this.angle; + vec2.copy(rememberPosition, this.position); + + // Got a start and end point. Approximate time of impact using binary search + var iter = 0; + var tmin = 0; + var tmid = 0; + var tmax = timeOfImpact; + while (tmax >= tmin && iter < this.ccdIterations) { + iter++; + + // calculate the midpoint + tmid = (tmax - tmin) / 2; + + // Move the body to that point + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, rememberPosition, integrate_velodt); + this.angle = rememberAngle + startToEndAngle * timeOfImpact; + this.updateAABB(); + + // check overlap + var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit); + + if (overlaps) { + // change min to search upper interval + tmin = tmid; + } else { + // change max to search lower interval + tmax = tmid; + } + } + + timeOfImpact = tmid; + + vec2.copy(this.position, rememberPosition); + this.angle = rememberAngle; + + // move to TOI + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, this.position, integrate_velodt); + if(!this.fixedRotation){ + this.angle += startToEndAngle * timeOfImpact; + } + + return true; +}; + +/** + * Get velocity of a point in the body. + * @method getVelocityAtPoint + * @param {Array} result A vector to store the result in + * @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from + * @return {Array} The result vector + */ +Body.prototype.getVelocityAtPoint = function(result, relativePoint){ + vec2.crossVZ(result, relativePoint, this.angularVelocity); + vec2.subtract(result, this.velocity, result); + return result; +}; + +/** + * @event sleepy + */ +Body.sleepyEvent = { + type: "sleepy" +}; + +/** + * @event sleep + */ +Body.sleepEvent = { + type: "sleep" +}; + +/** + * @event wakeup + */ +Body.wakeUpEvent = { + type: "wakeup" +}; + +/** + * Dynamic body. + * @property DYNAMIC + * @type {Number} + * @static + */ +Body.DYNAMIC = 1; + +/** + * Static body. + * @property STATIC + * @type {Number} + * @static + */ +Body.STATIC = 2; + +/** + * Kinematic body. + * @property KINEMATIC + * @type {Number} + * @static + */ +Body.KINEMATIC = 4; + +/** + * @property AWAKE + * @type {Number} + * @static + */ +Body.AWAKE = 0; + +/** + * @property SLEEPY + * @type {Number} + * @static + */ +Body.SLEEPY = 1; + +/** + * @property SLEEPING + * @type {Number} + * @static + */ +Body.SLEEPING = 2; + + +},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = LinearSpring; + +/** + * A spring, connecting two bodies. + * + * The Spring explicitly adds force and angularForce to the bodies. + * + * @class LinearSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + */ +function LinearSpring(bodyA,bodyB,options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Anchor for bodyA in local bodyA coordinates. + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = vec2.fromValues(0,0); + + /** + * Anchor for bodyB in local bodyB coordinates. + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = vec2.fromValues(0,0); + + if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); } + if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); } + if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } + if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } + + var worldAnchorA = vec2.create(); + var worldAnchorB = vec2.create(); + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + var worldDistance = vec2.distance(worldAnchorA, worldAnchorB); + + /** + * Rest length of the spring. + * @property restLength + * @type {number} + */ + this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance; +} +LinearSpring.prototype = new Spring(); +LinearSpring.prototype.constructor = LinearSpring; + +/** + * Set the anchor point on body A, using world coordinates. + * @method setWorldAnchorA + * @param {Array} worldAnchorA + */ +LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){ + this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); +}; + +/** + * Set the anchor point on body B, using world coordinates. + * @method setWorldAnchorB + * @param {Array} worldAnchorB + */ +LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){ + this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); +}; + +/** + * Get the anchor point on body A, in world coordinates. + * @method getWorldAnchorA + * @param {Array} result The vector to store the result in. + */ +LinearSpring.prototype.getWorldAnchorA = function(result){ + this.bodyA.toWorldFrame(result, this.localAnchorA); +}; + +/** + * Get the anchor point on body B, in world coordinates. + * @method getWorldAnchorB + * @param {Array} result The vector to store the result in. + */ +LinearSpring.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(); + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +LinearSpring.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; + + // Get world anchors + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + + // Get offset points + vec2.sub(ri, worldAnchorA, bodyA.position); + vec2.sub(rj, worldAnchorB, bodyB.position); + + // Compute distance vector between world anchor points + vec2.sub(r, worldAnchorB, worldAnchorA); + var rlen = vec2.len(r); + vec2.normalize(r_unit,r); + + //console.log(rlen) + //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) + + // Compute relative velocity of the anchor points, u + 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); + + // F = - k * ( x - L ) - D * ( u ) + vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); + + // Add forces to bodies + vec2.sub( bodyA.force, bodyA.force, f); + vec2.add( bodyB.force, bodyB.force, f); + + // Angular force + 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":57,"./Spring":34}],33:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); + +module.exports = RotationalSpring; + +/** + * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies. + * + * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap. + * + * @class RotationalSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. + */ +function RotationalSpring(bodyA, bodyB, options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Rest angle of the spring. + * @property restAngle + * @type {number} + */ + this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle; +} +RotationalSpring.prototype = new Spring(); +RotationalSpring.prototype.constructor = RotationalSpring; + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +RotationalSpring.prototype.applyForce = function(){ + var k = this.stiffness, + d = this.damping, + l = this.restAngle, + bodyA = this.bodyA, + bodyB = this.bodyB, + x = bodyB.angle - bodyA.angle, + u = bodyB.angularVelocity - bodyA.angularVelocity; + + var torque = - k * (x - l) - d * u * 0; + + bodyA.angularForce -= torque; + bodyB.angularForce += torque; +}; + +},{"../math/vec2":30,"./Spring":34}],34:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = Spring; + +/** + * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver. + * + * @class Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + */ +function Spring(bodyA, bodyB, options){ + options = Utils.defaults(options,{ + stiffness: 100, + damping: 1, + }); + + /** + * Stiffness of the spring. + * @property stiffness + * @type {number} + */ + this.stiffness = options.stiffness; + + /** + * Damping of the spring. + * @property damping + * @type {number} + */ + this.damping = options.damping; + + /** + * First connected body. + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second connected body. + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; +} + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +Spring.prototype.applyForce = function(){ + // To be implemented by subclasses +}; + +},{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); +var Constraint = _dereq_('../constraints/Constraint'); +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Body = _dereq_('../objects/Body'); + +module.exports = TopDownVehicle; + +/** + * @class TopDownVehicle + * @constructor + * @param {Body} chassisBody A dynamic body, already added to the world. + * @param {Object} [options] + * + * @example + * + * // Create a dynamic body for the chassis + * var chassisBody = new Body({ + * mass: 1 + * }); + * var boxShape = new Box({ width: 0.5, height: 1 }); + * chassisBody.addShape(boxShape); + * world.addBody(chassisBody); + * + * // Create the vehicle + * var vehicle = new TopDownVehicle(chassisBody); + * + * // Add one front wheel and one back wheel - we don't actually need four :) + * var frontWheel = vehicle.addWheel({ + * localPosition: [0, 0.5] // front + * }); + * frontWheel.setSideFriction(4); + * + * // Back wheel + * var backWheel = vehicle.addWheel({ + * localPosition: [0, -0.5] // back + * }); + * backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift + * vehicle.addToWorld(world); + * + * // Steer value zero means straight forward. Positive is left and negative right. + * frontWheel.steerValue = Math.PI / 16; + * + * // Engine force forward + * backWheel.engineForce = 10; + * backWheel.setBrakeForce(0); + */ +function TopDownVehicle(chassisBody, options){ + options = options || {}; + + /** + * @property {Body} chassisBody + */ + this.chassisBody = chassisBody; + + /** + * @property {Array} wheels + */ + this.wheels = []; + + // A dummy body to constrain the chassis to + this.groundBody = new Body({ mass: 0 }); + + this.world = null; + + var that = this; + this.preStepCallback = function(){ + that.update(); + }; +} + +/** + * @method addToWorld + * @param {World} world + */ +TopDownVehicle.prototype.addToWorld = function(world){ + this.world = world; + world.addBody(this.groundBody); + world.on('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.addConstraint(wheel); + } +}; + +/** + * @method removeFromWorld + * @param {World} world + */ +TopDownVehicle.prototype.removeFromWorld = function(){ + var world = this.world; + world.removeBody(this.groundBody); + world.off('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.removeConstraint(wheel); + } + this.world = null; +}; + +/** + * @method addWheel + * @param {object} [wheelOptions] + * @return {WheelConstraint} + */ +TopDownVehicle.prototype.addWheel = function(wheelOptions){ + var wheel = new WheelConstraint(this,wheelOptions); + this.wheels.push(wheel); + return wheel; +}; + +/** + * @method update + */ +TopDownVehicle.prototype.update = function(){ + for (var i = 0; i < this.wheels.length; i++) { + this.wheels[i].update(); + } +}; + +/** + * @class WheelConstraint + * @constructor + * @extends {Constraint} + * @param {Vehicle} vehicle + * @param {object} [options] + * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero. + * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body. + * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction. + */ +function WheelConstraint(vehicle, options){ + options = options || {}; + + this.vehicle = vehicle; + + this.forwardEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + this.sideEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + /** + * @property {number} steerValue + */ + this.steerValue = 0; + + /** + * @property {number} engineForce + */ + this.engineForce = 0; + + this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5); + + /** + * @property {Array} localForwardVector + */ + this.localForwardVector = vec2.fromValues(0, 1); + if(options.localForwardVector){ + vec2.copy(this.localForwardVector, options.localForwardVector); + } + + /** + * @property {Array} localPosition + */ + this.localPosition = vec2.fromValues(0, 0); + if(options.localPosition){ + vec2.copy(this.localPosition, options.localPosition); + } + + Constraint.apply(this, vehicle.chassisBody, vehicle.groundBody); + + this.equations.push( + this.forwardEquation, + this.sideEquation + ); + + this.setBrakeForce(0); +} +WheelConstraint.prototype = new Constraint(); + +/** + * @method setForwardFriction + */ +WheelConstraint.prototype.setBrakeForce = function(force){ + this.forwardEquation.setSlipForce(force); +}; + +/** + * @method setSideFriction + */ +WheelConstraint.prototype.setSideFriction = function(force){ + this.sideEquation.setSlipForce(force); +}; + +var worldVelocity = vec2.create(); +var relativePoint = vec2.create(); + +/** + * @method getSpeed + */ +WheelConstraint.prototype.getSpeed = function(){ + this.vehicle.chassisBody.vectorToWorldFrame(relativePoint, this.localForwardVector); + this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity, relativePoint); + return vec2.dot(worldVelocity, relativePoint); +}; + +var tmpVec = vec2.create(); + +/** + * @method update + */ +WheelConstraint.prototype.update = function(){ + + // Directional + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t, this.localForwardVector); + vec2.rotate(this.sideEquation.t, this.localForwardVector, Math.PI / 2); + this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t, this.sideEquation.t); + + vec2.rotate(this.forwardEquation.t, this.forwardEquation.t, this.steerValue); + vec2.rotate(this.sideEquation.t, this.sideEquation.t, this.steerValue); + + // Attachment point + this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB, this.localPosition); + vec2.copy(this.sideEquation.contactPointB, this.forwardEquation.contactPointB); + + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA, this.localPosition); + vec2.copy(this.sideEquation.contactPointA, this.forwardEquation.contactPointA); + + // Add engine force + vec2.normalize(tmpVec, this.forwardEquation.t); + vec2.scale(tmpVec, tmpVec, this.engineForce); + + this.vehicle.chassisBody.applyForce(tmpVec, this.forwardEquation.contactPointA); +}; +},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(_dereq_,module,exports){ +// Export p2 classes +var p2 = module.exports = { + AABB : _dereq_('./collision/AABB'), + AngleLockEquation : _dereq_('./equations/AngleLockEquation'), + Body : _dereq_('./objects/Body'), + Broadphase : _dereq_('./collision/Broadphase'), + Capsule : _dereq_('./shapes/Capsule'), + Circle : _dereq_('./shapes/Circle'), + Constraint : _dereq_('./constraints/Constraint'), + ContactEquation : _dereq_('./equations/ContactEquation'), + ContactEquationPool : _dereq_('./utils/ContactEquationPool'), + ContactMaterial : _dereq_('./material/ContactMaterial'), + Convex : _dereq_('./shapes/Convex'), + DistanceConstraint : _dereq_('./constraints/DistanceConstraint'), + Equation : _dereq_('./equations/Equation'), + EventEmitter : _dereq_('./events/EventEmitter'), + FrictionEquation : _dereq_('./equations/FrictionEquation'), + FrictionEquationPool : _dereq_('./utils/FrictionEquationPool'), + GearConstraint : _dereq_('./constraints/GearConstraint'), + GSSolver : _dereq_('./solver/GSSolver'), + Heightfield : _dereq_('./shapes/Heightfield'), + Line : _dereq_('./shapes/Line'), + LockConstraint : _dereq_('./constraints/LockConstraint'), + Material : _dereq_('./material/Material'), + Narrowphase : _dereq_('./collision/Narrowphase'), + NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'), + Particle : _dereq_('./shapes/Particle'), + Plane : _dereq_('./shapes/Plane'), + Pool : _dereq_('./utils/Pool'), + RevoluteConstraint : _dereq_('./constraints/RevoluteConstraint'), + PrismaticConstraint : _dereq_('./constraints/PrismaticConstraint'), + Ray : _dereq_('./collision/Ray'), + RaycastResult : _dereq_('./collision/RaycastResult'), + Box : _dereq_('./shapes/Box'), + RotationalVelocityEquation : _dereq_('./equations/RotationalVelocityEquation'), + SAPBroadphase : _dereq_('./collision/SAPBroadphase'), + Shape : _dereq_('./shapes/Shape'), + Solver : _dereq_('./solver/Solver'), + Spring : _dereq_('./objects/Spring'), + TopDownVehicle : _dereq_('./objects/TopDownVehicle'), + LinearSpring : _dereq_('./objects/LinearSpring'), + RotationalSpring : _dereq_('./objects/RotationalSpring'), + Utils : _dereq_('./utils/Utils'), + World : _dereq_('./world/World'), + vec2 : _dereq_('./math/vec2'), + version : _dereq_('../package.json').version, +}; + +Object.defineProperty(p2, 'Rectangle', { + get: function() { + console.warn('The Rectangle class has been renamed to Box.'); + return this.Box; + } +}); +},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":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/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Shape = _dereq_('./Shape') +, Convex = _dereq_('./Convex'); + +module.exports = Box; + +/** + * Box shape class. + * @class Box + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.width=1] Total width of the box + * @param {Number} [options.height=1] Total height of the box + * @extends Convex + */ +function Box(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + width: arguments[0], + height: arguments[1] + }; + console.warn('The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })'); + } + options = options || {}; + + /** + * Total width of the box + * @property width + * @type {Number} + */ + var width = this.width = options.width || 1; + + /** + * Total height of the box + * @property height + * @type {Number} + */ + var height = this.height = options.height || 1; + + var verts = [ + vec2.fromValues(-width/2, -height/2), + vec2.fromValues( width/2, -height/2), + vec2.fromValues( width/2, height/2), + vec2.fromValues(-width/2, height/2) + ]; + var axes = [ + vec2.fromValues(1, 0), + vec2.fromValues(0, 1) + ]; + + options.vertices = verts; + options.axes = axes; + options.type = Shape.BOX; + Convex.call(this, options); +} +Box.prototype = new Convex(); +Box.prototype.constructor = Box; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Box.prototype.computeMomentOfInertia = function(mass){ + var w = this.width, + h = this.height; + return mass * (h*h + w*w) / 12; +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Box.prototype.updateBoundingRadius = function(){ + var w = this.width, + h = this.height; + this.boundingRadius = Math.sqrt(w*w + h*h) / 2; +}; + +var corner1 = vec2.create(), + corner2 = vec2.create(), + corner3 = vec2.create(), + corner4 = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Box.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices,position,angle,0); +}; + +Box.prototype.updateArea = function(){ + this.area = this.width * this.height; +}; + + +},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Capsule; + +/** + * Capsule shape class. + * @class Capsule + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The distance between the end points + * @param {Number} [options.radius=1] Radius of the capsule + * @example + * var capsuleShape = new Capsule({ + * length: 1, + * radius: 2 + * }); + * body.addShape(capsuleShape); + */ +function Capsule(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + length: arguments[0], + radius: arguments[1] + }; + console.warn('The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })'); + } + options = options || {}; + + /** + * The distance between the end points. + * @property {Number} length + */ + this.length = options.length || 1; + + /** + * The radius of the capsule. + * @property {Number} radius + */ + this.radius = options.radius || 1; + + options.type = Shape.CAPSULE; + Shape.call(this, options); +} +Capsule.prototype = new Shape(); +Capsule.prototype.constructor = Capsule; + +/** + * Compute the mass moment of inertia of the Capsule. + * @method conputeMomentOfInertia + * @param {Number} mass + * @return {Number} + * @todo + */ +Capsule.prototype.computeMomentOfInertia = function(mass){ + // Approximate with rectangle + var r = this.radius, + w = this.length + r, // 2*r is too much, 0 is too little + h = r*2; + return mass * (h*h + w*w) / 12; +}; + +/** + * @method updateBoundingRadius + */ +Capsule.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius + this.length/2; +}; + +/** + * @method updateArea + */ +Capsule.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; +}; + +var r = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Capsule.prototype.computeAABB = function(out, position, angle){ + var radius = this.radius; + + // Compute center position of one of the the circles, world oriented, but with local offset + vec2.set(r,this.length / 2,0); + if(angle !== 0){ + vec2.rotate(r,r,angle); + } + + // Get bounds + 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)); + + // Add offset + vec2.add(out.lowerBound, out.lowerBound, position); + vec2.add(out.upperBound, out.upperBound, position); +}; + +var intersectCapsule_hitPointWorld = vec2.create(); +var intersectCapsule_normal = vec2.create(); +var intersectCapsule_l0 = vec2.create(); +var intersectCapsule_l1 = vec2.create(); +var intersectCapsule_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Capsule.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectCapsule_hitPointWorld; + var normal = intersectCapsule_normal; + var l0 = intersectCapsule_l0; + var l1 = intersectCapsule_l1; + + // The sides + var halfLen = this.length / 2; + for(var i=0; i<2; i++){ + + // get start and end of the line + var y = this.radius * (i*2-1); + vec2.set(l0, -halfLen, y); + vec2.set(l1, halfLen, y); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var delta = vec2.getLineSegmentsIntersectionFraction(from, to, l0, l1); + if(delta >= 0){ + vec2.rotate(normal, intersectCapsule_unit_y, angle); + vec2.scale(normal, normal, (i*2-1)); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + // Circles + var diagonalLengthSquared = Math.pow(this.radius, 2) + Math.pow(halfLen, 2); + for(var i=0; i<2; i++){ + vec2.set(l0, halfLen * (i*2-1), 0); + vec2.toGlobalFrame(l0, l0, position, angle); + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - l0[0]) + (to[1] - from[1]) * (from[1] - l0[1])); + var c = Math.pow(from[0] - l0[0], 2) + Math.pow(from[1] - l0[1], 2) - Math.pow(this.radius, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + if(delta < 0){ + // No intersection + continue; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(hitPointWorld, from, to, delta); + + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(hitPointWorld, from, to, d1); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d1, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(hitPointWorld, from, to, d2); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d2, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + } + } +}; +},{"../math/vec2":30,"./Shape":45}],39:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Circle; + +/** + * Circle shape class. + * @class Circle + * @extends Shape + * @constructor + * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {number} [options.radius=1] The radius of this circle + * + * @example + * var circleShape = new Circle({ radius: 1 }); + * body.addShape(circleShape); + */ +function Circle(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + radius: arguments[0] + }; + console.warn('The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })'); + } + options = options || {}; + + /** + * The radius of the circle. + * @property radius + * @type {number} + */ + this.radius = options.radius || 1; + + options.type = Shape.CIRCLE; + Shape.call(this, options); +} +Circle.prototype = new Shape(); +Circle.prototype.constructor = Circle; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Circle.prototype.computeMomentOfInertia = function(mass){ + var r = this.radius; + return mass * r * r / 2; +}; + +/** + * @method updateBoundingRadius + * @return {Number} + */ +Circle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius; +}; + +/** + * @method updateArea + * @return {Number} + */ +Circle.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius; +}; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +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); + } +}; + +var Ray_intersectSphere_intersectionPoint = vec2.create(); +var Ray_intersectSphere_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Circle.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from, + to = ray.to, + r = this.radius; + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1])); + var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + var intersectionPoint = Ray_intersectSphere_intersectionPoint; + var normal = Ray_intersectSphere_normal; + + if(delta < 0){ + // No intersection + return; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(intersectionPoint, from, to, delta); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, delta, normal, -1); + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(intersectionPoint, from, to, d1); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d1, normal, -1); + + if(result.shouldStop(ray)){ + return; + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(intersectionPoint, from, to, d2); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d2, normal, -1); + } + } +}; +},{"../math/vec2":30,"./Shape":45}],40:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, polyk = _dereq_('../math/polyk') +, decomp = _dereq_('poly-decomp'); + +module.exports = Convex; + +/** + * Convex shape class. + * @class Convex + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. + * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex. + * @example + * // Create a box + * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]]; + * var convexShape = new Convex({ vertices: vertices }); + * body.addShape(convexShape); + */ +function Convex(options){ + if(Array.isArray(arguments[0])){ + options = { + vertices: arguments[0], + axes: arguments[1] + }; + console.warn('The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })'); + } + options = options || {}; + + /** + * Vertices defined in the local frame. + * @property vertices + * @type {Array} + */ + this.vertices = []; + + // Copy the verts + var vertices = options.vertices !== undefined ? options.vertices : []; + for(var i=0; i < vertices.length; i++){ + var v = vec2.create(); + vec2.copy(v, vertices[i]); + this.vertices.push(v); + } + + /** + * Axes defined in the local frame. + * @property axes + * @type {Array} + */ + this.axes = []; + + if(options.axes){ + + // Copy the axes + for(var i=0; i < options.axes.length; i++){ + var axis = vec2.create(); + vec2.copy(axis, options.axes[i]); + this.axes.push(axis); + } + + } else { + + // Construct axes from the vertex data + for(var i = 0; i < this.vertices.length; i++){ + // Get the world edge + var worldPoint0 = this.vertices[i]; + var worldPoint1 = this.vertices[(i+1) % this.vertices.length]; + + var normal = vec2.create(); + vec2.sub(normal, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, normal); + vec2.normalize(normal, normal); + + this.axes.push(normal); + } + + } + + /** + * The center of mass of the Convex + * @property centerOfMass + * @type {Array} + */ + this.centerOfMass = vec2.fromValues(0,0); + + /** + * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. + * @property triangles + * @type {Array} + */ + this.triangles = []; + + if(this.vertices.length){ + this.updateTriangles(); + this.updateCenterOfMass(); + } + + /** + * The bounding radius of the convex + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + options.type = Shape.CONVEX; + Shape.call(this, options); + + this.updateBoundingRadius(); + this.updateArea(); + if(this.area < 0){ + throw new Error("Convex vertices must be given in conter-clockwise winding."); + } +} +Convex.prototype = new Shape(); +Convex.prototype.constructor = Convex; + +var tmpVec1 = vec2.create(); +var tmpVec2 = vec2.create(); + +/** + * Project a Convex onto a world-oriented axis + * @method projectOntoAxis + * @static + * @param {Array} offset + * @param {Array} localAxis + * @param {Array} result + */ +Convex.prototype.projectOntoLocalAxis = function(localAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = tmpVec1; + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + vec2.set(result, min, max); +}; + +Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){ + var worldAxis = tmpVec2; + + this.projectOntoLocalAxis(localAxis, result); + + // Project the position of the body onto the axis - need to add this to the result + if(shapeAngle !== 0){ + vec2.rotate(worldAxis, localAxis, shapeAngle); + } else { + worldAxis = localAxis; + } + var offset = vec2.dot(shapeOffset, worldAxis); + + vec2.set(result, result[0] + offset, result[1] + offset); +}; + + +/** + * Update the .triangles property + * @method updateTriangles + */ +Convex.prototype.updateTriangles = function(){ + + this.triangles.length = 0; + + // Rewrite on polyk notation, array of numbers + var polykVerts = []; + for(var i=0; i r2){ + r2 = l2; + } + } + + this.boundingRadius = Math.sqrt(r2); +}; + +/** + * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. + * @static + * @method triangleArea + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +Convex.triangleArea = function(a,b,c){ + return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; +}; + +/** + * Update the .area + * @method updateArea + */ +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]]; + + // Get mass for the triangle (density=1 in this case) + var m = Convex.triangleArea(a,b,c); + this.area += m; + } +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Convex.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices, position, angle, 0); +}; + +var intersectConvex_rayStart = vec2.create(); +var intersectConvex_rayEnd = vec2.create(); +var intersectConvex_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Convex.prototype.raycast = function(result, ray, position, angle){ + var rayStart = intersectConvex_rayStart; + var rayEnd = intersectConvex_rayEnd; + var normal = intersectConvex_normal; + var vertices = this.vertices; + + // Transform to local shape space + vec2.toLocalFrame(rayStart, ray.from, position, angle); + vec2.toLocalFrame(rayEnd, ray.to, position, angle); + + var n = vertices.length; + + for (var i = 0; i < n && !result.shouldStop(ray); i++) { + var q1 = vertices[i]; + var q2 = vertices[(i+1) % n]; + var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2); + + if(delta >= 0){ + vec2.sub(normal, q2, q1); + vec2.rotate(normal, normal, -Math.PI / 2 + angle); + vec2.normalize(normal, normal); + ray.reportIntersection(result, delta, normal, i); + } + } +}; + +},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Heightfield; + +/** + * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". + * @class Heightfield + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {array} [options.heights] An array of Y values that will be used to construct the terrain. + * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given. + * @param {Number} [options.maxValue] Maximum value. + * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction. + * + * @example + * // Generate some height data (y-values). + * var heights = []; + * for(var i = 0; i < 1000; i++){ + * var y = 0.5 * Math.cos(0.2 * i); + * heights.push(y); + * } + * + * // Create the heightfield shape + * var heightfieldShape = new Heightfield({ + * heights: heights, + * elementWidth: 1 // Distance between the data points in X direction + * }); + * var heightfieldBody = new Body(); + * heightfieldBody.addShape(heightfieldShape); + * world.addBody(heightfieldBody); + * + * @todo Should use a scale property with X and Y direction instead of just elementWidth + */ +function Heightfield(options){ + if(Array.isArray(arguments[0])){ + options = { + heights: arguments[0] + }; + + if(typeof(arguments[1]) === 'object'){ + for(var key in arguments[1]){ + options[key] = arguments[1][key]; + } + } + + console.warn('The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })'); + } + options = options || {}; + + /** + * An array of numbers, or height values, that are spread out along the x axis. + * @property {array} heights + */ + this.heights = options.heights ? options.heights.slice(0) : []; + + /** + * Max value of the heights + * @property {number} maxValue + */ + this.maxValue = options.maxValue || null; + + /** + * Max value of the heights + * @property {number} minValue + */ + this.minValue = options.minValue || null; + + /** + * The width of each element + * @property {number} elementWidth + */ + this.elementWidth = options.elementWidth || 0.1; + + if(options.maxValue === undefined || options.minValue === undefined){ + this.updateMaxMinValues(); + } + + options.type = Shape.HEIGHTFIELD; + Shape.call(this, options); +} +Heightfield.prototype = new Shape(); +Heightfield.prototype.constructor = Heightfield; + +/** + * Update the .minValue and the .maxValue + * @method updateMaxMinValues + */ +Heightfield.prototype.updateMaxMinValues = function(){ + var data = this.heights; + var maxValue = data[0]; + var minValue = data[0]; + for(var i=0; i !== data.length; i++){ + var v = data[i]; + if(v > maxValue){ + maxValue = v; + } + if(v < minValue){ + minValue = v; + } + } + this.maxValue = maxValue; + this.minValue = minValue; +}; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Heightfield.prototype.computeMomentOfInertia = function(mass){ + return Number.MAX_VALUE; +}; + +Heightfield.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +Heightfield.prototype.updateArea = function(){ + var data = this.heights, + area = 0; + for(var i=0; i= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + var intX = p0[0] + (t * s1_x); + var intY = p0[1] + (t * s1_y); + out[0] = intX; + out[1] = intY; + return t; + } + return -1; // No collision +} + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Heightfield.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectHeightfield_hitPointWorld; + var worldNormal = intersectHeightfield_worldNormal; + var l0 = intersectHeightfield_l0; + var l1 = intersectHeightfield_l1; + var localFrom = intersectHeightfield_localFrom; + var localTo = intersectHeightfield_localTo; + + // get local ray start and end + vec2.toLocalFrame(localFrom, from, position, angle); + vec2.toLocalFrame(localTo, to, position, angle); + + // Get the segment range + var i0 = this.getClampedSegmentIndex(localFrom); + var i1 = this.getClampedSegmentIndex(localTo); + if(i0 > i1){ + var tmp = i0; + i0 = i1; + i1 = tmp; + } + + // The segments + for(var i=0; i= 0){ + vec2.sub(worldNormal, l1, l0); + vec2.rotate(worldNormal, worldNormal, angle + Math.PI / 2); + vec2.normalize(worldNormal, worldNormal); + ray.reportIntersection(result, t, worldNormal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Line; + +/** + * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * @class Line + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The total length of the line + * @extends Shape + * @constructor + */ +function Line(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + length: arguments[0] + }; + console.warn('The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })'); + } + options = options || {}; + + /** + * Length of this line + * @property {Number} length + * @default 1 + */ + this.length = options.length || 1; + + options.type = Shape.LINE; + Shape.call(this, options); +} +Line.prototype = new Shape(); +Line.prototype.constructor = Line; + +Line.prototype.computeMomentOfInertia = function(mass){ + return mass * Math.pow(this.length,2) / 12; +}; + +Line.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.length/2; +}; + +var points = [vec2.create(),vec2.create()]; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Line.prototype.computeAABB = function(out, position, angle){ + var l2 = this.length / 2; + vec2.set(points[0], -l2, 0); + vec2.set(points[1], l2, 0); + out.setFromPoints(points,position,angle,0); +}; + +var raycast_hitPoint = vec2.create(); +var raycast_normal = vec2.create(); +var raycast_l0 = vec2.create(); +var raycast_l1 = vec2.create(); +var raycast_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {number} angle + * @param {array} position + */ +Line.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + + var l0 = raycast_l0; + var l1 = raycast_l1; + + // get start and end of the line + var halfLen = this.length / 2; + vec2.set(l0, -halfLen, 0); + vec2.set(l1, halfLen, 0); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to); + if(fraction >= 0){ + var normal = raycast_normal; + vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from + ray.reportIntersection(result, fraction, normal, -1); + } +}; +},{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Particle; + +/** + * Particle shape class. + * @class Particle + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @extends Shape + */ +function Particle(options){ + options = options || {}; + options.type = Shape.PARTICLE; + Shape.call(this, options); +} +Particle.prototype = new Shape(); +Particle.prototype.constructor = Particle; + +Particle.prototype.computeMomentOfInertia = function(mass){ + return 0; // Can't rotate a particle +}; + +Particle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = 0; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Particle.prototype.computeAABB = function(out, position, angle){ + vec2.copy(out.lowerBound, position); + vec2.copy(out.upperBound, position); +}; + +},{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Plane; + +/** + * Plane shape class. The plane is facing in the Y direction. + * @class Plane + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + */ +function Plane(options){ + options = options || {}; + options.type = Shape.PLANE; + Shape.call(this, options); +} +Plane.prototype = new Shape(); +Plane.prototype.constructor = Plane; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + */ +Plane.prototype.computeMomentOfInertia = function(mass){ + return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Plane.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Plane.prototype.computeAABB = function(out, position, angle){ + var a = angle % (2 * Math.PI); + var set = vec2.set; + var max = 1e7; + var lowerBound = out.lowerBound; + var upperBound = out.upperBound; + + // Set max bounds + set(lowerBound, -max, -max); + set(upperBound, max, max); + + if(a === 0){ + // y goes from -inf to 0 + upperBound[1] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, max, 0); + + } else if(a === Math.PI / 2){ + + // x goes from 0 to inf + lowerBound[0] = 0; + // set(lowerBound, 0, -max); + // set(upperBound, max, max); + + } else if(a === Math.PI){ + + // y goes from 0 to inf + lowerBound[1] = 0; + // set(lowerBound, -max, 0); + // set(upperBound, max, max); + + } else if(a === 3*Math.PI/2){ + + // x goes from -inf to 0 + upperBound[0] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, 0, max); + + } +}; + +Plane.prototype.updateArea = function(){ + this.area = Number.MAX_VALUE; +}; + +var intersectPlane_planePointToFrom = vec2.create(); +var intersectPlane_dir_scaled_with_t = vec2.create(); +var intersectPlane_hitPoint = vec2.create(); +var intersectPlane_normal = vec2.create(); +var intersectPlane_len = vec2.create(); + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Plane.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + var planePointToFrom = intersectPlane_planePointToFrom; + var dir_scaled_with_t = intersectPlane_dir_scaled_with_t; + var hitPoint = intersectPlane_hitPoint; + var normal = intersectPlane_normal; + var len = intersectPlane_len; + + // Get plane normal + vec2.set(normal, 0, 1); + vec2.rotate(normal, normal, angle); + + vec2.sub(len, from, position); + var planeToFrom = vec2.dot(len, normal); + vec2.sub(len, to, position); + var planeToTo = vec2.dot(len, normal); + + if(planeToFrom * planeToTo > 0){ + // "from" and "to" are on the same side of the plane... bail out + return; + } + + if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){ + return; + } + + var n_dot_dir = vec2.dot(normal, direction); + + vec2.sub(planePointToFrom, from, position); + var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length; + + ray.reportIntersection(result, t, normal, -1); +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(_dereq_,module,exports){ +module.exports = Shape; + +var vec2 = _dereq_('../math/vec2'); + +/** + * Base class for shapes. + * @class Shape + * @constructor + * @param {object} [options] + * @param {array} [options.position] + * @param {number} [options.angle=0] + * @param {number} [options.collisionGroup=1] + * @param {number} [options.collisionMask=1] + * @param {boolean} [options.sensor=false] + * @param {boolean} [options.collisionResponse=true] + * @param {object} [options.type=0] + */ +function Shape(options){ + options = options || {}; + + /** + * The body this shape is attached to. A shape can only be attached to a single body. + * @property {Body} body + */ + this.body = null; + + /** + * Body-local position of the shape. + * @property {Array} position + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * Body-local angle of the shape. + * @property {number} angle + */ + this.angle = options.angle || 0; + + /** + * The type of the shape. One of: + * + * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} + * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} + * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} + * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} + * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} + * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}} + * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} + * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} + * + * @property {number} type + */ + this.type = options.type || 0; + + /** + * Shape object identifier. + * @type {Number} + * @property id + */ + this.id = Shape.idCounter++; + + /** + * Bounding circle radius of this shape + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + /** + * Collision group that this shape belongs to (bit mask). See this tutorial. + * @property collisionGroup + * @type {Number} + * @example + * // Setup bits for each available group + * var PLAYER = Math.pow(2,0), + * ENEMY = Math.pow(2,1), + * GROUND = Math.pow(2,2) + * + * // Put shapes into their groups + * player1Shape.collisionGroup = PLAYER; + * player2Shape.collisionGroup = PLAYER; + * enemyShape .collisionGroup = ENEMY; + * groundShape .collisionGroup = GROUND; + * + * // Assign groups that each shape collide with. + * // Note that the players can collide with ground and enemies, but not with other players. + * player1Shape.collisionMask = ENEMY | GROUND; + * player2Shape.collisionMask = ENEMY | GROUND; + * enemyShape .collisionMask = PLAYER | GROUND; + * groundShape .collisionMask = PLAYER | ENEMY; + * + * @example + * // How collision check is done + * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ + * // The shapes will collide + * } + */ + this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. + * @property {Boolean} collisionResponse + */ + this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; + + /** + * Collision mask of this shape. See .collisionGroup. + * @property collisionMask + * @type {Number} + */ + this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; + + /** + * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. + * @property material + * @type {Material} + */ + this.material = options.material || null; + + /** + * Area of this shape. + * @property area + * @type {Number} + */ + this.area = 0; + + /** + * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. + * @property {Boolean} sensor + */ + this.sensor = options.sensor !== undefined ? options.sensor : false; + + if(this.type){ + this.updateBoundingRadius(); + } + + this.updateArea(); +} + +Shape.idCounter = 0; + +/** + * @static + * @property {Number} CIRCLE + */ +Shape.CIRCLE = 1; + +/** + * @static + * @property {Number} PARTICLE + */ +Shape.PARTICLE = 2; + +/** + * @static + * @property {Number} PLANE + */ +Shape.PLANE = 4; + +/** + * @static + * @property {Number} CONVEX + */ +Shape.CONVEX = 8; + +/** + * @static + * @property {Number} LINE + */ +Shape.LINE = 16; + +/** + * @static + * @property {Number} BOX + */ +Shape.BOX = 32; + +/** + * @static + * @property {Number} CAPSULE + */ +Shape.CAPSULE = 64; + +/** + * @static + * @property {Number} HEIGHTFIELD + */ +Shape.HEIGHTFIELD = 128; + +/** + * Should return the moment of inertia around the Z axis of the body given the total mass. See Wikipedia's list of moments of inertia. + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. + */ +Shape.prototype.computeMomentOfInertia = function(mass){}; + +/** + * Returns the bounding circle radius of this shape. + * @method updateBoundingRadius + * @return {Number} + */ +Shape.prototype.updateBoundingRadius = function(){}; + +/** + * Update the .area property of the shape. + * @method updateArea + */ +Shape.prototype.updateArea = function(){ + // To be implemented in all subclasses +}; + +/** + * Compute the world axis-aligned bounding box (AABB) of this shape. + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position World position of the shape. + * @param {Number} angle World angle of the shape. + */ +Shape.prototype.computeAABB = function(out, position, angle){ + // To be implemented in each subclass +}; + +/** + * Perform raycasting on this shape. + * @method raycast + * @param {RayResult} result Where to store the resulting data. + * @param {Ray} ray The Ray that you want to use for raycasting. + * @param {array} position World position of the shape (the .position property will be ignored). + * @param {number} angle World angle of the shape (the .angle property will be ignored). + */ +Shape.prototype.raycast = function(result, ray, position, angle){ + // To be implemented in each subclass +}; +},{"../math/vec2":30}],46:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Solver = _dereq_('./Solver') +, Utils = _dereq_('../utils/Utils') +, FrictionEquation = _dereq_('../equations/FrictionEquation'); + +module.exports = GSSolver; + +/** + * Iterative Gauss-Seidel constraint equation solver. + * + * @class GSSolver + * @constructor + * @extends Solver + * @param {Object} [options] + * @param {Number} [options.iterations=10] + * @param {Number} [options.tolerance=0] + */ +function GSSolver(options){ + Solver.call(this,options,Solver.GS); + options = options || {}; + + /** + * The max number of iterations to do when solving. More gives better results, but is more expensive. + * @property iterations + * @type {Number} + */ + this.iterations = options.iterations || 10; + + /** + * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. + * @property tolerance + * @type {Number} + * @default 1e-7 + */ + this.tolerance = options.tolerance || 1e-7; + + this.arrayStep = 30; + this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); + + /** + * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. + * @property useZeroRHS + * @type {Boolean} + * @todo Remove, not used + */ + this.useZeroRHS = false; + + /** + * Number of solver iterations that are used to approximate normal forces used for friction (F_friction = mu * F_normal). These friction forces will override any other friction forces that are set. If you set frictionIterations = 0, then this feature will be disabled. + * + * Use only frictionIterations > 0 if the approximated normal force (F_normal = mass * gravity) is not good enough. Examples of where it can happen is in space games where gravity is zero, or in tall stacks where the normal force is large at bottom but small at top. + * + * @property frictionIterations + * @type {Number} + * @default 0 + */ + this.frictionIterations = options.frictionIterations !== undefined ? 0 : options.frictionIterations; + + /** + * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. + * @property {Number} usedIterations + */ + this.usedIterations = 0; +} +GSSolver.prototype = new Solver(); +GSSolver.prototype.constructor = GSSolver; + +function setArrayZero(array){ + var l = array.length; + while(l--){ + array[l] = +0.0; + } +} + +/** + * Solve the system of equations + * @method solve + * @param {Number} h Time step + * @param {World} world World to solve + */ +GSSolver.prototype.solve = function(h, world){ + + this.sortEquations(); + + var iter = 0, + maxIter = this.iterations, + maxFrictionIter = this.frictionIterations, + equations = this.equations, + Neq = equations.length, + tolSquared = Math.pow(this.tolerance*Neq, 2), + bodies = world.bodies, + Nbodies = world.bodies.length, + add = vec2.add, + set = vec2.set, + useZeroRHS = this.useZeroRHS, + lambda = this.lambda; + + this.usedIterations = 0; + + if(Neq){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Update solve mass + b.updateSolveMassProperties(); + } + } + + // Things that does not change during iteration can be computed once + if(lambda.length < Neq){ + lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + } + setArrayZero(lambda); + var invCs = this.invCs, + Bs = this.Bs, + lambda = this.lambda; + + for(var i=0; i!==equations.length; i++){ + var c = equations[i]; + if(c.timeStep !== h || c.needsUpdate){ + c.timeStep = h; + c.update(); + } + Bs[i] = c.computeB(c.a,c.b,h); + invCs[i] = c.computeInvC(c.epsilon); + } + + var q, B, c, deltalambdaTot,i,j; + + if(Neq !== 0){ + + for(i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Reset vlambda + b.resetConstraintVelocity(); + } + + if(maxFrictionIter){ + // Iterate over contact equations to get normal forces + for(iter=0; iter!==maxFrictionIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + + // Set computed friction force + for(j=0; j!==Neq; j++){ + var eq = equations[j]; + if(eq instanceof FrictionEquation){ + var f = 0.0; + for(var k=0; k!==eq.contactEquations.length; k++){ + f += eq.contactEquations[k].multiplier; + } + f *= eq.frictionCoefficient / eq.contactEquations.length; + eq.maxForce = f; + eq.minForce = -f; + } + } + } + + // Iterate over all equations + for(iter=0; iter!==maxIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + // Add result to velocity + for(i=0; i!==Nbodies; i++){ + bodies[i].addConstraintVelocity(); + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + } +}; + +// Sets the .multiplier property of each equation +GSSolver.updateMultipliers = function(equations, lambda, invDt){ + // Set the .multiplier property of each equation + var l = equations.length; + while(l--){ + equations[l].multiplier = lambda[l] * invDt; + } +}; + +GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ + // Compute iteration + var B = Bs[j], + invC = invCs[j], + lambdaj = lambda[j], + GWlambda = eq.computeGWlambda(); + + var maxForce = eq.maxForce, + minForce = eq.minForce; + + if(useZeroRHS){ + B = 0; + } + + var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); + + // Clamp if we are not within the min/max interval + var lambdaj_plus_deltalambda = lambdaj + deltalambda; + if(lambdaj_plus_deltalambda < minForce*dt){ + deltalambda = minForce*dt - lambdaj; + } else if(lambdaj_plus_deltalambda > maxForce*dt){ + deltalambda = maxForce*dt - lambdaj; + } + lambda[j] += deltalambda; + eq.addToWlambda(deltalambda); + + return deltalambda; +}; + +},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Solver; + +/** + * Base class for constraint solvers. + * @class Solver + * @constructor + * @extends EventEmitter + */ +function Solver(options,type){ + options = options || {}; + + EventEmitter.call(this); + + this.type = type; + + /** + * Current equations in the solver. + * + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Function that is used to sort all equations before each solve. + * @property equationSortFunction + * @type {function|boolean} + */ + this.equationSortFunction = options.equationSortFunction || false; +} +Solver.prototype = new EventEmitter(); +Solver.prototype.constructor = Solver; + +/** + * Method to be implemented in each subclass + * @method solve + * @param {Number} dt + * @param {World} world + */ +Solver.prototype.solve = function(dt,world){ + throw new Error("Solver.solve should be implemented by subclasses!"); +}; + +var mockWorld = {bodies:[]}; + +/** + * Solves all constraints in an island. + * @method solveIsland + * @param {Number} dt + * @param {Island} island + */ +Solver.prototype.solveIsland = function(dt,island){ + + this.removeAllEquations(); + + if(island.equations.length){ + // Add equations to solver + this.addEquations(island.equations); + mockWorld.bodies.length = 0; + island.getBodies(mockWorld.bodies); + + // Solve + if(mockWorld.bodies.length){ + this.solve(dt,mockWorld); + } + } +}; + +/** + * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. + * @method sortEquations + */ +Solver.prototype.sortEquations = function(){ + if(this.equationSortFunction){ + this.equations.sort(this.equationSortFunction); + } +}; + +/** + * Add an equation to be solved. + * + * @method addEquation + * @param {Equation} eq + */ +Solver.prototype.addEquation = function(eq){ + if(eq.enabled){ + this.equations.push(eq); + } +}; + +/** + * Add equations. Same as .addEquation, but this time the argument is an array of Equations + * + * @method addEquations + * @param {Array} eqs + */ +Solver.prototype.addEquations = function(eqs){ + //Utils.appendArray(this.equations,eqs); + for(var i=0, N=eqs.length; i!==N; i++){ + var eq = eqs[i]; + if(eq.enabled){ + this.equations.push(eq); + } + } +}; + +/** + * Remove an equation. + * + * @method removeEquation + * @param {Equation} eq + */ +Solver.prototype.removeEquation = function(eq){ + var i = this.equations.indexOf(eq); + if(i !== -1){ + this.equations.splice(i,1); + } +}; + +/** + * Remove all currently added equations. + * + * @method removeAllEquations + */ +Solver.prototype.removeAllEquations = function(){ + this.equations.length=0; +}; + +Solver.GS = 1; +Solver.ISLAND = 2; + +},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){ +var ContactEquation = _dereq_('../equations/ContactEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = ContactEquationPool; + +/** + * @class + */ +function ContactEquationPool() { + Pool.apply(this, arguments); +} +ContactEquationPool.prototype = new Pool(); +ContactEquationPool.prototype.constructor = ContactEquationPool; + +/** + * @method create + * @return {ContactEquation} + */ +ContactEquationPool.prototype.create = function () { + return new ContactEquation(); +}; + +/** + * @method destroy + * @param {ContactEquation} equation + * @return {ContactEquationPool} + */ +ContactEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){ +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = FrictionEquationPool; + +/** + * @class + */ +function FrictionEquationPool() { + Pool.apply(this, arguments); +} +FrictionEquationPool.prototype = new Pool(); +FrictionEquationPool.prototype.constructor = FrictionEquationPool; + +/** + * @method create + * @return {FrictionEquation} + */ +FrictionEquationPool.prototype.create = function () { + return new FrictionEquation(); +}; + +/** + * @method destroy + * @param {FrictionEquation} equation + * @return {FrictionEquationPool} + */ +FrictionEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){ +var IslandNode = _dereq_('../world/IslandNode'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandNodePool; + +/** + * @class + */ +function IslandNodePool() { + Pool.apply(this, arguments); +} +IslandNodePool.prototype = new Pool(); +IslandNodePool.prototype.constructor = IslandNodePool; + +/** + * @method create + * @return {IslandNode} + */ +IslandNodePool.prototype.create = function () { + return new IslandNode(); +}; + +/** + * @method destroy + * @param {IslandNode} node + * @return {IslandNodePool} + */ +IslandNodePool.prototype.destroy = function (node) { + node.reset(); + return this; +}; + +},{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){ +var Island = _dereq_('../world/Island'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandPool; + +/** + * @class + */ +function IslandPool() { + Pool.apply(this, arguments); +} +IslandPool.prototype = new Pool(); +IslandPool.prototype.constructor = IslandPool; + +/** + * @method create + * @return {Island} + */ +IslandPool.prototype.create = function () { + return new Island(); +}; + +/** + * @method destroy + * @param {Island} island + * @return {IslandPool} + */ +IslandPool.prototype.destroy = function (island) { + island.reset(); + return this; +}; + +},{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){ +var TupleDictionary = _dereq_('./TupleDictionary'); +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool'); +var Utils = _dereq_('./Utils'); + +module.exports = OverlapKeeper; + +/** + * Keeps track of overlaps in the current state and the last step state. + * @class OverlapKeeper + * @constructor + */ +function OverlapKeeper() { + this.overlappingShapesLastState = new TupleDictionary(); + this.overlappingShapesCurrentState = new TupleDictionary(); + this.recordPool = new OverlapKeeperRecordPool({ size: 16 }); + this.tmpDict = new TupleDictionary(); + this.tmpArray1 = []; +} + +/** + * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current. + * @method tick + */ +OverlapKeeper.prototype.tick = function() { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Save old objects into pool + var l = last.keys.length; + while(l--){ + var key = last.keys[l]; + var lastObject = last.getByKey(key); + var currentObject = current.getByKey(key); + if(lastObject){ + // The record is only used in the "last" dict, and will be removed. We might as well pool it. + this.recordPool.release(lastObject); + } + } + + // Clear last object + last.reset(); + + // Transfer from new object to old + last.copy(current); + + // Clear current object + current.reset(); +}; + +/** + * @method setOverlapping + * @param {Body} bodyA + * @param {Body} shapeA + * @param {Body} bodyB + * @param {Body} shapeB + */ +OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Store current contact state + if(!current.get(shapeA.id, shapeB.id)){ + var data = this.recordPool.get(); + data.set(bodyA, shapeA, bodyB, shapeB); + current.set(shapeA.id, shapeB.id, data); + } +}; + +OverlapKeeper.prototype.getNewOverlaps = function(result){ + return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result); +}; + +OverlapKeeper.prototype.getEndOverlaps = function(result){ + return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result); +}; + +/** + * Checks if two bodies are currently overlapping. + * @method bodiesAreOverlapping + * @param {Body} bodyA + * @param {Body} bodyB + * @return {boolean} + */ +OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){ + var current = this.overlappingShapesCurrentState; + var l = current.keys.length; + while(l--){ + var key = current.keys[l]; + var data = current.data[key]; + if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){ + return true; + } + } + return false; +}; + +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){ + // Not overlapping in last state, but in current. + result.push(data); + } + } + + return result; +}; + +OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ + var idA = shapeA.id|0, + idB = shapeB.id|0; + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + // Not in last but in new + return !!!last.get(idA, idB) && !!current.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]; + + // Since we use body id's for the accumulator, these will be a subset of the original one + accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); + } + + l = accumulator.keys.length; + while(l--){ + var data = accumulator.getByKey(accumulator.keys[l]); + if(data){ + result.push(data.bodyA, data.bodyB); + } + } + + accumulator.reset(); + + return result; +}; + +},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){ +module.exports = OverlapKeeperRecord; + +/** + * Overlap data container for the OverlapKeeper + * @class OverlapKeeperRecord + * @constructor + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ + /** + * @property {Shape} shapeA + */ + this.shapeA = shapeA; + /** + * @property {Shape} shapeB + */ + this.shapeB = shapeB; + /** + * @property {Body} bodyA + */ + this.bodyA = bodyA; + /** + * @property {Body} bodyB + */ + this.bodyB = bodyB; +} + +/** + * Set the data for the record + * @method set + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ + OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); +}; + +},{}],54:[function(_dereq_,module,exports){ +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var Pool = _dereq_('./Pool'); + +module.exports = OverlapKeeperRecordPool; + +/** + * @class + */ +function OverlapKeeperRecordPool() { + Pool.apply(this, arguments); +} +OverlapKeeperRecordPool.prototype = new Pool(); +OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool; + +/** + * @method create + * @return {OverlapKeeperRecord} + */ +OverlapKeeperRecordPool.prototype.create = function () { + return new OverlapKeeperRecord(); +}; + +/** + * @method destroy + * @param {OverlapKeeperRecord} record + * @return {OverlapKeeperRecordPool} + */ +OverlapKeeperRecordPool.prototype.destroy = function (record) { + record.bodyA = record.bodyB = record.shapeA = record.shapeB = null; + return this; +}; + +},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){ +module.exports = Pool; + +/** + * @class Object pooling utility. + */ +function Pool(options) { + options = options || {}; + + /** + * @property {Array} objects + * @type {Array} + */ + this.objects = []; + + if(options.size !== undefined){ + this.resize(options.size); + } +} + +/** + * @method resize + * @param {number} size + * @return {Pool} Self, for chaining + */ +Pool.prototype.resize = function (size) { + var objects = this.objects; + + while (objects.length > size) { + objects.pop(); + } + + while (objects.length < size) { + objects.push(this.create()); + } + + return this; +}; + +/** + * Get an object from the pool or create a new instance. + * @method get + * @return {Object} + */ +Pool.prototype.get = function () { + var objects = this.objects; + return objects.length ? objects.pop() : this.create(); +}; + +/** + * Clean up and put the object back into the pool for later use. + * @method release + * @param {Object} object + * @return {Pool} Self for chaining + */ +Pool.prototype.release = function (object) { + this.destroy(object); + this.objects.push(object); + return this; +}; + +},{}],56:[function(_dereq_,module,exports){ +var Utils = _dereq_('./Utils'); + +module.exports = TupleDictionary; + +/** + * @class TupleDictionary + * @constructor + */ +function TupleDictionary() { + + /** + * The data storage + * @property data + * @type {Object} + */ + this.data = {}; + + /** + * Keys that are currently used. + * @property {Array} keys + */ + this.keys = []; +} + +/** + * Generate a key given two integers + * @method getKey + * @param {number} i + * @param {number} j + * @return {string} + */ +TupleDictionary.prototype.getKey = function(id1, id2) { + id1 = id1|0; + id2 = id2|0; + + if ( (id1|0) === (id2|0) ){ + return -1; + } + + // valid for values < 2^16 + return ((id1|0) > (id2|0) ? + (id1 << 16) | (id2 & 0xFFFF) : + (id2 << 16) | (id1 & 0xFFFF))|0 + ; +}; + +/** + * @method getByKey + * @param {Number} key + * @return {Object} + */ +TupleDictionary.prototype.getByKey = function(key) { + key = key|0; + return this.data[key]; +}; + +/** + * @method get + * @param {Number} i + * @param {Number} j + * @return {Number} + */ +TupleDictionary.prototype.get = function(i, j) { + return this.data[this.getKey(i, j)]; +}; + +/** + * Set a value. + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +TupleDictionary.prototype.set = function(i, j, value) { + if(!value){ + throw new Error("No data!"); + } + + var key = this.getKey(i, j); + + // Check if key already exists + if(!this.data[key]){ + this.keys.push(key); + } + + this.data[key] = value; + + return key; +}; + +/** + * Remove all data. + * @method reset + */ +TupleDictionary.prototype.reset = function() { + var data = this.data, + keys = this.keys; + + var l = keys.length; + while(l--) { + delete data[keys[l]]; + } + + keys.length = 0; +}; + +/** + * Copy another TupleDictionary. Note that all data in this dictionary will be removed. + * @method copy + * @param {TupleDictionary} dict The TupleDictionary to copy into this one. + */ +TupleDictionary.prototype.copy = function(dict) { + this.reset(); + Utils.appendArray(this.keys, dict.keys); + var l = dict.keys.length; + while(l--){ + var key = dict.keys[l]; + this.data[key] = dict.data[key]; + } +}; + +},{"./Utils":57}],57:[function(_dereq_,module,exports){ +/* global P2_ARRAY_TYPE */ + +module.exports = Utils; + +/** + * Misc utility functions + * @class Utils + * @constructor + */ +function Utils(){} + +/** + * Append the values in array b to the array a. See this for an explanation. + * @method appendArray + * @static + * @param {Array} a + * @param {Array} b + */ +Utils.appendArray = function(a,b){ + if (b.length < 150000) { + a.push.apply(a, b); + } else { + for (var i = 0, len = b.length; i !== len; ++i) { + a.push(b[i]); + } + } +}; + +/** + * Garbage free Array.splice(). Does not allocate a new array. + * @method splice + * @static + * @param {Array} array + * @param {Number} index + * @param {Number} howmany + */ +Utils.splice = function(array,index,howmany){ + howmany = howmany || 1; + for (var i=index, len=array.length-howmany; i < len; i++){ + array[i] = array[i + howmany]; + } + array.length = len; +}; + +/** + * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. + * @static + * @property {function} ARRAY_TYPE + * @example + * + * + */ +if(typeof P2_ARRAY_TYPE !== 'undefined') { + Utils.ARRAY_TYPE = P2_ARRAY_TYPE; +} else if (typeof Float32Array !== 'undefined'){ + Utils.ARRAY_TYPE = Float32Array; +} else { + Utils.ARRAY_TYPE = Array; +} + +/** + * Extend an object with the properties of another + * @static + * @method extend + * @param {object} a + * @param {object} b + */ +Utils.extend = function(a,b){ + for(var key in b){ + a[key] = b[key]; + } +}; + +/** + * Extend an options object with default values. + * @static + * @method defaults + * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. + * @param {object} defaults An object containing default values. + * @return {object} The modified options object. + */ +Utils.defaults = function(options, defaults){ + options = options || {}; + for(var key in defaults){ + if(!(key in options)){ + options[key] = defaults[key]; + } + } + return options; +}; + +},{}],58:[function(_dereq_,module,exports){ +var Body = _dereq_('../objects/Body'); + +module.exports = Island; + +/** + * An island of bodies connected with equations. + * @class Island + * @constructor + */ +function Island(){ + + /** + * Current equations in this island. + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Current bodies in this island. + * @property bodies + * @type {Array} + */ + this.bodies = []; +} + +/** + * Clean this island from bodies and equations. + * @method reset + */ +Island.prototype.reset = function(){ + this.equations.length = this.bodies.length = 0; +}; + +var bodyIds = []; + +/** + * Get all unique bodies in this island. + * @method getBodies + * @return {Array} An array of Body + */ +Island.prototype.getBodies = function(result){ + var bodies = result || [], + eqs = this.equations; + bodyIds.length = 0; + for(var i=0; i!==eqs.length; i++){ + var eq = eqs[i]; + if(bodyIds.indexOf(eq.bodyA.id)===-1){ + bodies.push(eq.bodyA); + bodyIds.push(eq.bodyA.id); + } + if(bodyIds.indexOf(eq.bodyB.id)===-1){ + bodies.push(eq.bodyB); + bodyIds.push(eq.bodyB.id); + } + } + return bodies; +}; + +/** + * Check if the entire island wants to sleep. + * @method wantsToSleep + * @return {Boolean} + */ +Island.prototype.wantsToSleep = function(){ + for(var i=0; i= dt && substeps < maxSubSteps) { + // Do fixed steps to catch up + this.internalStep(dt); + this.time += dt; + this.accumulator -= dt; + substeps++; + } + + var t = (this.accumulator % dt) / dt; + for(var j=0; j!==this.bodies.length; j++){ + var b = this.bodies[j]; + vec2.lerp(b.interpolatedPosition, b.previousPosition, b.position, t); + b.interpolatedAngle = b.previousAngle + t * (b.angle - b.previousAngle); + } + } +}; + +var endOverlaps = []; + +/** + * Make a fixed step. + * @method internalStep + * @param {number} dt + * @private + */ +World.prototype.internalStep = function(dt){ + this.stepping = true; + + var that = this, + Nsprings = this.springs.length, + springs = this.springs, + bodies = this.bodies, + g = this.gravity, + solver = this.solver, + Nbodies = this.bodies.length, + broadphase = this.broadphase, + np = this.narrowphase, + constraints = this.constraints, + t0, t1, + fhMinv = step_fhMinv, + velodt = step_velodt, + mg = step_mg, + scale = vec2.scale, + add = vec2.add, + rotate = vec2.rotate, + islandManager = this.islandManager; + + this.overlapKeeper.tick(); + + this.lastTimeStep = dt; + + // Update approximate friction gravity. + if(this.useWorldGravityAsFrictionGravity){ + var gravityLen = vec2.length(this.gravity); + if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){ + // Nonzero gravity. Use it. + this.frictionGravity = gravityLen; + } + } + + // Add gravity to bodies + if(this.applyGravity){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i], + fi = b.force; + if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ + continue; + } + vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g + add(fi,fi,mg); + } + } + + // Add spring forces + if(this.applySpringForces){ + for(var i=0; i!==Nsprings; i++){ + var s = springs[i]; + s.applyForce(); + } + } + + if(this.applyDamping){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + if(b.type === Body.DYNAMIC){ + b.applyDamping(dt); + } + } + } + + // Broadphase + var result = broadphase.getCollisionPairs(this); + + // Remove ignored collision pairs + var ignoredPairs = this.disabledBodyCollisionPairs; + for(var i=ignoredPairs.length-2; 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); + } + } + } + + // Remove constrained pairs with collideConnected == false + 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); + } + } + } + } + + // postBroadphase event + this.postBroadphaseEvent.pairs = result; + this.emit(this.postBroadphaseEvent); + this.postBroadphaseEvent.pairs = null; + + // Narrowphase + np.reset(this); + for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ + var bi = result[i], + bj = result[i+1]; + + // Loop over all shapes of body i + for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ + var si = bi.shapes[k], + xi = si.position, + ai = si.angle; + + // All shapes of body j + for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ + var sj = bj.shapes[l], + xj = sj.position, + aj = sj.angle; + + 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); + } + } + } + + // Wake up bodies + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + if(body._wakeUpAfterNarrowphase){ + body.wakeUp(); + body._wakeUpAfterNarrowphase = false; + } + } + + // Emit end overlap events + 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.bodyB; + this.emit(e); + } + endOverlaps.length = 0; + } + + var preSolveEvent = this.preSolveEvent; + preSolveEvent.contactEquations = np.contactEquations; + preSolveEvent.frictionEquations = np.frictionEquations; + this.emit(preSolveEvent); + preSolveEvent.contactEquations = preSolveEvent.frictionEquations = null; + + // update constraint equations + var Nconstraints = constraints.length; + for(i=0; i!==Nconstraints; i++){ + constraints[i].update(); + } + + if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){ + if(this.islandSplit){ + // Split into islands + 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 { + + // Add contact equations to solver + solver.addEquations(np.contactEquations); + solver.addEquations(np.frictionEquations); + + // Add user-defined constraint equations + for(i=0; i!==Nconstraints; i++){ + solver.addEquations(constraints[i].equations); + } + + if(this.solveConstraints){ + solver.solve(dt,this); + } + + solver.removeAllEquations(); + } + } + + // Step forward + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + + // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){ + body.integrate(dt); + // } + } + + // Reset force + for(var i=0; i!==Nbodies; i++){ + bodies[i].setZeroForce(); + } + + // Emit impact event + 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); + } + } + } + + // Sleeping update + if(this.sleepMode === World.BODY_SLEEPING){ + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, false, dt); + } + } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){ + + // Tell all bodies to sleep tick but dont sleep yet + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, true, dt); + } + + // Sleep islands + for(var i=0; i 0; + np.frictionCoefficient = cm.friction; + var reducedMass; + if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){ + reducedMass = bj.mass; + } else if(bj.type === Body.STATIC || bj.type === 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; + np.contactSkinSize = cm.contactSkinSize; + np.enabledEquations = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse; + + 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 < sj.type) { + numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); + } else { + numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); + } + var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; + + if(numContacts){ + + if( bi.allowSleep && + bi.type === Body.DYNAMIC && + bi.sleepState === Body.SLEEPING && + bj.sleepState === Body.AWAKE && + bj.type !== Body.STATIC + ){ + var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); + var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); + if(speedSquaredB >= speedLimitSquaredB*2){ + bi._wakeUpAfterNarrowphase = true; + } + } + + if( bj.allowSleep && + bj.type === Body.DYNAMIC && + bj.sleepState === Body.SLEEPING && + bi.sleepState === Body.AWAKE && + bi.type !== 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)){ + + // Report new shape overlap + var e = this.beginContactEvent; + e.shapeA = si; + e.shapeB = sj; + e.bodyA = bi; + e.bodyB = bj; + + // Reset contact equations + e.contactEquations.length = 0; + + if(typeof(numContacts)==="number"){ + for(var i=np.contactEquations.length-numContacts; i 1){ // Why divide by 1? + for(var i=np.frictionEquations.length-numFrictionEquations; i=0; i--){ + this.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.bodies; + for(var i=bodies.length-1; i>=0; i--){ + this.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.springs; + for(var i=springs.length-1; i>=0; i--){ + this.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.contactMaterials; + for(var i=cms.length-1; i>=0; i--){ + this.removeContactMaterial(cms[i]); + } + + World.apply(this); +}; + +var hitTest_tmp1 = vec2.create(), + hitTest_zero = vec2.fromValues(0,0), + hitTest_tmp2 = vec2.fromValues(0,0); + +/** + * Test if a world point overlaps bodies + * @method hitTest + * @param {Array} worldPoint Point to use for intersection tests + * @param {Array} bodies A list of objects to check for intersection + * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @return {Array} Array of bodies that overlap the point + * @todo Should use an api similar to the raycast function + * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient + * @todo Should use the broadphase + */ +World.prototype.hitTest = function(worldPoint,bodies,precision){ + precision = precision || 0; + + // Create a dummy particle body with a particle shape to test against the bodies + 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 = []; + + // Check bodies + 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]; + + // Get shape world position + angle + vec2.rotate(x, s.position, b.angle); + vec2.add(x, x, b.position); + var a = s.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)) < precision*precision) + ){ + result.push(b); + } + } + } + + return result; +}; + +/** + * Set the stiffness for all equations and contact materials. + * @method setGlobalStiffness + * @param {Number} stiffness + */ +World.prototype.setGlobalStiffness = function(stiffness){ + + // Set for all constraints + var constraints = this.constraints; + for(var i=0; i !== constraints.length; i++){ + var c = constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.stiffness = stiffness; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + var contactMaterials = this.contactMaterials; + for(var i=0; i !== contactMaterials.length; i++){ + var c = contactMaterials[i]; + c.stiffness = c.frictionStiffness = stiffness; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.stiffness = c.frictionStiffness = stiffness; +}; + +/** + * Set the relaxation for all equations and contact materials. + * @method setGlobalRelaxation + * @param {Number} relaxation + */ +World.prototype.setGlobalRelaxation = function(relaxation){ + + // Set for all constraints + for(var i=0; i !== this.constraints.length; i++){ + var c = this.constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.relaxation = relaxation; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + for(var i=0; i !== this.contactMaterials.length; i++){ + var c = this.contactMaterials[i]; + c.relaxation = c.frictionRelaxation = relaxation; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.relaxation = c.frictionRelaxation = relaxation; +}; + +var tmpAABB = new AABB(); +var tmpArray = []; + +/** + * Ray cast against all bodies in the world. + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @return {boolean} True if any body was hit. + * + * @example + * var ray = new Ray({ + * mode: Ray.CLOSEST, // or ANY + * from: [0, 0], + * to: [10, 0], + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * @example + * var ray = new Ray({ + * mode: Ray.ALL, + * from: [0, 0], + * to: [10, 0], + * callback: function(result){ + * + * // Print some info about the hit + * console.log('Hit body and shape: ', result.body, result.shape); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * // If you are happy with the hits you got this far, you can stop the traversal here: + * result.stop(); + * } + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + */ +World.prototype.raycast = function(result, ray){ + + // Get all bodies within the ray AABB + ray.getAABB(tmpAABB); + this.broadphase.aabbQuery(this, tmpAABB, tmpArray); + ray.intersectBodies(result, tmpArray); + tmpArray.length = 0; + + return result.hasHit(); +}; + +},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36]) +(36) +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +(function(){ + + var root = this; + +/** + * Namespace-class for [pixi.js](http://www.pixijs.com/). + * + * Contains assorted static properties and enumerations. + * + * @namespace PIXI + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ +var PIXI = PIXI || {}; + +/** +* @author Mat Groves http://matgroves.com @Doormat23 +* @author Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The base class for all objects that are rendered. Contains properties for position, scaling, +* rotation, masks and cache handling. +* +* This is an abstract class and should not be used on its own, rather it should be extended. +* +* It is used internally by the likes of PIXI.Sprite. +* +* @class PIXI.DisplayObject +* @constructor +*/ +PIXI.DisplayObject = function () { + + /** + * The coordinates, in pixels, of this DisplayObject, relative to its parent container. + * + * The value of this property does not reflect any positioning happening further up the display list. + * To obtain that value please see the `worldPosition` property. + * + * @property {PIXI.Point} position + * @default + */ + this.position = new PIXI.Point(0, 0); + + /** + * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject + * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on. + * + * The value of this property does not reflect any scaling happening further up the display list. + * To obtain that value please see the `worldScale` property. + * + * @property {PIXI.Point} scale + * @default + */ + this.scale = new PIXI.Point(1, 1); + + /** + * The pivot point of this DisplayObject that it rotates around. The values are expressed + * in pixel values. + * @property {PIXI.Point} pivot + * @default + */ + this.pivot = new PIXI.Point(0, 0); + + /** + * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on + * a right-handed orientation. + * + * The value of this property does not reflect any rotation happening further up the display list. + * To obtain that value please see the `worldRotation` property. + * + * @property {number} rotation + * @default + */ + this.rotation = 0; + + /** + * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * Please note that an object with an alpha value of 0 is skipped during the render pass. + * + * The value of this property does not reflect any alpha values set further up the display list. + * To obtain that value please see the `worldAlpha` property. + * + * @property {number} alpha + * @default + */ + this.alpha = 1; + + /** + * The visibility of this DisplayObject. A value of `false` makes the object invisible. + * A value of `true` makes it visible. Please note that an object with a visible value of + * `false` is skipped during the render pass. Equally a DisplayObject with visible false will + * not render any of its children. + * + * The value of this property does not reflect any visible values set further up the display list. + * To obtain that value please see the `worldVisible` property. + * + * @property {boolean} visible + * @default + */ + this.visible = true; + + /** + * This is the defined area that will pick up mouse / touch events. It is null by default. + * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children) + * + * @property hitArea + * @type Rectangle|Circle|Ellipse|Polygon + */ + this.hitArea = null; + + /** + * Should this DisplayObject be rendered by the renderer? An object with a renderable value of + * `false` is skipped during the render pass. + * + * @property {boolean} renderable + * @default + */ + this.renderable = false; + + /** + * The parent DisplayObjectContainer that this DisplayObject is a child of. + * All DisplayObjects must belong to a parent in order to be rendered. + * The root parent is the Stage object. This property is set automatically when the + * DisplayObject is added to, or removed from, a DisplayObjectContainer. + * + * @property {PIXI.DisplayObjectContainer} parent + * @default + * @readOnly + */ + this.parent = null; + + /** + * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects + * in the display list. + * + * To obtain, and set, the local alpha value, see the `alpha` property. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldAlpha + * @readOnly + */ + this.worldAlpha = 1; + + /** + * The current transform of this DisplayObject. + * + * This property contains the calculated total, based on the transforms of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {Phaser.Matrix} worldTransform + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * The coordinates, in pixels, of this DisplayObject within the world. + * + * This property contains the calculated total, based on the positions of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldPosition + * @readOnly + */ + this.worldPosition = new PIXI.Point(0, 0); + + /** + * The global scale of this DisplayObject. + * + * This property contains the calculated total, based on the scales of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldScale + * @readOnly + */ + this.worldScale = new PIXI.Point(1, 1); + + /** + * The rotation, in radians, of this DisplayObject. + * + * This property contains the calculated total, based on the rotations of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldRotation + * @readOnly + */ + this.worldRotation = 0; + + /** + * The rectangular area used by filters when rendering a shader for this DisplayObject. + * + * @property {PIXI.Rectangle} filterArea + * @type Rectangle + * @default + */ + this.filterArea = null; + + /** + * @property {number} _sr - Cached rotation value. + * @private + */ + this._sr = 0; + + /** + * @property {number} _cr - Cached rotation value. + * @private + */ + this._cr = 1; + + /** + * @property {PIXI.Rectangle} _bounds - The cached bounds of this object. + * @private + */ + this._bounds = new PIXI.Rectangle(0, 0, 0, 0); + + /** + * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object. + * @private + */ + this._currentBounds = null; + + /** + * @property {PIXI.Rectangle} _mask - The cached mask of this object. + * @private + */ + this._mask = null; + + /** + * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag. + * @private + */ + this._cacheAsBitmap = false; + + /** + * @property {boolean} _cacheIsDirty - Internal dirty cache flag. + * @private + */ + this._cacheIsDirty = false; + +}; + +PIXI.DisplayObject.prototype = { + + constructor: PIXI.DisplayObject, + + /** + * Destroy this DisplayObject. + * + * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask. + * + * Also iteratively calls `destroy` on any children. + * + * @method PIXI.DisplayObject#destroy + */ + destroy: function () { + + if (this.children) + { + var i = this.children.length; + + while (i--) + { + this.children[i].destroy(); + } + + this.children = []; + } + + this.hitArea = null; + this.parent = null; + this.worldTransform = null; + this.filterArea = null; + this.renderable = false; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + }, + + /** + * Updates the transform matrix this DisplayObject uses for rendering. + * + * If the object has no parent, and no parent parameter is provided, it will default to + * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place. + * + * The `parent` parameter has priority over the actual parent. Use it as a parent override. + * Setting it does **not** change the actual parent of this DisplayObject. + * + * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale` + * and `worldRotation` properties. + * + * If a `transformCallback` has been specified, it is called at the end of this method, and is passed + * the new, updated, worldTransform property, along with the parent transform used. + * + * @method PIXI.DisplayObject#updateTransform + * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from. + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateTransform: function (parent) { + + if (!parent && !this.parent && !this.game) + { + return this; + } + + var p = this.parent; + + if (parent) + { + p = parent; + } + else if (!this.parent) + { + p = this.game.world; + } + + // create some matrix refs for easy access + var pt = p.worldTransform; + var wt = this.worldTransform; + + // temporary matrix variables + var a, b, c, d, tx, ty; + + // so if rotation is between 0 then we can simplify the multiplication process.. + if (this.rotation % Phaser.Math.PI2) + { + // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes + if (this.rotation !== this.rotationCache) + { + this.rotationCache = this.rotation; + this._sr = Math.sin(this.rotation); + this._cr = Math.cos(this.rotation); + } + + // get the matrix values of the displayobject based on its transform properties.. + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + tx = this.position.x; + ty = this.position.y; + + // check for pivot.. not often used so geared towards that fact! + if (this.pivot.x || this.pivot.y) + { + tx -= this.pivot.x * a + this.pivot.y * c; + ty -= this.pivot.x * b + this.pivot.y * d; + } + + // concat the parent matrix with the objects transform. + wt.a = a * pt.a + b * pt.c; + wt.b = a * pt.b + b * pt.d; + wt.c = c * pt.a + d * pt.c; + wt.d = c * pt.b + d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + else + { + // lets do the fast version as we know there is no rotation.. + a = this.scale.x; + b = 0; + c = 0; + d = this.scale.y; + tx = this.position.x - this.pivot.x * a; + ty = this.position.y - this.pivot.y * d; + + wt.a = a * pt.a; + wt.b = a * pt.b; + wt.c = d * pt.c; + wt.d = d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + + a = wt.a; + b = wt.b; + c = wt.c; + d = wt.d; + + var determ = (a * d) - (b * c); + + if (a || b) + { + var r = Math.sqrt((a * a) + (b * b)); + + this.worldRotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); + this.worldScale.x = r; + this.worldScale.y = determ / r; + } + else if (c || d) + { + var s = Math.sqrt((c * c) + (d * d)); + + this.worldRotation = Phaser.Math.HALF_PI - ((d > 0) ? Math.acos(-c / s) : -Math.acos(c / s)); + this.worldScale.x = determ / s; + this.worldScale.y = s; + } + else + { + this.worldScale.x = 0; + this.worldScale.y = 0; + } + + // Set the World values + this.worldAlpha = this.alpha * p.worldAlpha; + this.worldPosition.x = wt.tx; + this.worldPosition.y = wt.ty; + + // reset the bounds each time this is called! + this._currentBounds = null; + + // Custom callback? + if (this.transformCallback) + { + this.transformCallback.call(this.transformCallbackContext, wt, pt); + } + + return this; + + }, + + /** + * To be overridden by classes that require it. + * + * @method PIXI.DisplayObject#preUpdate + */ + preUpdate: function () { + + }, + + /** + * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites. + * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times. + * + * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures, + * and references to them, so they don't linger in memory. + * + * @method PIXI.DisplayObject#generateTexture + * @param {number} [resolution=1] - The resolution of the texture being generated. + * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values. + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture. + * @return {Phaser.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked. + */ + generateTexture: function (resolution, scaleMode, renderer) { + + var bounds = this.getLocalBounds(); + + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + + renderTexture.render(this, PIXI.DisplayObject._tempMatrix); + + return renderTexture; + + }, + + /** + * If this DisplayObject has a cached Sprite, this method generates and updates it. + * + * @method PIXI.DisplayObject#updateCache + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateCache: function () { + + this._generateCachedSprite(); + + return this; + + }, + + /** + * Calculates the global position of this DisplayObject, based on the position given. + * + * @method PIXI.DisplayObject#toGlobal + * @param {PIXI.Point} position - The global position to calculate from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toGlobal: function (position) { + + this.updateTransform(); + + return this.worldTransform.apply(position); + + }, + + /** + * Calculates the local position of this DisplayObject, relative to another point. + * + * @method PIXI.DisplayObject#toLocal + * @param {PIXI.Point} position - The world origin to calculate from. + * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toLocal: function (position, from) { + + if (from) + { + position = from.toGlobal(position); + } + + this.updateTransform(); + + return this.worldTransform.applyInverse(position); + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_renderCachedSprite + * @private + * @param {Object} renderSession - The render session + */ + _renderCachedSprite: function (renderSession) { + + this._cachedSprite.worldAlpha = this.worldAlpha; + + if (renderSession.gl) + { + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + } + else + { + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + } + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_generateCachedSprite + * @private + */ + _generateCachedSprite: function () { + + this._cacheAsBitmap = false; + + var bounds = this.getLocalBounds(); + + // Round it off and force non-zero dimensions + bounds.width = Math.max(1, Math.ceil(bounds.width)); + bounds.height = Math.max(1, Math.ceil(bounds.height)); + + this.updateTransform(); + + if (!this._cachedSprite) + { + var textureUnit = 0; + if (this.texture && this.texture.baseTexture && PIXI._enableMultiTextureToggle) + { + textureUnit = this.texture.baseTexture.textureIndex; + } + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width, bounds.height, undefined, undefined, undefined, undefined, textureUnit); + this._cachedSprite = new PIXI.Sprite(renderTexture); + this._cachedSprite.worldTransform = this.worldTransform; + } + else + { + this._cachedSprite.texture.resize(bounds.width, bounds.height); + } + + // Remove filters + var tempFilters = this._filters; + + this._filters = null; + this._cachedSprite.filters = tempFilters; + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true); + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + this._filters = tempFilters; + + this._cacheAsBitmap = true; + + }, + + /** + * Destroys a cached Sprite. + * + * @method PIXI.DisplayObject#_destroyCachedSprite + * @private + */ + _destroyCachedSprite: function () { + + if (!this._cachedSprite) + { + return; + } + + this._cachedSprite.texture.destroy(true); + + this._cachedSprite = null; + + } + +}; + +// Alias for updateTransform. As used in DisplayObject container, etc. +PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform; + +Object.defineProperties(PIXI.DisplayObject.prototype, { + + /** + * The horizontal position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#x + * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent. + */ + 'x': { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + } + + }, + + /** + * The vertical position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#y + * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent. + */ + 'y': { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + + }, + + /** + * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + * @name PIXI.DisplayObject#worldVisible + * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + */ + 'worldVisible': { + + get: function () { + + if (!this.visible) + { + return false; + } + else + { + var item = this.parent; + + if (!item) + { + return this.visible; + } + else + { + do + { + if (!item.visible) + { + return false; + } + + item = item.parent; + } + while (item); + + } + + return true; + } + + } + + }, + + /** + * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object. + * When applied it limits the visible area of this DisplayObject to the shape of the mask. + * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer. + * To remove a mask, set this property to `null`. + * + * @name PIXI.DisplayObject#mask + * @property {Phaser.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask. + */ + 'mask': { + + get: function () { + + return this._mask; + + }, + + set: function (value) { + + if (this._mask) + { + this._mask.isMask = false; + } + + this._mask = value; + + if (value) + { + this._mask.isMask = true; + } + + } + + }, + + /** + * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas + * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter + * using `DisplayObject.filterArea`. + * + * To remove filters, set this property to `null`. + * + * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a + * filter will reset this DisplayObjects blend mode to NORMAL. + * + * @name PIXI.DisplayObject#filters + * @property {Array} filters - An Array of Phaser.Filter objects, or objects that extend them. + */ + 'filters': { + + get: function () { + + return this._filters; + + }, + + set: function (value) { + + if (Array.isArray(value)) + { + // Put all the passes in one place. + var passes = []; + + for (var i = 0; i < value.length; i++) + { + var filterPasses = value[i].passes; + + for (var j = 0; j < filterPasses.length; j++) + { + passes.push(filterPasses[j]); + } + } + + // Needed any more? + this._filterBlock = { target: this, filterPasses: passes }; + } + + this._filters = value; + + if (this.blendMode && this.blendMode === PIXI.blendModes.MULTIPLY) + { + this.blendMode = PIXI.blendModes.NORMAL; + } + + } + + }, + + /** + * Sets if this DisplayObject should be cached as a bitmap. + * + * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it + * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a + * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not + * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`. + * + * To remove a cached bitmap, set this property to `null`. + * + * @name PIXI.DisplayObject#cacheAsBitmap + * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap. + */ + 'cacheAsBitmap': { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + if (this._cacheAsBitmap === value) + { + return; + } + + if (value) + { + this._generateCachedSprite(); + } + else + { + this._destroyCachedSprite(); + } + + this._cacheAsBitmap = value; + + } + + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A DisplayObjectContainer represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + * @class PIXI.DisplayObjectContainer + * @extends PIXI.DisplayObject + * @constructor + */ +PIXI.DisplayObjectContainer = function () { + + PIXI.DisplayObject.call(this); + + /** + * [read-only] The array of children of this container. + * + * @property children + * @type Array(DisplayObject) + * @readOnly + */ + this.children = []; + + /** + * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events. + * + * If this property is `true` then the children will _not_ be considered as valid for Input events. + * + * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. + * @property {boolean} ignoreChildInput + * @default + */ + this.ignoreChildInput = false; + +}; + +PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); +PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; + +/** + * Adds a child to the container. + * + * @method PIXI.DisplayObjectContainer#addChild + * @param child {DisplayObject} The DisplayObject to add to the container + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChild = function (child) { + + return this.addChildAt(child, this.children.length); + +}; + +/** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @method PIXI.DisplayObjectContainer#addChildAt + * @param child {DisplayObject} The child to add + * @param index {Number} The index to place the child in + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) { + + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + return child; + } + else + { + throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); + } + +}; + +/** + * Swaps the position of 2 Display Objects within this container. + * + * @method PIXI.DisplayObjectContainer#swapChildren + * @param child {DisplayObject} + * @param child2 {DisplayObject} + */ +PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) { + + if (child === child2) + { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(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; + +}; + +/** + * Returns the index position of a child DisplayObject instance + * + * @method PIXI.DisplayObjectContainer#getChildIndex + * @param child {DisplayObject} The DisplayObject instance to identify + * @return {Number} The index position of the child display object to identify + */ +PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + +}; + +/** + * Changes the position of an existing child in the display object container + * + * @method PIXI.DisplayObjectContainer#setChildIndex + * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number + * @param index {Number} The resulting index number for the child display object + */ +PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + this.children.splice(currentIndex, 1); //remove from old position + this.children.splice(index, 0, child); //add at new position + +}; + +/** + * Returns the child at the specified index + * + * @method PIXI.DisplayObjectContainer#getChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child at the given index, if any. + */ +PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller'); + } + + return this.children[index]; + +}; + +/** + * Removes a child from the container. + * + * @method PIXI.DisplayObjectContainer#removeChild + * @param child {DisplayObject} The DisplayObject to remove + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChild = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + return; + } + + return this.removeChildAt(index); + +}; + +/** + * Removes a child from the specified index position. + * + * @method PIXI.DisplayObjectContainer#removeChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) { + + var child = this.getChildAt(index); + + if (child) + { + child.parent = undefined; + + this.children.splice(index, 1); + } + + return child; + +}; + +/** +* Removes all children from this container that are within the begin and end indexes. +* +* @method PIXI.DisplayObjectContainer#removeChildren +* @param beginIndex {Number} The beginning position. Default value is 0. +* @param endIndex {Number} The ending position. Default value is size of the container. +*/ +PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { + + if (beginIndex === undefined) { beginIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var range = endIndex - beginIndex; + + if (range > 0 && range <= endIndex) + { + var removed = this.children.splice(beginIndex, range); + + for (var i = 0; i < removed.length; i++) + { + var child = removed[i]; + child.parent = undefined; + } + + return removed; + } + else if (range === 0 && this.children.length === 0) + { + return []; + } + else + { + throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' ); + } + +}; + +/* + * Updates the transform on all children of this container for rendering + * + * @method PIXI.DisplayObjectContainer#updateTransform + * @private + */ +PIXI.DisplayObjectContainer.prototype.updateTransform = function () { + + if (!this.visible) + { + return; + } + + this.displayObjectUpdateTransform(); + + if (this._cacheAsBitmap) + { + return; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +// performance increase to avoid using call.. (10x faster) +PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform; + +/** + * Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getBounds + * @param {PIXI.DisplayObject|Phaser.Matrix} [targetCoordinateSpace] Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpace) { + + var isTargetCoordinateSpaceDisplayObject = (targetCoordinateSpace && targetCoordinateSpace instanceof PIXI.DisplayObject); + var isTargetCoordinateSpaceThisOrParent = true; + + if (!isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace = this; + } + else if (targetCoordinateSpace instanceof PIXI.DisplayObjectContainer) + { + isTargetCoordinateSpaceThisOrParent = targetCoordinateSpace.contains(this); + } + else + { + isTargetCoordinateSpaceThisOrParent = false; + } + + var i; + + if (isTargetCoordinateSpaceDisplayObject) + { + var matrixCache = targetCoordinateSpace.worldTransform; + + targetCoordinateSpace.worldTransform = Phaser.identityMatrix; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + var minX = Infinity; + var minY = Infinity; + + var maxX = -Infinity; + var maxY = -Infinity; + + var childBounds; + var childMaxX; + var childMaxY; + + var childVisible = false; + + for (i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + childVisible = true; + + childBounds = this.children[i].getBounds(); + + minX = (minX < childBounds.x) ? minX : childBounds.x; + minY = (minY < childBounds.y) ? minY : childBounds.y; + + childMaxX = childBounds.width + childBounds.x; + childMaxY = childBounds.height + childBounds.y; + + maxX = (maxX > childMaxX) ? maxX : childMaxX; + maxY = (maxY > childMaxY) ? maxY : childMaxY; + } + + var bounds = this._bounds; + + if (!childVisible) + { + bounds = new PIXI.Rectangle(); + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + maxX = x1; + maxY = y1; + + minX = x1; + minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + } + + bounds.x = minX; + bounds.y = minY; + bounds.width = maxX - minX; + bounds.height = maxY - minY; + + if (isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace.worldTransform = matrixCache; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + if (!isTargetCoordinateSpaceThisOrParent) + { + var targetCoordinateSpaceBounds = targetCoordinateSpace.getBounds(); + + bounds.x -= targetCoordinateSpaceBounds.x; + bounds.y -= targetCoordinateSpaceBounds.y; + } + + return bounds; + +}; + +/** + * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getLocalBounds = function () { + + return this.getBounds(this); + +}; + +/** +* Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. +* +* @method PIXI.DisplayObjectContainer#contains +* @param {DisplayObject} child +* @returns {boolean} +*/ +PIXI.DisplayObjectContainer.prototype.contains = function (child) { + + if (!child) + { + return false; + } + else if (child === this) + { + return true; + } + else + { + return this.contains(child.parent); + } +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.DisplayObjectContainer#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + var i; + + if (this._mask || this._filters) + { + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + renderSession.spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + renderSession.spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + renderSession.spriteBatch.start(); + } + + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + renderSession.spriteBatch.start(); + } + else + { + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.DisplayObjectContainer#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) { + + if (this.visible === false || this.alpha === 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', { + + get: function() { + return this.getLocalBounds().width * this.scale.x; + }, + + set: function(value) { + + var width = this.getLocalBounds().width; + + if (width !== 0) + { + this.scale.x = value / width; + } + else + { + this.scale.x = 1; + } + + this._width = value; + } +}); + +/** + * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', { + + get: function() { + return this.getLocalBounds().height * this.scale.y; + }, + + set: function(value) { + + var height = this.getLocalBounds().height; + + if (height !== 0) + { + this.scale.y = value / height; + } + else + { + this.scale.y = 1; + } + + this._height = value; + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * @class PIXI.Sprite + * @extends PIXI.DisplayObjectContainer + * @constructor + * @param texture {Texture} The texture for this sprite + */ +PIXI.Sprite = function (texture) { + + PIXI.DisplayObjectContainer.call(this); + + /** + * The anchor sets the origin point of the texture. + * The default (0, 0) is the top left. + * (0.5, 0.5) is the center. + * (1, 1) is the bottom right. + * + * You can modify the default values in PIXI.Sprite.defaultAnchor. + * + * @property anchor + * @type Point + */ + this.anchor = new PIXI.Point(PIXI.Sprite.defaultAnchor.x, PIXI.Sprite.defaultAnchor.y); + + /** + * The texture that the sprite is using + * + * @property texture + * @type Texture + */ + this.texture = texture || PIXI.Texture.emptyTexture; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @property _width + * @type Number + * @private + */ + this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @property _height + * @type Number + * @private + */ + this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF (Phaser.Color.WHITE) will remove any tint effect. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @property cachedTint + * @private + * @type Number + * @default -1 + */ + this.cachedTint = -1; + + /** + * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) + * + * @property tintedTexture + * @type Canvas + * @default null + */ + this.tintedTexture = null; + + /** + * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. + * + * Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * The shader that will be used to render this Sprite. + * Set to null to remove a current shader. + * + * @property shader + * @type Phaser.Filter + * @default null + */ + this.shader = null; + + /** + * Controls if this Sprite is processed by the core Phaser game loops and Group loops (except {@link Phaser.Group#update}). + * + * @property exists + * @type Boolean + * @default true + */ + this.exists = true; + + if (this.texture.baseTexture.hasLoaded) + { + this.onTextureUpdate(); + } + + this.renderable = true; + +}; + +/** + * @property PIXI.Sprite.defaultAnchor - A Point-like object. + * @type {{x: number, y: number}} + * @default + */ +PIXI.Sprite.defaultAnchor = {x: 0, y: 0}; + +// constructor +PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +PIXI.Sprite.prototype.constructor = PIXI.Sprite; + +/** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'width', { + + get: function() { + return this.scale.x * this.texture.frame.width; + }, + + set: function(value) { + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'height', { + + get: function() { + return this.scale.y * this.texture.frame.height; + }, + + set: function(value) { + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +/** + * Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous + * texture this Sprite was using. + * + * @method PIXI.Sprite#setTexture + * @param texture {Texture} The PIXI texture that is displayed by the sprite + * @param [destroy=false] {boolean} Call Texture.destroy on the current texture before replacing it with the new one? + */ +PIXI.Sprite.prototype.setTexture = function(texture, destroyBase) +{ + if (destroyBase) + { + this.texture.baseTexture.destroy(); + } + + // Over-ridden by loadTexture as needed + this.texture.baseTexture.skipRender = false; + this.texture = texture; + this.texture.valid = true; + this.cachedTint = -1; +}; + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @method PIXI.Sprite#onTextureUpdate + * @param event + * @private + */ +PIXI.Sprite.prototype.onTextureUpdate = function() +{ + // so if _width is 0 then width was not set.. + if (this._width) this.scale.x = this._width / this.texture.frame.width; + if (this._height) this.scale.y = this._height / this.texture.frame.height; +}; + +/** +* Returns the bounds of the Sprite as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* It is important to note that the transform is not updated when you call this method. +* So if this Sprite is the child of a Display Object which has had its transform +* updated since the last render pass, those changes will not yet have been applied +* to this Sprites worldTransform. If you need to ensure that all parent transforms +* are factored into this getBounds operation then you should call `updateTransform` +* on the root most object in this Sprites display list first. +* +* @method PIXI.Sprite#getBounds +* @param matrix {Matrix} the transformation matrix of the sprite +* @return {Rectangle} the framing rectangle +*/ +PIXI.Sprite.prototype.getBounds = function(matrix) +{ + var width = this.texture.frame.width; + var height = this.texture.frame.height; + + var w0 = width * (1-this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1-this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + if (b === 0 && c === 0) + { + // scale may be negative! + if (a < 0) + { + a *= -1; + var temp = w0; + w0 = -w1; + w1 = -temp; + } + + if (d < 0) + { + d *= -1; + var temp = h0; + h0 = -h1; + h1 = -temp; + } + + // this means there is no rotation going on right? RIGHT? + // if thats the case then we can avoid checking the bound values! yay + minX = a * w1 + tx; + maxX = a * w0 + tx; + minY = d * h1 + ty; + maxY = d * h0 + ty; + } + else + { + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; +}; + +/** + * Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. + * + * @method PIXI.Sprite#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.Sprite.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.Sprite#_renderWebGL +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix) +{ + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha <= 0 || !this.renderable) return; + + // They provided an alternative rendering matrix, so use it + var wt = this.worldTransform; + + if (matrix) + { + wt = matrix; + } + + // A quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) + { + var spriteBatch = renderSession.spriteBatch; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + spriteBatch.start(); + } + + // add this sprite to the batch + spriteBatch.render(this); + + // now loop through the children and make sure they get rendered + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + // time to stop the sprite batch as either a mask element or a filter draw will happen next + spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + spriteBatch.start(); + } + else + { + renderSession.spriteBatch.render(this); + + // Render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession, wt); + } + + } +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.Sprite#_renderCanvas +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix) +{ + // If the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha === 0 || !this.renderable || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { + return; + } + + var wt = this.worldTransform; + + // If they provided an alternative rendering matrix then use it + if (matrix) + { + wt = matrix; + } + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + // Ignore null sources + if (!this.texture.valid) + { + // Update the children and leave + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + return; + } + + var resolution = this.texture.baseTexture.resolution / renderSession.resolution; + + renderSession.context.globalAlpha = this.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for this texture + if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode) + { + renderSession.scaleMode = this.texture.baseTexture.scaleMode; + renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + + // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions + var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width; + var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height; + + var tx = (wt.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (wt.ty * renderSession.resolution) + renderSession.shakeY; + + var cw = this.texture.crop.width; + var ch = this.texture.crop.height; + + if (this.texture.rotated) + { + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var e = cw; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + wt.a = a * 6.123233995736766e-17 + -c; + wt.b = b * 6.123233995736766e-17 + -d; + wt.c = a + c * 6.123233995736766e-17; + wt.d = b + d * 6.123233995736766e-17; + + // Update cropping dimensions. + cw = ch; + ch = e; + } + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx | 0, ty | 0); + dx |= 0; + dy |= 0; + } + else + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + } + + dx /= resolution; + dy /= resolution; + + if (this.tint !== 0xFFFFFF) + { + if (this.texture.requiresReTint || this.cachedTint !== this.tint) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + } + + renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + else + { + var cx = this.texture.crop.x; + var cy = this.texture.crop.y; + + cw = Math.floor(cw) + ch = Math.floor(ch) + + renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @method PIXI.initDefaultShaders +* @static +* @private +*/ +PIXI.initDefaultShaders = function() +{ +}; + +/** +* @method PIXI.CompileVertexShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileVertexShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); +}; + +/** +* @method PIXI.CompileFragmentShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileFragmentShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); +}; + +/** +* @method PIXI._CompileShader +* @static +* @private +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @param shaderType {Number} +* @return {Any} +*/ +PIXI._CompileShader = function(gl, shaderSrc, shaderType) +{ + var src = shaderSrc; + + if (Array.isArray(shaderSrc)) + { + 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; +}; + +/** +* @method PIXI.compileProgram +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param vertexSrc {Array} +* @param fragmentSrc {Array} +* @return {Any} +*/ +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(gl.getProgramInfoLog(shaderProgram)); + window.console.log("Could not initialise shaders"); + } + + return shaderProgram; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + * @author Richard Davey http://www.photonstorm.com @photonstorm + */ + +/** +* @class PIXI.PixiShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PixiShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = null; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + /** + * A local flag + * @property firstRun + * @type Boolean + * @private + */ + this.firstRun = true; + + /** + * A dirty flag + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Uniform attributes cache. + * @property attributes + * @type Array + * @private + */ + this.attributes = []; + + this.init(); +}; + +PIXI.PixiShader.prototype.constructor = PIXI.PixiShader; + +PIXI.PixiShader.prototype.initMultitexShader = function () { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.fragmentSrc = [ + '// PixiShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}', + '}' + ]; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + //this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.uSamplerArray = gl.getUniformLocation(program, 'uSamplerArray[0]'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSamplerArray, indices); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; + +PIXI.PixiShader.prototype.initDefaultShader = function () { + + if (this.fragmentSrc === null) { + this.fragmentSrc = [ + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', + '}' + ]; + } + + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; +/** +* Initialises the shader. +* +* @method PIXI.PixiShader#init +*/ +PIXI.PixiShader.prototype.init = function(usingFilter) +{ + if (PIXI._enableMultiTextureToggle && !usingFilter) { + this.initMultitexShader(); + } else { + this.initDefaultShader(); + } +}; + +/** +* Initialises the shader uniform values. +* +* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ +* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf +* +* @method PIXI.PixiShader#initUniforms +*/ +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') + { + // These require special handling + 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 + { + // GL function reference + 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; + } + } + } + +}; + +/** +* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) +* +* @method PIXI.PixiShader#initSampler2D +*/ +PIXI.PixiShader.prototype.initSampler2D = function(uniform) +{ + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { + return; + } + + var gl = this.gl; + + // No need to do string manipulation for this. + gl.activeTexture(gl.TEXTURE0 + this.textureCount); + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + + // Extended texture data + if (uniform.textureData) + { + var data = uniform.textureData; + + // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); + // GLTextureLinear = mag/min linear, wrap clamp + // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat + // GLTextureNearest = mag/min nearest, wrap clamp + // AudioTexture = whatever + luminance + width 512, height 2, border 0 + // KeyTexture = whatever + luminance + width 256, height 2, border 0 + + // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + + 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; + + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels); + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); + } + else + { + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels); + 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++; + +}; + +/** +* Updates the shader uniform values. +* +* @method PIXI.PixiShader#syncUniforms +*/ +PIXI.PixiShader.prototype.syncUniforms = function() +{ + this.textureCount = 1; + var uniform; + var gl = this.gl; + + // This would probably be faster in an array and it would guarantee key order + 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]); + + if(uniform.value.baseTexture._dirty[gl.id]) + { + PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + } + + // 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); + } + } + } + +}; + +/** +* Destroys the shader. +* +* @method PIXI.PixiShader#destroy +*/ +PIXI.PixiShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** +* The Default Vertex shader source. +* +* @property defaultVertexSrc +* @type String +*/ +PIXI.PixiShader.defaultVertexSrc = [ + '// PixiShader Vertex Shader', + '// With multi-texture rendering', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute vec4 aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + + 'const vec2 center = vec2(-1.0, 1.0);', + + 'void main(void) {', + ' if (aTextureIndex > 0.0) gl_Position = vec4(0.0);', + ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', + ' vTextureCoord = aTextureCoord;', + ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', + ' vTextureIndex = aTextureIndex;', + '}' +]; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @class PIXI.PixiFastShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.PixiFastShader = function (gl) { + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '// PixiFastShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aPositionCoord;', + 'attribute vec2 aScale;', + 'attribute float aRotation;', + 'attribute vec2 aTextureCoord;', + 'attribute float aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform mat3 uMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + + '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;', + ' vTextureIndex = aTextureIndex;', + // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;', + ' vColor = aColor;', + '}' + ]; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + this.init(); +}; + +PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader; + +/** + * Initialises the shader. + * + * @method PIXI.PixiFastShader#init + */ +PIXI.PixiFastShader.prototype.init = function () { + + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + this.uMatrix = gl.getUniformLocation(program, 'uMatrix'); + + // get and store the attributes + 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'); + + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its somthing to do with the current state of the gl context. + // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if (this.colorAttribute === -1) { + this.colorAttribute = 2; + } + + this.attributes = [ + this.aVertexPosition, + this.aPositionCoord, + this.aScale, + this.aRotation, + this.aTextureCoord, + this.colorAttribute, + this.aTextureIndex + ]; + + // End worst hack eva // + + this.program = program; +}; + +/** + * Destroys the shader. + * + * @method PIXI.PixiFastShader#destroy + */ +PIXI.PixiFastShader.prototype.destroy = function () { + this.gl.deleteProgram(this.program); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.StripShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.StripShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord);return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) ;return;}\n' + } + + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord);', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '//StripShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute float aTextureIndex;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + // 'uniform float alpha;', + // 'uniform vec3 tint;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // '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);', + ' vTextureCoord = aTextureCoord;', + ' vTextureIndex = aTextureIndex;', + // ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.StripShader.prototype.constructor = PIXI.StripShader; + +/** +* Initialises the shader. +* +* @method PIXI.StripShader#init +*/ +PIXI.StripShader.prototype.init = function() +{ + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + //this.dimensions = gl.getUniformLocation(this.program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.aTextureIndex]; + + this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix'); + this.alpha = gl.getUniformLocation(program, 'alpha'); + + this.program = program; +}; + +/** +* Destroys the shader. +* +* @method PIXI.StripShader#destroy +*/ +PIXI.StripShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.PrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + 'precision mediump float;', + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform float alpha;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.PrimitiveShader#init +*/ +PIXI.PrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.PrimitiveShader#destroy +*/ +PIXI.PrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.ComplexPrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.ComplexPrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + + 'precision mediump float;', + + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + //'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 color;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.ComplexPrimitiveShader#init +*/ +PIXI.ComplexPrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.color = gl.getUniformLocation(program, 'color'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.ComplexPrimitiveShader#destroy +*/ +PIXI.ComplexPrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +PIXI.glContexts = []; // this is where we store the webGL contexts for easy access. +PIXI.instances = []; +PIXI._enableMultiTextureToggle = false; + +/** + * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class PIXI.WebGLRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.WebGLRenderer = function(game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + this.extensions = {}; + + /** + * @property type + * @type Number + */ + this.type = Phaser.WEBGL; + + /** + * The resolution of the renderer + * + * @property resolution + * @type Number + * @default 1 + */ + this.resolution = game.resolution; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * + * @property preserveDrawingBuffer + * @type Boolean + */ + this.preserveDrawingBuffer = game.preserveDrawingBuffer; + + /** + * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true: + * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0). + * If the Stage is transparent, Pixi will clear to the target Stage's background color. + * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * The width of the canvas view + * + * @property width + * @type Number + */ + this.width = game.width; + + /** + * The height of the canvas view + * + * @property height + * @type Number + */ + this.height = game.height; + + /** + * The canvas element that everything is drawn to + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * @property _contextOptions + * @type Object + * @private + */ + this._contextOptions = { + alpha: this.transparent, + antialias: game.antialias, + failIfMajorPerformanceCaveat: config.failIfMajorPerformanceCaveat, + premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: this.preserveDrawingBuffer + }; + + /** + * @property projection + * @type Point + */ + this.projection = new PIXI.Point(); + + /** + * @property offset + * @type Point + */ + this.offset = new PIXI.Point(); + + // time to create the render managers! each one focuses on managing a state in webGL + + /** + * Deals with managing the shader programs and their attribs + * @property shaderManager + * @type WebGLShaderManager + */ + this.shaderManager = new PIXI.WebGLShaderManager(); + + /** + * Manages the rendering of sprites + * @property spriteBatch + * @type WebGLSpriteBatch + */ + this.spriteBatch = new PIXI.WebGLSpriteBatch(game); + + /** + * Manages the masks using the stencil buffer + * @property maskManager + * @type WebGLMaskManager + */ + this.maskManager = new PIXI.WebGLMaskManager(); + + /** + * Manages the filters + * @property filterManager + * @type WebGLFilterManager + */ + this.filterManager = new PIXI.WebGLFilterManager(); + + /** + * Manages the stencil buffer + * @property stencilManager + * @type WebGLStencilManager + */ + this.stencilManager = new PIXI.WebGLStencilManager(); + + /** + * Manages the blendModes + * @property blendModeManager + * @type WebGLBlendModeManager + */ + this.blendModeManager = new PIXI.WebGLBlendModeManager(); + + /** + * @property renderSession + * @type Object + */ + this.renderSession = {}; + + /** + * @property currentBatchedTextures + * @type Array + */ + this.currentBatchedTextures = []; + + // Needed? + this.renderSession.game = this.game; + this.renderSession.gl = this.gl; + this.renderSession.drawCount = 0; + this.renderSession.shaderManager = this.shaderManager; + this.renderSession.maskManager = this.maskManager; + this.renderSession.filterManager = this.filterManager; + this.renderSession.blendModeManager = this.blendModeManager; + this.renderSession.spriteBatch = this.spriteBatch; + this.renderSession.stencilManager = this.stencilManager; + this.renderSession.renderer = this; + this.renderSession.resolution = this.resolution; + this.renderSession.roundPixels = config.roundPixels || false; + this.renderSession.maxTextureAvailableSpace = null; // filled in setTexturePriority() + + // time init the context.. + this.initContext(); + + // map some webGL blend modes.. + this.mapBlendModes(); + +}; + +// constructor +PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer; + +/** +* @method PIXI.WebGLRenderer#initContext +*/ +PIXI.WebGLRenderer.prototype.initContext = function() +{ + var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); + + this.gl = gl; + + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + this.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.maxTextureSize = this.gl.getParameter(gl.MAX_TEXTURE_SIZE); + + this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++; + + PIXI.glContexts[this.glContextId] = gl; + + PIXI.instances[this.glContextId] = this; + + // set up the default pixi settings.. + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + gl.enable(gl.BLEND); + + // need to set the context for all the managers... + this.shaderManager.setContext(gl); + this.spriteBatch.setContext(gl); + this.maskManager.setContext(gl); + this.filterManager.setContext(gl); + this.blendModeManager.setContext(gl); + this.stencilManager.setContext(gl); + + this.renderSession.gl = this.gl; + + // now resize and we are good to go! + this.resize(this.width, this.height); + + // Load WebGL extension + this.extensions.compression = {}; + + var etc1 = gl.getExtension('WEBGL_compressed_texture_etc1') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'); + var pvrtc = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); + var s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); + + if (etc1) { this.extensions.compression.ETC1 = etc1; } + if (pvrtc) { this.extensions.compression.PVRTC = pvrtc; } + if (s3tc) { this.extensions.compression.S3TC = s3tc; } +}; + +/** +* If Multi Texture support has been enabled, then calling this method will enable batching on the given +* textures. The texture collection is an array of keys, that map to Phaser.Cache image entries. +* +* The number of textures that can be batched is dependent on hardware. If you provide more textures +* than can be batched by the GPU, then only those at the start of the array will be used. Generally +* you shouldn't provide more than 16 textures to this method. You can check the hardware limit via the +* `maxTextures` property. +* +* You can also check the property `currentBatchedTextures` at any time, to see which textures are currently +* being batched. +* +* To stop all textures from being batched, call this method again with an empty array. +* +* To change the textures being batched, call this method with a new array of image keys. The old ones +* will all be purged out and no-longer batched, and the new ones enabled. +* +* Note: Throws a warning if you haven't enabled Multiple Texture batching support in the Phaser Game config. +* +* @method PIXI.WebGLRenderer#setTexturePriority +* @param textureNameCollection {Array} An Array of Texture Cache keys to use for multi-texture batching. +* @return {Array} An array containing the texture keys that were enabled for batching. +*/ +PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + if (!PIXI._enableMultiTextureToggle) + { + console.warn('setTexturePriority error: Multi Texture support hasn\'t been enabled in the Phaser Game Config.'); + return; + } + var clampPot = function (potSize) { + --potSize; + potSize |= potSize >> 1; + potSize |= potSize >> 2; + potSize |= potSize >> 4; + potSize |= potSize >> 8; + potSize |= potSize >> 16; + return ++potSize; + }; + var gl = this.gl; + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + var imageCache = this.game.cache._cache.image; + var imageName = null; + + // Clear out all previously batched textures and reset their flags. + // If the array has been modified, then the developer will have to + // deal with that in their own way. + for (var i = 0; i < this.currentBatchedTextures.length; i++) + { + imageName = this.currentBatchedTextures[i]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + + imageCache[imageName].base.textureIndex = 0; + } + var maxTextureAvailableSpace = (maxTextureSize) - clampPot(Math.max(this.width, this.height)); + this.currentBatchedTextures.length = 0; + // We start from 1 because framebuffer texture uses unit 0. + for (var j = 0; j < textureNameCollection.length; ++j) + { + imageName = textureNameCollection[j]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + // Unit 0 is reserved for Pixi's framebuffer + var base = imageCache[imageName].base; + maxTextureAvailableSpace -= clampPot(Math.max(base.width, base.height)); + if (maxTextureAvailableSpace <= 0) { + base.textureIndex = 0; + console.warn('setTexturePriority: Image "%s" was given textureIndex=0 because there is no available texture space (%s).', + imageName, maxTextureAvailableSpace); + } else { + base.textureIndex = (1 + (j % (maxTextures - 1))); + } + this.currentBatchedTextures.push(imageName); + } + + this.renderSession.maxTextureAvailableSpace = maxTextureAvailableSpace; + + return this.currentBatchedTextures; + +}; + +/** + * Renders the stage to its webGL view + * + * @method PIXI.WebGLRenderer#render + * @param stage {Stage} the Stage element to be rendered + */ +PIXI.WebGLRenderer.prototype.render = function(stage) +{ + // no point rendering if our context has been blown up! + if (this.contextLost) + { + return; + } + + var gl = this.gl; + + // -- Does this need to be set every frame? -- // + gl.viewport(0, 0, this.width, this.height); + + // make sure we are bound to the main frame buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + if (this.game.clearBeforeRender) + { + gl.clearColor(stage._bgColor.r, stage._bgColor.g, stage._bgColor.b, stage._bgColor.a); + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + this.offset.x = this.game.camera._shake.x; + this.offset.y = this.game.camera._shake.y; + + this.renderDisplayObject(stage, this.projection); +}; + +/** + * Renders a Display Object. + * + * @method PIXI.WebGLRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The DisplayObject to render + * @param projection {Point} The projection + * @param buffer {Array} a standard WebGL buffer + */ +PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix) +{ + this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL); + + // reset the render session data.. + this.renderSession.drawCount = 0; + + // make sure to flip the Y if using a render texture.. + this.renderSession.flipY = buffer ? -1 : 1; + + // set the default projection + this.renderSession.projection = projection; + + //set the default offset + this.renderSession.offset = this.offset; + + // start the sprite batch + this.spriteBatch.begin(this.renderSession); + + // start the filter manager + this.filterManager.begin(this.renderSession, buffer); + + // render the scene! + displayObject._renderWebGL(this.renderSession, matrix); + + // finish the sprite batch + this.spriteBatch.end(); +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @method PIXI.WebGLRenderer#resize + * @param width {Number} the new width of the webGL view + * @param height {Number} the new height of the webGL view + */ +PIXI.WebGLRenderer.prototype.resize = function(width, height) +{ + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } + + this.gl.viewport(0, 0, this.width, this.height); + + this.projection.x = this.width / 2 / this.resolution; + this.projection.y = -this.height / 2 / this.resolution; +}; + +/** + * Updates and creates a WebGL compressed texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateCompressedTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateCompressedTexture = function (texture) { + if (!texture.hasLoaded) + { + return false; + } + var gl = this.gl; + var textureMetaData = texture.source; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + textureMetaData.glExtensionFormat, + textureMetaData.width, + textureMetaData.height, + 0, + textureMetaData.textureData + ); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + texture._dirty[gl.id] = false; + return true; +}; + +/** + * Updates and Creates a WebGL texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateTexture = function(texture) +{ + if (!texture.hasLoaded) + { + return false; + } + if (texture.source.compressionAlgorithm) { + return this.updateCompressedTexture(texture); + } + + var gl = this.gl; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha); + + 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); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + + texture._dirty[gl.id] = false; + + // return texture._glTextures[gl.id]; + return true; + +}; + +/** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @method PIXI.WebGLRenderer#destroy + */ +PIXI.WebGLRenderer.prototype.destroy = function() +{ + 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; + + Phaser.CanvasPool.remove(this); + + PIXI.instances[this.glContextId] = null; + + PIXI.WebGLRenderer.glContextId--; +}; + +/** + * Maps Pixi blend modes to WebGL blend modes. + * + * @method PIXI.WebGLRenderer#mapBlendModes + */ +PIXI.WebGLRenderer.prototype.mapBlendModes = function() +{ + var gl = this.gl; + + if (!PIXI.blendModesWebGL) + { + var b = []; + var modes = PIXI.blendModes; + + b[modes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA]; + b[modes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SCREEN] = [gl.SRC_ALPHA, gl.ONE]; + b[modes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + PIXI.blendModesWebGL = b; + } +}; + +PIXI.WebGLRenderer.prototype.getMaxTextureUnit = function() { + var gl = this.gl; + return gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); +}; + +PIXI.enableMultiTexture = function() { + PIXI._enableMultiTextureToggle = true; +}; + +PIXI.WebGLRenderer.glContextId = 0; +PIXI.WebGLRenderer.textureArray = []; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLBlendModeManager +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLBlendModeManager = function() +{ + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 99999; +}; + +PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLBlendModeManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLBlendModeManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Sets-up the given blendMode from WebGL's point of view. +* +* @method PIXI.WebGLBlendModeManager#setBlendMode +* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD +*/ +PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode) +{ + if(this.currentBlendMode === blendMode)return false; + + this.currentBlendMode = blendMode; + + var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode]; + + if (blendModeWebGL) + { + this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLBlendModeManager#destroy +*/ +PIXI.WebGLBlendModeManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLMaskManager +* @constructor +* @private +*/ +PIXI.WebGLMaskManager = function() +{ +}; + +PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLMaskManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLMaskManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLMaskManager#pushMask +* @param maskData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession) +{ + var gl = renderSession.gl; + + if (maskData.dirty) + { + PIXI.WebGLGraphics.updateGraphics(maskData, gl); + } + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLMaskManager#popMask +* @param maskData {Array} +* @param renderSession {Object} an object containing all the useful parameters +*/ +PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession) +{ + var gl = this.gl; + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); + +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLMaskManager#destroy +*/ +PIXI.WebGLMaskManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLStencilManager +* @constructor +* @private +*/ +PIXI.WebGLStencilManager = function() +{ + this.stencilStack = []; + this.reverse = true; + this.count = 0; +}; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLStencilManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLStencilManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLStencilManager#pushMask +* @param graphics {Graphics} +* @param webGLData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.bindGraphics(graphics, webGLData, renderSession); + + if(this.stencilStack.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + this.reverse = true; + this.count = 0; + } + + this.stencilStack.push(webGLData); + + var level = this.count; + + gl.colorMask(false, false, false, false); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + + if(webGLData.mode === 1) + { + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + + this.reverse = !this.reverse; + } + else + { + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + this.count++; +}; + +/** + * TODO this does not belong here! + * + * @method PIXI.WebGLStencilManager#bindGraphics + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession) +{ + //if(this._currentGraphics === graphics)return; + this._currentGraphics = graphics; + + var gl = this.gl; + + // bind the graphics object.. + var projection = renderSession.projection, + offset = renderSession.offset, + shader;// = renderSession.shaderManager.primitiveShader; + + if(webGLData.mode === 1) + { + shader = renderSession.shaderManager.complexPrimitiveShader; + + renderSession.shaderManager.setShader( shader ); + + gl.uniform1f(shader.flipY, renderSession.flipY); + + 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, Phaser.Color.hexToRGBArray(graphics.tint)); + gl.uniform3fv(shader.color, webGLData.color); + + gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0); + + + // now do the rest.. + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } + else + { + //renderSession.shaderManager.activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + renderSession.shaderManager.setShader( shader ); + + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, renderSession.flipY); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } +}; + +/** + * @method PIXI.WebGLStencilManager#popStencil + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.stencilStack.pop(); + + this.count--; + + if(this.stencilStack.length === 0) + { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + + } + else + { + + var level = this.count; + + this.bindGraphics(graphics, webGLData, renderSession); + + gl.colorMask(false, false, false, false); + + if(webGLData.mode === 1) + { + this.reverse = !this.reverse; + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + + } + else + { + // console.log("<<>>") + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + + } +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLStencilManager#destroy +*/ +PIXI.WebGLStencilManager.prototype.destroy = function() +{ + this.stencilStack = null; + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLShaderManager +* @constructor +* @private +*/ +PIXI.WebGLShaderManager = function() +{ + /** + * @property maxAttibs + * @type Number + */ + this.maxAttibs = 10; + + /** + * @property attribState + * @type Array + */ + this.attribState = []; + + /** + * @property tempAttribState + * @type Array + */ + this.tempAttribState = []; + + for (var i = 0; i < this.maxAttibs; i++) + { + this.attribState[i] = false; + } + + /** + * @property stack + * @type Array + */ + this.stack = []; + +}; + +PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLShaderManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLShaderManager.prototype.setContext = function(gl) +{ + this.gl = gl; + + // the next one is used for rendering primitives + this.primitiveShader = new PIXI.PrimitiveShader(gl); + + // the next one is used for rendering triangle strips + this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl); + + // this shader is used for the default sprite rendering + this.defaultShader = new PIXI.PixiShader(gl); + + // this shader is used for the fast sprite rendering + this.fastShader = new PIXI.PixiFastShader(gl); + + // the next one is used for rendering triangle strips + this.stripShader = new PIXI.StripShader(gl); + + // the next one is used for rendering creature meshes + this.creatureShader = PIXI.CreatureShader ? new PIXI.CreatureShader(gl) : null; + + this.setShader(this.defaultShader); +}; + +/** +* Takes the attributes given in parameters. +* +* @method PIXI.WebGLShaderManager#setAttribs +* @param attribs {Array} attribs +*/ +PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs) +{ + // reset temp state + var i; + + for (i = 0; i < this.tempAttribState.length; i++) + { + this.tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + var attribId = attribs[i]; + this.tempAttribState[attribId] = true; + } + + var gl = this.gl; + + for (i = 0; i < this.attribState.length; i++) + { + if(this.attribState[i] !== this.tempAttribState[i]) + { + this.attribState[i] = this.tempAttribState[i]; + + if(this.tempAttribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } +}; + +/** +* Sets the current shader. +* +* @method PIXI.WebGLShaderManager#setShader +* @param shader {Any} +*/ +PIXI.WebGLShaderManager.prototype.setShader = function(shader) +{ + if(this._currentId === shader._UID)return false; + + this._currentId = shader._UID; + + this.currentShader = shader; + + this.gl.useProgram(shader.program); + this.setAttribs(shader.attributes); + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLShaderManager#destroy +*/ +PIXI.WebGLShaderManager.prototype.destroy = function() +{ + this.attribState = null; + + this.tempAttribState = null; + + this.primitiveShader.destroy(); + + this.complexPrimitiveShader.destroy(); + + this.defaultShader.destroy(); + + this.fastShader.destroy(); + + this.stripShader.destroy(); + + if (this.creatureShader) { + this.creatureShader.destroy(); + } + + this.gl = null; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** + * + * @class PIXI.WebGLSpriteBatch + * @private + * @constructor + */ +PIXI.WebGLSpriteBatch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 5; + + /** + * The number of images in the SpriteBatch before it flushes + * @property size + * @type Number + */ + this.size = 2000; //Math.pow(2, 16) / this.vertSize; + + //the total number of bytes in our batch + // Including texture index: + // position + uv + color + textureIndex + // vec2 + vec2 + (char * 4) + float + this.vertexSize = (4 * 2) + (4 * 2) + (4) + (4); + var numVerts = this.vertexSize * this.size * 4; + //this.size * 4 * 4 * this.vertSize; + //the total number of indices in our batch + var numIndices = this.size * 6; + + /** + * Holds the vertices + * + * @property vertices + * @type ArrayBuffer + */ + this.vertices = new ArrayBuffer(numVerts); + + /** + * View on the vertices as a Float32Array + * + * @property positions + * @type Float32Array + */ + this.positions = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array + * + * @property colors + * @type Uint32Array + */ + this.colors = new Uint32Array(this.vertices); + + /** + * Holds the indices + * + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * @property textures + * @type Array + */ + this.textures = []; + + /** + * @property blendModes + * @type Array + */ + this.blendModes = []; + + /** + * @property shaders + * @type Array + */ + this.shaders = []; + + /** + * @property sprites + * @type Array + */ + this.sprites = []; + + /** + * @property defaultShader + * @type Phaser.Filter + */ + this.defaultShader = null; +}; + +/** + * @method PIXI.WebGLSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLSpriteBatch.prototype.setContext = function (gl) { + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.gl = gl; + if (PIXI._enableMultiTextureToggle) { + var dynamicIfs = '\tif (vTextureIndex == 0.0) {gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + 'void main(void) {', + dynamicIfs, + '\tgl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;', + '}' + ]); + } + else + { + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]); + } + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + this.currentBlendMode = 99999; + + var shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = this.defaultShader.fragmentSrc; + shader.uniforms = {}; + shader.init(); + + this.defaultShader.shaders[gl.id] = shader; +}; + +/** + * @method PIXI.WebGLSpriteBatch#begin + * @param renderSession {Object} The RenderSession object + */ +PIXI.WebGLSpriteBatch.prototype.begin = function (renderSession) { + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.defaultShader; + + this.start(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#end + */ +PIXI.WebGLSpriteBatch.prototype.end = function () { + this.flush(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#render + * @param sprite {Sprite} the sprite to render when using this spritebatch + * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. + */ +PIXI.WebGLSpriteBatch.prototype.render = function (sprite, matrix) { + var texture = sprite.texture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + if (PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + baseTexture.textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] = baseTexture; + } + + // They provided an alternative rendering matrix, so use it + var wt = sprite.worldTransform; + + if (matrix) { + wt = matrix; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // get the uvs for the texture + var uvs = texture._uvs; + + // if the uvs have not updated then no point rendering just yet! + if (!uvs) { + return; + } + + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + + var w0, w1, h0, h1; + + if (texture.trim) { + // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords. + var trim = texture.trim; + + w1 = trim.x - aX * trim.width; + w0 = w1 + texture.crop.width; + + h1 = trim.y - aY * trim.height; + h0 = h1 + texture.crop.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 i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + var tiOffset = this.currentBatchSize * 4; + var resolution = texture.baseTexture.resolution; + var textureIndex = texture.baseTexture.textureIndex; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + + var cw = texture.crop.width; + var ch = texture.crop.height; + + if (texture.rotated) + { + var a0 = wt.a; + var b0 = wt.b; + var c0 = wt.c; + var d0 = wt.d; + var _w1 = w1; + var _w0 = w0; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + a = a0 * 6.123233995736766e-17 + -c0; + b = b0 * 6.123233995736766e-17 + -d0; + c = a0 + c0 * 6.123233995736766e-17; + d = b0 + d0 * 6.123233995736766e-17; + + // Update UV coordinates + texture._updateUvsInverted(); + + // Rotate dimensions + w0 = h0; + w1 = h1; + h0 = _w0; + h1 = _w1; + } + + var colors = this.colors; + var positions = this.positions; + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + if (this.renderSession.roundPixels) { + positions[i++] = a * w1 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w1 + ty | 0; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w0 + ty | 0; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w0 + ty | 0; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w1 + ty | 0; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } else { + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx; + positions[i++] = d * h1 + b * w0 + ty; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders a TilingSprite using the spriteBatch. + * + * @method PIXI.WebGLSpriteBatch#renderTilingSprite + * @param sprite {TilingSprite} the sprite to render + */ +PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function (sprite) { + var texture = sprite.tilingTexture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + var textureIndex = sprite.texture.baseTexture.textureIndex; + if (PIXI.WebGLRenderer.textureArray[textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[textureIndex] = baseTexture; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // set the textures uvs temporarily + if (!sprite._uvs) { + sprite._uvs = new PIXI.TextureUvs(); + } + + var uvs = sprite._uvs; + + var w = texture.baseTexture.width; + var h = texture.baseTexture.height; + + // var w = sprite._frame.sourceSizeW; + // var h = sprite._frame.sourceSizeH; + + // w = 16; + // h = 16; + + sprite.tilePosition.x %= w * sprite.tileScaleOffset.x; + sprite.tilePosition.y %= h * sprite.tileScaleOffset.y; + + var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x); + var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y); + + var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x); + var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.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; + + // Get the sprites current alpha and tint and combine them into a single color + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + var positions = this.positions; + var colors = this.colors; + + var width = sprite.width; + var height = sprite.height; + + // TODO trim?? + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + var w0 = width * (1 - aX); + var w1 = width * -aX; + + var h0 = height * (1 - aY); + var h1 = height * -aY; + + var i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + + var resolution = texture.baseTexture.resolution; + + var wt = sprite.worldTransform; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + // xy + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + // uv + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = (a * w0 + c * h1 + tx); + positions[i++] = d * h1 + b * w0 + ty; + // uv + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + // uv + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + // uv + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders the content and empties the current batch. + * + * @method PIXI.WebGLSpriteBatch#flush + */ +PIXI.WebGLSpriteBatch.prototype.flush = function () { + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize === 0) { + return; + } + + var gl = this.gl; + var shader; + + if (this.dirty) { + this.dirty = false; + + shader = this.defaultShader.shaders[gl.id]; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + // this is the same for each shader? + var stride = this.vertexSize; //this.vertSize * 4; + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 8); + + // color attributes will be interpreted as unsigned bytes and normalized + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 16); + + // Texture index + gl.vertexAttribPointer(shader.aTextureIndex, 1, gl.FLOAT, false, stride, 20); + } + + // upload the verts to the buffer + if (this.currentBatchSize > (this.size * 0.5)) { + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + } else { + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + var view = this.positions.subarray(0, this.currentBatchSize * this.vertexSize); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); + } + + var nextTexture, nextBlendMode, nextShader; + var batchSize = 0; + var start = 0; + + var currentBaseTexture = null; + var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode; + var currentShader = null; + + var blendSwap = false; + var shaderSwap = false; + var sprite; + var textureIndex = 0; + + for (var i = 0, j = this.currentBatchSize; i < j; i++) { + + sprite = this.sprites[i]; + + if (sprite.tilingTexture) { + nextTexture = sprite.tilingTexture.baseTexture; + } else { + nextTexture = sprite.texture.baseTexture; + } + + nextBlendMode = sprite.blendMode; + nextShader = sprite.shader || this.defaultShader; + + blendSwap = currentBlendMode !== nextBlendMode; + shaderSwap = currentShader !== nextShader; // should I use _UIDS??? + + var skip = nextTexture.skipRender; + + if (skip && sprite.children.length > 0) { + skip = false; + } + // + if (/*(currentBaseTexture != nextTexture && !skip) ||*/ + blendSwap || + shaderSwap) { + this.renderBatch(currentBaseTexture, batchSize, start); + + start = i; + batchSize = 0; + currentBaseTexture = nextTexture; + + if (blendSwap) { + currentBlendMode = nextBlendMode; + this.renderSession.blendModeManager.setBlendMode(currentBlendMode); + } + + if (shaderSwap) { + currentShader = nextShader; + + shader = currentShader.shaders[gl.id]; + + if (!shader) { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = currentShader.fragmentSrc; + shader.uniforms = currentShader.uniforms; + shader.init(); + + currentShader.shaders[gl.id] = shader; + } + + // set shader function??? + this.renderSession.shaderManager.setShader(shader); + + if (shader.dirty) { + shader.syncUniforms(); + } + + // both these only need to be set if they are changing.. + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(shader.projectionVector, projection.x, projection.y); + + // TODO - this is temporary! + var offsetVector = this.renderSession.offset; + gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y); + + // set the pointers + } + } + + batchSize++; + } + + this.renderBatch(currentBaseTexture, batchSize, start); + + // then reset the batch! + this.currentBatchSize = 0; +}; + +/** + * @method PIXI.WebGLSpriteBatch#renderBatch + * @param texture {Texture} + * @param size {Number} + * @param startIndex {Number} + */ +PIXI.WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { + if (size === 0) { + return; + } + + var gl = this.gl; + + // check if a texture is dirty.. + if (texture._dirty[gl.id]) { + if (!this.renderSession.renderer.updateTexture(texture)) { + // If updateTexture returns false then we cannot render it, so bail out now + return; + } + }else { + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + } + + gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2); + // increment the draw count + this.renderSession.drawCount++; +}; + +/** + * @method PIXI.WebGLSpriteBatch#stop + */ +PIXI.WebGLSpriteBatch.prototype.stop = function () { + this.flush(); + this.dirty = true; +}; + +/** + * @method PIXI.WebGLSpriteBatch#start + */ +PIXI.WebGLSpriteBatch.prototype.start = function () { + this.dirty = true; +}; + +/** + * Destroys the SpriteBatch. + * + * @method PIXI.WebGLSpriteBatch#destroy + */ +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; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** +* @class PIXI.WebGLFastSpriteBatch +* @constructor +*/ +PIXI.WebGLFastSpriteBatch = function(gl) +{ + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 11; + + /** + * @property maxSize + * @type Number + */ + this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize; + + /** + * @property size + * @type Number + */ + this.size = this.maxSize; + + //the total number of floats in our batch + var numVerts = this.size * 4 * this.vertSize; + + //the total number of indices in our batch + var numIndices = this.maxSize * 6; + + /** + * Vertex data + * @property vertices + * @type Float32Array + */ + this.vertices = new Float32Array(numVerts); + + /** + * Index data + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property vertexBuffer + * @type Object + */ + this.vertexBuffer = null; + + /** + * @property indexBuffer + * @type Object + */ + this.indexBuffer = null; + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i=0, j=0; i < numIndices; i += 6, j += 4) + { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 0; + + /** + * @property renderSession + * @type Object + */ + this.renderSession = null; + + /** + * @property shader + * @type Object + */ + this.shader = null; + + /** + * @property matrix + * @type Matrix + */ + this.matrix = null; + + this.setContext(gl); +}; + +PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLFastSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl) +{ + this.gl = gl; + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#begin + * @param spriteBatch {WebGLSpriteBatch} + * @param renderSession {Object} + */ +PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession) +{ + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.fastShader; + + this.matrix = spriteBatch.worldTransform.toArray(true); + + this.start(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#end + */ +PIXI.WebGLFastSpriteBatch.prototype.end = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#render + * @param spriteBatch {WebGLSpriteBatch} + */ +PIXI.WebGLFastSpriteBatch.prototype.render = function (spriteBatch) +{ + var children = spriteBatch.children; + var sprite = children[0]; + + // if the uvs have not updated then no point rendering just yet! + + // check texture. + if(!sprite.texture._uvs)return; + + this.currentBaseTexture = sprite.texture.baseTexture; + + // check blend mode + if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode) + { + this.flush(); + this.renderSession.blendModeManager.setBlendMode(sprite.blendMode); + } + + for(var i=0,j= children.length; i= this.size) + { + this.flush(); + } +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#flush + */ +PIXI.WebGLFastSpriteBatch.prototype.flush = function() +{ + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize===0)return; + + var gl = this.gl; + + // bind the current texture + + if(!this.currentBaseTexture._glTextures[gl.id]) { + this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl); + return; + } + + //gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); + + // upload the verts to the buffer + + if(this.currentBatchSize > ( this.size * 0.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); + } + + // now draw those suckas! + gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0); + + // then reset the batch! + this.currentBatchSize = 0; + + // increment the draw count + this.renderSession.drawCount++; + +}; + + +/** + * @method PIXI.WebGLFastSpriteBatch#stop + */ +PIXI.WebGLFastSpriteBatch.prototype.stop = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#start + */ +PIXI.WebGLFastSpriteBatch.prototype.start = function() +{ + var gl = this.gl; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(this.shader.projectionVector, projection.x, projection.y); + + // set the matrix + gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix); + + // set the pointers + 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); + gl.vertexAttribPointer(this.shader.aTextureIndex, 1, gl.FLOAT, false, stride, 10 * 4); + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLFilterManager +* @constructor +*/ +PIXI.WebGLFilterManager = function() +{ + /** + * @property filterStack + * @type Array + */ + this.filterStack = []; + + /** + * @property offsetX + * @type Number + */ + this.offsetX = 0; + + /** + * @property offsetY + * @type Number + */ + this.offsetY = 0; +}; + +PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLFilterManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLFilterManager.prototype.setContext = function(gl) +{ + this.gl = gl; + this.texturePool = []; + + this.initShaderBuffers(); +}; + +/** +* @method PIXI.WebGLFilterManager#begin +* @param renderSession {RenderSession} +* @param buffer {ArrayBuffer} +*/ +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; +}; + +/** +* Applies the filter and adds it to the current filter stack. +* +* @method PIXI.WebGLFilterManager#pushFilter +* @param filterBlock {Object} the filter that will be pushed to the current filter stack +*/ +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(); + + // >>> modify by nextht + filterBlock._previous_stencil_mgr = this.renderSession.stencilManager; + this.renderSession.stencilManager = new PIXI.WebGLStencilManager(); + this.renderSession.stencilManager.setContext(gl); + gl.disable(gl.STENCIL_TEST); + // <<< modify by nextht + + // filter program + // OPTIMISATION - the first filter is free if its a simple color change? + 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.renderSession.resolution, this.height * this.renderSession.resolution); + } + else + { + texture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + } + + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea; + + var padding = filter.padding; + filterArea.x -= padding; + filterArea.y -= padding; + filterArea.width += padding * 2; + filterArea.height += padding * 2; + + // cap filter to screen size.. + 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer); + + // set view port + gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + projection.x = filterArea.width/2; + projection.y = -filterArea.height/2; + + offset.x = -filterArea.x; + offset.y = -filterArea.y; + + // update projection + // now restore the regular shader.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + //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; + +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLFilterManager#popFilter +*/ +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 * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + 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); + // now set the uvs.. + 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.renderSession.resolution, this.height * this.renderSession.resolution); + outputTexture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + + // need to clear this FBO as it may have some left over elements from a previous filter. + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + gl.clear(gl.COLOR_BUFFER_BIT); + + gl.disable(gl.BLEND); + + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { + var filterPass = filterBlock.filterPasses[i]; + + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture); + + // draw texture.. + //filterPass.applyFilterPass(filterArea.width, filterArea.height); + this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height); + + // swap the textures.. + var temp = inputTexture; + inputTexture = outputTexture; + outputTexture = temp; + } + + gl.enable(gl.BLEND); + + texture = inputTexture; + this.texturePool.push(outputTexture); + } + + var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1]; + + this.offsetX -= filterArea.x; + this.offsetY -= filterArea.y; + + var sizeX = this.width; + var sizeY = this.height; + + var offsetX = 0; + var offsetY = 0; + + var buffer = this.buffer; + + // time to render the filters texture to the previous scene + if(this.filterStack.length === 0) + { + gl.colorMask(true, true, true, true);//this.transparent); + } + else + { + var currentFilter = this.filterStack[this.filterStack.length-1]; + filterArea = currentFilter._filterArea; + + sizeX = filterArea.width; + sizeY = filterArea.height; + + offsetX = filterArea.x; + offsetY = filterArea.y; + + buffer = currentFilter._glFilterTexture.frameBuffer; + } + + // TODO need to remove these global elements.. + projection.x = sizeX/2; + projection.y = -sizeY/2; + + offset.x = offsetX; + offset.y = offsetY; + + filterArea = filterBlock._filterArea; + + var x = filterArea.x-offsetX; + var y = filterArea.y-offsetY; + + // update the buffers.. + // make sure to flip the y! + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + + this.vertexArray[0] = x; + this.vertexArray[1] = y + filterArea.height; + + this.vertexArray[2] = x + filterArea.width; + this.vertexArray[3] = y + filterArea.height; + + this.vertexArray[4] = x; + this.vertexArray[5] = y; + + this.vertexArray[6] = x + filterArea.width; + this.vertexArray[7] = y; + + 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); + + gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution); + + // bind the buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, buffer ); + + // set the blend mode! + //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + // >>> modify by nextht + if (this.renderSession.stencilManager) { + this.renderSession.stencilManager.destroy(); + } + this.renderSession.stencilManager = filterBlock._previous_stencil_mgr; + filterBlock._previous_stencil_mgr = null; + if (this.renderSession.stencilManager.count > 0) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + // <<< modify by nextht + + // apply! + this.applyFilterPass(filter, filterArea, sizeX, sizeY); + + // now restore the regular shader.. should happen automatically now.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2); + // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY); + + // return the texture to the pool + this.texturePool.push(texture); + filterBlock._glFilterTexture = null; +}; + + +/** +* Applies the filter to the specified area. +* +* @method PIXI.WebGLFilterManager#applyFilterPass +* @param filter {Phaser.Filter} the filter that needs to be applied +* @param filterArea {Texture} TODO - might need an update +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +*/ +PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height) +{ + // use program + var gl = this.gl; + var shader = filter.shaders[gl.id]; + + if(!shader) + { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = filter.fragmentSrc; + shader.uniforms = filter.uniforms; + shader.init(true); + + filter.shaders[gl.id] = shader; + } + + // set the shader + this.renderSession.shaderManager.setShader(shader); + +// gl.useProgram(shader.program); + + gl.uniform2f(shader.projectionVector, width/2, -height/2); + gl.uniform2f(shader.offsetVector, 0,0); + + if(filter.uniforms.dimensions) + { + filter.uniforms.dimensions.value[0] = this.width;//width; + filter.uniforms.dimensions.value[1] = this.height;//height; + filter.uniforms.dimensions.value[2] = this.vertexArray[0]; + filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height; + } + + shader.syncUniforms(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // draw the filter... + gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + + this.renderSession.drawCount++; +}; + +/** +* Initialises the shader buffers. +* +* @method PIXI.WebGLFilterManager#initShaderBuffers +*/ +PIXI.WebGLFilterManager.prototype.initShaderBuffers = function() +{ + var gl = this.gl; + + // create some buffers + this.vertexBuffer = gl.createBuffer(); + this.uvBuffer = gl.createBuffer(); + this.colorBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // bind and upload the vertexs.. + // keep a reference to the vertexFloatData.. + this.vertexArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW); + + // bind and upload the uv buffer + this.uvArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW); + + this.colorArray = new Float32Array([1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW); + + // bind and upload the index + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW); + +}; + +/** +* Destroys the filter and removes it from the filter stack. +* +* @method PIXI.WebGLFilterManager#destroy +*/ +PIXI.WebGLFilterManager.prototype.destroy = function() +{ + var gl = this.gl; + + this.filterStack = null; + + this.offsetX = 0; + this.offsetY = 0; + + // destroy textures + for (var i = 0; i < this.texturePool.length; i++) { + this.texturePool[i].destroy(); + } + + this.texturePool = null; + + //destroy buffers.. + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.uvBuffer); + gl.deleteBuffer(this.colorBuffer); + gl.deleteBuffer(this.indexBuffer); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @private + */ +function _CreateEmptyTexture(gl, width, height, scaleMode) { + var texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + return texture; +} + +/** + * @private + */ +var _fbErrors = { + 36054: 'Incomplete attachment', + 36055: 'Missing attachment', + 36057: 'Incomplete dimensions', + 36061: 'Framebuffer unsupported' +}; + +/** + * @private + */ +function _CreateFramebuffer(gl, width, height, scaleMode, textureUnit) { + var framebuffer = gl.createFramebuffer(); + var depthStencilBuffer = gl.createRenderbuffer(); + var colorBuffer = null; + var fbStatus = 0; + + gl.activeTexture(gl.TEXTURE0 + textureUnit); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer); + colorBuffer = _CreateEmptyTexture(gl, width, height, scaleMode); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorBuffer, 0); + fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + if(fbStatus !== gl.FRAMEBUFFER_COMPLETE) { + console.error('Incomplete GL framebuffer. ', _fbErrors[fbStatus]); + } + framebuffer.width = width; + framebuffer.height = height; + framebuffer.targetTexture = colorBuffer; + framebuffer.renderBuffer = depthStencilBuffer; + return framebuffer; +} + +/** +* @class PIXI.FilterTexture +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +* @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values +*/ +PIXI.FilterTexture = function(gl, width, height, scaleMode, textureUnit) +{ + textureUnit = typeof textureUnit === 'number' ? textureUnit : 0; + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + // next time to create a frame buffer and texture + + /** + * @property frameBuffer + * @type Any + */ + this.frameBuffer = _CreateFramebuffer(gl, width, height, scaleMode || PIXI.scaleModes.DEFAULT, textureUnit); + /** + * @property texture + * @type Any + */ + this.texture = this.frameBuffer.targetTexture; + this.width = width; + this.height = height; + this.renderBuffer = this.frameBuffer.renderBuffer; +}; + +PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture; + +/** +* Clears the filter texture. +* +* @method PIXI.FilterTexture#clear +*/ +PIXI.FilterTexture.prototype.clear = function() +{ + var gl = this.gl; + + gl.clearColor(0,0,0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Resizes the texture to the specified width and height + * + * @method PIXI.FilterTexture#resize + * @param width {Number} the new width of the texture + * @param height {Number} the new height of the texture + */ +PIXI.FilterTexture.prototype.resize = function(width, height) +{ + if(this.width === width && this.height === height) return; + + this.width = width; + this.height = height; + + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height ); +}; + +/** +* Destroys the filter texture. +* +* @method PIXI.FilterTexture#destroy +*/ +PIXI.FilterTexture.prototype.destroy = function() +{ + var gl = this.gl; + gl.deleteFramebuffer( this.frameBuffer ); + gl.deleteTexture( this.texture ); + + this.frameBuffer = null; + this.texture = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Creates a Canvas element of the given size. + * + * @class PIXI.CanvasBuffer + * @constructor + * @param width {Number} the width for the newly created canvas + * @param height {Number} the height for the newly created canvas + */ +PIXI.CanvasBuffer = function(width, height) +{ + /** + * The width of the Canvas in pixels. + * + * @property width + * @type Number + */ + this.width = width; + + /** + * The height of the Canvas in pixels. + * + * @property height + * @type Number + */ + this.height = height; + + /** + * The Canvas object that belongs to this CanvasBuffer. + * + * @property canvas + * @type HTMLCanvasElement + */ + this.canvas = Phaser.CanvasPool.create(this, this.width, this.height); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.canvas.getContext("2d"); + + this.canvas.width = width; + this.canvas.height = height; +}; + +PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer; + +/** + * Clears the canvas that was created by the CanvasBuffer class. + * + * @method PIXI.CanvasBuffer#clear + * @private + */ +PIXI.CanvasBuffer.prototype.clear = function() +{ + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0,0, this.width, this.height); +}; + +/** + * Resizes the canvas to the specified width and height. + * + * @method PIXI.CanvasBuffer#resize + * @param width {Number} the new width of the canvas + * @param height {Number} the new height of the canvas + */ +PIXI.CanvasBuffer.prototype.resize = function(width, height) +{ + this.width = this.canvas.width = width; + this.height = this.canvas.height = height; +}; + +/** + * Frees the canvas up for use again. + * + * @method PIXI.CanvasBuffer#destroy + */ +PIXI.CanvasBuffer.prototype.destroy = function() +{ + Phaser.CanvasPool.remove(this); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used to handle masking. + * + * @class PIXI.CanvasMaskManager + * @constructor + */ +PIXI.CanvasMaskManager = function() +{ +}; + +PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; + +/** + * This method adds it to the current stack of masks. + * + * @method PIXI.CanvasMaskManager#pushMask + * @param maskData {Object} the maskData that will be pushed + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) { + + var context = renderSession.context; + + context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.worldTransform; + + var resolution = renderSession.resolution; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution); + + PIXI.CanvasGraphics.renderGraphicsMask(maskData, context); + + context.clip(); + + maskData.worldAlpha = cacheAlpha; +}; + +/** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @method PIXI.CanvasMaskManager#popMask + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.popMask = function(renderSession) +{ + renderSession.context.restore(); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class PIXI.CanvasTinter + * @static + */ +PIXI.CanvasTinter = function() {}; + +/** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @method PIXI.CanvasTinter#getTintedTexture + * @static + * @param sprite {Sprite} the sprite to tint + * @param color {Number} the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ +PIXI.CanvasTinter.getTintedTexture = function(sprite, color) +{ + var canvas = sprite.tintedTexture || Phaser.CanvasPool.create(this); + + PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas); + + return canvas; +}; + +/** + * Tint a texture using the "multiply" operation. + * + * @method PIXI.CanvasTinter#tintWithMultiply + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.clearRect(0, 0, w, h); + + context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, w, h); + + context.globalCompositeOperation = "multiply"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + context.globalCompositeOperation = "destination-atop"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + +}; + +/** + * Tint a texture pixel per pixel. + * + * @method PIXI.CanvasTinter#tintPerPixel + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.globalCompositeOperation = "copy"; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + var rgbValues = Phaser.Color.hexToRGBArray(color); + var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, w, h); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) + { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + + if (!PIXI.CanvasTinter.canHandleAlpha) + { + var alpha = pixels[i + 3]; + + pixels[i + 0] /= 255 / alpha; + pixels[i + 1] /= 255 / alpha; + pixels[i + 2] /= 255 / alpha; + } + } + + context.putImageData(pixelData, 0, 0); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class PIXI.CanvasRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.CanvasRenderer = function (game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + /** + * The renderer type. + * + * @property type + * @type Number + */ + this.type = Phaser.CANVAS; + + /** + * The resolution of the canvas. + * + * @property resolution + * @type Number + */ + this.resolution = game.resolution; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. + * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame. + * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The width of the canvas view + * + * @property width + * @type Number + * @default 800 + */ + this.width = game.width * this.resolution; + + /** + * The height of the canvas view + * + * @property height + * @type Number + * @default 600 + */ + this.height = game.height * this.resolution; + + /** + * The canvas element that everything is drawn to. + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * The canvas 2d context that everything is drawn with + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.view.getContext("2d", { alpha: this.transparent } ); + + /** + * Boolean flag controlling canvas refresh. + * + * @property refresh + * @type Boolean + */ + this.refresh = true; + + /** + * Internal var. + * + * @property count + * @type Number + */ + this.count = 0; + + /** + * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer + * @property CanvasMaskManager + * @type CanvasMaskManager + */ + this.maskManager = new PIXI.CanvasMaskManager(); + + /** + * The render session is just a bunch of parameter used for rendering + * @property renderSession + * @type Object + */ + this.renderSession = { + context: this.context, + maskManager: this.maskManager, + scaleMode: null, + smoothProperty: Phaser.Canvas.getSmoothingPrefix(this.context), + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + */ + roundPixels: config.roundPixels || false + }; + + this.mapBlendModes(); + + this.resize(this.width, this.height); + +}; + +// constructor +PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer; + +/** + * Renders the DisplayObjectContainer, usually the Phaser.Stage, to this canvas view. + * + * @method PIXI.CanvasRenderer#render + * @param root {Phaser.Stage|PIXI.DisplayObjectContainer} The root element to be rendered. + */ +PIXI.CanvasRenderer.prototype.render = function (root) { + + this.context.setTransform(1, 0, 0, 1, 0, 0); + + this.context.globalAlpha = 1; + + this.renderSession.currentBlendMode = 0; + this.renderSession.shakeX = this.game.camera._shake.x; + this.renderSession.shakeY = this.game.camera._shake.y; + + this.context.globalCompositeOperation = 'source-over'; + + if (navigator.isCocoonJS && this.view.screencanvas) + { + this.context.fillStyle = "black"; + this.context.clear(); + } + + if (this.clearBeforeRender) + { + if (this.transparent) + { + this.context.clearRect(0, 0, this.width, this.height); + } + else if (root._bgColor) + { + this.context.fillStyle = root._bgColor.rgba; + this.context.fillRect(0, 0, this.width , this.height); + } + } + + this.renderDisplayObject(root); + +}; + +PIXI.CanvasRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + // Does nothing on Canvas, but here to allow you to simply set + // `game.renderer.setTexturePriority()` without having to worry about + // running in WebGL or not. + +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @method PIXI.CanvasRenderer#destroy + * @param [removeView=true] {boolean} Removes the Canvas element from the DOM. + */ +PIXI.CanvasRenderer.prototype.destroy = function (removeView) { + + if (removeView === undefined) { removeView = true; } + + if (removeView && this.view.parent) + { + this.view.parent.removeChild(this.view); + } + + this.view = null; + this.context = null; + this.maskManager = null; + this.renderSession = null; + +}; + +/** + * Resizes the canvas view to the specified width and height + * + * @method PIXI.CanvasRenderer#resize + * @param width {Number} the new width of the canvas view + * @param height {Number} the new height of the canvas view + */ +PIXI.CanvasRenderer.prototype.resize = function (width, height) { + + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) + { + this.view.style.width = this.width / this.resolution + "px"; + this.view.style.height = this.height / this.resolution + "px"; + } + + if (this.renderSession.smoothProperty) + { + this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + +}; + +/** + * Renders a display object + * + * @method PIXI.CanvasRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The displayObject to render + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. + * @private + */ +PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) { + + this.renderSession.context = context || this.context; + this.renderSession.resolution = this.resolution; + displayObject._renderCanvas(this.renderSession, matrix); + +}; + +/** + * Maps Pixi blend modes to canvas blend modes. + * + * @method PIXI.CanvasRenderer#mapBlendModes + * @private + */ +PIXI.CanvasRenderer.prototype.mapBlendModes = function () { + + if (!PIXI.blendModesCanvas) + { + var b = []; + var modes = PIXI.blendModes; + var useNew = this.game.device.canUseMultiply; + + b[modes.NORMAL] = 'source-over'; + b[modes.ADD] = 'lighter'; + b[modes.MULTIPLY] = (useNew) ? 'multiply' : 'source-over'; + b[modes.SCREEN] = (useNew) ? 'screen' : 'source-over'; + b[modes.OVERLAY] = (useNew) ? 'overlay' : 'source-over'; + b[modes.DARKEN] = (useNew) ? 'darken' : 'source-over'; + b[modes.LIGHTEN] = (useNew) ? 'lighten' : 'source-over'; + b[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : 'source-over'; + b[modes.COLOR_BURN] = (useNew) ? 'color-burn' : 'source-over'; + b[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : 'source-over'; + b[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : 'source-over'; + b[modes.DIFFERENCE] = (useNew) ? 'difference' : 'source-over'; + b[modes.EXCLUSION] = (useNew) ? 'exclusion' : 'source-over'; + b[modes.HUE] = (useNew) ? 'hue' : 'source-over'; + b[modes.SATURATION] = (useNew) ? 'saturation' : 'source-over'; + b[modes.COLOR] = (useNew) ? 'color' : 'source-over'; + b[modes.LUMINOSITY] = (useNew) ? 'luminosity' : 'source-over'; + + PIXI.blendModesCanvas = b; + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class PIXI.BaseTexture + * @constructor + * @param source {String|Canvas} the source object (image or canvas) + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + */ +PIXI.BaseTexture = function(source, scaleMode, resolution) +{ + /** + * The Resolution of the texture. + * + * @property resolution + * @type Number + */ + this.resolution = resolution || 1; + + /** + * [read-only] The width of the base texture set when the image has loaded + * + * @property width + * @type Number + * @readOnly + */ + this.width = 100; + + /** + * [read-only] The height of the base texture set when the image has loaded + * + * @property height + * @type Number + * @readOnly + */ + this.height = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @property scaleMode + * @type {Number} + * @default PIXI.scaleModes.LINEAR + */ + this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT; + + /** + * [read-only] Set to true once the base texture has loaded + * + * @property hasLoaded + * @type Boolean + * @readOnly + */ + this.hasLoaded = false; + + /** + * The image source that is used to create the texture. + * + * @property source + * @type Image + */ + this.source = source; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * + * @property premultipliedAlpha + * @type Boolean + * @default true + */ + this.premultipliedAlpha = true; + + // used for webGL + + /** + * @property _glTextures + * @type Array + * @private + */ + this._glTextures = []; + + /** + * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @property mipmap + * @type {Boolean} + */ + this.mipmap = false; + + /** + * The multi texture batching index number. + * @property textureIndex + * @type Number + */ + this.textureIndex = 0; + + /** + * @property _dirty + * @type Array + * @private + */ + this._dirty = [true, true, true, true]; + + if (!source) + { + return; + } + + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { + this.hasLoaded = true; + this.width = this.source.naturalWidth || this.source.width; + this.height = this.source.naturalHeight || this.source.height; + this.dirty(); + } + + /** + * A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch. + * + * You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture) + * that has children that you do want to render, without causing a batch flush in the process. + * + * @property skipRender + * @type Boolean + */ + this.skipRender = false; + + /** + * @property _powerOf2 + * @type Boolean + * @private + */ + this._powerOf2 = false; + +}; + +PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture; + +/** + * Forces this BaseTexture to be set as loaded, with the given width and height. + * Then calls BaseTexture.dirty. + * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have. + * + * @method PIXI.BaseTexture#forceLoaded + * @param {number} width - The new width to force the BaseTexture to be. + * @param {number} height - The new height to force the BaseTexture to be. + */ +PIXI.BaseTexture.prototype.forceLoaded = function(width, height) +{ + this.hasLoaded = true; + this.width = width; + this.height = height; + this.dirty(); +}; + +/** + * Destroys this base texture + * + * @method PIXI.BaseTexture#destroy + */ +PIXI.BaseTexture.prototype.destroy = function() +{ + if (this.source) + { + Phaser.CanvasPool.removeByCanvas(this.source); + } + + this.source = null; + + this.unloadFromGPU(); +}; + +/** + * Sets all glTextures to be dirty. + * + * @method PIXI.BaseTexture#dirty + */ +PIXI.BaseTexture.prototype.dirty = function() +{ + for (var i = 0; i < this._glTextures.length; i++) + { + this._dirty[i] = true; + } +}; + +/** + * Removes the base texture from the GPU, useful for managing resources on the GPU. + * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it. + * + * @method PIXI.BaseTexture#unloadFromGPU + */ +PIXI.BaseTexture.prototype.unloadFromGPU = function() +{ + this.dirty(); + + // delete the webGL textures if any. + for (var i = this._glTextures.length - 1; i >= 0; i--) + { + var glTexture = this._glTextures[i]; + var gl = PIXI.glContexts[i]; + + if(gl && glTexture) + { + gl.deleteTexture(glTexture); + } + + } + + this._glTextures.length = 0; + + this.dirty(); +}; + +/** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @method PIXI.BaseTexture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + * @return {BaseTexture} + */ +PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode, resolution) +{ + if (canvas.width === 0) + { + canvas.width = 1; + } + + if (canvas.height === 0) + { + canvas.height = 1; + } + + resolution = resolution || 1; + + return new PIXI.BaseTexture(canvas, scaleMode, resolution); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * TextureSilentFail is a boolean that defaults to `false`. + * If `true` then {@link PIXI.Texture#setFrame} will no longer throw an error if the texture dimensions are incorrect. + * Instead {@link PIXI.Texture#valid} will be set to `false` (#1556) + * + * @type {boolean} + */ +PIXI.TextureSilentFail = false; + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used. + * + * @class PIXI.Texture + * @constructor + * @param baseTexture {BaseTexture} The base texture source to create the texture from + * @param frame {Rectangle} The rectangle frame of the texture to show + * @param [crop] {Rectangle} The area of original texture + * @param [trim] {Rectangle} Trimmed texture rectangle + */ +PIXI.Texture = function(baseTexture, frame, crop, trim) +{ + /** + * Does this Texture have any frame data assigned to it? + * + * @property noFrame + * @type Boolean + */ + this.noFrame = false; + + if (!frame) + { + this.noFrame = true; + frame = new PIXI.Rectangle(0,0,1,1); + } + + if (baseTexture instanceof PIXI.Texture) + { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = baseTexture; + + /** + * The frame specifies the region of the base texture that this texture uses + * + * @property frame + * @type Rectangle + */ + this.frame = frame; + + /** + * The texture trim data. + * + * @property trim + * @type Rectangle + */ + this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @property valid + * @type Boolean + */ + this.valid = false; + + /** + * Is this a tiling texture? As used by the likes of a TilingSprite. + * + * @property isTiling + * @type Boolean + */ + this.isTiling = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @property requiresUpdate + * @type Boolean + */ + this.requiresUpdate = false; + + /** + * This will let a renderer know that a tinted parent has updated its texture. + * + * @property requiresReTint + * @type Boolean + */ + this.requiresReTint = false; + + /** + * The WebGL UV data cache. + * + * @property _uvs + * @type Object + * @private + */ + this._uvs = null; + + /** + * The width of the Texture in pixels. + * + * @property width + * @type Number + */ + this.width = 0; + + /** + * The height of the Texture in pixels. + * + * @property height + * @type Number + */ + this.height = 0; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @property crop + * @type Rectangle + */ + this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1); + + /** + * A flag that controls if this frame is rotated or not. + * Rotation allows you to use rotated frames in texture atlas packing, it has nothing to do with + * Sprite rotation. + * + * @property rotated + * @type Boolean + */ + this.rotated = false; + + if (baseTexture.hasLoaded) + { + if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + this.setFrame(frame); + } + +}; + +PIXI.Texture.prototype.constructor = PIXI.Texture; + +/** + * Called when the base texture is loaded + * + * @method PIXI.Texture#onBaseTextureLoaded + * @private + */ +PIXI.Texture.prototype.onBaseTextureLoaded = function() +{ + var baseTexture = this.baseTexture; + + if (this.noFrame) + { + this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } + + this.setFrame(this.frame); +}; + +/** + * Destroys this texture + * + * @method PIXI.Texture#destroy + * @param destroyBase {Boolean} Whether to destroy the base texture as well + */ +PIXI.Texture.prototype.destroy = function(destroyBase) +{ + if (destroyBase) this.baseTexture.destroy(); + + this.valid = false; +}; + +/** + * Specifies the region of the baseTexture that this texture will use. + * + * @method PIXI.Texture#setFrame + * @param frame {Rectangle} The frame of the texture to set it to + */ +PIXI.Texture.prototype.setFrame = function(frame) +{ + this.noFrame = false; + + this.frame = frame; + this.width = frame.width; + this.height = frame.height; + + this.crop.x = frame.x; + this.crop.y = frame.y; + this.crop.width = frame.width; + this.crop.height = frame.height; + + if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { + if (!PIXI.TextureSilentFail) + { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + this.valid = false; + return; + } + + this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + + if (this.trim) + { + this.width = this.trim.width; + this.height = this.trim.height; + this.frame.width = this.trim.width; + this.frame.height = this.trim.height; + } + + if (this.valid) this._updateUvs(); + +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvs + * @private + */ +PIXI.Texture.prototype._updateUvs = function() +{ + if(!this._uvs)this._uvs = new PIXI.TextureUvs(); + + var frame = this.crop; + 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; +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvsInverted + * @private + */ +PIXI.Texture.prototype._updateUvsInverted = function () { + + if (!this._uvs) { this._uvs = new PIXI.TextureUvs(); } + + var frame = this.crop; + 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.height) / tw; + this._uvs.y1 = frame.y / th; + + this._uvs.x2 = (frame.x + frame.height) / tw; + this._uvs.y2 = (frame.y + frame.width) / th; + + this._uvs.x3 = frame.x / tw; + this._uvs.y3 = (frame.y + frame.width) / th; + +}; + +/** + * Helper function that creates a new a Texture based on the given canvas element. + * + * @static + * @method PIXI.Texture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @return {Texture} + */ +PIXI.Texture.fromCanvas = function(canvas, scaleMode) +{ + var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode); + + return new PIXI.Texture(baseTexture); +}; + +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.y3 = 0; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = PIXI; + } + exports.PIXI = PIXI; + } else if (typeof define !== 'undefined' && define.amd) { + define('PIXI', (function() { return root.PIXI = PIXI; })() ); + } else { + root.PIXI = PIXI; + } + + return PIXI; +}).call(this); +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +(function(){ + + var root = this; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @namespace Phaser +*/ +var Phaser = Phaser || { // jshint ignore:line + + /** + * The Phaser version number. + * @constant Phaser.VERSION + * @type {string} + */ + VERSION: '2.10.0', + + /** + * An array of Phaser game instances. + * @constant Phaser.GAMES + * @type {array} + */ + GAMES: [], + + /** + * AUTO renderer - picks between WebGL or Canvas based on device. + * @constant Phaser.AUTO + * @type {integer} + */ + AUTO: 0, + + /** + * Canvas Renderer. + * @constant Phaser.CANVAS + * @type {integer} + */ + CANVAS: 1, + + /** + * WebGL Renderer. + * @constant Phaser.WEBGL + * @type {integer} + */ + WEBGL: 2, + + /** + * Headless renderer (not visual output) + * @constant Phaser.HEADLESS + * @type {integer} + */ + HEADLESS: 3, + + /** + * WebGL Renderer with MultiTexture support enabled. + * @constant Phaser.WEBGL_MULTI + * @type {integer} + */ + WEBGL_MULTI: 4, + + /** + * Direction constant. + * @constant Phaser.NONE + * @type {integer} + */ + NONE: 0, + + /** + * Direction constant. + * @constant Phaser.LEFT + * @type {integer} + */ + LEFT: 1, + + /** + * Direction constant. + * @constant Phaser.RIGHT + * @type {integer} + */ + RIGHT: 2, + + /** + * Direction constant. + * @constant Phaser.UP + * @type {integer} + */ + UP: 3, + + /** + * Direction constant. + * @constant Phaser.DOWN + * @type {integer} + */ + DOWN: 4, + + /** + * Game Object type. + * @constant Phaser.SPRITE + * @type {integer} + */ + SPRITE: 0, + + /** + * Game Object type. + * @constant Phaser.BUTTON + * @type {integer} + */ + BUTTON: 1, + + /** + * Game Object type. + * @constant Phaser.IMAGE + * @type {integer} + */ + IMAGE: 2, + + /** + * Game Object type. + * @constant Phaser.GRAPHICS + * @type {integer} + */ + GRAPHICS: 3, + + /** + * Game Object type. + * @constant Phaser.TEXT + * @type {integer} + */ + TEXT: 4, + + /** + * Game Object type. + * @constant Phaser.TILESPRITE + * @type {integer} + */ + TILESPRITE: 5, + + /** + * Game Object type. + * @constant Phaser.BITMAPTEXT + * @type {integer} + */ + BITMAPTEXT: 6, + + /** + * Game Object type. + * @constant Phaser.GROUP + * @type {integer} + */ + GROUP: 7, + + /** + * Game Object type. + * @constant Phaser.RENDERTEXTURE + * @type {integer} + */ + RENDERTEXTURE: 8, + + /** + * Game Object type. + * @constant Phaser.TILEMAP + * @type {integer} + */ + TILEMAP: 9, + + /** + * Game Object type. + * @constant Phaser.TILEMAPLAYER + * @type {integer} + */ + TILEMAPLAYER: 10, + + /** + * Game Object type. + * @constant Phaser.EMITTER + * @type {integer} + */ + EMITTER: 11, + + /** + * Game Object type. + * @constant Phaser.POLYGON + * @type {integer} + */ + POLYGON: 12, + + /** + * Game Object type. + * @constant Phaser.BITMAPDATA + * @type {integer} + */ + BITMAPDATA: 13, + + /** + * Game Object type. + * @constant Phaser.CANVAS_FILTER + * @type {integer} + */ + CANVAS_FILTER: 14, + + /** + * Game Object type. + * @constant Phaser.WEBGL_FILTER + * @type {integer} + */ + WEBGL_FILTER: 15, + + /** + * Game Object type. + * @constant Phaser.ELLIPSE + * @type {integer} + */ + ELLIPSE: 16, + + /** + * Game Object type. + * @constant Phaser.SPRITEBATCH + * @type {integer} + */ + SPRITEBATCH: 17, + + /** + * Game Object type. + * @constant Phaser.RETROFONT + * @type {integer} + */ + RETROFONT: 18, + + /** + * Game Object type. + * @constant Phaser.POINTER + * @type {integer} + */ + POINTER: 19, + + /** + * Game Object type. + * @constant Phaser.ROPE + * @type {integer} + */ + ROPE: 20, + + /** + * Game Object type. + * @constant Phaser.CIRCLE + * @type {integer} + */ + CIRCLE: 21, + + /** + * Game Object type. + * @constant Phaser.RECTANGLE + * @type {integer} + */ + RECTANGLE: 22, + + /** + * Game Object type. + * @constant Phaser.LINE + * @type {integer} + */ + LINE: 23, + + /** + * Game Object type. + * @constant Phaser.MATRIX + * @type {integer} + */ + MATRIX: 24, + + /** + * Game Object type. + * @constant Phaser.POINT + * @type {integer} + */ + POINT: 25, + + /** + * Game Object type. + * @constant Phaser.ROUNDEDRECTANGLE + * @type {integer} + */ + ROUNDEDRECTANGLE: 26, + + /** + * Game Object type. + * @constant Phaser.CREATURE + * @type {integer} + */ + CREATURE: 27, + + /** + * Game Object type. + * @constant Phaser.VIDEO + * @type {integer} + */ + VIDEO: 28, + + /** + * Game Object type. + * @constant Phaser.PENDING_ATLAS + * @type {integer} + */ + PENDING_ATLAS: -1, + + /** + * A horizontal orientation + * @constant Phaser.HORIZONTAL + * @type {integer} + */ + HORIZONTAL: 0, + + /** + * A vertical orientation + * @constant Phaser.VERTICAL + * @type {integer} + */ + VERTICAL: 1, + + /** + * A landscape orientation + * @constant Phaser.LANDSCAPE + * @type {integer} + */ + LANDSCAPE: 0, + + /** + * A portrait orientation + * @constant Phaser.PORTRAIT + * @type {integer} + */ + PORTRAIT: 1, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face up. + * @constant Phaser.ANGLE_UP + * @type {integer} + */ + ANGLE_UP: 270, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face down. + * @constant Phaser.ANGLE_DOWN + * @type {integer} + */ + ANGLE_DOWN: 90, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face left. + * @constant Phaser.ANGLE_LEFT + * @type {integer} + */ + ANGLE_LEFT: 180, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face right. + * @constant Phaser.ANGLE_RIGHT + * @type {integer} + */ + ANGLE_RIGHT: 0, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north east. + * @constant Phaser.ANGLE_NORTH_EAST + * @type {integer} + */ + ANGLE_NORTH_EAST: 315, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north west. + * @constant Phaser.ANGLE_NORTH_WEST + * @type {integer} + */ + ANGLE_NORTH_WEST: 225, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south east. + * @constant Phaser.ANGLE_SOUTH_EAST + * @type {integer} + */ + ANGLE_SOUTH_EAST: 45, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south west. + * @constant Phaser.ANGLE_SOUTH_WEST + * @type {integer} + */ + ANGLE_SOUTH_WEST: 135, + + /** + * A constant representing a top-left alignment or position. + * @constant Phaser.TOP_LEFT + * @type {integer} + */ + TOP_LEFT: 0, + + /** + * A constant representing a top-center alignment or position. + * @constant Phaser.TOP_CENTER + * @type {integer} + */ + TOP_CENTER: 1, + + /** + * A constant representing a top-right alignment or position. + * @constant Phaser.TOP_RIGHT + * @type {integer} + */ + TOP_RIGHT: 2, + + /** + * A constant representing a left-top alignment or position. + * @constant Phaser.Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_TOP: 3, + + /** + * A constant representing a left-center alignment or position. + * @constant Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_CENTER: 4, + + /** + * A constant representing a left-bottom alignment or position. + * @constant Phaser.LEFT_BOTTOM + * @type {integer} + */ + LEFT_BOTTOM: 5, + + /** + * A constant representing a center alignment or position. + * @constant Phaser.CENTER + * @type {integer} + */ + CENTER: 6, + + /** + * A constant representing a right-top alignment or position. + * @constant Phaser.RIGHT_TOP + * @type {integer} + */ + RIGHT_TOP: 7, + + /** + * A constant representing a right-center alignment or position. + * @constant Phaser.RIGHT_CENTER + * @type {integer} + */ + RIGHT_CENTER: 8, + + /** + * A constant representing a right-bottom alignment or position. + * @constant Phaser.RIGHT_BOTTOM + * @type {integer} + */ + RIGHT_BOTTOM: 9, + + /** + * A constant representing a bottom-left alignment or position. + * @constant Phaser.BOTTOM_LEFT + * @type {integer} + */ + BOTTOM_LEFT: 10, + + /** + * A constant representing a bottom-center alignment or position. + * @constant Phaser.BOTTOM_CENTER + * @type {integer} + */ + BOTTOM_CENTER: 11, + + /** + * A constant representing a bottom-right alignment or position. + * @constant Phaser.BOTTOM_RIGHT + * @type {integer} + */ + BOTTOM_RIGHT: 12, + + /** + * Various blend modes supported by Pixi. See the samples in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing Canvas Tutorial: Compositing}. + * + * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * + * @constant {Object} Phaser.blendModes + * @property {Number} blendModes.NORMAL - Draws new shapes on top of the existing content. This is the default setting. + * @property {Number} blendModes.ADD - Where both shapes overlap the color is determined by adding color values. + * @property {Number} blendModes.MULTIPLY - The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer, making a darker picture. + * @property {Number} blendModes.SCREEN - The pixels are inverted, multiplied, and inverted again, making a lighter picture. + * @property {Number} blendModes.OVERLAY + * @property {Number} blendModes.DARKEN + * @property {Number} blendModes.LIGHTEN + * @property {Number} blendModes.COLOR_DODGE + * @property {Number} blendModes.COLOR_BURN + * @property {Number} blendModes.HARD_LIGHT + * @property {Number} blendModes.SOFT_LIGHT + * @property {Number} blendModes.DIFFERENCE + * @property {Number} blendModes.EXCLUSION + * @property {Number} blendModes.HUE + * @property {Number} blendModes.SATURATION + * @property {Number} blendModes.COLOR + * @property {Number} blendModes.LUMINOSITY + * @static + */ + 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 + }, + + /** + * The scale modes that are supported by Pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @constant {Object} Phaser.scaleModes + * @property {Number} Phaser.scaleModes.DEFAULT=LINEAR + * @property {Number} Phaser.scaleModes.LINEAR Smooth scaling + * @property {Number} Phaser.scaleModes.NEAREST Pixelating scaling + * @static + */ + scaleModes: { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 + }, + + PIXI: PIXI || {}, + + // Used to create IDs for various Pixi objects. + _UID: 0 + +}; + +/** +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc +if (!Math.trunc) { + Math.trunc = function trunc(x) { + return x < 0 ? Math.ceil(x) : Math.floor(x); + }; +} + +/** +* A polyfill for Function.prototype.bind +*/ +if (!Function.prototype.bind) { + + /* jshint freeze: false */ + 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)) + { + /* jshint supernew: true */ + return new F; + } + })(target.prototype); + + return bound; + }; + })(); +} + +/** +* A polyfill for Array.isArray +*/ +if (!Array.isArray) +{ + Array.isArray = function (arg) + { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + +/** +* A polyfill for Array.forEach +* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach +*/ +if (!Array.prototype.forEach) +{ + Array.prototype.forEach = function(fun /*, thisArg */) + { + "use strict"; + + if (this === void 0 || this === null) + { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + if (typeof fun !== "function") + { + throw new TypeError(); + } + + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + + for (var i = 0; i < len; i++) + { + if (i in t) + { + fun.call(thisArg, t[i], i, t); + } + } + }; +} + +/** +* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 +* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ +* Cameron Foale (http://www.kibibu.com) +*/ +if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object") +{ + var CheapArray = function(type) + { + var proto = new Array(); // jshint ignore:line + + window[type] = function(arg) { + + if (typeof(arg) === "number") + { + Array.call(this, arg); + this.length = arg; + + for (var i = 0; i < this.length; i++) + { + this[i] = 0; + } + } + else + { + Array.call(this, arg.length); + + this.length = arg.length; + + for (var i = 0; i < this.length; i++) + { + this[i] = arg[i]; + } + } + }; + + window[type].prototype = proto; + window[type].constructor = window[type]; + }; + + CheapArray('Float32Array'); // jshint ignore:line + CheapArray('Uint32Array'); // jshint ignore:line + CheapArray('Uint16Array'); // jshint ignore:line + CheapArray('Int16Array'); // jshint ignore:line + CheapArray('ArrayBuffer'); // jshint ignore:line +} + +/** + * Also fix for the absent console in IE9 + */ +if (!window.console) +{ + window.console = {}; + window.console.log = window.console.assert = function(){}; + window.console.warn = window.console.assert = function(){}; +} + +/** + * Fix for Object.assign not existing on older devices + */ + +if (!Object.assign) { + /* jshint -W098 */ + // We include `varArgs` (unused) to ensure Object.assign.length === 2 + Object.assign = function(target, varArgs) { + /* jshint +W098 */ + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + var hasOwn = Object.prototype.hasOwnProperty; + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (hasOwn.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @class Phaser.Utils +* @static +*/ +Phaser.Utils = { + + /** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @method Phaser.Utils.reverseString + * @param {string} string - The string to be reversed. + * @return {string} The reversed string. + */ + reverseString: function (string) { + + return string.split('').reverse().join(''); + + }, + + /** + * Gets an object's property by string. + * + * @method Phaser.Utils.getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + getProperty: function(obj, name) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + return obj[name]; + case 2: + return obj[parts[0]][parts[1]]; + case 3: + return obj[parts[0]][parts[1]][parts[2]]; + case 4: + return obj[parts[0]][parts[1]][parts[2]][parts[3]]; + default: + return this._getProperty(obj, name); + } + + }, + + /** + * Sets an object's properties from a map of property names and values. + * + * ```javascript + * Phaser.Utils.setProperties(sprite, { + * 'animations.paused': true, + * 'body.enable': false, + * 'input.draggable': true, + * }); + * ``` + * + * @method Phaser.Utils.setProperties + * @param {object} obj - The object to modify. + * @param {object} props - The property names and values to set on the object (see {@link #setProperty}). + * @return {object} The modified object. + */ + setProperties: function(obj, props) { + + for (var name in props) + { + this.setProperty(obj, name, props[name]); + } + + return obj; + + }, + + /** + * Sets an object's property by name and value. + * + * ```javascript + * Phaser.Utils.setProperty(sprite, 'body.velocity.x', 60); + * ``` + * + * @method Phaser.Utils.setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + + setProperty: function(obj, name, value) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + obj[name] = value; + break; + case 2: + obj[parts[0]][parts[1]] = value; + break; + case 3: + obj[parts[0]][parts[1]][parts[2]] = value; + break; + case 4: + obj[parts[0]][parts[1]][parts[2]][parts[3]] = value; + break; + default: + this._setProperty(obj, name, value); + } + }, + + /** + * Gets an object's property by string. + * + * @private + * @method Phaser.Utils._getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property whose value will be returned. + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + _getProperty: function(obj, name) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + val = obj; + + while (i < len) + { + var key = parts[i]; + + if (val != null) + { + val = val[key]; + i++; + } + else + { + return undefined; + } + } + + return val; + + }, + + /** + * Sets an object's property by name and value. + * + * @private + * @method Phaser.Utils._setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + _setProperty: function(obj, name, value) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + currentObj = obj, + key = parts[0]; + + if (len === 1) + { + obj[name] = value; + } + else + { + while (i < (len - 1)) + { + currentObj = currentObj[key]; + i++; + key = parts[i]; + } + + currentObj[key] = value; + } + + return obj; + + }, + + /** + * Generate a random bool result based on the chance value. + * + * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance + * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. + * + * @method Phaser.Utils#chanceRoll + * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). + * @return {boolean} True if the roll passed, or false otherwise. + */ + chanceRoll: function (chance) { + if (chance === undefined) { chance = 50; } + return chance > 0 && (Math.random() * 100 <= chance); + }, + + /** + * Choose between one of two values randomly. + * + * @method Phaser.Utils#randomChoice + * @param {any} choice1 + * @param {any} choice2 + * @return {any} The randomly selected choice + */ + randomChoice: function (choice1, choice2) { + return (Math.random() < 0.5) ? choice1 : choice2; + }, + + /** + * Get a unit dimension from a string. + * + * @method Phaser.Utils.parseDimension + * @param {string|number} size - The size to parse. + * @param {number} dimension - The window dimension to check. + * @return {number} The parsed dimension. + */ + parseDimension: function (size, dimension) { + + var f = 0; + var px = 0; + + if (typeof size === 'string') + { + // %? + if (size.substr(-1) === '%') + { + f = parseInt(size, 10) / 100; + + if (dimension === 0) + { + px = window.innerWidth * f; + } + else + { + px = window.innerHeight * f; + } + } + else + { + px = parseInt(size, 10); + } + } + else + { + px = size; + } + + return px; + + }, + + /** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @method Phaser.Utils.pad + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * @return {string} The padded string. + */ + pad: function (str, len, pad, dir) { + + if (len === undefined) { var len = 0; } + if (pad === undefined) { var pad = ' '; } + if (dir === undefined) { var dir = 3; } + + str = str.toString(); + + 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; + + }, + + /** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * @method Phaser.Utils.isPlainObject + * @param {object} obj - The object to inspect. + * @return {boolean} - true if the object is plain, otherwise false. + */ + isPlainObject: function (obj) { + + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) + { + return false; + } + + // Support: Firefox <20 + // The try/catch suppresses exceptions thrown when attempting to access + // the "constructor" property of certain host objects, ie. |window.location| + // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + try { + if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) + { + return false; + } + } catch (e) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + /** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @method Phaser.Utils.extend + * @param {boolean} deep - Perform a deep copy? + * @param {object} target - The target object to copy to. + * @return {object} The extended object. + */ + extend: function () { + + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if (typeof target === "boolean") + { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } + + for (; i < length; i++) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) + { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = Phaser.Utils.extend(deep, clone, copy); + + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; + + }, + + /** + * Mixes in an existing mixin object with the target. + * + * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` + * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and + * the result is assigned directly. + * + * @method Phaser.Utils.mixinPrototype + * @param {object} target - The target object to receive the new functions. + * @param {object} mixin - The object to copy the functions from. + * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not? + */ + mixinPrototype: function (target, mixin, replace) { + + if (replace === undefined) { replace = false; } + + var mixinKeys = Object.keys(mixin); + + for (var i = 0; i < mixinKeys.length; i++) + { + var key = mixinKeys[i]; + var value = mixin[key]; + + if (!replace && (key in target)) + { + // Not overwriting existing property + continue; + } + else + { + if (value && + (typeof value.get === 'function' || typeof value.set === 'function')) + { + // Special case for classes like Phaser.Point which has a 'set' function! + if (typeof value.clone === 'function') + { + target[key] = value.clone(); + } + else + { + Object.defineProperty(target, key, value); + } + } + else + { + target[key] = value; + } + } + } + + }, + + /** + * Mixes the source object into the destination object, returning the newly modified destination object. + * Based on original code by @mudcube + * + * @method Phaser.Utils.mixin + * @param {object} from - The object to copy (the source object). + * @param {object} to - The object to copy to (the destination object). + * @return {object} The modified destination object. + */ + mixin: function (from, to) { + + if (!from || typeof (from) !== "object") + { + return to; + } + + for (var key in from) + { + var o = from[key]; + + if (o.childNodes || o.cloneNode) + { + continue; + } + + var type = typeof (from[key]); + + if (!from[key] || type !== "object") + { + to[key] = from[key]; + } + else + { + // Clone sub-object + if (typeof (to[key]) === type) + { + to[key] = Phaser.Utils.mixin(from[key], to[key]); + } + else + { + to[key] = Phaser.Utils.mixin(from[key], new o.constructor()); + } + } + } + + return to; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. +* If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. +* +* @class Phaser.Circle +* @constructor +* @param {number} [x=0] - The x coordinate of the center of the circle. +* @param {number} [y=0] - The y coordinate of the center of the circle. +* @param {number} [diameter=0] - The diameter of the circle. +*/ +Phaser.Circle = function (x, y, diameter) { + + x = x || 0; + y = y || 0; + diameter = diameter || 0; + + /** + * @property {number} x - The x coordinate of the center of the circle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the center of the circle. + */ + this.y = y; + + /** + * @property {number} _diameter - The diameter of the circle. + * @private + */ + this._diameter = diameter; + + /** + * @property {number} _radius - The radius of the circle. + * @private + */ + this._radius = 0; + + if (diameter > 0) + { + this._radius = diameter * 0.5; + } + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.CIRCLE; + +}; + +Phaser.Circle.prototype = { + + /** + * The circumference of the circle. + * + * @method Phaser.Circle#circumference + * @return {number} The circumference of the circle. + */ + circumference: function () { + + return 2 * (Math.PI * this._radius); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Circle. + * + * @method Phaser.Circle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = 2 * Math.PI * Math.random(); + var u = Math.random() + Math.random(); + var r = (u > 1) ? 2 - u : u; + var x = r * Math.cos(t); + var y = r * Math.sin(t); + + out.x = this.x + (x * this.radius); + out.y = this.y + (y * this.radius); + + return out; + + }, + + /** + * Returns the framing rectangle of the circle as a Phaser.Rectangle object. + * + * @method Phaser.Circle#getBounds + * @return {Phaser.Rectangle} The bounds of the Circle. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter); + + }, + + /** + * Sets the members of Circle to the specified values. + * @method Phaser.Circle#setTo + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} diameter - The diameter of the circle. + * @return {Circle} This circle object. + */ + setTo: function (x, y, diameter) { + + this.x = x; + this.y = y; + this._diameter = diameter; + this._radius = diameter * 0.5; + + return this; + + }, + + /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method Phaser.Circle#copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.diameter); + + }, + + /** + * Copies the x, y and diameter properties from this Circle to any given object. + * @method Phaser.Circle#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.diameter = this._diameter; + + return dest; + + }, + + /** + * Returns the distance from the center of the Circle object to the given object + * (can be Circle, Point or anything with x/y properties) + * @method Phaser.Circle#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round=false] - Round the distance to the nearest integer. + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y); + return round ? Math.round(distance) : distance; + + }, + + /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. + * @method Phaser.Circle#clone + * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} The cloned Circle object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Circle(this.x, this.y, this.diameter); + } + else + { + output.setTo(this.x, this.y, this.diameter); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Circle object. + * @method Phaser.Circle#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this circle, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Circle.contains(this, x, y); + + }, + + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method Phaser.Circle#circumferencePoint + * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ + circumferencePoint: function (angle, asDegrees, out) { + + return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out); + + }, + + + /** + * Creates or positions points on the circle. + * + * The points are equally distributed in the half-closed interval [startAngle, endAngle). The default arc is the entire circle. + * + * If the `out` argument is omitted, this method creates and returns an array of {@link Phaser.Point points}. If an array is passed as `out`, its items are treated as points and placed in the same way. + * + * @param {type} [steps=60] - The number of points to place. + * @param {type} [startAngle=0] - The starting angle in radians (unless asDegrees is true). + * @param {type} [endAngle=Phaser.Math.PI2] - The end angle in radians (unless asDegrees is true). + * @param {type} [asDegrees=false] - Are the given angles in radians (false) or degrees (true)? + * @param {any[]} [out] - An array of points or point-like objects (e.g., sprites). It should start at index 0 and its length should be equal to or greater than `steps`. + * @return {any[]} - The modified `out` argument or a new array of points. + */ + sample: function (steps, startAngle, endAngle, asDegrees, out) { + + if (!steps) { steps = 60; } + if (startAngle == null) { startAngle = 0; } + if (endAngle == null) { endAngle = Phaser.Math.PI2; } + if (!out) { out = []; } + + var i = 0; + + while (i < steps) + { + this.circumferencePoint( + Phaser.Math.linear(startAngle, endAngle, i / steps), + asDegrees, + out[i] || (out[i] = new Phaser.Point()) + ); + + i += 1; + } + + return out; + + }, + + /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method Phaser.Circle#offset + * @param {number} dx - Moves the x value of the Circle object by this amount. + * @param {number} dy - Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Circle#offsetPoint + * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). + * @return {Circle} This Circle object. + */ + offsetPoint: function (point) { + return this.offset(point.x, point.y); + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Circle#toString + * @return {string} a string representation of the instance. + */ + toString: function () { + return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; + } + +}; + +Phaser.Circle.prototype.constructor = Phaser.Circle; + +/** +* The largest distance between any two points on the circle. The same as the radius * 2. +* +* @name Phaser.Circle#diameter +* @property {number} diameter - Gets or sets the diameter of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "diameter", { + + get: function () { + return this._diameter; + }, + + set: function (value) { + + if (value > 0) + { + this._diameter = value; + this._radius = value * 0.5; + } + } + +}); + +/** +* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. +* @name Phaser.Circle#radius +* @property {number} radius - Gets or sets the radius of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "radius", { + + get: function () { + return this._radius; + }, + + set: function (value) { + + if (value > 0) + { + this._radius = value; + this._diameter = value * 2; + } + + } + +}); + +/** +* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#left +* @propety {number} left - Gets or sets the value of the leftmost point of the circle. +*/ +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; + } + + } + +}); + +/** +* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#right +* @property {number} right - Gets or sets the value of the rightmost point of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "right", { + + get: function () { + return this.x + this._radius; + }, + + set: function (value) { + + if (value < this.x) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.x; + } + + } + +}); + +/** +* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#top +* @property {number} top - Gets or sets the top of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "top", { + + get: function () { + return this.y - this._radius; + }, + + set: function (value) { + + if (value > this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = this.y - value; + } + + } + +}); + +/** +* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#bottom +* @property {number} bottom - Gets or sets the bottom of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "bottom", { + + get: function () { + return this.y + this._radius; + }, + + set: function (value) { + + if (value < this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.y; + } + + } + +}); + +/** +* The area of this Circle. +* @name Phaser.Circle#area +* @property {number} area - The area of this circle. +* @readonly +*/ +Object.defineProperty(Phaser.Circle.prototype, "area", { + + get: function () { + + if (this._radius > 0) + { + return Math.PI * this._radius * this._radius; + } + else + { + return 0; + } + + } + +}); + +/** +* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. +* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. +* @name Phaser.Circle#empty +* @property {boolean} empty - Gets or sets the empty state of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "empty", { + + get: function () { + return (this._diameter === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Circle object. +* @method Phaser.Circle.contains +* @param {Phaser.Circle} a - The Circle to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this circle, otherwise false. +*/ +Phaser.Circle.contains = function (a, x, y) { + + // Check if x/y are within the bounds first + 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; + } + +}; + +/** +* Determines whether the two Circle objects match. This method compares the x, y and diameter properties. +* @method Phaser.Circle.equals +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. +*/ +Phaser.Circle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.diameter === b.diameter); + +}; + +/** +* Determines whether the two Circle objects intersect. +* This method checks the radius distances between the two Circle objects to see if they intersect. +* @method Phaser.Circle.intersects +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. +*/ +Phaser.Circle.intersects = function (a, b) { + + return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius)); + +}; + +/** +* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. +* @method Phaser.Circle.circumferencePoint +* @param {Phaser.Circle} a - The first Circle object. +* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. +* @return {Phaser.Point} The Point object holding the result. +*/ +Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) { + + if (asDegrees === undefined) { asDegrees = false; } + if (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; + +}; + +/** +* Checks if the given Circle and Rectangle objects intersect. +* @method Phaser.Circle.intersectsRectangle +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Rectangle} r - The Rectangle object to test. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +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; + +}; + +/** +* Checks if the given Circle and Line objects intersect. +* @method Phaser.Circle.intersectsLine +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnpoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Circle.intersectsLine = function (c, l, returnPoints) { + var h = c.x; + var k = c.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = c.radius; + var b = c.radius; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Circle = Phaser.Circle; + +/** +* @author Richard Davey +* @author Chad Engler +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a Ellipse object. A curve on a plane surrounding two focal points. +* +* @class Phaser.Ellipse +* @constructor +* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [width=0] - The overall width of this ellipse. +* @param {number} [height=0] - The overall height of this ellipse. +*/ +Phaser.Ellipse = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.x = x; + + /** + * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.y = y; + + /** + * @property {number} width - The overall width of this ellipse. + */ + this.width = width; + + /** + * @property {number} height - The overall height of this ellipse. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ELLIPSE; + +}; + +Phaser.Ellipse.prototype = { + + /** + * Sets the members of the Ellipse to the specified values. + * @method Phaser.Ellipse#setTo + * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} width - The overall width of this ellipse. + * @param {number} height - The overall height of this ellipse. + * @return {Phaser.Ellipse} This Ellipse object. + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. + * + * @method Phaser.Ellipse#getBounds + * @return {Phaser.Rectangle} The bounds of the Ellipse. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Ellipse. + * + * @method Phaser.Ellipse#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Ellipse} This Ellipse object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Ellipse to any given object. + * @method Phaser.Ellipse#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function(dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. + * @method Phaser.Ellipse#clone + * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. + * @return {Phaser.Ellipse} The cloned Ellipse object. + */ + clone: function(output) { + + if (output === undefined || output === null) + { + output = new Phaser.Ellipse(this.x, this.y, this.width, this.height); + } + else + { + output.setTo(this.x, this.y, this.width, this.height); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Ellipse object. + * + * @method Phaser.Ellipse#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this ellipse, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Ellipse.contains(this, x, y); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Ellipse. + * + * @method Phaser.Ellipse#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var p = Math.random() * Math.PI * 2; + var r = Math.random(); + + out.x = Math.sqrt(r) * Math.cos(p); + out.y = Math.sqrt(r) * Math.sin(p); + + out.x = this.x + (out.x * this.width / 2.0); + out.y = this.y + (out.y * this.height / 2.0); + + return out; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Ellipse#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]"; + } + +}; + +Phaser.Ellipse.prototype.constructor = Phaser.Ellipse; + +/** +* The left coordinate of the Ellipse. The same as the X coordinate. +* @name Phaser.Ellipse#left +* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + + this.x = value; + + } + +}); + +/** +* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. +* @name Phaser.Ellipse#right +* @property {number} right - Gets or sets the value of the rightmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "right", { + + get: function () { + return this.x + this.width; + }, + + set: function (value) { + + if (value < this.x) + { + this.width = 0; + } + else + { + this.width = value - this.x; + } + } + +}); + +/** +* The top of the Ellipse. The same as its y property. +* @name Phaser.Ellipse#top +* @property {number} top - Gets or sets the top of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "top", { + + get: function () { + return this.y; + }, + + set: function (value) { + this.y = value; + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. +* @name Phaser.Ellipse#bottom +* @property {number} bottom - Gets or sets the bottom of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value < this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + } + +}); + +/** +* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. +* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. +* @name Phaser.Ellipse#empty +* @property {boolean} empty - Gets or sets the empty state of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "empty", { + + get: function () { + return (this.width === 0 || this.height === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Ellipse object. +* +* @method Phaser.Ellipse.contains +* @param {Phaser.Ellipse} a - The Ellipse to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this ellipse, otherwise false. +*/ +Phaser.Ellipse.contains = function (a, x, y) { + + if (a.width <= 0 || a.height <= 0) { + return false; + } + + // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 + var normx = ((x - a.x) / a.width) - 0.5; + var normy = ((y - a.y) / a.height) - 0.5; + + normx *= normx; + normy *= normy; + + return (normx + normy < 0.25); + +}; + +/** +* Checks if the given Ellipse and Line objects intersect. +* @method Phaser.Ellipse.intersectsLine +* @param {Phaser.Ellipse} e - The Ellipse object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnPoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Ellipse.intersectsLine = function (e, l, returnPoints) { + var h = e.x; + var k = e.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = e.width / 2; + var b = e.height / 2; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Ellipse = Phaser.Ellipse; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Line object with a start and an end point. +* +* @class Phaser.Line +* @constructor +* @param {number} [x1=0] - The x coordinate of the start of the line. +* @param {number} [y1=0] - The y coordinate of the start of the line. +* @param {number} [x2=0] - The x coordinate of the end of the line. +* @param {number} [y2=0] - The y coordinate of the end of the line. +*/ +Phaser.Line = function (x1, y1, x2, y2) { + + x1 = x1 || 0; + y1 = y1 || 0; + x2 = x2 || 0; + y2 = y2 || 0; + + /** + * @property {Phaser.Point} start - The start point of the line. + */ + this.start = new Phaser.Point(x1, y1); + + /** + * @property {Phaser.Point} end - The end point of the line. + */ + this.end = new Phaser.Point(x2, y2); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.LINE; + +}; + +Phaser.Line.prototype = { + + /** + * Sets the components of the Line to the specified values. + * + * @method Phaser.Line#setTo + * @param {number} [x1=0] - The x coordinate of the start of the line. + * @param {number} [y1=0] - The y coordinate of the start of the line. + * @param {number} [x2=0] - The x coordinate of the end of the line. + * @param {number} [y2=0] - The y coordinate of the end of the line. + * @return {Phaser.Line} This line object + */ + setTo: function (x1, y1, x2, y2) { + + this.start.setTo(x1, y1); + this.end.setTo(x2, y2); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given points. + * + * @param {any} start - A {@link Phaser.Point} or point-like object. + * @param {any} end - A {@link Phaser.Point} or point-like object. + * @return {Phaser.Line} - This line object. + */ + fromPoints: function (start, end) { + + this.setTo(start.x, start.y, end.x, end.y); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given sprites. + * Can optionally be calculated from their center coordinates. + * + * @method Phaser.Line#fromSprite + * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {boolean} [useCenter=false] - If true it will use startSprite.centerX, if false startSprite.x. + * @return {Phaser.Line} This line object + */ + fromSprite: function (startSprite, endSprite, useCenter) { + + if (useCenter === undefined) { useCenter = false; } + + if (useCenter) + { + return this.setTo(startSprite.centerX, startSprite.centerY, endSprite.centerX, endSprite.centerY); + } + + return this.fromPoints(startSprite, endSprite); + + }, + + /** + * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. + * + * @method Phaser.Line#fromAngle + * @param {number} x - The x coordinate of the start of the line. + * @param {number} y - The y coordinate of the start of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line in pixels. + * @return {Phaser.Line} This line object + */ + fromAngle: function (x, y, angle, length) { + + this.start.setTo(x, y); + this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length)); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place from the center of the line. + * If you wish to rotate around a different point see Line.rotateAround. + * + * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. + * + * @method Phaser.Line#rotate + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotate: function (angle, asDegrees) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + this.start.rotate(cx, cy, angle, asDegrees); + this.end.rotate(cx, cy, angle, asDegrees); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place around the coordinates given. + * + * @method Phaser.Line#rotateAround + * @param {number} x - The x coordinate to offset the rotation from. + * @param {number} y - The y coordinate to offset the rotation from. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotateAround: function (x, y, angle, asDegrees) { + + this.start.rotate(x, y, angle, asDegrees); + this.end.rotate(x, y, angle, asDegrees); + + return this; + + }, + + /** + * Checks for intersection between this line and another Line. + * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * + * @method Phaser.Line#intersects + * @param {Phaser.Line} line - The line to check against this one. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ + intersects: function (line, asSegment, result) { + + return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result); + + }, + + /** + * Returns the reflected angle between two lines. + * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. + * + * @method Phaser.Line#reflect + * @param {Phaser.Line} line - The line to reflect off this line. + * @return {number} The reflected angle in radians. + */ + reflect: function (line) { + + return Phaser.Line.reflect(this, line); + + }, + + /** + * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. + * + * @method Phaser.Line#midPoint + * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. + * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. + */ + midPoint: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = (this.start.x + this.end.x) / 2; + out.y = (this.start.y + this.end.y) / 2; + + return out; + + }, + + /** + * Centers this Line on the given coordinates. + * + * The line is centered by positioning the start and end points so that the lines midpoint matches + * the coordinates given. + * + * @method Phaser.Line#centerOn + * @param {number} x - The x position to center the line on. + * @param {number} y - The y position to center the line on. + * @return {Phaser.Line} This line object + */ + centerOn: function (x, y) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + var tx = x - cx; + var ty = y - cy; + + this.start.add(tx, ty); + this.end.add(tx, ty); + + }, + + /** + * Tests if the given coordinates fall on this line. See {@link #pointOnSegment} to test against just the line segment. + * + * @method Phaser.Line#pointOnLine + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line, false if not. + */ + pointOnLine: function (x, y, epsilon) { + + return Phaser.Math.fuzzyEqual((x - this.start.x) * (this.end.y - this.start.y), (this.end.x - this.start.x) * (y - this.start.y), epsilon || 0); + + }, + + /** + * Tests if the given coordinates fall on this line and within the segment. See {@link #pointOnLine} to test against just the line. + * + * @method Phaser.Line#pointOnSegment + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line and segment, false if not. + */ + pointOnSegment: function (x, y, epsilon) { + + var xMin = Math.min(this.start.x, this.end.x); + var xMax = Math.max(this.start.x, this.end.x); + var yMin = Math.min(this.start.y, this.end.y); + var yMax = Math.max(this.start.y, this.end.y); + + return (this.pointOnLine(x, y, epsilon) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)); + + }, + + /** + * Picks a random point from anywhere on the Line segment and returns it. + * + * @method Phaser.Line#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = Math.random(); + + out.x = this.start.x + t * (this.end.x - this.start.x); + out.y = this.start.y + t * (this.end.y - this.start.y); + + return out; + + }, + + /** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * The start and end points are rounded before this runs as the algorithm works on integers. + * + * @method Phaser.Line#coordinatesOnLine + * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. + * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. + * @return {array} An array of coordinates. + */ + coordinatesOnLine: function (stepRate, results) { + + if (stepRate === undefined) { stepRate = 1; } + if (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 < x2) ? 1 : -1; + var sy = (y1 < y2) ? 1 : -1; + var err = dx - dy; + + results.push([x1, y1]); + + var i = 1; + + while (!((x1 === x2) && (y1 === y2))) + { + var e2 = err << 1; + + if (e2 > -dy) + { + err -= dy; + x1 += sx; + } + + if (e2 < dx) + { + err += dx; + y1 += sy; + } + + if (i % stepRate === 0) + { + results.push([x1, y1]); + } + + i++; + + } + + return results; + + }, + + /** + * Returns a new Line object with the same values for the start and end properties as this Line object. + * @method Phaser.Line#clone + * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned. + * @return {Phaser.Line} The cloned Line object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y); + } + else + { + output.setTo(this.start.x, this.start.y, this.end.x, this.end.y); + } + + return output; + + } + +}; + +/** +* @name Phaser.Line#length +* @property {number} length - Gets the length of the line segment. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "length", { + + get: function () { + return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#angle +* @property {number} angle - Gets the angle of the line in radians. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "angle", { + + get: function () { + return Phaser.Point.angle(this.end, this.start); + } + +}); + +/** +* @name Phaser.Line#slope +* @property {number} slope - Gets the slope of the line (y/x). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "slope", { + + get: function () { + return (this.end.y - this.start.y) / (this.end.x - this.start.x); + } + +}); + +/** +* @name Phaser.Line#perpSlope +* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "perpSlope", { + + get: function () { + return -((this.end.x - this.start.x) / (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#x +* @property {number} x - Gets the x coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "x", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#y +* @property {number} y - Gets the y coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "y", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#left +* @property {number} left - Gets the left-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "left", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#right +* @property {number} right - Gets the right-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "right", { + + get: function () { + return Math.max(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#top +* @property {number} top - Gets the top-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "top", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#bottom +* @property {number} bottom - Gets the bottom-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "bottom", { + + get: function () { + return Math.max(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#width +* @property {number} width - Gets the width of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "width", { + + get: function () { + return Math.abs(this.start.x - this.end.x); + } + +}); + +/** +* @name Phaser.Line#height +* @property {number} height - Gets the height of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "height", { + + get: function () { + return Math.abs(this.start.y - this.end.y); + } + +}); + +/** +* @name Phaser.Line#normalX +* @property {number} normalX - Gets the x component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalX", { + + get: function () { + return Math.cos(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalY +* @property {number} normalY - Gets the y component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalY", { + + get: function () { + return Math.sin(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalAngle +* @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalAngle", { + + get: function () { + return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI); + } + +}); + +/** +* Checks for intersection between two lines as defined by the given start and end points. +* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersectsPoints +* @param {Phaser.Point} a - The start of the first Line to be checked. +* @param {Phaser.Point} b - The end of the first line to be checked. +* @param {Phaser.Point} e - The start of the second Line to be checked. +* @param {Phaser.Point} f - The end of the second line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) { + + if (asSegment === undefined) { asSegment = true; } + if (result === undefined) { result = new Phaser.Point(); } + + var a1 = b.y - a.y; + var a2 = f.y - e.y; + var b1 = a.x - b.x; + var b2 = e.x - f.x; + var c1 = (b.x * a.y) - (a.x * b.y); + var c2 = (f.x * e.y) - (e.x * f.y); + var denom = (a1 * b2) - (a2 * b1); + + if (denom === 0) + { + return null; + } + + result.x = ((b1 * c2) - (b2 * c1)) / denom; + result.y = ((a2 * c1) - (a1 * c2)) / denom; + + if (asSegment) + { + var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y)); + var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc; + var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc; + + if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) + { + return result; + } + else + { + return null; + } + } + + return result; + +}; + +/** +* Checks for intersection between two lines. +* If asSegment is true it will check for segment intersection. +* If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersects +* @param {Phaser.Line} a - The first Line to be checked. +* @param {Phaser.Line} b - The second Line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersects = function (a, b, asSegment, result) { + + return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result); + +}; + +/** +* Checks for intersection between the Line and a Rectangle shape, or a rectangle-like +* object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. +* +* An intersection is considered valid if: +* +* The line starts within or ends within the rectangle; or +* The line segment intersects one of the 4 rectangle edges; and +* The line has a non-zero length; and +* The rectangle is not empty. +* +* For the purposes of this function rectangles are considered 'solid'. +* +* @method Phaser.Line.intersectsRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle. +*/ +Phaser.Line.intersectsRectangle = function (line, rect) { + + // Quick bail out + if (line.length === 0 || rect.empty) + { + return false; + } + + var x1 = line.start.x; + var y1 = line.start.y; + + var x2 = line.end.x; + var y2 = line.end.y; + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + + var t = 0; + + // If the start or end of the line is inside the rect then we assume + // collision, as rects are solid for our use-case. + + if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || + (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) + { + return true; + } + + if (x1 < bx1 && x2 >= bx1) + { + // Left edge + t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); + + if (t > by1 && t <= by2) + { + return true; + } + } + else if (x1 > bx2 && x2 <= bx2) + { + // Right edge + t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); + + if (t >= by1 && t <= by2) + { + return true; + } + } + + if (y1 < by1 && y2 >= by1) + { + // Top edge + t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + else if (y1 > by2 && y2 <= by2) + { + // Bottom edge + t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + + return false; + +}; + +/** +* Finds the closest intersection between the Line and a Rectangle shape, or a rectangle-like +* object, such as a Sprite or Body. +* +* @method Phaser.Line.intersectionWithRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @param {Phaser.Point} [result] - A Point object to store the result in. +* @return {?Phaser.Point} - The intersection closest to the Line's start, or null if there is no intersection. +*/ +Phaser.Line.intersectionWithRectangle = function (line, rect, result) { + + var self = Phaser.Line.intersectionWithRectangle; + + if (!result) + { + result = new Phaser.Point(); + } + + if (!self.edges) + { + self.edges = [new Phaser.Line(), new Phaser.Line(), new Phaser.Line(), new Phaser.Line()]; + } + + if (!self.edgeIntersection) + { + self.edgeIntersection = new Phaser.Point(); + } + + var edges = self.edges; + var edgeIntersection = self.edgeIntersection.set(0); + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + var closestDistance = Infinity; + + edges[0].setTo(bx1, by1, bx2, by1); + edges[1].setTo(bx1, by2, bx2, by2); + edges[2].setTo(bx1, by1, bx1, by2); + edges[3].setTo(bx2, by1, bx2, by2); + + for (var edge, i = 0; (edge = edges[i]); i++) + { + if (line.intersects(edge, true, edgeIntersection)) + { + var distance = line.start.distance(edgeIntersection); + + if (distance < closestDistance) + { + closestDistance = distance; + result.copyFrom(edgeIntersection); + } + } + } + + if (distance != null) + { + return result; + } + + return null; + +}; + +/** +* Returns the reflected angle between two lines. +* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. +* +* @method Phaser.Line.reflect +* @param {Phaser.Line} a - The base line. +* @param {Phaser.Line} b - The line to be reflected from the base line. +* @return {number} The reflected angle in radians. +*/ +Phaser.Line.reflect = function (a, b) { + + return 2 * b.normalAngle - 3.141592653589793 - a.angle; + +}; + +/** +* @author Mat Groves http://matgroves.com/ @Doormat23 +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. +* +* It is represented like so: +* +* | a | b | tx | +* | c | d | ty | +* | 0 | 0 | 1 | +* +* @class Phaser.Matrix +* @constructor +* @param {number} [a=1] - Horizontal scaling +* @param {number} [b=0] - Horizontal skewing +* @param {number} [c=0] - Vertical skewing +* @param {number} [d=1] - Vertical scaling +* @param {number} [tx=0] - Horizontal translation +* @param {number} [ty=0] - Vertical translation +*/ +Phaser.Matrix = function (a, b, c, d, tx, ty) { + + if (a === undefined || a === null) { a = 1; } + if (b === undefined || b === null) { b = 0; } + if (c === undefined || c === null) { c = 0; } + if (d === undefined || d === null) { d = 1; } + if (tx === undefined || tx === null) { tx = 0; } + if (ty === undefined || ty === null) { ty = 0; } + + /** + * @property {number} a + * @default 1 + */ + this.a = a; + + /** + * @property {number} b + * @default 0 + */ + this.b = b; + + /** + * @property {number} c + * @default 0 + */ + this.c = c; + + /** + * @property {number} d + * @default 1 + */ + this.d = d; + + /** + * @property {number} tx + * @default 0 + */ + this.tx = tx; + + /** + * @property {number} ty + * @default 0 + */ + this.ty = ty; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.MATRIX; + +}; + +Phaser.Matrix.prototype = { + + /** + * Sets the values of this Matrix to the values in the given array. + * + * The Array elements should be set as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @method Phaser.Matrix#fromArray + * @param {Array} array - The array to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + fromArray: function (array) { + + return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]); + + }, + + /** + * Sets the values of this Matrix to the given values. + * + * @method Phaser.Matrix#setTo + * @param {number} a - Horizontal scaling + * @param {number} b - Horizontal skewing + * @param {number} c - Vertical skewing + * @param {number} d - Vertical scaling + * @param {number} tx - Horizontal translation + * @param {number} ty - Vertical translation + * @return {Phaser.Matrix} This Matrix object. + */ + setTo: function (a, b, c, d, tx, ty) { + + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + + }, + + /** + * Creates a new Matrix object based on the values of this Matrix. + * If you provide the output parameter the values of this Matrix will be copied over to it. + * If the output parameter is blank a new Matrix object will be created. + * + * @method Phaser.Matrix#clone + * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created. + * @return {Phaser.Matrix} A clone of this Matrix. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); + } + else + { + output.a = this.a; + output.b = this.b; + output.c = this.c; + output.d = this.d; + output.tx = this.tx; + output.ty = this.ty; + } + + return output; + + }, + + /** + * Copies the properties from this Matrix to the given Matrix. + * + * @method Phaser.Matrix#copyTo + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} The destination Matrix object. + */ + copyTo: function (matrix) { + + matrix.copyFrom(this); + + return matrix; + + }, + + /** + * Copies the properties from the given Matrix into this Matrix. + * + * @method Phaser.Matrix#copyFrom + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + copyFrom: function (matrix) { + + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + + return this; + + }, + + /** + * Creates a Float32 Array with values populated from this Matrix object. + * + * @method Phaser.Matrix#toArray + * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not. + * @param {Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created. + * @return {Float32Array} The newly created array which contains the matrix. + */ + toArray: function (transpose, array) { + + if (array === undefined) { array = new Float32Array(9); } + + if (transpose) + { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else + { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + + }, + + /** + * Get a new position with the current transformation applied. + * + * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) + * + * @method Phaser.Matrix#apply + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, transformed through this matrix. + */ + apply: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + newPos.x = this.a * pos.x + this.c * pos.y + this.tx; + newPos.y = this.b * pos.x + this.d * pos.y + this.ty; + + return newPos; + + }, + + /** + * Get a new position with the inverse of the current transformation applied. + * + * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) + * + * @method Phaser.Matrix#applyInverse + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, inverse transformed through this matrix. + */ + applyInverse: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + var id = 1 / (this.a * this.d + this.c * -this.b); + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + + }, + + /** + * Translates the matrix on the x and y. + * This is the same as Matrix.tx += x. + * + * @method Phaser.Matrix#translate + * @param {number} x - The x value to translate on. + * @param {number} y - The y value to translate on. + * @return {Phaser.Matrix} This Matrix object. + */ + translate: function (x, y) { + + this.tx += x; + this.ty += y; + + return this; + + }, + + /** + * Applies a scale transformation to this matrix. + * + * @method Phaser.Matrix#scale + * @param {number} x - The amount to scale horizontally. + * @param {number} y - The amount to scale vertically. + * @return {Phaser.Matrix} This Matrix object. + */ + scale: function (x, y) { + + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + + }, + + /** + * Applies a rotation transformation to this matrix. + * + * @method Phaser.Matrix#rotate + * @param {number} angle - The angle to rotate by, given in radians. + * @return {Phaser.Matrix} This Matrix object. + */ + rotate: function (angle) { + + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos-this.b * sin; + this.b = a1 * sin+this.b * cos; + this.c = c1 * cos-this.d * sin; + this.d = c1 * sin+this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + + }, + + /** + * Appends the given Matrix to this Matrix. + * + * @method Phaser.Matrix#append + * @param {Phaser.Matrix} matrix - The matrix to append to this one. + * @return {Phaser.Matrix} This Matrix object. + */ + append: function (matrix) { + + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + + }, + + /** + * Resets this Matrix to an identity (default) matrix. + * + * @method Phaser.Matrix#identity + * @return {Phaser.Matrix} This Matrix object. + */ + identity: function () { + + return this.setTo(1, 0, 0, 1, 0, 0); + + } + +}; + +Phaser.identityMatrix = new Phaser.Matrix(); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. +* The following code creates a point at (0,0): +* `var myPoint = new Phaser.Point();` +* You can also use them as 2D Vectors and you'll find different vector related methods in this class. +* +* @class Phaser.Point +* @constructor +* @param {number} [x=0] - The horizontal position of this Point. +* @param {number} [y=0] - The vertical position of this Point. +*/ +Phaser.Point = function (x, y) { + + x = x || 0; + y = y || 0; + + /** + * @property {number} x - The x value of the point. + */ + this.x = x; + + /** + * @property {number} y - The y value of the point. + */ + this.y = y; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINT; + +}; + +Phaser.Point.prototype = { + + /** + * Copies the x and y properties from any given object to this Point. + * + * @method Phaser.Point#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Point} This Point object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y); + + }, + + /** + * Inverts the x and y values of this Point + * + * @method Phaser.Point#invert + * @return {Phaser.Point} This Point object. + */ + invert: function () { + + return this.setTo(this.y, this.x); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.setTo(2)` is the same as `Point.setTo(2, 2)` + * + * Identical to {@link #set}. + * + * @method Phaser.Point#setTo + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setTo: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.set(2)` is the same as `Point.set(2, 2)` + * + * Identical to {@link #setTo}. + * + * @method Phaser.Point#set + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + set: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object from a given polar coordinate. + * + * @method Phaser.Point#setToPolar + * @param {number} azimuth - The angular coordinate, in radians (unless `asDegrees`). + * @param {number} [radius=1] - The radial coordinate (length). + * @param {boolean} [asDegrees=false] - True if `azimuth` is in degrees. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setToPolar: function(azimuth, radius, asDegrees) { + + if (radius == null) { radius = 1; } + if (asDegrees) { azimuth = Phaser.Math.degToRad(azimuth); } + + return this.setTo(Math.cos(azimuth) * radius, Math.sin(azimuth) * radius); + + }, + + /** + * Adds the given x and y values to this Point. + * + * @method Phaser.Point#add + * @param {number} x - The value to add to Point.x. + * @param {number} y - The value to add to Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + add: function (x, y) { + + this.x += x; + this.y += y; + return this; + + }, + + /** + * Subtracts the given x and y values from this Point. + * + * @method Phaser.Point#subtract + * @param {number} x - The value to subtract from Point.x. + * @param {number} y - The value to subtract from Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + subtract: function (x, y) { + + this.x -= x; + this.y -= y; + return this; + + }, + + /** + * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. + * + * @method Phaser.Point#multiply + * @param {number} x - The value to multiply Point.x by. + * @param {number} y - The value to multiply Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + multiply: function (x, y) { + + this.x *= x; + this.y *= y; + return this; + + }, + + /** + * Divides Point.x and Point.y by the given x and y values. + * + * @method Phaser.Point#divide + * @param {number} x - The value to divide Point.x by. + * @param {number} y - The value to divide Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + divide: function (x, y) { + + this.x /= x; + this.y /= y; + return this; + + }, + + /** + * Clamps the x value of this Point to be between the given min and max. + * + * @method Phaser.Point#clampX + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampX: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + return this; + + }, + + /** + * Clamps the y value of this Point to be between the given min and max + * + * @method Phaser.Point#clampY + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampY: function (min, max) { + + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * Clamps this Point object values to be between the given min and max. + * + * @method Phaser.Point#clamp + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clamp: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * If this Point is not within the given object, moves it inside (at the nearest edge). + * + * @method Phaser.Point#clip + * @param {any} rect - A {@link Phaser.Rectangle} or any object with left, top, right, and bottom properties. + * @return {Phaser.Point} This Point object. + */ + clip: function (rect) { + + var left = rect.left, top = rect.top, right = rect.right, bottom = rect.bottom; + + if (this.x < left ) { this.x = left; } + else if (this.x > right) { this.x = right; } + if (this.y < top) { this.y = top; } + else if (this.y > bottom) { this.y = bottom; } + + return this; + + }, + + /** + * Creates a copy of the given Point. + * + * @method Phaser.Point#clone + * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The new Point object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(this.x, this.y); + } + else + { + output.setTo(this.x, this.y); + } + + return output; + + }, + + /** + * Copies the x and y properties from this Point to any given object. + * + * @method Phaser.Point#copyTo + * @param {any} dest - The object to copy to. + * @return {object} The dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + + return dest; + + }, + + /** + * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) + * + * @method Phaser.Point#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round] - Round the distance to the nearest integer (default false). + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + return Phaser.Point.distance(this, dest, round); + + }, + + /** + * Determines whether the given objects x/y values are equal to this Point object. + * + * @method Phaser.Point#equals + * @param {Phaser.Point|any} a - The object to compare with this Point. + * @return {boolean} A value of true if the x and y points are equal, otherwise false. + */ + equals: function (a) { + + return a.x === this.x && a.y === this.y; + + }, + + /** + * Determines whether a set of x-y coordinates are equal to this Point's. + * + * @method Phaser.Point#equalsXY + * @param {number} x - The x-coordinate to compare with this Point. + * @param {number} y - The y-coordinate to compare with this Point. + * @return {boolean} A value of true if the Point's coordinates are identical to the arguments, otherwise false. + */ + equalsXY: function (x, y) { + + return this.x === x && this.y === y; + + }, + + fuzzyEquals: function (a, epsilon) { + + return Phaser.Point.fuzzyEquals(this, a, epsilon); + + }, + + fuzzyEqualsXY: function (x, y, epsilon) { + + return Phaser.Point.fuzzyEqualsXY(this, x, y, epsilon); + + }, + + /** + * Returns the angle between this Point object and another object with public x and y properties. + * + * @method Phaser.Point#angle + * @param {Phaser.Point|any} a - The object to get the angle from this Point to. + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angle: function (a, asDegrees) { + + return this.angleXY(a.x, a.y, asDegrees); + + }, + + /** + * Returns the angle between this Point object and an x-y coordinate pair. + * + * @method Phaser.Point#angleXY + * @param {number} x - The x-coordinate + * @param {number} y - The y-coordinate + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angleXY: function (x, y, asDegrees) { + + var angle = Math.atan2(y - this.y, x - this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Returns the arctangent of this Point. + * + * @method Phaser.Point#atan + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where the vertex is (0, 0). Within [-pi, pi] or [-180deg, 180deg]. + */ + atan: function (asDegrees) { + + var angle = Math.atan2(this.y, this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Rotates this Point around the x/y coordinates given to the desired angle. + * + * @method Phaser.Point#rotate + * @param {number} x - The x coordinate of the anchor point. + * @param {number} y - The y coordinate of the anchor point. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {number} [distance] - An optional distance constraint between the Point and the anchor. + * @return {Phaser.Point} The modified point object. + */ + rotate: function (x, y, angle, asDegrees, distance) { + + return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance); + + }, + + /** + * Calculates the length of the Point object. + * + * @method Phaser.Point#getMagnitude + * @return {number} The length of the Point. + */ + getMagnitude: function () { + + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + + }, + + /** + * Calculates the length squared of the Point object. + * + * @method Phaser.Point#getMagnitudeSq + * @return {number} The length ^ 2 of the Point. + */ + getMagnitudeSq: function () { + + return (this.x * this.x) + (this.y * this.y); + + }, + + /** + * Alters the length of the Point without changing the direction. + * + * @method Phaser.Point#setMagnitude + * @param {number} magnitude - The desired magnitude of the resulting Point. + * @return {Phaser.Point} This Point object. + */ + setMagnitude: function (magnitude) { + + return this.normalize().multiply(magnitude, magnitude); + + }, + + /** + * Alters the Point object so that its length is 1, but it retains the same direction. + * + * @method Phaser.Point#normalize + * @return {Phaser.Point} This Point object. + */ + normalize: function () { + + if (!this.isZero()) + { + var m = this.getMagnitude(); + this.x /= m; + this.y /= m; + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at most the max value. + * + * @method Phaser.Point#limit + * @param {number} max - The maximum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#expand + */ + limit: function (max) { + + if (this.getMagnitudeSq() > max * max) + { + this.setMagnitude(max); + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at least the min value. + * + * @method Phaser.Point#expand + * @param {number} min - The minimum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#limit + */ + expand: function (min) { + + if (this.getMagnitudeSq() < min * min) + { + this.setMagnitude(min); + } + + return this; + + }, + + /** + * Determine if this point is at 0,0. + * + * @method Phaser.Point#isZero + * @return {boolean} True if this Point is 0,0, otherwise false. + */ + isZero: function () { + + return (this.x === 0 && this.y === 0); + + }, + + /** + * The dot product of this and another Point object. + * + * @method Phaser.Point#dot + * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point. + * @return {number} The result. + */ + dot: function (a) { + + return ((this.x * a.x) + (this.y * a.y)); + + }, + + /** + * The cross product of this and another Point object. + * + * @method Phaser.Point#cross + * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point. + * @return {number} The result. + */ + cross: function (a) { + + return ((this.x * a.y) - (this.y * a.x)); + + }, + + /** + * Make this Point perpendicular (90 degrees rotation) + * + * @method Phaser.Point#perp + * @return {Phaser.Point} This Point object. + */ + perp: function () { + + return this.setTo(-this.y, this.x); + + }, + + /** + * Make this Point perpendicular (-90 degrees rotation) + * + * @method Phaser.Point#rperp + * @return {Phaser.Point} This Point object. + */ + rperp: function () { + + return this.setTo(this.y, -this.x); + + }, + + /** + * Right-hand normalize (make unit length) this Point. + * + * @method Phaser.Point#normalRightHand + * @return {Phaser.Point} This Point object. + */ + normalRightHand: function () { + + return this.setTo(this.y * -1, this.x); + + }, + + /** + * Math.floor() both the x and y properties of this Point. + * + * @method Phaser.Point#floor + * @return {Phaser.Point} This Point object. + */ + floor: function () { + + return this.setTo(Math.floor(this.x), Math.floor(this.y)); + + }, + + /** + * Math.ceil() both the x and y properties of this Point. + * + * @method Phaser.Point#ceil + * @return {Phaser.Point} This Point object. + */ + ceil: function () { + + return this.setTo(Math.ceil(this.x), Math.ceil(this.y)); + + }, + + /** + * Math.round() both the x and y properties of this Point. + * + * @method Phaser.Point#round + * @return {Phaser.Point} This Point object. + */ + round: function () { + + return this.setTo(Math.round(this.x), Math.round(this.y)); + + }, + + /** + * Returns a string representation of this object. + * + * @method Phaser.Point#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; + + } + +}; + +Phaser.Point.prototype.constructor = Phaser.Point; + +/** +* Adds the coordinates of two points together to create a new point. +* +* @method Phaser.Point.add +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.add = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x + b.x; + out.y = a.y + b.y; + + return out; + +}; + +/** +* Subtracts the coordinates of two points to create a new point. +* +* @method Phaser.Point.subtract +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.subtract = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x - b.x; + out.y = a.y - b.y; + + return out; + +}; + +/** +* Multiplies the coordinates of two points to create a new point. +* +* @method Phaser.Point.multiply +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiply = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x * b.x; + out.y = a.y * b.y; + + return out; + +}; + +/** +* Divides the coordinates of two points to create a new point. +* +* @method Phaser.Point.divide +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.divide = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x / b.x; + out.y = a.y / b.y; + + return out; + +}; + +/** +* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. +* +* @method Phaser.Point.equals +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {boolean} A value of true if the Points are equal, otherwise false. +*/ +Phaser.Point.equals = function (a, b) { + + return a.x === b.x && a.y === b.y; + +}; + +Phaser.Point.equalsXY = function (a, x, y) { + + return a.x === x && a.y === y; + +}; + +Phaser.Point.fuzzyEquals = function (a, b, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, b.x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, b.y, epsilon); + +}; + +Phaser.Point.fuzzyEqualsXY = function (a, x, y, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, y, epsilon); + +}; + +/** +* Returns the angle between two Point objects. +* +* @method Phaser.Point.angle +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {number} The angle, where b is the vertex. Within [-pi, pi]. +*/ +Phaser.Point.angle = function (a, b) { + + return Math.atan2(a.y - b.y, a.x - b.x); + +}; + +/** +* Creates a negative Point. +* +* @method Phaser.Point.negative +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.negative = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.x, -a.y); + +}; + +/** +* Adds two 2D Points together and multiplies the result by the given scalar. +* +* @method Phaser.Point.multiplyAdd +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} s - The scaling value. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiplyAdd = function (a, b, s, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + b.x * s, a.y + b.y * s); + +}; + +/** +* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. +* +* @method Phaser.Point.interpolate +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.interpolate = function (a, b, f, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f); + +}; + +/** +* Return a perpendicular vector (90 degrees rotation) +* +* @method Phaser.Point.perp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.perp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.y, a.x); + +}; + +/** +* Return a perpendicular vector (-90 degrees rotation) +* +* @method Phaser.Point.rperp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.rperp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y, -a.x); + +}; + +/** +* Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). +* +* @method Phaser.Point.distance +* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. +* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. +* @param {boolean} [round=false] - Round the distance to the nearest integer. +* @return {number} The distance between this Point object and the destination Point object. +*/ +Phaser.Point.distance = function (a, b, round) { + + var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y); + return round ? Math.round(distance) : distance; + +}; + +/** +* Project two Points onto another Point. +* +* @method Phaser.Point.project +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.project = function (a, b, out) { + + if (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; + +}; + +/** +* Project two Points onto a Point of unit length. +* +* @method Phaser.Point.projectUnit +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.projectUnit = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var amt = a.dot(b); + + if (amt !== 0) + { + out.setTo(amt * b.x, amt * b.y); + } + + return out; + +}; + +/** +* Right-hand normalize (make unit length) a Point. +* +* @method Phaser.Point.normalRightHand +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalRightHand = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y * -1, a.x); + +}; + +/** +* Normalize (make unit length) a Point. +* +* @method Phaser.Point.normalize +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalize = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var m = a.getMagnitude(); + + if (m !== 0) + { + out.setTo(a.x / m, a.y / m); + } + + return out; + +}; + +/** +* Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by +* the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument +* is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. +* +* The distance allows you to specify a distance constraint for the rotation between the point and the +* coordinates. If none is given the distance between the two is calculated and used. +* +* @method Phaser.Point.rotate +* @param {Phaser.Point} a - The Point object to rotate. +* @param {number} x - The x coordinate of the anchor point +* @param {number} y - The y coordinate of the anchor point +* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {number} [distance] - An optional distance constraint between the Point and the anchor. +* @return {Phaser.Point} The modified point object. +*/ +Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) { + + if (asDegrees) { angle = Phaser.Math.degToRad(angle); } + + if (distance === undefined) + { + a.subtract(x, y); + + var s = Math.sin(angle); + var c = Math.cos(angle); + + var tx = c * a.x - s * a.y; + var ty = s * a.x + c * a.y; + + a.x = tx + x; + a.y = ty + y; + } + else + { + var t = angle + Math.atan2(a.y - y, a.x - x); + a.x = x + distance * Math.cos(t); + a.y = y + distance * Math.sin(t); + } + + return a; + +}; + +/** +* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. +* +* @method Phaser.Point.centroid +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.centroid = function (points, out) { + + if (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 < pointslength; i++) + { + Phaser.Point.add(out, points[i], out); + } + + out.divide(pointslength, pointslength); + + return out; + +}; + +/** +* Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. +* If the object doesn't contain those properties a Point with x/y of zero will be returned. +* +* @method Phaser.Point.parse +* @static +* @param {object} obj - The object to parse. +* @param {string} [xProp='x'] - The property used to set the Point.x value. +* @param {string} [yProp='y'] - The property used to set the Point.y value. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.parse = function(obj, xProp, yProp) { + + xProp = xProp || 'x'; + yProp = yProp || 'y'; + + var point = new Phaser.Point(); + + if (obj[xProp]) + { + point.x = parseInt(obj[xProp], 10); + } + + if (obj[yProp]) + { + point.y = parseInt(obj[yProp], 10); + } + + return point; + +}; + +/** + * Tests a Point or Point-like object. + * + * @method Phaser.Point.isPoint + * @static + * @return {boolean} - True if the object has numeric x and y properties. + */ +Phaser.Point.isPoint = function(obj) { + + return (obj != null) && (typeof obj.x === 'number') && (typeof obj.y === 'number'); + +}; + +/** +* Sets the `x` and `y` values of an object and returns the object. +* +* @method Phaser.Point#set +* @static +* @param {object} obj - An object with numeric x and y properties. +* @param {number} x - The x value. +* @param {number} [y] - The y value. If not given the x value will be used in its place. +* @return {object} The object. Useful for chaining method calls. +*/ +Phaser.Point.set = function(obj, x, y) { + + obj.x = x || 0; + obj.y = y || ( (y !== 0) ? obj.x : 0 ); + + return obj; + +}; + +/** +* Sorts an array of points in a clockwise direction, relative to a reference point. +* +* The sort is clockwise relative to the display, starting from a 12 o'clock position. +* (In the Cartesian plane, it is anticlockwise, starting from the -y direction.) +* +* Example sequence: (0, -1), (1, 0), (0, 1), (-1, 0) +* +* @method Phaser.Point#sortClockwise +* @static +* @param {array} points - An array of Points or point-like objects (e.g., sprites). +* @param {object|Phaser.Point} [center] - The reference point. If omitted, the {@link #centroid} (midpoint) of the points is used. +* @return {array} The sorted array. +*/ +Phaser.Point.sortClockwise = function(points, center) { + + // Adapted from (ciamej) + + if (!center) + { + center = this.centroid(points); + } + + var cx = center.x; + var cy = center.y; + + var sort = function(a, b) { + if (a.x - cx >= 0 && b.x - cx < 0) + { + return -1; + } + + if (a.x - cx < 0 && b.x - cx >= 0) + { + return 1; + } + + if (a.x - cx === 0 && b.x - cx === 0) + { + if (a.y - cy >= 0 || b.y - cy >= 0) + { + return (a.y > b.y) ? 1 : -1; + } + + return (b.y > a.y) ? 1 : -1; + } + + // Compute the cross product of vectors (center -> a) * (center -> b) + var det = (a.x - cx) * -(b.y - cy) - (b.x - cx) * -(a.y - cy); + + if (det < 0) + { + return -1; + } + + if (det > 0) + { + return 1; + } + + // Points a and b are on the same line from the center + // Check which point is closer to the center + var d1 = (a.x - cx) * (a.x - cx) + (a.y - cy) * (a.y - cy); + var d2 = (b.x - cx) * (b.x - cx) + (b.y - cy) * (b.y - cy); + + return (d1 > d2) ? -1 : 1; + }; + + return points.sort(sort); + +}; + + +// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Point = Phaser.Point; + +/** +* @author Richard Davey +* @author Adrien Brault +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Polygon. +* +* The points can be set from a variety of formats: +* +* - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` +* - An array of objects with public x/y properties: `[obj1, obj2, ...]` +* - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` +* - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` +* - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` +* - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` +* +* @class Phaser.Polygon +* @constructor +* @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. +*/ +Phaser.Polygon = function () { + + /** + * @property {number} area - The area of this Polygon. + */ + this.area = 0; + + /** + * @property {array} _points - An array of Points that make up this Polygon. + * @private + */ + this._points = []; + + if (arguments.length > 0) + { + this.setTo.apply(this, arguments); + } + + /** + * @property {boolean} closed - Is the Polygon closed or not? + */ + this.closed = true; + + /** + * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ? + */ + this.flattened = false; + + /** + * @property {number} type - The base object type. + */ + this.type = Phaser.POLYGON; + +}; + +Phaser.Polygon.prototype = { + + /** + * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] + * + * @method Phaser.Polygon#toNumberArray + * @param {array} [output] - The array to append the points to. If not specified a new array will be created. + * @return {array} The flattened array. + */ + toNumberArray: function (output) { + + if (output === undefined) { output = []; } + + for (var i = 0; i < this._points.length; i++) + { + if (typeof this._points[i] === 'number') + { + output.push(this._points[i]); + output.push(this._points[i + 1]); + i++; + } + else + { + output.push(this._points[i].x); + output.push(this._points[i].y); + } + } + + return output; + + }, + + /** + * Flattens this Polygon so the points are a sequence of numbers. + * Any Point objects found are removed and replaced with two numbers. + * Also sets the Polygon.flattened property to `true`. + * + * @method Phaser.Polygon#flatten + * @return {Phaser.Polygon} This Polygon object + */ + flatten: function () { + + this._points = this.toNumberArray(); + + this.flattened = true; + + return this; + + }, + + /** + * Creates a copy of the given Polygon. + * This is a deep clone, the resulting copy contains new Phaser.Point objects + * + * @method Phaser.Polygon#clone + * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created. + * @return {Phaser.Polygon} The cloned (`output`) polygon object. + */ + clone: function (output) { + + var points = this._points.slice(); + + if (output === undefined || output === null) + { + output = new Phaser.Polygon(points); + } + else + { + output.setTo(points); + } + + return output; + + }, + + /** + * Checks whether the x and y coordinates are contained within this polygon. + * + * @method Phaser.Polygon#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this polygon, otherwise false. + */ + contains: function (x, y) { + + // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva + + var inside = false; + + if (this.flattened) + { + for (var i = -2, j = this._points.length - 2; (i += 2) < this._points.length; j = i) + { + var ix = this._points[i]; + var iy = this._points[i + 1]; + + var jx = this._points[j]; + var jy = this._points[j + 1]; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + + } + else + { + for (var i = -1, j = this._points.length - 1; ++i < this._points.length; j = i) + { + var ix = this._points[i].x; + var iy = this._points[i].y; + + var jx = this._points[j].x; + var jy = this._points[j].y; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + } + + return inside; + + }, + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` + * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` + * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` + * + * `setTo` may also be called without any arguments to remove all points. + * + * @method Phaser.Polygon#setTo + * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. + * @return {Phaser.Polygon} This Polygon object + */ + setTo: function (points) { + + this.area = 0; + this._points = []; + + if (arguments.length > 0) + { + // If points isn't an array, use arguments as the array + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments); + } + + var y0 = Number.MAX_VALUE; + + // Allows for mixed-type arguments + for (var i = 0, len = points.length; i < len; i++) + { + if (typeof points[i] === 'number') + { + var p = new PIXI.Point(points[i], points[i + 1]); + i++; + } + else if (Array.isArray(points[i])) + { + var p = new PIXI.Point(points[i][0], points[i][1]); + } + else + { + var p = new PIXI.Point(points[i].x, points[i].y); + } + + this._points.push(p); + + // Lowest boundary + if (p.y < y0) + { + y0 = p.y; + } + } + + this.calculateArea(y0); + } + + return this; + + }, + + /** + * Calcuates the area of the Polygon. This is available in the property Polygon.area + * + * @method Phaser.Polygon#calculateArea + * @private + * @param {number} y0 - The lowest boundary + * @return {number} The area of the Polygon. + */ + calculateArea: function (y0) { + + var p1; + var p2; + var avgHeight; + var width; + + for (var i = 0, len = this._points.length; i < len; i++) + { + p1 = this._points[i]; + + if (i === len - 1) + { + p2 = this._points[0]; + } + else + { + p2 = this._points[i + 1]; + } + + avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2; + width = p1.x - p2.x; + this.area += avgHeight * width; + } + + return this.area; + + } + +}; + +Phaser.Polygon.prototype.constructor = Phaser.Polygon; + +/** +* The points of this polygon. +* +* You can modify these with {@link Phaser.Polygon#setTo setTo}. +* +* @name Phaser.Polygon#points +* @property {Phaser.Point[]} points - The array of vertex points. +* @readonly +*/ +Object.defineProperty(Phaser.Polygon.prototype, 'points', { + + get: function() { + return this._points; + } + +}); + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Polygon = Phaser.Polygon; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. +* If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. +* +* @class Phaser.Rectangle +* @constructor +* @param {number} x - The x coordinate of the top-left corner of the Rectangle. +* @param {number} y - The y coordinate of the top-left corner of the Rectangle. +* @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. +*/ +Phaser.Rectangle = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.RECTANGLE; + +}; + +Phaser.Rectangle.prototype = { + + /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method Phaser.Rectangle#offset + * @param {number} dx - Moves the x value of the Rectangle object by this amount. + * @param {number} dy - Moves the y value of the Rectangle object by this amount. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Rectangle#offsetPoint + * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offsetPoint: function (point) { + + return this.offset(point.x, point.y); + + }, + + /** + * Sets the members of Rectangle to the specified values. + * @method Phaser.Rectangle#setTo + * @param {number} x - The x coordinate of the top-left corner of the Rectangle. + * @param {number} y - The y coordinate of the top-left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Scales the width and height of this Rectangle by the given amounts. + * + * @method Phaser.Rectangle#scale + * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. + * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. + * @return {Phaser.Rectangle} This Rectangle object + */ + scale: function (x, y) { + + if (y === undefined) { y = x; } + + this.width *= x; + this.height *= y; + + return this; + + }, + + /** + * Centers this Rectangle so that the center coordinates match the given x and y values. + * + * @method Phaser.Rectangle#centerOn + * @param {number} x - The x coordinate to place the center of the Rectangle at. + * @param {number} y - The y coordinate to place the center of the Rectangle at. + * @return {Phaser.Rectangle} This Rectangle object + */ + centerOn: function (x, y) { + + this.centerX = x; + this.centerY = y; + + return this; + + }, + + /** + * Runs Math.floor() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#floor + */ + floor: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + + }, + + /** + * Runs Math.floor() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#floorAll + */ + floorAll: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.width = Math.floor(this.width); + this.height = Math.floor(this.height); + + }, + + /** + * Runs Math.ceil() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#ceil + */ + ceil: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + + }, + + /** + * Runs Math.ceil() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#ceilAll + */ + ceilAll: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.width = Math.ceil(this.width); + this.height = Math.ceil(this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the left, top, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFromBounds + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFromBounds: function(source) { + + return this.setTo(source.left, source.top, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Rectangle to any given object. + * @method Phaser.Rectangle#copyTo + * @param {any} source - The object to copy to. + * @return {object} This object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method Phaser.Rectangle#inflate + * @param {number} dx - The amount to be added to the left side of the Rectangle. + * @param {number} dy - The amount to be added to the bottom side of the Rectangle. + * @return {Phaser.Rectangle} This Rectangle object. + */ + inflate: function (dx, dy) { + + return Phaser.Rectangle.inflate(this, dx, dy); + + }, + + /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method Phaser.Rectangle#size + * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object. + */ + size: function (output) { + + return Phaser.Rectangle.size(this, output); + + }, + + /** + * Resize the Rectangle by providing a new width and height. + * The x and y positions remain unchanged. + * + * @method Phaser.Rectangle#resize + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method Phaser.Rectangle#clone + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ + clone: function (output) { + + return Phaser.Rectangle.clone(this, output); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method Phaser.Rectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + contains: function (x, y) { + + return Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method Phaser.Rectangle#containsRect + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + containsRect: function (b) { + + return Phaser.Rectangle.containsRect(b, this); + + }, + + /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method Phaser.Rectangle#equals + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + */ + equals: function (b) { + + return Phaser.Rectangle.equals(this, b); + + }, + + /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method Phaser.Rectangle#intersection + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ + intersection: function (b, out) { + + return Phaser.Rectangle.intersection(this, b, out); + + }, + + /** + * Determines whether this Rectangle and another given Rectangle intersect with each other. + * This method checks the x, y, width, and height properties of the two Rectangles. + * + * @method Phaser.Rectangle#intersects + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + */ + intersects: function (b) { + + return Phaser.Rectangle.intersects(this, b); + + }, + + /** + * Determines whether the coordinates given intersects (overlaps) with this Rectangle. + * + * @method Phaser.Rectangle#intersectsRaw + * @param {number} left - The x coordinate of the left of the area. + * @param {number} right - The right coordinate of the area. + * @param {number} top - The y coordinate of the area. + * @param {number} bottom - The bottom coordinate of the area. + * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 + * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + */ + intersectsRaw: function (left, right, top, bottom, tolerance) { + + return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance); + + }, + + /** + * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. + * @method Phaser.Rectangle#union + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ + union: function (b, out) { + + return Phaser.Rectangle.union(this, b, out); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Rectangle. + * + * @method Phaser.Rectangle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = this.randomX; + out.y = this.randomY; + + return out; + + }, + + /** + * Returns a point based on the given position constant, which can be one of: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * This method returns the same values as calling Rectangle.bottomLeft, etc, but those + * calls always create a new Point object, where-as this one allows you to use your own. + * + * @method Phaser.Rectangle#getPoint + * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. + * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the point in its `x` and `y` properties. + */ + getPoint: function (position, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + return out.set(this.x, this.y); + + case Phaser.TOP_CENTER: + return out.set(this.centerX, this.y); + + case Phaser.TOP_RIGHT: + return out.set(this.right, this.y); + + case Phaser.LEFT_CENTER: + return out.set(this.x, this.centerY); + + case Phaser.CENTER: + return out.set(this.centerX, this.centerY); + + case Phaser.RIGHT_CENTER: + return out.set(this.right, this.centerY); + + case Phaser.BOTTOM_LEFT: + return out.set(this.x, this.bottom); + + case Phaser.BOTTOM_CENTER: + return out.set(this.centerX, this.bottom); + + case Phaser.BOTTOM_RIGHT: + return out.set(this.right, this.bottom); + } + + }, + + /** + * Creates or positions four {@link Phaser.Line} lines representing the Rectangle's sides. + * + * @method Phaser.Rectangle#sides + * @param {Phaser.Line} [top] + * @param {Phaser.Line} [right] + * @param {Phaser.Line} [bottom] + * @param {Phaser.Line} [left] + * @return {?Phaser.Line[]} - An array containing four lines (if no arguments were given), or null. + */ + sides: function (top, right, bottom, left) { + + if (!arguments.length) { + top = new Phaser.Line(); + right = new Phaser.Line(); + bottom = new Phaser.Line(); + left = new Phaser.Line(); + } + + var x1 = this.x; + var y1 = this.y; + var x2 = this.right; + var y2 = this.bottom; + + top.setTo(x1, y1, x2, y1); + right.setTo(x2, y1, x2, y2); + bottom.setTo(x1, y2, x2, y2); + left.setTo(x1, y1, x1, y2); + + if (!arguments.length) { + return [top, right, bottom, left]; + } + + return null; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Rectangle#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + + } + +}; + +/** +* @name Phaser.Rectangle#halfWidth +* @property {number} halfWidth - Half of the width of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", { + + get: function () { + return Math.round(this.width / 2); + } + +}); + +/** +* @name Phaser.Rectangle#halfHeight +* @property {number} halfHeight - Half of the height of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", { + + get: function () { + return Math.round(this.height / 2); + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. +* @name Phaser.Rectangle#bottom +* @property {number} bottom - The sum of the y and height properties. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value <= this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + + } + +}); + +/** +* The location of the Rectangles bottom left corner as a Point object. +* @name Phaser.Rectangle#bottomLeft +* @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", { + + get: function () { + return new Phaser.Point(this.x, this.bottom); + }, + + set: function (value) { + this.x = value.x; + this.bottom = value.y; + } + +}); + +/** +* The location of the Rectangles bottom right corner as a Point object. +* @name Phaser.Rectangle#bottomRight +* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", { + + get: function () { + return new Phaser.Point(this.right, this.bottom); + }, + + set: function (value) { + this.right = value.x; + this.bottom = value.y; + } + +}); + +/** +* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. +* @name Phaser.Rectangle#left +* @property {number} left - The x coordinate of the left of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + if (value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + } + +}); + +/** +* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. +* @name Phaser.Rectangle#right +* @property {number} right - The sum of the x and width properties. +*/ +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 = value - this.x; + } + } + +}); + +/** +* The volume of the Rectangle derived from width * height. +* @name Phaser.Rectangle#volume +* @property {number} volume - The volume of the Rectangle derived from width * height. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "volume", { + + get: function () { + return this.width * this.height; + } + +}); + +/** +* The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @name Phaser.Rectangle#perimeter +* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", { + + get: function () { + return (this.width * 2) + (this.height * 2); + } + +}); + +/** +* The x coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerX +* @property {number} centerX - The x coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerX", { + + get: function () { + return this.x + this.halfWidth; + }, + + set: function (value) { + this.x = value - this.halfWidth; + } + +}); + +/** +* The y coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerY +* @property {number} centerY - The y coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerY", { + + get: function () { + return this.y + this.halfHeight; + }, + + set: function (value) { + this.y = value - this.halfHeight; + } + +}); + +/** +* A random value between the left and right values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomX +* @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomX", { + + get: function () { + + return this.x + (Math.random() * this.width); + + } + +}); + +/** +* A random value between the top and bottom values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomY +* @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomY", { + + get: function () { + + return this.y + (Math.random() * this.height); + + } + +}); + +/** +* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. +* However it does affect the height property, whereas changing the y value does not affect the height property. +* @name Phaser.Rectangle#top +* @property {number} top - The y coordinate of the top of the Rectangle. +*/ +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); + } + } + +}); + +/** +* The location of the Rectangles top left corner as a Point object. +* @name Phaser.Rectangle#topLeft +* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. +*/ +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; + } + +}); + +/** +* The location of the Rectangles top right corner as a Point object. +* @name Phaser.Rectangle#topRight +* @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "topRight", { + + get: function () { + return new Phaser.Point(this.x + this.width, this.y); + }, + + set: function (value) { + this.right = value.x; + this.y = value.y; + } + +}); + +/** +* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. +* If set to true then all of the Rectangle properties are set to 0. +* @name Phaser.Rectangle#empty +* @property {boolean} empty - Gets or sets the Rectangles empty state. +*/ +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; + +/** +* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. +* @method Phaser.Rectangle.inflate +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} dx - The amount to be added to the left side of the Rectangle. +* @param {number} dy - The amount to be added to the bottom side of the Rectangle. +* @return {Phaser.Rectangle} This Rectangle object. +*/ +Phaser.Rectangle.inflate = function (a, dx, dy) { + + a.x -= dx; + a.width += 2 * dx; + a.y -= dy; + a.height += 2 * dy; + + return a; + +}; + +/** +* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. +* @method Phaser.Rectangle.inflatePoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. +* @return {Phaser.Rectangle} The Rectangle object. +*/ +Phaser.Rectangle.inflatePoint = function (a, point) { + + return Phaser.Rectangle.inflate(a, point.x, point.y); + +}; + +/** +* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. +* @method Phaser.Rectangle.size +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. +* @return {Phaser.Point} The size of the Rectangle object +*/ +Phaser.Rectangle.size = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(a.width, a.height); + } + else + { + output.setTo(a.width, a.height); + } + + return output; + +}; + +/** +* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. +* @method Phaser.Rectangle.clone +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.clone = function (a, output) { + + if (output === undefined || output === null) + { + 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; + +}; + +/** +* Returns a new Rectangle object with the same values for the left, top, width, and height properties as the original object. +* @method Phaser.Rectangle.createFromBounds +* @param {any} a - An object with `left`, `top`, `width`, and `height` properties. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.createFromBounds = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Rectangle(a.x, a.y, a.width, a.height); + } + + return output.copyFromBounds(a); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by this Rectangle object. +* @method Phaser.Rectangle.contains +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +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); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by the given raw values. +* @method Phaser.Rectangle.containsRaw +* @param {number} rx - The x coordinate of the top left of the area. +* @param {number} ry - The y coordinate of the top left of the area. +* @param {number} rw - The width of the area. +* @param {number} rh - The height of the area. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) { + + return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh)); + +}; + +/** +* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. +* @method Phaser.Rectangle.containsPoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsPoint = function (a, point) { + + return Phaser.Rectangle.contains(a, point.x, point.y); + +}; + +/** +* Determines whether the first Rectangle object is fully contained within the second Rectangle object. +* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. +* @method Phaser.Rectangle.containsRect +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRect = function (a, b) { + + // If the given rect has a larger volume than this one then it can never contain it + if (a.volume > b.volume) + { + return false; + } + + return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom); + +}; + +/** +* Determines whether the two Rectangles are equal. +* This method compares the x, y, width and height properties of each Rectangle. +* @method Phaser.Rectangle.equals +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. +*/ +Phaser.Rectangle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height); + +}; + +/** +* Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. +* @method Phaser.Rectangle.sameDimensions +* @param {Rectangle-like} a - The first Rectangle object. +* @param {Rectangle-like} b - The second Rectangle object. +* @return {boolean} True if the object have equivalent values for the width and height properties. +*/ +Phaser.Rectangle.sameDimensions = function (a, b) { + + return (a.width === b.width && a.height === b.height); + +}; + +/** +* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. +* @method Phaser.Rectangle.intersection +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. +*/ +Phaser.Rectangle.intersection = function (a, b, output) { + + if (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; + +}; + +/** +* Determines whether the two Rectangles intersect with each other. +* This method checks the x, y, width, and height properties of the Rectangles. +* @method Phaser.Rectangle.intersects +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. +*/ +Phaser.Rectangle.intersects = function (a, b) { + + if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) + { + return false; + } + + return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom); + +}; + +/** +* Determines whether the object specified intersects (overlaps) with the given values. +* @method Phaser.Rectangle.intersectsRaw +* @param {number} left - The x coordinate of the left of the area. +* @param {number} right - The right coordinate of the area. +* @param {number} top - The y coordinate of the area. +* @param {number} bottom - The bottom coordinate of the area. +* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 +* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. +*/ +Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) { + + if (tolerance === undefined) { tolerance = 0; } + + return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); + +}; + +/** +* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. +* @method Phaser.Rectangle.union +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. +*/ +Phaser.Rectangle.union = function (a, b, output) { + + if (output === undefined) + { + output = new Phaser.Rectangle(); + } + + return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top)); + +}; + +/** +* Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. +* +* @method Phaser.Rectangle#aabb +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. +* @return {Phaser.Rectangle} The new Rectangle object. +* @static +*/ +Phaser.Rectangle.aabb = function(points, out) { + + if (out === undefined) { + out = new Phaser.Rectangle(); + } + + var xMax = Number.NEGATIVE_INFINITY, + xMin = Number.POSITIVE_INFINITY, + yMax = Number.NEGATIVE_INFINITY, + yMin = Number.POSITIVE_INFINITY; + + points.forEach(function(point) { + if (point.x > xMax) { + xMax = point.x; + } + if (point.x < xMin) { + xMin = point.x; + } + + if (point.y > yMax) { + yMax = point.y; + } + if (point.y < yMin) { + yMin = point.y; + } + }); + + out.setTo(xMin, yMin, xMax - xMin, yMax - yMin); + + return out; +}; + +// Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Rectangle = Phaser.Rectangle; +PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0); + +/** +* @author Mat Groves http://matgroves.com/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Rounded Rectangle object is an area defined by its position and has nice rounded corners, +* as indicated by its top-left corner point (x, y) and by its width and its height. +* +* @class Phaser.RoundedRectangle +* @constructor +* @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle. +* @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle. +* @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value. +* @param {number} [radius=20] - Controls the radius of the rounded corners. +*/ +Phaser.RoundedRectangle = function(x, y, width, height, radius) +{ + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + if (radius === undefined) { radius = 20; } + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} radius - The radius of the rounded corners. + */ + this.radius = radius || 20; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROUNDEDRECTANGLE; +}; + +Phaser.RoundedRectangle.prototype = { + + /** + * Returns a new RoundedRectangle object with the same values for the x, y, width, height and + * radius properties as this RoundedRectangle object. + * + * @method Phaser.RoundedRectangle#clone + * @return {Phaser.RoundedRectangle} + */ + clone: function () { + + return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. + * + * @method Phaser.RoundedRectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. + */ + 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; + + } + +}; + +Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle; + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.RoundedRectangle = Phaser.RoundedRectangle; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. +* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y +* +* @class Phaser.Camera +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera +* @param {number} x - Position of the camera on the X axis +* @param {number} y - Position of the camera on the Y axis +* @param {number} width - The width of the view rectangle +* @param {number} height - The height of the view rectangle +*/ +Phaser.Camera = function (game, id, x, y, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + */ + this.world = game.world; + + /** + * @property {number} id - Reserved for future multiple camera set-ups. + * @default + */ + this.id = 0; + + /** + * Camera view. + * The view into the world we wish to render (by default the game dimensions). + * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. + * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. + * @property {Phaser.Rectangle} view + */ + this.view = new Phaser.Rectangle(x, y, width, height); + + /** + * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. + * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound + * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. + * + * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. + */ + this.bounds = new Phaser.Rectangle(x, y, width, height); + + /** + * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move. + */ + this.deadzone = null; + + /** + * @property {boolean} visible - Whether this camera is visible or not. + * @default + */ + this.visible = true; + + /** + * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. + * @default + */ + this.roundPx = true; + + /** + * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. + */ + this.atLimit = { x: false, y: false }; + + /** + * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. + * @default + */ + this.target = null; + + /** + * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot. + */ + this.displayObject = null; + + /** + * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot. + */ + this.scale = null; + + /** + * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. + * @readonly + */ + this.totalInView = 0; + + /** + * The linear interpolation value to use when following a target. + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * @property {Phaser.Point} lerp + * @default + */ + this.lerp = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes. + */ + this.onShakeComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes. + */ + this.onFlashComplete = new Phaser.Signal(); + + /** + * This signal is dispatched when the camera fade effect completes. + * When the fade effect completes you will be left with the screen black (or whatever + * color you faded to). In order to reset this call `Camera.resetFX`. This is called + * automatically when you change State. + * @property {Phaser.Signal} onFadeComplete + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * The Graphics object used to handle camera fx such as fade and flash. + * @property {Phaser.Graphics} fx + * @protected + */ + this.fx = null; + + /** + * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position. + * @private + */ + this._targetPosition = new Phaser.Point(); + + /** + * @property {number} edge - Edge property. + * @private + * @default + */ + this._edge = 0; + + /** + * @property {Phaser.Point} position - Current position of the camera in world. + * @private + * @default + */ + this._position = new Phaser.Point(); + + /** + * @property {Object} _shake - The shake effect container. + * @private + */ + this._shake = { + intensity: 0, + duration: 0, + horizontal: false, + vertical: false, + shakeBounds: true, + x: 0, + y: 0 + }; + + /** + * @property {number} _fxDuration - FX duration timer. + * @private + */ + this._fxDuration = 0; + + /** + * @property {number} _fxType - The FX type running. + * @private + */ + this._fxType = 0; + + /** + * @property {Phaser.Rectangle} + * @private + */ + this._fixedView = new Phaser.Rectangle(); + +}; + +/** +* A follow style that uses no deadzone. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_LOCKON = 0; + +/** +* A follow style that uses a tall, narrow deadzone (0.33 x 0.125) with a center slightly above the view center. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_PLATFORMER = 1; + +/** +* A follow style that uses a square deadzone (0.25 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN = 2; + +/** +* A follow style that uses a small square deadzone (0.125 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_BOTH = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_HORIZONTAL = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_VERTICAL = 6; + +/** +* @constant +* @type {boolean} +*/ +Phaser.Camera.ENABLE_FX = true; + +Phaser.Camera.prototype = { + + /** + * Called automatically by Phaser.World. + * + * @method Phaser.Camera#boot + * @private + */ + boot: function () { + + this.displayObject = this.game.world; + + this.scale = this.game.world.scale; + + this.game.camera = this; + + if (Phaser.Graphics && Phaser.Camera.ENABLE_FX) + { + this.fx = new Phaser.Graphics(this.game); + + this.game.stage.addChild(this.fx); + } + + }, + + /** + * Camera preUpdate. Sets the total view counter to zero. + * + * @method Phaser.Camera#preUpdate + */ + preUpdate: function () { + + this.totalInView = 0; + + }, + + /** + * Tell the camera which sprite to follow. + * + * You can set the follow type and a linear interpolation value. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. + * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. + * + * @method Phaser.Camera#follow + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything. + * @param {number} [style] - Leverage one of the existing {@link deadzone} presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + */ + follow: function (target, style, lerpX, lerpY) { + + if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; } + if (lerpX === undefined) { lerpX = 1; } + if (lerpY === undefined) { lerpY = 1; } + + this.target = target; + this.lerp.set(lerpX, lerpY); + + var helper; + + switch (style) { + + case Phaser.Camera.FOLLOW_PLATFORMER: + var w = this.width / 8; + var h = this.height / 3; + this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN: + helper = Math.max(this.width, this.height) / 4; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT: + helper = Math.max(this.width, this.height) / 8; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_LOCKON: + this.deadzone = null; + break; + + default: + this.deadzone = null; + break; + } + + }, + + /** + * Sets the Camera follow target to null, stopping it from following an object if it's doing so. + * + * @method Phaser.Camera#unfollow + */ + unfollow: function () { + + this.target = null; + + }, + + /** + * Move the camera focus on a display object instantly. + * @method Phaser.Camera#focusOn + * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. + */ + focusOn: function (displayObject) { + + this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight)); + + }, + + /** + * Move the camera focus on a location instantly. + * @method Phaser.Camera#focusOnXY + * @param {number} x - X position. + * @param {number} y - Y position. + */ + focusOnXY: function (x, y) { + + this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight)); + + }, + + /** + * This creates a camera shake effect. It works by applying a random amount of additional + * spacing on the x and y axis each frame. You can control the intensity and duration + * of the effect, and if it should effect both axis or just one. + * + * When the shake effect ends the signal Camera.onShakeComplete is dispatched. + * + * @method Phaser.Camera#shake + * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. + * @param {number} [duration=500] - The duration of the shake effect in milliseconds. + * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL. + * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?). + * @return {boolean} True if the shake effect was started, otherwise false. + */ + shake: function (intensity, duration, force, direction, shakeBounds) { + + if (intensity === undefined) { intensity = 0.05; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = true; } + if (direction === undefined) { direction = Phaser.Camera.SHAKE_BOTH; } + if (shakeBounds === undefined) { shakeBounds = true; } + + if (!force && this._shake.duration > 0) + { + // Can't reset an already running shake + return false; + } + + this._shake.intensity = intensity; + this._shake.duration = duration; + this._shake.shakeBounds = shakeBounds; + + this._shake.x = 0; + this._shake.y = 0; + + this._shake.horizontal = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_HORIZONTAL); + this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL); + + return true; + + }, + + /** + * This creates a camera flash effect. It works by filling the game with the solid fill + * color specified, and then fading it away to alpha 0 over the duration given. + * + * You can use this for things such as hit feedback effects. + * + * When the effect ends the signal Camera.onFlashComplete is dispatched. + * + * @method Phaser.Camera#flash + * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the flash effect in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the flash effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + flash: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0xffffff; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 1; + + this._fxDuration = duration; + this._fxType = 0; + + return true; + + }, + + /** + * This creates a camera fade effect. It works by filling the game with the + * color specified, over the duration given, ending with a solid fill. + * + * You can use this for things such as transitioning to a new scene. + * + * The game will be left 'filled' at the end of this effect, likely obscuring + * everything. In order to reset it you can call `Camera.resetFX` and it will clear the + * fade. Or you can call `Camera.flash` with the same color as the fade, and it will + * reverse the process, bringing the game back into view again. + * + * When the effect ends the signal Camera.onFadeComplete is dispatched. + * + * @method Phaser.Camera#fade + * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the fade in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the fade effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + fade: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0x000000; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 0; + + this._fxDuration = duration; + this._fxType = 1; + + return true; + + }, + + /** + * The camera update loop. This is called automatically by the core game loop. + * + * @method Phaser.Camera#update + * @protected + */ + update: function () { + + if (this._fxDuration > 0) + { + this.updateFX(); + } + + if (this._shake.duration > 0) + { + this.updateShake(); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + this._shake.x = Math.floor(this._shake.x); + this._shake.y = Math.floor(this._shake.y); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the camera flash and fade effects. + * + * @method Phaser.Camera#updateFX + * @private + */ + updateFX: function () { + + if (this._fxType === 0) + { + // flash + this.fx.alpha -= this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha <= 0) + { + this._fxDuration = 0; + this.fx.alpha = 0; + this.onFlashComplete.dispatch(); + } + } + else + { + // fade + this.fx.alpha += this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha >= 1) + { + this._fxDuration = 0; + this.fx.alpha = 1; + this.onFadeComplete.dispatch(); + } + } + + }, + + /** + * Update the camera shake effect. + * + * @method Phaser.Camera#updateShake + * @private + */ + updateShake: function () { + + this._shake.duration -= this.game.time.elapsedMS; + + if (this._shake.duration <= 0) + { + this.onShakeComplete.dispatch(); + this._shake.x = 0; + this._shake.y = 0; + } + else + { + if (this._shake.horizontal) + { + this._shake.x = this.game.rnd.frac() * this._shake.intensity * this.view.width * 2 - this._shake.intensity * this.view.width; + } + + if (this._shake.vertical) + { + this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height; + } + } + + }, + + /** + * Internal method that handles tracking a sprite. + * + * @method Phaser.Camera#updateTarget + * @private + */ + updateTarget: function () { + + this._targetPosition.x = this.view.x + this.target.worldPosition.x; + this._targetPosition.y = this.view.y + this.target.worldPosition.y; + + if (this.deadzone) + { + this._edge = this._targetPosition.x - this.view.x; + + if (this._edge < this.deadzone.left) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.left, this.lerp.x); + } + else if (this._edge > this.deadzone.right) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.right, this.lerp.x); + } + + this._edge = this._targetPosition.y - this.view.y; + + if (this._edge < this.deadzone.top) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.top, this.lerp.y); + } + else if (this._edge > this.deadzone.bottom) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.bottom, this.lerp.y); + } + } + else + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.view.halfWidth, this.lerp.x); + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.view.halfHeight, this.lerp.y); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the Camera bounds to match the game world. + * + * @method Phaser.Camera#setBoundsToWorld + */ + setBoundsToWorld: function () { + + if (this.bounds) + { + this.bounds.copyFrom(this.game.world.bounds); + } + + }, + + /** + * Method called to ensure the camera doesn't venture outside of the game world. + * Called automatically by Camera.update. + * + * @method Phaser.Camera#checkBounds + * @protected + */ + checkBounds: function () { + + this.atLimit.x = false; + this.atLimit.y = false; + + var vx = this.view.x + this._shake.x; + var vw = this.view.right + this._shake.x; + var vy = this.view.y + this._shake.y; + var vh = this.view.bottom + this._shake.y; + + // Make sure we didn't go outside the cameras bounds + if (vx <= this.bounds.x * this.scale.x) + { + this.atLimit.x = true; + this.view.x = this.bounds.x * this.scale.x; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + else if (vw >= this.bounds.right * this.scale.x) + { + this.atLimit.x = true; + this.view.x = (this.bounds.right * this.scale.x) - this.width; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + + if (vy <= this.bounds.top * this.scale.y) + { + this.atLimit.y = true; + this.view.y = this.bounds.top * this.scale.y; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + else if (vh >= this.bounds.bottom * this.scale.y) + { + this.atLimit.y = true; + this.view.y = (this.bounds.bottom * this.scale.y) - this.height; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + + }, + + /** + * A helper function to set both the X and Y properties of the camera at once + * without having to use game.camera.x and game.camera.y. + * + * @method Phaser.Camera#setPosition + * @param {number} x - X position. + * @param {number} y - Y position. + */ + setPosition: function (x, y) { + + this.view.x = x; + this.view.y = y; + + if (this.bounds) + { + this.checkBounds(); + } + + }, + + /** + * Sets the size of the view rectangle given the width and height in parameters. + * + * @method Phaser.Camera#setSize + * @param {number} width - The desired width. + * @param {number} height - The desired height. + */ + setSize: function (width, height) { + + this.view.width = width; + this.view.height = height; + + }, + + /** + * Resets the camera back to 0,0 and un-follows any object it may have been tracking. + * Also immediately resets any camera effects that may have been running such as + * shake, flash or fade. + * + * @method Phaser.Camera#reset + */ + reset: function () { + + this.target = null; + + this.view.x = 0; + this.view.y = 0; + + this._shake.duration = 0; + this._shake.x = 0; + this._shake.y = 0; + + this.resetFX(); + + }, + + /** + * Resets any active FX, such as a fade or flash and immediately clears it. + * Useful to calling after a fade in order to remove the fade from the Stage. + * + * @method Phaser.Camera#resetFX + */ + resetFX: function () { + + if (this.fx) + { + this.fx.clear(); + this.fx.alpha = 0; + } + + this._fxDuration = 0; + + } + +}; + +Phaser.Camera.prototype.constructor = Phaser.Camera; + +/** +* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#x +* @property {number} x - Gets or sets the cameras x position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "x", { + + get: function () { + + return this.view.x; + + }, + + set: function (value) { + + this.view.x = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#y +* @property {number} y - Gets or sets the cameras y position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "y", { + + get: function () { + + return this.view.y; + + }, + + set: function (value) { + + this.view.y = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras position. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#position +* @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object. +*/ +Object.defineProperty(Phaser.Camera.prototype, "position", { + + get: function () { + + this._position.set(this.view.x, this.view.y); + + return this._position; + + }, + + set: function (value) { + + if (typeof value.x !== "undefined") { this.view.x = value.x; } + if (typeof value.y !== "undefined") { this.view.y = value.y; } + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras width. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#width +* @property {number} width - Gets or sets the cameras width. +*/ +Object.defineProperty(Phaser.Camera.prototype, "width", { + + get: function () { + + return this.view.width; + + }, + + set: function (value) { + + this.view.width = value; + + } + +}); + +/** +* The Cameras height. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#height +* @property {number} height - Gets or sets the cameras height. +*/ +Object.defineProperty(Phaser.Camera.prototype, "height", { + + get: function () { + + return this.view.height; + + }, + + set: function (value) { + + this.view.height = value; + + } + +}); + + +/** +* The Cameras shake intensity. +* @name Phaser.Camera#shakeIntensity +* @property {number} shakeIntensity - Gets or sets the cameras shake intensity. +*/ +Object.defineProperty(Phaser.Camera.prototype, "shakeIntensity", { + + get: function () { + + return this._shake.intensity; + + }, + + set: function (value) { + + this._shake.intensity = value; + + } + +}); + + +/** + * Immobile {@link #view} rectangle. Its top-left is always (0, 0). You can use this align fixedToCamera objects. + * @name Phaser.Camera#fixedView + * @property {Phaser.Rectangle} fixedView + * @readonly + */ +Object.defineProperty(Phaser.Camera.prototype, "fixedView", { + + get: function () { + + this._fixedView.setTo(0, 0, this.view.width, this.view.height); + + return this._fixedView; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base State class which can be extended if you are creating your own game. +* It provides quick access to common functions such as the camera, cache, input, match, sound and more. +* +* #### Callbacks +* +* | start | preload | loaded | paused | stop | +* |-------|-------------|------------|--------------|----------| +* | init | | | | | +* | | preload | create | paused | | +* | | loadUpdate* | update* | pauseUpdate* | | +* | | | preRender* | | | +* | | loadRender* | render* | render* | | +* | | | | resumed | | +* | | | | | shutdown | +* +* Update and render calls (*) are repeated. +* +* If your State has a constructor, it will be invoked exactly once, during {@link {@link Phaser.StateManager#add}. +* +* @class Phaser.State +* @constructor +*/ +Phaser.State = function () { + + /** + * @property {Phaser.Game} game - This is a reference to the currently running Game. + */ + this.game = null; + + /** + * @property {string} key - The string based identifier given to the State when added into the State Manager. + */ + this.key = ''; + + /** + * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects. + */ + this.make = null; + + /** + * @property {Phaser.Camera} camera - A handy reference to World.camera. + */ + this.camera = null; + + /** + * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - A reference to the Input Manager. + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions. + */ + this.math = null; + + /** + * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. + */ + this.sound = null; + + /** + * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays. + */ + this.scale = null; + + /** + * @property {Phaser.Stage} stage - A reference to the Stage. + */ + this.stage = null; + + /** + * @property {Phaser.StateManager} stage - A reference to the State Manager, which controls state changes. + */ + this.state = null; + + /** + * @property {Phaser.Time} time - A reference to the game clock and timed events system. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - A reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. + */ + this.world = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. + */ + this.particles = null; + + /** + * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser. + */ + this.physics = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator. + */ + this.rnd = null; + +}; + +Phaser.State.prototype = { + + /** + * init is the very first function called when your State starts up. It's called before preload, create or anything else. + * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables + * or objects before the preloading starts. + * + * @method Phaser.State#init + * @param {...any} args - Any extra arguments passed to {@link Phaser.StateManager#start} or {@link Phaser.StateManager#restart}. + */ + init: function () { + }, + + /** + * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) + * You shouldn't create any objects in this method that require assets that you're also loading in this method, as + * they won't yet be available. + * + * @method Phaser.State#preload + * @param {Phaser.Game} game + */ + preload: function () { + }, + + /** + * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * + * @method Phaser.State#loadUpdate + * @param {Phaser.Game} game + */ + loadUpdate: function () { + }, + + /** + * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. + * + * @method Phaser.State#loadRender + * @param {Phaser.Game} game + */ + loadRender: function () { + }, + + /** + * create is called once preload has completed, this includes the loading of any assets from the Loader. + * If you don't have a preload method then create is the first method called in your State. + * + * @method Phaser.State#create + * @param {Phaser.Game} game + */ + create: function () { + }, + + /** + * The update method is left empty for your own use. + * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. + * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. + * + * @method Phaser.State#update + * @param {Phaser.Game} game + */ + update: function () { + }, + + /** + * The preRender method is called after all Game Objects have been updated, but before any rendering takes place. + * + * @method Phaser.State#preRender + * @param {Phaser.Game} game + * @param {number} elapsedTime + */ + preRender: function () { + }, + + /** + * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. + * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any + * final post-processing style effects here. Note that this happens before plugins postRender takes place. + * + * @method Phaser.State#render + * @param {Phaser.Game} game + */ + render: function () { + }, + + /** + * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. + * + * @method Phaser.State#resize + * @param {number} width + * @param {number} height + */ + resize: function () { + }, + + /** + * This method will be called if the core game loop is paused. + * + * @method Phaser.State#paused + * @param {Phaser.Game} game + */ + paused: function () { + }, + + /** + * This method will be called when the core game loop resumes from a paused state. + * + * @method Phaser.State#resumed + * @param {Phaser.Game} game + */ + resumed: function () { + }, + + /** + * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. + * + * @method Phaser.State#pauseUpdate + * @param {Phaser.Game} game + */ + pauseUpdate: function () { + }, + + /** + * This method will be called when the State is shutdown (i.e. you switch to another state from this one). + * + * @method Phaser.State#shutdown + * @param {Phaser.Game} game + */ + shutdown: function () { + } + +}; + +Phaser.State.prototype.constructor = Phaser.State; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The State Manager is responsible for loading, setting up and switching game states. +* +* @class Phaser.StateManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. +*/ +Phaser.StateManager = function (game, pendingState) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {object} states - The object containing Phaser.States. + */ + this.states = {}; + + /** + * @property {Phaser.State} _pendingState - The state to be switched to in the next frame. + * @private + */ + this._pendingState = null; + + if (typeof pendingState !== 'undefined' && pendingState !== null) + { + this._pendingState = pendingState; + } + + /** + * @property {boolean} _clearWorld - Clear the world when we switch state? + * @private + */ + this._clearWorld = false; + + /** + * @property {boolean} _clearCache - Clear the cache when we switch state? + * @private + */ + this._clearCache = false; + + /** + * @property {boolean} _created - Flag that sets if the State has been created or not. + * @private + */ + this._created = false; + + /** + * @property {any[]} _args - Temporary container when you pass vars from one State to another. + * @private + */ + this._args = []; + + /** + * @property {string} current - The current active State object. + * @default + */ + this.current = ''; + + /** + * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. + * + * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start + * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states + * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. + * + * The callback you specify is sent two parameters: the string based key of the new state, + * and the second parameter is the string based key of the old / previous state. + * + * @property {Phaser.Signal} onStateChange + */ + this.onStateChange = new Phaser.Signal(); + + /** + * @property {function} onInitCallback - This is called when the state is set as the active state. + * @default + */ + this.onInitCallback = null; + + /** + * @property {function} onPreloadCallback - This is called when the state starts to load assets. + * @default + */ + this.onPreloadCallback = null; + + /** + * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins. + * @default + */ + this.onCreateCallback = null; + + /** + * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). + * @default + */ + this.onUpdateCallback = null; + + /** + * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). + * @default + */ + this.onRenderCallback = null; + + /** + * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. + * @default + */ + this.onResizeCallback = null; + + /** + * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. + * @default + */ + this.onPreRenderCallback = null; + + /** + * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase. + * @default + */ + this.onLoadUpdateCallback = null; + + /** + * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase. + * @default + */ + this.onLoadRenderCallback = null; + + /** + * @property {function} onPausedCallback - This is called when the game is paused. + * @default + */ + this.onPausedCallback = null; + + /** + * @property {function} onResumedCallback - This is called when the game is resumed from a paused state. + * @default + */ + this.onResumedCallback = null; + + /** + * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused. + * @default + */ + this.onPauseUpdateCallback = null; + + /** + * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state). + * @default + */ + this.onShutDownCallback = null; + +}; + +Phaser.StateManager.prototype = { + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * @method Phaser.StateManager#boot + * @private + */ + boot: function () { + + this.game.onPause.add(this.pause, this); + this.game.onResume.add(this.resume, this); + + if (this._pendingState !== null && typeof this._pendingState !== 'string') + { + this.add('default', this._pendingState, true); + } + + }, + + /** + * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. + * + * The State can be any of + * + * - a plain JavaScript object containing at least one required callback (see {@link #checkState}) + * - an instance of {@link Phaser.State} + * - an instance of a class extending Phaser.State + * - a constructor function (class) + * + * If a function is given a new state object will be created by calling it, passing the current {@link Phaser.Game game} as the first argument. + * + * @method Phaser.StateManager#add + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + * @param {Phaser.State|object|function} state - The state you want to switch to. + * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it. + */ + add: function (key, state, autoStart) { + + if (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; + + }, + + /** + * Delete the given state. + * @method Phaser.StateManager#remove + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + */ + 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.onPreRenderCallback = null; + this.onRenderCallback = null; + this.onResizeCallback = null; + this.onPausedCallback = null; + this.onResumedCallback = null; + this.onPauseUpdateCallback = null; + } + + delete this.states[key]; + + }, + + /** + * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. + * + * @method Phaser.StateManager#start + * @param {string} key - The key of the state you want to start. + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one). + */ + start: function (key, clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + if (this.checkState(key)) + { + // Place the state in the queue. It will be started the next time the game loop begins. + this._pendingState = key; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 3) + { + this._args = Array.prototype.splice.call(arguments, 3); + } + } + + }, + + /** + * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. + * + * @method Phaser.StateManager#restart + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one. + */ + restart: function (clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + // Place the state in the queue. It will be started the next time the game loop starts. + this._pendingState = this.current; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 2) + { + this._args = Array.prototype.slice.call(arguments, 2); + } + + }, + + /** + * Used by onInit and onShutdown when those functions don't exist on the state + * @method Phaser.StateManager#dummy + * @private + */ + dummy: function () { + }, + + /** + * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. + * + * @method Phaser.StateManager#preUpdate + */ + preUpdate: function () { + + if (this._pendingState && this.game.isBooted) + { + var previousStateKey = this.current; + + // Already got a state running? + this.clearCurrentState(); + + this.setCurrentState(this._pendingState); + + this.onStateChange.dispatch(this.current, previousStateKey); + + if (this.current !== this._pendingState) + { + return; + } + else + { + this._pendingState = null; + } + + // If StateManager.start has been called from the init of a State that ALSO has a preload, then + // onPreloadCallback will be set, but must be ignored + if (this.onPreloadCallback) + { + this.game.load.reset(true); + this.onPreloadCallback.call(this.callbackContext, this.game); + + // Is the loader empty? + if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0) + { + this.loadComplete(); + } + else + { + // Start the loader going as we have something in the queue + this.game.load.start(); + } + } + else + { + // No init? Then there was nothing to load either + this.loadComplete(); + } + } + + }, + + /** + * This method clears the current State, calling its shutdown callback. The process also removes any active tweens, + * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. + * + * @method Phaser.StateManager#clearCurrentState + */ + clearCurrentState: function () { + + if (this.current) + { + if (this.onShutDownCallback) + { + 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(); + + this.game.scale.reset(this._clearWorld); + + if (this.game.debug) + { + this.game.debug.reset(); + } + + if (this._clearWorld) + { + this.game.world.shutdown(); + + if (this._clearCache) + { + this.game.cache.destroy(); + } + } + } + + }, + + /** + * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. + * + * @method Phaser.StateManager#checkState + * @param {string} key - The key of the state you want to check. + * @return {boolean} true if the State has the required functions, otherwise false. + */ + checkState: function (key) { + + var state = this.states[key]; + + if (state) + { + if (state.preload || state.create || state.update || state.render) + { + return true; + } + else + { + console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"); + return false; + } + } + else + { + console.warn("Phaser.StateManager - No state found with the key: " + key); + return false; + } + + }, + + /** + * Links game properties to the State given by the key. + * + * @method Phaser.StateManager#link + * @param {string} key - State key. + * @protected + */ + link: function (key) { + + var state = this.states[key]; + + state.game = this.game; + state.add = this.game.add; + state.make = this.game.make; + state.camera = this.game.camera; + state.cache = this.game.cache; + state.input = this.game.input; + state.load = this.game.load; + state.math = this.game.math; + state.sound = this.game.sound; + state.scale = this.game.scale; + state.state = this; + state.stage = this.game.stage; + state.time = this.game.time; + state.tweens = this.game.tweens; + state.world = this.game.world; + state.particles = this.game.particles; + state.rnd = this.game.rnd; + state.physics = this.game.physics; + state.key = key; + + }, + + /** + * Nulls all State level Phaser properties, including a reference to Game. + * + * @method Phaser.StateManager#unlink + * @param {string} key - State key. + * @protected + */ + unlink: function (key) { + + var state = this.states[key]; + + if (state) + { + state.game = null; + state.add = null; + state.make = null; + state.camera = null; + state.cache = null; + state.input = null; + state.load = null; + state.math = null; + state.sound = null; + state.scale = null; + state.state = null; + state.stage = null; + state.time = null; + state.tweens = null; + state.world = null; + state.particles = null; + state.rnd = null; + state.physics = null; + } + + }, + + /** + * Sets the current State. Should not be called directly (use StateManager.start) + * + * @method Phaser.StateManager#setCurrentState + * @param {string} key - State key. + * @private + */ + setCurrentState: function (key) { + + var state = this.states[key]; + + this.callbackContext = state; + + this.link(key); + + // Used when the state is set as being the current active state + this.onInitCallback = state['init'] || this.dummy; + + this.onPreloadCallback = state['preload'] || null; + this.onLoadRenderCallback = state['loadRender'] || null; + this.onLoadUpdateCallback = state['loadUpdate'] || null; + this.onCreateCallback = state['create'] || null; + this.onUpdateCallback = state['update'] || null; + this.onPreRenderCallback = state['preRender'] || null; + this.onRenderCallback = state['render'] || null; + this.onResizeCallback = state['resize'] || null; + this.onPausedCallback = state['paused'] || null; + this.onResumedCallback = state['resumed'] || null; + this.onPauseUpdateCallback = state['pauseUpdate'] || null; + + // Used when the state is no longer the current active state + this.onShutDownCallback = state['shutdown'] || this.dummy; + + // Reset the physics system, but not on the first state start + if (this.current !== '') + { + this.game.physics.reset(); + } + + this.current = key; + this._created = false; + + // At this point key and pendingState should equal each other + this.onInitCallback.apply(this.callbackContext, this._args); + + // If they no longer do then the init callback hit StateManager.start + if (key === this._pendingState) + { + this._args = []; + } + + this.game._kickstart = true; + + }, + + /** + * Gets the current State. + * + * @method Phaser.StateManager#getCurrentState + * @return {Phaser.State} + * @public + */ + getCurrentState: function() { + return this.states[this.current]; + }, + + /** + * @method Phaser.StateManager#loadComplete + * @protected + */ + loadComplete: function () { + + // Make sure to do load-update one last time before state is set to _created + if (this._created === false && this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + + if (this._created === false && this.onCreateCallback) + { + this._created = true; + this.onCreateCallback.call(this.callbackContext, this.game); + } + else + { + this._created = true; + } + + }, + + /** + * @method Phaser.StateManager#pause + * @protected + */ + pause: function () { + + if (this._created && this.onPausedCallback) + { + this.onPausedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#resume + * @protected + */ + resume: function () { + + if (this._created && this.onResumedCallback) + { + this.onResumedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#update + * @protected + */ + update: function () { + + if (this._created) + { + if (this.onUpdateCallback) + { + this.onUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#pauseUpdate + * @protected + */ + pauseUpdate: function () { + + if (this._created) + { + if (this.onPauseUpdateCallback) + { + this.onPauseUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#preRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + preRender: function (elapsedTime) { + + if (this._created && this.onPreRenderCallback) + { + this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime); + } + + }, + + /** + * @method Phaser.StateManager#resize + * @protected + */ + resize: function (width, height) { + + if (this.onResizeCallback) + { + this.onResizeCallback.call(this.callbackContext, width, height); + } + + }, + + /** + * @method Phaser.StateManager#render + * @protected + */ + render: function () { + + if (this._created) + { + if (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); + this.game.context.restore(); + } + else + { + this.onRenderCallback.call(this.callbackContext, this.game); + } + } + } + else + { + if (this.onLoadRenderCallback) + { + this.onLoadRenderCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. + * You don't recover from this without rebuilding the Phaser instance again. + * @method Phaser.StateManager#destroy + */ + destroy: function () { + + this._clearWorld = true; + this._clearCache = true; + + this.clearCurrentState(); + + 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; + this.current = ''; + + } + +}; + +Phaser.StateManager.prototype.constructor = Phaser.StateManager; + +/** +* @name Phaser.StateManager#created +* @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default). +* @readOnly +*/ +Object.defineProperty(Phaser.StateManager.prototype, "created", { + + get: function () { + + return this._created; + + } + +}); + +/** +* "It's like nailing jelly to a kitten" - Gary Penn +*/ + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Signals are what Phaser uses to handle events and event dispatching. +* You can listen for a Signal by binding a callback / function to it. +* This is done by using either `Signal.add` or `Signal.addOnce`. +* +* For example you can listen for a touch or click event from the Input Manager +* by using its `onDown` Signal: +* +* `game.input.onDown.add(function() { ... });` +* +* Rather than inline your function, you can pass a reference: +* +* `game.input.onDown.add(clicked, this);` +* `function clicked () { ... }` +* +* In this case the second argument (`this`) is the context in which your function should be called. +* +* Now every time the InputManager dispatches the `onDown` signal (or event), your function +* will be called. +* +* Multiple callbacks can be bound to the same signal. +* They're ordered first by their `priority` arguments and then by the order in which they were added. +* If a callback calls {@link #halt} or returns `false`, any remaining callbacks are skipped. +* +* Very often a Signal will send arguments to your function. +* This is specific to the Signal itself. +* If you're unsure then check the documentation, or failing that simply do: +* +* `Signal.add(function() { console.log(arguments); })` +* +* and it will log all of the arguments your function received from the Signal. +* +* Sprites have lots of default signals you can listen to in their Events class, such as: +* +* `sprite.events.onKilled` +* +* Which is called automatically whenever the Sprite is killed. +* There are lots of other events, see the Events component for a list. +* +* As well as listening to pre-defined Signals you can also create your own: +* +* `var mySignal = new Phaser.Signal();` +* +* This creates a new Signal. You can bind a callback to it: +* +* `mySignal.add(myCallback, this);` +* +* and then finally when ready you can dispatch the Signal: +* +* `mySignal.dispatch(your arguments);` +* +* And your callback will be invoked. See the dispatch method for more details. +* +* @class Phaser.Signal +* @constructor +*/ +Phaser.Signal = function () {}; + +Phaser.Signal.prototype = { + + /** + * @property {?Array.} _bindings - Internal variable. + * @private + */ + _bindings: null, + + /** + * @property {any} _prevParams - Internal variable. + * @private + */ + _prevParams: null, + + /** + * Memorize the previously dispatched event? + * + * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}. + * Use {@link #forget} to clear any currently memorized event. + * + * @property {boolean} memorize + */ + memorize: false, + + /** + * @property {boolean} _shouldPropagate + * @private + */ + _shouldPropagate: true, + + /** + * Is the Signal active? Only active signals will broadcast dispatched events. + * + * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}. + * + * @property {boolean} active + * @default + */ + active: true, + + /** + * @property {function} _boundDispatch - The bound dispatch function, if any. + * @private + */ + _boundDispatch: false, + + /** + * @method Phaser.Signal#validateListener + * @param {function} listener - Signal handler function. + * @param {string} fnName - Function name. + * @private + */ + validateListener: function (listener, fnName) { + + if (typeof listener !== 'function') + { + throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); + } + + }, + + /** + * @method Phaser.Signal#_registerListener + * @private + * @param {function} listener - Signal handler function. + * @param {boolean} isOnce - Should the listener only be called once? + * @param {object} [listenerContext] - The context under which the listener is invoked. + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + _registerListener: function (listener, isOnce, listenerContext, priority, args) { + + var prevIndex = this._indexOfListener(listener, listenerContext); + var binding; + + if (prevIndex !== -1) + { + binding = this._bindings[prevIndex]; + + if (binding.isOnce() !== isOnce) + { + throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); + } + } + else + { + binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args); + this._addBinding(binding); + } + + if (this.memorize && this._prevParams) + { + binding.execute(this._prevParams); + } + + return binding; + + }, + + /** + * @method Phaser.Signal#_addBinding + * @private + * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. + */ + _addBinding: function (binding) { + + if (!this._bindings) + { + this._bindings = []; + } + + // Simplified insertion sort + var n = this._bindings.length; + + do { + n--; + } + while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); + + this._bindings.splice(n + 1, 0, binding); + + }, + + /** + * @method Phaser.Signal#_indexOfListener + * @private + * @param {function} listener - Signal handler function. + * @param {object} [context=null] - Signal handler function. + * @return {number} The index of the listener within the private bindings array. + */ + _indexOfListener: function (listener, context) { + + if (!this._bindings) + { + return -1; + } + + if (context === undefined) { context = null; } + + var n = this._bindings.length; + var cur; + + while (n--) + { + cur = this._bindings[n]; + + if (cur._listener === listener && cur.context === context) + { + return n; + } + } + + return -1; + + }, + + /** + * Check if a specific listener is attached. + * + * @method Phaser.Signal#has + * @param {function} listener - Signal handler function. + * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @return {boolean} If Signal has the specified listener. + */ + has: function (listener, context) { + + return this._indexOfListener(listener, context) !== -1; + + }, + + /** + * Add an event listener for this signal. + * + * An event listener is a callback with a related context and priority. + * + * You can optionally provide extra arguments which will be passed to the callback after any internal parameters. + * + * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. + * Any arguments you've specified after `priority` will be sent as well: + * + * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` + * + * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. + * + * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', + * and the value 100 were the custom arguments given in the call to 'add'. + * + * If the callback calls {@link #halt} or returns `false`, any remaining callbacks bound to this Signal are skipped. + * + * @method Phaser.Signal#add + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + add: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'add'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, false, listenerContext, priority, args); + + }, + + /** + * Add a one-time listener - the listener is automatically removed after the first execution. + * + * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and + * the listener will be removed immediately. + * + * @method Phaser.Signal#addOnce + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + addOnce: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'addOnce'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, true, listenerContext, priority, args); + + }, + + /** + * Remove a single event listener. + * + * @method Phaser.Signal#remove + * @param {function} listener - Handler function that should be removed. + * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {function} Listener handler function. + */ + remove: function (listener, context) { + + this.validateListener(listener, 'remove'); + + var i = this._indexOfListener(listener, context); + + if (i !== -1) + { + this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal + this._bindings.splice(i, 1); + } + + return listener; + + }, + + /** + * Remove all event listeners. + * + * @method Phaser.Signal#removeAll + * @param {object} [context=null] - If specified only listeners for the given context will be removed. + */ + removeAll: function (context) { + + if (context === undefined) { context = null; } + + if (!this._bindings) + { + return; + } + + var n = this._bindings.length; + + while (n--) + { + if (context) + { + if (this._bindings[n].context === context) + { + this._bindings[n]._destroy(); + this._bindings.splice(n, 1); + } + } + else + { + this._bindings[n]._destroy(); + } + } + + if (!context) + { + this._bindings.length = 0; + } + + }, + + /** + * Gets the total number of listeners attached to this Signal. + * + * @method Phaser.Signal#getNumListeners + * @return {integer} Number of listeners attached to the Signal. + */ + getNumListeners: function () { + + return this._bindings ? this._bindings.length : 0; + + }, + + /** + * Stop propagation of the event, blocking the dispatch to next listener on the queue. + * + * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. + * See {@link #active} to enable/disable the signal entirely. + * + * @method Phaser.Signal#halt + */ + halt: function () { + + this._shouldPropagate = false; + + }, + + /** + * Dispatch / broadcast the event to all listeners. + * + * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}. + * + * @method Phaser.Signal#dispatch + * @param {any} [params] - Parameters that should be passed to each handler. + */ + dispatch: function () { + + if (!this.active || !this._bindings) + { + return; + } + + var paramsArr = Array.prototype.slice.call(arguments); + var n = this._bindings.length; + var bindings; + + if (this.memorize) + { + this._prevParams = paramsArr; + } + + if (!n) + { + // Should come after memorize + return; + } + + bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch + this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. + + //execute all callbacks until end of the list or until a callback returns `false` or stops propagation + //reverse loop since listeners with higher priority will be added at the end of the list + do { + n--; + } + while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); + + }, + + /** + * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any. + * + * @method Phaser.Signal#forget + */ + forget: function() { + + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * Dispose the signal - no more events can be dispatched. + * + * This removes all event listeners and clears references to external objects. + * Calling methods on a disposed objects results in undefined behavior. + * + * @method Phaser.Signal#dispose + */ + dispose: function () { + + this.removeAll(); + + this._bindings = null; + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * A string representation of the object. + * + * @method Phaser.Signal#toString + * @return {string} String representation of the object. + */ + toString: function () { + + return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']'; + + } + +}; + +/** +* Create a `dispatch` function that maintains a binding to the original Signal context. +* +* Use the resulting value if the dispatch function needs to be passed somewhere +* or called independently of the Signal object. +* +* @memberof Phaser.Signal +* @property {function} boundDispatch +*/ +Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", { + + get: function () { + var _this = this; + return this._boundDispatch || (this._boundDispatch = function () { + return _this.dispatch.apply(_this, arguments); + }); + } + +}); + +Phaser.Signal.prototype.constructor = Phaser.Signal; + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Object that represents a binding between a Signal and a listener function. +* This is an internal constructor and shouldn't be created directly. +* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. +* +* @class Phaser.SignalBinding +* @constructor +* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to. +* @param {function} listener - Handler function bound to the signal. +* @param {boolean} isOnce - If binding should be executed just once. +* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). +* @param {number} [priority] - The priority level of the event listener. (default = 0). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. +*/ +Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) { + + /** + * @property {Phaser.Game} _listener - Handler function bound to the signal. + * @private + */ + this._listener = listener; + + if (isOnce) + { + this._isOnce = true; + } + + if (listenerContext != null) /* not null/undefined */ + { + this.context = listenerContext; + } + + /** + * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to. + * @private + */ + this._signal = signal; + + if (priority) + { + this._priority = priority; + } + + if (args && args.length) + { + this._args = args; + } + +}; + +Phaser.SignalBinding.prototype = { + + /** + * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + */ + context: null, + + /** + * @property {boolean} _isOnce - If binding should be executed just once. + * @private + */ + _isOnce: false, + + /** + * @property {number} _priority - Listener priority. + * @private + */ + _priority: 0, + + /** + * @property {array} _args - Listener arguments. + * @private + */ + _args: null, + + /** + * @property {number} callCount - The number of times the handler function has been called. + */ + callCount: 0, + + /** + * If binding is active and should be executed. + * @property {boolean} active + * @default + */ + active: true, + + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). + * @property {array|null} params + * @default + */ + params: null, + + /** + * Call listener passing arbitrary parameters. + * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. + * @method Phaser.SignalBinding#execute + * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener. + * @return {any} Value returned by the listener. + */ + execute: function(paramsArr) { + + var handlerReturn, params; + + if (this.active && !!this._listener) + { + params = this.params ? this.params.concat(paramsArr) : paramsArr; + + if (this._args) + { + params = params.concat(this._args); + } + + handlerReturn = this._listener.apply(this.context, params); + + this.callCount++; + + if (this._isOnce) + { + this.detach(); + } + } + + return handlerReturn; + + }, + + /** + * Detach binding from signal. + * alias to: @see mySignal.remove(myBinding.getListener()); + * @method Phaser.SignalBinding#detach + * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ + detach: function () { + return this.isBound() ? this._signal.remove(this._listener, this.context) : null; + }, + + /** + * @method Phaser.SignalBinding#isBound + * @return {boolean} True if binding is still bound to the signal and has a listener. + */ + isBound: function () { + return (!!this._signal && !!this._listener); + }, + + /** + * @method Phaser.SignalBinding#isOnce + * @return {boolean} If SignalBinding will only be executed once. + */ + isOnce: function () { + return this._isOnce; + }, + + /** + * @method Phaser.SignalBinding#getListener + * @return {function} Handler function bound to the signal. + */ + getListener: function () { + return this._listener; + }, + + /** + * @method Phaser.SignalBinding#getSignal + * @return {Phaser.Signal} Signal that listener is currently bound to. + */ + getSignal: function () { + return this._signal; + }, + + /** + * Delete instance properties + * @method Phaser.SignalBinding#_destroy + * @private + */ + _destroy: function () { + delete this._signal; + delete this._listener; + delete this.context; + }, + + /** + * @method Phaser.SignalBinding#toString + * @return {string} String representation of the object. + */ + toString: function () { + return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']'; + } + +}; + +Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding; + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Filter class to use for any Phaser filter development. +* If you want to make a custom filter, this should be your base class. +* +* The default uniforms, types and values for all Filters are: +* +* ```javascript +* resolution: { type: '2f', value: { x: 256, y: 256 }} +* time: { type: '1f', value: 0 } +* mouse: { type: '2f', value: { x: 0.0, y: 0.0 } } +* date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] } +* sampleRate: { type: '1f', value: 44100.0 } +* iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* ``` +* +* The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and +* therefore only work in WebGL and are not supported by Canvas at all. +* +* @class Phaser.Filter +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [uniforms] - Uniform mappings object. The uniforms are added on the default uniforms, or replace them if the keys are the same. +* @param {Array|string} [fragmentSrc] - The fragment shader code. Either an array, one element per line of code, or a string. +*/ +Phaser.Filter = function (game, uniforms, fragmentSrc) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. + * @default + */ + this.type = Phaser.WEBGL_FILTER; + + /** + * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. + * For example the blur filter has two passes blurX and blurY. + * @property {array} passes - An array of filter objects. + * @private + */ + this.passes = [ this ]; + + /** + * @property {array} shaders - Array an array of shaders. + * @private + */ + this.shaders = []; + + /** + * @property {boolean} dirty - Internal PIXI var. + * @default + */ + this.dirty = true; + + /** + * @property {number} padding - Internal PIXI var. + * @default + */ + this.padding = 0; + + /** + * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same) + */ + this.prevPoint = new Phaser.Point(); + + /* + * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D. + */ + + var d = new Date(); + + /** + * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. + */ + this.uniforms = { + + resolution: { type: '2f', value: { x: 256, y: 256 }}, + time: { type: '1f', value: 0 }, + mouse: { type: '2f', value: { x: 0.0, y: 0.0 } }, + date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, + sampleRate: { type: '1f', value: 44100.0 }, + iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + + }; + + // Copy over / replace any passed in the constructor + if (uniforms) + { + for (var key in uniforms) + { + this.uniforms[key] = uniforms[key]; + } + } + + // If fragmentSrc is a string, split it based on new-lines into an array + if (typeof fragmentSrc === 'string') + { + fragmentSrc = fragmentSrc.split('\n'); + } + + /** + * @property {array|string} fragmentSrc - The fragment shader code. + */ + this.fragmentSrc = fragmentSrc || []; + +}; + +Phaser.Filter.prototype = { + + /** + * This should be over-ridden. Will receive a variable number of arguments. + * + * @method Phaser.Filter#init + */ + init: function () { + + // This should be over-ridden. Will receive a variable number of arguments. + + }, + + /** + * Set the resolution uniforms on the filter. + * + * @method Phaser.Filter#setResolution + * @param {number} width - The width of the display. + * @param {number} height - The height of the display. + */ + setResolution: function (width, height) { + + this.uniforms.resolution.value.x = width; + this.uniforms.resolution.value.y = height; + + }, + + /** + * Updates the filter. + * + * @method Phaser.Filter#update + * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. + */ + update: function (pointer) { + + if (pointer) + { + var x = pointer.x / this.game.width; + var y = 1 - pointer.y / this.game.height; + + if (x !== this.prevPoint.x || y !== this.prevPoint.y) + { + this.uniforms.mouse.value.x = x.toFixed(2); + this.uniforms.mouse.value.y = y.toFixed(2); + this.prevPoint.set(x, y); + } + } + + this.uniforms.time.value = this.game.time.totalElapsedSeconds(); + + }, + + /** + * Creates a new Phaser.Image object using a blank texture and assigns + * this Filter to it. The image is then added to the world. + * + * If you don't provide width and height values then Filter.width and Filter.height are used. + * + * If you do provide width and height values then this filter will be resized to match those + * values. + * + * @method Phaser.Filter#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. + * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, width, height, anchorX, anchorY) { + + if (anchorX === undefined) { anchorX = 0; } + if (anchorY === undefined) { anchorY = 0; } + + if (width !== undefined && width !== null) + { + this.width = width; + } + else + { + width = this.width; + } + + if (height !== undefined && height !== null) + { + this.height = height; + } + else + { + height = this.height; + } + + var image = this.game.add.image(x, y, Phaser.Cache.DEFAULT); + + image.width = width; + image.height = height; + + image.anchor.set(anchorX, anchorY); + + image.filters = [ this ]; + + return image; + + }, + + /** + * Syncs the uniforms between the class object and the shaders. + * + * @method Phaser.Filter#syncUniforms + */ + syncUniforms: function () { + + for (var i = 0; i < this.shaders.length; i++) + { + this.shaders[i].dirty = true; + } + + }, + + /** + * Clear down this Filter and null out references to game. + * + * @method Phaser.Filter#destroy + */ + destroy: function () { + + this.passes.length = 0; + this.shaders.length = 0; + this.fragmentSrc.length = 0; + + this.game = null; + this.uniforms = null; + this.prevPoint = null; + + } + +}; + +Phaser.Filter.prototype.constructor = Phaser.Filter; + +/** +* @name Phaser.Filter#width +* @property {number} width - The width (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'width', { + + get: function () { + + return this.uniforms.resolution.value.x; + + }, + + set: function (value) { + + this.uniforms.resolution.value.x = value; + + } + +}); + +/** +* @name Phaser.Filter#height +* @property {number} height - The height (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'height', { + + get: function () { + + return this.uniforms.resolution.value.y; + + }, + + set: function (value) { + + this.uniforms.resolution.value.y = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Plugin template to use for any Phaser plugin development. +* +* ##### Callbacks +* +* add | active | visible | remove +* -----|-------------|-------------|-------- +* init | | | +* | preUpdate* | | +* | update* | render* | +* | postUpdate* | postRender* | +* | | | destroy +* +* Update and render calls are repeated (*). +* +* @class Phaser.Plugin +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager. +*/ +Phaser.Plugin = function (game, parent) { + + if (parent === undefined) { parent = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. + */ + this.parent = parent; + + /** + * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. + * @default + */ + this.active = false; + + /** + * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. + * @default + */ + this.visible = false; + + /** + * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. + * @default + */ + this.hasPreUpdate = false; + + /** + * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. + * @default + */ + this.hasUpdate = false; + + /** + * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. + * @default + */ + this.hasPostUpdate = false; + + /** + * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. + * @default + */ + this.hasRender = false; + + /** + * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. + * @default + */ + this.hasPostRender = false; + +}; + +Phaser.Plugin.prototype = { + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It is only called if active is set to true. + * @method Phaser.Plugin#preUpdate + */ + preUpdate: function () { + }, + + /** + * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It is only called if active is set to true. + * @method Phaser.Plugin#update + */ + update: function () { + }, + + /** + * Render is called right after the Game Renderer completes, but before the State.render. + * It is only called if visible is set to true. + * @method Phaser.Plugin#render + */ + render: function () { + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It is only called if visible is set to true. + * @method Phaser.Plugin#postRender + */ + postRender: function () { + }, + + /** + * Clear down this Plugin and null out references + * @method Phaser.Plugin#destroy + */ + destroy: function () { + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + + } + +}; + +Phaser.Plugin.prototype.constructor = Phaser.Plugin; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. +* +* @class Phaser.PluginManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.PluginManager = function(game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager. + */ + this.plugins = []; + + /** + * @property {number} _len - Internal cache var. + * @private + */ + this._len = 0; + + /** + * @property {number} _i - Internal cache var. + * @private + */ + this._i = 0; + +}; + +Phaser.PluginManager.prototype = { + + /** + * Add a new Plugin into the PluginManager. + * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.PluginManager#add + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + add: function (plugin) { + + var args = Array.prototype.slice.call(arguments, 1); + var result = false; + + // Prototype? + if (typeof plugin === 'function') + { + plugin = new plugin(this.game, this); + } + else + { + plugin.game = this.game; + plugin.parent = this; + } + + // Check for methods now to avoid having to do this every loop + 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; + } + + // The plugin must have at least one of the above functions to be added to the PluginManager. + 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); + + // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager + if (typeof plugin['init'] === 'function') + { + plugin.init.apply(plugin, args); + } + + return plugin; + } + else + { + return null; + } + }, + + /** + * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. + * + * @method Phaser.PluginManager#remove + * @param {Phaser.Plugin} plugin - The plugin to be removed. + * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed? + */ + remove: function (plugin, destroy) { + + if (destroy === undefined) { destroy = true; } + + this._i = this._len; + + while (this._i--) + { + if (this.plugins[this._i] === plugin) + { + if (destroy) + { + plugin.destroy(); + } + + this.plugins.splice(this._i, 1); + this._len--; + return; + } + } + + }, + + /** + * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. + * + * @method Phaser.PluginManager#removeAll + */ + removeAll: function() { + + this._i = this._len; + + while (this._i--) + { + this.plugins[this._i].destroy(); + } + + this.plugins.length = 0; + this._len = 0; + + }, + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#preUpdate + */ + 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 is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#update + */ + 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 is the last thing to be called before the world render. + * In particular, it is called after the world postUpdate, which means the camera has been adjusted. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#postUpdate + */ + 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 is called right after the Game Renderer completes, but before the State.render. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#render + */ + 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(); + } + } + + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#postRender + */ + 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(); + } + } + + }, + + /** + * Clear down this PluginManager, calls destroy on every plugin and nulls out references. + * + * @method Phaser.PluginManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.game = null; + + } + +}; + +Phaser.PluginManager.prototype.constructor = Phaser.PluginManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Stage controls root level display objects upon which everything is displayed. +* It also handles browser visibility handling and the pausing due to loss of focus. +* +* @class Phaser.Stage +* @extends PIXI.DisplayObjectContainer +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Stage = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {string} name - The name of this object. + * @default + */ + this.name = '_stage_root'; + + /** + * By default if the browser tab loses focus the game will pause. + * You can stop that behavior by setting this property to true. + * Note that the browser can still elect to pause your game if it wishes to do so, + * for example swapping to another browser tab. This will cause the RAF callback to halt, + * effectively pausing your game, even though no in-game pause event is triggered if you enable this property. + * @property {boolean} disableVisibilityChange + * @default + */ + this.disableVisibilityChange = false; + + /** + * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. + * @default + */ + this.exists = true; + + /** + * @property {Phaser.Matrix} worldTransform - Current transform of the object based on world (parent) factors + * @private + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage) + * @private + * @readOnly + */ + this.stage = this; + + /** + * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. + */ + this.currentRenderOrderID = 0; + + /** + * @property {string} hiddenVar - The page visibility API event name. + * @private + */ + this._hiddenVar = 'hidden'; + + /** + * @property {function} _onChange - The blur/focus event handler. + * @private + */ + this._onChange = null; + + /** + * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor. + * @private + */ + this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' }; + + if (!this.game.transparent) + { + // transparent = 0,0,0,0 - otherwise r,g,b,1 + this._bgColor.a = 1; + } + + if (game.config) + { + this.parseConfig(game.config); + } + +}; + +Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Stage.prototype.constructor = Phaser.Stage; + +/** +* Parses a Game configuration object. +* +* @method Phaser.Stage#parseConfig +* @protected +* @param {object} config -The configuration object to parse. +*/ +Phaser.Stage.prototype.parseConfig = function (config) { + + if (config['disableVisibilityChange']) + { + this.disableVisibilityChange = config['disableVisibilityChange']; + } + + if (config['backgroundColor']) + { + this.setBackgroundColor(config['backgroundColor']); + } + +}; + +/** +* Initialises the stage and adds the event listeners. +* @method Phaser.Stage#boot +* @private +*/ +Phaser.Stage.prototype.boot = function () { + + Phaser.DOM.getOffset(this.game.canvas, this.offset); + + Phaser.Canvas.setUserSelect(this.game.canvas, 'none'); + Phaser.Canvas.setTouchAction(this.game.canvas, 'none'); + + this.checkVisibility(); + +}; + +/** +* This is called automatically after the plugins preUpdate and before the State.update. +* Most objects have preUpdate methods and it's where initial movement and positioning is done. +* +* @method Phaser.Stage#preUpdate +*/ +Phaser.Stage.prototype.preUpdate = function () { + + this.currentRenderOrderID = 0; + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + +}; + +/** +* This is called automatically after the State.update, but before particles or plugins update. +* +* @method Phaser.Stage#update +*/ +Phaser.Stage.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + this.children[i].update(); + } + +}; + +/** +* This is called automatically before the renderer runs and after the plugins have updated. +* In postUpdate this is where all the final physics calculations and object positioning happens. +* The objects are processed in the order of the display list. +* +* @method Phaser.Stage#postUpdate +*/ +Phaser.Stage.prototype.postUpdate = function () { + + // Apply the camera shake, fade, bounds, etc + this.game.camera.update(); + + // Camera target first? + if (this.game.camera.target) + { + this.game.camera.target.postUpdate(); + + this.updateTransform(); + + this.game.camera.updateTarget(); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + this.updateTransform(); + +}; + +/** +* Updates the transforms for all objects on the display list. +* This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. +* +* @method Phaser.Stage#updateTransform +*/ +Phaser.Stage.prototype.updateTransform = function () { + + this.worldAlpha = 1; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +/** +* Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. +* Also listens for window.onblur and window.onfocus. +* +* @method Phaser.Stage#checkVisibility +*/ +Phaser.Stage.prototype.checkVisibility = function () { + + if (document.hidden !== undefined) + { + this._hiddenVar = 'visibilitychange'; + } + else if (document.webkitHidden !== undefined) + { + this._hiddenVar = 'webkitvisibilitychange'; + } + else if (document.mozHidden !== undefined) + { + this._hiddenVar = 'mozvisibilitychange'; + } + else if (document.msHidden !== undefined) + { + this._hiddenVar = 'msvisibilitychange'; + } + else + { + this._hiddenVar = null; + } + + var _this = this; + + this._onChange = function (event) { + return _this.visibilityChange(event); + }; + + this._onClick = function (event) { + if ((document.hasFocus !== undefined) && !document.hasFocus()) + { + _this.visibilityChange(event); + } + }; + + // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus + if (this._hiddenVar) + { + document.addEventListener(this._hiddenVar, this._onChange, false); + } + + window.onblur = this._onChange; + window.onfocus = this._onChange; + + window.onpagehide = this._onChange; + window.onpageshow = this._onChange; + + window.addEventListener('click', this._onClick); + + if (this.game.device.cocoonJSApp) + { + CocoonJS.App.onSuspended.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" }); + }); + + CocoonJS.App.onActivated.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" }); + }); + } + +}; + +/** +* This method is called when the document visibility is changed. +* +* - `blur` and `pagehide` events trigger {@link Phaser.Game#onBlur}. They {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `click`, `focus`, and `pageshow` trigger {@link Phaser.Game#onFocus}. They {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (hidden) and CocoonJS's `onSuspended` {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (visible) and CocoonJS's `onActivated` {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* +* @method Phaser.Stage#visibilityChange +* @param {Event} event - Its type will be used to decide whether the game should be paused or not. +*/ +Phaser.Stage.prototype.visibilityChange = function (event) { + + // These events always trigger the Game#onBlur or Game#onFocus signals. + + switch (event.type) + { + case 'blur': + case 'pagehide': + this.game.focusLoss(event); + return; + case 'click': + case 'focus': + case 'pageshow': + this.game.focusGain(event); + return; + } + + if (this.disableVisibilityChange) + { + return; + } + + if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause") + { + this.game.gamePaused(event); + } + else + { + this.game.gameResumed(event); + } + +}; + +/** +* Sets the background color for the Stage. +* +* The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). +* +* An alpha channel is _not_ supported and will be ignored. +* +* If you've set your game to be {@link Phaser.Game#transparent transparent} then calls to setBackgroundColor are ignored. +* +* If {@link Phaser.Game#clearBeforeRender} is off then the background color won't appear. +* +* @method Phaser.Stage#setBackgroundColor +* @param {number|string} color - The color of the background. +*/ +Phaser.Stage.prototype.setBackgroundColor = function (color) { + + if (this.game.transparent) { return; } + + Phaser.Color.valueToColor(color, this._bgColor); + Phaser.Color.updateColor(this._bgColor); + + // For gl.clearColor (canvas uses _bgColor.rgba) + this._bgColor.r /= 255; + this._bgColor.g /= 255; + this._bgColor.b /= 255; + this._bgColor.a = 1; + +}; + +/** +* Destroys the Stage and removes event listeners. +* +* @method Phaser.Stage#destroy +*/ +Phaser.Stage.prototype.destroy = function () { + + if (this._hiddenVar) + { + document.removeEventListener(this._hiddenVar, this._onChange, false); + } + + window.onpagehide = null; + window.onpageshow = null; + + window.onblur = null; + window.onfocus = null; + + window.removeEventListener('click', this._onClick); + +}; + +/** +* Adds an existing object to the Stage. +* +* The child is automatically added to the front of the Stage, and is displayed above every previous child. +* Or if the _optional_ `index` is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the object was already on the Stage, it is simply returned, and nothing else happens to it. +* +* @method Phaser.Stage#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent] - Unused. Kept for compatibility with {@link Phaser.Group#add}. +* @param {integer} [index] - The index to insert the object to. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Stage.prototype.add = function (child, silent, index) { + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + this.addChild(child); + } + else + { + this.addChildAt(child, index); + } + + return child; + +}; + +/** +* @name Phaser.Stage#backgroundColor +* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' +* @see Phaser.Stage#setBackgroundColor +*/ +Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", { + + get: function () { + + return this._bgColor.color; + + }, + + set: function (color) { + + this.setBackgroundColor(color); + + } + +}); + +/** +* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. +* +* @name Phaser.Stage#smoothed +* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) +*/ +Object.defineProperty(Phaser.Stage.prototype, "smoothed", { + + get: function () { + + return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR; + + }, + + set: function (value) { + + if (value) + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR; + } + else + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}. +* +* Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. +* For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. +* +* In addition, Groups provides support for fast pooling and object recycling. +* +* Groups are also display objects and can be nested as children within other Groups. +* +* @class Phaser.Group +* @extends PIXI.DisplayObjectContainer +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to. +* If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent. +* @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World. +* @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}. +* @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values. +*/ +Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) { + + if (addToStage === undefined) { addToStage = false; } + if (enableBody === undefined) { enableBody = false; } + if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + if (parent === undefined) + { + parent = game.world; + } + + /** + * A name for this group. Not used internally but useful for debugging. + * @property {string} name + */ + this.name = name || 'group'; + + /** + * The z-depth value of this object within its parent container/Group - the World is a Group as well. + * This value must be unique for each child in a Group. + * @property {integer} z + * @readOnly + */ + this.z = 0; + + PIXI.DisplayObjectContainer.call(this); + + if (addToStage) + { + this.game.stage.addChild(this); + this.z = this.game.stage.children.length; + } + else + { + if (parent) + { + parent.addChild(this); + this.z = parent.children.length; + } + } + + /** + * Internal Phaser Type value. + * @property {integer} type + * @protected + */ + this.type = Phaser.GROUP; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. + * @property {boolean} alive + * @default + */ + this.alive = true; + + /** + * If exists is false the group will be excluded from collision checks and filters such as {@link #forEachExists}. The group will not call `preUpdate` and `postUpdate` on its children and the children will not receive physics updates or camera/world boundary checks. The group will still be {@link #visible} and will still call `update` on its children (unless {@link #updateOnlyExistingChildren} is true). + * @property {boolean} exists + * @default + */ + this.exists = true; + + /** + * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. + * @property {boolean} ignoreDestroy + * @default + */ + this.ignoreDestroy = false; + + /** + * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method + * called on the next logic update. + * You can set it directly to flag the Group to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy a Group from within one of its own callbacks + * or a callback of one of its children. + * + * @property {boolean} pendingDestroy + */ + this.pendingDestroy = false; + + /** + * The type of objects that will be created when using {@link #create} or {@link #createMultiple}. + * + * It should extend either Sprite or Image and accept the same constructor arguments: `(game, x, y, key, frame)`. + * + * @property {function} classType + * @default {@link Phaser.Sprite} + */ + this.classType = Phaser.Sprite; + + /** + * The current display object that the group cursor is pointing to, if any. (Can be set manually.) + * + * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}. + * @property {?DisplayObject} cursor + */ + this.cursor = null; + + /** + * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` + * on any children _added_ to, or _created by_, this Group. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * @property {boolean} inputEnableChildren + * @default + */ + this.inputEnableChildren = false; + + /** + * Skip children with `exists = false` in {@link #update}. + * + * @property {boolean} updateOnlyExistingChildren + * @default + */ + this.updateOnlyExistingChildren = false; + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputDown + */ + this.onChildInputDown = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, + * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer + * is still over the Sprite or not. + * + * @property {Phaser.Signal} onChildInputUp + */ + this.onChildInputUp = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOver + */ + this.onChildInputOver = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOut + */ + this.onChildInputOut = new Phaser.Signal(); + + /** + * If true all Sprites created by, or added to this group, will have a physics body enabled on them. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * The default body type is controlled with {@link #physicsBodyType}. + * @property {boolean} enableBody + */ + this.enableBody = enableBody; + + /** + * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well. + * + * This only works for P2 bodies. + * @property {boolean} enableBodyDebug + * @default + */ + this.enableBodyDebug = false; + + /** + * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites. + * + * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc. + * @property {integer} physicsBodyType + */ + this.physicsBodyType = physicsBodyType; + + /** + * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. + * + * It should be set to one of the Phaser.Physics.Arcade sort direction constants: + * + * Phaser.Physics.Arcade.SORT_NONE + * Phaser.Physics.Arcade.LEFT_RIGHT + * Phaser.Physics.Arcade.RIGHT_LEFT + * Phaser.Physics.Arcade.TOP_BOTTOM + * Phaser.Physics.Arcade.BOTTOM_TOP + * + * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. + * + * @property {integer} physicsSortDirection + * @default + */ + this.physicsSortDirection = null; + + /** + * This signal is dispatched when the group is destroyed. + * @property {Phaser.Signal} onDestroy + */ + this.onDestroy = new Phaser.Signal(); + + /** + * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next. + * @readOnly + */ + this.cursorIndex = 0; + + /** + * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. + * + * Note that the cameraOffset values are in addition to any parent in the display list. + * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x + * + * @property {boolean} fixedToCamera + */ + this.fixedToCamera = false; + + /** + * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view. + * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. + * @property {Phaser.Point} cameraOffset + */ + this.cameraOffset = new Phaser.Point(); + + /** + * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. + * + * Only children of this Group can be added to and removed from the hash. + * + * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. + * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own + * sorting and filtering of Group children without touching their z-index (and therefore display draw order) + * + * @property {array} hash + */ + this.hash = []; + + /** + * The property on which children are sorted. + * @property {string} _sortProperty + * @private + */ + this._sortProperty = 'z'; + +}; + +Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Group.prototype.constructor = Phaser.Group; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_NONE = 0; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_TOTAL = 1; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_CHILD = 2; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_ALL = 3; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_ASCENDING = -1; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_DESCENDING = 1; + +/** +* Adds an existing object as the top child in this group. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the child was already in this Group, it is simply returned, and nothing else happens to it. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* Use {@link #create} to create and add a new child. +* +* @method Phaser.Group#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.add = function (child, silent, index) { + + if (silent === undefined) { silent = false; } + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + child.z = this.children.length; + + this.addChild(child); + } + else + { + this.addChildAt(child, index); + + this.updateZ(); + } + + if (this.enableBody && child.hasOwnProperty('body') && child.body === null) + { + this.game.physics.enable(child, this.physicsBodyType); + } + else if (child.body) + { + this.addToHash(child); + } + + if (this.inputEnableChildren && (!child.input || child.inputEnabled)) + { + child.inputEnabled = true; + } + + if (!silent && child.events) + { + child.events.onAddedToGroup$dispatch(child, this); + } + + if (this.cursor === null) + { + this.cursor = child; + } + + return child; + +}; + +/** +* Adds an existing object to this group. +* +* The child is added to the group at the location specified by the index value, this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#addAt +* @param {DisplayObject} child - The display object to add as a child. +* @param {integer} [index=0] - The index within the group to insert the child to. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.addAt = function (child, index, silent) { + + return this.add(child, silent, index); + +}; + +/** +* Adds a child of this Group into the hash array. +* This call will return false if the child is not a child of this Group, or is already in the hash. +* +* @method Phaser.Group#addToHash +* @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. +* @return {boolean} True if the child was successfully added to the hash, otherwise false. +*/ +Phaser.Group.prototype.addToHash = function (child) { + + if (child.parent === this) + { + var index = this.hash.indexOf(child); + + if (index === -1) + { + this.hash.push(child); + return true; + } + } + + return false; + +}; + +/** +* Removes a child of this Group from the hash array. +* This call will return false if the child is not in the hash. +* +* @method Phaser.Group#removeFromHash +* @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash. +* @return {boolean} True if the child was successfully removed from the hash, otherwise false. +*/ +Phaser.Group.prototype.removeFromHash = function (child) { + + if (child) + { + var index = this.hash.indexOf(child); + + if (index !== -1) + { + this.hash.splice(index, 1); + return true; + } + } + + return false; + +}; + +/** +* Adds an array of existing Display Objects to this Group. +* +* The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. +* +* As well as an array you can also pass another Group as the first argument. In this case all of the children from that +* Group will be removed from it and added into this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#addMultiple +* @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group. +*/ +Phaser.Group.prototype.addMultiple = function (children, silent) { + + if (children instanceof Phaser.Group) + { + children.moveAll(this, silent); + } + else if (Array.isArray(children)) + { + for (var i = 0; i < children.length; i++) + { + this.add(children[i], silent); + } + } + + return children; + +}; + +/** +* Returns the child found at the given index within this group. +* +* @method Phaser.Group#getAt +* @param {integer} index - The index to return the child from. +* @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index. +*/ +Phaser.Group.prototype.getAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + return -1; + } + else + { + return this.getChildAt(index); + } + +}; + +/** +* Creates a new Phaser.Sprite object and adds it to the top of this group. +* +* Use {@link #classType} to change the type of object created. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#create +* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. +* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {boolean} [exists=true] - The default exists state of the Sprite. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed. +*/ +Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) { + + if (exists === undefined) { exists = true; } + + var child = new this.classType(this.game, x, y, key, frame); + + child.exists = exists; + child.visible = exists; + child.alive = exists; + + return this.add(child, false, index); + +}; + +/** +* Creates multiple Phaser.Sprite objects and adds them to the top of this Group. +* +* This method is useful if you need to quickly generate a pool of sprites, such as bullets. +* +* Use {@link #classType} to change the type of object created. +* +* You can provide an array as the `key` and / or `frame` arguments. When you do this +* it will create `quantity` Sprites for every key (and frame) in the arrays. +* +* For example: +* +* `createMultiple(25, ['ball', 'carrot'])` +* +* In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be +* created in total, 25 of each. You can also have the `frame` as an array: +* +* `createMultiple(5, 'bricks', [0, 1, 2, 3])` +* +* In the above there is one key (bricks), which is a sprite sheet. The frames array tells +* this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because +* the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with +* frame 1, and so on. +* +* If you set both the key and frame arguments to be arrays then understand it will create +* a total quantity of sprites equal to the size of both arrays times each other. I.e.: +* +* `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` +* +* The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. +* It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. +* In total it will have created 120 sprites. +* +* By default the Sprites will have their `exists` property set to `false`, and they will be +* positioned at 0x0, relative to the `Group.x / y` values. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#createMultiple +* @param {integer} quantity - The number of Sprites to create. +* @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. +* @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. +* @param {boolean} [exists=false] - The default exists state of the Sprite. +* @param {function} [callback] - The function that will be called for each applicable child. It will be passed the new child and the loop index (0 through quantity - 1). +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). The default context is the new child. +* @return {array} An array containing all of the Sprites that were created. +*/ +Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, callback, callbackContext) { + + if (frame === undefined) { frame = 0; } + if (exists === undefined) { exists = false; } + + if (!Array.isArray(key)) + { + key = [ key ]; + } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + + var _this = this; + var children = []; + + key.forEach(function(singleKey) { + + frame.forEach(function(singleFrame) { + + for (var i = 0; i < quantity; i++) + { + var child = _this.create(0, 0, singleKey, singleFrame, exists); + + if (callback) { callback.call(callbackContext || child, child, i); } + + children.push(child); + } + + }); + + }); + + return children; + +}; + +/** +* Internal method that re-applies all of the children's Z values. +* +* This must be called whenever children ordering is altered so that their `z` indices are correctly updated. +* +* @method Phaser.Group#updateZ +* @protected +*/ +Phaser.Group.prototype.updateZ = function () { + + var i = this.children.length; + + while (i--) + { + this.children[i].z = i; + } + +}; + +/** +* This method iterates through all children in the Group (regardless if they are visible or exist) +* and then changes their position so they are arranged in a Grid formation. Children must have +* the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have +* this. +* +* The grid dimensions are determined by the first four arguments. The `width` and `height` arguments +* relate to the width and height of the grid respectively. +* +* For example if the Group had 100 children in it: +* +* `Group.align(10, 10, 32, 32)` +* +* This will align all of the children into a grid formation of 10x10, using 32 pixels per +* grid cell. If you want a wider grid, you could do: +* +* `Group.align(25, 4, 32, 32)` +* +* This will align the children into a grid of 25x4, again using 32 pixels per grid cell. +* +* You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method +* to keep on aligning children until there are no children left. For example if this Group had +* 48 children in it, the following: +* +* `Group.align(-1, 8, 32, 32)` +* +* ... will align the children so that there are 8 children vertically (the second argument), +* and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) +* +* You can also do: +* +* `Group.align(10, -1, 32, 32)` +* +* In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit +* all of the children in. +* +* The `position` property allows you to control where in each grid cell the child is positioned. +* This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, +* `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, +* `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* +* The final argument; `offset` lets you start the alignment from a specific child index. +* +* @method Phaser.Group#align +* @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. +* @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. +* @param {integer} cellWidth - The width of each grid cell, in pixels. +* @param {integer} cellHeight - The height of each grid cell, in pixels. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. +* @return {boolean} True if the Group children were aligned, otherwise false. +*/ +Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, position, offset) { + + if (position === undefined) { position = Phaser.TOP_LEFT; } + if (offset === undefined) { offset = 0; } + + if (this.children.length === 0 || offset > this.children.length || (width === -1 && height === -1)) + { + return false; + } + + var r = new Phaser.Rectangle(0, 0, cellWidth, cellHeight); + var w = (width * cellWidth); + var h = (height * cellHeight); + + for (var i = offset; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child['alignIn']) + { + child.alignIn(r, position); + } + else + { + continue; + } + + if (width === -1) + { + // We keep laying them out horizontally until we've done them all + r.y += cellHeight; + + if (r.y === h) + { + r.x += cellWidth; + r.y = 0; + } + } + else if (height === -1) + { + // We keep laying them out vertically until we've done them all + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + } + } + else + { + // We keep laying them out until we hit the column limit + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + + if (r.y === h) + { + // We've hit the column limit, so return, even if there are children left + return true; + } + } + } + } + + return true; + +}; + +/** +* Sets the group cursor to the first child in the group. +* +* If the optional index parameter is given it sets the cursor to the object at that index instead. +* +* @method Phaser.Group#resetCursor +* @param {integer} [index=0] - Set the cursor to point to a specific index. +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.resetCursor = function (index) { + + if (index === undefined) { index = 0; } + + if (index > this.children.length - 1) + { + index = 0; + } + + if (this.cursor) + { + this.cursorIndex = index; + this.cursor = this.children[this.cursorIndex]; + return this.cursor; + } + +}; + +/** +* Advances the group cursor to the next (higher) object in the group. +* +* If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). +* +* @method Phaser.Group#next +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.next = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex >= this.children.length - 1) + { + this.cursorIndex = 0; + } + else + { + this.cursorIndex++; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Moves the group cursor to the previous (lower) child in the group. +* +* If the cursor is at the start of the group (bottom child) it is moved to the end (top child). +* +* @method Phaser.Group#previous +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.previous = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex === 0) + { + this.cursorIndex = this.children.length - 1; + } + else + { + this.cursorIndex--; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Swaps the position of two children in this group. +* +* Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. +* +* @method Phaser.Group#swap +* @param {any} child1 - The first child to swap. +* @param {any} child2 - The second child to swap. +*/ +Phaser.Group.prototype.swap = function (child1, child2) { + + this.swapChildren(child1, child2); + this.updateZ(); + +}; + +/** +* Brings the given child to the top of this group so it renders above all other children. +* +* @method Phaser.Group#bringToTop +* @param {any} child - The child to bring to the top of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.bringToTop = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length) + { + this.remove(child, false, true); + this.add(child, true); + } + + return child; + +}; + +/** +* Sends the given child to the bottom of this group so it renders below all other children. +* +* @method Phaser.Group#sendToBack +* @param {any} child - The child to send to the bottom of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.sendToBack = function (child) { + + if (child.parent === this && this.getIndex(child) > 0) + { + this.remove(child, false, true); + this.addAt(child, 0, true); + } + + return child; + +}; + +/** +* Moves the given child up one place in this group unless it's already at the top. +* +* @method Phaser.Group#moveUp +* @param {any} child - The child to move up in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveUp = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length - 1) + { + var a = this.getIndex(child); + var b = this.getAt(a + 1); + + if (b) + { + this.swap(child, b); + } + } + + return child; + +}; + +/** +* Moves the given child down one place in this group unless it's already at the bottom. +* +* @method Phaser.Group#moveDown +* @param {any} child - The child to move down in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveDown = 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; + +}; + +/** +* Positions the child found at the given index within this group to the given x and y coordinates. +* +* @method Phaser.Group#xy +* @param {integer} index - The index of the child in the group to set the position of. +* @param {number} x - The new x position of the child. +* @param {number} y - The new y position of the 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; + } + +}; + +/** +* Reverses all children in this group. +* +* This operation applies only to immediate children and does not propagate to subgroups. +* +* @method Phaser.Group#reverse +*/ +Phaser.Group.prototype.reverse = function () { + + this.children.reverse(); + this.updateZ(); + +}; + +/** +* Get the index position of the given child in this group, which should match the child's `z` property. +* +* @method Phaser.Group#getIndex +* @param {any} child - The child to get the index for. +* @return {integer} The index of the child or -1 if it's not a member of this group. +*/ +Phaser.Group.prototype.getIndex = function (child) { + + return this.children.indexOf(child); + +}; + +/** +* Searches the Group for the first instance of a child with the `name` +* property matching the given argument. Should more than one child have +* the same name only the first instance is returned. +* +* @method Phaser.Group#getByName +* @param {string} name - The name to search for. +* @return {any} The first child with a matching name, or null if none were found. +*/ +Phaser.Group.prototype.getByName = function (name) { + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].name === name) + { + return this.children[i]; + } + } + + return null; + +}; + +/** +* Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#replace +* @param {any} oldChild - The child in this group that will be replaced. +* @param {any} newChild - The child to be inserted into this group. +* @return {any} Returns the oldChild that was replaced within this group. +*/ +Phaser.Group.prototype.replace = function (oldChild, newChild) { + + var index = this.getIndex(oldChild); + + if (index !== -1) + { + if (newChild.parent) + { + if (newChild.parent instanceof Phaser.Group) + { + newChild.parent.remove(newChild); + } + else + { + newChild.parent.removeChild(newChild); + } + } + + this.remove(oldChild); + + this.addAt(newChild, index); + + return oldChild; + } + +}; + +/** +* Checks if the child has the given property. +* +* Will scan up to 4 levels deep only. +* +* @method Phaser.Group#hasProperty +* @param {any} child - The child to check for the existence of the property on. +* @param {string[]} key - An array of strings that make up the property. +* @return {boolean} True if the child has the property, otherwise false. +*/ +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; + +}; + +/** +* Sets a property to the given value on the child. The operation parameter controls how the value is set. +* +* The operations are: +* - 0: set the existing value to the given value; if force is `true` a new property will be created if needed +* - 1: will add the given value to the value already present. +* - 2: will subtract the given value from the value already present. +* - 3: will multiply the value already present by the given value. +* - 4: will divide the value already present by the given value. +* +* @method Phaser.Group#setProperty +* @param {any} child - The child to set the property value on. +* @param {array} key - An array of strings that make up the property that will be set. +* @param {any} value - The value that will be set. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) { + + if (force === undefined) { force = false; } + + operation = operation || 0; + + // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration. + + // 0 = Equals + // 1 = Add + // 2 = Subtract + // 3 = Multiply + // 4 = Divide + + // We can't force a property in and the child doesn't have it, so abort. + // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too. + 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; + +}; + +/** +* Checks a property for the given value on the child. +* +* @method Phaser.Group#checkProperty +* @param {any} child - The child to check the property value on. +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} True if `child` is a child of this Group and the property was equal to value, false if not. +*/ +Phaser.Group.prototype.checkProperty = function (child, key, value, force) { + + if (force === undefined) { force = false; } + + if (this !== child.parent) + { + return false; + } + + var result = Phaser.Utils.getProperty(child, key); + + if (((result === undefined) && force) || (result !== value)) + { + return false; + } + + return true; + +}; + +/** +* Quickly set a property on a single child of this group to a new value. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#set +* @param {Phaser.Sprite} child - The child to set the property on. +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true. +* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) { + + if (force === undefined) { force = false; } + + key = key.split('.'); + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible))) + { + return this.setProperty(child, key, value, operation, force); + } + +}; + +/** +* Quickly set the same property across all children of this group to a new value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. +* If you need that ability please see `Group.setAllChildren`. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAll +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + key = key.split('.'); + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + this.setProperty(this.children[i], key, value, operation, force); + } + } + +}; + +/** +* Quickly set the same property across all children of this group, and any child Groups, to a new value. +* +* If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. +* Unlike with `setAll` the property is NOT set on child Groups itself. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAllChildren +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + if (this.children[i] instanceof Phaser.Group) + { + this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force); + } + else + { + this.setProperty(this.children[i], key.split('.'), value, operation, force); + } + } + } + +}; + +/** +* Test that the same property across all children of this group is equal to the given value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAll +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} - True if all eligible children have the given property value (but see `force`); otherwise false. +*/ +Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (!this.checkProperty(child, key, value, force)) + { + return false; + } + } + } + + return true; + +}; + +/** +* Test that at least one child of this group has the given property value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAny +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @return {boolean} - True if at least one eligible child has the given property value; otherwise false. +*/ +Phaser.Group.prototype.checkAny = function (key, value, checkAlive, checkVisible) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (this.checkProperty(child, key, value)) + { + return true; + } + } + } + + return false; + +}; + +/** +* Adds the amount to the given property on all children in this group. +* +* `Group.addAll('x', 10)` will add 10 to the child.x value for each child. +* +* @method Phaser.Group#addAll +* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. +* @param {boolean} [checkAlive] - If true the property will only be changed if the child is alive. +* @param {boolean} [checkVisible] - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 1); + +}; + +/** +* Subtracts the amount from the given property on all children in this group. +* +* `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. +* +* @method Phaser.Group#subAll +* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 2); + +}; + +/** +* Multiplies the given property by the amount on all children in this group. +* +* `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. +* +* @method Phaser.Group#multiplyAll +* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 3); + +}; + +/** +* Divides the given property by the amount on all children in this group. +* +* `Group.divideAll('x', 2)` will half the child.x value for each child. +* +* @method Phaser.Group#divideAll +* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 4); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to false. + * + * @method Phaser.Group#kill + */ +Phaser.Group.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + +}; + +/** + * Kills all children having exists=true. + * + * @method Phaser.Group#killAll + */ +Phaser.Group.prototype.killAll = function () { + + this.callAllExists('kill', true); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to true. + * + * @method Phaser.Group#revive + */ +Phaser.Group.prototype.revive = function () { + + this.alive = true; + this.exists = true; + this.visible = true; + +}; + +/** + * Revives all children having exists=false. + * + * @method Phaser.Group#reviveAll + */ +Phaser.Group.prototype.reviveAll = function () { + + this.callAllExists('revive', false); + +}; + +/** +* Calls {@link #resetChild} on each child (or each existing child). +* +* @method Phaser.Group#resetAll +* @param {number} [x] - The x coordinate to reset each child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset each child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image or texture used by the Sprite during rendering. +* @param {string|number} [frame] - The frame of a sprite sheet or texture atlas. +* @param {boolean} [checkExists=false] - Reset only existing children. +*/ +Phaser.Group.prototype.resetAll = function (x, y, key, frame, checkExists) { + + this.forEach(this.resetChild, this, checkExists, x, y, key, frame); + +}; + +/** +* Calls a function, specified by name, on all children in the group who exist (or do not exist). +* +* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. +* +* @method Phaser.Group#callAllExists +* @param {string} callback - Name of the function on the children to call. +* @param {boolean} existsValue - Only children with exists=existsValue will be called. +* @param {...any} parameter - Additional parameters that will be passed to the callback. +*/ +Phaser.Group.prototype.callAllExists = function (callback, existsValue) { + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].exists === existsValue && this.children[i][callback]) + { + this.children[i][callback].apply(this.children[i], args); + } + } + +}; + +/** +* Returns a reference to a function that exists on a child of the group based on the given callback array. +* +* @method Phaser.Group#callbackFromArray +* @param {object} child - The object to inspect. +* @param {array} callback - The array of function names. +* @param {integer} length - The size of the array (pre-calculated in callAll). +* @protected +*/ +Phaser.Group.prototype.callbackFromArray = function (child, callback, length) { + + // Kinda looks like a Christmas tree + + if (length === 1) + { + if (child[callback[0]]) + { + return child[callback[0]]; + } + } + else if (length === 2) + { + if (child[callback[0]][callback[1]]) + { + return child[callback[0]][callback[1]]; + } + } + else if (length === 3) + { + if (child[callback[0]][callback[1]][callback[2]]) + { + return child[callback[0]][callback[1]][callback[2]]; + } + } + else if (length === 4) + { + if (child[callback[0]][callback[1]][callback[2]][callback[3]]) + { + return child[callback[0]][callback[1]][callback[2]][callback[3]]; + } + } + else if (child[callback]) + { + return child[callback]; + } + + return false; + +}; + +/** +* Calls a function, specified by name, on all on children. +* +* The function is called for all children regardless if they are dead or alive (see callAllExists for different options). +* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. +* +* @method Phaser.Group#callAll +* @param {string} method - Name of the function on the child to call. Deep property lookup is supported. +* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child. +* @param {...any} args - Additional parameters that will be passed to the method. +*/ +Phaser.Group.prototype.callAll = function (method, context) { + + if (method === undefined) + { + return; + } + + // Extract the method into an array + method = method.split('.'); + + var methodLength = method.length; + + if (context === undefined || context === null || context === '') + { + context = null; + } + else + { + // Extract the context into an array + if (typeof context === 'string') + { + context = context.split('.'); + var contextLength = context.length; + } + } + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + var callback = null; + var callbackContext = null; + + for (var i = 0; i < this.children.length; i++) + { + callback = this.callbackFromArray(this.children[i], method, methodLength); + + if (context && callback) + { + callbackContext = this.callbackFromArray(this.children[i], context, contextLength); + + if (callback) + { + callback.apply(callbackContext, args); + } + } + else if (callback) + { + callback.apply(this.children[i], args); + } + } + +}; + +/** +* The core preUpdate - as called by World. +* @method Phaser.Group#preUpdate +* @protected +*/ +Phaser.Group.prototype.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + // This chunk is identical to Phaser.Component.Core.prototype.preUpdateChildren, which is not yet defined. + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + return true; + +}; + +/** +* The core update - as called by World. +* +* Children with `exists = false` are updated unless {@link #updateOnlyExistingChildren} is true. +* +* @method Phaser.Group#update +* @protected +*/ +Phaser.Group.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + var len = this.children.length; + + if (i >= len) { i = len - 1; } + + var child = this.children[i]; + + if (!this.updateOnlyExistingChildren || child.exists) { + child.update(); + } + } + +}; + +/** +* The core postUpdate - as called by World. +* @method Phaser.Group#postUpdate +* @protected +*/ +Phaser.Group.prototype.postUpdate = function () { + + // Fixed to Camera? + if (this.fixedToCamera) + { + this.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; + this.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Find children matching a certain predicate. +* +* For example: +* +* var healthyList = Group.filter(function(child, index, children) { +* return child.health > 10 ? true : false; +* }, true); +* healthyList.callAll('attack'); +* +* Note: Currently this will skip any children which are Groups themselves. +* +* @method Phaser.Group#filter +* @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third +* @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. +* @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for +*/ +Phaser.Group.prototype.filter = function (predicate, checkExists) { + + var index = -1; + var length = this.children.length; + var results = []; + + while (++index < length) + { + var child = this.children[index]; + + if (!checkExists || (checkExists && child.exists)) + { + if (predicate(child, index, this.children)) + { + results.push(child); + } + } + } + + return new Phaser.ArraySet(results); + +}; + +/** +* Call a function on each child in this group. +* +* Additional arguments for the callback can be specified after the `checkExists` parameter. For example, +* +* Group.forEach(awardBonusGold, this, true, 100, 500) +* +* would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. +* +* Note: This check will skip any children which are Groups themselves. +* +* @method Phaser.Group#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) { + + if (checkExists === undefined) { checkExists = false; } + + if (arguments.length <= 3) + { + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + callback.call(callbackContext, this.children[i]); + } + } + } + else + { + // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE. + // Using an array and pushing each element (not a slice!) is _significantly_ faster. + var args = [null]; + + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + } + } + +}; + +/** +* Call a function on each existing child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachExists +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachExists = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each alive child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachAlive +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each dead child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachDead +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachDead = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Sort the children in the group according to a particular key and ordering. +* +* Call this function to sort the group according to a particular key value and order. +* +* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. +* +* Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including +* alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. +* +* @method Phaser.Group#sort +* @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value. +* @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}). +*/ +Phaser.Group.prototype.sort = function (key, order) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + if (key === undefined) { key = 'z'; } + if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; } + + this._sortProperty = key; + + if (order === Phaser.Group.SORT_ASCENDING) + { + this.children.sort(this.ascendingSortHandler.bind(this)); + } + else + { + this.children.sort(this.descendingSortHandler.bind(this)); + } + + this.updateZ(); + +}; + +/** +* Sort the children in the group according to custom sort function. +* +* The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). +* It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. +* +* @method Phaser.Group#customSort +* @param {function} sortHandler - The custom sort function. +* @param {object} [context=undefined] - The context in which the sortHandler is called. +*/ +Phaser.Group.prototype.customSort = function (sortHandler, context) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + this.children.sort(sortHandler.bind(context)); + + this.updateZ(); + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#ascendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.ascendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return -1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return 1; + } + else + { + if (a.z < b.z) + { + return -1; + } + else + { + return 1; + } + } + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#descendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.descendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return 1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return -1; + } + else + { + return 0; + } + +}; + +/** +* Iterates over the children of the group performing one of several actions for matched children. +* +* A child is considered a match when it has a property, named `key`, whose value is equal to `value` +* according to a strict equality comparison. +* +* The result depends on the `returnType`: +* +* - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}: +* The callback, if any, is applied to all matching children. The number of matched children is returned. +* - {@link Phaser.Group.RETURN_NONE RETURN_NONE}: +* The callback, if any, is applied to all matching children. No value is returned. +* - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}: +* The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. +* If there is no matching child then null is returned. +* +* If `args` is specified it must be an array. The matched child will be assigned to the first +* element and the entire array will be applied to the callback function. +* +* @method Phaser.Group#iterate +* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' +* @param {any} value - A child matches if `child[key] === value` is true. +* @param {integer} returnType - How to iterate the children and what to return. +* @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. +* @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null. +*/ +Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) { + + if (this.children.length === 0) + { + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return 0; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return []; + } + } + + var total = 0; + + if (returnType === Phaser.Group.RETURN_ALL) + { + var output = []; + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i][key] === value) + { + total++; + + if (callback) + { + if (args) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + else + { + callback.call(callbackContext, this.children[i]); + } + } + + if (returnType === Phaser.Group.RETURN_CHILD) + { + return this.children[i]; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + output.push(this.children[i]); + } + } + } + + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return total; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return output; + } + else + { + // RETURN_CHILD or RETURN_NONE + return null; + } + +}; + +/** +* Get the first display object with the given property name and value. +* +* @method Phaser.Group#getFirst +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {DisplayObject} The first child matching the query, or `null` if none were found. +*/ +Phaser.Group.prototype.getFirst = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_CHILD); + +}; + +/** +* Get the first display object that exists, or doesn't exist. +* +* You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstExists +* @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child. +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + if (typeof exists !== 'boolean') + { + exists = true; + } + + var child = this.getFirst('exists', exists); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is alive (`child.alive === true`). +* +* This is handy for choosing a squad leader, etc. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstAlive +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', true); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is dead (`child.alive === false`). +* +* This is handy for checking if everything has been wiped out and adding to the pool as needed. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstDead +* @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', false); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. +* +* If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. +* +* The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. +* +* @method Phaser.Group#resetChild +* @param {DisplayObject} child - The child to reset and/or load the texture on. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}. +*/ +Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) { + + if (child === null) + { + return null; + } + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (x !== null && y !== null) + { + child.reset(x, y); + } + + if (key !== undefined) + { + child.loadTexture(key, frame); + } + + return child; + +}; + +/** +* Return the child at the top of this group. +* +* The top child is the child displayed (rendered) above every other child. +* +* @method Phaser.Group#getTop +* @return {any} The child at the top of the Group. +*/ +Phaser.Group.prototype.getTop = function () { + + if (this.children.length > 0) + { + return this.children[this.children.length - 1]; + } + +}; + +/** +* Returns the child at the bottom of this group. +* +* The bottom child the child being displayed (rendered) below every other child. +* +* @method Phaser.Group#getBottom +* @return {any} The child at the bottom of the Group. +*/ +Phaser.Group.prototype.getBottom = function () { + + if (this.children.length > 0) + { + return this.children[0]; + } + +}; + +/** +* Get the closest child to given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getClosestTo +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child closest to given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContext) { + + var distance = Number.MAX_VALUE; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance < distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the child furthest away from the given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getFurthestFrom +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child furthest from the given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackContext) { + + var distance = 0; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance > distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the number of children with the given property name and value. +* +* @method Phaser.Group#count +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {integer} The number of children matching the query. +*/ +Phaser.Group.prototype.count = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_TOTAL); + +}; + +/** +* Get the number of living children in this group. +* +* @method Phaser.Group#countLiving +* @return {integer} The number of children flagged as alive. +*/ +Phaser.Group.prototype.countLiving = function () { + + return this.count('alive', true); + +}; + +/** +* Get the number of dead children in this group. +* +* @method Phaser.Group#countDead +* @return {integer} The number of children flagged as dead. +*/ +Phaser.Group.prototype.countDead = function () { + + return this.count('alive', false); + +}; + +/** +* Returns a random child from the group. +* +* @method Phaser.Group#getRandom +* @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). +* @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. +* @return {any} A random child of this Group. +*/ +Phaser.Group.prototype.getRandom = function (startIndex, length) { + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = this.children.length; } + + if (length === 0) + { + return null; + } + + return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length); + +}; + +/** +* Returns a random child from the Group that has `exists` set to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only +* the first 50 children in the Group. +* +* @method Phaser.Group#getRandomExists +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up to. +* @return {any} A random child of this Group that exists. +*/ +Phaser.Group.prototype.getRandomExists = function (startIndex, endIndex) { + + var list = this.getAll('exists', true, startIndex, endIndex); + + return this.game.rnd.pick(list); + +}; + +/** +* Returns all children in this Group. +* +* You can optionally specify a matching criteria using the `property` and `value` arguments. +* +* For example: `getAll('exists', true)` would return only children that have an `exists` property equal to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return the first 50 children in the Group. +* If `property` and `value` are also specified, only children within the given index range are searched. +* +* @method Phaser.Group#getAll +* @param {string} [property] - An optional property to test against the value argument. +* @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results. +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up until. +* @return {array} - An array containing all, some, or none of the Children of this Group. +*/ +Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) { + + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var output = []; + + for (var i = startIndex; i < endIndex; i++) + { + var child = this.children[i]; + + if (property) + { + if (child[property] === value) + { + output.push(child); + } + } + else + { + output.push(child); + } + } + + return output; + +}; + +/** +* Removes the given child from this group. +* +* This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. +* +* If the group cursor was referring to the removed child it is updated to refer to the next child. +* +* @method Phaser.Group#remove +* @param {any} child - The child to remove. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child. +* @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event. +* @return {boolean} true if the child was removed from this group, otherwise false. +*/ +Phaser.Group.prototype.remove = function (child, destroy, silent) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + + if (this.children.length === 0 || this.children.indexOf(child) === -1) + { + return false; + } + + if (!silent && child.events && !child.destroyPhase) + { + child.events.onRemovedFromGroup$dispatch(child, this); + } + + var removed = this.removeChild(child); + + this.removeFromHash(child); + + this.updateZ(); + + if (this.cursor === child) + { + this.next(); + } + + if (destroy && removed) + { + removed.destroy(true); + } + + return true; + +}; + +/** +* Moves all children from this Group to the Group given. +* +* @method Phaser.Group#moveAll +* @param {Phaser.Group} group - The new Group to which the children will be moved to. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group. +* @return {Phaser.Group} The Group to which all the children were moved. +*/ +Phaser.Group.prototype.moveAll = function (group, silent) { + + if (silent === undefined) { silent = false; } + + if (this.children.length > 0 && group instanceof Phaser.Group) + { + do + { + group.add(this.children[0], silent); + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + } + + return group; + +}; + +/** +* Removes all children from this Group, but does not remove the group from its parent. +* +* The children can be optionally destroyed as they are removed. +* +* You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've +* more than one Game Object sharing the same BaseTexture. +* +* @method Phaser.Group#removeAll +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +* @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. +*/ +Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + if (destroyTexture === undefined) { destroyTexture = false; } + + if (this.children.length === 0) + { + return; + } + + do + { + if (!silent && this.children[0].events) + { + this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this); + } + + var removed = this.removeChild(this.children[0]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true, destroyTexture); + } + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + +}; + +/** +* Removes all children from this group whose index falls beteen the given startIndex and endIndex values. +* +* @method Phaser.Group#removeBetween +* @param {integer} startIndex - The index to start removing children from. +* @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +*/ +Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) { + + if (endIndex === undefined) { endIndex = this.children.length - 1; } + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = 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 (!silent && this.children[i].events) + { + this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this); + } + + var removed = this.removeChild(this.children[i]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true); + } + + if (this.cursor === this.children[i]) + { + this.cursor = null; + } + + i--; + } + + this.updateZ(); + +}; + +/** + * Places each child at a random position within the given Rectangle (or the {@link Phaser.World#bounds World bounds}). + * + * @method Phaser.Group#scatter + * @param {Phaser.Rectangle} [rect=this.game.world.bounds] - A Rectangle. If omitted {@link Phaser.World#bounds} is used. + * @param {boolean} [checkExists=false] - Place only children with exists=true. + */ +Phaser.Group.prototype.scatter = function (rect, checkExists) { + + if (rect == null) { rect = this.game.world.bounds; } + + this.forEach(function (child) { + + child.position.set(rect.randomX, rect.randomY); + + }, null, checkExists); + +}; + +/** + * Orders this Group's children randomly. + * + * This can be more efficient than calling {@link #getRandom} repeatedly. + * + * @method Phaser.Group#shuffle + */ +Phaser.Group.prototype.shuffle = function () { + + Phaser.ArrayUtils.shuffle(this.children); + this.updateZ(); + +}; + +/** +* Destroys this group. +* +* Removes all children, then removes this group from its parent and nulls references. +* +* @method Phaser.Group#destroy +* @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. +*/ +Phaser.Group.prototype.destroy = function (destroyChildren, soft) { + + if (this.game === null || this.ignoreDestroy) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (soft === undefined) { soft = false; } + + this.onDestroy.dispatch(this, destroyChildren, soft); + + this.removeAll(destroyChildren); + + this.cursor = null; + this.filters = null; + this.pendingDestroy = false; + + if (!soft) + { + if (this.parent) + { + this.parent.removeChild(this); + } + + this.game = null; + this.exists = false; + } + +}; + +/** +* Total number of existing children in the group. +* +* @name Phaser.Group#total +* @property {integer} total +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "total", { + + get: function () { + + return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); + + } + +}); + +/** +* Total number of children in this group, regardless of exists/alive status. +* +* @name Phaser.Group#length +* @property {integer} length +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "length", { + + get: function () { + + return this.children.length; + + } + +}); + +/** +* The angle of rotation of the group container, in degrees. +* +* This adjusts the group itself by modifying its local rotation transform. +* +* This has no impact on the rotation/angle properties of the children, but it will update their worldTransform +* and on-screen orientation and position. +* +* @name Phaser.Group#angle +* @property {number} angle +*/ +Object.defineProperty(Phaser.Group.prototype, "angle", { + + get: function() { + return Phaser.Math.radToDeg(this.rotation); + }, + + set: function(value) { + this.rotation = Phaser.Math.degToRad(value); + } + +}); + +/** +* The center x coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerX +* @property {number} centerX +*/ +Object.defineProperty(Phaser.Group.prototype, "centerX", { + + get: function () { + + return this.getBounds(this.parent).centerX; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.halfWidth; + + } + +}); + +/** +* The center y coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerY +* @property {number} centerY +*/ +Object.defineProperty(Phaser.Group.prototype, "centerY", { + + get: function () { + + return this.getBounds(this.parent).centerY; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.halfHeight; + + } + +}); + +/** +* The left coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#left +* @property {number} left +*/ +Object.defineProperty(Phaser.Group.prototype, "left", { + + get: function () { + + return this.getBounds(this.parent).left; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = value + offset; + + } + +}); + +/** +* The right coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#right +* @property {number} right +*/ +Object.defineProperty(Phaser.Group.prototype, "right", { + + get: function () { + + return this.getBounds(this.parent).right; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.width; + + } + +}); + +/** +* The top coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#top +* @property {number} top +*/ +Object.defineProperty(Phaser.Group.prototype, "top", { + + get: function () { + + return this.getBounds(this.parent).top; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset); + + } + +}); + +/** +* The bottom coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#bottom +* @property {number} bottom +*/ +Object.defineProperty(Phaser.Group.prototype, "bottom", { + + get: function () { + + return this.getBounds(this.parent).bottom; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.height; + + } + +}); + +/** +* Aligns this Group within another Game Object, or Rectangle, known as the +* 'container', to one of 9 possible positions. +* +* The container must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the container. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, +* `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, +* `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* container, taking into consideration rotation and scale of its children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignIn +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* Aligns this Group to the side of another Game Object, or Rectangle, known as the +* 'parent', in one of 11 possible positions. +* +* The parent must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the parent. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, +* `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, +* `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` +* and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* parent, taking into consideration rotation and scale of the children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignTo +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* A display object is any object that can be rendered in the Phaser/pixi.js scene graph: +* +* - {@link PIXI.DisplayObject} +* - {@link PIXI.DisplayObjectContainer} +* - {@link Phaser.BitmapText} +* - {@link Phaser.Creature} +* - {@link Phaser.Graphics} +* - {@link Phaser.Group} +* - {@link Phaser.FlexLayer} +* - {@link Phaser.Particles.Arcade.Emitter} +* - {@link Phaser.Physics.P2.BodyDebug} +* - {@link Phaser.SpriteBatch} +* - {@link Phaser.World} +* - {@link Phaser.Rope} +* - {@link Phaser.Stage} +* - {@link PIXI.Sprite} +* - {@link Phaser.Image} +* - {@link Phaser.Button} +* - {@link Phaser.Sprite} +* - {@link Phaser.Bullet} +* - {@link Phaser.Particle} +* - {@link Phaser.Text} +* - {@link Phaser.TilemapLayer} +* - {@link Phaser.TileSprite} +* +* @typedef {object} DisplayObject +*/ +// Documentation stub for linking. + +/** +* The x coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#x +* @property {number} x +*/ + +/** +* The y coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#y +* @property {number} y +*/ + +/** +* The angle of rotation of the group container, in radians. +* +* This will adjust the group container itself by modifying its rotation. +* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#rotation +* @property {number} rotation +*/ + +/** +* The visible state of the group. Non-visible Groups and all of their children are not rendered. +* +* @name Phaser.Group#visible +* @property {boolean} visible +*/ + +/** +* The alpha value of the group container. +* +* @name Phaser.Group#alpha +* @property {number} alpha +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* "This world is but a canvas to our imagination." - Henry David Thoreau +* +* A game has only one world. The world is an abstract place in which all game objects live. It is not bound +* by stage limits and can be any size. You look into the world via cameras. All game objects live within +* the world at world-based coordinates. By default a world is created the same size as your Stage. +* +* @class Phaser.World +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.World = function (game) { + + Phaser.Group.call(this, game, null, '__world', false); + + /** + * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. + * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. + * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. + * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. + * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height); + + /** + * @property {Phaser.Camera} camera - Camera instance. + */ + this.camera = null; + + /** + * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. + * @readonly + */ + this._definedSize = false; + + /** + * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._width = game.width; + + /** + * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._height = game.height; + + this.game.state.onStateChange.add(this.stateChange, this); + +}; + +Phaser.World.prototype = Object.create(Phaser.Group.prototype); +Phaser.World.prototype.constructor = Phaser.World; + +/** +* Initialises the game world. +* +* @method Phaser.World#boot +* @protected +*/ +Phaser.World.prototype.boot = function () { + + this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height); + + this.game.stage.addChild(this); + + this.camera.boot(); + +}; + +/** +* Called whenever the State changes or resets. +* +* It resets the world.x and world.y coordinates back to zero, +* then resets the Camera. +* +* @method Phaser.World#stateChange +* @protected +*/ +Phaser.World.prototype.stateChange = function () { + + this.x = 0; + this.y = 0; + + this.camera.reset(); + +}; + +/** +* Updates the size of this world and sets World.x/y to the given values +* The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. +* +* @method Phaser.World#setBounds +* @param {number} x - Top left most corner of the world. +* @param {number} y - Top left most corner of the world. +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.setBounds = function (x, y, width, height) { + + this._definedSize = true; + this._width = width; + this._height = height; + + this.bounds.setTo(x, y, width, height); + + this.x = x; + this.y = y; + + if (this.camera.bounds) + { + // The Camera can never be smaller than the game size + this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height)); + } + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Updates this world's width and height (but not smaller than any previous {@link #setBounds defined size}). +* +* Phaser uses this to adapt to {@link Phaser.ScaleManager#updateDimensions layout changes}. +* You probably want to use {@link #setBounds} instead. +* +* @method Phaser.World#resize +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.resize = function (width, height) { + + // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size + + if (this._definedSize) + { + if (width < this._width) + { + width = this._width; + } + + if (height < this._height) + { + height = this._height; + } + } + + this.bounds.width = width; + this.bounds.height = height; + + this.game.camera.setBoundsToWorld(); + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Destroyer of worlds. +* +* @method Phaser.World#shutdown +*/ +Phaser.World.prototype.shutdown = function () { + + // World is a Group, so run a soft destruction on this and all children. + this.destroy(true, true); + +}; + +/** +* This will take the given game object and check if its x/y coordinates fall outside of the world bounds. +* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. +* If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. +* +* Please understand there are limitations to this method. For example if you have scaled the World +* then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. +* +* @method Phaser.World#wrap +* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) { + + if (padding === undefined) { padding = 0; } + if (useBounds === undefined) { useBounds = false; } + if (horizontal === undefined) { horizontal = true; } + if (vertical === undefined) { vertical = true; } + + if (!useBounds) + { + if (horizontal && sprite.x + padding < this.bounds.x) + { + sprite.x = this.bounds.right + padding; + } + else if (horizontal && sprite.x - padding > this.bounds.right) + { + sprite.x = this.bounds.left - padding; + } + + if (vertical && sprite.y + padding < this.bounds.top) + { + sprite.y = this.bounds.bottom + padding; + } + else if (vertical && sprite.y - padding > this.bounds.bottom) + { + sprite.y = this.bounds.top - padding; + } + } + else + { + sprite.getBounds(); + + if (horizontal) + { + if ((sprite.x + sprite._currentBounds.width) < this.bounds.x) + { + sprite.x = this.bounds.right; + } + else if (sprite.x > this.bounds.right) + { + sprite.x = this.bounds.left; + } + } + + if (vertical) + { + if ((sprite.y + sprite._currentBounds.height) < this.bounds.top) + { + sprite.y = this.bounds.bottom; + } + else if (sprite.y > this.bounds.bottom) + { + sprite.y = this.bounds.top; + } + } + } + +}; + +/** +* @method Phaser.World#wrapAll +* @param {Phaser.Group} group - A group of sprites. +* @param {boolean} [checkExists=false] - Wrap only sprites having `exists=true`. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrapAll = function (group, checkExists, padding, useBounds, horizontal, vertical) { + + group.forEach(this.wrap, this, checkExists, padding, useBounds, horizontal, vertical); + +}; + +/** +* @name Phaser.World#width +* @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "width", { + + get: function () { + return this.bounds.width; + }, + + set: function (value) { + + if (value < this.game.width) + { + value = this.game.width; + } + + this.bounds.width = value; + this._width = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#height +* @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "height", { + + get: function () { + return this.bounds.height; + }, + + set: function (value) { + + if (value < this.game.height) + { + value = this.game.height; + } + + this.bounds.height = value; + this._height = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#centerX +* @property {number} centerX - Gets the X position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerX", { + + get: function () { + return this.bounds.halfWidth + this.bounds.x; + } + +}); + +/** +* @name Phaser.World#centerY +* @property {number} centerY - Gets the Y position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerY", { + + get: function () { + return this.bounds.halfHeight + this.bounds.y; + } + +}); + +/** +* @name Phaser.World#randomX +* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomX", { + + get: function () { + + if (this.bounds.x < 0) + { + return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x))); + } + else + { + return this.game.rnd.between(this.bounds.x, this.bounds.width); + } + + } + +}); + +/** +* @name Phaser.World#randomY +* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomY", { + + get: function () { + + if (this.bounds.y < 0) + { + return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y))); + } + else + { + return this.game.rnd.between(this.bounds.y, this.bounds.height); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Game object is the main controller for the entire Phaser game. It is responsible +* for handling the boot process, parsing the configuration values, creating the renderer, +* and setting-up all of the Phaser systems, such as physics, sound and input. +* Once that is complete it will start the default State, and then begin the main game loop. +* +* You can access lots of the Phaser systems via the properties on the `game` object. For +* example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on. +* +* Anywhere you can access the `game` property, you can access all of these core systems. +* For example a Sprite has a `game` property, allowing you to talk to the various parts +* of Phaser directly, without having to look after your own references. +* +* In it's most simplest form, a Phaser game can be created by providing the arguments +* to the constructor: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create }); +* ``` +* +* In the example above it is passing in a State object directly. You can also use the State +* Manager to do this: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO); +* game.state.add('Boot', BasicGame.Boot); +* game.state.add('Preloader', BasicGame.Preloader); +* game.state.add('MainMenu', BasicGame.MainMenu); +* game.state.add('Game', BasicGame.Game); +* game.state.start('Boot'); +* ``` +* +* In the example above, 4 States are added to the State Manager, and Phaser is told to +* start running the `Boot` state when it has finished initializing. There are example +* project templates you can use in the Phaser GitHub repo, inside the `resources` folder. +* +* Instead of specifying arguments you can also pass {@link GameConfig a single object} instead: +* +* ```javascript +* var config = { +* width: 800, +* height: 600, +* renderer: Phaser.AUTO, +* antialias: true, +* multiTexture: true, +* state: { +* preload: preload, +* create: create, +* update: update +* } +* } +* +* var game = new Phaser.Game(config); +* ``` +* +* @class Phaser.Game +* @constructor +* @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. +* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. +* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). +* @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body. +* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. +* @param {boolean} [transparent=false] - Use a transparent canvas background or not. +* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) { + + /** + * @property {number} id - Phaser Game ID + * @readonly + */ + this.id = Phaser.GAMES.push(this) - 1; + + /** + * @property {object} config - The Phaser.Game configuration object. + */ + this.config = null; + + /** + * @property {object} physicsConfig - The Phaser.Physics.World configuration object. + */ + this.physicsConfig = physicsConfig; + + /** + * @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted. + * @readonly + * @default + */ + this.parent = ''; + + /** + * The current Game Width in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} width + * @readonly + * @default + */ + this.width = 800; + + /** + * The current Game Height in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} height + * @readonly + * @default + */ + this.height = 600; + + /** + * The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object. + * + * @property {integer} resolution + * @readonly + * @default + */ + this.resolution = 1; + + /** + * @property {integer} _width - Private internal var. + * @private + */ + this._width = 800; + + /** + * @property {integer} _height - Private internal var. + * @private + */ + this._height = 600; + + /** + * @property {boolean} transparent - Use a transparent canvas background or not. + * @default + */ + this.transparent = false; + + /** + * @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead. + * @readonly + * @default + */ + this.antialias = true; + + /** + * Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property. + * To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game + * Configuration object with the property `multiTexture` set to true. It has to be enabled before + * Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it + * via the `game.renderer.setTexturePriority` method. + * + * @property {boolean} multiTexture + * @readonly + * @default + */ + this.multiTexture = false; + + /** + * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * @default + */ + this.preserveDrawingBuffer = false; + + /** + * Clear the Canvas each frame before rendering the display list. + * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. + * This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage. + * @property {boolean} clearBeforeRender + * @default + */ + this.clearBeforeRender = true; + + /** + * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. + * @protected + */ + this.renderer = null; + + /** + * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `render` hooks but not `preRender` or `postRender`; set {@link lockRender} to skip those as well. + * @readonly + */ + this.renderType = Phaser.AUTO; + + /** + * @property {Phaser.StateManager} state - The StateManager. + */ + this.state = null; + + /** + * @property {boolean} isBooted - Whether the game engine is booted, aka available. + * @readonly + */ + this.isBooted = false; + + /** + * @property {boolean} isRunning - Is game running or paused? + * @readonly + */ + this.isRunning = false; + + /** + * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout + * @protected + */ + this.raf = null; + + /** + * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. + */ + this.make = null; + + /** + * @property {Phaser.Cache} cache - Reference to the assets cache. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - Reference to the input manager + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - Reference to the assets loader. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - Reference to the math helper. + */ + this.math = null; + + /** + * @property {Phaser.Net} net - Reference to the network class. + */ + this.net = null; + + /** + * @property {Phaser.ScaleManager} scale - The game scale manager. + */ + this.scale = null; + + /** + * @property {Phaser.SoundManager} sound - Reference to the sound manager. + */ + this.sound = null; + + /** + * @property {Phaser.Stage} stage - Reference to the stage. + */ + this.stage = null; + + /** + * @property {Phaser.Time} time - Reference to the core game clock. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - Reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - Reference to the world. + */ + this.world = null; + + /** + * @property {Phaser.Physics} physics - Reference to the physics manager. + */ + this.physics = null; + + /** + * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. + */ + this.plugins = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. + */ + this.rnd = null; + + /** + * @property {Phaser.Device} device - Contains device information and capabilities. + */ + this.device = Phaser.Device; + + /** + * @property {Phaser.Camera} camera - A handy reference to world.camera. + */ + this.camera = null; + + /** + * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) + */ + this.context = null; + + /** + * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. + */ + this.debug = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. + */ + this.particles = null; + + /** + * @property {Phaser.Create} create - The Asset Generator. + */ + this.create = null; + + /** + * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. + * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. + * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. + * @property {boolean} lockRender + * @default + */ + this.lockRender = false; + + /** + * @property {boolean} pendingDestroy - Destroy the game at the next update. + * @default + */ + this.pendingDestroy = false; + + /** + * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). + * @default + * @readonly + */ + this.stepping = false; + + /** + * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. + * @default + * @readonly + */ + this.pendingStep = false; + + /** + * @property {number} stepCount - When stepping is enabled this contains the current step cycle. + * @default + * @readonly + */ + this.stepCount = 0; + + /** + * @property {Phaser.Signal} onPause - This event is fired when the game pauses. + */ + this.onPause = null; + + /** + * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. + */ + this.onResume = null; + + /** + * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). + */ + this.onBlur = null; + + /** + * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). + */ + this.onFocus = null; + + /** + * @property {boolean} _paused - Is game paused? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _codePaused - Was the game paused via code or a visibility change? + * @private + */ + this._codePaused = false; + + /** + * The ID of the current/last logic update applied this animation frame, starting from 0. + * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` + * @property {integer} currentUpdateID + * @protected + */ + this.currentUpdateID = 0; + + /** + * Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed). + * @property {integer} updatesThisFrame + * @protected + */ + this.updatesThisFrame = 1; + + /** + * Number of renders expected to occur this animation frame. May be 0 if {@link #dropFrames is on} or {@link #forceSingleRender} is off; otherwise it will be 1. + * @property {integer} updatesThisFrame + * @protected + */ + this.rendersThisFrame = 1; + + /** + * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. + * @private + */ + this._deltaTime = 0; + + /** + * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. + * @private + */ + this._lastCount = 0; + + /** + * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. + * @private + */ + this._spiraling = 0; + + /** + * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) + * @private + */ + this._kickstart = true; + + /** + * If the game is struggling to maintain the desired FPS, this signal will be dispatched. + * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. + * @property {Phaser.Signal} fpsProblemNotifier + * @public + */ + this.fpsProblemNotifier = new Phaser.Signal(); + + /** + * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? You can toggle it on the fly. + */ + this.forceSingleUpdate = true; + + /** + * @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update? (During spiraling conditions, {@link #dropFrames} is used instead.) + */ + this.forceSingleRender = true; + + /** + * @property {boolean} dropFrames - When {@link #forceSingleUpdate} is off, skip {@link #updateRender rendering} if logic updates are spiraling upwards. + */ + this.dropFrames = false; + + /** + * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. + * @private + */ + this._nextFpsNotification = 0; + + // Parse the configuration object (if any) + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + this.parseConfig(arguments[0]); + } + else + { + this.config = { enableDebug: true }; + + if (typeof width !== 'undefined') + { + this._width = width; + } + + if (typeof height !== 'undefined') + { + this._height = height; + } + + if (typeof renderer !== 'undefined') + { + 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); + } + + this.device.whenReady(this.boot, this); + + return this; + +}; + +/** +* A configuration object for {@link Phaser.Game}. +* +* @typedef {object} GameConfig +* @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}. +* @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}. +* @property {number|string} [GameConfig.antialias=true] +* @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}. +* @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in. +* @property {string} [GameConfig.canvasId] - `id` attribute value to assign to the game canvas. +* @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas. +* @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}. +* @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange} +* @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing. +* @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production. +* @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO. +* @property {boolean} [GameConfig.forceSetTimeout] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeOut} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available. +* @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen. +* @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked. +* @property {number|string} [GameConfig.height=600] +* @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`. +* @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected. +* @property {object} [GameConfig.physicsConfig] +* @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering. +* @property {number} [GameConfig.renderer=Phaser.AUTO] +* @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels. +* @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices. +* @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen. +* @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}. +* @property {object} [GameConfig.state] +* @property {boolean} [GameConfig.transparent=false] +* @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode. +* @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode. +* @property {number|string} [GameConfig.width=800] +*/ +// Documentation stub for linking. + +Phaser.Game.prototype = { + + /** + * Parses a Game configuration object. + * + * @method Phaser.Game#parseConfig + * @protected + */ + parseConfig: function (config) { + + this.config = config; + + if (config['enableDebug'] === undefined) + { + this.config.enableDebug = true; + } + + if (config['width']) + { + this._width = config['width']; + } + + if (config['height']) + { + this._height = config['height']; + } + + if (config['renderer']) + { + this.renderType = config['renderer']; + } + + if (config['parent']) + { + this.parent = config['parent']; + } + + if (config['transparent'] !== undefined) + { + this.transparent = config['transparent']; + } + + if (config['antialias'] !== undefined) + { + this.antialias = config['antialias']; + } + + if (config['multiTexture'] !== undefined) + { + this.multiTexture = config['multiTexture']; + } + + if (config['resolution']) + { + this.resolution = config['resolution']; + } + + if (config['preserveDrawingBuffer'] !== undefined) + { + this.preserveDrawingBuffer = config['preserveDrawingBuffer']; + } + + 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); + + }, + + /** + * Initialize engine sub modules and start the game. + * + * @method Phaser.Game#boot + * @protected + */ + boot: function () { + + if (this.isBooted) + { + return; + } + + this.onPause = new Phaser.Signal(); + this.onResume = new Phaser.Signal(); + this.onBlur = new Phaser.Signal(); + this.onFocus = new Phaser.Signal(); + + this.isBooted = true; + + PIXI.game = this; + + this.math = Phaser.Math; + + this.scale = new Phaser.ScaleManager(this, this._width, this._height); + this.stage = new Phaser.Stage(this); + + this.setUpRenderer(); + + 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.create = new Phaser.Create(this); + this.plugins = new Phaser.PluginManager(this); + this.net = new Phaser.Net(this); + + this.time.boot(); + this.stage.boot(); + this.world.boot(); + this.scale.boot(); + this.input.boot(); + this.sound.boot(); + this.state.boot(); + + if (this.config['enableDebug']) + { + this.debug = new Phaser.Utils.Debug(this); + this.debug.boot(); + } + else + { + this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {}, isDisabled: true }; + } + + 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._kickstart = true; + + if (window['focus']) + { + if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus)) + { + window.focus(); + } + } + + if (this.config['disableStart']) + { + return; + } + + if (this.cache.isReady) + { + this.raf.start(); + } + else + { + this.cache.onReady.addOnce(function () { + this.raf.start(); + }, this); + } + + }, + + /** + * Displays a Phaser version debug header in the console. + * + * @method Phaser.Game#showDebugHeader + * @protected + */ + showDebugHeader: function () { + + if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner) + { + return; + } + + 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.ie) // https://developer.mozilla.org/en-US/docs/Web/API/Console/log#Browser_compatibility + { + var args = [ + '%c %c %c Phaser CE v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665', + 'background: #fb8cb3', + 'background: #d44a52', + 'color: #ffffff; background: #871905;', + 'background: #d44a52', + 'background: #fb8cb3', + 'background: #ffffff' + ]; + + for (var i = 0; i < 3; i++) + { + if (i < c) + { + args.push('color: #ff2424; background: #fff'); + } + else + { + args.push('color: #959595; background: #fff'); + } + } + + console.log.apply(console, args); + } + else if (window['console']) + { + console.log('Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' | http://phaser.io'); + } + + }, + + /** + * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. + * + * @method Phaser.Game#setUpRenderer + * @protected + */ + setUpRenderer: function () { + + if (!this.device.canvas) + { + // Nothing else to do + throw new Error('Phaser.Game - Cannot create Canvas 2d context, aborting.'); + } + + if (this.config['canvas']) + { + this.canvas = this.config['canvas']; + } + else + { + this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true); + } + + if (this.config['canvasStyle']) + { + this.canvas.style = this.config['canvasStyle']; + } + else + { + this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; + } + + if (this.config['crisp']) + { + Phaser.Canvas.setImageRenderingCrisp(this.canvas); + } + + if ((this.renderType === Phaser.WEBGL) || + (this.renderType === Phaser.WEBGL_MULTI) || + (this.renderType === Phaser.AUTO && this.device.webGL)) + { + if (this.multiTexture || this.renderType === Phaser.WEBGL_MULTI) + { + PIXI.enableMultiTexture(); + this.multiTexture = true; + } + + try + { + this.renderer = new PIXI.WebGLRenderer(this, this.config); + this.renderType = Phaser.WEBGL; + this.context = null; + this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); + this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); + } + catch (webGLRendererError) + { + this.renderer = null; + this.multiTexture = false; + PIXI._enableMultiTextureToggle = false; + + if (this.renderType === Phaser.WEBGL) + { + // No fallback + throw webGLRendererError; + } + } + } + + if (!this.renderer) + { + this.renderer = new PIXI.CanvasRenderer(this, this.config); + this.context = this.renderer.context; + + if (this.renderType === Phaser.AUTO) + { + this.renderType = Phaser.CANVAS; + } + } + + if (this.device.cocoonJS) + { + this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false; + } + + if (this.renderType !== Phaser.HEADLESS) + { + this.stage.smoothed = this.antialias; + + Phaser.Canvas.addToDOM(this.canvas, this.parent, false); + Phaser.Canvas.setTouchAction(this.canvas); + } + + }, + + /** + * Handles WebGL context loss. + * + * @method Phaser.Game#contextLost + * @private + * @param {Event} event - The webglcontextlost event. + */ + contextLost: function (event) { + + event.preventDefault(); + + this.renderer.contextLost = true; + + }, + + /** + * Handles WebGL context restoration. + * + * @method Phaser.Game#contextRestored + * @private + */ + contextRestored: function () { + + this.renderer.initContext(); + + this.cache.clearGLTextures(); + + this.renderer.contextLost = false; + + }, + + /** + * The core game loop. + * + * @method Phaser.Game#update + * @protected + * @param {number} time - The current time as provided by RequestAnimationFrame. + */ + update: function (time) { + + if (this.pendingDestroy) + { + this.destroy(); + return; + } + + this.time.update(time); + + if (this._kickstart) + { + this.updateLogic(this.time.desiredFpsMult); + + // call the game render update exactly once every frame + this.updateRender(this.time.slowMotion * this.time.desiredFps); + + this._kickstart = false; + + return; + } + + // if the logic time is spiraling upwards, skip a frame entirely + if (this._spiraling > 1 && !this.forceSingleUpdate) + { + // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate + if (this.time.time > this._nextFpsNotification) + { + // only permit one fps notification per 10 seconds + this._nextFpsNotification = this.time.time + 10000; + + // dispatch the notification signal + this.fpsProblemNotifier.dispatch(); + } + + // reset the _deltaTime accumulator which will cause all pending late updates to be permanently skipped + this._deltaTime = 0; + this._spiraling = 0; + + if (this.dropFrames) + { + this.rendersThisFrame = 0; + } + else + { + this.updateRender(this.time.slowMotion * this.time.desiredFps); + this.rendersThisFrame = 1; + } + } + else + { + // step size taking into account the slow motion speed + var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps; + + // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals + this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0); + + // call the game update logic multiple times if necessary to "catch up" with dropped frames + // unless forceSingleUpdate is true + var count = 0; + + this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); + + if (this.forceSingleUpdate) + { + this.updatesThisFrame = Math.min(1, this.updatesThisFrame); + } + + if (this.forceSingleRender) + { + this.rendersThisFrame = 1; + } + else + { + this.rendersThisFrame = Math.min(1, this.updatesThisFrame); + } + + while (this._deltaTime >= slowStep) + { + this._deltaTime -= slowStep; + this.currentUpdateID = count; + + this.updateLogic(this.time.desiredFpsMult); + + count++; + + if (this.forceSingleUpdate && count === 1) + { + break; + } + else + { + this.time.refresh(); + } + } + + // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly) + if (count > this._lastCount) + { + this._spiraling++; + } + else if (count < this._lastCount) + { + // looks like it caught up successfully, reset the spiral alert counter + this._spiraling = 0; + } + + this._lastCount = count; + + if (this.rendersThisFrame > 0) + { + this.updateRender(this._deltaTime / slowStep); + } + } + + }, + + /** + * Updates all logic subsystems in Phaser. Called automatically by Game.update. + * + * @method Phaser.Game#updateLogic + * @protected + * @param {number} timeStep - The current timeStep value as determined by Game.update. + */ + updateLogic: function (timeStep) { + + if (!this._paused && !this.pendingStep) + { + if (this.stepping) + { + this.pendingStep = true; + } + + this.time.countUpdate(); + + this.scale.preUpdate(); + this.debug.preUpdate(); + this.camera.preUpdate(); + this.physics.preUpdate(); + this.state.preUpdate(timeStep); + this.plugins.preUpdate(timeStep); + this.stage.preUpdate(); + + this.state.update(); + this.stage.update(); + this.tweens.update(); + this.sound.update(); + this.input.update(); + this.physics.update(); + this.plugins.update(); + + this.stage.postUpdate(); + this.plugins.postUpdate(); + } + else + { + // Scaling and device orientation changes are still reflected when paused. + this.scale.pauseUpdate(); + this.state.pauseUpdate(timeStep); + this.debug.preUpdate(); + this.input.pauseUpdate(); + } + + this.stage.updateTransform(); + + }, + + /** + * Runs the Render cycle. + * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. + * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. + * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. + * After this State.render is called. Any rendering that happens here will take place on-top of the display list. + * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. + * This method is called automatically by Game.update, you don't need to call it directly. + * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. + * Phaser will only render when this boolean is `false`. + * + * @method Phaser.Game#updateRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + updateRender: function (elapsedTime) { + + if (this.lockRender) + { + return; + } + + this.time.countRender(); + + this.state.preRender(elapsedTime); + + if (this.renderType !== Phaser.HEADLESS) + { + this.renderer.render(this.stage); + + this.plugins.render(elapsedTime); + + this.state.render(elapsedTime); + } + + this.plugins.postRender(elapsedTime); + + }, + + /** + * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) + * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! + * + * @method Phaser.Game#enableStep + */ + enableStep: function () { + + this.stepping = true; + this.pendingStep = false; + this.stepCount = 0; + + }, + + /** + * Disables core game loop stepping. + * + * @method Phaser.Game#disableStep + */ + disableStep: function () { + + this.stepping = false; + this.pendingStep = false; + + }, + + /** + * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. + * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. + * + * @method Phaser.Game#step + */ + step: function () { + + this.pendingStep = false; + this.stepCount++; + + }, + + /** + * Nukes the entire game from orbit. + * + * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. + * + * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM + * and resets the PIXI default renderer. + * + * To destroy the game during an update callback, set {@link #pendingDestroy} instead. + * + * @method Phaser.Game#destroy + */ + destroy: function () { + + this.raf.stop(); + + if (this.debug.destroy) + { + this.debug.destroy(); + } + + this.state.destroy(); + this.sound.destroy(); + this.scale.destroy(); + this.stage.destroy(); + this.input.destroy(); + this.physics.destroy(); + this.plugins.destroy(); + + this.debug = null; + this.state = null; + this.sound = null; + this.scale = null; + this.stage = null; + this.input = null; + this.physics = null; + this.plugins = null; + + this.cache = null; + this.load = null; + this.time = null; + this.world = null; + + this.isBooted = false; + + this.renderer.destroy(false); + + Phaser.Canvas.removeFromDOM(this.canvas); + + PIXI.defaultRenderer = null; + + Phaser.GAMES[this.id] = null; + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gamePaused + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gamePaused: function (event) { + + // If the game is already paused it was done via game code, so don't re-pause it + if (!this._paused) + { + this._paused = true; + + this.time.gamePaused(); + + if (this.sound.muteOnPause) + { + this.sound.setMute(); + } + + this.onPause.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = true; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gameResumed + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gameResumed: function (event) { + + // Game is paused, but wasn't paused via code, so resume it + if (this._paused && !this._codePaused) + { + this._paused = false; + + this.time.gameResumed(); + + this.input.reset(); + + if (this.sound.muteOnPause) + { + this.sound.unsetMute(); + } + + this.onResume.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = false; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusLoss + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusLoss: function (event) { + + this.onBlur.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gamePaused(event); + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusGain + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusGain: function (event) { + + this.onFocus.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gameResumed(event); + } + + } + +}; + +Phaser.Game.prototype.constructor = Phaser.Game; + +/** +* The paused state of the Game. A paused game doesn't update any of its subsystems. +* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. +* @name Phaser.Game#paused +* @property {boolean} paused - Gets and sets the paused state of the Game. +*/ +Object.defineProperty(Phaser.Game.prototype, "paused", { + + get: function () { + return this._paused; + }, + + set: function (value) { + + if (value === true) + { + if (this._paused === false) + { + this._paused = true; + this.sound.setMute(); + this.time.gamePaused(); + this.onPause.dispatch(this); + } + this._codePaused = true; + } + else + { + if (this._paused) + { + this._paused = false; + this.input.reset(); + this.sound.unsetMute(); + this.time.gameResumed(); + this.onResume.dispatch(this); + } + this._codePaused = false; + } + + } + +}); + +/** + * + * "Deleted code is debugged code." - Jeff Sickel + * + * ヽ(〃^▽^〃)ノ + * +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. +* The Input manager is updated automatically by the core game loop. +* +* @class Phaser.Input +* @constructor +* @param {Phaser.Game} game - Current game instance. +*/ +Phaser.Input = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. + * @default + */ + this.hitCanvas = null; + + /** + * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. + * @default + */ + this.hitContext = null; + + /** + * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. + * To add a callback to this array please use `Input.addMoveCallback`. + * @property {array} moveCallbacks + * @protected + */ + this.moveCallbacks = []; + + /** + * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandler = null; + + /** + * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandlerContext = null; + + /** + * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. + * @default + */ + this.pollRate = 0; + + /** + * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. + * + * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. + * @default + */ + this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE; + + /** + * @property {Phaser.Point} position - A point object representing the current position of the Pointer. + * @default + */ + this.position = null; + + /** + * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. + */ + this.speed = null; + + /** + * A Circle object centered on the x/y screen coordinates of the Input. + * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. + * @property {Phaser.Circle} circle + */ + this.circle = null; + + /** + * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. + */ + this.scale = null; + + /** + * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1. + * @default -1 (Limited by total pointers.) + */ + this.maxPointers = -1; + + /** + * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. + * @default + */ + this.tapRate = 200; + + /** + * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. + * @default + */ + this.doubleTapRate = 300; + + /** + * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. + * @default + */ + this.holdRate = 2000; + + /** + * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. + * @default + */ + this.justPressedRate = 200; + + /** + * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . + * @default + */ + this.justReleasedRate = 200; + + /** + * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. + * The history is cleared each time the Pointer is pressed down. + * The history is updated at the rate specified in Input.pollRate + * @property {boolean} recordPointerHistory + * @default + */ + this.recordPointerHistory = false; + + /** + * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. + * @default + */ + this.recordRate = 100; + + /** + * The total number of entries that can be recorded into the Pointer objects tracking history. + * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. + * @property {number} recordLimit + * @default + */ + this.recordLimit = 100; + + /** + * An array of callbacks that will be fired every time a native touch start or touch end event (pointerdown or pointerup when using Pointer events) is received from the browser. + * This is used internally to handle audio and video unlocking on mobile devices. + * To add a callback to this array please use `Input.addTouchLockCallback`. + * @property {array} touchLockCallbacks + * @protected + */ + this.touchLockCallbacks = []; + + /** + * @property {Phaser.Pointer} pointer1 - A Pointer object. + */ + this.pointer1 = null; + + /** + * @property {Phaser.Pointer} pointer2 - A Pointer object. + */ + this.pointer2 = null; + + /** + * @property {Phaser.Pointer} pointer3 - A Pointer object. + */ + this.pointer3 = null; + + /** + * @property {Phaser.Pointer} pointer4 - A Pointer object. + */ + this.pointer4 = null; + + /** + * @property {Phaser.Pointer} pointer5 - A Pointer object. + */ + this.pointer5 = null; + + /** + * @property {Phaser.Pointer} pointer6 - A Pointer object. + */ + this.pointer6 = null; + + /** + * @property {Phaser.Pointer} pointer7 - A Pointer object. + */ + this.pointer7 = null; + + /** + * @property {Phaser.Pointer} pointer8 - A Pointer object. + */ + this.pointer8 = null; + + /** + * @property {Phaser.Pointer} pointer9 - A Pointer object. + */ + this.pointer9 = null; + + /** + * @property {Phaser.Pointer} pointer10 - A Pointer object. + */ + this.pointer10 = null; + + /** + * An array of non-mouse pointers that have been added to the game. + * The properties `pointer1..N` are aliases for `pointers[0..N-1]`. + * @property {Phaser.Pointer[]} pointers + * @public + * @readonly + */ + this.pointers = []; + + /** + * The most recently active Pointer object. + * + * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. + * + * @property {Phaser.Pointer} activePointer + */ + this.activePointer = null; + + /** + * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. + * + * @property {Pointer} mousePointer + */ + this.mousePointer = null; + + /** + * The Mouse Input manager. + * + * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Mouse} mouse + */ + this.mouse = null; + + /** + * The Keyboard Input manager. + * + * @property {Phaser.Keyboard} keyboard + */ + this.keyboard = null; + + /** + * The Touch Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Touch} touch + */ + this.touch = null; + + /** + * The MSPointer Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.MSPointer} mspointer + */ + this.mspointer = null; + + /** + * The Gamepad Input manager. + * + * @property {Phaser.Gamepad} gamepad + */ + this.gamepad = null; + + /** + * If the Input Manager has been reset locked then all calls made to InputManager.reset, + * such as from a State change, are ignored. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is pressed down. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onDown + */ + this.onDown = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is released. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onUp + */ + this.onUp = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is tapped. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {boolean} True if this was a double tap. + * + * @property {Phaser.Signal} onTap + */ + this.onTap = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is held down. + * It is sent one argument: + * + * - {Phaser.Pointer} The pointer that caused the event. + * + * @property {Phaser.Signal} onHold + */ + this.onHold = null; + + /** + * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. + * This is useful when stacking UI layers. Set to zero to disable. + * @property {number} minPriorityID + * @default + */ + this.minPriorityID = 0; + + /** + * A list of interactive objects. The InputHandler components add and remove themselves from this list. + * @property {Phaser.ArraySet} interactiveItems + */ + this.interactiveItems = new Phaser.ArraySet(); + + /** + * @property {Phaser.Point} _localPoint - Internal cache var. + * @private + */ + this._localPoint = new Phaser.Point(); + + /** + * @property {number} _pollCounter - Internal var holding the current poll counter. + * @private + */ + this._pollCounter = 0; + + /** + * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. + * @private + */ + this._oldPosition = null; + + /** + * @property {number} _x - x coordinate of the most recent Pointer event + * @private + */ + this._x = 0; + + /** + * @property {number} _y - Y coordinate of the most recent Pointer event + * @private + */ + this._y = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_TOUCH_COMBINE = 2; + +/** +* The maximum number of pointers that can be added. This excludes the mouse pointer. +* @constant +* @type {integer} +*/ +Phaser.Input.MAX_POINTERS = 10; + +Phaser.Input.prototype = { + + /** + * Starts the Input Manager running. + * + * @method Phaser.Input#boot + * @protected + */ + boot: function () { + + this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR); + this.addPointer(); + this.addPointer(); + + this.mouse = new Phaser.Mouse(this.game); + this.touch = new Phaser.Touch(this.game); + this.mspointer = new Phaser.MSPointer(this.game); + + if (Phaser.Keyboard) + { + this.keyboard = new Phaser.Keyboard(this.game); + } + + if (Phaser.Gamepad) + { + this.gamepad = new Phaser.Gamepad(this.game); + } + + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + + this.scale = new Phaser.Point(1, 1); + this.speed = new Phaser.Point(); + this.position = new Phaser.Point(); + this._oldPosition = new Phaser.Point(); + + this.circle = new Phaser.Circle(0, 0, 44); + + this.activePointer = this.mousePointer; + + this.hitCanvas = Phaser.CanvasPool.create(this, 1, 1); + this.hitContext = this.hitCanvas.getContext('2d'); + + this.mouse.start(); + if (!this.game.device.mspointer) + { + // Chrome >= 55 fires both PointerEvent and TouchEvent. + // Pick only one. + this.touch.start(); + } + this.mspointer.start(); + this.mousePointer.active = true; + + if (this.keyboard) + { + this.keyboard.start(); + } + + var _this = this; + + this._onClickTrampoline = function (event) { + _this.onClickTrampoline(event); + }; + + this.game.canvas.addEventListener('click', this._onClickTrampoline, false); + + }, + + /** + * Stops all of the Input Managers from running. + * + * @method Phaser.Input#destroy + */ + destroy: function () { + + this.mouse.stop(); + this.touch.stop(); + this.mspointer.stop(); + + if (this.keyboard) + { + this.keyboard.stop(); + } + + if (this.gamepad) + { + this.gamepad.stop(); + } + + this.moveCallbacks = []; + + Phaser.CanvasPool.remove(this); + + this.game.canvas.removeEventListener('click', this._onClickTrampoline); + + }, + + /** + * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. + * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to + * interact with. It works by polling all of the valid game objects, and then slowly discounting those + * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). + * + * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid + * for input and overlap with the Pointer. If you need fine-grained control over which of the items is + * selected then you can use this callback to do so. + * + * The callback will be sent 3 parameters: + * + * 1) A reference to the Phaser.Pointer object that is processing the Items. + * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. + * 3) The current 'favorite' candidate, based on its priorityID and position in the display list. + * + * Your callback MUST return one of the candidates sent to it. + * + * @method Phaser.Input#setInteractiveCandidateHandler + * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. + * @param {object} context - The context in which the callback will be called. + */ + setInteractiveCandidateHandler: function (callback, context) { + + this.customCandidateHandler = callback; + this.customCandidateHandlerContext = context; + + }, + + /** + * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. + * + * The callback will be sent 4 parameters: + * + * A reference to the Phaser.Pointer object that moved, + * The x position of the pointer, + * The y position, + * A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down). + * + * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best + * to only use if you've limited input to a single pointer (i.e. mouse or touch). + * + * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. + * + * @method Phaser.Input#addMoveCallback + * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. + * @param {object} context - The context in which the callback will be called. + */ + addMoveCallback: function (callback, context) { + + this.moveCallbacks.push({ callback: callback, context: context }); + + }, + + + /** + * Adds a callback that is fired when a browser touchstart/pointerdown or touchend/pointerup event is received. + * + * This is used internally to handle audio and video unlocking on mobile devices. + * + * If the callback returns 'true' then the callback is automatically deleted once invoked. + * + * The callback is added to the {@link #touchLockCallbacks} array and should be removed with {@link #removeTouchLockCallback}. + * + * @method Phaser.Input#addTouchLockCallback + * @param {function} callback - The callback that will be called when a touchstart event is received. + * @param {object} context - The context in which the callback will be called. + * @param {boolean} [onEnd=false] - Will the callback fire on a touchstart/pointerdown (default) or touchend/pointerup event? + */ + addTouchLockCallback: function (callback, context, onEnd) { + + if (onEnd === undefined) { onEnd = false; } + + this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd }); + + }, + + /** + * Removes the callback at the defined index from the {@link #touchLockCallbacks} array + * + * @method Phaser.Input#removeTouchLockCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + * @return {boolean} True if the callback was deleted, otherwise false. + */ + removeTouchLockCallback: function (callback, context) { + + var i = this.touchLockCallbacks.length; + + while (i--) + { + if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context) + { + this.touchLockCallbacks.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Execute any {@link #touchLockCallbacks} of the given type. + * + * @method Phaser.Input#executeTouchLockCallbacks + * @private + * @param {boolean} onEnd - Execute the touchend/pointerup callbacks (true) or the touchstart/pointerdown callbacks (false). Required! + * @param {Event} event - The native event from the browser. + */ + executeTouchLockCallbacks: function (onEnd, event) { + var i = this.touchLockCallbacks.length; + + while (i--) + { + var cb = this.touchLockCallbacks[i]; + + if (cb.onEnd === onEnd && cb.callback.call(cb.context, this, event)) + { + this.touchLockCallbacks.splice(i, 1); + } + } + }, + + /** + * Removes the callback from the Phaser.Input.moveCallbacks array. + * + * @method Phaser.Input#deleteMoveCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + */ + deleteMoveCallback: function (callback, context) { + + var i = this.moveCallbacks.length; + + while (i--) + { + if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context) + { + this.moveCallbacks.splice(i, 1); + return; + } + } + + }, + + /** + * Add a new Pointer object to the Input Manager. + * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. + * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). + * + * @method Phaser.Input#addPointer + * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. + */ + addPointer: function () { + + if (this.pointers.length >= Phaser.Input.MAX_POINTERS) + { + console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached."); + return null; + } + + var id = this.pointers.length + 1; + var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.CONTACT); + + this.pointers.push(pointer); + this['pointer' + id] = pointer; + + return pointer; + + }, + + /** + * Updates the Input Manager. Called by the core Game loop. + * + * @method Phaser.Input#update + * @protected + */ + update: function () { + + if (this.keyboard) + { + this.keyboard.update(); + } + + if (this.pollRate > 0 && this._pollCounter < this.pollRate) + { + this._pollCounter++; + return; + } + + this.speed.x = this.position.x - this._oldPosition.x; + this.speed.y = this.position.y - this._oldPosition.y; + + this._oldPosition.copyFrom(this.position); + this.mousePointer.update(); + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].update(); + } + + this._pollCounter = 0; + + }, + + /** + * Update method while paused. + * + * @method Phaser.Input#pauseUpdate + * @private + */ + pauseUpdate: function () { + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + }, + + /** + * Reset all of the Pointers and Input states. + * + * The optional `hard` parameter will reset any events or callbacks that may be bound. + * Input.reset is called automatically during a State change or if a game loses focus / visibility. + * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. + * + * @method Phaser.Input#reset + * @public + * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. + */ + reset: function (hard) { + + if (!this.game.isBooted || this.resetLocked) + { + return; + } + + if (hard === undefined) { hard = false; } + + this.mousePointer.reset(); + + if (this.keyboard) + { + this.keyboard.reset(hard); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].reset(); + } + + if (this.game.canvas.style.cursor !== 'none') + { + this.game.canvas.style.cursor = ''; + } + + if (hard) + { + this.onDown.dispose(); + this.onUp.dispose(); + this.onTap.dispose(); + this.onHold.dispose(); + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + this.moveCallbacks = []; + } + + this._pollCounter = 0; + + }, + + /** + * Resets the speed and old position properties. + * + * @method Phaser.Input#resetSpeed + * @param {number} x - Sets the oldPosition.x value. + * @param {number} y - Sets the oldPosition.y value. + */ + resetSpeed: function (x, y) { + + this._oldPosition.setTo(x, y); + this.speed.setTo(0, 0); + + }, + + /** + * Find the first free Pointer object and start it, passing in the event data. + * This is called automatically by Phaser.Touch and Phaser.MSPointer. + * + * @method Phaser.Input#startPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. + */ + startPointer: function (event) { + + if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers) + { + return null; + } + + if (!this.pointer1.active) + { + return this.pointer1.start(event); + } + + if (!this.pointer2.active) + { + return this.pointer2.start(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (!pointer.active) + { + return pointer.start(event); + } + } + + return null; + + }, + + /** + * Updates the matching Pointer object, passing in the event data. + * This is called automatically and should not normally need to be invoked. + * + * @method Phaser.Input#updatePointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. + */ + updatePointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.move(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.move(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.move(event); + } + } + + return null; + + }, + + /** + * Stops the matching Pointer object, passing in the event data. + * + * @method Phaser.Input#stopPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. + */ + stopPointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.stop(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.stop(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.stop(event); + } + } + + return null; + + }, + + /** + * Returns the total number of active pointers, not exceeding the specified limit + * + * @name Phaser.Input#countActivePointers + * @private + * @property {integer} [limit=(max pointers)] - Stop counting after this. + * @return {integer} The number of active pointers, or limit - whichever is less. + */ + countActivePointers: function (limit) { + + if (limit === undefined) { limit = this.pointers.length; } + + var count = limit; + + for (var i = 0; i < this.pointers.length && count > 0; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active) + { + count--; + } + } + + return (limit - count); + + }, + + /** + * Get the first Pointer with the given active state. + * + * @method Phaser.Input#getPointer + * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. + */ + getPointer: function (isActive) { + + if (isActive === undefined) { isActive = false; } + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active === isActive) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `identifier` property matches the given identifier value. + * + * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down, and is not fixed once set. + * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. + * + * @method Phaser.Input#getPointerFromIdentifier + * @param {number} identifier - The Pointer.identifier value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromIdentifier: function (identifier) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.identifier === identifier) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `pointerId` property matches the given value. + * + * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down if the browser recycles it. + * + * @method Phaser.Input#getPointerFromId + * @param {number} pointerId - The `pointerId` (not 'id') value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromId: function (pointerId) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.pointerId === pointerId) + { + return pointer; + } + } + + return null; + + }, + + /** + * This will return the local coordinates of the specified displayObject based on the given Pointer. + * + * @method Phaser.Input#getLocalPosition + * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. + * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. + * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. + */ + getLocalPosition: function (displayObject, pointer, output) { + + if (output === undefined) { output = new Phaser.Point(); } + + var wt = displayObject.worldTransform; + var id = 1 / (wt.a * wt.d + wt.c * -wt.b); + + return output.setTo( + wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id, + wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id + ); + + }, + + /** + * Tests if the pointer hits the given object. + * + * @method Phaser.Input#hitTest + * @param {DisplayObject} displayObject - The displayObject to test for a hit. + * @param {Phaser.Pointer} pointer - The pointer to use for the test. + * @param {Phaser.Point} localPoint - The local translated point. + */ + hitTest: function (displayObject, pointer, localPoint) { + + if (!displayObject.worldVisible) + { + return false; + } + + this.getLocalPosition(displayObject, pointer, this._localPoint); + + localPoint.copyFrom(this._localPoint); + + if (displayObject.hitArea && displayObject.hitArea.contains) + { + return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y)); + } + else if (Phaser.Creature && displayObject instanceof Phaser.Creature) { + var width = Math.abs(displayObject.width); + var height = Math.abs(displayObject.height); + var x1 = displayObject.x - (width * displayObject.anchorX); + + if (this.game.camera.x + pointer.x >= x1 && this.game.camera.x + pointer.x < x1 + width) + { + var y1 = displayObject.y - (height * displayObject.anchorY); + + if (this.game.camera.y + pointer.y >= y1 && this.game.camera.y + pointer.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.TileSprite) + { + var width = displayObject.width; + var height = displayObject.height; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof PIXI.Sprite) + { + var width = displayObject.texture.frame.width / displayObject.texture.baseTexture.resolution; + var height = displayObject.texture.frame.height / displayObject.texture.baseTexture.resolution; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.Graphics) + { + for (var i = 0; i < displayObject.graphicsData.length; i++) + { + var data = displayObject.graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // Only deal with fills.. + if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y)) + { + return true; + } + } + } + + // Didn't hit the parent, does it have any children? + + for (var i = 0; i < displayObject.children.length; i++) + { + if (this.hitTest(displayObject.children[i], pointer, localPoint)) + { + return true; + } + } + + return false; + }, + + /** + * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. + * + * @method Phaser.Input#onClickTrampoline + * @private + */ + onClickTrampoline: function () { + + // It might not always be the active pointer, but this does work on + // Desktop browsers (read: IE) with Mouse or MSPointer input. + this.activePointer.processClickTrampolines(); + + } + +}; + +Phaser.Input.prototype.constructor = Phaser.Input; + +/** +* The X coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. +* @name Phaser.Input#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Input.prototype, "x", { + + get: function () { + return this._x; + }, + + set: function (value) { + this._x = Math.floor(value); + } + +}); + +/** +* The Y coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. +* @name Phaser.Input#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Input.prototype, "y", { + + get: function () { + return this._y; + }, + + set: function (value) { + this._y = Math.floor(value); + } + +}); + +/** +* True if the Input is currently poll rate locked. +* @name Phaser.Input#pollLocked +* @property {boolean} pollLocked +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "pollLocked", { + + get: function () { + return (this.pollRate > 0 && this._pollCounter < this.pollRate); + } + +}); + +/** +* The total number of inactive Pointers. +* @name Phaser.Input#totalInactivePointers +* @property {number} totalInactivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", { + + get: function () { + return this.pointers.length - this.countActivePointers(); + } + +}); + +/** +* The total number of active Pointers, not counting the mouse pointer. +* @name Phaser.Input#totalActivePointers +* @property {integers} totalActivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", { + + get: function () { + return this.countActivePointers(); + } + +}); + +/** +* The world X coordinate of the most recently active pointer. +* @name Phaser.Input#worldX +* @property {number} worldX - The world X coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldX", { + + get: function () { + return this.game.camera.view.x + this.x; + } + +}); + +/** +* The world Y coordinate of the most recently active pointer. +* @name Phaser.Input#worldY +* @property {number} worldY - The world Y coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldY", { + + get: function () { + return this.game.camera.view.y + this.y; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Mouse class is responsible for handling all aspects of mouse interaction with the browser. +* +* It captures and processes mouse events that happen on the game canvas object. +* It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released +* when not over the game. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object +* which normalises all game input for you, including accurate button handling. +* +* @class Phaser.Mouse +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Mouse = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down. + */ + this.mouseDownCallback = null; + + /** + * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state. + */ + this.mouseUpCallback = null; + + /** + * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas. + */ + this.mouseOutCallback = null; + + /** + * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). + */ + this.mouseOverCallback = null; + + /** + * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used. + */ + this.mouseWheelCallback = null; + + /** + * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + */ + this.capture = false; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + * @default + */ + this.button = -1; + + /** + * The direction of the _last_ mousewheel usage 1 for up -1 for down. + * @property {number} wheelDelta + */ + this.wheelDelta = 0; + + /** + * Mouse input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true. + * @default + */ + this.locked = false; + + /** + * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas. + * @default + */ + this.stopOnGameOut = false; + + /** + * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state. + * @default + */ + this.pointerLock = new Phaser.Signal(); + + /** + * The browser mouse DOM event. Will be null if no mouse event has ever been received. + * Access this property only inside a Mouse event handler and do not keep references to it. + * @property {MouseEvent|null} event + * @default + */ + this.event = null; + + /** + * @property {function} _onMouseDown - Internal event handler reference. + * @private + */ + this._onMouseDown = null; + + /** + * @property {function} _onMouseMove - Internal event handler reference. + * @private + */ + this._onMouseMove = null; + + /** + * @property {function} _onMouseUp - Internal event handler reference. + * @private + */ + this._onMouseUp = null; + + /** + * @property {function} _onMouseOut - Internal event handler reference. + * @private + */ + this._onMouseOut = null; + + /** + * @property {function} _onMouseOver - Internal event handler reference. + * @private + */ + this._onMouseOver = null; + + /** + * @property {function} _onMouseWheel - Internal event handler reference. + * @private + */ + this._onMouseWheel = null; + + /** + * Wheel proxy event object, if required. Shared for all wheel events for this mouse. + * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent + * @private + */ + this._wheelEvent = null; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.NO_BUTTON = -1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.LEFT_BUTTON = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.MIDDLE_BUTTON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.RIGHT_BUTTON = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.BACK_BUTTON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.FORWARD_BUTTON = 4; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_UP = 1; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_DOWN = -1; + +Phaser.Mouse.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Mouse#start + */ + start: function () { + + if (this.game.device.android && this.game.device.chrome === false) + { + // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ... + return; + } + + if (this._onMouseDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onMouseDown = function (event) { + return _this.onMouseDown(event); + }; + + this._onMouseMove = function (event) { + return _this.onMouseMove(event); + }; + + this._onMouseUp = function (event) { + return _this.onMouseUp(event); + }; + + this._onMouseUpGlobal = function (event) { + return _this.onMouseUpGlobal(event); + }; + + this._onMouseOutGlobal = function (event) { + return _this.onMouseOutGlobal(event); + }; + + this._onMouseOut = function (event) { + return _this.onMouseOut(event); + }; + + this._onMouseOver = function (event) { + return _this.onMouseOver(event); + }; + + this._onMouseWheel = function (event) { + return _this.onMouseWheel(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('mousedown', this._onMouseDown, true); + canvas.addEventListener('mousemove', this._onMouseMove, true); + canvas.addEventListener('mouseup', this._onMouseUp, true); + + if (!this.game.device.cocoonJS) + { + window.addEventListener('mouseup', this._onMouseUpGlobal, true); + window.addEventListener('mouseout', this._onMouseOutGlobal, true); + canvas.addEventListener('mouseover', this._onMouseOver, true); + canvas.addEventListener('mouseout', this._onMouseOut, true); + } + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.addEventListener(wheelEvent, this._onMouseWheel, true); + + if (wheelEvent === 'mousewheel') + { + this._wheelEvent = new WheelEventProxy(-1/40, 1); + } + else if (wheelEvent === 'DOMMouseScroll') + { + this._wheelEvent = new WheelEventProxy(1, 1); + } + } + + }, + + /** + * The internal method that handles the mouse down event from the browser. + * @method Phaser.Mouse#onMouseDown + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseDown: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseDownCallback) + { + this.mouseDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.start(event); + + }, + + /** + * The internal method that handles the mouse move event from the browser. + * @method Phaser.Mouse#onMouseMove + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseMoveCallback) + { + this.mouseMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.move(event); + + }, + + /** + * The internal method that handles the mouse up event from the browser. + * @method Phaser.Mouse#onMouseUp + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUp: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.Mouse#onMouseUpGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUpGlobal: function (event) { + + if (!this.input.mousePointer.withinGame) + { + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + }, + + /** + * The internal method that handles the mouse out event from the window. + * + * @method Phaser.Mouse#onMouseOutGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOutGlobal: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (!this.input.enabled || !this.enabled) + { + return; + } + + // If we get a mouseout event from the window then basically + // something serious has gone down, usually along the lines of + // the browser opening a context-menu or similar. + // On OS X Chrome especially this is bad news, as it blocks + // us then getting a mouseup event, so we need to force that through. + // + // No matter what, we must cancel the left and right buttons + + this.input.mousePointer.stop(event); + + // Clear the button states (again?) + this.input.mousePointer.resetButtons(); + + }, + + /** + * The internal method that handles the mouse out event from the browser. + * + * @method Phaser.Mouse#onMouseOut + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (this.mouseOutCallback) + { + this.mouseOutCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.stopOnGameOut) + { + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + this.input.interactiveItems.callAll('_pointerOutHandler', this.input.mousePointer); + + }, + + /** + * The internal method that handles the mouse over event from the browser. + * + * @method Phaser.Mouse#onMouseOver + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = true; + + if (this.mouseOverCallback) + { + this.mouseOverCallback.call(this.callbackContext, event); + } + + }, + + /** + * The internal method that handles the mouse wheel event from the browser. + * + * @method Phaser.Mouse#onMouseWheel + * @param {MouseEvent} event - The native event from the browser. + */ + onMouseWheel: function (event) { + + if (this._wheelEvent) { + event = this._wheelEvent.bindEvent(event); + } + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + // reverse detail for firefox + this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1); + + if (this.mouseWheelCallback) + { + this.mouseWheelCallback.call(this.callbackContext, event); + } + + }, + + /** + * If the browser supports it you can request that the pointer be locked to the browser window. + * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key. + * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'. + * @method Phaser.Mouse#requestPointerLock + */ + requestPointerLock: function () { + + if (this.game.device.pointerLock) + { + var element = this.game.canvas; + + element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; + + element.requestPointerLock(); + + var _this = this; + + this._pointerLockChange = function (event) { + return _this.pointerLockChange(event); + }; + + document.addEventListener('pointerlockchange', this._pointerLockChange, true); + document.addEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true); + } + + }, + + /** + * Internal pointerLockChange handler. + * + * @method Phaser.Mouse#pointerLockChange + * @param {Event} event - The native event from the browser. This gets stored in Mouse.event. + */ + pointerLockChange: function (event) { + + var element = this.game.canvas; + + if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) + { + // Pointer was successfully locked + this.locked = true; + this.pointerLock.dispatch(true, event); + } + else + { + // Pointer was unlocked + this.locked = false; + this.pointerLock.dispatch(false, event); + } + + }, + + /** + * Internal release pointer lock handler. + * @method Phaser.Mouse#releasePointerLock + */ + releasePointerLock: function () { + + document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; + + document.exitPointerLock(); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + }, + + /** + * Stop the event listeners. + * @method Phaser.Mouse#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('mousedown', this._onMouseDown, true); + canvas.removeEventListener('mousemove', this._onMouseMove, true); + canvas.removeEventListener('mouseup', this._onMouseUp, true); + canvas.removeEventListener('mouseover', this._onMouseOver, true); + canvas.removeEventListener('mouseout', this._onMouseOut, true); + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.removeEventListener(wheelEvent, this._onMouseWheel, true); + } + + window.removeEventListener('mouseup', this._onMouseUpGlobal, true); + window.removeEventListener('mouseout', this._onMouseOutGlobal, true); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + } + +}; + +Phaser.Mouse.prototype.constructor = Phaser.Mouse; + +/* jshint latedef:nofunc */ +/** +* A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel' +* events to 'wheel'-like events. +* +* See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode. +* +* @method Phaser.Mouse#WheelEventProxy +* @private +* @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. +* @param {integer} deltaMode - The reported delta mode. +*/ +function WheelEventProxy (scaleFactor, deltaMode) { + + /** + * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. + * @private + */ + this._scaleFactor = scaleFactor; + + /** + * @property {number} _deltaMode - The reported delta mode. + * @private + */ + this._deltaMode = deltaMode; + + /** + * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit. + * @private + */ + this.originalEvent = null; + +} + +WheelEventProxy.prototype = {}; +WheelEventProxy.prototype.constructor = WheelEventProxy; + +WheelEventProxy.prototype.bindEvent = function (event) { + + // Generate stubs automatically + if (!WheelEventProxy._stubsGenerated && event) + { + var makeBinder = function (name) { + + return function () { + var v = this.originalEvent[name]; + return typeof v !== 'function' ? v : v.bind(this.originalEvent); + }; + + }; + + for (var prop in event) + { + if (!(prop in WheelEventProxy.prototype)) + { + Object.defineProperty(WheelEventProxy.prototype, prop, { + get: makeBinder(prop) + }); + } + } + WheelEventProxy._stubsGenerated = true; + } + + this.originalEvent = event; + return this; + +}; + +Object.defineProperties(WheelEventProxy.prototype, { + "type": { value: "wheel" }, + "deltaMode": { get: function () { return this._deltaMode; } }, + "deltaY": { + get: function () { + return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0; + } + }, + "deltaX": { + get: function () { + return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0; + } + }, + "deltaZ": { value: 0 } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The MSPointer class handles {@link https://developers.google.com/web/updates/2016/10/pointer-events Pointer-event} interactions with the game via a dedicated {@link Phaser.Pointer}. (It's named after the nonstandard {@link https://msdn.microsoft.com/library/hh673557(v=vs.85).aspx MSPointerEvent} since that was the first browser implementation.) +* +* It's {@link http://caniuse.com/#feat=pointer currently supported in IE 10+, Edge, Chrome (including Android), and Opera}. +* +* You should not normally access this class directly, but instead use a {@link Phaser.Pointer} object which +* normalises all game input for you including accurate button handling. +* +* Please note that at the current time of writing Phaser does not yet support chorded button interactions: +* http://www.w3.org/TR/pointerevents/#chorded-button-interactions +* +* You can disable Phaser's use of Pointer Events by either of two ways: +* +* ```javascript +* // **Before** `new Phaser.Game(…)`: +* Phaser.Device.onInitialized.add(function () { +* this.mspointer = false; +* }); +* ``` +* +* ```javascript +* // Once, in the earliest State `init` or `create` callback (e.g., Boot): +* this.input.mspointer.stop(); +* ``` +* +* @class Phaser.MSPointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.MSPointer = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called (defaults to game). + */ + this.callbackContext = this.game; + + /** + * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event. + */ + this.pointerDownCallback = null; + + /** + * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event. + */ + this.pointerMoveCallback = null; + + /** + * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event. + */ + this.pointerUpCallback = null; + + /** + * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, canceling the corresponding MouseEvent or TouchEvent. + */ + this.capture = true; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + */ + this.button = -1; + + /** + * The most recent PointerEvent from the browser. Will be null if no event has ever been received. + * Access this property only inside a Pointer event handler and do not keep references to it. + * @property {MSPointerEvent|PointerEvent|null} event + * @default + */ + this.event = null; + + /** + * PointerEvent input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {function} _onMSPointerDown - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerDown = null; + + /** + * @property {function} _onMSPointerMove - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerMove = null; + + /** + * @property {function} _onMSPointerUp - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUp = null; + + /** + * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUpGlobal = null; + + /** + * @property {function} _onMSPointerOut - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOut = null; + + /** + * @property {function} _onMSPointerOver - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOver = null; + +}; + +Phaser.MSPointer.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.MSPointer#start + */ + start: function () { + + if (this._onMSPointerDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + if (this.game.device.mspointer) + { + this._onMSPointerDown = function (event) { + return _this.onPointerDown(event); + }; + + this._onMSPointerMove = function (event) { + return _this.onPointerMove(event); + }; + + this._onMSPointerUp = function (event) { + return _this.onPointerUp(event); + }; + + this._onMSPointerUpGlobal = function (event) { + return _this.onPointerUpGlobal(event); + }; + + this._onMSPointerOut = function (event) { + return _this.onPointerOut(event); + }; + + this._onMSPointerOver = function (event) { + return _this.onPointerOver(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.addEventListener('pointerdown', this._onMSPointerDown, false); + canvas.addEventListener('pointermove', this._onMSPointerMove, false); + canvas.addEventListener('pointerup', this._onMSPointerUp, false); + + canvas.style['-ms-content-zooming'] = 'none'; + canvas.style['-ms-touch-action'] = 'none'; + + if (!this.game.device.cocoonJS) + { + window.addEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.addEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.addEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.addEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.addEventListener('pointerover', this._onMSPointerOver, true); + canvas.addEventListener('pointerout', this._onMSPointerOut, true); + } + } + + }, + + /** + * The function that handles the PointerDown event. + * + * @method Phaser.MSPointer#onPointerDown + * @param {PointerEvent} event - The native DOM event. + */ + onPointerDown: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerDownCallback) + { + this.pointerDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.start(event); + } + else + { + this.input.startPointer(event); + } + + }, + + /** + * The function that handles the PointerMove event. + * @method Phaser.MSPointer#onPointerMove + * @param {PointerEvent} event - The native DOM event. + */ + onPointerMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerMoveCallback) + { + this.pointerMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.move(event); + } + else + { + this.input.updatePointer(event); + } + + }, + + /** + * The function that handles the PointerUp event. + * @method Phaser.MSPointer#onPointerUp + * @param {PointerEvent} event - The native DOM event. + */ + onPointerUp: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerUpCallback) + { + this.pointerUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.stop(event); + } + else + { + this.input.stopPointer(event); + } + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.MSPointer#onPointerUpGlobal + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerUpGlobal: function (event) { + + if ((event.pointerType === 'mouse' || event.pointerType === 0x00000004) && !this.input.mousePointer.withinGame) + { + this.onPointerUp(event); + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer && pointer.withinGame) + { + this.onPointerUp(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = false; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = false; + } + } + + if (this.input.mouse.mouseOutCallback) + { + this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.input.mouse.stopOnGameOut) + { + event['identifier'] = 0; + + if (pointer) + { + pointer.stop(event); + } + else + { + this.input.mousePointer.stop(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = true; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = true; + } + } + + if (this.input.mouse.mouseOverCallback) + { + this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext, event); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.MSPointer#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.removeEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.removeEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.removeEventListener('pointerdown', this._onMSPointerDown, false); + canvas.removeEventListener('pointermove', this._onMSPointerMove, false); + canvas.removeEventListener('pointerup', this._onMSPointerUp, false); + + window.removeEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.removeEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.removeEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('pointerover', this._onMSPointerOver, true); + canvas.removeEventListener('pointerout', this._onMSPointerOut, true); + + } + +}; + +Phaser.MSPointer.prototype.constructor = Phaser.MSPointer; + +/** +* @author Richard Davey +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. +* +* For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, +* middle button and advanced buttons like back and forward. +* +* Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. +* +* On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. +* +* At the time of writing this there are device limitations you should be aware of: +* +* - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions +* (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, +* even when they are pressed. +* - On Linux (GTK), the 4th button and the 5th button are not supported. +* - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. +* +* @class Phaser.DeviceButton +* @constructor +* @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad. +* @param {number} buttonCode - The button code this DeviceButton is responsible for. +*/ +Phaser.DeviceButton = function (parent, buttonCode) { + + /** + * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = parent.game; + + /** + * @property {object} event - The DOM event that caused the change in button state. + * @default + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the button. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the button. + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - The timestamp when the button was last pressed down. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - The timestamp when the button was last released. + * @default + */ + this.timeUp = 0; + + /** + * Gamepad only. + * If a button is held down this holds down the number of times the button has 'repeated'. + * @property {number} repeats + * @default + */ + this.repeats = 0; + + /** + * True if the alt key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} altKey + * @default + */ + this.altKey = false; + + /** + * True if the shift key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} shiftKey + * @default + */ + this.shiftKey = false; + + /** + * True if the control key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} ctrlKey + * @default + */ + this.ctrlKey = false; + + /** + * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. + * @default + */ + this.value = 0; + + /** + * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. + */ + this.buttonCode = buttonCode; + + /** + * This Signal is dispatched every time this DeviceButton is pressed down. + * It is only dispatched once (until the button is released again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onDown + */ + this.onDown = new Phaser.Signal(); + + /** + * This Signal is dispatched every time this DeviceButton is released from a down state. + * It is only dispatched once (until the button is pressed again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onUp + */ + this.onUp = new Phaser.Signal(); + + /** + * Gamepad only. + * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onFloat + */ + this.onFloat = new Phaser.Signal(); + +}; + +Phaser.DeviceButton.prototype = { + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button down state. + * + * @method Phaser.DeviceButton#start + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + start: function (event, value) { + + if (this.isDown) + { + return; + } + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onDown.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button up state. + * + * @method Phaser.DeviceButton#stop + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + stop: function (event, value) { + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onUp.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer. + * Starts or stops button based on condition. + * + * @method Phaser.DeviceButton#startStop + * @protected + * @param {boolean} [condition] - The condition that decides between start or stop. + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + startStop: function (condition, event, value) { + + if (condition) + { + this.start(event, value); + } + else + { + this.stop(event, value); + } + + }, + + /** + * Called automatically by Phaser.SinglePad. + * + * @method Phaser.DeviceButton#padFloat + * @protected + * @param {number} value - Button value + */ + padFloat: function (value) { + + this.isDown = false; + this.isUp = false; + + this.value = value; + + this.onFloat.dispatch(this, value); + + }, + + /** + * Returns the "just pressed" state of this button. + * Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justPressed + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (duration) { + + duration = duration || 250; + + return (this.isDown && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * Returns the "just released" state of this button. + * Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justReleased + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (duration) { + + duration = duration || 250; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. + * + * @method Phaser.DeviceButton#reset + */ + reset: function () { + + this.isDown = false; + this.isUp = true; + + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.altKey = false; + this.shiftKey = false; + this.ctrlKey = false; + + }, + + /** + * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals + * and clears the parent and game references. + * + * @method Phaser.DeviceButton#destroy + */ + destroy: function () { + + this.onDown.dispose(); + this.onUp.dispose(); + this.onFloat.dispose(); + + this.parent = null; + this.game = null; + + } + +}; + +Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton; + +/** +* How long the button has been held down for in milliseconds. +* If not currently down it returns -1. +* +* @name Phaser.DeviceButton#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.DeviceButton.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. +* +* @class Phaser.Pointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. +* @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or CONTACT. +*/ +Phaser.Pointer = function (game, id, pointerMode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. + */ + this.id = id; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINTER; + + /** + * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps. + * @default + */ + this.exists = true; + + /** + * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.identifier = 0; + + /** + * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. + * @default + */ + this.pointerId = null; + + /** + * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer. + */ + this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT); + + /** + * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.target = null; + + /** + * The button property of the most recent DOM event when this Pointer is started. + * You should not rely on this value for accurate button detection, instead use the Pointer properties + * `leftButton`, `rightButton`, `middleButton` and so on. + * @property {any} button + * @default + */ + this.button = null; + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * @property {Phaser.DeviceButton} leftButton + * @default + */ + this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} middleButton + * @default + */ + this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} rightButton + * @default + */ + this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} backButton + * @default + */ + this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} forwardButton + * @default + */ + this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON); + + /** + * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} eraserButton + * @default + */ + this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON); + + /** + * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event. + * @private + * @default + */ + this._holdSent = false; + + /** + * @property {array} _history - Local private variable storing the short-term history of pointer movements. + * @private + */ + this._history = []; + + /** + * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur. + * @private + */ + this._nextDrop = 0; + + /** + * @property {boolean} _stateReset - Monitor events outside of a state reset loop. + * @private + */ + this._stateReset = false; + + /** + * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false. + */ + this.withinGame = false; + + /** + * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientX = -1; + + /** + * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientY = -1; + + /** + * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document. + */ + this.pageX = -1; + + /** + * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document. + */ + this.pageY = -1; + + /** + * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen. + */ + this.screenX = -1; + + /** + * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen. + */ + this.screenY = -1; + + /** + * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementX = 0; + + /** + * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementY = 0; + + /** + * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementX = 0; + + /** + * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementY = 0; + + /** + * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.x = -1; + + /** + * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.y = -1; + + /** + * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false. + */ + this.isMouse = (id === 0); + + /** + * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. + * @property {boolean} isDown + * @default + */ + this.isDown = false; + + /** + * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. + * @property {boolean} isUp + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen. + * @default + */ + this.timeUp = 0; + + /** + * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked. + * @default + */ + this.previousTapTime = 0; + + /** + * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen. + * @default + */ + this.totalTouches = 0; + + /** + * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event. + * @default + */ + this.msSinceLastClick = Number.MAX_VALUE; + + /** + * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging. + * @default + */ + this.targetObject = null; + + /** + * This array is erased and re-populated every time this Pointer is updated. It contains references to all + * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be + * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over + * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset + * every frame. + * @property {array} interactiveCandidates + * @default + */ + this.interactiveCandidates = []; + + /** + * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active. + * @default + */ + this.active = false; + + /** + * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. + * @default + */ + this.dirty = false; + + /** + * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display. + */ + this.position = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. + */ + this.positionDown = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released. + */ + this.positionUp = new Phaser.Point(); + + /** + * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. + * The Circle size is 44px (Apples recommended "finger tip" size). + * @property {Phaser.Circle} circle + */ + this.circle = new Phaser.Circle(0, 0, 44); + + /** + * Click trampolines associated with this pointer. See `addClickTrampoline`. + * @property {object[]|null} _clickTrampolines + * @private + */ + this._clickTrampolines = null; + + /** + * When the Pointer has click trampolines the last target object is stored here + * so it can be used to check for validity of the trampoline in a post-Up/'stop'. + * @property {object} _trampolineTargetObject + * @private + */ + this._trampolineTargetObject = null; + +}; + +/** +* No buttons at all. +* @constant +* @type {number} +*/ +Phaser.Pointer.NO_BUTTON = 0; + +/** +* The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. +* @constant +* @type {number} +*/ +Phaser.Pointer.LEFT_BUTTON = 1; + +/** +* The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. +* @constant +* @type {number} +*/ +Phaser.Pointer.RIGHT_BUTTON = 2; + +/** +* The Middle Mouse button. +* @constant +* @type {number} +*/ +Phaser.Pointer.MIDDLE_BUTTON = 4; + +/** +* The X1 button. This is typically the mouse Back button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.BACK_BUTTON = 8; + +/** +* The X2 button. This is typically the mouse Forward button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.FORWARD_BUTTON = 16; + +/** +* The Eraser pen button on PointerEvent supported devices only. +* @constant +* @type {number} +*/ +Phaser.Pointer.ERASER_BUTTON = 32; + +Phaser.Pointer.prototype = { + + /** + * Resets the states of all the button booleans. + * + * @method Phaser.Pointer#resetButtons + * @protected + */ + resetButtons: function () { + + this.isDown = false; + this.isUp = true; + + if (this.isMouse) + { + this.leftButton.reset(); + this.middleButton.reset(); + this.rightButton.reset(); + this.backButton.reset(); + this.forwardButton.reset(); + this.eraserButton.reset(); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsDown + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsDown: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.start(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.start(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.start(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.start(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.start(event); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsUp + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUp: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.stop(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.stop(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.stop(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.stop(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.stop(event); + } + + }, + + /** + * Called by updateButtons. + * + * @method Phaser.Pointer#processButtonsUpDown + * @private + * @param {integer} buttons - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons MouseEvent#buttons} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUpDown: function (buttons, event) { + + var down = (event.type.toLowerCase().substr(-4) === 'down'); + var move = (event.type.toLowerCase().substr(-4) === 'move'); + + if (buttons !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && buttons === 1 && event.ctrlKey) + { + buttons = 2; + } + + // Note: These are bitwise checks, not booleans + this.leftButton.startStop(Phaser.Pointer.LEFT_BUTTON & buttons, event); + this.rightButton.startStop(Phaser.Pointer.RIGHT_BUTTON & buttons, event); + this.middleButton.startStop(Phaser.Pointer.MIDDLE_BUTTON & buttons, event); + this.backButton.startStop(Phaser.Pointer.BACK_BUTTON & buttons, event); + this.forwardButton.startStop(Phaser.Pointer.FORWARD_BUTTON & buttons, event); + this.eraserButton.startStop(Phaser.Pointer.ERASER_BUTTON & buttons, event); + } + else + { + // No buttons property (like Safari on OSX when using a trackpad) + // Attempt to use event.button property or fallback to default + if (event.button !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && event.ctrlKey && event.button === 0) + { + this.rightButton.start(event); + } + else + { + if (down) + { + this.processButtonsDown(event.button, event); + } + else if (!move) + { + this.processButtonsUp(event.button, event); + } + } + } + else + { + if (down) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (event.ctrlKey) + { + this.rightButton.start(event); + } + else + { + this.leftButton.start(event); + } + } + else + { + this.leftButton.stop(event); + this.rightButton.stop(event); + } + } + } + + }, + + /** + * Called when the event.buttons property changes from zero. + * Contains a button bitmask. + * + * @method Phaser.Pointer#updateButtons + * @protected + * @param {MouseEvent} event - The DOM event. + */ + updateButtons: function (event) { + + this.button = event.button; + this.processButtonsUpDown(event.buttons, event); + + this.isUp = true; + this.isDown = false; + + if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown) + { + this.isUp = false; + this.isDown = true; + } + + }, + + /** + * Called when the Pointer is pressed onto the touchscreen. + * @method Phaser.Pointer#start + * @param {any} event - The DOM event from the browser. + */ + start: function (event) { + + var input = this.game.input; + + if (event['pointerId']) + { + this.pointerId = event.pointerId; + } + + this.identifier = event.identifier; + this.target = event.target; + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = true; + this.isUp = false; + } + + this.active = true; + this.withinGame = true; + this.dirty = false; + + this._history = []; + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + // Work out how long it has been since the last click + this.msSinceLastClick = this.game.time.time - this.timeDown; + this.timeDown = this.game.time.time; + this._holdSent = false; + + // This sets the x/y and other local values + this.move(event, true); + + // x and y are the old values here? + this.positionDown.setTo(this.x, this.y); + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.x = this.x; + input.y = this.y; + input.position.setTo(this.x, this.y); + input.onDown.dispatch(this, event); + input.resetSpeed(this.x, this.y); + } + + this._stateReset = false; + + this.totalTouches++; + + if (this.targetObject !== null) + { + this.targetObject._touchedHandler(this); + } + + return this; + + }, + + /** + * Called by the Input Manager. + * @method Phaser.Pointer#update + */ + update: function () { + + var input = this.game.input; + + if (this.active) + { + // Force a check? + if (this.dirty) + { + if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(false); + } + + this.dirty = false; + } + + if (this._holdSent === false && this.duration >= input.holdRate) + { + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onHold.dispatch(this); + } + + this._holdSent = true; + } + + // Update the droppings history + if (input.recordPointerHistory && this.game.time.time >= this._nextDrop) + { + this._nextDrop = this.game.time.time + input.recordRate; + + this._history.push({ + x: this.position.x, + y: this.position.y + }); + + if (this._history.length > input.recordLimit) + { + this._history.shift(); + } + } + } + + }, + + /** + * Called when the Pointer is moved. + * + * @method Phaser.Pointer#move + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + * @param {boolean} [fromClick=false] - Was this called from the click event? + */ + move: function (event, fromClick) { + + var input = this.game.input; + + if (input.pollLocked) + { + return; + } + + if (fromClick === undefined) { fromClick = false; } + + if (event.button !== undefined) + { + this.button = event.button; + } + + if (this.isMouse) + { + this.updateButtons(event); + } + + 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 && 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.scale.offset.x) * input.scale.x; + this.y = (this.pageY - this.game.scale.offset.y) * input.scale.y; + + this.position.setTo(this.x, this.y); + this.circle.x = this.x; + this.circle.y = this.y; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.activePointer = this; + input.x = this.x; + input.y = this.y; + input.position.setTo(input.x, input.y); + input.circle.x = input.x; + input.circle.y = input.y; + } + + this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY); + + var i = input.moveCallbacks.length; + + while (i--) + { + input.moveCallbacks[i].callback.call(input.moveCallbacks[i].context, this, this.x, this.y, fromClick); + } + + // Easy out if we're dragging something and it still exists + if (this.targetObject !== null && (!this.game.paused || this.targetObject.noPause) && this.targetObject.isDragged === true) + { + if (this.targetObject.update(this) === false) + { + this.targetObject = null; + } + } + else if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(fromClick); + } + + return this; + + }, + + /** + * Process all interactive objects to find out which ones were updated in the recent Pointer move. + * + * @method Phaser.Pointer#processInteractiveObjects + * @protected + * @param {boolean} [fromClick=false] - Was this called from the click event? + * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. + */ + processInteractiveObjects: function (fromClick) { + + // Work out which object is on the top + var highestRenderOrderID = 0; + var highestInputPriorityID = -1; + var candidateTarget = null; + + // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID + // We know they'll be valid for input detection but not which is the top just yet + + var currentNode = this.game.input.interactiveItems.first; + + this.interactiveCandidates = []; + + while (currentNode) + { + // Reset checked status + currentNode.checked = false; + + if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false) && (!this.game.paused || currentNode.sprite.noPause)) + { + // Flag it as checked so we don't re-scan it on the next phase + currentNode.checked = true; + + if ((fromClick && currentNode.checkPointerDown(this, true)) || + (!fromClick && currentNode.checkPointerOver(this, true))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID + // because if their ID is lower anyway then we can just automatically discount them + // (A node that was previously checked did not request a pixel-perfect check.) + + currentNode = this.game.input.interactiveItems.first; + + while (currentNode) + { + if (!currentNode.checked && + currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true)) + { + if ((fromClick && currentNode.checkPointerDown(this, false)) || + (!fromClick && currentNode.checkPointerOver(this, false))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + if (this.game.input.customCandidateHandler) + { + candidateTarget = this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext, this, this.interactiveCandidates, candidateTarget); + } + + this.swapTarget(candidateTarget, false); + + return (this.targetObject !== null); + + }, + + /** + * This will change the `Pointer.targetObject` object to be the one provided. + * + * This allows you to have fine-grained control over which object the Pointer is targeting. + * + * Note that even if you set a new Target here, it is still able to be replaced by any other valid + * target during the next Pointer update. + * + * @method Phaser.Pointer#swapTarget + * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. + * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. + */ + swapTarget: function (newTarget, silent) { + + if (silent === undefined) { silent = false; } + + // Now we know the top-most item (if any) we can process it + if (newTarget === null) + { + // The pointer isn't currently over anything, check if we've got a lingering previous target + if (this.targetObject) + { + this.targetObject._pointerOutHandler(this, silent); + this.targetObject = null; + } + } + else + { + if (this.targetObject === null) + { + // And now set the new one + this.targetObject = newTarget; + newTarget._pointerOverHandler(this, silent); + } + else + { + // We've got a target from the last update + if (this.targetObject === newTarget) + { + // Same target as before, so update it + if (newTarget.update(this) === false) + { + this.targetObject = null; + } + } + else + { + // The target has changed, so tell the old one we've left it + this.targetObject._pointerOutHandler(this, silent); + + // And now set the new one + this.targetObject = newTarget; + this.targetObject._pointerOverHandler(this, silent); + } + } + } + + }, + + /** + * Called when the Pointer leaves the target area. + * + * @method Phaser.Pointer#leave + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + leave: function (event) { + + this.withinGame = false; + this.move(event, false); + + }, + + /** + * Called when the Pointer leaves the touchscreen. + * + * @method Phaser.Pointer#stop + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + stop: function (event) { + + var input = this.game.input; + + if (this._stateReset && this.withinGame) + { + event.preventDefault(); + return; + } + + this.timeUp = this.game.time.time; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onUp.dispatch(this, event); + + // Was it a tap? + if (this.duration >= 0 && this.duration <= input.tapRate) + { + // Was it a double-tap? + if (this.timeUp - this.previousTapTime < input.doubleTapRate) + { + // Yes, let's dispatch the signal then with the 2nd parameter set to true + input.onTap.dispatch(this, true); + } + else + { + // Wasn't a double-tap, so dispatch a single tap signal + input.onTap.dispatch(this, false); + } + + this.previousTapTime = this.timeUp; + } + } + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = false; + this.isUp = true; + } + + // Mouse is always active + if (this.id > 0) + { + this.active = false; + } + + this.withinGame = this.game.scale.bounds.contains(event.pageX, event.pageY); + this.pointerId = null; + this.identifier = null; + + this.positionUp.setTo(this.x, this.y); + + if (this.isMouse === false) + { + input.currentPointers--; + } + + input.interactiveItems.callAll('_releasedHandler', this); + + if (this._clickTrampolines) + { + this._trampolineTargetObject = this.targetObject; + } + + this.targetObject = null; + + return this; + + }, + + /** + * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. + * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. + * @method Phaser.Pointer#justPressed + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate. + * @return {boolean} true if the Pointer was pressed down within the duration given. + */ + justPressed: function (duration) { + + duration = duration || this.game.input.justPressedRate; + + return (this.isDown === true && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. + * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. + * @method Phaser.Pointer#justReleased + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate. + * @return {boolean} true if the Pointer was released within the duration given. + */ + justReleased: function (duration) { + + duration = duration || this.game.input.justReleasedRate; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Add a click trampoline to this pointer. + * + * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily + * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen + * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. + * + * This is used internally by the ScaleManager; click trampoline usage is uncommon. + * Click trampolines can only be added to pointers that are currently down. + * + * @method Phaser.Pointer#addClickTrampoline + * @protected + * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer. + * @param {function} callback - Callback to run/trampoline. + * @param {object} callbackContext - Context of the callback. + * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array. + */ + addClickTrampoline: function (name, callback, callbackContext, callbackArgs) { + + if (!this.isDown) + { + return; + } + + var trampolines = (this._clickTrampolines = this._clickTrampolines || []); + + for (var i = 0; i < trampolines.length; i++) + { + if (trampolines[i].name === name) + { + trampolines.splice(i, 1); + break; + } + } + + trampolines.push({ + name: name, + targetObject: this.targetObject, + callback: callback, + callbackContext: callbackContext, + callbackArgs: callbackArgs + }); + + }, + + /** + * Fire all click trampolines for which the pointers are still referring to the registered object. + * @method Phaser.Pointer#processClickTrampolines + * @private + */ + processClickTrampolines: function () { + + var trampolines = this._clickTrampolines; + + if (!trampolines) + { + return; + } + + for (var i = 0; i < trampolines.length; i++) + { + var trampoline = trampolines[i]; + + if (trampoline.targetObject === this._trampolineTargetObject) + { + trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs); + } + } + + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + }, + + /** + * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. + * @method Phaser.Pointer#reset + */ + reset: function () { + + if (this.isMouse === false) + { + this.active = false; + } + + this.pointerId = null; + this.identifier = null; + this.dirty = false; + this.totalTouches = 0; + this._holdSent = false; + this._history.length = 0; + this._stateReset = true; + + this.resetButtons(); + + if (this.targetObject) + { + this.targetObject._releasedHandler(this); + } + + this.targetObject = null; + + }, + + /** + * Resets the movementX and movementY properties. Use in your update handler after retrieving the values. + * @method Phaser.Pointer#resetMovement + */ + resetMovement: function() { + + this.movementX = 0; + this.movementY = 0; + + } + +}; + +Phaser.Pointer.prototype.constructor = Phaser.Pointer; + +/** +* How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. +* If not currently down it returns -1. +* If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. +* +* @name Phaser.Pointer#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* Gets the X value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldX +* @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldX", { + + get: function () { + + return this.game.world.camera.x + this.x; + + } + +}); + +/** +* Gets the Y value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldY +* @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldY", { + + get: function () { + + return this.game.world.camera.y + this.y; + + } + +}); + +/** +* Enumeration categorizing operational modes of pointers. +* +* PointerType values represent valid bitmasks. +* For example, a value representing both Mouse and Touch devices +* can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. +* +* Values may be added for future mode categorizations. +* @class Phaser.PointerMode +*/ +Phaser.PointerMode = { + + /** + * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. + * + * It has the property that a cursor is passively moved without activating the input. + * This currently corresponds with {@link Phaser.Pointer#isMouse} property. + * @constant + */ + CURSOR: 1 << 0, + + /** + * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. + * @constant + */ + CONTACT: 1 << 1 + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. +* +* @class Phaser.Touch +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Touch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * Touch events will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} touchStartCallback - A callback that can be fired on a touchStart event. + */ + this.touchStartCallback = null; + + /** + * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event. + */ + this.touchMoveCallback = null; + + /** + * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event. + */ + this.touchEndCallback = null; + + /** + * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event. + */ + this.touchEnterCallback = null; + + /** + * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event. + */ + this.touchLeaveCallback = null; + + /** + * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event. + */ + this.touchCancelCallback = null; + + /** + * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it. + * @default + */ + this.preventDefault = true; + + /** + * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received. + * @default + */ + this.event = null; + + /** + * @property {function} _onTouchStart - Internal event handler reference. + * @private + */ + this._onTouchStart = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + + /** + * @property {function} _onTouchEnd - Internal event handler reference. + * @private + */ + this._onTouchEnd = null; + + /** + * @property {function} _onTouchEnter - Internal event handler reference. + * @private + */ + this._onTouchEnter = null; + + /** + * @property {function} _onTouchLeave - Internal event handler reference. + * @private + */ + this._onTouchLeave = null; + + /** + * @property {function} _onTouchCancel - Internal event handler reference. + * @private + */ + this._onTouchCancel = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + +}; + +Phaser.Touch.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Touch#start + */ + start: function () { + + if (this._onTouchStart !== null) + { + // Avoid setting multiple listeners + 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('touchcancel', this._onTouchCancel, false); + + if (!this.game.device.cocoonJS) + { + this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false); + this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false); + } + } + + }, + + /** + * Consumes all touchmove events on the document (only enable this if you know you need it!). + * @method Phaser.Touch#consumeTouchMove + */ + consumeDocumentTouches: function () { + + this._documentTouchMove = function (event) { + event.preventDefault(); + }; + + document.addEventListener('touchmove', this._documentTouchMove, false); + + }, + + /** + * The internal method that handles the touchstart event from the browser. + * @method Phaser.Touch#onTouchStart + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchStart: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.touchStartCallback) + { + this.touchStartCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.startPointer(event.changedTouches[i]); + } + + }, + + /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. + * @method Phaser.Touch#onTouchCancel + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchCancel: function (event) { + + this.event = event; + + if (this.touchCancelCallback) + { + this.touchCancelCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchEnter + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnter: function (event) { + + this.event = event; + + if (this.touchEnterCallback) + { + this.touchEnterCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchLeave + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchLeave: function (event) { + + this.event = event; + + if (this.touchLeaveCallback) + { + this.touchLeaveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * The handler for the touchmove events. + * @method Phaser.Touch#onTouchMove + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchMove: function (event) { + + this.event = event; + + if (this.touchMoveCallback) + { + this.touchMoveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.updatePointer(event.changedTouches[i]); + } + + }, + + /** + * The handler for the touchend events. + * @method Phaser.Touch#onTouchEnd + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnd: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.touchEndCallback) + { + this.touchEndCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.Touch#stop + */ + stop: function () { + + if (this.game.device.touch) + { + this.game.canvas.removeEventListener('touchstart', this._onTouchStart); + this.game.canvas.removeEventListener('touchmove', this._onTouchMove); + this.game.canvas.removeEventListener('touchend', this._onTouchEnd); + this.game.canvas.removeEventListener('touchenter', this._onTouchEnter); + this.game.canvas.removeEventListener('touchleave', this._onTouchLeave); + this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel); + } + + } + +}; + +Phaser.Touch.prototype.constructor = Phaser.Touch; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. +* +* @class Phaser.InputHandler +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. +*/ +Phaser.InputHandler = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = sprite.game; + + /** + * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity. + * @default + */ + this.enabled = false; + + /** + * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks. + * @protected + */ + this.checked = false; + + /** + * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have + * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can + * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. + * @property {number} priorityID + * @default + */ + this.priorityID = 0; + + /** + * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. + * @default + */ + this.useHandCursor = false; + + /** + * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor? + * @private + */ + this._setHandCursor = false; + + /** + * @property {boolean} isDragged - true if the Sprite is being currently dragged. + * @default + */ + this.isDragged = false; + + /** + * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally. + * @default + */ + this.allowHorizontalDrag = true; + + /** + * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically. + * @default + */ + this.allowVerticalDrag = true; + + /** + * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. + * @default + */ + this.bringToTop = false; + + /** + * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset. + * @default + */ + this.snapOffset = null; + + /** + * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. + * @default + */ + this.snapOnDrag = false; + + /** + * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release. + * @default + */ + this.snapOnRelease = false; + + /** + * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid. + * @default + */ + this.snapX = 0; + + /** + * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid. + * @default + */ + this.snapY = 0; + + /** + * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid. + * @default + */ + this.snapOffsetX = 0; + + /** + * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid.. + * @default + */ + this.snapOffsetY = 0; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. + * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over. + * @default + */ + this.pixelPerfectOver = false; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive so only enable if you really need it. + * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite. + * @default + */ + this.pixelPerfectClick = false; + + /** + * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. + * @default + */ + this.pixelPerfectAlpha = 255; + + /** + * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no + * @default + */ + this.draggable = false; + + /** + * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag. + * @default + */ + this.boundsRect = null; + + /** + * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. + * @default + */ + this.boundsSprite = null; + + /** + * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. + */ + this.scaleLayer = false; + + /** + * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from. + */ + this.dragOffset = new Phaser.Point(); + + /** + * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? + */ + this.dragFromCenter = false; + + /** + * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. + */ + this.dragStopBlocksInputUp = false; + + /** + * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. + */ + this.dragStartPoint = new Phaser.Point(); + + /** + * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. + */ + this.dragDistanceThreshold = 0; + + /** + * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. + */ + this.dragTimeThreshold = 0; + + /** + * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. + */ + this.downPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. + */ + this.snapPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} _dragPoint - Internal cache var. + * @private + */ + this._dragPoint = new Phaser.Point(); + + /** + * @property {boolean} _dragPhase - Internal cache var. + * @private + */ + this._dragPhase = false; + + /** + * @property {boolean} _pendingDrag - Internal cache var. + * @private + */ + this._pendingDrag = false; + + /** + * @property {boolean} _dragTimePass - Internal cache var. + * @private + */ + this._dragTimePass = false; + + /** + * @property {boolean} _dragDistancePass - Internal cache var. + * @private + */ + this._dragDistancePass = false; + + /** + * @property {boolean} _wasEnabled - Internal cache var. + * @private + */ + this._wasEnabled = false; + + /** + * @property {Phaser.Point} _tempPoint - Internal cache var. + * @private + */ + this._tempPoint = new Phaser.Point(); + + /** + * @property {array} _pointerData - Internal cache var. + * @private + */ + this._pointerData = []; + + this._pointerData.push({ + id: 0, + x: 0, + y: 0, + camX: 0, + camY: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }); + +}; + +Phaser.InputHandler.prototype = { + + /** + * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. + * + * @method Phaser.InputHandler#start + * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. + * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) + * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound. + */ + start: function (priority, useHandCursor) { + + priority = priority || 0; + if (useHandCursor === undefined) { useHandCursor = false; } + + // Turning on + if (this.enabled === false) + { + // Register, etc + this.game.input.interactiveItems.add(this); + this.useHandCursor = useHandCursor; + this.priorityID = priority; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + + this.snapOffset = new Phaser.Point(); + this.enabled = true; + this._wasEnabled = true; + + } + + this.sprite.events.onAddedToGroup.add(this.addedToGroup, this); + this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this); + + return this.sprite; + + }, + + /** + * Handles when the parent Sprite is added to a new Group. + * + * @method Phaser.InputHandler#addedToGroup + * @private + */ + addedToGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this._wasEnabled && !this.enabled) + { + this.start(); + } + + }, + + /** + * Handles when the parent Sprite is removed from a Group. + * + * @method Phaser.InputHandler#removedFromGroup + * @private + */ + removedFromGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this.enabled) + { + this._wasEnabled = true; + this.stop(); + } + else + { + this._wasEnabled = false; + } + + }, + + /** + * Resets the Input Handler and disables it. + * @method Phaser.InputHandler#reset + */ + reset: function () { + + this.enabled = false; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + }, + + /** + * Stops the Input Handler from running. + * @method Phaser.InputHandler#stop + */ + stop: function () { + + // Turning off + if (this.enabled === false) + { + return; + } + else + { + // De-register, etc + this.enabled = false; + this.game.input.interactiveItems.remove(this); + } + + }, + + /** + * Clean up memory. + * @method Phaser.InputHandler#destroy + */ + destroy: function () { + + if (this.sprite) + { + if (this._setHandCursor) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + this.enabled = false; + + this.game.input.interactiveItems.remove(this); + + this._pointerData.length = 0; + this.boundsRect = null; + this.boundsSprite = null; + this.sprite = null; + } + + }, + + /** + * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. + * This is called by Phaser.Pointer and shouldn't typically be called directly. + * + * @method Phaser.InputHandler#validForInput + * @protected + * @param {number} highestID - The highest ID currently processed by the Pointer. + * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer. + * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? + * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection. + */ + validForInput: function (highestID, highestRenderID, includePixelPerfect) { + + if (includePixelPerfect === undefined) { includePixelPerfect = true; } + + if (!this.enabled || + this.sprite.scale.x === 0 || + this.sprite.scale.y === 0 || + this.priorityID < this.game.input.minPriorityID || + (this.sprite.parent && this.sprite.parent.ignoreChildInput)) + { + return false; + } + + // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it + if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver)) + { + return false; + } + + if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID > highestRenderID)) + { + return true; + } + + return false; + + }, + + /** + * Is this object using pixel perfect checking? + * + * @method Phaser.InputHandler#isPixelPerfect + * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. + */ + isPixelPerfect: function () { + + return (this.pixelPerfectClick || this.pixelPerfectOver); + + }, + + /** + * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerX + * @param {integer} [pointerId=0] + * @return {number} The x coordinate of the Input pointer. + */ + pointerX: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].x; + + }, + + /** + * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerY + * @param {integer} [pointerId=0] + * @return {number} The y coordinate of the Input pointer. + */ + pointerY: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].y; + + }, + + /** + * If the Pointer is down this returns true. + * This *only* checks if the Pointer is down, not if it's down over any specific Sprite. + * + * @method Phaser.InputHandler#pointerDown + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is down, otherwise false. + */ + pointerDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDown; + + }, + + /** + * If the Pointer is up this returns true. + * This *only* checks if the Pointer is up, not if it's up over any specific Sprite. + * + * @method Phaser.InputHandler#pointerUp + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is up, otherwise false. + */ + pointerUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isUp; + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeDown + * @param {integer} [pointerId=(check all)] + * @return {number} + */ + pointerTimeDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeDown; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeUp + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeUp; + + }, + + /** + * Is the Pointer over this Sprite? + * + * @method Phaser.InputHandler#pointerOver + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object. + */ + pointerOver: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOver) + { + return true; + } + } + + return false; + } + else + { + return this._pointerData[pointerId].isOver; + } + + }, + + /** + * Is the Pointer outside of this Sprite? + * + * @method Phaser.InputHandler#pointerOut + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. + */ + pointerOut: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOut) + { + return true; + } + } + } + else + { + return this._pointerData[pointerId].isOut; + } + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOver + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOver: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOver; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOut + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOut: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOut; + + }, + + /** + * Is this sprite being dragged by the mouse or not? + * + * @method Phaser.InputHandler#pointerDragged + * @param {integer} [pointerId=0] + * @return {boolean} True if the pointer is dragging an object, otherwise false. + */ + pointerDragged: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDragged; + + }, + + /** + * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerDown + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} True if the pointer is down, otherwise false. + */ + checkPointerDown: function (pointer, fastTest) { + + if (!pointer.isDown || + !this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectClick) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Checks if the given pointer is over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerOver + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} + */ + checkPointerOver: function (pointer, fastTest) { + + if (!this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectOver) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. + * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. + * + * @method Phaser.InputHandler#checkPixel + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters. + * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha + */ + checkPixel: function (x, y, pointer) { + + // Grab a pixel from our image into the hitCanvas and then test it + if (this.sprite.texture.baseTexture.source) + { + if (x === null && y === null) + { + // Use the pointer parameter + this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint); + + var x = this._tempPoint.x; + var y = this._tempPoint.y; + } + + if (this.sprite.anchor.x !== 0) + { + x -= -this.sprite.texture.frame.width * this.sprite.anchor.x; + } + + if (this.sprite.anchor.y !== 0) + { + y -= -this.sprite.texture.frame.height * this.sprite.anchor.y; + } + + x += this.sprite.texture.frame.x; + y += this.sprite.texture.frame.y; + + if (this.sprite.texture.trim) + { + x -= this.sprite.texture.trim.x; + y -= this.sprite.texture.trim.y; + + // If the coordinates are outside the trim area we return false immediately, to save doing a draw call + if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom) + { + this._dx = x; + this._dy = y; + return false; + } + } + + this._dx = x; + this._dy = y; + + this.game.input.hitContext.clearRect(0, 0, 1, 1); + this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1); + + if (rgb.data[3] >= this.pixelPerfectAlpha) + { + return true; + } + } + + return false; + + }, + + /** + * Internal Update method. This is called automatically and handles the Pointer + * and drag update loops. + * + * @method Phaser.InputHandler#update + * @protected + * @param {Phaser.Pointer} pointer + * @return {boolean} True if the pointer is still active, otherwise false. + */ + update: function (pointer) { + + if (this.sprite === null || this.sprite.parent === undefined) + { + // Abort. We've been destroyed. + return; + } + + if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible) + { + this._pointerOutHandler(pointer); + return false; + } + + if (this._pendingDrag) + { + if (!this._dragDistancePass) + { + this._dragDistancePass = (Phaser.Math.distance(pointer.x, pointer.y, this.downPoint.x, this.downPoint.y) >= this.dragDistanceThreshold); + } + + if (this._dragDistancePass && this._dragTimePass) + { + this.startDrag(pointer); + } + + return true; + } + else if (this.draggable && this._draggedPointerID === pointer.id) + { + return this.updateDrag(pointer, false); + } + else if (this._pointerData[pointer.id].isOver) + { + 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; + } + } + }, + + /** + * Internal method handling the pointer over event. + * + * @method Phaser.InputHandler#_pointerOverHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOverHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (data.isOver === false || pointer.dirty) + { + var sendEvent = (data.isOver === false); + + data.isOver = true; + data.isOut = false; + data.timeOver = this.game.time.time; + data.x = pointer.x - this.sprite.x; + data.y = pointer.y - this.sprite.y; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = "pointer"; + this._setHandCursor = true; + } + + if (!silent && sendEvent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOver$dispatch(this.sprite, pointer); + } + + if (this.sprite.parent && this.sprite.parent.onChildInputOver) + { + this.sprite.parent.onChildInputOver.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the pointer out event. + * + * @method Phaser.InputHandler#_pointerOutHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOutHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + data.isOver = false; + data.isOut = true; + data.timeOut = this.game.time.time; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + if (!silent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOut$dispatch(this.sprite, pointer); + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputOut) + { + this.sprite.parent.onChildInputOut.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the touched / clicked event. + * + * @method Phaser.InputHandler#_touchedHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + */ + _touchedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (!data.isDown && data.isOver) + { + if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer)) + { + return; + } + + data.isDown = true; + data.isUp = false; + data.timeDown = this.game.time.time; + + this.downPoint.set(pointer.x, pointer.y); + + // It's possible the onInputDown event creates a new Sprite that is on-top of this one, so we ought to force a Pointer update + pointer.dirty = true; + + if (this.sprite && this.sprite.events) + { + this.sprite.events.onInputDown$dispatch(this.sprite, pointer); + + // The event above might have destroyed this sprite. + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputDown) + { + this.sprite.parent.onChildInputDown.dispatch(this.sprite, pointer); + } + + // The events might have destroyed this sprite. + if (this.sprite === null) + { + return; + } + } + + // Start drag + if (this.draggable && this.isDragged === false) + { + if (this.dragTimeThreshold === 0 && this.dragDistanceThreshold === 0) + { + this.startDrag(pointer); + } + else + { + this._pendingDrag = true; + + this._dragDistancePass = (this.dragDistanceThreshold === 0); + + if (this.dragTimeThreshold > 0) + { + this._dragTimePass = false; + this.game.time.events.add(this.dragTimeThreshold, this.dragTimeElapsed, this, pointer); + } + else + { + this._dragTimePass = true; + } + } + } + + if (this.bringToTop) + { + this.sprite.bringToTop(); + } + } + + }, + + /** + * Internal method handling the drag threshold timer. + * + * @method Phaser.InputHandler#dragTimeElapsed + * @private + * @param {Phaser.Pointer} pointer + */ + dragTimeElapsed: function (pointer) { + + this._dragTimePass = true; + + if (this._pendingDrag && this.sprite) + { + if (this._dragDistancePass) + { + this.startDrag(pointer); + } + } + + }, + + /** + * Internal method handling the pointer released event. + * @method Phaser.InputHandler#_releasedHandler + * @private + * @param {Phaser.Pointer} pointer + */ + _releasedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + // If was previously touched by this Pointer, check if still is AND still over this item + if (data.isDown && pointer.isUp) + { + data.isDown = false; + data.isUp = true; + data.timeUp = this.game.time.time; + data.downDuration = data.timeUp - data.timeDown; + + // Only release the InputUp signal if the pointer is still over this sprite + var isOver = this.checkPointerOver(pointer); + + if (this.sprite && this.sprite.events) + { + if (!this.dragStopBlocksInputUp || + this.dragStopBlocksInputUp && !(this.draggable && this.isDragged && this._draggedPointerID === pointer.id)) + { + this.sprite.events.onInputUp$dispatch(this.sprite, pointer, isOver); + } + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputUp) + { + this.sprite.parent.onChildInputUp.dispatch(this.sprite, pointer, isOver); + } + + // The onInputUp event may have changed the sprite so that checkPointerOver is no longer true, so update it. + if (isOver) + { + isOver = this.checkPointerOver(pointer); + } + } + + data.isOver = isOver; + + if (!isOver && this.useHandCursor) + { + this.game.canvas.style.cursor = "default"; + this._setHandCursor = false; + } + + // It's possible the onInputUp event created a new Sprite that is on-top of this one, so force a Pointer update + pointer.dirty = true; + + this._pendingDrag = false; + + // Stop drag + if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id) + { + this.stopDrag(pointer); + } + } + + }, + + /** + * Called as a Pointer actively drags this Game Object. + * + * @method Phaser.InputHandler#updateDrag + * @private + * @param {Phaser.Pointer} pointer - The Pointer causing the drag update. + * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started. + * @return {boolean} + */ + updateDrag: function (pointer, fromStart) { + + if (fromStart === undefined) { fromStart = false; } + + if (pointer.isUp) + { + this.stopDrag(pointer); + return false; + } + + var pointerLocalCoord = this.globalToLocal(pointer); + + if (this.sprite.fixedToCamera) + { + var px = this.game.camera.scale.x * pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = this.game.camera.scale.y * pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + else + { + var px = pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + + if (this.sprite.fixedToCamera) + { + if (this.allowHorizontalDrag) + { + this.sprite.cameraOffset.x = px - this.game.camera.x; + } + + if (this.allowVerticalDrag) + { + this.sprite.cameraOffset.y = py - this.game.camera.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); + this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y); + } + } + else + { + var cx = this.game.camera.x - this._pointerData[pointer.id].camX; + var cy = this.game.camera.y - this._pointerData[pointer.id].camY; + + if (this.allowHorizontalDrag) + { + this.sprite.x = px + cx; + } + + if (this.allowVerticalDrag) + { + this.sprite.y = py + cy; + } + + 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); + this.snapPoint.set(this.sprite.x, this.sprite.y); + } + } + + this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint, fromStart); + + return true; + + }, + + /** + * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOver + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justOver: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOut + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justOut: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay)); + + }, + + /** + * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justPressed + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justPressed: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justReleased + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justReleased: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay)); + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#overDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. + */ + overDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isOver) + { + return this.game.time.time - this._pointerData[pointerId].timeOver; + } + + return -1; + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#downDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. + */ + downDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isDown) + { + return this.game.time.time - this._pointerData[pointerId].timeDown; + } + + return -1; + + }, + + /** + * Allow this Sprite to be dragged by any valid pointer. + * + * When the drag begins the Sprite.events.onDragStart event will be dispatched. + * + * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. + * + * You can control the thresholds over when a drag starts via the properties: + * + * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move + * before the drag will start. + * + * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on + * the Sprite before the drag will start. + * + * You can set either (or both) of these properties after enabling a Sprite for drag. + * + * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually + * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`. + * + * @method Phaser.InputHandler#enableDrag + * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. + * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group. + * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. + * @param {integer} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. + * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. + * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. + */ + enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) { + + if (lockCenter === undefined) { lockCenter = false; } + if (bringToTop === undefined) { bringToTop = false; } + if (pixelPerfect === undefined) { pixelPerfect = false; } + if (alphaThreshold === undefined) { alphaThreshold = 255; } + if (boundsRect === undefined) { boundsRect = null; } + if (boundsSprite === undefined) { boundsSprite = null; } + + this._dragPoint = new Phaser.Point(); + this.draggable = true; + this.bringToTop = bringToTop; + this.dragOffset = new Phaser.Point(); + this.dragFromCenter = lockCenter; + + this.pixelPerfectClick = pixelPerfect; + this.pixelPerfectAlpha = alphaThreshold; + + if (boundsRect) + { + this.boundsRect = boundsRect; + } + + if (boundsSprite) + { + this.boundsSprite = boundsSprite; + } + + }, + + /** + * Stops this sprite from being able to be dragged. + * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. + * + * @method Phaser.InputHandler#disableDrag + */ + disableDrag: function () { + + if (this._pointerData) + { + for (var i = 0; i < 10; i++) + { + this._pointerData[i].isDragged = false; + } + } + + this.draggable = false; + this.isDragged = false; + this._draggedPointerID = -1; + this._pendingDrag = false; + + }, + + /** + * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#startDrag + * @param {Phaser.Pointer} pointer + */ + startDrag: function (pointer) { + + var x = this.sprite.x; + var y = this.sprite.y; + var pointerLocalCoord = this.globalToLocal(pointer); + + this.isDragged = true; + this._draggedPointerID = pointer.id; + + this._pointerData[pointer.id].camX = this.game.camera.x; + this._pointerData[pointer.id].camY = this.game.camera.y; + + this._pointerData[pointer.id].isDragged = true; + + if (this.sprite.fixedToCamera) + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.cameraOffset.x = pointerLocalCoord.x + (this.sprite.cameraOffset.x - boundsCenterLocalCoord.x); + this.sprite.cameraOffset.y = pointerLocalCoord.y + (this.sprite.cameraOffset.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y); + } + else + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.x = pointerLocalCoord.x + (this.sprite.x - boundsCenterLocalCoord.x); + this.sprite.y = pointerLocalCoord.y + (this.sprite.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.x - pointerLocalCoord.x, this.sprite.y - pointerLocalCoord.y); + } + + this.updateDrag(pointer, true); + + if (this.bringToTop) + { + this._dragPhase = true; + this.sprite.bringToTop(); + } + + this.dragStartPoint.set(x, y); + + this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y); + + this._pendingDrag = false; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalX + * @param {number} x + */ + globalToLocalX: function (x) { + + if (this.scaleLayer) + { + x -= this.game.scale.grid.boundsFluid.x; + x *= this.game.scale.grid.scaleFluidInversed.x; + } + + return x; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalY + * @param {number} y + */ + globalToLocalY: function (y) { + + if (this.scaleLayer) + { + y -= this.game.scale.grid.boundsFluid.y; + y *= this.game.scale.grid.scaleFluidInversed.y; + } + + return y; + + }, + + /** + * Convert global coordinates to local sprite coordinates + * + * @method Phaser.InputHandler#globalToLocal + * @param {Phaser.Point} globalCoord - The global coordinates to convert. + * @return {Phaser.Point} A point containing the local coordinates. + */ + globalToLocal: function (globalCoord) { + + if (this.sprite.parent) + { + return this.game.input.getLocalPosition(this.sprite.parent, {x: globalCoord.x, y: globalCoord.y}); + } + else + { + return globalCoord; + } + + }, + + /** + * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#stopDrag + * @param {Phaser.Pointer} pointer + */ + stopDrag: function (pointer) { + + this.isDragged = false; + this._draggedPointerID = -1; + this._pointerData[pointer.id].isDragged = false; + this._dragPhase = false; + this._pendingDrag = false; + + if (this.snapOnRelease) + { + if (this.sprite.fixedToCamera) + { + 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 + { + 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); + } + } + + this.sprite.events.onDragStop$dispatch(this.sprite, pointer); + + if (this.checkPointerOver(pointer) === false) + { + this._pointerOutHandler(pointer); + } + + }, + + /** + * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! + * + * @method Phaser.InputHandler#setDragLock + * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false. + * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false. + */ + setDragLock: function (allowHorizontal, allowVertical) { + + if (allowHorizontal === undefined) { allowHorizontal = true; } + if (allowVertical === undefined) { allowVertical = true; } + + this.allowHorizontalDrag = allowHorizontal; + this.allowVerticalDrag = allowVertical; + + }, + + /** + * Make this Sprite snap to the given grid either during drag or when it's released. + * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. + * + * @method Phaser.InputHandler#enableSnap + * @param {number} snapX - The width of the grid cell to snap to. + * @param {number} snapY - The height of the grid cell to snap to. + * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged. + * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released. + * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid. + * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid. + */ + enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) { + + if (onDrag === undefined) { onDrag = true; } + if (onRelease === undefined) { onRelease = false; } + if (snapOffsetX === undefined) { snapOffsetX = 0; } + if (snapOffsetY === undefined) { snapOffsetY = 0; } + + this.snapX = snapX; + this.snapY = snapY; + this.snapOffsetX = snapOffsetX; + this.snapOffsetY = snapOffsetY; + this.snapOnDrag = onDrag; + this.snapOnRelease = onRelease; + + }, + + /** + * Stops the sprite from snapping to a grid during drag or release. + * + * @method Phaser.InputHandler#disableSnap + */ + disableSnap: function () { + + this.snapOnDrag = false; + this.snapOnRelease = false; + + }, + + /** + * Bounds Rect check for the sprite drag + * + * @method Phaser.InputHandler#checkBoundsRect + */ + checkBoundsRect: function () { + + if (this.sprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsRect.left) + { + this.sprite.cameraOffset.x = this.boundsRect.left; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right) + { + this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsRect.top) + { + this.sprite.cameraOffset.y = this.boundsRect.top; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom) + { + this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsRect.left) + { + this.sprite.x = this.boundsRect.x + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsRect.right) + { + this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsRect.top) + { + this.sprite.y = this.boundsRect.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsRect.bottom) + { + this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + }, + + /** + * Parent Sprite Bounds check for the sprite drag. + * + * @method Phaser.InputHandler#checkBoundsSprite + */ + checkBoundsSprite: function () { + + if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x) + { + this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width)) + { + this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y) + { + this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height)) + { + this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsSprite.left) + { + this.sprite.x = this.boundsSprite.left + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsSprite.right) + { + this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsSprite.top) + { + this.sprite.y = this.boundsSprite.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsSprite.bottom) + { + this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + } + +}; + +Phaser.InputHandler.prototype.constructor = Phaser.InputHandler; + +/** +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Gamepad class handles gamepad input and dispatches gamepad events. +* +* Remember to call `gamepad.start()`. +* +* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! +* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it +* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. +* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. +* +* @class Phaser.Gamepad +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Gamepad = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads + * @private + */ + this._gamepadIndexMap = {}; + + /** + * @property {Array} _rawPads - The raw state of the gamepads from the browser + * @private + */ + this._rawPads = []; + + /** + * @property {boolean} _active - Private flag for whether or not the API is polled + * @private + * @default + */ + this._active = false; + + /** + * Gamepad input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation. + * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not? + * @private + */ + this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') !== -1) || !!navigator.getGamepads; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevRawGamepadTypes + * @private + * @default + */ + this._prevRawGamepadTypes = []; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevTimestamps + * @private + * @default + */ + this._prevTimestamps = []; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._ongamepadconnected = null; + + /** + * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._gamepaddisconnected = null; + + /** + * @property {Array} _gamepads - The four Phaser Gamepads. + * @private + */ + this._gamepads = [ + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this) + ]; + +}; + +Phaser.Gamepad.prototype = { + + /** + * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. + * + * @method Phaser.Gamepad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callback methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + this.callbackContext = context; + } + + }, + + /** + * Starts the Gamepad event handling. + * This MUST be called manually before Phaser will start polling the Gamepad API. + * + * @method Phaser.Gamepad#start + */ + start: function () { + + if (this._active) + { + // Avoid setting multiple listeners + return; + } + + this._active = true; + + var _this = this; + + this._onGamepadConnected = function (event) { + return _this.onGamepadConnected(event); + }; + + this._onGamepadDisconnected = function (event) { + return _this.onGamepadDisconnected(event); + }; + + window.addEventListener('gamepadconnected', this._onGamepadConnected, false); + window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false); + + }, + + /** + * Handles the connection of a Gamepad. + * + * @method onGamepadConnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadConnected: function (event) { + + var newPad = event.gamepad; + this._rawPads.push(newPad); + this._gamepads[newPad.index].connect(newPad); + + }, + + /** + * Handles the disconnection of a Gamepad. + * + * @method onGamepadDisconnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadDisconnected: function (event) { + + var removedPad = event.gamepad; + + for (var i in this._rawPads) + { + if (this._rawPads[i].index === removedPad.index) + { + this._rawPads.splice(i,1); + } + } + + this._gamepads[removedPad.index].disconnect(); + + }, + + /** + * Main gamepad update loop. Should not be called manually. + * @method Phaser.Gamepad#update + * @protected + */ + update: function () { + + this._pollGamepads(); + + this.pad1.pollStatus(); + this.pad2.pollStatus(); + this.pad3.pollStatus(); + this.pad4.pollStatus(); + + }, + + /** + * Updating connected gamepads (for Google Chrome). Should not be called manually. + * + * @method Phaser.Gamepad#_pollGamepads + * @private + */ + _pollGamepads: function () { + + if (!this._active) + { + return; + } + + if (navigator['getGamepads']) + { + var rawGamepads = navigator.getGamepads(); + } + else if (navigator['webkitGetGamepads']) + { + var rawGamepads = navigator.webkitGetGamepads(); + } + else if (navigator['webkitGamepads']) + { + var rawGamepads = navigator.webkitGamepads(); + } + + if (rawGamepads) + { + this._rawPads = []; + + var gamepadsChanged = false; + + for (var i = 0; i < rawGamepads.length; i++) + { + if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i]) + { + gamepadsChanged = true; + this._prevRawGamepadTypes[i] = typeof rawGamepads[i]; + } + + if (rawGamepads[i]) + { + this._rawPads.push(rawGamepads[i]); + } + + // Support max 4 pads at the moment + if (i === 3) + { + break; + } + } + + for (var g = 0; g < this._gamepads.length; g++) + { + this._gamepads[g]._rawPad = this._rawPads[g]; + } + + if (gamepadsChanged) + { + var validConnections = { rawIndices: {}, padIndices: {} }; + var singlePad; + + for (var j = 0; j < this._gamepads.length; j++) + { + singlePad = this._gamepads[j]; + + if (singlePad.connected) + { + for (var k = 0; k < this._rawPads.length; k++) + { + if (this._rawPads[k].index === singlePad.index) + { + validConnections.rawIndices[singlePad.index] = true; + validConnections.padIndices[j] = true; + } + } + } + } + + for (var l = 0; l < this._gamepads.length; l++) + { + singlePad = this._gamepads[l]; + + if (validConnections.padIndices[l]) + { + continue; + } + + if (this._rawPads.length < 1) + { + singlePad.disconnect(); + } + + for (var m = 0; m < this._rawPads.length; m++) + { + if (validConnections.padIndices[l]) + { + break; + } + + var rawPad = this._rawPads[m]; + + if (rawPad) + { + if (validConnections.rawIndices[rawPad.index]) + { + singlePad.disconnect(); + continue; + } + else + { + singlePad.connect(rawPad); + validConnections.rawIndices[rawPad.index] = true; + validConnections.padIndices[l] = true; + } + } + else + { + singlePad.disconnect(); + } + } + } + } + } + }, + + /** + * Sets the deadZone variable for all four gamepads + * @method Phaser.Gamepad#setDeadZones + */ + setDeadZones: function (value) { + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].deadZone = value; + } + + }, + + /** + * Stops the Gamepad event handling. + * + * @method Phaser.Gamepad#stop + */ + stop: function () { + + this._active = false; + + window.removeEventListener('gamepadconnected', this._onGamepadConnected); + window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected); + + }, + + /** + * Reset all buttons/axes of all gamepads + * @method Phaser.Gamepad#reset + */ + reset: function () { + + this.update(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].reset(); + } + + }, + + /** + * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justPressed(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justReleased(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns true if the button is currently pressed down, on ANY gamepad. + * @method Phaser.Gamepad#isDown + * @param {number} buttonCode - The buttonCode of the button to check for. + * @return {boolean} True if a button is currently down. + */ + isDown: function (buttonCode) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].isDown(buttonCode) === true) + { + return true; + } + } + + return false; + }, + + /** + * Destroys this object and the associated event listeners. + * + * @method Phaser.Gamepad#destroy + */ + destroy: function () { + + this.stop(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].destroy(); + } + + } + +}; + +Phaser.Gamepad.prototype.constructor = Phaser.Gamepad; + +/** +* If the gamepad input is active or not - if not active it should not be updated from Input.js +* @name Phaser.Gamepad#active +* @property {boolean} active - If the gamepad input is active or not. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "active", { + + get: function () { + return this._active; + } + +}); + +/** +* Whether or not gamepads are supported in current browser. +* @name Phaser.Gamepad#supported +* @property {boolean} supported - Whether or not gamepads are supported in current browser. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "supported", { + + get: function () { + return this._gamepadSupportAvailable; + } + +}); + +/** +* How many live gamepads are currently connected. +* @name Phaser.Gamepad#padsConnected +* @property {number} padsConnected - How many live gamepads are currently connected. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", { + + get: function () { + return this._rawPads.length; + } + +}); + +/** +* Gamepad #1 +* @name Phaser.Gamepad#pad1 +* @property {Phaser.SinglePad} pad1 - Gamepad #1; +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad1", { + + get: function () { + return this._gamepads[0]; + } + +}); + +/** +* Gamepad #2 +* @name Phaser.Gamepad#pad2 +* @property {Phaser.SinglePad} pad2 - Gamepad #2 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad2", { + + get: function () { + return this._gamepads[1]; + } + +}); + +/** +* Gamepad #3 +* @name Phaser.Gamepad#pad3 +* @property {Phaser.SinglePad} pad3 - Gamepad #3 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad3", { + + get: function () { + return this._gamepads[2]; + } + +}); + +/** +* Gamepad #4 +* @name Phaser.Gamepad#pad4 +* @property {Phaser.SinglePad} pad4 - Gamepad #4 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad4", { + + get: function () { + return this._gamepads[3]; + } + +}); + +Phaser.Gamepad.BUTTON_0 = 0; +Phaser.Gamepad.BUTTON_1 = 1; +Phaser.Gamepad.BUTTON_2 = 2; +Phaser.Gamepad.BUTTON_3 = 3; +Phaser.Gamepad.BUTTON_4 = 4; +Phaser.Gamepad.BUTTON_5 = 5; +Phaser.Gamepad.BUTTON_6 = 6; +Phaser.Gamepad.BUTTON_7 = 7; +Phaser.Gamepad.BUTTON_8 = 8; +Phaser.Gamepad.BUTTON_9 = 9; +Phaser.Gamepad.BUTTON_10 = 10; +Phaser.Gamepad.BUTTON_11 = 11; +Phaser.Gamepad.BUTTON_12 = 12; +Phaser.Gamepad.BUTTON_13 = 13; +Phaser.Gamepad.BUTTON_14 = 14; +Phaser.Gamepad.BUTTON_15 = 15; + +Phaser.Gamepad.AXIS_0 = 0; +Phaser.Gamepad.AXIS_1 = 1; +Phaser.Gamepad.AXIS_2 = 2; +Phaser.Gamepad.AXIS_3 = 3; +Phaser.Gamepad.AXIS_4 = 4; +Phaser.Gamepad.AXIS_5 = 5; +Phaser.Gamepad.AXIS_6 = 6; +Phaser.Gamepad.AXIS_7 = 7; +Phaser.Gamepad.AXIS_8 = 8; +Phaser.Gamepad.AXIS_9 = 9; + +// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7). +// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button. +// In other words - discrepancies when using gamepads. + +Phaser.Gamepad.XBOX360_A = 0; +Phaser.Gamepad.XBOX360_B = 1; +Phaser.Gamepad.XBOX360_X = 2; +Phaser.Gamepad.XBOX360_Y = 3; +Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4; +Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5; +Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6; +Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7; +Phaser.Gamepad.XBOX360_BACK = 8; +Phaser.Gamepad.XBOX360_START = 9; +Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11; + +Phaser.Gamepad.XBOX360_DPAD_LEFT = 14; +Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15; +Phaser.Gamepad.XBOX360_DPAD_UP = 12; +Phaser.Gamepad.XBOX360_DPAD_DOWN = 13; + +// On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right +Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0; +Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1; +Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2; +Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3; + +// PlayStation 3 controller (masquerading as xbox360 controller) button mappings + +Phaser.Gamepad.PS3XC_X = 0; +Phaser.Gamepad.PS3XC_CIRCLE = 1; +Phaser.Gamepad.PS3XC_SQUARE = 2; +Phaser.Gamepad.PS3XC_TRIANGLE = 3; +Phaser.Gamepad.PS3XC_L1 = 4; +Phaser.Gamepad.PS3XC_R1 = 5; +Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_SELECT = 8; +Phaser.Gamepad.PS3XC_START = 9; +Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11; +Phaser.Gamepad.PS3XC_DPAD_UP = 12; +Phaser.Gamepad.PS3XC_DPAD_DOWN = 13; +Phaser.Gamepad.PS3XC_DPAD_LEFT = 14; +Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15; +Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1 + +/** +* @author @karlmacklin +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A single Phaser Gamepad +* +* @class Phaser.SinglePad +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this) +*/ +Phaser.SinglePad = function (game, padParent) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {number} index - The gamepad index as per browsers data + * @readonly + */ + this.index = null; + + /** + * @property {boolean} connected - Whether or not this particular gamepad is connected or not. + * @readonly + */ + this.connected = false; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time a button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time an axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates. + */ + this.deadZone = 0.26; + + /** + * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object + * @private + */ + this._padParent = padParent; + + /** + * @property {object} _rawPad - The 'raw' gamepad data. + * @private + */ + this._rawPad = null; + + /** + * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads. + * @private + */ + this._prevTimestamp = null; + + /** + * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected. + * @private + */ + this._buttons = []; + + /** + * @property {number} _buttonsLen - Length of the _buttons array. + * @private + */ + this._buttonsLen = 0; + + /** + * @property {Array} _axes - Current axes state. + * @private + */ + this._axes = []; + + /** + * @property {number} _axesLen - Length of the _axes array. + * @private + */ + this._axesLen = 0; + +}; + +Phaser.SinglePad.prototype = { + + /** + * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. + * + * @method Phaser.SinglePad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callbak methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + + this.callbackContext = context; + } + }, + + /** + * Gets a DeviceButton object from this controller to be stored and referenced locally. + * The DeviceButton object can then be polled, have events attached to it, etc. + * + * @method Phaser.SinglePad#getButton + * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc. + * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly. + */ + getButton: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode]; + } + else + { + return null; + } + + }, + + /** + * Main update function called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#pollStatus + */ + pollStatus: function () { + + if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp))) + { + return; + } + + for (var i = 0; i < this._buttonsLen; i++) + { + var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i]; + + if (rawButtonVal !== this._buttons[i].value) + { + if (rawButtonVal === 1) + { + this.processButtonDown(i, rawButtonVal); + } + else if (rawButtonVal === 0) + { + this.processButtonUp(i, rawButtonVal); + } + else + { + this.processButtonFloat(i, rawButtonVal); + } + } + } + + for (var index = 0; index < this._axesLen; index++) + { + var value = this._rawPad.axes[index]; + + if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone)) + { + this.processAxisChange(index, value); + } + else + { + this.processAxisChange(index, 0); + } + } + + this._prevTimestamp = this._rawPad.timestamp; + + }, + + /** + * Gamepad connect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#connect + * @param {object} rawPad - The raw gamepad object + */ + connect: function (rawPad) { + + var triggerCallback = !this.connected; + + this.connected = true; + this.index = rawPad.index; + + this._rawPad = rawPad; + + this._buttons = []; + this._buttonsLen = rawPad.buttons.length; + + this._axes = []; + this._axesLen = rawPad.axes.length; + + for (var a = 0; a < this._axesLen; a++) + { + this._axes[a] = rawPad.axes[a]; + } + + for (var buttonCode in rawPad.buttons) + { + buttonCode = parseInt(buttonCode, 10); + this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode); + } + + if (triggerCallback && this._padParent.onConnectCallback) + { + this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index); + } + + if (triggerCallback && this.onConnectCallback) + { + this.onConnectCallback.call(this.callbackContext); + } + + }, + + /** + * Gamepad disconnect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#disconnect + */ + disconnect: function () { + + var triggerCallback = this.connected; + var disconnectingIndex = this.index; + + this.connected = false; + this.index = null; + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + if (triggerCallback && this._padParent.onDisconnectCallback) + { + this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex); + } + + if (triggerCallback && this.onDisconnectCallback) + { + this.onDisconnectCallback.call(this.callbackContext); + } + + }, + + /** + * Destroys this object and associated callback references. + * + * @method Phaser.SinglePad#destroy + */ + destroy: function () { + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + this.onConnectCallback = null; + this.onDisconnectCallback = null; + this.onDownCallback = null; + this.onUpCallback = null; + this.onAxisCallback = null; + this.onFloatCallback = null; + + }, + + /** + * Handles changes in axis. + * + * @method Phaser.SinglePad#processAxisChange + * @param {object} axisState - State of the relevant axis + */ + processAxisChange: function (index, value) { + + if (this._axes[index] === value) + { + return; + } + + this._axes[index] = value; + + if (this._padParent.onAxisCallback) + { + this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value); + } + + if (this.onAxisCallback) + { + this.onAxisCallback.call(this.callbackContext, this, index, value); + } + + }, + + /** + * Handles button down press. + * + * @method Phaser.SinglePad#processButtonDown + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonDown: function (buttonCode, value) { + + if (this._buttons[buttonCode]) + { + this._buttons[buttonCode].start(null, value); + } + + 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); + } + + }, + + /** + * Handles button release. + * + * @method Phaser.SinglePad#processButtonUp + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonUp: function (buttonCode, value) { + + 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._buttons[buttonCode]) + { + this._buttons[buttonCode].stop(null, value); + } + + }, + + /** + * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) + * + * @method Phaser.SinglePad#processButtonFloat + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. + */ + processButtonFloat: function (buttonCode, value) { + + 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].padFloat(value); + } + + }, + + /** + * Returns value of requested axis. + * + * @method Phaser.SinglePad#axis + * @param {number} axisCode - The index of the axis to check + * @return {number} Axis value if available otherwise false + */ + axis: function (axisCode) { + + if (this._axes[axisCode]) + { + return this._axes[axisCode]; + } + + return false; + + }, + + /** + * Returns true if the button is pressed down. + * + * @method Phaser.SinglePad#isDown + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is pressed down. + */ + isDown: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isDown; + } + + return false; + + }, + + /** + * Returns true if the button is not currently pressed. + * + * @method Phaser.SinglePad#isUp + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is not currently pressed down. + */ + isUp: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isUp; + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justReleased + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justReleased(duration); + } + + }, + + /** + * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justPressed(duration); + } + + }, + + /** + * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example + * analog trigger buttons on the XBOX 360 controller. + * + * @method Phaser.SinglePad#buttonValue + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. + */ + buttonValue: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].value; + } + + return null; + + }, + + /** + * Reset all buttons/axes of this gamepad. + * + * @method Phaser.SinglePad#reset + */ + reset: function () { + + for (var j = 0; j < this._axes.length; j++) + { + this._axes[j] = 0; + } + + } + +}; + +Phaser.SinglePad.prototype.constructor = Phaser.SinglePad; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. +* +* @class Phaser.Key +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}. +*/ +Phaser.Key = function (game, keycode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * The enabled state of the key - see `enabled`. + * @property {boolean} _enabled + * @private + */ + this._enabled = true; + + /** + * @property {object} event - Stores the most recent DOM event. + * @readonly + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * @default + */ + this.isUp = true; + + /** + * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. + * @default + */ + this.altKey = false; + + /** + * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. + * @default + */ + this.ctrlKey = false; + + /** + * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. + * @default + */ + this.shiftKey = false; + + /** + * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now. + */ + this.timeDown = 0; + + /** + * If the key is down this value holds the duration of that key press and is constantly updated. + * If the key is up it holds the duration of the previous down session. + * @property {number} duration - The number of milliseconds this key has been held down for. + * @default + */ + this.duration = 0; + + /** + * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now. + * @default + */ + this.timeUp = -2500; + + /** + * If the key is up this value holds the duration of that key release and is constantly updated. + * If the key is down it holds the duration of the previous up session. + * @property {number} duration - The number of milliseconds this key has been up for. + * @default + */ + this.durationUp = -2500; + + /** + * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. + * @default + */ + this.repeats = 0; + + /** + * @property {number} keyCode - The keycode of this key. + */ + this.keyCode = keycode; + + /** + * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). + */ + this.onDown = new Phaser.Signal(); + + /** + * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. + */ + this.onHoldCallback = null; + + /** + * @property {object} onHoldContext - The context under which the onHoldCallback will be called. + */ + this.onHoldContext = null; + + /** + * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). + */ + this.onUp = new Phaser.Signal(); + + /** + * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justDown = false; + + /** + * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justUp = false; + +}; + +Phaser.Key.prototype = { + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#update + * @protected + */ + update: function () { + + if (!this._enabled) { return; } + + if (this.isDown) + { + this.duration = this.game.time.time - this.timeDown; + this.repeats++; + + if (this.onHoldCallback) + { + this.onHoldCallback.call(this.onHoldContext, this); + } + } + else + { + this.durationUp = this.game.time.time - this.timeUp; + } + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyDown + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyDown: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + // exit if this key down is from auto-repeat + if (this.isDown) + { + return; + } + + this.altKey = event.altKey; + this.ctrlKey = event.ctrlKey; + this.shiftKey = event.shiftKey; + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.duration = 0; + this.durationUp = this.game.time.time - this.timeUp; + this.repeats = 0; + + // _justDown will remain true until it is read via the justDown Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justDown = true; + + this.onDown.dispatch(this); + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyUp + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyUp: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = this.game.time.time - this.timeDown; + this.durationUp = 0; + + // _justUp will remain true until it is read via the justUp Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justUp = true; + + this.onUp.dispatch(this); + + }, + + /** + * Resets the state of this Key. + * + * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key. + * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. + * + * @method Phaser.Key#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = 0; + this.durationUp = -2500; + this._enabled = true; // .enabled causes reset(false) + this._justDown = false; + this._justUp = false; + + if (hard) + { + this.onDown.removeAll(); + this.onUp.removeAll(); + this.onHoldCallback = null; + this.onHoldContext = null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#downDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration. + */ + downDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (this.isDown && this.duration < duration); + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#upDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration. + */ + upDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (!this.isDown && ((this.game.time.time - this.timeUp) < duration)); + + }, + + /** + * Returns `true` if the Key was just pressed down this update tick, or `false` if it either isn't down, + * or was pressed down on a previous update tick. + * + * @method Phaser.Key#justPressed + * @return {boolean} True if the key was just pressed down this update tick. + */ + justPressed: function () { + + return (this.isDown && this.duration === 0); + + }, + + /** + * Returns `true` if the Key was just released this update tick, or `false` if it either isn't up, + * or was released on a previous update tick. + * + * @method Phaser.Key#justReleased + * @return {boolean} True if the key was just released this update tick. + */ + justReleased: function () { + + return (!this.isDown && this.durationUp === 0); + + } + +}; + +/** +* The justDown value allows you to test if this Key has just been pressed down or not. +* When you check this value it will return `true` if the Key is down, otherwise `false`. +* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. +* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justDown +* @property {boolean} justDown +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justDown", { + + get: function () { + + var current = this._justDown; + this._justDown = false; + return current; + + } + +}); + +/** +* The justUp value allows you to test if this Key has just been released or not. +* When you check this value it will return `true` if the Key is up, otherwise `false`. +* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again. +* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justUp +* @property {boolean} justUp +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justUp", { + + get: function () { + + var current = this._justUp; + this._justUp = false; + return current; + + } + +}); + +/** +* An enabled key processes its update and dispatches events. +* A key can be disabled momentarily at runtime instead of deleting it. +* @name Phaser.Key#enabled +* @property {boolean} enabled +* @memberof Phaser.Key +* @default true +*/ +Object.defineProperty(Phaser.Key.prototype, "enabled", { + + get: function () { + + return this._enabled; + + }, + + set: function (value) { + + value = !!value; + + if (value !== this._enabled) + { + if (!value) + { + this.reset(false); + } + + this._enabled = value; + } + } + +}); + +Phaser.Key.prototype.constructor = Phaser.Key; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Keyboard class monitors keyboard input and dispatches keyboard events. +* +* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. +* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. +* +* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. +* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. +* So please check your extensions before opening Phaser issues. +* +* @class Phaser.Keyboard +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Keyboard = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Keyboard input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. + */ + this.event = null; + + /** + * @property {object} pressEvent - The most recent DOM event from keypress. + */ + this.pressEvent = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. + */ + this.onDownCallback = null; + + /** + * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. + */ + this.onPressCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a key is released. + */ + this.onUpCallback = null; + + /** + * @property {array} _keys - The array the Phaser.Key objects are stored in. + * @private + */ + this._keys = []; + + /** + * @property {array} _capture - The array the key capture values are stored in. + * @private + */ + this._capture = []; + + /** + * @property {function} _onKeyDown + * @private + * @default + */ + this._onKeyDown = null; + + /** + * @property {function} _onKeyPress + * @private + * @default + */ + this._onKeyPress = null; + + /** + * @property {function} _onKeyUp + * @private + * @default + */ + this._onKeyUp = null; + + /** + * @property {number} _i - Internal cache var + * @private + */ + this._i = 0; + + /** + * @property {number} _k - Internal cache var + * @private + */ + this._k = 0; + +}; + +Phaser.Keyboard.prototype = { + + /** + * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. + * + * @method Phaser.Keyboard#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down. + * @param {function} [onUp=null] - This callback is invoked every time a key is released. + * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised. + */ + addCallbacks: function (context, onDown, onUp, onPress) { + + this.callbackContext = context; + + if (onDown !== undefined && onDown !== null) + { + this.onDownCallback = onDown; + } + + if (onUp !== undefined && onUp !== null) + { + this.onUpCallback = onUp; + } + + if (onPress !== undefined && onPress !== null) + { + this.onPressCallback = onPress; + } + + }, + + /** + * Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}. + * + * @method Phaser.Keyboard#removeCallbacks + */ + removeCallbacks: function () { + + this.callbackContext = this; + this.onDownCallback = null; + this.onUpCallback = null; + this.onPressCallback = null; + + }, + + /** + * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. + * The Key object can then be polled, have events attached to it, etc. + * + * @method Phaser.Keyboard#addKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key. + * @return {Phaser.Key} The Key object which you can store locally and reference directly. + */ + addKey: function (keycode) { + + if (!this._keys[keycode]) + { + this._keys[keycode] = new Phaser.Key(this.game, keycode); + + this.addKeyCapture(keycode); + } + + return this._keys[keycode]; + + }, + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example, + * + * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); + * + * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object. + * + * @method Phaser.Keyboard#addKeys + * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. + * @return {object} An object containing the properties mapped to {@link Phaser.Key} values. + */ + addKeys: function (keys) { + + var output = {}; + + for (var key in keys) + { + output[key] = this.addKey(keys[key]); + } + + return output; + + }, + + /** + * Removes a Key object from the Keyboard manager. + * + * @method Phaser.Keyboard#removeKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove. + */ + removeKey: function (keycode) { + + if (this._keys[keycode]) + { + this._keys[keycode] = null; + + this.removeKeyCapture(keycode); + } + + }, + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. + * + * @method Phaser.Keyboard#createCursorKeys + * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects. + */ + createCursorKeys: function () { + + return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT }); + + }, + + /** + * Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window. + * This is called automatically by Phaser.Input and should not normally be invoked directly. + * + * @method Phaser.Keyboard#start + * @protected + */ + start: function () { + + if (this.game.device.cocoonJS) + { + return; + } + + if (this._onKeyDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onKeyDown = function (event) { + return _this.processKeyDown(event); + }; + + this._onKeyUp = function (event) { + return _this.processKeyUp(event); + }; + + this._onKeyPress = function (event) { + return _this.processKeyPress(event); + }; + + window.addEventListener('keydown', this._onKeyDown, false); + window.addEventListener('keyup', this._onKeyUp, false); + window.addEventListener('keypress', this._onKeyPress, false); + + }, + + /** + * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. + * + * @method Phaser.Keyboard#stop + */ + stop: function () { + + window.removeEventListener('keydown', this._onKeyDown); + window.removeEventListener('keyup', this._onKeyUp); + window.removeEventListener('keypress', this._onKeyPress); + + this._onKeyDown = null; + this._onKeyUp = null; + this._onKeyPress = null; + + }, + + /** + * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. + * Also clears all key captures and currently created Key objects. + * + * @method Phaser.Keyboard#destroy + */ + destroy: function () { + + this.stop(); + + this.clearCaptures(); + + this._keys.length = 0; + this._i = 0; + + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Pass in either a single keycode or an array/hash of keycodes. + * + * @method Phaser.Keyboard#addKeyCapture + * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`. + */ + addKeyCapture: function (keycode) { + + if (typeof keycode === 'object') + { + for (var key in keycode) + { + this._capture[keycode[key]] = true; + } + } + else + { + this._capture[keycode] = true; + } + }, + + /** + * Removes an existing key capture. + * + * @method Phaser.Keyboard#removeKeyCapture + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of. + */ + removeKeyCapture: function (keycode) { + + delete this._capture[keycode]; + + }, + + /** + * Clear all set key captures. + * + * @method Phaser.Keyboard#clearCaptures + */ + clearCaptures: function () { + + this._capture = {}; + + }, + + /** + * Updates all currently defined keys. + * + * @method Phaser.Keyboard#update + */ + update: function () { + + this._i = this._keys.length; + + while (this._i--) + { + if (this._keys[this._i]) + { + this._keys[this._i].update(); + } + } + + }, + + /** + * Process the keydown event. + * + * @method Phaser.Keyboard#processKeyDown + * @param {KeyboardEvent} event + * @protected + */ + processKeyDown: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + // The event is being captured but another hotkey may need it + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyDown(event); + + this._k = key; + + if (this.onDownCallback) + { + this.onDownCallback.call(this.callbackContext, event); + } + + }, + + /** + * Process the keypress event. + * + * @method Phaser.Keyboard#processKeyPress + * @param {KeyboardEvent} event + * @protected + */ + processKeyPress: function (event) { + + this.pressEvent = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.onPressCallback) + { + this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event); + } + + }, + + /** + * Process the keyup event. + * + * @method Phaser.Keyboard#processKeyUp + * @param {KeyboardEvent} event + * @protected + */ + processKeyUp: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyUp(event); + + if (this.onUpCallback) + { + this.onUpCallback.call(this.callbackContext, event); + } + + }, + + /** + * Resets all Keys. + * + * @method Phaser.Keyboard#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.event = null; + + var i = this._keys.length; + + while (i--) + { + if (this._keys[i]) + { + this._keys[i].reset(hard); + } + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#downDuration + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. + */ + downDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].downDuration(duration); + } + else + { + return null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#upDuration + * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found. + */ + upDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].upDuration(duration); + } + else + { + return null; + } + + }, + + justPressed: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justPressed(); + } + else + { + return null; + } + + }, + + justReleased: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justReleased(); + } + else + { + return null; + } + + }, + + /** + * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. + * + * @method Phaser.Keyboard#isDown + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found. + */ + isDown: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].isDown; + } + else + { + return null; + } + + } + +}; + +/** +* Returns the string value of the most recently pressed key. +* @name Phaser.Keyboard#lastChar +* @property {string} lastChar - The string value of the most recently pressed key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", { + + get: function () { + + if (this.event && this.event.charCode === 32) + { + return ''; + } + else if (this.pressEvent) + { + return String.fromCharCode(this.pressEvent.charCode); + } + else + { + return null; + } + + } + +}); + +/** +* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. +* @name Phaser.Keyboard#lastKey +* @property {Phaser.Key} lastKey - The most recently pressed Key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", { + + get: function () { + + return this._keys[this._k]; + + } + +}); + +Phaser.Keyboard.prototype.constructor = Phaser.Keyboard; + +/** +* A key code represents a physical key on a keyboard. +* +* The KeyCode class contains commonly supported keyboard key codes which can be used +* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods. +* +* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. +* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. +* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property. +* +* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; +* the latter approach is supported for compatibility. +* +* @class Phaser.KeyCode +*/ +Phaser.KeyCode = { + /** @static */ + A: "A".charCodeAt(0), + /** @static */ + B: "B".charCodeAt(0), + /** @static */ + C: "C".charCodeAt(0), + /** @static */ + D: "D".charCodeAt(0), + /** @static */ + E: "E".charCodeAt(0), + /** @static */ + F: "F".charCodeAt(0), + /** @static */ + G: "G".charCodeAt(0), + /** @static */ + H: "H".charCodeAt(0), + /** @static */ + I: "I".charCodeAt(0), + /** @static */ + J: "J".charCodeAt(0), + /** @static */ + K: "K".charCodeAt(0), + /** @static */ + L: "L".charCodeAt(0), + /** @static */ + M: "M".charCodeAt(0), + /** @static */ + N: "N".charCodeAt(0), + /** @static */ + O: "O".charCodeAt(0), + /** @static */ + P: "P".charCodeAt(0), + /** @static */ + Q: "Q".charCodeAt(0), + /** @static */ + R: "R".charCodeAt(0), + /** @static */ + S: "S".charCodeAt(0), + /** @static */ + T: "T".charCodeAt(0), + /** @static */ + U: "U".charCodeAt(0), + /** @static */ + V: "V".charCodeAt(0), + /** @static */ + W: "W".charCodeAt(0), + /** @static */ + X: "X".charCodeAt(0), + /** @static */ + Y: "Y".charCodeAt(0), + /** @static */ + Z: "Z".charCodeAt(0), + /** @static */ + ZERO: "0".charCodeAt(0), + /** @static */ + ONE: "1".charCodeAt(0), + /** @static */ + TWO: "2".charCodeAt(0), + /** @static */ + THREE: "3".charCodeAt(0), + /** @static */ + FOUR: "4".charCodeAt(0), + /** @static */ + FIVE: "5".charCodeAt(0), + /** @static */ + SIX: "6".charCodeAt(0), + /** @static */ + SEVEN: "7".charCodeAt(0), + /** @static */ + EIGHT: "8".charCodeAt(0), + /** @static */ + NINE: "9".charCodeAt(0), + /** @static */ + NUMPAD_0: 96, + /** @static */ + NUMPAD_1: 97, + /** @static */ + NUMPAD_2: 98, + /** @static */ + NUMPAD_3: 99, + /** @static */ + NUMPAD_4: 100, + /** @static */ + NUMPAD_5: 101, + /** @static */ + NUMPAD_6: 102, + /** @static */ + NUMPAD_7: 103, + /** @static */ + NUMPAD_8: 104, + /** @static */ + NUMPAD_9: 105, + /** @static */ + NUMPAD_MULTIPLY: 106, + /** @static */ + NUMPAD_ADD: 107, + /** @static */ + NUMPAD_ENTER: 108, + /** @static */ + NUMPAD_SUBTRACT: 109, + /** @static */ + NUMPAD_DECIMAL: 110, + /** @static */ + NUMPAD_DIVIDE: 111, + /** @static */ + F1: 112, + /** @static */ + F2: 113, + /** @static */ + F3: 114, + /** @static */ + F4: 115, + /** @static */ + F5: 116, + /** @static */ + F6: 117, + /** @static */ + F7: 118, + /** @static */ + F8: 119, + /** @static */ + F9: 120, + /** @static */ + F10: 121, + /** @static */ + F11: 122, + /** @static */ + F12: 123, + /** @static */ + F13: 124, + /** @static */ + F14: 125, + /** @static */ + F15: 126, + /** @static */ + COLON: 186, + /** @static */ + EQUALS: 187, + /** @static */ + COMMA: 188, + /** @static */ + UNDERSCORE: 189, + /** @static */ + PERIOD: 190, + /** @static */ + QUESTION_MARK: 191, + /** @static */ + TILDE: 192, + /** @static */ + OPEN_BRACKET: 219, + /** @static */ + BACKWARD_SLASH: 220, + /** @static */ + CLOSED_BRACKET: 221, + /** @static */ + QUOTES: 222, + /** @static */ + BACKSPACE: 8, + /** @static */ + TAB: 9, + /** @static */ + CLEAR: 12, + /** @static */ + ENTER: 13, + /** @static */ + SHIFT: 16, + /** @static */ + CONTROL: 17, + /** @static */ + ALT: 18, + /** @static */ + CAPS_LOCK: 20, + /** @static */ + ESC: 27, + /** @static */ + SPACEBAR: 32, + /** @static */ + PAGE_UP: 33, + /** @static */ + PAGE_DOWN: 34, + /** @static */ + END: 35, + /** @static */ + HOME: 36, + /** @static */ + LEFT: 37, + /** @static */ + UP: 38, + /** @static */ + RIGHT: 39, + /** @static */ + DOWN: 40, + /** @static */ + PLUS: 43, + /** @static */ + MINUS: 44, + /** @static */ + INSERT: 45, + /** @static */ + DELETE: 46, + /** @static */ + HELP: 47, + /** @static */ + NUM_LOCK: 144 +}; + +// Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility +for (var key in Phaser.KeyCode) +{ + if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/)) + { + Phaser.Keyboard[key] = Phaser.KeyCode[key]; + } +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +Phaser.Component = function () {}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. +* +* @class +*/ +Phaser.Component.Angle = function () {}; + +Phaser.Component.Angle.prototype = { + + /** + * The angle property is the rotation of the Game Object in *degrees* from its original orientation. + * + * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. + * + * Values outside this range are added to or subtracted from 360 to obtain a value within the range. + * For example, the statement player.angle = 450 is the same as player.angle = 90. + * + * If you wish to work in radians instead of degrees you can use the property `rotation` instead. + * Working in radians is slightly faster as it doesn't have to perform any calculations. + * + * @property {number} angle + */ + angle: { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); + + }, + + set: function(value) { + + this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. +* +* @class +*/ +Phaser.Component.Animation = function () {}; + +Phaser.Component.Animation.prototype = { + + /** + * Plays an Animation. + * + * The animation should have previously been created via `animations.add`. + * + * If the animation is already playing calling this again won't do anything. + * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. + * + * @method + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation. + */ + play: function (name, frameRate, loop, killOnComplete) { + + if (this.animations) + { + return this.animations.play(name, frameRate, loop, killOnComplete); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. +* It is used by the InWorld component. +* +* @class +*/ +Phaser.Component.AutoCull = function () {}; + +Phaser.Component.AutoCull.prototype = { + + /** + * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. + * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. + * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} autoCull + * @default + */ + autoCull: false, + + /** + * Checks if the Game Objects bounds intersect with the Game Camera bounds. + * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + if (!this.autoCull && !this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + } + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Bounds component contains properties related to the bounds of the Game Object. +* +* @class +*/ +Phaser.Component.Bounds = function () {}; + +Phaser.Component.Bounds.prototype = { + + /** + * The amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * anchor.x`. + * It will only be > 0 if anchor.x is not equal to zero. + * + * @property {number} offsetX + * @readOnly + */ + offsetX: { + + get: function () { + + return this.anchor.x * this.width; + + } + + }, + + /** + * The amount the Game Object is visually offset from its y coordinate. + * This is the same as `height * anchor.y`. + * It will only be > 0 if anchor.y is not equal to zero. + * + * @property {number} offsetY + * @readOnly + */ + offsetY: { + + get: function () { + + return this.anchor.y * this.height; + + } + + }, + + /** + * The local center x coordinate of the Game Object. + * This is the same as `(x - offsetX) + (width / 2)`. + * + * @property {number} centerX + */ + centerX: { + + get: function () { + + return (this.x - this.offsetX) + (this.width * 0.5); + + }, + + set: function (value) { + + this.x = (value + this.offsetX) - (this.width * 0.5); + + } + + }, + + /** + * The local center y coordinate of the Game Object. + * This is the same as `(y - offsetY) + (height / 2)`. + * + * @property {number} centerY + */ + centerY: { + + get: function () { + + return (this.y - this.offsetY) + (this.height * 0.5); + + }, + + set: function (value) { + + this.y = (value + this.offsetY) - (this.height * 0.5); + + } + + }, + + /** + * The left coordinate of the Game Object. + * This is the same as `x - offsetX`. + * + * @property {number} left + */ + left: { + + get: function () { + + return this.x - this.offsetX; + + }, + + set: function (value) { + + this.x = value + this.offsetX; + + } + + }, + + /** + * The right coordinate of the Game Object. + * This is the same as `x + width - offsetX`. + * + * @property {number} right + */ + right: { + + get: function () { + + return (this.x + this.width) - this.offsetX; + + }, + + set: function (value) { + + this.x = value - (this.width) + this.offsetX; + + } + + }, + + /** + * The y coordinate of the Game Object. + * This is the same as `y - offsetY`. + * + * @property {number} top + */ + top: { + + get: function () { + + return this.y - this.offsetY; + + }, + + set: function (value) { + + this.y = value + this.offsetY; + + } + + }, + + /** + * The sum of the y and height properties. + * This is the same as `y + height - offsetY`. + * + * @property {number} bottom + */ + bottom: { + + get: function () { + + return (this.y + this.height) - this.offsetY; + + }, + + set: function (value) { + + this.y = value - (this.height) + this.offsetY; + + } + + }, + + /** + * Aligns this Game Object within another Game Object, or Rectangle, known as the + * 'container', to one of 9 possible positions. + * + * The container must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the container. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, + * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * container, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignIn: function (container, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = container.left - offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = container.centerX + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = container.right + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.left = container.left - offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.CENTER: + this.centerX = container.centerX + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.right = container.right + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = container.left - offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = container.centerX + offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = container.right + offsetX; + this.bottom = container.bottom + offsetY; + break; + } + + return this; + + }, + + /** + * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the + * 'parent', in one of 11 possible positions. + * + * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the parent. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, + * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, + * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * parent, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignTo: function (parent, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = parent.left - offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = parent.centerX + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = parent.right + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.LEFT_TOP: + this.right = parent.left - offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.right = parent.left - offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.LEFT_BOTTOM: + this.right = parent.left - offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.RIGHT_TOP: + this.left = parent.right + offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.left = parent.right + offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.RIGHT_BOTTOM: + this.left = parent.right + offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = parent.left - offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = parent.centerX + offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = parent.right + offsetX; + this.top = parent.bottom + offsetY; + break; + } + + return this; + + } + +}; + +// Phaser.Group extensions + +Phaser.Group.prototype.alignIn = Phaser.Component.Bounds.prototype.alignIn; +Phaser.Group.prototype.alignTo = Phaser.Component.Bounds.prototype.alignTo; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The BringToTop Component features quick access to Group sorting related methods. +* +* @class +*/ +Phaser.Component.BringToTop = function () {}; + +/** +* Brings this Game Object to the top of its parents display list. +* Visually this means it will render over the top of any old child in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.bringToTop = function() { + + if (this.parent) + { + this.parent.bringToTop(this); + } + + return this; + +}; + +/** +* Sends this Game Object to the bottom of its parents display list. +* Visually this means it will render below all other children in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.sendToBack = function() { + + if (this.parent) + { + this.parent.sendToBack(this); + } + + return this; + +}; + +/** +* Moves this Game Object up one place in its parents display list. +* This call has no effect if the Game Object is already at the top of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveUp = function () { + + if (this.parent) + { + this.parent.moveUp(this); + } + + return this; + +}; + +/** +* Moves this Game Object down one place in its parents display list. +* This call has no effect if the Game Object is already at the bottom of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveDown = function () { + + if (this.parent) + { + this.parent.moveDown(this); + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Core Component Features. +* +* @class +*/ +Phaser.Component.Core = function () {}; + +/** + * @property {boolean} skipTypeChecks - Skip type checks in {@link #init}. + * @static + * @default + */ +Phaser.Component.Core.skipTypeChecks = false; + +/** +* Installs / registers mixin components. +* +* The `this` context should be that of the applicable object instance or prototype. +* +* @method +* @protected +*/ +Phaser.Component.Core.install = function (components) { + + // Always install 'Core' first + Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype); + + this.components = {}; + + for (var i = 0; i < components.length; i++) + { + var id = components[i]; + var replace = false; + + if (id === 'Destroy') + { + replace = true; + } + + Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace); + + this.components[id] = true; + } + +}; + +/** +* Initializes the mixin components. +* +* The `this` context should be an instance of the component mixin target. +* +* @method +* @protected +*/ +Phaser.Component.Core.init = function (game, x, y, key, frame) { + + if (!Phaser.Component.Core.skipTypeChecks) + { + if (!(game instanceof Phaser.Game)) + { + throw new Error('The value passed as the `game` argument (' + game + ') is not an instance of Phaser.Game.'); + } + + if (typeof x !== 'number') + { + console.warn('The `x` argument value (%s) should be a number.', x); + x = 0; // This would be done implicitly in position.set(). + } + + if (typeof y !== 'number') + { + console.warn('The `y` argument value (%s) should be a number.', y); + y = 0; // This would be done implicitly in position.set(). + } + } + + this.game = game; + this.key = key; + this.data = {}; + + this.position.set(x, y); + this.world = new Phaser.Point(x, y); + this.previousPosition = new Phaser.Point(x, y); + + this.events = new Phaser.Events(this); + + this._bounds = new Phaser.Rectangle(); + + if (this.components.PhysicsBody) + { + // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype. + this.body = this.body; + } + + if (this.components.Animation) + { + this.animations = new Phaser.AnimationManager(this); + } + + if (this.components.LoadTexture && key !== null) + { + this.loadTexture(key, frame); + } + + if (this.components.FixedToCamera) + { + this.cameraOffset = new Phaser.Point(x, y); + } + +}; + +Phaser.Component.Core.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty); + + if (this.visible) + { + this.renderOrderID = this.game.stage.currentRenderOrderID++; + } + + if (this.animations) + { + this.animations.update(); + } + + if (this.body) + { + this.body.preUpdate(); + } + + this.preUpdateChildren(); + + return true; + +}; + +Phaser.Component.Core.prototype = { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + game: null, + + /** + * A user defined name given to this Game Object. + * This value isn't ever used internally by Phaser, it is meant as a game level property. + * @property {string} name + * @default + */ + name: '', + + /** + * An empty Object that belongs to this Game Object. + * This value isn't ever used internally by Phaser, but may be used by your own code, or + * by Phaser Plugins, to store data that needs to be associated with the Game Object, + * without polluting the Game Object directly. + * @property {Object} data + * @default + */ + data: {}, + + /** + * The components this Game Object has installed. + * @property {object} components + * @protected + */ + components: {}, + + /** + * The z depth of this Game Object within its parent Group. + * No two objects in a Group can have the same z value. + * This value is adjusted automatically whenever the Group hierarchy changes. + * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. + * @property {number} z + * @readOnly + */ + z: 0, + + /** + * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this + * Game Object, or any of its components. + * @see Phaser.Events + * @property {Phaser.Events} events + */ + events: undefined, + + /** + * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. + * Through it you can create, play, pause and stop animations. + * @see Phaser.AnimationManager + * @property {Phaser.AnimationManager} animations + */ + animations: undefined, + + /** + * The key of the image or texture used by this Game Object during rendering. + * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. + * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. + * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. + * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key + */ + key: '', + + /** + * The world coordinates of this Game Object in pixels. + * Depending on where in the display list this Game Object is placed this value can differ from `position`, + * which contains the x/y coordinates relative to the Game Objects parent. + * @property {Phaser.Point} world + */ + world: null, + + /** + * A debug flag designed for use with `Game.enableStep`. + * @property {boolean} debug + * @default + */ + debug: false, + + /** + * The position the Game Object was located in the previous frame. + * @property {Phaser.Point} previousPosition + * @readOnly + */ + previousPosition: null, + + /** + * The rotation the Game Object was in set to in the previous frame. Value is in radians. + * @property {number} previousRotation + * @readOnly + */ + previousRotation: 0, + + /** + * The render order ID is used internally by the renderer and Input Manager and should not be modified. + * This property is mostly used internally by the renderers, but is exposed for the use of plugins. + * @property {number} renderOrderID + * @readOnly + */ + renderOrderID: 0, + + /** + * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. + * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. + * @property {boolean} fresh + * @readOnly + */ + fresh: true, + + /** + * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. + * You can set it directly to allow you to flag an object to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy an object from within one of its own callbacks + * such as with Buttons or other Input events. + * + * @property {boolean} pendingDestroy + */ + pendingDestroy: false, + + /** + * @property {Phaser.Rectangle} _bounds - Internal cache var. + * @private + */ + _bounds: null, + + /** + * @property {boolean} _exists - Internal cache var. + * @private + */ + _exists: true, + + /** + * Controls if this Game Object is processed by the core game loop. + * If this Game Object has a physics body it also controls if its physics body is updated or not. + * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. + * It also toggles the `visible` property to false as well. + * + * Setting `exists` to true will add its physics body back in to the physics world, if it has one. + * It will also set the `visible` property to `true`. + * + * @property {boolean} exists + */ + exists: { + + get: function () { + + return this._exists; + + }, + + set: function (value) { + + if (value) + { + this._exists = true; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.addToWorld(); + } + + this.visible = true; + } + else + { + this._exists = false; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.removeFromWorld(); + } + + this.visible = false; + } + + } + + }, + + /** + * Internal method called by preUpdate. + * + * @method + * @protected + */ + preUpdateChildren: function() { + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + }, + + /** + * Override this method in your own custom objects to handle any update requirements. + * It is called immediately after `preUpdate` and before `postUpdate`. + * Remember if this Game Object has any children you should call update on those too. + * + * @method + */ + update: function() { + + }, + + /** + * Internal method called by the World postUpdate cycle. + * + * @method + * @protected + */ + postUpdate: function() { + + if (this.customRender) + { + this.key.render(); + } + + if (this.components.PhysicsBody) + { + Phaser.Component.PhysicsBody.postUpdate.call(this); + } + + if (this.components.FixedToCamera) + { + Phaser.Component.FixedToCamera.postUpdate.call(this); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, +* which can be updated in real-time. +* +* @class +*/ +Phaser.Component.Crop = function () {}; + +Phaser.Component.Crop.prototype = { + + /** + * The Rectangle used to crop the texture this Game Object uses. + * Set this property via `crop`. + * If you modify this property directly you must call `updateCrop` in order to have the change take effect. + * @property {Phaser.Rectangle} cropRect + * @default + */ + cropRect: null, + + /** + * @property {Phaser.Rectangle} _crop - Internal cache var. + * @private + */ + _crop: null, + + /** + * Crop allows you to crop the texture being used to display this Game Object. + * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. + * + * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, + * or by modifying `cropRect` property directly and then calling `updateCrop`. + * + * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object + * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. + * + * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, + * in which case the values are duplicated to a local object. + * + * @method + * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. + * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. + */ + crop: function (rect, copy) { + + if (copy === undefined) { copy = false; } + + if (rect) + { + if (copy && this.cropRect !== null) + { + this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height); + } + else if (copy && this.cropRect === null) + { + this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height); + } + else + { + this.cropRect = rect; + } + + this.updateCrop(); + } + else + { + this._crop = null; + this.cropRect = null; + + this.resetFrame(); + } + + }, + + /** + * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, + * or the rectangle it references, then you need to update the crop frame by calling this method. + * + * @method + */ + updateCrop: function () { + + if (!this.cropRect) + { + return; + } + + var oldX = this.texture.crop.x; + var oldY = this.texture.crop.y; + var oldW = this.texture.crop.width; + var oldH = this.texture.crop.height; + + this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop); + this._crop.x += this._frame.x; + this._crop.y += this._frame.y; + + var cx = Math.max(this._frame.x, this._crop.x); + var cy = Math.max(this._frame.y, this._crop.y); + var cw = Math.min(this._frame.right, this._crop.right) - cx; + var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy; + + this.texture.crop.x = cx; + this.texture.crop.y = cy; + this.texture.crop.width = cw; + this.texture.crop.height = ch; + + this.texture.frame.width = Math.min(cw, this.cropRect.width); + this.texture.frame.height = Math.min(ch, this.cropRect.height); + + this.texture.width = this.texture.frame.width; + this.texture.height = this.texture.frame.height; + + this.texture._updateUvs(); + + if (this.tint !== 0xffffff && (oldX !== cx || oldY !== cy || oldW !== cw || oldH !== ch)) + { + this.texture.requiresReTint = true; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Delta component provides access to delta values between the Game Objects current and previous position. +* +* @class +*/ +Phaser.Component.Delta = function () {}; + +Phaser.Component.Delta.prototype = { + + /** + * Returns the delta x value. The difference between world.x now and in the previous frame. + * + * The value will be positive if the Game Object has moved to the right or negative if to the left. + * + * @property {number} deltaX + * @readonly + */ + deltaX: { + + get: function() { + + return this.world.x - this.previousPosition.x; + + } + + }, + + /** + * Returns the delta y value. The difference between world.y now and in the previous frame. + * + * The value will be positive if the Game Object has moved down or negative if up. + * + * @property {number} deltaY + * @readonly + */ + deltaY: { + + get: function() { + + return this.world.y - this.previousPosition.y; + + } + + }, + + /** + * Returns the delta z value. The difference between rotation now and in the previous frame. + * + * @property {number} deltaZ - The delta value. + * @readonly + */ + deltaZ: { + + get: function() { + + return this.rotation - this.previousRotation; + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Destroy component is responsible for destroying a Game Object. +* +* @class +*/ +Phaser.Component.Destroy = function () {}; + +Phaser.Component.Destroy.prototype = { + + /** + * As a Game Object runs through its destroy method this flag is set to true, + * and can be checked in any sub-systems or plugins it is being destroyed from. + * @property {boolean} destroyPhase + * @readOnly + */ + destroyPhase: false, + + /** + * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present + * and nulls its reference to `game`, freeing it up for garbage collection. + * + * If this Game Object has the Events component it will also dispatch the `onDestroy` event. + * + * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've + * more than one Game Object sharing the same BaseTexture. + * + * @method + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? + * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. + */ + destroy: function (destroyChildren, destroyTexture) { + + if (this.game === null || this.destroyPhase) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (destroyTexture === undefined) { destroyTexture = false; } + + this.destroyPhase = true; + + if (this.events) + { + this.events.onDestroy$dispatch(this); + } + + if (this.parent) + { + if (this.parent instanceof Phaser.Group) + { + this.parent.remove(this); + } + else + { + this.parent.removeChild(this); + } + } + + if (this.input) + { + this.input.destroy(); + } + + if (this.animations) + { + this.animations.destroy(); + } + + if (this.body) + { + this.body.destroy(); + } + + if (this.events) + { + this.events.destroy(); + } + + this.game.tweens.removeFrom(this); + + var i = this.children.length; + + if (destroyChildren) + { + while (i--) + { + this.children[i].destroy(destroyChildren); + } + } + else + { + while (i--) + { + this.removeChild(this.children[i]); + } + } + + if (this._crop) + { + this._crop = null; + this.cropRect = null; + } + + if (this._frame) + { + this._frame = null; + } + + if (Phaser.Video && this.key instanceof Phaser.Video) + { + this.key.onChangeSource.remove(this.resizeFrame, this); + } + + if (Phaser.BitmapText && this._glyphs) + { + this._glyphs = []; + } + + this.alive = false; + this.exists = false; + this.visible = false; + + this.filters = null; + this.mask = null; + this.game = null; + + this.data = {}; + + // In case Pixi is still going to try and render it even though destroyed + this.renderable = false; + + if (this.transformCallback) + { + this.transformCallback = null; + this.transformCallbackContext = null; + } + + // Pixi level DisplayObject destroy + this.hitArea = null; + this.parent = null; + this.stage = null; + this.worldTransform = null; + this.filterArea = null; + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + // Texture? + if (destroyTexture) + { + this.texture.destroy(true); + } + + this.destroyPhase = false; + this.pendingDestroy = false; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Events component is a collection of events fired by the parent Game Object. +* +* Phaser uses what are known as 'Signals' for all event handling. All of the events in +* this class are signals you can subscribe to, much in the same way you'd "listen" for +* an event. +* +* For example to tell when a Sprite has been added to a new group, you can bind a function +* to the {@link #onAddedToGroup} signal: +* +* `sprite.events.onAddedToGroup.add(yourFunction, this);` +* +* Where `yourFunction` is the function you want called when this event occurs. +* +* For more details about how signals work please see the {@link Phaser.Signal} class. +* +* The Input-related events will only be dispatched if the Sprite has had {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true` +* and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. +* +* @class Phaser.Events +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. +*/ +Phaser.Events = function (sprite) { + + /** + * @property {Phaser.Sprite} parent - The Sprite that owns these events. + */ + this.parent = sprite; + + // The signals are automatically added by the corresponding proxy properties + +}; + +Phaser.Events.prototype = { + + /** + * Removes all events. + * + * @method Phaser.Events#destroy + */ + destroy: function () { + + this._parent = null; + + if (this._onDestroy) { this._onDestroy.dispose(); } + if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } + if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } + if (this._onKilled) { this._onKilled.dispose(); } + if (this._onRevived) { this._onRevived.dispose(); } + if (this._onEnterBounds) { this._onEnterBounds.dispose(); } + if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } + + if (this._onInputOver) { this._onInputOver.dispose(); } + if (this._onInputOut) { this._onInputOut.dispose(); } + if (this._onInputDown) { this._onInputDown.dispose(); } + if (this._onInputUp) { this._onInputUp.dispose(); } + if (this._onDragStart) { this._onDragStart.dispose(); } + if (this._onDragUpdate) { this._onDragUpdate.dispose(); } + if (this._onDragStop) { this._onDragStop.dispose(); } + + if (this._onAnimationStart) { this._onAnimationStart.dispose(); } + if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } + if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } + + }, + + // The following properties are sentinels that will be replaced with getters + + /** + * This signal is dispatched when this Game Object is added to a new {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was added to the Group. + * - {Phaser.Group} The Group it was added to. + * + * @property {Phaser.Signal} onAddedToGroup + */ + onAddedToGroup: null, + + /** + * This signal is dispatched when the Game Object is removed from a {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was removed from the Group. + * - {Phaser.Group} The Group it was removed from. + * + * @property {Phaser.Signal} onRemovedFromGroup + */ + onRemovedFromGroup: null, + + /** + * This signal is dispatched when the Game Object is destroyed. + * This happens when {@link Phaser.Sprite#destroy Sprite.destroy()} is called, or {@link Phaser.Group#destroy Group.destroy()} with `destroyChildren` set to true. + * It is sent one argument: + * + * - {any} The Game Object that was destroyed. + * + * @property {Phaser.Signal} onDestroy + */ + onDestroy: null, + + /** + * This signal is dispatched when the Game Object is killed. + * This happens when {@link Phaser.Sprite#kill Sprite.kill()} is called. + * Please understand the difference between {@link Phaser.Sprite#kill kill} and {@link Phaser.Sprite#destroy destroy} by looking at their respective methods. + * It is sent one argument: + * + * - {any} The Game Object that was killed. + * + * @property {Phaser.Signal} onKilled + */ + onKilled: null, + + /** + * This signal is dispatched when the Game Object is revived from a previously killed state. + * This happens when {@link Phaser.Sprite#revive Sprite.revive()} is called. + * It is sent one argument: + * + * - {any} The Game Object that was revived. + * + * @property {Phaser.Signal} onRevived + */ + onRevived: null, + + /** + * This signal is dispatched when the Game Object leaves the Phaser.World {@link Phaser.World#bounds bounds}. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that left the World bounds. + * + * @property {Phaser.Signal} onOutOfBounds + */ + onOutOfBounds: null, + + /** + * This signal is dispatched when the Game Object returns within the Phaser.World {@link Phaser.World#bounds bounds}, having previously been outside of them. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that entered the World bounds. + * + * @property {Phaser.Signal} onEnterBounds + */ + onEnterBounds: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an over event from a {@link Phaser.Pointer}. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOver + */ + onInputOver: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an out event from a {@link Phaser.Pointer}, which was previously over it. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOut + */ + onInputOut: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives a down event from a {@link Phaser.Pointer}. This effectively means the Pointer has been + * pressed down (but not yet released) on the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputDown + */ + onInputDown: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an up event from a {@link Phaser.Pointer}. This effectively means the Pointer had been + * pressed down, and was then released on the Game Object. + * It is sent three arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {boolean} isOver - Is the Pointer still over the Game Object? + * + * @property {Phaser.Signal} onInputUp + */ + onInputUp: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} starts to drag the Game Object, taking into consideration the various + * drag limitations that may be set. + * It is sent four arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The x coordinate that the drag started from. + * - {number} The y coordinate that the drag started from. + * + * @property {Phaser.Signal} onDragStart + */ + onDragStart: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} is actively dragging the Game Object. + * Be warned: This is a high volume Signal. Be careful what you bind to it. + * It is sent six arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The new x coordinate of the Game Object. + * - {number} The new y coordinate of the Game Object. + * - {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. + * - {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. + * + * @property {Phaser.Signal} onDragUpdate + */ + onDragUpdate: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} stops dragging the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onDragStop + */ + onDragStop: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been played. + * You can also listen to {@link Phaser.Animation#onStart} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was started. + * + * @property {Phaser.Signal} onAnimationStart + */ + onAnimationStart: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been stopped (via {@link Phaser.AnimationManager#stop animation.stop()} and the `dispatchComplete` argument has been set. + * You can also listen to {@link Phaser.Animation#onComplete} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was stopped. + * + * @property {Phaser.Signal} onAnimationComplete + */ + onAnimationComplete: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has looped playback. + * You can also listen to {@link Phaser.Animation#onLoop} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that looped. + * + * @property {Phaser.Signal} onAnimationLoop + */ + onAnimationLoop: null + +}; + +Phaser.Events.prototype.constructor = Phaser.Events; + +// Create an auto-create proxy getter and dispatch method for all events. +// The backing property is the same as the event name, prefixed with '_' +// and the dispatch method is the same as the event name postfixed with '$dispatch'. +for (var prop in Phaser.Events.prototype) +{ + if (!Phaser.Events.prototype.hasOwnProperty(prop) || + prop.indexOf('on') !== 0 || + Phaser.Events.prototype[prop] !== null) + { + continue; + } + + (function (prop, backing) { + 'use strict'; + + // The accessor creates a new Signal; and so it should only be used from user-code. + Object.defineProperty(Phaser.Events.prototype, prop, { + get: function () { + return this[backing] || (this[backing] = new Phaser.Signal()); + } + }); + + // The dispatcher will only broadcast on an already-created signal; call this internally. + Phaser.Events.prototype[prop + '$dispatch'] = function () { + return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; + }; + + })(prop, '_' + prop); + +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless +* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. +* +* @class +*/ +Phaser.Component.FixedToCamera = function () {}; + +/** + * The FixedToCamera component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.FixedToCamera.postUpdate = function () { + + if (this.fixedToCamera) + { + 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.Component.FixedToCamera.prototype = { + + /** + * @property {boolean} _fixedToCamera + * @private + */ + _fixedToCamera: false, + + /** + * A Game Object that is "fixed" to the camera is rendered at a given x/y offsets from the top left of the camera. The offsets + * are stored in the `cameraOffset` property, which is initialized with the current object coordinates. + * + * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. + * + * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world + * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times + * regardless where in the world the camera is. + * + * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. + * + * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. + * + * @property {boolean} fixedToCamera + */ + fixedToCamera: { + + get: function () { + + return this._fixedToCamera; + + }, + + set: function (value) { + + if (value) + { + this._fixedToCamera = true; + this.cameraOffset.set(this.x, this.y); + } + else + { + this._fixedToCamera = false; + } + + } + + }, + + /** + * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. + * + * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. + * @property {Phaser.Point} cameraOffset + */ + cameraOffset: new Phaser.Point() + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Health component provides the ability for Game Objects to have a `health` property +* that can be damaged and reset through game code. +* Requires the LifeSpan component. +* +* @class +*/ +Phaser.Component.Health = function () {}; + +Phaser.Component.Health.prototype = { + + /** + * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. + * + * It can be used in combination with the `damage` method or modified directly. + * + * @property {number} health + * @default + */ + health: 1, + + /** + * The Game Objects maximum health value. This works in combination with the `heal` method to ensure + * the health value never exceeds the maximum. + * + * @property {number} maxHealth + * @default + */ + maxHealth: 100, + + /** + * Damages the Game Object. This removes the given amount of health from the `health` property. + * + * If health is taken below or is equal to zero then the `kill` method is called. + * + * @method + * @param {number} amount - The amount to subtract from the current `health` value. + * @return {Phaser.Sprite} This instance. + */ + damage: function (amount) { + + if (this.alive) + { + this.health -= amount; + + if (this.health <= 0) + { + this.kill(); + } + } + + return this; + + }, + + /** + * Sets the health property of the Game Object to the given amount. + * Will never exceed the `maxHealth` value. + * + * @method + * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + setHealth: function (amount) { + + this.health = amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + + return this; + + }, + + /** + * Heal the Game Object. This adds the given amount of health to the `health` property. + * + * @method + * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + heal: function (amount) { + + if (this.alive) + { + this.health += amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InCamera component checks if the Game Object intersects with the Game Camera. +* +* @class +*/ +Phaser.Component.InCamera = function () {}; + +Phaser.Component.InCamera.prototype = { + + /** + * Checks if this Game Objects bounds intersects with the Game Cameras bounds. + * + * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. + * + * An object outside the bounds can be considered for camera culling if it has the AutoCull component. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. +* +* @class +*/ +Phaser.Component.InputEnabled = function () {}; + +Phaser.Component.InputEnabled.prototype = { + + /** + * The Input Handler for this Game Object. + * + * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. + * + * After you have done this, this property will be a reference to the Phaser InputHandler. + * @property {Phaser.InputHandler|null} input + */ + input: null, + + /** + * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created + * for this Game Object and it will then start to process click / touch events and more. + * + * You can then access the Input Handler via `this.input`. + * + * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. + * + * If you set this property to false it will stop the Input Handler from processing any more input events. + * + * If you want to _temporarily_ disable input for a Game Object, then it's better to set + * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. + * You can then toggle this back on as needed. + * + * @property {boolean} inputEnabled + */ + inputEnabled: { + + get: function () { + + return (this.input && this.input.enabled); + + }, + + set: function (value) { + + if (value) + { + if (this.input === null) + { + this.input = new Phaser.InputHandler(this); + this.input.start(); + } + else if (this.input && !this.input.enabled) + { + this.input.start(); + } + } + else + { + if (this.input && this.input.enabled) + { + this.input.stop(); + } + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InWorld component checks if a Game Object is within the Game World Bounds. +* An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. +* If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. +* +* @class +*/ +Phaser.Component.InWorld = function () {}; + +/** + * The InWorld component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.InWorld.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + // Cache the bounds if we need it + if (this.autoCull || this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + + if (this.autoCull) + { + // Won't get rendered but will still get its transform updated + if (this.game.world.camera.view.intersects(this._bounds)) + { + this.renderable = true; + this.game.world.camera.totalInView++; + } + else + { + this.renderable = false; + + if (this.outOfCameraBoundsKill) + { + this.kill(); + return false; + } + } + } + + if (this.checkWorldBounds) + { + // The Sprite is already out of the world bounds, so let's check to see if it has come back again + if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds)) + { + this._outOfBoundsFired = false; + this.events.onEnterBounds$dispatch(this); + } + else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds)) + { + // The Sprite WAS in the screen, but has now left. + this._outOfBoundsFired = true; + this.events.onOutOfBounds$dispatch(this); + + if (this.outOfBoundsKill) + { + this.kill(); + return false; + } + } + } + } + + return true; + +}; + +Phaser.Component.InWorld.prototype = { + + /** + * If this is set to `true` the Game Object checks if it is within the World bounds each frame. + * + * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. + * + * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. + * + * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. + * + * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} checkWorldBounds + * @default + */ + checkWorldBounds: false, + + /** + * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. + * + * @property {boolean} outOfBoundsKill + * @default + */ + outOfBoundsKill: false, + + /** + * If this and the `autoCull` property are both set to `true`, then the `kill` method + * is called as soon as the Game Object leaves the camera bounds. + * + * @property {boolean} outOfCameraBoundsKill + * @default + */ + outOfCameraBoundsKill: false, + + /** + * @property {boolean} _outOfBoundsFired - Internal state var. + * @private + */ + _outOfBoundsFired: false, + + /** + * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. + * + * @property {boolean} inWorld + * @readonly + */ + inWorld: { + + get: function () { + + return this.game.world.bounds.intersects(this.getBounds()); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* LifeSpan Component Features. +* +* @class +*/ +Phaser.Component.LifeSpan = function () {}; + +/** + * The LifeSpan component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.LifeSpan.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.lifespan > 0) + { + this.lifespan -= this.game.time.physicsElapsedMS; + + if (this.lifespan <= 0) + { + this.kill(); + return false; + } + } + + return true; + +}; + +Phaser.Component.LifeSpan.prototype = { + + /** + * A useful flag to control if the Game Object is alive or dead. + * + * This is set automatically by the Health components `damage` method should the object run out of health. + * Or you can toggle it via your game code. + * + * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. + * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. + * @property {boolean} alive + * @default + */ + alive: true, + + /** + * The lifespan allows you to give a Game Object a lifespan in milliseconds. + * + * Once the Game Object is 'born' you can set this to a positive value. + * + * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. + * When it reaches zero it will call the `kill` method. + * + * Very handy for particles, bullets, collectibles, or any other short-lived entity. + * + * @property {number} lifespan + * @default + */ + lifespan: 0, + + /** + * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. + * + * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. + * + * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. + * + * @method + * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. + * @return {PIXI.DisplayObject} This instance. + */ + revive: function (health) { + + if (health === undefined) { health = 100; } + + this.alive = true; + this.exists = true; + this.visible = true; + + if (typeof this.setHealth === 'function') + { + this.setHealth(health); + } + + if (this.events) + { + this.events.onRevived$dispatch(this); + } + + return this; + + }, + + /** + * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. + * + * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. + * + * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, + * it doesn't destroy the object or free it up from memory. + * + * If you don't need this Game Object any more you should call `destroy` instead. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ + kill: function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + if (this.events) + { + this.events.onKilled$dispatch(this); + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. +* +* @class +*/ +Phaser.Component.LoadTexture = function () {}; + +Phaser.Component.LoadTexture.prototype = { + + /** + * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) + * @private + */ + customRender: false, + + /** + * @property {Phaser.Rectangle} _frame - Internal cache var. + * @private + */ + _frame: null, + + /** + * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. + * + * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. + * + * You should only use `loadTexture` if you want to replace the base texture entirely. + * + * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. + * + * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. + * Doing this then sets the key to be the `frame` argument (the frame is set to zero). + * + * This allows you to create sprites using `load.image` during development, and then change them + * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' + * and swapping it to be the key of the atlas data. + * + * Note: You cannot use a RenderTexture as a texture for a TileSprite. + * + * @method + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. + */ + loadTexture: function (key, frame, stopAnimation) { + + if (key === Phaser.PENDING_ATLAS) + { + key = frame; + frame = 0; + } + else + { + frame = frame || 0; + } + + if ((stopAnimation || stopAnimation === undefined) && this.animations) + { + this.animations.stop(); + } + + this.key = key; + this.customRender = false; + var cache = this.game.cache; + + var setFrame = true; + var smoothed = !this.texture.baseTexture.scaleMode; + + if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture) + { + this.key = key.key; + this.setTexture(key); + } + else if (Phaser.BitmapData && key instanceof Phaser.BitmapData) + { + this.customRender = true; + + this.setTexture(key.texture); + + if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA)) + { + setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame); + } + else + { + setFrame = !this.animations.loadFrameData(key.frameData, 0); + } + } + else if (Phaser.Video && key instanceof Phaser.Video) + { + this.customRender = true; + + // This works from a reference, which probably isn't what we need here + var valid = key.texture.valid; + this.setTexture(key.texture); + this.setFrame(key.texture.frame.clone()); + key.onChangeSource.add(this.resizeFrame, this); + this.texture.valid = valid; + } + else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer) + { + // this.customRender = true; + + this.setTexture(PIXI.Texture.fromCanvas(key.canvas)); + } + else if (key instanceof PIXI.Texture) + { + this.setTexture(key); + } + else + { + var img = cache.getImage(key, true); + + this.key = img.key; + this.setTexture(new PIXI.Texture(img.base)); + + if (key === '__default') + { + this.texture.baseTexture.skipRender = true; + } + else + { + this.texture.baseTexture.skipRender = false; + } + + setFrame = !this.animations.loadFrameData(img.frameData, frame); + } + + if (setFrame) + { + this._frame = Phaser.Rectangle.clone(this.texture.frame); + } + + if (!smoothed) + { + this.texture.baseTexture.scaleMode = 1; + } + + }, + + /** + * Sets the texture frame the Game Object uses for rendering. + * + * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. + * + * @method + * @param {Phaser.Frame} frame - The Frame to be used by the texture. + */ + setFrame: function (frame) { + + this._frame = frame; + + this.texture.frame.x = frame.x; + this.texture.frame.y = frame.y; + this.texture.frame.width = frame.width; + this.texture.frame.height = frame.height; + + this.texture.crop.x = frame.x; + this.texture.crop.y = frame.y; + this.texture.crop.width = frame.width; + this.texture.crop.height = frame.height; + + if (frame.trimmed) + { + if (this.texture.trim) + { + this.texture.trim.x = frame.spriteSourceSizeX; + this.texture.trim.y = frame.spriteSourceSizeY; + this.texture.trim.width = frame.sourceSizeW; + this.texture.trim.height = frame.sourceSizeH; + } + else + { + this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH }; + } + + this.texture.width = frame.sourceSizeW; + this.texture.height = frame.sourceSizeH; + this.texture.frame.width = frame.sourceSizeW; + this.texture.frame.height = frame.sourceSizeH; + } + else if (!frame.trimmed && this.texture.trim) + { + this.texture.trim = null; + } + + if (frame.rotated) + { + this.texture.rotated = true; + } + + if (this.cropRect) + { + this.updateCrop(); + } + + this.texture.requiresReTint = true; + + this.texture._updateUvs(); + + if (this.tilingTexture) + { + this.refreshTexture = true; + } + + }, + + /** + * Resizes the Frame dimensions that the Game Object uses for rendering. + * + * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData + * it can be useful to adjust the dimensions directly in this way. + * + * @method + * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. + * @param {integer} width - The new width of the texture. + * @param {integer} height - The new height of the texture. + */ + resizeFrame: function (parent, width, height) { + + this.texture.frame.resize(width, height); + this.texture.setFrame(this.texture.frame); + + }, + + /** + * Resets the texture frame dimensions that the Game Object uses for rendering. + * + * @method + */ + resetFrame: function () { + + if (this._frame) + { + this.setFrame(this._frame); + } + + }, + + /** + * Gets or sets the current frame index of the texture being used to render this Game Object. + * + * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, + * for example: `player.frame = 4`. + * + * If the frame index given doesn't exist it will revert to the first frame found in the texture. + * + * If you are using a texture atlas then you should use the `frameName` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {integer} frame + */ + frame: { + + get: function () { + return this.animations.frame; + }, + + set: function (value) { + this.animations.frame = value; + } + + }, + + /** + * Gets or sets the current frame name of the texture being used to render this Game Object. + * + * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, + * for example: `player.frameName = "idle"`. + * + * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. + * + * If you are using a sprite sheet then you should use the `frame` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {string} frameName + */ + frameName: { + + get: function () { + return this.animations.frameName; + }, + + set: function (value) { + this.animations.frameName = value; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. +* +* @class +*/ +Phaser.Component.Overlap = function () {}; + +Phaser.Component.Overlap.prototype = { + + /** + * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, + * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. + * + * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. + * + * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. + * It should be fine for low-volume testing where physics isn't required. + * + * @method + * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. + * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. + */ + overlap: function (displayObject) { + + return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds()); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The PhysicsBody component manages the Game Objects physics body and physics enabling. +* It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. +* +* @class +*/ +Phaser.Component.PhysicsBody = function () {}; + +/** + * The PhysicsBody component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.fresh && 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.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (this.body) + { + this.body.preUpdate(); + } + + this.fresh = false; + + this.preUpdateChildren(); + + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this._exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + return true; + +}; + +/** + * The PhysicsBody component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.postUpdate = function () { + + if (this.exists && this.body) + { + this.body.postUpdate(); + } + +}; + +Phaser.Component.PhysicsBody.prototype = { + + /** + * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated + * properties and methods via it. + * + * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. + * + * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object + * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. + * + * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. + * + * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, + * so the physics body is centered on the Game Object. + * + * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. + * + * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body + * @default + */ + body: null, + + /** + * The position of the Game Object on the x axis relative to the local coordinates of the parent. + * + * @property {number} x + */ + x: { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + }, + + /** + * The position of the Game Object on the y axis relative to the local coordinates of the parent. + * + * @property {number} y + */ + y: { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Reset component allows a Game Object to be reset and repositioned to a new location. +* +* @class +*/ +Phaser.Component.Reset = function () {}; + +/** +* Resets the Game Object. +* +* This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, +* `visible` and `renderable` to true. +* +* If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. +* +* If this Game Object has a Physics Body it will reset the Body. +* +* @method +* @param {number} x - The x coordinate (in world space) to position the Game Object at. +* @param {number} y - The y coordinate (in world space) to position the Game Object at. +* @param {number} [health=1] - The health to give the Game Object if it has the Health component. +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.Reset.prototype.reset = function (x, y, health) { + + if (health === undefined) { health = 1; } + + this.world.set(x, y); + this.position.set(x, y); + + this.fresh = true; + this.exists = true; + this.visible = true; + this.renderable = true; + + if (this.components.InWorld) + { + this._outOfBoundsFired = false; + } + + if (this.components.LifeSpan) + { + this.alive = true; + this.health = health; + } + + if (this.components.PhysicsBody) + { + if (this.body) + { + this.body.reset(x, y, false, false); + } + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. +* +* @class +*/ +Phaser.Component.ScaleMinMax = function () {}; + +Phaser.Component.ScaleMinMax.prototype = { + + /** + * The callback that will apply any scale limiting to the worldTransform. + * @property {function} transformCallback + */ + transformCallback: null, + + /** + * The context under which `transformCallback` is called. + * @property {object} transformCallbackContext + */ + transformCallbackContext: this, + + /** + * The minimum scale this Game Object will scale down to. + * + * It allows you to prevent a parent from scaling this Game Object lower than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMin + */ + scaleMin: null, + + /** + * The maximum scale this Game Object will scale up to. + * + * It allows you to prevent a parent from scaling this Game Object higher than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMax + */ + scaleMax: null, + + /** + * Adjust scaling limits, if set, to this Game Object. + * + * @method + * @private + * @param {Phaser.Matrix} wt - The updated worldTransform matrix. + */ + checkTransform: function (wt) { + + if (this.scaleMin) + { + if (wt.a < this.scaleMin.x) + { + wt.a = this.scaleMin.x; + } + + if (wt.d < this.scaleMin.y) + { + wt.d = this.scaleMin.y; + } + } + + if (this.scaleMax) + { + if (wt.a > this.scaleMax.x) + { + wt.a = this.scaleMax.x; + } + + if (wt.d > this.scaleMax.y) + { + wt.d = this.scaleMax.y; + } + } + + }, + + /** + * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. + * + * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored + * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. + * + * By setting these values you can carefully control how Game Objects deal with responsive scaling. + * + * If only one parameter is given then that value will be used for both scaleMin and scaleMax: + * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 + * + * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: + * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 + * + * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, + * or pass `null` for the `maxX` and `maxY` parameters. + * + * Call `setScaleMinMax(null)` to clear all previously set values. + * + * @method + * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to. + * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to. + * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to. + * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to. + */ + setScaleMinMax: function (minX, minY, maxX, maxY) { + + if (minY === undefined) + { + // 1 parameter, set all to it + minY = maxX = maxY = minX; + } + else if (maxX === undefined) + { + // 2 parameters, the first is min, the second max + maxX = maxY = minY; + minY = minX; + } + + if (minX === null) + { + this.scaleMin = null; + } + else + { + if (this.scaleMin) + { + this.scaleMin.set(minX, minY); + } + else + { + this.scaleMin = new Phaser.Point(minX, minY); + } + } + + if (maxX === null) + { + this.scaleMax = null; + } + else + { + if (this.scaleMax) + { + this.scaleMax.set(maxX, maxY); + } + else + { + this.scaleMax = new Phaser.Point(maxX, maxY); + } + } + + if (this.scaleMin === null) + { + this.transformCallback = null; + } + else + { + this.transformCallback = this.checkTransform; + this.transformCallbackContext = this; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. +* +* @class +*/ +Phaser.Component.Smoothed = function () {}; + +Phaser.Component.Smoothed.prototype = { + + /** + * Enable or disable texture smoothing for this Game Object. + * + * It only takes effect if the Game Object is using an image based texture. + * + * Smoothing is enabled by default. + * + * @property {boolean} smoothed + */ + smoothed: { + + get: function () { + + return !this.texture.baseTexture.scaleMode; + + }, + + set: function (value) { + + if (value) + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 0; + this.texture.baseTexture.dirty(); + } + } + else + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 1; + this.texture.baseTexture.dirty(); + } + } + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectFactory is a quick way to create many common game objects +* using {@linkcode Phaser.Game#add `game.add`}. +* +* Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group. +* +* @class Phaser.GameObjectFactory +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectFactory = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectFactory.prototype = { + + /** + * Adds an existing display object to the game world. + * + * @method Phaser.GameObjectFactory#existing + * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object. + * @return {any} The child that was added to the World. + */ + existing: function (object) { + + return this.world.add(object); + + }, + + /** + * Weapons provide the ability to easily create a bullet pool and manager. + * + * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. + * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. + * + * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you + * can usually do with a Group, such as move it around the display list, iterate it, etc can be done + * to the bullets Group too. + * + * Bullets can have textures and even animations. You can control the speed at which they are fired, + * the firing rate, the firing angle, and even set things like gravity for them. + * + * @method Phaser.GameObjectFactory#weapon + * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group. + * @param {function} [bulletClass] - The Class of the bullets that are launched by this Weapon. See {@link Phaser.Weapon#bulletClass} + * @returns {Phaser.Weapon} A Weapon instance. + */ + weapon: function (quantity, key, frame, group, bulletClass) { + + var weapon = this.game.plugins.add(Phaser.Weapon); + + if (bulletClass) + { + weapon.bulletClass = bulletClass; + } + + weapon.createBullets(quantity, key, frame, group); + + return weapon; + + }, + + /** + * Create a new `Image` object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * + * It can still rotate, scale, crop and receive input events. + * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectFactory#image + * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Image} The newly created Image object. + */ + image: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Image(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. + * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), + * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. + * + * @method Phaser.GameObjectFactory#sprite + * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Sprite} The newly created Sprite object. + */ + sprite: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Sprite(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Creature Animation object. + * + * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. + * + * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). + * + * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. + * + * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them + * loaded before your Phaser game boots. + * + * See the Phaser custom build process for more details. + * + * @method Phaser.GameObjectFactory#creature + * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Creature} The newly created Creature object. + */ + creature: function (x, y, key, mesh, group) { + + if (group === undefined) { group = this.world; } + + var obj = new Phaser.Creature(this.game, x, y, key, mesh); + + group.add(obj); + + return obj; + + }, + + /** + * Create a tween on a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectFactory#tween + * @param {object} object - Object the tween will be run on. + * @return {Phaser.Tween} The newly created Phaser.Tween object. + */ + tween: function (object) { + + return this.game.tweens.create(object); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectFactory#group + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates + * are automatically given a physics body. + * + * @method Phaser.GameObjectFactory#physicsGroup + * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc. + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.Group} The newly created Group. + */ + physicsGroup: function (physicsBodyType, parent, name, addToStage) { + + return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType); + + }, + + /** + * A SpriteBatch is a really fast version of a Phaser Group built solely for speed. + * Use when you need a lot of sprites or particles all sharing the same texture. + * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. + * + * @method Phaser.GameObjectFactory#spriteBatch + * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. + * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. + * @return {Phaser.SpriteBatch} The newly created Sprite Batch. + */ + spriteBatch: function (parent, name, addToStage) { + + if (parent === undefined) { parent = null; } + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectFactory#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectFactory#tileSprite + * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TileSprite} The newly created TileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); + + }, + + /** + * Creates a new Rope object. + * + * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js + * + * @method Phaser.GameObjectFactory#rope + * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Array} points - An array of {Phaser.Point}. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Rope} The newly created Rope object. + */ + rope: function (x, y, key, frame, points, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Rope(this.game, x, y, key, frame, points)); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectFactory#text + * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {string} [text=''] - The text string that will be displayed. + * @param {object} [style] - The style object containing style attributes like font, font size , etc. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Text(this.game, x, y, text, style)); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectFactory#button + * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] - The function to call when this button is pressed + * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Button} The newly created Button object. + */ + button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectFactory#graphics + * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Graphics(this.game, x, y)); + + }, + + /** + * Create a new Emitter. + * + * A particle emitter can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accordingly. + * + * @method Phaser.GameObjectFactory#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles)); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectFactory#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectFactory#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size)); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectFactory#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {Phaser.Tilemap} The newly created tilemap object. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectFactory#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a Video object. + * + * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. + * + * @method Phaser.GameObjectFactory#video + * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. + * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) + * @return {Phaser.Video} The newly created Video object. + */ + video: function (key, url) { + + return new Phaser.Video(this.game, key, url); + + }, + + /** + * Create a BitmapData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectFactory#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectFactory#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + }, + + /** + * Add a new Plugin into the PluginManager. + * + * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.GameObjectFactory#plugin + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + plugin: function (plugin) { + + return this.game.plugins.add(plugin); + + } + +}; + +Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world. +* The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}. +* +* @class Phaser.GameObjectCreator +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectCreator = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectCreator.prototype = { + + /** + * Create a new Image object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectCreator#image + * @param {number} x - X position of the image. + * @param {number} y - Y position of the image. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Image} the newly created sprite object. + */ + image: function (x, y, key, frame) { + + return new Phaser.Image(this.game, x, y, key, frame); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * @method Phaser.GameObjectCreator#sprite + * @param {number} x - X position of the new sprite. + * @param {number} y - Y position of the new sprite. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Sprite} the newly created sprite object. + */ + sprite: function (x, y, key, frame) { + + return new Phaser.Sprite(this.game, x, y, key, frame); + + }, + + /** + * Create a tween object for a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectCreator#tween + * @param {object} obj - Object the tween will be run on. + * @return {Phaser.Tween} The Tween object. + */ + tween: function (obj) { + + return new Phaser.Tween(obj, this.game, this.game.tweens); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectCreator#group + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * Create a new SpriteBatch. + * + * @method Phaser.GameObjectCreator#spriteBatch + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.SpriteBatch} The newly created group. + */ + spriteBatch: function (parent, name, addToStage) { + + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectCreator#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectCreator#tileSprite + * @param {number} x - The x coordinate (in world space) to position the TileSprite at. + * @param {number} y - The y coordinate (in world space) to position the TileSprite at. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.TileSprite} The newly created tileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame) { + + return new Phaser.TileSprite(this.game, x, y, width, height, key, frame); + + }, + + /** + * Creates a new Rope object. + * + * @method Phaser.GameObjectCreator#rope + * @param {number} x - The x coordinate (in world space) to position the Rope at. + * @param {number} y - The y coordinate (in world space) to position the Rope at. + * @param {number} width - The width of the Rope. + * @param {number} height - The height of the Rope. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.Rope} The newly created rope object. + */ + rope: function (x, y, key, frame, points) { + + return new Phaser.Rope(this.game, x, y, key, frame, points); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectCreator#text + * @param {number} x - X position of the new text object. + * @param {number} y - Y position of the new text object. + * @param {string} text - The actual text that will be written. + * @param {object} style - The style object containing style attributes like font, font size , etc. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style) { + + return new Phaser.Text(this.game, x, y, text, style); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectCreator#button + * @param {number} [x] X position of the new button object. + * @param {number} [y] Y position of the new button object. + * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] The function to call when this button is pressed + * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @return {Phaser.Button} The newly created button object. + */ + 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); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectCreator#graphics + * @param {number} [x=0] - X position of the new graphics object. + * @param {number} [y=0] - Y position of the new graphics object. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y) { + + return new Phaser.Graphics(this.game, x, y); + + }, + + /** + * Creat a new Emitter. + * + * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accorindgly. + * + * @method Phaser.GameObjectCreator#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectCreator#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectCreator#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, align) { + + return new Phaser.BitmapText(this.game, x, y, font, text, size, align); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectCreator#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectCreator#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a BitmpaData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectCreator#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectCreator#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + } + +}; + +Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Sprites are the lifeblood of your game, used for nearly everything visual. +* +* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. +* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), +* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. +* +* @class Phaser.Sprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. If this argument is omitted, the sprite will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Sprite = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.SPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Sprite.prototype.constructor = Phaser.Sprite; + +Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.Sprite +* @return {boolean} True if the Sprite was rendered, otherwise false. +*/ +Phaser.Sprite.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image is a light-weight object you can use to display anything that doesn't need health, physics, or complex position monitoring. +* +* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. +* +* @class Phaser.Image +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. If this argument is omitted, the image will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Image = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.IMAGE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Image.prototype.constructor = Phaser.Image; + +Phaser.Component.Core.install.call(Phaser.Image.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Image.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Image#preUpdate +* @memberof Phaser.Image +*/ +Phaser.Image.prototype.preUpdate = function() { + + if (!this.preUpdateInWorld() || !this.preUpdateLifeSpan()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. +* +* The four states a Button responds to are: +* +* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. +* * 'Out' - when the Pointer that was previously over the Button moves out of it. +* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. +* * 'Up' - when the Pointer that was pressed down on the Button is released again. +* +* A different texture/frame and activation sound can be specified for any of the states. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. +* +* @class Phaser.Button +* @constructor +* @extends Phaser.Image +* @param {Phaser.Game} game Current game instance. +* @param {number} [x=0] - X position of the Button. +* @param {number} [y=0] - Y position of the Button. +* @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button. +* @param {function} [callback] - The function to call when this Button is pressed, receiving `this` (the Button), `pointer`, and `isOver` (see {@link Phaser.Events#onInputUp}.) +* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) { + + x = x || 0; + y = y || 0; + key = key || null; + callback = callback || null; + callbackContext = callbackContext || this; + + Phaser.Image.call(this, game, x, y, key, outFrame); + + /** + * The Phaser Object Type. + * @property {number} type + * @readonly + */ + this.type = Phaser.BUTTON; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * The name or ID of the Over state frame. + * @property {string|integer} onOverFrame + * @private + */ + this._onOverFrame = null; + + /** + * The name or ID of the Out state frame. + * @property {string|integer} onOutFrame + * @private + */ + this._onOutFrame = null; + + /** + * The name or ID of the Down state frame. + * @property {string|integer} onDownFrame + * @private + */ + this._onDownFrame = null; + + /** + * The name or ID of the Up state frame. + * @property {string|integer} onUpFrame + * @private + */ + this._onUpFrame = null; + + /** + * The Sound to be played when this Buttons Over state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound + * @readonly + */ + this.onOverSound = null; + + /** + * The Sound to be played when this Buttons Out state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound + * @readonly + */ + this.onOutSound = null; + + /** + * The Sound to be played when this Buttons Down state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound + * @readonly + */ + this.onDownSound = null; + + /** + * The Sound to be played when this Buttons Up state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound + * @readonly + */ + this.onUpSound = null; + + /** + * The Sound Marker used in conjunction with the onOverSound. + * @property {string} onOverSoundMarker + * @readonly + */ + this.onOverSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onOutSound. + * @property {string} onOutSoundMarker + * @readonly + */ + this.onOutSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onDownSound. + * @property {string} onDownSoundMarker + * @readonly + */ + this.onDownSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onUpSound. + * @property {string} onUpSoundMarker + * @readonly + */ + this.onUpSoundMarker = ''; + + /** + * The Signal (or event) dispatched when this Button is in an Over state. + * @property {Phaser.Signal} onInputOver + */ + this.onInputOver = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Out state. + * @property {Phaser.Signal} onInputOut + */ + this.onInputOut = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Down state. + * @property {Phaser.Signal} onInputDown + */ + this.onInputDown = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Up state. + * @property {Phaser.Signal} onInputUp + */ + this.onInputUp = new Phaser.Signal(); + + /** + * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. + * The frame will still be changed as applicable. + * + * @property {boolean} onOverMouseOnly + * @default + */ + this.onOverMouseOnly = true; + + /** + * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}. + * + * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. + * + * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR + */ + this.justReleasedPreventsOver = Phaser.PointerMode.CONTACT; + + /** + * When true the the texture frame will not be automatically switched on up/down/over/out events. + * @property {boolean} freezeFrames + * @default + */ + this.freezeFrames = false; + + /** + * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". + * + * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control. + * + * @property {boolean|Phaser.PointerMode} forceOut=false + * @default + */ + this.forceOut = false; + + this.inputEnabled = true; + + this.input.start(0, true); + + this.input.useHandCursor = true; + + this.setFrames(overFrame, outFrame, downFrame, upFrame); + + if (callback !== null) + { + this.onInputUp.add(callback, callbackContext); + } + + // Redirect the input events to here so we can handle animation updates, etc + this.events.onInputOver.add(this.onInputOverHandler, this); + this.events.onInputOut.add(this.onInputOutHandler, this); + this.events.onInputDown.add(this.onInputDownHandler, this); + this.events.onInputUp.add(this.onInputUpHandler, this); + +}; + +Phaser.Button.prototype = Object.create(Phaser.Image.prototype); +Phaser.Button.prototype.constructor = Phaser.Button; + +// State constants; local only. These are tied to property names in Phaser.Button. +var STATE_OVER = 'Over'; +var STATE_OUT = 'Out'; +var STATE_DOWN = 'Down'; +var STATE_UP = 'Up'; + +/** +* Clears all of the frames set on this Button. +* +* @method Phaser.Button#clearFrames +*/ +Phaser.Button.prototype.clearFrames = function () { + + this.setFrames(null, null, null, null); + +}; + +/** +* Set the frame name/ID for the given state. +* +* @method Phaser.Button#setStateFrame +* @private +* @param {object} state - See `STATE_*` +* @param {number|string} frame - The number or string representing the frame. +* @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true. +*/ +Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately) +{ + var frameKey = '_on' + state + 'Frame'; + + if (frame !== null) // not null or undefined + { + this[frameKey] = frame; + + if (switchImmediately) + { + this.changeStateFrame(state); + } + } + else + { + this[frameKey] = null; + } + +}; + +/** +* Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen". +* +* @method Phaser.Button#changeStateFrame +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if the frame was assigned a value, possibly the same one it already had. +*/ +Phaser.Button.prototype.changeStateFrame = function (state) { + + if (this.freezeFrames) + { + return false; + } + + var frameKey = '_on' + state + 'Frame'; + var frame = this[frameKey]; + + if (typeof frame === 'string') + { + this.frameName = frame; + return true; + } + else if (typeof frame === 'number') + { + this.frame = frame; + return true; + } + else + { + return false; + } + +}; + +/** +* Used to manually set the frames that will be used for the different states of the Button. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. +* +* @method Phaser.Button#setFrames +* @public +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) { + + this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver()); + this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver()); + this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown()); + this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp()); + +}; + +/** +* Set the sound/marker for the given state. +* +* @method Phaser.Button#setStateSound +* @private +* @param {object} state - See `STATE_*` +* @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound. +* @param {string} [marker=''] - Sound marker. +*/ +Phaser.Button.prototype.setStateSound = function (state, sound, marker) { + + var soundKey = 'on' + state + 'Sound'; + var markerKey = 'on' + state + 'SoundMarker'; + + if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite) + { + this[soundKey] = sound; + this[markerKey] = typeof marker === 'string' ? marker : ''; + } + else + { + this[soundKey] = null; + this[markerKey] = ''; + } + +}; + +/** +* Play the sound for the given state, _if_ the state has a sound assigned. +* +* @method Phaser.Button#playStateSound +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if a sound was played. +*/ +Phaser.Button.prototype.playStateSound = function (state) { + + var soundKey = 'on' + state + 'Sound'; + var sound = this[soundKey]; + + if (sound) + { + var markerKey = 'on' + state + 'SoundMarker'; + var marker = this[markerKey]; + + sound.play(marker); + return true; + } + else + { + return false; + } + +}; + +/** +* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. +* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. +* +* Call this function with no parameters to reset all sounds on this Button. +* +* @method Phaser.Button#setSounds +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound. +* @param {string} [overMarker] - Over Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound. +* @param {string} [downMarker] - Down Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound. +* @param {string} [outMarker] - Out Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound. +* @param {string} [upMarker] - Up Button Sound Marker. +*/ +Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) { + + this.setStateSound(STATE_OVER, overSound, overMarker); + this.setStateSound(STATE_OUT, outSound, outMarker); + this.setStateSound(STATE_DOWN, downSound, downMarker); + this.setStateSound(STATE_UP, upSound, upMarker); + +}; + +/** +* The Sound to be played when a Pointer moves over this Button. +* +* @method Phaser.Button#setOverSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOverSound = function (sound, marker) { + + this.setStateSound(STATE_OVER, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer moves out of this Button. +* +* @method Phaser.Button#setOutSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOutSound = function (sound, marker) { + + this.setStateSound(STATE_OUT, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer presses down on this Button. +* +* @method Phaser.Button#setDownSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setDownSound = function (sound, marker) { + + this.setStateSound(STATE_DOWN, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer has pressed down and is released from this Button. +* +* @method Phaser.Button#setUpSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setUpSound = function (sound, marker) { + + this.setStateSound(STATE_UP, sound, marker); + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOverHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) { + + if (pointer.justReleased() && + (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode) + { + // If the Pointer was only just released then we don't fire an over event + return; + } + + this.changeStateFrame(STATE_OVER); + + if (this.onOverMouseOnly && !pointer.isMouse) + { + return; + } + + this.playStateSound(STATE_OVER); + + if (this.onInputOver) + { + this.onInputOver.dispatch(this, pointer); + } + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOutHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_OUT); + + this.playStateSound(STATE_OUT); + + if (this.onInputOut) + { + this.onInputOut.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputDownHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_DOWN); + + this.playStateSound(STATE_DOWN); + + if (this.onInputDown) + { + this.onInputDown.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputUpHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) { + + this.playStateSound(STATE_UP); + + // Input dispatched early, before state change (but after sound) + if (this.onInputUp) + { + this.onInputUp.dispatch(this, pointer, isOver); + } + + if (this.freezeFrames) + { + return; + } + + if (this.forceOut === true || (this.forceOut & pointer.pointerMode) === pointer.pointerMode) + { + this.changeStateFrame(STATE_OUT); + } + else + { + var changedUp = this.changeStateFrame(STATE_UP); + if (!changedUp) + { + // No Up frame to show.. + if (isOver) + { + this.changeStateFrame(STATE_OVER); + } + else + { + this.changeStateFrame(STATE_OUT); + } + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. +* It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over +* 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled +* Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. +* +* Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. +* +* @class Phaser.SpriteBatch +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. +* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. +*/ +Phaser.SpriteBatch = function (game, parent, name, addToStage) { + + if (parent === undefined || parent === null) { parent = game.world; } + + Phaser.Group.call(this, game, parent, name, addToStage); + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.SPRITEBATCH; + + /** + * @property {Object} fastSpriteBatch - WebGL Batch Shader. + * @private + */ + this.fastSpriteBatch = null; + + /** + * @property {boolean} ready - Internal flag. + * @private + */ + this.ready = false; + +}; + +Phaser.SpriteBatch.prototype = Object.create(Phaser.Group.prototype); + +Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch; + +/** +* Renders the Sprite Batch using the WebGL renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + if (!this.ready) + { + this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(renderSession.gl); + + this.ready = true; + } + + if (this.fastSpriteBatch.gl !== renderSession.gl) + { + this.fastSpriteBatch.setContext(renderSession.gl); + } + + renderSession.spriteBatch.stop(); + + renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader); + + this.fastSpriteBatch.begin(this, renderSession); + this.fastSpriteBatch.render(this); + + renderSession.spriteBatch.start(); + +}; + +/** +* Renders the Sprite Batch using the Canvas renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + var context = renderSession.context; + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + var transform = this.worldTransform; + + var isRotated = true; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + var texture = child.texture; + var frame = texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) + { + // If rotation === 0 we can avoid setTransform + + if (isRotated) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); + isRotated = false; + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5 + renderSession.shakeX) | 0, + ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5 + renderSession.shakeY) | 0, + frame.width * child.scale.x, + frame.height * child.scale.y); + } + else + { + if (!isRotated) + { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + var tx = (childTransform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (childTransform.ty * renderSession.resolution) + renderSession.shakeY; + + // allow for trimming + + if (renderSession.roundPixels) + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx, ty); + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width) + 0.5) | 0, + ((child.anchor.y) * (-frame.height) + 0.5) | 0, + frame.width, + frame.height); + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. +* A single BitmapData can be used as the texture for one or many Images / Sprites. +* So if you need to dynamically create a Sprite texture then they are a good choice. +* +* Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't +* live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy +* in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. +* +* @class Phaser.BitmapData +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string} key - Internal Phaser reference key for the BitmapData. +* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. +*/ +Phaser.BitmapData = function (game, key, width, height, skipPool) { + + if (width === undefined || width === 0) { width = 256; } + if (height === undefined || height === 0) { height = 256; } + if (skipPool === undefined) { skipPool = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the BitmapData in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} width - The width of the BitmapData in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the BitmapData in pixels. + */ + this.height = height; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. + * @default + */ + this.canvas = Phaser.Canvas.create(this, width, height, null, skipPool); + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + * @default + */ + this.context = this.canvas.getContext('2d', { alpha: true }); + + /** + * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context. + */ + this.ctx = this.context; + + /** + * @property {string} smoothProperty - The context property needed for smoothing this Canvas. + */ + this.smoothProperty = (game.renderType === Phaser.CANVAS) ? game.renderer.renderSession.smoothProperty : Phaser.Canvas.getSmoothingPrefix(this.context); + + /** + * @property {ImageData} imageData - The context image data. + * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. + * This property is updated automatically after the first game loop, according to the dirty flag property. + */ + this.imageData = this.context.getImageData(0, 0, width, height); + + /** + * A Uint8ClampedArray view into BitmapData.buffer. + * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) + * @property {Uint8ClampedArray} data + */ + this.data = null; + + if (this.imageData) + { + this.data = this.imageData.data; + } + + /** + * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer. + */ + this.pixels = null; + + /** + * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData. + */ + if (this.data) + { + 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; + } + } + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + this.baseTexture = new PIXI.BaseTexture(this.canvas, null, this.game.resolution); + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering. + */ + this.frameData = new Phaser.FrameData(); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. + * @default + */ + this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData')); + + this.texture.frame = this.textureFrame; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.BITMAPDATA; + + /** + * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} dirty - If dirty this BitmapData will be re-rendered. + */ + this.dirty = false; + + // Aliases + this.cls = this.clear; + + /** + * @property {number} _image - Internal cache var. + * @private + */ + this._image = null; + + /** + * @property {Phaser.Point} _pos - Internal cache var. + * @private + */ + this._pos = new Phaser.Point(); + + /** + * @property {Phaser.Point} _size - Internal cache var. + * @private + */ + this._size = new Phaser.Point(); + + /** + * @property {Phaser.Point} _scale - Internal cache var. + * @private + */ + this._scale = new Phaser.Point(); + + /** + * @property {number} _rotate - Internal cache var. + * @private + */ + this._rotate = 0; + + /** + * @property {object} _alpha - Internal cache var. + * @private + */ + this._alpha = { prev: 1, current: 1 }; + + /** + * @property {Phaser.Point} _anchor - Internal cache var. + * @private + */ + this._anchor = new Phaser.Point(); + + /** + * @property {number} _tempR - Internal cache var. + * @private + */ + this._tempR = 0; + + /** + * @property {number} _tempG - Internal cache var. + * @private + */ + this._tempG = 0; + + /** + * @property {number} _tempB - Internal cache var. + * @private + */ + this._tempB = 0; + + /** + * @property {Phaser.Circle} _circle - Internal cache var. + * @private + */ + this._circle = new Phaser.Circle(); + + /** + * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods. + * @private + */ + this._swapCanvas = undefined; + +}; + +Phaser.BitmapData.prototype = { + + /** + * Shifts the contents of this BitmapData by the distances given. + * + * The image will wrap-around the edges on all sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#move + * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + move: function (x, y, wrap) { + + if (x !== 0) + { + this.moveH(x, wrap); + } + + if (y !== 0) + { + this.moveV(y, wrap); + } + + return this; + + }, + + /** + * Shifts the contents of this BitmapData horizontally. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveH + * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveH: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var h = this.height; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving to the left + var w = this.width - distance; + + // Left-hand chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h); + } + else + { + // Moving to the right + var w = this.width - distance; + + // Right-hand chunk + if (wrap) + { + ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Shifts the contents of this BitmapData vertically. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveV + * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveV: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var w = this.width; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving up + var h = this.height - distance; + + // Top chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h); + } + else + { + // Moving down + var h = this.height - distance; + + // Bottom chunk + if (wrap) + { + ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Updates the given objects so that they use this BitmapData as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.BitmapData#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. + * The source game object is not modified by this operation. + * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. + * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. + * + * @method Phaser.BitmapData#load + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + load: function (source) { + + if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + } + + if (source) + { + this.resize(source.width, source.height); + this.cls(); + } + else + { + return; + } + + this.draw(source); + + this.update(); + + return this; + + }, + + /** + * Clears the BitmapData context using a clearRect. + * + * @method Phaser.BitmapData#cls + */ + + /** + * Clears the BitmapData context using a clearRect. + * + * You can optionally define the area to clear. + * If the arguments are left empty it will clear the entire canvas. + * + * You may need to call BitmapData.update after this in order to clear out the pixel data, + * but Phaser will not do this automatically for you. + * + * @method Phaser.BitmapData#clear + * @param {number} [x=0] - The x coordinate of the top-left of the area to clear. + * @param {number} [y=0] - The y coordinate of the top-left of the area to clear. + * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width. + * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + clear: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + this.context.clearRect(x, y, width, height); + + this.dirty = true; + + return this; + + }, + + /** + * Fills the BitmapData with the given color. + * + * @method Phaser.BitmapData#fill + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} [a=1] - The alpha color value, between 0 and 1. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + fill: function (r, g, b, a) { + + if (a === undefined) { a = 1; } + + this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; + this.context.fillRect(0, 0, this.width, this.height); + this.dirty = true; + + return this; + + }, + + /** + * Creates a new {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image} element by converting this BitmapDatas canvas into a dataURL. + * + * The image is then stored in the {@link Phaser.Cache image Cache} using the key given. + * + * Finally a {@link PIXI.Texture} is created based on the image and returned. + * + * You can apply the texture to a sprite or any other supporting object by using either the + * key or the texture. First call `generateTexture`: + * + * ```javascript + * var texture = bitmapdata.generateTexture('ball'); + * ``` + * + * Then you can either apply the texture to a sprite: + * + * ```javascript + * game.add.sprite(0, 0, texture); + * ``` + * + * or by using the string based key: + * + * ```javascript + * game.add.sprite(0, 0, 'ball'); + * ``` + * + * Most browsers now load the image data asynchronously, so you should use a callback: + * + * ```javascript + * bitmapdata.generateTexture('ball', function (texture) { + * game.add.sprite(0, 0, texture); + * // or + * game.add.sprite(0, 0, 'ball'); + * }); + * ``` + * + * If this BitmapData is available during preload, you can use {@link Phaser.Loader#imageFromBitmapData} instead. + * + * @method Phaser.BitmapData#generateTexture + * @param {string} key - The key which will be used to store the image in the Cache. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {PIXI.Texture|null} The newly generated texture, or `null` if a callback was passed and the texture isn't available yet. + */ + generateTexture: function (key, callback, callbackContext) { + + var cache = this.game.cache; + var image = new Image(); + + if (callback) + { + image.onload = function () { + var obj = cache.addImage(key, '', image); + var texture = new PIXI.Texture(obj.base); + + callback.call(callbackContext || null, texture); + + image.onload = null; + }; + } + + image.src = this.canvas.toDataURL("image/png"); + + if (!callback) + { + var obj = cache.addImage(key, '', image); + + return new PIXI.Texture(obj.base); + } + + return null; + + }, + + /** + * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. + * + * @method Phaser.BitmapData#resize + * @param {integer} width - The new width of the BitmapData. + * @param {integer} height - The new height of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + resize: function (width, height) { + + if (width !== this.width || height !== this.height) + { + this.width = width; + this.height = height; + + this.canvas.width = width; + this.canvas.height = height; + + if (this._swapCanvas !== undefined) + { + this._swapCanvas.width = width; + this._swapCanvas.height = height; + } + + this.baseTexture.width = width; + this.baseTexture.height = height; + + this.textureFrame.width = width; + this.textureFrame.height = height; + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.update(); + this.dirty = true; + } + + return this; + + }, + + /** + * This re-creates the BitmapData.imageData from the current context. + * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. + * If not given the dimensions defaults to the full size of the context. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.BitmapData#update + * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from. + * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from. + * @param {number} [width=1] - The width of the image data area. + * @param {number} [height=1] - The height of the image data area. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + update: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = Math.max(1, this.width); } + if (height === undefined) { height = Math.max(1, this.height); } + + this.imageData = this.context.getImageData(x, y, width, height); + this.data = this.imageData.data; + + 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; + } + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. + * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. + * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. + * The `color` property is an Int32 of the full color. Note the endianess of this will change per system. + * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. + * The callback will also be sent the pixels x and y coordinates respectively. + * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. + * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. + * + * @method Phaser.BitmapData#processPixelRGB + * @param {function} callback - The callback that will be sent each pixel color object to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixelRGB: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = Phaser.Color.createColor(); + var result = { r: 0, g: 0, b: 0, a: 0 }; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel); + + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== false && result !== null && result !== undefined) + { + this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false); + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. + * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. + * Note that the format of the color received will be different depending on if the system is big or little endian. + * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. + * The callback will also be sent the pixels x and y coordinates respectively. + * + * @method Phaser.BitmapData#processPixel + * @param {function} callback - The callback that will be sent each pixel color to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixel: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = 0; + var result = 0; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + pixel = this.getPixel32(tx, ty); + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== pixel) + { + this.pixels[ty * this.width + tx] = result; + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. + * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. + * + * @method Phaser.BitmapData#replaceRGB + * @param {number} r1 - The red color value to be replaced. Between 0 and 255. + * @param {number} g1 - The green color value to be replaced. Between 0 and 255. + * @param {number} b1 - The blue color value to be replaced. Between 0 and 255. + * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255. + * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255. + * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255. + * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255. + * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255. + * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) { + + var sx = 0; + var sy = 0; + var w = this.width; + var h = this.height; + var source = Phaser.Color.packPixel(r1, g1, b1, a1); + + if (region !== undefined && region instanceof Phaser.Rectangle) + { + sx = region.x; + sy = region.y; + w = region.width; + h = region.height; + } + + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + if (this.getPixel32(sx + x, sy + y) === source) + { + this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false); + } + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * + * @method Phaser.BitmapData#setHSL + * @param {number} [h=null] - The hue, in the range 0 - 1. + * @param {number} [s=null] - The saturation, in the range 0 - 1. + * @param {number} [l=null] - The lightness, in the range 0 - 1. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setHSL: function (h, s, l, region) { + + var bHaveH = h || h === 0; + var bHaveS = s || s === 0; + var bHaveL = l || l === 0; + + if (!bHaveH && !bHaveS && !bHaveL) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (bHaveH) + { + pixel.h = h; + } + + if (bHaveS) + { + pixel.s = s; + } + + if (bHaveL) + { + pixel.l = l; + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * Shifting will add the given value onto the current h, s and l values, not replace them. + * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. + * + * @method Phaser.BitmapData#shiftHSL + * @param {number} [h=null] - The amount to shift the hue by. Within [-1, 1]. + * @param {number} [s=null] - The amount to shift the saturation by. Within [-1, 1]. + * @param {number} [l=null] - The amount to shift the lightness by. Within [-1, 1]. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shiftHSL: function (h, s, l, region) { + + if (h === undefined || h === null) { h = false; } + if (s === undefined || s === null) { s = false; } + if (l === undefined || l === null) { l = false; } + + if (!h && !s && !l) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (h) + { + pixel.h = this.game.math.wrap(pixel.h + h, 0, 1); + } + + if (s) + { + pixel.s = this.game.math.clamp(pixel.s + s, 0, 1); + } + + if (l) + { + pixel.l = this.game.math.clamp(pixel.l + l, 0, 1); + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green, blue and alpha values. + * + * @method Phaser.BitmapData#setPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel32: function (x, y, red, green, blue, alpha, immediate) { + + if (immediate === undefined) { immediate = true; } + + if (x >= 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; + } + } + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green and blue values. + * + * @method Phaser.BitmapData#setPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel: function (x, y, red, green, blue, immediate) { + + return this.setPixel32(x, y, red, green, blue, 255, immediate); + + }, + + /** + * Get the color of a specific pixel in the context into a color object. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + getPixel: function (x, y, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var index = ~~(x + (y * this.width)); + + index *= 4; + + out.r = this.data[index]; + out.g = this.data[++index]; + out.b = this.data[++index]; + out.a = this.data[++index]; + + return out; + + }, + + /** + * Get the color of a specific pixel including its alpha value. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. + * + * @method Phaser.BitmapData#getPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @return {number} A native color value integer (format: 0xAARRGGBB) + */ + getPixel32: function (x, y) { + + if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) + { + return this.pixels[y * this.width + x]; + } + + }, + + /** + * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixelRGB + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + getPixelRGB: function (x, y, out, hsl, hsv) { + + return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv); + + }, + + /** + * Gets all the pixels from the region specified by the given Rectangle object. + * + * @method Phaser.BitmapData#getPixels + * @param {Phaser.Rectangle} rect - The Rectangle region to get. + * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property. + */ + getPixels: function (rect) { + + return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); + + }, + + /** + * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). + * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. + * + * The direction parameter controls from which direction it should start the scan: + * + * 0 = top to bottom + * 1 = bottom to top + * 2 = left to right + * 3 = right to left + * + * @method Phaser.BitmapData#getFirstPixel + * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. + * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. + */ + getFirstPixel: function (direction) { + + if (direction === undefined) { direction = 0; } + + var pixel = Phaser.Color.createColor(); + + var x = 0; + var y = 0; + var v = 1; + var scan = false; + + if (direction === 1) + { + v = -1; + y = this.height; + } + else if (direction === 3) + { + v = -1; + x = this.width; + } + + do { + + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel); + + if (direction === 0 || direction === 1) + { + // Top to Bottom / Bottom to Top + x++; + + if (x === this.width) + { + x = 0; + y += v; + + if (y >= this.height || y <= 0) + { + scan = true; + } + } + } + else if (direction === 2 || direction === 3) + { + // Left to Right / Right to Left + y++; + + if (y === this.height) + { + y = 0; + x += v; + + if (x >= this.width || x <= 0) + { + scan = true; + } + } + } + } + while (pixel.a === 0 && !scan); + + pixel.x = x; + pixel.y = y; + + return pixel; + + }, + + /** + * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. + * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. + * + * @method Phaser.BitmapData#getBounds + * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. + * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. + */ + getBounds: function (rect) { + + if (rect === undefined) { rect = new Phaser.Rectangle(); } + + rect.x = this.getFirstPixel(2).x; + + // If we hit this, there's no point scanning any more, the image is empty + if (rect.x === this.width) + { + return rect.setTo(0, 0, 0, 0); + } + + rect.y = this.getFirstPixel(0).y; + rect.width = (this.getFirstPixel(3).x - rect.x) + 1; + rect.height = (this.getFirstPixel(1).y - rect.y) + 1; + + return rect; + + }, + + /** + * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. + * + * @method Phaser.BitmapData#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself. + * + * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn. + * + * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters. + * + * Note that the source image can also be this BitmapData, which can create some interesting effects. + * + * This method has a lot of parameters for maximum control. + * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all. + * + * You may prefer to use `copyTransform` if you're simply trying to draw a Sprite to this BitmapData, + * and don't wish to translate, scale or rotate it from its original values. + * + * @method Phaser.BitmapData#copy + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image. + * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image. + * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width. + * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height. + * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`. + * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`. + * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter. + * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter. + * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters. + * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) { + + if (source === undefined || source === null) { source = this; } + + if (source instanceof Phaser.RenderTexture) + { + source = source.getCanvas(); + } + + this._image = source; + + if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text || source instanceof PIXI.Sprite) + { + // Copy over sprite values + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + this._scale.set(source.scale.x, source.scale.y); + this._anchor.set(source.anchor.x, source.anchor.y); + this._rotate = source.rotation; + this._alpha.current = source.alpha; + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + if (tx === undefined || tx === null) { tx = source.x; } + if (ty === undefined || ty === null) { ty = source.y; } + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + } + else + { + // Reset + this._pos.set(0); + this._scale.set(1); + this._anchor.set(0); + this._rotate = 0; + this._alpha.current = 1; + + if (source instanceof Phaser.BitmapData) + { + this._image = source.canvas; + } + else if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + + if (source === null) + { + return; + } + else + { + this._image = source; + } + } + + this._size.set(this._image.width, this._image.height); + } + + // The source region to copy from + if (x === undefined || x === null) { x = 0; } + if (y === undefined || y === null) { y = 0; } + + // If they set a width/height then we override the frame values with them + if (width) + { + this._size.x = width; + } + + if (height) + { + this._size.y = height; + } + + // The destination region to copy to + if (tx === undefined || tx === null) { tx = x; } + if (ty === undefined || ty === null) { ty = y; } + if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; } + if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; } + + // Rotation - if set this will override any potential Sprite value + if (typeof rotate === 'number') + { + this._rotate = rotate; + } + + // Anchor - if set this will override any potential Sprite value + if (typeof anchorX === 'number') + { + this._anchor.x = anchorX; + } + + if (typeof anchorY === 'number') + { + this._anchor.y = anchorY; + } + + // Scaling - if set this will override any potential Sprite value + if (typeof scaleX === 'number') + { + this._scale.x = scaleX; + } + + if (typeof scaleY === 'number') + { + this._scale.y = scaleY; + } + + // Effects + if (typeof alpha === 'number') + { + this._alpha.current = alpha; + } + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + // Doesn't work fully with children, or nested scale + rotation transforms (see copyTransform) + ctx.translate(tx, ty); + + ctx.scale(this._scale.x, this._scale.y); + + ctx.rotate(this._rotate); + + ctx.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight); + + // Carry on ... + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the + * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. + * It takes the objects tint and scale mode into consideration before drawing. + * + * You can optionally specify Blend Mode and Round Pixels arguments. + * + * @method Phaser.BitmapData#copyTransform + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyTransform: function (source, blendMode, roundPx) { + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (!source.hasOwnProperty('worldTransform') || !source.worldVisible || source.worldAlpha === 0) + { + return this; + } + + var wt = source.worldTransform; + + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + + if (wt.a === 0 || wt.d === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return this; + } + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + var tx = wt.tx; + var ty = wt.ty; + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + ctx[this.smoothProperty] = (source.texture.baseTexture.scaleMode === PIXI.scaleModes.LINEAR); + + ctx.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + + ctx.drawImage(this._image, + this._pos.x, + this._pos.y, + this._size.x, + this._size.y, + -this._size.x * source.anchor.x, + -this._size.y * source.anchor.y, + this._size.x, + this._size.y); + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. + * + * @method Phaser.BitmapData#copyRect + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. + * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image. + * @param {number} x - The destination x coordinate to copy the image to. + * @param {number} y - The destination y coordinate to copy the image to. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyRect: function (source, area, x, y, alpha, blendMode, roundPx) { + + return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx); + + }, + + /** + * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. + * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. + * + * @method Phaser.BitmapData#draw + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData. + * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`. + * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`. + * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`. + * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + draw: function (source, x, y, width, height, blendMode, roundPx) { + + // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here + return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx); + + }, + + /** + * Draws the immediate children of a Phaser.Group to this BitmapData. + * + * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. + * + * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. + * + * @method Phaser.BitmapData#drawGroup + * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawGroup: function (group, blendMode, roundPx) { + + if (group.total > 0) + { + group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx); + } + + return this; + + }, + + /** + * A proxy for drawGroup that handles child iteration for more complex Game Objects. + * + * @method Phaser.BitmapData#drawGroupProxy + * @private + * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + */ + drawGroupProxy: function (child, blendMode, roundPx) { + + if (child.hasOwnProperty('texture')) + { + this.copyTransform(child, blendMode, roundPx); + } + + if (child.type === Phaser.GROUP && child.exists) + { + this.drawGroup(child, blendMode, roundPx); + } + else + { + if (child.hasOwnProperty('children') && child.children.length > 0) + { + for (var i = 0; i < child.children.length; i++) + { + if (child.children[i].exists) + { + this.copyTransform(child.children[i], blendMode, roundPx); + } + } + } + } + + }, + + /** + * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. + * + * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData + * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the + * bounds of the top-level Game Object. + * + * When drawing it will take into account the child's world rotation, scale and alpha values. + * + * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. + * + * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update + * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can + * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. + * + * @method Phaser.BitmapData#drawFull + * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawFull: function (parent, blendMode, roundPx) { + + if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false)) + { + return this; + } + + if (parent.type !== Phaser.GROUP && parent.type !== Phaser.EMITTER && parent.type !== Phaser.BITMAPTEXT) + { + if (parent.type === Phaser.GRAPHICS) + { + var bounds = parent.getBounds(); + this.ctx.save(); + this.ctx.translate(bounds.x, bounds.y); + PIXI.CanvasGraphics.renderGraphics(parent, this.ctx); + this.ctx.restore(); + } + else + { + this.copy(parent, null, null, null, null, parent.worldPosition.x, parent.worldPosition.y, null, null, parent.worldRotation, null, null, parent.worldScale.x, parent.worldScale.y, parent.worldAlpha, blendMode, roundPx); + } + } + + if (parent.children) + { + for (var i = 0; i < parent.children.length; i++) + { + this.drawFull(parent.children[i], blendMode, roundPx); + } + } + + return this; + + }, + + /** + * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. + * You can cancel an existing shadow by calling this method and passing no parameters. + * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. + * + * @method Phaser.BitmapData#shadow + * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. + * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. + * @param {number} [x=10] - The horizontal offset of the shadow in pixels. + * @param {number} [y=10] - The vertical offset of the shadow in pixels. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shadow: function (color, blur, x, y) { + + var ctx = this.context; + + if (color === undefined || color === null) + { + ctx.shadowColor = 'rgba(0,0,0,0)'; + } + else + { + ctx.shadowColor = color; + ctx.shadowBlur = blur || 5; + ctx.shadowOffsetX = x || 10; + ctx.shadowOffsetY = y || 10; + } + + return this; + + }, + + /** + * Draws the image onto this BitmapData using an image as an alpha mask. + * + * @method Phaser.BitmapData#alphaMask + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. + * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. + * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + alphaMask: function (source, mask, sourceRect, maskRect) { + + if (maskRect === undefined || maskRect === null) + { + this.draw(mask).blendSourceAtop(); + } + else + { + this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop(); + } + + if (sourceRect === undefined || sourceRect === null) + { + this.draw(source).blendReset(); + } + else + { + this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset(); + } + + return this; + + }, + + /** + * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. + * The original BitmapData remains unchanged. + * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. + * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: + * `picture.extract(mask, r, g, b)` + * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. + * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint + * the color during extraction. + * + * @method Phaser.BitmapData#extract + * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. + * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied? + * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255. + * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255. + * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255. + * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on. + */ + extract: function (destination, r, g, b, a, resize, r2, g2, b2) { + + if (a === undefined) { a = 255; } + if (resize === undefined) { resize = false; } + if (r2 === undefined) { r2 = r; } + if (g2 === undefined) { g2 = g; } + if (b2 === undefined) { b2 = b; } + + if (resize) + { + destination.resize(this.width, this.height); + } + + this.processPixelRGB( + function (pixel, x, y) + { + if (pixel.r === r && pixel.g === g && pixel.b === b) + { + destination.setPixel32(x, y, r2, g2, b2, a, false); + } + return false; + }, + this); + + destination.context.putImageData(destination.imageData, 0, 0); + destination.dirty = true; + + return destination; + + }, + + /** + * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. + * + * @method Phaser.BitmapData#rect + * @param {number} x - The x coordinate of the top-left of the Rectangle. + * @param {number} y - The y coordinate of the top-left of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + rect: function (x, y, width, height, fillStyle) { + + if (typeof fillStyle !== 'undefined') + { + this.context.fillStyle = fillStyle; + } + + this.context.fillRect(x, y, width, height); + + return this; + + }, + + /** + * Draws text to the BitmapData in the given font and color. + * The default font is 14px Courier, so useful for quickly drawing debug text. + * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. + * + * @method Phaser.BitmapData#text + * @param {string} text - The text to write to the BitmapData. + * @param {number} x - The x coordinate of the top-left of the text string. + * @param {number} y - The y coordinate of the top-left of the text string. + * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can. + * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in. + * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1) + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + text: function (text, x, y, font, color, shadow) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (font === undefined) { font = '14px Courier'; } + if (color === undefined) { color = 'rgb(255,255,255)'; } + if (shadow === undefined) { shadow = true; } + + var ctx = this.context; + var prevFont = ctx.font; + + ctx.font = font; + + if (shadow) + { + ctx.fillStyle = 'rgb(0,0,0)'; + ctx.fillText(text, x + 1, y + 1); + } + + ctx.fillStyle = color; + ctx.fillText(text, x, y); + + ctx.font = prevFont; + + return this; + + }, + + /** + * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. + * + * @method Phaser.BitmapData#circle + * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle. + * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle. + * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + circle: function (x, y, radius, fillStyle) { + + var ctx = this.context; + + if (fillStyle !== undefined) + { + ctx.fillStyle = fillStyle; + } + + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2, false); + ctx.closePath(); + + ctx.fill(); + + return this; + + }, + + /** + * Draws a line between the coordinates given in the color and thickness specified. + * + * @method Phaser.BitmapData#line + * @param {number} x1 - The x coordinate to start the line from. + * @param {number} y1 - The y coordinate to start the line from. + * @param {number} x2 - The x coordinate to draw the line to. + * @param {number} y2 - The y coordinate to draw the line to. + * @param {string} [color='#fff'] - The stroke color that the line will be drawn in. + * @param {number} [width=1] - The line thickness. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + line: function (x1, y1, x2, y2, color, width) { + + if (color === undefined) { color = '#fff'; } + if (width === undefined) { width = 1; } + + var ctx = this.context; + + ctx.beginPath(); + + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); + + ctx.closePath(); + + return this; + + }, + + /** + * Draws a polygon. + * + * @method Phaser.BitmapData#polygon + * @param {object[]} points - An array of {@link Phaser.Point} or point-like objects. + * @param {CanvasGradient|CanvasPattern|string} [fillStyle] - A color, gradient, or pattern. + * @param {number} [lineWidth=0] - The line thickness. + * @param {CanvasGradient|CanvasPattern|string} [strokeStyle='#fff'] - The line color, gradient, or pattern (when `lineWidth` > 0). + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + polygon: function (points, fillStyle, lineWidth, strokeStyle) { + + // Could reject points.length < 3 + + if (strokeStyle === undefined) { strokeStyle = '#fff'; } + if (lineWidth === undefined) { lineWidth = 0; } + + var ctx = this.context; + + if (fillStyle) + { + ctx.fillStyle = fillStyle; + } + + if (lineWidth) + { + ctx.lineWidth = lineWidth; + ctx.strokeStyle = strokeStyle; + } + + ctx.beginPath(); + + ctx.moveTo(points[0].x, points[0].y); + + for (var i = 1, len = points.length; i < len; i++) + { + var point = points[i]; + ctx.lineTo(point.x, point.y); + } + + ctx.closePath(); + + if (fillStyle) { ctx.fill(); } + if (lineWidth) { ctx.stroke(); } + + return this; + + }, + + /** + * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. + * + * @method Phaser.BitmapData#textureLine + * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line. + * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. + * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + textureLine: function (line, image, repeat) { + + if (repeat === undefined) { repeat = 'repeat-x'; } + + if (typeof image === 'string') + { + image = this.game.cache.getImage(image); + + if (!image) + { + return; + } + } + + var width = line.length; + + if (repeat === 'no-repeat' && width > image.width) + { + width = image.width; + } + + var ctx = this.context; + + ctx.fillStyle = ctx.createPattern(image, repeat); + + this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height); + + this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos); + + ctx.save(); + ctx.translate(this._pos.x, this._pos.y); + ctx.rotate(line.angle); + ctx.fillRect(0, 0, width, image.height); + ctx.restore(); + + this.dirty = true; + + return this; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. + * + * @method Phaser.BitmapData#render + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + render: function () { + + if (!this.disableTextureUpload && this.dirty) + { + this.baseTexture.dirty(); + this.dirty = false; + } + + return this; + + }, + + /** + * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. + * + * @method Phaser.BitmapData#destroy + */ + destroy: function () { + + this.frameData.destroy(); + + this.texture.destroy(true); + + Phaser.CanvasPool.remove(this); + + }, + + /** + * Resets the blend mode (effectively sets it to 'source-over') + * + * @method Phaser.BitmapData#blendReset + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendReset: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-over' + * + * @method Phaser.BitmapData#blendSourceOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOver: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-in' + * + * @method Phaser.BitmapData#blendSourceIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceIn: function () { + + this.op = 'source-in'; + return this; + + }, + + /** + * Sets the blend mode to 'source-out' + * + * @method Phaser.BitmapData#blendSourceOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOut: function () { + + this.op = 'source-out'; + return this; + + }, + + /** + * Sets the blend mode to 'source-atop' + * + * @method Phaser.BitmapData#blendSourceAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceAtop: function () { + + this.op = 'source-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-over' + * + * @method Phaser.BitmapData#blendDestinationOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOver: function () { + + this.op = 'destination-over'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-in' + * + * @method Phaser.BitmapData#blendDestinationIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationIn: function () { + + this.op = 'destination-in'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-out' + * + * @method Phaser.BitmapData#blendDestinationOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOut: function () { + + this.op = 'destination-out'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-atop' + * + * @method Phaser.BitmapData#blendDestinationAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationAtop: function () { + + this.op = 'destination-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'xor' + * + * @method Phaser.BitmapData#blendXor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendXor: function () { + + this.op = 'xor'; + return this; + + }, + + /** + * Sets the blend mode to 'lighter' + * + * @method Phaser.BitmapData#blendAdd + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendAdd: function () { + + this.op = 'lighter'; + return this; + + }, + + /** + * Sets the blend mode to 'multiply' + * + * @method Phaser.BitmapData#blendMultiply + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendMultiply: function () { + + this.op = 'multiply'; + return this; + + }, + + /** + * Sets the blend mode to 'screen' + * + * @method Phaser.BitmapData#blendScreen + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendScreen: function () { + + this.op = 'screen'; + return this; + + }, + + /** + * Sets the blend mode to 'overlay' + * + * @method Phaser.BitmapData#blendOverlay + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendOverlay: function () { + + this.op = 'overlay'; + return this; + + }, + + /** + * Sets the blend mode to 'darken' + * + * @method Phaser.BitmapData#blendDarken + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDarken: function () { + + this.op = 'darken'; + return this; + + }, + + /** + * Sets the blend mode to 'lighten' + * + * @method Phaser.BitmapData#blendLighten + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLighten: function () { + + this.op = 'lighten'; + return this; + + }, + + /** + * Sets the blend mode to 'color-dodge' + * + * @method Phaser.BitmapData#blendColorDodge + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorDodge: function () { + + this.op = 'color-dodge'; + return this; + + }, + + /** + * Sets the blend mode to 'color-burn' + * + * @method Phaser.BitmapData#blendColorBurn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorBurn: function () { + + this.op = 'color-burn'; + return this; + + }, + + /** + * Sets the blend mode to 'hard-light' + * + * @method Phaser.BitmapData#blendHardLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHardLight: function () { + + this.op = 'hard-light'; + return this; + + }, + + /** + * Sets the blend mode to 'soft-light' + * + * @method Phaser.BitmapData#blendSoftLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSoftLight: function () { + + this.op = 'soft-light'; + return this; + + }, + + /** + * Sets the blend mode to 'difference' + * + * @method Phaser.BitmapData#blendDifference + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDifference: function () { + + this.op = 'difference'; + return this; + + }, + + /** + * Sets the blend mode to 'exclusion' + * + * @method Phaser.BitmapData#blendExclusion + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendExclusion: function () { + + this.op = 'exclusion'; + return this; + + }, + + /** + * Sets the blend mode to 'hue' + * + * @method Phaser.BitmapData#blendHue + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHue: function () { + + this.op = 'hue'; + return this; + + }, + + /** + * Sets the blend mode to 'saturation' + * + * @method Phaser.BitmapData#blendSaturation + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSaturation: function () { + + this.op = 'saturation'; + return this; + + }, + + /** + * Sets the blend mode to 'color' + * + * @method Phaser.BitmapData#blendColor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColor: function () { + + this.op = 'color'; + return this; + + }, + + /** + * Sets the blend mode to 'luminosity' + * + * @method Phaser.BitmapData#blendLuminosity + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLuminosity: function () { + + this.op = 'luminosity'; + return this; + + }, + + /** + * Updates a portion of the BitmapData from a source Bitmap. + * This optimization is important if calling update() on a large Bitmap is causing performance issues. + * Make sure you use getPixel32() instead of getPixel(). + * This does not work with floating point numbers for x and y. + * + * @method Phaser.BitmapData#copyBitmapData + * @param {Phaser.BitmapData} [source] - The BitmapData you wish to copy. + * @param {number} [x] - The x coordinate of the top-left of the area to copy. + * @param {number} [y] - The y coordinate of the top-left of the area to copy. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyBitmapData: function(source, x, y) { + + source.update(); + for (var i = 0, destRowStart; i < source.height; i++) { + destRowStart = (y + i) * this.width + x; + for (var j = 0; j < source.width; j++) { + this.pixels[destRowStart + j] = source.pixels[i * source.width + j]; + } + } + return this; + + } + +}; + +/** +* @memberof Phaser.BitmapData +* @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", { + + get: function () { + + Phaser.Canvas.getSmoothingEnabled(this.context); + + }, + + set: function (value) { + + Phaser.Canvas.setSmoothingEnabled(this.context, value); + + } + +}); + +/** +* @memberof Phaser.BitmapData +* @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "op", { + + get: function () { + + return this.context.globalCompositeOperation; + + }, + + set: function (value) { + + this.context.globalCompositeOperation = value; + + } + +}); + +/** + * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform. + * + * @method Phaser.BitmapData.getTransform + * @param {number} translateX - The x translate value. + * @param {number} translateY - The y translate value. + * @param {number} scaleX - The scale x value. + * @param {number} scaleY - The scale y value. + * @param {number} skewX - The skew x value. + * @param {number} skewY - The skew y value. + * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms. + */ +Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) { + + if (typeof translateX !== 'number') { translateX = 0; } + if (typeof translateY !== 'number') { translateY = 0; } + if (typeof scaleX !== 'number') { scaleX = 1; } + if (typeof scaleY !== 'number') { scaleY = 1; } + if (typeof skewX !== 'number') { skewX = 0; } + if (typeof skewY !== 'number') { skewY = 0; } + + return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY }; + +}; + +Phaser.BitmapData.prototype.constructor = Phaser.BitmapData; + +/* jshint ignore:start */ + +/* +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ + +/** +* @class EarCut +*/ +Phaser.EarCut = {}; + +Phaser.EarCut.Triangulate = function (data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = Phaser.EarCut.linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = Phaser.EarCut.eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + Phaser.EarCut.earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +}; + +// create a circular doubly linked list from polygon points in the specified winding order + +Phaser.EarCut.linkedList = function (data, start, end, dim, clockwise) { + var sum = 0, + i, j, last; + + // calculate original winding order of a polygon ring + for (i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + + // link points into circular doubly-linked list in the specified winding order + if (clockwise === (sum > 0)) { + for (i = start; i < end; i += dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } + + return last; +}; + +// eliminate colinear or duplicate points + +Phaser.EarCut.filterPoints = function (start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (Phaser.EarCut.equals(p, p.next) || Phaser.EarCut.area(p.prev, p, p.next) === 0)) { + Phaser.EarCut.removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +}; + +// main ear slicing loop which triangulates a polygon (given as a linked list) + +Phaser.EarCut.earcutLinked = function (ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) Phaser.EarCut.indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? Phaser.EarCut.isEarHashed(ear, minX, minY, size) : Phaser.EarCut.isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + Phaser.EarCut.removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + Phaser.EarCut.earcutLinked(Phaser.EarCut.filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = Phaser.EarCut.cureLocalIntersections(ear, triangles, dim); + Phaser.EarCut.earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + Phaser.EarCut.splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +}; + +// check whether a polygon node forms a valid ear with adjacent nodes + +Phaser.EarCut.isEar = function (ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +}; + +Phaser.EarCut.isEarHashed = function (ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = Phaser.EarCut.zOrder(minTX, minTY, minX, minY, size), + maxZ = Phaser.EarCut.zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +}; + +// go through all polygon nodes and cure small local self-intersections + +Phaser.EarCut.cureLocalIntersections = function (start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) + if (Phaser.EarCut.intersects(a, p, p.next, b) && Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + Phaser.EarCut.removeNode(p); + Phaser.EarCut.removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +}; + +// try splitting polygon into two and triangulate them independently + +Phaser.EarCut.splitEarcut = function (start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && Phaser.EarCut.isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = Phaser.EarCut.splitPolygon(a, b); + + // filter colinear points around the cuts + a = Phaser.EarCut.filterPoints(a, a.next); + c = Phaser.EarCut.filterPoints(c, c.next); + + // run earcut on each half + Phaser.EarCut.earcutLinked(a, triangles, dim, minX, minY, size); + Phaser.EarCut.earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +}; + +// link every hole into the outer loop, producing a single-ring polygon without holes + +Phaser.EarCut.eliminateHoles = function (data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = Phaser.EarCut.linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(Phaser.EarCut.getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + Phaser.EarCut.eliminateHole(queue[i], outerNode); + outerNode = Phaser.EarCut.filterPoints(outerNode, outerNode.next); + } + + return outerNode; +}; + +Phaser.EarCut.compareX = function (a, b) { + return a.x - b.x; +}; + +// find a bridge between vertices that connects hole with an outer ring and and link it + +Phaser.EarCut.eliminateHole = function (hole, outerNode) { + outerNode = Phaser.EarCut.findHoleBridge(hole, outerNode); + if (outerNode) { + var b = Phaser.EarCut.splitPolygon(outerNode, hole); + Phaser.EarCut.filterPoints(b, b.next); + } +}; + +// David Eberly's algorithm for finding a bridge between hole and outer polygon + +Phaser.EarCut.findHoleBridge = function (hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hole.x === m.x) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= m.x && + Phaser.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && Phaser.EarCut.locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +}; + +// interlink polygon nodes in z-order + +Phaser.EarCut.indexCurve = function (start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = Phaser.EarCut.zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + Phaser.EarCut.sortLinked(p); +}; + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + +Phaser.EarCut.sortLinked = function (list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +}; + +// z-order of a point given coords and size of the data bounding box + +Phaser.EarCut.zOrder = function (x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +}; + +// find the leftmost node of a polygon ring + +Phaser.EarCut.getLeftmost = function (start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +}; + +// check if a point lies within a convex triangle + +Phaser.EarCut.pointInTriangle = function (ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +}; + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) + +Phaser.EarCut.isValidDiagonal = function (a, b) { + return Phaser.EarCut.equals(a, b) || a.next.i !== b.i && a.prev.i !== b.i && !Phaser.EarCut.intersectsPolygon(a, b) && + Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a) && Phaser.EarCut.middleInside(a, b); +}; + +// signed area of a triangle + +Phaser.EarCut.area = function (p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +}; + +// check if two points are equal + +Phaser.EarCut.equals = function (p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +}; + +// check if two segments intersect + +Phaser.EarCut.intersects = function (p1, q1, p2, q2) { + return Phaser.EarCut.area(p1, q1, p2) > 0 !== Phaser.EarCut.area(p1, q1, q2) > 0 && + Phaser.EarCut.area(p2, q2, p1) > 0 !== Phaser.EarCut.area(p2, q2, q1) > 0; +}; + +// check if a polygon diagonal intersects any polygon segments + +Phaser.EarCut.intersectsPolygon = function (a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + Phaser.EarCut.intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +}; + +// check if a polygon diagonal is locally inside the polygon + +Phaser.EarCut.locallyInside = function (a, b) { + return Phaser.EarCut.area(a.prev, a, a.next) < 0 ? + Phaser.EarCut.area(a, b, a.next) >= 0 && Phaser.EarCut.area(a, a.prev, b) >= 0 : + Phaser.EarCut.area(a, b, a.prev) < 0 || Phaser.EarCut.area(a, a.next, b) < 0; +}; + +// check if the middle point of a polygon diagonal is inside the polygon + +Phaser.EarCut.middleInside = function (a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +}; + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring + +Phaser.EarCut.splitPolygon = function (a, b) { + var a2 = new Phaser.EarCut.Node(a.i, a.x, a.y), + b2 = new Phaser.EarCut.Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +}; + +// create a node and optionally link it with previous one (in a circular doubly linked list) + +Phaser.EarCut.insertNode = function (i, x, y, last) { + var p = new Phaser.EarCut.Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +}; + +Phaser.EarCut.removeNode = function (p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +}; + +Phaser.EarCut.Node = function (i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +}; + +/* jshint ignore:end */ + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used by the webGL renderer to draw the primitive graphics data + * + * @class PIXI.WebGLGraphics + * @private + * @static + */ +PIXI.WebGLGraphics = function() +{ +}; + +/** + * The number of points beyond which Pixi swaps to using the Stencil Buffer to render the Graphics. + * + * @type {number} + */ +PIXI.WebGLGraphics.stencilBufferLimit = 6; + +/** + * Renders the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.renderGraphics + * @param graphics {Graphics} + * @param renderSession {Object} + */ +PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset) +{ + var gl = renderSession.gl; + var projection = renderSession.projection, + offset = renderSession.offset, + shader = renderSession.shaderManager.primitiveShader, + webGLData; + + if(graphics.dirty) + { + PIXI.WebGLGraphics.updateGraphics(graphics, gl); + } + + var webGL = graphics._webGL[gl.id]; + + // if the graphics object does not exist in the webGL context skip rendering! + if(!webGL) + { + return; + } + + // This could be speeded up for sure! + + for (var i = 0; i < webGL.data.length; i++) + { + if(webGL.data[i].mode === 1) + { + webGLData = webGL.data[i]; + + renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession); + + // render quad.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + renderSession.stencilManager.popStencil(graphics, webGLData, renderSession); + } + else + { + webGLData = webGL.data[i]; + + + renderSession.shaderManager.setShader( shader );//activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, 1); + + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + } + } +}; + +/** + * Updates the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.updateGraphics + * @param graphicsData {Graphics} The graphics object to update + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLGraphics.updateGraphics = function(graphics, gl) +{ + // get the contexts graphics object + var webGL = graphics._webGL[gl.id]; + // if the graphics object does not exist in the webGL context time to create it! + if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; + + // flag the graphics as not dirty as we are about to update it... + graphics.dirty = false; + + var i; + + // if the user cleared the graphics object we will need to clear every object + if(graphics.clearDirty) + { + graphics.clearDirty = false; + + // lop through and return all the webGLDatas to the object pool so than can be reused later on + for (i = 0; i < webGL.data.length; i++) + { + var graphicsData = webGL.data[i]; + graphicsData.reset(); + PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData ); + } + + // clear the array and reset the index.. + webGL.data = []; + webGL.lastIndex = 0; + } + + var webGLData; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + if (data.type === Phaser.POLYGON) + { + // need to add the points the the graphics object.. + data.points = data.shape.points.slice(); + if(data.shape.closed) + { + // close the poly if the value is true! + if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { + data.points.push(data.points[0], data.points[1]); + } + } + + // MAKE SURE WE HAVE THE CORRECT TYPE.. + if(data.fill) + { + if(data.points.length >= PIXI.WebGLGraphics.stencilBufferLimit) + { + if(data.points.length < PIXI.WebGLGraphics.stencilBufferLimit * 2) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData); + // console.log(canDrawUsingSimple); + + if(!canDrawUsingSimple) + { + // console.log("<>>>") + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + } + } + + if(data.lineWidth > 0) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + PIXI.WebGLGraphics.buildLine(data, webGLData); + + } + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + if (data.type === Phaser.RECTANGLE) + { + PIXI.WebGLGraphics.buildRectangle(data, webGLData); + } + else if (data.type === Phaser.CIRCLE || data.type === Phaser.ELLIPSE) + { + PIXI.WebGLGraphics.buildCircle(data, webGLData); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData); + } + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (i = 0; i < webGL.data.length; i++) + { + webGLData = webGL.data[i]; + if(webGLData.dirty)webGLData.upload(); + } +}; + +/** + * @static + * @private + * @method PIXI.WebGLGraphics.switchMode + * @param webGL {WebGLContext} + * @param type {Number} + */ +PIXI.WebGLGraphics.switchMode = function(webGL, type) +{ + var webGLData; + + if(!webGL.data.length) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + else + { + webGLData = webGL.data[webGL.data.length-1]; + + if(webGLData.mode !== type || type === 1) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + } + + webGLData.dirty = true; + + return webGLData; +}; + +/** + * Builds a rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData) +{ + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; + + // start + 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); + + // insert 2 dead triangles.. + 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; + } +}; + +/** + * Builds a rounded rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRoundedRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData) +{ + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + recPoints.push(x, y + radius); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); + + if (graphicsData.fill) { + var color = Phaser.Color.hexToRGBArray(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; + + var triangles = Phaser.EarCut.Triangulate(recPoints, null, 2); + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i+1] + vecPos); + indices.push(triangles[i+2] + vecPos); + indices.push(triangles[i+2] + vecPos); + } + + + for (i = 0; i < recPoints.length; i++) + { + verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @static + * @private + * @method PIXI.WebGLGraphics.quadraticBezierCurve + * @param fromX {Number} Origin point x + * @param fromY {Number} Origin point x + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Array(Number)} + */ +PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) { + + var xa, + ya, + xb, + yb, + x, + y, + n = 20, + points = []; + + function getPt(n1 , n2, perc) { + var diff = n2 - n1; + + return n1 + ( diff * perc ); + } + + var j = 0; + for (var i = 0; i <= n; i++ ) + { + j = i / n; + + // The Green Line + xa = getPt( fromX , cpX , j ); + ya = getPt( fromY , cpY , j ); + xb = getPt( cpX , toX , j ); + yb = getPt( cpY , toY , j ); + + // The Black Dot + x = getPt( xa , xb , j ); + y = getPt( ya , yb , j ); + + points.push(x, y); + } + return points; +}; + +/** + * Builds a circle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildCircle + * @param graphicsData {Graphics} The graphics object to draw + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData) +{ + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + + // TODO - bit hacky?? + if (graphicsData.type === Phaser.CIRCLE) + { + width = circleData.radius; + height = circleData.radius; + } + else + { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = 40; + var seg = (Math.PI * 2) / totalSegs ; + + var i = 0; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; i < totalSegs + 1 ; i++) + { + verts.push(x,y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos-1); + } + + if(graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (i = 0; i < totalSegs + 1; i++) + { + graphicsData.points.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height); + } + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Builds a line to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildLine + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData) +{ + // TODO OPTIMISE! + var i = 0; + var points = graphicsData.points; + if(points.length === 0)return; + + // if the line width is an odd number add 0.5 to align to a whole pixel + if(graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) { + points[i] += 0.5; + } + } + + // get first and last point.. figure out the middle! + var firstPoint = new PIXI.Point( points[0], points[1] ); + var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + // if the first point is the last point - gonna have issues :) + if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length/6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var px, py, p1x, p1y, p2x, p2y, p3x, p3y; + var perpx, perpy, perp2x, perp2y, perp3x, perp3y; + var a1, b1, c1, a2, b2, c2; + var denom, pdist, dist; + + p1x = points[0]; + p1y = points[1]; + + p2x = points[2]; + p2y = points[3]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx , p1y - perpy, + r, g, b, alpha); + + verts.push(p1x + perpx , p1y + perpy, + r, g, b, alpha); + + for (i = 1; i < length-1; i++) + { + p1x = points[(i-1)*2]; + p1y = points[(i-1)*2 + 1]; + + p2x = points[(i)*2]; + p2y = points[(i)*2 + 1]; + + p3x = points[(i+1)*2]; + p3y = points[(i+1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + a1 = (-perpy + p1y) - (-perpy + p2y); + b1 = (-perpx + p2x) - (-perpx + p1x); + c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + a2 = (-perp2y + p3y) - (-perp2y + p2y); + b2 = (-perp2x + p2x) - (-perp2x + p3x); + c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + denom = a1*b2 - a2*b1; + + if(Math.abs(denom) < 0.1 ) + { + + denom+=10.1; + verts.push(p2x - perpx , p2y - perpy, + r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy, + r, g, b, alpha); + + continue; + } + + px = (b1*c2 - b2*c1)/denom; + py = (a2*c1 - a1*c2)/denom; + + + pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); + + + if(pdist > 140 * 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 < indexCount; i++) + { + indices.push(indexStart++); + } + + indices.push(indexStart-1); +}; + +/** + * Builds a complex polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildComplexPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData) +{ + //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. + var points = graphicsData.points.slice(); + if(points.length < 6)return; + + // get first and last point.. figure out the middle! + var indices = webGLData.indices; + webGLData.points = points; + webGLData.alpha = graphicsData.fillAlpha; + webGLData.color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + + /* + calclate the bounds.. + */ + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + var x,y; + + // get size.. + for (var i = 0; i < points.length; i+=2) + { + x = points[i]; + y = points[i+1]; + + minX = x < minX ? x : minX; + maxX = x > maxX ? x : maxX; + + minY = y < minY ? y : minY; + maxY = y > maxY ? y : maxY; + } + + // add a quad to the end cos there is no point making another buffer! + points.push(minX, minY, + maxX, minY, + maxX, maxY, + minX, maxY); + + // push a quad onto the end.. + + //TODO - this aint needed! + var length = points.length / 2; + for (i = 0; i < length; i++) + { + indices.push( i ); + } + +}; + +/** + * Builds a polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData) +{ + var points = graphicsData.points; + + if(points.length < 6)return; + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = Phaser.EarCut.Triangulate(points, null, 2); + + if(!triangles)return false; + + var vertPos = verts.length / 6; + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i] + vertPos); + indices.push(triangles[i+1] + vertPos); + indices.push(triangles[i+2] +vertPos); + indices.push(triangles[i+2] + vertPos); + } + + for (i = 0; i < length; i++) + { + verts.push(points[i * 2], points[i * 2 + 1], + r, g, b, alpha); + } + + return true; +}; + +PIXI.WebGLGraphics.graphicsDataPool = []; + +/** + * @class WebGLGraphicsData + * @private + * @static + */ +PIXI.WebGLGraphicsData = function(gl) +{ + this.gl = gl; + + //TODO does this need to be split before uploding?? + this.color = [0,0,0]; // color split! + this.points = []; + this.indices = []; + this.buffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + this.mode = 1; + this.alpha = 1; + this.dirty = true; +}; + +/** + * @method PIXI.WebGLGraphics.reset + */ +PIXI.WebGLGraphicsData.prototype.reset = function() +{ + this.points = []; + this.indices = []; +}; + +/** + * @method PIXI.WebGLGraphics.upload + */ +PIXI.WebGLGraphicsData.prototype.upload = function() +{ + var gl = this.gl; + +// this.lastIndex = graphics.graphicsData.length; + this.glPoints = new Float32Array(this.points); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW); + + this.glIndicies = new Uint16Array(this.indices); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW); + + this.dirty = false; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + +/** + * A set of functions used by the canvas renderer to draw the primitive graphics data. + * + * @class PIXI.CanvasGraphics + * @static + */ +PIXI.CanvasGraphics = function() +{ +}; + +/** + * Renders a {@link Phaser.Graphics} object to a canvas. + * + * @method PIXI.CanvasGraphics.renderGraphics + * @static + * @param graphics {Graphics} the actual graphics object to render + * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas + */ +PIXI.CanvasGraphics.renderGraphics = function(graphics, context) +{ + var worldAlpha = graphics.worldAlpha; + + if (graphics.dirty) + { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === Phaser.POLYGON) + { + context.beginPath(); + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (shape.closed) + { + context.lineTo(points[0], points[1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.RECTANGLE) + { + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ELLIPSE) + { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + context.beginPath(); + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + +}; + +/** + * Renders a graphics mask + * + * @static + * @private + * @method PIXI.CanvasGraphics.renderGraphicsMask + * @param graphics {Graphics} the graphics which will be used as a mask + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + */ +PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context) +{ + var len = graphics.graphicsData.length; + + if (len === 0) + { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === Phaser.POLYGON) + { + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + } + else if (data.type === Phaser.RECTANGLE) + { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } + else if (data.type === Phaser.ELLIPSE) + { + + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } +}; + +PIXI.CanvasGraphics.updateGraphicsTint = function(graphics) +{ + if (graphics.tint === 0xFFFFFF) + { + return; + } + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF)/ 255; + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255); + data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255); + + } + +}; + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + * @param lineWidth {number} the width of the line to draw + * @param lineColor {number} the color of the line to draw + * @param lineAlpha {number} the alpha of the line to draw + * @param fillColor {number} the color of the fill + * @param fillAlpha {number} the alpha of the fill + * @param fill {boolean} whether or not the shape is filled with a colour + * @param shape {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + +Phaser.GraphicsData = function (lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { + + /* + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /* + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /* + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /* + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /* + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /* + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /* + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /* + * @member {boolean} whether or not the shape is filled with a color + */ + this.fill = fill; + + /* + * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + this.shape = shape; + + /* + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + +}; + +Phaser.GraphicsData.prototype.constructor = Phaser.GraphicsData; + +/** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {GraphicsData} + */ +Phaser.GraphicsData.prototype.clone = function () { + + return new Phaser.GraphicsData( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.fill, + this.shape + ); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, +* Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will +* be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: +* +* ```javascript +* graphics.beginFill(0xff0000); +* graphics.drawCircle(50, 50, 100); +* graphics.endFill(); +* ``` +* +* This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. +* +* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or +* WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the +* graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. +* +* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help +* performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. +* You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then +* you should avoid doing this, as it will constantly generate new textures, which will consume memory. +* +* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful +* in their complexity and quantity of them in your game. +* +* @class Phaser.Graphics +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - X position of the new graphics object. +* @param {number} [y=0] - Y position of the new graphics object. +*/ +Phaser.Graphics = function (game, x, y) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.GRAPHICS; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value. + * @private + */ + this.anchor = new Phaser.Point(); + + PIXI.DisplayObjectContainer.call(this); + + this.renderable = true; + + /** + * The alpha value used when filling the Graphics object. + * + * @property fillAlpha + * @type Number + */ + this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @property lineWidth + * @type Number + */ + this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @property lineColor + * @type String + * @default 0 + */ + this.lineColor = 0; + + /** + * Graphics data + * + * @property graphicsData + * @type Array + * @private + */ + this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF (Phaser.Color.WHITE) to reset the tint. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * Current path + * + * @property currentPath + * @type Object + * @private + */ + this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @property _webGL + * @type Array + * @private + */ + this._webGL = []; + + /** + * Whether this shape is being used as a mask. + * + * @property isMask + * @type Boolean + */ + this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @property boundsPadding + * @type Number + */ + this.boundsPadding = 0; + + this._localBounds = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property dirty + * @type Boolean + * @private + */ + this.dirty = true; + + /** + * Used to detect if the bounds have been invalidated, by this Graphics being cleared or drawn to. + * If this is set to true then the updateLocalBounds is called once in the postUpdate method. + * + * @property _boundsDirty + * @type Boolean + * @private + */ + this._boundsDirty = false; + + /** + * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property webGLDirty + * @type Boolean + * @private + */ + this.webGLDirty = false; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @property cachedSpriteDirty + * @type Boolean + * @private + */ + this.cachedSpriteDirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.Graphics.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Graphics.prototype.constructor = Phaser.Graphics; + +Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Graphics#preUpdate +*/ +Phaser.Graphics.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World +* +* @method Phaser.Graphics#postUpdate +*/ +Phaser.Graphics.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this._boundsDirty) + { + this.updateLocalBounds(); + this._boundsDirty = false; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Destroy this Graphics instance. +* +* @method Phaser.Graphics#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Graphics.prototype.destroy = function (destroyChildren) { + + this.clear(); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Draws a single {@link Phaser.Polygon} triangle from a {@link Phaser.Point} array +* +* @method Phaser.Graphics#drawTriangle +* @param {Array} points - An array of Phaser.Points that make up the three vertices of this triangle +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangle = function (points, cull) { + + if (cull === undefined) { cull = false; } + + var triangle = new Phaser.Polygon(points); + + if (cull) + { + var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y); + var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y); + var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y); + var faceNormal = cb.cross(ab); + + if (cameraToFace.dot(faceNormal) > 0) + { + this.drawPolygon(triangle); + } + } + else + { + this.drawPolygon(triangle); + } + +}; + +/** +* Draws {@link Phaser.Polygon} triangles +* +* @method Phaser.Graphics#drawTriangles +* @param {Array|Array} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles +* @param {Array} [indices=null] - An array of numbers that describe what order to draw the vertices in +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) { + + if (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 < vertices.length / 3; i++) + { + this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull); + } + } + else + { + for (i = 0; i < vertices.length / 6; i++) + { + point1.x = vertices[i * 6 + 0]; + point1.y = vertices[i * 6 + 1]; + point2.x = vertices[i * 6 + 2]; + point2.y = vertices[i * 6 + 3]; + point3.x = vertices[i * 6 + 4]; + point3.y = vertices[i * 6 + 5]; + this.drawTriangle([point1, point2, point3], cull); + } + } + } + else + { + if (vertices[0] instanceof Phaser.Point) + { + for (i = 0; i < indices.length /3; i++) + { + points.push(vertices[indices[i * 3 ]]); + points.push(vertices[indices[i * 3 + 1]]); + points.push(vertices[indices[i * 3 + 2]]); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + else + { + for (i = 0; i < indices.length; i++) + { + point1.x = vertices[indices[i] * 2]; + point1.y = vertices[indices[i] * 2 + 1]; + points.push(point1.copyTo({})); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + } +}; + +/** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. + * + * @method Phaser.Graphics#lineStyle + * @param lineWidth {Number} width of the line to draw, will update the objects stored style + * @param color {Number} color of the line to draw, will update the objects stored style + * @param alpha {Number} alpha of the line to draw, will update the objects stored style + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { + + this.lineWidth = lineWidth || 0; + this.lineColor = color || 0; + this.lineAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { + // halfway through a line? start a new one! + this.drawShape(new Phaser.Polygon(this.currentPath.shape.points.slice(-2))); + } + else + { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + +}; + +/** + * Moves the current drawing position to x, y. + * + * @method Phaser.Graphics#moveTo + * @param x {Number} the X coordinate to move to + * @param y {Number} the Y coordinate to move to + * @return {Graphics} + */ +Phaser.Graphics.prototype.moveTo = function (x, y) { + + this.drawShape(new Phaser.Polygon([ x, y ])); + + return this; + +}; + +/** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @method Phaser.Graphics#lineTo + * @param x {Number} the X coordinate to draw to + * @param y {Number} the Y coordinate to draw to + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineTo = function (x, y) { + + if (!this.currentPath) + { + this.moveTo(0, 0); + } + + this.currentPath.shape.points.push(x, y); + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @method Phaser.Graphics#quadraticCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [ 0, 0 ]; + } + } + else + { + this.moveTo(0,0); + } + + var xa, + ya, + n = 20, + points = this.currentPath.shape.points; + + if (points.length === 0) + { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var j = 0; + for (var i = 1; i <= n; ++i) + { + j = i / n; + + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + + points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), + ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a bezier curve and then draws it. + * + * @method Phaser.Graphics#bezierCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param cpX2 {Number} Second Control point x + * @param cpY2 {Number} Second Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + var n = 20, + dt, + dt2, + dt3, + t2, + t3, + points = this.currentPath.shape.points; + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + var j = 0; + + for (var i = 1; i <= n; ++i) + { + j = i / n; + + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, + dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @method Phaser.Graphics#arcTo + * @param x1 {Number} The x-coordinate of the beginning of the arc + * @param y1 {Number} The y-coordinate of the beginning of the arc + * @param x2 {Number} The x-coordinate of the end of the arc + * @param y2 {Number} The y-coordinate of the end of the arc + * @param radius {Number} The radius of the arc + * @return {Graphics} + */ +Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points.push(x1, y1); + } + } + else + { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points, + fromX = points[points.length-2], + fromY = points[points.length-1], + a1 = fromY - y1, + b1 = fromX - x1, + a2 = y2 - y1, + b2 = x2 - x1, + mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { + points.push(x1, y1); + } + } + else + { + var dd = a1 * a1 + b1 * b1, + cc = a2 * a2 + b2 * b2, + tt = a1 * a2 + b1 * b2, + k1 = radius * Math.sqrt(dd) / mm, + k2 = radius * Math.sqrt(cc) / mm, + j1 = k1 * tt / dd, + j2 = k2 * tt / cc, + cx = k1 * b2 + k2 * b1, + cy = k1 * a2 + k2 * a1, + px = b1 * (k2 + j1), + py = a1 * (k2 + j1), + qx = b2 * (k1 + j2), + qy = a2 * (k1 + j2), + startAngle = Math.atan2(py - cy, px - cx), + endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @method Phaser.Graphics#arc + * @param cx {Number} The x-coordinate of the center of the circle + * @param cy {Number} The y-coordinate of the center of the circle + * @param radius {Number} The radius of the circle + * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) + * @param endAngle {Number} The ending angle, in radians + * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. + * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. + * @return {Graphics} + */ +Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise, segments) { + + // If we do this we can never draw a full circle + if (startAngle === endAngle) + { + return this; + } + + if (anticlockwise === undefined) { anticlockwise = false; } + if (segments === undefined) { segments = 40; } + + if (!anticlockwise && endAngle <= startAngle) + { + endAngle += Math.PI * 2; + } + else if (anticlockwise && startAngle <= endAngle) + { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments; + + // Sweep check - moved here because we don't want to do the moveTo below if the arc fails + if (sweep === 0) + { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (anticlockwise && this.filling) + { + this.moveTo(cx, cy); + } + else + { + this.moveTo(startX, startY); + } + + // currentPath will always exist after calling a moveTo + var points = this.currentPath.shape.points; + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = (segMinus % 1) / segMinus; + + for (var i = 0; i <= segMinus; i++) + { + var real = i + remainder * i; + + var angle = ((theta) + startAngle + (theta2 * real)); + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, + ( (cTheta * -s) + (sTheta * c) ) * radius + cy); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @method Phaser.Graphics#beginFill + * @param color {Number} the color of the fill + * @param alpha {Number} the alpha of the fill + * @return {Graphics} + */ +Phaser.Graphics.prototype.beginFill = function (color, alpha) { + + this.filling = true; + this.fillColor = color || 0; + this.fillAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + +}; + +/** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @method Phaser.Graphics#endFill + * @return {Graphics} + */ +Phaser.Graphics.prototype.endFill = function () { + + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRect + * + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawRect = function (x, y, width, height) { + + this.drawShape(new Phaser.Rectangle(x, y, width, height)); + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRoundedRect + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. + */ +Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + + this.drawShape(new Phaser.RoundedRectangle(x, y, width, height, radius)); + + return this; + +}; + +/** + * Draws a circle. + * + * @method Phaser.Graphics#drawCircle + * @param x {Number} The X coordinate of the center of the circle + * @param y {Number} The Y coordinate of the center of the circle + * @param diameter {Number} The diameter of the circle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) { + + this.drawShape(new Phaser.Circle(x, y, diameter)); + + return this; + +}; + +/** + * Draws an ellipse. + * + * @method Phaser.Graphics#drawEllipse + * @param x {Number} The X coordinate of the center of the ellipse + * @param y {Number} The Y coordinate of the center of the ellipse + * @param width {Number} The half width of the ellipse + * @param height {Number} The half height of the ellipse + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawEllipse = function (x, y, width, height) { + + this.drawShape(new Phaser.Ellipse(x, y, width, height)); + + return this; + +}; + +/** + * Draws a polygon using the given path. + * + * @method Phaser.Graphics#drawPolygon + * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawPolygon = function (path) { + + if (path instanceof Phaser.Polygon) + { + path = path.points; + } + + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) + { + points[i] = arguments[i]; + } + } + + this.drawShape(new Phaser.Polygon(points)); + + return this; + +}; + +/** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @method Phaser.Graphics#clear + * @return {Graphics} + */ +Phaser.Graphics.prototype.clear = function () { + + this.lineWidth = 0; + this.filling = false; + + this.dirty = true; + this._boundsDirty = true; + this.clearDirty = true; + this.graphicsData = []; + + this.updateLocalBounds(); + + return this; + +}; + +/** + * Useful function that returns a texture of the graphics object that can then be used to create sprites + * This can be quite useful if your geometry is complicated and needs to be reused multiple times. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * @method Phaser.Graphics#generateTexture + * @param [resolution=1] {Number} The resolution of the texture being generated + * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts + * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0) + * @return {Texture} a texture of the graphics object + */ +Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, padding) { + + if (resolution === undefined) { resolution = 1; } + if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; } + if (padding === undefined) { padding = 0; } + + var bounds = this.getBounds(); + + bounds.width += padding; + bounds.height += padding; + + var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution); + + var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + + canvasBuffer.context.scale(resolution, resolution); + + canvasBuffer.context.translate(-bounds.x, -bounds.y); + + PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context); + + return texture; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Graphics#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderWebGL = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture on the gpu too! + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.worldAlpha = this.worldAlpha; + + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + + return; + } + else + { + renderSession.spriteBatch.stop(); + renderSession.blendModeManager.setBlendMode(this.blendMode); + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + if (this._filters) + { + renderSession.filterManager.pushFilter(this._filterBlock); + } + + // check blend mode + if (this.blendMode !== renderSession.spriteBatch.currentBlendMode) + { + renderSession.spriteBatch.currentBlendMode = this.blendMode; + var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode]; + renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + // check if the webgl graphic needs to be updated + if (this.webGLDirty) + { + this.dirty = true; + this.webGLDirty = false; + } + + PIXI.WebGLGraphics.renderGraphics(this, renderSession); + + // only render if it has children! + if (this.children.length) + { + renderSession.spriteBatch.start(); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + } + + if (this._filters) + { + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + renderSession.maskManager.popMask(this.mask, renderSession); + } + + renderSession.drawCount++; + + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method Phaser.Graphics#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderCanvas = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) + { + this.dirty = true; + this._prevTint = this.tint; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.alpha = this.alpha; + + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + + return; + } + else + { + var context = renderSession.context; + var transform = this.worldTransform; + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + var resolution = renderSession.resolution; + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + tx, + ty); + + PIXI.CanvasGraphics.renderGraphics(this, context); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + } + +}; + +/** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @method Phaser.Graphics#getBounds + * @return {Rectangle} the rectangular bounding area + */ +Phaser.Graphics.prototype.getBounds = function (matrix) { + + if (this._currentBounds) + { + return this._currentBounds; + } + + // Return an empty object if the item is a mask! + if (!this.renderable) + { + return Phaser.EmptyRectangle; + } + + if (this.dirty) + { + this.updateLocalBounds(); + this.webGLDirty = true; + this.cachedSpriteDirty = true; + this.dirty = false; + } + + var bounds = this._localBounds; + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = x1; + var maxY = y1; + + var minX = x1; + var minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + + this._bounds.x = minX; + this._bounds.width = maxX - minX; + + this._bounds.y = minY; + this._bounds.height = maxY - minY; + + this._currentBounds = this._bounds; + + return this._currentBounds; + +}; + +/** + * Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration. + * + * @method Phaser.Graphics#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +Phaser.Graphics.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Tests if a point is inside this graphics object +* +* @param point {Point} the point to test +* @return {boolean} the result of the test +*/ +Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) { + + if (tempPoint === undefined) { tempPoint = new Phaser.Point(); } + + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; i++) + { + var data = graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // only deal with fills.. + if (data.shape) + { + if (data.shape.contains(tempPoint.x, tempPoint.y)) + { + return true; + } + } + } + + return false; + +}; + +/** + * Update the bounds of the object + * + * @method Phaser.Graphics#updateLocalBounds + */ +Phaser.Graphics.prototype.updateLocalBounds = function () { + + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) + { + var shape, points, x, y, w, h; + + for (var i = 0; i < this.graphicsData.length; i++) + { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + shape = data.shape; + + if (type === Phaser.RECTANGLE || type === Phaser.ROUNDEDRECTANGLE) + { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.CIRCLE) + { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.ELLIPSE) + { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else + { + // POLY - assumes points are sequential, not Point objects + points = shape.points; + + for (var j = 0; j < points.length; j++) + { + if (points[j] instanceof Phaser.Point) + { + x = points[j].x; + y = points[j].y; + } + else + { + x = points[j]; + y = points[j + 1]; + + if (j < points.length - 1) + { + j++; + } + } + + minX = x - lineWidth < minX ? x - lineWidth : minX; + maxX = x + lineWidth > maxX ? x + lineWidth : maxX; + + minY = y - lineWidth < minY ? y - lineWidth : minY; + maxY = y + lineWidth > maxY ? y + lineWidth : maxY; + } + } + } + } + else + { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.x = minX - padding; + this._localBounds.width = (maxX - minX) + padding * 2; + + this._localBounds.y = minY - padding; + this._localBounds.height = (maxY - minY) + padding * 2; + +}; + +/** + * Generates the cached sprite when the sprite has cacheAsBitmap = true + * + * @method Phaser.Graphics#_generateCachedSprite + * @private + */ +Phaser.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); + } + + // leverage the anchor to account for the offset of the element + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + // this._cachedSprite.buffer.context.save(); + this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y); + + // make sure we set the alpha of the graphics to 1 for the render.. + this.worldAlpha = 1; + + // now render the graphic.. + PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context); + this._cachedSprite.alpha = this.alpha; + +}; + +/** + * Updates texture size based on canvas size + * + * @method Phaser.Graphics#updateCachedSpriteTexture + * @private + */ +Phaser.Graphics.prototype.updateCachedSpriteTexture = function () { + + var cachedSprite = this._cachedSprite; + var texture = cachedSprite.texture; + var canvas = cachedSprite.buffer.canvas; + + texture.baseTexture.width = canvas.width; + texture.baseTexture.height = canvas.height; + texture.crop.width = texture.frame.width = canvas.width; + texture.crop.height = texture.frame.height = canvas.height; + + cachedSprite._width = canvas.width; + cachedSprite._height = canvas.height; + + // update the dirty base textures + texture.baseTexture.dirty(); + +}; + +/** + * Destroys a previous cached sprite. + * + * @method Phaser.Graphics#destroyCachedSprite + */ +Phaser.Graphics.prototype.destroyCachedSprite = function () { + + this._cachedSprite.texture.destroy(true); + this._cachedSprite = null; + +}; + +/** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @method Phaser.Graphics#drawShape + * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. + * @return {GraphicsData} The generated GraphicsData object. + */ +Phaser.Graphics.prototype.drawShape = function (shape) { + + if (this.currentPath) + { + // check current path! + if (this.currentPath.shape.points.length <= 2) + { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + // Handle mixed-type polygons + if (shape instanceof Phaser.Polygon) + { + shape = shape.clone(); + shape.flatten(); + } + + var data = new Phaser.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === Phaser.POLYGON) + { + data.shape.closed = this.filling; + this.currentPath = data; + } + + this.dirty = true; + this._boundsDirty = true; + + return data; + +}; + +/** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory. + * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas. + * This is not recommended if you are constantly redrawing the graphics element. + * + * @property cacheAsBitmap + * @type Boolean + * @default false + * @private + */ +Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + this._cacheAsBitmap = value; + + if (this._cacheAsBitmap) + { + this._generateCachedSprite(); + } + else + { + this.destroyCachedSprite(); + } + + this.dirty = true; + this.webGLDirty = true; + + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and +* render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. +* +* @class Phaser.RenderTexture +* @constructor +* @extends PIXI.Texture +* @param {Phaser.Game} game - Current game instance. +* @param {number} [width=100] - The width of the render texture. +* @param {number} [height=100] - The height of the render texture. +* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there. +* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts. +* @param {number} [resolution=1] - The resolution of the texture being generated. +*/ +Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution, renderer, textureUnit) { + + if (width === undefined) { width = 100; } + if (height === undefined) { height = 100; } + if (key === undefined) { key = ''; } + if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; } + if (resolution === undefined) { resolution = 1; } + if (renderer === undefined) { renderer = PIXI.defaultRenderer; } + if (textureUnit === undefined) { textureUnit = 0; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the RenderTexture in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RENDERTEXTURE; + + /** + * @property {Phaser.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture. + * @private + */ + this._tempMatrix = new Phaser.Matrix(); + + this.width = width; + this.height = height; + this.resolution = resolution; + + this.frame = new Phaser.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); + + this.crop = this.frame.clone(); + + /** + * The base texture object that this texture uses + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = new PIXI.BaseTexture(); + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + this.baseTexture._glTextures = []; + this.baseTexture.resolution = this.resolution; + + this.baseTexture.scaleMode = scaleMode; + + this.baseTexture.hasLoaded = true; + + PIXI.Texture.call(this, this.baseTexture, this.frame.clone()); + + /** + * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. + * + * @property renderer + * @type CanvasRenderer|WebGLRenderer + */ + this.renderer = renderer; + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + this.baseTexture.textureIndex = textureUnit; + this.baseTexture._dirty[gl.id] = false; + + this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode, textureUnit); + this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; + + this.projection = new Phaser.Point(this.width * 0.5, -this.height * 0.5); + } + else + { + this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution); + this.baseTexture.source = this.textureBuffer.canvas; + } + + /** + * @property valid + * @type Boolean + */ + this.valid = true; + + this.tempMatrix = new Phaser.Matrix(); + + this._updateUvs(); + +}; + +Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype); +Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it takes into account scale and rotation. +* +* If you don't want those then use RenderTexture.renderRawXY instead. +* +* @method Phaser.RenderTexture.prototype.renderXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) { + + displayObject.updateTransform(); + + this._tempMatrix.copyFrom(displayObject.worldTransform); + this._tempMatrix.tx = x; + this._tempMatrix.ty = y; + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it doesn't take into account scale, rotation or translation. +* +* If you need those then use RenderTexture.renderXY instead. +* +* @method Phaser.RenderTexture.prototype.renderRawXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) { + + this._tempMatrix.identity().translate(x, y); + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture. +* +* In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. +* This is now a Matrix allowing you much more control over how the Display Object is rendered. +* If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. +* +* If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either +* pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. +* +* @method Phaser.RenderTexture.prototype.render +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) { + + if (matrix === undefined || matrix === null) + { + this._tempMatrix.copyFrom(displayObject.worldTransform); + } + else + { + this._tempMatrix.copyFrom(matrix); + } + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* Resizes the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.resize +* @param {number} width - The width to resize to. +* @param {number} height - The height to resize to. +* @param {boolean} updateBase - Should the baseTexture.width and height values be resized as well? +*/ +Phaser.RenderTexture.prototype.resize = function (width, height, updateBase) { + + if (width === this.width && height === this.height) + { + return; + } + + this.valid = (width > 0 && height > 0); + + this.width = width; + this.height = height; + this.frame.width = this.crop.width = width * this.resolution; + this.frame.height = this.crop.height = height * this.resolution; + + if (updateBase) + { + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.projection.x = this.width / 2; + this.projection.y = -this.height / 2; + } + + if (!this.valid) + { + return; + } + + this.textureBuffer.resize(this.width, this.height); + +}; + +/** +* Clears the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.clear +*/ +Phaser.RenderTexture.prototype.clear = function () { + + if (!this.valid) + { + return; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + } + + this.textureBuffer.clear(); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderWebGL +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +* @private +*/ +Phaser.RenderTexture.prototype._renderWebGL = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + wt.translate(0, this.projection.y * 2); + + if (matrix) + { + wt.append(matrix); + } + + wt.scale(1, -1); + + // Time to update all the children of the displayObject with the new matrix. + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + // Time for the webGL fun stuff! + var gl = this.renderer.gl; + + gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + + if (clear) + { + this.textureBuffer.clear(); + } + + this.renderer.spriteBatch.dirty = true; + + this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix); + + this.renderer.spriteBatch.dirty = true; + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderCanvas +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +*/ +Phaser.RenderTexture.prototype._renderCanvas = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + + if (matrix) + { + wt.append(matrix); + } + + // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!) + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + if (clear) + { + this.textureBuffer.clear(); + } + + var realResolution = this.renderer.resolution; + + this.renderer.resolution = this.resolution; + + this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix); + + this.renderer.resolution = realResolution; + +}; + +/** +* Will return a HTML Image of the texture +* +* @method Phaser.RenderTexture.prototype.getImage +* @return {Image} +*/ +Phaser.RenderTexture.prototype.getImage = function () { + + var image = new Image(); + image.src = this.getBase64(); + + return image; + +}; + +/** +* Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. +* +* @method Phaser.RenderTexture.prototype.getBase64 +* @return {String} A base64 encoded string of the texture. +*/ +Phaser.RenderTexture.prototype.getBase64 = function () { + + return this.getCanvas().toDataURL(); + +}; + +/** +* Creates a Canvas element, renders this RenderTexture to it and then returns it. +* +* @method Phaser.RenderTexture.prototype.getCanvas +* @return {HTMLCanvasElement} A Canvas element with the texture rendered on. +*/ +Phaser.RenderTexture.prototype.getCanvas = function () { + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + var width = this.textureBuffer.width; + var height = this.textureBuffer.height; + + var webGLPixels = new Uint8Array(4 * width * height); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + var tempCanvas = new PIXI.CanvasBuffer(width, height); + var canvasData = tempCanvas.context.getImageData(0, 0, width, height); + canvasData.data.set(webGLPixels); + + tempCanvas.context.putImageData(canvasData, 0, 0); + + return tempCanvas.canvas; + } + else + { + return this.textureBuffer.canvas; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new game object for displaying Text. +* +* This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. +* Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. +* +* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers. +* +* @class Phaser.Text +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {number} x - X position of the new text object. +* @param {number} y - Y position of the new text object. +* @param {string} text - The actual text that will be written. +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +*/ +Phaser.Text = function (game, x, y, text, style) { + + x = x || 0; + y = y || 0; + + if (text === undefined || text === null) + { + text = ''; + } + else + { + text = text.toString(); + } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.TEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. + * @property {Phaser.Point} padding + */ + this.padding = new Phaser.Point(); + + /** + * The textBounds property allows you to specify a rectangular region upon which text alignment is based. + * See `Text.setTextBounds` for more details. + * @property {Phaser.Rectangle} textBounds + * @readOnly + */ + this.textBounds = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. + */ + this.canvas = Phaser.CanvasPool.create(this); + + /** + * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. + */ + this.context = this.canvas.getContext('2d'); + + /** + * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}. + */ + this.colors = []; + + /** + * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}. + */ + this.strokeColors = []; + + /** + * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}. + */ + this.fontStyles = []; + + /** + * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}. + */ + this.fontWeights = []; + + /** + * Should the linePositionX and Y values be automatically rounded before rendering the Text? + * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. + * @property {boolean} autoRound + * @default + */ + this.autoRound = false; + + /** + * Will this Text object use Basic or Advanced Word Wrapping? + * + * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. + * White space is condensed (e.g., consecutive spaces are replaced with one). + * Lines are trimmed of white space before processing. + * + * It throws an error if wordWrapWidth is less than a single character. + * @property {boolean} useAdvancedWrap + * @default + */ + this.useAdvancedWrap = false; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + * @property {Object} splitRegExp + */ + this.splitRegExp = /(?:\r\n|\r|\n)/; + + + /** The maximum number of characters that can be set. + * @property {number} characterLimitSize + */ + this.characterLimitSize = -1; + + /** The suffix that is applied to truncated text that is longer than the + * characterLimitSize. + * @property {string} characterLimitSuffix + */ + this.characterLimitSuffix = ''; + + /** + * @property {number} _res - Internal canvas resolution var. + * @private + */ + this._res = game.renderer.resolution; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text; + + /** + * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`. + * @private + */ + this._fontComponents = null; + + /** + * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. + * @private + */ + this._lineSpacing = 0; + + /** + * @property {number} _charCount - Internal character counter used by the text coloring. + * @private + */ + this._charCount = 0; + + /** + * @property {number} _width - Internal width var. + * @private + */ + this._width = 0; + + /** + * @property {number} _height - Internal height var. + * @private + */ + this._height = 0; + + Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas)); + + /** + * @property {object} style + * @private + */ + this.style = {}; + + this.setStyle(style || {}); + + if (text !== '') + { + this.updateText(); + } + +}; + +Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Text.prototype.constructor = Phaser.Text; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Text#preUpdate +* @protected +*/ +Phaser.Text.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override this function to handle any special update requirements. +* +* @method Phaser.Text#update +* @protected +*/ +Phaser.Text.prototype.update = function() { + +}; + +/** +* Destroy this Text object, removing it from the group it belongs to. +* +* @method Phaser.Text#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Text.prototype.destroy = function (destroyChildren) { + + this.texture.destroy(true); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. +* The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. +* The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. +* To remove a shadow already in place you can call this method with no parameters set. +* +* @method Phaser.Text#setShadow +* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +* @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. +* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +* @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set). +* @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; } + if (blur === undefined) { blur = 0; } + if (shadowStroke === undefined) { shadowStroke = true; } + if (shadowFill === undefined) { shadowFill = true; } + + this.style.shadowOffsetX = x; + this.style.shadowOffsetY = y; + this.style.shadowColor = color; + this.style.shadowBlur = blur; + this.style.shadowStroke = shadowStroke; + this.style.shadowFill = shadowFill; + this.dirty = true; + + return this; + +}; + +/** +* Set the style of the text by passing a single style object to it. +* +* @method Phaser.Text#setStyle +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +* @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setStyle = function (style, update) { + + if (update === undefined) { update = false; } + + var newStyle = Object.assign({}, style); + newStyle.font = style.font || 'bold 20pt Arial'; + newStyle.backgroundColor = style.backgroundColor || null; + newStyle.fill = style.fill || 'black'; + newStyle.align = (style.align || 'left').toLowerCase(); + newStyle.boundsAlignH = (style.boundsAlignH || 'left').toLowerCase(); + newStyle.boundsAlignV = (style.boundsAlignV || 'top').toLowerCase(); + newStyle.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136 + newStyle.strokeThickness = Number(style.strokeThickness) || 0; + newStyle.wordWrap = style.wordWrap || false; + newStyle.wordWrapWidth = style.wordWrapWidth || 100; + newStyle.maxLines = style.maxLines || 0; + newStyle.shadowOffsetX = style.shadowOffsetX || 0; + newStyle.shadowOffsetY = style.shadowOffsetY || 0; + newStyle.shadowColor = style.shadowColor || 'rgba(0,0,0,0)'; + newStyle.shadowBlur = style.shadowBlur || 0; + newStyle.tabs = style.tabs || 0; + + var components = this.fontToComponents(newStyle.font); + + if (newStyle.fontStyle) + { + components.fontStyle = newStyle.fontStyle; + } + + if (newStyle.fontVariant) + { + components.fontVariant = newStyle.fontVariant; + } + + if (newStyle.fontWeight) + { + components.fontWeight = newStyle.fontWeight; + } + + if (newStyle.fontSize) + { + if (typeof newStyle.fontSize === 'number') + { + newStyle.fontSize = newStyle.fontSize + 'px'; + } + + components.fontSize = newStyle.fontSize; + } + + this._fontComponents = components; + + newStyle.font = this.componentsToFont(this._fontComponents); + + this.style = newStyle; + this.dirty = true; + + if (update) + { + this.updateText(); + } + + return this; + +}; + +/** +* Renders text to the internal canvas. +* +* @method Phaser.Text#updateText +* @private +*/ +Phaser.Text.prototype.updateText = function () { + + this.texture.baseTexture.resolution = this._res; + + this.context.font = this.style.font; + + var outputText = this.text; + + if (this.characterLimitSize > -1 && this.characterLimitSize < outputText.length) { + outputText = this.text.substring(0, this.characterLimitSize) + this.characterLimitSuffix; + } + + if (this.style.wordWrap) + { + outputText = this.runWordWrap(this.text); + } + + // Split text into lines + var lines = outputText.split(this.splitRegExp); + + // Calculate text width + var tabs = this.style.tabs; + var lineWidths = []; + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this.style.font); + + var drawnLines = lines.length; + + if (this.style.maxLines > 0 && this.style.maxLines < lines.length) + { + drawnLines = this.style.maxLines; + } + + this._charCount = 0; + + for (var i = 0; i < drawnLines; i++) + { + if (tabs === 0) + { + // Simple layout (no tabs) + var lineWidth = this.style.strokeThickness + this.padding.x; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(lines[i]); + } + else + { + lineWidth += this.context.measureText(lines[i]).width; + } + + // Adjust for wrapped text + if (this.style.wordWrap) + { + lineWidth -= this.context.measureText(' ').width; + } + } + else + { + // Complex layout (tabs) + var line = lines[i].split(/(?:\t)/); + var lineWidth = this.padding.x + this.style.strokeThickness; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < line.length; c++) + { + var section = 0; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + section = this.measureLine(line[c]); + } + else + { + section = Math.ceil(this.context.measureText(line[c]).width); + } + + if (c > 0) + { + tab += tabs[c - 1]; + } + + lineWidth = tab + section; + } + } + else + { + for (var c = 0; c < line.length; c++) + { + // How far to the next tab? + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(line[c]); + } + else + { + lineWidth += Math.ceil(this.context.measureText(line[c]).width); + } + + var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth; + + lineWidth += diff; + } + } + } + + lineWidths[i] = Math.ceil(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); + } + + this.canvas.width = maxLineWidth * this._res; + + // Calculate text height + var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y; + var height = lineHeight * drawnLines; + var lineSpacing = this._lineSpacing; + + if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight) + { + lineSpacing = -lineHeight; + } + + // Adjust for line spacing + if (lineSpacing !== 0) + { + height += (lineSpacing > 0) ? lineSpacing * lines.length : lineSpacing * (lines.length - 1); + } + + this.canvas.height = height * this._res; + + this.context.scale(this._res, this._res); + + if (navigator.isCocoonJS) + { + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + } + + if (this.style.backgroundColor) + { + this.context.fillStyle = this.style.backgroundColor; + this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); + } + + this.context.fillStyle = this.style.fill; + this.context.font = this.style.font; + this.context.strokeStyle = this.style.stroke; + this.context.textBaseline = 'alphabetic'; + + this.context.lineWidth = this.style.strokeThickness; + this.context.lineCap = 'round'; + this.context.lineJoin = 'round'; + + var linePositionX; + var linePositionY; + + this._charCount = 0; + + // Draw text line by line + for (i = 0; i < drawnLines; i++) + { + // Split the line by + + linePositionX = this.style.strokeThickness / 2; + linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (i > 0) + { + linePositionY += (lineSpacing * i); + } + + if (this.style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (this.style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (this.autoRound) + { + linePositionX = Math.round(linePositionX); + linePositionY = Math.round(linePositionY); + } + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + this.updateLine(lines[i], linePositionX, linePositionY); + } + else + { + if (this.style.stroke && this.style.strokeThickness) + { + this.updateShadow(this.style.shadowStroke); + + if (tabs === 0) + { + this.context.strokeText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, false); + } + } + + if (this.style.fill) + { + this.updateShadow(this.style.shadowFill); + + if (tabs === 0) + { + this.context.fillText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, true); + } + } + } + } + + this.updateTexture(); + + this.dirty = false; + +}; + +/** +* Renders a line of text that contains tab characters if Text.tab > 0. +* Called automatically by updateText. +* +* @method Phaser.Text#renderTabLine +* @private +* @param {string} line - The line of text to render. +* @param {integer} x - The x position to start rendering from. +* @param {integer} y - The y position to start rendering from. +* @param {boolean} fill - If true uses fillText, if false uses strokeText. +*/ +Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) { + + var text = line.split(/(?:\t)/); + var tabs = this.style.tabs; + var snap = 0; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < text.length; c++) + { + if (c > 0) + { + tab += tabs[c - 1]; + } + + snap = x + tab; + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + } + } + else + { + for (var c = 0; c < text.length; c++) + { + var section = Math.ceil(this.context.measureText(text[c]).width); + + // How far to the next tab? + snap = this.game.math.snapToCeil(x, tabs); + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + + x = snap + section; + } + } + +}; + +/** +* Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. +* This is called automatically by Text.updateText. +* +* @method Phaser.Text#updateShadow +* @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero. +*/ +Phaser.Text.prototype.updateShadow = function (state) { + + if (state) + { + this.context.shadowOffsetX = this.style.shadowOffsetX; + this.context.shadowOffsetY = this.style.shadowOffsetY; + this.context.shadowColor = this.style.shadowColor; + this.context.shadowBlur = this.style.shadowBlur; + } + else + { + this.context.shadowOffsetX = 0; + this.context.shadowOffsetY = 0; + this.context.shadowColor = 0; + this.context.shadowBlur = 0; + } + +}; + +/** +* Measures a line of text character by character taking into the account the specified character styles. +* +* @method Phaser.Text#measureLine +* @private +* @param {string} line - The line of text to measure. +* @return {integer} length of the line. +*/ +Phaser.Text.prototype.measureLine = function (line) { + + var lineLength = 0; + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + } + + lineLength += this.context.measureText(letter).width; + + this._charCount++; + } + + return Math.ceil(lineLength); +}; + +/** +* Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable. +* +* @method Phaser.Text#updateLine +* @private +*/ +Phaser.Text.prototype.updateLine = function (line, x, y) { + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + this.context.strokeText(letter, x, y); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + this.context.fillText(letter, x, y); + } + + x += this.context.measureText(letter).width; + + this._charCount++; + } + +}; + +/** +* Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. +* +* @method Phaser.Text#clearColors +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearColors = function () { + + this.colors = []; + this.strokeColors = []; + this.dirty = true; + + return this; + +}; + +/** +* Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. +* +* @method Phaser.Text#clearFontValues +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearFontValues = function () { + + this.fontStyles = []; + this.fontWeights = []; + this.dirty = true; + + return this; + +}; + +/** +* Set specific colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* If you wish to change the stroke color see addStrokeColor instead. +* +* @method Phaser.Text#addColor +* @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addColor = function (color, position) { + + this.colors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific stroke colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* This has no effect if stroke is disabled or has a thickness of 0. +* +* If you wish to change the text fill color see addColor instead. +* +* @method Phaser.Text#addStrokeColor +* @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addStrokeColor = function (color, position) { + + this.strokeColors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font styles for certain characters within the Text. +* +* It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. +* The position value is the index of the character in the Text string to start applying this font style to. +* Once set the font style remains in use until either another font style or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. +* +* If you wish to change the text font weight see addFontWeight instead. +* +* @method Phaser.Text#addFontStyle +* @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. +* @param {number} position - The index of the character in the string to start applying this font style value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontStyle = function (style, position) { + + this.fontStyles[position] = style; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font weights for certain characters within the Text. +* +* It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. +* The position value is the index of the character in the Text string to start applying this font weight to. +* Once set the font weight remains in use until either another font weight or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. +* +* If you wish to change the text font style see addFontStyle instead. +* +* @method Phaser.Text#addFontWeight +* @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. +* @param {number} position - The index of the character in the string to start applying this font weight value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontWeight = function (weight, position) { + + this.fontWeights[position] = weight; + this.dirty = true; + + return this; + +}; + +/** +* Runs the given text through the Text.runWordWrap function and returns +* the results as an array, where each element of the array corresponds to a wrapped +* line of text. +* +* Useful if you wish to control pagination on long pieces of content. +* +* @method Phaser.Text#precalculateWordWrap +* @param {string} text - The text for which the wrapping will be calculated. +* @return {array} An array of strings with the pieces of wrapped text. +*/ +Phaser.Text.prototype.precalculateWordWrap = function (text) { + + this.texture.baseTexture.resolution = this._res; + this.context.font = this.style.font; + + var wrappedLines = this.runWordWrap(text); + + return wrappedLines.split(/(?:\r\n|\r|\n)/); + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#runWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.runWordWrap = function (text) { + + if (this.useAdvancedWrap) + { + return this.advancedWordWrap(text); + } + else + { + return this.basicWordWrap(text); + } + +}; + +/** +* Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* White space is condensed (e.g., consecutive spaces are replaced with one). +* Lines are trimmed of white space before processing. +* Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character. +* +* @method Phaser.Text#advancedWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.advancedWordWrap = function (text) { + + var context = this.context; + var wordWrapWidth = this.style.wordWrapWidth; + + var output = ''; + + // (1) condense whitespace + // (2) split into lines + var lines = text + .replace(/ +/gi, ' ') + .split(/\r?\n/gi); + + var linesCount = lines.length; + + for (var i = 0; i < linesCount; i++) + { + var line = lines[i]; + var out = ''; + + // trim whitespace + line = line.replace(/^ *|\s*$/gi, ''); + + // if entire line is less than wordWrapWidth + // append the entire line and exit early + var lineWidth = context.measureText(line).width; + + if (lineWidth < wordWrapWidth) + { + output += line + '\n'; + continue; + } + + // otherwise, calculate new lines + var currentLineWidth = wordWrapWidth; + + // split into words + var words = line.split(' '); + + for (var j = 0; j < words.length; j++) + { + var word = words[j]; + var wordWithSpace = word + ' '; + var wordWidth = context.measureText(wordWithSpace).width; + + if (wordWidth > currentLineWidth) + { + // break word + if (j === 0) + { + // shave off letters from word until it's small enough + var newWord = wordWithSpace; + + while (newWord.length) + { + newWord = newWord.slice(0, -1); + wordWidth = context.measureText(newWord).width; + + if (wordWidth <= currentLineWidth) + { + break; + } + } + + // if wordWrapWidth is too small for even a single + // letter, shame user failure with a fatal error + if (!newWord.length) + { + throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); + } + + // replace current word in array with remainder + var secondPart = word.substr(newWord.length); + + words[j] = secondPart; + + // append first piece to output + out += newWord; + } + + // if existing word length is 0, don't include it + var offset = (words[j].length) ? j : j + 1; + + // collapse rest of sentence + var remainder = words.slice(offset).join(' ') + // remove any trailing white space + .replace(/[ \n]*$/gi, ''); + + // prepend remainder to next line + lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); + linesCount = lines.length; + + break; // processing on this line + + // append word with space to output + } + else + { + out += wordWithSpace; + currentLineWidth -= wordWidth; + } + } + + // append processed line to output + output += out.replace(/[ \n]*$/gi, '') + '\n'; + } + + // trim the end of the string + output = output.replace(/[\s|\n]*$/gi, ''); + + return output; + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#basicWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.basicWordWrap = function (text) { + + var result = ''; + var lines = text.split('\n'); + + for (var i = 0; i < lines.length; i++) + { + var spaceLeft = this.style.wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) + { + var wordWidth = this.context.measureText(words[j]).width; + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is greater than the word wrap width. + if (j > 0) + { + result += '\n'; + } + result += words[j] + ' '; + spaceLeft = this.style.wordWrapWidth - wordWidth; + } + else + { + spaceLeft -= wordWidthWithSpace; + result += words[j] + ' '; + } + } + + if (i < lines.length-1) + { + result += '\n'; + } + } + + return result; + +}; + +/** +* Updates the internal `style.font` if it now differs according to generation from components. +* +* @method Phaser.Text#updateFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.updateFont = function (components) { + + var font = this.componentsToFont(components); + + if (this.style.font !== font) + { + this.style.font = font; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + +}; + +/** +* Converting a short CSS-font string into the relevant components. +* +* @method Phaser.Text#fontToComponents +* @private +* @param {string} font - a CSS font string +*/ +Phaser.Text.prototype.fontToComponents = function (font) { + + // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand: + // style - normal | italic | oblique | inherit + // variant - normal | small-caps | inherit + // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit + // size - xx-small | x-small | small | medium | large | x-large | xx-large, + // larger | smaller + // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %) + // font-family - rest (but identifiers or quoted with comma separation) + var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/); + + if (m) + { + var family = m[5].trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(family) && !/['",]/.exec(family)) + { + family = "'" + family + "'"; + } + + return { + font: font, + fontStyle: m[1] || 'normal', + fontVariant: m[2] || 'normal', + fontWeight: m[3] || 'normal', + fontSize: m[4] || 'medium', + fontFamily: family + }; + } + else + { + console.warn("Phaser.Text - unparsable CSS font: " + font); + + return { + font: font + }; + } + +}; + +/** +* Converts individual font components (see `fontToComponents`) to a short CSS font string. +* +* @method Phaser.Text#componentsToFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.componentsToFont = function (components) { + + var parts = []; + var v; + + v = components.fontStyle; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontVariant; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontWeight; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontSize; + if (v && v !== 'medium') { parts.push(v); } + + v = components.fontFamily; + if (v) { parts.push(v); } + + if (!parts.length) + { + // Fallback to whatever value the 'font' was + parts.push(components.font); + } + + return parts.join(" "); + +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* Use the optional `immediate` argument if you need the Text display to update immediately. +* +* If not it will re-create the texture of this Text object during the next time the render +* loop is called. +* +* @method Phaser.Text#setText +* @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present. +* @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setText = function (text, immediate) { + + if (immediate === undefined) { immediate = false; } + + this.text = text.toString() || ''; + + if (immediate) + { + this.updateText(); + } + else + { + this.dirty = true; + } + + return this; + +}; + +/** + * Converts the given array into a tab delimited string and then updates this Text object. + * This is mostly used when you want to display external data using tab stops. + * + * The array can be either single or multi dimensional depending on the result you need: + * + * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`. + * + * Where as: + * + * `[ + * [ 'a', 'b', 'c' ], + * [ 'd', 'e', 'f'] + * ]` + * + * would convert in to: `"a\tb\tc\nd\te\tf"` + * + * @method Phaser.Text#parseList + * @param {array} list - The array of data to convert into a string. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.parseList = function (list) { + + if (!Array.isArray(list)) + { + return this; + } + else + { + var s = ""; + + for (var i = 0; i < list.length; i++) + { + if (Array.isArray(list[i])) + { + s += list[i].join("\t"); + + if (i < list.length - 1) + { + s += "\n"; + } + } + else + { + s += list[i]; + + if (i < list.length - 1) + { + s += "\t"; + } + } + } + } + + this.text = s; + this.dirty = true; + + return this; + +}; + +/** + * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned, + * regardless of the number of lines in the text, the font size or any other attribute. + * + * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly + * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment. + * + * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to + * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of + * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center + * of the text bounds. + * + * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions + * may vary based on font (say for multi-lingual games). + * + * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width. + * + * Call this method with no arguments given to reset an existing textBounds. + * + * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts + * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot` + * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then + * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot. + * + * @method Phaser.Text#setTextBounds + * @param {number} [x] - The x coordinate of the Text Bounds region. + * @param {number} [y] - The y coordinate of the Text Bounds region. + * @param {number} [width] - The width of the Text Bounds region. + * @param {number} [height] - The height of the Text Bounds region. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.setTextBounds = function (x, y, width, height) { + + if (x === undefined) + { + this.textBounds = null; + } + else + { + if (!this.textBounds) + { + this.textBounds = new Phaser.Rectangle(x, y, width, height); + } + else + { + this.textBounds.setTo(x, y, width, height); + } + + if (this.style.wordWrapWidth > width) + { + this.style.wordWrapWidth = width; + } + } + + this.updateTexture(); + + return this; + +}; + +/** + * Updates the texture based on the canvas dimensions. + * + * @method Phaser.Text#updateTexture + * @private + */ +Phaser.Text.prototype.updateTexture = function () { + + var base = this.texture.baseTexture; + var crop = this.texture.crop; + var frame = this.texture.frame; + + var w = this.canvas.width; + var h = this.canvas.height; + + base.width = w; + base.height = h; + + crop.width = w; + crop.height = h; + + frame.width = w; + frame.height = h; + + this.texture.width = w; + this.texture.height = h; + + this._width = w; + this._height = h; + + if (this.textBounds) + { + var x = this.textBounds.x; + var y = this.textBounds.y; + + // Align the canvas based on the bounds + if (this.style.boundsAlignH === 'right') + { + x += this.textBounds.width - this.canvas.width / this.resolution; + } + else if (this.style.boundsAlignH === 'center') + { + x += this.textBounds.halfWidth - (this.canvas.width / this.resolution / 2); + } + + if (this.style.boundsAlignV === 'bottom') + { + y += this.textBounds.height - this.canvas.height / this.resolution; + } + else if (this.style.boundsAlignV === 'middle') + { + y += this.textBounds.halfHeight - (this.canvas.height / this.resolution / 2); + } + + this.pivot.x = -x; + this.pivot.y = -y; + } + + // Can't render something with a zero sized dimension + this.renderable = (w !== 0 && h !== 0); + + this.texture.requiresReTint = true; + + this.texture.baseTexture.dirty(); + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Text#_renderWebGL +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderWebGL = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Renders the object using the Canvas renderer. +* +* @method Phaser.Text#_renderCanvas +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderCanvas = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Calculates the ascent, descent and fontSize of a given font style. +* +* @method Phaser.Text#determineFontProperties +* @private +* @param {object} fontStyle +*/ +Phaser.Text.prototype.determineFontProperties = function (fontStyle) { + + var properties = Phaser.Text.fontPropertiesCache[fontStyle]; + + if (!properties) + { + properties = {}; + + var canvas = Phaser.Text.fontPropertiesCanvas; + var context = Phaser.Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('|MÉq').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + if (!context.getImageData(0, 0, width, height)) + { + properties.ascent = baseline; + properties.descent = baseline + 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + } + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i, j; + + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + properties.descent = i - baseline; + //TODO might need a tweak. kind of a temp fix! + properties.descent += 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; + +}; + +/** +* Returns the bounds of the Text as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Text#getBounds +* @param {Phaser.Matrix} matrix - The transformation matrix of the Text. +* @return {Phaser.Rectangle} The framing rectangle +*/ +Phaser.Text.prototype.getBounds = function (matrix) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return PIXI.Sprite.prototype.getBounds.call(this, matrix); + +}; + +/** +* Sets the character limit of the text, with a suffix. +* If the text is longer than this limit, it is truncated and the suffix is appended. +* +* @method Phaser.Text#setCharacterLimit +* @param {number} [characterLimit] - The x coordinate of the Text Bounds region. +* @param {string} [suffix] - The suffix to append to the truncated text. +*/ +Phaser.Text.prototype.setCharacterLimit = function (characterLimit, suffix) { + + this.characterLimitSuffix = (suffix === undefined) ? '' : suffix; + this.characterLimitSize = characterLimit; + + this.updateText(); +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* @name Phaser.Text#text +* @property {string} text +*/ +Object.defineProperty(Phaser.Text.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* Change the font used. +* +* This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except +* that unlike using `setStyle` this will not change any current font fill/color settings. +* +* The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. +* +* @name Phaser.Text#cssFont +* @property {string} cssFont +*/ +Object.defineProperty(Phaser.Text.prototype, 'cssFont', { + + get: function() { + return this.componentsToFont(this._fontComponents); + }, + + set: function (value) + { + value = value || 'bold 20pt Arial'; + this._fontComponents = this.fontToComponents(value); + this.updateFont(this._fontComponents); + } + +}); + +/** +* Change the font family that the text will be rendered in, such as 'Arial'. +* +* Multiple CSS font families and generic fallbacks can be specified as long as +* {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed. +* +* To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`. +* +* @name Phaser.Text#font +* @property {string} font +*/ +Object.defineProperty(Phaser.Text.prototype, 'font', { + + get: function() { + return this._fontComponents.fontFamily; + }, + + set: function(value) { + + value = value || 'Arial'; + value = value.trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value)) + { + value = "'" + value + "'"; + } + + this._fontComponents.fontFamily = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The size of the font. +* +* If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing +* the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). +* +* @name Phaser.Text#fontSize +* @property {number|string} fontSize +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontSize', { + + get: function() { + + var size = this._fontComponents.fontSize; + + if (size && /(?:^0$|px$)/.exec(size)) + { + return parseInt(size, 10); + } + else + { + return size; + } + + }, + + set: function(value) { + + value = value || '0'; + + if (typeof value === 'number') + { + value = value + 'px'; + } + + this._fontComponents.fontSize = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}. +* @name Phaser.Text#fontWeight +* @property {string} fontWeight +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontWeight', { + + get: function() { + return this._fontComponents.fontWeight || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontWeight = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The style of the font: 'normal', 'italic', 'oblique' +* @name Phaser.Text#fontStyle +* @property {string} fontStyle +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontStyle', { + + get: function() { + return this._fontComponents.fontStyle || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontStyle = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The variant the font: 'normal', 'small-caps' +* @name Phaser.Text#fontVariant +* @property {string} fontVariant +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontVariant', { + + get: function() { + return this._fontComponents.fontVariant || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontVariant = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* @name Phaser.Text#fill +* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'fill', { + + get: function() { + return this.style.fill; + }, + + set: function(value) { + + if (value !== this.style.fill) + { + this.style.fill = value; + this.dirty = true; + } + + } + +}); + +/** +* Controls the horizontal alignment for multiline text. +* Can be: 'left', 'center' or 'right'. +* Does not affect single lines of text. For that please see `setTextBounds`. +* @name Phaser.Text#align +* @property {string} align +*/ +Object.defineProperty(Phaser.Text.prototype, 'align', { + + get: function() { + return this.style.align; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.align) + { + this.style.align = value; + this.dirty = true; + } + + } + +}); + +/** +* The resolution of the canvas the text is rendered to. +* This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. +* @name Phaser.Text#resolution +* @property {integer} resolution +*/ +Object.defineProperty(Phaser.Text.prototype, 'resolution', { + + get: function() { + return this._res; + }, + + set: function(value) { + + if (value !== this._res) + { + this._res = value; + this.dirty = true; + } + + } + +}); + +/** +* The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. +* Can be an integer or an array of varying tab sizes, one tab per element. +* For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. +* If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. +* +* @name Phaser.Text#tabs +* @property {integer|array} tabs +*/ +Object.defineProperty(Phaser.Text.prototype, 'tabs', { + + get: function() { + return this.style.tabs; + }, + + set: function(value) { + + if (value !== this.style.tabs) + { + this.style.tabs = value; + this.dirty = true; + } + + } + +}); + +/** +* Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @name Phaser.Text#boundsAlignH +* @property {string} boundsAlignH +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', { + + get: function() { + return this.style.boundsAlignH; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignH) + { + this.style.boundsAlignH = value; + this.dirty = true; + } + + } + +}); + +/** +* Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @name Phaser.Text#boundsAlignV +* @property {string} boundsAlignV +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', { + + get: function() { + return this.style.boundsAlignV; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignV) + { + this.style.boundsAlignV = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#stroke +* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'stroke', { + + get: function() { + return this.style.stroke; + }, + + set: function(value) { + + if (value !== this.style.stroke) + { + this.style.stroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#strokeThickness +* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke) +*/ +Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', { + + get: function() { + return this.style.strokeThickness; + }, + + set: function(value) { + + if (value !== this.style.strokeThickness) + { + this.style.strokeThickness = Number(value); + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrap +* @property {boolean} wordWrap - Indicates if word wrap should be used. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrap', { + + get: function() { + return this.style.wordWrap; + }, + + set: function(value) { + + if (value !== this.style.wordWrap) + { + this.style.wordWrap = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrapWidth +* @property {number} wordWrapWidth - The width at which text will wrap. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', { + + get: function() { + return this.style.wordWrapWidth; + }, + + set: function(value) { + + if (value !== this.style.wordWrapWidth) + { + this.style.wordWrapWidth = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#lineSpacing +* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. +*/ +Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { + + get: function() { + return this._lineSpacing; + }, + + set: function(value) { + + if (value !== this._lineSpacing) + { + this._lineSpacing = parseFloat(value); + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetX +* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', { + + get: function() { + return this.style.shadowOffsetX; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetX) + { + this.style.shadowOffsetX = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetY +* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', { + + get: function() { + return this.style.shadowOffsetY; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetY) + { + this.style.shadowOffsetY = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowColor +* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowColor', { + + get: function() { + return this.style.shadowColor; + }, + + set: function(value) { + + if (value !== this.style.shadowColor) + { + this.style.shadowColor = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowBlur +* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', { + + get: function() { + return this.style.shadowBlur; + }, + + set: function(value) { + + if (value !== this.style.shadowBlur) + { + this.style.shadowBlur = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowStroke +* @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', { + + get: function() { + return this.style.shadowStroke; + }, + + set: function(value) { + + if (value !== this.style.shadowStroke) + { + this.style.shadowStroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowFill +* @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowFill', { + + get: function() { + return this.style.shadowFill; + }, + + set: function(value) { + + if (value !== this.style.shadowFill) + { + this.style.shadowFill = value; + this.dirty = true; + } + + } + +}); + +/** +* The width of the Text object in pixels. This is width of the Texture frame / the Text.resolution. +* @name Phaser.Text#width +* @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'width', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.x * (this.texture.frame.width / this.resolution); + }, + + set: function(value) { + + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** +* The height of the Text object in pixels. This is height of the Texture frame / the Text.resolution. +* @name Phaser.Text#height +* @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'height', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.y * (this.texture.frame.height / this.resolution); + }, + + set: function(value) { + + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +Phaser.Text.fontPropertiesCache = {}; + +Phaser.Text.fontPropertiesCanvas = document.createElement('canvas'); +Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d'); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. +* It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to +* match the font structure. +* +* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability +* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by +* processing the font texture in an image editor, applying fills and any other effects required. +* +* To create multi-line text insert \r, \n or \r\n escape codes into the text string. +* +* If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly +* updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. +* +* To create a BitmapText data files you can use: +* +* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ +* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner +* Littera (Web-based, free): http://kvazars.com/littera/ +* +* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of +* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson +* +* If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. +* +* @class Phaser.BitmapText +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - X coordinate to display the BitmapText object at. +* @param {number} y - Y coordinate to display the BitmapText object at. +* @param {string} font - The key of the BitmapText as stored in Phaser.Cache. +* @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. +* @param {number} [size=32] - The size the font will be rendered at in pixels. +* @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. +*/ +Phaser.BitmapText = function (game, x, y, font, text, size, align) { + + x = x || 0; + y = y || 0; + font = font || ''; + text = text || ''; + size = size || 32; + align = align || 'left'; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.BITMAPTEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textWidth = 0; + + /** + * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textHeight = 0; + + /** + * @property {Phaser.Point} anchor - The anchor value of this BitmapText. + */ + this.anchor = new Phaser.Point(); + + /** + * @property {Phaser.Point} _prevAnchor - The previous anchor value. + * @private + */ + this._prevAnchor = new Phaser.Point(); + + /** + * @property {array} _glyphs - Private tracker for the letter sprite pool. + * @private + */ + this._glyphs = []; + + /** + * @property {number} _maxWidth - Internal cache var. + * @private + */ + this._maxWidth = 0; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text.toString() || ''; + + /** + * @property {string} _data - Internal cache var. + * @private + */ + this._data = game.cache.getBitmapFont(font); + + /** + * @property {string} _font - Internal cache var. + * @private + */ + this._font = font; + + /** + * @property {number} _fontSize - Internal cache var. + * @private + */ + this._fontSize = size; + + /** + * @property {string} _align - Internal cache var. + * @private + */ + this._align = align; + + /** + * @property {number} _tint - Internal cache var. + * @private + */ + this._tint = 0xFFFFFF; + + this.updateText(); + + /** + * @property {boolean} dirty - The dirty state of this object. + */ + this.dirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.BitmapText.prototype.constructor = Phaser.BitmapText; + +Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.BitmapText +* @return {boolean} True if the BitmapText was rendered, otherwise false. +*/ +Phaser.BitmapText.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.preUpdate. +* @method Phaser.BitmapText.prototype.postUpdate +*/ +Phaser.BitmapText.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this.body && this.body.type === Phaser.Physics.ARCADE) + { + if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight)) + { + this.body.setSize(this.textWidth, this.textHeight); + } + } + +}; + +/** +* The text to be displayed by this BitmapText object. +* +* It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. +* +* @method Phaser.BitmapText.prototype.setText +* @param {string} text - The text to be displayed by this BitmapText object. +*/ +Phaser.BitmapText.prototype.setText = function (text) { + + this.text = text; + +}; + +/** +* Given the input text this will scan the characters until either a newline is encountered, +* or the line exceeds maxWidth, taking into account kerning, character widths and scaling. +* +* @method Phaser.BitmapText.prototype.scanLine +* @private +* @param {object} data - A reference to the font object in the Phaser.Cache. +* @param {float} scale - The scale of the font in relation to the texture. +* @param {string} text - The text to parse. +* @return {object} An object containing the parsed characters, total pixel width and x offsets. +*/ +Phaser.BitmapText.prototype.scanLine = function (data, scale, text) { + + var x = 0; + var w = 0; + var lastSpace = -1; + var wrappedWidth = 0; + var prevCharCode = null; + var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null; + var chars = []; + + // Let's scan the text and work out if any of the lines are > maxWidth + for (var i = 0; i < text.length; i++) + { + var end = (i === text.length - 1) ? true : false; + + if (/(?:\r\n|\r|\n)/.test(text.charAt(i))) + { + return { width: w, text: text.substr(0, i), end: end, chars: chars }; + } + else + { + var charCode = text.charCodeAt(i); + var charData = data.chars[charCode]; + + var c = 0; + + // If the character data isn't found in the data array + // then we replace it with a blank space + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + // Adjust for kerning from previous character to this one + var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0; + + // Record the last space in the string and the current width + if (/(\s)/.test(text.charAt(i))) + { + lastSpace = i; + wrappedWidth = w; + } + + // What will the line width be if we add this character to it? + c = (kerning + charData.texture.width + charData.xOffset) * scale; + + // Do we need to line-wrap? + if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1) + { + // The last space was at "lastSpace" which was "i - lastSpace" characters ago + return { width: wrappedWidth || w, text: text.substr(0, i - (i - lastSpace)), end: false, chars: chars }; + } + else + { + w += (charData.xAdvance + kerning) * scale; + + chars.push(x + (charData.xOffset + kerning) * scale); + + x += (charData.xAdvance + kerning) * scale; + + prevCharCode = charCode; + } + } + } + + return { width: w, text: text, end: end, chars: chars }; + +}; + +/** +* Given a text string this will scan each character in the string to ensure it exists +* in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. +* +* If no font data has been loaded at all this returns an empty string, as nothing can be rendered. +* +* @method Phaser.BitmapText.prototype.cleanText +* @param {string} text - The text to parse. +* @param {string} [replace=''] - The replacement string for any missing characters. +* @return {string} The cleaned text string. +*/ +Phaser.BitmapText.prototype.cleanText = function (text, replace) { + + if (replace === undefined) + { + replace = ''; + } + + var data = this._data.font; + + if (!data) + { + return ''; + } + + var re = /\r\n|\n\r|\n|\r/g; + var lines = text.replace(re, "\n").split("\n"); + + for (var i = 0; i < lines.length; i++) + { + var output = ''; + var line = lines[i]; + + for (var c = 0; c < line.length; c++) + { + if (data.chars[line.charCodeAt(c)]) + { + output = output.concat(line[c]); + } + else + { + output = output.concat(replace); + } + } + + lines[i] = output; + } + + return lines.join("\n"); + +}; + +/** +* Renders text and updates it when needed. +* +* @method Phaser.BitmapText.prototype.updateText +* @private +*/ +Phaser.BitmapText.prototype.updateText = function () { + + var data = this._data.font; + + if (!data) + { + return; + } + + var text = this.text; + var scale = this._fontSize / data.size; + var lines = []; + + var y = 0; + + this.textWidth = 0; + + do + { + var line = this.scanLine(data, scale, text); + + line.y = y; + + lines.push(line); + + if (line.width > this.textWidth) + { + this.textWidth = line.width; + } + + y += (data.lineHeight * scale); + + text = text.substr(line.text.length + 1); + + } while (line.end === false); + + this.textHeight = y; + + var t = 0; + var align = 0; + var ax = this.textWidth * this.anchor.x; + var ay = this.textHeight * this.anchor.y; + + for (var i = 0; i < lines.length; i++) + { + var line = lines[i]; + + if (this._align === 'right') + { + align = this.textWidth - line.width; + } + else if (this._align === 'center') + { + align = (this.textWidth - line.width) / 2; + } + + for (var c = 0; c < line.text.length; c++) + { + var charCode = line.text.charCodeAt(c); + var charData = data.chars[charCode]; + + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + var g = this._glyphs[t]; + + if (g) + { + // Sprite already exists in the glyphs pool, so we'll reuse it for this letter + g.texture = charData.texture; + } + else + { + // We need a new sprite as the pool is empty or exhausted + g = new PIXI.Sprite(charData.texture); + g.name = line.text[c]; + this._glyphs.push(g); + } + + g.position.x = (line.chars[c] + align) - ax; + g.position.y = (line.y + (charData.yOffset * scale)) - ay; + + g.scale.set(scale); + g.tint = this.tint; + g.texture.requiresReTint = true; + g.cachedTint = 0xFFFFFF; + + if (!g.parent) + { + this.addChild(g); + } + + t++; + } + } + + // Remove unnecessary children + // This moves them from the display list (children array) but retains them in the _glyphs pool + for (i = t; i < this._glyphs.length; i++) + { + this.removeChild(this._glyphs[i]); + } + +}; + +/** +* If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of +* Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they +* still take up memory while sat in the glyphs pool waiting to be re-used in the future. +* +* If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool +* by calling this method. +* +* Calling this doesn't prevent you from increasing the length of the text again in the future. +* +* @method Phaser.BitmapText.prototype.purgeGlyphs +* @return {integer} The amount of glyphs removed from the pool. +*/ +Phaser.BitmapText.prototype.purgeGlyphs = function () { + + var len = this._glyphs.length; + var kept = []; + + for (var i = 0; i < this._glyphs.length; i++) + { + if (this._glyphs[i].parent !== this) + { + this._glyphs[i].destroy(); + } + else + { + kept.push(this._glyphs[i]); + } + } + + this._glyphs = []; + this._glyphs = kept; + + this.updateText(); + + return len - kept.length; + +}; + +/** +* Updates the transform of this object. +* +* @method Phaser.BitmapText.prototype.updateTransform +* @private +*/ +Phaser.BitmapText.prototype.updateTransform = function () { + + if (this.dirty || !this.anchor.equals(this._prevAnchor)) + { + this.updateText(); + this.dirty = false; + this._prevAnchor.copyFrom(this.anchor); + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/** +* @name Phaser.BitmapText#align +* @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'align', { + + get: function() { + return this._align; + }, + + set: function(value) { + + if (value !== this._align && (value === 'left' || value === 'center' || value === 'right')) + { + this._align = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#tint +* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'tint', { + + get: function() { + return this._tint; + }, + + set: function(value) { + + if (value !== this._tint) + { + this._tint = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#font +* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'font', { + + get: function() { + return this._font; + }, + + set: function(value) { + + if (value !== this._font) + { + this._font = value.trim(); + this._data = this.game.cache.getBitmapFont(this._font); + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#fontSize +* @property {number} fontSize - The size of the font in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { + + get: function() { + return this._fontSize; + }, + + set: function(value) { + + value = parseInt(value, 10); + + if (value !== this._fontSize && value > 0) + { + this._fontSize = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#text +* @property {string} text - The text to be displayed by this BitmapText object. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.updateText(); + } + + } + +}); + +/** +* The maximum display width of this BitmapText in pixels. +* +* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped +* based on the last whitespace character found in the line. +* +* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. +* +* Disable maxWidth by setting the value to 0. +* +* @name Phaser.BitmapText#maxWidth +* @property {number} maxWidth - The maximum width of this BitmapText in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', { + + get: function() { + + return this._maxWidth; + + }, + + set: function(value) { + + if (value !== this._maxWidth) + { + this._maxWidth = value; + this.updateText(); + } + + } + +}); + +/** +* Enable or disable texture smoothing for this BitmapText. +* +* The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. +* +* Smoothing is enabled by default. +* +* @name Phaser.BitmapText#smoothed +* @property {boolean} smoothed +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', { + + get: function() { + + return !this._data.base.scaleMode; + + }, + + set: function(value) { + + if (value) + { + this._data.base.scaleMode = 0; + } + else + { + this._data.base.scaleMode = 1; + } + this._data.base.dirty(); + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont +* is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. +* +* @class Phaser.RetroFont +* @extends Phaser.RenderTexture +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {string} key - The font set graphic set as stored in the Game.Cache. +* @param {number} characterWidth - The width of each character in the font set. +* @param {number} characterHeight - The height of each character in the font set. +* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. +* @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. +* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. +* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { + + if (!game.cache.checkImageKey(key)) + { + return false; + } + + if (charsPerRow === undefined || charsPerRow === null) + { + charsPerRow = game.cache.getImage(key).width / characterWidth; + } + + /** + * @property {number} characterWidth - The width of each character in the font set. + */ + this.characterWidth = characterWidth; + + /** + * @property {number} characterHeight - The height of each character in the font set. + */ + this.characterHeight = characterHeight; + + /** + * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here. + */ + this.characterSpacingX = xSpacing || 0; + + /** + * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here. + */ + this.characterSpacingY = ySpacing || 0; + + /** + * @property {number} characterPerRow - The number of characters per row in the font set. + */ + this.characterPerRow = charsPerRow; + + /** + * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @readonly + */ + this.offsetX = xOffset || 0; + + /** + * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @readonly + */ + this.offsetY = yOffset || 0; + + /** + * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + */ + this.align = "left"; + + /** + * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) + * @default + */ + this.multiLine = false; + + /** + * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. + * @default + */ + this.autoUpperCase = true; + + /** + * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels. + * @default + */ + this.customSpacingX = 0; + + /** + * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels. + * @default + */ + this.customSpacingY = 0; + + /** + * If you need this RetroFont image to have a fixed width you can set the width in this value. + * If text is wider than the width specified it will be cropped off. + * @property {number} fixedWidth + */ + this.fixedWidth = 0; + + /** + * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font. + */ + this.fontSet = game.cache.getImage(key); + + /** + * @property {string} _text - The text of the font image. + * @private + */ + this._text = ''; + + /** + * @property {array} grabData - An array of rects for faster character pasting. + * @private + */ + this.grabData = []; + + /** + * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font. + */ + this.frameData = new Phaser.FrameData(); + + // Now generate our rects for faster copying later on + var currentX = this.offsetX; + var currentY = this.offsetY; + var r = 0; + + for (var c = 0; c < chars.length; c++) + { + var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight)); + + this.grabData[chars.charCodeAt(c)] = frame.index; + + r++; + + if (r === this.characterPerRow) + { + r = 0; + currentX = this.offsetX; + currentY += this.characterHeight + this.characterSpacingY; + } + else + { + currentX += this.characterWidth + this.characterSpacingX; + } + } + + game.cache.updateFrameData(key, this.frameData); + + /** + * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font. + * @readonly + */ + this.stamp = new Phaser.Image(game, 0, 0, key, 0); + + Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST); + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RETROFONT; + +}; + +Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype); +Phaser.RetroFont.prototype.constructor = Phaser.RetroFont; + +/** +* Align each line of multi-line text to the left. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_LEFT = "left"; + +/** +* Align each line of multi-line text to the right. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_RIGHT = "right"; + +/** +* Align each line of multi-line text in the center. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_CENTER = "center"; + +/** +* Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + +/** +* Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "; + +/** +* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789"; + +/** +* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789"; + +/** +* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' "; + +/** +* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39"; + +/** +* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!"; + +/** +* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"; + +/** +* If you need this RetroFont to have a fixed width and custom alignment you can set the width here. +* If text is wider than the width specified it will be cropped off. +* +* @method Phaser.RetroFont#setFixedWidth +* @memberof Phaser.RetroFont +* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. +* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +*/ +Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) { + + if (lineAlignment === undefined) { lineAlignment = 'left'; } + + this.fixedWidth = width; + this.align = lineAlignment; + +}; + +/** +* A helper function that quickly sets lots of variables at once, and then updates the text. +* +* @method Phaser.RetroFont#setText +* @memberof Phaser.RetroFont +* @param {string} content - The text of this sprite. +* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. +* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels. +* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels. +* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. +*/ +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; + } + +}; + +/** +* Updates the texture with the new text. +* +* @method Phaser.RetroFont#buildRetroFontText +* @memberof Phaser.RetroFont +*/ +Phaser.RetroFont.prototype.buildRetroFontText = function () { + + var cx = 0; + var cy = 0; + + // Clears the textureBuffer + 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); + } + + // Loop through each line of text + for (var i = 0; i < lines.length; i++) + { + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + // This line of text is held in lines[i] - need to work out the alignment + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(lines[i], cx, cy, this.customSpacingX); + + cy += this.characterHeight + this.customSpacingY; + } + } + else + { + if (this.fixedWidth > 0) + { + this.resize(this.fixedWidth, this.characterHeight, true); + } + else + { + this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true); + } + + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(this._text, cx, 0, this.customSpacingX); + } + + this.requiresReTint = true; + +}; + +/** +* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. +* Used by getLine and getMultiLine +* +* @method Phaser.RetroFont#pasteLine +* @memberof Phaser.RetroFont +* @param {string} line - The single line of text to paste. +* @param {number} x - The x coordinate. +* @param {number} y - The y coordinate. +* @param {number} customSpacingX - Custom X spacing. +*/ +Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) { + + for (var c = 0; c < line.length; c++) + { + // If it's a space then there is no point copying, so leave a blank space + if (line.charAt(c) === " ") + { + x += this.characterWidth + customSpacingX; + } + else + { + // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it + if (this.grabData[line.charCodeAt(c)] >= 0) + { + this.stamp.frame = this.grabData[line.charCodeAt(c)]; + this.renderXY(this.stamp, x, y, false); + + x += this.characterWidth + customSpacingX; + + if (x > this.width) + { + break; + } + } + } + } +}; + +/** +* Works out the longest line of text in _text and returns its length +* +* @method Phaser.RetroFont#getLongestLine +* @memberof Phaser.RetroFont +* @return {number} The length of the longest line of text. +*/ +Phaser.RetroFont.prototype.getLongestLine = function () { + + var longestLine = 0; + + if (this._text.length > 0) + { + var lines = this._text.split("\n"); + + for (var i = 0; i < lines.length; i++) + { + if (lines[i].length > longestLine) + { + longestLine = lines[i].length; + } + } + } + + return longestLine; +}; + +/** +* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set. +* +* @method Phaser.RetroFont#removeUnsupportedCharacters +* @memberof Phaser.RetroFont +* @protected +* @param {boolean} [stripCR=true] - Should it strip carriage returns as well? +* @return {string} A clean version of the string. +*/ +Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) { + + var newString = ""; + + for (var c = 0; c < this._text.length; c++) + { + var aChar = this._text[c]; + var code = aChar.charCodeAt(0); + + if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n")) + { + newString = newString.concat(aChar); + } + } + + return newString; + +}; + +/** +* Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. +* Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. +* So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. +* +* @method Phaser.RetroFont#updateOffset +* @memberof Phaser.RetroFont +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont.prototype.updateOffset = function (x, y) { + + if (this.offsetX === x && this.offsetY === y) + { + return; + } + + var diffX = x - this.offsetX; + var diffY = y - this.offsetY; + + var frames = this.game.cache.getFrameData(this.stamp.key).getFrames(); + var i = frames.length; + + while (i--) + { + frames[i].x += diffX; + frames[i].y += diffY; + } + + this.buildRetroFontText(); + +}; + +/** +* @name Phaser.RetroFont#text +* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. +*/ +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(); + } + + } + +}); + +/** +* @name Phaser.RetroFont#smoothed +* @property {boolean} smoothed - Sets if the stamp is smoothed or not. +*/ +Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", { + + get: function () { + + return this.stamp.smoothed; + + }, + + set: function (value) { + + this.stamp.smoothed = value; + this.buildRetroFontText(); + + } + +}); + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @author Rovanion Luckey +* @copyright 2016 Photon Storm Ltd, Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Rope is a Sprite that has a repeating texture. +* +* The texture will automatically wrap on the edges as it moves. +* +* Please note that Ropes cannot have an input handler. +* +* @class Phaser.Rope +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Rope at. +* @param {number} y - The y coordinate (in world space) to position the Rope at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {Array} points - An array of {Phaser.Point}. +*/ +Phaser.Rope = function (game, x, y, key, frame, points) { + + this.points = points || []; + this._hasUpdateAnimation = false; + this._updateAnimationCallback = null; + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROPE; + + PIXI.DisplayObjectContainer.call(this); + + this.texture = Phaser.Cache.DEFAULT; + + // set up the main bits.. + this.uvs = new Float32Array([0, 1, + 1, 1, + 1, 0, + 0, 1]); + + this.vertices = new Float32Array([0, 0, + 100, 0, + 100, 100, + 0, 100]); + + this.colors = new Float32Array([1, 1, 1, 1]); + + this.indices = new Uint16Array([0, 1, 2, 3]); + + if (points) + { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + /** + * Whether the strip is dirty or not + * + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. + * + * @property canvasPadding + * @type Number + */ + this.canvasPadding = 0; + + this.drawMode = Phaser.Rope.TRIANGLE_STRIP; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + + this.refresh(); + +}; + +Phaser.Rope.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Rope.prototype.constructor = Phaser.Rope; + +Phaser.Component.Core.install.call(Phaser.Rope.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +Phaser.Rope.TRIANGLE_STRIP = 0; +Phaser.Rope.TRIANGLES = 1; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Rope#preUpdate +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override and use this function in your own custom objects to handle any update requirements you may have. +* +* @method Phaser.Rope#update +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.update = function() { + + if (this._hasUpdateAnimation) + { + this.updateAnimation.call(this); + } + +}; + +/** +* Resets the Rope. This places the Rope at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the Rope has a physics body that too is reset. +* +* @method Phaser.Rope#reset +* @memberof Phaser.Rope +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.Rope} This instance. +*/ +Phaser.Rope.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + return this; + +}; + +/* +* Refreshes the rope texture and UV coordinates. +* +* @method Phaser.Rope#refresh +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.refresh = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + this.count -= 0.2; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + var index; + var amount; + + for (var i = 1; i < total; i++) + { + index = i * 4; + + // time to do some smart drawing! + amount = i / (total - 1); + + if (i % 2) + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + else + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + +}; + +/* +* Updates the Ropes transform ready for rendering. +* +* @method Phaser.Rope#updateTransform +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.updateTransform = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var lastPoint = points[0]; + var nextPoint; + var perp = { x:0, y:0 }; + + this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + var point; + var index; + var ratio; + var perpLength; + var num; + + for (var i = 0; i < total; i++) + { + point = points[i]; + index = i * 4; + + if(i < points.length - 1) + { + nextPoint = points[i + 1]; + } + else + { + nextPoint = point; + } + + perp.y = -(nextPoint.x - lastPoint.x); + perp.x = nextPoint.y - lastPoint.y; + + ratio = (1 - (i / (total - 1))) * 10; + + if (ratio > 1) + { + ratio = 1; + } + + perpLength = Math.sqrt((perp.x * perp.x) + (perp.y * perp.y)); + num = this.texture.height / 2; + perp.x /= perpLength; + perp.y /= perpLength; + + perp.x *= num; + perp.y *= num; + + vertices[index] = point.x + perp.x; + vertices[index + 1] = point.y + perp.y; + vertices[index + 2] = point.x - perp.x; + vertices[index + 3] = point.y - perp.y; + + lastPoint = point; + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/* +* Sets the Texture this Rope uses for rendering. +* +* @method Phaser.Rope#setTexture +* @memberof Phaser.Rope +* @param {Texture} texture - The texture that will be used. +*/ +Phaser.Rope.prototype.setTexture = function (texture) { + + this.texture = texture; + +}; + +/* +* Renders the Rope to WebGL. +* +* @private +* @method Phaser.Rope#_renderWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + renderSession.spriteBatch.stop(); + + if (!this._vertexBuffer) + { + this._initWebGL(renderSession); + } + + renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader); + + this._renderStrip(renderSession); + + renderSession.spriteBatch.start(); + +}; + +/* +* Builds the Strip. +* +* @private +* @method Phaser.Rope#_initWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._initWebGL = function (renderSession) { + + // build the strip! + var gl = renderSession.gl; + + this._vertexBuffer = gl.createBuffer(); + this._indexBuffer = gl.createBuffer(); + this._uvBuffer = gl.createBuffer(); + this._colorBuffer = gl.createBuffer(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + +}; + +/* +* Renders the Strip to WebGL. +* +* @private +* @method Phaser.Rope#_renderStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderStrip = function (renderSession) { + + var gl = renderSession.gl; + var projection = renderSession.projection; + var offset = renderSession.offset; + var shader = renderSession.shaderManager.stripShader; + + var drawMode = (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + renderSession.blendModeManager.setBlendMode(this.blendMode); + + // set uniforms + gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true)); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + gl.uniform1f(shader.alpha, this.worldAlpha); + + if (!this.dirty) + { + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + } + else + { + this.dirty = false; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + } + + gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0); + +}; + +/* +* Renders the Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvas +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvas = function (renderSession) { + + var context = renderSession.context; + + var transform = this.worldTransform; + + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + if (renderSession.roundPixels) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx, ty); + } + + if (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) + { + this._renderCanvasTriangleStrip(context); + } + else + { + this._renderCanvasTriangles(context); + } + +}; + +/* +* Renders a Triangle Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangleStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangleStrip = function (context) { + + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + + var length = vertices.length / 2; + + this.count++; + + for (var i = 0; i < length - 2; i++) + { + var index = i * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangles +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangles = function (context) { + + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + + var length = indices.length; + + this.count++; + + for (var i = 0; i < length; i += 3) + { + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasDrawTriangle +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { + + var textureSource = this.texture.baseTexture.source; + var textureWidth = this.texture.width; + var textureHeight = this.texture.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var u0 = uvs[index0] * textureWidth; + var u1 = uvs[index1] * textureWidth; + var u2 = uvs[index2] * textureWidth; + var v0 = uvs[index0 + 1] * textureHeight; + var v1 = uvs[index1 + 1] * textureHeight; + var v2 = uvs[index2 + 1] * textureHeight; + + if (this.canvasPadding > 0) + { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt((normX * normX) + (normY * normY)); + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2); + var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2); + var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2); + var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2); + var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2); + var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2); + var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2); + + context.transform( + deltaA / delta, + deltaD / delta, + deltaB / delta, + deltaE / delta, + deltaC / delta, + deltaF / delta); + + context.drawImage(textureSource, 0, 0); + context.restore(); + +}; + +/* +* Renders a flat strip. +* +* @method Phaser.Rope#renderStripFlat +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.renderStripFlat = function (strip) { + + var context = this.context; + var vertices = strip.vertices; + + var length = vertices.length / 2; + + this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; i++) + { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var x1 = vertices[index + 2]; + var x2 = vertices[index + 4]; + var y0 = vertices[index + 1]; + var y1 = vertices[index + 3]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + +}; + +/* +* Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Rope#getBounds +* @memberof Phaser.Rope +* @param {Matrix} matrix - The transformation matrix of the Sprite. +* @return {Rectangle} The framing rectangle. +*/ +Phaser.Rope.prototype.getBounds = function (matrix) { + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + var vertices = this.vertices; + + for (var i = 0; i < vertices.length; i += 2) + { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + if (minX === -Infinity || maxY === Infinity) + { + return PIXI.EmptyRectangle; + } + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // Store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* A Rope will call its updateAnimation function on each update loop if it has one. +* +* @name Phaser.Rope#updateAnimation +* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. +*/ +Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", { + + get: function () { + + return this._updateAnimation; + + }, + + set: function (value) { + + if (value && typeof value === 'function') + { + this._hasUpdateAnimation = true; + this._updateAnimation = value; + } + else + { + this._hasUpdateAnimation = false; + this._updateAnimation = null; + } + + } + +}); + +/** +* The segments that make up the rope body as an array of Phaser.Rectangles +* +* @name Phaser.Rope#segments +* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope +*/ +Object.defineProperty(Phaser.Rope.prototype, "segments", { + + get: function () { + + var segments = []; + var index, x1, y1, x2, y2, width, height, rect; + + for (var i = 0; i < this.points.length; i++) + { + index = i * 4; + + x1 = this.vertices[index] * this.scale.x; + y1 = this.vertices[index + 1] * this.scale.y; + x2 = this.vertices[index + 4] * this.scale.x; + y2 = this.vertices[index + 3] * this.scale.y; + + width = Phaser.Math.difference(x1, x2); + height = Phaser.Math.difference(y1, y2); + + x1 += this.world.x; + y1 += this.world.y; + rect = new Phaser.Rectangle(x1, y1, width, height); + segments.push(rect); + } + + return segments; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. +* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. +* +* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. +* +* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background +* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` +* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will +* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to +* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. +* +* An important note about texture dimensions: +* +* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be +* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two +* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and +* bottom of your frame. To avoid this ensure your textures are perfect powers of two. +* +* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However +* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive +* additional padding to enforce it to be so. +* +* @class Phaser.TileSprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate (in world space) to position the TileSprite at. +* @param {number} [y=0] - The y coordinate (in world space) to position the TileSprite at. +* @param {number} [width=256] - The width of the TileSprite. +* @param {number} [height=256] - The height of the TileSprite. +* @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. +* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.TileSprite = function (game, x, y, width, height, key, frame) { + + x = x || 0; + y = y || 0; + width = width || 256; + height = height || 256; + key = key || null; + frame = frame || null; + + PIXI.Sprite.call(this, new PIXI.Texture(Phaser.Cache.DEFAULT.baseTexture), width, height); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.TILESPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} _scroll - Internal cache var. + * @private + */ + this._scroll = new Phaser.Point(); + + /** + * @property {Phaser.Point} tileScale - The scale applied to the image being tiled. + */ + this.tileScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tileScaleOffset - The scale offset applied to the image being tiled. + */ + this.tileScaleOffset = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tilePosition - The offset position of the image being tiled. + */ + this.tilePosition = new Phaser.Point(); + + /** + * If enabled a green rectangle will be drawn behind the generated tiling texture, + * allowing you to visually debug the texture being used. + * + * @property {boolean} textureDebug + */ + this.textureDebug = false; + + /** + * The CanvasBuffer object that the tiled texture is drawn to. + * + * @property {PIXI.CanvasBuffer} canvasBuffer + */ + this.canvasBuffer = null; + + /** + * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. + * + * @property {PIXI.Texture} tilingTexture + */ + this.tilingTexture = null; + + /** + * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). + * + * @property {object} tilePattern + */ + this.tilePattern = null; + + /** + * If true the TileSprite will run `generateTexture` on its **next** render pass. + * This is set by the likes of Phaser.LoadTexture.setFrame. + * + * @property {boolean} refreshTexture + */ + this.refreshTexture = true; + + this.frameWidth = 0; + this.frameHeight = 0; + + this._width = width; + this._height = height; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.TileSprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.TileSprite.prototype.constructor = Phaser.TileSprite; + +Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'Smoothed' +]); + +Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TileSprite#preUpdate +* @memberof Phaser.TileSprite +* @return {boolean} +*/ +Phaser.TileSprite.prototype.preUpdate = function () { + + if (this._scroll.x !== 0) + { + this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed; + } + + if (this._scroll.y !== 0) + { + this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed; + } + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). +* The scroll speed is specified in pixels per second. +* A negative x value will scroll to the left. A positive x value will scroll to the right. +* A negative y value will scroll up. A positive y value will scroll down. +* +* @method Phaser.TileSprite#autoScroll +* @memberof Phaser.TileSprite +* @param {number} x - Horizontal scroll speed in pixels per second. +* @param {number} y - Vertical scroll speed in pixels per second. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.autoScroll = function (x, y) { + + this._scroll.set(x, y); + + return this; + +}; + +/** +* Stops an automatically scrolling TileSprite. +* +* @method Phaser.TileSprite#stopScroll +* @memberof Phaser.TileSprite +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.stopScroll = function () { + + this._scroll.set(0, 0); + + return this; + +}; + +/** +* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present +* and nulls its reference to game, freeing it up for garbage collection. +* +* @method Phaser.TileSprite#destroy +* @memberof Phaser.TileSprite +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.TileSprite.prototype.destroy = function (destroyChildren) { + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + + PIXI.Sprite.prototype.destroy.call(this); + + if (this.canvasBuffer) + { + this.canvasBuffer.destroy(); + this.canvasBuffer = null; + } + + this.tileScale = null; + this.tileScaleOffset = null; + this.tilePosition = null; + + if (this.tilingTexture) + { + this.tilingTexture.destroy(true); + this.tilingTexture = null; + } + +}; + +/** +* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the TileSprite has a physics body that too is reset. +* +* @method Phaser.TileSprite#reset +* @memberof Phaser.TileSprite +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + this.tilePosition.x = 0; + this.tilePosition.y = 0; + + return this; + +}; + +/** +* Changes the texture being rendered by this TileSprite. +* Causes a texture refresh to take place on the next render. +* +* @method Phaser.TileSprite#setTexture +* @memberof Phaser.TileSprite +* @param {PIXI.Texture} texture - The texture to apply to this TileSprite. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.setTexture = function (texture) { + + if (this.texture !== texture) + { + this.texture = texture; + this.refreshTexture = true; + this.cachedTint = 0xFFFFFF; + } + + return this; + +}; + +/** +* Renders the TileSprite using the WebGL Renderer. +* +* @private +* @method Phaser.TileSprite#_renderWebGL +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + 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.refreshTexture) + { + this.generateTilingTexture(true, renderSession); + + if (this.tilingTexture) + { + if (this.tilingTexture.needsUpdate) + { + this.tilingTexture.baseTexture.textureIndex = this.texture.baseTexture.textureIndex; + renderSession.renderer.updateTexture(this.tilingTexture.baseTexture); + this.tilingTexture.needsUpdate = false; + } + } + else + { + return; + } + } + + renderSession.spriteBatch.renderTilingSprite(this); + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + var restartBatch = false; + + if (this._filters) + { + restartBatch = true; + renderSession.spriteBatch.stop(); + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + if (!restartBatch) + { + renderSession.spriteBatch.stop(); + } + + renderSession.maskManager.popMask(this._mask, renderSession); + } + + if (restartBatch) + { + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the TileSprite using the Canvas Renderer. +* +* @private +* @method Phaser.TileSprite#_renderCanvas +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + var context = renderSession.context; + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + context.globalAlpha = this.worldAlpha; + + var wt = this.worldTransform; + var resolution = renderSession.resolution; + var tx = (wt.tx * resolution) + renderSession.shakeX; + var ty = (wt.ty * resolution) + renderSession.shakeY; + + context.setTransform(wt.a * resolution, wt.b * resolution, wt.c * resolution, wt.d * resolution, tx, ty); + + if (this.tint !== 0xFFFFFF && (this.texture.requiresReTint || this.cachedTint !== this.tint)) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + this.refreshTexture = true; + } + + if (this.refreshTexture) + { + this.generateTilingTexture(false, renderSession); + + if (this.tilingTexture) + { + this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat'); + } + else + { + return; + } + } + + var sessionBlendMode = renderSession.currentBlendMode; + + // Check blend mode + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + var tilePosition = this.tilePosition; + var tileScale = this.tileScale; + + tilePosition.x %= this.tilingTexture.baseTexture.width; + tilePosition.y %= this.tilingTexture.baseTexture.height; + + // Translate + context.scale(tileScale.x, tileScale.y); + context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height)); + + context.fillStyle = this.tilePattern; + + tx = -tilePosition.x; + ty = -tilePosition.y; + + var tw = this._width / tileScale.x; + var th = this._height / tileScale.y; + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + tx |= 0; + ty |= 0; + tw |= 0; + th |= 0; + } + + context.fillRect(tx, ty, tw, th); + + // Translate back again + context.scale(1 / tileScale.x, 1 / tileScale.y); + context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height)); + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + // Reset blend mode + if (sessionBlendMode !== this.blendMode) + { + renderSession.currentBlendMode = sessionBlendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode]; + } + +}; + +/** +* Override the Sprite method. +* +* @private +* @method Phaser.TileSprite#onTextureUpdate +* @memberof Phaser.TileSprite +*/ +Phaser.TileSprite.prototype.onTextureUpdate = function () { + + // overriding the sprite version of this! + +}; + +/** +* Internal method that generates a new tiling texture. +* +* @method Phaser.TileSprite#generateTilingTexture +* @memberof Phaser.TileSprite +* @param {boolean} forcePowerOfTwo - Whether we want to force the texture to be a power of two +*/ +Phaser.TileSprite.prototype.generateTilingTexture = function (forcePowerOfTwo) { + + if (!this.texture.baseTexture.hasLoaded) + { + return; + } + + var texture = this.texture; + var frame = texture.frame; + + var targetWidth = this._frame.sourceSizeW || this._frame.width; + var targetHeight = this._frame.sourceSizeH || this._frame.height; + + var dx = 0; + var dy = 0; + + if (this._frame.trimmed) + { + dx = this._frame.spriteSourceSizeX; + dy = this._frame.spriteSourceSizeY; + } + + if (forcePowerOfTwo) + { + targetWidth = Phaser.Math.getNextPowerOfTwo(targetWidth); + targetHeight = Phaser.Math.getNextPowerOfTwo(targetHeight); + } + + if (this.canvasBuffer) + { + this.canvasBuffer.resize(targetWidth, targetHeight); + this.tilingTexture.baseTexture.width = targetWidth; + this.tilingTexture.baseTexture.height = targetHeight; + this.tilingTexture.needsUpdate = true; + } + else + { + this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight); + this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas); + this.tilingTexture.isTiling = true; + this.tilingTexture.needsUpdate = true; + } + + if (this.textureDebug) + { + this.canvasBuffer.context.strokeStyle = '#00ff00'; + this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight); + } + + // If a sprite sheet we need this: + var w = texture.crop.width; + var h = texture.crop.height; + + if (w !== targetWidth || h !== targetHeight) + { + w = targetWidth; + h = targetHeight; + } + + var targetTexture = this.tintedTexture ? this.tintedTexture : texture.baseTexture.source; + + this.canvasBuffer.context.drawImage( + targetTexture, + texture.crop.x, + texture.crop.y, + texture.crop.width, + texture.crop.height, + dx, + dy, + w, + h + ); + + this.tileScaleOffset.x = frame.width / targetWidth; + this.tileScaleOffset.y = frame.height / targetHeight; + + this.refreshTexture = false; + + this.tilingTexture.baseTexture._powerOf2 = true; + +}; + +/** +* Returns the framing rectangle of the Tile Sprite. +* +* @method Phaser.TileSprite#getBounds +* @memberof Phaser.TileSprite +* @return {Phaser.Rectangle} The bounds of the Tile Sprite. +*/ +Phaser.TileSprite.prototype.getBounds = function () { + + var width = this._width; + var height = this._height; + + var w0 = width * (1 - this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1 - this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = (a * w1) + (c * h1) + tx; + var y1 = (d * h1) + (b * w1) + ty; + + var x2 = (a * w0) + (c * h1) + tx; + var y2 = (d * h1) + (b * w0) + ty; + + var x3 = (a * w0) + (c * h0) + tx; + var y3 = (d * h0) + (b * w0) + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // TODO: This is surely always undefined? As it's not set anywhere in the parent objects + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* The width of the sprite, setting this will actually modify the scale to achieve the value set +* +* @property width +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'width', { + + get: function () { + + return this._width; + + }, + + set: function (value) { + + this._width = value; + + } + +}); + +/** +* The height of the TilingSprite, setting this will actually modify the scale to achieve the value set +* +* @property height +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'height', { + + get: function () { + + return this._height; + + }, + + set: function (value) { + + this._height = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The CanvasPool is a global static object, that allows Phaser to recycle and pool Canvas DOM elements. +* +* @class Phaser.CanvasPool +* @static +*/ +Phaser.CanvasPool = { + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @method Phaser.CanvasPool.create + * @static + * @param {any} parent - The parent of the canvas element. + * @param {number} width - The width of the canvas element. + * @param {number} height - The height of the canvas element. + * @return {HTMLCanvasElement} The canvas element. + */ + create: function (parent, width, height) { + + var idx = Phaser.CanvasPool.getFirst(); + var canvas; + + if (idx === -1) + { + var container = { + parent: parent, + canvas: document.createElement('canvas') + }; + + Phaser.CanvasPool.pool.push(container); + + canvas = container.canvas; + } + else + { + Phaser.CanvasPool.pool[idx].parent = parent; + + canvas = Phaser.CanvasPool.pool[idx].canvas; + } + + if (width !== undefined) + { + canvas.width = width; + canvas.height = height; + } + + return canvas; + + }, + + /** + * Gets the first free canvas index from the pool. + * + * @static + * @method Phaser.CanvasPool.getFirst + * @return {number} + */ + getFirst: function () { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + return i; + } + } + + return -1; + + }, + + /** + * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.remove + * @param {any} parent - The parent of the canvas element. + */ + remove: function (parent) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent === parent) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Looks up a canvas based on its type, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.removeByCanvas + * @param {HTMLCanvasElement} canvas - The canvas element to remove. + */ + removeByCanvas: function (canvas) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].canvas === canvas) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Gets the total number of used canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getTotal + * @return {number} The number of in-use (parented) canvas elements in the pool. + */ + getTotal: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent) + { + c++; + } + } + + return c; + + }, + + /** + * Gets the total number of free canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getFree + * @return {number} The number of free (un-parented) canvas elements in the pool. + */ + getFree: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + c++; + } + } + + return c; + + }, + + + /** + * Prints in-use, free, and total counts to console.log. + * + * @static + * @method Phaser.CanvasPool.log + */ + log: function () { + + console.log('CanvasPool: %s used, %s free, %s total', this.getTotal(), this.getFree(), this.pool.length); + + } + +}; + +/** + * The pool into which the canvas elements are placed. + * + * @property pool + * @type Array + * @static + */ +Phaser.CanvasPool.pool = []; + + +/** + * The total number of canvas elements in the {@link Phaser.CanvasPool.pool pool}. + * + * @property length + * @type number + * @static + * @readonly + */ +Object.defineProperty(Phaser.CanvasPool, 'length', { + get: function () { + return this.pool.length; + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}. +* +* This class represents a singleton object that can be accessed directly as `game.device` +* (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it. +* +* Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization +* occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase. +* Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal, e.g., +* +* ```javascript +* Phaser.Device.onInitialized.add(function (device) { +* +* device.canvasBitBltShift = true; +* device.mspointer = false; +* +* }); +* +* var game = new Phaser.Game(); +* ``` +* +* When checking features using the exposed properties only the *truth-iness* of the value should be relied upon +* unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined` +* when indicating the lack of a feature. +* +* Uses elements from System.js by MrDoob and Modernizr +* +* @description +* It is not possible to instantiate the Device class manually. +* +* @class +* @protected +*/ +Phaser.Device = function () { + + /** + * The time the device became ready. + * @property {integer} deviceReadyAt + * @protected + */ + this.deviceReadyAt = 0; + + /** + * The time as which initialization has completed. + * @property {boolean} initialized + * @protected + */ + this.initialized = false; + + // Browser / Host / Operating System + + /** + * @property {boolean} desktop - Is running on a desktop? + * @default + */ + this.desktop = false; + + /** + * @property {boolean} iOS - Is running on iOS? + * @default + */ + this.iOS = false; + + /** + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @default + */ + this.iOSVersion = 0; + + /** + * @property {boolean} cocoonJS - Is the game running under CocoonJS? + * @default + */ + this.cocoonJS = false; + + /** + * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App? + * @default + */ + this.cocoonJSApp = false; + + /** + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @default + */ + this.cordova = false; + + /** + * @property {boolean} node - Is the game running under Node.js? + * @default + */ + this.node = false; + + /** + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @default + */ + this.nodeWebkit = false; + + /** + * @property {boolean} electron - Is the game running under GitHub Electron? + * @default + */ + this.electron = false; + + /** + * @property {boolean} ejecta - Is the game running under Ejecta? + * @default + */ + this.ejecta = false; + + /** + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @default + */ + this.crosswalk = false; + + /** + * @property {boolean} android - Is running on android? + * @default + */ + this.android = false; + + /** + * @property {boolean} chromeOS - Is running on chromeOS? + * @default + */ + this.chromeOS = false; + + /** + * @property {boolean} linux - Is running on linux? + * @default + */ + this.linux = false; + + /** + * @property {boolean} macOS - Is running on macOS? + * @default + */ + this.macOS = false; + + /** + * @property {boolean} windows - Is running on windows? + * @default + */ + this.windows = false; + + /** + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @default + */ + this.windowsPhone = false; + + // Features + + /** + * @property {boolean} canvas - Is canvas available? + * @default + */ + this.canvas = false; + + /** + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @default + */ + this.canvasBitBltShift = null; + + /** + * If the browser isn't capable of handling tinting with alpha this will be false. + * @property {boolean} canHandleAlpha + * @default + */ + this.canHandleAlpha = false; + + /** + * Whether or not the {@link http://caniuse.com/#feat=canvas-blending Canvas Blend Modes} are supported, consequently the ability to tint using the multiply method. + * + * Expect `false` in Internet Explorer <= 11. + * + * @property {boolean} canUseMultiply + * @default + */ + this.canUseMultiply = false; + + /** + * @property {boolean} webGL - Is webGL available? + * @default + */ + this.webGL = false; + + /** + * @property {boolean} file - Is file available? + * @default + */ + this.file = false; + + /** + * @property {boolean} fileSystem - Is fileSystem available? + * @default + */ + this.fileSystem = false; + + /** + * @property {boolean} localStorage - Is localStorage available? + * @default + */ + this.localStorage = false; + + /** + * @property {boolean} worker - Is worker available? + * @default + */ + this.worker = false; + + /** + * @property {boolean} css3D - Is css3D available? + * @default + */ + this.css3D = false; + + /** + * @property {boolean} pointerLock - Is Pointer Lock available? + * @default + */ + this.pointerLock = false; + + /** + * @property {boolean} typedArray - Does the browser support TypedArrays? + * @default + */ + this.typedArray = false; + + /** + * @property {boolean} vibration - Does the device support the Vibration API? + * @default + */ + this.vibration = false; + + /** + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @default + */ + this.getUserMedia = true; + + /** + * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true) + * @default + */ + this.quirksMode = false; + + // Input + + /** + * @property {boolean} touch - Is touch available? + * @default + */ + this.touch = false; + + /** + * @property {boolean} mspointer - Is mspointer available? + * @default + */ + this.mspointer = false; + + /** + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @default + * @protected + */ + this.wheelEvent = null; + + // Browser + + /** + * @property {boolean} arora - Set to true if running in Arora. + * @default + */ + this.arora = false; + + /** + * @property {boolean} chrome - Set to true if running in Chrome. + * @default + */ + this.chrome = false; + + /** + * @property {number} chromeVersion - If running in Chrome this will contain the major version number. + * @default + */ + this.chromeVersion = 0; + + /** + * @property {boolean} epiphany - Set to true if running in Epiphany. + * @default + */ + this.epiphany = false; + + /** + * @property {boolean} firefox - Set to true if running in Firefox. + * @default + */ + this.firefox = false; + + /** + * @property {number} firefoxVersion - If running in Firefox this will contain the major version number. + * @default + */ + this.firefoxVersion = 0; + + /** + * @property {boolean} ie - Set to true if running in Internet Explorer. + * @default + */ + this.ie = false; + + /** + * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. + * @default + */ + this.ieVersion = 0; + + /** + * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+) + * @default + */ + this.trident = false; + + /** + * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx} + * @default + */ + this.tridentVersion = 0; + + /** + * @property {boolean} edge - Set to true if running in Microsoft Edge browser. + * @default + */ + this.edge = false; + + /** + * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. + * @default + */ + this.mobileSafari = false; + + /** + * @property {boolean} midori - Set to true if running in Midori. + * @default + */ + this.midori = false; + + /** + * @property {boolean} opera - Set to true if running in Opera. + * @default + */ + this.opera = false; + + /** + * @property {boolean} safari - Set to true if running in Safari. + * @default + */ + this.safari = false; + + /** + * @property {number} safariVersion - If running in Safari this will contain the major version number. + * @default + */ + this.safariVersion = 0; + + /** + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @default + */ + this.webApp = false; + + /** + * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle) + * @default + */ + this.silk = false; + + // Audio + + /** + * @property {boolean} audioData - Are Audio tags available? + * @default + */ + this.audioData = false; + + /** + * @property {boolean} webAudio - Is the WebAudio API available? + * @default + */ + this.webAudio = false; + + /** + * @property {boolean} ogg - Can this device play ogg files? + * @default + */ + this.ogg = false; + + /** + * @property {boolean} opus - Can this device play opus files? + * @default + */ + this.opus = false; + + /** + * @property {boolean} mp3 - Can this device play mp3 files? + * @default + */ + this.mp3 = false; + + /** + * @property {boolean} wav - Can this device play wav files? + * @default + */ + this.wav = false; + + /** + * Can this device play m4a files? + * @property {boolean} m4a - True if this device can play m4a files. + * @default + */ + this.m4a = false; + + /** + * @property {boolean} webm - Can this device play webm files? + * @default + */ + this.webm = false; + + /** + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @default + */ + this.dolby = false; + + // Video + + /** + * @property {boolean} oggVideo - Can this device play ogg video files? + * @default + */ + this.oggVideo = false; + + /** + * @property {boolean} h264Video - Can this device play h264 mp4 video files? + * @default + */ + this.h264Video = false; + + /** + * @property {boolean} mp4Video - Can this device play h264 mp4 video files? + * @default + */ + this.mp4Video = false; + + /** + * @property {boolean} webmVideo - Can this device play webm video files? + * @default + */ + this.webmVideo = false; + + /** + * @property {boolean} vp9Video - Can this device play vp9 video files? + * @default + */ + this.vp9Video = false; + + /** + * @property {boolean} hlsVideo - Can this device play hls video files? + * @default + */ + this.hlsVideo = false; + + // Device + + /** + * @property {boolean} iPhone - Is running on iPhone? + * @default + */ + this.iPhone = false; + + /** + * @property {boolean} iPhone4 - Is running on iPhone4? + * @default + */ + this.iPhone4 = false; + + /** + * @property {boolean} iPad - Is running on iPad? + * @default + */ + this.iPad = false; + + // Device features + + /** + * @property {number} pixelRatio - PixelRatio of the host device? + * @default + */ + this.pixelRatio = 0; + + /** + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @default + */ + this.littleEndian = false; + + /** + * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`. + * @default + */ + this.LITTLE_ENDIAN = false; + + /** + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @default + */ + this.support32bit = false; + + /** + * @property {boolean} fullscreen - Does the browser support the Full Screen API? + * @default + */ + this.fullscreen = false; + + /** + * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it. + * @default + */ + this.requestFullscreen = ''; + + /** + * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @default + */ + this.cancelFullscreen = ''; + + /** + * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @default + */ + this.fullscreenKeyboard = false; + +}; + +// Device is really a singleton/static entity; instantiate it +// and add new methods directly sans-prototype. +Phaser.Device = new Phaser.Device(); + +/** +* This signal is dispatched after device initialization occurs but before any of the ready +* callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked. +* +* Local "patching" for a particular device can/should be done in this event. +* +* _Note_: This signal is removed after the device has been readied; if a handler has not been +* added _before_ `new Phaser.Game(..)` it is probably too late. +* +* @type {?Phaser.Signal} +* @static +*/ +Phaser.Device.onInitialized = new Phaser.Signal(); + +/** +* Add a device-ready handler and ensure the device ready sequence is started. +* +* Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added, +* which is normally done automatically be calling `new Phaser.Game(..)`. +* +* The handler is invoked when the device is considered "ready", which may be immediately +* if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}. +* +* @method +* @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. +* @param {object} [context] - Context in which to invoke the handler +* @param {boolean} [nonPrimer=false] - If true the device ready check will not be started. +*/ +Phaser.Device.whenReady = function (callback, context, nonPrimer) { + + var readyCheck = this._readyCheck; + + if (this.deviceReadyAt || !readyCheck) + { + callback.call(context, this); + } + else if (readyCheck._monitor || nonPrimer) + { + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + } + else + { + readyCheck._monitor = readyCheck.bind(this); + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + + var cordova = typeof window.cordova !== 'undefined'; + var cocoonJS = navigator['isCocoonJS']; + + if (document.readyState === 'complete' || document.readyState === 'interactive') + { + // Why is there an additional timeout here? + window.setTimeout(readyCheck._monitor, 0); + } + else if (cordova && !cocoonJS) + { + // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + // Cordova, but NOT Cocoon? + document.addEventListener('deviceready', readyCheck._monitor, false); + } + else + { + document.addEventListener('DOMContentLoaded', readyCheck._monitor, false); + window.addEventListener('load', readyCheck._monitor, false); + } + } + +}; + +/** +* Internal method used for checking when the device is ready. +* This function is removed from Phaser.Device when the device becomes ready. +* +* @method +* @private +*/ +Phaser.Device._readyCheck = function () { + + var readyCheck = this._readyCheck; + + if (!document.body) + { + window.setTimeout(readyCheck._monitor, 20); + } + else if (!this.deviceReadyAt) + { + this.deviceReadyAt = Date.now(); + + document.removeEventListener('deviceready', readyCheck._monitor); + document.removeEventListener('DOMContentLoaded', readyCheck._monitor); + window.removeEventListener('load', readyCheck._monitor); + + this._initialize(); + this.initialized = true; + + this.onInitialized.dispatch(this); + + var item; + while ((item = readyCheck._queue.shift())) + { + var callback = item[0]; + var context = item[1]; + callback.call(context, this); + } + + // Remove no longer useful methods and properties. + this._readyCheck = null; + this._initialize = null; + this.onInitialized = null; + } + +}; + +/** +* Internal method to initialize the capability checks. +* This function is removed from Phaser.Device once the device is initialized. +* +* @method +* @private +*/ +Phaser.Device._initialize = function () { + + var device = this; + + /** + * Check which OS is game running on. + */ + function _checkOS () { + + var ua = navigator.userAgent; + + if (/Playstation Vita/.test(ua)) + { + device.vita = true; + } + else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua)) + { + device.kindle = true; + // This will NOT detect early generations of Kindle Fire, I think there is no reliable way... + // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true" + } + else if (/Android/.test(ua)) + { + device.android = true; + } + else if (/CrOS/.test(ua)) + { + device.chromeOS = true; + } + else if (/iP[ao]d|iPhone/i.test(ua)) + { + device.iOS = true; + (navigator.appVersion).match(/OS (\d+)/); + device.iOSVersion = parseInt(RegExp.$1, 10); + } + else if (/Linux/.test(ua)) + { + device.linux = true; + } + else if (/Mac OS/.test(ua)) + { + device.macOS = true; + } + else if (/Windows/.test(ua)) + { + device.windows = true; + } + + if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua)) + { + device.android = false; + device.iOS = false; + device.macOS = false; + device.windows = true; + device.windowsPhone = true; + } + + var silk = /Silk/.test(ua); // detected in browsers + + if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS) + { + device.desktop = true; + } + + // Windows Phone / Table reset + if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) + { + device.desktop = false; + } + + } + + /** + * Checks if the browser correctly supports putImageData alpha channels. + * If the browser isn't capable of handling tinting with alpha, `Device.canHandleAlpha` will be false. + * Also checks whether the Canvas BlendModes are supported by the current browser for drawImage. + */ + function _checkCanvasFeatures () { + + var canvas = Phaser.CanvasPool.create(this, 6, 1); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgba(10, 20, 30, 0.5)'; + + // Draw a single pixel + context.fillRect(0, 0, 1, 1); + + // Get the color values + var s1 = context.getImageData(0, 0, 1, 1); + + if (s1) + { + // Plot them to x2 + context.putImageData(s1, 1, 0); + + // Get those values + var s2 = context.getImageData(1, 0, 1, 1); + + // Compare and set + device.canHandleAlpha = ( + s2.data[0] === s1.data[0] && + s2.data[1] === s1.data[1] && + s2.data[2] === s1.data[2] && + s2.data[3] === s1.data[3] + ); + } + + // Checks whether the Canvas BlendModes are supported by the current browser for drawImage. + context.globalCompositeOperation = 'multiply'; + device.canUseMultiply = (context.globalCompositeOperation === 'multiply'); + + Phaser.CanvasPool.removeByCanvas(canvas); + + PIXI.CanvasTinter.tintMethod = (device.canUseMultiply) ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel; + + } + + /** + * Check HTML5 features of the host environment. + */ + function _checkFeatures () { + + device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS; + + try { + device.localStorage = !!localStorage.getItem; + } catch (error) { + device.localStorage = false; + } + + device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; + device.fileSystem = !!window['requestFileSystem']; + + device.webGL = !!window.WebGLRenderingContext; + + device.worker = !!window['Worker']; + + device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; + + device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL; + + // Older versions of firefox (< 21) apparently claim support but user media does not actually work + if (device.firefox && device.firefoxVersion < 21) + { + device.getUserMedia = false; + } + + // TODO: replace canvasBitBltShift detection with actual feature check + + // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it + // is safer to not try and use the fast copy-over method. + if (!device.iOS && (device.ie || device.firefox || device.chrome)) + { + device.canvasBitBltShift = true; + } + + // Known not to work + if (device.safari || device.mobileSafari) + { + device.canvasBitBltShift = false; + } + + } + + /** + * Checks/configures various input. + */ + function _checkInput () { + + if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1)) + { + device.touch = true; + } + + if (window.PointerEvent || window.MSPointerEvent || window.navigator.msPointerEnabled || window.navigator.pointerEnabled) + { + device.mspointer = true; + } + + if (!device.cocoonJS) + { + // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel + if ('onwheel' in window || (device.ie && 'WheelEvent' in window)) + { + // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ + device.wheelEvent = 'wheel'; + } + else if ('onmousewheel' in window) + { + // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. + device.wheelEvent = 'mousewheel'; + } + else if (device.firefox && 'MouseScrollEvent' in window) + { + // FF prior to 17. This should probably be scrubbed. + device.wheelEvent = 'DOMMouseScroll'; + } + } + + } + + /** + * Checks for support of the Full Screen API. + */ + function _checkFullScreenSupport () { + + var fs = [ + 'requestFullscreen', + 'requestFullScreen', + 'webkitRequestFullscreen', + 'webkitRequestFullScreen', + 'msRequestFullscreen', + 'msRequestFullScreen', + 'mozRequestFullScreen', + 'mozRequestFullscreen' + ]; + + var element = document.createElement('div'); + + for (var i = 0; i < fs.length; i++) + { + if (element[fs[i]]) + { + device.fullscreen = true; + device.requestFullscreen = fs[i]; + break; + } + } + + var cfs = [ + 'cancelFullScreen', + 'exitFullscreen', + 'webkitCancelFullScreen', + 'webkitExitFullscreen', + 'msCancelFullScreen', + 'msExitFullscreen', + 'mozCancelFullScreen', + 'mozExitFullscreen' + ]; + + if (device.fullscreen) + { + for (var i = 0; i < cfs.length; i++) + { + if (document[cfs[i]]) + { + device.cancelFullscreen = cfs[i]; + break; + } + } + } + + // Keyboard Input? + if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT']) + { + device.fullscreenKeyboard = true; + } + + } + + /** + * Check what browser is game running in. + */ + function _checkBrowser () { + + var ua = navigator.userAgent; + + if (/Arora/.test(ua)) + { + device.arora = true; + } + else if (/Edge\/\d+/.test(ua)) + { + device.edge = true; + } + else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.chrome = true; + device.chromeVersion = parseInt(RegExp.$1, 10); + } + else if (/Epiphany/.test(ua)) + { + device.epiphany = true; + } + else if (/Firefox\D+(\d+)/.test(ua)) + { + device.firefox = true; + device.firefoxVersion = parseInt(RegExp.$1, 10); + } + else if (/AppleWebKit/.test(ua) && device.iOS) + { + device.mobileSafari = true; + } + else if (/MSIE (\d+\.\d+);/.test(ua)) + { + device.ie = true; + device.ieVersion = parseInt(RegExp.$1, 10); + } + else if (/Midori/.test(ua)) + { + device.midori = true; + } + else if (/Opera/.test(ua)) + { + device.opera = true; + } + else if (/Safari\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.safari = true; + + if (/Version\/(\d+)\./.test(ua)) + { + device.safariVersion = parseInt(RegExp.$1, 10); + } + } + else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua)) + { + device.ie = true; + device.trident = true; + device.tridentVersion = parseInt(RegExp.$1, 10); + device.ieVersion = parseInt(RegExp.$3, 10); + } + + // Silk gets its own if clause because its ua also contains 'Safari' + if (/Silk/.test(ua)) + { + device.silk = true; + } + + // WebApp mode in iOS + if (navigator['standalone']) + { + device.webApp = true; + } + + if (typeof window.cordova !== 'undefined') + { + device.cordova = true; + } + + if (typeof process !== 'undefined' && typeof require !== 'undefined') + { + device.node = true; + } + + if (device.node && typeof process.versions === 'object') + { + device.nodeWebkit = !!process.versions['node-webkit']; + + device.electron = !!process.versions.electron; + } + + if (navigator['isCocoonJS']) + { + device.cocoonJS = true; + } + + if (device.cocoonJS) + { + try { + device.cocoonJSApp = (typeof CocoonJS !== 'undefined'); + } + catch(error) + { + device.cocoonJSApp = false; + } + } + + if (typeof window.ejecta !== 'undefined') + { + device.ejecta = true; + } + + if (/Crosswalk/.test(ua)) + { + device.crosswalk = true; + } + + } + + /** + * Check video support. + */ + function _checkVideo () { + + var videoElement = document.createElement("video"); + var result = false; + + try { + if (result = !!videoElement.canPlayType) + { + if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) + { + device.oggVideo = true; + } + + if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + device.h264Video = true; + device.mp4Video = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) + { + device.webmVideo = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) + { + device.vp9Video = true; + } + + if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + device.hlsVideo = true; + } + } + } catch (e) {} + } + + /** + * Check audio support. + */ + function _checkAudio () { + + device.audioData = !!(window['Audio']); + device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); + var audioElement = document.createElement('audio'); + var result = false; + + try { + if (result = !!audioElement.canPlayType) + { + if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) + { + device.ogg = true; + } + + if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) + { + device.opus = true; + } + + if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) + { + device.mp3 = true; + } + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) + { + device.wav = true; + } + + if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) + { + device.m4a = true; + } + + if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) + { + device.webm = true; + } + + if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') + { + if (device.edge) + { + device.dolby = true; + } + else if (device.safari && device.safariVersion >= 9) + { + if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)) + { + var major = parseInt(RegExp.$1, 10); + var minor = parseInt(RegExp.$2, 10); + + if ((major === 10 && minor >= 11) || major > 10) + { + device.dolby = true; + } + } + } + } + } + } catch (e) { + } + + } + + /** + * Check Little or Big Endian system. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsLittleEndian () { + + var a = new ArrayBuffer(4); + var b = new Uint8Array(a); + var c = new Uint32Array(a); + + b[0] = 0xa1; + b[1] = 0xb2; + b[2] = 0xc3; + b[3] = 0xd4; + + if (c[0] === 0xd4c3b2a1) + { + return true; + } + + if (c[0] === 0xa1b2c3d4) + { + return false; + } + else + { + // Could not determine endianness + return null; + } + + } + + /** + * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsUint8ClampedImageData () { + + if (Uint8ClampedArray === undefined) + { + return false; + } + + var elem = Phaser.CanvasPool.create(this, 1, 1); + var ctx = elem.getContext('2d'); + + if (!ctx) + { + return false; + } + + var image = ctx.createImageData(1, 1); + + Phaser.CanvasPool.remove(this); + + return image.data instanceof Uint8ClampedArray; + + } + + /** + * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess. + */ + function _checkDevice () { + + device.pixelRatio = window['devicePixelRatio'] || 1; + device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1; + device.iPhone4 = (device.pixelRatio === 2 && device.iPhone); + device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') !== -1; + + if (typeof Int8Array !== 'undefined') + { + device.typedArray = true; + } + else + { + device.typedArray = false; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') + { + device.littleEndian = _checkIsLittleEndian(); + device.LITTLE_ENDIAN = device.littleEndian; + } + + device.support32bit = (typeof ArrayBuffer !== 'undefined' && typeof Uint8ClampedArray !== 'undefined' && typeof Int32Array !== 'undefined' && device.littleEndian !== null && _checkIsUint8ClampedImageData()); + + navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; + + if (navigator.vibrate) + { + device.vibration = true; + } + + } + + /** + * Check whether the host environment support 3D CSS. + */ + function _checkCSS3D () { + + var el = document.createElement('p'); + var has3d; + var transforms = { + 'webkitTransform': '-webkit-transform', + 'OTransform': '-o-transform', + 'msTransform': '-ms-transform', + 'MozTransform': '-moz-transform', + 'transform': 'transform' + }; + + // Add it to the body to get the computed style. + document.body.insertBefore(el, null); + + for (var t in transforms) + { + if (el.style[t] !== undefined) + { + el.style[t] = "translate3d(1px,1px,1px)"; + has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]); + } + } + + document.body.removeChild(el); + device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none"); + + } + + // Run the checks + _checkOS(); + _checkBrowser(); + _checkAudio(); + _checkVideo(); + _checkCSS3D(); + _checkDevice(); + _checkFeatures(); + _checkCanvasFeatures(); + _checkFullScreenSupport(); + _checkInput(); + +}; + +/** +* Check whether the host environment can play audio. +* +* @method canPlayAudio +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.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 === 'opus' && this.opus) + { + return true; + } + else if (type === 'wav' && this.wav) + { + return true; + } + else if (type === 'webm' && this.webm) + { + return true; + } + else if (type === 'mp4' && this.dolby) + { + return true; + } + + return false; + +}; + +/** +* Check whether the host environment can play video files. +* +* @method canPlayVideo +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.canPlayVideo = function (type) { + + if (type === 'webm' && (this.webmVideo || this.vp9Video)) + { + return true; + } + else if (type === 'mp4' && (this.mp4Video || this.h264Video)) + { + return true; + } + else if ((type === 'ogg' || type === 'ogv') && this.oggVideo) + { + return true; + } + else if (type === 'mpeg' && this.hlsVideo) + { + return true; + } + + return false; + +}; + +/** + * Whether the device plays audio/video only in response to a user touch event. + * + * @method needsTouchUnlock + * @memberof Phaser.Device.prototype + * @return {boolean} + */ +Phaser.Device.needsTouchUnlock = function () { + return !!(!this.cocoonJS && (this.iOS || this.android) || (window.PhaserGlobal && window.PhaserGlobal.fakeiOSTouchLock)); +}; + +/** +* Detect if the host is a an Android Stock browser. +* This is available before the device "ready" event. +* +* Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. +* +* @example +* var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; +* +* @method isAndroidStockBrowser +* @memberof Phaser.Device.prototype +*/ +Phaser.Device.isAndroidStockBrowser = function () { + + var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/); + return matches && matches[1] < 537; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, +* including styles, offset and aspect ratio. +* +* @class Phaser.Canvas +* @static +*/ +Phaser.Canvas = { + + /** + * Creates a `canvas` DOM element. The element is not automatically added to the document. + * + * @method Phaser.Canvas.create + * @param {object} parent - The object that will own the canvas that is created. + * @param {number} [width=256] - The width of the canvas element. + * @param {number} [height=256] - The height of the canvas element.. + * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. + * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global. + * @return {HTMLCanvasElement} The newly created canvas element. + */ + create: function (parent, width, height, id, skipPool) { + + width = width || 256; + height = height || 256; + + var canvas = (skipPool) ? document.createElement('canvas') : Phaser.CanvasPool.create(parent, width, height); + + if (typeof id === 'string' && id !== '') + { + canvas.id = id; + } + + canvas.width = width; + canvas.height = height; + canvas.style.display = 'block'; + + return canvas; + + }, + + /** + * Sets the background color behind the canvas. This changes the canvas style property. + * + * @method Phaser.Canvas.setBackgroundColor + * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. + * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setBackgroundColor: function (canvas, color) { + + color = color || 'rgb(0,0,0)'; + + canvas.style.backgroundColor = color; + + return canvas; + + }, + + /** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @method Phaser.Canvas.setTouchAction + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @method Phaser.Canvas.setUserSelect + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. + * If no parent is given it will be added as a child of the document.body. + * + * @method Phaser.Canvas.addToDOM + * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM. + * @param {string|HTMLElement} parent - The DOM element to add the canvas to. + * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + addToDOM: function (canvas, parent, overflowHidden) { + + var target; + + if (overflowHidden === undefined) { overflowHidden = true; } + + if (parent) + { + if (typeof parent === 'string') + { + // hopefully an element ID + target = document.getElementById(parent); + } + else if (typeof parent === 'object' && parent.nodeType === 1) + { + // quick test for a HTMLelement + target = parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + target = document.body; + } + + if (overflowHidden && target.style) + { + target.style.overflow = 'hidden'; + } + + target.appendChild(canvas); + + return canvas; + + }, + + /** + * Removes the given canvas element from the DOM. + * + * @method Phaser.Canvas.removeFromDOM + * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM. + */ + removeFromDOM: function (canvas) { + + if (canvas.parentNode) + { + canvas.parentNode.removeChild(canvas); + } + + }, + + /** + * Sets the transform of the given canvas to the matrix values provided. + * + * @method Phaser.Canvas.setTransform + * @param {CanvasRenderingContext2D} context - The context to set the transform on. + * @param {number} translateX - The value to translate horizontally by. + * @param {number} translateY - The value to translate vertically by. + * @param {number} scaleX - The value to scale horizontally by. + * @param {number} scaleY - The value to scale vertically by. + * @param {number} skewX - The value to skew horizontaly by. + * @param {number} skewY - The value to skew vertically by. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) { + + context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); + + return context; + + }, + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @method Phaser.Canvas.setSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setSmoothingEnabled: function (context, value) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + context[s] = value; + } + + return context; + + }, + + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @method Phaser.Canvas.getSmoothingPrefix + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context. + */ + getSmoothingPrefix: function (context) { + + var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; + + for (var prefix in vendor) + { + var s = vendor[prefix] + 'mageSmoothingEnabled'; + + if (s in context) + { + return s; + } + } + + return null; + + }, + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * + * @method Phaser.Canvas.getSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to check for smoothing on. + * @return {boolean} True if the given context has image smoothing enabled, otherwise false. + */ + getSmoothingEnabled: function (context) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + return context[s]; + } + + }, + + /** + * Sets the CSS image-rendering property to `pixelated` or `crisp-edges`. + * This can remove blurring when the game canvas is scaled up. + * In some browsers this has no visible effect in WEBGL mode. + * Note that if this doesn't given the desired result then see the setSmoothingEnabled. + * + * @method Phaser.Canvas.setImageRenderingCrisp + * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. + * @return {HTMLCanvasElement} Returns the source canvas. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering + * @see https://caniuse.com/#feat=css-crisp-edges + */ + setImageRenderingCrisp: function (canvas) { + + var types = [ '-webkit-optimize-contrast', '-moz-crisp-edges', 'crisp-edges', 'pixelated' ]; + + for (var i = 0; i < types.length; i++) + { + canvas.style['image-rendering'] = types[i]; + } + + canvas.style.msInterpolationMode = 'nearest-neighbor'; + + return canvas; + + }, + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method Phaser.Canvas.setImageRenderingBicubic + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setImageRenderingBicubic: function (canvas) { + + canvas.style['image-rendering'] = 'auto'; + canvas.style.msInterpolationMode = 'bicubic'; + + return canvas; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Abstracts away the use of RAF or setTimeOut for the core game update loop. +* +* @class Phaser.RequestAnimationFrame +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available. +*/ +Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) { + + if (forceSetTimeOut === undefined) { forceSetTimeOut = false; } + + /** + * @property {Phaser.Game} game - The currently running game. + */ + this.game = game; + + /** + * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available. + */ + this.forceSetTimeOut = forceSetTimeOut; + + var vendors = [ + 'ms', + 'moz', + 'webkit', + 'o' + ]; + + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) + { + window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; + } + + /** + * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. + * @private + */ + this._isSetTimeOut = false; + + /** + * @property {function} _onLoop - The function called by the update. + * @private + */ + this._onLoop = null; + + /** + * @property {number} _timeOutID - The callback ID used when calling cancel. + * @private + */ + this._timeOutID = null; + +}; + +Phaser.RequestAnimationFrame.prototype = { + + /** + * Starts the requestAnimationFrame running or setTimeout if unavailable in browser + * @method Phaser.RequestAnimationFrame#start + */ + start: function () { + + this.isRunning = true; + + var _this = this; + + if (!window.requestAnimationFrame || this.forceSetTimeOut) + { + this._isSetTimeOut = true; + + this._onLoop = function () { + return _this.updateSetTimeout(); + }; + + this._timeOutID = window.setTimeout(this._onLoop, 0); + } + else + { + this._isSetTimeOut = false; + + this._onLoop = function (time) { + return _this.updateRAF(time); + }; + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the requestAnimationFrame + * @method Phaser.RequestAnimationFrame#updateRAF + */ + updateRAF: function (rafTime) { + + if (this.isRunning) + { + // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below) + this.game.update(Math.floor(rafTime)); + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the setTimeout. + * @method Phaser.RequestAnimationFrame#updateSetTimeout + */ + updateSetTimeout: function () { + + if (this.isRunning) + { + this.game.update(Date.now()); + + this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); + } + + }, + + /** + * Stops the requestAnimationFrame from running. + * @method Phaser.RequestAnimationFrame#stop + */ + stop: function () { + + if (this._isSetTimeOut) + { + clearTimeout(this._timeOutID); + } + else + { + window.cancelAnimationFrame(this._timeOutID); + } + + this.isRunning = false; + + }, + + /** + * Is the browser using setTimeout? + * @method Phaser.RequestAnimationFrame#isSetTimeOut + * @return {boolean} + */ + isSetTimeOut: function () { + return this._isSetTimeOut; + }, + + /** + * Is the browser using requestAnimationFrame? + * @method Phaser.RequestAnimationFrame#isRAF + * @return {boolean} + */ + isRAF: function () { + return (this._isSetTimeOut === false); + } + +}; + +Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of useful mathematical functions. +* +* These are normally accessed through `game.math`. +* +* @class Phaser.Math +* @static +* @see {@link Phaser.Utils} +* @see {@link Phaser.ArrayUtils} +*/ +Phaser.Math = { + + /** + * Twice PI. + * @property {number} Phaser.Math#PI2 + * @default ~6.283 + */ + PI2: Math.PI * 2, + + /** + * Half PI. + * @property {number} Phaser.Math#HALF_PI + * @default ~1.570 + */ + HALF_PI: Math.PI * 0.5, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#DEG_TO_RAD + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#RAD_TO_DEG + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * Convert degrees to radians. + * + * @method Phaser.Math#degToRad + * @param {number} degrees - Angle in degrees. + * @return {number} Angle in radians. + */ + degToRad: function (degrees) { + + return degrees * Phaser.Math.DEG_TO_RAD; + + }, + + /** + * Convert radians to degrees. + * + * @method Phaser.Math#radToDeg + * @param {number} radians - Angle in radians. + * @return {number} Angle in degrees + */ + radToDeg: function (radians) { + + return radians * Phaser.Math.RAD_TO_DEG; + + }, + + /** + * Given a number, this function returns the closest number that is a power of two. + * This function is from the Starling Framework. + * + * @method Phaser.Math#getNextPowerOfTwo + * @param {number} value - The value to get the closest power of two from. + * @return {number} The closest number that is a power of two. + */ + getNextPowerOfTwo: function (value) { + + if (value > 0 && (value & (value - 1)) === 0) + { + // http://goo.gl/D9kPj + return value; + } + else + { + var result = 1; + + while (result < value) + { + result <<= 1; + } + + return result; + } + + }, + + /** + * Checks if the given dimensions make a power of two texture. + * + * @method Phaser.Math#isPowerOfTwo + * @param {number} width - The width to check. + * @param {number} height - The height to check. + * @return {boolean} True if the width and height are a power of two. + */ + isPowerOfTwo: function (width, height) { + + return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); + + }, + + /** + * Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#random + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} A floating point number between min (inclusive) and max (exclusive). + */ + random: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + return (Math.random() * (max - min) + min); + + }, + + /** + * Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#between + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} An integer between min (inclusive) and max (inclusive). + */ + between: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + min = Math.ceil(min); + max = Math.floor(max); + + return Math.floor(Math.random() * (max - min + 1)) + min; + + }, + + /** + * Two number are fuzzyEqual if their difference is less than epsilon. + * + * @method Phaser.Math#fuzzyEqual + * @param {number} a - The first number to compare. + * @param {number} b - The second number to compare. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {boolean} True if |a-b|b+epsilon + */ + fuzzyGreaterThan: function (a, b, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return a > b - epsilon; + + }, + + /** + * Applies a fuzzy ceil to the given value. + * + * @method Phaser.Math#fuzzyCeil + * @param {number} val - The value to ceil. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} ceiling(val-epsilon) + */ + fuzzyCeil: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.ceil(val - epsilon); + + }, + + /** + * Applies a fuzzy floor to the given value. + * + * @method Phaser.Math#fuzzyFloor + * @param {number} val - The value to floor. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} floor(val+epsilon) + */ + fuzzyFloor: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.floor(val + epsilon); + + }, + + /** + * Averages all values passed to the function and returns the result. + * + * @method Phaser.Math#average + * @params {...number} The numbers to average + * @return {number} The average of all given values. + */ + average: function () { + + var sum = 0; + var len = arguments.length; + + for (var i = 0; i < len; i++) + { + sum += (+arguments[i]); + } + + return sum / len; + + }, + + /** + * @method Phaser.Math#shear + * @param {number} n + * @return {number} n mod 1 + */ + shear: function (n) { + + return n % 1; + + }, + + /** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. + * + * @method Phaser.Math#snapTo + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapTo: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.round(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. + * As will 14 snap to 10... but 16 will snap to 15. + * + * @method Phaser.Math#snapToFloor + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToFloor: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.floor(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. + * As will 14 will snap to 15... but 16 will snap to 20. + * + * @method Phaser.Math#snapToCeil + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToCeil: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.ceil(input / gap); + + return start + input; + + }, + + /** + * Round to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) === 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + * + * @method Phaser.Math#roundTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + roundTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.round(value * p) / p; + + }, + + /** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#floorTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + floorTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.floor(value * p) / p; + + }, + + /** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#ceilTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + ceilTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.ceil(value * p) / p; + + }, + + /** + * Rotates currentAngle towards targetAngle, taking the shortest rotation distance. + * The lerp argument is the amount to rotate by in this call. + * + * @method Phaser.Math#rotateToAngle + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * @return {number} The adjusted angle. + */ + rotateToAngle: function (currentAngle, targetAngle, lerp) { + + if (lerp === undefined) { lerp = 0.05; } + + if (currentAngle === targetAngle) + { + return currentAngle; + } + + if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (Phaser.Math.PI2 - lerp)) + { + currentAngle = targetAngle; + } + else + { + if (Math.abs(targetAngle - currentAngle) > Math.PI) + { + if (targetAngle < currentAngle) + { + targetAngle += Phaser.Math.PI2; + } + else + { + targetAngle -= Phaser.Math.PI2; + } + } + + if (targetAngle > currentAngle) + { + currentAngle += lerp; + } + else if (targetAngle < currentAngle) + { + currentAngle -= lerp; + } + } + + return currentAngle; + + }, + + /** + * Gets the shortest angle between `angle1` and `angle2`. + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method, and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * @method Phaser.Math#getShortestAngle + * @param {number} angle1 - The first angle. In the range -180 to 180. + * @param {number} angle2 - The second angle. In the range -180 to 180. + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ + getShortestAngle: function (angle1, angle2) { + + var difference = angle2 - angle1; + + if (difference === 0) + { + return 0; + } + + var times = Math.floor((difference - (-180)) / 360); + + return difference - (times * 360); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @method Phaser.Math#angleBetween + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetween: function (x1, y1, x2, y2) { + + return Math.atan2(y2 - y1, x2 - x1); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels + * down the screen. + * + * @method Phaser.Math#angleBetweenY + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetweenY: function (x1, y1, x2, y2) { + + return Math.atan2(x2 - x1, y2 - y1); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * @method Phaser.Math#angleBetweenPoints + * @param {Phaser.Point} point1 - The first point. + * @param {Phaser.Point} point2 - The second point. + * @return {number} The angle between the two points, in radians. + */ + angleBetweenPoints: function (point1, point2) { + + return Math.atan2(point2.y - point1.y, point2.x - point1.x); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * @method Phaser.Math#angleBetweenPointsY + * @param {Phaser.Point} point1 + * @param {Phaser.Point} point2 + * @return {number} The angle, in radians. + */ + angleBetweenPointsY: function (point1, point2) { + + return Math.atan2(point2.x - point1.x, point2.y - point1.y); + + }, + + /** + * Reverses an angle. + * @method Phaser.Math#reverseAngle + * @param {number} angleRad - The angle to reverse, in radians. + * @return {number} The reverse angle, in radians. + */ + reverseAngle: function (angleRad) { + + return this.normalizeAngle(angleRad + Math.PI, true); + + }, + + /** + * Normalizes an angle to the [0,2pi) range. + * @method Phaser.Math#normalizeAngle + * @param {number} angleRad - The angle to normalize, in radians. + * @return {number} The angle, fit within the [0,2pi] range, in radians. + */ + normalizeAngle: function (angleRad) { + + angleRad = angleRad % (2 * Math.PI); + return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI; + + }, + + /** + * Adds the given amount to the value, but never lets the value go over the specified maximum. + * + * @method Phaser.Math#maxAdd + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The new value. + */ + maxAdd: function (value, amount, max) { + + return Math.min(value + amount, max); + + }, + + /** + * Subtracts the given amount from the value, but never lets the value go below the specified minimum. + * + * @method Phaser.Math#minSub + * @param {number} value - The base value. + * @param {number} amount - The amount to subtract from the base value. + * @param {number} min - The minimum the value is allowed to be. + * @return {number} The new value. + */ + minSub: function (value, amount, min) { + + return Math.max(value - amount, min); + + }, + + /** + * Ensures that the value always stays between min and max, by wrapping the value around. + * + * If `max` is not larger than `min` the result is 0. + * + * @method Phaser.Math#wrap + * @param {number} value - The value to wrap. + * @param {number} min - The minimum the value is allowed to be. + * @param {number} max - The maximum the value is allowed to be, should be larger than `min`. + * @return {number} The wrapped value. + */ + wrap: function (value, min, max) { + + var range = max - min; + + if (range <= 0) + { + return 0; + } + + var result = (value - min) % range; + + if (result < 0) + { + result += range; + } + + return result + min; + + }, + + /** + * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. + * + * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. + * + * @method Phaser.Math#wrapValue + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The wrapped value. + */ + wrapValue: function (value, amount, max) { + + var diff; + value = Math.abs(value); + amount = Math.abs(amount); + max = Math.abs(max); + diff = (value + amount) % max; + + return diff; + + }, + + /** + * Returns true if the number given is odd. + * + * @method Phaser.Math#isOdd + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is odd. False if the given number is even. + */ + isOdd: function (n) { + + // Does not work with extremely large values + return !!(n & 1); + + }, + + /** + * Returns true if the number given is even. + * + * @method Phaser.Math#isEven + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is even. False if the given number is odd. + */ + isEven: function (n) { + + // Does not work with extremely large values + return !(n & 1); + + }, + + /** + * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.min` function when appropriate. + * + * @method Phaser.Math#min + * @return {number} The lowest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + 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; i < len; i++) + { + if (data[i] < data[min]) + { + min = i; + } + } + + return data[min]; + + }, + + /** + * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.max` function when appropriate. + * + * @method Phaser.Math#max + * @return {number} The largest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + max: function () { + + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + var data = arguments[0]; + } + else + { + var data = arguments; + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i] > data[max]) + { + max = i; + } + } + + return data[max]; + + }, + + /** + * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. + * It will find the lowest matching property value from the given objects. + * + * @method Phaser.Math#minProperty + * @return {number} The lowest value from those given. + */ + 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; i < len; i++) + { + if (data[i][property] < data[min][property]) + { + min = i; + } + } + + return data[min][property]; + + }, + + /** + * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. + * It will find the largest matching property value from the given objects. + * + * @method Phaser.Math#maxProperty + * @return {number} The largest value from those given. + */ + maxProperty: function (property) { + + if (arguments.length === 2 && typeof arguments[1] === 'object') + { + var data = arguments[1]; + } + else + { + var data = arguments.slice(1); + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i][property] > data[max][property]) + { + max = i; + } + } + + return data[max][property]; + + }, + + /** + * Keeps an angle value between -180 and +180; or -PI and PI if radians. + * + * @method Phaser.Math#wrapAngle + * @param {number} angle - The angle value to wrap + * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected. + * @return {number} The new angle value; will be the same as the input angle if it was within bounds. + */ + wrapAngle: function (angle, radians) { + + return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180); + + }, + + /** + * A Linear Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#linearInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + linearInterpolation: function (v, k) { + + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (k < 0) + { + return this.linear(v[0], v[1], f); + } + + if (k > 1) + { + return this.linear(v[m], v[m - 1], m - f); + } + + return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); + + }, + + /** + * A Bezier Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#bezierInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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; + + }, + + /** + * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#catmullRomInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + } + + }, + + /** + * Calculates a linear (interpolation) value over t. + * + * @method Phaser.Math#linear + * @param {number} p0 + * @param {number} p1 + * @param {number} t - A value between 0 and 1. + * @return {number} + */ + linear: function (p0, p1, t) { + + return (p1 - p0) * t + p0; + + }, + + /** + * @method Phaser.Math#bernstein + * @protected + * @param {number} n + * @param {number} i + * @return {number} + */ + bernstein: function (n, i) { + + return this.factorial(n) / this.factorial(i) / this.factorial(n - i); + + }, + + /** + * @method Phaser.Math#factorial + * @param {number} value - the number you want to evaluate + * @return {number} + */ + factorial: function (value) { + + if (value === 0) + { + return 1; + } + + var res = value; + + while(--value) + { + res *= value; + } + + return res; + + }, + + /** + * Calculates a catmum rom value. + * + * @method Phaser.Math#catmullRom + * @protected + * @param {number} p0 + * @param {number} p1 + * @param {number} p2 + * @param {number} p3 + * @param {number} t + * @return {number} + */ + catmullRom: function (p0, p1, p2, p3, t) { + + var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + + }, + + /** + * The absolute difference between two values. + * + * @method Phaser.Math#difference + * @param {number} a - The first value to check. + * @param {number} b - The second value to check. + * @return {number} The absolute difference between the two values. + */ + difference: function (a, b) { + + return Math.abs(a - b); + + }, + + /** + * Round to the next whole number _away_ from zero. + * + * @method Phaser.Math#roundAwayFromZero + * @param {number} value - Any number. + * @return {integer} The rounded value of that number. + */ + roundAwayFromZero: function (value) { + + // "Opposite" of truncate. + return (value > 0) ? Math.ceil(value) : Math.floor(value); + + }, + + /** + * Generate a sine and cosine table simultaneously and extremely quickly. + * The parameters allow you to specify the length, amplitude and frequency of the wave. + * This generator is fast enough to be used in real-time. + * Code based on research by Franky of scene.at + * + * @method Phaser.Math#sinCosGenerator + * @param {number} length - The length of the wave + * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} frequency - The frequency of the sine and cosine table data + * @return {{sin:number[], cos:number[]}} Returns the table data. + */ + sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) { + + if (sinAmplitude === undefined) { sinAmplitude = 1.0; } + if (cosAmplitude === undefined) { cosAmplitude = 1.0; } + if (frequency === undefined) { frequency = 1.0; } + + var sin = sinAmplitude; + var cos = cosAmplitude; + var frq = frequency * Math.PI / length; + + var cosTable = []; + var sinTable = []; + + for (var c = 0; c < length; c++) { + + cos -= sin * frq; + sin += cos * frq; + + cosTable[c] = cos; + sinTable[c] = sin; + + } + + return { sin: sinTable, cos: cosTable, length: length }; + + }, + + /** + * Returns the length of the hypotenuse connecting two segments of given lengths. + * + * @method Phaser.Math#hypot + * @param {number} a + * @param {number} b + * @return {number} The length of the hypotenuse connecting the given lengths. + */ + hypot: function (a, b) { + + return Math.sqrt(a * a + b * b); + + }, + + /** + * Returns the euclidian distance between the two given set of coordinates. + * + * @method Phaser.Math#distance + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance between the two sets of coordinates. + */ + distance: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Returns the euclidean distance squared between the two given set of + * coordinates (cuts out a square root operation before returning). + * + * @method Phaser.Math#distanceSq + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance squared between the two sets of coordinates. + */ + distanceSq: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return dx * dx + dy * dy; + + }, + + /** + * Returns the distance between the two given set of coordinates at the power given. + * + * @method Phaser.Math#distancePow + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} [pow=2] + * @return {number} The distance between the two sets of coordinates. + */ + distancePow: function (x1, y1, x2, y2, pow) { + + if (pow === undefined) { pow = 2; } + + return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); + + }, + + /** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @method Phaser.Math#clamp + * @param {float} v - The value to be clamped. + * @param {float} min - The minimum bounds. + * @param {float} max - The maximum bounds. + * @return {number} The clamped value. + */ + clamp: function (v, min, max) { + + if (v < min) + { + return min; + } + else if (max < v) + { + return max; + } + else + { + return v; + } + + }, + + /** + * Clamp `x` to the range `[a, Infinity)`. + * Roughly the same as `Math.max(x, a)`, except for NaN handling. + * + * @method Phaser.Math#clampBottom + * @param {number} x + * @param {number} a + * @return {number} + */ + clampBottom: function (x, a) { + + return x < a ? a : x; + + }, + + /** + * Checks if two values are within the given tolerance of each other. + * + * @method Phaser.Math#within + * @param {number} a - The first number to check + * @param {number} b - The second number to check + * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range. + * @return {boolean} True if a is <= tolerance of b. + * @see {@link Phaser.Math.fuzzyEqual} + */ + within: function (a, b, tolerance) { + + return (Math.abs(a - b) <= tolerance); + + }, + + /** + * Linear mapping from range to range + * + * @method Phaser.Math#mapLinear + * @param {number} x - The value to map + * @param {number} a1 - First endpoint of the range + * @param {number} a2 - Final endpoint of the range + * @param {number} b1 - First endpoint of the range + * @param {number} b2 - Final endpoint of the range + * @return {number} + */ + mapLinear: function (x, a1, a2, b1, b2) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + + }, + + /** + * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smoothstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smoothstep: function (x, min, max) { + + // Scale, bias and saturate x to 0..1 range + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + // Evaluate polynomial + return x * x * (3 - 2 * x); + + }, + + /** + * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smootherstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smootherstep: function (x, min, max) { + + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + return x * x * x * (x * (x * 6 - 15) + 10); + + }, + + /** + * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. + * + * This works differently from `Math.sign` for values of NaN and -0, etc. + * + * @method Phaser.Math#sign + * @param {number} x + * @return {integer} An integer in {-1, 0, 1} + */ + sign: function (x) { + + return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); + + }, + + /** + * Work out what percentage value `a` is of value `b` using the given base. + * + * @method Phaser.Math#percent + * @param {number} a - The value to work out the percentage for. + * @param {number} b - The value you wish to get the percentage of. + * @param {number} [base=0] - The base value. + * @return {number} The percentage a is of b, between 0 and 1. + */ + percent: function (a, b, base) { + + if (base === undefined) { base = 0; } + + if (a > b || base > b) + { + return 1; + } + else if (a < base || base > a) + { + return 0; + } + else + { + return (a - base) / b; + } + + } + +}; + +/* jshint noempty: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An extremely useful repeatable random data generator. +* +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. +* +* The random number genererator is based on the Alea PRNG, but is modified. +* - https://github.com/coverslide/node-alea +* - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror +* - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404) +* +* @class Phaser.RandomDataGenerator +* @constructor +* @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}). +*/ +Phaser.RandomDataGenerator = function (seeds) { + + if (seeds === undefined) { seeds = []; } + + /** + * @property {number} c - Internal var. + * @private + */ + this.c = 1; + + /** + * @property {number} s0 - Internal var. + * @private + */ + this.s0 = 0; + + /** + * @property {number} s1 - Internal var. + * @private + */ + this.s1 = 0; + + /** + * @property {number} s2 - Internal var. + * @private + */ + this.s2 = 0; + + if (typeof seeds === 'string') + { + this.state(seeds); + } + else + { + this.sow(seeds); + } + +}; + +Phaser.RandomDataGenerator.prototype = { + + /** + * Private random helper. + * + * @method Phaser.RandomDataGenerator#rnd + * @private + * @return {number} + */ + rnd: function () { + + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + + return this.s2; + }, + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.RandomDataGenerator#sow + * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used. + */ + sow: function (seeds) { + + // Always reset to default seed + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + this.c = 1; + + if (!seeds) + { + return; + } + + // Apply any seeds + for (var i = 0; i < seeds.length && (seeds[i] != null); i++) + { + var 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); + } + + }, + + /** + * Internal method that creates a seed hash. + * + * @method Phaser.RandomDataGenerator#hash + * @private + * @param {any} data + * @return {number} hashed value. + */ + hash: function (data) { + + var h, i, n; + n = 0xefc8249d; + data = data.toString(); + + for (i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } + + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + + }, + + /** + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#integer + * @return {number} A random integer between 0 and 2^32. + */ + integer: function() { + + return this.rnd.apply(this) * 0x100000000;// 2^32 + + }, + + /** + * Returns a random real number between 0 and 1. + * + * @method Phaser.RandomDataGenerator#frac + * @return {number} A random real number between 0 and 1. + */ + frac: function() { + + return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 + + }, + + /** + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#real + * @return {number} A random real number between 0 and 2^32. + */ + real: function() { + + return this.integer() + this.frac(); + + }, + + /** + * Returns a random integer between and including min and max. + * + * @method Phaser.RandomDataGenerator#integerInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + integerInRange: function (min, max) { + + return Math.floor(this.realInRange(0, max - min + 1) + min); + + }, + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.RandomDataGenerator#between + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + between: function (min, max) { + + return this.integerInRange(min, max); + + }, + + /** + * Returns a random real number between min and max. + * + * @method Phaser.RandomDataGenerator#realInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + realInRange: function (min, max) { + + return this.frac() * (max - min) + min; + + }, + + /** + * Returns a random real number between -1 and 1. + * + * @method Phaser.RandomDataGenerator#normal + * @return {number} A random real number between -1 and 1. + */ + normal: function () { + + return 1 - 2 * this.frac(); + + }, + + /** + * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 + * + * @method Phaser.RandomDataGenerator#uuid + * @return {string} A valid RFC4122 version4 ID hex string + */ + 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; + + }, + + /** + * Returns a random member of `array`. + * + * @method Phaser.RandomDataGenerator#pick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + pick: function (ary) { + + return ary[this.integerInRange(0, ary.length - 1)]; + + }, + + /** + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.RandomDataGenerator#sign + * @return {number} -1 or +1. + */ + sign: function () { + + return this.pick([-1, 1]); + + }, + + /** + * Returns a random member of `array`, favoring the earlier entries. + * + * @method Phaser.RandomDataGenerator#weightedPick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + weightedPick: function (ary) { + + return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)]; + + }, + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.RandomDataGenerator#timestamp + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random timestamp between min and max. + */ + timestamp: function (min, max) { + + return this.realInRange(min || 946684800000, max || 1577862000000); + + }, + + /** + * Returns a random angle between -180 and 180. + * + * @method Phaser.RandomDataGenerator#angle + * @return {number} A random number between -180 and 180. + */ + angle: function() { + + return this.integerInRange(-180, 180); + + }, + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.RandomDataGenerator#state + * @param {string} [state] - Generator state to be set. + * @return {string} The current state of the generator. + */ + state: function (state) { + + if (typeof state === 'string' && state.match(/^!rnd/)) + { + state = state.split(','); + + this.c = parseFloat(state[1]); + this.s0 = parseFloat(state[2]); + this.s1 = parseFloat(state[3]); + this.s2 = parseFloat(state[4]); + } + + return ['!rnd', this.c, this.s0, this.s1, this.s2].join(','); + + } + +}; + +Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator; + +/** + * @author Timo Hausmann + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** +* A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. +* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. +* Original version at https://github.com/timohausmann/quadtree-js/ +* +* @class Phaser.QuadTree +* @constructor +* @param {number} x - The top left coordinate of the quadtree. +* @param {number} y - The top left coordinate of the quadtree. +* @param {number} width - The width of the quadtree in pixels. +* @param {number} height - The height of the quadtree in pixels. +* @param {number} [maxObjects=10] - The maximum number of objects per node. +* @param {number} [maxLevels=4] - The maximum number of levels to iterate to. +* @param {number} [level=0] - Which level is this? +*/ +Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) { + + /** + * @property {number} maxObjects - The maximum number of objects per node. + * @default + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - The maximum number of levels to break down to. + * @default + */ + this.maxLevels = 4; + + /** + * @property {number} level - The current level. + */ + this.level = 0; + + /** + * @property {object} bounds - Object that contains the quadtree bounds. + */ + this.bounds = {}; + + /** + * @property {array} objects - Array of quadtree children. + */ + this.objects = []; + + /** + * @property {array} nodes - Array of associated child nodes. + */ + this.nodes = []; + + /** + * @property {array} _empty - Internal empty array. + * @private + */ + this._empty = []; + + this.reset(x, y, width, height, maxObjects, maxLevels, level); + +}; + +Phaser.QuadTree.prototype = { + + /** + * Resets the QuadTree. + * + * @method Phaser.QuadTree#reset + * @param {number} x - The top left coordinate of the quadtree. + * @param {number} y - The top left coordinate of the quadtree. + * @param {number} width - The width of the quadtree in pixels. + * @param {number} height - The height of the quadtree in pixels. + * @param {number} [maxObjects=10] - The maximum number of objects per node. + * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. + * @param {number} [level=0] - Which level is this? + */ + 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; + + }, + + /** + * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. + * + * @method Phaser.QuadTree#populate + * @param {Phaser.Group} group - The Group to add to the quadtree. + */ + populate: function (group) { + + group.forEach(this.populateHandler, this, true); + + }, + + /** + * Handler for the populate method. + * + * @method Phaser.QuadTree#populateHandler + * @param {Phaser.Sprite|object} sprite - The Sprite to check. + */ + populateHandler: function (sprite) { + + if (sprite.body && sprite.exists) + { + this.insert(sprite.body); + } + + }, + + /** + * Split the node into 4 subnodes + * + * @method Phaser.QuadTree#split + */ + split: function () { + + // top right node + this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // top left node + this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom left node + this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom right node + this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + }, + + /** + * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. + * + * @method Phaser.QuadTree#insert + * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. + */ + insert: function (body) { + + var i = 0; + var index; + + // if we have subnodes ... + 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.level < this.maxLevels) + { + // Split if we don't already have subnodes + if (this.nodes[0] == null) + { + this.split(); + } + + // Add objects to subnodes + while (i < this.objects.length) + { + index = this.getIndex(this.objects[i]); + + if (index !== -1) + { + // this is expensive - see what we can do about it + this.nodes[index].insert(this.objects.splice(i, 1)[0]); + } + else + { + i++; + } + } + } + + }, + + /** + * Determine which node the object belongs to. + * + * @method Phaser.QuadTree#getIndex + * @param {Phaser.Rectangle|object} rect - The bounds in which to check. + * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. + */ + getIndex: function (rect) { + + // default is that rect doesn't fit, i.e. it straddles the internal quadrants + var index = -1; + + if (rect.x < this.bounds.right && rect.right < this.bounds.right) + { + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-left quadrant of this quadtree + index = 1; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-left quadrant of this quadtree + index = 2; + } + } + else if (rect.x > this.bounds.right) + { + // rect can completely fit within the right quadrants + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-right quadrant of this quadtree + index = 0; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-right quadrant of this quadtree + index = 3; + } + } + + return index; + + }, + + /** + * Return all objects that could collide with the given Sprite or Rectangle. + * + * @method Phaser.QuadTree#retrieve + * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle. + * @return {array} - Array with all detected objects. + */ + 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 rect fits into a subnode .. + if (index !== -1) + { + returnObjects = returnObjects.concat(this.nodes[index].retrieve(source)); + } + else + { + // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed) + 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 the quadtree. + * @method Phaser.QuadTree#clear + */ + 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; + +/** +* Javascript QuadTree +* @version 1.0 +* +* @version 1.3, March 11th 2014 +* @author Richard Davey +* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked +* it massively to add node indexing, removed lots of temp. var creation and significantly +* increased performance as a result. +* +* Original version at https://github.com/timohausmann/quadtree-js/ +*/ + +/** +* @copyright © 2012 Timo Hausmann +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. +* +* @class Phaser.Net +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Net = function (game) { + + this.game = game; + +}; + +Phaser.Net.prototype = { + + /** + * Returns the hostname given by the browser. + * + * @method Phaser.Net#getHostName + * @return {string} + */ + getHostName: function () { + + if (window.location && window.location.hostname) { + return window.location.hostname; + } + + return null; + + }, + + /** + * Compares the given domain name against the hostname of the browser containing the game. + * If the domain name is found it returns true. + * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. + * Do not include 'http://' at the start. + * + * @method Phaser.Net#checkDomainName + * @param {string} domain + * @return {boolean} true if the given domain fragment can be found in the window.location.hostname + */ + checkDomainName: function (domain) { + return window.location.hostname.indexOf(domain) !== -1; + }, + + /** + * Updates a value on the Query String and returns it in full. + * If the value doesn't already exist it is set. + * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. + * Optionally you can redirect to the new url, or just return it as a string. + * + * @method Phaser.Net#updateQueryString + * @param {string} key - The querystring key to update. + * @param {string} value - The new value to be set. If it already exists it will be replaced. + * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. + * @param {string} url - The URL to modify. If none is given it uses window.location.href. + * @return {string} If redirect is false then the modified url and query string is returned. + */ + updateQueryString: function (key, value, redirect, url) { + + if (redirect === undefined) { redirect = false; } + if (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; + } + + }, + + /** + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#getQueryString + * @param {string} [parameter=''] - If specified this will return just the value for that key. + * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. + */ + getQueryString: function (parameter) { + + if (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 && parameter === this.decodeURI(key[0])) + { + return this.decodeURI(key[1]); + } + else + { + output[this.decodeURI(key[0])] = this.decodeURI(key[1]); + } + } + } + + return output; + + }, + + /** + * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and + * decodes it, replacing \ with spaces in the return. Used internally by the Net classes. + * + * @method Phaser.Net#decodeURI + * @param {string} value - The URI component to be decoded. + * @return {string} The decoded value. + */ + decodeURI: function (value) { + return decodeURIComponent(value.replace(/\+/g, " ")); + } + +}; + +Phaser.Net.prototype.constructor = Phaser.Net; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. +* Tweens are hooked into the game clock and pause system, adjusting based on the game state. +* +* TweenManager is based heavily on tween.js by http://soledadpenades.com. +* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. +* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. +* Please see https://github.com/sole/tween.js for a full list of contributors. +* +* @class Phaser.TweenManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.TweenManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * @property {boolean} frameBased + * @default + */ + this.frameBased = false; + + /** + * @property {array} _tweens - All of the currently running tweens. + * @private + */ + this._tweens = []; + + /** + * @property {array} _add - All of the tweens queued to be added in the next update. + * @private + */ + this._add = []; + + this.easeMap = { + + "Power0": Phaser.Easing.Power0, + "Power1": Phaser.Easing.Power1, + "Power2": Phaser.Easing.Power2, + "Power3": Phaser.Easing.Power3, + "Power4": Phaser.Easing.Power4, + + "Linear": Phaser.Easing.Linear.None, + "Quad": Phaser.Easing.Quadratic.Out, + "Cubic": Phaser.Easing.Cubic.Out, + "Quart": Phaser.Easing.Quartic.Out, + "Quint": Phaser.Easing.Quintic.Out, + "Sine": Phaser.Easing.Sinusoidal.Out, + "Expo": Phaser.Easing.Exponential.Out, + "Circ": Phaser.Easing.Circular.Out, + "Elastic": Phaser.Easing.Elastic.Out, + "Back": Phaser.Easing.Back.Out, + "Bounce": Phaser.Easing.Bounce.Out, + + "Quad.easeIn": Phaser.Easing.Quadratic.In, + "Cubic.easeIn": Phaser.Easing.Cubic.In, + "Quart.easeIn": Phaser.Easing.Quartic.In, + "Quint.easeIn": Phaser.Easing.Quintic.In, + "Sine.easeIn": Phaser.Easing.Sinusoidal.In, + "Expo.easeIn": Phaser.Easing.Exponential.In, + "Circ.easeIn": Phaser.Easing.Circular.In, + "Elastic.easeIn": Phaser.Easing.Elastic.In, + "Back.easeIn": Phaser.Easing.Back.In, + "Bounce.easeIn": Phaser.Easing.Bounce.In, + + "Quad.easeOut": Phaser.Easing.Quadratic.Out, + "Cubic.easeOut": Phaser.Easing.Cubic.Out, + "Quart.easeOut": Phaser.Easing.Quartic.Out, + "Quint.easeOut": Phaser.Easing.Quintic.Out, + "Sine.easeOut": Phaser.Easing.Sinusoidal.Out, + "Expo.easeOut": Phaser.Easing.Exponential.Out, + "Circ.easeOut": Phaser.Easing.Circular.Out, + "Elastic.easeOut": Phaser.Easing.Elastic.Out, + "Back.easeOut": Phaser.Easing.Back.Out, + "Bounce.easeOut": Phaser.Easing.Bounce.Out, + + "Quad.easeInOut": Phaser.Easing.Quadratic.InOut, + "Cubic.easeInOut": Phaser.Easing.Cubic.InOut, + "Quart.easeInOut": Phaser.Easing.Quartic.InOut, + "Quint.easeInOut": Phaser.Easing.Quintic.InOut, + "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut, + "Expo.easeInOut": Phaser.Easing.Exponential.InOut, + "Circ.easeInOut": Phaser.Easing.Circular.InOut, + "Elastic.easeInOut": Phaser.Easing.Elastic.InOut, + "Back.easeInOut": Phaser.Easing.Back.InOut, + "Bounce.easeInOut": Phaser.Easing.Bounce.InOut + + }; + + this.game.onPause.add(this._pauseAll, this); + this.game.onResume.add(this._resumeAll, this); + +}; + +Phaser.TweenManager.prototype = { + + /** + * Get all the tween objects in an array. + * @method Phaser.TweenManager#getAll + * @returns {Phaser.Tween[]} Array with all tween objects. + */ + getAll: function () { + + return this._tweens; + + }, + + /** + * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. + * @method Phaser.TweenManager#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._tweens.length; i++) + { + this._tweens[i].pendingDelete = true; + } + + this._add = []; + + }, + + /** + * Remove all tweens from a specific object, array of objects or Group. + * + * @method Phaser.TweenManager#removeFrom + * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. + * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. + */ + removeFrom: function (obj, children) { + + if (children === undefined) { children = true; } + + var i; + var len; + + if (Array.isArray(obj)) + { + for (i = 0, len = obj.length; i < len; i++) + { + this.removeFrom(obj[i]); + } + } + else if (obj.type === Phaser.GROUP && children) + { + for (var i = 0, len = obj.children.length; i < len; i++) + { + this.removeFrom(obj.children[i]); + } + } + else + { + for (i = 0, len = this._tweens.length; i < len; i++) + { + if (obj === this._tweens[i].target) + { + this.remove(this._tweens[i]); + } + } + + for (i = 0, len = this._add.length; i < len; i++) + { + if (obj === this._add[i].target) + { + this.remove(this._add[i]); + } + } + } + + }, + + /** + * Add a new tween into the TweenManager. + * + * @method Phaser.TweenManager#add + * @param {Phaser.Tween} tween - The tween object you want to add. + * @returns {Phaser.Tween} The tween object you added to the manager. + */ + add: function (tween) { + + tween._manager = this; + this._add.push(tween); + + }, + + /** + * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.TweenManager#create + * @param {object} object - Object the tween will be run on. + * @returns {Phaser.Tween} The newly created tween object. + */ + create: function (object) { + + return new Phaser.Tween(object, this.game, this); + + }, + + /** + * Remove a tween from this manager. + * + * @method Phaser.TweenManager#remove + * @param {Phaser.Tween} tween - The tween object you want to remove. + */ + remove: function (tween) { + + var i = this._tweens.indexOf(tween); + + if (i !== -1) + { + this._tweens[i].pendingDelete = true; + } + else + { + i = this._add.indexOf(tween); + + if (i !== -1) + { + this._add[i].pendingDelete = true; + } + } + + }, + + /** + * Update all the tween objects you added to this manager. + * + * @method Phaser.TweenManager#update + * @returns {boolean} Return false if there's no tween to update, otherwise return true. + */ + update: function () { + + var addTweens = this._add.length; + var numTweens = this._tweens.length; + + if (numTweens === 0 && addTweens === 0) + { + return false; + } + + var i = 0; + + while (i < numTweens) + { + if (this._tweens[i].update(this.game.time.time)) + { + i++; + } + else + { + this._tweens.splice(i, 1); + + numTweens--; + } + } + + // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running + if (addTweens > 0) + { + this._tweens = this._tweens.concat(this._add); + this._add.length = 0; + } + + return true; + + }, + + /** + * Checks to see if a particular Sprite is currently being tweened. + * + * The `checkIsRunning` parameter will exclude tweens that have **just** completed or been stopped but haven't yet been removed from the manager. + * + * @method Phaser.TweenManager#isTweening + * @param {object} object - The object to check for tweens against. + * @param {boolean} [checkIsRunning=false] - Also check that the tween is running and is not marked for deletion. + * @returns {boolean} Returns true if the object is currently being tweened, false if not. + */ + isTweening: function(object, checkIsRunning) { + + if (!checkIsRunning) { checkIsRunning = false; } + + return this._tweens.some(function(tween) { + return (tween.target === object) && (!checkIsRunning || (tween.isRunning && !tween.pendingDelete)); + }); + + }, + + /** + * Private. Called by game focus loss. Pauses all currently running tweens. + * + * @method Phaser.TweenManager#_pauseAll + * @private + */ + _pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._pause(); + } + + }, + + /** + * Private. Called by game focus loss. Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#_resumeAll + * @private + */ + _resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._resume(); + } + + }, + + /** + * Pauses all currently running tweens. + * + * @method Phaser.TweenManager#pauseAll + */ + pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].pause(); + } + + }, + + /** + * Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#resumeAll + */ + resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].resume(true); + } + + } + +}; + +Phaser.TweenManager.prototype.constructor = Phaser.TweenManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tween allows you to alter one or more properties of a target object over a defined period of time. +* This can be used for things such as alpha fading Sprites, scaling them or motion. +* Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object +* by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and +* are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. +* +* @class Phaser.Tween +* @constructor +* @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. +* @param {Phaser.Game} game - Current game instance. +* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. +*/ +Phaser.Tween = function (target, game, manager) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. + */ + this.target = target; + + /** + * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween. + */ + this.manager = manager; + + /** + * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween. + */ + this.timeline = []; + + /** + * If set to `true` the current tween will play in reverse. + * If the tween hasn't yet started this has no effect. + * If there are child tweens then all child tweens will play in reverse from the current point. + * @property {boolean} reverse + * @default + */ + this.reverse = false; + + /** + * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. + * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. + * + * @property {number} timeScale + * @default + */ + this.timeScale = 1; + + /** + * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count. + */ + this.repeatCounter = 0; + + /** + * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager. + * @default + * @readonly + */ + this.pendingDelete = false; + + /** + * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onStart + */ + this.onStart = new Phaser.Signal(); + + /** + * The onLoop event is fired if the Tween, or any child tweens loop. + * It will be sent 2 parameters: the target object and this tween. + * + * @property {Phaser.Signal} onLoop + */ + this.onLoop = new Phaser.Signal(); + + /** + * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onRepeat + */ + this.onRepeat = new Phaser.Signal(); + + /** + * The onChildComplete event is fired when the Tween or any of its children completes. + * Fires every time a child completes unless a child is set to repeat forever. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onChildComplete + */ + this.onChildComplete = new Phaser.Signal(); + + /** + * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. + * @default + */ + this.isRunning = false; + + /** + * @property {number} current - The current Tween child being run. + * @default + * @readonly + */ + this.current = 0; + + /** + * @property {object} properties - Target property cache used when building the child data values. + */ + this.properties = {}; + + /** + * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it. + */ + this.chainedTween = null; + + /** + * @property {boolean} isPaused - Is this Tween paused or not? + * @default + */ + this.isPaused = false; + + /** + * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * + * The default value is whatever you've set in TweenManager.frameBased. + * + * @property {boolean} frameBased + * @default + */ + this.frameBased = manager.frameBased; + + /** + * @property {function} _onUpdateCallback - An onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallback = null; + + /** + * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallbackContext = null; + + /** + * @property {number} _pausedTime - Private pause timer. + * @private + * @default + */ + this._pausedTime = 0; + + /** + * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not. + * @private + */ + this._hasStarted = false; +}; + +/** +* A helper for tweening {@link Phaser.Color.createColor color objects}. +* +* It can be passed to {@link #onUpdateCallback}. +* +* ```javascript +* var color = Phaser.Color.createColor(255, 0, 0); // red +* +* var tween = game.add.tween(color).to({ +* r: 0, g: 0, b: 255 // blue +* }); +* +* tween.onUpdateCallback(Phaser.Tween.updateColor); +* +* tween.start(); +* ``` +* +* @method Phaser.Tween.updateColor +* @static +* @param {Phaser.Tween} tween - A Tween with a {@link #target} that is a {@link Phaser.Color.createColor color object}. +*/ +Phaser.Tween.updateColor = function (tween) { + + Phaser.Color.updateColor(tween.target); + +}; + +Phaser.Tween.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#to + * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined || duration <= 0) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.to cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#from + * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.from cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Starts the tween running. Can also be called by the `autoStart` parameter of {@link #to} or {@link #from}. + * This sets the {@link #isRunning} property to `true` and dispatches the {@link #onStart} signal. + * If the tween has a delay set then nothing will start tweening until the delay has expired. + * If the tween is already running, is flagged for deletion (such as after {@link #stop}), + * or has an empty timeline, calling start has no effect and the `onStart` signal is not dispatched. + * + * @method Phaser.Tween#start + * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + start: function (index) { + + if (index === undefined) { index = 0; } + + if (this.pendingDelete) + { + console.warn('Phaser.Tween.start cannot be called after Tween.stop'); + return this; + } + + if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning) + { + return this; + } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + this.manager.add(this); + + this.isRunning = true; + + if (index < 0 || index > this.timeline.length - 1) + { + index = 0; + } + + this.current = index; + + this.timeline[this.current].start(); + + return this; + + }, + + /** + * Stops the tween if running and flags it for deletion from the TweenManager. The tween can't be {@link #start restarted} after this. + * The {@link #onComplete} signal is not dispatched and no chained tweens are started unless the `complete` parameter is set to `true`. + * If you just wish to pause a tween then use {@link #pause} instead. + * If the tween is not running, it is **not** flagged for deletion and can be started again. + * + * @method Phaser.Tween#stop + * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + stop: function (complete) { + + if (complete === undefined) { complete = false; } + + this.isRunning = false; + + this._onUpdateCallback = null; + this._onUpdateCallbackContext = null; + + if (complete) + { + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + } + + this.manager.remove(this); + + return this; + + }, + + /** + * Updates either a single TweenData or all TweenData objects properties to the given value. + * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. + * The property is not checked, so if you pass an invalid one you'll generate a run-time error. + * + * @method Phaser.Tween#updateTweenData + * @param {string} property - The property to update. + * @param {number|function} value - The value to set the property to. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + updateTweenData: function (property, value, index) { + + if (this.timeline.length === 0) { return this; } + + if (index === undefined) { index = 0; } + + if (index === -1) + { + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i][property] = value; + } + } + else + { + this.timeline[index][property] = value; + } + + return this; + + }, + + /** + * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. + * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. + * If you have child tweens and pass -1 as the index value it sets the delay across all of them. + * + * @method Phaser.Tween#delay + * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + delay: function (duration, index) { + + return this.updateTweenData('delay', duration, index); + + }, + + /** + * Sets the number of times this tween will repeat. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. + * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. + * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. + * + * @method Phaser.Tween#repeat + * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeat: function (total, repeatDelay, index) { + + if (repeatDelay === undefined) { repeatDelay = 0; } + + this.updateTweenData('repeatCounter', total, index); + this.updateTweenData('repeatTotal', total, index); + + return this.updateTweenData('repeatDelay', repeatDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will repeat itself. + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#repeatDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatDelay: function (duration, index) { + + return this.updateTweenData('repeatDelay', duration, index); + + }, + + /** + * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. + * Used in combination with repeat you can create endless loops. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. + * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. + * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. + * + * @method Phaser.Tween#yoyo + * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo. + * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyo: function(enable, yoyoDelay, index) { + + if (yoyoDelay === undefined) { yoyoDelay = 0; } + + this.updateTweenData('yoyo', enable, index); + + return this.updateTweenData('yoyoDelay', yoyoDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#yoyoDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyoDelay: function (duration, index) { + + return this.updateTweenData('yoyoDelay', duration, index); + + }, + + /** + * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. + * + * @method Phaser.Tween#easing + * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + easing: function (ease, index) { + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + return this.updateTweenData('easingFunction', ease, index); + + }, + + /** + * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. + * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. + * The interpolation function is only used if the target properties is an array. + * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. + * + * @method Phaser.Tween#interpolation + * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) + * @param {object} [context] - The context under which the interpolation function will be run. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + interpolation: function (interpolation, context, index) { + + if (context === undefined) { context = Phaser.Math; } + + this.updateTweenData('interpolationFunction', interpolation, index); + + return this.updateTweenData('interpolationContext', context, index); + + }, + + /** + * Set how many times this tween and all of its children will repeat. + * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. + * + * @method Phaser.Tween#repeatAll + * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatAll: function (total) { + + if (total === undefined) { total = 0; } + + this.repeatCounter = total; + + return this; + + }, + + /** + * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called + * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. + * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. + * For that you should listen to `onComplete` on the final tween in your chain. + * + * If you pass multiple tweens to this method they will be joined into a single long chain. + * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. + * Any previously chained tweens that may have been set will be overwritten. + * + * @method Phaser.Tween#chain + * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + chain: function () { + + var i = arguments.length; + + while (i--) + { + if (i > 0) + { + arguments[i - 1].chainedTween = arguments[i]; + } + else + { + this.chainedTween = arguments[i]; + } + } + + return this; + + }, + + /** + * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. + * + * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. + * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. + * + * Usage: + * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) + * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) + * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) + * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) + * .loop(); + * @method Phaser.Tween#loop + * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + loop: function (value) { + + if (value === undefined) { value = true; } + + this.repeatCounter = (value) ? -1 : 0; + + return this; + + }, + + /** + * Sets a callback to be fired each time this tween updates. + * + * The callback receives the current Tween, the {@link Phaser.TweenData#value 'value' of the current TweenData}, and the current {@link Phaser.TweenData TweenData}. The second parameter is most useful. + * + * ```javascript + * tween.onUpdateCallback(function (tween, value, tweenData) { + * console.log('Tween running -- percent: %.2f value: %.2f', tweenData.percent, value); + * }); + * ``` + * + * @method Phaser.Tween#onUpdateCallback + * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. + * @param {object} callbackContext - The context in which to call the onUpdate callback. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + onUpdateCallback: function (callback, callbackContext) { + + this._onUpdateCallback = callback; + this._onUpdateCallbackContext = callbackContext; + + return this; + + }, + + /** + * Pauses the tween. Resume playback with Tween.resume. + * + * @method Phaser.Tween#pause + */ + pause: function () { + + this.isPaused = true; + + this._codePaused = true; + + this._pausedTime = this.game.time.time; + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * + * @private + * @method Phaser.Tween#_pause + */ + _pause: function () { + + if (!this._codePaused) + { + this.isPaused = true; + + this._pausedTime = this.game.time.time; + } + + }, + + /** + * Resumes a paused tween. + * + * @method Phaser.Tween#resume + */ + resume: function () { + + if (this.isPaused) + { + this.isPaused = false; + + this._codePaused = false; + + for (var i = 0; i < this.timeline.length; i++) + { + if (!this.timeline[i].isRunning) + { + this.timeline[i].startTime += (this.game.time.time - this._pausedTime); + } + } + } + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * @method Phaser.Tween#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Core tween update function called by the TweenManager. Does not need to be invoked directly. + * + * @method Phaser.Tween#update + * @param {number} time - A timestamp passed in by the TweenManager. + * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). + */ + update: function (time) { + + if (this.pendingDelete || !this.target) + { + return false; + } + + if (this.isPaused) + { + return true; + } + + var status = this.timeline[this.current].update(time); + + if (status === Phaser.TweenData.PENDING) + { + return true; + } + else if (status === Phaser.TweenData.RUNNING) + { + if (!this._hasStarted) + { + this.onStart.dispatch(this.target, this); + this._hasStarted = true; + } + + if (this._onUpdateCallback !== null) + { + this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]); + } + + // In case the update callback modifies this tween + return this.isRunning; + } + else if (status === Phaser.TweenData.LOOPED) + { + if (this.timeline[this.current].repeatCounter === -1) + { + this.onLoop.dispatch(this.target, this); + } + else + { + this.onRepeat.dispatch(this.target, this); + } + + return true; + } + else if (status === Phaser.TweenData.COMPLETE) + { + var complete = false; + + // What now? + if (this.reverse) + { + this.current--; + + if (this.current < 0) + { + this.current = this.timeline.length - 1; + complete = true; + } + } + else + { + this.current++; + + if (this.current === this.timeline.length) + { + this.current = 0; + complete = true; + } + } + + if (complete) + { + // We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it? + if (this.repeatCounter === -1) + { + this.timeline[this.current].start(); + this.onLoop.dispatch(this.target, this); + return true; + } + else if (this.repeatCounter > 0) + { + this.repeatCounter--; + + this.timeline[this.current].start(); + this.onRepeat.dispatch(this.target, this); + return true; + } + else + { + // No more repeats and no more children, so we're done + this.isRunning = false; + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + + return false; + } + } + else + { + // We've still got some children to go + this.onChildComplete.dispatch(this.target, this); + this.timeline[this.current].start(); + return true; + } + } + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * It ignores delay and repeat counts and any chained tweens, but does include child tweens. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.Tween#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate, data) { + + if (this.game === null || this.target === null) + { + return null; + } + + if (frameRate === undefined) { frameRate = 60; } + if (data === undefined) { data = []; } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + for (var i = 0; i < this.timeline.length; i++) + { + data = data.concat(this.timeline[i].generateData(frameRate)); + } + + return data; + + } + +}; + +/** +* @name Phaser.Tween#totalDuration +* @property {number} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds. +*/ +Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', { + + get: function () { + + var total = 0; + + for (var i = 0; i < this.timeline.length; i++) + { + total += this.timeline[i].duration; + } + + return total; + + } + +}); + +Phaser.Tween.prototype.constructor = Phaser.Tween; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the +* starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for +* TweenData objects and can contain multiple TweenData objects. +* +* @class Phaser.TweenData +* @constructor +* @param {Phaser.Tween} parent - The Tween that owns this TweenData object. +*/ +Phaser.TweenData = function (parent) { + + /** + * @property {Phaser.Tween} parent - The Tween which owns this TweenData. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = parent.game; + + /** + * @property {object} vStart - An object containing the values at the start of the tween. + * @private + */ + this.vStart = {}; + + /** + * @property {object} vStartCache - Cached starting values. + * @private + */ + this.vStartCache = {}; + + /** + * @property {object} vEnd - An object containing the values at the end of the tween. + * @private + */ + this.vEnd = {}; + + /** + * @property {object} vEndCache - Cached ending values. + * @private + */ + this.vEndCache = {}; + + /** + * @property {number} duration - The duration of the tween in ms. + * @default + */ + this.duration = 1000; + + /** + * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is. + * @readonly + */ + this.percent = 0; + + /** + * @property {number} value - The output of the easing function for the current {@link #percent}. Depending on the easing function, this will be within [0, 1] or a slightly larger range (e.g., Bounce). When easing is Linear, this will be identical to {@link #percent}. + * @readonly + */ + this.value = 0; + + /** + * @property {number} repeatCounter - If the Tween is set to repeat this is the number of repeats remaining (and `repeatTotal - repeatCounter` is the number of repeats completed). + */ + this.repeatCounter = 0; + + /** + * @property {number} repeatDelay - The amount of time in ms between repeats of this tween. + */ + this.repeatDelay = 0; + + /** + * @property {number} repeatTotal - The total number of times this Tween will repeat. + * @readonly + */ + this.repeatTotal = 0; + + /** + * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween) + * @default + * @todo Appears unused. + */ + this.interpolate = false; + + /** + * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false. + * @default + */ + this.yoyo = false; + + /** + * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween. + */ + this.yoyoDelay = 0; + + /** + * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). + * @default + */ + this.inReverse = false; + + /** + * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. + * @default + */ + this.delay = 0; + + /** + * @property {number} dt - Current time value. + */ + this.dt = 0; + + /** + * @property {number} startTime - The time the Tween started or null if it hasn't yet started. + */ + this.startTime = null; + + /** + * @property {function} easingFunction - The easing function used for the Tween. + * @default Phaser.Easing.Default + */ + this.easingFunction = Phaser.Easing.Default; + + /** + * @property {function} interpolationFunction - The interpolation function used for Array-based Tween. + * @default Phaser.Math.linearInterpolation + */ + this.interpolationFunction = Phaser.Math.linearInterpolation; + + /** + * @property {object} interpolationContext - The interpolation function context used for the Tween. + * @default Phaser.Math + */ + this.interpolationContext = Phaser.Math; + + /** + * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} isFrom - Is this a from tween or a to tween? + * @default + */ + this.isFrom = false; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.PENDING = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.RUNNING = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.LOOPED = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.COMPLETE = 3; + +Phaser.TweenData.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * + * @method Phaser.TweenData#to + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + to: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = false; + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * + * @method Phaser.TweenData#from + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + from: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = true; + + return this; + + }, + + /** + * Starts the Tween running. + * + * @method Phaser.TweenData#start + * @return {Phaser.TweenData} This Tween object. + */ + start: function () { + + this.startTime = this.game.time.time + this.delay; + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + if (this.delay > 0) + { + this.isRunning = false; + } + else + { + this.isRunning = true; + } + + if (this.isFrom) + { + // Reverse them all and instant set them + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + this.parent.target[property] = this.vStart[property]; + } + } + + this.value = 0; + this.repeatCounter = this.repeatTotal; + + return this; + + }, + + /** + * Loads the values from the target object into this Tween. + * + * @private + * @method Phaser.TweenData#loadValues + * @return {Phaser.TweenData} This Tween object. + */ + loadValues: function () { + + for (var property in this.parent.properties) + { + // Load the property from the parent object + this.vStart[property] = this.parent.properties[property]; + + // Check if an Array was provided as property value + if (Array.isArray(this.vEnd[property])) + { + if (this.vEnd[property].length === 0) + { + continue; + } + + if (this.percent === 0) + { + // Put the start value at the beginning of the array + // but we only want to do this once, if the Tween hasn't run before + this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]); + } + } + + if (typeof this.vEnd[property] !== 'undefined') + { + if (typeof this.vEnd[property] === 'string') + { + // Parses relative end values with start as base (e.g.: +10, -3) + this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10); + } + + this.parent.properties[property] = this.vEnd[property]; + } + else + { + // Null tween + this.vEnd[property] = this.vStart[property]; + } + + this.vStartCache[property] = this.vStart[property]; + this.vEndCache[property] = this.vEnd[property]; + } + + return this; + + }, + + /** + * Updates this Tween. This is called automatically by Phaser.Tween. + * + * @protected + * @method Phaser.TweenData#update + * @param {number} time - A timestamp passed in by the Tween parent. + * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. + */ + update: function (time) { + + if (!this.isRunning) + { + if (time >= this.startTime) + { + this.isRunning = true; + } + else + { + return Phaser.TweenData.PENDING; + } + } + else + { + // Is Running, but is waiting to repeat + if (time < this.startTime) + { + return Phaser.TweenData.RUNNING; + } + } + + var ms = (this.parent.frameBased) ? this.game.time.physicsElapsedMS : this.game.time.elapsedMS; + + if (this.parent.reverse) + { + this.dt -= ms * this.parent.timeScale; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += ms * this.parent.timeScale; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + this.parent.target[property] = start + ((end - start) * this.value); + } + } + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + return this.repeat(); + } + + return Phaser.TweenData.RUNNING; + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.TweenData#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate) { + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + var data = []; + var complete = false; + var fps = (1 / frameRate) * 1000; + + do + { + if (this.parent.reverse) + { + this.dt -= fps; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += fps; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + var blob = {}; + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + blob[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + blob[property] = start + ((end - start) * this.value); + } + } + + data.push(blob); + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + complete = true; + } + + } while (!complete); + + if (this.yoyo) + { + var reversed = data.slice(); + reversed.reverse(); + data = data.concat(reversed); + } + + return data; + + }, + + /** + * Checks if this Tween is meant to repeat or yoyo and handles doing so. + * + * @private + * @method Phaser.TweenData#repeat + * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE. + */ + repeat: function () { + + // If not a yoyo and repeatCounter = 0 then we're done + if (this.yoyo) + { + // We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end + if (this.inReverse && this.repeatCounter === 0) + { + // Restore the properties + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + this.inReverse = false; + + return Phaser.TweenData.COMPLETE; + } + + this.inReverse = !this.inReverse; + } + else + { + if (this.repeatCounter === 0) + { + return Phaser.TweenData.COMPLETE; + } + } + + if (this.inReverse) + { + // If inReverse we're going from vEnd to vStartCache + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + } + } + else + { + // If not inReverse we're just repopulating the cache again + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + // -1 means repeat forever, otherwise decrement the repeatCounter + // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total + if (this.repeatCounter > 0) + { + this.repeatCounter--; + } + } + + this.startTime = this.game.time.time; + + if (this.yoyo && this.inReverse) + { + this.startTime += this.yoyoDelay; + } + else if (!this.inReverse) + { + this.startTime += this.repeatDelay; + } + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + return Phaser.TweenData.LOOPED; + + } + +}; + +Phaser.TweenData.prototype.constructor = Phaser.TweenData; + +/* jshint curly: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of easing methods defining ease-in and ease-out curves. +* +* @class Phaser.Easing +*/ +Phaser.Easing = { + + /** + * Linear easing. + * + * @class Phaser.Easing.Linear + */ + Linear: { + + /** + * Linear Easing (no variation). + * + * @method Phaser.Easing.Linear#None + * @param {number} k - The value to be tweened. + * @returns {number} k. + */ + None: function ( k ) { + + return k; + + } + + }, + + /** + * Quadratic easing. + * + * @class Phaser.Easing.Quadratic + */ + Quadratic: { + + /** + * Ease-in. + * + * @method Phaser.Easing.Quadratic#In + * @param {number} k - The value to be tweened. + * @returns {number} k^2. + */ + In: function ( k ) { + + return k * k; + + }, + + /** + * Ease-out. + * + * @method Phaser.Easing.Quadratic#Out + * @param {number} k - The value to be tweened. + * @returns {number} k* (2-k). + */ + Out: function ( k ) { + + return k * ( 2 - k ); + + }, + + /** + * Ease-in/out. + * + * @method Phaser.Easing.Quadratic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; + return - 0.5 * ( --k * ( k - 2 ) - 1 ); + + } + + }, + + /** + * Cubic easing. + * + * @class Phaser.Easing.Cubic + */ + Cubic: { + + /** + * Cubic ease-in. + * + * @method Phaser.Easing.Cubic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k; + + }, + + /** + * Cubic ease-out. + * + * @method Phaser.Easing.Cubic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k + 1; + + }, + + /** + * Cubic ease-in/out. + * + * @method Phaser.Easing.Cubic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k + 2 ); + + } + + }, + + /** + * Quartic easing. + * + * @class Phaser.Easing.Quartic + */ + Quartic: { + + /** + * Quartic ease-in. + * + * @method Phaser.Easing.Quartic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k; + + }, + + /** + * Quartic ease-out. + * + * @method Phaser.Easing.Quartic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return 1 - ( --k * k * k * k ); + + }, + + /** + * Quartic ease-in/out. + * + * @method Phaser.Easing.Quartic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; + return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); + + } + + }, + + /** + * Quintic easing. + * + * @class Phaser.Easing.Quintic + */ + Quintic: { + + /** + * Quintic ease-in. + * + * @method Phaser.Easing.Quintic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k * k; + + }, + + /** + * Quintic ease-out. + * + * @method Phaser.Easing.Quintic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k * k * k + 1; + + }, + + /** + * Quintic ease-in/out. + * + * @method Phaser.Easing.Quintic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); + + } + + }, + + /** + * Sinusoidal easing. + * + * @class Phaser.Easing.Sinusoidal + */ + Sinusoidal: { + + /** + * Sinusoidal ease-in. + * + * @method Phaser.Easing.Sinusoidal#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 1 - Math.cos( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-out. + * + * @method Phaser.Easing.Sinusoidal#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return Math.sin( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-in/out. + * + * @method Phaser.Easing.Sinusoidal#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); + + } + + }, + + /** + * Exponential easing. + * + * @class Phaser.Easing.Exponential + */ + Exponential: { + + /** + * Exponential ease-in. + * + * @method Phaser.Easing.Exponential#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k === 0 ? 0 : Math.pow( 1024, k - 1 ); + + }, + + /** + * Exponential ease-out. + * + * @method Phaser.Easing.Exponential#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); + + }, + + /** + * Exponential ease-in/out. + * + * @method Phaser.Easing.Exponential#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); + return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); + + } + + }, + + /** + * Circular easing. + * + * @class Phaser.Easing.Circular + */ + Circular: { + + /** + * Circular ease-in. + * + * @method Phaser.Easing.Circular#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Math.sqrt( 1 - k * k ); + + }, + + /** + * Circular ease-out. + * + * @method Phaser.Easing.Circular#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return Math.sqrt( 1 - ( --k * k ) ); + + }, + + /** + * Circular ease-in/out. + * + * @method Phaser.Easing.Circular#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); + return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); + + } + + }, + + /** + * Elastic easing. + * + * @class Phaser.Easing.Elastic + */ + Elastic: { + + /** + * Elastic ease-in. + * + * @method Phaser.Easing.Elastic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + + }, + + /** + * Elastic ease-out. + * + * @method Phaser.Easing.Elastic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); + + }, + + /** + * Elastic ease-in/out. + * + * @method Phaser.Easing.Elastic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; + + } + + }, + + /** + * Back easing. + * + * @class Phaser.Easing.Back + */ + Back: { + + /** + * Back ease-in. + * + * @method Phaser.Easing.Back#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s = 1.70158; + return k * k * ( ( s + 1 ) * k - s ); + + }, + + /** + * Back ease-out. + * + * @method Phaser.Easing.Back#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s = 1.70158; + return --k * k * ( ( s + 1 ) * k + s ) + 1; + + }, + + /** + * Back ease-in/out. + * + * @method Phaser.Easing.Back#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s = 1.70158 * 1.525; + if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); + return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); + + } + + }, + + /** + * Bounce easing. + * + * @class Phaser.Easing.Bounce + */ + Bounce: { + + /** + * Bounce ease-in. + * + * @method Phaser.Easing.Bounce#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Phaser.Easing.Bounce.Out( 1 - k ); + + }, + + /** + * Bounce ease-out. + * + * @method Phaser.Easing.Bounce#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if ( k < ( 1 / 2.75 ) ) { + + return 7.5625 * k * k; + + } else if ( k < ( 2 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; + + } else if ( k < ( 2.5 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; + + } else { + + return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; + + } + + }, + + /** + * Bounce ease-in/out. + * + * @method Phaser.Easing.Bounce#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5; + return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5; + + } + + } + +}; + +Phaser.Easing.Default = Phaser.Easing.Linear.None; +Phaser.Easing.Power0 = Phaser.Easing.Linear.None; +Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out; +Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out; +Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out; +Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is the core internal game clock. +* +* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, +* and also handles the standard Timer pool. +* +* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}. +* +* There are different *types* of time in Phaser: +* +* - ***Game time*** always runs at the speed of time in real life. +* +* Unlike wall-clock time, *game time stops when Phaser is paused*. +* +* Game time is used for {@link Phaser.Timer timer events}. +* +* - ***Physics time*** represents the amount of time given to physics calculations. +* +* *When {@link #slowMotion} is in effect physics time runs slower than game time.* +* Like game time, physics time stops when Phaser is paused. +* +* Physics time is used for physics calculations and {@link Phaser.Tween tweens}. +* +* - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time. +* +* This time is independent of Phaser and always progresses, regardless of if Phaser is paused. +* +* @class Phaser.Time +* @constructor +* @param {Phaser.Game} game A reference to the currently running game. +*/ +Phaser.Time = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * The `Date.now()` value when the time was last updated. + * @property {integer} time + * @protected + */ + this.time = 0; + + /** + * The `now` when the previous update occurred. + * @property {number} prevTime + * @protected + */ + this.prevTime = 0; + + /** + * An increasing value representing cumulative milliseconds since an undisclosed epoch. + * + * While this value is in milliseconds and can be used to compute time deltas, + * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference. + * + * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; + * the value can only be relied upon within a particular game instance. + * + * @property {number} now + * @protected + */ + this.now = 0; + + /** + * Elapsed time since the last time update, in milliseconds, based on `now`. + * + * This value _may_ include time that the game is paused/inactive. + * + * While the game is active, this will be similar to (1000 / {@link #fps}). + * + * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {number} elapsed + * @see Phaser.Time.time + * @protected + */ + this.elapsed = 0; + + /** + * The time in ms since the last time update, in milliseconds, based on `time`. + * + * This value is corrected for game pauses and will be "about zero" after a game is resumed. + * + * _Note:_ This is updated once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {integer} elapsedMS + * @protected + */ + this.elapsedMS = 0; + + /** + * The physics update delta, in fractional seconds. + * + * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) + * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system + * is unable to consistently maintain the desired FPS. + * + * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. + * + * @property {number} physicsElapsed + */ + this.physicsElapsed = 1 / 60; + + /** + * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. + * + * @property {number} physicsElapsedMS + */ + this.physicsElapsedMS = (1 / 60) * 1000; + + /** + * The desiredFps multiplier as used by Game.update. + * @property {integer} desiredFpsMult + * @protected + */ + this.desiredFpsMult = 1.0 / 60; + + /** + * The desired frame rate of the game. + * + * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates. + * + * @property {number} _desiredFps + * @private + * @default + */ + this._desiredFps = 60; + + /** + * The suggested frame rate for your game, based on an averaged real frame rate. + * This value is only populated if `Time.advancedTiming` is enabled. + * + * _Note:_ This is not available until after a few frames have passed; until then + * it's set to the same value as desiredFps. + * + * @property {number} suggestedFps + * @default + */ + this.suggestedFps = this.desiredFps; + + /** + * Scaling factor to make the game move smoothly in slow motion (or fast motion) + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * You likely need to adjust {@link #desiredFps} as well such that `desiredFps / slowMotion === 60`. + * + * @property {number} slowMotion + * @default + */ + this.slowMotion = 1.0; + + /** + * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. This isn't expensive, but displaying it with {@link Phaser.Utils.Debug#text} can be, especially in WebGL mode. + * @property {boolean} advancedTiming + * @default + */ + this.advancedTiming = false; + + /** + * Advanced timing result: The number of animation frames received from the browser in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} frames + * @readonly + */ + this.frames = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateLogic logic updates} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} updates + * @readonly + */ + this.updates = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateRender renders} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} renders + * @readonly + */ + this.renders = 0; + + /** + * Advanced timing result: Frames per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} fps + * @readonly + */ + this.fps = 0; + + /** + * Advanced timing result: Logic updates per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} ups + * @readonly + */ + this.ups = 0; + + /** + * Advanced timing result: Renders per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} rps + * @readonly + */ + this.rps = 0; + + /** + * Advanced timing result: The lowest rate the fps has dropped to. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMin + */ + this.fpsMin = 1000; + + /** + * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMax + */ + this.fpsMax = 0; + + /** + * Advanced timing result: The minimum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMin + * @default + */ + this.msMin = 1000; + + /** + * Advanced timing result: The maximum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMax + */ + this.msMax = 0; + + /** + * Records how long the game was last paused, in milliseconds. + * (This is not updated until the game is resumed.) + * @property {number} pauseDuration + */ + this.pauseDuration = 0; + + /** + * @property {number} timeToCall - The value that setTimeout needs to work out when to next update + * @protected + */ + this.timeToCall = 0; + + /** + * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop + * @protected + */ + this.timeExpected = 0; + + /** + * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to. + * @property {Phaser.Timer} events + */ + this.events = new Phaser.Timer(this.game, false); + + /** + * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated + * @private + */ + this._frameCount = 0; + + /** + * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated + * @private + */ + this._elapsedAccumulator = 0; + + /** + * @property {number} _started - The time at which the Game instance started. + * @private + */ + this._started = 0; + + /** + * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. + * @private + */ + this._timeLastSecond = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {boolean} _justResumed - Internal value used to recover from the game pause state. + * @private + */ + this._justResumed = false; + + /** + * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects. + * @private + */ + this._timers = []; + +}; + +Phaser.Time.prototype = { + + /** + * Called automatically by Phaser.Game after boot. Should not be called directly. + * + * @method Phaser.Time#boot + * @protected + */ + boot: function () { + + this._started = Date.now(); + this.time = Date.now(); + this.events.start(); + this.timeExpected = this.time; + + }, + + /** + * Adds an existing Phaser.Timer object to the Timer pool. + * + * @method Phaser.Time#add + * @param {Phaser.Timer} timer - An existing Phaser.Timer object. + * @return {Phaser.Timer} The given Phaser.Timer object. + */ + add: function (timer) { + + this._timers.push(timer); + + return timer; + + }, + + /** + * Creates a new stand-alone Phaser.Timer object. + * + * @method Phaser.Time#create + * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). + * @return {Phaser.Timer} The Timer object that was created. + */ + create: function (autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + var timer = new Phaser.Timer(this.game, autoDestroy); + + this._timers.push(timer); + + return timer; + + }, + + /** + * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer. + * + * @method Phaser.Time#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._timers.length; i++) + { + this._timers[i].destroy(); + } + + this._timers = []; + + this.events.removeAll(); + + }, + + /** + * Refreshes the Time.time and Time.elapsedMS properties from the system clock. + * + * @method Phaser.Time#refresh + */ + refresh: function () { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + }, + + /** + * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. + * + * @method Phaser.Time#update + * @protected + * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}. + */ + update: function (time) { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + // 'now' is currently still holding the time of the last call, move it into prevTime + this.prevTime = this.now; + + // update 'now' to hold the current time + // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now) + this.now = time; + + // elapsed time between previous call and now - this could be a high resolution value + this.elapsed = this.now - this.prevTime; + + if (this.game.raf._isSetTimeOut) + { + // console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time); + + // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game + this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time))); + + // time when the next call is expected if using timers + this.timeExpected = time + this.timeToCall; + + // console.log('Time expect', this.timeExpected); + } + + if (this.advancedTiming) + { + this.updateAdvancedTiming(); + } + + // Paused but still running? + if (!this.game.paused) + { + // Our internal Phaser.Timer + this.events.update(this.time); + + if (this._timers.length) + { + this.updateTimers(); + } + } + + }, + + /** + * Handles the updating of the Phaser.Timers (if any) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateTimers + * @private + */ + updateTimers: function () { + + // Any game level timers + var i = 0; + var len = this._timers.length; + + while (i < len) + { + if (this._timers[i].update(this.time)) + { + i++; + } + else + { + // Timer requests to be removed + this._timers.splice(i, 1); + len--; + } + } + + }, + + /** + * Handles the updating of the advanced timing values (if enabled) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateAdvancedTiming + * @private + */ + updateAdvancedTiming: function () { + + // count the number of time.update calls + this._frameCount++; + this._elapsedAccumulator += this.elapsed; + + // occasionally recalculate the suggestedFps based on the accumulated elapsed time + if (this._frameCount >= this._desiredFps * 2) + { + // this formula calculates suggestedFps in multiples of 5 fps + this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5; + this._frameCount = 0; + this._elapsedAccumulator = 0; + } + + this.msMin = Math.min(this.msMin, this.elapsed); + this.msMax = Math.max(this.msMax, this.elapsed); + + this.frames++; + + if (this.now > this._timeLastSecond + 1000) + { + var interval = this.now - this._timeLastSecond; + this.fps = Math.round((this.frames * 1000) / interval); + this.ups = Math.round((this.updates * 1000) / interval); + this.rps = Math.round((this.renders * 1000) / interval); + this.fpsMin = Math.min(this.fpsMin, this.fps); + this.fpsMax = Math.max(this.fpsMax, this.fps); + this._timeLastSecond = this.now; + this.frames = 0; + this.updates = 0; + this.renders = 0; + } + + }, + + /** + * Counts one logic update (if advanced timing is enabled). + * + * @method Phaser.Time#countUpdate + * @private + */ + countUpdate: function () { + + if (this.advancedTiming) + { + this.updates++; + } + + }, + + /** + * Counts one render (if advanced timing is enabled). + * + * @method Phaser.Time#countRender + * @private + */ + countRender: function () { + + if (this.advancedTiming) + { + this.renders++; + } + + }, + + /** + * Called when the game enters a paused state. + * + * @method Phaser.Time#gamePaused + * @private + */ + gamePaused: function () { + + this._pauseStarted = Date.now(); + + this.events.pause(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._pause(); + } + + }, + + /** + * Called when the game resumes from a paused state. + * + * @method Phaser.Time#gameResumed + * @private + */ + gameResumed: function () { + + // Set the parameter which stores Date.now() to make sure it's correct on resume + this.time = Date.now(); + + this.pauseDuration = this.time - this._pauseStarted; + + this.events.resume(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._resume(); + } + + }, + + /** + * The number of seconds that have elapsed since the game was started. + * + * @method Phaser.Time#totalElapsedSeconds + * @return {number} The number of seconds that have elapsed since the game was started. + */ + totalElapsedSeconds: function() { + return (this.time - this._started) * 0.001; + }, + + /** + * How long has passed since the given time. + * + * @method Phaser.Time#elapsedSince + * @param {number} since - The time you want to measure against. + * @return {number} The difference between the given time and now. + */ + elapsedSince: function (since) { + return this.time - since; + }, + + /** + * How long has passed since the given time (in seconds). + * + * @method Phaser.Time#elapsedSecondsSince + * @param {number} since - The time you want to measure (in seconds). + * @return {number} Duration between given time and now (in seconds). + */ + elapsedSecondsSince: function (since) { + return (this.time - since) * 0.001; + }, + + /** + * Resets the private _started value to now and removes all currently running Timers. + * + * @method Phaser.Time#reset + */ + reset: function () { + + this._started = this.time; + this.removeAll(); + + } + +}; + +/** +* The number of logic updates per second. +* +* This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. +* +* The render rate is unaffected unless you also turn off {@link Phaser.Game#forceSingleRender}. +* +* @name Phaser.Time#desiredFps +* @type {integer} +* @default 60 +*/ +Object.defineProperty(Phaser.Time.prototype, "desiredFps", { + + get: function () { + + return this._desiredFps; + + }, + + set: function (value) { + + this._desiredFps = value; + + // Set the physics elapsed time... this will always be 1 / this.desiredFps + // because we're using fixed time steps in game.update + this.physicsElapsed = 1 / value; + + this.physicsElapsedMS = this.physicsElapsed * 1000; + + this.desiredFpsMult = 1.0 / value; + + } + +}); + +Phaser.Time.prototype.constructor = Phaser.Time; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback. +* Many different timer events, with individual delays, can be added to the same Timer. +* +* All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. +* +* Timers are based on real life time, adjusted for game pause durations. +* That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account. +* +* @class Phaser.Timer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). +*/ +Phaser.Timer = function (game, autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * True if the Timer is actively running. + * + * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer. + * @property {boolean} running + * @default + * @readonly + */ + this.running = false; + + /** + * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). + * @property {boolean} autoDestroy + */ + this.autoDestroy = autoDestroy; + + /** + * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending. + * @readonly + * @default + */ + this.expired = false; + + /** + * @property {number} elapsed - Elapsed time since the last frame (in ms). + * @protected + */ + this.elapsed = 0; + + /** + * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. + */ + this.events = []; + + /** + * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. + * + * The signal is supplied with one argument, `timer`, which is this Timer object. + * + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {number} nextTick - The time the next tick will occur. + * @readonly + * @protected + */ + this.nextTick = 0; + + /** + * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. + */ + this.timeCap = 1000; + + /** + * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. + * @readonly + * @default + */ + this.paused = false; + + /** + * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {number} _started - The time at which this Timer instance started running. + * @private + * @default + */ + this._started = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {number} _pauseTotal - Total paused time. + * @private + */ + this._pauseTotal = 0; + + /** + * @property {number} _now - The current start-time adjusted time. + * @private + */ + this._now = Date.now(); + + /** + * @property {number} _len - Temp. array length variable. + * @private + */ + this._len = 0; + + /** + * @property {number} _marked - Temp. counter variable. + * @private + */ + this._marked = 0; + + /** + * @property {number} _i - Temp. array counter variable. + * @private + */ + this._i = 0; + + /** + * @property {number} _diff - Internal cache var. + * @private + */ + this._diff = 0; + + /** + * @property {number} _newTick - Internal cache var. + * @private + */ + this._newTick = 0; + +}; + +/** +* Number of milliseconds in a minute. +* @constant +* @type {integer} +*/ +Phaser.Timer.MINUTE = 60000; + +/** +* Number of milliseconds in a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.SECOND = 1000; + +/** +* Number of milliseconds in half a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.HALF = 500; + +/** +* Number of milliseconds in a quarter of a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.QUARTER = 250; + +Phaser.Timer.prototype = { + + /** + * Creates a new TimerEvent on this Timer. + * + * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. + * + * @method Phaser.Timer#create + * @private + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {boolean} loop - Should the event loop or not? + * @param {number} repeatCount - The number of times the event will repeat. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {any[]} arguments - The values to be sent to your callback function when it is called. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + create: function (delay, loop, repeatCount, callback, callbackContext, args) { + + delay = Math.round(delay); + + var tick = delay; + + if (this._now === 0) + { + tick += this.game.time.time; + } + else + { + tick += this._now; + } + + var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args); + + this.events.push(event); + + this.order(); + + this.expired = false; + + return event; + + }, + + /** + * Adds a new Event to this Timer. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#add + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + add: function (delay, callback, callbackContext) { + + return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. + * If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#repeat + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + repeat: function (delay, repeatCount, callback, callbackContext) { + + return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4)); + + }, + + /** + * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#loop + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + loop: function (delay, callback, callbackContext) { + + return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Starts this Timer running. + * @method Phaser.Timer#start + * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start. + */ + start: function (delay) { + + if (this.running) + { + return; + } + + this._started = this.game.time.time + (delay || 0); + + this.running = true; + + for (var i = 0; i < this.events.length; i++) + { + this.events[i].tick = this.events[i].delay + this._started; + } + + }, + + /** + * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. + * @method Phaser.Timer#stop + * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain. + */ + stop: function (clearEvents) { + + this.running = false; + + if (clearEvents === undefined) { clearEvents = true; } + + if (clearEvents) + { + this.events.length = 0; + } + + }, + + /** + * Removes a pending TimerEvent from the queue. + * @param {Phaser.TimerEvent} event - The event to remove from the queue. + * @method Phaser.Timer#remove + */ + remove: function (event) { + + for (var i = 0; i < this.events.length; i++) + { + if (this.events[i] === event) + { + this.events[i].pendingDelete = true; + return true; + } + } + + return false; + + }, + + /** + * Orders the events on this Timer so they are in tick order. + * This is called automatically when new events are created. + * @method Phaser.Timer#order + * @protected + */ + order: function () { + + if (this.events.length > 0) + { + // Sort the events so the one with the lowest tick is first + this.events.sort(this.sortHandler); + + this.nextTick = this.events[0].tick; + } + + }, + + /** + * Sort handler used by Phaser.Timer.order. + * @method Phaser.Timer#sortHandler + * @private + */ + sortHandler: function (a, b) { + + if (a.tick < b.tick) + { + return -1; + } + else if (a.tick > b.tick) + { + return 1; + } + + return 0; + + }, + + /** + * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values. + * + * @method Phaser.Timer#clearPendingEvents + * @protected + */ + 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; + + }, + + /** + * The main Timer update event, called automatically by Phaser.Time.update. + * + * @method Phaser.Timer#update + * @protected + * @param {number} time - The time from the core game clock. + * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. + */ + update: function (time) { + + if (this.paused) + { + return true; + } + + this.elapsed = time - this._now; + this._now = time; + + // spike-dislike + if (this.elapsed > this.timeCap) + { + // For some reason the time between now and the last time the game was updated was larger than our timeCap. + // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause. + // In this case we need to adjust the TimerEvents and nextTick. + this.adjustEvents(time - this.elapsed); + } + + this._marked = 0; + + // Clears events marked for deletion and resets _len and _i to 0. + this.clearPendingEvents(); + + if (this.running && this._now >= this.nextTick && this._len > 0) + { + while (this._i < this._len && this.running) + { + var event = this.events[this._i]; + + if (this._now >= event.tick && !event.pendingDelete) + { + // (now + delay) - (time difference from last tick to now) + this._newTick = (this._now + event.delay) - (this._now - event.tick); + + if (this._newTick < 0) + { + this._newTick = this._now + event.delay; + } + + if (event.loop === true) + { + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else if (event.repeatCount > 0) + { + event.repeatCount--; + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else + { + this._marked++; + event.pendingDelete = true; + event.callback.apply(event.callbackContext, event.args); + } + + this._i++; + } + else + { + break; + } + } + + // Are there any events left? + 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; + } + + }, + + /** + * Pauses the Timer and all events in the queue. + * @method Phaser.Timer#pause + */ + pause: function () { + + if (!this.running) + { + return; + } + + this._codePaused = true; + + if (this.paused) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Internal pause/resume control - user code should use Timer.pause instead. + * @method Phaser.Timer#_pause + * @private + */ + _pause: function () { + + if (this.paused || !this.running) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Adjusts the time of all pending events and the nextTick by the given baseTime. + * + * @method Phaser.Timer#adjustEvents + * @protected + */ + adjustEvents: function (baseTime) { + + for (var i = 0; i < this.events.length; i++) + { + if (!this.events[i].pendingDelete) + { + // Work out how long there would have been from when the game paused until the events next tick + var t = this.events[i].tick - baseTime; + + if (t < 0) + { + t = 0; + } + + // Add the difference on to the time now + this.events[i].tick = this._now + t; + } + } + + var d = this.nextTick - baseTime; + + if (d < 0) + { + this.nextTick = this._now; + } + else + { + this.nextTick = this._now + d; + } + + }, + + /** + * Resumes the Timer and updates all pending events. + * + * @method Phaser.Timer#resume + */ + resume: function () { + + if (!this.paused) + { + return; + } + + var now = this.game.time.time; + this._pauseTotal += now - this._now; + this._now = now; + + this.adjustEvents(this._pauseStarted); + + this.paused = false; + this._codePaused = false; + + }, + + /** + * Internal pause/resume control - user code should use Timer.resume instead. + * @method Phaser.Timer#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#removeAll + */ + removeAll: function () { + + this.onComplete.removeAll(); + this.events.length = 0; + this._len = 0; + this._i = 0; + + }, + + /** + * Destroys this Timer. Any pending Events are not dispatched. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#destroy + */ + destroy: function () { + + this.onComplete.removeAll(); + this.running = false; + this.expired = true; + this.events = []; + this._len = 0; + this._i = 0; + + } + +}; + +/** +* @name Phaser.Timer#next +* @property {number} next - The time at which the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "next", { + + get: function () { + return this.nextTick; + } + +}); + +/** +* @name Phaser.Timer#duration +* @property {number} duration - The duration in ms remaining until the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "duration", { + + get: function () { + + if (this.running && this.nextTick > this._now) + { + return this.nextTick - this._now; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#length +* @property {number} length - The number of pending events in the queue. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "length", { + + get: function () { + return this.events.length; + } + +}); + +/** +* @name Phaser.Timer#ms +* @property {number} ms - The duration in milliseconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "ms", { + + get: function () { + + if (this.running) + { + return this._now - this._started - this._pauseTotal; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#seconds +* @property {number} seconds - The duration in seconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "seconds", { + + get: function () { + + if (this.running) + { + return this.ms * 0.001; + } + else + { + return 0; + } + + } + +}); + +Phaser.Timer.prototype.constructor = Phaser.Timer; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TimerEvent is a single event that is processed by a Phaser.Timer. +* +* It consists of a delay, which is a value in milliseconds after which the event will fire. +* When the event fires it calls a specific callback with the specified arguments. +* +* TimerEvents are removed by their parent timer once finished firing or repeating. +* +* Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. +* +* @class Phaser.TimerEvent +* @constructor +* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. +* @param {number} delay - The delay in ms at which this TimerEvent fires. +* @param {number} tick - The tick is the next game clock time that this event will fire at. +* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times. +* @param {boolean} loop - True if this TimerEvent loops, otherwise false. +* @param {function} callback - The callback that will be called when the TimerEvent occurs. +* @param {object} callbackContext - The context in which the callback will be called. +* @param {any[]} arguments - Additional arguments to be passed to the callback. +*/ +Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) { + + /** + * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. + * @protected + * @readonly + */ + this.timer = timer; + + /** + * @property {number} delay - The delay in ms at which this TimerEvent fires. + */ + this.delay = delay; + + /** + * @property {number} tick - The tick is the next game clock time that this event will fire at. + */ + this.tick = tick; + + /** + * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times. + */ + this.repeatCount = repeatCount - 1; + + /** + * @property {boolean} loop - True if this TimerEvent loops, otherwise false. + */ + this.loop = loop; + + /** + * @property {function} callback - The callback that will be called when the TimerEvent occurs. + */ + this.callback = callback; + + /** + * @property {object} callbackContext - The context in which the callback will be called. + */ + this.callbackContext = callbackContext; + + /** + * @property {any[]} arguments - Additional arguments to be passed to the callback. + */ + this.args = args; + + /** + * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion. + * @protected + */ + this.pendingDelete = false; + +}; + +Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Manager is used to add, play and update Phaser Animations. +* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. +* +* @class Phaser.AnimationManager +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. +*/ +Phaser.AnimationManager = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = sprite.game; + + /** + * The currently displayed Frame of animation, if any. + * This property is only set once an Animation starts playing. Until that point it remains set as `null`. + * + * @property {Phaser.Frame} currentFrame + * @default + */ + this.currentFrame = null; + + /** + * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any. + * @default + */ + this.currentAnim = null; + + /** + * @property {boolean} updateIfVisible - Update the animation data only while the the sprite is {@link Phaser.Sprite#visible}. Set to `false` to continue updating while the sprite is invisible. + * @default + */ + this.updateIfVisible = true; + + /** + * @property {boolean} isLoaded - Set to true once animation data has been loaded. + * @default + */ + this.isLoaded = false; + + /** + * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. + * @private + * @default + */ + this._frameData = null; + + /** + * @property {object} _anims - An internal object that stores all of the Animation instances. + * @private + */ + this._anims = {}; + + /** + * @property {object} _outputFrames - An internal object to help avoid gc. + * @private + */ + this._outputFrames = []; + +}; + +Phaser.AnimationManager.prototype = { + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#loadFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + loadFrameData: function (frameData, frame) { + + if (frameData === undefined) + { + return false; + } + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(frameData); + } + } + + this._frameData = frameData; + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#copyFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + copyFrameData: function (frameData, frame) { + + this._frameData = frameData.clone(); + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(this._frameData); + } + } + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. + * Animations added in this way are played back with the play function. + * + * @method Phaser.AnimationManager#add + * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". + * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. + * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. + * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? + * @return {Phaser.Animation} The Animation object that was created. + */ + add: function (name, frames, frameRate, loop, useNumericIndex) { + + frames = frames || []; + frameRate = frameRate || 60; + + if (loop === undefined) { loop = false; } + + // If they didn't set the useNumericIndex then let's at least try and guess it + if (useNumericIndex === undefined) + { + if (frames && typeof frames[0] === 'number') + { + useNumericIndex = true; + } + else + { + useNumericIndex = false; + } + } + + this._outputFrames = []; + + 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]; + + if (this.sprite.tilingTexture) + { + this.sprite.refreshTexture = true; + } + + return this._anims[name]; + + }, + + /** + * Check whether the frames in the given array are valid and exist. + * + * @method Phaser.AnimationManager#validateFrames + * @param {Array} frames - An array of frames to be validated. + * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) + * @return {boolean} True if all given Frames are valid, otherwise false. + */ + validateFrames: function (frames, useNumericIndex) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + + for (var i = 0; i < frames.length; i++) + { + if (useNumericIndex === true) + { + if (frames[i] > this._frameData.total) + { + return false; + } + } + else + { + if (this._frameData.checkFrameName(frames[i]) === false) + { + return false; + } + } + } + + return true; + + }, + + /** + * Play an animation based on the given key. The animation should previously have been added via `animations.add` + * + * If the requested animation is already playing this request will be ignored. + * If you need to reset an already running animation do so directly on the Animation object itself. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.AnimationManager#play + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation instance. + */ + 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); + } + + return this.currentAnim; + } + else + { + if (this.currentAnim && this.currentAnim.isPlaying) + { + this.currentAnim.stop(); + } + + this.currentAnim = this._anims[name]; + this.currentAnim.paused = false; + this.currentFrame = this.currentAnim.currentFrame; + return this.currentAnim.play(frameRate, loop, killOnComplete); + } + } + + }, + + /** + * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. + * The currentAnim property of the AnimationManager is automatically set to the animation given. + * + * @method Phaser.AnimationManager#stop + * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. + * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) + */ + stop: function (name, resetFrame) { + + if (resetFrame === undefined) { resetFrame = false; } + + if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name)) + { + this.currentAnim.stop(resetFrame); + } + + }, + + /** + * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. + * + * @method Phaser.AnimationManager#update + * @protected + * @return {boolean} True if a new animation frame has been set, otherwise false. + */ + update: function () { + + if (this.updateIfVisible && !this.sprite.visible) + { + return false; + } + + if (this.currentAnim && this.currentAnim.update()) + { + this.currentFrame = this.currentAnim.currentFrame; + return true; + } + + return false; + + }, + + /** + * Advances by the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.next(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Moves backwards the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.previous(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Returns an animation that was previously added by name. + * + * @method Phaser.AnimationManager#getAnimation + * @param {string} name - The name of the animation to be returned, e.g. "fire". + * @return {Phaser.Animation} The Animation instance, if found, otherwise null. + */ + getAnimation: function (name) { + + if (typeof name === 'string') + { + if (this._anims[name]) + { + return this._anims[name]; + } + } + + return null; + + }, + + /** + * Refreshes the current frame data back to the parent Sprite and also resets the texture data. + * + * @method Phaser.AnimationManager#refreshFrame + */ + refreshFrame: function () { + + // TODO + // this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); + + }, + + /** + * Destroys all references this AnimationManager contains. + * Iterates through the list of animations stored in this manager and calls destroy on each of them. + * + * @method Phaser.AnimationManager#destroy + */ + destroy: function () { + + var anim = null; + + for (var anim in this._anims) + { + if (this._anims.hasOwnProperty(anim)) + { + this._anims[anim].destroy(); + } + } + + this._anims = {}; + this._outputFrames = []; + this._frameData = null; + this.currentAnim = null; + this.currentFrame = null; + this.sprite = null; + this.game = null; + + } + +}; + +Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager; + +/** +* @name Phaser.AnimationManager#frameData +* @property {Phaser.FrameData} frameData - The current animations FrameData. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', { + + get: function () { + return this._frameData; + } + +}); + +/** +* @name Phaser.AnimationManager#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', { + + get: function () { + + return this._frameData.total; + } + +}); + +/** +* @name Phaser.AnimationManager#paused +* @property {boolean} paused - Gets and sets the paused state of the current animation. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', { + + get: function () { + + return this.currentAnim.isPaused; + + }, + + set: function (value) { + + this.currentAnim.paused = value; + + } + +}); + +/** +* @name Phaser.AnimationManager#name +* @property {string} name - Gets the current animation name, if set. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'name', { + + get: function () { + + if (this.currentAnim) + { + return this.currentAnim.name; + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.index; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'number' && this._frameData && (gotFrame = this._frameData.getFrame(value))) + { + this.currentFrame = gotFrame; + this.sprite.setFrame(this.currentFrame); + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frameName +* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.name; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'string' && this._frameData && (gotFrame = this._frameData.getFrameByName(value))) + { + this.currentFrame = gotFrame; + this._frameIndex = this.currentFrame.index; + this.sprite.setFrame(this.currentFrame); + } + else + { + console.warn('Cannot set frameName: ' + value); + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Animation instance contains a single animation and the controls to play it. +* +* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. +* +* @class Phaser.Animation +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Sprite} parent - A reference to the owner of this Animation. +* @param {string} name - The unique name for this animation, used in playback commands. +* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. +* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +*/ +Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) { + + if (loop === undefined) { loop = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. + * @private + */ + this._parent = parent; + + /** + * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. + * @private + */ + this._frameData = frameData; + + /** + * @property {string} name - The user defined name given to this Animation. + */ + this.name = name; + + /** + * @property {array} _frames + * @private + */ + this._frames = []; + this._frames = this._frames.concat(frames); + + /** + * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. + */ + this.delay = 1000 / frameRate; + + /** + * @property {boolean} loop - The loop state of the Animation. + */ + this.loop = loop; + + /** + * @property {number} loopCount - The number of times the animation has looped since it was last started. + */ + this.loopCount = 0; + + /** + * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? + * @default + */ + this.killOnComplete = false; + + /** + * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. + * @default + */ + this.isFinished = false; + + /** + * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. + * @default + */ + this.isPlaying = false; + + /** + * @property {boolean} isPaused - The paused state of the Animation. + * @default + */ + this.isPaused = false; + + /** + * @property {boolean} _pauseStartTime - The time the animation paused. + * @private + * @default + */ + this._pauseStartTime = 0; + + /** + * @property {number} _frameIndex + * @private + * @default + */ + this._frameIndex = 0; + + /** + * @property {number} _frameDiff + * @private + * @default + */ + this._frameDiff = 0; + + /** + * @property {number} _frameSkip + * @private + * @default + */ + this._frameSkip = 1; + + /** + * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. + */ + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + /** + * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. + */ + this.onStart = new Phaser.Signal(); + + /** + * This event is dispatched when the Animation changes frame. + * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. + * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations + * will automatically frame-skip to try and claw back time, so do not base your code on expecting to + * receive a perfectly sequential set of frames from this event. + * @property {Phaser.Signal|null} onUpdate + * @default + */ + this.onUpdate = null; + + /** + * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {boolean} isReversed - Indicates if the animation will play backwards. + * @default + */ + this.isReversed = false; + + // Set-up some event listeners + this.game.onPause.add(this.onPause, this); + this.game.onResume.add(this.onResume, this); + +}; + +Phaser.Animation.prototype = { + + /** + * Plays this animation. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.Animation#play + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} - A reference to this Animation instance. + */ + play: function (frameRate, loop, killOnComplete) { + + if (typeof frameRate === 'number') + { + // If they set a new frame rate then use it, otherwise use the one set on creation + this.delay = 1000 / frameRate; + } + + if (typeof loop === 'boolean') + { + // If they set a new loop value then use it, otherwise use the one set on creation + this.loop = loop; + } + + if (typeof killOnComplete !== 'undefined') + { + // Remove the parent sprite once the animation has finished? + this.killOnComplete = killOnComplete; + } + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = this.isReversed ? this._frames.length - 1 : 0; + this.updateCurrentFrame(false, true); + + this._parent.events.onAnimationStart$dispatch(this._parent, this); + + this.onStart.dispatch(this._parent, this); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + return this; + + }, + + /** + * Sets this animation back to the first frame and restarts the animation. + * + * @method Phaser.Animation#restart + */ + restart: function () { + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = 0; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + this._parent.setFrame(this.currentFrame); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + this.onStart.dispatch(this._parent, this); + + }, + + /** + * Reverses the animation direction. + * + * @method Phaser.Animation#reverse + * @return {Phaser.Animation} The animation instance. + */ + reverse: function () { + + this.reversed = !this.reversed; + + return this; + + }, + + /** + * Reverses the animation direction for the current/next animation only + * Once the onComplete event is called this method will be called again and revert + * the reversed state. + * + * @method Phaser.Animation#reverseOnce + * @return {Phaser.Animation} The animation instance. + */ + reverseOnce: function () { + + this.onComplete.addOnce(this.reverse, this); + + return this.reverse(); + + }, + + /** + * Sets this animations playback to a given frame with the given ID. + * + * @method Phaser.Animation#setFrame + * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. + * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. + */ + setFrame: function(frameId, useLocalFrameIndex) { + + var frameIndex; + + if (useLocalFrameIndex === undefined) + { + useLocalFrameIndex = false; + } + + // Find the index to the desired frame. + if (typeof frameId === "string") + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frameData.getFrame(this._frames[i]).name === frameId) + { + frameIndex = i; + } + } + } + else if (typeof frameId === "number") + { + if (useLocalFrameIndex) + { + frameIndex = frameId; + } + else + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frames[i] === frameId) + { + frameIndex = i; + } + } + } + } + + if (frameIndex) + { + // Set the current frame index to the found index. Subtract a directional offset so that it animates to the desired frame on update. + var directionalOffset = this.isReversed ? -1 : 1; + this._frameIndex = frameIndex - directionalOffset; + + // Make the animation update at next update + this._timeNextFrame = this.game.time.time; + + this.update(); + } + + }, + + /** + * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. + * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. + * + * @method Phaser.Animation#stop + * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. + * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? + */ + stop: function (resetFrame, dispatchComplete) { + + if (resetFrame === undefined) { resetFrame = false; } + if (dispatchComplete === undefined) { dispatchComplete = false; } + + this.isPlaying = false; + this.isFinished = true; + this.paused = false; + + if (resetFrame) + { + this.currentFrame = this._frameData.getFrame(this._frames[0]); + this._parent.setFrame(this.currentFrame); + } + + if (dispatchComplete) + { + this._parent.events.onAnimationComplete$dispatch(this._parent, this); + this.onComplete.dispatch(this._parent, this); + } + + }, + + /** + * Called when the Game enters a paused state. + * + * @method Phaser.Animation#onPause + */ + onPause: function () { + + if (this.isPlaying) + { + this._frameDiff = this._timeNextFrame - this.game.time.time; + } + + }, + + /** + * Called when the Game resumes from a paused state. + * + * @method Phaser.Animation#onResume + */ + onResume: function () { + + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this._frameDiff; + } + + }, + + /** + * Updates this animation. Called automatically by the AnimationManager. + * + * @method Phaser.Animation#update + */ + update: function () { + + if (this.isPaused) + { + return false; + } + + if (this.isPlaying && this.game.time.time >= this._timeNextFrame) + { + this._frameSkip = 1; + + // Lagging? + this._frameDiff = this.game.time.time - this._timeNextFrame; + + this._timeLastFrame = this.game.time.time; + + if (this._frameDiff > this.delay) + { + // We need to skip a frame, work out how many + this._frameSkip = Math.floor(this._frameDiff / this.delay); + this._frameDiff -= (this._frameSkip * this.delay); + } + else + { + this._frameDiff = 0; + } + + // And what's left now? + this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff); + + if (this.isReversed) + { + this._frameIndex -= this._frameSkip; + } + else + { + this._frameIndex += this._frameSkip; + } + + if (!this.isReversed && this._frameIndex >= this._frames.length || this.isReversed && this._frameIndex <= -1) + { + if (this.loop) + { + // Update current state before event callback + this._frameIndex = Math.abs(this._frameIndex) % this._frames.length; + + if (this.isReversed) + { + this._frameIndex = this._frames.length - 1 - this._frameIndex; + } + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + // Instead of calling updateCurrentFrame we do it here instead + if (this.currentFrame) + { + this._parent.setFrame(this.currentFrame); + } + + this.loopCount++; + this._parent.events.onAnimationLoop$dispatch(this._parent, this); + this.onLoop.dispatch(this._parent, this); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + } + else + { + this.complete(); + return false; + } + } + else + { + return this.updateCurrentFrame(true); + } + } + + return false; + + }, + + /** + * Changes the currentFrame per the _frameIndex, updates the display state, + * and triggers the update signal. + * + * Returns true if the current frame update was 'successful', false otherwise. + * + * @method Phaser.Animation#updateCurrentFrame + * @private + * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. + * @param {boolean} fromPlay - Was this call made from the playing of a new animation? + * @return {boolean} True if the current frame was updated, otherwise false. + */ + updateCurrentFrame: function (signalUpdate, fromPlay) { + + if (fromPlay === undefined) { fromPlay = false; } + + if (!this._frameData) + { + // The animation is already destroyed, probably from a callback + return false; + } + + // Previous index + var idx = this.currentFrame.index; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index))) + { + this._parent.setFrame(this.currentFrame); + } + + if (this.onUpdate && signalUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + + }, + + /** + * Advances by the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex + quantity; + + if (frame >= this._frames.length) + { + if (this.loop) + { + frame %= this._frames.length; + } + else + { + frame = this._frames.length - 1; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex - quantity; + + if (frame < 0) + { + if (this.loop) + { + frame = this._frames.length + frame; + } + else + { + frame++; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Changes the FrameData object this Animation is using. + * + * @method Phaser.Animation#updateFrameData + * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. + */ + updateFrameData: function (frameData) { + + this._frameData = frameData; + this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null; + + }, + + /** + * Cleans up this animation ready for deletion. Nulls all values and references. + * + * @method Phaser.Animation#destroy + */ + destroy: function () { + + if (!this._frameData) + { + // Already destroyed + return; + } + + 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(); + + if (this.onUpdate) + { + this.onUpdate.dispose(); + } + + }, + + /** + * Called internally when the animation finishes playback. + * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. + * + * @method Phaser.Animation#complete + */ + complete: function () { + + this._frameIndex = this._frames.length - 1; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + 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; + +/** +* @name Phaser.Animation#paused +* @property {boolean} paused - Gets and sets the paused state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'paused', { + + get: function () { + + return this.isPaused; + + }, + + set: function (value) { + + this.isPaused = value; + + if (value) + { + // Paused + this._pauseStartTime = this.game.time.time; + } + else + { + // Un-paused + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this.delay; + } + } + + } + +}); + +/** +* @name Phaser.Animation#reversed +* @property {boolean} reversed - Gets and sets the isReversed state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'reversed', { + + get: function () { + + return this.isReversed; + + }, + + set: function (value) { + + this.isReversed = value; + + } + +}); + +/** +* @name Phaser.Animation#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @name Phaser.Animation#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +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.setFrame(this.currentFrame); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + } + } + + } + +}); + +/** +* @name Phaser.Animation#speed +* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'speed', { + + get: function () { + + return 1000 / this.delay; + + }, + + set: function (value) { + + if (value > 0) + { + this.delay = 1000 / value; + } + + } + +}); + +/** +* @name Phaser.Animation#enableUpdate +* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { + + get: function () { + + return (this.onUpdate !== null); + + }, + + set: function (value) { + + if (value && this.onUpdate === null) + { + this.onUpdate = new Phaser.Signal(); + } + else if (!value && this.onUpdate !== null) + { + this.onUpdate.dispose(); + this.onUpdate = null; + } + + } + +}); + +/** +* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. +* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' +* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); +* +* @method Phaser.Animation.generateFrameNames +* @static +* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. +* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. +* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. +* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'. +* @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. +* @return {string[]} An array of framenames. +*/ +Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { + + if (suffix === undefined) { suffix = ''; } + + var output = []; + var frame = ''; + + if (start < stop) + { + for (var i = start; i <= stop; i++) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + else + { + for (var i = start; i >= stop; i--) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + + return output; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Frame is a single frame of an animation and is part of a FrameData collection. +* +* @class Phaser.Frame +* @constructor +* @param {number} index - The index of this Frame within the FrameData set it is being added to. +* @param {number} x - X position of the frame within the texture image. +* @param {number} y - Y position of the frame within the texture image. +* @param {number} width - Width of the frame within the texture image. +* @param {number} height - Height of the frame within the texture image. +* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. +*/ +Phaser.Frame = function (index, x, y, width, height, name) { + + /** + * @property {number} index - The index of this Frame within the FrameData set it is being added to. + */ + this.index = index; + + /** + * @property {number} x - X position within the image to cut from. + */ + this.x = x; + + /** + * @property {number} y - Y position within the image to cut from. + */ + this.y = y; + + /** + * @property {number} width - Width of the frame. + */ + this.width = width; + + /** + * @property {number} height - Height of the frame. + */ + this.height = height; + + if (this.width === 0 || this.height === 0) + { + console.warn('Phaser.Frame: Frame "' + this.name + '" has a width or height of zero'); + } + + /** + * @property {string} name - Useful for Texture Atlas files (is set to the filename value). + */ + this.name = name; + + /** + * @property {number} centerX - Center X position within the image to cut from. + */ + this.centerX = Math.floor(width / 2); + + /** + * @property {number} centerY - Center Y position within the image to cut from. + */ + this.centerY = Math.floor(height / 2); + + /** + * @property {number} distance - The distance from the top left to the bottom-right of this Frame. + */ + this.distance = Phaser.Math.distance(0, 0, width, height); + + /** + * @property {boolean} rotated - Is the frame rotated in the source texture? + * @default + */ + this.rotated = false; + + /** + * @property {boolean} trimmed - Was it trimmed when packed? + * @default + */ + this.trimmed = false; + + /** + * @property {number} sourceSizeW - Width of the original sprite before it was trimmed. + */ + this.sourceSizeW = width; + + /** + * @property {number} sourceSizeH - Height of the original sprite before it was trimmed. + */ + this.sourceSizeH = height; + + /** + * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeX = 0; + + /** + * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeY = 0; + + /** + * @property {number} spriteSourceSizeW - Width of the trimmed sprite. + * @default + */ + this.spriteSourceSizeW = 0; + + /** + * @property {number} spriteSourceSizeH - Height of the trimmed sprite. + * @default + */ + this.spriteSourceSizeH = 0; + + /** + * @property {number} right - The right of the Frame (x + width). + */ + this.right = this.x + this.width; + + /** + * @property {number} bottom - The bottom of the frame (y + height). + */ + this.bottom = this.y + this.height; + +}; + +Phaser.Frame.prototype = { + + /** + * Adjusts of all the Frame properties based on the given width and height values. + * + * @method Phaser.Frame#resize + * @param {integer} width - The new width of the Frame. + * @param {integer} height - The new height of the Frame. + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + this.centerX = Math.floor(width / 2); + this.centerY = Math.floor(height / 2); + this.distance = Phaser.Math.distance(0, 0, width, height); + this.sourceSizeW = width; + this.sourceSizeH = height; + this.right = this.x + width; + this.bottom = this.y + height; + + }, + + /** + * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. + * + * @method Phaser.Frame#setTrim + * @param {boolean} trimmed - If this frame was trimmed or not. + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + */ + setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { + + this.trimmed = trimmed; + + if (trimmed) + { + 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; + } + + }, + + /** + * Clones this Frame into a new Phaser.Frame object and returns it. + * Note that all properties are cloned, including the name and index. + * + * @method Phaser.Frame#clone + * @return {Phaser.Frame} An exact copy of this Frame object. + */ + clone: function () { + + var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name); + + for (var prop in this) + { + if (this.hasOwnProperty(prop)) + { + output[prop] = this[prop]; + } + } + + return output; + + }, + + /** + * Returns a Rectangle set to the dimensions of this Frame. + * + * @method Phaser.Frame#getRect + * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to. + * @return {Phaser.Rectangle} A rectangle. + */ + getRect: function (out) { + + if (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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. +* +* @class Phaser.FrameData +* @constructor +*/ +Phaser.FrameData = function () { + + /** + * @property {Array} _frames - Local array of frames. + * @private + */ + this._frames = []; + + /** + * @property {Array} _frameNames - Local array of frame names for name to index conversions. + * @private + */ + this._frameNames = []; + +}; + +Phaser.FrameData.prototype = { + + /** + * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. + * + * @method Phaser.FrameData#addFrame + * @param {Phaser.Frame} frame - The frame to add to this FrameData set. + * @return {Phaser.Frame} The frame that was just added. + */ + addFrame: function (frame) { + + frame.index = this._frames.length; + + this._frames.push(frame); + + if (frame.name !== '') + { + this._frameNames[frame.name] = frame.index; + } + + return frame; + + }, + + /** + * Get a Frame by its numerical index. + * + * @method Phaser.FrameData#getFrame + * @param {number} index - The index of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or undefined. + */ + getFrame: function (index) { + + if (index >= this._frames.length) + { + index = 0; + } + + return this._frames[index]; + + }, + + /** + * Get a Frame by its frame name. + * + * @method Phaser.FrameData#getFrameByName + * @param {string} name - The name of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or null. + */ + getFrameByName: function (name) { + + if (typeof this._frameNames[name] === 'number') + { + return this._frames[this._frameNames[name]]; + } + + return null; + + }, + + /** + * Check if there is a Frame with the given name. + * + * @method Phaser.FrameData#checkFrameName + * @param {string} name - The name of the frame you want to check. + * @return {boolean} True if the frame is found, otherwise false. + */ + checkFrameName: function (name) { + + if (this._frameNames[name] == null) + { + return false; + } + + return true; + + }, + + /** + * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains. + * + * @method Phaser.FrameData#clone + * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains. + */ + clone: function () { + + var output = new Phaser.FrameData(); + + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output._frames.push(this._frames[i].clone()); + } + + for (var p in this._frameNames) + { + if (this._frameNames.hasOwnProperty(p)) + { + output._frameNames.push(this._frameNames[p]); + } + } + + return output; + + }, + + /** + * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. + * + * @method Phaser.FrameData#getFrameRange + * @param {number} start - The starting frame index. + * @param {number} end - The ending frame index. + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. + */ + getFrameRange: function (start, end, output) { + + if (output === undefined) { output = []; } + + for (var i = start; i <= end; i++) + { + output.push(this._frames[i]); + } + + return output; + + }, + + /** + * Returns all of the Frames in this FrameData set where the frame index is found in the input array. + * The frames are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrames + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. + */ + getFrames: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + // We only need the indexes + output.push(this._frames[i]); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the input array contain names or indexes? + if (useNumericIndex) + { + // The actual frame + output.push(this.getFrame(frames[i])); + } + else + { + // The actual frame + output.push(this.getFrameByName(frames[i])); + } + } + } + + return output; + + }, + + /** + * Returns all of the Frame indexes in this FrameData set. + * The frames indexes are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrameIndexes + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frame indexes matching the given names or IDs. + */ + getFrameIndexes: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No frames array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output.push(this._frames[i].index); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the frames array contain names or indexes? + if (useNumericIndex && this._frames[frames[i]]) + { + output.push(this._frames[frames[i]].index); + } + else + { + if (this.getFrameByName(frames[i])) + { + output.push(this.getFrameByName(frames[i]).index); + } + } + } + } + + return output; + + }, + + /** + * Destroys this FrameData collection by nulling the _frames and _frameNames arrays. + * + * @method Phaser.FrameData#destroy + */ + destroy: function () { + + this._frames = null; + this._frameNames = null; + + } + +}; + +Phaser.FrameData.prototype.constructor = Phaser.FrameData; + +/** +* @name Phaser.FrameData#total +* @property {number} total - The total number of frames in this FrameData set. +* @readonly +*/ +Object.defineProperty(Phaser.FrameData.prototype, "total", { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +* +* @class Phaser.AnimationParser +* @static +*/ +Phaser.AnimationParser = { + + /** + * Parse a Sprite Sheet and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.spriteSheet + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. + * @param {number} frameWidth - The fixed width of each frame of the animation. + * @param {number} frameHeight - The fixed height of each frame of the animation. + * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + var img = key; + + if (typeof key === 'string') + { + img = game.cache.getImage(key); + } + + if (img === null) + { + return null; + } + + var width = img.width; + var height = img.height; + + if (frameWidth <= 0) + { + frameWidth = Math.floor(-width / Math.min(-1, frameWidth)); + } + + if (frameHeight <= 0) + { + frameHeight = Math.floor(-height / Math.min(-1, frameHeight)); + } + + var row = Math.floor((width - margin) / (frameWidth + spacing)); + var column = Math.floor((height - margin) / (frameHeight + spacing)); + var total = row * column; + + if (skipFrames > total || skipFrames < -total) + { + console.warn( + "Phaser.AnimationParser.spriteSheet: skipFrames = " + + skipFrames.toString() + " is larger than total sprite number " + + total.toString()); + return null; + } + + if (skipFrames < 0) + { + // Allow negative skipframes. + skipFrames = total + skipFrames; + } + + if (frameMax !== -1) + { + total = skipFrames + frameMax; + } + + // Zero or smaller than frame sizes? + if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0) + { + console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight"); + return null; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var x = margin; + var y = margin; + + for (var i = 0; i < total; i++) + { + data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '')); + + x += frameWidth + spacing; + + if (x + frameWidth > width) + { + x = margin; + y += frameHeight + spacing; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONData: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].frame.x, + frames[i].frame.y, + frames[i].frame.w, + frames[i].frame.h, + frames[i].filename + )); + + if (frames[i].trimmed) + { + newFrame.setTrim( + frames[i].trimmed, + frames[i].sourceSize.w, + frames[i].sourceSize.h, + frames[i].spriteSourceSize.x, + frames[i].spriteSourceSize.y, + frames[i].spriteSourceSize.w, + frames[i].spriteSourceSize.h + ); + } + + if (frames[i].rotated) + { + newFrame.rotated = true; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataPyxel + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataPyxel: function (game, json) { + + // Malformed? There are a few keys to check here. + var signature = ['layers', 'tilewidth','tileheight','tileswide', 'tileshigh']; + + signature.forEach( function(key) { + if (!json[key]) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "' + key + '" key.'); + console.log(json); + return; + } + }); + + // For this purpose, I only care about parsing tilemaps with a single layer. + if (json['layers'].length !== 1) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps.'); + console.log(json); + return; + } + + var data = new Phaser.FrameData(); + + var tileheight = json['tileheight']; + var tilewidth = json['tilewidth']; + + var frames = json['layers'][0]['tiles']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].x, + frames[i].y, + tilewidth, + tileheight, + "frame_" + i // No names are included in pyxel tilemap data. + )); + + // No trim data is included. + newFrame.setTrim(false); + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataHash + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataHash: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + var i = 0; + + for (var key in frames) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[key].frame.x, + frames[key].frame.y, + frames[key].frame.w, + frames[key].frame.h, + key + )); + + if (frames[key].trimmed) + { + newFrame.setTrim( + frames[key].trimmed, + frames[key].sourceSize.w, + frames[key].sourceSize.h, + frames[key].spriteSourceSize.x, + frames[key].spriteSourceSize.y, + frames[key].spriteSourceSize.w, + frames[key].spriteSourceSize.h + ); + } + + if (frames[key].rotated) + { + newFrame.rotated = true; + } + + i++; + } + + return data; + + }, + + /** + * Parse the XML data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.XMLData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + XMLData: function (game, xml) { + + // Malformed? + if (!xml.getElementsByTagName('TextureAtlas')) + { + console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing tag"); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var frames = xml.getElementsByTagName('SubTexture'); + var newFrame; + + var name; + var frame; + var x; + var y; + var width; + var height; + var frameX; + var frameY; + var frameWidth; + var frameHeight; + + for (var i = 0; i < frames.length; i++) + { + frame = frames[i].attributes; + + name = frame.name.value; + x = parseInt(frame.x.value, 10); + y = parseInt(frame.y.value, 10); + width = parseInt(frame.width.value, 10); + height = parseInt(frame.height.value, 10); + + frameX = null; + frameY = null; + + if (frame.frameX) + { + frameX = Math.abs(parseInt(frame.frameX.value, 10)); + frameY = Math.abs(parseInt(frame.frameY.value, 10)); + frameWidth = parseInt(frame.frameWidth.value, 10); + frameHeight = parseInt(frame.frameHeight.value, 10); + } + + newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name)); + + // Trimmed? + if (frameX !== null || frameY !== null) + { + newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight); + } + } + + return data; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser has one single cache in which it stores all assets. +* +* The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using +* a unique string-based key as their identifier. Assets stored in different areas of the cache can have the +* same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, +* because they are unique data types. +* +* The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets +* such as images they are automatically placed into their respective cache. Most common Game Objects, such as +* Sprites and Videos automatically query the cache to extract the assets they need on instantiation. +* +* You can access the cache from within a State via `this.cache`. From here you can call any public method it has, +* including adding new entries to it, deleting them or querying them. +* +* Understand that almost without exception when you get an item from the cache it will return a reference to the +* item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original +* object in the cache will also be updated, even if you don't put it back into the cache again. +* +* By default when you change State the cache is _not_ cleared, although there is an option to clear it should +* your game require it. In a typical game set-up the cache is populated once after the main game has loaded and +* then used as an asset store. +* +* @class Phaser.Cache +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Cache = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. + * @property {boolean} autoResolveURL + */ + this.autoResolveURL = false; + + /** + * The main cache object into which all resources are placed. + * @property {object} _cache + * @private + */ + this._cache = { + canvas: {}, + image: {}, + texture: {}, + sound: {}, + video: {}, + text: {}, + json: {}, + xml: {}, + physics: {}, + tilemap: {}, + binary: {}, + bitmapData: {}, + bitmapFont: {}, + shader: {}, + renderTexture: {}, + compressedTexture: {} + }; + + /** + * @property {object} _urlMap - Maps URLs to resources. + * @private + */ + this._urlMap = {}; + + /** + * @property {Image} _urlResolver - Used to resolve URLs to the absolute path. + * @private + */ + this._urlResolver = new Image(); + + /** + * @property {string} _urlTemp - Temporary variable to hold a resolved url. + * @private + */ + this._urlTemp = null; + + /** + * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices. + */ + this.onSoundUnlock = new Phaser.Signal(); + + /** + * @property {array} _cacheMap - Const to cache object look-up array. + * @private + */ + this._cacheMap = []; + + this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas; + this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image; + this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture; + this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound; + this._cacheMap[Phaser.Cache.TEXT] = this._cache.text; + this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics; + this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap; + this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary; + this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData; + this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont; + this._cacheMap[Phaser.Cache.JSON] = this._cache.json; + this._cacheMap[Phaser.Cache.XML] = this._cache.xml; + this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video; + this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader; + this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture; + + /** + * @property {number} + * @private + */ + this._pendingCount = 0; + + /** + * Dispatched when the DEFAULT and MISSING images have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). + * + * @property {Phaser.Signal} onReady + */ + this.onReady = new Phaser.Signal(); + + this._addImages(); + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.CANVAS = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.IMAGE = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXTURE = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SOUND = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXT = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.PHYSICS = 6; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TILEMAP = 7; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BINARY = 8; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPDATA = 9; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPFONT = 10; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.JSON = 11; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.XML = 12; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.VIDEO = 13; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SHADER = 14; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.RENDER_TEXTURE = 15; + +/** +* The default image used for a texture when no other is specified. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.DEFAULT = null; + +/** + * Key for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_KEY = '__default'; + +/** + * URL for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='; + +/** +* The default image used for a texture when the source image is missing. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.MISSING = null; + +/** + * Key for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_KEY = '__missing'; + +/** + * URL for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='; + +/** +* The maximum amount of time (ms) to wait for the built-in DEFAULT and MISSING images to load. +* @static +* @type {number} +* @default +*/ +Phaser.Cache.READY_TIMEOUT = 1000; + +Phaser.Cache.prototype = { + + ////////////////// + // Add Methods // + ////////////////// + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCompressedTextureMetaData + * @private + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url + * @param {string} extension + * @param {array} arrayBuffer + * @return {object} The compressed texture entry. + */ + addCompressedTextureMetaData: function (key, url, extension, arrayBuffer) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + var data = (extension in Phaser.LoaderParser) ? Phaser.LoaderParser[extension](arrayBuffer) : arrayBuffer; + + var texture = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData(), + fileFormat: extension + }; + + texture.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = texture; + + this._resolveURL(url, texture); + + return texture; + + }, + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCanvas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {HTMLCanvasElement} canvas - The Canvas DOM element. + * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`. + */ + addCanvas: function (key, canvas, context) { + + if (context === undefined) { context = canvas.getContext('2d'); } + + this._cache.canvas[key] = { canvas: canvas, context: context }; + + }, + + /** + * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. + * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. + * + * If the image has not yet been fetched (successfully or not), a `console.warn` message will be displayed. + * + * @method Phaser.Cache#addImage + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra image data. + * @return {object} The full image object that was added to the cache. + */ + addImage: function (key, url, data) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + if (data.complete === false) + { + console.warn('Phaser.Cache.addImage: Image "' + key + '" hasn\'t been retrieved yet'); + } + + var img = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData() + }; + + img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = img; + + this._resolveURL(url, img); + + if (key === '__default') + { + Phaser.Cache.DEFAULT = new PIXI.Texture(img.base); + } + else if (key === '__missing') + { + Phaser.Cache.MISSING = new PIXI.Texture(img.base); + } + + return img; + + }, + + /** + * @method Phaser.Cache#addImageAsync + * @private + */ + addImageAsync: function (key, src, callback) { + + var self = this; + var img = new Image(); + + img.onload = function () { + callback.call(this, self.addImage(key, null, img)); + self._removePending(); + img.onload = null; + }; + + this._addPending(); + img.src = src; + + }, + + /** + * Adds a default image to be used in special cases such as WebGL Filters. + * It uses the special reserved key of `__default`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addDefaultImage + * @protected + */ + addDefaultImage: function () { + + this.addImageAsync(Phaser.Cache.DEFAULT_KEY, Phaser.Cache.DEFAULT_SRC, function (obj) { + // Because we don't want to invalidate the sprite batch for an invisible texture + obj.base.skipRender = true; + + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.DEFAULT = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds an image to be used when a key is wrong / missing. + * It uses the special reserved key of `__missing`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addMissingImage + * @protected + */ + addMissingImage: function () { + + this.addImageAsync(Phaser.Cache.MISSING_KEY, Phaser.Cache.MISSING_SRC, function (obj) { + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.MISSING = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addSound + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sound data. + * @param {boolean} webAudio - True if the file is using web audio. + * @param {boolean} audioTag - True if the file is using legacy HTML audio. + */ + addSound: function (key, url, data, webAudio, audioTag) { + + if (webAudio === undefined) { webAudio = true; audioTag = false; } + if (audioTag === undefined) { webAudio = false; audioTag = true; } + + var decoded = false; + + if (audioTag) + { + decoded = true; + } + + this._cache.sound[key] = { + url: url, + data: data, + isDecoding: false, + decoded: decoded, + webAudio: webAudio, + audioTag: audioTag, + locked: this.game.sound.touchLocked + }; + + this._resolveURL(url, this._cache.sound[key]); + + }, + + /** + * Add a new text data. + * + * @method Phaser.Cache#addText + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addText: function (key, url, data) { + + this._cache.text[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.text[key]); + + }, + + /** + * Add a new physics data object to the Cache. + * + * @method Phaser.Cache#addPhysicsData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} JSONData - The physics data object (a JSON file). + * @param {number} format - The format of the physics data. + */ + addPhysicsData: function (key, url, JSONData, format) { + + this._cache.physics[key] = { url: url, data: JSONData, format: format }; + + this._resolveURL(url, this._cache.physics[key]); + + }, + + /** + * Add a new tilemap to the Cache. + * + * @method Phaser.Cache#addTilemap + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} mapData - The tilemap data object (either a CSV or JSON file). + * @param {number} format - The format of the tilemap data. + */ + addTilemap: function (key, url, mapData, format) { + + this._cache.tilemap[key] = { url: url, data: mapData, format: format }; + + this._resolveURL(url, this._cache.tilemap[key]); + + }, + + /** + * Add a binary object in to the cache. + * + * @method Phaser.Cache#addBinary + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {object} binaryData - The binary object to be added to the cache. + */ + addBinary: function (key, binaryData) { + + this._cache.binary[key] = binaryData; + + }, + + /** + * Add a BitmapData object to the cache. + * + * @method Phaser.Cache#addBitmapData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. + * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. + * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. + */ + addBitmapData: function (key, bitmapData, frameData) { + + bitmapData.key = key; + + if (frameData === undefined) + { + frameData = new Phaser.FrameData(); + frameData.addFrame(bitmapData.textureFrame); + } + + this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData }; + + return bitmapData; + + }, + + /** + * Add a new Bitmap Font to the Cache. + * + * @method Phaser.Cache#addBitmapFont + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra font data. + * @param {object} atlasData - The Bitmap Font data. + * @param {string} [atlasType='xml'] - The format of the Bitmap Font data file: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) { + + var obj = { + url: url, + data: data, + font: null, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + if (atlasType === 'json') + { + obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + else + { + obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new Bitmap Font to the Cache, where the font texture is part of a Texture Atlas. + * + * The atlas must already exist in the cache, and be available based on the given `atlasKey`. + * + * The `atlasFrame` specifies the name of the frame within the atlas that the Bitmap Font is + * stored in. + * + * The `dataKey` is the key of the XML or JSON Bitmap Font Data, which must already be in + * the Cache. + * + * @method Phaser.Cache#addBitmapFontFromAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} atlasKey - The key of the Texture Atlas in the Cache. + * @param {string} atlasFrame - The frame of the Texture Atlas that the Bitmap Font is in. + * @param {string} dataKey - The key of the Bitmap Font data in the Cache + * @param {string} [dataType='xml'] - The format of the Bitmap Font data: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFontFromAtlas: function (key, atlasKey, atlasFrame, dataKey, dataType, xSpacing, ySpacing) { + + var frame = this.getFrameByName(atlasKey, atlasFrame); + + if (!frame) + { + return; + } + + var obj = { + font: null, + base: this.getBaseTexture(atlasKey), + frame: frame + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + var fontData; + + if (dataType === 'json') + { + fontData = this.getJSON(dataKey); + obj.font = Phaser.LoaderParser.jsonBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + else + { + fontData = this.getXML(dataKey); + obj.font = Phaser.LoaderParser.xmlBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + }, + + /** + * Add a new json object into the cache. + * + * @method Phaser.Cache#addJSON + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra json data. + */ + addJSON: function (key, url, data) { + + this._cache.json[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.json[key]); + + }, + + /** + * Add a new xml object into the cache. + * + * @method Phaser.Cache#addXML + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addXML: function (key, url, data) { + + this._cache.xml[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.xml[key]); + + }, + + /** + * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addVideo + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra video data. + * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. + */ + addVideo: function (key, url, data, isBlob) { + + this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true }; + + this._resolveURL(url, this._cache.video[key]); + + }, + + /** + * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addShader + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra shader data. + */ + addShader: function (key, url, data) { + + this._cache.shader[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.shader[key]); + + }, + + /** + * Add a new Phaser.RenderTexture in to the cache. + * + * @method Phaser.Cache#addRenderTexture + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture. + */ + addRenderTexture: function (key, texture) { + + this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') }; + + }, + + /** + * Add a new sprite sheet in to the cache. + * + * @method Phaser.Cache#addSpriteSheet + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sprite sheet data. + * @param {number} frameWidth - Width of the sprite sheet. + * @param {number} frameHeight - Height of the sprite sheet. + * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + */ + addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + var obj = { + key: key, + url: url, + data: data, + frameWidth: frameWidth, + frameHeight: frameHeight, + margin: margin, + spacing: spacing, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) + }; + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new texture atlas to the Cache. + * + * @method Phaser.Cache#addTextureAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra texture atlas data. + * @param {object} atlasData - Texture atlas frames data. + * @param {number} format - The format of the texture atlas. + */ + addTextureAtlas: function (key, url, data, atlasData, format) { + + var obj = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key); + } + else if (format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + obj.frameData = Phaser.AnimationParser.JSONDataPyxel(this.game, atlasData, key); + } + else + { + // Let's just work it out from the frames array + if (Array.isArray(atlasData.frames)) + { + obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key); + } + else + { + obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key); + } + } + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + //////////////////////////// + // Sound Related Methods // + //////////////////////////// + + /** + * Reload a Sound file from the server. + * + * @method Phaser.Cache#reloadSound + * @param {string} key - The key of the asset within the cache. + */ + reloadSound: function (key) { + + var _this = this; + + var sound = this.getSound(key); + + if (sound) + { + sound.data.src = sound.url; + + sound.data.addEventListener('canplaythrough', function () { + return _this.reloadSoundComplete(key); + }, false); + + sound.data.load(); + } + + }, + + /** + * Fires the onSoundUnlock event when the sound has completed reloading. + * + * @method Phaser.Cache#reloadSoundComplete + * @param {string} key - The key of the asset within the cache. + */ + reloadSoundComplete: function (key) { + + var sound = this.getSound(key); + + if (sound) + { + sound.locked = false; + this.onSoundUnlock.dispatch(key); + } + + }, + + /** + * Updates the sound object in the cache. + * + * @method Phaser.Cache#updateSound + * @param {string} key - The key of the asset within the cache. + */ + updateSound: function (key, property, value) { + + var sound = this.getSound(key); + + if (sound) + { + sound[property] = value; + } + + }, + + /** + * Add a new decoded sound. + * + * @method Phaser.Cache#decodedSound + * @param {string} key - The key of the asset within the cache. + * @param {object} data - Extra sound data. + */ + decodedSound: function (key, data) { + + var sound = this.getSound(key); + + sound.data = data; + sound.decoded = true; + sound.isDecoding = false; + + }, + + /** + * Check if the given sound has finished decoding. + * + * @method Phaser.Cache#isSoundDecoded + * @param {string} key - The key of the asset within the cache. + * @return {boolean} The decoded state of the Sound object. + */ + isSoundDecoded: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return sound.decoded; + } + + }, + + /** + * Check if the given sound is ready for playback. + * A sound is considered ready when it has finished decoding and the device is no longer touch locked. + * + * @method Phaser.Cache#isSoundReady + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the sound is decoded and the device is not touch locked. + */ + isSoundReady: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return (sound.decoded && !this.game.sound.touchLocked); + } + + }, + + //////////////////////// + // Check Key Methods // + //////////////////////// + + /** + * Checks if a key for the given cache object type exists. + * + * @method Phaser.Cache#checkKey + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists, otherwise false. + */ + checkKey: function (cache, key) { + + if (this._cacheMap[cache][key]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given URL has been loaded into the Cache. + * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. + * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox + * which may cause double-load instances. + * + * @method Phaser.Cache#checkURL + * @param {string} url - The url to check for in the cache. + * @return {boolean} True if the url exists, otherwise false. + */ + checkURL: function (url) { + + if (this._urlMap[this._resolveURL(url)]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given key exists in the Canvas Cache. + * + * @method Phaser.Cache#checkCanvasKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkCanvasKey: function (key) { + + return this.checkKey(Phaser.Cache.CANVAS, key); + + }, + + /** + * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. + * + * @method Phaser.Cache#checkImageKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkImageKey: function (key) { + + return this.checkKey(Phaser.Cache.IMAGE, key); + + }, + + /** + * Checks if the given key exists in the Texture Cache. + * + * @method Phaser.Cache#checkTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXTURE, key); + + }, + + /** + * Checks if the given key exists in the Sound Cache. + * + * @method Phaser.Cache#checkSoundKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkSoundKey: function (key) { + + return this.checkKey(Phaser.Cache.SOUND, key); + + }, + + /** + * Checks if the given key exists in the Text Cache. + * + * @method Phaser.Cache#checkTextKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXT, key); + + }, + + /** + * Checks if the given key exists in the Physics Cache. + * + * @method Phaser.Cache#checkPhysicsKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkPhysicsKey: function (key) { + + return this.checkKey(Phaser.Cache.PHYSICS, key); + + }, + + /** + * Checks if the given key exists in the Tilemap Cache. + * + * @method Phaser.Cache#checkTilemapKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTilemapKey: function (key) { + + return this.checkKey(Phaser.Cache.TILEMAP, key); + + }, + + /** + * Checks if the given key exists in the Binary Cache. + * + * @method Phaser.Cache#checkBinaryKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBinaryKey: function (key) { + + return this.checkKey(Phaser.Cache.BINARY, key); + + }, + + /** + * Checks if the given key exists in the BitmapData Cache. + * + * @method Phaser.Cache#checkBitmapDataKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapDataKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPDATA, key); + + }, + + /** + * Checks if the given key exists in the BitmapFont Cache. + * + * @method Phaser.Cache#checkBitmapFontKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapFontKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPFONT, key); + + }, + + /** + * Checks if the given key exists in the JSON Cache. + * + * @method Phaser.Cache#checkJSONKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkJSONKey: function (key) { + + return this.checkKey(Phaser.Cache.JSON, key); + + }, + + /** + * Checks if the given key exists in the XML Cache. + * + * @method Phaser.Cache#checkXMLKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkXMLKey: function (key) { + + return this.checkKey(Phaser.Cache.XML, key); + + }, + + /** + * Checks if the given key exists in the Video Cache. + * + * @method Phaser.Cache#checkVideoKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkVideoKey: function (key) { + + return this.checkKey(Phaser.Cache.VIDEO, key); + + }, + + /** + * Checks if the given key exists in the Fragment Shader Cache. + * + * @method Phaser.Cache#checkShaderKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkShaderKey: function (key) { + + return this.checkKey(Phaser.Cache.SHADER, key); + + }, + + /** + * Checks if the given key exists in the Render Texture Cache. + * + * @method Phaser.Cache#checkRenderTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkRenderTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key); + + }, + + //////////////// + // Get Items // + //////////////// + + /** + * Get an item from a cache based on the given key and property. + * + * This method is mostly used internally by other Cache methods such as `getImage` but is exposed + * publicly for your own use as well. + * + * @method Phaser.Cache#getItem + * @param {string} key - The key of the asset within the cache. + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output. + * @param {string} [property] - If you require a specific property from the cache item, specify it here. + * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. + */ + getItem: function (key, cache, method, property) { + + if (!this.checkKey(cache, key)) + { + if (method) + { + console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.'); + } + } + else + { + if (property === undefined) + { + return this._cacheMap[cache][key]; + } + else + { + return this._cacheMap[cache][key][property]; + } + } + + return null; + + }, + + /** + * Gets a Canvas object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getCanvas + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The canvas object or `null` if no item could be found matching the given key. + */ + getCanvas: function (key) { + + return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas'); + + }, + + /** + * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. + * + * If you need the image used by a bitmap font or similar then please use those respective 'get' methods. + * + * @method Phaser.Cache#getImage + * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. + * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned. + * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. + */ + getImage: function (key, full) { + + if (key === undefined || key === null) + { + key = '__default'; + } + + if (full === undefined) { full = false; } + + var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage'); + + if (img === null) + { + img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage'); + } + + if (full) + { + return img; + } + else + { + return img.data; + } + + }, + + /** + * Get a single texture frame by key. + * + * You'd only do this to get the default Frame created for a non-atlas / spritesheet image. + * + * @method Phaser.Cache#getTextureFrame + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Frame} The frame data. + */ + getTextureFrame: function (key) { + + return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame'); + + }, + + /** + * Gets a Phaser.Sound object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSound + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Sound} The sound object. + */ + getSound: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSound'); + + }, + + /** + * Gets a raw Sound data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSoundData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The sound data. + */ + getSoundData: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data'); + + }, + + /** + * Gets a Text object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getText + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The text data. + */ + getText: function (key) { + + return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data'); + + }, + + /** + * Gets a Physics Data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can get either the entire data set, a single object or a single fixture of an object from it. + * + * @method Phaser.Cache#getPhysicsData + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all. + * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. + * @return {object} The requested physics object data if found. + */ + getPhysicsData: function (key, object, fixtureKey) { + + var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data'); + + if (data === null || object === undefined || object === null) + { + return data; + } + else + { + if (data[object]) + { + var fixtures = data[object]; + + // Try to find a fixture by its fixture key if given + if (fixtures && fixtureKey) + { + for (var fixture in fixtures) + { + // This contains the fixture data of a polygon or a circle + fixture = fixtures[fixture]; + + // Test the key + if (fixture.fixtureKey === fixtureKey) + { + return fixture; + } + } + + // We did not find the requested fixture + console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"'); + } + else + { + return fixtures; + } + } + else + { + console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"'); + } + } + + return null; + + }, + + /** + * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getTilemapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The raw tilemap data in CSV or JSON format. + */ + getTilemapData: function (key) { + + return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData'); + + }, + + /** + * Gets a binary object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBinary + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The binary data object. + */ + getBinary: function (key) { + + return this.getItem(key, Phaser.Cache.BINARY, 'getBinary'); + + }, + + /** + * Gets a BitmapData object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. + */ + getBitmapData: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data'); + + }, + + /** + * Gets a Bitmap Font object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapFont + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not. + */ + getBitmapFont: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont'); + + }, + + /** + * Gets a JSON object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can either return the object by reference (the default), or return a clone + * of it by setting the `clone` argument to `true`. + * + * @method Phaser.Cache#getJSON + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false) + * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. + */ + getJSON: function (key, clone) { + + var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data'); + + if (data) + { + if (clone) + { + return Phaser.Utils.extend(true, Array.isArray(data) ? [] : {}, data); + } + else + { + return data; + } + } + else + { + return null; + } + + }, + + /** + * Gets an XML object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getXML + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The XML object. + */ + getXML: function (key) { + + return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data'); + + }, + + /** + * Gets a Phaser.Video object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getVideo + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Video} The video object. + */ + getVideo: function (key) { + + return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo'); + + }, + + /** + * Gets a fragment shader object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getShader + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {string} The shader object. + */ + getShader: function (key) { + + return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data'); + + }, + + /** + * Gets a RenderTexture object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getRenderTexture + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame. + */ + getRenderTexture: function (key) { + + return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture'); + + }, + + //////////////////////////// + // Frame Related Methods // + //////////////////////////// + + /** + * Gets a PIXI.BaseTexture by key from the given Cache. + * + * @method Phaser.Cache#getBaseTexture + * @param {string} key - Asset key of the image for which you want the BaseTexture for. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {PIXI.BaseTexture} The BaseTexture object. + */ + getBaseTexture: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getBaseTexture', 'base'); + + }, + + /** + * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. + * + * @method Phaser.Cache#getFrame + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.Frame} The frame data. + */ + getFrame: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrame', 'frame'); + + }, + + /** + * Get the total number of frames contained in the FrameData object specified by the given key. + * + * @method Phaser.Cache#getFrameCount + * @param {string} key - Asset key of the FrameData you want. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {number} Then number of frames. 0 if the image is not found. + */ + getFrameCount: function (key, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.total; + } + else + { + return 0; + } + + }, + + /** + * Gets a Phaser.FrameData object from the Image Cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.FrameData} The frame data. + */ + getFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrameData', 'frameData'); + + }, + + /** + * Check if the FrameData for the given key exists in the Image Cache. + * + * @method Phaser.Cache#hasFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {boolean} True if the given key has frameData in the cache, otherwise false. + */ + hasFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return (this.getItem(key, cache, '', 'frameData') !== null); + + }, + + /** + * Replaces a set of frameData with a new Phaser.FrameData object. + * + * @method Phaser.Cache#updateFrameData + * @param {string} key - The unique key by which you will reference this object. + * @param {number} frameData - The new FrameData. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + */ + updateFrameData: function (key, frameData, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + if (this._cacheMap[cache][key]) + { + this._cacheMap[cache][key].frameData = frameData; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByIndex + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {number} index - The index of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByIndex: function (key, index, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrame(index); + } + else + { + return null; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByName + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {string} name - The name of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByName: function (key, name, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrameByName(name); + } + else + { + return null; + } + + }, + + /** + * Get a cached object by the URL. + * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. + * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. + * + * @method Phaser.Cache#getURL + * @param {string} url - The url for the object loaded to get from the cache. + * @return {object} The cached object. + */ + getURL: function (url) { + + var url = this._resolveURL(url); + + if (url) + { + return this._urlMap[url]; + } + else + { + console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false'); + return null; + } + + }, + + /** + * Gets all keys used in the requested Cache. + * + * @method Phaser.Cache#getKeys + * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. + * @return {Array} The array of keys in the requested cache. + */ + getKeys: function (cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + var out = []; + + if (this._cacheMap[cache]) + { + for (var key in this._cacheMap[cache]) + { + if (key !== '__default' && key !== '__missing') + { + out.push(key); + } + } + } + + return out; + + }, + + ///////////////////// + // Remove Methods // + ///////////////////// + + /** + * Removes a canvas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeCanvas + * @param {string} key - Key of the asset you want to remove. + */ + removeCanvas: function (key) { + + delete this._cache.canvas[key]; + + }, + + /** + * Removes an image from the cache. + * + * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. + * + * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeImage + * @param {string} key - Key of the asset you want to remove. + * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed? + */ + removeImage: function (key, destroyBaseTexture) { + + if (destroyBaseTexture === undefined) { destroyBaseTexture = true; } + + var img = this.getImage(key, true); + + if (destroyBaseTexture && img.base) + { + img.base.destroy(); + } + + delete this._cache.image[key]; + + }, + + /** + * Removes a sound from the cache. + * + * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will + * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then + * you must finish your house-keeping and destroy them all yourself first, before calling this method. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSound + * @param {string} key - Key of the asset you want to remove. + */ + removeSound: function (key) { + + delete this._cache.sound[key]; + + }, + + /** + * Removes a text file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeText + * @param {string} key - Key of the asset you want to remove. + */ + removeText: function (key) { + + delete this._cache.text[key]; + + }, + + /** + * Removes a physics data file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removePhysics + * @param {string} key - Key of the asset you want to remove. + */ + removePhysics: function (key) { + + delete this._cache.physics[key]; + + }, + + /** + * Removes a tilemap from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTilemap + * @param {string} key - Key of the asset you want to remove. + */ + removeTilemap: function (key) { + + delete this._cache.tilemap[key]; + + }, + + /** + * Removes a binary file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBinary + * @param {string} key - Key of the asset you want to remove. + */ + removeBinary: function (key) { + + delete this._cache.binary[key]; + + }, + + /** + * Removes a bitmap data from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapData + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapData: function (key) { + + delete this._cache.bitmapData[key]; + + }, + + /** + * Removes a bitmap font from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapFont + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapFont: function (key) { + + delete this._cache.bitmapFont[key]; + + }, + + /** + * Removes a json object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeJSON + * @param {string} key - Key of the asset you want to remove. + */ + removeJSON: function (key) { + + delete this._cache.json[key]; + + }, + + /** + * Removes a xml object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeXML + * @param {string} key - Key of the asset you want to remove. + */ + removeXML: function (key) { + + delete this._cache.xml[key]; + + }, + + /** + * Removes a video from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeVideo + * @param {string} key - Key of the asset you want to remove. + */ + removeVideo: function (key) { + + delete this._cache.video[key]; + + }, + + /** + * Removes a shader from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeShader + * @param {string} key - Key of the asset you want to remove. + */ + removeShader: function (key) { + + delete this._cache.shader[key]; + + }, + + /** + * Removes a Render Texture from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeRenderTexture + * @param {string} key - Key of the asset you want to remove. + */ + removeRenderTexture: function (key) { + + delete this._cache.renderTexture[key]; + + }, + + /** + * Removes a Sprite Sheet from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSpriteSheet + * @param {string} key - Key of the asset you want to remove. + */ + removeSpriteSheet: function (key) { + + delete this._cache.spriteSheet[key]; + + }, + + /** + * Removes a Texture Atlas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTextureAtlas + * @param {string} key - Key of the asset you want to remove. + */ + removeTextureAtlas: function (key) { + + delete this._cache.image[key]; + + }, + + /** + * Empties out all of the GL Textures from Images stored in the cache. + * This is called automatically when the WebGL context is lost and then restored. + * + * @method Phaser.Cache#clearGLTextures + * @protected + */ + clearGLTextures: function () { + + for (var key in this._cache.image) + { + this._cache.image[key].base._glTextures = []; + } + + }, + + /** + * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`. + * This is then looked-up by the Cache.getURL and Cache.checkURL calls. + * + * @method Phaser.Cache#_resolveURL + * @private + * @param {string} url - The URL to resolve. This is appended to Loader.baseURL. + * @param {object} [data] - The data associated with the URL to be stored to the URL Map. + * @return {string} The resolved URL. + */ + _resolveURL: function (url, data) { + + if (!this.autoResolveURL) + { + return null; + } + + this._urlResolver.src = this.game.load.baseURL + url; + + this._urlTemp = this._urlResolver.src; + + // Ensure no request is actually made + this._urlResolver.src = ''; + + // Record the URL to the map + if (data) + { + this._urlMap[this._urlTemp] = data; + } + + return this._urlTemp; + + }, + + /** + * Clears the cache. Removes every local cache object reference. + * If an object in the cache has a `destroy` method it will be called; + * otherwise, `destroy` will be called on any of the object's `base`, `data`, + * `frameData`, or `texture` properties. + * + * @method Phaser.Cache#destroy + */ + destroy: function () { + + for (var i = 0; i < this._cacheMap.length; i++) + { + var cache = this._cacheMap[i]; + + for (var key in cache) + { + if (key !== '__default' && key !== '__missing') + { + this.destroyItem(cache[key]); + + delete cache[key]; + } + } + } + + this._urlMap = null; + this._urlResolver = null; + this._urlTemp = null; + + }, + + /** + * @method Phaser.Cache#destroyItem + * @protected + * @param {object} item + */ + destroyItem: function (item) { + + if (item.destroy) + { + item.destroy(); + } + else + { + if (item.base && item.base.destroy) + { + item.base.destroy(); + } + + if (item.data && item.data.destroy) + { + item.data.destroy(); + } + + if (item.frameData && item.frameData.destroy) + { + item.frameData.destroy(); + } + + if (item.texture && item.texture.destroy) + { + item.texture.destroy(true); + } + } + + }, + + /** + * Starts loading the DEFAULT and MISSING images. + * + * @private + */ + _addImages: function () { + + this._pendingCount = 0; + + this.addDefaultImage(); + this.addMissingImage(); + + var self = this; + var readyTimeout = Phaser.Cache.READY_TIMEOUT; + + if (Phaser.Cache.READY_TIMEOUT > 0) + { + setTimeout(function () { + if (!self.isReady) + { + console.warn('Phaser.Cache: Still waiting for images after %s ms.', readyTimeout); + + self._ready(); + } + }, Phaser.Cache.READY_TIMEOUT); + } + else + { + this._ready(); + } + + }, + + + /** + * Increments the pending count. + * + * @private + */ + _addPending: function () { + + this._pendingCount += 1; + + }, + + + /** + * Decrements the pending count and checks if complete. + * + * @private + */ + _removePending: function () { + + this._pendingCount -= 1; + this._checkReady(); + + }, + + + /** + * Calls {@link #_ready} if no pending items remain. + * + * @private + */ + _checkReady: function () { + + if (this.isReady) + { + this._ready(); + } + + }, + + + /** + * Resets pending count and triggers {@link #onReady}. + * + * @private + */ + _ready: function () { + + this._pendingCount = 0; + this.onReady.dispatch(this); + + } + +}; + +Phaser.Cache.prototype.constructor = Phaser.Cache; + +/** +* The DEFAULT and MISSING textures have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). +* +* @property {boolean} Phaser.Cache#isReady +*/ +Object.defineProperty(Phaser.Cache.prototype, 'isReady', { + get: function () { + return this._pendingCount <= 0; + } +}); + +/* jshint wsh:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* +* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. +* +* Parallel loading (see {@link #enableParallel}) is supported and enabled by default. +* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}. +* +* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and +* [Shoebox](http://renderhjs.net/shoebox/) +* +* @class Phaser.Loader +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Loader = function (game) { + + /** + * Local reference to game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + /** + * Local reference to the Phaser.Cache. + * @property {Phaser.Cache} cache + * @protected + */ + this.cache = game.cache; + + /** + * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * True if the Loader is in the process of loading the queue. + * @property {boolean} isLoading + * @default + */ + this.isLoading = false; + + /** + * True if all assets in the queue have finished loading. + * @property {boolean} hasLoaded + * @default + */ + this.hasLoaded = false; + + /** + * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}. + * + * This property is an object containing: sprite, rect, direction, width and height + * + * @property {?object} preloadSprite + * @protected + */ + this.preloadSprite = null; + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * @property {boolean|string} crossOrigin + * @default + */ + this.crossOrigin = false; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * Useful if allowing the asset base url to be configured outside of the game code. + * The string _must_ end with a "/". + * + * @property {string} baseURL + */ + this.baseURL = ''; + + /** + * The value of `path`, if set, is placed before any _relative_ file path given. For example: + * + * ```javascript + * load.path = "images/sprites/"; + * load.image("ball", "ball.png"); + * load.image("tree", "level1/oaktree.png"); + * load.image("boom", "http://server.com/explode.png"); + * ``` + * + * Would load the `ball` file from `images/sprites/ball.png` and the tree from + * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL + * given as it's an absolute URL. + * + * Please note that the path is added before the filename but *after* the baseURL (if set.) + * + * The string _must_ end with a "/". + * + * @property {string} path + */ + this.path = ''; + + /** + * Used to map the application mime-types to to the Accept header in XHR requests. + * If you don't require these mappings, or they cause problems on your server, then + * remove them from the headers object and the XHR request will not try to use them. + * + * This object can also be used to set the `X-Requested-With` header to + * `XMLHttpRequest` (or any other value you need). To enable this do: + * + * ```javascript + * this.load.headers.requestedWith = 'XMLHttpRequest' + * ``` + * + * before adding anything to the Loader. The XHR loader will then call: + * + * ```javascript + * setRequestHeader('X-Requested-With', this.headers['requestedWith']) + * ``` + * + * @property {object} headers + * @default + */ + this.headers = { + "requestedWith": false, + "json": "application/json", + "xml": "application/xml" + }; + + /** + * This event is dispatched when the loading process starts: before the first file has been requested, + * but after all the initial packs have been loaded. + * + * @property {Phaser.Signal} onLoadStart + */ + this.onLoadStart = new Phaser.Signal(); + + /** + * This event is dispatched when the final file in the load queue has either loaded or failed. + * + * @property {Phaser.Signal} onLoadComplete + */ + this.onLoadComplete = new Phaser.Signal(); + + /** + * This event is dispatched when an asset pack has either loaded or failed to load. + * + * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. + * + * Params: `(pack key, success?, total packs loaded, total packs)` + * + * @property {Phaser.Signal} onPackComplete + */ + this.onPackComplete = new Phaser.Signal(); + + /** + * This event is dispatched immediately before a file starts loading. + * It's possible the file may fail (eg. download error, invalid format) after this event is sent. + * + * Params: `(progress, file key, file url)` + * + * @property {Phaser.Signal} onFileStart + */ + this.onFileStart = new Phaser.Signal(); + + /** + * This event is dispatched when a file has either loaded or failed to load. + * + * Any function bound to this will receive the following parameters: + * + * progress, file key, success?, total loaded files, total files + * + * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. + * + * @property {Phaser.Signal} onFileComplete + */ + this.onFileComplete = new Phaser.Signal(); + + /** + * This event is dispatched when a file (or pack) errors as a result of the load request. + * + * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. + * + * Params: `(file key, file)` + * + * @property {Phaser.Signal} onFileError + */ + this.onFileError = new Phaser.Signal(); + + /** + * If true (the default) then parallel downloading will be enabled. + * + * To disable all parallel downloads this must be set to false prior to any resource being loaded. + * + * @property {boolean} enableParallel + */ + this.enableParallel = true; + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Many current browsers limit 6 requests per domain; this is slightly conservative. + * + * This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently. + * + * @property {integer} maxParallelDownloads + */ + this.maxParallelDownloads = 4; + + /** + * A counter: if more than zero, files will be automatically added as a synchronization point. + * @property {integer} _withSyncPointDepth; + */ + this._withSyncPointDepth = 0; + + /** + * Contains all the information for asset files (including packs) to load. + * + * File/assets are only removed from the list after all loading completes. + * + * @property {file[]} _fileList + * @private + */ + this._fileList = []; + + /** + * Inflight files (or packs) that are being fetched/processed. + * + * This means that if there are any files in the flight queue there should still be processing + * going on; it should only be empty before or after loading. + * + * The files in the queue may have additional properties added to them, + * including `requestObject` which is normally the associated XHR. + * + * @property {file[]} _flightQueue + * @private + */ + this._flightQueue = []; + + /** + * The offset into the fileList past all the complete (loaded or error) entries. + * + * @property {integer} _processingHead + * @private + */ + this._processingHead = 0; + + /** + * True when the first file (not pack) has loading started. + * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded. + * + * @property {boolean} _initialPacksLoaded + * @private + */ + this._fileLoadStarted = false; + + /** + * Total packs seen - adjusted when a pack is added. + * @property {integer} _totalPackCount + * @private + */ + this._totalPackCount = 0; + + /** + * Total files seen - adjusted when a file is added. + * @property {integer} _totalFileCount + * @private + */ + this._totalFileCount = 0; + + /** + * Total packs loaded - adjusted just prior to `onPackComplete`. + * @property {integer} _loadedPackCount + * @private + */ + this._loadedPackCount = 0; + + /** + * Total files loaded - adjusted just prior to `onFileComplete`. + * @property {integer} _loadedFileCount + * @private + */ + this._loadedFileCount = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_PHASER_JSON = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5; + +Phaser.Loader.prototype = { + + /** + * Set a Sprite to be a "preload" sprite by passing it to this method. + * + * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. + * This allows you to easily make loading bars for games. + * + * The sprite will automatically be made visible when calling this. + * + * @method Phaser.Loader#setPreloadSprite + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load. + * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. + */ + setPreloadSprite: function (sprite, direction) { + + direction = direction || 0; + + this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null }; + + if (direction === 0) + { + // Horizontal rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height); + } + else + { + // Vertical rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1); + } + + sprite.crop(this.preloadSprite.rect); + + sprite.visible = true; + + }, + + /** + * Called automatically by ScaleManager when the game resizes in RESIZE scalemode. + * + * This can be used to adjust the preloading sprite size, eg. + * + * @method Phaser.Loader#resize + * @protected + */ + resize: function () { + + if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height) + { + this.preloadSprite.rect.height = this.preloadSprite.sprite.height; + } + + }, + + /** + * Check whether a file/asset with a specific key is queued to be loaded. + * + * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey} + * + * @method Phaser.Loader#checkKeyExists + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ + checkKeyExists: function (type, key) { + + return this.getAssetIndex(type, key) > -1; + + }, + + /** + * Get the queue-index of the file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAssetIndex + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {number} The index of this key in the filelist, or -1 if not found. + * The index may change and should only be used immediately following this call + */ + getAssetIndex: function (type, key) { + + var bestFound = -1; + + for (var i = 0; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + if (file.type === type && file.key === key) + { + bestFound = i; + + // An already loaded/loading file may be superceded. + if (!file.loaded && !file.loading) + { + break; + } + } + } + + return bestFound; + + }, + + /** + * Find a file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAsset + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. + * The index may change and should only be used immediately following this call. + */ + getAsset: function (type, key) { + + var fileIndex = this.getAssetIndex(type, key); + + if (fileIndex > -1) + { + return { index: fileIndex, file: this._fileList[fileIndex] }; + } + + return false; + + }, + + /** + * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. + * + * This will abort any loading and clear any queued assets. + * + * Optionally you can clear any associated events. + * + * @method Phaser.Loader#reset + * @protected + * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared. + * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them. + */ + reset: function (hard, clearEvents) { + + if (clearEvents === undefined) { clearEvents = false; } + + if (this.resetLocked) + { + return; + } + + if (hard) + { + this.preloadSprite = null; + } + + this.isLoading = false; + + this._processingHead = 0; + this._fileList.length = 0; + this._flightQueue.length = 0; + + this._fileLoadStarted = false; + this._totalFileCount = 0; + this._totalPackCount = 0; + this._loadedPackCount = 0; + this._loadedFileCount = 0; + + if (clearEvents) + { + this.onLoadStart.removeAll(); + this.onLoadComplete.removeAll(); + this.onPackComplete.removeAll(); + this.onFileStart.removeAll(); + this.onFileComplete.removeAll(); + this.onFileError.removeAll(); + } + + }, + + /** + * Internal function that adds a new entry to the file list. Do not call directly. + * + * @method Phaser.Loader#addToFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} [url] - The URL the asset will be loaded from. + * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. + * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. + * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. + * @return {Phaser.Loader} This instance of the Phaser Loader. + */ + addToFileList: function (type, key, url, properties, overwrite, extension) { + + if (overwrite === undefined) { overwrite = false; } + + if (key === undefined || key === '') + { + console.warn("Phaser.Loader: Invalid or no key given of type " + type); + return this; + } + + if (url === undefined || url === null) + { + if (extension) + { + url = key + extension; + } + else + { + console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key); + return this; + } + } + + var file = { + type: type, + key: key, + path: this.path, + url: url, + syncPoint: this._withSyncPointDepth > 0, + data: null, + loading: false, + loaded: false, + error: false + }; + + if (properties) + { + for (var prop in properties) + { + file[prop] = properties[prop]; + } + } + + var fileIndex = this.getAssetIndex(type, key); + + if (overwrite && fileIndex > -1) + { + var currentFile = this._fileList[fileIndex]; + + if (!currentFile.loading && !currentFile.loaded) + { + this._fileList[fileIndex] = file; + } + else + { + this._fileList.push(file); + this._totalFileCount++; + } + } + else if (fileIndex === -1) + { + this._fileList.push(file); + this._totalFileCount++; + } + + return this; + + }, + + /** + * Internal function that replaces an existing entry in the file list with a new one. Do not call directly. + * + * @method Phaser.Loader#replaceInFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} url - The URL the asset will be loaded from. + * @param {object} properties - Any additional properties needed to load the file. + */ + replaceInFileList: function (type, key, url, properties) { + + return this.addToFileList(type, key, url, properties, true); + + }, + + /** + * Add a JSON resource pack ('packfile') to the Loader. + * + * A packfile is a JSON file that contains a list of assets to the be loaded. + * Please see the example 'loader/asset pack' in the Phaser Examples repository. + * + * Packs are always put before the first non-pack file that is not loaded / loading. + * + * This means that all packs added before any loading has started are added to the front + * of the file queue, in the order added. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#pack + * @param {string} key - Unique asset key of this resource pack. + * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. + * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO + * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. + * @return {Phaser.Loader} This Loader instance. + */ + pack: function (key, url, data, callbackContext) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (callbackContext === undefined) { callbackContext = null; } + + if (!url && !data) + { + console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.'); + + return this; + } + + var pack = { + type: 'packfile', + key: key, + url: url, + path: this.path, + syncPoint: true, + data: null, + loading: false, + loaded: false, + error: false, + callbackContext: callbackContext + }; + + // A data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + pack.data = data || {}; + + // Already consider 'loaded' + pack.loaded = true; + } + + // Add before first non-pack/no-loaded ~ last pack from start prior to loading + // (Read one past for splice-to-end) + for (var i = 0; i < this._fileList.length + 1; i++) + { + var file = this._fileList[i]; + + if (!file || (!file.loaded && !file.loading && file.type !== 'packfile')) + { + this._fileList.splice(i, 0, pack); + this._totalPackCount++; + break; + } + } + + return this; + + }, + + /** + * Adds an Image to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * This method also supports passing in a texture object as the `url` argument. This allows you to load + * compressed textures into Phaser. You can also use `Loader.texture` to do this. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.image('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * @method Phaser.Loader#image + * @param {string} key - Unique asset key of this image file. + * @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + image: function (key, url, overwrite) { + + if (typeof url === 'object') + { + return this.texture(key, url, overwrite); + } + else + { + return this.addToFileList('image', key, url, undefined, overwrite, '.png'); + } + + }, + + /** + * Generate an image from a BitmapData object and add it to the current load queue. + * + * @method Phaser.Loader#imageFromBitmapData + * @param {string} key - Unique asset key for the generated image. + * @param {Phaser.BitmapData} bitmapData + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + imageFromBitmapData: function (key, bitmapData, overwrite) { + + return this.image(key, bitmapData.canvas.toDataURL('image/png'), overwrite); + + }, + + /** + * Generate a grid image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromGrid + * @see Phaser.Create#grid + */ + imageFromGrid: function (key, width, height, cellWidth, cellHeight, color) { + + return this.imageFromBitmapData(key, this.game.create.grid(key, width, height, cellWidth, cellHeight, color, false)); + + }, + + /** + * Generate a texture image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromTexture + * @see Phaser.Create#texture + */ + imageFromTexture: function (key, data, pixelWidth, pixelHeight, palette) { + + return this.imageFromBitmapData(key, this.game.create.texture(key, data, pixelWidth, pixelHeight, palette, false)); + + }, + + /** + * Adds a Compressed Texture Image to the current load queue. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.texture('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#texture + * @param {string} key - Unique asset key of this image file. + * @param {object} object - The texture path data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + texture: function (key, object, overwrite) { + + if (this.game.renderType === Phaser.WEBGL) + { + var compression = this.game.renderer.extensions.compression; + var exkey; + + for (exkey in object) + { + if (exkey.toUpperCase() in compression) + { + return this.addToFileList('texture', key, object[exkey], undefined, overwrite, '.pvr'); + } + } + } + + // Check if we have a truecolor texture to fallback. + // Also catches calls to this function that are from a Canvas renderer + + if (object['truecolor']) + { + this.addToFileList('image', key, object['truecolor'], undefined, overwrite, '.png'); + } + + return this; + + }, + + /** + * Adds an array of images to the current load queue. + * + * It works by passing each element of the array to the Loader.image method. + * + * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. + * + * Retrieve the images via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#images + * @param {array} keys - An array of unique asset keys of the image files. + * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. + * @return {Phaser.Loader} This Loader instance. + */ + images: function (keys, urls) { + + if (Array.isArray(urls)) + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i], urls[i]); + } + } + else + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i]); + } + } + + return this; + + }, + + /** + * Adds a Text file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getText(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#text + * @param {string} key - Unique asset key of the text file. + * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + text: function (key, url, overwrite) { + + return this.addToFileList('text', key, url, undefined, overwrite, '.txt'); + + }, + + /** + * Adds a JSON file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#json + * @param {string} key - Unique asset key of the json file. + * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + json: function (key, url, overwrite) { + + return this.addToFileList('json', key, url, undefined, overwrite, '.json'); + + }, + + /** + * Adds a fragment shader file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getShader(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" + * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#shader + * @param {string} key - Unique asset key of the fragment file. + * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + shader: function (key, url, overwrite) { + + return this.addToFileList('shader', key, url, undefined, overwrite, '.frag'); + + }, + + /** + * Adds an XML file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getXML(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#xml + * @param {string} key - Unique asset key of the xml file. + * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + xml: function (key, url, overwrite) { + + return this.addToFileList('xml', key, url, undefined, overwrite, '.xml'); + + }, + + /** + * Adds a JavaScript file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. + * If you do not desire this action then provide a URL. + * + * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! + * + * A callback, which will be invoked as the script tag has been created, can also be specified. + * The callback must return relevant `data`. + * + * @method Phaser.Loader#script + * @param {string} key - Unique asset key of the script file. + * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing. + * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. + * @return {Phaser.Loader} This Loader instance. + */ + script: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + if (callback !== false && callbackContext === undefined) { callbackContext = this; } + + return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js'); + + }, + + /** + * Adds a binary file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBinary(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. + * If you do not desire this action then provide a URL. + * + * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. + * When the callback is called it will be passed 2 parameters: the key of the file and the file data. + * + * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. + * + * @method Phaser.Loader#binary + * @param {string} key - Unique asset key of the binary file. + * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it. + * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context. + * @return {Phaser.Loader} This Loader instance. + */ + binary: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + // Why is the default callback context the ..callback? + if (callback !== false && callbackContext === undefined) { callbackContext = callback; } + + return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin'); + + }, + + /** + * Adds a Sprite Sheet to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal + * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. + * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. + * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming + * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. + * If you've got an atlas then use `Loader.atlas` instead. + * + * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#spritesheet + * @param {string} key - Unique asset key of the sheet file. + * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet. + * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.Loader} This Loader instance. + */ + spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing, skipFrames: skipFrames }, false, '.png'); + + }, + + /** + * Adds an audio file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getSound(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. + * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. + * The solution is to use a lower encoding rate such as 44100 Hz. + * + * @method Phaser.Loader#audio + * @param {string} key - Unique asset key of the audio file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp3']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audio: function (key, urls, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (autoDecode === undefined) { autoDecode = true; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); + + }, + + /** + * Adds an audio sprite file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Audio Sprites are a combination of audio files and a JSON configuration. + * + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * Retrieve the file via `Cache.getSoundData(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#audioSprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (jsonURL === undefined) { jsonURL = null; } + if (jsonData === undefined) { jsonData = null; } + if (autoDecode === undefined) { autoDecode = true; } + + this.audio(key, urls, autoDecode); + + if (jsonURL) + { + this.json(key + '-audioatlas', jsonURL); + } + else if (jsonData) + { + if (typeof jsonData === 'string') + { + jsonData = JSON.parse(jsonData); + } + + this.cache.addJSON(key + '-audioatlas', '', jsonData); + } + else + { + console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object'); + } + + return this; + + }, + + /** + * A legacy alias for Loader.audioSprite. Please see that method for documentation. + * + * @method Phaser.Loader#audiosprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode); + + }, + + /** + * Adds a video file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getVideo(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. + * + * @method Phaser.Loader#video + * @param {string} key - Unique asset key of the video file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp4']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete. + * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. + * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. + * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the + * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. + * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set. + * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. + * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. + * @return {Phaser.Loader} This Loader instance. + */ + video: function (key, urls, loadEvent, asBlob) { + + if (loadEvent === undefined) + { + if (this.game.device.firefox) + { + loadEvent = 'loadeddata'; + } + else + { + loadEvent = 'canplaythrough'; + } + } + + if (asBlob === undefined) { asBlob = false; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent }); + + }, + + /** + * Adds a Tile Map data file to the current load queue. + * + * Phaser can load data in two different formats: CSV and Tiled JSON. + * + * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". + * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#tilemap + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. + * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + * @return {Phaser.Loader} This Loader instance. + */ + tilemap: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Tilemap.CSV; } + + if (!url && !data) + { + if (format === Phaser.Tilemap.CSV) + { + url = key + '.csv'; + } + else + { + url = key + '.json'; + } + } + + // A map data object has been given + if (data) + { + switch (format) + { + // A csv string or object has been given + case Phaser.Tilemap.CSV: + break; + + // A json string or object has been given + case Phaser.Tilemap.TILED_JSON: + + if (typeof data === 'string') + { + data = JSON.parse(data); + } + break; + } + + this.cache.addTilemap(key, null, data, format); + } + else + { + this.addToFileList('tilemap', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds a physics data file to the current load queue. + * + * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". + * It will always use `.json` as the extension. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#physics + * @param {string} key - Unique asset key of the physics json data. + * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. + * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data. + * @return {Phaser.Loader} This Loader instance. + */ + physics: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; } + + if (!url && !data) + { + url = key + '.json'; + } + + // A map data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + this.cache.addPhysicsData(key, null, data, format); + } + else + { + this.addToFileList('physics', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds Bitmap Font files to the current load queue. + * + * To create the Bitmap Font files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `xmlData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#bitmapFont + * @param {string} key - Unique asset key of the bitmap font. + * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". + * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". + * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json). + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + * @return {Phaser.Loader} This Loader instance. + */ + bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (atlasURL === null && atlasData === null) + { + atlasURL = key + '.xml'; + } + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + // A URL to a json/xml atlas has been given + if (atlasURL) + { + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing }); + } + else + { + // A stringified xml/json atlas has been given + if (typeof atlasData === 'string') + { + var json, xml; + + try + { + json = JSON.parse(atlasData); + } + catch ( e ) + { + xml = this.parseXml(atlasData); + } + + if (!xml && !json) + { + throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given"); + } + + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml, + atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing }); + } + } + + return this; + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONArray + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONHash + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * This call expects the atlas data to be in the Starling XML data format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasXML + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasXML: function (key, textureURL, atlasURL, atlasData) { + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (!atlasURL && !atlasData) + { + atlasURL = key + '.xml'; + } + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlas + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. + * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING. + * @return {Phaser.Loader} This Loader instance. + */ + atlas: function (key, textureURL, atlasURL, atlasData, format) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } + + if (!atlasURL && !atlasData) + { + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + atlasURL = key + '.xml'; + } + else + { + atlasURL = key + '.json'; + } + } + + // A URL to a json/xml file has been given + if (atlasURL) + { + this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); + } + else + { + switch (format) + { + // A json string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: + + if (typeof atlasData === 'string') + { + atlasData = JSON.parse(atlasData); + } + break; + + // An xml string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: + + if (typeof atlasData === 'string') + { + var xml = this.parseXml(atlasData); + + if (!xml) + { + throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); + } + + atlasData = xml; + } + break; + } + + this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); + + } + + return this; + + }, + + /** + * Add a synchronization point to the assets / files added within the supplied callback. + * + * A synchronization point denotes that an asset _must_ be completely loaded before + * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait + * for previous assets to load (unless they are sync-points). Resources, such as packs, may still + * be downloaded around sync-points, as long as they do not finalize loading. + * + * @method Phaser.Loader#withSyncPoint + * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader. + * @param {object} [callbackContext=(loader)] - Context for the callback. + * @return {Phaser.Loader} This Loader instance. + */ + withSyncPoint: function (callback, callbackContext) { + + this._withSyncPointDepth++; + + try { + callback.call(callbackContext || this, this); + } finally { + this._withSyncPointDepth--; + } + + return this; + }, + + /** + * Add a synchronization point to a specific file/asset in the load queue. + * + * This has no effect on already loaded assets. + * + * @method Phaser.Loader#addSyncPoint + * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc). + * @param {string} key - Key of the file you want to turn into a sync point. + * @return {Phaser.Loader} This Loader instance. + * @see {@link Phaser.Loader#withSyncPoint withSyncPoint} + */ + addSyncPoint: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + asset.file.syncPoint = true; + } + + return this; + }, + + /** + * Remove a file/asset from the loading queue. + * + * A file that is loaded or has started loading cannot be removed. + * + * @method Phaser.Loader#removeFile + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - Key of the file you want to remove. + */ + removeFile: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + if (!asset.loaded && !asset.loading) + { + this._fileList.splice(asset.index, 1); + } + } + + }, + + /** + * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead. + * + * @method Phaser.Loader#removeAll + * @protected + */ + removeAll: function () { + + this._fileList.length = 0; + this._flightQueue.length = 0; + + }, + + /** + * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. + * + * @method Phaser.Loader#start + */ + start: function () { + + if (this.isLoading) + { + return; + } + + this.hasLoaded = false; + this.isLoading = true; + + this.updateProgress(); + + this.processLoadQueue(); + + }, + + /** + * Process the next item(s) in the file/asset queue. + * + * Process the queue and start loading enough items to fill up the inflight queue. + * + * If a sync-file is encountered then subsequent asset processing is delayed until it completes. + * The exception to this rule is that packfiles can be downloaded (but not processed) even if + * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel. + * such as during the start phaser. + * + * @method Phaser.Loader#processLoadQueue + * @private + */ + processLoadQueue: function () { + + if (!this.isLoading) + { + console.warn('Phaser.Loader - active loading canceled / reset'); + this.finishedLoading(true); + return; + } + + // Empty the flight queue as applicable + for (var i = 0; i < this._flightQueue.length; i++) + { + var file = this._flightQueue[i]; + + if (file.loaded || file.error) + { + this._flightQueue.splice(i, 1); + i--; + + file.loading = false; + file.requestUrl = null; + file.requestObject = null; + + if (file.error) + { + this.onFileError.dispatch(file.key, file); + } + + if (file.type !== 'packfile') + { + this._loadedFileCount++; + this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount); + } + else if (file.type === 'packfile' && file.error) + { + // Non-error pack files are handled when processing the file queue + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + } + } + + // When true further non-pack file downloads are suppressed + var syncblock = false; + + var inflightLimit = this.enableParallel ? Math.max(1, this.maxParallelDownloads) : 1; + + for (var i = this._processingHead; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + // Pack is fetched (ie. has data) and is currently at the start of the process queue. + if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead) + { + // Processing the pack / adds more files + this.processPack(file); + + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + if (file.loaded || file.error) + { + // Item at the start of file list finished, can skip it in future + if (i === this._processingHead) + { + this._processingHead = i + 1; + } + } + else if (!file.loading && this._flightQueue.length < inflightLimit) + { + // -> not loaded/failed, not loading + if (file.type === 'packfile' && !file.data) + { + // Fetches the pack data: the pack is processed above as it reaches queue-start. + // (Packs do not trigger onLoadStart or onFileStart.) + this._flightQueue.push(file); + file.loading = true; + + this.loadFile(file); + } + else if (!syncblock) + { + if (!this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this._flightQueue.push(file); + file.loading = true; + this.onFileStart.dispatch(this.progress, file.key, file.url); + + this.loadFile(file); + } + } + + if (!file.loaded && file.syncPoint) + { + syncblock = true; + } + + // Stop looking if queue full - or if syncblocked and there are no more packs. + // (As only packs can be loaded around a syncblock) + if (this._flightQueue.length >= inflightLimit || + (syncblock && this._loadedPackCount === this._totalPackCount)) + { + break; + } + } + + this.updateProgress(); + + // True when all items in the queue have been advanced over + // (There should be no inflight items as they are complete - loaded/error.) + if (this._processingHead >= this._fileList.length) + { + this.finishedLoading(); + } + else if (!this._flightQueue.length) + { + // Flight queue is empty but file list is not done being processed. + // This indicates a critical internal error with no known recovery. + console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled"); + + var _this = this; + + setTimeout(function () { + _this.finishedLoading(true); + }, 2000); + } + + }, + + /** + * The loading is all finished. + * + * @method Phaser.Loader#finishedLoading + * @private + * @param {boolean} [abnormal=true] - True if the loading finished abnormally. + */ + finishedLoading: function (abnormal) { + + if (this.hasLoaded) + { + return; + } + + this.hasLoaded = true; + this.isLoading = false; + + // If there were no files make sure to trigger the event anyway, for consistency + if (!abnormal && !this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this.reset(); + + this.onLoadComplete.dispatch(); + + // Check if the state still exists since destroy could have occurred while loading + if (this.game.state) + { + this.game.state.loadComplete(); + } + + }, + + /** + * Informs the loader that the given file resource has been fetched and processed; + * or such a request has failed. + * + * @method Phaser.Loader#asyncComplete + * @private + * @param {object} file + * @param {string} [error=''] - The error message, if any. No message implies no error. + */ + asyncComplete: function (file, errorMessage) { + + if (errorMessage === undefined) { errorMessage = ''; } + + file.loaded = true; + file.error = !!errorMessage; + + if (errorMessage) + { + file.errorMessage = errorMessage; + + console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage); + } + + this.processLoadQueue(); + + }, + + /** + * Process pack data. This will usually modify the file list. + * + * @method Phaser.Loader#processPack + * @private + * @param {object} pack + */ + processPack: function (pack) { + + var packData = pack.data[pack.key]; + + if (!packData) + { + console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key'); + return; + } + + for (var i = 0; i < packData.length; i++) + { + var file = packData[i]; + + switch (file.type) + { + case "image": + this.image(file.key, file.url, file.overwrite); + break; + + case "text": + this.text(file.key, file.url, file.overwrite); + break; + + case "json": + this.json(file.key, file.url, file.overwrite); + break; + + case "xml": + this.xml(file.key, file.url, file.overwrite); + break; + + case "script": + this.script(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "binary": + this.binary(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "spritesheet": + this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case "video": + this.video(file.key, file.urls); + break; + + case "audio": + this.audio(file.key, file.urls, file.autoDecode); + break; + + case "audiosprite": + this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode); + break; + + case "tilemap": + this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]); + break; + + case "physics": + this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]); + break; + + case "bitmapFont": + this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing); + break; + + case "atlasJSONArray": + this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasJSONHash": + this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasXML": + this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlas": + this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]); + break; + + case "shader": + this.shader(file.key, file.url, file.overwrite); + break; + } + } + + }, + + /** + * Transforms the asset URL. + * + * The default implementation prepends the baseURL if the url doesn't begin with http or // + * + * @method Phaser.Loader#transformUrl + * @protected + * @param {string} url - The url to transform. + * @param {object} file - The file object being transformed. + * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead. + */ + transformUrl: function (url, file) { + + if (!url) + { + return false; + } + + if (url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) + { + return url; + } + else + { + return this.baseURL + file.path + url; + } + + }, + + /** + * Start fetching a resource. + * + * All code paths, async or otherwise, from this function must return to `asyncComplete`. + * + * @method Phaser.Loader#loadFile + * @private + * @param {object} file + */ + loadFile: function (file) { + + // Image or Data? + switch (file.type) + { + case 'packfile': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'image': + case 'spritesheet': + case 'textureatlas': + case 'bitmapfont': + this.loadImageTag(file); + break; + + case 'audio': + file.url = this.getAudioURL(file.url); + + if (file.url) + { + // WebAudio or Audio Tag? + if (this.game.sound.usingWebAudio) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + else if (this.game.sound.usingAudioTag) + { + this.loadAudioTag(file); + } + } + else + { + this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support'); + } + break; + + case 'video': + file.url = this.getVideoURL(file.url); + + if (file.url) + { + if (file.asBlob) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'blob', this.fileComplete); + } + else + { + this.loadVideoTag(file); + } + } + else + { + this.fileError(file, null, 'No supported video URL specified or device does not have video playback support'); + } + break; + + case 'json': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + break; + + case 'xml': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete); + break; + + case 'tilemap': + + if (file.format === Phaser.Tilemap.TILED_JSON) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Tilemap.CSV) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete); + } + else + { + this.asyncComplete(file, "invalid Tilemap format: " + file.format); + } + break; + + case 'text': + case 'script': + case 'shader': + case 'physics': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'texture': + + if (file.key.split('_').pop() === 'truecolor') + { + this.loadImageTag(file); + } + else + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + break; + + case 'binary': + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + break; + } + + }, + + /** + * Continue async loading through an Image tag. + * @private + */ + loadImageTag: function (file) { + var _this = this; + + file.data = new Image(); + file.data.name = file.key; + + if (this.crossOrigin) + { + file.data.crossOrigin = this.crossOrigin; + } + + file.data.onload = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileComplete(file); + } + }; + + file.data.onerror = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileError(file); + } + }; + + file.data.src = this.transformUrl(file.url, file); + + // Image is immediately-available/cached + // Special Firefox magic, exclude from cached reload + // More info here: https://github.com/photonstorm/phaser/issues/2534 + if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height) + { + file.data.onload = null; + file.data.onerror = null; + this.fileComplete(file); + } + + }, + + /** + * Continue async loading through a Video tag. + * @private + */ + loadVideoTag: function (file) { + + var _this = this; + + file.data = document.createElement("video"); + file.data.name = file.key; + file.data.controls = false; + file.data.autoplay = false; + + var videoLoadEvent = function () { + + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = true; + Phaser.GAMES[_this.game.id].load.fileComplete(file); + + }; + + file.data.onerror = function () { + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = false; + _this.fileError(file); + }; + + file.data.addEventListener(file.loadEvent, videoLoadEvent, false); + + file.data.src = this.transformUrl(file.url, file); + file.data.load(); + + }, + + /** + * Continue async loading through an Audio tag. + * @private + */ + loadAudioTag: function (file) { + + var _this = this; + + if (this.game.sound.touchLocked) + { + // If audio is locked we can't do this yet, so need to queue this load request. Bum. + file.data = new Audio(); + file.data.name = file.key; + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + + this.fileComplete(file); + } + else + { + file.data = new Audio(); + file.data.name = file.key; + + var playThroughEvent = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileComplete(file); + }; + + file.data.onerror = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileError(file); + }; + + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + file.data.addEventListener('canplaythrough', playThroughEvent, false); + file.data.load(); + } + + }, + + /** + * Starts the xhr loader. + * + * This is designed specifically to use with asset file processing. + * + * @method Phaser.Loader#xhrLoad + * @private + * @param {object} file - The file/pack to load. + * @param {string} url - The URL of the file. + * @param {string} type - The xhr responseType. + * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments. + * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments. + */ + xhrLoad: function (file, url, type, onload, onerror) { + + var xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = type; + + if (this.headers['requestedWith'] !== false) + { + xhr.setRequestHeader('X-Requested-With', this.headers['requestedWith']); + } + + if (this.headers[file.type]) + { + xhr.setRequestHeader('Accept', this.headers[file.type]); + } + + onerror = onerror || this.fileError; + + var _this = this; + + xhr.onload = function () { + + try { + if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. + return onerror.call(_this, file, xhr); + } + else { + return onload.call(_this, file, xhr); + } + } catch (e) { + + // If this was the last file in the queue and an error is thrown in the create method + // then it's caught here, so be sure we don't carry on processing it + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + } + }; + + xhr.onerror = function () { + + try { + + return onerror.call(_this, file, xhr); + + } catch (e) { + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + + } + }; + + file.requestObject = xhr; + file.requestUrl = url; + + xhr.send(); + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getVideoURL + * @private + * @param {object[]|string[]} urls - See {@link #video} for format. + * @return {string} The URL to try and fetch; or null. + */ + getVideoURL: function (urls) { + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var videoType; + + if (url.uri) // {uri: .., type: ..} pair + { + videoType = url.type; + url = url.uri; + + if (this.game.device.canPlayVideo(videoType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + videoType = extension.toLowerCase(); + + if (this.game.device.canPlayVideo(videoType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getAudioURL + * @private + * @param {object[]|string[]} urls - See {@link #audio} for format. + * @return {string} The URL to try and fetch; or null. + */ + getAudioURL: function (urls) { + + if (this.game.sound.noAudio) + { + return null; + } + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var audioType; + + if (url.uri) // {uri: .., type: ..} pair + { + audioType = url.type; + url = url.uri; + + if (this.game.device.canPlayAudio(audioType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + audioType = extension.toLowerCase(); + + if (this.game.device.canPlayAudio(audioType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Error occurred when loading a file. + * + * @method Phaser.Loader#fileError + * @private + * @param {object} file + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + * @param {string} reason + */ + fileError: function (file, xhr, reason) { + + var url = file.requestUrl || this.transformUrl(file.url, file); + var message = 'error loading asset from URL ' + url; + + if (!reason && xhr) + { + reason = xhr.status; + } + + if (reason) + { + message = message + ' (' + reason + ')'; + } + + this.asyncComplete(file, message); + + }, + + /** + * Called when a file has been downloaded and needs to be processed further. + * + * @method Phaser.Loader#fileComplete + * @private + * @param {object} file - File loaded + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + */ + fileComplete: function (file, xhr) { + + var loadNext = true; + + switch (file.type) + { + case 'packfile': + + // Pack data must never be false-ish after it is fetched without error + var data = JSON.parse(xhr.responseText); + file.data = data || {}; + break; + + case 'texture': + + var extension = /\.([^.]+)$/.exec(file.url.split('?', 1)[0])[1].toLowerCase(); + if (file.data !== null) + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, file.data); + } + else + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, xhr.response); + } + break; + + case 'image': + + this.cache.addImage(file.key, file.url, file.data); + break; + + case 'spritesheet': + + this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case 'textureatlas': + + if (file.atlasURL == null) + { + this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); + } + else + { + // Load the JSON or XML before carrying on with the next file + loadNext = false; + + if (file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_HASH || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete); + } + else + { + throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); + } + } + break; + + case 'bitmapfont': + + if (!file.atlasURL) + { + this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing); + } + else + { + // Load the XML before carrying on with the next file + loadNext = false; + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) { + var json; + + try + { + // Try to parse as JSON, if it fails, then it's hopefully XML + json = JSON.parse(xhr.responseText); + } + catch (e) {} + + if (!!json) + { + file.atlasType = 'json'; + this.jsonLoadComplete(file, xhr); + } + else + { + file.atlasType = 'xml'; + this.xmlLoadComplete(file, xhr); + } + }); + } + break; + + case 'video': + + if (file.asBlob) + { + try + { + file.data = xhr.response; + } + catch (e) + { + throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key); + } + } + + this.cache.addVideo(file.key, file.url, file.data, file.asBlob); + break; + + case 'audio': + + if (this.game.sound.usingWebAudio) + { + file.data = xhr.response; + + this.cache.addSound(file.key, file.url, file.data, true, false); + + if (file.autoDecode) + { + this.game.sound.decode(file.key); + } + } + else + { + this.cache.addSound(file.key, file.url, file.data, false, true); + } + break; + + case 'text': + file.data = xhr.responseText; + this.cache.addText(file.key, file.url, file.data); + break; + + case 'shader': + file.data = xhr.responseText; + this.cache.addShader(file.key, file.url, file.data); + break; + + case 'physics': + var data = JSON.parse(xhr.responseText); + this.cache.addPhysicsData(file.key, file.url, data, file.format); + break; + + case 'script': + file.data = document.createElement('script'); + file.data.language = 'javascript'; + file.data.type = 'text/javascript'; + file.data.defer = false; + file.data.text = xhr.responseText; + document.head.appendChild(file.data); + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText); + } + break; + + case 'binary': + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.response); + } + else + { + file.data = xhr.response; + } + + this.cache.addBinary(file.key, file.data); + + break; + } + + if (loadNext) + { + this.asyncComplete(file); + } + + }, + + /** + * Successfully loaded a JSON file - only used for certain types. + * + * @method Phaser.Loader#jsonLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + jsonLoadComplete: function (file, xhr) { + + var data = JSON.parse(xhr.responseText); + + if (file.type === 'tilemap') + { + this.cache.addTilemap(file.key, file.url, data, file.format); + } + else if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'json') + { + this.cache.addJSON(file.key, file.url, data); + } + else + { + this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); + } + + this.asyncComplete(file); + }, + + /** + * Successfully loaded a CSV file - only used for certain types. + * + * @method Phaser.Loader#csvLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + csvLoadComplete: function (file, xhr) { + + var data = xhr.responseText; + + this.cache.addTilemap(file.key, file.url, data, file.format); + + this.asyncComplete(file); + + }, + + /** + * Successfully loaded an XML file - only used for certain types. + * + * @method Phaser.Loader#xmlLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + xmlLoadComplete: function (file, xhr) { + + // Always try parsing the content as XML, regardless of actually response type + var data = xhr.responseText; + var xml = this.parseXml(data); + + if (!xml) + { + var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest + console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')'); + this.asyncComplete(file, "invalid XML"); + return; + } + + if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'textureatlas') + { + this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); + } + else if (file.type === 'xml') + { + this.cache.addXML(file.key, file.url, xml); + } + + this.asyncComplete(file); + + }, + + /** + * Parses string data as XML. + * + * @method Phaser.Loader#parseXml + * @private + * @param {string} data - The XML text to parse + * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document. + */ + parseXml: function (data) { + + var xml; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + // Why is this 'false'? + xml.async = 'false'; + xml.loadXML(data); + } + } + catch (e) + { + xml = null; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + return null; + } + else + { + return xml; + } + + }, + + /** + * Update the loading sprite progress. + * + * @method Phaser.Loader#updateProgress + * @private + */ + updateProgress: function () { + + if (this.preloadSprite) + { + if (this.preloadSprite.direction === 0) + { + this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress); + } + else + { + this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress); + } + + if (this.preloadSprite.sprite) + { + this.preloadSprite.sprite.updateCrop(); + } + else + { + // We seem to have lost our sprite - maybe it was destroyed? + this.preloadSprite = null; + } + } + + }, + + /** + * Returns the number of files that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedFiles + * @protected + * @return {number} The number of files that have already been loaded (even if they errored) + */ + totalLoadedFiles: function () { + + return this._loadedFileCount; + + }, + + /** + * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedFiles + * @protected + * @return {number} The number of files that still remain in the load queue. + */ + totalQueuedFiles: function () { + + return this._totalFileCount - this._loadedFileCount; + + }, + + /** + * Returns the number of asset packs that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedPacks + * @protected + * @return {number} The number of asset packs that have already been loaded (even if they errored) + */ + totalLoadedPacks: function () { + + return this._totalPackCount; + + }, + + /** + * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedPacks + * @protected + * @return {number} The number of asset packs that still remain in the load queue. + */ + totalQueuedPacks: function () { + + return this._totalPackCount - this._loadedPackCount; + + } + +}; + +/** +* The non-rounded load progress value (from 0.0 to 100.0). +* +* A general indicator of the progress. +* It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. +* +* @name Phaser.Loader#progressFloat +* @property {number} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progressFloat", { + + get: function () { + var progress = (this._loadedFileCount / this._totalFileCount) * 100; + return Phaser.Math.clamp(progress || 0, 0, 100); + } + +}); + +/** +* The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}. +* +* @name Phaser.Loader#progress +* @property {integer} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progress", { + + get: function () { + return Math.round(this.progressFloat); + } + +}); + +Phaser.Loader.prototype.constructor = Phaser.Loader; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. +* +* @class Phaser.LoaderParser +*/ +Phaser.LoaderParser = { + + /** + * Alias for xmlBitmapFont, for backwards compatibility. + * + * @method Phaser.LoaderParser.bitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + bitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing, frame, resolution); + + }, + + /** + * Parse a Bitmap Font from an XML file. + * + * @method Phaser.LoaderParser.xmlBitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing; + data.chars = {}; + + var letters = xml.getElementsByTagName('char'); + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + for (var i = 0; i < letters.length; i++) + { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + data.chars[charCode] = { + x: x + parseInt(letters[i].getAttribute('x'), 10), + y: y + parseInt(letters[i].getAttribute('y'), 10), + width: parseInt(letters[i].getAttribute('width'), 10), + height: parseInt(letters[i].getAttribute('height'), 10), + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10) / resolution, + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10) / resolution, + xAdvance: (parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing) / resolution, + kerning: {} + }; + } + + var kernings = xml.getElementsByTagName('kerning'); + + for (i = 0; i < kernings.length; i++) + { + var first = parseInt(kernings[i].getAttribute('first'), 10); + var second = parseInt(kernings[i].getAttribute('second'), 10); + var amount = parseInt(kernings[i].getAttribute('amount'), 10) / resolution; + + data.chars[second].kerning[first] = amount; + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Parse a Bitmap Font from a JSON file. + * + * @method Phaser.LoaderParser.jsonBitmapFont + * @param {object} json - JSON data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = { + font: json.font.info._face, + size: parseInt(json.font.info._size, 10), + lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing, + chars: {} + }; + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + json.font.chars["char"].forEach( + + function parseChar(letter) { + + var charCode = parseInt(letter._id, 10); + + data.chars[charCode] = { + x: x + parseInt(letter._x, 10), + y: y + parseInt(letter._y, 10), + width: parseInt(letter._width, 10), + height: parseInt(letter._height, 10), + xOffset: parseInt(letter._xoffset, 10) / resolution, + yOffset: parseInt(letter._yoffset, 10) / resolution, + xAdvance: (parseInt(letter._xadvance, 10) + xSpacing) / resolution, + kerning: {} + }; + } + + ); + + if (json.font.kernings && json.font.kernings.kerning) + { + json.font.kernings.kerning.forEach( + + function parseKerning(kerning) { + + data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10) / resolution; + + } + + ); + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Finalize Bitmap Font parsing. + * + * @method Phaser.LoaderParser.finalizeBitmapFont + * @private + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {object} bitmapFontData - Pre-parsed bitmap font data. + * @return {object} The parsed Bitmap Font data. + */ + finalizeBitmapFont: function (baseTexture, bitmapFontData) { + + Object.keys(bitmapFontData.chars).forEach( + + function addTexture(charCode) { + + var letter = bitmapFontData.chars[charCode]; + + letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height)); + + } + + ); + + return bitmapFontData; + + }, + + /** + * Extract PVR header from loaded binary + * + * @method Phaser.LoaderParser.pvr + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PVR file including texture data. + */ + pvr: function (arrayBuffer) { + + // Reference: http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf + // PVR 3 header structure + // --------------------------------------- + // address: 0, size: 4 bytes version + // address: 4, size: 4 bytes flags + // address: 8, size: 8 bytes pixel format + // address: 16, size: 4 bytes color space + // address: 20, size: 4 bytes channel type + // address: 24, size: 4 bytes height + // address: 28, size: 4 bytes width + // address: 32, size: 4 bytes depth + // address: 36, size: 4 bytes number of surfaces + // address: 40, size: 4 bytes number of faces + // address: 44, size: 4 bytes number of mipmaps + // address: 48, size: 4 bytes meta data size + // --------------------------------------- + var uintArray = new Uint32Array(arrayBuffer.slice(0, 52)), + byteArray = new Uint8Array(arrayBuffer), + pvrHeader = null, + pixelFormat = (uintArray[3] << 32 | uintArray[2]), + compressionAlgorithm, + glExtensionFormat = 0; + + if (uintArray[0] === 0x03525650 && + [ // Validate WebGL Pixel Format + 0, 1, 2, 3, + 6, 7, 9, 11 + ].indexOf(pixelFormat) >= 0 + ) { + if (pixelFormat >= 0 && pixelFormat <= 3) { + compressionAlgorithm = 'PVRTC'; + } else if (pixelFormat >= 7 && pixelFormat <= 11) { + compressionAlgorithm = 'S3TC'; + } else if (pixelFormat === 6) { + compressionAlgorithm = 'ETC1'; + } + + switch (pixelFormat) { + case 0: + glExtensionFormat = 0x8C01; + break; + case 1: + glExtensionFormat = 0x8C03; + break; + case 2: + glExtensionFormat = 0x8C00; + break; + case 3: + glExtensionFormat = 0x8C02; + break; + case 6: + glExtensionFormat = 0x8D64; + break; + case 7: + glExtensionFormat = 0x83F1; + break; + case 9: + glExtensionFormat = 0x83F2; + break; + case 11: + glExtensionFormat = 0x83F3; + break; + default: + glExtensionFormat = -1; + } + + pvrHeader = { + complete: true, + fileFormat: 'PVR', + compressionAlgorithm: compressionAlgorithm, + flags: uintArray[1], + pixelFormat: pixelFormat, + colorSpace: uintArray[4], + channelType: uintArray[5], + height: uintArray[6], + width: uintArray[7], + depth: uintArray[8], + numberOfSurfaces: uintArray[9], + numberOfFaces: uintArray[10], + numberOfMipmaps: uintArray[11], + metaDataSize: uintArray[12], + textureData: byteArray.subarray(52 + uintArray[12], byteArray.byteLength), + glExtensionFormat: glExtensionFormat + }; + } + + return pvrHeader; + + }, + + /** + * Extract DDS header from loaded binary + * + * @method Phaser.LoaderParser.dds + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed DDS file including texture data. + */ + dds: function (arrayBuffer) { + + // Reference at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx + // DDS header structure + // --------------------------------------- + // address: 0, size: 4 bytes Identifier 'DDS ' + // address: 4, size: 4 bytes size + // address: 8, size: 4 bytes flags + // address: 12, size: 4 bytes height + // address: 16, size: 4 bytes width + // address: 20, size: 4 bytes pitch or linear size + // address: 24, size: 4 bytes depth + // address: 28, size: 4 bytes mipmap count + // address: 32, size: 44 bytes reserved space 1 + // address: 76, size: 4 pixel format size + // address: 80, size: 4 pixel format flag + // address: 84, size: 4 pixel format four CC + // address: 88, size: 4 pixel format bit count + // address: 92, size: 4 pixel format R bit mask + // address: 96, size: 4 pixel format G bit mask + // address: 100, size: 4 pixel format B bit mask + // address: 104, size: 4 pixel format A bit mask + // address: 108, size: 4 caps 1 + // address: 112, size: 4 caps 2 + // address: 116, size: 4 caps 3 + // address: 120, size: 4 caps 4 + // address: 124, size: 4 reserved 2 + // -- DXT10 extension + // address: 130, size: 4 DXGI Format + // address: 134, size: 4 resource dimension + // address: 138, size: 4 misc flag + // address: 142, size: 4 array size + // address: 146, size: 4 misc flag 2 + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ddsHeader = null; + + if (byteArray[0] === 0x44 && + byteArray[1] === 0x44 && + byteArray[2] === 0x53 && + byteArray[3] === 0x20) { + ddsHeader = { + complete: true, + fileFormat: 'DDS', + compressionAlgorithm: 'S3TC', + size: uintArray[1], + flags: uintArray[2], + height: uintArray[3], + width: uintArray[4], + pitch: uintArray[5], + depth: uintArray[6], + mipmapCount: uintArray[7], + formatSize: uintArray[19], + formatFlag: uintArray[19], + formatFourCC: [ + String.fromCharCode(byteArray[84]), + String.fromCharCode(byteArray[85]), + String.fromCharCode(byteArray[86]), + String.fromCharCode(byteArray[87]) + ].join(''), + formatBitCount: uintArray[21], + formatRBitMask: uintArray[22], + formatGBitMask: uintArray[23], + formatBBitMask: uintArray[24], + formatABitMask: uintArray[25], + caps1: uintArray[26], + caps2: uintArray[27], + caps3: uintArray[28], + caps4: uintArray[29], + reserved2: uintArray[30], + DXGIFormat: null, + resourceDimension: null, + miscFlag: null, + arraySize: null, + textureData: byteArray.subarray(uintArray[1] + 4, byteArray.byteLength) + }; + if (ddsHeader.formatFourCC === 'DX10') { + ddsHeader.DXGIFormat = uintArray[31]; + ddsHeader.resourceDimension = uintArray[32]; + ddsHeader.miscFlag = uintArray[33]; + ddsHeader.arraySize = uintArray[34]; + ddsHeader.miscFlag = uintArray[35]; + } + } + + return ddsHeader; + + }, + + /** + * Extract KTX header from loaded binary + * + * @method Phaser.LoaderParser.ktx + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed KTX file including texture data. + */ + ktx: function (arrayBuffer) { + + // Reference: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + // KTX header structure + // --------------------------------------- + // address: 0, size 12 bytes: Identifier '«KTX 11»\r\n\x1A\n' + // address: 12, size 4 bytes: endianness + // address: 16, size 4 bytes: GL type + // address: 20, size 4 bytes: GL type size + // address: 24, size 4 bytes: GL format + // address: 28, size 4 bytes: GL internal format + // address: 32, size 4 bytes: GL base internal format + // address: 36, size 4 bytes: pixel width + // address: 40, size 4 bytes: pixel height + // address: 44, size 4 bytes: pixel depth + // address: 48, size 4 bytes: number of array elements + // address: 52, size 4 bytes: number of faces + // address: 56, size 4 bytes: number of mipmap levels + // address: 60, size 4 bytes: bytes of key value data + // address: 64, size 4 bytes: key and value bytes size + // address: X, size 1 byte : key and value + // address: X, size 1 byte : value padding + // address: X, size 4 byte : image size + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ktxHeader = null, + imageSizeOffset = 16 + (uintArray[15] / 4) | 0, + imageSize = uintArray[imageSizeOffset], + glInternalFormat = uintArray[7], + compressionAlgorithm = 0; + + if (byteArray[0] === 0xAB && byteArray[1] === 0x4B && + byteArray[2] === 0x54 && byteArray[3] === 0x58 && + byteArray[4] === 0x20 && byteArray[5] === 0x31 && + byteArray[6] === 0x31 && byteArray[7] === 0xBB && + byteArray[8] === 0x0D && byteArray[9] === 0x0A && + byteArray[10] === 0x1A && byteArray[11] === 0x0A && + //Check if internal GL format is supported by WebGL + [ + // ETC1 + 0x8D64, + // PVRTC + 0x8C00, 0x8C01, 0x8C02, 0x8C03, + // DXTC | S3TC + 0x83F0, 0x83F1, 0x83F2, 0x83F3 + ].indexOf(glInternalFormat) >= 0) { + switch (glInternalFormat) { + case 0x8D64: + compressionAlgorithm = 'ETC1'; + break; + case 0x8C00: + case 0x8C01: + case 0x8C02: + case 0x8C03: + compressionAlgorithm = 'PVRTC'; + break; + case 0x83F0: + case 0x83F1: + case 0x83F2: + case 0x83F3: + compressionAlgorithm = 'S3TC'; + break; + } + + ktxHeader = { + complete: true, + fileFormat: 'KTX', + compressionAlgorithm: compressionAlgorithm, + endianness: uintArray[3], + glType: uintArray[4], + glTypeSize: uintArray[5], + glFormat: uintArray[6], + glInternalFormat: uintArray[7], + glBaseInternalFormat: uintArray[8], + width: uintArray[9], + height: uintArray[10], + pixelDepth: uintArray[11], + numberOfArrayElements: uintArray[12], + numberOfFaces: uintArray[13], + numberOfMipmapLevels: uintArray[14], + bytesOfKeyValueData: uintArray[15], + keyAndValueByteSize: uintArray[16], + imageSize: imageSize, + textureData: byteArray.subarray((imageSizeOffset + 1) * 4, imageSize + 100) + }; + } + + return ktxHeader; + + }, + + /** + * Extract PKM header from loaded binary + * + * @method Phaser.LoaderParser.pkm + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PKM file including texture data. + */ + pkm: function (arrayBuffer) { + + // PKM header structure + // --------------------------------------- + // address: 0, size 4 bytes: for 'PKM ' + // address: 4, size 2 bytes: for version + // address: 6, size 2 bytes: for type + // address: 8, size 2 bytes: for extended width + // address: 10, size 2 bytes: for extended height + // address: 12, size 2 bytes: for original width + // address: 14, size 2 bytes: for original height + // address: 16, texture data + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + pkmHeader = null; + + if (byteArray[0] === 0x50 && + byteArray[1] === 0x4B && + byteArray[2] === 0x4D && + byteArray[3] === 0x20) { + + pkmHeader = { + complete: true, + fileFormat: 'PKM', + compressionAlgorithm: 'ETC1', + format: ((byteArray[6] << 8 | byteArray[7])) & 0xFFFF, + width: ((byteArray[8] << 8 | byteArray[9])) & 0xFFFF, + height: ((byteArray[10] << 8 | byteArray[11])) & 0xFFFF, + originalWidth: ((byteArray[12] << 8 | byteArray[13])) & 0xFFFF, + originalHeight: ((byteArray[14] << 8 | byteArray[15])) & 0xFFFF, + textureData: byteArray.subarray(16, byteArray.length) + }; + } + + return pkmHeader; + + } + +}; + +/** + * @author Jeremy Dowell + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * Audio Sprites are a combination of audio files and a JSON configuration. + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * @class Phaser.AudioSprite + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + * @param {string} key - Asset key for the sound. + */ +Phaser.AudioSprite = function (game, key) { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * Asset key for the Audio Sprite. + * @property {string} key + */ + this.key = key; + + /** + * JSON audio atlas object. + * @property {object} config + */ + this.config = this.game.cache.getJSON(key + '-audioatlas'); + + /** + * If a sound is set to auto play, this holds the marker key of it. + * @property {string} autoplayKey + */ + this.autoplayKey = null; + + /** + * Is a sound set to autoplay or not? + * @property {boolean} autoplay + * @default + */ + this.autoplay = false; + + /** + * An object containing the Phaser.Sound objects for the Audio Sprite. + * @property {object} sounds + */ + this.sounds = {}; + + for (var k in this.config.spritemap) + { + var marker = this.config.spritemap[k]; + var sound = this.game.add.sound(this.key); + + sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop); + + this.sounds[k] = sound; + } + + if (this.config.autoplay) + { + this.autoplayKey = this.config.autoplay; + this.play(this.autoplayKey); + this.autoplay = this.sounds[this.autoplayKey]; + } + +}; + +Phaser.AudioSprite.prototype = { + + /** + * Play a sound with the given name. + * + * @method Phaser.AudioSprite#play + * @param {string} [marker] - The name of sound to play + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, volume) { + + if (volume === undefined) { volume = 1; } + + return this.sounds[marker].play(marker, null, volume); + + }, + + /** + * Stop a sound with the given name. + * + * @method Phaser.AudioSprite#stop + * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite. + */ + stop: function (marker) { + + if (!marker) + { + for (var key in this.sounds) + { + this.sounds[key].stop(); + } + } + else + { + this.sounds[marker].stop(); + } + + }, + + /** + * Get a sound with the given name. + * + * @method Phaser.AudioSprite#get + * @param {string} marker - The name of sound to get. + * @return {Phaser.Sound} The sound instance. + */ + get: function(marker) { + + return this.sounds[marker]; + + } + +}; + +Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound class constructor. +* +* @class Phaser.Sound +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {string} key - Asset key for the sound. +* @param {number} [volume=1] - Default value for the volume, between 0 and 1. +* @param {boolean} [loop=false] - Whether or not the sound will loop. +*/ +Phaser.Sound = function (game, key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = game.sound.connectToMaster; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * @property {string} name - Name of the sound. + */ + this.name = key; + + /** + * @property {string} key - Asset key for the sound. + */ + this.key = key; + + /** + * @property {boolean} loop - Whether or not the sound or current sound marker will loop. + */ + this.loop = loop; + + /** + * @property {object} markers - The sound markers. + */ + this.markers = {}; + + /** + * @property {AudioContext} context - Reference to the AudioContext instance. + */ + this.context = null; + + /** + * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically. + */ + this.autoplay = false; + + /** + * @property {number} totalDuration - The total duration of the sound in seconds. + */ + this.totalDuration = 0; + + /** + * @property {number} startTime - The time the sound starts at in ms (typically 0 unless starting from a marker). + * @default + */ + this.startTime = 0; + + /** + * @property {number} currentTime - The current time of sound playback in ms. + */ + this.currentTime = 0; + + /** + * @property {number} duration - The duration of the current sound marker in seconds. + */ + this.duration = 0; + + /** + * @property {number} durationMS - The duration of the current sound marker in ms. + */ + this.durationMS = 0; + + /** + * @property {number} position - The position of the current sound marker in ms. + */ + this.position = 0; + + /** + * @property {number} stopTime - The time the sound stopped in ms. + */ + this.stopTime = 0; + + /** + * @property {boolean} paused - true if the sound is paused, otherwise false. + * @default + */ + this.paused = false; + + /** + * @property {number} pausedPosition - The position the sound had reached when it was paused in ms. + */ + this.pausedPosition = 0; + + /** + * @property {number} pausedTime - The game time (ms) at which the sound was paused. + */ + this.pausedTime = 0; + + /** + * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false. + * @default + */ + this.isPlaying = false; + + /** + * @property {string} currentMarker - The string ID of the currently playing marker, if any. + * @default + */ + this.currentMarker = ''; + + /** + * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. + */ + this.fadeTween = null; + + /** + * @property {boolean} pendingPlayback - true if the sound file is pending playback + * @readonly + */ + this.pendingPlayback = false; + + /** + * @property {boolean} override - if true when you play this sound it will always start from the beginning. + * @default + */ + this.override = false; + + /** + * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. + * @default + */ + this.allowMultiple = false; + + /** + * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio. + * @readonly + */ + this.usingWebAudio = this.game.sound.usingWebAudio; + + /** + * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag. + */ + this.usingAudioTag = this.game.sound.usingAudioTag; + + /** + * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. + */ + this.externalNode = null; + + /** + * @property {object} masterGainNode - The master gain node in a Web Audio system. + */ + this.masterGainNode = null; + + /** + * @property {object} gainNode - The gain node in a Web Audio system. + */ + this.gainNode = null; + + /** + * @property {object} _sound - Internal var. + * @private + */ + this._sound = null; + + /** + * @property {object} _globalVolume - Internal var for keeping track of global volume when using AudioTag + * @private + */ + this._globalVolume = 1; + + /** + * @property {boolean} _markedToDelete - When audio stops, disconnect Web Audio nodes. + * @private + */ + this._markedToDelete = false; + + /** + * @property {boolean} _removeFromSoundManager - When audio stops, remove it from the Sound Manager and destroy it. + * @private + */ + this._removeFromSoundManager = false; + + + + if (this.usingWebAudio) + { + this.context = this.game.sound.context; + this.masterGainNode = this.game.sound.masterGain; + + if (this.context.createGain === undefined) + { + this.gainNode = this.context.createGainNode(); + } + else + { + this.gainNode = this.context.createGain(); + } + + this.gainNode.gain.value = volume; + + if (connect) + { + this.gainNode.connect(this.masterGainNode); + } + } + else if (this.usingAudioTag) + { + if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key)) + { + this._sound = this.game.cache.getSoundData(key); + this.totalDuration = 0; + + if (this._sound.duration) + { + this.totalDuration = this._sound.duration; + } + } + else + { + this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this); + } + } + + /** + * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files). It passes one argument, this sound. + */ + this.onDecoded = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played or a looping marker is restarted. It passes one argument, this sound. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. It passes one argument, this sound. + */ + this.onPause = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. It passes one argument, this sound. + */ + this.onResume = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. It passes one argument, this sound. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback or when a non-looping marker completes. It passes two arguments: this sound and any {@link #currentMarker marker} that was playing. + */ + this.onStop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted. It passes one argument, this sound. + */ + this.onMute = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. It passes two arguments: the {@link #currentMarker} and this sound. + */ + this.onMarkerComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out. It passes two arguments: this sound and its current {@link #volume}. + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + */ + this._volume = volume; + + /** + * @property {any} _buffer - Decoded data buffer / Audio tag. + * @private + */ + this._buffer = null; + + /** + * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. + * @private + */ + this._muted = false; + + /** + * @property {number} _tempMarker - Internal marker var. + * @private + */ + this._tempMarker = 0; + + /** + * @property {number} _tempPosition - Internal marker var. + * @private + */ + this._tempPosition = 0; + + /** + * @property {number} _tempVolume - Internal marker var. + * @private + */ + this._tempVolume = 0; + + /** + * @property {number} _tempPause - Internal marker var. + * @private + */ + this._tempPause = 0; + + /** + * @property {number} _muteVolume - Internal cache var. + * @private + */ + this._muteVolume = 0; + + /** + * @property {boolean} _tempLoop - Internal cache var. + * @private + */ + this._tempLoop = 0; + + /** + * @property {boolean} _paused - Was this sound paused via code or a game event? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched? + * @private + */ + this._onDecodedEventDispatched = false; + +}; + +Phaser.Sound.prototype = { + + /** + * Called automatically when this sound is unlocked. + * @method Phaser.Sound#soundHasUnlocked + * @param {string} key - The Phaser.Cache key of the sound file to check for decoding. + * @protected + */ + soundHasUnlocked: function (key) { + + if (key === this.key) + { + this._sound = this.game.cache.getSoundData(this.key); + this.totalDuration = this._sound.duration; + } + + }, + + /** + * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound#addMarker + * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. + * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). + * @param {boolean} [loop=false] - Sets if the sound will loop or not. + */ + addMarker: function (name, start, duration, volume, loop) { + + if (duration === undefined || duration === null) { duration = 1; } + if (volume === undefined || volume === null) { volume = 1; } + if (loop === undefined) { loop = false; } + + this.markers[name] = { + name: name, + start: start, + stop: start + duration, + volume: volume, + duration: duration, + durationMS: duration * 1000, + loop: loop + }; + + }, + + /** + * Removes a marker from the sound. + * @method Phaser.Sound#removeMarker + * @param {string} name - The key of the marker to remove. + */ + removeMarker: function (name) { + + delete this.markers[name]; + + }, + + /** + * Called automatically by the AudioContext when the sound stops playing. + * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. + * + * @method Phaser.Sound#onEndedHandler + * @protected + */ + onEndedHandler: function () { + + this._sound.onended = null; + this.isPlaying = false; + this.currentTime = this.durationMS; + this.stop(); + + if (this._markedToDelete) + { + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + if (this._removeFromSoundManager) + { + this.game.sound.remove(this); + } + else + { + 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(); + } + } + }, + + /** + * Called automatically by Phaser.SoundManager. + * @method Phaser.Sound#update + * @protected + */ + update: function () { + + if (!this.game.cache.checkSoundKey(this.key)) + { + this.destroy(); + return; + } + + if (this.isDecoded && !this._onDecodedEventDispatched) + { + this.onDecoded.dispatch(this); + this._onDecodedEventDispatched = true; + } + + if (this.pendingPlayback && this.game.cache.isSoundReady(this.key)) + { + this.pendingPlayback = false; + this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop); + } + + if (this.isPlaying) + { + this.currentTime = this.game.time.time - this.startTime; + + if (this.currentTime >= this.durationMS) + { + if (this.usingWebAudio) + { + if (this.loop) + { + // won't work with markers, needs to reset the position + this.onLoop.dispatch(this); + + // Gets reset by the play function + this.isPlaying = false; + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + this.isPlaying = true; // play not called again in this case + } + else + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + this.play(this.currentMarker, 0, this.volume, true, true); + } + } + else + { + // Stop if we're using an audio marker, otherwise we let onended handle it + if (this.currentMarker !== '') + { + this.stop(); + } + } + } + else + { + if (this.loop) + { + this.onLoop.dispatch(this); + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + } + + // Gets reset by the play function + this.isPlaying = false; + + this.play(this.currentMarker, 0, this.volume, true, true); + } + else + { + this.stop(); + } + } + } + } + }, + + /** + * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters. + * + * @method Phaser.Sound#loopFull + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + loopFull: function (volume) { + + return this.play(null, 0, volume, true); + + }, + + /** + * Play this sound, or a marked section of it. + * + * @method Phaser.Sound#play + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. + * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, position, volume, loop, forceRestart) { + + if (marker === undefined || marker === false || marker === null) { marker = ''; } + if (forceRestart === undefined) { forceRestart = true; } + + if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override) + { + // Use Restart instead + return this; + } + + if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart)) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) { + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + + this.isPlaying = false; + } + + if (marker === '' && Object.keys(this.markers).length > 0) + { + // If they didn't specify a marker but this is an audio sprite, + // we should never play the entire thing + return this; + } + + if (marker !== '') + { + if (this.markers[marker]) + { + this.currentMarker = marker; + + // Playing a marker? Then we default to the marker values + 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 (volume === undefined) { volume = this._volume; } + if (loop === undefined) { loop = this.loop; } + + this.position = Math.max(0, 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) + { + // Does the sound need decoding? + if (this.game.cache.isSoundDecoded(this.key)) + { + this._sound = this.context.createBufferSource(); + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + this._buffer = this.game.cache.getSoundData(this.key); + this._sound.buffer = this._buffer; + + if (this.loop && marker === '') + { + this._sound.loop = true; + } + + if (!this.loop && marker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + this.totalDuration = this._sound.buffer.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = Math.ceil(this.totalDuration * 1000); + } + + // Useful to cache this somewhere perhaps? + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, this.position, this.duration); + } + else + { + if (this.loop && marker === '') + { + this._sound.start(0, 0); + } + else + { + this._sound.start(0, this.position, this.duration); + } + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + 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 doesn't become available until you call play(), wonderful ... + this.totalDuration = this._sound.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = this.totalDuration * 1000; + } + + this._sound.currentTime = this.position; + this._sound.muted = this._muted; + + if (this._muted || this.game.sound.mute) + { + this._sound.volume = 0; + } + else + { + this._sound.volume = this._volume; + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + this.currentTime = 0; + this.stopTime = this.startTime + this.durationMS; + + this.onPlay.dispatch(this); + } + else + { + this.pendingPlayback = true; + } + } + } + + return this; + + }, + + /** + * Restart the sound, or a marked section of it. + * + * @method Phaser.Sound#restart + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. + * @param {boolean} [loop=false] - Loop when it finished playing? + */ + restart: function (marker, position, volume, loop) { + + marker = marker || ''; + position = position || 0; + volume = volume || 1; + if (loop === undefined) { loop = false; } + + this.play(marker, position, volume, loop, true); + + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound#pause + */ + pause: function () { + + if (this.isPlaying && this._sound) + { + this.paused = true; + this.pausedPosition = this.currentTime; + this.pausedTime = this.game.time.time; + this._tempPause = this._sound.currentTime; + this.onPause.dispatch(this); + this.stop(); + } + + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound#resume + */ + resume: function () { + + if (this.paused && this._sound) + { + if (this.usingWebAudio) + { + var p = Math.max(0, this.position + (this.pausedPosition / 1000)); + + this._sound = this.context.createBufferSource(); + this._sound.buffer = this._buffer; + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + if (this.loop) + { + this._sound.loop = true; + } + + if (!this.loop && this.currentMarker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + var duration = this.duration - (this.pausedPosition / 1000); + + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, p, duration); + //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it + } + else + { + if (this.loop && this.game.device.chrome) + { + // Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099 + if (this.game.device.chromeVersion === 42) + { + this._sound.start(0); + } + else + { + this._sound.start(0, p); + } + } + else + { + this._sound.start(0, p, duration); + } + } + } + else + { + this._sound.currentTime = this._tempPause; + this._sound.play(); + } + + this.isPlaying = true; + this.paused = false; + this.startTime += (this.game.time.time - this.pausedTime); + this.onResume.dispatch(this); + } + + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound#stop + */ + stop: function () { + + if (this.isPlaying && this._sound) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) + { + // Thanks Android 4.4 + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + } + + this.pendingPlayback = false; + this.isPlaying = false; + + if (!this.paused) + { + var prevMarker = this.currentMarker; + + if (this.currentMarker !== '') + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + } + + this.currentMarker = ''; + + if (this.fadeTween !== null) + { + this.fadeTween.stop(); + } + + this.onStop.dispatch(this, prevMarker); + } + + }, + + /** + * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. + * Then increases the volume from 0 to 1 over the duration specified. + * + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (1) as the second parameter. + * + * @method Phaser.Sound#fadeIn + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in. + * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. + * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. + */ + fadeIn: function (duration, loop, marker) { + + if (loop === undefined) { loop = false; } + if (marker === undefined) { marker = this.currentMarker; } + + if (this.paused) + { + return; + } + + this.play(marker, 0, 0, loop); + + this.fadeTo(duration, 1); + + }, + + /** + * Decreases the volume of this Sound from its current value to 0 over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (0) as the second parameter. + * + * @method Phaser.Sound#fadeOut + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out. + */ + fadeOut: function (duration) { + + this.fadeTo(duration, 0); + + }, + + /** + * Fades the volume of this Sound from its current value to the given volume over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (volume) as the second parameter. + * + * @method Phaser.Sound#fadeTo + * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out. + * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1. + */ + fadeTo: function (duration, volume) { + + if (!this.isPlaying || this.paused || volume === this.volume) + { + return; + } + + if (duration === undefined) { duration = 1000; } + + if (volume === undefined) + { + console.warn("Phaser.Sound.fadeTo: No Volume Specified."); + return; + } + + this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true); + + this.fadeTween.onComplete.add(this.fadeComplete, this); + + }, + + /** + * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo. + * + * @method Phaser.Sound#fadeComplete + * @private + */ + fadeComplete: function () { + + this.onFadeComplete.dispatch(this, this.volume); + + if (this.volume === 0) + { + this.stop(); + } + + }, + + /** + * Called automatically by SoundManager.volume. + * + * Sets the volume of AudioTag Sounds as a percentage of the Global Volume. + * + * You should not normally call this directly. + * + * @method Phaser.Sound#updateGlobalVolume + * @protected + * @param {float} globalVolume - The global SoundManager volume. + */ + updateGlobalVolume: function (globalVolume) { + + // this._volume is the % of the global volume this sound should be played at + + if (this.usingAudioTag && this._sound) + { + this._globalVolume = globalVolume; + this._sound.volume = this._globalVolume * this._volume; + } + + }, + + /** + * Destroys this sound and all associated events and removes it from the SoundManager. + * + * @method Phaser.Sound#destroy + * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager. + */ + destroy: function (remove) { + + if (remove === undefined) { remove = true; } + + this._markedToDelete = true; + this._removeFromSoundManager = remove; + this.stop(); + + if (remove) + { + this.game.sound.remove(this); + } + else + { + 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; + +/** +* @name Phaser.Sound#isDecoding +* @property {boolean} isDecoding - Returns true if the sound file is still decoding. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoding", { + + get: function () { + return this.game.cache.getSound(this.key).isDecoding; + } + +}); + +/** +* @name Phaser.Sound#isDecoded +* @property {boolean} isDecoded - Returns true if the sound file has decoded. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoded", { + + get: function () { + return this.game.cache.isSoundDecoded(this.key); + } + +}); + +/** +* @name Phaser.Sound#mute +* @property {boolean} mute - Gets or sets the muted state of this sound. +*/ +Object.defineProperty(Phaser.Sound.prototype, "mute", { + + get: function () { + + return (this._muted || this.game.sound.mute); + + }, + + set: function (value) { + + value = value || false; + + if (value === this._muted) + { + return; + } + + if (value) + { + this._muted = true; + this._muteVolume = this._tempVolume; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = 0; + } + else if (this.usingAudioTag && this._sound) + { + 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); + + } + +}); + +/** +* @name Phaser.Sound#volume +* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Sound.prototype, "volume", { + + get: function () { + return this._volume; + }, + + set: function (value) { + + // Causes an Index size error if you don't clamp the value + if (this.usingAudioTag) + { + value = this.game.math.clamp(value, 0, 1); + } + + if (this._muted) + { + this._muteVolume = value; + return; + } + + this._tempVolume = value; + this._volume = value; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = value; + } + else if (this.usingAudioTag && this._sound) + { + this._sound.volume = this._globalVolume * value; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. +* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. +* The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. +* There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ +* +* If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out +* of AudioContext nodes. If this is the case create a global var called {@link PhaserGlobal} on the window object before creating the game. The active +* AudioContext will then be saved to `window.PhaserGlobal.audioContext` when the Phaser game is destroyed, and re-used when it starts again. +* +* Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. +* When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. +* The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will +* be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. +* +* @class Phaser.SoundManager +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.SoundManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) + */ + this.onSoundDecode = new Phaser.Signal(); + + /** + * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. + * @property {Phaser.Signal} onVolumeChange + */ + this.onVolumeChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. + * @property {Phaser.Signal} onMute + */ + this.onMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. + * @property {Phaser.Signal} onUnMute + */ + this.onUnMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is touch-unlocked. + * If the device doesn't {@link Phaser.Device.needsTouchUnlock need touch-unlocking}, the signal won't be dispatched. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * @property {AudioContext} context - The AudioContext being used for playback. + * @default + */ + this.context = null; + + /** + * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio. + * @readonly + */ + this.usingWebAudio = false; + + /** + * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio. + * @readonly + */ + this.usingAudioTag = false; + + /** + * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. + * @default + */ + this.noAudio = false; + + /** + * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. + * @default + */ + this.connectToMaster = true; + + /** + * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. + * @default + */ + this.touchLocked = false; + + /** + * @property {number} channels - The number of audio channels to use in playback. + * @default + */ + this.channels = 32; + + /** + * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), + * or set to false to keep audio playing, regardless of the game pause state. You may need to + * do this should you wish to control audio muting via external DOM buttons or similar. + * @property {boolean} muteOnPause + * @default + */ + this.muteOnPause = true; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {AudioContext} _unlockSource - Internal unlock tracking var. + * @private + * @default + */ + this._unlockSource = null; + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + * @default + */ + this._volume = 1; + + + /** + * @property {array} _sounds - An array containing all the sounds + * @private + */ + this._sounds = []; + + /** + * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status. + * @private + */ + this._watchList = new Phaser.ArraySet(); + + /** + * @property {boolean} _watching - Is the SoundManager monitoring the watchList? + * @private + */ + this._watching = false; + + /** + * @property {function} _watchCallback - The callback to invoke once the watchlist is clear. + * @private + */ + this._watchCallback = null; + + /** + * @property {object} _watchContext - The context in which to call the watchlist callback. + * @private + */ + this._watchContext = null; + +}; + +Phaser.SoundManager.prototype = { + + /** + * Initialises the sound manager. + * @method Phaser.SoundManager#boot + * @protected + */ + boot: function () { + + var device = this.game.device; + var PhaserGlobal = window.PhaserGlobal; + + if (device.iOS && device.webAudio === false) + { + this.channels = 1; + } + + // PhaserGlobal overrides + if (PhaserGlobal) + { + // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class) + if (PhaserGlobal.disableAudio === true) + { + this.noAudio = true; + this.touchLocked = false; + return; + } + + // Check if the Web Audio API is disabled (for testing Audio Tag playback during development) + if (PhaserGlobal.disableWebAudio === true) + { + this.usingAudioTag = true; + this.touchLocked = false; + return; + } + } + + if (PhaserGlobal && PhaserGlobal.audioContext) + { + this.context = PhaserGlobal.audioContext; + } + else + { + if (!!window['AudioContext']) + { + try { + this.context = new window['AudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + else if (!!window['webkitAudioContext']) + { + try { + this.context = new window['webkitAudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + } + + if (this.context === null) + { + // No Web Audio support - how about legacy Audio? + if (window['Audio'] === undefined) + { + this.noAudio = true; + return; + } + else + { + this.usingAudioTag = true; + } + } + else + { + this.usingWebAudio = true; + + if (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); + } + + if (!this.noAudio) + { + // On mobile we need a native touch event before we can play anything, so capture it here + if (device.needsTouchUnlock()) + { + this.setTouchLock(); + } + } + + if (this.usingWebAudio && device.chrome && device.chromeVersion <= 65) + { + console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. '); + } + + }, + + /** + * Sets the Input Manager touch callback to be SoundManager.unlock. + * Required for iOS audio device unlocking. Mostly just used internally. + * + * @method Phaser.SoundManager#setTouchLock + */ + setTouchLock: function () { + + if (this.noAudio || (window.PhaserGlobal && window.PhaserGlobal.disableAudio === true)) + { + return; + } + + this.game.input.addTouchLockCallback(this.unlock, this, true); + + this.touchLocked = true; + + }, + + /** + * Turns off {@link #touchLocked} and dispatches {@link #onTouchUnlock}. + * + * @method Phaser.SoundManager#setTouchUnlock + * @private + */ + setTouchUnlock: function () { + + this.touchLocked = false; + this._unlockSource = null; + this.onTouchUnlock.dispatch(); + + }, + + /** + * Enables the audio, usually after the first touch. + * + * @method Phaser.SoundManager#unlock + * @return {boolean} True if the callback should be removed, otherwise false. + */ + unlock: function () { + + if (this.noAudio || !this.touchLocked || this._unlockSource !== null) + { + return true; + } + + // Global override (mostly for Audio Tag testing) + if (this.usingAudioTag) + { + this.setTouchUnlock(); + } + else if (this.usingWebAudio) + { + // Create empty buffer and play it + // The SoundManager.update loop captures the state of it and then resets touchLocked to false + + var buffer = this.context.createBuffer(1, 1, 22050); + this._unlockSource = this.context.createBufferSource(); + this._unlockSource.buffer = buffer; + this._unlockSource.connect(this.context.destination); + + if (this._unlockSource.start === undefined) + { + this._unlockSource.noteOn(0); + } + else + { + this._unlockSource.start(0); + } + + //This fixes locked audio in Chrome > 55 cross origin iframes + if (this._unlockSource.context.state === 'suspended') { + this._unlockSource.context.resume(); + } + } + + // We can remove the event because we've done what we needed (started the unlock sound playing) + return true; + + }, + + /** + * Stops all the sounds in the game. + * + * @method Phaser.SoundManager#stopAll + */ + stopAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].stop(); + } + } + + }, + + /** + * Pauses all the sounds in the game. + * + * @method Phaser.SoundManager#pauseAll + */ + pauseAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].pause(); + } + } + + }, + + /** + * Resumes every sound in the game. + * + * @method Phaser.SoundManager#resumeAll + */ + resumeAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].resume(); + } + } + + }, + + /** + * Decode a sound by its asset key. + * + * @method Phaser.SoundManager#decode + * @param {string} key - Assets key of the sound to be decoded. + * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. + */ + decode: function (key, sound) { + + sound = sound || null; + + var soundData = this.game.cache.getSoundData(key); + + if (soundData) + { + if (this.game.cache.isSoundDecoded(key) === false) + { + this.game.cache.updateSound(key, 'isDecoding', true); + + var _this = this; + + try { + this.context.decodeAudioData(soundData, function (buffer) { + + if (buffer) + { + _this.game.cache.decodedSound(key, buffer); + _this.onSoundDecode.dispatch(key, sound); + } + }); + } + catch (e) {} + } + } + + }, + + /** + * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback. + * Once all of the Sound files have finished decoding the callback will be invoked. + * The amount of time spent decoding depends on the codec used and file size. + * If all of the files given have already decoded the callback is triggered immediately. + * + * @method Phaser.SoundManager#setDecodedCallback + * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache. + * @param {Function} callback - The callback which will be invoked once all files have finished decoding. + * @param {Object} callbackContext - The context in which the callback will run. + */ + setDecodedCallback: function (files, callback, callbackContext) { + + if (typeof files === 'string') + { + files = [ files ]; + } + + this._watchList.reset(); + + for (var i = 0; i < files.length; i++) + { + if (files[i] instanceof Phaser.Sound) + { + if (!this.game.cache.isSoundDecoded(files[i].key)) + { + this._watchList.add(files[i].key); + } + } + else if (!this.game.cache.isSoundDecoded(files[i])) + { + this._watchList.add(files[i]); + } + } + + // All decoded already? + if (this._watchList.total === 0) + { + this._watching = false; + callback.call(callbackContext); + } + else + { + this._watching = true; + this._watchCallback = callback; + this._watchContext = callbackContext; + } + + }, + + /** + * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. + * + * @method Phaser.SoundManager#update + * @protected + */ + update: function () { + + if (this.noAudio) + { + return; + } + + if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE)) + { + this.setTouchUnlock(); + } + + for (var i = 0; i < this._sounds.length; i++) + { + this._sounds[i].update(); + } + + if (this._watching) + { + var key = this._watchList.first; + + while (key) + { + if (this.game.cache.isSoundDecoded(key)) + { + this._watchList.remove(key); + } + + key = this._watchList.next; + } + + if (this._watchList.total === 0) + { + this._watching = false; + this._watchCallback.call(this._watchContext); + } + } + + }, + + /** + * Adds a new Sound into the SoundManager. + * + * @method Phaser.SoundManager#add + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The new sound instance. + */ + add: function (key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = this.connectToMaster; } + + var sound = new Phaser.Sound(this.game, key, volume, loop, connect); + + this._sounds.push(sound); + + return sound; + + }, + + /** + * Adds a new AudioSprite into the SoundManager. + * + * @method Phaser.SoundManager#addSprite + * @param {string} key - Asset key for the sound. + * @return {Phaser.AudioSprite} The new AudioSprite instance. + */ + addSprite: function(key) { + + var audioSprite = new Phaser.AudioSprite(this.game, key); + + return audioSprite; + + }, + + /** + * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. + * + * @method Phaser.SoundManager#remove + * @param {Phaser.Sound} sound - The sound object to remove. + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ + remove: function (sound) { + + var i = this._sounds.length; + + while (i--) + { + if (this._sounds[i] === sound) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Removes all Sounds from the SoundManager. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeAll + */ + removeAll: function () { + + this.stopAll(); + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].destroy(); + } + } + + this._sounds.length = 0; + + }, + + /** + * Removes all Sounds from the SoundManager that have an asset key matching the given value. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeByKey + * @param {string} key - The key to match when removing sound objects. + * @return {number} The number of matching sound objects that were removed. + */ + removeByKey: function (key) { + + var i = this._sounds.length; + var removed = 0; + + while (i--) + { + if (this._sounds[i].key === key) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + removed++; + } + } + + return removed; + + }, + + /** + * Adds a new Sound into the SoundManager and starts it playing. + * + * @method Phaser.SoundManager#play + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @return {Phaser.Sound} The new sound instance. + */ + play: function (key, volume, loop) { + + if (this.noAudio) + { + return; + } + + var sound = this.add(key, volume, loop); + + sound.play(); + + return sound; + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + if (this.usingWebAudio) + { + this._muteVolume = this.masterGain.gain.value; + this.masterGain.gain.value = 0; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = true; + } + } + + this.onMute.dispatch(); + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = this._muteVolume; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = false; + } + } + + this.onUnMute.dispatch(); + + }, + + /** + * Stops all the sounds in the game, then destroys them and finally clears up any callbacks. + * + * @method Phaser.SoundManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.onSoundDecode.dispose(); + + if (this.context) + { + if (window.PhaserGlobal) + { + // Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing + window.PhaserGlobal.audioContext = this.context; + } + else + { + if (this.context.close) + { + this.context.close(); + } + } + } + + } + +}; + +Phaser.SoundManager.prototype.constructor = Phaser.SoundManager; + +/** +* @name Phaser.SoundManager#mute +* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || false; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* @name Phaser.SoundManager#volume +* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "volume", { + + get: function () { + + return this._volume; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this._volume !== value) + { + this._volume = value; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = value; + } + else + { + // Loop through the sound cache and change the volume of all html audio tags + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].updateGlobalVolume(value); + } + } + } + + this.onVolumeChange.dispatch(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* The ScaleManager object handles the the scaling, resizing, and alignment of the +* Game size and the game Display canvas. +* +* The Game size is the logical size of the game; the Display canvas has size as an HTML element. +* +* The calculations of these are heavily influenced by the bounding Parent size which is the computed +* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the +* canvas's Parent element play an important role_ in the operation of the ScaleManager. +* +* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size. +* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}). +* +* #### Parent and Display canvas containment guidelines: +* +* - Style the Parent element (of the game canvas) to control the Parent size and +* thus the Display canvas's size and layout. +* +* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior. +* +* - The Parent element should _not_ apply a padding as this is not accounted for. +* If a padding is required apply it to the Parent's parent or apply a margin to the Parent. +* If you need to add a border, margin or any other CSS around your game container, then use a parent element and +* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container. +* +* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as +* they may be updated by the ScaleManager. +* +* #### Example Uses +* +* - ##### Fixed game size; scale canvas proportionally to fill its container +* +* Use `scaleMode` SHOW_ALL. +* +* - ##### Fixed game size; stretch canvas to fill its container (uncommon) +* +* Use `scaleMode` EXACT_FIT. +* +* - ##### Fixed game size; scale canvas proportionally by some other criteria +* +* Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary. +* +* - ##### Fluid game/canvas size +* +* Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary. +* +* - ##### Preferred orientation +* +* Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals. +* +* @description +* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game} +* +* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. +* +* @class +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number|string} width - The width of the game. See above. +* @param {number|string} height - The height of the game. See above. +*/ +Phaser.ScaleManager = function (game, width, height) { + + /** + * A reference to the currently running game. + * @property {Phaser.Game} game + * @protected + * @readonly + */ + this.game = game; + + /** + * Provides access to some cross-device DOM functions. + * @property {Phaser.DOM} dom + * @protected + * @readonly + */ + this.dom = Phaser.DOM; + + /** + * _EXPERIMENTAL:_ A responsive grid on which you can align game objects. + * @property {Phaser.FlexGrid} grid + * @public + */ + this.grid = null; + + /** + * Target width (in pixels) of the Display canvas. + * @property {number} width + * @readonly + */ + this.width = 0; + + /** + * Target height (in pixels) of the Display canvas. + * @property {number} height + * @readonly + */ + this.height = 0; + + /** + * Minimum width the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minWidth + * @readonly + * @protected + */ + this.minWidth = null; + + /** + * Maximum width the canvas should be scaled to (in pixels). + * If null it will scale to whatever width the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxWidth + * @readonly + * @protected + */ + this.maxWidth = null; + + /** + * Minimum height the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minHeight + * @readonly + * @protected + */ + this.minHeight = null; + + /** + * Maximum height the canvas should be scaled to (in pixels). + * If null it will scale to whatever height the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxHeight + * @readonly + * @protected + */ + this.maxHeight = null; + + /** + * The offset coordinates of the Display canvas from the top-left of the browser window. + * The is used internally by Phaser.Pointer (for Input) and possibly other types. + * @property {Phaser.Point} offset + * @readonly + * @protected + */ + this.offset = new Phaser.Point(); + + /** + * If true, the game should only run in a landscape orientation. + * Change with {@link #forceOrientation}. + * @property {boolean} forceLandscape + * @readonly + * @default + * @protected + */ + this.forceLandscape = false; + + /** + * If true, the game should only run in a portrait + * Change with {@link #forceOrientation}. + * @property {boolean} forcePortrait + * @readonly + * @default + * @protected + */ + this.forcePortrait = false; + + /** + * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation. + * + * This value is not updated immediately. + * + * @property {boolean} incorrectOrientation + * @readonly + * @protected + */ + this.incorrectOrientation = false; + + /** + * See {@link #pageAlignHorizontally}. + * @property {boolean} _pageAlignHorizontally + * @private + */ + this._pageAlignHorizontally = false; + + /** + * See {@link #pageAlignVertically}. + * @property {boolean} _pageAlignVertically + * @private + */ + this._pageAlignVertically = false; + + /** + * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes. + * + * The signal is supplied with the following arguments: + * - `scale` - the ScaleManager object + * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}. + * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. + * + * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. + * Thus the following tests can be done: + * + * // The orientation itself changed: + * scale.screenOrientation !== prevOrientation + * // The orientation just became incorrect: + * scale.incorrectOrientation && !wasIncorrect + * + * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation + * correctness changes even if the orientation itself does not change. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onOrientationChange + * @public + */ + this.onOrientationChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} enterIncorrectOrientation + * @public + */ + this.enterIncorrectOrientation = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} leaveIncorrectOrientation + * @public + */ + this.leaveIncorrectOrientation = new Phaser.Signal(); + + /** + * This boolean provides you with a way to determine if the browser is in Full Screen + * mode (via the Full Screen API), and Phaser was the one responsible for activating it. + * + * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the + * one that made the browser go full-screen, so this flag lets you determine that. + * + * @property {boolean} hasPhaserSetFullScreen + * @default + */ + this.hasPhaserSetFullScreen = false; + + /** + * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. + * The target element must have the correct CSS styling and contain the Display canvas. + * + * The elements style will be modified (ie. the width and height might be set to 100%) + * but it will not be added to, removed from, or repositioned within the DOM. + * An attempt is made to restore relevant style changes when fullscreen mode is left. + * + * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. + * + * @property {?DOMElement} fullScreenTarget + * @default + */ + this.fullScreenTarget = null; + + /** + * The fullscreen target, as created by {@link #createFullScreenTarget}. + * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends. + * @property {?DOMElement} _createdFullScreenTarget + * @private + */ + this._createdFullScreenTarget = null; + + /** + * This signal is dispatched when fullscreen mode is ready to be initialized but + * before the fullscreen request. + * + * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. + * + * The `targetElement` is the {@link #fullScreenTarget} element, + * if such is assigned, or a new element created by {@link #createFullScreenTarget}. + * + * Custom CSS styling or resets can be applied to `targetElement` as required. + * + * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}: + * - After initialization the Display canvas is moved onto the `targetElement` for + * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. + * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. + * + * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}. + * + * @property {Phaser.Signal} onFullScreenInit + * @public + */ + this.onFullScreenInit = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine + * if currently running in Fullscreen mode. + * + * @property {Phaser.Signal} onFullScreenChange + * @public + */ + this.onFullScreenChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser fails to enter fullscreen mode; + * or if the device does not support fullscreen mode and `startFullScreen` is invoked. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). + * + * @property {Phaser.Signal} onFullScreenError + * @public + */ + this.onFullScreenError = new Phaser.Signal(); + + /** + * The _last known_ orientation of the screen, as defined in the Window Screen Web API. + * See {@link Phaser.DOM.getScreenOrientation} for possible values. + * + * @property {string} screenOrientation + * @readonly + * @public + */ + this.screenOrientation = this.dom.getScreenOrientation(); + + /** + * The _current_ scale factor based on the game dimensions vs. the scaled dimensions. + * @property {Phaser.Point} scaleFactor + * @readonly + */ + this.scaleFactor = new Phaser.Point(1, 1); + + /** + * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions. + * @property {Phaser.Point} scaleFactorInversed + * @readonly + * @protected + */ + this.scaleFactorInversed = new Phaser.Point(1, 1); + + /** + * The Display canvas is aligned by adjusting the margins; the last margins are stored here. + * + * @property {Bounds-like} margin + * @readonly + * @protected + */ + this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0}; + + /** + * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. + * @property {Phaser.Rectangle} bounds + * @readonly + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The aspect ratio of the scaled Display canvas. + * @property {number} aspectRatio + * @readonly + */ + this.aspectRatio = 0; + + /** + * The aspect ratio of the original game dimensions. + * @property {number} sourceAspectRatio + * @readonly + */ + this.sourceAspectRatio = 0; + + /** + * The native browser events from Fullscreen API changes. + * @property {any} event + * @readonly + * @private + */ + this.event = null; + + /** + * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container. + * + * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. + * - If 'visual', the edge will be constrained to the Window / displayed screen area + * - If 'layout', the edge will be constrained to the CSS Layout bounds + * - An invalid value is treated as 'visual' + * + * @member + * @property {string} bottom + * @property {string} right + * @default + */ + this.windowConstraints = { + right: 'layout', + bottom: '' + }; + + /** + * Various compatibility settings. + * A value of "(auto)" indicates the setting is configured based on device and runtime information. + * + * A {@link #refresh} may need to be performed after making changes. + * + * @protected + * + * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.) + * + * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}. + * + * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. + * + * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh. + * + * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates. + * The height set varies by device and may either be the height of the window or the viewport. + * + * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. + * + * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. + * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. + * Any other string value (including the empty string) prevents using click trampolines. + * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}. + */ + this.compatibility = { + supportsFullScreen: false, + orientationFallback: null, + noMargins: false, + scrollTo: null, + forceMinimumDocumentHeight: false, + canExpandParent: true, + clickTrampoline: '' + }; + + /** + * Scale mode to be used when not in fullscreen. + * @property {number} _scaleMode + * @private + */ + this._scaleMode = Phaser.ScaleManager.NO_SCALE; + + /* + * Scale mode to be used in fullscreen. + * @property {number} _fullScreenScaleMode + * @private + */ + this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE; + + /** + * True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * The {@link #parentNode} property is generally ignored while this is in effect. + * + * @property {boolean} parentIsWindow + */ + this.parentIsWindow = false; + + /** + * The _original_ DOM element for the parent of the Display canvas. + * This may be different in fullscreen - see {@link #createFullScreenTarget}. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * This should only be changed after moving the Game canvas to a different DOM parent. + * + * @property {?DOMElement} parentNode + */ + this.parentNode = null; + + /** + * The scale of the game in relation to its parent container. + * @property {Phaser.Point} parentScaleFactor + * @readonly + */ + this.parentScaleFactor = new Phaser.Point(1, 1); + + /** + * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). + * Update checks normally happen quicker in response to other events. + * + * @property {integer} trackParentInterval + * @default + * @protected + * @see {@link Phaser.ScaleManager#refresh refresh} + */ + this.trackParentInterval = 2000; + + /** + * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. + * When invoked this is done _after_ the Canvas size/position have been updated. + * + * The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.) + * + * This signal is _only_ called when a change occurs and a reflow may be required. + * For example, if the canvas does not change sizes because of CSS settings (such as min-width) + * then this signal will _not_ be triggered. + * + * Use this to handle responsive game layout options. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onSizeChange + */ + this.onSizeChange = new Phaser.Signal(); + + /** + * The callback that will be called each the parent container resizes. + * @property {function} onResize + * @private + */ + this.onResize = null; + + /** + * The context in which the {@link #onResize} callback will be called. + * @property {object} onResizeContext + * @private + */ + this.onResizeContext = null; + + /** + * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot. + * @private + */ + this._pendingScaleMode = null; + + /** + * Information saved when fullscreen mode is started. + * @property {?object} _fullScreenRestore + * @private + */ + this._fullScreenRestore = null; + + /** + * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}. + * @property {Phaser.Rectangle} _gameSize + * @private + */ + this._gameSize = new Phaser.Rectangle(); + + /** + * The user-supplied scale factor, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleFactor + * @private + */ + this._userScaleFactor = new Phaser.Point(1, 1); + + /** + * The user-supplied scale trim, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleTrim + * @private + */ + this._userScaleTrim = new Phaser.Point(0, 0); + + /** + * The last time the bounds were checked in `preUpdate`. + * @property {number} _lastUpdate + * @private + */ + this._lastUpdate = 0; + + /** + * Size checks updates are delayed according to the throttle. + * The throttle increases to `trackParentInterval` over time and is used to more + * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety. + * @property {integer} _updateThrottle + * @private + */ + this._updateThrottle = 0; + + /** + * The minimum throttle allowed until it has slowed down sufficiently. + * @property {integer} _updateThrottleReset + * @private + */ + this._updateThrottleReset = 100; + + /** + * The cached result of the parent (possibly window) bounds; used to invalidate sizing. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._parentBounds = new Phaser.Rectangle(); + + /** + * Temporary bounds used for internal work to cut down on new objects created. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._tempBounds = new Phaser.Rectangle(); + + /** + * The Canvas size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedCanvasSize + * @private + */ + this._lastReportedCanvasSize = new Phaser.Rectangle(); + + /** + * The Game size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedGameSize + * @private + */ + this._lastReportedGameSize = new Phaser.Rectangle(); + + /** + * @property {boolean} _booted - ScaleManager booted state. + * @private + */ + this._booted = false; + + if (game.config) + { + this.parseConfig(game.config); + } + + this.setupScale(width, height); + +}; + +/** +* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.EXACT_FIT = 0; + +/** +* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.NO_SCALE = 1; + +/** +* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.SHOW_ALL = 2; + +/** +* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.RESIZE = 3; + +/** +* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.USER_SCALE = 4; + +/** +* Names of the scale modes, indexed by value. +* +* @constant +* @type {string[]} +*/ +Phaser.ScaleManager.MODES = [ + 'EXACT_FIT', + 'NO_SCALE', + 'SHOW_ALL', + 'RESIZE', + 'USER_SCALE' +]; + +Phaser.ScaleManager.prototype = { + + /** + * Start the ScaleManager. + * + * @method Phaser.ScaleManager#boot + * @protected + */ + boot: function () { + + // Configure device-dependent compatibility + + var compat = this.compatibility; + + compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS; + + // We can't do anything about the status bars in iPads, web apps or desktops + if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop) + { + if (this.game.device.android && !this.game.device.chrome) + { + compat.scrollTo = new Phaser.Point(0, 1); + } + else + { + compat.scrollTo = new Phaser.Point(0, 0); + } + } + + if (this.game.device.desktop) + { + compat.orientationFallback = 'screen'; + compat.clickTrampoline = 'when-not-mouse'; + } + else + { + compat.orientationFallback = ''; + compat.clickTrampoline = ''; + } + + // Configure event listeners + + var _this = this; + + this._orientationChange = function(event) { + return _this.orientationChange(event); + }; + + this._windowResize = function(event) { + return _this.windowResize(event); + }; + + // This does not appear to be on the standards track + window.addEventListener('orientationchange', this._orientationChange, false); + window.addEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + this._fullScreenChange = function(event) { + return _this.fullScreenChange(event); + }; + + this._fullScreenError = function(event) { + return _this.fullScreenError(event); + }; + + document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.addEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.addEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.addEventListener('fullscreenchange', this._fullScreenChange, false); + + document.addEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.addEventListener('mozfullscreenerror', this._fullScreenError, false); + document.addEventListener('MSFullscreenError', this._fullScreenError, false); + document.addEventListener('fullscreenerror', this._fullScreenError, false); + } + + this.game.onResume.add(this._gameResumed, this); + + // Initialize core bounds + + this.dom.getOffset(this.game.canvas, this.offset); + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + this.setGameSize(this.game.width, this.game.height); + + // Don't use updateOrientationState so events are not fired + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + if (Phaser.FlexGrid) + { + this.grid = new Phaser.FlexGrid(this, this.width, this.height); + } + + this._booted = true; + + if (this._pendingScaleMode !== null) + { + this.scaleMode = this._pendingScaleMode; + this._pendingScaleMode = null; + } + + }, + + /** + * Load configuration settings. + * + * @method Phaser.ScaleManager#parseConfig + * @protected + * @param {object} config - The game configuration object. + */ + parseConfig: function (config) { + + if (config['scaleMode'] !== undefined) + { + if (this._booted) + { + this.scaleMode = config['scaleMode']; + } + else + { + this._pendingScaleMode = config['scaleMode']; + } + } + + if (config['fullScreenScaleMode'] !== undefined) + { + this.fullScreenScaleMode = config['fullScreenScaleMode']; + } + + if (config['fullScreenTarget']) + { + this.fullScreenTarget = config['fullScreenTarget']; + } + + this.pageAlignHorizontally = config.alignH || false; + this.pageAlignVertically = config.alignV || false; + + if (config.scaleH && config.scaleV) + { + this.setUserScale(config.scaleH, config.scaleV, config.trimH, config.trimV); + } + + }, + + /** + * Calculates and sets the game dimensions based on the given width and height. + * + * This should _not_ be called when in fullscreen mode. + * + * @method Phaser.ScaleManager#setupScale + * @protected + * @param {number|string} width - The width of the game. + * @param {number|string} height - The height of the game. + */ + setupScale: function (width, height) { + + var target; + var rect = new Phaser.Rectangle(); + + if (this.game.parent !== '') + { + if (typeof this.game.parent === 'string') + { + // hopefully an element ID + target = document.getElementById(this.game.parent); + } + else if (this.game.parent && this.game.parent.nodeType === 1) + { + // quick test for a HTMLelement + target = this.game.parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + // Use the full window + this.parentNode = null; + this.parentIsWindow = true; + + rect.width = this.dom.visualBounds.width; + rect.height = this.dom.visualBounds.height; + + this.offset.set(0, 0); + } + else + { + this.parentNode = target; + this.parentIsWindow = false; + + this.getParentBounds(this._parentBounds); + + rect.width = this._parentBounds.width; + rect.height = this._parentBounds.height; + + this.offset.set(this._parentBounds.x, this._parentBounds.y); + } + + var newWidth = 0; + var newHeight = 0; + + if (typeof width === 'number') + { + newWidth = width; + } + else + { + // Percentage based + this.parentScaleFactor.x = parseInt(width, 10) / 100; + newWidth = rect.width * this.parentScaleFactor.x; + } + + if (typeof height === 'number') + { + newHeight = height; + } + else + { + // Percentage based + this.parentScaleFactor.y = parseInt(height, 10) / 100; + newHeight = rect.height * this.parentScaleFactor.y; + } + + newWidth = Math.floor(newWidth); + newHeight = Math.floor(newHeight); + + this._gameSize.setTo(0, 0, newWidth, newHeight); + + this.updateDimensions(newWidth, newHeight, false); + + }, + + /** + * Invoked when the game is resumed. + * + * @method Phaser.ScaleManager#_gameResumed + * @private + */ + _gameResumed: function () { + + this.queueUpdate(true); + + }, + + /** + * Set the actual Game size. + * Use this instead of directly changing `game.width` or `game.height`. + * + * The actual physical display (Canvas element size) depends on various settings including + * - Scale mode + * - Scaling factor + * - Size of Canvas's parent element or CSS rules such as min-height/max-height; + * - The size of the Window + * + * @method Phaser.ScaleManager#setGameSize + * @public + * @param {integer} width - _Game width_, in pixels. + * @param {integer} height - _Game height_, in pixels. + */ + setGameSize: function (width, height) { + + this._gameSize.setTo(0, 0, width, height); + + if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE) + { + this.updateDimensions(width, height, true); + } + + this.queueUpdate(true); + + }, + + /** + * Set a User scaling factor used in the USER_SCALE scaling mode. + * + * The target canvas size is computed by: + * + * canvas.width = (game.width * hScale) - hTrim + * canvas.height = (game.height * vScale) - vTrim + * + * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly. + * + * @method Phaser.ScaleManager#setUserScale + * @param {number} hScale - Horizontal scaling factor. + * @param {numer} vScale - Vertical scaling factor. + * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling. + * @param {integer} [vTrim=0] - Vertical trim, applied after scaling. + * @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate + * @param {boolean} [force=true] - Force a resize during the next preUpdate + */ + setUserScale: function (hScale, vScale, hTrim, vTrim, queueUpdate, force) { + + this._userScaleFactor.setTo(hScale, vScale); + this._userScaleTrim.setTo(hTrim | 0, vTrim | 0); + + if (queueUpdate === undefined) { queueUpdate = true; } + if (force === undefined) { force = true; } + + if (queueUpdate) + { + this.queueUpdate(force); + } + + }, + + /** + * Sets the callback that will be invoked before sizing calculations. + * + * Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries: + * the browser window has been resized, the device has been rotated, or the parent container's size has changed. + * At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all + * after it makes its sizing calculations). You can read the size of the parent container from the + * `parentBounds` argument to the callback. + * + * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling. + * + * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager + * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. + * + * This callback + * - May be invoked even though the parent container or canvas sizes have not changed + * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated + * - Will be invoked from `preUpdate`, _even when_ the game is paused + * + * See {@link #onSizeChange} for a better way of reacting to layout updates. + * + * @method Phaser.ScaleManager#setResizeCallback + * @public + * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes. + * @param {object} context - The context in which the callback will be called. + */ + setResizeCallback: function (callback, context) { + + this.onResize = callback; + this.onResizeContext = context; + + }, + + /** + * Signals a resize - IF the canvas or Game size differs from the last signal. + * + * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager). + * + * It dispatches the {@link #onSizeChange} signal. + * + * @method Phaser.ScaleManager#signalSizeChange + * @private + */ + signalSizeChange: function () { + + if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) || + !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize)) + { + var width = this.width; + var height = this.height; + + this._lastReportedCanvasSize.setTo(0, 0, width, height); + this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height); + + if (this.grid) + { + this.grid.onResize(width, height); + } + + this.onSizeChange.dispatch(this, width, height); + + // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode. + if (this.currentScaleMode === Phaser.ScaleManager.RESIZE) + { + this.game.state.resize(width, height); + this.game.load.resize(width, height); + } + } + + }, + + /** + * Set the min and max dimensions for the Display canvas. + * + * _Note:_ The min/max dimensions are only applied in some cases + * - When the device is not in an incorrect orientation; or + * - The scale mode is EXACT_FIT when not in fullscreen + * + * @method Phaser.ScaleManager#setMinMax + * @public + * @param {number} minWidth - The minimum width the game is allowed to scale down to. + * @param {number} minHeight - The minimum height the game is allowed to scale down to. + * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified. + * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified. + * @todo These values are only sometimes honored. + */ + setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) { + + this.minWidth = minWidth; + this.minHeight = minHeight; + + if (typeof maxWidth !== 'undefined') + { + this.maxWidth = maxWidth; + } + + if (typeof maxHeight !== 'undefined') + { + this.maxHeight = maxHeight; + } + + }, + + /** + * The ScaleManager.preUpdate is called automatically by the core Game loop. + * + * @method Phaser.ScaleManager#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.game.time.time < (this._lastUpdate + this._updateThrottle)) + { + return; + } + + var prevThrottle = this._updateThrottle; + this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100; + + this.dom.getOffset(this.game.canvas, this.offset); + + var prevWidth = this._parentBounds.width; + var prevHeight = this._parentBounds.height; + var bounds = this.getParentBounds(this._parentBounds); + + var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight; + + // Always invalidate on a newly detected orientation change + var orientationChanged = this.updateOrientationState(); + + if (boundsChanged || orientationChanged) + { + if (this.onResize) + { + this.onResize.call(this.onResizeContext, this, bounds); + } + + this.updateLayout(); + + this.signalSizeChange(); + } + + // Next throttle, eg. 25, 50, 100, 200.. + var throttle = this._updateThrottle * 2; + + // Don't let an update be too eager about resetting the throttle. + if (this._updateThrottle < prevThrottle) + { + throttle = Math.min(prevThrottle, this._updateThrottleReset); + } + + this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval); + this._lastUpdate = this.game.time.time; + + }, + + /** + * Update method while paused. + * + * @method Phaser.ScaleManager#pauseUpdate + * @private + */ + pauseUpdate: function () { + + this.preUpdate(); + + // Updates at slowest. + this._updateThrottle = this.trackParentInterval; + + }, + + /** + * Update the dimensions taking the parent scaling factor into account. + * + * @method Phaser.ScaleManager#updateDimensions + * @private + * @param {number} width - The new width of the parent container. + * @param {number} height - The new height of the parent container. + * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars. + */ + updateDimensions: function (width, height, resize) { + + this.width = width * this.parentScaleFactor.x; + this.height = height * this.parentScaleFactor.y; + + this.game.width = this.width; + this.game.height = this.height; + + this.sourceAspectRatio = this.width / this.height; + this.updateScalingAndBounds(); + + if (resize) + { + // Resize the renderer (which in turn resizes the Display canvas!) + this.game.renderer.resize(this.width, this.height); + + // The Camera can never be smaller than the Game size + this.game.camera.setSize(this.width, this.height); + + // This should only happen if the world is smaller than the new canvas size + this.game.world.resize(this.width, this.height); + } + + }, + + /** + * Update relevant scaling values based on the ScaleManager dimension and game dimensions, + * which should already be set. This does not change {@link #sourceAspectRatio}. + * + * @method Phaser.ScaleManager#updateScalingAndBounds + * @private + */ + updateScalingAndBounds: function () { + + this.scaleFactor.x = this.game.width / this.width; + this.scaleFactor.y = this.game.height / this.height; + + this.scaleFactorInversed.x = this.width / this.game.width; + this.scaleFactorInversed.y = this.height / this.game.height; + + this.aspectRatio = this.width / this.height; + + // This can be invoked in boot pre-canvas + if (this.game.canvas) + { + this.dom.getOffset(this.game.canvas, this.offset); + } + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + // Can be invoked in boot pre-input + if (this.game.input && this.game.input.scale) + { + this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y); + } + + }, + + /** + * Force the game to run in only one orientation. + * + * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. + * + * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor + * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the + * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` + * + * @method Phaser.ScaleManager#forceOrientation + * @public + * @param {boolean} forceLandscape - true if the game should run in landscape mode only. + * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. + */ + forceOrientation: function (forceLandscape, forcePortrait) { + + if (forcePortrait === undefined) { forcePortrait = false; } + + if (forceLandscape === true && forcePortrait === true) + { + console.warn('Phaser.ScaleManager: forceLandscape and forcePortrait cannot both be true.'); + return; + } + + this.forceLandscape = forceLandscape; + this.forcePortrait = forcePortrait; + + this.queueUpdate(true); + + }, + + /** + * Classify the orientation, per `getScreenOrientation`. + * + * @method Phaser.ScaleManager#classifyOrientation + * @private + * @param {string} orientation - The orientation string, e.g. 'portrait-primary'. + * @return {?string} The classified orientation: 'portrait', 'landscape`, or null. + */ + classifyOrientation: function (orientation) { + + if (orientation === 'portrait-primary' || orientation === 'portrait-secondary') + { + return 'portrait'; + } + else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary') + { + return 'landscape'; + } + else + { + return null; + } + + }, + + /** + * Updates the current orientation and dispatches orientation change events. + * + * @method Phaser.ScaleManager#updateOrientationState + * @private + * @return {boolean} True if the orientation state changed which means a forced update is likely required. + */ + updateOrientationState: function () { + + var previousOrientation = this.screenOrientation; + var previouslyIncorrect = this.incorrectOrientation; + + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) || + (this.forcePortrait && !this.isPortrait); + + var changed = previousOrientation !== this.screenOrientation; + var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation; + + if (correctnessChanged) + { + if (this.incorrectOrientation) + { + this.enterIncorrectOrientation.dispatch(); + } + else + { + this.leaveIncorrectOrientation.dispatch(); + } + } + + if (changed || correctnessChanged) + { + this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect); + } + + return changed || correctnessChanged; + + }, + + /** + * window.orientationchange event handler. + * + * @method Phaser.ScaleManager#orientationChange + * @private + * @param {Event} event - The orientationchange event data. + */ + orientationChange: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * window.resize event handler. + * + * @method Phaser.ScaleManager#windowResize + * @private + * @param {Event} event - The resize event data. + */ + windowResize: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * Scroll to the top - in some environments. See `compatibility.scrollTo`. + * + * @method Phaser.ScaleManager#scrollTop + * @private + */ + scrollTop: function () { + + var scrollTo = this.compatibility.scrollTo; + + if (scrollTo) + { + window.scrollTo(scrollTo.x, scrollTo.y); + } + + }, + + /** + * The "refresh" methods informs the ScaleManager that a layout refresh is required. + * + * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) + * when the browser is resized, the orientation changes, or when there is a detected change + * of the Parent size. Refreshing is also done automatically when public properties, + * such as {@link #scaleMode}, are updated or state-changing methods are invoked. + * + * The "refresh" method _may_ need to be used in a few (rare) situtations when + * + * - a device change event is not correctly detected; or + * - the Parent size changes (and an immediate reflow is desired); or + * - the ScaleManager state is updated by non-standard means; or + * - certain {@link #compatibility} properties are manually changed. + * + * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. + * + * @method Phaser.ScaleManager#refresh + * @public + */ + refresh: function () { + + this.scrollTop(); + this.queueUpdate(true); + + }, + + /** + * Updates the game / canvas position and size. + * + * @method Phaser.ScaleManager#updateLayout + * @private + */ + updateLayout: function () { + + var scaleMode = this.currentScaleMode; + + if (scaleMode === Phaser.ScaleManager.RESIZE) + { + this.reflowGame(); + return; + } + + this.scrollTop(); + + if (this.compatibility.forceMinimumDocumentHeight) + { + // (This came from older code, by why is it here?) + // Set minimum height of content to new window height + document.documentElement.style.minHeight = window.innerHeight + 'px'; + } + + if (this.incorrectOrientation) + { + this.setMaximum(); + } + else + { + if (scaleMode === Phaser.ScaleManager.EXACT_FIT) + { + this.setExactFit(); + } + else if (scaleMode === Phaser.ScaleManager.SHOW_ALL) + { + if (!this.isFullScreen && this.boundingParent && + this.compatibility.canExpandParent) + { + // Try to expand parent out, but choosing maximizing dimensions. + // Then select minimize dimensions which should then honor parent + // maximum bound applications. + this.setShowAll(true); + this.resetCanvas(); + this.setShowAll(); + } + else + { + this.setShowAll(); + } + } + else if (scaleMode === Phaser.ScaleManager.NO_SCALE) + { + this.width = this.game.width; + this.height = this.game.height; + } + else if (scaleMode === Phaser.ScaleManager.USER_SCALE) + { + this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x; + this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y; + } + } + + if (!this.compatibility.canExpandParent && + (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE)) + { + var bounds = this.getParentBounds(this._tempBounds); + this.width = Math.min(this.width, bounds.width); + this.height = Math.min(this.height, bounds.height); + } + + // Always truncate / force to integer + this.width = this.width | 0; + this.height = this.height | 0; + + this.reflowCanvas(); + + }, + + /** + * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. + * + * If in fullscreen mode or without parent (see {@link #parentIsWindow}), + * this will be the bounds of the visual viewport itself. + * + * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside + * the viewport then this function may return a smaller than expected size. + * + * Values are rounded to the nearest pixel. + * + * @method Phaser.ScaleManager#getParentBounds + * @protected + * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed. + * @return {Phaser.Rectangle} The established parent bounds. + */ + getParentBounds: function (target) { + + var bounds = target || new Phaser.Rectangle(); + var parentNode = this.boundingParent; + var visualBounds = this.dom.visualBounds; + var layoutBounds = this.dom.layoutBounds; + + if (!parentNode) + { + bounds.setTo(0, 0, visualBounds.width, visualBounds.height); + } + else + { + // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect + var clientRect = parentNode.getBoundingClientRect(); + var parentRect = (parentNode.offsetParent) ? parentNode.offsetParent.getBoundingClientRect() : parentNode.getBoundingClientRect(); + + bounds.setTo(clientRect.left - parentRect.left, clientRect.top - parentRect.top, clientRect.width, clientRect.height); + + var wc = this.windowConstraints; + + if (wc.right) + { + var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds; + bounds.right = Math.min(bounds.right, windowBounds.width); + } + + if (wc.bottom) + { + var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds; + bounds.bottom = Math.min(bounds.bottom, windowBounds.height); + } + } + + bounds.setTo( + Math.round(bounds.x), Math.round(bounds.y), + Math.round(bounds.width), Math.round(bounds.height)); + + return bounds; + + }, + + + /** + * Shorthand for setting {@link #pageAlignHorizontally} and {@link #pageAlignVertically}. + * + * @method Phaser.ScaleManager#align + * @param {boolean} [horizontal] - Value for {@link #pageAlignHorizontally}. Pass `null` to leave unchanged. + * @param {boolean} [vertical] - Value for {@link #pageAlignVertically}. Omit or pass `null` to leave unchanged. + */ + align: function (horizontal, vertical) { + + if (horizontal != null) + { + this.pageAlignHorizontally = horizontal; + } + + if (vertical != null) + { + this.pageAlignVertically = vertical; + } + + }, + + /** + * Update the canvas position/margins - for alignment within the parent container. + * + * The canvas margins _must_ be reset/cleared prior to invoking this. + * + * @method Phaser.ScaleManager#alignCanvas + * @private + * @param {boolean} horizontal - Align horizontally? + * @param {boolean} vertical - Align vertically? + */ + alignCanvas: function (horizontal, vertical) { + + var parentBounds = this.getParentBounds(this._tempBounds); + var canvas = this.game.canvas; + var margin = this.margin; + + if (horizontal) + { + margin.left = margin.right = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.width < parentBounds.width && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.left - parentBounds.x; + var targetEdge = (parentBounds.width / 2) - (this.width / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + + margin.left = Math.round(offset); + } + + canvas.style.marginLeft = margin.left + 'px'; + + if (margin.left !== 0) + { + margin.right = -(parentBounds.width - canvasBounds.width - margin.left); + canvas.style.marginRight = margin.right + 'px'; + } + } + + if (vertical) + { + margin.top = margin.bottom = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.height < parentBounds.height && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.top - parentBounds.y; + var targetEdge = (parentBounds.height / 2) - (this.height / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + margin.top = Math.round(offset); + } + + canvas.style.marginTop = margin.top + 'px'; + + if (margin.top !== 0) + { + margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top); + canvas.style.marginBottom = margin.bottom + 'px'; + } + } + + // Silly backwards compatibility.. + margin.x = margin.left; + margin.y = margin.top; + + }, + + /** + * Updates the Game state / size. + * + * The canvas margins may always be adjusted, even if alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowGame + * @private + */ + reflowGame: function () { + + this.resetCanvas('', ''); + + var bounds = this.getParentBounds(this._tempBounds); + this.updateDimensions(bounds.width, bounds.height, true); + + }, + + /** + * Updates the Display canvas size. + * + * The canvas margins may always be adjusted, even alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowCanvas + * @private + */ + reflowCanvas: function () { + + if (!this.incorrectOrientation) + { + this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width); + this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height); + } + + this.resetCanvas(); + + if (!this.compatibility.noMargins) + { + if (this.isFullScreen && this._createdFullScreenTarget) + { + this.alignCanvas(true, true); + } + else + { + this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically); + } + } + + this.updateScalingAndBounds(); + + }, + + /** + * "Reset" the Display canvas and set the specified width/height. + * + * @method Phaser.ScaleManager#resetCanvas + * @private + * @param {string} [cssWidth=(current width)] - The css width to set. + * @param {string} [cssHeight=(current height)] - The css height to set. + */ + resetCanvas: function (cssWidth, cssHeight) { + + if (cssWidth === undefined) { cssWidth = this.width + 'px'; } + if (cssHeight === undefined) { cssHeight = this.height + 'px'; } + + var canvas = this.game.canvas; + + if (!this.compatibility.noMargins) + { + canvas.style.marginLeft = ''; + canvas.style.marginTop = ''; + canvas.style.marginRight = ''; + canvas.style.marginBottom = ''; + } + + canvas.style.width = cssWidth; + canvas.style.height = cssHeight; + + }, + + /** + * Queues/marks a size/bounds check as needing to occur (from `preUpdate`). + * + * @method Phaser.ScaleManager#queueUpdate + * @private + * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty. + */ + queueUpdate: function (force) { + + if (force) + { + this._parentBounds.width = 0; + this._parentBounds.height = 0; + } + + this._updateThrottle = this._updateThrottleReset; + + }, + + /** + * Reset internal data/state. + * + * @method Phaser.ScaleManager#reset + * @private + */ + reset: function (clearWorld) { + + if (clearWorld && this.grid) + { + this.grid.reset(); + } + + }, + + /** + * Updates the width/height to that of the window. + * + * @method Phaser.ScaleManager#setMaximum + * @private + */ + setMaximum: function () { + + this.width = this.dom.visualBounds.width; + this.height = this.dom.visualBounds.height; + + }, + + /** + * Updates the width/height such that the game is scaled proportionally. + * + * @method Phaser.ScaleManager#setShowAll + * @private + * @param {boolean} expanding - If true then the maximizing dimension is chosen. + */ + setShowAll: function (expanding) { + + var bounds = this.getParentBounds(this._tempBounds); + var width = bounds.width; + var height = bounds.height; + + var multiplier; + + if (expanding) + { + multiplier = Math.max((height / this.game.height), (width / this.game.width)); + } + else + { + multiplier = Math.min((height / this.game.height), (width / this.game.width)); + } + + this.width = Math.round(this.game.width * multiplier); + this.height = Math.round(this.game.height * multiplier); + + }, + + /** + * Updates the width/height such that the game is stretched to the available size. + * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen. + * + * @method Phaser.ScaleManager#setExactFit + * @private + */ + setExactFit: function () { + + var bounds = this.getParentBounds(this._tempBounds); + + this.width = bounds.width; + this.height = bounds.height; + + if (this.isFullScreen) + { + // Max/min not honored fullscreen + return; + } + + if (this.maxWidth) + { + this.width = Math.min(this.width, this.maxWidth); + } + + if (this.maxHeight) + { + this.height = Math.min(this.height, this.maxHeight); + } + + }, + + /** + * Creates a fullscreen target. This is called automatically as as needed when entering + * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}. + * + * Use {@link #onFullScreenInit} to customize the created object. + * + * @method Phaser.ScaleManager#createFullScreenTarget + * @protected + */ + createFullScreenTarget: function () { + + var fsTarget = document.createElement('div'); + + fsTarget.style.margin = '0'; + fsTarget.style.padding = '0'; + fsTarget.style.background = '#000'; + + return fsTarget; + + }, + + /** + * Display the game in the browser's fullscreen mode. + * + * This _must_ be called from a user-input Pointer or Mouse event (and possibly a {@link https://www.chromestatus.com/feature/6131337345892352 "user gesture"}), e.g., + * + * - {@link Phaser.Events#onInputUp} + * - {@link Phaser.Input#onUp} or {@link Phaser.Input#onTap} + * - `click`, `mousedown`, `mouseup`, `pointerup`, or `touchend` + * + * Games within an iframe will also be blocked from fullscreen unless the iframe has the `allowfullscreen` attribute. + * + * The {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} must be {@link http://caniuse.com/#search=fullscreen supported by the browser} for this to work - it is not the same as setting + * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current + * device is reported to support fullscreen mode. + * + * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. + * + * Safari blocks access to keyboard events in fullscreen mode (as a security measure). + * + * @method Phaser.ScaleManager#startFullScreen + * @public + * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. + * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed. + * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) + */ + startFullScreen: function (antialias, allowTrampoline) { + + if (this.isFullScreen) + { + return false; + } + + if (!this.compatibility.supportsFullScreen) + { + // Error is called in timeout to emulate the real fullscreenerror event better + var _this = this; + + setTimeout(function () { + _this.fullScreenError(); + }, 10); + + return; + } + + if (this.compatibility.clickTrampoline === 'when-not-mouse') + { + var input = this.game.input; + + if (input.activePointer && + input.activePointer !== input.mousePointer && + (allowTrampoline || allowTrampoline !== false)) + { + input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]); + return; + } + } + + if (antialias !== undefined && this.game.renderType === Phaser.CANVAS) + { + this.game.stage.smoothed = antialias; + } + + var fsTarget = this.fullScreenTarget; + + if (!fsTarget) + { + this.cleanupCreatedTarget(); + + this._createdFullScreenTarget = this.createFullScreenTarget(); + fsTarget = this._createdFullScreenTarget; + } + + var initData = { + targetElement: fsTarget + }; + + this.hasPhaserSetFullScreen = true; + + this.onFullScreenInit.dispatch(this, initData); + + if (this._createdFullScreenTarget) + { + // Move the Display canvas inside of the target and add the target to the DOM + // (The target has to be added for the Fullscreen API to work.) + var canvas = this.game.canvas; + var parent = canvas.parentNode; + parent.insertBefore(fsTarget, canvas); + fsTarget.appendChild(canvas); + } + + if (this.game.device.fullscreenKeyboard) + { + fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT); + } + else + { + fsTarget[this.game.device.requestFullscreen](); + } + + return true; + + }, + + /** + * Stops / exits fullscreen mode, if active. + * + * @method Phaser.ScaleManager#stopFullScreen + * @public + * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. + */ + stopFullScreen: function () { + + if (!this.isFullScreen || !this.compatibility.supportsFullScreen) + { + return false; + } + + this.hasPhaserSetFullScreen = false; + + document[this.game.device.cancelFullscreen](); + + return true; + + }, + + /** + * Cleans up the previous fullscreen target, if such was automatically created. + * This ensures the canvas is restored to its former parent, assuming the target didn't move. + * + * @method Phaser.ScaleManager#cleanupCreatedTarget + * @private + */ + cleanupCreatedTarget: function () { + + var fsTarget = this._createdFullScreenTarget; + + if (fsTarget && fsTarget.parentNode) + { + // Make sure to cleanup synthetic target for sure; + // swap the canvas back to the parent. + var parent = fsTarget.parentNode; + parent.insertBefore(this.game.canvas, fsTarget); + parent.removeChild(fsTarget); + } + + this._createdFullScreenTarget = null; + + }, + + /** + * Used to prepare/restore extra fullscreen mode settings. + * (This does move any elements within the DOM tree.) + * + * @method Phaser.ScaleManager#prepScreenMode + * @private + * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_. + */ + prepScreenMode: function (enteringFullscreen) { + + var createdTarget = !!this._createdFullScreenTarget; + var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget; + + if (enteringFullscreen) + { + if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT) + { + // Resize target, as long as it's not the canvas + if (fsTarget !== this.game.canvas) + { + this._fullScreenRestore = { + targetWidth: fsTarget.style.width, + targetHeight: fsTarget.style.height + }; + + fsTarget.style.width = '100%'; + fsTarget.style.height = '100%'; + } + } + } + else + { + // Have restore information + if (this._fullScreenRestore) + { + fsTarget.style.width = this._fullScreenRestore.targetWidth; + fsTarget.style.height = this._fullScreenRestore.targetHeight; + + this._fullScreenRestore = null; + } + + // Always reset to game size + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.resetCanvas(); + } + + }, + + /** + * Called automatically when the browser enters of leaves fullscreen mode. + * + * @method Phaser.ScaleManager#fullScreenChange + * @private + * @param {Event} [event=undefined] - The fullscreenchange event + */ + fullScreenChange: function (event) { + + this.event = event; + + if (this.isFullScreen) + { + this.prepScreenMode(true); + + this.updateLayout(); + this.queueUpdate(true); + } + else + { + this.prepScreenMode(false); + + this.cleanupCreatedTarget(); + + this.updateLayout(); + this.queueUpdate(true); + } + + this.onFullScreenChange.dispatch(this, this.width, this.height); + + }, + + /** + * Called automatically when the browser fullscreen request fails; + * or called when a fullscreen request is made on a device for which it is not supported. + * + * @method Phaser.ScaleManager#fullScreenError + * @private + * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API. + */ + fullScreenError: function (event) { + + this.event = event; + + this.cleanupCreatedTarget(); + + console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API'); + + this.onFullScreenError.dispatch(this); + + }, + + /** + * Takes a Sprite or Image object and scales it to fit the given dimensions. + * Scaling happens proportionally without distortion to the sprites texture. + * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the + * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either + * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. + * + * @method Phaser.ScaleManager#scaleSprite + * @protected + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale. + * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. + * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. + * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. + * @return {Phaser.Sprite|Phaser.Image} The scaled sprite. + */ + scaleSprite: function (sprite, width, height, letterBox) { + + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + if (letterBox === undefined) { letterBox = false; } + + if (!sprite || !sprite['scale']) + { + return sprite; + } + + sprite.scale.x = 1; + sprite.scale.y = 1; + + if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0)) + { + return sprite; + } + + var scaleX1 = width; + var scaleY1 = (sprite.height * width) / sprite.width; + + var scaleX2 = (sprite.width * height) / sprite.height; + var scaleY2 = height; + + var scaleOnWidth = (scaleX2 > width); + + if (scaleOnWidth) + { + scaleOnWidth = letterBox; + } + else + { + scaleOnWidth = !letterBox; + } + + if (scaleOnWidth) + { + sprite.width = Math.floor(scaleX1); + sprite.height = Math.floor(scaleY1); + } + else + { + sprite.width = Math.floor(scaleX2); + sprite.height = Math.floor(scaleY2); + } + + // Enable at some point? + // sprite.x = Math.floor((width - sprite.width) / 2); + // sprite.y = Math.floor((height - sprite.height) / 2); + + return sprite; + + }, + + /** + * Destroys the ScaleManager and removes any event listeners. + * This should probably only be called when the game is destroyed. + * + * @method Phaser.ScaleManager#destroy + * @protected + */ + destroy: function () { + + this.game.onResume.remove(this._gameResumed, this); + + window.removeEventListener('orientationchange', this._orientationChange, false); + window.removeEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.removeEventListener('fullscreenchange', this._fullScreenChange, false); + + document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.removeEventListener('mozfullscreenerror', this._fullScreenError, false); + document.removeEventListener('MSFullscreenError', this._fullScreenError, false); + document.removeEventListener('fullscreenerror', this._fullScreenError, false); + } + + } + +}; + +Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager; + +/** +* The DOM element that is considered the Parent bounding element, if any. +* +* This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified. +* It will also be null if there is no game canvas or if the game canvas has no parent. +* +* @name Phaser.ScaleManager#boundingParent +* @property {?DOMElement} boundingParent +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", { + + get: function () { + + if (this.parentIsWindow || + (this.isFullScreen && this.hasPhaserSetFullScreen && !this._createdFullScreenTarget)) + { + return null; + } + + var parentNode = this.game.canvas && this.game.canvas.parentNode; + + return parentNode || null; + + } + +}); + +/** +* The scaling method used by the ScaleManager when not in fullscreen. +* +*
+*
{@link Phaser.ScaleManager.NO_SCALE}
+*
+* The Game display area will not be scaled - even if it is too large for the canvas/screen. +* This mode _ignores_ any applied scaling factor and displays the canvas at the Game size. +*
+*
{@link Phaser.ScaleManager.EXACT_FIT}
+*
+* The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen. +* Proportions are not maintained. +*
+*
{@link Phaser.ScaleManager.SHOW_ALL}
+*
+* Show the entire game display area while _maintaining_ the original aspect ratio. +*
+*
{@link Phaser.ScaleManager.RESIZE}
+*
+* The dimensions of the game display area are changed to match the size of the parent container. +* That is, this mode _changes the Game size_ to match the display size. +*

+* Any manually set Game size (see {@link #setGameSize}) is ignored while in effect. +*

+*
{@link Phaser.ScaleManager.USER_SCALE}
+*
+* The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}. +*

+* This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback} +* for flexible custom-sizing needs. +*

+*
+* +* @name Phaser.ScaleManager#scaleMode +* @property {integer} scaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", { + + get: function () { + + return this._scaleMode; + + }, + + set: function (value) { + + if (value !== this._scaleMode) + { + if (!this.isFullScreen) + { + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.queueUpdate(true); + } + + this._scaleMode = value; + } + + return this._scaleMode; + + } + +}); + +/** +* The scaling method used by the ScaleManager when in fullscreen. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#fullScreenScaleMode +* @property {integer} fullScreenScaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", { + + get: function () { + + return this._fullScreenScaleMode; + + }, + + set: function (value) { + + if (value !== this._fullScreenScaleMode) + { + // If in fullscreen then need a wee bit more work + if (this.isFullScreen) + { + this.prepScreenMode(false); + this._fullScreenScaleMode = value; + this.prepScreenMode(true); + + this.queueUpdate(true); + } + else + { + this._fullScreenScaleMode = value; + } + } + + return this._fullScreenScaleMode; + + } + +}); + +/** +* Returns the current scale mode - for normal or fullscreen operation. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#currentScaleMode +* @property {number} currentScaleMode +* @protected +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", { + + get: function () { + + return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode; + + } + +}); + +/** +* When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align horizontally across the page the Display canvas should be added directly to page; +* or the parent container should itself be horizontally aligned. +* +* Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignHorizontally +* @property {boolean} pageAlignHorizontally +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", { + + get: function () { + + return this._pageAlignHorizontally; + + }, + + set: function (value) { + + if (value !== this._pageAlignHorizontally) + { + this._pageAlignHorizontally = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain +* a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically +* _within_ the remaining available height dictated by the Parent element. +* +* One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. +* If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). +* +* _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height. +* To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true. +* +* Vertical alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignVertically +* @property {boolean} pageAlignVertically +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", { + + get: function () { + + return this._pageAlignVertically; + + }, + + set: function (value) { + + if (value !== this._pageAlignVertically) + { + this._pageAlignVertically = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* Returns true if the browser is in fullscreen mode, otherwise false. +* @name Phaser.ScaleManager#isFullScreen +* @property {boolean} isFullScreen +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", { + + get: function () { + return !!(document['fullscreenElement'] || + document['webkitFullscreenElement'] || + document['mozFullScreenElement'] || + document['msFullscreenElement']); + } + +}); + +/** +* Returns true if the screen orientation is in portrait mode. +* +* @name Phaser.ScaleManager#isPortrait +* @property {boolean} isPortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'portrait'; + } + +}); + +/** +* Returns true if the screen orientation is in landscape mode. +* +* @name Phaser.ScaleManager#isLandscape +* @property {boolean} isLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'landscape'; + } + +}); + +/** +* Returns true if the game dimensions are portrait (height > width). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGamePortrait +* @property {boolean} isGamePortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", { + + get: function () { + return (this.height > this.width); + } + +}); + +/** +* Returns true if the game dimensions are landscape (width > height). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGameLandscape +* @property {boolean} isGameLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", { + + get: function () { + return (this.width > this.height); + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of methods for displaying debug information about game objects. +* +* If your game is running in Canvas mode, then you should invoke all of the Debug methods from +* your games `render` function. This is because they are drawn directly onto the game canvas +* itself, so if you call any debug methods outside of `render` they are likely to be overwritten +* by the game itself. +* +* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture +* to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug +* in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! +* +* @class Phaser.Utils.Debug +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Utils.Debug = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Image} sprite - If debugging in WebGL mode, this is the Image displaying the debug {@link #bmd BitmapData}. + */ + this.sprite = null; + + /** + * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.context = null; + + /** + * @property {string} font - The font that the debug information is rendered in. + * @default + */ + this.font = '14px Courier'; + + /** + * @property {number} columnWidth - The spacing between columns. + * @default + */ + this.columnWidth = 100; + + /** + * @property {number} lineHeight - The line height between the debug text. + * @default + */ + this.lineHeight = 16; + + /** + * @property {number} lineWidth - The width of the stroke on lines and shapes. A positive number. + * @default + */ + this.lineWidth = 1; + + /** + * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. + * @default + */ + this.renderShadow = true; + + /** + * @property {string} currentColor - The color last set by {@link #start} or {@link #text}. + * @default + * @protected + */ + this.currentColor = null; + + /** + * @property {number} currentX - The current X position the debug information will be rendered at. + * @default + */ + this.currentX = 0; + + /** + * @property {number} currentY - The current Y position the debug information will be rendered at. + * @default + */ + this.currentY = 0; + + /** + * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it. + * @default + */ + this.currentAlpha = 1; + + /** + * @property {boolean} dirty - Does the canvas need re-rendering? + * @default + */ + this.dirty = false; + + /** + * @property {boolean} isDisabled - If `enableDebug: false` is passed to {@link Phaser.Game} or if Phaser is built without the Debug class, this will be true. + * @default + * @readonly + */ + this.isDisabled = false; + + /** + * @property {Phaser.Line} _line - A reusable rendering line. + * @private + */ + this._line = null; + + /** + * @property {Phaser.Rectangle} _rect - A reusable rendering rectangle. + * @private + */ + this._rect = null; + +}; + +Phaser.Utils.Debug.prototype = { + + /** + * Internal method that boots the debug displayer. + * + * @method Phaser.Utils.Debug#boot + * @protected + */ + boot: function () { + + if (this.game.renderType === Phaser.CANVAS) + { + this.context = this.game.context; + } + else + { + this.bmd = new Phaser.BitmapData(this.game, '__DEBUG', this.game.width, this.game.height, true); + this.sprite = this.game.make.image(0, 0, this.bmd); + this.game.stage.addChild(this.sprite); + + this.game.scale.onSizeChange.add(this.resize, this); + + this.canvas = Phaser.CanvasPool.create(this, this.game.width, this.game.height); + this.context = this.canvas.getContext('2d'); + } + + this._line = new Phaser.Line(); + this._rect = new Phaser.Rectangle(); + + }, + + /** + * Internal method that resizes the BitmapData and Canvas. + * Called by ScaleManager.onSizeChange only in WebGL mode. + * + * @method Phaser.Utils.Debug#resize + * @protected + */ + resize: function () { + + this.bmd.resize(this.game.width, this.game.height); + + this.canvas.width = this.game.width; + this.canvas.height = this.game.height; + + }, + + /** + * Internal method that clears the canvas (if a Sprite) ready for a new debug session. + * + * @method Phaser.Utils.Debug#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.dirty && this.sprite) + { + this.bmd.clear(); + this.bmd.draw(this.canvas, 0, 0); + + this.context.clearRect(0, 0, this.game.width, this.game.height); + this.dirty = false; + } + + }, + + /** + * Clears the Debug canvas. + * + * @method Phaser.Utils.Debug#reset + */ + reset: function () { + + if (this.context) + { + this.context.clearRect(0, 0, this.game.width, this.game.height); + } + + if (this.sprite) + { + this.bmd.clear(); + } + + }, + + /** + * Internal method that resets and starts the debug output values. + * + * @method Phaser.Utils.Debug#start + * @protected + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + * @param {number} [columnWidth=0] - The spacing between columns. + */ + start: function (x, y, color, columnWidth) { + + if (typeof x !== 'number') { x = 0; } + if (typeof y !== 'number') { y = 0; } + color = color || 'rgb(255,255,255)'; + if (columnWidth === undefined) { columnWidth = 0; } + + this.currentX = x; + this.currentY = y; + this.currentColor = color; + this.columnWidth = columnWidth; + + this.dirty = true; + + this.context.save(); + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.strokeStyle = color; + this.context.fillStyle = color; + this.context.font = this.font; + this.context.globalAlpha = this.currentAlpha; + + }, + + /** + * Internal method that stops the debug output. + * + * @method Phaser.Utils.Debug#stop + * @protected + */ + stop: function () { + + this.context.restore(); + + }, + + /** + * Internal method that outputs a single line of text split over as many columns as needed, one per parameter. + * + * @method Phaser.Utils.Debug#line + * @protected + */ + line: function () { + + var x = this.currentX; + + for (var i = 0; i < arguments.length; i++) + { + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(arguments[i], x + 1, this.currentY + 1); + this.context.fillStyle = this.currentColor; + } + + this.context.fillText(arguments[i], x, this.currentY); + + x += this.columnWidth; + } + + this.currentY += this.lineHeight; + + }, + + /** + * Render Sound Manager information, including volume, mute, audio mode, and locked status. + * + * @method Phaser.Utils.Debug#sound + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + sound: function (x, y, color) { + + var sound = this.game.sound; + + this.start(x, y, color); + + if (sound.noAudio) + { + this.line('Audio is disabled'); + } + else + { + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Mute on pause: ' + sound.muteOnPause); + this.line('Using: ' + (sound.usingWebAudio ? ('Web Audio - ' + sound.context.state) : 'Audio Tag')); + this.line('Touch locked: ' + sound.touchLocked); + } + + this.stop(); + + }, + + /** + * Render Sound information, including decoded state, duration, volume and more. + * + * @method Phaser.Utils.Debug#soundInfo + * @param {Phaser.Sound} sound - The sound object to debug. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + soundInfo: function (sound, x, y, color) { + + this.start(x, y, color); + this.line('Sound: ' + sound.key + ' Touch locked: ' + sound.game.sound.touchLocked); + this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback); + this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding); + this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying + ' Loop: ' + sound.loop); + this.line('Time: ' + sound.currentTime); + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Using: ' + (sound.usingWebAudio ? 'Web Audio' : 'Audio Tag')); + + if (sound.currentMarker !== '') + { + this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')'); + this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop); + this.line('Position: ' + sound.position); + } + + this.stop(); + + }, + + /** + * Marks the follow {@link #target} and {@link #deadzone}. + * + * @method Phaser.Utils.Debug#camera + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {string} [color] - Color of the debug shapes to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the shapes filled (default, true) or stroked (false). + */ + camera: function (camera, color, filled) { + + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + if (deadzone) + { + this._rect.setTo(view.x + deadzone.x, view.y + deadzone.y, deadzone.width, deadzone.height); + this.rectangle(this._rect, color, filled); + } + + if (target) + { + this._line.setTo(view.centerX, view.centerY, target.x, target.y); + this.geom(this._line, color, filled); + this.geom(target, color, false, 3); + } + + }, + + /** + * Render camera information including dimensions and location. + * + * @method Phaser.Utils.Debug#cameraInfo + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + cameraInfo: function (camera, x, y, color) { + + var bounds = camera.bounds; + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + this.start(x, y, color); + this.line('Camera (' + camera.width + ' x ' + camera.height + ')'); + this.line('x: ' + camera.x + ' y: ' + camera.y); + this.line('Bounds: ' + (bounds ? ('x: ' + bounds.x + ' y: ' + bounds.y + ' w: ' + bounds.width + ' h: ' + bounds.height) : 'none')); + this.line('View: x: ' + view.x + ' y: ' + view.y + ' w: ' + view.width + ' h: ' + view.height); + this.line('Deadzone: ' + (deadzone ? ('x: ' + deadzone.x + ' y: ' + deadzone.y + ' w: ' + deadzone.width + ' h: ' + deadzone.height) : deadzone)); + this.line('Total in view: ' + camera.totalInView); + this.line('At limit: x: ' + camera.atLimit.x + ' y: ' + camera.atLimit.y); + this.line('Target: ' + (target ? (target.name || target) : 'none')); + this.stop(); + + }, + + /** + * Render Timer information. + * + * @method Phaser.Utils.Debug#timer + * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + timer: function (timer, x, y, color) { + + this.start(x, y, color); + this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')'); + this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration); + this.line('Paused: ' + timer.paused + ' Length: ' + timer.length); + this.stop(); + + }, + + /** + * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text. + * + * @method Phaser.Utils.Debug#pointer + * @param {Phaser.Pointer} pointer - The Pointer you wish to display. + * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. + * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down. + * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false). + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + pointer: function (pointer, hideIfUp, downColor, upColor, color) { + + if (pointer == null) + { + return; + } + + if (hideIfUp === undefined) { hideIfUp = false; } + downColor = downColor || 'rgba(0,255,0,0.5)'; + upColor = upColor || 'rgba(255,0,0,0.5)'; + + if (hideIfUp === true && pointer.isUp === true) + { + return; + } + + this.start(pointer.x, pointer.y - 100, color); + this.context.beginPath(); + this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2); + + if (pointer.active) + { + this.context.fillStyle = downColor; + } + else + { + this.context.fillStyle = upColor; + } + + this.context.fill(); + this.context.closePath(); + + // Render the points + this.context.beginPath(); + this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y); + this.context.lineTo(pointer.position.x, pointer.position.y); + this.context.lineWidth = 2; + this.context.stroke(); + this.context.closePath(); + + // Render the text + this.line('ID: ' + pointer.id + " Active: " + pointer.active); + this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY); + this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y + " In: " + pointer.withinGame); + this.line('Duration: ' + pointer.duration + " ms"); + this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp); + this.stop(); + + }, + + /** + * Render Sprite Input Debug information. + * + * @method Phaser.Utils.Debug#spriteInputInfo + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInputInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')'); + this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1)); + this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0)); + this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0)); + this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut()); + this.stop(); + + }, + + /** + * Renders Phaser.Key object information. + * + * @method Phaser.Utils.Debug#key + * @param {Phaser.Key} key - The Key to render the information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + key: function (key, x, y, color) { + + this.start(x, y, color, 150); + + this.line('Key:', key.keyCode, 'isDown:', key.isDown); + this.line('justDown:', key.justDown, 'justUp:', key.justUp); + this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0)); + + this.stop(); + + }, + + /** + * Render debug information about the Input object. + * + * @method Phaser.Utils.Debug#inputInfo + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + inputInfo: function (x, y, color) { + + this.start(x, y, color); + this.line('Input'); + this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y); + this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY); + this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1)); + this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY); + this.stop(); + + }, + + /** + * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! + * + * @method Phaser.Utils.Debug#spriteBounds + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + spriteBounds: function (sprite, color, filled) { + + var bounds = sprite.getBounds(); + + bounds.x += this.game.camera.x; + bounds.y += this.game.camera.y; + + this.rectangle(bounds, color, filled); + + }, + + /** + * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it + * + * @method Phaser.Utils.Debug#ropeSegments + * @param {Phaser.Rope} rope - The rope to display the segments of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + ropeSegments: function (rope, color, filled) { + + var segments = rope.segments; + + var self = this; + + segments.forEach(function(segment) { + self.rectangle(segment, color, filled); + }, this); + + }, + + /** + * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. + * + * @method Phaser.Utils.Debug#spriteInfo + * @param {Phaser.Sprite} sprite - The Sprite to display the information of. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + + this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y); + this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1)); + this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1)); + this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera); + this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1)); + + this.stop(); + + }, + + /** + * Renders the sprite coordinates in local, positional and world space. + * + * @method Phaser.Utils.Debug#spriteCoords + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteCoords: function (sprite, x, y, color) { + + this.start(x, y, color, 100); + + if (sprite.name) + { + this.line(sprite.name); + } + + this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2)); + this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2)); + this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2)); + + this.stop(); + + }, + + /** + * Renders Line information in the given color. + * + * @method Phaser.Utils.Debug#lineInfo + * @param {Phaser.Line} line - The Line to display the data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + lineInfo: function (line, x, y, color) { + + this.start(x, y, color, 80); + this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2)); + this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2)); + this.line('length:', line.length.toFixed(2), 'angle:', line.angle); + this.stop(); + + }, + + /** + * Renders a single pixel at the given size. + * + * @method Phaser.Utils.Debug#pixel + * @param {number} x - X position of the pixel to be rendered. + * @param {number} y - Y position of the pixel to be rendered. + * @param {string} [color] - Color of the pixel (format is css color string). + * @param {number} [size=2] - The 'size' to render the pixel at. + */ + pixel: function (x, y, color, size) { + + size = size || 2; + + this.start(); + this.context.fillStyle = color; + this.context.fillRect(x, y, size, size); + this.stop(); + + }, + + /** + * Renders a Phaser geometry object including Rectangle, Circle, Ellipse, Point or Line. + * + * @method Phaser.Utils.Debug#geom + * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Ellipse|Phaser.Point|Phaser.Line} object - The geometry object to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) + * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle,3 = Point, 4 = Line and 5 = Ellipse. + */ + geom: function (object, color, filled, forceType) { + + if (filled === undefined) { filled = true; } + if (forceType === undefined) { forceType = 0; } + + color = color || 'rgba(0,255,0,0.4)'; + + this.start(); + + this.context.fillStyle = color; + this.context.strokeStyle = color; + this.context.lineWidth = this.lineWidth; + + if (object instanceof Phaser.Rectangle || forceType === 1) + { + if (filled) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + } + else if (object instanceof Phaser.Circle || forceType === 2) + { + this.context.beginPath(); + this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + else if (object instanceof Phaser.Point || forceType === 3) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4); + } + else if (object instanceof Phaser.Line || forceType === 4) + { + this.context.beginPath(); + this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y); + this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y); + this.context.closePath(); + this.context.stroke(); + } + else if (object instanceof Phaser.Ellipse || forceType === 5) + { + this.context.beginPath(); + this.context.ellipse(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width/2, object.height/2, 0,2 * Math.PI,false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + + this.stop(); + + }, + + /** + * Renders a Rectangle. + * + * @method Phaser.Utils.Debug#rectangle + * @param {Phaser.Rectangle|object} object - The rectangle to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as filled (default, true) or a stroked (false) + */ + rectangle: function (object, color, filled) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0, 255, 0, 0.4)'; + + this.start(); + + if (filled) + { + this.context.fillStyle = color; + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.lineWidth = this.lineWidth; + this.context.strokeStyle = color; + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + + this.stop(); + + }, + + /** + * Render a string of text. + * + * @method Phaser.Utils.Debug#text + * @param {string} text - The line of text to draw. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {string} [font] - The font of text to draw. + */ + text: function (text, x, y, color, font) { + + color = color || 'rgb(255,255,255)'; + font = font || '16px Courier'; + + this.start(); + this.context.font = font; + + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(text, x + 1, y + 1); + } + + this.context.fillStyle = color; + this.context.fillText(text, x, y); + + this.stop(); + + }, + + /** + * Visually renders a QuadTree to the display. + * + * @method Phaser.Utils.Debug#quadTree + * @param {Phaser.QuadTree} quadtree - The quadtree to render. + * @param {string} color - The color of the lines in the quadtree. + */ + quadTree: function (quadtree, color) { + + color = color || 'rgba(255,0,0,0.3)'; + + this.start(); + + var bounds = quadtree.bounds; + + if (quadtree.nodes.length === 0) + { + this.context.strokeStyle = color; + this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height); + this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier'); + + this.context.strokeStyle = 'rgb(0,255,0)'; + + for (var i = 0; i < quadtree.objects.length; i++) + { + this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height); + } + } + else + { + for (var i = 0; i < quadtree.nodes.length; i++) + { + this.quadTree(quadtree.nodes[i]); + } + } + + this.stop(); + + }, + + /** + * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. + * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. + * To display a P2 Physics body you should enable debug mode on the body when creating it. + * + * @method Phaser.Utils.Debug#body + * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false) + */ + body: function (sprite, color, filled) { + + if (sprite.body) + { + this.start(); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled, this.lineWidth); + } + else if (sprite.body.type === Phaser.Physics.NINJA) + { + Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color); + } + + this.stop(); + } + + }, + + /** + * Render a Sprites Physic Body information. + * + * @method Phaser.Utils.Debug#bodyInfo + * @param {Phaser.Sprite} sprite - The sprite to be rendered. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + bodyInfo: function (sprite, x, y, color) { + + if (sprite.body) + { + this.start(x, y, color, 210); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + this.game.physics.box2d.renderBodyInfo(this, sprite.body); + } + + this.stop(); + } + + }, + + /** + * Renders 'debug draw' data for the Box2D world if it exists. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by + * the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dWorld + */ + box2dWorld: function () { + + this.start(); + + this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0); + this.game.physics.box2d.renderDebugDraw(this.context); + + this.stop(); + + }, + + /** + * Renders 'debug draw' data for the given Box2D body. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dBody + * @param {Phaser.Physics.Box2D.Body} body - The body to be rendered. + * @param {string} [color='rgb(0,255,0)'] - Color of the rendering (format is css color string). + */ + box2dBody: function (body, color) { + + this.start(); + Phaser.Physics.Box2D.renderBody(this.context, body, color); + this.stop(); + + }, + + /** + * Call this function from the Dev Tools console. + * + * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. + * + * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) + * + * @method Phaser.Utils.Debug#displayList + * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World. + */ + displayList: function (displayObject) { + + if (displayObject === undefined) { displayObject = this.game.world; } + + if (displayObject.hasOwnProperty('renderOrderID')) + { + console.log('[' + displayObject.renderOrderID + ']', displayObject); + } + else + { + console.log('[]', displayObject); + } + + if (displayObject.children && displayObject.children.length > 0) + { + for (var i = 0; i < displayObject.children.length; i++) + { + this.game.debug.displayList(displayObject.children[i]); + } + } + + }, + + /** + * Prints a description of the {@link Phaser.Game#renderer renderer} and render session. + * + * @method Phaser.Utils.Debug#renderer + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + renderer: function (x, y, color) { + + var r = this.game.renderer; + var s = r.renderSession; + + this.start(x, y, color); + + this.line((r.gl ? 'WebGL' : 'Canvas') + ' Renderer (' + r.width + ' x ' + r.height + ')'); + this.line('autoResize: ' + r.autoResize); + this.line('clearBeforeRender: ' + r.clearBeforeRender); + this.line('resolution: ' + r.resolution); + this.line('transparent: ' + r.transparent); + this.line('renderSession:'); + + if (r.gl) + { + this.line(' currentBatchedTextures: ('+ r.currentBatchedTextures.length + ')'); + + for (var i = 0; i < r.currentBatchedTextures.length; i++) + { + this.line(' ' + r.currentBatchedTextures[i]); + } + + this.line(' drawCount: ' + s.drawCount); + this.line(' maxTextures: ' + r.maxTextures); + this.line(' maxTextureSize: ' + r.maxTextureSize); + this.line(' maxTextureAvailableSpace: ' + s.maxTextureAvailableSpace); + this.line(' roundPixels: ' + s.roundPixels); + } + else + { + this.line(' roundPixels: ' + s.roundPixels); + this.line(' scaleMode: ' + (s.scaleMode === 0 ? 'LINEAR' : (s.scaleMode === 1 ? 'NEAREST' : s.scaleMode))); + } + + this.stop(); + + }, + + canvasPool: function (x, y, color, columnWidth) { + var pool = Phaser.CanvasPool; + + this.start(x, y, color, columnWidth || 100); + this.line('Canvas Pool'); + this.line('Used:', pool.getTotal()); + this.line('Free:', pool.getFree()); + this.line('Total:', pool.length); + this.stop(); + }, + + /** + * Render each physics {@link #body} in a group. + * + * @method Phaser.Utils.Debug#physicsGroup + * @param {Phaser.Group} group - A group containing physics-enabled sprites. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false). + * @param {boolean} [checkExists=false] Render only children with `exists=true`. + */ + physicsGroup: function (group, color, filled, checkExists) { + + group.forEach(this.body, this, checkExists, color, filled); + + }, + + /** + * Prints Phaser {@link Phaser.VERSION version}, {@link Phaser.Game.#renderType rendering mode}, and {@link Phaser.Device#webAudio device audio support}. + * + * @method Phaser.Utils.Debug#phaser + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + phaser: function (x, y, color) { + + this.text('Phaser v' + Phaser.VERSION + ' ' + + (this.game.renderType === Phaser.WEBGL ? 'WebGL' : 'Canvas') + ' ' + + (this.game.device.webAudio ? 'WebAudio' : 'HTML Audio'), + x, y, color, this.font); + + }, + + /** + * Prints game/canvas dimensions and {@link Phaser.ScaleManager game scale} settings. + * + * @method Phaser.Utils.Debug#scale + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + scale: function (x, y, color) { + + this.start(x, y, color); + + var scale = this.game.scale; + var factor = scale.scaleFactorInversed; + var bounds = scale._parentBounds; + var x = ' x '; + + this.line('Game: ' + this.game.width + x + this.game.height); + this.line('Canvas: ' + scale.width + x + scale.height + + ' (' + factor.x.toFixed(2) + x + factor.y.toFixed(2) + ')' + + ' [' + scale.aspectRatio.toFixed(2) + ']'); + this.line('Mode: ' + Phaser.ScaleManager.MODES[scale.currentScaleMode] + + (scale.currentScaleMode === Phaser.ScaleManager.USER_SCALE ? + (' (' + scale._userScaleFactor.x + x + scale._userScaleFactor.y + ')') : + '')); + this.line('Parent: ' + (scale.parentIsWindow ? 'window' : scale.parentNode) + + (bounds.empty ? '' : (' (' + bounds.width + x + bounds.height + ')'))); + this.line('Screen: ' + scale.classifyOrientation(scale.screenOrientation) + + (scale.incorrectOrientation ? ' (incorrect)' : '')); + + this.stop(); + + }, + + /** + * Prints the progress of a {@link Phaser.Loader}. + * + * Typically you would call this within a {@link State#loadRender} callback and pass `game.load` ({@link Phaser.Game#load}). + * + * You can enable {@link Phaser.Loader#resetLocked} to temporarily hold the loader in its 'complete' state. + * Just remember to disable it before restarting the loader (such as when changing states). + * + * @method Phaser.Utils.Debug#loader + * @param {Phaser.Loader} loader - The loader. Usually `game.load` ({@link Phaser.Game#load}). + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + loader: function (loader, x, y, color) { + + var pad = Phaser.Utils.pad; + + this.start(x, y, color); + + if (loader.hasLoaded) + { + this.line('Complete' + (loader.resetLocked ? ' [locked]' : '')); + } + else if (loader.isLoading) + { + this.line('Loading'); + } + else + { + this.line('Not started'); + } + + if (!loader.hasLoaded || loader.resetLocked) + { + this.line('Progress: ' + (pad(loader.progress, 3) + '%')); + this.line('Files: ' + loader._loadedFileCount + ' of ' + + loader._totalFileCount); + this.line('Packs: ' + loader._loadedPackCount + ' of ' + + loader._loadedPackCount); + } + + this.stop(); + + }, + + /** + * Destroy this object. + * + * @method Phaser.Utils.Debug#destroy + */ + destroy: function () { + + Phaser.CanvasPool.remove(this); + + } + +}; + +Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DOM utility class. +* +* Provides a useful Window and Element functions as well as cross-browser compatibility buffer. +* +* Some code originally derived from {@link https://github.com/ryanve/verge verge}. +* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. +* +* @class Phaser.DOM +* @static +*/ +Phaser.DOM = { + + /** + * Get the [absolute] position of the element relative to the Document. + * + * The value may vary slightly as the page is scrolled due to rounding errors. + * + * @method Phaser.DOM.getOffset + * @param {DOMElement} element - The targeted element that we want to retrieve the offset. + * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. + * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. + */ + getOffset: function (element, point) { + + point = point || new Phaser.Point(); + + var box = element.getBoundingClientRect(); + + var scrollTop = Phaser.DOM.scrollY; + var scrollLeft = Phaser.DOM.scrollX; + var clientTop = document.documentElement.clientTop; + var clientLeft = document.documentElement.clientLeft; + + point.x = box.left + scrollLeft - clientLeft; + point.y = box.top + scrollTop - clientTop; + + return point; + + }, + + /** + * A cross-browser element.getBoundingClientRect method with optional cushion. + * + * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. + * Its properties match the native rectangle. + * The cushion parameter is an amount of pixels (+/-) to cushion the element. + * It adjusts the measurements such that it is possible to detect when an element is near the viewport. + * + * @method Phaser.DOM.getBounds + * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for. + * @param {number} [cushion] - A +/- pixel adjustment amount. + * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. + */ + getBounds: function (element, cushion) { + + if (cushion === undefined) { cushion = 0; } + + element = element && !element.nodeType ? element[0] : element; + + if (!element || element.nodeType !== 1) + { + return false; + } + else + { + return this.calibrate(element.getBoundingClientRect(), cushion); + } + + }, + + /** + * Calibrates element coordinates for `inLayoutViewport` checks. + * + * @method Phaser.DOM.calibrate + * @private + * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}` + * @param {number} [cushion] - A value to adjust the coordinates by. + * @return {object} The calibrated element coordinates + */ + calibrate: function (coords, cushion) { + + cushion = +cushion || 0; + + var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 }; + + output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion); + output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion); + + return output; + + }, + + /** + * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) + * + * @method Phaser.DOM.getAspectRatio + * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. + * @return {number} The aspect ratio. + */ + getAspectRatio: function (object) { + + object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object; + + var w = object['width']; + var h = object['height']; + + if (typeof w === 'function') + { + w = w.call(object); + } + + if (typeof h === 'function') + { + h = h.call(object); + } + + return w / h; + + }, + + /** + * Tests if the given DOM element is within the Layout viewport. + * + * The optional cushion parameter allows you to specify a distance. + * + * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. + * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. + * + * @method Phaser.DOM.inLayoutViewport + * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas. + * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport. + * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it. + */ + inLayoutViewport: function (element, cushion) { + + var r = this.getBounds(element, cushion); + + return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height; + + }, + + /** + * Returns the device screen orientation. + * + * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. + * + * Order of resolving: + * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. + * - Screen size ratio check - If fallback is 'screen', suited for desktops. + * - Viewport size ratio check - If fallback is 'viewport', suited for mobile. + * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. + * - Media query + * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..) + * + * See + * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) + * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) + * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx + * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries + * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation + * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation + * + * @method Phaser.DOM.getScreenOrientation + * @protected + * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'. + */ + getScreenOrientation: function (primaryFallback) { + + var screen = window.screen; + var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; + + if (orientation && typeof orientation.type === 'string') + { + // Screen Orientation API specification + return orientation.type; + } + else if (typeof orientation === 'string') + { + // moz/ms-orientation are strings + return orientation; + } + + var PORTRAIT = 'portrait-primary'; + var LANDSCAPE = 'landscape-primary'; + + if (primaryFallback === 'screen') + { + return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'viewport') + { + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number') + { + // This may change by device based on "natural" orientation. + return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE; + } + else if (window.matchMedia) + { + if (window.matchMedia("(orientation: portrait)").matches) + { + return PORTRAIT; + } + else if (window.matchMedia("(orientation: landscape)").matches) + { + return LANDSCAPE; + } + } + + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + + }, + + /** + * The bounds of the Visual viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one} + * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers. + * + * Supported mobile: + * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} x - Scroll, left offset - eg. "scrollX" + * @property {number} y - Scroll, top offset - eg. "scrollY" + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + visualBounds: new Phaser.Rectangle(), + + /** + * The bounds of the Layout viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two}; + * but honoring the constraints as specified applicable viewport meta-tag. + * + * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see + * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}). + * + * This is _not_ representative of the Visual bounds: in particular the non-primary axis will + * generally be significantly larger than the screen height on mobile devices when running with a + * constrained viewport. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + layoutBounds: new Phaser.Rectangle(), + + /** + * The size of the document / Layout viewport. + * + * This incorrectly reports the dimensions in IE. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Document width in pixels. + * @property {number} height - Document height in pixels. + * @readonly + */ + documentBounds: new Phaser.Rectangle() + +}; + +Phaser.Device.whenReady(function (device) { + + // All target browsers should support page[XY]Offset. + var scrollX = window && ('pageXOffset' in window) ? + function () { return window.pageXOffset; } : + function () { return document.documentElement.scrollLeft; }; + + var scrollY = window && ('pageYOffset' in window) ? + function () { return window.pageYOffset; } : + function () { return document.documentElement.scrollTop; }; + + /** + * A cross-browser window.scrollX. + * + * @name Phaser.DOM.scrollX + * @property {number} scrollX + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollX", { + get: scrollX + }); + + /** + * A cross-browser window.scrollY. + * + * @name Phaser.DOM.scrollY + * @property {number} scrollY + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollY", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "x", { + get: scrollX + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "y", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "y", { + value: 0 + }); + + var treatAsDesktop = device.desktop && + (document.documentElement.clientWidth <= window.innerWidth) && + (document.documentElement.clientHeight <= window.innerHeight); + + // Desktop browsers align the layout viewport with the visual viewport. + // This differs from mobile browsers with their zooming design. + // Ref. http://quirksmode.org/mobile/tableViewport.html + if (treatAsDesktop) + { + + // PST- When scrollbars are not included this causes upstream issues in ScaleManager. + // So reverted to the old "include scrollbars." + var clientWidth = function () { + return Math.max(window.innerWidth, document.documentElement.clientWidth); + }; + var clientHeight = function () { + return Math.max(window.innerHeight, document.documentElement.clientHeight); + }; + + // Interested in area sans-scrollbar + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: clientHeight + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + get: clientHeight + }); + + } else { + + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: function () { + return window.innerWidth; + } + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: function () { + return window.innerHeight; + } + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + + get: function () { + var a = document.documentElement.clientWidth; + var b = window.innerWidth; + + return a < b ? b : a; // max + } + + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + + get: function () { + var a = document.documentElement.clientHeight; + var b = window.innerHeight; + + return a < b ? b : a; // max + } + + }); + + } + + // For Phaser.DOM.documentBounds + // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html + + Object.defineProperty(Phaser.DOM.documentBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "y", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "width", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth); + } + + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "height", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight); + } + + }); + +}, null, true); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* ArraySet is a Set data structure (items must be unique within the set) that also maintains order. +* This allows specific items to be easily added or removed from the Set. +* +* Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. +* +* This used primarily by the Input subsystem. +* +* @class Phaser.ArraySet +* @constructor +* @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet. +*/ +Phaser.ArraySet = function (list) { + + /** + * Current cursor position as established by `first` and `next`. + * @property {integer} position + * @default + */ + this.position = 0; + + /** + * The backing array. + * @property {any[]} list + */ + this.list = list || []; + +}; + +Phaser.ArraySet.prototype = { + + /** + * Adds a new element to the end of the list. + * If the item already exists in the list it is not moved. + * + * @method Phaser.ArraySet#add + * @param {any} item - The element to add to this list. + * @return {any} The item that was added. + */ + add: function (item) { + + if (!this.exists(item)) + { + this.list.push(item); + } + + return item; + + }, + + /** + * Gets the index of the item in the list, or -1 if it isn't in the list. + * + * @method Phaser.ArraySet#getIndex + * @param {any} item - The element to get the list index for. + * @return {integer} The index of the item or -1 if not found. + */ + getIndex: function (item) { + + return this.list.indexOf(item); + + }, + + /** + * Gets an item from the set based on the property strictly equaling the value given. + * Returns null if not found. + * + * @method Phaser.ArraySet#getByKey + * @param {string} property - The property to check against the value. + * @param {any} value - The value to check if the property strictly equals. + * @return {any} The item that was found, or null if nothing matched. + */ + getByKey: function (property, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i][property] === value) + { + return this.list[i]; + } + } + + return null; + + }, + + /** + * Checks for the item within this list. + * + * @method Phaser.ArraySet#exists + * @param {any} item - The element to get the list index for. + * @return {boolean} True if the item is found in the list, otherwise false. + */ + exists: function (item) { + + return (this.list.indexOf(item) > -1); + + }, + + /** + * Removes all the items. + * + * @method Phaser.ArraySet#reset + */ + reset: function () { + + this.list.length = 0; + + }, + + /** + * Removes the given element from this list if it exists. + * + * @method Phaser.ArraySet#remove + * @param {any} item - The item to be removed from the list. + * @return {any} item - The item that was removed. + */ + remove: function (item) { + + var idx = this.list.indexOf(item); + + if (idx > -1) + { + this.list.splice(idx, 1); + return item; + } + + }, + + /** + * Sets the property `key` to the given value on all members of this list. + * + * @method Phaser.ArraySet#setAll + * @param {any} key - The property of the item to set. + * @param {any} value - The value to set the property to. + */ + setAll: function (key, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + this.list[i][key] = value; + } + } + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * + * If the `key` property is present it must be a function. + * The function is invoked using the item as the context. + * + * @method Phaser.ArraySet#callAll + * @param {string} key - The name of the property with the function to call. + * @param {...*} parameter - Additional parameters that will be passed to the callback. + */ + callAll: function (key) { + + var args = Array.prototype.slice.call(arguments, 1); + + var i = this.list.length; + + while (i--) + { + if (this.list[i] && this.list[i][key]) + { + this.list[i][key].apply(this.list[i], args); + } + } + + }, + + /** + * Removes every member from this ArraySet and optionally destroys it. + * + * @method Phaser.ArraySet#removeAll + * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set. + */ + removeAll: function (destroy) { + + if (destroy === undefined) { destroy = false; } + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + var item = this.remove(this.list[i]); + + if (destroy) + { + item.destroy(); + } + } + } + + this.position = 0; + this.list = []; + + } + +}; + +/** +* Number of items in the ArraySet. Same as `list.length`. +* +* @name Phaser.ArraySet#total +* @property {integer} total +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "total", { + + get: function () { + return this.list.length; + } + +}); + +/** +* Returns the first item and resets the cursor to the start. +* +* @name Phaser.ArraySet#first +* @property {any} first +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "first", { + + get: function () { + + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + + } + +}); + +/** +* Returns the the next item (based on the cursor) and advances the cursor. +* +* @name Phaser.ArraySet#next +* @property {any} next +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "next", { + + get: function () { + + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + + } + +}); + +Phaser.ArraySet.prototype.constructor = Phaser.ArraySet; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Utility functions for dealing with Arrays. +* +* @class Phaser.ArrayUtils +* @static +*/ +Phaser.ArrayUtils = { + + /** + * Fetch a random entry from the given array. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.getRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was selected. + */ + getRandomItem: function (objects, startIndex, length) { + + if (objects === null) { return null; } + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + + return objects[randomIndex] === undefined ? null : objects[randomIndex]; + + }, + + /** + * Removes a random object from the given array and returns it. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.removeRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was removed. + */ + removeRandomItem: function (objects, startIndex, length) { + + if (objects == null) { // undefined or null + return null; + } + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + if (randomIndex < objects.length) + { + var removed = objects.splice(randomIndex, 1); + return removed[0] === undefined ? null : removed[0]; + } + else + { + return null; + } + + }, + + /** + * Remove one or more items at the given index and reorder the array. + * + * The new array length will be `array.length - count`. + * + * This is an alternative to `array.splice(startIndex, count)`. + * + * @see https://github.com/mreinstein/remove-array-items + * @see https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ + * + * @method Phaser.ArrayUtils.remove + * @param {any[]} array + * @param {integer} startIndex + * @param {integer} [count=1] + * @return {any[]} The modified array. + */ + remove: function (array, startIndex, count) + { + var length = array.length; + + if (startIndex >= length || count === 0) { return; } + + if (count == null) { count = 1; } + + var newLength = length - count; + + for (var i = startIndex; i < newLength; ++i) + { + array[i] = array[i + count]; + } + + array.length = newLength; + }, + + /** + * A standard Fisher-Yates Array shuffle implementation which modifies the array in place. + * + * @method Phaser.ArrayUtils.shuffle + * @param {any[]} array - The array to shuffle. + * @return {any[]} The original array, now shuffled. + */ + shuffle: function (array) { + + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; + + }, + + /** + * Transposes the elements of the given matrix (array of arrays). + * + * @method Phaser.ArrayUtils.transposeMatrix + * @param {Array} array - The matrix to transpose. + * @return {Array} A new transposed matrix + */ + transposeMatrix: function (array) { + + var sourceRowCount = array.length; + var sourceColCount = array[0].length; + + var result = new Array(sourceColCount); + + for (var i = 0; i < sourceColCount; i++) + { + result[i] = new Array(sourceRowCount); + + for (var j = sourceRowCount - 1; j > -1; j--) + { + result[i][j] = array[j][i]; + } + } + + return result; + + }, + + /** + * Rotates the given matrix (array of arrays). + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @method Phaser.ArrayUtils.rotateMatrix + * @param {Array} matrix - The array to rotate; this matrix _may_ be altered. + * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). + * @return {Array} The rotated matrix. The source matrix should be discarded for the returned matrix. + */ + rotateMatrix: function (matrix, direction) { + + if (typeof direction !== 'string') + { + direction = ((direction % 360) + 360) % 360; + } + + if (direction === 90 || direction === -270 || direction === 'rotateLeft') + { + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + matrix = matrix.reverse(); + } + else if (direction === -90 || direction === 270 || direction === 'rotateRight') + { + matrix = matrix.reverse(); + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + } + else if (Math.abs(direction) === 180 || direction === 'rotate180') + { + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + matrix = matrix.reverse(); + } + + return matrix; + + }, + + /** + * Snaps a value to the nearest value in a sorted numeric array. + * The result will always be in the range `[first_value, last_value]`. + * + * @method Phaser.ArrayUtils.findClosest + * @param {number} value - The search value + * @param {number[]} arr - The input array which _must_ be sorted. + * @return {number} The nearest value found. + */ + findClosest: function (value, arr) { + + if (!arr.length) + { + return NaN; + } + else if (arr.length === 1 || value < arr[0]) + { + return arr[0]; + } + + var i = 1; + while (arr[i] < value) { + i++; + } + + var low = arr[i - 1]; + var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; + + return ((high - value) <= (value - low)) ? high : low; + + }, + + /** + * Moves the element from the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ F, A, B, C, D, E ]` + * + * See also Phaser.ArrayUtils.rotateLeft. + * + * @method Phaser.ArrayUtils.rotateRight + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The shifted value. + */ + rotateRight: function (array) { + + var s = array.pop(); + array.unshift(s); + + return s; + + }, + + /** + * Moves the element from the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ B, C, D, E, F, A ]` + * + * See also Phaser.ArrayUtils.rotateRight + * + * @method Phaser.ArrayUtils.rotateLeft + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The rotated value. + */ + rotateLeft: function (array) { + + var s = array.shift(); + array.push(s); + + return s; + + }, + + /** + * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]` (or `[0, start]`, if `end` is omitted). + * This is equivalent to `numberArrayStep(start, 1 + end, 1)`. + * + * When exactly one argument is passed, it's used as `end` and 0 is used as `start`. The length of the result is (1 + end). + * + * ##### Examples + * + * ```javascript + * numberArray(3); // -> [0, 1, 2, 3] + * numberArray(0, 3); // -> [0, 1, 2, 3] + * numberArray(1, 3); // -> [1, 2, 3] + * ``` + * + * @method Phaser.ArrayUtils.numberArray + * @param {number} start - The minimum value the array starts with. + * @param {number} [end] - The maximum value the array contains. + * @return {number[]} The array of number values. + */ + numberArray: function (start, end) { + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + var result = []; + + for (var i = start; i <= end; i++) + { + result.push(i); + } + + return result; + + }, + + /** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @method Phaser.ArrayUtils.numberArrayStep + * @param {number} start - The start of the range. + * @param {number} [end] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * @returns {Array} Returns the new array of numbers. + * @example + * Phaser.ArrayUtils.numberArrayStep(4); + * // => [0, 1, 2, 3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * Phaser.ArrayUtils.numberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * Phaser.ArrayUtils.numberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * Phaser.ArrayUtils.numberArrayStep(0); + * // => [] + */ + numberArrayStep: function (start, end, step) { + + if (start === undefined || start === null) { start = 0; } + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + if (step === undefined) { step = 1; } + + var result = []; + var total = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0); + + for (var i = 0; i < total; i++) + { + result.push(start); + start += step; + } + + return result; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A basic Linked List data structure. +* +* This implementation _modifies_ the `prev` and `next` properties of each item added: +* - The `prev` and `next` properties must be writable and should not be used for any other purpose. +* - Items _cannot_ be added to multiple LinkedLists at the same time. +* - Only objects can be added. +* +* @class Phaser.LinkedList +* @constructor +*/ +Phaser.LinkedList = function () { + + /** + * Next element in the list. + * @property {object} next + * @default + */ + this.next = null; + + /** + * Previous element in the list. + * @property {object} prev + * @default + */ + this.prev = null; + + /** + * First element in the list. + * @property {object} first + * @default + */ + this.first = null; + + /** + * Last element in the list. + * @property {object} last + * @default + */ + this.last = null; + + /** + * Number of elements in the list. + * @property {integer} total + * @default + */ + this.total = 0; + +}; + +Phaser.LinkedList.prototype = { + + /** + * Adds a new element to this linked list. + * + * @method Phaser.LinkedList#add + * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. + * @return {object} The item that was added. + */ + add: function (item) { + + // If the list is empty + if (this.total === 0 && this.first === null && this.last === null) + { + this.first = item; + this.last = item; + this.next = item; + item.prev = this; + this.total++; + return item; + } + + // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list) + this.last.next = item; + + item.prev = this.last; + + this.last = item; + + this.total++; + + return item; + + }, + + /** + * Resets the first, last, next and previous node pointers in this list. + * + * @method Phaser.LinkedList#reset + */ + reset: function () { + + this.first = null; + this.last = null; + this.next = null; + this.prev = null; + this.total = 0; + + }, + + /** + * Removes the given element from this linked list if it exists. + * + * @method Phaser.LinkedList#remove + * @param {object} item - The item to be removed from the list. + */ + remove: function (item) { + + if (this.total === 1) + { + this.reset(); + item.next = item.prev = null; + return; + } + + if (item === this.first) + { + // It was 'first', make 'first' point to first.next + this.first = this.first.next; + } + else if (item === this.last) + { + // It was 'last', make 'last' point to last.prev + this.last = this.last.prev; + } + + if (item.prev) + { + // make item.prev.next point to childs.next instead of item + item.prev.next = item.next; + } + + if (item.next) + { + // make item.next.prev point to item.prev instead of item + item.next.prev = item.prev; + } + + item.next = item.prev = null; + + if (this.first === null ) + { + this.last = null; + } + + this.total--; + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * The function must exist on the member. + * + * @method Phaser.LinkedList#callAll + * @param {function} callback - The function to call. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content +* quickly and easily, without the need for any external files. You can create textures for sprites and in +* coming releases we'll add dynamic sound effect generation support as well (like sfxr). +* +* Access this via `Game.create` (`this.game.create` from within a State object). +* +* @class Phaser.Create +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Create = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.ctx = null; + + /** + * @property {array} palettes - A range of 16 color palettes for use with sprite generation. + */ + this.palettes = [ + { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' }, + { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' }, + { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' } + ]; + +}; + +/** +* A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_ARNE = 0; + +/** +* A 16 color JMP inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JMP = 1; + +/** +* A 16 color CGA inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_CGA = 2; + +/** +* A 16 color C64 inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_C64 = 3; + +/** +* A 16 color palette inspired by Japanese computers like the MSX. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JAPANESE_MACHINE = 4; + +Phaser.Create.prototype = { + + /** + * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite. + * + * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images + * rather than Phaser.Graphics objects, which are expensive to render and limited in scope. + * + * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts. + * + * For example: + * + * `var data = [ + * ' 333 ', + * ' 777 ', + * 'E333E', + * ' 333 ', + * ' 3 3 ' + * ];` + * + * `game.create.texture('bob', data);` + * + * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it + * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');` + * + * Use {@link Phaser.Loader#imageFromTexture} to preload an image of the same. + * + * @method Phaser.Create#texture + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {array} data - An array of pixel data. + * @param {integer} [pixelWidth=8] - The width of each pixel. + * @param {integer} [pixelHeight=8] - The height of each pixel. + * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + texture: function (key, data, pixelWidth, pixelHeight, palette, generateTexture, callback, callbackContext) { + + if (pixelWidth === undefined) { pixelWidth = 8; } + if (pixelHeight === undefined) { pixelHeight = pixelWidth; } + if (palette === undefined) { palette = 0; } + if (generateTexture === undefined) { generateTexture = true; } + + var w = data[0].length * pixelWidth; + var h = data.length * pixelHeight; + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(w, h); + this.bmd.clear(); + + // Draw it + for (var y = 0; y < data.length; y++) + { + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var d = row[x]; + + if (d !== '.' && d !== ' ') + { + this.ctx.fillStyle = this.palettes[palette][d]; + this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); + } + } + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Creates a grid texture based on the given dimensions. + * + * Use {@link Phaser.Loader#imageFromGrid} to preload an image of the same. + * + * @method Phaser.Create#grid + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {integer} width - The width of the grid in pixels. + * @param {integer} height - The height of the grid in pixels. + * @param {integer} cellWidth - The width of the grid cells in pixels. + * @param {integer} cellHeight - The height of the grid cells in pixels. + * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + grid: function (key, width, height, cellWidth, cellHeight, color, generateTexture, callback, callbackContext) { + + if (generateTexture === undefined) { generateTexture = true; } + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(width, height); + + this.ctx.fillStyle = color; + + for (var y = 0; y < height; y += cellHeight) + { + this.ctx.fillRect(0, y, width, 1); + } + + for (var x = 0; x < width; x += cellWidth) + { + this.ctx.fillRect(x, 0, 1, height); + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Copies the contents of {@link bmd Create's canvas} to the given BitmapData object, or a new BitmapData object. + * + * @param {Phaser.BitmapData} [dest] - The BitmapData receiving the copied image. + * @param {number} [x=0] - The x coordinate to translate to before drawing. + * @param {number} [y=0] - The y coordinate to translate to before drawing. + * @param {number} [width] - The new width of the Sprite being copied. + * @param {number} [height] - The new height of the Sprite being copied. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} - The `dest` argument (if passed), or a new BitmapData object + */ + copy: function (dest, x, y, width, height, blendMode, roundPx) { + + if (dest == null) { dest = this.game.make.bitmapData(); } + + dest.resize(this.bmd.width, this.bmd.height); + + return dest.draw(this.bmd, x, y, width, height, blendMode, roundPx); + + } + +}; + +Phaser.Create.prototype.constructor = Phaser.Create; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers +* to provide for game object positioning in a responsive manner. +* +* @class Phaser.FlexGrid +* @constructor +* @param {Phaser.ScaleManager} manager - The ScaleManager. +* @param {number} width - The width of the game. +* @param {number} height - The height of the game. +*/ +Phaser.FlexGrid = function (manager, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = manager.game; + + /** + * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager. + */ + this.manager = manager; + + // The perfect dimensions on which everything else is based + this.width = width; + this.height = height; + + this.boundsCustom = new Phaser.Rectangle(0, 0, width, height); + this.boundsFluid = new Phaser.Rectangle(0, 0, width, height); + this.boundsFull = new Phaser.Rectangle(0, 0, width, height); + this.boundsNone = new Phaser.Rectangle(0, 0, width, height); + + /** + * @property {Phaser.Point} position - + * @readonly + */ + this.positionCustom = new Phaser.Point(0, 0); + this.positionFluid = new Phaser.Point(0, 0); + this.positionFull = new Phaser.Point(0, 0); + this.positionNone = new Phaser.Point(0, 0); + + /** + * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. + * @readonly + */ + this.scaleCustom = new Phaser.Point(1, 1); + this.scaleFluid = new Phaser.Point(1, 1); + this.scaleFluidInversed = new Phaser.Point(1, 1); + this.scaleFull = new Phaser.Point(1, 1); + this.scaleNone = new Phaser.Point(1, 1); + + this.customWidth = 0; + this.customHeight = 0; + this.customOffsetX = 0; + this.customOffsetY = 0; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.multiplier = 0; + + this.layers = []; + +}; + +Phaser.FlexGrid.prototype = { + + /** + * Sets the core game size. This resets the w/h parameters and bounds. + * + * @method Phaser.FlexGrid#setSize + * @param {number} width - The new dimensions. + * @param {number} height - The new dimensions. + */ + setSize: function (width, height) { + + // These are locked and don't change until setSize is called again + this.width = width; + this.height = height; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.scaleNone = new Phaser.Point(1, 1); + + this.boundsNone.width = this.width; + this.boundsNone.height = this.height; + + this.refresh(); + + }, + + // Need ability to create your own layers with custom scaling, etc. + + /** + * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createCustomLayer + * @param {number} width - Width of this layer in pixels. + * @param {number} height - Height of this layer in pixels. + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createCustomLayer: function (width, height, children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + this.customWidth = width; + this.customHeight = height; + + this.boundsCustom.width = width; + this.boundsCustom.height = height; + + var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createFluidLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFluidLayer: function (children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios. + * + * @method Phaser.FlexGrid#createFullLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFullLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled. + * + * @method Phaser.FlexGrid#createFixedLayer + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFixedLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * Resets the layer children references + * + * @method Phaser.FlexGrid#reset + */ + reset: function () { + + var i = this.layers.length; + + while (i--) + { + if (!this.layers[i].persist) + { + // Remove references to this class + this.layers[i].position = null; + this.layers[i].scale = null; + this.layers.slice(i, 1); + } + } + + }, + + /** + * Called when the game container changes dimensions. + * + * @method Phaser.FlexGrid#onResize + * @param {number} width - The new width of the game container. + * @param {number} height - The new height of the game container. + */ + onResize: function (width, height) { + + this.ratioH = width / height; + this.ratioV = height / width; + + this.refresh(width, height); + + }, + + /** + * Updates all internal vars such as the bounds and scale values. + * + * @method Phaser.FlexGrid#refresh + */ + refresh: function () { + + this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width)); + + this.boundsFluid.width = Math.round(this.width * this.multiplier); + this.boundsFluid.height = Math.round(this.height * this.multiplier); + + this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height); + this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height); + + this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height); + + this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x); + this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y); + + this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + + this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y); + this.positionNone.set(this.boundsNone.x, this.boundsNone.y); + + }, + + /** + * Fits a sprites width to the bounds. + * + * @method Phaser.FlexGrid#fitSprite + * @param {Phaser.Sprite} sprite - The Sprite to fit. + */ + fitSprite: function (sprite) { + + this.manager.scaleSprite(sprite); + + sprite.x = this.manager.bounds.centerX; + sprite.y = this.manager.bounds.centerY; + + }, + + /** + * Call in the render function to output the bounds rects. + * + * @method Phaser.FlexGrid#debug + */ + debug: function () { + + // for (var i = 0; i < this.layers.length; i++) + // { + // this.layers[i].debug(); + // } + + // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16); + // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false); + + this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16); + this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false); + + // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16); + // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false); + + // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16); + // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false); + + } + +}; + +Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* A responsive grid layer. +* +* @class Phaser.FlexLayer +* @extends Phaser.Group +* @constructor +* @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer. +* @param {Phaser.Point} position - A reference to the Point object used for positioning. +* @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds. +* @param {Phaser.Point} scale - A reference to the Point object used for layer scaling. +*/ +Phaser.FlexLayer = function (manager, position, bounds, scale) { + + Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false); + + /** + * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager. + */ + this.manager = manager.manager; + + /** + * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer. + */ + this.grid = manager; + + /** + * Should the FlexLayer remain through a State swap? + * + * @type {boolean} + */ + this.persist = false; + + /** + * @property {Phaser.Point} position + */ + this.position = position; + + /** + * @property {Phaser.Rectangle} bounds + */ + this.bounds = bounds; + + /** + * @property {Phaser.Point} scale + */ + this.scale = scale; + + /** + * @property {Phaser.Point} topLeft + */ + this.topLeft = bounds.topLeft; + + /** + * @property {Phaser.Point} topMiddle + */ + this.topMiddle = new Phaser.Point(bounds.halfWidth, 0); + + /** + * @property {Phaser.Point} topRight + */ + this.topRight = bounds.topRight; + + /** + * @property {Phaser.Point} bottomLeft + */ + this.bottomLeft = bounds.bottomLeft; + + /** + * @property {Phaser.Point} bottomMiddle + */ + this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom); + + /** + * @property {Phaser.Point} bottomRight + */ + this.bottomRight = bounds.bottomRight; + +}; + +Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype); +Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer; + +/** + * Resize. + * + * @method Phaser.FlexLayer#resize + */ +Phaser.FlexLayer.prototype.resize = function () { +}; + +/** + * Debug. + * + * @method Phaser.FlexLayer#debug + */ +Phaser.FlexLayer.prototype.debug = function () { + + this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16); + this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false); + + this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9'); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. +* +* @class Phaser.Color +*/ +Phaser.Color = { + + /** + * Red (0xff0000) + * + * @type number + * @constant + * @default + */ + RED: 0xff0000, + + /** + * Orange (0xff9900) + * + * @type number + * @constant + * @default + */ + ORANGE: 0xff9900, + + /** + * Yellow (0xffff00) + * + * @type number + * @constant + * @default + */ + YELLOW: 0xffff00, + + /** + * Green (0x00ff00) + * + * @type number + * @constant + * @default + */ + GREEN: 0x00ff00, + + /** + * Aqua (0x00ffff) + * + * @type number + * @constant + * @default + */ + AQUA: 0x00ffff, + + /** + * Blue (0x0000ff) + * + * @type number + * @constant + * @default + */ + BLUE: 0x0000ff, + + /** + * Violet/purple (0xff00ff) + * + * @type number + * @constant + * @default + */ + VIOLET: 0xff00ff, + + /** + * White (0xffffff) + * + * @type number + * @constant + * @default + */ + WHITE: 0xffffff, + + /** + * Black (0x000000) + * + * @type number + * @constant + * @default + */ + BLACK: 0, + + /** + * Gray (0x666666) + * + * @type number + * @constant + * @default + */ + GRAY: 0x666666, + + /** + * Packs the r, g, b, a components into a single integer, for use with Int32Array. + * If device is little endian then ABGR order is used. Otherwise RGBA order is used. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.packPixel + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} The packed color as uint32 + */ + packPixel: function (r, g, b, a) { + + if (Phaser.Device.LITTLE_ENDIAN) + { + return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0; + } + else + { + return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0; + } + + }, + + /** + * Unpacks the r, g, b, a components into the specified color object, or a new + * object, for use with Int32Array. If little endian, then ABGR order is used when + * unpacking, otherwise, RGBA order is used. The resulting color object has the + * `r, g, b, a` properties which are unrelated to endianness. + * + * Note that the integer is assumed to be packed in the correct endianness. On little-endian + * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a + * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.unpackPixel + * @static + * @param {number} rgba - The integer, packed in endian order by packPixel. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + unpackPixel: function (rgba, out, hsl, hsv) { + + if (out === undefined || out === null) { out = Phaser.Color.createColor(); } + if (hsl === undefined || hsl === null) { hsl = false; } + if (hsv === undefined || hsv === null) { hsv = false; } + + if (Phaser.Device.LITTLE_ENDIAN) + { + out.a = ((rgba & 0xff000000) >>> 24); + out.b = ((rgba & 0x00ff0000) >>> 16); + out.g = ((rgba & 0x0000ff00) >>> 8); + out.r = ((rgba & 0x000000ff)); + } + else + { + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + } + + 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; + + }, + + /** + * A utility to convert an integer in 0xRRGGBBAA format to a color object. + * This does not rely on endianness. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.fromRGBA + * @static + * @param {number} rgba - An RGBA hex + * @param {object} [out] - The object to use, optional. + * @return {object} A color object. + */ + fromRGBA: function (rgba, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + + out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')'; + + return out; + + }, + + /** + * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.toRGBA + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toRGBA: function (r, g, b, a) { + + return (r << 24) | (g << 16) | (b << 8) | a; + + }, + + /** + * Converts RGBA components to a 32 bit integer in AABBGGRR format. + * + * @method Phaser.Color.toABGR + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toABGR: function (r, g, b, a) { + + return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; + + }, + + /** + * Converts a hex color value to an [R, G, B] array. + * + * @static + * @method Phaser.Color.hexToRGBArray + * @param {number} color - The color to convert to an RGB array. In the format 0xRRGGBB. + * @return {array} An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + */ + hexToRGBArray: function (color) { + + return [ + (color >> 16 & 0xFF) / 255, + (color >> 8 & 0xFF) / 255, + (color & 0xFF) / 255 + ]; + + }, + + /** + * Converts an RGB color array, in the format: [R, G, B], to a hex color value. + * + * @static + * @method Phaser.Color.RGBArrayToHex + * @param {array} rgb - An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + * @return {number} The color value, in the format 0xRRGGBB. + */ + RGBArrayToHex: function (rgb) { + + return ((rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255); + + }, + + /** + * Converts an RGB color value to HSL (hue, saturation and lightness). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSL + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. + */ + 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); + + // achromatic by default + out.h = 0; + out.s = 0; + out.l = (max + min) / 2; + + if (max !== min) + { + var d = max - min; + + out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min); + + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSL (hue, saturation and lightness) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSLtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} l - The lightness, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSLtoRGB: function (h, s, l, out) { + + if (!out) + { + out = Phaser.Color.createColor(l, l, l); + } + else + { + // achromatic by default + out.r = l; + out.g = l; + out.b = l; + } + + if (s !== 0) + { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3); + out.g = Phaser.Color.hueToColor(p, q, h); + out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3); + } + + // out.r = (out.r * 255 | 0); + // out.g = (out.g * 255 | 0); + // out.b = (out.b * 255 | 0); + + out.r = Math.floor((out.r * 255 | 0)); + out.g = Math.floor((out.g * 255 | 0)); + out.b = Math.floor((out.b * 255 | 0)); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts an RGB color value to HSV (hue, saturation and value). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSV + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and value set in the h, s and v properties. + */ + RGBtoHSV: function (r, g, b, out) { + + if (!out) + { + out = Phaser.Color.createColor(r, g, b, 255); + } + + r /= 255; + g /= 255; + b /= 255; + + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var d = max - min; + + // achromatic by default + out.h = 0; + out.s = max === 0 ? 0 : d / max; + out.v = max; + + if (max !== min) + { + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSVtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} v - The value, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSVtoRGB: function (h, s, v, out) { + + if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); } + + var r, g, b; + var i = Math.floor(h * 6); + var f = h * 6 - i; + var p = v * (1 - s); + var q = v * (1 - f * s); + var t = v * (1 - (1 - f) * s); + + switch (i % 6) + { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } + + out.r = Math.floor(r * 255); + out.g = Math.floor(g * 255); + out.b = Math.floor(b * 255); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.hueToColor + * @static + * @param {number} p + * @param {number} q + * @param {number} t + * @return {number} The color component value. + */ + hueToColor: function (p, q, t) { + + if (t < 0) + { + t += 1; + } + + if (t > 1) + { + t -= 1; + } + + if (t < 1 / 6) + { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) + { + return q; + } + + if (t < 2 / 3) + { + return p + (q - p) * (2 / 3 - t) * 6; + } + + return p; + + }, + + /** + * A utility function to create a lightweight 'color' object with the default components. + * Any components that are not specified will default to zero. + * + * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.createColor + * @static + * @param {number} [r=0] - The red color component, in the range 0 - 255. + * @param {number} [g=0] - The green color component, in the range 0 - 255. + * @param {number} [b=0] - The blue color component, in the range 0 - 255. + * @param {number} [a=1] - The alpha color component, in the range 0 - 1. + * @param {number} [h=0] - The hue, in the range 0 - 1. + * @param {number} [s=0] - The saturation, in the range 0 - 1. + * @param {number} [l=0] - The lightness, in the range 0 - 1. + * @param {number} [v=0] - The value, in the range 0 - 1. + * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. + */ + 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, color32: 0, rgba: '' }; + + return Phaser.Color.updateColor(out); + + }, + + /** + * Takes a color object and updates the rgba, color and color32 properties. + * + * @method Phaser.Color.updateColor + * @static + * @param {object} out - The color object to update. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + updateColor: function (out) { + + out.rgba = 'rgba(' + out.r.toFixed() + ',' + out.g.toFixed() + ',' + out.b.toFixed() + ',' + out.a.toString() + ')'; + out.color = Phaser.Color.getColor(out.r, out.g, out.b); + out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b); + + return out; + + }, + + /** + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor32 + * @static + * @param {number} a - The alpha color component, in the range 0 - 255. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + getColor32: function (a, r, g, b) { + + return a << 24 | r << 16 | g << 8 | b; + + }, + + /** + * Given 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xRRGGBB). + */ + getColor: function (r, g, b) { + + return r << 16 | g << 8 | b; + + }, + + /** + * Converts the given color values into a string. + * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + * + * @method Phaser.Color.RGBtoString + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255. + * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. + * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + */ + RGBtoString: function (r, g, b, a, prefix) { + + if (a === undefined) { a = 255; } + if (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); + } + + }, + + /** + * Converts a hex string into an integer color value. + * + * @method Phaser.Color.hexToRGB + * @static + * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. + * @return {number} The rgb color value in the format 0xAARRGGBB. + */ + hexToRGB: function (hex) { + + var rgb = Phaser.Color.hexToColor(hex); + + if (rgb) + { + return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b); + } + + }, + + /** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @method Phaser.Color.hexToColor + * @static + * @param {string} hex - The color string in a hex format. + * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + hexToColor: function (hex, out) { + + // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") + hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { + return r + r + g + g + b + b; + }); + + var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + + if (result) + { + var r = parseInt(result[1], 16); + var g = parseInt(result[2], 16); + var b = parseInt(result[3], 16); + + if (!out) + { + out = Phaser.Color.createColor(r, g, b); + } + else + { + out.r = r; + out.g = g; + out.b = b; + } + } + + return out; + + }, + + /** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @method Phaser.Color.webToColor + * @static + * @param {string} web - The color string in CSS 'web' format. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + webToColor: function (web, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web); + + if (result) + { + out.r = ~~Number(result[1]); + out.g = ~~Number(result[2]); + out.b = ~~Number(result[3]); + out.a = result[4] !== undefined ? Number(result[4]) : 1; + Phaser.Color.updateColor(out); + } + + return out; + + }, + + /** + * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. + * + * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). + * + * An alpha channel is _not_ supported when specifying a hex string. + * + * @method Phaser.Color.valueToColor + * @static + * @param {string|number} value - The color expressed as a recognized string format or a packed integer. + * @param {object} [out] - The object to use for the output. If not provided a new object will be created. + * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. + */ + valueToColor: function (value, out) { + + // The behavior is not consistent between hexToColor/webToColor on invalid input. + // This unifies both by returning a new object, but returning null may be better. + if (!out) + { + out = Phaser.Color.createColor(); + } + + if (typeof value === 'string') + { + if (value.indexOf('rgb') === 0) + { + return Phaser.Color.webToColor(value, out); + } + else + { + // `hexToColor` does not support alpha; match `createColor`. + out.a = 1; + return Phaser.Color.hexToColor(value, out); + } + } + else if (typeof value === 'number') + { + // `getRGB` does not take optional object to modify; + // alpha is also adjusted to match `createColor`. + var tempColor = Phaser.Color.getRGB(value); + out.r = tempColor.r; + out.g = tempColor.g; + out.b = tempColor.b; + out.a = tempColor.a / 255; + return out; + } + else + { + return out; + } + + }, + + /** + * Return a string containing a hex representation of the given color component. + * + * @method Phaser.Color.componentToHex + * @static + * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. + * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ + componentToHex: function (color) { + + var hex = color.toString(16); + + return (hex.length === 1) ? '0' + hex : hex; + + }, + + /** + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSVColorWheel + * @static + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSV color wheel. + */ + HSVColorWheel: function (s, v) { + + if (s === undefined) { s = 1.0; } + if (v === undefined) { v = 1.0; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v)); + } + + return colors; + + }, + + /** + * Get HSL color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSLColorWheel + * @static + * @param {number} [s=0.5] - The saturation, in the range 0 - 1. + * @param {number} [l=0.5] - The lightness, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSL color wheel. + */ + HSLColorWheel: function (s, l) { + + if (s === undefined) { s = 0.5; } + if (l === undefined) { l = 0.5; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l)); + } + + return colors; + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColor + * @static + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @param {number} [alpha] - The alpha of the returned color. + * @param {number} [colorSpace=0] - The color space to interpolate in. 0 = RGB, 1 = HSV. + * @returns {number} The interpolated color value. + */ + interpolateColor: function (color1, color2, steps, currentStep, alpha, colorSpace) { + + if (alpha === undefined) { alpha = 255; } + if (colorSpace === undefined) { colorSpace = 0; } + + var src1 = Phaser.Color.getRGB(color1); + var src2 = Phaser.Color.getRGB(color2); + + if (colorSpace === 0) + { + 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; + } + + if (colorSpace === 1) + { + var hsv1 = Phaser.Color.RGBtoHSV(src1.r, src1.g, src1.b); + var hsv2 = Phaser.Color.RGBtoHSV(src2.r, src2.g, src2.b); + var dh = hsv2.h - hsv1.h; + var h; + + if (hsv1.h > hsv2.h) + { + var h3 = hsv2.h; + hsv2.h = hsv1.h; + hsv1.h = h3; + dh = -dh; + currentStep = steps - currentStep; + } + + if (dh > 0.5) + { + hsv1.h = hsv1.h + 1; + h = (((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h) % 1; + } + + if (dh <= 0.5) + { + h = ((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h; + } + + var s = (((hsv2.s - hsv1.s) * currentStep) / steps) + hsv1.s; + var v = (((hsv2.v - hsv1.v) * currentStep) / steps) + hsv1.v; + + var rgb = Phaser.Color.HSVtoRGB(h, s, v, rgb); + var r = rgb.r; + var g = rgb.g; + var b = rgb.b; + } + + return Phaser.Color.getColor32(alpha, r, g, b); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColorWithRGB + * @static + * @param {number} color - The first color value. + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * @method Phaser.Color.interpolateRGB + * @static + * @param {number} r1 - The red color value, between 0 and 0xFF (255). + * @param {number} g1 - The green color value, between 0 and 0xFF (255). + * @param {number} b1 - The blue color value, between 0 and 0xFF (255). + * @param {number} r2 - The red color value, between 0 and 0xFF (255). + * @param {number} g2 - The green color value, between 0 and 0xFF (255). + * @param {number} b2 - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + + /** + * Calculates a linear (interpolation) value of two colors over t. + * + * This is a slightly simpler interface to {@link Phaser.Color.interpolateColor}. + * + * The arguments are similar to {@link Phaser.Math.linear}. + * + * @method Phaser.Color.linear + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linear: function (color1, color2, t) { + + return this.interpolateColor(color1, color2, 1, t); + + }, + + /** + * Calculates a linear (interpolation) value of an array of colors over t. + * + * The arguments are similar to {@link Phaser.Math.linearInterpolation}. + * + * This can be used as a {@link Phaser.TweenData#interpolationFunction}. + * + * @method Phaser.Color.linearInterpolation + * @param {number[]} colors - The input array of color values to interpolate between. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linearInterpolation: function (colors, t) { + + var k = Phaser.Math.linear(0, colors.length - 1, t); + var color1 = colors[ Math.floor(k) ]; + var color2 = colors[ Math.ceil(k)] ; + + return this.linear(color1, color2, k % 1); + + }, + + /** + * Returns a random color value between black and white + * Set the min value to start each channel from the given offset. + * Set the max value to restrict the maximum color used per channel. + * + * @method Phaser.Color.getRandomColor + * @static + * @param {number} [min=0] - The lowest value to use for the color. + * @param {number} [max=255] - The highest value to use for the color. + * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). + * @returns {number} 32-bit color value with alpha. + */ + getRandomColor: function (min, max, alpha) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + if (alpha === undefined) { alpha = 255; } + + // Sanity checks + 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); + + }, + + /** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exist in the given color (0xAARRGGBB) + * + * @method Phaser.Color.getRGB + * @static + * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). + * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. + */ + getRGB: function (color) { + + if (color > 16777215) + { + // The color value has an alpha component + return { + alpha: color >>> 24, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: color >>> 24, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + else + { + return { + alpha: 255, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: 255, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + + }, + + /** + * Returns a CSS friendly string value from the given color. + * + * @method Phaser.Color.getWebRGB + * @static + * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. + * @returns {string} A string in the format: 'rgba(r,g,b,a)' + */ + getWebRGB: function (color) { + + if (typeof color === 'object') + { + return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')'; + } + else + { + var rgb = Phaser.Color.getRGB(color); + return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')'; + } + + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. + * + * @method Phaser.Color.getAlpha + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlpha: function (color) { + return color >>> 24; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. + * + * @method Phaser.Color.getAlphaFloat + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlphaFloat: function (color) { + return (color >>> 24) / 255; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. + * + * @method Phaser.Color.getRed + * @static + * @param {number} color In the format 0xAARRGGBB. + * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). + */ + getRed: function (color) { + return color >> 16 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. + * + * @method Phaser.Color.getGreen + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). + */ + getGreen: function (color) { + return color >> 8 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. + * + * @method Phaser.Color.getBlue + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). + */ + getBlue: function (color) { + return color & 0xFF; + }, + + /** + * Blends the source color, ignoring the backdrop. + * + * @method Phaser.Color.blendNormal + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNormal: function (a) { + return a; + }, + + /** + * Selects the lighter of the backdrop and source colors. + * + * @method Phaser.Color.blendLighten + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLighten: function (a, b) { + return (b > a) ? b : a; + }, + + /** + * Selects the darker of the backdrop and source colors. + * + * @method Phaser.Color.blendDarken + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDarken: function (a, b) { + return (b > a) ? a : b; + }, + + /** + * Multiplies the backdrop and source color values. + * The result color is always at least as dark as either of the two constituent + * colors. Multiplying any color with black produces black; + * multiplying with white leaves the original color unchanged. + * + * @method Phaser.Color.blendMultiply + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendMultiply: function (a, b) { + return (a * b) / 255; + }, + + /** + * Takes the average of the source and backdrop colors. + * + * @method Phaser.Color.blendAverage + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAverage: function (a, b) { + return (a + b) / 2; + }, + + /** + * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. + * + * @method Phaser.Color.blendAdd + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAdd: function (a, b) { + return Math.min(255, a + b); + }, + + /** + * Combines the source and backdrop colors and returns their value minus 255. + * + * @method Phaser.Color.blendSubtract + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSubtract: function (a, b) { + return Math.max(0, a + b - 255); + }, + + /** + * Subtracts the darker of the two constituent colors from the lighter. + * + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendDifference + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDifference: function (a, b) { + return Math.abs(a - b); + }, + + /** + * Negation blend mode. + * + * @method Phaser.Color.blendNegation + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNegation: function (a, b) { + return 255 - Math.abs(255 - a - b); + }, + + /** + * Multiplies the complements of the backdrop and source color values, then complements the result. + * The result color is always at least as light as either of the two constituent colors. + * Screening any color with white produces white; screening with black leaves the original color unchanged. + * + * @method Phaser.Color.blendScreen + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendScreen: function (a, b) { + return 255 - (((255 - a) * (255 - b)) >> 8); + }, + + /** + * Produces an effect similar to that of the Difference mode, but lower in contrast. + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendExclusion + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendExclusion: function (a, b) { + return a + b - 2 * a * b / 255; + }, + + /** + * Multiplies or screens the colors, depending on the backdrop color. + * Source colors overlay the backdrop while preserving its highlights and shadows. + * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. + * + * @method Phaser.Color.blendOverlay + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendOverlay: function (a, b) { + return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255); + }, + + /** + * Darkens or lightens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. + * The effect is similar to shining a diffused spotlight on the backdrop. + * + * @method Phaser.Color.blendSoftLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSoftLight: function (a, b) { + return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255); + }, + + /** + * Multiplies or screens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; + * this is useful for adding shadows to a scene. + * + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. + * + * @method Phaser.Color.blendHardLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardLight: function (a, b) { + return Phaser.Color.blendOverlay(b, a); + }, + + /** + * Brightens the backdrop color to reflect the source color. + * Painting with black produces no change. + * + * @method Phaser.Color.blendColorDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorDodge: function (a, b) { + return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b))); + }, + + /** + * Darkens the backdrop color to reflect the source color. + * Painting with white produces no change. + * + * @method Phaser.Color.blendColorBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorBurn: function (a, b) { + return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b)); + }, + + /** + * An alias for blendAdd, it simply sums the values of the two colors. + * + * @method Phaser.Color.blendLinearDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearDodge: function (a, b) { + return Phaser.Color.blendAdd(a, b); + }, + + /** + * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. + * + * @method Phaser.Color.blendLinearBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearBurn: function (a, b) { + return Phaser.Color.blendSubtract(a, b); + }, + + /** + * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). + * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. + * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. + * + * @method Phaser.Color.blendLinearLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearLight: function (a, b) { + return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128))); + }, + + /** + * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). + * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. + * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom + * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. + * + * @method Phaser.Color.blendVividLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendVividLight: function (a, b) { + return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128))); + }, + + /** + * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. + * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. + * + * @method Phaser.Color.blendPinLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPinLight: function (a, b) { + return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128))); + }, + + /** + * Runs blendVividLight on the source and backdrop colors. + * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. + * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. + * This changes all pixels to primary additive colors (red, green, or blue), white, or black. + * + * @method Phaser.Color.blendHardMix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardMix: function (a, b) { + return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255; + }, + + /** + * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. + * + * @method Phaser.Color.blendReflect + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendReflect: function (a, b) { + return b === 255 ? b : Math.min(255, (a * a / (255 - b))); + }, + + /** + * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. + * + * @method Phaser.Color.blendGlow + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendGlow: function (a, b) { + return Phaser.Color.blendReflect(b, a); + }, + + /** + * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. + * + * @method Phaser.Color.blendPhoenix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPhoenix: function (a, b) { + return Math.min(a, b) - Math.max(a, b) + 255; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Manager is responsible for looking after all of the running physics systems. +* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. +* +* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. +* +* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the +* faster (due to being much simpler) Arcade Physics system. +* +* @class Phaser.Physics +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Physics = function (game, config) { + + config = config || {}; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} config - The physics configuration object as passed to the game on creation. + */ + this.config = config; + + /** + * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. + */ + this.arcade = null; + + /** + * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. + */ + this.p2 = null; + + /** + * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. + */ + this.ninja = null; + + /** + * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. + */ + this.box2d = null; + + /** + * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). + */ + this.chipmunk = null; + + /** + * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). + */ + this.matter = null; + + this.parseConfig(); + +}; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.ARCADE = 0; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.P2JS = 1; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.NINJA = 2; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.BOX2D = 3; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.CHIPMUNK = 4; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.MATTERJS = 5; + +Phaser.Physics.prototype = { + + /** + * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. + * + * @method Phaser.Physics#parseConfig + */ + parseConfig: function () { + + if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade')) + { + // If Arcade isn't specified, we create it automatically if we can + this.arcade = new Phaser.Physics.Arcade(this.game); + } + + 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); + } + + if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D')) + { + this.box2d = new Phaser.Physics.BOX2D(this.game, this.config); + } + + if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter')) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + + }, + + /** + * This will create an instance of the requested physics simulation. + * Phaser.Physics.Arcade is running by default, but all others need activating directly. + * + * You can start the following physics systems: + * + * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. + * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) + * + * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. + * They are not bundled into the core Phaser library. + * + * If the physics world has already been created (i.e. in another state in your game) then + * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors + * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. + * + * @method Phaser.Physics#startSystem + * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. + */ + startSystem: function (system) { + + if (system === Phaser.Physics.ARCADE) + { + this.arcade = new Phaser.Physics.Arcade(this.game); + } + else if (system === Phaser.Physics.P2JS) + { + if (this.p2 === null) + { + this.p2 = new Phaser.Physics.P2(this.game, this.config); + } + else + { + this.p2.reset(); + } + } + else if (system === Phaser.Physics.NINJA) + { + this.ninja = new Phaser.Physics.Ninja(this.game); + } + else if (system === Phaser.Physics.BOX2D) + { + if (this.box2d === null) + { + this.box2d = new Phaser.Physics.Box2D(this.game, this.config); + } + else + { + this.box2d.reset(); + } + } + else if (system === Phaser.Physics.MATTERJS) + { + if (this.matter === null) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + else + { + this.matter.reset(); + } + } + + }, + + /** + * This will create a default physics body on the given game object or array of objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * It can be for any of the physics systems that have been started: + * + * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. + * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. + * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 + * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) + * Phaser.Physics.CHIPMUNK is still in development. + * + * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the + * individual physics systems `enable` methods instead of using this generic one. + * + * @method Phaser.Physics#enable + * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. + * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. + * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. + */ + enable: function (object, system, debug) { + + if (system === undefined) { system = Phaser.Physics.ARCADE; } + if (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); + } + else if (system === Phaser.Physics.BOX2D && this.box2d) + { + this.box2d.enable(object); + } + else if (system === Phaser.Physics.MATTERJS && this.matter) + { + this.matter.enable(object); + } + else + { + console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.'); + } + + }, + + /** + * preUpdate checks. + * + * @method Phaser.Physics#preUpdate + * @protected + */ + preUpdate: function () { + + // ArcadePhysics / Ninja don't have a core to preUpdate + + if (this.p2) + { + this.p2.preUpdate(); + } + + if (this.box2d) + { + this.box2d.preUpdate(); + } + + if (this.matter) + { + this.matter.preUpdate(); + } + + }, + + /** + * Updates all running physics systems. + * + * @method Phaser.Physics#update + * @protected + */ + update: function () { + + // ArcadePhysics / Ninja don't have a core to update + + if (this.p2) + { + this.p2.update(); + } + + if (this.box2d) + { + this.box2d.update(); + } + + if (this.matter) + { + this.matter.update(); + } + + }, + + /** + * Updates the physics bounds to match the world dimensions. + * + * @method Phaser.Physics#setBoundsToWorld + * @protected + */ + setBoundsToWorld: function () { + + if (this.arcade) + { + this.arcade.setBoundsToWorld(); + } + + if (this.ninja) + { + this.ninja.setBoundsToWorld(); + } + + if (this.p2) + { + this.p2.setBoundsToWorld(); + } + + if (this.box2d) + { + this.box2d.setBoundsToWorld(); + } + + if (this.matter) + { + this.matter.setBoundsToWorld(); + } + + }, + + /** + * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. + * + * @method Phaser.Physics#clear + * @protected + */ + clear: function () { + + if (this.p2) + { + this.p2.clear(); + } + + if (this.box2d) + { + this.box2d.clear(); + } + + if (this.matter) + { + this.matter.clear(); + } + + }, + + /** + * Resets the active physics system. Called automatically on a Phaser.State swap. + * + * @method Phaser.Physics#reset + * @protected + */ + reset: function () { + + if (this.p2) + { + this.p2.reset(); + } + + if (this.box2d) + { + this.box2d.reset(); + } + + if (this.matter) + { + this.matter.reset(); + } + + }, + + /** + * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. + * + * @method Phaser.Physics#destroy + */ + destroy: function () { + + if (this.p2) + { + this.p2.destroy(); + } + + if (this.box2d) + { + this.box2d.destroy(); + } + + if (this.matter) + { + this.matter.destroy(); + } + + this.arcade = null; + this.ninja = null; + this.p2 = null; + this.box2d = null; + this.matter = null; + + } + +}; + +Phaser.Physics.prototype.constructor = Phaser.Physics; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. +* +* @class Phaser.Physics.Arcade +* @constructor +* @param {Phaser.Game} game - reference to the current game instance. +*/ +Phaser.Physics.Arcade = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height); + + /** + * Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`. + * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. + * @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right). + */ + this.checkCollision = { up: true, down: true, left: true, right: true }; + + /** + * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. + */ + this.maxLevels = 4; + + /** + * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. + * @default + */ + this.OVERLAP_BIAS = 4; + + /** + * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. + */ + this.forceX = false; + + /** + * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT. + * @default + */ + this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT; + + /** + * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. + */ + this.skipQuadTree = true; + + /** + * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. + */ + this.isPaused = false; + + /** + * @property {Phaser.QuadTree} quadTree - The world QuadTree. + */ + 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); + + /** + * @property {number} _total - Internal cache var. + * @private + */ + this._total = 0; + + // By default we want the bounds the same size as the world bounds + this.setBoundsToWorld(); + +}; + +Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade; + +/** +* A constant used for the sortDirection value. +* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.SORT_NONE = 0; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.LEFT_RIGHT = 1; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.RIGHT_LEFT = 2; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.TOP_BOTTOM = 3; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.BOTTOM_TOP = 4; + +Phaser.Physics.Arcade.prototype = { + + /** + * Updates the size of this physics world. + * + * @method Phaser.Physics.Arcade#setBounds + * @param {number} x - Top left most corner of the world. + * @param {number} y - Top left most corner of the world. + * @param {number} width - New width of the world. Can never be smaller than the Game.width. + * @param {number} height - New height of the world. Can never be smaller than the Game.height. + */ + setBounds: function (x, y, width, height) { + + this.bounds.setTo(x, y, width, height); + + }, + + /** + * Updates the size of this physics world to match the size of the game world. + * + * @method Phaser.Physics.Arcade#setBoundsToWorld + */ + setBoundsToWorld: function () { + + this.bounds.copyFrom(this.game.world.bounds); + + }, + + /** + * This will create an Arcade Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * + * @method Phaser.Physics.Arcade#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, children) { + + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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) + { + // If it's a Group then we do it on the children regardless + this.enable(object.children, children); + } + else + { + this.enableBody(object); + + if (children && object.hasOwnProperty('children') && object.children.length > 0) + { + this.enable(object.children, true); + } + } + } + + }, + + /** + * Creates an Arcade Physics body on the given game object. + * + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. + * + * @method Phaser.Physics.Arcade#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + */ + enableBody: function (object) { + + if (object.hasOwnProperty('body') && object.body === null) + { + object.body = new Phaser.Physics.Arcade.Body(object); + + if (object.parent && object.parent instanceof Phaser.Group) + { + object.parent.addToHash(object); + } + } + + }, + + /** + * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. + * + * @method Phaser.Physics.Arcade#updateMotion + * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. + */ + updateMotion: function (body) { + + if (body.allowRotation) + { + var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity; + body.angularVelocity += 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); + + }, + + /** + * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * Based on a function in Flixel by @ADAMATOMIC + * + * @method Phaser.Physics.Arcade#computeVelocity + * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical. + * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. + * @param {number} velocity - Any component of velocity (e.g. 20). + * @param {number} acceleration - Rate at which the velocity is changing. + * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. + * @param {number} [max=10000] - An absolute value cap for the velocity. + * @return {number} The altered Velocity value. + */ + computeVelocity: function (axis, body, velocity, acceleration, drag, max) { + + if (max === undefined) { max = 10000; } + + 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 && body.allowDrag) + { + drag *= this.game.time.physicsElapsed; + + if (velocity - drag > 0) + { + velocity -= drag; + } + else if (velocity + drag < 0) + { + velocity += drag; + } + else + { + velocity = 0; + } + } + + if (velocity > max) + { + velocity = max; + } + else if (velocity < -max) + { + velocity = -max; + } + + return velocity; + + }, + + /** + * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. + * + * Unlike {@link #collide} the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. + * Both the first and second parameter can be arrays of objects, of differing types. + * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups within Groups). + * + * ##### Tilemaps + * + * Any overlapping tiles, including blank/null tiles, will give a positive result. Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) have no special status, and callbacks added via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} are not invoked. So calling this method without any callbacks isn't very useful. + * + * If you're interested only in whether an object overlaps a certain tile or class of tiles, filter the tiles with `processCallback` and then use the result returned by this method. Blank/null tiles can be excluded by their {@link Phaser.Tile#index index} (-1). + * + * If you want to take action on certain overlaps, examine the tiles in `collideCallback` and then handle as you like. + * + * @method Phaser.Physics.Arcade#overlap + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if an overlap occurred otherwise false. + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) { + + overlapCallback = overlapCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || overlapCallback; + + this._total = 0; + + this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + + return (this._total > 0); + + }, + + /** + * Checks for collision between two game objects and separates them if colliding ({@link https://gist.github.com/samme/cbb81dd19f564dcfe2232761e575063d details}). If you don't require separation then use {@link #overlap} instead. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. + * Both the `object1` and `object2` can be arrays of objects, of differing types. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If one Group **only** is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If either object is `null` the collision test will fail. + * + * Bodies with `enable = false` and Sprites with `exists = false` are skipped (ignored). + * + * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. + * + * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). + * + * ##### Examples + * + * ```javascript + * collide(group); + * collide(group, undefined); // equivalent + * + * collide(sprite1, sprite2); + * + * collide(sprite, group); + * + * collide(group1, group2); + * + * collide([sprite1, sprite2], [sprite3, sprite4]); // 1 vs. 3, 1 vs. 4, 2 vs. 3, 2 vs. 4 + * ``` + * + * ##### Tilemaps + * + * Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) are "solid". If a Sprite collides with one of these tiles, the two are separated by moving the Sprite outside the tile's edges. Enable {@link Phaser.TilemapLayer#debug} to see the colliding edges of the Tilemap. + * + * Tiles with a callback attached via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} invoke the callback if a Sprite collides with them. If a tile has a callback attached via both methods, only the location callback is invoked. The colliding Sprite is separated from the tile only if the callback returns `true`. + * + * @method Phaser.Physics.Arcade#collide + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. + * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if a collision occurred otherwise false. + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) { + + collideCallback = collideCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || collideCallback; + + this._total = 0; + + this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + + return (this._total > 0); + + }, + + /** + * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortLeftRight + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortLeftRight: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.x - b.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortRightLeft + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortRightLeft: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.x - a.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortTopBottom + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortTopBottom: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.y - b.body.y; + + }, + + /** + * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortBottomTop + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortBottomTop: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.y - a.body.y; + + }, + + /** + * This method will sort a Groups hash array. + * + * If the Group has `physicsSortDirection` set it will use the sort direction defined. + * + * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection. + * + * By changing Group.physicsSortDirection you can customise each Group to sort in a different order. + * + * @method Phaser.Physics.Arcade#sort + * @param {Phaser.Group} group - The Group to sort. + * @param {integer} [sortDirection] - The sort direction used to sort this Group. + */ + sort: function (group, sortDirection) { + + if (group.physicsSortDirection !== null) + { + sortDirection = group.physicsSortDirection; + } + else + { + if (sortDirection === undefined) { sortDirection = this.sortDirection; } + } + + if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + // Game world is say 2000x600 and you start at 0 + group.hash.sort(this.sortLeftRight); + } + else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + // Game world is say 2000x600 and you start at 2000 + group.hash.sort(this.sortRightLeft); + } + else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + // Game world is say 800x2000 and you start at 0 + group.hash.sort(this.sortTopBottom); + } + else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + // Game world is say 800x2000 and you start at 2000 + group.hash.sort(this.sortBottomTop); + } + + }, + + /** + * Internal collision handler. Extracts objects for {@link #collideHandler}. + * + * @method Phaser.Physics.Arcade#collideObjects + * @private + */ + collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object2.length; i++) + { + if (!object2[i]) { continue; } + + this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && !Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + for (var j = 0; j < object2.length; j++) + { + if (!object2[j]) { continue; } + + this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + + }, + + /** + * Internal collision handler. Matches arguments to other handlers. + * + * @method Phaser.Physics.Arcade#collideHandler + * @private + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + // Only collide valid objects + if (object2 === undefined && object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly); + return; + } + + // If neither of the objects are set or exist then bail out + if (!object1 || !object2 || !object1.exists || !object2.exists) + { + return; + } + + // Groups? Sort them + if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE) + { + if (object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + } + + if (object2.physicsType === Phaser.GROUP) + { + this.sort(object2); + } + } + + // SPRITES + if (object1.physicsType === Phaser.SPRITE) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // GROUPS + else if (object1.physicsType === Phaser.GROUP) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // TILEMAP LAYERS + else if (object1.physicsType === Phaser.TILEMAPLAYER) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsSprite + * @private + * @param {Phaser.Sprite} sprite1 - The first sprite to check. + * @param {Phaser.Sprite} sprite2 - The second sprite to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + 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; + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsGroup + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0 || !sprite.body) + { + return; + } + + if (this.skipQuadTree || sprite.body.skipQuadTree) + { + var bounds = {}; + + for (var i = 0; i < group.hash.length; i++) + { + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds object + bounds = object1.body.getBounds(bounds); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (sprite.body.right < bounds.x) + { + break; + } + else if (bounds.right < sprite.body.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (sprite.body.x > bounds.right) + { + break; + } + else if (bounds.x > sprite.body.right) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (sprite.body.bottom < bounds.y) + { + break; + } + else if (bounds.bottom < sprite.body.y) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (sprite.body.y > bounds.bottom) + { + break; + } + else if (bounds.y > sprite.body.bottom) + { + continue; + } + } + + this.collideSpriteVsSprite(sprite, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else + { + // What is the sprite colliding with in the quadtree? + 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 items = this.quadTree.retrieve(sprite); + + for (var i = 0; i < items.length; i++) + { + // We have our potential suspects, are they in this group? + if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, items[i].sprite); + } + + this._total++; + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsSelf + * @private + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.hash.length; i++) + { + var bounds1 = {}; + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds1 object + bounds1 = object1.body.getBounds(bounds1); + + for (var j = i + 1; j < group.hash.length; j++) + { + var bounds2 = {}; + var object2 = group.hash[j]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object2 || !object2.exists || !object2.body) + { + continue; + } + + // Inject the Body bounds data into the bounds2 object + bounds2 = object2.body.getBounds(bounds2); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (bounds1.right < bounds2.x) + { + break; + } + else if (bounds2.right < bounds1.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (bounds1.x > bounds2.right) + { + continue; + } + else if (bounds2.x > bounds1.right) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (bounds1.bottom < bounds2.y) + { + continue; + } + else if (bounds2.bottom < bounds1.y) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (bounds1.y > bounds2.bottom) + { + continue; + } + else if (bounds2.y > object1.body.bottom) + { + break; + } + } + + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsGroup + * @private + * @param {Phaser.Group} group1 - The first Group to check. + * @param {Phaser.Group} group2 - The second Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group1.length === 0 || group2.length === 0) + { + return; + } + + for (var i = 0; i < group1.children.length; i++) + { + if (group1.children[i].exists) + { + if (group1.children[i].physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else + { + this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + + }, + + /** + * The core separation function to separate two physics bodies. + * + * @private + * @method Phaser.Physics.Arcade#separate + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true. + * @param {object} [callbackContext] - The context in which to run the process callback. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} Returns true if the bodies collided, otherwise false. + */ + separate: function (body1, body2, processCallback, callbackContext, overlapOnly) { + + if ( + !body1.enable || + !body2.enable || + body1.checkCollision.none || + body2.checkCollision.none || + !this.intersects(body1, body2)) + { + return false; + } + + // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. + if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false) + { + return false; + } + + // Circle vs. Circle quick bail out + if (body1.isCircle && body2.isCircle) + { + return this.separateCircle(body1, body2, overlapOnly); + } + + // We define the behavior of bodies in a collision circle and rectangle + // If a collision occurs in the corner points of the rectangle, the body behave like circles + + // Either body1 or body2 is a circle + if (body1.isCircle !== body2.isCircle) + { + var bodyRect = (body1.isCircle) ? body2 : body1; + var bodyCircle = (body1.isCircle) ? body1 : body2; + + var rect = { + x: bodyRect.x, + y: bodyRect.y, + right: bodyRect.right, + bottom: bodyRect.bottom + }; + + var circle = bodyCircle.center; + + if (circle.y < rect.y || circle.y > rect.bottom) + { + if (circle.x < rect.x || circle.x > rect.right) + { + return this.separateCircle(body1, body2, overlapOnly); + } + } + } + + var resultX = false; + var resultY = false; + + // Do we separate on x or y first? + if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) + { + resultX = this.separateX(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultY = this.separateY(body1, body2, overlapOnly); + } + } + else + { + resultY = this.separateY(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultX = this.separateX(body1, body2, overlapOnly); + } + } + + var result = (resultX || resultY); + + if (result) + { + if (overlapOnly) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + else + { + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + } + } + + return result; + + }, + + /** + * Check for intersection against two bodies. + * + * @method Phaser.Physics.Arcade#intersects + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check. + * @return {boolean} True if they intersect, otherwise false. + */ + intersects: function (body1, body2) { + + if (body1 === body2) + { + return false; + } + + if (body1.isCircle) + { + if (body2.isCircle) + { + // Circle vs. Circle + return Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); + } + else + { + // Circle vs. Rect + return this.circleBodyIntersects(body1, body2); + } + } + else + { + if (body2.isCircle) + { + // Rect vs. Circle + return this.circleBodyIntersects(body2, body1); + } + else + { + // Rect vs. Rect + if (body1.right <= body2.position.x) + { + return false; + } + + if (body1.bottom <= body2.position.y) + { + return false; + } + + if (body1.position.x >= body2.right) + { + return false; + } + + if (body1.position.y >= body2.bottom) + { + return false; + } + + return true; + } + } + + }, + + /** + * Checks to see if a circular Body intersects with a Rectangular Body. + * + * @method Phaser.Physics.Arcade#circleBodyIntersects + * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set. + * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape) + * @return {boolean} Returns true if the bodies intersect, otherwise false. + */ + circleBodyIntersects: function (circle, body) { + + var x = Phaser.Math.clamp(circle.center.x, body.left, body.right); + var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom); + + var dx = (circle.center.x - x) * (circle.center.x - x); + var dy = (circle.center.y - y) * (circle.center.y - y); + + return (dx + dy) <= (circle.halfWidth * circle.halfWidth); + + }, + + /** + * The core separation function to separate two circular physics bodies. + * + * @method Phaser.Physics.Arcade#separateCircle + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateCircle: function (body1, body2, overlapOnly) { + + // Set the bounding box overlap values + this.getOverlapX(body1, body2); + this.getOverlapY(body1, body2); + + var dx = body2.center.x - body1.center.x; + var dy = body2.center.y - body1.center.y; + + var angleCollision = Math.atan2(dy, dx); + + var overlap = 0; + + if (body1.isCircle !== body2.isCircle) + { + var rect = { + x: (body2.isCircle) ? body1.position.x : body2.position.x, + y: (body2.isCircle) ? body1.position.y : body2.position.y, + right: (body2.isCircle) ? body1.right : body2.right, + bottom: (body2.isCircle) ? body1.bottom : body2.bottom + }; + + var circle = { + x: (body1.isCircle) ? body1.center.x : body2.center.x, + y: (body1.isCircle) ? body1.center.y : body2.center.y, + radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth + }; + + if (circle.y < rect.y) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.y) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.y) - circle.radius; + } + } + else if (circle.y > rect.bottom) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; + } + } + + overlap *= -1; + } + else + { + overlap = (body1.halfWidth + body2.halfWidth) - Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y); + } + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + if (overlap !== 0) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + + // return true if there was some overlap, otherwise false + return (overlap !== 0); + } + + // Transform the velocity vector to the coordinate system oriented along the direction of impact. + // This is done to eliminate the vertical component of the velocity + var v1 = { + x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision), + y: body1.velocity.x * Math.sin(angleCollision) - body1.velocity.y * Math.cos(angleCollision) + }; + + var v2 = { + x: body2.velocity.x * Math.cos(angleCollision) + body2.velocity.y * Math.sin(angleCollision), + y: body2.velocity.x * Math.sin(angleCollision) - body2.velocity.y * Math.cos(angleCollision) + }; + + // We expect the new velocity after impact + var tempVel1 = ((body1.mass - body2.mass) * v1.x + 2 * body2.mass * v2.x) / (body1.mass + body2.mass); + var tempVel2 = (2 * body1.mass * v1.x + (body2.mass - body1.mass) * v2.x) / (body1.mass + body2.mass); + + // We convert the vector to the original coordinate system and multiplied by factor of rebound + if (!body1.immovable) + { + body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x; + body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y; + } + + if (!body2.immovable) + { + body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x; + body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y; + } + + // When the collision angle is almost perpendicular to the total initial velocity vector + // (collision on a tangent) vector direction can be determined incorrectly. + // This code fixes the problem + + if (Math.abs(angleCollision) < Math.PI / 2) + { + if ((body1.velocity.x > 0) && !body1.immovable && (body2.velocity.x > body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x < 0) && !body2.immovable && (body1.velocity.x < body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y > 0) && !body1.immovable && (body2.velocity.y > body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y < 0) && !body2.immovable && (body1.velocity.y < body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + else if (Math.abs(angleCollision) > Math.PI / 2) + { + if ((body1.velocity.x < 0) && !body1.immovable && (body2.velocity.x < body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y < 0) && !body1.immovable && (body2.velocity.y < body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + + if (!body1.immovable) + { + body1.x += (body1.velocity.x * this.game.time.physicsElapsed) - overlap * Math.cos(angleCollision); + body1.y += (body1.velocity.y * this.game.time.physicsElapsed) - overlap * Math.sin(angleCollision); + } + + if (!body2.immovable) + { + body2.x += (body2.velocity.x * this.game.time.physicsElapsed) + overlap * Math.cos(angleCollision); + body2.y += (body2.velocity.y * this.game.time.physicsElapsed) + overlap * Math.sin(angleCollision); + } + + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + + return true; + + }, + + /** + * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: + * `touching.left`, `touching.right` and `overlapX`. + * + * @method Phaser.Physics.Arcade#getOverlapX + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of horizontal overlap between the two bodies. + */ + getOverlapX: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS; + + if (body1.deltaX() === 0 && body2.deltaX() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaX() > body2.deltaX()) + { + // Body1 is moving right and / or Body2 is moving left + overlap = body1.right - body2.x; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.right = true; + body2.touching.none = false; + body2.touching.left = true; + } + } + else if (body1.deltaX() < body2.deltaX()) + { + // Body1 is moving left and/or Body2 is moving right + overlap = body1.x - body2.width - body2.x; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.left = true; + body2.touching.none = false; + body2.touching.right = true; + } + } + + // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapX = overlap; + body2.overlapX = overlap; + + return overlap; + + }, + + /** + * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: + * `touching.up`, `touching.down` and `overlapY`. + * + * @method Phaser.Physics.Arcade#getOverlapY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of vertical overlap between the two bodies. + */ + getOverlapY: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS; + + if (body1.deltaY() === 0 && body2.deltaY() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaY() > body2.deltaY()) + { + // Body1 is moving down and/or Body2 is moving up + overlap = body1.bottom - body2.y; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.down = true; + body2.touching.none = false; + body2.touching.up = true; + } + } + else if (body1.deltaY() < body2.deltaY()) + { + // Body1 is moving up and/or Body2 is moving down + overlap = body1.y - body2.bottom; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.up = true; + body2.touching.none = false; + body2.touching.down = true; + } + } + + // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapY = overlap; + body2.overlapY = overlap; + + return overlap; + + }, + + /** + * The core separation function to separate two physics bodies on the x axis. + * + * @method Phaser.Physics.Arcade#separateX + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateX: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapX(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.x; + var v2 = body2.velocity.x; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.x -= overlap; + body2.x += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.x = avg + nv1 * body1.bounce.x; + body2.velocity.x = avg + nv2 * body2.bounce.x; + } + else if (!body1.immovable) + { + body1.x -= overlap; + body1.velocity.x = v2 - v1 * body1.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body2.moves) + { + body1.y += (body2.y - body2.prev.y) * body2.friction.y; + } + } + else + { + body2.x += overlap; + body2.velocity.x = v1 - v2 * body2.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body1.moves) + { + body2.y += (body1.y - body1.prev.y) * body1.friction.y; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * The core separation function to separate two physics bodies on the y axis. + * + * @private + * @method Phaser.Physics.Arcade#separateY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateY: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapY(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.y; + var v2 = body2.velocity.y; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.y -= overlap; + body2.y += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.y = avg + nv1 * body1.bounce.y; + body2.velocity.y = avg + nv2 * body2.bounce.y; + } + else if (!body1.immovable) + { + body1.y -= overlap; + body1.velocity.y = v2 - v1 * body1.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body2.moves) + { + body1.x += (body2.x - body2.prev.x) * body2.friction.x; + } + } + else + { + body2.y += overlap; + body2.velocity.y = v1 - v2 * body2.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body1.moves) + { + body2.x += (body1.x - body1.prev.x) * body1.friction.x; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. + * + * @method Phaser.Physics.Arcade#getObjectsUnderPointer + * @param {Phaser.Pointer} pointer - The Pointer to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. + * @param {object} [callbackContext] - The context in which to run the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates. + */ + getObjectsUnderPointer: function (pointer, group, callback, callbackContext) { + + if (group.length === 0 || !pointer.exists) + { + return; + } + + return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer); + + }, + + /** + * Given a Group and a location this will check to see which Group children overlap with the coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. + * + * @method Phaser.Physics.Arcade#getObjectsAtLocation + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. + * @param {object} [callbackContext] - The context in which to run the callback. + * @param {object} [callbackArg] - An argument to pass to the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates. + */ + getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) { + + 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(x, y, 1, 1); + var output = []; + + var items = this.quadTree.retrieve(rect); + + for (var i = 0; i < items.length; i++) + { + if (items[i].hitTest(x, y)) + { + if (callback) + { + callback.call(callbackContext, callbackArg, items[i].sprite); + } + + output.push(items[i].sprite); + } + } + + return output; + + }, + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToObject: function (displayObject, destination, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Phaser.Point.angle(destination, displayObject); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#moveToPointer + * @param {any} displayObject - The display object to move. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToPointer: function (displayObject, speed, pointer, maxTime) { + + if (speed === undefined) { speed = 60; } + pointer = pointer || this.game.input.activePointer; + if (maxTime === undefined) { maxTime = 0; } + + var angle = this.angleToPointer(displayObject, pointer); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToXY: function (displayObject, x, y, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Math.atan2(y - displayObject.y, x - displayObject.x); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromAngle + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromAngle: function (angle, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(angle, speed, true); + + }, + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. + * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. + * + * @method Phaser.Physics.Arcade#accelerationFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. + * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. + */ + accelerationFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleBetween(displayObject, destination); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToPointer + * @param {any} displayObject - The display object to move. + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToPointer(displayObject, pointer); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToXY(displayObject, x, y); + + displayObject.body.acceleration.setTo(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Find the distance between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * If you have nested objects and need to calculate the distance between their centers in World coordinates, + * set their anchors to (0.5, 0.5) and use the `world` argument. + * + * If objects aren't nested or they share a parent's offset, you can calculate the distance between their + * centers with the `useCenter` argument, regardless of their anchor values. + * + * @method Phaser.Physics.Arcade#distanceBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {number} The distance between the source and target objects. + */ + distanceBetween: function (source, target, world, useCenter) { + + if (world === undefined) { world = false; } + + var dx; + var dy; + + if (useCenter) + { + dx = source.centerX - target.centerX; + dy = source.centerY - target.centerY; + } + else if (world) + { + dx = source.world.x - target.world.x; + dy = source.world.y - target.world.y; + } + else + { + dx = source.x - target.x; + dy = source.y - target.y; + } + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and the given x/y coordinates. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the x/y coordinates. + */ + distanceToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - x : displayObject.x - x; + var dy = (world) ? displayObject.world.y - y : displayObject.y - y; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the Pointer. + */ + distanceToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.x - pointer.worldX; + var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + + /** + * From a set of points or display objects, find the one closest to a source point or object. + * + * @method Phaser.Physics.Arcade#closest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The first target closest to the origin. + */ + closest: function (source, targets, world, useCenter) { + var min = Infinity; + var closest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance < min) + { + closest = target; + min = distance; + } + } + + return closest; + }, + + /** + * From a set of points or display objects, find the one farthest from a source point or object. + * + * @method Phaser.Physics.Arcade#farthest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The target closest to the origin. + */ + farthest: function (source, targets, world, useCenter) { + var max = -1; + var farthest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance > max) + { + farthest = target; + max = distance; + } + } + + return farthest; + }, + + /** + * Find the angle in radians between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetween: function (source, target, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Phaser.Point.angle(target.world, source.world); + } + else + { + return Phaser.Point.angle(target, source); + } + + }, + + /** + * Find the angle in radians between centers of two display objects (like Sprites). + * + * @method Phaser.Physics.Arcade#angleBetweenCenters + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetweenCenters: function (source, target) { + + var dx = target.centerX - source.centerX; + var dy = target.centerY - source.centerY; + + return Math.atan2(dy, dx); + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to get the angle to. + * @param {number} y - The y coordinate to get the angle to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(y - displayObject.world.y, x - displayObject.world.x); + } + else + { + return Math.atan2(y - displayObject.y, x - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x); + } + else + { + return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, + * taking their x/y and center into account relative to the world. + * + * @method Phaser.Physics.Arcade#worldAngleToPointer + * @param {any} displayObject - The DisplayObjerct to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY + */ + worldAngleToPointer: function (displayObject, pointer) { + + return this.angleToPointer(displayObject, pointer, true); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than +* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. +* +* @class Phaser.Physics.Arcade.Body +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. +*/ +Phaser.Physics.Arcade.Body = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = sprite.game; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.ARCADE; + + /** + * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. + * @default + */ + this.enable = true; + + /** + * If `true` this Body is using circular collision detection. If `false` it is using rectangular. + * Use `Body.setCircle` to control the collision shape this Body uses. + * @property {boolean} isCircle + * @default + * @readOnly + */ + this.isCircle = false; + + /** + * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled, relative to the Sprite's _texture_. + * If you wish to change the radius then call {@link #setCircle} again with the new value. + * If you wish to stop the Body using a circle then call {@link #setCircle} with a radius of zero (or undefined). + * The actual radius of the Body (at any Sprite scale) is equal to {@link #halfWidth} and the diameter is equal to {@link #width}. + * @property {number} radius + * @default + * @readOnly + */ + this.radius = 0; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite's texture. + */ + this.offset = new Phaser.Point(); + + /** + * @property {Phaser.Point} position - The position of the physics body, equivalent to ({@link #left}, {@link #top}). + * @readonly + */ + this.position = new Phaser.Point(sprite.x, sprite.y); + + /** + * @property {Phaser.Point} prev - The previous position of the physics body. + * @readonly + */ + this.prev = new Phaser.Point(this.position.x, this.position.y); + + /** + * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) + * @default + */ + this.allowRotation = true; + + /** + * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body + * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. + * @property {number} rotation + */ + this.rotation = sprite.angle; + + /** + * @property {number} preRotation - The previous rotation of the physics body, in degrees. + * @readonly + */ + this.preRotation = sprite.angle; + + /** + * @property {number} width - The calculated width of the physics body. + * @readonly + */ + this.width = sprite.width; + + /** + * @property {number} height - The calculated height of the physics body. + * @readonly + */ + this.height = sprite.height; + + /** + * @property {number} sourceWidth - The un-scaled original size. + * @readonly + */ + this.sourceWidth = sprite.width; + + /** + * @property {number} sourceHeight - The un-scaled original size. + * @readonly + */ + this.sourceHeight = sprite.height; + + if (sprite.texture) + { + this.sourceWidth = sprite.texture.frame.width; + this.sourceHeight = sprite.texture.frame.height; + } + + /** + * @property {number} halfWidth - The calculated width / 2 of the physics body. + * @readonly + */ + this.halfWidth = Math.abs(sprite.width / 2); + + /** + * @property {number} halfHeight - The calculated height / 2 of the physics body. + * @readonly + */ + this.halfHeight = Math.abs(sprite.height / 2); + + /** + * @property {Phaser.Point} center - The center coordinate of the Physics Body. + * @readonly + */ + this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight); + + /** + * @property {Phaser.Point} velocity - The velocity, or rate of change the Body's position. Measured in pixels per second. + */ + this.velocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} newVelocity - The distanced traveled during the last update, equal to `velocity * physicsElapsed`. Calculated during the Body.preUpdate and applied to its position. + * @readonly + */ + this.newVelocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. + */ + this.deltaMax = new Phaser.Point(); + + /** + * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + */ + this.acceleration = new Phaser.Point(); + + /** + * @property {boolean} allowDrag - Allow this Body to be influenced by {@link #drag}? + * @default + */ + this.allowDrag = true; + + /** + * @property {Phaser.Point} drag - The drag applied to the motion of the Body (when {@link #allowDrag} is enabled). Measured in pixels per second squared. + */ + this.drag = new Phaser.Point(); + + /** + * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local. + * @default + */ + this.allowGravity = true; + + /** + * @property {Phaser.Point} gravity - This Body's local gravity, **added** to any world gravity, unless Body.allowGravity is set to false. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. + */ + this.bounce = new Phaser.Point(); + + /** + * The elasticity of the Body when colliding with the World bounds. + * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property + * to a Phaser.Point object in order to enable a World bounds specific bounce value. + * @property {Phaser.Point} worldBounce + */ + this.worldBounce = null; + + /** + * A Signal that is dispatched when this Body collides with the world bounds. + * Due to the potentially high volume of signals this could create it is disabled by default. + * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` + * and it will be called when a collision happens, passing five arguments: + * `onWorldBounds(sprite, up, down, left, right)` + * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans + * indicating on which side of the world the Body collided. + * @property {Phaser.Signal} onWorldBounds + */ + this.onWorldBounds = null; + + /** + * A Signal that is dispatched when this Body collides with another Body. + * + * You still need to call `game.physics.arcade.collide` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `collide` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onCollide + */ + this.onCollide = null; + + /** + * A Signal that is dispatched when this Body overlaps with another Body. + * + * You still need to call `game.physics.arcade.overlap` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `overlap` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onOverlap + */ + this.onOverlap = null; + + /** + * @property {Phaser.Point} maxVelocity - The maximum velocity (in pixels per second squared) that the Body can reach. + * @default + */ + this.maxVelocity = new Phaser.Point(10000, 10000); + + /** + * @property {Phaser.Point} friction - If this Body is {@link #immovable} and moving, and another Body is 'riding' this one, this is the amount of motion the riding Body receives on each axis. + */ + this.friction = new Phaser.Point(1, 0); + + /** + * @property {number} angularVelocity - The angular velocity is the rate of change of the Body's rotation. It is measured in degrees per second. + * @default + */ + this.angularVelocity = 0; + + /** + * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. + * @default + */ + this.angularAcceleration = 0; + + /** + * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach. + * @default + */ + this.maxAngular = 1000; + + /** + * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. + * @default + */ + this.mass = 1; + + /** + * @property {number} angle - The angle of the Body's **velocity** in radians. + * @readonly + */ + this.angle = 0; + + /** + * @property {number} speed - The speed of the Body in pixels per second, equal to the magnitude of the velocity. + * @readonly + */ + this.speed = 0; + + /** + * @property {number} facing - A const reference to the direction the Body is traveling or facing: Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.UP, or Phaser.DOWN. If the Body is moving on both axes, UP and DOWN take precedence. + * @default + */ + this.facing = Phaser.NONE; + + /** + * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. **Two** immovable Bodies can't separate or exchange momentum and will pass through each other. + * @default + */ + this.immovable = false; + + /** + * Whether the physics system should update the Body's position and rotation based on its velocity, acceleration, drag, and gravity. + * + * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never + * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. + * If you want the physics system to move the body around, then set moves to true. + * + * A Body with moves = false can still be moved slightly (but not accelerated) during collision separation unless you set {@link #immovable} as well. + * + * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually. + * @default + */ + this.moves = true; + + /** + * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateX = false; + + /** + * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateY = false; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapX - The amount of horizontal overlap during the collision. + */ + this.overlapX = 0; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapY - The amount of vertical overlap during the collision. + */ + this.overlapY = 0; + + /** + * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. + * @property {number} overlapR - The amount of overlap during the collision. + */ + this.overlapR = 0; + + /** + * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. + * @property {boolean} embedded - Body embed value. + */ + this.embedded = false; + + /** + * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. + * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? + */ + this.collideWorldBounds = false; + + /** + * Set the checkCollision properties to control which directions collision is processed for this Body. + * For example checkCollision.up = false means it won't collide when the collision happened while moving up. + * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. + * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. + * @property {object} checkCollision - An object containing allowed collision (none, up, down, left, right). + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * This object is populated with boolean values when the Body collides with another. + * touching.up = true means the collision happened to the top of this Body for example. + * @property {object} touching - An object containing touching results (none, up, down, left, right). + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with previous touching values from the bodies previous collision. + * @property {object} wasTouching - An object containing previous touching results (none, up, down, left, right). + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with boolean values when the Body collides with the World bounds or a Tile. + * For example if blocked.up is true then the Body cannot move up. + * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any (none, up, down, left, right). + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. + * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. + * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision. + */ + this.tilePadding = new Phaser.Point(); + + /** + * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state? + */ + this.dirty = false; + + /** + * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. + */ + this.skipQuadTree = false; + + /** + * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. + * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. + * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, + * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. + * @property {boolean} syncBounds + * @default + */ + this.syncBounds = false; + + /** + * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods. + */ + this.isMoving = false; + + /** + * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods. + */ + this.stopVelocityOnCollide = true; + + /** + * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveTimer = 0; + + /** + * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDistance = 0; + + /** + * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDuration = 0; + + /** + * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveTarget = null; + + /** + * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveEnd = null; + + /** + * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events. + */ + this.onMoveComplete = new Phaser.Signal(); + + /** + * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. + */ + this.movementCallback = null; + + /** + * @property {object} movementCallbackContext - Context in which to call the movementCallback. + */ + this.movementCallbackContext = null; + + /** + * @property {boolean} _reset - Internal cache var. + * @private + */ + this._reset = true; + + /** + * @property {number} _sx - Internal cache var. + * @private + */ + this._sx = sprite.scale.x; + + /** + * @property {number} _sy - Internal cache var. + * @private + */ + this._sy = sprite.scale.y; + + /** + * @property {number} _dx - Internal cache var. + * @private + */ + this._dx = 0; + + /** + * @property {number} _dy - Internal cache var. + * @private + */ + this._dy = 0; + +}; + +Phaser.Physics.Arcade.Body.prototype = { + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @protected + */ + updateBounds: function () { + + if (this.syncBounds) + { + var b = this.sprite.getBounds(); + b.ceilAll(); + + if (b.width !== this.width || b.height !== this.height) + { + this.width = b.width; + this.height = b.height; + this._reset = true; + } + } + else + { + 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._sx = asx; + this._sy = asy; + this._reset = true; + } + } + + if (this._reset) + { + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.updateCenter(); + } + + }, + + /** + * Update the Body's center from its position. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @protected + */ + updateCenter: function () { + + this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @protected + */ + preUpdate: function () { + + if (!this.enable || this.game.physics.arcade.isPaused) + { + return; + } + + this.dirty = true; + + // Store and reset collision flags + 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.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; + + this.overlapR = 0; + this.overlapX = 0; + this.overlapY = 0; + + this.embedded = false; + + this.updateBounds(); + + this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.updateCenter(); + + this.rotation = this.sprite.angle; + + this.preRotation = this.rotation; + + if (this._reset || this.sprite.fresh) + { + 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; + this.updateCenter(); + + if (this.position.x !== this.prev.x || this.position.y !== this.prev.y) + { + this.angle = this.velocity.atan(); + } + + this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); + + // Now the State update will throw collision checks at the Body + // And finally we'll integrate the new position back to the Sprite in postUpdate + + if (this.collideWorldBounds) + { + if (this.checkWorldBounds() && this.onWorldBounds) + { + this.onWorldBounds.dispatch(this.sprite, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); + } + } + } + + this._dx = this.deltaX(); + this._dy = this.deltaY(); + + this._reset = false; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateMovement + * @protected + */ + updateMovement: function () { + + var percent = 0; + var collided = (this.overlapX !== 0 || this.overlapY !== 0); + + // Duration or Distance based? + + if (this.moveDuration > 0) + { + this.moveTimer += this.game.time.elapsedMS; + + percent = this.moveTimer / this.moveDuration; + } + else + { + this.moveTarget.end.set(this.position.x, this.position.y); + + percent = this.moveTarget.length / this.moveDistance; + } + + if (this.movementCallback) + { + var result = this.movementCallback.call(this.movementCallbackContext, this, this.velocity, percent); + } + + if (collided || percent >= 1 || (result !== undefined && result !== true)) + { + this.stopMovement((percent >= 1) || (this.stopVelocityOnCollide && collided)); + return false; + } + + return true; + + }, + + /** + * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it + * has Body.isMoving true), then calling this method will stop the movement before + * either the duration or distance counters expire. + * + * The `onMoveComplete` signal is dispatched. + * + * @method Phaser.Physics.Arcade.Body#stopMovement + * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero? + */ + stopMovement: function (stopVelocity) { + + if (this.isMoving) + { + this.isMoving = false; + + if (stopVelocity) + { + this.velocity.set(0); + } + + // Send the Sprite this Body belongs to + // and a boolean indicating if it stopped because of a collision or not + this.onMoveComplete.dispatch(this.sprite, (this.overlapX !== 0 || this.overlapY !== 0)); + } + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @protected + */ + postUpdate: function () { + + // Only allow postUpdate to be called once per frame + if (!this.enable || !this.dirty) + { + return; + } + + // Moving? + if (this.isMoving) + { + this.updateMovement(); + } + + this.dirty = false; + + 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.position.x += this._dx; + this.sprite.position.y += this._dy; + this._reset = true; + } + + this.updateCenter(); + + if (this.allowRotation) + { + this.sprite.angle += this.deltaZ(); + } + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @protected + * @return {boolean} True if the Body collided with the world bounds, otherwise false. + */ + checkWorldBounds: function () { + + var pos = this.position; + var bounds = this.game.physics.arcade.bounds; + var check = this.game.physics.arcade.checkCollision; + + var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; + var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; + + if (pos.x < bounds.x && check.left) + { + pos.x = bounds.x; + this.velocity.x *= bx; + this.blocked.left = true; + this.blocked.none = false; + } + else if (this.right > bounds.right && check.right) + { + pos.x = bounds.right - this.width; + this.velocity.x *= bx; + this.blocked.right = true; + this.blocked.none = false; + } + + if (pos.y < bounds.y && check.up) + { + pos.y = bounds.y; + this.velocity.y *= by; + this.blocked.up = true; + this.blocked.none = false; + } + else if (this.bottom > bounds.bottom && check.down) + { + pos.y = bounds.bottom - this.height; + this.velocity.y *= by; + this.blocked.down = true; + this.blocked.none = false; + } + + return !this.blocked.none; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal timer, and then + * monitoring the duration each frame. When the duration is up the movement is + * stopped and the `Body.onMoveComplete` signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * You can optionally set a speed in pixels per second. If not specified it + * will use the current `Body.speed` value. If this is zero, the function will return false. + * + * Please note that due to browser timings you should allow for a variance in + * when the duration will actually expire. Depending on system it may be as much as + * +- 50ms. Also this method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveFrom + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveFrom: function (duration, speed, direction) { + + if (speed === undefined) { speed = this.speed; } + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + this.moveTimer = 0; + this.moveDuration = duration; + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal distance counter. + * The distance is monitored each frame. When the distance equals the distance + * specified in this call, the movement is stopped, and the `Body.onMoveComplete` + * signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * Please note that due to browser timings you should allow for a variance in + * when the distance will actually expire. + * + * Note: This method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveTo + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} distance - The distance, in pixels, the Body will move. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveTo: function (duration, distance, direction) { + + var speed = distance / (duration / 1000); + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + distance = Math.abs(distance); + + this.moveDuration = 0; + this.moveDistance = distance; + + if (this.moveTarget === null) + { + this.moveTarget = new Phaser.Line(); + this.moveEnd = new Phaser.Point(); + } + + this.moveTarget.fromAngle(this.x, this.y, angle, distance); + + this.moveEnd.set(this.moveTarget.end.x, this.moveTarget.end.y); + + this.moveTarget.setTo(this.x, this.y, this.x, this.y); + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * You can modify the size of the physics Body to be any dimension you need. + * This allows you to make it smaller, or larger, than the parent Sprite. You + * can also control the x and y offset of the Body. + * + * The width, height, and offset arguments are relative to the Sprite + * _texture_ and are scaled with the Sprite's {@link Phaser.Sprite#scale} + * (but **not** the scale of any ancestors or the {@link Phaser.Camera#scale + * Camera scale}). + * + * For example: If you have a Sprite with a texture that is 80x100 in size, + * and you want the physics body to be 32x32 pixels in the middle of the + * texture, you would do: + * + * `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, + * 34)` + * + * Where the first two parameters are the new Body size (32x32 pixels) + * relative to the Sprite's scale. 24 is the horizontal offset of the Body + * from the top-left of the Sprites texture, and 34 is the vertical offset. + * + * If you've scaled a Sprite by altering its `width`, `height`, or `scale` + * and you want to position the Body relative to the Sprite's dimensions + * (which will differ from its texture's dimensions), you should divide these + * arguments by the Sprite's current scale: + * + * `setSize(32 / sprite.scale.x, 32 / sprite.scale.y)` + * + * Calling `setSize` on a Body that has already had `setCircle` will reset + * all of the Circle properties, making this Body rectangular again. + * @method Phaser.Physics.Arcade.Body#setSize + * @param {number} width - The width of the Body, relative to the Sprite's + * texture. + * @param {number} height - The height of the Body, relative to the Sprite's + * texture. + * @param {number} [offsetX] - The X offset of the Body from the left of the + * Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the + * Sprite's texture. + */ + setSize: function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { 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.updateCenter(); + + this.isCircle = false; + this.radius = 0; + + }, + + /** + * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. + * The radius is given in pixels (relative to the Sprite's _texture_) and is the distance from the center of the circle to the edge. + * + * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite's texture. + * + * To change a Body back to being rectangular again call `Body.setSize`. + * + * Note: Circular collision only happens with other Arcade Physics bodies, it does not + * work against tile maps, where rectangular collision is the only method supported. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. + * @param {number} [offsetX] - The X offset of the Body from the left of the Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the Sprite's texture. + */ + setCircle: function (radius, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.isCircle = true; + this.radius = radius; + + this.sourceWidth = radius * 2; + this.sourceHeight = radius * 2; + + 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.updateCenter(); + } + else + { + this.isCircle = false; + } + + }, + + /** + * Resets all Body values (velocity, acceleration, rotation, etc) + * + * @method Phaser.Physics.Arcade.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new y position of the Body. + */ + reset: function (x, y) { + + this.stop(); + + this.position.x = (x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + this.rotation = this.sprite.angle; + this.preRotation = this.rotation; + + this.updateBounds(); + + this.updateCenter(); + + }, + + /** + * Sets acceleration, velocity, and {@link #speed} to 0. + * + * @method Phaser.Physics.Arcade.Body#stop + */ + stop: function () { + + this.velocity.set(0); + this.acceleration.set(0); + this.speed = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + + }, + + /** + * Returns the bounds of this physics body. + * + * Only used internally by the World collision methods. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @param {object} obj - The object in which to set the bounds values. + * @return {object} The object that was given to this method. + */ + getBounds: function (obj) { + + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + + }, + + /** + * Tests if a world point lies within this Body. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @param {number} x - The world x coordinate to test. + * @param {number} y - The world y coordinate to test. + * @return {boolean} True if the given coordinates are inside this Body, otherwise false. + */ + hitTest: function (x, y) { + + return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Returns true if the bottom of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onFloor: function () { + + return this.blocked.down; + + }, + + /** + * Returns true if the top of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onCeiling: function(){ + + return this.blocked.up; + + }, + + /** + * Returns true if either side of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onWall: function () { + + return (this.blocked.left || this.blocked.right); + + }, + + /** + * Returns the absolute delta x value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @return {number} The absolute delta value. + */ + deltaAbsX: function () { + + return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); + + }, + + /** + * Returns the absolute delta y value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @return {number} The absolute delta value. + */ + deltaAbsY: function () { + + return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); + + }, + + /** + * Returns the delta x value. The difference between Body.x now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. + */ + deltaX: function () { + + return this.position.x - this.prev.x; + + }, + + /** + * Returns the delta y value. The difference between Body.y now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. + */ + deltaY: function () { + + return this.position.y - this.prev.y; + + }, + + /** + * Returns the delta z value. The difference between Body.rotation now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise. + */ + deltaZ: function () { + + return this.rotation - this.preRotation; + + }, + + /** + * Destroys this Body. + * + * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. + * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. + * + * @method Phaser.Physics.Arcade.Body#destroy + */ + destroy: function () { + + if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group) + { + this.sprite.parent.removeFromHash(this.sprite); + } + + this.sprite.body = null; + this.sprite = null; + + } + +}; + +/** +* @name Phaser.Physics.Arcade.Body#left +* @property {number} left - The x position of the Body. The same as `Body.x`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "left", { + + get: function () { + + return this.position.x; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#right +* @property {number} right - The right value of this Body (same as Body.x + Body.width) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", { + + get: function () { + + return this.position.x + this.width; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#top +* @property {number} top - The y position of the Body. The same as `Body.y`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "top", { + + get: function () { + + return this.position.y; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#bottom +* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", { + + get: function () { + + return this.position.y + this.height; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#x +* @property {number} x - The x position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#y +* @property {number} y - The y position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + +}); + +/** +* Render Sprite Body. +* +* @method Phaser.Physics.Arcade.Body#render +* @param {object} context - The context to render to. +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string). +* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) +* @param {number} [lineWidth=1] - The width of the stroke when unfilled. +*/ +Phaser.Physics.Arcade.Body.render = function (context, body, color, filled, lineWidth) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0,255,0,0.4)'; + + context.fillStyle = color; + context.strokeStyle = color; + context.lineWidth = lineWidth || 1; + + if (body.isCircle) + { + context.beginPath(); + context.arc(body.center.x - body.game.camera.x, body.center.y - body.game.camera.y, body.halfWidth, 0, 2 * Math.PI); + + if (filled) + { + context.fill(); + } + else + { + context.stroke(); + } + } + else + { + if (filled) + { + context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + else + { + context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + } + +}; + +/** +* Render Sprite Body Physics Data as text. +* +* @method Phaser.Physics.Arcade.Body#renderBodyInfo +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {number} x - X position of the debug info to be rendered. +* @param {number} y - Y position of the debug info to be rendered. +* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). +*/ +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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics Tile map collision methods. +* +* @class Phaser.Physics.Arcade.TilemapCollision +* @constructor +*/ +Phaser.Physics.Arcade.TilemapCollision = function () {}; + +Phaser.Physics.Arcade.TilemapCollision.prototype = { + + /** + * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling. + */ + TILE_BIAS: 16, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!sprite.body) + { + return; + } + + var mapData = tilemapLayer.getTiles( + sprite.body.position.x - sprite.body.tilePadding.x - tilemapLayer.getTileOffsetX(), + sprite.body.position.y - sprite.body.tilePadding.y - tilemapLayer.getTileOffsetY(), + sprite.body.width + sprite.body.tilePadding.x, + sprite.body.height + sprite.body.tilePadding.y, + false, false); + + if (mapData.length === 0) + { + return; + } + + for (var i = 0; i < mapData.length; i++) + { + if (processCallback) + { + if (processCallback.call(callbackContext, sprite, mapData[i])) + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + else + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @private + * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer + * @param {Phaser.Group} group - The Group to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.children.length; i++) + { + if (group.children[i].exists) + { + this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * The core separation function to separate a physics body and a tile. + * + * @private + * @method Phaser.Physics.Arcade#separateTile + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to collide against. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {boolean} Returns true if the body was separated, otherwise false. + */ + separateTile: function (i, body, tile, tilemapLayer, overlapOnly) { + + if (!body.enable) + { + return false; + } + + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + // We re-check for collision in case body was separated in a previous step + if (!tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + // no collision so bail out (separated in a previous step) + return false; + } + else if (overlapOnly) + { + // There is an overlap, and we don't need to separate. Bail. + return true; + } + + // They overlap. Any custom callbacks? + + // A local callback always takes priority over a layer level callback + if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + else if (typeof tile.layer.callbacks !== 'undefined' && tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + + // We don't need to go any further if this tile doesn't actually separate + if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom) + { + // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation + return false; + } + + var ox = 0; + var oy = 0; + var minX = 0; + var minY = 1; + + if (body.deltaAbsX() > body.deltaAbsY()) + { + // Moving faster horizontally, check X axis first + minX = -1; + } + else if (body.deltaAbsX() < body.deltaAbsY()) + { + // Moving faster vertically, check Y axis first + minY = -1; + } + + if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom)) + { + // We only need do this if both axis have checking faces AND we're moving in both directions + minX = Math.min(Math.abs((body.position.x - tilemapLayerOffsetX) - tile.right), Math.abs((body.right - tilemapLayerOffsetX) - tile.left)); + minY = Math.min(Math.abs((body.position.y - tilemapLayerOffsetY) - tile.bottom), Math.abs((body.bottom - tilemapLayerOffsetY) - tile.top)); + } + + if (minX < minY) + { + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + + // That's horizontal done, check if we still intersects? If not then we can return now + if (ox !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + } + } + else + { + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + + // That's vertical done, check if we still intersects? If not then we can return now + if (oy !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + } + } + + return (ox !== 0 || oy !== 0); + + }, + + /** + * Check the body against the given tile on the X axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckX: function (body, tile, tilemapLayer) { + + var ox = 0; + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + + if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left) + { + // Body is moving LEFT + if (tile.faceRight && (body.x - tilemapLayerOffsetX) < tile.right) + { + ox = (body.x - tilemapLayerOffsetX) - tile.right; + + if (ox < -this.TILE_BIAS) + { + ox = 0; + } + } + } + else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right) + { + // Body is moving RIGHT + if (tile.faceLeft && (body.right - tilemapLayerOffsetX) > tile.left) + { + ox = (body.right - tilemapLayerOffsetX) - tile.left; + + if (ox > this.TILE_BIAS) + { + ox = 0; + } + } + } + + if (ox !== 0) + { + if (body.customSeparateX) + { + body.overlapX = ox; + } + else + { + this.processTileSeparationX(body, ox); + } + } + + return ox; + + }, + + /** + * Check the body against the given tile on the Y axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckY: function (body, tile, tilemapLayer) { + + var oy = 0; + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up) + { + // Body is moving UP + if (tile.faceBottom && (body.y - tilemapLayerOffsetY) < tile.bottom) + { + oy = (body.y - tilemapLayerOffsetY) - tile.bottom; + + if (oy < -this.TILE_BIAS) + { + oy = 0; + } + } + } + else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down) + { + // Body is moving DOWN + if (tile.faceTop && (body.bottom - tilemapLayerOffsetY) > tile.top) + { + oy = (body.bottom - tilemapLayerOffsetY) - tile.top; + + if (oy > this.TILE_BIAS) + { + oy = 0; + } + } + } + + if (oy !== 0) + { + if (body.customSeparateY) + { + body.overlapY = oy; + } + else + { + this.processTileSeparationY(body, oy); + } + } + + return oy; + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} x - The x separation amount. + */ + processTileSeparationX: function (body, x) { + + if (x < 0) + { + body.blocked.left = true; + body.blocked.none = false; + } + else if (x > 0) + { + body.blocked.right = true; + body.blocked.none = false; + } + + body.position.x -= x; + + if (body.bounce.x === 0) + { + body.velocity.x = 0; + } + else + { + body.velocity.x = -body.velocity.x * body.bounce.x; + } + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} y - The y separation amount. + */ + processTileSeparationY: function (body, y) { + + if (y < 0) + { + body.blocked.up = true; + body.blocked.none = false; + } + else if (y > 0) + { + body.blocked.down = true; + body.blocked.none = false; + } + + body.position.y -= y; + + if (body.bounce.y === 0) + { + body.velocity.y = 0; + } + else + { + body.velocity.y = -body.velocity.y * body.bounce.y; + } + + } + +}; + +// Merge this with the Arcade Physics prototype +Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Add an extra properties to p2 that we need +p2.Body.prototype.parent = null; +p2.Spring.prototype.parent = null; + +/** +* This is your main access to the P2 Physics World. +* From here you can create materials, listen for events and add bodies into the physics simulation. +* +* @class Phaser.Physics.P2 +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {object} [config] - Physics configuration object passed in from the game constructor. +*/ +Phaser.Physics.P2 = function (game, config) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + if (config === undefined) + { + config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; + } + else + { + if (!config.hasOwnProperty('gravity')) + { + config.gravity = [0, 0]; + } + + if (!config.hasOwnProperty('broadphase')) + { + config.broadphase = new p2.SAPBroadphase(); + } + } + + /** + * @property {object} config - The p2 World configuration object. + * @protected + */ + this.config = config; + + /** + * @property {p2.World} world - The p2 World in which the simulation is run. + * @protected + */ + this.world = new p2.World(this.config); + + /** + * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. + * @default + */ + this.frameRate = 1 / 60; + + /** + * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. + * @default + */ + this.useElapsedTime = false; + + /** + * @property {boolean} paused - The paused state of the P2 World. + * @default + */ + this.paused = false; + + /** + * @property {array} materials - A local array of all created Materials. + * @protected + */ + this.materials = []; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. + */ + this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); + + /** + * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * This signal is dispatched when a new Body is added to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world. + * + * @property {Phaser.Signal} onBodyAdded + */ + this.onBodyAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Body is removed to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world. + * + * @property {Phaser.Signal} onBodyRemoved + */ + this.onBodyRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is added to the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world. + * + * @property {Phaser.Signal} onSpringAdded + */ + this.onSpringAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is removed from the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world. + * + * @property {Phaser.Signal} onSpringRemoved + */ + this.onSpringRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is added to the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world. + * + * @property {Phaser.Signal} onConstraintAdded + */ + this.onConstraintAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is removed from the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world. + * + * @property {Phaser.Signal} onConstraintRemoved + */ + this.onConstraintRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is added to the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world. + * + * @property {Phaser.Signal} onContactMaterialAdded + */ + this.onContactMaterialAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is removed from the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world. + * + * @property {Phaser.Signal} onContactMaterialRemoved + */ + this.onContactMaterialRemoved = new Phaser.Signal(); + + /** + * @property {function} postBroadphaseCallback - A postBroadphase callback. + */ + this.postBroadphaseCallback = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are fired. + */ + this.callbackContext = null; + + /** + * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done. + * + * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done. + * + * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + // Pixel to meter function overrides + if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) + { + this.mpx = config.mpx; + this.mpxi = config.mpxi; + this.pxm = config.pxm; + this.pxmi = config.pxmi; + } + + // Hook into the World events + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + /** + * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. + */ + this.collisionGroups = []; + + /** + * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. + */ + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. + */ + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. + */ + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + /** + * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. + */ + this.boundsCollidesWith = []; + + /** + * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. + * @private + */ + this._toRemove = []; + + /** + * @property {number} _collisionGroupID - Internal var. + * @private + */ + this._collisionGroupID = 2; + + /** + * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsLeft = true; + + /** + * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsRight = true; + + /** + * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsTop = true; + + /** + * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsBottom = true; + + /** + * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsOwnGroup = false; + + // By default we want everything colliding with everything + this.setBoundsToWorld(true, true, true, true, false); + +}; + +Phaser.Physics.P2.prototype = { + + /** + * This will add a P2 Physics body into the removal list for the next step. + * + * @method Phaser.Physics.P2#removeBodyNextStep + * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. + */ + removeBodyNextStep: function (body) { + + this._toRemove.push(body); + + }, + + /** + * Called at the start of the core update loop. Purges flagged bodies from the world. + * + * @method Phaser.Physics.P2#preUpdate + */ + preUpdate: function () { + + var i = this._toRemove.length; + + while (i--) + { + this.removeBody(this._toRemove[i]); + } + + this._toRemove.length = 0; + + }, + + /** + * This will create a P2 Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. + * + * @method Phaser.Physics.P2#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [debug=false] - Create a debug object to go with this body? + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, debug, children) { + + if (debug === undefined) { debug = false; } + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + this.enable(object[i].children, debug, children); + } + else + { + this.enableBody(object[i], debug); + + if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) + { + this.enable(object[i], debug, true); + } + } + } + } + else + { + if (object instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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); + } + } + } + + }, + + /** + * Creates a P2 Physics body on the given game object. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * @method Phaser.Physics.P2#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + * @param {boolean} debug - Create a debug object to go with this body? + */ + 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; + if (typeof object.anchor !== 'undefined') { + object.anchor.set(0.5); + } + } + + }, + + /** + * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. + * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. + * + * @method Phaser.Physics.P2#setImpactEvents + * @param {boolean} state - Set to true to enable impact events, or false to disable. + */ + setImpactEvents: function (state) { + + if (state) + { + this.world.on("impact", this.impactHandler, this); + } + else + { + this.world.off("impact", this.impactHandler, this); + } + + }, + + /** + * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. + * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. + * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. + * Returning `true` from the callback will ensure they are checked in the narrowphase. + * + * @method Phaser.Physics.P2#setPostBroadphaseCallback + * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. + * @param {object} context - The context under which the callback will be fired. + */ + 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); + } + + }, + + /** + * Internal handler for the postBroadphase event. + * + * @method Phaser.Physics.P2#postBroadphaseHandler + * @private + * @param {object} event - The event data. + */ + postBroadphaseHandler: function (event) { + + if (!this.postBroadphaseCallback || event.pairs.length === 0) + { + return; + } + + for (var i = event.pairs.length - 2; i >= 0; 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); + } + } + + }, + + /** + * Handles a p2 impact event. + * + * @method Phaser.Physics.P2#impactHandler + * @private + * @param {object} event - The event data. + */ + impactHandler: function (event) { + + if (event.bodyA.parent && event.bodyB.parent) + { + // Body vs. Body callbacks + 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); + } + + // Body vs. Group callbacks + 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); + } + } + + }, + + /** + * Handles a p2 begin contact event. + * + * @method Phaser.Physics.P2#beginContactHandler + * @param {object} event - The event data. + */ + beginContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + 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.bodyB, event.shapeA, event.shapeB, event.contactEquations); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations); + } + } + + }, + + /** + * Handles a p2 end contact event. + * + * @method Phaser.Physics.P2#endContactHandler + * @param {object} event - The event data. + */ + endContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); + + if (event.bodyA.parent) + { + event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA); + } + } + + }, + + /** + * Sets the bounds of the Physics world to match the Game.World dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * + * @method Phaser.Physics#setBoundsToWorld + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + 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); + + }, + + /** + * Sets the given material against the 4 bounds of this World. + * + * @method Phaser.Physics#setWorldMaterial + * @param {Phaser.Physics.P2.Material} material - The material to set. + * @param {boolean} [left=true] - If true will set the material on the left bounds wall. + * @param {boolean} [right=true] - If true will set the material on the right bounds wall. + * @param {boolean} [top=true] - If true will set the material on the top bounds wall. + * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. + */ + setWorldMaterial: function (material, left, right, top, bottom) { + + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (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; + } + + }, + + /** + * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. + * If you start to use your own collision groups then your objects will no longer collide with the bounds. + * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. + * + * @method Phaser.Physics.P2#updateBoundsCollisionGroup + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + updateBoundsCollisionGroup: function (setCollisionGroup) { + + if (setCollisionGroup === undefined) { setCollisionGroup = true; } + + var mask = (setCollisionGroup) ? this.boundsCollisionGroup.mask : this.everythingCollisionGroup.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; + } + + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.P2#setBounds + * @param {number} x - The x coordinate of the top-left corner of the bounds. + * @param {number} y - The y coordinate of the top-left corner of the bounds. + * @param {number} width - The width of the bounds. + * @param {number} height - The height of the bounds. + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { + + if (left === undefined) { left = this._boundsLeft; } + if (right === undefined) { right = this._boundsRight; } + if (top === undefined) { top = this._boundsTop; } + if (bottom === undefined) { bottom = this._boundsBottom; } + if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; } + + this.setupWall(left, 'left', x, y, 1.5707963267948966, setCollisionGroup); + this.setupWall(right, 'right', x + width, y, -1.5707963267948966, setCollisionGroup); + this.setupWall(top, 'top', x, y, -3.141592653589793, setCollisionGroup); + this.setupWall(bottom, 'bottom', x, y + height, 0, setCollisionGroup); + + // Remember the bounds settings in case they change later on via World.setBounds + this._boundsLeft = left; + this._boundsRight = right; + this._boundsTop = top; + this._boundsBottom = bottom; + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Internal method called by setBounds. Responsible for creating, updating or + * removing the wall body shapes. + * + * @method Phaser.Physics.P2#setupWall + * @private + * @param {boolean} create - True to create the wall shape, false to remove it. + * @param {string} wall - The wall segment to update. + * @param {number} x - The x coordinate of the wall. + * @param {number} y - The y coordinate of the wall. + * @param {float} angle - The angle of the wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setupWall: function (create, wall, x, y, angle, setCollisionGroup) { + + if (create) + { + // We need a left wall. Do we have one already? + if (this.walls[wall]) + { + this.walls[wall].position = [ this.pxmi(x), this.pxmi(y) ]; + } + else + { + this.walls[wall] = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: angle }); + this.walls[wall].addShape(new p2.Plane()); + + this.world.addBody(this.walls[wall]); + } + + if (setCollisionGroup) + { + this.walls[wall].shapes[0].collisionGroup = this.boundsCollisionGroup.mask; + } + } + else + { + if (this.walls[wall]) + { + this.world.removeBody(this.walls[wall]); + this.walls[wall] = null; + } + } + + }, + + /** + * Pauses the P2 World independent of the game pause state. + * + * @method Phaser.Physics.P2#pause + */ + pause: function() { + + this.paused = true; + + }, + + /** + * Resumes a paused P2 World. + * + * @method Phaser.Physics.P2#resume + */ + resume: function() { + + this.paused = false; + + }, + + /** + * Internal P2 update loop. + * + * @method Phaser.Physics.P2#update + */ + update: function () { + + // Do nothing if the physics engine was paused before + if (this.paused) + { + return; + } + + if (this.useElapsedTime) + { + this.world.step(this.game.time.physicsElapsed); + } + else + { + this.world.step(this.frameRate); + } + + }, + + /** + * Called by Phaser.Physics when a State swap occurs. + * Starts the begin and end Contact listeners again. + * + * @method Phaser.Physics.P2#reset + */ + reset: function () { + + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + this._collisionGroupID = 2; + + this.setBoundsToWorld(true, true, true, true, false); + + }, + + /** + * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. + * + * The P2 world is also cleared: + * + * * Removes all solver equations + * * Removes all constraints + * * Removes all bodies + * * Removes all springs + * * Removes all contact materials + * + * This is called automatically when you switch state. + * + * @method Phaser.Physics.P2#clear + */ + clear: function () { + + this.world.time = 0; + this.world.fixedStepTime = 0; + + // Remove all solver equations + if (this.world.solver && this.world.solver.equations.length) + { + this.world.solver.removeAllEquations(); + } + + // Remove all constraints + var cs = this.world.constraints; + + for (var i = cs.length - 1; i >= 0; i--) + { + this.world.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.world.bodies; + + for (var i = bodies.length - 1; i >= 0; i--) + { + this.world.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.world.springs; + + for (var i = springs.length - 1; i >= 0; i--) + { + this.world.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.world.contactMaterials; + + for (var i = cms.length - 1; i >= 0; i--) + { + this.world.removeContactMaterial(cms[i]); + } + + 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.boundsCollidesWith = []; + + // Remove the world bounds + this.walls = { left: null, right: null, top: null, bottom: null }; + + }, + + /** + * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. + * + * @method Phaser.Physics.P2#destroy + */ + destroy: function () { + + this.clear(); + + this.game = null; + + }, + + /** + * Add a body to the world. + * + * @method Phaser.Physics.P2#addBody + * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. + * @return {boolean} True if the Body was added successfully, otherwise false. + */ + addBody: function (body) { + + if (body.data.world) + { + return false; + } + else + { + this.world.addBody(body.data); + + this.onBodyAdded.dispatch(body); + + return true; + } + + }, + + /** + * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. + * + * @method Phaser.Physics.P2#removeBody + * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. + * @return {Phaser.Physics.P2.Body} The Body that was removed. + */ + removeBody: function (body) { + + if (body.data.world === this.world) + { + this.world.removeBody(body.data); + + this.onBodyRemoved.dispatch(body); + } + + return body; + + }, + + /** + * Adds a Spring to the world. + * + * @method Phaser.Physics.P2#addSpring + * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was added. + */ + addSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.addSpring(spring.data); + } + else + { + this.world.addSpring(spring); + } + + this.onSpringAdded.dispatch(spring); + + return spring; + + }, + + /** + * Removes a Spring from the world. + * + * @method Phaser.Physics.P2#removeSpring + * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was removed. + */ + removeSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.removeSpring(spring.data); + } + else + { + this.world.removeSpring(spring); + } + + this.onSpringRemoved.dispatch(spring); + + return spring; + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createDistanceConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} distance - The distance to keep between the bodies. + * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. + * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.DistanceConstraint} The constraint + */ + createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, 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, localAnchorA, localAnchorB, maxForce)); + } + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createGearConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [angle=0] - The relative angle + * @param {number} [ratio=1] - The gear ratio. + * @return {Phaser.Physics.P2.GearConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * The pivot points are given in world (pixel) coordinates. + * + * @method Phaser.Physics.P2#createRevoluteConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. + * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint + */ + createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + 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, worldPivot)); + } + + }, + + /** + * Locks the relative position between two bodies. + * + * @method Phaser.Physics.P2#createLockConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.LockConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Constraint that only allows bodies to move along a line, relative to each other. + * See http://www.iforce2d.net/b2dtut/joints-prismatic + * + * @method Phaser.Physics.P2#createPrismaticConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. + * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Adds a Constraint to the world. + * + * @method Phaser.Physics.P2#addConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. + */ + addConstraint: function (constraint) { + + this.world.addConstraint(constraint); + + this.onConstraintAdded.dispatch(constraint); + + return constraint; + + }, + + /** + * Removes a Constraint from the world. + * + * @method Phaser.Physics.P2#removeConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. + */ + removeConstraint: function (constraint) { + + this.world.removeConstraint(constraint); + + this.onConstraintRemoved.dispatch(constraint); + + return constraint; + + }, + + /** + * Adds a Contact Material to the world. + * + * @method Phaser.Physics.P2#addContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. + */ + addContactMaterial: function (material) { + + this.world.addContactMaterial(material); + + this.onContactMaterialAdded.dispatch(material); + + return material; + + }, + + /** + * Removes a Contact Material from the world. + * + * @method Phaser.Physics.P2#removeContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. + */ + removeContactMaterial: function (material) { + + this.world.removeContactMaterial(material); + + this.onContactMaterialRemoved.dispatch(material); + + return material; + + }, + + /** + * Gets a Contact Material based on the two given Materials. + * + * @method Phaser.Physics.P2#getContactMaterial + * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. + * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. + * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. + */ + getContactMaterial: function (materialA, materialB) { + + return this.world.getContactMaterial(materialA, materialB); + + }, + + /** + * Sets the given Material against all Shapes owned by all the Bodies in the given array. + * + * @method Phaser.Physics.P2#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. + * @param {array} bodies - An Array of Body objects that the given Material will be set on. + */ + setMaterial: function (material, bodies) { + + var i = bodies.length; + + while (i--) + { + bodies[i].setMaterial(material); + } + + }, + + /** + * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). + * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. + * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. + * + * @method Phaser.Physics.P2#createMaterial + * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. + * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. + * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. + */ + 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; + + }, + + /** + * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. + * + * @method Phaser.Physics.P2#createContactMaterial + * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {object} [options] - Material options object. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. + */ + createContactMaterial: function (materialA, materialB, options) { + + if (materialA === undefined) { materialA = this.createMaterial(); } + if (materialB === undefined) { materialB = this.createMaterial(); } + + var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); + + return this.addContactMaterial(contact); + + }, + + /** + * Populates and returns an array with references to of all current Bodies in the world. + * + * @method Phaser.Physics.P2#getBodies + * @return {array} An array containing all current Bodies in the world. + */ + getBodies: function () { + + var output = []; + var i = this.world.bodies.length; + + while (i--) + { + output.push(this.world.bodies[i].parent); + } + + return output; + + }, + + /** + * Checks the given object to see if it has a p2.Body and if so returns it. + * + * @method Phaser.Physics.P2#getBody + * @param {object} object - The object to check for a p2.Body on. + * @return {p2.Body} The p2.Body, or null if not found. + */ + getBody: function (object) { + + if (object instanceof p2.Body) + { + // Native p2 body + return object; + } + else if (object instanceof Phaser.Physics.P2.Body) + { + // Phaser P2 Body + return object.data; + } + else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) + { + // Sprite, TileSprite, etc + return object.body.data; + } + + return null; + + }, + + /** + * Populates and returns an array of all current Springs in the world. + * + * @method Phaser.Physics.P2#getSprings + * @return {array} An array containing all current Springs in the world. + */ + getSprings: function () { + + var output = []; + var i = this.world.springs.length; + + while (i--) + { + output.push(this.world.springs[i].parent); + } + + return output; + + }, + + /** + * Populates and returns an array of all current Constraints in the world. + * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain + * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type. + * + * @method Phaser.Physics.P2#getConstraints + * @return {array} An array containing all current Constraints in the world. + */ + getConstraints: function () { + + var output = []; + var i = this.world.constraints.length; + + while (i--) + { + output.push(this.world.constraints[i]); + } + + return output; + + }, + + /** + * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to + * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. + * + * @method Phaser.Physics.P2#hitTest + * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. + * @param {Array} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) + * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. + * @return {Array} Array of bodies that overlap the point. + */ + hitTest: function (worldPoint, bodies, precision, filterStatic) { + + if (bodies === undefined) { bodies = this.world.bodies; } + if (precision === undefined) { precision = 5; } + if (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.type === p2.Body.STATIC)) + { + query.push(bodies[i].data); + } + else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC)) + { + query.push(bodies[i]); + } + else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC)) + { + query.push(bodies[i].body.data); + } + } + + return this.world.hitTest(physicsPosition, query, precision); + + }, + + /** + * Converts the current world into a JSON object. + * + * @method Phaser.Physics.P2#toJSON + * @return {object} A JSON representation of the world. + */ + toJSON: function () { + + return this.world.toJSON(); + + }, + + /** + * Creates a new Collision Group and optionally applies it to the given object. + * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. + * + * @method Phaser.Physics.P2#createCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + */ + 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; + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. + * + * @method Phaser.Physics.P2y#setCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + */ + setCollisionGroup: function (object, group) { + + if (object instanceof Phaser.Group) + { + for (var i = 0; i < object.total; i++) + { + if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) + { + object.children[i].body.setCollisionGroup(group); + } + } + } + else + { + object.body.setCollisionGroup(group); + } + + }, + + /** + * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restLength=1] - Rest length of the spring. A number > 0. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @return {Phaser.Physics.P2.Spring} The spring + */ + createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); + } + + }, + + /** + * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createRotationalSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @return {Phaser.Physics.P2.RotationalSpring} The spring + */ + createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Rotational Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping)); + } + + }, + + /** + * Creates a new Body and adds it to the World. + * + * @method Phaser.Physics.P2#createBody + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {Phaser.Physics.P2.Body} The body + */ + createBody: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Creates a new Particle and adds it to the World. + * + * @method Phaser.Physics.P2#createParticle + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + */ + createParticle: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Converts all of the polyline, polygon, and rectangle objects inside a Tiled ObjectGroup into physics bodies that are added to the world. + * Note that the polylines and polygons must be created in such a way that they can withstand polygon decomposition. + * + * @method Phaser.Physics.P2#convertCollisionObjects + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. + * @return {array} An array of the Phaser.Physics.Body objects that have been created. + */ + convertCollisionObjects: function (map, layer, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var output = []; + + for (var i = 0, len = map.collision[layer].length; i < len; i++) + { + // name: json.layers[i].objects[v].name, + // x: json.layers[i].objects[v].x, + // y: json.layers[i].objects[v].y, + // width: json.layers[i].objects[v].width, + // height: json.layers[i].objects[v].height, + // visible: json.layers[i].objects[v].visible, + // properties: json.layers[i].objects[v].properties, + // polyline: json.layers[i].objects[v].polyline + + var object = map.collision[layer][i]; + var shapeData = object.polyline || object.polygon; + + // polyline/polygon shape data present + if (shapeData) + { + var body = this.createBody(object.x, object.y, 0, addToWorld, {}, shapeData); + } + + // tilemap parser sets rectangle=true when parsing object groups + else if (object.rectangle) + { + var body = this.createBody(object.x, object.y, 0, addToWorld); + body.addRectangle(object.width, object.height, object.width / 2, object.height / 2); + } + + // ellipse could be added here, but Tiled ellipses use height/width instead of radius + // (to support oblong ellipses), which p2 doesn't currently support. + + if (body) + { + output.push(body); + } + } + + return output; + + }, + + /** + * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. + * + * @method Phaser.Physics.P2#clearTilemapLayerBodies + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + */ + 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 = 0; + + }, + + /** + * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. + * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. + * Every time you call this method it will destroy any previously created bodies and remove them from the world. + * Therefore understand it's a very expensive operation and not to be done in a core game update loop. + * + * @method Phaser.Physics.P2#convertTilemap + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. + * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. + * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. + */ + convertTilemap: function (map, layer, addToWorld, optimize) { + + layer = map.getLayer(layer); + + if (addToWorld === undefined) { addToWorld = true; } + if (optimize === undefined) { optimize = true; } + + // If the bodies array is already populated we need to nuke it + this.clearTilemapLayerBodies(map, layer); + + var width = 0; + var sx = 0; + var sy = 0; + + for (var y = 0, h = map.layers[layer].height; y < h; y++) + { + width = 0; + + for (var x = 0, w = map.layers[layer].width; x < w; x++) + { + var tile = map.layers[layer].data[y][x]; + + if (tile && tile.index > -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; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpx + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpx: function (v) { + + return v *= 20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters). + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxm + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxm: function (v) { + + return v * 0.05; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpxi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpxi: function (v) { + + return v *= -20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters) and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxmi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxmi: function (v) { + + return v * -0.05; + + } + +}; + +/** +* @name Phaser.Physics.P2#friction +* @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { + + get: function () { + + return this.world.defaultContactMaterial.friction; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.friction = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#restitution +* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { + + get: function () { + + return this.world.defaultContactMaterial.restitution; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.restitution = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#contactMaterial +* @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { + + get: function () { + + return this.world.defaultContactMaterial; + + }, + + set: function (value) { + + this.world.defaultContactMaterial = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applySpringForces +* @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { + + get: function () { + + return this.world.applySpringForces; + + }, + + set: function (value) { + + this.world.applySpringForces = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyDamping +* @property {boolean} applyDamping - Enable to automatically apply body damping each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { + + get: function () { + + return this.world.applyDamping; + + }, + + set: function (value) { + + this.world.applyDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyGravity +* @property {boolean} applyGravity - Enable to automatically apply gravity each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { + + get: function () { + + return this.world.applyGravity; + + }, + + set: function (value) { + + this.world.applyGravity = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#solveConstraints +* @property {boolean} solveConstraints - Enable/disable constraint solving in each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { + + get: function () { + + return this.world.solveConstraints; + + }, + + set: function (value) { + + this.world.solveConstraints = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#time +* @property {boolean} time - The World time. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "time", { + + get: function () { + + return this.world.time; + + } + +}); + +/** +* @name Phaser.Physics.P2#emitImpactEvent +* @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { + + get: function () { + + return this.world.emitImpactEvent; + + }, + + set: function (value) { + + this.world.emitImpactEvent = value; + + } + +}); + +/** +* How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. +* If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. +* @name Phaser.Physics.P2#sleepMode +* @property {number} sleepMode +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", { + + get: function () { + + return this.world.sleepMode; + + }, + + set: function (value) { + + this.world.sleepMode = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#total +* @property {number} total - The total number of bodies in the world. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "total", { + + get: function () { + + return this.world.bodies.length; + + } + +}); + +/* jshint noarg: false */ + +/** +* @author Georgios Kaleadis https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Allow to access a list of created fixture (coming from Body#addPhaserPolygon) +* which itself parse the input from PhysicsEditor with the custom phaser exporter. +* You can access fixtures of a Body by a group index or even by providing a fixture Key. + +* You can set the fixture key and also the group index for a fixture in PhysicsEditor. +* This gives you the power to create a complex body built of many fixtures and modify them +* during runtime (to remove parts, set masks, categories & sensor properties) +* +* @class Phaser.Physics.P2.FixtureList +* @constructor +* @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) +*/ +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 = { + + /** + * @method Phaser.Physics.P2.FixtureList#init + */ + init: function () { + + /** + * @property {object} namedFixtures - Collect all fixtures with a key + * @private + */ + this.namedFixtures = {}; + + /** + * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group + * @private + */ + this.groupedFixtures = []; + + /** + * @property {Array} allFixtures - This is a list of everything in this collection + * @private + */ + this.allFixtures = []; + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setCategory + * @param {number} bit - The bit to set as the collision group. + * @param {string} fixtureKey - Only apply to the fixture with the given key. + */ + setCategory: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionGroup = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMask + * @param {number} bit - The bit to set as the collision mask + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMask: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionMask = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setSensor + * @param {boolean} value - sensor true or false + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setSensor: function (value, fixtureKey) { + + var setter = function(fixture) { + fixture.sensor = value; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMaterial + * @param {Object} material - The contact material for a fixture + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMaterial: function (material, fixtureKey) { + + var setter = function(fixture) { + fixture.material = material; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * Accessor to get either a list of specified fixtures by key or the whole fixture list + * + * @method Phaser.Physics.P2.FixtureList#getFixtures + * @param {array} keys - A list of fixture keys + */ + 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; + } + + }, + + /** + * Accessor to get either a single fixture by its key. + * + * @method Phaser.Physics.P2.FixtureList#getFixtureByKey + * @param {string} key - The key of the fixture. + */ + getFixtureByKey: function (key) { + + return this.namedFixtures[key]; + + }, + + /** + * Accessor to get a group of fixtures by its group index. + * + * @method Phaser.Physics.P2.FixtureList#getGroup + * @param {number} groupID - The group index. + */ + getGroup: function (groupID) { + + return this.groupedFixtures[groupID]; + + }, + + /** + * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon + * + * @method Phaser.Physics.P2.FixtureList#parse + */ + 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)); + } + + }, + + /** + * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. + * + * @method Phaser.Physics.P2.FixtureList#flatten + * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. + */ + 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; + + } + +}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. +* +* @class Phaser.Physics.P2.PointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.PointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; + +/** +* @name Phaser.Physics.P2.PointProxy#x +* @property {number} x - The x property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { + + get: function () { + + return this.world.mpx(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#y +* @property {number} y - The y property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { + + get: function () { + + return this.world.mpx(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#mx +* @property {number} mx - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#my +* @property {number} my - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. +* +* @class Phaser.Physics.P2.InversePointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.InversePointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; + +/** +* @name Phaser.Physics.P2.InversePointProxy#x +* @property {number} x - The x property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#y +* @property {number} y - The y property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#mx +* @property {number} mx - The x property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = -value; + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#my +* @property {number} my - The y property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = -value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. +* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. +* In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. +* By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. +* Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. +* Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. +* +* @class Phaser.Physics.P2.Body +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. +* @param {number} [x=0] - The x coordinate of this Body. +* @param {number} [y=0] - The y coordinate of this Body. +* @param {number} [mass=1] - The default mass of this Body (0 = static). +*/ +Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { + + sprite = sprite || null; + x = x || 0; + y = y || 0; + if (mass === undefined) { mass = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to the P2 World. + */ + this.world = game.physics.p2; + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.P2JS; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. + */ + this.offset = new Phaser.Point(); + + /** + * @property {p2.Body} data - The p2 Body data. + * @protected + */ + this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); + + this.data.parent = this; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. + */ + this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); + + /** + * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body. + */ + this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); + + /** + * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. + */ + this.gravity = new Phaser.Point(); + + /** + * Dispatched when a first contact is created between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 5 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body is in contact with. + * The Shape from this body that caused the contact. + * The Shape from the contact body. + * The Contact Equation data array. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * Dispatched when contact ends between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 4 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body has ended contact with. + * The Shape from this body that caused the original contact. + * The Shape from the contact body. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + /** + * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. + */ + this.collidesWith = []; + + /** + * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. + */ + this.removeNextStep = false; + + /** + * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. + */ + this.debugBody = null; + + /** + * @property {boolean} dirty - Internally used by Sprite.x/y + */ + this.dirty = false; + + /** + * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. + * @private + */ + this._collideWorldBounds = true; + + /** + * @property {object} _bodyCallbacks - Array of Body callbacks. + * @private + */ + this._bodyCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Body callback contexts. + * @private + */ + this._bodyCallbackContext = {}; + + /** + * @property {object} _groupCallbacks - Array of Group callbacks. + * @private + */ + this._groupCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. + * @private + */ + this._groupCallbackContext = {}; + + /** + * @property {boolean} _reset - Internal var. + * @private + */ + this._reset = false; + + // Set-up the default shape + if (sprite) + { + this.setRectangleFromSprite(sprite); + + if (sprite.exists) + { + this.game.physics.p2.addBody(this); + } + } + +}; + +Phaser.Physics.P2.Body.prototype = { + + /** + * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createBodyCallback + * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + 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; + } + } + + }, + + /** + * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * This callback will only fire if this Body has been assigned a collision group. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createGroupCallback + * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + createGroupCallback: function (group, callback, callbackContext) { + + if (callback === null) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + else + { + this._groupCallbacks[group.mask] = callback; + this._groupCallbackContext[group.mask] = callbackContext; + } + + }, + + /** + * Gets the collision bitmask from the groups this body collides with. + * + * @method Phaser.Physics.P2.Body#getCollisionMask + * @return {number} The bitmask. + */ + getCollisionMask: function () { + + var mask = 0; + + if (this._collideWorldBounds) + { + mask = this.game.physics.p2.boundsCollisionGroup.mask; + } + + for (var i = 0; i < this.collidesWith.length; i++) + { + mask = mask | this.collidesWith[i].mask; + } + + return mask; + + }, + + /** + * Updates the collisionMask. + * + * @method Phaser.Physics.P2.Body#updateCollisionMask + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + updateCollisionMask: function (shape) { + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * This also resets the collisionMask. + * + * @method Phaser.Physics.P2.Body#setCollisionGroup + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + setCollisionGroup: function (group, shape) { + + var mask = this.getCollisionMask(); + + if (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; + } + + }, + + /** + * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. + * + * @method Phaser.Physics.P2.Body#clearCollision + * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? + * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. + */ + clearCollision: function (clearGroup, clearMask, shape) { + + if (clearGroup === undefined) { clearGroup = true; } + if (clearMask === undefined) { clearMask = true; } + + if (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; + } + + }, + + /** + * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#removeCollisionGroup + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore. + * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body. + */ + removeCollisionGroup: function (group, clearCallback, shape) { + + if (clearCallback === undefined) { clearCallback = true; } + + var index; + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + index = this.collidesWith.indexOf(group[i]); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + } + else + { + index = this.collidesWith.indexOf(group); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#collides + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. + * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. + * @param {object} [callbackContext] - The context under which the callback will be called. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. + */ + collides: function (group, callback, callbackContext, shape) { + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + if (this.collidesWith.indexOf(group[i]) === -1) + { + this.collidesWith.push(group[i]); + + if (callback) + { + this.createGroupCallback(group[i], callback, callbackContext); + } + } + } + } + else + { + if (this.collidesWith.indexOf(group) === -1) + { + this.collidesWith.push(group); + + if (callback) + { + this.createGroupCallback(group, callback, callbackContext); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Moves the shape offsets so their center of mass becomes the body center of mass. + * + * @method Phaser.Physics.P2.Body#adjustCenterOfMass + */ + adjustCenterOfMass: function () { + + this.data.adjustCenterOfMass(); + this.shapeChanged(); + + }, + + /** + * Gets the velocity of a point in the body. + * + * @method Phaser.Physics.P2.Body#getVelocityAtPoint + * @param {Array} result - A vector to store the result in. + * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from. + * @return {Array} The result vector. + */ + getVelocityAtPoint: function (result, relativePoint) { + + return this.data.getVelocityAtPoint(result, relativePoint); + + }, + + /** + * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. + * + * @method Phaser.Physics.P2.Body#applyDamping + * @param {number} dt - Current time step. + */ + applyDamping: function (dt) { + + this.data.applyDamping(dt); + + }, + + /** + * Apply impulse to a point relative to the body. + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulse + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space. + * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + */ + applyImpulse: function (impulse, worldX, worldY) { + + this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Apply impulse to a point local to the body. + * + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulseLocal + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space. + * @param {number} localX - A local point on the body. + * @param {number} localY - A local point on the body. + */ + applyImpulseLocal: function (impulse, localX, localY) { + + this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]); + + }, + + /** + * Apply force to a world point. + * + * This could for example be a point on the RigidBody surface. Applying force + * this way will add to Body.force and Body.angularForce. + * + * @method Phaser.Physics.P2.Body#applyForce + * @param {Float32Array|Array} force - The force vector to add. + * @param {number} worldX - The world x point to apply the force on. + * @param {number} worldY - The world y point to apply the force on. + */ + applyForce: function (force, worldX, worldY) { + + this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Sets the force on the body to zero. + * + * @method Phaser.Physics.P2.Body#setZeroForce + */ + setZeroForce: function () { + + this.data.setZeroForce(); + + }, + + /** + * If this Body is dynamic then this will zero its angular velocity. + * + * @method Phaser.Physics.P2.Body#setZeroRotation + */ + setZeroRotation: function () { + + this.data.angularVelocity = 0; + + }, + + /** + * If this Body is dynamic then this will zero its velocity on both axis. + * + * @method Phaser.Physics.P2.Body#setZeroVelocity + */ + setZeroVelocity: function () { + + this.data.velocity[0] = 0; + this.data.velocity[1] = 0; + + }, + + /** + * Sets the Body damping and angularDamping to zero. + * + * @method Phaser.Physics.P2.Body#setZeroDamping + */ + setZeroDamping: function () { + + this.data.damping = 0; + this.data.angularDamping = 0; + + }, + + /** + * Transform a world point to local body frame. + * + * @method Phaser.Physics.P2.Body#toLocalFrame + * @param {Float32Array|Array} out - The vector to store the result in. + * @param {Float32Array|Array} worldPoint - The input world vector. + */ + toLocalFrame: function (out, worldPoint) { + + return this.data.toLocalFrame(out, worldPoint); + + }, + + /** + * Transform a local point to world frame. + * + * @method Phaser.Physics.P2.Body#toWorldFrame + * @param {Array} out - The vector to store the result in. + * @param {Array} localPoint - The input local vector. + */ + toWorldFrame: function (out, localPoint) { + + return this.data.toWorldFrame(out, localPoint); + + }, + + /** + * This will rotate the Body by the given speed to the left (counter-clockwise). + * + * @method Phaser.Physics.P2.Body#rotateLeft + * @param {number} speed - The speed at which it should rotate. + */ + rotateLeft: function (speed) { + + this.data.angularVelocity = this.world.pxm(-speed); + + }, + + /** + * This will rotate the Body by the given speed to the left (clockwise). + * + * @method Phaser.Physics.P2.Body#rotateRight + * @param {number} speed - The speed at which it should rotate. + */ + rotateRight: function (speed) { + + this.data.angularVelocity = this.world.pxm(speed); + + }, + + /** + * Moves the Body forwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveForward + * @param {number} speed - The speed at which it should move forwards. + */ + 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); + + }, + + /** + * Moves the Body backwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveBackward + * @param {number} speed - The speed at which it should move backwards. + */ + 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)); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrust + * @param {number} speed - The speed at which it should thrust. + */ + 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); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustLeft + * @param {number} speed - The speed at which it should move to the left. + */ + thrustLeft: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] += magnitude * Math.cos(angle); + this.data.force[1] += magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustRight + * @param {number} speed - The speed at which it should move to the right. + */ + thrustRight: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] -= magnitude * Math.cos(angle); + this.data.force[1] -= magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#reverse + * @param {number} speed - The speed at which it should reverse. + */ + 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); + + }, + + /** + * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveLeft + * @param {number} speed - The speed at which it should move to the left, in pixels per second. + */ + moveLeft: function (speed) { + + this.data.velocity[0] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveRight + * @param {number} speed - The speed at which it should move to the right, in pixels per second. + */ + moveRight: function (speed) { + + this.data.velocity[0] = this.world.pxmi(speed); + + }, + + /** + * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveUp + * @param {number} speed - The speed at which it should move up, in pixels per second. + */ + moveUp: function (speed) { + + this.data.velocity[1] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveDown + * @param {number} speed - The speed at which it should move down, in pixels per second. + */ + moveDown: function (speed) { + + this.data.velocity[1] = this.world.pxmi(speed); + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#preUpdate + * @protected + */ + preUpdate: function () { + + this.dirty = true; + + if (this.removeNextStep) + { + this.removeFromWorld(); + this.removeNextStep = false; + } + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#postUpdate + * @protected + */ + postUpdate: function () { + + this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x; + this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y; + + if (!this.fixedRotation) + { + this.sprite.rotation = this.data.angle; + } + + if (this.debugBody) + { + this.debugBody.updateSpriteTransform(); + } + + this.dirty = false; + + }, + + /** + * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. + * + * @method Phaser.Physics.P2.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new x position of the Body. + * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. + * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. + */ + reset: function (x, y, resetDamping, resetMass) { + + if (resetDamping === undefined) { resetDamping = false; } + if (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; + + }, + + /** + * Adds this physics body to the world. + * + * @method Phaser.Physics.P2.Body#addToWorld + */ + addToWorld: function () { + + if (this.game.physics.p2._toRemove) + { + for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) + { + if (this.game.physics.p2._toRemove[i] === this) + { + this.game.physics.p2._toRemove.splice(i, 1); + } + } + } + + if (this.data.world !== this.game.physics.p2.world) + { + this.game.physics.p2.addBody(this); + } + + }, + + /** + * Removes this physics body from the world. + * + * @method Phaser.Physics.P2.Body#removeFromWorld + */ + removeFromWorld: function () { + + if (this.data.world === this.game.physics.p2.world) + { + this.game.physics.p2.removeBodyNextStep(this); + } + + }, + + /** + * Destroys this Body and all references it holds to other objects. + * + * @method Phaser.Physics.P2.Body#destroy + */ + destroy: function () { + + this.removeFromWorld(); + + this.clearShapes(); + + this._bodyCallbacks = {}; + this._bodyCallbackContext = {}; + this._groupCallbacks = {}; + this._groupCallbackContext = {}; + + if (this.debugBody) + { + this.debugBody.destroy(true, true); + } + + this.debugBody = null; + + if (this.sprite) + { + this.sprite.body = null; + this.sprite = null; + } + + }, + + /** + * Removes all Shapes from this Body. + * + * @method Phaser.Physics.P2.Body#clearShapes + */ + clearShapes: function () { + + var i = this.data.shapes.length; + + while (i--) + { + this.data.removeShape(this.data.shapes[i]); + } + + this.shapeChanged(); + + }, + + /** + * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#addShape + + * @param {p2.Shape} shape - The shape to add to the body. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Shape} The shape that was added to the body. + */ + addShape: function (shape, offsetX, offsetY, rotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (rotation === undefined) { rotation = 0; } + + this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); + this.shapeChanged(); + + return shape; + + }, + + /** + * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Circle} The Circle shape that was added to the Body. + */ + addCircle: function (radius, offsetX, offsetY, rotation) { + + var shape = new p2.Circle({ radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addRectangle + * @param {number} width - The width of the rectangle in pixels. + * @param {number} height - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Box} The shape that was added to the Body. + */ + addRectangle: function (width, height, offsetX, offsetY, rotation) { + + var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addPlane + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Plane} The Plane shape that was added to the Body. + */ + addPlane: function (offsetX, offsetY, rotation) { + + var shape = new p2.Plane(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addParticle + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Particle} The Particle shape that was added to the Body. + */ + addParticle: function (offsetX, offsetY, rotation) { + + var shape = new p2.Particle(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Line shape to this Body. + * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addLine + * @param {number} length - The length of this line (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Line} The Line shape that was added to the Body. + */ + addLine: function (length, offsetX, offsetY, rotation) { + + var shape = new p2.Line({ length: this.world.pxm(length)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Capsule shape to this Body. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCapsule + * @param {number} length - The distance between the end points in pixels. + * @param {number} radius - Radius of the capsule in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Capsule} The Capsule shape that was added to the Body. + */ + addCapsule: function (length, radius, offsetX, offsetY, rotation) { + + var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. + * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. + * + * @method Phaser.Physics.P2.Body#addPolygon + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...]. In the first form **the array will mutate**. + * Or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {boolean} True on success, else false. + */ + addPolygon: function (options, points) { + + options = options || {}; + + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments, 1); + } + + var path = []; + + // Did they pass in a single array of points? + if (points.length === 1 && Array.isArray(points[0])) + { + path = points[0].slice(0); + } + else if (Array.isArray(points[0])) + { + path = points.slice(); + } + else if (typeof points[0] === 'number') + { + // We've a list of numbers + for (var i = 0, len = points.length; i < len; i += 2) + { + path.push([points[i], points[i + 1]]); + } + } + + // top and tail + var idx = path.length - 1; + + if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) + { + path.pop(); + } + + // Now process them into p2 values + for (var p = 0; p < path.length; p++) + { + path[p][0] = this.world.pxmi(path[p][0]); + path[p][1] = this.world.pxmi(path[p][1]); + } + + var result = this.data.fromPolygon(path, options); + + this.shapeChanged(); + + return result; + + }, + + /** + * Remove a shape from the body. Will automatically update the mass properties and bounding radius. + * + * @method Phaser.Physics.P2.Body#removeShape + * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. + * @return {boolean} True if the shape was found and removed, else false. + */ + removeShape: function (shape) { + + var result = this.data.removeShape(shape); + + this.shapeChanged(); + + return result; + }, + + /** + * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + */ + setCircle: function (radius, offsetX, offsetY, rotation) { + + this.clearShapes(); + + return this.addCircle(radius, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. + * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangle + * @param {number} [width=16] - The width of the rectangle in pixels. + * @param {number} [height=16] - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangle: function (width, height, offsetX, offsetY, rotation) { + + if (width === undefined) { width = 16; } + if (height === undefined) { height = 16; } + + this.clearShapes(); + + return this.addRectangle(width, height, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. + * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. + * If no Sprite is given it defaults to using the parent of this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangleFromSprite + * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangleFromSprite: function (sprite) { + + if (sprite === undefined) { sprite = this.sprite; } + + this.clearShapes(); + + return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); + + }, + + /** + * Adds the given Material to all Shapes that belong to this Body. + * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. + * + * @method Phaser.Physics.P2.Body#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. + */ + setMaterial: function (material, shape) { + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].material = material; + } + } + else + { + shape.material = material; + } + + }, + + /** + * Updates the debug draw if any body shapes change. + * + * @method Phaser.Physics.P2.Body#shapeChanged + */ + shapeChanged: function() { + + if (this.debugBody) + { + this.debugBody.draw(); + } + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * The shape data format is based on the output of the + * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for + * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor} + * + * @method Phaser.Physics.P2.Body#addPhaserPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. + * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. + * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList + */ + addPhaserPolygon: function (key, object) { + + var data = this.game.cache.getPhysicsData(key, object); + var createdFixtures = []; + + // Cycle through the fixtures + for (var i = 0; i < data.length; i++) + { + var fixtureData = data[i]; + var shapesOfFixture = this.addFixture(fixtureData); + + // Always add to a group + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); + + // if (unique) fixture key is provided + if (fixtureData.fixtureKey) + { + createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; + } + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return createdFixtures; + + }, + + /** + * Add a polygon fixture. This is used during #loadPolygon. + * + * @method Phaser.Physics.P2.Body#addFixture + * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. + * @return {array} An array containing the generated shapes for the given polygon. + */ + addFixture: function (fixtureData) { + + var generatedShapes = []; + + if (fixtureData.circle) + { + var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) }); + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + var offset = p2.vec2.create(); + offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); + offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); + + this.data.addShape(shape, offset); + generatedShapes.push(shape); + } + else + { + var polygons = fixtureData.polygons; + var cm = p2.vec2.create(); + + for (var i = 0; i < polygons.length; i++) + { + var shapes = polygons[i]; + var vertices = []; + + for (var s = 0; s < shapes.length; s += 2) + { + vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); + } + + var shape = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== shape.vertices.length; j++) + { + var v = shape.vertices[j]; + p2.vec2.sub(v, v, shape.centerOfMass); + } + + p2.vec2.scale(cm, shape.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + shape.updateTriangles(); + shape.updateCenterOfMass(); + shape.updateBoundingRadius(); + + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + this.data.addShape(shape, cm); + + generatedShapes.push(shape); + } + } + + return generatedShapes; + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * + * As well as reading the data from the Cache you can also pass `null` as the first argument and a + * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance. + * + * For more details see the format of the Lime / Corona Physics Editor export. + * + * @method Phaser.Physics.P2.Body#loadPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the + * data as the 2nd argument. + * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from, + * or if key is null pass the actual physics data object itself as this parameter. + * @param {number} [scale=1] - Optionally resize the loaded polygon. + * @return {boolean} True on success, else false. + */ + loadPolygon: function (key, object, scale) { + + if (key === null) + { + var data = object; + } + else + { + var data = this.game.cache.getPhysicsData(key, object); + } + + if (typeof scale !== "number") + { + scale = 1; + } + + // We've multiple Convex shapes, they should be CCW automatically + var cm = p2.vec2.create(); + + for (var i = 0; i < data.length; i++) + { + var vertices = []; + + for (var s = 0; s < data[i].shape.length; s += 2) + { + vertices.push([ + this.world.pxmi(data[i].shape[s] * scale), + this.world.pxmi(data[i].shape[s + 1] * scale) + ]); + } + + var c = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== c.vertices.length; j++) + { + var v = c.vertices[j]; + p2.vec2.sub(v, v, c.centerOfMass); + } + + p2.vec2.scale(cm, c.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + c.updateTriangles(); + c.updateCenterOfMass(); + c.updateBoundingRadius(); + + this.data.addShape(c, cm); + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return true; + + } + +}; + +Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; + +/** + * Dynamic body. Dynamic bodies body can move and respond to collisions and forces. + * @property DYNAMIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.DYNAMIC = 1; + +/** + * Static body. Static bodies do not move, and they do not respond to forces or collision. + * @property STATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.STATIC = 2; + +/** + * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. + * @property KINEMATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.KINEMATIC = 4; + +/** +* @name Phaser.Physics.P2.Body#static +* @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.STATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#dynamic +* @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#kinematic +* @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.KINEMATIC; + this.mass = 4; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#allowSleep +* @property {boolean} allowSleep - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { + + get: function () { + + return this.data.allowSleep; + + }, + + set: function (value) { + + if (value !== this.data.allowSleep) + { + this.data.allowSleep = value; + } + + } + +}); + +/** +* The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. +* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. +* If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#angle +* @property {number} angle - The angle of this Body in degrees. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); + + }, + + set: function(value) { + + this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#angularDamping +* @property {number} angularDamping - The angular damping acting acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { + + get: function () { + + return this.data.angularDamping; + + }, + + set: function (value) { + + this.data.angularDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularForce +* @property {number} angularForce - The angular force acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { + + get: function () { + + return this.data.angularForce; + + }, + + set: function (value) { + + this.data.angularForce = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularVelocity +* @property {number} angularVelocity - The angular velocity of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { + + get: function () { + + return this.data.angularVelocity; + + }, + + set: function (value) { + + this.data.angularVelocity = value; + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#damping +* @property {number} damping - The linear damping acting on the body in the velocity direction. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { + + get: function () { + + return this.data.damping; + + }, + + set: function (value) { + + this.data.damping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#fixedRotation +* @property {boolean} fixedRotation - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { + + get: function () { + + return this.data.fixedRotation; + + }, + + set: function (value) { + + if (value !== this.data.fixedRotation) + { + this.data.fixedRotation = value; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#inertia +* @property {number} inertia - The inertia of the body around the Z axis.. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { + + get: function () { + + return this.data.inertia; + + }, + + set: function (value) { + + this.data.inertia = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#mass +* @property {number} mass - The mass of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { + + get: function () { + + return this.data.mass; + + }, + + set: function (value) { + + if (value !== this.data.mass) + { + this.data.mass = value; + this.data.updateMassProperties(); + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#motionState +* @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { + + get: function () { + + return this.data.type; + + }, + + set: function (value) { + + if (value !== this.data.type) + { + this.data.type = value; + } + + } + +}); + +/** +* The angle of the Body in radians. +* If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#rotation +* @property {number} rotation - The angle of this Body in radians. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { + + get: function() { + + return this.data.angle; + + }, + + set: function(value) { + + this.data.angle = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#sleepSpeedLimit +* @property {number} sleepSpeedLimit - . +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { + + get: function () { + + return this.data.sleepSpeedLimit; + + }, + + set: function (value) { + + this.data.sleepSpeedLimit = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#x +* @property {number} x - The x coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.data.position[0]); + + }, + + set: function (value) { + + this.data.position[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#y +* @property {number} y - The y coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.data.position[1]); + + }, + + set: function (value) { + + this.data.position[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#id +* @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { + + get: function () { + + return this.data.id; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#debug +* @property {boolean} debug - Enable or disable debug drawing of this body +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { + + get: function () { + + return (this.debugBody !== null); + + }, + + set: function (value) { + + if (value && !this.debugBody) + { + // This will be added to the global space + this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); + } + else if (!value && this.debugBody) + { + this.debugBody.destroy(); + this.debugBody = null; + } + + } + +}); + +/** +* A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. +* Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. +* Also note that when you set this it will only affect Body shapes that already exist. If you then add further shapes to your Body +* after setting this it will *not* proactively set them to collide with the bounds. +* +* @name Phaser.Physics.P2.Body#collideWorldBounds +* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? +* @default true +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { + + get: function () { + + return this._collideWorldBounds; + + }, + + set: function (value) { + + if (value && !this._collideWorldBounds) + { + this._collideWorldBounds = true; + this.updateCollisionMask(); + } + else if (!value && this._collideWorldBounds) + { + this._collideWorldBounds = false; + this.updateCollisionMask(); + } + + } + +}); + +/** +* @author George https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Draws a P2 Body to a Graphics instance for visual debugging. +* Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. +* So use sparingly and rarely (if ever) in production code. +* +* Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you +* manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will +* need to manually adjust its BodyDebug as well. +* +* @class Phaser.Physics.P2.BodyDebug +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. +* @param {object} settings - Settings object. +*/ +Phaser.Physics.P2.BodyDebug = function(game, body, settings) { + + Phaser.Group.call(this, game); + + /** + * @property {object} defaultSettings - Default debug settings. + * @private + */ + var defaultSettings = { + pixelsPerLengthUnit: game.physics.p2.mpx(1), + debugPolygons: false, + lineWidth: 1, + alpha: 0.5 + }; + + this.settings = Object.assign(defaultSettings, settings); + + /** + * @property {number} ppu - Pixels per Length Unit. + */ + this.ppu = this.settings.pixelsPerLengthUnit; + this.ppu = -1 * this.ppu; + + /** + * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. + */ + this.body = body; + + /** + * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. + */ + this.canvas = new Phaser.Graphics(game); + + this.canvas.alpha = this.settings.alpha; + + this.add(this.canvas); + + this.draw(); + + this.updateSpriteTransform(); + +}; + +Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); +Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; + +Object.assign(Phaser.Physics.P2.BodyDebug.prototype, { + + /** + * Core update. + * + * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform + */ + updateSpriteTransform: function() { + + this.position.x = this.body.position[0] * this.ppu; + this.position.y = this.body.position[1] * this.ppu; + this.rotation = this.body.angle; + + }, + + /** + * Draws the P2 shapes to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#draw + */ + draw: function() { + + var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; + + obj = this.body; + sprite = this.canvas; + sprite.clear(); + color = parseInt(this.randomPastelHex(), 16); + lineColor = 0xff0000; + lw = this.lineWidth; + + if (obj instanceof p2.Body && obj.shapes.length) + { + var l = obj.shapes.length; + + i = 0; + + while (i !== l) + { + child = obj.shapes[i]; + offset = child.position || 0; + angle = child.angle || 0; + + if (child instanceof p2.Circle) + { + this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); + } + else if (child instanceof p2.Capsule) + { + this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw); + } + 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.Box) + { + this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); + } + else if (child instanceof p2.Convex) + { + verts = []; + vrot = p2.vec2.create(); + + for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _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]); + } + + i++; + } + } + + }, + + /** + * Draws a p2.Box to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawRectangle + * @private + */ + drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + g.beginFill(fillColor); + g.drawRect(x - w / 2, y - h / 2, w, h); + + }, + + /** + * Draws a p2.Circle to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCircle + * @private + */ + drawCircle: function(g, x, y, angle, radius, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + g.lineStyle(lineWidth, 0x000000, 1); + g.beginFill(color, 1.0); + g.drawCircle(x, y, -radius*2); + g.endFill(); + g.moveTo(x, y); + g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); + + }, + + /** + * Draws a p2.Line to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawLine + * @private + */ + drawLine: function(g, len, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth * 5, color, 1); + g.moveTo(-len / 2, 0); + g.lineTo(len / 2, 0); + + }, + + /** + * Draws a p2.Convex to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawConvex + * @private + */ + drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { + + var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + 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 = [0xff0000, 0x00ff00, 0x0000ff]; + 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, 0x000000, 1); + return g.drawCircle(offset[0], offset[1], lineWidth * 2); + } + + }, + + /** + * Draws a p2.Path to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPath + * @private + */ + drawPath: function(g, path, color, fillColor, lineWidth) { + + var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + if (typeof fillColor === "number") + { + g.beginFill(fillColor); + } + + lastx = null; + lasty = null; + i = 0; + + while (i < path.length) + { + v = path[i]; + x = v[0]; + y = v[1]; + + if (x !== lastx || y !== lasty) + { + if (i === 0) + { + g.moveTo(x, y); + } + else + { + p1x = lastx; + p1y = lasty; + p2x = x; + p2y = y; + p3x = path[(i + 1) % path.length][0]; + p3y = path[(i + 1) % path.length][1]; + area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); + + if (area !== 0) + { + g.lineTo(x, y); + } + } + lastx = x; + lasty = y; + } + + i++; + + } + + if (typeof fillColor === "number") + { + g.endFill(); + } + + if (path.length > 2 && typeof fillColor === "number") + { + g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); + g.lineTo(path[0][0], path[0][1]); + } + + }, + + /** + * Draws a p2.Plane to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPlane + * @private + */ + drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { + + var max, xd, yd; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + + 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); + + }, + + /** + * Draws a p2.Capsule to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCapsule + * @private + */ + drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + // Draw circles at ends + var c = Math.cos(angle); + var s = Math.sin(angle); + + g.beginFill(fillColor, 1); + g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2); + g.drawCircle( len/2*c + x, len/2*s + y, -radius * 2); + g.endFill(); + + // Draw rectangle + g.lineStyle(lineWidth, color, 0); + g.beginFill(fillColor, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.endFill(); + + // Draw lines in between + g.lineStyle(lineWidth, color, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + + }, + + /** + * Picks a random pastel color. + * + * @method Phaser.Physics.P2.BodyDebug#randomPastelHex + * @private + */ + 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); + + }, + + /** + * Converts from RGB to Hex. + * + * @method Phaser.Physics.P2.BodyDebug#rgbToHex + * @private + */ + rgbToHex: function(r, g, b) { + return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); + }, + + /** + * Component to hex conversion. + * + * @method Phaser.Physics.P2.BodyDebug#componentToHex + * @private + */ + componentToHex: function(c) { + + var hex; + hex = c.toString(16); + + if (hex.length === 2) + { + return hex; + } + else + { + return hex + '0'; + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.Spring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restLength=1] - Rest length of the spring. A number > 0. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +*/ +Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restLength === undefined) { restLength = 1; } + if (stiffness === undefined) { stiffness = 100; } + if (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]) ]; + } + + /** + * @property {p2.LinearSpring} data - The actual p2 spring object. + */ + this.data = new p2.LinearSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.RotationalSpring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +*/ +Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restAngle === undefined) { restAngle = null; } + if (stiffness === undefined) { stiffness = 100; } + if (damping === undefined) { damping = 1; } + + if (restAngle) + { + restAngle = world.pxm(restAngle); + } + + var options = { + restAngle: restAngle, + stiffness: stiffness, + damping: damping + }; + + /** + * @property {p2.RotationalSpring} data - The actual p2 spring object. + */ + this.data = new p2.RotationalSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A P2 Material. +* +* \o/ ~ "Because I'm a Material girl" +* +* @class Phaser.Physics.P2.Material +* @constructor +* @param {string} name - The user defined name given to this Material. +*/ +Phaser.Physics.P2.Material = function (name) { + + /** + * @property {string} name - The user defined name given to this Material. + * @default + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Defines a physics material +* +* @class Phaser.Physics.P2.ContactMaterial +* @constructor +* @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. +* @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. +* @param {object} [options] - Additional configuration options. +*/ +Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { + + /** + * @property {number} id - The contact material identifier. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. + */ + + /** + * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. + */ + + /** + * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. + */ + + /** + * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + */ + + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Collision Group +* +* @class Phaser.Physics.P2.CollisionGroup +* @constructor +* @param {number} bitmask - The CollisionGroup bitmask. +*/ +Phaser.Physics.P2.CollisionGroup = function (bitmask) { + + /** + * @property {number} mask - The CollisionGroup bitmask. + */ + this.mask = bitmask; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A constraint that tries to keep the distance between two bodies constant. +* +* @class Phaser.Physics.P2.DistanceConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} distance - The distance to keep between the bodies. +* @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. +* @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. +* @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply. +*/ +Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { + + if (distance === undefined) { distance = 100; } + if (localAnchorA === undefined) { localAnchorA = [0, 0]; } + if (localAnchorB === undefined) { localAnchorB = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + distance = world.pxm(distance); + + localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ]; + localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ]; + + var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce }; + + p2.DistanceConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); +Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.GearConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [angle=0] - The relative angle +* @param {number} [ratio=1] - The gear ratio. +*/ +Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { + + if (angle === undefined) { angle = 0; } + if (ratio === undefined) { ratio = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Locks the relative position between two bodies. +* +* @class Phaser.Physics.P2.LockConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [angle=0] - The angle of bodyB in bodyA's frame. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { + + if (offset === undefined) { offset = [0, 0]; } + if (angle === undefined) { angle = 0; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.PrismaticConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. +* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { + + if (lockRotation === undefined) { lockRotation = true; } + if (anchorA === undefined) { anchorA = [0, 0]; } + if (anchorB === undefined) { anchorB = [0, 0]; } + if (axis === undefined) { axis = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* The pivot points are given in world (pixel) coordinates. +* +* @class Phaser.Physics.P2.RevoluteConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {p2.Body} bodyB - Second connected body. +* @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. +* @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. +*/ +Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + if (worldPivot === undefined) { worldPivot = null; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; + pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; + + if (worldPivot) + { + worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ]; + } + + var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce }; + + p2.RevoluteConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); +Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image Collection is a special tileset containing mulitple images, with no slicing into each image. +* +* Image Collections are normally created automatically when Tiled data is loaded. +* +* @class Phaser.ImageCollection +* @constructor +* @param {string} name - The name of the image collection in the map data. +* @param {integer} firstgid - The first image index this image collection contains. +* @param {integer} [width=32] - Width of widest image (in pixels). +* @param {integer} [height=32] - Height of tallest image (in pixels). +* @param {integer} [margin=0] - The margin around all images in the collection (in pixels). +* @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). +* @param {object} [properties={}] - Custom Image Collection properties. +*/ +Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Image Collection. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of the widest image (in pixels). + * @property {integer} imageWidth + * @readonly + */ + this.imageWidth = width | 0; + + /** + * The height of the tallest image (in pixels). + * @property {integer} imageHeight + * @readonly + */ + this.imageHeight = height | 0; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageMarge + * @readonly + */ + // Modified internally + this.imageMargin = margin | 0; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageSpacing + * @readonly + */ + this.imageSpacing = spacing | 0; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached images that are a part of this collection. + * @property {array} images + * @readonly + */ + // Modified internally + this.images = []; + + /** + * The total number of images in the image collection. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; +}; + +Phaser.ImageCollection.prototype = { + + /** + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.ImageCollection#containsImageIndex + * @param {integer} imageIndex - The image index to search for. + * @return {boolean} True if this Image Collection contains the given index. + */ + containsImageIndex: function (imageIndex) { + + return ( + imageIndex >= this.firstgid && + imageIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Add an image to this Image Collection. + * + * @method Phaser.ImageCollection#addImage + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + */ + addImage: function (gid, image) { + + this.images.push({ gid: gid, image: image }); + this.total++; + + } + +}; + +Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile is a representation of a single tile within the Tilemap. +* +* @class Phaser.Tile +* @constructor +* @param {object} layer - The layer in the Tilemap data that this tile belongs to. +* @param {number} index - The index of this tile type in the core map data. +* @param {number} x - The x coordinate of this tile. +* @param {number} y - The y coordinate of this tile. +* @param {number} width - Width of the tile. +* @param {number} height - Height of the tile. +*/ +Phaser.Tile = function (layer, index, x, y, width, height) { + + /** + * @property {object} layer - The layer in the Tilemap data that this tile belongs to. + */ + this.layer = layer; + + /** + * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. + */ + this.index = index; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.x = x; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.y = y; + + /** + * @property {number} rotation - The rotation angle of this tile. + */ + this.rotation = 0; + + /** + * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not. + */ + this.flipped = false; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.worldX = x * width; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.worldY = y * height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.height = height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.centerX = Math.abs(width / 2); + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.centerY = Math.abs(height / 2); + + /** + * @property {number} alpha - The alpha value at which this tile is drawn to the canvas. + */ + this.alpha = 1; + + /** + * @property {object} properties - Tile specific properties. + */ + this.properties = {}; + + /** + * @property {boolean} scanned - Has this tile been walked / turned into a poly? + */ + this.scanned = false; + + /** + * @property {boolean} faceTop - Is the top of this tile an interesting edge? + */ + this.faceTop = false; + + /** + * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge? + */ + this.faceBottom = false; + + /** + * @property {boolean} faceLeft - Is the left of this tile an interesting edge? + */ + this.faceLeft = false; + + /** + * @property {boolean} faceRight - Is the right of this tile an interesting edge? + */ + this.faceRight = false; + + /** + * @property {boolean} collideLeft - Indicating collide with any object on the left. + * @default + */ + this.collideLeft = false; + + /** + * @property {boolean} collideRight - Indicating collide with any object on the right. + * @default + */ + this.collideRight = false; + + /** + * @property {boolean} collideUp - Indicating collide with any object on the top. + * @default + */ + this.collideUp = false; + + /** + * @property {boolean} collideDown - Indicating collide with any object on the bottom. + * @default + */ + this.collideDown = false; + + /** + * @property {function} collisionCallback - Tile collision callback. + * @default + */ + this.collisionCallback = null; + + /** + * @property {object} collisionCallbackContext - The context in which the collision callback will be called. + * @default + */ + this.collisionCallbackContext = this; + + /** + * @property {boolean} debug + * @default + */ + this.debug = false; + +}; + +Phaser.Tile.prototype = { + + /** + * Check if the given x and y world coordinates are within this Tile. + * + * @method Phaser.Tile#containsPoint + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ + containsPoint: function (x, y) { + + return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom); + + }, + + /** + * Check for intersection with this tile. + * + * @method Phaser.Tile#intersects + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + */ + 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; + + }, + + /** + * Set a callback to be called when this tile is hit by an object. + * The callback must true true for collision processing to take place. + * + * @method Phaser.Tile#setCollisionCallback + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + */ + setCollisionCallback: function (callback, context) { + + this.collisionCallback = callback; + this.collisionCallbackContext = context; + + }, + + /** + * Clean up memory. + * + * @method Phaser.Tile#destroy + */ + destroy: function () { + + this.collisionCallback = null; + this.collisionCallbackContext = null; + this.properties = null; + + }, + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tile#setCollision + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} right - Indicating collide with any object on the right. + * @param {boolean} up - Indicating collide with any object on the top. + * @param {boolean} down - Indicating collide with any object on the bottom. + */ + setCollision: function (left, right, up, down) { + + this.collideLeft = left; + this.collideRight = right; + this.collideUp = up; + this.collideDown = down; + + this.faceLeft = left; + this.faceRight = right; + this.faceTop = up; + this.faceBottom = down; + + }, + + /** + * Reset collision status flags. + * + * @method Phaser.Tile#resetCollision + */ + 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; + + }, + + /** + * Is this tile interesting? + * + * @method Phaser.Tile#isInteresting + * @param {boolean} collides - If true will check any collides value. + * @param {boolean} faces - If true will check any face value. + * @return {boolean} True if the Tile is interesting, otherwise false. + */ + isInteresting: function (collides, faces) { + + if (collides && faces) + { + // Does this tile have any collide flags OR interesting face? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback); + } + else if (collides) + { + // Does this tile collide? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + else if (faces) + { + // Does this tile have an interesting face? + return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); + } + + return false; + + }, + + /** + * Copies the tile data and properties from the given tile to this tile. + * + * @method Phaser.Tile#copy + * @param {Phaser.Tile} tile - The tile to copy from. + */ + 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; + +/** +* @name Phaser.Tile#collides +* @property {boolean} collides - True if this tile can collide on any of its faces. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "collides", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + +}); + +/** +* @name Phaser.Tile#canCollide +* @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "canCollide", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); + } + +}); + +/** +* @name Phaser.Tile#left +* @property {number} left - The x value in pixels. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "left", { + + get: function () { + return this.worldX; + } + +}); + +/** +* @name Phaser.Tile#right +* @property {number} right - The sum of the x and width properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "right", { + + get: function () { + return this.worldX + this.width; + } + +}); + +/** +* @name Phaser.Tile#top +* @property {number} top - The y value. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "top", { + + get: function () { + return this.worldY; + } + +}); + +/** +* @name Phaser.Tile#bottom +* @property {number} bottom - The sum of the y and height properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "bottom", { + + get: function () { + return this.worldY + this.height; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. +* +* Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org +* +* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. +* When using CSV data you must provide the key and the tileWidth and tileHeight parameters. +* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. +* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. +* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. +* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. +* +* @class Phaser.Tilemap +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. +* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +*/ +Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {string} key - The key of this map data in the Phaser.Cache. + */ + this.key = key; + + var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height); + + if (data === null) + { + return; + } + + /** + * @property {number} width - The width of the map (in tiles). + */ + this.width = data.width; + + /** + * @property {number} height - The height of the map (in tiles). + */ + this.height = data.height; + + /** + * @property {number} tileWidth - The base width of the tiles in the map (in pixels). + */ + this.tileWidth = data.tileWidth; + + /** + * @property {number} tileHeight - The base height of the tiles in the map (in pixels). + */ + this.tileHeight = data.tileHeight; + + /** + * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + */ + this.orientation = data.orientation; + + /** + * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + */ + this.format = data.format; + + /** + * @property {number} version - The version of the map data (as specified in Tiled, usually 1). + */ + this.version = data.version; + + /** + * @property {object} properties - Map specific properties as specified in Tiled. + */ + this.properties = data.properties; + + /** + * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth. + */ + this.widthInPixels = data.widthInPixels; + + /** + * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight. + */ + this.heightInPixels = data.heightInPixels; + + /** + * @property {array} layers - An array of Tilemap layer data. + */ + this.layers = data.layers; + + /** + * @property {array} tilesets - An array of Tilesets. + */ + this.tilesets = data.tilesets; + + /** + * @property {array} imagecollections - An array of Image Collections. + */ + this.imagecollections = data.imagecollections; + + /** + * @property {array} tiles - The super array of Tiles. + */ + this.tiles = data.tiles; + + /** + * @property {array} objects - An array of Tiled Object Layers. + */ + this.objects = data.objects; + + /** + * @property {array} collideIndexes - An array of tile indexes that collide. + */ + this.collideIndexes = []; + + /** + * @property {array} collision - An array of collision data (polylines, etc). + */ + this.collision = data.collision; + + /** + * @property {array} images - An array of Tiled Image Layers. + */ + this.images = data.images; + + /** + * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data. + */ + this.enableDebug = false; + + /** + * @property {number} currentLayer - The current layer. + */ + this.currentLayer = 0; + + /** + * @property {array} debugMap - Map data used for debug values only. + */ + this.debugMap = []; + + /** + * @property {array} _results - Internal var. + * @private + */ + this._results = []; + + /** + * @property {number} _tempA - Internal var. + * @private + */ + this._tempA = 0; + + /** + * @property {number} _tempB - Internal var. + * @private + */ + this._tempB = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.CSV = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.TILED_JSON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.NORTH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.EAST = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.SOUTH = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.WEST = 3; + +Phaser.Tilemap.prototype = { + + /** + * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. + * + * @method Phaser.Tilemap#create + * @param {string} name - The name of the default layer of the map. + * @param {number} width - The width of the map in tiles. + * @param {number} height - The height of the map in tiles. + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + create: function (name, width, height, tileWidth, tileHeight, group) { + + if (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); + + }, + + /** + * Sets the base tile size for the map. + * + * @method Phaser.Tilemap#setTileSize + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + */ + setTileSize: function (tileWidth, tileHeight) { + + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.widthInPixels = this.width * tileWidth; + this.heightInPixels = this.height * tileHeight; + + }, + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. + * + * @method Phaser.Tilemap#addTilesetImage + * @param {string} tileset - The name of the tileset as specified in the map data. + * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset. + * If `undefined` or `null` it will look for an image with a key matching the tileset parameter. + * You can also pass in a BitmapData which can be used instead of an Image. + * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. + * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. + * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. + * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. + * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. + * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed. + */ + addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { + + if (tileset === undefined) { return null; } + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (gid === undefined) { gid = 0; } + + // In-case we're working from a blank map + if (tileWidth === 0) + { + tileWidth = 32; + } + + if (tileHeight === 0) + { + tileHeight = 32; + } + + var img = null; + + if (key === undefined || key === null) + { + key = tileset; + } + + if (key instanceof Phaser.BitmapData) + { + img = key.canvas; + } + else + { + if (!this.game.cache.checkImageKey(key)) + { + console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"'); + return null; + } + + img = this.game.cache.getImage(key); + } + + var idx = this.getTilesetIndex(tileset); + + if (idx === null && this.format === Phaser.Tilemap.TILED_JSON) + { + console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + tileset + '"'); + console.log('Tilesets: ', this.tilesets); + return null; + } + + if (this.tilesets[idx]) + { + this.tilesets[idx].setImage(img); + return this.tilesets[idx]; + } + else + { + var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {}); + + newSet.setImage(img); + + 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; t < gid + newSet.total; t++) + { + this.tiles[t] = [x, y, i]; + + x += tileWidth + tileSpacing; + + count++; + + if (count === newSet.total) + { + break; + } + + countX++; + + if (countX === newSet.columns) + { + x = tileMargin; + y += tileHeight + tileSpacing; + + countX = 0; + countY++; + + if (countY === newSet.rows) + { + break; + } + } + } + + return newSet; + + } + + return null; + + }, + + /** + * Creates a Sprite for every {@link http://doc.mapeditor.org/reference/tmx-map-format/#object object} matching the `gid` argument. You can optionally specify the group that the Sprite will be created in. If none is + * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to + * configure Sprite properties from within the map editor. For example giving an object a property of `alpha: 0.5` in the map editor will duplicate that when the + * Sprite is created. You could also give it a value like: `body.velocity.x: 100` to set it moving automatically. + * + * The `gid` argument is matched against: + * + * 1. For a tile object, the tile identifier (`gid`); or + * 2. The object's unique ID (`id`); or + * 3. The object's `name` (a string) + * + * @method Phaser.Tilemap#createFromObjects + * @param {string} name - The name of the Object Group to create Sprites from. + * @param {number|string} gid - The object's tile reference (gid), unique ID (id) or name. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. + * @param {boolean} [exists=true] - The default exists state of the Sprite. + * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. + * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. + * @param {boolean} [adjustSize=true] - By default the width and height of the objects are transferred to the sprite. This parameter controls that behavior. + */ + createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY, adjustSize) { + + if (exists === undefined) { exists = true; } + if (autoCull === undefined) { autoCull = false; } + if (group === undefined) { group = this.game.world; } + if (CustomClass === undefined) { CustomClass = Phaser.Sprite; } + if (adjustY === undefined) { adjustY = true; } + if (adjustSize === undefined) { adjustSize = true; } + + if (!this.objects[name]) + { + console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name); + console.log('Objects: ', this.objects); + return; + } + + for (var i = 0; i < this.objects[name].length; i++) + { + var found = false; + var obj = this.objects[name][i]; + + if (obj.gid !== undefined && typeof gid === 'number' && obj.gid === gid) + { + found = true; + } + else if (obj.id !== undefined && typeof gid === 'number' && obj.id === gid) + { + found = true; + } + else if (obj.name !== undefined && typeof gid === 'string' && obj.name === gid) + { + found = true; + } + + if (found) + { + var sprite = new CustomClass(this.game, parseFloat(obj.x, 10), parseFloat(obj.y, 10), key, frame); + + sprite.name = obj.name; + sprite.autoCull = autoCull; + sprite.exists = exists; + sprite.visible = obj.visible; + + if (adjustSize) + { + if (obj.width) + { + sprite.width = obj.width; + } + + if (obj.height) + { + sprite.height = obj.height; + } + } + + if (obj.rotation) + { + sprite.angle = obj.rotation; + } + + if (adjustY) + { + sprite.y -= sprite.height; + } + + group.add(sprite); + + for (var property in obj.properties) + { + group.set(sprite, property, obj.properties[property], false, false, 0, true); + } + } + } + + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the map data. + * You can specify the group that the Sprite will be created in. If none is given it will be created in the World. + * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special + * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemap#createFromTiles + * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from. + * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. + * @return {integer} The number of Sprites that were created. + */ + createFromTiles: function (tiles, replacements, key, layer, group, properties) { + + if (typeof tiles === 'number') { tiles = [tiles]; } + + if (replacements === undefined || replacements === null) + { + replacements = []; + } + else if (typeof replacements === 'number') + { + replacements = [replacements]; + } + + layer = this.getLayer(layer); + + if (group === undefined) { group = this.game.world; } + if (properties === undefined) { properties = {}; } + + if (properties.customClass === undefined) + { + properties.customClass = Phaser.Sprite; + } + + if (properties.adjustY === undefined) + { + properties.adjustY = true; + } + + var lw = this.layers[layer].width; + var lh = this.layers[layer].height; + + this.copy(0, 0, lw, lh, layer); + + if (this._results.length < 2) + { + return 0; + } + + var total = 0; + var sprite; + + for (var i = 1, len = this._results.length; i < len; i++) + { + if (tiles.indexOf(this._results[i].index) !== -1) + { + sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key); + + for (var property in properties) + { + sprite[property] = properties[property]; + } + + group.add(sprite); + total++; + } + + } + + if (replacements.length === 1) + { + // Assume 1 replacement for all types of tile given + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer); + } + } + else if (replacements.length > 1) + { + // Assume 1 for 1 mapping + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer); + } + } + + return total; + + }, + + /** + * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. + * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. + * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. + * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. + * + * @method Phaser.Tilemap#createLayer + * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. + * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. + * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. + * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. + */ + createLayer: function (layer, width, height, group) { + + // Add Buffer support for the left of the canvas + + if (width === undefined) { width = this.game.width; } + if (height === undefined) { height = this.game.height; } + if (group === undefined) { group = this.game.world; } + + var index = layer; + + if (typeof layer === 'string') + { + index = this.getLayerIndex(layer); + } + + if (index === null || index > this.layers.length) + { + console.warn('Tilemap.createLayer: Invalid layer ID given: "' + layer + '"'); + console.log('Layers: ', this.layers); + return; + } + + // Sort out the display dimensions, so they never render too much, or too little. + + if (width === undefined || width <= 0) + { + width = Math.min(this.game.width, this.layers[index].widthInPixels); + } + else if (width > this.game.width) + { + width = this.game.width; + } + + if (height === undefined || height <= 0) + { + height = Math.min(this.game.height, this.layers[index].heightInPixels); + } + else if (height > this.game.height) + { + height = this.game.height; + } + + if (this.enableDebug) + { + console.group('Tilemap.createLayer'); + console.log('Name:', this.layers[index].name); + console.log('Size:', width, 'x', height); + console.log('Tileset:', this.tilesets[0].name, 'index:', index); + } + + var rootLayer = group.add(new Phaser.TilemapLayer(this.game, this, index, width, height)); + + if (this.enableDebug) + { + console.groupEnd(); + } + + return rootLayer; + + }, + + + /** + * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. + * + * @method Phaser.Tilemap#createBlankLayer + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {number} width - The width of the layer in tiles. + * @param {number} height - The height of the layer in tiles. + * @param {number} tileWidth - The width of the tiles the layer uses for calculations. + * @param {number} tileHeight - The height of the tiles the layer uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) { + + if (group === undefined) { group = this.game.world; } + + if (this.getLayerIndex(name) !== null) + { + console.warn('Tilemap.createBlankLayer: Layer with matching name already exists: ' + name); + 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; y < height; y++) + { + row = []; + + for (var x = 0; x < width; x++) + { + row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight)); + } + + output.push(row); + } + + layer.data = output; + + this.layers.push(layer); + + this.currentLayer = this.layers.length - 1; + + var w = layer.widthInPixels; + var h = layer.heightInPixels; + + if (w > this.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); + + }, + + /** + * Gets the layer index based on the layers name. + * + * @method Phaser.Tilemap#getIndex + * @protected + * @param {array} location - The local array to search. + * @param {string} name - The name of the array element to get. + * @return {number} The index of the element in the array, or null if not found. + */ + getIndex: function (location, name) { + + for (var i = 0; i < location.length; i++) + { + if (location[i].name === name) + { + return i; + } + } + + return null; + + }, + + /** + * Gets the layer index based on its name. + * + * @method Phaser.Tilemap#getLayerIndex + * @param {string} name - The name of the layer to get. + * @return {number} The index of the layer in this tilemap, or null if not found. + */ + getLayerIndex: function (name) { + + return this.getIndex(this.layers, name); + + }, + + /** + * Gets the tileset index based on its name. + * + * @method Phaser.Tilemap#getTilesetIndex + * @param {string} name - The name of the tileset to get. + * @return {number} The index of the tileset in this tilemap, or null if not found. + */ + getTilesetIndex: function (name) { + + return this.getIndex(this.tilesets, name); + + }, + + /** + * Gets the image index based on its name. + * + * @method Phaser.Tilemap#getImageIndex + * @param {string} name - The name of the image to get. + * @return {number} The index of the image in this tilemap, or null if not found. + */ + getImageIndex: function (name) { + + return this.getIndex(this.images, name); + + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileIndexCallback + * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileIndexCallback: function (indexes, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes]; + } + else + { + // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much + // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit. + this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext }; + } + } + else + { + for (var i = 0, len = indexes.length; i < len; i++) + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes[i]]; + } + else + { + this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext }; + } + } + } + + }, + + /** + * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileLocationCallback + * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} width - The width of the area to copy (given in tiles, not pixels) + * @param {number} height - The height of the area to copy (given in tiles, not pixels) + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].setCollisionCallback(callback, callbackContext); + } + + }, + + /** + * Sets collision on the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [2, 3, 15, 20]. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * Collision-enabled tiles can be collided against Sprites using {@link Phaser.Physics.Arcade#collide}. + * + * You can verify the collision faces by enabling {@link Phaser.TilemapLayer#debug}. + * + * @method Phaser.Tilemap#setCollision + * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollision: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + return this.setCollisionByIndex(indexes, collides, layer, true); + } + else if (Array.isArray(indexes)) + { + // Collide all of the IDs given in the indexes array + for (var i = 0; i < indexes.length; i++) + { + this.setCollisionByIndex(indexes[i], collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + } + + }, + + /** + * Sets collision on a range of tiles where the tile IDs increment sequentially. + * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionBetween + * @param {number} start - The first index of the tile to be set for collision. + * @param {number} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionBetween: function (start, stop, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (start > stop) + { + return; + } + + for (var index = start; index <= stop; index++) + { + this.setCollisionByIndex(index, collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision on all tiles in the given layer, except for the IDs of those in the given array. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionByExclusion + * @param {array} indexes - An array of the tile IDs to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByExclusion: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + // Collide everything, except the IDs given in the indexes array + for (var i = 0, len = this.tiles.length; i < len; i++) + { + if (indexes.indexOf(i) === -1) + { + this.setCollisionByIndex(i, collides, layer, false); + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision values on a tile in the set. + * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. + * + * @method Phaser.Tilemap#setCollisionByIndex + * @protected + * @param {number} index - The index of the tile on the layer. + * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile. + * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByIndex: function (index, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (layer === undefined) { layer = this.currentLayer; } + if (recalculate === undefined) { recalculate = true; } + + if (collides) + { + this.collideIndexes.push(index); + } + else + { + var i = this.collideIndexes.indexOf(index); + + if (i > -1) + { + this.collideIndexes.splice(i, 1); + } + } + + for (var y = 0; y < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile && tile.index === index) + { + if (collides) + { + tile.setCollision(true, true, true, true); + } + else + { + tile.resetCollision(); + } + + tile.faceTop = collides; + tile.faceBottom = collides; + tile.faceLeft = collides; + tile.faceRight = collides; + } + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + return layer; + + }, + + /** + * Gets the TilemapLayer index as used in the setCollision calls. + * + * @method Phaser.Tilemap#getLayer + * @protected + * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer. + * @return {number} The TilemapLayer index. + */ + getLayer: function (layer) { + + if (layer === undefined) + { + layer = this.currentLayer; + } + else if (typeof layer === 'string') + { + var layerArg = layer; + + layer = this.getLayerIndex(layer); + + if (!layer) + { + console.warn('No such layer name: ' + layerArg); + } + } + else if (layer instanceof Phaser.TilemapLayer) + { + layer = layer.index; + } + + return layer; + + }, + + /** + * Turn off/on the recalculation of faces for tile or collision updates. + * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. + * + * @method Phaser.Tilemap#setPreventRecalculate + * @param {boolean} value - If true it will put the recalculation on hold. + */ + setPreventRecalculate: function (value) { + + if (value === true && this.preventingRecalculate !== true) + { + this.preventingRecalculate = true; + this.needToRecalculate = {}; + } + + if (value === false && this.preventingRecalculate === true) + { + this.preventingRecalculate = false; + + for (var i in this.needToRecalculate) + { + this.calculateFaces(i); + } + + this.needToRecalculate = false; + } + + }, + + /** + * Internal function. + * + * @method Phaser.Tilemap#calculateFaces + * @protected + * @param {number} layer - The index of the TilemapLayer to operate on. + */ + calculateFaces: function (layer) { + + if (this.preventingRecalculate) + { + this.needToRecalculate[layer] = true; + return; + } + + var above = null; + var below = null; + var left = null; + var right = null; + + for (var y = 0, h = this.layers[layer].height; y < h; y++) + { + for (var x = 0, w = this.layers[layer].width; x < w; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile) + { + above = this.getTileAbove(layer, x, y); + below = this.getTileBelow(layer, x, y); + left = this.getTileLeft(layer, x, y); + right = this.getTileRight(layer, x, y); + + if (tile.collides) + { + tile.faceTop = true; + tile.faceBottom = true; + tile.faceLeft = true; + tile.faceRight = true; + } + + if (above && above.collides) + { + // There is a tile above this one that also collides, so the top of this tile is no longer interesting + tile.faceTop = false; + } + + if (below && below.collides) + { + // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting + tile.faceBottom = false; + } + + if (left && left.collides) + { + // There is a tile left this one that also collides, so the left of this tile is no longer interesting + tile.faceLeft = false; + } + + if (right && right.collides) + { + // There is a tile right this one that also collides, so the right of this tile is no longer interesting + tile.faceRight = false; + } + } + } + } + + }, + + /** + * Gets the tile above the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileAbove + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileAbove: function (layer, x, y) { + + if (y > 0) + { + return this.layers[layer].data[y - 1][x]; + } + + return null; + + }, + + /** + * Gets the tile below the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileBelow + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileBelow: function (layer, x, y) { + + if (y < this.layers[layer].height - 1) + { + return this.layers[layer].data[y + 1][x]; + } + + return null; + + }, + + /** + * Gets the tile to the left of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileLeft + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileLeft: function (layer, x, y) { + + if (x > 0) + { + return this.layers[layer].data[y][x - 1]; + } + + return null; + + }, + + /** + * Gets the tile to the right of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileRight + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileRight: function (layer, x, y) { + + if (x < this.layers[layer].width - 1) + { + return this.layers[layer].data[y][x + 1]; + } + + return null; + + }, + + /** + * Sets the current layer to the given index. + * + * @method Phaser.Tilemap#setLayer + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + */ + setLayer: function (layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer]) + { + this.currentLayer = layer; + } + + }, + + /** + * Checks if there is a tile at the given location. + * + * @method Phaser.Tilemap#hasTile + * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels) + * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + * @return {boolean} True if there is a tile at the given location, otherwise false. + */ + hasTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined) + { + return false; + } + + return (this.layers[layer].data[y][x].index > -1); + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. + * + * @method Phaser.Tilemap#removeTile + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.hasTile(x, y, layer)) + { + var tile = this.layers[layer].data[y][x]; + + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight); + + this.layers[layer].dirty = true; + + this.calculateFaces(layer); + + return tile; + } + } + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#removeTileWorldXY + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTileWorldXY: function (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.removeTile(x, y, layer); + + }, + + /** + * Puts a tile of the given index value at the coordinate specified. + * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. + * + * @method Phaser.Tilemap#putTile + * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map. + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + putTile: function (tile, x, y, layer) { + + if (tile === null) + { + return this.removeTile(x, y, layer); + } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + var index; + + if (tile instanceof Phaser.Tile) + { + index = tile.index; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].copy(tile); + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height); + } + } + else + { + index = tile; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].index = index; + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight); + } + } + + if (this.collideIndexes.indexOf(index) > -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; + + }, + + /** + * Puts a tile into the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#putTileWorldXY + * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object. + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + 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); + + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. + * If no match is found it returns null. + * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. + * + * @method Phaser.Tilemap#searchTileIndex + * @param {number} index - The tile index value to search for. + * @param {number} [skip=0] - The number of times to skip a matching tile before returning. + * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @return {Phaser.Tile} The first (or n skipped) tile with the matching index. + */ + searchTileIndex: function (index, skip, reverse, layer) { + + if (skip === undefined) { skip = 0; } + if (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 < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + if (this.layers[layer].data[y][x].index === index) + { + if (c === skip) + { + return this.layers[layer].data[y][x]; + } + else + { + c++; + } + } + } + } + } + + return null; + + }, + + /** + * Gets a tile from the Tilemap Layer. The coordinates are given in tile values. + * + * @method Phaser.Tilemap#getTile + * @param {number} x - X position to get the tile from (given in tile units, not pixels) + * @param {number} y - Y position to get the tile from (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTile: function (x, y, layer, nonNull) { + + if (nonNull === undefined) { nonNull = false; } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.layers[layer].data[y][x].index === -1) + { + if (nonNull) + { + return this.layers[layer].data[y][x]; + } + else + { + return null; + } + } + else + { + return this.layers[layer].data[y][x]; + } + } + else + { + return null; + } + + }, + + /** + * Gets a tile from the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#getTileWorldXY + * @param {number} x - X position to get the tile from (given in pixels) + * @param {number} y - Y position to get the tile from (given in pixels) + * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used. + * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates. + */ + getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) { + + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + + layer = this.getLayer(layer); + + x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; + y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; + + return this.getTile(x, y, layer, nonNull); + + }, + + /** + * Copies all of the tiles in the given rectangular block into the tilemap data buffer. + * + * @method Phaser.Tilemap#copy + * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} width - The width of the area to copy (given in tiles, not pixels) + * @param {integer} height - The height of the area to copy (given in tiles, not pixels) + * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from. + * @return {array} An array of the tiles that were copied. + */ + copy: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + if (!this.layers[layer]) + { + this._results.length = 0; + return; + } + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.layers[layer].width; } + if (height === undefined) { height = this.layers[layer].height; } + + if (x < 0) + { + x = 0; + } + + if (y < 0) + { + y = 0; + } + + if (width > this.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; ty < y + height; ty++) + { + for (var tx = x; tx < x + width; tx++) + { + this._results.push(this.layers[layer].data[ty][tx]); + } + } + + return this._results; + + }, + + /** + * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. + * + * @method Phaser.Tilemap#paste + * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels) + * @param {array} tileblock - The block of tiles to paste. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into. + */ + paste: function (x, y, tileblock, layer) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + layer = this.getLayer(layer); + + if (!tileblock || tileblock.length < 2) + { + return; + } + + // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste + var diffX = x - tileblock[1].x; + var diffY = y - tileblock[1].y; + + for (var i = 1; i < tileblock.length; i++) + { + this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]); + } + + this.layers[layer].dirty = true; + this.calculateFaces(layer); + + }, + + /** + * Scans the given area for tiles with an index matching tileA and swaps them with tileB. + * + * @method Phaser.Tilemap#swap + * @param {number} tileA - First tile index. + * @param {number} tileB - Second tile index. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + swap: function (tileA, tileB, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._tempA = tileA; + this._tempB = tileB; + + this._results.forEach(this.swapHandler, this); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Internal function that handles the swapping of tiles. + * + * @method Phaser.Tilemap#swapHandler + * @private + * @param {number} value + */ + swapHandler: function (value) { + + if (value.index === this._tempA) + { + // Swap A with B + value.index = this._tempB; + } + else if (value.index === this._tempB) + { + // Swap B with A + value.index = this._tempA; + } + + }, + + /** + * For each tile in the given area defined by x/y and width/height run the given callback. + * + * @method Phaser.Tilemap#forEach + * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {number} context - The context under which the callback should be run. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + forEach: function (callback, context, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._results.forEach(callback, context); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. + * + * @method Phaser.Tilemap#replace + * @param {number} source - The tile index value to scan for. + * @param {number} dest - The tile index value to replace found tiles with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + replace: function (source, dest, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + if (this._results[i].index === source) + { + this._results[i].index = dest; + } + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Randomises a set of tiles in a given area. + * + * @method Phaser.Tilemap#random + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + random: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + var idx = this._results[t].index; + + if (indexes.indexOf(idx) === -1) + { + indexes.push(idx); + } + } + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = this.game.rnd.pick(indexes); + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! + * + * @method Phaser.Tilemap#shuffle + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + shuffle: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + indexes.push(this._results[t].index); + } + } + + Phaser.ArrayUtils.shuffle(indexes); + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = indexes[i - 1]; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Fills the given area with the specified tile. + * + * @method Phaser.Tilemap#fill + * @param {number} index - The index of the tile that the area will be filled with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + fill: function (index, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = index; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Removes all layers from this tile map. + * + * @method Phaser.Tilemap#removeAllLayers + */ + removeAllLayers: function () { + + this.layers.length = 0; + this.currentLayer = 0; + + }, + + /** + * Dumps the tilemap data out to the console. + * + * @method Phaser.Tilemap#dump + */ + dump: function () { + + var txt = ''; + var args = ['']; + + for (var y = 0; y < this.layers[this.currentLayer].height; y++) + { + for (var x = 0; x < this.layers[this.currentLayer].width; x++) + { + txt += "%c "; + + if (this.layers[this.currentLayer].data[y][x] > 1) + { + 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); + + }, + + /** + * Removes all layer data from this tile map and nulls the game reference. + * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. + * + * @method Phaser.Tilemap#destroy + */ + destroy: function () { + + this.removeAllLayers(); + this.data = []; + this.game = null; + + } + +}; + +Phaser.Tilemap.prototype.constructor = Phaser.Tilemap; + +/** +* @name Phaser.Tilemap#layer +* @property {number|string|Phaser.TilemapLayer} layer - The current layer object. +*/ +Object.defineProperty(Phaser.Tilemap.prototype, "layer", { + + get: function () { + + return this.layers[this.currentLayer]; + + }, + + set: function (value) { + + if (value !== this.currentLayer) + { + this.setLayer(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. +* +* Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. +* +* By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. +* +* @class Phaser.TilemapLayer +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs. +* @param {integer} index - The index of the TileLayer to render within the Tilemap. +* @param {integer} width - Width of the renderable area of the layer (in pixels). +* @param {integer} height - Height of the renderable area of the layer (in pixels). +*/ +Phaser.TilemapLayer = function (game, tilemap, index, width, height) { + + width |= 0; + height |= 0; + + Phaser.Sprite.call(this, game, 0, 0); + + /** + * The Tilemap to which this layer is bound. + * @property {Phaser.Tilemap} map + * @protected + * @readonly + */ + this.map = tilemap; + + /** + * The index of this layer within the Tilemap. + * @property {number} index + * @protected + * @readonly + */ + this.index = index; + + /** + * The layer object within the Tilemap that this layer represents. + * @property {object} layer + * @protected + * @readonly + */ + this.layer = tilemap.layers[index]; + + /** + * The canvas to which this TilemapLayer draws. + * @property {HTMLCanvasElement} canvas + * @protected + */ + this.canvas = Phaser.CanvasPool.create(this, width, height); + + /** + * The 2d context of the canvas. + * @property {CanvasRenderingContext2D} context + * @private + */ + this.context = this.canvas.getContext('2d'); + + this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas, null, this.game.resolution))); + + /** + * The const type of this object. + * @property {number} type + * @readonly + * @protected + * @default Phaser.TILEMAPLAYER + */ + this.type = Phaser.TILEMAPLAYER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.TILEMAPLAYER; + + /** + * Settings that control standard (non-diagnostic) rendering. + * + * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view. + * This can greatly improve scrolling rendering performance, especially when there are many small tiles. + * It should only be disabled in rare cases. + * + * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas. + * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior + * in some browsers, notably Safari. + * + * @default + */ + this.renderSettings = { + enableScrollDelta: true, + overdrawRatio: 0.20, + copyCanvas: null + }; + + /** + * Enable an additional "debug rendering" pass to display collision information. + * + * @property {boolean} debug + * @default + */ + this.debug = false; + + /** + * @property {boolean} exists - Controls if the core game loop and physics update this game object or not. + */ + this.exists = true; + + /** + * Settings used for debugging and diagnostics. + * + * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. + * + * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. + * + * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. + * + * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. + * + */ + this.debugSettings = { + + missingImageFill: 'rgb(255,255,255)', + debuggedTileOverfill: 'rgba(0,255,0,0.4)', + + forceFullRedraw: true, + + debugAlpha: 0.5, + facingEdgeStroke: 'rgba(0,255,0,1)', + collidingTileOverfill: 'rgba(0,255,0,0.2)' + + }; + + /** + * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). + * @property {number} scrollFactorX + * @public + * @default + */ + this.scrollFactorX = 1; + + /** + * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) + * @property {number} scrollFactorY + * @public + * @default + */ + this.scrollFactorY = 1; + + /** + * If true tiles will be force rendered, even if such is not believed to be required. + * @property {boolean} dirty + * @protected + */ + this.dirty = true; + + /** + * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. + * @property {integer} rayStepRate + * @default + */ + this.rayStepRate = 4; + + /** + * Flag controlling if the layer tiles wrap at the edges. + * @property {boolean} _wrap + * @private + */ + this._wrap = false; + + /** + * Local map data and calculation cache. + * @property {object} _mc + * @private + */ + this._mc = { + + // Used to bypass rendering without reliance on `dirty` and detect changes. + scrollX: 0, + scrollY: 0, + renderWidth: 0, + renderHeight: 0, + + tileWidth: tilemap.tileWidth, + tileHeight: tilemap.tileHeight, + + // Collision width/height (pixels) + // What purpose do these have? Most things use tile width/height directly. + // This also only extends collisions right and down. + cw: tilemap.tileWidth, + ch: tilemap.tileHeight, + + // Cached tilesets from index -> Tileset + tilesets: [] + + }; + + /** + * The current canvas left after scroll is applied. + * @property {number} _scrollX + * @private + */ + this._scrollX = 0; + + /** + * The current canvas top after scroll is applied. + * @property {number} _scrollY + * @private + */ + this._scrollY = 0; + + /** + * The position offset of the layer's tiles. + * @property {Phaser.Point} + */ + this.tileOffset = new Phaser.Point(this.layer.offsetX || 0, this.layer.offsetY || 0); + + /** + * Used for caching the tiles / array of tiles. + * @property {Phaser.Tile[]} _results + * @private + */ + this._results = []; + + if (!game.device.canvasBitBltShift) + { + this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas(); + } + + this.fixedToCamera = true; + +}; + +Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer; + +Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* The shared double-copy canvas, created as needed. +* +* @private +* @static +*/ +Phaser.TilemapLayer.sharedCopyCanvas = null; + +/** +* Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. +* +* Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. +* +* @method Phaser.TilemapLayer#ensureSharedCopyCanvas +* @protected +* @static +*/ +Phaser.TilemapLayer.ensureSharedCopyCanvas = function () { + + if (!this.sharedCopyCanvas) + { + this.sharedCopyCanvas = Phaser.CanvasPool.create(this, 2, 2); + } + + return this.sharedCopyCanvas; + +}; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TilemapLayer#preUpdate +*/ +Phaser.TilemapLayer.prototype.preUpdate = function() { + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.postUpdate. Handles cache updates. +* +* @method Phaser.TilemapLayer#postUpdate +* @protected +*/ +Phaser.TilemapLayer.prototype.postUpdate = function () { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderCanvas function. +* +* @method Phaser.TilemapLayer#_renderCanvas +* @private +*/ +Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderWebGL function. +* +* @method Phaser.TilemapLayer#_renderWebGL +* @private +*/ +Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Destroys this TilemapLayer. +* +* @method Phaser.TilemapLayer#destroy +*/ +Phaser.TilemapLayer.prototype.destroy = function() { + + Phaser.CanvasPool.remove(this); + + Phaser.Component.Destroy.prototype.destroy.call(this); + +}; + +/** +* Resizes the internal canvas and texture frame used by this TilemapLayer. +* +* This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully +* selected times. +* +* Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not +* modified either. You will have to handle both of these things from your game code if required. +* +* @method Phaser.TilemapLayer#resize +* @param {number} width - The new width of the TilemapLayer +* @param {number} height - The new height of the TilemapLayer +*/ +Phaser.TilemapLayer.prototype.resize = function (width, height) { + + this.canvas.width = width; + this.canvas.height = height; + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.texture.baseTexture.width = width; + this.texture.baseTexture.height = height; + + this.texture.baseTexture.dirty(); + this.texture.requiresUpdate = true; + + this.texture._updateUvs(); + + this.dirty = true; + +}; + +/** +* Sets the world size to match the size of this layer. +* +* @method Phaser.TilemapLayer#resizeWorld +* @public +*/ +Phaser.TilemapLayer.prototype.resizeWorld = function () { + + this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y); + +}; + +/** + * Get the X axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getLayerOffsetX + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetX = function () { + + return this.tileOffset.x || ((!this.fixedToCamera) ? this.position.x : 0); + +}; + +/** + * Get the Y axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getTileOffsetY + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetY = function () { + + return this.tileOffset.y || ((!this.fixedToCamera) ? this.position.y : 0); + +}; + +/** +* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixX +* @private +* @param {number} x - x coordinate in camera space +* @return {number} x coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixX = function (x) { + + if (this.scrollFactorX === 1 || (this.scrollFactorX === 0 && this.position.x === 0)) + { + return x; + } + + // This executes if the scrollFactorX is 0 and the x position of the tilemap is off from standard. + if (this.scrollFactorX === 0 && this.position.x !== 0) + { + return x - this.position.x; + } + + return this._scrollX + (x - (this._scrollX / this.scrollFactorX)); + +}; + +/** +* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixX +* @private +* @param {number} x - x coordinate in scrollFactor-adjusted dimensions +* @return {number} x coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixX = function (x) { + + if (this.scrollFactorX === 1) + { + return x; + } + + return (this._scrollX / this.scrollFactorX) + (x - this._scrollX); + +}; + +/** +* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixY +* @private +* @param {number} y - y coordinate in camera space +* @return {number} y coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixY = function (y) { + + if (this.scrollFactorY === 1 || (this.scrollFactorY === 0 && this.position.y === 0)) + { + return y; + } + + // This executes if the scrollFactorY is 0 and the y position of the tilemap is off from standard. + if (this.scrollFactorY === 0 && this.position.y !== 0) + { + return y - this.position.y; + } + + return this._scrollY + (y - (this._scrollY / this.scrollFactorY)); + +}; + +/** +* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixY +* @private +* @param {number} y - y coordinate in scrollFactor-adjusted dimensions +* @return {number} y coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixY = function (y) { + + if (this.scrollFactorY === 1) + { + return y; + } + + return (this._scrollY / this.scrollFactorY) + (y - this._scrollY); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileX +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @return {integer} The X map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileX = function (x) { + + // var tileWidth = this.tileWidth * this.scale.x; + return Math.floor(this._fixX(x) / this._mc.tileWidth); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileY +* @public +* @param {number} y - Y position of the point in target tile (in pixels). +* @return {integer} The Y map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileY = function (y) { + + // var tileHeight = this.tileHeight * this.scale.y; + return Math.floor(this._fixY(y) / this._mc.tileHeight); + +}; + +/** +* Convert a pixel coordinate to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileXY +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @param {number} y - Y position of the point in target tile (in pixels). +* @param {(Phaser.Point|object)} point - The Point/object to update. +* @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set. +*/ +Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) { + + point.x = this.getTileX(x); + point.y = this.getTileY(y); + + return point; + +}; + +/** +* Gets all tiles that intersect with the given line. +* +* @method Phaser.TilemapLayer#getRayCastTiles +* @public +* @param {Phaser.Line} line - The line used to determine which tiles to return. +* @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`. +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {Phaser.Tile[]} An array of Phaser.Tiles. +*/ +Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) { + + if (!stepRate) { stepRate = this.rayStepRate; } + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + // First get all tiles that touch the bounds of the line + var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace); + + if (tiles.length === 0) + { + return []; + } + + // Now we only want the tiles that intersect with the points on this line + var coords = line.coordinatesOnLine(stepRate); + var results = []; + + for (var i = 0; i < tiles.length; i++) + { + for (var t = 0; t < coords.length; t++) + { + var tile = tiles[i]; + var coord = coords[t]; + if (tile.containsPoint(coord[0], coord[1])) + { + results.push(tile); + break; + } + } + } + + return results; + +}; + +/** +* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. +* +* @method Phaser.TilemapLayer#getTiles +* @public +* @param {number} x - X position of the top left corner (in pixels). +* @param {number} y - Y position of the top left corner (in pixels). +* @param {number} width - Width of the area to get (in pixels). +* @param {number} height - Height of the area to get (in pixels). +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {array} An array of Tiles. +*/ +Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) { + + // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all) + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + var fetchAll = !(collides || interestingFace); + + // Adjust the x,y coordinates for scrollFactor + x = this._fixX(x); + y = this._fixY(y); + + // Convert the pixel values into tile coordinates + var tx = Math.floor(x / (this._mc.cw * this.scale.x)); + var ty = Math.floor(y / (this._mc.ch * this.scale.y)); + // Don't just use ceil(width/cw) to allow account for x/y diff within cell + var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx; + var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty; + + while (this._results.length) + { + this._results.pop(); + } + + for (var wy = ty; wy < ty + th; wy++) + { + for (var wx = tx; wx < tx + tw; wx++) + { + var row = this.layer.data[wy]; + + if (row && row[wx]) + { + if (fetchAll || row[wx].isInteresting(collides, interestingFace)) + { + this._results.push(row[wx]); + } + } + } + } + + return this._results.slice(); + +}; + +/** +* Returns the appropriate tileset for the index, updating the internal cache as required. +* This should only be called if `tilesets[index]` evaluates to undefined. +* +* @method Phaser.TilemapLayer#resolveTileset +* @private +* @param {integer} Tile index +* @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping. +*/ +Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) { + + var tilesets = this._mc.tilesets; + + // Try for dense array if reasonable + if (tileIndex < 2000) + { + while (tilesets.length < tileIndex) + { + tilesets.push(undefined); + } + } + + var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2]; + + if (setIndex !== null) + { + var tileset = this.map.tilesets[setIndex]; + + if (tileset && tileset.containsTileIndex(tileIndex)) + { + return (tilesets[tileIndex] = tileset); + } + } + + return (tilesets[tileIndex] = null); + +}; + +/** +* The TilemapLayer caches tileset look-ups. +* +* Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. +* +* @method Phaser.TilemapLayer#resetTilesetCache +* @public +*/ +Phaser.TilemapLayer.prototype.resetTilesetCache = function () { + + var tilesets = this._mc.tilesets; + + while (tilesets.length) + { + tilesets.pop(); + } + +}; + +/** + * This method will set the scale of the tilemap as well as update the underlying block data of this layer. + * + * @method Phaser.TilemapLayer#setScale + * @param {number} [xScale=1] - The scale factor along the X-plane + * @param {number} [yScale] - The scale factor along the Y-plane + */ +Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) { + + xScale = xScale || 1; + yScale = yScale || xScale; + + for (var y = 0; y < this.layer.data.length; y++) + { + var row = this.layer.data[y]; + + for (var x = 0; x < row.length; x++) + { + var tile = row[x]; + + tile.width = this.map.tileWidth * xScale; + tile.height = this.map.tileHeight * yScale; + + tile.worldX = tile.x * tile.width; + tile.worldY = tile.y * tile.height; + } + } + + this.scale.setTo(xScale, yScale); + +}; + +/** +* Shifts the contents of the canvas - does extra math so that different browsers agree on the result. +* +* The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in. +* +* @method Phaser.TilemapLayer#shiftCanvas +* @private +* @param {CanvasRenderingContext2D} context - The context to shift +* @param {integer} x +* @param {integer} y +*/ +Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) { + + var canvas = context.canvas; + var copyW = canvas.width - Math.abs(x); + var copyH = canvas.height - Math.abs(y); + + // When x/y non-negative + var dx = 0; + var dy = 0; + var sx = x; + var sy = y; + + if (x < 0) + { + dx = -x; + sx = 0; + } + + if (y < 0) + { + dy = -y; + sy = 0; + } + + var copyCanvas = this.renderSettings.copyCanvas; + + if (copyCanvas) + { + // Use a second copy buffer, without slice support, for Safari .. again. + // Ensure copy canvas is large enough + if (copyCanvas.width < copyW || copyCanvas.height < copyH) + { + copyCanvas.width = copyW; + copyCanvas.height = copyH; + } + + var copyContext = copyCanvas.getContext('2d'); + copyContext.clearRect(0, 0, copyW, copyH); + copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH); + // clear allows default 'source-over' semantics + context.clearRect(sx, sy, copyW, copyH); + context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH); + } + else + { + // Avoids a second copy but flickers in Safari / Safari Mobile + // Ref. https://github.com/photonstorm/phaser/issues/1439 + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH); + context.restore(); + } + +}; + +/** +* Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor. +* This will constrain the tile coordinates based on wrapping but not physical coordinates. +* +* @method Phaser.TilemapLayer#renderRegion +* @private +* @param {integer} scrollX - Render x offset/scroll. +* @param {integer} scrollY - Render y offset/scroll. +* @param {integer} left - Leftmost column to render. +* @param {integer} top - Topmost row to render. +* @param {integer} right - Rightmost column to render. +* @param {integer} bottom - Bottommost row to render. +*/ +Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) { + + var context = this.context; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var tilesets = this._mc.tilesets; + var lastAlpha = NaN; + + if (!this._wrap) + { + if (left <= right) // Only adjust if going to render + { + left = Math.max(0, left); + right = Math.min(width - 1, right); + } + if (top <= bottom) + { + top = Math.max(0, top); + bottom = Math.min(height - 1, bottom); + } + } + + // top-left pixel of top-left cell + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values. + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + // tx/ty - are pixel coordinates where tile is drawn + // x/y - is cell location, normalized [0..width/height) in loop + // xmax/ymax - remaining cells to render on column/row + var tx, ty, x, y, xmax, ymax; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + + if (!tile || tile.index < 0) + { + continue; + } + + var index = tile.index; + + var set = tilesets[index]; + + if (set === undefined) + { + set = this.resolveTileset(index); + } + + // Setting the globalAlpha is "surprisingly expensive" in Chrome (38) + if (tile.alpha !== lastAlpha && !this.debug) + { + context.globalAlpha = tile.alpha; + lastAlpha = tile.alpha; + } + + if (set) + { + if (tile.rotation || tile.flipped) + { + context.save(); + context.translate(tx + tile.centerX, ty + tile.centerY); + context.rotate(tile.rotation); + + if (tile.flipped) + { + context.scale(-1, 1); + } + + set.draw(context, -tile.centerX, -tile.centerY, index); + context.restore(); + } + else + { + set.draw(context, tx, ty, index); + } + } + else if (this.debugSettings.missingImageFill) + { + context.fillStyle = this.debugSettings.missingImageFill; + context.fillRect(tx, ty, tw, th); + } + + if (tile.debug && this.debugSettings.debuggedTileOverfill) + { + context.fillStyle = this.debugSettings.debuggedTileOverfill; + context.fillRect(tx, ty, tw, th); + } + + } + + } + +}; + +/** +* Shifts the canvas and render damaged edge tiles. +* +* @method Phaser.TilemapLayer#renderDeltaScroll +* @private +*/ +Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds. + + // Start in pixels + var left = 0; + var right = -tw; + var top = 0; + var bottom = -th; + + if (shiftX < 0) // layer moving left, damage right + { + left = renderW + shiftX; // shiftX neg. + right = renderW - 1; + } + else if (shiftX > 0) + { + // left -> 0 + right = shiftX; + } + + if (shiftY < 0) // layer moving down, damage top + { + top = renderH + shiftY; // shiftY neg. + bottom = renderH - 1; + } + else if (shiftY > 0) + { + // top -> 0 + bottom = shiftY; + } + + this.shiftCanvas(this.context, shiftX, shiftY); + + // Transform into tile-space + left = Math.floor((left + scrollX) / tw); + right = Math.floor((right + scrollX) / tw); + top = Math.floor((top + scrollY) / th); + bottom = Math.floor((bottom + scrollY) / th); + + if (left <= right) + { + // Clear left or right edge + this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH); + + var trueTop = Math.floor((0 + scrollY) / th); + var trueBottom = Math.floor((renderH - 1 + scrollY) / th); + this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom); + } + + if (top <= bottom) + { + // Clear top or bottom edge + this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th); + + var trueLeft = Math.floor((0 + scrollX) / tw); + var trueRight = Math.floor((renderW - 1 + scrollX) / tw); + this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom); + } + +}; + +/** +* Clear and render the entire canvas. +* +* @method Phaser.TilemapLayer#renderFull +* @private +*/ +Phaser.TilemapLayer.prototype.renderFull = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + this.context.clearRect(0, 0, renderW, renderH); + + this.renderRegion(scrollX, scrollY, left, top, right, bottom); + +}; + +/** +* Renders the tiles to the layer canvas and pushes to the display. +* +* @method Phaser.TilemapLayer#render +* @protected +*/ +Phaser.TilemapLayer.prototype.render = function () { + + var redrawAll = false; + + if (!this.visible) + { + return; + } + + if (this.dirty || this.layer.dirty) + { + this.layer.dirty = false; + redrawAll = true; + } + + var renderWidth = this.canvas.width; // Use Sprite.width/height? + var renderHeight = this.canvas.height; + + // Scrolling bias; whole pixels only + var scrollX = this._scrollX | 0; + var scrollY = this._scrollY | 0; + + var mc = this._mc; + var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down + var shiftY = mc.scrollY - scrollY; + + if (!redrawAll && + shiftX === 0 && shiftY === 0 && + mc.renderWidth === renderWidth && mc.renderHeight === renderHeight) + { + // No reason to redraw map, looking at same thing and not invalidated. + return; + } + + this.context.save(); + + mc.scrollX = scrollX; + mc.scrollY = scrollY; + + if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight) + { + // Could support automatic canvas resizing + mc.renderWidth = renderWidth; + mc.renderHeight = renderHeight; + } + + if (this.debug) + { + this.context.globalAlpha = this.debugSettings.debugAlpha; + + if (this.debugSettings.forceFullRedraw) + { + redrawAll = true; + } + } + + if (!redrawAll && + this.renderSettings.enableScrollDelta && + (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight)) + { + this.renderDeltaScroll(shiftX, shiftY); + } + else + { + // Too much change or otherwise requires full render + this.renderFull(); + } + + if (this.debug) + { + this.context.globalAlpha = 1; + this.renderDebug(); + } + + this.texture.baseTexture.dirty(); + + this.dirty = false; + + this.context.restore(); + + return true; + +}; + +/** +* Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true. +* +* See `debugSettings` for assorted configuration options. +* +* @method Phaser.TilemapLayer#renderDebug +* @private +*/ +Phaser.TilemapLayer.prototype.renderDebug = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var context = this.context; + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + var tx, ty, x, y, xmax, ymax; + + context.strokeStyle = this.debugSettings.facingEdgeStroke; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + if (!tile || tile.index < 0 || !tile.collides) + { + continue; + } + + if (this.debugSettings.collidingTileOverfill) + { + context.fillStyle = this.debugSettings.collidingTileOverfill; + context.fillRect(tx, ty, this._mc.cw, this._mc.ch); + } + + if (this.debugSettings.facingEdgeStroke) + { + context.beginPath(); + + if (tile.faceTop) + { + context.moveTo(tx, ty); + context.lineTo(tx + this._mc.cw, ty); + } + + if (tile.faceBottom) + { + context.moveTo(tx, ty + this._mc.ch); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + if (tile.faceLeft) + { + context.moveTo(tx, ty); + context.lineTo(tx, ty + this._mc.ch); + } + + if (tile.faceRight) + { + context.moveTo(tx + this._mc.cw, ty); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + context.closePath(); + + context.stroke(); + } + + } + + } + +}; + +/** +* Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size. +* +* @property {boolean} wrap +* @memberof Phaser.TilemapLayer +* @public +* @default false +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", { + + get: function () { + return this._wrap; + }, + + set: function (value) { + this._wrap = value; + this.dirty = true; + } + +}); + +/** +* Scrolls the map horizontally or returns the current x position. +* +* @property {number} scrollX +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", { + + get: function () { + return this._scrollX; + }, + + set: function (value) { + this._scrollX = value; + } + +}); + +/** +* Scrolls the map vertically or returns the current y position. +* +* @property {number} scrollY +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", { + + get: function () { + return this._scrollY; + }, + + set: function (value) { + this._scrollY = value; + } + +}); + +/** +* The width of the collision tiles (in pixels). +* +* @property {integer} collisionWidth +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", { + + get: function () { + return this._mc.cw; + }, + + set: function (value) { + this._mc.cw = value | 0; + this.dirty = true; + } + +}); + +/** +* The height of the collision tiles (in pixels). +* +* @property {integer} collisionHeight +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", { + + get: function () { + return this._mc.ch; + }, + + set: function (value) { + this._mc.ch = value | 0; + this.dirty = true; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. +* +* @class Phaser.TilemapParser +* @static +*/ +Phaser.TilemapParser = { + + /** + * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or + * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type + * depends how this should be configured. If you've a large sparsely populated map and the tile + * data doesn't need to change then setting this value to `true` will help with memory consumption. + * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes + * during the game) then leave the default value set. + * + * @constant + * @type {boolean} + */ + INSERT_NULL: false, + + /** + * Parse tilemap data from the cache and creates data for a Tilemap object. + * + * @method Phaser.TilemapParser.parse + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {string} key - The key of the tilemap in the Cache. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {object} The parsed map object. + */ + parse: function (game, key, tileWidth, tileHeight, width, height) { + + if (tileWidth === undefined) { tileWidth = 32; } + if (tileHeight === undefined) { tileHeight = 32; } + if (width === undefined) { width = 10; } + if (height === undefined) { height = 10; } + + if (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); + } + + }, + + /** + * Parses a CSV file into valid map data. + * + * @method Phaser.TilemapParser.parseCSV + * @param {string} key - The name you want to give the map data. + * @param {string} data - The CSV file data. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @return {object} Generated map data. + */ + parseCSV: function (key, data, tileWidth, tileHeight) { + + var map = this.getEmptyData(); + + // Trim any rogue whitespace from the data + data = data.trim(); + + var output = []; + var rows = data.split("\n"); + var height = rows.length; + var width = 0; + + for (var y = 0; y < rows.length; y++) + { + output[y] = []; + + var column = rows[y].split(","); + + for (var x = 0; x < column.length; x++) + { + output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight); + } + + if (width === 0) + { + width = column.length; + } + } + + map.format = Phaser.Tilemap.CSV; + map.name = key; + map.width = width; + map.height = height; + map.tileWidth = tileWidth; + map.tileHeight = tileHeight; + map.widthInPixels = width * tileWidth; + map.heightInPixels = height * tileHeight; + + map.layers[0].width = width; + map.layers[0].height = height; + map.layers[0].widthInPixels = map.widthInPixels; + map.layers[0].heightInPixels = map.heightInPixels; + map.layers[0].data = output; + + return map; + + }, + + /** + * Returns an empty map data object. + * + * @method Phaser.TilemapParser.getEmptyData + * @return {object} Generated map data. + */ + getEmptyData: function (tileWidth, tileHeight, width, height) { + + return { + width: (width !== undefined && width !== null) ? width : 0, + height: (height !== undefined && height !== null) ? height : 0, + tileWidth: (tileWidth !== undefined && tileWidth !== null) ? tileWidth : 0, + tileHeight: (tileHeight !== undefined && tileHeight !== null) ? tileHeight : 0, + orientation: 'orthogonal', + version: '1', + properties: {}, + widthInPixels: 0, + heightInPixels: 0, + layers: [ + { + name: 'layer', + x: 0, + y: 0, + width: 0, + height: 0, + widthInPixels: 0, + heightInPixels: 0, + alpha: 1, + visible: true, + properties: {}, + indexes: [], + callbacks: [], + bodies: [], + data: [] + } + ], + images: [], + objects: {}, + collision: {}, + tilesets: [], + tiles: [] + }; + + }, + + _slice: function(obj, fields) { + var sliced = {}; + + for (var k in fields) + { + var key = fields[k]; + + if (typeof obj[key] !== 'undefined') + { + sliced[key] = obj[key]; + } + } + + return sliced; + }, + + /** + * Parses an object group in Tiled JSON files. Object groups can be found in both layers and tilesets. Called internally in parseTiledJSON. + * @method Phaser.TilemapParser.parseObjectGroup + * @param {object} objectGroup - A JSON object group. + * @param {object} objectsCollection - An object into which new array of Tiled map objects will be added. + * @param {object} collisionCollection - An object into which new array of collision objects will be added. Currently only polylines are added. + * @param {string} [nameKey=objectGroup.name] - Key under which to store objects in collisions in objectsCollection and collisionCollection + * @param {object} [relativePosition={x: 0, y: 0}] - Coordinates the object group's position is relative to. + * @return {object} A object literal containing the objectsCollection and collisionCollection + */ + parseObjectGroup: function(objectGroup, objectsCollection, collisionCollection, nameKey, relativePosition) { + + var nameKey = nameKey || objectGroup.name; + var relativePosition = relativePosition || {x: 0, y: 0}; + var slice = this._slice; + + if (!nameKey) + { + console.warn('No name found for objectGroup', objectGroup); + } + + if (relativePosition.x === undefined || relativePosition.y === undefined) + { + console.warn('Malformed xy properties in relativePosition', relativePosition); + } + + objectsCollection[nameKey] = objectsCollection[nameKey] || []; + collisionCollection[nameKey] = collisionCollection[nameKey] || []; + + for (var v = 0, len = objectGroup.objects.length; v < len; v++) + { + var o = objectGroup.objects[v]; + + // Object Tiles + if (o.gid) + { + var object = { + gid: o.gid, + name: o.name, + type: o.type || '', + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + objectsCollection[nameKey].push(object); + } + else if (o.polyline) + { + var object = { + name: o.name, + type: o.type, + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + object.polyline = []; + + // Parse the polyline into an array + for (var p = 0; p < o.polyline.length; p++) + { + object.polyline.push([o.polyline[p].x, o.polyline[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // polygon + else if (o.polygon) + { + var object = slice(o, ['name', 'type', 'x', 'y', 'visible', 'rotation', 'properties']); + + object.x += relativePosition.x; + object.y += relativePosition.y; + + // Parse the polygon into an array + object.polygon = []; + + for (var p = 0; p < o.polygon.length; p++) + { + object.polygon.push([o.polygon[p].x, o.polygon[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // ellipse + else if (o.ellipse) + { + var object = slice(o, ['name', 'type', 'ellipse', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // otherwise it's a rectangle + else + { + var object = slice(o, ['name', 'type', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + object.rectangle = true; + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + } + + return { + objectsCollection: objectsCollection, + collisionCollection: collisionCollection + }; + }, + + /** + * Parses a Tiled JSON file into valid map data. + * @method Phaser.TilemapParser.parseTiledJSON + * @param {object} json - The JSON map data. + * @return {object} Generated and parsed map data. + */ + parseTiledJSON: function (json) { + + if (json.orientation !== 'orthogonal') + { + console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser'); + return null; + } + + // Map data will consist of: layers, objects, images, tilesets, sizes + var map = { + width: json.width, + height: json.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + orientation: json.orientation, + format: Phaser.Tilemap.TILED_JSON, + version: json.version, + properties: json.properties, + widthInPixels: json.width * json.tilewidth, + heightInPixels: json.height * json.tileheight + }; + + // Tile Layers + var layers = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'tilelayer') + { + continue; + } + + var curl = json.layers[i]; + + // Base64 decode data if necessary + // NOTE: uncompressed base64 only. + + if (!curl.compression && curl.encoding && curl.encoding === 'base64') + { + var binaryString = window.atob(curl.data); + var len = binaryString.length; + var bytes = new Array(len); + + // Interpret binaryString as an array of bytes representing + // little-endian encoded uint32 values. + for (var j = 0; j < len; j+=4) + { + bytes[j / 4] = ( + binaryString.charCodeAt(j) | + binaryString.charCodeAt(j + 1) << 8 | + binaryString.charCodeAt(j + 2) << 16 | + binaryString.charCodeAt(j + 3) << 24 + ) >>> 0; + } + + curl.data = bytes; + + delete curl.encoding; + } + else if (curl.compression) + { + console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\''); + continue; + } + + var layer = { + + name: curl.name, + x: curl.x, + y: curl.y, + width: curl.width, + height: curl.height, + widthInPixels: curl.width * json.tilewidth, + heightInPixels: curl.height * json.tileheight, + alpha: curl.opacity, + offsetX: curl.offsetx, + offsetY: curl.offsety, + visible: curl.visible, + properties: {}, + indexes: [], + callbacks: [], + bodies: [] + + }; + + if (curl.properties) + { + layer.properties = curl.properties; + } + + var x = 0; + var row = []; + var output = []; + var rotation, flipped, flippedVal, gid; + + // Loop through the data field in the JSON. + + // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV) + // If the map contains multiple tilesets then the indexes are relative to that which the set starts from. + // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset. + + for (var t = 0, len = curl.data.length; t < len; t++) + { + rotation = 0; + flipped = false; + gid = curl.data[t]; + flippedVal = 0; + + // If true the current tile is flipped or rotated (Tiled TMX format) + if (gid > 0x20000000) + { + // FlippedX + if (gid > 0x80000000) + { + gid -= 0x80000000; + flippedVal += 4; + } + + // FlippedY + if (gid > 0x40000000) + { + gid -= 0x40000000; + flippedVal += 2; + } + + // FlippedAD (anti-diagonal = top-right is swapped with bottom-left corners) + if (gid > 0x20000000) + { + gid -= 0x20000000; + flippedVal += 1; + } + + switch (flippedVal) + { + case 5: + rotation = Math.PI / 2; + break; + + case 6: + rotation = Math.PI; + break; + + case 3: + rotation = 3 * Math.PI / 2; + break; + + case 4: + rotation = 0; + flipped = true; + break; + + case 7: + rotation = Math.PI / 2; + flipped = true; + break; + + case 2: + rotation = Math.PI; + flipped = true; + break; + + case 1: + rotation = 3 * Math.PI / 2; + flipped = true; + break; + } + } + + // index, x, y, width, height + if (gid > 0) + { + var tile = new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight); + + tile.rotation = rotation; + tile.flipped = flipped; + + if (flippedVal !== 0) + { + // The WebGL renderer uses this to flip UV coordinates before drawing + tile.flippedVal = flippedVal; + } + + row.push(tile); + } + else + { + if (Phaser.TilemapParser.INSERT_NULL) + { + row.push(null); + } + else + { + row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight)); + } + } + + x++; + + if (x === curl.width) + { + output.push(row); + x = 0; + row = []; + } + } + + layer.data = output; + + layers.push(layer); + } + + map.layers = layers; + + // Images + var images = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'imagelayer') + { + continue; + } + + var curi = json.layers[i]; + + var image = { + + name: curi.name, + image: curi.image, + x: curi.x, + y: curi.y, + alpha: curi.opacity, + visible: curi.visible, + properties: {} + + }; + + if (curi.properties) + { + image.properties = curi.properties; + } + + images.push(image); + + } + + map.images = images; + + // Tilesets & Image Collections + var tilesets = []; + var tilesetGroupObjects = {}; + var imagecollections = []; + var lastSet = null; + + for (var i = 0; i < json.tilesets.length; i++) + { + // name, firstgid, width, height, margin, spacing, properties + var set = json.tilesets[i]; + + if (set.source) + { + console.warn('Phaser.TilemapParser - Phaser can\'t load external tilesets (%s). Use the Embed Tileset button and then export the map again.', set.source); + } + else if (set.image) + { + var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + if (set.tileproperties) + { + newSet.tileProperties = set.tileproperties; + } + + // For a normal sliced tileset the row/count/size information is computed when updated. + // This is done (again) after the image is set. + newSet.updateTileData(set.imagewidth, set.imageheight); + + tilesets.push(newSet); + } + else if (set.tiles) + { + var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + for (var ti in set.tiles) + { + var image = set.tiles[ti].image; + var gid = set.firstgid + parseInt(ti, 10); + newCollection.addImage(gid, image); + } + + imagecollections.push(newCollection); + } + else + { + throw new Error('Tileset ' + set.name + ' has no `image` or `tiles` property.'); + } + + // build a temporary object for objectgroups found in the tileset's tiles + for (var ti in set.tiles) + { + var objectGroup = set.tiles[ti].objectgroup; + + if (!objectGroup) + { + continue; + } + + tilesetGroupObjects[parseInt(ti, 10) + set.firstgid] = objectGroup; + } + + // We've got a new Tileset, so set the lastgid into the previous one + if (lastSet) + { + lastSet.lastgid = set.firstgid - 1; + } + + lastSet = set; + } + + if (tilesets.length === 0 && imagecollections.length === 0) + { + throw new Error('This tilemap has no tilesets.'); + } + + map.tilesets = tilesets; + map.imagecollections = imagecollections; + + // Objects & Collision Data (polylines, etc) + var objects = {}; + var collision = {}; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'objectgroup') + { + continue; + } + + var objectGroup = json.layers[i]; + this.parseObjectGroup(objectGroup, objects, collision); + } + + map.objects = objects; + map.collision = collision; + + map.tiles = []; + + // Finally lets build our super tileset index + for (var i = 0; i < map.tilesets.length; i++) + { + var set = map.tilesets[i]; + + var x = set.tileMargin; + var y = set.tileMargin; + + var count = 0; + var countX = 0; + var countY = 0; + + for (var t = set.firstgid; t < set.firstgid + set.total; t++) + { + // Can add extra properties here as needed + map.tiles[t] = [x, y, i]; + + x += set.tileWidth + set.tileSpacing; + + count++; + + if (count === set.total) + { + break; + } + + countX++; + + if (countX === set.columns) + { + x = set.tileMargin; + y += set.tileHeight + set.tileSpacing; + + countX = 0; + countY++; + + if (countY === set.rows) + { + break; + } + } + } + + } + + // assign tile properties + + var layer; + var tile; + var sid; + var set; + + // go through each of the map data layers + for (var i = 0; i < map.layers.length; i++) + { + layer = map.layers[i]; + collision[layer.name] = []; + set = null; + + // rows of tiles + for (var j = 0; j < layer.data.length; j++) + { + row = layer.data[j]; + + // individual tiles + for (var k = 0; k < row.length; k++) + { + tile = row[k]; + + if (tile === null || tile.index < 0) + { + continue; + } + + // find the relevant tileset + + sid = map.tiles[tile.index][2]; + set = map.tilesets[sid]; + + + // if that tile type has any properties, add them to the tile object + + if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) + { + tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties); + } + + var objectGroup = tilesetGroupObjects[tile.index]; + if (objectGroup) + { + // build collisions and objects for objectgroups found in the tileset's tiles + this.parseObjectGroup( + objectGroup, + map.objects, + map.collision, + tile.layer.name, + { + x: tile.worldX + objectGroup.x, + y: tile.worldY + objectGroup.y + }); + } + + } + } + } + + return map; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile set is a combination of an image containing the tiles and collision data per tile. +* +* Tilesets are normally created automatically when Tiled data is loaded. +* +* @class Phaser.Tileset +* @constructor +* @param {string} name - The name of the tileset in the map data. +* @param {integer} firstgid - The first tile index this tileset contains. +* @param {integer} [width=32] - Width of each tile (in pixels). +* @param {integer} [height=32] - Height of each tile (in pixels). +* @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels). +* @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels). +* @param {object} [properties={}] - Custom Tileset properties. +*/ +Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Tileset. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first tile index this Tileset contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of each tile (in pixels). + * @property {integer} tileWidth + * @readonly + */ + this.tileWidth = width | 0; + + /** + * The height of each tile (in pixels). + * @property {integer} tileHeight + * @readonly + */ + this.tileHeight = height | 0; + + /** + * The margin around the tiles in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileMarge + * @readonly + */ + // Modified internally + this.tileMargin = margin | 0; + + /** + * The spacing between each tile in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileSpacing + * @readonly + */ + this.tileSpacing = spacing | 0; + + /** + * Tileset-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set. + * @property {?object} image + * @readonly + */ + // Modified internally + this.image = null; + + /** + * The number of tile rows in the the tileset. + * @property {integer} + * @readonly + */ + // Modified internally + this.rows = 0; + + /** + * The number of tile columns in the tileset. + * @property {integer} columns + * @readonly + */ + // Modified internally + this.columns = 0; + + /** + * The total number of tiles in the tileset. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; + + /** + * The look-up table to specific tile image offsets. + * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1. + * @property {integer[]} drawCoords + * @private + */ + this.drawCoords = []; + +}; + +Phaser.Tileset.prototype = { + + /** + * Draws a tile from this Tileset at the given coordinates on the context. + * + * @method Phaser.Tileset#draw + * @public + * @param {CanvasRenderingContext2D} context - The context to draw the tile onto. + * @param {number} x - The x coordinate to draw to. + * @param {number} y - The y coordinate to draw to. + * @param {integer} index - The index of the tile within the set to draw. + */ + draw: function (context, x, y, index) { + + // Correct the tile index for the set and bias for interlacing + var coordIndex = (index - this.firstgid) << 1; + + if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length) + { + context.drawImage( + this.image, + this.drawCoords[coordIndex], + this.drawCoords[coordIndex + 1], + this.tileWidth, + this.tileHeight, + x, + y, + this.tileWidth, + this.tileHeight + ); + } + + }, + + /** + * Returns true if and only if this tileset contains the given tile index. + * + * @method Phaser.Tileset#containsTileIndex + * @public + * @param {number} tileIndex + * @return {boolean} True if this tileset contains the given index. + */ + containsTileIndex: function (tileIndex) { + + return ( + tileIndex >= this.firstgid && + tileIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Set the image associated with this Tileset and update the tile data. + * + * @method Phaser.Tileset#setImage + * @public + * @param {Image} image - The image that contains the tiles. + */ + setImage: function (image) { + + this.image = image; + this.updateTileData(image.width, image.height); + + }, + + /** + * Sets tile spacing and margins. + * + * @method Phaser.Tileset#setSpacing + * @public + * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels). + */ + setSpacing: function (margin, spacing) { + + this.tileMargin = margin | 0; + this.tileSpacing = spacing | 0; + + if (this.image) + { + this.updateTileData(this.image.width, this.image.height); + } + + }, + + /** + * Updates tile coordinates and tileset data. + * + * @method Phaser.Tileset#updateTileData + * @private + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + */ + updateTileData: function (imageWidth, imageHeight) { + + // May be fractional values + var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); + var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); + + if (rowCount % 1 !== 0 || colCount % 1 !== 0) + { + console.warn( + "Phaser.Tileset - '%s' image tile area (%s x %s) is not a whole multiple of tile size (%s x %s + %s + %s)", + this.name, imageWidth, imageHeight, this.tileWidth, this.tileHeight, this.tileMargin, this.tileSpacing + ); + } + + // In Tiled a tileset image that is not an even multiple of the tile dimensions + // is truncated - hence the floor when calculating the rows/columns. + rowCount = Math.floor(rowCount); + colCount = Math.floor(colCount); + + if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount)) + { + console.warn( + "Phaser.Tileset - Tile layout from image '%s' (%s rows by %s columns) differs from tileset '%s' (%s rows by %s columns)", + this.image.name, colCount, rowCount, this.name, this.columns, this.rows + ); + } + + this.rows = rowCount; + this.columns = colCount; + this.total = rowCount * colCount; + + this.drawCoords.length = 0; + + var tx = this.tileMargin; + var ty = this.tileMargin; + + for (var y = 0; y < this.rows; y++) + { + for (var x = 0; x < this.columns; x++) + { + this.drawCoords.push(tx); + this.drawCoords.push(ty); + tx += this.tileWidth + this.tileSpacing; + } + + tx = this.tileMargin; + ty += this.tileHeight + this.tileSpacing; + } + + } + +}; + +Phaser.Tileset.prototype.constructor = Phaser.Tileset; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. +* +* @class Phaser.Particle +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Particle = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + /** + * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData. + * @protected + */ + this.autoScale = false; + + /** + * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.scaleData = null; + + /** + * @property {number} _s - Internal cache var for tracking auto scale. + * @private + */ + this._s = 0; + + /** + * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. + * @protected + */ + this.autoAlpha = false; + + /** + * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.alphaData = null; + + /** + * @property {number} _a - Internal cache var for tracking auto alpha. + * @private + */ + this._a = 0; + +}; + +Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Particle.prototype.constructor = Phaser.Particle; + +/** +* Updates the Particle scale or alpha if autoScale and autoAlpha are set. +* +* @method Phaser.Particle#update +* @memberof 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; + } + } + +}; + +/** +* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. +* +* @method Phaser.Particle#onEmit +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.onEmit = function() { +}; + +/** +* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. +* +* @method Phaser.Particle#setAlphaData +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.setAlphaData = function(data) { + + this.alphaData = data; + this._a = data.length - 1; + this.alpha = this.alphaData[this._a].v; + this.autoAlpha = true; + +}; + +/** +* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. +* +* @method Phaser.Particle#setScaleData +* @memberof Phaser.Particle +*/ +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; + +}; + +/** +* Resets the Particle. This places the Particle at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. +* If the Particle has a physics body that too is reset. +* +* @method Phaser.Particle#reset +* @memberof Phaser.Particle +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {number} [health=1] - The health to give the Particle. +* @return {Phaser.Particle} This instance. +*/ +Phaser.Particle.prototype.reset = function(x, y, health) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y, health); + + this.alpha = 1; + this.scale.set(1); + + this.autoScale = false; + this.autoAlpha = false; + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Particles tracks any Emitters attached to it. +* +* @class Phaser.Particles +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Particles = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} emitters - Internal emitters store. + */ + this.emitters = {}; + + /** + * @property {number} ID - + * @default + */ + this.ID = 0; + +}; + +Phaser.Particles.prototype = { + + /** + * Adds a new Particle Emitter to the Particle Manager. + * @method Phaser.Particles#add + * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. + * @return {Phaser.Emitter} The emitter that was added. + */ + add: function (emitter) { + this.emitters[emitter.id] = emitter; + return emitter; + }, + + /** + * Removes an existing Particle Emitter from the Particle Manager. + * @method Phaser.Particles#remove + * @param {Phaser.Emitter} emitter - The emitter to remove. + */ + remove: function (emitter) { + delete this.emitters[emitter.id]; + } + +}; + +Phaser.Particles.prototype.constructor = Phaser.Particles; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Arcade Particles is a Particle System integrated with Arcade Physics. +* +* @class Phaser.Particles.Arcade +*/ +Phaser.Particles.Arcade = {}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Emitter is a lightweight particle emitter that uses Arcade Physics. +* It can be used for one-time explosions or for continuous effects like rain and fire. +* All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. +* +* @class Phaser.Particles.Arcade.Emitter +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. +* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. +* @param {number} [maxParticles=50] - The total number of particles in this emitter. +*/ +Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { + + /** + * @property {number} maxParticles - The total number of particles in this emitter. + * @default + */ + this.maxParticles = maxParticles || 50; + + Phaser.Group.call(this, game); + + /** + * @property {number} _id - Internal ID for this emitter -- only used by the Particle System in most cases + * @private + */ + this._id = this.game.particles.ID++; + + /** + * @property {string} name - A handy string name for this emitter. Can be set to anything. + */ + this.name = 'emitter' + this.id; + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.EMITTER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * @property {Phaser.Rectangle} area - The {@link #setSize size} of the emitter's emit area. The **actual** emit area is a rectangle of this size centered on (emitX, emitY): `{x: this.left, y: this.top, width: this.area.width, height: this.area.height}`. Particles are generated at a random position within this area. + * @default + */ + this.area = new Phaser.Rectangle(x, y, 1, 1); + + /** + * @property {?number} minAngle - The minimum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #maxAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.minAngle = null; + + /** + * @property {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #minAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.maxAngle = null; + + /** + * @property {number} minSpeed - The minimum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.minSpeed = 0; + + /** + * @property {number} maxSpeed - The maximum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.maxSpeed = 100; + + /** + * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle. + * @default + */ + this.minParticleSpeed = new Phaser.Point(-100, -100); + + /** + * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle. + * @default + */ + this.maxParticleSpeed = new Phaser.Point(100, 100); + + /** + * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. + * @default + */ + this.minParticleScale = 1; + + /** + * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. + * @default + */ + this.maxParticleScale = 1; + + /** + * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0. + */ + this.scaleData = null; + + /** + * @property {number} minRotation - The minimum possible angular velocity of a particle. + * @default + */ + this.minRotation = -360; + + /** + * @property {number} maxRotation - The maximum possible angular velocity of a particle. + * @default + */ + this.maxRotation = 360; + + /** + * @property {number} minParticleAlpha - The minimum possible alpha value of a particle. + * @default + */ + this.minParticleAlpha = 1; + + /** + * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle. + * @default + */ + this.maxParticleAlpha = 1; + + /** + * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0. + */ + this.alphaData = null; + + /** + * @property {function} particleClass - For emitting your own particle class types. They must extend Phaser.Particle. + * @default + */ + this.particleClass = Phaser.Particle; + + /** + * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter. + */ + this.particleDrag = new Phaser.Point(); + + /** + * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false). + * @default + */ + this.frequency = 100; + + /** + * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. + * @default + */ + this.lifespan = 2000; + + /** + * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. + */ + this.bounce = new Phaser.Point(); + + /** + * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. + * @default + */ + this.on = false; + + /** + * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) + * @default + */ + this.particleAnchor = new Phaser.Point(0.5, 0.5); + + /** + * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) + * @default + */ + this.blendMode = Phaser.blendModes.NORMAL; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitX + */ + this.emitX = x; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitY + */ + this.emitY = y; + + /** + * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. + */ + this.autoScale = false; + + /** + * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. + */ + this.autoAlpha = false; + + /** + * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. + * @default + */ + this.particleBringToTop = false; + + /** + * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. + * @default + */ + this.particleSendToBack = false; + + /** + * @property {object} counts - Records emitter activity. + * @property {number} counts.emitted - How many particles were emitted during the last update. + * @property {number} counts.failed - How many particles could not be emitted during the last update (because no particles were available). + * @property {number} counts.totalEmitted - How many particles have been emitted. + * @property {number} counts.totalFailed - How many particles could not be emitted when they were due (because no particles were available). + */ + this.counts = { + emitted: 0, + failed: 0, + totalEmitted: 0, + totalFailed: 0 + }; + + /** + * @property {Phaser.Point} _gravity - Internal gravity value. + * @private + */ + this._gravity = new Phaser.Point(0, 100); + + /** + * @property {Phaser.Point} _minParticleScale - Internal particle scale var. + * @private + */ + this._minParticleScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} _maxParticleScale - Internal particle scale var. + * @private + */ + this._maxParticleScale = new Phaser.Point(1, 1); + + /** + * @property {number} _total - Internal helper for deciding how many particles to launch (via {@link #start}). + * @private + */ + this._total = 0; + + /** + * @property {number} _timer - Internal helper for deciding when to launch particles or kill them. + * @private + */ + this._timer = 0; + + /** + * @property {number} _counter - Internal counter for figuring out how many particles to launch. + * @private + */ + this._counter = 0; + + /** + * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update. + * @private + */ + this._flowQuantity = 0; + + /** + * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total (via {@link #flow}). + * @private + */ + this._flowTotal = 0; + + /** + * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time). + * @private + */ + this._explode = true; + + /** + * @property {any} _frames - Internal helper for the particle frame. + * @private + */ + this._frames = null; + +}; + +Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); +Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter; + +/** +* Called automatically by the game loop, decides when to launch particles and when to "die". +* +* @method Phaser.Particles.Arcade.Emitter#update +*/ +Phaser.Particles.Arcade.Emitter.prototype.update = function () { + + this.counts.emitted = 0; + this.counts.failed = 0; + + if (this.on && this.game.time.time >= this._timer) + { + this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion; + + if (this._flowTotal !== 0) + { + if (this._flowQuantity > 0) + { + for (var i = 0; i < this._flowQuantity; i++) + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + break; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._total > 0 && this._counter >= this._total) + { + this.on = false; + } + } + } + + } + + var i = this.children.length; + + while (i--) + { + if (this.children[i].exists) + { + this.children[i].update(); + } + } + +}; + +/** +* This function generates a new set of particles for use by this emitter. +* The particles are stored internally waiting to be emitted via Emitter.start. +* +* @method Phaser.Particles.Arcade.Emitter#makeParticles +* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. +* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random. +* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. +* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. +* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. +* @param {object} [particleArguments=null] - Custom arguments to pass to your particle class +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds, particleArguments) { + + if (frames === undefined) { frames = 0; } + if (quantity === undefined) { quantity = this.maxParticles; } + if (collide === undefined) { collide = false; } + if (collideWorldBounds === undefined) { collideWorldBounds = false; } + if (particleArguments === undefined) { particleArguments = null; } + + var particle; + var i = 0; + var rndKey = keys; + var rndFrame = frames; + this._frames = frames; + + if (quantity > this.maxParticles) + { + this.maxParticles = quantity; + } + + while (i < quantity) + { + if (Array.isArray(keys)) + { + rndKey = this.game.rnd.pick(keys); + } + + if (Array.isArray(frames)) + { + rndFrame = this.game.rnd.pick(frames); + } + + particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame, particleArguments); + + this.game.physics.arcade.enable(particle, false); + + particle.body.checkCollision.none = !collide; + particle.body.collideWorldBounds = collideWorldBounds; + particle.body.skipQuadTree = true; + + particle.exists = false; + particle.visible = false; + particle.anchor.copyFrom(this.particleAnchor); + + this.add(particle); + + i++; + } + + return this; + +}; + +/** +* Call this function to turn off all the particles and the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#kill +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.kill = function () { + + this.on = false; + this.alive = false; + this.exists = false; + + return this; + +}; + +/** +* Handy for bringing game objects "back to life". Just sets alive and exists back to true. +* +* @method Phaser.Particles.Arcade.Emitter#revive +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.revive = function () { + + this.alive = true; + this.exists = true; + + return this; + +}; + +/** +* Call this function to emit the given quantity of particles at all once (an explosion) +* +* @method Phaser.Particles.Arcade.Emitter#explode +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [quantity=this.maxParticles] - How many particles to launch. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) { + + if (quantity === undefined) { + quantity = this.maxParticles; + } + + this._flowTotal = 0; + + this.start(true, lifespan, 0, quantity, false); + + return this; + +}; + +/** +* Call this function to start emitting a flow of particles. +* `quantity` particles are released every interval of `frequency` ms until `total` particles have been released (or forever). +* If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 × 5 = 20 total) and then turn {@link #on off}. +* If you set the total to be -1 then no quantity cap is used and it will keep emitting (as long as there are inactive particles available). +* +* {@link #output}, {@link #lifespanOutput}, and {@link #remainder} describe the particle flow rate. +* During a stable flow, the number of active particles approaches {@link #lifespanOutput} and the number of inactive particles approaches {@link #remainder}. +* If {@link #remainder} is less than 0, there will likely be no particles available for a portion of the flow (see {@link #count}). +* +* @method Phaser.Particles.Arcade.Emitter#flow +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of particles, given in ms. Values between 0 and 16.66 will behave the same (60 releases per second). +* @param {number} [quantity=1] - How many particles to launch at each interval. Not larger than {@link #maxParticles}. +* @param {number} [total=-1] - Turn {@link #on off} after launching this many particles in total. If -1 it will carry on indefinitely. +* @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) { + + if (frequency === undefined || frequency === null) { frequency = 250; } + if (quantity === undefined || quantity === 0) { quantity = 1; } + if (total === undefined) { total = -1; } + if (immediate === undefined) { immediate = true; } + + if (quantity > this.maxParticles) + { + quantity = this.maxParticles; + } + + this._counter = 0; + this._flowQuantity = quantity; + this._flowTotal = total; + + if (immediate) + { + this.start(true, lifespan, frequency, quantity); + + this._counter += quantity; + this.on = true; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + else + { + this.start(false, lifespan, frequency, quantity); + } + + return this; + +}; + +/** +* Start emitting particles. +* +* {@link #explode} and {@link #flow} are simpler methods. +* +* There are two patterns, based on the `explode` argument: +* +* ##### explode=true +* +* start(true, lifespan=0, null, total) +* +* When `explode` is true or `forceQuantity` is true, `start` emits `total` particles immediately. You should pass a nonzero `total`. +* +* ##### explode=false +* +* start(false, lifespan=0, frequency=250, total=0) +* +* When `explode` is false and `forceQuantity` is false, `start` emits 1 particle every interval of `frequency` ms. If `total` is not zero, the emitter turns itself off after `total` particles have been released. If `total` is zero, the emitter keeps emitting particles as long as they are available. To emit more than 1 particle per flow interval, use {@link #flow} instead. +* +* `forceQuantity` seems equivalent to `explode` and can probably be avoided. +* +* @method Phaser.Particles.Arcade.Emitter#start +* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false). +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of 1 particle, when `explode` is false. Value given in ms. Ignored if `explode` is set to true. +* @param {number} [total=0] - Turn {@link #on off} after launching this many particles in total. +* @param {number} [forceQuantity=false] - Equivalent to `explodes`. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, total, forceQuantity) { + + if (explode === undefined) { explode = true; } + if (lifespan === undefined) { lifespan = 0; } + if (frequency === undefined || frequency === null) { frequency = 250; } + if (total === undefined) { total = 0; } + if (forceQuantity === undefined) { forceQuantity = false; } + + if (total > this.maxParticles) + { + total = this.maxParticles; + } + + this.revive(); + + this.visible = true; + + this.lifespan = lifespan; + this.frequency = frequency; + + if (explode || forceQuantity) + { + for (var i = 0; i < total; i++) + { + this.emitParticle(); + } + } + else + { + this.on = true; + this._total = total; + this._counter = 0; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + + return this; + +}; + +/** +* This function is used internally to emit the next particle in the queue. +* +* However it can also be called externally to emit a particle. +* +* When called externally you can use the arguments to override any defaults the Emitter has set. +* +* The newly emitted particle is available in {@link Phaser.Particles.Arcade.Emitter#cursor}. +* +* @method Phaser.Particles.Arcade.Emitter#emitParticle +* @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. +* @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {boolean} True if a particle was emitted, otherwise false. +*/ +Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + var particle = this.getNextParticle(); + + if (particle === null) + { + this.counts.failed++; + this.counts.totalFailed++; + + return false; + } + + this.counts.emitted++; + this.counts.totalEmitted++; + + var rnd = this.game.rnd; + + if (key !== undefined && frame !== undefined) + { + particle.loadTexture(key, frame); + } + else if (key !== undefined) + { + particle.loadTexture(key); + particle.frame = Array.isArray(this._frames) ? rnd.pick(this._frames) : this._frames; + } + + var emitX = this.emitX; + var emitY = this.emitY; + + if (x !== null) + { + emitX = x; + } + else if (this.width > 1) + { + emitX = rnd.between(this.left, this.right); + } + + if (y !== null) + { + emitY = y; + } + else if (this.height > 1) + { + emitY = rnd.between(this.top, this.bottom); + } + + this.resetParticle(particle, emitX, emitY); + + return true; + +}; + + +/** +* Helper for {@link #emitParticle}. Gets the next available particle. +* +* @private +* @return {?Phaser.Particle} The first particle with exists=false, or null +*/ +Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () { + + var i = this.length; + + while (i--) + { + var next = this.next(); + + if (!next.exists) + { + return next; + } + } + + return null; + +}; + +/** + * Helper for {@link #emitParticle}. Sets particle properties and calls {@link Particle#onEmit}. + * + * @private + * @param {Phaser.Particle} particle + * @param {number} x + * @param {number} y + */ +Phaser.Particles.Arcade.Emitter.prototype.resetParticle = function (particle, x, y) { + + var rnd = this.game.rnd; + + particle.reset(x, y); + + 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(rnd.realInRange(this.minParticleScale, this.maxParticleScale)); + } + else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y)) + { + particle.scale.set(rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y)); + } + else + { + particle.scale.set(this._minParticleScale.x, this._minParticleScale.y); + } + + if (this.autoAlpha) + { + particle.setAlphaData(this.alphaData); + } + else + { + particle.alpha = rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha); + } + + particle.blendMode = this.blendMode; + + var body = particle.body; + + body.updateBounds(); + + body.bounce.copyFrom(this.bounce); + body.drag.copyFrom(this.particleDrag); + + if (this.minAngle != null && this.maxAngle != null) + { + this.game.physics.arcade.velocityFromAngle( + (this.minAngle === this.maxAngle) ? this.minAngle : rnd.between(this.minAngle, this.maxAngle), + (this.minSpeed === this.maxSpeed) ? this.minSpeed : rnd.between(this.minSpeed, this.maxSpeed), + body.velocity + ); + } + else + { + body.velocity.x = rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x); + body.velocity.y = rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y); + } + + body.angularVelocity = rnd.between(this.minRotation, this.maxRotation); + body.gravity.copyFrom(this.gravity); + body.angularDrag = this.angularDrag; + + particle.onEmit(); + +}; + +/** +* Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. +* +* @method Phaser.Particles.Arcade.Emitter#destroy +*/ +Phaser.Particles.Arcade.Emitter.prototype.destroy = function () { + + this.game.particles.remove(this); + + Phaser.Group.prototype.destroy.call(this, true, false); + +}; + +/** +* A more compact way of setting the width and height of the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#setSize +* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). +* @param {number} height - The desired height of the emitter. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { + + this.area.width = width; + this.area.height = height; + + return this; + +}; + +/** +* A more compact way of setting the X velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setXSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.x = min; + this.maxParticleSpeed.x = max; + + return this; + +}; + +/** +* A more compact way of setting the Y velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setYSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.y = min; + this.maxParticleSpeed.y = max; + + return this; + +}; + +/** +* A more compact way of setting the angular velocity constraints of the particles. +* +* @method Phaser.Particles.Arcade.Emitter#setRotation +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minRotation = min; + this.maxRotation = max; + + return this; + +}; + +/** +* A more compact way of setting the alpha constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. +* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setAlpha +* @param {number} [min=1] - The minimum value for this range. +* @param {number} [max=1] - The maximum value for this range. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) { + + if (min === undefined) { min = 1; } + if (max === undefined) { max = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.alphaData.reverse(); + this.autoAlpha = true; + } + + return this; + +}; + +/** +* A more compact way of setting the scale constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. +* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setScale +* @param {number} [minX=1] - The minimum value of Particle.scale.x. +* @param {number} [maxX=1] - The maximum value of Particle.scale.x. +* @param {number} [minY=1] - The minimum value of Particle.scale.y. +* @param {number} [maxY=1] - The maximum value of Particle.scale.y. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) { + + if (minX === undefined) { minX = 1; } + if (maxX === undefined) { maxX = 1; } + if (minY === undefined) { minY = 1; } + if (maxY === undefined) { maxY = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (yoyo === undefined) { yoyo = false; } + + // Reset these + 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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.scaleData.reverse(); + this.autoScale = true; + } + + return this; + +}; + +/** + * Sets a radial pattern for emitting particles. + * + * This is a shorthand for setting {@link #minAngle}, {@link #maxAngle}, {@link #minSpeed}, and {@link #maxSpeed}. + * + * To remove the radial pattern, use `setAngle(null, null)`. + * + * @method Phaser.Particles.Arcade.Emitter#setAngle + * @param {?number} minAngle - The minimum angle of initial particle velocities, in degrees. + * @param {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. + * @param {number} [minSpeed] - The minimum initial particle speed. + * @param {number} [maxSpeed] - The maximum initial particle speed. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ +Phaser.Particles.Arcade.Emitter.prototype.setAngle = function (minAngle, maxAngle, minSpeed, maxSpeed) { + + this.minAngle = minAngle; + this.maxAngle = maxAngle; + + if (minSpeed != null) { this.minSpeed = minSpeed; } + if (maxSpeed != null) { this.maxSpeed = maxSpeed; } + + return this; + +}; + +/** +* Change the emitter's center to match the center of any object with a `center` property, such as an Arcade Body. +* If the object doesn't have a `center` property it will be set to the object's anchor-adjusted world position (`object.world`). +* +* @method Phaser.Particles.Arcade.Emitter#at +* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +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); + } + + return this; + +}; + +/** + * @name Phaser.Particles.Arcade.Emitter#gravity + * @property {Phaser.Point} gravity - Sets the `body.gravity` of each particle sprite to this on launch. + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "gravity", { + + get: function () { + return this._gravity; + }, + + set: function (value) { + if (typeof value === "number") + { + this._gravity.y = value; + } + else + { + this._gravity = value; + } + } + +}); + + +/** +* @name Phaser.Particles.Arcade.Emitter#id +* @property {number} id - Gets the internal ID that represents this emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "id", { + get: function () { + return this._id; + } +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#width +* @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", { + + get: function () { + return this.area.width; + }, + + set: function (value) { + this.area.width = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#height +* @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", { + + get: function () { + return this.area.height; + }, + + set: function (value) { + this.area.height = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#x +* @property {number} x - Gets or sets the x position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", { + + get: function () { + return this.emitX; + }, + + set: function (value) { + this.emitX = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#y +* @property {number} y - Gets or sets the y position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", { + + get: function () { + return this.emitY; + }, + + set: function (value) { + this.emitY = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#left +* @property {number} left - Gets the left position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", { + + get: function () { + return Math.floor(this.x - (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#right +* @property {number} right - Gets the right position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", { + + get: function () { + return Math.floor(this.x + (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#top +* @property {number} top - Gets the top position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", { + + get: function () { + return Math.floor(this.y - (this.area.height / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#bottom +* @property {number} bottom - Gets the bottom position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", { + + get: function () { + return Math.floor(this.y + (this.area.height / 2)); + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#output + * @property {number} output - The number of particles released per second, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "output", { + + get: function () { + return 1000 * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#lifespanOutput + * @property {number} lifespanOutput - The number of particles released during one particle's {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "lifespanOutput", { + + get: function () { + return (this.lifespan === 0 ? Infinity : this.lifespan) * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#remainder + * @property {number} remainder - The expected number of unreleased particles after a flow interval of {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "remainder", { + + get: function () { + return this.maxParticles - this.lifespanOutput; + } + +}); + +/** +* The last particle released, if any. +* +* You should treat this as read-only (and also avoid {@link #next} and {@link #previous}) once the emitter is started. Phaser uses it internally to track particles. +* +* @name Phaser.Particles.Arcade.Emitter#cursor +* @property {?DisplayObject} cursor +* @readonly +*/ +// Inherited from Phaser.Group#cursor + +/** +* Advances the cursor to the next particle. +* +* @method Phaser.Particles.Arcade.Emitter#next +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#next + +/** +* Moves the group cursor to the previous particle. +* +* @method Phaser.Particles.Arcade.Emitter#previous +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#previous + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Weapon Plugin provides the ability to easily create a bullet pool and manager. +* +* Weapons fire {@link Phaser.Bullet} objects, which are essentially Sprites with a few extra properties. +* The Bullets are enabled for {@link Phaser.Physics.Arcade Arcade Physics}. They do not currently work with P2 Physics. +* +* The Bullets are created inside of {@link #bullets weapon.bullets}, which is a {@link Phaser.Group} instance. Anything you +* can usually do with a Group, such as move it around the display list, iterate it, etc can be done +* to the bullets Group too. +* +* Bullets can have textures and even animations. You can control the speed at which they are fired, +* the firing rate, the firing angle, and even set things like gravity for them. +* +* A small example, using {@link Phaser.GameObjectFactory#weapon add.weapon}, assumed to be running from within a {@link Phaser.State#create} method: +* +* ```javascript +* var weapon = this.add.weapon(10, 'bullet'); +* weapon.fireFrom.set(300, 300); +* this.input.onDown.add(weapon.fire, this); +* ``` +* +* If you want to (re)create the bullet pool separately, you can use: +* +* ```javascript +* var weapon = this.game.plugins.add(Phaser.Weapon); +* // … +* weapon.createBullets(10, 'bullet'); +* ``` +* +* @class Phaser.Weapon +* @constructor +* @param {Phaser.Game} game - A reference to the current Phaser.Game instance. +* @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin. +*/ +Phaser.Weapon = function (game, parent) { + + Phaser.Plugin.call(this, game, parent); + + /** + * This is the Phaser.Group that contains all of the bullets managed by this plugin. + * @type {Phaser.Group} + */ + this.bullets = null; + + /** + * Should the bullet pool run out of bullets (i.e. they are all in flight) then this + * boolean controls if the Group will create a brand new bullet object or not. + * @type {boolean} + * @default + */ + this.autoExpandBulletsGroup = false; + + /** + * Will this weapon auto fire? If set to true then a new bullet will be fired + * based on the {@link #fireRate} value. + * @type {boolean} + * @default + */ + this.autofire = false; + + /** + * The total number of bullets this Weapon has fired so far. + * You can limit the number of shots allowed (via {@link #fireLimit}), and reset + * this total via {@link #resetShots}. + * @type {number} + * @default + */ + this.shots = 0; + + /** + * The maximum number of shots that this Weapon is allowed to fire before it stops. + * When the limit is his the {@link #onFireLimit} Signal is dispatched. + * You can reset the shot counter via {@link #resetShots}. + * @type {number} + * @default + */ + this.fireLimit = 0; + + /** + * The minimum interval between shots, in milliseconds. + * @type {number} + * @default + */ + this.fireRate = 100; + + /** + * This is a modifier that is added to the {@link #fireRate} each update to add variety + * to the firing rate of the Weapon. The value is given in milliseconds. + * If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual + * firing rate of the Weapon will be between 150 and 250. + * @type {number} + * @default + */ + this.fireRateVariance = 0; + + /** + * This is a Rectangle from within which the bullets are fired. By default it's a 1x1 + * rectangle, the equivalent of a Point. But you can change the width and height, and if + * larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from. + * @type {Phaser.Rectangle} + */ + this.fireFrom = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE_UP + * or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right. + * @type {integer} + * @default + */ + this.fireAngle = Phaser.ANGLE_UP; + + /** + * When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set. + * @type {boolean} + * @default + */ + this.bulletInheritSpriteSpeed = false; + + /** + * The string based name of the animation that the Bullet will be given on launch. + * This is set via {@link #addBulletAnimation}. + * @type {string} + * @default + */ + this.bulletAnimation = ''; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to pick a random frame from the set. + * @type {boolean} + * @default + */ + this.bulletFrameRandom = false; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to use the next frame in the set. The frame index is then + * advanced one frame until it reaches the end of the set, then it starts from the start + * again. Cycling frames like this allows you to create varied bullet effects via + * sprite sheets. + * @type {boolean} + * @default + */ + this.bulletFrameCycle = false; + + /** + * Should the Bullets wrap around the world bounds? This automatically calls + * `World.wrap` on the Bullet each frame. See the docs for that method for details. + * @type {boolean} + * @default + */ + this.bulletWorldWrap = false; + + /** + * If `bulletWorldWrap` is true then you can provide an optional padding value with this + * property. It's added to the calculations determining when the Bullet should wrap around + * the world or not. The value is given in pixels. + * @type {integer} + * @default + */ + this.bulletWorldWrapPadding = 0; + + /** + * An optional angle offset applied to the Bullets when they are launched. + * This is useful if for example your bullet sprites have been drawn facing up, instead of + * to the right, and you want to fire them at an angle. In which case you can set the + * angle offset to be 90 and they'll be properly rotated when fired. + * @type {number} + * @default + */ + this.bulletAngleOffset = 0; + + /** + * This is a variance added to the angle of Bullets when they are fired. + * If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual + * angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a + * great 'spread' effect to a Weapon. + * @type {number} + * @default + */ + this.bulletAngleVariance = 0; + + /** + * The initial velocity of fired bullets, in pixels per second. + * @type {number} + * @default + */ + this.bulletSpeed = 200; + + /** + * This is a variance added to the speed of Bullets when they are fired. + * If bullets have a {@link #bulletSpeed} value of 200, and a `bulletSpeedVariance` of 50 + * then the actual speed of the Bullets will be between 150 and 250 pixels per second. + * @type {number} + * @default + */ + this.bulletSpeedVariance = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount + * of lifespan the Bullets have set on launch. The value is given in milliseconds. + * When a Bullet hits its lifespan limit it will be automatically killed. + * @type {number} + * @default + */ + this.bulletLifespan = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_DISTANCE` this controls the distance + * the Bullet can travel before it is automatically killed. The distance is given in pixels. + * @type {number} + * @default + */ + this.bulletKillDistance = 0; + + /** + * This is the amount of {@link Phaser.Physics.Arcade.Body#gravity} added to the Bullets physics body when fired. + * Gravity is expressed in pixels / second / second. + * @type {Phaser.Point} + */ + this.bulletGravity = new Phaser.Point(0, 0); + + /** + * Bullets can optionally adjust their rotation in-flight to match their velocity. + * This can create the effect of a bullet 'pointing' to the path it is following, for example + * an arrow being fired from a bow, and works especially well when added to {@link #bulletGravity}. + * @type {boolean} + * @default + */ + this.bulletRotateToVelocity = false; + + /** + * The Texture Key that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string} + * @default + */ + this.bulletKey = ''; + + /** + * The Texture Frame that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string|integer} + * @default + */ + this.bulletFrame = ''; + + /** + * Private var that holds the public `bulletClass` property. + * @type {function} + * @private + */ + this._bulletClass = Phaser.Bullet; + + /** + * Private var that holds the public `bulletCollideWorldBounds` property. + * @type {boolean} + * @private + */ + this._bulletCollideWorldBounds = false; + + /** + * Private var that holds the public `bulletKillType` property. + * @type {integer} + * @private + */ + this._bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; + + /** + * Holds internal data about custom bullet body sizes. + * + * @type {Object} + * @private + */ + this._data = { + customBody: false, + width: 0, + height: 0, + offsetX: 0, + offsetY: 0 + }; + + /** + * This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not. + * It's used in combination with {@link #bulletKillType} when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS` + * or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored. + * If you are tracking a Sprite or Point then the bounds are centered on that object every frame. + * + * @type {Phaser.Rectangle} + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The Rectangle used to calculate the bullet bounds from. + * + * @type {Phaser.Rectangle} + * @private + */ + this.bulletBounds = game.world.bounds; + + /** + * This array stores the frames added via @link #setBulletFrames. + * + * @type {Array} + * @protected + */ + this.bulletFrames = []; + + /** + * The index of the frame within {@link #bulletFrames} that is currently being used. + * This value is only used if {@link #bulletFrameCycle} is set to `true`. + * @type {number} + * @private + */ + this.bulletFrameIndex = 0; + + /** + * An internal object that stores the animation data added via {@link #addBulletAnimation}. + * @type {Object} + * @private + */ + this.anims = {}; + + /** + * The onFire Signal is dispatched each time {@link #fire} is called, and a Bullet is + * _successfully_ launched. The callback is set two arguments: a reference to the bullet sprite itself, + * and a reference to the Weapon that fired the bullet. + * + * @type {Phaser.Signal} + */ + this.onFire = new Phaser.Signal(); + + /** + * The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result + * of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance. + * The callback is sent one argument: A reference to the bullet sprite itself. + * + * @type {Phaser.Signal} + */ + this.onKill = new Phaser.Signal(); + + /** + * The onFireLimit Signal is dispatched if {@link #fireLimit} is > 0, and a bullet launch takes the number + * of shots fired to equal the fire limit. + * The callback is sent two arguments: A reference to this Weapon, and the value of + * {@link #fireLimit}. + * + * @type {Phaser.Signal} + */ + this.onFireLimit = new Phaser.Signal(); + + /** + * The Sprite currently being tracked by the Weapon, if any. + * This is set via the {@link #trackSprite} method. + * + * @type {Phaser.Sprite|Object} + */ + this.trackedSprite = null; + + /** + * The Pointer currently being tracked by the Weapon, if any. + * This is set via the {@link #trackPointer} method. + * + * @type {Phaser.Pointer} + */ + this.trackedPointer = null; + + /** + * If you want this Weapon to be able to fire more than 1 bullet in a single + * update, then set this property to `true`. When `true` the Weapon plugin won't + * set the shot / firing timers until the `postRender` phase of the game loop. + * This means you can call `fire` (and similar methods) as often as you like in one + * single game update. + * + * @type {boolean} + * @default + */ + this.multiFire = false; + + /** + * Internal multiFire test flag. + * + * @type {boolean} + */ + this._hasFired = false; + + /** + * If the Weapon is tracking a Sprite, should it also track the Sprites rotation? + * This is useful for a game such as Asteroids, where you want the weapon to fire based + * on the sprites rotation. + * + * @type {boolean} + * @default + */ + this.trackRotation = false; + + /** + * The Track Offset is a Point object that allows you to specify a pixel offset that bullets use + * when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels + * in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have + * the bullet launched from the center of the Sprite. + * + * @type {Phaser.Point} + */ + this.trackOffset = new Phaser.Point(); + + /** + * Internal firing rate time tracking variable. + * + * @type {number} + * @private + */ + this._nextFire = 0; + + /** + * Internal firing rate time tracking variable used by multiFire. + * + * @type {number} + * @private + */ + this._tempNextFire = 0; + + /** + * Internal firing rotation tracking point. + * + * @type {Phaser.Point} + * @private + */ + this._rotatedPoint = new Phaser.Point(); + +}; + +Phaser.Weapon.prototype = Object.create(Phaser.Plugin.prototype); +Phaser.Weapon.prototype.constructor = Phaser.Weapon; + +/** +* A {@link #bulletKillType} constant that stops the bullets from ever being destroyed automatically. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_NEVER = 0; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when their {@link #bulletLifespan} expires. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_LIFESPAN = 1; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets after they +* exceed the {@link #bulletDistance} from their original firing position. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_DISTANCE = 2; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WEAPON_BOUNDS = 3; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.Camera#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_CAMERA_BOUNDS = 4; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.World#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WORLD_BOUNDS = 5; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_STATIC_BOUNDS = 6; + +/** +* This method performs two actions: First it will check to see if the {@link #bullets} Group exists or not, +* and if not it creates it, adding it the `group` given as the 4th argument. +* +* Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame +* provided (if any). +* +* If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets +* in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of +* the in-flight bullets have been killed, freeing them up for use by the Weapon again. +* +* If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will +* keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however, +* so be careful it doesn't grow too large. +* +* You can either set the texture key and frame here, or via the {@link #bulletKey} and {@link #bulletFrame} +* properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a +* single Weapon instance must share the same texture key however. +* +* @method Phaser.Weapon#createBullets +* @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. +* @param {string} [key] - The Game.cache key of the image that this Sprite will use. +* @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. +* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.createBullets = function (quantity, key, frame, group) { + + if (quantity === undefined) { quantity = 1; } + if (group === undefined) { group = this.game.world; } + + if (this.bullets && !this.bullets.game) + { + this.bullets = null; + } + + if (!this.bullets) + { + this.bullets = this.game.add.physicsGroup(Phaser.Physics.ARCADE, group); + this.bullets.classType = this._bulletClass; + } + + if (quantity !== 0) + { + if (quantity === -1) + { + this.autoExpandBulletsGroup = true; + quantity = 1; + } + + this.bullets.createMultiple(quantity, key, frame); + + this.bullets.setAll('data.bulletManager', this); + + this.bulletKey = key; + this.bulletFrame = frame; + } + + return this; + +}; + +/** +* Call a function on each in-flight bullet in this Weapon. +* +* See {@link Phaser.Group#forEachExists forEachExists} for more details. +* +* @method Phaser.Weapon#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.forEach = function (callback, callbackContext) { + + this.bullets.forEachExists(callback, callbackContext, arguments); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `false` on each bullet in this Weapon. +* This has the effect of stopping them in-flight should they be moving. +* It also stops them being able to be checked for collision. +* +* @method Phaser.Weapon#pauseAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.pauseAll = function () { + + this.bullets.setAll('body.enable', false); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `true` on each bullet in this Weapon. +* This has the effect of resuming their motion should they be in-flight. +* It also enables them for collision checks again. +* +* @method Phaser.Weapon#resumeAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resumeAll = function () { + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Calls {@link Phaser.Bullet#kill} on every in-flight bullet in this Weapon. +* Also re-enables their physics bodies, should they have been disabled via {@link #pauseAll}. +* +* @method Phaser.Weapon#killAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.killAll = function () { + + this.bullets.callAllExists('kill', true); + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Resets the {@link #shots} counter back to zero. This is used when you've set +* {@link #fireLimit} and have hit (or just wish to reset) your limit. +* +* @method Phaser.Weapon#resetShots +* @param {integer} [newLimit] - Optionally set a new {@link #fireLimit}. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resetShots = function (newLimit) { + + this.shots = 0; + + if (newLimit !== undefined) + { + this.fireLimit = newLimit; + } + + return this; + +}; + +/** +* Destroys this Weapon. It removes itself from the PluginManager, destroys +* the {@link #bullets} Group, and nulls internal references. +* +* @method Phaser.Weapon#destroy +*/ +Phaser.Weapon.prototype.destroy = function () { + + this.parent.remove(this, false); + + this.bullets.destroy(); + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#update +* @protected +*/ +Phaser.Weapon.prototype.update = function () { + + if (this._bulletKillType === Phaser.Weapon.KILL_WEAPON_BOUNDS) + { + if (this.trackedSprite) + { + this.trackedSprite.updateTransform(); + this.bounds.centerOn(this.trackedSprite.worldPosition.x, this.trackedSprite.worldPosition.y); + } + else if (this.trackedPointer) + { + this.bounds.centerOn(this.trackedPointer.worldX, this.trackedPointer.worldY); + } + } + + if (this.autofire) + { + this.fire(); + } + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#postRender +* @protected +*/ +Phaser.Weapon.prototype.postRender = function () { + + if (!this.multiFire || !this._hasFired) + { + return; + } + + this._hasFired = false; + + this._nextFire = this._tempNextFire; + +}; + +/** +* Sets this Weapon to track the given Sprite, or any Object with a public {@link Phaser.Component.Core#world world} Point object. +* When a Weapon tracks a Sprite it will automatically update its {@link #fireFrom} value to match the Sprite's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location. +* +* Calling `trackSprite` will reset {@link #trackedPointer} to null, should it have been set, as you can +* only track _either_ a Sprite, or a Pointer, at once, but not both. +* +* @method Phaser.Weapon#trackSprite +* @param {Phaser.Sprite|Object} sprite - The Sprite to track the position of. +* @param {integer} [offsetX=0] - The horizontal offset from the Sprites position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Sprites position to be applied to the Weapon. +* @param {boolean} [trackRotation=false] - Should the Weapon also track the Sprites rotation? +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackSprite = function (sprite, offsetX, offsetY, trackRotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (trackRotation === undefined) { trackRotation = false; } + + this.trackedPointer = null; + this.trackedSprite = sprite; + this.trackRotation = trackRotation; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Sets this Weapon to track the given Pointer. +* When a Weapon tracks a Pointer it will automatically update its {@link #fireFrom} value to match the Pointer's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location. +* +* Calling `trackPointer` will reset {@link #trackedSprite} to null, should it have been set, as you can +* only track _either_ a Pointer, or a Sprite, at once, but not both. +* +* @method Phaser.Weapon#trackPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to track the position of. Defaults to `Input.activePointer` if not specified. +* @param {integer} [offsetX=0] - The horizontal offset from the Pointers position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Pointers position to be applied to the Weapon. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackPointer = function (pointer, offsetX, offsetY) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this.trackedPointer = pointer; + this.trackedSprite = null; + this.trackRotation = false; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Attempts to fire multiple bullets from the positions defined in the given array. +* +* If you provide a `from` argument, or if there is a tracked Sprite or Pointer, then +* the positions are treated as __offsets__ from the given objects position. +* +* If `from` is undefined, and there is no tracked object, then the bullets are fired +* from the given positions, as they exist in the world. +* +* Calling this method sets {@link #multiFire} to `true`. +* +* If there are not enough bullets available in the pool, and the pool cannot be extended, +* then this method may not fire from all of the given positions. +* +* When the bullets are launched they have their texture and frame updated, as required. +* The velocity of the bullets are calculated based on Weapon properties like {@link #bulletSpeed}. +* +* @method Phaser.Weapon#fireMany +* @param {array} positions - An array of positions. Each position can be any Object, as long as it has public `x` and `y` properties, such as Phaser.Point, { x: 0, y: 0 }, Phaser.Sprite, etc. +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullets **from** the `x` and `y` properties of this object, _instead_ of any {@link #trackedSprite} or `trackedPointer` that is set. +* @return {array} An array containing all of the fired Phaser.Bullet objects, if a launch was successful, otherwise an empty array. +*/ +Phaser.Weapon.prototype.fireMany = function (positions, from) { + + this.multiFire = true; + + var bullets = []; + + var _this = this; + + if (from || this.trackedSprite || this.trackedPointer) + { + positions.forEach(function(offset) { + + bullets.push(_this.fire(from, null, null, offset.x, offset.y)); + + }); + } + else + { + positions.forEach(function(position) { + + bullets.push(_this.fire(position)); + + }); + } + + return bullets; + +}; + +/** +* Attempts to fire a single Bullet from a tracked Sprite or Pointer, but applies an offset +* to the position first. This is the same as calling {@link #fire} and passing in the offset arguments. +* +* If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like {@link #bulletSpeed}. +* +* If you wish to fire multiple bullets in a single game update, then set {@link #multiFire} to `true` +* and you can call this method as many times as you like, per loop. See also {@link #fireMany}. +* +* @method Phaser.Weapon#fireOffset +* @param {number} [offsetX=0] - The horizontal offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @param {number} [offsetY=0] - The vertical offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fireOffset = function (offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + return this.fire(null, null, null, offsetX, offsetY); + +}; + +/** +* Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at. +* +* If you don't provide any of the arguments then it uses those set via properties such as {@link #trackedSprite}, +* {@link #bulletAngle} and so on. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like `bulletSpeed`. +* +* If you wish to fire multiple bullets in a single game update, then set `Weapon.multiFire = true` +* and you can call `fire` as many times as you like, per loop. Multiple fires in a single update +* only counts once towards the `shots` total, but you will still receive a Signal for each bullet. +* +* @method Phaser.Weapon#fire +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides {@link #trackedSprite} or `trackedPointer`. Pass `null` to ignore it. +* @param {number} [x] - The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [offsetX=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a horizontal offset from the launch position. +* @param {number} [offsetY=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a vertical offset from the launch position. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fire = function (from, x, y, offsetX, offsetY) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (this.game.time.now < this._nextFire || (this.fireLimit > 0 && this.shots === this.fireLimit)) + { + return null; + } + + var speed = this.bulletSpeed; + + // Apply +- speed variance + if (this.bulletSpeedVariance !== 0) + { + speed += Phaser.Math.between(-this.bulletSpeedVariance, this.bulletSpeedVariance); + } + + if (from) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(from.x, from.y); + } + else + { + this.fireFrom.x = from.x; + this.fireFrom.y = from.y; + } + } + else if (this.trackedSprite) + { + if (this.trackRotation) + { + this._rotatedPoint.set(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.worldRotation); + + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this._rotatedPoint.x, this._rotatedPoint.y); + } + else + { + this.fireFrom.x = this._rotatedPoint.x; + this.fireFrom.y = this._rotatedPoint.y; + } + } + else + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedSprite.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedSprite.world.y + this.trackOffset.y; + } + } + + if (this.bulletInheritSpriteSpeed) + { + speed += this.trackedSprite.body.speed; + } + } + else if (this.trackedPointer) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedPointer.world.x + this.trackOffset.x, this.trackedPointer.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedPointer.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedPointer.world.y + this.trackOffset.y; + } + } + + if (offsetX !== undefined) + { + this.fireFrom.x += offsetX; + } + + if (offsetY !== undefined) + { + this.fireFrom.y += offsetY; + } + + var fromX = (this.fireFrom.width > 1) ? this.fireFrom.randomX : this.fireFrom.x; + var fromY = (this.fireFrom.height > 1) ? this.fireFrom.randomY : this.fireFrom.y; + + var angle = (this.trackRotation) ? this.trackedSprite.angle : this.fireAngle; + + // The position (in world space) to fire the bullet towards, if set + if (x !== null && y !== null) + { + angle = this.game.math.radToDeg(Math.atan2(y - fromY, x - fromX)); + } + + // Apply +- angle variance + if (this.bulletAngleVariance !== 0) + { + angle += Phaser.Math.between(-this.bulletAngleVariance, this.bulletAngleVariance); + } + + var moveX = 0; + var moveY = 0; + + // Avoid sin/cos for right-angled shots + if (angle === 0 || angle === 180) + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + } + else if (angle === 90 || angle === 270) + { + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + else + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + + var bullet = null; + + if (this.autoExpandBulletsGroup) + { + bullet = this.bullets.getFirstExists(false, true, fromX, fromY, this.bulletKey, this.bulletFrame); + + bullet.data.bulletManager = this; + } + else + { + bullet = this.bullets.getFirstExists(false); + } + + if (bullet) + { + bullet.reset(fromX, fromY); + + bullet.data.fromX = fromX; + bullet.data.fromY = fromY; + bullet.data.killType = this.bulletKillType; + bullet.data.killDistance = this.bulletKillDistance; + bullet.data.rotateToVelocity = this.bulletRotateToVelocity; + + if (this.bulletKillType === Phaser.Weapon.KILL_LIFESPAN) + { + bullet.lifespan = this.bulletLifespan; + } + + bullet.angle = angle + this.bulletAngleOffset; + + // Frames and Animations + if (this.bulletAnimation !== '') + { + if (bullet.animations.getAnimation(this.bulletAnimation) === null) + { + var anim = this.anims[this.bulletAnimation]; + + bullet.animations.add(anim.name, anim.frames, anim.frameRate, anim.loop, anim.useNumericIndex); + } + + bullet.animations.play(this.bulletAnimation); + } + else + { + if (this.bulletFrameCycle) + { + bullet.frame = this.bulletFrames[this.bulletFrameIndex]; + + this.bulletFrameIndex++; + + if (this.bulletFrameIndex >= this.bulletFrames.length) + { + this.bulletFrameIndex = 0; + } + } + else if (this.bulletFrameRandom) + { + bullet.frame = this.bulletFrames[Math.floor(Math.random() * this.bulletFrames.length)]; + } + } + + if (bullet.data.bodyDirty) + { + if (this._data.customBody) + { + bullet.body.setSize(this._data.width, this._data.height, this._data.offsetX, this._data.offsetY); + } + + bullet.body.collideWorldBounds = this.bulletCollideWorldBounds; + + bullet.data.bodyDirty = false; + } + + bullet.body.velocity.set(moveX, moveY); + bullet.body.gravity.set(this.bulletGravity.x, this.bulletGravity.y); + + var next = 0; + + if (this.bulletSpeedVariance !== 0) + { + var rate = this.fireRate; + + rate += Phaser.Math.between(-this.fireRateVariance, this.fireRateVariance); + + if (rate < 0) + { + rate = 0; + } + + next = this.game.time.now + rate; + } + else + { + next = this.game.time.now + this.fireRate; + } + + if (this.multiFire) + { + if (!this._hasFired) + { + // We only add 1 to the 'shots' count for multiFire shots + this._hasFired = true; + this._tempNextFire = next; + this.shots++; + } + } + else + { + this._nextFire = next; + + this.shots++; + } + + this.onFire.dispatch(bullet, this, speed); + + if (this.fireLimit > 0 && this.shots === this.fireLimit) + { + this.onFireLimit.dispatch(this, this.fireLimit); + } + } + + return bullet; + +}; + +/** +* Fires a bullet **at** the given Pointer. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtPointer = function (pointer) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + + return this.fire(null, pointer.worldX, pointer.worldY); + +}; + +/** +* Fires a bullet **at** the given Sprite. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtSprite +* @param {Phaser.Sprite} [sprite] - The Sprite to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtSprite = function (sprite) { + + return this.fire(null, sprite.world.x, sprite.world.y); + +}; + +/** +* Fires a bullet **at** the given coordinates. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtXY +* @param {number} [x] - The x coordinate, in world space, to fire the bullet towards. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtXY = function (x, y) { + + return this.fire(null, x, y); + +}; + +/** +* You can modify the size of the physics Body the Bullets use to be any dimension you need. +* This allows you to make it smaller, or larger, than the parent Sprite. +* You can also control the x and y offset of the Body. This is the position of the +* Body relative to the top-left of the Sprite _texture_. +* +* For example: If you have a Sprite with a texture that is 80x100 in size, +* and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: +* +* `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, 34)` +* +* Where the first two parameters are the new Body size (32x32 pixels) relative to the Sprite's scale. +* 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 +* is the vertical offset. +* +* @method Phaser.Weapon#setBulletBodyOffset +* @param {number} width - The width of the Body. +* @param {number} height - The height of the Body. +* @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture. +* @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture. +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletBodyOffset = function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this._data.customBody = true; + this._data.width = width; + this._data.height = height; + this._data.offsetX = offsetX; + this._data.offsetY = offsetY; + + // Update all bullets in the pool + this.bullets.callAll('body.setSize', 'body', width, height, offsetX, offsetY); + this.bullets.setAll('data.bodyDirty', false); + + return this; + +}; + +/** +* Sets the texture frames that the bullets can use when being launched. +* +* This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet. +* +* It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values +* provided. Then it sets the frame index to be zero. +* +* You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames +* when they're fired, or pick one at random. +* +* @method Phaser.Weapon#setBulletFrames +* @param {integer} min - The minimum value the frame can be. Usually zero. +* @param {integer} max - The maximum value the frame can be. +* @param {boolean} [cycle=true] - Should the bullet frames cycle as they are fired? +* @param {boolean} [random=false] - Should the bullet frames be picked at random as they are fired? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletFrames = function (min, max, cycle, random) { + + if (cycle === undefined) { cycle = true; } + if (random === undefined) { random = false; } + + this.bulletFrames = Phaser.ArrayUtils.numberArray(min, max); + + this.bulletFrameIndex = 0; + + this.bulletFrameCycle = cycle; + this.bulletFrameRandom = random; + + return this; + +}; + +/** +* Adds a new animation under the given key. Optionally set the frames, frame rate and loop. +* The arguments are all the same as for `Animation.add`, and work in the same way. +* +* {@link #bulletAnimation} will be set to this animation after it's created. From that point on, all +* bullets fired will play using this animation. You can swap between animations by calling this method +* several times, and then just changing the {@link #bulletAnimation} property to the name of the animation +* you wish to play for the next launched bullet. +* +* If you wish to stop using animations at all, set {@link #bulletAnimation} to '' (an empty string). +* +* @method Phaser.Weapon#addBulletAnimation +* @param {string} name - The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast". +* @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.addBulletAnimation = function (name, frames, frameRate, loop, useNumericIndex) { + + this.anims[name] = { + name: name, + frames: frames, + frameRate: frameRate, + loop: loop, + useNumericIndex: useNumericIndex + }; + + // Add the animation to any existing bullets in the pool + this.bullets.callAll('animations.add', 'animations', name, frames, frameRate, loop, useNumericIndex); + + this.bulletAnimation = name; + + return this; + +}; + +/** +* Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets +* both in-flight, and available. And optionally the physics debug bodies of the bullets. +* +* @method Phaser.Weapon#debug +* @param {integer} [x=16] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {integer} [y=32] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {boolean} [debugBodies=false] - Optionally draw the physics body of every bullet in-flight. +*/ +Phaser.Weapon.prototype.debug = function (x, y, debugBodies) { + + if (x === undefined) { x = 16; } + if (y === undefined) { y = 32; } + if (debugBodies === undefined) { debugBodies = false; } + + this.game.debug.text("Weapon Plugin", x, y); + this.game.debug.text("Bullets Alive: " + this.bullets.total + " - Total: " + this.bullets.length, x, y + 24); + + if (debugBodies) + { + this.bullets.forEachExists(this.game.debug.body, this.game.debug, 'rgba(255, 0, 255, 0.8)'); + } + +}; + +/** +* The Class of the bullets that are launched by this Weapon. Defaults to {@link Phaser.Bullet}, but can be +* overridden before calling `createBullets` and set to your own class type. +* +* It should be a constructor function accepting `(game, x, y, key, frame)`. +* +* @name Phaser.Weapon#bulletClass +* @property {function} bulletClass +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletClass", { + + get: function () { + + return this._bulletClass; + + }, + + set: function (classType) { + + this._bulletClass = classType; + + // `this.bullets` exists only after createBullets() + if (this.bullets) { + this.bullets.classType = this._bulletClass; + } + } + +}); + +/** +* This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`. +* +* There are 7 different "kill types" available: +* +* * `Phaser.Weapon.KILL_NEVER` +* The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code. +* +* * `Phaser.Weapon.KILL_LIFESPAN` +* The bullets are automatically killed when their `bulletLifespan` amount expires. +* +* * `Phaser.Weapon.KILL_DISTANCE` +* The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position. +* +* * `Phaser.Weapon.KILL_WEAPON_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* +* * `Phaser.Weapon.KILL_CAMERA_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.Camera#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_WORLD_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.World#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_STATIC_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to +* match the position of a tracked sprite or pointer. +* +* @name Phaser.Weapon#bulletKillType +* @property {integer} bulletKillType +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletKillType", { + + get: function () { + + return this._bulletKillType; + + }, + + set: function (type) { + + switch (type) + { + case Phaser.Weapon.KILL_STATIC_BOUNDS: + case Phaser.Weapon.KILL_WEAPON_BOUNDS: + this.bulletBounds = this.bounds; + break; + + case Phaser.Weapon.KILL_CAMERA_BOUNDS: + this.bulletBounds = this.game.camera.view; + break; + + case Phaser.Weapon.KILL_WORLD_BOUNDS: + this.bulletBounds = this.game.world.bounds; + break; + } + + this._bulletKillType = type; + + } + +}); + +/** +* Should bullets collide with the World bounds or not? +* +* @name Phaser.Weapon#bulletCollideWorldBounds +* @property {boolean} bulletCollideWorldBounds +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletCollideWorldBounds", { + + get: function () { + + return this._bulletCollideWorldBounds; + + }, + + set: function (value) { + + this._bulletCollideWorldBounds = value; + + this.bullets.setAll('body.collideWorldBounds', value); + this.bullets.setAll('data.bodyDirty', false); + + } + +}); + +/** +* The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Weapon.prototype, "x", { + + get: function () { + + return this.fireFrom.x; + + }, + + set: function (value) { + + this.fireFrom.x = value; + } + +}); + +/** +* The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Weapon.prototype, "y", { + + get: function () { + + return this.fireFrom.y; + + }, + + set: function (value) { + + this.fireFrom.y = value; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites, +* with a few extra properties in the data object to handle Weapon specific features. +* +* @class Phaser.Bullet +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Bullet = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + this.anchor.set(0.5); + + this.data = { + bulletManager: null, + fromX: 0, + fromY: 0, + bodyDirty: true, + rotateToVelocity: false, + killType: 0, + killDistance: 0 + }; + +}; + +Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Bullet.prototype.constructor = Phaser.Bullet; + +/** +* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool. +* Also dispatches the `Weapon.onKill` signal. +* +* @method Phaser.Bullet#kill +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + this.data.bulletManager.onKill.dispatch(this); + + return this; + +}; + +/** +* Updates the Bullet, killing as required. +* +* @method Phaser.Bullet#update +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.update = function () { + + if (!this.exists) + { + return; + } + + if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN) + { + if (this.data.killType === Phaser.Weapon.KILL_DISTANCE) + { + if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance) + { + this.kill(); + } + } + else + { + if (!this.data.bulletManager.bulletBounds.intersects(this)) + { + this.kill(); + } + } + } + + if (this.data.rotateToVelocity) + { + this.rotation = this.body.velocity.atan(); + } + + if (this.data.bulletManager.bulletWorldWrap) + { + this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding); + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. +* +* Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to +* the Video instead (see `startMediaStream` method) +* +* The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback +* changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. +* +* Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. +* +* If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. +* Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. +* +* On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. +* This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio +* it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` +* method to try and work around this limitation, but see the method help for details. +* +* Small screen devices, especially iPod and iPhone will launch the video in its own native video player, +* outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. +* +* Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) +* then you need to add your own event listener +* +* @class Phaser.Video +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. +* @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) +*/ +Phaser.Video = function (game, key, url) { + + if (key === undefined) { key = null; } + if (url === undefined) { url = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. + * @default null + */ + this.key = key; + + /** + * @property {number} width - The width of the video in pixels. + * @default + */ + this.width = 0; + + /** + * @property {number} height - The height of the video in pixels. + * @default + */ + this.height = 0; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.VIDEO; + + /** + * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. + * @default + */ + this.touchLocked = false; + + /** + * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. + */ + this.onChangeSource = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam. + */ + this.onAccess = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. + */ + this.onError = new Phaser.Signal(); + + /** + * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. + * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. + * @property {Phaser.Signal} onTimeout + */ + this.onTimeout = new Phaser.Signal(); + + /** + * This signal is dispatched when the Video is unlocked. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * Start playing the video when it's unlocked. + * @property {boolean} playWhenUnlocked + * @default + */ + this.playWhenUnlocked = true; + + /** + * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. + * @default + */ + this.timeout = 15000; + + /** + * @property {integer} _timeOutID - setTimeout ID. + * @private + */ + this._timeOutID = null; + + /** + * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document. + */ + this.video = null; + + /** + * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. + */ + this.videoStream = null; + + /** + * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam. + */ + this.isStreaming = false; + + /** + * When starting playback of a video Phaser will monitor its readyState using a setTimeout call. + * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * @property {integer} retryLimit + * @default + */ + this.retryLimit = 20; + + /** + * @property {integer} retry - The current retry attempt. + * @default + */ + this.retry = 0; + + /** + * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video. + * @default + */ + this.retryInterval = 500; + + /** + * @property {integer} _retryID - The callback ID of the retry setTimeout. + * @private + */ + this._retryID = null; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {boolean} _codePaused - Internal paused tracking var. + * @private + * @default + */ + this._codePaused = false; + + /** + * @property {boolean} _paused - Internal paused tracking var. + * @private + * @default + */ + this._paused = false; + + /** + * @property {boolean} _pending - Internal var tracking play pending. + * @private + * @default + */ + this._pending = false; + + /** + * @property {boolean} _pendingChangeSource - Internal var tracking play pending. + * @private + * @default + */ + this._pendingChangeSource = false; + + /** + * @property {boolean} _autoplay - Internal var tracking autoplay when changing source. + * @private + * @default + */ + this._autoplay = false; + + /** + * @property {function} _endCallback - The addEventListener ended function. + * @private + */ + this._endCallback = null; + + /** + * @property {function} _playCallback - The addEventListener playing function. + * @private + */ + this._playCallback = null; + + if (key && this.game.cache.checkVideoKey(key)) + { + var _video = this.game.cache.getVideo(key); + + if (_video.isBlob) + { + this.createVideoFromBlob(_video.data); + } + else + { + this.video = _video.data; + } + + this.width = this.video.videoWidth; + this.height = this.video.videoHeight; + } + else if (url) + { + this.createVideoFromURL(url, false); + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + if (this.video && !url) + { + this.baseTexture = new PIXI.BaseTexture(this.video, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + else + { + this.baseTexture = new PIXI.BaseTexture(Phaser.Cache.DEFAULT.baseTexture.source, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering. + * @default + */ + this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video'); + + this.texture.setFrame(this.textureFrame); + + this.texture.valid = false; + + if (key !== null && this.video) + { + this.texture.valid = this.video.canplay; + } + + /** + * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). + * When called the BitmapData is updated with a grab taken from the current video playing or active video stream. + * If Phaser has been compiled without BitmapData support this property will always be `null`. + * + * @property {Phaser.BitmapData} snapshot + * @readOnly + */ + this.snapshot = null; + + if (Phaser.BitmapData) + { + this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height); + } + + if (this.game.device.needsTouchUnlock()) + { + this.setTouchLock(); + } + else + { + if (_video) + { + _video.locked = false; + } + } + +}; + +Phaser.Video.prototype = { + + /** + * Connects to an external media stream for the webcam, rather than using a local one. + * + * @method Phaser.Video#connectToMediaStream + * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses. + * @param {MediaStream} stream - The Video Stream data. + * @return {Phaser.Video} This Video object for method chaining. + */ + connectToMediaStream: function (video, stream) { + + if (video && stream) + { + this.video = video; + this.videoStream = stream; + + this.isStreaming = true; + this.baseTexture.source = this.video; + this.updateTexture(null, this.video.videoWidth, this.video.videoHeight); + + this.onAccess.dispatch(this); + } + + return this; + + }, + + /** + * Instead of playing a video file this method allows you to stream video data from an attached webcam. + * + * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam. + * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream. + * + * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError + * or MediaStreamError event. + * + * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions. + * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device. + * You can listen for this with the onChangeSource signal. + * + * @method Phaser.Video#startMediaStream + * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream. + * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source. + * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source. + * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia. + */ + startMediaStream: function (captureAudio, width, height) { + + if (captureAudio === undefined) { captureAudio = false; } + if (width === undefined) { width = null; } + if (height === undefined) { height = null; } + + if (!this.game.device.getUserMedia) + { + this.onError.dispatch(this, 'No getUserMedia'); + return false; + } + + if (this.videoStream !== null) + { + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + this.videoStream.stop(); + } + } + + this.removeVideoElement(); + + this.video = document.createElement("video"); + this.video.setAttribute('autoplay', 'autoplay'); + + if (width !== null) + { + this.video.width = width; + } + + if (height !== null) + { + this.video.height = height; + } + + // Request access to the webcam + + this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout); + + try { + navigator.getUserMedia( + { "audio": captureAudio, "video": true }, + this.getUserMediaSuccess.bind(this), + this.getUserMediaError.bind(this) + ); + } + catch (error) + { + this.getUserMediaError(error); + } + + return this; + + }, + + /** + * @method Phaser.Video#getUserMediaTimeout + * @private + */ + getUserMediaTimeout: function () { + + clearTimeout(this._timeOutID); + + this.onTimeout.dispatch(this); + + }, + + /** + * @method Phaser.Video#getUserMediaError + * @private + */ + getUserMediaError: function (event) { + + clearTimeout(this._timeOutID); + + this.onError.dispatch(this, event); + + }, + + /** + * @method Phaser.Video#getUserMediaSuccess + * @private + */ + getUserMediaSuccess: function (stream) { + + clearTimeout(this._timeOutID); + + // Attach the stream to the video + this.videoStream = stream; + + // Set the source of the video element with the stream from the camera + if (this.video.mozSrcObject !== undefined) + { + this.video.mozSrcObject = stream; + } + else + { + this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; + } + + var self = this; + + this.video.onloadeddata = function () { + + var retry = 10; + + function checkStream () { + + if (retry > 0) + { + if (self.video.videoWidth > 0) + { + // Patch for Firefox bug where the height can't be read from the video + var width = self.video.videoWidth; + var height = self.video.videoHeight; + + if (isNaN(self.video.videoHeight)) + { + height = width / (4/3); + } + + self.video.play(); + + self.isStreaming = true; + self.baseTexture.source = self.video; + self.updateTexture(null, width, height); + self.onAccess.dispatch(self); + } + else + { + window.setTimeout(checkStream, 500); + } + } + else + { + console.warn('Unable to connect to video stream. Webcam error?'); + } + + retry--; + } + + checkStream(); + + }; + + }, + + /** + * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format. + * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience. + * + * @method Phaser.Video#createVideoFromBlob + * @param {Blob} blob - The Blob containing the video data. + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromBlob: function (blob) { + + var _this = this; + + this.video = document.createElement("video"); + this.video.controls = false; + this.video.setAttribute('autoplay', 'autoplay'); + this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true); + this.video.src = window.URL.createObjectURL(blob); + this.video.canplay = true; + + return this; + + }, + + /** + * Creates a new Video element from the given URL. + * + * @method Phaser.Video#createVideoFromURL + * @param {string} url - The URL of the video. + * @param {boolean} [autoplay=false] - Automatically start the video? + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromURL: function (url, autoplay) { + + if (autoplay === undefined) { autoplay = false; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + if (this.texture) + { + this.texture.valid = false; + } + + this.video = document.createElement("video"); + this.video.controls = false; + + if (autoplay) + { + this.video.setAttribute('autoplay', 'autoplay'); + } + + this.video.src = url; + + this.video.canplay = true; + + this.video.load(); + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.key = url; + + return this; + + }, + + /** + * Called automatically if the video source changes and updates the internal texture dimensions. + * Then dispatches the onChangeSource signal. + * + * @method Phaser.Video#updateTexture + * @param {object} [event] - The event which triggered the texture update. + * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used. + * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used. + */ + updateTexture: function (event, width, height) { + + var change = false; + + if (width === undefined || width === null) { width = this.video.videoWidth; change = true; } + if (height === undefined || height === null) { height = this.video.videoHeight; } + + this.width = width; + this.height = height; + + if (this.baseTexture.source !== this.video) + { + this.baseTexture.source = this.video; + } + + this.baseTexture.forceLoaded(width, height); + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.valid = true; + + if (this.snapshot) + { + this.snapshot.resize(width, height); + } + + if (change && this.key !== null) + { + this.onChangeSource.dispatch(this, width, height); + + if (this._autoplay) + { + this.video.play(); + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + } + + }, + + /** + * Called when the video completes playback (reaches and ended state). + * Dispatches the Video.onComplete signal. + * + * @method Phaser.Video#complete + */ + complete: function () { + + this.onComplete.dispatch(this); + + }, + + /** + * Starts this video playing. + * + * If the video is already playing, or has been queued to play with `changeSource` then this method just returns. + * + * @method Phaser.Video#play + * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. + * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate. + * @return {Phaser.Video} This Video object for method chaining. + */ + play: function (loop, playbackRate) { + + if (this._pendingChangeSource) + { + return this; + } + + if (loop === undefined) { loop = false; } + if (playbackRate === undefined) { playbackRate = 1; } + + if (this.game.sound.onMute) + { + this.game.sound.onMute.add(this.setMute, this); + this.game.sound.onUnMute.add(this.unsetMute, this); + + if (this.game.sound.mute) + { + this.setMute(); + } + } + + this.game.onPause.add(this.setPause, this); + this.game.onResume.add(this.setResume, this); + + this._endCallback = this.complete.bind(this); + + this.video.addEventListener('ended', this._endCallback, true); + this.video.addEventListener('webkitendfullscreen', this._endCallback, true); + + if (loop) + { + this.video.loop = 'loop'; + } + else + { + this.video.loop = ''; + } + + this.video.playbackRate = playbackRate; + + if (this.touchLocked) + { + this._pending = true; + } + else + { + this._pending = false; + + if (this.key !== null) + { + if (this.video.readyState !== 4) + { + this.retry = this.retryLimit; + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + this._playCallback = this.playHandler.bind(this); + this.video.addEventListener('playing', this._playCallback, true); + } + } + + this.video.play(); + + this.onPlay.dispatch(this, loop, playbackRate); + } + + return this; + + }, + + /** + * Called when the video starts to play. Updates the texture. + * + * @method Phaser.Video#playHandler + * @private + */ + playHandler: function () { + + this.video.removeEventListener('playing', this._playCallback, true); + + this.updateTexture(); + + }, + + /** + * Stops the video playing. + * + * This removes all locally set signals. + * + * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead. + * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to + * call `Video.destroy` instead. + * + * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam. + * + * @method Phaser.Video#stop + * @return {Phaser.Video} This Video object for method chaining. + */ + stop: function () { + + if (this.game.sound.onMute) + { + this.game.sound.onMute.remove(this.setMute, this); + this.game.sound.onUnMute.remove(this.unsetMute, this); + } + + this.game.onPause.remove(this.setPause, this); + this.game.onResume.remove(this.setResume, this); + + // Stream or file? + + if (this.isStreaming) + { + if (this.video.mozSrcObject) + { + this.video.mozSrcObject.stop(); + this.video.src = null; + } + else + { + this.video.src = ''; + + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + if (this.videoStream.getTracks) + { + this.videoStream.getTracks().forEach(function (track) { + track.stop(); + }); + } + else + { + this.videoStream.stop(); + } + } + } + + this.videoStream = null; + this.isStreaming = false; + } + else + { + this.video.removeEventListener('ended', this._endCallback, true); + this.video.removeEventListener('webkitendfullscreen', this._endCallback, true); + this.video.removeEventListener('playing', this._playCallback, true); + + if (this.touchLocked) + { + this._pending = false; + } + else + { + this.video.pause(); + } + } + + return this; + + }, + + /** + * Updates the given Display Objects so they use this Video as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.Video#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.Video} This Video object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. + * + * @method Phaser.Video#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set Video.disableTextureUpload to `true`. + * + * @method Phaser.Video#render + */ + render: function () { + + if (!this.disableTextureUpload && this.playing) + { + this.baseTexture.dirty(); + } + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + this.video.muted = true; + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + this.video.muted = false; + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setPause + * @private + */ + setPause: function () { + + if (this._paused || this.touchLocked) + { + return; + } + + this._paused = true; + + this.video.pause(); + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setResume + * @private + */ + setResume: function () { + + if (!this._paused || this._codePaused || this.touchLocked) + { + return; + } + + this._paused = false; + + if (!this.video.ended) + { + this.video.play(); + } + + }, + + /** + * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it. + * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over" + * split into three different Video objects, then you will need the user to touch-unlock every single one of them. + * + * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains + * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again. + * + * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate. + * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it + * cannot render the new video on iOS (desktop browsers cope better). + * + * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know + * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state + * are adopted automatically by the new video. + * + * @method Phaser.Video#changeSource + * @param {string} src - The new URL to change the video.src to. + * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated? + * @return {Phaser.Video} This Video object for method chaining. + */ + changeSource: function (src, autoplay) { + + if (autoplay === undefined) { autoplay = true; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + this.texture.valid = false; + + this.video.pause(); + + this._pendingChangeSource = true; + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.video.src = src; + + this.video.load(); + + this._autoplay = autoplay; + + if (!autoplay) + { + this.paused = true; + } + + return this; + + }, + + /** + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.Video#checkVideoProgress + * @private + */ + checkVideoProgress: function () { + + // if (this.video.readyState === 2 || this.video.readyState === 4) + if (this.video.readyState === 4) + { + this._pendingChangeSource = false; + + // We've got enough data to update the texture for playback + this.updateTexture(); + } + else + { + this.retry--; + + if (this.retry > 0) + { + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming); + } + } + + }, + + /** + * Sets the Input Manager touch callback to be Video.unlock. + * Required for mobile video unlocking. Mostly just used internally. + * + * @method Phaser.Video#setTouchLock + */ + setTouchLock: function () { + + this.game.input.addTouchLockCallback(this.unlock, this, true); + this.touchLocked = true; + + }, + + /** + * Enables the video on mobile devices, usually after the first touch. + * If the SoundManager hasn't been unlocked then this will automatically unlock that as well. + * Only one video can be pending unlock at any one time. + * + * @method Phaser.Video#unlock + */ + unlock: function () { + + this.touchLocked = false; + + if (this.playWhenUnlocked) + { + this.video.play(); + + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + + if (this.key) + { + var _video = this.game.cache.getVideo(this.key); + + if (_video && !_video.isBlob) + { + _video.locked = false; + } + } + + this.onTouchUnlock.dispatch(this); + + return true; + + }, + + /** + * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData. + * + * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw. + * + * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy. + * + * @method Phaser.Video#grab + * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false. + * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining. + */ + grab: function (clear, alpha, blendMode) { + + if (clear === undefined) { clear = false; } + if (alpha === undefined) { alpha = 1; } + if (blendMode === undefined) { blendMode = null; } + + if (this.snapshot === null) + { + console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable'); + return; + } + + if (clear) + { + this.snapshot.cls(); + } + + this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode); + + return this.snapshot; + + }, + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * Also removes the autoplay and src attributes and nulls the reference. + * + * @method Phaser.Video#removeVideoElement + */ + removeVideoElement: function () { + + if (!this.video) + { + return; + } + + if (this.video.parentNode) + { + this.video.parentNode.removeChild(this.video); + } + + while (this.video.hasChildNodes()) + { + this.video.removeChild(this.video.firstChild); + } + + this.video.removeAttribute('autoplay'); + this.video.removeAttribute('src'); + + this.video = null; + + }, + + /** + * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`. + * If any Sprites are using this Video as their texture it is up to you to manage those. + * + * @method Phaser.Video#destroy + */ + destroy: function () { + + this.stop(); + + this.removeVideoElement(); + + if (this.touchLocked) + { + this.game.input.touch.removeTouchLockCallback(this.unlock, this); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + + } + +}; + +/** +* @name Phaser.Video#currentTime +* @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time. +*/ +Object.defineProperty(Phaser.Video.prototype, "currentTime", { + + get: function () { + + return (this.video) ? this.video.currentTime : 0; + + }, + + set: function (value) { + + this.video.currentTime = value; + + } + +}); + +/** +* @name Phaser.Video#duration +* @property {number} duration - The duration of the video in seconds. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "duration", { + + get: function () { + + return (this.video) ? this.video.duration : 0; + + } + +}); + +/** +* @name Phaser.Video#progress +* @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "progress", { + + get: function () { + + return (this.video) ? (this.video.currentTime / this.video.duration) : 0; + + } + +}); + +/** +* @name Phaser.Video#mute +* @property {boolean} mute - Gets or sets the muted state of the Video. +*/ +Object.defineProperty(Phaser.Video.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || null; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* Gets or sets the paused state of the Video. +* If the video is still touch locked (such as on iOS devices) this call has no effect. +* +* @name Phaser.Video#paused +* @property {boolean} paused +*/ +Object.defineProperty(Phaser.Video.prototype, "paused", { + + get: function () { + + return this._paused; + + }, + + set: function (value) { + + value = value || null; + + if (this.touchLocked) + { + return; + } + + if (value) + { + if (this._paused) + { + return; + } + + this._codePaused = true; + this.setPause(); + } + else + { + if (!this._paused) + { + return; + } + + this._codePaused = false; + this.setResume(); + } + } + +}); + +/** +* @name Phaser.Video#volume +* @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Video.prototype, "volume", { + + get: function () { + + return (this.video) ? this.video.volume : 1; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this.video) + { + this.video.volume = value; + } + + } + +}); + +/** +* @name Phaser.Video#playbackRate +* @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing. +*/ +Object.defineProperty(Phaser.Video.prototype, "playbackRate", { + + get: function () { + + return (this.video) ? this.video.playbackRate : 1; + + }, + + set: function (value) { + + if (this.video) + { + this.video.playbackRate = value; + } + + } + +}); + +/** +* Gets or sets if the Video is set to loop. +* Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. +* If the video isn't yet set this will always return false. +* +* @name Phaser.Video#loop +* @property {boolean} loop +*/ +Object.defineProperty(Phaser.Video.prototype, "loop", { + + get: function () { + + return (this.video) ? this.video.loop : false; + + }, + + set: function (value) { + + if (value && this.video) + { + this.video.loop = 'loop'; + } + else if (this.video) + { + this.video.loop = ''; + } + + } + +}); + +/** +* @name Phaser.Video#playing +* @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "playing", { + + get: function () { + + return (this.video) ? !(this.video.paused && this.video.ended) : false; + + } + +}); + +Phaser.Video.prototype.constructor = Phaser.Video; + +/* global Phaser:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Pixi expects these globals to exist + +if (PIXI.blendModes === undefined) +{ + PIXI.blendModes = Phaser.blendModes; +} + +if (PIXI.scaleModes === undefined) +{ + PIXI.scaleModes = Phaser.scaleModes; +} + +if (PIXI.Texture.emptyTexture === undefined) +{ + PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture()); +} + +if (PIXI.DisplayObject._tempMatrix === undefined) +{ + PIXI.DisplayObject._tempMatrix = new Phaser.Matrix(); +} + +PIXI.TextureSilentFail = true; + +// Required by Particle Storm +PIXI.canUseNewCanvasBlendModes = function () { + return Phaser.Device.canUseMultiply; +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = Phaser; + } + exports.Phaser = Phaser; + } else if (typeof define !== 'undefined' && define.amd) { + define('Phaser', (function() { return root.Phaser = Phaser; })() ); + } else { + root.Phaser = Phaser; + } + + return Phaser; +}).call(this); + +/* +* "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer +*/ diff --git a/Iteration Sequence 1/js/phaser.map b/Iteration Sequence 1/js/phaser.map new file mode 100644 index 000000000..70723bbf8 --- /dev/null +++ b/Iteration Sequence 1/js/phaser.map @@ -0,0 +1 @@ +{"version":3,"sources":["phaser.js"],"names":["e","exports","module","f","window","global","self","p2","t","n","r","s","o","u","a","require","i","Error","call","length","1","_dereq_","Line","Scalar","lineInt","l1","l2","precision","a1","b1","c1","a2","b2","c2","det","eq","segmentsIntersect","p1","q1","q2","dx","dy","da","db","./Scalar","2","Point","area","b","c","left","leftOn","right","rightOn","tmpPoint1","tmpPoint2","collinear","thresholdAngle","ab","bc","dot","magA","Math","sqrt","magB","acos","sqdist","3","Polygon","this","vertices","getIntersectionPoint","delta","prototype","at","v","first","last","clear","append","poly","from","to","push","makeCCW","br","reverse","tmp","N","pop","isReflex","tmpLine1","tmpLine2","canSee","p","dist","copy","j","targetPoly","k","getCutEdges","min","tmp1","tmp2","tmpPoly","nDiags","Number","MAX_VALUE","decomp","edges","slice","cutEdges","Array","polys","cutEdge","result","splice","indexOf","isSimple","path","quickDecomp","reflexVertices","steinerPoints","maxlevel","level","upperInt","lowerInt","upperDist","lowerDist","d","closestDist","upperIndex","lowerIndex","closestIndex","lowerPoly","upperPoly","console","warn","removeCollinearPoints","num","./Line","./Point","4","abs","5","./Polygon","6","name","version","description","author","keywords","main","engines","node","repository","type","url","bugs","licenses","devDependencies","grunt","grunt-contrib-jshint","grunt-contrib-nodeunit","grunt-contrib-uglify","grunt-contrib-watch","grunt-browserify","grunt-contrib-concat","dependencies","poly-decomp","7","AABB","options","lowerBound","vec2","create","upperBound","setFromPoints","points","position","angle","skinSize","l","rotate","cosAngle","cos","sinAngle","sin","x","y","add","aabb","extend","overlaps","u1","u2","containsPoint","point","overlapsRay","ray","dirFracX","direction","dirFracY","t1","t2","t3","t4","tmin","max","tmax","../math/vec2","../utils/Utils","8","Broadphase","world","boundingVolumeType","Body","BOUNDING_CIRCLE","setWorld","getCollisionPairs","boundingRadiusCheck","bodyA","bodyB","sub","d2","squaredLength","boundingRadius","aabbCheck","getAABB","boundingVolumeCheck","canCollide","KINEMATIC","STATIC","sleepState","SLEEPING","NAIVE","SAP","../objects/Body","9","NaiveBroadphase","constructor","bodies","Ncolliding","bi","bj","aabbQuery","aabbNeedsUpdate","updateAABB","../collision/Broadphase","../shapes/Circle","../shapes/Particle","../shapes/Plane","../shapes/Shape","10","Narrowphase","contactEquations","frictionEquations","enableFriction","enabledEquations","slipForce","frictionCoefficient","surfaceVelocity","contactEquationPool","ContactEquationPool","size","frictionEquationPool","FrictionEquationPool","restitution","stiffness","Equation","DEFAULT_STIFFNESS","relaxation","DEFAULT_RELAXATION","frictionStiffness","frictionRelaxation","enableFrictionReduction","collidingBodiesLastStep","TupleDictionary","contactSkinSize","setConvexToCapsuleShapeMiddle","convexShape","capsuleShape","set","radius","pointInConvex","worldPoint","convexOffset","convexAngle","worldVertex0","pic_worldVertex0","worldVertex1","pic_worldVertex1","r0","pic_r0","r1","pic_r1","verts","lastCross","v0","v1","cross","crossLength","Circle","Convex","Shape","Box","yAxis","fromValues","tmp3","tmp4","tmp5","tmp6","tmp7","tmp8","tmp9","tmp10","tmp11","tmp12","tmp13","tmp14","tmp15","tmp16","tmp17","tmp18","tmpArray","bodiesOverlap_shapePositionA","bodiesOverlap_shapePositionB","bodiesOverlap","shapePositionA","shapePositionB","Nshapesi","shapes","shapeA","toWorldFrame","Nshapesj","shapeB","collidedLastStep","id1","id","id2","get","reset","eqs","ce","fe","release","createContactEquation","firstImpact","needsUpdate","enabled","offset","createFrictionEquation","setSlipForce","relativeVelocity","createFrictionFromContact","contactPointA","contactPointB","rotate90cw","normalA","createFrictionFromAverage","numContacts","invNumContacts","scale","normalize","LINE","CONVEX","convexLine","convexBody","lineBody","lineShape","lineOffset","lineAngle","justTest","BOX","lineBox","boxBody","boxShape","boxOffset","boxAngle","convexCapsule_tempRect","width","height","convexCapsule_tempVec","CAPSULE","convexCapsule","convexPosition","capsuleBody","capsulePosition","capsuleAngle","circlePos","result1","circleConvex","result2","convexConvex","lineCapsule","linePosition","capsuleCapsule_tempVec1","capsuleCapsule_tempVec2","capsuleCapsule_tempRect1","capsuleCapsule","si","xi","ai","sj","xj","aj","circlePosi","circlePosj","enableFrictionBefore","circleCircle","rect","lineLine","positionA","angleA","positionB","angleB","PLANE","planeLine","planeBody","planeShape","planeOffset","planeAngle","worldVertex01","worldVertex11","worldEdge","worldEdgeUnit","worldNormal","worldTangent","PARTICLE","particleCapsule","particleBody","particleShape","particlePosition","particleAngle","circleLine","CIRCLE","circleBody","circleShape","circleOffset","circleAngle","lineRadius","circleRadius","orthoDist","lineToCircleOrthoUnit","projectedPoint","centerDist","lineToCircle","lineEndToLineRadius","radiusSum","pos","pos0","pos1","pow","circleCapsule","worldVertex","closestEdgeProjectedPoint","candidate","candidateDist","minCandidate","found","minCandidateDistance","candidateDistance","localVertex","particleConvex","particleOffset","convexToparticle","minEdgeNormal","offsetA","offsetB","radiusA","radiusB","planeConvex","numReported","particlePlane","circleParticle","planeCapsule_tmpCircle","planeCapsule_tmp1","planeCapsule_tmp2","planeCapsule","capsuleOffset","end1","end2","circle","numContacts1","circlePlane","numContacts2","numTotal","planeToCircle","temp","contact","sepAxis","worldPoint0","worldPoint1","penetrationVec","findSeparatingAxis","closestEdge1","getClosestEdge","closestEdge2","closestEdgeA","closestEdgeB","insideNumEdges","pcoa_tmp1","projectConvexOntoAxis","worldAxis","value","localAxis","fsa_tmp1","fsa_tmp2","fsa_tmp3","fsa_tmp4","fsa_tmp5","fsa_tmp6","offset1","angle1","offset2","angle2","maxDist","overlap","edge","normal","span1","span2","gce_tmp1","gce_tmp2","gce_tmp3","axis","flip","closestEdge","maxDot","circleHeightfield_candidate","circleHeightfield_dist","circleHeightfield_v0","circleHeightfield_v1","circleHeightfield_minCandidate","circleHeightfield_worldNormal","circleHeightfield_minCandidateNormal","HEIGHTFIELD","circleHeightfield","hfBody","hfShape","hfPos","hfAngle","data","heights","w","elementWidth","minCandidateNormal","idxA","floor","idxB","ceil","PI","convexHeightfield_v0","convexHeightfield_v1","convexHeightfield_tilePos","convexHeightfield_tempConvexShape","convexHeightfield","convexPos","tilePos","tileConvex","../equations/ContactEquation","../equations/Equation","../equations/FrictionEquation","../shapes/Box","../shapes/Convex","../utils/ContactEquationPool","../utils/FrictionEquationPool","../utils/TupleDictionary","11","Ray","checkCollisionResponse","undefined","skipBackfaces","collisionMask","collisionGroup","mode","ANY","callback","update","distanceFromIntersectionSquared","intersect","squaredDistance","CLOSEST","ALL","intersectBodies","shouldStop","body","intersectBody","intersectBody_worldPosition","collisionResponse","worldPosition","shape","worldAngle","intersectShape","_currentBody","_currentShape","raycast","reportIntersection","fraction","faceIndex","hasHit","../collision/AABB","../collision/RaycastResult","12","RaycastResult","isStopped","getHitDistance","distance","getHitPoint","out","lerp","stop","../collision/Ray","13","SAPBroadphase","axisList","axisIndex","that","_addBodyHandler","_removeBodyHandler","idx","Utils","appendArray","off","on","sortAxisList","sortList","14","Constraint","defaults","collideConnected","wakeUpBodies","equations","wakeUp","DISTANCE","GEAR","LOCK","PRISMATIC","REVOLUTE","setStiffness","setRelaxation","15","DistanceConstraint","localAnchorA","localAnchorB","worldAnchorA","worldAnchorB","maxForce","ri","rj","computeGq","setMaxForce","upperLimitEnabled","upperLimit","lowerLimitEnabled","lowerLimit","normalEquation","G","violating","minForce","rixn","rjxn","getMaxForce","./Constraint","16","GearConstraint","ratio","AngleLockEquation","maxTorque","setMaxTorque","setRatio","torque","getMaxTorque","../equations/AngleLockEquation","17","LockConstraint","localAngleB","rot","g","localOffsetB","force","xAxis","18","PrismaticConstraint","localAxisA","trans","gg","updateJacobian","disableRotationalLock","RotationalLockEquation","velocity","upperLimitEquation","ContactEquation","lowerLimitEquation","motorEquation","motorEnabled","motorSpeed","computeGW","vi","vj","wi","angularVelocity","wj","gmult","worldAxisA","orientedAnchorA","orientedAnchorB","relPosition","enableMotor","disableMotor","setLimits","lower","upper","../equations/RotationalLockEquation","19","RevoluteConstraint","pivotA","pivotB","worldPivot","localPivotA","localPivotB","worldPivotA","worldPivotB","RotationalVelocityEquation","relAngle","setMotorSpeed","speed","getMotorSpeed","../equations/RotationalVelocityEquation","20","./Equation","21","computeB","h","GW","Gq","computeGiMf","relVel","getVelocityAlongNormal","getVelocityAtPoint","subtract","22","ARRAY_TYPE","epsilon","timeStep","multiplier","qi","qj","computeGWlambda","vlambda","wlambda","iMfi","iMfj","fi","ti","angularForce","fj","tj","invMassi","invMassSolve","invMassj","invIi","invInertiaSolve","invIj","multiply","massMultiplier","computeGiMGt","addToWlambda_temp","addToWlambda_Gi","addToWlambda_Gj","addToWlambda","deltalambda","Gi","Gj","computeInvC","eps","23","FrictionEquation","getSlipForce","24","worldVectorA","worldVectorB","25","GiMf","26","EventEmitter","listener","context","_listeners","listeners","has","index","emit","event","listenerArray","target","27","ContactMaterial","materialA","materialB","Material","idCounter","friction","./Material","28","29","PolyK","GetArea","sum","Triangulate","tgs","avl","al","i0","i1","i2","ax","ay","bx","by","cx","cy","earFound","_convex","_PointInTriangle","px","py","v0x","v0y","v1x","v1y","v2x","v2y","dot00","dot01","dot02","dot11","dot12","invDenom","30","crossVZ","vec","zcomp","crossZV","toLocalFrame","framePosition","frameAngle","toGlobalFrame","localPoint","vectorToLocalFrame","worldVector","vectorToGlobalFrame","localVector","centroid","clone","mul","divide","div","sqrDist","len","sqrLen","negate","str","reflect","vector","getLineSegmentsIntersection","p0","p3","getLineSegmentsIntersectionFraction","s1_x","s1_y","s2_x","s2_y","31","_idCounter","mass","invMass","inertia","invInertia","fixedRotation","fixedX","fixedY","interpolatedPosition","interpolatedAngle","previousPosition","previousAngle","damping","angularDamping","DYNAMIC","allowSleep","wantsToSleep","AWAKE","sleepSpeedLimit","sleepTimeLimit","gravityScale","idleTime","timeLastSleepy","ccdSpeedThreshold","ccdIterations","concavePath","_wakeUpAfterNarrowphase","updateMassProperties","updateSolveMassProperties","setDensity","density","totalArea","getArea","shapeAABB","bodyAngle","computeAABB","updateBoundingRadius","addShape","removeShape","m","I","r2","computeMomentOfInertia","applyForce","relativePoint","rotForce","Body_applyForce_forceWorld","Body_applyForce_pointWorld","Body_applyForce_pointLocal","applyForceLocal","localForce","worldForce","vectorToWorldFrame","Body_applyImpulse_velo","applyImpulse","impulseVector","velo","rotVelo","Body_applyImpulse_impulseWorld","Body_applyImpulse_pointWorld","Body_applyImpulse_pointLocal","applyImpulseLocal","localImpulse","worldImpulse","fromPolygon","convexes","optimalDecomp","cm","centerOfMass","updateTriangles","updateCenterOfMass","adjustCenterOfMass","adjustCenterOfMass_tmp2","adjustCenterOfMass_tmp3","adjustCenterOfMass_tmp4","offset_times_area","setZeroForce","resetConstraintVelocity","addConstraintVelocity","applyDamping","dt","wakeUpEvent","sleep","sleepEvent","sleepTick","time","dontSleep","SLEEPY","overlapKeeper","bodiesAreOverlapping","integrate_fhMinv","integrate_velodt","integrate","minv","integrateToTimeOfImpact","end","startToEnd","rememberPosition","hit","startToEndAngle","timeOfImpact","rememberAngle","iter","tmid","narrowphase","sleepyEvent","../events/EventEmitter","32","LinearSpring","Spring","setWorldAnchorA","setWorldAnchorB","getWorldAnchorA","getWorldAnchorB","worldDistance","restLength","applyForce_r","applyForce_r_unit","applyForce_u","applyForce_f","applyForce_worldAnchorA","applyForce_worldAnchorB","applyForce_ri","applyForce_rj","applyForce_tmp","r_unit","rlen","ri_x_f","rj_x_f","./Spring","33","RotationalSpring","restAngle","34","35","TopDownVehicle","chassisBody","wheels","groundBody","preStepCallback","WheelConstraint","vehicle","forwardEquation","sideEquation","steerValue","engineForce","setSideFriction","sideFriction","localForwardVector","localPosition","apply","setBrakeForce","addToWorld","addBody","wheel","addConstraint","removeFromWorld","removeBody","removeConstraint","addWheel","wheelOptions","worldVelocity","getSpeed","tmpVec","../constraints/Constraint","36","Capsule","GSSolver","Heightfield","Particle","Plane","Pool","Solver","World","Object","defineProperty","../package.json","./collision/AABB","./collision/Broadphase","./collision/NaiveBroadphase","./collision/Narrowphase","./collision/Ray","./collision/RaycastResult","./collision/SAPBroadphase","./constraints/Constraint","./constraints/DistanceConstraint","./constraints/GearConstraint","./constraints/LockConstraint","./constraints/PrismaticConstraint","./constraints/RevoluteConstraint","./equations/AngleLockEquation","./equations/ContactEquation","./equations/Equation","./equations/FrictionEquation","./equations/RotationalVelocityEquation","./events/EventEmitter","./material/ContactMaterial","./material/Material","./math/vec2","./objects/Body","./objects/LinearSpring","./objects/RotationalSpring","./objects/Spring","./objects/TopDownVehicle","./shapes/Box","./shapes/Capsule","./shapes/Circle","./shapes/Convex","./shapes/Heightfield","./shapes/Line","./shapes/Particle","./shapes/Plane","./shapes/Shape","./solver/GSSolver","./solver/Solver","./utils/ContactEquationPool","./utils/FrictionEquationPool","./utils/Pool","./utils/Utils","./world/World","37","arguments","axes","updateArea","./Convex","./Shape","38","intersectCapsule_hitPointWorld","intersectCapsule_normal","intersectCapsule_l0","intersectCapsule_l1","intersectCapsule_unit_y","hitPointWorld","l0","halfLen","diagonalLengthSquared","sqrtDelta","inv2a","d1","39","Ray_intersectSphere_intersectionPoint","Ray_intersectSphere_normal","intersectionPoint","40","isArray","triangles","polyk","tmpVec1","tmpVec2","projectOntoLocalAxis","projectOntoWorldAxis","shapeOffset","shapeAngle","polykVerts","id3","updateCenterOfMass_centroid","updateCenterOfMass_centroid_times_mass","updateCenterOfMass_a","updateCenterOfMass_b","updateCenterOfMass_c","centroid_times_mass","triangleArea","denom","numer","intersectConvex_rayStart","intersectConvex_rayEnd","intersectConvex_normal","rayStart","rayEnd","../math/polyk","41","key","maxValue","minValue","updateMaxMinValues","getLineSegment","start","getSegmentIndex","getClampedSegmentIndex","intersectHeightfield_worldNormal","intersectHeightfield_l0","intersectHeightfield_l1","intersectHeightfield_localFrom","intersectHeightfield_localTo","localFrom","localTo","42","raycast_normal","raycast_l0","raycast_l1","raycast_unit_y","43","44","intersectPlane_planePointToFrom","intersectPlane_normal","intersectPlane_len","planePointToFrom","planeToFrom","n_dot_dir","45","material","sensor","46","GS","iterations","tolerance","arrayStep","lambda","Bs","invCs","useZeroRHS","frictionIterations","usedIterations","setArrayZero","array","solve","sortEquations","maxIter","maxFrictionIter","Neq","tolSquared","Nbodies","deltalambdaTot","iterateEquation","updateMultipliers","invDt","B","invC","lambdaj","GWlambda","lambdaj_plus_deltalambda","./Solver","47","equationSortFunction","mockWorld","solveIsland","island","removeAllEquations","addEquations","getBodies","sort","addEquation","removeEquation","ISLAND","48","destroy","equation","./Pool","49","50","IslandNodePool","IslandNode","../world/IslandNode","51","IslandPool","Island","../world/Island","52","OverlapKeeper","overlappingShapesLastState","overlappingShapesCurrentState","recordPool","OverlapKeeperRecordPool","tmpDict","tmpArray1","tick","current","keys","lastObject","getByKey","setOverlapping","getNewOverlaps","getDiff","getEndOverlaps","dictA","dictB","isNewOverlap","idA","idB","getNewBodyOverlaps","getBodyDiff","getEndBodyOverlaps","accumulator","./OverlapKeeperRecord","./OverlapKeeperRecordPool","./TupleDictionary","./Utils","53","OverlapKeeperRecord","54","record","55","objects","resize","object","56","getKey","dict","57","howmany","P2_ARRAY_TYPE","Float32Array","58","bodyIds","59","IslandManager","nodePool","islandPool","islands","nodes","queue","getUnvisitedNode","Nnodes","visited","visit","bds","Neqs","bfs","root","child","neighbors","split","ni","nj","./../utils/IslandNodePool","./../utils/IslandPool","./Island","./IslandNode","60","61","springs","disabledBodyCollisionPairs","solver","islandManager","gravity","frictionGravity","useWorldGravityAsFrictionGravity","useFrictionGravityOnZeroGravity","broadphase","constraints","defaultMaterial","defaultContactMaterial","lastTimeStep","applySpringForces","applyGravity","solveConstraints","contactMaterials","stepping","bodiesToBeRemoved","islandSplit","emitImpactEvent","_constraintIdCounter","_bodyIdCounter","postStepEvent","addBodyEvent","removeBodyEvent","addSpringEvent","spring","impactEvent","contactEquation","postBroadphaseEvent","pairs","sleepMode","NO_SLEEPING","beginContactEvent","endContactEvent","preSolveEvent","BODY_SLEEPING","ISLAND_SLEEPING","constraint","addContactMaterial","contactMaterial","removeContactMaterial","getContactMaterial","cmats","step_mg","xiw","xjw","step","timeSinceLastCalled","maxSubSteps","internalStep","substeps","endOverlaps","Nsprings","np","mg","gravityLen","ignoredPairs","Nconstraints","Nresults","runNarrowphase","ev","glen","aiw","ajw","reducedMass","resolver","numFrictionBefore","numFrictionEquations","addSpring","evt","removeSpring","getBodyById","disableBodyCollision","enableBodyCollision","cs","cms","hitTest_tmp1","hitTest_tmp2","hitTest","pb","ps","NS","setGlobalStiffness","setGlobalRelaxation","tmpAABB","../../package.json","../collision/Narrowphase","../collision/SAPBroadphase","../constraints/DistanceConstraint","../constraints/GearConstraint","../constraints/LockConstraint","../constraints/PrismaticConstraint","../constraints/RevoluteConstraint","../material/ContactMaterial","../material/Material","../objects/LinearSpring","../objects/RotationalSpring","../shapes/Capsule","../shapes/Line","../solver/GSSolver","../solver/Solver","../utils/OverlapKeeper","./IslandManager","_CreateEmptyTexture","gl","scaleMode","texture","createTexture","bindTexture","TEXTURE_2D","texParameteri","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","TEXTURE_MAG_FILTER","PIXI","scaleModes","LINEAR","NEAREST","TEXTURE_MIN_FILTER","texImage2D","RGBA","UNSIGNED_BYTE","_CreateFramebuffer","textureUnit","framebuffer","createFramebuffer","depthStencilBuffer","createRenderbuffer","colorBuffer","fbStatus","activeTexture","TEXTURE0","bindFramebuffer","FRAMEBUFFER","bindRenderbuffer","RENDERBUFFER","framebufferRenderbuffer","DEPTH_STENCIL_ATTACHMENT","renderBuffer","framebufferTexture2D","COLOR_ATTACHMENT0","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","error","_fbErrors","targetTexture","DisplayObject","pivot","rotation","alpha","visible","hitArea","renderable","parent","worldAlpha","worldTransform","Phaser","Matrix","worldScale","worldRotation","filterArea","_sr","_cr","_bounds","Rectangle","_currentBounds","_mask","_cacheAsBitmap","_cacheIsDirty","children","_destroyCachedSprite","updateTransform","game","tx","ty","pt","wt","PI2","rotationCache","determ","HALF_PI","transformCallback","transformCallbackContext","preUpdate","generateTexture","resolution","renderer","bounds","getLocalBounds","renderTexture","RenderTexture","_tempMatrix","render","updateCache","_generateCachedSprite","toGlobal","toLocal","applyInverse","_renderCachedSprite","renderSession","_cachedSprite","Sprite","_renderWebGL","_renderCanvas","baseTexture","_enableMultiTextureToggle","textureIndex","tempFilters","_filters","filters","anchor","displayObjectUpdateTransform","defineProperties","worldVisible","item","mask","isMask","passes","filterPasses","_filterBlock","blendMode","blendModes","MULTIPLY","NORMAL","cacheAsBitmap","DisplayObjectContainer","ignoreChildInput","addChild","addChildAt","removeChild","swapChildren","child2","index1","getChildIndex","index2","setChildIndex","currentIndex","getChildAt","removeChildAt","removeChildren","beginIndex","endIndex","range","removed","displayObjectContainerUpdateTransform","getBounds","targetCoordinateSpace","isTargetCoordinateSpaceDisplayObject","isTargetCoordinateSpaceThisOrParent","contains","matrixCache","identityMatrix","childBounds","childMaxX","childMaxY","minX","Infinity","minY","maxX","maxY","childVisible","w0","w1","h0","h1","x1","y1","x2","y2","x3","y3","x4","y4","targetCoordinateSpaceBounds","spriteBatch","flush","filterManager","pushFilter","maskManager","pushMask","popMask","popFilter","_width","_height","defaultAnchor","Texture","emptyTexture","tint","cachedTint","tintedTexture","shader","exists","hasLoaded","onTextureUpdate","frame","setTexture","destroyBase","skipRender","valid","matrix","crop","currentBlendMode","globalCompositeOperation","blendModesCanvas","globalAlpha","smoothProperty","trim","shakeX","shakeY","cw","ch","rotated","roundPixels","setTransform","requiresReTint","CanvasTinter","getTintedTexture","drawImage","source","initDefaultShaders","CompileVertexShader","shaderSrc","_CompileShader","VERTEX_SHADER","CompileFragmentShader","FRAGMENT_SHADER","shaderType","src","join","createShader","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","log","getShaderInfoLog","compileProgram","vertexSrc","fragmentSrc","fragmentShader","vertexShader","shaderProgram","createProgram","attachShader","linkProgram","getProgramParameter","LINK_STATUS","getProgramInfoLog","PixiShader","_UID","program","textureCount","firstRun","dirty","attributes","init","initMultitexShader","MAX_TEXTURES","getParameter","MAX_TEXTURE_IMAGE_UNITS","dynamicIfs","defaultVertexSrc","useProgram","uSamplerArray","getUniformLocation","projectionVector","offsetVector","dimensions","aVertexPosition","getAttribLocation","aTextureCoord","colorAttribute","aTextureIndex","indices","tempTexture","RGB","uniform1iv","uniforms","uniformLocation","initUniforms","initDefaultShader","uSampler","usingFilter","uniform","_init","initSampler2D","glMatrix","glValueLength","glFunc","uniformMatrix2fv","uniformMatrix3fv","uniformMatrix4fv","_glTextures","textureData","magFilter","minFilter","wrapS","wrapT","format","LUMINANCE","repeat","REPEAT","pixelStorei","UNPACK_FLIP_Y_WEBGL","flipY","border","uniform1i","syncUniforms","transpose","z","_dirty","instances","updateTexture","deleteProgram","PixiFastShader","uMatrix","aPositionCoord","aScale","aRotation","StripShader","translationMatrix","attribute","PrimitiveShader","tintColor","ComplexPrimitiveShader","color","glContexts","WebGLRenderer","config","defaultRenderer","extensions","WEBGL","transparent","autoResize","preserveDrawingBuffer","clearBeforeRender","view","canvas","_contextOptions","antialias","failIfMajorPerformanceCaveat","premultipliedAlpha","stencil","projection","shaderManager","WebGLShaderManager","WebGLSpriteBatch","WebGLMaskManager","WebGLFilterManager","stencilManager","WebGLStencilManager","blendModeManager","WebGLBlendModeManager","currentBatchedTextures","drawCount","maxTextureAvailableSpace","initContext","mapBlendModes","getContext","maxTextures","maxTextureSize","MAX_TEXTURE_SIZE","glContextId","disable","DEPTH_TEST","CULL_FACE","enable","BLEND","setContext","compression","etc1","getExtension","pvrtc","s3tc","ETC1","PVRTC","S3TC","setTexturePriority","textureNameCollection","clampPot","potSize","imageCache","cache","_cache","image","imageName","base","stage","contextLost","viewport","clearColor","_bgColor","COLOR_BUFFER_BIT","camera","_shake","renderDisplayObject","displayObject","buffer","setBlendMode","begin","style","updateCompressedTexture","textureMetaData","compressedTexImage2D","glExtensionFormat","mipmap","isPowerOfTwo","LINEAR_MIPMAP_LINEAR","NEAREST_MIPMAP_NEAREST","generateMipmap","_powerOf2","compressionAlgorithm","UNPACK_PREMULTIPLY_ALPHA_WEBGL","CanvasPool","remove","blendModesWebGL","modes","ONE","ONE_MINUS_SRC_ALPHA","ADD","SRC_ALPHA","DST_ALPHA","DST_COLOR","SCREEN","OVERLAY","DARKEN","LIGHTEN","COLOR_DODGE","COLOR_BURN","HARD_LIGHT","SOFT_LIGHT","DIFFERENCE","EXCLUSION","HUE","SATURATION","COLOR","LUMINOSITY","getMaxTextureUnit","enableMultiTexture","textureArray","blendModeWebGL","blendFunc","maskData","WebGLGraphics","updateGraphics","_webGL","pushStencil","popStencil","stencilStack","count","graphics","webGLData","bindGraphics","STENCIL_TEST","STENCIL_BUFFER_BIT","colorMask","stencilFunc","ALWAYS","stencilOp","KEEP","INVERT","drawElements","TRIANGLE_FAN","UNSIGNED_SHORT","EQUAL","DECR","INCR","TRIANGLE_STRIP","_currentGraphics","complexPrimitiveShader","setShader","uniform1f","toArray","uniform2f","uniform3fv","Color","hexToRGBArray","bindBuffer","ARRAY_BUFFER","vertexAttribPointer","FLOAT","ELEMENT_ARRAY_BUFFER","indexBuffer","primitiveShader","maxAttibs","attribState","tempAttribState","stack","defaultShader","fastShader","stripShader","creatureShader","CreatureShader","setAttribs","attribs","attribId","enableVertexAttribArray","disableVertexAttribArray","_currentId","currentShader","vertSize","vertexSize","numVerts","numIndices","ArrayBuffer","positions","colors","Uint32Array","Uint16Array","lastIndexCount","drawing","currentBatchSize","currentBaseTexture","textures","shaders","sprites","Filter","vertexBuffer","createBuffer","bufferData","STATIC_DRAW","DYNAMIC_DRAW","sprite","uvs","_uvs","aX","aY","a0","b0","c0","d0","_w1","_w0","_updateUvsInverted","x0","y0","renderTilingSprite","tilingTexture","TextureUvs","tilePosition","tileScaleOffset","offsetX","offsetY","scaleX","tileScale","scaleY","stride","bufferSubData","subarray","nextTexture","nextBlendMode","nextShader","batchSize","blendSwap","shaderSwap","skip","renderBatch","startIndex","TRIANGLES","deleteBuffer","WebGLFastSpriteBatch","maxSize","renderSprite","filterStack","texturePool","initShaderBuffers","filterBlock","_filterArea","_previous_stencil_mgr","filter","FilterTexture","padding","frameBuffer","_glFilterTexture","vertexArray","uvBuffer","uvArray","inputTexture","outputTexture","filterPass","applyFilterPass","sizeX","sizeY","currentFilter","colorArray","36054","36055","36057","36061","DEFAULT","renderbufferStorage","DEPTH_STENCIL","deleteFramebuffer","deleteTexture","CanvasBuffer","clearRect","CanvasMaskManager","save","cacheAlpha","transform","CanvasGraphics","renderGraphicsMask","clip","restore","tintMethod","tintWithMultiply","fillStyle","toString","substr","fillRect","tintWithPerPixel","rgbValues","pixelData","getImageData","pixels","canHandleAlpha","putImageData","CanvasRenderer","CANVAS","refresh","Canvas","getSmoothingPrefix","navigator","isCocoonJS","screencanvas","rgba","removeView","useNew","device","canUseMultiply","BaseTexture","complete","naturalWidth","naturalHeight","forceLoaded","removeByCanvas","unloadFromGPU","glTexture","fromCanvas","TextureSilentFail","noFrame","isTiling","requiresUpdate","setFrame","onBaseTextureLoaded","_updateUvs","tw","th","define","amd","WheelEventProxy","scaleFactor","deltaMode","_scaleFactor","_deltaMode","originalEvent","VERSION","GAMES","AUTO","HEADLESS","WEBGL_MULTI","NONE","LEFT","RIGHT","UP","DOWN","SPRITE","BUTTON","IMAGE","GRAPHICS","TEXT","TILESPRITE","BITMAPTEXT","GROUP","RENDERTEXTURE","TILEMAP","TILEMAPLAYER","EMITTER","POLYGON","BITMAPDATA","CANVAS_FILTER","WEBGL_FILTER","ELLIPSE","SPRITEBATCH","RETROFONT","POINTER","ROPE","RECTANGLE","MATRIX","POINT","ROUNDEDRECTANGLE","CREATURE","VIDEO","PENDING_ATLAS","HORIZONTAL","VERTICAL","LANDSCAPE","PORTRAIT","ANGLE_UP","ANGLE_DOWN","ANGLE_LEFT","ANGLE_RIGHT","ANGLE_NORTH_EAST","ANGLE_NORTH_WEST","ANGLE_SOUTH_EAST","ANGLE_SOUTH_WEST","TOP_LEFT","TOP_CENTER","TOP_RIGHT","LEFT_TOP","LEFT_CENTER","LEFT_BOTTOM","CENTER","RIGHT_TOP","RIGHT_CENTER","RIGHT_BOTTOM","BOTTOM_LEFT","BOTTOM_CENTER","BOTTOM_RIGHT","trunc","Function","bind","thisArg","bound","args","boundArgs","concat","TypeError","F","proto","arg","forEach","fun","CheapArray","assert","assign","varArgs","hasOwn","hasOwnProperty","nextSource","nextKey","reverseString","string","getProperty","obj","parts","_getProperty","setProperties","props","setProperty","_setProperty","val","currentObj","chanceRoll","chance","random","randomChoice","choice1","choice2","parseDimension","dimension","parseInt","innerWidth","innerHeight","pad","dir","padlen","isPlainObject","nodeType","copyIsArray","deep","mixinPrototype","mixin","replace","mixinKeys","childNodes","cloneNode","diameter","_diameter","_radius","circumference","setTo","copyFrom","copyTo","dest","round","output","circumferencePoint","asDegrees","sample","steps","startAngle","endAngle","linear","offsetPoint","top","bottom","equals","intersects","degToRad","intersectsRectangle","halfWidth","halfHeight","xCornerDist","yCornerDist","intersectsLine","returnPoints","del","p0Exists","pointOnSegment","p1Exists","Ellipse","normx","normy","fromPoints","fromSprite","startSprite","endSprite","useCenter","centerX","centerY","fromAngle","rotateAround","line","asSegment","intersectsPoints","midPoint","centerOn","pointOnLine","fuzzyEqual","xMin","xMax","yMin","yMax","coordinatesOnLine","stepRate","results","sx","sy","err","e2","wrap","uc","ua","ub","empty","bx1","by1","bx2","by2","intersectionWithRectangle","edgeIntersection","closestDistance","normalAngle","fromArray","newPos","translate","tx1","identity","invert","setToPolar","azimuth","clampX","clamp","clampY","equalsXY","fuzzyEquals","fuzzyEqualsXY","angleXY","atan2","radToDeg","atan","getMagnitude","getMagnitudeSq","setMagnitude","magnitude","isZero","limit","expand","perp","rperp","normalRightHand","negative","multiplyAdd","interpolate","project","amt","projectUnit","pointslength","parse","xProp","yProp","isPoint","sortClockwise","center","_points","closed","flattened","toNumberArray","flatten","inside","ix","iy","jx","jy","calculateArea","avgHeight","floorAll","ceilAll","copyFromBounds","inflate","containsRect","intersection","intersectsRaw","union","randomX","randomY","getPoint","sides","inflatePoint","createFromBounds","containsRaw","rx","ry","rw","rh","volume","sameDimensions","NEGATIVE_INFINITY","POSITIVE_INFINITY","EmptyRectangle","RoundedRectangle","Camera","deadzone","roundPx","atLimit","totalInView","onShakeComplete","Signal","onFlashComplete","onFadeComplete","fx","_targetPosition","_edge","_position","intensity","duration","horizontal","vertical","shakeBounds","_fxDuration","_fxType","_fixedView","FOLLOW_LOCKON","FOLLOW_PLATFORMER","FOLLOW_TOPDOWN","FOLLOW_TOPDOWN_TIGHT","SHAKE_BOTH","SHAKE_HORIZONTAL","SHAKE_VERTICAL","ENABLE_FX","boot","Graphics","follow","lerpX","lerpY","helper","unfollow","focusOn","setPosition","focusOnXY","shake","flash","beginFill","drawRect","endFill","fade","updateFX","updateShake","checkBounds","elapsedMS","dispatch","rnd","frac","updateTarget","math","setBoundsToWorld","vx","vw","vy","vh","setSize","resetFX","State","make","input","load","sound","state","tweens","particles","physics","preload","loadUpdate","loadRender","preRender","paused","resumed","pauseUpdate","shutdown","StateManager","pendingState","states","_pendingState","_clearWorld","_clearCache","_created","_args","onStateChange","onInitCallback","onPreloadCallback","onCreateCallback","onUpdateCallback","onRenderCallback","onResizeCallback","onPreRenderCallback","onLoadUpdateCallback","onLoadRenderCallback","onPausedCallback","onResumedCallback","onPauseUpdateCallback","onShutDownCallback","onPause","pause","onResume","resume","autoStart","newState","isBooted","callbackContext","clearWorld","clearCache","checkState","restart","dummy","previousStateKey","clearCurrentState","setCurrentState","totalQueuedFiles","totalQueuedPacks","loadComplete","removeAll","debug","link","unlink","_kickstart","getCurrentState","elapsedTime","renderType","_bindings","_prevParams","memorize","_shouldPropagate","active","_boundDispatch","validateListener","fnName","_registerListener","isOnce","listenerContext","priority","binding","prevIndex","_indexOfListener","SignalBinding","_addBinding","execute","_priority","cur","_listener","addOnce","_destroy","getNumListeners","halt","bindings","paramsArr","forget","dispose","_this","signal","_isOnce","_signal","callCount","params","handlerReturn","detach","isBound","getListener","getSignal","prevPoint","Date","mouse","date","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","sampleRate","iChannel0","iChannel1","iChannel2","iChannel3","setResolution","pointer","toFixed","totalElapsedSeconds","anchorX","anchorY","Cache","Plugin","hasPreUpdate","hasUpdate","hasPostUpdate","hasRender","hasPostRender","postRender","PluginManager","plugins","_len","_i","plugin","postUpdate","Stage","disableVisibilityChange","currentRenderOrderID","_hiddenVar","_onChange","parseConfig","setBackgroundColor","DOM","getOffset","setUserSelect","setTouchAction","checkVisibility","document","hidden","webkitHidden","mozHidden","msHidden","visibilityChange","_onClick","hasFocus","addEventListener","onblur","onfocus","onpagehide","onpageshow","cocoonJSApp","CocoonJS","App","onSuspended","onActivated","focusLoss","focusGain","gamePaused","gameResumed","valueToColor","updateColor","removeEventListener","silent","hash","removeFromHash","Group","addToStage","enableBody","physicsBodyType","Physics","ARCADE","physicsType","alive","ignoreDestroy","pendingDestroy","classType","cursor","inputEnableChildren","updateOnlyExistingChildren","onChildInputDown","onChildInputUp","onChildInputOver","onChildInputOut","enableBodyDebug","physicsSortDirection","onDestroy","cursorIndex","fixedToCamera","cameraOffset","_sortProperty","RETURN_NONE","RETURN_TOTAL","RETURN_CHILD","RETURN_ALL","SORT_ASCENDING","SORT_DESCENDING","updateZ","addToHash","inputEnabled","events","onAddedToGroup$dispatch","addAt","addMultiple","moveAll","getAt","createMultiple","quantity","singleKey","singleFrame","align","cellWidth","cellHeight","alignIn","resetCursor","next","previous","swap","child1","bringToTop","getIndex","sendToBack","moveUp","moveDown","xy","getByName","oldChild","newChild","hasProperty","operation","checkProperty","checkAlive","checkVisible","setAll","setAllChildren","checkAll","checkAny","addAll","property","amount","subAll","multiplyAll","divideAll","kill","killAll","callAllExists","revive","reviveAll","resetAll","checkExists","resetChild","existsValue","callbackFromArray","callAll","method","methodLength","contextLength","renderOrderID","predicate","ArraySet","forEachExists","iterate","forEachAlive","forEachDead","order","ascendingSortHandler","descendingSortHandler","customSort","sortHandler","returnType","total","getFirst","getFirstExists","createIfNull","getFirstAlive","getFirstDead","loadTexture","getTop","getBottom","getClosestTo","tempDistance","getFurthestFrom","countLiving","countDead","getRandom","ArrayUtils","getRandomItem","getRandomExists","list","getAll","pick","destroyPhase","onRemovedFromGroup$dispatch","group","destroyTexture","removeBetween","scatter","shuffle","destroyChildren","soft","_definedSize","stateChange","setBounds","useBounds","wrapAll","between","Game","physicsConfig","multiTexture","isRunning","raf","net","Device","lockRender","pendingStep","stepCount","onBlur","onFocus","_paused","_codePaused","currentUpdateID","updatesThisFrame","rendersThisFrame","_deltaTime","_lastCount","_spiraling","fpsProblemNotifier","forceSingleUpdate","forceSingleRender","dropFrames","_nextFpsNotification","enableDebug","RandomDataGenerator","now","whenReady","seed","ScaleManager","setUpRenderer","GameObjectFactory","GameObjectCreator","Loader","Time","TweenManager","Input","SoundManager","Particles","Create","Net","Debug","isDisabled","showDebugHeader","RequestAnimationFrame","stopFocus","focus","isReady","onReady","hideBanner","webAudio","ie","setImageRenderingCrisp","webGL","contextRestored","webGLRendererError","cocoonJS","smoothed","addToDOM","preventDefault","clearGLTextures","updateLogic","desiredFpsMult","updateRender","slowMotion","desiredFps","slowStep","elapsed","countUpdate","countRender","enableStep","disableStep","removeFromDOM","muteOnPause","setMute","cordova","iOS","unsetMute","hitCanvas","hitContext","moveCallbacks","customCandidateHandler","customCandidateHandlerContext","pollRate","multiInputOverride","MOUSE_TOUCH_COMBINE","maxPointers","tapRate","doubleTapRate","holdRate","justPressedRate","justReleasedRate","recordPointerHistory","recordRate","recordLimit","touchLockCallbacks","pointer1","pointer2","pointer3","pointer4","pointer5","pointer6","pointer7","pointer8","pointer9","pointer10","pointers","activePointer","mousePointer","keyboard","touch","mspointer","gamepad","resetLocked","onDown","onUp","onTap","onHold","minPriorityID","interactiveItems","_localPoint","_pollCounter","_oldPosition","_x","_y","MOUSE_OVERRIDES_TOUCH","TOUCH_OVERRIDES_MOUSE","MAX_POINTERS","Pointer","PointerMode","CURSOR","addPointer","Mouse","Touch","MSPointer","Keyboard","Gamepad","_onClickTrampoline","onClickTrampoline","setInteractiveCandidateHandler","addMoveCallback","addTouchLockCallback","onEnd","removeTouchLockCallback","executeTouchLockCallbacks","cb","deleteMoveCallback","CONTACT","hard","resetSpeed","startPointer","countActivePointers","updatePointer","identifier","move","stopPointer","getPointer","isActive","getPointerFromIdentifier","getPointerFromId","pointerId","getLocalPosition","Creature","TileSprite","graphicsData","fill","processClickTrampolines","mouseDownCallback","mouseUpCallback","mouseOutCallback","mouseOverCallback","mouseWheelCallback","capture","button","wheelDelta","locked","stopOnGameOut","pointerLock","_onMouseDown","_onMouseMove","_onMouseUp","_onMouseOut","_onMouseOver","_onMouseWheel","_wheelEvent","NO_BUTTON","LEFT_BUTTON","MIDDLE_BUTTON","RIGHT_BUTTON","BACK_BUTTON","FORWARD_BUTTON","WHEEL_UP","WHEEL_DOWN","android","chrome","onMouseDown","onMouseMove","onMouseUp","_onMouseUpGlobal","onMouseUpGlobal","_onMouseOutGlobal","onMouseOutGlobal","onMouseOut","onMouseOver","onMouseWheel","wheelEvent","mouseMoveCallback","withinGame","resetButtons","bindEvent","deltaY","requestPointerLock","element","mozRequestPointerLock","webkitRequestPointerLock","_pointerLockChange","pointerLockChange","pointerLockElement","mozPointerLockElement","webkitPointerLockElement","releasePointerLock","exitPointerLock","mozExitPointerLock","webkitExitPointerLock","_stubsGenerated","prop","makeBinder","detail","deltaX","wheelDeltaX","deltaZ","pointerDownCallback","pointerMoveCallback","pointerUpCallback","_onMSPointerDown","_onMSPointerMove","_onMSPointerUp","_onMSPointerUpGlobal","_onMSPointerOut","_onMSPointerOver","onPointerDown","onPointerMove","onPointerUp","onPointerUpGlobal","onPointerOut","onPointerOver","pointerType","DeviceButton","buttonCode","isDown","isUp","timeDown","timeUp","repeats","altKey","shiftKey","ctrlKey","onFloat","startStop","condition","padFloat","justPressed","justReleased","pointerMode","leftButton","middleButton","rightButton","backButton","forwardButton","eraserButton","ERASER_BUTTON","_holdSent","_history","_nextDrop","_stateReset","clientX","clientY","pageX","pageY","screenX","screenY","rawMovementX","rawMovementY","movementX","movementY","isMouse","previousTapTime","totalTouches","msSinceLastClick","targetObject","interactiveCandidates","positionDown","positionUp","_clickTrampolines","_trampolineTargetObject","processButtonsDown","processButtonsUp","processButtonsUpDown","buttons","down","toLowerCase","updateButtons","totalActivePointers","_touchedHandler","processInteractiveObjects","shift","fromClick","pollLocked","mozMovementX","webkitMovementX","mozMovementY","webkitMovementY","noPause","isDragged","highestRenderOrderID","highestInputPriorityID","candidateTarget","currentNode","checked","validForInput","checkPointerDown","checkPointerOver","priorityID","swapTarget","newTarget","_pointerOutHandler","_pointerOverHandler","leave","currentPointers","addClickTrampoline","callbackArgs","trampolines","trampoline","_releasedHandler","resetMovement","touchStartCallback","touchMoveCallback","touchEndCallback","touchEnterCallback","touchLeaveCallback","touchCancelCallback","_onTouchStart","_onTouchMove","_onTouchEnd","_onTouchEnter","_onTouchLeave","_onTouchCancel","onTouchStart","onTouchMove","onTouchEnd","onTouchEnter","onTouchLeave","onTouchCancel","consumeDocumentTouches","_documentTouchMove","changedTouches","InputHandler","useHandCursor","_setHandCursor","allowHorizontalDrag","allowVerticalDrag","snapOffset","snapOnDrag","snapOnRelease","snapX","snapY","snapOffsetX","snapOffsetY","pixelPerfectOver","pixelPerfectClick","pixelPerfectAlpha","draggable","boundsRect","boundsSprite","scaleLayer","dragOffset","dragFromCenter","dragStopBlocksInputUp","dragStartPoint","dragDistanceThreshold","dragTimeThreshold","downPoint","snapPoint","_dragPoint","_dragPhase","_pendingDrag","_dragTimePass","_dragDistancePass","_wasEnabled","_tempPoint","_pointerData","camX","camY","isOver","isOut","timeOver","timeOut","downDuration","onAddedToGroup","addedToGroup","onRemovedFromGroup","removedFromGroup","highestID","highestRenderID","includePixelPerfect","isPixelPerfect","pointerX","pointerY","pointerDown","pointerUp","pointerTimeDown","pointerTimeUp","pointerOver","pointerOut","pointerTimeOver","pointerTimeOut","pointerDragged","fastTest","checkPixel","_dx","_dy","startDrag","_draggedPointerID","updateDrag","sendEvent","onInputOver$dispatch","onInputOut$dispatch","onInputDown$dispatch","dragTimeElapsed","onInputUp$dispatch","stopDrag","fromStart","pointerLocalCoord","globalToLocal","checkBoundsRect","checkBoundsSprite","onDragUpdate","justOver","delay","overDuration","justOut","enableDrag","lockCenter","pixelPerfect","alphaThreshold","disableDrag","boundsCenterLocalCoord","onDragStart$dispatch","globalToLocalX","grid","boundsFluid","scaleFluidInversed","globalToLocalY","globalCoord","onDragStop$dispatch","setDragLock","allowHorizontal","allowVertical","enableSnap","onDrag","onRelease","disableSnap","_gamepadIndexMap","_rawPads","_active","_gamepadSupportAvailable","webkitGetGamepads","webkitGamepads","userAgent","getGamepads","_prevRawGamepadTypes","_prevTimestamps","onConnectCallback","onDisconnectCallback","onDownCallback","onUpCallback","onAxisCallback","onFloatCallback","_ongamepadconnected","_gamepaddisconnected","_gamepads","SinglePad","addCallbacks","callbacks","onConnect","onDisconnect","onAxis","_onGamepadConnected","onGamepadConnected","_onGamepadDisconnected","onGamepadDisconnected","newPad","connect","removedPad","disconnect","_pollGamepads","pad1","pollStatus","pad2","pad3","pad4","rawGamepads","gamepadsChanged","_rawPad","singlePad","validConnections","rawIndices","padIndices","connected","rawPad","setDeadZones","deadZone","BUTTON_0","BUTTON_1","BUTTON_2","BUTTON_3","BUTTON_4","BUTTON_5","BUTTON_6","BUTTON_7","BUTTON_8","BUTTON_9","BUTTON_10","BUTTON_11","BUTTON_12","BUTTON_13","BUTTON_14","BUTTON_15","AXIS_0","AXIS_1","AXIS_2","AXIS_3","AXIS_4","AXIS_5","AXIS_6","AXIS_7","AXIS_8","AXIS_9","XBOX360_A","XBOX360_B","XBOX360_X","XBOX360_Y","XBOX360_LEFT_BUMPER","XBOX360_RIGHT_BUMPER","XBOX360_LEFT_TRIGGER","XBOX360_RIGHT_TRIGGER","XBOX360_BACK","XBOX360_START","XBOX360_STICK_LEFT_BUTTON","XBOX360_STICK_RIGHT_BUTTON","XBOX360_DPAD_LEFT","XBOX360_DPAD_RIGHT","XBOX360_DPAD_UP","XBOX360_DPAD_DOWN","XBOX360_STICK_LEFT_X","XBOX360_STICK_LEFT_Y","XBOX360_STICK_RIGHT_X","XBOX360_STICK_RIGHT_Y","PS3XC_X","PS3XC_CIRCLE","PS3XC_SQUARE","PS3XC_TRIANGLE","PS3XC_L1","PS3XC_R1","PS3XC_L2","PS3XC_R2","PS3XC_SELECT","PS3XC_START","PS3XC_STICK_LEFT_BUTTON","PS3XC_STICK_RIGHT_BUTTON","PS3XC_DPAD_UP","PS3XC_DPAD_DOWN","PS3XC_DPAD_LEFT","PS3XC_DPAD_RIGHT","PS3XC_STICK_LEFT_X","PS3XC_STICK_LEFT_Y","PS3XC_STICK_RIGHT_X","PS3XC_STICK_RIGHT_Y","padParent","_padParent","_prevTimestamp","_buttons","_buttonsLen","_axes","_axesLen","getButton","timestamp","rawButtonVal","isNaN","processButtonDown","processButtonUp","processButtonFloat","processAxisChange","triggerCallback","disconnectingIndex","axisCode","buttonValue","Key","keycode","_enabled","durationUp","keyCode","onHoldCallback","onHoldContext","_justDown","_justUp","processKeyDown","processKeyUp","upDuration","pressEvent","onPressCallback","_keys","_capture","_onKeyDown","_onKeyPress","_onKeyUp","_k","onPress","removeCallbacks","addKey","addKeyCapture","addKeys","removeKey","removeKeyCapture","createCursorKeys","up","KeyCode","processKeyPress","clearCaptures","String","fromCharCode","charCode","A","charCodeAt","C","D","E","H","J","K","L","M","O","P","Q","R","S","T","U","V","W","X","Y","Z","ZERO","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","NUMPAD_0","NUMPAD_1","NUMPAD_2","NUMPAD_3","NUMPAD_4","NUMPAD_5","NUMPAD_6","NUMPAD_7","NUMPAD_8","NUMPAD_9","NUMPAD_MULTIPLY","NUMPAD_ADD","NUMPAD_ENTER","NUMPAD_SUBTRACT","NUMPAD_DECIMAL","NUMPAD_DIVIDE","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","F13","F14","F15","COLON","EQUALS","COMMA","UNDERSCORE","PERIOD","QUESTION_MARK","TILDE","OPEN_BRACKET","BACKWARD_SLASH","CLOSED_BRACKET","QUOTES","BACKSPACE","TAB","CLEAR","ENTER","SHIFT","CONTROL","ALT","CAPS_LOCK","ESC","SPACEBAR","PAGE_UP","PAGE_DOWN","END","HOME","PLUS","MINUS","INSERT","DELETE","HELP","NUM_LOCK","match","Component","Angle","wrapAngle","Animation","play","frameRate","loop","killOnComplete","animations","AutoCull","autoCull","inCamera","checkWorldBounds","Bounds","container","alignTo","BringToTop","Core","skipTypeChecks","install","components","Events","PhysicsBody","AnimationManager","LoadTexture","FixedToCamera","previousRotation","preUpdateChildren","fresh","_exists","P2JS","customRender","Crop","cropRect","_crop","updateCrop","resetFrame","oldX","oldY","oldW","oldH","_frame","Delta","Destroy","onDestroy$dispatch","removeFrom","Video","onChangeSource","resizeFrame","BitmapText","_glyphs","_parent","_onDestroy","_onAddedToGroup","_onRemovedFromGroup","_onKilled","_onRevived","_onEnterBounds","_onOutOfBounds","_onInputOver","_onInputOut","_onInputDown","_onInputUp","_onDragStart","_onDragUpdate","_onDragStop","_onAnimationStart","_onAnimationComplete","_onAnimationLoop","onKilled","onRevived","onOutOfBounds","onEnterBounds","onInputOver","onInputOut","onInputDown","onInputUp","onDragStart","onDragStop","onAnimationStart","onAnimationComplete","onAnimationLoop","backing","_fixedToCamera","Health","health","maxHealth","damage","setHealth","heal","InCamera","InputEnabled","InWorld","outOfCameraBoundsKill","_outOfBoundsFired","onEnterBounds$dispatch","onOutOfBounds$dispatch","outOfBoundsKill","inWorld","LifeSpan","lifespan","physicsElapsedMS","onRevived$dispatch","onKilled$dispatch","stopAnimation","BitmapData","hasFrameData","loadFrameData","getFrameData","frameData","Tilemap","TilemapLayer","img","getImage","trimmed","spriteSourceSizeX","spriteSourceSizeY","sourceSizeW","sourceSizeH","refreshTexture","frameName","Overlap","_reset","Reset","ScaleMinMax","scaleMin","scaleMax","checkTransform","setScaleMinMax","Smoothed","existing","weapon","bulletClass","Weapon","createBullets","Image","creature","mesh","tween","physicsGroup","SpriteBatch","audio","audioSprite","addSprite","tileSprite","rope","Rope","text","Text","overFrame","outFrame","downFrame","upFrame","Button","emitter","maxParticles","Arcade","Emitter","retroFont","font","characterWidth","characterHeight","chars","charsPerRow","xSpacing","ySpacing","xOffset","yOffset","RetroFont","bitmapText","tilemap","tileWidth","tileHeight","addToCache","uuid","addRenderTexture","video","bitmapData","addBitmapData","Tween","preUpdatePhysics","preUpdateLifeSpan","preUpdateInWorld","preUpdateCore","_onOverFrame","_onOutFrame","_onDownFrame","_onUpFrame","onOverSound","onOutSound","onDownSound","onUpSound","onOverSoundMarker","onOutSoundMarker","onDownSoundMarker","onUpSoundMarker","onOverMouseOnly","justReleasedPreventsOver","freezeFrames","forceOut","setFrames","onInputOverHandler","onInputOutHandler","onInputDownHandler","onInputUpHandler","clearFrames","setStateFrame","switchImmediately","frameKey","changeStateFrame","setStateSound","marker","soundKey","markerKey","Sound","AudioSprite","playStateSound","setSounds","overSound","overMarker","downSound","downMarker","outSound","outMarker","upSound","upMarker","setOverSound","setOutSound","setDownSound","setUpSound","fastSpriteBatch","ready","isRotated","childTransform","skipPool","ctx","imageData","FrameData","textureFrame","addFrame","Frame","disableTextureUpload","cls","_image","_pos","_size","_scale","_rotate","_alpha","prev","_anchor","_tempR","_tempG","_tempB","_circle","_swapCanvas","moveH","moveV","draw","onload","addImage","toDataURL","processPixelRGB","pixel","createColor","unpackPixel","getPixel32","setPixel32","processPixel","replaceRGB","g1","g2","region","packPixel","setHSL","bHaveH","bHaveS","bHaveL","HSLtoRGB","shiftHSL","red","green","blue","immediate","LITTLE_ENDIAN","setPixel","getPixel","getPixelRGB","hsl","hsv","getPixels","getFirstPixel","scan","newWidth","newHeight","getCanvas","op","copyTransform","copyRect","drawGroup","drawGroupProxy","drawFull","renderGraphics","shadow","blur","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","alphaMask","sourceRect","maskRect","blendSourceAtop","blendReset","extract","destination","prevFont","fillText","beginPath","arc","closePath","moveTo","lineTo","lineWidth","strokeStyle","stroke","polygon","textureLine","createPattern","blendSourceOver","blendSourceIn","blendSourceOut","blendDestinationOver","blendDestinationIn","blendDestinationOut","blendDestinationAtop","blendXor","blendAdd","blendMultiply","blendScreen","blendOverlay","blendDarken","blendLighten","blendColorDodge","blendColorBurn","blendHardLight","blendSoftLight","blendDifference","blendExclusion","blendHue","blendSaturation","blendColor","blendLuminosity","copyBitmapData","destRowStart","getSmoothingEnabled","setSmoothingEnabled","getTransform","translateX","translateY","skewX","skewY","EarCut","holeIndices","dim","hasHoles","outerLen","outerNode","linkedList","eliminateHoles","earcutLinked","clockwise","insertNode","filterPoints","again","steiner","removeNode","ear","pass","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","minTX","minTY","maxTX","maxTY","minZ","zOrder","maxZ","nextZ","prevZ","locallyInside","isValidDiagonal","splitPolygon","getLeftmost","compareX","eliminateHole","hole","findHoleBridge","hx","hy","qx","tan","tanMin","sortLinked","q","tail","numMerges","pSize","qSize","inSize","leftmost","intersectsPolygon","middleInside","Node","an","bp","stencilBufferLimit","lastIndex","clearDirty","graphicsDataPool","switchMode","buildPoly","buildComplexPoly","buildLine","buildRectangle","buildCircle","buildRoundedRectangle","upload","WebGLGraphicsData","rectData","fillColor","fillAlpha","vertPos","tempPoints","rrectData","recPoints","quadraticBezierCurve","vecPos","fromX","fromY","cpX","cpY","toX","toY","getPt","n1","n2","perc","xa","ya","xb","yb","circleData","seg","totalSegs","firstPoint","lastPoint","midPointX","midPointY","unshift","p1x","p1y","p2x","p2y","p3x","p3y","perpx","perpy","perp2x","perp2y","perp3x","perp3y","indexCount","indexStart","lineColor","lineAlpha","glPoints","glIndicies","updateGraphicsTint","_fillTint","_lineTint","strokeRect","ox","oy","xe","ye","xm","ym","bezierCurveTo","maxRadius","quadraticCurveTo","tintR","tintG","tintB","GraphicsData","currentPath","boundsPadding","_localBounds","_boundsDirty","webGLDirty","cachedSpriteDirty","updateLocalBounds","drawTriangle","cull","triangle","cameraToFace","faceNormal","drawPolygon","drawTriangles","point1","point2","point3","lineStyle","drawShape","cpX2","cpY2","dt2","dt3","arcTo","mm","dd","cc","tt","k1","k2","j1","j2","qy","anticlockwise","segments","sweep","segs","startX","startY","filling","theta","theta2","cTheta","sTheta","segMinus","remainder","drawRoundedRect","drawCircle","drawEllipse","canvasBuffer","updateCachedSpriteTexture","_prevTint","tempPoint","cachedSprite","destroyCachedSprite","textureBuffer","tempMatrix","renderXY","renderRawXY","updateBase","realResolution","getBase64","webGLPixels","Uint8Array","readPixels","tempCanvas","canvasData","textBounds","strokeColors","fontStyles","fontWeights","autoRound","useAdvancedWrap","splitRegExp","characterLimitSize","characterLimitSuffix","_res","_text","_fontComponents","_lineSpacing","_charCount","setStyle","updateText","setShadow","shadowStroke","shadowFill","newStyle","backgroundColor","boundsAlignH","boundsAlignV","strokeThickness","wordWrap","wordWrapWidth","maxLines","tabs","fontToComponents","fontStyle","fontVariant","fontWeight","fontSize","componentsToFont","outputText","substring","runWordWrap","lines","lineWidths","maxLineWidth","fontProperties","determineFontProperties","drawnLines","measureLine","measureText","tab","section","snapToCeil","lineHeight","lineSpacing","textBaseline","lineCap","lineJoin","linePositionX","linePositionY","ascent","updateLine","updateShadow","strokeText","renderTabLine","snap","lineLength","letter","clearColors","clearFontValues","addColor","addStrokeColor","addFontStyle","addFontWeight","weight","precalculateWordWrap","advancedWordWrap","basicWordWrap","linesCount","currentLineWidth","words","word","wordWithSpace","wordWidth","newWord","secondPart","spaceLeft","wordWidthWithSpace","updateFont","family","exec","fontFamily","setText","parseList","setTextBounds","properties","fontPropertiesCache","fontPropertiesCanvas","fontPropertiesContext","baseline","descent","imagedata","setCharacterLimit","characterLimit","suffix","parseFloat","createElement","textWidth","textHeight","_prevAnchor","_maxWidth","_data","getBitmapFont","_font","_fontSize","_align","_tint","sourceWidth","sourceHeight","scanLine","lastSpace","wrappedWidth","prevCharCode","maxWidth","test","charAt","charData","kerning","xAdvance","cleanText","re","purgeGlyphs","kept","checkImageKey","characterSpacingX","characterSpacingY","characterPerRow","multiLine","autoUpperCase","customSpacingX","customSpacingY","fixedWidth","fontSet","grabData","currentX","currentY","updateFrameData","stamp","ALIGN_LEFT","ALIGN_RIGHT","ALIGN_CENTER","TEXT_SET1","TEXT_SET2","TEXT_SET3","TEXT_SET4","TEXT_SET5","TEXT_SET6","TEXT_SET7","TEXT_SET8","TEXT_SET9","TEXT_SET10","TEXT_SET11","setFixedWidth","lineAlignment","content","characterSpacing","allowLowerCase","buildRetroFontText","getLongestLine","pasteLine","longestLine","removeUnsupportedCharacters","stripCR","newString","aChar","code","updateOffset","diffX","diffY","frames","getFrames","newText","toUpperCase","_hasUpdateAnimation","_updateAnimationCallback","canvasPadding","drawMode","updateAnimation","nextPoint","perpLength","_vertexBuffer","_initWebGL","_renderStrip","_indexBuffer","_uvBuffer","_colorBuffer","_renderCanvasTriangleStrip","_renderCanvasTriangles","_renderCanvasDrawTriangle","index0","textureSource","textureWidth","textureHeight","u0","v2","paddingX","paddingY","normX","normY","deltaA","deltaB","deltaC","deltaD","deltaE","deltaF","renderStripFlat","strip","rawX","rawY","_updateAnimation","difference","_scroll","textureDebug","tilePattern","frameWidth","frameHeight","physicsElapsed","autoScroll","stopScroll","generateTilingTexture","restartBatch","sessionBlendMode","forcePowerOfTwo","targetWidth","targetHeight","getNextPowerOfTwo","pool","getTotal","getFree","deviceReadyAt","initialized","desktop","iOSVersion","nodeWebkit","electron","ejecta","crosswalk","chromeOS","linux","macOS","windows","windowsPhone","canvasBitBltShift","file","fileSystem","localStorage","worker","css3D","typedArray","vibration","getUserMedia","quirksMode","arora","chromeVersion","epiphany","firefox","firefoxVersion","ieVersion","trident","tridentVersion","mobileSafari","midori","opera","safari","safariVersion","webApp","silk","audioData","ogg","opus","mp3","wav","m4a","webm","dolby","oggVideo","h264Video","mp4Video","webmVideo","vp9Video","hlsVideo","iPhone","iPhone4","iPad","pixelRatio","littleEndian","support32bit","fullscreen","requestFullscreen","cancelFullscreen","fullscreenKeyboard","onInitialized","nonPrimer","readyCheck","_readyCheck","_monitor","_queue","readyState","setTimeout","_initialize","_checkIsLittleEndian","_checkIsUint8ClampedImageData","Uint8ClampedArray","createImageData","vita","kindle","RegExp","$1","_checkOS","$3","process","versions","_checkBrowser","audioElement","canPlayType","major","minor","$2","_checkAudio","videoElement","_checkVideo","has3d","el","transforms","webkitTransform","OTransform","msTransform","MozTransform","insertBefore","getComputedStyle","getPropertyValue","_checkCSS3D","Int8Array","Int32Array","vibrate","webkitVibrate","mozVibrate","msVibrate","getItem","WebGLRenderingContext","compatMode","webkitGetUserMedia","mozGetUserMedia","msGetUserMedia","oGetUserMedia","URL","webkitURL","mozURL","msURL","_checkFeatures","s1","s2","_checkCanvasFeatures","fs","cfs","Element","_checkFullScreenSupport","documentElement","maxTouchPoints","PointerEvent","MSPointerEvent","msPointerEnabled","pointerEnabled","canPlayAudio","canPlayVideo","needsTouchUnlock","PhaserGlobal","fakeiOSTouchLock","isAndroidStockBrowser","matches","display","msTouchAction","overflowHidden","getElementById","overflow","appendChild","parentNode","vendor","prefix","types","msInterpolationMode","setImageRenderingBicubic","forceSetTimeOut","vendors","requestAnimationFrame","cancelAnimationFrame","_isSetTimeOut","_onLoop","_timeOutID","updateSetTimeout","updateRAF","rafTime","timeToCall","clearTimeout","isSetTimeOut","isRAF","DEG_TO_RAD","RAD_TO_DEG","degrees","radians","fuzzyLessThan","fuzzyGreaterThan","fuzzyCeil","fuzzyFloor","average","shear","snapTo","gap","snapToFloor","roundTo","place","floorTo","ceilTo","rotateToAngle","currentAngle","targetAngle","getShortestAngle","angleBetween","angleBetweenY","angleBetweenPoints","angleBetweenPointsY","reverseAngle","angleRad","normalizeAngle","maxAdd","minSub","wrapValue","isOdd","isEven","minProperty","maxProperty","linearInterpolation","bezierInterpolation","bernstein","catmullRomInterpolation","catmullRom","factorial","res","roundAwayFromZero","sinCosGenerator","sinAmplitude","cosAmplitude","frequency","frq","cosTable","sinTable","hypot","distanceSq","distancePow","clampBottom","within","mapLinear","smoothstep","smootherstep","sign","percent","seeds","s0","sow","integer","real","integerInRange","realInRange","ary","weightedPick","QuadTree","maxObjects","maxLevels","_empty","subWidth","subHeight","populate","populateHandler","insert","retrieve","returnObjects","getHostName","location","hostname","checkDomainName","domain","updateQueryString","redirect","href","separator","getQueryString","parameter","keyValues","search","decodeURI","decodeURIComponent","frameBased","_tweens","_add","easeMap","Power0","Easing","Power1","Power2","Power3","Power4","Linear","None","Quad","Quadratic","Out","Cubic","Quart","Quartic","Quint","Quintic","Sine","Sinusoidal","Expo","Exponential","Circ","Circular","Elastic","Back","Bounce","Quad.easeIn","In","Cubic.easeIn","Quart.easeIn","Quint.easeIn","Sine.easeIn","Expo.easeIn","Circ.easeIn","Elastic.easeIn","Back.easeIn","Bounce.easeIn","Quad.easeOut","Cubic.easeOut","Quart.easeOut","Quint.easeOut","Sine.easeOut","Expo.easeOut","Circ.easeOut","Elastic.easeOut","Back.easeOut","Bounce.easeOut","Quad.easeInOut","InOut","Cubic.easeInOut","Quart.easeInOut","Quint.easeInOut","Sine.easeInOut","Expo.easeInOut","Circ.easeInOut","Elastic.easeInOut","Back.easeInOut","Bounce.easeInOut","_pauseAll","_resumeAll","pendingDelete","_manager","addTweens","numTweens","isTweening","checkIsRunning","some","_pause","_resume","pauseAll","resumeAll","manager","timeline","timeScale","repeatCounter","onStart","onLoop","onRepeat","onChildComplete","onComplete","chainedTween","isPaused","_onUpdateCallback","_onUpdateCallbackContext","_pausedTime","_hasStarted","ease","yoyo","Default","TweenData","vEnd","loadValues","updateTweenData","repeatDelay","yoyoDelay","easing","interpolation","repeatAll","chain","startTime","status","PENDING","RUNNING","LOOPED","COMPLETE","generateData","vStart","vStartCache","vEndCache","repeatTotal","inReverse","easingFunction","interpolationFunction","interpolationContext","isFrom","ms","fps","blob","reversed","asin","prevTime","_desiredFps","suggestedFps","advancedTiming","updates","renders","ups","rps","fpsMin","fpsMax","msMin","msMax","pauseDuration","timeExpected","Timer","_frameCount","_elapsedAccumulator","_started","_timeLastSecond","_pauseStarted","_justResumed","_timers","timer","autoDestroy","previousDateNow","updateAdvancedTiming","updateTimers","interval","elapsedSince","since","elapsedSecondsSince","running","expired","nextTick","timeCap","_pauseTotal","_now","_marked","_diff","_newTick","MINUTE","SECOND","HALF","QUARTER","repeatCount","TimerEvent","clearEvents","clearPendingEvents","adjustEvents","baseTime","currentFrame","currentAnim","updateIfVisible","isLoaded","_frameData","_anims","_outputFrames","anim","copyFrameData","useNumericIndex","getFrameIndexes","validateFrames","checkFrameName","isPlaying","getAnimation","refreshFrame","gotFrame","getFrame","getFrameByName","_frameIndex","_frames","loopCount","isFinished","_pauseStartTime","_frameDiff","_frameSkip","onUpdate","isReversed","_timeLastFrame","_timeNextFrame","updateCurrentFrame","onAnimationStart$dispatch","reverseOnce","frameId","useLocalFrameIndex","frameIndex","directionalOffset","dispatchComplete","onAnimationComplete$dispatch","onAnimationLoop$dispatch","signalUpdate","fromPlay","generateFrameNames","zeroPad","spriteSourceSizeW","spriteSourceSizeH","setTrim","actualWidth","actualHeight","destX","destY","destWidth","destHeight","getRect","_frameNames","getFrameRange","AnimationParser","spriteSheet","frameMax","margin","spacing","skipFrames","JSONData","json","newFrame","filename","sourceSize","spriteSourceSize","JSONDataPyxel","tileheight","tilewidth","JSONDataHash","XMLData","xml","getElementsByTagName","frameX","frameY","autoResolveURL","binary","bitmapFont","compressedTexture","_urlMap","_urlResolver","_urlTemp","onSoundUnlock","_cacheMap","TEXTURE","SOUND","PHYSICS","BINARY","BITMAPFONT","JSON","XML","SHADER","RENDER_TEXTURE","_pendingCount","_addImages","DEFAULT_KEY","DEFAULT_SRC","MISSING","MISSING_KEY","MISSING_SRC","READY_TIMEOUT","addCompressedTextureMetaData","extension","arrayBuffer","removeImage","LoaderParser","fileFormat","_resolveURL","addCanvas","addImageAsync","_removePending","_addPending","addDefaultImage","addMissingImage","addSound","audioTag","decoded","isDecoding","touchLocked","addText","addPhysicsData","addTilemap","mapData","addBinary","binaryData","addBitmapFont","atlasData","atlasType","jsonBitmapFont","xmlBitmapFont","addBitmapFontFromAtlas","atlasKey","atlasFrame","dataKey","dataType","getBaseTexture","fontData","getJSON","getXML","addJSON","addXML","addVideo","isBlob","addShader","addSpriteSheet","addTextureAtlas","TEXTURE_ATLAS_XML_STARLING","TEXTURE_ATLAS_JSON_PYXEL","reloadSound","getSound","reloadSoundComplete","updateSound","decodedSound","isSoundDecoded","isSoundReady","checkKey","checkURL","checkCanvasKey","checkTextureKey","checkSoundKey","checkTextKey","checkPhysicsKey","checkTilemapKey","checkBinaryKey","checkBitmapDataKey","checkBitmapFontKey","checkJSONKey","checkXMLKey","checkVideoKey","checkShaderKey","checkRenderTextureKey","full","getTextureFrame","getSoundData","getText","getPhysicsData","fixtureKey","fixtures","fixture","getTilemapData","getBinary","getBitmapData","getVideo","getShader","getRenderTexture","getFrameCount","getFrameByIndex","getURL","getKeys","removeCanvas","destroyBaseTexture","removeSound","removeText","removePhysics","removeTilemap","removeBinary","removeBitmapData","removeBitmapFont","removeJSON","removeXML","removeVideo","removeShader","removeRenderTexture","removeSpriteSheet","removeTextureAtlas","baseURL","destroyItem","readyTimeout","_ready","_checkReady","isLoading","preloadSprite","crossOrigin","headers","requestedWith","onLoadStart","onLoadComplete","onPackComplete","onFileStart","onFileComplete","onFileError","enableParallel","maxParallelDownloads","_withSyncPointDepth","_fileList","_flightQueue","_processingHead","_fileLoadStarted","_totalPackCount","_totalFileCount","_loadedPackCount","_loadedFileCount","TEXTURE_ATLAS_JSON_ARRAY","TEXTURE_ATLAS_JSON_HASH","PHYSICS_LIME_CORONA_JSON","PHYSICS_PHASER_JSON","setPreloadSprite","checkKeyExists","getAssetIndex","bestFound","loaded","loading","getAsset","fileIndex","addToFileList","overwrite","syncPoint","currentFile","replaceInFileList","pack","imageFromBitmapData","imageFromGrid","imageFromTexture","pixelWidth","pixelHeight","palette","exkey","images","urls","script","spritesheet","autoDecode","noAudio","jsonURL","jsonData","audiosprite","loadEvent","asBlob","CSV","TILED_JSON","LIME_CORONA_JSON","textureURL","atlasURL","parseXml","atlasJSONArray","atlas","atlasJSONHash","atlasXML","withSyncPoint","addSyncPoint","asset","removeFile","updateProgress","processLoadQueue","finishedLoading","requestUrl","requestObject","progress","syncblock","inflightLimit","processPack","loadFile","abnormal","asyncComplete","errorMessage","packData","transformUrl","xhrLoad","fileComplete","loadImageTag","getAudioURL","usingWebAudio","usingAudioTag","loadAudioTag","fileError","getVideoURL","loadVideoTag","jsonLoadComplete","xmlLoadComplete","csvLoadComplete","onerror","controls","autoplay","videoLoadEvent","canplay","Audio","playThroughEvent","xhr","XMLHttpRequest","open","responseType","setRequestHeader","message","send","videoType","uri","lastIndexOf","audioType","reason","loadNext","responseText","response","decode","language","defer","head","contentType","domparser","DOMParser","parseFromString","ActiveXObject","async","loadXML","totalLoadedFiles","totalLoadedPacks","progressFloat","info","common","getAttribute","letters","kernings","second","finalizeBitmapFont","_face","_lineHeight","_id","_xoffset","_yoffset","_xadvance","_second","_first","_amount","bitmapFontData","pvr","uintArray","byteArray","pvrHeader","pixelFormat","flags","colorSpace","channelType","depth","numberOfSurfaces","numberOfFaces","numberOfMipmaps","metaDataSize","byteLength","dds","ddsHeader","pitch","mipmapCount","formatSize","formatFlag","formatFourCC","formatBitCount","formatRBitMask","formatGBitMask","formatBBitMask","formatABitMask","caps1","caps2","caps3","caps4","reserved2","DXGIFormat","resourceDimension","miscFlag","arraySize","ktx","ktxHeader","imageSizeOffset","imageSize","glInternalFormat","endianness","glType","glTypeSize","glFormat","glBaseInternalFormat","pixelDepth","numberOfArrayElements","numberOfMipmapLevels","bytesOfKeyValueData","keyAndValueByteSize","pkm","pkmHeader","originalWidth","originalHeight","autoplayKey","sounds","spritemap","addMarker","connectToMaster","markers","totalDuration","currentTime","durationMS","stopTime","pausedPosition","pausedTime","currentMarker","fadeTween","pendingPlayback","override","allowMultiple","externalNode","masterGainNode","gainNode","_sound","_globalVolume","_markedToDelete","_removeFromSoundManager","masterGain","createGain","createGainNode","gain","soundHasUnlocked","onDecoded","onPlay","onStop","onMute","onMarkerComplete","_volume","_buffer","_muted","_tempMarker","_tempPosition","_tempVolume","_tempPause","_muteVolume","_tempLoop","_onDecodedEventDispatched","removeMarker","onEndedHandler","onended","isDecoded","loopFull","forceRestart","noteOff","createBufferSource","noteGrainOn","muted","mute","prevMarker","fadeIn","fadeTo","fadeOut","fadeComplete","updateGlobalVolume","globalVolume","onSoundDecode","onVolumeChange","onUnMute","onTouchUnlock","channels","_codeMuted","_unlockSource","_sounds","_watchList","_watching","_watchCallback","_watchContext","disableAudio","disableWebAudio","audioContext","setTouchLock","unlock","setTouchUnlock","noteOn","stopAll","soundData","decodeAudioData","setDecodedCallback","files","playbackState","PLAYING_STATE","FINISHED_STATE","removeByKey","close","dom","minWidth","minHeight","maxHeight","forceLandscape","forcePortrait","incorrectOrientation","_pageAlignHorizontally","_pageAlignVertically","onOrientationChange","enterIncorrectOrientation","leaveIncorrectOrientation","hasPhaserSetFullScreen","fullScreenTarget","_createdFullScreenTarget","onFullScreenInit","onFullScreenChange","onFullScreenError","screenOrientation","getScreenOrientation","scaleFactorInversed","aspectRatio","sourceAspectRatio","windowConstraints","compatibility","supportsFullScreen","orientationFallback","noMargins","scrollTo","forceMinimumDocumentHeight","canExpandParent","clickTrampoline","_scaleMode","NO_SCALE","_fullScreenScaleMode","parentIsWindow","parentScaleFactor","trackParentInterval","onSizeChange","onResize","onResizeContext","_pendingScaleMode","_fullScreenRestore","_gameSize","_userScaleFactor","_userScaleTrim","_lastUpdate","_updateThrottle","_updateThrottleReset","_parentBounds","_tempBounds","_lastReportedCanvasSize","_lastReportedGameSize","_booted","setupScale","EXACT_FIT","SHOW_ALL","RESIZE","USER_SCALE","MODES","compat","_orientationChange","orientationChange","_windowResize","windowResize","_fullScreenChange","fullScreenChange","_fullScreenError","fullScreenError","_gameResumed","setGameSize","FlexGrid","fullScreenScaleMode","pageAlignHorizontally","alignH","pageAlignVertically","alignV","scaleH","scaleV","setUserScale","trimH","trimV","getParentBounds","visualBounds","updateDimensions","queueUpdate","currentScaleMode","hScale","vScale","hTrim","vTrim","setResizeCallback","signalSizeChange","setMinMax","prevThrottle","prevWidth","prevHeight","boundsChanged","orientationChanged","updateOrientationState","updateLayout","throttle","updateScalingAndBounds","forceOrientation","classifyOrientation","orientation","previousOrientation","previouslyIncorrect","isLandscape","isPortrait","changed","correctnessChanged","scrollTop","setMaximum","setExactFit","isFullScreen","boundingParent","setShowAll","resetCanvas","reflowCanvas","reflowGame","layoutBounds","clientRect","getBoundingClientRect","parentRect","offsetParent","wc","windowBounds","alignCanvas","parentBounds","canvasBounds","currentEdge","targetEdge","marginLeft","marginRight","marginTop","marginBottom","cssWidth","cssHeight","expanding","createFullScreenTarget","fsTarget","background","startFullScreen","allowTrampoline","cleanupCreatedTarget","initData","targetElement","ALLOW_KEYBOARD_INPUT","stopFullScreen","prepScreenMode","enteringFullscreen","createdTarget","scaleSprite","letterBox","scaleX1","scaleY1","scaleX2","scaleY2","scaleOnWidth","bmd","columnWidth","renderShadow","currentColor","currentAlpha","_line","_rect","soundInfo","filled","rectangle","geom","cameraInfo","hideIfUp","downColor","upColor","worldX","worldY","spriteInputInfo","justDown","justUp","inputInfo","spriteBounds","ropeSegments","segment","spriteInfo","spriteCoords","lineInfo","forceType","ellipse","quadTree","quadtree","NINJA","Ninja","BOX2D","Box2D","renderBody","bodyInfo","renderBodyInfo","box2d","box2dWorld","renderDebugDraw","box2dBody","displayList","canvasPool","phaser","factor","loader","box","scrollY","scrollLeft","scrollX","clientTop","clientLeft","cushion","calibrate","coords","getAspectRatio","inLayoutViewport","primaryFallback","screen","mozOrientation","msOrientation","matchMedia","documentBounds","pageXOffset","pageYOffset","clientWidth","clientHeight","offsetWidth","scrollWidth","offsetHeight","scrollHeight","randomIndex","removeRandomItem","newLength","transposeMatrix","sourceRowCount","sourceColCount","rotateMatrix","findClosest","arr","NaN","low","high","rotateRight","rotateLeft","numberArray","numberArrayStep","LinkedList","entity","palettes","0","PALETTE_ARNE","PALETTE_JMP","PALETTE_CGA","PALETTE_C64","PALETTE_JAPANESE_MACHINE","row","boundsCustom","boundsFull","boundsNone","positionCustom","positionFluid","positionFull","positionNone","scaleCustom","scaleFluid","scaleFull","scaleNone","customWidth","customHeight","customOffsetX","customOffsetY","ratioH","ratioV","layers","createCustomLayer","layer","FlexLayer","createFluidLayer","createFullLayer","createFixedLayer","persist","fitSprite","topLeft","topMiddle","topRight","bottomLeft","bottomMiddle","bottomRight","RED","ORANGE","YELLOW","GREEN","AQUA","BLUE","VIOLET","WHITE","BLACK","GRAY","RGBtoHSL","RGBtoHSV","fromRGBA","toRGBA","toABGR","RGBArrayToHex","rgb","hueToColor","HSVtoRGB","color32","getColor","getColor32","RGBtoString","componentToHex","hexToRGB","hex","hexToColor","webToColor","web","tempColor","getRGB","HSVColorWheel","HSLColorWheel","interpolateColor","color1","color2","currentStep","src1","src2","hsv1","hsv2","dh","h3","interpolateColorWithRGB","or","og","ob","interpolateRGB","getRandomColor","getWebRGB","getAlpha","getAlphaFloat","getRed","getGreen","getBlue","blendNormal","blendAverage","blendSubtract","blendNegation","blendLinearDodge","blendLinearBurn","blendLinearLight","blendVividLight","blendPinLight","blendHardMix","blendReflect","blendGlow","blendPhoenix","arcade","ninja","chipmunk","matter","CHIPMUNK","MATTERJS","P2","Matter","startSystem","system","enableAABB","checkCollision","OVERLAP_BIAS","forceX","sortDirection","LEFT_RIGHT","skipQuadTree","_total","SORT_NONE","RIGHT_LEFT","TOP_BOTTOM","BOTTOM_TOP","updateMotion","allowRotation","velocityDelta","computeVelocity","angularAcceleration","angularDrag","maxAngular","acceleration","drag","maxVelocity","allowGravity","allowDrag","object1","object2","overlapCallback","processCallback","collideObjects","collide","collideCallback","sortLeftRight","sortRightLeft","sortTopBottom","sortBottomTop","overlapOnly","collideHandler","collideGroupVsSelf","collideSpriteVsSprite","collideSpriteVsGroup","collideSpriteVsTilemapLayer","collideGroupVsGroup","collideGroupVsTilemapLayer","sprite1","sprite2","separate","items","bounds1","bounds2","group1","group2","body1","body2","none","isCircle","separateCircle","bodyRect","bodyCircle","resultX","resultY","separateX","separateY","onOverlap","onCollide","circleBodyIntersects","getOverlapX","getOverlapY","angleCollision","immovable","customSeparateX","tempVel1","tempVel2","bounce","maxOverlap","deltaAbsX","embedded","touching","overlapX","deltaAbsY","overlapY","moves","nv1","nv2","avg","customSeparateY","getObjectsUnderPointer","getObjectsAtLocation","callbackArg","moveToObject","maxTime","distanceBetween","moveToPointer","angleToPointer","distanceToPointer","moveToXY","distanceToXY","velocityFromAngle","velocityFromRotation","accelerationFromRotation","accelerateToObject","xSpeedMax","ySpeedMax","accelerateToPointer","accelerateToXY","angleToXY","closest","targets","farthest","angleBetweenCenters","worldAngleToPointer","preRotation","newVelocity","deltaMax","worldBounce","onWorldBounds","facing","overlapR","collideWorldBounds","wasTouching","blocked","tilePadding","syncBounds","isMoving","stopVelocityOnCollide","moveTimer","moveDistance","moveDuration","moveTarget","moveEnd","onMoveComplete","movementCallback","movementCallbackContext","_sx","_sy","updateBounds","asx","asy","updateCenter","updateMovement","collided","stopMovement","stopVelocity","check","moveFrom","setCircle","onFloor","onCeiling","onWall","TilemapCollision","TILE_BIAS","tilemapLayer","getTiles","getTileOffsetX","getTileOffsetY","separateTile","tile","tilemapLayerOffsetX","tilemapLayerOffsetY","collisionCallback","collisionCallbackContext","faceLeft","faceRight","faceTop","faceBottom","tileCheckX","tileCheckY","collideRight","collideLeft","processTileSeparationX","collideDown","collideUp","processTileSeparationY","useElapsedTime","materials","InversePointProxy","walls","onBodyAdded","onBodyRemoved","onSpringAdded","onSpringRemoved","onConstraintAdded","onConstraintRemoved","onContactMaterialAdded","onContactMaterialRemoved","postBroadphaseCallback","onBeginContact","onEndContact","mpx","mpxi","pxm","pxmi","beginContactHandler","endContactHandler","collisionGroups","nothingCollisionGroup","CollisionGroup","boundsCollisionGroup","everythingCollisionGroup","boundsCollidesWith","_toRemove","_collisionGroupID","_boundsLeft","_boundsRight","_boundsTop","_boundsBottom","_boundsOwnGroup","removeBodyNextStep","setImpactEvents","impactHandler","setPostBroadphaseCallback","postBroadphaseHandler","_bodyCallbacks","_bodyCallbackContext","_groupCallbacks","_groupCallbackContext","setCollisionGroup","setWorldMaterial","updateBoundsCollisionGroup","setupWall","wall","fixedStepTime","impactCallback","createDistanceConstraint","getBody","createGearConstraint","createRevoluteConstraint","createLockConstraint","createPrismaticConstraint","lockRotation","anchorA","anchorB","setMaterial","createMaterial","createContactMaterial","getSprings","getConstraints","filterStatic","physicsPosition","query","toJSON","createCollisionGroup","bitmask","createSpring","worldA","worldB","localA","localB","createRotationalSpring","createBody","addPolygon","createParticle","convertCollisionObjects","map","collision","shapeData","polyline","addRectangle","clearTilemapLayerBodies","getLayer","convertTilemap","optimize","collides","getTileRight","FixtureList","rawList","namedFixtures","groupedFixtures","allFixtures","setCategory","bit","getFixtures","setMask","setSensor","getFixtureByKey","getGroup","groupID","_ref","_results","callee","PointProxy","collidesWith","removeNextStep","debugBody","_collideWorldBounds","setRectangleFromSprite","createBodyCallback","createGroupCallback","getCollisionMask","updateCollisionMask","clearCollision","clearGroup","clearMask","removeCollisionGroup","clearCallback","shapeChanged","impulse","localX","localY","setZeroRotation","setZeroVelocity","setZeroDamping","moveForward","moveBackward","thrust","thrustLeft","thrustRight","moveLeft","moveRight","updateSpriteTransform","resetDamping","resetMass","clearShapes","addCircle","addPlane","addParticle","addLine","addCapsule","setRectangle","addPhaserPolygon","createdFixtures","fixtureData","shapesOfFixture","addFixture","generatedShapes","categoryBits","maskBits","isSensor","polygons","loadPolygon","BodyDebug","settings","defaultSettings","pixelsPerLengthUnit","debugPolygons","ppu","lw","vrot","_j","_ref1","randomPastelHex","drawCapsule","drawPlane","drawLine","drawRectangle","drawConvex","drawPath","lastx","lasty","diagMargin","diagSize","maxLength","xd","yd","mix","rgbToHex","ImageCollection","firstgid","imageWidth","imageHeight","imageMargin","imageSpacing","containsImageIndex","imageIndex","gid","Tile","flipped","scanned","setCollisionCallback","setCollision","resetCollision","isInteresting","faces","TilemapParser","widthInPixels","heightInPixels","tilesets","imagecollections","tiles","collideIndexes","currentLayer","debugMap","_tempA","NORTH","EAST","SOUTH","WEST","setTileSize","createBlankLayer","addTilesetImage","tileset","tileMargin","tileSpacing","getTilesetIndex","setImage","newSet","Tileset","countX","countY","columns","rows","createFromObjects","CustomClass","adjustY","adjustSize","createFromTiles","replacements","customClass","lh","createLayer","getLayerIndex","rootLayer","groupEnd","indexes","getImageIndex","setTileIndexCallback","setTileLocationCallback","recalculate","setCollisionByIndex","calculateFaces","setCollisionBetween","setCollisionByExclusion","layerArg","setPreventRecalculate","preventingRecalculate","needToRecalculate","above","below","getTileAbove","getTileBelow","getTileLeft","setLayer","hasTile","removeTile","removeTileWorldXY","putTile","putTileWorldXY","searchTileIndex","getTile","nonNull","getTileWorldXY","paste","tileblock","tileA","tileB","swapHandler","removeAllLayers","dump","txt","renderSettings","enableScrollDelta","overdrawRatio","copyCanvas","debugSettings","missingImageFill","debuggedTileOverfill","forceFullRedraw","debugAlpha","facingEdgeStroke","collidingTileOverfill","scrollFactorX","scrollFactorY","rayStepRate","_wrap","_mc","renderWidth","renderHeight","_scrollX","_scrollY","tileOffset","ensureSharedCopyCanvas","sharedCopyCanvas","resizeWorld","_fixX","_unfixX","_fixY","_unfixY","getTileX","getTileY","getTileXY","getRayCastTiles","interestingFace","coord","fetchAll","wy","wx","resolveTileset","tileIndex","setIndex","containsTileIndex","resetTilesetCache","setScale","xScale","yScale","shiftCanvas","copyW","copyH","copyContext","renderRegion","lastAlpha","xmax","ymax","baseX","normStartX","renderDeltaScroll","shiftX","shiftY","renderW","renderH","trueTop","trueBottom","trueLeft","trueRight","renderFull","redrawAll","mc","renderDebug","baseY","normStartY","INSERT_NULL","getEmptyData","parseCSV","parseTiledJSON","column","_slice","fields","sliced","parseObjectGroup","objectGroup","objectsCollection","collisionCollection","nameKey","relativePosition","curl","encoding","binaryString","atob","bytes","opacity","offsetx","offsety","flippedVal","curi","tilesetGroupObjects","lastSet","tileproperties","tileProperties","updateTileData","imagewidth","imageheight","newCollection","objectgroup","lastgid","sid","drawCoords","coordIndex","setSpacing","rowCount","colCount","autoScale","scaleData","_s","autoAlpha","alphaData","_a","onEmit","setAlphaData","setScaleData","emitters","ID","minAngle","maxAngle","minSpeed","maxSpeed","minParticleSpeed","maxParticleSpeed","minParticleScale","maxParticleScale","minRotation","maxRotation","minParticleAlpha","maxParticleAlpha","particleClass","particleDrag","particleAnchor","emitX","emitY","particleBringToTop","particleSendToBack","counts","emitted","failed","totalEmitted","totalFailed","_gravity","_minParticleScale","_maxParticleScale","_timer","_counter","_flowQuantity","_flowTotal","_explode","emitParticle","makeParticles","particleArguments","particle","rndKey","rndFrame","explode","flow","forceQuantity","getNextParticle","resetParticle","setXSpeed","setYSpeed","setRotation","setAlpha","rate","tweenData","setAngle","lifespanOutput","bullets","autoExpandBulletsGroup","autofire","shots","fireLimit","fireRate","fireRateVariance","fireFrom","fireAngle","bulletInheritSpriteSpeed","bulletAnimation","bulletFrameRandom","bulletFrameCycle","bulletWorldWrap","bulletWorldWrapPadding","bulletAngleOffset","bulletAngleVariance","bulletSpeed","bulletSpeedVariance","bulletLifespan","bulletKillDistance","bulletGravity","bulletRotateToVelocity","bulletKey","bulletFrame","_bulletClass","Bullet","_bulletCollideWorldBounds","_bulletKillType","KILL_WORLD_BOUNDS","customBody","bulletBounds","bulletFrames","bulletFrameIndex","anims","onFire","onKill","onFireLimit","trackedSprite","trackedPointer","multiFire","_hasFired","trackRotation","trackOffset","_nextFire","_tempNextFire","_rotatedPoint","KILL_NEVER","KILL_LIFESPAN","KILL_DISTANCE","KILL_WEAPON_BOUNDS","KILL_CAMERA_BOUNDS","KILL_STATIC_BOUNDS","resetShots","newLimit","fire","trackSprite","trackPointer","fireMany","fireOffset","moveX","moveY","bullet","bulletManager","killType","bulletKillType","killDistance","rotateToVelocity","bodyDirty","bulletCollideWorldBounds","fireAtPointer","fireAtSprite","fireAtXY","setBulletBodyOffset","setBulletFrames","cycle","addBulletAnimation","debugBodies","onAccess","onError","onTimeout","playWhenUnlocked","timeout","videoStream","isStreaming","retryLimit","retry","retryInterval","_retryID","_pending","_pendingChangeSource","_autoplay","_endCallback","_playCallback","_video","createVideoFromBlob","videoWidth","videoHeight","createVideoFromURL","snapshot","connectToMediaStream","stream","startMediaStream","captureAudio","removeVideoElement","setAttribute","getUserMediaTimeout","getUserMediaSuccess","getUserMediaError","mozSrcObject","createObjectURL","onloadeddata","checkStream","checkVideoProgress","change","playbackRate","setPause","setResume","playHandler","getTracks","track","playing","ended","changeSource","grab","hasChildNodes","firstChild","removeAttribute","canUseNewCanvasBlendModes"],"mappings":";;CAoDC,SAASA,GAAG,GAAG,iBAAiBC,QAAQC,OAAOD,QAAQD,QAAS,CAAmD,IAAIG,EAAE,oBAAoBC,OAAOD,EAAEC,OAAO,oBAAoBC,OAAOF,EAAEE,OAAO,oBAAoBC,OAAOH,EAAEG,MAAMH,EAAEI,GAAGP,KAAzO,CAA+O,WAAqC,OAAO,SAAUA,EAAEQ,EAAEC,EAAEC,GAAG,SAASC,EAAEC,EAAEC,GAAG,IAAIJ,EAAEG,GAAG,CAAC,IAAIJ,EAAEI,GAAG,CAAC,IAAIE,EAAkB,mBAATC,SAAqBA,QAAQ,IAAIF,GAAGC,EAAE,OAAOA,EAAEF,GAAE,GAAI,GAAGI,EAAE,OAAOA,EAAEJ,GAAE,GAAI,MAAM,IAAIK,MAAM,uBAAuBL,EAAE,KAAK,IAAIT,EAAEM,EAAEG,IAAIX,YAAYO,EAAEI,GAAG,GAAGM,KAAKf,EA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EACpB19C,EAASitB,KAAW4wB,EAEpB79C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAItW,GACxB99C,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAGpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIpW,GACxBh+C,EAASitB,KAAWmnC,EAAInW,GAExBj+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAKpBn6C,EAASitB,KAAW0wB,EACpB39C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIlW,GACxBl+C,EAASitB,KAAWmnC,EAAIjW,GAExBn+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,IAGpBp6C,KAAKyzD,kBAEuBzzD,KAAKmM,MAE7BnM,KAAKy+C,UAObjK,EAAKkiB,qBAAqBt2D,UAAUq+C,MAAQ,WAGxC,GAA4B,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AK2G,aAEL3G,KAAK2G,WAAajE,EAAOiE,iBAGL77B,IAApBk1B,KAAKC,aAELD,KAAKC,WAAayC,EAAOzC,iBAGKn1B,IAA9Bk1B,KAAK2K,QAAQC,eAEb5K,KAAK2K,QAAQC,aAAe,IAAI5K,KAAK2K,QAAQ,IAAI3K,KAAKwmB,mBAGnB17C,IAAnCk1B,KAAKgC,cAAc6C,cAEnB7E,KAAKgC,cAAc6C,YAAc,IAAInC,EAAOC,QAGhD3C,KAAKinB,mBAAoB,EAGzBjnB,KAAKwxJ,0BAA4B,WAC7B,OAAO9uJ,EAAOgvC,OAAOnrB,gBASE,oBAAZn/D,SACe,oBAAXC,QAA0BA,OAAOD,UACxCA,QAAUC,OAAOD,QAAUs7C,GAE/Bt7C,QAAQs7C,OAASA,GACQ,oBAAXglB,QAA0BA,OAAOC,IAC/CD,OAAO,SAA+B3vB,EAAK2K,OAASA,GAEpD3K,EAAK2K,OAASA,EAGXA,GACRr6C,KAAKmD","file":"phaser.min.js"} \ No newline at end of file diff --git a/Iteration Sequence 1/js/phaser.min.js b/Iteration Sequence 1/js/phaser.min.js new file mode 100644 index 000000000..6eb048b7a --- /dev/null +++ b/Iteration Sequence 1/js/phaser.min.js @@ -0,0 +1,4 @@ +/* Phaser v2.10.0 - http://phaser.io - @photonstorm - (c) 2016 Photon Storm Ltd. */ + +!function(t){if("object"==typeof exports)module.exports=t();else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.p2=t()}}(function(){return function t(e,i,s){function n(o,a){if(!i[o]){if(!e[o]){var h="function"==typeof require&&require;if(!a&&h)return h(o,!0);if(r)return r(o,!0);throw new Error("Cannot find module '"+o+"'")}var l=i[o]={exports:{}};e[o][0].call(l.exports,function(t){var i=e[o][1][t];return n(i||t)},l,l.exports,t,e,i,s)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;se[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;ia)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var T=0;Tm&&(m+=this.vertices.length),g=Number.MAX_VALUE,m3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e) (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.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.1"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;ca[f]&&(a[f]=u[f]),u[f]i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle");var n=t("../collision/Broadphase");t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;az&&Y0)for(G=0;GMath.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=x,f=b,g=_,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var w=r.vertices[y];if(o.rotate(p,w,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var T=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(T.normalA,f);var P=l(g,T.normalA);o.scale(g,T.normalA,P),a(T.contactPointB,p,n.position),a(T.contactPointA,p,g),a(T.contactPointA,T.contactPointA,t.position),this.contactEquations.push(T),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(T))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=x,p=b;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=x;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,w=u;w=w||0;var T=x,P=b,C=_;a(T,g,y),o.rotate(P,v,w);var S=l(P,T);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,P),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,T,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=x,m=b,y=_,v=w,P=T,E=C,M=S,R=A,L=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(M,u,i),l(g,M)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),I=s.getClosestEdge(c,d,g);if(-1===B||-1===I)return 0;for(var O=0;O<2;O++){var k=B,F=I,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===O){var q;q=k,k=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H=3){if(p)return!0;var Z=this.createContactEquation(j,V,D,U);L++;var J=D.vertices[k%D.vertices.length],Q=D.vertices[(k+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(P,v,y),o.rotate90cw(Z.normalA,P),o.normalize(Z.normalA,Z.normalA),a(M,m,y);var $=l(Z.normalA,M);o.scale(E,Z.normalA,$),a(Z.contactPointA,m,G),a(Z.contactPointA,Z.contactPointA,E),h(Z.contactPointA,Z.contactPointA,G),a(Z.contactPointA,Z.contactPointA,j.position),a(Z.contactPointB,m,N),h(Z.contactPointB,Z.contactPointB,N),a(Z.contactPointB,Z.contactPointB,V.position),this.contactEquations.push(Z),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Z))}}}return this.enableFrictionReduction&&this.enableFriction&&L&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;dh)&&(h=a),(null===c||ah){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,x=nt;if(t instanceof y&&n instanceof y)for(P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(C=0;2!==C;C++){0===C?o.set(m,0,1):1===C&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0),u=(S=T[0]-w[1])<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(var C=0;C!==b.vertices.length;C++){o.rotate(f,b.vertices[C],_),o.rotate(g,b.vertices[(C+1)%b.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0);var S=T[0]-w[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,x=pt,b=ct,_=ut,w=Math.floor((i[0]-d-l[0])/f),T=Math.ceil((i[0]+d-l[0])/f);w<0&&(w=0),T>=p.length&&(T=p.length-1);for(var P=p[w],C=p[T],S=w;SP&&(P=p[S]);if(i[1]-d>P)return!u&&0;for(var A=!1,S=w;S=b[0]&&m[0]<_[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,x,-E),o.add(y,m,g),o.copy(v,x);M=this.createContactEquation(n,t,r,e);o.copy(M.normalA,v),o.scale(M.contactPointB,M.normalA,-d),h(M.contactPointB,M.contactPointB,i),a(M.contactPointB,M.contactPointB,t.position),o.copy(M.contactPointA,y),o.sub(M.contactPointA,M.contactPointA,n.position),this.contactEquations.push(M),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(M))}}if(A=!1,d>0)for(S=w;S<=T;S++)if(o.set(b,S*f,p[S]),o.add(b,b,l),o.sub(g,i,b),o.squaredLength(g)=c.length&&(y=c.length-1);for(var v=c[m],x=c[y],b=m;bv&&(v=c[b]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var _=0,b=m;b=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;ne.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){this.from,this.to;var o=this._currentShape,a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;cthis.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.positioni?(a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n)):-1!==(b=t.indexOf(n))&&t.splice(b,1),this.lowerLimitEnabled&&va?(f.angle=a,-1===n.indexOf(f)&&n.push(f)):-1!==(y=n.indexOf(f))&&n.splice(y,1),this.lowerLimitEnabled&&m>1;if(e<3)return[];for(var i=[],n=[],r=0;r3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,x=1/(f*y-g*g),b=(y*m-g*v)*x,_=(f*v-g*m)*x;return b>=0&&_>=0&&b+_<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;ei&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),x=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||x;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(h=this.shapes.length;h>=0;--h)this.removeShape(this.shapes[h]);var i=new r.Polygon;if(i.vertices=t,i.makeCCW(),"number"==typeof e.removeCollinearPoints&&i.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!i.isSimple())return!1;this.concavePath=i.vertices.slice(0);for(h=0;h=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var T=n.create(),P=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(T,i,t*e),n.multiply(T,this.massMultiplier,T),n.add(r,T,r),this.integrateToTimeOfImpact(t)||(n.scale(P,r,t),n.add(s,s,P),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),M=n.create(),R=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)=l&&h=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var b=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),w=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),T=Math.pow(_,2)-4*b*w;if(!(T<0))if(0===T){if(r.lerp(d,n,o,T),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}else{var P=Math.sqrt(T),C=1/(2*b),S=(-_-P)*C,A=(-_+P)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,x=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;x>=0&&x<=1&&(r.lerp(f,n,h,x),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,x,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;in)&&(n=s),(null===o||sn){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;ee&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),nv){var x=y;y=v,v=x}for(var b=0;b=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,_,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};r.create();var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){(t=t||{}).type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){(t=t||{}).type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=t.lowerBound,a=t.upperBound;n(o,-1e7,-1e7),n(a,1e7,1e7),0===s?a[1]=0:s===Math.PI/2?o[0]=0:s===Math.PI?o[1]=0:s===3*Math.PI/2&&(a[0]=0)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}t("../utils/Utils");var n=t("../events/EventEmitter");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){this.overlappingShapesLastState;var n=this.overlappingShapesCurrentState;if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var s=t,n=e;(i=i||[]).length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;)(n=i.getByKey(i.keys[s]))&&e.push(n.bodyA,n.bodyB);return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s=t&&s=0;T-=2)for(S=b.length-2;S>=0;S-=2)(w[T]===b[S]&&w[T+1]===b[S+1]||w[T+1]===b[S]&&w[T]===b[S+1])&&b.splice(S,2);q=u.length;for(T=0;T!==q;T++){var C=u[T];if(!C.collideConnected)for(var S=b.length-2;S>=0;S-=2)(C.bodyA===b[S]&&C.bodyB===b[S+1]||C.bodyB===b[S]&&C.bodyA===b[S+1])&&b.splice(S,2)}this.postBroadphaseEvent.pairs=b,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var T=0,A=b.length;T!==A;T+=2)for(var E=b[T],M=b[T+1],R=0,L=E.shapes.length;R!==L;R++)for(var B=E.shapes[R],I=B.position,O=B.angle,k=0,F=M.shapes.length;k!==F;k++){var D=M.shapes[k],U=D.position,G=D.angle,N=this.defaultContactMaterial;if(B.material&&D.material){var X=this.getContactMaterial(B.material,D.material);X&&(N=X)}this.runNarrowphase(c,E,B,I,O,M,D,U,G,N,this.frictionGravity)}for(T=0;T!==h;T++)(H=n[T])._wakeUpAfterNarrowphase&&(H.wakeUp(),H._wakeUpAfterNarrowphase=!1);if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(P);for(var W=this.endContactEvent,k=P.length;k--;){var j=P[k];W.shapeA=j.shapeA,W.shapeB=j.shapeB,W.bodyA=j.bodyA,W.bodyB=j.bodyB,this.emit(W)}P.length=0}var V=this.preSolveEvent;V.contactEquations=c.contactEquations,V.frictionEquations=c.frictionEquations,this.emit(V),V.contactEquations=V.frictionEquations=null;var q=u.length;for(T=0;T!==q;T++)u[T].update();if(c.contactEquations.length||c.frictionEquations.length||q)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),T=0;T!==q;T++)v.appendArray(g.equations,u[T].equations);g.split(this);for(T=0;T!==g.islands.length;T++)(K=g.islands[T]).equations.length&&a.solveIsland(t,K)}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),T=0;T!==q;T++)a.addEquations(u[T].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(T=0;T!==h;T++){var H=n[T];H.integrate(t)}for(T=0;T!==h;T++)n[T].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var Y=this.impactEvent,T=0;T!==c.contactEquations.length;T++){var z=c.contactEquations[T];z.firstImpact&&(Y.bodyA=z.bodyA,Y.bodyB=z.bodyB,Y.shapeA=z.shapeA,Y.shapeB=z.shapeB,Y.contactEquation=z,this.emit(Y))}if(this.sleepMode===s.BODY_SLEEPING)for(T=0;T!==h;T++)n[T].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(T=0;T!==h;T++)n[T].sleepTick(this.time,!0,t);for(T=0;T0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,x=t.frictionEquations.length;y=i.type=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0),o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC&&r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0),this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var _=this.beginContactEvent;if(_.shapeA=i,_.shapeB=a,_.bodyA=e,_.bodyB=o,_.contactEquations.length=0,"number"==typeof y)for(P=t.contactEquations.length-y;P1)for(var P=t.frictionEquations.length-b;P=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var x=e[y],b=0,_=x.shapes.length;b!==_;b++){var w=x.shapes[b];r.rotate(p,w.position,x.angle),r.add(p,p,x.position);var T=w.angle+x.angle;(w instanceof o&&g.circleParticle(x,w,p,T,s,n,u,0,!0)||w instanceof a&&g.particleConvex(s,n,u,0,x,w,p,T,!0)||w instanceof h&&g.particlePlane(s,n,u,0,x,w,p,T,!0)||w instanceof l&&g.particleCapsule(s,n,u,0,x,w,p,T,!0)||w instanceof c&&r.squaredLength(r.sub(f,p,t))0?Math.acos(i/u):-Math.acos(i/u),this.worldScale.x=u,this.worldScale.y=c/u}else if(n||r){var d=Math.sqrt(n*n+r*r);this.worldRotation=Phaser.Math.HALF_PI-(r>0?Math.acos(-n/d):-Math.acos(n/d)),this.worldScale.x=c/d,this.worldScale.y=d}else this.worldScale.x=0,this.worldScale.y=0;return this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.x=l.tx,this.worldPosition.y=l.ty,this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,l,h),this},preUpdate:function(){},generateTexture:function(t,e,i){var n=this.getLocalBounds(),r=new Phaser.RenderTexture(this.game,0|n.width,0|n.height,i,e,t);return s.DisplayObject._tempMatrix.tx=-n.x,s.DisplayObject._tempMatrix.ty=-n.y,r.render(this,s.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?s.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):s.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=0;this.texture&&this.texture.baseTexture&&s._enableMultiTextureToggle&&(e=this.texture.baseTexture.textureIndex);var i=new Phaser.RenderTexture(this.game,t.width,t.height,void 0,void 0,void 0,void 0,e);this._cachedSprite=new s.Sprite(i),this._cachedSprite.worldTransform=this.worldTransform}var n=this._filters;this._filters=null,this._cachedSprite.filters=n,s.DisplayObject._tempMatrix.tx=-t.x,s.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,s.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=n,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},s.DisplayObject.prototype.displayObjectUpdateTransform=s.DisplayObject.prototype.updateTransform,Object.defineProperties(s.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],i=0;i=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},s.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},s.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},s.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},s.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},s.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},s.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},s.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(t,i),n=0;na?u:a,d=d>h?d:h);var f=this._bounds;if(!p){var g=(f=new s.Rectangle).x,m=f.width+f.x,y=f.y,v=f.height+f.y,x=this.worldTransform,b=x.a,_=x.b,w=x.c,T=x.d,P=x.tx,C=x.ty,S=b*m+w*v+P,A=T*v+_*m+C,E=b*g+w*v+P,M=T*v+_*g+C,R=b*g+w*y+P,L=T*y+_*g+C,B=b*m+w*y+P,I=T*y+_*m+C;u=S,d=A,c=A,l=B<(l=R<(l=E<(l=S)?E:l)?R:l)?B:l,c=I<(c=L<(c=M(u=R>(u=E>u?E:u)?R:u)?B:u,d=I>(d=L>(d=M>d?M:d)?L:d)?I:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n(f=T>(f=_>(f=x>f?x:f)?_:f)?T:f)?C:f,g=S>(g=P>(g=w>(g=b>g?b:g)?w:g)?P:g)?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},s.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=Phaser.identityMatrix;for(var e=0;e= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}","}"];var n=s.compileProgram(t,this.vertexSrc||s.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(n),this.uSamplerArray=t.getUniformLocation(n,"uSamplerArray[0]"),this.projectionVector=t.getUniformLocation(n,"projectionVector"),this.offsetVector=t.getUniformLocation(n,"offsetVector"),this.dimensions=t.getUniformLocation(n,"dimensions"),this.aVertexPosition=t.getAttribLocation(n,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(n,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(n,"aColor"),this.aTextureIndex=t.getAttribLocation(n,"aTextureIndex");var r=[],o=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var a=0;a 0.0) gl_Position = vec4(0.0);"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);"," vTextureIndex = aTextureIndex;","}"],s.PixiFastShader=function(t){if(this._UID=Phaser._UID++,this.gl=t,this.program=null,s._enableMultiTextureToggle){var t=this.gl;this.MAX_TEXTURES=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(var e="\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n",i=1;i= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["// PixiFastShader Fragment Shader.","precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;","}"];this.vertexSrc=["// PixiFastShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","attribute float aTextureIndex;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;"," vColor = aColor;","}"],this.textureCount=0,this.init()},s.PixiFastShader.prototype.constructor=s.PixiFastShader,s.PixiFastShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["//StripShader Fragment Shader.","precision mediump float;","varying vec2 vTextureCoord;","varying float vTextureIndex;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord);","}"];this.vertexSrc=["//StripShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aTextureIndex;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;","}"],this.init()},s.StripShader.prototype.constructor=s.StripShader,s.StripShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t},i=this.gl,n=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),r=i.getParameter(i.MAX_TEXTURE_SIZE),o=this.game.cache._cache.image,a=null,h=0;h=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var a=i._uvs;if(a){var h,l,c,u,d=t.anchor.x,p=t.anchor.y;if(i.trim){var f=i.trim;h=(l=f.x-d*f.width)+i.crop.width,c=(u=f.y-p*f.height)+i.crop.height}else h=i.frame.width*(1-d),l=i.frame.width*-d,c=i.frame.height*(1-p),u=i.frame.height*-p;var g=this.currentBatchSize*this.vertexSize,m=(this.currentBatchSize,i.baseTexture.resolution),y=i.baseTexture.textureIndex,v=o.a/m,x=o.b/m,b=o.c/m,_=o.d/m,w=o.tx,T=o.ty,P=(i.crop.width,i.crop.height);if(i.rotated){var C=o.a,S=o.b,A=o.c,E=o.d,M=l,R=h;w=o.c*P+w,T=o.d*P+T,v=6.123233995736766e-17*C-A,x=6.123233995736766e-17*S-E,b=C+6.123233995736766e-17*A,_=S+6.123233995736766e-17*E,i._updateUvsInverted(),h=c,l=u,c=R,u=M}var L=this.colors,B=this.positions,I=t.tint,O=(I>>16)+(65280&I)+((255&I)<<16)+(255*t.worldAlpha<<24);this.renderSession.roundPixels?(B[g++]=v*l+b*u+w|0,B[g++]=_*u+x*l+T|0,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w|0,B[g++]=_*u+x*h+T|0,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w|0,B[g++]=_*c+x*h+T|0,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w|0,B[g++]=_*c+x*l+T|0,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y):(B[g++]=v*l+b*u+w,B[g++]=_*u+x*l+T,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w,B[g++]=_*u+x*h+T,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w,B[g++]=_*c+x*h+T,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w,B[g++]=_*c+x*l+T,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y),this.sprites[this.currentBatchSize++]=t}},s.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture,i=e.baseTexture,n=this.gl,r=t.texture.baseTexture.textureIndex;s.WebGLRenderer.textureArray[r]!=i&&(this.flush(),n.activeTexture(n.TEXTURE0+r),n.bindTexture(n.TEXTURE_2D,i._glTextures[n.id]),s.WebGLRenderer.textureArray[r]=i),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new s.TextureUvs);var o=t._uvs,a=e.baseTexture.width,h=e.baseTexture.height;t.tilePosition.x%=a*t.tileScaleOffset.x,t.tilePosition.y%=h*t.tileScaleOffset.y;var l=t.tilePosition.x/(a*t.tileScaleOffset.x),c=t.tilePosition.y/(h*t.tileScaleOffset.y),u=t.width/a/(t.tileScale.x*t.tileScaleOffset.x),d=t.height/h/(t.tileScale.y*t.tileScaleOffset.y);o.x0=0-l,o.y0=0-c,o.x1=1*u-l,o.y1=0-c,o.x2=1*u-l,o.y2=1*d-c,o.x3=0-l,o.y3=1*d-c;var p=t.tint,f=(p>>16)+(65280&p)+((255&p)<<16)+(255*t.worldAlpha<<24),g=this.positions,m=this.colors,y=t.width,v=t.height,x=t.anchor.x,b=t.anchor.y,_=y*(1-x),w=y*-x,T=v*(1-b),P=v*-b,C=this.currentBatchSize*this.vertexSize,S=e.baseTexture.resolution,A=t.worldTransform,E=A.a/S,M=A.b/S,R=A.c/S,L=A.d/S,B=A.tx,I=A.ty;g[C++]=E*w+R*P+B,g[C++]=L*P+M*w+I,g[C++]=o.x0,g[C++]=o.y0,m[C++]=f,g[C++]=r,g[C++]=E*_+R*P+B,g[C++]=L*P+M*_+I,g[C++]=o.x1,g[C++]=o.y1,m[C++]=f,g[C++]=r,g[C++]=E*_+R*T+B,g[C++]=L*T+M*_+I,g[C++]=o.x2,g[C++]=o.y2,m[C++]=f,g[C++]=r,g[C++]=E*w+R*T+B,g[C++]=L*T+M*w+I,g[C++]=o.x3,g[C++]=o.y3,m[C++]=f,g[C++]=r,this.sprites[this.currentBatchSize++]=t},s.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,t=this.defaultShader.shaders[e.id],e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var i=this.vertexSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,i,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,i,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,i,16),e.vertexAttribPointer(t.aTextureIndex,1,e.FLOAT,!1,i,20)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);var n=this.positions.subarray(0,this.currentBatchSize*this.vertexSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m0&&(v=!1),(f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){(t=(p=a).shaders[e.id])||((t=new s.PixiShader(e)).fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var x=this.renderSession.projection;e.uniform2f(t.projectionVector,x.x,x.y);var b=this.renderSession.offset;e.uniform2f(t.offsetVector,b.x,b.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},s.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},s.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},s.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},s.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},s.WebGLFastSpriteBatch=function(t){this.vertSize=11,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,i=6*this.maxSize;this.vertices=new Float32Array(e),this.indices=new Uint16Array(i),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var s=0,n=0;s=this.size&&this.flush()}},s.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]){if(this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}else this.renderSession.renderer.updateTexture(this.currentBaseTexture,t)}},s.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},s.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36),t.vertexAttribPointer(this.shader.aTextureIndex,1,t.FLOAT,!1,i,40)},s.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},s.WebGLFilterManager.prototype.constructor=s.WebGLFilterManager,s.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},s.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},s.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,i=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new s.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),i.x=a.width/2,i.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},s.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),i=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,i.width*this.renderSession.resolution,i.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=i.height,this.vertexArray[2]=i.width,this.vertexArray[3]=i.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=i.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=i.width/this.width,this.uvArray[5]=i.height/this.height,this.uvArray[6]=i.width/this.width,this.uvArray[7]=i.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,i,p,f),this.texturePool.push(n),e._glFilterTexture=null},s.WebGLFilterManager.prototype.applyFilterPass=function(t,e,i,n){var r=this.gl,o=t.shaders[r.id];o||((o=new s.PixiShader(r)).fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(!0),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,i/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},s.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},s.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e=0;t--){var e=this._glTextures[t],i=s.glContexts[t];i&&e&&i.deleteTexture(e)}this._glTextures.length=0,this.dirty()},s.BaseTexture.fromCanvas=function(t,e,i){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),i=i||1,new s.BaseTexture(t,e,i)},s.TextureSilentFail=!1,s.Texture=function(t,e,i,n){this.noFrame=!1,e||(this.noFrame=!0,e=new s.Rectangle(0,0,1,1)),t instanceof s.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=i||new s.Rectangle(0,0,1,1),this.rotated=!1,t.hasLoaded&&(this.noFrame&&(e=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},s.Texture.prototype.constructor=s.Texture,s.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},s.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},s.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,this.trim||!(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height))this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs();else{if(!s.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=!1}},s.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/i},s.Texture.prototype._updateUvsInverted=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.height)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.height)/e,this._uvs.y2=(t.y+t.width)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.width)/i},s.Texture.fromCanvas=function(t,e){var i=s.BaseTexture.fromCanvas(t,e);return new s.Texture(i)},s.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=s),exports.PIXI=s):"undefined"!=typeof define&&define.amd?define("PIXI",i.PIXI=s):i.PIXI=s,s}.call(this),function(){function t(t,e){this._scaleFactor=t,this._deltaMode=e,this.originalEvent=null}var e=this,i=i||{VERSION:"2.10.0",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,WEBGL_MULTI:4,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,PENDING_ATLAS:-1,HORIZONTAL:0,VERTICAL:1,LANDSCAPE:0,PORTRAIT:1,ANGLE_UP:270,ANGLE_DOWN:90,ANGLE_LEFT:180,ANGLE_RIGHT:0,ANGLE_NORTH_EAST:315,ANGLE_NORTH_WEST:225,ANGLE_SOUTH_EAST:45,ANGLE_SOUTH_WEST:135,TOP_LEFT:0,TOP_CENTER:1,TOP_RIGHT:2,LEFT_TOP:3,LEFT_CENTER:4,LEFT_BOTTOM:5,CENTER:6,RIGHT_TOP:7,RIGHT_CENTER:8,RIGHT_BOTTOM:9,BOTTOM_LEFT:10,BOTTOM_CENTER:11,BOTTOM_RIGHT:12,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},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{},_UID:0};if(Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Function.prototype.bind||(Function.prototype.bind=function(){var t=Array.prototype.slice;return function(e){function i(){var r=n.concat(t.call(arguments));s.apply(this instanceof i?this:e,r)}var s=this,n=t.call(arguments,1);if("function"!=typeof s)throw new TypeError;return i.prototype=function t(e){if(e&&(t.prototype=e),!(this instanceof t))return new t}(s.prototype),i}}()),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var s=arguments.length>=2?arguments[1]:void 0,n=0;n0&&100*Math.random()<=t},randomChoice:function(t,e){return Math.random()<.5?t:e},parseDimension:function(t,e){var i=0,s=0;return"string"==typeof t?"%"===t.substr(-1)?(i=parseInt(t,10)/100,s=0===e?window.innerWidth*i:window.innerHeight*i):s=parseInt(t,10):s=t,s},pad:function(t,e,i,s){if(void 0===e)var e=0;if(void 0===i)var i=" ";if(void 0===s)var s=3;var n=0;if(e+1>=(t=t.toString()).length)switch(s){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((n=e-t.length)/2),o=n-r;t=new Array(o+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t},isPlainObject:function(t){if("object"!=typeof t||t.nodeType||t===t.window)return!1;try{if(t.constructor&&!{}.hasOwnProperty.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},extend:function(){var t,e,s,n,r,o,a=arguments[0]||{},h=1,l=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[1]||{},h=2),l===h&&(a=this,--h);h0&&(this._radius=.5*s),this.type=i.CIRCLE},i.Circle.prototype={circumference:function(){return Math.PI*this._radius*2},random:function(t){void 0===t&&(t=new i.Point);var e=2*Math.PI*Math.random(),s=Math.random()+Math.random(),n=s>1?2-s:s,r=n*Math.cos(e),o=n*Math.sin(e);return t.x=this.x+r*this.radius,t.y=this.y+o*this.radius,t},getBounds:function(){return new i.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(t,e,i){return this.x=t,this.y=e,this._diameter=i,this._radius=.5*i,this},copyFrom:function(t){return this.setTo(t.x,t.y,t.diameter)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.diameter=this._diameter,t},distance:function(t,e){var s=i.Math.distance(this.x,this.y,t.x,t.y);return e?Math.round(s):s},clone:function(t){return void 0===t||null===t?t=new i.Circle(this.x,this.y,this.diameter):t.setTo(this.x,this.y,this.diameter),t},contains:function(t,e){return i.Circle.contains(this,t,e)},circumferencePoint:function(t,e,s){return i.Circle.circumferencePoint(this,t,e,s)},sample:function(t,e,s,n,r){t||(t=60),null==e&&(e=0),null==s&&(s=i.Math.PI2),r||(r=[]);for(var o=0;o0&&(this._diameter=t,this._radius=.5*t)}}),Object.defineProperty(i.Circle.prototype,"radius",{get:function(){return this._radius},set:function(t){t>0&&(this._radius=t,this._diameter=2*t)}}),Object.defineProperty(i.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(t){t>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-t}}),Object.defineProperty(i.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(t){tthis.y?(this._radius=0,this._diameter=0):this.radius=this.y-t}}),Object.defineProperty(i.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(t){t0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(i.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(t){!0===t&&this.setTo(0,0,0)}}),i.Circle.contains=function(t,e,i){return t.radius>0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius},i.Circle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.diameter===e.diameter},i.Circle.intersects=function(t,e){return i.Math.distance(t.x,t.y,e.x,e.y)<=t.radius+e.radius},i.Circle.circumferencePoint=function(t,e,s,n){return void 0===s&&(s=!1),void 0===n&&(n=new i.Point),!0===s&&(e=i.Math.degToRad(e)),n.x=t.x+t.radius*Math.cos(e),n.y=t.y+t.radius*Math.sin(e),n},i.Circle.intersectsRectangle=function(t,e){var i=Math.abs(t.x-e.x-e.halfWidth);if(i>e.halfWidth+t.radius)return!1;var s=Math.abs(t.y-e.y-e.halfHeight);if(s>e.halfHeight+t.radius)return!1;if(i<=e.halfWidth||s<=e.halfHeight)return!0;var n=i-e.halfWidth,r=s-e.halfHeight;return n*n+r*r<=t.radius*t.radius},i.Circle.intersectsLine=function(t,e,s){var n=t.x,r=t.y,o=(e.end.y-e.start.y)/(e.end.x-e.start.x),a=e.end.y-o*e.end.x,h=t.radius,l=t.radius,c=a+o*n,u=(n*(l*l)-o*(h*h)*(a-r)+h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),d=(n*(l*l)-o*(h*h)*(a-r)-h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),p=o*u+a,f=o*d+a,g=new i.Point(u,p),m=new i.Point(d,f),y=e.pointOnSegment(g.x,g.y,.01),v=e.pointOnSegment(m.x,m.y,.01);return y&&v?!s||[g,m]:y?!s||[g]:v?!s||[m]:!!s&&[]},PIXI.Circle=i.Circle,i.Ellipse=function(t,e,s,n){t=t||0,e=e||0,s=s||0,n=n||0,this.x=t,this.y=e,this.width=s,this.height=n,this.type=i.ELLIPSE},i.Ellipse.prototype={setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},getBounds:function(){return new i.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},clone:function(t){return void 0===t||null===t?t=new i.Ellipse(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t},contains:function(t,e){return i.Ellipse.contains(this,t,e)},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random()*Math.PI*2,s=Math.random();return t.x=Math.sqrt(s)*Math.cos(e),t.y=Math.sqrt(s)*Math.sin(e),t.x=this.x+t.x*this.width/2,t.y=this.y+t.y*this.height/2,t},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},i.Ellipse.prototype.constructor=i.Ellipse,Object.defineProperty(i.Ellipse.prototype,"left",{get:function(){return this.x},set:function(t){this.x=t}}),Object.defineProperty(i.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t=s&&t<=n&&e>=r&&e<=o},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random();return t.x=this.start.x+e*(this.end.x-this.start.x),t.y=this.start.y+e*(this.end.y-this.start.y),t},coordinatesOnLine:function(t,e){void 0===t&&(t=1),void 0===e&&(e=[]);var i=Math.round(this.start.x),s=Math.round(this.start.y),n=Math.round(this.end.x),r=Math.round(this.end.y),o=Math.abs(n-i),a=Math.abs(r-s),h=i-a&&(c-=a,i+=h),d=0&&g<=1&&m>=0&&m<=1?o:null}return o},i.Line.intersects=function(t,e,s,n){return i.Line.intersectsPoints(t.start,t.end,e.start,e.end,s,n)},i.Line.intersectsRectangle=function(t,e){if(0===t.length||e.empty)return!1;var i=t.start.x,s=t.start.y,n=t.end.x,r=t.end.y,o=e.x,a=e.y,h=e.right,l=e.bottom,c=0;if(i>=o&&i<=h&&s>=a&&s<=l||n>=o&&n<=h&&r>=a&&r<=l)return!0;if(i=o){if((c=s+(r-s)*(o-i)/(n-i))>a&&c<=l)return!0}else if(i>h&&n<=h&&(c=s+(r-s)*(h-i)/(n-i))>=a&&c<=l)return!0;if(s=a){if((c=i+(n-i)*(a-s)/(r-s))>=o&&c<=h)return!0}else if(s>l&&r<=l&&(c=i+(n-i)*(l-s)/(r-s))>=o&&c<=h)return!0;return!1},i.Line.intersectionWithRectangle=function(t,e,s){var n=i.Line.intersectionWithRectangle;s||(s=new i.Point),n.edges||(n.edges=[new i.Line,new i.Line,new i.Line,new i.Line]),n.edgeIntersection||(n.edgeIntersection=new i.Point);var r=n.edges,o=n.edgeIntersection.set(0),a=e.x,h=e.y,l=e.right,c=e.bottom,u=1/0;r[0].setTo(a,h,l,h),r[1].setTo(a,c,l,c),r[2].setTo(a,h,a,c),r[3].setTo(l,h,l,c);for(var d,p=0;d=r[p];p++)if(t.intersects(d,!0,o)){var f=t.start.distance(o);fs&&(this.x=s),this.yn&&(this.y=n),this},clone:function(t){return void 0===t||null===t?t=new i.Point(this.x,this.y):t.setTo(this.x,this.y),t},copyTo:function(t){return t.x=this.x,t.y=this.y,t},distance:function(t,e){return i.Point.distance(this,t,e)},equals:function(t){return t.x===this.x&&t.y===this.y},equalsXY:function(t,e){return this.x===t&&this.y===e},fuzzyEquals:function(t,e){return i.Point.fuzzyEquals(this,t,e)},fuzzyEqualsXY:function(t,e,s){return i.Point.fuzzyEqualsXY(this,t,e,s)},angle:function(t,e){return this.angleXY(t.x,t.y,e)},angleXY:function(t,e,s){var n=Math.atan2(e-this.y,t-this.x);return s?i.Math.radToDeg(n):n},atan:function(t){var e=Math.atan2(this.y,this.x);return t?i.Math.radToDeg(e):e},rotate:function(t,e,s,n,r){return i.Point.rotate(this,t,e,s,n,r)},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(t){return this.normalize().multiply(t,t)},normalize:function(){if(!this.isZero()){var t=this.getMagnitude();this.x/=t,this.y/=t}return this},limit:function(t){return this.getMagnitudeSq()>t*t&&this.setMagnitude(t),this},expand:function(t){return this.getMagnitudeSq()=0&&e.x-i<0)return-1;if(t.x-i<0&&e.x-i>=0)return 1;if(t.x-i==0&&e.x-i==0)return t.y-s>=0||e.y-s>=0?t.y>e.y?1:-1:e.y>t.y?1:-1;var n=(t.x-i)*-(e.y-s)-(e.x-i)*-(t.y-s);return n<0?-1:n>0?1:(t.x-i)*(t.x-i)+(t.y-s)*(t.y-s)>(e.x-i)*(e.x-i)+(e.y-s)*(e.y-s)?-1:1})},PIXI.Point=i.Point,i.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.flattened=!1,this.type=i.POLYGON},i.Polygon.prototype={toNumberArray:function(t){void 0===t&&(t=[]);for(var e=0;e0){Array.isArray(t)||(t=Array.prototype.slice.call(arguments));for(var e=Number.MAX_VALUE,i=0,s=t.length;i=this.right?this.width=0:this.width=this.right-t,this.x=t}}),Object.defineProperty(i.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(i.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(i.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(i.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(t){this.x=t-this.halfWidth}}),Object.defineProperty(i.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(t){this.y=t-this.halfHeight}}),Object.defineProperty(i.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(i.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(i.Rectangle.prototype,"top",{get:function(){return this.y},set:function(t){t>=this.bottom?(this.height=0,this.y=t):this.height=this.bottom-t}}),Object.defineProperty(i.Rectangle.prototype,"topLeft",{get:function(){return new i.Point(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"topRight",{get:function(){return new i.Point(this.x+this.width,this.y)},set:function(t){this.right=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),i.Rectangle.prototype.constructor=i.Rectangle,i.Rectangle.inflate=function(t,e,i){return t.x-=e,t.width+=2*e,t.y-=i,t.height+=2*i,t},i.Rectangle.inflatePoint=function(t,e){return i.Rectangle.inflate(t,e.x,e.y)},i.Rectangle.size=function(t,e){return void 0===e||null===e?e=new i.Point(t.width,t.height):e.setTo(t.width,t.height),e},i.Rectangle.clone=function(t,e){return void 0===e||null===e?e=new i.Rectangle(t.x,t.y,t.width,t.height):e.setTo(t.x,t.y,t.width,t.height),e},i.Rectangle.createFromBounds=function(t,e){return void 0!==e&&null!==e||(e=new i.Rectangle(t.x,t.y,t.width,t.height)),e.copyFromBounds(t)},i.Rectangle.contains=function(t,e,i){return!(t.width<=0||t.height<=0)&&(e>=t.x&&e=t.y&&i=t&&n=e&&re.volume)&&(t.x>=e.x&&t.y>=e.y&&t.righte.right||t.y>e.bottom)},i.Rectangle.intersectsRaw=function(t,e,i,s,n,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||ns&&(s=t.x),t.xr&&(r=t.y),t.y=i&&t<=i+this.width){var s=this.y;if(e>=s&&e<=s+this.height)return!0}return!1}},i.RoundedRectangle.prototype.constructor=i.RoundedRectangle,PIXI.RoundedRectangle=i.RoundedRectangle,i.Camera=function(t,e,s,n,r,o){this.game=t,this.world=t.world,this.id=0,this.view=new i.Rectangle(s,n,r,o),this.bounds=new i.Rectangle(s,n,r,o),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this.lerp=new i.Point(1,1),this.onShakeComplete=new i.Signal,this.onFlashComplete=new i.Signal,this.onFadeComplete=new i.Signal,this.fx=null,this._targetPosition=new i.Point,this._edge=0,this._position=new i.Point,this._shake={intensity:0,duration:0,horizontal:!1,vertical:!1,shakeBounds:!0,x:0,y:0},this._fxDuration=0,this._fxType=0,this._fixedView=new i.Rectangle},i.Camera.FOLLOW_LOCKON=0,i.Camera.FOLLOW_PLATFORMER=1,i.Camera.FOLLOW_TOPDOWN=2,i.Camera.FOLLOW_TOPDOWN_TIGHT=3,i.Camera.SHAKE_BOTH=4,i.Camera.SHAKE_HORIZONTAL=5,i.Camera.SHAKE_VERTICAL=6,i.Camera.ENABLE_FX=!0,i.Camera.prototype={boot:function(){this.displayObject=this.game.world,this.scale=this.game.world.scale,this.game.camera=this,i.Graphics&&i.Camera.ENABLE_FX&&(this.fx=new i.Graphics(this.game),this.game.stage.addChild(this.fx))},preUpdate:function(){this.totalInView=0},follow:function(t,e,s,n){void 0===e&&(e=i.Camera.FOLLOW_LOCKON),void 0===s&&(s=1),void 0===n&&(n=1),this.target=t,this.lerp.set(s,n);var r;switch(e){case i.Camera.FOLLOW_PLATFORMER:var o=this.width/8,a=this.height/3;this.deadzone=new i.Rectangle((this.width-o)/2,(this.height-a)/2-.25*a,o,a);break;case i.Camera.FOLLOW_TOPDOWN:r=Math.max(this.width,this.height)/4,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_TOPDOWN_TIGHT:r=Math.max(this.width,this.height)/8,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_LOCKON:default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(t){this.setPosition(Math.round(t.x-this.view.halfWidth),Math.round(t.y-this.view.halfHeight))},focusOnXY:function(t,e){this.setPosition(Math.round(t-this.view.halfWidth),Math.round(e-this.view.halfHeight))},shake:function(t,e,s,n,r){return void 0===t&&(t=.05),void 0===e&&(e=500),void 0===s&&(s=!0),void 0===n&&(n=i.Camera.SHAKE_BOTH),void 0===r&&(r=!0),!(!s&&this._shake.duration>0)&&(this._shake.intensity=t,this._shake.duration=e,this._shake.shakeBounds=r,this._shake.x=0,this._shake.y=0,this._shake.horizontal=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_HORIZONTAL,this._shake.vertical=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_VERTICAL,!0)},flash:function(t,e,i,s){return void 0===t&&(t=16777215),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=1,this._fxDuration=e,this._fxType=0,!0)},fade:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=0,this._fxDuration=e,this._fxType=1,!0)},update:function(){this._fxDuration>0&&this.updateFX(),this._shake.duration>0&&this.updateShake(),this.bounds&&this.checkBounds(),this.roundPx&&(this.view.floor(),this._shake.x=Math.floor(this._shake.x),this._shake.y=Math.floor(this._shake.y)),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateFX:function(){0===this._fxType?(this.fx.alpha-=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha<=0&&(this._fxDuration=0,this.fx.alpha=0,this.onFlashComplete.dispatch())):(this.fx.alpha+=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha>=1&&(this._fxDuration=0,this.fx.alpha=1,this.onFadeComplete.dispatch()))},updateShake:function(){this._shake.duration-=this.game.time.elapsedMS,this._shake.duration<=0?(this.onShakeComplete.dispatch(),this._shake.x=0,this._shake.y=0):(this._shake.horizontal&&(this._shake.x=this.game.rnd.frac()*this._shake.intensity*this.view.width*2-this._shake.intensity*this.view.width),this._shake.vertical&&(this._shake.y=this.game.rnd.frac()*this._shake.intensity*this.view.height*2-this._shake.intensity*this.view.height))},updateTarget:function(){this._targetPosition.x=this.view.x+this.target.worldPosition.x,this._targetPosition.y=this.view.y+this.target.worldPosition.y,this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edgethis.deadzone.right&&(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.right,this.lerp.x)),this._edge=this._targetPosition.y-this.view.y,this._edgethis.deadzone.bottom&&(this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.bottom,this.lerp.y))):(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.view.halfWidth,this.lerp.x),this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.view.halfHeight,this.lerp.y)),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},setBoundsToWorld:function(){this.bounds&&this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1;var t=this.view.x+this._shake.x,e=this.view.right+this._shake.x,i=this.view.y+this._shake.y,s=this.view.bottom+this._shake.y;t<=this.bounds.x*this.scale.x?(this.atLimit.x=!0,this.view.x=this.bounds.x*this.scale.x,this._shake.shakeBounds||(this._shake.x=0)):e>=this.bounds.right*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.right*this.scale.x-this.width,this._shake.shakeBounds||(this._shake.x=0)),i<=this.bounds.top*this.scale.y?(this.atLimit.y=!0,this.view.y=this.bounds.top*this.scale.y,this._shake.shakeBounds||(this._shake.y=0)):s>=this.bounds.bottom*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom*this.scale.y-this.height,this._shake.shakeBounds||(this._shake.y=0))},setPosition:function(t,e){this.view.x=t,this.view.y=e,this.bounds&&this.checkBounds()},setSize:function(t,e){this.view.width=t,this.view.height=e},reset:function(){this.target=null,this.view.x=0,this.view.y=0,this._shake.duration=0,this._shake.x=0,this._shake.y=0,this.resetFX()},resetFX:function(){this.fx&&(this.fx.clear(),this.fx.alpha=0),this._fxDuration=0}},i.Camera.prototype.constructor=i.Camera,Object.defineProperty(i.Camera.prototype,"x",{get:function(){return this.view.x},set:function(t){this.view.x=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"y",{get:function(){return this.view.y},set:function(t){this.view.y=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"position",{get:function(){return this._position.set(this.view.x,this.view.y),this._position},set:function(t){void 0!==t.x&&(this.view.x=t.x),void 0!==t.y&&(this.view.y=t.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"width",{get:function(){return this.view.width},set:function(t){this.view.width=t}}),Object.defineProperty(i.Camera.prototype,"height",{get:function(){return this.view.height},set:function(t){this.view.height=t}}),Object.defineProperty(i.Camera.prototype,"shakeIntensity",{get:function(){return this._shake.intensity},set:function(t){this._shake.intensity=t}}),Object.defineProperty(i.Camera.prototype,"fixedView",{get:function(){return this._fixedView.setTo(0,0,this.view.width,this.view.height),this._fixedView}}),i.State=function(){this.game=null,this.key="",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.state=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},i.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},i.State.prototype.constructor=i.State,i.StateManager=function(t,e){this.game=t,this.states={},this._pendingState=null,void 0!==e&&null!==e&&(this._pendingState=e),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new i.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},i.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(t,e,s){void 0===s&&(s=!1);var n;return e instanceof i.State?n=e:"object"==typeof e?(n=e).game=this.game:"function"==typeof e&&(n=new e(this.game)),this.states[t]=n,s&&(this.game.isBooted?this.start(t):this._pendingState=t),n},remove:function(t){this.current===t&&(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.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[t]},start:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1),this.checkState(t)&&(this._pendingState=t,this._clearWorld=e,this._clearCache=i,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!1),this._pendingState=this.current,this._clearWorld=t,this._clearCache=e,arguments.length>2&&(this._args=Array.prototype.slice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var t=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,t),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache&&this.game.cache.destroy()))},checkState:function(t){var e=this.states[t];return e?!!(e.preload||e.create||e.update||e.render)||(console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"),!1):(console.warn("Phaser.StateManager - No state found with the key: "+t),!1)},link:function(t){var e=this.states[t];e.game=this.game,e.add=this.game.add,e.make=this.game.make,e.camera=this.game.camera,e.cache=this.game.cache,e.input=this.game.input,e.load=this.game.load,e.math=this.game.math,e.sound=this.game.sound,e.scale=this.game.scale,e.state=this,e.stage=this.game.stage,e.time=this.game.time,e.tweens=this.game.tweens,e.world=this.game.world,e.particles=this.game.particles,e.rnd=this.game.rnd,e.physics=this.game.physics,e.key=t},unlink:function(t){var e=this.states[t];e&&(e.game=null,e.add=null,e.make=null,e.camera=null,e.cache=null,e.input=null,e.load=null,e.math=null,e.sound=null,e.scale=null,e.state=null,e.stage=null,e.time=null,e.tweens=null,e.world=null,e.particles=null,e.rnd=null,e.physics=null)},setCurrentState:function(t){var e=this.states[t];this.callbackContext=e,this.link(t),this.onInitCallback=e.init||this.dummy,this.onPreloadCallback=e.preload||null,this.onLoadRenderCallback=e.loadRender||null,this.onLoadUpdateCallback=e.loadUpdate||null,this.onCreateCallback=e.create||null,this.onUpdateCallback=e.update||null,this.onPreRenderCallback=e.preRender||null,this.onRenderCallback=e.render||null,this.onResizeCallback=e.resize||null,this.onPausedCallback=e.paused||null,this.onResumedCallback=e.resumed||null,this.onPauseUpdateCallback=e.pauseUpdate||null,this.onShutDownCallback=e.shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=t,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),t===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){!1===this._created&&this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game),!1===this._created&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(t){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,t)},resize:function(t,e){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,t,e)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===i.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this._clearWorld=!0,this._clearCache=!0,this.clearCurrentState(),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,this.current=""}},i.StateManager.prototype.constructor=i.StateManager,Object.defineProperty(i.StateManager.prototype,"created",{get:function(){return this._created}}),i.Signal=function(){},i.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!1,validateListener:function(t,e){if("function"!=typeof t)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",e))},_registerListener:function(t,e,s,n,r){var o,a=this._indexOfListener(t,s);if(-1!==a){if((o=this._bindings[a]).isOnce()!==e)throw new Error("You cannot add"+(e?"":"Once")+"() then add"+(e?"Once":"")+"() the same listener without removing the relationship first.")}else o=new i.SignalBinding(this,t,e,s,n,r),this._addBinding(o);return this.memorize&&this._prevParams&&o.execute(this._prevParams),o},_addBinding:function(t){this._bindings||(this._bindings=[]);var e=this._bindings.length;do{e--}while(this._bindings[e]&&t._priority<=this._bindings[e]._priority);this._bindings.splice(e+1,0,t)},_indexOfListener:function(t,e){if(!this._bindings)return-1;void 0===e&&(e=null);for(var i,s=this._bindings.length;s--;)if((i=this._bindings[s])._listener===t&&i.context===e)return s;return-1},has:function(t,e){return-1!==this._indexOfListener(t,e)},add:function(t,e,i){this.validateListener(t,"add");var s=[];if(arguments.length>3)for(var n=3;n3)for(var n=3;n=this.children.length?-1:this.getChildAt(t)},i.Group.prototype.create=function(t,e,i,s,n,r){void 0===n&&(n=!0);var o=new this.classType(this.game,t,e,i,s);return o.exists=n,o.visible=n,o.alive=n,this.add(o,!1,r)},i.Group.prototype.createMultiple=function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=!1),Array.isArray(e)||(e=[e]),Array.isArray(i)||(i=[i]);var o=this,a=[];return e.forEach(function(e){i.forEach(function(i){for(var h=0;hthis.children.length||-1===t&&-1===e)return!1;for(var a=new i.Rectangle(0,0,s,n),h=t*s,l=e*n,c=o;cthis.children.length-1&&(t=0),this.cursor)return this.cursorIndex=t,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.next=function(){if(this.cursor)return this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.previous=function(){if(this.cursor)return 0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.swap=function(t,e){this.swapChildren(t,e),this.updateZ()},i.Group.prototype.bringToTop=function(t){return t.parent===this&&this.getIndex(t)0&&(this.remove(t,!1,!0),this.addAt(t,0,!0)),t},i.Group.prototype.moveUp=function(t){if(t.parent===this&&this.getIndex(t)0){var e=this.getIndex(t),i=this.getAt(e-1);i&&this.swap(t,i)}return t},i.Group.prototype.xy=function(t,e,i){if(t<0||t>this.children.length)return-1;this.getChildAt(t).x=e,this.getChildAt(t).y=i},i.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},i.Group.prototype.getIndex=function(t){return this.children.indexOf(t)},i.Group.prototype.getByName=function(t){for(var e=0;e0))return!1;var r=e.length;return 1===r?0===s?t[e[0]]=i:1===s?t[e[0]]+=i:2===s?t[e[0]]-=i:3===s?t[e[0]]*=i:4===s&&(t[e[0]]/=i):2===r?0===s?t[e[0]][e[1]]=i:1===s?t[e[0]][e[1]]+=i:2===s?t[e[0]][e[1]]-=i:3===s?t[e[0]][e[1]]*=i:4===s&&(t[e[0]][e[1]]/=i):3===r?0===s?t[e[0]][e[1]][e[2]]=i:1===s?t[e[0]][e[1]][e[2]]+=i:2===s?t[e[0]][e[1]][e[2]]-=i:3===s?t[e[0]][e[1]][e[2]]*=i:4===s&&(t[e[0]][e[1]][e[2]]/=i):4===r&&(0===s?t[e[0]][e[1]][e[2]][e[3]]=i:1===s?t[e[0]][e[1]][e[2]][e[3]]+=i:2===s?t[e[0]][e[1]][e[2]][e[3]]-=i:3===s?t[e[0]][e[1]][e[2]][e[3]]*=i:4===s&&(t[e[0]][e[1]][e[2]][e[3]]/=i)),!0},i.Group.prototype.checkProperty=function(t,e,s,n){if(void 0===n&&(n=!1),this!==t.parent)return!1;var r=i.Utils.getProperty(t,e);return!(void 0===r&&n||r!==s)},i.Group.prototype.set=function(t,e,i,s,n,r,o){if(void 0===o&&(o=!1),e=e.split("."),void 0===s&&(s=!1),void 0===n&&(n=!1),(!1===s||s&&t.alive)&&(!1===n||n&&t.visible))return this.setProperty(t,e,i,r,o)},i.Group.prototype.setAll=function(t,e,i,s,n,r){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===r&&(r=!1),t=t.split("."),n=n||0;for(var o=0;o2){i=[];for(s=2;s2){n=[];for(a=2;a=e&&(t=e-1);var i=this.children[t];this.updateOnlyExistingChildren&&!i.exists||i.update()}},i.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y);for(var t=0;t2){s=[null];for(var n=2;n2){s=[null];for(var n=2;n2){s=[null];for(var n=2;ne[this._sortProperty]?1:t.ze[this._sortProperty]?-1:0},i.Group.prototype.iterate=function(t,e,s,n,r,o){if(0===this.children.length){if(s===i.Group.RETURN_TOTAL)return 0;if(s===i.Group.RETURN_ALL)return[]}var a=0;if(s===i.Group.RETURN_ALL)var h=[];for(var l=0;l0)return this.children[this.children.length-1]},i.Group.prototype.getBottom=function(){if(this.children.length>0)return this.children[0]},i.Group.prototype.getClosestTo=function(t,e,s){for(var n=Number.MAX_VALUE,r=0,o=null,a=0;an&&(!e||e.call(s,h,r))&&(n=r,o=h)}return o},i.Group.prototype.count=function(t,e){return this.iterate(t,e,i.Group.RETURN_TOTAL)},i.Group.prototype.countLiving=function(){return this.count("alive",!0)},i.Group.prototype.countDead=function(){return this.count("alive",!1)},i.Group.prototype.getRandom=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.children.length),0===e?null:i.ArrayUtils.getRandomItem(this.children,t,e)},i.Group.prototype.getRandomExists=function(t,e){var i=this.getAll("exists",!0,t,e);return this.game.rnd.pick(i)},i.Group.prototype.getAll=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=this.children.length);for(var n=[],r=i;r0&&t instanceof i.Group){do{t.add(this.children[0],e)}while(this.children.length>0);this.hash=[],this.cursor=null}return t},i.Group.prototype.removeAll=function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),0!==this.children.length){do{!e&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var s=this.removeChild(this.children[0]);this.removeFromHash(s),t&&s&&s.destroy(!0,i)}while(this.children.length>0);this.hash=[],this.cursor=null}},i.Group.prototype.removeBetween=function(t,e,i,s){if(void 0===e&&(e=this.children.length-1),void 0===i&&(i=!1),void 0===s&&(s=!1),0!==this.children.length){if(t>e||t<0||e>this.children.length)return!1;for(var n=e;n>=t;){!s&&this.children[n].events&&this.children[n].events.onRemovedFromGroup$dispatch(this.children[n],this);var r=this.removeChild(this.children[n]);this.removeFromHash(r),i&&r&&r.destroy(!0),this.cursor===this.children[n]&&(this.cursor=null),n--}this.updateZ()}},i.Group.prototype.scatter=function(t,e){null==t&&(t=this.game.world.bounds),this.forEach(function(e){e.position.set(t.randomX,t.randomY)},null,e)},i.Group.prototype.shuffle=function(){i.ArrayUtils.shuffle(this.children),this.updateZ()},i.Group.prototype.destroy=function(t,e){null===this.game||this.ignoreDestroy||(void 0===t&&(t=!0),void 0===e&&(e=!1),this.onDestroy.dispatch(this,t,e),this.removeAll(t),this.cursor=null,this.filters=null,this.pendingDestroy=!1,e||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(i.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,i.Group.RETURN_TOTAL)}}),Object.defineProperty(i.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(i.Group.prototype,"angle",{get:function(){return i.Math.radToDeg(this.rotation)},set:function(t){this.rotation=i.Math.degToRad(t)}}),Object.defineProperty(i.Group.prototype,"centerX",{get:function(){return this.getBounds(this.parent).centerX},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.halfWidth}}),Object.defineProperty(i.Group.prototype,"centerY",{get:function(){return this.getBounds(this.parent).centerY},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.halfHeight}}),Object.defineProperty(i.Group.prototype,"left",{get:function(){return this.getBounds(this.parent).left},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i}}),Object.defineProperty(i.Group.prototype,"right",{get:function(){return this.getBounds(this.parent).right},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.width}}),Object.defineProperty(i.Group.prototype,"top",{get:function(){return this.getBounds(this.parent).top},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i}}),Object.defineProperty(i.Group.prototype,"bottom",{get:function(){return this.getBounds(this.parent).bottom},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.height}}),i.World=function(t){i.Group.call(this,t,null,"__world",!1),this.bounds=new i.Rectangle(0,0,t.width,t.height),this.camera=null,this._definedSize=!1,this._width=t.width,this._height=t.height,this.game.state.onStateChange.add(this.stateChange,this)},i.World.prototype=Object.create(i.Group.prototype),i.World.prototype.constructor=i.World,i.World.prototype.boot=function(){this.camera=new i.Camera(this.game,0,0,0,this.game.width,this.game.height),this.game.stage.addChild(this),this.camera.boot()},i.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},i.World.prototype.setBounds=function(t,e,i,s){this._definedSize=!0,this._width=i,this._height=s,this.bounds.setTo(t,e,i,s),this.x=t,this.y=e,this.camera.bounds&&this.camera.bounds.setTo(t,e,Math.max(i,this.game.width),Math.max(s,this.game.height)),this.game.physics.setBoundsToWorld()},i.World.prototype.resize=function(t,e){this._definedSize&&(tthis.bounds.right&&(t.x=this.bounds.left)),n&&(t.y+t._currentBounds.heightthis.bounds.bottom&&(t.y=this.bounds.top))):(s&&t.x+ethis.bounds.right&&(t.x=this.bounds.left-e),n&&t.y+ethis.bounds.bottom&&(t.y=this.bounds.top-e))},i.World.prototype.wrapAll=function(t,e,i,s,n,r){t.forEach(this.wrap,this,e,i,s,n,r)},Object.defineProperty(i.World.prototype,"width",{get:function(){return this.bounds.width},set:function(t){t1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.dropFrames?this.rendersThisFrame=0:(this.updateRender(this.time.slowMotion*this.time.desiredFps),this.rendersThisFrame=1);else{var e=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*e,this.time.elapsed),0);var i=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/e),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame)),this.forceSingleRender?this.rendersThisFrame=1:this.rendersThisFrame=Math.min(1,this.updatesThisFrame);this._deltaTime>=e&&(this._deltaTime-=e,this.currentUpdateID=i,this.updateLogic(this.time.desiredFpsMult),i++,!this.forceSingleUpdate||1!==i);)this.time.refresh();i>this._lastCount?this._spiraling++:i0&&this.updateRender(this._deltaTime/e)}}},updateLogic:function(t){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(t),this.debug.preUpdate(),this.input.pauseUpdate()):(this.stepping&&(this.pendingStep=!0),this.time.countUpdate(),this.scale.preUpdate(),this.debug.preUpdate(),this.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(t),this.plugins.preUpdate(t),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(),this.sound.update(),this.input.update(),this.physics.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate()),this.stage.updateTransform()},updateRender:function(t){this.lockRender||(this.time.countRender(),this.state.preRender(t),this.renderType!==i.HEADLESS&&(this.renderer.render(this.stage),this.plugins.render(t),this.state.render(t)),this.plugins.postRender(t))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.debug.destroy&&this.debug.destroy(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.plugins.destroy(),this.debug=null,this.state=null,this.sound=null,this.scale=null,this.stage=null,this.input=null,this.physics=null,this.plugins=null,this.cache=null,this.load=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),i.Canvas.removeFromDOM(this.canvas),PIXI.defaultRenderer=null,i.GAMES[this.id]=null},gamePaused:function(t){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.muteOnPause&&this.sound.setMute(),this.onPause.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(t){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.muteOnPause&&this.sound.unsetMute(),this.onResume.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(t){this.onBlur.dispatch(t),this.stage.disableVisibilityChange||this.gamePaused(t)},focusGain:function(t){this.onFocus.dispatch(t),this.stage.disableVisibilityChange||this.gameResumed(t)}},i.Game.prototype.constructor=i.Game,Object.defineProperty(i.Game.prototype,"paused",{get:function(){return this._paused},set:function(t){!0===t?(!1===this._paused&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),i.Input=function(t){this.game=t,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.customCandidateHandler=null,this.customCandidateHandlerContext=null,this.pollRate=0,this.enabled=!0,this.multiInputOverride=i.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.touchLockCallbacks=[],this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new i.ArraySet,this._localPoint=new i.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},i.Input.MOUSE_OVERRIDES_TOUCH=0,i.Input.TOUCH_OVERRIDES_MOUSE=1,i.Input.MOUSE_TOUCH_COMBINE=2,i.Input.MAX_POINTERS=10,i.Input.prototype={boot:function(){this.mousePointer=new i.Pointer(this.game,0,i.PointerMode.CURSOR),this.addPointer(),this.addPointer(),this.mouse=new i.Mouse(this.game),this.touch=new i.Touch(this.game),this.mspointer=new i.MSPointer(this.game),i.Keyboard&&(this.keyboard=new i.Keyboard(this.game)),i.Gamepad&&(this.gamepad=new i.Gamepad(this.game)),this.onDown=new i.Signal,this.onUp=new i.Signal,this.onTap=new i.Signal,this.onHold=new i.Signal,this.scale=new i.Point(1,1),this.speed=new i.Point,this.position=new i.Point,this._oldPosition=new i.Point,this.circle=new i.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=i.CanvasPool.create(this,1,1),this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.game.device.mspointer||this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var t=this;this._onClickTrampoline=function(e){t.onClickTrampoline(e)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],i.CanvasPool.remove(this),this.game.canvas.removeEventListener("click",this._onClickTrampoline)},setInteractiveCandidateHandler:function(t,e){this.customCandidateHandler=t,this.customCandidateHandlerContext=e},addMoveCallback:function(t,e){this.moveCallbacks.push({callback:t,context:e})},addTouchLockCallback:function(t,e,i){void 0===i&&(i=!1),this.touchLockCallbacks.push({callback:t,context:e,onEnd:i})},removeTouchLockCallback:function(t,e){for(var i=this.touchLockCallbacks.length;i--;)if(this.touchLockCallbacks[i].callback===t&&this.touchLockCallbacks[i].context===e)return this.touchLockCallbacks.splice(i,1),!0;return!1},executeTouchLockCallbacks:function(t,e){for(var i=this.touchLockCallbacks.length;i--;){var s=this.touchLockCallbacks[i];s.onEnd===t&&s.callback.call(s.context,this,e)&&this.touchLockCallbacks.splice(i,1)}},deleteMoveCallback:function(t,e){for(var i=this.moveCallbacks.length;i--;)if(this.moveCallbacks[i].callback===t&&this.moveCallbacks[i].context===e)return void this.moveCallbacks.splice(i,1)},addPointer:function(){if(this.pointers.length>=i.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+i.Input.MAX_POINTERS+" pointers reached."),null;var t=this.pointers.length+1,e=new i.Pointer(this.game,t,i.PointerMode.CONTACT);return this.pointers.push(e),this["pointer"+t]=e,e},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(t);if(!this.pointer2.active)return this.pointer2.start(t);for(var e=2;e0;i++)this.pointers[i].active&&e--;return t-e},getPointer:function(t){void 0===t&&(t=!1);for(var e=0;e=o&&this.game.camera.x+e.x=a&&this.game.camera.y+e.y=o&&this._localPoint.x=a&&this._localPoint.y=o&&this._localPoint.x=a&&this._localPoint.y0&&this._pollCounterthis.game.time.time},justReleased:function(t){return t=t||250,this.isUp&&this.timeUp+t>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},i.DeviceButton.prototype.constructor=i.DeviceButton,Object.defineProperty(i.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),i.Pointer=function(t,e,s){this.game=t,this.id=e,this.type=i.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.pointerMode=s||i.PointerMode.CURSOR|i.PointerMode.CONTACT,this.target=null,this.button=null,this.leftButton=new i.DeviceButton(this,i.Pointer.LEFT_BUTTON),this.middleButton=new i.DeviceButton(this,i.Pointer.MIDDLE_BUTTON),this.rightButton=new i.DeviceButton(this,i.Pointer.RIGHT_BUTTON),this.backButton=new i.DeviceButton(this,i.Pointer.BACK_BUTTON),this.forwardButton=new i.DeviceButton(this,i.Pointer.FORWARD_BUTTON),this.eraserButton=new i.DeviceButton(this,i.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===e,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.interactiveCandidates=[],this.active=!1,this.dirty=!1,this.position=new i.Point,this.positionDown=new i.Point,this.positionUp=new i.Point,this.circle=new i.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},i.Pointer.NO_BUTTON=0,i.Pointer.LEFT_BUTTON=1,i.Pointer.RIGHT_BUTTON=2,i.Pointer.MIDDLE_BUTTON=4,i.Pointer.BACK_BUTTON=8,i.Pointer.FORWARD_BUTTON=16,i.Pointer.ERASER_BUTTON=32,i.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.start(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.start(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.start(e),t===i.Mouse.BACK_BUTTON&&this.backButton.start(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.start(e)},processButtonsUp:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.stop(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.stop(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(e),t===i.Mouse.BACK_BUTTON&&this.backButton.stop(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(e)},processButtonsUpDown:function(t,e){var s="down"===e.type.toLowerCase().substr(-4),n="move"===e.type.toLowerCase().substr(-4);void 0!==t?(s&&1===t&&e.ctrlKey&&(t=2),this.leftButton.startStop(i.Pointer.LEFT_BUTTON&t,e),this.rightButton.startStop(i.Pointer.RIGHT_BUTTON&t,e),this.middleButton.startStop(i.Pointer.MIDDLE_BUTTON&t,e),this.backButton.startStop(i.Pointer.BACK_BUTTON&t,e),this.forwardButton.startStop(i.Pointer.FORWARD_BUTTON&t,e),this.eraserButton.startStop(i.Pointer.ERASER_BUTTON&t,e)):void 0!==e.button?s&&e.ctrlKey&&0===e.button?this.rightButton.start(e):s?this.processButtonsDown(e.button,e):n||this.processButtonsUp(e.button,e):s?e.ctrlKey?this.rightButton.start(e):this.leftButton.start(e):(this.leftButton.stop(e),this.rightButton.stop(e))},updateButtons:function(t){this.button=t.button,this.processButtonsUpDown(t.buttons,t),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(t){var e=this.game.input;return t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.isMouse?this.updateButtons(t):(this.isDown=!0,this.isUp=!1),this.active=!0,this.withinGame=!0,this.dirty=!1,this._history=[],this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(t,!0),this.positionDown.setTo(this.x,this.y),(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.x=this.x,e.y=this.y,e.position.setTo(this.x,this.y),e.onDown.dispatch(this,t),e.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){var t=this.game.input;this.active&&(this.dirty&&(t.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),!1===this._holdSent&&this.duration>=t.holdRate&&((t.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||t.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||t.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===t.totalActivePointers)&&t.onHold.dispatch(this),this._holdSent=!0),t.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+t.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>t.recordLimit&&this._history.shift()))},move:function(t,e){var s=this.game.input;if(!s.pollLocked){void 0===e&&(e=!1),void 0!==t.button&&(this.button=t.button),this.isMouse&&this.updateButtons(t),this.clientX=t.clientX,this.clientY=t.clientY,this.pageX=t.pageX,this.pageY=t.pageY,this.screenX=t.screenX,this.screenY=t.screenY,this.isMouse&&s.mouse.locked&&!e&&(this.rawMovementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.rawMovementY=t.movementY||t.mozMovementY||t.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*s.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*s.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(s.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||s.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||s.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===s.totalActivePointers)&&(s.activePointer=this,s.x=this.x,s.y=this.y,s.position.setTo(s.x,s.y),s.circle.x=s.x,s.circle.y=s.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY);for(var n=s.moveCallbacks.length;n--;)s.moveCallbacks[n].callback.call(s.moveCallbacks[n].context,this,this.x,this.y,e);return null===this.targetObject||this.game.paused&&!this.targetObject.noPause||!0!==this.targetObject.isDragged?s.interactiveItems.total>0&&this.processInteractiveObjects(e):!1===this.targetObject.update(this)&&(this.targetObject=null),this}},processInteractiveObjects:function(t){var e=0,i=-1,s=null,n=this.game.input.interactiveItems.first;for(this.interactiveCandidates=[];n;)n.checked=!1,!n.validForInput(i,e,!1)||this.game.paused&&!n.sprite.noPause||(n.checked=!0,(t&&n.checkPointerDown(this,!0)||!t&&n.checkPointerOver(this,!0))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n))),n=this.game.input.interactiveItems.next;for(n=this.game.input.interactiveItems.first;n;)!n.checked&&n.validForInput(i,e,!0)&&(t&&n.checkPointerDown(this,!1)||!t&&n.checkPointerOver(this,!1))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n)),n=this.game.input.interactiveItems.next;return this.game.input.customCandidateHandler&&(s=this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext,this,this.interactiveCandidates,s)),this.swapTarget(s,!1),null!==this.targetObject},swapTarget:function(t,e){void 0===e&&(e=!1),null===t?this.targetObject&&(this.targetObject._pointerOutHandler(this,e),this.targetObject=null):null===this.targetObject?(this.targetObject=t,t._pointerOverHandler(this,e)):this.targetObject===t?!1===t.update(this)&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this,e),this.targetObject=t,this.targetObject._pointerOverHandler(this,e))},leave:function(t){this.withinGame=!1,this.move(t,!1)},stop:function(t){var e=this.game.input;{if(!this._stateReset||!this.withinGame)return this.timeUp=this.game.time.time,(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.onUp.dispatch(this,t),this.duration>=0&&this.duration<=e.tapRate&&(this.timeUp-this.previousTapTime0&&(this.active=!1),this.withinGame=this.game.scale.bounds.contains(t.pageX,t.pageY),this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),!1===this.isMouse&&e.currentPointers--,e.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this;t.preventDefault()}},justPressed:function(t){return t=t||this.game.input.justPressedRate,!0===this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||this.game.input.justReleasedRate,this.isUp&&this.timeUp+t>this.game.time.time},addClickTrampoline:function(t,e,i,s){if(this.isDown){for(var n=this._clickTrampolines=this._clickTrampolines||[],r=0;rt||this.priorityID===t&&this.sprite.renderOrderID>e))},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(t){return t=t||0,this._pointerData[t].x},pointerY:function(t){return t=t||0,this._pointerData[t].y},pointerDown:function(t){return t=t||0,this._pointerData[t].isDown},pointerUp:function(t){return t=t||0,this._pointerData[t].isUp},pointerTimeDown:function(t){return t=t||0,this._pointerData[t].timeDown},pointerTimeUp:function(t){return t=t||0,this._pointerData[t].timeUp},pointerOver:function(t){if(!this.enabled)return!1;if(void 0===t){for(var e=0;e<10;e++)if(this._pointerData[e].isOver)return!0;return!1}return this._pointerData[t].isOver},pointerOut:function(t){if(!this.enabled)return!1;if(void 0!==t)return this._pointerData[t].isOut;for(var e=0;e<10;e++)if(this._pointerData[e].isOut)return!0},pointerTimeOver:function(t){return t=t||0,this._pointerData[t].timeOver},pointerTimeOut:function(t){return t=t||0,this._pointerData[t].timeOut},pointerDragged:function(t){return t=t||0,this._pointerData[t].isDragged},checkPointerDown:function(t,e){return!!(t.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectClick)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPointerOver:function(t,e){return!!(this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectOver)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPixel:function(t,e,i){if(this.sprite.texture.baseTexture.source){if(null===t&&null===e){this.game.input.getLocalPosition(this.sprite,i,this._tempPoint);var t=this._tempPoint.x,e=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(t-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(e-=-this.sprite.texture.frame.height*this.sprite.anchor.y),t+=this.sprite.texture.frame.x,e+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(t-=this.sprite.texture.trim.x,e-=this.sprite.texture.trim.y,tthis.sprite.texture.crop.right||ethis.sprite.texture.crop.bottom))return this._dx=t,this._dy=e,!1;if(this._dx=t,this._dy=e,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,t,e,1,1,0,0,1,1),this.game.input.hitContext.getImageData(0,0,1,1).data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(t){if(null!==this.sprite&&void 0!==this.sprite.parent)return this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this._pendingDrag?(this._dragDistancePass||(this._dragDistancePass=i.Math.distance(t.x,t.y,this.downPoint.x,this.downPoint.y)>=this.dragDistanceThreshold),this._dragDistancePass&&this._dragTimePass&&this.startDrag(t),!0):this.draggable&&this._draggedPointerID===t.id?this.updateDrag(t,!1):this._pointerData[t.id].isOver?this.checkPointerOver(t)?(this._pointerData[t.id].x=t.x-this.sprite.x,this._pointerData[t.id].y=t.y-this.sprite.y,!0):(this._pointerOutHandler(t),!1):void 0:(this._pointerOutHandler(t),!1)},_pointerOverHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];if(!1===i.isOver||t.dirty){var s=!1===i.isOver;i.isOver=!0,i.isOut=!1,i.timeOver=this.game.time.time,i.x=t.x-this.sprite.x,i.y=t.y-this.sprite.y,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),!e&&s&&this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,t),this.sprite.parent&&this.sprite.parent.onChildInputOver&&this.sprite.parent.onChildInputOver.dispatch(this.sprite,t)}}},_pointerOutHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];i.isOver=!1,i.isOut=!0,i.timeOut=this.game.time.time,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="",this._setHandCursor=!1),!e&&this.sprite&&this.sprite.events&&(this.sprite.events.onInputOut$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputOut&&this.sprite.parent.onChildInputOut.dispatch(this.sprite,t))}},_touchedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(!e.isDown&&e.isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,t))return;if(e.isDown=!0,e.isUp=!1,e.timeDown=this.game.time.time,this.downPoint.set(t.x,t.y),t.dirty=!0,this.sprite&&this.sprite.events&&(this.sprite.events.onInputDown$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputDown&&this.sprite.parent.onChildInputDown.dispatch(this.sprite,t),null===this.sprite))return;this.draggable&&!1===this.isDragged&&(0===this.dragTimeThreshold&&0===this.dragDistanceThreshold?this.startDrag(t):(this._pendingDrag=!0,this._dragDistancePass=0===this.dragDistanceThreshold,this.dragTimeThreshold>0?(this._dragTimePass=!1,this.game.time.events.add(this.dragTimeThreshold,this.dragTimeElapsed,this,t)):this._dragTimePass=!0)),this.bringToTop&&this.sprite.bringToTop()}}},dragTimeElapsed:function(t){this._dragTimePass=!0,this._pendingDrag&&this.sprite&&this._dragDistancePass&&this.startDrag(t)},_releasedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(e.isDown&&t.isUp){e.isDown=!1,e.isUp=!0,e.timeUp=this.game.time.time,e.downDuration=e.timeUp-e.timeDown;var i=this.checkPointerOver(t);this.sprite&&this.sprite.events&&(this.dragStopBlocksInputUp&&(!this.dragStopBlocksInputUp||this.draggable&&this.isDragged&&this._draggedPointerID===t.id)||this.sprite.events.onInputUp$dispatch(this.sprite,t,i),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputUp&&this.sprite.parent.onChildInputUp.dispatch(this.sprite,t,i),i&&(i=this.checkPointerOver(t))),e.isOver=i,!i&&this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),t.dirty=!0,this._pendingDrag=!1,this.draggable&&this.isDragged&&this._draggedPointerID===t.id&&this.stopDrag(t)}}},updateDrag:function(t,e){if(void 0===e&&(e=!1),t.isUp)return this.stopDrag(t),!1;var i=this.globalToLocal(t);if(this.sprite.fixedToCamera)var s=this.game.camera.scale.x*i.x+this._dragPoint.x+this.dragOffset.x,n=this.game.camera.scale.y*i.y+this._dragPoint.y+this.dragOffset.y;else var s=i.x+this._dragPoint.x+this.dragOffset.x,n=i.y+this._dragPoint.y+this.dragOffset.y;if(this.sprite.fixedToCamera)this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=s-this.game.camera.x),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=n-this.game.camera.y),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y));else{var r=this.game.camera.x-this._pointerData[t.id].camX,o=this.game.camera.y-this._pointerData[t.id].camY;this.allowHorizontalDrag&&(this.sprite.x=s+r),this.allowVerticalDrag&&(this.sprite.y=n+o),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.x,this.sprite.y))}return this.sprite.events.onDragUpdate.dispatch(this.sprite,t,s,n,this.snapPoint,e),!0},justOver:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOver&&this.overDuration(t)this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.ythis.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.leftthis.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.xthis.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.ythis.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.leftthis.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},i.InputHandler.prototype.constructor=i.InputHandler,i.Gamepad=function(t){this.game=t,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!==navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this)]},i.Gamepad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},start:function(){if(!this._active){this._active=!0;var t=this;this._onGamepadConnected=function(e){return t.onGamepadConnected(e)},this._onGamepadDisconnected=function(e){return t.onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(t){var e=t.gamepad;this._rawPads.push(e),this._gamepads[e.index].connect(e)},onGamepadDisconnected:function(t){var e=t.gamepad;for(var i in this._rawPads)this._rawPads[i].index===e.index&&this._rawPads.splice(i,1);this._gamepads[e.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(this._active){if(navigator.getGamepads)t=navigator.getGamepads();else if(navigator.webkitGetGamepads)t=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var t=navigator.webkitGamepads();if(t){this._rawPads=[];for(var e=!1,i=0;i0&&s>this.deadZone||s<0&&s<-this.deadZone?this.processAxisChange(i,s):this.processAxisChange(i,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(t){var e=!this.connected;this.connected=!0,this.index=t.index,this._rawPad=t,this._buttons=[],this._buttonsLen=t.buttons.length,this._axes=[],this._axesLen=t.axes.length;for(var s=0;sthis.maxHealth&&(this.health=this.maxHealth),this},heal:function(t){return this.alive&&(this.health+=t,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},i.Component.InCamera=function(){},i.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},i.Component.InputEnabled=function(){},i.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(t){t?null===this.input?(this.input=new i.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},i.Component.InWorld=function(){},i.Component.InWorld.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(this.autoCull||this.checkWorldBounds){if(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull)if(this.game.world.camera.view.intersects(this._bounds))this.renderable=!0,this.game.world.camera.totalInView++;else if(this.renderable=!1,this.outOfCameraBoundsKill)return this.kill(),!1;if(this.checkWorldBounds)if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1}return!0},i.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,outOfCameraBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},i.Component.LifeSpan=function(){},i.Component.LifeSpan.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):!(this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0))||(this.kill(),!1)},i.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(t){return void 0===t&&(t=100),this.alive=!0,this.exists=!0,this.visible=!0,"function"==typeof this.setHealth&&this.setHealth(t),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},i.Component.LoadTexture=function(){},i.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(t,e,s){t===i.PENDING_ATLAS?(t=e,e=0):e=e||0,(s||void 0===s)&&this.animations&&this.animations.stop(),this.key=t,this.customRender=!1;var n=this.game.cache,r=!0,o=!this.texture.baseTexture.scaleMode;if(i.RenderTexture&&t instanceof i.RenderTexture)this.key=t.key,this.setTexture(t);else if(i.BitmapData&&t instanceof i.BitmapData)this.customRender=!0,this.setTexture(t.texture),r=n.hasFrameData(t.key,i.Cache.BITMAPDATA)?!this.animations.loadFrameData(n.getFrameData(t.key,i.Cache.BITMAPDATA),e):!this.animations.loadFrameData(t.frameData,0);else if(i.Video&&t instanceof i.Video){this.customRender=!0;var a=t.texture.valid;this.setTexture(t.texture),this.setFrame(t.texture.frame.clone()),t.onChangeSource.add(this.resizeFrame,this),this.texture.valid=a}else if(i.Tilemap&&t instanceof i.TilemapLayer)this.setTexture(PIXI.Texture.fromCanvas(t.canvas));else if(t instanceof PIXI.Texture)this.setTexture(t);else{var h=n.getImage(t,!0);this.key=h.key,this.setTexture(new PIXI.Texture(h.base)),this.texture.baseTexture.skipRender="__default"===t,r=!this.animations.loadFrameData(h.frameData,e)}r&&(this._frame=i.Rectangle.clone(this.texture.frame)),o||(this.texture.baseTexture.scaleMode=1)},setFrame:function(t){this._frame=t,this.texture.frame.x=t.x,this.texture.frame.y=t.y,this.texture.frame.width=t.width,this.texture.frame.height=t.height,this.texture.crop.x=t.x,this.texture.crop.y=t.y,this.texture.crop.width=t.width,this.texture.crop.height=t.height,t.trimmed?(this.texture.trim?(this.texture.trim.x=t.spriteSourceSizeX,this.texture.trim.y=t.spriteSourceSizeY,this.texture.trim.width=t.sourceSizeW,this.texture.trim.height=t.sourceSizeH):this.texture.trim={x:t.spriteSourceSizeX,y:t.spriteSourceSizeY,width:t.sourceSizeW,height:t.sourceSizeH},this.texture.width=t.sourceSizeW,this.texture.height=t.sourceSizeH,this.texture.frame.width=t.sourceSizeW,this.texture.frame.height=t.sourceSizeH):!t.trimmed&&this.texture.trim&&(this.texture.trim=null),t.rotated&&(this.texture.rotated=!0),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(t,e,i){this.texture.frame.resize(e,i),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(t){this.animations.frame=t}},frameName:{get:function(){return this.animations.frameName},set:function(t){this.animations.frameName=t}}},i.Component.Overlap=function(){},i.Component.Overlap.prototype={overlap:function(t){return i.Rectangle.intersects(this.getBounds(),t.getBounds())}},i.Component.PhysicsBody=function(){},i.Component.PhysicsBody.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):this.fresh&&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.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,this.preUpdateChildren(),!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!(!this._exists||!this.parent.exists)||(this.renderOrderID=-1,!1))},i.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},i.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(t){this.position.x=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},i.Component.Reset=function(){},i.Component.Reset.prototype.reset=function(t,e,i){return void 0===i&&(i=1),this.world.set(t,e),this.position.set(t,e),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=i),this.components.PhysicsBody&&this.body&&this.body.reset(t,e,!1,!1),this},i.Component.ScaleMinMax=function(){},i.Component.ScaleMinMax.prototype={transformCallback:null,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(t){this.scaleMin&&(t.athis.scaleMax.x&&(t.a=this.scaleMax.x),t.d>this.scaleMax.y&&(t.d=this.scaleMax.y))},setScaleMinMax:function(t,e,s,n){void 0===e?e=s=n=t:void 0===s&&(s=n=e,e=t),null===t?this.scaleMin=null:this.scaleMin?this.scaleMin.set(t,e):this.scaleMin=new i.Point(t,e),null===s?this.scaleMax=null:this.scaleMax?this.scaleMax.set(s,n):this.scaleMax=new i.Point(s,n),null===this.scaleMin?this.transformCallback=null:(this.transformCallback=this.checkTransform,this.transformCallbackContext=this)}},i.Component.Smoothed=function(){},i.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(t){t?this.texture&&(this.texture.baseTexture.scaleMode=0,this.texture.baseTexture.dirty()):this.texture&&(this.texture.baseTexture.scaleMode=1,this.texture.baseTexture.dirty())}}},i.GameObjectFactory=function(t){this.game=t,this.world=this.game.world},i.GameObjectFactory.prototype={existing:function(t){return this.world.add(t)},weapon:function(t,e,s,n,r){var o=this.game.plugins.add(i.Weapon);return r&&(o.bulletClass=r),o.createBullets(t,e,s,n),o},image:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Image(this.game,t,e,s,n))},sprite:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Sprite(this.game,t,e,s,n))},creature:function(t,e,s,n,r){void 0===r&&(r=this.world);var o=new i.Creature(this.game,t,e,s,n);return r.add(o),o},tween:function(t){return this.game.tweens.create(t)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},physicsGroup:function(t,e,s,n){return new i.Group(this.game,e,s,n,!0,t)},spriteBatch:function(t,e,s){return void 0===t&&(t=null),void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},tileSprite:function(t,e,s,n,r,o,a){return void 0===a&&(a=this.world),a.add(new i.TileSprite(this.game,t,e,s,n,r,o))},rope:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.Rope(this.game,t,e,s,n,r))},text:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Text(this.game,t,e,s,n))},button:function(t,e,s,n,r,o,a,h,l,c){return void 0===c&&(c=this.world),c.add(new i.Button(this.game,t,e,s,n,r,o,a,h,l))},graphics:function(t,e,s){return void 0===s&&(s=this.world),s.add(new i.Graphics(this.game,t,e))},emitter:function(t,e,s){return this.game.particles.add(new i.Particles.Arcade.Emitter(this.game,t,e,s))},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.BitmapText(this.game,t,e,s,n,r))},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},video:function(t,e){return new i.Video(this.game,t,e)},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t},plugin:function(t){return this.game.plugins.add(t)}},i.GameObjectFactory.prototype.constructor=i.GameObjectFactory,i.GameObjectCreator=function(t){this.game=t,this.world=this.game.world},i.GameObjectCreator.prototype={image:function(t,e,s,n){return new i.Image(this.game,t,e,s,n)},sprite:function(t,e,s,n){return new i.Sprite(this.game,t,e,s,n)},tween:function(t){return new i.Tween(t,this.game,this.game.tweens)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},spriteBatch:function(t,e,s){return void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},tileSprite:function(t,e,s,n,r,o){return new i.TileSprite(this.game,t,e,s,n,r,o)},rope:function(t,e,s,n,r){return new i.Rope(this.game,t,e,s,n,r)},text:function(t,e,s,n){return new i.Text(this.game,t,e,s,n)},button:function(t,e,s,n,r,o,a,h,l){return new i.Button(this.game,t,e,s,n,r,o,a,h,l)},graphics:function(t,e){return new i.Graphics(this.game,t,e)},emitter:function(t,e,s){return new i.Particles.Arcade.Emitter(this.game,t,e,s)},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return new i.BitmapText(this.game,t,e,s,n,r,o)},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t}},i.GameObjectCreator.prototype.constructor=i.GameObjectCreator,i.Sprite=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.SPRITE,this.physicsType=i.SPRITE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Sprite.prototype=Object.create(PIXI.Sprite.prototype),i.Sprite.prototype.constructor=i.Sprite,i.Component.Core.install.call(i.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Sprite.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Sprite.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Sprite.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Sprite.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Sprite.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Image=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.IMAGE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Image.prototype=Object.create(PIXI.Sprite.prototype),i.Image.prototype.constructor=i.Image,i.Component.Core.install.call(i.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","ScaleMinMax","Smoothed"]),i.Image.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Image.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Image.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Image.prototype.preUpdate=function(){return!(!this.preUpdateInWorld()||!this.preUpdateLifeSpan())&&this.preUpdateCore()},i.Button=function(t,e,s,n,r,o,a,h,l,c){e=e||0,s=s||0,n=n||null,r=r||null,o=o||this,i.Image.call(this,t,e,s,n,h),this.type=i.BUTTON,this.physicsType=i.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new i.Signal,this.onInputOut=new i.Signal,this.onInputDown=new i.Signal,this.onInputUp=new i.Signal,this.onOverMouseOnly=!0,this.justReleasedPreventsOver=i.PointerMode.CONTACT,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(a,h,l,c),null!==r&&this.onInputUp.add(r,o),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this)},i.Button.prototype=Object.create(i.Image.prototype),i.Button.prototype.constructor=i.Button;return i.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},i.Button.prototype.setStateFrame=function(t,e,i){var s="_on"+t+"Frame";null!==e?(this[s]=e,i&&this.changeStateFrame(t)):this[s]=null},i.Button.prototype.changeStateFrame=function(t){if(this.freezeFrames)return!1;var e=this["_on"+t+"Frame"];return"string"==typeof e?(this.frameName=e,!0):"number"==typeof e&&(this.frame=e,!0)},i.Button.prototype.setFrames=function(t,e,i,s){this.setStateFrame("Over",t,this.input.pointerOver()),this.setStateFrame("Out",e,!this.input.pointerOver()),this.setStateFrame("Down",i,this.input.pointerDown()),this.setStateFrame("Up",s,this.input.pointerUp())},i.Button.prototype.setStateSound=function(t,e,s){var n="on"+t+"Sound",r="on"+t+"SoundMarker";e instanceof i.Sound||e instanceof i.AudioSprite?(this[n]=e,this[r]="string"==typeof s?s:""):(this[n]=null,this[r]="")},i.Button.prototype.playStateSound=function(t){var e=this["on"+t+"Sound"];if(e){var i=this["on"+t+"SoundMarker"];return e.play(i),!0}return!1},i.Button.prototype.setSounds=function(t,e,i,s,n,r,o,a){this.setStateSound("Over",t,e),this.setStateSound("Out",n,r),this.setStateSound("Down",i,s),this.setStateSound("Up",o,a)},i.Button.prototype.setOverSound=function(t,e){this.setStateSound("Over",t,e)},i.Button.prototype.setOutSound=function(t,e){this.setStateSound("Out",t,e)},i.Button.prototype.setDownSound=function(t,e){this.setStateSound("Down",t,e)},i.Button.prototype.setUpSound=function(t,e){this.setStateSound("Up",t,e)},i.Button.prototype.onInputOverHandler=function(t,e){e.justReleased()&&(this.justReleasedPreventsOver&e.pointerMode)===e.pointerMode||(this.changeStateFrame("Over"),this.onOverMouseOnly&&!e.isMouse||(this.playStateSound("Over"),this.onInputOver&&this.onInputOver.dispatch(this,e)))},i.Button.prototype.onInputOutHandler=function(t,e){this.changeStateFrame("Out"),this.playStateSound("Out"),this.onInputOut&&this.onInputOut.dispatch(this,e)},i.Button.prototype.onInputDownHandler=function(t,e){this.changeStateFrame("Down"),this.playStateSound("Down"),this.onInputDown&&this.onInputDown.dispatch(this,e)},i.Button.prototype.onInputUpHandler=function(t,e,i){this.playStateSound("Up"),this.onInputUp&&this.onInputUp.dispatch(this,e,i),this.freezeFrames||(!0===this.forceOut||(this.forceOut&e.pointerMode)===e.pointerMode?this.changeStateFrame("Out"):this.changeStateFrame("Up")||(i?this.changeStateFrame("Over"):this.changeStateFrame("Out")))},i.SpriteBatch=function(t,e,s,n){void 0!==e&&null!==e||(e=t.world),i.Group.call(this,t,e,s,n),this.type=i.SPRITEBATCH,this.fastSpriteBatch=null,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.Group.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||(this.fastSpriteBatch=new PIXI.WebGLFastSpriteBatch(t.gl),this.ready=!0),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n=0&&t<=this.width&&e>=0&&e<=this.height&&(i.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|n<<8|s:this.pixels[e*this.width+t]=s<<24|n<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,s){s||(s=i.Color.createColor());var n=~~(t+e*this.width);return n*=4,s.r=this.data[n],s.g=this.data[++n],s.b=this.data[++n],s.a=this.data[++n],s},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,s,n,r){return i.Color.unpackPixel(this.getPixel32(t,e),s,n,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=i.Color.createColor(),s=0,n=0,r=1,o=!1;1===t?(r=-1,n=this.height):3===t&&(r=-1,s=this.width);do{i.Color.unpackPixel(this.getPixel32(s,n),e),0===t||1===t?++s===this.width&&(s=0,((n+=r)>=this.height||n<=0)&&(o=!0)):2!==t&&3!==t||++n===this.height&&(n=0,((s+=r)>=this.width||s<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=s,e.y=n,e},getBounds:function(t){return void 0===t&&(t=new i.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,s,n,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),t instanceof i.RenderTexture&&(t=t.getCanvas()),this._image=t,t instanceof i.Sprite||t instanceof i.Image||t instanceof i.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof i.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==s&&null!==s||(s=0),n&&(this._size.x=n),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=s),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+s,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var n=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===n.a||0===n.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=n.tx,o=n.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),s&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(n.a,n.b,n.c,n.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,s){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,s),t.type===i.GROUP&&t.exists)this.drawGroup(t,e,s);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var n=0;ne.width&&(n=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,s),this._circle=new i.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,n,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),i.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this},copyBitmapData:function(t,e,i){t.update();for(var s,n=0;n80*s){h=c=t[0],l=u=t[1];for(var g=s;gc&&(c=d),p>u&&(u=p);f=Math.max(c-h,u-l)}return i.EarCut.earcutLinked(o,a,s,h,l,f),a},i.EarCut.linkedList=function(t,e,s,n,r){var o,a,h,l=0;for(o=e,a=s-n;o0)for(o=e;o=e;o-=n)h=i.EarCut.insertNode(o,t[o],t[o+1],h);return h},i.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var s,n=t;do{if(s=!1,n.steiner||!i.EarCut.equals(n,n.next)&&0!==i.EarCut.area(n.prev,n,n.next))n=n.next;else{if(i.EarCut.removeNode(n),(n=e=n.prev)===n.next)return null;s=!0}}while(s||n!==e);return e},i.EarCut.earcutLinked=function(t,e,s,n,r,o,a){if(t){!a&&o&&i.EarCut.indexCurve(t,n,r,o);for(var h,l,c=t;t.prev!==t.next;)if(h=t.prev,l=t.next,o?i.EarCut.isEarHashed(t,n,r,o):i.EarCut.isEar(t))e.push(h.i/s),e.push(t.i/s),e.push(l.i/s),i.EarCut.removeNode(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?(t=i.EarCut.cureLocalIntersections(t,e,s),i.EarCut.earcutLinked(t,e,s,n,r,o,2)):2===a&&i.EarCut.splitEarcut(t,e,s,n,r,o):i.EarCut.earcutLinked(i.EarCut.filterPoints(t),e,s,n,r,o,1);break}}},i.EarCut.isEar=function(t){var e=t.prev,s=t,n=t.next;if(i.EarCut.area(e,s,n)>=0)return!1;for(var r=t.next.next;r!==t.prev;){if(i.EarCut.pointInTriangle(e.x,e.y,s.x,s.y,n.x,n.y,r.x,r.y)&&i.EarCut.area(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},i.EarCut.isEarHashed=function(t,e,s,n){var r=t.prev,o=t,a=t.next;if(i.EarCut.area(r,o,a)>=0)return!1;for(var h=r.xo.x?r.x>a.x?r.x:a.x:o.x>a.x?o.x:a.x,u=r.y>o.y?r.y>a.y?r.y:a.y:o.y>a.y?o.y:a.y,d=i.EarCut.zOrder(h,l,e,s,n),p=i.EarCut.zOrder(c,u,e,s,n),f=t.nextZ;f&&f.z<=p;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=d;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0},i.EarCut.cureLocalIntersections=function(t,e,s){var n=t;do{var r=n.prev,o=n.next.next;i.EarCut.intersects(r,n,n.next,o)&&i.EarCut.locallyInside(r,o)&&i.EarCut.locallyInside(o,r)&&(e.push(r.i/s),e.push(n.i/s),e.push(o.i/s),i.EarCut.removeNode(n),i.EarCut.removeNode(n.next),n=t=o),n=n.next}while(n!==t);return n},i.EarCut.splitEarcut=function(t,e,s,n,r,o){var a=t;do{for(var h=a.next.next;h!==a.prev;){if(a.i!==h.i&&i.EarCut.isValidDiagonal(a,h)){var l=i.EarCut.splitPolygon(a,h);return a=i.EarCut.filterPoints(a,a.next),l=i.EarCut.filterPoints(l,l.next),i.EarCut.earcutLinked(a,e,s,n,r,o),void i.EarCut.earcutLinked(l,e,s,n,r,o)}h=h.next}a=a.next}while(a!==t)},i.EarCut.eliminateHoles=function(t,e,s,n){var r,o,a,h,l,c=[];for(r=0,o=e.length;r=n.next.y){var h=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);h<=r&&h>a&&(a=h,s=n.x=n.x&&n.x>=s.x&&i.EarCut.pointInTriangle(os.x)&&i.EarCut.locallyInside(n,t)&&(s=n,u=l),n=n.next;return s},i.EarCut.indexCurve=function(t,e,s,n){var r=t;do{null===r.z&&(r.z=i.EarCut.zOrder(r.x,r.y,e,s,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,i.EarCut.sortLinked(r)},i.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},i.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},i.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},i.EarCut.isValidDiagonal=function(t,e){return i.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!i.EarCut.intersectsPolygon(t,e)&&i.EarCut.locallyInside(t,e)&&i.EarCut.locallyInside(e,t)&&i.EarCut.middleInside(t,e)},i.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},i.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},i.EarCut.intersects=function(t,e,s,n){return i.EarCut.area(t,e,s)>0!=i.EarCut.area(t,e,n)>0&&i.EarCut.area(s,n,t)>0!=i.EarCut.area(s,n,e)>0},i.EarCut.intersectsPolygon=function(t,e){var s=t;do{if(s.i!==t.i&&s.next.i!==t.i&&s.i!==e.i&&s.next.i!==e.i&&i.EarCut.intersects(s,s.next,t,e))return!0;s=s.next}while(s!==t);return!1},i.EarCut.locallyInside=function(t,e){return i.EarCut.area(t.prev,t,t.next)<0?i.EarCut.area(t,e,t.next)>=0&&i.EarCut.area(t,t.prev,e)>=0:i.EarCut.area(t,e,t.prev)<0||i.EarCut.area(t,t.next,e)<0},i.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},i.EarCut.splitPolygon=function(t,e){var s=new i.EarCut.Node(t.i,t.x,t.y),n=new i.EarCut.Node(e.i,e.x,e.y),r=t.next,o=e.prev;return t.next=e,e.prev=t,s.next=r,r.prev=s,n.next=s,s.prev=n,o.next=n,n.prev=o,n},i.EarCut.insertNode=function(t,e,s,n){var r=new i.EarCut.Node(t,e,s);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r},i.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},i.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var s,n=e.gl,r=e.projection,o=e.offset,a=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,n);var h=t._webGL[n.id];if(h)for(var l=0;l=PIXI.WebGLGraphics.stencilBufferLimit&&(a.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit?(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildPoly(a,o)||(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))),a.lineWidth>0&&(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildLine(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,0),a.type===i.RECTANGLE?PIXI.WebGLGraphics.buildRectangle(a,o):a.type===i.CIRCLE||a.type===i.ELLIPSE?PIXI.WebGLGraphics.buildCircle(a,o):a.type===i.ROUNDEDRECTANGLE&&PIXI.WebGLGraphics.buildRoundedRectangle(a,o)),s.lastIndex++}for(n=0;n19600?(_=y-x,w=v-b,_/=R=Math.sqrt(_*_+w*w),w/=R,_*=F,w*=F,L.push(p-_,f-w),L.push(G,N,X,U),L.push(p+_,f+w),L.push(G,N,X,U),L.push(p-_,f-w),L.push(G,N,X,U),O++):(L.push(l,c),L.push(G,N,X,U),L.push(p-(l-p),f-(c-f)),L.push(G,N,X,U));for(u=n[2*(I-2)],d=n[2*(I-2)+1],p=n[2*(I-1)],y=-(d-(f=n[2*(I-1)+1])),v=u-p,y/=R=Math.sqrt(y*y+v*v),v/=R,y*=F,v*=F,L.push(p-y,f-v),L.push(G,N,X,U),L.push(p+y,f+v),L.push(G,N,X,U),B.push(k),s=0;sh?r:h,l=oc?o:c;s.push(a,l,h,l,h,c,a,c);var d=s.length/2;for(u=0;uS?S:C,e.beginPath(),e.moveTo(_,w+C),e.lineTo(_,w+P-C),e.quadraticCurveTo(_,w+P,_+C,w+P),e.lineTo(_+T-C,w+P),e.quadraticCurveTo(_+T,w+P,_+T,w+P-C),e.lineTo(_+T,w+C),e.quadraticCurveTo(_+T,w,_+T-C,w),e.lineTo(_+C,w),e.quadraticCurveTo(_,w,_,w+C),e.closePath(),(r.fillColor||0===r.fillColor)&&(e.globalAlpha=r.fillAlpha*s,e.fillStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.fill()),r.lineWidth&&(e.globalAlpha=r.lineAlpha*s,e.strokeStyle="#"+("00000"+(0|h).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var s=t.graphicsData.length;if(0!==s){e.beginPath();for(var n=0;nP?P:T,e.moveTo(x,b+T),e.lineTo(x,b+w-T),e.quadraticCurveTo(x,b+w,x+T,b+w),e.lineTo(x+_-T,b+w),e.quadraticCurveTo(x+_,b+w,x+_,b+w-T),e.lineTo(x+_,b+T),e.quadraticCurveTo(x+_,b,x+_-T,b),e.lineTo(x+T,b),e.quadraticCurveTo(x,b,x,b+T),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},i.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},i.GraphicsData.prototype.constructor=i.GraphicsData,i.GraphicsData.prototype.clone=function(){return new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},i.Graphics=function(t,e,s){void 0===e&&(e=0),void 0===s&&(s=0),this.type=i.GRAPHICS,this.physicsType=i.SPRITE,this.anchor=new i.Point,PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new i.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1,i.Component.Core.init.call(this,t,e,s,"",null)},i.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Graphics.prototype.constructor=i.Graphics,i.Component.Core.install.call(i.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),i.Graphics.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Graphics.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Graphics.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Graphics.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Graphics.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Graphics.prototype.postUpdate=function(){i.Component.PhysicsBody.postUpdate.call(this),i.Component.FixedToCamera.postUpdate.call(this),this._boundsDirty&&(this.updateLocalBounds(),this._boundsDirty=!1);for(var t=0;t0&&this.drawPolygon(s)}else this.drawPolygon(s)},i.Graphics.prototype.drawTriangles=function(t,e,s){void 0===s&&(s=!1);var n,r=new i.Point,o=new i.Point,a=new i.Point,h=[];if(e)if(t[0]instanceof i.Point)for(n=0;nc*a)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var x=d+s+p*(v+y*v),b=Math.cos(x),_=-Math.sin(x);u.push((f*b+g*_)*i+t,(f*-_+g*b)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},i.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},i.Graphics.prototype.drawRect=function(t,e,s,n){return this.drawShape(new i.Rectangle(t,e,s,n)),this},i.Graphics.prototype.drawRoundedRect=function(t,e,s,n,r){return this.drawShape(new i.RoundedRectangle(t,e,s,n,r)),this},i.Graphics.prototype.drawCircle=function(t,e,s){return this.drawShape(new i.Circle(t,e,s)),this},i.Graphics.prototype.drawEllipse=function(t,e,s,n){return this.drawShape(new i.Ellipse(t,e,s,n)),this},i.Graphics.prototype.drawPolygon=function(t){t instanceof i.Polygon&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var s=0;sw?m:w,w=v>w?v:w,w=b>w?b:w,T=y>T?y:T,T=x>T?x:T,T=_>T?_:T,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=C,this._bounds.height=T-C,this._currentBounds=this._bounds,this._currentBounds},i.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;ee?a+l:e,s=hn?h+c:n;else if(p===i.CIRCLE)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else if(p===i.ELLIPSE)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else{o=r.points;for(var g=0;ge?a+f:e,s=h-fn?h+f:n}}else t=0,e=0,s=0,n=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=s-m,this._localBounds.height=n-s+2*m},i.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},i.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},i.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},i.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof i.Polygon&&(t=t.clone()).flatten();var e=new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===i.POLYGON&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(i.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),i.RenderTexture=function(t,e,s,n,r,o,a,h){if(void 0===e&&(e=100),void 0===s&&(s=100),void 0===n&&(n=""),void 0===r&&(r=i.scaleModes.DEFAULT),void 0===o&&(o=1),void 0===a&&(a=PIXI.defaultRenderer),void 0===h&&(h=0),this.game=t,this.key=n,this.type=i.RENDERTEXTURE,this._tempMatrix=new i.Matrix,this.width=e,this.height=s,this.resolution=o,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=this.frame.clone(),this.baseTexture=new PIXI.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=r,this.baseTexture.hasLoaded=!0,PIXI.Texture.call(this,this.baseTexture,this.frame.clone()),this.renderer=a,this.renderer.type===i.WEBGL){var l=this.renderer.gl;this.baseTexture.textureIndex=h,this.baseTexture._dirty[l.id]=!1,this.textureBuffer=new PIXI.FilterTexture(l,this.width,this.height,this.baseTexture.scaleMode,h),this.baseTexture._glTextures[l.id]=this.textureBuffer.texture,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.textureBuffer=new PIXI.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new i.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(PIXI.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.renderXY=function(t,e,s,n){t.updateTransform(),this._tempMatrix.copyFrom(t.worldTransform),this._tempMatrix.tx=e,this._tempMatrix.ty=s,this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.renderRawXY=function(t,e,s,n){this._tempMatrix.identity().translate(e,s),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.render=function(t,e,s){void 0===e||null===e?this._tempMatrix.copyFrom(t.worldTransform):this._tempMatrix.copyFrom(e),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,s):this._renderCanvas(t,this._tempMatrix,s)},i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype._renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n-1&&this.characterLimitSize0&&this.style.maxLines0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(e[a]):l+=this.context.measureText(e[a]).width,this.style.wordWrap&&(l-=this.context.measureText(" ").width)}else{var h=e[a].split(/(?:\t)/),l=this.padding.x+this.style.strokeThickness;if(Array.isArray(i))for(var c=0,u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.measureLine(h[u]):Math.ceil(this.context.measureText(h[u]).width),u>0&&(c+=i[u-1]),l=c+d}else for(u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(h[u]):l+=Math.ceil(this.context.measureText(h[u]).width),l+=this.game.math.snapToCeil(l,i)-l}s[a]=Math.ceil(l),n=Math.max(n,s[a])}this.canvas.width=n*this._res;var p=r.fontSize+this.style.strokeThickness+this.padding.y,f=p*o,g=this._lineSpacing;g<0&&Math.abs(g)>p&&(g=-p),0!==g&&(f+=g>0?g*e.length:g*(e.length-1)),this.canvas.height=f*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var m,y;for(this._charCount=0,a=0;a0&&(y+=g*a),"right"===this.style.align?m+=n-s[a]:"center"===this.style.align&&(m+=(n-s[a])/2),this.autoRound&&(m=Math.round(m),y=Math.round(y)),this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.updateLine(e[a],m,y):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===i?this.context.strokeText(e[a],m,y):this.renderTabLine(e[a],m,y,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===i?this.context.fillText(e[a],m,y):this.renderTabLine(e[a],m,y,!0)));this.updateTexture(),this.dirty=!1},i.Text.prototype.renderTabLine=function(t,e,i,s){var n=t.split(/(?:\t)/),r=this.style.tabs,o=0;if(Array.isArray(r))for(var a=0,h=0;h0&&(a+=r[h-1]),o=e+a,s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i);else for(h=0;h0||this.fontStyles.length>0){var n=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(n.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(n.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(n)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill)),e+=this.context.measureText(s).width,this._charCount++}return Math.ceil(e)},i.Text.prototype.updateLine=function(t,e,i){for(var s=0;s0||this.fontStyles.length>0){var r=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(r.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(r.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(r)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(n,e,i)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(n,e,i)),e+=this.context.measureText(n).width,this._charCount++}},i.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},i.Text.prototype.clearFontValues=function(){return this.fontStyles=[],this.fontWeights=[],this.dirty=!0,this},i.Text.prototype.addColor=function(t,e){return this.colors[e]=t,this.dirty=!0,this},i.Text.prototype.addStrokeColor=function(t,e){return this.strokeColors[e]=t,this.dirty=!0,this},i.Text.prototype.addFontStyle=function(t,e){return this.fontStyles[e]=t,this.dirty=!0,this},i.Text.prototype.addFontWeight=function(t,e){return this.fontWeights[e]=t,this.dirty=!0,this},i.Text.prototype.precalculateWordWrap=function(t){return this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font,this.runWordWrap(t).split(/(?:\r\n|\r|\n)/)},i.Text.prototype.runWordWrap=function(t){return this.useAdvancedWrap?this.advancedWordWrap(t):this.basicWordWrap(t)},i.Text.prototype.advancedWordWrap=function(t){for(var e=this.context,i=this.style.wordWrapWidth,s="",n=t.replace(/ +/gi," ").split(/\r?\n/gi),r=n.length,o=0;ol){if(0===u){for(var g=p;g.length&&(g=g.slice(0,-1),!((f=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var m=d.substr(g.length);c[u]=m,h+=g}var y=c[u].length?u:u+1,v=c.slice(y).join(" ").replace(/[ \n]*$/gi,"");n[o+1]=v+" "+(n[o+1]||""),r=n.length;break}h+=p,l-=f}s+=h.replace(/[ \n]*$/gi,"")+"\n"}}return s=s.replace(/[\s|\n]*$/gi,"")},i.Text.prototype.basicWordWrap=function(t){for(var e="",i=t.split("\n"),s=0;sn?(o>0&&(e+="\n"),e+=r[o]+" ",n=this.style.wordWrapWidth-a):(n-=h,e+=r[o]+" ")}ss&&(this.style.wordWrapWidth=s)),this.updateTexture(),this},i.Text.prototype.updateTexture=function(){var t=this.texture.baseTexture,e=this.texture.crop,i=this.texture.frame,s=this.canvas.width,n=this.canvas.height;if(t.width=s,t.height=n,e.width=s,e.height=n,i.width=s,i.height=n,this.texture.width=s,this.texture.height=n,this._width=s,this._height=n,this.textBounds){var r=this.textBounds.x,o=this.textBounds.y;"right"===this.style.boundsAlignH?r+=this.textBounds.width-this.canvas.width/this.resolution:"center"===this.style.boundsAlignH&&(r+=this.textBounds.halfWidth-this.canvas.width/this.resolution/2),"bottom"===this.style.boundsAlignV?o+=this.textBounds.height-this.canvas.height/this.resolution:"middle"===this.style.boundsAlignV&&(o+=this.textBounds.halfHeight-this.canvas.height/this.resolution/2),this.pivot.x=-r,this.pivot.y=-o}this.renderable=0!==s&&0!==n,this.texture.requiresReTint=!0,this.texture.baseTexture.dirty()},i.Text.prototype._renderWebGL=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.Text.prototype._renderCanvas=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.Text.prototype.determineFontProperties=function(t){var e=i.Text.fontPropertiesCache[t];if(!e){e={};var s=i.Text.fontPropertiesCanvas,n=i.Text.fontPropertiesContext;n.font=t;var r=Math.ceil(n.measureText("|MÉq").width),o=Math.ceil(n.measureText("|MÉq").width),a=2*o;if(o=1.4*o|0,s.width=r,s.height=a,n.fillStyle="#f00",n.fillRect(0,0,r,a),n.font=t,n.textBaseline="alphabetic",n.fillStyle="#000",n.fillText("|MÉq",0,o),!n.getImageData(0,0,r,a))return e.ascent=o,e.descent=o+6,e.fontSize=e.ascent+e.descent,i.Text.fontPropertiesCache[t]=e,e;var h,l,c=n.getImageData(0,0,r,a).data,u=c.length,d=4*r,p=0,f=!1;for(h=0;ho;h--){for(l=0;l0?this._maxWidth:null,l=[],c=0;c=h&&r>-1)return{width:o||n,text:i.substr(0,c-(c-r)),end:!1,chars:l};n+=(p.xAdvance+g)*e,l.push(s+(p.xOffset+g)*e),s+=(p.xAdvance+g)*e,a=d}return{width:n,text:i,end:u,chars:l}},i.BitmapText.prototype.cleanText=function(t,e){void 0===e&&(e="");var i=this._data.font;if(!i)return"";for(var s=/\r\n|\n\r|\n|\r/g,n=t.replace(s,"\n").split("\n"),r=0;rthis.textWidth&&(this.textWidth=c.width),n+=t.lineHeight*i,e=e.substr(c.text.length+1)}while(!1===c.end);this.textHeight=n;for(var r=0,o=0,a=this.textWidth*this.anchor.x,h=this.textHeight*this.anchor.y,l=0;l0&&(this._fontSize=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"smoothed",{get:function(){return!this._data.base.scaleMode},set:function(t){this._data.base.scaleMode=t?0:1,this._data.base.dirty()}}),i.RetroFont=function(t,e,s,n,r,o,a,h,l,c){if(!t.cache.checkImageKey(e))return!1;void 0!==o&&null!==o||(o=t.cache.getImage(e).width/s),this.characterWidth=s,this.characterHeight=n,this.characterSpacingX=a||0,this.characterSpacingY=h||0,this.characterPerRow=o,this.offsetX=l||0,this.offsetY=c||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=t.cache.getImage(e),this._text="",this.grabData=[],this.frameData=new i.FrameData;for(var u=this.offsetX,d=this.offsetY,p=0,f=0;f?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",i.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",i.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",i.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",i.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",i.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",i.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",i.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",i.RetroFont.prototype.setFixedWidth=function(t,e){void 0===e&&(e="left"),this.fixedWidth=t,this.align=e},i.RetroFont.prototype.setText=function(t,e,i,s,n,r){this.multiLine=e||!1,this.customSpacingX=i||0,this.customSpacingY=s||0,this.align=n||"left",this.autoUpperCase=!r,t.length>0&&(this.text=t)},i.RetroFont.prototype.buildRetroFontText=function(){var t=0,e=0;if(this.clear(),this.multiLine){var s=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var n=0;n0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),t=0,this.align===i.RetroFont.ALIGN_RIGHT?t=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===i.RetroFont.ALIGN_CENTER&&(t=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(this._text,t,0,this.customSpacingX);this.requiresReTint=!0},i.RetroFont.prototype.pasteLine=function(t,e,i,s){for(var n=0;n=0&&(this.stamp.frame=this.grabData[t.charCodeAt(n)],this.renderXY(this.stamp,e,i,!1),(e+=this.characterWidth+s)>this.width))break},i.RetroFont.prototype.getLongestLine=function(){var t=0;if(this._text.length>0)for(var e=this._text.split("\n"),i=0;it&&(t=e[i].length);return t},i.RetroFont.prototype.removeUnsupportedCharacters=function(t){for(var e="",i=0;i=0||!t&&"\n"===s)&&(e=e.concat(s))}return e},i.RetroFont.prototype.updateOffset=function(t,e){if(this.offsetX!==t||this.offsetY!==e){for(var i=t-this.offsetX,s=e-this.offsetY,n=this.game.cache.getFrameData(this.stamp.key).getFrames(),r=n.length;r--;)n[r].x+=i,n[r].y+=s;this.buildRetroFontText()}},Object.defineProperty(i.RetroFont.prototype,"text",{get:function(){return this._text},set:function(t){var e;(e=this.autoUpperCase?t.toUpperCase():t)!==this._text&&(this._text=e,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(i.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(t){this.stamp.smoothed=t,this.buildRetroFontText()}}),i.Rope=function(t,e,s,n,r,o){this.points=o||[],this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.ROPE,PIXI.DisplayObjectContainer.call(this),this.texture=i.Cache.DEFAULT,this.uvs=new Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new Float32Array([0,0,100,0,100,100,0,100]),this.colors=new Float32Array([1,1,1,1]),this.indices=new Uint16Array([0,1,2,3]),o&&(this.vertices=new Float32Array(4*o.length),this.uvs=new Float32Array(4*o.length),this.colors=new Float32Array(2*o.length),this.indices=new Uint16Array(2*o.length)),this.dirty=!0,this.canvasPadding=0,this.drawMode=i.Rope.TRIANGLE_STRIP,i.Component.Core.init.call(this,t,e,s,n,r),this.refresh()},i.Rope.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Rope.prototype.constructor=i.Rope,i.Component.Core.install.call(i.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Rope.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Rope.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Rope.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Rope.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Rope.TRIANGLE_STRIP=0,i.Rope.TRIANGLES=1,i.Rope.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},i.Rope.prototype.reset=function(t,e){return i.Component.Reset.prototype.reset.call(this,t,e),this},i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=this.indices,s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o=t.length,a=1;a1&&1,o=Math.sqrt(s.x*s.x+s.y*s.y),a=this.texture.height/2,s.x/=o,s.y/=o,s.x*=a,s.y*=a,h[r]=n.x+s.x,h[r+1]=n.y+s.y,h[r+2]=n.x-s.x,h[r+3]=n.y-s.y,i=n;PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.Rope.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Rope.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Rope.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Rope.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Rope.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Rope.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Rope.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n0){var _=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,T=(l+c+u)/3,P=(d+p+f)/3,C=l-T,S=d-P,A=Math.sqrt(C*C+S*S);l=T+C/A*(A+_),d=P+S/A*(A+w),S=p-P,c=T+(C=c-T)/(A=Math.sqrt(C*C+S*S))*(A+_),p=P+S/A*(A+w),S=f-P,u=T+(C=u-T)/(A=Math.sqrt(C*C+S*S))*(A+_),f=P+S/A*(A+w)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*x+v*y+m*b-x*y-v*m-g*b,M=l*x+v*u+c*b-x*u-v*c-l*b,R=g*c+l*y+m*u-c*y-l*m-g*u,L=g*x*u+v*c*y+l*m*b-l*x*y-v*m*u-g*c*b,B=d*x+v*f+p*b-x*f-v*p-d*b,I=g*p+d*y+m*f-p*y-d*m-g*f,O=g*x*f+v*p*y+d*m*b-d*x*y-v*m*f-g*p*b;t.transform(M/E,B/E,R/E,I/E,L/E,O/E),t.drawImage(o,0,0),t.restore()},i.Rope.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;nh?m:h,l=y>l?y:l}if(c===-1/0||l===1/0)return PIXI.EmptyRectangle;var v=this._bounds;return v.x=c,v.width=h-c,v.y=u,v.height=l-u,this._currentBounds=v,v},Object.defineProperty(i.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(t){t&&"function"==typeof t?(this._hasUpdateAnimation=!0,this._updateAnimation=t):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(i.Rope.prototype,"segments",{get:function(){for(var t,e,s,n,r,o,a,h,l=[],c=0;c(_=y>(_=g>(_=p>_?p:_)?g:_)?y:_)?x:_,w=b>(w=v>(w=m>(w=f>w?f:w)?m:w)?v:w)?b:w;var C=this._bounds;return C.x=T,C.width=_-T,C.y=P,C.height=w-P,this._currentBounds=C,C},Object.defineProperty(i.TileSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TileSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var e=parseInt(RegExp.$1,10),i=parseInt(RegExp.$2,10);(10===e&&i>=11||e>10)&&(s.dolby=!0)}}catch(t){}}(),function(){var t=document.createElement("video");try{!!t.canPlayType&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(s.oggVideo=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.h264Video=!0,s.mp4Video=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(s.webmVideo=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(s.vp9Video=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.hlsVideo=!0))}catch(t){}}(),function(){var t,e=document.createElement("p"),i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var n in i)void 0!==e.style[n]&&(e.style[n]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(i[n]));document.body.removeChild(e),s.css3D=void 0!==t&&t.length>0&&"none"!==t}(),s.pixelRatio=window.devicePixelRatio||1,s.iPhone=-1!==navigator.userAgent.toLowerCase().indexOf("iphone"),s.iPhone4=2===s.pixelRatio&&s.iPhone,s.iPad=-1!==navigator.userAgent.toLowerCase().indexOf("ipad"),"undefined"!=typeof Int8Array?s.typedArray=!0:s.typedArray=!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(s.littleEndian=t(),s.LITTLE_ENDIAN=s.littleEndian),s.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==s.littleEndian&&e(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(s.vibration=!0),function(){s.canvas=!!window.CanvasRenderingContext2D||s.cocoonJS;try{s.localStorage=!!localStorage.getItem}catch(t){s.localStorage=!1}s.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),s.fileSystem=!!window.requestFileSystem,s.webGL=!!window.WebGLRenderingContext,s.worker=!!window.Worker,s.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,s.quirksMode="CSS1Compat"!==document.compatMode,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,s.getUserMedia=s.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,s.firefox&&s.firefoxVersion<21&&(s.getUserMedia=!1),!s.iOS&&(s.ie||s.firefox||s.chrome)&&(s.canvasBitBltShift=!0),(s.safari||s.mobileSafari)&&(s.canvasBitBltShift=!1)}(),function(){var t=i.CanvasPool.create(this,6,1),e=t.getContext("2d");e.fillStyle="rgba(10, 20, 30, 0.5)",e.fillRect(0,0,1,1);var n=e.getImageData(0,0,1,1);if(n){e.putImageData(n,1,0);var r=e.getImageData(1,0,1,1);s.canHandleAlpha=r.data[0]===n.data[0]&&r.data[1]===n.data[1]&&r.data[2]===n.data[2]&&r.data[3]===n.data[3]}e.globalCompositeOperation="multiply",s.canUseMultiply="multiply"===e.globalCompositeOperation,i.CanvasPool.removeByCanvas(t),PIXI.CanvasTinter.tintMethod=s.canUseMultiply?PIXI.CanvasTinter.tintWithMultiply:PIXI.CanvasTinter.tintWithPerPixel}(),function(){for(var t=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],e=document.createElement("div"),i=0;i=1)&&(s.touch=!0),(window.PointerEvent||window.MSPointerEvent||window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(s.mspointer=!0),s.cocoonJS||("onwheel"in window||s.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":s.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"))},i.Device.canPlayAudio=function(t){return!("mp3"!==t||!this.mp3)||(!("ogg"!==t||!this.ogg&&!this.opus)||(!("m4a"!==t||!this.m4a)||(!("opus"!==t||!this.opus)||(!("wav"!==t||!this.wav)||(!("webm"!==t||!this.webm)||!("mp4"!==t||!this.dolby))))))},i.Device.canPlayVideo=function(t){return!("webm"!==t||!this.webmVideo&&!this.vp9Video)||(!("mp4"!==t||!this.mp4Video&&!this.h264Video)||(!("ogg"!==t&&"ogv"!==t||!this.oggVideo)||!("mpeg"!==t||!this.hlsVideo)))},i.Device.needsTouchUnlock=function(){return!!(!this.cocoonJS&&(this.iOS||this.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)},i.Device.isAndroidStockBrowser=function(){var t=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return t&&t[1]<537},i.Canvas={create:function(t,e,s,n,r){e=e||256,s=s||256;var o=r?document.createElement("canvas"):i.CanvasPool.create(t,e,s);return"string"==typeof n&&""!==n&&(o.id=n),o.width=e,o.height=s,o.style.display="block",o},setBackgroundColor:function(t,e){return e=e||"rgb(0,0,0)",t.style.backgroundColor=e,t},setTouchAction:function(t,e){return e=e||"none",t.style.msTouchAction=e,t.style["ms-touch-action"]=e,t.style["touch-action"]=e,t},setUserSelect:function(t,e){return e=e||"none",t.style["-webkit-touch-callout"]=e,t.style["-webkit-user-select"]=e,t.style["-khtml-user-select"]=e,t.style["-moz-user-select"]=e,t.style["-ms-user-select"]=e,t.style["user-select"]=e,t.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",t},addToDOM:function(t,e,i){var s;return void 0===i&&(i=!0),e&&("string"==typeof e?s=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(s=e)),s||(s=document.body),i&&s.style&&(s.style.overflow="hidden"),s.appendChild(t),t},removeFromDOM:function(t){t.parentNode&&t.parentNode.removeChild(t)},setTransform:function(t,e,i,s,n,r,o){return t.setTransform(s,r,o,n,e,i),t},setSmoothingEnabled:function(t,e){var s=i.Canvas.getSmoothingPrefix(t);return s&&(t[s]=e),t},getSmoothingPrefix:function(t){var e=["i","webkitI","msI","mozI","oI"];for(var i in e){var s=e[i]+"mageSmoothingEnabled";if(s in t)return s}return null},getSmoothingEnabled:function(t){var e=i.Canvas.getSmoothingPrefix(t);if(e)return t[e]},setImageRenderingCrisp:function(t){for(var e=["-webkit-optimize-contrast","-moz-crisp-edges","crisp-edges","pixelated"],i=0;i0&&0==(t&t-1))return t;for(var e=1;e0&&0==(t&t-1)&&e>0&&0==(e&e-1)},random:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return Math.random()*(e-t)+t},between:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t},fuzzyEqual:function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)e-i},fuzzyCeil:function(t,e){return void 0===e&&(e=1e-4),Math.ceil(t-e)},fuzzyFloor:function(t,e){return void 0===e&&(e=1e-4),Math.floor(t+e)},average:function(){for(var t=0,e=arguments.length,i=0;i=i.Math.PI2-s?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=s:e=0?t:t+2*Math.PI},maxAdd:function(t,e,i){return Math.min(t+e,i)},minSub:function(t,e,i){return Math.max(t-e,i)},wrap:function(t,e,i){var s=i-e;if(s<=0)return 0;var n=(t-e)%s;return n<0&&(n+=s),n+e},wrapValue:function(t,e,i){return t=Math.abs(t),e=Math.abs(e),i=Math.abs(i),(t+e)%i},isOdd:function(t){return!!(1&t)},isEven:function(t){return!(1&t)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;et[i]&&(i=e);return t[i]},minProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;ie[s][t]&&(s=i);return e[s][t]},wrapAngle:function(t,e){return e?this.wrap(t,-Math.PI,Math.PI):this.wrap(t,-180,180)},linearInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return e<0?this.linear(t[0],t[1],s):e>1?this.linear(t[i],t[i-1],i-s):this.linear(t[n],t[n+1>i?i:n+1],s-n)},bezierInterpolation:function(t,e){for(var i=0,s=t.length-1,n=0;n<=s;n++)i+=Math.pow(1-e,s-n)*Math.pow(e,n)*t[n]*this.bernstein(s,n);return i},catmullRomInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return t[0]===t[i]?(e<0&&(n=Math.floor(s=i*(1+e))),this.catmullRom(t[(n-1+i)%i],t[n],t[(n+1)%i],t[(n+2)%i],s-n)):e<0?t[0]-(this.catmullRom(t[0],t[0],t[1],t[1],-s)-t[0]):e>1?t[i]-(this.catmullRom(t[i],t[i],t[i-1],t[i-1],s-i)-t[i]):this.catmullRom(t[n?n-1:0],t[n],t[i0?Math.ceil(t):Math.floor(t)},sinCosGenerator:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1);for(var n=e,r=i,o=s*Math.PI/t,a=[],h=[],l=0;l0?1:0},percent:function(t,e,i){return void 0===i&&(i=0),t>e||i>e?1:tt?0:(t-i)/e}},i.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},i.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e>>0,s=(e*=s)>>>0,s+=4294967296*(e-=s);return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},i.RandomDataGenerator.prototype.constructor=i.RandomDataGenerator,i.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},i.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new i.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new i.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new i.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new i.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null==this.nodes[0]||-1===(e=this.getIndex(t))){if(this.objects.push(t),this.objects.length>this.maxObjects&&this.levelthis.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.ythis.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof i.Rectangle)var e=this.objects,s=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,s=this.getIndex(t.body)}return this.nodes[0]&&(e=-1!==s?e.concat(this.nodes[s].retrieve(t)):(e=(e=(e=e.concat(this.nodes[0].retrieve(t))).concat(this.nodes[1].retrieve(t))).concat(this.nodes[2].retrieve(t))).concat(this.nodes[3].retrieve(t))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},i.QuadTree.prototype.constructor=i.QuadTree,i.Net=function(t){this.game=t},i.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},i.Net.prototype.constructor=i.Net,i.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:i.Easing.Power0,Power1:i.Easing.Power1,Power2:i.Easing.Power2,Power3:i.Easing.Power3,Power4:i.Easing.Power4,Linear:i.Easing.Linear.None,Quad:i.Easing.Quadratic.Out,Cubic:i.Easing.Cubic.Out,Quart:i.Easing.Quartic.Out,Quint:i.Easing.Quintic.Out,Sine:i.Easing.Sinusoidal.Out,Expo:i.Easing.Exponential.Out,Circ:i.Easing.Circular.Out,Elastic:i.Easing.Elastic.Out,Back:i.Easing.Back.Out,Bounce:i.Easing.Bounce.Out,"Quad.easeIn":i.Easing.Quadratic.In,"Cubic.easeIn":i.Easing.Cubic.In,"Quart.easeIn":i.Easing.Quartic.In,"Quint.easeIn":i.Easing.Quintic.In,"Sine.easeIn":i.Easing.Sinusoidal.In,"Expo.easeIn":i.Easing.Exponential.In,"Circ.easeIn":i.Easing.Circular.In,"Elastic.easeIn":i.Easing.Elastic.In,"Back.easeIn":i.Easing.Back.In,"Bounce.easeIn":i.Easing.Bounce.In,"Quad.easeOut":i.Easing.Quadratic.Out,"Cubic.easeOut":i.Easing.Cubic.Out,"Quart.easeOut":i.Easing.Quartic.Out,"Quint.easeOut":i.Easing.Quintic.Out,"Sine.easeOut":i.Easing.Sinusoidal.Out,"Expo.easeOut":i.Easing.Exponential.Out,"Circ.easeOut":i.Easing.Circular.Out,"Elastic.easeOut":i.Easing.Elastic.Out,"Back.easeOut":i.Easing.Back.Out,"Bounce.easeOut":i.Easing.Bounce.Out,"Quad.easeInOut":i.Easing.Quadratic.InOut,"Cubic.easeInOut":i.Easing.Cubic.InOut,"Quart.easeInOut":i.Easing.Quartic.InOut,"Quint.easeInOut":i.Easing.Quintic.InOut,"Sine.easeInOut":i.Easing.Sinusoidal.InOut,"Expo.easeInOut":i.Easing.Exponential.InOut,"Circ.easeInOut":i.Easing.Circular.InOut,"Elastic.easeInOut":i.Easing.Elastic.InOut,"Back.easeInOut":i.Easing.Back.InOut,"Bounce.easeInOut":i.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},i.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t,e){return e||(e=!1),this._tweens.some(function(i){return i.target===t&&(!e||i.isRunning&&!i.pendingDelete)})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},i.TweenManager.prototype.constructor=i.TweenManager,i.Tween=function(t,e,s){this.game=e,this.target=t,this.manager=s,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new i.Signal,this.onLoop=new i.Signal,this.onRepeat=new i.Signal,this.onChildComplete=new i.Signal,this.onComplete=new i.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=s.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},i.Tween.updateColor=function(t){i.Color.updateColor(t.target)},i.Tween.prototype={to:function(t,e,s,n,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).to(t,e,s,r,o,a)),n&&this.start(),this)},from:function(t,e,s,n,r,o,a){return void 0===e&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).from(t,e,s,r,o,a)),n&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),this.pendingDelete)return console.warn("Phaser.Tween.start cannot be called after Tween.stop"),this;if(null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(i=0;ithis.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(s=0;s0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t=this.startTime))return i.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var s in this.vEnd){var n=this.vStart[s],r=this.vEnd[s];Array.isArray(r)?this.parent.target[s]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[s]=n+(r-n)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():i.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction.call(this.interpolationContext,a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,i.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return i.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,i.TweenData.LOOPED}},i.TweenData.prototype.constructor=i.TweenData,i.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-i.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*i.Easing.Bounce.In(2*t):.5*i.Easing.Bounce.Out(2*t-1)+.5}}},i.Easing.Default=i.Easing.Linear.None,i.Easing.Power0=i.Easing.Linear.None,i.Easing.Power1=i.Easing.Quadratic.Out,i.Easing.Power2=i.Easing.Cubic.Out,i.Easing.Power3=i.Easing.Quartic.Out,i.Easing.Power4=i.Easing.Quintic.Out,i.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.updates=0,this.renders=0,this.fps=0,this.ups=0,this.rps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new i.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},i.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new i.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3){var t=this.now-this._timeLastSecond;this.fps=Math.round(1e3*this.frames/t),this.ups=Math.round(1e3*this.updates/t),this.rps=Math.round(1e3*this.renders/t),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0,this.updates=0,this.renders=0}},countUpdate:function(){this.advancedTiming&&this.updates++},countRender:function(){this.advancedTiming&&this.renders++},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(i.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),i.Time.prototype.constructor=i.Time,i.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new i.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},i.Timer.MINUTE=6e4,i.Timer.SECOND=1e3,i.Timer.HALF=500,i.Timer.QUARTER=250,i.Timer.prototype={create:function(t,e,s,n,r,o){var a=t=Math.round(t);0===this._now?a+=this.game.time.time:a+=this._now;var h=new i.TimerEvent(this,t,a,s,e,n,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.ticke.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i=e.tick)||e.pendingDelete)break;this._newTick=this._now+e.delay-(this._now-e.tick),this._newTick<0&&(this._newTick=this._now+e.delay),!0===e.loop?(e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):e.repeatCount>0?(e.repeatCount--,e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):(this._marked++,e.pendingDelete=!0,e.callback.apply(e.callbackContext,e.args)),this._i++}this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;ethis._now?this.nextTick-this._now:0}}),Object.defineProperty(i.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(i.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(i.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),i.Timer.prototype.constructor=i.Timer,i.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},i.TimerEvent.prototype.constructor=i.TimerEvent,i.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},i.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,s,n,r){return e=e||[],s=s||60,void 0===n&&(n=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new i.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,s,n),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;ithis._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},i.AnimationManager.prototype.constructor=i.AnimationManager,Object.defineProperty(i.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(i.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(i.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(i.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(i.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){var e;"number"==typeof t&&this._frameData&&(e=this._frameData.getFrame(t))&&(this.currentFrame=e,this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(i.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){var e;"string"==typeof t&&this._frameData&&(e=this._frameData.getFrameByName(t))?(this.currentFrame=e,this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame)):console.warn("Cannot set frameName: "+t)}}),i.Animation=function(t,e,s,n,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=n,this.name=s,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new i.Signal,this.onUpdate=null,this.onComplete=new i.Signal,this.onLoop=new i.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},i.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(s=0;s=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay?(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay):this._frameDiff=0,this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(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=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},i.Animation.prototype.constructor=i.Animation,Object.defineProperty(i.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(i.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(i.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(i.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(i.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(i.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new i.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),i.Animation.generateFrameNames=function(t,e,s,n,r){void 0===n&&(n="");var o=[],a="";if(e=s;h--)a=t+(a="number"==typeof r?i.Utils.pad(h.toString(),r,"0",1):h.toString())+n,o.push(a);return o},i.Frame=function(t,e,s,n,r,o){this.index=t,this.x=e,this.y=s,this.width=n,this.height=r,0!==this.width&&0!==this.height||console.warn('Phaser.Frame: Frame "'+this.name+'" has a width or height of zero'),this.name=o,this.centerX=Math.floor(n/2),this.centerY=Math.floor(r/2),this.distance=i.Math.distance(0,0,n,r),this.rotated=!1,this.trimmed=!1,this.sourceSizeW=n,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},i.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=i.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new i.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new i.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},i.Frame.prototype.constructor=i.Frame,i.FrameData=function(){this._frames=[],this._frameNames=[]},i.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new i.FrameData,e=0;ed||h<-d)return console.warn("Phaser.AnimationParser.spriteSheet: skipFrames = "+h.toString()+" is larger than total sprite number "+d.toString()),null;if(h<0&&(h=d+h),-1!==r&&(d=h+r),0===c||0===u||cc&&(f=o,g+=n+a);return p},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var s,n=new i.FrameData,r=e.frames,o=0;o tag")}},i.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{},compressedTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new i.Signal,this._cacheMap=[],this._cacheMap[i.Cache.CANVAS]=this._cache.canvas,this._cacheMap[i.Cache.IMAGE]=this._cache.image,this._cacheMap[i.Cache.TEXTURE]=this._cache.texture,this._cacheMap[i.Cache.SOUND]=this._cache.sound,this._cacheMap[i.Cache.TEXT]=this._cache.text,this._cacheMap[i.Cache.PHYSICS]=this._cache.physics,this._cacheMap[i.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[i.Cache.BINARY]=this._cache.binary,this._cacheMap[i.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[i.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[i.Cache.JSON]=this._cache.json,this._cacheMap[i.Cache.XML]=this._cache.xml,this._cacheMap[i.Cache.VIDEO]=this._cache.video,this._cacheMap[i.Cache.SHADER]=this._cache.shader,this._cacheMap[i.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this._pendingCount=0,this.onReady=new i.Signal,this._addImages()},i.Cache.CANVAS=1,i.Cache.IMAGE=2,i.Cache.TEXTURE=3,i.Cache.SOUND=4,i.Cache.TEXT=5,i.Cache.PHYSICS=6,i.Cache.TILEMAP=7,i.Cache.BINARY=8,i.Cache.BITMAPDATA=9,i.Cache.BITMAPFONT=10,i.Cache.JSON=11,i.Cache.XML=12,i.Cache.VIDEO=13,i.Cache.SHADER=14,i.Cache.RENDER_TEXTURE=15,i.Cache.DEFAULT=null,i.Cache.DEFAULT_KEY="__default",i.Cache.DEFAULT_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==",i.Cache.MISSING=null,i.Cache.MISSING_KEY="__missing",i.Cache.MISSING_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==",i.Cache.READY_TIMEOUT=1e3,i.Cache.prototype={addCompressedTextureMetaData:function(t,e,s,n){this.checkImageKey(t)&&this.removeImage(t);var r=s in i.LoaderParser?i.LoaderParser[s](n):n,o={key:t,url:e,data:r,base:new PIXI.BaseTexture(r,null,this.game.resolution),frame:new i.Frame(0,0,0,r.width,r.height,t),frameData:new i.FrameData,fileFormat:s};return o.frameData.addFrame(new i.Frame(0,0,0,r.width,r.height,e)),this._cache.image[t]=o,this._resolveURL(e,o),o},addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,s){this.checkImageKey(t)&&this.removeImage(t),!1===s.complete&&console.warn('Phaser.Cache.addImage: Image "'+t+"\" hasn't been retrieved yet");var n={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution),frame:new i.Frame(0,0,0,s.width,s.height,t),frameData:new i.FrameData};return n.frameData.addFrame(new i.Frame(0,0,0,s.width,s.height,e)),this._cache.image[t]=n,this._resolveURL(e,n),"__default"===t?i.Cache.DEFAULT=new PIXI.Texture(n.base):"__missing"===t&&(i.Cache.MISSING=new PIXI.Texture(n.base)),n},addImageAsync:function(t,e,i){var s=this,n=new Image;n.onload=function(){i.call(this,s.addImage(t,null,n)),s._removePending(),n.onload=null},this._addPending(),n.src=e},addDefaultImage:function(){this.addImageAsync(i.Cache.DEFAULT_KEY,i.Cache.DEFAULT_SRC,function(t){t.base.skipRender=!0,i.Cache.DEFAULT=new PIXI.Texture(t.base)})},addMissingImage:function(){this.addImageAsync(i.Cache.MISSING_KEY,i.Cache.MISSING_SRC,function(t){i.Cache.MISSING=new PIXI.Texture(t.base)})},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,s){return e.key=t,void 0===s&&(s=new i.FrameData).addFrame(e.textureFrame),this._cache.bitmapData[t]={data:e,frameData:s},e},addBitmapFont:function(t,e,s,n,r,o,a){var h={url:e,data:s,font:null,base:new PIXI.BaseTexture(s,null,this.game.resolution)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?i.LoaderParser.jsonBitmapFont(n,h.base,o,a,!1,this.game.resolution):i.LoaderParser.xmlBitmapFont(n,h.base,o,a,!1,this.game.resolution),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addBitmapFontFromAtlas:function(t,e,s,n,r,o,a){var h=this.getFrameByName(e,s);if(h){var l={font:null,base:this.getBaseTexture(e),frame:h};void 0===o&&(o=0),void 0===a&&(a=0);var c;"json"===r?(c=this.getJSON(n),l.font=i.LoaderParser.jsonBitmapFont(c,l.base,o,a,h,this.game.resolution)):(c=this.getXML(n),l.font=i.LoaderParser.xmlBitmapFont(c,l.base,o,a,h,this.game.resolution)),this._cache.bitmapFont[t]=l}},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new i.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,s,n,r,o,a,h,l){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var c={key:t,url:e,data:s,frameWidth:n,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(s,null,this.game.resolution),frameData:i.AnimationParser.spriteSheet(this.game,s,n,r,o,a,h,l)};this._cache.image[t]=c,this._resolveURL(e,c)},addTextureAtlas:function(t,e,s,n,r){var o={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution)};r===i.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=i.AnimationParser.XMLData(this.game,n,t):r===i.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=i.AnimationParser.JSONDataPyxel(this.game,n,t):Array.isArray(n.frames)?o.frameData=i.AnimationParser.JSONData(this.game,n,t):o.frameData=i.AnimationParser.JSONDataHash(this.game,n,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(i.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(i.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(i.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(i.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(i.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(i.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(i.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(i.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(i.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(i.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(i.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(i.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(i.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(i.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(i.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,i.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var s=this.getItem(t,i.Cache.IMAGE,"getImage");return null===s&&(s=this.getItem("__missing",i.Cache.IMAGE,"getImage")),e?s:s.data},getTextureFrame:function(t){return this.getItem(t,i.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,i.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,i.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,i.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,s){var n=this.getItem(t,i.Cache.PHYSICS,"getPhysicsData","data");if(null===n||void 0===e||null===e)return n;if(n[e]){var r=n[e];if(!r||!s)return r;for(var o in r)if((o=r[o]).fixtureKey===s)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+s+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,i.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,i.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,i.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,i.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var s=this.getItem(t,i.Cache.JSON,"getJSON","data");return s?e?i.Utils.extend(!0,Array.isArray(s)?[]:{},s):s:null},getXML:function(t){return this.getItem(t,i.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,i.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,i.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,i.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,s){void 0===s&&(s=i.Cache.IMAGE),this._cacheMap[s][t]&&(this._cacheMap[s][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){return(t=this._resolveURL(t))?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=i.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var s in this._cacheMap[t])"__default"!==s&&"__missing"!==s&&e.push(s);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.image[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t0?setTimeout(function(){t.isReady||(console.warn("Phaser.Cache: Still waiting for images after %s ms.",e),t._ready())},i.Cache.READY_TIMEOUT):this._ready()},_addPending:function(){this._pendingCount+=1},_removePending:function(){this._pendingCount-=1,this._checkReady()},_checkReady:function(){this.isReady&&this._ready()},_ready:function(){this._pendingCount=0,this.onReady.dispatch(this)}},i.Cache.prototype.constructor=i.Cache,Object.defineProperty(i.Cache.prototype,"isReady",{get:function(){return this._pendingCount<=0}}),i.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new i.Signal,this.onLoadComplete=new i.Signal,this.onPackComplete=new i.Signal,this.onFileStart=new i.Signal,this.onFileComplete=new i.Signal,this.onFileError=new i.Signal,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},i.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,i.Loader.TEXTURE_ATLAS_JSON_HASH=1,i.Loader.TEXTURE_ATLAS_XML_STARLING=2,i.Loader.PHYSICS_LIME_CORONA_JSON=3,i.Loader.PHYSICS_PHASER_JSON=4,i.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,i.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new i.Rectangle(0,0,1,t.height):new i.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r=e||t&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var n=this;setTimeout(function(){n.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.reset(),this.onLoadComplete.dispatch(),this.game.state&&this.game.state.loadComplete())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(e)for(var s=0;s=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},getVideoURL:function(t){for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s="error loading asset from URL "+(t.requestUrl||this.transformUrl(t.url,t));!i&&e&&(i=e.status),i&&(s=s+" ("+i+")"),this.asyncComplete(t,s)},fileComplete:function(t,e){var s=!0;switch(t.type){case"packfile":r=JSON.parse(e.responseText);t.data=r||{};break;case"texture":var n=/\.([^.]+)$/.exec(t.url.split("?",1)[0])[1].toLowerCase();null!==t.data?this.cache.addCompressedTextureMetaData(t.key,t.url,n,t.data):this.cache.addCompressedTextureMetaData(t.key,t.url,n,e.response);break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing,t.skipFrames);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(s=!1,t.format===i.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===i.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===i.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==i.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(s=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var r=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,r,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}s&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else(e=new ActiveXObject("Microsoft.XMLDOM")).async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(i.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return i.Math.clamp(t||0,0,100)}}),Object.defineProperty(i.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),i.Loader.prototype.constructor=i.Loader,i.LoaderParser={bitmapFont:function(t,e,i,s,n,r){return this.xmlBitmapFont(t,e,i,s,n,r)},xmlBitmapFont:function(t,e,i,s,n,r){null==r&&(r=1);var o={},a=t.getElementsByTagName("info")[0],h=t.getElementsByTagName("common")[0];o.font=a.getAttribute("face"),o.size=parseInt(a.getAttribute("size"),10),o.lineHeight=parseInt(h.getAttribute("lineHeight"),10)+s,o.chars={};for(var l=t.getElementsByTagName("char"),c=n?n.x:0,u=n?n.y:0,d=0;d=0){switch(r>=0&&r<=3?e="PVRTC":r>=7&&r<=11?e="S3TC":6===r&&(e="ETC1"),r){case 0:o=35841;break;case 1:o=35843;break;case 2:o=35840;break;case 3:o=35842;break;case 6:o=36196;break;case 7:o=33777;break;case 9:o=33778;break;case 11:o=33779;break;default:o=-1}n={complete:!0,fileFormat:"PVR",compressionAlgorithm:e,flags:i[1],pixelFormat:r,colorSpace:i[4],channelType:i[5],height:i[6],width:i[7],depth:i[8],numberOfSurfaces:i[9],numberOfFaces:i[10],numberOfMipmaps:i[11],metaDataSize:i[12],textureData:s.subarray(52+i[12],s.byteLength),glExtensionFormat:o}}return n},dds:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null;return 68===e[0]&&68===e[1]&&83===e[2]&&32===e[3]&&"DX10"===(s={complete:!0,fileFormat:"DDS",compressionAlgorithm:"S3TC",size:i[1],flags:i[2],height:i[3],width:i[4],pitch:i[5],depth:i[6],mipmapCount:i[7],formatSize:i[19],formatFlag:i[19],formatFourCC:[String.fromCharCode(e[84]),String.fromCharCode(e[85]),String.fromCharCode(e[86]),String.fromCharCode(e[87])].join(""),formatBitCount:i[21],formatRBitMask:i[22],formatGBitMask:i[23],formatBBitMask:i[24],formatABitMask:i[25],caps1:i[26],caps2:i[27],caps3:i[28],caps4:i[29],reserved2:i[30],DXGIFormat:null,resourceDimension:null,miscFlag:null,arraySize:null,textureData:e.subarray(i[1]+4,e.byteLength)}).formatFourCC&&(s.DXGIFormat=i[31],s.resourceDimension=i[32],s.miscFlag=i[33],s.arraySize=i[34],s.miscFlag=i[35]),s},ktx:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null,n=16+i[15]/4|0,r=i[n],o=i[7],a=0;if(171===e[0]&&75===e[1]&&84===e[2]&&88===e[3]&&32===e[4]&&49===e[5]&&49===e[6]&&187===e[7]&&13===e[8]&&10===e[9]&&26===e[10]&&10===e[11]&&[36196,35840,35841,35842,35843,33776,33777,33778,33779].indexOf(o)>=0){switch(o){case 36196:a="ETC1";break;case 35840:case 35841:case 35842:case 35843:a="PVRTC";break;case 33776:case 33777:case 33778:case 33779:a="S3TC"}s={complete:!0,fileFormat:"KTX",compressionAlgorithm:a,endianness:i[3],glType:i[4],glTypeSize:i[5],glFormat:i[6],glInternalFormat:i[7],glBaseInternalFormat:i[8],width:i[9],height:i[10],pixelDepth:i[11],numberOfArrayElements:i[12],numberOfFaces:i[13],numberOfMipmapLevels:i[14],bytesOfKeyValueData:i[15],keyAndValueByteSize:i[16],imageSize:r,textureData:e.subarray(4*(n+1),r+100)}}return s},pkm:function(t){var e=new Uint8Array(t),i=null;return 80===e[0]&&75===e[1]&&77===e[2]&&32===e[3]&&(i={complete:!0,fileFormat:"PKM",compressionAlgorithm:"ETC1",format:65535&(e[6]<<8|e[7]),width:65535&(e[8]<<8|e[9]),height:65535&(e[10]<<8|e[11]),originalWidth:65535&(e[12]<<8|e[13]),originalHeight:65535&(e[14]<<8|e[15]),textureData:e.subarray(16,e.length)}),i}},i.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},i.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},i.AudioSprite.prototype.constructor=i.AudioSprite,i.Sound=function(t,e,s,n,r){void 0===s&&(s=1),void 0===n&&(n=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=n,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this._globalVolume=1,this._markedToDelete=!1,this._removeFromSoundManager=!1,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=s,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new i.Signal,this.onPlay=new i.Signal,this.onPause=new i.Signal,this.onResume=new i.Signal,this.onLoop=new i.Signal,this.onStop=new i.Signal,this.onMute=new i.Signal,this.onMarkerComplete=new i.Signal,this.onFadeComplete=new i.Signal,this._volume=s,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},i.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop(),this._markedToDelete&&(this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode),this._removeFromSoundManager?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()))},update:function(){this.game.cache.checkSoundKey(this.key)?(this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))):this.destroy()},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){this.isPlaying&&!this.paused&&e!==this.volume&&(void 0===t&&(t=1e3),void 0!==e?(this.fadeTween=this.game.add.tween(this).to({volume:e},t,i.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)):console.warn("Phaser.Sound.fadeTo: No Volume Specified."))},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._globalVolume=t,this._sound.volume=this._globalVolume*this._volume)},destroy:function(t){void 0===t&&(t=!0),this._markedToDelete=!0,this._removeFromSoundManager=t,this.stop(),t?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())}},i.Sound.prototype.constructor=i.Sound,Object.defineProperty(i.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(i.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(i.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(i.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted?this._muteVolume=t:(this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=this._globalVolume*t))}}),i.SoundManager=function(t){this.game=t,this.onSoundDecode=new i.Signal,this.onVolumeChange=new i.Signal,this.onMute=new i.Signal,this.onUnMute=new i.Signal,this.onTouchUnlock=new i.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new i.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},i.SoundManager.prototype={boot:function(){var t=this.game.device,e=window.PhaserGlobal;if(t.iOS&&!1===t.webAudio&&(this.channels=1),e){if(!0===e.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===e.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(e&&e.audioContext)this.context=e.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||t.needsTouchUnlock()&&this.setTouchLock(),this.usingWebAudio&&t.chrome&&t.chromeVersion<=65&&console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. ')},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0)},setTouchUnlock:function(){this.touchLocked=!1,this._unlockSource=null,this.onTouchUnlock.dispatch()},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.setTouchUnlock();else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0),"suspended"===this._unlockSource.context.state&&this._unlockSource.context.resume()}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,s=this._parentBounds.height,n=this.getParentBounds(this._parentBounds),r=n.width!==e||n.height!==s,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,n),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottlee;return(h=h?s:!s)?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},i.ScaleManager.prototype.constructor=i.ScaleManager,Object.defineProperty(i.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(i.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(i.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(i.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),i.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.lineWidth=1,this.renderShadow=!0,this.currentColor=null,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1,this.isDisabled=!1,this._line=null,this._rect=null},i.Utils.Debug.prototype={boot:function(){this.game.renderType===i.CANVAS?this.context=this.game.context:(this.bmd=new i.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=i.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d")),this._line=new i.Line,this._rect=new i.Rectangle},resize:function(){this.bmd.resize(this.game.width,this.game.height),this.canvas.width=this.game.width,this.canvas.height=this.game.height},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e0)for(var e=0;e=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new i.Rectangle,layoutBounds:new i.Rectangle,documentBounds:new i.Rectangle},i.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},s=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(i.DOM,"scrollX",{get:e}),Object.defineProperty(i.DOM,"scrollY",{get:s}),Object.defineProperty(i.DOM.visualBounds,"x",{get:e}),Object.defineProperty(i.DOM.visualBounds,"y",{get:s}),Object.defineProperty(i.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(i.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var n=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(i.DOM.visualBounds,"width",{get:n}),Object.defineProperty(i.DOM.visualBounds,"height",{get:r}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:n}),Object.defineProperty(i.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(i.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(i.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(i.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(i.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(i.ArraySet.prototype,"next",{get:function(){return this.position=s||0===i)){null==i&&(i=1);for(var n=s-i,r=e;r0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=(t=i.ArrayUtils.transposeMatrix(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=i.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var s=0;s>>0:(t<<24|e<<16|s<<8|n)>>>0},unpackPixel:function(t,e,s,n){return void 0!==e&&null!==e||(e=i.Color.createColor()),void 0!==s&&null!==s||(s=!1),void 0!==n&&null!==n||(n=!1),i.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",s&&i.Color.RGBtoHSL(e.r,e.g,e.b,e),n&&i.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=i.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},hexToRGBArray:function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},RGBArrayToHex:function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},RGBtoHSL:function(t,e,s,n){n||(n=i.Color.createColor(t,e,s,1)),t/=255,e/=255,s/=255;var r=Math.min(t,e,s),o=Math.max(t,e,s);if(n.h=0,n.s=0,n.l=(o+r)/2,o!==r){var a=o-r;n.s=n.l>.5?a/(2-o-r):a/(o+r),o===t?n.h=(e-s)/a+(e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,s,n,r,o,a,h){var l={r:t||0,g:e||0,b:s||0,a:n||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return i.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toFixed()+","+t.g.toFixed()+","+t.b.toFixed()+","+t.a.toString()+")",t.color=i.Color.getColor(t.r,t.g,t.b),t.color32=i.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,s,n,r){return void 0===n&&(n=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+s).toString(16).slice(1):"0x"+i.Color.componentToHex(n)+i.Color.componentToHex(t)+i.Color.componentToHex(e)+i.Color.componentToHex(s)},hexToRGB:function(t){var e=i.Color.hexToColor(t);if(e)return i.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var s=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(s){var n=parseInt(s[1],16),r=parseInt(s[2],16),o=parseInt(s[3],16);e?(e.r=n,e.g=r,e.b=o):e=i.Color.createColor(n,r,o)}return e},webToColor:function(t,e){e||(e=i.Color.createColor());var s=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return s&&(e.r=~~Number(s[1]),e.g=~~Number(s[2]),e.b=~~Number(s[3]),e.a=void 0!==s[4]?Number(s[4]):1,i.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=i.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?i.Color.webToColor(t,e):(e.a=1,i.Color.hexToColor(t,e));if("number"==typeof t){var s=i.Color.getRGB(t);return e.r=s.r,e.g=s.g,e.b=s.b,e.a=s.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSVtoRGB(n/359,t,e));return s},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSLtoRGB(n/359,t,e));return s},interpolateColor:function(t,e,s,n,r,o){void 0===r&&(r=255),void 0===o&&(o=0);var a=i.Color.getRGB(t),h=i.Color.getRGB(e);if(0===o)var l=(h.red-a.red)*n/s+a.red,c=(h.green-a.green)*n/s+a.green,u=(h.blue-a.blue)*n/s+a.blue;if(1===o){var d,p=i.Color.RGBtoHSV(a.r,a.g,a.b),f=i.Color.RGBtoHSV(h.r,h.g,h.b),g=f.h-p.h;if(p.h>f.h){var m=f.h;f.h=p.h,p.h=m,g=-g,n=s-n}g>.5&&(p.h=p.h+1,d=((f.h-p.h)*n/s+p.h)%1),g<=.5&&(d=(f.h-p.h)*n/s+p.h);var y=(f.s-p.s)*n/s+p.s,v=(f.v-p.v)*n/s+p.v,x=i.Color.HSVtoRGB(d,y,v,x),l=x.r,c=x.g,u=x.b}return i.Color.getColor32(r,l,c,u)},interpolateColorWithRGB:function(t,e,s,n,r,o){var a=i.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(s-a.green)*o/r+a.green,c=(n-a.blue)*o/r+a.blue;return i.Color.getColor(h,l,c)},interpolateRGB:function(t,e,s,n,r,o,a,h){var l=(n-t)*h/a+t,c=(r-e)*h/a+e,u=(o-s)*h/a+s;return i.Color.getColor(l,c,u)},linear:function(t,e,i){return this.interpolateColor(t,e,1,i)},linearInterpolation:function(t,e){var s=i.Math.linear(0,t.length-1,e),n=t[Math.floor(s)],r=t[Math.ceil(s)];return this.linear(n,r,s%1)},getRandomColor:function(t,e,s){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===s&&(s=255),e>255||t>e)return i.Color.getColor(255,255,255);var n=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return i.Color.getColor32(s,n,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=i.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return i.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return i.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return i.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?i.Color.blendLinearBurn(t,2*e):i.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?i.Color.blendColorBurn(t,2*e):i.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?i.Color.blendDarken(t,2*e):i.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return i.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return i.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},i.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},i.Physics.ARCADE=0,i.Physics.P2JS=1,i.Physics.NINJA=2,i.Physics.BOX2D=3,i.Physics.CHIPMUNK=4,i.Physics.MATTERJS=5,i.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!i.Physics.hasOwnProperty("Arcade")||(this.arcade=new i.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&i.Physics.hasOwnProperty("Ninja")&&(this.ninja=new i.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&i.Physics.hasOwnProperty("P2")&&(this.p2=new i.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&i.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new i.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&i.Physics.hasOwnProperty("Matter")&&(this.matter=new i.Physics.Matter(this.game,this.config))},startSystem:function(t){t===i.Physics.ARCADE?this.arcade=new i.Physics.Arcade(this.game):t===i.Physics.P2JS?null===this.p2?this.p2=new i.Physics.P2(this.game,this.config):this.p2.reset():t===i.Physics.NINJA?this.ninja=new i.Physics.Ninja(this.game):t===i.Physics.BOX2D?null===this.box2d?this.box2d=new i.Physics.Box2D(this.game,this.config):this.box2d.reset():t===i.Physics.MATTERJS&&(null===this.matter?this.matter=new i.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,s){void 0===e&&(e=i.Physics.ARCADE),void 0===s&&(s=!1),e===i.Physics.ARCADE?this.arcade.enable(t):e===i.Physics.P2JS&&this.p2?this.p2.enable(t,s):e===i.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===i.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===i.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},i.Physics.prototype.constructor=i.Physics,i.Physics.Arcade=function(t){this.game=t,this.gravity=new i.Point,this.bounds=new i.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=i.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new i.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._total=0,this.setBoundsToWorld()},i.Physics.Arcade.prototype.constructor=i.Physics.Arcade,i.Physics.Arcade.SORT_NONE=0,i.Physics.Arcade.LEFT_RIGHT=1,i.Physics.Arcade.RIGHT_LEFT=2,i.Physics.Arcade.TOP_BOTTOM=3,i.Physics.Arcade.BOTTOM_TOP=4,i.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof i.Group?this.enable(t[s].children,e):(this.enableBody(t[s]),e&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],!0));else t instanceof i.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.Arcade.Body(t),t.parent&&t.parent instanceof i.Group&&t.parent.addToHash(t))},updateMotion:function(t){if(t.allowRotation){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed}t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&e.allowDrag&&(i-(n*=this.game.time.physicsElapsed)>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!0),this._total>0},collide:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!1),this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===i.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===i.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===i.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===i.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideObjects:function(t,e,i,s,n,r){if(!Array.isArray(t)&&Array.isArray(e))for(o=0;oa.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(t.body.bottoma.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,s,n,r,o)}}else{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(e);for(var c=this.quadTree.retrieve(t),h=0;hc.right)continue;if(c.x>a.right)break}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(a.bottomc.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,s,n,r)}}}}},collideGroupVsGroup:function(t,e,s,n,r,o){if(0!==t.length&&0!==e.length)for(var a=0;aa.bottom)&&(h.xa.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var s=i.Math.clamp(t.center.x,e.left,e.right),n=i.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-s)*(t.center.x-s)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},separateCircle:function(t,e,s){this.getOverlapX(t,e),this.getOverlapY(t,e);var n=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,n),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.center.x:e.center.x,y:t.isCircle?t.center.y:e.center.y,radius:t.isCircle?t.halfWidth:e.halfWidth};l.yh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.xh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.halfWidth+e.halfWidth-i.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(s||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.yMath.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x)>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0):t.deltaX()n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y)>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0):t.deltaY()n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,s,n,r,o){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(s);for(var a=new i.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c0&&(s=this.distanceBetween(t,e)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.setToPolar(n,e),n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},velocityFromAngle:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e,!0)},velocityFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerationFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(o,s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i,s){void 0===i&&(i=!1);var n,r;return s?(n=t.centerX-e.centerX,r=t.centerY-e.centerY):i?(n=t.world.x-e.world.x,r=t.world.y-e.world.y):(n=t.x-e.x,r=t.y-e.y),Math.sqrt(n*n+r*r)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},closest:function(t,e,i,s){for(var n=1/0,r=null,o=0,a=e.length;on&&(r=h,n=l)}return r},angleBetween:function(t,e,s){return void 0===s&&(s=!1),s?i.Point.angle(e.world,t.world):i.Point.angle(e,t)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},i.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=i.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new i.Point,this.position=new i.Point(t.x,t.y),this.prev=new i.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new i.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new i.Point,this.newVelocity=new i.Point,this.deltaMax=new i.Point,this.acceleration=new i.Point,this.allowDrag=!0,this.drag=new i.Point,this.allowGravity=!0,this.gravity=new i.Point,this.bounce=new i.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new i.Point(1e4,1e4),this.friction=new i.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=i.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.tilePadding=new i.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new i.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},i.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter())},updateCenter:function(){this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,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=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.none=!0,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.overlapR=0,this.overlapX=0,this.overlapY=0,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.updateCenter(),this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),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,this.updateCenter(),this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=this.velocity.atan()),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=i.LEFT:this.deltaX()>0&&(this.facing=i.RIGHT),this.deltaY()<0?this.facing=i.UP:this.deltaY()>0&&(this.facing=i.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.updateCenter(),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0,this.blocked.none=!1),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0,this.blocked.none=!1),!this.blocked.none},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.setToPolar(s,e),this.isMoving=!0,!0},moveTo:function(t,e,s){var n=e/(t/1e3);if(0===n)return!1;var r;return void 0===s?(r=this.angle,s=this.game.math.radToDeg(r)):r=this.game.math.degToRad(s),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new i.Line,this.moveEnd=new i.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===s||180===s?this.velocity.set(Math.cos(r)*n,0):90===s||270===s?this.velocity.set(0,Math.sin(r)*n):this.velocity.setToPolar(r,n),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,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(i,s),this.updateCenter(),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,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(e,i),this.updateCenter()):this.isCircle=!1},reset:function(t,e){this.stop(),this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this.updateBounds(),this.updateCenter()},stop:function(){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?i.Circle.contains(this,t,e):i.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},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},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof i.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(i.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),i.Physics.Arcade.Body.render=function(t,e,i,s,n){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,t.lineWidth=n||1,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.halfWidth,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},i.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},i.Physics.Arcade.Body.prototype.constructor=i.Physics.Arcade.Body,i.Physics.Arcade.TilemapCollision=function(){},i.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x-e.getTileOffsetX(),t.body.position.y-t.body.tilePadding.y-e.getTileOffsetY(),t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;ae.deltaAbsY()?l=-1:e.deltaAbsX()0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.getTileOffsetY();return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?(t.blocked.left=!0,t.blocked.none=!1):e>0&&(t.blocked.right=!0,t.blocked.none=!1),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?(t.blocked.up=!0,t.blocked.none=!1):e>0&&(t.blocked.down=!0,t.blocked.none=!1),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},i.Utils.mixinPrototype(i.Physics.Arcade.prototype,i.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,i.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new i.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new i.Signal,this.onBodyRemoved=new i.Signal,this.onSpringAdded=new i.Signal,this.onSpringRemoved=new i.Signal,this.onConstraintAdded=new i.Signal,this.onConstraintRemoved=new i.Signal,this.onContactMaterialAdded=new i.Signal,this.onContactMaterialRemoved=new i.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},i.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,s){void 0===e&&(e=!1),void 0===s&&(s=!0);var n=1;if(Array.isArray(t))for(n=t.length;n--;)t[n]instanceof i.Group?this.enable(t[n].children,e,s):(this.enableBody(t[n],e),s&&t[n].hasOwnProperty("children")&&t[n].children.length>0&&this.enable(t[n],e,!0));else t instanceof i.Group?this.enable(t.children,e,s):(this.enableBody(t,e),s&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);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.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.DistanceConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,s,n){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.GearConstraint(this,t,e,s,n));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),s=this.getBody(s),t&&s)return this.addConstraint(new i.Physics.P2.RevoluteConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,s,n,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.LockConstraint(this,t,e,s,n,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,s,n,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.PrismaticConstraint(this,t,e,s,n,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var s=new i.Physics.P2.Material(t);return this.materials.push(s),void 0!==e&&e.setMaterial(s),s},createContactMaterial:function(t,e,s){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var n=new i.Physics.P2.ContactMaterial(t,e,s);return this.addContactMaterial(n)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof i.Physics.P2.Body?t.data:t.body&&t.body.type===i.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,s,n){void 0===e&&(e=this.world.bodies),void 0===s&&(s=5),void 0===n&&(n=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof i.Physics.P2.Body&&(!n||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!n||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof i.Sprite&&e[a].hasOwnProperty("body")&&(!n||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,s)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var s=new i.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(s),t&&this.setCollisionGroup(t,s),s},setCollisionGroup:function(t,e){if(t instanceof i.Group)for(var s=0;s-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides?n+=u.width:((p=this.createBody(r,o,0,!1)).addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0)}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(i.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(i.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(i.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(i.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(i.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(i.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(i.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(i.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(i.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),i.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},i.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionGroup=t})},setMask:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionMask=t})},setSensor:function(t,e){this.getFixtures(e).forEach(function(e){e.sensor=t})},setMaterial:function(t,e){this.getFixtures(e).forEach(function(e){e.material=t})},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},i.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.PointProxy.prototype.constructor=i.Physics.P2.PointProxy,Object.defineProperty(i.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),i.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.InversePointProxy.prototype.constructor=i.Physics.P2.InversePointProxy,Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),i.Physics.P2.Body=function(t,e,s,n,r){e=e||null,s=s||0,n=n||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=i.Physics.P2JS,this.offset=new i.Point,this.data=new p2.Body({position:[this.world.pxmi(s),this.world.pxmi(n)],mass:r}),this.data.parent=this,this.velocity=new i.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new i.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new i.Point,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},i.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(r=0;r-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var n=this.getCollisionMask();if(void 0===i)for(var r=this.data.shapes.length-1;r>=0;r--)this.data.shapes[r].collisionMask=n;else i.collisionMask=n},collides:function(t,e,i,s){if(Array.isArray(t))for(r=0;r=0;r--)this.data.shapes[r].collisionMask=n;else s.collisionMask=n},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},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(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;np;n=0<=p?++d:--d)l=e.vertices[n],p2.vec2.rotate(u,l,t),c.push([(u[0]+a[0])*this.ppu,-(u[1]+a[1])*this.ppu]);this.drawConvex(h,c,e.triangles,16711680,i,r,this.settings.debugPolygons,[a[0]*this.ppu,-a[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)p=(c=e[l])[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return 2===(e=t.toString(16)).length?e:e+"0"}}),i.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1);var c={restLength:s=t.pxm(s),stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},i.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),i.Physics.P2.Material.prototype.constructor=i.Physics.P2.Material,i.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},i.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),i.Physics.P2.ContactMaterial.prototype.constructor=i.Physics.P2.ContactMaterial,i.Physics.P2.CollisionGroup=function(t){this.mask=t},i.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t;var a={distance:s=t.pxm(s),localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},i.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),i.Physics.P2.DistanceConstraint.prototype.constructor=i.Physics.P2.DistanceConstraint,i.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},i.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),i.Physics.P2.GearConstraint.prototype.constructor=i.Physics.P2.GearConstraint,i.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t;var o={localOffsetB:s=[t.pxm(s[0]),t.pxm(s[1])],localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},i.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),i.Physics.P2.LockConstraint.prototype.constructor=i.Physics.P2.LockConstraint,i.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t;var h={localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},i.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),i.Physics.P2.PrismaticConstraint.prototype.constructor=i.Physics.P2.PrismaticConstraint,i.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},i.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),i.Physics.P2.RevoluteConstraint.prototype.constructor=i.Physics.P2.RevoluteConstraint,i.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},i.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&tthis.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},i.Tile.prototype.constructor=i.Tile,Object.defineProperty(i.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(i.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(i.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(i.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(i.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(i.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),i.Tilemap=function(t,e,s,n,r,o){this.game=t,this.key=e;var a=i.TilemapParser.parse(this.game,e,s,n,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},i.Tilemap.CSV=0,i.Tilemap.TILED_JSON=1,i.Tilemap.NORTH=0,i.Tilemap.EAST=1,i.Tilemap.SOUTH=2,i.Tilemap.WEST=3,i.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,s,n,r,o,a){if(void 0===t)return null;void 0===s&&(s=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===s&&(s=32),0===n&&(n=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof i.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===i.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),console.log("Tilesets: ",this.tilesets),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new i.Tileset(t,a,s,n,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y1)for(u=0;uthis.layers.length)return console.warn('Tilemap.createLayer: Invalid layer ID given: "'+t+'"'),void console.log("Layers: ",this.layers);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===s||s<=0?s=Math.min(this.game.height,this.layers[r].heightInPixels):s>this.game.height&&(s=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",s),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=n.add(new i.TilemapLayer(this.game,this,r,e,s));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,s,n,r,o){void 0===o&&(o=this.game.world);{if(null===this.getLayerIndex(t)){for(var a,h={name:t,x:0,y:0,width:e,height:s,widthInPixels:e*n,heightInPixels:s*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;cthis.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height),(l=new i.TilemapLayer(this.game,this,this.layers.length-1,d,p)).name=t,o.add(l)}console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t)}},getIndex:function(t,e){for(var i=0;ie)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n-1&&this.collideIndexes.splice(n,1)}for(var r=0;r0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e-1},removeTile:function(t,e,s){if(s=this.getLayer(s),t>=0&&t=0&&e=0&&e=0&&s-1?this.layers[n].data[s][e].setCollision(!0,!0,!0,!0):this.layers[n].data[s][e].resetCollision(),this.layers[n].dirty=!0,this.calculateFaces(n),this.layers[n].data[s][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(r=this.layers[s].height-1;r>=0;r--)for(o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r=0&&t=0&&ethis.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},i.Tilemap.prototype.constructor=i.Tilemap,Object.defineProperty(i.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),i.TilemapLayer=function(t,e,s,n,r){n|=0,r|=0,i.Sprite.call(this,t,0,0),this.map=e,this.index=s,this.layer=e.layers[s],this.canvas=i.CanvasPool.create(this,n,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas,null,this.game.resolution))),this.type=i.TILEMAPLAYER,this.physicsType=i.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!0,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this.tileOffset=new i.Point(this.layer.offsetX||0,this.layer.offsetY||0),this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=i.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},i.TilemapLayer.prototype=Object.create(i.Sprite.prototype),i.TilemapLayer.prototype.constructor=i.TilemapLayer,i.TilemapLayer.prototype.preUpdateCore=i.Component.Core.preUpdate,i.TilemapLayer.sharedCopyCanvas=null,i.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=i.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},i.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},i.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y},i.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.TilemapLayer.prototype.destroy=function(){i.CanvasPool.remove(this),i.Component.Destroy.prototype.destroy.call(this)},i.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},i.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},i.TilemapLayer.prototype.getTileOffsetX=function(){return this.tileOffset.x||(this.fixedToCamera?0:this.position.x)},i.TilemapLayer.prototype.getTileOffsetY=function(){return this.tileOffset.y||(this.fixedToCamera?0:this.position.y)},i.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},i.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},i.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},i.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},i.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},i.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},i.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},i.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a=0;m++,v--,f+=c){m>=h&&(m-=h);var _=this.layer.data[m];for(g=b,y=n-i,p=x;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var w=_[g];if(w&&!(w.index<0)){var T=w.index,P=u[T];void 0===P&&(P=this.resolveTileset(T)),w.alpha===d||this.debug||(o.globalAlpha=w.alpha,d=w.alpha),P?w.rotation||w.flipped?(o.save(),o.translate(p+w.centerX,f+w.centerY),o.rotate(w.rotation),w.flipped&&o.scale(-1,1),P.draw(o,-w.centerX,-w.centerY,T),o.restore()):P.draw(o,p,f,T):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),w.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},i.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},i.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},i.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)=0;s++,r--,e+=f){s>=d&&(s-=d);var T=this.layer.data[s];for(i=_,n=m-g,t=x;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var P=T[i];!P||P.index<0||!P.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),P.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),P.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),P.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),P.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(i.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),i.TilemapParser={INSERT_NULL:!1,parse:function(t,e,s,n,r,o){if(void 0===s&&(s=32),void 0===n&&(n=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(s,n,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===i.Tilemap.CSV)return this.parseCSV(e,a.data,s,n);if(!a.format||a.format===i.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,s,n){for(var r=this.getEmptyData(),o=[],a=(e=e.trim()).split("\n"),h=a.length,l=0,c=0;c>>0;r.data=h,delete r.encoding}else if(r.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+r.name+"'");continue}k={name:r.name,x:r.x,y:r.y,width:r.width,height:r.height,widthInPixels:r.width*t.tilewidth,heightInPixels:r.height*t.tileheight,alpha:r.opacity,offsetX:r.offsetx,offsetY:r.offsety,visible:r.visible,properties:{},indexes:[],callbacks:[],bodies:[]};r.properties&&(k.properties=r.properties);for(var c,u,d,p=0,f=[],g=[],m=0,a=r.data.length;m536870912)switch(A>2147483648&&(A-=2147483648,d+=4),A>1073741824&&(A-=1073741824,d+=2),A>536870912&&(A-=536870912,d+=1),d){case 5:c=Math.PI/2;break;case 6:c=Math.PI;break;case 3:c=3*Math.PI/2;break;case 4:c=0,u=!0;break;case 7:c=Math.PI/2,u=!0;break;case 2:c=Math.PI,u=!0;break;case 1:c=3*Math.PI/2,u=!0}A>0?((F=new i.Tile(k,A,p,g.length,t.tilewidth,t.tileheight)).rotation=c,F.flipped=u,0!==d&&(F.flippedVal=d),f.push(F)):i.TilemapParser.INSERT_NULL?f.push(null):f.push(new i.Tile(k,-1,p,g.length,t.tilewidth,t.tileheight)),++p===r.width&&(g.push(f),p=0,f=[])}k.data=g,s.push(k)}e.layers=s;for(var y=[],n=0;n=0&&n+1=this.firstgid&&t=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(t=0;t=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._total>0&&this._counter>=this._total&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},i.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1),void 0===r&&(r=null);var o,a=0,h=t,l=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);athis.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},i.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),this.resetParticle(n,o,a),!0},i.Particles.Arcade.Emitter.prototype.getNextParticle=function(){for(var t=this.length;t--;){var e=this.next();if(!e.exists)return e}return null},i.Particles.Arcade.Emitter.prototype.resetParticle=function(t,e,i){var s=this.game.rnd;t.reset(e,i),t.angle=0,t.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(t):this.particleSendToBack&&this.sendToBack(t),this.autoScale?t.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?t.scale.set(s.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y?t.scale.set(s.realInRange(this._minParticleScale.x,this._maxParticleScale.x),s.realInRange(this._minParticleScale.y,this._maxParticleScale.y)):t.scale.set(this._minParticleScale.x,this._minParticleScale.y),this.autoAlpha?t.setAlphaData(this.alphaData):t.alpha=s.realInRange(this.minParticleAlpha,this.maxParticleAlpha),t.blendMode=this.blendMode;var n=t.body;n.updateBounds(),n.bounce.copyFrom(this.bounce),n.drag.copyFrom(this.particleDrag),null!=this.minAngle&&null!=this.maxAngle?this.game.physics.arcade.velocityFromAngle(this.minAngle===this.maxAngle?this.minAngle:s.between(this.minAngle,this.maxAngle),this.minSpeed===this.maxSpeed?this.minSpeed:s.between(this.minSpeed,this.maxSpeed),n.velocity):(n.velocity.x=s.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),n.velocity.y=s.between(this.minParticleSpeed.y,this.maxParticleSpeed.y)),n.angularVelocity=s.between(this.minRotation,this.maxRotation),n.gravity.copyFrom(this.gravity),n.angularDrag=this.angularDrag,t.onEmit()},i.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),i.Group.prototype.destroy.call(this,!0,!1)},i.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},i.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},i.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},i.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},i.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,s,n,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=0),void 0===n&&(n=i.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,s>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},s,n);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},i.Particles.Arcade.Emitter.prototype.setScale=function(t,e,s,n,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=1),void 0===n&&(n=1),void 0===r&&(r=0),void 0===o&&(o=i.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,s),this._maxParticleScale.set(e,n),this.autoScale=!1,r>0&&(t!==e||s!==n)){var h={x:t,y:s},l=this.game.make.tween(h).to({x:e,y:n},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},i.Particles.Arcade.Emitter.prototype.setAngle=function(t,e,i,s){return this.minAngle=t,this.maxAngle=e,null!=i&&(this.minSpeed=i),null!=s&&(this.maxSpeed=s),this},i.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"gravity",{get:function(){return this._gravity},set:function(t){"number"==typeof t?this._gravity.y=t:this._gravity=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"id",{get:function(){return this._id}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"output",{get:function(){return 1e3*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"lifespanOutput",{get:function(){return(0===this.lifespan?1/0:this.lifespan)*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"remainder",{get:function(){return this.maxParticles-this.lifespanOutput}}),i.Weapon=function(t,e){i.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new i.Rectangle(0,0,1,1),this.fireAngle=i.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new i.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=i.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=i.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new i.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new i.Signal,this.onKill=new i.Signal,this.onFireLimit=new i.Signal,this.trackedSprite=null,this.trackedPointer=null,this.multiFire=!1,this._hasFired=!1,this.trackRotation=!1,this.trackOffset=new i.Point,this._nextFire=0,this._tempNextFire=0,this._rotatedPoint=new i.Point},i.Weapon.prototype=Object.create(i.Plugin.prototype),i.Weapon.prototype.constructor=i.Weapon,i.Weapon.KILL_NEVER=0,i.Weapon.KILL_LIFESPAN=1,i.Weapon.KILL_DISTANCE=2,i.Weapon.KILL_WEAPON_BOUNDS=3,i.Weapon.KILL_CAMERA_BOUNDS=4,i.Weapon.KILL_WORLD_BOUNDS=5,i.Weapon.KILL_STATIC_BOUNDS=6,i.Weapon.prototype.createBullets=function(t,e,s,n){return void 0===t&&(t=1),void 0===n&&(n=this.game.world),this.bullets&&!this.bullets.game&&(this.bullets=null),this.bullets||(this.bullets=this.game.add.physicsGroup(i.Physics.ARCADE,n),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,s),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=s),this},i.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},i.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},i.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},i.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},i.Weapon.prototype.update=function(){this._bulletKillType===i.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},i.Weapon.prototype.postRender=function(){this.multiFire&&this._hasFired&&(this._hasFired=!1,this._nextFire=this._tempNextFire)},i.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},i.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},i.Weapon.prototype.fireMany=function(t,e){this.multiFire=!0;var i=[],s=this;return e||this.trackedSprite||this.trackedPointer?t.forEach(function(t){i.push(s.fire(e,null,null,t.x,t.y))}):t.forEach(function(t){i.push(s.fire(t))}),i},i.Weapon.prototype.fireOffset=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.fire(null,null,null,t,e)},i.Weapon.prototype.fire=function(t,e,s,n,r){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game.time.now0&&this.shots===this.fireLimit)return null;var o=this.bulletSpeed;0!==this.bulletSpeedVariance&&(o+=i.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.worldRotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(o+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y)),void 0!==n&&(this.fireFrom.x+=n),void 0!==r&&(this.fireFrom.y+=r);var a=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,h=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,l=this.trackRotation?this.trackedSprite.angle:this.fireAngle;null!==e&&null!==s&&(l=this.game.math.radToDeg(Math.atan2(s-h,e-a))),0!==this.bulletAngleVariance&&(l+=i.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var c=0,u=0;0===l||180===l?c=Math.cos(this.game.math.degToRad(l))*o:90===l||270===l?u=Math.sin(this.game.math.degToRad(l))*o:(c=Math.cos(this.game.math.degToRad(l))*o,u=Math.sin(this.game.math.degToRad(l))*o);var d=null;if(this.autoExpandBulletsGroup?(d=this.bullets.getFirstExists(!1,!0,a,h,this.bulletKey,this.bulletFrame)).data.bulletManager=this:d=this.bullets.getFirstExists(!1),d){if(d.reset(a,h),d.data.fromX=a,d.data.fromY=h,d.data.killType=this.bulletKillType,d.data.killDistance=this.bulletKillDistance,d.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===i.Weapon.KILL_LIFESPAN&&(d.lifespan=this.bulletLifespan),d.angle=l+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===d.animations.getAnimation(this.bulletAnimation)){var p=this.anims[this.bulletAnimation];d.animations.add(p.name,p.frames,p.frameRate,p.loop,p.useNumericIndex)}d.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(d.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(d.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);d.data.bodyDirty&&(this._data.customBody&&d.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),d.body.collideWorldBounds=this.bulletCollideWorldBounds,d.data.bodyDirty=!1),d.body.velocity.set(c,u),d.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y);var f=0;if(0!==this.bulletSpeedVariance){var g=this.fireRate;(g+=i.Math.between(-this.fireRateVariance,this.fireRateVariance))<0&&(g=0),f=this.game.time.now+g}else f=this.game.time.now+this.fireRate;this.multiFire?this._hasFired||(this._hasFired=!0,this._tempNextFire=f,this.shots++):(this._nextFire=f,this.shots++),this.onFire.dispatch(d,this,o),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return d},i.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},i.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},i.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},i.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},i.Weapon.prototype.setBulletFrames=function(t,e,s,n){return void 0===s&&(s=!0),void 0===n&&(n=!1),this.bulletFrames=i.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=s,this.bulletFrameRandom=n,this},i.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},i.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(i.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets&&(this.bullets.classType=this._bulletClass)}}),Object.defineProperty(i.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case i.Weapon.KILL_STATIC_BOUNDS:case i.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case i.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case i.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(i.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(i.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(i.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),i.Bullet=function(t,e,s,n,r){i.Sprite.call(this,t,e,s,n,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},i.Bullet.prototype=Object.create(i.Sprite.prototype),i.Bullet.prototype.constructor=i.Bullet,i.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},i.Bullet.prototype.update=function(){this.exists&&(this.data.killType>i.Weapon.KILL_LIFESPAN&&(this.data.killType===i.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=this.body.velocity.atan()),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},i.Video=function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=i.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new i.Signal,this.onChangeSource=new i.Signal,this.onComplete=new i.Signal,this.onAccess=new i.Signal,this.onError=new i.Signal,this.onTimeout=new i.Signal,this.onTouchUnlock=new i.Signal,this.playWhenUnlocked=!0,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._pendingChangeSource=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var n=this.game.cache.getVideo(e);n.isBlob?this.createVideoFromBlob(n.data):this.video=n.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else s&&this.createVideoFromURL(s,!1);this.video&&!s?(this.baseTexture=new PIXI.BaseTexture(this.video,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(i.Cache.DEFAULT.baseTexture.source,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new i.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,i.BitmapData&&(this.snapshot=new i.BitmapData(this.game,"",this.width,this.height)),this.game.device.needsTouchUnlock()?this.setTouchLock():n&&(n.locked=!1)},i.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return this._pendingChangeSource?this:(void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this)},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming)},setTouchLock:function(){this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.playWhenUnlocked&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return this.onTouchUnlock.dispatch(this),!0},grab:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null!==this.snapshot)return t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot;console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable")},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(i.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(i.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(i.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(i.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(i.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(i.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(i.Video.prototype,"playing",{get:function(){return!!this.video&&!(this.video.paused&&this.video.ended)}}),i.Video.prototype.constructor=i.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=i.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=i.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new i.Matrix),PIXI.TextureSilentFail=!0,PIXI.canUseNewCanvasBlendModes=function(){return i.Device.canUseMultiply},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=i),exports.Phaser=i):"undefined"!=typeof define&&define.amd?define("Phaser",e.Phaser=i):e.Phaser=i,i}.call(this); +//# sourceMappingURL=phaser.map \ No newline at end of file diff --git a/Iteration Sequence 1/js/stage_fight.js b/Iteration Sequence 1/js/stage_fight.js new file mode 100644 index 000000000..c4e262197 --- /dev/null +++ b/Iteration Sequence 1/js/stage_fight.js @@ -0,0 +1,16 @@ +var gameOver = function(game){} + +gameOver.prototype = { + init: function(score){ + alert("You scored: "+score) + }, + create: function(){ + var gameOverTitle = this.game.add.sprite(160,160,"gameover"); + gameOverTitle.anchor.setTo(0.5,0.5); + var playButton = this.game.add.button(160,320,"play",this.playTheGame,this); + playButton.anchor.setTo(0.5,0.5); + }, + playTheGame: function(){ + this.game.state.start("TheGame"); + } +} \ No newline at end of file diff --git a/Iteration Sequence 1/sources.txt b/Iteration Sequence 1/sources.txt new file mode 100644 index 000000000..afe7c94fc --- /dev/null +++ b/Iteration Sequence 1/sources.txt @@ -0,0 +1,5 @@ +https://www.123rf.com/photo_62999359_stock-vector-game-background-flat-style-2d-game-application.html +http://kenney.nl/assets +https://phaser.io/examples/v2/sprites/move-a-sprite + +http://www.emanueleferonato.com/2014/08/28/phaser-tutorial-understanding-phaser-states/ \ No newline at end of file diff --git a/Iteration Sequence 2.2/assets/Attack.png b/Iteration Sequence 2.2/assets/Attack.png new file mode 100644 index 000000000..254b6eaf5 Binary files /dev/null and b/Iteration Sequence 2.2/assets/Attack.png differ diff --git a/Iteration Sequence 2.2/assets/Move.png b/Iteration Sequence 2.2/assets/Move.png new file mode 100644 index 000000000..31994c184 Binary files /dev/null and b/Iteration Sequence 2.2/assets/Move.png differ diff --git a/Iteration Sequence 2.2/assets/Play.png b/Iteration Sequence 2.2/assets/Play.png new file mode 100644 index 000000000..32ec4a7a7 Binary files /dev/null and b/Iteration Sequence 2.2/assets/Play.png differ diff --git a/Iteration Sequence 2.2/assets/Turret.png b/Iteration Sequence 2.2/assets/Turret.png new file mode 100644 index 000000000..6c0a3a042 Binary files /dev/null and b/Iteration Sequence 2.2/assets/Turret.png differ diff --git a/Iteration Sequence 2.2/assets/background.png b/Iteration Sequence 2.2/assets/background.png new file mode 100644 index 000000000..c80bf6d67 Binary files /dev/null and b/Iteration Sequence 2.2/assets/background.png differ diff --git a/Iteration Sequence 2.2/assets/buy.png b/Iteration Sequence 2.2/assets/buy.png new file mode 100644 index 000000000..7648772a8 Binary files /dev/null and b/Iteration Sequence 2.2/assets/buy.png differ diff --git a/Iteration Sequence 2.2/assets/character.png b/Iteration Sequence 2.2/assets/character.png new file mode 100644 index 000000000..1cb3e4d3c Binary files /dev/null and b/Iteration Sequence 2.2/assets/character.png differ diff --git a/Iteration Sequence 2.2/assets/endTurn.png b/Iteration Sequence 2.2/assets/endTurn.png new file mode 100644 index 000000000..75f6a6c79 Binary files /dev/null and b/Iteration Sequence 2.2/assets/endTurn.png differ diff --git a/Iteration Sequence 2.2/assets/grid.png b/Iteration Sequence 2.2/assets/grid.png new file mode 100644 index 000000000..b7815c713 Binary files /dev/null and b/Iteration Sequence 2.2/assets/grid.png differ diff --git a/Iteration Sequence 2.2/assets/grid_A.png b/Iteration Sequence 2.2/assets/grid_A.png new file mode 100644 index 000000000..be2105641 Binary files /dev/null and b/Iteration Sequence 2.2/assets/grid_A.png differ diff --git a/Iteration Sequence 2.2/assets/grid_B.png b/Iteration Sequence 2.2/assets/grid_B.png new file mode 100644 index 000000000..4eb4bf4ae Binary files /dev/null and b/Iteration Sequence 2.2/assets/grid_B.png differ diff --git a/Iteration Sequence 2.2/assets/play_button.json b/Iteration Sequence 2.2/assets/play_button.json new file mode 100644 index 000000000..174926e9c --- /dev/null +++ b/Iteration Sequence 2.2/assets/play_button.json @@ -0,0 +1,36 @@ +{"frames": [ + +{ + "filename": "down", + "frame": {"x":0,"y":142,"w":193,"h":71}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":193,"h":71}, + "sourceSize": {"w":193,"h":71} +}, +{ + "filename": "out", + "frame": {"x":0,"y":71,"w":193,"h":71}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":193,"h":71}, + "sourceSize": {"w":193,"h":71} +}, +{ + "filename": "over", + "frame": {"x":0,"y":0,"w":193,"h":71}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":193,"h":71}, + "sourceSize": {"w":193,"h":71} +}], +"meta": { + "app": "http://www.texturepacker.com", + "version": "1.0", + "image": "button_texture_atlas.png", + "format": "RGBA8888", + "size": {"w":193,"h":213}, + "scale": "1", + "smartupdate": "$TexturePacker:SmartUpdate:94df81041404a206a4e9cd597a1e3495$" +} +} diff --git a/Iteration Sequence 2.2/assets/preloader_background.jpg b/Iteration Sequence 2.2/assets/preloader_background.jpg new file mode 100644 index 000000000..feae1e6e1 Binary files /dev/null and b/Iteration Sequence 2.2/assets/preloader_background.jpg differ diff --git a/Iteration Sequence 2.2/assets/preloader_bar.png b/Iteration Sequence 2.2/assets/preloader_bar.png new file mode 100644 index 000000000..ee98e864e Binary files /dev/null and b/Iteration Sequence 2.2/assets/preloader_bar.png differ diff --git a/Iteration Sequence 2.2/assets/spot.png b/Iteration Sequence 2.2/assets/spot.png new file mode 100644 index 000000000..e30a50194 Binary files /dev/null and b/Iteration Sequence 2.2/assets/spot.png differ diff --git a/Iteration Sequence 2.2/assets/tank.png b/Iteration Sequence 2.2/assets/tank.png new file mode 100644 index 000000000..ad378c7a7 Binary files /dev/null and b/Iteration Sequence 2.2/assets/tank.png differ diff --git a/Iteration Sequence 2.2/assets/test.json b/Iteration Sequence 2.2/assets/test.json new file mode 100644 index 000000000..428eed420 --- /dev/null +++ b/Iteration Sequence 2.2/assets/test.json @@ -0,0 +1,100 @@ +{"frames": [ + +{ + "filename": "run00", + "frame": {"x":34,"y":128,"w":56,"h":60}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":2,"w":56,"h":60}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run01", + "frame": {"x":54,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run02", + "frame": {"x":54,"y":58,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run03", + "frame": {"x":0,"y":192,"w":34,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":11,"y":0,"w":34,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run04", + "frame": {"x":0,"y":64,"w":54,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":1,"y":0,"w":54,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run05", + "frame": {"x":196,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run06", + "frame": {"x":0,"y":0,"w":54,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":1,"y":0,"w":54,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run07", + "frame": {"x":140,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run08", + "frame": {"x":34,"y":188,"w":50,"h":60}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":3,"y":2,"w":50,"h":60}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run09", + "frame": {"x":0,"y":128,"w":34,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":11,"y":0,"w":34,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run10", + "frame": {"x":84,"y":188,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}], +"meta": { + "app": "http://www.texturepacker.com", + "version": "1.0", + "image": "running_bot.png", + "format": "RGBA8888", + "size": {"w":252,"h":256}, + "scale": "0.2", + "smartupdate": "$TexturePacker:SmartUpdate:fb56f261b1eb04e3215824426595f64c$" +} +} diff --git a/Iteration Sequence 2.2/assets/title.jpg b/Iteration Sequence 2.2/assets/title.jpg new file mode 100644 index 000000000..d416d3bb1 Binary files /dev/null and b/Iteration Sequence 2.2/assets/title.jpg differ diff --git a/Iteration Sequence 2.2/index.html b/Iteration Sequence 2.2/index.html new file mode 100644 index 000000000..4161c198a --- /dev/null +++ b/Iteration Sequence 2.2/index.html @@ -0,0 +1,142 @@ + + + + + Iteration Sequence 2 + + + + + + + + + + + + + + +
+
+

Iteration Sequence 2

+
    +
  • Originality: + What is original about your game? +
  • +
      +
    • + Game is work in progress. This is a game of zone control where players are actively trying to control multiple zones for economy and fighting advantage. +
    • +
    +
  • Technical Merit: + What is interesting about your game technology? +
  • +
      +
    • Players can select/deselect their own units.
    • +
    • Players can view stats for individual units.
    • +
    • (Soon)Players will be able to purchase additional units as well as build turrets.
    • +
    • (Soon)Players will be able to engage in combats and destroy enemy units.
    • +
    +
  • Prototype Postmortem: + What did you learn from this prototype? What was the easiest or hardest part of making it? +
  • +
      +
    • I am somewhat learning object oriented programming through javascript
    • +
    • Creating different keys for different function calls.
    • +
    • How to destory sprite/objects.
    • +
    • (Soon)How to balance the stats of the units
    • +
    +
  • Prototype Assets: + Did you make your prototype assets from scratch? Did you borrow them? Cite your sources here. + +
  • Prototype Closest Other Game: + Which other game most closely resembles your game? If you are borrowing code from a Phaser Example, you must say so here. If you borrow code from elsewhere, you must say so here. +
  • +
      +
    • Idea was inspired by starcraft but core mechanics should be original.
    • +
    +
  • High Concept: + A one-sentence summary of your game. +
  • +
      +
    • (Soon)Build turrets to reinforce your troops whlie conquering your oppoenents.
    • +
    +
  • Theme: + State which of the Storymatic themes you used. +
  • +
      +
    • Soldier
    • +
    +
  • Mandated Variety: + State which input, randomness, genre, and play style you used in this prototype. +
  • +
      +
    • Input: keyboard clicks + mouse clicks.
    • +
    • Randomness: (Soon) Most elements are deterministic.
    • +
    • Play style: Competitor, Explorer, Director. Trying their best to defeat the opponent. Player directs their units to a certain grid and chooses whether they want to attack. If this game were to be a real game the map would be a lot bigger allowing players to explore.
    • +
    • Genre: Real Time Strategy
    • +
    +
  • Prototype Goal: + What game mechanic is this prototype evaluating? +
  • +
      +
    • This prototype has only implemented the basic ideas of my physical prototype.
    • +
    • This prototype will help me with balancing the stats for each unit
    • +
    +
  • Player Experience Goals: + What experience do you want players to have when playing your game? +
  • +
      +
    • Enjoyment from getting stronger every turn.
    • +
    • Strategicaly placing units and fighting opponents.
    • +
    +
  • Gameplay: + A paragraph describing the actions the player can perform, the system dynamics, and the core mechanic. Include a concise explanation of the prototype’s inputs and their expected effects (how to play). You can also describe game play that is not in the prototype. You may include mock-up images for parts of the game not in the prototype. +
  • +
      +
    • To be announced.
    • +
    +
  • Strategies: + What player strategies do you expect will be effective at playing this game? +
  • +
      +
    • TBA
    • +
    +
  • Story/Setting/Premise: + A paragraph about the world your game is set in and who the characters are. What makes the game world and its occupants unique and interesting? Do the tokens represent something? If the game has a backstory, mention it here. If the game is abstract, then say so. + How will the dramatic tension interact with the gameplay tension? +
  • +
      +
    • No Story for this game for now.
    • +
    +
  • Target Audience: + A single sentence that describes the demographic you're trying to reach. +
  • +
      +
    • Ages 12+
    • +
    +
  • Play Time: + How long does your game take to play? +
  • +
      +
    • Depends on how fast player thinks. My estimate would be around 10 minutes.
    • +
    +
+ + \ No newline at end of file diff --git a/Iteration Sequence 2.2/js/Boot.js b/Iteration Sequence 2.2/js/Boot.js new file mode 100644 index 000000000..349a93294 --- /dev/null +++ b/Iteration Sequence 2.2/js/Boot.js @@ -0,0 +1,48 @@ +"use strict"; + +var GameStates = {}; + +GameStates.makeBoot = function( game ) { + return { + init: function () { + + // Unless you specifically know your game needs to support multi-touch I would recommend setting this to 1 + game.input.maxPointers = 1; + + // Phaser will automatically pause if the browser tab the game is in loses focus. You can disable that here: + game.stage.disableVisibilityChange = true; + + if (game.device.desktop) + { + // If you have any desktop specific settings, they can go in here + game.scale.pageAlignHorizontally = true; + } + else + { + // Same goes for mobile settings. + // In this case we're saying "scale the game, no lower than 480x260 and no higher than 1024x768" + game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; + game.scale.setMinMax(480, 260, 1024, 768); + game.scale.forceLandscape = true; + game.scale.pageAlignHorizontally = true; + } + + }, + + preload: function () { + + // Here we load the assets required for our Preloader state (in this case a background and a loading bar) + game.load.image('preloaderBackground', 'assets/preloader_background.jpg'); + game.load.image('preloaderBar', 'assets/preloader_bar.png'); + + }, + + create: function () { + + // By this point the preloader assets have loaded to the cache, we've set the game settings + // So now let's start the real preloader going + game.state.start('Preloader'); + + } + }; +}; diff --git a/Iteration Sequence 2.2/js/Game.js b/Iteration Sequence 2.2/js/Game.js new file mode 100644 index 000000000..dcd0bb62c --- /dev/null +++ b/Iteration Sequence 2.2/js/Game.js @@ -0,0 +1,719 @@ +"use strict"; + +GameStates.makeGame = function( game, shared ) { + // Create your own letiables. + let grid; + let attack = false; + let move = false; + let attack_button; + let move_button; + + let soldier; + let sniper; + let tank; + let turret; + + let selected = null; + let selected_square = null; + + let esc_key; + let space_key; + let a_key; + let m_key; + let p_key; + + let moved_group; + + let player1_square; + let player2_square; + + let player; + let player_turn; + let player_array; + + let buy1_button; + let buy2_button; + let buy3_button; + let buy4_button; + let end_button; + + let x_count = 50; + + let txt_style = {font: "20px Arial"}; + let stat_msg; + let stat_msg2; + let unit_msg; + let unit_msg2; + + let event_msg; + let event_msg2; + let event_msg3; + let event_msg4; + + function createPlayer(square, num) + { + this.num = num; + this.money = 0; + this.turn = false; + this.turret = 1; + this.square = square; + } + + function createSoldier(soldier, num) + { + soldier.type = 'soldier'; + soldier.hp = 2; + soldier.atk = 1; + soldier.range = 1; + soldier.move = 1; + soldier.cost = 1; + soldier.num = num; + soldier.moved = false; + + if (soldier.num === 0) + { + soldier.tint = 0xFF00FF; + soldier.i = player1_square.i; + soldier.j = player1_square.j; + } + if (soldier.num === 1) + { + soldier.tint = 0xCCCC00; + soldier.i = player2_square.i; + soldier.j = player2_square.j; + } + + soldier.inputEnabled = true; + soldier.events.onInputDown.add( clickUnit, this ); + } + + function createSniper(sniper, num) + { + sniper.type = 'sniper'; + sniper.hp = 1; + sniper.atk = 1; + sniper.range = 1; + sniper.move = 1; + sniper.cost = 2; + sniper.diagonal = true; + sniper.num = num; + sniper.moved = false; + + if (sniper.num === 0) + { + sniper.tint = 0xFF00FF; + sniper.i = player1_square.i; + sniper.j = player1_square.j; + } + if (sniper.num === 1) + { + sniper.tint = 0xCCCC00; + sniper.i = player2_square.i; + sniper.j = player2_square.j; + } + + sniper.inputEnabled = true; + sniper.events.onInputDown.add( clickUnit, this ); + } + + function createTank(tank, num) + { + tank.type = 'tank'; + tank.hp = 5; + tank.atk = 1; + tank.range = 1; + tank.move = 1; + tank.cost = 4; + tank.diagonal = true; + tank.num = num; + tank.moved = false; + + if (tank.num === 0) + { + tank.tint = 0xFF00FF; + tank.i = player1_square.i; + tank.j = player1_square.j; + } + if (tank.num === 1) + { + tank.tint = 0xCCCC00; + tank.i = player2_square.i; + tank.j = player2_square.j; + } + + tank.inputEnabled = true; + tank.events.onInputUp.add( clickUnit, this ); + } + + function createTurret(turret, num) + { + turret.type = 'turret'; + turret.hp = 3; + turret.atk = 2; + turret.range = 1; + turret.move = 0; + turret.cost = 1; + turret.diagonal = true; + turret.num = num; + turret.moved = false; + + if (turret.num === 0) + { + turret.tint = 0xFF00FF; + } + if (turret.num === 1) + { + turret.tint = 0xCCCC00; + } + + turret.inputEnabled = true; + turret.events.onInputDown.add( clickUnit, this ); + } + + function createSquare(square, i, j) + { + square.items = game.add.group(); + square.items.visible = false; + square.i = i; + square.j = j; + square.inputEnabled = true; + square.events.onInputDown.add( clickSquare, this ); + } + + function createGrid() + { + grid = new Array(4); + + for (let i = 0; i < grid.length; i++) + { + grid[i] = new Array(grid.length); + + for (let j = 0; j < grid[i].length; j++) + { + if (i === 0 && j === 1) + { + grid[i][j] = game.add.image(0 + 110 * j, 150 + 110 * i, 'gridA'); + createSquare(grid[i][j], i , j); + player1_square = grid[i][j]; + } + else if (i === 3 && j === 2) + { + grid[i][j] = game.add.image(0 + 110 * j, 150 + 110 * i, 'gridB'); + createSquare(grid[i][j], i , j); + player2_square = grid[i][j]; + } + else + { + grid[i][j] = game.add.image(0 + 110 * j, 150 + 110 * i, 'grid'); + createSquare(grid[i][j]); + } + } + } + } + + function buySoldier() + { + if (player.money > 0) + { + player.money -= 1; + soldier = player.square.items.create(400 + x_count, 100, 'char', 7); + createSoldier(soldier, player.num); + x_count += 20; + event_msg3.setText('Total money: ' + player.money); + event_msg4.setText('Purchasing a soldier.'); + } + else + { + event_msg4.setText('Not enough money to buy a soldier.'); + } + } + + function buySniper() + { + if (player.money > 1) + { + player.money -= 2; + sniper = player.square.items.create(400 + x_count, 100, 'char', 1); + createSniper(sniper, player.num); + x_count += 20; + event_msg3.setText('Total money: ' + player.money); + event_msg4.setText('Purchasing a sniper.'); + } + else + { + event_msg4.setText('Not enough money to buy a sniper.'); + } + } + + function buyTank() + { + if (player.money > 3) + { + player.money -= 4; + tank = player.square.items.create(400 + x_count, 100, 'tank', 0); + tank.scale.setTo(0.5, 0.5); + createTank(tank, player.num); + x_count += 20; + event_msg3.setText('Total money: ' + player.money); + event_msg4.setText('Purchasing a tank.'); + } + else + { + event_msg4.setText('Not enough money to buy a tank.'); + } + } + + function buyTurret() + { + if (player.money > 0) + { + player.money -= 1; + player.turret++; + turret = player.square.items.create(400 + x_count, 100, 'turret'); + turret.scale.setTo(0.5, 0.5); + createTurret(turret, player.num); + x_count += 20; + event_msg3.setText('Total money: ' + player.money); + event_msg4.setText('Constructing a turret.'); + } + else + { + event_msg4.setText('Not enough money to buy a turret.'); + } + } + + function issueAttack() + { + //console.log('issueAttack'); + if (move === true) + { + resetMove(); + } + + if (selected !== null) + { + if (attack === false) + { + attack = true; + attack_button.tint = 0xFFFF00; + //attack_button.loadTexture('attack', 1); + console.log('A is down'); + } + else + { + resetAttack(); + console.log('A is up'); + } + } + } + + function issueMove() + { + if (attack === true) + { + resetAttack(); + } + + if (selected !== null) + { + if (move === false) + { + move = true; + move_button.tint = 0xFFFF00; + console.log('move'); + } + else + { + resetMove(); + } + } + } + + function resetUnit() + { + resetAttack(); + resetMove(); + if (selected_square !== null) + { + selected_square.tint = 0xFFFFFF; + selected_square.items.visible = false; + } + if (selected !== null) + { + if (selected.num === 0) + { + selected.tint = 0xFF00FF; + } + if (selected.num === 1) + { + selected.tint = 0xCCCC00; + } + } + selected_square = null; + selected = null; + stat_msg2.setText(''); + unit_msg2.setText('null'); + } + + // call this function when attack is true and need to swap to false; + function resetAttack() + { + attack = false; + attack_button.tint = 0xFFFFFF; + //attack_button.loadTexture('attack', 0); + } + + // call this function when move is true and need to swap back to false. + function resetMove() + { + move = false; + move_button.tint = 0xFFFFFF; + } + + function swapTurn() + { + resetUnit(); + + // change player turn to the next person in the group. + if (player_turn + 1 < player_array.length) + { + player = player_array[player_turn + 1]; + player_turn = player.num; + } + else + { + player = player_array[0]; + player_turn = player.num; + } + + startTurn(); + } + + function startTurn() + { + let income = 2 + Math.floor(player.turret / 2); + player.money += income; + + event_msg.setText('Player ' + (player_turn + 1) + '\'s turn'); + event_msg2.setText('Income: ' + income); + event_msg3.setText('Total money: ' + player.money); + event_msg4.setText(''); + } + + /* + function quitGame() + { + // Here you should destroy anything you no longer need. + // Stop music, delete sprites, purge caches, free resources, all that good stuff. + + // Then let's go back to the main menu. + game.state.start('MainMenu'); + + } + + function bossFight() + { + + if (shared.stat_remain === 0) + { + game.state.start('Boss'); + } + else + { + stat_msg2.setText("Consume all your stat points before\nfighting the boss.") + } + } + */ + + // function called when square is clicked. Action depends on the state of the game. + function clickSquare(square) + { + console.log(square); + console.log(square.j); + /// check if a unit is selected and the move option is enabled. + if (selected !== null && move === true) + { + if (selected.moved === true) + { + event_msg4.setText('This unit has already moved this turn.'); + resetMove(); + } + else + { + let x = Math.hypot((selected.i - square.i), (selected.j - square.j)); + console.log(selected.i); + console.log(selected.j); + console.log(square.i); + console.log(square.j); + + switch(selected.type) + { + case 'soldier': + if (x <= 1) + { + moveUnit(square); + event_msg4.setText('Moving to ' + selected.i + ', ' + selected.j); + resetMove(); + } + else + { + console.log(x); + event_msg4.setText('That square is too far away.'); + resetMove(); + } + break; + case 'sniper': + if (x <= 1) + { + moveUnit(square); + event_msg4.setText('Moving to ' + selected.i + ', ' + selected.j); + resetMove(); + } + else + { + event_msg4.setText('That square is too far away.'); + resetMove(); + } + break; + case 'tank': + if (x <= 1) + { + moveUnit(square); + event_msg4.setText('Moving to ' + selected.i + ', ' + selected.j); + resetMove(); + } + else + { + event_msg4.setText('That square is too far away.'); + resetMove(); + } + break; + case 'turret': + event_msg4.setText('This unit can\'t move.'); + break + default: + break; + } + } + } + // Get a reference to the square that has just been selected and make the state of the square visible. + else + { + if (selected_square !== null) + { + selected_square.items.visible = false; + selected_square.tint = 0xFFFFFF; + } + + selected_square = square; + selected_square.items.visible = true; + selected_square.tint = 0x999999; + } + } + + function moveUnit(square) + { + selected.moved = true; + selected.i = square.i; + selected.j = square.j; + selected_square.items.remove(selected); + square.items.add(selected); + } + + function clickUnit(unit) + { + //console.log('clickUnit'); + //console.log(attack); + + /// check if there is no unit selected or if there is no attack/move command issued. + /// change the selected unit if the above is true. + if (selected === null || (attack === false && move === false)) + { + if (selected !== null) + { + if (selected.num === 0) + { + selected.tint = 0xFF00FF; + } + if (selected.num === 1) + { + selected.tint = 0xCCCC00; + } + } + selected = unit; + selected.tint = 0xFFFFFF; + stat_msg2.setText('\n' + unit.hp + '\n' + unit.atk + '\n' + unit.range + '\n' + unit.move + '\n' + unit.cost); + unit_msg2.setText(unit.type); + } + else if (attack === true) + { + if (selected.num !== player.num) + { + event_msg4.setText('Can\'t attack with opponent\'s unit.'); + resetAttack(); + } + else if (selected === unit) + { + event_msg4.setText('Can\'t attack yourself.'); + resetAttack(); + } + else if (selected.num === unit.num) + { + event_msg4.setText('Can\'t attack your allies.'); + resetAttack(); + } + else + { + let x = Math.hypot((selected.i - unit.i), (selected.j - unit.j)); + + switch (selected.type) + { + case 'soldier': + console.log('soldier'); + console.log(x); + if (x <= 1) + { + dealDamage(selected, unit); + event_msg4.setText('Attacking ' + unit.type); + resetAttack(); + } + else + { + event_msg4.setText('That unit is too far away.'); + resetAttack(); + } + break; + case 'sniper': + console.log('sniper'); + console.log(x); + if (x <= 2) + { + dealDamage(selected, unit); + event_msg4.setText('Attacking ' + unit.type); + resetAttack(); + } + else + { + event_msg4.setText('That unit is too far away.'); + resetAttack(); + } + break; + case 'tank': + console.log('tank'); + console.log(x); + if (x <= 1.5) + { + dealDamage(selected, unit); + event_msg4.setText('Attacking ' + unit.type); + resetAttack(); + } + else + { + event_msg4.setText('That unit is too far away.'); + resetAttack(); + } + break; + case 'turret': + console.log('turret'); + console.log(x); + if (x <= 1.5) + { + dealDamage(selected, unit); + event_msg4.setText('Attacking ' + unit.type); + resetAttack(); + } + else + { + event_msg4.setText('That unit is too far away.'); + resetAttack(); + } + break; + default: + break; + } + } + } + } + + function dealDamage(arg1, arg2) + { + console.log(arg1 + ' Deal Damage to ' + arg2); + arg2.hp -= arg1.atk; + if (arg2.hp <= 0) + { + let id = arg2.num; + player_array[id].turret--; + arg2.destroy(); + } + } + + function pauseGame() + { + //console.log('pauseGame'); + game.state.start('Pause'); + } + + return { + + create: function () + { + console.log('Test Game'); + + // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! + game.add.tileSprite(0, 0, 1024, 700, 'background'); + game.world.setBounds(0, 0, 1024, 700); + + createGrid(); + + stat_msg = game.add.text(450, 300, 'Stats\nHP: \nAttack: \nRange: \nMovement: \nCost:'); + stat_msg2 = game.add.text(600, 300 , ''); + + unit_msg = game.add.text (450, 520, 'Selected: '); + unit_msg2 = game.add.text (600, 520); + + event_msg = game.add.text(0, 0, 'Event MSG1'); + event_msg2 = game.add.text(0, 40, 'Event MSG2'); + event_msg3 = game.add.text(210, 40, 'Event MSG3'); + event_msg4 = game.add.text(0, 80, ''); + + moved_group = game.add.group(); + player_array = []; + player = new createPlayer(player1_square, 0); + player_array.push(player); + player = new createPlayer(player2_square, 1); + player_array.push(player); + + player = player_array[0]; + player_turn = player.num; + + // Set the starting player as player 1. + startTurn(); + + buy1_button = game.add.button(0, 600, 'buy', buySoldier, this); + buy2_button = game.add.button(140, 600, 'buy', buySniper, this); + buy3_button = game.add.button(280, 600, 'buy', buyTank, this); + buy4_button = game.add.button(420, 600, 'buy', buyTurret, this); + + end_button = game.add.button(560, 600, 'end', swapTurn); + + attack_button = game.add.sprite(550, 200, 'attack', 0); + move_button = game.add.sprite(650, 200, 'move', 0); + + a_key = game.input.keyboard.addKey(Phaser.Keyboard.A); + m_key = game.input.keyboard.addKey(Phaser.Keyboard.M); + p_key = game.input.keyboard.addKey(Phaser.Keyboard.P); + esc_key = game.input.keyboard.addKey(Phaser.Keyboard.ESC); + space_key = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); + + a_key.onDown.add(issueAttack, this); + m_key.onDown.add(issueMove, this); + p_key.onDown.add(pauseGame, this); + esc_key.onDown.add(resetUnit, this); + }, + + update: function () + { + // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! + } + }; +}; diff --git a/Iteration Sequence 2.2/js/Game2.js b/Iteration Sequence 2.2/js/Game2.js new file mode 100644 index 000000000..b5e8da83a --- /dev/null +++ b/Iteration Sequence 2.2/js/Game2.js @@ -0,0 +1,466 @@ +"use strict"; + +GameStates.makeGame = function( game, shared ) { + // Create your own variables. + var grid; + var attack = false; + var move = false; + var attack_button; + var move_button; + + var soldier; + var sniper; + var tank; + var turret; + + var selected = null; + var selected_square = null; + + var esc_key; + var space_key; + var a_key; + var m_key; + var p_key; + + var player1_square; + var player2_square; + + var player; + var player_turn; + var player_array; + + var buy1_button; + var buy2_button; + var buy3_button; + var buy4_button; + var end_button; + + var x_count = 50; + + var txt_style = {font: "20px Arial"}; + var stat_msg; + var stat_msg2; + var unit_msg; + var unit_msg2; + var event_msg; + var event_msg2; + + function createPlayer(square, num) + { + this.num = num; + this.money = 0; + this.turn = false; + this.turret = game.add.group(); + this.square = square; + } + + function createSoldier(soldier) + { + soldier.type = 'soldier'; + soldier.hp = 2; + soldier.atk = 1; + soldier.range = 1; + soldier.move = 1; + soldier.cost = 1; + + soldier.inputEnabled = true; + soldier.events.onInputDown.add( clickUnit, this ); + } + + function createSniper(sniper) + { + sniper.type = 'sniper'; + sniper.hp = 1; + sniper.atk = 1; + sniper.range = 1; + sniper.move = 1; + sniper.cost = 2; + sniper.diagonal = true; + + sniper.inputEnabled = true; + sniper.events.onInputDown.add( clickUnit, this ); + } + + function createTank(tank) + { + tank.type = 'tank'; + tank.hp = 5; + tank.atk = 1; + tank.range = 1; + tank.move = 1; + tank.cost = 4; + tank.diagonal = true; + + tank.inputEnabled = true; + tank.events.onInputUp.add( clickUnit, this ); + } + + function createTurret(turret) + { + turret.type = 'turret'; + turret.hp = 3; + turret.atk = 2; + turret.range = 1; + turret.move = 0; + turret.cost = 1; + turret.diagonal = true; + + turret.inputEnabled = true; + turret.events.onInputDown.add( clickUnit, this ); + } + + function createSquare(square, i, j) + { + square.items = game.add.group(); + square.items.visible = false; + square.i = i; + square.j = j; + square.inputEnabled = true; + square.events.onInputDown.add( clickSquare, this ); + } + + function createGrid() + { + grid = new Array(4); + + for (let i = 0; i < grid.length; i++) + { + grid[i] = new Array(grid.length); + + for (let j = 0; j < grid[i].length; j++) + { + if (i === 0 && j === 1) + { + grid[i][j] = game.add.image(0 + 110 * j, 150 + 110 * i, 'gridA'); + createSquare(grid[i][j], i , j); + player1_square = grid[i][j]; + } + else if (i === 3 && j === 2) + { + grid[i][j] = game.add.image(0 + 110 * j, 150 + 110 * i, 'gridB'); + createSquare(grid[i][j], i , j); + player2_square = grid[i][j]; + } + else + { + grid[i][j] = game.add.image(0 + 110 * j, 150 + 110 * i, 'grid'); + createSquare(grid[i][j]); + } + } + } + } + + function buySoldier() + { + if (player.money > 0) + { + player.money -= 1; + soldier = player.square.items.create(400 + x_count, 100, 'char', 7); + createSoldier(soldier); + x_count += 20; + } + } + + function buySniper() + { + if (player.money > 1) + { + player.money -= 2; + sniper = player.square.items.create(400 + x_count, 100, 'char', 1); + createSniper(sniper); + x_count += 20; + } + } + + function buyTank() + { + if (player.money > 3) + { + player.money -= 4; + tank = player.square.items.create(400 + x_count, 100, 'tank', 1); + tank.scale.setTo(0.5, 0.5); + createTank(tank); + x_count += 20; + } + } + + function buyTurret() + { + if (player.money > 0) + { + player.money -= 1; + turret = player.square.items.create(400 + x_count, 100, 'turret'); + turret.scale.setTo(0.5, 0.5); + createTurret(turret); + x_count += 20; + } + } + + function issueAttack() + { + //console.log('issueAttack'); + if (move === true) + { + resetMove(); + } + + if (selected !== null) + { + if (attack === false) + { + attack = true; + attack_button.tint = 0xFFFF00; + //attack_button.loadTexture('attack', 1); + console.log('A is down'); + } + else + { + resetAttack(); + console.log('A is up'); + } + } + } + + function issueMove() + { + if (attack === true) + { + resetAttack(); + } + + if (selected !== null) + { + if (move === false) + { + move = true; + move_button.tint = 0xFFFF00; + console.log('move'); + } + else + { + resetMove(); + } + } + } + + function resetUnit() + { + resetAttack(); + resetMove(); + selected_square = null; + selected = null; + stat_msg2.setText(''); + unit_msg2.setText('null'); + } + + // call this function when attack is true and need to swap to false; + function resetAttack() + { + attack = false; + attack_button.tint = 0xFFFFFF; + //attack_button.loadTexture('attack', 0); + } + + // call this function when move is true and need to swap back to false. + function resetMove() + { + move = false; + move_button.tint = 0xFFFFFF; + } + + function swapTurn() + { + player.square.items.visible = false; + selected = null; + stat_msg2.setText(''); + unit_msg2.setText('null'); + + // change player turn to the next person in the group. + if (player_turn + 1 < player_array.length) + { + player = player_array[player_turn + 1]; + player_turn = player.num; + } + else + { + player = player_array[0]; + player_turn = player.num; + } + + startTurn(); + } + + function startTurn() + { + let income = 2 + (player.turret.children.length / 2); + player.money += income; + + selected_square = player.sqaure; + player.square.items.visible = true; + + event_msg.setText('Player ' + (player_turn + 1) + '\'s turn'); + event_msg2.setText('Starting income: ' + income + '\nTotal money: ' + player.money); + } + + /* + function quitGame() + { + // Here you should destroy anything you no longer need. + // Stop music, delete sprites, purge caches, free resources, all that good stuff. + + // Then let's go back to the main menu. + game.state.start('MainMenu'); + + } + + function bossFight() + { + + if (shared.stat_remain === 0) + { + game.state.start('Boss'); + } + else + { + stat_msg2.setText("Consume all your stat points before\nfighting the boss.") + } + } + */ + + // function called when square is clicked. Action depends on the state of the game. + function clickSquare(square) + { + /// check if a unit is selected and the move option is enabled. + if (selected !== null && move === true) + { + moveUnit(square); + resetMove(); + } + // Get a reference to the square that has just been selected and make the state of the square visible. + else if (selected_square !== null) + { + selected_square.items.visible = false; + } + + selected_square = square; + selected_square.items.visible = true; + + } + + function moveUnit(square) + { + selected_square.items.remove(selected); + square.items.add(selected); + } + + function clickUnit(unit) + { + //console.log('clickUnit'); + //console.log(attack); + + /// check if there is no unit selected or if there is no attack/move command issued. + /// change the selected unit if the above is true. + if (selected === null || (attack === false && move === false)) + { + selected = unit; + stat_msg2.setText(unit.type + '\n' + unit.hp + '\n' + unit.atk + '\n' + unit.range + '\n' + unit.move + '\n' + unit.cost); + unit_msg2.setText(unit.type); + } + else if (attack === true) + { + if (selected === unit) + { + event_msg.setText('Can\'t attack yourself.'); + resetAttack(); + } + else + { + dealDamage(selected, unit); + event_msg.setText('Attacking ' + unit.type); + resetAttack(); + } + } + } + + function checkRange(arg1, arg2) + { + + } + + function dealDamage(arg1, arg2) + { + console.log(arg1 + ' Deal Damage to ' + arg2); + arg2.hp -= arg1.atk; + if (arg2.hp <= 0) + { + arg2.destroy(); + } + } + + function pauseGame() + { + //console.log('pauseGame'); + game.state.start('Pause'); + } + + return { + + create: function () + { + console.log('Test Game'); + + // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! + game.add.tileSprite(0, 0, 1024, 700, 'background'); + game.world.setBounds(0, 0, 1024, 700); + + createGrid(); + + stat_msg = game.add.text(450, 300, 'Stats\nHP: \nAttack: \nRange: \nMovement: \nCost:'); + stat_msg2 = game.add.text(600, 300 , 'Test'); + + unit_msg = game.add.text (450, 520, 'Selected: '); + unit_msg2 = game.add.text (600, 520); + + event_msg = game.add.text(0, 0, 'Event MSG1'); + event_msg2 = game.add.text(0, 50, 'Event MSG2'); + + player_array = []; + player = new createPlayer(player1_square, 0); + player_array.push(player); + player = new createPlayer(player2_square, 1); + player_array.push(player); + + player = player_array[0]; + player_turn = player.num; + + // Set the starting player as player 1. + startTurn(); + + buy1_button = game.add.button(0, 600, 'buy', buySoldier, this); + buy2_button = game.add.button(140, 600, 'buy', buySniper, this); + buy3_button = game.add.button(280, 600, 'buy', buyTank, this); + buy4_button = game.add.button(420, 600, 'buy', buyTurret, this); + + end_button = game.add.button(560, 600, 'end', swapTurn); + + attack_button = game.add.sprite(550, 200, 'attack', 0); + move_button = game.add.sprite(650, 200, 'move', 0); + + a_key = game.input.keyboard.addKey(Phaser.Keyboard.A); + m_key = game.input.keyboard.addKey(Phaser.Keyboard.M); + p_key = game.input.keyboard.addKey(Phaser.Keyboard.P); + esc_key = game.input.keyboard.addKey(Phaser.Keyboard.ESC); + space_key = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); + + a_key.onDown.add(issueAttack, this); + m_key.onDown.add(issueMove, this); + p_key.onDown.add(pauseGame, this); + esc_key.onDown.add(resetUnit, this); + }, + + update: function () + { + // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! + } + }; +}; diff --git a/Iteration Sequence 2.2/js/MainMenu.js b/Iteration Sequence 2.2/js/MainMenu.js new file mode 100644 index 000000000..5616daf32 --- /dev/null +++ b/Iteration Sequence 2.2/js/MainMenu.js @@ -0,0 +1,41 @@ +"use strict"; + +GameStates.makeMainMenu = function( game, shared ) { + + var music = null; + var playButton = null; + + function startGame(pointer) + { + // Ok, the Play Button has been clicked or touched, so let's stop the music (otherwise it'll carry on playing) + //music.stop(); + console.log('Starting game'); + // And start the actual game + game.state.start('Game'); + } + + return { + + create: function () { + + // We've already preloaded our assets, so let's kick right into the Main Menu itself. + // Here all we're doing is playing some music and adding a picture and button + // Naturally I expect you to do something significantly better :) + + //music = game.add.audio('titleMusic'); + //music.play(); + + game.add.sprite(0, 0, 'preloaderBackground'); + playButton = game.add.button( 500, 300, 'playButton', startGame, null, 'out', 'over', 'down'); + playButton.anchor.setTo(0.5); + + }, + + update: function () { + + // Do some nice funky main menu effect here + + } + + }; +}; diff --git a/Iteration Sequence 2.2/js/Preloader.js b/Iteration Sequence 2.2/js/Preloader.js new file mode 100644 index 000000000..8d9cc7791 --- /dev/null +++ b/Iteration Sequence 2.2/js/Preloader.js @@ -0,0 +1,77 @@ +"use strict"; + +GameStates.makePreloader = function( game ) +{ + + var background = null; + var preloadBar = null; + + var ready = false; + + return { + + preload: function () + { + // These are the assets we loaded in Boot.js + // A nice sparkly background and a loading progress bar + background = game.add.sprite(0, 0, 'preloaderBackground'); + preloadBar = game.add.sprite(500, 300, 'preloaderBar'); + preloadBar.anchor.setTo(0.5); + + // This sets the preloadBar sprite as a loader sprite. + // What that does is automatically crop the sprite from 0 to full-width + // as the files below are loaded in. + game.load.setPreloadSprite(preloadBar); + + // Here we load the rest of the assets our game needs. + // As this is just a Project Template I've not provided these assets, swap them for your own. + game.load.atlas('playButton', 'assets/Play.png', 'assets/play_button.json'); + // + lots of other required assets here + + // My Assets + game.load.image('background','assets/background.png'); + //game.load.image('spot','assets/spot.png'); + game.load.image('grid','assets/grid.png'); + game.load.image('gridA','assets/grid_A.png'); + game.load.image('gridB','assets/grid_B.png'); + game.load.image('buy','assets/buy.png'); + game.load.image('end','assets/endTurn.png'); + + game.load.spritesheet('move', 'assets/Move.png', 80, 80); + game.load.spritesheet('attack', 'assets/Attack.png', 80, 80); + + game.load.spritesheet('char','assets/character.png', 32, 32); + game.load.spritesheet('tank','assets/tank.png', 92, 70); + game.load.image('turret','assets/Turret.png'); + + //game.load.spritesheet('tile','assets/sheet.png', 70, 70); + }, + + create: function () + { + // Once the load has finished we disable the crop because we're going to sit in the update loop for a short while as the music decodes + preloadBar.cropEnabled = false; + + }, + + update: function () + { + // You don't actually need to do this, but I find it gives a much smoother game experience. + // Basically it will wait for our audio file to be decoded before proceeding to the MainMenu. + // You can jump right into the menu if you want and still play the music, but you'll have a few + // seconds of delay while the mp3 decodes - so if you need your music to be in-sync with your menu + // it's best to wait for it to decode here first, then carry on. + + // If you don't have any music in your game then put the game.state.start line into the create function and delete + // the update function completely. + + + if (ready == false) + { + ready = true; + game.state.start('MainMenu'); + } + } + + }; +}; diff --git a/Iteration Sequence 2.2/js/game_boss.js b/Iteration Sequence 2.2/js/game_boss.js new file mode 100644 index 000000000..be45a9ec9 --- /dev/null +++ b/Iteration Sequence 2.2/js/game_boss.js @@ -0,0 +1,259 @@ +"use strict"; + +GameStates.makeBoss = function( game, shared ) { + // Create your own variables. + var boss_bg; + + var player; + var zombie; + var fire; + var boundaries; + + var stat_text; + var stat_text2; + var stat_text3; + var tip_text; + + var player_hp = 50; + var enemy_hp = 100; + var tookDamage = false; + var inputEnabled = false; + + /* + var timer; + var fire_group; + function Fire(game) { + + var x = 600; + var y = game.rnd.between(400, 600); + + Phaser.Sprite.call(this, game, x, y, 'fire', 1); + + game.physics.arcade.enable(this); + }*/ + + function returnMenu() { + + shared.stat_strength = 0; + shared.stat_resist = 0; + shared.stat_speed = 0; + shared.stat_luck = 0; + shared.stat_remain = 7; + + player_hp = 50; + enemy_hp = 100; + tookDamage = false; + inputEnabled = false; + + game.state.start('MainMenu'); + } + + function stopGravity(obj1, obj2) + { + obj1.body.gravity.y = 0; + //console.log(obj1.y); + } + + function dealDamage(obj1, obj2) + { + var bonusDamage; + switch (shared.stat_strength) + { + case 1: + bonusDamage = 1; + break; + case 2: + bonusDamage = 2; + break; + case 3: + bonusDamage = 4; + break; + default: + bonusDamage = 0; + break; + } + + enemy_hp = enemy_hp - 5 - bonusDamage; + + stat_text3.setText(enemy_hp); + zombieAttack(); + } + + function zombieAttack() + { + player.x = 100; + } + + function takeDamage(obj1, obj2) + { + var bonusResist; + + //console.log('TD: ' + tookDamage); + if (tookDamage == false) + { + //console.log('SSR: ' + shared.stat_resist); + switch (shared.stat_resist) + { + case 1: + bonusResist = 1; + break; + case 2: + bonusResist = 2; + break; + case 3: + bonusResist = 4; + break; + default: + bonusResist = 0; + break; + } + + //console.log('Player hp = ' + player_hp); + player_hp = player_hp - (8 - bonusResist); + //console.log('Collision: hp = ' + player_hp); + stat_text2.setText(player_hp); + tookDamage = true; + fire.body.checkCollision.none = true; + } + + } + + /* + function spawnFire() + { + fire_group.add(new Fire(game)); + } + */ + + return { + + create: function () { + + boss_bg = game.add.tileSprite(0, 0, 1000, 600, 'boss_bg'); + //game.add.tileSprite(0, 0, 300, 250, 'stat'); + //game.add.tileSprite(400, 0, 300, 250, 'stat'); + //stat_text = game.add.text(0, 0, 'Hit Points:\nStrength: \nResistance: \nSpeed: \nLuck: '); + //stat_text2 = game.add.text(250, 0, player_hp + '\n' + shared.stat_strength + '\n' + shared.stat_resist + '\n' + shared.stat_speed + '\n' + shared.stat_luck); + stat_text = game.add.text(0, 0, 'Hit Points: '); + stat_text2 = game.add.text(250, 0, player_hp); + tip_text = game.add.text(0, 150, 'Use the arrow keys to move and jump.\nCollide with the zombie to deal damage.\nPlayers will lose hp if they collide with the fire.'); + + game.add.text(600, 0, 'Hit Points: '); + stat_text3 = game.add.text(750, 0, enemy_hp); + + zombie = game.add.sprite(700, 450, 'zombie', 0); + zombie.anchor.setTo(0.5, 0.5); + zombie.scale.setTo(1, 1); + + player = game.add.sprite(100, 450, 'man', 0); + player.anchor.setTo(0.5, 0.5); + player.scale.setTo(1, 1); + + zombie.animations.add('run', [6,7,8,12,13,14]) + zombie.animations.play('run', 8, true); + + player.animations.add('run', [0,9]); + player.animations.play('run', 8, true); + + boundaries = game.add.sprite(0, 510, 'boundaries', 0); + + fire = game.add.sprite(600, 450, 'fire', 0); + + game.physics.startSystem(Phaser.Physics.ARCADE); + + // Set the world (global) gravity + game.physics.arcade.gravity.y = 1500; + + // Enable physics on those sprites + game.physics.enable( [ player, zombie, boundaries, fire ], Phaser.Physics.ARCADE); + + player.body.collideWorldBounds = true; + player.body.bounce.y = 0; + + zombie.body.allowGravity = false; + zombie.body.immovable = true; + zombie.body.collideWorldBounds = true; + //zombie.body.bounce.y = 0; + zombie.body.setSize(60, 85, 10, 25); + + + boundaries.body.allowGravity = false; + boundaries.body.collideWolrdBounds = true; + boundaries.visible = false; + boundaries.body.immovable = true; + + /* + timer = game.time.create(); + timer.loop(2000, spawnFire(), this); + fire_group = game.add.group(); + timer.start(); + */ + + fire.body.gravity.y = 0; + fire.body.allowGravity = false; + fire.body.velocity.x = -200; + fire.body.checkCollision.up = false; + fire.body.checkCollision.down = false; + + }, + + update: function () { + + player.body.velocity.x = 0; + fire.body.velocity.x = -200; + + game.physics.arcade.collide(player, boundaries, stopGravity, null, this); + game.physics.arcade.collide(zombie, boundaries, stopGravity, null, this); + game.physics.arcade.collide(player, fire, takeDamage, null, this); + game.physics.arcade.collide(player, zombie, dealDamage, null, this); + + + if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) + { + player.body.velocity.x = -(150 * (1 + shared.stat_speed)); + } + else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) + { + player.body.velocity.x = 150 * (1 + shared.stat_speed); + } + + if (game.input.keyboard.isDown(Phaser.Keyboard.UP) && player.y >= 455) + { + //player.body.gravity.y; + player.body.velocity.y = -500 - 50 * shared.stat_speed; + } + + if (fire.x < -200) + { + fire.x = 600; + tookDamage = false; + fire.body.checkCollision.none = false; + } + + if (player_hp <= 0 && inputEnabled == false) + { + tip_text.setText('You lose. Click ESC to return to main menu.'); + inputEnabled = true; + + } + else if (enemy_hp <= 0 && inputEnabled == false) + { + tip_text.setText('You win. Click ESC to return to main menu.'); + inputEnabled = true; + + } + + if (inputEnabled == true && game.input.keyboard.isDown(Phaser.Keyboard.ESC)) + { + returnMenu(); + } + + if (inputEnabled == true) + { + player.body.moves = false; + fire.body.moves = false; + } + + } + }; +}; diff --git a/Iteration Sequence 2.2/js/main.js b/Iteration Sequence 2.2/js/main.js new file mode 100644 index 000000000..994fe4ba0 --- /dev/null +++ b/Iteration Sequence 2.2/js/main.js @@ -0,0 +1,31 @@ +"use strict"; + +window.onload = function() +{ + + // Create your Phaser game and inject it into the 'game' div. + // We did it in a window.onload event, but you can do it anywhere (requireJS load, anonymous function, jQuery dom ready, - whatever floats your boat) + var game = new Phaser.Game( 1024, 700, Phaser.AUTO, 'game' ); + + // Add the States your game has. + // You don't have to do this in the html, it could be done in your Boot state too, but for simplicity I'll keep it here. + + // An object for shared variables, so that them main menu can show + // the high score if you want. + var shared = + { + stat_type: -1, + } + + game.state.add( 'Boot', GameStates.makeBoot( game ) ); + game.state.add( 'Preloader', GameStates.makePreloader( game ) ); + game.state.add( 'MainMenu', GameStates.makeMainMenu( game, shared ) ); + game.state.add( 'Game', GameStates.makeGame( game, shared ) ); + game.state.add( 'Boss', GameStates.makeBoss( game, shared ) ); + game.state.add( 'Pause', GameStates.makePause( game, shared ) ); + + + // Now start the Boot state. + game.state.start('Boot'); + +}; diff --git a/Iteration Sequence 2.2/js/pause.js b/Iteration Sequence 2.2/js/pause.js new file mode 100644 index 000000000..a09b111b7 --- /dev/null +++ b/Iteration Sequence 2.2/js/pause.js @@ -0,0 +1,40 @@ +"use strict"; + +GameStates.makePause = function( game, shared ) { + // Create your own variables. + var stat_text; + var instruction; + var txt_style = {fill: "#ffffff"}; + var tip_text; + + var esc_key; + + function returnGame() { + // Here you should destroy anything you no longer need. + // Stop music, delete sprites, purge caches, free resources, all that good stuff. + + // Then let's go back to the main menu. + game.state.start('Game'); + + } + + + + return { + + create: function () { + + stat_text = game.add.text(0, 0, 'Pause Screen', txt_style); + instruction = game.add.text(300, 0, 'Click ESC to return to Game.', txt_style); + tip_text = game.add.text(0, 300, 'TIPS' , txt_style); + + + esc_key = game.input.keyboard.addKey(Phaser.Keyboard.ESC); + esc_key.onDown.addOnce(returnGame, this); + }, + + update: function () { + + } + }; +}; diff --git a/Iteration Sequence 2.2/js/phaser.js b/Iteration Sequence 2.2/js/phaser.js new file mode 100644 index 000000000..3bac171a7 --- /dev/null +++ b/Iteration Sequence 2.2/js/phaser.js @@ -0,0 +1,107825 @@ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +* +* @overview +* +* Phaser - http://phaser.io +* +* v2.10.0 "2018-01-18" - Built: Thu Jan 18 2018 16:35:03 +* +* By Richard Davey http://www.photonstorm.com @photonstorm +* +* Phaser is a fun, free and fast 2D game framework for making HTML5 games +* for desktop and mobile web browsers, supporting Canvas and WebGL rendering. +* +* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23 +* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe +* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com +* +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate. +* +* Follow development at http://phaser.io and on our forum +* +* "If you want your children to be intelligent, read them fairy tales." +* "If you want them to be more intelligent, read them more fairy tales." +* -- Albert Einstein +*/ + +/** + * The MIT License (MIT) + * + * Copyright (c) 2015 p2.js authors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=0 && s<=1 && t>=0 && t<=1); +}; + + +},{"./Scalar":4}],2:[function(_dereq_,module,exports){ +module.exports = Point; + +/** + * Point related functions + * @class Point + */ +function Point(){}; + +/** + * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. + * @static + * @method area + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +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 = []; + +/** + * Check if three points are collinear + * @method collinear + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. + * @return {Boolean} + */ +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 angle < thresholdAngle; + } +}; + +Point.sqdist = function(a,b){ + var dx = b[0] - a[0]; + var dy = b[1] - a[1]; + return dx * dx + dy * dy; +}; + +},{}],3:[function(_dereq_,module,exports){ +var Line = _dereq_("./Line") +, Point = _dereq_("./Point") +, Scalar = _dereq_("./Scalar") + +module.exports = Polygon; + +/** + * Polygon class. + * @class Polygon + * @constructor + */ +function Polygon(){ + + /** + * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] + * @property vertices + * @type {Array} + */ + this.vertices = []; +} + +/** + * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. + * @method at + * @param {Number} i + * @return {Array} + */ +Polygon.prototype.at = function(i){ + var v = this.vertices, + s = v.length; + return v[i < 0 ? i % s + s : i % s]; +}; + +/** + * Get first vertex + * @method first + * @return {Array} + */ +Polygon.prototype.first = function(){ + return this.vertices[0]; +}; + +/** + * Get last vertex + * @method last + * @return {Array} + */ +Polygon.prototype.last = function(){ + return this.vertices[this.vertices.length-1]; +}; + +/** + * Clear the polygon data + * @method clear + * @return {Array} + */ +Polygon.prototype.clear = function(){ + this.vertices.length = 0; +}; + +/** + * Append points "from" to "to"-1 from an other polygon "poly" onto this one. + * @method append + * @param {Polygon} poly The polygon to get points from. + * @param {Number} from The vertex index in "poly". + * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. + * @return {Array} + */ +Polygon.prototype.append = function(poly,from,to){ + if(typeof(from) == "undefined") throw new Error("From is not given!"); + if(typeof(to) == "undefined") throw new Error("To is not given!"); + + if(to-1 < from) throw new Error("lol1"); + if(to > poly.vertices.length) throw new Error("lol2"); + if(from < 0) throw new Error("lol3"); + + for(var i=from; i v[br][0])) { + br = i; + } + } + + // reverse poly if clockwise + if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { + this.reverse(); + } +}; + +/** + * Reverse the vertices in the polygon + * @method 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; +}; + +/** + * Check if a point in the polygon is a reflex point + * @method isReflex + * @param {Number} i + * @return {Boolean} + */ +Polygon.prototype.isReflex = function(i){ + return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); +}; + +var tmpLine1=[], + tmpLine2=[]; + +/** + * Check if two vertices in the polygon can see each other + * @method canSee + * @param {Number} a Vertex index 1 + * @param {Number} b Vertex index 2 + * @return {Boolean} + */ +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) { // for each edge + if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges + 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))) { // if diag intersects an edge + 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) < dist) { // if edge is blocking visibility to b + return false; + } + } + } + + return true; +}; + +/** + * Copy the polygon from vertex i to vertex j. + * @method copy + * @param {Number} i + * @param {Number} j + * @param {Polygon} [targetPoly] Optional target polygon to save in. + * @return {Polygon} The resulting copy. + */ +Polygon.prototype.copy = function(i,j,targetPoly){ + var p = targetPoly || new Polygon(); + p.clear(); + if (i < j) { + // Insert all vertices from i to j + for(var k=i; k<=j; k++) + p.vertices.push(this.vertices[k]); + + } else { + + // Insert vertices 0 to j + for(var k=0; k<=j; k++) + p.vertices.push(this.vertices[k]); + + // Insert vertices i to end + for(var k=i; k 0) + return this.slice(edges); + else + return [this]; +}; + +/** + * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. + * @method slice + * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() + * @return {Array} + */ +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; i maxlevel){ + console.warn("quickDecomp: max level ("+maxlevel+") reached."); + return result; + } + + for (var i = 0; i < this.vertices.length; ++i) { + if (poly.isReflex(i)) { + reflexVertices.push(poly.vertices[i]); + upperDist = lowerDist = Number.MAX_VALUE; + + + for (var j = 0; j < this.vertices.length; ++j) { + if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge + p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection + if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly + d = Point.sqdist(poly.vertices[i], p); + if (d < lowerDist) { // keep only the closest intersection + lowerDist = d; + lowerInt = p; + lowerIndex = j; + } + } + } + if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); + if (Point.left(poly.at(i - 1), poly.at(i), p)) { + d = Point.sqdist(poly.vertices[i], p); + if (d < upperDist) { + upperDist = d; + upperInt = p; + upperIndex = j; + } + } + } + } + + // if there are no vertices to connect to, choose a point in the middle + if (lowerIndex == (upperIndex + 1) % this.vertices.length) { + //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); + p[0] = (lowerInt[0] + upperInt[0]) / 2; + p[1] = (lowerInt[1] + upperInt[1]) / 2; + steinerPoints.push(p); + + if (i < upperIndex) { + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); + lowerPoly.append(poly, i, upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + if (lowerIndex != 0){ + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); + upperPoly.append(poly,lowerIndex,poly.vertices.length); + } + //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); + lowerPoly.append(poly,i,poly.vertices.length); + } + //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); + lowerPoly.append(poly,0,upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); + upperPoly.append(poly,lowerIndex,i+1); + } + } else { + // connect to the closest point within the triangle + //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); + + if (lowerIndex > upperIndex) { + upperIndex += this.vertices.length; + } + closestDist = Number.MAX_VALUE; + + if(upperIndex < lowerIndex){ + return result; + } + + for (var j = lowerIndex; j <= upperIndex; ++j) { + if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + d = Point.sqdist(poly.at(i), poly.at(j)); + if (d < closestDist) { + closestDist = d; + closestIndex = j % this.vertices.length; + } + } + } + + if (i < closestIndex) { + lowerPoly.append(poly,i,closestIndex+1); + if (closestIndex != 0){ + upperPoly.append(poly,closestIndex,v.length); + } + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + lowerPoly.append(poly,i,v.length); + } + lowerPoly.append(poly,0,closestIndex+1); + upperPoly.append(poly,closestIndex,i+1); + } + } + + // solve smallest poly first + if (lowerPoly.vertices.length < upperPoly.vertices.length) { + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } else { + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } + + return result; + } + } + result.push(this); + + return result; +}; + +/** + * Remove collinear points in the polygon. + * @method removeCollinearPoints + * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. + * @return {Number} The number of points removed + */ +Polygon.prototype.removeCollinearPoints = function(precision){ + var num = 0; + for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ + if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ + // Remove the middle point + this.vertices.splice(i%this.vertices.length,1); + i--; // Jump one point forward. Otherwise we may get a chain removal + num++; + } + } + return num; +}; + +},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){ +module.exports = Scalar; + +/** + * Scalar functions + * @class Scalar + */ +function Scalar(){} + +/** + * Check if two scalars are equal + * @static + * @method eq + * @param {Number} a + * @param {Number} b + * @param {Number} [precision] + * @return {Boolean} + */ +Scalar.eq = function(a,b,precision){ + precision = precision || 0; + return Math.abs(a-b) < precision; +}; + +},{}],5:[function(_dereq_,module,exports){ +module.exports = { + Polygon : _dereq_("./Polygon"), + Point : _dereq_("./Point"), +}; + +},{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){ +module.exports={ + "name": "p2", + "version": "0.7.1", + "description": "A JavaScript 2D physics engine.", + "author": "Stefan Hedman (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.5", + "grunt-contrib-jshint": "^0.11.2", + "grunt-contrib-nodeunit": "^0.4.1", + "grunt-contrib-uglify": "~0.4.0", + "grunt-contrib-watch": "~0.5.0", + "grunt-browserify": "~2.0.1", + "grunt-contrib-concat": "^0.4.0" + }, + "dependencies": { + "poly-decomp": "0.1.1" + } +} + +},{}],7:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = AABB; + +/** + * Axis aligned bounding box class. + * @class AABB + * @constructor + * @param {Object} [options] + * @param {Array} [options.upperBound] + * @param {Array} [options.lowerBound] + */ +function AABB(options){ + + /** + * The lower bound of the bounding box. + * @property lowerBound + * @type {Array} + */ + this.lowerBound = vec2.create(); + if(options && options.lowerBound){ + vec2.copy(this.lowerBound, options.lowerBound); + } + + /** + * The upper bound of the bounding box. + * @property upperBound + * @type {Array} + */ + this.upperBound = vec2.create(); + if(options && options.upperBound){ + vec2.copy(this.upperBound, options.upperBound); + } +} + +var tmp = vec2.create(); + +/** + * Set the AABB bounds from a set of points, transformed by the given position and angle. + * @method setFromPoints + * @param {Array} points An array of vec2's. + * @param {Array} position + * @param {number} angle + * @param {number} skinSize Some margin to be added to the AABB. + */ +AABB.prototype.setFromPoints = function(points, position, angle, skinSize){ + var l = this.lowerBound, + u = this.upperBound; + + if(typeof(angle) !== "number"){ + angle = 0; + } + + // Set to the first point + if(angle !== 0){ + vec2.rotate(l, points[0], angle); + } else { + vec2.copy(l, points[0]); + } + vec2.copy(u, l); + + // Compute cosines and sines just once + var cosAngle = Math.cos(angle), + sinAngle = Math.sin(angle); + for(var i = 1; i u[j]){ + u[j] = p[j]; + } + if(p[j] < l[j]){ + l[j] = p[j]; + } + } + } + + // Add offset + if(position){ + vec2.add(this.lowerBound, this.lowerBound, position); + vec2.add(this.upperBound, this.upperBound, position); + } + + if(skinSize){ + this.lowerBound[0] -= skinSize; + this.lowerBound[1] -= skinSize; + this.upperBound[0] += skinSize; + this.upperBound[1] += skinSize; + } +}; + +/** + * Copy bounds from an AABB to this AABB + * @method copy + * @param {AABB} aabb + */ +AABB.prototype.copy = function(aabb){ + vec2.copy(this.lowerBound, aabb.lowerBound); + vec2.copy(this.upperBound, aabb.upperBound); +}; + +/** + * Extend this AABB so that it covers the given AABB too. + * @method extend + * @param {AABB} aabb + */ +AABB.prototype.extend = function(aabb){ + // Loop over x and y + var i = 2; + while(i--){ + // Extend lower bound + var l = aabb.lowerBound[i]; + if(this.lowerBound[i] > l){ + this.lowerBound[i] = l; + } + + // Upper + var u = aabb.upperBound[i]; + if(this.upperBound[i] < u){ + this.upperBound[i] = u; + } + } +}; + +/** + * Returns true if the given AABB overlaps this AABB. + * @method overlaps + * @param {AABB} aabb + * @return {Boolean} + */ +AABB.prototype.overlaps = function(aabb){ + var l1 = this.lowerBound, + u1 = this.upperBound, + l2 = aabb.lowerBound, + u2 = aabb.upperBound; + + // l2 u2 + // |---------| + // |--------| + // l1 u1 + + 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])); +}; + +/** + * @method containsPoint + * @param {Array} point + * @return {boolean} + */ +AABB.prototype.containsPoint = function(point){ + var l = this.lowerBound, + u = this.upperBound; + return l[0] <= point[0] && point[0] <= u[0] && l[1] <= point[1] && point[1] <= u[1]; +}; + +/** + * Check if the AABB is hit by a ray. + * @method overlapsRay + * @param {Ray} ray + * @return {number} -1 if no hit, a number between 0 and 1 if hit. + */ +AABB.prototype.overlapsRay = function(ray){ + var t = 0; + + // ray.direction is unit direction vector of ray + var dirFracX = 1 / ray.direction[0]; + var dirFracY = 1 / ray.direction[1]; + + // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner + var t1 = (this.lowerBound[0] - ray.from[0]) * dirFracX; + var t2 = (this.upperBound[0] - ray.from[0]) * dirFracX; + var t3 = (this.lowerBound[1] - ray.from[1]) * dirFracY; + var t4 = (this.upperBound[1] - ray.from[1]) * dirFracY; + + var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4))); + var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4))); + + // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us + if (tmax < 0){ + //t = tmax; + return -1; + } + + // if tmin > tmax, ray doesn't intersect AABB + if (tmin > tmax){ + //t = tmax; + return -1; + } + + return tmin; +}; +},{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Body = _dereq_('../objects/Body'); + +module.exports = Broadphase; + +/** + * Base class for broadphase implementations. + * @class Broadphase + * @constructor + */ +function Broadphase(type){ + + this.type = type; + + /** + * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). + * @property result + * @type {Array} + */ + this.result = []; + + /** + * The world to search for collision pairs in. To change it, use .setWorld() + * @property world + * @type {World} + * @readOnly + */ + this.world = null; + + /** + * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE. + * @property {Number} boundingVolumeType + */ + this.boundingVolumeType = Broadphase.AABB; +} + +/** + * Axis aligned bounding box type. + * @static + * @property {Number} AABB + */ +Broadphase.AABB = 1; + +/** + * Bounding circle type. + * @static + * @property {Number} BOUNDING_CIRCLE + */ +Broadphase.BOUNDING_CIRCLE = 2; + +/** + * Set the world that we are searching for collision pairs in. + * @method setWorld + * @param {World} world + */ +Broadphase.prototype.setWorld = function(world){ + this.world = world; +}; + +/** + * Get all potential intersecting body pairs. + * @method getCollisionPairs + * @param {World} world The world to search in. + * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). + */ +Broadphase.prototype.getCollisionPairs = function(world){}; + +var dist = vec2.create(); + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.aabbCheck = function(bodyA, bodyB){ + return bodyA.getAABB().overlaps(bodyB.getAABB()); +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether two bodies are allowed to collide at all. + * @method canCollide + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.canCollide = function(bodyA, bodyB){ + var KINEMATIC = Body.KINEMATIC; + var STATIC = Body.STATIC; + + // Cannot collide static bodies + if(bodyA.type === STATIC && bodyB.type === STATIC){ + return false; + } + + // Cannot collide static vs kinematic bodies + if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) || + (bodyA.type === STATIC && bodyB.type === KINEMATIC)){ + return false; + } + + // Cannot collide kinematic vs kinematic + if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){ + return false; + } + + // Cannot collide both sleeping bodies + if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ + return false; + } + + // Cannot collide if one is static and the other is sleeping + if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === STATIC) || + (bodyB.sleepState === Body.SLEEPING && bodyA.type === STATIC)){ + return false; + } + + return true; +}; + +Broadphase.NAIVE = 1; +Broadphase.SAP = 2; + +},{"../math/vec2":30,"../objects/Body":31}],9:[function(_dereq_,module,exports){ +var Circle = _dereq_('../shapes/Circle'), + Plane = _dereq_('../shapes/Plane'), + Shape = _dereq_('../shapes/Shape'), + Particle = _dereq_('../shapes/Particle'), + Broadphase = _dereq_('../collision/Broadphase'), + vec2 = _dereq_('../math/vec2'); + +module.exports = NaiveBroadphase; + +/** + * Naive broadphase implementation. Does N^2 tests. + * + * @class NaiveBroadphase + * @constructor + * @extends Broadphase + */ +function NaiveBroadphase(){ + Broadphase.call(this, Broadphase.NAIVE); +} +NaiveBroadphase.prototype = new Broadphase(); +NaiveBroadphase.prototype.constructor = NaiveBroadphase; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +NaiveBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = world.bodies, + result = this.result; + + result.length = 0; + + for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ + var bi = bodies[i]; + + for(var j=0; j pos0 && pos < pos1){ + // We got contact! + + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape); + + vec2.scale(c.normalA, orthoDist, -1); + vec2.normalize(c.normalA, c.normalA); + + vec2.scale( c.contactPointA, c.normalA, circleRadius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + sub(c.contactPointB, projectedPoint, lineOffset); + add(c.contactPointB, c.contactPointB, lineOffset); + sub(c.contactPointB, c.contactPointB, lineBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; + } + } + + // Add corner + verts[0] = worldVertex0; + verts[1] = worldVertex1; + + for(var i=0; i 0){ + for(var i=0; i Math.pow(r,2)){ + return 0; + } + + if(justTest){ + return true; + } + + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + 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; +}; + +/** + * Plane/Convex Narrowphase + * @method planeConvex + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} convexBody + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = +Narrowphase.prototype[Shape.PLANE | Shape.BOX] = +Narrowphase.prototype.planeConvex = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + convexBody, + convexShape, + convexOffset, + convexAngle, + justTest +){ + var worldVertex = tmp1, + worldNormal = tmp2, + dist = tmp3; + + var numReported = 0; + vec2.rotate(worldNormal, yAxis, planeAngle); + + for(var i=0; i!==convexShape.vertices.length; i++){ + var v = convexShape.vertices[i]; + vec2.rotate(worldVertex, v, convexAngle); + add(worldVertex, worldVertex, convexOffset); + + sub(dist, worldVertex, planeOffset); + + if(dot(dist,worldNormal) <= 0){ + + if(justTest){ + return true; + } + + // Found vertex + numReported++; + + var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); + + sub(dist, worldVertex, planeOffset); + + vec2.copy(c.normalA, worldNormal); + + var d = dot(dist, c.normalA); + vec2.scale(dist, c.normalA, d); + + // rj is from convex center to contact + sub(c.contactPointB, worldVertex, convexBody.position); + + + // ri is from plane center to contact + sub( c.contactPointA, worldVertex, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + this.contactEquations.push(c); + + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numReported){ + this.frictionEquations.push(this.createFrictionFromAverage(numReported)); + } + } + + return numReported; +}; + +/** + * Narrowphase for particle vs plane + * @method particlePlane + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = +Narrowphase.prototype.particlePlane = function( + particleBody, + particleShape, + particleOffset, + particleAngle, + planeBody, + planeShape, + planeOffset, + planeAngle, + justTest +){ + var dist = tmp1, + worldNormal = tmp2; + + planeAngle = planeAngle || 0; + + sub(dist, particleOffset, planeOffset); + vec2.rotate(worldNormal, yAxis, planeAngle); + + var d = dot(dist, worldNormal); + + if(d > 0){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape); + + vec2.copy(c.normalA, worldNormal); + vec2.scale( dist, c.normalA, d ); + // dist is now the distance vector in the normal direction + + // ri is the particle position projected down onto the plane, from the plane center + sub( c.contactPointA, particleOffset, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + // rj is from the body center to the particle center + sub( c.contactPointB, particleOffset, particleBody.position ); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + return 1; +}; + +/** + * Circle/Particle Narrowphase + * @method circleParticle + * @param {Body} circleBody + * @param {Circle} circleShape + * @param {Array} circleOffset + * @param {Number} circleAngle + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = +Narrowphase.prototype.circleParticle = function( + circleBody, + circleShape, + circleOffset, + circleAngle, + particleBody, + particleShape, + particleOffset, + particleAngle, + justTest +){ + var dist = tmp1; + + sub(dist, particleOffset, circleOffset); + if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape); + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + // Vector from circle to contact point is the normal times the circle radius + vec2.scale(c.contactPointA, c.normalA, circleShape.radius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + // Vector from particle center to contact point is zero + sub(c.contactPointB, particleOffset, particleBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; +}; + +var planeCapsule_tmpCircle = new Circle({ radius: 1 }), + planeCapsule_tmp1 = vec2.create(), + planeCapsule_tmp2 = vec2.create(), + planeCapsule_tmp3 = vec2.create(); + +/** + * @method planeCapsule + * @param {Body} planeBody + * @param {Circle} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} capsuleBody + * @param {Particle} capsuleShape + * @param {Array} capsuleOffset + * @param {Number} capsuleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = +Narrowphase.prototype.planeCapsule = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + capsuleBody, + capsuleShape, + capsuleOffset, + capsuleAngle, + justTest +){ + var end1 = planeCapsule_tmp1, + end2 = planeCapsule_tmp2, + circle = planeCapsule_tmpCircle, + dst = planeCapsule_tmp3; + + // Compute world end positions + vec2.set(end1, -capsuleShape.length/2, 0); + vec2.rotate(end1,end1,capsuleAngle); + add(end1,end1,capsuleOffset); + + vec2.set(end2, capsuleShape.length/2, 0); + vec2.rotate(end2,end2,capsuleAngle); + add(end2,end2,capsuleOffset); + + circle.radius = capsuleShape.radius; + + var enableFrictionBefore; + + // Temporarily turn off friction + if(this.enableFrictionReduction){ + enableFrictionBefore = this.enableFriction; + this.enableFriction = false; + } + + // Do Narrowphase as two circles + var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest), + numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest); + + // Restore friction + if(this.enableFrictionReduction){ + this.enableFriction = enableFrictionBefore; + } + + if(justTest){ + return numContacts1 || numContacts2; + } else { + var numTotal = numContacts1 + numContacts2; + if(this.enableFrictionReduction){ + if(numTotal){ + this.frictionEquations.push(this.createFrictionFromAverage(numTotal)); + } + } + return numTotal; + } +}; + +/** + * Creates ContactEquations and FrictionEquations for a collision. + * @method circlePlane + * @param {Body} bi The first body that should be connected to the equations. + * @param {Circle} si The circle shape participating in the collision. + * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. + * @param {Body} bj The second body that should be connected to the equations. + * @param {Plane} sj The Plane shape that is participating + * @param {Array} xj Extra offset for the plane shape. + * @param {Number} aj Extra angle to apply to the plane + */ +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, // Offset from body center, rotated! + planeBody = bj, + shapeB = sj, + planeOffset = xj, + planeAngle = aj; + + planeAngle = planeAngle || 0; + + // Vector from plane to circle + var planeToCircle = tmp1, + worldNormal = tmp2, + temp = tmp3; + + sub(planeToCircle, circleOffset, planeOffset); + + // World plane normal + vec2.rotate(worldNormal, yAxis, planeAngle); + + // Normal direction distance + var d = dot(worldNormal, planeToCircle); + + if(d > circleShape.radius){ + return 0; // No overlap. Abort. + } + + if(justTest){ + return true; + } + + // Create contact + var contact = this.createContactEquation(planeBody,circleBody,sj,si); + + // ni is the plane world normal + vec2.copy(contact.normalA, worldNormal); + + // rj is the vector from circle center to the contact point + vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); + add(contact.contactPointB, contact.contactPointB, circleOffset); + sub(contact.contactPointB, contact.contactPointB, circleBody.position); + + // ri is the distance from plane center to contact. + vec2.scale(temp, contact.normalA, d); + sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector + 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; +}; + +/** + * Convex/convex Narrowphase.See this article for more info. + * @method convexConvex + * @param {Body} bi + * @param {Convex} si + * @param {Array} xi + * @param {Number} ai + * @param {Body} bj + * @param {Convex} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CONVEX] = +Narrowphase.prototype[Shape.CONVEX | Shape.BOX] = +Narrowphase.prototype[Shape.BOX] = +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 = typeof(precision) === 'number' ? precision : 0; + + var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); + if(!found){ + return 0; + } + + // Make sure the separating axis is directed from shape i to shape j + sub(dist,xj,xi); + if(dot(sepAxis,dist) > 0){ + vec2.scale(sepAxis,sepAxis,-1); + } + + // Find edges with normals closest to the separating axis + var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis + closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); + + if(closestEdge1 === -1 || closestEdge2 === -1){ + return 0; + } + + // Loop over the shapes + 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){ + // Swap! + 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; + } + + // Loop over 2 points in convex B + for(var j=closestEdgeB; j= 3){ + + if(justTest){ + return true; + } + + // worldPoint was on the "inside" side of each of the 3 checked edges. + // Project it to the center edge and use the projection direction as normal + + // Create contact + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + numContacts++; + + // Get center edge from body A + var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], + v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; + + // Construct the edge + 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); // Normal points out of convex A + vec2.normalize(c.normalA,c.normalA); + + sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point + var d = dot(c.normalA,dist); // Penetration + vec2.scale(penetrationVec, c.normalA, d); // Vector penetration + + 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); + + // Todo reduce to 1 friction equation if we have 2 contact points + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numContacts){ + this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); + } + } + + return numContacts; +}; + +// .projectConvex is called by other functions, need local tmp vectors +var pcoa_tmp1 = vec2.fromValues(0,0); + +/** + * Project a Convex onto a world-oriented axis + * @method projectConvexOntoAxis + * @static + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Array} worldAxis + * @param {Array} result + */ +Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = pcoa_tmp1; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, worldAxis, -convexAngle); + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + // Project the position of the body onto the axis - need to add this to the result + var offset = dot(convexOffset, worldAxis); + + vec2.set( result, min + offset, max + offset); +}; + +// .findSeparatingAxis is called by other functions, need local tmp vectors +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); + +/** + * Find a separating axis between the shapes, that maximizes the separating distance between them. + * @method findSeparatingAxis + * @static + * @param {Convex} c1 + * @param {Array} offset1 + * @param {Number} angle1 + * @param {Convex} c2 + * @param {Array} offset2 + * @param {Number} angle2 + * @param {Array} sepAxis The resulting axis + * @return {Boolean} Whether the axis could be found. + */ +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; + + if(c1 instanceof Box && c2 instanceof Box){ + + for(var j=0; j!==2; j++){ + var c = c1, + angle = angle1; + if(j===1){ + c = c2; + angle = angle2; + } + + for(var i=0; i!==2; i++){ + + // Get the world edge + if(i === 0){ + vec2.set(normal, 0, 1); + } else if(i === 1) { + vec2.set(normal, 1, 0); + } + if(angle !== 0){ + vec2.rotate(normal, normal, angle); + } + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + + } else { + + 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++){ + // Get the world edge + vec2.rotate(worldPoint0, c.vertices[i], angle); + vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); + + sub(edge, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, edge); + vec2.normalize(normal,normal); + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + } + + + /* + // Needs to be tested some more + 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.axes.length; i++){ + + var normal = c.axes[i]; + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1); + Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + 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; +}; + +// .getClosestEdge is called by other functions, need local tmp vectors +var gce_tmp1 = vec2.fromValues(0,0) +, gce_tmp2 = vec2.fromValues(0,0) +, gce_tmp3 = vec2.fromValues(0,0); + +/** + * Get the edge that has a normal closest to an axis. + * @method getClosestEdge + * @static + * @param {Convex} c + * @param {Number} angle + * @param {Array} axis + * @param {Boolean} flip + * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. + */ +Narrowphase.getClosestEdge = function(c,angle,axis,flip){ + var localAxis = gce_tmp1, + edge = gce_tmp2, + normal = gce_tmp3; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, axis, -angle); + if(flip){ + vec2.scale(localAxis,localAxis,-1); + } + + var closestEdge = -1, + N = c.vertices.length, + maxDot = -1; + for(var i=0; i!==N; i++){ + // Get the edge + sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + 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(); + +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = +Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, + hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ + var data = hfShape.heights, + 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; + + // Get the index of the points to test against + var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), + idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); + + /*if(idxB < 0 || idxA >= data.length) + return justTest ? false : 0;*/ + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(circlePos[1]-radius > max){ + return justTest ? false : 0; + } + + /* + if(circlePos[1]+radius < min){ + // Below the minimum point... We can just guess. + // TODO + } + */ + + // 1. Check so center of circle is not inside the field. If it is, this wont work... + // 2. For each edge + // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) + // 2. 2. Check if point is inside. + + var found = false; + + // Check all edges first + for(var i=idxA; i= v0[0] && candidate[0] < v1[0] && d <= 0){ + + if(justTest){ + return true; + } + + found = true; + + // Store the candidate point, projected to the edge + vec2.scale(dist,worldNormal,-d); + vec2.add(minCandidate,candidate,dist); + vec2.copy(minCandidateNormal,worldNormal); + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Normal is out of the heightfield + vec2.copy(c.normalA, minCandidateNormal); + + // Vector from circle to heightfield + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + vec2.copy(c.contactPointA, minCandidate); + vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push( this.createFrictionFromContact(c) ); + } + } + } + + // Check all vertices + found = false; + if(radius > 0){ + for(var i=idxA; i<=idxB; i++){ + + // Get point + vec2.set(v0, i*w, data[i]); + vec2.add(v0,v0,hfPos); + + vec2.sub(dist, circlePos, v0); + + if(vec2.squaredLength(dist) < Math.pow(radius, 2)){ + + if(justTest){ + return true; + } + + found = true; + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Construct normal - out of heightfield + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + sub(c.contactPointA, v0, hfPos); + add(c.contactPointA, c.contactPointA, hfPos); + sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(found){ + return 1; + } + + return 0; + +}; + +var convexHeightfield_v0 = vec2.create(), + convexHeightfield_v1 = vec2.create(), + convexHeightfield_tilePos = vec2.create(), + convexHeightfield_tempConvexShape = new Convex({ vertices: [vec2.create(),vec2.create(),vec2.create(),vec2.create()] }); +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.BOX | Shape.HEIGHTFIELD] = +Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = +Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, + hfBody,hfShape,hfPos,hfAngle, justTest ){ + var data = hfShape.heights, + w = hfShape.elementWidth, + v0 = convexHeightfield_v0, + v1 = convexHeightfield_v1, + tilePos = convexHeightfield_tilePos, + tileConvex = convexHeightfield_tempConvexShape; + + // Get the index of the points to test against + var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), + idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(convexBody.aabb.lowerBound[1] > max){ + return justTest ? false : 0; + } + + var found = false; + var numContacts = 0; + + // Loop over all edges + // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape) + for(var i=idxA; i= 0 || aabb.containsPoint(this.from)){ + this.intersectBody(result, body); + } + } +}; + +var intersectBody_worldPosition = vec2.create(); + +/** + * Shoot a ray at a body, get back information about the hit. + * @method intersectBody + * @private + * @param {Body} body + */ +Ray.prototype.intersectBody = function (result, body) { + var checkCollisionResponse = this.checkCollisionResponse; + + if(checkCollisionResponse && !body.collisionResponse){ + return; + } + + var worldPosition = intersectBody_worldPosition; + + for (var i = 0, N = body.shapes.length; i < N; i++) { + var shape = body.shapes[i]; + + if(checkCollisionResponse && !shape.collisionResponse){ + continue; // Skip + } + + if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){ + continue; + } + + // Get world angle and position of the shape + vec2.rotate(worldPosition, shape.position, body.angle); + vec2.add(worldPosition, worldPosition, body.position); + var worldAngle = shape.angle + body.angle; + + this.intersectShape( + result, + shape, + worldAngle, + worldPosition, + body + ); + + if(result.shouldStop(this)){ + break; + } + } +}; + +/** + * @method intersectShape + * @private + * @param {Shape} shape + * @param {number} angle + * @param {array} position + * @param {Body} body + */ +Ray.prototype.intersectShape = function(result, shape, angle, position, body){ + var from = this.from; + + // Checking radius + var distance = distanceFromIntersectionSquared(from, this.direction, position); + if (distance > shape.boundingRadius * shape.boundingRadius) { + return; + } + + this._currentBody = body; + this._currentShape = shape; + + shape.raycast(result, this, position, angle); + + this._currentBody = this._currentShape = null; +}; + +/** + * Get the AABB of the ray. + * @method getAABB + * @param {AABB} aabb + */ +Ray.prototype.getAABB = function(result){ + var to = this.to; + var from = this.from; + vec2.set( + result.lowerBound, + Math.min(to[0], from[0]), + Math.min(to[1], from[1]) + ); + vec2.set( + result.upperBound, + Math.max(to[0], from[0]), + Math.max(to[1], from[1]) + ); +}; + +var hitPointWorld = vec2.create(); + +/** + * @method reportIntersection + * @private + * @param {number} fraction + * @param {array} normal + * @param {number} [faceIndex=-1] + * @return {boolean} True if the intersections should continue + */ +Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){ + var from = this.from; + var to = this.to; + var shape = this._currentShape; + var body = this._currentBody; + + // Skip back faces? + if(this.skipBackfaces && vec2.dot(normal, this.direction) > 0){ + return; + } + + switch(this.mode){ + + case Ray.ALL: + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + this.callback(result); + break; + + case Ray.CLOSEST: + + // Store if closer than current closest + if(fraction < result.fraction || !result.hasHit()){ + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + } + break; + + case Ray.ANY: + + // Report and stop. + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + break; + } +}; + +var v0 = vec2.create(), + intersect = vec2.create(); +function distanceFromIntersectionSquared(from, direction, position) { + + // v0 is vector from from to position + vec2.sub(v0, position, from); + var dot = vec2.dot(v0, direction); + + // intersect = direction * dot + from + vec2.scale(intersect, direction, dot); + vec2.add(intersect, intersect, from); + + return vec2.squaredDistance(position, intersect); +} + + +},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Ray = _dereq_('../collision/Ray'); + +module.exports = RaycastResult; + +/** + * Storage for Ray casting hit data. + * @class RaycastResult + * @constructor + */ +function RaycastResult(){ + + /** + * The normal of the hit, oriented in world space. + * @property {array} normal + */ + this.normal = vec2.create(); + + /** + * The hit shape, or null. + * @property {Shape} shape + */ + this.shape = null; + + /** + * The hit body, or null. + * @property {Body} body + */ + this.body = null; + + /** + * The index of the hit triangle, if the hit shape was indexable. + * @property {number} faceIndex + * @default -1 + */ + this.faceIndex = -1; + + /** + * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet. + * @property {number} fraction + * @default -1 + */ + this.fraction = -1; + + /** + * If the ray should stop traversing. + * @readonly + * @property {Boolean} isStopped + */ + this.isStopped = false; +} + +/** + * Reset all result data. Must be done before re-using the result object. + * @method reset + */ +RaycastResult.prototype.reset = function () { + vec2.set(this.normal, 0, 0); + this.shape = null; + this.body = null; + this.faceIndex = -1; + this.fraction = -1; + this.isStopped = false; +}; + +/** + * Get the distance to the hit point. + * @method getHitDistance + * @param {Ray} ray + */ +RaycastResult.prototype.getHitDistance = function (ray) { + return vec2.distance(ray.from, ray.to) * this.fraction; +}; + +/** + * Returns true if the ray hit something since the last reset(). + * @method hasHit + */ +RaycastResult.prototype.hasHit = function () { + return this.fraction !== -1; +}; + +/** + * Get world hit point. + * @method getHitPoint + * @param {array} out + * @param {Ray} ray + */ +RaycastResult.prototype.getHitPoint = function (out, ray) { + vec2.lerp(out, ray.from, ray.to, this.fraction); +}; + +/** + * Can be called while iterating over hits to stop searching for hit points. + * @method stop + */ +RaycastResult.prototype.stop = function(){ + this.isStopped = true; +}; + +/** + * @method shouldStop + * @private + * @param {Ray} ray + * @return {boolean} + */ +RaycastResult.prototype.shouldStop = function(ray){ + return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY); +}; + +/** + * @method set + * @private + * @param {array} normal + * @param {Shape} shape + * @param {Body} body + * @param {number} fraction + */ +RaycastResult.prototype.set = function( + normal, + shape, + body, + fraction, + faceIndex +){ + vec2.copy(this.normal, normal); + this.shape = shape; + this.body = body; + this.fraction = fraction; + this.faceIndex = faceIndex; +}; +},{"../collision/Ray":11,"../math/vec2":30}],13:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, Broadphase = _dereq_('../collision/Broadphase'); + +module.exports = SAPBroadphase; + +/** + * Sweep and prune broadphase along one axis. + * + * @class SAPBroadphase + * @constructor + * @extends Broadphase + */ +function SAPBroadphase(){ + Broadphase.call(this,Broadphase.SAP); + + /** + * List of bodies currently in the broadphase. + * @property axisList + * @type {Array} + */ + this.axisList = []; + + /** + * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance. + * @property axisIndex + * @type {Number} + */ + this.axisIndex = 0; + + var that = this; + this._addBodyHandler = function(e){ + that.axisList.push(e.body); + }; + + this._removeBodyHandler = function(e){ + // Remove from list + var idx = that.axisList.indexOf(e.body); + if(idx !== -1){ + that.axisList.splice(idx,1); + } + }; +} +SAPBroadphase.prototype = new Broadphase(); +SAPBroadphase.prototype.constructor = SAPBroadphase; + +/** + * Change the world + * @method setWorld + * @param {World} world + */ +SAPBroadphase.prototype.setWorld = function(world){ + // Clear the old axis array + this.axisList.length = 0; + + // Add all bodies from the new world + Utils.appendArray(this.axisList, world.bodies); + + // Remove old handlers, if any + world + .off("addBody",this._addBodyHandler) + .off("removeBody",this._removeBodyHandler); + + // Add handlers to update the list of bodies. + world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); + + this.world = world; +}; + +/** + * Sorts bodies along an axis. + * @method sortAxisList + * @param {Array} a + * @param {number} axisIndex + * @return {Array} + */ +SAPBroadphase.sortAxisList = function(a, axisIndex){ + axisIndex = axisIndex|0; + for(var i=1,l=a.length; 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.sortList = function(){ + var bodies = this.axisList, + axisIndex = this.axisIndex; + + // Sort the lists + SAPBroadphase.sortAxisList(bodies, axisIndex); +}; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +SAPBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = this.axisList, + result = this.result, + axisIndex = this.axisIndex; + + result.length = 0; + + // Update all AABBs if needed + var l = bodies.length; + while(l--){ + var b = bodies[l]; + if(b.aabbNeedsUpdate){ + b.updateAABB(); + } + } + + // Sort the lists + this.sortList(); + + // Look through the X list + for(var i=0, N=bodies.length|0; i!==N; i++){ + var bi = bodies[i]; + + for(var j=i+1; j G = [-n -rixn n rjxn] + + var r = vec2.create(); + var ri = vec2.create(); // worldAnchorA + var rj = vec2.create(); // worldAnchorB + var that = this; + normal.computeGq = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + xi = bodyA.position, + xj = bodyB.position; + + // Transform local anchors to world + vec2.rotate(ri, localAnchorA, bodyA.angle); + vec2.rotate(rj, localAnchorB, bodyB.angle); + + vec2.add(r, xj, rj); + vec2.sub(r, r, ri); + vec2.sub(r, r, xi); + + //vec2.sub(r, bodyB.position, bodyA.position); + return vec2.length(r) - that.distance; + }; + + // Make the contact constraint bilateral + this.setMaxForce(maxForce); + + /** + * If the upper limit is enabled or not. + * @property {Boolean} upperLimitEnabled + */ + this.upperLimitEnabled = false; + + /** + * The upper constraint limit. + * @property {number} upperLimit + */ + this.upperLimit = 1; + + /** + * If the lower limit is enabled or not. + * @property {Boolean} lowerLimitEnabled + */ + this.lowerLimitEnabled = false; + + /** + * The lower constraint limit. + * @property {number} lowerLimit + */ + this.lowerLimit = 0; + + /** + * Current constraint position. This is equal to the current distance between the world anchor points. + * @property {number} position + */ + this.position = 0; +} +DistanceConstraint.prototype = new Constraint(); +DistanceConstraint.prototype.constructor = DistanceConstraint; + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +var n = vec2.create(); +var ri = vec2.create(); // worldAnchorA +var rj = vec2.create(); // worldAnchorB +DistanceConstraint.prototype.update = function(){ + var normal = this.equations[0], + bodyA = this.bodyA, + bodyB = this.bodyB, + distance = this.distance, + xi = bodyA.position, + xj = bodyB.position, + normalEquation = this.equations[0], + G = normal.G; + + // Transform local anchors to world + vec2.rotate(ri, this.localAnchorA, bodyA.angle); + vec2.rotate(rj, this.localAnchorB, bodyB.angle); + + // Get world anchor points and normal + vec2.add(n, xj, rj); + vec2.sub(n, n, ri); + vec2.sub(n, n, xi); + this.position = vec2.length(n); + + var violating = false; + if(this.upperLimitEnabled){ + if(this.position > this.upperLimit){ + normalEquation.maxForce = 0; + normalEquation.minForce = -this.maxForce; + this.distance = this.upperLimit; + violating = true; + } + } + + if(this.lowerLimitEnabled){ + if(this.position < this.lowerLimit){ + normalEquation.maxForce = this.maxForce; + normalEquation.minForce = 0; + this.distance = this.lowerLimit; + violating = true; + } + } + + if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){ + // No constraint needed. + normalEquation.enabled = false; + return; + } + + normalEquation.enabled = true; + + vec2.normalize(n,n); + + // Caluclate cross products + var rixn = vec2.crossLength(ri, n), + rjxn = vec2.crossLength(rj, n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; +}; + +/** + * Set the max force to be used + * @method setMaxForce + * @param {Number} maxForce + */ +DistanceConstraint.prototype.setMaxForce = function(maxForce){ + var normal = this.equations[0]; + normal.minForce = -maxForce; + normal.maxForce = maxForce; +}; + +/** + * Get the max force + * @method getMaxForce + * @return {Number} + */ +DistanceConstraint.prototype.getMaxForce = function(){ + var normal = this.equations[0]; + return normal.maxForce; +}; + +},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, AngleLockEquation = _dereq_('../equations/AngleLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = GearConstraint; + +/** + * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB. + * @class GearConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for). + * @param {Number} [options.ratio=1] Gear ratio. + * @param {Number} [options.maxTorque] Maximum torque to apply. + * @extends Constraint + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB, { + * ratio: 2, + * maxTorque: 1000 + * }); + * world.addConstraint(constraint); + */ +function GearConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); + + /** + * The gear ratio. + * @property ratio + * @type {Number} + */ + this.ratio = options.ratio !== undefined ? options.ratio : 1; + + /** + * The relative angle + * @property angle + * @type {Number} + */ + this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle; + + // Send same parameters to the equation + options.angle = this.angle; + options.ratio = this.ratio; + + this.equations = [ + new AngleLockEquation(bodyA,bodyB,options), + ]; + + // Set max torque + if(options.maxTorque !== undefined){ + this.setMaxTorque(options.maxTorque); + } +} +GearConstraint.prototype = new Constraint(); +GearConstraint.prototype.constructor = GearConstraint; + +GearConstraint.prototype.update = function(){ + var eq = this.equations[0]; + if(eq.ratio !== this.ratio){ + eq.setRatio(this.ratio); + } + eq.angle = this.angle; +}; + +/** + * Set the max torque for the constraint. + * @method setMaxTorque + * @param {Number} torque + */ +GearConstraint.prototype.setMaxTorque = function(torque){ + this.equations[0].setMaxTorque(torque); +}; + +/** + * Get the max torque for the constraint. + * @method getMaxTorque + * @return {Number} + */ +GearConstraint.prototype.getMaxTorque = function(torque){ + return this.equations[0].maxForce; +}; +},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('../equations/Equation'); + +module.exports = LockConstraint; + +/** + * Locks the relative position and rotation between two bodies. + * + * @class LockConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions. + * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles. + * @param {number} [options.maxForce] + * @extends Constraint + * + * @example + * // Locks the relative position and rotation between bodyA and bodyB + * var constraint = new LockConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + */ +function LockConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); + + var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); + + var localAngleB = options.localAngleB || 0; + + // Use 3 equations: + // gx = (xj - xi - l) * xhat = 0 + // gy = (xj - xi - l) * yhat = 0 + // gr = (xi - xj + r) * that = 0 + // + // ...where: + // l is the localOffsetB vector rotated to world in bodyA frame + // r is the same vector but reversed and rotated from bodyB frame + // xhat, yhat are world axis vectors + // that is the tangent of r + // + // For the first two constraints, we get + // G*W = (vj - vi - ldot ) * xhat + // = (vj - vi - wi x l) * xhat + // + // Since (wi x l) * xhat = (l x xhat) * wi, we get + // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] + // + // The last constraint gives + // GW = (vi - vj + wj x r) * that + // = [ that 0 -that (r x t) ] + + var x = new Equation(bodyA,bodyB,-maxForce,maxForce), + y = new Equation(bodyA,bodyB,-maxForce,maxForce), + rot = new Equation(bodyA,bodyB,-maxForce,maxForce); + + var l = vec2.create(), + g = vec2.create(), + that = this; + x.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[0]; + }; + y.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[1]; + }; + var r = vec2.create(), + t = vec2.create(); + rot.computeGq = function(){ + vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); + vec2.scale(r,r,-1); + vec2.sub(g,bodyA.position,bodyB.position); + vec2.add(g,g,r); + vec2.rotate(t,r,-Math.PI/2); + vec2.normalize(t,t); + return vec2.dot(g,t); + }; + + /** + * The offset of bodyB in bodyA's frame. + * @property {Array} localOffsetB + */ + this.localOffsetB = vec2.create(); + if(options.localOffsetB){ + vec2.copy(this.localOffsetB, options.localOffsetB); + } else { + // Construct from current positions + vec2.sub(this.localOffsetB, bodyB.position, bodyA.position); + vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle); + } + + /** + * The offset angle of bodyB in bodyA's frame. + * @property {Number} localAngleB + */ + this.localAngleB = 0; + if(typeof(options.localAngleB) === 'number'){ + this.localAngleB = options.localAngleB; + } else { + // Construct + this.localAngleB = bodyB.angle - bodyA.angle; + } + + this.equations.push(x, y, rot); + this.setMaxForce(maxForce); +} +LockConstraint.prototype = new Constraint(); +LockConstraint.prototype.constructor = LockConstraint; + +/** + * Set the maximum force to be applied. + * @method setMaxForce + * @param {Number} force + */ +LockConstraint.prototype.setMaxForce = function(force){ + var eqs = this.equations; + for(var i=0; ithis tutorial. Also called "slider constraint". + * + * @class PrismaticConstraint + * @constructor + * @extends Constraint + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.maxForce] Max force to be applied by the constraint + * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. + * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. + * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. + * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. + * @param {Number} [options.upperLimit] + * @param {Number} [options.lowerLimit] + * @todo Ability to create using only a point and a worldAxis + */ +function PrismaticConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); + + // Get anchors + var localAnchorA = vec2.fromValues(0,0), + localAxisA = vec2.fromValues(1,0), + localAnchorB = vec2.fromValues(0,0); + if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); } + if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); } + if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); } + + /** + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = localAnchorA; + + /** + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = localAnchorB; + + /** + * @property localAxisA + * @type {Array} + */ + this.localAxisA = localAxisA; + + /* + + The constraint violation for the common axis point is + + g = ( xj + rj - xi - ri ) * t := gg*t + + where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. + + gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) + + Note the use of the chain rule. Now we identify the jacobian + + G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] + + The rotational part is just a rotation lock. + + */ + + var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE; + + // Translational part + var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); + var ri = new vec2.create(), + rj = new vec2.create(), + gg = new vec2.create(), + t = new vec2.create(); + trans.computeGq = function(){ + // g = ( xj + rj - xi - ri ) * t + return vec2.dot(gg,t); + }; + trans.updateJacobian = function(){ + var G = this.G, + xi = bodyA.position, + xj = bodyB.position; + vec2.rotate(ri,localAnchorA,bodyA.angle); + vec2.rotate(rj,localAnchorB,bodyB.angle); + vec2.add(gg,xj,rj); + vec2.sub(gg,gg,xi); + vec2.sub(gg,gg,ri); + vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); + + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + }; + this.equations.push(trans); + + // Rotational part + if(!options.disableRotationalLock){ + var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); + this.equations.push(rot); + } + + /** + * The position of anchor A relative to anchor B, along the constraint axis. + * @property position + * @type {Number} + */ + this.position = 0; + + // Is this one used at all? + this.velocity = 0; + + /** + * Set to true to enable lower limit. + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; + + /** + * Set to true to enable upper limit. + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; + + /** + * Lower constraint limit. The constraint position is forced to be larger than this value. + * @property lowerLimit + * @type {Number} + */ + this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; + + /** + * Upper constraint limit. The constraint position is forced to be smaller than this value. + * @property upperLimit + * @type {Number} + */ + this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; + + // Equations used for limits + this.upperLimitEquation = new ContactEquation(bodyA,bodyB); + this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); + + // Set max/min forces + this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; + this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; + + /** + * Equation used for the motor. + * @property motorEquation + * @type {Equation} + */ + this.motorEquation = new Equation(bodyA,bodyB); + + /** + * The current motor state. Enable or disable the motor using .enableMotor + * @property motorEnabled + * @type {Boolean} + */ + this.motorEnabled = false; + + /** + * Set the target speed for the motor. + * @property motorSpeed + * @type {Number} + */ + this.motorSpeed = 0; + + var that = this; + var motorEquation = this.motorEquation; + var old = motorEquation.computeGW; + motorEquation.computeGq = function(){ return 0; }; + motorEquation.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed; + }; +} + +PrismaticConstraint.prototype = new Constraint(); +PrismaticConstraint.prototype.constructor = PrismaticConstraint; + +var worldAxisA = vec2.create(), + worldAnchorA = vec2.create(), + worldAnchorB = vec2.create(), + orientedAnchorA = vec2.create(), + orientedAnchorB = vec2.create(), + tmp = vec2.create(); + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +PrismaticConstraint.prototype.update = function(){ + var eqs = this.equations, + trans = eqs[0], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation, + bodyA = this.bodyA, + bodyB = this.bodyB, + localAxisA = this.localAxisA, + localAnchorA = this.localAnchorA, + localAnchorB = this.localAnchorB; + + trans.updateJacobian(); + + // Transform local things to world + vec2.rotate(worldAxisA, localAxisA, bodyA.angle); + vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); + vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); + vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); + vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); + + var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); + + // Motor + if(this.motorEnabled){ + // G = [ a a x ri -a -a x rj ] + var G = this.motorEquation.G; + G[0] = worldAxisA[0]; + G[1] = worldAxisA[1]; + G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); + G[3] = -worldAxisA[0]; + G[4] = -worldAxisA[1]; + G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); + } + + /* + Limits strategy: + Add contact equation, with normal along the constraint axis. + min/maxForce is set so the constraint is repulsive in the correct direction. + Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. + + ^ + | + upperLimit x + | ------ + anchorB x<---| B | + | | | + ------ | ------ + | | | + | A |-->x anchorA + ------ | + x lowerLimit + | + axis + */ + + + if(this.upperLimitEnabled && relPosition > upperLimit){ + // Update contact constraint normal, etc + 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 && relPosition < lowerLimit){ + // Update contact constraint normal, etc + vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); + vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); + vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); + vec2.scale(tmp,worldAxisA,lowerLimit); + vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } +}; + +/** + * Enable the motor + * @method enableMotor + */ +PrismaticConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +PrismaticConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the constraint limits. + * @method setLimits + * @param {number} lower Lower limit. + * @param {number} upper Upper limit. + */ +PrismaticConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + + +},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation') +, RotationalLockEquation = _dereq_('../equations/RotationalLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = RevoluteConstraint; + +var worldPivotA = vec2.create(), + worldPivotB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1), + g = vec2.create(); + +/** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * @class RevoluteConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to. + * @param {Array} [options.localPivotB] See localPivotA. + * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. + * @extends Constraint + * + * @example + * // This will create a revolute constraint between two bodies with pivot point in between them. + * var bodyA = new Body({ mass: 1, position: [-1, 0] }); + * var bodyB = new Body({ mass: 1, position: [1, 0] }); + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * worldPivot: [0, 0] + * }); + * world.addConstraint(constraint); + * + * // Using body-local pivot points, the constraint could have been constructed like this: + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * localPivotA: [1, 0], + * localPivotB: [-1, 0] + * }); + */ +function RevoluteConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); + + var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; + + /** + * @property {Array} pivotA + */ + this.pivotA = vec2.create(); + + /** + * @property {Array} pivotB + */ + this.pivotB = vec2.create(); + + if(options.worldPivot){ + // Compute pivotA and pivotB + vec2.sub(this.pivotA, options.worldPivot, bodyA.position); + vec2.sub(this.pivotB, options.worldPivot, bodyB.position); + // Rotate to local coordinate system + vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle); + vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle); + } else { + // Get pivotA and pivotB + vec2.copy(this.pivotA, options.localPivotA); + vec2.copy(this.pivotB, options.localPivotB); + } + + // Equations to be fed to the solver + var eqs = this.equations = [ + new Equation(bodyA,bodyB,-maxForce,maxForce), + new Equation(bodyA,bodyB,-maxForce,maxForce), + ]; + + var x = eqs[0]; + var y = eqs[1]; + var that = this; + + x.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,xAxis); + }; + + y.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,yAxis); + }; + + y.minForce = x.minForce = -maxForce; + y.maxForce = x.maxForce = maxForce; + + this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); + + /** + * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. + * @property {Boolean} motorEnabled + * @readOnly + */ + this.motorEnabled = false; + + /** + * The constraint position. + * @property angle + * @type {Number} + * @readOnly + */ + this.angle = 0; + + /** + * Set to true to enable lower limit + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = false; + + /** + * Set to true to enable upper limit + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = false; + + /** + * The lower limit on the constraint angle. + * @property lowerLimit + * @type {Boolean} + */ + this.lowerLimit = 0; + + /** + * The upper limit on the constraint angle. + * @property upperLimit + * @type {Boolean} + */ + this.upperLimit = 0; + + this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.upperLimitEquation.minForce = 0; + this.lowerLimitEquation.maxForce = 0; +} +RevoluteConstraint.prototype = new Constraint(); +RevoluteConstraint.prototype.constructor = RevoluteConstraint; + +/** + * Set the constraint angle limits. + * @method setLimits + * @param {number} lower Lower angle limit. + * @param {number} upper Upper angle limit. + */ +RevoluteConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + +RevoluteConstraint.prototype.update = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + pivotA = this.pivotA, + pivotB = this.pivotB, + eqs = this.equations, + normal = eqs[0], + tangent= eqs[1], + x = eqs[0], + y = eqs[1], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation; + + var relAngle = this.angle = bodyB.angle - bodyA.angle; + + if(this.upperLimitEnabled && relAngle > upperLimit){ + 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 < lowerLimit){ + lowerLimitEquation.angle = lowerLimit; + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } + + /* + + The constraint violation is + + g = xj + rj - xi - ri + + ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: + + gdot = vj + wj x rj - vi - wi x ri + + We split this into x and y directions. (let x and y be unit vectors along the respective axes) + + gdot * x = ( vj + wj x rj - vi - wi x ri ) * x + = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x + = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi + = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] + = G*W + + ...and similar for y. We have then identified the jacobian entries for x and y directions: + + Gx = [ x (rj x x) -x -(ri x x)] + Gy = [ y (rj x y) -y -(ri x y)] + + */ + + vec2.rotate(worldPivotA, pivotA, bodyA.angle); + vec2.rotate(worldPivotB, pivotB, bodyB.angle); + + // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc + + x.G[0] = -1; + x.G[1] = 0; + x.G[2] = -vec2.crossLength(worldPivotA,xAxis); + x.G[3] = 1; + x.G[4] = 0; + x.G[5] = vec2.crossLength(worldPivotB,xAxis); + + y.G[0] = 0; + y.G[1] = -1; + y.G[2] = -vec2.crossLength(worldPivotA,yAxis); + y.G[3] = 0; + y.G[4] = 1; + y.G[5] = vec2.crossLength(worldPivotB,yAxis); +}; + +/** + * Enable the rotational motor + * @method enableMotor + */ +RevoluteConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +RevoluteConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the speed of the rotational constraint motor + * @method setMotorSpeed + * @param {Number} speed + */ +RevoluteConstraint.prototype.setMotorSpeed = function(speed){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations[i].relativeVelocity = speed; +}; + +/** + * Get the speed of the rotational constraint motor + * @method getMotorSpeed + * @return {Number} The current speed, or false if the motor is not enabled. + */ +RevoluteConstraint.prototype.getMotorSpeed = function(){ + if(!this.motorEnabled){ + return false; + } + return this.motorEquation.relativeVelocity; +}; + +},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = AngleLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class AngleLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in body A. + * @param {Number} [options.ratio] Gear ratio + */ +function AngleLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); + this.angle = options.angle || 0; + + /** + * The gear ratio. + * @property {Number} ratio + * @private + * @see setRatio + */ + this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; + + this.setRatio(this.ratio); +} +AngleLockEquation.prototype = new Equation(); +AngleLockEquation.prototype.constructor = AngleLockEquation; + +AngleLockEquation.prototype.computeGq = function(){ + return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; +}; + +/** + * Set the gear ratio for this equation + * @method setRatio + * @param {Number} ratio + */ +AngleLockEquation.prototype.setRatio = function(ratio){ + var G = this.G; + G[2] = ratio; + G[5] = -1; + this.ratio = ratio; +}; + +/** + * Set the max force for the equation. + * @method setMaxTorque + * @param {Number} torque + */ +AngleLockEquation.prototype.setMaxTorque = function(torque){ + this.maxForce = torque; + this.minForce = -torque; +}; + +},{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = ContactEquation; + +/** + * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive. + * + * @class ContactEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function ContactEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); + + /** + * Vector from body i center of mass to the contact point. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + this.penetrationVec = vec2.create(); + + /** + * World-oriented vector from body A center of mass to the contact point. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * The normal vector, pointing out of body i + * @property normalA + * @type {Array} + */ + this.normalA = vec2.create(); + + /** + * The restitution to use (0=no bounciness, 1=max bounciness). + * @property restitution + * @type {Number} + */ + this.restitution = 0; + + /** + * This property is set to true if this is the first impact between the bodies (not persistant contact). + * @property firstImpact + * @type {Boolean} + * @readOnly + */ + this.firstImpact = false; + + /** + * The shape in body i that triggered this contact. + * @property shapeA + * @type {Shape} + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this contact. + * @property shapeB + * @type {Shape} + */ + this.shapeB = null; +} +ContactEquation.prototype = new Equation(); +ContactEquation.prototype.constructor = ContactEquation; +ContactEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + xi = bi.position, + xj = bj.position; + + var penetrationVec = this.penetrationVec, + n = this.normalA, + G = this.G; + + // Caluclate cross products + var rixn = vec2.crossLength(ri,n), + rjxn = vec2.crossLength(rj,n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; + + // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector + vec2.add(penetrationVec,xj,rj); + vec2.sub(penetrationVec,penetrationVec,xi); + vec2.sub(penetrationVec,penetrationVec,ri); + + // Compute iteration + var GW, Gq; + if(this.firstImpact && this.restitution !== 0){ + Gq = 0; + GW = (1/b)*(1+this.restitution) * this.computeGW(); + } else { + Gq = vec2.dot(n,penetrationVec) + this.offset; + GW = this.computeGW(); + } + + var GiMf = this.computeGiMf(); + var B = - Gq * a - GW * b - h*GiMf; + + return B; +}; + +var vi = vec2.create(); +var vj = vec2.create(); +var relVel = vec2.create(); + +/** + * Get the relative velocity along the normal vector. + * @return {number} + */ +ContactEquation.prototype.getVelocityAlongNormal = function(){ + + this.bodyA.getVelocityAtPoint(vi, this.contactPointA); + this.bodyB.getVelocityAtPoint(vj, this.contactPointB); + + vec2.subtract(relVel, vi, vj); + + return vec2.dot(this.normalA, relVel); +}; +},{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){ +module.exports = Equation; + +var vec2 = _dereq_('../math/vec2'), + Utils = _dereq_('../utils/Utils'), + Body = _dereq_('../objects/Body'); + +/** + * Base class for constraint equations. + * @class Equation + * @constructor + * @param {Body} bodyA First body participating in the equation + * @param {Body} bodyB Second body participating in the equation + * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE + * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE + */ +function Equation(bodyA, bodyB, minForce, maxForce){ + + /** + * Minimum force to apply when solving. + * @property minForce + * @type {Number} + */ + this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; + + /** + * Max force to apply when solving. + * @property maxForce + * @type {Number} + */ + this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; + + /** + * First body participating in the constraint + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second body participating in the constraint + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; + + /** + * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. + * @property stiffness + * @type {Number} + */ + this.stiffness = Equation.DEFAULT_STIFFNESS; + + /** + * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. + * @property relaxation + * @type {Number} + */ + this.relaxation = Equation.DEFAULT_RELAXATION; + + /** + * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). + * @property G + * @type {Array} + */ + this.G = new Utils.ARRAY_TYPE(6); + for(var i=0; i<6; i++){ + this.G[i]=0; + } + + this.offset = 0; + + this.a = 0; + this.b = 0; + this.epsilon = 0; + this.timeStep = 1/60; + + /** + * Indicates if stiffness or relaxation was changed. + * @property {Boolean} needsUpdate + */ + this.needsUpdate = true; + + /** + * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. + * @property multiplier + * @type {Number} + */ + this.multiplier = 0; + + /** + * Relative velocity. + * @property {Number} relativeVelocity + */ + this.relativeVelocity = 0; + + /** + * Whether this equation is enabled or not. If true, it will be added to the solver. + * @property {Boolean} enabled + */ + this.enabled = true; +} +Equation.prototype.constructor = Equation; + +/** + * The default stiffness when creating a new Equation. + * @static + * @property {Number} DEFAULT_STIFFNESS + * @default 1e6 + */ +Equation.DEFAULT_STIFFNESS = 1e6; + +/** + * The default relaxation when creating a new Equation. + * @static + * @property {Number} DEFAULT_RELAXATION + * @default 4 + */ +Equation.DEFAULT_RELAXATION = 4; + +/** + * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the SPOOK notes. + * @method update + */ +Equation.prototype.update = function(){ + var k = this.stiffness, + d = this.relaxation, + h = this.timeStep; + + this.a = 4.0 / (h * (1 + 4 * d)); + this.b = (4.0 * d) / (1 + 4 * d); + this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); + + this.needsUpdate = false; +}; + +/** + * Multiply a jacobian entry with corresponding positions or velocities + * @method gmult + * @return {Number} + */ +Equation.prototype.gmult = function(G,vi,wi,vj,wj){ + return G[0] * vi[0] + + G[1] * vi[1] + + G[2] * wi + + G[3] * vj[0] + + G[4] * vj[1] + + G[5] * wj; +}; + +/** + * Computes the RHS of the SPOOK equation + * @method computeB + * @return {Number} + */ +Equation.prototype.computeB = function(a,b,h){ + var GW = this.computeGW(); + var Gq = this.computeGq(); + var GiMf = this.computeGiMf(); + return - Gq * a - GW * b - GiMf*h; +}; + +/** + * Computes G\*q, where q are the generalized body coordinates + * @method computeGq + * @return {Number} + */ +var qi = vec2.create(), + qj = vec2.create(); +Equation.prototype.computeGq = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + xi = bi.position, + xj = bj.position, + ai = bi.angle, + aj = bj.angle; + + return this.gmult(G, qi, ai, qj, aj) + this.offset; +}; + +/** + * Computes G\*W, where W are the body velocities + * @method computeGW + * @return {Number} + */ +Equation.prototype.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity; +}; + +/** + * Computes G\*Wlambda, where W are the body velocities + * @method computeGWlambda + * @return {Number} + */ +Equation.prototype.computeGWlambda = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.vlambda, + vj = bj.vlambda, + wi = bi.wlambda, + wj = bj.wlambda; + return this.gmult(G,vi,wi,vj,wj); +}; + +/** + * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. + * @method computeGiMf + * @return {Number} + */ +var iMfi = vec2.create(), + iMfj = vec2.create(); +Equation.prototype.computeGiMf = function(){ + var bi = this.bodyA, + bj = this.bodyB, + fi = bi.force, + ti = bi.angularForce, + fj = bj.force, + tj = bj.angularForce, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + vec2.scale(iMfi, fi, invMassi); + vec2.multiply(iMfi, bi.massMultiplier, iMfi); + vec2.scale(iMfj, fj,invMassj); + vec2.multiply(iMfj, bj.massMultiplier, iMfj); + + return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); +}; + +/** + * Computes G\*inv(M)\*G' + * @method computeGiMGt + * @return {Number} + */ +Equation.prototype.computeGiMGt = function(){ + var bi = this.bodyA, + bj = this.bodyB, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + return G[0] * G[0] * invMassi * bi.massMultiplier[0] + + G[1] * G[1] * invMassi * bi.massMultiplier[1] + + G[2] * G[2] * invIi + + G[3] * G[3] * invMassj * bj.massMultiplier[0] + + G[4] * G[4] * invMassj * bj.massMultiplier[1] + + G[5] * G[5] * invIj; +}; + +var addToWlambda_temp = vec2.create(), + addToWlambda_Gi = vec2.create(), + addToWlambda_Gj = vec2.create(), + addToWlambda_ri = vec2.create(), + addToWlambda_rj = vec2.create(), + addToWlambda_Mdiag = vec2.create(); + +/** + * Add constraint velocity to the bodies. + * @method addToWlambda + * @param {Number} deltalambda + */ +Equation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bodyA, + bj = this.bodyB, + temp = addToWlambda_temp, + Gi = addToWlambda_Gi, + Gj = addToWlambda_Gj, + ri = addToWlambda_ri, + rj = addToWlambda_rj, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + Mdiag = addToWlambda_Mdiag, + G = this.G; + + Gi[0] = G[0]; + Gi[1] = G[1]; + Gj[0] = G[3]; + Gj[1] = G[4]; + + // Add to linear velocity + // v_lambda += inv(M) * delta_lamba * G + vec2.scale(temp, Gi, invMassi*deltalambda); + vec2.multiply(temp, temp, bi.massMultiplier); + vec2.add( bi.vlambda, bi.vlambda, temp); + // This impulse is in the offset frame + // Also add contribution to angular + //bi.wlambda -= vec2.crossLength(temp,ri); + bi.wlambda += invIi * G[2] * deltalambda; + + + vec2.scale(temp, Gj, invMassj*deltalambda); + vec2.multiply(temp, temp, bj.massMultiplier); + vec2.add( bj.vlambda, bj.vlambda, temp); + //bj.wlambda -= vec2.crossLength(temp,rj); + bj.wlambda += invIj * G[5] * deltalambda; +}; + +/** + * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps + * @method computeInvC + * @param {Number} eps + * @return {Number} + */ +Equation.prototype.computeInvC = function(eps){ + return 1.0 / (this.computeGiMGt() + eps); +}; + +},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('./Equation') +, Utils = _dereq_('../utils/Utils'); + +module.exports = FrictionEquation; + +/** + * Constrains the slipping in a contact along a tangent + * + * @class FrictionEquation + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Number} slipForce + * @extends Equation + */ +function FrictionEquation(bodyA, bodyB, slipForce){ + Equation.call(this, bodyA, bodyB, -slipForce, slipForce); + + /** + * Relative vector from center of body A to the contact point, world oriented. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + + /** + * Relative vector from center of body B to the contact point, world oriented. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * Tangent vector that the friction force will act along. World oriented. + * @property t + * @type {Array} + */ + this.t = vec2.create(); + + /** + * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average. + * @property contactEquations + * @type {ContactEquation} + */ + this.contactEquations = []; + + /** + * The shape in body i that triggered this friction. + * @property shapeA + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeA... + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this friction. + * @property shapeB + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeB... + */ + this.shapeB = null; + + /** + * The friction coefficient to use. + * @property frictionCoefficient + * @type {Number} + */ + this.frictionCoefficient = 0.3; +} +FrictionEquation.prototype = new Equation(); +FrictionEquation.prototype.constructor = FrictionEquation; + +/** + * Set the slipping condition for the constraint. The friction force cannot be + * larger than this value. + * @method setSlipForce + * @param {Number} slipForce + */ +FrictionEquation.prototype.setSlipForce = function(slipForce){ + this.maxForce = slipForce; + this.minForce = -slipForce; +}; + +/** + * Get the max force for the constraint. + * @method getSlipForce + * @return {Number} + */ +FrictionEquation.prototype.getSlipForce = function(){ + return this.maxForce; +}; + +FrictionEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + t = this.t, + G = this.G; + + // G = [-t -rixt t rjxt] + // And remember, this is a pure velocity constraint, g is always zero! + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + + var GW = this.computeGW(), + GiMf = this.computeGiMf(); + + var B = /* - g * a */ - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class RotationalLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in bodyA. + */ +function RotationalLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + + /** + * @property {number} angle + */ + this.angle = options.angle || 0; + + var G = this.G; + G[2] = 1; + G[5] = -1; +} +RotationalLockEquation.prototype = new Equation(); +RotationalLockEquation.prototype.constructor = RotationalLockEquation; + +var worldVectorA = vec2.create(), + worldVectorB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1); +RotationalLockEquation.prototype.computeGq = function(){ + vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); + vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); + return vec2.dot(worldVectorA,worldVectorB); +}; + +},{"../math/vec2":30,"./Equation":22}],25:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalVelocityEquation; + +/** + * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). + * + * @class RotationalVelocityEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function RotationalVelocityEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + this.relativeVelocity = 1; + this.ratio = 1; +} +RotationalVelocityEquation.prototype = new Equation(); +RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; +RotationalVelocityEquation.prototype.computeB = function(a,b,h){ + var G = this.G; + G[2] = -1; + G[5] = this.ratio; + + var GiMf = this.computeGiMf(); + var GW = this.computeGW(); + var B = - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"./Equation":22}],26:[function(_dereq_,module,exports){ +/** + * Base class for objects that dispatches events. + * @class EventEmitter + * @constructor + */ +var EventEmitter = function () {}; + +module.exports = EventEmitter; + +EventEmitter.prototype = { + constructor: EventEmitter, + + /** + * Add an event listener + * @method on + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + on: function ( type, listener, context ) { + listener.context = context || this; + if ( this._listeners === undefined ){ + this._listeners = {}; + } + var listeners = this._listeners; + if ( listeners[ type ] === undefined ) { + listeners[ type ] = []; + } + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + listeners[ type ].push( listener ); + } + return this; + }, + + /** + * Check if an event listener is added + * @method has + * @param {String} type + * @param {Function} listener + * @return {Boolean} + */ + has: function ( type, listener ) { + if ( this._listeners === undefined ){ + return false; + } + var listeners = this._listeners; + if(listener){ + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + return true; + } + } else { + if ( listeners[ type ] !== undefined ) { + return true; + } + } + + return false; + }, + + /** + * Remove an event listener + * @method off + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + off: function ( type, listener ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var index = listeners[ type ].indexOf( listener ); + if ( index !== - 1 ) { + listeners[ type ].splice( index, 1 ); + } + return this; + }, + + /** + * Emit an event. + * @method emit + * @param {Object} event + * @param {String} event.type + * @return {EventEmitter} The self object, for chainability. + */ + emit: function ( event ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; + if ( listenerArray !== undefined ) { + event.target = this; + for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { + var listener = listenerArray[ i ]; + listener.call( listener.context, event ); + } + } + return this; + } +}; + +},{}],27:[function(_dereq_,module,exports){ +var Material = _dereq_('./Material'); +var Equation = _dereq_('../equations/Equation'); + +module.exports = ContactMaterial; + +/** + * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. + * @class ContactMaterial + * @constructor + * @param {Material} materialA + * @param {Material} materialB + * @param {Object} [options] + * @param {Number} [options.friction=0.3] Friction coefficient. + * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". + * @param {Number} [options.stiffness] ContactEquation stiffness. + * @param {Number} [options.relaxation] ContactEquation relaxation. + * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. + * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. + * @param {Number} [options.surfaceVelocity=0] Surface velocity. + * @author schteppe + */ +function ContactMaterial(materialA, materialB, options){ + options = options || {}; + + if(!(materialA instanceof Material) || !(materialB instanceof Material)){ + throw new Error("First two arguments must be Material instances."); + } + + /** + * The contact material identifier + * @property id + * @type {Number} + */ + this.id = ContactMaterial.idCounter++; + + /** + * First material participating in the contact material + * @property materialA + * @type {Material} + */ + this.materialA = materialA; + + /** + * Second material participating in the contact material + * @property materialB + * @type {Material} + */ + this.materialB = materialB; + + /** + * Friction coefficient to use in the contact of these two materials. Friction = 0 will make the involved objects super slippery, and friction = 1 will make it much less slippery. A friction coefficient larger than 1 will allow for very large friction forces, which can be convenient for preventing car tires not slip on the ground. + * @property friction + * @type {Number} + * @default 0.3 + */ + this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; + + /** + * Restitution, or "bounciness" to use in the contact of these two materials. A restitution of 0 will make no bounce, while restitution=1 will approximately bounce back with the same velocity the object came with. + * @property restitution + * @type {Number} + * @default 0 + */ + this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0; + + /** + * Hardness of the contact. Less stiffness will make the objects penetrate more, and will make the contact act more like a spring than a contact force. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property stiffness + * @type {Number} + */ + this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting ContactEquation that this ContactMaterial generate. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property relaxation + * @type {Number} + */ + this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Stiffness of the resulting friction force. For most cases, the value of this property should be a large number. I cannot think of any case where you would want less frictionStiffness. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property frictionStiffness + * @type {Number} + */ + this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting friction force. The default value should be good for most simulations. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property frictionRelaxation + * @type {Number} + */ + this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + * @property {Number} surfaceVelocity + * @default 0 + */ + this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; + + /** + * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts". + * @property contactSkinSize + * @type {Number} + */ + this.contactSkinSize = 0.005; +} + +ContactMaterial.idCounter = 0; + +},{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){ +module.exports = Material; + +/** + * Defines a physics material. + * @class Material + * @constructor + * @param {number} id Material identifier + * @author schteppe + */ +function Material(id){ + /** + * The material identifier + * @property id + * @type {Number} + */ + this.id = id || Material.idCounter++; +} + +Material.idCounter = 0; + +},{}],29:[function(_dereq_,module,exports){ + + /* + PolyK library + url: http://polyk.ivank.net + Released under MIT licence. + + Copyright (c) 2012 Ivan Kuckir + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + */ + + var PolyK = {}; + + /* + Is Polygon self-intersecting? + + O(n^2) + */ + /* + PolyK.IsSimple = function(p) + { + var n = p.length>>1; + if(n<4) return true; + var a1 = new PolyK._P(), a2 = new PolyK._P(); + var b1 = new PolyK._P(), b2 = new PolyK._P(); + var c = new PolyK._P(); + + for(var i=0; i>1; + if(n<3) return []; + var tgs = []; + var avl = []; + for(var i=0; i 3) + { + 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; j 3*al) break; // no convex angles :( + } + tgs.push(avl[0], avl[1], avl[2]); + return tgs; + } + /* + PolyK.ContainsPoint = function(p, px, py) + { + var n = p.length>>1; + var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; + var depth = 0; + for(var i=0; i=0 && by>=0) continue; // both "up" or both "donw" + if(ax< 0 && bx< 0) continue; + + var lx = ax + (bx-ax)*(-ay)/(by-ay); + if(lx>0) depth++; + } + return (depth & 1) == 1; + } + + PolyK.Slice = function(p, ax, ay, bx, by) + { + if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; + + var a = new PolyK._P(ax, ay); + var b = new PolyK._P(bx, by); + var iscs = []; // intersections + var ps = []; // points + for(var i=0; i 0) + { + var n = ps.length; + var i0 = iscs[0]; + var i1 = iscs[1]; + var ind0 = ps.indexOf(i0); + var ind1 = ps.indexOf(i1); + var solved = false; + + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + else + { + i0 = iscs[1]; + i1 = iscs[0]; + ind0 = ps.indexOf(i0); + ind1 = ps.indexOf(i1); + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + } + if(solved) + { + dir--; + var pgn = PolyK._getPoints(ps, ind0, ind1); + pgs.push(pgn); + ps = PolyK._getPoints(ps, ind1, ind0); + i0.flag = i1.flag = false; + iscs.splice(0,2); + if(iscs.length == 0) pgs.push(ps); + } + else { dir++; iscs.reverse(); } + if(dir>1) break; + } + var result = []; + for(var i=0; i>1, isc); + } + b1.x = b2.x; b1.y = b2.y; + b2.x = p[0]; b2.y = p[1]; + PolyK._pointLineDist(a1, b1, b2, l>>1, isc); + + var idst = 1/isc.dist; + isc.norm.x = (x-isc.point.x)*idst; + isc.norm.y = (y-isc.point.y)*idst; + return isc; + } + + PolyK._pointLineDist = function(p, a, b, edge, isc) + { + var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; + + var A = x - x1; + var B = y - y1; + var C = x2 - x1; + var D = y2 - y1; + + var dot = A * C + B * D; + var len_sq = C * C + D * D; + var param = dot / len_sq; + + var xx, yy; + + if (param < 0 || (x1 == x2 && y1 == y2)) { + xx = x1; + yy = y1; + } + else if (param > 1) { + xx = x2; + yy = y2; + } + else { + xx = x1 + param * C; + yy = y1 + param * D; + } + + var dx = x - xx; + var dy = y - yy; + var dst = Math.sqrt(dx * dx + dy * dy); + if(dst= 0) && (v >= 0) && (u + v < 1); + } + /* + PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) + { + var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); + var day = (a1.y-a2.y), dby = (b1.y-b2.y); + + var Den = dax*dby - day*dbx; + if (Den == 0) return null; // parallel + + var A = (a1.x * a2.y - a1.y * a2.x); + var B = (b1.x * b2.y - b1.y * b2.x); + + var I = c; + var iDen = 1/Den; + I.x = ( A*dbx - dax*B ) * iDen; + I.y = ( A*dby - day*B ) * iDen; + + if(!PolyK._InRect(I, b1, b2)) return null; + if((day>0 && I.y>a1.y) || (day<0 && I.y0 && I.x>a1.x) || (dax<0 && I.x=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); + if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); + + if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) + && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) + return true; + return false; + } + */ + PolyK._convex = function(ax, ay, bx, by, cx, cy) + { + return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; + } + /* + PolyK._P = function(x,y) + { + this.x = x; + this.y = y; + this.flag = false; + } + PolyK._P.prototype.toString = function() + { + return "Point ["+this.x+", "+this.y+"]"; + } + PolyK._P.dist = function(a,b) + { + var dx = b.x-a.x; + var dy = b.y-a.y; + return Math.sqrt(dx*dx + dy*dy); + } + + PolyK._tp = []; + for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); + */ + +module.exports = PolyK; + +},{}],30:[function(_dereq_,module,exports){ +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. + * @class vec2 + */ + +var vec2 = module.exports = {}; + +var Utils = _dereq_('../utils/Utils'); + +/** + * Make a cross product and only return the z component + * @method crossLength + * @static + * @param {Array} a + * @param {Array} b + * @return {Number} + */ +vec2.crossLength = function(a,b){ + return a[0] * b[1] - a[1] * b[0]; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossVZ + * @static + * @param {Array} out + * @param {Array} vec + * @param {Number} zcomp + * @return {Number} + */ +vec2.crossVZ = function(out, vec, zcomp){ + vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossZV + * @static + * @param {Array} out + * @param {Number} zcomp + * @param {Array} vec + * @return {Number} + */ +vec2.crossZV = function(out, zcomp, vec){ + vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Rotate a vector by an angle + * @method rotate + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate = function(out,a,angle){ + if(angle !== 0){ + 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; + } else { + out[0] = a[0]; + out[1] = a[1]; + } +}; + +/** + * Rotate a vector 90 degrees clockwise + * @method rotate90cw + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate90cw = function(out, a) { + var x = a[0]; + var y = a[1]; + out[0] = y; + out[1] = -x; +}; + +/** + * Transform a point position to local frame. + * @method toLocalFrame + * @param {Array} out + * @param {Array} worldPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ + vec2.copy(out, worldPoint); + vec2.sub(out, out, framePosition); + vec2.rotate(out, out, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ + vec2.copy(out, localPoint); + vec2.rotate(out, out, frameAngle); + vec2.add(out, out, framePosition); +}; + +/** + * Transform a vector to local frame. + * @method vectorToLocalFrame + * @param {Array} out + * @param {Array} worldVector + * @param {Number} frameAngle + */ +vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ + vec2.rotate(out, worldVector, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localVector + * @param {Number} frameAngle + */ +vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){ + vec2.rotate(out, localVector, frameAngle); +}; + +/** + * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php + * @method centroid + * @static + * @param {Array} out + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Array} The out object + */ +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; +}; + +/** + * Creates a new, empty vec2 + * @static + * @method create + * @return {Array} a new 2D vector + */ +vec2.create = function() { + var out = new Utils.ARRAY_TYPE(2); + out[0] = 0; + out[1] = 0; + return out; +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * @static + * @method clone + * @param {Array} a vector to clone + * @return {Array} a new 2D vector + */ +vec2.clone = function(a) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Creates a new vec2 initialized with the given values + * @static + * @method fromValues + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} a new 2D vector + */ +vec2.fromValues = function(x, y) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Copy the values from one vec2 to another + * @static + * @method copy + * @param {Array} out the receiving vector + * @param {Array} a the source vector + * @return {Array} out + */ +vec2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * @static + * @method set + * @param {Array} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} out + */ +vec2.set = function(out, x, y) { + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Adds two vec2's + * @static + * @method add + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +}; + +/** + * Subtracts two vec2's + * @static + * @method subtract + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +}; + +/** + * Alias for vec2.subtract + * @static + * @method sub + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * @static + * @method multiply + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +}; + +/** + * Alias for vec2.multiply + * @static + * @method mul + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * @static + * @method divide + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +}; + +/** + * Alias for vec2.divide + * @static + * @method div + */ +vec2.div = vec2.divide; + +/** + * Scales a vec2 by a scalar number + * @static + * @method scale + * @param {Array} out the receiving vector + * @param {Array} a the vector to scale + * @param {Number} b amount to scale the vector by + * @return {Array} out + */ +vec2.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * @static + * @method distance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} distance between a and b + */ +vec2.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.distance + * @static + * @method dist + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * @static + * @method squaredDistance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} squared distance between a and b + */ +vec2.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredDistance + * @static + * @method sqrDist + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * @static + * @method length + * @param {Array} a vector to calculate length of + * @return {Number} length of a + */ +vec2.length = function (a) { + var x = a[0], + y = a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.length + * @method len + * @static + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * @static + * @method squaredLength + * @param {Array} a vector to calculate squared length of + * @return {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a[0], + y = a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredLength + * @static + * @method sqrLen + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * @static + * @method negate + * @param {Array} out the receiving vector + * @param {Array} a vector to negate + * @return {Array} out + */ +vec2.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +}; + +/** + * Normalize a vec2 + * @static + * @method normalize + * @param {Array} out the receiving vector + * @param {Array} a vector to normalize + * @return {Array} out + */ +vec2.normalize = function(out, a) { + var x = a[0], + y = a[1]; + var len = x*x + y*y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * @static + * @method dot + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1]; +}; + +/** + * Returns a string representation of a vector + * @static + * @method str + * @param {Array} vec vector to represent as a string + * @return {String} string representation of the vector + */ +vec2.str = function (a) { + return 'vec2(' + a[0] + ', ' + a[1] + ')'; +}; + +/** + * Linearly interpolate/mix two vectors. + * @static + * @method lerp + * @param {Array} out + * @param {Array} a First vector + * @param {Array} b Second vector + * @param {number} t Lerp factor + */ +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; +}; + +/** + * Reflect a vector along a normal. + * @static + * @method reflect + * @param {Array} out + * @param {Array} vector + * @param {Array} normal + */ +vec2.reflect = function(out, vector, normal){ + var dot = vector[0] * normal[0] + vector[1] * normal[1]; + out[0] = vector[0] - 2 * normal[0] * dot; + out[1] = vector[1] - 2 * normal[1] * dot; +}; + +/** + * Get the intersection point between two line segments. + * @static + * @method getLineSegmentsIntersection + * @param {Array} out + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {boolean} True if there was an intersection, otherwise false. + */ +vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { + var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); + if(t < 0){ + return false; + } else { + out[0] = p0[0] + (t * (p1[0] - p0[0])); + out[1] = p0[1] + (t * (p1[1] - p0[1])); + return true; + } +}; + +/** + * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) + * @static + * @method getLineSegmentsIntersectionFraction + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. + */ +vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { + var s1_x = p1[0] - p0[0]; + var s1_y = p1[1] - p0[1]; + var s2_x = p3[0] - p2[0]; + var s2_y = p3[1] - p2[1]; + + var s, t; + s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); + t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); + if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + return t; + } + return -1; // No collision +}; + +},{"../utils/Utils":57}],31:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, decomp = _dereq_('poly-decomp') +, Convex = _dereq_('../shapes/Convex') +, RaycastResult = _dereq_('../collision/RaycastResult') +, Ray = _dereq_('../collision/Ray') +, AABB = _dereq_('../collision/AABB') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Body; + +/** + * A rigid body. Has got a center of mass, position, velocity and a number of + * shapes that are used for collisions. + * + * @class Body + * @constructor + * @extends EventEmitter + * @param {Array} [options.force] + * @param {Array} [options.position] + * @param {Array} [options.velocity] + * @param {Boolean} [options.allowSleep] + * @param {Boolean} [options.collisionResponse] + * @param {Number} [options.angle=0] + * @param {Number} [options.angularForce=0] + * @param {Number} [options.angularVelocity=0] + * @param {Number} [options.ccdIterations=10] + * @param {Number} [options.ccdSpeedThreshold=-1] + * @param {Number} [options.fixedRotation=false] + * @param {Number} [options.gravityScale] + * @param {Number} [options.id] + * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. + * @param {Number} [options.sleepSpeedLimit] + * @param {Number} [options.sleepTimeLimit] + * @param {Object} [options] + * + * @example + * + * // Create a typical dynamic body + * var body = new Body({ + * mass: 1, + * position: [0, 0], + * angle: 0, + * velocity: [0, 0], + * angularVelocity: 0 + * }); + * + * // Add a circular shape to the body + * body.addShape(new Circle({ radius: 1 })); + * + * // Add the body to the world + * world.addBody(body); + */ +function Body(options){ + options = options || {}; + + EventEmitter.call(this); + + /** + * The body identifyer + * @property id + * @type {Number} + */ + this.id = options.id || ++Body._idCounter; + + /** + * The world that this body is added to. This property is set to NULL if the body is not added to any world. + * @property world + * @type {World} + */ + this.world = null; + + /** + * The shapes of the body. + * + * @property shapes + * @type {Array} + */ + this.shapes = []; + + /** + * The mass of the body. + * @property mass + * @type {number} + */ + this.mass = options.mass || 0; + + /** + * The inverse mass of the body. + * @property invMass + * @type {number} + */ + this.invMass = 0; + + /** + * The inertia of the body around the Z axis. + * @property inertia + * @type {number} + */ + this.inertia = 0; + + /** + * The inverse inertia of the body. + * @property invInertia + * @type {number} + */ + this.invInertia = 0; + + this.invMassSolve = 0; + this.invInertiaSolve = 0; + + /** + * Set to true if you want to fix the rotation of the body. + * @property fixedRotation + * @type {Boolean} + */ + this.fixedRotation = !!options.fixedRotation; + + /** + * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y. + * @property {Boolean} fixedX + */ + this.fixedX = !!options.fixedX; + + /** + * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X. + * @property {Boolean} fixedY + */ + this.fixedY = !!options.fixedY; + + /** + * @private + * @property {array} massMultiplier + */ + this.massMultiplier = vec2.create(); + + /** + * The position of the body + * @property position + * @type {Array} + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * The interpolated position of the body. Use this for rendering. + * @property interpolatedPosition + * @type {Array} + */ + this.interpolatedPosition = vec2.fromValues(0,0); + + /** + * The interpolated angle of the body. Use this for rendering. + * @property interpolatedAngle + * @type {Number} + */ + this.interpolatedAngle = 0; + + /** + * The previous position of the body. + * @property previousPosition + * @type {Array} + */ + this.previousPosition = vec2.fromValues(0,0); + + /** + * The previous angle of the body. + * @property previousAngle + * @type {Number} + */ + this.previousAngle = 0; + + /** + * The current velocity of the body. + * @property velocity + * @type {Array} + */ + this.velocity = vec2.fromValues(0,0); + if(options.velocity){ + vec2.copy(this.velocity, options.velocity); + } + + /** + * Constraint velocity that was added to the body during the last step. + * @property vlambda + * @type {Array} + */ + this.vlambda = vec2.fromValues(0,0); + + /** + * Angular constraint velocity that was added to the body during last step. + * @property wlambda + * @type {Array} + */ + this.wlambda = 0; + + /** + * The angle of the body, in radians. + * @property angle + * @type {number} + * @example + * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. + * // If you need a value between 0 and 2*pi, use the following function to normalize it. + * function normalizeAngle(angle){ + * angle = angle % (2*Math.PI); + * if(angle < 0){ + * angle += (2*Math.PI); + * } + * return angle; + * } + */ + this.angle = options.angle || 0; + + /** + * The angular velocity of the body, in radians per second. + * @property angularVelocity + * @type {number} + */ + this.angularVelocity = options.angularVelocity || 0; + + /** + * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. + * @property force + * @type {Array} + * + * @example + * // This produces a forcefield of 1 Newton in the positive x direction. + * for(var i=0; i radius){ + radius = offset + r; + } + } + + this.boundingRadius = radius; +}; + +/** + * Add a shape to the body. You can pass a local transform when adding a shape, + * so that the shape gets an offset and angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * + * @method addShape + * @param {Shape} shape + * @param {Array} [offset] Local body offset of the shape. + * @param {Number} [angle] Local body angle. + * + * @example + * var body = new Body(), + * shape = new Circle({ radius: 1 }); + * + * // Add the shape to the body, positioned in the center + * body.addShape(shape); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. + * body.addShape(shape,[1,0]); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. + * body.addShape(shape,[0,1],Math.PI/2); + */ +Body.prototype.addShape = function(shape, offset, angle){ + if(shape.body){ + throw new Error('A shape can only be added to one body.'); + } + shape.body = this; + + // Copy the offset vector + if(offset){ + vec2.copy(shape.position, offset); + } else { + vec2.set(shape.position, 0, 0); + } + + shape.angle = angle || 0; + + this.shapes.push(shape); + this.updateMassProperties(); + this.updateBoundingRadius(); + + this.aabbNeedsUpdate = true; +}; + +/** + * Remove a shape + * @method removeShape + * @param {Shape} shape + * @return {Boolean} True if the shape was found and removed, else false. + */ +Body.prototype.removeShape = function(shape){ + var idx = this.shapes.indexOf(shape); + + if(idx !== -1){ + this.shapes.splice(idx,1); + this.aabbNeedsUpdate = true; + shape.body = null; + return true; + } else { + return false; + } +}; + +/** + * Updates .inertia, .invMass, .invInertia for this Body. Should be called when + * changing the structure or mass of the Body. + * + * @method updateMassProperties + * + * @example + * body.mass += 1; + * body.updateMassProperties(); + */ +Body.prototype.updateMassProperties = function(){ + if(this.type === Body.STATIC || this.type === 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; + } + + // Inverse mass properties are easy + this.invMass = 1 / this.mass; + + vec2.set( + this.massMultiplier, + this.fixedX ? 0 : 1, + this.fixedY ? 0 : 1 + ); + } +}; + +var Body_applyForce_r = vec2.create(); + +/** + * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero. + * @method applyForce + * @param {Array} force The force to add. + * @param {Array} [relativePoint] A world point to apply the force on. + */ +Body.prototype.applyForce = function(force, relativePoint){ + + // Add linear force + vec2.add(this.force, this.force, force); + + if(relativePoint){ + + // Compute produced rotational force + var rotForce = vec2.crossLength(relativePoint,force); + + // Add rotational force + this.angularForce += rotForce; + } +}; + +/** + * Apply force to a body-local point. + * @method applyForceLocal + * @param {Array} localForce The force vector to add, oriented in local body space. + * @param {Array} [localPoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyForce_forceWorld = vec2.create(); +var Body_applyForce_pointWorld = vec2.create(); +var Body_applyForce_pointLocal = vec2.create(); +Body.prototype.applyForceLocal = function(localForce, localPoint){ + localPoint = localPoint || Body_applyForce_pointLocal; + var worldForce = Body_applyForce_forceWorld; + var worldPoint = Body_applyForce_pointWorld; + this.vectorToWorldFrame(worldForce, localForce); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyForce(worldForce, worldPoint); +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulse + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_velo = vec2.create(); +Body.prototype.applyImpulse = function(impulseVector, relativePoint){ + if(this.type !== Body.DYNAMIC){ + return; + } + + // Compute produced central impulse velocity + var velo = Body_applyImpulse_velo; + vec2.scale(velo, impulseVector, this.invMass); + vec2.multiply(velo, this.massMultiplier, velo); + + // Add linear impulse + vec2.add(this.velocity, velo, this.velocity); + + if(relativePoint){ + // Compute produced rotational impulse velocity + var rotVelo = vec2.crossLength(relativePoint, impulseVector); + rotVelo *= this.invInertia; + + // Add rotational Impulse + this.angularVelocity += rotVelo; + } +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulseLocal + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_impulseWorld = vec2.create(); +var Body_applyImpulse_pointWorld = vec2.create(); +var Body_applyImpulse_pointLocal = vec2.create(); +Body.prototype.applyImpulseLocal = function(localImpulse, localPoint){ + localPoint = localPoint || Body_applyImpulse_pointLocal; + var worldImpulse = Body_applyImpulse_impulseWorld; + var worldPoint = Body_applyImpulse_pointWorld; + this.vectorToWorldFrame(worldImpulse, localImpulse); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyImpulse(worldImpulse, worldPoint); +}; + +/** + * Transform a world point to local body frame. + * @method toLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldPoint The input world point + */ +Body.prototype.toLocalFrame = function(out, worldPoint){ + vec2.toLocalFrame(out, worldPoint, this.position, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method toWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localPoint The input local point + */ +Body.prototype.toWorldFrame = function(out, localPoint){ + vec2.toGlobalFrame(out, localPoint, this.position, this.angle); +}; + +/** + * Transform a world point to local body frame. + * @method vectorToLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldVector The input world vector + */ +Body.prototype.vectorToLocalFrame = function(out, worldVector){ + vec2.vectorToLocalFrame(out, worldVector, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method vectorToWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localVector The input local vector + */ +Body.prototype.vectorToWorldFrame = function(out, localVector){ + vec2.vectorToGlobalFrame(out, localVector, this.angle); +}; + +/** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. + * @method fromPolygon + * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. + * @param {Object} [options] + * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. + * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @return {Boolean} True on success, else false. + */ +Body.prototype.fromPolygon = function(path,options){ + options = options || {}; + + // Remove all shapes + for(var i=this.shapes.length; i>=0; --i){ + this.removeShape(this.shapes[i]); + } + + var p = new decomp.Polygon(); + p.vertices = path; + + // Make it counter-clockwise + p.makeCCW(); + + if(typeof(options.removeCollinearPoints) === "number"){ + p.removeCollinearPoints(options.removeCollinearPoints); + } + + // Check if any line segment intersects the path itself + if(typeof(options.skipSimpleCheck) === "undefined"){ + if(!p.isSimple()){ + return false; + } + } + + // Save this path for later + this.concavePath = p.vertices.slice(0); + for(var i=0; ithis for details. + * @method applyDamping + * @param {number} dt Current time step + */ +Body.prototype.applyDamping = function(dt){ + if(this.type === Body.DYNAMIC){ // Only for dynamic bodies + var v = this.velocity; + vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); + this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); + } +}; + +/** + * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. + * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. + * @method wakeUp + */ +Body.prototype.wakeUp = function(){ + var s = this.sleepState; + this.sleepState = Body.AWAKE; + this.idleTime = 0; + if(s !== Body.AWAKE){ + this.emit(Body.wakeUpEvent); + } +}; + +/** + * Force body sleep + * @method sleep + */ +Body.prototype.sleep = function(){ + this.sleepState = Body.SLEEPING; + this.angularVelocity = 0; + this.angularForce = 0; + vec2.set(this.velocity,0,0); + vec2.set(this.force,0,0); + this.emit(Body.sleepEvent); +}; + +/** + * Called every timestep to update internal sleep timer and change sleep state if needed. + * @method sleepTick + * @param {number} time The world time in seconds + * @param {boolean} dontSleep + * @param {number} dt + */ +Body.prototype.sleepTick = function(time, dontSleep, dt){ + if(!this.allowSleep || this.type === Body.SLEEPING){ + return; + } + + this.wantsToSleep = false; + + var sleepState = this.sleepState, + speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), + speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); + + // Add to idle time + if(speedSquared >= 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; + } + } +}; + +/** + * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. + * @method overlaps + * @param {Body} body + * @return {boolean} + */ +Body.prototype.overlaps = function(body){ + return this.world.overlapKeeper.bodiesAreOverlapping(this, body); +}; + +var integrate_fhMinv = vec2.create(); +var integrate_velodt = vec2.create(); + +/** + * Move the body forward in time given its current velocity. + * @method integrate + * @param {Number} dt + */ +Body.prototype.integrate = function(dt){ + var minv = this.invMass, + f = this.force, + pos = this.position, + velo = this.velocity; + + // Save old position + vec2.copy(this.previousPosition, this.position); + this.previousAngle = this.angle; + + // Velocity update + if(!this.fixedRotation){ + this.angularVelocity += this.angularForce * this.invInertia * dt; + } + vec2.scale(integrate_fhMinv, f, dt * minv); + vec2.multiply(integrate_fhMinv, this.massMultiplier, integrate_fhMinv); + vec2.add(velo, integrate_fhMinv, velo); + + // CCD + if(!this.integrateToTimeOfImpact(dt)){ + + // Regular position update + vec2.scale(integrate_velodt, velo, dt); + vec2.add(pos, pos, integrate_velodt); + if(!this.fixedRotation){ + this.angle += this.angularVelocity * dt; + } + } + + this.aabbNeedsUpdate = true; +}; + +var result = new RaycastResult(); +var ray = new Ray({ + mode: Ray.ALL +}); +var direction = vec2.create(); +var end = vec2.create(); +var startToEnd = vec2.create(); +var rememberPosition = vec2.create(); +Body.prototype.integrateToTimeOfImpact = function(dt){ + + if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){ + return false; + } + + vec2.normalize(direction, this.velocity); + + vec2.scale(end, this.velocity, dt); + vec2.add(end, end, this.position); + + vec2.sub(startToEnd, end, this.position); + var startToEndAngle = this.angularVelocity * dt; + var len = vec2.length(startToEnd); + + var timeOfImpact = 1; + + var hit; + var that = this; + result.reset(); + ray.callback = function (result) { + if(result.body === that){ + return; + } + hit = result.body; + result.getHitPoint(end, ray); + vec2.sub(startToEnd, end, that.position); + timeOfImpact = vec2.length(startToEnd) / len; + result.stop(); + }; + vec2.copy(ray.from, this.position); + vec2.copy(ray.to, end); + ray.update(); + this.world.raycast(result, ray); + + if(!hit){ + return false; + } + + var rememberAngle = this.angle; + vec2.copy(rememberPosition, this.position); + + // Got a start and end point. Approximate time of impact using binary search + var iter = 0; + var tmin = 0; + var tmid = 0; + var tmax = timeOfImpact; + while (tmax >= tmin && iter < this.ccdIterations) { + iter++; + + // calculate the midpoint + tmid = (tmax - tmin) / 2; + + // Move the body to that point + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, rememberPosition, integrate_velodt); + this.angle = rememberAngle + startToEndAngle * timeOfImpact; + this.updateAABB(); + + // check overlap + var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit); + + if (overlaps) { + // change min to search upper interval + tmin = tmid; + } else { + // change max to search lower interval + tmax = tmid; + } + } + + timeOfImpact = tmid; + + vec2.copy(this.position, rememberPosition); + this.angle = rememberAngle; + + // move to TOI + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, this.position, integrate_velodt); + if(!this.fixedRotation){ + this.angle += startToEndAngle * timeOfImpact; + } + + return true; +}; + +/** + * Get velocity of a point in the body. + * @method getVelocityAtPoint + * @param {Array} result A vector to store the result in + * @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from + * @return {Array} The result vector + */ +Body.prototype.getVelocityAtPoint = function(result, relativePoint){ + vec2.crossVZ(result, relativePoint, this.angularVelocity); + vec2.subtract(result, this.velocity, result); + return result; +}; + +/** + * @event sleepy + */ +Body.sleepyEvent = { + type: "sleepy" +}; + +/** + * @event sleep + */ +Body.sleepEvent = { + type: "sleep" +}; + +/** + * @event wakeup + */ +Body.wakeUpEvent = { + type: "wakeup" +}; + +/** + * Dynamic body. + * @property DYNAMIC + * @type {Number} + * @static + */ +Body.DYNAMIC = 1; + +/** + * Static body. + * @property STATIC + * @type {Number} + * @static + */ +Body.STATIC = 2; + +/** + * Kinematic body. + * @property KINEMATIC + * @type {Number} + * @static + */ +Body.KINEMATIC = 4; + +/** + * @property AWAKE + * @type {Number} + * @static + */ +Body.AWAKE = 0; + +/** + * @property SLEEPY + * @type {Number} + * @static + */ +Body.SLEEPY = 1; + +/** + * @property SLEEPING + * @type {Number} + * @static + */ +Body.SLEEPING = 2; + + +},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = LinearSpring; + +/** + * A spring, connecting two bodies. + * + * The Spring explicitly adds force and angularForce to the bodies. + * + * @class LinearSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + */ +function LinearSpring(bodyA,bodyB,options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Anchor for bodyA in local bodyA coordinates. + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = vec2.fromValues(0,0); + + /** + * Anchor for bodyB in local bodyB coordinates. + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = vec2.fromValues(0,0); + + if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); } + if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); } + if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } + if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } + + var worldAnchorA = vec2.create(); + var worldAnchorB = vec2.create(); + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + var worldDistance = vec2.distance(worldAnchorA, worldAnchorB); + + /** + * Rest length of the spring. + * @property restLength + * @type {number} + */ + this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance; +} +LinearSpring.prototype = new Spring(); +LinearSpring.prototype.constructor = LinearSpring; + +/** + * Set the anchor point on body A, using world coordinates. + * @method setWorldAnchorA + * @param {Array} worldAnchorA + */ +LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){ + this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); +}; + +/** + * Set the anchor point on body B, using world coordinates. + * @method setWorldAnchorB + * @param {Array} worldAnchorB + */ +LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){ + this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); +}; + +/** + * Get the anchor point on body A, in world coordinates. + * @method getWorldAnchorA + * @param {Array} result The vector to store the result in. + */ +LinearSpring.prototype.getWorldAnchorA = function(result){ + this.bodyA.toWorldFrame(result, this.localAnchorA); +}; + +/** + * Get the anchor point on body B, in world coordinates. + * @method getWorldAnchorB + * @param {Array} result The vector to store the result in. + */ +LinearSpring.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(); + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +LinearSpring.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; + + // Get world anchors + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + + // Get offset points + vec2.sub(ri, worldAnchorA, bodyA.position); + vec2.sub(rj, worldAnchorB, bodyB.position); + + // Compute distance vector between world anchor points + vec2.sub(r, worldAnchorB, worldAnchorA); + var rlen = vec2.len(r); + vec2.normalize(r_unit,r); + + //console.log(rlen) + //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) + + // Compute relative velocity of the anchor points, u + 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); + + // F = - k * ( x - L ) - D * ( u ) + vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); + + // Add forces to bodies + vec2.sub( bodyA.force, bodyA.force, f); + vec2.add( bodyB.force, bodyB.force, f); + + // Angular force + 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":57,"./Spring":34}],33:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); + +module.exports = RotationalSpring; + +/** + * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies. + * + * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap. + * + * @class RotationalSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. + */ +function RotationalSpring(bodyA, bodyB, options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Rest angle of the spring. + * @property restAngle + * @type {number} + */ + this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle; +} +RotationalSpring.prototype = new Spring(); +RotationalSpring.prototype.constructor = RotationalSpring; + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +RotationalSpring.prototype.applyForce = function(){ + var k = this.stiffness, + d = this.damping, + l = this.restAngle, + bodyA = this.bodyA, + bodyB = this.bodyB, + x = bodyB.angle - bodyA.angle, + u = bodyB.angularVelocity - bodyA.angularVelocity; + + var torque = - k * (x - l) - d * u * 0; + + bodyA.angularForce -= torque; + bodyB.angularForce += torque; +}; + +},{"../math/vec2":30,"./Spring":34}],34:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = Spring; + +/** + * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver. + * + * @class Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + */ +function Spring(bodyA, bodyB, options){ + options = Utils.defaults(options,{ + stiffness: 100, + damping: 1, + }); + + /** + * Stiffness of the spring. + * @property stiffness + * @type {number} + */ + this.stiffness = options.stiffness; + + /** + * Damping of the spring. + * @property damping + * @type {number} + */ + this.damping = options.damping; + + /** + * First connected body. + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second connected body. + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; +} + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +Spring.prototype.applyForce = function(){ + // To be implemented by subclasses +}; + +},{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); +var Constraint = _dereq_('../constraints/Constraint'); +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Body = _dereq_('../objects/Body'); + +module.exports = TopDownVehicle; + +/** + * @class TopDownVehicle + * @constructor + * @param {Body} chassisBody A dynamic body, already added to the world. + * @param {Object} [options] + * + * @example + * + * // Create a dynamic body for the chassis + * var chassisBody = new Body({ + * mass: 1 + * }); + * var boxShape = new Box({ width: 0.5, height: 1 }); + * chassisBody.addShape(boxShape); + * world.addBody(chassisBody); + * + * // Create the vehicle + * var vehicle = new TopDownVehicle(chassisBody); + * + * // Add one front wheel and one back wheel - we don't actually need four :) + * var frontWheel = vehicle.addWheel({ + * localPosition: [0, 0.5] // front + * }); + * frontWheel.setSideFriction(4); + * + * // Back wheel + * var backWheel = vehicle.addWheel({ + * localPosition: [0, -0.5] // back + * }); + * backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift + * vehicle.addToWorld(world); + * + * // Steer value zero means straight forward. Positive is left and negative right. + * frontWheel.steerValue = Math.PI / 16; + * + * // Engine force forward + * backWheel.engineForce = 10; + * backWheel.setBrakeForce(0); + */ +function TopDownVehicle(chassisBody, options){ + options = options || {}; + + /** + * @property {Body} chassisBody + */ + this.chassisBody = chassisBody; + + /** + * @property {Array} wheels + */ + this.wheels = []; + + // A dummy body to constrain the chassis to + this.groundBody = new Body({ mass: 0 }); + + this.world = null; + + var that = this; + this.preStepCallback = function(){ + that.update(); + }; +} + +/** + * @method addToWorld + * @param {World} world + */ +TopDownVehicle.prototype.addToWorld = function(world){ + this.world = world; + world.addBody(this.groundBody); + world.on('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.addConstraint(wheel); + } +}; + +/** + * @method removeFromWorld + * @param {World} world + */ +TopDownVehicle.prototype.removeFromWorld = function(){ + var world = this.world; + world.removeBody(this.groundBody); + world.off('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.removeConstraint(wheel); + } + this.world = null; +}; + +/** + * @method addWheel + * @param {object} [wheelOptions] + * @return {WheelConstraint} + */ +TopDownVehicle.prototype.addWheel = function(wheelOptions){ + var wheel = new WheelConstraint(this,wheelOptions); + this.wheels.push(wheel); + return wheel; +}; + +/** + * @method update + */ +TopDownVehicle.prototype.update = function(){ + for (var i = 0; i < this.wheels.length; i++) { + this.wheels[i].update(); + } +}; + +/** + * @class WheelConstraint + * @constructor + * @extends {Constraint} + * @param {Vehicle} vehicle + * @param {object} [options] + * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero. + * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body. + * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction. + */ +function WheelConstraint(vehicle, options){ + options = options || {}; + + this.vehicle = vehicle; + + this.forwardEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + this.sideEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + /** + * @property {number} steerValue + */ + this.steerValue = 0; + + /** + * @property {number} engineForce + */ + this.engineForce = 0; + + this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5); + + /** + * @property {Array} localForwardVector + */ + this.localForwardVector = vec2.fromValues(0, 1); + if(options.localForwardVector){ + vec2.copy(this.localForwardVector, options.localForwardVector); + } + + /** + * @property {Array} localPosition + */ + this.localPosition = vec2.fromValues(0, 0); + if(options.localPosition){ + vec2.copy(this.localPosition, options.localPosition); + } + + Constraint.apply(this, vehicle.chassisBody, vehicle.groundBody); + + this.equations.push( + this.forwardEquation, + this.sideEquation + ); + + this.setBrakeForce(0); +} +WheelConstraint.prototype = new Constraint(); + +/** + * @method setForwardFriction + */ +WheelConstraint.prototype.setBrakeForce = function(force){ + this.forwardEquation.setSlipForce(force); +}; + +/** + * @method setSideFriction + */ +WheelConstraint.prototype.setSideFriction = function(force){ + this.sideEquation.setSlipForce(force); +}; + +var worldVelocity = vec2.create(); +var relativePoint = vec2.create(); + +/** + * @method getSpeed + */ +WheelConstraint.prototype.getSpeed = function(){ + this.vehicle.chassisBody.vectorToWorldFrame(relativePoint, this.localForwardVector); + this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity, relativePoint); + return vec2.dot(worldVelocity, relativePoint); +}; + +var tmpVec = vec2.create(); + +/** + * @method update + */ +WheelConstraint.prototype.update = function(){ + + // Directional + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t, this.localForwardVector); + vec2.rotate(this.sideEquation.t, this.localForwardVector, Math.PI / 2); + this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t, this.sideEquation.t); + + vec2.rotate(this.forwardEquation.t, this.forwardEquation.t, this.steerValue); + vec2.rotate(this.sideEquation.t, this.sideEquation.t, this.steerValue); + + // Attachment point + this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB, this.localPosition); + vec2.copy(this.sideEquation.contactPointB, this.forwardEquation.contactPointB); + + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA, this.localPosition); + vec2.copy(this.sideEquation.contactPointA, this.forwardEquation.contactPointA); + + // Add engine force + vec2.normalize(tmpVec, this.forwardEquation.t); + vec2.scale(tmpVec, tmpVec, this.engineForce); + + this.vehicle.chassisBody.applyForce(tmpVec, this.forwardEquation.contactPointA); +}; +},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(_dereq_,module,exports){ +// Export p2 classes +var p2 = module.exports = { + AABB : _dereq_('./collision/AABB'), + AngleLockEquation : _dereq_('./equations/AngleLockEquation'), + Body : _dereq_('./objects/Body'), + Broadphase : _dereq_('./collision/Broadphase'), + Capsule : _dereq_('./shapes/Capsule'), + Circle : _dereq_('./shapes/Circle'), + Constraint : _dereq_('./constraints/Constraint'), + ContactEquation : _dereq_('./equations/ContactEquation'), + ContactEquationPool : _dereq_('./utils/ContactEquationPool'), + ContactMaterial : _dereq_('./material/ContactMaterial'), + Convex : _dereq_('./shapes/Convex'), + DistanceConstraint : _dereq_('./constraints/DistanceConstraint'), + Equation : _dereq_('./equations/Equation'), + EventEmitter : _dereq_('./events/EventEmitter'), + FrictionEquation : _dereq_('./equations/FrictionEquation'), + FrictionEquationPool : _dereq_('./utils/FrictionEquationPool'), + GearConstraint : _dereq_('./constraints/GearConstraint'), + GSSolver : _dereq_('./solver/GSSolver'), + Heightfield : _dereq_('./shapes/Heightfield'), + Line : _dereq_('./shapes/Line'), + LockConstraint : _dereq_('./constraints/LockConstraint'), + Material : _dereq_('./material/Material'), + Narrowphase : _dereq_('./collision/Narrowphase'), + NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'), + Particle : _dereq_('./shapes/Particle'), + Plane : _dereq_('./shapes/Plane'), + Pool : _dereq_('./utils/Pool'), + RevoluteConstraint : _dereq_('./constraints/RevoluteConstraint'), + PrismaticConstraint : _dereq_('./constraints/PrismaticConstraint'), + Ray : _dereq_('./collision/Ray'), + RaycastResult : _dereq_('./collision/RaycastResult'), + Box : _dereq_('./shapes/Box'), + RotationalVelocityEquation : _dereq_('./equations/RotationalVelocityEquation'), + SAPBroadphase : _dereq_('./collision/SAPBroadphase'), + Shape : _dereq_('./shapes/Shape'), + Solver : _dereq_('./solver/Solver'), + Spring : _dereq_('./objects/Spring'), + TopDownVehicle : _dereq_('./objects/TopDownVehicle'), + LinearSpring : _dereq_('./objects/LinearSpring'), + RotationalSpring : _dereq_('./objects/RotationalSpring'), + Utils : _dereq_('./utils/Utils'), + World : _dereq_('./world/World'), + vec2 : _dereq_('./math/vec2'), + version : _dereq_('../package.json').version, +}; + +Object.defineProperty(p2, 'Rectangle', { + get: function() { + console.warn('The Rectangle class has been renamed to Box.'); + return this.Box; + } +}); +},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":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/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Shape = _dereq_('./Shape') +, Convex = _dereq_('./Convex'); + +module.exports = Box; + +/** + * Box shape class. + * @class Box + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.width=1] Total width of the box + * @param {Number} [options.height=1] Total height of the box + * @extends Convex + */ +function Box(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + width: arguments[0], + height: arguments[1] + }; + console.warn('The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })'); + } + options = options || {}; + + /** + * Total width of the box + * @property width + * @type {Number} + */ + var width = this.width = options.width || 1; + + /** + * Total height of the box + * @property height + * @type {Number} + */ + var height = this.height = options.height || 1; + + var verts = [ + vec2.fromValues(-width/2, -height/2), + vec2.fromValues( width/2, -height/2), + vec2.fromValues( width/2, height/2), + vec2.fromValues(-width/2, height/2) + ]; + var axes = [ + vec2.fromValues(1, 0), + vec2.fromValues(0, 1) + ]; + + options.vertices = verts; + options.axes = axes; + options.type = Shape.BOX; + Convex.call(this, options); +} +Box.prototype = new Convex(); +Box.prototype.constructor = Box; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Box.prototype.computeMomentOfInertia = function(mass){ + var w = this.width, + h = this.height; + return mass * (h*h + w*w) / 12; +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Box.prototype.updateBoundingRadius = function(){ + var w = this.width, + h = this.height; + this.boundingRadius = Math.sqrt(w*w + h*h) / 2; +}; + +var corner1 = vec2.create(), + corner2 = vec2.create(), + corner3 = vec2.create(), + corner4 = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Box.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices,position,angle,0); +}; + +Box.prototype.updateArea = function(){ + this.area = this.width * this.height; +}; + + +},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Capsule; + +/** + * Capsule shape class. + * @class Capsule + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The distance between the end points + * @param {Number} [options.radius=1] Radius of the capsule + * @example + * var capsuleShape = new Capsule({ + * length: 1, + * radius: 2 + * }); + * body.addShape(capsuleShape); + */ +function Capsule(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + length: arguments[0], + radius: arguments[1] + }; + console.warn('The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })'); + } + options = options || {}; + + /** + * The distance between the end points. + * @property {Number} length + */ + this.length = options.length || 1; + + /** + * The radius of the capsule. + * @property {Number} radius + */ + this.radius = options.radius || 1; + + options.type = Shape.CAPSULE; + Shape.call(this, options); +} +Capsule.prototype = new Shape(); +Capsule.prototype.constructor = Capsule; + +/** + * Compute the mass moment of inertia of the Capsule. + * @method conputeMomentOfInertia + * @param {Number} mass + * @return {Number} + * @todo + */ +Capsule.prototype.computeMomentOfInertia = function(mass){ + // Approximate with rectangle + var r = this.radius, + w = this.length + r, // 2*r is too much, 0 is too little + h = r*2; + return mass * (h*h + w*w) / 12; +}; + +/** + * @method updateBoundingRadius + */ +Capsule.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius + this.length/2; +}; + +/** + * @method updateArea + */ +Capsule.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; +}; + +var r = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Capsule.prototype.computeAABB = function(out, position, angle){ + var radius = this.radius; + + // Compute center position of one of the the circles, world oriented, but with local offset + vec2.set(r,this.length / 2,0); + if(angle !== 0){ + vec2.rotate(r,r,angle); + } + + // Get bounds + 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)); + + // Add offset + vec2.add(out.lowerBound, out.lowerBound, position); + vec2.add(out.upperBound, out.upperBound, position); +}; + +var intersectCapsule_hitPointWorld = vec2.create(); +var intersectCapsule_normal = vec2.create(); +var intersectCapsule_l0 = vec2.create(); +var intersectCapsule_l1 = vec2.create(); +var intersectCapsule_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Capsule.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectCapsule_hitPointWorld; + var normal = intersectCapsule_normal; + var l0 = intersectCapsule_l0; + var l1 = intersectCapsule_l1; + + // The sides + var halfLen = this.length / 2; + for(var i=0; i<2; i++){ + + // get start and end of the line + var y = this.radius * (i*2-1); + vec2.set(l0, -halfLen, y); + vec2.set(l1, halfLen, y); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var delta = vec2.getLineSegmentsIntersectionFraction(from, to, l0, l1); + if(delta >= 0){ + vec2.rotate(normal, intersectCapsule_unit_y, angle); + vec2.scale(normal, normal, (i*2-1)); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + // Circles + var diagonalLengthSquared = Math.pow(this.radius, 2) + Math.pow(halfLen, 2); + for(var i=0; i<2; i++){ + vec2.set(l0, halfLen * (i*2-1), 0); + vec2.toGlobalFrame(l0, l0, position, angle); + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - l0[0]) + (to[1] - from[1]) * (from[1] - l0[1])); + var c = Math.pow(from[0] - l0[0], 2) + Math.pow(from[1] - l0[1], 2) - Math.pow(this.radius, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + if(delta < 0){ + // No intersection + continue; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(hitPointWorld, from, to, delta); + + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(hitPointWorld, from, to, d1); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d1, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(hitPointWorld, from, to, d2); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d2, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + } + } +}; +},{"../math/vec2":30,"./Shape":45}],39:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Circle; + +/** + * Circle shape class. + * @class Circle + * @extends Shape + * @constructor + * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {number} [options.radius=1] The radius of this circle + * + * @example + * var circleShape = new Circle({ radius: 1 }); + * body.addShape(circleShape); + */ +function Circle(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + radius: arguments[0] + }; + console.warn('The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })'); + } + options = options || {}; + + /** + * The radius of the circle. + * @property radius + * @type {number} + */ + this.radius = options.radius || 1; + + options.type = Shape.CIRCLE; + Shape.call(this, options); +} +Circle.prototype = new Shape(); +Circle.prototype.constructor = Circle; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Circle.prototype.computeMomentOfInertia = function(mass){ + var r = this.radius; + return mass * r * r / 2; +}; + +/** + * @method updateBoundingRadius + * @return {Number} + */ +Circle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius; +}; + +/** + * @method updateArea + * @return {Number} + */ +Circle.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius; +}; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +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); + } +}; + +var Ray_intersectSphere_intersectionPoint = vec2.create(); +var Ray_intersectSphere_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Circle.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from, + to = ray.to, + r = this.radius; + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1])); + var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + var intersectionPoint = Ray_intersectSphere_intersectionPoint; + var normal = Ray_intersectSphere_normal; + + if(delta < 0){ + // No intersection + return; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(intersectionPoint, from, to, delta); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, delta, normal, -1); + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(intersectionPoint, from, to, d1); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d1, normal, -1); + + if(result.shouldStop(ray)){ + return; + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(intersectionPoint, from, to, d2); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d2, normal, -1); + } + } +}; +},{"../math/vec2":30,"./Shape":45}],40:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, polyk = _dereq_('../math/polyk') +, decomp = _dereq_('poly-decomp'); + +module.exports = Convex; + +/** + * Convex shape class. + * @class Convex + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. + * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex. + * @example + * // Create a box + * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]]; + * var convexShape = new Convex({ vertices: vertices }); + * body.addShape(convexShape); + */ +function Convex(options){ + if(Array.isArray(arguments[0])){ + options = { + vertices: arguments[0], + axes: arguments[1] + }; + console.warn('The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })'); + } + options = options || {}; + + /** + * Vertices defined in the local frame. + * @property vertices + * @type {Array} + */ + this.vertices = []; + + // Copy the verts + var vertices = options.vertices !== undefined ? options.vertices : []; + for(var i=0; i < vertices.length; i++){ + var v = vec2.create(); + vec2.copy(v, vertices[i]); + this.vertices.push(v); + } + + /** + * Axes defined in the local frame. + * @property axes + * @type {Array} + */ + this.axes = []; + + if(options.axes){ + + // Copy the axes + for(var i=0; i < options.axes.length; i++){ + var axis = vec2.create(); + vec2.copy(axis, options.axes[i]); + this.axes.push(axis); + } + + } else { + + // Construct axes from the vertex data + for(var i = 0; i < this.vertices.length; i++){ + // Get the world edge + var worldPoint0 = this.vertices[i]; + var worldPoint1 = this.vertices[(i+1) % this.vertices.length]; + + var normal = vec2.create(); + vec2.sub(normal, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, normal); + vec2.normalize(normal, normal); + + this.axes.push(normal); + } + + } + + /** + * The center of mass of the Convex + * @property centerOfMass + * @type {Array} + */ + this.centerOfMass = vec2.fromValues(0,0); + + /** + * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. + * @property triangles + * @type {Array} + */ + this.triangles = []; + + if(this.vertices.length){ + this.updateTriangles(); + this.updateCenterOfMass(); + } + + /** + * The bounding radius of the convex + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + options.type = Shape.CONVEX; + Shape.call(this, options); + + this.updateBoundingRadius(); + this.updateArea(); + if(this.area < 0){ + throw new Error("Convex vertices must be given in conter-clockwise winding."); + } +} +Convex.prototype = new Shape(); +Convex.prototype.constructor = Convex; + +var tmpVec1 = vec2.create(); +var tmpVec2 = vec2.create(); + +/** + * Project a Convex onto a world-oriented axis + * @method projectOntoAxis + * @static + * @param {Array} offset + * @param {Array} localAxis + * @param {Array} result + */ +Convex.prototype.projectOntoLocalAxis = function(localAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = tmpVec1; + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + vec2.set(result, min, max); +}; + +Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){ + var worldAxis = tmpVec2; + + this.projectOntoLocalAxis(localAxis, result); + + // Project the position of the body onto the axis - need to add this to the result + if(shapeAngle !== 0){ + vec2.rotate(worldAxis, localAxis, shapeAngle); + } else { + worldAxis = localAxis; + } + var offset = vec2.dot(shapeOffset, worldAxis); + + vec2.set(result, result[0] + offset, result[1] + offset); +}; + + +/** + * Update the .triangles property + * @method updateTriangles + */ +Convex.prototype.updateTriangles = function(){ + + this.triangles.length = 0; + + // Rewrite on polyk notation, array of numbers + var polykVerts = []; + for(var i=0; i r2){ + r2 = l2; + } + } + + this.boundingRadius = Math.sqrt(r2); +}; + +/** + * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. + * @static + * @method triangleArea + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +Convex.triangleArea = function(a,b,c){ + return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; +}; + +/** + * Update the .area + * @method updateArea + */ +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]]; + + // Get mass for the triangle (density=1 in this case) + var m = Convex.triangleArea(a,b,c); + this.area += m; + } +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Convex.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices, position, angle, 0); +}; + +var intersectConvex_rayStart = vec2.create(); +var intersectConvex_rayEnd = vec2.create(); +var intersectConvex_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Convex.prototype.raycast = function(result, ray, position, angle){ + var rayStart = intersectConvex_rayStart; + var rayEnd = intersectConvex_rayEnd; + var normal = intersectConvex_normal; + var vertices = this.vertices; + + // Transform to local shape space + vec2.toLocalFrame(rayStart, ray.from, position, angle); + vec2.toLocalFrame(rayEnd, ray.to, position, angle); + + var n = vertices.length; + + for (var i = 0; i < n && !result.shouldStop(ray); i++) { + var q1 = vertices[i]; + var q2 = vertices[(i+1) % n]; + var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2); + + if(delta >= 0){ + vec2.sub(normal, q2, q1); + vec2.rotate(normal, normal, -Math.PI / 2 + angle); + vec2.normalize(normal, normal); + ray.reportIntersection(result, delta, normal, i); + } + } +}; + +},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Heightfield; + +/** + * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". + * @class Heightfield + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {array} [options.heights] An array of Y values that will be used to construct the terrain. + * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given. + * @param {Number} [options.maxValue] Maximum value. + * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction. + * + * @example + * // Generate some height data (y-values). + * var heights = []; + * for(var i = 0; i < 1000; i++){ + * var y = 0.5 * Math.cos(0.2 * i); + * heights.push(y); + * } + * + * // Create the heightfield shape + * var heightfieldShape = new Heightfield({ + * heights: heights, + * elementWidth: 1 // Distance between the data points in X direction + * }); + * var heightfieldBody = new Body(); + * heightfieldBody.addShape(heightfieldShape); + * world.addBody(heightfieldBody); + * + * @todo Should use a scale property with X and Y direction instead of just elementWidth + */ +function Heightfield(options){ + if(Array.isArray(arguments[0])){ + options = { + heights: arguments[0] + }; + + if(typeof(arguments[1]) === 'object'){ + for(var key in arguments[1]){ + options[key] = arguments[1][key]; + } + } + + console.warn('The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })'); + } + options = options || {}; + + /** + * An array of numbers, or height values, that are spread out along the x axis. + * @property {array} heights + */ + this.heights = options.heights ? options.heights.slice(0) : []; + + /** + * Max value of the heights + * @property {number} maxValue + */ + this.maxValue = options.maxValue || null; + + /** + * Max value of the heights + * @property {number} minValue + */ + this.minValue = options.minValue || null; + + /** + * The width of each element + * @property {number} elementWidth + */ + this.elementWidth = options.elementWidth || 0.1; + + if(options.maxValue === undefined || options.minValue === undefined){ + this.updateMaxMinValues(); + } + + options.type = Shape.HEIGHTFIELD; + Shape.call(this, options); +} +Heightfield.prototype = new Shape(); +Heightfield.prototype.constructor = Heightfield; + +/** + * Update the .minValue and the .maxValue + * @method updateMaxMinValues + */ +Heightfield.prototype.updateMaxMinValues = function(){ + var data = this.heights; + var maxValue = data[0]; + var minValue = data[0]; + for(var i=0; i !== data.length; i++){ + var v = data[i]; + if(v > maxValue){ + maxValue = v; + } + if(v < minValue){ + minValue = v; + } + } + this.maxValue = maxValue; + this.minValue = minValue; +}; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Heightfield.prototype.computeMomentOfInertia = function(mass){ + return Number.MAX_VALUE; +}; + +Heightfield.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +Heightfield.prototype.updateArea = function(){ + var data = this.heights, + area = 0; + for(var i=0; i= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + var intX = p0[0] + (t * s1_x); + var intY = p0[1] + (t * s1_y); + out[0] = intX; + out[1] = intY; + return t; + } + return -1; // No collision +} + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Heightfield.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectHeightfield_hitPointWorld; + var worldNormal = intersectHeightfield_worldNormal; + var l0 = intersectHeightfield_l0; + var l1 = intersectHeightfield_l1; + var localFrom = intersectHeightfield_localFrom; + var localTo = intersectHeightfield_localTo; + + // get local ray start and end + vec2.toLocalFrame(localFrom, from, position, angle); + vec2.toLocalFrame(localTo, to, position, angle); + + // Get the segment range + var i0 = this.getClampedSegmentIndex(localFrom); + var i1 = this.getClampedSegmentIndex(localTo); + if(i0 > i1){ + var tmp = i0; + i0 = i1; + i1 = tmp; + } + + // The segments + for(var i=0; i= 0){ + vec2.sub(worldNormal, l1, l0); + vec2.rotate(worldNormal, worldNormal, angle + Math.PI / 2); + vec2.normalize(worldNormal, worldNormal); + ray.reportIntersection(result, t, worldNormal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Line; + +/** + * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * @class Line + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The total length of the line + * @extends Shape + * @constructor + */ +function Line(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + length: arguments[0] + }; + console.warn('The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })'); + } + options = options || {}; + + /** + * Length of this line + * @property {Number} length + * @default 1 + */ + this.length = options.length || 1; + + options.type = Shape.LINE; + Shape.call(this, options); +} +Line.prototype = new Shape(); +Line.prototype.constructor = Line; + +Line.prototype.computeMomentOfInertia = function(mass){ + return mass * Math.pow(this.length,2) / 12; +}; + +Line.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.length/2; +}; + +var points = [vec2.create(),vec2.create()]; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Line.prototype.computeAABB = function(out, position, angle){ + var l2 = this.length / 2; + vec2.set(points[0], -l2, 0); + vec2.set(points[1], l2, 0); + out.setFromPoints(points,position,angle,0); +}; + +var raycast_hitPoint = vec2.create(); +var raycast_normal = vec2.create(); +var raycast_l0 = vec2.create(); +var raycast_l1 = vec2.create(); +var raycast_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {number} angle + * @param {array} position + */ +Line.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + + var l0 = raycast_l0; + var l1 = raycast_l1; + + // get start and end of the line + var halfLen = this.length / 2; + vec2.set(l0, -halfLen, 0); + vec2.set(l1, halfLen, 0); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to); + if(fraction >= 0){ + var normal = raycast_normal; + vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from + ray.reportIntersection(result, fraction, normal, -1); + } +}; +},{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Particle; + +/** + * Particle shape class. + * @class Particle + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @extends Shape + */ +function Particle(options){ + options = options || {}; + options.type = Shape.PARTICLE; + Shape.call(this, options); +} +Particle.prototype = new Shape(); +Particle.prototype.constructor = Particle; + +Particle.prototype.computeMomentOfInertia = function(mass){ + return 0; // Can't rotate a particle +}; + +Particle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = 0; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Particle.prototype.computeAABB = function(out, position, angle){ + vec2.copy(out.lowerBound, position); + vec2.copy(out.upperBound, position); +}; + +},{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Plane; + +/** + * Plane shape class. The plane is facing in the Y direction. + * @class Plane + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + */ +function Plane(options){ + options = options || {}; + options.type = Shape.PLANE; + Shape.call(this, options); +} +Plane.prototype = new Shape(); +Plane.prototype.constructor = Plane; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + */ +Plane.prototype.computeMomentOfInertia = function(mass){ + return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Plane.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Plane.prototype.computeAABB = function(out, position, angle){ + var a = angle % (2 * Math.PI); + var set = vec2.set; + var max = 1e7; + var lowerBound = out.lowerBound; + var upperBound = out.upperBound; + + // Set max bounds + set(lowerBound, -max, -max); + set(upperBound, max, max); + + if(a === 0){ + // y goes from -inf to 0 + upperBound[1] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, max, 0); + + } else if(a === Math.PI / 2){ + + // x goes from 0 to inf + lowerBound[0] = 0; + // set(lowerBound, 0, -max); + // set(upperBound, max, max); + + } else if(a === Math.PI){ + + // y goes from 0 to inf + lowerBound[1] = 0; + // set(lowerBound, -max, 0); + // set(upperBound, max, max); + + } else if(a === 3*Math.PI/2){ + + // x goes from -inf to 0 + upperBound[0] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, 0, max); + + } +}; + +Plane.prototype.updateArea = function(){ + this.area = Number.MAX_VALUE; +}; + +var intersectPlane_planePointToFrom = vec2.create(); +var intersectPlane_dir_scaled_with_t = vec2.create(); +var intersectPlane_hitPoint = vec2.create(); +var intersectPlane_normal = vec2.create(); +var intersectPlane_len = vec2.create(); + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Plane.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + var planePointToFrom = intersectPlane_planePointToFrom; + var dir_scaled_with_t = intersectPlane_dir_scaled_with_t; + var hitPoint = intersectPlane_hitPoint; + var normal = intersectPlane_normal; + var len = intersectPlane_len; + + // Get plane normal + vec2.set(normal, 0, 1); + vec2.rotate(normal, normal, angle); + + vec2.sub(len, from, position); + var planeToFrom = vec2.dot(len, normal); + vec2.sub(len, to, position); + var planeToTo = vec2.dot(len, normal); + + if(planeToFrom * planeToTo > 0){ + // "from" and "to" are on the same side of the plane... bail out + return; + } + + if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){ + return; + } + + var n_dot_dir = vec2.dot(normal, direction); + + vec2.sub(planePointToFrom, from, position); + var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length; + + ray.reportIntersection(result, t, normal, -1); +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(_dereq_,module,exports){ +module.exports = Shape; + +var vec2 = _dereq_('../math/vec2'); + +/** + * Base class for shapes. + * @class Shape + * @constructor + * @param {object} [options] + * @param {array} [options.position] + * @param {number} [options.angle=0] + * @param {number} [options.collisionGroup=1] + * @param {number} [options.collisionMask=1] + * @param {boolean} [options.sensor=false] + * @param {boolean} [options.collisionResponse=true] + * @param {object} [options.type=0] + */ +function Shape(options){ + options = options || {}; + + /** + * The body this shape is attached to. A shape can only be attached to a single body. + * @property {Body} body + */ + this.body = null; + + /** + * Body-local position of the shape. + * @property {Array} position + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * Body-local angle of the shape. + * @property {number} angle + */ + this.angle = options.angle || 0; + + /** + * The type of the shape. One of: + * + * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} + * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} + * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} + * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} + * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} + * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}} + * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} + * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} + * + * @property {number} type + */ + this.type = options.type || 0; + + /** + * Shape object identifier. + * @type {Number} + * @property id + */ + this.id = Shape.idCounter++; + + /** + * Bounding circle radius of this shape + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + /** + * Collision group that this shape belongs to (bit mask). See this tutorial. + * @property collisionGroup + * @type {Number} + * @example + * // Setup bits for each available group + * var PLAYER = Math.pow(2,0), + * ENEMY = Math.pow(2,1), + * GROUND = Math.pow(2,2) + * + * // Put shapes into their groups + * player1Shape.collisionGroup = PLAYER; + * player2Shape.collisionGroup = PLAYER; + * enemyShape .collisionGroup = ENEMY; + * groundShape .collisionGroup = GROUND; + * + * // Assign groups that each shape collide with. + * // Note that the players can collide with ground and enemies, but not with other players. + * player1Shape.collisionMask = ENEMY | GROUND; + * player2Shape.collisionMask = ENEMY | GROUND; + * enemyShape .collisionMask = PLAYER | GROUND; + * groundShape .collisionMask = PLAYER | ENEMY; + * + * @example + * // How collision check is done + * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ + * // The shapes will collide + * } + */ + this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. + * @property {Boolean} collisionResponse + */ + this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; + + /** + * Collision mask of this shape. See .collisionGroup. + * @property collisionMask + * @type {Number} + */ + this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; + + /** + * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. + * @property material + * @type {Material} + */ + this.material = options.material || null; + + /** + * Area of this shape. + * @property area + * @type {Number} + */ + this.area = 0; + + /** + * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. + * @property {Boolean} sensor + */ + this.sensor = options.sensor !== undefined ? options.sensor : false; + + if(this.type){ + this.updateBoundingRadius(); + } + + this.updateArea(); +} + +Shape.idCounter = 0; + +/** + * @static + * @property {Number} CIRCLE + */ +Shape.CIRCLE = 1; + +/** + * @static + * @property {Number} PARTICLE + */ +Shape.PARTICLE = 2; + +/** + * @static + * @property {Number} PLANE + */ +Shape.PLANE = 4; + +/** + * @static + * @property {Number} CONVEX + */ +Shape.CONVEX = 8; + +/** + * @static + * @property {Number} LINE + */ +Shape.LINE = 16; + +/** + * @static + * @property {Number} BOX + */ +Shape.BOX = 32; + +/** + * @static + * @property {Number} CAPSULE + */ +Shape.CAPSULE = 64; + +/** + * @static + * @property {Number} HEIGHTFIELD + */ +Shape.HEIGHTFIELD = 128; + +/** + * Should return the moment of inertia around the Z axis of the body given the total mass. See Wikipedia's list of moments of inertia. + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. + */ +Shape.prototype.computeMomentOfInertia = function(mass){}; + +/** + * Returns the bounding circle radius of this shape. + * @method updateBoundingRadius + * @return {Number} + */ +Shape.prototype.updateBoundingRadius = function(){}; + +/** + * Update the .area property of the shape. + * @method updateArea + */ +Shape.prototype.updateArea = function(){ + // To be implemented in all subclasses +}; + +/** + * Compute the world axis-aligned bounding box (AABB) of this shape. + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position World position of the shape. + * @param {Number} angle World angle of the shape. + */ +Shape.prototype.computeAABB = function(out, position, angle){ + // To be implemented in each subclass +}; + +/** + * Perform raycasting on this shape. + * @method raycast + * @param {RayResult} result Where to store the resulting data. + * @param {Ray} ray The Ray that you want to use for raycasting. + * @param {array} position World position of the shape (the .position property will be ignored). + * @param {number} angle World angle of the shape (the .angle property will be ignored). + */ +Shape.prototype.raycast = function(result, ray, position, angle){ + // To be implemented in each subclass +}; +},{"../math/vec2":30}],46:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Solver = _dereq_('./Solver') +, Utils = _dereq_('../utils/Utils') +, FrictionEquation = _dereq_('../equations/FrictionEquation'); + +module.exports = GSSolver; + +/** + * Iterative Gauss-Seidel constraint equation solver. + * + * @class GSSolver + * @constructor + * @extends Solver + * @param {Object} [options] + * @param {Number} [options.iterations=10] + * @param {Number} [options.tolerance=0] + */ +function GSSolver(options){ + Solver.call(this,options,Solver.GS); + options = options || {}; + + /** + * The max number of iterations to do when solving. More gives better results, but is more expensive. + * @property iterations + * @type {Number} + */ + this.iterations = options.iterations || 10; + + /** + * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. + * @property tolerance + * @type {Number} + * @default 1e-7 + */ + this.tolerance = options.tolerance || 1e-7; + + this.arrayStep = 30; + this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); + + /** + * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. + * @property useZeroRHS + * @type {Boolean} + * @todo Remove, not used + */ + this.useZeroRHS = false; + + /** + * Number of solver iterations that are used to approximate normal forces used for friction (F_friction = mu * F_normal). These friction forces will override any other friction forces that are set. If you set frictionIterations = 0, then this feature will be disabled. + * + * Use only frictionIterations > 0 if the approximated normal force (F_normal = mass * gravity) is not good enough. Examples of where it can happen is in space games where gravity is zero, or in tall stacks where the normal force is large at bottom but small at top. + * + * @property frictionIterations + * @type {Number} + * @default 0 + */ + this.frictionIterations = options.frictionIterations !== undefined ? 0 : options.frictionIterations; + + /** + * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. + * @property {Number} usedIterations + */ + this.usedIterations = 0; +} +GSSolver.prototype = new Solver(); +GSSolver.prototype.constructor = GSSolver; + +function setArrayZero(array){ + var l = array.length; + while(l--){ + array[l] = +0.0; + } +} + +/** + * Solve the system of equations + * @method solve + * @param {Number} h Time step + * @param {World} world World to solve + */ +GSSolver.prototype.solve = function(h, world){ + + this.sortEquations(); + + var iter = 0, + maxIter = this.iterations, + maxFrictionIter = this.frictionIterations, + equations = this.equations, + Neq = equations.length, + tolSquared = Math.pow(this.tolerance*Neq, 2), + bodies = world.bodies, + Nbodies = world.bodies.length, + add = vec2.add, + set = vec2.set, + useZeroRHS = this.useZeroRHS, + lambda = this.lambda; + + this.usedIterations = 0; + + if(Neq){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Update solve mass + b.updateSolveMassProperties(); + } + } + + // Things that does not change during iteration can be computed once + if(lambda.length < Neq){ + lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + } + setArrayZero(lambda); + var invCs = this.invCs, + Bs = this.Bs, + lambda = this.lambda; + + for(var i=0; i!==equations.length; i++){ + var c = equations[i]; + if(c.timeStep !== h || c.needsUpdate){ + c.timeStep = h; + c.update(); + } + Bs[i] = c.computeB(c.a,c.b,h); + invCs[i] = c.computeInvC(c.epsilon); + } + + var q, B, c, deltalambdaTot,i,j; + + if(Neq !== 0){ + + for(i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Reset vlambda + b.resetConstraintVelocity(); + } + + if(maxFrictionIter){ + // Iterate over contact equations to get normal forces + for(iter=0; iter!==maxFrictionIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + + // Set computed friction force + for(j=0; j!==Neq; j++){ + var eq = equations[j]; + if(eq instanceof FrictionEquation){ + var f = 0.0; + for(var k=0; k!==eq.contactEquations.length; k++){ + f += eq.contactEquations[k].multiplier; + } + f *= eq.frictionCoefficient / eq.contactEquations.length; + eq.maxForce = f; + eq.minForce = -f; + } + } + } + + // Iterate over all equations + for(iter=0; iter!==maxIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + // Add result to velocity + for(i=0; i!==Nbodies; i++){ + bodies[i].addConstraintVelocity(); + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + } +}; + +// Sets the .multiplier property of each equation +GSSolver.updateMultipliers = function(equations, lambda, invDt){ + // Set the .multiplier property of each equation + var l = equations.length; + while(l--){ + equations[l].multiplier = lambda[l] * invDt; + } +}; + +GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ + // Compute iteration + var B = Bs[j], + invC = invCs[j], + lambdaj = lambda[j], + GWlambda = eq.computeGWlambda(); + + var maxForce = eq.maxForce, + minForce = eq.minForce; + + if(useZeroRHS){ + B = 0; + } + + var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); + + // Clamp if we are not within the min/max interval + var lambdaj_plus_deltalambda = lambdaj + deltalambda; + if(lambdaj_plus_deltalambda < minForce*dt){ + deltalambda = minForce*dt - lambdaj; + } else if(lambdaj_plus_deltalambda > maxForce*dt){ + deltalambda = maxForce*dt - lambdaj; + } + lambda[j] += deltalambda; + eq.addToWlambda(deltalambda); + + return deltalambda; +}; + +},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Solver; + +/** + * Base class for constraint solvers. + * @class Solver + * @constructor + * @extends EventEmitter + */ +function Solver(options,type){ + options = options || {}; + + EventEmitter.call(this); + + this.type = type; + + /** + * Current equations in the solver. + * + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Function that is used to sort all equations before each solve. + * @property equationSortFunction + * @type {function|boolean} + */ + this.equationSortFunction = options.equationSortFunction || false; +} +Solver.prototype = new EventEmitter(); +Solver.prototype.constructor = Solver; + +/** + * Method to be implemented in each subclass + * @method solve + * @param {Number} dt + * @param {World} world + */ +Solver.prototype.solve = function(dt,world){ + throw new Error("Solver.solve should be implemented by subclasses!"); +}; + +var mockWorld = {bodies:[]}; + +/** + * Solves all constraints in an island. + * @method solveIsland + * @param {Number} dt + * @param {Island} island + */ +Solver.prototype.solveIsland = function(dt,island){ + + this.removeAllEquations(); + + if(island.equations.length){ + // Add equations to solver + this.addEquations(island.equations); + mockWorld.bodies.length = 0; + island.getBodies(mockWorld.bodies); + + // Solve + if(mockWorld.bodies.length){ + this.solve(dt,mockWorld); + } + } +}; + +/** + * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. + * @method sortEquations + */ +Solver.prototype.sortEquations = function(){ + if(this.equationSortFunction){ + this.equations.sort(this.equationSortFunction); + } +}; + +/** + * Add an equation to be solved. + * + * @method addEquation + * @param {Equation} eq + */ +Solver.prototype.addEquation = function(eq){ + if(eq.enabled){ + this.equations.push(eq); + } +}; + +/** + * Add equations. Same as .addEquation, but this time the argument is an array of Equations + * + * @method addEquations + * @param {Array} eqs + */ +Solver.prototype.addEquations = function(eqs){ + //Utils.appendArray(this.equations,eqs); + for(var i=0, N=eqs.length; i!==N; i++){ + var eq = eqs[i]; + if(eq.enabled){ + this.equations.push(eq); + } + } +}; + +/** + * Remove an equation. + * + * @method removeEquation + * @param {Equation} eq + */ +Solver.prototype.removeEquation = function(eq){ + var i = this.equations.indexOf(eq); + if(i !== -1){ + this.equations.splice(i,1); + } +}; + +/** + * Remove all currently added equations. + * + * @method removeAllEquations + */ +Solver.prototype.removeAllEquations = function(){ + this.equations.length=0; +}; + +Solver.GS = 1; +Solver.ISLAND = 2; + +},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){ +var ContactEquation = _dereq_('../equations/ContactEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = ContactEquationPool; + +/** + * @class + */ +function ContactEquationPool() { + Pool.apply(this, arguments); +} +ContactEquationPool.prototype = new Pool(); +ContactEquationPool.prototype.constructor = ContactEquationPool; + +/** + * @method create + * @return {ContactEquation} + */ +ContactEquationPool.prototype.create = function () { + return new ContactEquation(); +}; + +/** + * @method destroy + * @param {ContactEquation} equation + * @return {ContactEquationPool} + */ +ContactEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){ +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = FrictionEquationPool; + +/** + * @class + */ +function FrictionEquationPool() { + Pool.apply(this, arguments); +} +FrictionEquationPool.prototype = new Pool(); +FrictionEquationPool.prototype.constructor = FrictionEquationPool; + +/** + * @method create + * @return {FrictionEquation} + */ +FrictionEquationPool.prototype.create = function () { + return new FrictionEquation(); +}; + +/** + * @method destroy + * @param {FrictionEquation} equation + * @return {FrictionEquationPool} + */ +FrictionEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){ +var IslandNode = _dereq_('../world/IslandNode'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandNodePool; + +/** + * @class + */ +function IslandNodePool() { + Pool.apply(this, arguments); +} +IslandNodePool.prototype = new Pool(); +IslandNodePool.prototype.constructor = IslandNodePool; + +/** + * @method create + * @return {IslandNode} + */ +IslandNodePool.prototype.create = function () { + return new IslandNode(); +}; + +/** + * @method destroy + * @param {IslandNode} node + * @return {IslandNodePool} + */ +IslandNodePool.prototype.destroy = function (node) { + node.reset(); + return this; +}; + +},{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){ +var Island = _dereq_('../world/Island'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandPool; + +/** + * @class + */ +function IslandPool() { + Pool.apply(this, arguments); +} +IslandPool.prototype = new Pool(); +IslandPool.prototype.constructor = IslandPool; + +/** + * @method create + * @return {Island} + */ +IslandPool.prototype.create = function () { + return new Island(); +}; + +/** + * @method destroy + * @param {Island} island + * @return {IslandPool} + */ +IslandPool.prototype.destroy = function (island) { + island.reset(); + return this; +}; + +},{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){ +var TupleDictionary = _dereq_('./TupleDictionary'); +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool'); +var Utils = _dereq_('./Utils'); + +module.exports = OverlapKeeper; + +/** + * Keeps track of overlaps in the current state and the last step state. + * @class OverlapKeeper + * @constructor + */ +function OverlapKeeper() { + this.overlappingShapesLastState = new TupleDictionary(); + this.overlappingShapesCurrentState = new TupleDictionary(); + this.recordPool = new OverlapKeeperRecordPool({ size: 16 }); + this.tmpDict = new TupleDictionary(); + this.tmpArray1 = []; +} + +/** + * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current. + * @method tick + */ +OverlapKeeper.prototype.tick = function() { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Save old objects into pool + var l = last.keys.length; + while(l--){ + var key = last.keys[l]; + var lastObject = last.getByKey(key); + var currentObject = current.getByKey(key); + if(lastObject){ + // The record is only used in the "last" dict, and will be removed. We might as well pool it. + this.recordPool.release(lastObject); + } + } + + // Clear last object + last.reset(); + + // Transfer from new object to old + last.copy(current); + + // Clear current object + current.reset(); +}; + +/** + * @method setOverlapping + * @param {Body} bodyA + * @param {Body} shapeA + * @param {Body} bodyB + * @param {Body} shapeB + */ +OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Store current contact state + if(!current.get(shapeA.id, shapeB.id)){ + var data = this.recordPool.get(); + data.set(bodyA, shapeA, bodyB, shapeB); + current.set(shapeA.id, shapeB.id, data); + } +}; + +OverlapKeeper.prototype.getNewOverlaps = function(result){ + return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result); +}; + +OverlapKeeper.prototype.getEndOverlaps = function(result){ + return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result); +}; + +/** + * Checks if two bodies are currently overlapping. + * @method bodiesAreOverlapping + * @param {Body} bodyA + * @param {Body} bodyB + * @return {boolean} + */ +OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){ + var current = this.overlappingShapesCurrentState; + var l = current.keys.length; + while(l--){ + var key = current.keys[l]; + var data = current.data[key]; + if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){ + return true; + } + } + return false; +}; + +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){ + // Not overlapping in last state, but in current. + result.push(data); + } + } + + return result; +}; + +OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ + var idA = shapeA.id|0, + idB = shapeB.id|0; + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + // Not in last but in new + return !!!last.get(idA, idB) && !!current.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]; + + // Since we use body id's for the accumulator, these will be a subset of the original one + accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); + } + + l = accumulator.keys.length; + while(l--){ + var data = accumulator.getByKey(accumulator.keys[l]); + if(data){ + result.push(data.bodyA, data.bodyB); + } + } + + accumulator.reset(); + + return result; +}; + +},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){ +module.exports = OverlapKeeperRecord; + +/** + * Overlap data container for the OverlapKeeper + * @class OverlapKeeperRecord + * @constructor + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ + /** + * @property {Shape} shapeA + */ + this.shapeA = shapeA; + /** + * @property {Shape} shapeB + */ + this.shapeB = shapeB; + /** + * @property {Body} bodyA + */ + this.bodyA = bodyA; + /** + * @property {Body} bodyB + */ + this.bodyB = bodyB; +} + +/** + * Set the data for the record + * @method set + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ + OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); +}; + +},{}],54:[function(_dereq_,module,exports){ +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var Pool = _dereq_('./Pool'); + +module.exports = OverlapKeeperRecordPool; + +/** + * @class + */ +function OverlapKeeperRecordPool() { + Pool.apply(this, arguments); +} +OverlapKeeperRecordPool.prototype = new Pool(); +OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool; + +/** + * @method create + * @return {OverlapKeeperRecord} + */ +OverlapKeeperRecordPool.prototype.create = function () { + return new OverlapKeeperRecord(); +}; + +/** + * @method destroy + * @param {OverlapKeeperRecord} record + * @return {OverlapKeeperRecordPool} + */ +OverlapKeeperRecordPool.prototype.destroy = function (record) { + record.bodyA = record.bodyB = record.shapeA = record.shapeB = null; + return this; +}; + +},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){ +module.exports = Pool; + +/** + * @class Object pooling utility. + */ +function Pool(options) { + options = options || {}; + + /** + * @property {Array} objects + * @type {Array} + */ + this.objects = []; + + if(options.size !== undefined){ + this.resize(options.size); + } +} + +/** + * @method resize + * @param {number} size + * @return {Pool} Self, for chaining + */ +Pool.prototype.resize = function (size) { + var objects = this.objects; + + while (objects.length > size) { + objects.pop(); + } + + while (objects.length < size) { + objects.push(this.create()); + } + + return this; +}; + +/** + * Get an object from the pool or create a new instance. + * @method get + * @return {Object} + */ +Pool.prototype.get = function () { + var objects = this.objects; + return objects.length ? objects.pop() : this.create(); +}; + +/** + * Clean up and put the object back into the pool for later use. + * @method release + * @param {Object} object + * @return {Pool} Self for chaining + */ +Pool.prototype.release = function (object) { + this.destroy(object); + this.objects.push(object); + return this; +}; + +},{}],56:[function(_dereq_,module,exports){ +var Utils = _dereq_('./Utils'); + +module.exports = TupleDictionary; + +/** + * @class TupleDictionary + * @constructor + */ +function TupleDictionary() { + + /** + * The data storage + * @property data + * @type {Object} + */ + this.data = {}; + + /** + * Keys that are currently used. + * @property {Array} keys + */ + this.keys = []; +} + +/** + * Generate a key given two integers + * @method getKey + * @param {number} i + * @param {number} j + * @return {string} + */ +TupleDictionary.prototype.getKey = function(id1, id2) { + id1 = id1|0; + id2 = id2|0; + + if ( (id1|0) === (id2|0) ){ + return -1; + } + + // valid for values < 2^16 + return ((id1|0) > (id2|0) ? + (id1 << 16) | (id2 & 0xFFFF) : + (id2 << 16) | (id1 & 0xFFFF))|0 + ; +}; + +/** + * @method getByKey + * @param {Number} key + * @return {Object} + */ +TupleDictionary.prototype.getByKey = function(key) { + key = key|0; + return this.data[key]; +}; + +/** + * @method get + * @param {Number} i + * @param {Number} j + * @return {Number} + */ +TupleDictionary.prototype.get = function(i, j) { + return this.data[this.getKey(i, j)]; +}; + +/** + * Set a value. + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +TupleDictionary.prototype.set = function(i, j, value) { + if(!value){ + throw new Error("No data!"); + } + + var key = this.getKey(i, j); + + // Check if key already exists + if(!this.data[key]){ + this.keys.push(key); + } + + this.data[key] = value; + + return key; +}; + +/** + * Remove all data. + * @method reset + */ +TupleDictionary.prototype.reset = function() { + var data = this.data, + keys = this.keys; + + var l = keys.length; + while(l--) { + delete data[keys[l]]; + } + + keys.length = 0; +}; + +/** + * Copy another TupleDictionary. Note that all data in this dictionary will be removed. + * @method copy + * @param {TupleDictionary} dict The TupleDictionary to copy into this one. + */ +TupleDictionary.prototype.copy = function(dict) { + this.reset(); + Utils.appendArray(this.keys, dict.keys); + var l = dict.keys.length; + while(l--){ + var key = dict.keys[l]; + this.data[key] = dict.data[key]; + } +}; + +},{"./Utils":57}],57:[function(_dereq_,module,exports){ +/* global P2_ARRAY_TYPE */ + +module.exports = Utils; + +/** + * Misc utility functions + * @class Utils + * @constructor + */ +function Utils(){} + +/** + * Append the values in array b to the array a. See this for an explanation. + * @method appendArray + * @static + * @param {Array} a + * @param {Array} b + */ +Utils.appendArray = function(a,b){ + if (b.length < 150000) { + a.push.apply(a, b); + } else { + for (var i = 0, len = b.length; i !== len; ++i) { + a.push(b[i]); + } + } +}; + +/** + * Garbage free Array.splice(). Does not allocate a new array. + * @method splice + * @static + * @param {Array} array + * @param {Number} index + * @param {Number} howmany + */ +Utils.splice = function(array,index,howmany){ + howmany = howmany || 1; + for (var i=index, len=array.length-howmany; i < len; i++){ + array[i] = array[i + howmany]; + } + array.length = len; +}; + +/** + * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. + * @static + * @property {function} ARRAY_TYPE + * @example + * + * + */ +if(typeof P2_ARRAY_TYPE !== 'undefined') { + Utils.ARRAY_TYPE = P2_ARRAY_TYPE; +} else if (typeof Float32Array !== 'undefined'){ + Utils.ARRAY_TYPE = Float32Array; +} else { + Utils.ARRAY_TYPE = Array; +} + +/** + * Extend an object with the properties of another + * @static + * @method extend + * @param {object} a + * @param {object} b + */ +Utils.extend = function(a,b){ + for(var key in b){ + a[key] = b[key]; + } +}; + +/** + * Extend an options object with default values. + * @static + * @method defaults + * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. + * @param {object} defaults An object containing default values. + * @return {object} The modified options object. + */ +Utils.defaults = function(options, defaults){ + options = options || {}; + for(var key in defaults){ + if(!(key in options)){ + options[key] = defaults[key]; + } + } + return options; +}; + +},{}],58:[function(_dereq_,module,exports){ +var Body = _dereq_('../objects/Body'); + +module.exports = Island; + +/** + * An island of bodies connected with equations. + * @class Island + * @constructor + */ +function Island(){ + + /** + * Current equations in this island. + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Current bodies in this island. + * @property bodies + * @type {Array} + */ + this.bodies = []; +} + +/** + * Clean this island from bodies and equations. + * @method reset + */ +Island.prototype.reset = function(){ + this.equations.length = this.bodies.length = 0; +}; + +var bodyIds = []; + +/** + * Get all unique bodies in this island. + * @method getBodies + * @return {Array} An array of Body + */ +Island.prototype.getBodies = function(result){ + var bodies = result || [], + eqs = this.equations; + bodyIds.length = 0; + for(var i=0; i!==eqs.length; i++){ + var eq = eqs[i]; + if(bodyIds.indexOf(eq.bodyA.id)===-1){ + bodies.push(eq.bodyA); + bodyIds.push(eq.bodyA.id); + } + if(bodyIds.indexOf(eq.bodyB.id)===-1){ + bodies.push(eq.bodyB); + bodyIds.push(eq.bodyB.id); + } + } + return bodies; +}; + +/** + * Check if the entire island wants to sleep. + * @method wantsToSleep + * @return {Boolean} + */ +Island.prototype.wantsToSleep = function(){ + for(var i=0; i= dt && substeps < maxSubSteps) { + // Do fixed steps to catch up + this.internalStep(dt); + this.time += dt; + this.accumulator -= dt; + substeps++; + } + + var t = (this.accumulator % dt) / dt; + for(var j=0; j!==this.bodies.length; j++){ + var b = this.bodies[j]; + vec2.lerp(b.interpolatedPosition, b.previousPosition, b.position, t); + b.interpolatedAngle = b.previousAngle + t * (b.angle - b.previousAngle); + } + } +}; + +var endOverlaps = []; + +/** + * Make a fixed step. + * @method internalStep + * @param {number} dt + * @private + */ +World.prototype.internalStep = function(dt){ + this.stepping = true; + + var that = this, + Nsprings = this.springs.length, + springs = this.springs, + bodies = this.bodies, + g = this.gravity, + solver = this.solver, + Nbodies = this.bodies.length, + broadphase = this.broadphase, + np = this.narrowphase, + constraints = this.constraints, + t0, t1, + fhMinv = step_fhMinv, + velodt = step_velodt, + mg = step_mg, + scale = vec2.scale, + add = vec2.add, + rotate = vec2.rotate, + islandManager = this.islandManager; + + this.overlapKeeper.tick(); + + this.lastTimeStep = dt; + + // Update approximate friction gravity. + if(this.useWorldGravityAsFrictionGravity){ + var gravityLen = vec2.length(this.gravity); + if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){ + // Nonzero gravity. Use it. + this.frictionGravity = gravityLen; + } + } + + // Add gravity to bodies + if(this.applyGravity){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i], + fi = b.force; + if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ + continue; + } + vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g + add(fi,fi,mg); + } + } + + // Add spring forces + if(this.applySpringForces){ + for(var i=0; i!==Nsprings; i++){ + var s = springs[i]; + s.applyForce(); + } + } + + if(this.applyDamping){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + if(b.type === Body.DYNAMIC){ + b.applyDamping(dt); + } + } + } + + // Broadphase + var result = broadphase.getCollisionPairs(this); + + // Remove ignored collision pairs + var ignoredPairs = this.disabledBodyCollisionPairs; + for(var i=ignoredPairs.length-2; 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); + } + } + } + + // Remove constrained pairs with collideConnected == false + 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); + } + } + } + } + + // postBroadphase event + this.postBroadphaseEvent.pairs = result; + this.emit(this.postBroadphaseEvent); + this.postBroadphaseEvent.pairs = null; + + // Narrowphase + np.reset(this); + for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ + var bi = result[i], + bj = result[i+1]; + + // Loop over all shapes of body i + for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ + var si = bi.shapes[k], + xi = si.position, + ai = si.angle; + + // All shapes of body j + for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ + var sj = bj.shapes[l], + xj = sj.position, + aj = sj.angle; + + 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); + } + } + } + + // Wake up bodies + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + if(body._wakeUpAfterNarrowphase){ + body.wakeUp(); + body._wakeUpAfterNarrowphase = false; + } + } + + // Emit end overlap events + 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.bodyB; + this.emit(e); + } + endOverlaps.length = 0; + } + + var preSolveEvent = this.preSolveEvent; + preSolveEvent.contactEquations = np.contactEquations; + preSolveEvent.frictionEquations = np.frictionEquations; + this.emit(preSolveEvent); + preSolveEvent.contactEquations = preSolveEvent.frictionEquations = null; + + // update constraint equations + var Nconstraints = constraints.length; + for(i=0; i!==Nconstraints; i++){ + constraints[i].update(); + } + + if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){ + if(this.islandSplit){ + // Split into islands + 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 { + + // Add contact equations to solver + solver.addEquations(np.contactEquations); + solver.addEquations(np.frictionEquations); + + // Add user-defined constraint equations + for(i=0; i!==Nconstraints; i++){ + solver.addEquations(constraints[i].equations); + } + + if(this.solveConstraints){ + solver.solve(dt,this); + } + + solver.removeAllEquations(); + } + } + + // Step forward + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + + // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){ + body.integrate(dt); + // } + } + + // Reset force + for(var i=0; i!==Nbodies; i++){ + bodies[i].setZeroForce(); + } + + // Emit impact event + 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); + } + } + } + + // Sleeping update + if(this.sleepMode === World.BODY_SLEEPING){ + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, false, dt); + } + } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){ + + // Tell all bodies to sleep tick but dont sleep yet + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, true, dt); + } + + // Sleep islands + for(var i=0; i 0; + np.frictionCoefficient = cm.friction; + var reducedMass; + if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){ + reducedMass = bj.mass; + } else if(bj.type === Body.STATIC || bj.type === 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; + np.contactSkinSize = cm.contactSkinSize; + np.enabledEquations = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse; + + 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 < sj.type) { + numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); + } else { + numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); + } + var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; + + if(numContacts){ + + if( bi.allowSleep && + bi.type === Body.DYNAMIC && + bi.sleepState === Body.SLEEPING && + bj.sleepState === Body.AWAKE && + bj.type !== Body.STATIC + ){ + var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); + var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); + if(speedSquaredB >= speedLimitSquaredB*2){ + bi._wakeUpAfterNarrowphase = true; + } + } + + if( bj.allowSleep && + bj.type === Body.DYNAMIC && + bj.sleepState === Body.SLEEPING && + bi.sleepState === Body.AWAKE && + bi.type !== 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)){ + + // Report new shape overlap + var e = this.beginContactEvent; + e.shapeA = si; + e.shapeB = sj; + e.bodyA = bi; + e.bodyB = bj; + + // Reset contact equations + e.contactEquations.length = 0; + + if(typeof(numContacts)==="number"){ + for(var i=np.contactEquations.length-numContacts; i 1){ // Why divide by 1? + for(var i=np.frictionEquations.length-numFrictionEquations; i=0; i--){ + this.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.bodies; + for(var i=bodies.length-1; i>=0; i--){ + this.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.springs; + for(var i=springs.length-1; i>=0; i--){ + this.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.contactMaterials; + for(var i=cms.length-1; i>=0; i--){ + this.removeContactMaterial(cms[i]); + } + + World.apply(this); +}; + +var hitTest_tmp1 = vec2.create(), + hitTest_zero = vec2.fromValues(0,0), + hitTest_tmp2 = vec2.fromValues(0,0); + +/** + * Test if a world point overlaps bodies + * @method hitTest + * @param {Array} worldPoint Point to use for intersection tests + * @param {Array} bodies A list of objects to check for intersection + * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @return {Array} Array of bodies that overlap the point + * @todo Should use an api similar to the raycast function + * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient + * @todo Should use the broadphase + */ +World.prototype.hitTest = function(worldPoint,bodies,precision){ + precision = precision || 0; + + // Create a dummy particle body with a particle shape to test against the bodies + 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 = []; + + // Check bodies + 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]; + + // Get shape world position + angle + vec2.rotate(x, s.position, b.angle); + vec2.add(x, x, b.position); + var a = s.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)) < precision*precision) + ){ + result.push(b); + } + } + } + + return result; +}; + +/** + * Set the stiffness for all equations and contact materials. + * @method setGlobalStiffness + * @param {Number} stiffness + */ +World.prototype.setGlobalStiffness = function(stiffness){ + + // Set for all constraints + var constraints = this.constraints; + for(var i=0; i !== constraints.length; i++){ + var c = constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.stiffness = stiffness; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + var contactMaterials = this.contactMaterials; + for(var i=0; i !== contactMaterials.length; i++){ + var c = contactMaterials[i]; + c.stiffness = c.frictionStiffness = stiffness; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.stiffness = c.frictionStiffness = stiffness; +}; + +/** + * Set the relaxation for all equations and contact materials. + * @method setGlobalRelaxation + * @param {Number} relaxation + */ +World.prototype.setGlobalRelaxation = function(relaxation){ + + // Set for all constraints + for(var i=0; i !== this.constraints.length; i++){ + var c = this.constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.relaxation = relaxation; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + for(var i=0; i !== this.contactMaterials.length; i++){ + var c = this.contactMaterials[i]; + c.relaxation = c.frictionRelaxation = relaxation; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.relaxation = c.frictionRelaxation = relaxation; +}; + +var tmpAABB = new AABB(); +var tmpArray = []; + +/** + * Ray cast against all bodies in the world. + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @return {boolean} True if any body was hit. + * + * @example + * var ray = new Ray({ + * mode: Ray.CLOSEST, // or ANY + * from: [0, 0], + * to: [10, 0], + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * @example + * var ray = new Ray({ + * mode: Ray.ALL, + * from: [0, 0], + * to: [10, 0], + * callback: function(result){ + * + * // Print some info about the hit + * console.log('Hit body and shape: ', result.body, result.shape); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * // If you are happy with the hits you got this far, you can stop the traversal here: + * result.stop(); + * } + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + */ +World.prototype.raycast = function(result, ray){ + + // Get all bodies within the ray AABB + ray.getAABB(tmpAABB); + this.broadphase.aabbQuery(this, tmpAABB, tmpArray); + ray.intersectBodies(result, tmpArray); + tmpArray.length = 0; + + return result.hasHit(); +}; + +},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36]) +(36) +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +(function(){ + + var root = this; + +/** + * Namespace-class for [pixi.js](http://www.pixijs.com/). + * + * Contains assorted static properties and enumerations. + * + * @namespace PIXI + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ +var PIXI = PIXI || {}; + +/** +* @author Mat Groves http://matgroves.com @Doormat23 +* @author Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The base class for all objects that are rendered. Contains properties for position, scaling, +* rotation, masks and cache handling. +* +* This is an abstract class and should not be used on its own, rather it should be extended. +* +* It is used internally by the likes of PIXI.Sprite. +* +* @class PIXI.DisplayObject +* @constructor +*/ +PIXI.DisplayObject = function () { + + /** + * The coordinates, in pixels, of this DisplayObject, relative to its parent container. + * + * The value of this property does not reflect any positioning happening further up the display list. + * To obtain that value please see the `worldPosition` property. + * + * @property {PIXI.Point} position + * @default + */ + this.position = new PIXI.Point(0, 0); + + /** + * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject + * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on. + * + * The value of this property does not reflect any scaling happening further up the display list. + * To obtain that value please see the `worldScale` property. + * + * @property {PIXI.Point} scale + * @default + */ + this.scale = new PIXI.Point(1, 1); + + /** + * The pivot point of this DisplayObject that it rotates around. The values are expressed + * in pixel values. + * @property {PIXI.Point} pivot + * @default + */ + this.pivot = new PIXI.Point(0, 0); + + /** + * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on + * a right-handed orientation. + * + * The value of this property does not reflect any rotation happening further up the display list. + * To obtain that value please see the `worldRotation` property. + * + * @property {number} rotation + * @default + */ + this.rotation = 0; + + /** + * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * Please note that an object with an alpha value of 0 is skipped during the render pass. + * + * The value of this property does not reflect any alpha values set further up the display list. + * To obtain that value please see the `worldAlpha` property. + * + * @property {number} alpha + * @default + */ + this.alpha = 1; + + /** + * The visibility of this DisplayObject. A value of `false` makes the object invisible. + * A value of `true` makes it visible. Please note that an object with a visible value of + * `false` is skipped during the render pass. Equally a DisplayObject with visible false will + * not render any of its children. + * + * The value of this property does not reflect any visible values set further up the display list. + * To obtain that value please see the `worldVisible` property. + * + * @property {boolean} visible + * @default + */ + this.visible = true; + + /** + * This is the defined area that will pick up mouse / touch events. It is null by default. + * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children) + * + * @property hitArea + * @type Rectangle|Circle|Ellipse|Polygon + */ + this.hitArea = null; + + /** + * Should this DisplayObject be rendered by the renderer? An object with a renderable value of + * `false` is skipped during the render pass. + * + * @property {boolean} renderable + * @default + */ + this.renderable = false; + + /** + * The parent DisplayObjectContainer that this DisplayObject is a child of. + * All DisplayObjects must belong to a parent in order to be rendered. + * The root parent is the Stage object. This property is set automatically when the + * DisplayObject is added to, or removed from, a DisplayObjectContainer. + * + * @property {PIXI.DisplayObjectContainer} parent + * @default + * @readOnly + */ + this.parent = null; + + /** + * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects + * in the display list. + * + * To obtain, and set, the local alpha value, see the `alpha` property. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldAlpha + * @readOnly + */ + this.worldAlpha = 1; + + /** + * The current transform of this DisplayObject. + * + * This property contains the calculated total, based on the transforms of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {Phaser.Matrix} worldTransform + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * The coordinates, in pixels, of this DisplayObject within the world. + * + * This property contains the calculated total, based on the positions of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldPosition + * @readOnly + */ + this.worldPosition = new PIXI.Point(0, 0); + + /** + * The global scale of this DisplayObject. + * + * This property contains the calculated total, based on the scales of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldScale + * @readOnly + */ + this.worldScale = new PIXI.Point(1, 1); + + /** + * The rotation, in radians, of this DisplayObject. + * + * This property contains the calculated total, based on the rotations of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldRotation + * @readOnly + */ + this.worldRotation = 0; + + /** + * The rectangular area used by filters when rendering a shader for this DisplayObject. + * + * @property {PIXI.Rectangle} filterArea + * @type Rectangle + * @default + */ + this.filterArea = null; + + /** + * @property {number} _sr - Cached rotation value. + * @private + */ + this._sr = 0; + + /** + * @property {number} _cr - Cached rotation value. + * @private + */ + this._cr = 1; + + /** + * @property {PIXI.Rectangle} _bounds - The cached bounds of this object. + * @private + */ + this._bounds = new PIXI.Rectangle(0, 0, 0, 0); + + /** + * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object. + * @private + */ + this._currentBounds = null; + + /** + * @property {PIXI.Rectangle} _mask - The cached mask of this object. + * @private + */ + this._mask = null; + + /** + * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag. + * @private + */ + this._cacheAsBitmap = false; + + /** + * @property {boolean} _cacheIsDirty - Internal dirty cache flag. + * @private + */ + this._cacheIsDirty = false; + +}; + +PIXI.DisplayObject.prototype = { + + constructor: PIXI.DisplayObject, + + /** + * Destroy this DisplayObject. + * + * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask. + * + * Also iteratively calls `destroy` on any children. + * + * @method PIXI.DisplayObject#destroy + */ + destroy: function () { + + if (this.children) + { + var i = this.children.length; + + while (i--) + { + this.children[i].destroy(); + } + + this.children = []; + } + + this.hitArea = null; + this.parent = null; + this.worldTransform = null; + this.filterArea = null; + this.renderable = false; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + }, + + /** + * Updates the transform matrix this DisplayObject uses for rendering. + * + * If the object has no parent, and no parent parameter is provided, it will default to + * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place. + * + * The `parent` parameter has priority over the actual parent. Use it as a parent override. + * Setting it does **not** change the actual parent of this DisplayObject. + * + * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale` + * and `worldRotation` properties. + * + * If a `transformCallback` has been specified, it is called at the end of this method, and is passed + * the new, updated, worldTransform property, along with the parent transform used. + * + * @method PIXI.DisplayObject#updateTransform + * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from. + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateTransform: function (parent) { + + if (!parent && !this.parent && !this.game) + { + return this; + } + + var p = this.parent; + + if (parent) + { + p = parent; + } + else if (!this.parent) + { + p = this.game.world; + } + + // create some matrix refs for easy access + var pt = p.worldTransform; + var wt = this.worldTransform; + + // temporary matrix variables + var a, b, c, d, tx, ty; + + // so if rotation is between 0 then we can simplify the multiplication process.. + if (this.rotation % Phaser.Math.PI2) + { + // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes + if (this.rotation !== this.rotationCache) + { + this.rotationCache = this.rotation; + this._sr = Math.sin(this.rotation); + this._cr = Math.cos(this.rotation); + } + + // get the matrix values of the displayobject based on its transform properties.. + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + tx = this.position.x; + ty = this.position.y; + + // check for pivot.. not often used so geared towards that fact! + if (this.pivot.x || this.pivot.y) + { + tx -= this.pivot.x * a + this.pivot.y * c; + ty -= this.pivot.x * b + this.pivot.y * d; + } + + // concat the parent matrix with the objects transform. + wt.a = a * pt.a + b * pt.c; + wt.b = a * pt.b + b * pt.d; + wt.c = c * pt.a + d * pt.c; + wt.d = c * pt.b + d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + else + { + // lets do the fast version as we know there is no rotation.. + a = this.scale.x; + b = 0; + c = 0; + d = this.scale.y; + tx = this.position.x - this.pivot.x * a; + ty = this.position.y - this.pivot.y * d; + + wt.a = a * pt.a; + wt.b = a * pt.b; + wt.c = d * pt.c; + wt.d = d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + + a = wt.a; + b = wt.b; + c = wt.c; + d = wt.d; + + var determ = (a * d) - (b * c); + + if (a || b) + { + var r = Math.sqrt((a * a) + (b * b)); + + this.worldRotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); + this.worldScale.x = r; + this.worldScale.y = determ / r; + } + else if (c || d) + { + var s = Math.sqrt((c * c) + (d * d)); + + this.worldRotation = Phaser.Math.HALF_PI - ((d > 0) ? Math.acos(-c / s) : -Math.acos(c / s)); + this.worldScale.x = determ / s; + this.worldScale.y = s; + } + else + { + this.worldScale.x = 0; + this.worldScale.y = 0; + } + + // Set the World values + this.worldAlpha = this.alpha * p.worldAlpha; + this.worldPosition.x = wt.tx; + this.worldPosition.y = wt.ty; + + // reset the bounds each time this is called! + this._currentBounds = null; + + // Custom callback? + if (this.transformCallback) + { + this.transformCallback.call(this.transformCallbackContext, wt, pt); + } + + return this; + + }, + + /** + * To be overridden by classes that require it. + * + * @method PIXI.DisplayObject#preUpdate + */ + preUpdate: function () { + + }, + + /** + * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites. + * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times. + * + * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures, + * and references to them, so they don't linger in memory. + * + * @method PIXI.DisplayObject#generateTexture + * @param {number} [resolution=1] - The resolution of the texture being generated. + * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values. + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture. + * @return {Phaser.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked. + */ + generateTexture: function (resolution, scaleMode, renderer) { + + var bounds = this.getLocalBounds(); + + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + + renderTexture.render(this, PIXI.DisplayObject._tempMatrix); + + return renderTexture; + + }, + + /** + * If this DisplayObject has a cached Sprite, this method generates and updates it. + * + * @method PIXI.DisplayObject#updateCache + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateCache: function () { + + this._generateCachedSprite(); + + return this; + + }, + + /** + * Calculates the global position of this DisplayObject, based on the position given. + * + * @method PIXI.DisplayObject#toGlobal + * @param {PIXI.Point} position - The global position to calculate from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toGlobal: function (position) { + + this.updateTransform(); + + return this.worldTransform.apply(position); + + }, + + /** + * Calculates the local position of this DisplayObject, relative to another point. + * + * @method PIXI.DisplayObject#toLocal + * @param {PIXI.Point} position - The world origin to calculate from. + * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toLocal: function (position, from) { + + if (from) + { + position = from.toGlobal(position); + } + + this.updateTransform(); + + return this.worldTransform.applyInverse(position); + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_renderCachedSprite + * @private + * @param {Object} renderSession - The render session + */ + _renderCachedSprite: function (renderSession) { + + this._cachedSprite.worldAlpha = this.worldAlpha; + + if (renderSession.gl) + { + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + } + else + { + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + } + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_generateCachedSprite + * @private + */ + _generateCachedSprite: function () { + + this._cacheAsBitmap = false; + + var bounds = this.getLocalBounds(); + + // Round it off and force non-zero dimensions + bounds.width = Math.max(1, Math.ceil(bounds.width)); + bounds.height = Math.max(1, Math.ceil(bounds.height)); + + this.updateTransform(); + + if (!this._cachedSprite) + { + var textureUnit = 0; + if (this.texture && this.texture.baseTexture && PIXI._enableMultiTextureToggle) + { + textureUnit = this.texture.baseTexture.textureIndex; + } + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width, bounds.height, undefined, undefined, undefined, undefined, textureUnit); + this._cachedSprite = new PIXI.Sprite(renderTexture); + this._cachedSprite.worldTransform = this.worldTransform; + } + else + { + this._cachedSprite.texture.resize(bounds.width, bounds.height); + } + + // Remove filters + var tempFilters = this._filters; + + this._filters = null; + this._cachedSprite.filters = tempFilters; + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true); + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + this._filters = tempFilters; + + this._cacheAsBitmap = true; + + }, + + /** + * Destroys a cached Sprite. + * + * @method PIXI.DisplayObject#_destroyCachedSprite + * @private + */ + _destroyCachedSprite: function () { + + if (!this._cachedSprite) + { + return; + } + + this._cachedSprite.texture.destroy(true); + + this._cachedSprite = null; + + } + +}; + +// Alias for updateTransform. As used in DisplayObject container, etc. +PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform; + +Object.defineProperties(PIXI.DisplayObject.prototype, { + + /** + * The horizontal position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#x + * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent. + */ + 'x': { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + } + + }, + + /** + * The vertical position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#y + * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent. + */ + 'y': { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + + }, + + /** + * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + * @name PIXI.DisplayObject#worldVisible + * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + */ + 'worldVisible': { + + get: function () { + + if (!this.visible) + { + return false; + } + else + { + var item = this.parent; + + if (!item) + { + return this.visible; + } + else + { + do + { + if (!item.visible) + { + return false; + } + + item = item.parent; + } + while (item); + + } + + return true; + } + + } + + }, + + /** + * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object. + * When applied it limits the visible area of this DisplayObject to the shape of the mask. + * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer. + * To remove a mask, set this property to `null`. + * + * @name PIXI.DisplayObject#mask + * @property {Phaser.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask. + */ + 'mask': { + + get: function () { + + return this._mask; + + }, + + set: function (value) { + + if (this._mask) + { + this._mask.isMask = false; + } + + this._mask = value; + + if (value) + { + this._mask.isMask = true; + } + + } + + }, + + /** + * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas + * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter + * using `DisplayObject.filterArea`. + * + * To remove filters, set this property to `null`. + * + * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a + * filter will reset this DisplayObjects blend mode to NORMAL. + * + * @name PIXI.DisplayObject#filters + * @property {Array} filters - An Array of Phaser.Filter objects, or objects that extend them. + */ + 'filters': { + + get: function () { + + return this._filters; + + }, + + set: function (value) { + + if (Array.isArray(value)) + { + // Put all the passes in one place. + var passes = []; + + for (var i = 0; i < value.length; i++) + { + var filterPasses = value[i].passes; + + for (var j = 0; j < filterPasses.length; j++) + { + passes.push(filterPasses[j]); + } + } + + // Needed any more? + this._filterBlock = { target: this, filterPasses: passes }; + } + + this._filters = value; + + if (this.blendMode && this.blendMode === PIXI.blendModes.MULTIPLY) + { + this.blendMode = PIXI.blendModes.NORMAL; + } + + } + + }, + + /** + * Sets if this DisplayObject should be cached as a bitmap. + * + * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it + * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a + * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not + * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`. + * + * To remove a cached bitmap, set this property to `null`. + * + * @name PIXI.DisplayObject#cacheAsBitmap + * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap. + */ + 'cacheAsBitmap': { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + if (this._cacheAsBitmap === value) + { + return; + } + + if (value) + { + this._generateCachedSprite(); + } + else + { + this._destroyCachedSprite(); + } + + this._cacheAsBitmap = value; + + } + + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A DisplayObjectContainer represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + * @class PIXI.DisplayObjectContainer + * @extends PIXI.DisplayObject + * @constructor + */ +PIXI.DisplayObjectContainer = function () { + + PIXI.DisplayObject.call(this); + + /** + * [read-only] The array of children of this container. + * + * @property children + * @type Array(DisplayObject) + * @readOnly + */ + this.children = []; + + /** + * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events. + * + * If this property is `true` then the children will _not_ be considered as valid for Input events. + * + * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. + * @property {boolean} ignoreChildInput + * @default + */ + this.ignoreChildInput = false; + +}; + +PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); +PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; + +/** + * Adds a child to the container. + * + * @method PIXI.DisplayObjectContainer#addChild + * @param child {DisplayObject} The DisplayObject to add to the container + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChild = function (child) { + + return this.addChildAt(child, this.children.length); + +}; + +/** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @method PIXI.DisplayObjectContainer#addChildAt + * @param child {DisplayObject} The child to add + * @param index {Number} The index to place the child in + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) { + + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + return child; + } + else + { + throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); + } + +}; + +/** + * Swaps the position of 2 Display Objects within this container. + * + * @method PIXI.DisplayObjectContainer#swapChildren + * @param child {DisplayObject} + * @param child2 {DisplayObject} + */ +PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) { + + if (child === child2) + { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(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; + +}; + +/** + * Returns the index position of a child DisplayObject instance + * + * @method PIXI.DisplayObjectContainer#getChildIndex + * @param child {DisplayObject} The DisplayObject instance to identify + * @return {Number} The index position of the child display object to identify + */ +PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + +}; + +/** + * Changes the position of an existing child in the display object container + * + * @method PIXI.DisplayObjectContainer#setChildIndex + * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number + * @param index {Number} The resulting index number for the child display object + */ +PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + this.children.splice(currentIndex, 1); //remove from old position + this.children.splice(index, 0, child); //add at new position + +}; + +/** + * Returns the child at the specified index + * + * @method PIXI.DisplayObjectContainer#getChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child at the given index, if any. + */ +PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller'); + } + + return this.children[index]; + +}; + +/** + * Removes a child from the container. + * + * @method PIXI.DisplayObjectContainer#removeChild + * @param child {DisplayObject} The DisplayObject to remove + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChild = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + return; + } + + return this.removeChildAt(index); + +}; + +/** + * Removes a child from the specified index position. + * + * @method PIXI.DisplayObjectContainer#removeChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) { + + var child = this.getChildAt(index); + + if (child) + { + child.parent = undefined; + + this.children.splice(index, 1); + } + + return child; + +}; + +/** +* Removes all children from this container that are within the begin and end indexes. +* +* @method PIXI.DisplayObjectContainer#removeChildren +* @param beginIndex {Number} The beginning position. Default value is 0. +* @param endIndex {Number} The ending position. Default value is size of the container. +*/ +PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { + + if (beginIndex === undefined) { beginIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var range = endIndex - beginIndex; + + if (range > 0 && range <= endIndex) + { + var removed = this.children.splice(beginIndex, range); + + for (var i = 0; i < removed.length; i++) + { + var child = removed[i]; + child.parent = undefined; + } + + return removed; + } + else if (range === 0 && this.children.length === 0) + { + return []; + } + else + { + throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' ); + } + +}; + +/* + * Updates the transform on all children of this container for rendering + * + * @method PIXI.DisplayObjectContainer#updateTransform + * @private + */ +PIXI.DisplayObjectContainer.prototype.updateTransform = function () { + + if (!this.visible) + { + return; + } + + this.displayObjectUpdateTransform(); + + if (this._cacheAsBitmap) + { + return; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +// performance increase to avoid using call.. (10x faster) +PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform; + +/** + * Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getBounds + * @param {PIXI.DisplayObject|Phaser.Matrix} [targetCoordinateSpace] Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpace) { + + var isTargetCoordinateSpaceDisplayObject = (targetCoordinateSpace && targetCoordinateSpace instanceof PIXI.DisplayObject); + var isTargetCoordinateSpaceThisOrParent = true; + + if (!isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace = this; + } + else if (targetCoordinateSpace instanceof PIXI.DisplayObjectContainer) + { + isTargetCoordinateSpaceThisOrParent = targetCoordinateSpace.contains(this); + } + else + { + isTargetCoordinateSpaceThisOrParent = false; + } + + var i; + + if (isTargetCoordinateSpaceDisplayObject) + { + var matrixCache = targetCoordinateSpace.worldTransform; + + targetCoordinateSpace.worldTransform = Phaser.identityMatrix; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + var minX = Infinity; + var minY = Infinity; + + var maxX = -Infinity; + var maxY = -Infinity; + + var childBounds; + var childMaxX; + var childMaxY; + + var childVisible = false; + + for (i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + childVisible = true; + + childBounds = this.children[i].getBounds(); + + minX = (minX < childBounds.x) ? minX : childBounds.x; + minY = (minY < childBounds.y) ? minY : childBounds.y; + + childMaxX = childBounds.width + childBounds.x; + childMaxY = childBounds.height + childBounds.y; + + maxX = (maxX > childMaxX) ? maxX : childMaxX; + maxY = (maxY > childMaxY) ? maxY : childMaxY; + } + + var bounds = this._bounds; + + if (!childVisible) + { + bounds = new PIXI.Rectangle(); + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + maxX = x1; + maxY = y1; + + minX = x1; + minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + } + + bounds.x = minX; + bounds.y = minY; + bounds.width = maxX - minX; + bounds.height = maxY - minY; + + if (isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace.worldTransform = matrixCache; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + if (!isTargetCoordinateSpaceThisOrParent) + { + var targetCoordinateSpaceBounds = targetCoordinateSpace.getBounds(); + + bounds.x -= targetCoordinateSpaceBounds.x; + bounds.y -= targetCoordinateSpaceBounds.y; + } + + return bounds; + +}; + +/** + * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getLocalBounds = function () { + + return this.getBounds(this); + +}; + +/** +* Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. +* +* @method PIXI.DisplayObjectContainer#contains +* @param {DisplayObject} child +* @returns {boolean} +*/ +PIXI.DisplayObjectContainer.prototype.contains = function (child) { + + if (!child) + { + return false; + } + else if (child === this) + { + return true; + } + else + { + return this.contains(child.parent); + } +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.DisplayObjectContainer#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + var i; + + if (this._mask || this._filters) + { + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + renderSession.spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + renderSession.spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + renderSession.spriteBatch.start(); + } + + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + renderSession.spriteBatch.start(); + } + else + { + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.DisplayObjectContainer#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) { + + if (this.visible === false || this.alpha === 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', { + + get: function() { + return this.getLocalBounds().width * this.scale.x; + }, + + set: function(value) { + + var width = this.getLocalBounds().width; + + if (width !== 0) + { + this.scale.x = value / width; + } + else + { + this.scale.x = 1; + } + + this._width = value; + } +}); + +/** + * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', { + + get: function() { + return this.getLocalBounds().height * this.scale.y; + }, + + set: function(value) { + + var height = this.getLocalBounds().height; + + if (height !== 0) + { + this.scale.y = value / height; + } + else + { + this.scale.y = 1; + } + + this._height = value; + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * @class PIXI.Sprite + * @extends PIXI.DisplayObjectContainer + * @constructor + * @param texture {Texture} The texture for this sprite + */ +PIXI.Sprite = function (texture) { + + PIXI.DisplayObjectContainer.call(this); + + /** + * The anchor sets the origin point of the texture. + * The default (0, 0) is the top left. + * (0.5, 0.5) is the center. + * (1, 1) is the bottom right. + * + * You can modify the default values in PIXI.Sprite.defaultAnchor. + * + * @property anchor + * @type Point + */ + this.anchor = new PIXI.Point(PIXI.Sprite.defaultAnchor.x, PIXI.Sprite.defaultAnchor.y); + + /** + * The texture that the sprite is using + * + * @property texture + * @type Texture + */ + this.texture = texture || PIXI.Texture.emptyTexture; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @property _width + * @type Number + * @private + */ + this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @property _height + * @type Number + * @private + */ + this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF (Phaser.Color.WHITE) will remove any tint effect. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @property cachedTint + * @private + * @type Number + * @default -1 + */ + this.cachedTint = -1; + + /** + * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) + * + * @property tintedTexture + * @type Canvas + * @default null + */ + this.tintedTexture = null; + + /** + * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. + * + * Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * The shader that will be used to render this Sprite. + * Set to null to remove a current shader. + * + * @property shader + * @type Phaser.Filter + * @default null + */ + this.shader = null; + + /** + * Controls if this Sprite is processed by the core Phaser game loops and Group loops (except {@link Phaser.Group#update}). + * + * @property exists + * @type Boolean + * @default true + */ + this.exists = true; + + if (this.texture.baseTexture.hasLoaded) + { + this.onTextureUpdate(); + } + + this.renderable = true; + +}; + +/** + * @property PIXI.Sprite.defaultAnchor - A Point-like object. + * @type {{x: number, y: number}} + * @default + */ +PIXI.Sprite.defaultAnchor = {x: 0, y: 0}; + +// constructor +PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +PIXI.Sprite.prototype.constructor = PIXI.Sprite; + +/** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'width', { + + get: function() { + return this.scale.x * this.texture.frame.width; + }, + + set: function(value) { + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'height', { + + get: function() { + return this.scale.y * this.texture.frame.height; + }, + + set: function(value) { + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +/** + * Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous + * texture this Sprite was using. + * + * @method PIXI.Sprite#setTexture + * @param texture {Texture} The PIXI texture that is displayed by the sprite + * @param [destroy=false] {boolean} Call Texture.destroy on the current texture before replacing it with the new one? + */ +PIXI.Sprite.prototype.setTexture = function(texture, destroyBase) +{ + if (destroyBase) + { + this.texture.baseTexture.destroy(); + } + + // Over-ridden by loadTexture as needed + this.texture.baseTexture.skipRender = false; + this.texture = texture; + this.texture.valid = true; + this.cachedTint = -1; +}; + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @method PIXI.Sprite#onTextureUpdate + * @param event + * @private + */ +PIXI.Sprite.prototype.onTextureUpdate = function() +{ + // so if _width is 0 then width was not set.. + if (this._width) this.scale.x = this._width / this.texture.frame.width; + if (this._height) this.scale.y = this._height / this.texture.frame.height; +}; + +/** +* Returns the bounds of the Sprite as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* It is important to note that the transform is not updated when you call this method. +* So if this Sprite is the child of a Display Object which has had its transform +* updated since the last render pass, those changes will not yet have been applied +* to this Sprites worldTransform. If you need to ensure that all parent transforms +* are factored into this getBounds operation then you should call `updateTransform` +* on the root most object in this Sprites display list first. +* +* @method PIXI.Sprite#getBounds +* @param matrix {Matrix} the transformation matrix of the sprite +* @return {Rectangle} the framing rectangle +*/ +PIXI.Sprite.prototype.getBounds = function(matrix) +{ + var width = this.texture.frame.width; + var height = this.texture.frame.height; + + var w0 = width * (1-this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1-this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + if (b === 0 && c === 0) + { + // scale may be negative! + if (a < 0) + { + a *= -1; + var temp = w0; + w0 = -w1; + w1 = -temp; + } + + if (d < 0) + { + d *= -1; + var temp = h0; + h0 = -h1; + h1 = -temp; + } + + // this means there is no rotation going on right? RIGHT? + // if thats the case then we can avoid checking the bound values! yay + minX = a * w1 + tx; + maxX = a * w0 + tx; + minY = d * h1 + ty; + maxY = d * h0 + ty; + } + else + { + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; +}; + +/** + * Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. + * + * @method PIXI.Sprite#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.Sprite.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.Sprite#_renderWebGL +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix) +{ + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha <= 0 || !this.renderable) return; + + // They provided an alternative rendering matrix, so use it + var wt = this.worldTransform; + + if (matrix) + { + wt = matrix; + } + + // A quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) + { + var spriteBatch = renderSession.spriteBatch; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + spriteBatch.start(); + } + + // add this sprite to the batch + spriteBatch.render(this); + + // now loop through the children and make sure they get rendered + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + // time to stop the sprite batch as either a mask element or a filter draw will happen next + spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + spriteBatch.start(); + } + else + { + renderSession.spriteBatch.render(this); + + // Render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession, wt); + } + + } +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.Sprite#_renderCanvas +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix) +{ + // If the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha === 0 || !this.renderable || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { + return; + } + + var wt = this.worldTransform; + + // If they provided an alternative rendering matrix then use it + if (matrix) + { + wt = matrix; + } + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + // Ignore null sources + if (!this.texture.valid) + { + // Update the children and leave + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + return; + } + + var resolution = this.texture.baseTexture.resolution / renderSession.resolution; + + renderSession.context.globalAlpha = this.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for this texture + if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode) + { + renderSession.scaleMode = this.texture.baseTexture.scaleMode; + renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + + // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions + var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width; + var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height; + + var tx = (wt.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (wt.ty * renderSession.resolution) + renderSession.shakeY; + + var cw = this.texture.crop.width; + var ch = this.texture.crop.height; + + if (this.texture.rotated) + { + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var e = cw; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + wt.a = a * 6.123233995736766e-17 + -c; + wt.b = b * 6.123233995736766e-17 + -d; + wt.c = a + c * 6.123233995736766e-17; + wt.d = b + d * 6.123233995736766e-17; + + // Update cropping dimensions. + cw = ch; + ch = e; + } + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx | 0, ty | 0); + dx |= 0; + dy |= 0; + } + else + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + } + + dx /= resolution; + dy /= resolution; + + if (this.tint !== 0xFFFFFF) + { + if (this.texture.requiresReTint || this.cachedTint !== this.tint) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + } + + renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + else + { + var cx = this.texture.crop.x; + var cy = this.texture.crop.y; + + cw = Math.floor(cw) + ch = Math.floor(ch) + + renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @method PIXI.initDefaultShaders +* @static +* @private +*/ +PIXI.initDefaultShaders = function() +{ +}; + +/** +* @method PIXI.CompileVertexShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileVertexShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); +}; + +/** +* @method PIXI.CompileFragmentShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileFragmentShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); +}; + +/** +* @method PIXI._CompileShader +* @static +* @private +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @param shaderType {Number} +* @return {Any} +*/ +PIXI._CompileShader = function(gl, shaderSrc, shaderType) +{ + var src = shaderSrc; + + if (Array.isArray(shaderSrc)) + { + 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; +}; + +/** +* @method PIXI.compileProgram +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param vertexSrc {Array} +* @param fragmentSrc {Array} +* @return {Any} +*/ +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(gl.getProgramInfoLog(shaderProgram)); + window.console.log("Could not initialise shaders"); + } + + return shaderProgram; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + * @author Richard Davey http://www.photonstorm.com @photonstorm + */ + +/** +* @class PIXI.PixiShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PixiShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = null; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + /** + * A local flag + * @property firstRun + * @type Boolean + * @private + */ + this.firstRun = true; + + /** + * A dirty flag + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Uniform attributes cache. + * @property attributes + * @type Array + * @private + */ + this.attributes = []; + + this.init(); +}; + +PIXI.PixiShader.prototype.constructor = PIXI.PixiShader; + +PIXI.PixiShader.prototype.initMultitexShader = function () { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.fragmentSrc = [ + '// PixiShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}', + '}' + ]; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + //this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.uSamplerArray = gl.getUniformLocation(program, 'uSamplerArray[0]'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSamplerArray, indices); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; + +PIXI.PixiShader.prototype.initDefaultShader = function () { + + if (this.fragmentSrc === null) { + this.fragmentSrc = [ + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', + '}' + ]; + } + + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; +/** +* Initialises the shader. +* +* @method PIXI.PixiShader#init +*/ +PIXI.PixiShader.prototype.init = function(usingFilter) +{ + if (PIXI._enableMultiTextureToggle && !usingFilter) { + this.initMultitexShader(); + } else { + this.initDefaultShader(); + } +}; + +/** +* Initialises the shader uniform values. +* +* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ +* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf +* +* @method PIXI.PixiShader#initUniforms +*/ +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') + { + // These require special handling + 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 + { + // GL function reference + 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; + } + } + } + +}; + +/** +* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) +* +* @method PIXI.PixiShader#initSampler2D +*/ +PIXI.PixiShader.prototype.initSampler2D = function(uniform) +{ + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { + return; + } + + var gl = this.gl; + + // No need to do string manipulation for this. + gl.activeTexture(gl.TEXTURE0 + this.textureCount); + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + + // Extended texture data + if (uniform.textureData) + { + var data = uniform.textureData; + + // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); + // GLTextureLinear = mag/min linear, wrap clamp + // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat + // GLTextureNearest = mag/min nearest, wrap clamp + // AudioTexture = whatever + luminance + width 512, height 2, border 0 + // KeyTexture = whatever + luminance + width 256, height 2, border 0 + + // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + + 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; + + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels); + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); + } + else + { + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels); + 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++; + +}; + +/** +* Updates the shader uniform values. +* +* @method PIXI.PixiShader#syncUniforms +*/ +PIXI.PixiShader.prototype.syncUniforms = function() +{ + this.textureCount = 1; + var uniform; + var gl = this.gl; + + // This would probably be faster in an array and it would guarantee key order + 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]); + + if(uniform.value.baseTexture._dirty[gl.id]) + { + PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + } + + // 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); + } + } + } + +}; + +/** +* Destroys the shader. +* +* @method PIXI.PixiShader#destroy +*/ +PIXI.PixiShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** +* The Default Vertex shader source. +* +* @property defaultVertexSrc +* @type String +*/ +PIXI.PixiShader.defaultVertexSrc = [ + '// PixiShader Vertex Shader', + '// With multi-texture rendering', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute vec4 aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + + 'const vec2 center = vec2(-1.0, 1.0);', + + 'void main(void) {', + ' if (aTextureIndex > 0.0) gl_Position = vec4(0.0);', + ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', + ' vTextureCoord = aTextureCoord;', + ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', + ' vTextureIndex = aTextureIndex;', + '}' +]; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @class PIXI.PixiFastShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.PixiFastShader = function (gl) { + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '// PixiFastShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aPositionCoord;', + 'attribute vec2 aScale;', + 'attribute float aRotation;', + 'attribute vec2 aTextureCoord;', + 'attribute float aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform mat3 uMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + + '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;', + ' vTextureIndex = aTextureIndex;', + // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;', + ' vColor = aColor;', + '}' + ]; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + this.init(); +}; + +PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader; + +/** + * Initialises the shader. + * + * @method PIXI.PixiFastShader#init + */ +PIXI.PixiFastShader.prototype.init = function () { + + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + this.uMatrix = gl.getUniformLocation(program, 'uMatrix'); + + // get and store the attributes + 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'); + + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its somthing to do with the current state of the gl context. + // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if (this.colorAttribute === -1) { + this.colorAttribute = 2; + } + + this.attributes = [ + this.aVertexPosition, + this.aPositionCoord, + this.aScale, + this.aRotation, + this.aTextureCoord, + this.colorAttribute, + this.aTextureIndex + ]; + + // End worst hack eva // + + this.program = program; +}; + +/** + * Destroys the shader. + * + * @method PIXI.PixiFastShader#destroy + */ +PIXI.PixiFastShader.prototype.destroy = function () { + this.gl.deleteProgram(this.program); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.StripShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.StripShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord);return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) ;return;}\n' + } + + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord);', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '//StripShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute float aTextureIndex;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + // 'uniform float alpha;', + // 'uniform vec3 tint;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // '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);', + ' vTextureCoord = aTextureCoord;', + ' vTextureIndex = aTextureIndex;', + // ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.StripShader.prototype.constructor = PIXI.StripShader; + +/** +* Initialises the shader. +* +* @method PIXI.StripShader#init +*/ +PIXI.StripShader.prototype.init = function() +{ + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + //this.dimensions = gl.getUniformLocation(this.program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.aTextureIndex]; + + this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix'); + this.alpha = gl.getUniformLocation(program, 'alpha'); + + this.program = program; +}; + +/** +* Destroys the shader. +* +* @method PIXI.StripShader#destroy +*/ +PIXI.StripShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.PrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + 'precision mediump float;', + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform float alpha;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.PrimitiveShader#init +*/ +PIXI.PrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.PrimitiveShader#destroy +*/ +PIXI.PrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.ComplexPrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.ComplexPrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + + 'precision mediump float;', + + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + //'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 color;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.ComplexPrimitiveShader#init +*/ +PIXI.ComplexPrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.color = gl.getUniformLocation(program, 'color'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.ComplexPrimitiveShader#destroy +*/ +PIXI.ComplexPrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +PIXI.glContexts = []; // this is where we store the webGL contexts for easy access. +PIXI.instances = []; +PIXI._enableMultiTextureToggle = false; + +/** + * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class PIXI.WebGLRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.WebGLRenderer = function(game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + this.extensions = {}; + + /** + * @property type + * @type Number + */ + this.type = Phaser.WEBGL; + + /** + * The resolution of the renderer + * + * @property resolution + * @type Number + * @default 1 + */ + this.resolution = game.resolution; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * + * @property preserveDrawingBuffer + * @type Boolean + */ + this.preserveDrawingBuffer = game.preserveDrawingBuffer; + + /** + * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true: + * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0). + * If the Stage is transparent, Pixi will clear to the target Stage's background color. + * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * The width of the canvas view + * + * @property width + * @type Number + */ + this.width = game.width; + + /** + * The height of the canvas view + * + * @property height + * @type Number + */ + this.height = game.height; + + /** + * The canvas element that everything is drawn to + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * @property _contextOptions + * @type Object + * @private + */ + this._contextOptions = { + alpha: this.transparent, + antialias: game.antialias, + failIfMajorPerformanceCaveat: config.failIfMajorPerformanceCaveat, + premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: this.preserveDrawingBuffer + }; + + /** + * @property projection + * @type Point + */ + this.projection = new PIXI.Point(); + + /** + * @property offset + * @type Point + */ + this.offset = new PIXI.Point(); + + // time to create the render managers! each one focuses on managing a state in webGL + + /** + * Deals with managing the shader programs and their attribs + * @property shaderManager + * @type WebGLShaderManager + */ + this.shaderManager = new PIXI.WebGLShaderManager(); + + /** + * Manages the rendering of sprites + * @property spriteBatch + * @type WebGLSpriteBatch + */ + this.spriteBatch = new PIXI.WebGLSpriteBatch(game); + + /** + * Manages the masks using the stencil buffer + * @property maskManager + * @type WebGLMaskManager + */ + this.maskManager = new PIXI.WebGLMaskManager(); + + /** + * Manages the filters + * @property filterManager + * @type WebGLFilterManager + */ + this.filterManager = new PIXI.WebGLFilterManager(); + + /** + * Manages the stencil buffer + * @property stencilManager + * @type WebGLStencilManager + */ + this.stencilManager = new PIXI.WebGLStencilManager(); + + /** + * Manages the blendModes + * @property blendModeManager + * @type WebGLBlendModeManager + */ + this.blendModeManager = new PIXI.WebGLBlendModeManager(); + + /** + * @property renderSession + * @type Object + */ + this.renderSession = {}; + + /** + * @property currentBatchedTextures + * @type Array + */ + this.currentBatchedTextures = []; + + // Needed? + this.renderSession.game = this.game; + this.renderSession.gl = this.gl; + this.renderSession.drawCount = 0; + this.renderSession.shaderManager = this.shaderManager; + this.renderSession.maskManager = this.maskManager; + this.renderSession.filterManager = this.filterManager; + this.renderSession.blendModeManager = this.blendModeManager; + this.renderSession.spriteBatch = this.spriteBatch; + this.renderSession.stencilManager = this.stencilManager; + this.renderSession.renderer = this; + this.renderSession.resolution = this.resolution; + this.renderSession.roundPixels = config.roundPixels || false; + this.renderSession.maxTextureAvailableSpace = null; // filled in setTexturePriority() + + // time init the context.. + this.initContext(); + + // map some webGL blend modes.. + this.mapBlendModes(); + +}; + +// constructor +PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer; + +/** +* @method PIXI.WebGLRenderer#initContext +*/ +PIXI.WebGLRenderer.prototype.initContext = function() +{ + var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); + + this.gl = gl; + + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + this.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.maxTextureSize = this.gl.getParameter(gl.MAX_TEXTURE_SIZE); + + this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++; + + PIXI.glContexts[this.glContextId] = gl; + + PIXI.instances[this.glContextId] = this; + + // set up the default pixi settings.. + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + gl.enable(gl.BLEND); + + // need to set the context for all the managers... + this.shaderManager.setContext(gl); + this.spriteBatch.setContext(gl); + this.maskManager.setContext(gl); + this.filterManager.setContext(gl); + this.blendModeManager.setContext(gl); + this.stencilManager.setContext(gl); + + this.renderSession.gl = this.gl; + + // now resize and we are good to go! + this.resize(this.width, this.height); + + // Load WebGL extension + this.extensions.compression = {}; + + var etc1 = gl.getExtension('WEBGL_compressed_texture_etc1') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'); + var pvrtc = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); + var s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); + + if (etc1) { this.extensions.compression.ETC1 = etc1; } + if (pvrtc) { this.extensions.compression.PVRTC = pvrtc; } + if (s3tc) { this.extensions.compression.S3TC = s3tc; } +}; + +/** +* If Multi Texture support has been enabled, then calling this method will enable batching on the given +* textures. The texture collection is an array of keys, that map to Phaser.Cache image entries. +* +* The number of textures that can be batched is dependent on hardware. If you provide more textures +* than can be batched by the GPU, then only those at the start of the array will be used. Generally +* you shouldn't provide more than 16 textures to this method. You can check the hardware limit via the +* `maxTextures` property. +* +* You can also check the property `currentBatchedTextures` at any time, to see which textures are currently +* being batched. +* +* To stop all textures from being batched, call this method again with an empty array. +* +* To change the textures being batched, call this method with a new array of image keys. The old ones +* will all be purged out and no-longer batched, and the new ones enabled. +* +* Note: Throws a warning if you haven't enabled Multiple Texture batching support in the Phaser Game config. +* +* @method PIXI.WebGLRenderer#setTexturePriority +* @param textureNameCollection {Array} An Array of Texture Cache keys to use for multi-texture batching. +* @return {Array} An array containing the texture keys that were enabled for batching. +*/ +PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + if (!PIXI._enableMultiTextureToggle) + { + console.warn('setTexturePriority error: Multi Texture support hasn\'t been enabled in the Phaser Game Config.'); + return; + } + var clampPot = function (potSize) { + --potSize; + potSize |= potSize >> 1; + potSize |= potSize >> 2; + potSize |= potSize >> 4; + potSize |= potSize >> 8; + potSize |= potSize >> 16; + return ++potSize; + }; + var gl = this.gl; + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + var imageCache = this.game.cache._cache.image; + var imageName = null; + + // Clear out all previously batched textures and reset their flags. + // If the array has been modified, then the developer will have to + // deal with that in their own way. + for (var i = 0; i < this.currentBatchedTextures.length; i++) + { + imageName = this.currentBatchedTextures[i]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + + imageCache[imageName].base.textureIndex = 0; + } + var maxTextureAvailableSpace = (maxTextureSize) - clampPot(Math.max(this.width, this.height)); + this.currentBatchedTextures.length = 0; + // We start from 1 because framebuffer texture uses unit 0. + for (var j = 0; j < textureNameCollection.length; ++j) + { + imageName = textureNameCollection[j]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + // Unit 0 is reserved for Pixi's framebuffer + var base = imageCache[imageName].base; + maxTextureAvailableSpace -= clampPot(Math.max(base.width, base.height)); + if (maxTextureAvailableSpace <= 0) { + base.textureIndex = 0; + console.warn('setTexturePriority: Image "%s" was given textureIndex=0 because there is no available texture space (%s).', + imageName, maxTextureAvailableSpace); + } else { + base.textureIndex = (1 + (j % (maxTextures - 1))); + } + this.currentBatchedTextures.push(imageName); + } + + this.renderSession.maxTextureAvailableSpace = maxTextureAvailableSpace; + + return this.currentBatchedTextures; + +}; + +/** + * Renders the stage to its webGL view + * + * @method PIXI.WebGLRenderer#render + * @param stage {Stage} the Stage element to be rendered + */ +PIXI.WebGLRenderer.prototype.render = function(stage) +{ + // no point rendering if our context has been blown up! + if (this.contextLost) + { + return; + } + + var gl = this.gl; + + // -- Does this need to be set every frame? -- // + gl.viewport(0, 0, this.width, this.height); + + // make sure we are bound to the main frame buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + if (this.game.clearBeforeRender) + { + gl.clearColor(stage._bgColor.r, stage._bgColor.g, stage._bgColor.b, stage._bgColor.a); + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + this.offset.x = this.game.camera._shake.x; + this.offset.y = this.game.camera._shake.y; + + this.renderDisplayObject(stage, this.projection); +}; + +/** + * Renders a Display Object. + * + * @method PIXI.WebGLRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The DisplayObject to render + * @param projection {Point} The projection + * @param buffer {Array} a standard WebGL buffer + */ +PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix) +{ + this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL); + + // reset the render session data.. + this.renderSession.drawCount = 0; + + // make sure to flip the Y if using a render texture.. + this.renderSession.flipY = buffer ? -1 : 1; + + // set the default projection + this.renderSession.projection = projection; + + //set the default offset + this.renderSession.offset = this.offset; + + // start the sprite batch + this.spriteBatch.begin(this.renderSession); + + // start the filter manager + this.filterManager.begin(this.renderSession, buffer); + + // render the scene! + displayObject._renderWebGL(this.renderSession, matrix); + + // finish the sprite batch + this.spriteBatch.end(); +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @method PIXI.WebGLRenderer#resize + * @param width {Number} the new width of the webGL view + * @param height {Number} the new height of the webGL view + */ +PIXI.WebGLRenderer.prototype.resize = function(width, height) +{ + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } + + this.gl.viewport(0, 0, this.width, this.height); + + this.projection.x = this.width / 2 / this.resolution; + this.projection.y = -this.height / 2 / this.resolution; +}; + +/** + * Updates and creates a WebGL compressed texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateCompressedTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateCompressedTexture = function (texture) { + if (!texture.hasLoaded) + { + return false; + } + var gl = this.gl; + var textureMetaData = texture.source; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + textureMetaData.glExtensionFormat, + textureMetaData.width, + textureMetaData.height, + 0, + textureMetaData.textureData + ); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + texture._dirty[gl.id] = false; + return true; +}; + +/** + * Updates and Creates a WebGL texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateTexture = function(texture) +{ + if (!texture.hasLoaded) + { + return false; + } + if (texture.source.compressionAlgorithm) { + return this.updateCompressedTexture(texture); + } + + var gl = this.gl; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha); + + 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); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + + texture._dirty[gl.id] = false; + + // return texture._glTextures[gl.id]; + return true; + +}; + +/** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @method PIXI.WebGLRenderer#destroy + */ +PIXI.WebGLRenderer.prototype.destroy = function() +{ + 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; + + Phaser.CanvasPool.remove(this); + + PIXI.instances[this.glContextId] = null; + + PIXI.WebGLRenderer.glContextId--; +}; + +/** + * Maps Pixi blend modes to WebGL blend modes. + * + * @method PIXI.WebGLRenderer#mapBlendModes + */ +PIXI.WebGLRenderer.prototype.mapBlendModes = function() +{ + var gl = this.gl; + + if (!PIXI.blendModesWebGL) + { + var b = []; + var modes = PIXI.blendModes; + + b[modes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA]; + b[modes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SCREEN] = [gl.SRC_ALPHA, gl.ONE]; + b[modes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + PIXI.blendModesWebGL = b; + } +}; + +PIXI.WebGLRenderer.prototype.getMaxTextureUnit = function() { + var gl = this.gl; + return gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); +}; + +PIXI.enableMultiTexture = function() { + PIXI._enableMultiTextureToggle = true; +}; + +PIXI.WebGLRenderer.glContextId = 0; +PIXI.WebGLRenderer.textureArray = []; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLBlendModeManager +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLBlendModeManager = function() +{ + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 99999; +}; + +PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLBlendModeManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLBlendModeManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Sets-up the given blendMode from WebGL's point of view. +* +* @method PIXI.WebGLBlendModeManager#setBlendMode +* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD +*/ +PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode) +{ + if(this.currentBlendMode === blendMode)return false; + + this.currentBlendMode = blendMode; + + var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode]; + + if (blendModeWebGL) + { + this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLBlendModeManager#destroy +*/ +PIXI.WebGLBlendModeManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLMaskManager +* @constructor +* @private +*/ +PIXI.WebGLMaskManager = function() +{ +}; + +PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLMaskManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLMaskManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLMaskManager#pushMask +* @param maskData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession) +{ + var gl = renderSession.gl; + + if (maskData.dirty) + { + PIXI.WebGLGraphics.updateGraphics(maskData, gl); + } + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLMaskManager#popMask +* @param maskData {Array} +* @param renderSession {Object} an object containing all the useful parameters +*/ +PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession) +{ + var gl = this.gl; + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); + +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLMaskManager#destroy +*/ +PIXI.WebGLMaskManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLStencilManager +* @constructor +* @private +*/ +PIXI.WebGLStencilManager = function() +{ + this.stencilStack = []; + this.reverse = true; + this.count = 0; +}; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLStencilManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLStencilManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLStencilManager#pushMask +* @param graphics {Graphics} +* @param webGLData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.bindGraphics(graphics, webGLData, renderSession); + + if(this.stencilStack.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + this.reverse = true; + this.count = 0; + } + + this.stencilStack.push(webGLData); + + var level = this.count; + + gl.colorMask(false, false, false, false); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + + if(webGLData.mode === 1) + { + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + + this.reverse = !this.reverse; + } + else + { + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + this.count++; +}; + +/** + * TODO this does not belong here! + * + * @method PIXI.WebGLStencilManager#bindGraphics + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession) +{ + //if(this._currentGraphics === graphics)return; + this._currentGraphics = graphics; + + var gl = this.gl; + + // bind the graphics object.. + var projection = renderSession.projection, + offset = renderSession.offset, + shader;// = renderSession.shaderManager.primitiveShader; + + if(webGLData.mode === 1) + { + shader = renderSession.shaderManager.complexPrimitiveShader; + + renderSession.shaderManager.setShader( shader ); + + gl.uniform1f(shader.flipY, renderSession.flipY); + + 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, Phaser.Color.hexToRGBArray(graphics.tint)); + gl.uniform3fv(shader.color, webGLData.color); + + gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0); + + + // now do the rest.. + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } + else + { + //renderSession.shaderManager.activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + renderSession.shaderManager.setShader( shader ); + + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, renderSession.flipY); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } +}; + +/** + * @method PIXI.WebGLStencilManager#popStencil + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.stencilStack.pop(); + + this.count--; + + if(this.stencilStack.length === 0) + { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + + } + else + { + + var level = this.count; + + this.bindGraphics(graphics, webGLData, renderSession); + + gl.colorMask(false, false, false, false); + + if(webGLData.mode === 1) + { + this.reverse = !this.reverse; + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + + } + else + { + // console.log("<<>>") + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + + } +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLStencilManager#destroy +*/ +PIXI.WebGLStencilManager.prototype.destroy = function() +{ + this.stencilStack = null; + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLShaderManager +* @constructor +* @private +*/ +PIXI.WebGLShaderManager = function() +{ + /** + * @property maxAttibs + * @type Number + */ + this.maxAttibs = 10; + + /** + * @property attribState + * @type Array + */ + this.attribState = []; + + /** + * @property tempAttribState + * @type Array + */ + this.tempAttribState = []; + + for (var i = 0; i < this.maxAttibs; i++) + { + this.attribState[i] = false; + } + + /** + * @property stack + * @type Array + */ + this.stack = []; + +}; + +PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLShaderManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLShaderManager.prototype.setContext = function(gl) +{ + this.gl = gl; + + // the next one is used for rendering primitives + this.primitiveShader = new PIXI.PrimitiveShader(gl); + + // the next one is used for rendering triangle strips + this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl); + + // this shader is used for the default sprite rendering + this.defaultShader = new PIXI.PixiShader(gl); + + // this shader is used for the fast sprite rendering + this.fastShader = new PIXI.PixiFastShader(gl); + + // the next one is used for rendering triangle strips + this.stripShader = new PIXI.StripShader(gl); + + // the next one is used for rendering creature meshes + this.creatureShader = PIXI.CreatureShader ? new PIXI.CreatureShader(gl) : null; + + this.setShader(this.defaultShader); +}; + +/** +* Takes the attributes given in parameters. +* +* @method PIXI.WebGLShaderManager#setAttribs +* @param attribs {Array} attribs +*/ +PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs) +{ + // reset temp state + var i; + + for (i = 0; i < this.tempAttribState.length; i++) + { + this.tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + var attribId = attribs[i]; + this.tempAttribState[attribId] = true; + } + + var gl = this.gl; + + for (i = 0; i < this.attribState.length; i++) + { + if(this.attribState[i] !== this.tempAttribState[i]) + { + this.attribState[i] = this.tempAttribState[i]; + + if(this.tempAttribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } +}; + +/** +* Sets the current shader. +* +* @method PIXI.WebGLShaderManager#setShader +* @param shader {Any} +*/ +PIXI.WebGLShaderManager.prototype.setShader = function(shader) +{ + if(this._currentId === shader._UID)return false; + + this._currentId = shader._UID; + + this.currentShader = shader; + + this.gl.useProgram(shader.program); + this.setAttribs(shader.attributes); + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLShaderManager#destroy +*/ +PIXI.WebGLShaderManager.prototype.destroy = function() +{ + this.attribState = null; + + this.tempAttribState = null; + + this.primitiveShader.destroy(); + + this.complexPrimitiveShader.destroy(); + + this.defaultShader.destroy(); + + this.fastShader.destroy(); + + this.stripShader.destroy(); + + if (this.creatureShader) { + this.creatureShader.destroy(); + } + + this.gl = null; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** + * + * @class PIXI.WebGLSpriteBatch + * @private + * @constructor + */ +PIXI.WebGLSpriteBatch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 5; + + /** + * The number of images in the SpriteBatch before it flushes + * @property size + * @type Number + */ + this.size = 2000; //Math.pow(2, 16) / this.vertSize; + + //the total number of bytes in our batch + // Including texture index: + // position + uv + color + textureIndex + // vec2 + vec2 + (char * 4) + float + this.vertexSize = (4 * 2) + (4 * 2) + (4) + (4); + var numVerts = this.vertexSize * this.size * 4; + //this.size * 4 * 4 * this.vertSize; + //the total number of indices in our batch + var numIndices = this.size * 6; + + /** + * Holds the vertices + * + * @property vertices + * @type ArrayBuffer + */ + this.vertices = new ArrayBuffer(numVerts); + + /** + * View on the vertices as a Float32Array + * + * @property positions + * @type Float32Array + */ + this.positions = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array + * + * @property colors + * @type Uint32Array + */ + this.colors = new Uint32Array(this.vertices); + + /** + * Holds the indices + * + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * @property textures + * @type Array + */ + this.textures = []; + + /** + * @property blendModes + * @type Array + */ + this.blendModes = []; + + /** + * @property shaders + * @type Array + */ + this.shaders = []; + + /** + * @property sprites + * @type Array + */ + this.sprites = []; + + /** + * @property defaultShader + * @type Phaser.Filter + */ + this.defaultShader = null; +}; + +/** + * @method PIXI.WebGLSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLSpriteBatch.prototype.setContext = function (gl) { + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.gl = gl; + if (PIXI._enableMultiTextureToggle) { + var dynamicIfs = '\tif (vTextureIndex == 0.0) {gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + 'void main(void) {', + dynamicIfs, + '\tgl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;', + '}' + ]); + } + else + { + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]); + } + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + this.currentBlendMode = 99999; + + var shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = this.defaultShader.fragmentSrc; + shader.uniforms = {}; + shader.init(); + + this.defaultShader.shaders[gl.id] = shader; +}; + +/** + * @method PIXI.WebGLSpriteBatch#begin + * @param renderSession {Object} The RenderSession object + */ +PIXI.WebGLSpriteBatch.prototype.begin = function (renderSession) { + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.defaultShader; + + this.start(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#end + */ +PIXI.WebGLSpriteBatch.prototype.end = function () { + this.flush(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#render + * @param sprite {Sprite} the sprite to render when using this spritebatch + * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. + */ +PIXI.WebGLSpriteBatch.prototype.render = function (sprite, matrix) { + var texture = sprite.texture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + if (PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + baseTexture.textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] = baseTexture; + } + + // They provided an alternative rendering matrix, so use it + var wt = sprite.worldTransform; + + if (matrix) { + wt = matrix; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // get the uvs for the texture + var uvs = texture._uvs; + + // if the uvs have not updated then no point rendering just yet! + if (!uvs) { + return; + } + + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + + var w0, w1, h0, h1; + + if (texture.trim) { + // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords. + var trim = texture.trim; + + w1 = trim.x - aX * trim.width; + w0 = w1 + texture.crop.width; + + h1 = trim.y - aY * trim.height; + h0 = h1 + texture.crop.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 i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + var tiOffset = this.currentBatchSize * 4; + var resolution = texture.baseTexture.resolution; + var textureIndex = texture.baseTexture.textureIndex; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + + var cw = texture.crop.width; + var ch = texture.crop.height; + + if (texture.rotated) + { + var a0 = wt.a; + var b0 = wt.b; + var c0 = wt.c; + var d0 = wt.d; + var _w1 = w1; + var _w0 = w0; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + a = a0 * 6.123233995736766e-17 + -c0; + b = b0 * 6.123233995736766e-17 + -d0; + c = a0 + c0 * 6.123233995736766e-17; + d = b0 + d0 * 6.123233995736766e-17; + + // Update UV coordinates + texture._updateUvsInverted(); + + // Rotate dimensions + w0 = h0; + w1 = h1; + h0 = _w0; + h1 = _w1; + } + + var colors = this.colors; + var positions = this.positions; + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + if (this.renderSession.roundPixels) { + positions[i++] = a * w1 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w1 + ty | 0; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w0 + ty | 0; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w0 + ty | 0; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w1 + ty | 0; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } else { + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx; + positions[i++] = d * h1 + b * w0 + ty; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders a TilingSprite using the spriteBatch. + * + * @method PIXI.WebGLSpriteBatch#renderTilingSprite + * @param sprite {TilingSprite} the sprite to render + */ +PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function (sprite) { + var texture = sprite.tilingTexture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + var textureIndex = sprite.texture.baseTexture.textureIndex; + if (PIXI.WebGLRenderer.textureArray[textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[textureIndex] = baseTexture; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // set the textures uvs temporarily + if (!sprite._uvs) { + sprite._uvs = new PIXI.TextureUvs(); + } + + var uvs = sprite._uvs; + + var w = texture.baseTexture.width; + var h = texture.baseTexture.height; + + // var w = sprite._frame.sourceSizeW; + // var h = sprite._frame.sourceSizeH; + + // w = 16; + // h = 16; + + sprite.tilePosition.x %= w * sprite.tileScaleOffset.x; + sprite.tilePosition.y %= h * sprite.tileScaleOffset.y; + + var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x); + var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y); + + var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x); + var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.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; + + // Get the sprites current alpha and tint and combine them into a single color + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + var positions = this.positions; + var colors = this.colors; + + var width = sprite.width; + var height = sprite.height; + + // TODO trim?? + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + var w0 = width * (1 - aX); + var w1 = width * -aX; + + var h0 = height * (1 - aY); + var h1 = height * -aY; + + var i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + + var resolution = texture.baseTexture.resolution; + + var wt = sprite.worldTransform; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + // xy + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + // uv + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = (a * w0 + c * h1 + tx); + positions[i++] = d * h1 + b * w0 + ty; + // uv + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + // uv + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + // uv + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders the content and empties the current batch. + * + * @method PIXI.WebGLSpriteBatch#flush + */ +PIXI.WebGLSpriteBatch.prototype.flush = function () { + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize === 0) { + return; + } + + var gl = this.gl; + var shader; + + if (this.dirty) { + this.dirty = false; + + shader = this.defaultShader.shaders[gl.id]; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + // this is the same for each shader? + var stride = this.vertexSize; //this.vertSize * 4; + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 8); + + // color attributes will be interpreted as unsigned bytes and normalized + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 16); + + // Texture index + gl.vertexAttribPointer(shader.aTextureIndex, 1, gl.FLOAT, false, stride, 20); + } + + // upload the verts to the buffer + if (this.currentBatchSize > (this.size * 0.5)) { + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + } else { + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + var view = this.positions.subarray(0, this.currentBatchSize * this.vertexSize); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); + } + + var nextTexture, nextBlendMode, nextShader; + var batchSize = 0; + var start = 0; + + var currentBaseTexture = null; + var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode; + var currentShader = null; + + var blendSwap = false; + var shaderSwap = false; + var sprite; + var textureIndex = 0; + + for (var i = 0, j = this.currentBatchSize; i < j; i++) { + + sprite = this.sprites[i]; + + if (sprite.tilingTexture) { + nextTexture = sprite.tilingTexture.baseTexture; + } else { + nextTexture = sprite.texture.baseTexture; + } + + nextBlendMode = sprite.blendMode; + nextShader = sprite.shader || this.defaultShader; + + blendSwap = currentBlendMode !== nextBlendMode; + shaderSwap = currentShader !== nextShader; // should I use _UIDS??? + + var skip = nextTexture.skipRender; + + if (skip && sprite.children.length > 0) { + skip = false; + } + // + if (/*(currentBaseTexture != nextTexture && !skip) ||*/ + blendSwap || + shaderSwap) { + this.renderBatch(currentBaseTexture, batchSize, start); + + start = i; + batchSize = 0; + currentBaseTexture = nextTexture; + + if (blendSwap) { + currentBlendMode = nextBlendMode; + this.renderSession.blendModeManager.setBlendMode(currentBlendMode); + } + + if (shaderSwap) { + currentShader = nextShader; + + shader = currentShader.shaders[gl.id]; + + if (!shader) { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = currentShader.fragmentSrc; + shader.uniforms = currentShader.uniforms; + shader.init(); + + currentShader.shaders[gl.id] = shader; + } + + // set shader function??? + this.renderSession.shaderManager.setShader(shader); + + if (shader.dirty) { + shader.syncUniforms(); + } + + // both these only need to be set if they are changing.. + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(shader.projectionVector, projection.x, projection.y); + + // TODO - this is temporary! + var offsetVector = this.renderSession.offset; + gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y); + + // set the pointers + } + } + + batchSize++; + } + + this.renderBatch(currentBaseTexture, batchSize, start); + + // then reset the batch! + this.currentBatchSize = 0; +}; + +/** + * @method PIXI.WebGLSpriteBatch#renderBatch + * @param texture {Texture} + * @param size {Number} + * @param startIndex {Number} + */ +PIXI.WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { + if (size === 0) { + return; + } + + var gl = this.gl; + + // check if a texture is dirty.. + if (texture._dirty[gl.id]) { + if (!this.renderSession.renderer.updateTexture(texture)) { + // If updateTexture returns false then we cannot render it, so bail out now + return; + } + }else { + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + } + + gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2); + // increment the draw count + this.renderSession.drawCount++; +}; + +/** + * @method PIXI.WebGLSpriteBatch#stop + */ +PIXI.WebGLSpriteBatch.prototype.stop = function () { + this.flush(); + this.dirty = true; +}; + +/** + * @method PIXI.WebGLSpriteBatch#start + */ +PIXI.WebGLSpriteBatch.prototype.start = function () { + this.dirty = true; +}; + +/** + * Destroys the SpriteBatch. + * + * @method PIXI.WebGLSpriteBatch#destroy + */ +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; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** +* @class PIXI.WebGLFastSpriteBatch +* @constructor +*/ +PIXI.WebGLFastSpriteBatch = function(gl) +{ + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 11; + + /** + * @property maxSize + * @type Number + */ + this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize; + + /** + * @property size + * @type Number + */ + this.size = this.maxSize; + + //the total number of floats in our batch + var numVerts = this.size * 4 * this.vertSize; + + //the total number of indices in our batch + var numIndices = this.maxSize * 6; + + /** + * Vertex data + * @property vertices + * @type Float32Array + */ + this.vertices = new Float32Array(numVerts); + + /** + * Index data + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property vertexBuffer + * @type Object + */ + this.vertexBuffer = null; + + /** + * @property indexBuffer + * @type Object + */ + this.indexBuffer = null; + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i=0, j=0; i < numIndices; i += 6, j += 4) + { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 0; + + /** + * @property renderSession + * @type Object + */ + this.renderSession = null; + + /** + * @property shader + * @type Object + */ + this.shader = null; + + /** + * @property matrix + * @type Matrix + */ + this.matrix = null; + + this.setContext(gl); +}; + +PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLFastSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl) +{ + this.gl = gl; + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#begin + * @param spriteBatch {WebGLSpriteBatch} + * @param renderSession {Object} + */ +PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession) +{ + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.fastShader; + + this.matrix = spriteBatch.worldTransform.toArray(true); + + this.start(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#end + */ +PIXI.WebGLFastSpriteBatch.prototype.end = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#render + * @param spriteBatch {WebGLSpriteBatch} + */ +PIXI.WebGLFastSpriteBatch.prototype.render = function (spriteBatch) +{ + var children = spriteBatch.children; + var sprite = children[0]; + + // if the uvs have not updated then no point rendering just yet! + + // check texture. + if(!sprite.texture._uvs)return; + + this.currentBaseTexture = sprite.texture.baseTexture; + + // check blend mode + if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode) + { + this.flush(); + this.renderSession.blendModeManager.setBlendMode(sprite.blendMode); + } + + for(var i=0,j= children.length; i= this.size) + { + this.flush(); + } +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#flush + */ +PIXI.WebGLFastSpriteBatch.prototype.flush = function() +{ + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize===0)return; + + var gl = this.gl; + + // bind the current texture + + if(!this.currentBaseTexture._glTextures[gl.id]) { + this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl); + return; + } + + //gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); + + // upload the verts to the buffer + + if(this.currentBatchSize > ( this.size * 0.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); + } + + // now draw those suckas! + gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0); + + // then reset the batch! + this.currentBatchSize = 0; + + // increment the draw count + this.renderSession.drawCount++; + +}; + + +/** + * @method PIXI.WebGLFastSpriteBatch#stop + */ +PIXI.WebGLFastSpriteBatch.prototype.stop = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#start + */ +PIXI.WebGLFastSpriteBatch.prototype.start = function() +{ + var gl = this.gl; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(this.shader.projectionVector, projection.x, projection.y); + + // set the matrix + gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix); + + // set the pointers + 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); + gl.vertexAttribPointer(this.shader.aTextureIndex, 1, gl.FLOAT, false, stride, 10 * 4); + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLFilterManager +* @constructor +*/ +PIXI.WebGLFilterManager = function() +{ + /** + * @property filterStack + * @type Array + */ + this.filterStack = []; + + /** + * @property offsetX + * @type Number + */ + this.offsetX = 0; + + /** + * @property offsetY + * @type Number + */ + this.offsetY = 0; +}; + +PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLFilterManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLFilterManager.prototype.setContext = function(gl) +{ + this.gl = gl; + this.texturePool = []; + + this.initShaderBuffers(); +}; + +/** +* @method PIXI.WebGLFilterManager#begin +* @param renderSession {RenderSession} +* @param buffer {ArrayBuffer} +*/ +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; +}; + +/** +* Applies the filter and adds it to the current filter stack. +* +* @method PIXI.WebGLFilterManager#pushFilter +* @param filterBlock {Object} the filter that will be pushed to the current filter stack +*/ +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(); + + // >>> modify by nextht + filterBlock._previous_stencil_mgr = this.renderSession.stencilManager; + this.renderSession.stencilManager = new PIXI.WebGLStencilManager(); + this.renderSession.stencilManager.setContext(gl); + gl.disable(gl.STENCIL_TEST); + // <<< modify by nextht + + // filter program + // OPTIMISATION - the first filter is free if its a simple color change? + 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.renderSession.resolution, this.height * this.renderSession.resolution); + } + else + { + texture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + } + + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea; + + var padding = filter.padding; + filterArea.x -= padding; + filterArea.y -= padding; + filterArea.width += padding * 2; + filterArea.height += padding * 2; + + // cap filter to screen size.. + 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer); + + // set view port + gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + projection.x = filterArea.width/2; + projection.y = -filterArea.height/2; + + offset.x = -filterArea.x; + offset.y = -filterArea.y; + + // update projection + // now restore the regular shader.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + //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; + +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLFilterManager#popFilter +*/ +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 * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + 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); + // now set the uvs.. + 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.renderSession.resolution, this.height * this.renderSession.resolution); + outputTexture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + + // need to clear this FBO as it may have some left over elements from a previous filter. + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + gl.clear(gl.COLOR_BUFFER_BIT); + + gl.disable(gl.BLEND); + + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { + var filterPass = filterBlock.filterPasses[i]; + + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture); + + // draw texture.. + //filterPass.applyFilterPass(filterArea.width, filterArea.height); + this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height); + + // swap the textures.. + var temp = inputTexture; + inputTexture = outputTexture; + outputTexture = temp; + } + + gl.enable(gl.BLEND); + + texture = inputTexture; + this.texturePool.push(outputTexture); + } + + var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1]; + + this.offsetX -= filterArea.x; + this.offsetY -= filterArea.y; + + var sizeX = this.width; + var sizeY = this.height; + + var offsetX = 0; + var offsetY = 0; + + var buffer = this.buffer; + + // time to render the filters texture to the previous scene + if(this.filterStack.length === 0) + { + gl.colorMask(true, true, true, true);//this.transparent); + } + else + { + var currentFilter = this.filterStack[this.filterStack.length-1]; + filterArea = currentFilter._filterArea; + + sizeX = filterArea.width; + sizeY = filterArea.height; + + offsetX = filterArea.x; + offsetY = filterArea.y; + + buffer = currentFilter._glFilterTexture.frameBuffer; + } + + // TODO need to remove these global elements.. + projection.x = sizeX/2; + projection.y = -sizeY/2; + + offset.x = offsetX; + offset.y = offsetY; + + filterArea = filterBlock._filterArea; + + var x = filterArea.x-offsetX; + var y = filterArea.y-offsetY; + + // update the buffers.. + // make sure to flip the y! + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + + this.vertexArray[0] = x; + this.vertexArray[1] = y + filterArea.height; + + this.vertexArray[2] = x + filterArea.width; + this.vertexArray[3] = y + filterArea.height; + + this.vertexArray[4] = x; + this.vertexArray[5] = y; + + this.vertexArray[6] = x + filterArea.width; + this.vertexArray[7] = y; + + 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); + + gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution); + + // bind the buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, buffer ); + + // set the blend mode! + //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + // >>> modify by nextht + if (this.renderSession.stencilManager) { + this.renderSession.stencilManager.destroy(); + } + this.renderSession.stencilManager = filterBlock._previous_stencil_mgr; + filterBlock._previous_stencil_mgr = null; + if (this.renderSession.stencilManager.count > 0) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + // <<< modify by nextht + + // apply! + this.applyFilterPass(filter, filterArea, sizeX, sizeY); + + // now restore the regular shader.. should happen automatically now.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2); + // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY); + + // return the texture to the pool + this.texturePool.push(texture); + filterBlock._glFilterTexture = null; +}; + + +/** +* Applies the filter to the specified area. +* +* @method PIXI.WebGLFilterManager#applyFilterPass +* @param filter {Phaser.Filter} the filter that needs to be applied +* @param filterArea {Texture} TODO - might need an update +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +*/ +PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height) +{ + // use program + var gl = this.gl; + var shader = filter.shaders[gl.id]; + + if(!shader) + { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = filter.fragmentSrc; + shader.uniforms = filter.uniforms; + shader.init(true); + + filter.shaders[gl.id] = shader; + } + + // set the shader + this.renderSession.shaderManager.setShader(shader); + +// gl.useProgram(shader.program); + + gl.uniform2f(shader.projectionVector, width/2, -height/2); + gl.uniform2f(shader.offsetVector, 0,0); + + if(filter.uniforms.dimensions) + { + filter.uniforms.dimensions.value[0] = this.width;//width; + filter.uniforms.dimensions.value[1] = this.height;//height; + filter.uniforms.dimensions.value[2] = this.vertexArray[0]; + filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height; + } + + shader.syncUniforms(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // draw the filter... + gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + + this.renderSession.drawCount++; +}; + +/** +* Initialises the shader buffers. +* +* @method PIXI.WebGLFilterManager#initShaderBuffers +*/ +PIXI.WebGLFilterManager.prototype.initShaderBuffers = function() +{ + var gl = this.gl; + + // create some buffers + this.vertexBuffer = gl.createBuffer(); + this.uvBuffer = gl.createBuffer(); + this.colorBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // bind and upload the vertexs.. + // keep a reference to the vertexFloatData.. + this.vertexArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW); + + // bind and upload the uv buffer + this.uvArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW); + + this.colorArray = new Float32Array([1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW); + + // bind and upload the index + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW); + +}; + +/** +* Destroys the filter and removes it from the filter stack. +* +* @method PIXI.WebGLFilterManager#destroy +*/ +PIXI.WebGLFilterManager.prototype.destroy = function() +{ + var gl = this.gl; + + this.filterStack = null; + + this.offsetX = 0; + this.offsetY = 0; + + // destroy textures + for (var i = 0; i < this.texturePool.length; i++) { + this.texturePool[i].destroy(); + } + + this.texturePool = null; + + //destroy buffers.. + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.uvBuffer); + gl.deleteBuffer(this.colorBuffer); + gl.deleteBuffer(this.indexBuffer); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @private + */ +function _CreateEmptyTexture(gl, width, height, scaleMode) { + var texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + return texture; +} + +/** + * @private + */ +var _fbErrors = { + 36054: 'Incomplete attachment', + 36055: 'Missing attachment', + 36057: 'Incomplete dimensions', + 36061: 'Framebuffer unsupported' +}; + +/** + * @private + */ +function _CreateFramebuffer(gl, width, height, scaleMode, textureUnit) { + var framebuffer = gl.createFramebuffer(); + var depthStencilBuffer = gl.createRenderbuffer(); + var colorBuffer = null; + var fbStatus = 0; + + gl.activeTexture(gl.TEXTURE0 + textureUnit); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer); + colorBuffer = _CreateEmptyTexture(gl, width, height, scaleMode); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorBuffer, 0); + fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + if(fbStatus !== gl.FRAMEBUFFER_COMPLETE) { + console.error('Incomplete GL framebuffer. ', _fbErrors[fbStatus]); + } + framebuffer.width = width; + framebuffer.height = height; + framebuffer.targetTexture = colorBuffer; + framebuffer.renderBuffer = depthStencilBuffer; + return framebuffer; +} + +/** +* @class PIXI.FilterTexture +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +* @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values +*/ +PIXI.FilterTexture = function(gl, width, height, scaleMode, textureUnit) +{ + textureUnit = typeof textureUnit === 'number' ? textureUnit : 0; + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + // next time to create a frame buffer and texture + + /** + * @property frameBuffer + * @type Any + */ + this.frameBuffer = _CreateFramebuffer(gl, width, height, scaleMode || PIXI.scaleModes.DEFAULT, textureUnit); + /** + * @property texture + * @type Any + */ + this.texture = this.frameBuffer.targetTexture; + this.width = width; + this.height = height; + this.renderBuffer = this.frameBuffer.renderBuffer; +}; + +PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture; + +/** +* Clears the filter texture. +* +* @method PIXI.FilterTexture#clear +*/ +PIXI.FilterTexture.prototype.clear = function() +{ + var gl = this.gl; + + gl.clearColor(0,0,0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Resizes the texture to the specified width and height + * + * @method PIXI.FilterTexture#resize + * @param width {Number} the new width of the texture + * @param height {Number} the new height of the texture + */ +PIXI.FilterTexture.prototype.resize = function(width, height) +{ + if(this.width === width && this.height === height) return; + + this.width = width; + this.height = height; + + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height ); +}; + +/** +* Destroys the filter texture. +* +* @method PIXI.FilterTexture#destroy +*/ +PIXI.FilterTexture.prototype.destroy = function() +{ + var gl = this.gl; + gl.deleteFramebuffer( this.frameBuffer ); + gl.deleteTexture( this.texture ); + + this.frameBuffer = null; + this.texture = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Creates a Canvas element of the given size. + * + * @class PIXI.CanvasBuffer + * @constructor + * @param width {Number} the width for the newly created canvas + * @param height {Number} the height for the newly created canvas + */ +PIXI.CanvasBuffer = function(width, height) +{ + /** + * The width of the Canvas in pixels. + * + * @property width + * @type Number + */ + this.width = width; + + /** + * The height of the Canvas in pixels. + * + * @property height + * @type Number + */ + this.height = height; + + /** + * The Canvas object that belongs to this CanvasBuffer. + * + * @property canvas + * @type HTMLCanvasElement + */ + this.canvas = Phaser.CanvasPool.create(this, this.width, this.height); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.canvas.getContext("2d"); + + this.canvas.width = width; + this.canvas.height = height; +}; + +PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer; + +/** + * Clears the canvas that was created by the CanvasBuffer class. + * + * @method PIXI.CanvasBuffer#clear + * @private + */ +PIXI.CanvasBuffer.prototype.clear = function() +{ + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0,0, this.width, this.height); +}; + +/** + * Resizes the canvas to the specified width and height. + * + * @method PIXI.CanvasBuffer#resize + * @param width {Number} the new width of the canvas + * @param height {Number} the new height of the canvas + */ +PIXI.CanvasBuffer.prototype.resize = function(width, height) +{ + this.width = this.canvas.width = width; + this.height = this.canvas.height = height; +}; + +/** + * Frees the canvas up for use again. + * + * @method PIXI.CanvasBuffer#destroy + */ +PIXI.CanvasBuffer.prototype.destroy = function() +{ + Phaser.CanvasPool.remove(this); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used to handle masking. + * + * @class PIXI.CanvasMaskManager + * @constructor + */ +PIXI.CanvasMaskManager = function() +{ +}; + +PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; + +/** + * This method adds it to the current stack of masks. + * + * @method PIXI.CanvasMaskManager#pushMask + * @param maskData {Object} the maskData that will be pushed + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) { + + var context = renderSession.context; + + context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.worldTransform; + + var resolution = renderSession.resolution; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution); + + PIXI.CanvasGraphics.renderGraphicsMask(maskData, context); + + context.clip(); + + maskData.worldAlpha = cacheAlpha; +}; + +/** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @method PIXI.CanvasMaskManager#popMask + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.popMask = function(renderSession) +{ + renderSession.context.restore(); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class PIXI.CanvasTinter + * @static + */ +PIXI.CanvasTinter = function() {}; + +/** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @method PIXI.CanvasTinter#getTintedTexture + * @static + * @param sprite {Sprite} the sprite to tint + * @param color {Number} the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ +PIXI.CanvasTinter.getTintedTexture = function(sprite, color) +{ + var canvas = sprite.tintedTexture || Phaser.CanvasPool.create(this); + + PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas); + + return canvas; +}; + +/** + * Tint a texture using the "multiply" operation. + * + * @method PIXI.CanvasTinter#tintWithMultiply + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.clearRect(0, 0, w, h); + + context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, w, h); + + context.globalCompositeOperation = "multiply"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + context.globalCompositeOperation = "destination-atop"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + +}; + +/** + * Tint a texture pixel per pixel. + * + * @method PIXI.CanvasTinter#tintPerPixel + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.globalCompositeOperation = "copy"; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + var rgbValues = Phaser.Color.hexToRGBArray(color); + var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, w, h); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) + { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + + if (!PIXI.CanvasTinter.canHandleAlpha) + { + var alpha = pixels[i + 3]; + + pixels[i + 0] /= 255 / alpha; + pixels[i + 1] /= 255 / alpha; + pixels[i + 2] /= 255 / alpha; + } + } + + context.putImageData(pixelData, 0, 0); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class PIXI.CanvasRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.CanvasRenderer = function (game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + /** + * The renderer type. + * + * @property type + * @type Number + */ + this.type = Phaser.CANVAS; + + /** + * The resolution of the canvas. + * + * @property resolution + * @type Number + */ + this.resolution = game.resolution; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. + * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame. + * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The width of the canvas view + * + * @property width + * @type Number + * @default 800 + */ + this.width = game.width * this.resolution; + + /** + * The height of the canvas view + * + * @property height + * @type Number + * @default 600 + */ + this.height = game.height * this.resolution; + + /** + * The canvas element that everything is drawn to. + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * The canvas 2d context that everything is drawn with + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.view.getContext("2d", { alpha: this.transparent } ); + + /** + * Boolean flag controlling canvas refresh. + * + * @property refresh + * @type Boolean + */ + this.refresh = true; + + /** + * Internal var. + * + * @property count + * @type Number + */ + this.count = 0; + + /** + * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer + * @property CanvasMaskManager + * @type CanvasMaskManager + */ + this.maskManager = new PIXI.CanvasMaskManager(); + + /** + * The render session is just a bunch of parameter used for rendering + * @property renderSession + * @type Object + */ + this.renderSession = { + context: this.context, + maskManager: this.maskManager, + scaleMode: null, + smoothProperty: Phaser.Canvas.getSmoothingPrefix(this.context), + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + */ + roundPixels: config.roundPixels || false + }; + + this.mapBlendModes(); + + this.resize(this.width, this.height); + +}; + +// constructor +PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer; + +/** + * Renders the DisplayObjectContainer, usually the Phaser.Stage, to this canvas view. + * + * @method PIXI.CanvasRenderer#render + * @param root {Phaser.Stage|PIXI.DisplayObjectContainer} The root element to be rendered. + */ +PIXI.CanvasRenderer.prototype.render = function (root) { + + this.context.setTransform(1, 0, 0, 1, 0, 0); + + this.context.globalAlpha = 1; + + this.renderSession.currentBlendMode = 0; + this.renderSession.shakeX = this.game.camera._shake.x; + this.renderSession.shakeY = this.game.camera._shake.y; + + this.context.globalCompositeOperation = 'source-over'; + + if (navigator.isCocoonJS && this.view.screencanvas) + { + this.context.fillStyle = "black"; + this.context.clear(); + } + + if (this.clearBeforeRender) + { + if (this.transparent) + { + this.context.clearRect(0, 0, this.width, this.height); + } + else if (root._bgColor) + { + this.context.fillStyle = root._bgColor.rgba; + this.context.fillRect(0, 0, this.width , this.height); + } + } + + this.renderDisplayObject(root); + +}; + +PIXI.CanvasRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + // Does nothing on Canvas, but here to allow you to simply set + // `game.renderer.setTexturePriority()` without having to worry about + // running in WebGL or not. + +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @method PIXI.CanvasRenderer#destroy + * @param [removeView=true] {boolean} Removes the Canvas element from the DOM. + */ +PIXI.CanvasRenderer.prototype.destroy = function (removeView) { + + if (removeView === undefined) { removeView = true; } + + if (removeView && this.view.parent) + { + this.view.parent.removeChild(this.view); + } + + this.view = null; + this.context = null; + this.maskManager = null; + this.renderSession = null; + +}; + +/** + * Resizes the canvas view to the specified width and height + * + * @method PIXI.CanvasRenderer#resize + * @param width {Number} the new width of the canvas view + * @param height {Number} the new height of the canvas view + */ +PIXI.CanvasRenderer.prototype.resize = function (width, height) { + + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) + { + this.view.style.width = this.width / this.resolution + "px"; + this.view.style.height = this.height / this.resolution + "px"; + } + + if (this.renderSession.smoothProperty) + { + this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + +}; + +/** + * Renders a display object + * + * @method PIXI.CanvasRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The displayObject to render + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. + * @private + */ +PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) { + + this.renderSession.context = context || this.context; + this.renderSession.resolution = this.resolution; + displayObject._renderCanvas(this.renderSession, matrix); + +}; + +/** + * Maps Pixi blend modes to canvas blend modes. + * + * @method PIXI.CanvasRenderer#mapBlendModes + * @private + */ +PIXI.CanvasRenderer.prototype.mapBlendModes = function () { + + if (!PIXI.blendModesCanvas) + { + var b = []; + var modes = PIXI.blendModes; + var useNew = this.game.device.canUseMultiply; + + b[modes.NORMAL] = 'source-over'; + b[modes.ADD] = 'lighter'; + b[modes.MULTIPLY] = (useNew) ? 'multiply' : 'source-over'; + b[modes.SCREEN] = (useNew) ? 'screen' : 'source-over'; + b[modes.OVERLAY] = (useNew) ? 'overlay' : 'source-over'; + b[modes.DARKEN] = (useNew) ? 'darken' : 'source-over'; + b[modes.LIGHTEN] = (useNew) ? 'lighten' : 'source-over'; + b[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : 'source-over'; + b[modes.COLOR_BURN] = (useNew) ? 'color-burn' : 'source-over'; + b[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : 'source-over'; + b[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : 'source-over'; + b[modes.DIFFERENCE] = (useNew) ? 'difference' : 'source-over'; + b[modes.EXCLUSION] = (useNew) ? 'exclusion' : 'source-over'; + b[modes.HUE] = (useNew) ? 'hue' : 'source-over'; + b[modes.SATURATION] = (useNew) ? 'saturation' : 'source-over'; + b[modes.COLOR] = (useNew) ? 'color' : 'source-over'; + b[modes.LUMINOSITY] = (useNew) ? 'luminosity' : 'source-over'; + + PIXI.blendModesCanvas = b; + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class PIXI.BaseTexture + * @constructor + * @param source {String|Canvas} the source object (image or canvas) + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + */ +PIXI.BaseTexture = function(source, scaleMode, resolution) +{ + /** + * The Resolution of the texture. + * + * @property resolution + * @type Number + */ + this.resolution = resolution || 1; + + /** + * [read-only] The width of the base texture set when the image has loaded + * + * @property width + * @type Number + * @readOnly + */ + this.width = 100; + + /** + * [read-only] The height of the base texture set when the image has loaded + * + * @property height + * @type Number + * @readOnly + */ + this.height = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @property scaleMode + * @type {Number} + * @default PIXI.scaleModes.LINEAR + */ + this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT; + + /** + * [read-only] Set to true once the base texture has loaded + * + * @property hasLoaded + * @type Boolean + * @readOnly + */ + this.hasLoaded = false; + + /** + * The image source that is used to create the texture. + * + * @property source + * @type Image + */ + this.source = source; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * + * @property premultipliedAlpha + * @type Boolean + * @default true + */ + this.premultipliedAlpha = true; + + // used for webGL + + /** + * @property _glTextures + * @type Array + * @private + */ + this._glTextures = []; + + /** + * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @property mipmap + * @type {Boolean} + */ + this.mipmap = false; + + /** + * The multi texture batching index number. + * @property textureIndex + * @type Number + */ + this.textureIndex = 0; + + /** + * @property _dirty + * @type Array + * @private + */ + this._dirty = [true, true, true, true]; + + if (!source) + { + return; + } + + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { + this.hasLoaded = true; + this.width = this.source.naturalWidth || this.source.width; + this.height = this.source.naturalHeight || this.source.height; + this.dirty(); + } + + /** + * A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch. + * + * You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture) + * that has children that you do want to render, without causing a batch flush in the process. + * + * @property skipRender + * @type Boolean + */ + this.skipRender = false; + + /** + * @property _powerOf2 + * @type Boolean + * @private + */ + this._powerOf2 = false; + +}; + +PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture; + +/** + * Forces this BaseTexture to be set as loaded, with the given width and height. + * Then calls BaseTexture.dirty. + * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have. + * + * @method PIXI.BaseTexture#forceLoaded + * @param {number} width - The new width to force the BaseTexture to be. + * @param {number} height - The new height to force the BaseTexture to be. + */ +PIXI.BaseTexture.prototype.forceLoaded = function(width, height) +{ + this.hasLoaded = true; + this.width = width; + this.height = height; + this.dirty(); +}; + +/** + * Destroys this base texture + * + * @method PIXI.BaseTexture#destroy + */ +PIXI.BaseTexture.prototype.destroy = function() +{ + if (this.source) + { + Phaser.CanvasPool.removeByCanvas(this.source); + } + + this.source = null; + + this.unloadFromGPU(); +}; + +/** + * Sets all glTextures to be dirty. + * + * @method PIXI.BaseTexture#dirty + */ +PIXI.BaseTexture.prototype.dirty = function() +{ + for (var i = 0; i < this._glTextures.length; i++) + { + this._dirty[i] = true; + } +}; + +/** + * Removes the base texture from the GPU, useful for managing resources on the GPU. + * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it. + * + * @method PIXI.BaseTexture#unloadFromGPU + */ +PIXI.BaseTexture.prototype.unloadFromGPU = function() +{ + this.dirty(); + + // delete the webGL textures if any. + for (var i = this._glTextures.length - 1; i >= 0; i--) + { + var glTexture = this._glTextures[i]; + var gl = PIXI.glContexts[i]; + + if(gl && glTexture) + { + gl.deleteTexture(glTexture); + } + + } + + this._glTextures.length = 0; + + this.dirty(); +}; + +/** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @method PIXI.BaseTexture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + * @return {BaseTexture} + */ +PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode, resolution) +{ + if (canvas.width === 0) + { + canvas.width = 1; + } + + if (canvas.height === 0) + { + canvas.height = 1; + } + + resolution = resolution || 1; + + return new PIXI.BaseTexture(canvas, scaleMode, resolution); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * TextureSilentFail is a boolean that defaults to `false`. + * If `true` then {@link PIXI.Texture#setFrame} will no longer throw an error if the texture dimensions are incorrect. + * Instead {@link PIXI.Texture#valid} will be set to `false` (#1556) + * + * @type {boolean} + */ +PIXI.TextureSilentFail = false; + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used. + * + * @class PIXI.Texture + * @constructor + * @param baseTexture {BaseTexture} The base texture source to create the texture from + * @param frame {Rectangle} The rectangle frame of the texture to show + * @param [crop] {Rectangle} The area of original texture + * @param [trim] {Rectangle} Trimmed texture rectangle + */ +PIXI.Texture = function(baseTexture, frame, crop, trim) +{ + /** + * Does this Texture have any frame data assigned to it? + * + * @property noFrame + * @type Boolean + */ + this.noFrame = false; + + if (!frame) + { + this.noFrame = true; + frame = new PIXI.Rectangle(0,0,1,1); + } + + if (baseTexture instanceof PIXI.Texture) + { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = baseTexture; + + /** + * The frame specifies the region of the base texture that this texture uses + * + * @property frame + * @type Rectangle + */ + this.frame = frame; + + /** + * The texture trim data. + * + * @property trim + * @type Rectangle + */ + this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @property valid + * @type Boolean + */ + this.valid = false; + + /** + * Is this a tiling texture? As used by the likes of a TilingSprite. + * + * @property isTiling + * @type Boolean + */ + this.isTiling = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @property requiresUpdate + * @type Boolean + */ + this.requiresUpdate = false; + + /** + * This will let a renderer know that a tinted parent has updated its texture. + * + * @property requiresReTint + * @type Boolean + */ + this.requiresReTint = false; + + /** + * The WebGL UV data cache. + * + * @property _uvs + * @type Object + * @private + */ + this._uvs = null; + + /** + * The width of the Texture in pixels. + * + * @property width + * @type Number + */ + this.width = 0; + + /** + * The height of the Texture in pixels. + * + * @property height + * @type Number + */ + this.height = 0; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @property crop + * @type Rectangle + */ + this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1); + + /** + * A flag that controls if this frame is rotated or not. + * Rotation allows you to use rotated frames in texture atlas packing, it has nothing to do with + * Sprite rotation. + * + * @property rotated + * @type Boolean + */ + this.rotated = false; + + if (baseTexture.hasLoaded) + { + if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + this.setFrame(frame); + } + +}; + +PIXI.Texture.prototype.constructor = PIXI.Texture; + +/** + * Called when the base texture is loaded + * + * @method PIXI.Texture#onBaseTextureLoaded + * @private + */ +PIXI.Texture.prototype.onBaseTextureLoaded = function() +{ + var baseTexture = this.baseTexture; + + if (this.noFrame) + { + this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } + + this.setFrame(this.frame); +}; + +/** + * Destroys this texture + * + * @method PIXI.Texture#destroy + * @param destroyBase {Boolean} Whether to destroy the base texture as well + */ +PIXI.Texture.prototype.destroy = function(destroyBase) +{ + if (destroyBase) this.baseTexture.destroy(); + + this.valid = false; +}; + +/** + * Specifies the region of the baseTexture that this texture will use. + * + * @method PIXI.Texture#setFrame + * @param frame {Rectangle} The frame of the texture to set it to + */ +PIXI.Texture.prototype.setFrame = function(frame) +{ + this.noFrame = false; + + this.frame = frame; + this.width = frame.width; + this.height = frame.height; + + this.crop.x = frame.x; + this.crop.y = frame.y; + this.crop.width = frame.width; + this.crop.height = frame.height; + + if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { + if (!PIXI.TextureSilentFail) + { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + this.valid = false; + return; + } + + this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + + if (this.trim) + { + this.width = this.trim.width; + this.height = this.trim.height; + this.frame.width = this.trim.width; + this.frame.height = this.trim.height; + } + + if (this.valid) this._updateUvs(); + +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvs + * @private + */ +PIXI.Texture.prototype._updateUvs = function() +{ + if(!this._uvs)this._uvs = new PIXI.TextureUvs(); + + var frame = this.crop; + 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; +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvsInverted + * @private + */ +PIXI.Texture.prototype._updateUvsInverted = function () { + + if (!this._uvs) { this._uvs = new PIXI.TextureUvs(); } + + var frame = this.crop; + 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.height) / tw; + this._uvs.y1 = frame.y / th; + + this._uvs.x2 = (frame.x + frame.height) / tw; + this._uvs.y2 = (frame.y + frame.width) / th; + + this._uvs.x3 = frame.x / tw; + this._uvs.y3 = (frame.y + frame.width) / th; + +}; + +/** + * Helper function that creates a new a Texture based on the given canvas element. + * + * @static + * @method PIXI.Texture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @return {Texture} + */ +PIXI.Texture.fromCanvas = function(canvas, scaleMode) +{ + var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode); + + return new PIXI.Texture(baseTexture); +}; + +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.y3 = 0; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = PIXI; + } + exports.PIXI = PIXI; + } else if (typeof define !== 'undefined' && define.amd) { + define('PIXI', (function() { return root.PIXI = PIXI; })() ); + } else { + root.PIXI = PIXI; + } + + return PIXI; +}).call(this); +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +(function(){ + + var root = this; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @namespace Phaser +*/ +var Phaser = Phaser || { // jshint ignore:line + + /** + * The Phaser version number. + * @constant Phaser.VERSION + * @type {string} + */ + VERSION: '2.10.0', + + /** + * An array of Phaser game instances. + * @constant Phaser.GAMES + * @type {array} + */ + GAMES: [], + + /** + * AUTO renderer - picks between WebGL or Canvas based on device. + * @constant Phaser.AUTO + * @type {integer} + */ + AUTO: 0, + + /** + * Canvas Renderer. + * @constant Phaser.CANVAS + * @type {integer} + */ + CANVAS: 1, + + /** + * WebGL Renderer. + * @constant Phaser.WEBGL + * @type {integer} + */ + WEBGL: 2, + + /** + * Headless renderer (not visual output) + * @constant Phaser.HEADLESS + * @type {integer} + */ + HEADLESS: 3, + + /** + * WebGL Renderer with MultiTexture support enabled. + * @constant Phaser.WEBGL_MULTI + * @type {integer} + */ + WEBGL_MULTI: 4, + + /** + * Direction constant. + * @constant Phaser.NONE + * @type {integer} + */ + NONE: 0, + + /** + * Direction constant. + * @constant Phaser.LEFT + * @type {integer} + */ + LEFT: 1, + + /** + * Direction constant. + * @constant Phaser.RIGHT + * @type {integer} + */ + RIGHT: 2, + + /** + * Direction constant. + * @constant Phaser.UP + * @type {integer} + */ + UP: 3, + + /** + * Direction constant. + * @constant Phaser.DOWN + * @type {integer} + */ + DOWN: 4, + + /** + * Game Object type. + * @constant Phaser.SPRITE + * @type {integer} + */ + SPRITE: 0, + + /** + * Game Object type. + * @constant Phaser.BUTTON + * @type {integer} + */ + BUTTON: 1, + + /** + * Game Object type. + * @constant Phaser.IMAGE + * @type {integer} + */ + IMAGE: 2, + + /** + * Game Object type. + * @constant Phaser.GRAPHICS + * @type {integer} + */ + GRAPHICS: 3, + + /** + * Game Object type. + * @constant Phaser.TEXT + * @type {integer} + */ + TEXT: 4, + + /** + * Game Object type. + * @constant Phaser.TILESPRITE + * @type {integer} + */ + TILESPRITE: 5, + + /** + * Game Object type. + * @constant Phaser.BITMAPTEXT + * @type {integer} + */ + BITMAPTEXT: 6, + + /** + * Game Object type. + * @constant Phaser.GROUP + * @type {integer} + */ + GROUP: 7, + + /** + * Game Object type. + * @constant Phaser.RENDERTEXTURE + * @type {integer} + */ + RENDERTEXTURE: 8, + + /** + * Game Object type. + * @constant Phaser.TILEMAP + * @type {integer} + */ + TILEMAP: 9, + + /** + * Game Object type. + * @constant Phaser.TILEMAPLAYER + * @type {integer} + */ + TILEMAPLAYER: 10, + + /** + * Game Object type. + * @constant Phaser.EMITTER + * @type {integer} + */ + EMITTER: 11, + + /** + * Game Object type. + * @constant Phaser.POLYGON + * @type {integer} + */ + POLYGON: 12, + + /** + * Game Object type. + * @constant Phaser.BITMAPDATA + * @type {integer} + */ + BITMAPDATA: 13, + + /** + * Game Object type. + * @constant Phaser.CANVAS_FILTER + * @type {integer} + */ + CANVAS_FILTER: 14, + + /** + * Game Object type. + * @constant Phaser.WEBGL_FILTER + * @type {integer} + */ + WEBGL_FILTER: 15, + + /** + * Game Object type. + * @constant Phaser.ELLIPSE + * @type {integer} + */ + ELLIPSE: 16, + + /** + * Game Object type. + * @constant Phaser.SPRITEBATCH + * @type {integer} + */ + SPRITEBATCH: 17, + + /** + * Game Object type. + * @constant Phaser.RETROFONT + * @type {integer} + */ + RETROFONT: 18, + + /** + * Game Object type. + * @constant Phaser.POINTER + * @type {integer} + */ + POINTER: 19, + + /** + * Game Object type. + * @constant Phaser.ROPE + * @type {integer} + */ + ROPE: 20, + + /** + * Game Object type. + * @constant Phaser.CIRCLE + * @type {integer} + */ + CIRCLE: 21, + + /** + * Game Object type. + * @constant Phaser.RECTANGLE + * @type {integer} + */ + RECTANGLE: 22, + + /** + * Game Object type. + * @constant Phaser.LINE + * @type {integer} + */ + LINE: 23, + + /** + * Game Object type. + * @constant Phaser.MATRIX + * @type {integer} + */ + MATRIX: 24, + + /** + * Game Object type. + * @constant Phaser.POINT + * @type {integer} + */ + POINT: 25, + + /** + * Game Object type. + * @constant Phaser.ROUNDEDRECTANGLE + * @type {integer} + */ + ROUNDEDRECTANGLE: 26, + + /** + * Game Object type. + * @constant Phaser.CREATURE + * @type {integer} + */ + CREATURE: 27, + + /** + * Game Object type. + * @constant Phaser.VIDEO + * @type {integer} + */ + VIDEO: 28, + + /** + * Game Object type. + * @constant Phaser.PENDING_ATLAS + * @type {integer} + */ + PENDING_ATLAS: -1, + + /** + * A horizontal orientation + * @constant Phaser.HORIZONTAL + * @type {integer} + */ + HORIZONTAL: 0, + + /** + * A vertical orientation + * @constant Phaser.VERTICAL + * @type {integer} + */ + VERTICAL: 1, + + /** + * A landscape orientation + * @constant Phaser.LANDSCAPE + * @type {integer} + */ + LANDSCAPE: 0, + + /** + * A portrait orientation + * @constant Phaser.PORTRAIT + * @type {integer} + */ + PORTRAIT: 1, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face up. + * @constant Phaser.ANGLE_UP + * @type {integer} + */ + ANGLE_UP: 270, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face down. + * @constant Phaser.ANGLE_DOWN + * @type {integer} + */ + ANGLE_DOWN: 90, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face left. + * @constant Phaser.ANGLE_LEFT + * @type {integer} + */ + ANGLE_LEFT: 180, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face right. + * @constant Phaser.ANGLE_RIGHT + * @type {integer} + */ + ANGLE_RIGHT: 0, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north east. + * @constant Phaser.ANGLE_NORTH_EAST + * @type {integer} + */ + ANGLE_NORTH_EAST: 315, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north west. + * @constant Phaser.ANGLE_NORTH_WEST + * @type {integer} + */ + ANGLE_NORTH_WEST: 225, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south east. + * @constant Phaser.ANGLE_SOUTH_EAST + * @type {integer} + */ + ANGLE_SOUTH_EAST: 45, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south west. + * @constant Phaser.ANGLE_SOUTH_WEST + * @type {integer} + */ + ANGLE_SOUTH_WEST: 135, + + /** + * A constant representing a top-left alignment or position. + * @constant Phaser.TOP_LEFT + * @type {integer} + */ + TOP_LEFT: 0, + + /** + * A constant representing a top-center alignment or position. + * @constant Phaser.TOP_CENTER + * @type {integer} + */ + TOP_CENTER: 1, + + /** + * A constant representing a top-right alignment or position. + * @constant Phaser.TOP_RIGHT + * @type {integer} + */ + TOP_RIGHT: 2, + + /** + * A constant representing a left-top alignment or position. + * @constant Phaser.Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_TOP: 3, + + /** + * A constant representing a left-center alignment or position. + * @constant Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_CENTER: 4, + + /** + * A constant representing a left-bottom alignment or position. + * @constant Phaser.LEFT_BOTTOM + * @type {integer} + */ + LEFT_BOTTOM: 5, + + /** + * A constant representing a center alignment or position. + * @constant Phaser.CENTER + * @type {integer} + */ + CENTER: 6, + + /** + * A constant representing a right-top alignment or position. + * @constant Phaser.RIGHT_TOP + * @type {integer} + */ + RIGHT_TOP: 7, + + /** + * A constant representing a right-center alignment or position. + * @constant Phaser.RIGHT_CENTER + * @type {integer} + */ + RIGHT_CENTER: 8, + + /** + * A constant representing a right-bottom alignment or position. + * @constant Phaser.RIGHT_BOTTOM + * @type {integer} + */ + RIGHT_BOTTOM: 9, + + /** + * A constant representing a bottom-left alignment or position. + * @constant Phaser.BOTTOM_LEFT + * @type {integer} + */ + BOTTOM_LEFT: 10, + + /** + * A constant representing a bottom-center alignment or position. + * @constant Phaser.BOTTOM_CENTER + * @type {integer} + */ + BOTTOM_CENTER: 11, + + /** + * A constant representing a bottom-right alignment or position. + * @constant Phaser.BOTTOM_RIGHT + * @type {integer} + */ + BOTTOM_RIGHT: 12, + + /** + * Various blend modes supported by Pixi. See the samples in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing Canvas Tutorial: Compositing}. + * + * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * + * @constant {Object} Phaser.blendModes + * @property {Number} blendModes.NORMAL - Draws new shapes on top of the existing content. This is the default setting. + * @property {Number} blendModes.ADD - Where both shapes overlap the color is determined by adding color values. + * @property {Number} blendModes.MULTIPLY - The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer, making a darker picture. + * @property {Number} blendModes.SCREEN - The pixels are inverted, multiplied, and inverted again, making a lighter picture. + * @property {Number} blendModes.OVERLAY + * @property {Number} blendModes.DARKEN + * @property {Number} blendModes.LIGHTEN + * @property {Number} blendModes.COLOR_DODGE + * @property {Number} blendModes.COLOR_BURN + * @property {Number} blendModes.HARD_LIGHT + * @property {Number} blendModes.SOFT_LIGHT + * @property {Number} blendModes.DIFFERENCE + * @property {Number} blendModes.EXCLUSION + * @property {Number} blendModes.HUE + * @property {Number} blendModes.SATURATION + * @property {Number} blendModes.COLOR + * @property {Number} blendModes.LUMINOSITY + * @static + */ + 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 + }, + + /** + * The scale modes that are supported by Pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @constant {Object} Phaser.scaleModes + * @property {Number} Phaser.scaleModes.DEFAULT=LINEAR + * @property {Number} Phaser.scaleModes.LINEAR Smooth scaling + * @property {Number} Phaser.scaleModes.NEAREST Pixelating scaling + * @static + */ + scaleModes: { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 + }, + + PIXI: PIXI || {}, + + // Used to create IDs for various Pixi objects. + _UID: 0 + +}; + +/** +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc +if (!Math.trunc) { + Math.trunc = function trunc(x) { + return x < 0 ? Math.ceil(x) : Math.floor(x); + }; +} + +/** +* A polyfill for Function.prototype.bind +*/ +if (!Function.prototype.bind) { + + /* jshint freeze: false */ + 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)) + { + /* jshint supernew: true */ + return new F; + } + })(target.prototype); + + return bound; + }; + })(); +} + +/** +* A polyfill for Array.isArray +*/ +if (!Array.isArray) +{ + Array.isArray = function (arg) + { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + +/** +* A polyfill for Array.forEach +* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach +*/ +if (!Array.prototype.forEach) +{ + Array.prototype.forEach = function(fun /*, thisArg */) + { + "use strict"; + + if (this === void 0 || this === null) + { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + if (typeof fun !== "function") + { + throw new TypeError(); + } + + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + + for (var i = 0; i < len; i++) + { + if (i in t) + { + fun.call(thisArg, t[i], i, t); + } + } + }; +} + +/** +* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 +* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ +* Cameron Foale (http://www.kibibu.com) +*/ +if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object") +{ + var CheapArray = function(type) + { + var proto = new Array(); // jshint ignore:line + + window[type] = function(arg) { + + if (typeof(arg) === "number") + { + Array.call(this, arg); + this.length = arg; + + for (var i = 0; i < this.length; i++) + { + this[i] = 0; + } + } + else + { + Array.call(this, arg.length); + + this.length = arg.length; + + for (var i = 0; i < this.length; i++) + { + this[i] = arg[i]; + } + } + }; + + window[type].prototype = proto; + window[type].constructor = window[type]; + }; + + CheapArray('Float32Array'); // jshint ignore:line + CheapArray('Uint32Array'); // jshint ignore:line + CheapArray('Uint16Array'); // jshint ignore:line + CheapArray('Int16Array'); // jshint ignore:line + CheapArray('ArrayBuffer'); // jshint ignore:line +} + +/** + * Also fix for the absent console in IE9 + */ +if (!window.console) +{ + window.console = {}; + window.console.log = window.console.assert = function(){}; + window.console.warn = window.console.assert = function(){}; +} + +/** + * Fix for Object.assign not existing on older devices + */ + +if (!Object.assign) { + /* jshint -W098 */ + // We include `varArgs` (unused) to ensure Object.assign.length === 2 + Object.assign = function(target, varArgs) { + /* jshint +W098 */ + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + var hasOwn = Object.prototype.hasOwnProperty; + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (hasOwn.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @class Phaser.Utils +* @static +*/ +Phaser.Utils = { + + /** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @method Phaser.Utils.reverseString + * @param {string} string - The string to be reversed. + * @return {string} The reversed string. + */ + reverseString: function (string) { + + return string.split('').reverse().join(''); + + }, + + /** + * Gets an object's property by string. + * + * @method Phaser.Utils.getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + getProperty: function(obj, name) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + return obj[name]; + case 2: + return obj[parts[0]][parts[1]]; + case 3: + return obj[parts[0]][parts[1]][parts[2]]; + case 4: + return obj[parts[0]][parts[1]][parts[2]][parts[3]]; + default: + return this._getProperty(obj, name); + } + + }, + + /** + * Sets an object's properties from a map of property names and values. + * + * ```javascript + * Phaser.Utils.setProperties(sprite, { + * 'animations.paused': true, + * 'body.enable': false, + * 'input.draggable': true, + * }); + * ``` + * + * @method Phaser.Utils.setProperties + * @param {object} obj - The object to modify. + * @param {object} props - The property names and values to set on the object (see {@link #setProperty}). + * @return {object} The modified object. + */ + setProperties: function(obj, props) { + + for (var name in props) + { + this.setProperty(obj, name, props[name]); + } + + return obj; + + }, + + /** + * Sets an object's property by name and value. + * + * ```javascript + * Phaser.Utils.setProperty(sprite, 'body.velocity.x', 60); + * ``` + * + * @method Phaser.Utils.setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + + setProperty: function(obj, name, value) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + obj[name] = value; + break; + case 2: + obj[parts[0]][parts[1]] = value; + break; + case 3: + obj[parts[0]][parts[1]][parts[2]] = value; + break; + case 4: + obj[parts[0]][parts[1]][parts[2]][parts[3]] = value; + break; + default: + this._setProperty(obj, name, value); + } + }, + + /** + * Gets an object's property by string. + * + * @private + * @method Phaser.Utils._getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property whose value will be returned. + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + _getProperty: function(obj, name) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + val = obj; + + while (i < len) + { + var key = parts[i]; + + if (val != null) + { + val = val[key]; + i++; + } + else + { + return undefined; + } + } + + return val; + + }, + + /** + * Sets an object's property by name and value. + * + * @private + * @method Phaser.Utils._setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + _setProperty: function(obj, name, value) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + currentObj = obj, + key = parts[0]; + + if (len === 1) + { + obj[name] = value; + } + else + { + while (i < (len - 1)) + { + currentObj = currentObj[key]; + i++; + key = parts[i]; + } + + currentObj[key] = value; + } + + return obj; + + }, + + /** + * Generate a random bool result based on the chance value. + * + * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance + * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. + * + * @method Phaser.Utils#chanceRoll + * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). + * @return {boolean} True if the roll passed, or false otherwise. + */ + chanceRoll: function (chance) { + if (chance === undefined) { chance = 50; } + return chance > 0 && (Math.random() * 100 <= chance); + }, + + /** + * Choose between one of two values randomly. + * + * @method Phaser.Utils#randomChoice + * @param {any} choice1 + * @param {any} choice2 + * @return {any} The randomly selected choice + */ + randomChoice: function (choice1, choice2) { + return (Math.random() < 0.5) ? choice1 : choice2; + }, + + /** + * Get a unit dimension from a string. + * + * @method Phaser.Utils.parseDimension + * @param {string|number} size - The size to parse. + * @param {number} dimension - The window dimension to check. + * @return {number} The parsed dimension. + */ + parseDimension: function (size, dimension) { + + var f = 0; + var px = 0; + + if (typeof size === 'string') + { + // %? + if (size.substr(-1) === '%') + { + f = parseInt(size, 10) / 100; + + if (dimension === 0) + { + px = window.innerWidth * f; + } + else + { + px = window.innerHeight * f; + } + } + else + { + px = parseInt(size, 10); + } + } + else + { + px = size; + } + + return px; + + }, + + /** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @method Phaser.Utils.pad + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * @return {string} The padded string. + */ + pad: function (str, len, pad, dir) { + + if (len === undefined) { var len = 0; } + if (pad === undefined) { var pad = ' '; } + if (dir === undefined) { var dir = 3; } + + str = str.toString(); + + 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; + + }, + + /** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * @method Phaser.Utils.isPlainObject + * @param {object} obj - The object to inspect. + * @return {boolean} - true if the object is plain, otherwise false. + */ + isPlainObject: function (obj) { + + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) + { + return false; + } + + // Support: Firefox <20 + // The try/catch suppresses exceptions thrown when attempting to access + // the "constructor" property of certain host objects, ie. |window.location| + // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + try { + if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) + { + return false; + } + } catch (e) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + /** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @method Phaser.Utils.extend + * @param {boolean} deep - Perform a deep copy? + * @param {object} target - The target object to copy to. + * @return {object} The extended object. + */ + extend: function () { + + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if (typeof target === "boolean") + { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } + + for (; i < length; i++) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) + { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = Phaser.Utils.extend(deep, clone, copy); + + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; + + }, + + /** + * Mixes in an existing mixin object with the target. + * + * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` + * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and + * the result is assigned directly. + * + * @method Phaser.Utils.mixinPrototype + * @param {object} target - The target object to receive the new functions. + * @param {object} mixin - The object to copy the functions from. + * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not? + */ + mixinPrototype: function (target, mixin, replace) { + + if (replace === undefined) { replace = false; } + + var mixinKeys = Object.keys(mixin); + + for (var i = 0; i < mixinKeys.length; i++) + { + var key = mixinKeys[i]; + var value = mixin[key]; + + if (!replace && (key in target)) + { + // Not overwriting existing property + continue; + } + else + { + if (value && + (typeof value.get === 'function' || typeof value.set === 'function')) + { + // Special case for classes like Phaser.Point which has a 'set' function! + if (typeof value.clone === 'function') + { + target[key] = value.clone(); + } + else + { + Object.defineProperty(target, key, value); + } + } + else + { + target[key] = value; + } + } + } + + }, + + /** + * Mixes the source object into the destination object, returning the newly modified destination object. + * Based on original code by @mudcube + * + * @method Phaser.Utils.mixin + * @param {object} from - The object to copy (the source object). + * @param {object} to - The object to copy to (the destination object). + * @return {object} The modified destination object. + */ + mixin: function (from, to) { + + if (!from || typeof (from) !== "object") + { + return to; + } + + for (var key in from) + { + var o = from[key]; + + if (o.childNodes || o.cloneNode) + { + continue; + } + + var type = typeof (from[key]); + + if (!from[key] || type !== "object") + { + to[key] = from[key]; + } + else + { + // Clone sub-object + if (typeof (to[key]) === type) + { + to[key] = Phaser.Utils.mixin(from[key], to[key]); + } + else + { + to[key] = Phaser.Utils.mixin(from[key], new o.constructor()); + } + } + } + + return to; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. +* If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. +* +* @class Phaser.Circle +* @constructor +* @param {number} [x=0] - The x coordinate of the center of the circle. +* @param {number} [y=0] - The y coordinate of the center of the circle. +* @param {number} [diameter=0] - The diameter of the circle. +*/ +Phaser.Circle = function (x, y, diameter) { + + x = x || 0; + y = y || 0; + diameter = diameter || 0; + + /** + * @property {number} x - The x coordinate of the center of the circle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the center of the circle. + */ + this.y = y; + + /** + * @property {number} _diameter - The diameter of the circle. + * @private + */ + this._diameter = diameter; + + /** + * @property {number} _radius - The radius of the circle. + * @private + */ + this._radius = 0; + + if (diameter > 0) + { + this._radius = diameter * 0.5; + } + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.CIRCLE; + +}; + +Phaser.Circle.prototype = { + + /** + * The circumference of the circle. + * + * @method Phaser.Circle#circumference + * @return {number} The circumference of the circle. + */ + circumference: function () { + + return 2 * (Math.PI * this._radius); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Circle. + * + * @method Phaser.Circle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = 2 * Math.PI * Math.random(); + var u = Math.random() + Math.random(); + var r = (u > 1) ? 2 - u : u; + var x = r * Math.cos(t); + var y = r * Math.sin(t); + + out.x = this.x + (x * this.radius); + out.y = this.y + (y * this.radius); + + return out; + + }, + + /** + * Returns the framing rectangle of the circle as a Phaser.Rectangle object. + * + * @method Phaser.Circle#getBounds + * @return {Phaser.Rectangle} The bounds of the Circle. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter); + + }, + + /** + * Sets the members of Circle to the specified values. + * @method Phaser.Circle#setTo + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} diameter - The diameter of the circle. + * @return {Circle} This circle object. + */ + setTo: function (x, y, diameter) { + + this.x = x; + this.y = y; + this._diameter = diameter; + this._radius = diameter * 0.5; + + return this; + + }, + + /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method Phaser.Circle#copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.diameter); + + }, + + /** + * Copies the x, y and diameter properties from this Circle to any given object. + * @method Phaser.Circle#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.diameter = this._diameter; + + return dest; + + }, + + /** + * Returns the distance from the center of the Circle object to the given object + * (can be Circle, Point or anything with x/y properties) + * @method Phaser.Circle#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round=false] - Round the distance to the nearest integer. + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y); + return round ? Math.round(distance) : distance; + + }, + + /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. + * @method Phaser.Circle#clone + * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} The cloned Circle object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Circle(this.x, this.y, this.diameter); + } + else + { + output.setTo(this.x, this.y, this.diameter); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Circle object. + * @method Phaser.Circle#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this circle, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Circle.contains(this, x, y); + + }, + + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method Phaser.Circle#circumferencePoint + * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ + circumferencePoint: function (angle, asDegrees, out) { + + return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out); + + }, + + + /** + * Creates or positions points on the circle. + * + * The points are equally distributed in the half-closed interval [startAngle, endAngle). The default arc is the entire circle. + * + * If the `out` argument is omitted, this method creates and returns an array of {@link Phaser.Point points}. If an array is passed as `out`, its items are treated as points and placed in the same way. + * + * @param {type} [steps=60] - The number of points to place. + * @param {type} [startAngle=0] - The starting angle in radians (unless asDegrees is true). + * @param {type} [endAngle=Phaser.Math.PI2] - The end angle in radians (unless asDegrees is true). + * @param {type} [asDegrees=false] - Are the given angles in radians (false) or degrees (true)? + * @param {any[]} [out] - An array of points or point-like objects (e.g., sprites). It should start at index 0 and its length should be equal to or greater than `steps`. + * @return {any[]} - The modified `out` argument or a new array of points. + */ + sample: function (steps, startAngle, endAngle, asDegrees, out) { + + if (!steps) { steps = 60; } + if (startAngle == null) { startAngle = 0; } + if (endAngle == null) { endAngle = Phaser.Math.PI2; } + if (!out) { out = []; } + + var i = 0; + + while (i < steps) + { + this.circumferencePoint( + Phaser.Math.linear(startAngle, endAngle, i / steps), + asDegrees, + out[i] || (out[i] = new Phaser.Point()) + ); + + i += 1; + } + + return out; + + }, + + /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method Phaser.Circle#offset + * @param {number} dx - Moves the x value of the Circle object by this amount. + * @param {number} dy - Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Circle#offsetPoint + * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). + * @return {Circle} This Circle object. + */ + offsetPoint: function (point) { + return this.offset(point.x, point.y); + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Circle#toString + * @return {string} a string representation of the instance. + */ + toString: function () { + return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; + } + +}; + +Phaser.Circle.prototype.constructor = Phaser.Circle; + +/** +* The largest distance between any two points on the circle. The same as the radius * 2. +* +* @name Phaser.Circle#diameter +* @property {number} diameter - Gets or sets the diameter of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "diameter", { + + get: function () { + return this._diameter; + }, + + set: function (value) { + + if (value > 0) + { + this._diameter = value; + this._radius = value * 0.5; + } + } + +}); + +/** +* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. +* @name Phaser.Circle#radius +* @property {number} radius - Gets or sets the radius of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "radius", { + + get: function () { + return this._radius; + }, + + set: function (value) { + + if (value > 0) + { + this._radius = value; + this._diameter = value * 2; + } + + } + +}); + +/** +* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#left +* @propety {number} left - Gets or sets the value of the leftmost point of the circle. +*/ +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; + } + + } + +}); + +/** +* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#right +* @property {number} right - Gets or sets the value of the rightmost point of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "right", { + + get: function () { + return this.x + this._radius; + }, + + set: function (value) { + + if (value < this.x) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.x; + } + + } + +}); + +/** +* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#top +* @property {number} top - Gets or sets the top of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "top", { + + get: function () { + return this.y - this._radius; + }, + + set: function (value) { + + if (value > this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = this.y - value; + } + + } + +}); + +/** +* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#bottom +* @property {number} bottom - Gets or sets the bottom of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "bottom", { + + get: function () { + return this.y + this._radius; + }, + + set: function (value) { + + if (value < this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.y; + } + + } + +}); + +/** +* The area of this Circle. +* @name Phaser.Circle#area +* @property {number} area - The area of this circle. +* @readonly +*/ +Object.defineProperty(Phaser.Circle.prototype, "area", { + + get: function () { + + if (this._radius > 0) + { + return Math.PI * this._radius * this._radius; + } + else + { + return 0; + } + + } + +}); + +/** +* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. +* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. +* @name Phaser.Circle#empty +* @property {boolean} empty - Gets or sets the empty state of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "empty", { + + get: function () { + return (this._diameter === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Circle object. +* @method Phaser.Circle.contains +* @param {Phaser.Circle} a - The Circle to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this circle, otherwise false. +*/ +Phaser.Circle.contains = function (a, x, y) { + + // Check if x/y are within the bounds first + 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; + } + +}; + +/** +* Determines whether the two Circle objects match. This method compares the x, y and diameter properties. +* @method Phaser.Circle.equals +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. +*/ +Phaser.Circle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.diameter === b.diameter); + +}; + +/** +* Determines whether the two Circle objects intersect. +* This method checks the radius distances between the two Circle objects to see if they intersect. +* @method Phaser.Circle.intersects +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. +*/ +Phaser.Circle.intersects = function (a, b) { + + return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius)); + +}; + +/** +* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. +* @method Phaser.Circle.circumferencePoint +* @param {Phaser.Circle} a - The first Circle object. +* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. +* @return {Phaser.Point} The Point object holding the result. +*/ +Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) { + + if (asDegrees === undefined) { asDegrees = false; } + if (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; + +}; + +/** +* Checks if the given Circle and Rectangle objects intersect. +* @method Phaser.Circle.intersectsRectangle +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Rectangle} r - The Rectangle object to test. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +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; + +}; + +/** +* Checks if the given Circle and Line objects intersect. +* @method Phaser.Circle.intersectsLine +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnpoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Circle.intersectsLine = function (c, l, returnPoints) { + var h = c.x; + var k = c.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = c.radius; + var b = c.radius; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Circle = Phaser.Circle; + +/** +* @author Richard Davey +* @author Chad Engler +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a Ellipse object. A curve on a plane surrounding two focal points. +* +* @class Phaser.Ellipse +* @constructor +* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [width=0] - The overall width of this ellipse. +* @param {number} [height=0] - The overall height of this ellipse. +*/ +Phaser.Ellipse = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.x = x; + + /** + * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.y = y; + + /** + * @property {number} width - The overall width of this ellipse. + */ + this.width = width; + + /** + * @property {number} height - The overall height of this ellipse. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ELLIPSE; + +}; + +Phaser.Ellipse.prototype = { + + /** + * Sets the members of the Ellipse to the specified values. + * @method Phaser.Ellipse#setTo + * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} width - The overall width of this ellipse. + * @param {number} height - The overall height of this ellipse. + * @return {Phaser.Ellipse} This Ellipse object. + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. + * + * @method Phaser.Ellipse#getBounds + * @return {Phaser.Rectangle} The bounds of the Ellipse. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Ellipse. + * + * @method Phaser.Ellipse#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Ellipse} This Ellipse object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Ellipse to any given object. + * @method Phaser.Ellipse#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function(dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. + * @method Phaser.Ellipse#clone + * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. + * @return {Phaser.Ellipse} The cloned Ellipse object. + */ + clone: function(output) { + + if (output === undefined || output === null) + { + output = new Phaser.Ellipse(this.x, this.y, this.width, this.height); + } + else + { + output.setTo(this.x, this.y, this.width, this.height); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Ellipse object. + * + * @method Phaser.Ellipse#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this ellipse, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Ellipse.contains(this, x, y); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Ellipse. + * + * @method Phaser.Ellipse#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var p = Math.random() * Math.PI * 2; + var r = Math.random(); + + out.x = Math.sqrt(r) * Math.cos(p); + out.y = Math.sqrt(r) * Math.sin(p); + + out.x = this.x + (out.x * this.width / 2.0); + out.y = this.y + (out.y * this.height / 2.0); + + return out; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Ellipse#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]"; + } + +}; + +Phaser.Ellipse.prototype.constructor = Phaser.Ellipse; + +/** +* The left coordinate of the Ellipse. The same as the X coordinate. +* @name Phaser.Ellipse#left +* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + + this.x = value; + + } + +}); + +/** +* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. +* @name Phaser.Ellipse#right +* @property {number} right - Gets or sets the value of the rightmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "right", { + + get: function () { + return this.x + this.width; + }, + + set: function (value) { + + if (value < this.x) + { + this.width = 0; + } + else + { + this.width = value - this.x; + } + } + +}); + +/** +* The top of the Ellipse. The same as its y property. +* @name Phaser.Ellipse#top +* @property {number} top - Gets or sets the top of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "top", { + + get: function () { + return this.y; + }, + + set: function (value) { + this.y = value; + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. +* @name Phaser.Ellipse#bottom +* @property {number} bottom - Gets or sets the bottom of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value < this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + } + +}); + +/** +* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. +* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. +* @name Phaser.Ellipse#empty +* @property {boolean} empty - Gets or sets the empty state of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "empty", { + + get: function () { + return (this.width === 0 || this.height === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Ellipse object. +* +* @method Phaser.Ellipse.contains +* @param {Phaser.Ellipse} a - The Ellipse to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this ellipse, otherwise false. +*/ +Phaser.Ellipse.contains = function (a, x, y) { + + if (a.width <= 0 || a.height <= 0) { + return false; + } + + // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 + var normx = ((x - a.x) / a.width) - 0.5; + var normy = ((y - a.y) / a.height) - 0.5; + + normx *= normx; + normy *= normy; + + return (normx + normy < 0.25); + +}; + +/** +* Checks if the given Ellipse and Line objects intersect. +* @method Phaser.Ellipse.intersectsLine +* @param {Phaser.Ellipse} e - The Ellipse object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnPoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Ellipse.intersectsLine = function (e, l, returnPoints) { + var h = e.x; + var k = e.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = e.width / 2; + var b = e.height / 2; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Ellipse = Phaser.Ellipse; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Line object with a start and an end point. +* +* @class Phaser.Line +* @constructor +* @param {number} [x1=0] - The x coordinate of the start of the line. +* @param {number} [y1=0] - The y coordinate of the start of the line. +* @param {number} [x2=0] - The x coordinate of the end of the line. +* @param {number} [y2=0] - The y coordinate of the end of the line. +*/ +Phaser.Line = function (x1, y1, x2, y2) { + + x1 = x1 || 0; + y1 = y1 || 0; + x2 = x2 || 0; + y2 = y2 || 0; + + /** + * @property {Phaser.Point} start - The start point of the line. + */ + this.start = new Phaser.Point(x1, y1); + + /** + * @property {Phaser.Point} end - The end point of the line. + */ + this.end = new Phaser.Point(x2, y2); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.LINE; + +}; + +Phaser.Line.prototype = { + + /** + * Sets the components of the Line to the specified values. + * + * @method Phaser.Line#setTo + * @param {number} [x1=0] - The x coordinate of the start of the line. + * @param {number} [y1=0] - The y coordinate of the start of the line. + * @param {number} [x2=0] - The x coordinate of the end of the line. + * @param {number} [y2=0] - The y coordinate of the end of the line. + * @return {Phaser.Line} This line object + */ + setTo: function (x1, y1, x2, y2) { + + this.start.setTo(x1, y1); + this.end.setTo(x2, y2); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given points. + * + * @param {any} start - A {@link Phaser.Point} or point-like object. + * @param {any} end - A {@link Phaser.Point} or point-like object. + * @return {Phaser.Line} - This line object. + */ + fromPoints: function (start, end) { + + this.setTo(start.x, start.y, end.x, end.y); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given sprites. + * Can optionally be calculated from their center coordinates. + * + * @method Phaser.Line#fromSprite + * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {boolean} [useCenter=false] - If true it will use startSprite.centerX, if false startSprite.x. + * @return {Phaser.Line} This line object + */ + fromSprite: function (startSprite, endSprite, useCenter) { + + if (useCenter === undefined) { useCenter = false; } + + if (useCenter) + { + return this.setTo(startSprite.centerX, startSprite.centerY, endSprite.centerX, endSprite.centerY); + } + + return this.fromPoints(startSprite, endSprite); + + }, + + /** + * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. + * + * @method Phaser.Line#fromAngle + * @param {number} x - The x coordinate of the start of the line. + * @param {number} y - The y coordinate of the start of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line in pixels. + * @return {Phaser.Line} This line object + */ + fromAngle: function (x, y, angle, length) { + + this.start.setTo(x, y); + this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length)); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place from the center of the line. + * If you wish to rotate around a different point see Line.rotateAround. + * + * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. + * + * @method Phaser.Line#rotate + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotate: function (angle, asDegrees) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + this.start.rotate(cx, cy, angle, asDegrees); + this.end.rotate(cx, cy, angle, asDegrees); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place around the coordinates given. + * + * @method Phaser.Line#rotateAround + * @param {number} x - The x coordinate to offset the rotation from. + * @param {number} y - The y coordinate to offset the rotation from. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotateAround: function (x, y, angle, asDegrees) { + + this.start.rotate(x, y, angle, asDegrees); + this.end.rotate(x, y, angle, asDegrees); + + return this; + + }, + + /** + * Checks for intersection between this line and another Line. + * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * + * @method Phaser.Line#intersects + * @param {Phaser.Line} line - The line to check against this one. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ + intersects: function (line, asSegment, result) { + + return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result); + + }, + + /** + * Returns the reflected angle between two lines. + * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. + * + * @method Phaser.Line#reflect + * @param {Phaser.Line} line - The line to reflect off this line. + * @return {number} The reflected angle in radians. + */ + reflect: function (line) { + + return Phaser.Line.reflect(this, line); + + }, + + /** + * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. + * + * @method Phaser.Line#midPoint + * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. + * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. + */ + midPoint: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = (this.start.x + this.end.x) / 2; + out.y = (this.start.y + this.end.y) / 2; + + return out; + + }, + + /** + * Centers this Line on the given coordinates. + * + * The line is centered by positioning the start and end points so that the lines midpoint matches + * the coordinates given. + * + * @method Phaser.Line#centerOn + * @param {number} x - The x position to center the line on. + * @param {number} y - The y position to center the line on. + * @return {Phaser.Line} This line object + */ + centerOn: function (x, y) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + var tx = x - cx; + var ty = y - cy; + + this.start.add(tx, ty); + this.end.add(tx, ty); + + }, + + /** + * Tests if the given coordinates fall on this line. See {@link #pointOnSegment} to test against just the line segment. + * + * @method Phaser.Line#pointOnLine + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line, false if not. + */ + pointOnLine: function (x, y, epsilon) { + + return Phaser.Math.fuzzyEqual((x - this.start.x) * (this.end.y - this.start.y), (this.end.x - this.start.x) * (y - this.start.y), epsilon || 0); + + }, + + /** + * Tests if the given coordinates fall on this line and within the segment. See {@link #pointOnLine} to test against just the line. + * + * @method Phaser.Line#pointOnSegment + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line and segment, false if not. + */ + pointOnSegment: function (x, y, epsilon) { + + var xMin = Math.min(this.start.x, this.end.x); + var xMax = Math.max(this.start.x, this.end.x); + var yMin = Math.min(this.start.y, this.end.y); + var yMax = Math.max(this.start.y, this.end.y); + + return (this.pointOnLine(x, y, epsilon) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)); + + }, + + /** + * Picks a random point from anywhere on the Line segment and returns it. + * + * @method Phaser.Line#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = Math.random(); + + out.x = this.start.x + t * (this.end.x - this.start.x); + out.y = this.start.y + t * (this.end.y - this.start.y); + + return out; + + }, + + /** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * The start and end points are rounded before this runs as the algorithm works on integers. + * + * @method Phaser.Line#coordinatesOnLine + * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. + * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. + * @return {array} An array of coordinates. + */ + coordinatesOnLine: function (stepRate, results) { + + if (stepRate === undefined) { stepRate = 1; } + if (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 < x2) ? 1 : -1; + var sy = (y1 < y2) ? 1 : -1; + var err = dx - dy; + + results.push([x1, y1]); + + var i = 1; + + while (!((x1 === x2) && (y1 === y2))) + { + var e2 = err << 1; + + if (e2 > -dy) + { + err -= dy; + x1 += sx; + } + + if (e2 < dx) + { + err += dx; + y1 += sy; + } + + if (i % stepRate === 0) + { + results.push([x1, y1]); + } + + i++; + + } + + return results; + + }, + + /** + * Returns a new Line object with the same values for the start and end properties as this Line object. + * @method Phaser.Line#clone + * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned. + * @return {Phaser.Line} The cloned Line object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y); + } + else + { + output.setTo(this.start.x, this.start.y, this.end.x, this.end.y); + } + + return output; + + } + +}; + +/** +* @name Phaser.Line#length +* @property {number} length - Gets the length of the line segment. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "length", { + + get: function () { + return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#angle +* @property {number} angle - Gets the angle of the line in radians. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "angle", { + + get: function () { + return Phaser.Point.angle(this.end, this.start); + } + +}); + +/** +* @name Phaser.Line#slope +* @property {number} slope - Gets the slope of the line (y/x). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "slope", { + + get: function () { + return (this.end.y - this.start.y) / (this.end.x - this.start.x); + } + +}); + +/** +* @name Phaser.Line#perpSlope +* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "perpSlope", { + + get: function () { + return -((this.end.x - this.start.x) / (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#x +* @property {number} x - Gets the x coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "x", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#y +* @property {number} y - Gets the y coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "y", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#left +* @property {number} left - Gets the left-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "left", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#right +* @property {number} right - Gets the right-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "right", { + + get: function () { + return Math.max(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#top +* @property {number} top - Gets the top-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "top", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#bottom +* @property {number} bottom - Gets the bottom-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "bottom", { + + get: function () { + return Math.max(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#width +* @property {number} width - Gets the width of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "width", { + + get: function () { + return Math.abs(this.start.x - this.end.x); + } + +}); + +/** +* @name Phaser.Line#height +* @property {number} height - Gets the height of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "height", { + + get: function () { + return Math.abs(this.start.y - this.end.y); + } + +}); + +/** +* @name Phaser.Line#normalX +* @property {number} normalX - Gets the x component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalX", { + + get: function () { + return Math.cos(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalY +* @property {number} normalY - Gets the y component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalY", { + + get: function () { + return Math.sin(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalAngle +* @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalAngle", { + + get: function () { + return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI); + } + +}); + +/** +* Checks for intersection between two lines as defined by the given start and end points. +* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersectsPoints +* @param {Phaser.Point} a - The start of the first Line to be checked. +* @param {Phaser.Point} b - The end of the first line to be checked. +* @param {Phaser.Point} e - The start of the second Line to be checked. +* @param {Phaser.Point} f - The end of the second line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) { + + if (asSegment === undefined) { asSegment = true; } + if (result === undefined) { result = new Phaser.Point(); } + + var a1 = b.y - a.y; + var a2 = f.y - e.y; + var b1 = a.x - b.x; + var b2 = e.x - f.x; + var c1 = (b.x * a.y) - (a.x * b.y); + var c2 = (f.x * e.y) - (e.x * f.y); + var denom = (a1 * b2) - (a2 * b1); + + if (denom === 0) + { + return null; + } + + result.x = ((b1 * c2) - (b2 * c1)) / denom; + result.y = ((a2 * c1) - (a1 * c2)) / denom; + + if (asSegment) + { + var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y)); + var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc; + var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc; + + if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) + { + return result; + } + else + { + return null; + } + } + + return result; + +}; + +/** +* Checks for intersection between two lines. +* If asSegment is true it will check for segment intersection. +* If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersects +* @param {Phaser.Line} a - The first Line to be checked. +* @param {Phaser.Line} b - The second Line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersects = function (a, b, asSegment, result) { + + return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result); + +}; + +/** +* Checks for intersection between the Line and a Rectangle shape, or a rectangle-like +* object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. +* +* An intersection is considered valid if: +* +* The line starts within or ends within the rectangle; or +* The line segment intersects one of the 4 rectangle edges; and +* The line has a non-zero length; and +* The rectangle is not empty. +* +* For the purposes of this function rectangles are considered 'solid'. +* +* @method Phaser.Line.intersectsRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle. +*/ +Phaser.Line.intersectsRectangle = function (line, rect) { + + // Quick bail out + if (line.length === 0 || rect.empty) + { + return false; + } + + var x1 = line.start.x; + var y1 = line.start.y; + + var x2 = line.end.x; + var y2 = line.end.y; + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + + var t = 0; + + // If the start or end of the line is inside the rect then we assume + // collision, as rects are solid for our use-case. + + if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || + (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) + { + return true; + } + + if (x1 < bx1 && x2 >= bx1) + { + // Left edge + t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); + + if (t > by1 && t <= by2) + { + return true; + } + } + else if (x1 > bx2 && x2 <= bx2) + { + // Right edge + t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); + + if (t >= by1 && t <= by2) + { + return true; + } + } + + if (y1 < by1 && y2 >= by1) + { + // Top edge + t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + else if (y1 > by2 && y2 <= by2) + { + // Bottom edge + t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + + return false; + +}; + +/** +* Finds the closest intersection between the Line and a Rectangle shape, or a rectangle-like +* object, such as a Sprite or Body. +* +* @method Phaser.Line.intersectionWithRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @param {Phaser.Point} [result] - A Point object to store the result in. +* @return {?Phaser.Point} - The intersection closest to the Line's start, or null if there is no intersection. +*/ +Phaser.Line.intersectionWithRectangle = function (line, rect, result) { + + var self = Phaser.Line.intersectionWithRectangle; + + if (!result) + { + result = new Phaser.Point(); + } + + if (!self.edges) + { + self.edges = [new Phaser.Line(), new Phaser.Line(), new Phaser.Line(), new Phaser.Line()]; + } + + if (!self.edgeIntersection) + { + self.edgeIntersection = new Phaser.Point(); + } + + var edges = self.edges; + var edgeIntersection = self.edgeIntersection.set(0); + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + var closestDistance = Infinity; + + edges[0].setTo(bx1, by1, bx2, by1); + edges[1].setTo(bx1, by2, bx2, by2); + edges[2].setTo(bx1, by1, bx1, by2); + edges[3].setTo(bx2, by1, bx2, by2); + + for (var edge, i = 0; (edge = edges[i]); i++) + { + if (line.intersects(edge, true, edgeIntersection)) + { + var distance = line.start.distance(edgeIntersection); + + if (distance < closestDistance) + { + closestDistance = distance; + result.copyFrom(edgeIntersection); + } + } + } + + if (distance != null) + { + return result; + } + + return null; + +}; + +/** +* Returns the reflected angle between two lines. +* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. +* +* @method Phaser.Line.reflect +* @param {Phaser.Line} a - The base line. +* @param {Phaser.Line} b - The line to be reflected from the base line. +* @return {number} The reflected angle in radians. +*/ +Phaser.Line.reflect = function (a, b) { + + return 2 * b.normalAngle - 3.141592653589793 - a.angle; + +}; + +/** +* @author Mat Groves http://matgroves.com/ @Doormat23 +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. +* +* It is represented like so: +* +* | a | b | tx | +* | c | d | ty | +* | 0 | 0 | 1 | +* +* @class Phaser.Matrix +* @constructor +* @param {number} [a=1] - Horizontal scaling +* @param {number} [b=0] - Horizontal skewing +* @param {number} [c=0] - Vertical skewing +* @param {number} [d=1] - Vertical scaling +* @param {number} [tx=0] - Horizontal translation +* @param {number} [ty=0] - Vertical translation +*/ +Phaser.Matrix = function (a, b, c, d, tx, ty) { + + if (a === undefined || a === null) { a = 1; } + if (b === undefined || b === null) { b = 0; } + if (c === undefined || c === null) { c = 0; } + if (d === undefined || d === null) { d = 1; } + if (tx === undefined || tx === null) { tx = 0; } + if (ty === undefined || ty === null) { ty = 0; } + + /** + * @property {number} a + * @default 1 + */ + this.a = a; + + /** + * @property {number} b + * @default 0 + */ + this.b = b; + + /** + * @property {number} c + * @default 0 + */ + this.c = c; + + /** + * @property {number} d + * @default 1 + */ + this.d = d; + + /** + * @property {number} tx + * @default 0 + */ + this.tx = tx; + + /** + * @property {number} ty + * @default 0 + */ + this.ty = ty; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.MATRIX; + +}; + +Phaser.Matrix.prototype = { + + /** + * Sets the values of this Matrix to the values in the given array. + * + * The Array elements should be set as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @method Phaser.Matrix#fromArray + * @param {Array} array - The array to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + fromArray: function (array) { + + return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]); + + }, + + /** + * Sets the values of this Matrix to the given values. + * + * @method Phaser.Matrix#setTo + * @param {number} a - Horizontal scaling + * @param {number} b - Horizontal skewing + * @param {number} c - Vertical skewing + * @param {number} d - Vertical scaling + * @param {number} tx - Horizontal translation + * @param {number} ty - Vertical translation + * @return {Phaser.Matrix} This Matrix object. + */ + setTo: function (a, b, c, d, tx, ty) { + + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + + }, + + /** + * Creates a new Matrix object based on the values of this Matrix. + * If you provide the output parameter the values of this Matrix will be copied over to it. + * If the output parameter is blank a new Matrix object will be created. + * + * @method Phaser.Matrix#clone + * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created. + * @return {Phaser.Matrix} A clone of this Matrix. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); + } + else + { + output.a = this.a; + output.b = this.b; + output.c = this.c; + output.d = this.d; + output.tx = this.tx; + output.ty = this.ty; + } + + return output; + + }, + + /** + * Copies the properties from this Matrix to the given Matrix. + * + * @method Phaser.Matrix#copyTo + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} The destination Matrix object. + */ + copyTo: function (matrix) { + + matrix.copyFrom(this); + + return matrix; + + }, + + /** + * Copies the properties from the given Matrix into this Matrix. + * + * @method Phaser.Matrix#copyFrom + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + copyFrom: function (matrix) { + + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + + return this; + + }, + + /** + * Creates a Float32 Array with values populated from this Matrix object. + * + * @method Phaser.Matrix#toArray + * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not. + * @param {Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created. + * @return {Float32Array} The newly created array which contains the matrix. + */ + toArray: function (transpose, array) { + + if (array === undefined) { array = new Float32Array(9); } + + if (transpose) + { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else + { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + + }, + + /** + * Get a new position with the current transformation applied. + * + * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) + * + * @method Phaser.Matrix#apply + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, transformed through this matrix. + */ + apply: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + newPos.x = this.a * pos.x + this.c * pos.y + this.tx; + newPos.y = this.b * pos.x + this.d * pos.y + this.ty; + + return newPos; + + }, + + /** + * Get a new position with the inverse of the current transformation applied. + * + * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) + * + * @method Phaser.Matrix#applyInverse + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, inverse transformed through this matrix. + */ + applyInverse: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + var id = 1 / (this.a * this.d + this.c * -this.b); + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + + }, + + /** + * Translates the matrix on the x and y. + * This is the same as Matrix.tx += x. + * + * @method Phaser.Matrix#translate + * @param {number} x - The x value to translate on. + * @param {number} y - The y value to translate on. + * @return {Phaser.Matrix} This Matrix object. + */ + translate: function (x, y) { + + this.tx += x; + this.ty += y; + + return this; + + }, + + /** + * Applies a scale transformation to this matrix. + * + * @method Phaser.Matrix#scale + * @param {number} x - The amount to scale horizontally. + * @param {number} y - The amount to scale vertically. + * @return {Phaser.Matrix} This Matrix object. + */ + scale: function (x, y) { + + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + + }, + + /** + * Applies a rotation transformation to this matrix. + * + * @method Phaser.Matrix#rotate + * @param {number} angle - The angle to rotate by, given in radians. + * @return {Phaser.Matrix} This Matrix object. + */ + rotate: function (angle) { + + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos-this.b * sin; + this.b = a1 * sin+this.b * cos; + this.c = c1 * cos-this.d * sin; + this.d = c1 * sin+this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + + }, + + /** + * Appends the given Matrix to this Matrix. + * + * @method Phaser.Matrix#append + * @param {Phaser.Matrix} matrix - The matrix to append to this one. + * @return {Phaser.Matrix} This Matrix object. + */ + append: function (matrix) { + + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + + }, + + /** + * Resets this Matrix to an identity (default) matrix. + * + * @method Phaser.Matrix#identity + * @return {Phaser.Matrix} This Matrix object. + */ + identity: function () { + + return this.setTo(1, 0, 0, 1, 0, 0); + + } + +}; + +Phaser.identityMatrix = new Phaser.Matrix(); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. +* The following code creates a point at (0,0): +* `var myPoint = new Phaser.Point();` +* You can also use them as 2D Vectors and you'll find different vector related methods in this class. +* +* @class Phaser.Point +* @constructor +* @param {number} [x=0] - The horizontal position of this Point. +* @param {number} [y=0] - The vertical position of this Point. +*/ +Phaser.Point = function (x, y) { + + x = x || 0; + y = y || 0; + + /** + * @property {number} x - The x value of the point. + */ + this.x = x; + + /** + * @property {number} y - The y value of the point. + */ + this.y = y; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINT; + +}; + +Phaser.Point.prototype = { + + /** + * Copies the x and y properties from any given object to this Point. + * + * @method Phaser.Point#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Point} This Point object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y); + + }, + + /** + * Inverts the x and y values of this Point + * + * @method Phaser.Point#invert + * @return {Phaser.Point} This Point object. + */ + invert: function () { + + return this.setTo(this.y, this.x); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.setTo(2)` is the same as `Point.setTo(2, 2)` + * + * Identical to {@link #set}. + * + * @method Phaser.Point#setTo + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setTo: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.set(2)` is the same as `Point.set(2, 2)` + * + * Identical to {@link #setTo}. + * + * @method Phaser.Point#set + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + set: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object from a given polar coordinate. + * + * @method Phaser.Point#setToPolar + * @param {number} azimuth - The angular coordinate, in radians (unless `asDegrees`). + * @param {number} [radius=1] - The radial coordinate (length). + * @param {boolean} [asDegrees=false] - True if `azimuth` is in degrees. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setToPolar: function(azimuth, radius, asDegrees) { + + if (radius == null) { radius = 1; } + if (asDegrees) { azimuth = Phaser.Math.degToRad(azimuth); } + + return this.setTo(Math.cos(azimuth) * radius, Math.sin(azimuth) * radius); + + }, + + /** + * Adds the given x and y values to this Point. + * + * @method Phaser.Point#add + * @param {number} x - The value to add to Point.x. + * @param {number} y - The value to add to Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + add: function (x, y) { + + this.x += x; + this.y += y; + return this; + + }, + + /** + * Subtracts the given x and y values from this Point. + * + * @method Phaser.Point#subtract + * @param {number} x - The value to subtract from Point.x. + * @param {number} y - The value to subtract from Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + subtract: function (x, y) { + + this.x -= x; + this.y -= y; + return this; + + }, + + /** + * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. + * + * @method Phaser.Point#multiply + * @param {number} x - The value to multiply Point.x by. + * @param {number} y - The value to multiply Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + multiply: function (x, y) { + + this.x *= x; + this.y *= y; + return this; + + }, + + /** + * Divides Point.x and Point.y by the given x and y values. + * + * @method Phaser.Point#divide + * @param {number} x - The value to divide Point.x by. + * @param {number} y - The value to divide Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + divide: function (x, y) { + + this.x /= x; + this.y /= y; + return this; + + }, + + /** + * Clamps the x value of this Point to be between the given min and max. + * + * @method Phaser.Point#clampX + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampX: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + return this; + + }, + + /** + * Clamps the y value of this Point to be between the given min and max + * + * @method Phaser.Point#clampY + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampY: function (min, max) { + + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * Clamps this Point object values to be between the given min and max. + * + * @method Phaser.Point#clamp + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clamp: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * If this Point is not within the given object, moves it inside (at the nearest edge). + * + * @method Phaser.Point#clip + * @param {any} rect - A {@link Phaser.Rectangle} or any object with left, top, right, and bottom properties. + * @return {Phaser.Point} This Point object. + */ + clip: function (rect) { + + var left = rect.left, top = rect.top, right = rect.right, bottom = rect.bottom; + + if (this.x < left ) { this.x = left; } + else if (this.x > right) { this.x = right; } + if (this.y < top) { this.y = top; } + else if (this.y > bottom) { this.y = bottom; } + + return this; + + }, + + /** + * Creates a copy of the given Point. + * + * @method Phaser.Point#clone + * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The new Point object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(this.x, this.y); + } + else + { + output.setTo(this.x, this.y); + } + + return output; + + }, + + /** + * Copies the x and y properties from this Point to any given object. + * + * @method Phaser.Point#copyTo + * @param {any} dest - The object to copy to. + * @return {object} The dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + + return dest; + + }, + + /** + * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) + * + * @method Phaser.Point#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round] - Round the distance to the nearest integer (default false). + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + return Phaser.Point.distance(this, dest, round); + + }, + + /** + * Determines whether the given objects x/y values are equal to this Point object. + * + * @method Phaser.Point#equals + * @param {Phaser.Point|any} a - The object to compare with this Point. + * @return {boolean} A value of true if the x and y points are equal, otherwise false. + */ + equals: function (a) { + + return a.x === this.x && a.y === this.y; + + }, + + /** + * Determines whether a set of x-y coordinates are equal to this Point's. + * + * @method Phaser.Point#equalsXY + * @param {number} x - The x-coordinate to compare with this Point. + * @param {number} y - The y-coordinate to compare with this Point. + * @return {boolean} A value of true if the Point's coordinates are identical to the arguments, otherwise false. + */ + equalsXY: function (x, y) { + + return this.x === x && this.y === y; + + }, + + fuzzyEquals: function (a, epsilon) { + + return Phaser.Point.fuzzyEquals(this, a, epsilon); + + }, + + fuzzyEqualsXY: function (x, y, epsilon) { + + return Phaser.Point.fuzzyEqualsXY(this, x, y, epsilon); + + }, + + /** + * Returns the angle between this Point object and another object with public x and y properties. + * + * @method Phaser.Point#angle + * @param {Phaser.Point|any} a - The object to get the angle from this Point to. + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angle: function (a, asDegrees) { + + return this.angleXY(a.x, a.y, asDegrees); + + }, + + /** + * Returns the angle between this Point object and an x-y coordinate pair. + * + * @method Phaser.Point#angleXY + * @param {number} x - The x-coordinate + * @param {number} y - The y-coordinate + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angleXY: function (x, y, asDegrees) { + + var angle = Math.atan2(y - this.y, x - this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Returns the arctangent of this Point. + * + * @method Phaser.Point#atan + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where the vertex is (0, 0). Within [-pi, pi] or [-180deg, 180deg]. + */ + atan: function (asDegrees) { + + var angle = Math.atan2(this.y, this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Rotates this Point around the x/y coordinates given to the desired angle. + * + * @method Phaser.Point#rotate + * @param {number} x - The x coordinate of the anchor point. + * @param {number} y - The y coordinate of the anchor point. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {number} [distance] - An optional distance constraint between the Point and the anchor. + * @return {Phaser.Point} The modified point object. + */ + rotate: function (x, y, angle, asDegrees, distance) { + + return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance); + + }, + + /** + * Calculates the length of the Point object. + * + * @method Phaser.Point#getMagnitude + * @return {number} The length of the Point. + */ + getMagnitude: function () { + + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + + }, + + /** + * Calculates the length squared of the Point object. + * + * @method Phaser.Point#getMagnitudeSq + * @return {number} The length ^ 2 of the Point. + */ + getMagnitudeSq: function () { + + return (this.x * this.x) + (this.y * this.y); + + }, + + /** + * Alters the length of the Point without changing the direction. + * + * @method Phaser.Point#setMagnitude + * @param {number} magnitude - The desired magnitude of the resulting Point. + * @return {Phaser.Point} This Point object. + */ + setMagnitude: function (magnitude) { + + return this.normalize().multiply(magnitude, magnitude); + + }, + + /** + * Alters the Point object so that its length is 1, but it retains the same direction. + * + * @method Phaser.Point#normalize + * @return {Phaser.Point} This Point object. + */ + normalize: function () { + + if (!this.isZero()) + { + var m = this.getMagnitude(); + this.x /= m; + this.y /= m; + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at most the max value. + * + * @method Phaser.Point#limit + * @param {number} max - The maximum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#expand + */ + limit: function (max) { + + if (this.getMagnitudeSq() > max * max) + { + this.setMagnitude(max); + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at least the min value. + * + * @method Phaser.Point#expand + * @param {number} min - The minimum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#limit + */ + expand: function (min) { + + if (this.getMagnitudeSq() < min * min) + { + this.setMagnitude(min); + } + + return this; + + }, + + /** + * Determine if this point is at 0,0. + * + * @method Phaser.Point#isZero + * @return {boolean} True if this Point is 0,0, otherwise false. + */ + isZero: function () { + + return (this.x === 0 && this.y === 0); + + }, + + /** + * The dot product of this and another Point object. + * + * @method Phaser.Point#dot + * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point. + * @return {number} The result. + */ + dot: function (a) { + + return ((this.x * a.x) + (this.y * a.y)); + + }, + + /** + * The cross product of this and another Point object. + * + * @method Phaser.Point#cross + * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point. + * @return {number} The result. + */ + cross: function (a) { + + return ((this.x * a.y) - (this.y * a.x)); + + }, + + /** + * Make this Point perpendicular (90 degrees rotation) + * + * @method Phaser.Point#perp + * @return {Phaser.Point} This Point object. + */ + perp: function () { + + return this.setTo(-this.y, this.x); + + }, + + /** + * Make this Point perpendicular (-90 degrees rotation) + * + * @method Phaser.Point#rperp + * @return {Phaser.Point} This Point object. + */ + rperp: function () { + + return this.setTo(this.y, -this.x); + + }, + + /** + * Right-hand normalize (make unit length) this Point. + * + * @method Phaser.Point#normalRightHand + * @return {Phaser.Point} This Point object. + */ + normalRightHand: function () { + + return this.setTo(this.y * -1, this.x); + + }, + + /** + * Math.floor() both the x and y properties of this Point. + * + * @method Phaser.Point#floor + * @return {Phaser.Point} This Point object. + */ + floor: function () { + + return this.setTo(Math.floor(this.x), Math.floor(this.y)); + + }, + + /** + * Math.ceil() both the x and y properties of this Point. + * + * @method Phaser.Point#ceil + * @return {Phaser.Point} This Point object. + */ + ceil: function () { + + return this.setTo(Math.ceil(this.x), Math.ceil(this.y)); + + }, + + /** + * Math.round() both the x and y properties of this Point. + * + * @method Phaser.Point#round + * @return {Phaser.Point} This Point object. + */ + round: function () { + + return this.setTo(Math.round(this.x), Math.round(this.y)); + + }, + + /** + * Returns a string representation of this object. + * + * @method Phaser.Point#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; + + } + +}; + +Phaser.Point.prototype.constructor = Phaser.Point; + +/** +* Adds the coordinates of two points together to create a new point. +* +* @method Phaser.Point.add +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.add = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x + b.x; + out.y = a.y + b.y; + + return out; + +}; + +/** +* Subtracts the coordinates of two points to create a new point. +* +* @method Phaser.Point.subtract +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.subtract = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x - b.x; + out.y = a.y - b.y; + + return out; + +}; + +/** +* Multiplies the coordinates of two points to create a new point. +* +* @method Phaser.Point.multiply +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiply = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x * b.x; + out.y = a.y * b.y; + + return out; + +}; + +/** +* Divides the coordinates of two points to create a new point. +* +* @method Phaser.Point.divide +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.divide = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x / b.x; + out.y = a.y / b.y; + + return out; + +}; + +/** +* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. +* +* @method Phaser.Point.equals +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {boolean} A value of true if the Points are equal, otherwise false. +*/ +Phaser.Point.equals = function (a, b) { + + return a.x === b.x && a.y === b.y; + +}; + +Phaser.Point.equalsXY = function (a, x, y) { + + return a.x === x && a.y === y; + +}; + +Phaser.Point.fuzzyEquals = function (a, b, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, b.x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, b.y, epsilon); + +}; + +Phaser.Point.fuzzyEqualsXY = function (a, x, y, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, y, epsilon); + +}; + +/** +* Returns the angle between two Point objects. +* +* @method Phaser.Point.angle +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {number} The angle, where b is the vertex. Within [-pi, pi]. +*/ +Phaser.Point.angle = function (a, b) { + + return Math.atan2(a.y - b.y, a.x - b.x); + +}; + +/** +* Creates a negative Point. +* +* @method Phaser.Point.negative +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.negative = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.x, -a.y); + +}; + +/** +* Adds two 2D Points together and multiplies the result by the given scalar. +* +* @method Phaser.Point.multiplyAdd +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} s - The scaling value. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiplyAdd = function (a, b, s, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + b.x * s, a.y + b.y * s); + +}; + +/** +* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. +* +* @method Phaser.Point.interpolate +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.interpolate = function (a, b, f, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f); + +}; + +/** +* Return a perpendicular vector (90 degrees rotation) +* +* @method Phaser.Point.perp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.perp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.y, a.x); + +}; + +/** +* Return a perpendicular vector (-90 degrees rotation) +* +* @method Phaser.Point.rperp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.rperp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y, -a.x); + +}; + +/** +* Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). +* +* @method Phaser.Point.distance +* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. +* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. +* @param {boolean} [round=false] - Round the distance to the nearest integer. +* @return {number} The distance between this Point object and the destination Point object. +*/ +Phaser.Point.distance = function (a, b, round) { + + var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y); + return round ? Math.round(distance) : distance; + +}; + +/** +* Project two Points onto another Point. +* +* @method Phaser.Point.project +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.project = function (a, b, out) { + + if (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; + +}; + +/** +* Project two Points onto a Point of unit length. +* +* @method Phaser.Point.projectUnit +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.projectUnit = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var amt = a.dot(b); + + if (amt !== 0) + { + out.setTo(amt * b.x, amt * b.y); + } + + return out; + +}; + +/** +* Right-hand normalize (make unit length) a Point. +* +* @method Phaser.Point.normalRightHand +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalRightHand = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y * -1, a.x); + +}; + +/** +* Normalize (make unit length) a Point. +* +* @method Phaser.Point.normalize +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalize = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var m = a.getMagnitude(); + + if (m !== 0) + { + out.setTo(a.x / m, a.y / m); + } + + return out; + +}; + +/** +* Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by +* the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument +* is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. +* +* The distance allows you to specify a distance constraint for the rotation between the point and the +* coordinates. If none is given the distance between the two is calculated and used. +* +* @method Phaser.Point.rotate +* @param {Phaser.Point} a - The Point object to rotate. +* @param {number} x - The x coordinate of the anchor point +* @param {number} y - The y coordinate of the anchor point +* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {number} [distance] - An optional distance constraint between the Point and the anchor. +* @return {Phaser.Point} The modified point object. +*/ +Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) { + + if (asDegrees) { angle = Phaser.Math.degToRad(angle); } + + if (distance === undefined) + { + a.subtract(x, y); + + var s = Math.sin(angle); + var c = Math.cos(angle); + + var tx = c * a.x - s * a.y; + var ty = s * a.x + c * a.y; + + a.x = tx + x; + a.y = ty + y; + } + else + { + var t = angle + Math.atan2(a.y - y, a.x - x); + a.x = x + distance * Math.cos(t); + a.y = y + distance * Math.sin(t); + } + + return a; + +}; + +/** +* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. +* +* @method Phaser.Point.centroid +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.centroid = function (points, out) { + + if (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 < pointslength; i++) + { + Phaser.Point.add(out, points[i], out); + } + + out.divide(pointslength, pointslength); + + return out; + +}; + +/** +* Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. +* If the object doesn't contain those properties a Point with x/y of zero will be returned. +* +* @method Phaser.Point.parse +* @static +* @param {object} obj - The object to parse. +* @param {string} [xProp='x'] - The property used to set the Point.x value. +* @param {string} [yProp='y'] - The property used to set the Point.y value. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.parse = function(obj, xProp, yProp) { + + xProp = xProp || 'x'; + yProp = yProp || 'y'; + + var point = new Phaser.Point(); + + if (obj[xProp]) + { + point.x = parseInt(obj[xProp], 10); + } + + if (obj[yProp]) + { + point.y = parseInt(obj[yProp], 10); + } + + return point; + +}; + +/** + * Tests a Point or Point-like object. + * + * @method Phaser.Point.isPoint + * @static + * @return {boolean} - True if the object has numeric x and y properties. + */ +Phaser.Point.isPoint = function(obj) { + + return (obj != null) && (typeof obj.x === 'number') && (typeof obj.y === 'number'); + +}; + +/** +* Sets the `x` and `y` values of an object and returns the object. +* +* @method Phaser.Point#set +* @static +* @param {object} obj - An object with numeric x and y properties. +* @param {number} x - The x value. +* @param {number} [y] - The y value. If not given the x value will be used in its place. +* @return {object} The object. Useful for chaining method calls. +*/ +Phaser.Point.set = function(obj, x, y) { + + obj.x = x || 0; + obj.y = y || ( (y !== 0) ? obj.x : 0 ); + + return obj; + +}; + +/** +* Sorts an array of points in a clockwise direction, relative to a reference point. +* +* The sort is clockwise relative to the display, starting from a 12 o'clock position. +* (In the Cartesian plane, it is anticlockwise, starting from the -y direction.) +* +* Example sequence: (0, -1), (1, 0), (0, 1), (-1, 0) +* +* @method Phaser.Point#sortClockwise +* @static +* @param {array} points - An array of Points or point-like objects (e.g., sprites). +* @param {object|Phaser.Point} [center] - The reference point. If omitted, the {@link #centroid} (midpoint) of the points is used. +* @return {array} The sorted array. +*/ +Phaser.Point.sortClockwise = function(points, center) { + + // Adapted from (ciamej) + + if (!center) + { + center = this.centroid(points); + } + + var cx = center.x; + var cy = center.y; + + var sort = function(a, b) { + if (a.x - cx >= 0 && b.x - cx < 0) + { + return -1; + } + + if (a.x - cx < 0 && b.x - cx >= 0) + { + return 1; + } + + if (a.x - cx === 0 && b.x - cx === 0) + { + if (a.y - cy >= 0 || b.y - cy >= 0) + { + return (a.y > b.y) ? 1 : -1; + } + + return (b.y > a.y) ? 1 : -1; + } + + // Compute the cross product of vectors (center -> a) * (center -> b) + var det = (a.x - cx) * -(b.y - cy) - (b.x - cx) * -(a.y - cy); + + if (det < 0) + { + return -1; + } + + if (det > 0) + { + return 1; + } + + // Points a and b are on the same line from the center + // Check which point is closer to the center + var d1 = (a.x - cx) * (a.x - cx) + (a.y - cy) * (a.y - cy); + var d2 = (b.x - cx) * (b.x - cx) + (b.y - cy) * (b.y - cy); + + return (d1 > d2) ? -1 : 1; + }; + + return points.sort(sort); + +}; + + +// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Point = Phaser.Point; + +/** +* @author Richard Davey +* @author Adrien Brault +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Polygon. +* +* The points can be set from a variety of formats: +* +* - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` +* - An array of objects with public x/y properties: `[obj1, obj2, ...]` +* - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` +* - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` +* - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` +* - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` +* +* @class Phaser.Polygon +* @constructor +* @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. +*/ +Phaser.Polygon = function () { + + /** + * @property {number} area - The area of this Polygon. + */ + this.area = 0; + + /** + * @property {array} _points - An array of Points that make up this Polygon. + * @private + */ + this._points = []; + + if (arguments.length > 0) + { + this.setTo.apply(this, arguments); + } + + /** + * @property {boolean} closed - Is the Polygon closed or not? + */ + this.closed = true; + + /** + * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ? + */ + this.flattened = false; + + /** + * @property {number} type - The base object type. + */ + this.type = Phaser.POLYGON; + +}; + +Phaser.Polygon.prototype = { + + /** + * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] + * + * @method Phaser.Polygon#toNumberArray + * @param {array} [output] - The array to append the points to. If not specified a new array will be created. + * @return {array} The flattened array. + */ + toNumberArray: function (output) { + + if (output === undefined) { output = []; } + + for (var i = 0; i < this._points.length; i++) + { + if (typeof this._points[i] === 'number') + { + output.push(this._points[i]); + output.push(this._points[i + 1]); + i++; + } + else + { + output.push(this._points[i].x); + output.push(this._points[i].y); + } + } + + return output; + + }, + + /** + * Flattens this Polygon so the points are a sequence of numbers. + * Any Point objects found are removed and replaced with two numbers. + * Also sets the Polygon.flattened property to `true`. + * + * @method Phaser.Polygon#flatten + * @return {Phaser.Polygon} This Polygon object + */ + flatten: function () { + + this._points = this.toNumberArray(); + + this.flattened = true; + + return this; + + }, + + /** + * Creates a copy of the given Polygon. + * This is a deep clone, the resulting copy contains new Phaser.Point objects + * + * @method Phaser.Polygon#clone + * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created. + * @return {Phaser.Polygon} The cloned (`output`) polygon object. + */ + clone: function (output) { + + var points = this._points.slice(); + + if (output === undefined || output === null) + { + output = new Phaser.Polygon(points); + } + else + { + output.setTo(points); + } + + return output; + + }, + + /** + * Checks whether the x and y coordinates are contained within this polygon. + * + * @method Phaser.Polygon#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this polygon, otherwise false. + */ + contains: function (x, y) { + + // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva + + var inside = false; + + if (this.flattened) + { + for (var i = -2, j = this._points.length - 2; (i += 2) < this._points.length; j = i) + { + var ix = this._points[i]; + var iy = this._points[i + 1]; + + var jx = this._points[j]; + var jy = this._points[j + 1]; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + + } + else + { + for (var i = -1, j = this._points.length - 1; ++i < this._points.length; j = i) + { + var ix = this._points[i].x; + var iy = this._points[i].y; + + var jx = this._points[j].x; + var jy = this._points[j].y; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + } + + return inside; + + }, + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` + * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` + * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` + * + * `setTo` may also be called without any arguments to remove all points. + * + * @method Phaser.Polygon#setTo + * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. + * @return {Phaser.Polygon} This Polygon object + */ + setTo: function (points) { + + this.area = 0; + this._points = []; + + if (arguments.length > 0) + { + // If points isn't an array, use arguments as the array + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments); + } + + var y0 = Number.MAX_VALUE; + + // Allows for mixed-type arguments + for (var i = 0, len = points.length; i < len; i++) + { + if (typeof points[i] === 'number') + { + var p = new PIXI.Point(points[i], points[i + 1]); + i++; + } + else if (Array.isArray(points[i])) + { + var p = new PIXI.Point(points[i][0], points[i][1]); + } + else + { + var p = new PIXI.Point(points[i].x, points[i].y); + } + + this._points.push(p); + + // Lowest boundary + if (p.y < y0) + { + y0 = p.y; + } + } + + this.calculateArea(y0); + } + + return this; + + }, + + /** + * Calcuates the area of the Polygon. This is available in the property Polygon.area + * + * @method Phaser.Polygon#calculateArea + * @private + * @param {number} y0 - The lowest boundary + * @return {number} The area of the Polygon. + */ + calculateArea: function (y0) { + + var p1; + var p2; + var avgHeight; + var width; + + for (var i = 0, len = this._points.length; i < len; i++) + { + p1 = this._points[i]; + + if (i === len - 1) + { + p2 = this._points[0]; + } + else + { + p2 = this._points[i + 1]; + } + + avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2; + width = p1.x - p2.x; + this.area += avgHeight * width; + } + + return this.area; + + } + +}; + +Phaser.Polygon.prototype.constructor = Phaser.Polygon; + +/** +* The points of this polygon. +* +* You can modify these with {@link Phaser.Polygon#setTo setTo}. +* +* @name Phaser.Polygon#points +* @property {Phaser.Point[]} points - The array of vertex points. +* @readonly +*/ +Object.defineProperty(Phaser.Polygon.prototype, 'points', { + + get: function() { + return this._points; + } + +}); + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Polygon = Phaser.Polygon; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. +* If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. +* +* @class Phaser.Rectangle +* @constructor +* @param {number} x - The x coordinate of the top-left corner of the Rectangle. +* @param {number} y - The y coordinate of the top-left corner of the Rectangle. +* @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. +*/ +Phaser.Rectangle = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.RECTANGLE; + +}; + +Phaser.Rectangle.prototype = { + + /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method Phaser.Rectangle#offset + * @param {number} dx - Moves the x value of the Rectangle object by this amount. + * @param {number} dy - Moves the y value of the Rectangle object by this amount. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Rectangle#offsetPoint + * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offsetPoint: function (point) { + + return this.offset(point.x, point.y); + + }, + + /** + * Sets the members of Rectangle to the specified values. + * @method Phaser.Rectangle#setTo + * @param {number} x - The x coordinate of the top-left corner of the Rectangle. + * @param {number} y - The y coordinate of the top-left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Scales the width and height of this Rectangle by the given amounts. + * + * @method Phaser.Rectangle#scale + * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. + * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. + * @return {Phaser.Rectangle} This Rectangle object + */ + scale: function (x, y) { + + if (y === undefined) { y = x; } + + this.width *= x; + this.height *= y; + + return this; + + }, + + /** + * Centers this Rectangle so that the center coordinates match the given x and y values. + * + * @method Phaser.Rectangle#centerOn + * @param {number} x - The x coordinate to place the center of the Rectangle at. + * @param {number} y - The y coordinate to place the center of the Rectangle at. + * @return {Phaser.Rectangle} This Rectangle object + */ + centerOn: function (x, y) { + + this.centerX = x; + this.centerY = y; + + return this; + + }, + + /** + * Runs Math.floor() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#floor + */ + floor: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + + }, + + /** + * Runs Math.floor() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#floorAll + */ + floorAll: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.width = Math.floor(this.width); + this.height = Math.floor(this.height); + + }, + + /** + * Runs Math.ceil() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#ceil + */ + ceil: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + + }, + + /** + * Runs Math.ceil() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#ceilAll + */ + ceilAll: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.width = Math.ceil(this.width); + this.height = Math.ceil(this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the left, top, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFromBounds + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFromBounds: function(source) { + + return this.setTo(source.left, source.top, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Rectangle to any given object. + * @method Phaser.Rectangle#copyTo + * @param {any} source - The object to copy to. + * @return {object} This object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method Phaser.Rectangle#inflate + * @param {number} dx - The amount to be added to the left side of the Rectangle. + * @param {number} dy - The amount to be added to the bottom side of the Rectangle. + * @return {Phaser.Rectangle} This Rectangle object. + */ + inflate: function (dx, dy) { + + return Phaser.Rectangle.inflate(this, dx, dy); + + }, + + /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method Phaser.Rectangle#size + * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object. + */ + size: function (output) { + + return Phaser.Rectangle.size(this, output); + + }, + + /** + * Resize the Rectangle by providing a new width and height. + * The x and y positions remain unchanged. + * + * @method Phaser.Rectangle#resize + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method Phaser.Rectangle#clone + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ + clone: function (output) { + + return Phaser.Rectangle.clone(this, output); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method Phaser.Rectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + contains: function (x, y) { + + return Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method Phaser.Rectangle#containsRect + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + containsRect: function (b) { + + return Phaser.Rectangle.containsRect(b, this); + + }, + + /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method Phaser.Rectangle#equals + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + */ + equals: function (b) { + + return Phaser.Rectangle.equals(this, b); + + }, + + /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method Phaser.Rectangle#intersection + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ + intersection: function (b, out) { + + return Phaser.Rectangle.intersection(this, b, out); + + }, + + /** + * Determines whether this Rectangle and another given Rectangle intersect with each other. + * This method checks the x, y, width, and height properties of the two Rectangles. + * + * @method Phaser.Rectangle#intersects + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + */ + intersects: function (b) { + + return Phaser.Rectangle.intersects(this, b); + + }, + + /** + * Determines whether the coordinates given intersects (overlaps) with this Rectangle. + * + * @method Phaser.Rectangle#intersectsRaw + * @param {number} left - The x coordinate of the left of the area. + * @param {number} right - The right coordinate of the area. + * @param {number} top - The y coordinate of the area. + * @param {number} bottom - The bottom coordinate of the area. + * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 + * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + */ + intersectsRaw: function (left, right, top, bottom, tolerance) { + + return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance); + + }, + + /** + * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. + * @method Phaser.Rectangle#union + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ + union: function (b, out) { + + return Phaser.Rectangle.union(this, b, out); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Rectangle. + * + * @method Phaser.Rectangle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = this.randomX; + out.y = this.randomY; + + return out; + + }, + + /** + * Returns a point based on the given position constant, which can be one of: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * This method returns the same values as calling Rectangle.bottomLeft, etc, but those + * calls always create a new Point object, where-as this one allows you to use your own. + * + * @method Phaser.Rectangle#getPoint + * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. + * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the point in its `x` and `y` properties. + */ + getPoint: function (position, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + return out.set(this.x, this.y); + + case Phaser.TOP_CENTER: + return out.set(this.centerX, this.y); + + case Phaser.TOP_RIGHT: + return out.set(this.right, this.y); + + case Phaser.LEFT_CENTER: + return out.set(this.x, this.centerY); + + case Phaser.CENTER: + return out.set(this.centerX, this.centerY); + + case Phaser.RIGHT_CENTER: + return out.set(this.right, this.centerY); + + case Phaser.BOTTOM_LEFT: + return out.set(this.x, this.bottom); + + case Phaser.BOTTOM_CENTER: + return out.set(this.centerX, this.bottom); + + case Phaser.BOTTOM_RIGHT: + return out.set(this.right, this.bottom); + } + + }, + + /** + * Creates or positions four {@link Phaser.Line} lines representing the Rectangle's sides. + * + * @method Phaser.Rectangle#sides + * @param {Phaser.Line} [top] + * @param {Phaser.Line} [right] + * @param {Phaser.Line} [bottom] + * @param {Phaser.Line} [left] + * @return {?Phaser.Line[]} - An array containing four lines (if no arguments were given), or null. + */ + sides: function (top, right, bottom, left) { + + if (!arguments.length) { + top = new Phaser.Line(); + right = new Phaser.Line(); + bottom = new Phaser.Line(); + left = new Phaser.Line(); + } + + var x1 = this.x; + var y1 = this.y; + var x2 = this.right; + var y2 = this.bottom; + + top.setTo(x1, y1, x2, y1); + right.setTo(x2, y1, x2, y2); + bottom.setTo(x1, y2, x2, y2); + left.setTo(x1, y1, x1, y2); + + if (!arguments.length) { + return [top, right, bottom, left]; + } + + return null; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Rectangle#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + + } + +}; + +/** +* @name Phaser.Rectangle#halfWidth +* @property {number} halfWidth - Half of the width of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", { + + get: function () { + return Math.round(this.width / 2); + } + +}); + +/** +* @name Phaser.Rectangle#halfHeight +* @property {number} halfHeight - Half of the height of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", { + + get: function () { + return Math.round(this.height / 2); + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. +* @name Phaser.Rectangle#bottom +* @property {number} bottom - The sum of the y and height properties. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value <= this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + + } + +}); + +/** +* The location of the Rectangles bottom left corner as a Point object. +* @name Phaser.Rectangle#bottomLeft +* @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", { + + get: function () { + return new Phaser.Point(this.x, this.bottom); + }, + + set: function (value) { + this.x = value.x; + this.bottom = value.y; + } + +}); + +/** +* The location of the Rectangles bottom right corner as a Point object. +* @name Phaser.Rectangle#bottomRight +* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", { + + get: function () { + return new Phaser.Point(this.right, this.bottom); + }, + + set: function (value) { + this.right = value.x; + this.bottom = value.y; + } + +}); + +/** +* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. +* @name Phaser.Rectangle#left +* @property {number} left - The x coordinate of the left of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + if (value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + } + +}); + +/** +* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. +* @name Phaser.Rectangle#right +* @property {number} right - The sum of the x and width properties. +*/ +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 = value - this.x; + } + } + +}); + +/** +* The volume of the Rectangle derived from width * height. +* @name Phaser.Rectangle#volume +* @property {number} volume - The volume of the Rectangle derived from width * height. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "volume", { + + get: function () { + return this.width * this.height; + } + +}); + +/** +* The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @name Phaser.Rectangle#perimeter +* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", { + + get: function () { + return (this.width * 2) + (this.height * 2); + } + +}); + +/** +* The x coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerX +* @property {number} centerX - The x coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerX", { + + get: function () { + return this.x + this.halfWidth; + }, + + set: function (value) { + this.x = value - this.halfWidth; + } + +}); + +/** +* The y coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerY +* @property {number} centerY - The y coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerY", { + + get: function () { + return this.y + this.halfHeight; + }, + + set: function (value) { + this.y = value - this.halfHeight; + } + +}); + +/** +* A random value between the left and right values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomX +* @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomX", { + + get: function () { + + return this.x + (Math.random() * this.width); + + } + +}); + +/** +* A random value between the top and bottom values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomY +* @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomY", { + + get: function () { + + return this.y + (Math.random() * this.height); + + } + +}); + +/** +* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. +* However it does affect the height property, whereas changing the y value does not affect the height property. +* @name Phaser.Rectangle#top +* @property {number} top - The y coordinate of the top of the Rectangle. +*/ +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); + } + } + +}); + +/** +* The location of the Rectangles top left corner as a Point object. +* @name Phaser.Rectangle#topLeft +* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. +*/ +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; + } + +}); + +/** +* The location of the Rectangles top right corner as a Point object. +* @name Phaser.Rectangle#topRight +* @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "topRight", { + + get: function () { + return new Phaser.Point(this.x + this.width, this.y); + }, + + set: function (value) { + this.right = value.x; + this.y = value.y; + } + +}); + +/** +* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. +* If set to true then all of the Rectangle properties are set to 0. +* @name Phaser.Rectangle#empty +* @property {boolean} empty - Gets or sets the Rectangles empty state. +*/ +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; + +/** +* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. +* @method Phaser.Rectangle.inflate +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} dx - The amount to be added to the left side of the Rectangle. +* @param {number} dy - The amount to be added to the bottom side of the Rectangle. +* @return {Phaser.Rectangle} This Rectangle object. +*/ +Phaser.Rectangle.inflate = function (a, dx, dy) { + + a.x -= dx; + a.width += 2 * dx; + a.y -= dy; + a.height += 2 * dy; + + return a; + +}; + +/** +* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. +* @method Phaser.Rectangle.inflatePoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. +* @return {Phaser.Rectangle} The Rectangle object. +*/ +Phaser.Rectangle.inflatePoint = function (a, point) { + + return Phaser.Rectangle.inflate(a, point.x, point.y); + +}; + +/** +* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. +* @method Phaser.Rectangle.size +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. +* @return {Phaser.Point} The size of the Rectangle object +*/ +Phaser.Rectangle.size = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(a.width, a.height); + } + else + { + output.setTo(a.width, a.height); + } + + return output; + +}; + +/** +* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. +* @method Phaser.Rectangle.clone +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.clone = function (a, output) { + + if (output === undefined || output === null) + { + 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; + +}; + +/** +* Returns a new Rectangle object with the same values for the left, top, width, and height properties as the original object. +* @method Phaser.Rectangle.createFromBounds +* @param {any} a - An object with `left`, `top`, `width`, and `height` properties. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.createFromBounds = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Rectangle(a.x, a.y, a.width, a.height); + } + + return output.copyFromBounds(a); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by this Rectangle object. +* @method Phaser.Rectangle.contains +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +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); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by the given raw values. +* @method Phaser.Rectangle.containsRaw +* @param {number} rx - The x coordinate of the top left of the area. +* @param {number} ry - The y coordinate of the top left of the area. +* @param {number} rw - The width of the area. +* @param {number} rh - The height of the area. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) { + + return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh)); + +}; + +/** +* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. +* @method Phaser.Rectangle.containsPoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsPoint = function (a, point) { + + return Phaser.Rectangle.contains(a, point.x, point.y); + +}; + +/** +* Determines whether the first Rectangle object is fully contained within the second Rectangle object. +* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. +* @method Phaser.Rectangle.containsRect +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRect = function (a, b) { + + // If the given rect has a larger volume than this one then it can never contain it + if (a.volume > b.volume) + { + return false; + } + + return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom); + +}; + +/** +* Determines whether the two Rectangles are equal. +* This method compares the x, y, width and height properties of each Rectangle. +* @method Phaser.Rectangle.equals +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. +*/ +Phaser.Rectangle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height); + +}; + +/** +* Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. +* @method Phaser.Rectangle.sameDimensions +* @param {Rectangle-like} a - The first Rectangle object. +* @param {Rectangle-like} b - The second Rectangle object. +* @return {boolean} True if the object have equivalent values for the width and height properties. +*/ +Phaser.Rectangle.sameDimensions = function (a, b) { + + return (a.width === b.width && a.height === b.height); + +}; + +/** +* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. +* @method Phaser.Rectangle.intersection +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. +*/ +Phaser.Rectangle.intersection = function (a, b, output) { + + if (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; + +}; + +/** +* Determines whether the two Rectangles intersect with each other. +* This method checks the x, y, width, and height properties of the Rectangles. +* @method Phaser.Rectangle.intersects +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. +*/ +Phaser.Rectangle.intersects = function (a, b) { + + if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) + { + return false; + } + + return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom); + +}; + +/** +* Determines whether the object specified intersects (overlaps) with the given values. +* @method Phaser.Rectangle.intersectsRaw +* @param {number} left - The x coordinate of the left of the area. +* @param {number} right - The right coordinate of the area. +* @param {number} top - The y coordinate of the area. +* @param {number} bottom - The bottom coordinate of the area. +* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 +* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. +*/ +Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) { + + if (tolerance === undefined) { tolerance = 0; } + + return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); + +}; + +/** +* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. +* @method Phaser.Rectangle.union +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. +*/ +Phaser.Rectangle.union = function (a, b, output) { + + if (output === undefined) + { + output = new Phaser.Rectangle(); + } + + return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top)); + +}; + +/** +* Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. +* +* @method Phaser.Rectangle#aabb +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. +* @return {Phaser.Rectangle} The new Rectangle object. +* @static +*/ +Phaser.Rectangle.aabb = function(points, out) { + + if (out === undefined) { + out = new Phaser.Rectangle(); + } + + var xMax = Number.NEGATIVE_INFINITY, + xMin = Number.POSITIVE_INFINITY, + yMax = Number.NEGATIVE_INFINITY, + yMin = Number.POSITIVE_INFINITY; + + points.forEach(function(point) { + if (point.x > xMax) { + xMax = point.x; + } + if (point.x < xMin) { + xMin = point.x; + } + + if (point.y > yMax) { + yMax = point.y; + } + if (point.y < yMin) { + yMin = point.y; + } + }); + + out.setTo(xMin, yMin, xMax - xMin, yMax - yMin); + + return out; +}; + +// Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Rectangle = Phaser.Rectangle; +PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0); + +/** +* @author Mat Groves http://matgroves.com/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Rounded Rectangle object is an area defined by its position and has nice rounded corners, +* as indicated by its top-left corner point (x, y) and by its width and its height. +* +* @class Phaser.RoundedRectangle +* @constructor +* @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle. +* @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle. +* @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value. +* @param {number} [radius=20] - Controls the radius of the rounded corners. +*/ +Phaser.RoundedRectangle = function(x, y, width, height, radius) +{ + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + if (radius === undefined) { radius = 20; } + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} radius - The radius of the rounded corners. + */ + this.radius = radius || 20; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROUNDEDRECTANGLE; +}; + +Phaser.RoundedRectangle.prototype = { + + /** + * Returns a new RoundedRectangle object with the same values for the x, y, width, height and + * radius properties as this RoundedRectangle object. + * + * @method Phaser.RoundedRectangle#clone + * @return {Phaser.RoundedRectangle} + */ + clone: function () { + + return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. + * + * @method Phaser.RoundedRectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. + */ + 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; + + } + +}; + +Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle; + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.RoundedRectangle = Phaser.RoundedRectangle; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. +* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y +* +* @class Phaser.Camera +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera +* @param {number} x - Position of the camera on the X axis +* @param {number} y - Position of the camera on the Y axis +* @param {number} width - The width of the view rectangle +* @param {number} height - The height of the view rectangle +*/ +Phaser.Camera = function (game, id, x, y, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + */ + this.world = game.world; + + /** + * @property {number} id - Reserved for future multiple camera set-ups. + * @default + */ + this.id = 0; + + /** + * Camera view. + * The view into the world we wish to render (by default the game dimensions). + * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. + * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. + * @property {Phaser.Rectangle} view + */ + this.view = new Phaser.Rectangle(x, y, width, height); + + /** + * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. + * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound + * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. + * + * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. + */ + this.bounds = new Phaser.Rectangle(x, y, width, height); + + /** + * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move. + */ + this.deadzone = null; + + /** + * @property {boolean} visible - Whether this camera is visible or not. + * @default + */ + this.visible = true; + + /** + * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. + * @default + */ + this.roundPx = true; + + /** + * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. + */ + this.atLimit = { x: false, y: false }; + + /** + * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. + * @default + */ + this.target = null; + + /** + * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot. + */ + this.displayObject = null; + + /** + * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot. + */ + this.scale = null; + + /** + * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. + * @readonly + */ + this.totalInView = 0; + + /** + * The linear interpolation value to use when following a target. + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * @property {Phaser.Point} lerp + * @default + */ + this.lerp = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes. + */ + this.onShakeComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes. + */ + this.onFlashComplete = new Phaser.Signal(); + + /** + * This signal is dispatched when the camera fade effect completes. + * When the fade effect completes you will be left with the screen black (or whatever + * color you faded to). In order to reset this call `Camera.resetFX`. This is called + * automatically when you change State. + * @property {Phaser.Signal} onFadeComplete + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * The Graphics object used to handle camera fx such as fade and flash. + * @property {Phaser.Graphics} fx + * @protected + */ + this.fx = null; + + /** + * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position. + * @private + */ + this._targetPosition = new Phaser.Point(); + + /** + * @property {number} edge - Edge property. + * @private + * @default + */ + this._edge = 0; + + /** + * @property {Phaser.Point} position - Current position of the camera in world. + * @private + * @default + */ + this._position = new Phaser.Point(); + + /** + * @property {Object} _shake - The shake effect container. + * @private + */ + this._shake = { + intensity: 0, + duration: 0, + horizontal: false, + vertical: false, + shakeBounds: true, + x: 0, + y: 0 + }; + + /** + * @property {number} _fxDuration - FX duration timer. + * @private + */ + this._fxDuration = 0; + + /** + * @property {number} _fxType - The FX type running. + * @private + */ + this._fxType = 0; + + /** + * @property {Phaser.Rectangle} + * @private + */ + this._fixedView = new Phaser.Rectangle(); + +}; + +/** +* A follow style that uses no deadzone. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_LOCKON = 0; + +/** +* A follow style that uses a tall, narrow deadzone (0.33 x 0.125) with a center slightly above the view center. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_PLATFORMER = 1; + +/** +* A follow style that uses a square deadzone (0.25 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN = 2; + +/** +* A follow style that uses a small square deadzone (0.125 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_BOTH = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_HORIZONTAL = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_VERTICAL = 6; + +/** +* @constant +* @type {boolean} +*/ +Phaser.Camera.ENABLE_FX = true; + +Phaser.Camera.prototype = { + + /** + * Called automatically by Phaser.World. + * + * @method Phaser.Camera#boot + * @private + */ + boot: function () { + + this.displayObject = this.game.world; + + this.scale = this.game.world.scale; + + this.game.camera = this; + + if (Phaser.Graphics && Phaser.Camera.ENABLE_FX) + { + this.fx = new Phaser.Graphics(this.game); + + this.game.stage.addChild(this.fx); + } + + }, + + /** + * Camera preUpdate. Sets the total view counter to zero. + * + * @method Phaser.Camera#preUpdate + */ + preUpdate: function () { + + this.totalInView = 0; + + }, + + /** + * Tell the camera which sprite to follow. + * + * You can set the follow type and a linear interpolation value. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. + * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. + * + * @method Phaser.Camera#follow + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything. + * @param {number} [style] - Leverage one of the existing {@link deadzone} presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + */ + follow: function (target, style, lerpX, lerpY) { + + if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; } + if (lerpX === undefined) { lerpX = 1; } + if (lerpY === undefined) { lerpY = 1; } + + this.target = target; + this.lerp.set(lerpX, lerpY); + + var helper; + + switch (style) { + + case Phaser.Camera.FOLLOW_PLATFORMER: + var w = this.width / 8; + var h = this.height / 3; + this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN: + helper = Math.max(this.width, this.height) / 4; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT: + helper = Math.max(this.width, this.height) / 8; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_LOCKON: + this.deadzone = null; + break; + + default: + this.deadzone = null; + break; + } + + }, + + /** + * Sets the Camera follow target to null, stopping it from following an object if it's doing so. + * + * @method Phaser.Camera#unfollow + */ + unfollow: function () { + + this.target = null; + + }, + + /** + * Move the camera focus on a display object instantly. + * @method Phaser.Camera#focusOn + * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. + */ + focusOn: function (displayObject) { + + this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight)); + + }, + + /** + * Move the camera focus on a location instantly. + * @method Phaser.Camera#focusOnXY + * @param {number} x - X position. + * @param {number} y - Y position. + */ + focusOnXY: function (x, y) { + + this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight)); + + }, + + /** + * This creates a camera shake effect. It works by applying a random amount of additional + * spacing on the x and y axis each frame. You can control the intensity and duration + * of the effect, and if it should effect both axis or just one. + * + * When the shake effect ends the signal Camera.onShakeComplete is dispatched. + * + * @method Phaser.Camera#shake + * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. + * @param {number} [duration=500] - The duration of the shake effect in milliseconds. + * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL. + * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?). + * @return {boolean} True if the shake effect was started, otherwise false. + */ + shake: function (intensity, duration, force, direction, shakeBounds) { + + if (intensity === undefined) { intensity = 0.05; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = true; } + if (direction === undefined) { direction = Phaser.Camera.SHAKE_BOTH; } + if (shakeBounds === undefined) { shakeBounds = true; } + + if (!force && this._shake.duration > 0) + { + // Can't reset an already running shake + return false; + } + + this._shake.intensity = intensity; + this._shake.duration = duration; + this._shake.shakeBounds = shakeBounds; + + this._shake.x = 0; + this._shake.y = 0; + + this._shake.horizontal = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_HORIZONTAL); + this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL); + + return true; + + }, + + /** + * This creates a camera flash effect. It works by filling the game with the solid fill + * color specified, and then fading it away to alpha 0 over the duration given. + * + * You can use this for things such as hit feedback effects. + * + * When the effect ends the signal Camera.onFlashComplete is dispatched. + * + * @method Phaser.Camera#flash + * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the flash effect in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the flash effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + flash: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0xffffff; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 1; + + this._fxDuration = duration; + this._fxType = 0; + + return true; + + }, + + /** + * This creates a camera fade effect. It works by filling the game with the + * color specified, over the duration given, ending with a solid fill. + * + * You can use this for things such as transitioning to a new scene. + * + * The game will be left 'filled' at the end of this effect, likely obscuring + * everything. In order to reset it you can call `Camera.resetFX` and it will clear the + * fade. Or you can call `Camera.flash` with the same color as the fade, and it will + * reverse the process, bringing the game back into view again. + * + * When the effect ends the signal Camera.onFadeComplete is dispatched. + * + * @method Phaser.Camera#fade + * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the fade in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the fade effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + fade: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0x000000; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 0; + + this._fxDuration = duration; + this._fxType = 1; + + return true; + + }, + + /** + * The camera update loop. This is called automatically by the core game loop. + * + * @method Phaser.Camera#update + * @protected + */ + update: function () { + + if (this._fxDuration > 0) + { + this.updateFX(); + } + + if (this._shake.duration > 0) + { + this.updateShake(); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + this._shake.x = Math.floor(this._shake.x); + this._shake.y = Math.floor(this._shake.y); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the camera flash and fade effects. + * + * @method Phaser.Camera#updateFX + * @private + */ + updateFX: function () { + + if (this._fxType === 0) + { + // flash + this.fx.alpha -= this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha <= 0) + { + this._fxDuration = 0; + this.fx.alpha = 0; + this.onFlashComplete.dispatch(); + } + } + else + { + // fade + this.fx.alpha += this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha >= 1) + { + this._fxDuration = 0; + this.fx.alpha = 1; + this.onFadeComplete.dispatch(); + } + } + + }, + + /** + * Update the camera shake effect. + * + * @method Phaser.Camera#updateShake + * @private + */ + updateShake: function () { + + this._shake.duration -= this.game.time.elapsedMS; + + if (this._shake.duration <= 0) + { + this.onShakeComplete.dispatch(); + this._shake.x = 0; + this._shake.y = 0; + } + else + { + if (this._shake.horizontal) + { + this._shake.x = this.game.rnd.frac() * this._shake.intensity * this.view.width * 2 - this._shake.intensity * this.view.width; + } + + if (this._shake.vertical) + { + this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height; + } + } + + }, + + /** + * Internal method that handles tracking a sprite. + * + * @method Phaser.Camera#updateTarget + * @private + */ + updateTarget: function () { + + this._targetPosition.x = this.view.x + this.target.worldPosition.x; + this._targetPosition.y = this.view.y + this.target.worldPosition.y; + + if (this.deadzone) + { + this._edge = this._targetPosition.x - this.view.x; + + if (this._edge < this.deadzone.left) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.left, this.lerp.x); + } + else if (this._edge > this.deadzone.right) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.right, this.lerp.x); + } + + this._edge = this._targetPosition.y - this.view.y; + + if (this._edge < this.deadzone.top) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.top, this.lerp.y); + } + else if (this._edge > this.deadzone.bottom) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.bottom, this.lerp.y); + } + } + else + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.view.halfWidth, this.lerp.x); + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.view.halfHeight, this.lerp.y); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the Camera bounds to match the game world. + * + * @method Phaser.Camera#setBoundsToWorld + */ + setBoundsToWorld: function () { + + if (this.bounds) + { + this.bounds.copyFrom(this.game.world.bounds); + } + + }, + + /** + * Method called to ensure the camera doesn't venture outside of the game world. + * Called automatically by Camera.update. + * + * @method Phaser.Camera#checkBounds + * @protected + */ + checkBounds: function () { + + this.atLimit.x = false; + this.atLimit.y = false; + + var vx = this.view.x + this._shake.x; + var vw = this.view.right + this._shake.x; + var vy = this.view.y + this._shake.y; + var vh = this.view.bottom + this._shake.y; + + // Make sure we didn't go outside the cameras bounds + if (vx <= this.bounds.x * this.scale.x) + { + this.atLimit.x = true; + this.view.x = this.bounds.x * this.scale.x; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + else if (vw >= this.bounds.right * this.scale.x) + { + this.atLimit.x = true; + this.view.x = (this.bounds.right * this.scale.x) - this.width; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + + if (vy <= this.bounds.top * this.scale.y) + { + this.atLimit.y = true; + this.view.y = this.bounds.top * this.scale.y; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + else if (vh >= this.bounds.bottom * this.scale.y) + { + this.atLimit.y = true; + this.view.y = (this.bounds.bottom * this.scale.y) - this.height; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + + }, + + /** + * A helper function to set both the X and Y properties of the camera at once + * without having to use game.camera.x and game.camera.y. + * + * @method Phaser.Camera#setPosition + * @param {number} x - X position. + * @param {number} y - Y position. + */ + setPosition: function (x, y) { + + this.view.x = x; + this.view.y = y; + + if (this.bounds) + { + this.checkBounds(); + } + + }, + + /** + * Sets the size of the view rectangle given the width and height in parameters. + * + * @method Phaser.Camera#setSize + * @param {number} width - The desired width. + * @param {number} height - The desired height. + */ + setSize: function (width, height) { + + this.view.width = width; + this.view.height = height; + + }, + + /** + * Resets the camera back to 0,0 and un-follows any object it may have been tracking. + * Also immediately resets any camera effects that may have been running such as + * shake, flash or fade. + * + * @method Phaser.Camera#reset + */ + reset: function () { + + this.target = null; + + this.view.x = 0; + this.view.y = 0; + + this._shake.duration = 0; + this._shake.x = 0; + this._shake.y = 0; + + this.resetFX(); + + }, + + /** + * Resets any active FX, such as a fade or flash and immediately clears it. + * Useful to calling after a fade in order to remove the fade from the Stage. + * + * @method Phaser.Camera#resetFX + */ + resetFX: function () { + + if (this.fx) + { + this.fx.clear(); + this.fx.alpha = 0; + } + + this._fxDuration = 0; + + } + +}; + +Phaser.Camera.prototype.constructor = Phaser.Camera; + +/** +* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#x +* @property {number} x - Gets or sets the cameras x position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "x", { + + get: function () { + + return this.view.x; + + }, + + set: function (value) { + + this.view.x = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#y +* @property {number} y - Gets or sets the cameras y position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "y", { + + get: function () { + + return this.view.y; + + }, + + set: function (value) { + + this.view.y = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras position. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#position +* @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object. +*/ +Object.defineProperty(Phaser.Camera.prototype, "position", { + + get: function () { + + this._position.set(this.view.x, this.view.y); + + return this._position; + + }, + + set: function (value) { + + if (typeof value.x !== "undefined") { this.view.x = value.x; } + if (typeof value.y !== "undefined") { this.view.y = value.y; } + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras width. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#width +* @property {number} width - Gets or sets the cameras width. +*/ +Object.defineProperty(Phaser.Camera.prototype, "width", { + + get: function () { + + return this.view.width; + + }, + + set: function (value) { + + this.view.width = value; + + } + +}); + +/** +* The Cameras height. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#height +* @property {number} height - Gets or sets the cameras height. +*/ +Object.defineProperty(Phaser.Camera.prototype, "height", { + + get: function () { + + return this.view.height; + + }, + + set: function (value) { + + this.view.height = value; + + } + +}); + + +/** +* The Cameras shake intensity. +* @name Phaser.Camera#shakeIntensity +* @property {number} shakeIntensity - Gets or sets the cameras shake intensity. +*/ +Object.defineProperty(Phaser.Camera.prototype, "shakeIntensity", { + + get: function () { + + return this._shake.intensity; + + }, + + set: function (value) { + + this._shake.intensity = value; + + } + +}); + + +/** + * Immobile {@link #view} rectangle. Its top-left is always (0, 0). You can use this align fixedToCamera objects. + * @name Phaser.Camera#fixedView + * @property {Phaser.Rectangle} fixedView + * @readonly + */ +Object.defineProperty(Phaser.Camera.prototype, "fixedView", { + + get: function () { + + this._fixedView.setTo(0, 0, this.view.width, this.view.height); + + return this._fixedView; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base State class which can be extended if you are creating your own game. +* It provides quick access to common functions such as the camera, cache, input, match, sound and more. +* +* #### Callbacks +* +* | start | preload | loaded | paused | stop | +* |-------|-------------|------------|--------------|----------| +* | init | | | | | +* | | preload | create | paused | | +* | | loadUpdate* | update* | pauseUpdate* | | +* | | | preRender* | | | +* | | loadRender* | render* | render* | | +* | | | | resumed | | +* | | | | | shutdown | +* +* Update and render calls (*) are repeated. +* +* If your State has a constructor, it will be invoked exactly once, during {@link {@link Phaser.StateManager#add}. +* +* @class Phaser.State +* @constructor +*/ +Phaser.State = function () { + + /** + * @property {Phaser.Game} game - This is a reference to the currently running Game. + */ + this.game = null; + + /** + * @property {string} key - The string based identifier given to the State when added into the State Manager. + */ + this.key = ''; + + /** + * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects. + */ + this.make = null; + + /** + * @property {Phaser.Camera} camera - A handy reference to World.camera. + */ + this.camera = null; + + /** + * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - A reference to the Input Manager. + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions. + */ + this.math = null; + + /** + * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. + */ + this.sound = null; + + /** + * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays. + */ + this.scale = null; + + /** + * @property {Phaser.Stage} stage - A reference to the Stage. + */ + this.stage = null; + + /** + * @property {Phaser.StateManager} stage - A reference to the State Manager, which controls state changes. + */ + this.state = null; + + /** + * @property {Phaser.Time} time - A reference to the game clock and timed events system. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - A reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. + */ + this.world = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. + */ + this.particles = null; + + /** + * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser. + */ + this.physics = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator. + */ + this.rnd = null; + +}; + +Phaser.State.prototype = { + + /** + * init is the very first function called when your State starts up. It's called before preload, create or anything else. + * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables + * or objects before the preloading starts. + * + * @method Phaser.State#init + * @param {...any} args - Any extra arguments passed to {@link Phaser.StateManager#start} or {@link Phaser.StateManager#restart}. + */ + init: function () { + }, + + /** + * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) + * You shouldn't create any objects in this method that require assets that you're also loading in this method, as + * they won't yet be available. + * + * @method Phaser.State#preload + * @param {Phaser.Game} game + */ + preload: function () { + }, + + /** + * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * + * @method Phaser.State#loadUpdate + * @param {Phaser.Game} game + */ + loadUpdate: function () { + }, + + /** + * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. + * + * @method Phaser.State#loadRender + * @param {Phaser.Game} game + */ + loadRender: function () { + }, + + /** + * create is called once preload has completed, this includes the loading of any assets from the Loader. + * If you don't have a preload method then create is the first method called in your State. + * + * @method Phaser.State#create + * @param {Phaser.Game} game + */ + create: function () { + }, + + /** + * The update method is left empty for your own use. + * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. + * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. + * + * @method Phaser.State#update + * @param {Phaser.Game} game + */ + update: function () { + }, + + /** + * The preRender method is called after all Game Objects have been updated, but before any rendering takes place. + * + * @method Phaser.State#preRender + * @param {Phaser.Game} game + * @param {number} elapsedTime + */ + preRender: function () { + }, + + /** + * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. + * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any + * final post-processing style effects here. Note that this happens before plugins postRender takes place. + * + * @method Phaser.State#render + * @param {Phaser.Game} game + */ + render: function () { + }, + + /** + * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. + * + * @method Phaser.State#resize + * @param {number} width + * @param {number} height + */ + resize: function () { + }, + + /** + * This method will be called if the core game loop is paused. + * + * @method Phaser.State#paused + * @param {Phaser.Game} game + */ + paused: function () { + }, + + /** + * This method will be called when the core game loop resumes from a paused state. + * + * @method Phaser.State#resumed + * @param {Phaser.Game} game + */ + resumed: function () { + }, + + /** + * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. + * + * @method Phaser.State#pauseUpdate + * @param {Phaser.Game} game + */ + pauseUpdate: function () { + }, + + /** + * This method will be called when the State is shutdown (i.e. you switch to another state from this one). + * + * @method Phaser.State#shutdown + * @param {Phaser.Game} game + */ + shutdown: function () { + } + +}; + +Phaser.State.prototype.constructor = Phaser.State; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The State Manager is responsible for loading, setting up and switching game states. +* +* @class Phaser.StateManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. +*/ +Phaser.StateManager = function (game, pendingState) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {object} states - The object containing Phaser.States. + */ + this.states = {}; + + /** + * @property {Phaser.State} _pendingState - The state to be switched to in the next frame. + * @private + */ + this._pendingState = null; + + if (typeof pendingState !== 'undefined' && pendingState !== null) + { + this._pendingState = pendingState; + } + + /** + * @property {boolean} _clearWorld - Clear the world when we switch state? + * @private + */ + this._clearWorld = false; + + /** + * @property {boolean} _clearCache - Clear the cache when we switch state? + * @private + */ + this._clearCache = false; + + /** + * @property {boolean} _created - Flag that sets if the State has been created or not. + * @private + */ + this._created = false; + + /** + * @property {any[]} _args - Temporary container when you pass vars from one State to another. + * @private + */ + this._args = []; + + /** + * @property {string} current - The current active State object. + * @default + */ + this.current = ''; + + /** + * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. + * + * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start + * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states + * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. + * + * The callback you specify is sent two parameters: the string based key of the new state, + * and the second parameter is the string based key of the old / previous state. + * + * @property {Phaser.Signal} onStateChange + */ + this.onStateChange = new Phaser.Signal(); + + /** + * @property {function} onInitCallback - This is called when the state is set as the active state. + * @default + */ + this.onInitCallback = null; + + /** + * @property {function} onPreloadCallback - This is called when the state starts to load assets. + * @default + */ + this.onPreloadCallback = null; + + /** + * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins. + * @default + */ + this.onCreateCallback = null; + + /** + * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). + * @default + */ + this.onUpdateCallback = null; + + /** + * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). + * @default + */ + this.onRenderCallback = null; + + /** + * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. + * @default + */ + this.onResizeCallback = null; + + /** + * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. + * @default + */ + this.onPreRenderCallback = null; + + /** + * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase. + * @default + */ + this.onLoadUpdateCallback = null; + + /** + * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase. + * @default + */ + this.onLoadRenderCallback = null; + + /** + * @property {function} onPausedCallback - This is called when the game is paused. + * @default + */ + this.onPausedCallback = null; + + /** + * @property {function} onResumedCallback - This is called when the game is resumed from a paused state. + * @default + */ + this.onResumedCallback = null; + + /** + * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused. + * @default + */ + this.onPauseUpdateCallback = null; + + /** + * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state). + * @default + */ + this.onShutDownCallback = null; + +}; + +Phaser.StateManager.prototype = { + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * @method Phaser.StateManager#boot + * @private + */ + boot: function () { + + this.game.onPause.add(this.pause, this); + this.game.onResume.add(this.resume, this); + + if (this._pendingState !== null && typeof this._pendingState !== 'string') + { + this.add('default', this._pendingState, true); + } + + }, + + /** + * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. + * + * The State can be any of + * + * - a plain JavaScript object containing at least one required callback (see {@link #checkState}) + * - an instance of {@link Phaser.State} + * - an instance of a class extending Phaser.State + * - a constructor function (class) + * + * If a function is given a new state object will be created by calling it, passing the current {@link Phaser.Game game} as the first argument. + * + * @method Phaser.StateManager#add + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + * @param {Phaser.State|object|function} state - The state you want to switch to. + * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it. + */ + add: function (key, state, autoStart) { + + if (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; + + }, + + /** + * Delete the given state. + * @method Phaser.StateManager#remove + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + */ + 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.onPreRenderCallback = null; + this.onRenderCallback = null; + this.onResizeCallback = null; + this.onPausedCallback = null; + this.onResumedCallback = null; + this.onPauseUpdateCallback = null; + } + + delete this.states[key]; + + }, + + /** + * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. + * + * @method Phaser.StateManager#start + * @param {string} key - The key of the state you want to start. + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one). + */ + start: function (key, clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + if (this.checkState(key)) + { + // Place the state in the queue. It will be started the next time the game loop begins. + this._pendingState = key; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 3) + { + this._args = Array.prototype.splice.call(arguments, 3); + } + } + + }, + + /** + * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. + * + * @method Phaser.StateManager#restart + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one. + */ + restart: function (clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + // Place the state in the queue. It will be started the next time the game loop starts. + this._pendingState = this.current; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 2) + { + this._args = Array.prototype.slice.call(arguments, 2); + } + + }, + + /** + * Used by onInit and onShutdown when those functions don't exist on the state + * @method Phaser.StateManager#dummy + * @private + */ + dummy: function () { + }, + + /** + * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. + * + * @method Phaser.StateManager#preUpdate + */ + preUpdate: function () { + + if (this._pendingState && this.game.isBooted) + { + var previousStateKey = this.current; + + // Already got a state running? + this.clearCurrentState(); + + this.setCurrentState(this._pendingState); + + this.onStateChange.dispatch(this.current, previousStateKey); + + if (this.current !== this._pendingState) + { + return; + } + else + { + this._pendingState = null; + } + + // If StateManager.start has been called from the init of a State that ALSO has a preload, then + // onPreloadCallback will be set, but must be ignored + if (this.onPreloadCallback) + { + this.game.load.reset(true); + this.onPreloadCallback.call(this.callbackContext, this.game); + + // Is the loader empty? + if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0) + { + this.loadComplete(); + } + else + { + // Start the loader going as we have something in the queue + this.game.load.start(); + } + } + else + { + // No init? Then there was nothing to load either + this.loadComplete(); + } + } + + }, + + /** + * This method clears the current State, calling its shutdown callback. The process also removes any active tweens, + * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. + * + * @method Phaser.StateManager#clearCurrentState + */ + clearCurrentState: function () { + + if (this.current) + { + if (this.onShutDownCallback) + { + 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(); + + this.game.scale.reset(this._clearWorld); + + if (this.game.debug) + { + this.game.debug.reset(); + } + + if (this._clearWorld) + { + this.game.world.shutdown(); + + if (this._clearCache) + { + this.game.cache.destroy(); + } + } + } + + }, + + /** + * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. + * + * @method Phaser.StateManager#checkState + * @param {string} key - The key of the state you want to check. + * @return {boolean} true if the State has the required functions, otherwise false. + */ + checkState: function (key) { + + var state = this.states[key]; + + if (state) + { + if (state.preload || state.create || state.update || state.render) + { + return true; + } + else + { + console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"); + return false; + } + } + else + { + console.warn("Phaser.StateManager - No state found with the key: " + key); + return false; + } + + }, + + /** + * Links game properties to the State given by the key. + * + * @method Phaser.StateManager#link + * @param {string} key - State key. + * @protected + */ + link: function (key) { + + var state = this.states[key]; + + state.game = this.game; + state.add = this.game.add; + state.make = this.game.make; + state.camera = this.game.camera; + state.cache = this.game.cache; + state.input = this.game.input; + state.load = this.game.load; + state.math = this.game.math; + state.sound = this.game.sound; + state.scale = this.game.scale; + state.state = this; + state.stage = this.game.stage; + state.time = this.game.time; + state.tweens = this.game.tweens; + state.world = this.game.world; + state.particles = this.game.particles; + state.rnd = this.game.rnd; + state.physics = this.game.physics; + state.key = key; + + }, + + /** + * Nulls all State level Phaser properties, including a reference to Game. + * + * @method Phaser.StateManager#unlink + * @param {string} key - State key. + * @protected + */ + unlink: function (key) { + + var state = this.states[key]; + + if (state) + { + state.game = null; + state.add = null; + state.make = null; + state.camera = null; + state.cache = null; + state.input = null; + state.load = null; + state.math = null; + state.sound = null; + state.scale = null; + state.state = null; + state.stage = null; + state.time = null; + state.tweens = null; + state.world = null; + state.particles = null; + state.rnd = null; + state.physics = null; + } + + }, + + /** + * Sets the current State. Should not be called directly (use StateManager.start) + * + * @method Phaser.StateManager#setCurrentState + * @param {string} key - State key. + * @private + */ + setCurrentState: function (key) { + + var state = this.states[key]; + + this.callbackContext = state; + + this.link(key); + + // Used when the state is set as being the current active state + this.onInitCallback = state['init'] || this.dummy; + + this.onPreloadCallback = state['preload'] || null; + this.onLoadRenderCallback = state['loadRender'] || null; + this.onLoadUpdateCallback = state['loadUpdate'] || null; + this.onCreateCallback = state['create'] || null; + this.onUpdateCallback = state['update'] || null; + this.onPreRenderCallback = state['preRender'] || null; + this.onRenderCallback = state['render'] || null; + this.onResizeCallback = state['resize'] || null; + this.onPausedCallback = state['paused'] || null; + this.onResumedCallback = state['resumed'] || null; + this.onPauseUpdateCallback = state['pauseUpdate'] || null; + + // Used when the state is no longer the current active state + this.onShutDownCallback = state['shutdown'] || this.dummy; + + // Reset the physics system, but not on the first state start + if (this.current !== '') + { + this.game.physics.reset(); + } + + this.current = key; + this._created = false; + + // At this point key and pendingState should equal each other + this.onInitCallback.apply(this.callbackContext, this._args); + + // If they no longer do then the init callback hit StateManager.start + if (key === this._pendingState) + { + this._args = []; + } + + this.game._kickstart = true; + + }, + + /** + * Gets the current State. + * + * @method Phaser.StateManager#getCurrentState + * @return {Phaser.State} + * @public + */ + getCurrentState: function() { + return this.states[this.current]; + }, + + /** + * @method Phaser.StateManager#loadComplete + * @protected + */ + loadComplete: function () { + + // Make sure to do load-update one last time before state is set to _created + if (this._created === false && this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + + if (this._created === false && this.onCreateCallback) + { + this._created = true; + this.onCreateCallback.call(this.callbackContext, this.game); + } + else + { + this._created = true; + } + + }, + + /** + * @method Phaser.StateManager#pause + * @protected + */ + pause: function () { + + if (this._created && this.onPausedCallback) + { + this.onPausedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#resume + * @protected + */ + resume: function () { + + if (this._created && this.onResumedCallback) + { + this.onResumedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#update + * @protected + */ + update: function () { + + if (this._created) + { + if (this.onUpdateCallback) + { + this.onUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#pauseUpdate + * @protected + */ + pauseUpdate: function () { + + if (this._created) + { + if (this.onPauseUpdateCallback) + { + this.onPauseUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#preRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + preRender: function (elapsedTime) { + + if (this._created && this.onPreRenderCallback) + { + this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime); + } + + }, + + /** + * @method Phaser.StateManager#resize + * @protected + */ + resize: function (width, height) { + + if (this.onResizeCallback) + { + this.onResizeCallback.call(this.callbackContext, width, height); + } + + }, + + /** + * @method Phaser.StateManager#render + * @protected + */ + render: function () { + + if (this._created) + { + if (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); + this.game.context.restore(); + } + else + { + this.onRenderCallback.call(this.callbackContext, this.game); + } + } + } + else + { + if (this.onLoadRenderCallback) + { + this.onLoadRenderCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. + * You don't recover from this without rebuilding the Phaser instance again. + * @method Phaser.StateManager#destroy + */ + destroy: function () { + + this._clearWorld = true; + this._clearCache = true; + + this.clearCurrentState(); + + 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; + this.current = ''; + + } + +}; + +Phaser.StateManager.prototype.constructor = Phaser.StateManager; + +/** +* @name Phaser.StateManager#created +* @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default). +* @readOnly +*/ +Object.defineProperty(Phaser.StateManager.prototype, "created", { + + get: function () { + + return this._created; + + } + +}); + +/** +* "It's like nailing jelly to a kitten" - Gary Penn +*/ + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Signals are what Phaser uses to handle events and event dispatching. +* You can listen for a Signal by binding a callback / function to it. +* This is done by using either `Signal.add` or `Signal.addOnce`. +* +* For example you can listen for a touch or click event from the Input Manager +* by using its `onDown` Signal: +* +* `game.input.onDown.add(function() { ... });` +* +* Rather than inline your function, you can pass a reference: +* +* `game.input.onDown.add(clicked, this);` +* `function clicked () { ... }` +* +* In this case the second argument (`this`) is the context in which your function should be called. +* +* Now every time the InputManager dispatches the `onDown` signal (or event), your function +* will be called. +* +* Multiple callbacks can be bound to the same signal. +* They're ordered first by their `priority` arguments and then by the order in which they were added. +* If a callback calls {@link #halt} or returns `false`, any remaining callbacks are skipped. +* +* Very often a Signal will send arguments to your function. +* This is specific to the Signal itself. +* If you're unsure then check the documentation, or failing that simply do: +* +* `Signal.add(function() { console.log(arguments); })` +* +* and it will log all of the arguments your function received from the Signal. +* +* Sprites have lots of default signals you can listen to in their Events class, such as: +* +* `sprite.events.onKilled` +* +* Which is called automatically whenever the Sprite is killed. +* There are lots of other events, see the Events component for a list. +* +* As well as listening to pre-defined Signals you can also create your own: +* +* `var mySignal = new Phaser.Signal();` +* +* This creates a new Signal. You can bind a callback to it: +* +* `mySignal.add(myCallback, this);` +* +* and then finally when ready you can dispatch the Signal: +* +* `mySignal.dispatch(your arguments);` +* +* And your callback will be invoked. See the dispatch method for more details. +* +* @class Phaser.Signal +* @constructor +*/ +Phaser.Signal = function () {}; + +Phaser.Signal.prototype = { + + /** + * @property {?Array.} _bindings - Internal variable. + * @private + */ + _bindings: null, + + /** + * @property {any} _prevParams - Internal variable. + * @private + */ + _prevParams: null, + + /** + * Memorize the previously dispatched event? + * + * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}. + * Use {@link #forget} to clear any currently memorized event. + * + * @property {boolean} memorize + */ + memorize: false, + + /** + * @property {boolean} _shouldPropagate + * @private + */ + _shouldPropagate: true, + + /** + * Is the Signal active? Only active signals will broadcast dispatched events. + * + * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}. + * + * @property {boolean} active + * @default + */ + active: true, + + /** + * @property {function} _boundDispatch - The bound dispatch function, if any. + * @private + */ + _boundDispatch: false, + + /** + * @method Phaser.Signal#validateListener + * @param {function} listener - Signal handler function. + * @param {string} fnName - Function name. + * @private + */ + validateListener: function (listener, fnName) { + + if (typeof listener !== 'function') + { + throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); + } + + }, + + /** + * @method Phaser.Signal#_registerListener + * @private + * @param {function} listener - Signal handler function. + * @param {boolean} isOnce - Should the listener only be called once? + * @param {object} [listenerContext] - The context under which the listener is invoked. + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + _registerListener: function (listener, isOnce, listenerContext, priority, args) { + + var prevIndex = this._indexOfListener(listener, listenerContext); + var binding; + + if (prevIndex !== -1) + { + binding = this._bindings[prevIndex]; + + if (binding.isOnce() !== isOnce) + { + throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); + } + } + else + { + binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args); + this._addBinding(binding); + } + + if (this.memorize && this._prevParams) + { + binding.execute(this._prevParams); + } + + return binding; + + }, + + /** + * @method Phaser.Signal#_addBinding + * @private + * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. + */ + _addBinding: function (binding) { + + if (!this._bindings) + { + this._bindings = []; + } + + // Simplified insertion sort + var n = this._bindings.length; + + do { + n--; + } + while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); + + this._bindings.splice(n + 1, 0, binding); + + }, + + /** + * @method Phaser.Signal#_indexOfListener + * @private + * @param {function} listener - Signal handler function. + * @param {object} [context=null] - Signal handler function. + * @return {number} The index of the listener within the private bindings array. + */ + _indexOfListener: function (listener, context) { + + if (!this._bindings) + { + return -1; + } + + if (context === undefined) { context = null; } + + var n = this._bindings.length; + var cur; + + while (n--) + { + cur = this._bindings[n]; + + if (cur._listener === listener && cur.context === context) + { + return n; + } + } + + return -1; + + }, + + /** + * Check if a specific listener is attached. + * + * @method Phaser.Signal#has + * @param {function} listener - Signal handler function. + * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @return {boolean} If Signal has the specified listener. + */ + has: function (listener, context) { + + return this._indexOfListener(listener, context) !== -1; + + }, + + /** + * Add an event listener for this signal. + * + * An event listener is a callback with a related context and priority. + * + * You can optionally provide extra arguments which will be passed to the callback after any internal parameters. + * + * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. + * Any arguments you've specified after `priority` will be sent as well: + * + * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` + * + * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. + * + * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', + * and the value 100 were the custom arguments given in the call to 'add'. + * + * If the callback calls {@link #halt} or returns `false`, any remaining callbacks bound to this Signal are skipped. + * + * @method Phaser.Signal#add + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + add: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'add'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, false, listenerContext, priority, args); + + }, + + /** + * Add a one-time listener - the listener is automatically removed after the first execution. + * + * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and + * the listener will be removed immediately. + * + * @method Phaser.Signal#addOnce + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + addOnce: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'addOnce'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, true, listenerContext, priority, args); + + }, + + /** + * Remove a single event listener. + * + * @method Phaser.Signal#remove + * @param {function} listener - Handler function that should be removed. + * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {function} Listener handler function. + */ + remove: function (listener, context) { + + this.validateListener(listener, 'remove'); + + var i = this._indexOfListener(listener, context); + + if (i !== -1) + { + this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal + this._bindings.splice(i, 1); + } + + return listener; + + }, + + /** + * Remove all event listeners. + * + * @method Phaser.Signal#removeAll + * @param {object} [context=null] - If specified only listeners for the given context will be removed. + */ + removeAll: function (context) { + + if (context === undefined) { context = null; } + + if (!this._bindings) + { + return; + } + + var n = this._bindings.length; + + while (n--) + { + if (context) + { + if (this._bindings[n].context === context) + { + this._bindings[n]._destroy(); + this._bindings.splice(n, 1); + } + } + else + { + this._bindings[n]._destroy(); + } + } + + if (!context) + { + this._bindings.length = 0; + } + + }, + + /** + * Gets the total number of listeners attached to this Signal. + * + * @method Phaser.Signal#getNumListeners + * @return {integer} Number of listeners attached to the Signal. + */ + getNumListeners: function () { + + return this._bindings ? this._bindings.length : 0; + + }, + + /** + * Stop propagation of the event, blocking the dispatch to next listener on the queue. + * + * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. + * See {@link #active} to enable/disable the signal entirely. + * + * @method Phaser.Signal#halt + */ + halt: function () { + + this._shouldPropagate = false; + + }, + + /** + * Dispatch / broadcast the event to all listeners. + * + * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}. + * + * @method Phaser.Signal#dispatch + * @param {any} [params] - Parameters that should be passed to each handler. + */ + dispatch: function () { + + if (!this.active || !this._bindings) + { + return; + } + + var paramsArr = Array.prototype.slice.call(arguments); + var n = this._bindings.length; + var bindings; + + if (this.memorize) + { + this._prevParams = paramsArr; + } + + if (!n) + { + // Should come after memorize + return; + } + + bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch + this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. + + //execute all callbacks until end of the list or until a callback returns `false` or stops propagation + //reverse loop since listeners with higher priority will be added at the end of the list + do { + n--; + } + while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); + + }, + + /** + * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any. + * + * @method Phaser.Signal#forget + */ + forget: function() { + + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * Dispose the signal - no more events can be dispatched. + * + * This removes all event listeners and clears references to external objects. + * Calling methods on a disposed objects results in undefined behavior. + * + * @method Phaser.Signal#dispose + */ + dispose: function () { + + this.removeAll(); + + this._bindings = null; + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * A string representation of the object. + * + * @method Phaser.Signal#toString + * @return {string} String representation of the object. + */ + toString: function () { + + return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']'; + + } + +}; + +/** +* Create a `dispatch` function that maintains a binding to the original Signal context. +* +* Use the resulting value if the dispatch function needs to be passed somewhere +* or called independently of the Signal object. +* +* @memberof Phaser.Signal +* @property {function} boundDispatch +*/ +Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", { + + get: function () { + var _this = this; + return this._boundDispatch || (this._boundDispatch = function () { + return _this.dispatch.apply(_this, arguments); + }); + } + +}); + +Phaser.Signal.prototype.constructor = Phaser.Signal; + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Object that represents a binding between a Signal and a listener function. +* This is an internal constructor and shouldn't be created directly. +* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. +* +* @class Phaser.SignalBinding +* @constructor +* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to. +* @param {function} listener - Handler function bound to the signal. +* @param {boolean} isOnce - If binding should be executed just once. +* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). +* @param {number} [priority] - The priority level of the event listener. (default = 0). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. +*/ +Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) { + + /** + * @property {Phaser.Game} _listener - Handler function bound to the signal. + * @private + */ + this._listener = listener; + + if (isOnce) + { + this._isOnce = true; + } + + if (listenerContext != null) /* not null/undefined */ + { + this.context = listenerContext; + } + + /** + * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to. + * @private + */ + this._signal = signal; + + if (priority) + { + this._priority = priority; + } + + if (args && args.length) + { + this._args = args; + } + +}; + +Phaser.SignalBinding.prototype = { + + /** + * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + */ + context: null, + + /** + * @property {boolean} _isOnce - If binding should be executed just once. + * @private + */ + _isOnce: false, + + /** + * @property {number} _priority - Listener priority. + * @private + */ + _priority: 0, + + /** + * @property {array} _args - Listener arguments. + * @private + */ + _args: null, + + /** + * @property {number} callCount - The number of times the handler function has been called. + */ + callCount: 0, + + /** + * If binding is active and should be executed. + * @property {boolean} active + * @default + */ + active: true, + + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). + * @property {array|null} params + * @default + */ + params: null, + + /** + * Call listener passing arbitrary parameters. + * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. + * @method Phaser.SignalBinding#execute + * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener. + * @return {any} Value returned by the listener. + */ + execute: function(paramsArr) { + + var handlerReturn, params; + + if (this.active && !!this._listener) + { + params = this.params ? this.params.concat(paramsArr) : paramsArr; + + if (this._args) + { + params = params.concat(this._args); + } + + handlerReturn = this._listener.apply(this.context, params); + + this.callCount++; + + if (this._isOnce) + { + this.detach(); + } + } + + return handlerReturn; + + }, + + /** + * Detach binding from signal. + * alias to: @see mySignal.remove(myBinding.getListener()); + * @method Phaser.SignalBinding#detach + * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ + detach: function () { + return this.isBound() ? this._signal.remove(this._listener, this.context) : null; + }, + + /** + * @method Phaser.SignalBinding#isBound + * @return {boolean} True if binding is still bound to the signal and has a listener. + */ + isBound: function () { + return (!!this._signal && !!this._listener); + }, + + /** + * @method Phaser.SignalBinding#isOnce + * @return {boolean} If SignalBinding will only be executed once. + */ + isOnce: function () { + return this._isOnce; + }, + + /** + * @method Phaser.SignalBinding#getListener + * @return {function} Handler function bound to the signal. + */ + getListener: function () { + return this._listener; + }, + + /** + * @method Phaser.SignalBinding#getSignal + * @return {Phaser.Signal} Signal that listener is currently bound to. + */ + getSignal: function () { + return this._signal; + }, + + /** + * Delete instance properties + * @method Phaser.SignalBinding#_destroy + * @private + */ + _destroy: function () { + delete this._signal; + delete this._listener; + delete this.context; + }, + + /** + * @method Phaser.SignalBinding#toString + * @return {string} String representation of the object. + */ + toString: function () { + return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']'; + } + +}; + +Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding; + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Filter class to use for any Phaser filter development. +* If you want to make a custom filter, this should be your base class. +* +* The default uniforms, types and values for all Filters are: +* +* ```javascript +* resolution: { type: '2f', value: { x: 256, y: 256 }} +* time: { type: '1f', value: 0 } +* mouse: { type: '2f', value: { x: 0.0, y: 0.0 } } +* date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] } +* sampleRate: { type: '1f', value: 44100.0 } +* iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* ``` +* +* The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and +* therefore only work in WebGL and are not supported by Canvas at all. +* +* @class Phaser.Filter +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [uniforms] - Uniform mappings object. The uniforms are added on the default uniforms, or replace them if the keys are the same. +* @param {Array|string} [fragmentSrc] - The fragment shader code. Either an array, one element per line of code, or a string. +*/ +Phaser.Filter = function (game, uniforms, fragmentSrc) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. + * @default + */ + this.type = Phaser.WEBGL_FILTER; + + /** + * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. + * For example the blur filter has two passes blurX and blurY. + * @property {array} passes - An array of filter objects. + * @private + */ + this.passes = [ this ]; + + /** + * @property {array} shaders - Array an array of shaders. + * @private + */ + this.shaders = []; + + /** + * @property {boolean} dirty - Internal PIXI var. + * @default + */ + this.dirty = true; + + /** + * @property {number} padding - Internal PIXI var. + * @default + */ + this.padding = 0; + + /** + * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same) + */ + this.prevPoint = new Phaser.Point(); + + /* + * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D. + */ + + var d = new Date(); + + /** + * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. + */ + this.uniforms = { + + resolution: { type: '2f', value: { x: 256, y: 256 }}, + time: { type: '1f', value: 0 }, + mouse: { type: '2f', value: { x: 0.0, y: 0.0 } }, + date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, + sampleRate: { type: '1f', value: 44100.0 }, + iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + + }; + + // Copy over / replace any passed in the constructor + if (uniforms) + { + for (var key in uniforms) + { + this.uniforms[key] = uniforms[key]; + } + } + + // If fragmentSrc is a string, split it based on new-lines into an array + if (typeof fragmentSrc === 'string') + { + fragmentSrc = fragmentSrc.split('\n'); + } + + /** + * @property {array|string} fragmentSrc - The fragment shader code. + */ + this.fragmentSrc = fragmentSrc || []; + +}; + +Phaser.Filter.prototype = { + + /** + * This should be over-ridden. Will receive a variable number of arguments. + * + * @method Phaser.Filter#init + */ + init: function () { + + // This should be over-ridden. Will receive a variable number of arguments. + + }, + + /** + * Set the resolution uniforms on the filter. + * + * @method Phaser.Filter#setResolution + * @param {number} width - The width of the display. + * @param {number} height - The height of the display. + */ + setResolution: function (width, height) { + + this.uniforms.resolution.value.x = width; + this.uniforms.resolution.value.y = height; + + }, + + /** + * Updates the filter. + * + * @method Phaser.Filter#update + * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. + */ + update: function (pointer) { + + if (pointer) + { + var x = pointer.x / this.game.width; + var y = 1 - pointer.y / this.game.height; + + if (x !== this.prevPoint.x || y !== this.prevPoint.y) + { + this.uniforms.mouse.value.x = x.toFixed(2); + this.uniforms.mouse.value.y = y.toFixed(2); + this.prevPoint.set(x, y); + } + } + + this.uniforms.time.value = this.game.time.totalElapsedSeconds(); + + }, + + /** + * Creates a new Phaser.Image object using a blank texture and assigns + * this Filter to it. The image is then added to the world. + * + * If you don't provide width and height values then Filter.width and Filter.height are used. + * + * If you do provide width and height values then this filter will be resized to match those + * values. + * + * @method Phaser.Filter#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. + * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, width, height, anchorX, anchorY) { + + if (anchorX === undefined) { anchorX = 0; } + if (anchorY === undefined) { anchorY = 0; } + + if (width !== undefined && width !== null) + { + this.width = width; + } + else + { + width = this.width; + } + + if (height !== undefined && height !== null) + { + this.height = height; + } + else + { + height = this.height; + } + + var image = this.game.add.image(x, y, Phaser.Cache.DEFAULT); + + image.width = width; + image.height = height; + + image.anchor.set(anchorX, anchorY); + + image.filters = [ this ]; + + return image; + + }, + + /** + * Syncs the uniforms between the class object and the shaders. + * + * @method Phaser.Filter#syncUniforms + */ + syncUniforms: function () { + + for (var i = 0; i < this.shaders.length; i++) + { + this.shaders[i].dirty = true; + } + + }, + + /** + * Clear down this Filter and null out references to game. + * + * @method Phaser.Filter#destroy + */ + destroy: function () { + + this.passes.length = 0; + this.shaders.length = 0; + this.fragmentSrc.length = 0; + + this.game = null; + this.uniforms = null; + this.prevPoint = null; + + } + +}; + +Phaser.Filter.prototype.constructor = Phaser.Filter; + +/** +* @name Phaser.Filter#width +* @property {number} width - The width (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'width', { + + get: function () { + + return this.uniforms.resolution.value.x; + + }, + + set: function (value) { + + this.uniforms.resolution.value.x = value; + + } + +}); + +/** +* @name Phaser.Filter#height +* @property {number} height - The height (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'height', { + + get: function () { + + return this.uniforms.resolution.value.y; + + }, + + set: function (value) { + + this.uniforms.resolution.value.y = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Plugin template to use for any Phaser plugin development. +* +* ##### Callbacks +* +* add | active | visible | remove +* -----|-------------|-------------|-------- +* init | | | +* | preUpdate* | | +* | update* | render* | +* | postUpdate* | postRender* | +* | | | destroy +* +* Update and render calls are repeated (*). +* +* @class Phaser.Plugin +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager. +*/ +Phaser.Plugin = function (game, parent) { + + if (parent === undefined) { parent = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. + */ + this.parent = parent; + + /** + * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. + * @default + */ + this.active = false; + + /** + * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. + * @default + */ + this.visible = false; + + /** + * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. + * @default + */ + this.hasPreUpdate = false; + + /** + * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. + * @default + */ + this.hasUpdate = false; + + /** + * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. + * @default + */ + this.hasPostUpdate = false; + + /** + * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. + * @default + */ + this.hasRender = false; + + /** + * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. + * @default + */ + this.hasPostRender = false; + +}; + +Phaser.Plugin.prototype = { + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It is only called if active is set to true. + * @method Phaser.Plugin#preUpdate + */ + preUpdate: function () { + }, + + /** + * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It is only called if active is set to true. + * @method Phaser.Plugin#update + */ + update: function () { + }, + + /** + * Render is called right after the Game Renderer completes, but before the State.render. + * It is only called if visible is set to true. + * @method Phaser.Plugin#render + */ + render: function () { + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It is only called if visible is set to true. + * @method Phaser.Plugin#postRender + */ + postRender: function () { + }, + + /** + * Clear down this Plugin and null out references + * @method Phaser.Plugin#destroy + */ + destroy: function () { + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + + } + +}; + +Phaser.Plugin.prototype.constructor = Phaser.Plugin; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. +* +* @class Phaser.PluginManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.PluginManager = function(game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager. + */ + this.plugins = []; + + /** + * @property {number} _len - Internal cache var. + * @private + */ + this._len = 0; + + /** + * @property {number} _i - Internal cache var. + * @private + */ + this._i = 0; + +}; + +Phaser.PluginManager.prototype = { + + /** + * Add a new Plugin into the PluginManager. + * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.PluginManager#add + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + add: function (plugin) { + + var args = Array.prototype.slice.call(arguments, 1); + var result = false; + + // Prototype? + if (typeof plugin === 'function') + { + plugin = new plugin(this.game, this); + } + else + { + plugin.game = this.game; + plugin.parent = this; + } + + // Check for methods now to avoid having to do this every loop + 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; + } + + // The plugin must have at least one of the above functions to be added to the PluginManager. + 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); + + // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager + if (typeof plugin['init'] === 'function') + { + plugin.init.apply(plugin, args); + } + + return plugin; + } + else + { + return null; + } + }, + + /** + * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. + * + * @method Phaser.PluginManager#remove + * @param {Phaser.Plugin} plugin - The plugin to be removed. + * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed? + */ + remove: function (plugin, destroy) { + + if (destroy === undefined) { destroy = true; } + + this._i = this._len; + + while (this._i--) + { + if (this.plugins[this._i] === plugin) + { + if (destroy) + { + plugin.destroy(); + } + + this.plugins.splice(this._i, 1); + this._len--; + return; + } + } + + }, + + /** + * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. + * + * @method Phaser.PluginManager#removeAll + */ + removeAll: function() { + + this._i = this._len; + + while (this._i--) + { + this.plugins[this._i].destroy(); + } + + this.plugins.length = 0; + this._len = 0; + + }, + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#preUpdate + */ + 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 is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#update + */ + 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 is the last thing to be called before the world render. + * In particular, it is called after the world postUpdate, which means the camera has been adjusted. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#postUpdate + */ + 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 is called right after the Game Renderer completes, but before the State.render. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#render + */ + 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(); + } + } + + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#postRender + */ + 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(); + } + } + + }, + + /** + * Clear down this PluginManager, calls destroy on every plugin and nulls out references. + * + * @method Phaser.PluginManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.game = null; + + } + +}; + +Phaser.PluginManager.prototype.constructor = Phaser.PluginManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Stage controls root level display objects upon which everything is displayed. +* It also handles browser visibility handling and the pausing due to loss of focus. +* +* @class Phaser.Stage +* @extends PIXI.DisplayObjectContainer +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Stage = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {string} name - The name of this object. + * @default + */ + this.name = '_stage_root'; + + /** + * By default if the browser tab loses focus the game will pause. + * You can stop that behavior by setting this property to true. + * Note that the browser can still elect to pause your game if it wishes to do so, + * for example swapping to another browser tab. This will cause the RAF callback to halt, + * effectively pausing your game, even though no in-game pause event is triggered if you enable this property. + * @property {boolean} disableVisibilityChange + * @default + */ + this.disableVisibilityChange = false; + + /** + * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. + * @default + */ + this.exists = true; + + /** + * @property {Phaser.Matrix} worldTransform - Current transform of the object based on world (parent) factors + * @private + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage) + * @private + * @readOnly + */ + this.stage = this; + + /** + * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. + */ + this.currentRenderOrderID = 0; + + /** + * @property {string} hiddenVar - The page visibility API event name. + * @private + */ + this._hiddenVar = 'hidden'; + + /** + * @property {function} _onChange - The blur/focus event handler. + * @private + */ + this._onChange = null; + + /** + * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor. + * @private + */ + this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' }; + + if (!this.game.transparent) + { + // transparent = 0,0,0,0 - otherwise r,g,b,1 + this._bgColor.a = 1; + } + + if (game.config) + { + this.parseConfig(game.config); + } + +}; + +Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Stage.prototype.constructor = Phaser.Stage; + +/** +* Parses a Game configuration object. +* +* @method Phaser.Stage#parseConfig +* @protected +* @param {object} config -The configuration object to parse. +*/ +Phaser.Stage.prototype.parseConfig = function (config) { + + if (config['disableVisibilityChange']) + { + this.disableVisibilityChange = config['disableVisibilityChange']; + } + + if (config['backgroundColor']) + { + this.setBackgroundColor(config['backgroundColor']); + } + +}; + +/** +* Initialises the stage and adds the event listeners. +* @method Phaser.Stage#boot +* @private +*/ +Phaser.Stage.prototype.boot = function () { + + Phaser.DOM.getOffset(this.game.canvas, this.offset); + + Phaser.Canvas.setUserSelect(this.game.canvas, 'none'); + Phaser.Canvas.setTouchAction(this.game.canvas, 'none'); + + this.checkVisibility(); + +}; + +/** +* This is called automatically after the plugins preUpdate and before the State.update. +* Most objects have preUpdate methods and it's where initial movement and positioning is done. +* +* @method Phaser.Stage#preUpdate +*/ +Phaser.Stage.prototype.preUpdate = function () { + + this.currentRenderOrderID = 0; + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + +}; + +/** +* This is called automatically after the State.update, but before particles or plugins update. +* +* @method Phaser.Stage#update +*/ +Phaser.Stage.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + this.children[i].update(); + } + +}; + +/** +* This is called automatically before the renderer runs and after the plugins have updated. +* In postUpdate this is where all the final physics calculations and object positioning happens. +* The objects are processed in the order of the display list. +* +* @method Phaser.Stage#postUpdate +*/ +Phaser.Stage.prototype.postUpdate = function () { + + // Apply the camera shake, fade, bounds, etc + this.game.camera.update(); + + // Camera target first? + if (this.game.camera.target) + { + this.game.camera.target.postUpdate(); + + this.updateTransform(); + + this.game.camera.updateTarget(); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + this.updateTransform(); + +}; + +/** +* Updates the transforms for all objects on the display list. +* This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. +* +* @method Phaser.Stage#updateTransform +*/ +Phaser.Stage.prototype.updateTransform = function () { + + this.worldAlpha = 1; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +/** +* Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. +* Also listens for window.onblur and window.onfocus. +* +* @method Phaser.Stage#checkVisibility +*/ +Phaser.Stage.prototype.checkVisibility = function () { + + if (document.hidden !== undefined) + { + this._hiddenVar = 'visibilitychange'; + } + else if (document.webkitHidden !== undefined) + { + this._hiddenVar = 'webkitvisibilitychange'; + } + else if (document.mozHidden !== undefined) + { + this._hiddenVar = 'mozvisibilitychange'; + } + else if (document.msHidden !== undefined) + { + this._hiddenVar = 'msvisibilitychange'; + } + else + { + this._hiddenVar = null; + } + + var _this = this; + + this._onChange = function (event) { + return _this.visibilityChange(event); + }; + + this._onClick = function (event) { + if ((document.hasFocus !== undefined) && !document.hasFocus()) + { + _this.visibilityChange(event); + } + }; + + // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus + if (this._hiddenVar) + { + document.addEventListener(this._hiddenVar, this._onChange, false); + } + + window.onblur = this._onChange; + window.onfocus = this._onChange; + + window.onpagehide = this._onChange; + window.onpageshow = this._onChange; + + window.addEventListener('click', this._onClick); + + if (this.game.device.cocoonJSApp) + { + CocoonJS.App.onSuspended.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" }); + }); + + CocoonJS.App.onActivated.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" }); + }); + } + +}; + +/** +* This method is called when the document visibility is changed. +* +* - `blur` and `pagehide` events trigger {@link Phaser.Game#onBlur}. They {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `click`, `focus`, and `pageshow` trigger {@link Phaser.Game#onFocus}. They {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (hidden) and CocoonJS's `onSuspended` {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (visible) and CocoonJS's `onActivated` {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* +* @method Phaser.Stage#visibilityChange +* @param {Event} event - Its type will be used to decide whether the game should be paused or not. +*/ +Phaser.Stage.prototype.visibilityChange = function (event) { + + // These events always trigger the Game#onBlur or Game#onFocus signals. + + switch (event.type) + { + case 'blur': + case 'pagehide': + this.game.focusLoss(event); + return; + case 'click': + case 'focus': + case 'pageshow': + this.game.focusGain(event); + return; + } + + if (this.disableVisibilityChange) + { + return; + } + + if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause") + { + this.game.gamePaused(event); + } + else + { + this.game.gameResumed(event); + } + +}; + +/** +* Sets the background color for the Stage. +* +* The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). +* +* An alpha channel is _not_ supported and will be ignored. +* +* If you've set your game to be {@link Phaser.Game#transparent transparent} then calls to setBackgroundColor are ignored. +* +* If {@link Phaser.Game#clearBeforeRender} is off then the background color won't appear. +* +* @method Phaser.Stage#setBackgroundColor +* @param {number|string} color - The color of the background. +*/ +Phaser.Stage.prototype.setBackgroundColor = function (color) { + + if (this.game.transparent) { return; } + + Phaser.Color.valueToColor(color, this._bgColor); + Phaser.Color.updateColor(this._bgColor); + + // For gl.clearColor (canvas uses _bgColor.rgba) + this._bgColor.r /= 255; + this._bgColor.g /= 255; + this._bgColor.b /= 255; + this._bgColor.a = 1; + +}; + +/** +* Destroys the Stage and removes event listeners. +* +* @method Phaser.Stage#destroy +*/ +Phaser.Stage.prototype.destroy = function () { + + if (this._hiddenVar) + { + document.removeEventListener(this._hiddenVar, this._onChange, false); + } + + window.onpagehide = null; + window.onpageshow = null; + + window.onblur = null; + window.onfocus = null; + + window.removeEventListener('click', this._onClick); + +}; + +/** +* Adds an existing object to the Stage. +* +* The child is automatically added to the front of the Stage, and is displayed above every previous child. +* Or if the _optional_ `index` is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the object was already on the Stage, it is simply returned, and nothing else happens to it. +* +* @method Phaser.Stage#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent] - Unused. Kept for compatibility with {@link Phaser.Group#add}. +* @param {integer} [index] - The index to insert the object to. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Stage.prototype.add = function (child, silent, index) { + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + this.addChild(child); + } + else + { + this.addChildAt(child, index); + } + + return child; + +}; + +/** +* @name Phaser.Stage#backgroundColor +* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' +* @see Phaser.Stage#setBackgroundColor +*/ +Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", { + + get: function () { + + return this._bgColor.color; + + }, + + set: function (color) { + + this.setBackgroundColor(color); + + } + +}); + +/** +* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. +* +* @name Phaser.Stage#smoothed +* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) +*/ +Object.defineProperty(Phaser.Stage.prototype, "smoothed", { + + get: function () { + + return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR; + + }, + + set: function (value) { + + if (value) + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR; + } + else + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}. +* +* Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. +* For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. +* +* In addition, Groups provides support for fast pooling and object recycling. +* +* Groups are also display objects and can be nested as children within other Groups. +* +* @class Phaser.Group +* @extends PIXI.DisplayObjectContainer +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to. +* If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent. +* @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World. +* @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}. +* @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values. +*/ +Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) { + + if (addToStage === undefined) { addToStage = false; } + if (enableBody === undefined) { enableBody = false; } + if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + if (parent === undefined) + { + parent = game.world; + } + + /** + * A name for this group. Not used internally but useful for debugging. + * @property {string} name + */ + this.name = name || 'group'; + + /** + * The z-depth value of this object within its parent container/Group - the World is a Group as well. + * This value must be unique for each child in a Group. + * @property {integer} z + * @readOnly + */ + this.z = 0; + + PIXI.DisplayObjectContainer.call(this); + + if (addToStage) + { + this.game.stage.addChild(this); + this.z = this.game.stage.children.length; + } + else + { + if (parent) + { + parent.addChild(this); + this.z = parent.children.length; + } + } + + /** + * Internal Phaser Type value. + * @property {integer} type + * @protected + */ + this.type = Phaser.GROUP; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. + * @property {boolean} alive + * @default + */ + this.alive = true; + + /** + * If exists is false the group will be excluded from collision checks and filters such as {@link #forEachExists}. The group will not call `preUpdate` and `postUpdate` on its children and the children will not receive physics updates or camera/world boundary checks. The group will still be {@link #visible} and will still call `update` on its children (unless {@link #updateOnlyExistingChildren} is true). + * @property {boolean} exists + * @default + */ + this.exists = true; + + /** + * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. + * @property {boolean} ignoreDestroy + * @default + */ + this.ignoreDestroy = false; + + /** + * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method + * called on the next logic update. + * You can set it directly to flag the Group to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy a Group from within one of its own callbacks + * or a callback of one of its children. + * + * @property {boolean} pendingDestroy + */ + this.pendingDestroy = false; + + /** + * The type of objects that will be created when using {@link #create} or {@link #createMultiple}. + * + * It should extend either Sprite or Image and accept the same constructor arguments: `(game, x, y, key, frame)`. + * + * @property {function} classType + * @default {@link Phaser.Sprite} + */ + this.classType = Phaser.Sprite; + + /** + * The current display object that the group cursor is pointing to, if any. (Can be set manually.) + * + * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}. + * @property {?DisplayObject} cursor + */ + this.cursor = null; + + /** + * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` + * on any children _added_ to, or _created by_, this Group. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * @property {boolean} inputEnableChildren + * @default + */ + this.inputEnableChildren = false; + + /** + * Skip children with `exists = false` in {@link #update}. + * + * @property {boolean} updateOnlyExistingChildren + * @default + */ + this.updateOnlyExistingChildren = false; + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputDown + */ + this.onChildInputDown = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, + * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer + * is still over the Sprite or not. + * + * @property {Phaser.Signal} onChildInputUp + */ + this.onChildInputUp = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOver + */ + this.onChildInputOver = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOut + */ + this.onChildInputOut = new Phaser.Signal(); + + /** + * If true all Sprites created by, or added to this group, will have a physics body enabled on them. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * The default body type is controlled with {@link #physicsBodyType}. + * @property {boolean} enableBody + */ + this.enableBody = enableBody; + + /** + * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well. + * + * This only works for P2 bodies. + * @property {boolean} enableBodyDebug + * @default + */ + this.enableBodyDebug = false; + + /** + * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites. + * + * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc. + * @property {integer} physicsBodyType + */ + this.physicsBodyType = physicsBodyType; + + /** + * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. + * + * It should be set to one of the Phaser.Physics.Arcade sort direction constants: + * + * Phaser.Physics.Arcade.SORT_NONE + * Phaser.Physics.Arcade.LEFT_RIGHT + * Phaser.Physics.Arcade.RIGHT_LEFT + * Phaser.Physics.Arcade.TOP_BOTTOM + * Phaser.Physics.Arcade.BOTTOM_TOP + * + * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. + * + * @property {integer} physicsSortDirection + * @default + */ + this.physicsSortDirection = null; + + /** + * This signal is dispatched when the group is destroyed. + * @property {Phaser.Signal} onDestroy + */ + this.onDestroy = new Phaser.Signal(); + + /** + * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next. + * @readOnly + */ + this.cursorIndex = 0; + + /** + * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. + * + * Note that the cameraOffset values are in addition to any parent in the display list. + * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x + * + * @property {boolean} fixedToCamera + */ + this.fixedToCamera = false; + + /** + * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view. + * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. + * @property {Phaser.Point} cameraOffset + */ + this.cameraOffset = new Phaser.Point(); + + /** + * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. + * + * Only children of this Group can be added to and removed from the hash. + * + * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. + * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own + * sorting and filtering of Group children without touching their z-index (and therefore display draw order) + * + * @property {array} hash + */ + this.hash = []; + + /** + * The property on which children are sorted. + * @property {string} _sortProperty + * @private + */ + this._sortProperty = 'z'; + +}; + +Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Group.prototype.constructor = Phaser.Group; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_NONE = 0; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_TOTAL = 1; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_CHILD = 2; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_ALL = 3; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_ASCENDING = -1; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_DESCENDING = 1; + +/** +* Adds an existing object as the top child in this group. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the child was already in this Group, it is simply returned, and nothing else happens to it. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* Use {@link #create} to create and add a new child. +* +* @method Phaser.Group#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.add = function (child, silent, index) { + + if (silent === undefined) { silent = false; } + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + child.z = this.children.length; + + this.addChild(child); + } + else + { + this.addChildAt(child, index); + + this.updateZ(); + } + + if (this.enableBody && child.hasOwnProperty('body') && child.body === null) + { + this.game.physics.enable(child, this.physicsBodyType); + } + else if (child.body) + { + this.addToHash(child); + } + + if (this.inputEnableChildren && (!child.input || child.inputEnabled)) + { + child.inputEnabled = true; + } + + if (!silent && child.events) + { + child.events.onAddedToGroup$dispatch(child, this); + } + + if (this.cursor === null) + { + this.cursor = child; + } + + return child; + +}; + +/** +* Adds an existing object to this group. +* +* The child is added to the group at the location specified by the index value, this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#addAt +* @param {DisplayObject} child - The display object to add as a child. +* @param {integer} [index=0] - The index within the group to insert the child to. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.addAt = function (child, index, silent) { + + return this.add(child, silent, index); + +}; + +/** +* Adds a child of this Group into the hash array. +* This call will return false if the child is not a child of this Group, or is already in the hash. +* +* @method Phaser.Group#addToHash +* @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. +* @return {boolean} True if the child was successfully added to the hash, otherwise false. +*/ +Phaser.Group.prototype.addToHash = function (child) { + + if (child.parent === this) + { + var index = this.hash.indexOf(child); + + if (index === -1) + { + this.hash.push(child); + return true; + } + } + + return false; + +}; + +/** +* Removes a child of this Group from the hash array. +* This call will return false if the child is not in the hash. +* +* @method Phaser.Group#removeFromHash +* @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash. +* @return {boolean} True if the child was successfully removed from the hash, otherwise false. +*/ +Phaser.Group.prototype.removeFromHash = function (child) { + + if (child) + { + var index = this.hash.indexOf(child); + + if (index !== -1) + { + this.hash.splice(index, 1); + return true; + } + } + + return false; + +}; + +/** +* Adds an array of existing Display Objects to this Group. +* +* The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. +* +* As well as an array you can also pass another Group as the first argument. In this case all of the children from that +* Group will be removed from it and added into this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#addMultiple +* @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group. +*/ +Phaser.Group.prototype.addMultiple = function (children, silent) { + + if (children instanceof Phaser.Group) + { + children.moveAll(this, silent); + } + else if (Array.isArray(children)) + { + for (var i = 0; i < children.length; i++) + { + this.add(children[i], silent); + } + } + + return children; + +}; + +/** +* Returns the child found at the given index within this group. +* +* @method Phaser.Group#getAt +* @param {integer} index - The index to return the child from. +* @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index. +*/ +Phaser.Group.prototype.getAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + return -1; + } + else + { + return this.getChildAt(index); + } + +}; + +/** +* Creates a new Phaser.Sprite object and adds it to the top of this group. +* +* Use {@link #classType} to change the type of object created. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#create +* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. +* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {boolean} [exists=true] - The default exists state of the Sprite. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed. +*/ +Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) { + + if (exists === undefined) { exists = true; } + + var child = new this.classType(this.game, x, y, key, frame); + + child.exists = exists; + child.visible = exists; + child.alive = exists; + + return this.add(child, false, index); + +}; + +/** +* Creates multiple Phaser.Sprite objects and adds them to the top of this Group. +* +* This method is useful if you need to quickly generate a pool of sprites, such as bullets. +* +* Use {@link #classType} to change the type of object created. +* +* You can provide an array as the `key` and / or `frame` arguments. When you do this +* it will create `quantity` Sprites for every key (and frame) in the arrays. +* +* For example: +* +* `createMultiple(25, ['ball', 'carrot'])` +* +* In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be +* created in total, 25 of each. You can also have the `frame` as an array: +* +* `createMultiple(5, 'bricks', [0, 1, 2, 3])` +* +* In the above there is one key (bricks), which is a sprite sheet. The frames array tells +* this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because +* the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with +* frame 1, and so on. +* +* If you set both the key and frame arguments to be arrays then understand it will create +* a total quantity of sprites equal to the size of both arrays times each other. I.e.: +* +* `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` +* +* The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. +* It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. +* In total it will have created 120 sprites. +* +* By default the Sprites will have their `exists` property set to `false`, and they will be +* positioned at 0x0, relative to the `Group.x / y` values. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#createMultiple +* @param {integer} quantity - The number of Sprites to create. +* @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. +* @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. +* @param {boolean} [exists=false] - The default exists state of the Sprite. +* @param {function} [callback] - The function that will be called for each applicable child. It will be passed the new child and the loop index (0 through quantity - 1). +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). The default context is the new child. +* @return {array} An array containing all of the Sprites that were created. +*/ +Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, callback, callbackContext) { + + if (frame === undefined) { frame = 0; } + if (exists === undefined) { exists = false; } + + if (!Array.isArray(key)) + { + key = [ key ]; + } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + + var _this = this; + var children = []; + + key.forEach(function(singleKey) { + + frame.forEach(function(singleFrame) { + + for (var i = 0; i < quantity; i++) + { + var child = _this.create(0, 0, singleKey, singleFrame, exists); + + if (callback) { callback.call(callbackContext || child, child, i); } + + children.push(child); + } + + }); + + }); + + return children; + +}; + +/** +* Internal method that re-applies all of the children's Z values. +* +* This must be called whenever children ordering is altered so that their `z` indices are correctly updated. +* +* @method Phaser.Group#updateZ +* @protected +*/ +Phaser.Group.prototype.updateZ = function () { + + var i = this.children.length; + + while (i--) + { + this.children[i].z = i; + } + +}; + +/** +* This method iterates through all children in the Group (regardless if they are visible or exist) +* and then changes their position so they are arranged in a Grid formation. Children must have +* the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have +* this. +* +* The grid dimensions are determined by the first four arguments. The `width` and `height` arguments +* relate to the width and height of the grid respectively. +* +* For example if the Group had 100 children in it: +* +* `Group.align(10, 10, 32, 32)` +* +* This will align all of the children into a grid formation of 10x10, using 32 pixels per +* grid cell. If you want a wider grid, you could do: +* +* `Group.align(25, 4, 32, 32)` +* +* This will align the children into a grid of 25x4, again using 32 pixels per grid cell. +* +* You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method +* to keep on aligning children until there are no children left. For example if this Group had +* 48 children in it, the following: +* +* `Group.align(-1, 8, 32, 32)` +* +* ... will align the children so that there are 8 children vertically (the second argument), +* and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) +* +* You can also do: +* +* `Group.align(10, -1, 32, 32)` +* +* In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit +* all of the children in. +* +* The `position` property allows you to control where in each grid cell the child is positioned. +* This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, +* `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, +* `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* +* The final argument; `offset` lets you start the alignment from a specific child index. +* +* @method Phaser.Group#align +* @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. +* @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. +* @param {integer} cellWidth - The width of each grid cell, in pixels. +* @param {integer} cellHeight - The height of each grid cell, in pixels. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. +* @return {boolean} True if the Group children were aligned, otherwise false. +*/ +Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, position, offset) { + + if (position === undefined) { position = Phaser.TOP_LEFT; } + if (offset === undefined) { offset = 0; } + + if (this.children.length === 0 || offset > this.children.length || (width === -1 && height === -1)) + { + return false; + } + + var r = new Phaser.Rectangle(0, 0, cellWidth, cellHeight); + var w = (width * cellWidth); + var h = (height * cellHeight); + + for (var i = offset; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child['alignIn']) + { + child.alignIn(r, position); + } + else + { + continue; + } + + if (width === -1) + { + // We keep laying them out horizontally until we've done them all + r.y += cellHeight; + + if (r.y === h) + { + r.x += cellWidth; + r.y = 0; + } + } + else if (height === -1) + { + // We keep laying them out vertically until we've done them all + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + } + } + else + { + // We keep laying them out until we hit the column limit + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + + if (r.y === h) + { + // We've hit the column limit, so return, even if there are children left + return true; + } + } + } + } + + return true; + +}; + +/** +* Sets the group cursor to the first child in the group. +* +* If the optional index parameter is given it sets the cursor to the object at that index instead. +* +* @method Phaser.Group#resetCursor +* @param {integer} [index=0] - Set the cursor to point to a specific index. +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.resetCursor = function (index) { + + if (index === undefined) { index = 0; } + + if (index > this.children.length - 1) + { + index = 0; + } + + if (this.cursor) + { + this.cursorIndex = index; + this.cursor = this.children[this.cursorIndex]; + return this.cursor; + } + +}; + +/** +* Advances the group cursor to the next (higher) object in the group. +* +* If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). +* +* @method Phaser.Group#next +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.next = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex >= this.children.length - 1) + { + this.cursorIndex = 0; + } + else + { + this.cursorIndex++; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Moves the group cursor to the previous (lower) child in the group. +* +* If the cursor is at the start of the group (bottom child) it is moved to the end (top child). +* +* @method Phaser.Group#previous +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.previous = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex === 0) + { + this.cursorIndex = this.children.length - 1; + } + else + { + this.cursorIndex--; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Swaps the position of two children in this group. +* +* Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. +* +* @method Phaser.Group#swap +* @param {any} child1 - The first child to swap. +* @param {any} child2 - The second child to swap. +*/ +Phaser.Group.prototype.swap = function (child1, child2) { + + this.swapChildren(child1, child2); + this.updateZ(); + +}; + +/** +* Brings the given child to the top of this group so it renders above all other children. +* +* @method Phaser.Group#bringToTop +* @param {any} child - The child to bring to the top of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.bringToTop = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length) + { + this.remove(child, false, true); + this.add(child, true); + } + + return child; + +}; + +/** +* Sends the given child to the bottom of this group so it renders below all other children. +* +* @method Phaser.Group#sendToBack +* @param {any} child - The child to send to the bottom of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.sendToBack = function (child) { + + if (child.parent === this && this.getIndex(child) > 0) + { + this.remove(child, false, true); + this.addAt(child, 0, true); + } + + return child; + +}; + +/** +* Moves the given child up one place in this group unless it's already at the top. +* +* @method Phaser.Group#moveUp +* @param {any} child - The child to move up in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveUp = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length - 1) + { + var a = this.getIndex(child); + var b = this.getAt(a + 1); + + if (b) + { + this.swap(child, b); + } + } + + return child; + +}; + +/** +* Moves the given child down one place in this group unless it's already at the bottom. +* +* @method Phaser.Group#moveDown +* @param {any} child - The child to move down in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveDown = 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; + +}; + +/** +* Positions the child found at the given index within this group to the given x and y coordinates. +* +* @method Phaser.Group#xy +* @param {integer} index - The index of the child in the group to set the position of. +* @param {number} x - The new x position of the child. +* @param {number} y - The new y position of the 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; + } + +}; + +/** +* Reverses all children in this group. +* +* This operation applies only to immediate children and does not propagate to subgroups. +* +* @method Phaser.Group#reverse +*/ +Phaser.Group.prototype.reverse = function () { + + this.children.reverse(); + this.updateZ(); + +}; + +/** +* Get the index position of the given child in this group, which should match the child's `z` property. +* +* @method Phaser.Group#getIndex +* @param {any} child - The child to get the index for. +* @return {integer} The index of the child or -1 if it's not a member of this group. +*/ +Phaser.Group.prototype.getIndex = function (child) { + + return this.children.indexOf(child); + +}; + +/** +* Searches the Group for the first instance of a child with the `name` +* property matching the given argument. Should more than one child have +* the same name only the first instance is returned. +* +* @method Phaser.Group#getByName +* @param {string} name - The name to search for. +* @return {any} The first child with a matching name, or null if none were found. +*/ +Phaser.Group.prototype.getByName = function (name) { + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].name === name) + { + return this.children[i]; + } + } + + return null; + +}; + +/** +* Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#replace +* @param {any} oldChild - The child in this group that will be replaced. +* @param {any} newChild - The child to be inserted into this group. +* @return {any} Returns the oldChild that was replaced within this group. +*/ +Phaser.Group.prototype.replace = function (oldChild, newChild) { + + var index = this.getIndex(oldChild); + + if (index !== -1) + { + if (newChild.parent) + { + if (newChild.parent instanceof Phaser.Group) + { + newChild.parent.remove(newChild); + } + else + { + newChild.parent.removeChild(newChild); + } + } + + this.remove(oldChild); + + this.addAt(newChild, index); + + return oldChild; + } + +}; + +/** +* Checks if the child has the given property. +* +* Will scan up to 4 levels deep only. +* +* @method Phaser.Group#hasProperty +* @param {any} child - The child to check for the existence of the property on. +* @param {string[]} key - An array of strings that make up the property. +* @return {boolean} True if the child has the property, otherwise false. +*/ +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; + +}; + +/** +* Sets a property to the given value on the child. The operation parameter controls how the value is set. +* +* The operations are: +* - 0: set the existing value to the given value; if force is `true` a new property will be created if needed +* - 1: will add the given value to the value already present. +* - 2: will subtract the given value from the value already present. +* - 3: will multiply the value already present by the given value. +* - 4: will divide the value already present by the given value. +* +* @method Phaser.Group#setProperty +* @param {any} child - The child to set the property value on. +* @param {array} key - An array of strings that make up the property that will be set. +* @param {any} value - The value that will be set. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) { + + if (force === undefined) { force = false; } + + operation = operation || 0; + + // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration. + + // 0 = Equals + // 1 = Add + // 2 = Subtract + // 3 = Multiply + // 4 = Divide + + // We can't force a property in and the child doesn't have it, so abort. + // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too. + 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; + +}; + +/** +* Checks a property for the given value on the child. +* +* @method Phaser.Group#checkProperty +* @param {any} child - The child to check the property value on. +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} True if `child` is a child of this Group and the property was equal to value, false if not. +*/ +Phaser.Group.prototype.checkProperty = function (child, key, value, force) { + + if (force === undefined) { force = false; } + + if (this !== child.parent) + { + return false; + } + + var result = Phaser.Utils.getProperty(child, key); + + if (((result === undefined) && force) || (result !== value)) + { + return false; + } + + return true; + +}; + +/** +* Quickly set a property on a single child of this group to a new value. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#set +* @param {Phaser.Sprite} child - The child to set the property on. +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true. +* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) { + + if (force === undefined) { force = false; } + + key = key.split('.'); + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible))) + { + return this.setProperty(child, key, value, operation, force); + } + +}; + +/** +* Quickly set the same property across all children of this group to a new value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. +* If you need that ability please see `Group.setAllChildren`. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAll +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + key = key.split('.'); + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + this.setProperty(this.children[i], key, value, operation, force); + } + } + +}; + +/** +* Quickly set the same property across all children of this group, and any child Groups, to a new value. +* +* If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. +* Unlike with `setAll` the property is NOT set on child Groups itself. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAllChildren +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + if (this.children[i] instanceof Phaser.Group) + { + this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force); + } + else + { + this.setProperty(this.children[i], key.split('.'), value, operation, force); + } + } + } + +}; + +/** +* Test that the same property across all children of this group is equal to the given value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAll +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} - True if all eligible children have the given property value (but see `force`); otherwise false. +*/ +Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (!this.checkProperty(child, key, value, force)) + { + return false; + } + } + } + + return true; + +}; + +/** +* Test that at least one child of this group has the given property value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAny +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @return {boolean} - True if at least one eligible child has the given property value; otherwise false. +*/ +Phaser.Group.prototype.checkAny = function (key, value, checkAlive, checkVisible) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (this.checkProperty(child, key, value)) + { + return true; + } + } + } + + return false; + +}; + +/** +* Adds the amount to the given property on all children in this group. +* +* `Group.addAll('x', 10)` will add 10 to the child.x value for each child. +* +* @method Phaser.Group#addAll +* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. +* @param {boolean} [checkAlive] - If true the property will only be changed if the child is alive. +* @param {boolean} [checkVisible] - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 1); + +}; + +/** +* Subtracts the amount from the given property on all children in this group. +* +* `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. +* +* @method Phaser.Group#subAll +* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 2); + +}; + +/** +* Multiplies the given property by the amount on all children in this group. +* +* `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. +* +* @method Phaser.Group#multiplyAll +* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 3); + +}; + +/** +* Divides the given property by the amount on all children in this group. +* +* `Group.divideAll('x', 2)` will half the child.x value for each child. +* +* @method Phaser.Group#divideAll +* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 4); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to false. + * + * @method Phaser.Group#kill + */ +Phaser.Group.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + +}; + +/** + * Kills all children having exists=true. + * + * @method Phaser.Group#killAll + */ +Phaser.Group.prototype.killAll = function () { + + this.callAllExists('kill', true); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to true. + * + * @method Phaser.Group#revive + */ +Phaser.Group.prototype.revive = function () { + + this.alive = true; + this.exists = true; + this.visible = true; + +}; + +/** + * Revives all children having exists=false. + * + * @method Phaser.Group#reviveAll + */ +Phaser.Group.prototype.reviveAll = function () { + + this.callAllExists('revive', false); + +}; + +/** +* Calls {@link #resetChild} on each child (or each existing child). +* +* @method Phaser.Group#resetAll +* @param {number} [x] - The x coordinate to reset each child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset each child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image or texture used by the Sprite during rendering. +* @param {string|number} [frame] - The frame of a sprite sheet or texture atlas. +* @param {boolean} [checkExists=false] - Reset only existing children. +*/ +Phaser.Group.prototype.resetAll = function (x, y, key, frame, checkExists) { + + this.forEach(this.resetChild, this, checkExists, x, y, key, frame); + +}; + +/** +* Calls a function, specified by name, on all children in the group who exist (or do not exist). +* +* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. +* +* @method Phaser.Group#callAllExists +* @param {string} callback - Name of the function on the children to call. +* @param {boolean} existsValue - Only children with exists=existsValue will be called. +* @param {...any} parameter - Additional parameters that will be passed to the callback. +*/ +Phaser.Group.prototype.callAllExists = function (callback, existsValue) { + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].exists === existsValue && this.children[i][callback]) + { + this.children[i][callback].apply(this.children[i], args); + } + } + +}; + +/** +* Returns a reference to a function that exists on a child of the group based on the given callback array. +* +* @method Phaser.Group#callbackFromArray +* @param {object} child - The object to inspect. +* @param {array} callback - The array of function names. +* @param {integer} length - The size of the array (pre-calculated in callAll). +* @protected +*/ +Phaser.Group.prototype.callbackFromArray = function (child, callback, length) { + + // Kinda looks like a Christmas tree + + if (length === 1) + { + if (child[callback[0]]) + { + return child[callback[0]]; + } + } + else if (length === 2) + { + if (child[callback[0]][callback[1]]) + { + return child[callback[0]][callback[1]]; + } + } + else if (length === 3) + { + if (child[callback[0]][callback[1]][callback[2]]) + { + return child[callback[0]][callback[1]][callback[2]]; + } + } + else if (length === 4) + { + if (child[callback[0]][callback[1]][callback[2]][callback[3]]) + { + return child[callback[0]][callback[1]][callback[2]][callback[3]]; + } + } + else if (child[callback]) + { + return child[callback]; + } + + return false; + +}; + +/** +* Calls a function, specified by name, on all on children. +* +* The function is called for all children regardless if they are dead or alive (see callAllExists for different options). +* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. +* +* @method Phaser.Group#callAll +* @param {string} method - Name of the function on the child to call. Deep property lookup is supported. +* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child. +* @param {...any} args - Additional parameters that will be passed to the method. +*/ +Phaser.Group.prototype.callAll = function (method, context) { + + if (method === undefined) + { + return; + } + + // Extract the method into an array + method = method.split('.'); + + var methodLength = method.length; + + if (context === undefined || context === null || context === '') + { + context = null; + } + else + { + // Extract the context into an array + if (typeof context === 'string') + { + context = context.split('.'); + var contextLength = context.length; + } + } + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + var callback = null; + var callbackContext = null; + + for (var i = 0; i < this.children.length; i++) + { + callback = this.callbackFromArray(this.children[i], method, methodLength); + + if (context && callback) + { + callbackContext = this.callbackFromArray(this.children[i], context, contextLength); + + if (callback) + { + callback.apply(callbackContext, args); + } + } + else if (callback) + { + callback.apply(this.children[i], args); + } + } + +}; + +/** +* The core preUpdate - as called by World. +* @method Phaser.Group#preUpdate +* @protected +*/ +Phaser.Group.prototype.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + // This chunk is identical to Phaser.Component.Core.prototype.preUpdateChildren, which is not yet defined. + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + return true; + +}; + +/** +* The core update - as called by World. +* +* Children with `exists = false` are updated unless {@link #updateOnlyExistingChildren} is true. +* +* @method Phaser.Group#update +* @protected +*/ +Phaser.Group.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + var len = this.children.length; + + if (i >= len) { i = len - 1; } + + var child = this.children[i]; + + if (!this.updateOnlyExistingChildren || child.exists) { + child.update(); + } + } + +}; + +/** +* The core postUpdate - as called by World. +* @method Phaser.Group#postUpdate +* @protected +*/ +Phaser.Group.prototype.postUpdate = function () { + + // Fixed to Camera? + if (this.fixedToCamera) + { + this.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; + this.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Find children matching a certain predicate. +* +* For example: +* +* var healthyList = Group.filter(function(child, index, children) { +* return child.health > 10 ? true : false; +* }, true); +* healthyList.callAll('attack'); +* +* Note: Currently this will skip any children which are Groups themselves. +* +* @method Phaser.Group#filter +* @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third +* @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. +* @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for +*/ +Phaser.Group.prototype.filter = function (predicate, checkExists) { + + var index = -1; + var length = this.children.length; + var results = []; + + while (++index < length) + { + var child = this.children[index]; + + if (!checkExists || (checkExists && child.exists)) + { + if (predicate(child, index, this.children)) + { + results.push(child); + } + } + } + + return new Phaser.ArraySet(results); + +}; + +/** +* Call a function on each child in this group. +* +* Additional arguments for the callback can be specified after the `checkExists` parameter. For example, +* +* Group.forEach(awardBonusGold, this, true, 100, 500) +* +* would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. +* +* Note: This check will skip any children which are Groups themselves. +* +* @method Phaser.Group#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) { + + if (checkExists === undefined) { checkExists = false; } + + if (arguments.length <= 3) + { + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + callback.call(callbackContext, this.children[i]); + } + } + } + else + { + // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE. + // Using an array and pushing each element (not a slice!) is _significantly_ faster. + var args = [null]; + + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + } + } + +}; + +/** +* Call a function on each existing child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachExists +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachExists = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each alive child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachAlive +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each dead child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachDead +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachDead = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Sort the children in the group according to a particular key and ordering. +* +* Call this function to sort the group according to a particular key value and order. +* +* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. +* +* Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including +* alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. +* +* @method Phaser.Group#sort +* @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value. +* @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}). +*/ +Phaser.Group.prototype.sort = function (key, order) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + if (key === undefined) { key = 'z'; } + if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; } + + this._sortProperty = key; + + if (order === Phaser.Group.SORT_ASCENDING) + { + this.children.sort(this.ascendingSortHandler.bind(this)); + } + else + { + this.children.sort(this.descendingSortHandler.bind(this)); + } + + this.updateZ(); + +}; + +/** +* Sort the children in the group according to custom sort function. +* +* The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). +* It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. +* +* @method Phaser.Group#customSort +* @param {function} sortHandler - The custom sort function. +* @param {object} [context=undefined] - The context in which the sortHandler is called. +*/ +Phaser.Group.prototype.customSort = function (sortHandler, context) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + this.children.sort(sortHandler.bind(context)); + + this.updateZ(); + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#ascendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.ascendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return -1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return 1; + } + else + { + if (a.z < b.z) + { + return -1; + } + else + { + return 1; + } + } + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#descendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.descendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return 1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return -1; + } + else + { + return 0; + } + +}; + +/** +* Iterates over the children of the group performing one of several actions for matched children. +* +* A child is considered a match when it has a property, named `key`, whose value is equal to `value` +* according to a strict equality comparison. +* +* The result depends on the `returnType`: +* +* - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}: +* The callback, if any, is applied to all matching children. The number of matched children is returned. +* - {@link Phaser.Group.RETURN_NONE RETURN_NONE}: +* The callback, if any, is applied to all matching children. No value is returned. +* - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}: +* The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. +* If there is no matching child then null is returned. +* +* If `args` is specified it must be an array. The matched child will be assigned to the first +* element and the entire array will be applied to the callback function. +* +* @method Phaser.Group#iterate +* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' +* @param {any} value - A child matches if `child[key] === value` is true. +* @param {integer} returnType - How to iterate the children and what to return. +* @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. +* @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null. +*/ +Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) { + + if (this.children.length === 0) + { + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return 0; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return []; + } + } + + var total = 0; + + if (returnType === Phaser.Group.RETURN_ALL) + { + var output = []; + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i][key] === value) + { + total++; + + if (callback) + { + if (args) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + else + { + callback.call(callbackContext, this.children[i]); + } + } + + if (returnType === Phaser.Group.RETURN_CHILD) + { + return this.children[i]; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + output.push(this.children[i]); + } + } + } + + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return total; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return output; + } + else + { + // RETURN_CHILD or RETURN_NONE + return null; + } + +}; + +/** +* Get the first display object with the given property name and value. +* +* @method Phaser.Group#getFirst +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {DisplayObject} The first child matching the query, or `null` if none were found. +*/ +Phaser.Group.prototype.getFirst = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_CHILD); + +}; + +/** +* Get the first display object that exists, or doesn't exist. +* +* You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstExists +* @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child. +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + if (typeof exists !== 'boolean') + { + exists = true; + } + + var child = this.getFirst('exists', exists); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is alive (`child.alive === true`). +* +* This is handy for choosing a squad leader, etc. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstAlive +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', true); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is dead (`child.alive === false`). +* +* This is handy for checking if everything has been wiped out and adding to the pool as needed. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstDead +* @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', false); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. +* +* If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. +* +* The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. +* +* @method Phaser.Group#resetChild +* @param {DisplayObject} child - The child to reset and/or load the texture on. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}. +*/ +Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) { + + if (child === null) + { + return null; + } + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (x !== null && y !== null) + { + child.reset(x, y); + } + + if (key !== undefined) + { + child.loadTexture(key, frame); + } + + return child; + +}; + +/** +* Return the child at the top of this group. +* +* The top child is the child displayed (rendered) above every other child. +* +* @method Phaser.Group#getTop +* @return {any} The child at the top of the Group. +*/ +Phaser.Group.prototype.getTop = function () { + + if (this.children.length > 0) + { + return this.children[this.children.length - 1]; + } + +}; + +/** +* Returns the child at the bottom of this group. +* +* The bottom child the child being displayed (rendered) below every other child. +* +* @method Phaser.Group#getBottom +* @return {any} The child at the bottom of the Group. +*/ +Phaser.Group.prototype.getBottom = function () { + + if (this.children.length > 0) + { + return this.children[0]; + } + +}; + +/** +* Get the closest child to given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getClosestTo +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child closest to given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContext) { + + var distance = Number.MAX_VALUE; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance < distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the child furthest away from the given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getFurthestFrom +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child furthest from the given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackContext) { + + var distance = 0; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance > distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the number of children with the given property name and value. +* +* @method Phaser.Group#count +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {integer} The number of children matching the query. +*/ +Phaser.Group.prototype.count = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_TOTAL); + +}; + +/** +* Get the number of living children in this group. +* +* @method Phaser.Group#countLiving +* @return {integer} The number of children flagged as alive. +*/ +Phaser.Group.prototype.countLiving = function () { + + return this.count('alive', true); + +}; + +/** +* Get the number of dead children in this group. +* +* @method Phaser.Group#countDead +* @return {integer} The number of children flagged as dead. +*/ +Phaser.Group.prototype.countDead = function () { + + return this.count('alive', false); + +}; + +/** +* Returns a random child from the group. +* +* @method Phaser.Group#getRandom +* @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). +* @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. +* @return {any} A random child of this Group. +*/ +Phaser.Group.prototype.getRandom = function (startIndex, length) { + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = this.children.length; } + + if (length === 0) + { + return null; + } + + return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length); + +}; + +/** +* Returns a random child from the Group that has `exists` set to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only +* the first 50 children in the Group. +* +* @method Phaser.Group#getRandomExists +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up to. +* @return {any} A random child of this Group that exists. +*/ +Phaser.Group.prototype.getRandomExists = function (startIndex, endIndex) { + + var list = this.getAll('exists', true, startIndex, endIndex); + + return this.game.rnd.pick(list); + +}; + +/** +* Returns all children in this Group. +* +* You can optionally specify a matching criteria using the `property` and `value` arguments. +* +* For example: `getAll('exists', true)` would return only children that have an `exists` property equal to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return the first 50 children in the Group. +* If `property` and `value` are also specified, only children within the given index range are searched. +* +* @method Phaser.Group#getAll +* @param {string} [property] - An optional property to test against the value argument. +* @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results. +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up until. +* @return {array} - An array containing all, some, or none of the Children of this Group. +*/ +Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) { + + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var output = []; + + for (var i = startIndex; i < endIndex; i++) + { + var child = this.children[i]; + + if (property) + { + if (child[property] === value) + { + output.push(child); + } + } + else + { + output.push(child); + } + } + + return output; + +}; + +/** +* Removes the given child from this group. +* +* This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. +* +* If the group cursor was referring to the removed child it is updated to refer to the next child. +* +* @method Phaser.Group#remove +* @param {any} child - The child to remove. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child. +* @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event. +* @return {boolean} true if the child was removed from this group, otherwise false. +*/ +Phaser.Group.prototype.remove = function (child, destroy, silent) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + + if (this.children.length === 0 || this.children.indexOf(child) === -1) + { + return false; + } + + if (!silent && child.events && !child.destroyPhase) + { + child.events.onRemovedFromGroup$dispatch(child, this); + } + + var removed = this.removeChild(child); + + this.removeFromHash(child); + + this.updateZ(); + + if (this.cursor === child) + { + this.next(); + } + + if (destroy && removed) + { + removed.destroy(true); + } + + return true; + +}; + +/** +* Moves all children from this Group to the Group given. +* +* @method Phaser.Group#moveAll +* @param {Phaser.Group} group - The new Group to which the children will be moved to. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group. +* @return {Phaser.Group} The Group to which all the children were moved. +*/ +Phaser.Group.prototype.moveAll = function (group, silent) { + + if (silent === undefined) { silent = false; } + + if (this.children.length > 0 && group instanceof Phaser.Group) + { + do + { + group.add(this.children[0], silent); + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + } + + return group; + +}; + +/** +* Removes all children from this Group, but does not remove the group from its parent. +* +* The children can be optionally destroyed as they are removed. +* +* You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've +* more than one Game Object sharing the same BaseTexture. +* +* @method Phaser.Group#removeAll +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +* @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. +*/ +Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + if (destroyTexture === undefined) { destroyTexture = false; } + + if (this.children.length === 0) + { + return; + } + + do + { + if (!silent && this.children[0].events) + { + this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this); + } + + var removed = this.removeChild(this.children[0]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true, destroyTexture); + } + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + +}; + +/** +* Removes all children from this group whose index falls beteen the given startIndex and endIndex values. +* +* @method Phaser.Group#removeBetween +* @param {integer} startIndex - The index to start removing children from. +* @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +*/ +Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) { + + if (endIndex === undefined) { endIndex = this.children.length - 1; } + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = 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 (!silent && this.children[i].events) + { + this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this); + } + + var removed = this.removeChild(this.children[i]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true); + } + + if (this.cursor === this.children[i]) + { + this.cursor = null; + } + + i--; + } + + this.updateZ(); + +}; + +/** + * Places each child at a random position within the given Rectangle (or the {@link Phaser.World#bounds World bounds}). + * + * @method Phaser.Group#scatter + * @param {Phaser.Rectangle} [rect=this.game.world.bounds] - A Rectangle. If omitted {@link Phaser.World#bounds} is used. + * @param {boolean} [checkExists=false] - Place only children with exists=true. + */ +Phaser.Group.prototype.scatter = function (rect, checkExists) { + + if (rect == null) { rect = this.game.world.bounds; } + + this.forEach(function (child) { + + child.position.set(rect.randomX, rect.randomY); + + }, null, checkExists); + +}; + +/** + * Orders this Group's children randomly. + * + * This can be more efficient than calling {@link #getRandom} repeatedly. + * + * @method Phaser.Group#shuffle + */ +Phaser.Group.prototype.shuffle = function () { + + Phaser.ArrayUtils.shuffle(this.children); + this.updateZ(); + +}; + +/** +* Destroys this group. +* +* Removes all children, then removes this group from its parent and nulls references. +* +* @method Phaser.Group#destroy +* @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. +*/ +Phaser.Group.prototype.destroy = function (destroyChildren, soft) { + + if (this.game === null || this.ignoreDestroy) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (soft === undefined) { soft = false; } + + this.onDestroy.dispatch(this, destroyChildren, soft); + + this.removeAll(destroyChildren); + + this.cursor = null; + this.filters = null; + this.pendingDestroy = false; + + if (!soft) + { + if (this.parent) + { + this.parent.removeChild(this); + } + + this.game = null; + this.exists = false; + } + +}; + +/** +* Total number of existing children in the group. +* +* @name Phaser.Group#total +* @property {integer} total +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "total", { + + get: function () { + + return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); + + } + +}); + +/** +* Total number of children in this group, regardless of exists/alive status. +* +* @name Phaser.Group#length +* @property {integer} length +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "length", { + + get: function () { + + return this.children.length; + + } + +}); + +/** +* The angle of rotation of the group container, in degrees. +* +* This adjusts the group itself by modifying its local rotation transform. +* +* This has no impact on the rotation/angle properties of the children, but it will update their worldTransform +* and on-screen orientation and position. +* +* @name Phaser.Group#angle +* @property {number} angle +*/ +Object.defineProperty(Phaser.Group.prototype, "angle", { + + get: function() { + return Phaser.Math.radToDeg(this.rotation); + }, + + set: function(value) { + this.rotation = Phaser.Math.degToRad(value); + } + +}); + +/** +* The center x coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerX +* @property {number} centerX +*/ +Object.defineProperty(Phaser.Group.prototype, "centerX", { + + get: function () { + + return this.getBounds(this.parent).centerX; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.halfWidth; + + } + +}); + +/** +* The center y coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerY +* @property {number} centerY +*/ +Object.defineProperty(Phaser.Group.prototype, "centerY", { + + get: function () { + + return this.getBounds(this.parent).centerY; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.halfHeight; + + } + +}); + +/** +* The left coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#left +* @property {number} left +*/ +Object.defineProperty(Phaser.Group.prototype, "left", { + + get: function () { + + return this.getBounds(this.parent).left; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = value + offset; + + } + +}); + +/** +* The right coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#right +* @property {number} right +*/ +Object.defineProperty(Phaser.Group.prototype, "right", { + + get: function () { + + return this.getBounds(this.parent).right; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.width; + + } + +}); + +/** +* The top coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#top +* @property {number} top +*/ +Object.defineProperty(Phaser.Group.prototype, "top", { + + get: function () { + + return this.getBounds(this.parent).top; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset); + + } + +}); + +/** +* The bottom coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#bottom +* @property {number} bottom +*/ +Object.defineProperty(Phaser.Group.prototype, "bottom", { + + get: function () { + + return this.getBounds(this.parent).bottom; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.height; + + } + +}); + +/** +* Aligns this Group within another Game Object, or Rectangle, known as the +* 'container', to one of 9 possible positions. +* +* The container must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the container. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, +* `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, +* `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* container, taking into consideration rotation and scale of its children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignIn +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* Aligns this Group to the side of another Game Object, or Rectangle, known as the +* 'parent', in one of 11 possible positions. +* +* The parent must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the parent. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, +* `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, +* `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` +* and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* parent, taking into consideration rotation and scale of the children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignTo +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* A display object is any object that can be rendered in the Phaser/pixi.js scene graph: +* +* - {@link PIXI.DisplayObject} +* - {@link PIXI.DisplayObjectContainer} +* - {@link Phaser.BitmapText} +* - {@link Phaser.Creature} +* - {@link Phaser.Graphics} +* - {@link Phaser.Group} +* - {@link Phaser.FlexLayer} +* - {@link Phaser.Particles.Arcade.Emitter} +* - {@link Phaser.Physics.P2.BodyDebug} +* - {@link Phaser.SpriteBatch} +* - {@link Phaser.World} +* - {@link Phaser.Rope} +* - {@link Phaser.Stage} +* - {@link PIXI.Sprite} +* - {@link Phaser.Image} +* - {@link Phaser.Button} +* - {@link Phaser.Sprite} +* - {@link Phaser.Bullet} +* - {@link Phaser.Particle} +* - {@link Phaser.Text} +* - {@link Phaser.TilemapLayer} +* - {@link Phaser.TileSprite} +* +* @typedef {object} DisplayObject +*/ +// Documentation stub for linking. + +/** +* The x coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#x +* @property {number} x +*/ + +/** +* The y coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#y +* @property {number} y +*/ + +/** +* The angle of rotation of the group container, in radians. +* +* This will adjust the group container itself by modifying its rotation. +* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#rotation +* @property {number} rotation +*/ + +/** +* The visible state of the group. Non-visible Groups and all of their children are not rendered. +* +* @name Phaser.Group#visible +* @property {boolean} visible +*/ + +/** +* The alpha value of the group container. +* +* @name Phaser.Group#alpha +* @property {number} alpha +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* "This world is but a canvas to our imagination." - Henry David Thoreau +* +* A game has only one world. The world is an abstract place in which all game objects live. It is not bound +* by stage limits and can be any size. You look into the world via cameras. All game objects live within +* the world at world-based coordinates. By default a world is created the same size as your Stage. +* +* @class Phaser.World +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.World = function (game) { + + Phaser.Group.call(this, game, null, '__world', false); + + /** + * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. + * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. + * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. + * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. + * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height); + + /** + * @property {Phaser.Camera} camera - Camera instance. + */ + this.camera = null; + + /** + * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. + * @readonly + */ + this._definedSize = false; + + /** + * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._width = game.width; + + /** + * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._height = game.height; + + this.game.state.onStateChange.add(this.stateChange, this); + +}; + +Phaser.World.prototype = Object.create(Phaser.Group.prototype); +Phaser.World.prototype.constructor = Phaser.World; + +/** +* Initialises the game world. +* +* @method Phaser.World#boot +* @protected +*/ +Phaser.World.prototype.boot = function () { + + this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height); + + this.game.stage.addChild(this); + + this.camera.boot(); + +}; + +/** +* Called whenever the State changes or resets. +* +* It resets the world.x and world.y coordinates back to zero, +* then resets the Camera. +* +* @method Phaser.World#stateChange +* @protected +*/ +Phaser.World.prototype.stateChange = function () { + + this.x = 0; + this.y = 0; + + this.camera.reset(); + +}; + +/** +* Updates the size of this world and sets World.x/y to the given values +* The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. +* +* @method Phaser.World#setBounds +* @param {number} x - Top left most corner of the world. +* @param {number} y - Top left most corner of the world. +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.setBounds = function (x, y, width, height) { + + this._definedSize = true; + this._width = width; + this._height = height; + + this.bounds.setTo(x, y, width, height); + + this.x = x; + this.y = y; + + if (this.camera.bounds) + { + // The Camera can never be smaller than the game size + this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height)); + } + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Updates this world's width and height (but not smaller than any previous {@link #setBounds defined size}). +* +* Phaser uses this to adapt to {@link Phaser.ScaleManager#updateDimensions layout changes}. +* You probably want to use {@link #setBounds} instead. +* +* @method Phaser.World#resize +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.resize = function (width, height) { + + // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size + + if (this._definedSize) + { + if (width < this._width) + { + width = this._width; + } + + if (height < this._height) + { + height = this._height; + } + } + + this.bounds.width = width; + this.bounds.height = height; + + this.game.camera.setBoundsToWorld(); + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Destroyer of worlds. +* +* @method Phaser.World#shutdown +*/ +Phaser.World.prototype.shutdown = function () { + + // World is a Group, so run a soft destruction on this and all children. + this.destroy(true, true); + +}; + +/** +* This will take the given game object and check if its x/y coordinates fall outside of the world bounds. +* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. +* If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. +* +* Please understand there are limitations to this method. For example if you have scaled the World +* then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. +* +* @method Phaser.World#wrap +* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) { + + if (padding === undefined) { padding = 0; } + if (useBounds === undefined) { useBounds = false; } + if (horizontal === undefined) { horizontal = true; } + if (vertical === undefined) { vertical = true; } + + if (!useBounds) + { + if (horizontal && sprite.x + padding < this.bounds.x) + { + sprite.x = this.bounds.right + padding; + } + else if (horizontal && sprite.x - padding > this.bounds.right) + { + sprite.x = this.bounds.left - padding; + } + + if (vertical && sprite.y + padding < this.bounds.top) + { + sprite.y = this.bounds.bottom + padding; + } + else if (vertical && sprite.y - padding > this.bounds.bottom) + { + sprite.y = this.bounds.top - padding; + } + } + else + { + sprite.getBounds(); + + if (horizontal) + { + if ((sprite.x + sprite._currentBounds.width) < this.bounds.x) + { + sprite.x = this.bounds.right; + } + else if (sprite.x > this.bounds.right) + { + sprite.x = this.bounds.left; + } + } + + if (vertical) + { + if ((sprite.y + sprite._currentBounds.height) < this.bounds.top) + { + sprite.y = this.bounds.bottom; + } + else if (sprite.y > this.bounds.bottom) + { + sprite.y = this.bounds.top; + } + } + } + +}; + +/** +* @method Phaser.World#wrapAll +* @param {Phaser.Group} group - A group of sprites. +* @param {boolean} [checkExists=false] - Wrap only sprites having `exists=true`. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrapAll = function (group, checkExists, padding, useBounds, horizontal, vertical) { + + group.forEach(this.wrap, this, checkExists, padding, useBounds, horizontal, vertical); + +}; + +/** +* @name Phaser.World#width +* @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "width", { + + get: function () { + return this.bounds.width; + }, + + set: function (value) { + + if (value < this.game.width) + { + value = this.game.width; + } + + this.bounds.width = value; + this._width = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#height +* @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "height", { + + get: function () { + return this.bounds.height; + }, + + set: function (value) { + + if (value < this.game.height) + { + value = this.game.height; + } + + this.bounds.height = value; + this._height = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#centerX +* @property {number} centerX - Gets the X position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerX", { + + get: function () { + return this.bounds.halfWidth + this.bounds.x; + } + +}); + +/** +* @name Phaser.World#centerY +* @property {number} centerY - Gets the Y position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerY", { + + get: function () { + return this.bounds.halfHeight + this.bounds.y; + } + +}); + +/** +* @name Phaser.World#randomX +* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomX", { + + get: function () { + + if (this.bounds.x < 0) + { + return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x))); + } + else + { + return this.game.rnd.between(this.bounds.x, this.bounds.width); + } + + } + +}); + +/** +* @name Phaser.World#randomY +* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomY", { + + get: function () { + + if (this.bounds.y < 0) + { + return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y))); + } + else + { + return this.game.rnd.between(this.bounds.y, this.bounds.height); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Game object is the main controller for the entire Phaser game. It is responsible +* for handling the boot process, parsing the configuration values, creating the renderer, +* and setting-up all of the Phaser systems, such as physics, sound and input. +* Once that is complete it will start the default State, and then begin the main game loop. +* +* You can access lots of the Phaser systems via the properties on the `game` object. For +* example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on. +* +* Anywhere you can access the `game` property, you can access all of these core systems. +* For example a Sprite has a `game` property, allowing you to talk to the various parts +* of Phaser directly, without having to look after your own references. +* +* In it's most simplest form, a Phaser game can be created by providing the arguments +* to the constructor: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create }); +* ``` +* +* In the example above it is passing in a State object directly. You can also use the State +* Manager to do this: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO); +* game.state.add('Boot', BasicGame.Boot); +* game.state.add('Preloader', BasicGame.Preloader); +* game.state.add('MainMenu', BasicGame.MainMenu); +* game.state.add('Game', BasicGame.Game); +* game.state.start('Boot'); +* ``` +* +* In the example above, 4 States are added to the State Manager, and Phaser is told to +* start running the `Boot` state when it has finished initializing. There are example +* project templates you can use in the Phaser GitHub repo, inside the `resources` folder. +* +* Instead of specifying arguments you can also pass {@link GameConfig a single object} instead: +* +* ```javascript +* var config = { +* width: 800, +* height: 600, +* renderer: Phaser.AUTO, +* antialias: true, +* multiTexture: true, +* state: { +* preload: preload, +* create: create, +* update: update +* } +* } +* +* var game = new Phaser.Game(config); +* ``` +* +* @class Phaser.Game +* @constructor +* @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. +* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. +* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). +* @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body. +* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. +* @param {boolean} [transparent=false] - Use a transparent canvas background or not. +* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) { + + /** + * @property {number} id - Phaser Game ID + * @readonly + */ + this.id = Phaser.GAMES.push(this) - 1; + + /** + * @property {object} config - The Phaser.Game configuration object. + */ + this.config = null; + + /** + * @property {object} physicsConfig - The Phaser.Physics.World configuration object. + */ + this.physicsConfig = physicsConfig; + + /** + * @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted. + * @readonly + * @default + */ + this.parent = ''; + + /** + * The current Game Width in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} width + * @readonly + * @default + */ + this.width = 800; + + /** + * The current Game Height in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} height + * @readonly + * @default + */ + this.height = 600; + + /** + * The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object. + * + * @property {integer} resolution + * @readonly + * @default + */ + this.resolution = 1; + + /** + * @property {integer} _width - Private internal var. + * @private + */ + this._width = 800; + + /** + * @property {integer} _height - Private internal var. + * @private + */ + this._height = 600; + + /** + * @property {boolean} transparent - Use a transparent canvas background or not. + * @default + */ + this.transparent = false; + + /** + * @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead. + * @readonly + * @default + */ + this.antialias = true; + + /** + * Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property. + * To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game + * Configuration object with the property `multiTexture` set to true. It has to be enabled before + * Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it + * via the `game.renderer.setTexturePriority` method. + * + * @property {boolean} multiTexture + * @readonly + * @default + */ + this.multiTexture = false; + + /** + * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * @default + */ + this.preserveDrawingBuffer = false; + + /** + * Clear the Canvas each frame before rendering the display list. + * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. + * This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage. + * @property {boolean} clearBeforeRender + * @default + */ + this.clearBeforeRender = true; + + /** + * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. + * @protected + */ + this.renderer = null; + + /** + * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `render` hooks but not `preRender` or `postRender`; set {@link lockRender} to skip those as well. + * @readonly + */ + this.renderType = Phaser.AUTO; + + /** + * @property {Phaser.StateManager} state - The StateManager. + */ + this.state = null; + + /** + * @property {boolean} isBooted - Whether the game engine is booted, aka available. + * @readonly + */ + this.isBooted = false; + + /** + * @property {boolean} isRunning - Is game running or paused? + * @readonly + */ + this.isRunning = false; + + /** + * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout + * @protected + */ + this.raf = null; + + /** + * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. + */ + this.make = null; + + /** + * @property {Phaser.Cache} cache - Reference to the assets cache. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - Reference to the input manager + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - Reference to the assets loader. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - Reference to the math helper. + */ + this.math = null; + + /** + * @property {Phaser.Net} net - Reference to the network class. + */ + this.net = null; + + /** + * @property {Phaser.ScaleManager} scale - The game scale manager. + */ + this.scale = null; + + /** + * @property {Phaser.SoundManager} sound - Reference to the sound manager. + */ + this.sound = null; + + /** + * @property {Phaser.Stage} stage - Reference to the stage. + */ + this.stage = null; + + /** + * @property {Phaser.Time} time - Reference to the core game clock. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - Reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - Reference to the world. + */ + this.world = null; + + /** + * @property {Phaser.Physics} physics - Reference to the physics manager. + */ + this.physics = null; + + /** + * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. + */ + this.plugins = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. + */ + this.rnd = null; + + /** + * @property {Phaser.Device} device - Contains device information and capabilities. + */ + this.device = Phaser.Device; + + /** + * @property {Phaser.Camera} camera - A handy reference to world.camera. + */ + this.camera = null; + + /** + * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) + */ + this.context = null; + + /** + * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. + */ + this.debug = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. + */ + this.particles = null; + + /** + * @property {Phaser.Create} create - The Asset Generator. + */ + this.create = null; + + /** + * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. + * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. + * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. + * @property {boolean} lockRender + * @default + */ + this.lockRender = false; + + /** + * @property {boolean} pendingDestroy - Destroy the game at the next update. + * @default + */ + this.pendingDestroy = false; + + /** + * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). + * @default + * @readonly + */ + this.stepping = false; + + /** + * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. + * @default + * @readonly + */ + this.pendingStep = false; + + /** + * @property {number} stepCount - When stepping is enabled this contains the current step cycle. + * @default + * @readonly + */ + this.stepCount = 0; + + /** + * @property {Phaser.Signal} onPause - This event is fired when the game pauses. + */ + this.onPause = null; + + /** + * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. + */ + this.onResume = null; + + /** + * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). + */ + this.onBlur = null; + + /** + * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). + */ + this.onFocus = null; + + /** + * @property {boolean} _paused - Is game paused? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _codePaused - Was the game paused via code or a visibility change? + * @private + */ + this._codePaused = false; + + /** + * The ID of the current/last logic update applied this animation frame, starting from 0. + * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` + * @property {integer} currentUpdateID + * @protected + */ + this.currentUpdateID = 0; + + /** + * Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed). + * @property {integer} updatesThisFrame + * @protected + */ + this.updatesThisFrame = 1; + + /** + * Number of renders expected to occur this animation frame. May be 0 if {@link #dropFrames is on} or {@link #forceSingleRender} is off; otherwise it will be 1. + * @property {integer} updatesThisFrame + * @protected + */ + this.rendersThisFrame = 1; + + /** + * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. + * @private + */ + this._deltaTime = 0; + + /** + * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. + * @private + */ + this._lastCount = 0; + + /** + * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. + * @private + */ + this._spiraling = 0; + + /** + * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) + * @private + */ + this._kickstart = true; + + /** + * If the game is struggling to maintain the desired FPS, this signal will be dispatched. + * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. + * @property {Phaser.Signal} fpsProblemNotifier + * @public + */ + this.fpsProblemNotifier = new Phaser.Signal(); + + /** + * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? You can toggle it on the fly. + */ + this.forceSingleUpdate = true; + + /** + * @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update? (During spiraling conditions, {@link #dropFrames} is used instead.) + */ + this.forceSingleRender = true; + + /** + * @property {boolean} dropFrames - When {@link #forceSingleUpdate} is off, skip {@link #updateRender rendering} if logic updates are spiraling upwards. + */ + this.dropFrames = false; + + /** + * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. + * @private + */ + this._nextFpsNotification = 0; + + // Parse the configuration object (if any) + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + this.parseConfig(arguments[0]); + } + else + { + this.config = { enableDebug: true }; + + if (typeof width !== 'undefined') + { + this._width = width; + } + + if (typeof height !== 'undefined') + { + this._height = height; + } + + if (typeof renderer !== 'undefined') + { + 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); + } + + this.device.whenReady(this.boot, this); + + return this; + +}; + +/** +* A configuration object for {@link Phaser.Game}. +* +* @typedef {object} GameConfig +* @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}. +* @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}. +* @property {number|string} [GameConfig.antialias=true] +* @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}. +* @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in. +* @property {string} [GameConfig.canvasId] - `id` attribute value to assign to the game canvas. +* @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas. +* @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}. +* @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange} +* @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing. +* @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production. +* @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO. +* @property {boolean} [GameConfig.forceSetTimeout] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeOut} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available. +* @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen. +* @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked. +* @property {number|string} [GameConfig.height=600] +* @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`. +* @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected. +* @property {object} [GameConfig.physicsConfig] +* @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering. +* @property {number} [GameConfig.renderer=Phaser.AUTO] +* @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels. +* @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices. +* @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen. +* @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}. +* @property {object} [GameConfig.state] +* @property {boolean} [GameConfig.transparent=false] +* @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode. +* @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode. +* @property {number|string} [GameConfig.width=800] +*/ +// Documentation stub for linking. + +Phaser.Game.prototype = { + + /** + * Parses a Game configuration object. + * + * @method Phaser.Game#parseConfig + * @protected + */ + parseConfig: function (config) { + + this.config = config; + + if (config['enableDebug'] === undefined) + { + this.config.enableDebug = true; + } + + if (config['width']) + { + this._width = config['width']; + } + + if (config['height']) + { + this._height = config['height']; + } + + if (config['renderer']) + { + this.renderType = config['renderer']; + } + + if (config['parent']) + { + this.parent = config['parent']; + } + + if (config['transparent'] !== undefined) + { + this.transparent = config['transparent']; + } + + if (config['antialias'] !== undefined) + { + this.antialias = config['antialias']; + } + + if (config['multiTexture'] !== undefined) + { + this.multiTexture = config['multiTexture']; + } + + if (config['resolution']) + { + this.resolution = config['resolution']; + } + + if (config['preserveDrawingBuffer'] !== undefined) + { + this.preserveDrawingBuffer = config['preserveDrawingBuffer']; + } + + 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); + + }, + + /** + * Initialize engine sub modules and start the game. + * + * @method Phaser.Game#boot + * @protected + */ + boot: function () { + + if (this.isBooted) + { + return; + } + + this.onPause = new Phaser.Signal(); + this.onResume = new Phaser.Signal(); + this.onBlur = new Phaser.Signal(); + this.onFocus = new Phaser.Signal(); + + this.isBooted = true; + + PIXI.game = this; + + this.math = Phaser.Math; + + this.scale = new Phaser.ScaleManager(this, this._width, this._height); + this.stage = new Phaser.Stage(this); + + this.setUpRenderer(); + + 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.create = new Phaser.Create(this); + this.plugins = new Phaser.PluginManager(this); + this.net = new Phaser.Net(this); + + this.time.boot(); + this.stage.boot(); + this.world.boot(); + this.scale.boot(); + this.input.boot(); + this.sound.boot(); + this.state.boot(); + + if (this.config['enableDebug']) + { + this.debug = new Phaser.Utils.Debug(this); + this.debug.boot(); + } + else + { + this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {}, isDisabled: true }; + } + + 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._kickstart = true; + + if (window['focus']) + { + if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus)) + { + window.focus(); + } + } + + if (this.config['disableStart']) + { + return; + } + + if (this.cache.isReady) + { + this.raf.start(); + } + else + { + this.cache.onReady.addOnce(function () { + this.raf.start(); + }, this); + } + + }, + + /** + * Displays a Phaser version debug header in the console. + * + * @method Phaser.Game#showDebugHeader + * @protected + */ + showDebugHeader: function () { + + if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner) + { + return; + } + + 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.ie) // https://developer.mozilla.org/en-US/docs/Web/API/Console/log#Browser_compatibility + { + var args = [ + '%c %c %c Phaser CE v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665', + 'background: #fb8cb3', + 'background: #d44a52', + 'color: #ffffff; background: #871905;', + 'background: #d44a52', + 'background: #fb8cb3', + 'background: #ffffff' + ]; + + for (var i = 0; i < 3; i++) + { + if (i < c) + { + args.push('color: #ff2424; background: #fff'); + } + else + { + args.push('color: #959595; background: #fff'); + } + } + + console.log.apply(console, args); + } + else if (window['console']) + { + console.log('Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' | http://phaser.io'); + } + + }, + + /** + * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. + * + * @method Phaser.Game#setUpRenderer + * @protected + */ + setUpRenderer: function () { + + if (!this.device.canvas) + { + // Nothing else to do + throw new Error('Phaser.Game - Cannot create Canvas 2d context, aborting.'); + } + + if (this.config['canvas']) + { + this.canvas = this.config['canvas']; + } + else + { + this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true); + } + + if (this.config['canvasStyle']) + { + this.canvas.style = this.config['canvasStyle']; + } + else + { + this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; + } + + if (this.config['crisp']) + { + Phaser.Canvas.setImageRenderingCrisp(this.canvas); + } + + if ((this.renderType === Phaser.WEBGL) || + (this.renderType === Phaser.WEBGL_MULTI) || + (this.renderType === Phaser.AUTO && this.device.webGL)) + { + if (this.multiTexture || this.renderType === Phaser.WEBGL_MULTI) + { + PIXI.enableMultiTexture(); + this.multiTexture = true; + } + + try + { + this.renderer = new PIXI.WebGLRenderer(this, this.config); + this.renderType = Phaser.WEBGL; + this.context = null; + this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); + this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); + } + catch (webGLRendererError) + { + this.renderer = null; + this.multiTexture = false; + PIXI._enableMultiTextureToggle = false; + + if (this.renderType === Phaser.WEBGL) + { + // No fallback + throw webGLRendererError; + } + } + } + + if (!this.renderer) + { + this.renderer = new PIXI.CanvasRenderer(this, this.config); + this.context = this.renderer.context; + + if (this.renderType === Phaser.AUTO) + { + this.renderType = Phaser.CANVAS; + } + } + + if (this.device.cocoonJS) + { + this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false; + } + + if (this.renderType !== Phaser.HEADLESS) + { + this.stage.smoothed = this.antialias; + + Phaser.Canvas.addToDOM(this.canvas, this.parent, false); + Phaser.Canvas.setTouchAction(this.canvas); + } + + }, + + /** + * Handles WebGL context loss. + * + * @method Phaser.Game#contextLost + * @private + * @param {Event} event - The webglcontextlost event. + */ + contextLost: function (event) { + + event.preventDefault(); + + this.renderer.contextLost = true; + + }, + + /** + * Handles WebGL context restoration. + * + * @method Phaser.Game#contextRestored + * @private + */ + contextRestored: function () { + + this.renderer.initContext(); + + this.cache.clearGLTextures(); + + this.renderer.contextLost = false; + + }, + + /** + * The core game loop. + * + * @method Phaser.Game#update + * @protected + * @param {number} time - The current time as provided by RequestAnimationFrame. + */ + update: function (time) { + + if (this.pendingDestroy) + { + this.destroy(); + return; + } + + this.time.update(time); + + if (this._kickstart) + { + this.updateLogic(this.time.desiredFpsMult); + + // call the game render update exactly once every frame + this.updateRender(this.time.slowMotion * this.time.desiredFps); + + this._kickstart = false; + + return; + } + + // if the logic time is spiraling upwards, skip a frame entirely + if (this._spiraling > 1 && !this.forceSingleUpdate) + { + // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate + if (this.time.time > this._nextFpsNotification) + { + // only permit one fps notification per 10 seconds + this._nextFpsNotification = this.time.time + 10000; + + // dispatch the notification signal + this.fpsProblemNotifier.dispatch(); + } + + // reset the _deltaTime accumulator which will cause all pending late updates to be permanently skipped + this._deltaTime = 0; + this._spiraling = 0; + + if (this.dropFrames) + { + this.rendersThisFrame = 0; + } + else + { + this.updateRender(this.time.slowMotion * this.time.desiredFps); + this.rendersThisFrame = 1; + } + } + else + { + // step size taking into account the slow motion speed + var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps; + + // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals + this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0); + + // call the game update logic multiple times if necessary to "catch up" with dropped frames + // unless forceSingleUpdate is true + var count = 0; + + this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); + + if (this.forceSingleUpdate) + { + this.updatesThisFrame = Math.min(1, this.updatesThisFrame); + } + + if (this.forceSingleRender) + { + this.rendersThisFrame = 1; + } + else + { + this.rendersThisFrame = Math.min(1, this.updatesThisFrame); + } + + while (this._deltaTime >= slowStep) + { + this._deltaTime -= slowStep; + this.currentUpdateID = count; + + this.updateLogic(this.time.desiredFpsMult); + + count++; + + if (this.forceSingleUpdate && count === 1) + { + break; + } + else + { + this.time.refresh(); + } + } + + // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly) + if (count > this._lastCount) + { + this._spiraling++; + } + else if (count < this._lastCount) + { + // looks like it caught up successfully, reset the spiral alert counter + this._spiraling = 0; + } + + this._lastCount = count; + + if (this.rendersThisFrame > 0) + { + this.updateRender(this._deltaTime / slowStep); + } + } + + }, + + /** + * Updates all logic subsystems in Phaser. Called automatically by Game.update. + * + * @method Phaser.Game#updateLogic + * @protected + * @param {number} timeStep - The current timeStep value as determined by Game.update. + */ + updateLogic: function (timeStep) { + + if (!this._paused && !this.pendingStep) + { + if (this.stepping) + { + this.pendingStep = true; + } + + this.time.countUpdate(); + + this.scale.preUpdate(); + this.debug.preUpdate(); + this.camera.preUpdate(); + this.physics.preUpdate(); + this.state.preUpdate(timeStep); + this.plugins.preUpdate(timeStep); + this.stage.preUpdate(); + + this.state.update(); + this.stage.update(); + this.tweens.update(); + this.sound.update(); + this.input.update(); + this.physics.update(); + this.plugins.update(); + + this.stage.postUpdate(); + this.plugins.postUpdate(); + } + else + { + // Scaling and device orientation changes are still reflected when paused. + this.scale.pauseUpdate(); + this.state.pauseUpdate(timeStep); + this.debug.preUpdate(); + this.input.pauseUpdate(); + } + + this.stage.updateTransform(); + + }, + + /** + * Runs the Render cycle. + * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. + * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. + * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. + * After this State.render is called. Any rendering that happens here will take place on-top of the display list. + * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. + * This method is called automatically by Game.update, you don't need to call it directly. + * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. + * Phaser will only render when this boolean is `false`. + * + * @method Phaser.Game#updateRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + updateRender: function (elapsedTime) { + + if (this.lockRender) + { + return; + } + + this.time.countRender(); + + this.state.preRender(elapsedTime); + + if (this.renderType !== Phaser.HEADLESS) + { + this.renderer.render(this.stage); + + this.plugins.render(elapsedTime); + + this.state.render(elapsedTime); + } + + this.plugins.postRender(elapsedTime); + + }, + + /** + * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) + * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! + * + * @method Phaser.Game#enableStep + */ + enableStep: function () { + + this.stepping = true; + this.pendingStep = false; + this.stepCount = 0; + + }, + + /** + * Disables core game loop stepping. + * + * @method Phaser.Game#disableStep + */ + disableStep: function () { + + this.stepping = false; + this.pendingStep = false; + + }, + + /** + * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. + * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. + * + * @method Phaser.Game#step + */ + step: function () { + + this.pendingStep = false; + this.stepCount++; + + }, + + /** + * Nukes the entire game from orbit. + * + * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. + * + * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM + * and resets the PIXI default renderer. + * + * To destroy the game during an update callback, set {@link #pendingDestroy} instead. + * + * @method Phaser.Game#destroy + */ + destroy: function () { + + this.raf.stop(); + + if (this.debug.destroy) + { + this.debug.destroy(); + } + + this.state.destroy(); + this.sound.destroy(); + this.scale.destroy(); + this.stage.destroy(); + this.input.destroy(); + this.physics.destroy(); + this.plugins.destroy(); + + this.debug = null; + this.state = null; + this.sound = null; + this.scale = null; + this.stage = null; + this.input = null; + this.physics = null; + this.plugins = null; + + this.cache = null; + this.load = null; + this.time = null; + this.world = null; + + this.isBooted = false; + + this.renderer.destroy(false); + + Phaser.Canvas.removeFromDOM(this.canvas); + + PIXI.defaultRenderer = null; + + Phaser.GAMES[this.id] = null; + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gamePaused + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gamePaused: function (event) { + + // If the game is already paused it was done via game code, so don't re-pause it + if (!this._paused) + { + this._paused = true; + + this.time.gamePaused(); + + if (this.sound.muteOnPause) + { + this.sound.setMute(); + } + + this.onPause.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = true; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gameResumed + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gameResumed: function (event) { + + // Game is paused, but wasn't paused via code, so resume it + if (this._paused && !this._codePaused) + { + this._paused = false; + + this.time.gameResumed(); + + this.input.reset(); + + if (this.sound.muteOnPause) + { + this.sound.unsetMute(); + } + + this.onResume.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = false; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusLoss + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusLoss: function (event) { + + this.onBlur.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gamePaused(event); + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusGain + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusGain: function (event) { + + this.onFocus.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gameResumed(event); + } + + } + +}; + +Phaser.Game.prototype.constructor = Phaser.Game; + +/** +* The paused state of the Game. A paused game doesn't update any of its subsystems. +* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. +* @name Phaser.Game#paused +* @property {boolean} paused - Gets and sets the paused state of the Game. +*/ +Object.defineProperty(Phaser.Game.prototype, "paused", { + + get: function () { + return this._paused; + }, + + set: function (value) { + + if (value === true) + { + if (this._paused === false) + { + this._paused = true; + this.sound.setMute(); + this.time.gamePaused(); + this.onPause.dispatch(this); + } + this._codePaused = true; + } + else + { + if (this._paused) + { + this._paused = false; + this.input.reset(); + this.sound.unsetMute(); + this.time.gameResumed(); + this.onResume.dispatch(this); + } + this._codePaused = false; + } + + } + +}); + +/** + * + * "Deleted code is debugged code." - Jeff Sickel + * + * ヽ(〃^▽^〃)ノ + * +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. +* The Input manager is updated automatically by the core game loop. +* +* @class Phaser.Input +* @constructor +* @param {Phaser.Game} game - Current game instance. +*/ +Phaser.Input = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. + * @default + */ + this.hitCanvas = null; + + /** + * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. + * @default + */ + this.hitContext = null; + + /** + * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. + * To add a callback to this array please use `Input.addMoveCallback`. + * @property {array} moveCallbacks + * @protected + */ + this.moveCallbacks = []; + + /** + * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandler = null; + + /** + * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandlerContext = null; + + /** + * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. + * @default + */ + this.pollRate = 0; + + /** + * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. + * + * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. + * @default + */ + this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE; + + /** + * @property {Phaser.Point} position - A point object representing the current position of the Pointer. + * @default + */ + this.position = null; + + /** + * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. + */ + this.speed = null; + + /** + * A Circle object centered on the x/y screen coordinates of the Input. + * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. + * @property {Phaser.Circle} circle + */ + this.circle = null; + + /** + * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. + */ + this.scale = null; + + /** + * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1. + * @default -1 (Limited by total pointers.) + */ + this.maxPointers = -1; + + /** + * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. + * @default + */ + this.tapRate = 200; + + /** + * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. + * @default + */ + this.doubleTapRate = 300; + + /** + * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. + * @default + */ + this.holdRate = 2000; + + /** + * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. + * @default + */ + this.justPressedRate = 200; + + /** + * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . + * @default + */ + this.justReleasedRate = 200; + + /** + * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. + * The history is cleared each time the Pointer is pressed down. + * The history is updated at the rate specified in Input.pollRate + * @property {boolean} recordPointerHistory + * @default + */ + this.recordPointerHistory = false; + + /** + * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. + * @default + */ + this.recordRate = 100; + + /** + * The total number of entries that can be recorded into the Pointer objects tracking history. + * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. + * @property {number} recordLimit + * @default + */ + this.recordLimit = 100; + + /** + * An array of callbacks that will be fired every time a native touch start or touch end event (pointerdown or pointerup when using Pointer events) is received from the browser. + * This is used internally to handle audio and video unlocking on mobile devices. + * To add a callback to this array please use `Input.addTouchLockCallback`. + * @property {array} touchLockCallbacks + * @protected + */ + this.touchLockCallbacks = []; + + /** + * @property {Phaser.Pointer} pointer1 - A Pointer object. + */ + this.pointer1 = null; + + /** + * @property {Phaser.Pointer} pointer2 - A Pointer object. + */ + this.pointer2 = null; + + /** + * @property {Phaser.Pointer} pointer3 - A Pointer object. + */ + this.pointer3 = null; + + /** + * @property {Phaser.Pointer} pointer4 - A Pointer object. + */ + this.pointer4 = null; + + /** + * @property {Phaser.Pointer} pointer5 - A Pointer object. + */ + this.pointer5 = null; + + /** + * @property {Phaser.Pointer} pointer6 - A Pointer object. + */ + this.pointer6 = null; + + /** + * @property {Phaser.Pointer} pointer7 - A Pointer object. + */ + this.pointer7 = null; + + /** + * @property {Phaser.Pointer} pointer8 - A Pointer object. + */ + this.pointer8 = null; + + /** + * @property {Phaser.Pointer} pointer9 - A Pointer object. + */ + this.pointer9 = null; + + /** + * @property {Phaser.Pointer} pointer10 - A Pointer object. + */ + this.pointer10 = null; + + /** + * An array of non-mouse pointers that have been added to the game. + * The properties `pointer1..N` are aliases for `pointers[0..N-1]`. + * @property {Phaser.Pointer[]} pointers + * @public + * @readonly + */ + this.pointers = []; + + /** + * The most recently active Pointer object. + * + * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. + * + * @property {Phaser.Pointer} activePointer + */ + this.activePointer = null; + + /** + * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. + * + * @property {Pointer} mousePointer + */ + this.mousePointer = null; + + /** + * The Mouse Input manager. + * + * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Mouse} mouse + */ + this.mouse = null; + + /** + * The Keyboard Input manager. + * + * @property {Phaser.Keyboard} keyboard + */ + this.keyboard = null; + + /** + * The Touch Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Touch} touch + */ + this.touch = null; + + /** + * The MSPointer Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.MSPointer} mspointer + */ + this.mspointer = null; + + /** + * The Gamepad Input manager. + * + * @property {Phaser.Gamepad} gamepad + */ + this.gamepad = null; + + /** + * If the Input Manager has been reset locked then all calls made to InputManager.reset, + * such as from a State change, are ignored. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is pressed down. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onDown + */ + this.onDown = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is released. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onUp + */ + this.onUp = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is tapped. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {boolean} True if this was a double tap. + * + * @property {Phaser.Signal} onTap + */ + this.onTap = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is held down. + * It is sent one argument: + * + * - {Phaser.Pointer} The pointer that caused the event. + * + * @property {Phaser.Signal} onHold + */ + this.onHold = null; + + /** + * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. + * This is useful when stacking UI layers. Set to zero to disable. + * @property {number} minPriorityID + * @default + */ + this.minPriorityID = 0; + + /** + * A list of interactive objects. The InputHandler components add and remove themselves from this list. + * @property {Phaser.ArraySet} interactiveItems + */ + this.interactiveItems = new Phaser.ArraySet(); + + /** + * @property {Phaser.Point} _localPoint - Internal cache var. + * @private + */ + this._localPoint = new Phaser.Point(); + + /** + * @property {number} _pollCounter - Internal var holding the current poll counter. + * @private + */ + this._pollCounter = 0; + + /** + * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. + * @private + */ + this._oldPosition = null; + + /** + * @property {number} _x - x coordinate of the most recent Pointer event + * @private + */ + this._x = 0; + + /** + * @property {number} _y - Y coordinate of the most recent Pointer event + * @private + */ + this._y = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_TOUCH_COMBINE = 2; + +/** +* The maximum number of pointers that can be added. This excludes the mouse pointer. +* @constant +* @type {integer} +*/ +Phaser.Input.MAX_POINTERS = 10; + +Phaser.Input.prototype = { + + /** + * Starts the Input Manager running. + * + * @method Phaser.Input#boot + * @protected + */ + boot: function () { + + this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR); + this.addPointer(); + this.addPointer(); + + this.mouse = new Phaser.Mouse(this.game); + this.touch = new Phaser.Touch(this.game); + this.mspointer = new Phaser.MSPointer(this.game); + + if (Phaser.Keyboard) + { + this.keyboard = new Phaser.Keyboard(this.game); + } + + if (Phaser.Gamepad) + { + this.gamepad = new Phaser.Gamepad(this.game); + } + + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + + this.scale = new Phaser.Point(1, 1); + this.speed = new Phaser.Point(); + this.position = new Phaser.Point(); + this._oldPosition = new Phaser.Point(); + + this.circle = new Phaser.Circle(0, 0, 44); + + this.activePointer = this.mousePointer; + + this.hitCanvas = Phaser.CanvasPool.create(this, 1, 1); + this.hitContext = this.hitCanvas.getContext('2d'); + + this.mouse.start(); + if (!this.game.device.mspointer) + { + // Chrome >= 55 fires both PointerEvent and TouchEvent. + // Pick only one. + this.touch.start(); + } + this.mspointer.start(); + this.mousePointer.active = true; + + if (this.keyboard) + { + this.keyboard.start(); + } + + var _this = this; + + this._onClickTrampoline = function (event) { + _this.onClickTrampoline(event); + }; + + this.game.canvas.addEventListener('click', this._onClickTrampoline, false); + + }, + + /** + * Stops all of the Input Managers from running. + * + * @method Phaser.Input#destroy + */ + destroy: function () { + + this.mouse.stop(); + this.touch.stop(); + this.mspointer.stop(); + + if (this.keyboard) + { + this.keyboard.stop(); + } + + if (this.gamepad) + { + this.gamepad.stop(); + } + + this.moveCallbacks = []; + + Phaser.CanvasPool.remove(this); + + this.game.canvas.removeEventListener('click', this._onClickTrampoline); + + }, + + /** + * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. + * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to + * interact with. It works by polling all of the valid game objects, and then slowly discounting those + * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). + * + * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid + * for input and overlap with the Pointer. If you need fine-grained control over which of the items is + * selected then you can use this callback to do so. + * + * The callback will be sent 3 parameters: + * + * 1) A reference to the Phaser.Pointer object that is processing the Items. + * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. + * 3) The current 'favorite' candidate, based on its priorityID and position in the display list. + * + * Your callback MUST return one of the candidates sent to it. + * + * @method Phaser.Input#setInteractiveCandidateHandler + * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. + * @param {object} context - The context in which the callback will be called. + */ + setInteractiveCandidateHandler: function (callback, context) { + + this.customCandidateHandler = callback; + this.customCandidateHandlerContext = context; + + }, + + /** + * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. + * + * The callback will be sent 4 parameters: + * + * A reference to the Phaser.Pointer object that moved, + * The x position of the pointer, + * The y position, + * A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down). + * + * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best + * to only use if you've limited input to a single pointer (i.e. mouse or touch). + * + * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. + * + * @method Phaser.Input#addMoveCallback + * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. + * @param {object} context - The context in which the callback will be called. + */ + addMoveCallback: function (callback, context) { + + this.moveCallbacks.push({ callback: callback, context: context }); + + }, + + + /** + * Adds a callback that is fired when a browser touchstart/pointerdown or touchend/pointerup event is received. + * + * This is used internally to handle audio and video unlocking on mobile devices. + * + * If the callback returns 'true' then the callback is automatically deleted once invoked. + * + * The callback is added to the {@link #touchLockCallbacks} array and should be removed with {@link #removeTouchLockCallback}. + * + * @method Phaser.Input#addTouchLockCallback + * @param {function} callback - The callback that will be called when a touchstart event is received. + * @param {object} context - The context in which the callback will be called. + * @param {boolean} [onEnd=false] - Will the callback fire on a touchstart/pointerdown (default) or touchend/pointerup event? + */ + addTouchLockCallback: function (callback, context, onEnd) { + + if (onEnd === undefined) { onEnd = false; } + + this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd }); + + }, + + /** + * Removes the callback at the defined index from the {@link #touchLockCallbacks} array + * + * @method Phaser.Input#removeTouchLockCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + * @return {boolean} True if the callback was deleted, otherwise false. + */ + removeTouchLockCallback: function (callback, context) { + + var i = this.touchLockCallbacks.length; + + while (i--) + { + if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context) + { + this.touchLockCallbacks.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Execute any {@link #touchLockCallbacks} of the given type. + * + * @method Phaser.Input#executeTouchLockCallbacks + * @private + * @param {boolean} onEnd - Execute the touchend/pointerup callbacks (true) or the touchstart/pointerdown callbacks (false). Required! + * @param {Event} event - The native event from the browser. + */ + executeTouchLockCallbacks: function (onEnd, event) { + var i = this.touchLockCallbacks.length; + + while (i--) + { + var cb = this.touchLockCallbacks[i]; + + if (cb.onEnd === onEnd && cb.callback.call(cb.context, this, event)) + { + this.touchLockCallbacks.splice(i, 1); + } + } + }, + + /** + * Removes the callback from the Phaser.Input.moveCallbacks array. + * + * @method Phaser.Input#deleteMoveCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + */ + deleteMoveCallback: function (callback, context) { + + var i = this.moveCallbacks.length; + + while (i--) + { + if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context) + { + this.moveCallbacks.splice(i, 1); + return; + } + } + + }, + + /** + * Add a new Pointer object to the Input Manager. + * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. + * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). + * + * @method Phaser.Input#addPointer + * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. + */ + addPointer: function () { + + if (this.pointers.length >= Phaser.Input.MAX_POINTERS) + { + console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached."); + return null; + } + + var id = this.pointers.length + 1; + var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.CONTACT); + + this.pointers.push(pointer); + this['pointer' + id] = pointer; + + return pointer; + + }, + + /** + * Updates the Input Manager. Called by the core Game loop. + * + * @method Phaser.Input#update + * @protected + */ + update: function () { + + if (this.keyboard) + { + this.keyboard.update(); + } + + if (this.pollRate > 0 && this._pollCounter < this.pollRate) + { + this._pollCounter++; + return; + } + + this.speed.x = this.position.x - this._oldPosition.x; + this.speed.y = this.position.y - this._oldPosition.y; + + this._oldPosition.copyFrom(this.position); + this.mousePointer.update(); + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].update(); + } + + this._pollCounter = 0; + + }, + + /** + * Update method while paused. + * + * @method Phaser.Input#pauseUpdate + * @private + */ + pauseUpdate: function () { + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + }, + + /** + * Reset all of the Pointers and Input states. + * + * The optional `hard` parameter will reset any events or callbacks that may be bound. + * Input.reset is called automatically during a State change or if a game loses focus / visibility. + * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. + * + * @method Phaser.Input#reset + * @public + * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. + */ + reset: function (hard) { + + if (!this.game.isBooted || this.resetLocked) + { + return; + } + + if (hard === undefined) { hard = false; } + + this.mousePointer.reset(); + + if (this.keyboard) + { + this.keyboard.reset(hard); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].reset(); + } + + if (this.game.canvas.style.cursor !== 'none') + { + this.game.canvas.style.cursor = ''; + } + + if (hard) + { + this.onDown.dispose(); + this.onUp.dispose(); + this.onTap.dispose(); + this.onHold.dispose(); + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + this.moveCallbacks = []; + } + + this._pollCounter = 0; + + }, + + /** + * Resets the speed and old position properties. + * + * @method Phaser.Input#resetSpeed + * @param {number} x - Sets the oldPosition.x value. + * @param {number} y - Sets the oldPosition.y value. + */ + resetSpeed: function (x, y) { + + this._oldPosition.setTo(x, y); + this.speed.setTo(0, 0); + + }, + + /** + * Find the first free Pointer object and start it, passing in the event data. + * This is called automatically by Phaser.Touch and Phaser.MSPointer. + * + * @method Phaser.Input#startPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. + */ + startPointer: function (event) { + + if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers) + { + return null; + } + + if (!this.pointer1.active) + { + return this.pointer1.start(event); + } + + if (!this.pointer2.active) + { + return this.pointer2.start(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (!pointer.active) + { + return pointer.start(event); + } + } + + return null; + + }, + + /** + * Updates the matching Pointer object, passing in the event data. + * This is called automatically and should not normally need to be invoked. + * + * @method Phaser.Input#updatePointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. + */ + updatePointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.move(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.move(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.move(event); + } + } + + return null; + + }, + + /** + * Stops the matching Pointer object, passing in the event data. + * + * @method Phaser.Input#stopPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. + */ + stopPointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.stop(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.stop(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.stop(event); + } + } + + return null; + + }, + + /** + * Returns the total number of active pointers, not exceeding the specified limit + * + * @name Phaser.Input#countActivePointers + * @private + * @property {integer} [limit=(max pointers)] - Stop counting after this. + * @return {integer} The number of active pointers, or limit - whichever is less. + */ + countActivePointers: function (limit) { + + if (limit === undefined) { limit = this.pointers.length; } + + var count = limit; + + for (var i = 0; i < this.pointers.length && count > 0; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active) + { + count--; + } + } + + return (limit - count); + + }, + + /** + * Get the first Pointer with the given active state. + * + * @method Phaser.Input#getPointer + * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. + */ + getPointer: function (isActive) { + + if (isActive === undefined) { isActive = false; } + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active === isActive) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `identifier` property matches the given identifier value. + * + * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down, and is not fixed once set. + * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. + * + * @method Phaser.Input#getPointerFromIdentifier + * @param {number} identifier - The Pointer.identifier value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromIdentifier: function (identifier) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.identifier === identifier) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `pointerId` property matches the given value. + * + * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down if the browser recycles it. + * + * @method Phaser.Input#getPointerFromId + * @param {number} pointerId - The `pointerId` (not 'id') value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromId: function (pointerId) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.pointerId === pointerId) + { + return pointer; + } + } + + return null; + + }, + + /** + * This will return the local coordinates of the specified displayObject based on the given Pointer. + * + * @method Phaser.Input#getLocalPosition + * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. + * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. + * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. + */ + getLocalPosition: function (displayObject, pointer, output) { + + if (output === undefined) { output = new Phaser.Point(); } + + var wt = displayObject.worldTransform; + var id = 1 / (wt.a * wt.d + wt.c * -wt.b); + + return output.setTo( + wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id, + wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id + ); + + }, + + /** + * Tests if the pointer hits the given object. + * + * @method Phaser.Input#hitTest + * @param {DisplayObject} displayObject - The displayObject to test for a hit. + * @param {Phaser.Pointer} pointer - The pointer to use for the test. + * @param {Phaser.Point} localPoint - The local translated point. + */ + hitTest: function (displayObject, pointer, localPoint) { + + if (!displayObject.worldVisible) + { + return false; + } + + this.getLocalPosition(displayObject, pointer, this._localPoint); + + localPoint.copyFrom(this._localPoint); + + if (displayObject.hitArea && displayObject.hitArea.contains) + { + return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y)); + } + else if (Phaser.Creature && displayObject instanceof Phaser.Creature) { + var width = Math.abs(displayObject.width); + var height = Math.abs(displayObject.height); + var x1 = displayObject.x - (width * displayObject.anchorX); + + if (this.game.camera.x + pointer.x >= x1 && this.game.camera.x + pointer.x < x1 + width) + { + var y1 = displayObject.y - (height * displayObject.anchorY); + + if (this.game.camera.y + pointer.y >= y1 && this.game.camera.y + pointer.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.TileSprite) + { + var width = displayObject.width; + var height = displayObject.height; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof PIXI.Sprite) + { + var width = displayObject.texture.frame.width / displayObject.texture.baseTexture.resolution; + var height = displayObject.texture.frame.height / displayObject.texture.baseTexture.resolution; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.Graphics) + { + for (var i = 0; i < displayObject.graphicsData.length; i++) + { + var data = displayObject.graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // Only deal with fills.. + if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y)) + { + return true; + } + } + } + + // Didn't hit the parent, does it have any children? + + for (var i = 0; i < displayObject.children.length; i++) + { + if (this.hitTest(displayObject.children[i], pointer, localPoint)) + { + return true; + } + } + + return false; + }, + + /** + * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. + * + * @method Phaser.Input#onClickTrampoline + * @private + */ + onClickTrampoline: function () { + + // It might not always be the active pointer, but this does work on + // Desktop browsers (read: IE) with Mouse or MSPointer input. + this.activePointer.processClickTrampolines(); + + } + +}; + +Phaser.Input.prototype.constructor = Phaser.Input; + +/** +* The X coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. +* @name Phaser.Input#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Input.prototype, "x", { + + get: function () { + return this._x; + }, + + set: function (value) { + this._x = Math.floor(value); + } + +}); + +/** +* The Y coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. +* @name Phaser.Input#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Input.prototype, "y", { + + get: function () { + return this._y; + }, + + set: function (value) { + this._y = Math.floor(value); + } + +}); + +/** +* True if the Input is currently poll rate locked. +* @name Phaser.Input#pollLocked +* @property {boolean} pollLocked +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "pollLocked", { + + get: function () { + return (this.pollRate > 0 && this._pollCounter < this.pollRate); + } + +}); + +/** +* The total number of inactive Pointers. +* @name Phaser.Input#totalInactivePointers +* @property {number} totalInactivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", { + + get: function () { + return this.pointers.length - this.countActivePointers(); + } + +}); + +/** +* The total number of active Pointers, not counting the mouse pointer. +* @name Phaser.Input#totalActivePointers +* @property {integers} totalActivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", { + + get: function () { + return this.countActivePointers(); + } + +}); + +/** +* The world X coordinate of the most recently active pointer. +* @name Phaser.Input#worldX +* @property {number} worldX - The world X coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldX", { + + get: function () { + return this.game.camera.view.x + this.x; + } + +}); + +/** +* The world Y coordinate of the most recently active pointer. +* @name Phaser.Input#worldY +* @property {number} worldY - The world Y coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldY", { + + get: function () { + return this.game.camera.view.y + this.y; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Mouse class is responsible for handling all aspects of mouse interaction with the browser. +* +* It captures and processes mouse events that happen on the game canvas object. +* It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released +* when not over the game. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object +* which normalises all game input for you, including accurate button handling. +* +* @class Phaser.Mouse +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Mouse = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down. + */ + this.mouseDownCallback = null; + + /** + * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state. + */ + this.mouseUpCallback = null; + + /** + * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas. + */ + this.mouseOutCallback = null; + + /** + * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). + */ + this.mouseOverCallback = null; + + /** + * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used. + */ + this.mouseWheelCallback = null; + + /** + * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + */ + this.capture = false; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + * @default + */ + this.button = -1; + + /** + * The direction of the _last_ mousewheel usage 1 for up -1 for down. + * @property {number} wheelDelta + */ + this.wheelDelta = 0; + + /** + * Mouse input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true. + * @default + */ + this.locked = false; + + /** + * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas. + * @default + */ + this.stopOnGameOut = false; + + /** + * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state. + * @default + */ + this.pointerLock = new Phaser.Signal(); + + /** + * The browser mouse DOM event. Will be null if no mouse event has ever been received. + * Access this property only inside a Mouse event handler and do not keep references to it. + * @property {MouseEvent|null} event + * @default + */ + this.event = null; + + /** + * @property {function} _onMouseDown - Internal event handler reference. + * @private + */ + this._onMouseDown = null; + + /** + * @property {function} _onMouseMove - Internal event handler reference. + * @private + */ + this._onMouseMove = null; + + /** + * @property {function} _onMouseUp - Internal event handler reference. + * @private + */ + this._onMouseUp = null; + + /** + * @property {function} _onMouseOut - Internal event handler reference. + * @private + */ + this._onMouseOut = null; + + /** + * @property {function} _onMouseOver - Internal event handler reference. + * @private + */ + this._onMouseOver = null; + + /** + * @property {function} _onMouseWheel - Internal event handler reference. + * @private + */ + this._onMouseWheel = null; + + /** + * Wheel proxy event object, if required. Shared for all wheel events for this mouse. + * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent + * @private + */ + this._wheelEvent = null; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.NO_BUTTON = -1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.LEFT_BUTTON = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.MIDDLE_BUTTON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.RIGHT_BUTTON = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.BACK_BUTTON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.FORWARD_BUTTON = 4; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_UP = 1; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_DOWN = -1; + +Phaser.Mouse.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Mouse#start + */ + start: function () { + + if (this.game.device.android && this.game.device.chrome === false) + { + // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ... + return; + } + + if (this._onMouseDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onMouseDown = function (event) { + return _this.onMouseDown(event); + }; + + this._onMouseMove = function (event) { + return _this.onMouseMove(event); + }; + + this._onMouseUp = function (event) { + return _this.onMouseUp(event); + }; + + this._onMouseUpGlobal = function (event) { + return _this.onMouseUpGlobal(event); + }; + + this._onMouseOutGlobal = function (event) { + return _this.onMouseOutGlobal(event); + }; + + this._onMouseOut = function (event) { + return _this.onMouseOut(event); + }; + + this._onMouseOver = function (event) { + return _this.onMouseOver(event); + }; + + this._onMouseWheel = function (event) { + return _this.onMouseWheel(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('mousedown', this._onMouseDown, true); + canvas.addEventListener('mousemove', this._onMouseMove, true); + canvas.addEventListener('mouseup', this._onMouseUp, true); + + if (!this.game.device.cocoonJS) + { + window.addEventListener('mouseup', this._onMouseUpGlobal, true); + window.addEventListener('mouseout', this._onMouseOutGlobal, true); + canvas.addEventListener('mouseover', this._onMouseOver, true); + canvas.addEventListener('mouseout', this._onMouseOut, true); + } + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.addEventListener(wheelEvent, this._onMouseWheel, true); + + if (wheelEvent === 'mousewheel') + { + this._wheelEvent = new WheelEventProxy(-1/40, 1); + } + else if (wheelEvent === 'DOMMouseScroll') + { + this._wheelEvent = new WheelEventProxy(1, 1); + } + } + + }, + + /** + * The internal method that handles the mouse down event from the browser. + * @method Phaser.Mouse#onMouseDown + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseDown: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseDownCallback) + { + this.mouseDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.start(event); + + }, + + /** + * The internal method that handles the mouse move event from the browser. + * @method Phaser.Mouse#onMouseMove + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseMoveCallback) + { + this.mouseMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.move(event); + + }, + + /** + * The internal method that handles the mouse up event from the browser. + * @method Phaser.Mouse#onMouseUp + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUp: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.Mouse#onMouseUpGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUpGlobal: function (event) { + + if (!this.input.mousePointer.withinGame) + { + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + }, + + /** + * The internal method that handles the mouse out event from the window. + * + * @method Phaser.Mouse#onMouseOutGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOutGlobal: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (!this.input.enabled || !this.enabled) + { + return; + } + + // If we get a mouseout event from the window then basically + // something serious has gone down, usually along the lines of + // the browser opening a context-menu or similar. + // On OS X Chrome especially this is bad news, as it blocks + // us then getting a mouseup event, so we need to force that through. + // + // No matter what, we must cancel the left and right buttons + + this.input.mousePointer.stop(event); + + // Clear the button states (again?) + this.input.mousePointer.resetButtons(); + + }, + + /** + * The internal method that handles the mouse out event from the browser. + * + * @method Phaser.Mouse#onMouseOut + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (this.mouseOutCallback) + { + this.mouseOutCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.stopOnGameOut) + { + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + this.input.interactiveItems.callAll('_pointerOutHandler', this.input.mousePointer); + + }, + + /** + * The internal method that handles the mouse over event from the browser. + * + * @method Phaser.Mouse#onMouseOver + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = true; + + if (this.mouseOverCallback) + { + this.mouseOverCallback.call(this.callbackContext, event); + } + + }, + + /** + * The internal method that handles the mouse wheel event from the browser. + * + * @method Phaser.Mouse#onMouseWheel + * @param {MouseEvent} event - The native event from the browser. + */ + onMouseWheel: function (event) { + + if (this._wheelEvent) { + event = this._wheelEvent.bindEvent(event); + } + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + // reverse detail for firefox + this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1); + + if (this.mouseWheelCallback) + { + this.mouseWheelCallback.call(this.callbackContext, event); + } + + }, + + /** + * If the browser supports it you can request that the pointer be locked to the browser window. + * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key. + * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'. + * @method Phaser.Mouse#requestPointerLock + */ + requestPointerLock: function () { + + if (this.game.device.pointerLock) + { + var element = this.game.canvas; + + element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; + + element.requestPointerLock(); + + var _this = this; + + this._pointerLockChange = function (event) { + return _this.pointerLockChange(event); + }; + + document.addEventListener('pointerlockchange', this._pointerLockChange, true); + document.addEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true); + } + + }, + + /** + * Internal pointerLockChange handler. + * + * @method Phaser.Mouse#pointerLockChange + * @param {Event} event - The native event from the browser. This gets stored in Mouse.event. + */ + pointerLockChange: function (event) { + + var element = this.game.canvas; + + if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) + { + // Pointer was successfully locked + this.locked = true; + this.pointerLock.dispatch(true, event); + } + else + { + // Pointer was unlocked + this.locked = false; + this.pointerLock.dispatch(false, event); + } + + }, + + /** + * Internal release pointer lock handler. + * @method Phaser.Mouse#releasePointerLock + */ + releasePointerLock: function () { + + document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; + + document.exitPointerLock(); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + }, + + /** + * Stop the event listeners. + * @method Phaser.Mouse#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('mousedown', this._onMouseDown, true); + canvas.removeEventListener('mousemove', this._onMouseMove, true); + canvas.removeEventListener('mouseup', this._onMouseUp, true); + canvas.removeEventListener('mouseover', this._onMouseOver, true); + canvas.removeEventListener('mouseout', this._onMouseOut, true); + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.removeEventListener(wheelEvent, this._onMouseWheel, true); + } + + window.removeEventListener('mouseup', this._onMouseUpGlobal, true); + window.removeEventListener('mouseout', this._onMouseOutGlobal, true); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + } + +}; + +Phaser.Mouse.prototype.constructor = Phaser.Mouse; + +/* jshint latedef:nofunc */ +/** +* A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel' +* events to 'wheel'-like events. +* +* See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode. +* +* @method Phaser.Mouse#WheelEventProxy +* @private +* @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. +* @param {integer} deltaMode - The reported delta mode. +*/ +function WheelEventProxy (scaleFactor, deltaMode) { + + /** + * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. + * @private + */ + this._scaleFactor = scaleFactor; + + /** + * @property {number} _deltaMode - The reported delta mode. + * @private + */ + this._deltaMode = deltaMode; + + /** + * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit. + * @private + */ + this.originalEvent = null; + +} + +WheelEventProxy.prototype = {}; +WheelEventProxy.prototype.constructor = WheelEventProxy; + +WheelEventProxy.prototype.bindEvent = function (event) { + + // Generate stubs automatically + if (!WheelEventProxy._stubsGenerated && event) + { + var makeBinder = function (name) { + + return function () { + var v = this.originalEvent[name]; + return typeof v !== 'function' ? v : v.bind(this.originalEvent); + }; + + }; + + for (var prop in event) + { + if (!(prop in WheelEventProxy.prototype)) + { + Object.defineProperty(WheelEventProxy.prototype, prop, { + get: makeBinder(prop) + }); + } + } + WheelEventProxy._stubsGenerated = true; + } + + this.originalEvent = event; + return this; + +}; + +Object.defineProperties(WheelEventProxy.prototype, { + "type": { value: "wheel" }, + "deltaMode": { get: function () { return this._deltaMode; } }, + "deltaY": { + get: function () { + return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0; + } + }, + "deltaX": { + get: function () { + return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0; + } + }, + "deltaZ": { value: 0 } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The MSPointer class handles {@link https://developers.google.com/web/updates/2016/10/pointer-events Pointer-event} interactions with the game via a dedicated {@link Phaser.Pointer}. (It's named after the nonstandard {@link https://msdn.microsoft.com/library/hh673557(v=vs.85).aspx MSPointerEvent} since that was the first browser implementation.) +* +* It's {@link http://caniuse.com/#feat=pointer currently supported in IE 10+, Edge, Chrome (including Android), and Opera}. +* +* You should not normally access this class directly, but instead use a {@link Phaser.Pointer} object which +* normalises all game input for you including accurate button handling. +* +* Please note that at the current time of writing Phaser does not yet support chorded button interactions: +* http://www.w3.org/TR/pointerevents/#chorded-button-interactions +* +* You can disable Phaser's use of Pointer Events by either of two ways: +* +* ```javascript +* // **Before** `new Phaser.Game(…)`: +* Phaser.Device.onInitialized.add(function () { +* this.mspointer = false; +* }); +* ``` +* +* ```javascript +* // Once, in the earliest State `init` or `create` callback (e.g., Boot): +* this.input.mspointer.stop(); +* ``` +* +* @class Phaser.MSPointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.MSPointer = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called (defaults to game). + */ + this.callbackContext = this.game; + + /** + * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event. + */ + this.pointerDownCallback = null; + + /** + * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event. + */ + this.pointerMoveCallback = null; + + /** + * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event. + */ + this.pointerUpCallback = null; + + /** + * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, canceling the corresponding MouseEvent or TouchEvent. + */ + this.capture = true; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + */ + this.button = -1; + + /** + * The most recent PointerEvent from the browser. Will be null if no event has ever been received. + * Access this property only inside a Pointer event handler and do not keep references to it. + * @property {MSPointerEvent|PointerEvent|null} event + * @default + */ + this.event = null; + + /** + * PointerEvent input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {function} _onMSPointerDown - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerDown = null; + + /** + * @property {function} _onMSPointerMove - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerMove = null; + + /** + * @property {function} _onMSPointerUp - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUp = null; + + /** + * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUpGlobal = null; + + /** + * @property {function} _onMSPointerOut - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOut = null; + + /** + * @property {function} _onMSPointerOver - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOver = null; + +}; + +Phaser.MSPointer.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.MSPointer#start + */ + start: function () { + + if (this._onMSPointerDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + if (this.game.device.mspointer) + { + this._onMSPointerDown = function (event) { + return _this.onPointerDown(event); + }; + + this._onMSPointerMove = function (event) { + return _this.onPointerMove(event); + }; + + this._onMSPointerUp = function (event) { + return _this.onPointerUp(event); + }; + + this._onMSPointerUpGlobal = function (event) { + return _this.onPointerUpGlobal(event); + }; + + this._onMSPointerOut = function (event) { + return _this.onPointerOut(event); + }; + + this._onMSPointerOver = function (event) { + return _this.onPointerOver(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.addEventListener('pointerdown', this._onMSPointerDown, false); + canvas.addEventListener('pointermove', this._onMSPointerMove, false); + canvas.addEventListener('pointerup', this._onMSPointerUp, false); + + canvas.style['-ms-content-zooming'] = 'none'; + canvas.style['-ms-touch-action'] = 'none'; + + if (!this.game.device.cocoonJS) + { + window.addEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.addEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.addEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.addEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.addEventListener('pointerover', this._onMSPointerOver, true); + canvas.addEventListener('pointerout', this._onMSPointerOut, true); + } + } + + }, + + /** + * The function that handles the PointerDown event. + * + * @method Phaser.MSPointer#onPointerDown + * @param {PointerEvent} event - The native DOM event. + */ + onPointerDown: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerDownCallback) + { + this.pointerDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.start(event); + } + else + { + this.input.startPointer(event); + } + + }, + + /** + * The function that handles the PointerMove event. + * @method Phaser.MSPointer#onPointerMove + * @param {PointerEvent} event - The native DOM event. + */ + onPointerMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerMoveCallback) + { + this.pointerMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.move(event); + } + else + { + this.input.updatePointer(event); + } + + }, + + /** + * The function that handles the PointerUp event. + * @method Phaser.MSPointer#onPointerUp + * @param {PointerEvent} event - The native DOM event. + */ + onPointerUp: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerUpCallback) + { + this.pointerUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.stop(event); + } + else + { + this.input.stopPointer(event); + } + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.MSPointer#onPointerUpGlobal + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerUpGlobal: function (event) { + + if ((event.pointerType === 'mouse' || event.pointerType === 0x00000004) && !this.input.mousePointer.withinGame) + { + this.onPointerUp(event); + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer && pointer.withinGame) + { + this.onPointerUp(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = false; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = false; + } + } + + if (this.input.mouse.mouseOutCallback) + { + this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.input.mouse.stopOnGameOut) + { + event['identifier'] = 0; + + if (pointer) + { + pointer.stop(event); + } + else + { + this.input.mousePointer.stop(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = true; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = true; + } + } + + if (this.input.mouse.mouseOverCallback) + { + this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext, event); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.MSPointer#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.removeEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.removeEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.removeEventListener('pointerdown', this._onMSPointerDown, false); + canvas.removeEventListener('pointermove', this._onMSPointerMove, false); + canvas.removeEventListener('pointerup', this._onMSPointerUp, false); + + window.removeEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.removeEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.removeEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('pointerover', this._onMSPointerOver, true); + canvas.removeEventListener('pointerout', this._onMSPointerOut, true); + + } + +}; + +Phaser.MSPointer.prototype.constructor = Phaser.MSPointer; + +/** +* @author Richard Davey +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. +* +* For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, +* middle button and advanced buttons like back and forward. +* +* Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. +* +* On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. +* +* At the time of writing this there are device limitations you should be aware of: +* +* - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions +* (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, +* even when they are pressed. +* - On Linux (GTK), the 4th button and the 5th button are not supported. +* - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. +* +* @class Phaser.DeviceButton +* @constructor +* @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad. +* @param {number} buttonCode - The button code this DeviceButton is responsible for. +*/ +Phaser.DeviceButton = function (parent, buttonCode) { + + /** + * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = parent.game; + + /** + * @property {object} event - The DOM event that caused the change in button state. + * @default + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the button. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the button. + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - The timestamp when the button was last pressed down. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - The timestamp when the button was last released. + * @default + */ + this.timeUp = 0; + + /** + * Gamepad only. + * If a button is held down this holds down the number of times the button has 'repeated'. + * @property {number} repeats + * @default + */ + this.repeats = 0; + + /** + * True if the alt key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} altKey + * @default + */ + this.altKey = false; + + /** + * True if the shift key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} shiftKey + * @default + */ + this.shiftKey = false; + + /** + * True if the control key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} ctrlKey + * @default + */ + this.ctrlKey = false; + + /** + * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. + * @default + */ + this.value = 0; + + /** + * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. + */ + this.buttonCode = buttonCode; + + /** + * This Signal is dispatched every time this DeviceButton is pressed down. + * It is only dispatched once (until the button is released again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onDown + */ + this.onDown = new Phaser.Signal(); + + /** + * This Signal is dispatched every time this DeviceButton is released from a down state. + * It is only dispatched once (until the button is pressed again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onUp + */ + this.onUp = new Phaser.Signal(); + + /** + * Gamepad only. + * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onFloat + */ + this.onFloat = new Phaser.Signal(); + +}; + +Phaser.DeviceButton.prototype = { + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button down state. + * + * @method Phaser.DeviceButton#start + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + start: function (event, value) { + + if (this.isDown) + { + return; + } + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onDown.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button up state. + * + * @method Phaser.DeviceButton#stop + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + stop: function (event, value) { + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onUp.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer. + * Starts or stops button based on condition. + * + * @method Phaser.DeviceButton#startStop + * @protected + * @param {boolean} [condition] - The condition that decides between start or stop. + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + startStop: function (condition, event, value) { + + if (condition) + { + this.start(event, value); + } + else + { + this.stop(event, value); + } + + }, + + /** + * Called automatically by Phaser.SinglePad. + * + * @method Phaser.DeviceButton#padFloat + * @protected + * @param {number} value - Button value + */ + padFloat: function (value) { + + this.isDown = false; + this.isUp = false; + + this.value = value; + + this.onFloat.dispatch(this, value); + + }, + + /** + * Returns the "just pressed" state of this button. + * Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justPressed + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (duration) { + + duration = duration || 250; + + return (this.isDown && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * Returns the "just released" state of this button. + * Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justReleased + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (duration) { + + duration = duration || 250; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. + * + * @method Phaser.DeviceButton#reset + */ + reset: function () { + + this.isDown = false; + this.isUp = true; + + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.altKey = false; + this.shiftKey = false; + this.ctrlKey = false; + + }, + + /** + * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals + * and clears the parent and game references. + * + * @method Phaser.DeviceButton#destroy + */ + destroy: function () { + + this.onDown.dispose(); + this.onUp.dispose(); + this.onFloat.dispose(); + + this.parent = null; + this.game = null; + + } + +}; + +Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton; + +/** +* How long the button has been held down for in milliseconds. +* If not currently down it returns -1. +* +* @name Phaser.DeviceButton#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.DeviceButton.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. +* +* @class Phaser.Pointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. +* @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or CONTACT. +*/ +Phaser.Pointer = function (game, id, pointerMode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. + */ + this.id = id; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINTER; + + /** + * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps. + * @default + */ + this.exists = true; + + /** + * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.identifier = 0; + + /** + * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. + * @default + */ + this.pointerId = null; + + /** + * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer. + */ + this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT); + + /** + * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.target = null; + + /** + * The button property of the most recent DOM event when this Pointer is started. + * You should not rely on this value for accurate button detection, instead use the Pointer properties + * `leftButton`, `rightButton`, `middleButton` and so on. + * @property {any} button + * @default + */ + this.button = null; + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * @property {Phaser.DeviceButton} leftButton + * @default + */ + this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} middleButton + * @default + */ + this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} rightButton + * @default + */ + this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} backButton + * @default + */ + this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} forwardButton + * @default + */ + this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON); + + /** + * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} eraserButton + * @default + */ + this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON); + + /** + * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event. + * @private + * @default + */ + this._holdSent = false; + + /** + * @property {array} _history - Local private variable storing the short-term history of pointer movements. + * @private + */ + this._history = []; + + /** + * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur. + * @private + */ + this._nextDrop = 0; + + /** + * @property {boolean} _stateReset - Monitor events outside of a state reset loop. + * @private + */ + this._stateReset = false; + + /** + * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false. + */ + this.withinGame = false; + + /** + * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientX = -1; + + /** + * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientY = -1; + + /** + * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document. + */ + this.pageX = -1; + + /** + * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document. + */ + this.pageY = -1; + + /** + * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen. + */ + this.screenX = -1; + + /** + * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen. + */ + this.screenY = -1; + + /** + * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementX = 0; + + /** + * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementY = 0; + + /** + * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementX = 0; + + /** + * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementY = 0; + + /** + * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.x = -1; + + /** + * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.y = -1; + + /** + * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false. + */ + this.isMouse = (id === 0); + + /** + * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. + * @property {boolean} isDown + * @default + */ + this.isDown = false; + + /** + * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. + * @property {boolean} isUp + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen. + * @default + */ + this.timeUp = 0; + + /** + * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked. + * @default + */ + this.previousTapTime = 0; + + /** + * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen. + * @default + */ + this.totalTouches = 0; + + /** + * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event. + * @default + */ + this.msSinceLastClick = Number.MAX_VALUE; + + /** + * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging. + * @default + */ + this.targetObject = null; + + /** + * This array is erased and re-populated every time this Pointer is updated. It contains references to all + * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be + * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over + * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset + * every frame. + * @property {array} interactiveCandidates + * @default + */ + this.interactiveCandidates = []; + + /** + * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active. + * @default + */ + this.active = false; + + /** + * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. + * @default + */ + this.dirty = false; + + /** + * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display. + */ + this.position = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. + */ + this.positionDown = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released. + */ + this.positionUp = new Phaser.Point(); + + /** + * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. + * The Circle size is 44px (Apples recommended "finger tip" size). + * @property {Phaser.Circle} circle + */ + this.circle = new Phaser.Circle(0, 0, 44); + + /** + * Click trampolines associated with this pointer. See `addClickTrampoline`. + * @property {object[]|null} _clickTrampolines + * @private + */ + this._clickTrampolines = null; + + /** + * When the Pointer has click trampolines the last target object is stored here + * so it can be used to check for validity of the trampoline in a post-Up/'stop'. + * @property {object} _trampolineTargetObject + * @private + */ + this._trampolineTargetObject = null; + +}; + +/** +* No buttons at all. +* @constant +* @type {number} +*/ +Phaser.Pointer.NO_BUTTON = 0; + +/** +* The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. +* @constant +* @type {number} +*/ +Phaser.Pointer.LEFT_BUTTON = 1; + +/** +* The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. +* @constant +* @type {number} +*/ +Phaser.Pointer.RIGHT_BUTTON = 2; + +/** +* The Middle Mouse button. +* @constant +* @type {number} +*/ +Phaser.Pointer.MIDDLE_BUTTON = 4; + +/** +* The X1 button. This is typically the mouse Back button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.BACK_BUTTON = 8; + +/** +* The X2 button. This is typically the mouse Forward button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.FORWARD_BUTTON = 16; + +/** +* The Eraser pen button on PointerEvent supported devices only. +* @constant +* @type {number} +*/ +Phaser.Pointer.ERASER_BUTTON = 32; + +Phaser.Pointer.prototype = { + + /** + * Resets the states of all the button booleans. + * + * @method Phaser.Pointer#resetButtons + * @protected + */ + resetButtons: function () { + + this.isDown = false; + this.isUp = true; + + if (this.isMouse) + { + this.leftButton.reset(); + this.middleButton.reset(); + this.rightButton.reset(); + this.backButton.reset(); + this.forwardButton.reset(); + this.eraserButton.reset(); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsDown + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsDown: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.start(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.start(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.start(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.start(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.start(event); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsUp + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUp: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.stop(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.stop(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.stop(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.stop(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.stop(event); + } + + }, + + /** + * Called by updateButtons. + * + * @method Phaser.Pointer#processButtonsUpDown + * @private + * @param {integer} buttons - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons MouseEvent#buttons} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUpDown: function (buttons, event) { + + var down = (event.type.toLowerCase().substr(-4) === 'down'); + var move = (event.type.toLowerCase().substr(-4) === 'move'); + + if (buttons !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && buttons === 1 && event.ctrlKey) + { + buttons = 2; + } + + // Note: These are bitwise checks, not booleans + this.leftButton.startStop(Phaser.Pointer.LEFT_BUTTON & buttons, event); + this.rightButton.startStop(Phaser.Pointer.RIGHT_BUTTON & buttons, event); + this.middleButton.startStop(Phaser.Pointer.MIDDLE_BUTTON & buttons, event); + this.backButton.startStop(Phaser.Pointer.BACK_BUTTON & buttons, event); + this.forwardButton.startStop(Phaser.Pointer.FORWARD_BUTTON & buttons, event); + this.eraserButton.startStop(Phaser.Pointer.ERASER_BUTTON & buttons, event); + } + else + { + // No buttons property (like Safari on OSX when using a trackpad) + // Attempt to use event.button property or fallback to default + if (event.button !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && event.ctrlKey && event.button === 0) + { + this.rightButton.start(event); + } + else + { + if (down) + { + this.processButtonsDown(event.button, event); + } + else if (!move) + { + this.processButtonsUp(event.button, event); + } + } + } + else + { + if (down) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (event.ctrlKey) + { + this.rightButton.start(event); + } + else + { + this.leftButton.start(event); + } + } + else + { + this.leftButton.stop(event); + this.rightButton.stop(event); + } + } + } + + }, + + /** + * Called when the event.buttons property changes from zero. + * Contains a button bitmask. + * + * @method Phaser.Pointer#updateButtons + * @protected + * @param {MouseEvent} event - The DOM event. + */ + updateButtons: function (event) { + + this.button = event.button; + this.processButtonsUpDown(event.buttons, event); + + this.isUp = true; + this.isDown = false; + + if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown) + { + this.isUp = false; + this.isDown = true; + } + + }, + + /** + * Called when the Pointer is pressed onto the touchscreen. + * @method Phaser.Pointer#start + * @param {any} event - The DOM event from the browser. + */ + start: function (event) { + + var input = this.game.input; + + if (event['pointerId']) + { + this.pointerId = event.pointerId; + } + + this.identifier = event.identifier; + this.target = event.target; + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = true; + this.isUp = false; + } + + this.active = true; + this.withinGame = true; + this.dirty = false; + + this._history = []; + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + // Work out how long it has been since the last click + this.msSinceLastClick = this.game.time.time - this.timeDown; + this.timeDown = this.game.time.time; + this._holdSent = false; + + // This sets the x/y and other local values + this.move(event, true); + + // x and y are the old values here? + this.positionDown.setTo(this.x, this.y); + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.x = this.x; + input.y = this.y; + input.position.setTo(this.x, this.y); + input.onDown.dispatch(this, event); + input.resetSpeed(this.x, this.y); + } + + this._stateReset = false; + + this.totalTouches++; + + if (this.targetObject !== null) + { + this.targetObject._touchedHandler(this); + } + + return this; + + }, + + /** + * Called by the Input Manager. + * @method Phaser.Pointer#update + */ + update: function () { + + var input = this.game.input; + + if (this.active) + { + // Force a check? + if (this.dirty) + { + if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(false); + } + + this.dirty = false; + } + + if (this._holdSent === false && this.duration >= input.holdRate) + { + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onHold.dispatch(this); + } + + this._holdSent = true; + } + + // Update the droppings history + if (input.recordPointerHistory && this.game.time.time >= this._nextDrop) + { + this._nextDrop = this.game.time.time + input.recordRate; + + this._history.push({ + x: this.position.x, + y: this.position.y + }); + + if (this._history.length > input.recordLimit) + { + this._history.shift(); + } + } + } + + }, + + /** + * Called when the Pointer is moved. + * + * @method Phaser.Pointer#move + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + * @param {boolean} [fromClick=false] - Was this called from the click event? + */ + move: function (event, fromClick) { + + var input = this.game.input; + + if (input.pollLocked) + { + return; + } + + if (fromClick === undefined) { fromClick = false; } + + if (event.button !== undefined) + { + this.button = event.button; + } + + if (this.isMouse) + { + this.updateButtons(event); + } + + 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 && 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.scale.offset.x) * input.scale.x; + this.y = (this.pageY - this.game.scale.offset.y) * input.scale.y; + + this.position.setTo(this.x, this.y); + this.circle.x = this.x; + this.circle.y = this.y; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.activePointer = this; + input.x = this.x; + input.y = this.y; + input.position.setTo(input.x, input.y); + input.circle.x = input.x; + input.circle.y = input.y; + } + + this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY); + + var i = input.moveCallbacks.length; + + while (i--) + { + input.moveCallbacks[i].callback.call(input.moveCallbacks[i].context, this, this.x, this.y, fromClick); + } + + // Easy out if we're dragging something and it still exists + if (this.targetObject !== null && (!this.game.paused || this.targetObject.noPause) && this.targetObject.isDragged === true) + { + if (this.targetObject.update(this) === false) + { + this.targetObject = null; + } + } + else if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(fromClick); + } + + return this; + + }, + + /** + * Process all interactive objects to find out which ones were updated in the recent Pointer move. + * + * @method Phaser.Pointer#processInteractiveObjects + * @protected + * @param {boolean} [fromClick=false] - Was this called from the click event? + * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. + */ + processInteractiveObjects: function (fromClick) { + + // Work out which object is on the top + var highestRenderOrderID = 0; + var highestInputPriorityID = -1; + var candidateTarget = null; + + // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID + // We know they'll be valid for input detection but not which is the top just yet + + var currentNode = this.game.input.interactiveItems.first; + + this.interactiveCandidates = []; + + while (currentNode) + { + // Reset checked status + currentNode.checked = false; + + if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false) && (!this.game.paused || currentNode.sprite.noPause)) + { + // Flag it as checked so we don't re-scan it on the next phase + currentNode.checked = true; + + if ((fromClick && currentNode.checkPointerDown(this, true)) || + (!fromClick && currentNode.checkPointerOver(this, true))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID + // because if their ID is lower anyway then we can just automatically discount them + // (A node that was previously checked did not request a pixel-perfect check.) + + currentNode = this.game.input.interactiveItems.first; + + while (currentNode) + { + if (!currentNode.checked && + currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true)) + { + if ((fromClick && currentNode.checkPointerDown(this, false)) || + (!fromClick && currentNode.checkPointerOver(this, false))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + if (this.game.input.customCandidateHandler) + { + candidateTarget = this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext, this, this.interactiveCandidates, candidateTarget); + } + + this.swapTarget(candidateTarget, false); + + return (this.targetObject !== null); + + }, + + /** + * This will change the `Pointer.targetObject` object to be the one provided. + * + * This allows you to have fine-grained control over which object the Pointer is targeting. + * + * Note that even if you set a new Target here, it is still able to be replaced by any other valid + * target during the next Pointer update. + * + * @method Phaser.Pointer#swapTarget + * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. + * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. + */ + swapTarget: function (newTarget, silent) { + + if (silent === undefined) { silent = false; } + + // Now we know the top-most item (if any) we can process it + if (newTarget === null) + { + // The pointer isn't currently over anything, check if we've got a lingering previous target + if (this.targetObject) + { + this.targetObject._pointerOutHandler(this, silent); + this.targetObject = null; + } + } + else + { + if (this.targetObject === null) + { + // And now set the new one + this.targetObject = newTarget; + newTarget._pointerOverHandler(this, silent); + } + else + { + // We've got a target from the last update + if (this.targetObject === newTarget) + { + // Same target as before, so update it + if (newTarget.update(this) === false) + { + this.targetObject = null; + } + } + else + { + // The target has changed, so tell the old one we've left it + this.targetObject._pointerOutHandler(this, silent); + + // And now set the new one + this.targetObject = newTarget; + this.targetObject._pointerOverHandler(this, silent); + } + } + } + + }, + + /** + * Called when the Pointer leaves the target area. + * + * @method Phaser.Pointer#leave + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + leave: function (event) { + + this.withinGame = false; + this.move(event, false); + + }, + + /** + * Called when the Pointer leaves the touchscreen. + * + * @method Phaser.Pointer#stop + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + stop: function (event) { + + var input = this.game.input; + + if (this._stateReset && this.withinGame) + { + event.preventDefault(); + return; + } + + this.timeUp = this.game.time.time; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onUp.dispatch(this, event); + + // Was it a tap? + if (this.duration >= 0 && this.duration <= input.tapRate) + { + // Was it a double-tap? + if (this.timeUp - this.previousTapTime < input.doubleTapRate) + { + // Yes, let's dispatch the signal then with the 2nd parameter set to true + input.onTap.dispatch(this, true); + } + else + { + // Wasn't a double-tap, so dispatch a single tap signal + input.onTap.dispatch(this, false); + } + + this.previousTapTime = this.timeUp; + } + } + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = false; + this.isUp = true; + } + + // Mouse is always active + if (this.id > 0) + { + this.active = false; + } + + this.withinGame = this.game.scale.bounds.contains(event.pageX, event.pageY); + this.pointerId = null; + this.identifier = null; + + this.positionUp.setTo(this.x, this.y); + + if (this.isMouse === false) + { + input.currentPointers--; + } + + input.interactiveItems.callAll('_releasedHandler', this); + + if (this._clickTrampolines) + { + this._trampolineTargetObject = this.targetObject; + } + + this.targetObject = null; + + return this; + + }, + + /** + * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. + * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. + * @method Phaser.Pointer#justPressed + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate. + * @return {boolean} true if the Pointer was pressed down within the duration given. + */ + justPressed: function (duration) { + + duration = duration || this.game.input.justPressedRate; + + return (this.isDown === true && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. + * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. + * @method Phaser.Pointer#justReleased + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate. + * @return {boolean} true if the Pointer was released within the duration given. + */ + justReleased: function (duration) { + + duration = duration || this.game.input.justReleasedRate; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Add a click trampoline to this pointer. + * + * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily + * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen + * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. + * + * This is used internally by the ScaleManager; click trampoline usage is uncommon. + * Click trampolines can only be added to pointers that are currently down. + * + * @method Phaser.Pointer#addClickTrampoline + * @protected + * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer. + * @param {function} callback - Callback to run/trampoline. + * @param {object} callbackContext - Context of the callback. + * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array. + */ + addClickTrampoline: function (name, callback, callbackContext, callbackArgs) { + + if (!this.isDown) + { + return; + } + + var trampolines = (this._clickTrampolines = this._clickTrampolines || []); + + for (var i = 0; i < trampolines.length; i++) + { + if (trampolines[i].name === name) + { + trampolines.splice(i, 1); + break; + } + } + + trampolines.push({ + name: name, + targetObject: this.targetObject, + callback: callback, + callbackContext: callbackContext, + callbackArgs: callbackArgs + }); + + }, + + /** + * Fire all click trampolines for which the pointers are still referring to the registered object. + * @method Phaser.Pointer#processClickTrampolines + * @private + */ + processClickTrampolines: function () { + + var trampolines = this._clickTrampolines; + + if (!trampolines) + { + return; + } + + for (var i = 0; i < trampolines.length; i++) + { + var trampoline = trampolines[i]; + + if (trampoline.targetObject === this._trampolineTargetObject) + { + trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs); + } + } + + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + }, + + /** + * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. + * @method Phaser.Pointer#reset + */ + reset: function () { + + if (this.isMouse === false) + { + this.active = false; + } + + this.pointerId = null; + this.identifier = null; + this.dirty = false; + this.totalTouches = 0; + this._holdSent = false; + this._history.length = 0; + this._stateReset = true; + + this.resetButtons(); + + if (this.targetObject) + { + this.targetObject._releasedHandler(this); + } + + this.targetObject = null; + + }, + + /** + * Resets the movementX and movementY properties. Use in your update handler after retrieving the values. + * @method Phaser.Pointer#resetMovement + */ + resetMovement: function() { + + this.movementX = 0; + this.movementY = 0; + + } + +}; + +Phaser.Pointer.prototype.constructor = Phaser.Pointer; + +/** +* How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. +* If not currently down it returns -1. +* If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. +* +* @name Phaser.Pointer#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* Gets the X value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldX +* @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldX", { + + get: function () { + + return this.game.world.camera.x + this.x; + + } + +}); + +/** +* Gets the Y value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldY +* @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldY", { + + get: function () { + + return this.game.world.camera.y + this.y; + + } + +}); + +/** +* Enumeration categorizing operational modes of pointers. +* +* PointerType values represent valid bitmasks. +* For example, a value representing both Mouse and Touch devices +* can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. +* +* Values may be added for future mode categorizations. +* @class Phaser.PointerMode +*/ +Phaser.PointerMode = { + + /** + * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. + * + * It has the property that a cursor is passively moved without activating the input. + * This currently corresponds with {@link Phaser.Pointer#isMouse} property. + * @constant + */ + CURSOR: 1 << 0, + + /** + * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. + * @constant + */ + CONTACT: 1 << 1 + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. +* +* @class Phaser.Touch +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Touch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * Touch events will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} touchStartCallback - A callback that can be fired on a touchStart event. + */ + this.touchStartCallback = null; + + /** + * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event. + */ + this.touchMoveCallback = null; + + /** + * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event. + */ + this.touchEndCallback = null; + + /** + * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event. + */ + this.touchEnterCallback = null; + + /** + * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event. + */ + this.touchLeaveCallback = null; + + /** + * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event. + */ + this.touchCancelCallback = null; + + /** + * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it. + * @default + */ + this.preventDefault = true; + + /** + * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received. + * @default + */ + this.event = null; + + /** + * @property {function} _onTouchStart - Internal event handler reference. + * @private + */ + this._onTouchStart = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + + /** + * @property {function} _onTouchEnd - Internal event handler reference. + * @private + */ + this._onTouchEnd = null; + + /** + * @property {function} _onTouchEnter - Internal event handler reference. + * @private + */ + this._onTouchEnter = null; + + /** + * @property {function} _onTouchLeave - Internal event handler reference. + * @private + */ + this._onTouchLeave = null; + + /** + * @property {function} _onTouchCancel - Internal event handler reference. + * @private + */ + this._onTouchCancel = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + +}; + +Phaser.Touch.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Touch#start + */ + start: function () { + + if (this._onTouchStart !== null) + { + // Avoid setting multiple listeners + 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('touchcancel', this._onTouchCancel, false); + + if (!this.game.device.cocoonJS) + { + this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false); + this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false); + } + } + + }, + + /** + * Consumes all touchmove events on the document (only enable this if you know you need it!). + * @method Phaser.Touch#consumeTouchMove + */ + consumeDocumentTouches: function () { + + this._documentTouchMove = function (event) { + event.preventDefault(); + }; + + document.addEventListener('touchmove', this._documentTouchMove, false); + + }, + + /** + * The internal method that handles the touchstart event from the browser. + * @method Phaser.Touch#onTouchStart + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchStart: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.touchStartCallback) + { + this.touchStartCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.startPointer(event.changedTouches[i]); + } + + }, + + /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. + * @method Phaser.Touch#onTouchCancel + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchCancel: function (event) { + + this.event = event; + + if (this.touchCancelCallback) + { + this.touchCancelCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchEnter + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnter: function (event) { + + this.event = event; + + if (this.touchEnterCallback) + { + this.touchEnterCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchLeave + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchLeave: function (event) { + + this.event = event; + + if (this.touchLeaveCallback) + { + this.touchLeaveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * The handler for the touchmove events. + * @method Phaser.Touch#onTouchMove + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchMove: function (event) { + + this.event = event; + + if (this.touchMoveCallback) + { + this.touchMoveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.updatePointer(event.changedTouches[i]); + } + + }, + + /** + * The handler for the touchend events. + * @method Phaser.Touch#onTouchEnd + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnd: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.touchEndCallback) + { + this.touchEndCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.Touch#stop + */ + stop: function () { + + if (this.game.device.touch) + { + this.game.canvas.removeEventListener('touchstart', this._onTouchStart); + this.game.canvas.removeEventListener('touchmove', this._onTouchMove); + this.game.canvas.removeEventListener('touchend', this._onTouchEnd); + this.game.canvas.removeEventListener('touchenter', this._onTouchEnter); + this.game.canvas.removeEventListener('touchleave', this._onTouchLeave); + this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel); + } + + } + +}; + +Phaser.Touch.prototype.constructor = Phaser.Touch; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. +* +* @class Phaser.InputHandler +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. +*/ +Phaser.InputHandler = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = sprite.game; + + /** + * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity. + * @default + */ + this.enabled = false; + + /** + * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks. + * @protected + */ + this.checked = false; + + /** + * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have + * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can + * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. + * @property {number} priorityID + * @default + */ + this.priorityID = 0; + + /** + * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. + * @default + */ + this.useHandCursor = false; + + /** + * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor? + * @private + */ + this._setHandCursor = false; + + /** + * @property {boolean} isDragged - true if the Sprite is being currently dragged. + * @default + */ + this.isDragged = false; + + /** + * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally. + * @default + */ + this.allowHorizontalDrag = true; + + /** + * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically. + * @default + */ + this.allowVerticalDrag = true; + + /** + * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. + * @default + */ + this.bringToTop = false; + + /** + * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset. + * @default + */ + this.snapOffset = null; + + /** + * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. + * @default + */ + this.snapOnDrag = false; + + /** + * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release. + * @default + */ + this.snapOnRelease = false; + + /** + * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid. + * @default + */ + this.snapX = 0; + + /** + * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid. + * @default + */ + this.snapY = 0; + + /** + * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid. + * @default + */ + this.snapOffsetX = 0; + + /** + * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid.. + * @default + */ + this.snapOffsetY = 0; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. + * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over. + * @default + */ + this.pixelPerfectOver = false; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive so only enable if you really need it. + * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite. + * @default + */ + this.pixelPerfectClick = false; + + /** + * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. + * @default + */ + this.pixelPerfectAlpha = 255; + + /** + * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no + * @default + */ + this.draggable = false; + + /** + * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag. + * @default + */ + this.boundsRect = null; + + /** + * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. + * @default + */ + this.boundsSprite = null; + + /** + * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. + */ + this.scaleLayer = false; + + /** + * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from. + */ + this.dragOffset = new Phaser.Point(); + + /** + * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? + */ + this.dragFromCenter = false; + + /** + * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. + */ + this.dragStopBlocksInputUp = false; + + /** + * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. + */ + this.dragStartPoint = new Phaser.Point(); + + /** + * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. + */ + this.dragDistanceThreshold = 0; + + /** + * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. + */ + this.dragTimeThreshold = 0; + + /** + * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. + */ + this.downPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. + */ + this.snapPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} _dragPoint - Internal cache var. + * @private + */ + this._dragPoint = new Phaser.Point(); + + /** + * @property {boolean} _dragPhase - Internal cache var. + * @private + */ + this._dragPhase = false; + + /** + * @property {boolean} _pendingDrag - Internal cache var. + * @private + */ + this._pendingDrag = false; + + /** + * @property {boolean} _dragTimePass - Internal cache var. + * @private + */ + this._dragTimePass = false; + + /** + * @property {boolean} _dragDistancePass - Internal cache var. + * @private + */ + this._dragDistancePass = false; + + /** + * @property {boolean} _wasEnabled - Internal cache var. + * @private + */ + this._wasEnabled = false; + + /** + * @property {Phaser.Point} _tempPoint - Internal cache var. + * @private + */ + this._tempPoint = new Phaser.Point(); + + /** + * @property {array} _pointerData - Internal cache var. + * @private + */ + this._pointerData = []; + + this._pointerData.push({ + id: 0, + x: 0, + y: 0, + camX: 0, + camY: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }); + +}; + +Phaser.InputHandler.prototype = { + + /** + * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. + * + * @method Phaser.InputHandler#start + * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. + * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) + * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound. + */ + start: function (priority, useHandCursor) { + + priority = priority || 0; + if (useHandCursor === undefined) { useHandCursor = false; } + + // Turning on + if (this.enabled === false) + { + // Register, etc + this.game.input.interactiveItems.add(this); + this.useHandCursor = useHandCursor; + this.priorityID = priority; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + + this.snapOffset = new Phaser.Point(); + this.enabled = true; + this._wasEnabled = true; + + } + + this.sprite.events.onAddedToGroup.add(this.addedToGroup, this); + this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this); + + return this.sprite; + + }, + + /** + * Handles when the parent Sprite is added to a new Group. + * + * @method Phaser.InputHandler#addedToGroup + * @private + */ + addedToGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this._wasEnabled && !this.enabled) + { + this.start(); + } + + }, + + /** + * Handles when the parent Sprite is removed from a Group. + * + * @method Phaser.InputHandler#removedFromGroup + * @private + */ + removedFromGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this.enabled) + { + this._wasEnabled = true; + this.stop(); + } + else + { + this._wasEnabled = false; + } + + }, + + /** + * Resets the Input Handler and disables it. + * @method Phaser.InputHandler#reset + */ + reset: function () { + + this.enabled = false; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + }, + + /** + * Stops the Input Handler from running. + * @method Phaser.InputHandler#stop + */ + stop: function () { + + // Turning off + if (this.enabled === false) + { + return; + } + else + { + // De-register, etc + this.enabled = false; + this.game.input.interactiveItems.remove(this); + } + + }, + + /** + * Clean up memory. + * @method Phaser.InputHandler#destroy + */ + destroy: function () { + + if (this.sprite) + { + if (this._setHandCursor) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + this.enabled = false; + + this.game.input.interactiveItems.remove(this); + + this._pointerData.length = 0; + this.boundsRect = null; + this.boundsSprite = null; + this.sprite = null; + } + + }, + + /** + * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. + * This is called by Phaser.Pointer and shouldn't typically be called directly. + * + * @method Phaser.InputHandler#validForInput + * @protected + * @param {number} highestID - The highest ID currently processed by the Pointer. + * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer. + * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? + * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection. + */ + validForInput: function (highestID, highestRenderID, includePixelPerfect) { + + if (includePixelPerfect === undefined) { includePixelPerfect = true; } + + if (!this.enabled || + this.sprite.scale.x === 0 || + this.sprite.scale.y === 0 || + this.priorityID < this.game.input.minPriorityID || + (this.sprite.parent && this.sprite.parent.ignoreChildInput)) + { + return false; + } + + // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it + if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver)) + { + return false; + } + + if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID > highestRenderID)) + { + return true; + } + + return false; + + }, + + /** + * Is this object using pixel perfect checking? + * + * @method Phaser.InputHandler#isPixelPerfect + * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. + */ + isPixelPerfect: function () { + + return (this.pixelPerfectClick || this.pixelPerfectOver); + + }, + + /** + * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerX + * @param {integer} [pointerId=0] + * @return {number} The x coordinate of the Input pointer. + */ + pointerX: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].x; + + }, + + /** + * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerY + * @param {integer} [pointerId=0] + * @return {number} The y coordinate of the Input pointer. + */ + pointerY: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].y; + + }, + + /** + * If the Pointer is down this returns true. + * This *only* checks if the Pointer is down, not if it's down over any specific Sprite. + * + * @method Phaser.InputHandler#pointerDown + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is down, otherwise false. + */ + pointerDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDown; + + }, + + /** + * If the Pointer is up this returns true. + * This *only* checks if the Pointer is up, not if it's up over any specific Sprite. + * + * @method Phaser.InputHandler#pointerUp + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is up, otherwise false. + */ + pointerUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isUp; + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeDown + * @param {integer} [pointerId=(check all)] + * @return {number} + */ + pointerTimeDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeDown; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeUp + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeUp; + + }, + + /** + * Is the Pointer over this Sprite? + * + * @method Phaser.InputHandler#pointerOver + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object. + */ + pointerOver: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOver) + { + return true; + } + } + + return false; + } + else + { + return this._pointerData[pointerId].isOver; + } + + }, + + /** + * Is the Pointer outside of this Sprite? + * + * @method Phaser.InputHandler#pointerOut + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. + */ + pointerOut: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOut) + { + return true; + } + } + } + else + { + return this._pointerData[pointerId].isOut; + } + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOver + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOver: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOver; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOut + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOut: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOut; + + }, + + /** + * Is this sprite being dragged by the mouse or not? + * + * @method Phaser.InputHandler#pointerDragged + * @param {integer} [pointerId=0] + * @return {boolean} True if the pointer is dragging an object, otherwise false. + */ + pointerDragged: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDragged; + + }, + + /** + * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerDown + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} True if the pointer is down, otherwise false. + */ + checkPointerDown: function (pointer, fastTest) { + + if (!pointer.isDown || + !this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectClick) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Checks if the given pointer is over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerOver + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} + */ + checkPointerOver: function (pointer, fastTest) { + + if (!this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectOver) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. + * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. + * + * @method Phaser.InputHandler#checkPixel + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters. + * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha + */ + checkPixel: function (x, y, pointer) { + + // Grab a pixel from our image into the hitCanvas and then test it + if (this.sprite.texture.baseTexture.source) + { + if (x === null && y === null) + { + // Use the pointer parameter + this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint); + + var x = this._tempPoint.x; + var y = this._tempPoint.y; + } + + if (this.sprite.anchor.x !== 0) + { + x -= -this.sprite.texture.frame.width * this.sprite.anchor.x; + } + + if (this.sprite.anchor.y !== 0) + { + y -= -this.sprite.texture.frame.height * this.sprite.anchor.y; + } + + x += this.sprite.texture.frame.x; + y += this.sprite.texture.frame.y; + + if (this.sprite.texture.trim) + { + x -= this.sprite.texture.trim.x; + y -= this.sprite.texture.trim.y; + + // If the coordinates are outside the trim area we return false immediately, to save doing a draw call + if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom) + { + this._dx = x; + this._dy = y; + return false; + } + } + + this._dx = x; + this._dy = y; + + this.game.input.hitContext.clearRect(0, 0, 1, 1); + this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1); + + if (rgb.data[3] >= this.pixelPerfectAlpha) + { + return true; + } + } + + return false; + + }, + + /** + * Internal Update method. This is called automatically and handles the Pointer + * and drag update loops. + * + * @method Phaser.InputHandler#update + * @protected + * @param {Phaser.Pointer} pointer + * @return {boolean} True if the pointer is still active, otherwise false. + */ + update: function (pointer) { + + if (this.sprite === null || this.sprite.parent === undefined) + { + // Abort. We've been destroyed. + return; + } + + if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible) + { + this._pointerOutHandler(pointer); + return false; + } + + if (this._pendingDrag) + { + if (!this._dragDistancePass) + { + this._dragDistancePass = (Phaser.Math.distance(pointer.x, pointer.y, this.downPoint.x, this.downPoint.y) >= this.dragDistanceThreshold); + } + + if (this._dragDistancePass && this._dragTimePass) + { + this.startDrag(pointer); + } + + return true; + } + else if (this.draggable && this._draggedPointerID === pointer.id) + { + return this.updateDrag(pointer, false); + } + else if (this._pointerData[pointer.id].isOver) + { + 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; + } + } + }, + + /** + * Internal method handling the pointer over event. + * + * @method Phaser.InputHandler#_pointerOverHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOverHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (data.isOver === false || pointer.dirty) + { + var sendEvent = (data.isOver === false); + + data.isOver = true; + data.isOut = false; + data.timeOver = this.game.time.time; + data.x = pointer.x - this.sprite.x; + data.y = pointer.y - this.sprite.y; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = "pointer"; + this._setHandCursor = true; + } + + if (!silent && sendEvent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOver$dispatch(this.sprite, pointer); + } + + if (this.sprite.parent && this.sprite.parent.onChildInputOver) + { + this.sprite.parent.onChildInputOver.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the pointer out event. + * + * @method Phaser.InputHandler#_pointerOutHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOutHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + data.isOver = false; + data.isOut = true; + data.timeOut = this.game.time.time; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + if (!silent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOut$dispatch(this.sprite, pointer); + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputOut) + { + this.sprite.parent.onChildInputOut.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the touched / clicked event. + * + * @method Phaser.InputHandler#_touchedHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + */ + _touchedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (!data.isDown && data.isOver) + { + if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer)) + { + return; + } + + data.isDown = true; + data.isUp = false; + data.timeDown = this.game.time.time; + + this.downPoint.set(pointer.x, pointer.y); + + // It's possible the onInputDown event creates a new Sprite that is on-top of this one, so we ought to force a Pointer update + pointer.dirty = true; + + if (this.sprite && this.sprite.events) + { + this.sprite.events.onInputDown$dispatch(this.sprite, pointer); + + // The event above might have destroyed this sprite. + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputDown) + { + this.sprite.parent.onChildInputDown.dispatch(this.sprite, pointer); + } + + // The events might have destroyed this sprite. + if (this.sprite === null) + { + return; + } + } + + // Start drag + if (this.draggable && this.isDragged === false) + { + if (this.dragTimeThreshold === 0 && this.dragDistanceThreshold === 0) + { + this.startDrag(pointer); + } + else + { + this._pendingDrag = true; + + this._dragDistancePass = (this.dragDistanceThreshold === 0); + + if (this.dragTimeThreshold > 0) + { + this._dragTimePass = false; + this.game.time.events.add(this.dragTimeThreshold, this.dragTimeElapsed, this, pointer); + } + else + { + this._dragTimePass = true; + } + } + } + + if (this.bringToTop) + { + this.sprite.bringToTop(); + } + } + + }, + + /** + * Internal method handling the drag threshold timer. + * + * @method Phaser.InputHandler#dragTimeElapsed + * @private + * @param {Phaser.Pointer} pointer + */ + dragTimeElapsed: function (pointer) { + + this._dragTimePass = true; + + if (this._pendingDrag && this.sprite) + { + if (this._dragDistancePass) + { + this.startDrag(pointer); + } + } + + }, + + /** + * Internal method handling the pointer released event. + * @method Phaser.InputHandler#_releasedHandler + * @private + * @param {Phaser.Pointer} pointer + */ + _releasedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + // If was previously touched by this Pointer, check if still is AND still over this item + if (data.isDown && pointer.isUp) + { + data.isDown = false; + data.isUp = true; + data.timeUp = this.game.time.time; + data.downDuration = data.timeUp - data.timeDown; + + // Only release the InputUp signal if the pointer is still over this sprite + var isOver = this.checkPointerOver(pointer); + + if (this.sprite && this.sprite.events) + { + if (!this.dragStopBlocksInputUp || + this.dragStopBlocksInputUp && !(this.draggable && this.isDragged && this._draggedPointerID === pointer.id)) + { + this.sprite.events.onInputUp$dispatch(this.sprite, pointer, isOver); + } + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputUp) + { + this.sprite.parent.onChildInputUp.dispatch(this.sprite, pointer, isOver); + } + + // The onInputUp event may have changed the sprite so that checkPointerOver is no longer true, so update it. + if (isOver) + { + isOver = this.checkPointerOver(pointer); + } + } + + data.isOver = isOver; + + if (!isOver && this.useHandCursor) + { + this.game.canvas.style.cursor = "default"; + this._setHandCursor = false; + } + + // It's possible the onInputUp event created a new Sprite that is on-top of this one, so force a Pointer update + pointer.dirty = true; + + this._pendingDrag = false; + + // Stop drag + if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id) + { + this.stopDrag(pointer); + } + } + + }, + + /** + * Called as a Pointer actively drags this Game Object. + * + * @method Phaser.InputHandler#updateDrag + * @private + * @param {Phaser.Pointer} pointer - The Pointer causing the drag update. + * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started. + * @return {boolean} + */ + updateDrag: function (pointer, fromStart) { + + if (fromStart === undefined) { fromStart = false; } + + if (pointer.isUp) + { + this.stopDrag(pointer); + return false; + } + + var pointerLocalCoord = this.globalToLocal(pointer); + + if (this.sprite.fixedToCamera) + { + var px = this.game.camera.scale.x * pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = this.game.camera.scale.y * pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + else + { + var px = pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + + if (this.sprite.fixedToCamera) + { + if (this.allowHorizontalDrag) + { + this.sprite.cameraOffset.x = px - this.game.camera.x; + } + + if (this.allowVerticalDrag) + { + this.sprite.cameraOffset.y = py - this.game.camera.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); + this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y); + } + } + else + { + var cx = this.game.camera.x - this._pointerData[pointer.id].camX; + var cy = this.game.camera.y - this._pointerData[pointer.id].camY; + + if (this.allowHorizontalDrag) + { + this.sprite.x = px + cx; + } + + if (this.allowVerticalDrag) + { + this.sprite.y = py + cy; + } + + 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); + this.snapPoint.set(this.sprite.x, this.sprite.y); + } + } + + this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint, fromStart); + + return true; + + }, + + /** + * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOver + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justOver: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOut + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justOut: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay)); + + }, + + /** + * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justPressed + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justPressed: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justReleased + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justReleased: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay)); + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#overDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. + */ + overDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isOver) + { + return this.game.time.time - this._pointerData[pointerId].timeOver; + } + + return -1; + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#downDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. + */ + downDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isDown) + { + return this.game.time.time - this._pointerData[pointerId].timeDown; + } + + return -1; + + }, + + /** + * Allow this Sprite to be dragged by any valid pointer. + * + * When the drag begins the Sprite.events.onDragStart event will be dispatched. + * + * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. + * + * You can control the thresholds over when a drag starts via the properties: + * + * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move + * before the drag will start. + * + * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on + * the Sprite before the drag will start. + * + * You can set either (or both) of these properties after enabling a Sprite for drag. + * + * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually + * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`. + * + * @method Phaser.InputHandler#enableDrag + * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. + * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group. + * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. + * @param {integer} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. + * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. + * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. + */ + enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) { + + if (lockCenter === undefined) { lockCenter = false; } + if (bringToTop === undefined) { bringToTop = false; } + if (pixelPerfect === undefined) { pixelPerfect = false; } + if (alphaThreshold === undefined) { alphaThreshold = 255; } + if (boundsRect === undefined) { boundsRect = null; } + if (boundsSprite === undefined) { boundsSprite = null; } + + this._dragPoint = new Phaser.Point(); + this.draggable = true; + this.bringToTop = bringToTop; + this.dragOffset = new Phaser.Point(); + this.dragFromCenter = lockCenter; + + this.pixelPerfectClick = pixelPerfect; + this.pixelPerfectAlpha = alphaThreshold; + + if (boundsRect) + { + this.boundsRect = boundsRect; + } + + if (boundsSprite) + { + this.boundsSprite = boundsSprite; + } + + }, + + /** + * Stops this sprite from being able to be dragged. + * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. + * + * @method Phaser.InputHandler#disableDrag + */ + disableDrag: function () { + + if (this._pointerData) + { + for (var i = 0; i < 10; i++) + { + this._pointerData[i].isDragged = false; + } + } + + this.draggable = false; + this.isDragged = false; + this._draggedPointerID = -1; + this._pendingDrag = false; + + }, + + /** + * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#startDrag + * @param {Phaser.Pointer} pointer + */ + startDrag: function (pointer) { + + var x = this.sprite.x; + var y = this.sprite.y; + var pointerLocalCoord = this.globalToLocal(pointer); + + this.isDragged = true; + this._draggedPointerID = pointer.id; + + this._pointerData[pointer.id].camX = this.game.camera.x; + this._pointerData[pointer.id].camY = this.game.camera.y; + + this._pointerData[pointer.id].isDragged = true; + + if (this.sprite.fixedToCamera) + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.cameraOffset.x = pointerLocalCoord.x + (this.sprite.cameraOffset.x - boundsCenterLocalCoord.x); + this.sprite.cameraOffset.y = pointerLocalCoord.y + (this.sprite.cameraOffset.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y); + } + else + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.x = pointerLocalCoord.x + (this.sprite.x - boundsCenterLocalCoord.x); + this.sprite.y = pointerLocalCoord.y + (this.sprite.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.x - pointerLocalCoord.x, this.sprite.y - pointerLocalCoord.y); + } + + this.updateDrag(pointer, true); + + if (this.bringToTop) + { + this._dragPhase = true; + this.sprite.bringToTop(); + } + + this.dragStartPoint.set(x, y); + + this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y); + + this._pendingDrag = false; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalX + * @param {number} x + */ + globalToLocalX: function (x) { + + if (this.scaleLayer) + { + x -= this.game.scale.grid.boundsFluid.x; + x *= this.game.scale.grid.scaleFluidInversed.x; + } + + return x; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalY + * @param {number} y + */ + globalToLocalY: function (y) { + + if (this.scaleLayer) + { + y -= this.game.scale.grid.boundsFluid.y; + y *= this.game.scale.grid.scaleFluidInversed.y; + } + + return y; + + }, + + /** + * Convert global coordinates to local sprite coordinates + * + * @method Phaser.InputHandler#globalToLocal + * @param {Phaser.Point} globalCoord - The global coordinates to convert. + * @return {Phaser.Point} A point containing the local coordinates. + */ + globalToLocal: function (globalCoord) { + + if (this.sprite.parent) + { + return this.game.input.getLocalPosition(this.sprite.parent, {x: globalCoord.x, y: globalCoord.y}); + } + else + { + return globalCoord; + } + + }, + + /** + * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#stopDrag + * @param {Phaser.Pointer} pointer + */ + stopDrag: function (pointer) { + + this.isDragged = false; + this._draggedPointerID = -1; + this._pointerData[pointer.id].isDragged = false; + this._dragPhase = false; + this._pendingDrag = false; + + if (this.snapOnRelease) + { + if (this.sprite.fixedToCamera) + { + 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 + { + 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); + } + } + + this.sprite.events.onDragStop$dispatch(this.sprite, pointer); + + if (this.checkPointerOver(pointer) === false) + { + this._pointerOutHandler(pointer); + } + + }, + + /** + * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! + * + * @method Phaser.InputHandler#setDragLock + * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false. + * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false. + */ + setDragLock: function (allowHorizontal, allowVertical) { + + if (allowHorizontal === undefined) { allowHorizontal = true; } + if (allowVertical === undefined) { allowVertical = true; } + + this.allowHorizontalDrag = allowHorizontal; + this.allowVerticalDrag = allowVertical; + + }, + + /** + * Make this Sprite snap to the given grid either during drag or when it's released. + * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. + * + * @method Phaser.InputHandler#enableSnap + * @param {number} snapX - The width of the grid cell to snap to. + * @param {number} snapY - The height of the grid cell to snap to. + * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged. + * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released. + * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid. + * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid. + */ + enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) { + + if (onDrag === undefined) { onDrag = true; } + if (onRelease === undefined) { onRelease = false; } + if (snapOffsetX === undefined) { snapOffsetX = 0; } + if (snapOffsetY === undefined) { snapOffsetY = 0; } + + this.snapX = snapX; + this.snapY = snapY; + this.snapOffsetX = snapOffsetX; + this.snapOffsetY = snapOffsetY; + this.snapOnDrag = onDrag; + this.snapOnRelease = onRelease; + + }, + + /** + * Stops the sprite from snapping to a grid during drag or release. + * + * @method Phaser.InputHandler#disableSnap + */ + disableSnap: function () { + + this.snapOnDrag = false; + this.snapOnRelease = false; + + }, + + /** + * Bounds Rect check for the sprite drag + * + * @method Phaser.InputHandler#checkBoundsRect + */ + checkBoundsRect: function () { + + if (this.sprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsRect.left) + { + this.sprite.cameraOffset.x = this.boundsRect.left; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right) + { + this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsRect.top) + { + this.sprite.cameraOffset.y = this.boundsRect.top; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom) + { + this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsRect.left) + { + this.sprite.x = this.boundsRect.x + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsRect.right) + { + this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsRect.top) + { + this.sprite.y = this.boundsRect.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsRect.bottom) + { + this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + }, + + /** + * Parent Sprite Bounds check for the sprite drag. + * + * @method Phaser.InputHandler#checkBoundsSprite + */ + checkBoundsSprite: function () { + + if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x) + { + this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width)) + { + this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y) + { + this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height)) + { + this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsSprite.left) + { + this.sprite.x = this.boundsSprite.left + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsSprite.right) + { + this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsSprite.top) + { + this.sprite.y = this.boundsSprite.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsSprite.bottom) + { + this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + } + +}; + +Phaser.InputHandler.prototype.constructor = Phaser.InputHandler; + +/** +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Gamepad class handles gamepad input and dispatches gamepad events. +* +* Remember to call `gamepad.start()`. +* +* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! +* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it +* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. +* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. +* +* @class Phaser.Gamepad +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Gamepad = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads + * @private + */ + this._gamepadIndexMap = {}; + + /** + * @property {Array} _rawPads - The raw state of the gamepads from the browser + * @private + */ + this._rawPads = []; + + /** + * @property {boolean} _active - Private flag for whether or not the API is polled + * @private + * @default + */ + this._active = false; + + /** + * Gamepad input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation. + * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not? + * @private + */ + this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') !== -1) || !!navigator.getGamepads; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevRawGamepadTypes + * @private + * @default + */ + this._prevRawGamepadTypes = []; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevTimestamps + * @private + * @default + */ + this._prevTimestamps = []; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._ongamepadconnected = null; + + /** + * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._gamepaddisconnected = null; + + /** + * @property {Array} _gamepads - The four Phaser Gamepads. + * @private + */ + this._gamepads = [ + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this) + ]; + +}; + +Phaser.Gamepad.prototype = { + + /** + * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. + * + * @method Phaser.Gamepad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callback methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + this.callbackContext = context; + } + + }, + + /** + * Starts the Gamepad event handling. + * This MUST be called manually before Phaser will start polling the Gamepad API. + * + * @method Phaser.Gamepad#start + */ + start: function () { + + if (this._active) + { + // Avoid setting multiple listeners + return; + } + + this._active = true; + + var _this = this; + + this._onGamepadConnected = function (event) { + return _this.onGamepadConnected(event); + }; + + this._onGamepadDisconnected = function (event) { + return _this.onGamepadDisconnected(event); + }; + + window.addEventListener('gamepadconnected', this._onGamepadConnected, false); + window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false); + + }, + + /** + * Handles the connection of a Gamepad. + * + * @method onGamepadConnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadConnected: function (event) { + + var newPad = event.gamepad; + this._rawPads.push(newPad); + this._gamepads[newPad.index].connect(newPad); + + }, + + /** + * Handles the disconnection of a Gamepad. + * + * @method onGamepadDisconnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadDisconnected: function (event) { + + var removedPad = event.gamepad; + + for (var i in this._rawPads) + { + if (this._rawPads[i].index === removedPad.index) + { + this._rawPads.splice(i,1); + } + } + + this._gamepads[removedPad.index].disconnect(); + + }, + + /** + * Main gamepad update loop. Should not be called manually. + * @method Phaser.Gamepad#update + * @protected + */ + update: function () { + + this._pollGamepads(); + + this.pad1.pollStatus(); + this.pad2.pollStatus(); + this.pad3.pollStatus(); + this.pad4.pollStatus(); + + }, + + /** + * Updating connected gamepads (for Google Chrome). Should not be called manually. + * + * @method Phaser.Gamepad#_pollGamepads + * @private + */ + _pollGamepads: function () { + + if (!this._active) + { + return; + } + + if (navigator['getGamepads']) + { + var rawGamepads = navigator.getGamepads(); + } + else if (navigator['webkitGetGamepads']) + { + var rawGamepads = navigator.webkitGetGamepads(); + } + else if (navigator['webkitGamepads']) + { + var rawGamepads = navigator.webkitGamepads(); + } + + if (rawGamepads) + { + this._rawPads = []; + + var gamepadsChanged = false; + + for (var i = 0; i < rawGamepads.length; i++) + { + if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i]) + { + gamepadsChanged = true; + this._prevRawGamepadTypes[i] = typeof rawGamepads[i]; + } + + if (rawGamepads[i]) + { + this._rawPads.push(rawGamepads[i]); + } + + // Support max 4 pads at the moment + if (i === 3) + { + break; + } + } + + for (var g = 0; g < this._gamepads.length; g++) + { + this._gamepads[g]._rawPad = this._rawPads[g]; + } + + if (gamepadsChanged) + { + var validConnections = { rawIndices: {}, padIndices: {} }; + var singlePad; + + for (var j = 0; j < this._gamepads.length; j++) + { + singlePad = this._gamepads[j]; + + if (singlePad.connected) + { + for (var k = 0; k < this._rawPads.length; k++) + { + if (this._rawPads[k].index === singlePad.index) + { + validConnections.rawIndices[singlePad.index] = true; + validConnections.padIndices[j] = true; + } + } + } + } + + for (var l = 0; l < this._gamepads.length; l++) + { + singlePad = this._gamepads[l]; + + if (validConnections.padIndices[l]) + { + continue; + } + + if (this._rawPads.length < 1) + { + singlePad.disconnect(); + } + + for (var m = 0; m < this._rawPads.length; m++) + { + if (validConnections.padIndices[l]) + { + break; + } + + var rawPad = this._rawPads[m]; + + if (rawPad) + { + if (validConnections.rawIndices[rawPad.index]) + { + singlePad.disconnect(); + continue; + } + else + { + singlePad.connect(rawPad); + validConnections.rawIndices[rawPad.index] = true; + validConnections.padIndices[l] = true; + } + } + else + { + singlePad.disconnect(); + } + } + } + } + } + }, + + /** + * Sets the deadZone variable for all four gamepads + * @method Phaser.Gamepad#setDeadZones + */ + setDeadZones: function (value) { + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].deadZone = value; + } + + }, + + /** + * Stops the Gamepad event handling. + * + * @method Phaser.Gamepad#stop + */ + stop: function () { + + this._active = false; + + window.removeEventListener('gamepadconnected', this._onGamepadConnected); + window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected); + + }, + + /** + * Reset all buttons/axes of all gamepads + * @method Phaser.Gamepad#reset + */ + reset: function () { + + this.update(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].reset(); + } + + }, + + /** + * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justPressed(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justReleased(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns true if the button is currently pressed down, on ANY gamepad. + * @method Phaser.Gamepad#isDown + * @param {number} buttonCode - The buttonCode of the button to check for. + * @return {boolean} True if a button is currently down. + */ + isDown: function (buttonCode) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].isDown(buttonCode) === true) + { + return true; + } + } + + return false; + }, + + /** + * Destroys this object and the associated event listeners. + * + * @method Phaser.Gamepad#destroy + */ + destroy: function () { + + this.stop(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].destroy(); + } + + } + +}; + +Phaser.Gamepad.prototype.constructor = Phaser.Gamepad; + +/** +* If the gamepad input is active or not - if not active it should not be updated from Input.js +* @name Phaser.Gamepad#active +* @property {boolean} active - If the gamepad input is active or not. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "active", { + + get: function () { + return this._active; + } + +}); + +/** +* Whether or not gamepads are supported in current browser. +* @name Phaser.Gamepad#supported +* @property {boolean} supported - Whether or not gamepads are supported in current browser. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "supported", { + + get: function () { + return this._gamepadSupportAvailable; + } + +}); + +/** +* How many live gamepads are currently connected. +* @name Phaser.Gamepad#padsConnected +* @property {number} padsConnected - How many live gamepads are currently connected. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", { + + get: function () { + return this._rawPads.length; + } + +}); + +/** +* Gamepad #1 +* @name Phaser.Gamepad#pad1 +* @property {Phaser.SinglePad} pad1 - Gamepad #1; +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad1", { + + get: function () { + return this._gamepads[0]; + } + +}); + +/** +* Gamepad #2 +* @name Phaser.Gamepad#pad2 +* @property {Phaser.SinglePad} pad2 - Gamepad #2 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad2", { + + get: function () { + return this._gamepads[1]; + } + +}); + +/** +* Gamepad #3 +* @name Phaser.Gamepad#pad3 +* @property {Phaser.SinglePad} pad3 - Gamepad #3 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad3", { + + get: function () { + return this._gamepads[2]; + } + +}); + +/** +* Gamepad #4 +* @name Phaser.Gamepad#pad4 +* @property {Phaser.SinglePad} pad4 - Gamepad #4 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad4", { + + get: function () { + return this._gamepads[3]; + } + +}); + +Phaser.Gamepad.BUTTON_0 = 0; +Phaser.Gamepad.BUTTON_1 = 1; +Phaser.Gamepad.BUTTON_2 = 2; +Phaser.Gamepad.BUTTON_3 = 3; +Phaser.Gamepad.BUTTON_4 = 4; +Phaser.Gamepad.BUTTON_5 = 5; +Phaser.Gamepad.BUTTON_6 = 6; +Phaser.Gamepad.BUTTON_7 = 7; +Phaser.Gamepad.BUTTON_8 = 8; +Phaser.Gamepad.BUTTON_9 = 9; +Phaser.Gamepad.BUTTON_10 = 10; +Phaser.Gamepad.BUTTON_11 = 11; +Phaser.Gamepad.BUTTON_12 = 12; +Phaser.Gamepad.BUTTON_13 = 13; +Phaser.Gamepad.BUTTON_14 = 14; +Phaser.Gamepad.BUTTON_15 = 15; + +Phaser.Gamepad.AXIS_0 = 0; +Phaser.Gamepad.AXIS_1 = 1; +Phaser.Gamepad.AXIS_2 = 2; +Phaser.Gamepad.AXIS_3 = 3; +Phaser.Gamepad.AXIS_4 = 4; +Phaser.Gamepad.AXIS_5 = 5; +Phaser.Gamepad.AXIS_6 = 6; +Phaser.Gamepad.AXIS_7 = 7; +Phaser.Gamepad.AXIS_8 = 8; +Phaser.Gamepad.AXIS_9 = 9; + +// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7). +// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button. +// In other words - discrepancies when using gamepads. + +Phaser.Gamepad.XBOX360_A = 0; +Phaser.Gamepad.XBOX360_B = 1; +Phaser.Gamepad.XBOX360_X = 2; +Phaser.Gamepad.XBOX360_Y = 3; +Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4; +Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5; +Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6; +Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7; +Phaser.Gamepad.XBOX360_BACK = 8; +Phaser.Gamepad.XBOX360_START = 9; +Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11; + +Phaser.Gamepad.XBOX360_DPAD_LEFT = 14; +Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15; +Phaser.Gamepad.XBOX360_DPAD_UP = 12; +Phaser.Gamepad.XBOX360_DPAD_DOWN = 13; + +// On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right +Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0; +Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1; +Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2; +Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3; + +// PlayStation 3 controller (masquerading as xbox360 controller) button mappings + +Phaser.Gamepad.PS3XC_X = 0; +Phaser.Gamepad.PS3XC_CIRCLE = 1; +Phaser.Gamepad.PS3XC_SQUARE = 2; +Phaser.Gamepad.PS3XC_TRIANGLE = 3; +Phaser.Gamepad.PS3XC_L1 = 4; +Phaser.Gamepad.PS3XC_R1 = 5; +Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_SELECT = 8; +Phaser.Gamepad.PS3XC_START = 9; +Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11; +Phaser.Gamepad.PS3XC_DPAD_UP = 12; +Phaser.Gamepad.PS3XC_DPAD_DOWN = 13; +Phaser.Gamepad.PS3XC_DPAD_LEFT = 14; +Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15; +Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1 + +/** +* @author @karlmacklin +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A single Phaser Gamepad +* +* @class Phaser.SinglePad +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this) +*/ +Phaser.SinglePad = function (game, padParent) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {number} index - The gamepad index as per browsers data + * @readonly + */ + this.index = null; + + /** + * @property {boolean} connected - Whether or not this particular gamepad is connected or not. + * @readonly + */ + this.connected = false; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time a button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time an axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates. + */ + this.deadZone = 0.26; + + /** + * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object + * @private + */ + this._padParent = padParent; + + /** + * @property {object} _rawPad - The 'raw' gamepad data. + * @private + */ + this._rawPad = null; + + /** + * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads. + * @private + */ + this._prevTimestamp = null; + + /** + * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected. + * @private + */ + this._buttons = []; + + /** + * @property {number} _buttonsLen - Length of the _buttons array. + * @private + */ + this._buttonsLen = 0; + + /** + * @property {Array} _axes - Current axes state. + * @private + */ + this._axes = []; + + /** + * @property {number} _axesLen - Length of the _axes array. + * @private + */ + this._axesLen = 0; + +}; + +Phaser.SinglePad.prototype = { + + /** + * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. + * + * @method Phaser.SinglePad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callbak methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + + this.callbackContext = context; + } + }, + + /** + * Gets a DeviceButton object from this controller to be stored and referenced locally. + * The DeviceButton object can then be polled, have events attached to it, etc. + * + * @method Phaser.SinglePad#getButton + * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc. + * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly. + */ + getButton: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode]; + } + else + { + return null; + } + + }, + + /** + * Main update function called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#pollStatus + */ + pollStatus: function () { + + if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp))) + { + return; + } + + for (var i = 0; i < this._buttonsLen; i++) + { + var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i]; + + if (rawButtonVal !== this._buttons[i].value) + { + if (rawButtonVal === 1) + { + this.processButtonDown(i, rawButtonVal); + } + else if (rawButtonVal === 0) + { + this.processButtonUp(i, rawButtonVal); + } + else + { + this.processButtonFloat(i, rawButtonVal); + } + } + } + + for (var index = 0; index < this._axesLen; index++) + { + var value = this._rawPad.axes[index]; + + if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone)) + { + this.processAxisChange(index, value); + } + else + { + this.processAxisChange(index, 0); + } + } + + this._prevTimestamp = this._rawPad.timestamp; + + }, + + /** + * Gamepad connect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#connect + * @param {object} rawPad - The raw gamepad object + */ + connect: function (rawPad) { + + var triggerCallback = !this.connected; + + this.connected = true; + this.index = rawPad.index; + + this._rawPad = rawPad; + + this._buttons = []; + this._buttonsLen = rawPad.buttons.length; + + this._axes = []; + this._axesLen = rawPad.axes.length; + + for (var a = 0; a < this._axesLen; a++) + { + this._axes[a] = rawPad.axes[a]; + } + + for (var buttonCode in rawPad.buttons) + { + buttonCode = parseInt(buttonCode, 10); + this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode); + } + + if (triggerCallback && this._padParent.onConnectCallback) + { + this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index); + } + + if (triggerCallback && this.onConnectCallback) + { + this.onConnectCallback.call(this.callbackContext); + } + + }, + + /** + * Gamepad disconnect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#disconnect + */ + disconnect: function () { + + var triggerCallback = this.connected; + var disconnectingIndex = this.index; + + this.connected = false; + this.index = null; + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + if (triggerCallback && this._padParent.onDisconnectCallback) + { + this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex); + } + + if (triggerCallback && this.onDisconnectCallback) + { + this.onDisconnectCallback.call(this.callbackContext); + } + + }, + + /** + * Destroys this object and associated callback references. + * + * @method Phaser.SinglePad#destroy + */ + destroy: function () { + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + this.onConnectCallback = null; + this.onDisconnectCallback = null; + this.onDownCallback = null; + this.onUpCallback = null; + this.onAxisCallback = null; + this.onFloatCallback = null; + + }, + + /** + * Handles changes in axis. + * + * @method Phaser.SinglePad#processAxisChange + * @param {object} axisState - State of the relevant axis + */ + processAxisChange: function (index, value) { + + if (this._axes[index] === value) + { + return; + } + + this._axes[index] = value; + + if (this._padParent.onAxisCallback) + { + this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value); + } + + if (this.onAxisCallback) + { + this.onAxisCallback.call(this.callbackContext, this, index, value); + } + + }, + + /** + * Handles button down press. + * + * @method Phaser.SinglePad#processButtonDown + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonDown: function (buttonCode, value) { + + if (this._buttons[buttonCode]) + { + this._buttons[buttonCode].start(null, value); + } + + 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); + } + + }, + + /** + * Handles button release. + * + * @method Phaser.SinglePad#processButtonUp + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonUp: function (buttonCode, value) { + + 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._buttons[buttonCode]) + { + this._buttons[buttonCode].stop(null, value); + } + + }, + + /** + * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) + * + * @method Phaser.SinglePad#processButtonFloat + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. + */ + processButtonFloat: function (buttonCode, value) { + + 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].padFloat(value); + } + + }, + + /** + * Returns value of requested axis. + * + * @method Phaser.SinglePad#axis + * @param {number} axisCode - The index of the axis to check + * @return {number} Axis value if available otherwise false + */ + axis: function (axisCode) { + + if (this._axes[axisCode]) + { + return this._axes[axisCode]; + } + + return false; + + }, + + /** + * Returns true if the button is pressed down. + * + * @method Phaser.SinglePad#isDown + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is pressed down. + */ + isDown: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isDown; + } + + return false; + + }, + + /** + * Returns true if the button is not currently pressed. + * + * @method Phaser.SinglePad#isUp + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is not currently pressed down. + */ + isUp: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isUp; + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justReleased + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justReleased(duration); + } + + }, + + /** + * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justPressed(duration); + } + + }, + + /** + * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example + * analog trigger buttons on the XBOX 360 controller. + * + * @method Phaser.SinglePad#buttonValue + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. + */ + buttonValue: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].value; + } + + return null; + + }, + + /** + * Reset all buttons/axes of this gamepad. + * + * @method Phaser.SinglePad#reset + */ + reset: function () { + + for (var j = 0; j < this._axes.length; j++) + { + this._axes[j] = 0; + } + + } + +}; + +Phaser.SinglePad.prototype.constructor = Phaser.SinglePad; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. +* +* @class Phaser.Key +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}. +*/ +Phaser.Key = function (game, keycode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * The enabled state of the key - see `enabled`. + * @property {boolean} _enabled + * @private + */ + this._enabled = true; + + /** + * @property {object} event - Stores the most recent DOM event. + * @readonly + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * @default + */ + this.isUp = true; + + /** + * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. + * @default + */ + this.altKey = false; + + /** + * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. + * @default + */ + this.ctrlKey = false; + + /** + * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. + * @default + */ + this.shiftKey = false; + + /** + * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now. + */ + this.timeDown = 0; + + /** + * If the key is down this value holds the duration of that key press and is constantly updated. + * If the key is up it holds the duration of the previous down session. + * @property {number} duration - The number of milliseconds this key has been held down for. + * @default + */ + this.duration = 0; + + /** + * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now. + * @default + */ + this.timeUp = -2500; + + /** + * If the key is up this value holds the duration of that key release and is constantly updated. + * If the key is down it holds the duration of the previous up session. + * @property {number} duration - The number of milliseconds this key has been up for. + * @default + */ + this.durationUp = -2500; + + /** + * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. + * @default + */ + this.repeats = 0; + + /** + * @property {number} keyCode - The keycode of this key. + */ + this.keyCode = keycode; + + /** + * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). + */ + this.onDown = new Phaser.Signal(); + + /** + * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. + */ + this.onHoldCallback = null; + + /** + * @property {object} onHoldContext - The context under which the onHoldCallback will be called. + */ + this.onHoldContext = null; + + /** + * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). + */ + this.onUp = new Phaser.Signal(); + + /** + * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justDown = false; + + /** + * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justUp = false; + +}; + +Phaser.Key.prototype = { + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#update + * @protected + */ + update: function () { + + if (!this._enabled) { return; } + + if (this.isDown) + { + this.duration = this.game.time.time - this.timeDown; + this.repeats++; + + if (this.onHoldCallback) + { + this.onHoldCallback.call(this.onHoldContext, this); + } + } + else + { + this.durationUp = this.game.time.time - this.timeUp; + } + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyDown + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyDown: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + // exit if this key down is from auto-repeat + if (this.isDown) + { + return; + } + + this.altKey = event.altKey; + this.ctrlKey = event.ctrlKey; + this.shiftKey = event.shiftKey; + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.duration = 0; + this.durationUp = this.game.time.time - this.timeUp; + this.repeats = 0; + + // _justDown will remain true until it is read via the justDown Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justDown = true; + + this.onDown.dispatch(this); + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyUp + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyUp: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = this.game.time.time - this.timeDown; + this.durationUp = 0; + + // _justUp will remain true until it is read via the justUp Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justUp = true; + + this.onUp.dispatch(this); + + }, + + /** + * Resets the state of this Key. + * + * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key. + * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. + * + * @method Phaser.Key#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = 0; + this.durationUp = -2500; + this._enabled = true; // .enabled causes reset(false) + this._justDown = false; + this._justUp = false; + + if (hard) + { + this.onDown.removeAll(); + this.onUp.removeAll(); + this.onHoldCallback = null; + this.onHoldContext = null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#downDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration. + */ + downDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (this.isDown && this.duration < duration); + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#upDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration. + */ + upDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (!this.isDown && ((this.game.time.time - this.timeUp) < duration)); + + }, + + /** + * Returns `true` if the Key was just pressed down this update tick, or `false` if it either isn't down, + * or was pressed down on a previous update tick. + * + * @method Phaser.Key#justPressed + * @return {boolean} True if the key was just pressed down this update tick. + */ + justPressed: function () { + + return (this.isDown && this.duration === 0); + + }, + + /** + * Returns `true` if the Key was just released this update tick, or `false` if it either isn't up, + * or was released on a previous update tick. + * + * @method Phaser.Key#justReleased + * @return {boolean} True if the key was just released this update tick. + */ + justReleased: function () { + + return (!this.isDown && this.durationUp === 0); + + } + +}; + +/** +* The justDown value allows you to test if this Key has just been pressed down or not. +* When you check this value it will return `true` if the Key is down, otherwise `false`. +* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. +* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justDown +* @property {boolean} justDown +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justDown", { + + get: function () { + + var current = this._justDown; + this._justDown = false; + return current; + + } + +}); + +/** +* The justUp value allows you to test if this Key has just been released or not. +* When you check this value it will return `true` if the Key is up, otherwise `false`. +* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again. +* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justUp +* @property {boolean} justUp +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justUp", { + + get: function () { + + var current = this._justUp; + this._justUp = false; + return current; + + } + +}); + +/** +* An enabled key processes its update and dispatches events. +* A key can be disabled momentarily at runtime instead of deleting it. +* @name Phaser.Key#enabled +* @property {boolean} enabled +* @memberof Phaser.Key +* @default true +*/ +Object.defineProperty(Phaser.Key.prototype, "enabled", { + + get: function () { + + return this._enabled; + + }, + + set: function (value) { + + value = !!value; + + if (value !== this._enabled) + { + if (!value) + { + this.reset(false); + } + + this._enabled = value; + } + } + +}); + +Phaser.Key.prototype.constructor = Phaser.Key; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Keyboard class monitors keyboard input and dispatches keyboard events. +* +* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. +* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. +* +* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. +* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. +* So please check your extensions before opening Phaser issues. +* +* @class Phaser.Keyboard +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Keyboard = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Keyboard input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. + */ + this.event = null; + + /** + * @property {object} pressEvent - The most recent DOM event from keypress. + */ + this.pressEvent = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. + */ + this.onDownCallback = null; + + /** + * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. + */ + this.onPressCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a key is released. + */ + this.onUpCallback = null; + + /** + * @property {array} _keys - The array the Phaser.Key objects are stored in. + * @private + */ + this._keys = []; + + /** + * @property {array} _capture - The array the key capture values are stored in. + * @private + */ + this._capture = []; + + /** + * @property {function} _onKeyDown + * @private + * @default + */ + this._onKeyDown = null; + + /** + * @property {function} _onKeyPress + * @private + * @default + */ + this._onKeyPress = null; + + /** + * @property {function} _onKeyUp + * @private + * @default + */ + this._onKeyUp = null; + + /** + * @property {number} _i - Internal cache var + * @private + */ + this._i = 0; + + /** + * @property {number} _k - Internal cache var + * @private + */ + this._k = 0; + +}; + +Phaser.Keyboard.prototype = { + + /** + * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. + * + * @method Phaser.Keyboard#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down. + * @param {function} [onUp=null] - This callback is invoked every time a key is released. + * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised. + */ + addCallbacks: function (context, onDown, onUp, onPress) { + + this.callbackContext = context; + + if (onDown !== undefined && onDown !== null) + { + this.onDownCallback = onDown; + } + + if (onUp !== undefined && onUp !== null) + { + this.onUpCallback = onUp; + } + + if (onPress !== undefined && onPress !== null) + { + this.onPressCallback = onPress; + } + + }, + + /** + * Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}. + * + * @method Phaser.Keyboard#removeCallbacks + */ + removeCallbacks: function () { + + this.callbackContext = this; + this.onDownCallback = null; + this.onUpCallback = null; + this.onPressCallback = null; + + }, + + /** + * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. + * The Key object can then be polled, have events attached to it, etc. + * + * @method Phaser.Keyboard#addKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key. + * @return {Phaser.Key} The Key object which you can store locally and reference directly. + */ + addKey: function (keycode) { + + if (!this._keys[keycode]) + { + this._keys[keycode] = new Phaser.Key(this.game, keycode); + + this.addKeyCapture(keycode); + } + + return this._keys[keycode]; + + }, + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example, + * + * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); + * + * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object. + * + * @method Phaser.Keyboard#addKeys + * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. + * @return {object} An object containing the properties mapped to {@link Phaser.Key} values. + */ + addKeys: function (keys) { + + var output = {}; + + for (var key in keys) + { + output[key] = this.addKey(keys[key]); + } + + return output; + + }, + + /** + * Removes a Key object from the Keyboard manager. + * + * @method Phaser.Keyboard#removeKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove. + */ + removeKey: function (keycode) { + + if (this._keys[keycode]) + { + this._keys[keycode] = null; + + this.removeKeyCapture(keycode); + } + + }, + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. + * + * @method Phaser.Keyboard#createCursorKeys + * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects. + */ + createCursorKeys: function () { + + return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT }); + + }, + + /** + * Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window. + * This is called automatically by Phaser.Input and should not normally be invoked directly. + * + * @method Phaser.Keyboard#start + * @protected + */ + start: function () { + + if (this.game.device.cocoonJS) + { + return; + } + + if (this._onKeyDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onKeyDown = function (event) { + return _this.processKeyDown(event); + }; + + this._onKeyUp = function (event) { + return _this.processKeyUp(event); + }; + + this._onKeyPress = function (event) { + return _this.processKeyPress(event); + }; + + window.addEventListener('keydown', this._onKeyDown, false); + window.addEventListener('keyup', this._onKeyUp, false); + window.addEventListener('keypress', this._onKeyPress, false); + + }, + + /** + * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. + * + * @method Phaser.Keyboard#stop + */ + stop: function () { + + window.removeEventListener('keydown', this._onKeyDown); + window.removeEventListener('keyup', this._onKeyUp); + window.removeEventListener('keypress', this._onKeyPress); + + this._onKeyDown = null; + this._onKeyUp = null; + this._onKeyPress = null; + + }, + + /** + * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. + * Also clears all key captures and currently created Key objects. + * + * @method Phaser.Keyboard#destroy + */ + destroy: function () { + + this.stop(); + + this.clearCaptures(); + + this._keys.length = 0; + this._i = 0; + + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Pass in either a single keycode or an array/hash of keycodes. + * + * @method Phaser.Keyboard#addKeyCapture + * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`. + */ + addKeyCapture: function (keycode) { + + if (typeof keycode === 'object') + { + for (var key in keycode) + { + this._capture[keycode[key]] = true; + } + } + else + { + this._capture[keycode] = true; + } + }, + + /** + * Removes an existing key capture. + * + * @method Phaser.Keyboard#removeKeyCapture + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of. + */ + removeKeyCapture: function (keycode) { + + delete this._capture[keycode]; + + }, + + /** + * Clear all set key captures. + * + * @method Phaser.Keyboard#clearCaptures + */ + clearCaptures: function () { + + this._capture = {}; + + }, + + /** + * Updates all currently defined keys. + * + * @method Phaser.Keyboard#update + */ + update: function () { + + this._i = this._keys.length; + + while (this._i--) + { + if (this._keys[this._i]) + { + this._keys[this._i].update(); + } + } + + }, + + /** + * Process the keydown event. + * + * @method Phaser.Keyboard#processKeyDown + * @param {KeyboardEvent} event + * @protected + */ + processKeyDown: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + // The event is being captured but another hotkey may need it + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyDown(event); + + this._k = key; + + if (this.onDownCallback) + { + this.onDownCallback.call(this.callbackContext, event); + } + + }, + + /** + * Process the keypress event. + * + * @method Phaser.Keyboard#processKeyPress + * @param {KeyboardEvent} event + * @protected + */ + processKeyPress: function (event) { + + this.pressEvent = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.onPressCallback) + { + this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event); + } + + }, + + /** + * Process the keyup event. + * + * @method Phaser.Keyboard#processKeyUp + * @param {KeyboardEvent} event + * @protected + */ + processKeyUp: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyUp(event); + + if (this.onUpCallback) + { + this.onUpCallback.call(this.callbackContext, event); + } + + }, + + /** + * Resets all Keys. + * + * @method Phaser.Keyboard#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.event = null; + + var i = this._keys.length; + + while (i--) + { + if (this._keys[i]) + { + this._keys[i].reset(hard); + } + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#downDuration + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. + */ + downDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].downDuration(duration); + } + else + { + return null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#upDuration + * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found. + */ + upDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].upDuration(duration); + } + else + { + return null; + } + + }, + + justPressed: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justPressed(); + } + else + { + return null; + } + + }, + + justReleased: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justReleased(); + } + else + { + return null; + } + + }, + + /** + * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. + * + * @method Phaser.Keyboard#isDown + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found. + */ + isDown: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].isDown; + } + else + { + return null; + } + + } + +}; + +/** +* Returns the string value of the most recently pressed key. +* @name Phaser.Keyboard#lastChar +* @property {string} lastChar - The string value of the most recently pressed key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", { + + get: function () { + + if (this.event && this.event.charCode === 32) + { + return ''; + } + else if (this.pressEvent) + { + return String.fromCharCode(this.pressEvent.charCode); + } + else + { + return null; + } + + } + +}); + +/** +* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. +* @name Phaser.Keyboard#lastKey +* @property {Phaser.Key} lastKey - The most recently pressed Key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", { + + get: function () { + + return this._keys[this._k]; + + } + +}); + +Phaser.Keyboard.prototype.constructor = Phaser.Keyboard; + +/** +* A key code represents a physical key on a keyboard. +* +* The KeyCode class contains commonly supported keyboard key codes which can be used +* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods. +* +* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. +* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. +* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property. +* +* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; +* the latter approach is supported for compatibility. +* +* @class Phaser.KeyCode +*/ +Phaser.KeyCode = { + /** @static */ + A: "A".charCodeAt(0), + /** @static */ + B: "B".charCodeAt(0), + /** @static */ + C: "C".charCodeAt(0), + /** @static */ + D: "D".charCodeAt(0), + /** @static */ + E: "E".charCodeAt(0), + /** @static */ + F: "F".charCodeAt(0), + /** @static */ + G: "G".charCodeAt(0), + /** @static */ + H: "H".charCodeAt(0), + /** @static */ + I: "I".charCodeAt(0), + /** @static */ + J: "J".charCodeAt(0), + /** @static */ + K: "K".charCodeAt(0), + /** @static */ + L: "L".charCodeAt(0), + /** @static */ + M: "M".charCodeAt(0), + /** @static */ + N: "N".charCodeAt(0), + /** @static */ + O: "O".charCodeAt(0), + /** @static */ + P: "P".charCodeAt(0), + /** @static */ + Q: "Q".charCodeAt(0), + /** @static */ + R: "R".charCodeAt(0), + /** @static */ + S: "S".charCodeAt(0), + /** @static */ + T: "T".charCodeAt(0), + /** @static */ + U: "U".charCodeAt(0), + /** @static */ + V: "V".charCodeAt(0), + /** @static */ + W: "W".charCodeAt(0), + /** @static */ + X: "X".charCodeAt(0), + /** @static */ + Y: "Y".charCodeAt(0), + /** @static */ + Z: "Z".charCodeAt(0), + /** @static */ + ZERO: "0".charCodeAt(0), + /** @static */ + ONE: "1".charCodeAt(0), + /** @static */ + TWO: "2".charCodeAt(0), + /** @static */ + THREE: "3".charCodeAt(0), + /** @static */ + FOUR: "4".charCodeAt(0), + /** @static */ + FIVE: "5".charCodeAt(0), + /** @static */ + SIX: "6".charCodeAt(0), + /** @static */ + SEVEN: "7".charCodeAt(0), + /** @static */ + EIGHT: "8".charCodeAt(0), + /** @static */ + NINE: "9".charCodeAt(0), + /** @static */ + NUMPAD_0: 96, + /** @static */ + NUMPAD_1: 97, + /** @static */ + NUMPAD_2: 98, + /** @static */ + NUMPAD_3: 99, + /** @static */ + NUMPAD_4: 100, + /** @static */ + NUMPAD_5: 101, + /** @static */ + NUMPAD_6: 102, + /** @static */ + NUMPAD_7: 103, + /** @static */ + NUMPAD_8: 104, + /** @static */ + NUMPAD_9: 105, + /** @static */ + NUMPAD_MULTIPLY: 106, + /** @static */ + NUMPAD_ADD: 107, + /** @static */ + NUMPAD_ENTER: 108, + /** @static */ + NUMPAD_SUBTRACT: 109, + /** @static */ + NUMPAD_DECIMAL: 110, + /** @static */ + NUMPAD_DIVIDE: 111, + /** @static */ + F1: 112, + /** @static */ + F2: 113, + /** @static */ + F3: 114, + /** @static */ + F4: 115, + /** @static */ + F5: 116, + /** @static */ + F6: 117, + /** @static */ + F7: 118, + /** @static */ + F8: 119, + /** @static */ + F9: 120, + /** @static */ + F10: 121, + /** @static */ + F11: 122, + /** @static */ + F12: 123, + /** @static */ + F13: 124, + /** @static */ + F14: 125, + /** @static */ + F15: 126, + /** @static */ + COLON: 186, + /** @static */ + EQUALS: 187, + /** @static */ + COMMA: 188, + /** @static */ + UNDERSCORE: 189, + /** @static */ + PERIOD: 190, + /** @static */ + QUESTION_MARK: 191, + /** @static */ + TILDE: 192, + /** @static */ + OPEN_BRACKET: 219, + /** @static */ + BACKWARD_SLASH: 220, + /** @static */ + CLOSED_BRACKET: 221, + /** @static */ + QUOTES: 222, + /** @static */ + BACKSPACE: 8, + /** @static */ + TAB: 9, + /** @static */ + CLEAR: 12, + /** @static */ + ENTER: 13, + /** @static */ + SHIFT: 16, + /** @static */ + CONTROL: 17, + /** @static */ + ALT: 18, + /** @static */ + CAPS_LOCK: 20, + /** @static */ + ESC: 27, + /** @static */ + SPACEBAR: 32, + /** @static */ + PAGE_UP: 33, + /** @static */ + PAGE_DOWN: 34, + /** @static */ + END: 35, + /** @static */ + HOME: 36, + /** @static */ + LEFT: 37, + /** @static */ + UP: 38, + /** @static */ + RIGHT: 39, + /** @static */ + DOWN: 40, + /** @static */ + PLUS: 43, + /** @static */ + MINUS: 44, + /** @static */ + INSERT: 45, + /** @static */ + DELETE: 46, + /** @static */ + HELP: 47, + /** @static */ + NUM_LOCK: 144 +}; + +// Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility +for (var key in Phaser.KeyCode) +{ + if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/)) + { + Phaser.Keyboard[key] = Phaser.KeyCode[key]; + } +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +Phaser.Component = function () {}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. +* +* @class +*/ +Phaser.Component.Angle = function () {}; + +Phaser.Component.Angle.prototype = { + + /** + * The angle property is the rotation of the Game Object in *degrees* from its original orientation. + * + * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. + * + * Values outside this range are added to or subtracted from 360 to obtain a value within the range. + * For example, the statement player.angle = 450 is the same as player.angle = 90. + * + * If you wish to work in radians instead of degrees you can use the property `rotation` instead. + * Working in radians is slightly faster as it doesn't have to perform any calculations. + * + * @property {number} angle + */ + angle: { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); + + }, + + set: function(value) { + + this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. +* +* @class +*/ +Phaser.Component.Animation = function () {}; + +Phaser.Component.Animation.prototype = { + + /** + * Plays an Animation. + * + * The animation should have previously been created via `animations.add`. + * + * If the animation is already playing calling this again won't do anything. + * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. + * + * @method + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation. + */ + play: function (name, frameRate, loop, killOnComplete) { + + if (this.animations) + { + return this.animations.play(name, frameRate, loop, killOnComplete); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. +* It is used by the InWorld component. +* +* @class +*/ +Phaser.Component.AutoCull = function () {}; + +Phaser.Component.AutoCull.prototype = { + + /** + * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. + * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. + * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} autoCull + * @default + */ + autoCull: false, + + /** + * Checks if the Game Objects bounds intersect with the Game Camera bounds. + * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + if (!this.autoCull && !this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + } + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Bounds component contains properties related to the bounds of the Game Object. +* +* @class +*/ +Phaser.Component.Bounds = function () {}; + +Phaser.Component.Bounds.prototype = { + + /** + * The amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * anchor.x`. + * It will only be > 0 if anchor.x is not equal to zero. + * + * @property {number} offsetX + * @readOnly + */ + offsetX: { + + get: function () { + + return this.anchor.x * this.width; + + } + + }, + + /** + * The amount the Game Object is visually offset from its y coordinate. + * This is the same as `height * anchor.y`. + * It will only be > 0 if anchor.y is not equal to zero. + * + * @property {number} offsetY + * @readOnly + */ + offsetY: { + + get: function () { + + return this.anchor.y * this.height; + + } + + }, + + /** + * The local center x coordinate of the Game Object. + * This is the same as `(x - offsetX) + (width / 2)`. + * + * @property {number} centerX + */ + centerX: { + + get: function () { + + return (this.x - this.offsetX) + (this.width * 0.5); + + }, + + set: function (value) { + + this.x = (value + this.offsetX) - (this.width * 0.5); + + } + + }, + + /** + * The local center y coordinate of the Game Object. + * This is the same as `(y - offsetY) + (height / 2)`. + * + * @property {number} centerY + */ + centerY: { + + get: function () { + + return (this.y - this.offsetY) + (this.height * 0.5); + + }, + + set: function (value) { + + this.y = (value + this.offsetY) - (this.height * 0.5); + + } + + }, + + /** + * The left coordinate of the Game Object. + * This is the same as `x - offsetX`. + * + * @property {number} left + */ + left: { + + get: function () { + + return this.x - this.offsetX; + + }, + + set: function (value) { + + this.x = value + this.offsetX; + + } + + }, + + /** + * The right coordinate of the Game Object. + * This is the same as `x + width - offsetX`. + * + * @property {number} right + */ + right: { + + get: function () { + + return (this.x + this.width) - this.offsetX; + + }, + + set: function (value) { + + this.x = value - (this.width) + this.offsetX; + + } + + }, + + /** + * The y coordinate of the Game Object. + * This is the same as `y - offsetY`. + * + * @property {number} top + */ + top: { + + get: function () { + + return this.y - this.offsetY; + + }, + + set: function (value) { + + this.y = value + this.offsetY; + + } + + }, + + /** + * The sum of the y and height properties. + * This is the same as `y + height - offsetY`. + * + * @property {number} bottom + */ + bottom: { + + get: function () { + + return (this.y + this.height) - this.offsetY; + + }, + + set: function (value) { + + this.y = value - (this.height) + this.offsetY; + + } + + }, + + /** + * Aligns this Game Object within another Game Object, or Rectangle, known as the + * 'container', to one of 9 possible positions. + * + * The container must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the container. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, + * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * container, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignIn: function (container, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = container.left - offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = container.centerX + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = container.right + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.left = container.left - offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.CENTER: + this.centerX = container.centerX + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.right = container.right + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = container.left - offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = container.centerX + offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = container.right + offsetX; + this.bottom = container.bottom + offsetY; + break; + } + + return this; + + }, + + /** + * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the + * 'parent', in one of 11 possible positions. + * + * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the parent. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, + * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, + * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * parent, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignTo: function (parent, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = parent.left - offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = parent.centerX + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = parent.right + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.LEFT_TOP: + this.right = parent.left - offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.right = parent.left - offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.LEFT_BOTTOM: + this.right = parent.left - offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.RIGHT_TOP: + this.left = parent.right + offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.left = parent.right + offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.RIGHT_BOTTOM: + this.left = parent.right + offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = parent.left - offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = parent.centerX + offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = parent.right + offsetX; + this.top = parent.bottom + offsetY; + break; + } + + return this; + + } + +}; + +// Phaser.Group extensions + +Phaser.Group.prototype.alignIn = Phaser.Component.Bounds.prototype.alignIn; +Phaser.Group.prototype.alignTo = Phaser.Component.Bounds.prototype.alignTo; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The BringToTop Component features quick access to Group sorting related methods. +* +* @class +*/ +Phaser.Component.BringToTop = function () {}; + +/** +* Brings this Game Object to the top of its parents display list. +* Visually this means it will render over the top of any old child in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.bringToTop = function() { + + if (this.parent) + { + this.parent.bringToTop(this); + } + + return this; + +}; + +/** +* Sends this Game Object to the bottom of its parents display list. +* Visually this means it will render below all other children in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.sendToBack = function() { + + if (this.parent) + { + this.parent.sendToBack(this); + } + + return this; + +}; + +/** +* Moves this Game Object up one place in its parents display list. +* This call has no effect if the Game Object is already at the top of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveUp = function () { + + if (this.parent) + { + this.parent.moveUp(this); + } + + return this; + +}; + +/** +* Moves this Game Object down one place in its parents display list. +* This call has no effect if the Game Object is already at the bottom of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveDown = function () { + + if (this.parent) + { + this.parent.moveDown(this); + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Core Component Features. +* +* @class +*/ +Phaser.Component.Core = function () {}; + +/** + * @property {boolean} skipTypeChecks - Skip type checks in {@link #init}. + * @static + * @default + */ +Phaser.Component.Core.skipTypeChecks = false; + +/** +* Installs / registers mixin components. +* +* The `this` context should be that of the applicable object instance or prototype. +* +* @method +* @protected +*/ +Phaser.Component.Core.install = function (components) { + + // Always install 'Core' first + Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype); + + this.components = {}; + + for (var i = 0; i < components.length; i++) + { + var id = components[i]; + var replace = false; + + if (id === 'Destroy') + { + replace = true; + } + + Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace); + + this.components[id] = true; + } + +}; + +/** +* Initializes the mixin components. +* +* The `this` context should be an instance of the component mixin target. +* +* @method +* @protected +*/ +Phaser.Component.Core.init = function (game, x, y, key, frame) { + + if (!Phaser.Component.Core.skipTypeChecks) + { + if (!(game instanceof Phaser.Game)) + { + throw new Error('The value passed as the `game` argument (' + game + ') is not an instance of Phaser.Game.'); + } + + if (typeof x !== 'number') + { + console.warn('The `x` argument value (%s) should be a number.', x); + x = 0; // This would be done implicitly in position.set(). + } + + if (typeof y !== 'number') + { + console.warn('The `y` argument value (%s) should be a number.', y); + y = 0; // This would be done implicitly in position.set(). + } + } + + this.game = game; + this.key = key; + this.data = {}; + + this.position.set(x, y); + this.world = new Phaser.Point(x, y); + this.previousPosition = new Phaser.Point(x, y); + + this.events = new Phaser.Events(this); + + this._bounds = new Phaser.Rectangle(); + + if (this.components.PhysicsBody) + { + // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype. + this.body = this.body; + } + + if (this.components.Animation) + { + this.animations = new Phaser.AnimationManager(this); + } + + if (this.components.LoadTexture && key !== null) + { + this.loadTexture(key, frame); + } + + if (this.components.FixedToCamera) + { + this.cameraOffset = new Phaser.Point(x, y); + } + +}; + +Phaser.Component.Core.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty); + + if (this.visible) + { + this.renderOrderID = this.game.stage.currentRenderOrderID++; + } + + if (this.animations) + { + this.animations.update(); + } + + if (this.body) + { + this.body.preUpdate(); + } + + this.preUpdateChildren(); + + return true; + +}; + +Phaser.Component.Core.prototype = { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + game: null, + + /** + * A user defined name given to this Game Object. + * This value isn't ever used internally by Phaser, it is meant as a game level property. + * @property {string} name + * @default + */ + name: '', + + /** + * An empty Object that belongs to this Game Object. + * This value isn't ever used internally by Phaser, but may be used by your own code, or + * by Phaser Plugins, to store data that needs to be associated with the Game Object, + * without polluting the Game Object directly. + * @property {Object} data + * @default + */ + data: {}, + + /** + * The components this Game Object has installed. + * @property {object} components + * @protected + */ + components: {}, + + /** + * The z depth of this Game Object within its parent Group. + * No two objects in a Group can have the same z value. + * This value is adjusted automatically whenever the Group hierarchy changes. + * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. + * @property {number} z + * @readOnly + */ + z: 0, + + /** + * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this + * Game Object, or any of its components. + * @see Phaser.Events + * @property {Phaser.Events} events + */ + events: undefined, + + /** + * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. + * Through it you can create, play, pause and stop animations. + * @see Phaser.AnimationManager + * @property {Phaser.AnimationManager} animations + */ + animations: undefined, + + /** + * The key of the image or texture used by this Game Object during rendering. + * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. + * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. + * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. + * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key + */ + key: '', + + /** + * The world coordinates of this Game Object in pixels. + * Depending on where in the display list this Game Object is placed this value can differ from `position`, + * which contains the x/y coordinates relative to the Game Objects parent. + * @property {Phaser.Point} world + */ + world: null, + + /** + * A debug flag designed for use with `Game.enableStep`. + * @property {boolean} debug + * @default + */ + debug: false, + + /** + * The position the Game Object was located in the previous frame. + * @property {Phaser.Point} previousPosition + * @readOnly + */ + previousPosition: null, + + /** + * The rotation the Game Object was in set to in the previous frame. Value is in radians. + * @property {number} previousRotation + * @readOnly + */ + previousRotation: 0, + + /** + * The render order ID is used internally by the renderer and Input Manager and should not be modified. + * This property is mostly used internally by the renderers, but is exposed for the use of plugins. + * @property {number} renderOrderID + * @readOnly + */ + renderOrderID: 0, + + /** + * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. + * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. + * @property {boolean} fresh + * @readOnly + */ + fresh: true, + + /** + * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. + * You can set it directly to allow you to flag an object to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy an object from within one of its own callbacks + * such as with Buttons or other Input events. + * + * @property {boolean} pendingDestroy + */ + pendingDestroy: false, + + /** + * @property {Phaser.Rectangle} _bounds - Internal cache var. + * @private + */ + _bounds: null, + + /** + * @property {boolean} _exists - Internal cache var. + * @private + */ + _exists: true, + + /** + * Controls if this Game Object is processed by the core game loop. + * If this Game Object has a physics body it also controls if its physics body is updated or not. + * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. + * It also toggles the `visible` property to false as well. + * + * Setting `exists` to true will add its physics body back in to the physics world, if it has one. + * It will also set the `visible` property to `true`. + * + * @property {boolean} exists + */ + exists: { + + get: function () { + + return this._exists; + + }, + + set: function (value) { + + if (value) + { + this._exists = true; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.addToWorld(); + } + + this.visible = true; + } + else + { + this._exists = false; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.removeFromWorld(); + } + + this.visible = false; + } + + } + + }, + + /** + * Internal method called by preUpdate. + * + * @method + * @protected + */ + preUpdateChildren: function() { + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + }, + + /** + * Override this method in your own custom objects to handle any update requirements. + * It is called immediately after `preUpdate` and before `postUpdate`. + * Remember if this Game Object has any children you should call update on those too. + * + * @method + */ + update: function() { + + }, + + /** + * Internal method called by the World postUpdate cycle. + * + * @method + * @protected + */ + postUpdate: function() { + + if (this.customRender) + { + this.key.render(); + } + + if (this.components.PhysicsBody) + { + Phaser.Component.PhysicsBody.postUpdate.call(this); + } + + if (this.components.FixedToCamera) + { + Phaser.Component.FixedToCamera.postUpdate.call(this); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, +* which can be updated in real-time. +* +* @class +*/ +Phaser.Component.Crop = function () {}; + +Phaser.Component.Crop.prototype = { + + /** + * The Rectangle used to crop the texture this Game Object uses. + * Set this property via `crop`. + * If you modify this property directly you must call `updateCrop` in order to have the change take effect. + * @property {Phaser.Rectangle} cropRect + * @default + */ + cropRect: null, + + /** + * @property {Phaser.Rectangle} _crop - Internal cache var. + * @private + */ + _crop: null, + + /** + * Crop allows you to crop the texture being used to display this Game Object. + * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. + * + * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, + * or by modifying `cropRect` property directly and then calling `updateCrop`. + * + * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object + * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. + * + * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, + * in which case the values are duplicated to a local object. + * + * @method + * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. + * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. + */ + crop: function (rect, copy) { + + if (copy === undefined) { copy = false; } + + if (rect) + { + if (copy && this.cropRect !== null) + { + this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height); + } + else if (copy && this.cropRect === null) + { + this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height); + } + else + { + this.cropRect = rect; + } + + this.updateCrop(); + } + else + { + this._crop = null; + this.cropRect = null; + + this.resetFrame(); + } + + }, + + /** + * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, + * or the rectangle it references, then you need to update the crop frame by calling this method. + * + * @method + */ + updateCrop: function () { + + if (!this.cropRect) + { + return; + } + + var oldX = this.texture.crop.x; + var oldY = this.texture.crop.y; + var oldW = this.texture.crop.width; + var oldH = this.texture.crop.height; + + this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop); + this._crop.x += this._frame.x; + this._crop.y += this._frame.y; + + var cx = Math.max(this._frame.x, this._crop.x); + var cy = Math.max(this._frame.y, this._crop.y); + var cw = Math.min(this._frame.right, this._crop.right) - cx; + var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy; + + this.texture.crop.x = cx; + this.texture.crop.y = cy; + this.texture.crop.width = cw; + this.texture.crop.height = ch; + + this.texture.frame.width = Math.min(cw, this.cropRect.width); + this.texture.frame.height = Math.min(ch, this.cropRect.height); + + this.texture.width = this.texture.frame.width; + this.texture.height = this.texture.frame.height; + + this.texture._updateUvs(); + + if (this.tint !== 0xffffff && (oldX !== cx || oldY !== cy || oldW !== cw || oldH !== ch)) + { + this.texture.requiresReTint = true; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Delta component provides access to delta values between the Game Objects current and previous position. +* +* @class +*/ +Phaser.Component.Delta = function () {}; + +Phaser.Component.Delta.prototype = { + + /** + * Returns the delta x value. The difference between world.x now and in the previous frame. + * + * The value will be positive if the Game Object has moved to the right or negative if to the left. + * + * @property {number} deltaX + * @readonly + */ + deltaX: { + + get: function() { + + return this.world.x - this.previousPosition.x; + + } + + }, + + /** + * Returns the delta y value. The difference between world.y now and in the previous frame. + * + * The value will be positive if the Game Object has moved down or negative if up. + * + * @property {number} deltaY + * @readonly + */ + deltaY: { + + get: function() { + + return this.world.y - this.previousPosition.y; + + } + + }, + + /** + * Returns the delta z value. The difference between rotation now and in the previous frame. + * + * @property {number} deltaZ - The delta value. + * @readonly + */ + deltaZ: { + + get: function() { + + return this.rotation - this.previousRotation; + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Destroy component is responsible for destroying a Game Object. +* +* @class +*/ +Phaser.Component.Destroy = function () {}; + +Phaser.Component.Destroy.prototype = { + + /** + * As a Game Object runs through its destroy method this flag is set to true, + * and can be checked in any sub-systems or plugins it is being destroyed from. + * @property {boolean} destroyPhase + * @readOnly + */ + destroyPhase: false, + + /** + * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present + * and nulls its reference to `game`, freeing it up for garbage collection. + * + * If this Game Object has the Events component it will also dispatch the `onDestroy` event. + * + * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've + * more than one Game Object sharing the same BaseTexture. + * + * @method + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? + * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. + */ + destroy: function (destroyChildren, destroyTexture) { + + if (this.game === null || this.destroyPhase) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (destroyTexture === undefined) { destroyTexture = false; } + + this.destroyPhase = true; + + if (this.events) + { + this.events.onDestroy$dispatch(this); + } + + if (this.parent) + { + if (this.parent instanceof Phaser.Group) + { + this.parent.remove(this); + } + else + { + this.parent.removeChild(this); + } + } + + if (this.input) + { + this.input.destroy(); + } + + if (this.animations) + { + this.animations.destroy(); + } + + if (this.body) + { + this.body.destroy(); + } + + if (this.events) + { + this.events.destroy(); + } + + this.game.tweens.removeFrom(this); + + var i = this.children.length; + + if (destroyChildren) + { + while (i--) + { + this.children[i].destroy(destroyChildren); + } + } + else + { + while (i--) + { + this.removeChild(this.children[i]); + } + } + + if (this._crop) + { + this._crop = null; + this.cropRect = null; + } + + if (this._frame) + { + this._frame = null; + } + + if (Phaser.Video && this.key instanceof Phaser.Video) + { + this.key.onChangeSource.remove(this.resizeFrame, this); + } + + if (Phaser.BitmapText && this._glyphs) + { + this._glyphs = []; + } + + this.alive = false; + this.exists = false; + this.visible = false; + + this.filters = null; + this.mask = null; + this.game = null; + + this.data = {}; + + // In case Pixi is still going to try and render it even though destroyed + this.renderable = false; + + if (this.transformCallback) + { + this.transformCallback = null; + this.transformCallbackContext = null; + } + + // Pixi level DisplayObject destroy + this.hitArea = null; + this.parent = null; + this.stage = null; + this.worldTransform = null; + this.filterArea = null; + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + // Texture? + if (destroyTexture) + { + this.texture.destroy(true); + } + + this.destroyPhase = false; + this.pendingDestroy = false; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Events component is a collection of events fired by the parent Game Object. +* +* Phaser uses what are known as 'Signals' for all event handling. All of the events in +* this class are signals you can subscribe to, much in the same way you'd "listen" for +* an event. +* +* For example to tell when a Sprite has been added to a new group, you can bind a function +* to the {@link #onAddedToGroup} signal: +* +* `sprite.events.onAddedToGroup.add(yourFunction, this);` +* +* Where `yourFunction` is the function you want called when this event occurs. +* +* For more details about how signals work please see the {@link Phaser.Signal} class. +* +* The Input-related events will only be dispatched if the Sprite has had {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true` +* and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. +* +* @class Phaser.Events +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. +*/ +Phaser.Events = function (sprite) { + + /** + * @property {Phaser.Sprite} parent - The Sprite that owns these events. + */ + this.parent = sprite; + + // The signals are automatically added by the corresponding proxy properties + +}; + +Phaser.Events.prototype = { + + /** + * Removes all events. + * + * @method Phaser.Events#destroy + */ + destroy: function () { + + this._parent = null; + + if (this._onDestroy) { this._onDestroy.dispose(); } + if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } + if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } + if (this._onKilled) { this._onKilled.dispose(); } + if (this._onRevived) { this._onRevived.dispose(); } + if (this._onEnterBounds) { this._onEnterBounds.dispose(); } + if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } + + if (this._onInputOver) { this._onInputOver.dispose(); } + if (this._onInputOut) { this._onInputOut.dispose(); } + if (this._onInputDown) { this._onInputDown.dispose(); } + if (this._onInputUp) { this._onInputUp.dispose(); } + if (this._onDragStart) { this._onDragStart.dispose(); } + if (this._onDragUpdate) { this._onDragUpdate.dispose(); } + if (this._onDragStop) { this._onDragStop.dispose(); } + + if (this._onAnimationStart) { this._onAnimationStart.dispose(); } + if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } + if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } + + }, + + // The following properties are sentinels that will be replaced with getters + + /** + * This signal is dispatched when this Game Object is added to a new {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was added to the Group. + * - {Phaser.Group} The Group it was added to. + * + * @property {Phaser.Signal} onAddedToGroup + */ + onAddedToGroup: null, + + /** + * This signal is dispatched when the Game Object is removed from a {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was removed from the Group. + * - {Phaser.Group} The Group it was removed from. + * + * @property {Phaser.Signal} onRemovedFromGroup + */ + onRemovedFromGroup: null, + + /** + * This signal is dispatched when the Game Object is destroyed. + * This happens when {@link Phaser.Sprite#destroy Sprite.destroy()} is called, or {@link Phaser.Group#destroy Group.destroy()} with `destroyChildren` set to true. + * It is sent one argument: + * + * - {any} The Game Object that was destroyed. + * + * @property {Phaser.Signal} onDestroy + */ + onDestroy: null, + + /** + * This signal is dispatched when the Game Object is killed. + * This happens when {@link Phaser.Sprite#kill Sprite.kill()} is called. + * Please understand the difference between {@link Phaser.Sprite#kill kill} and {@link Phaser.Sprite#destroy destroy} by looking at their respective methods. + * It is sent one argument: + * + * - {any} The Game Object that was killed. + * + * @property {Phaser.Signal} onKilled + */ + onKilled: null, + + /** + * This signal is dispatched when the Game Object is revived from a previously killed state. + * This happens when {@link Phaser.Sprite#revive Sprite.revive()} is called. + * It is sent one argument: + * + * - {any} The Game Object that was revived. + * + * @property {Phaser.Signal} onRevived + */ + onRevived: null, + + /** + * This signal is dispatched when the Game Object leaves the Phaser.World {@link Phaser.World#bounds bounds}. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that left the World bounds. + * + * @property {Phaser.Signal} onOutOfBounds + */ + onOutOfBounds: null, + + /** + * This signal is dispatched when the Game Object returns within the Phaser.World {@link Phaser.World#bounds bounds}, having previously been outside of them. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that entered the World bounds. + * + * @property {Phaser.Signal} onEnterBounds + */ + onEnterBounds: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an over event from a {@link Phaser.Pointer}. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOver + */ + onInputOver: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an out event from a {@link Phaser.Pointer}, which was previously over it. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOut + */ + onInputOut: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives a down event from a {@link Phaser.Pointer}. This effectively means the Pointer has been + * pressed down (but not yet released) on the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputDown + */ + onInputDown: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an up event from a {@link Phaser.Pointer}. This effectively means the Pointer had been + * pressed down, and was then released on the Game Object. + * It is sent three arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {boolean} isOver - Is the Pointer still over the Game Object? + * + * @property {Phaser.Signal} onInputUp + */ + onInputUp: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} starts to drag the Game Object, taking into consideration the various + * drag limitations that may be set. + * It is sent four arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The x coordinate that the drag started from. + * - {number} The y coordinate that the drag started from. + * + * @property {Phaser.Signal} onDragStart + */ + onDragStart: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} is actively dragging the Game Object. + * Be warned: This is a high volume Signal. Be careful what you bind to it. + * It is sent six arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The new x coordinate of the Game Object. + * - {number} The new y coordinate of the Game Object. + * - {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. + * - {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. + * + * @property {Phaser.Signal} onDragUpdate + */ + onDragUpdate: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} stops dragging the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onDragStop + */ + onDragStop: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been played. + * You can also listen to {@link Phaser.Animation#onStart} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was started. + * + * @property {Phaser.Signal} onAnimationStart + */ + onAnimationStart: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been stopped (via {@link Phaser.AnimationManager#stop animation.stop()} and the `dispatchComplete` argument has been set. + * You can also listen to {@link Phaser.Animation#onComplete} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was stopped. + * + * @property {Phaser.Signal} onAnimationComplete + */ + onAnimationComplete: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has looped playback. + * You can also listen to {@link Phaser.Animation#onLoop} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that looped. + * + * @property {Phaser.Signal} onAnimationLoop + */ + onAnimationLoop: null + +}; + +Phaser.Events.prototype.constructor = Phaser.Events; + +// Create an auto-create proxy getter and dispatch method for all events. +// The backing property is the same as the event name, prefixed with '_' +// and the dispatch method is the same as the event name postfixed with '$dispatch'. +for (var prop in Phaser.Events.prototype) +{ + if (!Phaser.Events.prototype.hasOwnProperty(prop) || + prop.indexOf('on') !== 0 || + Phaser.Events.prototype[prop] !== null) + { + continue; + } + + (function (prop, backing) { + 'use strict'; + + // The accessor creates a new Signal; and so it should only be used from user-code. + Object.defineProperty(Phaser.Events.prototype, prop, { + get: function () { + return this[backing] || (this[backing] = new Phaser.Signal()); + } + }); + + // The dispatcher will only broadcast on an already-created signal; call this internally. + Phaser.Events.prototype[prop + '$dispatch'] = function () { + return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; + }; + + })(prop, '_' + prop); + +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless +* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. +* +* @class +*/ +Phaser.Component.FixedToCamera = function () {}; + +/** + * The FixedToCamera component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.FixedToCamera.postUpdate = function () { + + if (this.fixedToCamera) + { + 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.Component.FixedToCamera.prototype = { + + /** + * @property {boolean} _fixedToCamera + * @private + */ + _fixedToCamera: false, + + /** + * A Game Object that is "fixed" to the camera is rendered at a given x/y offsets from the top left of the camera. The offsets + * are stored in the `cameraOffset` property, which is initialized with the current object coordinates. + * + * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. + * + * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world + * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times + * regardless where in the world the camera is. + * + * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. + * + * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. + * + * @property {boolean} fixedToCamera + */ + fixedToCamera: { + + get: function () { + + return this._fixedToCamera; + + }, + + set: function (value) { + + if (value) + { + this._fixedToCamera = true; + this.cameraOffset.set(this.x, this.y); + } + else + { + this._fixedToCamera = false; + } + + } + + }, + + /** + * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. + * + * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. + * @property {Phaser.Point} cameraOffset + */ + cameraOffset: new Phaser.Point() + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Health component provides the ability for Game Objects to have a `health` property +* that can be damaged and reset through game code. +* Requires the LifeSpan component. +* +* @class +*/ +Phaser.Component.Health = function () {}; + +Phaser.Component.Health.prototype = { + + /** + * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. + * + * It can be used in combination with the `damage` method or modified directly. + * + * @property {number} health + * @default + */ + health: 1, + + /** + * The Game Objects maximum health value. This works in combination with the `heal` method to ensure + * the health value never exceeds the maximum. + * + * @property {number} maxHealth + * @default + */ + maxHealth: 100, + + /** + * Damages the Game Object. This removes the given amount of health from the `health` property. + * + * If health is taken below or is equal to zero then the `kill` method is called. + * + * @method + * @param {number} amount - The amount to subtract from the current `health` value. + * @return {Phaser.Sprite} This instance. + */ + damage: function (amount) { + + if (this.alive) + { + this.health -= amount; + + if (this.health <= 0) + { + this.kill(); + } + } + + return this; + + }, + + /** + * Sets the health property of the Game Object to the given amount. + * Will never exceed the `maxHealth` value. + * + * @method + * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + setHealth: function (amount) { + + this.health = amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + + return this; + + }, + + /** + * Heal the Game Object. This adds the given amount of health to the `health` property. + * + * @method + * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + heal: function (amount) { + + if (this.alive) + { + this.health += amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InCamera component checks if the Game Object intersects with the Game Camera. +* +* @class +*/ +Phaser.Component.InCamera = function () {}; + +Phaser.Component.InCamera.prototype = { + + /** + * Checks if this Game Objects bounds intersects with the Game Cameras bounds. + * + * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. + * + * An object outside the bounds can be considered for camera culling if it has the AutoCull component. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. +* +* @class +*/ +Phaser.Component.InputEnabled = function () {}; + +Phaser.Component.InputEnabled.prototype = { + + /** + * The Input Handler for this Game Object. + * + * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. + * + * After you have done this, this property will be a reference to the Phaser InputHandler. + * @property {Phaser.InputHandler|null} input + */ + input: null, + + /** + * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created + * for this Game Object and it will then start to process click / touch events and more. + * + * You can then access the Input Handler via `this.input`. + * + * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. + * + * If you set this property to false it will stop the Input Handler from processing any more input events. + * + * If you want to _temporarily_ disable input for a Game Object, then it's better to set + * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. + * You can then toggle this back on as needed. + * + * @property {boolean} inputEnabled + */ + inputEnabled: { + + get: function () { + + return (this.input && this.input.enabled); + + }, + + set: function (value) { + + if (value) + { + if (this.input === null) + { + this.input = new Phaser.InputHandler(this); + this.input.start(); + } + else if (this.input && !this.input.enabled) + { + this.input.start(); + } + } + else + { + if (this.input && this.input.enabled) + { + this.input.stop(); + } + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InWorld component checks if a Game Object is within the Game World Bounds. +* An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. +* If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. +* +* @class +*/ +Phaser.Component.InWorld = function () {}; + +/** + * The InWorld component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.InWorld.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + // Cache the bounds if we need it + if (this.autoCull || this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + + if (this.autoCull) + { + // Won't get rendered but will still get its transform updated + if (this.game.world.camera.view.intersects(this._bounds)) + { + this.renderable = true; + this.game.world.camera.totalInView++; + } + else + { + this.renderable = false; + + if (this.outOfCameraBoundsKill) + { + this.kill(); + return false; + } + } + } + + if (this.checkWorldBounds) + { + // The Sprite is already out of the world bounds, so let's check to see if it has come back again + if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds)) + { + this._outOfBoundsFired = false; + this.events.onEnterBounds$dispatch(this); + } + else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds)) + { + // The Sprite WAS in the screen, but has now left. + this._outOfBoundsFired = true; + this.events.onOutOfBounds$dispatch(this); + + if (this.outOfBoundsKill) + { + this.kill(); + return false; + } + } + } + } + + return true; + +}; + +Phaser.Component.InWorld.prototype = { + + /** + * If this is set to `true` the Game Object checks if it is within the World bounds each frame. + * + * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. + * + * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. + * + * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. + * + * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} checkWorldBounds + * @default + */ + checkWorldBounds: false, + + /** + * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. + * + * @property {boolean} outOfBoundsKill + * @default + */ + outOfBoundsKill: false, + + /** + * If this and the `autoCull` property are both set to `true`, then the `kill` method + * is called as soon as the Game Object leaves the camera bounds. + * + * @property {boolean} outOfCameraBoundsKill + * @default + */ + outOfCameraBoundsKill: false, + + /** + * @property {boolean} _outOfBoundsFired - Internal state var. + * @private + */ + _outOfBoundsFired: false, + + /** + * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. + * + * @property {boolean} inWorld + * @readonly + */ + inWorld: { + + get: function () { + + return this.game.world.bounds.intersects(this.getBounds()); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* LifeSpan Component Features. +* +* @class +*/ +Phaser.Component.LifeSpan = function () {}; + +/** + * The LifeSpan component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.LifeSpan.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.lifespan > 0) + { + this.lifespan -= this.game.time.physicsElapsedMS; + + if (this.lifespan <= 0) + { + this.kill(); + return false; + } + } + + return true; + +}; + +Phaser.Component.LifeSpan.prototype = { + + /** + * A useful flag to control if the Game Object is alive or dead. + * + * This is set automatically by the Health components `damage` method should the object run out of health. + * Or you can toggle it via your game code. + * + * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. + * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. + * @property {boolean} alive + * @default + */ + alive: true, + + /** + * The lifespan allows you to give a Game Object a lifespan in milliseconds. + * + * Once the Game Object is 'born' you can set this to a positive value. + * + * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. + * When it reaches zero it will call the `kill` method. + * + * Very handy for particles, bullets, collectibles, or any other short-lived entity. + * + * @property {number} lifespan + * @default + */ + lifespan: 0, + + /** + * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. + * + * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. + * + * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. + * + * @method + * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. + * @return {PIXI.DisplayObject} This instance. + */ + revive: function (health) { + + if (health === undefined) { health = 100; } + + this.alive = true; + this.exists = true; + this.visible = true; + + if (typeof this.setHealth === 'function') + { + this.setHealth(health); + } + + if (this.events) + { + this.events.onRevived$dispatch(this); + } + + return this; + + }, + + /** + * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. + * + * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. + * + * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, + * it doesn't destroy the object or free it up from memory. + * + * If you don't need this Game Object any more you should call `destroy` instead. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ + kill: function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + if (this.events) + { + this.events.onKilled$dispatch(this); + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. +* +* @class +*/ +Phaser.Component.LoadTexture = function () {}; + +Phaser.Component.LoadTexture.prototype = { + + /** + * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) + * @private + */ + customRender: false, + + /** + * @property {Phaser.Rectangle} _frame - Internal cache var. + * @private + */ + _frame: null, + + /** + * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. + * + * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. + * + * You should only use `loadTexture` if you want to replace the base texture entirely. + * + * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. + * + * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. + * Doing this then sets the key to be the `frame` argument (the frame is set to zero). + * + * This allows you to create sprites using `load.image` during development, and then change them + * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' + * and swapping it to be the key of the atlas data. + * + * Note: You cannot use a RenderTexture as a texture for a TileSprite. + * + * @method + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. + */ + loadTexture: function (key, frame, stopAnimation) { + + if (key === Phaser.PENDING_ATLAS) + { + key = frame; + frame = 0; + } + else + { + frame = frame || 0; + } + + if ((stopAnimation || stopAnimation === undefined) && this.animations) + { + this.animations.stop(); + } + + this.key = key; + this.customRender = false; + var cache = this.game.cache; + + var setFrame = true; + var smoothed = !this.texture.baseTexture.scaleMode; + + if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture) + { + this.key = key.key; + this.setTexture(key); + } + else if (Phaser.BitmapData && key instanceof Phaser.BitmapData) + { + this.customRender = true; + + this.setTexture(key.texture); + + if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA)) + { + setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame); + } + else + { + setFrame = !this.animations.loadFrameData(key.frameData, 0); + } + } + else if (Phaser.Video && key instanceof Phaser.Video) + { + this.customRender = true; + + // This works from a reference, which probably isn't what we need here + var valid = key.texture.valid; + this.setTexture(key.texture); + this.setFrame(key.texture.frame.clone()); + key.onChangeSource.add(this.resizeFrame, this); + this.texture.valid = valid; + } + else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer) + { + // this.customRender = true; + + this.setTexture(PIXI.Texture.fromCanvas(key.canvas)); + } + else if (key instanceof PIXI.Texture) + { + this.setTexture(key); + } + else + { + var img = cache.getImage(key, true); + + this.key = img.key; + this.setTexture(new PIXI.Texture(img.base)); + + if (key === '__default') + { + this.texture.baseTexture.skipRender = true; + } + else + { + this.texture.baseTexture.skipRender = false; + } + + setFrame = !this.animations.loadFrameData(img.frameData, frame); + } + + if (setFrame) + { + this._frame = Phaser.Rectangle.clone(this.texture.frame); + } + + if (!smoothed) + { + this.texture.baseTexture.scaleMode = 1; + } + + }, + + /** + * Sets the texture frame the Game Object uses for rendering. + * + * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. + * + * @method + * @param {Phaser.Frame} frame - The Frame to be used by the texture. + */ + setFrame: function (frame) { + + this._frame = frame; + + this.texture.frame.x = frame.x; + this.texture.frame.y = frame.y; + this.texture.frame.width = frame.width; + this.texture.frame.height = frame.height; + + this.texture.crop.x = frame.x; + this.texture.crop.y = frame.y; + this.texture.crop.width = frame.width; + this.texture.crop.height = frame.height; + + if (frame.trimmed) + { + if (this.texture.trim) + { + this.texture.trim.x = frame.spriteSourceSizeX; + this.texture.trim.y = frame.spriteSourceSizeY; + this.texture.trim.width = frame.sourceSizeW; + this.texture.trim.height = frame.sourceSizeH; + } + else + { + this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH }; + } + + this.texture.width = frame.sourceSizeW; + this.texture.height = frame.sourceSizeH; + this.texture.frame.width = frame.sourceSizeW; + this.texture.frame.height = frame.sourceSizeH; + } + else if (!frame.trimmed && this.texture.trim) + { + this.texture.trim = null; + } + + if (frame.rotated) + { + this.texture.rotated = true; + } + + if (this.cropRect) + { + this.updateCrop(); + } + + this.texture.requiresReTint = true; + + this.texture._updateUvs(); + + if (this.tilingTexture) + { + this.refreshTexture = true; + } + + }, + + /** + * Resizes the Frame dimensions that the Game Object uses for rendering. + * + * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData + * it can be useful to adjust the dimensions directly in this way. + * + * @method + * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. + * @param {integer} width - The new width of the texture. + * @param {integer} height - The new height of the texture. + */ + resizeFrame: function (parent, width, height) { + + this.texture.frame.resize(width, height); + this.texture.setFrame(this.texture.frame); + + }, + + /** + * Resets the texture frame dimensions that the Game Object uses for rendering. + * + * @method + */ + resetFrame: function () { + + if (this._frame) + { + this.setFrame(this._frame); + } + + }, + + /** + * Gets or sets the current frame index of the texture being used to render this Game Object. + * + * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, + * for example: `player.frame = 4`. + * + * If the frame index given doesn't exist it will revert to the first frame found in the texture. + * + * If you are using a texture atlas then you should use the `frameName` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {integer} frame + */ + frame: { + + get: function () { + return this.animations.frame; + }, + + set: function (value) { + this.animations.frame = value; + } + + }, + + /** + * Gets or sets the current frame name of the texture being used to render this Game Object. + * + * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, + * for example: `player.frameName = "idle"`. + * + * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. + * + * If you are using a sprite sheet then you should use the `frame` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {string} frameName + */ + frameName: { + + get: function () { + return this.animations.frameName; + }, + + set: function (value) { + this.animations.frameName = value; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. +* +* @class +*/ +Phaser.Component.Overlap = function () {}; + +Phaser.Component.Overlap.prototype = { + + /** + * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, + * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. + * + * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. + * + * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. + * It should be fine for low-volume testing where physics isn't required. + * + * @method + * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. + * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. + */ + overlap: function (displayObject) { + + return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds()); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The PhysicsBody component manages the Game Objects physics body and physics enabling. +* It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. +* +* @class +*/ +Phaser.Component.PhysicsBody = function () {}; + +/** + * The PhysicsBody component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.fresh && 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.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (this.body) + { + this.body.preUpdate(); + } + + this.fresh = false; + + this.preUpdateChildren(); + + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this._exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + return true; + +}; + +/** + * The PhysicsBody component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.postUpdate = function () { + + if (this.exists && this.body) + { + this.body.postUpdate(); + } + +}; + +Phaser.Component.PhysicsBody.prototype = { + + /** + * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated + * properties and methods via it. + * + * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. + * + * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object + * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. + * + * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. + * + * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, + * so the physics body is centered on the Game Object. + * + * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. + * + * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body + * @default + */ + body: null, + + /** + * The position of the Game Object on the x axis relative to the local coordinates of the parent. + * + * @property {number} x + */ + x: { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + }, + + /** + * The position of the Game Object on the y axis relative to the local coordinates of the parent. + * + * @property {number} y + */ + y: { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Reset component allows a Game Object to be reset and repositioned to a new location. +* +* @class +*/ +Phaser.Component.Reset = function () {}; + +/** +* Resets the Game Object. +* +* This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, +* `visible` and `renderable` to true. +* +* If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. +* +* If this Game Object has a Physics Body it will reset the Body. +* +* @method +* @param {number} x - The x coordinate (in world space) to position the Game Object at. +* @param {number} y - The y coordinate (in world space) to position the Game Object at. +* @param {number} [health=1] - The health to give the Game Object if it has the Health component. +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.Reset.prototype.reset = function (x, y, health) { + + if (health === undefined) { health = 1; } + + this.world.set(x, y); + this.position.set(x, y); + + this.fresh = true; + this.exists = true; + this.visible = true; + this.renderable = true; + + if (this.components.InWorld) + { + this._outOfBoundsFired = false; + } + + if (this.components.LifeSpan) + { + this.alive = true; + this.health = health; + } + + if (this.components.PhysicsBody) + { + if (this.body) + { + this.body.reset(x, y, false, false); + } + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. +* +* @class +*/ +Phaser.Component.ScaleMinMax = function () {}; + +Phaser.Component.ScaleMinMax.prototype = { + + /** + * The callback that will apply any scale limiting to the worldTransform. + * @property {function} transformCallback + */ + transformCallback: null, + + /** + * The context under which `transformCallback` is called. + * @property {object} transformCallbackContext + */ + transformCallbackContext: this, + + /** + * The minimum scale this Game Object will scale down to. + * + * It allows you to prevent a parent from scaling this Game Object lower than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMin + */ + scaleMin: null, + + /** + * The maximum scale this Game Object will scale up to. + * + * It allows you to prevent a parent from scaling this Game Object higher than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMax + */ + scaleMax: null, + + /** + * Adjust scaling limits, if set, to this Game Object. + * + * @method + * @private + * @param {Phaser.Matrix} wt - The updated worldTransform matrix. + */ + checkTransform: function (wt) { + + if (this.scaleMin) + { + if (wt.a < this.scaleMin.x) + { + wt.a = this.scaleMin.x; + } + + if (wt.d < this.scaleMin.y) + { + wt.d = this.scaleMin.y; + } + } + + if (this.scaleMax) + { + if (wt.a > this.scaleMax.x) + { + wt.a = this.scaleMax.x; + } + + if (wt.d > this.scaleMax.y) + { + wt.d = this.scaleMax.y; + } + } + + }, + + /** + * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. + * + * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored + * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. + * + * By setting these values you can carefully control how Game Objects deal with responsive scaling. + * + * If only one parameter is given then that value will be used for both scaleMin and scaleMax: + * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 + * + * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: + * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 + * + * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, + * or pass `null` for the `maxX` and `maxY` parameters. + * + * Call `setScaleMinMax(null)` to clear all previously set values. + * + * @method + * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to. + * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to. + * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to. + * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to. + */ + setScaleMinMax: function (minX, minY, maxX, maxY) { + + if (minY === undefined) + { + // 1 parameter, set all to it + minY = maxX = maxY = minX; + } + else if (maxX === undefined) + { + // 2 parameters, the first is min, the second max + maxX = maxY = minY; + minY = minX; + } + + if (minX === null) + { + this.scaleMin = null; + } + else + { + if (this.scaleMin) + { + this.scaleMin.set(minX, minY); + } + else + { + this.scaleMin = new Phaser.Point(minX, minY); + } + } + + if (maxX === null) + { + this.scaleMax = null; + } + else + { + if (this.scaleMax) + { + this.scaleMax.set(maxX, maxY); + } + else + { + this.scaleMax = new Phaser.Point(maxX, maxY); + } + } + + if (this.scaleMin === null) + { + this.transformCallback = null; + } + else + { + this.transformCallback = this.checkTransform; + this.transformCallbackContext = this; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. +* +* @class +*/ +Phaser.Component.Smoothed = function () {}; + +Phaser.Component.Smoothed.prototype = { + + /** + * Enable or disable texture smoothing for this Game Object. + * + * It only takes effect if the Game Object is using an image based texture. + * + * Smoothing is enabled by default. + * + * @property {boolean} smoothed + */ + smoothed: { + + get: function () { + + return !this.texture.baseTexture.scaleMode; + + }, + + set: function (value) { + + if (value) + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 0; + this.texture.baseTexture.dirty(); + } + } + else + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 1; + this.texture.baseTexture.dirty(); + } + } + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectFactory is a quick way to create many common game objects +* using {@linkcode Phaser.Game#add `game.add`}. +* +* Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group. +* +* @class Phaser.GameObjectFactory +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectFactory = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectFactory.prototype = { + + /** + * Adds an existing display object to the game world. + * + * @method Phaser.GameObjectFactory#existing + * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object. + * @return {any} The child that was added to the World. + */ + existing: function (object) { + + return this.world.add(object); + + }, + + /** + * Weapons provide the ability to easily create a bullet pool and manager. + * + * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. + * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. + * + * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you + * can usually do with a Group, such as move it around the display list, iterate it, etc can be done + * to the bullets Group too. + * + * Bullets can have textures and even animations. You can control the speed at which they are fired, + * the firing rate, the firing angle, and even set things like gravity for them. + * + * @method Phaser.GameObjectFactory#weapon + * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group. + * @param {function} [bulletClass] - The Class of the bullets that are launched by this Weapon. See {@link Phaser.Weapon#bulletClass} + * @returns {Phaser.Weapon} A Weapon instance. + */ + weapon: function (quantity, key, frame, group, bulletClass) { + + var weapon = this.game.plugins.add(Phaser.Weapon); + + if (bulletClass) + { + weapon.bulletClass = bulletClass; + } + + weapon.createBullets(quantity, key, frame, group); + + return weapon; + + }, + + /** + * Create a new `Image` object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * + * It can still rotate, scale, crop and receive input events. + * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectFactory#image + * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Image} The newly created Image object. + */ + image: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Image(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. + * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), + * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. + * + * @method Phaser.GameObjectFactory#sprite + * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Sprite} The newly created Sprite object. + */ + sprite: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Sprite(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Creature Animation object. + * + * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. + * + * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). + * + * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. + * + * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them + * loaded before your Phaser game boots. + * + * See the Phaser custom build process for more details. + * + * @method Phaser.GameObjectFactory#creature + * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Creature} The newly created Creature object. + */ + creature: function (x, y, key, mesh, group) { + + if (group === undefined) { group = this.world; } + + var obj = new Phaser.Creature(this.game, x, y, key, mesh); + + group.add(obj); + + return obj; + + }, + + /** + * Create a tween on a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectFactory#tween + * @param {object} object - Object the tween will be run on. + * @return {Phaser.Tween} The newly created Phaser.Tween object. + */ + tween: function (object) { + + return this.game.tweens.create(object); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectFactory#group + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates + * are automatically given a physics body. + * + * @method Phaser.GameObjectFactory#physicsGroup + * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc. + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.Group} The newly created Group. + */ + physicsGroup: function (physicsBodyType, parent, name, addToStage) { + + return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType); + + }, + + /** + * A SpriteBatch is a really fast version of a Phaser Group built solely for speed. + * Use when you need a lot of sprites or particles all sharing the same texture. + * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. + * + * @method Phaser.GameObjectFactory#spriteBatch + * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. + * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. + * @return {Phaser.SpriteBatch} The newly created Sprite Batch. + */ + spriteBatch: function (parent, name, addToStage) { + + if (parent === undefined) { parent = null; } + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectFactory#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectFactory#tileSprite + * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TileSprite} The newly created TileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); + + }, + + /** + * Creates a new Rope object. + * + * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js + * + * @method Phaser.GameObjectFactory#rope + * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Array} points - An array of {Phaser.Point}. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Rope} The newly created Rope object. + */ + rope: function (x, y, key, frame, points, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Rope(this.game, x, y, key, frame, points)); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectFactory#text + * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {string} [text=''] - The text string that will be displayed. + * @param {object} [style] - The style object containing style attributes like font, font size , etc. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Text(this.game, x, y, text, style)); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectFactory#button + * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] - The function to call when this button is pressed + * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Button} The newly created Button object. + */ + button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectFactory#graphics + * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Graphics(this.game, x, y)); + + }, + + /** + * Create a new Emitter. + * + * A particle emitter can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accordingly. + * + * @method Phaser.GameObjectFactory#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles)); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectFactory#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectFactory#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size)); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectFactory#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {Phaser.Tilemap} The newly created tilemap object. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectFactory#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a Video object. + * + * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. + * + * @method Phaser.GameObjectFactory#video + * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. + * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) + * @return {Phaser.Video} The newly created Video object. + */ + video: function (key, url) { + + return new Phaser.Video(this.game, key, url); + + }, + + /** + * Create a BitmapData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectFactory#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectFactory#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + }, + + /** + * Add a new Plugin into the PluginManager. + * + * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.GameObjectFactory#plugin + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + plugin: function (plugin) { + + return this.game.plugins.add(plugin); + + } + +}; + +Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world. +* The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}. +* +* @class Phaser.GameObjectCreator +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectCreator = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectCreator.prototype = { + + /** + * Create a new Image object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectCreator#image + * @param {number} x - X position of the image. + * @param {number} y - Y position of the image. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Image} the newly created sprite object. + */ + image: function (x, y, key, frame) { + + return new Phaser.Image(this.game, x, y, key, frame); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * @method Phaser.GameObjectCreator#sprite + * @param {number} x - X position of the new sprite. + * @param {number} y - Y position of the new sprite. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Sprite} the newly created sprite object. + */ + sprite: function (x, y, key, frame) { + + return new Phaser.Sprite(this.game, x, y, key, frame); + + }, + + /** + * Create a tween object for a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectCreator#tween + * @param {object} obj - Object the tween will be run on. + * @return {Phaser.Tween} The Tween object. + */ + tween: function (obj) { + + return new Phaser.Tween(obj, this.game, this.game.tweens); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectCreator#group + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * Create a new SpriteBatch. + * + * @method Phaser.GameObjectCreator#spriteBatch + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.SpriteBatch} The newly created group. + */ + spriteBatch: function (parent, name, addToStage) { + + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectCreator#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectCreator#tileSprite + * @param {number} x - The x coordinate (in world space) to position the TileSprite at. + * @param {number} y - The y coordinate (in world space) to position the TileSprite at. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.TileSprite} The newly created tileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame) { + + return new Phaser.TileSprite(this.game, x, y, width, height, key, frame); + + }, + + /** + * Creates a new Rope object. + * + * @method Phaser.GameObjectCreator#rope + * @param {number} x - The x coordinate (in world space) to position the Rope at. + * @param {number} y - The y coordinate (in world space) to position the Rope at. + * @param {number} width - The width of the Rope. + * @param {number} height - The height of the Rope. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.Rope} The newly created rope object. + */ + rope: function (x, y, key, frame, points) { + + return new Phaser.Rope(this.game, x, y, key, frame, points); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectCreator#text + * @param {number} x - X position of the new text object. + * @param {number} y - Y position of the new text object. + * @param {string} text - The actual text that will be written. + * @param {object} style - The style object containing style attributes like font, font size , etc. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style) { + + return new Phaser.Text(this.game, x, y, text, style); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectCreator#button + * @param {number} [x] X position of the new button object. + * @param {number} [y] Y position of the new button object. + * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] The function to call when this button is pressed + * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @return {Phaser.Button} The newly created button object. + */ + 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); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectCreator#graphics + * @param {number} [x=0] - X position of the new graphics object. + * @param {number} [y=0] - Y position of the new graphics object. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y) { + + return new Phaser.Graphics(this.game, x, y); + + }, + + /** + * Creat a new Emitter. + * + * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accorindgly. + * + * @method Phaser.GameObjectCreator#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectCreator#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectCreator#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, align) { + + return new Phaser.BitmapText(this.game, x, y, font, text, size, align); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectCreator#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectCreator#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a BitmpaData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectCreator#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectCreator#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + } + +}; + +Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Sprites are the lifeblood of your game, used for nearly everything visual. +* +* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. +* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), +* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. +* +* @class Phaser.Sprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. If this argument is omitted, the sprite will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Sprite = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.SPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Sprite.prototype.constructor = Phaser.Sprite; + +Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.Sprite +* @return {boolean} True if the Sprite was rendered, otherwise false. +*/ +Phaser.Sprite.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image is a light-weight object you can use to display anything that doesn't need health, physics, or complex position monitoring. +* +* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. +* +* @class Phaser.Image +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. If this argument is omitted, the image will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Image = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.IMAGE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Image.prototype.constructor = Phaser.Image; + +Phaser.Component.Core.install.call(Phaser.Image.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Image.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Image#preUpdate +* @memberof Phaser.Image +*/ +Phaser.Image.prototype.preUpdate = function() { + + if (!this.preUpdateInWorld() || !this.preUpdateLifeSpan()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. +* +* The four states a Button responds to are: +* +* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. +* * 'Out' - when the Pointer that was previously over the Button moves out of it. +* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. +* * 'Up' - when the Pointer that was pressed down on the Button is released again. +* +* A different texture/frame and activation sound can be specified for any of the states. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. +* +* @class Phaser.Button +* @constructor +* @extends Phaser.Image +* @param {Phaser.Game} game Current game instance. +* @param {number} [x=0] - X position of the Button. +* @param {number} [y=0] - Y position of the Button. +* @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button. +* @param {function} [callback] - The function to call when this Button is pressed, receiving `this` (the Button), `pointer`, and `isOver` (see {@link Phaser.Events#onInputUp}.) +* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) { + + x = x || 0; + y = y || 0; + key = key || null; + callback = callback || null; + callbackContext = callbackContext || this; + + Phaser.Image.call(this, game, x, y, key, outFrame); + + /** + * The Phaser Object Type. + * @property {number} type + * @readonly + */ + this.type = Phaser.BUTTON; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * The name or ID of the Over state frame. + * @property {string|integer} onOverFrame + * @private + */ + this._onOverFrame = null; + + /** + * The name or ID of the Out state frame. + * @property {string|integer} onOutFrame + * @private + */ + this._onOutFrame = null; + + /** + * The name or ID of the Down state frame. + * @property {string|integer} onDownFrame + * @private + */ + this._onDownFrame = null; + + /** + * The name or ID of the Up state frame. + * @property {string|integer} onUpFrame + * @private + */ + this._onUpFrame = null; + + /** + * The Sound to be played when this Buttons Over state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound + * @readonly + */ + this.onOverSound = null; + + /** + * The Sound to be played when this Buttons Out state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound + * @readonly + */ + this.onOutSound = null; + + /** + * The Sound to be played when this Buttons Down state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound + * @readonly + */ + this.onDownSound = null; + + /** + * The Sound to be played when this Buttons Up state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound + * @readonly + */ + this.onUpSound = null; + + /** + * The Sound Marker used in conjunction with the onOverSound. + * @property {string} onOverSoundMarker + * @readonly + */ + this.onOverSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onOutSound. + * @property {string} onOutSoundMarker + * @readonly + */ + this.onOutSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onDownSound. + * @property {string} onDownSoundMarker + * @readonly + */ + this.onDownSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onUpSound. + * @property {string} onUpSoundMarker + * @readonly + */ + this.onUpSoundMarker = ''; + + /** + * The Signal (or event) dispatched when this Button is in an Over state. + * @property {Phaser.Signal} onInputOver + */ + this.onInputOver = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Out state. + * @property {Phaser.Signal} onInputOut + */ + this.onInputOut = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Down state. + * @property {Phaser.Signal} onInputDown + */ + this.onInputDown = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Up state. + * @property {Phaser.Signal} onInputUp + */ + this.onInputUp = new Phaser.Signal(); + + /** + * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. + * The frame will still be changed as applicable. + * + * @property {boolean} onOverMouseOnly + * @default + */ + this.onOverMouseOnly = true; + + /** + * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}. + * + * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. + * + * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR + */ + this.justReleasedPreventsOver = Phaser.PointerMode.CONTACT; + + /** + * When true the the texture frame will not be automatically switched on up/down/over/out events. + * @property {boolean} freezeFrames + * @default + */ + this.freezeFrames = false; + + /** + * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". + * + * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control. + * + * @property {boolean|Phaser.PointerMode} forceOut=false + * @default + */ + this.forceOut = false; + + this.inputEnabled = true; + + this.input.start(0, true); + + this.input.useHandCursor = true; + + this.setFrames(overFrame, outFrame, downFrame, upFrame); + + if (callback !== null) + { + this.onInputUp.add(callback, callbackContext); + } + + // Redirect the input events to here so we can handle animation updates, etc + this.events.onInputOver.add(this.onInputOverHandler, this); + this.events.onInputOut.add(this.onInputOutHandler, this); + this.events.onInputDown.add(this.onInputDownHandler, this); + this.events.onInputUp.add(this.onInputUpHandler, this); + +}; + +Phaser.Button.prototype = Object.create(Phaser.Image.prototype); +Phaser.Button.prototype.constructor = Phaser.Button; + +// State constants; local only. These are tied to property names in Phaser.Button. +var STATE_OVER = 'Over'; +var STATE_OUT = 'Out'; +var STATE_DOWN = 'Down'; +var STATE_UP = 'Up'; + +/** +* Clears all of the frames set on this Button. +* +* @method Phaser.Button#clearFrames +*/ +Phaser.Button.prototype.clearFrames = function () { + + this.setFrames(null, null, null, null); + +}; + +/** +* Set the frame name/ID for the given state. +* +* @method Phaser.Button#setStateFrame +* @private +* @param {object} state - See `STATE_*` +* @param {number|string} frame - The number or string representing the frame. +* @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true. +*/ +Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately) +{ + var frameKey = '_on' + state + 'Frame'; + + if (frame !== null) // not null or undefined + { + this[frameKey] = frame; + + if (switchImmediately) + { + this.changeStateFrame(state); + } + } + else + { + this[frameKey] = null; + } + +}; + +/** +* Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen". +* +* @method Phaser.Button#changeStateFrame +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if the frame was assigned a value, possibly the same one it already had. +*/ +Phaser.Button.prototype.changeStateFrame = function (state) { + + if (this.freezeFrames) + { + return false; + } + + var frameKey = '_on' + state + 'Frame'; + var frame = this[frameKey]; + + if (typeof frame === 'string') + { + this.frameName = frame; + return true; + } + else if (typeof frame === 'number') + { + this.frame = frame; + return true; + } + else + { + return false; + } + +}; + +/** +* Used to manually set the frames that will be used for the different states of the Button. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. +* +* @method Phaser.Button#setFrames +* @public +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) { + + this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver()); + this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver()); + this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown()); + this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp()); + +}; + +/** +* Set the sound/marker for the given state. +* +* @method Phaser.Button#setStateSound +* @private +* @param {object} state - See `STATE_*` +* @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound. +* @param {string} [marker=''] - Sound marker. +*/ +Phaser.Button.prototype.setStateSound = function (state, sound, marker) { + + var soundKey = 'on' + state + 'Sound'; + var markerKey = 'on' + state + 'SoundMarker'; + + if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite) + { + this[soundKey] = sound; + this[markerKey] = typeof marker === 'string' ? marker : ''; + } + else + { + this[soundKey] = null; + this[markerKey] = ''; + } + +}; + +/** +* Play the sound for the given state, _if_ the state has a sound assigned. +* +* @method Phaser.Button#playStateSound +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if a sound was played. +*/ +Phaser.Button.prototype.playStateSound = function (state) { + + var soundKey = 'on' + state + 'Sound'; + var sound = this[soundKey]; + + if (sound) + { + var markerKey = 'on' + state + 'SoundMarker'; + var marker = this[markerKey]; + + sound.play(marker); + return true; + } + else + { + return false; + } + +}; + +/** +* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. +* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. +* +* Call this function with no parameters to reset all sounds on this Button. +* +* @method Phaser.Button#setSounds +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound. +* @param {string} [overMarker] - Over Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound. +* @param {string} [downMarker] - Down Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound. +* @param {string} [outMarker] - Out Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound. +* @param {string} [upMarker] - Up Button Sound Marker. +*/ +Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) { + + this.setStateSound(STATE_OVER, overSound, overMarker); + this.setStateSound(STATE_OUT, outSound, outMarker); + this.setStateSound(STATE_DOWN, downSound, downMarker); + this.setStateSound(STATE_UP, upSound, upMarker); + +}; + +/** +* The Sound to be played when a Pointer moves over this Button. +* +* @method Phaser.Button#setOverSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOverSound = function (sound, marker) { + + this.setStateSound(STATE_OVER, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer moves out of this Button. +* +* @method Phaser.Button#setOutSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOutSound = function (sound, marker) { + + this.setStateSound(STATE_OUT, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer presses down on this Button. +* +* @method Phaser.Button#setDownSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setDownSound = function (sound, marker) { + + this.setStateSound(STATE_DOWN, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer has pressed down and is released from this Button. +* +* @method Phaser.Button#setUpSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setUpSound = function (sound, marker) { + + this.setStateSound(STATE_UP, sound, marker); + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOverHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) { + + if (pointer.justReleased() && + (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode) + { + // If the Pointer was only just released then we don't fire an over event + return; + } + + this.changeStateFrame(STATE_OVER); + + if (this.onOverMouseOnly && !pointer.isMouse) + { + return; + } + + this.playStateSound(STATE_OVER); + + if (this.onInputOver) + { + this.onInputOver.dispatch(this, pointer); + } + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOutHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_OUT); + + this.playStateSound(STATE_OUT); + + if (this.onInputOut) + { + this.onInputOut.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputDownHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_DOWN); + + this.playStateSound(STATE_DOWN); + + if (this.onInputDown) + { + this.onInputDown.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputUpHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) { + + this.playStateSound(STATE_UP); + + // Input dispatched early, before state change (but after sound) + if (this.onInputUp) + { + this.onInputUp.dispatch(this, pointer, isOver); + } + + if (this.freezeFrames) + { + return; + } + + if (this.forceOut === true || (this.forceOut & pointer.pointerMode) === pointer.pointerMode) + { + this.changeStateFrame(STATE_OUT); + } + else + { + var changedUp = this.changeStateFrame(STATE_UP); + if (!changedUp) + { + // No Up frame to show.. + if (isOver) + { + this.changeStateFrame(STATE_OVER); + } + else + { + this.changeStateFrame(STATE_OUT); + } + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. +* It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over +* 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled +* Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. +* +* Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. +* +* @class Phaser.SpriteBatch +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. +* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. +*/ +Phaser.SpriteBatch = function (game, parent, name, addToStage) { + + if (parent === undefined || parent === null) { parent = game.world; } + + Phaser.Group.call(this, game, parent, name, addToStage); + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.SPRITEBATCH; + + /** + * @property {Object} fastSpriteBatch - WebGL Batch Shader. + * @private + */ + this.fastSpriteBatch = null; + + /** + * @property {boolean} ready - Internal flag. + * @private + */ + this.ready = false; + +}; + +Phaser.SpriteBatch.prototype = Object.create(Phaser.Group.prototype); + +Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch; + +/** +* Renders the Sprite Batch using the WebGL renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + if (!this.ready) + { + this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(renderSession.gl); + + this.ready = true; + } + + if (this.fastSpriteBatch.gl !== renderSession.gl) + { + this.fastSpriteBatch.setContext(renderSession.gl); + } + + renderSession.spriteBatch.stop(); + + renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader); + + this.fastSpriteBatch.begin(this, renderSession); + this.fastSpriteBatch.render(this); + + renderSession.spriteBatch.start(); + +}; + +/** +* Renders the Sprite Batch using the Canvas renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + var context = renderSession.context; + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + var transform = this.worldTransform; + + var isRotated = true; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + var texture = child.texture; + var frame = texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) + { + // If rotation === 0 we can avoid setTransform + + if (isRotated) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); + isRotated = false; + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5 + renderSession.shakeX) | 0, + ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5 + renderSession.shakeY) | 0, + frame.width * child.scale.x, + frame.height * child.scale.y); + } + else + { + if (!isRotated) + { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + var tx = (childTransform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (childTransform.ty * renderSession.resolution) + renderSession.shakeY; + + // allow for trimming + + if (renderSession.roundPixels) + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx, ty); + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width) + 0.5) | 0, + ((child.anchor.y) * (-frame.height) + 0.5) | 0, + frame.width, + frame.height); + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. +* A single BitmapData can be used as the texture for one or many Images / Sprites. +* So if you need to dynamically create a Sprite texture then they are a good choice. +* +* Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't +* live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy +* in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. +* +* @class Phaser.BitmapData +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string} key - Internal Phaser reference key for the BitmapData. +* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. +*/ +Phaser.BitmapData = function (game, key, width, height, skipPool) { + + if (width === undefined || width === 0) { width = 256; } + if (height === undefined || height === 0) { height = 256; } + if (skipPool === undefined) { skipPool = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the BitmapData in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} width - The width of the BitmapData in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the BitmapData in pixels. + */ + this.height = height; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. + * @default + */ + this.canvas = Phaser.Canvas.create(this, width, height, null, skipPool); + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + * @default + */ + this.context = this.canvas.getContext('2d', { alpha: true }); + + /** + * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context. + */ + this.ctx = this.context; + + /** + * @property {string} smoothProperty - The context property needed for smoothing this Canvas. + */ + this.smoothProperty = (game.renderType === Phaser.CANVAS) ? game.renderer.renderSession.smoothProperty : Phaser.Canvas.getSmoothingPrefix(this.context); + + /** + * @property {ImageData} imageData - The context image data. + * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. + * This property is updated automatically after the first game loop, according to the dirty flag property. + */ + this.imageData = this.context.getImageData(0, 0, width, height); + + /** + * A Uint8ClampedArray view into BitmapData.buffer. + * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) + * @property {Uint8ClampedArray} data + */ + this.data = null; + + if (this.imageData) + { + this.data = this.imageData.data; + } + + /** + * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer. + */ + this.pixels = null; + + /** + * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData. + */ + if (this.data) + { + 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; + } + } + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + this.baseTexture = new PIXI.BaseTexture(this.canvas, null, this.game.resolution); + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering. + */ + this.frameData = new Phaser.FrameData(); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. + * @default + */ + this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData')); + + this.texture.frame = this.textureFrame; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.BITMAPDATA; + + /** + * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} dirty - If dirty this BitmapData will be re-rendered. + */ + this.dirty = false; + + // Aliases + this.cls = this.clear; + + /** + * @property {number} _image - Internal cache var. + * @private + */ + this._image = null; + + /** + * @property {Phaser.Point} _pos - Internal cache var. + * @private + */ + this._pos = new Phaser.Point(); + + /** + * @property {Phaser.Point} _size - Internal cache var. + * @private + */ + this._size = new Phaser.Point(); + + /** + * @property {Phaser.Point} _scale - Internal cache var. + * @private + */ + this._scale = new Phaser.Point(); + + /** + * @property {number} _rotate - Internal cache var. + * @private + */ + this._rotate = 0; + + /** + * @property {object} _alpha - Internal cache var. + * @private + */ + this._alpha = { prev: 1, current: 1 }; + + /** + * @property {Phaser.Point} _anchor - Internal cache var. + * @private + */ + this._anchor = new Phaser.Point(); + + /** + * @property {number} _tempR - Internal cache var. + * @private + */ + this._tempR = 0; + + /** + * @property {number} _tempG - Internal cache var. + * @private + */ + this._tempG = 0; + + /** + * @property {number} _tempB - Internal cache var. + * @private + */ + this._tempB = 0; + + /** + * @property {Phaser.Circle} _circle - Internal cache var. + * @private + */ + this._circle = new Phaser.Circle(); + + /** + * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods. + * @private + */ + this._swapCanvas = undefined; + +}; + +Phaser.BitmapData.prototype = { + + /** + * Shifts the contents of this BitmapData by the distances given. + * + * The image will wrap-around the edges on all sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#move + * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + move: function (x, y, wrap) { + + if (x !== 0) + { + this.moveH(x, wrap); + } + + if (y !== 0) + { + this.moveV(y, wrap); + } + + return this; + + }, + + /** + * Shifts the contents of this BitmapData horizontally. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveH + * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveH: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var h = this.height; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving to the left + var w = this.width - distance; + + // Left-hand chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h); + } + else + { + // Moving to the right + var w = this.width - distance; + + // Right-hand chunk + if (wrap) + { + ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Shifts the contents of this BitmapData vertically. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveV + * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveV: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var w = this.width; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving up + var h = this.height - distance; + + // Top chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h); + } + else + { + // Moving down + var h = this.height - distance; + + // Bottom chunk + if (wrap) + { + ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Updates the given objects so that they use this BitmapData as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.BitmapData#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. + * The source game object is not modified by this operation. + * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. + * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. + * + * @method Phaser.BitmapData#load + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + load: function (source) { + + if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + } + + if (source) + { + this.resize(source.width, source.height); + this.cls(); + } + else + { + return; + } + + this.draw(source); + + this.update(); + + return this; + + }, + + /** + * Clears the BitmapData context using a clearRect. + * + * @method Phaser.BitmapData#cls + */ + + /** + * Clears the BitmapData context using a clearRect. + * + * You can optionally define the area to clear. + * If the arguments are left empty it will clear the entire canvas. + * + * You may need to call BitmapData.update after this in order to clear out the pixel data, + * but Phaser will not do this automatically for you. + * + * @method Phaser.BitmapData#clear + * @param {number} [x=0] - The x coordinate of the top-left of the area to clear. + * @param {number} [y=0] - The y coordinate of the top-left of the area to clear. + * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width. + * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + clear: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + this.context.clearRect(x, y, width, height); + + this.dirty = true; + + return this; + + }, + + /** + * Fills the BitmapData with the given color. + * + * @method Phaser.BitmapData#fill + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} [a=1] - The alpha color value, between 0 and 1. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + fill: function (r, g, b, a) { + + if (a === undefined) { a = 1; } + + this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; + this.context.fillRect(0, 0, this.width, this.height); + this.dirty = true; + + return this; + + }, + + /** + * Creates a new {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image} element by converting this BitmapDatas canvas into a dataURL. + * + * The image is then stored in the {@link Phaser.Cache image Cache} using the key given. + * + * Finally a {@link PIXI.Texture} is created based on the image and returned. + * + * You can apply the texture to a sprite or any other supporting object by using either the + * key or the texture. First call `generateTexture`: + * + * ```javascript + * var texture = bitmapdata.generateTexture('ball'); + * ``` + * + * Then you can either apply the texture to a sprite: + * + * ```javascript + * game.add.sprite(0, 0, texture); + * ``` + * + * or by using the string based key: + * + * ```javascript + * game.add.sprite(0, 0, 'ball'); + * ``` + * + * Most browsers now load the image data asynchronously, so you should use a callback: + * + * ```javascript + * bitmapdata.generateTexture('ball', function (texture) { + * game.add.sprite(0, 0, texture); + * // or + * game.add.sprite(0, 0, 'ball'); + * }); + * ``` + * + * If this BitmapData is available during preload, you can use {@link Phaser.Loader#imageFromBitmapData} instead. + * + * @method Phaser.BitmapData#generateTexture + * @param {string} key - The key which will be used to store the image in the Cache. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {PIXI.Texture|null} The newly generated texture, or `null` if a callback was passed and the texture isn't available yet. + */ + generateTexture: function (key, callback, callbackContext) { + + var cache = this.game.cache; + var image = new Image(); + + if (callback) + { + image.onload = function () { + var obj = cache.addImage(key, '', image); + var texture = new PIXI.Texture(obj.base); + + callback.call(callbackContext || null, texture); + + image.onload = null; + }; + } + + image.src = this.canvas.toDataURL("image/png"); + + if (!callback) + { + var obj = cache.addImage(key, '', image); + + return new PIXI.Texture(obj.base); + } + + return null; + + }, + + /** + * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. + * + * @method Phaser.BitmapData#resize + * @param {integer} width - The new width of the BitmapData. + * @param {integer} height - The new height of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + resize: function (width, height) { + + if (width !== this.width || height !== this.height) + { + this.width = width; + this.height = height; + + this.canvas.width = width; + this.canvas.height = height; + + if (this._swapCanvas !== undefined) + { + this._swapCanvas.width = width; + this._swapCanvas.height = height; + } + + this.baseTexture.width = width; + this.baseTexture.height = height; + + this.textureFrame.width = width; + this.textureFrame.height = height; + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.update(); + this.dirty = true; + } + + return this; + + }, + + /** + * This re-creates the BitmapData.imageData from the current context. + * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. + * If not given the dimensions defaults to the full size of the context. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.BitmapData#update + * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from. + * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from. + * @param {number} [width=1] - The width of the image data area. + * @param {number} [height=1] - The height of the image data area. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + update: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = Math.max(1, this.width); } + if (height === undefined) { height = Math.max(1, this.height); } + + this.imageData = this.context.getImageData(x, y, width, height); + this.data = this.imageData.data; + + 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; + } + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. + * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. + * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. + * The `color` property is an Int32 of the full color. Note the endianess of this will change per system. + * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. + * The callback will also be sent the pixels x and y coordinates respectively. + * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. + * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. + * + * @method Phaser.BitmapData#processPixelRGB + * @param {function} callback - The callback that will be sent each pixel color object to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixelRGB: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = Phaser.Color.createColor(); + var result = { r: 0, g: 0, b: 0, a: 0 }; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel); + + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== false && result !== null && result !== undefined) + { + this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false); + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. + * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. + * Note that the format of the color received will be different depending on if the system is big or little endian. + * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. + * The callback will also be sent the pixels x and y coordinates respectively. + * + * @method Phaser.BitmapData#processPixel + * @param {function} callback - The callback that will be sent each pixel color to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixel: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = 0; + var result = 0; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + pixel = this.getPixel32(tx, ty); + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== pixel) + { + this.pixels[ty * this.width + tx] = result; + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. + * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. + * + * @method Phaser.BitmapData#replaceRGB + * @param {number} r1 - The red color value to be replaced. Between 0 and 255. + * @param {number} g1 - The green color value to be replaced. Between 0 and 255. + * @param {number} b1 - The blue color value to be replaced. Between 0 and 255. + * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255. + * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255. + * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255. + * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255. + * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255. + * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) { + + var sx = 0; + var sy = 0; + var w = this.width; + var h = this.height; + var source = Phaser.Color.packPixel(r1, g1, b1, a1); + + if (region !== undefined && region instanceof Phaser.Rectangle) + { + sx = region.x; + sy = region.y; + w = region.width; + h = region.height; + } + + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + if (this.getPixel32(sx + x, sy + y) === source) + { + this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false); + } + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * + * @method Phaser.BitmapData#setHSL + * @param {number} [h=null] - The hue, in the range 0 - 1. + * @param {number} [s=null] - The saturation, in the range 0 - 1. + * @param {number} [l=null] - The lightness, in the range 0 - 1. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setHSL: function (h, s, l, region) { + + var bHaveH = h || h === 0; + var bHaveS = s || s === 0; + var bHaveL = l || l === 0; + + if (!bHaveH && !bHaveS && !bHaveL) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (bHaveH) + { + pixel.h = h; + } + + if (bHaveS) + { + pixel.s = s; + } + + if (bHaveL) + { + pixel.l = l; + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * Shifting will add the given value onto the current h, s and l values, not replace them. + * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. + * + * @method Phaser.BitmapData#shiftHSL + * @param {number} [h=null] - The amount to shift the hue by. Within [-1, 1]. + * @param {number} [s=null] - The amount to shift the saturation by. Within [-1, 1]. + * @param {number} [l=null] - The amount to shift the lightness by. Within [-1, 1]. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shiftHSL: function (h, s, l, region) { + + if (h === undefined || h === null) { h = false; } + if (s === undefined || s === null) { s = false; } + if (l === undefined || l === null) { l = false; } + + if (!h && !s && !l) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (h) + { + pixel.h = this.game.math.wrap(pixel.h + h, 0, 1); + } + + if (s) + { + pixel.s = this.game.math.clamp(pixel.s + s, 0, 1); + } + + if (l) + { + pixel.l = this.game.math.clamp(pixel.l + l, 0, 1); + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green, blue and alpha values. + * + * @method Phaser.BitmapData#setPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel32: function (x, y, red, green, blue, alpha, immediate) { + + if (immediate === undefined) { immediate = true; } + + if (x >= 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; + } + } + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green and blue values. + * + * @method Phaser.BitmapData#setPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel: function (x, y, red, green, blue, immediate) { + + return this.setPixel32(x, y, red, green, blue, 255, immediate); + + }, + + /** + * Get the color of a specific pixel in the context into a color object. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + getPixel: function (x, y, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var index = ~~(x + (y * this.width)); + + index *= 4; + + out.r = this.data[index]; + out.g = this.data[++index]; + out.b = this.data[++index]; + out.a = this.data[++index]; + + return out; + + }, + + /** + * Get the color of a specific pixel including its alpha value. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. + * + * @method Phaser.BitmapData#getPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @return {number} A native color value integer (format: 0xAARRGGBB) + */ + getPixel32: function (x, y) { + + if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) + { + return this.pixels[y * this.width + x]; + } + + }, + + /** + * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixelRGB + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + getPixelRGB: function (x, y, out, hsl, hsv) { + + return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv); + + }, + + /** + * Gets all the pixels from the region specified by the given Rectangle object. + * + * @method Phaser.BitmapData#getPixels + * @param {Phaser.Rectangle} rect - The Rectangle region to get. + * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property. + */ + getPixels: function (rect) { + + return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); + + }, + + /** + * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). + * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. + * + * The direction parameter controls from which direction it should start the scan: + * + * 0 = top to bottom + * 1 = bottom to top + * 2 = left to right + * 3 = right to left + * + * @method Phaser.BitmapData#getFirstPixel + * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. + * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. + */ + getFirstPixel: function (direction) { + + if (direction === undefined) { direction = 0; } + + var pixel = Phaser.Color.createColor(); + + var x = 0; + var y = 0; + var v = 1; + var scan = false; + + if (direction === 1) + { + v = -1; + y = this.height; + } + else if (direction === 3) + { + v = -1; + x = this.width; + } + + do { + + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel); + + if (direction === 0 || direction === 1) + { + // Top to Bottom / Bottom to Top + x++; + + if (x === this.width) + { + x = 0; + y += v; + + if (y >= this.height || y <= 0) + { + scan = true; + } + } + } + else if (direction === 2 || direction === 3) + { + // Left to Right / Right to Left + y++; + + if (y === this.height) + { + y = 0; + x += v; + + if (x >= this.width || x <= 0) + { + scan = true; + } + } + } + } + while (pixel.a === 0 && !scan); + + pixel.x = x; + pixel.y = y; + + return pixel; + + }, + + /** + * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. + * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. + * + * @method Phaser.BitmapData#getBounds + * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. + * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. + */ + getBounds: function (rect) { + + if (rect === undefined) { rect = new Phaser.Rectangle(); } + + rect.x = this.getFirstPixel(2).x; + + // If we hit this, there's no point scanning any more, the image is empty + if (rect.x === this.width) + { + return rect.setTo(0, 0, 0, 0); + } + + rect.y = this.getFirstPixel(0).y; + rect.width = (this.getFirstPixel(3).x - rect.x) + 1; + rect.height = (this.getFirstPixel(1).y - rect.y) + 1; + + return rect; + + }, + + /** + * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. + * + * @method Phaser.BitmapData#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself. + * + * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn. + * + * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters. + * + * Note that the source image can also be this BitmapData, which can create some interesting effects. + * + * This method has a lot of parameters for maximum control. + * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all. + * + * You may prefer to use `copyTransform` if you're simply trying to draw a Sprite to this BitmapData, + * and don't wish to translate, scale or rotate it from its original values. + * + * @method Phaser.BitmapData#copy + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image. + * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image. + * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width. + * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height. + * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`. + * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`. + * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter. + * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter. + * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters. + * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) { + + if (source === undefined || source === null) { source = this; } + + if (source instanceof Phaser.RenderTexture) + { + source = source.getCanvas(); + } + + this._image = source; + + if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text || source instanceof PIXI.Sprite) + { + // Copy over sprite values + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + this._scale.set(source.scale.x, source.scale.y); + this._anchor.set(source.anchor.x, source.anchor.y); + this._rotate = source.rotation; + this._alpha.current = source.alpha; + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + if (tx === undefined || tx === null) { tx = source.x; } + if (ty === undefined || ty === null) { ty = source.y; } + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + } + else + { + // Reset + this._pos.set(0); + this._scale.set(1); + this._anchor.set(0); + this._rotate = 0; + this._alpha.current = 1; + + if (source instanceof Phaser.BitmapData) + { + this._image = source.canvas; + } + else if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + + if (source === null) + { + return; + } + else + { + this._image = source; + } + } + + this._size.set(this._image.width, this._image.height); + } + + // The source region to copy from + if (x === undefined || x === null) { x = 0; } + if (y === undefined || y === null) { y = 0; } + + // If they set a width/height then we override the frame values with them + if (width) + { + this._size.x = width; + } + + if (height) + { + this._size.y = height; + } + + // The destination region to copy to + if (tx === undefined || tx === null) { tx = x; } + if (ty === undefined || ty === null) { ty = y; } + if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; } + if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; } + + // Rotation - if set this will override any potential Sprite value + if (typeof rotate === 'number') + { + this._rotate = rotate; + } + + // Anchor - if set this will override any potential Sprite value + if (typeof anchorX === 'number') + { + this._anchor.x = anchorX; + } + + if (typeof anchorY === 'number') + { + this._anchor.y = anchorY; + } + + // Scaling - if set this will override any potential Sprite value + if (typeof scaleX === 'number') + { + this._scale.x = scaleX; + } + + if (typeof scaleY === 'number') + { + this._scale.y = scaleY; + } + + // Effects + if (typeof alpha === 'number') + { + this._alpha.current = alpha; + } + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + // Doesn't work fully with children, or nested scale + rotation transforms (see copyTransform) + ctx.translate(tx, ty); + + ctx.scale(this._scale.x, this._scale.y); + + ctx.rotate(this._rotate); + + ctx.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight); + + // Carry on ... + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the + * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. + * It takes the objects tint and scale mode into consideration before drawing. + * + * You can optionally specify Blend Mode and Round Pixels arguments. + * + * @method Phaser.BitmapData#copyTransform + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyTransform: function (source, blendMode, roundPx) { + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (!source.hasOwnProperty('worldTransform') || !source.worldVisible || source.worldAlpha === 0) + { + return this; + } + + var wt = source.worldTransform; + + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + + if (wt.a === 0 || wt.d === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return this; + } + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + var tx = wt.tx; + var ty = wt.ty; + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + ctx[this.smoothProperty] = (source.texture.baseTexture.scaleMode === PIXI.scaleModes.LINEAR); + + ctx.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + + ctx.drawImage(this._image, + this._pos.x, + this._pos.y, + this._size.x, + this._size.y, + -this._size.x * source.anchor.x, + -this._size.y * source.anchor.y, + this._size.x, + this._size.y); + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. + * + * @method Phaser.BitmapData#copyRect + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. + * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image. + * @param {number} x - The destination x coordinate to copy the image to. + * @param {number} y - The destination y coordinate to copy the image to. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyRect: function (source, area, x, y, alpha, blendMode, roundPx) { + + return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx); + + }, + + /** + * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. + * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. + * + * @method Phaser.BitmapData#draw + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData. + * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`. + * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`. + * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`. + * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + draw: function (source, x, y, width, height, blendMode, roundPx) { + + // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here + return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx); + + }, + + /** + * Draws the immediate children of a Phaser.Group to this BitmapData. + * + * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. + * + * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. + * + * @method Phaser.BitmapData#drawGroup + * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawGroup: function (group, blendMode, roundPx) { + + if (group.total > 0) + { + group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx); + } + + return this; + + }, + + /** + * A proxy for drawGroup that handles child iteration for more complex Game Objects. + * + * @method Phaser.BitmapData#drawGroupProxy + * @private + * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + */ + drawGroupProxy: function (child, blendMode, roundPx) { + + if (child.hasOwnProperty('texture')) + { + this.copyTransform(child, blendMode, roundPx); + } + + if (child.type === Phaser.GROUP && child.exists) + { + this.drawGroup(child, blendMode, roundPx); + } + else + { + if (child.hasOwnProperty('children') && child.children.length > 0) + { + for (var i = 0; i < child.children.length; i++) + { + if (child.children[i].exists) + { + this.copyTransform(child.children[i], blendMode, roundPx); + } + } + } + } + + }, + + /** + * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. + * + * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData + * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the + * bounds of the top-level Game Object. + * + * When drawing it will take into account the child's world rotation, scale and alpha values. + * + * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. + * + * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update + * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can + * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. + * + * @method Phaser.BitmapData#drawFull + * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawFull: function (parent, blendMode, roundPx) { + + if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false)) + { + return this; + } + + if (parent.type !== Phaser.GROUP && parent.type !== Phaser.EMITTER && parent.type !== Phaser.BITMAPTEXT) + { + if (parent.type === Phaser.GRAPHICS) + { + var bounds = parent.getBounds(); + this.ctx.save(); + this.ctx.translate(bounds.x, bounds.y); + PIXI.CanvasGraphics.renderGraphics(parent, this.ctx); + this.ctx.restore(); + } + else + { + this.copy(parent, null, null, null, null, parent.worldPosition.x, parent.worldPosition.y, null, null, parent.worldRotation, null, null, parent.worldScale.x, parent.worldScale.y, parent.worldAlpha, blendMode, roundPx); + } + } + + if (parent.children) + { + for (var i = 0; i < parent.children.length; i++) + { + this.drawFull(parent.children[i], blendMode, roundPx); + } + } + + return this; + + }, + + /** + * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. + * You can cancel an existing shadow by calling this method and passing no parameters. + * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. + * + * @method Phaser.BitmapData#shadow + * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. + * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. + * @param {number} [x=10] - The horizontal offset of the shadow in pixels. + * @param {number} [y=10] - The vertical offset of the shadow in pixels. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shadow: function (color, blur, x, y) { + + var ctx = this.context; + + if (color === undefined || color === null) + { + ctx.shadowColor = 'rgba(0,0,0,0)'; + } + else + { + ctx.shadowColor = color; + ctx.shadowBlur = blur || 5; + ctx.shadowOffsetX = x || 10; + ctx.shadowOffsetY = y || 10; + } + + return this; + + }, + + /** + * Draws the image onto this BitmapData using an image as an alpha mask. + * + * @method Phaser.BitmapData#alphaMask + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. + * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. + * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + alphaMask: function (source, mask, sourceRect, maskRect) { + + if (maskRect === undefined || maskRect === null) + { + this.draw(mask).blendSourceAtop(); + } + else + { + this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop(); + } + + if (sourceRect === undefined || sourceRect === null) + { + this.draw(source).blendReset(); + } + else + { + this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset(); + } + + return this; + + }, + + /** + * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. + * The original BitmapData remains unchanged. + * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. + * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: + * `picture.extract(mask, r, g, b)` + * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. + * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint + * the color during extraction. + * + * @method Phaser.BitmapData#extract + * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. + * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied? + * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255. + * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255. + * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255. + * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on. + */ + extract: function (destination, r, g, b, a, resize, r2, g2, b2) { + + if (a === undefined) { a = 255; } + if (resize === undefined) { resize = false; } + if (r2 === undefined) { r2 = r; } + if (g2 === undefined) { g2 = g; } + if (b2 === undefined) { b2 = b; } + + if (resize) + { + destination.resize(this.width, this.height); + } + + this.processPixelRGB( + function (pixel, x, y) + { + if (pixel.r === r && pixel.g === g && pixel.b === b) + { + destination.setPixel32(x, y, r2, g2, b2, a, false); + } + return false; + }, + this); + + destination.context.putImageData(destination.imageData, 0, 0); + destination.dirty = true; + + return destination; + + }, + + /** + * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. + * + * @method Phaser.BitmapData#rect + * @param {number} x - The x coordinate of the top-left of the Rectangle. + * @param {number} y - The y coordinate of the top-left of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + rect: function (x, y, width, height, fillStyle) { + + if (typeof fillStyle !== 'undefined') + { + this.context.fillStyle = fillStyle; + } + + this.context.fillRect(x, y, width, height); + + return this; + + }, + + /** + * Draws text to the BitmapData in the given font and color. + * The default font is 14px Courier, so useful for quickly drawing debug text. + * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. + * + * @method Phaser.BitmapData#text + * @param {string} text - The text to write to the BitmapData. + * @param {number} x - The x coordinate of the top-left of the text string. + * @param {number} y - The y coordinate of the top-left of the text string. + * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can. + * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in. + * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1) + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + text: function (text, x, y, font, color, shadow) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (font === undefined) { font = '14px Courier'; } + if (color === undefined) { color = 'rgb(255,255,255)'; } + if (shadow === undefined) { shadow = true; } + + var ctx = this.context; + var prevFont = ctx.font; + + ctx.font = font; + + if (shadow) + { + ctx.fillStyle = 'rgb(0,0,0)'; + ctx.fillText(text, x + 1, y + 1); + } + + ctx.fillStyle = color; + ctx.fillText(text, x, y); + + ctx.font = prevFont; + + return this; + + }, + + /** + * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. + * + * @method Phaser.BitmapData#circle + * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle. + * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle. + * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + circle: function (x, y, radius, fillStyle) { + + var ctx = this.context; + + if (fillStyle !== undefined) + { + ctx.fillStyle = fillStyle; + } + + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2, false); + ctx.closePath(); + + ctx.fill(); + + return this; + + }, + + /** + * Draws a line between the coordinates given in the color and thickness specified. + * + * @method Phaser.BitmapData#line + * @param {number} x1 - The x coordinate to start the line from. + * @param {number} y1 - The y coordinate to start the line from. + * @param {number} x2 - The x coordinate to draw the line to. + * @param {number} y2 - The y coordinate to draw the line to. + * @param {string} [color='#fff'] - The stroke color that the line will be drawn in. + * @param {number} [width=1] - The line thickness. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + line: function (x1, y1, x2, y2, color, width) { + + if (color === undefined) { color = '#fff'; } + if (width === undefined) { width = 1; } + + var ctx = this.context; + + ctx.beginPath(); + + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); + + ctx.closePath(); + + return this; + + }, + + /** + * Draws a polygon. + * + * @method Phaser.BitmapData#polygon + * @param {object[]} points - An array of {@link Phaser.Point} or point-like objects. + * @param {CanvasGradient|CanvasPattern|string} [fillStyle] - A color, gradient, or pattern. + * @param {number} [lineWidth=0] - The line thickness. + * @param {CanvasGradient|CanvasPattern|string} [strokeStyle='#fff'] - The line color, gradient, or pattern (when `lineWidth` > 0). + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + polygon: function (points, fillStyle, lineWidth, strokeStyle) { + + // Could reject points.length < 3 + + if (strokeStyle === undefined) { strokeStyle = '#fff'; } + if (lineWidth === undefined) { lineWidth = 0; } + + var ctx = this.context; + + if (fillStyle) + { + ctx.fillStyle = fillStyle; + } + + if (lineWidth) + { + ctx.lineWidth = lineWidth; + ctx.strokeStyle = strokeStyle; + } + + ctx.beginPath(); + + ctx.moveTo(points[0].x, points[0].y); + + for (var i = 1, len = points.length; i < len; i++) + { + var point = points[i]; + ctx.lineTo(point.x, point.y); + } + + ctx.closePath(); + + if (fillStyle) { ctx.fill(); } + if (lineWidth) { ctx.stroke(); } + + return this; + + }, + + /** + * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. + * + * @method Phaser.BitmapData#textureLine + * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line. + * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. + * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + textureLine: function (line, image, repeat) { + + if (repeat === undefined) { repeat = 'repeat-x'; } + + if (typeof image === 'string') + { + image = this.game.cache.getImage(image); + + if (!image) + { + return; + } + } + + var width = line.length; + + if (repeat === 'no-repeat' && width > image.width) + { + width = image.width; + } + + var ctx = this.context; + + ctx.fillStyle = ctx.createPattern(image, repeat); + + this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height); + + this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos); + + ctx.save(); + ctx.translate(this._pos.x, this._pos.y); + ctx.rotate(line.angle); + ctx.fillRect(0, 0, width, image.height); + ctx.restore(); + + this.dirty = true; + + return this; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. + * + * @method Phaser.BitmapData#render + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + render: function () { + + if (!this.disableTextureUpload && this.dirty) + { + this.baseTexture.dirty(); + this.dirty = false; + } + + return this; + + }, + + /** + * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. + * + * @method Phaser.BitmapData#destroy + */ + destroy: function () { + + this.frameData.destroy(); + + this.texture.destroy(true); + + Phaser.CanvasPool.remove(this); + + }, + + /** + * Resets the blend mode (effectively sets it to 'source-over') + * + * @method Phaser.BitmapData#blendReset + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendReset: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-over' + * + * @method Phaser.BitmapData#blendSourceOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOver: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-in' + * + * @method Phaser.BitmapData#blendSourceIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceIn: function () { + + this.op = 'source-in'; + return this; + + }, + + /** + * Sets the blend mode to 'source-out' + * + * @method Phaser.BitmapData#blendSourceOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOut: function () { + + this.op = 'source-out'; + return this; + + }, + + /** + * Sets the blend mode to 'source-atop' + * + * @method Phaser.BitmapData#blendSourceAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceAtop: function () { + + this.op = 'source-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-over' + * + * @method Phaser.BitmapData#blendDestinationOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOver: function () { + + this.op = 'destination-over'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-in' + * + * @method Phaser.BitmapData#blendDestinationIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationIn: function () { + + this.op = 'destination-in'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-out' + * + * @method Phaser.BitmapData#blendDestinationOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOut: function () { + + this.op = 'destination-out'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-atop' + * + * @method Phaser.BitmapData#blendDestinationAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationAtop: function () { + + this.op = 'destination-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'xor' + * + * @method Phaser.BitmapData#blendXor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendXor: function () { + + this.op = 'xor'; + return this; + + }, + + /** + * Sets the blend mode to 'lighter' + * + * @method Phaser.BitmapData#blendAdd + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendAdd: function () { + + this.op = 'lighter'; + return this; + + }, + + /** + * Sets the blend mode to 'multiply' + * + * @method Phaser.BitmapData#blendMultiply + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendMultiply: function () { + + this.op = 'multiply'; + return this; + + }, + + /** + * Sets the blend mode to 'screen' + * + * @method Phaser.BitmapData#blendScreen + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendScreen: function () { + + this.op = 'screen'; + return this; + + }, + + /** + * Sets the blend mode to 'overlay' + * + * @method Phaser.BitmapData#blendOverlay + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendOverlay: function () { + + this.op = 'overlay'; + return this; + + }, + + /** + * Sets the blend mode to 'darken' + * + * @method Phaser.BitmapData#blendDarken + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDarken: function () { + + this.op = 'darken'; + return this; + + }, + + /** + * Sets the blend mode to 'lighten' + * + * @method Phaser.BitmapData#blendLighten + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLighten: function () { + + this.op = 'lighten'; + return this; + + }, + + /** + * Sets the blend mode to 'color-dodge' + * + * @method Phaser.BitmapData#blendColorDodge + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorDodge: function () { + + this.op = 'color-dodge'; + return this; + + }, + + /** + * Sets the blend mode to 'color-burn' + * + * @method Phaser.BitmapData#blendColorBurn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorBurn: function () { + + this.op = 'color-burn'; + return this; + + }, + + /** + * Sets the blend mode to 'hard-light' + * + * @method Phaser.BitmapData#blendHardLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHardLight: function () { + + this.op = 'hard-light'; + return this; + + }, + + /** + * Sets the blend mode to 'soft-light' + * + * @method Phaser.BitmapData#blendSoftLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSoftLight: function () { + + this.op = 'soft-light'; + return this; + + }, + + /** + * Sets the blend mode to 'difference' + * + * @method Phaser.BitmapData#blendDifference + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDifference: function () { + + this.op = 'difference'; + return this; + + }, + + /** + * Sets the blend mode to 'exclusion' + * + * @method Phaser.BitmapData#blendExclusion + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendExclusion: function () { + + this.op = 'exclusion'; + return this; + + }, + + /** + * Sets the blend mode to 'hue' + * + * @method Phaser.BitmapData#blendHue + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHue: function () { + + this.op = 'hue'; + return this; + + }, + + /** + * Sets the blend mode to 'saturation' + * + * @method Phaser.BitmapData#blendSaturation + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSaturation: function () { + + this.op = 'saturation'; + return this; + + }, + + /** + * Sets the blend mode to 'color' + * + * @method Phaser.BitmapData#blendColor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColor: function () { + + this.op = 'color'; + return this; + + }, + + /** + * Sets the blend mode to 'luminosity' + * + * @method Phaser.BitmapData#blendLuminosity + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLuminosity: function () { + + this.op = 'luminosity'; + return this; + + }, + + /** + * Updates a portion of the BitmapData from a source Bitmap. + * This optimization is important if calling update() on a large Bitmap is causing performance issues. + * Make sure you use getPixel32() instead of getPixel(). + * This does not work with floating point numbers for x and y. + * + * @method Phaser.BitmapData#copyBitmapData + * @param {Phaser.BitmapData} [source] - The BitmapData you wish to copy. + * @param {number} [x] - The x coordinate of the top-left of the area to copy. + * @param {number} [y] - The y coordinate of the top-left of the area to copy. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyBitmapData: function(source, x, y) { + + source.update(); + for (var i = 0, destRowStart; i < source.height; i++) { + destRowStart = (y + i) * this.width + x; + for (var j = 0; j < source.width; j++) { + this.pixels[destRowStart + j] = source.pixels[i * source.width + j]; + } + } + return this; + + } + +}; + +/** +* @memberof Phaser.BitmapData +* @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", { + + get: function () { + + Phaser.Canvas.getSmoothingEnabled(this.context); + + }, + + set: function (value) { + + Phaser.Canvas.setSmoothingEnabled(this.context, value); + + } + +}); + +/** +* @memberof Phaser.BitmapData +* @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "op", { + + get: function () { + + return this.context.globalCompositeOperation; + + }, + + set: function (value) { + + this.context.globalCompositeOperation = value; + + } + +}); + +/** + * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform. + * + * @method Phaser.BitmapData.getTransform + * @param {number} translateX - The x translate value. + * @param {number} translateY - The y translate value. + * @param {number} scaleX - The scale x value. + * @param {number} scaleY - The scale y value. + * @param {number} skewX - The skew x value. + * @param {number} skewY - The skew y value. + * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms. + */ +Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) { + + if (typeof translateX !== 'number') { translateX = 0; } + if (typeof translateY !== 'number') { translateY = 0; } + if (typeof scaleX !== 'number') { scaleX = 1; } + if (typeof scaleY !== 'number') { scaleY = 1; } + if (typeof skewX !== 'number') { skewX = 0; } + if (typeof skewY !== 'number') { skewY = 0; } + + return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY }; + +}; + +Phaser.BitmapData.prototype.constructor = Phaser.BitmapData; + +/* jshint ignore:start */ + +/* +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ + +/** +* @class EarCut +*/ +Phaser.EarCut = {}; + +Phaser.EarCut.Triangulate = function (data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = Phaser.EarCut.linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = Phaser.EarCut.eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + Phaser.EarCut.earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +}; + +// create a circular doubly linked list from polygon points in the specified winding order + +Phaser.EarCut.linkedList = function (data, start, end, dim, clockwise) { + var sum = 0, + i, j, last; + + // calculate original winding order of a polygon ring + for (i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + + // link points into circular doubly-linked list in the specified winding order + if (clockwise === (sum > 0)) { + for (i = start; i < end; i += dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } + + return last; +}; + +// eliminate colinear or duplicate points + +Phaser.EarCut.filterPoints = function (start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (Phaser.EarCut.equals(p, p.next) || Phaser.EarCut.area(p.prev, p, p.next) === 0)) { + Phaser.EarCut.removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +}; + +// main ear slicing loop which triangulates a polygon (given as a linked list) + +Phaser.EarCut.earcutLinked = function (ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) Phaser.EarCut.indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? Phaser.EarCut.isEarHashed(ear, minX, minY, size) : Phaser.EarCut.isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + Phaser.EarCut.removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + Phaser.EarCut.earcutLinked(Phaser.EarCut.filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = Phaser.EarCut.cureLocalIntersections(ear, triangles, dim); + Phaser.EarCut.earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + Phaser.EarCut.splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +}; + +// check whether a polygon node forms a valid ear with adjacent nodes + +Phaser.EarCut.isEar = function (ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +}; + +Phaser.EarCut.isEarHashed = function (ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = Phaser.EarCut.zOrder(minTX, minTY, minX, minY, size), + maxZ = Phaser.EarCut.zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +}; + +// go through all polygon nodes and cure small local self-intersections + +Phaser.EarCut.cureLocalIntersections = function (start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) + if (Phaser.EarCut.intersects(a, p, p.next, b) && Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + Phaser.EarCut.removeNode(p); + Phaser.EarCut.removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +}; + +// try splitting polygon into two and triangulate them independently + +Phaser.EarCut.splitEarcut = function (start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && Phaser.EarCut.isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = Phaser.EarCut.splitPolygon(a, b); + + // filter colinear points around the cuts + a = Phaser.EarCut.filterPoints(a, a.next); + c = Phaser.EarCut.filterPoints(c, c.next); + + // run earcut on each half + Phaser.EarCut.earcutLinked(a, triangles, dim, minX, minY, size); + Phaser.EarCut.earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +}; + +// link every hole into the outer loop, producing a single-ring polygon without holes + +Phaser.EarCut.eliminateHoles = function (data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = Phaser.EarCut.linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(Phaser.EarCut.getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + Phaser.EarCut.eliminateHole(queue[i], outerNode); + outerNode = Phaser.EarCut.filterPoints(outerNode, outerNode.next); + } + + return outerNode; +}; + +Phaser.EarCut.compareX = function (a, b) { + return a.x - b.x; +}; + +// find a bridge between vertices that connects hole with an outer ring and and link it + +Phaser.EarCut.eliminateHole = function (hole, outerNode) { + outerNode = Phaser.EarCut.findHoleBridge(hole, outerNode); + if (outerNode) { + var b = Phaser.EarCut.splitPolygon(outerNode, hole); + Phaser.EarCut.filterPoints(b, b.next); + } +}; + +// David Eberly's algorithm for finding a bridge between hole and outer polygon + +Phaser.EarCut.findHoleBridge = function (hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hole.x === m.x) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= m.x && + Phaser.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && Phaser.EarCut.locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +}; + +// interlink polygon nodes in z-order + +Phaser.EarCut.indexCurve = function (start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = Phaser.EarCut.zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + Phaser.EarCut.sortLinked(p); +}; + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + +Phaser.EarCut.sortLinked = function (list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +}; + +// z-order of a point given coords and size of the data bounding box + +Phaser.EarCut.zOrder = function (x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +}; + +// find the leftmost node of a polygon ring + +Phaser.EarCut.getLeftmost = function (start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +}; + +// check if a point lies within a convex triangle + +Phaser.EarCut.pointInTriangle = function (ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +}; + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) + +Phaser.EarCut.isValidDiagonal = function (a, b) { + return Phaser.EarCut.equals(a, b) || a.next.i !== b.i && a.prev.i !== b.i && !Phaser.EarCut.intersectsPolygon(a, b) && + Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a) && Phaser.EarCut.middleInside(a, b); +}; + +// signed area of a triangle + +Phaser.EarCut.area = function (p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +}; + +// check if two points are equal + +Phaser.EarCut.equals = function (p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +}; + +// check if two segments intersect + +Phaser.EarCut.intersects = function (p1, q1, p2, q2) { + return Phaser.EarCut.area(p1, q1, p2) > 0 !== Phaser.EarCut.area(p1, q1, q2) > 0 && + Phaser.EarCut.area(p2, q2, p1) > 0 !== Phaser.EarCut.area(p2, q2, q1) > 0; +}; + +// check if a polygon diagonal intersects any polygon segments + +Phaser.EarCut.intersectsPolygon = function (a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + Phaser.EarCut.intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +}; + +// check if a polygon diagonal is locally inside the polygon + +Phaser.EarCut.locallyInside = function (a, b) { + return Phaser.EarCut.area(a.prev, a, a.next) < 0 ? + Phaser.EarCut.area(a, b, a.next) >= 0 && Phaser.EarCut.area(a, a.prev, b) >= 0 : + Phaser.EarCut.area(a, b, a.prev) < 0 || Phaser.EarCut.area(a, a.next, b) < 0; +}; + +// check if the middle point of a polygon diagonal is inside the polygon + +Phaser.EarCut.middleInside = function (a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +}; + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring + +Phaser.EarCut.splitPolygon = function (a, b) { + var a2 = new Phaser.EarCut.Node(a.i, a.x, a.y), + b2 = new Phaser.EarCut.Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +}; + +// create a node and optionally link it with previous one (in a circular doubly linked list) + +Phaser.EarCut.insertNode = function (i, x, y, last) { + var p = new Phaser.EarCut.Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +}; + +Phaser.EarCut.removeNode = function (p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +}; + +Phaser.EarCut.Node = function (i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +}; + +/* jshint ignore:end */ + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used by the webGL renderer to draw the primitive graphics data + * + * @class PIXI.WebGLGraphics + * @private + * @static + */ +PIXI.WebGLGraphics = function() +{ +}; + +/** + * The number of points beyond which Pixi swaps to using the Stencil Buffer to render the Graphics. + * + * @type {number} + */ +PIXI.WebGLGraphics.stencilBufferLimit = 6; + +/** + * Renders the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.renderGraphics + * @param graphics {Graphics} + * @param renderSession {Object} + */ +PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset) +{ + var gl = renderSession.gl; + var projection = renderSession.projection, + offset = renderSession.offset, + shader = renderSession.shaderManager.primitiveShader, + webGLData; + + if(graphics.dirty) + { + PIXI.WebGLGraphics.updateGraphics(graphics, gl); + } + + var webGL = graphics._webGL[gl.id]; + + // if the graphics object does not exist in the webGL context skip rendering! + if(!webGL) + { + return; + } + + // This could be speeded up for sure! + + for (var i = 0; i < webGL.data.length; i++) + { + if(webGL.data[i].mode === 1) + { + webGLData = webGL.data[i]; + + renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession); + + // render quad.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + renderSession.stencilManager.popStencil(graphics, webGLData, renderSession); + } + else + { + webGLData = webGL.data[i]; + + + renderSession.shaderManager.setShader( shader );//activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, 1); + + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + } + } +}; + +/** + * Updates the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.updateGraphics + * @param graphicsData {Graphics} The graphics object to update + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLGraphics.updateGraphics = function(graphics, gl) +{ + // get the contexts graphics object + var webGL = graphics._webGL[gl.id]; + // if the graphics object does not exist in the webGL context time to create it! + if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; + + // flag the graphics as not dirty as we are about to update it... + graphics.dirty = false; + + var i; + + // if the user cleared the graphics object we will need to clear every object + if(graphics.clearDirty) + { + graphics.clearDirty = false; + + // lop through and return all the webGLDatas to the object pool so than can be reused later on + for (i = 0; i < webGL.data.length; i++) + { + var graphicsData = webGL.data[i]; + graphicsData.reset(); + PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData ); + } + + // clear the array and reset the index.. + webGL.data = []; + webGL.lastIndex = 0; + } + + var webGLData; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + if (data.type === Phaser.POLYGON) + { + // need to add the points the the graphics object.. + data.points = data.shape.points.slice(); + if(data.shape.closed) + { + // close the poly if the value is true! + if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { + data.points.push(data.points[0], data.points[1]); + } + } + + // MAKE SURE WE HAVE THE CORRECT TYPE.. + if(data.fill) + { + if(data.points.length >= PIXI.WebGLGraphics.stencilBufferLimit) + { + if(data.points.length < PIXI.WebGLGraphics.stencilBufferLimit * 2) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData); + // console.log(canDrawUsingSimple); + + if(!canDrawUsingSimple) + { + // console.log("<>>>") + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + } + } + + if(data.lineWidth > 0) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + PIXI.WebGLGraphics.buildLine(data, webGLData); + + } + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + if (data.type === Phaser.RECTANGLE) + { + PIXI.WebGLGraphics.buildRectangle(data, webGLData); + } + else if (data.type === Phaser.CIRCLE || data.type === Phaser.ELLIPSE) + { + PIXI.WebGLGraphics.buildCircle(data, webGLData); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData); + } + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (i = 0; i < webGL.data.length; i++) + { + webGLData = webGL.data[i]; + if(webGLData.dirty)webGLData.upload(); + } +}; + +/** + * @static + * @private + * @method PIXI.WebGLGraphics.switchMode + * @param webGL {WebGLContext} + * @param type {Number} + */ +PIXI.WebGLGraphics.switchMode = function(webGL, type) +{ + var webGLData; + + if(!webGL.data.length) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + else + { + webGLData = webGL.data[webGL.data.length-1]; + + if(webGLData.mode !== type || type === 1) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + } + + webGLData.dirty = true; + + return webGLData; +}; + +/** + * Builds a rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData) +{ + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; + + // start + 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); + + // insert 2 dead triangles.. + 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; + } +}; + +/** + * Builds a rounded rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRoundedRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData) +{ + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + recPoints.push(x, y + radius); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); + + if (graphicsData.fill) { + var color = Phaser.Color.hexToRGBArray(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; + + var triangles = Phaser.EarCut.Triangulate(recPoints, null, 2); + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i+1] + vecPos); + indices.push(triangles[i+2] + vecPos); + indices.push(triangles[i+2] + vecPos); + } + + + for (i = 0; i < recPoints.length; i++) + { + verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @static + * @private + * @method PIXI.WebGLGraphics.quadraticBezierCurve + * @param fromX {Number} Origin point x + * @param fromY {Number} Origin point x + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Array(Number)} + */ +PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) { + + var xa, + ya, + xb, + yb, + x, + y, + n = 20, + points = []; + + function getPt(n1 , n2, perc) { + var diff = n2 - n1; + + return n1 + ( diff * perc ); + } + + var j = 0; + for (var i = 0; i <= n; i++ ) + { + j = i / n; + + // The Green Line + xa = getPt( fromX , cpX , j ); + ya = getPt( fromY , cpY , j ); + xb = getPt( cpX , toX , j ); + yb = getPt( cpY , toY , j ); + + // The Black Dot + x = getPt( xa , xb , j ); + y = getPt( ya , yb , j ); + + points.push(x, y); + } + return points; +}; + +/** + * Builds a circle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildCircle + * @param graphicsData {Graphics} The graphics object to draw + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData) +{ + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + + // TODO - bit hacky?? + if (graphicsData.type === Phaser.CIRCLE) + { + width = circleData.radius; + height = circleData.radius; + } + else + { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = 40; + var seg = (Math.PI * 2) / totalSegs ; + + var i = 0; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; i < totalSegs + 1 ; i++) + { + verts.push(x,y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos-1); + } + + if(graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (i = 0; i < totalSegs + 1; i++) + { + graphicsData.points.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height); + } + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Builds a line to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildLine + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData) +{ + // TODO OPTIMISE! + var i = 0; + var points = graphicsData.points; + if(points.length === 0)return; + + // if the line width is an odd number add 0.5 to align to a whole pixel + if(graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) { + points[i] += 0.5; + } + } + + // get first and last point.. figure out the middle! + var firstPoint = new PIXI.Point( points[0], points[1] ); + var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + // if the first point is the last point - gonna have issues :) + if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length/6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var px, py, p1x, p1y, p2x, p2y, p3x, p3y; + var perpx, perpy, perp2x, perp2y, perp3x, perp3y; + var a1, b1, c1, a2, b2, c2; + var denom, pdist, dist; + + p1x = points[0]; + p1y = points[1]; + + p2x = points[2]; + p2y = points[3]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx , p1y - perpy, + r, g, b, alpha); + + verts.push(p1x + perpx , p1y + perpy, + r, g, b, alpha); + + for (i = 1; i < length-1; i++) + { + p1x = points[(i-1)*2]; + p1y = points[(i-1)*2 + 1]; + + p2x = points[(i)*2]; + p2y = points[(i)*2 + 1]; + + p3x = points[(i+1)*2]; + p3y = points[(i+1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + a1 = (-perpy + p1y) - (-perpy + p2y); + b1 = (-perpx + p2x) - (-perpx + p1x); + c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + a2 = (-perp2y + p3y) - (-perp2y + p2y); + b2 = (-perp2x + p2x) - (-perp2x + p3x); + c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + denom = a1*b2 - a2*b1; + + if(Math.abs(denom) < 0.1 ) + { + + denom+=10.1; + verts.push(p2x - perpx , p2y - perpy, + r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy, + r, g, b, alpha); + + continue; + } + + px = (b1*c2 - b2*c1)/denom; + py = (a2*c1 - a1*c2)/denom; + + + pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); + + + if(pdist > 140 * 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 < indexCount; i++) + { + indices.push(indexStart++); + } + + indices.push(indexStart-1); +}; + +/** + * Builds a complex polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildComplexPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData) +{ + //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. + var points = graphicsData.points.slice(); + if(points.length < 6)return; + + // get first and last point.. figure out the middle! + var indices = webGLData.indices; + webGLData.points = points; + webGLData.alpha = graphicsData.fillAlpha; + webGLData.color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + + /* + calclate the bounds.. + */ + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + var x,y; + + // get size.. + for (var i = 0; i < points.length; i+=2) + { + x = points[i]; + y = points[i+1]; + + minX = x < minX ? x : minX; + maxX = x > maxX ? x : maxX; + + minY = y < minY ? y : minY; + maxY = y > maxY ? y : maxY; + } + + // add a quad to the end cos there is no point making another buffer! + points.push(minX, minY, + maxX, minY, + maxX, maxY, + minX, maxY); + + // push a quad onto the end.. + + //TODO - this aint needed! + var length = points.length / 2; + for (i = 0; i < length; i++) + { + indices.push( i ); + } + +}; + +/** + * Builds a polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData) +{ + var points = graphicsData.points; + + if(points.length < 6)return; + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = Phaser.EarCut.Triangulate(points, null, 2); + + if(!triangles)return false; + + var vertPos = verts.length / 6; + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i] + vertPos); + indices.push(triangles[i+1] + vertPos); + indices.push(triangles[i+2] +vertPos); + indices.push(triangles[i+2] + vertPos); + } + + for (i = 0; i < length; i++) + { + verts.push(points[i * 2], points[i * 2 + 1], + r, g, b, alpha); + } + + return true; +}; + +PIXI.WebGLGraphics.graphicsDataPool = []; + +/** + * @class WebGLGraphicsData + * @private + * @static + */ +PIXI.WebGLGraphicsData = function(gl) +{ + this.gl = gl; + + //TODO does this need to be split before uploding?? + this.color = [0,0,0]; // color split! + this.points = []; + this.indices = []; + this.buffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + this.mode = 1; + this.alpha = 1; + this.dirty = true; +}; + +/** + * @method PIXI.WebGLGraphics.reset + */ +PIXI.WebGLGraphicsData.prototype.reset = function() +{ + this.points = []; + this.indices = []; +}; + +/** + * @method PIXI.WebGLGraphics.upload + */ +PIXI.WebGLGraphicsData.prototype.upload = function() +{ + var gl = this.gl; + +// this.lastIndex = graphics.graphicsData.length; + this.glPoints = new Float32Array(this.points); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW); + + this.glIndicies = new Uint16Array(this.indices); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW); + + this.dirty = false; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + +/** + * A set of functions used by the canvas renderer to draw the primitive graphics data. + * + * @class PIXI.CanvasGraphics + * @static + */ +PIXI.CanvasGraphics = function() +{ +}; + +/** + * Renders a {@link Phaser.Graphics} object to a canvas. + * + * @method PIXI.CanvasGraphics.renderGraphics + * @static + * @param graphics {Graphics} the actual graphics object to render + * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas + */ +PIXI.CanvasGraphics.renderGraphics = function(graphics, context) +{ + var worldAlpha = graphics.worldAlpha; + + if (graphics.dirty) + { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === Phaser.POLYGON) + { + context.beginPath(); + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (shape.closed) + { + context.lineTo(points[0], points[1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.RECTANGLE) + { + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ELLIPSE) + { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + context.beginPath(); + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + +}; + +/** + * Renders a graphics mask + * + * @static + * @private + * @method PIXI.CanvasGraphics.renderGraphicsMask + * @param graphics {Graphics} the graphics which will be used as a mask + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + */ +PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context) +{ + var len = graphics.graphicsData.length; + + if (len === 0) + { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === Phaser.POLYGON) + { + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + } + else if (data.type === Phaser.RECTANGLE) + { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } + else if (data.type === Phaser.ELLIPSE) + { + + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } +}; + +PIXI.CanvasGraphics.updateGraphicsTint = function(graphics) +{ + if (graphics.tint === 0xFFFFFF) + { + return; + } + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF)/ 255; + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255); + data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255); + + } + +}; + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + * @param lineWidth {number} the width of the line to draw + * @param lineColor {number} the color of the line to draw + * @param lineAlpha {number} the alpha of the line to draw + * @param fillColor {number} the color of the fill + * @param fillAlpha {number} the alpha of the fill + * @param fill {boolean} whether or not the shape is filled with a colour + * @param shape {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + +Phaser.GraphicsData = function (lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { + + /* + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /* + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /* + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /* + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /* + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /* + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /* + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /* + * @member {boolean} whether or not the shape is filled with a color + */ + this.fill = fill; + + /* + * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + this.shape = shape; + + /* + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + +}; + +Phaser.GraphicsData.prototype.constructor = Phaser.GraphicsData; + +/** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {GraphicsData} + */ +Phaser.GraphicsData.prototype.clone = function () { + + return new Phaser.GraphicsData( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.fill, + this.shape + ); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, +* Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will +* be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: +* +* ```javascript +* graphics.beginFill(0xff0000); +* graphics.drawCircle(50, 50, 100); +* graphics.endFill(); +* ``` +* +* This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. +* +* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or +* WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the +* graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. +* +* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help +* performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. +* You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then +* you should avoid doing this, as it will constantly generate new textures, which will consume memory. +* +* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful +* in their complexity and quantity of them in your game. +* +* @class Phaser.Graphics +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - X position of the new graphics object. +* @param {number} [y=0] - Y position of the new graphics object. +*/ +Phaser.Graphics = function (game, x, y) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.GRAPHICS; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value. + * @private + */ + this.anchor = new Phaser.Point(); + + PIXI.DisplayObjectContainer.call(this); + + this.renderable = true; + + /** + * The alpha value used when filling the Graphics object. + * + * @property fillAlpha + * @type Number + */ + this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @property lineWidth + * @type Number + */ + this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @property lineColor + * @type String + * @default 0 + */ + this.lineColor = 0; + + /** + * Graphics data + * + * @property graphicsData + * @type Array + * @private + */ + this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF (Phaser.Color.WHITE) to reset the tint. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * Current path + * + * @property currentPath + * @type Object + * @private + */ + this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @property _webGL + * @type Array + * @private + */ + this._webGL = []; + + /** + * Whether this shape is being used as a mask. + * + * @property isMask + * @type Boolean + */ + this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @property boundsPadding + * @type Number + */ + this.boundsPadding = 0; + + this._localBounds = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property dirty + * @type Boolean + * @private + */ + this.dirty = true; + + /** + * Used to detect if the bounds have been invalidated, by this Graphics being cleared or drawn to. + * If this is set to true then the updateLocalBounds is called once in the postUpdate method. + * + * @property _boundsDirty + * @type Boolean + * @private + */ + this._boundsDirty = false; + + /** + * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property webGLDirty + * @type Boolean + * @private + */ + this.webGLDirty = false; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @property cachedSpriteDirty + * @type Boolean + * @private + */ + this.cachedSpriteDirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.Graphics.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Graphics.prototype.constructor = Phaser.Graphics; + +Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Graphics#preUpdate +*/ +Phaser.Graphics.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World +* +* @method Phaser.Graphics#postUpdate +*/ +Phaser.Graphics.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this._boundsDirty) + { + this.updateLocalBounds(); + this._boundsDirty = false; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Destroy this Graphics instance. +* +* @method Phaser.Graphics#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Graphics.prototype.destroy = function (destroyChildren) { + + this.clear(); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Draws a single {@link Phaser.Polygon} triangle from a {@link Phaser.Point} array +* +* @method Phaser.Graphics#drawTriangle +* @param {Array} points - An array of Phaser.Points that make up the three vertices of this triangle +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangle = function (points, cull) { + + if (cull === undefined) { cull = false; } + + var triangle = new Phaser.Polygon(points); + + if (cull) + { + var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y); + var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y); + var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y); + var faceNormal = cb.cross(ab); + + if (cameraToFace.dot(faceNormal) > 0) + { + this.drawPolygon(triangle); + } + } + else + { + this.drawPolygon(triangle); + } + +}; + +/** +* Draws {@link Phaser.Polygon} triangles +* +* @method Phaser.Graphics#drawTriangles +* @param {Array|Array} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles +* @param {Array} [indices=null] - An array of numbers that describe what order to draw the vertices in +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) { + + if (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 < vertices.length / 3; i++) + { + this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull); + } + } + else + { + for (i = 0; i < vertices.length / 6; i++) + { + point1.x = vertices[i * 6 + 0]; + point1.y = vertices[i * 6 + 1]; + point2.x = vertices[i * 6 + 2]; + point2.y = vertices[i * 6 + 3]; + point3.x = vertices[i * 6 + 4]; + point3.y = vertices[i * 6 + 5]; + this.drawTriangle([point1, point2, point3], cull); + } + } + } + else + { + if (vertices[0] instanceof Phaser.Point) + { + for (i = 0; i < indices.length /3; i++) + { + points.push(vertices[indices[i * 3 ]]); + points.push(vertices[indices[i * 3 + 1]]); + points.push(vertices[indices[i * 3 + 2]]); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + else + { + for (i = 0; i < indices.length; i++) + { + point1.x = vertices[indices[i] * 2]; + point1.y = vertices[indices[i] * 2 + 1]; + points.push(point1.copyTo({})); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + } +}; + +/** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. + * + * @method Phaser.Graphics#lineStyle + * @param lineWidth {Number} width of the line to draw, will update the objects stored style + * @param color {Number} color of the line to draw, will update the objects stored style + * @param alpha {Number} alpha of the line to draw, will update the objects stored style + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { + + this.lineWidth = lineWidth || 0; + this.lineColor = color || 0; + this.lineAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { + // halfway through a line? start a new one! + this.drawShape(new Phaser.Polygon(this.currentPath.shape.points.slice(-2))); + } + else + { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + +}; + +/** + * Moves the current drawing position to x, y. + * + * @method Phaser.Graphics#moveTo + * @param x {Number} the X coordinate to move to + * @param y {Number} the Y coordinate to move to + * @return {Graphics} + */ +Phaser.Graphics.prototype.moveTo = function (x, y) { + + this.drawShape(new Phaser.Polygon([ x, y ])); + + return this; + +}; + +/** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @method Phaser.Graphics#lineTo + * @param x {Number} the X coordinate to draw to + * @param y {Number} the Y coordinate to draw to + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineTo = function (x, y) { + + if (!this.currentPath) + { + this.moveTo(0, 0); + } + + this.currentPath.shape.points.push(x, y); + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @method Phaser.Graphics#quadraticCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [ 0, 0 ]; + } + } + else + { + this.moveTo(0,0); + } + + var xa, + ya, + n = 20, + points = this.currentPath.shape.points; + + if (points.length === 0) + { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var j = 0; + for (var i = 1; i <= n; ++i) + { + j = i / n; + + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + + points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), + ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a bezier curve and then draws it. + * + * @method Phaser.Graphics#bezierCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param cpX2 {Number} Second Control point x + * @param cpY2 {Number} Second Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + var n = 20, + dt, + dt2, + dt3, + t2, + t3, + points = this.currentPath.shape.points; + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + var j = 0; + + for (var i = 1; i <= n; ++i) + { + j = i / n; + + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, + dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @method Phaser.Graphics#arcTo + * @param x1 {Number} The x-coordinate of the beginning of the arc + * @param y1 {Number} The y-coordinate of the beginning of the arc + * @param x2 {Number} The x-coordinate of the end of the arc + * @param y2 {Number} The y-coordinate of the end of the arc + * @param radius {Number} The radius of the arc + * @return {Graphics} + */ +Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points.push(x1, y1); + } + } + else + { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points, + fromX = points[points.length-2], + fromY = points[points.length-1], + a1 = fromY - y1, + b1 = fromX - x1, + a2 = y2 - y1, + b2 = x2 - x1, + mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { + points.push(x1, y1); + } + } + else + { + var dd = a1 * a1 + b1 * b1, + cc = a2 * a2 + b2 * b2, + tt = a1 * a2 + b1 * b2, + k1 = radius * Math.sqrt(dd) / mm, + k2 = radius * Math.sqrt(cc) / mm, + j1 = k1 * tt / dd, + j2 = k2 * tt / cc, + cx = k1 * b2 + k2 * b1, + cy = k1 * a2 + k2 * a1, + px = b1 * (k2 + j1), + py = a1 * (k2 + j1), + qx = b2 * (k1 + j2), + qy = a2 * (k1 + j2), + startAngle = Math.atan2(py - cy, px - cx), + endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @method Phaser.Graphics#arc + * @param cx {Number} The x-coordinate of the center of the circle + * @param cy {Number} The y-coordinate of the center of the circle + * @param radius {Number} The radius of the circle + * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) + * @param endAngle {Number} The ending angle, in radians + * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. + * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. + * @return {Graphics} + */ +Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise, segments) { + + // If we do this we can never draw a full circle + if (startAngle === endAngle) + { + return this; + } + + if (anticlockwise === undefined) { anticlockwise = false; } + if (segments === undefined) { segments = 40; } + + if (!anticlockwise && endAngle <= startAngle) + { + endAngle += Math.PI * 2; + } + else if (anticlockwise && startAngle <= endAngle) + { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments; + + // Sweep check - moved here because we don't want to do the moveTo below if the arc fails + if (sweep === 0) + { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (anticlockwise && this.filling) + { + this.moveTo(cx, cy); + } + else + { + this.moveTo(startX, startY); + } + + // currentPath will always exist after calling a moveTo + var points = this.currentPath.shape.points; + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = (segMinus % 1) / segMinus; + + for (var i = 0; i <= segMinus; i++) + { + var real = i + remainder * i; + + var angle = ((theta) + startAngle + (theta2 * real)); + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, + ( (cTheta * -s) + (sTheta * c) ) * radius + cy); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @method Phaser.Graphics#beginFill + * @param color {Number} the color of the fill + * @param alpha {Number} the alpha of the fill + * @return {Graphics} + */ +Phaser.Graphics.prototype.beginFill = function (color, alpha) { + + this.filling = true; + this.fillColor = color || 0; + this.fillAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + +}; + +/** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @method Phaser.Graphics#endFill + * @return {Graphics} + */ +Phaser.Graphics.prototype.endFill = function () { + + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRect + * + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawRect = function (x, y, width, height) { + + this.drawShape(new Phaser.Rectangle(x, y, width, height)); + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRoundedRect + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. + */ +Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + + this.drawShape(new Phaser.RoundedRectangle(x, y, width, height, radius)); + + return this; + +}; + +/** + * Draws a circle. + * + * @method Phaser.Graphics#drawCircle + * @param x {Number} The X coordinate of the center of the circle + * @param y {Number} The Y coordinate of the center of the circle + * @param diameter {Number} The diameter of the circle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) { + + this.drawShape(new Phaser.Circle(x, y, diameter)); + + return this; + +}; + +/** + * Draws an ellipse. + * + * @method Phaser.Graphics#drawEllipse + * @param x {Number} The X coordinate of the center of the ellipse + * @param y {Number} The Y coordinate of the center of the ellipse + * @param width {Number} The half width of the ellipse + * @param height {Number} The half height of the ellipse + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawEllipse = function (x, y, width, height) { + + this.drawShape(new Phaser.Ellipse(x, y, width, height)); + + return this; + +}; + +/** + * Draws a polygon using the given path. + * + * @method Phaser.Graphics#drawPolygon + * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawPolygon = function (path) { + + if (path instanceof Phaser.Polygon) + { + path = path.points; + } + + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) + { + points[i] = arguments[i]; + } + } + + this.drawShape(new Phaser.Polygon(points)); + + return this; + +}; + +/** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @method Phaser.Graphics#clear + * @return {Graphics} + */ +Phaser.Graphics.prototype.clear = function () { + + this.lineWidth = 0; + this.filling = false; + + this.dirty = true; + this._boundsDirty = true; + this.clearDirty = true; + this.graphicsData = []; + + this.updateLocalBounds(); + + return this; + +}; + +/** + * Useful function that returns a texture of the graphics object that can then be used to create sprites + * This can be quite useful if your geometry is complicated and needs to be reused multiple times. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * @method Phaser.Graphics#generateTexture + * @param [resolution=1] {Number} The resolution of the texture being generated + * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts + * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0) + * @return {Texture} a texture of the graphics object + */ +Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, padding) { + + if (resolution === undefined) { resolution = 1; } + if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; } + if (padding === undefined) { padding = 0; } + + var bounds = this.getBounds(); + + bounds.width += padding; + bounds.height += padding; + + var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution); + + var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + + canvasBuffer.context.scale(resolution, resolution); + + canvasBuffer.context.translate(-bounds.x, -bounds.y); + + PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context); + + return texture; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Graphics#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderWebGL = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture on the gpu too! + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.worldAlpha = this.worldAlpha; + + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + + return; + } + else + { + renderSession.spriteBatch.stop(); + renderSession.blendModeManager.setBlendMode(this.blendMode); + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + if (this._filters) + { + renderSession.filterManager.pushFilter(this._filterBlock); + } + + // check blend mode + if (this.blendMode !== renderSession.spriteBatch.currentBlendMode) + { + renderSession.spriteBatch.currentBlendMode = this.blendMode; + var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode]; + renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + // check if the webgl graphic needs to be updated + if (this.webGLDirty) + { + this.dirty = true; + this.webGLDirty = false; + } + + PIXI.WebGLGraphics.renderGraphics(this, renderSession); + + // only render if it has children! + if (this.children.length) + { + renderSession.spriteBatch.start(); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + } + + if (this._filters) + { + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + renderSession.maskManager.popMask(this.mask, renderSession); + } + + renderSession.drawCount++; + + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method Phaser.Graphics#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderCanvas = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) + { + this.dirty = true; + this._prevTint = this.tint; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.alpha = this.alpha; + + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + + return; + } + else + { + var context = renderSession.context; + var transform = this.worldTransform; + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + var resolution = renderSession.resolution; + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + tx, + ty); + + PIXI.CanvasGraphics.renderGraphics(this, context); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + } + +}; + +/** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @method Phaser.Graphics#getBounds + * @return {Rectangle} the rectangular bounding area + */ +Phaser.Graphics.prototype.getBounds = function (matrix) { + + if (this._currentBounds) + { + return this._currentBounds; + } + + // Return an empty object if the item is a mask! + if (!this.renderable) + { + return Phaser.EmptyRectangle; + } + + if (this.dirty) + { + this.updateLocalBounds(); + this.webGLDirty = true; + this.cachedSpriteDirty = true; + this.dirty = false; + } + + var bounds = this._localBounds; + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = x1; + var maxY = y1; + + var minX = x1; + var minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + + this._bounds.x = minX; + this._bounds.width = maxX - minX; + + this._bounds.y = minY; + this._bounds.height = maxY - minY; + + this._currentBounds = this._bounds; + + return this._currentBounds; + +}; + +/** + * Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration. + * + * @method Phaser.Graphics#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +Phaser.Graphics.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Tests if a point is inside this graphics object +* +* @param point {Point} the point to test +* @return {boolean} the result of the test +*/ +Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) { + + if (tempPoint === undefined) { tempPoint = new Phaser.Point(); } + + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; i++) + { + var data = graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // only deal with fills.. + if (data.shape) + { + if (data.shape.contains(tempPoint.x, tempPoint.y)) + { + return true; + } + } + } + + return false; + +}; + +/** + * Update the bounds of the object + * + * @method Phaser.Graphics#updateLocalBounds + */ +Phaser.Graphics.prototype.updateLocalBounds = function () { + + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) + { + var shape, points, x, y, w, h; + + for (var i = 0; i < this.graphicsData.length; i++) + { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + shape = data.shape; + + if (type === Phaser.RECTANGLE || type === Phaser.ROUNDEDRECTANGLE) + { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.CIRCLE) + { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.ELLIPSE) + { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else + { + // POLY - assumes points are sequential, not Point objects + points = shape.points; + + for (var j = 0; j < points.length; j++) + { + if (points[j] instanceof Phaser.Point) + { + x = points[j].x; + y = points[j].y; + } + else + { + x = points[j]; + y = points[j + 1]; + + if (j < points.length - 1) + { + j++; + } + } + + minX = x - lineWidth < minX ? x - lineWidth : minX; + maxX = x + lineWidth > maxX ? x + lineWidth : maxX; + + minY = y - lineWidth < minY ? y - lineWidth : minY; + maxY = y + lineWidth > maxY ? y + lineWidth : maxY; + } + } + } + } + else + { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.x = minX - padding; + this._localBounds.width = (maxX - minX) + padding * 2; + + this._localBounds.y = minY - padding; + this._localBounds.height = (maxY - minY) + padding * 2; + +}; + +/** + * Generates the cached sprite when the sprite has cacheAsBitmap = true + * + * @method Phaser.Graphics#_generateCachedSprite + * @private + */ +Phaser.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); + } + + // leverage the anchor to account for the offset of the element + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + // this._cachedSprite.buffer.context.save(); + this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y); + + // make sure we set the alpha of the graphics to 1 for the render.. + this.worldAlpha = 1; + + // now render the graphic.. + PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context); + this._cachedSprite.alpha = this.alpha; + +}; + +/** + * Updates texture size based on canvas size + * + * @method Phaser.Graphics#updateCachedSpriteTexture + * @private + */ +Phaser.Graphics.prototype.updateCachedSpriteTexture = function () { + + var cachedSprite = this._cachedSprite; + var texture = cachedSprite.texture; + var canvas = cachedSprite.buffer.canvas; + + texture.baseTexture.width = canvas.width; + texture.baseTexture.height = canvas.height; + texture.crop.width = texture.frame.width = canvas.width; + texture.crop.height = texture.frame.height = canvas.height; + + cachedSprite._width = canvas.width; + cachedSprite._height = canvas.height; + + // update the dirty base textures + texture.baseTexture.dirty(); + +}; + +/** + * Destroys a previous cached sprite. + * + * @method Phaser.Graphics#destroyCachedSprite + */ +Phaser.Graphics.prototype.destroyCachedSprite = function () { + + this._cachedSprite.texture.destroy(true); + this._cachedSprite = null; + +}; + +/** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @method Phaser.Graphics#drawShape + * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. + * @return {GraphicsData} The generated GraphicsData object. + */ +Phaser.Graphics.prototype.drawShape = function (shape) { + + if (this.currentPath) + { + // check current path! + if (this.currentPath.shape.points.length <= 2) + { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + // Handle mixed-type polygons + if (shape instanceof Phaser.Polygon) + { + shape = shape.clone(); + shape.flatten(); + } + + var data = new Phaser.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === Phaser.POLYGON) + { + data.shape.closed = this.filling; + this.currentPath = data; + } + + this.dirty = true; + this._boundsDirty = true; + + return data; + +}; + +/** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory. + * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas. + * This is not recommended if you are constantly redrawing the graphics element. + * + * @property cacheAsBitmap + * @type Boolean + * @default false + * @private + */ +Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + this._cacheAsBitmap = value; + + if (this._cacheAsBitmap) + { + this._generateCachedSprite(); + } + else + { + this.destroyCachedSprite(); + } + + this.dirty = true; + this.webGLDirty = true; + + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and +* render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. +* +* @class Phaser.RenderTexture +* @constructor +* @extends PIXI.Texture +* @param {Phaser.Game} game - Current game instance. +* @param {number} [width=100] - The width of the render texture. +* @param {number} [height=100] - The height of the render texture. +* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there. +* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts. +* @param {number} [resolution=1] - The resolution of the texture being generated. +*/ +Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution, renderer, textureUnit) { + + if (width === undefined) { width = 100; } + if (height === undefined) { height = 100; } + if (key === undefined) { key = ''; } + if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; } + if (resolution === undefined) { resolution = 1; } + if (renderer === undefined) { renderer = PIXI.defaultRenderer; } + if (textureUnit === undefined) { textureUnit = 0; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the RenderTexture in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RENDERTEXTURE; + + /** + * @property {Phaser.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture. + * @private + */ + this._tempMatrix = new Phaser.Matrix(); + + this.width = width; + this.height = height; + this.resolution = resolution; + + this.frame = new Phaser.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); + + this.crop = this.frame.clone(); + + /** + * The base texture object that this texture uses + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = new PIXI.BaseTexture(); + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + this.baseTexture._glTextures = []; + this.baseTexture.resolution = this.resolution; + + this.baseTexture.scaleMode = scaleMode; + + this.baseTexture.hasLoaded = true; + + PIXI.Texture.call(this, this.baseTexture, this.frame.clone()); + + /** + * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. + * + * @property renderer + * @type CanvasRenderer|WebGLRenderer + */ + this.renderer = renderer; + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + this.baseTexture.textureIndex = textureUnit; + this.baseTexture._dirty[gl.id] = false; + + this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode, textureUnit); + this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; + + this.projection = new Phaser.Point(this.width * 0.5, -this.height * 0.5); + } + else + { + this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution); + this.baseTexture.source = this.textureBuffer.canvas; + } + + /** + * @property valid + * @type Boolean + */ + this.valid = true; + + this.tempMatrix = new Phaser.Matrix(); + + this._updateUvs(); + +}; + +Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype); +Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it takes into account scale and rotation. +* +* If you don't want those then use RenderTexture.renderRawXY instead. +* +* @method Phaser.RenderTexture.prototype.renderXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) { + + displayObject.updateTransform(); + + this._tempMatrix.copyFrom(displayObject.worldTransform); + this._tempMatrix.tx = x; + this._tempMatrix.ty = y; + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it doesn't take into account scale, rotation or translation. +* +* If you need those then use RenderTexture.renderXY instead. +* +* @method Phaser.RenderTexture.prototype.renderRawXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) { + + this._tempMatrix.identity().translate(x, y); + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture. +* +* In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. +* This is now a Matrix allowing you much more control over how the Display Object is rendered. +* If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. +* +* If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either +* pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. +* +* @method Phaser.RenderTexture.prototype.render +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) { + + if (matrix === undefined || matrix === null) + { + this._tempMatrix.copyFrom(displayObject.worldTransform); + } + else + { + this._tempMatrix.copyFrom(matrix); + } + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* Resizes the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.resize +* @param {number} width - The width to resize to. +* @param {number} height - The height to resize to. +* @param {boolean} updateBase - Should the baseTexture.width and height values be resized as well? +*/ +Phaser.RenderTexture.prototype.resize = function (width, height, updateBase) { + + if (width === this.width && height === this.height) + { + return; + } + + this.valid = (width > 0 && height > 0); + + this.width = width; + this.height = height; + this.frame.width = this.crop.width = width * this.resolution; + this.frame.height = this.crop.height = height * this.resolution; + + if (updateBase) + { + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.projection.x = this.width / 2; + this.projection.y = -this.height / 2; + } + + if (!this.valid) + { + return; + } + + this.textureBuffer.resize(this.width, this.height); + +}; + +/** +* Clears the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.clear +*/ +Phaser.RenderTexture.prototype.clear = function () { + + if (!this.valid) + { + return; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + } + + this.textureBuffer.clear(); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderWebGL +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +* @private +*/ +Phaser.RenderTexture.prototype._renderWebGL = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + wt.translate(0, this.projection.y * 2); + + if (matrix) + { + wt.append(matrix); + } + + wt.scale(1, -1); + + // Time to update all the children of the displayObject with the new matrix. + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + // Time for the webGL fun stuff! + var gl = this.renderer.gl; + + gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + + if (clear) + { + this.textureBuffer.clear(); + } + + this.renderer.spriteBatch.dirty = true; + + this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix); + + this.renderer.spriteBatch.dirty = true; + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderCanvas +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +*/ +Phaser.RenderTexture.prototype._renderCanvas = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + + if (matrix) + { + wt.append(matrix); + } + + // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!) + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + if (clear) + { + this.textureBuffer.clear(); + } + + var realResolution = this.renderer.resolution; + + this.renderer.resolution = this.resolution; + + this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix); + + this.renderer.resolution = realResolution; + +}; + +/** +* Will return a HTML Image of the texture +* +* @method Phaser.RenderTexture.prototype.getImage +* @return {Image} +*/ +Phaser.RenderTexture.prototype.getImage = function () { + + var image = new Image(); + image.src = this.getBase64(); + + return image; + +}; + +/** +* Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. +* +* @method Phaser.RenderTexture.prototype.getBase64 +* @return {String} A base64 encoded string of the texture. +*/ +Phaser.RenderTexture.prototype.getBase64 = function () { + + return this.getCanvas().toDataURL(); + +}; + +/** +* Creates a Canvas element, renders this RenderTexture to it and then returns it. +* +* @method Phaser.RenderTexture.prototype.getCanvas +* @return {HTMLCanvasElement} A Canvas element with the texture rendered on. +*/ +Phaser.RenderTexture.prototype.getCanvas = function () { + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + var width = this.textureBuffer.width; + var height = this.textureBuffer.height; + + var webGLPixels = new Uint8Array(4 * width * height); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + var tempCanvas = new PIXI.CanvasBuffer(width, height); + var canvasData = tempCanvas.context.getImageData(0, 0, width, height); + canvasData.data.set(webGLPixels); + + tempCanvas.context.putImageData(canvasData, 0, 0); + + return tempCanvas.canvas; + } + else + { + return this.textureBuffer.canvas; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new game object for displaying Text. +* +* This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. +* Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. +* +* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers. +* +* @class Phaser.Text +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {number} x - X position of the new text object. +* @param {number} y - Y position of the new text object. +* @param {string} text - The actual text that will be written. +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +*/ +Phaser.Text = function (game, x, y, text, style) { + + x = x || 0; + y = y || 0; + + if (text === undefined || text === null) + { + text = ''; + } + else + { + text = text.toString(); + } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.TEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. + * @property {Phaser.Point} padding + */ + this.padding = new Phaser.Point(); + + /** + * The textBounds property allows you to specify a rectangular region upon which text alignment is based. + * See `Text.setTextBounds` for more details. + * @property {Phaser.Rectangle} textBounds + * @readOnly + */ + this.textBounds = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. + */ + this.canvas = Phaser.CanvasPool.create(this); + + /** + * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. + */ + this.context = this.canvas.getContext('2d'); + + /** + * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}. + */ + this.colors = []; + + /** + * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}. + */ + this.strokeColors = []; + + /** + * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}. + */ + this.fontStyles = []; + + /** + * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}. + */ + this.fontWeights = []; + + /** + * Should the linePositionX and Y values be automatically rounded before rendering the Text? + * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. + * @property {boolean} autoRound + * @default + */ + this.autoRound = false; + + /** + * Will this Text object use Basic or Advanced Word Wrapping? + * + * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. + * White space is condensed (e.g., consecutive spaces are replaced with one). + * Lines are trimmed of white space before processing. + * + * It throws an error if wordWrapWidth is less than a single character. + * @property {boolean} useAdvancedWrap + * @default + */ + this.useAdvancedWrap = false; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + * @property {Object} splitRegExp + */ + this.splitRegExp = /(?:\r\n|\r|\n)/; + + + /** The maximum number of characters that can be set. + * @property {number} characterLimitSize + */ + this.characterLimitSize = -1; + + /** The suffix that is applied to truncated text that is longer than the + * characterLimitSize. + * @property {string} characterLimitSuffix + */ + this.characterLimitSuffix = ''; + + /** + * @property {number} _res - Internal canvas resolution var. + * @private + */ + this._res = game.renderer.resolution; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text; + + /** + * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`. + * @private + */ + this._fontComponents = null; + + /** + * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. + * @private + */ + this._lineSpacing = 0; + + /** + * @property {number} _charCount - Internal character counter used by the text coloring. + * @private + */ + this._charCount = 0; + + /** + * @property {number} _width - Internal width var. + * @private + */ + this._width = 0; + + /** + * @property {number} _height - Internal height var. + * @private + */ + this._height = 0; + + Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas)); + + /** + * @property {object} style + * @private + */ + this.style = {}; + + this.setStyle(style || {}); + + if (text !== '') + { + this.updateText(); + } + +}; + +Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Text.prototype.constructor = Phaser.Text; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Text#preUpdate +* @protected +*/ +Phaser.Text.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override this function to handle any special update requirements. +* +* @method Phaser.Text#update +* @protected +*/ +Phaser.Text.prototype.update = function() { + +}; + +/** +* Destroy this Text object, removing it from the group it belongs to. +* +* @method Phaser.Text#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Text.prototype.destroy = function (destroyChildren) { + + this.texture.destroy(true); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. +* The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. +* The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. +* To remove a shadow already in place you can call this method with no parameters set. +* +* @method Phaser.Text#setShadow +* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +* @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. +* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +* @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set). +* @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; } + if (blur === undefined) { blur = 0; } + if (shadowStroke === undefined) { shadowStroke = true; } + if (shadowFill === undefined) { shadowFill = true; } + + this.style.shadowOffsetX = x; + this.style.shadowOffsetY = y; + this.style.shadowColor = color; + this.style.shadowBlur = blur; + this.style.shadowStroke = shadowStroke; + this.style.shadowFill = shadowFill; + this.dirty = true; + + return this; + +}; + +/** +* Set the style of the text by passing a single style object to it. +* +* @method Phaser.Text#setStyle +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +* @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setStyle = function (style, update) { + + if (update === undefined) { update = false; } + + var newStyle = Object.assign({}, style); + newStyle.font = style.font || 'bold 20pt Arial'; + newStyle.backgroundColor = style.backgroundColor || null; + newStyle.fill = style.fill || 'black'; + newStyle.align = (style.align || 'left').toLowerCase(); + newStyle.boundsAlignH = (style.boundsAlignH || 'left').toLowerCase(); + newStyle.boundsAlignV = (style.boundsAlignV || 'top').toLowerCase(); + newStyle.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136 + newStyle.strokeThickness = Number(style.strokeThickness) || 0; + newStyle.wordWrap = style.wordWrap || false; + newStyle.wordWrapWidth = style.wordWrapWidth || 100; + newStyle.maxLines = style.maxLines || 0; + newStyle.shadowOffsetX = style.shadowOffsetX || 0; + newStyle.shadowOffsetY = style.shadowOffsetY || 0; + newStyle.shadowColor = style.shadowColor || 'rgba(0,0,0,0)'; + newStyle.shadowBlur = style.shadowBlur || 0; + newStyle.tabs = style.tabs || 0; + + var components = this.fontToComponents(newStyle.font); + + if (newStyle.fontStyle) + { + components.fontStyle = newStyle.fontStyle; + } + + if (newStyle.fontVariant) + { + components.fontVariant = newStyle.fontVariant; + } + + if (newStyle.fontWeight) + { + components.fontWeight = newStyle.fontWeight; + } + + if (newStyle.fontSize) + { + if (typeof newStyle.fontSize === 'number') + { + newStyle.fontSize = newStyle.fontSize + 'px'; + } + + components.fontSize = newStyle.fontSize; + } + + this._fontComponents = components; + + newStyle.font = this.componentsToFont(this._fontComponents); + + this.style = newStyle; + this.dirty = true; + + if (update) + { + this.updateText(); + } + + return this; + +}; + +/** +* Renders text to the internal canvas. +* +* @method Phaser.Text#updateText +* @private +*/ +Phaser.Text.prototype.updateText = function () { + + this.texture.baseTexture.resolution = this._res; + + this.context.font = this.style.font; + + var outputText = this.text; + + if (this.characterLimitSize > -1 && this.characterLimitSize < outputText.length) { + outputText = this.text.substring(0, this.characterLimitSize) + this.characterLimitSuffix; + } + + if (this.style.wordWrap) + { + outputText = this.runWordWrap(this.text); + } + + // Split text into lines + var lines = outputText.split(this.splitRegExp); + + // Calculate text width + var tabs = this.style.tabs; + var lineWidths = []; + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this.style.font); + + var drawnLines = lines.length; + + if (this.style.maxLines > 0 && this.style.maxLines < lines.length) + { + drawnLines = this.style.maxLines; + } + + this._charCount = 0; + + for (var i = 0; i < drawnLines; i++) + { + if (tabs === 0) + { + // Simple layout (no tabs) + var lineWidth = this.style.strokeThickness + this.padding.x; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(lines[i]); + } + else + { + lineWidth += this.context.measureText(lines[i]).width; + } + + // Adjust for wrapped text + if (this.style.wordWrap) + { + lineWidth -= this.context.measureText(' ').width; + } + } + else + { + // Complex layout (tabs) + var line = lines[i].split(/(?:\t)/); + var lineWidth = this.padding.x + this.style.strokeThickness; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < line.length; c++) + { + var section = 0; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + section = this.measureLine(line[c]); + } + else + { + section = Math.ceil(this.context.measureText(line[c]).width); + } + + if (c > 0) + { + tab += tabs[c - 1]; + } + + lineWidth = tab + section; + } + } + else + { + for (var c = 0; c < line.length; c++) + { + // How far to the next tab? + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(line[c]); + } + else + { + lineWidth += Math.ceil(this.context.measureText(line[c]).width); + } + + var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth; + + lineWidth += diff; + } + } + } + + lineWidths[i] = Math.ceil(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); + } + + this.canvas.width = maxLineWidth * this._res; + + // Calculate text height + var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y; + var height = lineHeight * drawnLines; + var lineSpacing = this._lineSpacing; + + if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight) + { + lineSpacing = -lineHeight; + } + + // Adjust for line spacing + if (lineSpacing !== 0) + { + height += (lineSpacing > 0) ? lineSpacing * lines.length : lineSpacing * (lines.length - 1); + } + + this.canvas.height = height * this._res; + + this.context.scale(this._res, this._res); + + if (navigator.isCocoonJS) + { + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + } + + if (this.style.backgroundColor) + { + this.context.fillStyle = this.style.backgroundColor; + this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); + } + + this.context.fillStyle = this.style.fill; + this.context.font = this.style.font; + this.context.strokeStyle = this.style.stroke; + this.context.textBaseline = 'alphabetic'; + + this.context.lineWidth = this.style.strokeThickness; + this.context.lineCap = 'round'; + this.context.lineJoin = 'round'; + + var linePositionX; + var linePositionY; + + this._charCount = 0; + + // Draw text line by line + for (i = 0; i < drawnLines; i++) + { + // Split the line by + + linePositionX = this.style.strokeThickness / 2; + linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (i > 0) + { + linePositionY += (lineSpacing * i); + } + + if (this.style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (this.style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (this.autoRound) + { + linePositionX = Math.round(linePositionX); + linePositionY = Math.round(linePositionY); + } + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + this.updateLine(lines[i], linePositionX, linePositionY); + } + else + { + if (this.style.stroke && this.style.strokeThickness) + { + this.updateShadow(this.style.shadowStroke); + + if (tabs === 0) + { + this.context.strokeText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, false); + } + } + + if (this.style.fill) + { + this.updateShadow(this.style.shadowFill); + + if (tabs === 0) + { + this.context.fillText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, true); + } + } + } + } + + this.updateTexture(); + + this.dirty = false; + +}; + +/** +* Renders a line of text that contains tab characters if Text.tab > 0. +* Called automatically by updateText. +* +* @method Phaser.Text#renderTabLine +* @private +* @param {string} line - The line of text to render. +* @param {integer} x - The x position to start rendering from. +* @param {integer} y - The y position to start rendering from. +* @param {boolean} fill - If true uses fillText, if false uses strokeText. +*/ +Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) { + + var text = line.split(/(?:\t)/); + var tabs = this.style.tabs; + var snap = 0; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < text.length; c++) + { + if (c > 0) + { + tab += tabs[c - 1]; + } + + snap = x + tab; + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + } + } + else + { + for (var c = 0; c < text.length; c++) + { + var section = Math.ceil(this.context.measureText(text[c]).width); + + // How far to the next tab? + snap = this.game.math.snapToCeil(x, tabs); + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + + x = snap + section; + } + } + +}; + +/** +* Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. +* This is called automatically by Text.updateText. +* +* @method Phaser.Text#updateShadow +* @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero. +*/ +Phaser.Text.prototype.updateShadow = function (state) { + + if (state) + { + this.context.shadowOffsetX = this.style.shadowOffsetX; + this.context.shadowOffsetY = this.style.shadowOffsetY; + this.context.shadowColor = this.style.shadowColor; + this.context.shadowBlur = this.style.shadowBlur; + } + else + { + this.context.shadowOffsetX = 0; + this.context.shadowOffsetY = 0; + this.context.shadowColor = 0; + this.context.shadowBlur = 0; + } + +}; + +/** +* Measures a line of text character by character taking into the account the specified character styles. +* +* @method Phaser.Text#measureLine +* @private +* @param {string} line - The line of text to measure. +* @return {integer} length of the line. +*/ +Phaser.Text.prototype.measureLine = function (line) { + + var lineLength = 0; + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + } + + lineLength += this.context.measureText(letter).width; + + this._charCount++; + } + + return Math.ceil(lineLength); +}; + +/** +* Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable. +* +* @method Phaser.Text#updateLine +* @private +*/ +Phaser.Text.prototype.updateLine = function (line, x, y) { + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + this.context.strokeText(letter, x, y); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + this.context.fillText(letter, x, y); + } + + x += this.context.measureText(letter).width; + + this._charCount++; + } + +}; + +/** +* Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. +* +* @method Phaser.Text#clearColors +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearColors = function () { + + this.colors = []; + this.strokeColors = []; + this.dirty = true; + + return this; + +}; + +/** +* Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. +* +* @method Phaser.Text#clearFontValues +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearFontValues = function () { + + this.fontStyles = []; + this.fontWeights = []; + this.dirty = true; + + return this; + +}; + +/** +* Set specific colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* If you wish to change the stroke color see addStrokeColor instead. +* +* @method Phaser.Text#addColor +* @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addColor = function (color, position) { + + this.colors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific stroke colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* This has no effect if stroke is disabled or has a thickness of 0. +* +* If you wish to change the text fill color see addColor instead. +* +* @method Phaser.Text#addStrokeColor +* @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addStrokeColor = function (color, position) { + + this.strokeColors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font styles for certain characters within the Text. +* +* It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. +* The position value is the index of the character in the Text string to start applying this font style to. +* Once set the font style remains in use until either another font style or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. +* +* If you wish to change the text font weight see addFontWeight instead. +* +* @method Phaser.Text#addFontStyle +* @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. +* @param {number} position - The index of the character in the string to start applying this font style value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontStyle = function (style, position) { + + this.fontStyles[position] = style; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font weights for certain characters within the Text. +* +* It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. +* The position value is the index of the character in the Text string to start applying this font weight to. +* Once set the font weight remains in use until either another font weight or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. +* +* If you wish to change the text font style see addFontStyle instead. +* +* @method Phaser.Text#addFontWeight +* @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. +* @param {number} position - The index of the character in the string to start applying this font weight value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontWeight = function (weight, position) { + + this.fontWeights[position] = weight; + this.dirty = true; + + return this; + +}; + +/** +* Runs the given text through the Text.runWordWrap function and returns +* the results as an array, where each element of the array corresponds to a wrapped +* line of text. +* +* Useful if you wish to control pagination on long pieces of content. +* +* @method Phaser.Text#precalculateWordWrap +* @param {string} text - The text for which the wrapping will be calculated. +* @return {array} An array of strings with the pieces of wrapped text. +*/ +Phaser.Text.prototype.precalculateWordWrap = function (text) { + + this.texture.baseTexture.resolution = this._res; + this.context.font = this.style.font; + + var wrappedLines = this.runWordWrap(text); + + return wrappedLines.split(/(?:\r\n|\r|\n)/); + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#runWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.runWordWrap = function (text) { + + if (this.useAdvancedWrap) + { + return this.advancedWordWrap(text); + } + else + { + return this.basicWordWrap(text); + } + +}; + +/** +* Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* White space is condensed (e.g., consecutive spaces are replaced with one). +* Lines are trimmed of white space before processing. +* Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character. +* +* @method Phaser.Text#advancedWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.advancedWordWrap = function (text) { + + var context = this.context; + var wordWrapWidth = this.style.wordWrapWidth; + + var output = ''; + + // (1) condense whitespace + // (2) split into lines + var lines = text + .replace(/ +/gi, ' ') + .split(/\r?\n/gi); + + var linesCount = lines.length; + + for (var i = 0; i < linesCount; i++) + { + var line = lines[i]; + var out = ''; + + // trim whitespace + line = line.replace(/^ *|\s*$/gi, ''); + + // if entire line is less than wordWrapWidth + // append the entire line and exit early + var lineWidth = context.measureText(line).width; + + if (lineWidth < wordWrapWidth) + { + output += line + '\n'; + continue; + } + + // otherwise, calculate new lines + var currentLineWidth = wordWrapWidth; + + // split into words + var words = line.split(' '); + + for (var j = 0; j < words.length; j++) + { + var word = words[j]; + var wordWithSpace = word + ' '; + var wordWidth = context.measureText(wordWithSpace).width; + + if (wordWidth > currentLineWidth) + { + // break word + if (j === 0) + { + // shave off letters from word until it's small enough + var newWord = wordWithSpace; + + while (newWord.length) + { + newWord = newWord.slice(0, -1); + wordWidth = context.measureText(newWord).width; + + if (wordWidth <= currentLineWidth) + { + break; + } + } + + // if wordWrapWidth is too small for even a single + // letter, shame user failure with a fatal error + if (!newWord.length) + { + throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); + } + + // replace current word in array with remainder + var secondPart = word.substr(newWord.length); + + words[j] = secondPart; + + // append first piece to output + out += newWord; + } + + // if existing word length is 0, don't include it + var offset = (words[j].length) ? j : j + 1; + + // collapse rest of sentence + var remainder = words.slice(offset).join(' ') + // remove any trailing white space + .replace(/[ \n]*$/gi, ''); + + // prepend remainder to next line + lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); + linesCount = lines.length; + + break; // processing on this line + + // append word with space to output + } + else + { + out += wordWithSpace; + currentLineWidth -= wordWidth; + } + } + + // append processed line to output + output += out.replace(/[ \n]*$/gi, '') + '\n'; + } + + // trim the end of the string + output = output.replace(/[\s|\n]*$/gi, ''); + + return output; + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#basicWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.basicWordWrap = function (text) { + + var result = ''; + var lines = text.split('\n'); + + for (var i = 0; i < lines.length; i++) + { + var spaceLeft = this.style.wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) + { + var wordWidth = this.context.measureText(words[j]).width; + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is greater than the word wrap width. + if (j > 0) + { + result += '\n'; + } + result += words[j] + ' '; + spaceLeft = this.style.wordWrapWidth - wordWidth; + } + else + { + spaceLeft -= wordWidthWithSpace; + result += words[j] + ' '; + } + } + + if (i < lines.length-1) + { + result += '\n'; + } + } + + return result; + +}; + +/** +* Updates the internal `style.font` if it now differs according to generation from components. +* +* @method Phaser.Text#updateFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.updateFont = function (components) { + + var font = this.componentsToFont(components); + + if (this.style.font !== font) + { + this.style.font = font; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + +}; + +/** +* Converting a short CSS-font string into the relevant components. +* +* @method Phaser.Text#fontToComponents +* @private +* @param {string} font - a CSS font string +*/ +Phaser.Text.prototype.fontToComponents = function (font) { + + // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand: + // style - normal | italic | oblique | inherit + // variant - normal | small-caps | inherit + // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit + // size - xx-small | x-small | small | medium | large | x-large | xx-large, + // larger | smaller + // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %) + // font-family - rest (but identifiers or quoted with comma separation) + var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/); + + if (m) + { + var family = m[5].trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(family) && !/['",]/.exec(family)) + { + family = "'" + family + "'"; + } + + return { + font: font, + fontStyle: m[1] || 'normal', + fontVariant: m[2] || 'normal', + fontWeight: m[3] || 'normal', + fontSize: m[4] || 'medium', + fontFamily: family + }; + } + else + { + console.warn("Phaser.Text - unparsable CSS font: " + font); + + return { + font: font + }; + } + +}; + +/** +* Converts individual font components (see `fontToComponents`) to a short CSS font string. +* +* @method Phaser.Text#componentsToFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.componentsToFont = function (components) { + + var parts = []; + var v; + + v = components.fontStyle; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontVariant; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontWeight; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontSize; + if (v && v !== 'medium') { parts.push(v); } + + v = components.fontFamily; + if (v) { parts.push(v); } + + if (!parts.length) + { + // Fallback to whatever value the 'font' was + parts.push(components.font); + } + + return parts.join(" "); + +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* Use the optional `immediate` argument if you need the Text display to update immediately. +* +* If not it will re-create the texture of this Text object during the next time the render +* loop is called. +* +* @method Phaser.Text#setText +* @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present. +* @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setText = function (text, immediate) { + + if (immediate === undefined) { immediate = false; } + + this.text = text.toString() || ''; + + if (immediate) + { + this.updateText(); + } + else + { + this.dirty = true; + } + + return this; + +}; + +/** + * Converts the given array into a tab delimited string and then updates this Text object. + * This is mostly used when you want to display external data using tab stops. + * + * The array can be either single or multi dimensional depending on the result you need: + * + * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`. + * + * Where as: + * + * `[ + * [ 'a', 'b', 'c' ], + * [ 'd', 'e', 'f'] + * ]` + * + * would convert in to: `"a\tb\tc\nd\te\tf"` + * + * @method Phaser.Text#parseList + * @param {array} list - The array of data to convert into a string. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.parseList = function (list) { + + if (!Array.isArray(list)) + { + return this; + } + else + { + var s = ""; + + for (var i = 0; i < list.length; i++) + { + if (Array.isArray(list[i])) + { + s += list[i].join("\t"); + + if (i < list.length - 1) + { + s += "\n"; + } + } + else + { + s += list[i]; + + if (i < list.length - 1) + { + s += "\t"; + } + } + } + } + + this.text = s; + this.dirty = true; + + return this; + +}; + +/** + * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned, + * regardless of the number of lines in the text, the font size or any other attribute. + * + * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly + * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment. + * + * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to + * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of + * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center + * of the text bounds. + * + * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions + * may vary based on font (say for multi-lingual games). + * + * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width. + * + * Call this method with no arguments given to reset an existing textBounds. + * + * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts + * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot` + * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then + * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot. + * + * @method Phaser.Text#setTextBounds + * @param {number} [x] - The x coordinate of the Text Bounds region. + * @param {number} [y] - The y coordinate of the Text Bounds region. + * @param {number} [width] - The width of the Text Bounds region. + * @param {number} [height] - The height of the Text Bounds region. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.setTextBounds = function (x, y, width, height) { + + if (x === undefined) + { + this.textBounds = null; + } + else + { + if (!this.textBounds) + { + this.textBounds = new Phaser.Rectangle(x, y, width, height); + } + else + { + this.textBounds.setTo(x, y, width, height); + } + + if (this.style.wordWrapWidth > width) + { + this.style.wordWrapWidth = width; + } + } + + this.updateTexture(); + + return this; + +}; + +/** + * Updates the texture based on the canvas dimensions. + * + * @method Phaser.Text#updateTexture + * @private + */ +Phaser.Text.prototype.updateTexture = function () { + + var base = this.texture.baseTexture; + var crop = this.texture.crop; + var frame = this.texture.frame; + + var w = this.canvas.width; + var h = this.canvas.height; + + base.width = w; + base.height = h; + + crop.width = w; + crop.height = h; + + frame.width = w; + frame.height = h; + + this.texture.width = w; + this.texture.height = h; + + this._width = w; + this._height = h; + + if (this.textBounds) + { + var x = this.textBounds.x; + var y = this.textBounds.y; + + // Align the canvas based on the bounds + if (this.style.boundsAlignH === 'right') + { + x += this.textBounds.width - this.canvas.width / this.resolution; + } + else if (this.style.boundsAlignH === 'center') + { + x += this.textBounds.halfWidth - (this.canvas.width / this.resolution / 2); + } + + if (this.style.boundsAlignV === 'bottom') + { + y += this.textBounds.height - this.canvas.height / this.resolution; + } + else if (this.style.boundsAlignV === 'middle') + { + y += this.textBounds.halfHeight - (this.canvas.height / this.resolution / 2); + } + + this.pivot.x = -x; + this.pivot.y = -y; + } + + // Can't render something with a zero sized dimension + this.renderable = (w !== 0 && h !== 0); + + this.texture.requiresReTint = true; + + this.texture.baseTexture.dirty(); + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Text#_renderWebGL +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderWebGL = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Renders the object using the Canvas renderer. +* +* @method Phaser.Text#_renderCanvas +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderCanvas = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Calculates the ascent, descent and fontSize of a given font style. +* +* @method Phaser.Text#determineFontProperties +* @private +* @param {object} fontStyle +*/ +Phaser.Text.prototype.determineFontProperties = function (fontStyle) { + + var properties = Phaser.Text.fontPropertiesCache[fontStyle]; + + if (!properties) + { + properties = {}; + + var canvas = Phaser.Text.fontPropertiesCanvas; + var context = Phaser.Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('|MÉq').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + if (!context.getImageData(0, 0, width, height)) + { + properties.ascent = baseline; + properties.descent = baseline + 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + } + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i, j; + + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + properties.descent = i - baseline; + //TODO might need a tweak. kind of a temp fix! + properties.descent += 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; + +}; + +/** +* Returns the bounds of the Text as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Text#getBounds +* @param {Phaser.Matrix} matrix - The transformation matrix of the Text. +* @return {Phaser.Rectangle} The framing rectangle +*/ +Phaser.Text.prototype.getBounds = function (matrix) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return PIXI.Sprite.prototype.getBounds.call(this, matrix); + +}; + +/** +* Sets the character limit of the text, with a suffix. +* If the text is longer than this limit, it is truncated and the suffix is appended. +* +* @method Phaser.Text#setCharacterLimit +* @param {number} [characterLimit] - The x coordinate of the Text Bounds region. +* @param {string} [suffix] - The suffix to append to the truncated text. +*/ +Phaser.Text.prototype.setCharacterLimit = function (characterLimit, suffix) { + + this.characterLimitSuffix = (suffix === undefined) ? '' : suffix; + this.characterLimitSize = characterLimit; + + this.updateText(); +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* @name Phaser.Text#text +* @property {string} text +*/ +Object.defineProperty(Phaser.Text.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* Change the font used. +* +* This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except +* that unlike using `setStyle` this will not change any current font fill/color settings. +* +* The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. +* +* @name Phaser.Text#cssFont +* @property {string} cssFont +*/ +Object.defineProperty(Phaser.Text.prototype, 'cssFont', { + + get: function() { + return this.componentsToFont(this._fontComponents); + }, + + set: function (value) + { + value = value || 'bold 20pt Arial'; + this._fontComponents = this.fontToComponents(value); + this.updateFont(this._fontComponents); + } + +}); + +/** +* Change the font family that the text will be rendered in, such as 'Arial'. +* +* Multiple CSS font families and generic fallbacks can be specified as long as +* {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed. +* +* To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`. +* +* @name Phaser.Text#font +* @property {string} font +*/ +Object.defineProperty(Phaser.Text.prototype, 'font', { + + get: function() { + return this._fontComponents.fontFamily; + }, + + set: function(value) { + + value = value || 'Arial'; + value = value.trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value)) + { + value = "'" + value + "'"; + } + + this._fontComponents.fontFamily = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The size of the font. +* +* If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing +* the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). +* +* @name Phaser.Text#fontSize +* @property {number|string} fontSize +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontSize', { + + get: function() { + + var size = this._fontComponents.fontSize; + + if (size && /(?:^0$|px$)/.exec(size)) + { + return parseInt(size, 10); + } + else + { + return size; + } + + }, + + set: function(value) { + + value = value || '0'; + + if (typeof value === 'number') + { + value = value + 'px'; + } + + this._fontComponents.fontSize = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}. +* @name Phaser.Text#fontWeight +* @property {string} fontWeight +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontWeight', { + + get: function() { + return this._fontComponents.fontWeight || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontWeight = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The style of the font: 'normal', 'italic', 'oblique' +* @name Phaser.Text#fontStyle +* @property {string} fontStyle +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontStyle', { + + get: function() { + return this._fontComponents.fontStyle || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontStyle = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The variant the font: 'normal', 'small-caps' +* @name Phaser.Text#fontVariant +* @property {string} fontVariant +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontVariant', { + + get: function() { + return this._fontComponents.fontVariant || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontVariant = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* @name Phaser.Text#fill +* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'fill', { + + get: function() { + return this.style.fill; + }, + + set: function(value) { + + if (value !== this.style.fill) + { + this.style.fill = value; + this.dirty = true; + } + + } + +}); + +/** +* Controls the horizontal alignment for multiline text. +* Can be: 'left', 'center' or 'right'. +* Does not affect single lines of text. For that please see `setTextBounds`. +* @name Phaser.Text#align +* @property {string} align +*/ +Object.defineProperty(Phaser.Text.prototype, 'align', { + + get: function() { + return this.style.align; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.align) + { + this.style.align = value; + this.dirty = true; + } + + } + +}); + +/** +* The resolution of the canvas the text is rendered to. +* This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. +* @name Phaser.Text#resolution +* @property {integer} resolution +*/ +Object.defineProperty(Phaser.Text.prototype, 'resolution', { + + get: function() { + return this._res; + }, + + set: function(value) { + + if (value !== this._res) + { + this._res = value; + this.dirty = true; + } + + } + +}); + +/** +* The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. +* Can be an integer or an array of varying tab sizes, one tab per element. +* For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. +* If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. +* +* @name Phaser.Text#tabs +* @property {integer|array} tabs +*/ +Object.defineProperty(Phaser.Text.prototype, 'tabs', { + + get: function() { + return this.style.tabs; + }, + + set: function(value) { + + if (value !== this.style.tabs) + { + this.style.tabs = value; + this.dirty = true; + } + + } + +}); + +/** +* Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @name Phaser.Text#boundsAlignH +* @property {string} boundsAlignH +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', { + + get: function() { + return this.style.boundsAlignH; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignH) + { + this.style.boundsAlignH = value; + this.dirty = true; + } + + } + +}); + +/** +* Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @name Phaser.Text#boundsAlignV +* @property {string} boundsAlignV +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', { + + get: function() { + return this.style.boundsAlignV; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignV) + { + this.style.boundsAlignV = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#stroke +* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'stroke', { + + get: function() { + return this.style.stroke; + }, + + set: function(value) { + + if (value !== this.style.stroke) + { + this.style.stroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#strokeThickness +* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke) +*/ +Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', { + + get: function() { + return this.style.strokeThickness; + }, + + set: function(value) { + + if (value !== this.style.strokeThickness) + { + this.style.strokeThickness = Number(value); + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrap +* @property {boolean} wordWrap - Indicates if word wrap should be used. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrap', { + + get: function() { + return this.style.wordWrap; + }, + + set: function(value) { + + if (value !== this.style.wordWrap) + { + this.style.wordWrap = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrapWidth +* @property {number} wordWrapWidth - The width at which text will wrap. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', { + + get: function() { + return this.style.wordWrapWidth; + }, + + set: function(value) { + + if (value !== this.style.wordWrapWidth) + { + this.style.wordWrapWidth = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#lineSpacing +* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. +*/ +Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { + + get: function() { + return this._lineSpacing; + }, + + set: function(value) { + + if (value !== this._lineSpacing) + { + this._lineSpacing = parseFloat(value); + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetX +* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', { + + get: function() { + return this.style.shadowOffsetX; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetX) + { + this.style.shadowOffsetX = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetY +* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', { + + get: function() { + return this.style.shadowOffsetY; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetY) + { + this.style.shadowOffsetY = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowColor +* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowColor', { + + get: function() { + return this.style.shadowColor; + }, + + set: function(value) { + + if (value !== this.style.shadowColor) + { + this.style.shadowColor = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowBlur +* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', { + + get: function() { + return this.style.shadowBlur; + }, + + set: function(value) { + + if (value !== this.style.shadowBlur) + { + this.style.shadowBlur = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowStroke +* @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', { + + get: function() { + return this.style.shadowStroke; + }, + + set: function(value) { + + if (value !== this.style.shadowStroke) + { + this.style.shadowStroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowFill +* @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowFill', { + + get: function() { + return this.style.shadowFill; + }, + + set: function(value) { + + if (value !== this.style.shadowFill) + { + this.style.shadowFill = value; + this.dirty = true; + } + + } + +}); + +/** +* The width of the Text object in pixels. This is width of the Texture frame / the Text.resolution. +* @name Phaser.Text#width +* @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'width', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.x * (this.texture.frame.width / this.resolution); + }, + + set: function(value) { + + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** +* The height of the Text object in pixels. This is height of the Texture frame / the Text.resolution. +* @name Phaser.Text#height +* @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'height', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.y * (this.texture.frame.height / this.resolution); + }, + + set: function(value) { + + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +Phaser.Text.fontPropertiesCache = {}; + +Phaser.Text.fontPropertiesCanvas = document.createElement('canvas'); +Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d'); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. +* It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to +* match the font structure. +* +* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability +* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by +* processing the font texture in an image editor, applying fills and any other effects required. +* +* To create multi-line text insert \r, \n or \r\n escape codes into the text string. +* +* If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly +* updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. +* +* To create a BitmapText data files you can use: +* +* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ +* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner +* Littera (Web-based, free): http://kvazars.com/littera/ +* +* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of +* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson +* +* If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. +* +* @class Phaser.BitmapText +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - X coordinate to display the BitmapText object at. +* @param {number} y - Y coordinate to display the BitmapText object at. +* @param {string} font - The key of the BitmapText as stored in Phaser.Cache. +* @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. +* @param {number} [size=32] - The size the font will be rendered at in pixels. +* @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. +*/ +Phaser.BitmapText = function (game, x, y, font, text, size, align) { + + x = x || 0; + y = y || 0; + font = font || ''; + text = text || ''; + size = size || 32; + align = align || 'left'; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.BITMAPTEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textWidth = 0; + + /** + * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textHeight = 0; + + /** + * @property {Phaser.Point} anchor - The anchor value of this BitmapText. + */ + this.anchor = new Phaser.Point(); + + /** + * @property {Phaser.Point} _prevAnchor - The previous anchor value. + * @private + */ + this._prevAnchor = new Phaser.Point(); + + /** + * @property {array} _glyphs - Private tracker for the letter sprite pool. + * @private + */ + this._glyphs = []; + + /** + * @property {number} _maxWidth - Internal cache var. + * @private + */ + this._maxWidth = 0; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text.toString() || ''; + + /** + * @property {string} _data - Internal cache var. + * @private + */ + this._data = game.cache.getBitmapFont(font); + + /** + * @property {string} _font - Internal cache var. + * @private + */ + this._font = font; + + /** + * @property {number} _fontSize - Internal cache var. + * @private + */ + this._fontSize = size; + + /** + * @property {string} _align - Internal cache var. + * @private + */ + this._align = align; + + /** + * @property {number} _tint - Internal cache var. + * @private + */ + this._tint = 0xFFFFFF; + + this.updateText(); + + /** + * @property {boolean} dirty - The dirty state of this object. + */ + this.dirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.BitmapText.prototype.constructor = Phaser.BitmapText; + +Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.BitmapText +* @return {boolean} True if the BitmapText was rendered, otherwise false. +*/ +Phaser.BitmapText.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.preUpdate. +* @method Phaser.BitmapText.prototype.postUpdate +*/ +Phaser.BitmapText.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this.body && this.body.type === Phaser.Physics.ARCADE) + { + if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight)) + { + this.body.setSize(this.textWidth, this.textHeight); + } + } + +}; + +/** +* The text to be displayed by this BitmapText object. +* +* It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. +* +* @method Phaser.BitmapText.prototype.setText +* @param {string} text - The text to be displayed by this BitmapText object. +*/ +Phaser.BitmapText.prototype.setText = function (text) { + + this.text = text; + +}; + +/** +* Given the input text this will scan the characters until either a newline is encountered, +* or the line exceeds maxWidth, taking into account kerning, character widths and scaling. +* +* @method Phaser.BitmapText.prototype.scanLine +* @private +* @param {object} data - A reference to the font object in the Phaser.Cache. +* @param {float} scale - The scale of the font in relation to the texture. +* @param {string} text - The text to parse. +* @return {object} An object containing the parsed characters, total pixel width and x offsets. +*/ +Phaser.BitmapText.prototype.scanLine = function (data, scale, text) { + + var x = 0; + var w = 0; + var lastSpace = -1; + var wrappedWidth = 0; + var prevCharCode = null; + var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null; + var chars = []; + + // Let's scan the text and work out if any of the lines are > maxWidth + for (var i = 0; i < text.length; i++) + { + var end = (i === text.length - 1) ? true : false; + + if (/(?:\r\n|\r|\n)/.test(text.charAt(i))) + { + return { width: w, text: text.substr(0, i), end: end, chars: chars }; + } + else + { + var charCode = text.charCodeAt(i); + var charData = data.chars[charCode]; + + var c = 0; + + // If the character data isn't found in the data array + // then we replace it with a blank space + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + // Adjust for kerning from previous character to this one + var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0; + + // Record the last space in the string and the current width + if (/(\s)/.test(text.charAt(i))) + { + lastSpace = i; + wrappedWidth = w; + } + + // What will the line width be if we add this character to it? + c = (kerning + charData.texture.width + charData.xOffset) * scale; + + // Do we need to line-wrap? + if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1) + { + // The last space was at "lastSpace" which was "i - lastSpace" characters ago + return { width: wrappedWidth || w, text: text.substr(0, i - (i - lastSpace)), end: false, chars: chars }; + } + else + { + w += (charData.xAdvance + kerning) * scale; + + chars.push(x + (charData.xOffset + kerning) * scale); + + x += (charData.xAdvance + kerning) * scale; + + prevCharCode = charCode; + } + } + } + + return { width: w, text: text, end: end, chars: chars }; + +}; + +/** +* Given a text string this will scan each character in the string to ensure it exists +* in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. +* +* If no font data has been loaded at all this returns an empty string, as nothing can be rendered. +* +* @method Phaser.BitmapText.prototype.cleanText +* @param {string} text - The text to parse. +* @param {string} [replace=''] - The replacement string for any missing characters. +* @return {string} The cleaned text string. +*/ +Phaser.BitmapText.prototype.cleanText = function (text, replace) { + + if (replace === undefined) + { + replace = ''; + } + + var data = this._data.font; + + if (!data) + { + return ''; + } + + var re = /\r\n|\n\r|\n|\r/g; + var lines = text.replace(re, "\n").split("\n"); + + for (var i = 0; i < lines.length; i++) + { + var output = ''; + var line = lines[i]; + + for (var c = 0; c < line.length; c++) + { + if (data.chars[line.charCodeAt(c)]) + { + output = output.concat(line[c]); + } + else + { + output = output.concat(replace); + } + } + + lines[i] = output; + } + + return lines.join("\n"); + +}; + +/** +* Renders text and updates it when needed. +* +* @method Phaser.BitmapText.prototype.updateText +* @private +*/ +Phaser.BitmapText.prototype.updateText = function () { + + var data = this._data.font; + + if (!data) + { + return; + } + + var text = this.text; + var scale = this._fontSize / data.size; + var lines = []; + + var y = 0; + + this.textWidth = 0; + + do + { + var line = this.scanLine(data, scale, text); + + line.y = y; + + lines.push(line); + + if (line.width > this.textWidth) + { + this.textWidth = line.width; + } + + y += (data.lineHeight * scale); + + text = text.substr(line.text.length + 1); + + } while (line.end === false); + + this.textHeight = y; + + var t = 0; + var align = 0; + var ax = this.textWidth * this.anchor.x; + var ay = this.textHeight * this.anchor.y; + + for (var i = 0; i < lines.length; i++) + { + var line = lines[i]; + + if (this._align === 'right') + { + align = this.textWidth - line.width; + } + else if (this._align === 'center') + { + align = (this.textWidth - line.width) / 2; + } + + for (var c = 0; c < line.text.length; c++) + { + var charCode = line.text.charCodeAt(c); + var charData = data.chars[charCode]; + + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + var g = this._glyphs[t]; + + if (g) + { + // Sprite already exists in the glyphs pool, so we'll reuse it for this letter + g.texture = charData.texture; + } + else + { + // We need a new sprite as the pool is empty or exhausted + g = new PIXI.Sprite(charData.texture); + g.name = line.text[c]; + this._glyphs.push(g); + } + + g.position.x = (line.chars[c] + align) - ax; + g.position.y = (line.y + (charData.yOffset * scale)) - ay; + + g.scale.set(scale); + g.tint = this.tint; + g.texture.requiresReTint = true; + g.cachedTint = 0xFFFFFF; + + if (!g.parent) + { + this.addChild(g); + } + + t++; + } + } + + // Remove unnecessary children + // This moves them from the display list (children array) but retains them in the _glyphs pool + for (i = t; i < this._glyphs.length; i++) + { + this.removeChild(this._glyphs[i]); + } + +}; + +/** +* If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of +* Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they +* still take up memory while sat in the glyphs pool waiting to be re-used in the future. +* +* If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool +* by calling this method. +* +* Calling this doesn't prevent you from increasing the length of the text again in the future. +* +* @method Phaser.BitmapText.prototype.purgeGlyphs +* @return {integer} The amount of glyphs removed from the pool. +*/ +Phaser.BitmapText.prototype.purgeGlyphs = function () { + + var len = this._glyphs.length; + var kept = []; + + for (var i = 0; i < this._glyphs.length; i++) + { + if (this._glyphs[i].parent !== this) + { + this._glyphs[i].destroy(); + } + else + { + kept.push(this._glyphs[i]); + } + } + + this._glyphs = []; + this._glyphs = kept; + + this.updateText(); + + return len - kept.length; + +}; + +/** +* Updates the transform of this object. +* +* @method Phaser.BitmapText.prototype.updateTransform +* @private +*/ +Phaser.BitmapText.prototype.updateTransform = function () { + + if (this.dirty || !this.anchor.equals(this._prevAnchor)) + { + this.updateText(); + this.dirty = false; + this._prevAnchor.copyFrom(this.anchor); + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/** +* @name Phaser.BitmapText#align +* @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'align', { + + get: function() { + return this._align; + }, + + set: function(value) { + + if (value !== this._align && (value === 'left' || value === 'center' || value === 'right')) + { + this._align = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#tint +* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'tint', { + + get: function() { + return this._tint; + }, + + set: function(value) { + + if (value !== this._tint) + { + this._tint = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#font +* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'font', { + + get: function() { + return this._font; + }, + + set: function(value) { + + if (value !== this._font) + { + this._font = value.trim(); + this._data = this.game.cache.getBitmapFont(this._font); + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#fontSize +* @property {number} fontSize - The size of the font in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { + + get: function() { + return this._fontSize; + }, + + set: function(value) { + + value = parseInt(value, 10); + + if (value !== this._fontSize && value > 0) + { + this._fontSize = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#text +* @property {string} text - The text to be displayed by this BitmapText object. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.updateText(); + } + + } + +}); + +/** +* The maximum display width of this BitmapText in pixels. +* +* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped +* based on the last whitespace character found in the line. +* +* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. +* +* Disable maxWidth by setting the value to 0. +* +* @name Phaser.BitmapText#maxWidth +* @property {number} maxWidth - The maximum width of this BitmapText in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', { + + get: function() { + + return this._maxWidth; + + }, + + set: function(value) { + + if (value !== this._maxWidth) + { + this._maxWidth = value; + this.updateText(); + } + + } + +}); + +/** +* Enable or disable texture smoothing for this BitmapText. +* +* The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. +* +* Smoothing is enabled by default. +* +* @name Phaser.BitmapText#smoothed +* @property {boolean} smoothed +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', { + + get: function() { + + return !this._data.base.scaleMode; + + }, + + set: function(value) { + + if (value) + { + this._data.base.scaleMode = 0; + } + else + { + this._data.base.scaleMode = 1; + } + this._data.base.dirty(); + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont +* is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. +* +* @class Phaser.RetroFont +* @extends Phaser.RenderTexture +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {string} key - The font set graphic set as stored in the Game.Cache. +* @param {number} characterWidth - The width of each character in the font set. +* @param {number} characterHeight - The height of each character in the font set. +* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. +* @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. +* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. +* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { + + if (!game.cache.checkImageKey(key)) + { + return false; + } + + if (charsPerRow === undefined || charsPerRow === null) + { + charsPerRow = game.cache.getImage(key).width / characterWidth; + } + + /** + * @property {number} characterWidth - The width of each character in the font set. + */ + this.characterWidth = characterWidth; + + /** + * @property {number} characterHeight - The height of each character in the font set. + */ + this.characterHeight = characterHeight; + + /** + * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here. + */ + this.characterSpacingX = xSpacing || 0; + + /** + * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here. + */ + this.characterSpacingY = ySpacing || 0; + + /** + * @property {number} characterPerRow - The number of characters per row in the font set. + */ + this.characterPerRow = charsPerRow; + + /** + * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @readonly + */ + this.offsetX = xOffset || 0; + + /** + * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @readonly + */ + this.offsetY = yOffset || 0; + + /** + * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + */ + this.align = "left"; + + /** + * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) + * @default + */ + this.multiLine = false; + + /** + * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. + * @default + */ + this.autoUpperCase = true; + + /** + * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels. + * @default + */ + this.customSpacingX = 0; + + /** + * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels. + * @default + */ + this.customSpacingY = 0; + + /** + * If you need this RetroFont image to have a fixed width you can set the width in this value. + * If text is wider than the width specified it will be cropped off. + * @property {number} fixedWidth + */ + this.fixedWidth = 0; + + /** + * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font. + */ + this.fontSet = game.cache.getImage(key); + + /** + * @property {string} _text - The text of the font image. + * @private + */ + this._text = ''; + + /** + * @property {array} grabData - An array of rects for faster character pasting. + * @private + */ + this.grabData = []; + + /** + * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font. + */ + this.frameData = new Phaser.FrameData(); + + // Now generate our rects for faster copying later on + var currentX = this.offsetX; + var currentY = this.offsetY; + var r = 0; + + for (var c = 0; c < chars.length; c++) + { + var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight)); + + this.grabData[chars.charCodeAt(c)] = frame.index; + + r++; + + if (r === this.characterPerRow) + { + r = 0; + currentX = this.offsetX; + currentY += this.characterHeight + this.characterSpacingY; + } + else + { + currentX += this.characterWidth + this.characterSpacingX; + } + } + + game.cache.updateFrameData(key, this.frameData); + + /** + * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font. + * @readonly + */ + this.stamp = new Phaser.Image(game, 0, 0, key, 0); + + Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST); + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RETROFONT; + +}; + +Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype); +Phaser.RetroFont.prototype.constructor = Phaser.RetroFont; + +/** +* Align each line of multi-line text to the left. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_LEFT = "left"; + +/** +* Align each line of multi-line text to the right. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_RIGHT = "right"; + +/** +* Align each line of multi-line text in the center. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_CENTER = "center"; + +/** +* Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + +/** +* Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "; + +/** +* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789"; + +/** +* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789"; + +/** +* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' "; + +/** +* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39"; + +/** +* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!"; + +/** +* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"; + +/** +* If you need this RetroFont to have a fixed width and custom alignment you can set the width here. +* If text is wider than the width specified it will be cropped off. +* +* @method Phaser.RetroFont#setFixedWidth +* @memberof Phaser.RetroFont +* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. +* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +*/ +Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) { + + if (lineAlignment === undefined) { lineAlignment = 'left'; } + + this.fixedWidth = width; + this.align = lineAlignment; + +}; + +/** +* A helper function that quickly sets lots of variables at once, and then updates the text. +* +* @method Phaser.RetroFont#setText +* @memberof Phaser.RetroFont +* @param {string} content - The text of this sprite. +* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. +* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels. +* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels. +* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. +*/ +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; + } + +}; + +/** +* Updates the texture with the new text. +* +* @method Phaser.RetroFont#buildRetroFontText +* @memberof Phaser.RetroFont +*/ +Phaser.RetroFont.prototype.buildRetroFontText = function () { + + var cx = 0; + var cy = 0; + + // Clears the textureBuffer + 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); + } + + // Loop through each line of text + for (var i = 0; i < lines.length; i++) + { + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + // This line of text is held in lines[i] - need to work out the alignment + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(lines[i], cx, cy, this.customSpacingX); + + cy += this.characterHeight + this.customSpacingY; + } + } + else + { + if (this.fixedWidth > 0) + { + this.resize(this.fixedWidth, this.characterHeight, true); + } + else + { + this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true); + } + + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(this._text, cx, 0, this.customSpacingX); + } + + this.requiresReTint = true; + +}; + +/** +* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. +* Used by getLine and getMultiLine +* +* @method Phaser.RetroFont#pasteLine +* @memberof Phaser.RetroFont +* @param {string} line - The single line of text to paste. +* @param {number} x - The x coordinate. +* @param {number} y - The y coordinate. +* @param {number} customSpacingX - Custom X spacing. +*/ +Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) { + + for (var c = 0; c < line.length; c++) + { + // If it's a space then there is no point copying, so leave a blank space + if (line.charAt(c) === " ") + { + x += this.characterWidth + customSpacingX; + } + else + { + // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it + if (this.grabData[line.charCodeAt(c)] >= 0) + { + this.stamp.frame = this.grabData[line.charCodeAt(c)]; + this.renderXY(this.stamp, x, y, false); + + x += this.characterWidth + customSpacingX; + + if (x > this.width) + { + break; + } + } + } + } +}; + +/** +* Works out the longest line of text in _text and returns its length +* +* @method Phaser.RetroFont#getLongestLine +* @memberof Phaser.RetroFont +* @return {number} The length of the longest line of text. +*/ +Phaser.RetroFont.prototype.getLongestLine = function () { + + var longestLine = 0; + + if (this._text.length > 0) + { + var lines = this._text.split("\n"); + + for (var i = 0; i < lines.length; i++) + { + if (lines[i].length > longestLine) + { + longestLine = lines[i].length; + } + } + } + + return longestLine; +}; + +/** +* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set. +* +* @method Phaser.RetroFont#removeUnsupportedCharacters +* @memberof Phaser.RetroFont +* @protected +* @param {boolean} [stripCR=true] - Should it strip carriage returns as well? +* @return {string} A clean version of the string. +*/ +Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) { + + var newString = ""; + + for (var c = 0; c < this._text.length; c++) + { + var aChar = this._text[c]; + var code = aChar.charCodeAt(0); + + if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n")) + { + newString = newString.concat(aChar); + } + } + + return newString; + +}; + +/** +* Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. +* Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. +* So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. +* +* @method Phaser.RetroFont#updateOffset +* @memberof Phaser.RetroFont +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont.prototype.updateOffset = function (x, y) { + + if (this.offsetX === x && this.offsetY === y) + { + return; + } + + var diffX = x - this.offsetX; + var diffY = y - this.offsetY; + + var frames = this.game.cache.getFrameData(this.stamp.key).getFrames(); + var i = frames.length; + + while (i--) + { + frames[i].x += diffX; + frames[i].y += diffY; + } + + this.buildRetroFontText(); + +}; + +/** +* @name Phaser.RetroFont#text +* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. +*/ +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(); + } + + } + +}); + +/** +* @name Phaser.RetroFont#smoothed +* @property {boolean} smoothed - Sets if the stamp is smoothed or not. +*/ +Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", { + + get: function () { + + return this.stamp.smoothed; + + }, + + set: function (value) { + + this.stamp.smoothed = value; + this.buildRetroFontText(); + + } + +}); + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @author Rovanion Luckey +* @copyright 2016 Photon Storm Ltd, Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Rope is a Sprite that has a repeating texture. +* +* The texture will automatically wrap on the edges as it moves. +* +* Please note that Ropes cannot have an input handler. +* +* @class Phaser.Rope +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Rope at. +* @param {number} y - The y coordinate (in world space) to position the Rope at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {Array} points - An array of {Phaser.Point}. +*/ +Phaser.Rope = function (game, x, y, key, frame, points) { + + this.points = points || []; + this._hasUpdateAnimation = false; + this._updateAnimationCallback = null; + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROPE; + + PIXI.DisplayObjectContainer.call(this); + + this.texture = Phaser.Cache.DEFAULT; + + // set up the main bits.. + this.uvs = new Float32Array([0, 1, + 1, 1, + 1, 0, + 0, 1]); + + this.vertices = new Float32Array([0, 0, + 100, 0, + 100, 100, + 0, 100]); + + this.colors = new Float32Array([1, 1, 1, 1]); + + this.indices = new Uint16Array([0, 1, 2, 3]); + + if (points) + { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + /** + * Whether the strip is dirty or not + * + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. + * + * @property canvasPadding + * @type Number + */ + this.canvasPadding = 0; + + this.drawMode = Phaser.Rope.TRIANGLE_STRIP; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + + this.refresh(); + +}; + +Phaser.Rope.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Rope.prototype.constructor = Phaser.Rope; + +Phaser.Component.Core.install.call(Phaser.Rope.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +Phaser.Rope.TRIANGLE_STRIP = 0; +Phaser.Rope.TRIANGLES = 1; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Rope#preUpdate +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override and use this function in your own custom objects to handle any update requirements you may have. +* +* @method Phaser.Rope#update +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.update = function() { + + if (this._hasUpdateAnimation) + { + this.updateAnimation.call(this); + } + +}; + +/** +* Resets the Rope. This places the Rope at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the Rope has a physics body that too is reset. +* +* @method Phaser.Rope#reset +* @memberof Phaser.Rope +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.Rope} This instance. +*/ +Phaser.Rope.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + return this; + +}; + +/* +* Refreshes the rope texture and UV coordinates. +* +* @method Phaser.Rope#refresh +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.refresh = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + this.count -= 0.2; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + var index; + var amount; + + for (var i = 1; i < total; i++) + { + index = i * 4; + + // time to do some smart drawing! + amount = i / (total - 1); + + if (i % 2) + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + else + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + +}; + +/* +* Updates the Ropes transform ready for rendering. +* +* @method Phaser.Rope#updateTransform +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.updateTransform = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var lastPoint = points[0]; + var nextPoint; + var perp = { x:0, y:0 }; + + this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + var point; + var index; + var ratio; + var perpLength; + var num; + + for (var i = 0; i < total; i++) + { + point = points[i]; + index = i * 4; + + if(i < points.length - 1) + { + nextPoint = points[i + 1]; + } + else + { + nextPoint = point; + } + + perp.y = -(nextPoint.x - lastPoint.x); + perp.x = nextPoint.y - lastPoint.y; + + ratio = (1 - (i / (total - 1))) * 10; + + if (ratio > 1) + { + ratio = 1; + } + + perpLength = Math.sqrt((perp.x * perp.x) + (perp.y * perp.y)); + num = this.texture.height / 2; + perp.x /= perpLength; + perp.y /= perpLength; + + perp.x *= num; + perp.y *= num; + + vertices[index] = point.x + perp.x; + vertices[index + 1] = point.y + perp.y; + vertices[index + 2] = point.x - perp.x; + vertices[index + 3] = point.y - perp.y; + + lastPoint = point; + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/* +* Sets the Texture this Rope uses for rendering. +* +* @method Phaser.Rope#setTexture +* @memberof Phaser.Rope +* @param {Texture} texture - The texture that will be used. +*/ +Phaser.Rope.prototype.setTexture = function (texture) { + + this.texture = texture; + +}; + +/* +* Renders the Rope to WebGL. +* +* @private +* @method Phaser.Rope#_renderWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + renderSession.spriteBatch.stop(); + + if (!this._vertexBuffer) + { + this._initWebGL(renderSession); + } + + renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader); + + this._renderStrip(renderSession); + + renderSession.spriteBatch.start(); + +}; + +/* +* Builds the Strip. +* +* @private +* @method Phaser.Rope#_initWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._initWebGL = function (renderSession) { + + // build the strip! + var gl = renderSession.gl; + + this._vertexBuffer = gl.createBuffer(); + this._indexBuffer = gl.createBuffer(); + this._uvBuffer = gl.createBuffer(); + this._colorBuffer = gl.createBuffer(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + +}; + +/* +* Renders the Strip to WebGL. +* +* @private +* @method Phaser.Rope#_renderStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderStrip = function (renderSession) { + + var gl = renderSession.gl; + var projection = renderSession.projection; + var offset = renderSession.offset; + var shader = renderSession.shaderManager.stripShader; + + var drawMode = (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + renderSession.blendModeManager.setBlendMode(this.blendMode); + + // set uniforms + gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true)); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + gl.uniform1f(shader.alpha, this.worldAlpha); + + if (!this.dirty) + { + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + } + else + { + this.dirty = false; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + } + + gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0); + +}; + +/* +* Renders the Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvas +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvas = function (renderSession) { + + var context = renderSession.context; + + var transform = this.worldTransform; + + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + if (renderSession.roundPixels) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx, ty); + } + + if (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) + { + this._renderCanvasTriangleStrip(context); + } + else + { + this._renderCanvasTriangles(context); + } + +}; + +/* +* Renders a Triangle Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangleStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangleStrip = function (context) { + + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + + var length = vertices.length / 2; + + this.count++; + + for (var i = 0; i < length - 2; i++) + { + var index = i * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangles +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangles = function (context) { + + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + + var length = indices.length; + + this.count++; + + for (var i = 0; i < length; i += 3) + { + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasDrawTriangle +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { + + var textureSource = this.texture.baseTexture.source; + var textureWidth = this.texture.width; + var textureHeight = this.texture.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var u0 = uvs[index0] * textureWidth; + var u1 = uvs[index1] * textureWidth; + var u2 = uvs[index2] * textureWidth; + var v0 = uvs[index0 + 1] * textureHeight; + var v1 = uvs[index1 + 1] * textureHeight; + var v2 = uvs[index2 + 1] * textureHeight; + + if (this.canvasPadding > 0) + { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt((normX * normX) + (normY * normY)); + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2); + var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2); + var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2); + var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2); + var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2); + var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2); + var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2); + + context.transform( + deltaA / delta, + deltaD / delta, + deltaB / delta, + deltaE / delta, + deltaC / delta, + deltaF / delta); + + context.drawImage(textureSource, 0, 0); + context.restore(); + +}; + +/* +* Renders a flat strip. +* +* @method Phaser.Rope#renderStripFlat +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.renderStripFlat = function (strip) { + + var context = this.context; + var vertices = strip.vertices; + + var length = vertices.length / 2; + + this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; i++) + { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var x1 = vertices[index + 2]; + var x2 = vertices[index + 4]; + var y0 = vertices[index + 1]; + var y1 = vertices[index + 3]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + +}; + +/* +* Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Rope#getBounds +* @memberof Phaser.Rope +* @param {Matrix} matrix - The transformation matrix of the Sprite. +* @return {Rectangle} The framing rectangle. +*/ +Phaser.Rope.prototype.getBounds = function (matrix) { + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + var vertices = this.vertices; + + for (var i = 0; i < vertices.length; i += 2) + { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + if (minX === -Infinity || maxY === Infinity) + { + return PIXI.EmptyRectangle; + } + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // Store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* A Rope will call its updateAnimation function on each update loop if it has one. +* +* @name Phaser.Rope#updateAnimation +* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. +*/ +Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", { + + get: function () { + + return this._updateAnimation; + + }, + + set: function (value) { + + if (value && typeof value === 'function') + { + this._hasUpdateAnimation = true; + this._updateAnimation = value; + } + else + { + this._hasUpdateAnimation = false; + this._updateAnimation = null; + } + + } + +}); + +/** +* The segments that make up the rope body as an array of Phaser.Rectangles +* +* @name Phaser.Rope#segments +* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope +*/ +Object.defineProperty(Phaser.Rope.prototype, "segments", { + + get: function () { + + var segments = []; + var index, x1, y1, x2, y2, width, height, rect; + + for (var i = 0; i < this.points.length; i++) + { + index = i * 4; + + x1 = this.vertices[index] * this.scale.x; + y1 = this.vertices[index + 1] * this.scale.y; + x2 = this.vertices[index + 4] * this.scale.x; + y2 = this.vertices[index + 3] * this.scale.y; + + width = Phaser.Math.difference(x1, x2); + height = Phaser.Math.difference(y1, y2); + + x1 += this.world.x; + y1 += this.world.y; + rect = new Phaser.Rectangle(x1, y1, width, height); + segments.push(rect); + } + + return segments; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. +* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. +* +* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. +* +* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background +* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` +* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will +* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to +* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. +* +* An important note about texture dimensions: +* +* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be +* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two +* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and +* bottom of your frame. To avoid this ensure your textures are perfect powers of two. +* +* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However +* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive +* additional padding to enforce it to be so. +* +* @class Phaser.TileSprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate (in world space) to position the TileSprite at. +* @param {number} [y=0] - The y coordinate (in world space) to position the TileSprite at. +* @param {number} [width=256] - The width of the TileSprite. +* @param {number} [height=256] - The height of the TileSprite. +* @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. +* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.TileSprite = function (game, x, y, width, height, key, frame) { + + x = x || 0; + y = y || 0; + width = width || 256; + height = height || 256; + key = key || null; + frame = frame || null; + + PIXI.Sprite.call(this, new PIXI.Texture(Phaser.Cache.DEFAULT.baseTexture), width, height); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.TILESPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} _scroll - Internal cache var. + * @private + */ + this._scroll = new Phaser.Point(); + + /** + * @property {Phaser.Point} tileScale - The scale applied to the image being tiled. + */ + this.tileScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tileScaleOffset - The scale offset applied to the image being tiled. + */ + this.tileScaleOffset = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tilePosition - The offset position of the image being tiled. + */ + this.tilePosition = new Phaser.Point(); + + /** + * If enabled a green rectangle will be drawn behind the generated tiling texture, + * allowing you to visually debug the texture being used. + * + * @property {boolean} textureDebug + */ + this.textureDebug = false; + + /** + * The CanvasBuffer object that the tiled texture is drawn to. + * + * @property {PIXI.CanvasBuffer} canvasBuffer + */ + this.canvasBuffer = null; + + /** + * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. + * + * @property {PIXI.Texture} tilingTexture + */ + this.tilingTexture = null; + + /** + * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). + * + * @property {object} tilePattern + */ + this.tilePattern = null; + + /** + * If true the TileSprite will run `generateTexture` on its **next** render pass. + * This is set by the likes of Phaser.LoadTexture.setFrame. + * + * @property {boolean} refreshTexture + */ + this.refreshTexture = true; + + this.frameWidth = 0; + this.frameHeight = 0; + + this._width = width; + this._height = height; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.TileSprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.TileSprite.prototype.constructor = Phaser.TileSprite; + +Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'Smoothed' +]); + +Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TileSprite#preUpdate +* @memberof Phaser.TileSprite +* @return {boolean} +*/ +Phaser.TileSprite.prototype.preUpdate = function () { + + if (this._scroll.x !== 0) + { + this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed; + } + + if (this._scroll.y !== 0) + { + this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed; + } + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). +* The scroll speed is specified in pixels per second. +* A negative x value will scroll to the left. A positive x value will scroll to the right. +* A negative y value will scroll up. A positive y value will scroll down. +* +* @method Phaser.TileSprite#autoScroll +* @memberof Phaser.TileSprite +* @param {number} x - Horizontal scroll speed in pixels per second. +* @param {number} y - Vertical scroll speed in pixels per second. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.autoScroll = function (x, y) { + + this._scroll.set(x, y); + + return this; + +}; + +/** +* Stops an automatically scrolling TileSprite. +* +* @method Phaser.TileSprite#stopScroll +* @memberof Phaser.TileSprite +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.stopScroll = function () { + + this._scroll.set(0, 0); + + return this; + +}; + +/** +* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present +* and nulls its reference to game, freeing it up for garbage collection. +* +* @method Phaser.TileSprite#destroy +* @memberof Phaser.TileSprite +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.TileSprite.prototype.destroy = function (destroyChildren) { + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + + PIXI.Sprite.prototype.destroy.call(this); + + if (this.canvasBuffer) + { + this.canvasBuffer.destroy(); + this.canvasBuffer = null; + } + + this.tileScale = null; + this.tileScaleOffset = null; + this.tilePosition = null; + + if (this.tilingTexture) + { + this.tilingTexture.destroy(true); + this.tilingTexture = null; + } + +}; + +/** +* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the TileSprite has a physics body that too is reset. +* +* @method Phaser.TileSprite#reset +* @memberof Phaser.TileSprite +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + this.tilePosition.x = 0; + this.tilePosition.y = 0; + + return this; + +}; + +/** +* Changes the texture being rendered by this TileSprite. +* Causes a texture refresh to take place on the next render. +* +* @method Phaser.TileSprite#setTexture +* @memberof Phaser.TileSprite +* @param {PIXI.Texture} texture - The texture to apply to this TileSprite. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.setTexture = function (texture) { + + if (this.texture !== texture) + { + this.texture = texture; + this.refreshTexture = true; + this.cachedTint = 0xFFFFFF; + } + + return this; + +}; + +/** +* Renders the TileSprite using the WebGL Renderer. +* +* @private +* @method Phaser.TileSprite#_renderWebGL +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + 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.refreshTexture) + { + this.generateTilingTexture(true, renderSession); + + if (this.tilingTexture) + { + if (this.tilingTexture.needsUpdate) + { + this.tilingTexture.baseTexture.textureIndex = this.texture.baseTexture.textureIndex; + renderSession.renderer.updateTexture(this.tilingTexture.baseTexture); + this.tilingTexture.needsUpdate = false; + } + } + else + { + return; + } + } + + renderSession.spriteBatch.renderTilingSprite(this); + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + var restartBatch = false; + + if (this._filters) + { + restartBatch = true; + renderSession.spriteBatch.stop(); + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + if (!restartBatch) + { + renderSession.spriteBatch.stop(); + } + + renderSession.maskManager.popMask(this._mask, renderSession); + } + + if (restartBatch) + { + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the TileSprite using the Canvas Renderer. +* +* @private +* @method Phaser.TileSprite#_renderCanvas +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + var context = renderSession.context; + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + context.globalAlpha = this.worldAlpha; + + var wt = this.worldTransform; + var resolution = renderSession.resolution; + var tx = (wt.tx * resolution) + renderSession.shakeX; + var ty = (wt.ty * resolution) + renderSession.shakeY; + + context.setTransform(wt.a * resolution, wt.b * resolution, wt.c * resolution, wt.d * resolution, tx, ty); + + if (this.tint !== 0xFFFFFF && (this.texture.requiresReTint || this.cachedTint !== this.tint)) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + this.refreshTexture = true; + } + + if (this.refreshTexture) + { + this.generateTilingTexture(false, renderSession); + + if (this.tilingTexture) + { + this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat'); + } + else + { + return; + } + } + + var sessionBlendMode = renderSession.currentBlendMode; + + // Check blend mode + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + var tilePosition = this.tilePosition; + var tileScale = this.tileScale; + + tilePosition.x %= this.tilingTexture.baseTexture.width; + tilePosition.y %= this.tilingTexture.baseTexture.height; + + // Translate + context.scale(tileScale.x, tileScale.y); + context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height)); + + context.fillStyle = this.tilePattern; + + tx = -tilePosition.x; + ty = -tilePosition.y; + + var tw = this._width / tileScale.x; + var th = this._height / tileScale.y; + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + tx |= 0; + ty |= 0; + tw |= 0; + th |= 0; + } + + context.fillRect(tx, ty, tw, th); + + // Translate back again + context.scale(1 / tileScale.x, 1 / tileScale.y); + context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height)); + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + // Reset blend mode + if (sessionBlendMode !== this.blendMode) + { + renderSession.currentBlendMode = sessionBlendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode]; + } + +}; + +/** +* Override the Sprite method. +* +* @private +* @method Phaser.TileSprite#onTextureUpdate +* @memberof Phaser.TileSprite +*/ +Phaser.TileSprite.prototype.onTextureUpdate = function () { + + // overriding the sprite version of this! + +}; + +/** +* Internal method that generates a new tiling texture. +* +* @method Phaser.TileSprite#generateTilingTexture +* @memberof Phaser.TileSprite +* @param {boolean} forcePowerOfTwo - Whether we want to force the texture to be a power of two +*/ +Phaser.TileSprite.prototype.generateTilingTexture = function (forcePowerOfTwo) { + + if (!this.texture.baseTexture.hasLoaded) + { + return; + } + + var texture = this.texture; + var frame = texture.frame; + + var targetWidth = this._frame.sourceSizeW || this._frame.width; + var targetHeight = this._frame.sourceSizeH || this._frame.height; + + var dx = 0; + var dy = 0; + + if (this._frame.trimmed) + { + dx = this._frame.spriteSourceSizeX; + dy = this._frame.spriteSourceSizeY; + } + + if (forcePowerOfTwo) + { + targetWidth = Phaser.Math.getNextPowerOfTwo(targetWidth); + targetHeight = Phaser.Math.getNextPowerOfTwo(targetHeight); + } + + if (this.canvasBuffer) + { + this.canvasBuffer.resize(targetWidth, targetHeight); + this.tilingTexture.baseTexture.width = targetWidth; + this.tilingTexture.baseTexture.height = targetHeight; + this.tilingTexture.needsUpdate = true; + } + else + { + this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight); + this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas); + this.tilingTexture.isTiling = true; + this.tilingTexture.needsUpdate = true; + } + + if (this.textureDebug) + { + this.canvasBuffer.context.strokeStyle = '#00ff00'; + this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight); + } + + // If a sprite sheet we need this: + var w = texture.crop.width; + var h = texture.crop.height; + + if (w !== targetWidth || h !== targetHeight) + { + w = targetWidth; + h = targetHeight; + } + + var targetTexture = this.tintedTexture ? this.tintedTexture : texture.baseTexture.source; + + this.canvasBuffer.context.drawImage( + targetTexture, + texture.crop.x, + texture.crop.y, + texture.crop.width, + texture.crop.height, + dx, + dy, + w, + h + ); + + this.tileScaleOffset.x = frame.width / targetWidth; + this.tileScaleOffset.y = frame.height / targetHeight; + + this.refreshTexture = false; + + this.tilingTexture.baseTexture._powerOf2 = true; + +}; + +/** +* Returns the framing rectangle of the Tile Sprite. +* +* @method Phaser.TileSprite#getBounds +* @memberof Phaser.TileSprite +* @return {Phaser.Rectangle} The bounds of the Tile Sprite. +*/ +Phaser.TileSprite.prototype.getBounds = function () { + + var width = this._width; + var height = this._height; + + var w0 = width * (1 - this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1 - this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = (a * w1) + (c * h1) + tx; + var y1 = (d * h1) + (b * w1) + ty; + + var x2 = (a * w0) + (c * h1) + tx; + var y2 = (d * h1) + (b * w0) + ty; + + var x3 = (a * w0) + (c * h0) + tx; + var y3 = (d * h0) + (b * w0) + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // TODO: This is surely always undefined? As it's not set anywhere in the parent objects + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* The width of the sprite, setting this will actually modify the scale to achieve the value set +* +* @property width +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'width', { + + get: function () { + + return this._width; + + }, + + set: function (value) { + + this._width = value; + + } + +}); + +/** +* The height of the TilingSprite, setting this will actually modify the scale to achieve the value set +* +* @property height +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'height', { + + get: function () { + + return this._height; + + }, + + set: function (value) { + + this._height = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The CanvasPool is a global static object, that allows Phaser to recycle and pool Canvas DOM elements. +* +* @class Phaser.CanvasPool +* @static +*/ +Phaser.CanvasPool = { + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @method Phaser.CanvasPool.create + * @static + * @param {any} parent - The parent of the canvas element. + * @param {number} width - The width of the canvas element. + * @param {number} height - The height of the canvas element. + * @return {HTMLCanvasElement} The canvas element. + */ + create: function (parent, width, height) { + + var idx = Phaser.CanvasPool.getFirst(); + var canvas; + + if (idx === -1) + { + var container = { + parent: parent, + canvas: document.createElement('canvas') + }; + + Phaser.CanvasPool.pool.push(container); + + canvas = container.canvas; + } + else + { + Phaser.CanvasPool.pool[idx].parent = parent; + + canvas = Phaser.CanvasPool.pool[idx].canvas; + } + + if (width !== undefined) + { + canvas.width = width; + canvas.height = height; + } + + return canvas; + + }, + + /** + * Gets the first free canvas index from the pool. + * + * @static + * @method Phaser.CanvasPool.getFirst + * @return {number} + */ + getFirst: function () { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + return i; + } + } + + return -1; + + }, + + /** + * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.remove + * @param {any} parent - The parent of the canvas element. + */ + remove: function (parent) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent === parent) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Looks up a canvas based on its type, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.removeByCanvas + * @param {HTMLCanvasElement} canvas - The canvas element to remove. + */ + removeByCanvas: function (canvas) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].canvas === canvas) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Gets the total number of used canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getTotal + * @return {number} The number of in-use (parented) canvas elements in the pool. + */ + getTotal: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent) + { + c++; + } + } + + return c; + + }, + + /** + * Gets the total number of free canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getFree + * @return {number} The number of free (un-parented) canvas elements in the pool. + */ + getFree: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + c++; + } + } + + return c; + + }, + + + /** + * Prints in-use, free, and total counts to console.log. + * + * @static + * @method Phaser.CanvasPool.log + */ + log: function () { + + console.log('CanvasPool: %s used, %s free, %s total', this.getTotal(), this.getFree(), this.pool.length); + + } + +}; + +/** + * The pool into which the canvas elements are placed. + * + * @property pool + * @type Array + * @static + */ +Phaser.CanvasPool.pool = []; + + +/** + * The total number of canvas elements in the {@link Phaser.CanvasPool.pool pool}. + * + * @property length + * @type number + * @static + * @readonly + */ +Object.defineProperty(Phaser.CanvasPool, 'length', { + get: function () { + return this.pool.length; + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}. +* +* This class represents a singleton object that can be accessed directly as `game.device` +* (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it. +* +* Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization +* occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase. +* Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal, e.g., +* +* ```javascript +* Phaser.Device.onInitialized.add(function (device) { +* +* device.canvasBitBltShift = true; +* device.mspointer = false; +* +* }); +* +* var game = new Phaser.Game(); +* ``` +* +* When checking features using the exposed properties only the *truth-iness* of the value should be relied upon +* unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined` +* when indicating the lack of a feature. +* +* Uses elements from System.js by MrDoob and Modernizr +* +* @description +* It is not possible to instantiate the Device class manually. +* +* @class +* @protected +*/ +Phaser.Device = function () { + + /** + * The time the device became ready. + * @property {integer} deviceReadyAt + * @protected + */ + this.deviceReadyAt = 0; + + /** + * The time as which initialization has completed. + * @property {boolean} initialized + * @protected + */ + this.initialized = false; + + // Browser / Host / Operating System + + /** + * @property {boolean} desktop - Is running on a desktop? + * @default + */ + this.desktop = false; + + /** + * @property {boolean} iOS - Is running on iOS? + * @default + */ + this.iOS = false; + + /** + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @default + */ + this.iOSVersion = 0; + + /** + * @property {boolean} cocoonJS - Is the game running under CocoonJS? + * @default + */ + this.cocoonJS = false; + + /** + * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App? + * @default + */ + this.cocoonJSApp = false; + + /** + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @default + */ + this.cordova = false; + + /** + * @property {boolean} node - Is the game running under Node.js? + * @default + */ + this.node = false; + + /** + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @default + */ + this.nodeWebkit = false; + + /** + * @property {boolean} electron - Is the game running under GitHub Electron? + * @default + */ + this.electron = false; + + /** + * @property {boolean} ejecta - Is the game running under Ejecta? + * @default + */ + this.ejecta = false; + + /** + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @default + */ + this.crosswalk = false; + + /** + * @property {boolean} android - Is running on android? + * @default + */ + this.android = false; + + /** + * @property {boolean} chromeOS - Is running on chromeOS? + * @default + */ + this.chromeOS = false; + + /** + * @property {boolean} linux - Is running on linux? + * @default + */ + this.linux = false; + + /** + * @property {boolean} macOS - Is running on macOS? + * @default + */ + this.macOS = false; + + /** + * @property {boolean} windows - Is running on windows? + * @default + */ + this.windows = false; + + /** + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @default + */ + this.windowsPhone = false; + + // Features + + /** + * @property {boolean} canvas - Is canvas available? + * @default + */ + this.canvas = false; + + /** + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @default + */ + this.canvasBitBltShift = null; + + /** + * If the browser isn't capable of handling tinting with alpha this will be false. + * @property {boolean} canHandleAlpha + * @default + */ + this.canHandleAlpha = false; + + /** + * Whether or not the {@link http://caniuse.com/#feat=canvas-blending Canvas Blend Modes} are supported, consequently the ability to tint using the multiply method. + * + * Expect `false` in Internet Explorer <= 11. + * + * @property {boolean} canUseMultiply + * @default + */ + this.canUseMultiply = false; + + /** + * @property {boolean} webGL - Is webGL available? + * @default + */ + this.webGL = false; + + /** + * @property {boolean} file - Is file available? + * @default + */ + this.file = false; + + /** + * @property {boolean} fileSystem - Is fileSystem available? + * @default + */ + this.fileSystem = false; + + /** + * @property {boolean} localStorage - Is localStorage available? + * @default + */ + this.localStorage = false; + + /** + * @property {boolean} worker - Is worker available? + * @default + */ + this.worker = false; + + /** + * @property {boolean} css3D - Is css3D available? + * @default + */ + this.css3D = false; + + /** + * @property {boolean} pointerLock - Is Pointer Lock available? + * @default + */ + this.pointerLock = false; + + /** + * @property {boolean} typedArray - Does the browser support TypedArrays? + * @default + */ + this.typedArray = false; + + /** + * @property {boolean} vibration - Does the device support the Vibration API? + * @default + */ + this.vibration = false; + + /** + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @default + */ + this.getUserMedia = true; + + /** + * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true) + * @default + */ + this.quirksMode = false; + + // Input + + /** + * @property {boolean} touch - Is touch available? + * @default + */ + this.touch = false; + + /** + * @property {boolean} mspointer - Is mspointer available? + * @default + */ + this.mspointer = false; + + /** + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @default + * @protected + */ + this.wheelEvent = null; + + // Browser + + /** + * @property {boolean} arora - Set to true if running in Arora. + * @default + */ + this.arora = false; + + /** + * @property {boolean} chrome - Set to true if running in Chrome. + * @default + */ + this.chrome = false; + + /** + * @property {number} chromeVersion - If running in Chrome this will contain the major version number. + * @default + */ + this.chromeVersion = 0; + + /** + * @property {boolean} epiphany - Set to true if running in Epiphany. + * @default + */ + this.epiphany = false; + + /** + * @property {boolean} firefox - Set to true if running in Firefox. + * @default + */ + this.firefox = false; + + /** + * @property {number} firefoxVersion - If running in Firefox this will contain the major version number. + * @default + */ + this.firefoxVersion = 0; + + /** + * @property {boolean} ie - Set to true if running in Internet Explorer. + * @default + */ + this.ie = false; + + /** + * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. + * @default + */ + this.ieVersion = 0; + + /** + * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+) + * @default + */ + this.trident = false; + + /** + * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx} + * @default + */ + this.tridentVersion = 0; + + /** + * @property {boolean} edge - Set to true if running in Microsoft Edge browser. + * @default + */ + this.edge = false; + + /** + * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. + * @default + */ + this.mobileSafari = false; + + /** + * @property {boolean} midori - Set to true if running in Midori. + * @default + */ + this.midori = false; + + /** + * @property {boolean} opera - Set to true if running in Opera. + * @default + */ + this.opera = false; + + /** + * @property {boolean} safari - Set to true if running in Safari. + * @default + */ + this.safari = false; + + /** + * @property {number} safariVersion - If running in Safari this will contain the major version number. + * @default + */ + this.safariVersion = 0; + + /** + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @default + */ + this.webApp = false; + + /** + * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle) + * @default + */ + this.silk = false; + + // Audio + + /** + * @property {boolean} audioData - Are Audio tags available? + * @default + */ + this.audioData = false; + + /** + * @property {boolean} webAudio - Is the WebAudio API available? + * @default + */ + this.webAudio = false; + + /** + * @property {boolean} ogg - Can this device play ogg files? + * @default + */ + this.ogg = false; + + /** + * @property {boolean} opus - Can this device play opus files? + * @default + */ + this.opus = false; + + /** + * @property {boolean} mp3 - Can this device play mp3 files? + * @default + */ + this.mp3 = false; + + /** + * @property {boolean} wav - Can this device play wav files? + * @default + */ + this.wav = false; + + /** + * Can this device play m4a files? + * @property {boolean} m4a - True if this device can play m4a files. + * @default + */ + this.m4a = false; + + /** + * @property {boolean} webm - Can this device play webm files? + * @default + */ + this.webm = false; + + /** + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @default + */ + this.dolby = false; + + // Video + + /** + * @property {boolean} oggVideo - Can this device play ogg video files? + * @default + */ + this.oggVideo = false; + + /** + * @property {boolean} h264Video - Can this device play h264 mp4 video files? + * @default + */ + this.h264Video = false; + + /** + * @property {boolean} mp4Video - Can this device play h264 mp4 video files? + * @default + */ + this.mp4Video = false; + + /** + * @property {boolean} webmVideo - Can this device play webm video files? + * @default + */ + this.webmVideo = false; + + /** + * @property {boolean} vp9Video - Can this device play vp9 video files? + * @default + */ + this.vp9Video = false; + + /** + * @property {boolean} hlsVideo - Can this device play hls video files? + * @default + */ + this.hlsVideo = false; + + // Device + + /** + * @property {boolean} iPhone - Is running on iPhone? + * @default + */ + this.iPhone = false; + + /** + * @property {boolean} iPhone4 - Is running on iPhone4? + * @default + */ + this.iPhone4 = false; + + /** + * @property {boolean} iPad - Is running on iPad? + * @default + */ + this.iPad = false; + + // Device features + + /** + * @property {number} pixelRatio - PixelRatio of the host device? + * @default + */ + this.pixelRatio = 0; + + /** + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @default + */ + this.littleEndian = false; + + /** + * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`. + * @default + */ + this.LITTLE_ENDIAN = false; + + /** + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @default + */ + this.support32bit = false; + + /** + * @property {boolean} fullscreen - Does the browser support the Full Screen API? + * @default + */ + this.fullscreen = false; + + /** + * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it. + * @default + */ + this.requestFullscreen = ''; + + /** + * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @default + */ + this.cancelFullscreen = ''; + + /** + * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @default + */ + this.fullscreenKeyboard = false; + +}; + +// Device is really a singleton/static entity; instantiate it +// and add new methods directly sans-prototype. +Phaser.Device = new Phaser.Device(); + +/** +* This signal is dispatched after device initialization occurs but before any of the ready +* callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked. +* +* Local "patching" for a particular device can/should be done in this event. +* +* _Note_: This signal is removed after the device has been readied; if a handler has not been +* added _before_ `new Phaser.Game(..)` it is probably too late. +* +* @type {?Phaser.Signal} +* @static +*/ +Phaser.Device.onInitialized = new Phaser.Signal(); + +/** +* Add a device-ready handler and ensure the device ready sequence is started. +* +* Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added, +* which is normally done automatically be calling `new Phaser.Game(..)`. +* +* The handler is invoked when the device is considered "ready", which may be immediately +* if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}. +* +* @method +* @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. +* @param {object} [context] - Context in which to invoke the handler +* @param {boolean} [nonPrimer=false] - If true the device ready check will not be started. +*/ +Phaser.Device.whenReady = function (callback, context, nonPrimer) { + + var readyCheck = this._readyCheck; + + if (this.deviceReadyAt || !readyCheck) + { + callback.call(context, this); + } + else if (readyCheck._monitor || nonPrimer) + { + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + } + else + { + readyCheck._monitor = readyCheck.bind(this); + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + + var cordova = typeof window.cordova !== 'undefined'; + var cocoonJS = navigator['isCocoonJS']; + + if (document.readyState === 'complete' || document.readyState === 'interactive') + { + // Why is there an additional timeout here? + window.setTimeout(readyCheck._monitor, 0); + } + else if (cordova && !cocoonJS) + { + // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + // Cordova, but NOT Cocoon? + document.addEventListener('deviceready', readyCheck._monitor, false); + } + else + { + document.addEventListener('DOMContentLoaded', readyCheck._monitor, false); + window.addEventListener('load', readyCheck._monitor, false); + } + } + +}; + +/** +* Internal method used for checking when the device is ready. +* This function is removed from Phaser.Device when the device becomes ready. +* +* @method +* @private +*/ +Phaser.Device._readyCheck = function () { + + var readyCheck = this._readyCheck; + + if (!document.body) + { + window.setTimeout(readyCheck._monitor, 20); + } + else if (!this.deviceReadyAt) + { + this.deviceReadyAt = Date.now(); + + document.removeEventListener('deviceready', readyCheck._monitor); + document.removeEventListener('DOMContentLoaded', readyCheck._monitor); + window.removeEventListener('load', readyCheck._monitor); + + this._initialize(); + this.initialized = true; + + this.onInitialized.dispatch(this); + + var item; + while ((item = readyCheck._queue.shift())) + { + var callback = item[0]; + var context = item[1]; + callback.call(context, this); + } + + // Remove no longer useful methods and properties. + this._readyCheck = null; + this._initialize = null; + this.onInitialized = null; + } + +}; + +/** +* Internal method to initialize the capability checks. +* This function is removed from Phaser.Device once the device is initialized. +* +* @method +* @private +*/ +Phaser.Device._initialize = function () { + + var device = this; + + /** + * Check which OS is game running on. + */ + function _checkOS () { + + var ua = navigator.userAgent; + + if (/Playstation Vita/.test(ua)) + { + device.vita = true; + } + else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua)) + { + device.kindle = true; + // This will NOT detect early generations of Kindle Fire, I think there is no reliable way... + // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true" + } + else if (/Android/.test(ua)) + { + device.android = true; + } + else if (/CrOS/.test(ua)) + { + device.chromeOS = true; + } + else if (/iP[ao]d|iPhone/i.test(ua)) + { + device.iOS = true; + (navigator.appVersion).match(/OS (\d+)/); + device.iOSVersion = parseInt(RegExp.$1, 10); + } + else if (/Linux/.test(ua)) + { + device.linux = true; + } + else if (/Mac OS/.test(ua)) + { + device.macOS = true; + } + else if (/Windows/.test(ua)) + { + device.windows = true; + } + + if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua)) + { + device.android = false; + device.iOS = false; + device.macOS = false; + device.windows = true; + device.windowsPhone = true; + } + + var silk = /Silk/.test(ua); // detected in browsers + + if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS) + { + device.desktop = true; + } + + // Windows Phone / Table reset + if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) + { + device.desktop = false; + } + + } + + /** + * Checks if the browser correctly supports putImageData alpha channels. + * If the browser isn't capable of handling tinting with alpha, `Device.canHandleAlpha` will be false. + * Also checks whether the Canvas BlendModes are supported by the current browser for drawImage. + */ + function _checkCanvasFeatures () { + + var canvas = Phaser.CanvasPool.create(this, 6, 1); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgba(10, 20, 30, 0.5)'; + + // Draw a single pixel + context.fillRect(0, 0, 1, 1); + + // Get the color values + var s1 = context.getImageData(0, 0, 1, 1); + + if (s1) + { + // Plot them to x2 + context.putImageData(s1, 1, 0); + + // Get those values + var s2 = context.getImageData(1, 0, 1, 1); + + // Compare and set + device.canHandleAlpha = ( + s2.data[0] === s1.data[0] && + s2.data[1] === s1.data[1] && + s2.data[2] === s1.data[2] && + s2.data[3] === s1.data[3] + ); + } + + // Checks whether the Canvas BlendModes are supported by the current browser for drawImage. + context.globalCompositeOperation = 'multiply'; + device.canUseMultiply = (context.globalCompositeOperation === 'multiply'); + + Phaser.CanvasPool.removeByCanvas(canvas); + + PIXI.CanvasTinter.tintMethod = (device.canUseMultiply) ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel; + + } + + /** + * Check HTML5 features of the host environment. + */ + function _checkFeatures () { + + device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS; + + try { + device.localStorage = !!localStorage.getItem; + } catch (error) { + device.localStorage = false; + } + + device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; + device.fileSystem = !!window['requestFileSystem']; + + device.webGL = !!window.WebGLRenderingContext; + + device.worker = !!window['Worker']; + + device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; + + device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL; + + // Older versions of firefox (< 21) apparently claim support but user media does not actually work + if (device.firefox && device.firefoxVersion < 21) + { + device.getUserMedia = false; + } + + // TODO: replace canvasBitBltShift detection with actual feature check + + // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it + // is safer to not try and use the fast copy-over method. + if (!device.iOS && (device.ie || device.firefox || device.chrome)) + { + device.canvasBitBltShift = true; + } + + // Known not to work + if (device.safari || device.mobileSafari) + { + device.canvasBitBltShift = false; + } + + } + + /** + * Checks/configures various input. + */ + function _checkInput () { + + if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1)) + { + device.touch = true; + } + + if (window.PointerEvent || window.MSPointerEvent || window.navigator.msPointerEnabled || window.navigator.pointerEnabled) + { + device.mspointer = true; + } + + if (!device.cocoonJS) + { + // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel + if ('onwheel' in window || (device.ie && 'WheelEvent' in window)) + { + // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ + device.wheelEvent = 'wheel'; + } + else if ('onmousewheel' in window) + { + // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. + device.wheelEvent = 'mousewheel'; + } + else if (device.firefox && 'MouseScrollEvent' in window) + { + // FF prior to 17. This should probably be scrubbed. + device.wheelEvent = 'DOMMouseScroll'; + } + } + + } + + /** + * Checks for support of the Full Screen API. + */ + function _checkFullScreenSupport () { + + var fs = [ + 'requestFullscreen', + 'requestFullScreen', + 'webkitRequestFullscreen', + 'webkitRequestFullScreen', + 'msRequestFullscreen', + 'msRequestFullScreen', + 'mozRequestFullScreen', + 'mozRequestFullscreen' + ]; + + var element = document.createElement('div'); + + for (var i = 0; i < fs.length; i++) + { + if (element[fs[i]]) + { + device.fullscreen = true; + device.requestFullscreen = fs[i]; + break; + } + } + + var cfs = [ + 'cancelFullScreen', + 'exitFullscreen', + 'webkitCancelFullScreen', + 'webkitExitFullscreen', + 'msCancelFullScreen', + 'msExitFullscreen', + 'mozCancelFullScreen', + 'mozExitFullscreen' + ]; + + if (device.fullscreen) + { + for (var i = 0; i < cfs.length; i++) + { + if (document[cfs[i]]) + { + device.cancelFullscreen = cfs[i]; + break; + } + } + } + + // Keyboard Input? + if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT']) + { + device.fullscreenKeyboard = true; + } + + } + + /** + * Check what browser is game running in. + */ + function _checkBrowser () { + + var ua = navigator.userAgent; + + if (/Arora/.test(ua)) + { + device.arora = true; + } + else if (/Edge\/\d+/.test(ua)) + { + device.edge = true; + } + else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.chrome = true; + device.chromeVersion = parseInt(RegExp.$1, 10); + } + else if (/Epiphany/.test(ua)) + { + device.epiphany = true; + } + else if (/Firefox\D+(\d+)/.test(ua)) + { + device.firefox = true; + device.firefoxVersion = parseInt(RegExp.$1, 10); + } + else if (/AppleWebKit/.test(ua) && device.iOS) + { + device.mobileSafari = true; + } + else if (/MSIE (\d+\.\d+);/.test(ua)) + { + device.ie = true; + device.ieVersion = parseInt(RegExp.$1, 10); + } + else if (/Midori/.test(ua)) + { + device.midori = true; + } + else if (/Opera/.test(ua)) + { + device.opera = true; + } + else if (/Safari\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.safari = true; + + if (/Version\/(\d+)\./.test(ua)) + { + device.safariVersion = parseInt(RegExp.$1, 10); + } + } + else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua)) + { + device.ie = true; + device.trident = true; + device.tridentVersion = parseInt(RegExp.$1, 10); + device.ieVersion = parseInt(RegExp.$3, 10); + } + + // Silk gets its own if clause because its ua also contains 'Safari' + if (/Silk/.test(ua)) + { + device.silk = true; + } + + // WebApp mode in iOS + if (navigator['standalone']) + { + device.webApp = true; + } + + if (typeof window.cordova !== 'undefined') + { + device.cordova = true; + } + + if (typeof process !== 'undefined' && typeof require !== 'undefined') + { + device.node = true; + } + + if (device.node && typeof process.versions === 'object') + { + device.nodeWebkit = !!process.versions['node-webkit']; + + device.electron = !!process.versions.electron; + } + + if (navigator['isCocoonJS']) + { + device.cocoonJS = true; + } + + if (device.cocoonJS) + { + try { + device.cocoonJSApp = (typeof CocoonJS !== 'undefined'); + } + catch(error) + { + device.cocoonJSApp = false; + } + } + + if (typeof window.ejecta !== 'undefined') + { + device.ejecta = true; + } + + if (/Crosswalk/.test(ua)) + { + device.crosswalk = true; + } + + } + + /** + * Check video support. + */ + function _checkVideo () { + + var videoElement = document.createElement("video"); + var result = false; + + try { + if (result = !!videoElement.canPlayType) + { + if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) + { + device.oggVideo = true; + } + + if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + device.h264Video = true; + device.mp4Video = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) + { + device.webmVideo = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) + { + device.vp9Video = true; + } + + if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + device.hlsVideo = true; + } + } + } catch (e) {} + } + + /** + * Check audio support. + */ + function _checkAudio () { + + device.audioData = !!(window['Audio']); + device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); + var audioElement = document.createElement('audio'); + var result = false; + + try { + if (result = !!audioElement.canPlayType) + { + if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) + { + device.ogg = true; + } + + if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) + { + device.opus = true; + } + + if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) + { + device.mp3 = true; + } + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) + { + device.wav = true; + } + + if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) + { + device.m4a = true; + } + + if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) + { + device.webm = true; + } + + if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') + { + if (device.edge) + { + device.dolby = true; + } + else if (device.safari && device.safariVersion >= 9) + { + if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)) + { + var major = parseInt(RegExp.$1, 10); + var minor = parseInt(RegExp.$2, 10); + + if ((major === 10 && minor >= 11) || major > 10) + { + device.dolby = true; + } + } + } + } + } + } catch (e) { + } + + } + + /** + * Check Little or Big Endian system. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsLittleEndian () { + + var a = new ArrayBuffer(4); + var b = new Uint8Array(a); + var c = new Uint32Array(a); + + b[0] = 0xa1; + b[1] = 0xb2; + b[2] = 0xc3; + b[3] = 0xd4; + + if (c[0] === 0xd4c3b2a1) + { + return true; + } + + if (c[0] === 0xa1b2c3d4) + { + return false; + } + else + { + // Could not determine endianness + return null; + } + + } + + /** + * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsUint8ClampedImageData () { + + if (Uint8ClampedArray === undefined) + { + return false; + } + + var elem = Phaser.CanvasPool.create(this, 1, 1); + var ctx = elem.getContext('2d'); + + if (!ctx) + { + return false; + } + + var image = ctx.createImageData(1, 1); + + Phaser.CanvasPool.remove(this); + + return image.data instanceof Uint8ClampedArray; + + } + + /** + * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess. + */ + function _checkDevice () { + + device.pixelRatio = window['devicePixelRatio'] || 1; + device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1; + device.iPhone4 = (device.pixelRatio === 2 && device.iPhone); + device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') !== -1; + + if (typeof Int8Array !== 'undefined') + { + device.typedArray = true; + } + else + { + device.typedArray = false; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') + { + device.littleEndian = _checkIsLittleEndian(); + device.LITTLE_ENDIAN = device.littleEndian; + } + + device.support32bit = (typeof ArrayBuffer !== 'undefined' && typeof Uint8ClampedArray !== 'undefined' && typeof Int32Array !== 'undefined' && device.littleEndian !== null && _checkIsUint8ClampedImageData()); + + navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; + + if (navigator.vibrate) + { + device.vibration = true; + } + + } + + /** + * Check whether the host environment support 3D CSS. + */ + function _checkCSS3D () { + + var el = document.createElement('p'); + var has3d; + var transforms = { + 'webkitTransform': '-webkit-transform', + 'OTransform': '-o-transform', + 'msTransform': '-ms-transform', + 'MozTransform': '-moz-transform', + 'transform': 'transform' + }; + + // Add it to the body to get the computed style. + document.body.insertBefore(el, null); + + for (var t in transforms) + { + if (el.style[t] !== undefined) + { + el.style[t] = "translate3d(1px,1px,1px)"; + has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]); + } + } + + document.body.removeChild(el); + device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none"); + + } + + // Run the checks + _checkOS(); + _checkBrowser(); + _checkAudio(); + _checkVideo(); + _checkCSS3D(); + _checkDevice(); + _checkFeatures(); + _checkCanvasFeatures(); + _checkFullScreenSupport(); + _checkInput(); + +}; + +/** +* Check whether the host environment can play audio. +* +* @method canPlayAudio +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.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 === 'opus' && this.opus) + { + return true; + } + else if (type === 'wav' && this.wav) + { + return true; + } + else if (type === 'webm' && this.webm) + { + return true; + } + else if (type === 'mp4' && this.dolby) + { + return true; + } + + return false; + +}; + +/** +* Check whether the host environment can play video files. +* +* @method canPlayVideo +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.canPlayVideo = function (type) { + + if (type === 'webm' && (this.webmVideo || this.vp9Video)) + { + return true; + } + else if (type === 'mp4' && (this.mp4Video || this.h264Video)) + { + return true; + } + else if ((type === 'ogg' || type === 'ogv') && this.oggVideo) + { + return true; + } + else if (type === 'mpeg' && this.hlsVideo) + { + return true; + } + + return false; + +}; + +/** + * Whether the device plays audio/video only in response to a user touch event. + * + * @method needsTouchUnlock + * @memberof Phaser.Device.prototype + * @return {boolean} + */ +Phaser.Device.needsTouchUnlock = function () { + return !!(!this.cocoonJS && (this.iOS || this.android) || (window.PhaserGlobal && window.PhaserGlobal.fakeiOSTouchLock)); +}; + +/** +* Detect if the host is a an Android Stock browser. +* This is available before the device "ready" event. +* +* Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. +* +* @example +* var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; +* +* @method isAndroidStockBrowser +* @memberof Phaser.Device.prototype +*/ +Phaser.Device.isAndroidStockBrowser = function () { + + var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/); + return matches && matches[1] < 537; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, +* including styles, offset and aspect ratio. +* +* @class Phaser.Canvas +* @static +*/ +Phaser.Canvas = { + + /** + * Creates a `canvas` DOM element. The element is not automatically added to the document. + * + * @method Phaser.Canvas.create + * @param {object} parent - The object that will own the canvas that is created. + * @param {number} [width=256] - The width of the canvas element. + * @param {number} [height=256] - The height of the canvas element.. + * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. + * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global. + * @return {HTMLCanvasElement} The newly created canvas element. + */ + create: function (parent, width, height, id, skipPool) { + + width = width || 256; + height = height || 256; + + var canvas = (skipPool) ? document.createElement('canvas') : Phaser.CanvasPool.create(parent, width, height); + + if (typeof id === 'string' && id !== '') + { + canvas.id = id; + } + + canvas.width = width; + canvas.height = height; + canvas.style.display = 'block'; + + return canvas; + + }, + + /** + * Sets the background color behind the canvas. This changes the canvas style property. + * + * @method Phaser.Canvas.setBackgroundColor + * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. + * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setBackgroundColor: function (canvas, color) { + + color = color || 'rgb(0,0,0)'; + + canvas.style.backgroundColor = color; + + return canvas; + + }, + + /** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @method Phaser.Canvas.setTouchAction + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @method Phaser.Canvas.setUserSelect + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. + * If no parent is given it will be added as a child of the document.body. + * + * @method Phaser.Canvas.addToDOM + * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM. + * @param {string|HTMLElement} parent - The DOM element to add the canvas to. + * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + addToDOM: function (canvas, parent, overflowHidden) { + + var target; + + if (overflowHidden === undefined) { overflowHidden = true; } + + if (parent) + { + if (typeof parent === 'string') + { + // hopefully an element ID + target = document.getElementById(parent); + } + else if (typeof parent === 'object' && parent.nodeType === 1) + { + // quick test for a HTMLelement + target = parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + target = document.body; + } + + if (overflowHidden && target.style) + { + target.style.overflow = 'hidden'; + } + + target.appendChild(canvas); + + return canvas; + + }, + + /** + * Removes the given canvas element from the DOM. + * + * @method Phaser.Canvas.removeFromDOM + * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM. + */ + removeFromDOM: function (canvas) { + + if (canvas.parentNode) + { + canvas.parentNode.removeChild(canvas); + } + + }, + + /** + * Sets the transform of the given canvas to the matrix values provided. + * + * @method Phaser.Canvas.setTransform + * @param {CanvasRenderingContext2D} context - The context to set the transform on. + * @param {number} translateX - The value to translate horizontally by. + * @param {number} translateY - The value to translate vertically by. + * @param {number} scaleX - The value to scale horizontally by. + * @param {number} scaleY - The value to scale vertically by. + * @param {number} skewX - The value to skew horizontaly by. + * @param {number} skewY - The value to skew vertically by. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) { + + context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); + + return context; + + }, + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @method Phaser.Canvas.setSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setSmoothingEnabled: function (context, value) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + context[s] = value; + } + + return context; + + }, + + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @method Phaser.Canvas.getSmoothingPrefix + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context. + */ + getSmoothingPrefix: function (context) { + + var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; + + for (var prefix in vendor) + { + var s = vendor[prefix] + 'mageSmoothingEnabled'; + + if (s in context) + { + return s; + } + } + + return null; + + }, + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * + * @method Phaser.Canvas.getSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to check for smoothing on. + * @return {boolean} True if the given context has image smoothing enabled, otherwise false. + */ + getSmoothingEnabled: function (context) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + return context[s]; + } + + }, + + /** + * Sets the CSS image-rendering property to `pixelated` or `crisp-edges`. + * This can remove blurring when the game canvas is scaled up. + * In some browsers this has no visible effect in WEBGL mode. + * Note that if this doesn't given the desired result then see the setSmoothingEnabled. + * + * @method Phaser.Canvas.setImageRenderingCrisp + * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. + * @return {HTMLCanvasElement} Returns the source canvas. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering + * @see https://caniuse.com/#feat=css-crisp-edges + */ + setImageRenderingCrisp: function (canvas) { + + var types = [ '-webkit-optimize-contrast', '-moz-crisp-edges', 'crisp-edges', 'pixelated' ]; + + for (var i = 0; i < types.length; i++) + { + canvas.style['image-rendering'] = types[i]; + } + + canvas.style.msInterpolationMode = 'nearest-neighbor'; + + return canvas; + + }, + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method Phaser.Canvas.setImageRenderingBicubic + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setImageRenderingBicubic: function (canvas) { + + canvas.style['image-rendering'] = 'auto'; + canvas.style.msInterpolationMode = 'bicubic'; + + return canvas; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Abstracts away the use of RAF or setTimeOut for the core game update loop. +* +* @class Phaser.RequestAnimationFrame +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available. +*/ +Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) { + + if (forceSetTimeOut === undefined) { forceSetTimeOut = false; } + + /** + * @property {Phaser.Game} game - The currently running game. + */ + this.game = game; + + /** + * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available. + */ + this.forceSetTimeOut = forceSetTimeOut; + + var vendors = [ + 'ms', + 'moz', + 'webkit', + 'o' + ]; + + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) + { + window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; + } + + /** + * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. + * @private + */ + this._isSetTimeOut = false; + + /** + * @property {function} _onLoop - The function called by the update. + * @private + */ + this._onLoop = null; + + /** + * @property {number} _timeOutID - The callback ID used when calling cancel. + * @private + */ + this._timeOutID = null; + +}; + +Phaser.RequestAnimationFrame.prototype = { + + /** + * Starts the requestAnimationFrame running or setTimeout if unavailable in browser + * @method Phaser.RequestAnimationFrame#start + */ + start: function () { + + this.isRunning = true; + + var _this = this; + + if (!window.requestAnimationFrame || this.forceSetTimeOut) + { + this._isSetTimeOut = true; + + this._onLoop = function () { + return _this.updateSetTimeout(); + }; + + this._timeOutID = window.setTimeout(this._onLoop, 0); + } + else + { + this._isSetTimeOut = false; + + this._onLoop = function (time) { + return _this.updateRAF(time); + }; + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the requestAnimationFrame + * @method Phaser.RequestAnimationFrame#updateRAF + */ + updateRAF: function (rafTime) { + + if (this.isRunning) + { + // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below) + this.game.update(Math.floor(rafTime)); + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the setTimeout. + * @method Phaser.RequestAnimationFrame#updateSetTimeout + */ + updateSetTimeout: function () { + + if (this.isRunning) + { + this.game.update(Date.now()); + + this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); + } + + }, + + /** + * Stops the requestAnimationFrame from running. + * @method Phaser.RequestAnimationFrame#stop + */ + stop: function () { + + if (this._isSetTimeOut) + { + clearTimeout(this._timeOutID); + } + else + { + window.cancelAnimationFrame(this._timeOutID); + } + + this.isRunning = false; + + }, + + /** + * Is the browser using setTimeout? + * @method Phaser.RequestAnimationFrame#isSetTimeOut + * @return {boolean} + */ + isSetTimeOut: function () { + return this._isSetTimeOut; + }, + + /** + * Is the browser using requestAnimationFrame? + * @method Phaser.RequestAnimationFrame#isRAF + * @return {boolean} + */ + isRAF: function () { + return (this._isSetTimeOut === false); + } + +}; + +Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of useful mathematical functions. +* +* These are normally accessed through `game.math`. +* +* @class Phaser.Math +* @static +* @see {@link Phaser.Utils} +* @see {@link Phaser.ArrayUtils} +*/ +Phaser.Math = { + + /** + * Twice PI. + * @property {number} Phaser.Math#PI2 + * @default ~6.283 + */ + PI2: Math.PI * 2, + + /** + * Half PI. + * @property {number} Phaser.Math#HALF_PI + * @default ~1.570 + */ + HALF_PI: Math.PI * 0.5, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#DEG_TO_RAD + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#RAD_TO_DEG + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * Convert degrees to radians. + * + * @method Phaser.Math#degToRad + * @param {number} degrees - Angle in degrees. + * @return {number} Angle in radians. + */ + degToRad: function (degrees) { + + return degrees * Phaser.Math.DEG_TO_RAD; + + }, + + /** + * Convert radians to degrees. + * + * @method Phaser.Math#radToDeg + * @param {number} radians - Angle in radians. + * @return {number} Angle in degrees + */ + radToDeg: function (radians) { + + return radians * Phaser.Math.RAD_TO_DEG; + + }, + + /** + * Given a number, this function returns the closest number that is a power of two. + * This function is from the Starling Framework. + * + * @method Phaser.Math#getNextPowerOfTwo + * @param {number} value - The value to get the closest power of two from. + * @return {number} The closest number that is a power of two. + */ + getNextPowerOfTwo: function (value) { + + if (value > 0 && (value & (value - 1)) === 0) + { + // http://goo.gl/D9kPj + return value; + } + else + { + var result = 1; + + while (result < value) + { + result <<= 1; + } + + return result; + } + + }, + + /** + * Checks if the given dimensions make a power of two texture. + * + * @method Phaser.Math#isPowerOfTwo + * @param {number} width - The width to check. + * @param {number} height - The height to check. + * @return {boolean} True if the width and height are a power of two. + */ + isPowerOfTwo: function (width, height) { + + return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); + + }, + + /** + * Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#random + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} A floating point number between min (inclusive) and max (exclusive). + */ + random: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + return (Math.random() * (max - min) + min); + + }, + + /** + * Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#between + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} An integer between min (inclusive) and max (inclusive). + */ + between: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + min = Math.ceil(min); + max = Math.floor(max); + + return Math.floor(Math.random() * (max - min + 1)) + min; + + }, + + /** + * Two number are fuzzyEqual if their difference is less than epsilon. + * + * @method Phaser.Math#fuzzyEqual + * @param {number} a - The first number to compare. + * @param {number} b - The second number to compare. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {boolean} True if |a-b|b+epsilon + */ + fuzzyGreaterThan: function (a, b, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return a > b - epsilon; + + }, + + /** + * Applies a fuzzy ceil to the given value. + * + * @method Phaser.Math#fuzzyCeil + * @param {number} val - The value to ceil. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} ceiling(val-epsilon) + */ + fuzzyCeil: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.ceil(val - epsilon); + + }, + + /** + * Applies a fuzzy floor to the given value. + * + * @method Phaser.Math#fuzzyFloor + * @param {number} val - The value to floor. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} floor(val+epsilon) + */ + fuzzyFloor: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.floor(val + epsilon); + + }, + + /** + * Averages all values passed to the function and returns the result. + * + * @method Phaser.Math#average + * @params {...number} The numbers to average + * @return {number} The average of all given values. + */ + average: function () { + + var sum = 0; + var len = arguments.length; + + for (var i = 0; i < len; i++) + { + sum += (+arguments[i]); + } + + return sum / len; + + }, + + /** + * @method Phaser.Math#shear + * @param {number} n + * @return {number} n mod 1 + */ + shear: function (n) { + + return n % 1; + + }, + + /** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. + * + * @method Phaser.Math#snapTo + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapTo: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.round(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. + * As will 14 snap to 10... but 16 will snap to 15. + * + * @method Phaser.Math#snapToFloor + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToFloor: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.floor(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. + * As will 14 will snap to 15... but 16 will snap to 20. + * + * @method Phaser.Math#snapToCeil + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToCeil: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.ceil(input / gap); + + return start + input; + + }, + + /** + * Round to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) === 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + * + * @method Phaser.Math#roundTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + roundTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.round(value * p) / p; + + }, + + /** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#floorTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + floorTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.floor(value * p) / p; + + }, + + /** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#ceilTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + ceilTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.ceil(value * p) / p; + + }, + + /** + * Rotates currentAngle towards targetAngle, taking the shortest rotation distance. + * The lerp argument is the amount to rotate by in this call. + * + * @method Phaser.Math#rotateToAngle + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * @return {number} The adjusted angle. + */ + rotateToAngle: function (currentAngle, targetAngle, lerp) { + + if (lerp === undefined) { lerp = 0.05; } + + if (currentAngle === targetAngle) + { + return currentAngle; + } + + if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (Phaser.Math.PI2 - lerp)) + { + currentAngle = targetAngle; + } + else + { + if (Math.abs(targetAngle - currentAngle) > Math.PI) + { + if (targetAngle < currentAngle) + { + targetAngle += Phaser.Math.PI2; + } + else + { + targetAngle -= Phaser.Math.PI2; + } + } + + if (targetAngle > currentAngle) + { + currentAngle += lerp; + } + else if (targetAngle < currentAngle) + { + currentAngle -= lerp; + } + } + + return currentAngle; + + }, + + /** + * Gets the shortest angle between `angle1` and `angle2`. + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method, and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * @method Phaser.Math#getShortestAngle + * @param {number} angle1 - The first angle. In the range -180 to 180. + * @param {number} angle2 - The second angle. In the range -180 to 180. + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ + getShortestAngle: function (angle1, angle2) { + + var difference = angle2 - angle1; + + if (difference === 0) + { + return 0; + } + + var times = Math.floor((difference - (-180)) / 360); + + return difference - (times * 360); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @method Phaser.Math#angleBetween + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetween: function (x1, y1, x2, y2) { + + return Math.atan2(y2 - y1, x2 - x1); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels + * down the screen. + * + * @method Phaser.Math#angleBetweenY + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetweenY: function (x1, y1, x2, y2) { + + return Math.atan2(x2 - x1, y2 - y1); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * @method Phaser.Math#angleBetweenPoints + * @param {Phaser.Point} point1 - The first point. + * @param {Phaser.Point} point2 - The second point. + * @return {number} The angle between the two points, in radians. + */ + angleBetweenPoints: function (point1, point2) { + + return Math.atan2(point2.y - point1.y, point2.x - point1.x); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * @method Phaser.Math#angleBetweenPointsY + * @param {Phaser.Point} point1 + * @param {Phaser.Point} point2 + * @return {number} The angle, in radians. + */ + angleBetweenPointsY: function (point1, point2) { + + return Math.atan2(point2.x - point1.x, point2.y - point1.y); + + }, + + /** + * Reverses an angle. + * @method Phaser.Math#reverseAngle + * @param {number} angleRad - The angle to reverse, in radians. + * @return {number} The reverse angle, in radians. + */ + reverseAngle: function (angleRad) { + + return this.normalizeAngle(angleRad + Math.PI, true); + + }, + + /** + * Normalizes an angle to the [0,2pi) range. + * @method Phaser.Math#normalizeAngle + * @param {number} angleRad - The angle to normalize, in radians. + * @return {number} The angle, fit within the [0,2pi] range, in radians. + */ + normalizeAngle: function (angleRad) { + + angleRad = angleRad % (2 * Math.PI); + return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI; + + }, + + /** + * Adds the given amount to the value, but never lets the value go over the specified maximum. + * + * @method Phaser.Math#maxAdd + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The new value. + */ + maxAdd: function (value, amount, max) { + + return Math.min(value + amount, max); + + }, + + /** + * Subtracts the given amount from the value, but never lets the value go below the specified minimum. + * + * @method Phaser.Math#minSub + * @param {number} value - The base value. + * @param {number} amount - The amount to subtract from the base value. + * @param {number} min - The minimum the value is allowed to be. + * @return {number} The new value. + */ + minSub: function (value, amount, min) { + + return Math.max(value - amount, min); + + }, + + /** + * Ensures that the value always stays between min and max, by wrapping the value around. + * + * If `max` is not larger than `min` the result is 0. + * + * @method Phaser.Math#wrap + * @param {number} value - The value to wrap. + * @param {number} min - The minimum the value is allowed to be. + * @param {number} max - The maximum the value is allowed to be, should be larger than `min`. + * @return {number} The wrapped value. + */ + wrap: function (value, min, max) { + + var range = max - min; + + if (range <= 0) + { + return 0; + } + + var result = (value - min) % range; + + if (result < 0) + { + result += range; + } + + return result + min; + + }, + + /** + * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. + * + * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. + * + * @method Phaser.Math#wrapValue + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The wrapped value. + */ + wrapValue: function (value, amount, max) { + + var diff; + value = Math.abs(value); + amount = Math.abs(amount); + max = Math.abs(max); + diff = (value + amount) % max; + + return diff; + + }, + + /** + * Returns true if the number given is odd. + * + * @method Phaser.Math#isOdd + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is odd. False if the given number is even. + */ + isOdd: function (n) { + + // Does not work with extremely large values + return !!(n & 1); + + }, + + /** + * Returns true if the number given is even. + * + * @method Phaser.Math#isEven + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is even. False if the given number is odd. + */ + isEven: function (n) { + + // Does not work with extremely large values + return !(n & 1); + + }, + + /** + * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.min` function when appropriate. + * + * @method Phaser.Math#min + * @return {number} The lowest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + 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; i < len; i++) + { + if (data[i] < data[min]) + { + min = i; + } + } + + return data[min]; + + }, + + /** + * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.max` function when appropriate. + * + * @method Phaser.Math#max + * @return {number} The largest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + max: function () { + + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + var data = arguments[0]; + } + else + { + var data = arguments; + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i] > data[max]) + { + max = i; + } + } + + return data[max]; + + }, + + /** + * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. + * It will find the lowest matching property value from the given objects. + * + * @method Phaser.Math#minProperty + * @return {number} The lowest value from those given. + */ + 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; i < len; i++) + { + if (data[i][property] < data[min][property]) + { + min = i; + } + } + + return data[min][property]; + + }, + + /** + * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. + * It will find the largest matching property value from the given objects. + * + * @method Phaser.Math#maxProperty + * @return {number} The largest value from those given. + */ + maxProperty: function (property) { + + if (arguments.length === 2 && typeof arguments[1] === 'object') + { + var data = arguments[1]; + } + else + { + var data = arguments.slice(1); + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i][property] > data[max][property]) + { + max = i; + } + } + + return data[max][property]; + + }, + + /** + * Keeps an angle value between -180 and +180; or -PI and PI if radians. + * + * @method Phaser.Math#wrapAngle + * @param {number} angle - The angle value to wrap + * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected. + * @return {number} The new angle value; will be the same as the input angle if it was within bounds. + */ + wrapAngle: function (angle, radians) { + + return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180); + + }, + + /** + * A Linear Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#linearInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + linearInterpolation: function (v, k) { + + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (k < 0) + { + return this.linear(v[0], v[1], f); + } + + if (k > 1) + { + return this.linear(v[m], v[m - 1], m - f); + } + + return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); + + }, + + /** + * A Bezier Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#bezierInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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; + + }, + + /** + * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#catmullRomInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + } + + }, + + /** + * Calculates a linear (interpolation) value over t. + * + * @method Phaser.Math#linear + * @param {number} p0 + * @param {number} p1 + * @param {number} t - A value between 0 and 1. + * @return {number} + */ + linear: function (p0, p1, t) { + + return (p1 - p0) * t + p0; + + }, + + /** + * @method Phaser.Math#bernstein + * @protected + * @param {number} n + * @param {number} i + * @return {number} + */ + bernstein: function (n, i) { + + return this.factorial(n) / this.factorial(i) / this.factorial(n - i); + + }, + + /** + * @method Phaser.Math#factorial + * @param {number} value - the number you want to evaluate + * @return {number} + */ + factorial: function (value) { + + if (value === 0) + { + return 1; + } + + var res = value; + + while(--value) + { + res *= value; + } + + return res; + + }, + + /** + * Calculates a catmum rom value. + * + * @method Phaser.Math#catmullRom + * @protected + * @param {number} p0 + * @param {number} p1 + * @param {number} p2 + * @param {number} p3 + * @param {number} t + * @return {number} + */ + catmullRom: function (p0, p1, p2, p3, t) { + + var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + + }, + + /** + * The absolute difference between two values. + * + * @method Phaser.Math#difference + * @param {number} a - The first value to check. + * @param {number} b - The second value to check. + * @return {number} The absolute difference between the two values. + */ + difference: function (a, b) { + + return Math.abs(a - b); + + }, + + /** + * Round to the next whole number _away_ from zero. + * + * @method Phaser.Math#roundAwayFromZero + * @param {number} value - Any number. + * @return {integer} The rounded value of that number. + */ + roundAwayFromZero: function (value) { + + // "Opposite" of truncate. + return (value > 0) ? Math.ceil(value) : Math.floor(value); + + }, + + /** + * Generate a sine and cosine table simultaneously and extremely quickly. + * The parameters allow you to specify the length, amplitude and frequency of the wave. + * This generator is fast enough to be used in real-time. + * Code based on research by Franky of scene.at + * + * @method Phaser.Math#sinCosGenerator + * @param {number} length - The length of the wave + * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} frequency - The frequency of the sine and cosine table data + * @return {{sin:number[], cos:number[]}} Returns the table data. + */ + sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) { + + if (sinAmplitude === undefined) { sinAmplitude = 1.0; } + if (cosAmplitude === undefined) { cosAmplitude = 1.0; } + if (frequency === undefined) { frequency = 1.0; } + + var sin = sinAmplitude; + var cos = cosAmplitude; + var frq = frequency * Math.PI / length; + + var cosTable = []; + var sinTable = []; + + for (var c = 0; c < length; c++) { + + cos -= sin * frq; + sin += cos * frq; + + cosTable[c] = cos; + sinTable[c] = sin; + + } + + return { sin: sinTable, cos: cosTable, length: length }; + + }, + + /** + * Returns the length of the hypotenuse connecting two segments of given lengths. + * + * @method Phaser.Math#hypot + * @param {number} a + * @param {number} b + * @return {number} The length of the hypotenuse connecting the given lengths. + */ + hypot: function (a, b) { + + return Math.sqrt(a * a + b * b); + + }, + + /** + * Returns the euclidian distance between the two given set of coordinates. + * + * @method Phaser.Math#distance + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance between the two sets of coordinates. + */ + distance: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Returns the euclidean distance squared between the two given set of + * coordinates (cuts out a square root operation before returning). + * + * @method Phaser.Math#distanceSq + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance squared between the two sets of coordinates. + */ + distanceSq: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return dx * dx + dy * dy; + + }, + + /** + * Returns the distance between the two given set of coordinates at the power given. + * + * @method Phaser.Math#distancePow + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} [pow=2] + * @return {number} The distance between the two sets of coordinates. + */ + distancePow: function (x1, y1, x2, y2, pow) { + + if (pow === undefined) { pow = 2; } + + return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); + + }, + + /** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @method Phaser.Math#clamp + * @param {float} v - The value to be clamped. + * @param {float} min - The minimum bounds. + * @param {float} max - The maximum bounds. + * @return {number} The clamped value. + */ + clamp: function (v, min, max) { + + if (v < min) + { + return min; + } + else if (max < v) + { + return max; + } + else + { + return v; + } + + }, + + /** + * Clamp `x` to the range `[a, Infinity)`. + * Roughly the same as `Math.max(x, a)`, except for NaN handling. + * + * @method Phaser.Math#clampBottom + * @param {number} x + * @param {number} a + * @return {number} + */ + clampBottom: function (x, a) { + + return x < a ? a : x; + + }, + + /** + * Checks if two values are within the given tolerance of each other. + * + * @method Phaser.Math#within + * @param {number} a - The first number to check + * @param {number} b - The second number to check + * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range. + * @return {boolean} True if a is <= tolerance of b. + * @see {@link Phaser.Math.fuzzyEqual} + */ + within: function (a, b, tolerance) { + + return (Math.abs(a - b) <= tolerance); + + }, + + /** + * Linear mapping from range to range + * + * @method Phaser.Math#mapLinear + * @param {number} x - The value to map + * @param {number} a1 - First endpoint of the range + * @param {number} a2 - Final endpoint of the range + * @param {number} b1 - First endpoint of the range + * @param {number} b2 - Final endpoint of the range + * @return {number} + */ + mapLinear: function (x, a1, a2, b1, b2) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + + }, + + /** + * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smoothstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smoothstep: function (x, min, max) { + + // Scale, bias and saturate x to 0..1 range + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + // Evaluate polynomial + return x * x * (3 - 2 * x); + + }, + + /** + * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smootherstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smootherstep: function (x, min, max) { + + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + return x * x * x * (x * (x * 6 - 15) + 10); + + }, + + /** + * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. + * + * This works differently from `Math.sign` for values of NaN and -0, etc. + * + * @method Phaser.Math#sign + * @param {number} x + * @return {integer} An integer in {-1, 0, 1} + */ + sign: function (x) { + + return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); + + }, + + /** + * Work out what percentage value `a` is of value `b` using the given base. + * + * @method Phaser.Math#percent + * @param {number} a - The value to work out the percentage for. + * @param {number} b - The value you wish to get the percentage of. + * @param {number} [base=0] - The base value. + * @return {number} The percentage a is of b, between 0 and 1. + */ + percent: function (a, b, base) { + + if (base === undefined) { base = 0; } + + if (a > b || base > b) + { + return 1; + } + else if (a < base || base > a) + { + return 0; + } + else + { + return (a - base) / b; + } + + } + +}; + +/* jshint noempty: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An extremely useful repeatable random data generator. +* +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. +* +* The random number genererator is based on the Alea PRNG, but is modified. +* - https://github.com/coverslide/node-alea +* - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror +* - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404) +* +* @class Phaser.RandomDataGenerator +* @constructor +* @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}). +*/ +Phaser.RandomDataGenerator = function (seeds) { + + if (seeds === undefined) { seeds = []; } + + /** + * @property {number} c - Internal var. + * @private + */ + this.c = 1; + + /** + * @property {number} s0 - Internal var. + * @private + */ + this.s0 = 0; + + /** + * @property {number} s1 - Internal var. + * @private + */ + this.s1 = 0; + + /** + * @property {number} s2 - Internal var. + * @private + */ + this.s2 = 0; + + if (typeof seeds === 'string') + { + this.state(seeds); + } + else + { + this.sow(seeds); + } + +}; + +Phaser.RandomDataGenerator.prototype = { + + /** + * Private random helper. + * + * @method Phaser.RandomDataGenerator#rnd + * @private + * @return {number} + */ + rnd: function () { + + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + + return this.s2; + }, + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.RandomDataGenerator#sow + * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used. + */ + sow: function (seeds) { + + // Always reset to default seed + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + this.c = 1; + + if (!seeds) + { + return; + } + + // Apply any seeds + for (var i = 0; i < seeds.length && (seeds[i] != null); i++) + { + var 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); + } + + }, + + /** + * Internal method that creates a seed hash. + * + * @method Phaser.RandomDataGenerator#hash + * @private + * @param {any} data + * @return {number} hashed value. + */ + hash: function (data) { + + var h, i, n; + n = 0xefc8249d; + data = data.toString(); + + for (i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } + + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + + }, + + /** + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#integer + * @return {number} A random integer between 0 and 2^32. + */ + integer: function() { + + return this.rnd.apply(this) * 0x100000000;// 2^32 + + }, + + /** + * Returns a random real number between 0 and 1. + * + * @method Phaser.RandomDataGenerator#frac + * @return {number} A random real number between 0 and 1. + */ + frac: function() { + + return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 + + }, + + /** + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#real + * @return {number} A random real number between 0 and 2^32. + */ + real: function() { + + return this.integer() + this.frac(); + + }, + + /** + * Returns a random integer between and including min and max. + * + * @method Phaser.RandomDataGenerator#integerInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + integerInRange: function (min, max) { + + return Math.floor(this.realInRange(0, max - min + 1) + min); + + }, + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.RandomDataGenerator#between + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + between: function (min, max) { + + return this.integerInRange(min, max); + + }, + + /** + * Returns a random real number between min and max. + * + * @method Phaser.RandomDataGenerator#realInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + realInRange: function (min, max) { + + return this.frac() * (max - min) + min; + + }, + + /** + * Returns a random real number between -1 and 1. + * + * @method Phaser.RandomDataGenerator#normal + * @return {number} A random real number between -1 and 1. + */ + normal: function () { + + return 1 - 2 * this.frac(); + + }, + + /** + * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 + * + * @method Phaser.RandomDataGenerator#uuid + * @return {string} A valid RFC4122 version4 ID hex string + */ + 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; + + }, + + /** + * Returns a random member of `array`. + * + * @method Phaser.RandomDataGenerator#pick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + pick: function (ary) { + + return ary[this.integerInRange(0, ary.length - 1)]; + + }, + + /** + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.RandomDataGenerator#sign + * @return {number} -1 or +1. + */ + sign: function () { + + return this.pick([-1, 1]); + + }, + + /** + * Returns a random member of `array`, favoring the earlier entries. + * + * @method Phaser.RandomDataGenerator#weightedPick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + weightedPick: function (ary) { + + return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)]; + + }, + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.RandomDataGenerator#timestamp + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random timestamp between min and max. + */ + timestamp: function (min, max) { + + return this.realInRange(min || 946684800000, max || 1577862000000); + + }, + + /** + * Returns a random angle between -180 and 180. + * + * @method Phaser.RandomDataGenerator#angle + * @return {number} A random number between -180 and 180. + */ + angle: function() { + + return this.integerInRange(-180, 180); + + }, + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.RandomDataGenerator#state + * @param {string} [state] - Generator state to be set. + * @return {string} The current state of the generator. + */ + state: function (state) { + + if (typeof state === 'string' && state.match(/^!rnd/)) + { + state = state.split(','); + + this.c = parseFloat(state[1]); + this.s0 = parseFloat(state[2]); + this.s1 = parseFloat(state[3]); + this.s2 = parseFloat(state[4]); + } + + return ['!rnd', this.c, this.s0, this.s1, this.s2].join(','); + + } + +}; + +Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator; + +/** + * @author Timo Hausmann + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** +* A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. +* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. +* Original version at https://github.com/timohausmann/quadtree-js/ +* +* @class Phaser.QuadTree +* @constructor +* @param {number} x - The top left coordinate of the quadtree. +* @param {number} y - The top left coordinate of the quadtree. +* @param {number} width - The width of the quadtree in pixels. +* @param {number} height - The height of the quadtree in pixels. +* @param {number} [maxObjects=10] - The maximum number of objects per node. +* @param {number} [maxLevels=4] - The maximum number of levels to iterate to. +* @param {number} [level=0] - Which level is this? +*/ +Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) { + + /** + * @property {number} maxObjects - The maximum number of objects per node. + * @default + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - The maximum number of levels to break down to. + * @default + */ + this.maxLevels = 4; + + /** + * @property {number} level - The current level. + */ + this.level = 0; + + /** + * @property {object} bounds - Object that contains the quadtree bounds. + */ + this.bounds = {}; + + /** + * @property {array} objects - Array of quadtree children. + */ + this.objects = []; + + /** + * @property {array} nodes - Array of associated child nodes. + */ + this.nodes = []; + + /** + * @property {array} _empty - Internal empty array. + * @private + */ + this._empty = []; + + this.reset(x, y, width, height, maxObjects, maxLevels, level); + +}; + +Phaser.QuadTree.prototype = { + + /** + * Resets the QuadTree. + * + * @method Phaser.QuadTree#reset + * @param {number} x - The top left coordinate of the quadtree. + * @param {number} y - The top left coordinate of the quadtree. + * @param {number} width - The width of the quadtree in pixels. + * @param {number} height - The height of the quadtree in pixels. + * @param {number} [maxObjects=10] - The maximum number of objects per node. + * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. + * @param {number} [level=0] - Which level is this? + */ + 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; + + }, + + /** + * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. + * + * @method Phaser.QuadTree#populate + * @param {Phaser.Group} group - The Group to add to the quadtree. + */ + populate: function (group) { + + group.forEach(this.populateHandler, this, true); + + }, + + /** + * Handler for the populate method. + * + * @method Phaser.QuadTree#populateHandler + * @param {Phaser.Sprite|object} sprite - The Sprite to check. + */ + populateHandler: function (sprite) { + + if (sprite.body && sprite.exists) + { + this.insert(sprite.body); + } + + }, + + /** + * Split the node into 4 subnodes + * + * @method Phaser.QuadTree#split + */ + split: function () { + + // top right node + this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // top left node + this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom left node + this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom right node + this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + }, + + /** + * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. + * + * @method Phaser.QuadTree#insert + * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. + */ + insert: function (body) { + + var i = 0; + var index; + + // if we have subnodes ... + 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.level < this.maxLevels) + { + // Split if we don't already have subnodes + if (this.nodes[0] == null) + { + this.split(); + } + + // Add objects to subnodes + while (i < this.objects.length) + { + index = this.getIndex(this.objects[i]); + + if (index !== -1) + { + // this is expensive - see what we can do about it + this.nodes[index].insert(this.objects.splice(i, 1)[0]); + } + else + { + i++; + } + } + } + + }, + + /** + * Determine which node the object belongs to. + * + * @method Phaser.QuadTree#getIndex + * @param {Phaser.Rectangle|object} rect - The bounds in which to check. + * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. + */ + getIndex: function (rect) { + + // default is that rect doesn't fit, i.e. it straddles the internal quadrants + var index = -1; + + if (rect.x < this.bounds.right && rect.right < this.bounds.right) + { + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-left quadrant of this quadtree + index = 1; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-left quadrant of this quadtree + index = 2; + } + } + else if (rect.x > this.bounds.right) + { + // rect can completely fit within the right quadrants + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-right quadrant of this quadtree + index = 0; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-right quadrant of this quadtree + index = 3; + } + } + + return index; + + }, + + /** + * Return all objects that could collide with the given Sprite or Rectangle. + * + * @method Phaser.QuadTree#retrieve + * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle. + * @return {array} - Array with all detected objects. + */ + 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 rect fits into a subnode .. + if (index !== -1) + { + returnObjects = returnObjects.concat(this.nodes[index].retrieve(source)); + } + else + { + // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed) + 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 the quadtree. + * @method Phaser.QuadTree#clear + */ + 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; + +/** +* Javascript QuadTree +* @version 1.0 +* +* @version 1.3, March 11th 2014 +* @author Richard Davey +* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked +* it massively to add node indexing, removed lots of temp. var creation and significantly +* increased performance as a result. +* +* Original version at https://github.com/timohausmann/quadtree-js/ +*/ + +/** +* @copyright © 2012 Timo Hausmann +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. +* +* @class Phaser.Net +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Net = function (game) { + + this.game = game; + +}; + +Phaser.Net.prototype = { + + /** + * Returns the hostname given by the browser. + * + * @method Phaser.Net#getHostName + * @return {string} + */ + getHostName: function () { + + if (window.location && window.location.hostname) { + return window.location.hostname; + } + + return null; + + }, + + /** + * Compares the given domain name against the hostname of the browser containing the game. + * If the domain name is found it returns true. + * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. + * Do not include 'http://' at the start. + * + * @method Phaser.Net#checkDomainName + * @param {string} domain + * @return {boolean} true if the given domain fragment can be found in the window.location.hostname + */ + checkDomainName: function (domain) { + return window.location.hostname.indexOf(domain) !== -1; + }, + + /** + * Updates a value on the Query String and returns it in full. + * If the value doesn't already exist it is set. + * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. + * Optionally you can redirect to the new url, or just return it as a string. + * + * @method Phaser.Net#updateQueryString + * @param {string} key - The querystring key to update. + * @param {string} value - The new value to be set. If it already exists it will be replaced. + * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. + * @param {string} url - The URL to modify. If none is given it uses window.location.href. + * @return {string} If redirect is false then the modified url and query string is returned. + */ + updateQueryString: function (key, value, redirect, url) { + + if (redirect === undefined) { redirect = false; } + if (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; + } + + }, + + /** + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#getQueryString + * @param {string} [parameter=''] - If specified this will return just the value for that key. + * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. + */ + getQueryString: function (parameter) { + + if (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 && parameter === this.decodeURI(key[0])) + { + return this.decodeURI(key[1]); + } + else + { + output[this.decodeURI(key[0])] = this.decodeURI(key[1]); + } + } + } + + return output; + + }, + + /** + * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and + * decodes it, replacing \ with spaces in the return. Used internally by the Net classes. + * + * @method Phaser.Net#decodeURI + * @param {string} value - The URI component to be decoded. + * @return {string} The decoded value. + */ + decodeURI: function (value) { + return decodeURIComponent(value.replace(/\+/g, " ")); + } + +}; + +Phaser.Net.prototype.constructor = Phaser.Net; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. +* Tweens are hooked into the game clock and pause system, adjusting based on the game state. +* +* TweenManager is based heavily on tween.js by http://soledadpenades.com. +* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. +* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. +* Please see https://github.com/sole/tween.js for a full list of contributors. +* +* @class Phaser.TweenManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.TweenManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * @property {boolean} frameBased + * @default + */ + this.frameBased = false; + + /** + * @property {array} _tweens - All of the currently running tweens. + * @private + */ + this._tweens = []; + + /** + * @property {array} _add - All of the tweens queued to be added in the next update. + * @private + */ + this._add = []; + + this.easeMap = { + + "Power0": Phaser.Easing.Power0, + "Power1": Phaser.Easing.Power1, + "Power2": Phaser.Easing.Power2, + "Power3": Phaser.Easing.Power3, + "Power4": Phaser.Easing.Power4, + + "Linear": Phaser.Easing.Linear.None, + "Quad": Phaser.Easing.Quadratic.Out, + "Cubic": Phaser.Easing.Cubic.Out, + "Quart": Phaser.Easing.Quartic.Out, + "Quint": Phaser.Easing.Quintic.Out, + "Sine": Phaser.Easing.Sinusoidal.Out, + "Expo": Phaser.Easing.Exponential.Out, + "Circ": Phaser.Easing.Circular.Out, + "Elastic": Phaser.Easing.Elastic.Out, + "Back": Phaser.Easing.Back.Out, + "Bounce": Phaser.Easing.Bounce.Out, + + "Quad.easeIn": Phaser.Easing.Quadratic.In, + "Cubic.easeIn": Phaser.Easing.Cubic.In, + "Quart.easeIn": Phaser.Easing.Quartic.In, + "Quint.easeIn": Phaser.Easing.Quintic.In, + "Sine.easeIn": Phaser.Easing.Sinusoidal.In, + "Expo.easeIn": Phaser.Easing.Exponential.In, + "Circ.easeIn": Phaser.Easing.Circular.In, + "Elastic.easeIn": Phaser.Easing.Elastic.In, + "Back.easeIn": Phaser.Easing.Back.In, + "Bounce.easeIn": Phaser.Easing.Bounce.In, + + "Quad.easeOut": Phaser.Easing.Quadratic.Out, + "Cubic.easeOut": Phaser.Easing.Cubic.Out, + "Quart.easeOut": Phaser.Easing.Quartic.Out, + "Quint.easeOut": Phaser.Easing.Quintic.Out, + "Sine.easeOut": Phaser.Easing.Sinusoidal.Out, + "Expo.easeOut": Phaser.Easing.Exponential.Out, + "Circ.easeOut": Phaser.Easing.Circular.Out, + "Elastic.easeOut": Phaser.Easing.Elastic.Out, + "Back.easeOut": Phaser.Easing.Back.Out, + "Bounce.easeOut": Phaser.Easing.Bounce.Out, + + "Quad.easeInOut": Phaser.Easing.Quadratic.InOut, + "Cubic.easeInOut": Phaser.Easing.Cubic.InOut, + "Quart.easeInOut": Phaser.Easing.Quartic.InOut, + "Quint.easeInOut": Phaser.Easing.Quintic.InOut, + "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut, + "Expo.easeInOut": Phaser.Easing.Exponential.InOut, + "Circ.easeInOut": Phaser.Easing.Circular.InOut, + "Elastic.easeInOut": Phaser.Easing.Elastic.InOut, + "Back.easeInOut": Phaser.Easing.Back.InOut, + "Bounce.easeInOut": Phaser.Easing.Bounce.InOut + + }; + + this.game.onPause.add(this._pauseAll, this); + this.game.onResume.add(this._resumeAll, this); + +}; + +Phaser.TweenManager.prototype = { + + /** + * Get all the tween objects in an array. + * @method Phaser.TweenManager#getAll + * @returns {Phaser.Tween[]} Array with all tween objects. + */ + getAll: function () { + + return this._tweens; + + }, + + /** + * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. + * @method Phaser.TweenManager#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._tweens.length; i++) + { + this._tweens[i].pendingDelete = true; + } + + this._add = []; + + }, + + /** + * Remove all tweens from a specific object, array of objects or Group. + * + * @method Phaser.TweenManager#removeFrom + * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. + * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. + */ + removeFrom: function (obj, children) { + + if (children === undefined) { children = true; } + + var i; + var len; + + if (Array.isArray(obj)) + { + for (i = 0, len = obj.length; i < len; i++) + { + this.removeFrom(obj[i]); + } + } + else if (obj.type === Phaser.GROUP && children) + { + for (var i = 0, len = obj.children.length; i < len; i++) + { + this.removeFrom(obj.children[i]); + } + } + else + { + for (i = 0, len = this._tweens.length; i < len; i++) + { + if (obj === this._tweens[i].target) + { + this.remove(this._tweens[i]); + } + } + + for (i = 0, len = this._add.length; i < len; i++) + { + if (obj === this._add[i].target) + { + this.remove(this._add[i]); + } + } + } + + }, + + /** + * Add a new tween into the TweenManager. + * + * @method Phaser.TweenManager#add + * @param {Phaser.Tween} tween - The tween object you want to add. + * @returns {Phaser.Tween} The tween object you added to the manager. + */ + add: function (tween) { + + tween._manager = this; + this._add.push(tween); + + }, + + /** + * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.TweenManager#create + * @param {object} object - Object the tween will be run on. + * @returns {Phaser.Tween} The newly created tween object. + */ + create: function (object) { + + return new Phaser.Tween(object, this.game, this); + + }, + + /** + * Remove a tween from this manager. + * + * @method Phaser.TweenManager#remove + * @param {Phaser.Tween} tween - The tween object you want to remove. + */ + remove: function (tween) { + + var i = this._tweens.indexOf(tween); + + if (i !== -1) + { + this._tweens[i].pendingDelete = true; + } + else + { + i = this._add.indexOf(tween); + + if (i !== -1) + { + this._add[i].pendingDelete = true; + } + } + + }, + + /** + * Update all the tween objects you added to this manager. + * + * @method Phaser.TweenManager#update + * @returns {boolean} Return false if there's no tween to update, otherwise return true. + */ + update: function () { + + var addTweens = this._add.length; + var numTweens = this._tweens.length; + + if (numTweens === 0 && addTweens === 0) + { + return false; + } + + var i = 0; + + while (i < numTweens) + { + if (this._tweens[i].update(this.game.time.time)) + { + i++; + } + else + { + this._tweens.splice(i, 1); + + numTweens--; + } + } + + // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running + if (addTweens > 0) + { + this._tweens = this._tweens.concat(this._add); + this._add.length = 0; + } + + return true; + + }, + + /** + * Checks to see if a particular Sprite is currently being tweened. + * + * The `checkIsRunning` parameter will exclude tweens that have **just** completed or been stopped but haven't yet been removed from the manager. + * + * @method Phaser.TweenManager#isTweening + * @param {object} object - The object to check for tweens against. + * @param {boolean} [checkIsRunning=false] - Also check that the tween is running and is not marked for deletion. + * @returns {boolean} Returns true if the object is currently being tweened, false if not. + */ + isTweening: function(object, checkIsRunning) { + + if (!checkIsRunning) { checkIsRunning = false; } + + return this._tweens.some(function(tween) { + return (tween.target === object) && (!checkIsRunning || (tween.isRunning && !tween.pendingDelete)); + }); + + }, + + /** + * Private. Called by game focus loss. Pauses all currently running tweens. + * + * @method Phaser.TweenManager#_pauseAll + * @private + */ + _pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._pause(); + } + + }, + + /** + * Private. Called by game focus loss. Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#_resumeAll + * @private + */ + _resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._resume(); + } + + }, + + /** + * Pauses all currently running tweens. + * + * @method Phaser.TweenManager#pauseAll + */ + pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].pause(); + } + + }, + + /** + * Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#resumeAll + */ + resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].resume(true); + } + + } + +}; + +Phaser.TweenManager.prototype.constructor = Phaser.TweenManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tween allows you to alter one or more properties of a target object over a defined period of time. +* This can be used for things such as alpha fading Sprites, scaling them or motion. +* Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object +* by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and +* are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. +* +* @class Phaser.Tween +* @constructor +* @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. +* @param {Phaser.Game} game - Current game instance. +* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. +*/ +Phaser.Tween = function (target, game, manager) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. + */ + this.target = target; + + /** + * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween. + */ + this.manager = manager; + + /** + * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween. + */ + this.timeline = []; + + /** + * If set to `true` the current tween will play in reverse. + * If the tween hasn't yet started this has no effect. + * If there are child tweens then all child tweens will play in reverse from the current point. + * @property {boolean} reverse + * @default + */ + this.reverse = false; + + /** + * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. + * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. + * + * @property {number} timeScale + * @default + */ + this.timeScale = 1; + + /** + * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count. + */ + this.repeatCounter = 0; + + /** + * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager. + * @default + * @readonly + */ + this.pendingDelete = false; + + /** + * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onStart + */ + this.onStart = new Phaser.Signal(); + + /** + * The onLoop event is fired if the Tween, or any child tweens loop. + * It will be sent 2 parameters: the target object and this tween. + * + * @property {Phaser.Signal} onLoop + */ + this.onLoop = new Phaser.Signal(); + + /** + * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onRepeat + */ + this.onRepeat = new Phaser.Signal(); + + /** + * The onChildComplete event is fired when the Tween or any of its children completes. + * Fires every time a child completes unless a child is set to repeat forever. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onChildComplete + */ + this.onChildComplete = new Phaser.Signal(); + + /** + * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. + * @default + */ + this.isRunning = false; + + /** + * @property {number} current - The current Tween child being run. + * @default + * @readonly + */ + this.current = 0; + + /** + * @property {object} properties - Target property cache used when building the child data values. + */ + this.properties = {}; + + /** + * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it. + */ + this.chainedTween = null; + + /** + * @property {boolean} isPaused - Is this Tween paused or not? + * @default + */ + this.isPaused = false; + + /** + * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * + * The default value is whatever you've set in TweenManager.frameBased. + * + * @property {boolean} frameBased + * @default + */ + this.frameBased = manager.frameBased; + + /** + * @property {function} _onUpdateCallback - An onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallback = null; + + /** + * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallbackContext = null; + + /** + * @property {number} _pausedTime - Private pause timer. + * @private + * @default + */ + this._pausedTime = 0; + + /** + * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not. + * @private + */ + this._hasStarted = false; +}; + +/** +* A helper for tweening {@link Phaser.Color.createColor color objects}. +* +* It can be passed to {@link #onUpdateCallback}. +* +* ```javascript +* var color = Phaser.Color.createColor(255, 0, 0); // red +* +* var tween = game.add.tween(color).to({ +* r: 0, g: 0, b: 255 // blue +* }); +* +* tween.onUpdateCallback(Phaser.Tween.updateColor); +* +* tween.start(); +* ``` +* +* @method Phaser.Tween.updateColor +* @static +* @param {Phaser.Tween} tween - A Tween with a {@link #target} that is a {@link Phaser.Color.createColor color object}. +*/ +Phaser.Tween.updateColor = function (tween) { + + Phaser.Color.updateColor(tween.target); + +}; + +Phaser.Tween.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#to + * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined || duration <= 0) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.to cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#from + * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.from cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Starts the tween running. Can also be called by the `autoStart` parameter of {@link #to} or {@link #from}. + * This sets the {@link #isRunning} property to `true` and dispatches the {@link #onStart} signal. + * If the tween has a delay set then nothing will start tweening until the delay has expired. + * If the tween is already running, is flagged for deletion (such as after {@link #stop}), + * or has an empty timeline, calling start has no effect and the `onStart` signal is not dispatched. + * + * @method Phaser.Tween#start + * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + start: function (index) { + + if (index === undefined) { index = 0; } + + if (this.pendingDelete) + { + console.warn('Phaser.Tween.start cannot be called after Tween.stop'); + return this; + } + + if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning) + { + return this; + } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + this.manager.add(this); + + this.isRunning = true; + + if (index < 0 || index > this.timeline.length - 1) + { + index = 0; + } + + this.current = index; + + this.timeline[this.current].start(); + + return this; + + }, + + /** + * Stops the tween if running and flags it for deletion from the TweenManager. The tween can't be {@link #start restarted} after this. + * The {@link #onComplete} signal is not dispatched and no chained tweens are started unless the `complete` parameter is set to `true`. + * If you just wish to pause a tween then use {@link #pause} instead. + * If the tween is not running, it is **not** flagged for deletion and can be started again. + * + * @method Phaser.Tween#stop + * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + stop: function (complete) { + + if (complete === undefined) { complete = false; } + + this.isRunning = false; + + this._onUpdateCallback = null; + this._onUpdateCallbackContext = null; + + if (complete) + { + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + } + + this.manager.remove(this); + + return this; + + }, + + /** + * Updates either a single TweenData or all TweenData objects properties to the given value. + * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. + * The property is not checked, so if you pass an invalid one you'll generate a run-time error. + * + * @method Phaser.Tween#updateTweenData + * @param {string} property - The property to update. + * @param {number|function} value - The value to set the property to. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + updateTweenData: function (property, value, index) { + + if (this.timeline.length === 0) { return this; } + + if (index === undefined) { index = 0; } + + if (index === -1) + { + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i][property] = value; + } + } + else + { + this.timeline[index][property] = value; + } + + return this; + + }, + + /** + * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. + * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. + * If you have child tweens and pass -1 as the index value it sets the delay across all of them. + * + * @method Phaser.Tween#delay + * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + delay: function (duration, index) { + + return this.updateTweenData('delay', duration, index); + + }, + + /** + * Sets the number of times this tween will repeat. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. + * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. + * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. + * + * @method Phaser.Tween#repeat + * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeat: function (total, repeatDelay, index) { + + if (repeatDelay === undefined) { repeatDelay = 0; } + + this.updateTweenData('repeatCounter', total, index); + this.updateTweenData('repeatTotal', total, index); + + return this.updateTweenData('repeatDelay', repeatDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will repeat itself. + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#repeatDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatDelay: function (duration, index) { + + return this.updateTweenData('repeatDelay', duration, index); + + }, + + /** + * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. + * Used in combination with repeat you can create endless loops. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. + * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. + * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. + * + * @method Phaser.Tween#yoyo + * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo. + * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyo: function(enable, yoyoDelay, index) { + + if (yoyoDelay === undefined) { yoyoDelay = 0; } + + this.updateTweenData('yoyo', enable, index); + + return this.updateTweenData('yoyoDelay', yoyoDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#yoyoDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyoDelay: function (duration, index) { + + return this.updateTweenData('yoyoDelay', duration, index); + + }, + + /** + * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. + * + * @method Phaser.Tween#easing + * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + easing: function (ease, index) { + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + return this.updateTweenData('easingFunction', ease, index); + + }, + + /** + * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. + * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. + * The interpolation function is only used if the target properties is an array. + * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. + * + * @method Phaser.Tween#interpolation + * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) + * @param {object} [context] - The context under which the interpolation function will be run. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + interpolation: function (interpolation, context, index) { + + if (context === undefined) { context = Phaser.Math; } + + this.updateTweenData('interpolationFunction', interpolation, index); + + return this.updateTweenData('interpolationContext', context, index); + + }, + + /** + * Set how many times this tween and all of its children will repeat. + * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. + * + * @method Phaser.Tween#repeatAll + * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatAll: function (total) { + + if (total === undefined) { total = 0; } + + this.repeatCounter = total; + + return this; + + }, + + /** + * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called + * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. + * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. + * For that you should listen to `onComplete` on the final tween in your chain. + * + * If you pass multiple tweens to this method they will be joined into a single long chain. + * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. + * Any previously chained tweens that may have been set will be overwritten. + * + * @method Phaser.Tween#chain + * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + chain: function () { + + var i = arguments.length; + + while (i--) + { + if (i > 0) + { + arguments[i - 1].chainedTween = arguments[i]; + } + else + { + this.chainedTween = arguments[i]; + } + } + + return this; + + }, + + /** + * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. + * + * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. + * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. + * + * Usage: + * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) + * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) + * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) + * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) + * .loop(); + * @method Phaser.Tween#loop + * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + loop: function (value) { + + if (value === undefined) { value = true; } + + this.repeatCounter = (value) ? -1 : 0; + + return this; + + }, + + /** + * Sets a callback to be fired each time this tween updates. + * + * The callback receives the current Tween, the {@link Phaser.TweenData#value 'value' of the current TweenData}, and the current {@link Phaser.TweenData TweenData}. The second parameter is most useful. + * + * ```javascript + * tween.onUpdateCallback(function (tween, value, tweenData) { + * console.log('Tween running -- percent: %.2f value: %.2f', tweenData.percent, value); + * }); + * ``` + * + * @method Phaser.Tween#onUpdateCallback + * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. + * @param {object} callbackContext - The context in which to call the onUpdate callback. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + onUpdateCallback: function (callback, callbackContext) { + + this._onUpdateCallback = callback; + this._onUpdateCallbackContext = callbackContext; + + return this; + + }, + + /** + * Pauses the tween. Resume playback with Tween.resume. + * + * @method Phaser.Tween#pause + */ + pause: function () { + + this.isPaused = true; + + this._codePaused = true; + + this._pausedTime = this.game.time.time; + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * + * @private + * @method Phaser.Tween#_pause + */ + _pause: function () { + + if (!this._codePaused) + { + this.isPaused = true; + + this._pausedTime = this.game.time.time; + } + + }, + + /** + * Resumes a paused tween. + * + * @method Phaser.Tween#resume + */ + resume: function () { + + if (this.isPaused) + { + this.isPaused = false; + + this._codePaused = false; + + for (var i = 0; i < this.timeline.length; i++) + { + if (!this.timeline[i].isRunning) + { + this.timeline[i].startTime += (this.game.time.time - this._pausedTime); + } + } + } + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * @method Phaser.Tween#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Core tween update function called by the TweenManager. Does not need to be invoked directly. + * + * @method Phaser.Tween#update + * @param {number} time - A timestamp passed in by the TweenManager. + * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). + */ + update: function (time) { + + if (this.pendingDelete || !this.target) + { + return false; + } + + if (this.isPaused) + { + return true; + } + + var status = this.timeline[this.current].update(time); + + if (status === Phaser.TweenData.PENDING) + { + return true; + } + else if (status === Phaser.TweenData.RUNNING) + { + if (!this._hasStarted) + { + this.onStart.dispatch(this.target, this); + this._hasStarted = true; + } + + if (this._onUpdateCallback !== null) + { + this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]); + } + + // In case the update callback modifies this tween + return this.isRunning; + } + else if (status === Phaser.TweenData.LOOPED) + { + if (this.timeline[this.current].repeatCounter === -1) + { + this.onLoop.dispatch(this.target, this); + } + else + { + this.onRepeat.dispatch(this.target, this); + } + + return true; + } + else if (status === Phaser.TweenData.COMPLETE) + { + var complete = false; + + // What now? + if (this.reverse) + { + this.current--; + + if (this.current < 0) + { + this.current = this.timeline.length - 1; + complete = true; + } + } + else + { + this.current++; + + if (this.current === this.timeline.length) + { + this.current = 0; + complete = true; + } + } + + if (complete) + { + // We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it? + if (this.repeatCounter === -1) + { + this.timeline[this.current].start(); + this.onLoop.dispatch(this.target, this); + return true; + } + else if (this.repeatCounter > 0) + { + this.repeatCounter--; + + this.timeline[this.current].start(); + this.onRepeat.dispatch(this.target, this); + return true; + } + else + { + // No more repeats and no more children, so we're done + this.isRunning = false; + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + + return false; + } + } + else + { + // We've still got some children to go + this.onChildComplete.dispatch(this.target, this); + this.timeline[this.current].start(); + return true; + } + } + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * It ignores delay and repeat counts and any chained tweens, but does include child tweens. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.Tween#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate, data) { + + if (this.game === null || this.target === null) + { + return null; + } + + if (frameRate === undefined) { frameRate = 60; } + if (data === undefined) { data = []; } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + for (var i = 0; i < this.timeline.length; i++) + { + data = data.concat(this.timeline[i].generateData(frameRate)); + } + + return data; + + } + +}; + +/** +* @name Phaser.Tween#totalDuration +* @property {number} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds. +*/ +Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', { + + get: function () { + + var total = 0; + + for (var i = 0; i < this.timeline.length; i++) + { + total += this.timeline[i].duration; + } + + return total; + + } + +}); + +Phaser.Tween.prototype.constructor = Phaser.Tween; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the +* starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for +* TweenData objects and can contain multiple TweenData objects. +* +* @class Phaser.TweenData +* @constructor +* @param {Phaser.Tween} parent - The Tween that owns this TweenData object. +*/ +Phaser.TweenData = function (parent) { + + /** + * @property {Phaser.Tween} parent - The Tween which owns this TweenData. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = parent.game; + + /** + * @property {object} vStart - An object containing the values at the start of the tween. + * @private + */ + this.vStart = {}; + + /** + * @property {object} vStartCache - Cached starting values. + * @private + */ + this.vStartCache = {}; + + /** + * @property {object} vEnd - An object containing the values at the end of the tween. + * @private + */ + this.vEnd = {}; + + /** + * @property {object} vEndCache - Cached ending values. + * @private + */ + this.vEndCache = {}; + + /** + * @property {number} duration - The duration of the tween in ms. + * @default + */ + this.duration = 1000; + + /** + * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is. + * @readonly + */ + this.percent = 0; + + /** + * @property {number} value - The output of the easing function for the current {@link #percent}. Depending on the easing function, this will be within [0, 1] or a slightly larger range (e.g., Bounce). When easing is Linear, this will be identical to {@link #percent}. + * @readonly + */ + this.value = 0; + + /** + * @property {number} repeatCounter - If the Tween is set to repeat this is the number of repeats remaining (and `repeatTotal - repeatCounter` is the number of repeats completed). + */ + this.repeatCounter = 0; + + /** + * @property {number} repeatDelay - The amount of time in ms between repeats of this tween. + */ + this.repeatDelay = 0; + + /** + * @property {number} repeatTotal - The total number of times this Tween will repeat. + * @readonly + */ + this.repeatTotal = 0; + + /** + * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween) + * @default + * @todo Appears unused. + */ + this.interpolate = false; + + /** + * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false. + * @default + */ + this.yoyo = false; + + /** + * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween. + */ + this.yoyoDelay = 0; + + /** + * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). + * @default + */ + this.inReverse = false; + + /** + * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. + * @default + */ + this.delay = 0; + + /** + * @property {number} dt - Current time value. + */ + this.dt = 0; + + /** + * @property {number} startTime - The time the Tween started or null if it hasn't yet started. + */ + this.startTime = null; + + /** + * @property {function} easingFunction - The easing function used for the Tween. + * @default Phaser.Easing.Default + */ + this.easingFunction = Phaser.Easing.Default; + + /** + * @property {function} interpolationFunction - The interpolation function used for Array-based Tween. + * @default Phaser.Math.linearInterpolation + */ + this.interpolationFunction = Phaser.Math.linearInterpolation; + + /** + * @property {object} interpolationContext - The interpolation function context used for the Tween. + * @default Phaser.Math + */ + this.interpolationContext = Phaser.Math; + + /** + * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} isFrom - Is this a from tween or a to tween? + * @default + */ + this.isFrom = false; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.PENDING = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.RUNNING = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.LOOPED = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.COMPLETE = 3; + +Phaser.TweenData.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * + * @method Phaser.TweenData#to + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + to: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = false; + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * + * @method Phaser.TweenData#from + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + from: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = true; + + return this; + + }, + + /** + * Starts the Tween running. + * + * @method Phaser.TweenData#start + * @return {Phaser.TweenData} This Tween object. + */ + start: function () { + + this.startTime = this.game.time.time + this.delay; + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + if (this.delay > 0) + { + this.isRunning = false; + } + else + { + this.isRunning = true; + } + + if (this.isFrom) + { + // Reverse them all and instant set them + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + this.parent.target[property] = this.vStart[property]; + } + } + + this.value = 0; + this.repeatCounter = this.repeatTotal; + + return this; + + }, + + /** + * Loads the values from the target object into this Tween. + * + * @private + * @method Phaser.TweenData#loadValues + * @return {Phaser.TweenData} This Tween object. + */ + loadValues: function () { + + for (var property in this.parent.properties) + { + // Load the property from the parent object + this.vStart[property] = this.parent.properties[property]; + + // Check if an Array was provided as property value + if (Array.isArray(this.vEnd[property])) + { + if (this.vEnd[property].length === 0) + { + continue; + } + + if (this.percent === 0) + { + // Put the start value at the beginning of the array + // but we only want to do this once, if the Tween hasn't run before + this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]); + } + } + + if (typeof this.vEnd[property] !== 'undefined') + { + if (typeof this.vEnd[property] === 'string') + { + // Parses relative end values with start as base (e.g.: +10, -3) + this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10); + } + + this.parent.properties[property] = this.vEnd[property]; + } + else + { + // Null tween + this.vEnd[property] = this.vStart[property]; + } + + this.vStartCache[property] = this.vStart[property]; + this.vEndCache[property] = this.vEnd[property]; + } + + return this; + + }, + + /** + * Updates this Tween. This is called automatically by Phaser.Tween. + * + * @protected + * @method Phaser.TweenData#update + * @param {number} time - A timestamp passed in by the Tween parent. + * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. + */ + update: function (time) { + + if (!this.isRunning) + { + if (time >= this.startTime) + { + this.isRunning = true; + } + else + { + return Phaser.TweenData.PENDING; + } + } + else + { + // Is Running, but is waiting to repeat + if (time < this.startTime) + { + return Phaser.TweenData.RUNNING; + } + } + + var ms = (this.parent.frameBased) ? this.game.time.physicsElapsedMS : this.game.time.elapsedMS; + + if (this.parent.reverse) + { + this.dt -= ms * this.parent.timeScale; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += ms * this.parent.timeScale; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + this.parent.target[property] = start + ((end - start) * this.value); + } + } + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + return this.repeat(); + } + + return Phaser.TweenData.RUNNING; + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.TweenData#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate) { + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + var data = []; + var complete = false; + var fps = (1 / frameRate) * 1000; + + do + { + if (this.parent.reverse) + { + this.dt -= fps; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += fps; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + var blob = {}; + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + blob[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + blob[property] = start + ((end - start) * this.value); + } + } + + data.push(blob); + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + complete = true; + } + + } while (!complete); + + if (this.yoyo) + { + var reversed = data.slice(); + reversed.reverse(); + data = data.concat(reversed); + } + + return data; + + }, + + /** + * Checks if this Tween is meant to repeat or yoyo and handles doing so. + * + * @private + * @method Phaser.TweenData#repeat + * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE. + */ + repeat: function () { + + // If not a yoyo and repeatCounter = 0 then we're done + if (this.yoyo) + { + // We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end + if (this.inReverse && this.repeatCounter === 0) + { + // Restore the properties + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + this.inReverse = false; + + return Phaser.TweenData.COMPLETE; + } + + this.inReverse = !this.inReverse; + } + else + { + if (this.repeatCounter === 0) + { + return Phaser.TweenData.COMPLETE; + } + } + + if (this.inReverse) + { + // If inReverse we're going from vEnd to vStartCache + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + } + } + else + { + // If not inReverse we're just repopulating the cache again + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + // -1 means repeat forever, otherwise decrement the repeatCounter + // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total + if (this.repeatCounter > 0) + { + this.repeatCounter--; + } + } + + this.startTime = this.game.time.time; + + if (this.yoyo && this.inReverse) + { + this.startTime += this.yoyoDelay; + } + else if (!this.inReverse) + { + this.startTime += this.repeatDelay; + } + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + return Phaser.TweenData.LOOPED; + + } + +}; + +Phaser.TweenData.prototype.constructor = Phaser.TweenData; + +/* jshint curly: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of easing methods defining ease-in and ease-out curves. +* +* @class Phaser.Easing +*/ +Phaser.Easing = { + + /** + * Linear easing. + * + * @class Phaser.Easing.Linear + */ + Linear: { + + /** + * Linear Easing (no variation). + * + * @method Phaser.Easing.Linear#None + * @param {number} k - The value to be tweened. + * @returns {number} k. + */ + None: function ( k ) { + + return k; + + } + + }, + + /** + * Quadratic easing. + * + * @class Phaser.Easing.Quadratic + */ + Quadratic: { + + /** + * Ease-in. + * + * @method Phaser.Easing.Quadratic#In + * @param {number} k - The value to be tweened. + * @returns {number} k^2. + */ + In: function ( k ) { + + return k * k; + + }, + + /** + * Ease-out. + * + * @method Phaser.Easing.Quadratic#Out + * @param {number} k - The value to be tweened. + * @returns {number} k* (2-k). + */ + Out: function ( k ) { + + return k * ( 2 - k ); + + }, + + /** + * Ease-in/out. + * + * @method Phaser.Easing.Quadratic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; + return - 0.5 * ( --k * ( k - 2 ) - 1 ); + + } + + }, + + /** + * Cubic easing. + * + * @class Phaser.Easing.Cubic + */ + Cubic: { + + /** + * Cubic ease-in. + * + * @method Phaser.Easing.Cubic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k; + + }, + + /** + * Cubic ease-out. + * + * @method Phaser.Easing.Cubic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k + 1; + + }, + + /** + * Cubic ease-in/out. + * + * @method Phaser.Easing.Cubic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k + 2 ); + + } + + }, + + /** + * Quartic easing. + * + * @class Phaser.Easing.Quartic + */ + Quartic: { + + /** + * Quartic ease-in. + * + * @method Phaser.Easing.Quartic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k; + + }, + + /** + * Quartic ease-out. + * + * @method Phaser.Easing.Quartic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return 1 - ( --k * k * k * k ); + + }, + + /** + * Quartic ease-in/out. + * + * @method Phaser.Easing.Quartic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; + return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); + + } + + }, + + /** + * Quintic easing. + * + * @class Phaser.Easing.Quintic + */ + Quintic: { + + /** + * Quintic ease-in. + * + * @method Phaser.Easing.Quintic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k * k; + + }, + + /** + * Quintic ease-out. + * + * @method Phaser.Easing.Quintic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k * k * k + 1; + + }, + + /** + * Quintic ease-in/out. + * + * @method Phaser.Easing.Quintic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); + + } + + }, + + /** + * Sinusoidal easing. + * + * @class Phaser.Easing.Sinusoidal + */ + Sinusoidal: { + + /** + * Sinusoidal ease-in. + * + * @method Phaser.Easing.Sinusoidal#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 1 - Math.cos( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-out. + * + * @method Phaser.Easing.Sinusoidal#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return Math.sin( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-in/out. + * + * @method Phaser.Easing.Sinusoidal#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); + + } + + }, + + /** + * Exponential easing. + * + * @class Phaser.Easing.Exponential + */ + Exponential: { + + /** + * Exponential ease-in. + * + * @method Phaser.Easing.Exponential#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k === 0 ? 0 : Math.pow( 1024, k - 1 ); + + }, + + /** + * Exponential ease-out. + * + * @method Phaser.Easing.Exponential#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); + + }, + + /** + * Exponential ease-in/out. + * + * @method Phaser.Easing.Exponential#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); + return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); + + } + + }, + + /** + * Circular easing. + * + * @class Phaser.Easing.Circular + */ + Circular: { + + /** + * Circular ease-in. + * + * @method Phaser.Easing.Circular#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Math.sqrt( 1 - k * k ); + + }, + + /** + * Circular ease-out. + * + * @method Phaser.Easing.Circular#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return Math.sqrt( 1 - ( --k * k ) ); + + }, + + /** + * Circular ease-in/out. + * + * @method Phaser.Easing.Circular#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); + return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); + + } + + }, + + /** + * Elastic easing. + * + * @class Phaser.Easing.Elastic + */ + Elastic: { + + /** + * Elastic ease-in. + * + * @method Phaser.Easing.Elastic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + + }, + + /** + * Elastic ease-out. + * + * @method Phaser.Easing.Elastic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); + + }, + + /** + * Elastic ease-in/out. + * + * @method Phaser.Easing.Elastic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; + + } + + }, + + /** + * Back easing. + * + * @class Phaser.Easing.Back + */ + Back: { + + /** + * Back ease-in. + * + * @method Phaser.Easing.Back#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s = 1.70158; + return k * k * ( ( s + 1 ) * k - s ); + + }, + + /** + * Back ease-out. + * + * @method Phaser.Easing.Back#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s = 1.70158; + return --k * k * ( ( s + 1 ) * k + s ) + 1; + + }, + + /** + * Back ease-in/out. + * + * @method Phaser.Easing.Back#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s = 1.70158 * 1.525; + if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); + return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); + + } + + }, + + /** + * Bounce easing. + * + * @class Phaser.Easing.Bounce + */ + Bounce: { + + /** + * Bounce ease-in. + * + * @method Phaser.Easing.Bounce#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Phaser.Easing.Bounce.Out( 1 - k ); + + }, + + /** + * Bounce ease-out. + * + * @method Phaser.Easing.Bounce#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if ( k < ( 1 / 2.75 ) ) { + + return 7.5625 * k * k; + + } else if ( k < ( 2 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; + + } else if ( k < ( 2.5 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; + + } else { + + return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; + + } + + }, + + /** + * Bounce ease-in/out. + * + * @method Phaser.Easing.Bounce#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5; + return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5; + + } + + } + +}; + +Phaser.Easing.Default = Phaser.Easing.Linear.None; +Phaser.Easing.Power0 = Phaser.Easing.Linear.None; +Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out; +Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out; +Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out; +Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is the core internal game clock. +* +* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, +* and also handles the standard Timer pool. +* +* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}. +* +* There are different *types* of time in Phaser: +* +* - ***Game time*** always runs at the speed of time in real life. +* +* Unlike wall-clock time, *game time stops when Phaser is paused*. +* +* Game time is used for {@link Phaser.Timer timer events}. +* +* - ***Physics time*** represents the amount of time given to physics calculations. +* +* *When {@link #slowMotion} is in effect physics time runs slower than game time.* +* Like game time, physics time stops when Phaser is paused. +* +* Physics time is used for physics calculations and {@link Phaser.Tween tweens}. +* +* - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time. +* +* This time is independent of Phaser and always progresses, regardless of if Phaser is paused. +* +* @class Phaser.Time +* @constructor +* @param {Phaser.Game} game A reference to the currently running game. +*/ +Phaser.Time = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * The `Date.now()` value when the time was last updated. + * @property {integer} time + * @protected + */ + this.time = 0; + + /** + * The `now` when the previous update occurred. + * @property {number} prevTime + * @protected + */ + this.prevTime = 0; + + /** + * An increasing value representing cumulative milliseconds since an undisclosed epoch. + * + * While this value is in milliseconds and can be used to compute time deltas, + * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference. + * + * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; + * the value can only be relied upon within a particular game instance. + * + * @property {number} now + * @protected + */ + this.now = 0; + + /** + * Elapsed time since the last time update, in milliseconds, based on `now`. + * + * This value _may_ include time that the game is paused/inactive. + * + * While the game is active, this will be similar to (1000 / {@link #fps}). + * + * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {number} elapsed + * @see Phaser.Time.time + * @protected + */ + this.elapsed = 0; + + /** + * The time in ms since the last time update, in milliseconds, based on `time`. + * + * This value is corrected for game pauses and will be "about zero" after a game is resumed. + * + * _Note:_ This is updated once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {integer} elapsedMS + * @protected + */ + this.elapsedMS = 0; + + /** + * The physics update delta, in fractional seconds. + * + * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) + * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system + * is unable to consistently maintain the desired FPS. + * + * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. + * + * @property {number} physicsElapsed + */ + this.physicsElapsed = 1 / 60; + + /** + * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. + * + * @property {number} physicsElapsedMS + */ + this.physicsElapsedMS = (1 / 60) * 1000; + + /** + * The desiredFps multiplier as used by Game.update. + * @property {integer} desiredFpsMult + * @protected + */ + this.desiredFpsMult = 1.0 / 60; + + /** + * The desired frame rate of the game. + * + * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates. + * + * @property {number} _desiredFps + * @private + * @default + */ + this._desiredFps = 60; + + /** + * The suggested frame rate for your game, based on an averaged real frame rate. + * This value is only populated if `Time.advancedTiming` is enabled. + * + * _Note:_ This is not available until after a few frames have passed; until then + * it's set to the same value as desiredFps. + * + * @property {number} suggestedFps + * @default + */ + this.suggestedFps = this.desiredFps; + + /** + * Scaling factor to make the game move smoothly in slow motion (or fast motion) + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * You likely need to adjust {@link #desiredFps} as well such that `desiredFps / slowMotion === 60`. + * + * @property {number} slowMotion + * @default + */ + this.slowMotion = 1.0; + + /** + * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. This isn't expensive, but displaying it with {@link Phaser.Utils.Debug#text} can be, especially in WebGL mode. + * @property {boolean} advancedTiming + * @default + */ + this.advancedTiming = false; + + /** + * Advanced timing result: The number of animation frames received from the browser in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} frames + * @readonly + */ + this.frames = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateLogic logic updates} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} updates + * @readonly + */ + this.updates = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateRender renders} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} renders + * @readonly + */ + this.renders = 0; + + /** + * Advanced timing result: Frames per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} fps + * @readonly + */ + this.fps = 0; + + /** + * Advanced timing result: Logic updates per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} ups + * @readonly + */ + this.ups = 0; + + /** + * Advanced timing result: Renders per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} rps + * @readonly + */ + this.rps = 0; + + /** + * Advanced timing result: The lowest rate the fps has dropped to. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMin + */ + this.fpsMin = 1000; + + /** + * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMax + */ + this.fpsMax = 0; + + /** + * Advanced timing result: The minimum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMin + * @default + */ + this.msMin = 1000; + + /** + * Advanced timing result: The maximum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMax + */ + this.msMax = 0; + + /** + * Records how long the game was last paused, in milliseconds. + * (This is not updated until the game is resumed.) + * @property {number} pauseDuration + */ + this.pauseDuration = 0; + + /** + * @property {number} timeToCall - The value that setTimeout needs to work out when to next update + * @protected + */ + this.timeToCall = 0; + + /** + * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop + * @protected + */ + this.timeExpected = 0; + + /** + * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to. + * @property {Phaser.Timer} events + */ + this.events = new Phaser.Timer(this.game, false); + + /** + * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated + * @private + */ + this._frameCount = 0; + + /** + * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated + * @private + */ + this._elapsedAccumulator = 0; + + /** + * @property {number} _started - The time at which the Game instance started. + * @private + */ + this._started = 0; + + /** + * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. + * @private + */ + this._timeLastSecond = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {boolean} _justResumed - Internal value used to recover from the game pause state. + * @private + */ + this._justResumed = false; + + /** + * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects. + * @private + */ + this._timers = []; + +}; + +Phaser.Time.prototype = { + + /** + * Called automatically by Phaser.Game after boot. Should not be called directly. + * + * @method Phaser.Time#boot + * @protected + */ + boot: function () { + + this._started = Date.now(); + this.time = Date.now(); + this.events.start(); + this.timeExpected = this.time; + + }, + + /** + * Adds an existing Phaser.Timer object to the Timer pool. + * + * @method Phaser.Time#add + * @param {Phaser.Timer} timer - An existing Phaser.Timer object. + * @return {Phaser.Timer} The given Phaser.Timer object. + */ + add: function (timer) { + + this._timers.push(timer); + + return timer; + + }, + + /** + * Creates a new stand-alone Phaser.Timer object. + * + * @method Phaser.Time#create + * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). + * @return {Phaser.Timer} The Timer object that was created. + */ + create: function (autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + var timer = new Phaser.Timer(this.game, autoDestroy); + + this._timers.push(timer); + + return timer; + + }, + + /** + * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer. + * + * @method Phaser.Time#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._timers.length; i++) + { + this._timers[i].destroy(); + } + + this._timers = []; + + this.events.removeAll(); + + }, + + /** + * Refreshes the Time.time and Time.elapsedMS properties from the system clock. + * + * @method Phaser.Time#refresh + */ + refresh: function () { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + }, + + /** + * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. + * + * @method Phaser.Time#update + * @protected + * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}. + */ + update: function (time) { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + // 'now' is currently still holding the time of the last call, move it into prevTime + this.prevTime = this.now; + + // update 'now' to hold the current time + // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now) + this.now = time; + + // elapsed time between previous call and now - this could be a high resolution value + this.elapsed = this.now - this.prevTime; + + if (this.game.raf._isSetTimeOut) + { + // console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time); + + // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game + this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time))); + + // time when the next call is expected if using timers + this.timeExpected = time + this.timeToCall; + + // console.log('Time expect', this.timeExpected); + } + + if (this.advancedTiming) + { + this.updateAdvancedTiming(); + } + + // Paused but still running? + if (!this.game.paused) + { + // Our internal Phaser.Timer + this.events.update(this.time); + + if (this._timers.length) + { + this.updateTimers(); + } + } + + }, + + /** + * Handles the updating of the Phaser.Timers (if any) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateTimers + * @private + */ + updateTimers: function () { + + // Any game level timers + var i = 0; + var len = this._timers.length; + + while (i < len) + { + if (this._timers[i].update(this.time)) + { + i++; + } + else + { + // Timer requests to be removed + this._timers.splice(i, 1); + len--; + } + } + + }, + + /** + * Handles the updating of the advanced timing values (if enabled) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateAdvancedTiming + * @private + */ + updateAdvancedTiming: function () { + + // count the number of time.update calls + this._frameCount++; + this._elapsedAccumulator += this.elapsed; + + // occasionally recalculate the suggestedFps based on the accumulated elapsed time + if (this._frameCount >= this._desiredFps * 2) + { + // this formula calculates suggestedFps in multiples of 5 fps + this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5; + this._frameCount = 0; + this._elapsedAccumulator = 0; + } + + this.msMin = Math.min(this.msMin, this.elapsed); + this.msMax = Math.max(this.msMax, this.elapsed); + + this.frames++; + + if (this.now > this._timeLastSecond + 1000) + { + var interval = this.now - this._timeLastSecond; + this.fps = Math.round((this.frames * 1000) / interval); + this.ups = Math.round((this.updates * 1000) / interval); + this.rps = Math.round((this.renders * 1000) / interval); + this.fpsMin = Math.min(this.fpsMin, this.fps); + this.fpsMax = Math.max(this.fpsMax, this.fps); + this._timeLastSecond = this.now; + this.frames = 0; + this.updates = 0; + this.renders = 0; + } + + }, + + /** + * Counts one logic update (if advanced timing is enabled). + * + * @method Phaser.Time#countUpdate + * @private + */ + countUpdate: function () { + + if (this.advancedTiming) + { + this.updates++; + } + + }, + + /** + * Counts one render (if advanced timing is enabled). + * + * @method Phaser.Time#countRender + * @private + */ + countRender: function () { + + if (this.advancedTiming) + { + this.renders++; + } + + }, + + /** + * Called when the game enters a paused state. + * + * @method Phaser.Time#gamePaused + * @private + */ + gamePaused: function () { + + this._pauseStarted = Date.now(); + + this.events.pause(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._pause(); + } + + }, + + /** + * Called when the game resumes from a paused state. + * + * @method Phaser.Time#gameResumed + * @private + */ + gameResumed: function () { + + // Set the parameter which stores Date.now() to make sure it's correct on resume + this.time = Date.now(); + + this.pauseDuration = this.time - this._pauseStarted; + + this.events.resume(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._resume(); + } + + }, + + /** + * The number of seconds that have elapsed since the game was started. + * + * @method Phaser.Time#totalElapsedSeconds + * @return {number} The number of seconds that have elapsed since the game was started. + */ + totalElapsedSeconds: function() { + return (this.time - this._started) * 0.001; + }, + + /** + * How long has passed since the given time. + * + * @method Phaser.Time#elapsedSince + * @param {number} since - The time you want to measure against. + * @return {number} The difference between the given time and now. + */ + elapsedSince: function (since) { + return this.time - since; + }, + + /** + * How long has passed since the given time (in seconds). + * + * @method Phaser.Time#elapsedSecondsSince + * @param {number} since - The time you want to measure (in seconds). + * @return {number} Duration between given time and now (in seconds). + */ + elapsedSecondsSince: function (since) { + return (this.time - since) * 0.001; + }, + + /** + * Resets the private _started value to now and removes all currently running Timers. + * + * @method Phaser.Time#reset + */ + reset: function () { + + this._started = this.time; + this.removeAll(); + + } + +}; + +/** +* The number of logic updates per second. +* +* This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. +* +* The render rate is unaffected unless you also turn off {@link Phaser.Game#forceSingleRender}. +* +* @name Phaser.Time#desiredFps +* @type {integer} +* @default 60 +*/ +Object.defineProperty(Phaser.Time.prototype, "desiredFps", { + + get: function () { + + return this._desiredFps; + + }, + + set: function (value) { + + this._desiredFps = value; + + // Set the physics elapsed time... this will always be 1 / this.desiredFps + // because we're using fixed time steps in game.update + this.physicsElapsed = 1 / value; + + this.physicsElapsedMS = this.physicsElapsed * 1000; + + this.desiredFpsMult = 1.0 / value; + + } + +}); + +Phaser.Time.prototype.constructor = Phaser.Time; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback. +* Many different timer events, with individual delays, can be added to the same Timer. +* +* All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. +* +* Timers are based on real life time, adjusted for game pause durations. +* That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account. +* +* @class Phaser.Timer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). +*/ +Phaser.Timer = function (game, autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * True if the Timer is actively running. + * + * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer. + * @property {boolean} running + * @default + * @readonly + */ + this.running = false; + + /** + * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). + * @property {boolean} autoDestroy + */ + this.autoDestroy = autoDestroy; + + /** + * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending. + * @readonly + * @default + */ + this.expired = false; + + /** + * @property {number} elapsed - Elapsed time since the last frame (in ms). + * @protected + */ + this.elapsed = 0; + + /** + * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. + */ + this.events = []; + + /** + * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. + * + * The signal is supplied with one argument, `timer`, which is this Timer object. + * + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {number} nextTick - The time the next tick will occur. + * @readonly + * @protected + */ + this.nextTick = 0; + + /** + * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. + */ + this.timeCap = 1000; + + /** + * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. + * @readonly + * @default + */ + this.paused = false; + + /** + * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {number} _started - The time at which this Timer instance started running. + * @private + * @default + */ + this._started = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {number} _pauseTotal - Total paused time. + * @private + */ + this._pauseTotal = 0; + + /** + * @property {number} _now - The current start-time adjusted time. + * @private + */ + this._now = Date.now(); + + /** + * @property {number} _len - Temp. array length variable. + * @private + */ + this._len = 0; + + /** + * @property {number} _marked - Temp. counter variable. + * @private + */ + this._marked = 0; + + /** + * @property {number} _i - Temp. array counter variable. + * @private + */ + this._i = 0; + + /** + * @property {number} _diff - Internal cache var. + * @private + */ + this._diff = 0; + + /** + * @property {number} _newTick - Internal cache var. + * @private + */ + this._newTick = 0; + +}; + +/** +* Number of milliseconds in a minute. +* @constant +* @type {integer} +*/ +Phaser.Timer.MINUTE = 60000; + +/** +* Number of milliseconds in a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.SECOND = 1000; + +/** +* Number of milliseconds in half a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.HALF = 500; + +/** +* Number of milliseconds in a quarter of a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.QUARTER = 250; + +Phaser.Timer.prototype = { + + /** + * Creates a new TimerEvent on this Timer. + * + * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. + * + * @method Phaser.Timer#create + * @private + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {boolean} loop - Should the event loop or not? + * @param {number} repeatCount - The number of times the event will repeat. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {any[]} arguments - The values to be sent to your callback function when it is called. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + create: function (delay, loop, repeatCount, callback, callbackContext, args) { + + delay = Math.round(delay); + + var tick = delay; + + if (this._now === 0) + { + tick += this.game.time.time; + } + else + { + tick += this._now; + } + + var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args); + + this.events.push(event); + + this.order(); + + this.expired = false; + + return event; + + }, + + /** + * Adds a new Event to this Timer. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#add + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + add: function (delay, callback, callbackContext) { + + return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. + * If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#repeat + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + repeat: function (delay, repeatCount, callback, callbackContext) { + + return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4)); + + }, + + /** + * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#loop + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + loop: function (delay, callback, callbackContext) { + + return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Starts this Timer running. + * @method Phaser.Timer#start + * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start. + */ + start: function (delay) { + + if (this.running) + { + return; + } + + this._started = this.game.time.time + (delay || 0); + + this.running = true; + + for (var i = 0; i < this.events.length; i++) + { + this.events[i].tick = this.events[i].delay + this._started; + } + + }, + + /** + * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. + * @method Phaser.Timer#stop + * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain. + */ + stop: function (clearEvents) { + + this.running = false; + + if (clearEvents === undefined) { clearEvents = true; } + + if (clearEvents) + { + this.events.length = 0; + } + + }, + + /** + * Removes a pending TimerEvent from the queue. + * @param {Phaser.TimerEvent} event - The event to remove from the queue. + * @method Phaser.Timer#remove + */ + remove: function (event) { + + for (var i = 0; i < this.events.length; i++) + { + if (this.events[i] === event) + { + this.events[i].pendingDelete = true; + return true; + } + } + + return false; + + }, + + /** + * Orders the events on this Timer so they are in tick order. + * This is called automatically when new events are created. + * @method Phaser.Timer#order + * @protected + */ + order: function () { + + if (this.events.length > 0) + { + // Sort the events so the one with the lowest tick is first + this.events.sort(this.sortHandler); + + this.nextTick = this.events[0].tick; + } + + }, + + /** + * Sort handler used by Phaser.Timer.order. + * @method Phaser.Timer#sortHandler + * @private + */ + sortHandler: function (a, b) { + + if (a.tick < b.tick) + { + return -1; + } + else if (a.tick > b.tick) + { + return 1; + } + + return 0; + + }, + + /** + * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values. + * + * @method Phaser.Timer#clearPendingEvents + * @protected + */ + 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; + + }, + + /** + * The main Timer update event, called automatically by Phaser.Time.update. + * + * @method Phaser.Timer#update + * @protected + * @param {number} time - The time from the core game clock. + * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. + */ + update: function (time) { + + if (this.paused) + { + return true; + } + + this.elapsed = time - this._now; + this._now = time; + + // spike-dislike + if (this.elapsed > this.timeCap) + { + // For some reason the time between now and the last time the game was updated was larger than our timeCap. + // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause. + // In this case we need to adjust the TimerEvents and nextTick. + this.adjustEvents(time - this.elapsed); + } + + this._marked = 0; + + // Clears events marked for deletion and resets _len and _i to 0. + this.clearPendingEvents(); + + if (this.running && this._now >= this.nextTick && this._len > 0) + { + while (this._i < this._len && this.running) + { + var event = this.events[this._i]; + + if (this._now >= event.tick && !event.pendingDelete) + { + // (now + delay) - (time difference from last tick to now) + this._newTick = (this._now + event.delay) - (this._now - event.tick); + + if (this._newTick < 0) + { + this._newTick = this._now + event.delay; + } + + if (event.loop === true) + { + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else if (event.repeatCount > 0) + { + event.repeatCount--; + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else + { + this._marked++; + event.pendingDelete = true; + event.callback.apply(event.callbackContext, event.args); + } + + this._i++; + } + else + { + break; + } + } + + // Are there any events left? + 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; + } + + }, + + /** + * Pauses the Timer and all events in the queue. + * @method Phaser.Timer#pause + */ + pause: function () { + + if (!this.running) + { + return; + } + + this._codePaused = true; + + if (this.paused) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Internal pause/resume control - user code should use Timer.pause instead. + * @method Phaser.Timer#_pause + * @private + */ + _pause: function () { + + if (this.paused || !this.running) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Adjusts the time of all pending events and the nextTick by the given baseTime. + * + * @method Phaser.Timer#adjustEvents + * @protected + */ + adjustEvents: function (baseTime) { + + for (var i = 0; i < this.events.length; i++) + { + if (!this.events[i].pendingDelete) + { + // Work out how long there would have been from when the game paused until the events next tick + var t = this.events[i].tick - baseTime; + + if (t < 0) + { + t = 0; + } + + // Add the difference on to the time now + this.events[i].tick = this._now + t; + } + } + + var d = this.nextTick - baseTime; + + if (d < 0) + { + this.nextTick = this._now; + } + else + { + this.nextTick = this._now + d; + } + + }, + + /** + * Resumes the Timer and updates all pending events. + * + * @method Phaser.Timer#resume + */ + resume: function () { + + if (!this.paused) + { + return; + } + + var now = this.game.time.time; + this._pauseTotal += now - this._now; + this._now = now; + + this.adjustEvents(this._pauseStarted); + + this.paused = false; + this._codePaused = false; + + }, + + /** + * Internal pause/resume control - user code should use Timer.resume instead. + * @method Phaser.Timer#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#removeAll + */ + removeAll: function () { + + this.onComplete.removeAll(); + this.events.length = 0; + this._len = 0; + this._i = 0; + + }, + + /** + * Destroys this Timer. Any pending Events are not dispatched. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#destroy + */ + destroy: function () { + + this.onComplete.removeAll(); + this.running = false; + this.expired = true; + this.events = []; + this._len = 0; + this._i = 0; + + } + +}; + +/** +* @name Phaser.Timer#next +* @property {number} next - The time at which the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "next", { + + get: function () { + return this.nextTick; + } + +}); + +/** +* @name Phaser.Timer#duration +* @property {number} duration - The duration in ms remaining until the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "duration", { + + get: function () { + + if (this.running && this.nextTick > this._now) + { + return this.nextTick - this._now; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#length +* @property {number} length - The number of pending events in the queue. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "length", { + + get: function () { + return this.events.length; + } + +}); + +/** +* @name Phaser.Timer#ms +* @property {number} ms - The duration in milliseconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "ms", { + + get: function () { + + if (this.running) + { + return this._now - this._started - this._pauseTotal; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#seconds +* @property {number} seconds - The duration in seconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "seconds", { + + get: function () { + + if (this.running) + { + return this.ms * 0.001; + } + else + { + return 0; + } + + } + +}); + +Phaser.Timer.prototype.constructor = Phaser.Timer; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TimerEvent is a single event that is processed by a Phaser.Timer. +* +* It consists of a delay, which is a value in milliseconds after which the event will fire. +* When the event fires it calls a specific callback with the specified arguments. +* +* TimerEvents are removed by their parent timer once finished firing or repeating. +* +* Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. +* +* @class Phaser.TimerEvent +* @constructor +* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. +* @param {number} delay - The delay in ms at which this TimerEvent fires. +* @param {number} tick - The tick is the next game clock time that this event will fire at. +* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times. +* @param {boolean} loop - True if this TimerEvent loops, otherwise false. +* @param {function} callback - The callback that will be called when the TimerEvent occurs. +* @param {object} callbackContext - The context in which the callback will be called. +* @param {any[]} arguments - Additional arguments to be passed to the callback. +*/ +Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) { + + /** + * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. + * @protected + * @readonly + */ + this.timer = timer; + + /** + * @property {number} delay - The delay in ms at which this TimerEvent fires. + */ + this.delay = delay; + + /** + * @property {number} tick - The tick is the next game clock time that this event will fire at. + */ + this.tick = tick; + + /** + * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times. + */ + this.repeatCount = repeatCount - 1; + + /** + * @property {boolean} loop - True if this TimerEvent loops, otherwise false. + */ + this.loop = loop; + + /** + * @property {function} callback - The callback that will be called when the TimerEvent occurs. + */ + this.callback = callback; + + /** + * @property {object} callbackContext - The context in which the callback will be called. + */ + this.callbackContext = callbackContext; + + /** + * @property {any[]} arguments - Additional arguments to be passed to the callback. + */ + this.args = args; + + /** + * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion. + * @protected + */ + this.pendingDelete = false; + +}; + +Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Manager is used to add, play and update Phaser Animations. +* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. +* +* @class Phaser.AnimationManager +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. +*/ +Phaser.AnimationManager = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = sprite.game; + + /** + * The currently displayed Frame of animation, if any. + * This property is only set once an Animation starts playing. Until that point it remains set as `null`. + * + * @property {Phaser.Frame} currentFrame + * @default + */ + this.currentFrame = null; + + /** + * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any. + * @default + */ + this.currentAnim = null; + + /** + * @property {boolean} updateIfVisible - Update the animation data only while the the sprite is {@link Phaser.Sprite#visible}. Set to `false` to continue updating while the sprite is invisible. + * @default + */ + this.updateIfVisible = true; + + /** + * @property {boolean} isLoaded - Set to true once animation data has been loaded. + * @default + */ + this.isLoaded = false; + + /** + * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. + * @private + * @default + */ + this._frameData = null; + + /** + * @property {object} _anims - An internal object that stores all of the Animation instances. + * @private + */ + this._anims = {}; + + /** + * @property {object} _outputFrames - An internal object to help avoid gc. + * @private + */ + this._outputFrames = []; + +}; + +Phaser.AnimationManager.prototype = { + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#loadFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + loadFrameData: function (frameData, frame) { + + if (frameData === undefined) + { + return false; + } + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(frameData); + } + } + + this._frameData = frameData; + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#copyFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + copyFrameData: function (frameData, frame) { + + this._frameData = frameData.clone(); + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(this._frameData); + } + } + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. + * Animations added in this way are played back with the play function. + * + * @method Phaser.AnimationManager#add + * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". + * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. + * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. + * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? + * @return {Phaser.Animation} The Animation object that was created. + */ + add: function (name, frames, frameRate, loop, useNumericIndex) { + + frames = frames || []; + frameRate = frameRate || 60; + + if (loop === undefined) { loop = false; } + + // If they didn't set the useNumericIndex then let's at least try and guess it + if (useNumericIndex === undefined) + { + if (frames && typeof frames[0] === 'number') + { + useNumericIndex = true; + } + else + { + useNumericIndex = false; + } + } + + this._outputFrames = []; + + 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]; + + if (this.sprite.tilingTexture) + { + this.sprite.refreshTexture = true; + } + + return this._anims[name]; + + }, + + /** + * Check whether the frames in the given array are valid and exist. + * + * @method Phaser.AnimationManager#validateFrames + * @param {Array} frames - An array of frames to be validated. + * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) + * @return {boolean} True if all given Frames are valid, otherwise false. + */ + validateFrames: function (frames, useNumericIndex) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + + for (var i = 0; i < frames.length; i++) + { + if (useNumericIndex === true) + { + if (frames[i] > this._frameData.total) + { + return false; + } + } + else + { + if (this._frameData.checkFrameName(frames[i]) === false) + { + return false; + } + } + } + + return true; + + }, + + /** + * Play an animation based on the given key. The animation should previously have been added via `animations.add` + * + * If the requested animation is already playing this request will be ignored. + * If you need to reset an already running animation do so directly on the Animation object itself. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.AnimationManager#play + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation instance. + */ + 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); + } + + return this.currentAnim; + } + else + { + if (this.currentAnim && this.currentAnim.isPlaying) + { + this.currentAnim.stop(); + } + + this.currentAnim = this._anims[name]; + this.currentAnim.paused = false; + this.currentFrame = this.currentAnim.currentFrame; + return this.currentAnim.play(frameRate, loop, killOnComplete); + } + } + + }, + + /** + * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. + * The currentAnim property of the AnimationManager is automatically set to the animation given. + * + * @method Phaser.AnimationManager#stop + * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. + * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) + */ + stop: function (name, resetFrame) { + + if (resetFrame === undefined) { resetFrame = false; } + + if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name)) + { + this.currentAnim.stop(resetFrame); + } + + }, + + /** + * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. + * + * @method Phaser.AnimationManager#update + * @protected + * @return {boolean} True if a new animation frame has been set, otherwise false. + */ + update: function () { + + if (this.updateIfVisible && !this.sprite.visible) + { + return false; + } + + if (this.currentAnim && this.currentAnim.update()) + { + this.currentFrame = this.currentAnim.currentFrame; + return true; + } + + return false; + + }, + + /** + * Advances by the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.next(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Moves backwards the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.previous(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Returns an animation that was previously added by name. + * + * @method Phaser.AnimationManager#getAnimation + * @param {string} name - The name of the animation to be returned, e.g. "fire". + * @return {Phaser.Animation} The Animation instance, if found, otherwise null. + */ + getAnimation: function (name) { + + if (typeof name === 'string') + { + if (this._anims[name]) + { + return this._anims[name]; + } + } + + return null; + + }, + + /** + * Refreshes the current frame data back to the parent Sprite and also resets the texture data. + * + * @method Phaser.AnimationManager#refreshFrame + */ + refreshFrame: function () { + + // TODO + // this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); + + }, + + /** + * Destroys all references this AnimationManager contains. + * Iterates through the list of animations stored in this manager and calls destroy on each of them. + * + * @method Phaser.AnimationManager#destroy + */ + destroy: function () { + + var anim = null; + + for (var anim in this._anims) + { + if (this._anims.hasOwnProperty(anim)) + { + this._anims[anim].destroy(); + } + } + + this._anims = {}; + this._outputFrames = []; + this._frameData = null; + this.currentAnim = null; + this.currentFrame = null; + this.sprite = null; + this.game = null; + + } + +}; + +Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager; + +/** +* @name Phaser.AnimationManager#frameData +* @property {Phaser.FrameData} frameData - The current animations FrameData. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', { + + get: function () { + return this._frameData; + } + +}); + +/** +* @name Phaser.AnimationManager#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', { + + get: function () { + + return this._frameData.total; + } + +}); + +/** +* @name Phaser.AnimationManager#paused +* @property {boolean} paused - Gets and sets the paused state of the current animation. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', { + + get: function () { + + return this.currentAnim.isPaused; + + }, + + set: function (value) { + + this.currentAnim.paused = value; + + } + +}); + +/** +* @name Phaser.AnimationManager#name +* @property {string} name - Gets the current animation name, if set. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'name', { + + get: function () { + + if (this.currentAnim) + { + return this.currentAnim.name; + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.index; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'number' && this._frameData && (gotFrame = this._frameData.getFrame(value))) + { + this.currentFrame = gotFrame; + this.sprite.setFrame(this.currentFrame); + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frameName +* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.name; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'string' && this._frameData && (gotFrame = this._frameData.getFrameByName(value))) + { + this.currentFrame = gotFrame; + this._frameIndex = this.currentFrame.index; + this.sprite.setFrame(this.currentFrame); + } + else + { + console.warn('Cannot set frameName: ' + value); + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Animation instance contains a single animation and the controls to play it. +* +* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. +* +* @class Phaser.Animation +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Sprite} parent - A reference to the owner of this Animation. +* @param {string} name - The unique name for this animation, used in playback commands. +* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. +* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +*/ +Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) { + + if (loop === undefined) { loop = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. + * @private + */ + this._parent = parent; + + /** + * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. + * @private + */ + this._frameData = frameData; + + /** + * @property {string} name - The user defined name given to this Animation. + */ + this.name = name; + + /** + * @property {array} _frames + * @private + */ + this._frames = []; + this._frames = this._frames.concat(frames); + + /** + * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. + */ + this.delay = 1000 / frameRate; + + /** + * @property {boolean} loop - The loop state of the Animation. + */ + this.loop = loop; + + /** + * @property {number} loopCount - The number of times the animation has looped since it was last started. + */ + this.loopCount = 0; + + /** + * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? + * @default + */ + this.killOnComplete = false; + + /** + * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. + * @default + */ + this.isFinished = false; + + /** + * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. + * @default + */ + this.isPlaying = false; + + /** + * @property {boolean} isPaused - The paused state of the Animation. + * @default + */ + this.isPaused = false; + + /** + * @property {boolean} _pauseStartTime - The time the animation paused. + * @private + * @default + */ + this._pauseStartTime = 0; + + /** + * @property {number} _frameIndex + * @private + * @default + */ + this._frameIndex = 0; + + /** + * @property {number} _frameDiff + * @private + * @default + */ + this._frameDiff = 0; + + /** + * @property {number} _frameSkip + * @private + * @default + */ + this._frameSkip = 1; + + /** + * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. + */ + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + /** + * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. + */ + this.onStart = new Phaser.Signal(); + + /** + * This event is dispatched when the Animation changes frame. + * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. + * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations + * will automatically frame-skip to try and claw back time, so do not base your code on expecting to + * receive a perfectly sequential set of frames from this event. + * @property {Phaser.Signal|null} onUpdate + * @default + */ + this.onUpdate = null; + + /** + * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {boolean} isReversed - Indicates if the animation will play backwards. + * @default + */ + this.isReversed = false; + + // Set-up some event listeners + this.game.onPause.add(this.onPause, this); + this.game.onResume.add(this.onResume, this); + +}; + +Phaser.Animation.prototype = { + + /** + * Plays this animation. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.Animation#play + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} - A reference to this Animation instance. + */ + play: function (frameRate, loop, killOnComplete) { + + if (typeof frameRate === 'number') + { + // If they set a new frame rate then use it, otherwise use the one set on creation + this.delay = 1000 / frameRate; + } + + if (typeof loop === 'boolean') + { + // If they set a new loop value then use it, otherwise use the one set on creation + this.loop = loop; + } + + if (typeof killOnComplete !== 'undefined') + { + // Remove the parent sprite once the animation has finished? + this.killOnComplete = killOnComplete; + } + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = this.isReversed ? this._frames.length - 1 : 0; + this.updateCurrentFrame(false, true); + + this._parent.events.onAnimationStart$dispatch(this._parent, this); + + this.onStart.dispatch(this._parent, this); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + return this; + + }, + + /** + * Sets this animation back to the first frame and restarts the animation. + * + * @method Phaser.Animation#restart + */ + restart: function () { + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = 0; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + this._parent.setFrame(this.currentFrame); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + this.onStart.dispatch(this._parent, this); + + }, + + /** + * Reverses the animation direction. + * + * @method Phaser.Animation#reverse + * @return {Phaser.Animation} The animation instance. + */ + reverse: function () { + + this.reversed = !this.reversed; + + return this; + + }, + + /** + * Reverses the animation direction for the current/next animation only + * Once the onComplete event is called this method will be called again and revert + * the reversed state. + * + * @method Phaser.Animation#reverseOnce + * @return {Phaser.Animation} The animation instance. + */ + reverseOnce: function () { + + this.onComplete.addOnce(this.reverse, this); + + return this.reverse(); + + }, + + /** + * Sets this animations playback to a given frame with the given ID. + * + * @method Phaser.Animation#setFrame + * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. + * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. + */ + setFrame: function(frameId, useLocalFrameIndex) { + + var frameIndex; + + if (useLocalFrameIndex === undefined) + { + useLocalFrameIndex = false; + } + + // Find the index to the desired frame. + if (typeof frameId === "string") + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frameData.getFrame(this._frames[i]).name === frameId) + { + frameIndex = i; + } + } + } + else if (typeof frameId === "number") + { + if (useLocalFrameIndex) + { + frameIndex = frameId; + } + else + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frames[i] === frameId) + { + frameIndex = i; + } + } + } + } + + if (frameIndex) + { + // Set the current frame index to the found index. Subtract a directional offset so that it animates to the desired frame on update. + var directionalOffset = this.isReversed ? -1 : 1; + this._frameIndex = frameIndex - directionalOffset; + + // Make the animation update at next update + this._timeNextFrame = this.game.time.time; + + this.update(); + } + + }, + + /** + * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. + * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. + * + * @method Phaser.Animation#stop + * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. + * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? + */ + stop: function (resetFrame, dispatchComplete) { + + if (resetFrame === undefined) { resetFrame = false; } + if (dispatchComplete === undefined) { dispatchComplete = false; } + + this.isPlaying = false; + this.isFinished = true; + this.paused = false; + + if (resetFrame) + { + this.currentFrame = this._frameData.getFrame(this._frames[0]); + this._parent.setFrame(this.currentFrame); + } + + if (dispatchComplete) + { + this._parent.events.onAnimationComplete$dispatch(this._parent, this); + this.onComplete.dispatch(this._parent, this); + } + + }, + + /** + * Called when the Game enters a paused state. + * + * @method Phaser.Animation#onPause + */ + onPause: function () { + + if (this.isPlaying) + { + this._frameDiff = this._timeNextFrame - this.game.time.time; + } + + }, + + /** + * Called when the Game resumes from a paused state. + * + * @method Phaser.Animation#onResume + */ + onResume: function () { + + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this._frameDiff; + } + + }, + + /** + * Updates this animation. Called automatically by the AnimationManager. + * + * @method Phaser.Animation#update + */ + update: function () { + + if (this.isPaused) + { + return false; + } + + if (this.isPlaying && this.game.time.time >= this._timeNextFrame) + { + this._frameSkip = 1; + + // Lagging? + this._frameDiff = this.game.time.time - this._timeNextFrame; + + this._timeLastFrame = this.game.time.time; + + if (this._frameDiff > this.delay) + { + // We need to skip a frame, work out how many + this._frameSkip = Math.floor(this._frameDiff / this.delay); + this._frameDiff -= (this._frameSkip * this.delay); + } + else + { + this._frameDiff = 0; + } + + // And what's left now? + this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff); + + if (this.isReversed) + { + this._frameIndex -= this._frameSkip; + } + else + { + this._frameIndex += this._frameSkip; + } + + if (!this.isReversed && this._frameIndex >= this._frames.length || this.isReversed && this._frameIndex <= -1) + { + if (this.loop) + { + // Update current state before event callback + this._frameIndex = Math.abs(this._frameIndex) % this._frames.length; + + if (this.isReversed) + { + this._frameIndex = this._frames.length - 1 - this._frameIndex; + } + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + // Instead of calling updateCurrentFrame we do it here instead + if (this.currentFrame) + { + this._parent.setFrame(this.currentFrame); + } + + this.loopCount++; + this._parent.events.onAnimationLoop$dispatch(this._parent, this); + this.onLoop.dispatch(this._parent, this); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + } + else + { + this.complete(); + return false; + } + } + else + { + return this.updateCurrentFrame(true); + } + } + + return false; + + }, + + /** + * Changes the currentFrame per the _frameIndex, updates the display state, + * and triggers the update signal. + * + * Returns true if the current frame update was 'successful', false otherwise. + * + * @method Phaser.Animation#updateCurrentFrame + * @private + * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. + * @param {boolean} fromPlay - Was this call made from the playing of a new animation? + * @return {boolean} True if the current frame was updated, otherwise false. + */ + updateCurrentFrame: function (signalUpdate, fromPlay) { + + if (fromPlay === undefined) { fromPlay = false; } + + if (!this._frameData) + { + // The animation is already destroyed, probably from a callback + return false; + } + + // Previous index + var idx = this.currentFrame.index; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index))) + { + this._parent.setFrame(this.currentFrame); + } + + if (this.onUpdate && signalUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + + }, + + /** + * Advances by the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex + quantity; + + if (frame >= this._frames.length) + { + if (this.loop) + { + frame %= this._frames.length; + } + else + { + frame = this._frames.length - 1; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex - quantity; + + if (frame < 0) + { + if (this.loop) + { + frame = this._frames.length + frame; + } + else + { + frame++; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Changes the FrameData object this Animation is using. + * + * @method Phaser.Animation#updateFrameData + * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. + */ + updateFrameData: function (frameData) { + + this._frameData = frameData; + this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null; + + }, + + /** + * Cleans up this animation ready for deletion. Nulls all values and references. + * + * @method Phaser.Animation#destroy + */ + destroy: function () { + + if (!this._frameData) + { + // Already destroyed + return; + } + + 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(); + + if (this.onUpdate) + { + this.onUpdate.dispose(); + } + + }, + + /** + * Called internally when the animation finishes playback. + * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. + * + * @method Phaser.Animation#complete + */ + complete: function () { + + this._frameIndex = this._frames.length - 1; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + 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; + +/** +* @name Phaser.Animation#paused +* @property {boolean} paused - Gets and sets the paused state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'paused', { + + get: function () { + + return this.isPaused; + + }, + + set: function (value) { + + this.isPaused = value; + + if (value) + { + // Paused + this._pauseStartTime = this.game.time.time; + } + else + { + // Un-paused + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this.delay; + } + } + + } + +}); + +/** +* @name Phaser.Animation#reversed +* @property {boolean} reversed - Gets and sets the isReversed state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'reversed', { + + get: function () { + + return this.isReversed; + + }, + + set: function (value) { + + this.isReversed = value; + + } + +}); + +/** +* @name Phaser.Animation#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @name Phaser.Animation#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +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.setFrame(this.currentFrame); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + } + } + + } + +}); + +/** +* @name Phaser.Animation#speed +* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'speed', { + + get: function () { + + return 1000 / this.delay; + + }, + + set: function (value) { + + if (value > 0) + { + this.delay = 1000 / value; + } + + } + +}); + +/** +* @name Phaser.Animation#enableUpdate +* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { + + get: function () { + + return (this.onUpdate !== null); + + }, + + set: function (value) { + + if (value && this.onUpdate === null) + { + this.onUpdate = new Phaser.Signal(); + } + else if (!value && this.onUpdate !== null) + { + this.onUpdate.dispose(); + this.onUpdate = null; + } + + } + +}); + +/** +* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. +* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' +* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); +* +* @method Phaser.Animation.generateFrameNames +* @static +* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. +* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. +* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. +* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'. +* @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. +* @return {string[]} An array of framenames. +*/ +Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { + + if (suffix === undefined) { suffix = ''; } + + var output = []; + var frame = ''; + + if (start < stop) + { + for (var i = start; i <= stop; i++) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + else + { + for (var i = start; i >= stop; i--) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + + return output; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Frame is a single frame of an animation and is part of a FrameData collection. +* +* @class Phaser.Frame +* @constructor +* @param {number} index - The index of this Frame within the FrameData set it is being added to. +* @param {number} x - X position of the frame within the texture image. +* @param {number} y - Y position of the frame within the texture image. +* @param {number} width - Width of the frame within the texture image. +* @param {number} height - Height of the frame within the texture image. +* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. +*/ +Phaser.Frame = function (index, x, y, width, height, name) { + + /** + * @property {number} index - The index of this Frame within the FrameData set it is being added to. + */ + this.index = index; + + /** + * @property {number} x - X position within the image to cut from. + */ + this.x = x; + + /** + * @property {number} y - Y position within the image to cut from. + */ + this.y = y; + + /** + * @property {number} width - Width of the frame. + */ + this.width = width; + + /** + * @property {number} height - Height of the frame. + */ + this.height = height; + + if (this.width === 0 || this.height === 0) + { + console.warn('Phaser.Frame: Frame "' + this.name + '" has a width or height of zero'); + } + + /** + * @property {string} name - Useful for Texture Atlas files (is set to the filename value). + */ + this.name = name; + + /** + * @property {number} centerX - Center X position within the image to cut from. + */ + this.centerX = Math.floor(width / 2); + + /** + * @property {number} centerY - Center Y position within the image to cut from. + */ + this.centerY = Math.floor(height / 2); + + /** + * @property {number} distance - The distance from the top left to the bottom-right of this Frame. + */ + this.distance = Phaser.Math.distance(0, 0, width, height); + + /** + * @property {boolean} rotated - Is the frame rotated in the source texture? + * @default + */ + this.rotated = false; + + /** + * @property {boolean} trimmed - Was it trimmed when packed? + * @default + */ + this.trimmed = false; + + /** + * @property {number} sourceSizeW - Width of the original sprite before it was trimmed. + */ + this.sourceSizeW = width; + + /** + * @property {number} sourceSizeH - Height of the original sprite before it was trimmed. + */ + this.sourceSizeH = height; + + /** + * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeX = 0; + + /** + * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeY = 0; + + /** + * @property {number} spriteSourceSizeW - Width of the trimmed sprite. + * @default + */ + this.spriteSourceSizeW = 0; + + /** + * @property {number} spriteSourceSizeH - Height of the trimmed sprite. + * @default + */ + this.spriteSourceSizeH = 0; + + /** + * @property {number} right - The right of the Frame (x + width). + */ + this.right = this.x + this.width; + + /** + * @property {number} bottom - The bottom of the frame (y + height). + */ + this.bottom = this.y + this.height; + +}; + +Phaser.Frame.prototype = { + + /** + * Adjusts of all the Frame properties based on the given width and height values. + * + * @method Phaser.Frame#resize + * @param {integer} width - The new width of the Frame. + * @param {integer} height - The new height of the Frame. + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + this.centerX = Math.floor(width / 2); + this.centerY = Math.floor(height / 2); + this.distance = Phaser.Math.distance(0, 0, width, height); + this.sourceSizeW = width; + this.sourceSizeH = height; + this.right = this.x + width; + this.bottom = this.y + height; + + }, + + /** + * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. + * + * @method Phaser.Frame#setTrim + * @param {boolean} trimmed - If this frame was trimmed or not. + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + */ + setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { + + this.trimmed = trimmed; + + if (trimmed) + { + 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; + } + + }, + + /** + * Clones this Frame into a new Phaser.Frame object and returns it. + * Note that all properties are cloned, including the name and index. + * + * @method Phaser.Frame#clone + * @return {Phaser.Frame} An exact copy of this Frame object. + */ + clone: function () { + + var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name); + + for (var prop in this) + { + if (this.hasOwnProperty(prop)) + { + output[prop] = this[prop]; + } + } + + return output; + + }, + + /** + * Returns a Rectangle set to the dimensions of this Frame. + * + * @method Phaser.Frame#getRect + * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to. + * @return {Phaser.Rectangle} A rectangle. + */ + getRect: function (out) { + + if (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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. +* +* @class Phaser.FrameData +* @constructor +*/ +Phaser.FrameData = function () { + + /** + * @property {Array} _frames - Local array of frames. + * @private + */ + this._frames = []; + + /** + * @property {Array} _frameNames - Local array of frame names for name to index conversions. + * @private + */ + this._frameNames = []; + +}; + +Phaser.FrameData.prototype = { + + /** + * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. + * + * @method Phaser.FrameData#addFrame + * @param {Phaser.Frame} frame - The frame to add to this FrameData set. + * @return {Phaser.Frame} The frame that was just added. + */ + addFrame: function (frame) { + + frame.index = this._frames.length; + + this._frames.push(frame); + + if (frame.name !== '') + { + this._frameNames[frame.name] = frame.index; + } + + return frame; + + }, + + /** + * Get a Frame by its numerical index. + * + * @method Phaser.FrameData#getFrame + * @param {number} index - The index of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or undefined. + */ + getFrame: function (index) { + + if (index >= this._frames.length) + { + index = 0; + } + + return this._frames[index]; + + }, + + /** + * Get a Frame by its frame name. + * + * @method Phaser.FrameData#getFrameByName + * @param {string} name - The name of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or null. + */ + getFrameByName: function (name) { + + if (typeof this._frameNames[name] === 'number') + { + return this._frames[this._frameNames[name]]; + } + + return null; + + }, + + /** + * Check if there is a Frame with the given name. + * + * @method Phaser.FrameData#checkFrameName + * @param {string} name - The name of the frame you want to check. + * @return {boolean} True if the frame is found, otherwise false. + */ + checkFrameName: function (name) { + + if (this._frameNames[name] == null) + { + return false; + } + + return true; + + }, + + /** + * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains. + * + * @method Phaser.FrameData#clone + * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains. + */ + clone: function () { + + var output = new Phaser.FrameData(); + + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output._frames.push(this._frames[i].clone()); + } + + for (var p in this._frameNames) + { + if (this._frameNames.hasOwnProperty(p)) + { + output._frameNames.push(this._frameNames[p]); + } + } + + return output; + + }, + + /** + * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. + * + * @method Phaser.FrameData#getFrameRange + * @param {number} start - The starting frame index. + * @param {number} end - The ending frame index. + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. + */ + getFrameRange: function (start, end, output) { + + if (output === undefined) { output = []; } + + for (var i = start; i <= end; i++) + { + output.push(this._frames[i]); + } + + return output; + + }, + + /** + * Returns all of the Frames in this FrameData set where the frame index is found in the input array. + * The frames are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrames + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. + */ + getFrames: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + // We only need the indexes + output.push(this._frames[i]); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the input array contain names or indexes? + if (useNumericIndex) + { + // The actual frame + output.push(this.getFrame(frames[i])); + } + else + { + // The actual frame + output.push(this.getFrameByName(frames[i])); + } + } + } + + return output; + + }, + + /** + * Returns all of the Frame indexes in this FrameData set. + * The frames indexes are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrameIndexes + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frame indexes matching the given names or IDs. + */ + getFrameIndexes: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No frames array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output.push(this._frames[i].index); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the frames array contain names or indexes? + if (useNumericIndex && this._frames[frames[i]]) + { + output.push(this._frames[frames[i]].index); + } + else + { + if (this.getFrameByName(frames[i])) + { + output.push(this.getFrameByName(frames[i]).index); + } + } + } + } + + return output; + + }, + + /** + * Destroys this FrameData collection by nulling the _frames and _frameNames arrays. + * + * @method Phaser.FrameData#destroy + */ + destroy: function () { + + this._frames = null; + this._frameNames = null; + + } + +}; + +Phaser.FrameData.prototype.constructor = Phaser.FrameData; + +/** +* @name Phaser.FrameData#total +* @property {number} total - The total number of frames in this FrameData set. +* @readonly +*/ +Object.defineProperty(Phaser.FrameData.prototype, "total", { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +* +* @class Phaser.AnimationParser +* @static +*/ +Phaser.AnimationParser = { + + /** + * Parse a Sprite Sheet and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.spriteSheet + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. + * @param {number} frameWidth - The fixed width of each frame of the animation. + * @param {number} frameHeight - The fixed height of each frame of the animation. + * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + var img = key; + + if (typeof key === 'string') + { + img = game.cache.getImage(key); + } + + if (img === null) + { + return null; + } + + var width = img.width; + var height = img.height; + + if (frameWidth <= 0) + { + frameWidth = Math.floor(-width / Math.min(-1, frameWidth)); + } + + if (frameHeight <= 0) + { + frameHeight = Math.floor(-height / Math.min(-1, frameHeight)); + } + + var row = Math.floor((width - margin) / (frameWidth + spacing)); + var column = Math.floor((height - margin) / (frameHeight + spacing)); + var total = row * column; + + if (skipFrames > total || skipFrames < -total) + { + console.warn( + "Phaser.AnimationParser.spriteSheet: skipFrames = " + + skipFrames.toString() + " is larger than total sprite number " + + total.toString()); + return null; + } + + if (skipFrames < 0) + { + // Allow negative skipframes. + skipFrames = total + skipFrames; + } + + if (frameMax !== -1) + { + total = skipFrames + frameMax; + } + + // Zero or smaller than frame sizes? + if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0) + { + console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight"); + return null; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var x = margin; + var y = margin; + + for (var i = 0; i < total; i++) + { + data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '')); + + x += frameWidth + spacing; + + if (x + frameWidth > width) + { + x = margin; + y += frameHeight + spacing; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONData: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].frame.x, + frames[i].frame.y, + frames[i].frame.w, + frames[i].frame.h, + frames[i].filename + )); + + if (frames[i].trimmed) + { + newFrame.setTrim( + frames[i].trimmed, + frames[i].sourceSize.w, + frames[i].sourceSize.h, + frames[i].spriteSourceSize.x, + frames[i].spriteSourceSize.y, + frames[i].spriteSourceSize.w, + frames[i].spriteSourceSize.h + ); + } + + if (frames[i].rotated) + { + newFrame.rotated = true; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataPyxel + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataPyxel: function (game, json) { + + // Malformed? There are a few keys to check here. + var signature = ['layers', 'tilewidth','tileheight','tileswide', 'tileshigh']; + + signature.forEach( function(key) { + if (!json[key]) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "' + key + '" key.'); + console.log(json); + return; + } + }); + + // For this purpose, I only care about parsing tilemaps with a single layer. + if (json['layers'].length !== 1) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps.'); + console.log(json); + return; + } + + var data = new Phaser.FrameData(); + + var tileheight = json['tileheight']; + var tilewidth = json['tilewidth']; + + var frames = json['layers'][0]['tiles']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].x, + frames[i].y, + tilewidth, + tileheight, + "frame_" + i // No names are included in pyxel tilemap data. + )); + + // No trim data is included. + newFrame.setTrim(false); + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataHash + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataHash: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + var i = 0; + + for (var key in frames) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[key].frame.x, + frames[key].frame.y, + frames[key].frame.w, + frames[key].frame.h, + key + )); + + if (frames[key].trimmed) + { + newFrame.setTrim( + frames[key].trimmed, + frames[key].sourceSize.w, + frames[key].sourceSize.h, + frames[key].spriteSourceSize.x, + frames[key].spriteSourceSize.y, + frames[key].spriteSourceSize.w, + frames[key].spriteSourceSize.h + ); + } + + if (frames[key].rotated) + { + newFrame.rotated = true; + } + + i++; + } + + return data; + + }, + + /** + * Parse the XML data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.XMLData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + XMLData: function (game, xml) { + + // Malformed? + if (!xml.getElementsByTagName('TextureAtlas')) + { + console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing tag"); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var frames = xml.getElementsByTagName('SubTexture'); + var newFrame; + + var name; + var frame; + var x; + var y; + var width; + var height; + var frameX; + var frameY; + var frameWidth; + var frameHeight; + + for (var i = 0; i < frames.length; i++) + { + frame = frames[i].attributes; + + name = frame.name.value; + x = parseInt(frame.x.value, 10); + y = parseInt(frame.y.value, 10); + width = parseInt(frame.width.value, 10); + height = parseInt(frame.height.value, 10); + + frameX = null; + frameY = null; + + if (frame.frameX) + { + frameX = Math.abs(parseInt(frame.frameX.value, 10)); + frameY = Math.abs(parseInt(frame.frameY.value, 10)); + frameWidth = parseInt(frame.frameWidth.value, 10); + frameHeight = parseInt(frame.frameHeight.value, 10); + } + + newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name)); + + // Trimmed? + if (frameX !== null || frameY !== null) + { + newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight); + } + } + + return data; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser has one single cache in which it stores all assets. +* +* The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using +* a unique string-based key as their identifier. Assets stored in different areas of the cache can have the +* same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, +* because they are unique data types. +* +* The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets +* such as images they are automatically placed into their respective cache. Most common Game Objects, such as +* Sprites and Videos automatically query the cache to extract the assets they need on instantiation. +* +* You can access the cache from within a State via `this.cache`. From here you can call any public method it has, +* including adding new entries to it, deleting them or querying them. +* +* Understand that almost without exception when you get an item from the cache it will return a reference to the +* item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original +* object in the cache will also be updated, even if you don't put it back into the cache again. +* +* By default when you change State the cache is _not_ cleared, although there is an option to clear it should +* your game require it. In a typical game set-up the cache is populated once after the main game has loaded and +* then used as an asset store. +* +* @class Phaser.Cache +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Cache = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. + * @property {boolean} autoResolveURL + */ + this.autoResolveURL = false; + + /** + * The main cache object into which all resources are placed. + * @property {object} _cache + * @private + */ + this._cache = { + canvas: {}, + image: {}, + texture: {}, + sound: {}, + video: {}, + text: {}, + json: {}, + xml: {}, + physics: {}, + tilemap: {}, + binary: {}, + bitmapData: {}, + bitmapFont: {}, + shader: {}, + renderTexture: {}, + compressedTexture: {} + }; + + /** + * @property {object} _urlMap - Maps URLs to resources. + * @private + */ + this._urlMap = {}; + + /** + * @property {Image} _urlResolver - Used to resolve URLs to the absolute path. + * @private + */ + this._urlResolver = new Image(); + + /** + * @property {string} _urlTemp - Temporary variable to hold a resolved url. + * @private + */ + this._urlTemp = null; + + /** + * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices. + */ + this.onSoundUnlock = new Phaser.Signal(); + + /** + * @property {array} _cacheMap - Const to cache object look-up array. + * @private + */ + this._cacheMap = []; + + this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas; + this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image; + this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture; + this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound; + this._cacheMap[Phaser.Cache.TEXT] = this._cache.text; + this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics; + this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap; + this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary; + this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData; + this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont; + this._cacheMap[Phaser.Cache.JSON] = this._cache.json; + this._cacheMap[Phaser.Cache.XML] = this._cache.xml; + this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video; + this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader; + this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture; + + /** + * @property {number} + * @private + */ + this._pendingCount = 0; + + /** + * Dispatched when the DEFAULT and MISSING images have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). + * + * @property {Phaser.Signal} onReady + */ + this.onReady = new Phaser.Signal(); + + this._addImages(); + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.CANVAS = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.IMAGE = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXTURE = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SOUND = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXT = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.PHYSICS = 6; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TILEMAP = 7; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BINARY = 8; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPDATA = 9; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPFONT = 10; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.JSON = 11; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.XML = 12; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.VIDEO = 13; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SHADER = 14; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.RENDER_TEXTURE = 15; + +/** +* The default image used for a texture when no other is specified. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.DEFAULT = null; + +/** + * Key for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_KEY = '__default'; + +/** + * URL for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='; + +/** +* The default image used for a texture when the source image is missing. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.MISSING = null; + +/** + * Key for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_KEY = '__missing'; + +/** + * URL for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='; + +/** +* The maximum amount of time (ms) to wait for the built-in DEFAULT and MISSING images to load. +* @static +* @type {number} +* @default +*/ +Phaser.Cache.READY_TIMEOUT = 1000; + +Phaser.Cache.prototype = { + + ////////////////// + // Add Methods // + ////////////////// + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCompressedTextureMetaData + * @private + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url + * @param {string} extension + * @param {array} arrayBuffer + * @return {object} The compressed texture entry. + */ + addCompressedTextureMetaData: function (key, url, extension, arrayBuffer) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + var data = (extension in Phaser.LoaderParser) ? Phaser.LoaderParser[extension](arrayBuffer) : arrayBuffer; + + var texture = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData(), + fileFormat: extension + }; + + texture.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = texture; + + this._resolveURL(url, texture); + + return texture; + + }, + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCanvas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {HTMLCanvasElement} canvas - The Canvas DOM element. + * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`. + */ + addCanvas: function (key, canvas, context) { + + if (context === undefined) { context = canvas.getContext('2d'); } + + this._cache.canvas[key] = { canvas: canvas, context: context }; + + }, + + /** + * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. + * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. + * + * If the image has not yet been fetched (successfully or not), a `console.warn` message will be displayed. + * + * @method Phaser.Cache#addImage + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra image data. + * @return {object} The full image object that was added to the cache. + */ + addImage: function (key, url, data) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + if (data.complete === false) + { + console.warn('Phaser.Cache.addImage: Image "' + key + '" hasn\'t been retrieved yet'); + } + + var img = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData() + }; + + img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = img; + + this._resolveURL(url, img); + + if (key === '__default') + { + Phaser.Cache.DEFAULT = new PIXI.Texture(img.base); + } + else if (key === '__missing') + { + Phaser.Cache.MISSING = new PIXI.Texture(img.base); + } + + return img; + + }, + + /** + * @method Phaser.Cache#addImageAsync + * @private + */ + addImageAsync: function (key, src, callback) { + + var self = this; + var img = new Image(); + + img.onload = function () { + callback.call(this, self.addImage(key, null, img)); + self._removePending(); + img.onload = null; + }; + + this._addPending(); + img.src = src; + + }, + + /** + * Adds a default image to be used in special cases such as WebGL Filters. + * It uses the special reserved key of `__default`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addDefaultImage + * @protected + */ + addDefaultImage: function () { + + this.addImageAsync(Phaser.Cache.DEFAULT_KEY, Phaser.Cache.DEFAULT_SRC, function (obj) { + // Because we don't want to invalidate the sprite batch for an invisible texture + obj.base.skipRender = true; + + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.DEFAULT = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds an image to be used when a key is wrong / missing. + * It uses the special reserved key of `__missing`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addMissingImage + * @protected + */ + addMissingImage: function () { + + this.addImageAsync(Phaser.Cache.MISSING_KEY, Phaser.Cache.MISSING_SRC, function (obj) { + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.MISSING = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addSound + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sound data. + * @param {boolean} webAudio - True if the file is using web audio. + * @param {boolean} audioTag - True if the file is using legacy HTML audio. + */ + addSound: function (key, url, data, webAudio, audioTag) { + + if (webAudio === undefined) { webAudio = true; audioTag = false; } + if (audioTag === undefined) { webAudio = false; audioTag = true; } + + var decoded = false; + + if (audioTag) + { + decoded = true; + } + + this._cache.sound[key] = { + url: url, + data: data, + isDecoding: false, + decoded: decoded, + webAudio: webAudio, + audioTag: audioTag, + locked: this.game.sound.touchLocked + }; + + this._resolveURL(url, this._cache.sound[key]); + + }, + + /** + * Add a new text data. + * + * @method Phaser.Cache#addText + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addText: function (key, url, data) { + + this._cache.text[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.text[key]); + + }, + + /** + * Add a new physics data object to the Cache. + * + * @method Phaser.Cache#addPhysicsData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} JSONData - The physics data object (a JSON file). + * @param {number} format - The format of the physics data. + */ + addPhysicsData: function (key, url, JSONData, format) { + + this._cache.physics[key] = { url: url, data: JSONData, format: format }; + + this._resolveURL(url, this._cache.physics[key]); + + }, + + /** + * Add a new tilemap to the Cache. + * + * @method Phaser.Cache#addTilemap + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} mapData - The tilemap data object (either a CSV or JSON file). + * @param {number} format - The format of the tilemap data. + */ + addTilemap: function (key, url, mapData, format) { + + this._cache.tilemap[key] = { url: url, data: mapData, format: format }; + + this._resolveURL(url, this._cache.tilemap[key]); + + }, + + /** + * Add a binary object in to the cache. + * + * @method Phaser.Cache#addBinary + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {object} binaryData - The binary object to be added to the cache. + */ + addBinary: function (key, binaryData) { + + this._cache.binary[key] = binaryData; + + }, + + /** + * Add a BitmapData object to the cache. + * + * @method Phaser.Cache#addBitmapData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. + * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. + * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. + */ + addBitmapData: function (key, bitmapData, frameData) { + + bitmapData.key = key; + + if (frameData === undefined) + { + frameData = new Phaser.FrameData(); + frameData.addFrame(bitmapData.textureFrame); + } + + this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData }; + + return bitmapData; + + }, + + /** + * Add a new Bitmap Font to the Cache. + * + * @method Phaser.Cache#addBitmapFont + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra font data. + * @param {object} atlasData - The Bitmap Font data. + * @param {string} [atlasType='xml'] - The format of the Bitmap Font data file: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) { + + var obj = { + url: url, + data: data, + font: null, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + if (atlasType === 'json') + { + obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + else + { + obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new Bitmap Font to the Cache, where the font texture is part of a Texture Atlas. + * + * The atlas must already exist in the cache, and be available based on the given `atlasKey`. + * + * The `atlasFrame` specifies the name of the frame within the atlas that the Bitmap Font is + * stored in. + * + * The `dataKey` is the key of the XML or JSON Bitmap Font Data, which must already be in + * the Cache. + * + * @method Phaser.Cache#addBitmapFontFromAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} atlasKey - The key of the Texture Atlas in the Cache. + * @param {string} atlasFrame - The frame of the Texture Atlas that the Bitmap Font is in. + * @param {string} dataKey - The key of the Bitmap Font data in the Cache + * @param {string} [dataType='xml'] - The format of the Bitmap Font data: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFontFromAtlas: function (key, atlasKey, atlasFrame, dataKey, dataType, xSpacing, ySpacing) { + + var frame = this.getFrameByName(atlasKey, atlasFrame); + + if (!frame) + { + return; + } + + var obj = { + font: null, + base: this.getBaseTexture(atlasKey), + frame: frame + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + var fontData; + + if (dataType === 'json') + { + fontData = this.getJSON(dataKey); + obj.font = Phaser.LoaderParser.jsonBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + else + { + fontData = this.getXML(dataKey); + obj.font = Phaser.LoaderParser.xmlBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + }, + + /** + * Add a new json object into the cache. + * + * @method Phaser.Cache#addJSON + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra json data. + */ + addJSON: function (key, url, data) { + + this._cache.json[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.json[key]); + + }, + + /** + * Add a new xml object into the cache. + * + * @method Phaser.Cache#addXML + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addXML: function (key, url, data) { + + this._cache.xml[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.xml[key]); + + }, + + /** + * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addVideo + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra video data. + * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. + */ + addVideo: function (key, url, data, isBlob) { + + this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true }; + + this._resolveURL(url, this._cache.video[key]); + + }, + + /** + * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addShader + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra shader data. + */ + addShader: function (key, url, data) { + + this._cache.shader[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.shader[key]); + + }, + + /** + * Add a new Phaser.RenderTexture in to the cache. + * + * @method Phaser.Cache#addRenderTexture + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture. + */ + addRenderTexture: function (key, texture) { + + this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') }; + + }, + + /** + * Add a new sprite sheet in to the cache. + * + * @method Phaser.Cache#addSpriteSheet + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sprite sheet data. + * @param {number} frameWidth - Width of the sprite sheet. + * @param {number} frameHeight - Height of the sprite sheet. + * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + */ + addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + var obj = { + key: key, + url: url, + data: data, + frameWidth: frameWidth, + frameHeight: frameHeight, + margin: margin, + spacing: spacing, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) + }; + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new texture atlas to the Cache. + * + * @method Phaser.Cache#addTextureAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra texture atlas data. + * @param {object} atlasData - Texture atlas frames data. + * @param {number} format - The format of the texture atlas. + */ + addTextureAtlas: function (key, url, data, atlasData, format) { + + var obj = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key); + } + else if (format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + obj.frameData = Phaser.AnimationParser.JSONDataPyxel(this.game, atlasData, key); + } + else + { + // Let's just work it out from the frames array + if (Array.isArray(atlasData.frames)) + { + obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key); + } + else + { + obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key); + } + } + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + //////////////////////////// + // Sound Related Methods // + //////////////////////////// + + /** + * Reload a Sound file from the server. + * + * @method Phaser.Cache#reloadSound + * @param {string} key - The key of the asset within the cache. + */ + reloadSound: function (key) { + + var _this = this; + + var sound = this.getSound(key); + + if (sound) + { + sound.data.src = sound.url; + + sound.data.addEventListener('canplaythrough', function () { + return _this.reloadSoundComplete(key); + }, false); + + sound.data.load(); + } + + }, + + /** + * Fires the onSoundUnlock event when the sound has completed reloading. + * + * @method Phaser.Cache#reloadSoundComplete + * @param {string} key - The key of the asset within the cache. + */ + reloadSoundComplete: function (key) { + + var sound = this.getSound(key); + + if (sound) + { + sound.locked = false; + this.onSoundUnlock.dispatch(key); + } + + }, + + /** + * Updates the sound object in the cache. + * + * @method Phaser.Cache#updateSound + * @param {string} key - The key of the asset within the cache. + */ + updateSound: function (key, property, value) { + + var sound = this.getSound(key); + + if (sound) + { + sound[property] = value; + } + + }, + + /** + * Add a new decoded sound. + * + * @method Phaser.Cache#decodedSound + * @param {string} key - The key of the asset within the cache. + * @param {object} data - Extra sound data. + */ + decodedSound: function (key, data) { + + var sound = this.getSound(key); + + sound.data = data; + sound.decoded = true; + sound.isDecoding = false; + + }, + + /** + * Check if the given sound has finished decoding. + * + * @method Phaser.Cache#isSoundDecoded + * @param {string} key - The key of the asset within the cache. + * @return {boolean} The decoded state of the Sound object. + */ + isSoundDecoded: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return sound.decoded; + } + + }, + + /** + * Check if the given sound is ready for playback. + * A sound is considered ready when it has finished decoding and the device is no longer touch locked. + * + * @method Phaser.Cache#isSoundReady + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the sound is decoded and the device is not touch locked. + */ + isSoundReady: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return (sound.decoded && !this.game.sound.touchLocked); + } + + }, + + //////////////////////// + // Check Key Methods // + //////////////////////// + + /** + * Checks if a key for the given cache object type exists. + * + * @method Phaser.Cache#checkKey + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists, otherwise false. + */ + checkKey: function (cache, key) { + + if (this._cacheMap[cache][key]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given URL has been loaded into the Cache. + * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. + * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox + * which may cause double-load instances. + * + * @method Phaser.Cache#checkURL + * @param {string} url - The url to check for in the cache. + * @return {boolean} True if the url exists, otherwise false. + */ + checkURL: function (url) { + + if (this._urlMap[this._resolveURL(url)]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given key exists in the Canvas Cache. + * + * @method Phaser.Cache#checkCanvasKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkCanvasKey: function (key) { + + return this.checkKey(Phaser.Cache.CANVAS, key); + + }, + + /** + * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. + * + * @method Phaser.Cache#checkImageKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkImageKey: function (key) { + + return this.checkKey(Phaser.Cache.IMAGE, key); + + }, + + /** + * Checks if the given key exists in the Texture Cache. + * + * @method Phaser.Cache#checkTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXTURE, key); + + }, + + /** + * Checks if the given key exists in the Sound Cache. + * + * @method Phaser.Cache#checkSoundKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkSoundKey: function (key) { + + return this.checkKey(Phaser.Cache.SOUND, key); + + }, + + /** + * Checks if the given key exists in the Text Cache. + * + * @method Phaser.Cache#checkTextKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXT, key); + + }, + + /** + * Checks if the given key exists in the Physics Cache. + * + * @method Phaser.Cache#checkPhysicsKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkPhysicsKey: function (key) { + + return this.checkKey(Phaser.Cache.PHYSICS, key); + + }, + + /** + * Checks if the given key exists in the Tilemap Cache. + * + * @method Phaser.Cache#checkTilemapKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTilemapKey: function (key) { + + return this.checkKey(Phaser.Cache.TILEMAP, key); + + }, + + /** + * Checks if the given key exists in the Binary Cache. + * + * @method Phaser.Cache#checkBinaryKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBinaryKey: function (key) { + + return this.checkKey(Phaser.Cache.BINARY, key); + + }, + + /** + * Checks if the given key exists in the BitmapData Cache. + * + * @method Phaser.Cache#checkBitmapDataKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapDataKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPDATA, key); + + }, + + /** + * Checks if the given key exists in the BitmapFont Cache. + * + * @method Phaser.Cache#checkBitmapFontKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapFontKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPFONT, key); + + }, + + /** + * Checks if the given key exists in the JSON Cache. + * + * @method Phaser.Cache#checkJSONKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkJSONKey: function (key) { + + return this.checkKey(Phaser.Cache.JSON, key); + + }, + + /** + * Checks if the given key exists in the XML Cache. + * + * @method Phaser.Cache#checkXMLKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkXMLKey: function (key) { + + return this.checkKey(Phaser.Cache.XML, key); + + }, + + /** + * Checks if the given key exists in the Video Cache. + * + * @method Phaser.Cache#checkVideoKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkVideoKey: function (key) { + + return this.checkKey(Phaser.Cache.VIDEO, key); + + }, + + /** + * Checks if the given key exists in the Fragment Shader Cache. + * + * @method Phaser.Cache#checkShaderKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkShaderKey: function (key) { + + return this.checkKey(Phaser.Cache.SHADER, key); + + }, + + /** + * Checks if the given key exists in the Render Texture Cache. + * + * @method Phaser.Cache#checkRenderTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkRenderTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key); + + }, + + //////////////// + // Get Items // + //////////////// + + /** + * Get an item from a cache based on the given key and property. + * + * This method is mostly used internally by other Cache methods such as `getImage` but is exposed + * publicly for your own use as well. + * + * @method Phaser.Cache#getItem + * @param {string} key - The key of the asset within the cache. + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output. + * @param {string} [property] - If you require a specific property from the cache item, specify it here. + * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. + */ + getItem: function (key, cache, method, property) { + + if (!this.checkKey(cache, key)) + { + if (method) + { + console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.'); + } + } + else + { + if (property === undefined) + { + return this._cacheMap[cache][key]; + } + else + { + return this._cacheMap[cache][key][property]; + } + } + + return null; + + }, + + /** + * Gets a Canvas object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getCanvas + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The canvas object or `null` if no item could be found matching the given key. + */ + getCanvas: function (key) { + + return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas'); + + }, + + /** + * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. + * + * If you need the image used by a bitmap font or similar then please use those respective 'get' methods. + * + * @method Phaser.Cache#getImage + * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. + * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned. + * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. + */ + getImage: function (key, full) { + + if (key === undefined || key === null) + { + key = '__default'; + } + + if (full === undefined) { full = false; } + + var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage'); + + if (img === null) + { + img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage'); + } + + if (full) + { + return img; + } + else + { + return img.data; + } + + }, + + /** + * Get a single texture frame by key. + * + * You'd only do this to get the default Frame created for a non-atlas / spritesheet image. + * + * @method Phaser.Cache#getTextureFrame + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Frame} The frame data. + */ + getTextureFrame: function (key) { + + return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame'); + + }, + + /** + * Gets a Phaser.Sound object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSound + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Sound} The sound object. + */ + getSound: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSound'); + + }, + + /** + * Gets a raw Sound data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSoundData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The sound data. + */ + getSoundData: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data'); + + }, + + /** + * Gets a Text object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getText + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The text data. + */ + getText: function (key) { + + return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data'); + + }, + + /** + * Gets a Physics Data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can get either the entire data set, a single object or a single fixture of an object from it. + * + * @method Phaser.Cache#getPhysicsData + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all. + * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. + * @return {object} The requested physics object data if found. + */ + getPhysicsData: function (key, object, fixtureKey) { + + var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data'); + + if (data === null || object === undefined || object === null) + { + return data; + } + else + { + if (data[object]) + { + var fixtures = data[object]; + + // Try to find a fixture by its fixture key if given + if (fixtures && fixtureKey) + { + for (var fixture in fixtures) + { + // This contains the fixture data of a polygon or a circle + fixture = fixtures[fixture]; + + // Test the key + if (fixture.fixtureKey === fixtureKey) + { + return fixture; + } + } + + // We did not find the requested fixture + console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"'); + } + else + { + return fixtures; + } + } + else + { + console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"'); + } + } + + return null; + + }, + + /** + * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getTilemapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The raw tilemap data in CSV or JSON format. + */ + getTilemapData: function (key) { + + return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData'); + + }, + + /** + * Gets a binary object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBinary + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The binary data object. + */ + getBinary: function (key) { + + return this.getItem(key, Phaser.Cache.BINARY, 'getBinary'); + + }, + + /** + * Gets a BitmapData object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. + */ + getBitmapData: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data'); + + }, + + /** + * Gets a Bitmap Font object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapFont + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not. + */ + getBitmapFont: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont'); + + }, + + /** + * Gets a JSON object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can either return the object by reference (the default), or return a clone + * of it by setting the `clone` argument to `true`. + * + * @method Phaser.Cache#getJSON + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false) + * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. + */ + getJSON: function (key, clone) { + + var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data'); + + if (data) + { + if (clone) + { + return Phaser.Utils.extend(true, Array.isArray(data) ? [] : {}, data); + } + else + { + return data; + } + } + else + { + return null; + } + + }, + + /** + * Gets an XML object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getXML + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The XML object. + */ + getXML: function (key) { + + return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data'); + + }, + + /** + * Gets a Phaser.Video object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getVideo + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Video} The video object. + */ + getVideo: function (key) { + + return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo'); + + }, + + /** + * Gets a fragment shader object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getShader + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {string} The shader object. + */ + getShader: function (key) { + + return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data'); + + }, + + /** + * Gets a RenderTexture object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getRenderTexture + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame. + */ + getRenderTexture: function (key) { + + return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture'); + + }, + + //////////////////////////// + // Frame Related Methods // + //////////////////////////// + + /** + * Gets a PIXI.BaseTexture by key from the given Cache. + * + * @method Phaser.Cache#getBaseTexture + * @param {string} key - Asset key of the image for which you want the BaseTexture for. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {PIXI.BaseTexture} The BaseTexture object. + */ + getBaseTexture: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getBaseTexture', 'base'); + + }, + + /** + * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. + * + * @method Phaser.Cache#getFrame + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.Frame} The frame data. + */ + getFrame: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrame', 'frame'); + + }, + + /** + * Get the total number of frames contained in the FrameData object specified by the given key. + * + * @method Phaser.Cache#getFrameCount + * @param {string} key - Asset key of the FrameData you want. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {number} Then number of frames. 0 if the image is not found. + */ + getFrameCount: function (key, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.total; + } + else + { + return 0; + } + + }, + + /** + * Gets a Phaser.FrameData object from the Image Cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.FrameData} The frame data. + */ + getFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrameData', 'frameData'); + + }, + + /** + * Check if the FrameData for the given key exists in the Image Cache. + * + * @method Phaser.Cache#hasFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {boolean} True if the given key has frameData in the cache, otherwise false. + */ + hasFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return (this.getItem(key, cache, '', 'frameData') !== null); + + }, + + /** + * Replaces a set of frameData with a new Phaser.FrameData object. + * + * @method Phaser.Cache#updateFrameData + * @param {string} key - The unique key by which you will reference this object. + * @param {number} frameData - The new FrameData. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + */ + updateFrameData: function (key, frameData, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + if (this._cacheMap[cache][key]) + { + this._cacheMap[cache][key].frameData = frameData; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByIndex + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {number} index - The index of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByIndex: function (key, index, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrame(index); + } + else + { + return null; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByName + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {string} name - The name of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByName: function (key, name, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrameByName(name); + } + else + { + return null; + } + + }, + + /** + * Get a cached object by the URL. + * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. + * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. + * + * @method Phaser.Cache#getURL + * @param {string} url - The url for the object loaded to get from the cache. + * @return {object} The cached object. + */ + getURL: function (url) { + + var url = this._resolveURL(url); + + if (url) + { + return this._urlMap[url]; + } + else + { + console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false'); + return null; + } + + }, + + /** + * Gets all keys used in the requested Cache. + * + * @method Phaser.Cache#getKeys + * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. + * @return {Array} The array of keys in the requested cache. + */ + getKeys: function (cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + var out = []; + + if (this._cacheMap[cache]) + { + for (var key in this._cacheMap[cache]) + { + if (key !== '__default' && key !== '__missing') + { + out.push(key); + } + } + } + + return out; + + }, + + ///////////////////// + // Remove Methods // + ///////////////////// + + /** + * Removes a canvas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeCanvas + * @param {string} key - Key of the asset you want to remove. + */ + removeCanvas: function (key) { + + delete this._cache.canvas[key]; + + }, + + /** + * Removes an image from the cache. + * + * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. + * + * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeImage + * @param {string} key - Key of the asset you want to remove. + * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed? + */ + removeImage: function (key, destroyBaseTexture) { + + if (destroyBaseTexture === undefined) { destroyBaseTexture = true; } + + var img = this.getImage(key, true); + + if (destroyBaseTexture && img.base) + { + img.base.destroy(); + } + + delete this._cache.image[key]; + + }, + + /** + * Removes a sound from the cache. + * + * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will + * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then + * you must finish your house-keeping and destroy them all yourself first, before calling this method. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSound + * @param {string} key - Key of the asset you want to remove. + */ + removeSound: function (key) { + + delete this._cache.sound[key]; + + }, + + /** + * Removes a text file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeText + * @param {string} key - Key of the asset you want to remove. + */ + removeText: function (key) { + + delete this._cache.text[key]; + + }, + + /** + * Removes a physics data file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removePhysics + * @param {string} key - Key of the asset you want to remove. + */ + removePhysics: function (key) { + + delete this._cache.physics[key]; + + }, + + /** + * Removes a tilemap from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTilemap + * @param {string} key - Key of the asset you want to remove. + */ + removeTilemap: function (key) { + + delete this._cache.tilemap[key]; + + }, + + /** + * Removes a binary file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBinary + * @param {string} key - Key of the asset you want to remove. + */ + removeBinary: function (key) { + + delete this._cache.binary[key]; + + }, + + /** + * Removes a bitmap data from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapData + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapData: function (key) { + + delete this._cache.bitmapData[key]; + + }, + + /** + * Removes a bitmap font from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapFont + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapFont: function (key) { + + delete this._cache.bitmapFont[key]; + + }, + + /** + * Removes a json object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeJSON + * @param {string} key - Key of the asset you want to remove. + */ + removeJSON: function (key) { + + delete this._cache.json[key]; + + }, + + /** + * Removes a xml object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeXML + * @param {string} key - Key of the asset you want to remove. + */ + removeXML: function (key) { + + delete this._cache.xml[key]; + + }, + + /** + * Removes a video from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeVideo + * @param {string} key - Key of the asset you want to remove. + */ + removeVideo: function (key) { + + delete this._cache.video[key]; + + }, + + /** + * Removes a shader from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeShader + * @param {string} key - Key of the asset you want to remove. + */ + removeShader: function (key) { + + delete this._cache.shader[key]; + + }, + + /** + * Removes a Render Texture from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeRenderTexture + * @param {string} key - Key of the asset you want to remove. + */ + removeRenderTexture: function (key) { + + delete this._cache.renderTexture[key]; + + }, + + /** + * Removes a Sprite Sheet from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSpriteSheet + * @param {string} key - Key of the asset you want to remove. + */ + removeSpriteSheet: function (key) { + + delete this._cache.spriteSheet[key]; + + }, + + /** + * Removes a Texture Atlas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTextureAtlas + * @param {string} key - Key of the asset you want to remove. + */ + removeTextureAtlas: function (key) { + + delete this._cache.image[key]; + + }, + + /** + * Empties out all of the GL Textures from Images stored in the cache. + * This is called automatically when the WebGL context is lost and then restored. + * + * @method Phaser.Cache#clearGLTextures + * @protected + */ + clearGLTextures: function () { + + for (var key in this._cache.image) + { + this._cache.image[key].base._glTextures = []; + } + + }, + + /** + * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`. + * This is then looked-up by the Cache.getURL and Cache.checkURL calls. + * + * @method Phaser.Cache#_resolveURL + * @private + * @param {string} url - The URL to resolve. This is appended to Loader.baseURL. + * @param {object} [data] - The data associated with the URL to be stored to the URL Map. + * @return {string} The resolved URL. + */ + _resolveURL: function (url, data) { + + if (!this.autoResolveURL) + { + return null; + } + + this._urlResolver.src = this.game.load.baseURL + url; + + this._urlTemp = this._urlResolver.src; + + // Ensure no request is actually made + this._urlResolver.src = ''; + + // Record the URL to the map + if (data) + { + this._urlMap[this._urlTemp] = data; + } + + return this._urlTemp; + + }, + + /** + * Clears the cache. Removes every local cache object reference. + * If an object in the cache has a `destroy` method it will be called; + * otherwise, `destroy` will be called on any of the object's `base`, `data`, + * `frameData`, or `texture` properties. + * + * @method Phaser.Cache#destroy + */ + destroy: function () { + + for (var i = 0; i < this._cacheMap.length; i++) + { + var cache = this._cacheMap[i]; + + for (var key in cache) + { + if (key !== '__default' && key !== '__missing') + { + this.destroyItem(cache[key]); + + delete cache[key]; + } + } + } + + this._urlMap = null; + this._urlResolver = null; + this._urlTemp = null; + + }, + + /** + * @method Phaser.Cache#destroyItem + * @protected + * @param {object} item + */ + destroyItem: function (item) { + + if (item.destroy) + { + item.destroy(); + } + else + { + if (item.base && item.base.destroy) + { + item.base.destroy(); + } + + if (item.data && item.data.destroy) + { + item.data.destroy(); + } + + if (item.frameData && item.frameData.destroy) + { + item.frameData.destroy(); + } + + if (item.texture && item.texture.destroy) + { + item.texture.destroy(true); + } + } + + }, + + /** + * Starts loading the DEFAULT and MISSING images. + * + * @private + */ + _addImages: function () { + + this._pendingCount = 0; + + this.addDefaultImage(); + this.addMissingImage(); + + var self = this; + var readyTimeout = Phaser.Cache.READY_TIMEOUT; + + if (Phaser.Cache.READY_TIMEOUT > 0) + { + setTimeout(function () { + if (!self.isReady) + { + console.warn('Phaser.Cache: Still waiting for images after %s ms.', readyTimeout); + + self._ready(); + } + }, Phaser.Cache.READY_TIMEOUT); + } + else + { + this._ready(); + } + + }, + + + /** + * Increments the pending count. + * + * @private + */ + _addPending: function () { + + this._pendingCount += 1; + + }, + + + /** + * Decrements the pending count and checks if complete. + * + * @private + */ + _removePending: function () { + + this._pendingCount -= 1; + this._checkReady(); + + }, + + + /** + * Calls {@link #_ready} if no pending items remain. + * + * @private + */ + _checkReady: function () { + + if (this.isReady) + { + this._ready(); + } + + }, + + + /** + * Resets pending count and triggers {@link #onReady}. + * + * @private + */ + _ready: function () { + + this._pendingCount = 0; + this.onReady.dispatch(this); + + } + +}; + +Phaser.Cache.prototype.constructor = Phaser.Cache; + +/** +* The DEFAULT and MISSING textures have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). +* +* @property {boolean} Phaser.Cache#isReady +*/ +Object.defineProperty(Phaser.Cache.prototype, 'isReady', { + get: function () { + return this._pendingCount <= 0; + } +}); + +/* jshint wsh:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* +* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. +* +* Parallel loading (see {@link #enableParallel}) is supported and enabled by default. +* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}. +* +* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and +* [Shoebox](http://renderhjs.net/shoebox/) +* +* @class Phaser.Loader +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Loader = function (game) { + + /** + * Local reference to game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + /** + * Local reference to the Phaser.Cache. + * @property {Phaser.Cache} cache + * @protected + */ + this.cache = game.cache; + + /** + * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * True if the Loader is in the process of loading the queue. + * @property {boolean} isLoading + * @default + */ + this.isLoading = false; + + /** + * True if all assets in the queue have finished loading. + * @property {boolean} hasLoaded + * @default + */ + this.hasLoaded = false; + + /** + * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}. + * + * This property is an object containing: sprite, rect, direction, width and height + * + * @property {?object} preloadSprite + * @protected + */ + this.preloadSprite = null; + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * @property {boolean|string} crossOrigin + * @default + */ + this.crossOrigin = false; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * Useful if allowing the asset base url to be configured outside of the game code. + * The string _must_ end with a "/". + * + * @property {string} baseURL + */ + this.baseURL = ''; + + /** + * The value of `path`, if set, is placed before any _relative_ file path given. For example: + * + * ```javascript + * load.path = "images/sprites/"; + * load.image("ball", "ball.png"); + * load.image("tree", "level1/oaktree.png"); + * load.image("boom", "http://server.com/explode.png"); + * ``` + * + * Would load the `ball` file from `images/sprites/ball.png` and the tree from + * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL + * given as it's an absolute URL. + * + * Please note that the path is added before the filename but *after* the baseURL (if set.) + * + * The string _must_ end with a "/". + * + * @property {string} path + */ + this.path = ''; + + /** + * Used to map the application mime-types to to the Accept header in XHR requests. + * If you don't require these mappings, or they cause problems on your server, then + * remove them from the headers object and the XHR request will not try to use them. + * + * This object can also be used to set the `X-Requested-With` header to + * `XMLHttpRequest` (or any other value you need). To enable this do: + * + * ```javascript + * this.load.headers.requestedWith = 'XMLHttpRequest' + * ``` + * + * before adding anything to the Loader. The XHR loader will then call: + * + * ```javascript + * setRequestHeader('X-Requested-With', this.headers['requestedWith']) + * ``` + * + * @property {object} headers + * @default + */ + this.headers = { + "requestedWith": false, + "json": "application/json", + "xml": "application/xml" + }; + + /** + * This event is dispatched when the loading process starts: before the first file has been requested, + * but after all the initial packs have been loaded. + * + * @property {Phaser.Signal} onLoadStart + */ + this.onLoadStart = new Phaser.Signal(); + + /** + * This event is dispatched when the final file in the load queue has either loaded or failed. + * + * @property {Phaser.Signal} onLoadComplete + */ + this.onLoadComplete = new Phaser.Signal(); + + /** + * This event is dispatched when an asset pack has either loaded or failed to load. + * + * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. + * + * Params: `(pack key, success?, total packs loaded, total packs)` + * + * @property {Phaser.Signal} onPackComplete + */ + this.onPackComplete = new Phaser.Signal(); + + /** + * This event is dispatched immediately before a file starts loading. + * It's possible the file may fail (eg. download error, invalid format) after this event is sent. + * + * Params: `(progress, file key, file url)` + * + * @property {Phaser.Signal} onFileStart + */ + this.onFileStart = new Phaser.Signal(); + + /** + * This event is dispatched when a file has either loaded or failed to load. + * + * Any function bound to this will receive the following parameters: + * + * progress, file key, success?, total loaded files, total files + * + * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. + * + * @property {Phaser.Signal} onFileComplete + */ + this.onFileComplete = new Phaser.Signal(); + + /** + * This event is dispatched when a file (or pack) errors as a result of the load request. + * + * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. + * + * Params: `(file key, file)` + * + * @property {Phaser.Signal} onFileError + */ + this.onFileError = new Phaser.Signal(); + + /** + * If true (the default) then parallel downloading will be enabled. + * + * To disable all parallel downloads this must be set to false prior to any resource being loaded. + * + * @property {boolean} enableParallel + */ + this.enableParallel = true; + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Many current browsers limit 6 requests per domain; this is slightly conservative. + * + * This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently. + * + * @property {integer} maxParallelDownloads + */ + this.maxParallelDownloads = 4; + + /** + * A counter: if more than zero, files will be automatically added as a synchronization point. + * @property {integer} _withSyncPointDepth; + */ + this._withSyncPointDepth = 0; + + /** + * Contains all the information for asset files (including packs) to load. + * + * File/assets are only removed from the list after all loading completes. + * + * @property {file[]} _fileList + * @private + */ + this._fileList = []; + + /** + * Inflight files (or packs) that are being fetched/processed. + * + * This means that if there are any files in the flight queue there should still be processing + * going on; it should only be empty before or after loading. + * + * The files in the queue may have additional properties added to them, + * including `requestObject` which is normally the associated XHR. + * + * @property {file[]} _flightQueue + * @private + */ + this._flightQueue = []; + + /** + * The offset into the fileList past all the complete (loaded or error) entries. + * + * @property {integer} _processingHead + * @private + */ + this._processingHead = 0; + + /** + * True when the first file (not pack) has loading started. + * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded. + * + * @property {boolean} _initialPacksLoaded + * @private + */ + this._fileLoadStarted = false; + + /** + * Total packs seen - adjusted when a pack is added. + * @property {integer} _totalPackCount + * @private + */ + this._totalPackCount = 0; + + /** + * Total files seen - adjusted when a file is added. + * @property {integer} _totalFileCount + * @private + */ + this._totalFileCount = 0; + + /** + * Total packs loaded - adjusted just prior to `onPackComplete`. + * @property {integer} _loadedPackCount + * @private + */ + this._loadedPackCount = 0; + + /** + * Total files loaded - adjusted just prior to `onFileComplete`. + * @property {integer} _loadedFileCount + * @private + */ + this._loadedFileCount = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_PHASER_JSON = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5; + +Phaser.Loader.prototype = { + + /** + * Set a Sprite to be a "preload" sprite by passing it to this method. + * + * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. + * This allows you to easily make loading bars for games. + * + * The sprite will automatically be made visible when calling this. + * + * @method Phaser.Loader#setPreloadSprite + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load. + * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. + */ + setPreloadSprite: function (sprite, direction) { + + direction = direction || 0; + + this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null }; + + if (direction === 0) + { + // Horizontal rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height); + } + else + { + // Vertical rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1); + } + + sprite.crop(this.preloadSprite.rect); + + sprite.visible = true; + + }, + + /** + * Called automatically by ScaleManager when the game resizes in RESIZE scalemode. + * + * This can be used to adjust the preloading sprite size, eg. + * + * @method Phaser.Loader#resize + * @protected + */ + resize: function () { + + if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height) + { + this.preloadSprite.rect.height = this.preloadSprite.sprite.height; + } + + }, + + /** + * Check whether a file/asset with a specific key is queued to be loaded. + * + * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey} + * + * @method Phaser.Loader#checkKeyExists + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ + checkKeyExists: function (type, key) { + + return this.getAssetIndex(type, key) > -1; + + }, + + /** + * Get the queue-index of the file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAssetIndex + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {number} The index of this key in the filelist, or -1 if not found. + * The index may change and should only be used immediately following this call + */ + getAssetIndex: function (type, key) { + + var bestFound = -1; + + for (var i = 0; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + if (file.type === type && file.key === key) + { + bestFound = i; + + // An already loaded/loading file may be superceded. + if (!file.loaded && !file.loading) + { + break; + } + } + } + + return bestFound; + + }, + + /** + * Find a file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAsset + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. + * The index may change and should only be used immediately following this call. + */ + getAsset: function (type, key) { + + var fileIndex = this.getAssetIndex(type, key); + + if (fileIndex > -1) + { + return { index: fileIndex, file: this._fileList[fileIndex] }; + } + + return false; + + }, + + /** + * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. + * + * This will abort any loading and clear any queued assets. + * + * Optionally you can clear any associated events. + * + * @method Phaser.Loader#reset + * @protected + * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared. + * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them. + */ + reset: function (hard, clearEvents) { + + if (clearEvents === undefined) { clearEvents = false; } + + if (this.resetLocked) + { + return; + } + + if (hard) + { + this.preloadSprite = null; + } + + this.isLoading = false; + + this._processingHead = 0; + this._fileList.length = 0; + this._flightQueue.length = 0; + + this._fileLoadStarted = false; + this._totalFileCount = 0; + this._totalPackCount = 0; + this._loadedPackCount = 0; + this._loadedFileCount = 0; + + if (clearEvents) + { + this.onLoadStart.removeAll(); + this.onLoadComplete.removeAll(); + this.onPackComplete.removeAll(); + this.onFileStart.removeAll(); + this.onFileComplete.removeAll(); + this.onFileError.removeAll(); + } + + }, + + /** + * Internal function that adds a new entry to the file list. Do not call directly. + * + * @method Phaser.Loader#addToFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} [url] - The URL the asset will be loaded from. + * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. + * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. + * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. + * @return {Phaser.Loader} This instance of the Phaser Loader. + */ + addToFileList: function (type, key, url, properties, overwrite, extension) { + + if (overwrite === undefined) { overwrite = false; } + + if (key === undefined || key === '') + { + console.warn("Phaser.Loader: Invalid or no key given of type " + type); + return this; + } + + if (url === undefined || url === null) + { + if (extension) + { + url = key + extension; + } + else + { + console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key); + return this; + } + } + + var file = { + type: type, + key: key, + path: this.path, + url: url, + syncPoint: this._withSyncPointDepth > 0, + data: null, + loading: false, + loaded: false, + error: false + }; + + if (properties) + { + for (var prop in properties) + { + file[prop] = properties[prop]; + } + } + + var fileIndex = this.getAssetIndex(type, key); + + if (overwrite && fileIndex > -1) + { + var currentFile = this._fileList[fileIndex]; + + if (!currentFile.loading && !currentFile.loaded) + { + this._fileList[fileIndex] = file; + } + else + { + this._fileList.push(file); + this._totalFileCount++; + } + } + else if (fileIndex === -1) + { + this._fileList.push(file); + this._totalFileCount++; + } + + return this; + + }, + + /** + * Internal function that replaces an existing entry in the file list with a new one. Do not call directly. + * + * @method Phaser.Loader#replaceInFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} url - The URL the asset will be loaded from. + * @param {object} properties - Any additional properties needed to load the file. + */ + replaceInFileList: function (type, key, url, properties) { + + return this.addToFileList(type, key, url, properties, true); + + }, + + /** + * Add a JSON resource pack ('packfile') to the Loader. + * + * A packfile is a JSON file that contains a list of assets to the be loaded. + * Please see the example 'loader/asset pack' in the Phaser Examples repository. + * + * Packs are always put before the first non-pack file that is not loaded / loading. + * + * This means that all packs added before any loading has started are added to the front + * of the file queue, in the order added. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#pack + * @param {string} key - Unique asset key of this resource pack. + * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. + * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO + * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. + * @return {Phaser.Loader} This Loader instance. + */ + pack: function (key, url, data, callbackContext) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (callbackContext === undefined) { callbackContext = null; } + + if (!url && !data) + { + console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.'); + + return this; + } + + var pack = { + type: 'packfile', + key: key, + url: url, + path: this.path, + syncPoint: true, + data: null, + loading: false, + loaded: false, + error: false, + callbackContext: callbackContext + }; + + // A data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + pack.data = data || {}; + + // Already consider 'loaded' + pack.loaded = true; + } + + // Add before first non-pack/no-loaded ~ last pack from start prior to loading + // (Read one past for splice-to-end) + for (var i = 0; i < this._fileList.length + 1; i++) + { + var file = this._fileList[i]; + + if (!file || (!file.loaded && !file.loading && file.type !== 'packfile')) + { + this._fileList.splice(i, 0, pack); + this._totalPackCount++; + break; + } + } + + return this; + + }, + + /** + * Adds an Image to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * This method also supports passing in a texture object as the `url` argument. This allows you to load + * compressed textures into Phaser. You can also use `Loader.texture` to do this. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.image('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * @method Phaser.Loader#image + * @param {string} key - Unique asset key of this image file. + * @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + image: function (key, url, overwrite) { + + if (typeof url === 'object') + { + return this.texture(key, url, overwrite); + } + else + { + return this.addToFileList('image', key, url, undefined, overwrite, '.png'); + } + + }, + + /** + * Generate an image from a BitmapData object and add it to the current load queue. + * + * @method Phaser.Loader#imageFromBitmapData + * @param {string} key - Unique asset key for the generated image. + * @param {Phaser.BitmapData} bitmapData + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + imageFromBitmapData: function (key, bitmapData, overwrite) { + + return this.image(key, bitmapData.canvas.toDataURL('image/png'), overwrite); + + }, + + /** + * Generate a grid image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromGrid + * @see Phaser.Create#grid + */ + imageFromGrid: function (key, width, height, cellWidth, cellHeight, color) { + + return this.imageFromBitmapData(key, this.game.create.grid(key, width, height, cellWidth, cellHeight, color, false)); + + }, + + /** + * Generate a texture image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromTexture + * @see Phaser.Create#texture + */ + imageFromTexture: function (key, data, pixelWidth, pixelHeight, palette) { + + return this.imageFromBitmapData(key, this.game.create.texture(key, data, pixelWidth, pixelHeight, palette, false)); + + }, + + /** + * Adds a Compressed Texture Image to the current load queue. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.texture('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#texture + * @param {string} key - Unique asset key of this image file. + * @param {object} object - The texture path data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + texture: function (key, object, overwrite) { + + if (this.game.renderType === Phaser.WEBGL) + { + var compression = this.game.renderer.extensions.compression; + var exkey; + + for (exkey in object) + { + if (exkey.toUpperCase() in compression) + { + return this.addToFileList('texture', key, object[exkey], undefined, overwrite, '.pvr'); + } + } + } + + // Check if we have a truecolor texture to fallback. + // Also catches calls to this function that are from a Canvas renderer + + if (object['truecolor']) + { + this.addToFileList('image', key, object['truecolor'], undefined, overwrite, '.png'); + } + + return this; + + }, + + /** + * Adds an array of images to the current load queue. + * + * It works by passing each element of the array to the Loader.image method. + * + * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. + * + * Retrieve the images via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#images + * @param {array} keys - An array of unique asset keys of the image files. + * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. + * @return {Phaser.Loader} This Loader instance. + */ + images: function (keys, urls) { + + if (Array.isArray(urls)) + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i], urls[i]); + } + } + else + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i]); + } + } + + return this; + + }, + + /** + * Adds a Text file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getText(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#text + * @param {string} key - Unique asset key of the text file. + * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + text: function (key, url, overwrite) { + + return this.addToFileList('text', key, url, undefined, overwrite, '.txt'); + + }, + + /** + * Adds a JSON file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#json + * @param {string} key - Unique asset key of the json file. + * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + json: function (key, url, overwrite) { + + return this.addToFileList('json', key, url, undefined, overwrite, '.json'); + + }, + + /** + * Adds a fragment shader file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getShader(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" + * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#shader + * @param {string} key - Unique asset key of the fragment file. + * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + shader: function (key, url, overwrite) { + + return this.addToFileList('shader', key, url, undefined, overwrite, '.frag'); + + }, + + /** + * Adds an XML file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getXML(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#xml + * @param {string} key - Unique asset key of the xml file. + * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + xml: function (key, url, overwrite) { + + return this.addToFileList('xml', key, url, undefined, overwrite, '.xml'); + + }, + + /** + * Adds a JavaScript file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. + * If you do not desire this action then provide a URL. + * + * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! + * + * A callback, which will be invoked as the script tag has been created, can also be specified. + * The callback must return relevant `data`. + * + * @method Phaser.Loader#script + * @param {string} key - Unique asset key of the script file. + * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing. + * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. + * @return {Phaser.Loader} This Loader instance. + */ + script: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + if (callback !== false && callbackContext === undefined) { callbackContext = this; } + + return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js'); + + }, + + /** + * Adds a binary file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBinary(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. + * If you do not desire this action then provide a URL. + * + * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. + * When the callback is called it will be passed 2 parameters: the key of the file and the file data. + * + * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. + * + * @method Phaser.Loader#binary + * @param {string} key - Unique asset key of the binary file. + * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it. + * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context. + * @return {Phaser.Loader} This Loader instance. + */ + binary: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + // Why is the default callback context the ..callback? + if (callback !== false && callbackContext === undefined) { callbackContext = callback; } + + return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin'); + + }, + + /** + * Adds a Sprite Sheet to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal + * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. + * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. + * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming + * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. + * If you've got an atlas then use `Loader.atlas` instead. + * + * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#spritesheet + * @param {string} key - Unique asset key of the sheet file. + * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet. + * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.Loader} This Loader instance. + */ + spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing, skipFrames: skipFrames }, false, '.png'); + + }, + + /** + * Adds an audio file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getSound(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. + * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. + * The solution is to use a lower encoding rate such as 44100 Hz. + * + * @method Phaser.Loader#audio + * @param {string} key - Unique asset key of the audio file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp3']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audio: function (key, urls, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (autoDecode === undefined) { autoDecode = true; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); + + }, + + /** + * Adds an audio sprite file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Audio Sprites are a combination of audio files and a JSON configuration. + * + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * Retrieve the file via `Cache.getSoundData(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#audioSprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (jsonURL === undefined) { jsonURL = null; } + if (jsonData === undefined) { jsonData = null; } + if (autoDecode === undefined) { autoDecode = true; } + + this.audio(key, urls, autoDecode); + + if (jsonURL) + { + this.json(key + '-audioatlas', jsonURL); + } + else if (jsonData) + { + if (typeof jsonData === 'string') + { + jsonData = JSON.parse(jsonData); + } + + this.cache.addJSON(key + '-audioatlas', '', jsonData); + } + else + { + console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object'); + } + + return this; + + }, + + /** + * A legacy alias for Loader.audioSprite. Please see that method for documentation. + * + * @method Phaser.Loader#audiosprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode); + + }, + + /** + * Adds a video file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getVideo(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. + * + * @method Phaser.Loader#video + * @param {string} key - Unique asset key of the video file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp4']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete. + * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. + * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. + * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the + * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. + * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set. + * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. + * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. + * @return {Phaser.Loader} This Loader instance. + */ + video: function (key, urls, loadEvent, asBlob) { + + if (loadEvent === undefined) + { + if (this.game.device.firefox) + { + loadEvent = 'loadeddata'; + } + else + { + loadEvent = 'canplaythrough'; + } + } + + if (asBlob === undefined) { asBlob = false; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent }); + + }, + + /** + * Adds a Tile Map data file to the current load queue. + * + * Phaser can load data in two different formats: CSV and Tiled JSON. + * + * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". + * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#tilemap + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. + * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + * @return {Phaser.Loader} This Loader instance. + */ + tilemap: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Tilemap.CSV; } + + if (!url && !data) + { + if (format === Phaser.Tilemap.CSV) + { + url = key + '.csv'; + } + else + { + url = key + '.json'; + } + } + + // A map data object has been given + if (data) + { + switch (format) + { + // A csv string or object has been given + case Phaser.Tilemap.CSV: + break; + + // A json string or object has been given + case Phaser.Tilemap.TILED_JSON: + + if (typeof data === 'string') + { + data = JSON.parse(data); + } + break; + } + + this.cache.addTilemap(key, null, data, format); + } + else + { + this.addToFileList('tilemap', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds a physics data file to the current load queue. + * + * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". + * It will always use `.json` as the extension. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#physics + * @param {string} key - Unique asset key of the physics json data. + * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. + * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data. + * @return {Phaser.Loader} This Loader instance. + */ + physics: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; } + + if (!url && !data) + { + url = key + '.json'; + } + + // A map data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + this.cache.addPhysicsData(key, null, data, format); + } + else + { + this.addToFileList('physics', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds Bitmap Font files to the current load queue. + * + * To create the Bitmap Font files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `xmlData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#bitmapFont + * @param {string} key - Unique asset key of the bitmap font. + * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". + * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". + * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json). + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + * @return {Phaser.Loader} This Loader instance. + */ + bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (atlasURL === null && atlasData === null) + { + atlasURL = key + '.xml'; + } + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + // A URL to a json/xml atlas has been given + if (atlasURL) + { + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing }); + } + else + { + // A stringified xml/json atlas has been given + if (typeof atlasData === 'string') + { + var json, xml; + + try + { + json = JSON.parse(atlasData); + } + catch ( e ) + { + xml = this.parseXml(atlasData); + } + + if (!xml && !json) + { + throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given"); + } + + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml, + atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing }); + } + } + + return this; + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONArray + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONHash + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * This call expects the atlas data to be in the Starling XML data format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasXML + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasXML: function (key, textureURL, atlasURL, atlasData) { + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (!atlasURL && !atlasData) + { + atlasURL = key + '.xml'; + } + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlas + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. + * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING. + * @return {Phaser.Loader} This Loader instance. + */ + atlas: function (key, textureURL, atlasURL, atlasData, format) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } + + if (!atlasURL && !atlasData) + { + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + atlasURL = key + '.xml'; + } + else + { + atlasURL = key + '.json'; + } + } + + // A URL to a json/xml file has been given + if (atlasURL) + { + this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); + } + else + { + switch (format) + { + // A json string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: + + if (typeof atlasData === 'string') + { + atlasData = JSON.parse(atlasData); + } + break; + + // An xml string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: + + if (typeof atlasData === 'string') + { + var xml = this.parseXml(atlasData); + + if (!xml) + { + throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); + } + + atlasData = xml; + } + break; + } + + this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); + + } + + return this; + + }, + + /** + * Add a synchronization point to the assets / files added within the supplied callback. + * + * A synchronization point denotes that an asset _must_ be completely loaded before + * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait + * for previous assets to load (unless they are sync-points). Resources, such as packs, may still + * be downloaded around sync-points, as long as they do not finalize loading. + * + * @method Phaser.Loader#withSyncPoint + * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader. + * @param {object} [callbackContext=(loader)] - Context for the callback. + * @return {Phaser.Loader} This Loader instance. + */ + withSyncPoint: function (callback, callbackContext) { + + this._withSyncPointDepth++; + + try { + callback.call(callbackContext || this, this); + } finally { + this._withSyncPointDepth--; + } + + return this; + }, + + /** + * Add a synchronization point to a specific file/asset in the load queue. + * + * This has no effect on already loaded assets. + * + * @method Phaser.Loader#addSyncPoint + * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc). + * @param {string} key - Key of the file you want to turn into a sync point. + * @return {Phaser.Loader} This Loader instance. + * @see {@link Phaser.Loader#withSyncPoint withSyncPoint} + */ + addSyncPoint: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + asset.file.syncPoint = true; + } + + return this; + }, + + /** + * Remove a file/asset from the loading queue. + * + * A file that is loaded or has started loading cannot be removed. + * + * @method Phaser.Loader#removeFile + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - Key of the file you want to remove. + */ + removeFile: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + if (!asset.loaded && !asset.loading) + { + this._fileList.splice(asset.index, 1); + } + } + + }, + + /** + * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead. + * + * @method Phaser.Loader#removeAll + * @protected + */ + removeAll: function () { + + this._fileList.length = 0; + this._flightQueue.length = 0; + + }, + + /** + * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. + * + * @method Phaser.Loader#start + */ + start: function () { + + if (this.isLoading) + { + return; + } + + this.hasLoaded = false; + this.isLoading = true; + + this.updateProgress(); + + this.processLoadQueue(); + + }, + + /** + * Process the next item(s) in the file/asset queue. + * + * Process the queue and start loading enough items to fill up the inflight queue. + * + * If a sync-file is encountered then subsequent asset processing is delayed until it completes. + * The exception to this rule is that packfiles can be downloaded (but not processed) even if + * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel. + * such as during the start phaser. + * + * @method Phaser.Loader#processLoadQueue + * @private + */ + processLoadQueue: function () { + + if (!this.isLoading) + { + console.warn('Phaser.Loader - active loading canceled / reset'); + this.finishedLoading(true); + return; + } + + // Empty the flight queue as applicable + for (var i = 0; i < this._flightQueue.length; i++) + { + var file = this._flightQueue[i]; + + if (file.loaded || file.error) + { + this._flightQueue.splice(i, 1); + i--; + + file.loading = false; + file.requestUrl = null; + file.requestObject = null; + + if (file.error) + { + this.onFileError.dispatch(file.key, file); + } + + if (file.type !== 'packfile') + { + this._loadedFileCount++; + this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount); + } + else if (file.type === 'packfile' && file.error) + { + // Non-error pack files are handled when processing the file queue + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + } + } + + // When true further non-pack file downloads are suppressed + var syncblock = false; + + var inflightLimit = this.enableParallel ? Math.max(1, this.maxParallelDownloads) : 1; + + for (var i = this._processingHead; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + // Pack is fetched (ie. has data) and is currently at the start of the process queue. + if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead) + { + // Processing the pack / adds more files + this.processPack(file); + + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + if (file.loaded || file.error) + { + // Item at the start of file list finished, can skip it in future + if (i === this._processingHead) + { + this._processingHead = i + 1; + } + } + else if (!file.loading && this._flightQueue.length < inflightLimit) + { + // -> not loaded/failed, not loading + if (file.type === 'packfile' && !file.data) + { + // Fetches the pack data: the pack is processed above as it reaches queue-start. + // (Packs do not trigger onLoadStart or onFileStart.) + this._flightQueue.push(file); + file.loading = true; + + this.loadFile(file); + } + else if (!syncblock) + { + if (!this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this._flightQueue.push(file); + file.loading = true; + this.onFileStart.dispatch(this.progress, file.key, file.url); + + this.loadFile(file); + } + } + + if (!file.loaded && file.syncPoint) + { + syncblock = true; + } + + // Stop looking if queue full - or if syncblocked and there are no more packs. + // (As only packs can be loaded around a syncblock) + if (this._flightQueue.length >= inflightLimit || + (syncblock && this._loadedPackCount === this._totalPackCount)) + { + break; + } + } + + this.updateProgress(); + + // True when all items in the queue have been advanced over + // (There should be no inflight items as they are complete - loaded/error.) + if (this._processingHead >= this._fileList.length) + { + this.finishedLoading(); + } + else if (!this._flightQueue.length) + { + // Flight queue is empty but file list is not done being processed. + // This indicates a critical internal error with no known recovery. + console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled"); + + var _this = this; + + setTimeout(function () { + _this.finishedLoading(true); + }, 2000); + } + + }, + + /** + * The loading is all finished. + * + * @method Phaser.Loader#finishedLoading + * @private + * @param {boolean} [abnormal=true] - True if the loading finished abnormally. + */ + finishedLoading: function (abnormal) { + + if (this.hasLoaded) + { + return; + } + + this.hasLoaded = true; + this.isLoading = false; + + // If there were no files make sure to trigger the event anyway, for consistency + if (!abnormal && !this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this.reset(); + + this.onLoadComplete.dispatch(); + + // Check if the state still exists since destroy could have occurred while loading + if (this.game.state) + { + this.game.state.loadComplete(); + } + + }, + + /** + * Informs the loader that the given file resource has been fetched and processed; + * or such a request has failed. + * + * @method Phaser.Loader#asyncComplete + * @private + * @param {object} file + * @param {string} [error=''] - The error message, if any. No message implies no error. + */ + asyncComplete: function (file, errorMessage) { + + if (errorMessage === undefined) { errorMessage = ''; } + + file.loaded = true; + file.error = !!errorMessage; + + if (errorMessage) + { + file.errorMessage = errorMessage; + + console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage); + } + + this.processLoadQueue(); + + }, + + /** + * Process pack data. This will usually modify the file list. + * + * @method Phaser.Loader#processPack + * @private + * @param {object} pack + */ + processPack: function (pack) { + + var packData = pack.data[pack.key]; + + if (!packData) + { + console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key'); + return; + } + + for (var i = 0; i < packData.length; i++) + { + var file = packData[i]; + + switch (file.type) + { + case "image": + this.image(file.key, file.url, file.overwrite); + break; + + case "text": + this.text(file.key, file.url, file.overwrite); + break; + + case "json": + this.json(file.key, file.url, file.overwrite); + break; + + case "xml": + this.xml(file.key, file.url, file.overwrite); + break; + + case "script": + this.script(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "binary": + this.binary(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "spritesheet": + this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case "video": + this.video(file.key, file.urls); + break; + + case "audio": + this.audio(file.key, file.urls, file.autoDecode); + break; + + case "audiosprite": + this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode); + break; + + case "tilemap": + this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]); + break; + + case "physics": + this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]); + break; + + case "bitmapFont": + this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing); + break; + + case "atlasJSONArray": + this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasJSONHash": + this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasXML": + this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlas": + this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]); + break; + + case "shader": + this.shader(file.key, file.url, file.overwrite); + break; + } + } + + }, + + /** + * Transforms the asset URL. + * + * The default implementation prepends the baseURL if the url doesn't begin with http or // + * + * @method Phaser.Loader#transformUrl + * @protected + * @param {string} url - The url to transform. + * @param {object} file - The file object being transformed. + * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead. + */ + transformUrl: function (url, file) { + + if (!url) + { + return false; + } + + if (url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) + { + return url; + } + else + { + return this.baseURL + file.path + url; + } + + }, + + /** + * Start fetching a resource. + * + * All code paths, async or otherwise, from this function must return to `asyncComplete`. + * + * @method Phaser.Loader#loadFile + * @private + * @param {object} file + */ + loadFile: function (file) { + + // Image or Data? + switch (file.type) + { + case 'packfile': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'image': + case 'spritesheet': + case 'textureatlas': + case 'bitmapfont': + this.loadImageTag(file); + break; + + case 'audio': + file.url = this.getAudioURL(file.url); + + if (file.url) + { + // WebAudio or Audio Tag? + if (this.game.sound.usingWebAudio) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + else if (this.game.sound.usingAudioTag) + { + this.loadAudioTag(file); + } + } + else + { + this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support'); + } + break; + + case 'video': + file.url = this.getVideoURL(file.url); + + if (file.url) + { + if (file.asBlob) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'blob', this.fileComplete); + } + else + { + this.loadVideoTag(file); + } + } + else + { + this.fileError(file, null, 'No supported video URL specified or device does not have video playback support'); + } + break; + + case 'json': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + break; + + case 'xml': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete); + break; + + case 'tilemap': + + if (file.format === Phaser.Tilemap.TILED_JSON) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Tilemap.CSV) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete); + } + else + { + this.asyncComplete(file, "invalid Tilemap format: " + file.format); + } + break; + + case 'text': + case 'script': + case 'shader': + case 'physics': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'texture': + + if (file.key.split('_').pop() === 'truecolor') + { + this.loadImageTag(file); + } + else + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + break; + + case 'binary': + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + break; + } + + }, + + /** + * Continue async loading through an Image tag. + * @private + */ + loadImageTag: function (file) { + var _this = this; + + file.data = new Image(); + file.data.name = file.key; + + if (this.crossOrigin) + { + file.data.crossOrigin = this.crossOrigin; + } + + file.data.onload = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileComplete(file); + } + }; + + file.data.onerror = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileError(file); + } + }; + + file.data.src = this.transformUrl(file.url, file); + + // Image is immediately-available/cached + // Special Firefox magic, exclude from cached reload + // More info here: https://github.com/photonstorm/phaser/issues/2534 + if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height) + { + file.data.onload = null; + file.data.onerror = null; + this.fileComplete(file); + } + + }, + + /** + * Continue async loading through a Video tag. + * @private + */ + loadVideoTag: function (file) { + + var _this = this; + + file.data = document.createElement("video"); + file.data.name = file.key; + file.data.controls = false; + file.data.autoplay = false; + + var videoLoadEvent = function () { + + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = true; + Phaser.GAMES[_this.game.id].load.fileComplete(file); + + }; + + file.data.onerror = function () { + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = false; + _this.fileError(file); + }; + + file.data.addEventListener(file.loadEvent, videoLoadEvent, false); + + file.data.src = this.transformUrl(file.url, file); + file.data.load(); + + }, + + /** + * Continue async loading through an Audio tag. + * @private + */ + loadAudioTag: function (file) { + + var _this = this; + + if (this.game.sound.touchLocked) + { + // If audio is locked we can't do this yet, so need to queue this load request. Bum. + file.data = new Audio(); + file.data.name = file.key; + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + + this.fileComplete(file); + } + else + { + file.data = new Audio(); + file.data.name = file.key; + + var playThroughEvent = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileComplete(file); + }; + + file.data.onerror = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileError(file); + }; + + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + file.data.addEventListener('canplaythrough', playThroughEvent, false); + file.data.load(); + } + + }, + + /** + * Starts the xhr loader. + * + * This is designed specifically to use with asset file processing. + * + * @method Phaser.Loader#xhrLoad + * @private + * @param {object} file - The file/pack to load. + * @param {string} url - The URL of the file. + * @param {string} type - The xhr responseType. + * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments. + * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments. + */ + xhrLoad: function (file, url, type, onload, onerror) { + + var xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = type; + + if (this.headers['requestedWith'] !== false) + { + xhr.setRequestHeader('X-Requested-With', this.headers['requestedWith']); + } + + if (this.headers[file.type]) + { + xhr.setRequestHeader('Accept', this.headers[file.type]); + } + + onerror = onerror || this.fileError; + + var _this = this; + + xhr.onload = function () { + + try { + if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. + return onerror.call(_this, file, xhr); + } + else { + return onload.call(_this, file, xhr); + } + } catch (e) { + + // If this was the last file in the queue and an error is thrown in the create method + // then it's caught here, so be sure we don't carry on processing it + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + } + }; + + xhr.onerror = function () { + + try { + + return onerror.call(_this, file, xhr); + + } catch (e) { + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + + } + }; + + file.requestObject = xhr; + file.requestUrl = url; + + xhr.send(); + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getVideoURL + * @private + * @param {object[]|string[]} urls - See {@link #video} for format. + * @return {string} The URL to try and fetch; or null. + */ + getVideoURL: function (urls) { + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var videoType; + + if (url.uri) // {uri: .., type: ..} pair + { + videoType = url.type; + url = url.uri; + + if (this.game.device.canPlayVideo(videoType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + videoType = extension.toLowerCase(); + + if (this.game.device.canPlayVideo(videoType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getAudioURL + * @private + * @param {object[]|string[]} urls - See {@link #audio} for format. + * @return {string} The URL to try and fetch; or null. + */ + getAudioURL: function (urls) { + + if (this.game.sound.noAudio) + { + return null; + } + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var audioType; + + if (url.uri) // {uri: .., type: ..} pair + { + audioType = url.type; + url = url.uri; + + if (this.game.device.canPlayAudio(audioType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + audioType = extension.toLowerCase(); + + if (this.game.device.canPlayAudio(audioType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Error occurred when loading a file. + * + * @method Phaser.Loader#fileError + * @private + * @param {object} file + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + * @param {string} reason + */ + fileError: function (file, xhr, reason) { + + var url = file.requestUrl || this.transformUrl(file.url, file); + var message = 'error loading asset from URL ' + url; + + if (!reason && xhr) + { + reason = xhr.status; + } + + if (reason) + { + message = message + ' (' + reason + ')'; + } + + this.asyncComplete(file, message); + + }, + + /** + * Called when a file has been downloaded and needs to be processed further. + * + * @method Phaser.Loader#fileComplete + * @private + * @param {object} file - File loaded + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + */ + fileComplete: function (file, xhr) { + + var loadNext = true; + + switch (file.type) + { + case 'packfile': + + // Pack data must never be false-ish after it is fetched without error + var data = JSON.parse(xhr.responseText); + file.data = data || {}; + break; + + case 'texture': + + var extension = /\.([^.]+)$/.exec(file.url.split('?', 1)[0])[1].toLowerCase(); + if (file.data !== null) + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, file.data); + } + else + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, xhr.response); + } + break; + + case 'image': + + this.cache.addImage(file.key, file.url, file.data); + break; + + case 'spritesheet': + + this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case 'textureatlas': + + if (file.atlasURL == null) + { + this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); + } + else + { + // Load the JSON or XML before carrying on with the next file + loadNext = false; + + if (file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_HASH || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete); + } + else + { + throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); + } + } + break; + + case 'bitmapfont': + + if (!file.atlasURL) + { + this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing); + } + else + { + // Load the XML before carrying on with the next file + loadNext = false; + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) { + var json; + + try + { + // Try to parse as JSON, if it fails, then it's hopefully XML + json = JSON.parse(xhr.responseText); + } + catch (e) {} + + if (!!json) + { + file.atlasType = 'json'; + this.jsonLoadComplete(file, xhr); + } + else + { + file.atlasType = 'xml'; + this.xmlLoadComplete(file, xhr); + } + }); + } + break; + + case 'video': + + if (file.asBlob) + { + try + { + file.data = xhr.response; + } + catch (e) + { + throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key); + } + } + + this.cache.addVideo(file.key, file.url, file.data, file.asBlob); + break; + + case 'audio': + + if (this.game.sound.usingWebAudio) + { + file.data = xhr.response; + + this.cache.addSound(file.key, file.url, file.data, true, false); + + if (file.autoDecode) + { + this.game.sound.decode(file.key); + } + } + else + { + this.cache.addSound(file.key, file.url, file.data, false, true); + } + break; + + case 'text': + file.data = xhr.responseText; + this.cache.addText(file.key, file.url, file.data); + break; + + case 'shader': + file.data = xhr.responseText; + this.cache.addShader(file.key, file.url, file.data); + break; + + case 'physics': + var data = JSON.parse(xhr.responseText); + this.cache.addPhysicsData(file.key, file.url, data, file.format); + break; + + case 'script': + file.data = document.createElement('script'); + file.data.language = 'javascript'; + file.data.type = 'text/javascript'; + file.data.defer = false; + file.data.text = xhr.responseText; + document.head.appendChild(file.data); + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText); + } + break; + + case 'binary': + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.response); + } + else + { + file.data = xhr.response; + } + + this.cache.addBinary(file.key, file.data); + + break; + } + + if (loadNext) + { + this.asyncComplete(file); + } + + }, + + /** + * Successfully loaded a JSON file - only used for certain types. + * + * @method Phaser.Loader#jsonLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + jsonLoadComplete: function (file, xhr) { + + var data = JSON.parse(xhr.responseText); + + if (file.type === 'tilemap') + { + this.cache.addTilemap(file.key, file.url, data, file.format); + } + else if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'json') + { + this.cache.addJSON(file.key, file.url, data); + } + else + { + this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); + } + + this.asyncComplete(file); + }, + + /** + * Successfully loaded a CSV file - only used for certain types. + * + * @method Phaser.Loader#csvLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + csvLoadComplete: function (file, xhr) { + + var data = xhr.responseText; + + this.cache.addTilemap(file.key, file.url, data, file.format); + + this.asyncComplete(file); + + }, + + /** + * Successfully loaded an XML file - only used for certain types. + * + * @method Phaser.Loader#xmlLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + xmlLoadComplete: function (file, xhr) { + + // Always try parsing the content as XML, regardless of actually response type + var data = xhr.responseText; + var xml = this.parseXml(data); + + if (!xml) + { + var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest + console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')'); + this.asyncComplete(file, "invalid XML"); + return; + } + + if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'textureatlas') + { + this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); + } + else if (file.type === 'xml') + { + this.cache.addXML(file.key, file.url, xml); + } + + this.asyncComplete(file); + + }, + + /** + * Parses string data as XML. + * + * @method Phaser.Loader#parseXml + * @private + * @param {string} data - The XML text to parse + * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document. + */ + parseXml: function (data) { + + var xml; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + // Why is this 'false'? + xml.async = 'false'; + xml.loadXML(data); + } + } + catch (e) + { + xml = null; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + return null; + } + else + { + return xml; + } + + }, + + /** + * Update the loading sprite progress. + * + * @method Phaser.Loader#updateProgress + * @private + */ + updateProgress: function () { + + if (this.preloadSprite) + { + if (this.preloadSprite.direction === 0) + { + this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress); + } + else + { + this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress); + } + + if (this.preloadSprite.sprite) + { + this.preloadSprite.sprite.updateCrop(); + } + else + { + // We seem to have lost our sprite - maybe it was destroyed? + this.preloadSprite = null; + } + } + + }, + + /** + * Returns the number of files that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedFiles + * @protected + * @return {number} The number of files that have already been loaded (even if they errored) + */ + totalLoadedFiles: function () { + + return this._loadedFileCount; + + }, + + /** + * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedFiles + * @protected + * @return {number} The number of files that still remain in the load queue. + */ + totalQueuedFiles: function () { + + return this._totalFileCount - this._loadedFileCount; + + }, + + /** + * Returns the number of asset packs that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedPacks + * @protected + * @return {number} The number of asset packs that have already been loaded (even if they errored) + */ + totalLoadedPacks: function () { + + return this._totalPackCount; + + }, + + /** + * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedPacks + * @protected + * @return {number} The number of asset packs that still remain in the load queue. + */ + totalQueuedPacks: function () { + + return this._totalPackCount - this._loadedPackCount; + + } + +}; + +/** +* The non-rounded load progress value (from 0.0 to 100.0). +* +* A general indicator of the progress. +* It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. +* +* @name Phaser.Loader#progressFloat +* @property {number} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progressFloat", { + + get: function () { + var progress = (this._loadedFileCount / this._totalFileCount) * 100; + return Phaser.Math.clamp(progress || 0, 0, 100); + } + +}); + +/** +* The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}. +* +* @name Phaser.Loader#progress +* @property {integer} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progress", { + + get: function () { + return Math.round(this.progressFloat); + } + +}); + +Phaser.Loader.prototype.constructor = Phaser.Loader; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. +* +* @class Phaser.LoaderParser +*/ +Phaser.LoaderParser = { + + /** + * Alias for xmlBitmapFont, for backwards compatibility. + * + * @method Phaser.LoaderParser.bitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + bitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing, frame, resolution); + + }, + + /** + * Parse a Bitmap Font from an XML file. + * + * @method Phaser.LoaderParser.xmlBitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing; + data.chars = {}; + + var letters = xml.getElementsByTagName('char'); + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + for (var i = 0; i < letters.length; i++) + { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + data.chars[charCode] = { + x: x + parseInt(letters[i].getAttribute('x'), 10), + y: y + parseInt(letters[i].getAttribute('y'), 10), + width: parseInt(letters[i].getAttribute('width'), 10), + height: parseInt(letters[i].getAttribute('height'), 10), + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10) / resolution, + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10) / resolution, + xAdvance: (parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing) / resolution, + kerning: {} + }; + } + + var kernings = xml.getElementsByTagName('kerning'); + + for (i = 0; i < kernings.length; i++) + { + var first = parseInt(kernings[i].getAttribute('first'), 10); + var second = parseInt(kernings[i].getAttribute('second'), 10); + var amount = parseInt(kernings[i].getAttribute('amount'), 10) / resolution; + + data.chars[second].kerning[first] = amount; + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Parse a Bitmap Font from a JSON file. + * + * @method Phaser.LoaderParser.jsonBitmapFont + * @param {object} json - JSON data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = { + font: json.font.info._face, + size: parseInt(json.font.info._size, 10), + lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing, + chars: {} + }; + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + json.font.chars["char"].forEach( + + function parseChar(letter) { + + var charCode = parseInt(letter._id, 10); + + data.chars[charCode] = { + x: x + parseInt(letter._x, 10), + y: y + parseInt(letter._y, 10), + width: parseInt(letter._width, 10), + height: parseInt(letter._height, 10), + xOffset: parseInt(letter._xoffset, 10) / resolution, + yOffset: parseInt(letter._yoffset, 10) / resolution, + xAdvance: (parseInt(letter._xadvance, 10) + xSpacing) / resolution, + kerning: {} + }; + } + + ); + + if (json.font.kernings && json.font.kernings.kerning) + { + json.font.kernings.kerning.forEach( + + function parseKerning(kerning) { + + data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10) / resolution; + + } + + ); + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Finalize Bitmap Font parsing. + * + * @method Phaser.LoaderParser.finalizeBitmapFont + * @private + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {object} bitmapFontData - Pre-parsed bitmap font data. + * @return {object} The parsed Bitmap Font data. + */ + finalizeBitmapFont: function (baseTexture, bitmapFontData) { + + Object.keys(bitmapFontData.chars).forEach( + + function addTexture(charCode) { + + var letter = bitmapFontData.chars[charCode]; + + letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height)); + + } + + ); + + return bitmapFontData; + + }, + + /** + * Extract PVR header from loaded binary + * + * @method Phaser.LoaderParser.pvr + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PVR file including texture data. + */ + pvr: function (arrayBuffer) { + + // Reference: http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf + // PVR 3 header structure + // --------------------------------------- + // address: 0, size: 4 bytes version + // address: 4, size: 4 bytes flags + // address: 8, size: 8 bytes pixel format + // address: 16, size: 4 bytes color space + // address: 20, size: 4 bytes channel type + // address: 24, size: 4 bytes height + // address: 28, size: 4 bytes width + // address: 32, size: 4 bytes depth + // address: 36, size: 4 bytes number of surfaces + // address: 40, size: 4 bytes number of faces + // address: 44, size: 4 bytes number of mipmaps + // address: 48, size: 4 bytes meta data size + // --------------------------------------- + var uintArray = new Uint32Array(arrayBuffer.slice(0, 52)), + byteArray = new Uint8Array(arrayBuffer), + pvrHeader = null, + pixelFormat = (uintArray[3] << 32 | uintArray[2]), + compressionAlgorithm, + glExtensionFormat = 0; + + if (uintArray[0] === 0x03525650 && + [ // Validate WebGL Pixel Format + 0, 1, 2, 3, + 6, 7, 9, 11 + ].indexOf(pixelFormat) >= 0 + ) { + if (pixelFormat >= 0 && pixelFormat <= 3) { + compressionAlgorithm = 'PVRTC'; + } else if (pixelFormat >= 7 && pixelFormat <= 11) { + compressionAlgorithm = 'S3TC'; + } else if (pixelFormat === 6) { + compressionAlgorithm = 'ETC1'; + } + + switch (pixelFormat) { + case 0: + glExtensionFormat = 0x8C01; + break; + case 1: + glExtensionFormat = 0x8C03; + break; + case 2: + glExtensionFormat = 0x8C00; + break; + case 3: + glExtensionFormat = 0x8C02; + break; + case 6: + glExtensionFormat = 0x8D64; + break; + case 7: + glExtensionFormat = 0x83F1; + break; + case 9: + glExtensionFormat = 0x83F2; + break; + case 11: + glExtensionFormat = 0x83F3; + break; + default: + glExtensionFormat = -1; + } + + pvrHeader = { + complete: true, + fileFormat: 'PVR', + compressionAlgorithm: compressionAlgorithm, + flags: uintArray[1], + pixelFormat: pixelFormat, + colorSpace: uintArray[4], + channelType: uintArray[5], + height: uintArray[6], + width: uintArray[7], + depth: uintArray[8], + numberOfSurfaces: uintArray[9], + numberOfFaces: uintArray[10], + numberOfMipmaps: uintArray[11], + metaDataSize: uintArray[12], + textureData: byteArray.subarray(52 + uintArray[12], byteArray.byteLength), + glExtensionFormat: glExtensionFormat + }; + } + + return pvrHeader; + + }, + + /** + * Extract DDS header from loaded binary + * + * @method Phaser.LoaderParser.dds + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed DDS file including texture data. + */ + dds: function (arrayBuffer) { + + // Reference at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx + // DDS header structure + // --------------------------------------- + // address: 0, size: 4 bytes Identifier 'DDS ' + // address: 4, size: 4 bytes size + // address: 8, size: 4 bytes flags + // address: 12, size: 4 bytes height + // address: 16, size: 4 bytes width + // address: 20, size: 4 bytes pitch or linear size + // address: 24, size: 4 bytes depth + // address: 28, size: 4 bytes mipmap count + // address: 32, size: 44 bytes reserved space 1 + // address: 76, size: 4 pixel format size + // address: 80, size: 4 pixel format flag + // address: 84, size: 4 pixel format four CC + // address: 88, size: 4 pixel format bit count + // address: 92, size: 4 pixel format R bit mask + // address: 96, size: 4 pixel format G bit mask + // address: 100, size: 4 pixel format B bit mask + // address: 104, size: 4 pixel format A bit mask + // address: 108, size: 4 caps 1 + // address: 112, size: 4 caps 2 + // address: 116, size: 4 caps 3 + // address: 120, size: 4 caps 4 + // address: 124, size: 4 reserved 2 + // -- DXT10 extension + // address: 130, size: 4 DXGI Format + // address: 134, size: 4 resource dimension + // address: 138, size: 4 misc flag + // address: 142, size: 4 array size + // address: 146, size: 4 misc flag 2 + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ddsHeader = null; + + if (byteArray[0] === 0x44 && + byteArray[1] === 0x44 && + byteArray[2] === 0x53 && + byteArray[3] === 0x20) { + ddsHeader = { + complete: true, + fileFormat: 'DDS', + compressionAlgorithm: 'S3TC', + size: uintArray[1], + flags: uintArray[2], + height: uintArray[3], + width: uintArray[4], + pitch: uintArray[5], + depth: uintArray[6], + mipmapCount: uintArray[7], + formatSize: uintArray[19], + formatFlag: uintArray[19], + formatFourCC: [ + String.fromCharCode(byteArray[84]), + String.fromCharCode(byteArray[85]), + String.fromCharCode(byteArray[86]), + String.fromCharCode(byteArray[87]) + ].join(''), + formatBitCount: uintArray[21], + formatRBitMask: uintArray[22], + formatGBitMask: uintArray[23], + formatBBitMask: uintArray[24], + formatABitMask: uintArray[25], + caps1: uintArray[26], + caps2: uintArray[27], + caps3: uintArray[28], + caps4: uintArray[29], + reserved2: uintArray[30], + DXGIFormat: null, + resourceDimension: null, + miscFlag: null, + arraySize: null, + textureData: byteArray.subarray(uintArray[1] + 4, byteArray.byteLength) + }; + if (ddsHeader.formatFourCC === 'DX10') { + ddsHeader.DXGIFormat = uintArray[31]; + ddsHeader.resourceDimension = uintArray[32]; + ddsHeader.miscFlag = uintArray[33]; + ddsHeader.arraySize = uintArray[34]; + ddsHeader.miscFlag = uintArray[35]; + } + } + + return ddsHeader; + + }, + + /** + * Extract KTX header from loaded binary + * + * @method Phaser.LoaderParser.ktx + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed KTX file including texture data. + */ + ktx: function (arrayBuffer) { + + // Reference: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + // KTX header structure + // --------------------------------------- + // address: 0, size 12 bytes: Identifier '«KTX 11»\r\n\x1A\n' + // address: 12, size 4 bytes: endianness + // address: 16, size 4 bytes: GL type + // address: 20, size 4 bytes: GL type size + // address: 24, size 4 bytes: GL format + // address: 28, size 4 bytes: GL internal format + // address: 32, size 4 bytes: GL base internal format + // address: 36, size 4 bytes: pixel width + // address: 40, size 4 bytes: pixel height + // address: 44, size 4 bytes: pixel depth + // address: 48, size 4 bytes: number of array elements + // address: 52, size 4 bytes: number of faces + // address: 56, size 4 bytes: number of mipmap levels + // address: 60, size 4 bytes: bytes of key value data + // address: 64, size 4 bytes: key and value bytes size + // address: X, size 1 byte : key and value + // address: X, size 1 byte : value padding + // address: X, size 4 byte : image size + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ktxHeader = null, + imageSizeOffset = 16 + (uintArray[15] / 4) | 0, + imageSize = uintArray[imageSizeOffset], + glInternalFormat = uintArray[7], + compressionAlgorithm = 0; + + if (byteArray[0] === 0xAB && byteArray[1] === 0x4B && + byteArray[2] === 0x54 && byteArray[3] === 0x58 && + byteArray[4] === 0x20 && byteArray[5] === 0x31 && + byteArray[6] === 0x31 && byteArray[7] === 0xBB && + byteArray[8] === 0x0D && byteArray[9] === 0x0A && + byteArray[10] === 0x1A && byteArray[11] === 0x0A && + //Check if internal GL format is supported by WebGL + [ + // ETC1 + 0x8D64, + // PVRTC + 0x8C00, 0x8C01, 0x8C02, 0x8C03, + // DXTC | S3TC + 0x83F0, 0x83F1, 0x83F2, 0x83F3 + ].indexOf(glInternalFormat) >= 0) { + switch (glInternalFormat) { + case 0x8D64: + compressionAlgorithm = 'ETC1'; + break; + case 0x8C00: + case 0x8C01: + case 0x8C02: + case 0x8C03: + compressionAlgorithm = 'PVRTC'; + break; + case 0x83F0: + case 0x83F1: + case 0x83F2: + case 0x83F3: + compressionAlgorithm = 'S3TC'; + break; + } + + ktxHeader = { + complete: true, + fileFormat: 'KTX', + compressionAlgorithm: compressionAlgorithm, + endianness: uintArray[3], + glType: uintArray[4], + glTypeSize: uintArray[5], + glFormat: uintArray[6], + glInternalFormat: uintArray[7], + glBaseInternalFormat: uintArray[8], + width: uintArray[9], + height: uintArray[10], + pixelDepth: uintArray[11], + numberOfArrayElements: uintArray[12], + numberOfFaces: uintArray[13], + numberOfMipmapLevels: uintArray[14], + bytesOfKeyValueData: uintArray[15], + keyAndValueByteSize: uintArray[16], + imageSize: imageSize, + textureData: byteArray.subarray((imageSizeOffset + 1) * 4, imageSize + 100) + }; + } + + return ktxHeader; + + }, + + /** + * Extract PKM header from loaded binary + * + * @method Phaser.LoaderParser.pkm + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PKM file including texture data. + */ + pkm: function (arrayBuffer) { + + // PKM header structure + // --------------------------------------- + // address: 0, size 4 bytes: for 'PKM ' + // address: 4, size 2 bytes: for version + // address: 6, size 2 bytes: for type + // address: 8, size 2 bytes: for extended width + // address: 10, size 2 bytes: for extended height + // address: 12, size 2 bytes: for original width + // address: 14, size 2 bytes: for original height + // address: 16, texture data + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + pkmHeader = null; + + if (byteArray[0] === 0x50 && + byteArray[1] === 0x4B && + byteArray[2] === 0x4D && + byteArray[3] === 0x20) { + + pkmHeader = { + complete: true, + fileFormat: 'PKM', + compressionAlgorithm: 'ETC1', + format: ((byteArray[6] << 8 | byteArray[7])) & 0xFFFF, + width: ((byteArray[8] << 8 | byteArray[9])) & 0xFFFF, + height: ((byteArray[10] << 8 | byteArray[11])) & 0xFFFF, + originalWidth: ((byteArray[12] << 8 | byteArray[13])) & 0xFFFF, + originalHeight: ((byteArray[14] << 8 | byteArray[15])) & 0xFFFF, + textureData: byteArray.subarray(16, byteArray.length) + }; + } + + return pkmHeader; + + } + +}; + +/** + * @author Jeremy Dowell + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * Audio Sprites are a combination of audio files and a JSON configuration. + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * @class Phaser.AudioSprite + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + * @param {string} key - Asset key for the sound. + */ +Phaser.AudioSprite = function (game, key) { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * Asset key for the Audio Sprite. + * @property {string} key + */ + this.key = key; + + /** + * JSON audio atlas object. + * @property {object} config + */ + this.config = this.game.cache.getJSON(key + '-audioatlas'); + + /** + * If a sound is set to auto play, this holds the marker key of it. + * @property {string} autoplayKey + */ + this.autoplayKey = null; + + /** + * Is a sound set to autoplay or not? + * @property {boolean} autoplay + * @default + */ + this.autoplay = false; + + /** + * An object containing the Phaser.Sound objects for the Audio Sprite. + * @property {object} sounds + */ + this.sounds = {}; + + for (var k in this.config.spritemap) + { + var marker = this.config.spritemap[k]; + var sound = this.game.add.sound(this.key); + + sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop); + + this.sounds[k] = sound; + } + + if (this.config.autoplay) + { + this.autoplayKey = this.config.autoplay; + this.play(this.autoplayKey); + this.autoplay = this.sounds[this.autoplayKey]; + } + +}; + +Phaser.AudioSprite.prototype = { + + /** + * Play a sound with the given name. + * + * @method Phaser.AudioSprite#play + * @param {string} [marker] - The name of sound to play + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, volume) { + + if (volume === undefined) { volume = 1; } + + return this.sounds[marker].play(marker, null, volume); + + }, + + /** + * Stop a sound with the given name. + * + * @method Phaser.AudioSprite#stop + * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite. + */ + stop: function (marker) { + + if (!marker) + { + for (var key in this.sounds) + { + this.sounds[key].stop(); + } + } + else + { + this.sounds[marker].stop(); + } + + }, + + /** + * Get a sound with the given name. + * + * @method Phaser.AudioSprite#get + * @param {string} marker - The name of sound to get. + * @return {Phaser.Sound} The sound instance. + */ + get: function(marker) { + + return this.sounds[marker]; + + } + +}; + +Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound class constructor. +* +* @class Phaser.Sound +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {string} key - Asset key for the sound. +* @param {number} [volume=1] - Default value for the volume, between 0 and 1. +* @param {boolean} [loop=false] - Whether or not the sound will loop. +*/ +Phaser.Sound = function (game, key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = game.sound.connectToMaster; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * @property {string} name - Name of the sound. + */ + this.name = key; + + /** + * @property {string} key - Asset key for the sound. + */ + this.key = key; + + /** + * @property {boolean} loop - Whether or not the sound or current sound marker will loop. + */ + this.loop = loop; + + /** + * @property {object} markers - The sound markers. + */ + this.markers = {}; + + /** + * @property {AudioContext} context - Reference to the AudioContext instance. + */ + this.context = null; + + /** + * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically. + */ + this.autoplay = false; + + /** + * @property {number} totalDuration - The total duration of the sound in seconds. + */ + this.totalDuration = 0; + + /** + * @property {number} startTime - The time the sound starts at in ms (typically 0 unless starting from a marker). + * @default + */ + this.startTime = 0; + + /** + * @property {number} currentTime - The current time of sound playback in ms. + */ + this.currentTime = 0; + + /** + * @property {number} duration - The duration of the current sound marker in seconds. + */ + this.duration = 0; + + /** + * @property {number} durationMS - The duration of the current sound marker in ms. + */ + this.durationMS = 0; + + /** + * @property {number} position - The position of the current sound marker in ms. + */ + this.position = 0; + + /** + * @property {number} stopTime - The time the sound stopped in ms. + */ + this.stopTime = 0; + + /** + * @property {boolean} paused - true if the sound is paused, otherwise false. + * @default + */ + this.paused = false; + + /** + * @property {number} pausedPosition - The position the sound had reached when it was paused in ms. + */ + this.pausedPosition = 0; + + /** + * @property {number} pausedTime - The game time (ms) at which the sound was paused. + */ + this.pausedTime = 0; + + /** + * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false. + * @default + */ + this.isPlaying = false; + + /** + * @property {string} currentMarker - The string ID of the currently playing marker, if any. + * @default + */ + this.currentMarker = ''; + + /** + * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. + */ + this.fadeTween = null; + + /** + * @property {boolean} pendingPlayback - true if the sound file is pending playback + * @readonly + */ + this.pendingPlayback = false; + + /** + * @property {boolean} override - if true when you play this sound it will always start from the beginning. + * @default + */ + this.override = false; + + /** + * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. + * @default + */ + this.allowMultiple = false; + + /** + * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio. + * @readonly + */ + this.usingWebAudio = this.game.sound.usingWebAudio; + + /** + * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag. + */ + this.usingAudioTag = this.game.sound.usingAudioTag; + + /** + * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. + */ + this.externalNode = null; + + /** + * @property {object} masterGainNode - The master gain node in a Web Audio system. + */ + this.masterGainNode = null; + + /** + * @property {object} gainNode - The gain node in a Web Audio system. + */ + this.gainNode = null; + + /** + * @property {object} _sound - Internal var. + * @private + */ + this._sound = null; + + /** + * @property {object} _globalVolume - Internal var for keeping track of global volume when using AudioTag + * @private + */ + this._globalVolume = 1; + + /** + * @property {boolean} _markedToDelete - When audio stops, disconnect Web Audio nodes. + * @private + */ + this._markedToDelete = false; + + /** + * @property {boolean} _removeFromSoundManager - When audio stops, remove it from the Sound Manager and destroy it. + * @private + */ + this._removeFromSoundManager = false; + + + + if (this.usingWebAudio) + { + this.context = this.game.sound.context; + this.masterGainNode = this.game.sound.masterGain; + + if (this.context.createGain === undefined) + { + this.gainNode = this.context.createGainNode(); + } + else + { + this.gainNode = this.context.createGain(); + } + + this.gainNode.gain.value = volume; + + if (connect) + { + this.gainNode.connect(this.masterGainNode); + } + } + else if (this.usingAudioTag) + { + if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key)) + { + this._sound = this.game.cache.getSoundData(key); + this.totalDuration = 0; + + if (this._sound.duration) + { + this.totalDuration = this._sound.duration; + } + } + else + { + this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this); + } + } + + /** + * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files). It passes one argument, this sound. + */ + this.onDecoded = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played or a looping marker is restarted. It passes one argument, this sound. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. It passes one argument, this sound. + */ + this.onPause = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. It passes one argument, this sound. + */ + this.onResume = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. It passes one argument, this sound. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback or when a non-looping marker completes. It passes two arguments: this sound and any {@link #currentMarker marker} that was playing. + */ + this.onStop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted. It passes one argument, this sound. + */ + this.onMute = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. It passes two arguments: the {@link #currentMarker} and this sound. + */ + this.onMarkerComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out. It passes two arguments: this sound and its current {@link #volume}. + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + */ + this._volume = volume; + + /** + * @property {any} _buffer - Decoded data buffer / Audio tag. + * @private + */ + this._buffer = null; + + /** + * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. + * @private + */ + this._muted = false; + + /** + * @property {number} _tempMarker - Internal marker var. + * @private + */ + this._tempMarker = 0; + + /** + * @property {number} _tempPosition - Internal marker var. + * @private + */ + this._tempPosition = 0; + + /** + * @property {number} _tempVolume - Internal marker var. + * @private + */ + this._tempVolume = 0; + + /** + * @property {number} _tempPause - Internal marker var. + * @private + */ + this._tempPause = 0; + + /** + * @property {number} _muteVolume - Internal cache var. + * @private + */ + this._muteVolume = 0; + + /** + * @property {boolean} _tempLoop - Internal cache var. + * @private + */ + this._tempLoop = 0; + + /** + * @property {boolean} _paused - Was this sound paused via code or a game event? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched? + * @private + */ + this._onDecodedEventDispatched = false; + +}; + +Phaser.Sound.prototype = { + + /** + * Called automatically when this sound is unlocked. + * @method Phaser.Sound#soundHasUnlocked + * @param {string} key - The Phaser.Cache key of the sound file to check for decoding. + * @protected + */ + soundHasUnlocked: function (key) { + + if (key === this.key) + { + this._sound = this.game.cache.getSoundData(this.key); + this.totalDuration = this._sound.duration; + } + + }, + + /** + * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound#addMarker + * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. + * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). + * @param {boolean} [loop=false] - Sets if the sound will loop or not. + */ + addMarker: function (name, start, duration, volume, loop) { + + if (duration === undefined || duration === null) { duration = 1; } + if (volume === undefined || volume === null) { volume = 1; } + if (loop === undefined) { loop = false; } + + this.markers[name] = { + name: name, + start: start, + stop: start + duration, + volume: volume, + duration: duration, + durationMS: duration * 1000, + loop: loop + }; + + }, + + /** + * Removes a marker from the sound. + * @method Phaser.Sound#removeMarker + * @param {string} name - The key of the marker to remove. + */ + removeMarker: function (name) { + + delete this.markers[name]; + + }, + + /** + * Called automatically by the AudioContext when the sound stops playing. + * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. + * + * @method Phaser.Sound#onEndedHandler + * @protected + */ + onEndedHandler: function () { + + this._sound.onended = null; + this.isPlaying = false; + this.currentTime = this.durationMS; + this.stop(); + + if (this._markedToDelete) + { + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + if (this._removeFromSoundManager) + { + this.game.sound.remove(this); + } + else + { + 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(); + } + } + }, + + /** + * Called automatically by Phaser.SoundManager. + * @method Phaser.Sound#update + * @protected + */ + update: function () { + + if (!this.game.cache.checkSoundKey(this.key)) + { + this.destroy(); + return; + } + + if (this.isDecoded && !this._onDecodedEventDispatched) + { + this.onDecoded.dispatch(this); + this._onDecodedEventDispatched = true; + } + + if (this.pendingPlayback && this.game.cache.isSoundReady(this.key)) + { + this.pendingPlayback = false; + this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop); + } + + if (this.isPlaying) + { + this.currentTime = this.game.time.time - this.startTime; + + if (this.currentTime >= this.durationMS) + { + if (this.usingWebAudio) + { + if (this.loop) + { + // won't work with markers, needs to reset the position + this.onLoop.dispatch(this); + + // Gets reset by the play function + this.isPlaying = false; + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + this.isPlaying = true; // play not called again in this case + } + else + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + this.play(this.currentMarker, 0, this.volume, true, true); + } + } + else + { + // Stop if we're using an audio marker, otherwise we let onended handle it + if (this.currentMarker !== '') + { + this.stop(); + } + } + } + else + { + if (this.loop) + { + this.onLoop.dispatch(this); + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + } + + // Gets reset by the play function + this.isPlaying = false; + + this.play(this.currentMarker, 0, this.volume, true, true); + } + else + { + this.stop(); + } + } + } + } + }, + + /** + * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters. + * + * @method Phaser.Sound#loopFull + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + loopFull: function (volume) { + + return this.play(null, 0, volume, true); + + }, + + /** + * Play this sound, or a marked section of it. + * + * @method Phaser.Sound#play + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. + * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, position, volume, loop, forceRestart) { + + if (marker === undefined || marker === false || marker === null) { marker = ''; } + if (forceRestart === undefined) { forceRestart = true; } + + if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override) + { + // Use Restart instead + return this; + } + + if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart)) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) { + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + + this.isPlaying = false; + } + + if (marker === '' && Object.keys(this.markers).length > 0) + { + // If they didn't specify a marker but this is an audio sprite, + // we should never play the entire thing + return this; + } + + if (marker !== '') + { + if (this.markers[marker]) + { + this.currentMarker = marker; + + // Playing a marker? Then we default to the marker values + 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 (volume === undefined) { volume = this._volume; } + if (loop === undefined) { loop = this.loop; } + + this.position = Math.max(0, 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) + { + // Does the sound need decoding? + if (this.game.cache.isSoundDecoded(this.key)) + { + this._sound = this.context.createBufferSource(); + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + this._buffer = this.game.cache.getSoundData(this.key); + this._sound.buffer = this._buffer; + + if (this.loop && marker === '') + { + this._sound.loop = true; + } + + if (!this.loop && marker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + this.totalDuration = this._sound.buffer.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = Math.ceil(this.totalDuration * 1000); + } + + // Useful to cache this somewhere perhaps? + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, this.position, this.duration); + } + else + { + if (this.loop && marker === '') + { + this._sound.start(0, 0); + } + else + { + this._sound.start(0, this.position, this.duration); + } + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + 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 doesn't become available until you call play(), wonderful ... + this.totalDuration = this._sound.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = this.totalDuration * 1000; + } + + this._sound.currentTime = this.position; + this._sound.muted = this._muted; + + if (this._muted || this.game.sound.mute) + { + this._sound.volume = 0; + } + else + { + this._sound.volume = this._volume; + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + this.currentTime = 0; + this.stopTime = this.startTime + this.durationMS; + + this.onPlay.dispatch(this); + } + else + { + this.pendingPlayback = true; + } + } + } + + return this; + + }, + + /** + * Restart the sound, or a marked section of it. + * + * @method Phaser.Sound#restart + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. + * @param {boolean} [loop=false] - Loop when it finished playing? + */ + restart: function (marker, position, volume, loop) { + + marker = marker || ''; + position = position || 0; + volume = volume || 1; + if (loop === undefined) { loop = false; } + + this.play(marker, position, volume, loop, true); + + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound#pause + */ + pause: function () { + + if (this.isPlaying && this._sound) + { + this.paused = true; + this.pausedPosition = this.currentTime; + this.pausedTime = this.game.time.time; + this._tempPause = this._sound.currentTime; + this.onPause.dispatch(this); + this.stop(); + } + + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound#resume + */ + resume: function () { + + if (this.paused && this._sound) + { + if (this.usingWebAudio) + { + var p = Math.max(0, this.position + (this.pausedPosition / 1000)); + + this._sound = this.context.createBufferSource(); + this._sound.buffer = this._buffer; + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + if (this.loop) + { + this._sound.loop = true; + } + + if (!this.loop && this.currentMarker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + var duration = this.duration - (this.pausedPosition / 1000); + + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, p, duration); + //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it + } + else + { + if (this.loop && this.game.device.chrome) + { + // Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099 + if (this.game.device.chromeVersion === 42) + { + this._sound.start(0); + } + else + { + this._sound.start(0, p); + } + } + else + { + this._sound.start(0, p, duration); + } + } + } + else + { + this._sound.currentTime = this._tempPause; + this._sound.play(); + } + + this.isPlaying = true; + this.paused = false; + this.startTime += (this.game.time.time - this.pausedTime); + this.onResume.dispatch(this); + } + + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound#stop + */ + stop: function () { + + if (this.isPlaying && this._sound) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) + { + // Thanks Android 4.4 + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + } + + this.pendingPlayback = false; + this.isPlaying = false; + + if (!this.paused) + { + var prevMarker = this.currentMarker; + + if (this.currentMarker !== '') + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + } + + this.currentMarker = ''; + + if (this.fadeTween !== null) + { + this.fadeTween.stop(); + } + + this.onStop.dispatch(this, prevMarker); + } + + }, + + /** + * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. + * Then increases the volume from 0 to 1 over the duration specified. + * + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (1) as the second parameter. + * + * @method Phaser.Sound#fadeIn + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in. + * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. + * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. + */ + fadeIn: function (duration, loop, marker) { + + if (loop === undefined) { loop = false; } + if (marker === undefined) { marker = this.currentMarker; } + + if (this.paused) + { + return; + } + + this.play(marker, 0, 0, loop); + + this.fadeTo(duration, 1); + + }, + + /** + * Decreases the volume of this Sound from its current value to 0 over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (0) as the second parameter. + * + * @method Phaser.Sound#fadeOut + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out. + */ + fadeOut: function (duration) { + + this.fadeTo(duration, 0); + + }, + + /** + * Fades the volume of this Sound from its current value to the given volume over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (volume) as the second parameter. + * + * @method Phaser.Sound#fadeTo + * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out. + * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1. + */ + fadeTo: function (duration, volume) { + + if (!this.isPlaying || this.paused || volume === this.volume) + { + return; + } + + if (duration === undefined) { duration = 1000; } + + if (volume === undefined) + { + console.warn("Phaser.Sound.fadeTo: No Volume Specified."); + return; + } + + this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true); + + this.fadeTween.onComplete.add(this.fadeComplete, this); + + }, + + /** + * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo. + * + * @method Phaser.Sound#fadeComplete + * @private + */ + fadeComplete: function () { + + this.onFadeComplete.dispatch(this, this.volume); + + if (this.volume === 0) + { + this.stop(); + } + + }, + + /** + * Called automatically by SoundManager.volume. + * + * Sets the volume of AudioTag Sounds as a percentage of the Global Volume. + * + * You should not normally call this directly. + * + * @method Phaser.Sound#updateGlobalVolume + * @protected + * @param {float} globalVolume - The global SoundManager volume. + */ + updateGlobalVolume: function (globalVolume) { + + // this._volume is the % of the global volume this sound should be played at + + if (this.usingAudioTag && this._sound) + { + this._globalVolume = globalVolume; + this._sound.volume = this._globalVolume * this._volume; + } + + }, + + /** + * Destroys this sound and all associated events and removes it from the SoundManager. + * + * @method Phaser.Sound#destroy + * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager. + */ + destroy: function (remove) { + + if (remove === undefined) { remove = true; } + + this._markedToDelete = true; + this._removeFromSoundManager = remove; + this.stop(); + + if (remove) + { + this.game.sound.remove(this); + } + else + { + 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; + +/** +* @name Phaser.Sound#isDecoding +* @property {boolean} isDecoding - Returns true if the sound file is still decoding. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoding", { + + get: function () { + return this.game.cache.getSound(this.key).isDecoding; + } + +}); + +/** +* @name Phaser.Sound#isDecoded +* @property {boolean} isDecoded - Returns true if the sound file has decoded. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoded", { + + get: function () { + return this.game.cache.isSoundDecoded(this.key); + } + +}); + +/** +* @name Phaser.Sound#mute +* @property {boolean} mute - Gets or sets the muted state of this sound. +*/ +Object.defineProperty(Phaser.Sound.prototype, "mute", { + + get: function () { + + return (this._muted || this.game.sound.mute); + + }, + + set: function (value) { + + value = value || false; + + if (value === this._muted) + { + return; + } + + if (value) + { + this._muted = true; + this._muteVolume = this._tempVolume; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = 0; + } + else if (this.usingAudioTag && this._sound) + { + 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); + + } + +}); + +/** +* @name Phaser.Sound#volume +* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Sound.prototype, "volume", { + + get: function () { + return this._volume; + }, + + set: function (value) { + + // Causes an Index size error if you don't clamp the value + if (this.usingAudioTag) + { + value = this.game.math.clamp(value, 0, 1); + } + + if (this._muted) + { + this._muteVolume = value; + return; + } + + this._tempVolume = value; + this._volume = value; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = value; + } + else if (this.usingAudioTag && this._sound) + { + this._sound.volume = this._globalVolume * value; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. +* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. +* The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. +* There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ +* +* If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out +* of AudioContext nodes. If this is the case create a global var called {@link PhaserGlobal} on the window object before creating the game. The active +* AudioContext will then be saved to `window.PhaserGlobal.audioContext` when the Phaser game is destroyed, and re-used when it starts again. +* +* Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. +* When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. +* The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will +* be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. +* +* @class Phaser.SoundManager +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.SoundManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) + */ + this.onSoundDecode = new Phaser.Signal(); + + /** + * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. + * @property {Phaser.Signal} onVolumeChange + */ + this.onVolumeChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. + * @property {Phaser.Signal} onMute + */ + this.onMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. + * @property {Phaser.Signal} onUnMute + */ + this.onUnMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is touch-unlocked. + * If the device doesn't {@link Phaser.Device.needsTouchUnlock need touch-unlocking}, the signal won't be dispatched. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * @property {AudioContext} context - The AudioContext being used for playback. + * @default + */ + this.context = null; + + /** + * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio. + * @readonly + */ + this.usingWebAudio = false; + + /** + * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio. + * @readonly + */ + this.usingAudioTag = false; + + /** + * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. + * @default + */ + this.noAudio = false; + + /** + * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. + * @default + */ + this.connectToMaster = true; + + /** + * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. + * @default + */ + this.touchLocked = false; + + /** + * @property {number} channels - The number of audio channels to use in playback. + * @default + */ + this.channels = 32; + + /** + * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), + * or set to false to keep audio playing, regardless of the game pause state. You may need to + * do this should you wish to control audio muting via external DOM buttons or similar. + * @property {boolean} muteOnPause + * @default + */ + this.muteOnPause = true; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {AudioContext} _unlockSource - Internal unlock tracking var. + * @private + * @default + */ + this._unlockSource = null; + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + * @default + */ + this._volume = 1; + + + /** + * @property {array} _sounds - An array containing all the sounds + * @private + */ + this._sounds = []; + + /** + * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status. + * @private + */ + this._watchList = new Phaser.ArraySet(); + + /** + * @property {boolean} _watching - Is the SoundManager monitoring the watchList? + * @private + */ + this._watching = false; + + /** + * @property {function} _watchCallback - The callback to invoke once the watchlist is clear. + * @private + */ + this._watchCallback = null; + + /** + * @property {object} _watchContext - The context in which to call the watchlist callback. + * @private + */ + this._watchContext = null; + +}; + +Phaser.SoundManager.prototype = { + + /** + * Initialises the sound manager. + * @method Phaser.SoundManager#boot + * @protected + */ + boot: function () { + + var device = this.game.device; + var PhaserGlobal = window.PhaserGlobal; + + if (device.iOS && device.webAudio === false) + { + this.channels = 1; + } + + // PhaserGlobal overrides + if (PhaserGlobal) + { + // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class) + if (PhaserGlobal.disableAudio === true) + { + this.noAudio = true; + this.touchLocked = false; + return; + } + + // Check if the Web Audio API is disabled (for testing Audio Tag playback during development) + if (PhaserGlobal.disableWebAudio === true) + { + this.usingAudioTag = true; + this.touchLocked = false; + return; + } + } + + if (PhaserGlobal && PhaserGlobal.audioContext) + { + this.context = PhaserGlobal.audioContext; + } + else + { + if (!!window['AudioContext']) + { + try { + this.context = new window['AudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + else if (!!window['webkitAudioContext']) + { + try { + this.context = new window['webkitAudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + } + + if (this.context === null) + { + // No Web Audio support - how about legacy Audio? + if (window['Audio'] === undefined) + { + this.noAudio = true; + return; + } + else + { + this.usingAudioTag = true; + } + } + else + { + this.usingWebAudio = true; + + if (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); + } + + if (!this.noAudio) + { + // On mobile we need a native touch event before we can play anything, so capture it here + if (device.needsTouchUnlock()) + { + this.setTouchLock(); + } + } + + if (this.usingWebAudio && device.chrome && device.chromeVersion <= 65) + { + console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. '); + } + + }, + + /** + * Sets the Input Manager touch callback to be SoundManager.unlock. + * Required for iOS audio device unlocking. Mostly just used internally. + * + * @method Phaser.SoundManager#setTouchLock + */ + setTouchLock: function () { + + if (this.noAudio || (window.PhaserGlobal && window.PhaserGlobal.disableAudio === true)) + { + return; + } + + this.game.input.addTouchLockCallback(this.unlock, this, true); + + this.touchLocked = true; + + }, + + /** + * Turns off {@link #touchLocked} and dispatches {@link #onTouchUnlock}. + * + * @method Phaser.SoundManager#setTouchUnlock + * @private + */ + setTouchUnlock: function () { + + this.touchLocked = false; + this._unlockSource = null; + this.onTouchUnlock.dispatch(); + + }, + + /** + * Enables the audio, usually after the first touch. + * + * @method Phaser.SoundManager#unlock + * @return {boolean} True if the callback should be removed, otherwise false. + */ + unlock: function () { + + if (this.noAudio || !this.touchLocked || this._unlockSource !== null) + { + return true; + } + + // Global override (mostly for Audio Tag testing) + if (this.usingAudioTag) + { + this.setTouchUnlock(); + } + else if (this.usingWebAudio) + { + // Create empty buffer and play it + // The SoundManager.update loop captures the state of it and then resets touchLocked to false + + var buffer = this.context.createBuffer(1, 1, 22050); + this._unlockSource = this.context.createBufferSource(); + this._unlockSource.buffer = buffer; + this._unlockSource.connect(this.context.destination); + + if (this._unlockSource.start === undefined) + { + this._unlockSource.noteOn(0); + } + else + { + this._unlockSource.start(0); + } + + //This fixes locked audio in Chrome > 55 cross origin iframes + if (this._unlockSource.context.state === 'suspended') { + this._unlockSource.context.resume(); + } + } + + // We can remove the event because we've done what we needed (started the unlock sound playing) + return true; + + }, + + /** + * Stops all the sounds in the game. + * + * @method Phaser.SoundManager#stopAll + */ + stopAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].stop(); + } + } + + }, + + /** + * Pauses all the sounds in the game. + * + * @method Phaser.SoundManager#pauseAll + */ + pauseAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].pause(); + } + } + + }, + + /** + * Resumes every sound in the game. + * + * @method Phaser.SoundManager#resumeAll + */ + resumeAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].resume(); + } + } + + }, + + /** + * Decode a sound by its asset key. + * + * @method Phaser.SoundManager#decode + * @param {string} key - Assets key of the sound to be decoded. + * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. + */ + decode: function (key, sound) { + + sound = sound || null; + + var soundData = this.game.cache.getSoundData(key); + + if (soundData) + { + if (this.game.cache.isSoundDecoded(key) === false) + { + this.game.cache.updateSound(key, 'isDecoding', true); + + var _this = this; + + try { + this.context.decodeAudioData(soundData, function (buffer) { + + if (buffer) + { + _this.game.cache.decodedSound(key, buffer); + _this.onSoundDecode.dispatch(key, sound); + } + }); + } + catch (e) {} + } + } + + }, + + /** + * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback. + * Once all of the Sound files have finished decoding the callback will be invoked. + * The amount of time spent decoding depends on the codec used and file size. + * If all of the files given have already decoded the callback is triggered immediately. + * + * @method Phaser.SoundManager#setDecodedCallback + * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache. + * @param {Function} callback - The callback which will be invoked once all files have finished decoding. + * @param {Object} callbackContext - The context in which the callback will run. + */ + setDecodedCallback: function (files, callback, callbackContext) { + + if (typeof files === 'string') + { + files = [ files ]; + } + + this._watchList.reset(); + + for (var i = 0; i < files.length; i++) + { + if (files[i] instanceof Phaser.Sound) + { + if (!this.game.cache.isSoundDecoded(files[i].key)) + { + this._watchList.add(files[i].key); + } + } + else if (!this.game.cache.isSoundDecoded(files[i])) + { + this._watchList.add(files[i]); + } + } + + // All decoded already? + if (this._watchList.total === 0) + { + this._watching = false; + callback.call(callbackContext); + } + else + { + this._watching = true; + this._watchCallback = callback; + this._watchContext = callbackContext; + } + + }, + + /** + * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. + * + * @method Phaser.SoundManager#update + * @protected + */ + update: function () { + + if (this.noAudio) + { + return; + } + + if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE)) + { + this.setTouchUnlock(); + } + + for (var i = 0; i < this._sounds.length; i++) + { + this._sounds[i].update(); + } + + if (this._watching) + { + var key = this._watchList.first; + + while (key) + { + if (this.game.cache.isSoundDecoded(key)) + { + this._watchList.remove(key); + } + + key = this._watchList.next; + } + + if (this._watchList.total === 0) + { + this._watching = false; + this._watchCallback.call(this._watchContext); + } + } + + }, + + /** + * Adds a new Sound into the SoundManager. + * + * @method Phaser.SoundManager#add + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The new sound instance. + */ + add: function (key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = this.connectToMaster; } + + var sound = new Phaser.Sound(this.game, key, volume, loop, connect); + + this._sounds.push(sound); + + return sound; + + }, + + /** + * Adds a new AudioSprite into the SoundManager. + * + * @method Phaser.SoundManager#addSprite + * @param {string} key - Asset key for the sound. + * @return {Phaser.AudioSprite} The new AudioSprite instance. + */ + addSprite: function(key) { + + var audioSprite = new Phaser.AudioSprite(this.game, key); + + return audioSprite; + + }, + + /** + * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. + * + * @method Phaser.SoundManager#remove + * @param {Phaser.Sound} sound - The sound object to remove. + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ + remove: function (sound) { + + var i = this._sounds.length; + + while (i--) + { + if (this._sounds[i] === sound) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Removes all Sounds from the SoundManager. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeAll + */ + removeAll: function () { + + this.stopAll(); + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].destroy(); + } + } + + this._sounds.length = 0; + + }, + + /** + * Removes all Sounds from the SoundManager that have an asset key matching the given value. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeByKey + * @param {string} key - The key to match when removing sound objects. + * @return {number} The number of matching sound objects that were removed. + */ + removeByKey: function (key) { + + var i = this._sounds.length; + var removed = 0; + + while (i--) + { + if (this._sounds[i].key === key) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + removed++; + } + } + + return removed; + + }, + + /** + * Adds a new Sound into the SoundManager and starts it playing. + * + * @method Phaser.SoundManager#play + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @return {Phaser.Sound} The new sound instance. + */ + play: function (key, volume, loop) { + + if (this.noAudio) + { + return; + } + + var sound = this.add(key, volume, loop); + + sound.play(); + + return sound; + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + if (this.usingWebAudio) + { + this._muteVolume = this.masterGain.gain.value; + this.masterGain.gain.value = 0; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = true; + } + } + + this.onMute.dispatch(); + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = this._muteVolume; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = false; + } + } + + this.onUnMute.dispatch(); + + }, + + /** + * Stops all the sounds in the game, then destroys them and finally clears up any callbacks. + * + * @method Phaser.SoundManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.onSoundDecode.dispose(); + + if (this.context) + { + if (window.PhaserGlobal) + { + // Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing + window.PhaserGlobal.audioContext = this.context; + } + else + { + if (this.context.close) + { + this.context.close(); + } + } + } + + } + +}; + +Phaser.SoundManager.prototype.constructor = Phaser.SoundManager; + +/** +* @name Phaser.SoundManager#mute +* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || false; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* @name Phaser.SoundManager#volume +* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "volume", { + + get: function () { + + return this._volume; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this._volume !== value) + { + this._volume = value; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = value; + } + else + { + // Loop through the sound cache and change the volume of all html audio tags + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].updateGlobalVolume(value); + } + } + } + + this.onVolumeChange.dispatch(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* The ScaleManager object handles the the scaling, resizing, and alignment of the +* Game size and the game Display canvas. +* +* The Game size is the logical size of the game; the Display canvas has size as an HTML element. +* +* The calculations of these are heavily influenced by the bounding Parent size which is the computed +* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the +* canvas's Parent element play an important role_ in the operation of the ScaleManager. +* +* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size. +* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}). +* +* #### Parent and Display canvas containment guidelines: +* +* - Style the Parent element (of the game canvas) to control the Parent size and +* thus the Display canvas's size and layout. +* +* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior. +* +* - The Parent element should _not_ apply a padding as this is not accounted for. +* If a padding is required apply it to the Parent's parent or apply a margin to the Parent. +* If you need to add a border, margin or any other CSS around your game container, then use a parent element and +* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container. +* +* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as +* they may be updated by the ScaleManager. +* +* #### Example Uses +* +* - ##### Fixed game size; scale canvas proportionally to fill its container +* +* Use `scaleMode` SHOW_ALL. +* +* - ##### Fixed game size; stretch canvas to fill its container (uncommon) +* +* Use `scaleMode` EXACT_FIT. +* +* - ##### Fixed game size; scale canvas proportionally by some other criteria +* +* Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary. +* +* - ##### Fluid game/canvas size +* +* Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary. +* +* - ##### Preferred orientation +* +* Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals. +* +* @description +* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game} +* +* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. +* +* @class +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number|string} width - The width of the game. See above. +* @param {number|string} height - The height of the game. See above. +*/ +Phaser.ScaleManager = function (game, width, height) { + + /** + * A reference to the currently running game. + * @property {Phaser.Game} game + * @protected + * @readonly + */ + this.game = game; + + /** + * Provides access to some cross-device DOM functions. + * @property {Phaser.DOM} dom + * @protected + * @readonly + */ + this.dom = Phaser.DOM; + + /** + * _EXPERIMENTAL:_ A responsive grid on which you can align game objects. + * @property {Phaser.FlexGrid} grid + * @public + */ + this.grid = null; + + /** + * Target width (in pixels) of the Display canvas. + * @property {number} width + * @readonly + */ + this.width = 0; + + /** + * Target height (in pixels) of the Display canvas. + * @property {number} height + * @readonly + */ + this.height = 0; + + /** + * Minimum width the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minWidth + * @readonly + * @protected + */ + this.minWidth = null; + + /** + * Maximum width the canvas should be scaled to (in pixels). + * If null it will scale to whatever width the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxWidth + * @readonly + * @protected + */ + this.maxWidth = null; + + /** + * Minimum height the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minHeight + * @readonly + * @protected + */ + this.minHeight = null; + + /** + * Maximum height the canvas should be scaled to (in pixels). + * If null it will scale to whatever height the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxHeight + * @readonly + * @protected + */ + this.maxHeight = null; + + /** + * The offset coordinates of the Display canvas from the top-left of the browser window. + * The is used internally by Phaser.Pointer (for Input) and possibly other types. + * @property {Phaser.Point} offset + * @readonly + * @protected + */ + this.offset = new Phaser.Point(); + + /** + * If true, the game should only run in a landscape orientation. + * Change with {@link #forceOrientation}. + * @property {boolean} forceLandscape + * @readonly + * @default + * @protected + */ + this.forceLandscape = false; + + /** + * If true, the game should only run in a portrait + * Change with {@link #forceOrientation}. + * @property {boolean} forcePortrait + * @readonly + * @default + * @protected + */ + this.forcePortrait = false; + + /** + * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation. + * + * This value is not updated immediately. + * + * @property {boolean} incorrectOrientation + * @readonly + * @protected + */ + this.incorrectOrientation = false; + + /** + * See {@link #pageAlignHorizontally}. + * @property {boolean} _pageAlignHorizontally + * @private + */ + this._pageAlignHorizontally = false; + + /** + * See {@link #pageAlignVertically}. + * @property {boolean} _pageAlignVertically + * @private + */ + this._pageAlignVertically = false; + + /** + * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes. + * + * The signal is supplied with the following arguments: + * - `scale` - the ScaleManager object + * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}. + * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. + * + * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. + * Thus the following tests can be done: + * + * // The orientation itself changed: + * scale.screenOrientation !== prevOrientation + * // The orientation just became incorrect: + * scale.incorrectOrientation && !wasIncorrect + * + * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation + * correctness changes even if the orientation itself does not change. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onOrientationChange + * @public + */ + this.onOrientationChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} enterIncorrectOrientation + * @public + */ + this.enterIncorrectOrientation = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} leaveIncorrectOrientation + * @public + */ + this.leaveIncorrectOrientation = new Phaser.Signal(); + + /** + * This boolean provides you with a way to determine if the browser is in Full Screen + * mode (via the Full Screen API), and Phaser was the one responsible for activating it. + * + * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the + * one that made the browser go full-screen, so this flag lets you determine that. + * + * @property {boolean} hasPhaserSetFullScreen + * @default + */ + this.hasPhaserSetFullScreen = false; + + /** + * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. + * The target element must have the correct CSS styling and contain the Display canvas. + * + * The elements style will be modified (ie. the width and height might be set to 100%) + * but it will not be added to, removed from, or repositioned within the DOM. + * An attempt is made to restore relevant style changes when fullscreen mode is left. + * + * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. + * + * @property {?DOMElement} fullScreenTarget + * @default + */ + this.fullScreenTarget = null; + + /** + * The fullscreen target, as created by {@link #createFullScreenTarget}. + * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends. + * @property {?DOMElement} _createdFullScreenTarget + * @private + */ + this._createdFullScreenTarget = null; + + /** + * This signal is dispatched when fullscreen mode is ready to be initialized but + * before the fullscreen request. + * + * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. + * + * The `targetElement` is the {@link #fullScreenTarget} element, + * if such is assigned, or a new element created by {@link #createFullScreenTarget}. + * + * Custom CSS styling or resets can be applied to `targetElement` as required. + * + * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}: + * - After initialization the Display canvas is moved onto the `targetElement` for + * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. + * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. + * + * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}. + * + * @property {Phaser.Signal} onFullScreenInit + * @public + */ + this.onFullScreenInit = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine + * if currently running in Fullscreen mode. + * + * @property {Phaser.Signal} onFullScreenChange + * @public + */ + this.onFullScreenChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser fails to enter fullscreen mode; + * or if the device does not support fullscreen mode and `startFullScreen` is invoked. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). + * + * @property {Phaser.Signal} onFullScreenError + * @public + */ + this.onFullScreenError = new Phaser.Signal(); + + /** + * The _last known_ orientation of the screen, as defined in the Window Screen Web API. + * See {@link Phaser.DOM.getScreenOrientation} for possible values. + * + * @property {string} screenOrientation + * @readonly + * @public + */ + this.screenOrientation = this.dom.getScreenOrientation(); + + /** + * The _current_ scale factor based on the game dimensions vs. the scaled dimensions. + * @property {Phaser.Point} scaleFactor + * @readonly + */ + this.scaleFactor = new Phaser.Point(1, 1); + + /** + * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions. + * @property {Phaser.Point} scaleFactorInversed + * @readonly + * @protected + */ + this.scaleFactorInversed = new Phaser.Point(1, 1); + + /** + * The Display canvas is aligned by adjusting the margins; the last margins are stored here. + * + * @property {Bounds-like} margin + * @readonly + * @protected + */ + this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0}; + + /** + * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. + * @property {Phaser.Rectangle} bounds + * @readonly + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The aspect ratio of the scaled Display canvas. + * @property {number} aspectRatio + * @readonly + */ + this.aspectRatio = 0; + + /** + * The aspect ratio of the original game dimensions. + * @property {number} sourceAspectRatio + * @readonly + */ + this.sourceAspectRatio = 0; + + /** + * The native browser events from Fullscreen API changes. + * @property {any} event + * @readonly + * @private + */ + this.event = null; + + /** + * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container. + * + * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. + * - If 'visual', the edge will be constrained to the Window / displayed screen area + * - If 'layout', the edge will be constrained to the CSS Layout bounds + * - An invalid value is treated as 'visual' + * + * @member + * @property {string} bottom + * @property {string} right + * @default + */ + this.windowConstraints = { + right: 'layout', + bottom: '' + }; + + /** + * Various compatibility settings. + * A value of "(auto)" indicates the setting is configured based on device and runtime information. + * + * A {@link #refresh} may need to be performed after making changes. + * + * @protected + * + * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.) + * + * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}. + * + * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. + * + * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh. + * + * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates. + * The height set varies by device and may either be the height of the window or the viewport. + * + * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. + * + * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. + * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. + * Any other string value (including the empty string) prevents using click trampolines. + * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}. + */ + this.compatibility = { + supportsFullScreen: false, + orientationFallback: null, + noMargins: false, + scrollTo: null, + forceMinimumDocumentHeight: false, + canExpandParent: true, + clickTrampoline: '' + }; + + /** + * Scale mode to be used when not in fullscreen. + * @property {number} _scaleMode + * @private + */ + this._scaleMode = Phaser.ScaleManager.NO_SCALE; + + /* + * Scale mode to be used in fullscreen. + * @property {number} _fullScreenScaleMode + * @private + */ + this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE; + + /** + * True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * The {@link #parentNode} property is generally ignored while this is in effect. + * + * @property {boolean} parentIsWindow + */ + this.parentIsWindow = false; + + /** + * The _original_ DOM element for the parent of the Display canvas. + * This may be different in fullscreen - see {@link #createFullScreenTarget}. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * This should only be changed after moving the Game canvas to a different DOM parent. + * + * @property {?DOMElement} parentNode + */ + this.parentNode = null; + + /** + * The scale of the game in relation to its parent container. + * @property {Phaser.Point} parentScaleFactor + * @readonly + */ + this.parentScaleFactor = new Phaser.Point(1, 1); + + /** + * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). + * Update checks normally happen quicker in response to other events. + * + * @property {integer} trackParentInterval + * @default + * @protected + * @see {@link Phaser.ScaleManager#refresh refresh} + */ + this.trackParentInterval = 2000; + + /** + * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. + * When invoked this is done _after_ the Canvas size/position have been updated. + * + * The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.) + * + * This signal is _only_ called when a change occurs and a reflow may be required. + * For example, if the canvas does not change sizes because of CSS settings (such as min-width) + * then this signal will _not_ be triggered. + * + * Use this to handle responsive game layout options. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onSizeChange + */ + this.onSizeChange = new Phaser.Signal(); + + /** + * The callback that will be called each the parent container resizes. + * @property {function} onResize + * @private + */ + this.onResize = null; + + /** + * The context in which the {@link #onResize} callback will be called. + * @property {object} onResizeContext + * @private + */ + this.onResizeContext = null; + + /** + * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot. + * @private + */ + this._pendingScaleMode = null; + + /** + * Information saved when fullscreen mode is started. + * @property {?object} _fullScreenRestore + * @private + */ + this._fullScreenRestore = null; + + /** + * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}. + * @property {Phaser.Rectangle} _gameSize + * @private + */ + this._gameSize = new Phaser.Rectangle(); + + /** + * The user-supplied scale factor, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleFactor + * @private + */ + this._userScaleFactor = new Phaser.Point(1, 1); + + /** + * The user-supplied scale trim, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleTrim + * @private + */ + this._userScaleTrim = new Phaser.Point(0, 0); + + /** + * The last time the bounds were checked in `preUpdate`. + * @property {number} _lastUpdate + * @private + */ + this._lastUpdate = 0; + + /** + * Size checks updates are delayed according to the throttle. + * The throttle increases to `trackParentInterval` over time and is used to more + * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety. + * @property {integer} _updateThrottle + * @private + */ + this._updateThrottle = 0; + + /** + * The minimum throttle allowed until it has slowed down sufficiently. + * @property {integer} _updateThrottleReset + * @private + */ + this._updateThrottleReset = 100; + + /** + * The cached result of the parent (possibly window) bounds; used to invalidate sizing. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._parentBounds = new Phaser.Rectangle(); + + /** + * Temporary bounds used for internal work to cut down on new objects created. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._tempBounds = new Phaser.Rectangle(); + + /** + * The Canvas size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedCanvasSize + * @private + */ + this._lastReportedCanvasSize = new Phaser.Rectangle(); + + /** + * The Game size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedGameSize + * @private + */ + this._lastReportedGameSize = new Phaser.Rectangle(); + + /** + * @property {boolean} _booted - ScaleManager booted state. + * @private + */ + this._booted = false; + + if (game.config) + { + this.parseConfig(game.config); + } + + this.setupScale(width, height); + +}; + +/** +* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.EXACT_FIT = 0; + +/** +* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.NO_SCALE = 1; + +/** +* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.SHOW_ALL = 2; + +/** +* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.RESIZE = 3; + +/** +* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.USER_SCALE = 4; + +/** +* Names of the scale modes, indexed by value. +* +* @constant +* @type {string[]} +*/ +Phaser.ScaleManager.MODES = [ + 'EXACT_FIT', + 'NO_SCALE', + 'SHOW_ALL', + 'RESIZE', + 'USER_SCALE' +]; + +Phaser.ScaleManager.prototype = { + + /** + * Start the ScaleManager. + * + * @method Phaser.ScaleManager#boot + * @protected + */ + boot: function () { + + // Configure device-dependent compatibility + + var compat = this.compatibility; + + compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS; + + // We can't do anything about the status bars in iPads, web apps or desktops + if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop) + { + if (this.game.device.android && !this.game.device.chrome) + { + compat.scrollTo = new Phaser.Point(0, 1); + } + else + { + compat.scrollTo = new Phaser.Point(0, 0); + } + } + + if (this.game.device.desktop) + { + compat.orientationFallback = 'screen'; + compat.clickTrampoline = 'when-not-mouse'; + } + else + { + compat.orientationFallback = ''; + compat.clickTrampoline = ''; + } + + // Configure event listeners + + var _this = this; + + this._orientationChange = function(event) { + return _this.orientationChange(event); + }; + + this._windowResize = function(event) { + return _this.windowResize(event); + }; + + // This does not appear to be on the standards track + window.addEventListener('orientationchange', this._orientationChange, false); + window.addEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + this._fullScreenChange = function(event) { + return _this.fullScreenChange(event); + }; + + this._fullScreenError = function(event) { + return _this.fullScreenError(event); + }; + + document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.addEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.addEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.addEventListener('fullscreenchange', this._fullScreenChange, false); + + document.addEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.addEventListener('mozfullscreenerror', this._fullScreenError, false); + document.addEventListener('MSFullscreenError', this._fullScreenError, false); + document.addEventListener('fullscreenerror', this._fullScreenError, false); + } + + this.game.onResume.add(this._gameResumed, this); + + // Initialize core bounds + + this.dom.getOffset(this.game.canvas, this.offset); + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + this.setGameSize(this.game.width, this.game.height); + + // Don't use updateOrientationState so events are not fired + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + if (Phaser.FlexGrid) + { + this.grid = new Phaser.FlexGrid(this, this.width, this.height); + } + + this._booted = true; + + if (this._pendingScaleMode !== null) + { + this.scaleMode = this._pendingScaleMode; + this._pendingScaleMode = null; + } + + }, + + /** + * Load configuration settings. + * + * @method Phaser.ScaleManager#parseConfig + * @protected + * @param {object} config - The game configuration object. + */ + parseConfig: function (config) { + + if (config['scaleMode'] !== undefined) + { + if (this._booted) + { + this.scaleMode = config['scaleMode']; + } + else + { + this._pendingScaleMode = config['scaleMode']; + } + } + + if (config['fullScreenScaleMode'] !== undefined) + { + this.fullScreenScaleMode = config['fullScreenScaleMode']; + } + + if (config['fullScreenTarget']) + { + this.fullScreenTarget = config['fullScreenTarget']; + } + + this.pageAlignHorizontally = config.alignH || false; + this.pageAlignVertically = config.alignV || false; + + if (config.scaleH && config.scaleV) + { + this.setUserScale(config.scaleH, config.scaleV, config.trimH, config.trimV); + } + + }, + + /** + * Calculates and sets the game dimensions based on the given width and height. + * + * This should _not_ be called when in fullscreen mode. + * + * @method Phaser.ScaleManager#setupScale + * @protected + * @param {number|string} width - The width of the game. + * @param {number|string} height - The height of the game. + */ + setupScale: function (width, height) { + + var target; + var rect = new Phaser.Rectangle(); + + if (this.game.parent !== '') + { + if (typeof this.game.parent === 'string') + { + // hopefully an element ID + target = document.getElementById(this.game.parent); + } + else if (this.game.parent && this.game.parent.nodeType === 1) + { + // quick test for a HTMLelement + target = this.game.parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + // Use the full window + this.parentNode = null; + this.parentIsWindow = true; + + rect.width = this.dom.visualBounds.width; + rect.height = this.dom.visualBounds.height; + + this.offset.set(0, 0); + } + else + { + this.parentNode = target; + this.parentIsWindow = false; + + this.getParentBounds(this._parentBounds); + + rect.width = this._parentBounds.width; + rect.height = this._parentBounds.height; + + this.offset.set(this._parentBounds.x, this._parentBounds.y); + } + + var newWidth = 0; + var newHeight = 0; + + if (typeof width === 'number') + { + newWidth = width; + } + else + { + // Percentage based + this.parentScaleFactor.x = parseInt(width, 10) / 100; + newWidth = rect.width * this.parentScaleFactor.x; + } + + if (typeof height === 'number') + { + newHeight = height; + } + else + { + // Percentage based + this.parentScaleFactor.y = parseInt(height, 10) / 100; + newHeight = rect.height * this.parentScaleFactor.y; + } + + newWidth = Math.floor(newWidth); + newHeight = Math.floor(newHeight); + + this._gameSize.setTo(0, 0, newWidth, newHeight); + + this.updateDimensions(newWidth, newHeight, false); + + }, + + /** + * Invoked when the game is resumed. + * + * @method Phaser.ScaleManager#_gameResumed + * @private + */ + _gameResumed: function () { + + this.queueUpdate(true); + + }, + + /** + * Set the actual Game size. + * Use this instead of directly changing `game.width` or `game.height`. + * + * The actual physical display (Canvas element size) depends on various settings including + * - Scale mode + * - Scaling factor + * - Size of Canvas's parent element or CSS rules such as min-height/max-height; + * - The size of the Window + * + * @method Phaser.ScaleManager#setGameSize + * @public + * @param {integer} width - _Game width_, in pixels. + * @param {integer} height - _Game height_, in pixels. + */ + setGameSize: function (width, height) { + + this._gameSize.setTo(0, 0, width, height); + + if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE) + { + this.updateDimensions(width, height, true); + } + + this.queueUpdate(true); + + }, + + /** + * Set a User scaling factor used in the USER_SCALE scaling mode. + * + * The target canvas size is computed by: + * + * canvas.width = (game.width * hScale) - hTrim + * canvas.height = (game.height * vScale) - vTrim + * + * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly. + * + * @method Phaser.ScaleManager#setUserScale + * @param {number} hScale - Horizontal scaling factor. + * @param {numer} vScale - Vertical scaling factor. + * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling. + * @param {integer} [vTrim=0] - Vertical trim, applied after scaling. + * @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate + * @param {boolean} [force=true] - Force a resize during the next preUpdate + */ + setUserScale: function (hScale, vScale, hTrim, vTrim, queueUpdate, force) { + + this._userScaleFactor.setTo(hScale, vScale); + this._userScaleTrim.setTo(hTrim | 0, vTrim | 0); + + if (queueUpdate === undefined) { queueUpdate = true; } + if (force === undefined) { force = true; } + + if (queueUpdate) + { + this.queueUpdate(force); + } + + }, + + /** + * Sets the callback that will be invoked before sizing calculations. + * + * Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries: + * the browser window has been resized, the device has been rotated, or the parent container's size has changed. + * At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all + * after it makes its sizing calculations). You can read the size of the parent container from the + * `parentBounds` argument to the callback. + * + * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling. + * + * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager + * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. + * + * This callback + * - May be invoked even though the parent container or canvas sizes have not changed + * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated + * - Will be invoked from `preUpdate`, _even when_ the game is paused + * + * See {@link #onSizeChange} for a better way of reacting to layout updates. + * + * @method Phaser.ScaleManager#setResizeCallback + * @public + * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes. + * @param {object} context - The context in which the callback will be called. + */ + setResizeCallback: function (callback, context) { + + this.onResize = callback; + this.onResizeContext = context; + + }, + + /** + * Signals a resize - IF the canvas or Game size differs from the last signal. + * + * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager). + * + * It dispatches the {@link #onSizeChange} signal. + * + * @method Phaser.ScaleManager#signalSizeChange + * @private + */ + signalSizeChange: function () { + + if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) || + !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize)) + { + var width = this.width; + var height = this.height; + + this._lastReportedCanvasSize.setTo(0, 0, width, height); + this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height); + + if (this.grid) + { + this.grid.onResize(width, height); + } + + this.onSizeChange.dispatch(this, width, height); + + // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode. + if (this.currentScaleMode === Phaser.ScaleManager.RESIZE) + { + this.game.state.resize(width, height); + this.game.load.resize(width, height); + } + } + + }, + + /** + * Set the min and max dimensions for the Display canvas. + * + * _Note:_ The min/max dimensions are only applied in some cases + * - When the device is not in an incorrect orientation; or + * - The scale mode is EXACT_FIT when not in fullscreen + * + * @method Phaser.ScaleManager#setMinMax + * @public + * @param {number} minWidth - The minimum width the game is allowed to scale down to. + * @param {number} minHeight - The minimum height the game is allowed to scale down to. + * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified. + * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified. + * @todo These values are only sometimes honored. + */ + setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) { + + this.minWidth = minWidth; + this.minHeight = minHeight; + + if (typeof maxWidth !== 'undefined') + { + this.maxWidth = maxWidth; + } + + if (typeof maxHeight !== 'undefined') + { + this.maxHeight = maxHeight; + } + + }, + + /** + * The ScaleManager.preUpdate is called automatically by the core Game loop. + * + * @method Phaser.ScaleManager#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.game.time.time < (this._lastUpdate + this._updateThrottle)) + { + return; + } + + var prevThrottle = this._updateThrottle; + this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100; + + this.dom.getOffset(this.game.canvas, this.offset); + + var prevWidth = this._parentBounds.width; + var prevHeight = this._parentBounds.height; + var bounds = this.getParentBounds(this._parentBounds); + + var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight; + + // Always invalidate on a newly detected orientation change + var orientationChanged = this.updateOrientationState(); + + if (boundsChanged || orientationChanged) + { + if (this.onResize) + { + this.onResize.call(this.onResizeContext, this, bounds); + } + + this.updateLayout(); + + this.signalSizeChange(); + } + + // Next throttle, eg. 25, 50, 100, 200.. + var throttle = this._updateThrottle * 2; + + // Don't let an update be too eager about resetting the throttle. + if (this._updateThrottle < prevThrottle) + { + throttle = Math.min(prevThrottle, this._updateThrottleReset); + } + + this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval); + this._lastUpdate = this.game.time.time; + + }, + + /** + * Update method while paused. + * + * @method Phaser.ScaleManager#pauseUpdate + * @private + */ + pauseUpdate: function () { + + this.preUpdate(); + + // Updates at slowest. + this._updateThrottle = this.trackParentInterval; + + }, + + /** + * Update the dimensions taking the parent scaling factor into account. + * + * @method Phaser.ScaleManager#updateDimensions + * @private + * @param {number} width - The new width of the parent container. + * @param {number} height - The new height of the parent container. + * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars. + */ + updateDimensions: function (width, height, resize) { + + this.width = width * this.parentScaleFactor.x; + this.height = height * this.parentScaleFactor.y; + + this.game.width = this.width; + this.game.height = this.height; + + this.sourceAspectRatio = this.width / this.height; + this.updateScalingAndBounds(); + + if (resize) + { + // Resize the renderer (which in turn resizes the Display canvas!) + this.game.renderer.resize(this.width, this.height); + + // The Camera can never be smaller than the Game size + this.game.camera.setSize(this.width, this.height); + + // This should only happen if the world is smaller than the new canvas size + this.game.world.resize(this.width, this.height); + } + + }, + + /** + * Update relevant scaling values based on the ScaleManager dimension and game dimensions, + * which should already be set. This does not change {@link #sourceAspectRatio}. + * + * @method Phaser.ScaleManager#updateScalingAndBounds + * @private + */ + updateScalingAndBounds: function () { + + this.scaleFactor.x = this.game.width / this.width; + this.scaleFactor.y = this.game.height / this.height; + + this.scaleFactorInversed.x = this.width / this.game.width; + this.scaleFactorInversed.y = this.height / this.game.height; + + this.aspectRatio = this.width / this.height; + + // This can be invoked in boot pre-canvas + if (this.game.canvas) + { + this.dom.getOffset(this.game.canvas, this.offset); + } + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + // Can be invoked in boot pre-input + if (this.game.input && this.game.input.scale) + { + this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y); + } + + }, + + /** + * Force the game to run in only one orientation. + * + * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. + * + * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor + * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the + * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` + * + * @method Phaser.ScaleManager#forceOrientation + * @public + * @param {boolean} forceLandscape - true if the game should run in landscape mode only. + * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. + */ + forceOrientation: function (forceLandscape, forcePortrait) { + + if (forcePortrait === undefined) { forcePortrait = false; } + + if (forceLandscape === true && forcePortrait === true) + { + console.warn('Phaser.ScaleManager: forceLandscape and forcePortrait cannot both be true.'); + return; + } + + this.forceLandscape = forceLandscape; + this.forcePortrait = forcePortrait; + + this.queueUpdate(true); + + }, + + /** + * Classify the orientation, per `getScreenOrientation`. + * + * @method Phaser.ScaleManager#classifyOrientation + * @private + * @param {string} orientation - The orientation string, e.g. 'portrait-primary'. + * @return {?string} The classified orientation: 'portrait', 'landscape`, or null. + */ + classifyOrientation: function (orientation) { + + if (orientation === 'portrait-primary' || orientation === 'portrait-secondary') + { + return 'portrait'; + } + else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary') + { + return 'landscape'; + } + else + { + return null; + } + + }, + + /** + * Updates the current orientation and dispatches orientation change events. + * + * @method Phaser.ScaleManager#updateOrientationState + * @private + * @return {boolean} True if the orientation state changed which means a forced update is likely required. + */ + updateOrientationState: function () { + + var previousOrientation = this.screenOrientation; + var previouslyIncorrect = this.incorrectOrientation; + + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) || + (this.forcePortrait && !this.isPortrait); + + var changed = previousOrientation !== this.screenOrientation; + var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation; + + if (correctnessChanged) + { + if (this.incorrectOrientation) + { + this.enterIncorrectOrientation.dispatch(); + } + else + { + this.leaveIncorrectOrientation.dispatch(); + } + } + + if (changed || correctnessChanged) + { + this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect); + } + + return changed || correctnessChanged; + + }, + + /** + * window.orientationchange event handler. + * + * @method Phaser.ScaleManager#orientationChange + * @private + * @param {Event} event - The orientationchange event data. + */ + orientationChange: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * window.resize event handler. + * + * @method Phaser.ScaleManager#windowResize + * @private + * @param {Event} event - The resize event data. + */ + windowResize: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * Scroll to the top - in some environments. See `compatibility.scrollTo`. + * + * @method Phaser.ScaleManager#scrollTop + * @private + */ + scrollTop: function () { + + var scrollTo = this.compatibility.scrollTo; + + if (scrollTo) + { + window.scrollTo(scrollTo.x, scrollTo.y); + } + + }, + + /** + * The "refresh" methods informs the ScaleManager that a layout refresh is required. + * + * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) + * when the browser is resized, the orientation changes, or when there is a detected change + * of the Parent size. Refreshing is also done automatically when public properties, + * such as {@link #scaleMode}, are updated or state-changing methods are invoked. + * + * The "refresh" method _may_ need to be used in a few (rare) situtations when + * + * - a device change event is not correctly detected; or + * - the Parent size changes (and an immediate reflow is desired); or + * - the ScaleManager state is updated by non-standard means; or + * - certain {@link #compatibility} properties are manually changed. + * + * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. + * + * @method Phaser.ScaleManager#refresh + * @public + */ + refresh: function () { + + this.scrollTop(); + this.queueUpdate(true); + + }, + + /** + * Updates the game / canvas position and size. + * + * @method Phaser.ScaleManager#updateLayout + * @private + */ + updateLayout: function () { + + var scaleMode = this.currentScaleMode; + + if (scaleMode === Phaser.ScaleManager.RESIZE) + { + this.reflowGame(); + return; + } + + this.scrollTop(); + + if (this.compatibility.forceMinimumDocumentHeight) + { + // (This came from older code, by why is it here?) + // Set minimum height of content to new window height + document.documentElement.style.minHeight = window.innerHeight + 'px'; + } + + if (this.incorrectOrientation) + { + this.setMaximum(); + } + else + { + if (scaleMode === Phaser.ScaleManager.EXACT_FIT) + { + this.setExactFit(); + } + else if (scaleMode === Phaser.ScaleManager.SHOW_ALL) + { + if (!this.isFullScreen && this.boundingParent && + this.compatibility.canExpandParent) + { + // Try to expand parent out, but choosing maximizing dimensions. + // Then select minimize dimensions which should then honor parent + // maximum bound applications. + this.setShowAll(true); + this.resetCanvas(); + this.setShowAll(); + } + else + { + this.setShowAll(); + } + } + else if (scaleMode === Phaser.ScaleManager.NO_SCALE) + { + this.width = this.game.width; + this.height = this.game.height; + } + else if (scaleMode === Phaser.ScaleManager.USER_SCALE) + { + this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x; + this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y; + } + } + + if (!this.compatibility.canExpandParent && + (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE)) + { + var bounds = this.getParentBounds(this._tempBounds); + this.width = Math.min(this.width, bounds.width); + this.height = Math.min(this.height, bounds.height); + } + + // Always truncate / force to integer + this.width = this.width | 0; + this.height = this.height | 0; + + this.reflowCanvas(); + + }, + + /** + * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. + * + * If in fullscreen mode or without parent (see {@link #parentIsWindow}), + * this will be the bounds of the visual viewport itself. + * + * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside + * the viewport then this function may return a smaller than expected size. + * + * Values are rounded to the nearest pixel. + * + * @method Phaser.ScaleManager#getParentBounds + * @protected + * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed. + * @return {Phaser.Rectangle} The established parent bounds. + */ + getParentBounds: function (target) { + + var bounds = target || new Phaser.Rectangle(); + var parentNode = this.boundingParent; + var visualBounds = this.dom.visualBounds; + var layoutBounds = this.dom.layoutBounds; + + if (!parentNode) + { + bounds.setTo(0, 0, visualBounds.width, visualBounds.height); + } + else + { + // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect + var clientRect = parentNode.getBoundingClientRect(); + var parentRect = (parentNode.offsetParent) ? parentNode.offsetParent.getBoundingClientRect() : parentNode.getBoundingClientRect(); + + bounds.setTo(clientRect.left - parentRect.left, clientRect.top - parentRect.top, clientRect.width, clientRect.height); + + var wc = this.windowConstraints; + + if (wc.right) + { + var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds; + bounds.right = Math.min(bounds.right, windowBounds.width); + } + + if (wc.bottom) + { + var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds; + bounds.bottom = Math.min(bounds.bottom, windowBounds.height); + } + } + + bounds.setTo( + Math.round(bounds.x), Math.round(bounds.y), + Math.round(bounds.width), Math.round(bounds.height)); + + return bounds; + + }, + + + /** + * Shorthand for setting {@link #pageAlignHorizontally} and {@link #pageAlignVertically}. + * + * @method Phaser.ScaleManager#align + * @param {boolean} [horizontal] - Value for {@link #pageAlignHorizontally}. Pass `null` to leave unchanged. + * @param {boolean} [vertical] - Value for {@link #pageAlignVertically}. Omit or pass `null` to leave unchanged. + */ + align: function (horizontal, vertical) { + + if (horizontal != null) + { + this.pageAlignHorizontally = horizontal; + } + + if (vertical != null) + { + this.pageAlignVertically = vertical; + } + + }, + + /** + * Update the canvas position/margins - for alignment within the parent container. + * + * The canvas margins _must_ be reset/cleared prior to invoking this. + * + * @method Phaser.ScaleManager#alignCanvas + * @private + * @param {boolean} horizontal - Align horizontally? + * @param {boolean} vertical - Align vertically? + */ + alignCanvas: function (horizontal, vertical) { + + var parentBounds = this.getParentBounds(this._tempBounds); + var canvas = this.game.canvas; + var margin = this.margin; + + if (horizontal) + { + margin.left = margin.right = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.width < parentBounds.width && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.left - parentBounds.x; + var targetEdge = (parentBounds.width / 2) - (this.width / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + + margin.left = Math.round(offset); + } + + canvas.style.marginLeft = margin.left + 'px'; + + if (margin.left !== 0) + { + margin.right = -(parentBounds.width - canvasBounds.width - margin.left); + canvas.style.marginRight = margin.right + 'px'; + } + } + + if (vertical) + { + margin.top = margin.bottom = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.height < parentBounds.height && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.top - parentBounds.y; + var targetEdge = (parentBounds.height / 2) - (this.height / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + margin.top = Math.round(offset); + } + + canvas.style.marginTop = margin.top + 'px'; + + if (margin.top !== 0) + { + margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top); + canvas.style.marginBottom = margin.bottom + 'px'; + } + } + + // Silly backwards compatibility.. + margin.x = margin.left; + margin.y = margin.top; + + }, + + /** + * Updates the Game state / size. + * + * The canvas margins may always be adjusted, even if alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowGame + * @private + */ + reflowGame: function () { + + this.resetCanvas('', ''); + + var bounds = this.getParentBounds(this._tempBounds); + this.updateDimensions(bounds.width, bounds.height, true); + + }, + + /** + * Updates the Display canvas size. + * + * The canvas margins may always be adjusted, even alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowCanvas + * @private + */ + reflowCanvas: function () { + + if (!this.incorrectOrientation) + { + this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width); + this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height); + } + + this.resetCanvas(); + + if (!this.compatibility.noMargins) + { + if (this.isFullScreen && this._createdFullScreenTarget) + { + this.alignCanvas(true, true); + } + else + { + this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically); + } + } + + this.updateScalingAndBounds(); + + }, + + /** + * "Reset" the Display canvas and set the specified width/height. + * + * @method Phaser.ScaleManager#resetCanvas + * @private + * @param {string} [cssWidth=(current width)] - The css width to set. + * @param {string} [cssHeight=(current height)] - The css height to set. + */ + resetCanvas: function (cssWidth, cssHeight) { + + if (cssWidth === undefined) { cssWidth = this.width + 'px'; } + if (cssHeight === undefined) { cssHeight = this.height + 'px'; } + + var canvas = this.game.canvas; + + if (!this.compatibility.noMargins) + { + canvas.style.marginLeft = ''; + canvas.style.marginTop = ''; + canvas.style.marginRight = ''; + canvas.style.marginBottom = ''; + } + + canvas.style.width = cssWidth; + canvas.style.height = cssHeight; + + }, + + /** + * Queues/marks a size/bounds check as needing to occur (from `preUpdate`). + * + * @method Phaser.ScaleManager#queueUpdate + * @private + * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty. + */ + queueUpdate: function (force) { + + if (force) + { + this._parentBounds.width = 0; + this._parentBounds.height = 0; + } + + this._updateThrottle = this._updateThrottleReset; + + }, + + /** + * Reset internal data/state. + * + * @method Phaser.ScaleManager#reset + * @private + */ + reset: function (clearWorld) { + + if (clearWorld && this.grid) + { + this.grid.reset(); + } + + }, + + /** + * Updates the width/height to that of the window. + * + * @method Phaser.ScaleManager#setMaximum + * @private + */ + setMaximum: function () { + + this.width = this.dom.visualBounds.width; + this.height = this.dom.visualBounds.height; + + }, + + /** + * Updates the width/height such that the game is scaled proportionally. + * + * @method Phaser.ScaleManager#setShowAll + * @private + * @param {boolean} expanding - If true then the maximizing dimension is chosen. + */ + setShowAll: function (expanding) { + + var bounds = this.getParentBounds(this._tempBounds); + var width = bounds.width; + var height = bounds.height; + + var multiplier; + + if (expanding) + { + multiplier = Math.max((height / this.game.height), (width / this.game.width)); + } + else + { + multiplier = Math.min((height / this.game.height), (width / this.game.width)); + } + + this.width = Math.round(this.game.width * multiplier); + this.height = Math.round(this.game.height * multiplier); + + }, + + /** + * Updates the width/height such that the game is stretched to the available size. + * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen. + * + * @method Phaser.ScaleManager#setExactFit + * @private + */ + setExactFit: function () { + + var bounds = this.getParentBounds(this._tempBounds); + + this.width = bounds.width; + this.height = bounds.height; + + if (this.isFullScreen) + { + // Max/min not honored fullscreen + return; + } + + if (this.maxWidth) + { + this.width = Math.min(this.width, this.maxWidth); + } + + if (this.maxHeight) + { + this.height = Math.min(this.height, this.maxHeight); + } + + }, + + /** + * Creates a fullscreen target. This is called automatically as as needed when entering + * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}. + * + * Use {@link #onFullScreenInit} to customize the created object. + * + * @method Phaser.ScaleManager#createFullScreenTarget + * @protected + */ + createFullScreenTarget: function () { + + var fsTarget = document.createElement('div'); + + fsTarget.style.margin = '0'; + fsTarget.style.padding = '0'; + fsTarget.style.background = '#000'; + + return fsTarget; + + }, + + /** + * Display the game in the browser's fullscreen mode. + * + * This _must_ be called from a user-input Pointer or Mouse event (and possibly a {@link https://www.chromestatus.com/feature/6131337345892352 "user gesture"}), e.g., + * + * - {@link Phaser.Events#onInputUp} + * - {@link Phaser.Input#onUp} or {@link Phaser.Input#onTap} + * - `click`, `mousedown`, `mouseup`, `pointerup`, or `touchend` + * + * Games within an iframe will also be blocked from fullscreen unless the iframe has the `allowfullscreen` attribute. + * + * The {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} must be {@link http://caniuse.com/#search=fullscreen supported by the browser} for this to work - it is not the same as setting + * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current + * device is reported to support fullscreen mode. + * + * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. + * + * Safari blocks access to keyboard events in fullscreen mode (as a security measure). + * + * @method Phaser.ScaleManager#startFullScreen + * @public + * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. + * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed. + * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) + */ + startFullScreen: function (antialias, allowTrampoline) { + + if (this.isFullScreen) + { + return false; + } + + if (!this.compatibility.supportsFullScreen) + { + // Error is called in timeout to emulate the real fullscreenerror event better + var _this = this; + + setTimeout(function () { + _this.fullScreenError(); + }, 10); + + return; + } + + if (this.compatibility.clickTrampoline === 'when-not-mouse') + { + var input = this.game.input; + + if (input.activePointer && + input.activePointer !== input.mousePointer && + (allowTrampoline || allowTrampoline !== false)) + { + input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]); + return; + } + } + + if (antialias !== undefined && this.game.renderType === Phaser.CANVAS) + { + this.game.stage.smoothed = antialias; + } + + var fsTarget = this.fullScreenTarget; + + if (!fsTarget) + { + this.cleanupCreatedTarget(); + + this._createdFullScreenTarget = this.createFullScreenTarget(); + fsTarget = this._createdFullScreenTarget; + } + + var initData = { + targetElement: fsTarget + }; + + this.hasPhaserSetFullScreen = true; + + this.onFullScreenInit.dispatch(this, initData); + + if (this._createdFullScreenTarget) + { + // Move the Display canvas inside of the target and add the target to the DOM + // (The target has to be added for the Fullscreen API to work.) + var canvas = this.game.canvas; + var parent = canvas.parentNode; + parent.insertBefore(fsTarget, canvas); + fsTarget.appendChild(canvas); + } + + if (this.game.device.fullscreenKeyboard) + { + fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT); + } + else + { + fsTarget[this.game.device.requestFullscreen](); + } + + return true; + + }, + + /** + * Stops / exits fullscreen mode, if active. + * + * @method Phaser.ScaleManager#stopFullScreen + * @public + * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. + */ + stopFullScreen: function () { + + if (!this.isFullScreen || !this.compatibility.supportsFullScreen) + { + return false; + } + + this.hasPhaserSetFullScreen = false; + + document[this.game.device.cancelFullscreen](); + + return true; + + }, + + /** + * Cleans up the previous fullscreen target, if such was automatically created. + * This ensures the canvas is restored to its former parent, assuming the target didn't move. + * + * @method Phaser.ScaleManager#cleanupCreatedTarget + * @private + */ + cleanupCreatedTarget: function () { + + var fsTarget = this._createdFullScreenTarget; + + if (fsTarget && fsTarget.parentNode) + { + // Make sure to cleanup synthetic target for sure; + // swap the canvas back to the parent. + var parent = fsTarget.parentNode; + parent.insertBefore(this.game.canvas, fsTarget); + parent.removeChild(fsTarget); + } + + this._createdFullScreenTarget = null; + + }, + + /** + * Used to prepare/restore extra fullscreen mode settings. + * (This does move any elements within the DOM tree.) + * + * @method Phaser.ScaleManager#prepScreenMode + * @private + * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_. + */ + prepScreenMode: function (enteringFullscreen) { + + var createdTarget = !!this._createdFullScreenTarget; + var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget; + + if (enteringFullscreen) + { + if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT) + { + // Resize target, as long as it's not the canvas + if (fsTarget !== this.game.canvas) + { + this._fullScreenRestore = { + targetWidth: fsTarget.style.width, + targetHeight: fsTarget.style.height + }; + + fsTarget.style.width = '100%'; + fsTarget.style.height = '100%'; + } + } + } + else + { + // Have restore information + if (this._fullScreenRestore) + { + fsTarget.style.width = this._fullScreenRestore.targetWidth; + fsTarget.style.height = this._fullScreenRestore.targetHeight; + + this._fullScreenRestore = null; + } + + // Always reset to game size + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.resetCanvas(); + } + + }, + + /** + * Called automatically when the browser enters of leaves fullscreen mode. + * + * @method Phaser.ScaleManager#fullScreenChange + * @private + * @param {Event} [event=undefined] - The fullscreenchange event + */ + fullScreenChange: function (event) { + + this.event = event; + + if (this.isFullScreen) + { + this.prepScreenMode(true); + + this.updateLayout(); + this.queueUpdate(true); + } + else + { + this.prepScreenMode(false); + + this.cleanupCreatedTarget(); + + this.updateLayout(); + this.queueUpdate(true); + } + + this.onFullScreenChange.dispatch(this, this.width, this.height); + + }, + + /** + * Called automatically when the browser fullscreen request fails; + * or called when a fullscreen request is made on a device for which it is not supported. + * + * @method Phaser.ScaleManager#fullScreenError + * @private + * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API. + */ + fullScreenError: function (event) { + + this.event = event; + + this.cleanupCreatedTarget(); + + console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API'); + + this.onFullScreenError.dispatch(this); + + }, + + /** + * Takes a Sprite or Image object and scales it to fit the given dimensions. + * Scaling happens proportionally without distortion to the sprites texture. + * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the + * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either + * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. + * + * @method Phaser.ScaleManager#scaleSprite + * @protected + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale. + * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. + * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. + * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. + * @return {Phaser.Sprite|Phaser.Image} The scaled sprite. + */ + scaleSprite: function (sprite, width, height, letterBox) { + + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + if (letterBox === undefined) { letterBox = false; } + + if (!sprite || !sprite['scale']) + { + return sprite; + } + + sprite.scale.x = 1; + sprite.scale.y = 1; + + if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0)) + { + return sprite; + } + + var scaleX1 = width; + var scaleY1 = (sprite.height * width) / sprite.width; + + var scaleX2 = (sprite.width * height) / sprite.height; + var scaleY2 = height; + + var scaleOnWidth = (scaleX2 > width); + + if (scaleOnWidth) + { + scaleOnWidth = letterBox; + } + else + { + scaleOnWidth = !letterBox; + } + + if (scaleOnWidth) + { + sprite.width = Math.floor(scaleX1); + sprite.height = Math.floor(scaleY1); + } + else + { + sprite.width = Math.floor(scaleX2); + sprite.height = Math.floor(scaleY2); + } + + // Enable at some point? + // sprite.x = Math.floor((width - sprite.width) / 2); + // sprite.y = Math.floor((height - sprite.height) / 2); + + return sprite; + + }, + + /** + * Destroys the ScaleManager and removes any event listeners. + * This should probably only be called when the game is destroyed. + * + * @method Phaser.ScaleManager#destroy + * @protected + */ + destroy: function () { + + this.game.onResume.remove(this._gameResumed, this); + + window.removeEventListener('orientationchange', this._orientationChange, false); + window.removeEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.removeEventListener('fullscreenchange', this._fullScreenChange, false); + + document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.removeEventListener('mozfullscreenerror', this._fullScreenError, false); + document.removeEventListener('MSFullscreenError', this._fullScreenError, false); + document.removeEventListener('fullscreenerror', this._fullScreenError, false); + } + + } + +}; + +Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager; + +/** +* The DOM element that is considered the Parent bounding element, if any. +* +* This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified. +* It will also be null if there is no game canvas or if the game canvas has no parent. +* +* @name Phaser.ScaleManager#boundingParent +* @property {?DOMElement} boundingParent +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", { + + get: function () { + + if (this.parentIsWindow || + (this.isFullScreen && this.hasPhaserSetFullScreen && !this._createdFullScreenTarget)) + { + return null; + } + + var parentNode = this.game.canvas && this.game.canvas.parentNode; + + return parentNode || null; + + } + +}); + +/** +* The scaling method used by the ScaleManager when not in fullscreen. +* +*
+*
{@link Phaser.ScaleManager.NO_SCALE}
+*
+* The Game display area will not be scaled - even if it is too large for the canvas/screen. +* This mode _ignores_ any applied scaling factor and displays the canvas at the Game size. +*
+*
{@link Phaser.ScaleManager.EXACT_FIT}
+*
+* The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen. +* Proportions are not maintained. +*
+*
{@link Phaser.ScaleManager.SHOW_ALL}
+*
+* Show the entire game display area while _maintaining_ the original aspect ratio. +*
+*
{@link Phaser.ScaleManager.RESIZE}
+*
+* The dimensions of the game display area are changed to match the size of the parent container. +* That is, this mode _changes the Game size_ to match the display size. +*

+* Any manually set Game size (see {@link #setGameSize}) is ignored while in effect. +*

+*
{@link Phaser.ScaleManager.USER_SCALE}
+*
+* The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}. +*

+* This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback} +* for flexible custom-sizing needs. +*

+*
+* +* @name Phaser.ScaleManager#scaleMode +* @property {integer} scaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", { + + get: function () { + + return this._scaleMode; + + }, + + set: function (value) { + + if (value !== this._scaleMode) + { + if (!this.isFullScreen) + { + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.queueUpdate(true); + } + + this._scaleMode = value; + } + + return this._scaleMode; + + } + +}); + +/** +* The scaling method used by the ScaleManager when in fullscreen. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#fullScreenScaleMode +* @property {integer} fullScreenScaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", { + + get: function () { + + return this._fullScreenScaleMode; + + }, + + set: function (value) { + + if (value !== this._fullScreenScaleMode) + { + // If in fullscreen then need a wee bit more work + if (this.isFullScreen) + { + this.prepScreenMode(false); + this._fullScreenScaleMode = value; + this.prepScreenMode(true); + + this.queueUpdate(true); + } + else + { + this._fullScreenScaleMode = value; + } + } + + return this._fullScreenScaleMode; + + } + +}); + +/** +* Returns the current scale mode - for normal or fullscreen operation. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#currentScaleMode +* @property {number} currentScaleMode +* @protected +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", { + + get: function () { + + return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode; + + } + +}); + +/** +* When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align horizontally across the page the Display canvas should be added directly to page; +* or the parent container should itself be horizontally aligned. +* +* Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignHorizontally +* @property {boolean} pageAlignHorizontally +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", { + + get: function () { + + return this._pageAlignHorizontally; + + }, + + set: function (value) { + + if (value !== this._pageAlignHorizontally) + { + this._pageAlignHorizontally = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain +* a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically +* _within_ the remaining available height dictated by the Parent element. +* +* One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. +* If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). +* +* _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height. +* To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true. +* +* Vertical alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignVertically +* @property {boolean} pageAlignVertically +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", { + + get: function () { + + return this._pageAlignVertically; + + }, + + set: function (value) { + + if (value !== this._pageAlignVertically) + { + this._pageAlignVertically = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* Returns true if the browser is in fullscreen mode, otherwise false. +* @name Phaser.ScaleManager#isFullScreen +* @property {boolean} isFullScreen +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", { + + get: function () { + return !!(document['fullscreenElement'] || + document['webkitFullscreenElement'] || + document['mozFullScreenElement'] || + document['msFullscreenElement']); + } + +}); + +/** +* Returns true if the screen orientation is in portrait mode. +* +* @name Phaser.ScaleManager#isPortrait +* @property {boolean} isPortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'portrait'; + } + +}); + +/** +* Returns true if the screen orientation is in landscape mode. +* +* @name Phaser.ScaleManager#isLandscape +* @property {boolean} isLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'landscape'; + } + +}); + +/** +* Returns true if the game dimensions are portrait (height > width). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGamePortrait +* @property {boolean} isGamePortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", { + + get: function () { + return (this.height > this.width); + } + +}); + +/** +* Returns true if the game dimensions are landscape (width > height). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGameLandscape +* @property {boolean} isGameLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", { + + get: function () { + return (this.width > this.height); + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of methods for displaying debug information about game objects. +* +* If your game is running in Canvas mode, then you should invoke all of the Debug methods from +* your games `render` function. This is because they are drawn directly onto the game canvas +* itself, so if you call any debug methods outside of `render` they are likely to be overwritten +* by the game itself. +* +* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture +* to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug +* in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! +* +* @class Phaser.Utils.Debug +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Utils.Debug = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Image} sprite - If debugging in WebGL mode, this is the Image displaying the debug {@link #bmd BitmapData}. + */ + this.sprite = null; + + /** + * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.context = null; + + /** + * @property {string} font - The font that the debug information is rendered in. + * @default + */ + this.font = '14px Courier'; + + /** + * @property {number} columnWidth - The spacing between columns. + * @default + */ + this.columnWidth = 100; + + /** + * @property {number} lineHeight - The line height between the debug text. + * @default + */ + this.lineHeight = 16; + + /** + * @property {number} lineWidth - The width of the stroke on lines and shapes. A positive number. + * @default + */ + this.lineWidth = 1; + + /** + * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. + * @default + */ + this.renderShadow = true; + + /** + * @property {string} currentColor - The color last set by {@link #start} or {@link #text}. + * @default + * @protected + */ + this.currentColor = null; + + /** + * @property {number} currentX - The current X position the debug information will be rendered at. + * @default + */ + this.currentX = 0; + + /** + * @property {number} currentY - The current Y position the debug information will be rendered at. + * @default + */ + this.currentY = 0; + + /** + * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it. + * @default + */ + this.currentAlpha = 1; + + /** + * @property {boolean} dirty - Does the canvas need re-rendering? + * @default + */ + this.dirty = false; + + /** + * @property {boolean} isDisabled - If `enableDebug: false` is passed to {@link Phaser.Game} or if Phaser is built without the Debug class, this will be true. + * @default + * @readonly + */ + this.isDisabled = false; + + /** + * @property {Phaser.Line} _line - A reusable rendering line. + * @private + */ + this._line = null; + + /** + * @property {Phaser.Rectangle} _rect - A reusable rendering rectangle. + * @private + */ + this._rect = null; + +}; + +Phaser.Utils.Debug.prototype = { + + /** + * Internal method that boots the debug displayer. + * + * @method Phaser.Utils.Debug#boot + * @protected + */ + boot: function () { + + if (this.game.renderType === Phaser.CANVAS) + { + this.context = this.game.context; + } + else + { + this.bmd = new Phaser.BitmapData(this.game, '__DEBUG', this.game.width, this.game.height, true); + this.sprite = this.game.make.image(0, 0, this.bmd); + this.game.stage.addChild(this.sprite); + + this.game.scale.onSizeChange.add(this.resize, this); + + this.canvas = Phaser.CanvasPool.create(this, this.game.width, this.game.height); + this.context = this.canvas.getContext('2d'); + } + + this._line = new Phaser.Line(); + this._rect = new Phaser.Rectangle(); + + }, + + /** + * Internal method that resizes the BitmapData and Canvas. + * Called by ScaleManager.onSizeChange only in WebGL mode. + * + * @method Phaser.Utils.Debug#resize + * @protected + */ + resize: function () { + + this.bmd.resize(this.game.width, this.game.height); + + this.canvas.width = this.game.width; + this.canvas.height = this.game.height; + + }, + + /** + * Internal method that clears the canvas (if a Sprite) ready for a new debug session. + * + * @method Phaser.Utils.Debug#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.dirty && this.sprite) + { + this.bmd.clear(); + this.bmd.draw(this.canvas, 0, 0); + + this.context.clearRect(0, 0, this.game.width, this.game.height); + this.dirty = false; + } + + }, + + /** + * Clears the Debug canvas. + * + * @method Phaser.Utils.Debug#reset + */ + reset: function () { + + if (this.context) + { + this.context.clearRect(0, 0, this.game.width, this.game.height); + } + + if (this.sprite) + { + this.bmd.clear(); + } + + }, + + /** + * Internal method that resets and starts the debug output values. + * + * @method Phaser.Utils.Debug#start + * @protected + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + * @param {number} [columnWidth=0] - The spacing between columns. + */ + start: function (x, y, color, columnWidth) { + + if (typeof x !== 'number') { x = 0; } + if (typeof y !== 'number') { y = 0; } + color = color || 'rgb(255,255,255)'; + if (columnWidth === undefined) { columnWidth = 0; } + + this.currentX = x; + this.currentY = y; + this.currentColor = color; + this.columnWidth = columnWidth; + + this.dirty = true; + + this.context.save(); + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.strokeStyle = color; + this.context.fillStyle = color; + this.context.font = this.font; + this.context.globalAlpha = this.currentAlpha; + + }, + + /** + * Internal method that stops the debug output. + * + * @method Phaser.Utils.Debug#stop + * @protected + */ + stop: function () { + + this.context.restore(); + + }, + + /** + * Internal method that outputs a single line of text split over as many columns as needed, one per parameter. + * + * @method Phaser.Utils.Debug#line + * @protected + */ + line: function () { + + var x = this.currentX; + + for (var i = 0; i < arguments.length; i++) + { + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(arguments[i], x + 1, this.currentY + 1); + this.context.fillStyle = this.currentColor; + } + + this.context.fillText(arguments[i], x, this.currentY); + + x += this.columnWidth; + } + + this.currentY += this.lineHeight; + + }, + + /** + * Render Sound Manager information, including volume, mute, audio mode, and locked status. + * + * @method Phaser.Utils.Debug#sound + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + sound: function (x, y, color) { + + var sound = this.game.sound; + + this.start(x, y, color); + + if (sound.noAudio) + { + this.line('Audio is disabled'); + } + else + { + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Mute on pause: ' + sound.muteOnPause); + this.line('Using: ' + (sound.usingWebAudio ? ('Web Audio - ' + sound.context.state) : 'Audio Tag')); + this.line('Touch locked: ' + sound.touchLocked); + } + + this.stop(); + + }, + + /** + * Render Sound information, including decoded state, duration, volume and more. + * + * @method Phaser.Utils.Debug#soundInfo + * @param {Phaser.Sound} sound - The sound object to debug. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + soundInfo: function (sound, x, y, color) { + + this.start(x, y, color); + this.line('Sound: ' + sound.key + ' Touch locked: ' + sound.game.sound.touchLocked); + this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback); + this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding); + this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying + ' Loop: ' + sound.loop); + this.line('Time: ' + sound.currentTime); + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Using: ' + (sound.usingWebAudio ? 'Web Audio' : 'Audio Tag')); + + if (sound.currentMarker !== '') + { + this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')'); + this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop); + this.line('Position: ' + sound.position); + } + + this.stop(); + + }, + + /** + * Marks the follow {@link #target} and {@link #deadzone}. + * + * @method Phaser.Utils.Debug#camera + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {string} [color] - Color of the debug shapes to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the shapes filled (default, true) or stroked (false). + */ + camera: function (camera, color, filled) { + + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + if (deadzone) + { + this._rect.setTo(view.x + deadzone.x, view.y + deadzone.y, deadzone.width, deadzone.height); + this.rectangle(this._rect, color, filled); + } + + if (target) + { + this._line.setTo(view.centerX, view.centerY, target.x, target.y); + this.geom(this._line, color, filled); + this.geom(target, color, false, 3); + } + + }, + + /** + * Render camera information including dimensions and location. + * + * @method Phaser.Utils.Debug#cameraInfo + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + cameraInfo: function (camera, x, y, color) { + + var bounds = camera.bounds; + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + this.start(x, y, color); + this.line('Camera (' + camera.width + ' x ' + camera.height + ')'); + this.line('x: ' + camera.x + ' y: ' + camera.y); + this.line('Bounds: ' + (bounds ? ('x: ' + bounds.x + ' y: ' + bounds.y + ' w: ' + bounds.width + ' h: ' + bounds.height) : 'none')); + this.line('View: x: ' + view.x + ' y: ' + view.y + ' w: ' + view.width + ' h: ' + view.height); + this.line('Deadzone: ' + (deadzone ? ('x: ' + deadzone.x + ' y: ' + deadzone.y + ' w: ' + deadzone.width + ' h: ' + deadzone.height) : deadzone)); + this.line('Total in view: ' + camera.totalInView); + this.line('At limit: x: ' + camera.atLimit.x + ' y: ' + camera.atLimit.y); + this.line('Target: ' + (target ? (target.name || target) : 'none')); + this.stop(); + + }, + + /** + * Render Timer information. + * + * @method Phaser.Utils.Debug#timer + * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + timer: function (timer, x, y, color) { + + this.start(x, y, color); + this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')'); + this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration); + this.line('Paused: ' + timer.paused + ' Length: ' + timer.length); + this.stop(); + + }, + + /** + * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text. + * + * @method Phaser.Utils.Debug#pointer + * @param {Phaser.Pointer} pointer - The Pointer you wish to display. + * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. + * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down. + * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false). + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + pointer: function (pointer, hideIfUp, downColor, upColor, color) { + + if (pointer == null) + { + return; + } + + if (hideIfUp === undefined) { hideIfUp = false; } + downColor = downColor || 'rgba(0,255,0,0.5)'; + upColor = upColor || 'rgba(255,0,0,0.5)'; + + if (hideIfUp === true && pointer.isUp === true) + { + return; + } + + this.start(pointer.x, pointer.y - 100, color); + this.context.beginPath(); + this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2); + + if (pointer.active) + { + this.context.fillStyle = downColor; + } + else + { + this.context.fillStyle = upColor; + } + + this.context.fill(); + this.context.closePath(); + + // Render the points + this.context.beginPath(); + this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y); + this.context.lineTo(pointer.position.x, pointer.position.y); + this.context.lineWidth = 2; + this.context.stroke(); + this.context.closePath(); + + // Render the text + this.line('ID: ' + pointer.id + " Active: " + pointer.active); + this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY); + this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y + " In: " + pointer.withinGame); + this.line('Duration: ' + pointer.duration + " ms"); + this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp); + this.stop(); + + }, + + /** + * Render Sprite Input Debug information. + * + * @method Phaser.Utils.Debug#spriteInputInfo + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInputInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')'); + this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1)); + this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0)); + this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0)); + this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut()); + this.stop(); + + }, + + /** + * Renders Phaser.Key object information. + * + * @method Phaser.Utils.Debug#key + * @param {Phaser.Key} key - The Key to render the information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + key: function (key, x, y, color) { + + this.start(x, y, color, 150); + + this.line('Key:', key.keyCode, 'isDown:', key.isDown); + this.line('justDown:', key.justDown, 'justUp:', key.justUp); + this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0)); + + this.stop(); + + }, + + /** + * Render debug information about the Input object. + * + * @method Phaser.Utils.Debug#inputInfo + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + inputInfo: function (x, y, color) { + + this.start(x, y, color); + this.line('Input'); + this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y); + this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY); + this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1)); + this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY); + this.stop(); + + }, + + /** + * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! + * + * @method Phaser.Utils.Debug#spriteBounds + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + spriteBounds: function (sprite, color, filled) { + + var bounds = sprite.getBounds(); + + bounds.x += this.game.camera.x; + bounds.y += this.game.camera.y; + + this.rectangle(bounds, color, filled); + + }, + + /** + * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it + * + * @method Phaser.Utils.Debug#ropeSegments + * @param {Phaser.Rope} rope - The rope to display the segments of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + ropeSegments: function (rope, color, filled) { + + var segments = rope.segments; + + var self = this; + + segments.forEach(function(segment) { + self.rectangle(segment, color, filled); + }, this); + + }, + + /** + * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. + * + * @method Phaser.Utils.Debug#spriteInfo + * @param {Phaser.Sprite} sprite - The Sprite to display the information of. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + + this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y); + this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1)); + this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1)); + this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera); + this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1)); + + this.stop(); + + }, + + /** + * Renders the sprite coordinates in local, positional and world space. + * + * @method Phaser.Utils.Debug#spriteCoords + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteCoords: function (sprite, x, y, color) { + + this.start(x, y, color, 100); + + if (sprite.name) + { + this.line(sprite.name); + } + + this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2)); + this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2)); + this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2)); + + this.stop(); + + }, + + /** + * Renders Line information in the given color. + * + * @method Phaser.Utils.Debug#lineInfo + * @param {Phaser.Line} line - The Line to display the data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + lineInfo: function (line, x, y, color) { + + this.start(x, y, color, 80); + this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2)); + this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2)); + this.line('length:', line.length.toFixed(2), 'angle:', line.angle); + this.stop(); + + }, + + /** + * Renders a single pixel at the given size. + * + * @method Phaser.Utils.Debug#pixel + * @param {number} x - X position of the pixel to be rendered. + * @param {number} y - Y position of the pixel to be rendered. + * @param {string} [color] - Color of the pixel (format is css color string). + * @param {number} [size=2] - The 'size' to render the pixel at. + */ + pixel: function (x, y, color, size) { + + size = size || 2; + + this.start(); + this.context.fillStyle = color; + this.context.fillRect(x, y, size, size); + this.stop(); + + }, + + /** + * Renders a Phaser geometry object including Rectangle, Circle, Ellipse, Point or Line. + * + * @method Phaser.Utils.Debug#geom + * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Ellipse|Phaser.Point|Phaser.Line} object - The geometry object to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) + * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle,3 = Point, 4 = Line and 5 = Ellipse. + */ + geom: function (object, color, filled, forceType) { + + if (filled === undefined) { filled = true; } + if (forceType === undefined) { forceType = 0; } + + color = color || 'rgba(0,255,0,0.4)'; + + this.start(); + + this.context.fillStyle = color; + this.context.strokeStyle = color; + this.context.lineWidth = this.lineWidth; + + if (object instanceof Phaser.Rectangle || forceType === 1) + { + if (filled) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + } + else if (object instanceof Phaser.Circle || forceType === 2) + { + this.context.beginPath(); + this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + else if (object instanceof Phaser.Point || forceType === 3) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4); + } + else if (object instanceof Phaser.Line || forceType === 4) + { + this.context.beginPath(); + this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y); + this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y); + this.context.closePath(); + this.context.stroke(); + } + else if (object instanceof Phaser.Ellipse || forceType === 5) + { + this.context.beginPath(); + this.context.ellipse(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width/2, object.height/2, 0,2 * Math.PI,false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + + this.stop(); + + }, + + /** + * Renders a Rectangle. + * + * @method Phaser.Utils.Debug#rectangle + * @param {Phaser.Rectangle|object} object - The rectangle to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as filled (default, true) or a stroked (false) + */ + rectangle: function (object, color, filled) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0, 255, 0, 0.4)'; + + this.start(); + + if (filled) + { + this.context.fillStyle = color; + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.lineWidth = this.lineWidth; + this.context.strokeStyle = color; + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + + this.stop(); + + }, + + /** + * Render a string of text. + * + * @method Phaser.Utils.Debug#text + * @param {string} text - The line of text to draw. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {string} [font] - The font of text to draw. + */ + text: function (text, x, y, color, font) { + + color = color || 'rgb(255,255,255)'; + font = font || '16px Courier'; + + this.start(); + this.context.font = font; + + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(text, x + 1, y + 1); + } + + this.context.fillStyle = color; + this.context.fillText(text, x, y); + + this.stop(); + + }, + + /** + * Visually renders a QuadTree to the display. + * + * @method Phaser.Utils.Debug#quadTree + * @param {Phaser.QuadTree} quadtree - The quadtree to render. + * @param {string} color - The color of the lines in the quadtree. + */ + quadTree: function (quadtree, color) { + + color = color || 'rgba(255,0,0,0.3)'; + + this.start(); + + var bounds = quadtree.bounds; + + if (quadtree.nodes.length === 0) + { + this.context.strokeStyle = color; + this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height); + this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier'); + + this.context.strokeStyle = 'rgb(0,255,0)'; + + for (var i = 0; i < quadtree.objects.length; i++) + { + this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height); + } + } + else + { + for (var i = 0; i < quadtree.nodes.length; i++) + { + this.quadTree(quadtree.nodes[i]); + } + } + + this.stop(); + + }, + + /** + * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. + * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. + * To display a P2 Physics body you should enable debug mode on the body when creating it. + * + * @method Phaser.Utils.Debug#body + * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false) + */ + body: function (sprite, color, filled) { + + if (sprite.body) + { + this.start(); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled, this.lineWidth); + } + else if (sprite.body.type === Phaser.Physics.NINJA) + { + Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color); + } + + this.stop(); + } + + }, + + /** + * Render a Sprites Physic Body information. + * + * @method Phaser.Utils.Debug#bodyInfo + * @param {Phaser.Sprite} sprite - The sprite to be rendered. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + bodyInfo: function (sprite, x, y, color) { + + if (sprite.body) + { + this.start(x, y, color, 210); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + this.game.physics.box2d.renderBodyInfo(this, sprite.body); + } + + this.stop(); + } + + }, + + /** + * Renders 'debug draw' data for the Box2D world if it exists. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by + * the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dWorld + */ + box2dWorld: function () { + + this.start(); + + this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0); + this.game.physics.box2d.renderDebugDraw(this.context); + + this.stop(); + + }, + + /** + * Renders 'debug draw' data for the given Box2D body. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dBody + * @param {Phaser.Physics.Box2D.Body} body - The body to be rendered. + * @param {string} [color='rgb(0,255,0)'] - Color of the rendering (format is css color string). + */ + box2dBody: function (body, color) { + + this.start(); + Phaser.Physics.Box2D.renderBody(this.context, body, color); + this.stop(); + + }, + + /** + * Call this function from the Dev Tools console. + * + * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. + * + * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) + * + * @method Phaser.Utils.Debug#displayList + * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World. + */ + displayList: function (displayObject) { + + if (displayObject === undefined) { displayObject = this.game.world; } + + if (displayObject.hasOwnProperty('renderOrderID')) + { + console.log('[' + displayObject.renderOrderID + ']', displayObject); + } + else + { + console.log('[]', displayObject); + } + + if (displayObject.children && displayObject.children.length > 0) + { + for (var i = 0; i < displayObject.children.length; i++) + { + this.game.debug.displayList(displayObject.children[i]); + } + } + + }, + + /** + * Prints a description of the {@link Phaser.Game#renderer renderer} and render session. + * + * @method Phaser.Utils.Debug#renderer + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + renderer: function (x, y, color) { + + var r = this.game.renderer; + var s = r.renderSession; + + this.start(x, y, color); + + this.line((r.gl ? 'WebGL' : 'Canvas') + ' Renderer (' + r.width + ' x ' + r.height + ')'); + this.line('autoResize: ' + r.autoResize); + this.line('clearBeforeRender: ' + r.clearBeforeRender); + this.line('resolution: ' + r.resolution); + this.line('transparent: ' + r.transparent); + this.line('renderSession:'); + + if (r.gl) + { + this.line(' currentBatchedTextures: ('+ r.currentBatchedTextures.length + ')'); + + for (var i = 0; i < r.currentBatchedTextures.length; i++) + { + this.line(' ' + r.currentBatchedTextures[i]); + } + + this.line(' drawCount: ' + s.drawCount); + this.line(' maxTextures: ' + r.maxTextures); + this.line(' maxTextureSize: ' + r.maxTextureSize); + this.line(' maxTextureAvailableSpace: ' + s.maxTextureAvailableSpace); + this.line(' roundPixels: ' + s.roundPixels); + } + else + { + this.line(' roundPixels: ' + s.roundPixels); + this.line(' scaleMode: ' + (s.scaleMode === 0 ? 'LINEAR' : (s.scaleMode === 1 ? 'NEAREST' : s.scaleMode))); + } + + this.stop(); + + }, + + canvasPool: function (x, y, color, columnWidth) { + var pool = Phaser.CanvasPool; + + this.start(x, y, color, columnWidth || 100); + this.line('Canvas Pool'); + this.line('Used:', pool.getTotal()); + this.line('Free:', pool.getFree()); + this.line('Total:', pool.length); + this.stop(); + }, + + /** + * Render each physics {@link #body} in a group. + * + * @method Phaser.Utils.Debug#physicsGroup + * @param {Phaser.Group} group - A group containing physics-enabled sprites. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false). + * @param {boolean} [checkExists=false] Render only children with `exists=true`. + */ + physicsGroup: function (group, color, filled, checkExists) { + + group.forEach(this.body, this, checkExists, color, filled); + + }, + + /** + * Prints Phaser {@link Phaser.VERSION version}, {@link Phaser.Game.#renderType rendering mode}, and {@link Phaser.Device#webAudio device audio support}. + * + * @method Phaser.Utils.Debug#phaser + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + phaser: function (x, y, color) { + + this.text('Phaser v' + Phaser.VERSION + ' ' + + (this.game.renderType === Phaser.WEBGL ? 'WebGL' : 'Canvas') + ' ' + + (this.game.device.webAudio ? 'WebAudio' : 'HTML Audio'), + x, y, color, this.font); + + }, + + /** + * Prints game/canvas dimensions and {@link Phaser.ScaleManager game scale} settings. + * + * @method Phaser.Utils.Debug#scale + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + scale: function (x, y, color) { + + this.start(x, y, color); + + var scale = this.game.scale; + var factor = scale.scaleFactorInversed; + var bounds = scale._parentBounds; + var x = ' x '; + + this.line('Game: ' + this.game.width + x + this.game.height); + this.line('Canvas: ' + scale.width + x + scale.height + + ' (' + factor.x.toFixed(2) + x + factor.y.toFixed(2) + ')' + + ' [' + scale.aspectRatio.toFixed(2) + ']'); + this.line('Mode: ' + Phaser.ScaleManager.MODES[scale.currentScaleMode] + + (scale.currentScaleMode === Phaser.ScaleManager.USER_SCALE ? + (' (' + scale._userScaleFactor.x + x + scale._userScaleFactor.y + ')') : + '')); + this.line('Parent: ' + (scale.parentIsWindow ? 'window' : scale.parentNode) + + (bounds.empty ? '' : (' (' + bounds.width + x + bounds.height + ')'))); + this.line('Screen: ' + scale.classifyOrientation(scale.screenOrientation) + + (scale.incorrectOrientation ? ' (incorrect)' : '')); + + this.stop(); + + }, + + /** + * Prints the progress of a {@link Phaser.Loader}. + * + * Typically you would call this within a {@link State#loadRender} callback and pass `game.load` ({@link Phaser.Game#load}). + * + * You can enable {@link Phaser.Loader#resetLocked} to temporarily hold the loader in its 'complete' state. + * Just remember to disable it before restarting the loader (such as when changing states). + * + * @method Phaser.Utils.Debug#loader + * @param {Phaser.Loader} loader - The loader. Usually `game.load` ({@link Phaser.Game#load}). + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + loader: function (loader, x, y, color) { + + var pad = Phaser.Utils.pad; + + this.start(x, y, color); + + if (loader.hasLoaded) + { + this.line('Complete' + (loader.resetLocked ? ' [locked]' : '')); + } + else if (loader.isLoading) + { + this.line('Loading'); + } + else + { + this.line('Not started'); + } + + if (!loader.hasLoaded || loader.resetLocked) + { + this.line('Progress: ' + (pad(loader.progress, 3) + '%')); + this.line('Files: ' + loader._loadedFileCount + ' of ' + + loader._totalFileCount); + this.line('Packs: ' + loader._loadedPackCount + ' of ' + + loader._loadedPackCount); + } + + this.stop(); + + }, + + /** + * Destroy this object. + * + * @method Phaser.Utils.Debug#destroy + */ + destroy: function () { + + Phaser.CanvasPool.remove(this); + + } + +}; + +Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DOM utility class. +* +* Provides a useful Window and Element functions as well as cross-browser compatibility buffer. +* +* Some code originally derived from {@link https://github.com/ryanve/verge verge}. +* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. +* +* @class Phaser.DOM +* @static +*/ +Phaser.DOM = { + + /** + * Get the [absolute] position of the element relative to the Document. + * + * The value may vary slightly as the page is scrolled due to rounding errors. + * + * @method Phaser.DOM.getOffset + * @param {DOMElement} element - The targeted element that we want to retrieve the offset. + * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. + * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. + */ + getOffset: function (element, point) { + + point = point || new Phaser.Point(); + + var box = element.getBoundingClientRect(); + + var scrollTop = Phaser.DOM.scrollY; + var scrollLeft = Phaser.DOM.scrollX; + var clientTop = document.documentElement.clientTop; + var clientLeft = document.documentElement.clientLeft; + + point.x = box.left + scrollLeft - clientLeft; + point.y = box.top + scrollTop - clientTop; + + return point; + + }, + + /** + * A cross-browser element.getBoundingClientRect method with optional cushion. + * + * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. + * Its properties match the native rectangle. + * The cushion parameter is an amount of pixels (+/-) to cushion the element. + * It adjusts the measurements such that it is possible to detect when an element is near the viewport. + * + * @method Phaser.DOM.getBounds + * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for. + * @param {number} [cushion] - A +/- pixel adjustment amount. + * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. + */ + getBounds: function (element, cushion) { + + if (cushion === undefined) { cushion = 0; } + + element = element && !element.nodeType ? element[0] : element; + + if (!element || element.nodeType !== 1) + { + return false; + } + else + { + return this.calibrate(element.getBoundingClientRect(), cushion); + } + + }, + + /** + * Calibrates element coordinates for `inLayoutViewport` checks. + * + * @method Phaser.DOM.calibrate + * @private + * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}` + * @param {number} [cushion] - A value to adjust the coordinates by. + * @return {object} The calibrated element coordinates + */ + calibrate: function (coords, cushion) { + + cushion = +cushion || 0; + + var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 }; + + output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion); + output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion); + + return output; + + }, + + /** + * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) + * + * @method Phaser.DOM.getAspectRatio + * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. + * @return {number} The aspect ratio. + */ + getAspectRatio: function (object) { + + object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object; + + var w = object['width']; + var h = object['height']; + + if (typeof w === 'function') + { + w = w.call(object); + } + + if (typeof h === 'function') + { + h = h.call(object); + } + + return w / h; + + }, + + /** + * Tests if the given DOM element is within the Layout viewport. + * + * The optional cushion parameter allows you to specify a distance. + * + * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. + * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. + * + * @method Phaser.DOM.inLayoutViewport + * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas. + * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport. + * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it. + */ + inLayoutViewport: function (element, cushion) { + + var r = this.getBounds(element, cushion); + + return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height; + + }, + + /** + * Returns the device screen orientation. + * + * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. + * + * Order of resolving: + * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. + * - Screen size ratio check - If fallback is 'screen', suited for desktops. + * - Viewport size ratio check - If fallback is 'viewport', suited for mobile. + * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. + * - Media query + * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..) + * + * See + * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) + * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) + * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx + * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries + * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation + * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation + * + * @method Phaser.DOM.getScreenOrientation + * @protected + * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'. + */ + getScreenOrientation: function (primaryFallback) { + + var screen = window.screen; + var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; + + if (orientation && typeof orientation.type === 'string') + { + // Screen Orientation API specification + return orientation.type; + } + else if (typeof orientation === 'string') + { + // moz/ms-orientation are strings + return orientation; + } + + var PORTRAIT = 'portrait-primary'; + var LANDSCAPE = 'landscape-primary'; + + if (primaryFallback === 'screen') + { + return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'viewport') + { + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number') + { + // This may change by device based on "natural" orientation. + return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE; + } + else if (window.matchMedia) + { + if (window.matchMedia("(orientation: portrait)").matches) + { + return PORTRAIT; + } + else if (window.matchMedia("(orientation: landscape)").matches) + { + return LANDSCAPE; + } + } + + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + + }, + + /** + * The bounds of the Visual viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one} + * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers. + * + * Supported mobile: + * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} x - Scroll, left offset - eg. "scrollX" + * @property {number} y - Scroll, top offset - eg. "scrollY" + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + visualBounds: new Phaser.Rectangle(), + + /** + * The bounds of the Layout viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two}; + * but honoring the constraints as specified applicable viewport meta-tag. + * + * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see + * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}). + * + * This is _not_ representative of the Visual bounds: in particular the non-primary axis will + * generally be significantly larger than the screen height on mobile devices when running with a + * constrained viewport. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + layoutBounds: new Phaser.Rectangle(), + + /** + * The size of the document / Layout viewport. + * + * This incorrectly reports the dimensions in IE. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Document width in pixels. + * @property {number} height - Document height in pixels. + * @readonly + */ + documentBounds: new Phaser.Rectangle() + +}; + +Phaser.Device.whenReady(function (device) { + + // All target browsers should support page[XY]Offset. + var scrollX = window && ('pageXOffset' in window) ? + function () { return window.pageXOffset; } : + function () { return document.documentElement.scrollLeft; }; + + var scrollY = window && ('pageYOffset' in window) ? + function () { return window.pageYOffset; } : + function () { return document.documentElement.scrollTop; }; + + /** + * A cross-browser window.scrollX. + * + * @name Phaser.DOM.scrollX + * @property {number} scrollX + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollX", { + get: scrollX + }); + + /** + * A cross-browser window.scrollY. + * + * @name Phaser.DOM.scrollY + * @property {number} scrollY + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollY", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "x", { + get: scrollX + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "y", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "y", { + value: 0 + }); + + var treatAsDesktop = device.desktop && + (document.documentElement.clientWidth <= window.innerWidth) && + (document.documentElement.clientHeight <= window.innerHeight); + + // Desktop browsers align the layout viewport with the visual viewport. + // This differs from mobile browsers with their zooming design. + // Ref. http://quirksmode.org/mobile/tableViewport.html + if (treatAsDesktop) + { + + // PST- When scrollbars are not included this causes upstream issues in ScaleManager. + // So reverted to the old "include scrollbars." + var clientWidth = function () { + return Math.max(window.innerWidth, document.documentElement.clientWidth); + }; + var clientHeight = function () { + return Math.max(window.innerHeight, document.documentElement.clientHeight); + }; + + // Interested in area sans-scrollbar + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: clientHeight + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + get: clientHeight + }); + + } else { + + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: function () { + return window.innerWidth; + } + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: function () { + return window.innerHeight; + } + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + + get: function () { + var a = document.documentElement.clientWidth; + var b = window.innerWidth; + + return a < b ? b : a; // max + } + + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + + get: function () { + var a = document.documentElement.clientHeight; + var b = window.innerHeight; + + return a < b ? b : a; // max + } + + }); + + } + + // For Phaser.DOM.documentBounds + // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html + + Object.defineProperty(Phaser.DOM.documentBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "y", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "width", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth); + } + + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "height", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight); + } + + }); + +}, null, true); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* ArraySet is a Set data structure (items must be unique within the set) that also maintains order. +* This allows specific items to be easily added or removed from the Set. +* +* Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. +* +* This used primarily by the Input subsystem. +* +* @class Phaser.ArraySet +* @constructor +* @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet. +*/ +Phaser.ArraySet = function (list) { + + /** + * Current cursor position as established by `first` and `next`. + * @property {integer} position + * @default + */ + this.position = 0; + + /** + * The backing array. + * @property {any[]} list + */ + this.list = list || []; + +}; + +Phaser.ArraySet.prototype = { + + /** + * Adds a new element to the end of the list. + * If the item already exists in the list it is not moved. + * + * @method Phaser.ArraySet#add + * @param {any} item - The element to add to this list. + * @return {any} The item that was added. + */ + add: function (item) { + + if (!this.exists(item)) + { + this.list.push(item); + } + + return item; + + }, + + /** + * Gets the index of the item in the list, or -1 if it isn't in the list. + * + * @method Phaser.ArraySet#getIndex + * @param {any} item - The element to get the list index for. + * @return {integer} The index of the item or -1 if not found. + */ + getIndex: function (item) { + + return this.list.indexOf(item); + + }, + + /** + * Gets an item from the set based on the property strictly equaling the value given. + * Returns null if not found. + * + * @method Phaser.ArraySet#getByKey + * @param {string} property - The property to check against the value. + * @param {any} value - The value to check if the property strictly equals. + * @return {any} The item that was found, or null if nothing matched. + */ + getByKey: function (property, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i][property] === value) + { + return this.list[i]; + } + } + + return null; + + }, + + /** + * Checks for the item within this list. + * + * @method Phaser.ArraySet#exists + * @param {any} item - The element to get the list index for. + * @return {boolean} True if the item is found in the list, otherwise false. + */ + exists: function (item) { + + return (this.list.indexOf(item) > -1); + + }, + + /** + * Removes all the items. + * + * @method Phaser.ArraySet#reset + */ + reset: function () { + + this.list.length = 0; + + }, + + /** + * Removes the given element from this list if it exists. + * + * @method Phaser.ArraySet#remove + * @param {any} item - The item to be removed from the list. + * @return {any} item - The item that was removed. + */ + remove: function (item) { + + var idx = this.list.indexOf(item); + + if (idx > -1) + { + this.list.splice(idx, 1); + return item; + } + + }, + + /** + * Sets the property `key` to the given value on all members of this list. + * + * @method Phaser.ArraySet#setAll + * @param {any} key - The property of the item to set. + * @param {any} value - The value to set the property to. + */ + setAll: function (key, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + this.list[i][key] = value; + } + } + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * + * If the `key` property is present it must be a function. + * The function is invoked using the item as the context. + * + * @method Phaser.ArraySet#callAll + * @param {string} key - The name of the property with the function to call. + * @param {...*} parameter - Additional parameters that will be passed to the callback. + */ + callAll: function (key) { + + var args = Array.prototype.slice.call(arguments, 1); + + var i = this.list.length; + + while (i--) + { + if (this.list[i] && this.list[i][key]) + { + this.list[i][key].apply(this.list[i], args); + } + } + + }, + + /** + * Removes every member from this ArraySet and optionally destroys it. + * + * @method Phaser.ArraySet#removeAll + * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set. + */ + removeAll: function (destroy) { + + if (destroy === undefined) { destroy = false; } + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + var item = this.remove(this.list[i]); + + if (destroy) + { + item.destroy(); + } + } + } + + this.position = 0; + this.list = []; + + } + +}; + +/** +* Number of items in the ArraySet. Same as `list.length`. +* +* @name Phaser.ArraySet#total +* @property {integer} total +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "total", { + + get: function () { + return this.list.length; + } + +}); + +/** +* Returns the first item and resets the cursor to the start. +* +* @name Phaser.ArraySet#first +* @property {any} first +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "first", { + + get: function () { + + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + + } + +}); + +/** +* Returns the the next item (based on the cursor) and advances the cursor. +* +* @name Phaser.ArraySet#next +* @property {any} next +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "next", { + + get: function () { + + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + + } + +}); + +Phaser.ArraySet.prototype.constructor = Phaser.ArraySet; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Utility functions for dealing with Arrays. +* +* @class Phaser.ArrayUtils +* @static +*/ +Phaser.ArrayUtils = { + + /** + * Fetch a random entry from the given array. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.getRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was selected. + */ + getRandomItem: function (objects, startIndex, length) { + + if (objects === null) { return null; } + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + + return objects[randomIndex] === undefined ? null : objects[randomIndex]; + + }, + + /** + * Removes a random object from the given array and returns it. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.removeRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was removed. + */ + removeRandomItem: function (objects, startIndex, length) { + + if (objects == null) { // undefined or null + return null; + } + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + if (randomIndex < objects.length) + { + var removed = objects.splice(randomIndex, 1); + return removed[0] === undefined ? null : removed[0]; + } + else + { + return null; + } + + }, + + /** + * Remove one or more items at the given index and reorder the array. + * + * The new array length will be `array.length - count`. + * + * This is an alternative to `array.splice(startIndex, count)`. + * + * @see https://github.com/mreinstein/remove-array-items + * @see https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ + * + * @method Phaser.ArrayUtils.remove + * @param {any[]} array + * @param {integer} startIndex + * @param {integer} [count=1] + * @return {any[]} The modified array. + */ + remove: function (array, startIndex, count) + { + var length = array.length; + + if (startIndex >= length || count === 0) { return; } + + if (count == null) { count = 1; } + + var newLength = length - count; + + for (var i = startIndex; i < newLength; ++i) + { + array[i] = array[i + count]; + } + + array.length = newLength; + }, + + /** + * A standard Fisher-Yates Array shuffle implementation which modifies the array in place. + * + * @method Phaser.ArrayUtils.shuffle + * @param {any[]} array - The array to shuffle. + * @return {any[]} The original array, now shuffled. + */ + shuffle: function (array) { + + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; + + }, + + /** + * Transposes the elements of the given matrix (array of arrays). + * + * @method Phaser.ArrayUtils.transposeMatrix + * @param {Array} array - The matrix to transpose. + * @return {Array} A new transposed matrix + */ + transposeMatrix: function (array) { + + var sourceRowCount = array.length; + var sourceColCount = array[0].length; + + var result = new Array(sourceColCount); + + for (var i = 0; i < sourceColCount; i++) + { + result[i] = new Array(sourceRowCount); + + for (var j = sourceRowCount - 1; j > -1; j--) + { + result[i][j] = array[j][i]; + } + } + + return result; + + }, + + /** + * Rotates the given matrix (array of arrays). + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @method Phaser.ArrayUtils.rotateMatrix + * @param {Array} matrix - The array to rotate; this matrix _may_ be altered. + * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). + * @return {Array} The rotated matrix. The source matrix should be discarded for the returned matrix. + */ + rotateMatrix: function (matrix, direction) { + + if (typeof direction !== 'string') + { + direction = ((direction % 360) + 360) % 360; + } + + if (direction === 90 || direction === -270 || direction === 'rotateLeft') + { + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + matrix = matrix.reverse(); + } + else if (direction === -90 || direction === 270 || direction === 'rotateRight') + { + matrix = matrix.reverse(); + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + } + else if (Math.abs(direction) === 180 || direction === 'rotate180') + { + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + matrix = matrix.reverse(); + } + + return matrix; + + }, + + /** + * Snaps a value to the nearest value in a sorted numeric array. + * The result will always be in the range `[first_value, last_value]`. + * + * @method Phaser.ArrayUtils.findClosest + * @param {number} value - The search value + * @param {number[]} arr - The input array which _must_ be sorted. + * @return {number} The nearest value found. + */ + findClosest: function (value, arr) { + + if (!arr.length) + { + return NaN; + } + else if (arr.length === 1 || value < arr[0]) + { + return arr[0]; + } + + var i = 1; + while (arr[i] < value) { + i++; + } + + var low = arr[i - 1]; + var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; + + return ((high - value) <= (value - low)) ? high : low; + + }, + + /** + * Moves the element from the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ F, A, B, C, D, E ]` + * + * See also Phaser.ArrayUtils.rotateLeft. + * + * @method Phaser.ArrayUtils.rotateRight + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The shifted value. + */ + rotateRight: function (array) { + + var s = array.pop(); + array.unshift(s); + + return s; + + }, + + /** + * Moves the element from the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ B, C, D, E, F, A ]` + * + * See also Phaser.ArrayUtils.rotateRight + * + * @method Phaser.ArrayUtils.rotateLeft + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The rotated value. + */ + rotateLeft: function (array) { + + var s = array.shift(); + array.push(s); + + return s; + + }, + + /** + * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]` (or `[0, start]`, if `end` is omitted). + * This is equivalent to `numberArrayStep(start, 1 + end, 1)`. + * + * When exactly one argument is passed, it's used as `end` and 0 is used as `start`. The length of the result is (1 + end). + * + * ##### Examples + * + * ```javascript + * numberArray(3); // -> [0, 1, 2, 3] + * numberArray(0, 3); // -> [0, 1, 2, 3] + * numberArray(1, 3); // -> [1, 2, 3] + * ``` + * + * @method Phaser.ArrayUtils.numberArray + * @param {number} start - The minimum value the array starts with. + * @param {number} [end] - The maximum value the array contains. + * @return {number[]} The array of number values. + */ + numberArray: function (start, end) { + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + var result = []; + + for (var i = start; i <= end; i++) + { + result.push(i); + } + + return result; + + }, + + /** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @method Phaser.ArrayUtils.numberArrayStep + * @param {number} start - The start of the range. + * @param {number} [end] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * @returns {Array} Returns the new array of numbers. + * @example + * Phaser.ArrayUtils.numberArrayStep(4); + * // => [0, 1, 2, 3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * Phaser.ArrayUtils.numberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * Phaser.ArrayUtils.numberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * Phaser.ArrayUtils.numberArrayStep(0); + * // => [] + */ + numberArrayStep: function (start, end, step) { + + if (start === undefined || start === null) { start = 0; } + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + if (step === undefined) { step = 1; } + + var result = []; + var total = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0); + + for (var i = 0; i < total; i++) + { + result.push(start); + start += step; + } + + return result; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A basic Linked List data structure. +* +* This implementation _modifies_ the `prev` and `next` properties of each item added: +* - The `prev` and `next` properties must be writable and should not be used for any other purpose. +* - Items _cannot_ be added to multiple LinkedLists at the same time. +* - Only objects can be added. +* +* @class Phaser.LinkedList +* @constructor +*/ +Phaser.LinkedList = function () { + + /** + * Next element in the list. + * @property {object} next + * @default + */ + this.next = null; + + /** + * Previous element in the list. + * @property {object} prev + * @default + */ + this.prev = null; + + /** + * First element in the list. + * @property {object} first + * @default + */ + this.first = null; + + /** + * Last element in the list. + * @property {object} last + * @default + */ + this.last = null; + + /** + * Number of elements in the list. + * @property {integer} total + * @default + */ + this.total = 0; + +}; + +Phaser.LinkedList.prototype = { + + /** + * Adds a new element to this linked list. + * + * @method Phaser.LinkedList#add + * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. + * @return {object} The item that was added. + */ + add: function (item) { + + // If the list is empty + if (this.total === 0 && this.first === null && this.last === null) + { + this.first = item; + this.last = item; + this.next = item; + item.prev = this; + this.total++; + return item; + } + + // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list) + this.last.next = item; + + item.prev = this.last; + + this.last = item; + + this.total++; + + return item; + + }, + + /** + * Resets the first, last, next and previous node pointers in this list. + * + * @method Phaser.LinkedList#reset + */ + reset: function () { + + this.first = null; + this.last = null; + this.next = null; + this.prev = null; + this.total = 0; + + }, + + /** + * Removes the given element from this linked list if it exists. + * + * @method Phaser.LinkedList#remove + * @param {object} item - The item to be removed from the list. + */ + remove: function (item) { + + if (this.total === 1) + { + this.reset(); + item.next = item.prev = null; + return; + } + + if (item === this.first) + { + // It was 'first', make 'first' point to first.next + this.first = this.first.next; + } + else if (item === this.last) + { + // It was 'last', make 'last' point to last.prev + this.last = this.last.prev; + } + + if (item.prev) + { + // make item.prev.next point to childs.next instead of item + item.prev.next = item.next; + } + + if (item.next) + { + // make item.next.prev point to item.prev instead of item + item.next.prev = item.prev; + } + + item.next = item.prev = null; + + if (this.first === null ) + { + this.last = null; + } + + this.total--; + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * The function must exist on the member. + * + * @method Phaser.LinkedList#callAll + * @param {function} callback - The function to call. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content +* quickly and easily, without the need for any external files. You can create textures for sprites and in +* coming releases we'll add dynamic sound effect generation support as well (like sfxr). +* +* Access this via `Game.create` (`this.game.create` from within a State object). +* +* @class Phaser.Create +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Create = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.ctx = null; + + /** + * @property {array} palettes - A range of 16 color palettes for use with sprite generation. + */ + this.palettes = [ + { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' }, + { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' }, + { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' } + ]; + +}; + +/** +* A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_ARNE = 0; + +/** +* A 16 color JMP inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JMP = 1; + +/** +* A 16 color CGA inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_CGA = 2; + +/** +* A 16 color C64 inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_C64 = 3; + +/** +* A 16 color palette inspired by Japanese computers like the MSX. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JAPANESE_MACHINE = 4; + +Phaser.Create.prototype = { + + /** + * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite. + * + * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images + * rather than Phaser.Graphics objects, which are expensive to render and limited in scope. + * + * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts. + * + * For example: + * + * `var data = [ + * ' 333 ', + * ' 777 ', + * 'E333E', + * ' 333 ', + * ' 3 3 ' + * ];` + * + * `game.create.texture('bob', data);` + * + * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it + * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');` + * + * Use {@link Phaser.Loader#imageFromTexture} to preload an image of the same. + * + * @method Phaser.Create#texture + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {array} data - An array of pixel data. + * @param {integer} [pixelWidth=8] - The width of each pixel. + * @param {integer} [pixelHeight=8] - The height of each pixel. + * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + texture: function (key, data, pixelWidth, pixelHeight, palette, generateTexture, callback, callbackContext) { + + if (pixelWidth === undefined) { pixelWidth = 8; } + if (pixelHeight === undefined) { pixelHeight = pixelWidth; } + if (palette === undefined) { palette = 0; } + if (generateTexture === undefined) { generateTexture = true; } + + var w = data[0].length * pixelWidth; + var h = data.length * pixelHeight; + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(w, h); + this.bmd.clear(); + + // Draw it + for (var y = 0; y < data.length; y++) + { + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var d = row[x]; + + if (d !== '.' && d !== ' ') + { + this.ctx.fillStyle = this.palettes[palette][d]; + this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); + } + } + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Creates a grid texture based on the given dimensions. + * + * Use {@link Phaser.Loader#imageFromGrid} to preload an image of the same. + * + * @method Phaser.Create#grid + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {integer} width - The width of the grid in pixels. + * @param {integer} height - The height of the grid in pixels. + * @param {integer} cellWidth - The width of the grid cells in pixels. + * @param {integer} cellHeight - The height of the grid cells in pixels. + * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + grid: function (key, width, height, cellWidth, cellHeight, color, generateTexture, callback, callbackContext) { + + if (generateTexture === undefined) { generateTexture = true; } + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(width, height); + + this.ctx.fillStyle = color; + + for (var y = 0; y < height; y += cellHeight) + { + this.ctx.fillRect(0, y, width, 1); + } + + for (var x = 0; x < width; x += cellWidth) + { + this.ctx.fillRect(x, 0, 1, height); + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Copies the contents of {@link bmd Create's canvas} to the given BitmapData object, or a new BitmapData object. + * + * @param {Phaser.BitmapData} [dest] - The BitmapData receiving the copied image. + * @param {number} [x=0] - The x coordinate to translate to before drawing. + * @param {number} [y=0] - The y coordinate to translate to before drawing. + * @param {number} [width] - The new width of the Sprite being copied. + * @param {number} [height] - The new height of the Sprite being copied. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} - The `dest` argument (if passed), or a new BitmapData object + */ + copy: function (dest, x, y, width, height, blendMode, roundPx) { + + if (dest == null) { dest = this.game.make.bitmapData(); } + + dest.resize(this.bmd.width, this.bmd.height); + + return dest.draw(this.bmd, x, y, width, height, blendMode, roundPx); + + } + +}; + +Phaser.Create.prototype.constructor = Phaser.Create; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers +* to provide for game object positioning in a responsive manner. +* +* @class Phaser.FlexGrid +* @constructor +* @param {Phaser.ScaleManager} manager - The ScaleManager. +* @param {number} width - The width of the game. +* @param {number} height - The height of the game. +*/ +Phaser.FlexGrid = function (manager, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = manager.game; + + /** + * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager. + */ + this.manager = manager; + + // The perfect dimensions on which everything else is based + this.width = width; + this.height = height; + + this.boundsCustom = new Phaser.Rectangle(0, 0, width, height); + this.boundsFluid = new Phaser.Rectangle(0, 0, width, height); + this.boundsFull = new Phaser.Rectangle(0, 0, width, height); + this.boundsNone = new Phaser.Rectangle(0, 0, width, height); + + /** + * @property {Phaser.Point} position - + * @readonly + */ + this.positionCustom = new Phaser.Point(0, 0); + this.positionFluid = new Phaser.Point(0, 0); + this.positionFull = new Phaser.Point(0, 0); + this.positionNone = new Phaser.Point(0, 0); + + /** + * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. + * @readonly + */ + this.scaleCustom = new Phaser.Point(1, 1); + this.scaleFluid = new Phaser.Point(1, 1); + this.scaleFluidInversed = new Phaser.Point(1, 1); + this.scaleFull = new Phaser.Point(1, 1); + this.scaleNone = new Phaser.Point(1, 1); + + this.customWidth = 0; + this.customHeight = 0; + this.customOffsetX = 0; + this.customOffsetY = 0; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.multiplier = 0; + + this.layers = []; + +}; + +Phaser.FlexGrid.prototype = { + + /** + * Sets the core game size. This resets the w/h parameters and bounds. + * + * @method Phaser.FlexGrid#setSize + * @param {number} width - The new dimensions. + * @param {number} height - The new dimensions. + */ + setSize: function (width, height) { + + // These are locked and don't change until setSize is called again + this.width = width; + this.height = height; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.scaleNone = new Phaser.Point(1, 1); + + this.boundsNone.width = this.width; + this.boundsNone.height = this.height; + + this.refresh(); + + }, + + // Need ability to create your own layers with custom scaling, etc. + + /** + * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createCustomLayer + * @param {number} width - Width of this layer in pixels. + * @param {number} height - Height of this layer in pixels. + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createCustomLayer: function (width, height, children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + this.customWidth = width; + this.customHeight = height; + + this.boundsCustom.width = width; + this.boundsCustom.height = height; + + var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createFluidLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFluidLayer: function (children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios. + * + * @method Phaser.FlexGrid#createFullLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFullLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled. + * + * @method Phaser.FlexGrid#createFixedLayer + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFixedLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * Resets the layer children references + * + * @method Phaser.FlexGrid#reset + */ + reset: function () { + + var i = this.layers.length; + + while (i--) + { + if (!this.layers[i].persist) + { + // Remove references to this class + this.layers[i].position = null; + this.layers[i].scale = null; + this.layers.slice(i, 1); + } + } + + }, + + /** + * Called when the game container changes dimensions. + * + * @method Phaser.FlexGrid#onResize + * @param {number} width - The new width of the game container. + * @param {number} height - The new height of the game container. + */ + onResize: function (width, height) { + + this.ratioH = width / height; + this.ratioV = height / width; + + this.refresh(width, height); + + }, + + /** + * Updates all internal vars such as the bounds and scale values. + * + * @method Phaser.FlexGrid#refresh + */ + refresh: function () { + + this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width)); + + this.boundsFluid.width = Math.round(this.width * this.multiplier); + this.boundsFluid.height = Math.round(this.height * this.multiplier); + + this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height); + this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height); + + this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height); + + this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x); + this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y); + + this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + + this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y); + this.positionNone.set(this.boundsNone.x, this.boundsNone.y); + + }, + + /** + * Fits a sprites width to the bounds. + * + * @method Phaser.FlexGrid#fitSprite + * @param {Phaser.Sprite} sprite - The Sprite to fit. + */ + fitSprite: function (sprite) { + + this.manager.scaleSprite(sprite); + + sprite.x = this.manager.bounds.centerX; + sprite.y = this.manager.bounds.centerY; + + }, + + /** + * Call in the render function to output the bounds rects. + * + * @method Phaser.FlexGrid#debug + */ + debug: function () { + + // for (var i = 0; i < this.layers.length; i++) + // { + // this.layers[i].debug(); + // } + + // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16); + // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false); + + this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16); + this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false); + + // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16); + // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false); + + // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16); + // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false); + + } + +}; + +Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* A responsive grid layer. +* +* @class Phaser.FlexLayer +* @extends Phaser.Group +* @constructor +* @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer. +* @param {Phaser.Point} position - A reference to the Point object used for positioning. +* @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds. +* @param {Phaser.Point} scale - A reference to the Point object used for layer scaling. +*/ +Phaser.FlexLayer = function (manager, position, bounds, scale) { + + Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false); + + /** + * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager. + */ + this.manager = manager.manager; + + /** + * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer. + */ + this.grid = manager; + + /** + * Should the FlexLayer remain through a State swap? + * + * @type {boolean} + */ + this.persist = false; + + /** + * @property {Phaser.Point} position + */ + this.position = position; + + /** + * @property {Phaser.Rectangle} bounds + */ + this.bounds = bounds; + + /** + * @property {Phaser.Point} scale + */ + this.scale = scale; + + /** + * @property {Phaser.Point} topLeft + */ + this.topLeft = bounds.topLeft; + + /** + * @property {Phaser.Point} topMiddle + */ + this.topMiddle = new Phaser.Point(bounds.halfWidth, 0); + + /** + * @property {Phaser.Point} topRight + */ + this.topRight = bounds.topRight; + + /** + * @property {Phaser.Point} bottomLeft + */ + this.bottomLeft = bounds.bottomLeft; + + /** + * @property {Phaser.Point} bottomMiddle + */ + this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom); + + /** + * @property {Phaser.Point} bottomRight + */ + this.bottomRight = bounds.bottomRight; + +}; + +Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype); +Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer; + +/** + * Resize. + * + * @method Phaser.FlexLayer#resize + */ +Phaser.FlexLayer.prototype.resize = function () { +}; + +/** + * Debug. + * + * @method Phaser.FlexLayer#debug + */ +Phaser.FlexLayer.prototype.debug = function () { + + this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16); + this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false); + + this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9'); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. +* +* @class Phaser.Color +*/ +Phaser.Color = { + + /** + * Red (0xff0000) + * + * @type number + * @constant + * @default + */ + RED: 0xff0000, + + /** + * Orange (0xff9900) + * + * @type number + * @constant + * @default + */ + ORANGE: 0xff9900, + + /** + * Yellow (0xffff00) + * + * @type number + * @constant + * @default + */ + YELLOW: 0xffff00, + + /** + * Green (0x00ff00) + * + * @type number + * @constant + * @default + */ + GREEN: 0x00ff00, + + /** + * Aqua (0x00ffff) + * + * @type number + * @constant + * @default + */ + AQUA: 0x00ffff, + + /** + * Blue (0x0000ff) + * + * @type number + * @constant + * @default + */ + BLUE: 0x0000ff, + + /** + * Violet/purple (0xff00ff) + * + * @type number + * @constant + * @default + */ + VIOLET: 0xff00ff, + + /** + * White (0xffffff) + * + * @type number + * @constant + * @default + */ + WHITE: 0xffffff, + + /** + * Black (0x000000) + * + * @type number + * @constant + * @default + */ + BLACK: 0, + + /** + * Gray (0x666666) + * + * @type number + * @constant + * @default + */ + GRAY: 0x666666, + + /** + * Packs the r, g, b, a components into a single integer, for use with Int32Array. + * If device is little endian then ABGR order is used. Otherwise RGBA order is used. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.packPixel + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} The packed color as uint32 + */ + packPixel: function (r, g, b, a) { + + if (Phaser.Device.LITTLE_ENDIAN) + { + return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0; + } + else + { + return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0; + } + + }, + + /** + * Unpacks the r, g, b, a components into the specified color object, or a new + * object, for use with Int32Array. If little endian, then ABGR order is used when + * unpacking, otherwise, RGBA order is used. The resulting color object has the + * `r, g, b, a` properties which are unrelated to endianness. + * + * Note that the integer is assumed to be packed in the correct endianness. On little-endian + * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a + * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.unpackPixel + * @static + * @param {number} rgba - The integer, packed in endian order by packPixel. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + unpackPixel: function (rgba, out, hsl, hsv) { + + if (out === undefined || out === null) { out = Phaser.Color.createColor(); } + if (hsl === undefined || hsl === null) { hsl = false; } + if (hsv === undefined || hsv === null) { hsv = false; } + + if (Phaser.Device.LITTLE_ENDIAN) + { + out.a = ((rgba & 0xff000000) >>> 24); + out.b = ((rgba & 0x00ff0000) >>> 16); + out.g = ((rgba & 0x0000ff00) >>> 8); + out.r = ((rgba & 0x000000ff)); + } + else + { + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + } + + 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; + + }, + + /** + * A utility to convert an integer in 0xRRGGBBAA format to a color object. + * This does not rely on endianness. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.fromRGBA + * @static + * @param {number} rgba - An RGBA hex + * @param {object} [out] - The object to use, optional. + * @return {object} A color object. + */ + fromRGBA: function (rgba, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + + out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')'; + + return out; + + }, + + /** + * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.toRGBA + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toRGBA: function (r, g, b, a) { + + return (r << 24) | (g << 16) | (b << 8) | a; + + }, + + /** + * Converts RGBA components to a 32 bit integer in AABBGGRR format. + * + * @method Phaser.Color.toABGR + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toABGR: function (r, g, b, a) { + + return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; + + }, + + /** + * Converts a hex color value to an [R, G, B] array. + * + * @static + * @method Phaser.Color.hexToRGBArray + * @param {number} color - The color to convert to an RGB array. In the format 0xRRGGBB. + * @return {array} An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + */ + hexToRGBArray: function (color) { + + return [ + (color >> 16 & 0xFF) / 255, + (color >> 8 & 0xFF) / 255, + (color & 0xFF) / 255 + ]; + + }, + + /** + * Converts an RGB color array, in the format: [R, G, B], to a hex color value. + * + * @static + * @method Phaser.Color.RGBArrayToHex + * @param {array} rgb - An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + * @return {number} The color value, in the format 0xRRGGBB. + */ + RGBArrayToHex: function (rgb) { + + return ((rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255); + + }, + + /** + * Converts an RGB color value to HSL (hue, saturation and lightness). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSL + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. + */ + 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); + + // achromatic by default + out.h = 0; + out.s = 0; + out.l = (max + min) / 2; + + if (max !== min) + { + var d = max - min; + + out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min); + + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSL (hue, saturation and lightness) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSLtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} l - The lightness, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSLtoRGB: function (h, s, l, out) { + + if (!out) + { + out = Phaser.Color.createColor(l, l, l); + } + else + { + // achromatic by default + out.r = l; + out.g = l; + out.b = l; + } + + if (s !== 0) + { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3); + out.g = Phaser.Color.hueToColor(p, q, h); + out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3); + } + + // out.r = (out.r * 255 | 0); + // out.g = (out.g * 255 | 0); + // out.b = (out.b * 255 | 0); + + out.r = Math.floor((out.r * 255 | 0)); + out.g = Math.floor((out.g * 255 | 0)); + out.b = Math.floor((out.b * 255 | 0)); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts an RGB color value to HSV (hue, saturation and value). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSV + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and value set in the h, s and v properties. + */ + RGBtoHSV: function (r, g, b, out) { + + if (!out) + { + out = Phaser.Color.createColor(r, g, b, 255); + } + + r /= 255; + g /= 255; + b /= 255; + + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var d = max - min; + + // achromatic by default + out.h = 0; + out.s = max === 0 ? 0 : d / max; + out.v = max; + + if (max !== min) + { + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSVtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} v - The value, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSVtoRGB: function (h, s, v, out) { + + if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); } + + var r, g, b; + var i = Math.floor(h * 6); + var f = h * 6 - i; + var p = v * (1 - s); + var q = v * (1 - f * s); + var t = v * (1 - (1 - f) * s); + + switch (i % 6) + { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } + + out.r = Math.floor(r * 255); + out.g = Math.floor(g * 255); + out.b = Math.floor(b * 255); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.hueToColor + * @static + * @param {number} p + * @param {number} q + * @param {number} t + * @return {number} The color component value. + */ + hueToColor: function (p, q, t) { + + if (t < 0) + { + t += 1; + } + + if (t > 1) + { + t -= 1; + } + + if (t < 1 / 6) + { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) + { + return q; + } + + if (t < 2 / 3) + { + return p + (q - p) * (2 / 3 - t) * 6; + } + + return p; + + }, + + /** + * A utility function to create a lightweight 'color' object with the default components. + * Any components that are not specified will default to zero. + * + * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.createColor + * @static + * @param {number} [r=0] - The red color component, in the range 0 - 255. + * @param {number} [g=0] - The green color component, in the range 0 - 255. + * @param {number} [b=0] - The blue color component, in the range 0 - 255. + * @param {number} [a=1] - The alpha color component, in the range 0 - 1. + * @param {number} [h=0] - The hue, in the range 0 - 1. + * @param {number} [s=0] - The saturation, in the range 0 - 1. + * @param {number} [l=0] - The lightness, in the range 0 - 1. + * @param {number} [v=0] - The value, in the range 0 - 1. + * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. + */ + 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, color32: 0, rgba: '' }; + + return Phaser.Color.updateColor(out); + + }, + + /** + * Takes a color object and updates the rgba, color and color32 properties. + * + * @method Phaser.Color.updateColor + * @static + * @param {object} out - The color object to update. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + updateColor: function (out) { + + out.rgba = 'rgba(' + out.r.toFixed() + ',' + out.g.toFixed() + ',' + out.b.toFixed() + ',' + out.a.toString() + ')'; + out.color = Phaser.Color.getColor(out.r, out.g, out.b); + out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b); + + return out; + + }, + + /** + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor32 + * @static + * @param {number} a - The alpha color component, in the range 0 - 255. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + getColor32: function (a, r, g, b) { + + return a << 24 | r << 16 | g << 8 | b; + + }, + + /** + * Given 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xRRGGBB). + */ + getColor: function (r, g, b) { + + return r << 16 | g << 8 | b; + + }, + + /** + * Converts the given color values into a string. + * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + * + * @method Phaser.Color.RGBtoString + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255. + * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. + * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + */ + RGBtoString: function (r, g, b, a, prefix) { + + if (a === undefined) { a = 255; } + if (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); + } + + }, + + /** + * Converts a hex string into an integer color value. + * + * @method Phaser.Color.hexToRGB + * @static + * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. + * @return {number} The rgb color value in the format 0xAARRGGBB. + */ + hexToRGB: function (hex) { + + var rgb = Phaser.Color.hexToColor(hex); + + if (rgb) + { + return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b); + } + + }, + + /** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @method Phaser.Color.hexToColor + * @static + * @param {string} hex - The color string in a hex format. + * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + hexToColor: function (hex, out) { + + // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") + hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { + return r + r + g + g + b + b; + }); + + var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + + if (result) + { + var r = parseInt(result[1], 16); + var g = parseInt(result[2], 16); + var b = parseInt(result[3], 16); + + if (!out) + { + out = Phaser.Color.createColor(r, g, b); + } + else + { + out.r = r; + out.g = g; + out.b = b; + } + } + + return out; + + }, + + /** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @method Phaser.Color.webToColor + * @static + * @param {string} web - The color string in CSS 'web' format. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + webToColor: function (web, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web); + + if (result) + { + out.r = ~~Number(result[1]); + out.g = ~~Number(result[2]); + out.b = ~~Number(result[3]); + out.a = result[4] !== undefined ? Number(result[4]) : 1; + Phaser.Color.updateColor(out); + } + + return out; + + }, + + /** + * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. + * + * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). + * + * An alpha channel is _not_ supported when specifying a hex string. + * + * @method Phaser.Color.valueToColor + * @static + * @param {string|number} value - The color expressed as a recognized string format or a packed integer. + * @param {object} [out] - The object to use for the output. If not provided a new object will be created. + * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. + */ + valueToColor: function (value, out) { + + // The behavior is not consistent between hexToColor/webToColor on invalid input. + // This unifies both by returning a new object, but returning null may be better. + if (!out) + { + out = Phaser.Color.createColor(); + } + + if (typeof value === 'string') + { + if (value.indexOf('rgb') === 0) + { + return Phaser.Color.webToColor(value, out); + } + else + { + // `hexToColor` does not support alpha; match `createColor`. + out.a = 1; + return Phaser.Color.hexToColor(value, out); + } + } + else if (typeof value === 'number') + { + // `getRGB` does not take optional object to modify; + // alpha is also adjusted to match `createColor`. + var tempColor = Phaser.Color.getRGB(value); + out.r = tempColor.r; + out.g = tempColor.g; + out.b = tempColor.b; + out.a = tempColor.a / 255; + return out; + } + else + { + return out; + } + + }, + + /** + * Return a string containing a hex representation of the given color component. + * + * @method Phaser.Color.componentToHex + * @static + * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. + * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ + componentToHex: function (color) { + + var hex = color.toString(16); + + return (hex.length === 1) ? '0' + hex : hex; + + }, + + /** + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSVColorWheel + * @static + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSV color wheel. + */ + HSVColorWheel: function (s, v) { + + if (s === undefined) { s = 1.0; } + if (v === undefined) { v = 1.0; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v)); + } + + return colors; + + }, + + /** + * Get HSL color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSLColorWheel + * @static + * @param {number} [s=0.5] - The saturation, in the range 0 - 1. + * @param {number} [l=0.5] - The lightness, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSL color wheel. + */ + HSLColorWheel: function (s, l) { + + if (s === undefined) { s = 0.5; } + if (l === undefined) { l = 0.5; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l)); + } + + return colors; + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColor + * @static + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @param {number} [alpha] - The alpha of the returned color. + * @param {number} [colorSpace=0] - The color space to interpolate in. 0 = RGB, 1 = HSV. + * @returns {number} The interpolated color value. + */ + interpolateColor: function (color1, color2, steps, currentStep, alpha, colorSpace) { + + if (alpha === undefined) { alpha = 255; } + if (colorSpace === undefined) { colorSpace = 0; } + + var src1 = Phaser.Color.getRGB(color1); + var src2 = Phaser.Color.getRGB(color2); + + if (colorSpace === 0) + { + 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; + } + + if (colorSpace === 1) + { + var hsv1 = Phaser.Color.RGBtoHSV(src1.r, src1.g, src1.b); + var hsv2 = Phaser.Color.RGBtoHSV(src2.r, src2.g, src2.b); + var dh = hsv2.h - hsv1.h; + var h; + + if (hsv1.h > hsv2.h) + { + var h3 = hsv2.h; + hsv2.h = hsv1.h; + hsv1.h = h3; + dh = -dh; + currentStep = steps - currentStep; + } + + if (dh > 0.5) + { + hsv1.h = hsv1.h + 1; + h = (((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h) % 1; + } + + if (dh <= 0.5) + { + h = ((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h; + } + + var s = (((hsv2.s - hsv1.s) * currentStep) / steps) + hsv1.s; + var v = (((hsv2.v - hsv1.v) * currentStep) / steps) + hsv1.v; + + var rgb = Phaser.Color.HSVtoRGB(h, s, v, rgb); + var r = rgb.r; + var g = rgb.g; + var b = rgb.b; + } + + return Phaser.Color.getColor32(alpha, r, g, b); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColorWithRGB + * @static + * @param {number} color - The first color value. + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * @method Phaser.Color.interpolateRGB + * @static + * @param {number} r1 - The red color value, between 0 and 0xFF (255). + * @param {number} g1 - The green color value, between 0 and 0xFF (255). + * @param {number} b1 - The blue color value, between 0 and 0xFF (255). + * @param {number} r2 - The red color value, between 0 and 0xFF (255). + * @param {number} g2 - The green color value, between 0 and 0xFF (255). + * @param {number} b2 - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + + /** + * Calculates a linear (interpolation) value of two colors over t. + * + * This is a slightly simpler interface to {@link Phaser.Color.interpolateColor}. + * + * The arguments are similar to {@link Phaser.Math.linear}. + * + * @method Phaser.Color.linear + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linear: function (color1, color2, t) { + + return this.interpolateColor(color1, color2, 1, t); + + }, + + /** + * Calculates a linear (interpolation) value of an array of colors over t. + * + * The arguments are similar to {@link Phaser.Math.linearInterpolation}. + * + * This can be used as a {@link Phaser.TweenData#interpolationFunction}. + * + * @method Phaser.Color.linearInterpolation + * @param {number[]} colors - The input array of color values to interpolate between. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linearInterpolation: function (colors, t) { + + var k = Phaser.Math.linear(0, colors.length - 1, t); + var color1 = colors[ Math.floor(k) ]; + var color2 = colors[ Math.ceil(k)] ; + + return this.linear(color1, color2, k % 1); + + }, + + /** + * Returns a random color value between black and white + * Set the min value to start each channel from the given offset. + * Set the max value to restrict the maximum color used per channel. + * + * @method Phaser.Color.getRandomColor + * @static + * @param {number} [min=0] - The lowest value to use for the color. + * @param {number} [max=255] - The highest value to use for the color. + * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). + * @returns {number} 32-bit color value with alpha. + */ + getRandomColor: function (min, max, alpha) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + if (alpha === undefined) { alpha = 255; } + + // Sanity checks + 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); + + }, + + /** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exist in the given color (0xAARRGGBB) + * + * @method Phaser.Color.getRGB + * @static + * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). + * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. + */ + getRGB: function (color) { + + if (color > 16777215) + { + // The color value has an alpha component + return { + alpha: color >>> 24, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: color >>> 24, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + else + { + return { + alpha: 255, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: 255, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + + }, + + /** + * Returns a CSS friendly string value from the given color. + * + * @method Phaser.Color.getWebRGB + * @static + * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. + * @returns {string} A string in the format: 'rgba(r,g,b,a)' + */ + getWebRGB: function (color) { + + if (typeof color === 'object') + { + return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')'; + } + else + { + var rgb = Phaser.Color.getRGB(color); + return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')'; + } + + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. + * + * @method Phaser.Color.getAlpha + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlpha: function (color) { + return color >>> 24; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. + * + * @method Phaser.Color.getAlphaFloat + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlphaFloat: function (color) { + return (color >>> 24) / 255; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. + * + * @method Phaser.Color.getRed + * @static + * @param {number} color In the format 0xAARRGGBB. + * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). + */ + getRed: function (color) { + return color >> 16 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. + * + * @method Phaser.Color.getGreen + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). + */ + getGreen: function (color) { + return color >> 8 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. + * + * @method Phaser.Color.getBlue + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). + */ + getBlue: function (color) { + return color & 0xFF; + }, + + /** + * Blends the source color, ignoring the backdrop. + * + * @method Phaser.Color.blendNormal + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNormal: function (a) { + return a; + }, + + /** + * Selects the lighter of the backdrop and source colors. + * + * @method Phaser.Color.blendLighten + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLighten: function (a, b) { + return (b > a) ? b : a; + }, + + /** + * Selects the darker of the backdrop and source colors. + * + * @method Phaser.Color.blendDarken + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDarken: function (a, b) { + return (b > a) ? a : b; + }, + + /** + * Multiplies the backdrop and source color values. + * The result color is always at least as dark as either of the two constituent + * colors. Multiplying any color with black produces black; + * multiplying with white leaves the original color unchanged. + * + * @method Phaser.Color.blendMultiply + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendMultiply: function (a, b) { + return (a * b) / 255; + }, + + /** + * Takes the average of the source and backdrop colors. + * + * @method Phaser.Color.blendAverage + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAverage: function (a, b) { + return (a + b) / 2; + }, + + /** + * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. + * + * @method Phaser.Color.blendAdd + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAdd: function (a, b) { + return Math.min(255, a + b); + }, + + /** + * Combines the source and backdrop colors and returns their value minus 255. + * + * @method Phaser.Color.blendSubtract + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSubtract: function (a, b) { + return Math.max(0, a + b - 255); + }, + + /** + * Subtracts the darker of the two constituent colors from the lighter. + * + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendDifference + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDifference: function (a, b) { + return Math.abs(a - b); + }, + + /** + * Negation blend mode. + * + * @method Phaser.Color.blendNegation + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNegation: function (a, b) { + return 255 - Math.abs(255 - a - b); + }, + + /** + * Multiplies the complements of the backdrop and source color values, then complements the result. + * The result color is always at least as light as either of the two constituent colors. + * Screening any color with white produces white; screening with black leaves the original color unchanged. + * + * @method Phaser.Color.blendScreen + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendScreen: function (a, b) { + return 255 - (((255 - a) * (255 - b)) >> 8); + }, + + /** + * Produces an effect similar to that of the Difference mode, but lower in contrast. + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendExclusion + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendExclusion: function (a, b) { + return a + b - 2 * a * b / 255; + }, + + /** + * Multiplies or screens the colors, depending on the backdrop color. + * Source colors overlay the backdrop while preserving its highlights and shadows. + * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. + * + * @method Phaser.Color.blendOverlay + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendOverlay: function (a, b) { + return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255); + }, + + /** + * Darkens or lightens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. + * The effect is similar to shining a diffused spotlight on the backdrop. + * + * @method Phaser.Color.blendSoftLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSoftLight: function (a, b) { + return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255); + }, + + /** + * Multiplies or screens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; + * this is useful for adding shadows to a scene. + * + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. + * + * @method Phaser.Color.blendHardLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardLight: function (a, b) { + return Phaser.Color.blendOverlay(b, a); + }, + + /** + * Brightens the backdrop color to reflect the source color. + * Painting with black produces no change. + * + * @method Phaser.Color.blendColorDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorDodge: function (a, b) { + return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b))); + }, + + /** + * Darkens the backdrop color to reflect the source color. + * Painting with white produces no change. + * + * @method Phaser.Color.blendColorBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorBurn: function (a, b) { + return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b)); + }, + + /** + * An alias for blendAdd, it simply sums the values of the two colors. + * + * @method Phaser.Color.blendLinearDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearDodge: function (a, b) { + return Phaser.Color.blendAdd(a, b); + }, + + /** + * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. + * + * @method Phaser.Color.blendLinearBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearBurn: function (a, b) { + return Phaser.Color.blendSubtract(a, b); + }, + + /** + * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). + * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. + * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. + * + * @method Phaser.Color.blendLinearLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearLight: function (a, b) { + return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128))); + }, + + /** + * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). + * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. + * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom + * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. + * + * @method Phaser.Color.blendVividLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendVividLight: function (a, b) { + return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128))); + }, + + /** + * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. + * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. + * + * @method Phaser.Color.blendPinLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPinLight: function (a, b) { + return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128))); + }, + + /** + * Runs blendVividLight on the source and backdrop colors. + * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. + * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. + * This changes all pixels to primary additive colors (red, green, or blue), white, or black. + * + * @method Phaser.Color.blendHardMix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardMix: function (a, b) { + return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255; + }, + + /** + * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. + * + * @method Phaser.Color.blendReflect + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendReflect: function (a, b) { + return b === 255 ? b : Math.min(255, (a * a / (255 - b))); + }, + + /** + * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. + * + * @method Phaser.Color.blendGlow + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendGlow: function (a, b) { + return Phaser.Color.blendReflect(b, a); + }, + + /** + * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. + * + * @method Phaser.Color.blendPhoenix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPhoenix: function (a, b) { + return Math.min(a, b) - Math.max(a, b) + 255; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Manager is responsible for looking after all of the running physics systems. +* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. +* +* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. +* +* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the +* faster (due to being much simpler) Arcade Physics system. +* +* @class Phaser.Physics +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Physics = function (game, config) { + + config = config || {}; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} config - The physics configuration object as passed to the game on creation. + */ + this.config = config; + + /** + * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. + */ + this.arcade = null; + + /** + * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. + */ + this.p2 = null; + + /** + * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. + */ + this.ninja = null; + + /** + * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. + */ + this.box2d = null; + + /** + * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). + */ + this.chipmunk = null; + + /** + * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). + */ + this.matter = null; + + this.parseConfig(); + +}; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.ARCADE = 0; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.P2JS = 1; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.NINJA = 2; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.BOX2D = 3; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.CHIPMUNK = 4; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.MATTERJS = 5; + +Phaser.Physics.prototype = { + + /** + * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. + * + * @method Phaser.Physics#parseConfig + */ + parseConfig: function () { + + if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade')) + { + // If Arcade isn't specified, we create it automatically if we can + this.arcade = new Phaser.Physics.Arcade(this.game); + } + + 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); + } + + if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D')) + { + this.box2d = new Phaser.Physics.BOX2D(this.game, this.config); + } + + if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter')) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + + }, + + /** + * This will create an instance of the requested physics simulation. + * Phaser.Physics.Arcade is running by default, but all others need activating directly. + * + * You can start the following physics systems: + * + * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. + * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) + * + * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. + * They are not bundled into the core Phaser library. + * + * If the physics world has already been created (i.e. in another state in your game) then + * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors + * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. + * + * @method Phaser.Physics#startSystem + * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. + */ + startSystem: function (system) { + + if (system === Phaser.Physics.ARCADE) + { + this.arcade = new Phaser.Physics.Arcade(this.game); + } + else if (system === Phaser.Physics.P2JS) + { + if (this.p2 === null) + { + this.p2 = new Phaser.Physics.P2(this.game, this.config); + } + else + { + this.p2.reset(); + } + } + else if (system === Phaser.Physics.NINJA) + { + this.ninja = new Phaser.Physics.Ninja(this.game); + } + else if (system === Phaser.Physics.BOX2D) + { + if (this.box2d === null) + { + this.box2d = new Phaser.Physics.Box2D(this.game, this.config); + } + else + { + this.box2d.reset(); + } + } + else if (system === Phaser.Physics.MATTERJS) + { + if (this.matter === null) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + else + { + this.matter.reset(); + } + } + + }, + + /** + * This will create a default physics body on the given game object or array of objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * It can be for any of the physics systems that have been started: + * + * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. + * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. + * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 + * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) + * Phaser.Physics.CHIPMUNK is still in development. + * + * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the + * individual physics systems `enable` methods instead of using this generic one. + * + * @method Phaser.Physics#enable + * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. + * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. + * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. + */ + enable: function (object, system, debug) { + + if (system === undefined) { system = Phaser.Physics.ARCADE; } + if (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); + } + else if (system === Phaser.Physics.BOX2D && this.box2d) + { + this.box2d.enable(object); + } + else if (system === Phaser.Physics.MATTERJS && this.matter) + { + this.matter.enable(object); + } + else + { + console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.'); + } + + }, + + /** + * preUpdate checks. + * + * @method Phaser.Physics#preUpdate + * @protected + */ + preUpdate: function () { + + // ArcadePhysics / Ninja don't have a core to preUpdate + + if (this.p2) + { + this.p2.preUpdate(); + } + + if (this.box2d) + { + this.box2d.preUpdate(); + } + + if (this.matter) + { + this.matter.preUpdate(); + } + + }, + + /** + * Updates all running physics systems. + * + * @method Phaser.Physics#update + * @protected + */ + update: function () { + + // ArcadePhysics / Ninja don't have a core to update + + if (this.p2) + { + this.p2.update(); + } + + if (this.box2d) + { + this.box2d.update(); + } + + if (this.matter) + { + this.matter.update(); + } + + }, + + /** + * Updates the physics bounds to match the world dimensions. + * + * @method Phaser.Physics#setBoundsToWorld + * @protected + */ + setBoundsToWorld: function () { + + if (this.arcade) + { + this.arcade.setBoundsToWorld(); + } + + if (this.ninja) + { + this.ninja.setBoundsToWorld(); + } + + if (this.p2) + { + this.p2.setBoundsToWorld(); + } + + if (this.box2d) + { + this.box2d.setBoundsToWorld(); + } + + if (this.matter) + { + this.matter.setBoundsToWorld(); + } + + }, + + /** + * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. + * + * @method Phaser.Physics#clear + * @protected + */ + clear: function () { + + if (this.p2) + { + this.p2.clear(); + } + + if (this.box2d) + { + this.box2d.clear(); + } + + if (this.matter) + { + this.matter.clear(); + } + + }, + + /** + * Resets the active physics system. Called automatically on a Phaser.State swap. + * + * @method Phaser.Physics#reset + * @protected + */ + reset: function () { + + if (this.p2) + { + this.p2.reset(); + } + + if (this.box2d) + { + this.box2d.reset(); + } + + if (this.matter) + { + this.matter.reset(); + } + + }, + + /** + * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. + * + * @method Phaser.Physics#destroy + */ + destroy: function () { + + if (this.p2) + { + this.p2.destroy(); + } + + if (this.box2d) + { + this.box2d.destroy(); + } + + if (this.matter) + { + this.matter.destroy(); + } + + this.arcade = null; + this.ninja = null; + this.p2 = null; + this.box2d = null; + this.matter = null; + + } + +}; + +Phaser.Physics.prototype.constructor = Phaser.Physics; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. +* +* @class Phaser.Physics.Arcade +* @constructor +* @param {Phaser.Game} game - reference to the current game instance. +*/ +Phaser.Physics.Arcade = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height); + + /** + * Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`. + * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. + * @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right). + */ + this.checkCollision = { up: true, down: true, left: true, right: true }; + + /** + * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. + */ + this.maxLevels = 4; + + /** + * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. + * @default + */ + this.OVERLAP_BIAS = 4; + + /** + * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. + */ + this.forceX = false; + + /** + * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT. + * @default + */ + this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT; + + /** + * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. + */ + this.skipQuadTree = true; + + /** + * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. + */ + this.isPaused = false; + + /** + * @property {Phaser.QuadTree} quadTree - The world QuadTree. + */ + 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); + + /** + * @property {number} _total - Internal cache var. + * @private + */ + this._total = 0; + + // By default we want the bounds the same size as the world bounds + this.setBoundsToWorld(); + +}; + +Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade; + +/** +* A constant used for the sortDirection value. +* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.SORT_NONE = 0; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.LEFT_RIGHT = 1; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.RIGHT_LEFT = 2; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.TOP_BOTTOM = 3; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.BOTTOM_TOP = 4; + +Phaser.Physics.Arcade.prototype = { + + /** + * Updates the size of this physics world. + * + * @method Phaser.Physics.Arcade#setBounds + * @param {number} x - Top left most corner of the world. + * @param {number} y - Top left most corner of the world. + * @param {number} width - New width of the world. Can never be smaller than the Game.width. + * @param {number} height - New height of the world. Can never be smaller than the Game.height. + */ + setBounds: function (x, y, width, height) { + + this.bounds.setTo(x, y, width, height); + + }, + + /** + * Updates the size of this physics world to match the size of the game world. + * + * @method Phaser.Physics.Arcade#setBoundsToWorld + */ + setBoundsToWorld: function () { + + this.bounds.copyFrom(this.game.world.bounds); + + }, + + /** + * This will create an Arcade Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * + * @method Phaser.Physics.Arcade#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, children) { + + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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) + { + // If it's a Group then we do it on the children regardless + this.enable(object.children, children); + } + else + { + this.enableBody(object); + + if (children && object.hasOwnProperty('children') && object.children.length > 0) + { + this.enable(object.children, true); + } + } + } + + }, + + /** + * Creates an Arcade Physics body on the given game object. + * + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. + * + * @method Phaser.Physics.Arcade#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + */ + enableBody: function (object) { + + if (object.hasOwnProperty('body') && object.body === null) + { + object.body = new Phaser.Physics.Arcade.Body(object); + + if (object.parent && object.parent instanceof Phaser.Group) + { + object.parent.addToHash(object); + } + } + + }, + + /** + * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. + * + * @method Phaser.Physics.Arcade#updateMotion + * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. + */ + updateMotion: function (body) { + + if (body.allowRotation) + { + var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity; + body.angularVelocity += 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); + + }, + + /** + * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * Based on a function in Flixel by @ADAMATOMIC + * + * @method Phaser.Physics.Arcade#computeVelocity + * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical. + * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. + * @param {number} velocity - Any component of velocity (e.g. 20). + * @param {number} acceleration - Rate at which the velocity is changing. + * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. + * @param {number} [max=10000] - An absolute value cap for the velocity. + * @return {number} The altered Velocity value. + */ + computeVelocity: function (axis, body, velocity, acceleration, drag, max) { + + if (max === undefined) { max = 10000; } + + 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 && body.allowDrag) + { + drag *= this.game.time.physicsElapsed; + + if (velocity - drag > 0) + { + velocity -= drag; + } + else if (velocity + drag < 0) + { + velocity += drag; + } + else + { + velocity = 0; + } + } + + if (velocity > max) + { + velocity = max; + } + else if (velocity < -max) + { + velocity = -max; + } + + return velocity; + + }, + + /** + * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. + * + * Unlike {@link #collide} the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. + * Both the first and second parameter can be arrays of objects, of differing types. + * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups within Groups). + * + * ##### Tilemaps + * + * Any overlapping tiles, including blank/null tiles, will give a positive result. Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) have no special status, and callbacks added via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} are not invoked. So calling this method without any callbacks isn't very useful. + * + * If you're interested only in whether an object overlaps a certain tile or class of tiles, filter the tiles with `processCallback` and then use the result returned by this method. Blank/null tiles can be excluded by their {@link Phaser.Tile#index index} (-1). + * + * If you want to take action on certain overlaps, examine the tiles in `collideCallback` and then handle as you like. + * + * @method Phaser.Physics.Arcade#overlap + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if an overlap occurred otherwise false. + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) { + + overlapCallback = overlapCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || overlapCallback; + + this._total = 0; + + this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + + return (this._total > 0); + + }, + + /** + * Checks for collision between two game objects and separates them if colliding ({@link https://gist.github.com/samme/cbb81dd19f564dcfe2232761e575063d details}). If you don't require separation then use {@link #overlap} instead. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. + * Both the `object1` and `object2` can be arrays of objects, of differing types. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If one Group **only** is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If either object is `null` the collision test will fail. + * + * Bodies with `enable = false` and Sprites with `exists = false` are skipped (ignored). + * + * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. + * + * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). + * + * ##### Examples + * + * ```javascript + * collide(group); + * collide(group, undefined); // equivalent + * + * collide(sprite1, sprite2); + * + * collide(sprite, group); + * + * collide(group1, group2); + * + * collide([sprite1, sprite2], [sprite3, sprite4]); // 1 vs. 3, 1 vs. 4, 2 vs. 3, 2 vs. 4 + * ``` + * + * ##### Tilemaps + * + * Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) are "solid". If a Sprite collides with one of these tiles, the two are separated by moving the Sprite outside the tile's edges. Enable {@link Phaser.TilemapLayer#debug} to see the colliding edges of the Tilemap. + * + * Tiles with a callback attached via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} invoke the callback if a Sprite collides with them. If a tile has a callback attached via both methods, only the location callback is invoked. The colliding Sprite is separated from the tile only if the callback returns `true`. + * + * @method Phaser.Physics.Arcade#collide + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. + * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if a collision occurred otherwise false. + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) { + + collideCallback = collideCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || collideCallback; + + this._total = 0; + + this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + + return (this._total > 0); + + }, + + /** + * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortLeftRight + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortLeftRight: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.x - b.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortRightLeft + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortRightLeft: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.x - a.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortTopBottom + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortTopBottom: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.y - b.body.y; + + }, + + /** + * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortBottomTop + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortBottomTop: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.y - a.body.y; + + }, + + /** + * This method will sort a Groups hash array. + * + * If the Group has `physicsSortDirection` set it will use the sort direction defined. + * + * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection. + * + * By changing Group.physicsSortDirection you can customise each Group to sort in a different order. + * + * @method Phaser.Physics.Arcade#sort + * @param {Phaser.Group} group - The Group to sort. + * @param {integer} [sortDirection] - The sort direction used to sort this Group. + */ + sort: function (group, sortDirection) { + + if (group.physicsSortDirection !== null) + { + sortDirection = group.physicsSortDirection; + } + else + { + if (sortDirection === undefined) { sortDirection = this.sortDirection; } + } + + if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + // Game world is say 2000x600 and you start at 0 + group.hash.sort(this.sortLeftRight); + } + else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + // Game world is say 2000x600 and you start at 2000 + group.hash.sort(this.sortRightLeft); + } + else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + // Game world is say 800x2000 and you start at 0 + group.hash.sort(this.sortTopBottom); + } + else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + // Game world is say 800x2000 and you start at 2000 + group.hash.sort(this.sortBottomTop); + } + + }, + + /** + * Internal collision handler. Extracts objects for {@link #collideHandler}. + * + * @method Phaser.Physics.Arcade#collideObjects + * @private + */ + collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object2.length; i++) + { + if (!object2[i]) { continue; } + + this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && !Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + for (var j = 0; j < object2.length; j++) + { + if (!object2[j]) { continue; } + + this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + + }, + + /** + * Internal collision handler. Matches arguments to other handlers. + * + * @method Phaser.Physics.Arcade#collideHandler + * @private + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + // Only collide valid objects + if (object2 === undefined && object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly); + return; + } + + // If neither of the objects are set or exist then bail out + if (!object1 || !object2 || !object1.exists || !object2.exists) + { + return; + } + + // Groups? Sort them + if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE) + { + if (object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + } + + if (object2.physicsType === Phaser.GROUP) + { + this.sort(object2); + } + } + + // SPRITES + if (object1.physicsType === Phaser.SPRITE) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // GROUPS + else if (object1.physicsType === Phaser.GROUP) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // TILEMAP LAYERS + else if (object1.physicsType === Phaser.TILEMAPLAYER) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsSprite + * @private + * @param {Phaser.Sprite} sprite1 - The first sprite to check. + * @param {Phaser.Sprite} sprite2 - The second sprite to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + 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; + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsGroup + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0 || !sprite.body) + { + return; + } + + if (this.skipQuadTree || sprite.body.skipQuadTree) + { + var bounds = {}; + + for (var i = 0; i < group.hash.length; i++) + { + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds object + bounds = object1.body.getBounds(bounds); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (sprite.body.right < bounds.x) + { + break; + } + else if (bounds.right < sprite.body.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (sprite.body.x > bounds.right) + { + break; + } + else if (bounds.x > sprite.body.right) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (sprite.body.bottom < bounds.y) + { + break; + } + else if (bounds.bottom < sprite.body.y) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (sprite.body.y > bounds.bottom) + { + break; + } + else if (bounds.y > sprite.body.bottom) + { + continue; + } + } + + this.collideSpriteVsSprite(sprite, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else + { + // What is the sprite colliding with in the quadtree? + 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 items = this.quadTree.retrieve(sprite); + + for (var i = 0; i < items.length; i++) + { + // We have our potential suspects, are they in this group? + if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, items[i].sprite); + } + + this._total++; + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsSelf + * @private + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.hash.length; i++) + { + var bounds1 = {}; + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds1 object + bounds1 = object1.body.getBounds(bounds1); + + for (var j = i + 1; j < group.hash.length; j++) + { + var bounds2 = {}; + var object2 = group.hash[j]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object2 || !object2.exists || !object2.body) + { + continue; + } + + // Inject the Body bounds data into the bounds2 object + bounds2 = object2.body.getBounds(bounds2); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (bounds1.right < bounds2.x) + { + break; + } + else if (bounds2.right < bounds1.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (bounds1.x > bounds2.right) + { + continue; + } + else if (bounds2.x > bounds1.right) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (bounds1.bottom < bounds2.y) + { + continue; + } + else if (bounds2.bottom < bounds1.y) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (bounds1.y > bounds2.bottom) + { + continue; + } + else if (bounds2.y > object1.body.bottom) + { + break; + } + } + + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsGroup + * @private + * @param {Phaser.Group} group1 - The first Group to check. + * @param {Phaser.Group} group2 - The second Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group1.length === 0 || group2.length === 0) + { + return; + } + + for (var i = 0; i < group1.children.length; i++) + { + if (group1.children[i].exists) + { + if (group1.children[i].physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else + { + this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + + }, + + /** + * The core separation function to separate two physics bodies. + * + * @private + * @method Phaser.Physics.Arcade#separate + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true. + * @param {object} [callbackContext] - The context in which to run the process callback. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} Returns true if the bodies collided, otherwise false. + */ + separate: function (body1, body2, processCallback, callbackContext, overlapOnly) { + + if ( + !body1.enable || + !body2.enable || + body1.checkCollision.none || + body2.checkCollision.none || + !this.intersects(body1, body2)) + { + return false; + } + + // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. + if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false) + { + return false; + } + + // Circle vs. Circle quick bail out + if (body1.isCircle && body2.isCircle) + { + return this.separateCircle(body1, body2, overlapOnly); + } + + // We define the behavior of bodies in a collision circle and rectangle + // If a collision occurs in the corner points of the rectangle, the body behave like circles + + // Either body1 or body2 is a circle + if (body1.isCircle !== body2.isCircle) + { + var bodyRect = (body1.isCircle) ? body2 : body1; + var bodyCircle = (body1.isCircle) ? body1 : body2; + + var rect = { + x: bodyRect.x, + y: bodyRect.y, + right: bodyRect.right, + bottom: bodyRect.bottom + }; + + var circle = bodyCircle.center; + + if (circle.y < rect.y || circle.y > rect.bottom) + { + if (circle.x < rect.x || circle.x > rect.right) + { + return this.separateCircle(body1, body2, overlapOnly); + } + } + } + + var resultX = false; + var resultY = false; + + // Do we separate on x or y first? + if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) + { + resultX = this.separateX(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultY = this.separateY(body1, body2, overlapOnly); + } + } + else + { + resultY = this.separateY(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultX = this.separateX(body1, body2, overlapOnly); + } + } + + var result = (resultX || resultY); + + if (result) + { + if (overlapOnly) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + else + { + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + } + } + + return result; + + }, + + /** + * Check for intersection against two bodies. + * + * @method Phaser.Physics.Arcade#intersects + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check. + * @return {boolean} True if they intersect, otherwise false. + */ + intersects: function (body1, body2) { + + if (body1 === body2) + { + return false; + } + + if (body1.isCircle) + { + if (body2.isCircle) + { + // Circle vs. Circle + return Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); + } + else + { + // Circle vs. Rect + return this.circleBodyIntersects(body1, body2); + } + } + else + { + if (body2.isCircle) + { + // Rect vs. Circle + return this.circleBodyIntersects(body2, body1); + } + else + { + // Rect vs. Rect + if (body1.right <= body2.position.x) + { + return false; + } + + if (body1.bottom <= body2.position.y) + { + return false; + } + + if (body1.position.x >= body2.right) + { + return false; + } + + if (body1.position.y >= body2.bottom) + { + return false; + } + + return true; + } + } + + }, + + /** + * Checks to see if a circular Body intersects with a Rectangular Body. + * + * @method Phaser.Physics.Arcade#circleBodyIntersects + * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set. + * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape) + * @return {boolean} Returns true if the bodies intersect, otherwise false. + */ + circleBodyIntersects: function (circle, body) { + + var x = Phaser.Math.clamp(circle.center.x, body.left, body.right); + var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom); + + var dx = (circle.center.x - x) * (circle.center.x - x); + var dy = (circle.center.y - y) * (circle.center.y - y); + + return (dx + dy) <= (circle.halfWidth * circle.halfWidth); + + }, + + /** + * The core separation function to separate two circular physics bodies. + * + * @method Phaser.Physics.Arcade#separateCircle + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateCircle: function (body1, body2, overlapOnly) { + + // Set the bounding box overlap values + this.getOverlapX(body1, body2); + this.getOverlapY(body1, body2); + + var dx = body2.center.x - body1.center.x; + var dy = body2.center.y - body1.center.y; + + var angleCollision = Math.atan2(dy, dx); + + var overlap = 0; + + if (body1.isCircle !== body2.isCircle) + { + var rect = { + x: (body2.isCircle) ? body1.position.x : body2.position.x, + y: (body2.isCircle) ? body1.position.y : body2.position.y, + right: (body2.isCircle) ? body1.right : body2.right, + bottom: (body2.isCircle) ? body1.bottom : body2.bottom + }; + + var circle = { + x: (body1.isCircle) ? body1.center.x : body2.center.x, + y: (body1.isCircle) ? body1.center.y : body2.center.y, + radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth + }; + + if (circle.y < rect.y) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.y) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.y) - circle.radius; + } + } + else if (circle.y > rect.bottom) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; + } + } + + overlap *= -1; + } + else + { + overlap = (body1.halfWidth + body2.halfWidth) - Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y); + } + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + if (overlap !== 0) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + + // return true if there was some overlap, otherwise false + return (overlap !== 0); + } + + // Transform the velocity vector to the coordinate system oriented along the direction of impact. + // This is done to eliminate the vertical component of the velocity + var v1 = { + x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision), + y: body1.velocity.x * Math.sin(angleCollision) - body1.velocity.y * Math.cos(angleCollision) + }; + + var v2 = { + x: body2.velocity.x * Math.cos(angleCollision) + body2.velocity.y * Math.sin(angleCollision), + y: body2.velocity.x * Math.sin(angleCollision) - body2.velocity.y * Math.cos(angleCollision) + }; + + // We expect the new velocity after impact + var tempVel1 = ((body1.mass - body2.mass) * v1.x + 2 * body2.mass * v2.x) / (body1.mass + body2.mass); + var tempVel2 = (2 * body1.mass * v1.x + (body2.mass - body1.mass) * v2.x) / (body1.mass + body2.mass); + + // We convert the vector to the original coordinate system and multiplied by factor of rebound + if (!body1.immovable) + { + body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x; + body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y; + } + + if (!body2.immovable) + { + body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x; + body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y; + } + + // When the collision angle is almost perpendicular to the total initial velocity vector + // (collision on a tangent) vector direction can be determined incorrectly. + // This code fixes the problem + + if (Math.abs(angleCollision) < Math.PI / 2) + { + if ((body1.velocity.x > 0) && !body1.immovable && (body2.velocity.x > body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x < 0) && !body2.immovable && (body1.velocity.x < body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y > 0) && !body1.immovable && (body2.velocity.y > body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y < 0) && !body2.immovable && (body1.velocity.y < body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + else if (Math.abs(angleCollision) > Math.PI / 2) + { + if ((body1.velocity.x < 0) && !body1.immovable && (body2.velocity.x < body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y < 0) && !body1.immovable && (body2.velocity.y < body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + + if (!body1.immovable) + { + body1.x += (body1.velocity.x * this.game.time.physicsElapsed) - overlap * Math.cos(angleCollision); + body1.y += (body1.velocity.y * this.game.time.physicsElapsed) - overlap * Math.sin(angleCollision); + } + + if (!body2.immovable) + { + body2.x += (body2.velocity.x * this.game.time.physicsElapsed) + overlap * Math.cos(angleCollision); + body2.y += (body2.velocity.y * this.game.time.physicsElapsed) + overlap * Math.sin(angleCollision); + } + + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + + return true; + + }, + + /** + * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: + * `touching.left`, `touching.right` and `overlapX`. + * + * @method Phaser.Physics.Arcade#getOverlapX + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of horizontal overlap between the two bodies. + */ + getOverlapX: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS; + + if (body1.deltaX() === 0 && body2.deltaX() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaX() > body2.deltaX()) + { + // Body1 is moving right and / or Body2 is moving left + overlap = body1.right - body2.x; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.right = true; + body2.touching.none = false; + body2.touching.left = true; + } + } + else if (body1.deltaX() < body2.deltaX()) + { + // Body1 is moving left and/or Body2 is moving right + overlap = body1.x - body2.width - body2.x; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.left = true; + body2.touching.none = false; + body2.touching.right = true; + } + } + + // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapX = overlap; + body2.overlapX = overlap; + + return overlap; + + }, + + /** + * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: + * `touching.up`, `touching.down` and `overlapY`. + * + * @method Phaser.Physics.Arcade#getOverlapY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of vertical overlap between the two bodies. + */ + getOverlapY: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS; + + if (body1.deltaY() === 0 && body2.deltaY() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaY() > body2.deltaY()) + { + // Body1 is moving down and/or Body2 is moving up + overlap = body1.bottom - body2.y; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.down = true; + body2.touching.none = false; + body2.touching.up = true; + } + } + else if (body1.deltaY() < body2.deltaY()) + { + // Body1 is moving up and/or Body2 is moving down + overlap = body1.y - body2.bottom; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.up = true; + body2.touching.none = false; + body2.touching.down = true; + } + } + + // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapY = overlap; + body2.overlapY = overlap; + + return overlap; + + }, + + /** + * The core separation function to separate two physics bodies on the x axis. + * + * @method Phaser.Physics.Arcade#separateX + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateX: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapX(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.x; + var v2 = body2.velocity.x; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.x -= overlap; + body2.x += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.x = avg + nv1 * body1.bounce.x; + body2.velocity.x = avg + nv2 * body2.bounce.x; + } + else if (!body1.immovable) + { + body1.x -= overlap; + body1.velocity.x = v2 - v1 * body1.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body2.moves) + { + body1.y += (body2.y - body2.prev.y) * body2.friction.y; + } + } + else + { + body2.x += overlap; + body2.velocity.x = v1 - v2 * body2.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body1.moves) + { + body2.y += (body1.y - body1.prev.y) * body1.friction.y; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * The core separation function to separate two physics bodies on the y axis. + * + * @private + * @method Phaser.Physics.Arcade#separateY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateY: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapY(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.y; + var v2 = body2.velocity.y; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.y -= overlap; + body2.y += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.y = avg + nv1 * body1.bounce.y; + body2.velocity.y = avg + nv2 * body2.bounce.y; + } + else if (!body1.immovable) + { + body1.y -= overlap; + body1.velocity.y = v2 - v1 * body1.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body2.moves) + { + body1.x += (body2.x - body2.prev.x) * body2.friction.x; + } + } + else + { + body2.y += overlap; + body2.velocity.y = v1 - v2 * body2.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body1.moves) + { + body2.x += (body1.x - body1.prev.x) * body1.friction.x; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. + * + * @method Phaser.Physics.Arcade#getObjectsUnderPointer + * @param {Phaser.Pointer} pointer - The Pointer to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. + * @param {object} [callbackContext] - The context in which to run the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates. + */ + getObjectsUnderPointer: function (pointer, group, callback, callbackContext) { + + if (group.length === 0 || !pointer.exists) + { + return; + } + + return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer); + + }, + + /** + * Given a Group and a location this will check to see which Group children overlap with the coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. + * + * @method Phaser.Physics.Arcade#getObjectsAtLocation + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. + * @param {object} [callbackContext] - The context in which to run the callback. + * @param {object} [callbackArg] - An argument to pass to the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates. + */ + getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) { + + 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(x, y, 1, 1); + var output = []; + + var items = this.quadTree.retrieve(rect); + + for (var i = 0; i < items.length; i++) + { + if (items[i].hitTest(x, y)) + { + if (callback) + { + callback.call(callbackContext, callbackArg, items[i].sprite); + } + + output.push(items[i].sprite); + } + } + + return output; + + }, + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToObject: function (displayObject, destination, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Phaser.Point.angle(destination, displayObject); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#moveToPointer + * @param {any} displayObject - The display object to move. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToPointer: function (displayObject, speed, pointer, maxTime) { + + if (speed === undefined) { speed = 60; } + pointer = pointer || this.game.input.activePointer; + if (maxTime === undefined) { maxTime = 0; } + + var angle = this.angleToPointer(displayObject, pointer); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToXY: function (displayObject, x, y, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Math.atan2(y - displayObject.y, x - displayObject.x); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromAngle + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromAngle: function (angle, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(angle, speed, true); + + }, + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. + * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. + * + * @method Phaser.Physics.Arcade#accelerationFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. + * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. + */ + accelerationFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleBetween(displayObject, destination); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToPointer + * @param {any} displayObject - The display object to move. + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToPointer(displayObject, pointer); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToXY(displayObject, x, y); + + displayObject.body.acceleration.setTo(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Find the distance between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * If you have nested objects and need to calculate the distance between their centers in World coordinates, + * set their anchors to (0.5, 0.5) and use the `world` argument. + * + * If objects aren't nested or they share a parent's offset, you can calculate the distance between their + * centers with the `useCenter` argument, regardless of their anchor values. + * + * @method Phaser.Physics.Arcade#distanceBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {number} The distance between the source and target objects. + */ + distanceBetween: function (source, target, world, useCenter) { + + if (world === undefined) { world = false; } + + var dx; + var dy; + + if (useCenter) + { + dx = source.centerX - target.centerX; + dy = source.centerY - target.centerY; + } + else if (world) + { + dx = source.world.x - target.world.x; + dy = source.world.y - target.world.y; + } + else + { + dx = source.x - target.x; + dy = source.y - target.y; + } + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and the given x/y coordinates. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the x/y coordinates. + */ + distanceToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - x : displayObject.x - x; + var dy = (world) ? displayObject.world.y - y : displayObject.y - y; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the Pointer. + */ + distanceToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.x - pointer.worldX; + var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + + /** + * From a set of points or display objects, find the one closest to a source point or object. + * + * @method Phaser.Physics.Arcade#closest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The first target closest to the origin. + */ + closest: function (source, targets, world, useCenter) { + var min = Infinity; + var closest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance < min) + { + closest = target; + min = distance; + } + } + + return closest; + }, + + /** + * From a set of points or display objects, find the one farthest from a source point or object. + * + * @method Phaser.Physics.Arcade#farthest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The target closest to the origin. + */ + farthest: function (source, targets, world, useCenter) { + var max = -1; + var farthest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance > max) + { + farthest = target; + max = distance; + } + } + + return farthest; + }, + + /** + * Find the angle in radians between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetween: function (source, target, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Phaser.Point.angle(target.world, source.world); + } + else + { + return Phaser.Point.angle(target, source); + } + + }, + + /** + * Find the angle in radians between centers of two display objects (like Sprites). + * + * @method Phaser.Physics.Arcade#angleBetweenCenters + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetweenCenters: function (source, target) { + + var dx = target.centerX - source.centerX; + var dy = target.centerY - source.centerY; + + return Math.atan2(dy, dx); + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to get the angle to. + * @param {number} y - The y coordinate to get the angle to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(y - displayObject.world.y, x - displayObject.world.x); + } + else + { + return Math.atan2(y - displayObject.y, x - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x); + } + else + { + return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, + * taking their x/y and center into account relative to the world. + * + * @method Phaser.Physics.Arcade#worldAngleToPointer + * @param {any} displayObject - The DisplayObjerct to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY + */ + worldAngleToPointer: function (displayObject, pointer) { + + return this.angleToPointer(displayObject, pointer, true); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than +* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. +* +* @class Phaser.Physics.Arcade.Body +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. +*/ +Phaser.Physics.Arcade.Body = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = sprite.game; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.ARCADE; + + /** + * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. + * @default + */ + this.enable = true; + + /** + * If `true` this Body is using circular collision detection. If `false` it is using rectangular. + * Use `Body.setCircle` to control the collision shape this Body uses. + * @property {boolean} isCircle + * @default + * @readOnly + */ + this.isCircle = false; + + /** + * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled, relative to the Sprite's _texture_. + * If you wish to change the radius then call {@link #setCircle} again with the new value. + * If you wish to stop the Body using a circle then call {@link #setCircle} with a radius of zero (or undefined). + * The actual radius of the Body (at any Sprite scale) is equal to {@link #halfWidth} and the diameter is equal to {@link #width}. + * @property {number} radius + * @default + * @readOnly + */ + this.radius = 0; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite's texture. + */ + this.offset = new Phaser.Point(); + + /** + * @property {Phaser.Point} position - The position of the physics body, equivalent to ({@link #left}, {@link #top}). + * @readonly + */ + this.position = new Phaser.Point(sprite.x, sprite.y); + + /** + * @property {Phaser.Point} prev - The previous position of the physics body. + * @readonly + */ + this.prev = new Phaser.Point(this.position.x, this.position.y); + + /** + * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) + * @default + */ + this.allowRotation = true; + + /** + * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body + * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. + * @property {number} rotation + */ + this.rotation = sprite.angle; + + /** + * @property {number} preRotation - The previous rotation of the physics body, in degrees. + * @readonly + */ + this.preRotation = sprite.angle; + + /** + * @property {number} width - The calculated width of the physics body. + * @readonly + */ + this.width = sprite.width; + + /** + * @property {number} height - The calculated height of the physics body. + * @readonly + */ + this.height = sprite.height; + + /** + * @property {number} sourceWidth - The un-scaled original size. + * @readonly + */ + this.sourceWidth = sprite.width; + + /** + * @property {number} sourceHeight - The un-scaled original size. + * @readonly + */ + this.sourceHeight = sprite.height; + + if (sprite.texture) + { + this.sourceWidth = sprite.texture.frame.width; + this.sourceHeight = sprite.texture.frame.height; + } + + /** + * @property {number} halfWidth - The calculated width / 2 of the physics body. + * @readonly + */ + this.halfWidth = Math.abs(sprite.width / 2); + + /** + * @property {number} halfHeight - The calculated height / 2 of the physics body. + * @readonly + */ + this.halfHeight = Math.abs(sprite.height / 2); + + /** + * @property {Phaser.Point} center - The center coordinate of the Physics Body. + * @readonly + */ + this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight); + + /** + * @property {Phaser.Point} velocity - The velocity, or rate of change the Body's position. Measured in pixels per second. + */ + this.velocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} newVelocity - The distanced traveled during the last update, equal to `velocity * physicsElapsed`. Calculated during the Body.preUpdate and applied to its position. + * @readonly + */ + this.newVelocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. + */ + this.deltaMax = new Phaser.Point(); + + /** + * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + */ + this.acceleration = new Phaser.Point(); + + /** + * @property {boolean} allowDrag - Allow this Body to be influenced by {@link #drag}? + * @default + */ + this.allowDrag = true; + + /** + * @property {Phaser.Point} drag - The drag applied to the motion of the Body (when {@link #allowDrag} is enabled). Measured in pixels per second squared. + */ + this.drag = new Phaser.Point(); + + /** + * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local. + * @default + */ + this.allowGravity = true; + + /** + * @property {Phaser.Point} gravity - This Body's local gravity, **added** to any world gravity, unless Body.allowGravity is set to false. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. + */ + this.bounce = new Phaser.Point(); + + /** + * The elasticity of the Body when colliding with the World bounds. + * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property + * to a Phaser.Point object in order to enable a World bounds specific bounce value. + * @property {Phaser.Point} worldBounce + */ + this.worldBounce = null; + + /** + * A Signal that is dispatched when this Body collides with the world bounds. + * Due to the potentially high volume of signals this could create it is disabled by default. + * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` + * and it will be called when a collision happens, passing five arguments: + * `onWorldBounds(sprite, up, down, left, right)` + * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans + * indicating on which side of the world the Body collided. + * @property {Phaser.Signal} onWorldBounds + */ + this.onWorldBounds = null; + + /** + * A Signal that is dispatched when this Body collides with another Body. + * + * You still need to call `game.physics.arcade.collide` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `collide` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onCollide + */ + this.onCollide = null; + + /** + * A Signal that is dispatched when this Body overlaps with another Body. + * + * You still need to call `game.physics.arcade.overlap` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `overlap` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onOverlap + */ + this.onOverlap = null; + + /** + * @property {Phaser.Point} maxVelocity - The maximum velocity (in pixels per second squared) that the Body can reach. + * @default + */ + this.maxVelocity = new Phaser.Point(10000, 10000); + + /** + * @property {Phaser.Point} friction - If this Body is {@link #immovable} and moving, and another Body is 'riding' this one, this is the amount of motion the riding Body receives on each axis. + */ + this.friction = new Phaser.Point(1, 0); + + /** + * @property {number} angularVelocity - The angular velocity is the rate of change of the Body's rotation. It is measured in degrees per second. + * @default + */ + this.angularVelocity = 0; + + /** + * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. + * @default + */ + this.angularAcceleration = 0; + + /** + * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach. + * @default + */ + this.maxAngular = 1000; + + /** + * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. + * @default + */ + this.mass = 1; + + /** + * @property {number} angle - The angle of the Body's **velocity** in radians. + * @readonly + */ + this.angle = 0; + + /** + * @property {number} speed - The speed of the Body in pixels per second, equal to the magnitude of the velocity. + * @readonly + */ + this.speed = 0; + + /** + * @property {number} facing - A const reference to the direction the Body is traveling or facing: Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.UP, or Phaser.DOWN. If the Body is moving on both axes, UP and DOWN take precedence. + * @default + */ + this.facing = Phaser.NONE; + + /** + * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. **Two** immovable Bodies can't separate or exchange momentum and will pass through each other. + * @default + */ + this.immovable = false; + + /** + * Whether the physics system should update the Body's position and rotation based on its velocity, acceleration, drag, and gravity. + * + * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never + * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. + * If you want the physics system to move the body around, then set moves to true. + * + * A Body with moves = false can still be moved slightly (but not accelerated) during collision separation unless you set {@link #immovable} as well. + * + * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually. + * @default + */ + this.moves = true; + + /** + * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateX = false; + + /** + * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateY = false; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapX - The amount of horizontal overlap during the collision. + */ + this.overlapX = 0; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapY - The amount of vertical overlap during the collision. + */ + this.overlapY = 0; + + /** + * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. + * @property {number} overlapR - The amount of overlap during the collision. + */ + this.overlapR = 0; + + /** + * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. + * @property {boolean} embedded - Body embed value. + */ + this.embedded = false; + + /** + * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. + * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? + */ + this.collideWorldBounds = false; + + /** + * Set the checkCollision properties to control which directions collision is processed for this Body. + * For example checkCollision.up = false means it won't collide when the collision happened while moving up. + * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. + * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. + * @property {object} checkCollision - An object containing allowed collision (none, up, down, left, right). + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * This object is populated with boolean values when the Body collides with another. + * touching.up = true means the collision happened to the top of this Body for example. + * @property {object} touching - An object containing touching results (none, up, down, left, right). + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with previous touching values from the bodies previous collision. + * @property {object} wasTouching - An object containing previous touching results (none, up, down, left, right). + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with boolean values when the Body collides with the World bounds or a Tile. + * For example if blocked.up is true then the Body cannot move up. + * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any (none, up, down, left, right). + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. + * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. + * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision. + */ + this.tilePadding = new Phaser.Point(); + + /** + * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state? + */ + this.dirty = false; + + /** + * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. + */ + this.skipQuadTree = false; + + /** + * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. + * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. + * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, + * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. + * @property {boolean} syncBounds + * @default + */ + this.syncBounds = false; + + /** + * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods. + */ + this.isMoving = false; + + /** + * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods. + */ + this.stopVelocityOnCollide = true; + + /** + * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveTimer = 0; + + /** + * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDistance = 0; + + /** + * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDuration = 0; + + /** + * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveTarget = null; + + /** + * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveEnd = null; + + /** + * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events. + */ + this.onMoveComplete = new Phaser.Signal(); + + /** + * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. + */ + this.movementCallback = null; + + /** + * @property {object} movementCallbackContext - Context in which to call the movementCallback. + */ + this.movementCallbackContext = null; + + /** + * @property {boolean} _reset - Internal cache var. + * @private + */ + this._reset = true; + + /** + * @property {number} _sx - Internal cache var. + * @private + */ + this._sx = sprite.scale.x; + + /** + * @property {number} _sy - Internal cache var. + * @private + */ + this._sy = sprite.scale.y; + + /** + * @property {number} _dx - Internal cache var. + * @private + */ + this._dx = 0; + + /** + * @property {number} _dy - Internal cache var. + * @private + */ + this._dy = 0; + +}; + +Phaser.Physics.Arcade.Body.prototype = { + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @protected + */ + updateBounds: function () { + + if (this.syncBounds) + { + var b = this.sprite.getBounds(); + b.ceilAll(); + + if (b.width !== this.width || b.height !== this.height) + { + this.width = b.width; + this.height = b.height; + this._reset = true; + } + } + else + { + 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._sx = asx; + this._sy = asy; + this._reset = true; + } + } + + if (this._reset) + { + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.updateCenter(); + } + + }, + + /** + * Update the Body's center from its position. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @protected + */ + updateCenter: function () { + + this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @protected + */ + preUpdate: function () { + + if (!this.enable || this.game.physics.arcade.isPaused) + { + return; + } + + this.dirty = true; + + // Store and reset collision flags + 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.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; + + this.overlapR = 0; + this.overlapX = 0; + this.overlapY = 0; + + this.embedded = false; + + this.updateBounds(); + + this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.updateCenter(); + + this.rotation = this.sprite.angle; + + this.preRotation = this.rotation; + + if (this._reset || this.sprite.fresh) + { + 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; + this.updateCenter(); + + if (this.position.x !== this.prev.x || this.position.y !== this.prev.y) + { + this.angle = this.velocity.atan(); + } + + this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); + + // Now the State update will throw collision checks at the Body + // And finally we'll integrate the new position back to the Sprite in postUpdate + + if (this.collideWorldBounds) + { + if (this.checkWorldBounds() && this.onWorldBounds) + { + this.onWorldBounds.dispatch(this.sprite, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); + } + } + } + + this._dx = this.deltaX(); + this._dy = this.deltaY(); + + this._reset = false; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateMovement + * @protected + */ + updateMovement: function () { + + var percent = 0; + var collided = (this.overlapX !== 0 || this.overlapY !== 0); + + // Duration or Distance based? + + if (this.moveDuration > 0) + { + this.moveTimer += this.game.time.elapsedMS; + + percent = this.moveTimer / this.moveDuration; + } + else + { + this.moveTarget.end.set(this.position.x, this.position.y); + + percent = this.moveTarget.length / this.moveDistance; + } + + if (this.movementCallback) + { + var result = this.movementCallback.call(this.movementCallbackContext, this, this.velocity, percent); + } + + if (collided || percent >= 1 || (result !== undefined && result !== true)) + { + this.stopMovement((percent >= 1) || (this.stopVelocityOnCollide && collided)); + return false; + } + + return true; + + }, + + /** + * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it + * has Body.isMoving true), then calling this method will stop the movement before + * either the duration or distance counters expire. + * + * The `onMoveComplete` signal is dispatched. + * + * @method Phaser.Physics.Arcade.Body#stopMovement + * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero? + */ + stopMovement: function (stopVelocity) { + + if (this.isMoving) + { + this.isMoving = false; + + if (stopVelocity) + { + this.velocity.set(0); + } + + // Send the Sprite this Body belongs to + // and a boolean indicating if it stopped because of a collision or not + this.onMoveComplete.dispatch(this.sprite, (this.overlapX !== 0 || this.overlapY !== 0)); + } + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @protected + */ + postUpdate: function () { + + // Only allow postUpdate to be called once per frame + if (!this.enable || !this.dirty) + { + return; + } + + // Moving? + if (this.isMoving) + { + this.updateMovement(); + } + + this.dirty = false; + + 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.position.x += this._dx; + this.sprite.position.y += this._dy; + this._reset = true; + } + + this.updateCenter(); + + if (this.allowRotation) + { + this.sprite.angle += this.deltaZ(); + } + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @protected + * @return {boolean} True if the Body collided with the world bounds, otherwise false. + */ + checkWorldBounds: function () { + + var pos = this.position; + var bounds = this.game.physics.arcade.bounds; + var check = this.game.physics.arcade.checkCollision; + + var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; + var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; + + if (pos.x < bounds.x && check.left) + { + pos.x = bounds.x; + this.velocity.x *= bx; + this.blocked.left = true; + this.blocked.none = false; + } + else if (this.right > bounds.right && check.right) + { + pos.x = bounds.right - this.width; + this.velocity.x *= bx; + this.blocked.right = true; + this.blocked.none = false; + } + + if (pos.y < bounds.y && check.up) + { + pos.y = bounds.y; + this.velocity.y *= by; + this.blocked.up = true; + this.blocked.none = false; + } + else if (this.bottom > bounds.bottom && check.down) + { + pos.y = bounds.bottom - this.height; + this.velocity.y *= by; + this.blocked.down = true; + this.blocked.none = false; + } + + return !this.blocked.none; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal timer, and then + * monitoring the duration each frame. When the duration is up the movement is + * stopped and the `Body.onMoveComplete` signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * You can optionally set a speed in pixels per second. If not specified it + * will use the current `Body.speed` value. If this is zero, the function will return false. + * + * Please note that due to browser timings you should allow for a variance in + * when the duration will actually expire. Depending on system it may be as much as + * +- 50ms. Also this method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveFrom + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveFrom: function (duration, speed, direction) { + + if (speed === undefined) { speed = this.speed; } + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + this.moveTimer = 0; + this.moveDuration = duration; + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal distance counter. + * The distance is monitored each frame. When the distance equals the distance + * specified in this call, the movement is stopped, and the `Body.onMoveComplete` + * signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * Please note that due to browser timings you should allow for a variance in + * when the distance will actually expire. + * + * Note: This method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveTo + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} distance - The distance, in pixels, the Body will move. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveTo: function (duration, distance, direction) { + + var speed = distance / (duration / 1000); + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + distance = Math.abs(distance); + + this.moveDuration = 0; + this.moveDistance = distance; + + if (this.moveTarget === null) + { + this.moveTarget = new Phaser.Line(); + this.moveEnd = new Phaser.Point(); + } + + this.moveTarget.fromAngle(this.x, this.y, angle, distance); + + this.moveEnd.set(this.moveTarget.end.x, this.moveTarget.end.y); + + this.moveTarget.setTo(this.x, this.y, this.x, this.y); + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * You can modify the size of the physics Body to be any dimension you need. + * This allows you to make it smaller, or larger, than the parent Sprite. You + * can also control the x and y offset of the Body. + * + * The width, height, and offset arguments are relative to the Sprite + * _texture_ and are scaled with the Sprite's {@link Phaser.Sprite#scale} + * (but **not** the scale of any ancestors or the {@link Phaser.Camera#scale + * Camera scale}). + * + * For example: If you have a Sprite with a texture that is 80x100 in size, + * and you want the physics body to be 32x32 pixels in the middle of the + * texture, you would do: + * + * `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, + * 34)` + * + * Where the first two parameters are the new Body size (32x32 pixels) + * relative to the Sprite's scale. 24 is the horizontal offset of the Body + * from the top-left of the Sprites texture, and 34 is the vertical offset. + * + * If you've scaled a Sprite by altering its `width`, `height`, or `scale` + * and you want to position the Body relative to the Sprite's dimensions + * (which will differ from its texture's dimensions), you should divide these + * arguments by the Sprite's current scale: + * + * `setSize(32 / sprite.scale.x, 32 / sprite.scale.y)` + * + * Calling `setSize` on a Body that has already had `setCircle` will reset + * all of the Circle properties, making this Body rectangular again. + * @method Phaser.Physics.Arcade.Body#setSize + * @param {number} width - The width of the Body, relative to the Sprite's + * texture. + * @param {number} height - The height of the Body, relative to the Sprite's + * texture. + * @param {number} [offsetX] - The X offset of the Body from the left of the + * Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the + * Sprite's texture. + */ + setSize: function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { 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.updateCenter(); + + this.isCircle = false; + this.radius = 0; + + }, + + /** + * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. + * The radius is given in pixels (relative to the Sprite's _texture_) and is the distance from the center of the circle to the edge. + * + * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite's texture. + * + * To change a Body back to being rectangular again call `Body.setSize`. + * + * Note: Circular collision only happens with other Arcade Physics bodies, it does not + * work against tile maps, where rectangular collision is the only method supported. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. + * @param {number} [offsetX] - The X offset of the Body from the left of the Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the Sprite's texture. + */ + setCircle: function (radius, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.isCircle = true; + this.radius = radius; + + this.sourceWidth = radius * 2; + this.sourceHeight = radius * 2; + + 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.updateCenter(); + } + else + { + this.isCircle = false; + } + + }, + + /** + * Resets all Body values (velocity, acceleration, rotation, etc) + * + * @method Phaser.Physics.Arcade.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new y position of the Body. + */ + reset: function (x, y) { + + this.stop(); + + this.position.x = (x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + this.rotation = this.sprite.angle; + this.preRotation = this.rotation; + + this.updateBounds(); + + this.updateCenter(); + + }, + + /** + * Sets acceleration, velocity, and {@link #speed} to 0. + * + * @method Phaser.Physics.Arcade.Body#stop + */ + stop: function () { + + this.velocity.set(0); + this.acceleration.set(0); + this.speed = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + + }, + + /** + * Returns the bounds of this physics body. + * + * Only used internally by the World collision methods. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @param {object} obj - The object in which to set the bounds values. + * @return {object} The object that was given to this method. + */ + getBounds: function (obj) { + + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + + }, + + /** + * Tests if a world point lies within this Body. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @param {number} x - The world x coordinate to test. + * @param {number} y - The world y coordinate to test. + * @return {boolean} True if the given coordinates are inside this Body, otherwise false. + */ + hitTest: function (x, y) { + + return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Returns true if the bottom of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onFloor: function () { + + return this.blocked.down; + + }, + + /** + * Returns true if the top of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onCeiling: function(){ + + return this.blocked.up; + + }, + + /** + * Returns true if either side of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onWall: function () { + + return (this.blocked.left || this.blocked.right); + + }, + + /** + * Returns the absolute delta x value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @return {number} The absolute delta value. + */ + deltaAbsX: function () { + + return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); + + }, + + /** + * Returns the absolute delta y value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @return {number} The absolute delta value. + */ + deltaAbsY: function () { + + return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); + + }, + + /** + * Returns the delta x value. The difference between Body.x now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. + */ + deltaX: function () { + + return this.position.x - this.prev.x; + + }, + + /** + * Returns the delta y value. The difference between Body.y now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. + */ + deltaY: function () { + + return this.position.y - this.prev.y; + + }, + + /** + * Returns the delta z value. The difference between Body.rotation now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise. + */ + deltaZ: function () { + + return this.rotation - this.preRotation; + + }, + + /** + * Destroys this Body. + * + * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. + * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. + * + * @method Phaser.Physics.Arcade.Body#destroy + */ + destroy: function () { + + if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group) + { + this.sprite.parent.removeFromHash(this.sprite); + } + + this.sprite.body = null; + this.sprite = null; + + } + +}; + +/** +* @name Phaser.Physics.Arcade.Body#left +* @property {number} left - The x position of the Body. The same as `Body.x`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "left", { + + get: function () { + + return this.position.x; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#right +* @property {number} right - The right value of this Body (same as Body.x + Body.width) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", { + + get: function () { + + return this.position.x + this.width; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#top +* @property {number} top - The y position of the Body. The same as `Body.y`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "top", { + + get: function () { + + return this.position.y; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#bottom +* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", { + + get: function () { + + return this.position.y + this.height; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#x +* @property {number} x - The x position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#y +* @property {number} y - The y position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + +}); + +/** +* Render Sprite Body. +* +* @method Phaser.Physics.Arcade.Body#render +* @param {object} context - The context to render to. +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string). +* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) +* @param {number} [lineWidth=1] - The width of the stroke when unfilled. +*/ +Phaser.Physics.Arcade.Body.render = function (context, body, color, filled, lineWidth) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0,255,0,0.4)'; + + context.fillStyle = color; + context.strokeStyle = color; + context.lineWidth = lineWidth || 1; + + if (body.isCircle) + { + context.beginPath(); + context.arc(body.center.x - body.game.camera.x, body.center.y - body.game.camera.y, body.halfWidth, 0, 2 * Math.PI); + + if (filled) + { + context.fill(); + } + else + { + context.stroke(); + } + } + else + { + if (filled) + { + context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + else + { + context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + } + +}; + +/** +* Render Sprite Body Physics Data as text. +* +* @method Phaser.Physics.Arcade.Body#renderBodyInfo +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {number} x - X position of the debug info to be rendered. +* @param {number} y - Y position of the debug info to be rendered. +* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). +*/ +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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics Tile map collision methods. +* +* @class Phaser.Physics.Arcade.TilemapCollision +* @constructor +*/ +Phaser.Physics.Arcade.TilemapCollision = function () {}; + +Phaser.Physics.Arcade.TilemapCollision.prototype = { + + /** + * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling. + */ + TILE_BIAS: 16, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!sprite.body) + { + return; + } + + var mapData = tilemapLayer.getTiles( + sprite.body.position.x - sprite.body.tilePadding.x - tilemapLayer.getTileOffsetX(), + sprite.body.position.y - sprite.body.tilePadding.y - tilemapLayer.getTileOffsetY(), + sprite.body.width + sprite.body.tilePadding.x, + sprite.body.height + sprite.body.tilePadding.y, + false, false); + + if (mapData.length === 0) + { + return; + } + + for (var i = 0; i < mapData.length; i++) + { + if (processCallback) + { + if (processCallback.call(callbackContext, sprite, mapData[i])) + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + else + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @private + * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer + * @param {Phaser.Group} group - The Group to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.children.length; i++) + { + if (group.children[i].exists) + { + this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * The core separation function to separate a physics body and a tile. + * + * @private + * @method Phaser.Physics.Arcade#separateTile + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to collide against. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {boolean} Returns true if the body was separated, otherwise false. + */ + separateTile: function (i, body, tile, tilemapLayer, overlapOnly) { + + if (!body.enable) + { + return false; + } + + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + // We re-check for collision in case body was separated in a previous step + if (!tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + // no collision so bail out (separated in a previous step) + return false; + } + else if (overlapOnly) + { + // There is an overlap, and we don't need to separate. Bail. + return true; + } + + // They overlap. Any custom callbacks? + + // A local callback always takes priority over a layer level callback + if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + else if (typeof tile.layer.callbacks !== 'undefined' && tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + + // We don't need to go any further if this tile doesn't actually separate + if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom) + { + // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation + return false; + } + + var ox = 0; + var oy = 0; + var minX = 0; + var minY = 1; + + if (body.deltaAbsX() > body.deltaAbsY()) + { + // Moving faster horizontally, check X axis first + minX = -1; + } + else if (body.deltaAbsX() < body.deltaAbsY()) + { + // Moving faster vertically, check Y axis first + minY = -1; + } + + if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom)) + { + // We only need do this if both axis have checking faces AND we're moving in both directions + minX = Math.min(Math.abs((body.position.x - tilemapLayerOffsetX) - tile.right), Math.abs((body.right - tilemapLayerOffsetX) - tile.left)); + minY = Math.min(Math.abs((body.position.y - tilemapLayerOffsetY) - tile.bottom), Math.abs((body.bottom - tilemapLayerOffsetY) - tile.top)); + } + + if (minX < minY) + { + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + + // That's horizontal done, check if we still intersects? If not then we can return now + if (ox !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + } + } + else + { + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + + // That's vertical done, check if we still intersects? If not then we can return now + if (oy !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + } + } + + return (ox !== 0 || oy !== 0); + + }, + + /** + * Check the body against the given tile on the X axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckX: function (body, tile, tilemapLayer) { + + var ox = 0; + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + + if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left) + { + // Body is moving LEFT + if (tile.faceRight && (body.x - tilemapLayerOffsetX) < tile.right) + { + ox = (body.x - tilemapLayerOffsetX) - tile.right; + + if (ox < -this.TILE_BIAS) + { + ox = 0; + } + } + } + else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right) + { + // Body is moving RIGHT + if (tile.faceLeft && (body.right - tilemapLayerOffsetX) > tile.left) + { + ox = (body.right - tilemapLayerOffsetX) - tile.left; + + if (ox > this.TILE_BIAS) + { + ox = 0; + } + } + } + + if (ox !== 0) + { + if (body.customSeparateX) + { + body.overlapX = ox; + } + else + { + this.processTileSeparationX(body, ox); + } + } + + return ox; + + }, + + /** + * Check the body against the given tile on the Y axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckY: function (body, tile, tilemapLayer) { + + var oy = 0; + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up) + { + // Body is moving UP + if (tile.faceBottom && (body.y - tilemapLayerOffsetY) < tile.bottom) + { + oy = (body.y - tilemapLayerOffsetY) - tile.bottom; + + if (oy < -this.TILE_BIAS) + { + oy = 0; + } + } + } + else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down) + { + // Body is moving DOWN + if (tile.faceTop && (body.bottom - tilemapLayerOffsetY) > tile.top) + { + oy = (body.bottom - tilemapLayerOffsetY) - tile.top; + + if (oy > this.TILE_BIAS) + { + oy = 0; + } + } + } + + if (oy !== 0) + { + if (body.customSeparateY) + { + body.overlapY = oy; + } + else + { + this.processTileSeparationY(body, oy); + } + } + + return oy; + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} x - The x separation amount. + */ + processTileSeparationX: function (body, x) { + + if (x < 0) + { + body.blocked.left = true; + body.blocked.none = false; + } + else if (x > 0) + { + body.blocked.right = true; + body.blocked.none = false; + } + + body.position.x -= x; + + if (body.bounce.x === 0) + { + body.velocity.x = 0; + } + else + { + body.velocity.x = -body.velocity.x * body.bounce.x; + } + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} y - The y separation amount. + */ + processTileSeparationY: function (body, y) { + + if (y < 0) + { + body.blocked.up = true; + body.blocked.none = false; + } + else if (y > 0) + { + body.blocked.down = true; + body.blocked.none = false; + } + + body.position.y -= y; + + if (body.bounce.y === 0) + { + body.velocity.y = 0; + } + else + { + body.velocity.y = -body.velocity.y * body.bounce.y; + } + + } + +}; + +// Merge this with the Arcade Physics prototype +Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Add an extra properties to p2 that we need +p2.Body.prototype.parent = null; +p2.Spring.prototype.parent = null; + +/** +* This is your main access to the P2 Physics World. +* From here you can create materials, listen for events and add bodies into the physics simulation. +* +* @class Phaser.Physics.P2 +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {object} [config] - Physics configuration object passed in from the game constructor. +*/ +Phaser.Physics.P2 = function (game, config) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + if (config === undefined) + { + config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; + } + else + { + if (!config.hasOwnProperty('gravity')) + { + config.gravity = [0, 0]; + } + + if (!config.hasOwnProperty('broadphase')) + { + config.broadphase = new p2.SAPBroadphase(); + } + } + + /** + * @property {object} config - The p2 World configuration object. + * @protected + */ + this.config = config; + + /** + * @property {p2.World} world - The p2 World in which the simulation is run. + * @protected + */ + this.world = new p2.World(this.config); + + /** + * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. + * @default + */ + this.frameRate = 1 / 60; + + /** + * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. + * @default + */ + this.useElapsedTime = false; + + /** + * @property {boolean} paused - The paused state of the P2 World. + * @default + */ + this.paused = false; + + /** + * @property {array} materials - A local array of all created Materials. + * @protected + */ + this.materials = []; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. + */ + this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); + + /** + * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * This signal is dispatched when a new Body is added to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world. + * + * @property {Phaser.Signal} onBodyAdded + */ + this.onBodyAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Body is removed to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world. + * + * @property {Phaser.Signal} onBodyRemoved + */ + this.onBodyRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is added to the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world. + * + * @property {Phaser.Signal} onSpringAdded + */ + this.onSpringAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is removed from the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world. + * + * @property {Phaser.Signal} onSpringRemoved + */ + this.onSpringRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is added to the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world. + * + * @property {Phaser.Signal} onConstraintAdded + */ + this.onConstraintAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is removed from the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world. + * + * @property {Phaser.Signal} onConstraintRemoved + */ + this.onConstraintRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is added to the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world. + * + * @property {Phaser.Signal} onContactMaterialAdded + */ + this.onContactMaterialAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is removed from the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world. + * + * @property {Phaser.Signal} onContactMaterialRemoved + */ + this.onContactMaterialRemoved = new Phaser.Signal(); + + /** + * @property {function} postBroadphaseCallback - A postBroadphase callback. + */ + this.postBroadphaseCallback = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are fired. + */ + this.callbackContext = null; + + /** + * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done. + * + * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done. + * + * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + // Pixel to meter function overrides + if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) + { + this.mpx = config.mpx; + this.mpxi = config.mpxi; + this.pxm = config.pxm; + this.pxmi = config.pxmi; + } + + // Hook into the World events + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + /** + * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. + */ + this.collisionGroups = []; + + /** + * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. + */ + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. + */ + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. + */ + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + /** + * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. + */ + this.boundsCollidesWith = []; + + /** + * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. + * @private + */ + this._toRemove = []; + + /** + * @property {number} _collisionGroupID - Internal var. + * @private + */ + this._collisionGroupID = 2; + + /** + * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsLeft = true; + + /** + * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsRight = true; + + /** + * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsTop = true; + + /** + * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsBottom = true; + + /** + * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsOwnGroup = false; + + // By default we want everything colliding with everything + this.setBoundsToWorld(true, true, true, true, false); + +}; + +Phaser.Physics.P2.prototype = { + + /** + * This will add a P2 Physics body into the removal list for the next step. + * + * @method Phaser.Physics.P2#removeBodyNextStep + * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. + */ + removeBodyNextStep: function (body) { + + this._toRemove.push(body); + + }, + + /** + * Called at the start of the core update loop. Purges flagged bodies from the world. + * + * @method Phaser.Physics.P2#preUpdate + */ + preUpdate: function () { + + var i = this._toRemove.length; + + while (i--) + { + this.removeBody(this._toRemove[i]); + } + + this._toRemove.length = 0; + + }, + + /** + * This will create a P2 Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. + * + * @method Phaser.Physics.P2#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [debug=false] - Create a debug object to go with this body? + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, debug, children) { + + if (debug === undefined) { debug = false; } + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + this.enable(object[i].children, debug, children); + } + else + { + this.enableBody(object[i], debug); + + if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) + { + this.enable(object[i], debug, true); + } + } + } + } + else + { + if (object instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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); + } + } + } + + }, + + /** + * Creates a P2 Physics body on the given game object. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * @method Phaser.Physics.P2#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + * @param {boolean} debug - Create a debug object to go with this body? + */ + 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; + if (typeof object.anchor !== 'undefined') { + object.anchor.set(0.5); + } + } + + }, + + /** + * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. + * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. + * + * @method Phaser.Physics.P2#setImpactEvents + * @param {boolean} state - Set to true to enable impact events, or false to disable. + */ + setImpactEvents: function (state) { + + if (state) + { + this.world.on("impact", this.impactHandler, this); + } + else + { + this.world.off("impact", this.impactHandler, this); + } + + }, + + /** + * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. + * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. + * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. + * Returning `true` from the callback will ensure they are checked in the narrowphase. + * + * @method Phaser.Physics.P2#setPostBroadphaseCallback + * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. + * @param {object} context - The context under which the callback will be fired. + */ + 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); + } + + }, + + /** + * Internal handler for the postBroadphase event. + * + * @method Phaser.Physics.P2#postBroadphaseHandler + * @private + * @param {object} event - The event data. + */ + postBroadphaseHandler: function (event) { + + if (!this.postBroadphaseCallback || event.pairs.length === 0) + { + return; + } + + for (var i = event.pairs.length - 2; i >= 0; 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); + } + } + + }, + + /** + * Handles a p2 impact event. + * + * @method Phaser.Physics.P2#impactHandler + * @private + * @param {object} event - The event data. + */ + impactHandler: function (event) { + + if (event.bodyA.parent && event.bodyB.parent) + { + // Body vs. Body callbacks + 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); + } + + // Body vs. Group callbacks + 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); + } + } + + }, + + /** + * Handles a p2 begin contact event. + * + * @method Phaser.Physics.P2#beginContactHandler + * @param {object} event - The event data. + */ + beginContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + 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.bodyB, event.shapeA, event.shapeB, event.contactEquations); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations); + } + } + + }, + + /** + * Handles a p2 end contact event. + * + * @method Phaser.Physics.P2#endContactHandler + * @param {object} event - The event data. + */ + endContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); + + if (event.bodyA.parent) + { + event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA); + } + } + + }, + + /** + * Sets the bounds of the Physics world to match the Game.World dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * + * @method Phaser.Physics#setBoundsToWorld + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + 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); + + }, + + /** + * Sets the given material against the 4 bounds of this World. + * + * @method Phaser.Physics#setWorldMaterial + * @param {Phaser.Physics.P2.Material} material - The material to set. + * @param {boolean} [left=true] - If true will set the material on the left bounds wall. + * @param {boolean} [right=true] - If true will set the material on the right bounds wall. + * @param {boolean} [top=true] - If true will set the material on the top bounds wall. + * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. + */ + setWorldMaterial: function (material, left, right, top, bottom) { + + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (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; + } + + }, + + /** + * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. + * If you start to use your own collision groups then your objects will no longer collide with the bounds. + * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. + * + * @method Phaser.Physics.P2#updateBoundsCollisionGroup + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + updateBoundsCollisionGroup: function (setCollisionGroup) { + + if (setCollisionGroup === undefined) { setCollisionGroup = true; } + + var mask = (setCollisionGroup) ? this.boundsCollisionGroup.mask : this.everythingCollisionGroup.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; + } + + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.P2#setBounds + * @param {number} x - The x coordinate of the top-left corner of the bounds. + * @param {number} y - The y coordinate of the top-left corner of the bounds. + * @param {number} width - The width of the bounds. + * @param {number} height - The height of the bounds. + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { + + if (left === undefined) { left = this._boundsLeft; } + if (right === undefined) { right = this._boundsRight; } + if (top === undefined) { top = this._boundsTop; } + if (bottom === undefined) { bottom = this._boundsBottom; } + if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; } + + this.setupWall(left, 'left', x, y, 1.5707963267948966, setCollisionGroup); + this.setupWall(right, 'right', x + width, y, -1.5707963267948966, setCollisionGroup); + this.setupWall(top, 'top', x, y, -3.141592653589793, setCollisionGroup); + this.setupWall(bottom, 'bottom', x, y + height, 0, setCollisionGroup); + + // Remember the bounds settings in case they change later on via World.setBounds + this._boundsLeft = left; + this._boundsRight = right; + this._boundsTop = top; + this._boundsBottom = bottom; + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Internal method called by setBounds. Responsible for creating, updating or + * removing the wall body shapes. + * + * @method Phaser.Physics.P2#setupWall + * @private + * @param {boolean} create - True to create the wall shape, false to remove it. + * @param {string} wall - The wall segment to update. + * @param {number} x - The x coordinate of the wall. + * @param {number} y - The y coordinate of the wall. + * @param {float} angle - The angle of the wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setupWall: function (create, wall, x, y, angle, setCollisionGroup) { + + if (create) + { + // We need a left wall. Do we have one already? + if (this.walls[wall]) + { + this.walls[wall].position = [ this.pxmi(x), this.pxmi(y) ]; + } + else + { + this.walls[wall] = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: angle }); + this.walls[wall].addShape(new p2.Plane()); + + this.world.addBody(this.walls[wall]); + } + + if (setCollisionGroup) + { + this.walls[wall].shapes[0].collisionGroup = this.boundsCollisionGroup.mask; + } + } + else + { + if (this.walls[wall]) + { + this.world.removeBody(this.walls[wall]); + this.walls[wall] = null; + } + } + + }, + + /** + * Pauses the P2 World independent of the game pause state. + * + * @method Phaser.Physics.P2#pause + */ + pause: function() { + + this.paused = true; + + }, + + /** + * Resumes a paused P2 World. + * + * @method Phaser.Physics.P2#resume + */ + resume: function() { + + this.paused = false; + + }, + + /** + * Internal P2 update loop. + * + * @method Phaser.Physics.P2#update + */ + update: function () { + + // Do nothing if the physics engine was paused before + if (this.paused) + { + return; + } + + if (this.useElapsedTime) + { + this.world.step(this.game.time.physicsElapsed); + } + else + { + this.world.step(this.frameRate); + } + + }, + + /** + * Called by Phaser.Physics when a State swap occurs. + * Starts the begin and end Contact listeners again. + * + * @method Phaser.Physics.P2#reset + */ + reset: function () { + + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + this._collisionGroupID = 2; + + this.setBoundsToWorld(true, true, true, true, false); + + }, + + /** + * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. + * + * The P2 world is also cleared: + * + * * Removes all solver equations + * * Removes all constraints + * * Removes all bodies + * * Removes all springs + * * Removes all contact materials + * + * This is called automatically when you switch state. + * + * @method Phaser.Physics.P2#clear + */ + clear: function () { + + this.world.time = 0; + this.world.fixedStepTime = 0; + + // Remove all solver equations + if (this.world.solver && this.world.solver.equations.length) + { + this.world.solver.removeAllEquations(); + } + + // Remove all constraints + var cs = this.world.constraints; + + for (var i = cs.length - 1; i >= 0; i--) + { + this.world.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.world.bodies; + + for (var i = bodies.length - 1; i >= 0; i--) + { + this.world.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.world.springs; + + for (var i = springs.length - 1; i >= 0; i--) + { + this.world.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.world.contactMaterials; + + for (var i = cms.length - 1; i >= 0; i--) + { + this.world.removeContactMaterial(cms[i]); + } + + 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.boundsCollidesWith = []; + + // Remove the world bounds + this.walls = { left: null, right: null, top: null, bottom: null }; + + }, + + /** + * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. + * + * @method Phaser.Physics.P2#destroy + */ + destroy: function () { + + this.clear(); + + this.game = null; + + }, + + /** + * Add a body to the world. + * + * @method Phaser.Physics.P2#addBody + * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. + * @return {boolean} True if the Body was added successfully, otherwise false. + */ + addBody: function (body) { + + if (body.data.world) + { + return false; + } + else + { + this.world.addBody(body.data); + + this.onBodyAdded.dispatch(body); + + return true; + } + + }, + + /** + * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. + * + * @method Phaser.Physics.P2#removeBody + * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. + * @return {Phaser.Physics.P2.Body} The Body that was removed. + */ + removeBody: function (body) { + + if (body.data.world === this.world) + { + this.world.removeBody(body.data); + + this.onBodyRemoved.dispatch(body); + } + + return body; + + }, + + /** + * Adds a Spring to the world. + * + * @method Phaser.Physics.P2#addSpring + * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was added. + */ + addSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.addSpring(spring.data); + } + else + { + this.world.addSpring(spring); + } + + this.onSpringAdded.dispatch(spring); + + return spring; + + }, + + /** + * Removes a Spring from the world. + * + * @method Phaser.Physics.P2#removeSpring + * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was removed. + */ + removeSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.removeSpring(spring.data); + } + else + { + this.world.removeSpring(spring); + } + + this.onSpringRemoved.dispatch(spring); + + return spring; + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createDistanceConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} distance - The distance to keep between the bodies. + * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. + * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.DistanceConstraint} The constraint + */ + createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, 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, localAnchorA, localAnchorB, maxForce)); + } + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createGearConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [angle=0] - The relative angle + * @param {number} [ratio=1] - The gear ratio. + * @return {Phaser.Physics.P2.GearConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * The pivot points are given in world (pixel) coordinates. + * + * @method Phaser.Physics.P2#createRevoluteConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. + * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint + */ + createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + 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, worldPivot)); + } + + }, + + /** + * Locks the relative position between two bodies. + * + * @method Phaser.Physics.P2#createLockConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.LockConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Constraint that only allows bodies to move along a line, relative to each other. + * See http://www.iforce2d.net/b2dtut/joints-prismatic + * + * @method Phaser.Physics.P2#createPrismaticConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. + * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Adds a Constraint to the world. + * + * @method Phaser.Physics.P2#addConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. + */ + addConstraint: function (constraint) { + + this.world.addConstraint(constraint); + + this.onConstraintAdded.dispatch(constraint); + + return constraint; + + }, + + /** + * Removes a Constraint from the world. + * + * @method Phaser.Physics.P2#removeConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. + */ + removeConstraint: function (constraint) { + + this.world.removeConstraint(constraint); + + this.onConstraintRemoved.dispatch(constraint); + + return constraint; + + }, + + /** + * Adds a Contact Material to the world. + * + * @method Phaser.Physics.P2#addContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. + */ + addContactMaterial: function (material) { + + this.world.addContactMaterial(material); + + this.onContactMaterialAdded.dispatch(material); + + return material; + + }, + + /** + * Removes a Contact Material from the world. + * + * @method Phaser.Physics.P2#removeContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. + */ + removeContactMaterial: function (material) { + + this.world.removeContactMaterial(material); + + this.onContactMaterialRemoved.dispatch(material); + + return material; + + }, + + /** + * Gets a Contact Material based on the two given Materials. + * + * @method Phaser.Physics.P2#getContactMaterial + * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. + * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. + * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. + */ + getContactMaterial: function (materialA, materialB) { + + return this.world.getContactMaterial(materialA, materialB); + + }, + + /** + * Sets the given Material against all Shapes owned by all the Bodies in the given array. + * + * @method Phaser.Physics.P2#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. + * @param {array} bodies - An Array of Body objects that the given Material will be set on. + */ + setMaterial: function (material, bodies) { + + var i = bodies.length; + + while (i--) + { + bodies[i].setMaterial(material); + } + + }, + + /** + * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). + * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. + * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. + * + * @method Phaser.Physics.P2#createMaterial + * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. + * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. + * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. + */ + 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; + + }, + + /** + * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. + * + * @method Phaser.Physics.P2#createContactMaterial + * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {object} [options] - Material options object. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. + */ + createContactMaterial: function (materialA, materialB, options) { + + if (materialA === undefined) { materialA = this.createMaterial(); } + if (materialB === undefined) { materialB = this.createMaterial(); } + + var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); + + return this.addContactMaterial(contact); + + }, + + /** + * Populates and returns an array with references to of all current Bodies in the world. + * + * @method Phaser.Physics.P2#getBodies + * @return {array} An array containing all current Bodies in the world. + */ + getBodies: function () { + + var output = []; + var i = this.world.bodies.length; + + while (i--) + { + output.push(this.world.bodies[i].parent); + } + + return output; + + }, + + /** + * Checks the given object to see if it has a p2.Body and if so returns it. + * + * @method Phaser.Physics.P2#getBody + * @param {object} object - The object to check for a p2.Body on. + * @return {p2.Body} The p2.Body, or null if not found. + */ + getBody: function (object) { + + if (object instanceof p2.Body) + { + // Native p2 body + return object; + } + else if (object instanceof Phaser.Physics.P2.Body) + { + // Phaser P2 Body + return object.data; + } + else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) + { + // Sprite, TileSprite, etc + return object.body.data; + } + + return null; + + }, + + /** + * Populates and returns an array of all current Springs in the world. + * + * @method Phaser.Physics.P2#getSprings + * @return {array} An array containing all current Springs in the world. + */ + getSprings: function () { + + var output = []; + var i = this.world.springs.length; + + while (i--) + { + output.push(this.world.springs[i].parent); + } + + return output; + + }, + + /** + * Populates and returns an array of all current Constraints in the world. + * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain + * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type. + * + * @method Phaser.Physics.P2#getConstraints + * @return {array} An array containing all current Constraints in the world. + */ + getConstraints: function () { + + var output = []; + var i = this.world.constraints.length; + + while (i--) + { + output.push(this.world.constraints[i]); + } + + return output; + + }, + + /** + * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to + * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. + * + * @method Phaser.Physics.P2#hitTest + * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. + * @param {Array} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) + * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. + * @return {Array} Array of bodies that overlap the point. + */ + hitTest: function (worldPoint, bodies, precision, filterStatic) { + + if (bodies === undefined) { bodies = this.world.bodies; } + if (precision === undefined) { precision = 5; } + if (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.type === p2.Body.STATIC)) + { + query.push(bodies[i].data); + } + else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC)) + { + query.push(bodies[i]); + } + else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC)) + { + query.push(bodies[i].body.data); + } + } + + return this.world.hitTest(physicsPosition, query, precision); + + }, + + /** + * Converts the current world into a JSON object. + * + * @method Phaser.Physics.P2#toJSON + * @return {object} A JSON representation of the world. + */ + toJSON: function () { + + return this.world.toJSON(); + + }, + + /** + * Creates a new Collision Group and optionally applies it to the given object. + * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. + * + * @method Phaser.Physics.P2#createCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + */ + 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; + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. + * + * @method Phaser.Physics.P2y#setCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + */ + setCollisionGroup: function (object, group) { + + if (object instanceof Phaser.Group) + { + for (var i = 0; i < object.total; i++) + { + if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) + { + object.children[i].body.setCollisionGroup(group); + } + } + } + else + { + object.body.setCollisionGroup(group); + } + + }, + + /** + * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restLength=1] - Rest length of the spring. A number > 0. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @return {Phaser.Physics.P2.Spring} The spring + */ + createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); + } + + }, + + /** + * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createRotationalSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @return {Phaser.Physics.P2.RotationalSpring} The spring + */ + createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Rotational Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping)); + } + + }, + + /** + * Creates a new Body and adds it to the World. + * + * @method Phaser.Physics.P2#createBody + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {Phaser.Physics.P2.Body} The body + */ + createBody: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Creates a new Particle and adds it to the World. + * + * @method Phaser.Physics.P2#createParticle + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + */ + createParticle: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Converts all of the polyline, polygon, and rectangle objects inside a Tiled ObjectGroup into physics bodies that are added to the world. + * Note that the polylines and polygons must be created in such a way that they can withstand polygon decomposition. + * + * @method Phaser.Physics.P2#convertCollisionObjects + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. + * @return {array} An array of the Phaser.Physics.Body objects that have been created. + */ + convertCollisionObjects: function (map, layer, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var output = []; + + for (var i = 0, len = map.collision[layer].length; i < len; i++) + { + // name: json.layers[i].objects[v].name, + // x: json.layers[i].objects[v].x, + // y: json.layers[i].objects[v].y, + // width: json.layers[i].objects[v].width, + // height: json.layers[i].objects[v].height, + // visible: json.layers[i].objects[v].visible, + // properties: json.layers[i].objects[v].properties, + // polyline: json.layers[i].objects[v].polyline + + var object = map.collision[layer][i]; + var shapeData = object.polyline || object.polygon; + + // polyline/polygon shape data present + if (shapeData) + { + var body = this.createBody(object.x, object.y, 0, addToWorld, {}, shapeData); + } + + // tilemap parser sets rectangle=true when parsing object groups + else if (object.rectangle) + { + var body = this.createBody(object.x, object.y, 0, addToWorld); + body.addRectangle(object.width, object.height, object.width / 2, object.height / 2); + } + + // ellipse could be added here, but Tiled ellipses use height/width instead of radius + // (to support oblong ellipses), which p2 doesn't currently support. + + if (body) + { + output.push(body); + } + } + + return output; + + }, + + /** + * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. + * + * @method Phaser.Physics.P2#clearTilemapLayerBodies + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + */ + 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 = 0; + + }, + + /** + * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. + * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. + * Every time you call this method it will destroy any previously created bodies and remove them from the world. + * Therefore understand it's a very expensive operation and not to be done in a core game update loop. + * + * @method Phaser.Physics.P2#convertTilemap + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. + * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. + * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. + */ + convertTilemap: function (map, layer, addToWorld, optimize) { + + layer = map.getLayer(layer); + + if (addToWorld === undefined) { addToWorld = true; } + if (optimize === undefined) { optimize = true; } + + // If the bodies array is already populated we need to nuke it + this.clearTilemapLayerBodies(map, layer); + + var width = 0; + var sx = 0; + var sy = 0; + + for (var y = 0, h = map.layers[layer].height; y < h; y++) + { + width = 0; + + for (var x = 0, w = map.layers[layer].width; x < w; x++) + { + var tile = map.layers[layer].data[y][x]; + + if (tile && tile.index > -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; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpx + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpx: function (v) { + + return v *= 20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters). + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxm + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxm: function (v) { + + return v * 0.05; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpxi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpxi: function (v) { + + return v *= -20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters) and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxmi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxmi: function (v) { + + return v * -0.05; + + } + +}; + +/** +* @name Phaser.Physics.P2#friction +* @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { + + get: function () { + + return this.world.defaultContactMaterial.friction; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.friction = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#restitution +* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { + + get: function () { + + return this.world.defaultContactMaterial.restitution; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.restitution = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#contactMaterial +* @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { + + get: function () { + + return this.world.defaultContactMaterial; + + }, + + set: function (value) { + + this.world.defaultContactMaterial = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applySpringForces +* @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { + + get: function () { + + return this.world.applySpringForces; + + }, + + set: function (value) { + + this.world.applySpringForces = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyDamping +* @property {boolean} applyDamping - Enable to automatically apply body damping each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { + + get: function () { + + return this.world.applyDamping; + + }, + + set: function (value) { + + this.world.applyDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyGravity +* @property {boolean} applyGravity - Enable to automatically apply gravity each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { + + get: function () { + + return this.world.applyGravity; + + }, + + set: function (value) { + + this.world.applyGravity = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#solveConstraints +* @property {boolean} solveConstraints - Enable/disable constraint solving in each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { + + get: function () { + + return this.world.solveConstraints; + + }, + + set: function (value) { + + this.world.solveConstraints = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#time +* @property {boolean} time - The World time. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "time", { + + get: function () { + + return this.world.time; + + } + +}); + +/** +* @name Phaser.Physics.P2#emitImpactEvent +* @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { + + get: function () { + + return this.world.emitImpactEvent; + + }, + + set: function (value) { + + this.world.emitImpactEvent = value; + + } + +}); + +/** +* How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. +* If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. +* @name Phaser.Physics.P2#sleepMode +* @property {number} sleepMode +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", { + + get: function () { + + return this.world.sleepMode; + + }, + + set: function (value) { + + this.world.sleepMode = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#total +* @property {number} total - The total number of bodies in the world. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "total", { + + get: function () { + + return this.world.bodies.length; + + } + +}); + +/* jshint noarg: false */ + +/** +* @author Georgios Kaleadis https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Allow to access a list of created fixture (coming from Body#addPhaserPolygon) +* which itself parse the input from PhysicsEditor with the custom phaser exporter. +* You can access fixtures of a Body by a group index or even by providing a fixture Key. + +* You can set the fixture key and also the group index for a fixture in PhysicsEditor. +* This gives you the power to create a complex body built of many fixtures and modify them +* during runtime (to remove parts, set masks, categories & sensor properties) +* +* @class Phaser.Physics.P2.FixtureList +* @constructor +* @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) +*/ +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 = { + + /** + * @method Phaser.Physics.P2.FixtureList#init + */ + init: function () { + + /** + * @property {object} namedFixtures - Collect all fixtures with a key + * @private + */ + this.namedFixtures = {}; + + /** + * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group + * @private + */ + this.groupedFixtures = []; + + /** + * @property {Array} allFixtures - This is a list of everything in this collection + * @private + */ + this.allFixtures = []; + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setCategory + * @param {number} bit - The bit to set as the collision group. + * @param {string} fixtureKey - Only apply to the fixture with the given key. + */ + setCategory: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionGroup = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMask + * @param {number} bit - The bit to set as the collision mask + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMask: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionMask = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setSensor + * @param {boolean} value - sensor true or false + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setSensor: function (value, fixtureKey) { + + var setter = function(fixture) { + fixture.sensor = value; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMaterial + * @param {Object} material - The contact material for a fixture + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMaterial: function (material, fixtureKey) { + + var setter = function(fixture) { + fixture.material = material; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * Accessor to get either a list of specified fixtures by key or the whole fixture list + * + * @method Phaser.Physics.P2.FixtureList#getFixtures + * @param {array} keys - A list of fixture keys + */ + 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; + } + + }, + + /** + * Accessor to get either a single fixture by its key. + * + * @method Phaser.Physics.P2.FixtureList#getFixtureByKey + * @param {string} key - The key of the fixture. + */ + getFixtureByKey: function (key) { + + return this.namedFixtures[key]; + + }, + + /** + * Accessor to get a group of fixtures by its group index. + * + * @method Phaser.Physics.P2.FixtureList#getGroup + * @param {number} groupID - The group index. + */ + getGroup: function (groupID) { + + return this.groupedFixtures[groupID]; + + }, + + /** + * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon + * + * @method Phaser.Physics.P2.FixtureList#parse + */ + 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)); + } + + }, + + /** + * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. + * + * @method Phaser.Physics.P2.FixtureList#flatten + * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. + */ + 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; + + } + +}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. +* +* @class Phaser.Physics.P2.PointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.PointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; + +/** +* @name Phaser.Physics.P2.PointProxy#x +* @property {number} x - The x property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { + + get: function () { + + return this.world.mpx(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#y +* @property {number} y - The y property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { + + get: function () { + + return this.world.mpx(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#mx +* @property {number} mx - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#my +* @property {number} my - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. +* +* @class Phaser.Physics.P2.InversePointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.InversePointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; + +/** +* @name Phaser.Physics.P2.InversePointProxy#x +* @property {number} x - The x property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#y +* @property {number} y - The y property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#mx +* @property {number} mx - The x property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = -value; + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#my +* @property {number} my - The y property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = -value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. +* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. +* In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. +* By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. +* Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. +* Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. +* +* @class Phaser.Physics.P2.Body +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. +* @param {number} [x=0] - The x coordinate of this Body. +* @param {number} [y=0] - The y coordinate of this Body. +* @param {number} [mass=1] - The default mass of this Body (0 = static). +*/ +Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { + + sprite = sprite || null; + x = x || 0; + y = y || 0; + if (mass === undefined) { mass = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to the P2 World. + */ + this.world = game.physics.p2; + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.P2JS; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. + */ + this.offset = new Phaser.Point(); + + /** + * @property {p2.Body} data - The p2 Body data. + * @protected + */ + this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); + + this.data.parent = this; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. + */ + this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); + + /** + * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body. + */ + this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); + + /** + * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. + */ + this.gravity = new Phaser.Point(); + + /** + * Dispatched when a first contact is created between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 5 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body is in contact with. + * The Shape from this body that caused the contact. + * The Shape from the contact body. + * The Contact Equation data array. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * Dispatched when contact ends between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 4 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body has ended contact with. + * The Shape from this body that caused the original contact. + * The Shape from the contact body. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + /** + * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. + */ + this.collidesWith = []; + + /** + * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. + */ + this.removeNextStep = false; + + /** + * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. + */ + this.debugBody = null; + + /** + * @property {boolean} dirty - Internally used by Sprite.x/y + */ + this.dirty = false; + + /** + * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. + * @private + */ + this._collideWorldBounds = true; + + /** + * @property {object} _bodyCallbacks - Array of Body callbacks. + * @private + */ + this._bodyCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Body callback contexts. + * @private + */ + this._bodyCallbackContext = {}; + + /** + * @property {object} _groupCallbacks - Array of Group callbacks. + * @private + */ + this._groupCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. + * @private + */ + this._groupCallbackContext = {}; + + /** + * @property {boolean} _reset - Internal var. + * @private + */ + this._reset = false; + + // Set-up the default shape + if (sprite) + { + this.setRectangleFromSprite(sprite); + + if (sprite.exists) + { + this.game.physics.p2.addBody(this); + } + } + +}; + +Phaser.Physics.P2.Body.prototype = { + + /** + * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createBodyCallback + * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + 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; + } + } + + }, + + /** + * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * This callback will only fire if this Body has been assigned a collision group. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createGroupCallback + * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + createGroupCallback: function (group, callback, callbackContext) { + + if (callback === null) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + else + { + this._groupCallbacks[group.mask] = callback; + this._groupCallbackContext[group.mask] = callbackContext; + } + + }, + + /** + * Gets the collision bitmask from the groups this body collides with. + * + * @method Phaser.Physics.P2.Body#getCollisionMask + * @return {number} The bitmask. + */ + getCollisionMask: function () { + + var mask = 0; + + if (this._collideWorldBounds) + { + mask = this.game.physics.p2.boundsCollisionGroup.mask; + } + + for (var i = 0; i < this.collidesWith.length; i++) + { + mask = mask | this.collidesWith[i].mask; + } + + return mask; + + }, + + /** + * Updates the collisionMask. + * + * @method Phaser.Physics.P2.Body#updateCollisionMask + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + updateCollisionMask: function (shape) { + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * This also resets the collisionMask. + * + * @method Phaser.Physics.P2.Body#setCollisionGroup + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + setCollisionGroup: function (group, shape) { + + var mask = this.getCollisionMask(); + + if (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; + } + + }, + + /** + * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. + * + * @method Phaser.Physics.P2.Body#clearCollision + * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? + * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. + */ + clearCollision: function (clearGroup, clearMask, shape) { + + if (clearGroup === undefined) { clearGroup = true; } + if (clearMask === undefined) { clearMask = true; } + + if (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; + } + + }, + + /** + * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#removeCollisionGroup + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore. + * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body. + */ + removeCollisionGroup: function (group, clearCallback, shape) { + + if (clearCallback === undefined) { clearCallback = true; } + + var index; + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + index = this.collidesWith.indexOf(group[i]); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + } + else + { + index = this.collidesWith.indexOf(group); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#collides + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. + * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. + * @param {object} [callbackContext] - The context under which the callback will be called. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. + */ + collides: function (group, callback, callbackContext, shape) { + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + if (this.collidesWith.indexOf(group[i]) === -1) + { + this.collidesWith.push(group[i]); + + if (callback) + { + this.createGroupCallback(group[i], callback, callbackContext); + } + } + } + } + else + { + if (this.collidesWith.indexOf(group) === -1) + { + this.collidesWith.push(group); + + if (callback) + { + this.createGroupCallback(group, callback, callbackContext); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Moves the shape offsets so their center of mass becomes the body center of mass. + * + * @method Phaser.Physics.P2.Body#adjustCenterOfMass + */ + adjustCenterOfMass: function () { + + this.data.adjustCenterOfMass(); + this.shapeChanged(); + + }, + + /** + * Gets the velocity of a point in the body. + * + * @method Phaser.Physics.P2.Body#getVelocityAtPoint + * @param {Array} result - A vector to store the result in. + * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from. + * @return {Array} The result vector. + */ + getVelocityAtPoint: function (result, relativePoint) { + + return this.data.getVelocityAtPoint(result, relativePoint); + + }, + + /** + * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. + * + * @method Phaser.Physics.P2.Body#applyDamping + * @param {number} dt - Current time step. + */ + applyDamping: function (dt) { + + this.data.applyDamping(dt); + + }, + + /** + * Apply impulse to a point relative to the body. + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulse + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space. + * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + */ + applyImpulse: function (impulse, worldX, worldY) { + + this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Apply impulse to a point local to the body. + * + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulseLocal + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space. + * @param {number} localX - A local point on the body. + * @param {number} localY - A local point on the body. + */ + applyImpulseLocal: function (impulse, localX, localY) { + + this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]); + + }, + + /** + * Apply force to a world point. + * + * This could for example be a point on the RigidBody surface. Applying force + * this way will add to Body.force and Body.angularForce. + * + * @method Phaser.Physics.P2.Body#applyForce + * @param {Float32Array|Array} force - The force vector to add. + * @param {number} worldX - The world x point to apply the force on. + * @param {number} worldY - The world y point to apply the force on. + */ + applyForce: function (force, worldX, worldY) { + + this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Sets the force on the body to zero. + * + * @method Phaser.Physics.P2.Body#setZeroForce + */ + setZeroForce: function () { + + this.data.setZeroForce(); + + }, + + /** + * If this Body is dynamic then this will zero its angular velocity. + * + * @method Phaser.Physics.P2.Body#setZeroRotation + */ + setZeroRotation: function () { + + this.data.angularVelocity = 0; + + }, + + /** + * If this Body is dynamic then this will zero its velocity on both axis. + * + * @method Phaser.Physics.P2.Body#setZeroVelocity + */ + setZeroVelocity: function () { + + this.data.velocity[0] = 0; + this.data.velocity[1] = 0; + + }, + + /** + * Sets the Body damping and angularDamping to zero. + * + * @method Phaser.Physics.P2.Body#setZeroDamping + */ + setZeroDamping: function () { + + this.data.damping = 0; + this.data.angularDamping = 0; + + }, + + /** + * Transform a world point to local body frame. + * + * @method Phaser.Physics.P2.Body#toLocalFrame + * @param {Float32Array|Array} out - The vector to store the result in. + * @param {Float32Array|Array} worldPoint - The input world vector. + */ + toLocalFrame: function (out, worldPoint) { + + return this.data.toLocalFrame(out, worldPoint); + + }, + + /** + * Transform a local point to world frame. + * + * @method Phaser.Physics.P2.Body#toWorldFrame + * @param {Array} out - The vector to store the result in. + * @param {Array} localPoint - The input local vector. + */ + toWorldFrame: function (out, localPoint) { + + return this.data.toWorldFrame(out, localPoint); + + }, + + /** + * This will rotate the Body by the given speed to the left (counter-clockwise). + * + * @method Phaser.Physics.P2.Body#rotateLeft + * @param {number} speed - The speed at which it should rotate. + */ + rotateLeft: function (speed) { + + this.data.angularVelocity = this.world.pxm(-speed); + + }, + + /** + * This will rotate the Body by the given speed to the left (clockwise). + * + * @method Phaser.Physics.P2.Body#rotateRight + * @param {number} speed - The speed at which it should rotate. + */ + rotateRight: function (speed) { + + this.data.angularVelocity = this.world.pxm(speed); + + }, + + /** + * Moves the Body forwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveForward + * @param {number} speed - The speed at which it should move forwards. + */ + 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); + + }, + + /** + * Moves the Body backwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveBackward + * @param {number} speed - The speed at which it should move backwards. + */ + 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)); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrust + * @param {number} speed - The speed at which it should thrust. + */ + 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); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustLeft + * @param {number} speed - The speed at which it should move to the left. + */ + thrustLeft: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] += magnitude * Math.cos(angle); + this.data.force[1] += magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustRight + * @param {number} speed - The speed at which it should move to the right. + */ + thrustRight: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] -= magnitude * Math.cos(angle); + this.data.force[1] -= magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#reverse + * @param {number} speed - The speed at which it should reverse. + */ + 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); + + }, + + /** + * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveLeft + * @param {number} speed - The speed at which it should move to the left, in pixels per second. + */ + moveLeft: function (speed) { + + this.data.velocity[0] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveRight + * @param {number} speed - The speed at which it should move to the right, in pixels per second. + */ + moveRight: function (speed) { + + this.data.velocity[0] = this.world.pxmi(speed); + + }, + + /** + * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveUp + * @param {number} speed - The speed at which it should move up, in pixels per second. + */ + moveUp: function (speed) { + + this.data.velocity[1] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveDown + * @param {number} speed - The speed at which it should move down, in pixels per second. + */ + moveDown: function (speed) { + + this.data.velocity[1] = this.world.pxmi(speed); + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#preUpdate + * @protected + */ + preUpdate: function () { + + this.dirty = true; + + if (this.removeNextStep) + { + this.removeFromWorld(); + this.removeNextStep = false; + } + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#postUpdate + * @protected + */ + postUpdate: function () { + + this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x; + this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y; + + if (!this.fixedRotation) + { + this.sprite.rotation = this.data.angle; + } + + if (this.debugBody) + { + this.debugBody.updateSpriteTransform(); + } + + this.dirty = false; + + }, + + /** + * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. + * + * @method Phaser.Physics.P2.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new x position of the Body. + * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. + * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. + */ + reset: function (x, y, resetDamping, resetMass) { + + if (resetDamping === undefined) { resetDamping = false; } + if (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; + + }, + + /** + * Adds this physics body to the world. + * + * @method Phaser.Physics.P2.Body#addToWorld + */ + addToWorld: function () { + + if (this.game.physics.p2._toRemove) + { + for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) + { + if (this.game.physics.p2._toRemove[i] === this) + { + this.game.physics.p2._toRemove.splice(i, 1); + } + } + } + + if (this.data.world !== this.game.physics.p2.world) + { + this.game.physics.p2.addBody(this); + } + + }, + + /** + * Removes this physics body from the world. + * + * @method Phaser.Physics.P2.Body#removeFromWorld + */ + removeFromWorld: function () { + + if (this.data.world === this.game.physics.p2.world) + { + this.game.physics.p2.removeBodyNextStep(this); + } + + }, + + /** + * Destroys this Body and all references it holds to other objects. + * + * @method Phaser.Physics.P2.Body#destroy + */ + destroy: function () { + + this.removeFromWorld(); + + this.clearShapes(); + + this._bodyCallbacks = {}; + this._bodyCallbackContext = {}; + this._groupCallbacks = {}; + this._groupCallbackContext = {}; + + if (this.debugBody) + { + this.debugBody.destroy(true, true); + } + + this.debugBody = null; + + if (this.sprite) + { + this.sprite.body = null; + this.sprite = null; + } + + }, + + /** + * Removes all Shapes from this Body. + * + * @method Phaser.Physics.P2.Body#clearShapes + */ + clearShapes: function () { + + var i = this.data.shapes.length; + + while (i--) + { + this.data.removeShape(this.data.shapes[i]); + } + + this.shapeChanged(); + + }, + + /** + * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#addShape + + * @param {p2.Shape} shape - The shape to add to the body. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Shape} The shape that was added to the body. + */ + addShape: function (shape, offsetX, offsetY, rotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (rotation === undefined) { rotation = 0; } + + this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); + this.shapeChanged(); + + return shape; + + }, + + /** + * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Circle} The Circle shape that was added to the Body. + */ + addCircle: function (radius, offsetX, offsetY, rotation) { + + var shape = new p2.Circle({ radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addRectangle + * @param {number} width - The width of the rectangle in pixels. + * @param {number} height - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Box} The shape that was added to the Body. + */ + addRectangle: function (width, height, offsetX, offsetY, rotation) { + + var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addPlane + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Plane} The Plane shape that was added to the Body. + */ + addPlane: function (offsetX, offsetY, rotation) { + + var shape = new p2.Plane(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addParticle + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Particle} The Particle shape that was added to the Body. + */ + addParticle: function (offsetX, offsetY, rotation) { + + var shape = new p2.Particle(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Line shape to this Body. + * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addLine + * @param {number} length - The length of this line (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Line} The Line shape that was added to the Body. + */ + addLine: function (length, offsetX, offsetY, rotation) { + + var shape = new p2.Line({ length: this.world.pxm(length)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Capsule shape to this Body. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCapsule + * @param {number} length - The distance between the end points in pixels. + * @param {number} radius - Radius of the capsule in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Capsule} The Capsule shape that was added to the Body. + */ + addCapsule: function (length, radius, offsetX, offsetY, rotation) { + + var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. + * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. + * + * @method Phaser.Physics.P2.Body#addPolygon + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...]. In the first form **the array will mutate**. + * Or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {boolean} True on success, else false. + */ + addPolygon: function (options, points) { + + options = options || {}; + + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments, 1); + } + + var path = []; + + // Did they pass in a single array of points? + if (points.length === 1 && Array.isArray(points[0])) + { + path = points[0].slice(0); + } + else if (Array.isArray(points[0])) + { + path = points.slice(); + } + else if (typeof points[0] === 'number') + { + // We've a list of numbers + for (var i = 0, len = points.length; i < len; i += 2) + { + path.push([points[i], points[i + 1]]); + } + } + + // top and tail + var idx = path.length - 1; + + if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) + { + path.pop(); + } + + // Now process them into p2 values + for (var p = 0; p < path.length; p++) + { + path[p][0] = this.world.pxmi(path[p][0]); + path[p][1] = this.world.pxmi(path[p][1]); + } + + var result = this.data.fromPolygon(path, options); + + this.shapeChanged(); + + return result; + + }, + + /** + * Remove a shape from the body. Will automatically update the mass properties and bounding radius. + * + * @method Phaser.Physics.P2.Body#removeShape + * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. + * @return {boolean} True if the shape was found and removed, else false. + */ + removeShape: function (shape) { + + var result = this.data.removeShape(shape); + + this.shapeChanged(); + + return result; + }, + + /** + * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + */ + setCircle: function (radius, offsetX, offsetY, rotation) { + + this.clearShapes(); + + return this.addCircle(radius, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. + * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangle + * @param {number} [width=16] - The width of the rectangle in pixels. + * @param {number} [height=16] - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangle: function (width, height, offsetX, offsetY, rotation) { + + if (width === undefined) { width = 16; } + if (height === undefined) { height = 16; } + + this.clearShapes(); + + return this.addRectangle(width, height, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. + * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. + * If no Sprite is given it defaults to using the parent of this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangleFromSprite + * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangleFromSprite: function (sprite) { + + if (sprite === undefined) { sprite = this.sprite; } + + this.clearShapes(); + + return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); + + }, + + /** + * Adds the given Material to all Shapes that belong to this Body. + * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. + * + * @method Phaser.Physics.P2.Body#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. + */ + setMaterial: function (material, shape) { + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].material = material; + } + } + else + { + shape.material = material; + } + + }, + + /** + * Updates the debug draw if any body shapes change. + * + * @method Phaser.Physics.P2.Body#shapeChanged + */ + shapeChanged: function() { + + if (this.debugBody) + { + this.debugBody.draw(); + } + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * The shape data format is based on the output of the + * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for + * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor} + * + * @method Phaser.Physics.P2.Body#addPhaserPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. + * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. + * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList + */ + addPhaserPolygon: function (key, object) { + + var data = this.game.cache.getPhysicsData(key, object); + var createdFixtures = []; + + // Cycle through the fixtures + for (var i = 0; i < data.length; i++) + { + var fixtureData = data[i]; + var shapesOfFixture = this.addFixture(fixtureData); + + // Always add to a group + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); + + // if (unique) fixture key is provided + if (fixtureData.fixtureKey) + { + createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; + } + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return createdFixtures; + + }, + + /** + * Add a polygon fixture. This is used during #loadPolygon. + * + * @method Phaser.Physics.P2.Body#addFixture + * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. + * @return {array} An array containing the generated shapes for the given polygon. + */ + addFixture: function (fixtureData) { + + var generatedShapes = []; + + if (fixtureData.circle) + { + var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) }); + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + var offset = p2.vec2.create(); + offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); + offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); + + this.data.addShape(shape, offset); + generatedShapes.push(shape); + } + else + { + var polygons = fixtureData.polygons; + var cm = p2.vec2.create(); + + for (var i = 0; i < polygons.length; i++) + { + var shapes = polygons[i]; + var vertices = []; + + for (var s = 0; s < shapes.length; s += 2) + { + vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); + } + + var shape = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== shape.vertices.length; j++) + { + var v = shape.vertices[j]; + p2.vec2.sub(v, v, shape.centerOfMass); + } + + p2.vec2.scale(cm, shape.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + shape.updateTriangles(); + shape.updateCenterOfMass(); + shape.updateBoundingRadius(); + + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + this.data.addShape(shape, cm); + + generatedShapes.push(shape); + } + } + + return generatedShapes; + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * + * As well as reading the data from the Cache you can also pass `null` as the first argument and a + * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance. + * + * For more details see the format of the Lime / Corona Physics Editor export. + * + * @method Phaser.Physics.P2.Body#loadPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the + * data as the 2nd argument. + * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from, + * or if key is null pass the actual physics data object itself as this parameter. + * @param {number} [scale=1] - Optionally resize the loaded polygon. + * @return {boolean} True on success, else false. + */ + loadPolygon: function (key, object, scale) { + + if (key === null) + { + var data = object; + } + else + { + var data = this.game.cache.getPhysicsData(key, object); + } + + if (typeof scale !== "number") + { + scale = 1; + } + + // We've multiple Convex shapes, they should be CCW automatically + var cm = p2.vec2.create(); + + for (var i = 0; i < data.length; i++) + { + var vertices = []; + + for (var s = 0; s < data[i].shape.length; s += 2) + { + vertices.push([ + this.world.pxmi(data[i].shape[s] * scale), + this.world.pxmi(data[i].shape[s + 1] * scale) + ]); + } + + var c = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== c.vertices.length; j++) + { + var v = c.vertices[j]; + p2.vec2.sub(v, v, c.centerOfMass); + } + + p2.vec2.scale(cm, c.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + c.updateTriangles(); + c.updateCenterOfMass(); + c.updateBoundingRadius(); + + this.data.addShape(c, cm); + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return true; + + } + +}; + +Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; + +/** + * Dynamic body. Dynamic bodies body can move and respond to collisions and forces. + * @property DYNAMIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.DYNAMIC = 1; + +/** + * Static body. Static bodies do not move, and they do not respond to forces or collision. + * @property STATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.STATIC = 2; + +/** + * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. + * @property KINEMATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.KINEMATIC = 4; + +/** +* @name Phaser.Physics.P2.Body#static +* @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.STATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#dynamic +* @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#kinematic +* @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.KINEMATIC; + this.mass = 4; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#allowSleep +* @property {boolean} allowSleep - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { + + get: function () { + + return this.data.allowSleep; + + }, + + set: function (value) { + + if (value !== this.data.allowSleep) + { + this.data.allowSleep = value; + } + + } + +}); + +/** +* The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. +* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. +* If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#angle +* @property {number} angle - The angle of this Body in degrees. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); + + }, + + set: function(value) { + + this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#angularDamping +* @property {number} angularDamping - The angular damping acting acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { + + get: function () { + + return this.data.angularDamping; + + }, + + set: function (value) { + + this.data.angularDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularForce +* @property {number} angularForce - The angular force acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { + + get: function () { + + return this.data.angularForce; + + }, + + set: function (value) { + + this.data.angularForce = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularVelocity +* @property {number} angularVelocity - The angular velocity of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { + + get: function () { + + return this.data.angularVelocity; + + }, + + set: function (value) { + + this.data.angularVelocity = value; + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#damping +* @property {number} damping - The linear damping acting on the body in the velocity direction. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { + + get: function () { + + return this.data.damping; + + }, + + set: function (value) { + + this.data.damping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#fixedRotation +* @property {boolean} fixedRotation - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { + + get: function () { + + return this.data.fixedRotation; + + }, + + set: function (value) { + + if (value !== this.data.fixedRotation) + { + this.data.fixedRotation = value; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#inertia +* @property {number} inertia - The inertia of the body around the Z axis.. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { + + get: function () { + + return this.data.inertia; + + }, + + set: function (value) { + + this.data.inertia = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#mass +* @property {number} mass - The mass of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { + + get: function () { + + return this.data.mass; + + }, + + set: function (value) { + + if (value !== this.data.mass) + { + this.data.mass = value; + this.data.updateMassProperties(); + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#motionState +* @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { + + get: function () { + + return this.data.type; + + }, + + set: function (value) { + + if (value !== this.data.type) + { + this.data.type = value; + } + + } + +}); + +/** +* The angle of the Body in radians. +* If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#rotation +* @property {number} rotation - The angle of this Body in radians. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { + + get: function() { + + return this.data.angle; + + }, + + set: function(value) { + + this.data.angle = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#sleepSpeedLimit +* @property {number} sleepSpeedLimit - . +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { + + get: function () { + + return this.data.sleepSpeedLimit; + + }, + + set: function (value) { + + this.data.sleepSpeedLimit = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#x +* @property {number} x - The x coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.data.position[0]); + + }, + + set: function (value) { + + this.data.position[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#y +* @property {number} y - The y coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.data.position[1]); + + }, + + set: function (value) { + + this.data.position[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#id +* @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { + + get: function () { + + return this.data.id; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#debug +* @property {boolean} debug - Enable or disable debug drawing of this body +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { + + get: function () { + + return (this.debugBody !== null); + + }, + + set: function (value) { + + if (value && !this.debugBody) + { + // This will be added to the global space + this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); + } + else if (!value && this.debugBody) + { + this.debugBody.destroy(); + this.debugBody = null; + } + + } + +}); + +/** +* A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. +* Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. +* Also note that when you set this it will only affect Body shapes that already exist. If you then add further shapes to your Body +* after setting this it will *not* proactively set them to collide with the bounds. +* +* @name Phaser.Physics.P2.Body#collideWorldBounds +* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? +* @default true +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { + + get: function () { + + return this._collideWorldBounds; + + }, + + set: function (value) { + + if (value && !this._collideWorldBounds) + { + this._collideWorldBounds = true; + this.updateCollisionMask(); + } + else if (!value && this._collideWorldBounds) + { + this._collideWorldBounds = false; + this.updateCollisionMask(); + } + + } + +}); + +/** +* @author George https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Draws a P2 Body to a Graphics instance for visual debugging. +* Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. +* So use sparingly and rarely (if ever) in production code. +* +* Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you +* manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will +* need to manually adjust its BodyDebug as well. +* +* @class Phaser.Physics.P2.BodyDebug +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. +* @param {object} settings - Settings object. +*/ +Phaser.Physics.P2.BodyDebug = function(game, body, settings) { + + Phaser.Group.call(this, game); + + /** + * @property {object} defaultSettings - Default debug settings. + * @private + */ + var defaultSettings = { + pixelsPerLengthUnit: game.physics.p2.mpx(1), + debugPolygons: false, + lineWidth: 1, + alpha: 0.5 + }; + + this.settings = Object.assign(defaultSettings, settings); + + /** + * @property {number} ppu - Pixels per Length Unit. + */ + this.ppu = this.settings.pixelsPerLengthUnit; + this.ppu = -1 * this.ppu; + + /** + * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. + */ + this.body = body; + + /** + * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. + */ + this.canvas = new Phaser.Graphics(game); + + this.canvas.alpha = this.settings.alpha; + + this.add(this.canvas); + + this.draw(); + + this.updateSpriteTransform(); + +}; + +Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); +Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; + +Object.assign(Phaser.Physics.P2.BodyDebug.prototype, { + + /** + * Core update. + * + * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform + */ + updateSpriteTransform: function() { + + this.position.x = this.body.position[0] * this.ppu; + this.position.y = this.body.position[1] * this.ppu; + this.rotation = this.body.angle; + + }, + + /** + * Draws the P2 shapes to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#draw + */ + draw: function() { + + var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; + + obj = this.body; + sprite = this.canvas; + sprite.clear(); + color = parseInt(this.randomPastelHex(), 16); + lineColor = 0xff0000; + lw = this.lineWidth; + + if (obj instanceof p2.Body && obj.shapes.length) + { + var l = obj.shapes.length; + + i = 0; + + while (i !== l) + { + child = obj.shapes[i]; + offset = child.position || 0; + angle = child.angle || 0; + + if (child instanceof p2.Circle) + { + this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); + } + else if (child instanceof p2.Capsule) + { + this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw); + } + 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.Box) + { + this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); + } + else if (child instanceof p2.Convex) + { + verts = []; + vrot = p2.vec2.create(); + + for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _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]); + } + + i++; + } + } + + }, + + /** + * Draws a p2.Box to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawRectangle + * @private + */ + drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + g.beginFill(fillColor); + g.drawRect(x - w / 2, y - h / 2, w, h); + + }, + + /** + * Draws a p2.Circle to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCircle + * @private + */ + drawCircle: function(g, x, y, angle, radius, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + g.lineStyle(lineWidth, 0x000000, 1); + g.beginFill(color, 1.0); + g.drawCircle(x, y, -radius*2); + g.endFill(); + g.moveTo(x, y); + g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); + + }, + + /** + * Draws a p2.Line to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawLine + * @private + */ + drawLine: function(g, len, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth * 5, color, 1); + g.moveTo(-len / 2, 0); + g.lineTo(len / 2, 0); + + }, + + /** + * Draws a p2.Convex to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawConvex + * @private + */ + drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { + + var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + 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 = [0xff0000, 0x00ff00, 0x0000ff]; + 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, 0x000000, 1); + return g.drawCircle(offset[0], offset[1], lineWidth * 2); + } + + }, + + /** + * Draws a p2.Path to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPath + * @private + */ + drawPath: function(g, path, color, fillColor, lineWidth) { + + var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + if (typeof fillColor === "number") + { + g.beginFill(fillColor); + } + + lastx = null; + lasty = null; + i = 0; + + while (i < path.length) + { + v = path[i]; + x = v[0]; + y = v[1]; + + if (x !== lastx || y !== lasty) + { + if (i === 0) + { + g.moveTo(x, y); + } + else + { + p1x = lastx; + p1y = lasty; + p2x = x; + p2y = y; + p3x = path[(i + 1) % path.length][0]; + p3y = path[(i + 1) % path.length][1]; + area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); + + if (area !== 0) + { + g.lineTo(x, y); + } + } + lastx = x; + lasty = y; + } + + i++; + + } + + if (typeof fillColor === "number") + { + g.endFill(); + } + + if (path.length > 2 && typeof fillColor === "number") + { + g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); + g.lineTo(path[0][0], path[0][1]); + } + + }, + + /** + * Draws a p2.Plane to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPlane + * @private + */ + drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { + + var max, xd, yd; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + + 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); + + }, + + /** + * Draws a p2.Capsule to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCapsule + * @private + */ + drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + // Draw circles at ends + var c = Math.cos(angle); + var s = Math.sin(angle); + + g.beginFill(fillColor, 1); + g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2); + g.drawCircle( len/2*c + x, len/2*s + y, -radius * 2); + g.endFill(); + + // Draw rectangle + g.lineStyle(lineWidth, color, 0); + g.beginFill(fillColor, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.endFill(); + + // Draw lines in between + g.lineStyle(lineWidth, color, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + + }, + + /** + * Picks a random pastel color. + * + * @method Phaser.Physics.P2.BodyDebug#randomPastelHex + * @private + */ + 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); + + }, + + /** + * Converts from RGB to Hex. + * + * @method Phaser.Physics.P2.BodyDebug#rgbToHex + * @private + */ + rgbToHex: function(r, g, b) { + return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); + }, + + /** + * Component to hex conversion. + * + * @method Phaser.Physics.P2.BodyDebug#componentToHex + * @private + */ + componentToHex: function(c) { + + var hex; + hex = c.toString(16); + + if (hex.length === 2) + { + return hex; + } + else + { + return hex + '0'; + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.Spring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restLength=1] - Rest length of the spring. A number > 0. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +*/ +Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restLength === undefined) { restLength = 1; } + if (stiffness === undefined) { stiffness = 100; } + if (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]) ]; + } + + /** + * @property {p2.LinearSpring} data - The actual p2 spring object. + */ + this.data = new p2.LinearSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.RotationalSpring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +*/ +Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restAngle === undefined) { restAngle = null; } + if (stiffness === undefined) { stiffness = 100; } + if (damping === undefined) { damping = 1; } + + if (restAngle) + { + restAngle = world.pxm(restAngle); + } + + var options = { + restAngle: restAngle, + stiffness: stiffness, + damping: damping + }; + + /** + * @property {p2.RotationalSpring} data - The actual p2 spring object. + */ + this.data = new p2.RotationalSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A P2 Material. +* +* \o/ ~ "Because I'm a Material girl" +* +* @class Phaser.Physics.P2.Material +* @constructor +* @param {string} name - The user defined name given to this Material. +*/ +Phaser.Physics.P2.Material = function (name) { + + /** + * @property {string} name - The user defined name given to this Material. + * @default + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Defines a physics material +* +* @class Phaser.Physics.P2.ContactMaterial +* @constructor +* @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. +* @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. +* @param {object} [options] - Additional configuration options. +*/ +Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { + + /** + * @property {number} id - The contact material identifier. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. + */ + + /** + * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. + */ + + /** + * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. + */ + + /** + * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + */ + + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Collision Group +* +* @class Phaser.Physics.P2.CollisionGroup +* @constructor +* @param {number} bitmask - The CollisionGroup bitmask. +*/ +Phaser.Physics.P2.CollisionGroup = function (bitmask) { + + /** + * @property {number} mask - The CollisionGroup bitmask. + */ + this.mask = bitmask; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A constraint that tries to keep the distance between two bodies constant. +* +* @class Phaser.Physics.P2.DistanceConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} distance - The distance to keep between the bodies. +* @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. +* @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. +* @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply. +*/ +Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { + + if (distance === undefined) { distance = 100; } + if (localAnchorA === undefined) { localAnchorA = [0, 0]; } + if (localAnchorB === undefined) { localAnchorB = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + distance = world.pxm(distance); + + localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ]; + localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ]; + + var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce }; + + p2.DistanceConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); +Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.GearConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [angle=0] - The relative angle +* @param {number} [ratio=1] - The gear ratio. +*/ +Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { + + if (angle === undefined) { angle = 0; } + if (ratio === undefined) { ratio = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Locks the relative position between two bodies. +* +* @class Phaser.Physics.P2.LockConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [angle=0] - The angle of bodyB in bodyA's frame. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { + + if (offset === undefined) { offset = [0, 0]; } + if (angle === undefined) { angle = 0; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.PrismaticConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. +* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { + + if (lockRotation === undefined) { lockRotation = true; } + if (anchorA === undefined) { anchorA = [0, 0]; } + if (anchorB === undefined) { anchorB = [0, 0]; } + if (axis === undefined) { axis = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* The pivot points are given in world (pixel) coordinates. +* +* @class Phaser.Physics.P2.RevoluteConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {p2.Body} bodyB - Second connected body. +* @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. +* @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. +*/ +Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + if (worldPivot === undefined) { worldPivot = null; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; + pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; + + if (worldPivot) + { + worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ]; + } + + var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce }; + + p2.RevoluteConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); +Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image Collection is a special tileset containing mulitple images, with no slicing into each image. +* +* Image Collections are normally created automatically when Tiled data is loaded. +* +* @class Phaser.ImageCollection +* @constructor +* @param {string} name - The name of the image collection in the map data. +* @param {integer} firstgid - The first image index this image collection contains. +* @param {integer} [width=32] - Width of widest image (in pixels). +* @param {integer} [height=32] - Height of tallest image (in pixels). +* @param {integer} [margin=0] - The margin around all images in the collection (in pixels). +* @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). +* @param {object} [properties={}] - Custom Image Collection properties. +*/ +Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Image Collection. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of the widest image (in pixels). + * @property {integer} imageWidth + * @readonly + */ + this.imageWidth = width | 0; + + /** + * The height of the tallest image (in pixels). + * @property {integer} imageHeight + * @readonly + */ + this.imageHeight = height | 0; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageMarge + * @readonly + */ + // Modified internally + this.imageMargin = margin | 0; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageSpacing + * @readonly + */ + this.imageSpacing = spacing | 0; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached images that are a part of this collection. + * @property {array} images + * @readonly + */ + // Modified internally + this.images = []; + + /** + * The total number of images in the image collection. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; +}; + +Phaser.ImageCollection.prototype = { + + /** + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.ImageCollection#containsImageIndex + * @param {integer} imageIndex - The image index to search for. + * @return {boolean} True if this Image Collection contains the given index. + */ + containsImageIndex: function (imageIndex) { + + return ( + imageIndex >= this.firstgid && + imageIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Add an image to this Image Collection. + * + * @method Phaser.ImageCollection#addImage + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + */ + addImage: function (gid, image) { + + this.images.push({ gid: gid, image: image }); + this.total++; + + } + +}; + +Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile is a representation of a single tile within the Tilemap. +* +* @class Phaser.Tile +* @constructor +* @param {object} layer - The layer in the Tilemap data that this tile belongs to. +* @param {number} index - The index of this tile type in the core map data. +* @param {number} x - The x coordinate of this tile. +* @param {number} y - The y coordinate of this tile. +* @param {number} width - Width of the tile. +* @param {number} height - Height of the tile. +*/ +Phaser.Tile = function (layer, index, x, y, width, height) { + + /** + * @property {object} layer - The layer in the Tilemap data that this tile belongs to. + */ + this.layer = layer; + + /** + * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. + */ + this.index = index; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.x = x; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.y = y; + + /** + * @property {number} rotation - The rotation angle of this tile. + */ + this.rotation = 0; + + /** + * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not. + */ + this.flipped = false; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.worldX = x * width; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.worldY = y * height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.height = height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.centerX = Math.abs(width / 2); + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.centerY = Math.abs(height / 2); + + /** + * @property {number} alpha - The alpha value at which this tile is drawn to the canvas. + */ + this.alpha = 1; + + /** + * @property {object} properties - Tile specific properties. + */ + this.properties = {}; + + /** + * @property {boolean} scanned - Has this tile been walked / turned into a poly? + */ + this.scanned = false; + + /** + * @property {boolean} faceTop - Is the top of this tile an interesting edge? + */ + this.faceTop = false; + + /** + * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge? + */ + this.faceBottom = false; + + /** + * @property {boolean} faceLeft - Is the left of this tile an interesting edge? + */ + this.faceLeft = false; + + /** + * @property {boolean} faceRight - Is the right of this tile an interesting edge? + */ + this.faceRight = false; + + /** + * @property {boolean} collideLeft - Indicating collide with any object on the left. + * @default + */ + this.collideLeft = false; + + /** + * @property {boolean} collideRight - Indicating collide with any object on the right. + * @default + */ + this.collideRight = false; + + /** + * @property {boolean} collideUp - Indicating collide with any object on the top. + * @default + */ + this.collideUp = false; + + /** + * @property {boolean} collideDown - Indicating collide with any object on the bottom. + * @default + */ + this.collideDown = false; + + /** + * @property {function} collisionCallback - Tile collision callback. + * @default + */ + this.collisionCallback = null; + + /** + * @property {object} collisionCallbackContext - The context in which the collision callback will be called. + * @default + */ + this.collisionCallbackContext = this; + + /** + * @property {boolean} debug + * @default + */ + this.debug = false; + +}; + +Phaser.Tile.prototype = { + + /** + * Check if the given x and y world coordinates are within this Tile. + * + * @method Phaser.Tile#containsPoint + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ + containsPoint: function (x, y) { + + return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom); + + }, + + /** + * Check for intersection with this tile. + * + * @method Phaser.Tile#intersects + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + */ + 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; + + }, + + /** + * Set a callback to be called when this tile is hit by an object. + * The callback must true true for collision processing to take place. + * + * @method Phaser.Tile#setCollisionCallback + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + */ + setCollisionCallback: function (callback, context) { + + this.collisionCallback = callback; + this.collisionCallbackContext = context; + + }, + + /** + * Clean up memory. + * + * @method Phaser.Tile#destroy + */ + destroy: function () { + + this.collisionCallback = null; + this.collisionCallbackContext = null; + this.properties = null; + + }, + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tile#setCollision + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} right - Indicating collide with any object on the right. + * @param {boolean} up - Indicating collide with any object on the top. + * @param {boolean} down - Indicating collide with any object on the bottom. + */ + setCollision: function (left, right, up, down) { + + this.collideLeft = left; + this.collideRight = right; + this.collideUp = up; + this.collideDown = down; + + this.faceLeft = left; + this.faceRight = right; + this.faceTop = up; + this.faceBottom = down; + + }, + + /** + * Reset collision status flags. + * + * @method Phaser.Tile#resetCollision + */ + 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; + + }, + + /** + * Is this tile interesting? + * + * @method Phaser.Tile#isInteresting + * @param {boolean} collides - If true will check any collides value. + * @param {boolean} faces - If true will check any face value. + * @return {boolean} True if the Tile is interesting, otherwise false. + */ + isInteresting: function (collides, faces) { + + if (collides && faces) + { + // Does this tile have any collide flags OR interesting face? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback); + } + else if (collides) + { + // Does this tile collide? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + else if (faces) + { + // Does this tile have an interesting face? + return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); + } + + return false; + + }, + + /** + * Copies the tile data and properties from the given tile to this tile. + * + * @method Phaser.Tile#copy + * @param {Phaser.Tile} tile - The tile to copy from. + */ + 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; + +/** +* @name Phaser.Tile#collides +* @property {boolean} collides - True if this tile can collide on any of its faces. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "collides", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + +}); + +/** +* @name Phaser.Tile#canCollide +* @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "canCollide", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); + } + +}); + +/** +* @name Phaser.Tile#left +* @property {number} left - The x value in pixels. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "left", { + + get: function () { + return this.worldX; + } + +}); + +/** +* @name Phaser.Tile#right +* @property {number} right - The sum of the x and width properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "right", { + + get: function () { + return this.worldX + this.width; + } + +}); + +/** +* @name Phaser.Tile#top +* @property {number} top - The y value. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "top", { + + get: function () { + return this.worldY; + } + +}); + +/** +* @name Phaser.Tile#bottom +* @property {number} bottom - The sum of the y and height properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "bottom", { + + get: function () { + return this.worldY + this.height; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. +* +* Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org +* +* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. +* When using CSV data you must provide the key and the tileWidth and tileHeight parameters. +* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. +* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. +* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. +* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. +* +* @class Phaser.Tilemap +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. +* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +*/ +Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {string} key - The key of this map data in the Phaser.Cache. + */ + this.key = key; + + var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height); + + if (data === null) + { + return; + } + + /** + * @property {number} width - The width of the map (in tiles). + */ + this.width = data.width; + + /** + * @property {number} height - The height of the map (in tiles). + */ + this.height = data.height; + + /** + * @property {number} tileWidth - The base width of the tiles in the map (in pixels). + */ + this.tileWidth = data.tileWidth; + + /** + * @property {number} tileHeight - The base height of the tiles in the map (in pixels). + */ + this.tileHeight = data.tileHeight; + + /** + * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + */ + this.orientation = data.orientation; + + /** + * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + */ + this.format = data.format; + + /** + * @property {number} version - The version of the map data (as specified in Tiled, usually 1). + */ + this.version = data.version; + + /** + * @property {object} properties - Map specific properties as specified in Tiled. + */ + this.properties = data.properties; + + /** + * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth. + */ + this.widthInPixels = data.widthInPixels; + + /** + * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight. + */ + this.heightInPixels = data.heightInPixels; + + /** + * @property {array} layers - An array of Tilemap layer data. + */ + this.layers = data.layers; + + /** + * @property {array} tilesets - An array of Tilesets. + */ + this.tilesets = data.tilesets; + + /** + * @property {array} imagecollections - An array of Image Collections. + */ + this.imagecollections = data.imagecollections; + + /** + * @property {array} tiles - The super array of Tiles. + */ + this.tiles = data.tiles; + + /** + * @property {array} objects - An array of Tiled Object Layers. + */ + this.objects = data.objects; + + /** + * @property {array} collideIndexes - An array of tile indexes that collide. + */ + this.collideIndexes = []; + + /** + * @property {array} collision - An array of collision data (polylines, etc). + */ + this.collision = data.collision; + + /** + * @property {array} images - An array of Tiled Image Layers. + */ + this.images = data.images; + + /** + * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data. + */ + this.enableDebug = false; + + /** + * @property {number} currentLayer - The current layer. + */ + this.currentLayer = 0; + + /** + * @property {array} debugMap - Map data used for debug values only. + */ + this.debugMap = []; + + /** + * @property {array} _results - Internal var. + * @private + */ + this._results = []; + + /** + * @property {number} _tempA - Internal var. + * @private + */ + this._tempA = 0; + + /** + * @property {number} _tempB - Internal var. + * @private + */ + this._tempB = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.CSV = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.TILED_JSON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.NORTH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.EAST = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.SOUTH = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.WEST = 3; + +Phaser.Tilemap.prototype = { + + /** + * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. + * + * @method Phaser.Tilemap#create + * @param {string} name - The name of the default layer of the map. + * @param {number} width - The width of the map in tiles. + * @param {number} height - The height of the map in tiles. + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + create: function (name, width, height, tileWidth, tileHeight, group) { + + if (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); + + }, + + /** + * Sets the base tile size for the map. + * + * @method Phaser.Tilemap#setTileSize + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + */ + setTileSize: function (tileWidth, tileHeight) { + + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.widthInPixels = this.width * tileWidth; + this.heightInPixels = this.height * tileHeight; + + }, + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. + * + * @method Phaser.Tilemap#addTilesetImage + * @param {string} tileset - The name of the tileset as specified in the map data. + * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset. + * If `undefined` or `null` it will look for an image with a key matching the tileset parameter. + * You can also pass in a BitmapData which can be used instead of an Image. + * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. + * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. + * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. + * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. + * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. + * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed. + */ + addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { + + if (tileset === undefined) { return null; } + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (gid === undefined) { gid = 0; } + + // In-case we're working from a blank map + if (tileWidth === 0) + { + tileWidth = 32; + } + + if (tileHeight === 0) + { + tileHeight = 32; + } + + var img = null; + + if (key === undefined || key === null) + { + key = tileset; + } + + if (key instanceof Phaser.BitmapData) + { + img = key.canvas; + } + else + { + if (!this.game.cache.checkImageKey(key)) + { + console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"'); + return null; + } + + img = this.game.cache.getImage(key); + } + + var idx = this.getTilesetIndex(tileset); + + if (idx === null && this.format === Phaser.Tilemap.TILED_JSON) + { + console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + tileset + '"'); + console.log('Tilesets: ', this.tilesets); + return null; + } + + if (this.tilesets[idx]) + { + this.tilesets[idx].setImage(img); + return this.tilesets[idx]; + } + else + { + var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {}); + + newSet.setImage(img); + + 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; t < gid + newSet.total; t++) + { + this.tiles[t] = [x, y, i]; + + x += tileWidth + tileSpacing; + + count++; + + if (count === newSet.total) + { + break; + } + + countX++; + + if (countX === newSet.columns) + { + x = tileMargin; + y += tileHeight + tileSpacing; + + countX = 0; + countY++; + + if (countY === newSet.rows) + { + break; + } + } + } + + return newSet; + + } + + return null; + + }, + + /** + * Creates a Sprite for every {@link http://doc.mapeditor.org/reference/tmx-map-format/#object object} matching the `gid` argument. You can optionally specify the group that the Sprite will be created in. If none is + * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to + * configure Sprite properties from within the map editor. For example giving an object a property of `alpha: 0.5` in the map editor will duplicate that when the + * Sprite is created. You could also give it a value like: `body.velocity.x: 100` to set it moving automatically. + * + * The `gid` argument is matched against: + * + * 1. For a tile object, the tile identifier (`gid`); or + * 2. The object's unique ID (`id`); or + * 3. The object's `name` (a string) + * + * @method Phaser.Tilemap#createFromObjects + * @param {string} name - The name of the Object Group to create Sprites from. + * @param {number|string} gid - The object's tile reference (gid), unique ID (id) or name. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. + * @param {boolean} [exists=true] - The default exists state of the Sprite. + * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. + * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. + * @param {boolean} [adjustSize=true] - By default the width and height of the objects are transferred to the sprite. This parameter controls that behavior. + */ + createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY, adjustSize) { + + if (exists === undefined) { exists = true; } + if (autoCull === undefined) { autoCull = false; } + if (group === undefined) { group = this.game.world; } + if (CustomClass === undefined) { CustomClass = Phaser.Sprite; } + if (adjustY === undefined) { adjustY = true; } + if (adjustSize === undefined) { adjustSize = true; } + + if (!this.objects[name]) + { + console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name); + console.log('Objects: ', this.objects); + return; + } + + for (var i = 0; i < this.objects[name].length; i++) + { + var found = false; + var obj = this.objects[name][i]; + + if (obj.gid !== undefined && typeof gid === 'number' && obj.gid === gid) + { + found = true; + } + else if (obj.id !== undefined && typeof gid === 'number' && obj.id === gid) + { + found = true; + } + else if (obj.name !== undefined && typeof gid === 'string' && obj.name === gid) + { + found = true; + } + + if (found) + { + var sprite = new CustomClass(this.game, parseFloat(obj.x, 10), parseFloat(obj.y, 10), key, frame); + + sprite.name = obj.name; + sprite.autoCull = autoCull; + sprite.exists = exists; + sprite.visible = obj.visible; + + if (adjustSize) + { + if (obj.width) + { + sprite.width = obj.width; + } + + if (obj.height) + { + sprite.height = obj.height; + } + } + + if (obj.rotation) + { + sprite.angle = obj.rotation; + } + + if (adjustY) + { + sprite.y -= sprite.height; + } + + group.add(sprite); + + for (var property in obj.properties) + { + group.set(sprite, property, obj.properties[property], false, false, 0, true); + } + } + } + + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the map data. + * You can specify the group that the Sprite will be created in. If none is given it will be created in the World. + * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special + * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemap#createFromTiles + * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from. + * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. + * @return {integer} The number of Sprites that were created. + */ + createFromTiles: function (tiles, replacements, key, layer, group, properties) { + + if (typeof tiles === 'number') { tiles = [tiles]; } + + if (replacements === undefined || replacements === null) + { + replacements = []; + } + else if (typeof replacements === 'number') + { + replacements = [replacements]; + } + + layer = this.getLayer(layer); + + if (group === undefined) { group = this.game.world; } + if (properties === undefined) { properties = {}; } + + if (properties.customClass === undefined) + { + properties.customClass = Phaser.Sprite; + } + + if (properties.adjustY === undefined) + { + properties.adjustY = true; + } + + var lw = this.layers[layer].width; + var lh = this.layers[layer].height; + + this.copy(0, 0, lw, lh, layer); + + if (this._results.length < 2) + { + return 0; + } + + var total = 0; + var sprite; + + for (var i = 1, len = this._results.length; i < len; i++) + { + if (tiles.indexOf(this._results[i].index) !== -1) + { + sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key); + + for (var property in properties) + { + sprite[property] = properties[property]; + } + + group.add(sprite); + total++; + } + + } + + if (replacements.length === 1) + { + // Assume 1 replacement for all types of tile given + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer); + } + } + else if (replacements.length > 1) + { + // Assume 1 for 1 mapping + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer); + } + } + + return total; + + }, + + /** + * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. + * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. + * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. + * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. + * + * @method Phaser.Tilemap#createLayer + * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. + * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. + * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. + * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. + */ + createLayer: function (layer, width, height, group) { + + // Add Buffer support for the left of the canvas + + if (width === undefined) { width = this.game.width; } + if (height === undefined) { height = this.game.height; } + if (group === undefined) { group = this.game.world; } + + var index = layer; + + if (typeof layer === 'string') + { + index = this.getLayerIndex(layer); + } + + if (index === null || index > this.layers.length) + { + console.warn('Tilemap.createLayer: Invalid layer ID given: "' + layer + '"'); + console.log('Layers: ', this.layers); + return; + } + + // Sort out the display dimensions, so they never render too much, or too little. + + if (width === undefined || width <= 0) + { + width = Math.min(this.game.width, this.layers[index].widthInPixels); + } + else if (width > this.game.width) + { + width = this.game.width; + } + + if (height === undefined || height <= 0) + { + height = Math.min(this.game.height, this.layers[index].heightInPixels); + } + else if (height > this.game.height) + { + height = this.game.height; + } + + if (this.enableDebug) + { + console.group('Tilemap.createLayer'); + console.log('Name:', this.layers[index].name); + console.log('Size:', width, 'x', height); + console.log('Tileset:', this.tilesets[0].name, 'index:', index); + } + + var rootLayer = group.add(new Phaser.TilemapLayer(this.game, this, index, width, height)); + + if (this.enableDebug) + { + console.groupEnd(); + } + + return rootLayer; + + }, + + + /** + * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. + * + * @method Phaser.Tilemap#createBlankLayer + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {number} width - The width of the layer in tiles. + * @param {number} height - The height of the layer in tiles. + * @param {number} tileWidth - The width of the tiles the layer uses for calculations. + * @param {number} tileHeight - The height of the tiles the layer uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) { + + if (group === undefined) { group = this.game.world; } + + if (this.getLayerIndex(name) !== null) + { + console.warn('Tilemap.createBlankLayer: Layer with matching name already exists: ' + name); + 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; y < height; y++) + { + row = []; + + for (var x = 0; x < width; x++) + { + row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight)); + } + + output.push(row); + } + + layer.data = output; + + this.layers.push(layer); + + this.currentLayer = this.layers.length - 1; + + var w = layer.widthInPixels; + var h = layer.heightInPixels; + + if (w > this.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); + + }, + + /** + * Gets the layer index based on the layers name. + * + * @method Phaser.Tilemap#getIndex + * @protected + * @param {array} location - The local array to search. + * @param {string} name - The name of the array element to get. + * @return {number} The index of the element in the array, or null if not found. + */ + getIndex: function (location, name) { + + for (var i = 0; i < location.length; i++) + { + if (location[i].name === name) + { + return i; + } + } + + return null; + + }, + + /** + * Gets the layer index based on its name. + * + * @method Phaser.Tilemap#getLayerIndex + * @param {string} name - The name of the layer to get. + * @return {number} The index of the layer in this tilemap, or null if not found. + */ + getLayerIndex: function (name) { + + return this.getIndex(this.layers, name); + + }, + + /** + * Gets the tileset index based on its name. + * + * @method Phaser.Tilemap#getTilesetIndex + * @param {string} name - The name of the tileset to get. + * @return {number} The index of the tileset in this tilemap, or null if not found. + */ + getTilesetIndex: function (name) { + + return this.getIndex(this.tilesets, name); + + }, + + /** + * Gets the image index based on its name. + * + * @method Phaser.Tilemap#getImageIndex + * @param {string} name - The name of the image to get. + * @return {number} The index of the image in this tilemap, or null if not found. + */ + getImageIndex: function (name) { + + return this.getIndex(this.images, name); + + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileIndexCallback + * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileIndexCallback: function (indexes, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes]; + } + else + { + // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much + // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit. + this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext }; + } + } + else + { + for (var i = 0, len = indexes.length; i < len; i++) + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes[i]]; + } + else + { + this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext }; + } + } + } + + }, + + /** + * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileLocationCallback + * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} width - The width of the area to copy (given in tiles, not pixels) + * @param {number} height - The height of the area to copy (given in tiles, not pixels) + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].setCollisionCallback(callback, callbackContext); + } + + }, + + /** + * Sets collision on the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [2, 3, 15, 20]. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * Collision-enabled tiles can be collided against Sprites using {@link Phaser.Physics.Arcade#collide}. + * + * You can verify the collision faces by enabling {@link Phaser.TilemapLayer#debug}. + * + * @method Phaser.Tilemap#setCollision + * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollision: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + return this.setCollisionByIndex(indexes, collides, layer, true); + } + else if (Array.isArray(indexes)) + { + // Collide all of the IDs given in the indexes array + for (var i = 0; i < indexes.length; i++) + { + this.setCollisionByIndex(indexes[i], collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + } + + }, + + /** + * Sets collision on a range of tiles where the tile IDs increment sequentially. + * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionBetween + * @param {number} start - The first index of the tile to be set for collision. + * @param {number} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionBetween: function (start, stop, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (start > stop) + { + return; + } + + for (var index = start; index <= stop; index++) + { + this.setCollisionByIndex(index, collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision on all tiles in the given layer, except for the IDs of those in the given array. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionByExclusion + * @param {array} indexes - An array of the tile IDs to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByExclusion: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + // Collide everything, except the IDs given in the indexes array + for (var i = 0, len = this.tiles.length; i < len; i++) + { + if (indexes.indexOf(i) === -1) + { + this.setCollisionByIndex(i, collides, layer, false); + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision values on a tile in the set. + * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. + * + * @method Phaser.Tilemap#setCollisionByIndex + * @protected + * @param {number} index - The index of the tile on the layer. + * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile. + * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByIndex: function (index, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (layer === undefined) { layer = this.currentLayer; } + if (recalculate === undefined) { recalculate = true; } + + if (collides) + { + this.collideIndexes.push(index); + } + else + { + var i = this.collideIndexes.indexOf(index); + + if (i > -1) + { + this.collideIndexes.splice(i, 1); + } + } + + for (var y = 0; y < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile && tile.index === index) + { + if (collides) + { + tile.setCollision(true, true, true, true); + } + else + { + tile.resetCollision(); + } + + tile.faceTop = collides; + tile.faceBottom = collides; + tile.faceLeft = collides; + tile.faceRight = collides; + } + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + return layer; + + }, + + /** + * Gets the TilemapLayer index as used in the setCollision calls. + * + * @method Phaser.Tilemap#getLayer + * @protected + * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer. + * @return {number} The TilemapLayer index. + */ + getLayer: function (layer) { + + if (layer === undefined) + { + layer = this.currentLayer; + } + else if (typeof layer === 'string') + { + var layerArg = layer; + + layer = this.getLayerIndex(layer); + + if (!layer) + { + console.warn('No such layer name: ' + layerArg); + } + } + else if (layer instanceof Phaser.TilemapLayer) + { + layer = layer.index; + } + + return layer; + + }, + + /** + * Turn off/on the recalculation of faces for tile or collision updates. + * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. + * + * @method Phaser.Tilemap#setPreventRecalculate + * @param {boolean} value - If true it will put the recalculation on hold. + */ + setPreventRecalculate: function (value) { + + if (value === true && this.preventingRecalculate !== true) + { + this.preventingRecalculate = true; + this.needToRecalculate = {}; + } + + if (value === false && this.preventingRecalculate === true) + { + this.preventingRecalculate = false; + + for (var i in this.needToRecalculate) + { + this.calculateFaces(i); + } + + this.needToRecalculate = false; + } + + }, + + /** + * Internal function. + * + * @method Phaser.Tilemap#calculateFaces + * @protected + * @param {number} layer - The index of the TilemapLayer to operate on. + */ + calculateFaces: function (layer) { + + if (this.preventingRecalculate) + { + this.needToRecalculate[layer] = true; + return; + } + + var above = null; + var below = null; + var left = null; + var right = null; + + for (var y = 0, h = this.layers[layer].height; y < h; y++) + { + for (var x = 0, w = this.layers[layer].width; x < w; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile) + { + above = this.getTileAbove(layer, x, y); + below = this.getTileBelow(layer, x, y); + left = this.getTileLeft(layer, x, y); + right = this.getTileRight(layer, x, y); + + if (tile.collides) + { + tile.faceTop = true; + tile.faceBottom = true; + tile.faceLeft = true; + tile.faceRight = true; + } + + if (above && above.collides) + { + // There is a tile above this one that also collides, so the top of this tile is no longer interesting + tile.faceTop = false; + } + + if (below && below.collides) + { + // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting + tile.faceBottom = false; + } + + if (left && left.collides) + { + // There is a tile left this one that also collides, so the left of this tile is no longer interesting + tile.faceLeft = false; + } + + if (right && right.collides) + { + // There is a tile right this one that also collides, so the right of this tile is no longer interesting + tile.faceRight = false; + } + } + } + } + + }, + + /** + * Gets the tile above the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileAbove + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileAbove: function (layer, x, y) { + + if (y > 0) + { + return this.layers[layer].data[y - 1][x]; + } + + return null; + + }, + + /** + * Gets the tile below the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileBelow + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileBelow: function (layer, x, y) { + + if (y < this.layers[layer].height - 1) + { + return this.layers[layer].data[y + 1][x]; + } + + return null; + + }, + + /** + * Gets the tile to the left of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileLeft + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileLeft: function (layer, x, y) { + + if (x > 0) + { + return this.layers[layer].data[y][x - 1]; + } + + return null; + + }, + + /** + * Gets the tile to the right of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileRight + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileRight: function (layer, x, y) { + + if (x < this.layers[layer].width - 1) + { + return this.layers[layer].data[y][x + 1]; + } + + return null; + + }, + + /** + * Sets the current layer to the given index. + * + * @method Phaser.Tilemap#setLayer + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + */ + setLayer: function (layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer]) + { + this.currentLayer = layer; + } + + }, + + /** + * Checks if there is a tile at the given location. + * + * @method Phaser.Tilemap#hasTile + * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels) + * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + * @return {boolean} True if there is a tile at the given location, otherwise false. + */ + hasTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined) + { + return false; + } + + return (this.layers[layer].data[y][x].index > -1); + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. + * + * @method Phaser.Tilemap#removeTile + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.hasTile(x, y, layer)) + { + var tile = this.layers[layer].data[y][x]; + + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight); + + this.layers[layer].dirty = true; + + this.calculateFaces(layer); + + return tile; + } + } + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#removeTileWorldXY + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTileWorldXY: function (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.removeTile(x, y, layer); + + }, + + /** + * Puts a tile of the given index value at the coordinate specified. + * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. + * + * @method Phaser.Tilemap#putTile + * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map. + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + putTile: function (tile, x, y, layer) { + + if (tile === null) + { + return this.removeTile(x, y, layer); + } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + var index; + + if (tile instanceof Phaser.Tile) + { + index = tile.index; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].copy(tile); + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height); + } + } + else + { + index = tile; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].index = index; + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight); + } + } + + if (this.collideIndexes.indexOf(index) > -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; + + }, + + /** + * Puts a tile into the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#putTileWorldXY + * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object. + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + 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); + + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. + * If no match is found it returns null. + * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. + * + * @method Phaser.Tilemap#searchTileIndex + * @param {number} index - The tile index value to search for. + * @param {number} [skip=0] - The number of times to skip a matching tile before returning. + * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @return {Phaser.Tile} The first (or n skipped) tile with the matching index. + */ + searchTileIndex: function (index, skip, reverse, layer) { + + if (skip === undefined) { skip = 0; } + if (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 < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + if (this.layers[layer].data[y][x].index === index) + { + if (c === skip) + { + return this.layers[layer].data[y][x]; + } + else + { + c++; + } + } + } + } + } + + return null; + + }, + + /** + * Gets a tile from the Tilemap Layer. The coordinates are given in tile values. + * + * @method Phaser.Tilemap#getTile + * @param {number} x - X position to get the tile from (given in tile units, not pixels) + * @param {number} y - Y position to get the tile from (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTile: function (x, y, layer, nonNull) { + + if (nonNull === undefined) { nonNull = false; } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.layers[layer].data[y][x].index === -1) + { + if (nonNull) + { + return this.layers[layer].data[y][x]; + } + else + { + return null; + } + } + else + { + return this.layers[layer].data[y][x]; + } + } + else + { + return null; + } + + }, + + /** + * Gets a tile from the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#getTileWorldXY + * @param {number} x - X position to get the tile from (given in pixels) + * @param {number} y - Y position to get the tile from (given in pixels) + * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used. + * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates. + */ + getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) { + + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + + layer = this.getLayer(layer); + + x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; + y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; + + return this.getTile(x, y, layer, nonNull); + + }, + + /** + * Copies all of the tiles in the given rectangular block into the tilemap data buffer. + * + * @method Phaser.Tilemap#copy + * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} width - The width of the area to copy (given in tiles, not pixels) + * @param {integer} height - The height of the area to copy (given in tiles, not pixels) + * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from. + * @return {array} An array of the tiles that were copied. + */ + copy: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + if (!this.layers[layer]) + { + this._results.length = 0; + return; + } + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.layers[layer].width; } + if (height === undefined) { height = this.layers[layer].height; } + + if (x < 0) + { + x = 0; + } + + if (y < 0) + { + y = 0; + } + + if (width > this.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; ty < y + height; ty++) + { + for (var tx = x; tx < x + width; tx++) + { + this._results.push(this.layers[layer].data[ty][tx]); + } + } + + return this._results; + + }, + + /** + * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. + * + * @method Phaser.Tilemap#paste + * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels) + * @param {array} tileblock - The block of tiles to paste. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into. + */ + paste: function (x, y, tileblock, layer) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + layer = this.getLayer(layer); + + if (!tileblock || tileblock.length < 2) + { + return; + } + + // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste + var diffX = x - tileblock[1].x; + var diffY = y - tileblock[1].y; + + for (var i = 1; i < tileblock.length; i++) + { + this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]); + } + + this.layers[layer].dirty = true; + this.calculateFaces(layer); + + }, + + /** + * Scans the given area for tiles with an index matching tileA and swaps them with tileB. + * + * @method Phaser.Tilemap#swap + * @param {number} tileA - First tile index. + * @param {number} tileB - Second tile index. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + swap: function (tileA, tileB, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._tempA = tileA; + this._tempB = tileB; + + this._results.forEach(this.swapHandler, this); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Internal function that handles the swapping of tiles. + * + * @method Phaser.Tilemap#swapHandler + * @private + * @param {number} value + */ + swapHandler: function (value) { + + if (value.index === this._tempA) + { + // Swap A with B + value.index = this._tempB; + } + else if (value.index === this._tempB) + { + // Swap B with A + value.index = this._tempA; + } + + }, + + /** + * For each tile in the given area defined by x/y and width/height run the given callback. + * + * @method Phaser.Tilemap#forEach + * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {number} context - The context under which the callback should be run. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + forEach: function (callback, context, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._results.forEach(callback, context); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. + * + * @method Phaser.Tilemap#replace + * @param {number} source - The tile index value to scan for. + * @param {number} dest - The tile index value to replace found tiles with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + replace: function (source, dest, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + if (this._results[i].index === source) + { + this._results[i].index = dest; + } + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Randomises a set of tiles in a given area. + * + * @method Phaser.Tilemap#random + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + random: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + var idx = this._results[t].index; + + if (indexes.indexOf(idx) === -1) + { + indexes.push(idx); + } + } + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = this.game.rnd.pick(indexes); + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! + * + * @method Phaser.Tilemap#shuffle + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + shuffle: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + indexes.push(this._results[t].index); + } + } + + Phaser.ArrayUtils.shuffle(indexes); + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = indexes[i - 1]; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Fills the given area with the specified tile. + * + * @method Phaser.Tilemap#fill + * @param {number} index - The index of the tile that the area will be filled with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + fill: function (index, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = index; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Removes all layers from this tile map. + * + * @method Phaser.Tilemap#removeAllLayers + */ + removeAllLayers: function () { + + this.layers.length = 0; + this.currentLayer = 0; + + }, + + /** + * Dumps the tilemap data out to the console. + * + * @method Phaser.Tilemap#dump + */ + dump: function () { + + var txt = ''; + var args = ['']; + + for (var y = 0; y < this.layers[this.currentLayer].height; y++) + { + for (var x = 0; x < this.layers[this.currentLayer].width; x++) + { + txt += "%c "; + + if (this.layers[this.currentLayer].data[y][x] > 1) + { + 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); + + }, + + /** + * Removes all layer data from this tile map and nulls the game reference. + * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. + * + * @method Phaser.Tilemap#destroy + */ + destroy: function () { + + this.removeAllLayers(); + this.data = []; + this.game = null; + + } + +}; + +Phaser.Tilemap.prototype.constructor = Phaser.Tilemap; + +/** +* @name Phaser.Tilemap#layer +* @property {number|string|Phaser.TilemapLayer} layer - The current layer object. +*/ +Object.defineProperty(Phaser.Tilemap.prototype, "layer", { + + get: function () { + + return this.layers[this.currentLayer]; + + }, + + set: function (value) { + + if (value !== this.currentLayer) + { + this.setLayer(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. +* +* Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. +* +* By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. +* +* @class Phaser.TilemapLayer +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs. +* @param {integer} index - The index of the TileLayer to render within the Tilemap. +* @param {integer} width - Width of the renderable area of the layer (in pixels). +* @param {integer} height - Height of the renderable area of the layer (in pixels). +*/ +Phaser.TilemapLayer = function (game, tilemap, index, width, height) { + + width |= 0; + height |= 0; + + Phaser.Sprite.call(this, game, 0, 0); + + /** + * The Tilemap to which this layer is bound. + * @property {Phaser.Tilemap} map + * @protected + * @readonly + */ + this.map = tilemap; + + /** + * The index of this layer within the Tilemap. + * @property {number} index + * @protected + * @readonly + */ + this.index = index; + + /** + * The layer object within the Tilemap that this layer represents. + * @property {object} layer + * @protected + * @readonly + */ + this.layer = tilemap.layers[index]; + + /** + * The canvas to which this TilemapLayer draws. + * @property {HTMLCanvasElement} canvas + * @protected + */ + this.canvas = Phaser.CanvasPool.create(this, width, height); + + /** + * The 2d context of the canvas. + * @property {CanvasRenderingContext2D} context + * @private + */ + this.context = this.canvas.getContext('2d'); + + this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas, null, this.game.resolution))); + + /** + * The const type of this object. + * @property {number} type + * @readonly + * @protected + * @default Phaser.TILEMAPLAYER + */ + this.type = Phaser.TILEMAPLAYER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.TILEMAPLAYER; + + /** + * Settings that control standard (non-diagnostic) rendering. + * + * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view. + * This can greatly improve scrolling rendering performance, especially when there are many small tiles. + * It should only be disabled in rare cases. + * + * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas. + * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior + * in some browsers, notably Safari. + * + * @default + */ + this.renderSettings = { + enableScrollDelta: true, + overdrawRatio: 0.20, + copyCanvas: null + }; + + /** + * Enable an additional "debug rendering" pass to display collision information. + * + * @property {boolean} debug + * @default + */ + this.debug = false; + + /** + * @property {boolean} exists - Controls if the core game loop and physics update this game object or not. + */ + this.exists = true; + + /** + * Settings used for debugging and diagnostics. + * + * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. + * + * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. + * + * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. + * + * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. + * + */ + this.debugSettings = { + + missingImageFill: 'rgb(255,255,255)', + debuggedTileOverfill: 'rgba(0,255,0,0.4)', + + forceFullRedraw: true, + + debugAlpha: 0.5, + facingEdgeStroke: 'rgba(0,255,0,1)', + collidingTileOverfill: 'rgba(0,255,0,0.2)' + + }; + + /** + * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). + * @property {number} scrollFactorX + * @public + * @default + */ + this.scrollFactorX = 1; + + /** + * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) + * @property {number} scrollFactorY + * @public + * @default + */ + this.scrollFactorY = 1; + + /** + * If true tiles will be force rendered, even if such is not believed to be required. + * @property {boolean} dirty + * @protected + */ + this.dirty = true; + + /** + * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. + * @property {integer} rayStepRate + * @default + */ + this.rayStepRate = 4; + + /** + * Flag controlling if the layer tiles wrap at the edges. + * @property {boolean} _wrap + * @private + */ + this._wrap = false; + + /** + * Local map data and calculation cache. + * @property {object} _mc + * @private + */ + this._mc = { + + // Used to bypass rendering without reliance on `dirty` and detect changes. + scrollX: 0, + scrollY: 0, + renderWidth: 0, + renderHeight: 0, + + tileWidth: tilemap.tileWidth, + tileHeight: tilemap.tileHeight, + + // Collision width/height (pixels) + // What purpose do these have? Most things use tile width/height directly. + // This also only extends collisions right and down. + cw: tilemap.tileWidth, + ch: tilemap.tileHeight, + + // Cached tilesets from index -> Tileset + tilesets: [] + + }; + + /** + * The current canvas left after scroll is applied. + * @property {number} _scrollX + * @private + */ + this._scrollX = 0; + + /** + * The current canvas top after scroll is applied. + * @property {number} _scrollY + * @private + */ + this._scrollY = 0; + + /** + * The position offset of the layer's tiles. + * @property {Phaser.Point} + */ + this.tileOffset = new Phaser.Point(this.layer.offsetX || 0, this.layer.offsetY || 0); + + /** + * Used for caching the tiles / array of tiles. + * @property {Phaser.Tile[]} _results + * @private + */ + this._results = []; + + if (!game.device.canvasBitBltShift) + { + this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas(); + } + + this.fixedToCamera = true; + +}; + +Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer; + +Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* The shared double-copy canvas, created as needed. +* +* @private +* @static +*/ +Phaser.TilemapLayer.sharedCopyCanvas = null; + +/** +* Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. +* +* Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. +* +* @method Phaser.TilemapLayer#ensureSharedCopyCanvas +* @protected +* @static +*/ +Phaser.TilemapLayer.ensureSharedCopyCanvas = function () { + + if (!this.sharedCopyCanvas) + { + this.sharedCopyCanvas = Phaser.CanvasPool.create(this, 2, 2); + } + + return this.sharedCopyCanvas; + +}; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TilemapLayer#preUpdate +*/ +Phaser.TilemapLayer.prototype.preUpdate = function() { + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.postUpdate. Handles cache updates. +* +* @method Phaser.TilemapLayer#postUpdate +* @protected +*/ +Phaser.TilemapLayer.prototype.postUpdate = function () { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderCanvas function. +* +* @method Phaser.TilemapLayer#_renderCanvas +* @private +*/ +Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderWebGL function. +* +* @method Phaser.TilemapLayer#_renderWebGL +* @private +*/ +Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Destroys this TilemapLayer. +* +* @method Phaser.TilemapLayer#destroy +*/ +Phaser.TilemapLayer.prototype.destroy = function() { + + Phaser.CanvasPool.remove(this); + + Phaser.Component.Destroy.prototype.destroy.call(this); + +}; + +/** +* Resizes the internal canvas and texture frame used by this TilemapLayer. +* +* This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully +* selected times. +* +* Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not +* modified either. You will have to handle both of these things from your game code if required. +* +* @method Phaser.TilemapLayer#resize +* @param {number} width - The new width of the TilemapLayer +* @param {number} height - The new height of the TilemapLayer +*/ +Phaser.TilemapLayer.prototype.resize = function (width, height) { + + this.canvas.width = width; + this.canvas.height = height; + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.texture.baseTexture.width = width; + this.texture.baseTexture.height = height; + + this.texture.baseTexture.dirty(); + this.texture.requiresUpdate = true; + + this.texture._updateUvs(); + + this.dirty = true; + +}; + +/** +* Sets the world size to match the size of this layer. +* +* @method Phaser.TilemapLayer#resizeWorld +* @public +*/ +Phaser.TilemapLayer.prototype.resizeWorld = function () { + + this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y); + +}; + +/** + * Get the X axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getLayerOffsetX + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetX = function () { + + return this.tileOffset.x || ((!this.fixedToCamera) ? this.position.x : 0); + +}; + +/** + * Get the Y axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getTileOffsetY + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetY = function () { + + return this.tileOffset.y || ((!this.fixedToCamera) ? this.position.y : 0); + +}; + +/** +* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixX +* @private +* @param {number} x - x coordinate in camera space +* @return {number} x coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixX = function (x) { + + if (this.scrollFactorX === 1 || (this.scrollFactorX === 0 && this.position.x === 0)) + { + return x; + } + + // This executes if the scrollFactorX is 0 and the x position of the tilemap is off from standard. + if (this.scrollFactorX === 0 && this.position.x !== 0) + { + return x - this.position.x; + } + + return this._scrollX + (x - (this._scrollX / this.scrollFactorX)); + +}; + +/** +* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixX +* @private +* @param {number} x - x coordinate in scrollFactor-adjusted dimensions +* @return {number} x coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixX = function (x) { + + if (this.scrollFactorX === 1) + { + return x; + } + + return (this._scrollX / this.scrollFactorX) + (x - this._scrollX); + +}; + +/** +* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixY +* @private +* @param {number} y - y coordinate in camera space +* @return {number} y coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixY = function (y) { + + if (this.scrollFactorY === 1 || (this.scrollFactorY === 0 && this.position.y === 0)) + { + return y; + } + + // This executes if the scrollFactorY is 0 and the y position of the tilemap is off from standard. + if (this.scrollFactorY === 0 && this.position.y !== 0) + { + return y - this.position.y; + } + + return this._scrollY + (y - (this._scrollY / this.scrollFactorY)); + +}; + +/** +* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixY +* @private +* @param {number} y - y coordinate in scrollFactor-adjusted dimensions +* @return {number} y coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixY = function (y) { + + if (this.scrollFactorY === 1) + { + return y; + } + + return (this._scrollY / this.scrollFactorY) + (y - this._scrollY); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileX +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @return {integer} The X map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileX = function (x) { + + // var tileWidth = this.tileWidth * this.scale.x; + return Math.floor(this._fixX(x) / this._mc.tileWidth); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileY +* @public +* @param {number} y - Y position of the point in target tile (in pixels). +* @return {integer} The Y map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileY = function (y) { + + // var tileHeight = this.tileHeight * this.scale.y; + return Math.floor(this._fixY(y) / this._mc.tileHeight); + +}; + +/** +* Convert a pixel coordinate to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileXY +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @param {number} y - Y position of the point in target tile (in pixels). +* @param {(Phaser.Point|object)} point - The Point/object to update. +* @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set. +*/ +Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) { + + point.x = this.getTileX(x); + point.y = this.getTileY(y); + + return point; + +}; + +/** +* Gets all tiles that intersect with the given line. +* +* @method Phaser.TilemapLayer#getRayCastTiles +* @public +* @param {Phaser.Line} line - The line used to determine which tiles to return. +* @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`. +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {Phaser.Tile[]} An array of Phaser.Tiles. +*/ +Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) { + + if (!stepRate) { stepRate = this.rayStepRate; } + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + // First get all tiles that touch the bounds of the line + var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace); + + if (tiles.length === 0) + { + return []; + } + + // Now we only want the tiles that intersect with the points on this line + var coords = line.coordinatesOnLine(stepRate); + var results = []; + + for (var i = 0; i < tiles.length; i++) + { + for (var t = 0; t < coords.length; t++) + { + var tile = tiles[i]; + var coord = coords[t]; + if (tile.containsPoint(coord[0], coord[1])) + { + results.push(tile); + break; + } + } + } + + return results; + +}; + +/** +* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. +* +* @method Phaser.TilemapLayer#getTiles +* @public +* @param {number} x - X position of the top left corner (in pixels). +* @param {number} y - Y position of the top left corner (in pixels). +* @param {number} width - Width of the area to get (in pixels). +* @param {number} height - Height of the area to get (in pixels). +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {array} An array of Tiles. +*/ +Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) { + + // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all) + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + var fetchAll = !(collides || interestingFace); + + // Adjust the x,y coordinates for scrollFactor + x = this._fixX(x); + y = this._fixY(y); + + // Convert the pixel values into tile coordinates + var tx = Math.floor(x / (this._mc.cw * this.scale.x)); + var ty = Math.floor(y / (this._mc.ch * this.scale.y)); + // Don't just use ceil(width/cw) to allow account for x/y diff within cell + var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx; + var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty; + + while (this._results.length) + { + this._results.pop(); + } + + for (var wy = ty; wy < ty + th; wy++) + { + for (var wx = tx; wx < tx + tw; wx++) + { + var row = this.layer.data[wy]; + + if (row && row[wx]) + { + if (fetchAll || row[wx].isInteresting(collides, interestingFace)) + { + this._results.push(row[wx]); + } + } + } + } + + return this._results.slice(); + +}; + +/** +* Returns the appropriate tileset for the index, updating the internal cache as required. +* This should only be called if `tilesets[index]` evaluates to undefined. +* +* @method Phaser.TilemapLayer#resolveTileset +* @private +* @param {integer} Tile index +* @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping. +*/ +Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) { + + var tilesets = this._mc.tilesets; + + // Try for dense array if reasonable + if (tileIndex < 2000) + { + while (tilesets.length < tileIndex) + { + tilesets.push(undefined); + } + } + + var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2]; + + if (setIndex !== null) + { + var tileset = this.map.tilesets[setIndex]; + + if (tileset && tileset.containsTileIndex(tileIndex)) + { + return (tilesets[tileIndex] = tileset); + } + } + + return (tilesets[tileIndex] = null); + +}; + +/** +* The TilemapLayer caches tileset look-ups. +* +* Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. +* +* @method Phaser.TilemapLayer#resetTilesetCache +* @public +*/ +Phaser.TilemapLayer.prototype.resetTilesetCache = function () { + + var tilesets = this._mc.tilesets; + + while (tilesets.length) + { + tilesets.pop(); + } + +}; + +/** + * This method will set the scale of the tilemap as well as update the underlying block data of this layer. + * + * @method Phaser.TilemapLayer#setScale + * @param {number} [xScale=1] - The scale factor along the X-plane + * @param {number} [yScale] - The scale factor along the Y-plane + */ +Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) { + + xScale = xScale || 1; + yScale = yScale || xScale; + + for (var y = 0; y < this.layer.data.length; y++) + { + var row = this.layer.data[y]; + + for (var x = 0; x < row.length; x++) + { + var tile = row[x]; + + tile.width = this.map.tileWidth * xScale; + tile.height = this.map.tileHeight * yScale; + + tile.worldX = tile.x * tile.width; + tile.worldY = tile.y * tile.height; + } + } + + this.scale.setTo(xScale, yScale); + +}; + +/** +* Shifts the contents of the canvas - does extra math so that different browsers agree on the result. +* +* The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in. +* +* @method Phaser.TilemapLayer#shiftCanvas +* @private +* @param {CanvasRenderingContext2D} context - The context to shift +* @param {integer} x +* @param {integer} y +*/ +Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) { + + var canvas = context.canvas; + var copyW = canvas.width - Math.abs(x); + var copyH = canvas.height - Math.abs(y); + + // When x/y non-negative + var dx = 0; + var dy = 0; + var sx = x; + var sy = y; + + if (x < 0) + { + dx = -x; + sx = 0; + } + + if (y < 0) + { + dy = -y; + sy = 0; + } + + var copyCanvas = this.renderSettings.copyCanvas; + + if (copyCanvas) + { + // Use a second copy buffer, without slice support, for Safari .. again. + // Ensure copy canvas is large enough + if (copyCanvas.width < copyW || copyCanvas.height < copyH) + { + copyCanvas.width = copyW; + copyCanvas.height = copyH; + } + + var copyContext = copyCanvas.getContext('2d'); + copyContext.clearRect(0, 0, copyW, copyH); + copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH); + // clear allows default 'source-over' semantics + context.clearRect(sx, sy, copyW, copyH); + context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH); + } + else + { + // Avoids a second copy but flickers in Safari / Safari Mobile + // Ref. https://github.com/photonstorm/phaser/issues/1439 + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH); + context.restore(); + } + +}; + +/** +* Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor. +* This will constrain the tile coordinates based on wrapping but not physical coordinates. +* +* @method Phaser.TilemapLayer#renderRegion +* @private +* @param {integer} scrollX - Render x offset/scroll. +* @param {integer} scrollY - Render y offset/scroll. +* @param {integer} left - Leftmost column to render. +* @param {integer} top - Topmost row to render. +* @param {integer} right - Rightmost column to render. +* @param {integer} bottom - Bottommost row to render. +*/ +Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) { + + var context = this.context; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var tilesets = this._mc.tilesets; + var lastAlpha = NaN; + + if (!this._wrap) + { + if (left <= right) // Only adjust if going to render + { + left = Math.max(0, left); + right = Math.min(width - 1, right); + } + if (top <= bottom) + { + top = Math.max(0, top); + bottom = Math.min(height - 1, bottom); + } + } + + // top-left pixel of top-left cell + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values. + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + // tx/ty - are pixel coordinates where tile is drawn + // x/y - is cell location, normalized [0..width/height) in loop + // xmax/ymax - remaining cells to render on column/row + var tx, ty, x, y, xmax, ymax; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + + if (!tile || tile.index < 0) + { + continue; + } + + var index = tile.index; + + var set = tilesets[index]; + + if (set === undefined) + { + set = this.resolveTileset(index); + } + + // Setting the globalAlpha is "surprisingly expensive" in Chrome (38) + if (tile.alpha !== lastAlpha && !this.debug) + { + context.globalAlpha = tile.alpha; + lastAlpha = tile.alpha; + } + + if (set) + { + if (tile.rotation || tile.flipped) + { + context.save(); + context.translate(tx + tile.centerX, ty + tile.centerY); + context.rotate(tile.rotation); + + if (tile.flipped) + { + context.scale(-1, 1); + } + + set.draw(context, -tile.centerX, -tile.centerY, index); + context.restore(); + } + else + { + set.draw(context, tx, ty, index); + } + } + else if (this.debugSettings.missingImageFill) + { + context.fillStyle = this.debugSettings.missingImageFill; + context.fillRect(tx, ty, tw, th); + } + + if (tile.debug && this.debugSettings.debuggedTileOverfill) + { + context.fillStyle = this.debugSettings.debuggedTileOverfill; + context.fillRect(tx, ty, tw, th); + } + + } + + } + +}; + +/** +* Shifts the canvas and render damaged edge tiles. +* +* @method Phaser.TilemapLayer#renderDeltaScroll +* @private +*/ +Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds. + + // Start in pixels + var left = 0; + var right = -tw; + var top = 0; + var bottom = -th; + + if (shiftX < 0) // layer moving left, damage right + { + left = renderW + shiftX; // shiftX neg. + right = renderW - 1; + } + else if (shiftX > 0) + { + // left -> 0 + right = shiftX; + } + + if (shiftY < 0) // layer moving down, damage top + { + top = renderH + shiftY; // shiftY neg. + bottom = renderH - 1; + } + else if (shiftY > 0) + { + // top -> 0 + bottom = shiftY; + } + + this.shiftCanvas(this.context, shiftX, shiftY); + + // Transform into tile-space + left = Math.floor((left + scrollX) / tw); + right = Math.floor((right + scrollX) / tw); + top = Math.floor((top + scrollY) / th); + bottom = Math.floor((bottom + scrollY) / th); + + if (left <= right) + { + // Clear left or right edge + this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH); + + var trueTop = Math.floor((0 + scrollY) / th); + var trueBottom = Math.floor((renderH - 1 + scrollY) / th); + this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom); + } + + if (top <= bottom) + { + // Clear top or bottom edge + this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th); + + var trueLeft = Math.floor((0 + scrollX) / tw); + var trueRight = Math.floor((renderW - 1 + scrollX) / tw); + this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom); + } + +}; + +/** +* Clear and render the entire canvas. +* +* @method Phaser.TilemapLayer#renderFull +* @private +*/ +Phaser.TilemapLayer.prototype.renderFull = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + this.context.clearRect(0, 0, renderW, renderH); + + this.renderRegion(scrollX, scrollY, left, top, right, bottom); + +}; + +/** +* Renders the tiles to the layer canvas and pushes to the display. +* +* @method Phaser.TilemapLayer#render +* @protected +*/ +Phaser.TilemapLayer.prototype.render = function () { + + var redrawAll = false; + + if (!this.visible) + { + return; + } + + if (this.dirty || this.layer.dirty) + { + this.layer.dirty = false; + redrawAll = true; + } + + var renderWidth = this.canvas.width; // Use Sprite.width/height? + var renderHeight = this.canvas.height; + + // Scrolling bias; whole pixels only + var scrollX = this._scrollX | 0; + var scrollY = this._scrollY | 0; + + var mc = this._mc; + var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down + var shiftY = mc.scrollY - scrollY; + + if (!redrawAll && + shiftX === 0 && shiftY === 0 && + mc.renderWidth === renderWidth && mc.renderHeight === renderHeight) + { + // No reason to redraw map, looking at same thing and not invalidated. + return; + } + + this.context.save(); + + mc.scrollX = scrollX; + mc.scrollY = scrollY; + + if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight) + { + // Could support automatic canvas resizing + mc.renderWidth = renderWidth; + mc.renderHeight = renderHeight; + } + + if (this.debug) + { + this.context.globalAlpha = this.debugSettings.debugAlpha; + + if (this.debugSettings.forceFullRedraw) + { + redrawAll = true; + } + } + + if (!redrawAll && + this.renderSettings.enableScrollDelta && + (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight)) + { + this.renderDeltaScroll(shiftX, shiftY); + } + else + { + // Too much change or otherwise requires full render + this.renderFull(); + } + + if (this.debug) + { + this.context.globalAlpha = 1; + this.renderDebug(); + } + + this.texture.baseTexture.dirty(); + + this.dirty = false; + + this.context.restore(); + + return true; + +}; + +/** +* Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true. +* +* See `debugSettings` for assorted configuration options. +* +* @method Phaser.TilemapLayer#renderDebug +* @private +*/ +Phaser.TilemapLayer.prototype.renderDebug = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var context = this.context; + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + var tx, ty, x, y, xmax, ymax; + + context.strokeStyle = this.debugSettings.facingEdgeStroke; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + if (!tile || tile.index < 0 || !tile.collides) + { + continue; + } + + if (this.debugSettings.collidingTileOverfill) + { + context.fillStyle = this.debugSettings.collidingTileOverfill; + context.fillRect(tx, ty, this._mc.cw, this._mc.ch); + } + + if (this.debugSettings.facingEdgeStroke) + { + context.beginPath(); + + if (tile.faceTop) + { + context.moveTo(tx, ty); + context.lineTo(tx + this._mc.cw, ty); + } + + if (tile.faceBottom) + { + context.moveTo(tx, ty + this._mc.ch); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + if (tile.faceLeft) + { + context.moveTo(tx, ty); + context.lineTo(tx, ty + this._mc.ch); + } + + if (tile.faceRight) + { + context.moveTo(tx + this._mc.cw, ty); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + context.closePath(); + + context.stroke(); + } + + } + + } + +}; + +/** +* Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size. +* +* @property {boolean} wrap +* @memberof Phaser.TilemapLayer +* @public +* @default false +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", { + + get: function () { + return this._wrap; + }, + + set: function (value) { + this._wrap = value; + this.dirty = true; + } + +}); + +/** +* Scrolls the map horizontally or returns the current x position. +* +* @property {number} scrollX +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", { + + get: function () { + return this._scrollX; + }, + + set: function (value) { + this._scrollX = value; + } + +}); + +/** +* Scrolls the map vertically or returns the current y position. +* +* @property {number} scrollY +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", { + + get: function () { + return this._scrollY; + }, + + set: function (value) { + this._scrollY = value; + } + +}); + +/** +* The width of the collision tiles (in pixels). +* +* @property {integer} collisionWidth +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", { + + get: function () { + return this._mc.cw; + }, + + set: function (value) { + this._mc.cw = value | 0; + this.dirty = true; + } + +}); + +/** +* The height of the collision tiles (in pixels). +* +* @property {integer} collisionHeight +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", { + + get: function () { + return this._mc.ch; + }, + + set: function (value) { + this._mc.ch = value | 0; + this.dirty = true; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. +* +* @class Phaser.TilemapParser +* @static +*/ +Phaser.TilemapParser = { + + /** + * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or + * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type + * depends how this should be configured. If you've a large sparsely populated map and the tile + * data doesn't need to change then setting this value to `true` will help with memory consumption. + * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes + * during the game) then leave the default value set. + * + * @constant + * @type {boolean} + */ + INSERT_NULL: false, + + /** + * Parse tilemap data from the cache and creates data for a Tilemap object. + * + * @method Phaser.TilemapParser.parse + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {string} key - The key of the tilemap in the Cache. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {object} The parsed map object. + */ + parse: function (game, key, tileWidth, tileHeight, width, height) { + + if (tileWidth === undefined) { tileWidth = 32; } + if (tileHeight === undefined) { tileHeight = 32; } + if (width === undefined) { width = 10; } + if (height === undefined) { height = 10; } + + if (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); + } + + }, + + /** + * Parses a CSV file into valid map data. + * + * @method Phaser.TilemapParser.parseCSV + * @param {string} key - The name you want to give the map data. + * @param {string} data - The CSV file data. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @return {object} Generated map data. + */ + parseCSV: function (key, data, tileWidth, tileHeight) { + + var map = this.getEmptyData(); + + // Trim any rogue whitespace from the data + data = data.trim(); + + var output = []; + var rows = data.split("\n"); + var height = rows.length; + var width = 0; + + for (var y = 0; y < rows.length; y++) + { + output[y] = []; + + var column = rows[y].split(","); + + for (var x = 0; x < column.length; x++) + { + output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight); + } + + if (width === 0) + { + width = column.length; + } + } + + map.format = Phaser.Tilemap.CSV; + map.name = key; + map.width = width; + map.height = height; + map.tileWidth = tileWidth; + map.tileHeight = tileHeight; + map.widthInPixels = width * tileWidth; + map.heightInPixels = height * tileHeight; + + map.layers[0].width = width; + map.layers[0].height = height; + map.layers[0].widthInPixels = map.widthInPixels; + map.layers[0].heightInPixels = map.heightInPixels; + map.layers[0].data = output; + + return map; + + }, + + /** + * Returns an empty map data object. + * + * @method Phaser.TilemapParser.getEmptyData + * @return {object} Generated map data. + */ + getEmptyData: function (tileWidth, tileHeight, width, height) { + + return { + width: (width !== undefined && width !== null) ? width : 0, + height: (height !== undefined && height !== null) ? height : 0, + tileWidth: (tileWidth !== undefined && tileWidth !== null) ? tileWidth : 0, + tileHeight: (tileHeight !== undefined && tileHeight !== null) ? tileHeight : 0, + orientation: 'orthogonal', + version: '1', + properties: {}, + widthInPixels: 0, + heightInPixels: 0, + layers: [ + { + name: 'layer', + x: 0, + y: 0, + width: 0, + height: 0, + widthInPixels: 0, + heightInPixels: 0, + alpha: 1, + visible: true, + properties: {}, + indexes: [], + callbacks: [], + bodies: [], + data: [] + } + ], + images: [], + objects: {}, + collision: {}, + tilesets: [], + tiles: [] + }; + + }, + + _slice: function(obj, fields) { + var sliced = {}; + + for (var k in fields) + { + var key = fields[k]; + + if (typeof obj[key] !== 'undefined') + { + sliced[key] = obj[key]; + } + } + + return sliced; + }, + + /** + * Parses an object group in Tiled JSON files. Object groups can be found in both layers and tilesets. Called internally in parseTiledJSON. + * @method Phaser.TilemapParser.parseObjectGroup + * @param {object} objectGroup - A JSON object group. + * @param {object} objectsCollection - An object into which new array of Tiled map objects will be added. + * @param {object} collisionCollection - An object into which new array of collision objects will be added. Currently only polylines are added. + * @param {string} [nameKey=objectGroup.name] - Key under which to store objects in collisions in objectsCollection and collisionCollection + * @param {object} [relativePosition={x: 0, y: 0}] - Coordinates the object group's position is relative to. + * @return {object} A object literal containing the objectsCollection and collisionCollection + */ + parseObjectGroup: function(objectGroup, objectsCollection, collisionCollection, nameKey, relativePosition) { + + var nameKey = nameKey || objectGroup.name; + var relativePosition = relativePosition || {x: 0, y: 0}; + var slice = this._slice; + + if (!nameKey) + { + console.warn('No name found for objectGroup', objectGroup); + } + + if (relativePosition.x === undefined || relativePosition.y === undefined) + { + console.warn('Malformed xy properties in relativePosition', relativePosition); + } + + objectsCollection[nameKey] = objectsCollection[nameKey] || []; + collisionCollection[nameKey] = collisionCollection[nameKey] || []; + + for (var v = 0, len = objectGroup.objects.length; v < len; v++) + { + var o = objectGroup.objects[v]; + + // Object Tiles + if (o.gid) + { + var object = { + gid: o.gid, + name: o.name, + type: o.type || '', + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + objectsCollection[nameKey].push(object); + } + else if (o.polyline) + { + var object = { + name: o.name, + type: o.type, + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + object.polyline = []; + + // Parse the polyline into an array + for (var p = 0; p < o.polyline.length; p++) + { + object.polyline.push([o.polyline[p].x, o.polyline[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // polygon + else if (o.polygon) + { + var object = slice(o, ['name', 'type', 'x', 'y', 'visible', 'rotation', 'properties']); + + object.x += relativePosition.x; + object.y += relativePosition.y; + + // Parse the polygon into an array + object.polygon = []; + + for (var p = 0; p < o.polygon.length; p++) + { + object.polygon.push([o.polygon[p].x, o.polygon[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // ellipse + else if (o.ellipse) + { + var object = slice(o, ['name', 'type', 'ellipse', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // otherwise it's a rectangle + else + { + var object = slice(o, ['name', 'type', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + object.rectangle = true; + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + } + + return { + objectsCollection: objectsCollection, + collisionCollection: collisionCollection + }; + }, + + /** + * Parses a Tiled JSON file into valid map data. + * @method Phaser.TilemapParser.parseTiledJSON + * @param {object} json - The JSON map data. + * @return {object} Generated and parsed map data. + */ + parseTiledJSON: function (json) { + + if (json.orientation !== 'orthogonal') + { + console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser'); + return null; + } + + // Map data will consist of: layers, objects, images, tilesets, sizes + var map = { + width: json.width, + height: json.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + orientation: json.orientation, + format: Phaser.Tilemap.TILED_JSON, + version: json.version, + properties: json.properties, + widthInPixels: json.width * json.tilewidth, + heightInPixels: json.height * json.tileheight + }; + + // Tile Layers + var layers = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'tilelayer') + { + continue; + } + + var curl = json.layers[i]; + + // Base64 decode data if necessary + // NOTE: uncompressed base64 only. + + if (!curl.compression && curl.encoding && curl.encoding === 'base64') + { + var binaryString = window.atob(curl.data); + var len = binaryString.length; + var bytes = new Array(len); + + // Interpret binaryString as an array of bytes representing + // little-endian encoded uint32 values. + for (var j = 0; j < len; j+=4) + { + bytes[j / 4] = ( + binaryString.charCodeAt(j) | + binaryString.charCodeAt(j + 1) << 8 | + binaryString.charCodeAt(j + 2) << 16 | + binaryString.charCodeAt(j + 3) << 24 + ) >>> 0; + } + + curl.data = bytes; + + delete curl.encoding; + } + else if (curl.compression) + { + console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\''); + continue; + } + + var layer = { + + name: curl.name, + x: curl.x, + y: curl.y, + width: curl.width, + height: curl.height, + widthInPixels: curl.width * json.tilewidth, + heightInPixels: curl.height * json.tileheight, + alpha: curl.opacity, + offsetX: curl.offsetx, + offsetY: curl.offsety, + visible: curl.visible, + properties: {}, + indexes: [], + callbacks: [], + bodies: [] + + }; + + if (curl.properties) + { + layer.properties = curl.properties; + } + + var x = 0; + var row = []; + var output = []; + var rotation, flipped, flippedVal, gid; + + // Loop through the data field in the JSON. + + // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV) + // If the map contains multiple tilesets then the indexes are relative to that which the set starts from. + // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset. + + for (var t = 0, len = curl.data.length; t < len; t++) + { + rotation = 0; + flipped = false; + gid = curl.data[t]; + flippedVal = 0; + + // If true the current tile is flipped or rotated (Tiled TMX format) + if (gid > 0x20000000) + { + // FlippedX + if (gid > 0x80000000) + { + gid -= 0x80000000; + flippedVal += 4; + } + + // FlippedY + if (gid > 0x40000000) + { + gid -= 0x40000000; + flippedVal += 2; + } + + // FlippedAD (anti-diagonal = top-right is swapped with bottom-left corners) + if (gid > 0x20000000) + { + gid -= 0x20000000; + flippedVal += 1; + } + + switch (flippedVal) + { + case 5: + rotation = Math.PI / 2; + break; + + case 6: + rotation = Math.PI; + break; + + case 3: + rotation = 3 * Math.PI / 2; + break; + + case 4: + rotation = 0; + flipped = true; + break; + + case 7: + rotation = Math.PI / 2; + flipped = true; + break; + + case 2: + rotation = Math.PI; + flipped = true; + break; + + case 1: + rotation = 3 * Math.PI / 2; + flipped = true; + break; + } + } + + // index, x, y, width, height + if (gid > 0) + { + var tile = new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight); + + tile.rotation = rotation; + tile.flipped = flipped; + + if (flippedVal !== 0) + { + // The WebGL renderer uses this to flip UV coordinates before drawing + tile.flippedVal = flippedVal; + } + + row.push(tile); + } + else + { + if (Phaser.TilemapParser.INSERT_NULL) + { + row.push(null); + } + else + { + row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight)); + } + } + + x++; + + if (x === curl.width) + { + output.push(row); + x = 0; + row = []; + } + } + + layer.data = output; + + layers.push(layer); + } + + map.layers = layers; + + // Images + var images = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'imagelayer') + { + continue; + } + + var curi = json.layers[i]; + + var image = { + + name: curi.name, + image: curi.image, + x: curi.x, + y: curi.y, + alpha: curi.opacity, + visible: curi.visible, + properties: {} + + }; + + if (curi.properties) + { + image.properties = curi.properties; + } + + images.push(image); + + } + + map.images = images; + + // Tilesets & Image Collections + var tilesets = []; + var tilesetGroupObjects = {}; + var imagecollections = []; + var lastSet = null; + + for (var i = 0; i < json.tilesets.length; i++) + { + // name, firstgid, width, height, margin, spacing, properties + var set = json.tilesets[i]; + + if (set.source) + { + console.warn('Phaser.TilemapParser - Phaser can\'t load external tilesets (%s). Use the Embed Tileset button and then export the map again.', set.source); + } + else if (set.image) + { + var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + if (set.tileproperties) + { + newSet.tileProperties = set.tileproperties; + } + + // For a normal sliced tileset the row/count/size information is computed when updated. + // This is done (again) after the image is set. + newSet.updateTileData(set.imagewidth, set.imageheight); + + tilesets.push(newSet); + } + else if (set.tiles) + { + var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + for (var ti in set.tiles) + { + var image = set.tiles[ti].image; + var gid = set.firstgid + parseInt(ti, 10); + newCollection.addImage(gid, image); + } + + imagecollections.push(newCollection); + } + else + { + throw new Error('Tileset ' + set.name + ' has no `image` or `tiles` property.'); + } + + // build a temporary object for objectgroups found in the tileset's tiles + for (var ti in set.tiles) + { + var objectGroup = set.tiles[ti].objectgroup; + + if (!objectGroup) + { + continue; + } + + tilesetGroupObjects[parseInt(ti, 10) + set.firstgid] = objectGroup; + } + + // We've got a new Tileset, so set the lastgid into the previous one + if (lastSet) + { + lastSet.lastgid = set.firstgid - 1; + } + + lastSet = set; + } + + if (tilesets.length === 0 && imagecollections.length === 0) + { + throw new Error('This tilemap has no tilesets.'); + } + + map.tilesets = tilesets; + map.imagecollections = imagecollections; + + // Objects & Collision Data (polylines, etc) + var objects = {}; + var collision = {}; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'objectgroup') + { + continue; + } + + var objectGroup = json.layers[i]; + this.parseObjectGroup(objectGroup, objects, collision); + } + + map.objects = objects; + map.collision = collision; + + map.tiles = []; + + // Finally lets build our super tileset index + for (var i = 0; i < map.tilesets.length; i++) + { + var set = map.tilesets[i]; + + var x = set.tileMargin; + var y = set.tileMargin; + + var count = 0; + var countX = 0; + var countY = 0; + + for (var t = set.firstgid; t < set.firstgid + set.total; t++) + { + // Can add extra properties here as needed + map.tiles[t] = [x, y, i]; + + x += set.tileWidth + set.tileSpacing; + + count++; + + if (count === set.total) + { + break; + } + + countX++; + + if (countX === set.columns) + { + x = set.tileMargin; + y += set.tileHeight + set.tileSpacing; + + countX = 0; + countY++; + + if (countY === set.rows) + { + break; + } + } + } + + } + + // assign tile properties + + var layer; + var tile; + var sid; + var set; + + // go through each of the map data layers + for (var i = 0; i < map.layers.length; i++) + { + layer = map.layers[i]; + collision[layer.name] = []; + set = null; + + // rows of tiles + for (var j = 0; j < layer.data.length; j++) + { + row = layer.data[j]; + + // individual tiles + for (var k = 0; k < row.length; k++) + { + tile = row[k]; + + if (tile === null || tile.index < 0) + { + continue; + } + + // find the relevant tileset + + sid = map.tiles[tile.index][2]; + set = map.tilesets[sid]; + + + // if that tile type has any properties, add them to the tile object + + if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) + { + tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties); + } + + var objectGroup = tilesetGroupObjects[tile.index]; + if (objectGroup) + { + // build collisions and objects for objectgroups found in the tileset's tiles + this.parseObjectGroup( + objectGroup, + map.objects, + map.collision, + tile.layer.name, + { + x: tile.worldX + objectGroup.x, + y: tile.worldY + objectGroup.y + }); + } + + } + } + } + + return map; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile set is a combination of an image containing the tiles and collision data per tile. +* +* Tilesets are normally created automatically when Tiled data is loaded. +* +* @class Phaser.Tileset +* @constructor +* @param {string} name - The name of the tileset in the map data. +* @param {integer} firstgid - The first tile index this tileset contains. +* @param {integer} [width=32] - Width of each tile (in pixels). +* @param {integer} [height=32] - Height of each tile (in pixels). +* @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels). +* @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels). +* @param {object} [properties={}] - Custom Tileset properties. +*/ +Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Tileset. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first tile index this Tileset contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of each tile (in pixels). + * @property {integer} tileWidth + * @readonly + */ + this.tileWidth = width | 0; + + /** + * The height of each tile (in pixels). + * @property {integer} tileHeight + * @readonly + */ + this.tileHeight = height | 0; + + /** + * The margin around the tiles in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileMarge + * @readonly + */ + // Modified internally + this.tileMargin = margin | 0; + + /** + * The spacing between each tile in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileSpacing + * @readonly + */ + this.tileSpacing = spacing | 0; + + /** + * Tileset-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set. + * @property {?object} image + * @readonly + */ + // Modified internally + this.image = null; + + /** + * The number of tile rows in the the tileset. + * @property {integer} + * @readonly + */ + // Modified internally + this.rows = 0; + + /** + * The number of tile columns in the tileset. + * @property {integer} columns + * @readonly + */ + // Modified internally + this.columns = 0; + + /** + * The total number of tiles in the tileset. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; + + /** + * The look-up table to specific tile image offsets. + * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1. + * @property {integer[]} drawCoords + * @private + */ + this.drawCoords = []; + +}; + +Phaser.Tileset.prototype = { + + /** + * Draws a tile from this Tileset at the given coordinates on the context. + * + * @method Phaser.Tileset#draw + * @public + * @param {CanvasRenderingContext2D} context - The context to draw the tile onto. + * @param {number} x - The x coordinate to draw to. + * @param {number} y - The y coordinate to draw to. + * @param {integer} index - The index of the tile within the set to draw. + */ + draw: function (context, x, y, index) { + + // Correct the tile index for the set and bias for interlacing + var coordIndex = (index - this.firstgid) << 1; + + if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length) + { + context.drawImage( + this.image, + this.drawCoords[coordIndex], + this.drawCoords[coordIndex + 1], + this.tileWidth, + this.tileHeight, + x, + y, + this.tileWidth, + this.tileHeight + ); + } + + }, + + /** + * Returns true if and only if this tileset contains the given tile index. + * + * @method Phaser.Tileset#containsTileIndex + * @public + * @param {number} tileIndex + * @return {boolean} True if this tileset contains the given index. + */ + containsTileIndex: function (tileIndex) { + + return ( + tileIndex >= this.firstgid && + tileIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Set the image associated with this Tileset and update the tile data. + * + * @method Phaser.Tileset#setImage + * @public + * @param {Image} image - The image that contains the tiles. + */ + setImage: function (image) { + + this.image = image; + this.updateTileData(image.width, image.height); + + }, + + /** + * Sets tile spacing and margins. + * + * @method Phaser.Tileset#setSpacing + * @public + * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels). + */ + setSpacing: function (margin, spacing) { + + this.tileMargin = margin | 0; + this.tileSpacing = spacing | 0; + + if (this.image) + { + this.updateTileData(this.image.width, this.image.height); + } + + }, + + /** + * Updates tile coordinates and tileset data. + * + * @method Phaser.Tileset#updateTileData + * @private + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + */ + updateTileData: function (imageWidth, imageHeight) { + + // May be fractional values + var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); + var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); + + if (rowCount % 1 !== 0 || colCount % 1 !== 0) + { + console.warn( + "Phaser.Tileset - '%s' image tile area (%s x %s) is not a whole multiple of tile size (%s x %s + %s + %s)", + this.name, imageWidth, imageHeight, this.tileWidth, this.tileHeight, this.tileMargin, this.tileSpacing + ); + } + + // In Tiled a tileset image that is not an even multiple of the tile dimensions + // is truncated - hence the floor when calculating the rows/columns. + rowCount = Math.floor(rowCount); + colCount = Math.floor(colCount); + + if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount)) + { + console.warn( + "Phaser.Tileset - Tile layout from image '%s' (%s rows by %s columns) differs from tileset '%s' (%s rows by %s columns)", + this.image.name, colCount, rowCount, this.name, this.columns, this.rows + ); + } + + this.rows = rowCount; + this.columns = colCount; + this.total = rowCount * colCount; + + this.drawCoords.length = 0; + + var tx = this.tileMargin; + var ty = this.tileMargin; + + for (var y = 0; y < this.rows; y++) + { + for (var x = 0; x < this.columns; x++) + { + this.drawCoords.push(tx); + this.drawCoords.push(ty); + tx += this.tileWidth + this.tileSpacing; + } + + tx = this.tileMargin; + ty += this.tileHeight + this.tileSpacing; + } + + } + +}; + +Phaser.Tileset.prototype.constructor = Phaser.Tileset; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. +* +* @class Phaser.Particle +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Particle = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + /** + * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData. + * @protected + */ + this.autoScale = false; + + /** + * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.scaleData = null; + + /** + * @property {number} _s - Internal cache var for tracking auto scale. + * @private + */ + this._s = 0; + + /** + * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. + * @protected + */ + this.autoAlpha = false; + + /** + * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.alphaData = null; + + /** + * @property {number} _a - Internal cache var for tracking auto alpha. + * @private + */ + this._a = 0; + +}; + +Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Particle.prototype.constructor = Phaser.Particle; + +/** +* Updates the Particle scale or alpha if autoScale and autoAlpha are set. +* +* @method Phaser.Particle#update +* @memberof 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; + } + } + +}; + +/** +* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. +* +* @method Phaser.Particle#onEmit +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.onEmit = function() { +}; + +/** +* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. +* +* @method Phaser.Particle#setAlphaData +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.setAlphaData = function(data) { + + this.alphaData = data; + this._a = data.length - 1; + this.alpha = this.alphaData[this._a].v; + this.autoAlpha = true; + +}; + +/** +* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. +* +* @method Phaser.Particle#setScaleData +* @memberof Phaser.Particle +*/ +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; + +}; + +/** +* Resets the Particle. This places the Particle at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. +* If the Particle has a physics body that too is reset. +* +* @method Phaser.Particle#reset +* @memberof Phaser.Particle +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {number} [health=1] - The health to give the Particle. +* @return {Phaser.Particle} This instance. +*/ +Phaser.Particle.prototype.reset = function(x, y, health) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y, health); + + this.alpha = 1; + this.scale.set(1); + + this.autoScale = false; + this.autoAlpha = false; + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Particles tracks any Emitters attached to it. +* +* @class Phaser.Particles +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Particles = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} emitters - Internal emitters store. + */ + this.emitters = {}; + + /** + * @property {number} ID - + * @default + */ + this.ID = 0; + +}; + +Phaser.Particles.prototype = { + + /** + * Adds a new Particle Emitter to the Particle Manager. + * @method Phaser.Particles#add + * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. + * @return {Phaser.Emitter} The emitter that was added. + */ + add: function (emitter) { + this.emitters[emitter.id] = emitter; + return emitter; + }, + + /** + * Removes an existing Particle Emitter from the Particle Manager. + * @method Phaser.Particles#remove + * @param {Phaser.Emitter} emitter - The emitter to remove. + */ + remove: function (emitter) { + delete this.emitters[emitter.id]; + } + +}; + +Phaser.Particles.prototype.constructor = Phaser.Particles; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Arcade Particles is a Particle System integrated with Arcade Physics. +* +* @class Phaser.Particles.Arcade +*/ +Phaser.Particles.Arcade = {}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Emitter is a lightweight particle emitter that uses Arcade Physics. +* It can be used for one-time explosions or for continuous effects like rain and fire. +* All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. +* +* @class Phaser.Particles.Arcade.Emitter +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. +* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. +* @param {number} [maxParticles=50] - The total number of particles in this emitter. +*/ +Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { + + /** + * @property {number} maxParticles - The total number of particles in this emitter. + * @default + */ + this.maxParticles = maxParticles || 50; + + Phaser.Group.call(this, game); + + /** + * @property {number} _id - Internal ID for this emitter -- only used by the Particle System in most cases + * @private + */ + this._id = this.game.particles.ID++; + + /** + * @property {string} name - A handy string name for this emitter. Can be set to anything. + */ + this.name = 'emitter' + this.id; + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.EMITTER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * @property {Phaser.Rectangle} area - The {@link #setSize size} of the emitter's emit area. The **actual** emit area is a rectangle of this size centered on (emitX, emitY): `{x: this.left, y: this.top, width: this.area.width, height: this.area.height}`. Particles are generated at a random position within this area. + * @default + */ + this.area = new Phaser.Rectangle(x, y, 1, 1); + + /** + * @property {?number} minAngle - The minimum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #maxAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.minAngle = null; + + /** + * @property {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #minAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.maxAngle = null; + + /** + * @property {number} minSpeed - The minimum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.minSpeed = 0; + + /** + * @property {number} maxSpeed - The maximum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.maxSpeed = 100; + + /** + * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle. + * @default + */ + this.minParticleSpeed = new Phaser.Point(-100, -100); + + /** + * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle. + * @default + */ + this.maxParticleSpeed = new Phaser.Point(100, 100); + + /** + * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. + * @default + */ + this.minParticleScale = 1; + + /** + * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. + * @default + */ + this.maxParticleScale = 1; + + /** + * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0. + */ + this.scaleData = null; + + /** + * @property {number} minRotation - The minimum possible angular velocity of a particle. + * @default + */ + this.minRotation = -360; + + /** + * @property {number} maxRotation - The maximum possible angular velocity of a particle. + * @default + */ + this.maxRotation = 360; + + /** + * @property {number} minParticleAlpha - The minimum possible alpha value of a particle. + * @default + */ + this.minParticleAlpha = 1; + + /** + * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle. + * @default + */ + this.maxParticleAlpha = 1; + + /** + * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0. + */ + this.alphaData = null; + + /** + * @property {function} particleClass - For emitting your own particle class types. They must extend Phaser.Particle. + * @default + */ + this.particleClass = Phaser.Particle; + + /** + * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter. + */ + this.particleDrag = new Phaser.Point(); + + /** + * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false). + * @default + */ + this.frequency = 100; + + /** + * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. + * @default + */ + this.lifespan = 2000; + + /** + * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. + */ + this.bounce = new Phaser.Point(); + + /** + * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. + * @default + */ + this.on = false; + + /** + * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) + * @default + */ + this.particleAnchor = new Phaser.Point(0.5, 0.5); + + /** + * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) + * @default + */ + this.blendMode = Phaser.blendModes.NORMAL; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitX + */ + this.emitX = x; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitY + */ + this.emitY = y; + + /** + * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. + */ + this.autoScale = false; + + /** + * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. + */ + this.autoAlpha = false; + + /** + * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. + * @default + */ + this.particleBringToTop = false; + + /** + * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. + * @default + */ + this.particleSendToBack = false; + + /** + * @property {object} counts - Records emitter activity. + * @property {number} counts.emitted - How many particles were emitted during the last update. + * @property {number} counts.failed - How many particles could not be emitted during the last update (because no particles were available). + * @property {number} counts.totalEmitted - How many particles have been emitted. + * @property {number} counts.totalFailed - How many particles could not be emitted when they were due (because no particles were available). + */ + this.counts = { + emitted: 0, + failed: 0, + totalEmitted: 0, + totalFailed: 0 + }; + + /** + * @property {Phaser.Point} _gravity - Internal gravity value. + * @private + */ + this._gravity = new Phaser.Point(0, 100); + + /** + * @property {Phaser.Point} _minParticleScale - Internal particle scale var. + * @private + */ + this._minParticleScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} _maxParticleScale - Internal particle scale var. + * @private + */ + this._maxParticleScale = new Phaser.Point(1, 1); + + /** + * @property {number} _total - Internal helper for deciding how many particles to launch (via {@link #start}). + * @private + */ + this._total = 0; + + /** + * @property {number} _timer - Internal helper for deciding when to launch particles or kill them. + * @private + */ + this._timer = 0; + + /** + * @property {number} _counter - Internal counter for figuring out how many particles to launch. + * @private + */ + this._counter = 0; + + /** + * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update. + * @private + */ + this._flowQuantity = 0; + + /** + * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total (via {@link #flow}). + * @private + */ + this._flowTotal = 0; + + /** + * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time). + * @private + */ + this._explode = true; + + /** + * @property {any} _frames - Internal helper for the particle frame. + * @private + */ + this._frames = null; + +}; + +Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); +Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter; + +/** +* Called automatically by the game loop, decides when to launch particles and when to "die". +* +* @method Phaser.Particles.Arcade.Emitter#update +*/ +Phaser.Particles.Arcade.Emitter.prototype.update = function () { + + this.counts.emitted = 0; + this.counts.failed = 0; + + if (this.on && this.game.time.time >= this._timer) + { + this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion; + + if (this._flowTotal !== 0) + { + if (this._flowQuantity > 0) + { + for (var i = 0; i < this._flowQuantity; i++) + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + break; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._total > 0 && this._counter >= this._total) + { + this.on = false; + } + } + } + + } + + var i = this.children.length; + + while (i--) + { + if (this.children[i].exists) + { + this.children[i].update(); + } + } + +}; + +/** +* This function generates a new set of particles for use by this emitter. +* The particles are stored internally waiting to be emitted via Emitter.start. +* +* @method Phaser.Particles.Arcade.Emitter#makeParticles +* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. +* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random. +* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. +* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. +* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. +* @param {object} [particleArguments=null] - Custom arguments to pass to your particle class +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds, particleArguments) { + + if (frames === undefined) { frames = 0; } + if (quantity === undefined) { quantity = this.maxParticles; } + if (collide === undefined) { collide = false; } + if (collideWorldBounds === undefined) { collideWorldBounds = false; } + if (particleArguments === undefined) { particleArguments = null; } + + var particle; + var i = 0; + var rndKey = keys; + var rndFrame = frames; + this._frames = frames; + + if (quantity > this.maxParticles) + { + this.maxParticles = quantity; + } + + while (i < quantity) + { + if (Array.isArray(keys)) + { + rndKey = this.game.rnd.pick(keys); + } + + if (Array.isArray(frames)) + { + rndFrame = this.game.rnd.pick(frames); + } + + particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame, particleArguments); + + this.game.physics.arcade.enable(particle, false); + + particle.body.checkCollision.none = !collide; + particle.body.collideWorldBounds = collideWorldBounds; + particle.body.skipQuadTree = true; + + particle.exists = false; + particle.visible = false; + particle.anchor.copyFrom(this.particleAnchor); + + this.add(particle); + + i++; + } + + return this; + +}; + +/** +* Call this function to turn off all the particles and the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#kill +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.kill = function () { + + this.on = false; + this.alive = false; + this.exists = false; + + return this; + +}; + +/** +* Handy for bringing game objects "back to life". Just sets alive and exists back to true. +* +* @method Phaser.Particles.Arcade.Emitter#revive +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.revive = function () { + + this.alive = true; + this.exists = true; + + return this; + +}; + +/** +* Call this function to emit the given quantity of particles at all once (an explosion) +* +* @method Phaser.Particles.Arcade.Emitter#explode +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [quantity=this.maxParticles] - How many particles to launch. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) { + + if (quantity === undefined) { + quantity = this.maxParticles; + } + + this._flowTotal = 0; + + this.start(true, lifespan, 0, quantity, false); + + return this; + +}; + +/** +* Call this function to start emitting a flow of particles. +* `quantity` particles are released every interval of `frequency` ms until `total` particles have been released (or forever). +* If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 × 5 = 20 total) and then turn {@link #on off}. +* If you set the total to be -1 then no quantity cap is used and it will keep emitting (as long as there are inactive particles available). +* +* {@link #output}, {@link #lifespanOutput}, and {@link #remainder} describe the particle flow rate. +* During a stable flow, the number of active particles approaches {@link #lifespanOutput} and the number of inactive particles approaches {@link #remainder}. +* If {@link #remainder} is less than 0, there will likely be no particles available for a portion of the flow (see {@link #count}). +* +* @method Phaser.Particles.Arcade.Emitter#flow +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of particles, given in ms. Values between 0 and 16.66 will behave the same (60 releases per second). +* @param {number} [quantity=1] - How many particles to launch at each interval. Not larger than {@link #maxParticles}. +* @param {number} [total=-1] - Turn {@link #on off} after launching this many particles in total. If -1 it will carry on indefinitely. +* @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) { + + if (frequency === undefined || frequency === null) { frequency = 250; } + if (quantity === undefined || quantity === 0) { quantity = 1; } + if (total === undefined) { total = -1; } + if (immediate === undefined) { immediate = true; } + + if (quantity > this.maxParticles) + { + quantity = this.maxParticles; + } + + this._counter = 0; + this._flowQuantity = quantity; + this._flowTotal = total; + + if (immediate) + { + this.start(true, lifespan, frequency, quantity); + + this._counter += quantity; + this.on = true; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + else + { + this.start(false, lifespan, frequency, quantity); + } + + return this; + +}; + +/** +* Start emitting particles. +* +* {@link #explode} and {@link #flow} are simpler methods. +* +* There are two patterns, based on the `explode` argument: +* +* ##### explode=true +* +* start(true, lifespan=0, null, total) +* +* When `explode` is true or `forceQuantity` is true, `start` emits `total` particles immediately. You should pass a nonzero `total`. +* +* ##### explode=false +* +* start(false, lifespan=0, frequency=250, total=0) +* +* When `explode` is false and `forceQuantity` is false, `start` emits 1 particle every interval of `frequency` ms. If `total` is not zero, the emitter turns itself off after `total` particles have been released. If `total` is zero, the emitter keeps emitting particles as long as they are available. To emit more than 1 particle per flow interval, use {@link #flow} instead. +* +* `forceQuantity` seems equivalent to `explode` and can probably be avoided. +* +* @method Phaser.Particles.Arcade.Emitter#start +* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false). +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of 1 particle, when `explode` is false. Value given in ms. Ignored if `explode` is set to true. +* @param {number} [total=0] - Turn {@link #on off} after launching this many particles in total. +* @param {number} [forceQuantity=false] - Equivalent to `explodes`. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, total, forceQuantity) { + + if (explode === undefined) { explode = true; } + if (lifespan === undefined) { lifespan = 0; } + if (frequency === undefined || frequency === null) { frequency = 250; } + if (total === undefined) { total = 0; } + if (forceQuantity === undefined) { forceQuantity = false; } + + if (total > this.maxParticles) + { + total = this.maxParticles; + } + + this.revive(); + + this.visible = true; + + this.lifespan = lifespan; + this.frequency = frequency; + + if (explode || forceQuantity) + { + for (var i = 0; i < total; i++) + { + this.emitParticle(); + } + } + else + { + this.on = true; + this._total = total; + this._counter = 0; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + + return this; + +}; + +/** +* This function is used internally to emit the next particle in the queue. +* +* However it can also be called externally to emit a particle. +* +* When called externally you can use the arguments to override any defaults the Emitter has set. +* +* The newly emitted particle is available in {@link Phaser.Particles.Arcade.Emitter#cursor}. +* +* @method Phaser.Particles.Arcade.Emitter#emitParticle +* @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. +* @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {boolean} True if a particle was emitted, otherwise false. +*/ +Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + var particle = this.getNextParticle(); + + if (particle === null) + { + this.counts.failed++; + this.counts.totalFailed++; + + return false; + } + + this.counts.emitted++; + this.counts.totalEmitted++; + + var rnd = this.game.rnd; + + if (key !== undefined && frame !== undefined) + { + particle.loadTexture(key, frame); + } + else if (key !== undefined) + { + particle.loadTexture(key); + particle.frame = Array.isArray(this._frames) ? rnd.pick(this._frames) : this._frames; + } + + var emitX = this.emitX; + var emitY = this.emitY; + + if (x !== null) + { + emitX = x; + } + else if (this.width > 1) + { + emitX = rnd.between(this.left, this.right); + } + + if (y !== null) + { + emitY = y; + } + else if (this.height > 1) + { + emitY = rnd.between(this.top, this.bottom); + } + + this.resetParticle(particle, emitX, emitY); + + return true; + +}; + + +/** +* Helper for {@link #emitParticle}. Gets the next available particle. +* +* @private +* @return {?Phaser.Particle} The first particle with exists=false, or null +*/ +Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () { + + var i = this.length; + + while (i--) + { + var next = this.next(); + + if (!next.exists) + { + return next; + } + } + + return null; + +}; + +/** + * Helper for {@link #emitParticle}. Sets particle properties and calls {@link Particle#onEmit}. + * + * @private + * @param {Phaser.Particle} particle + * @param {number} x + * @param {number} y + */ +Phaser.Particles.Arcade.Emitter.prototype.resetParticle = function (particle, x, y) { + + var rnd = this.game.rnd; + + particle.reset(x, y); + + 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(rnd.realInRange(this.minParticleScale, this.maxParticleScale)); + } + else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y)) + { + particle.scale.set(rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y)); + } + else + { + particle.scale.set(this._minParticleScale.x, this._minParticleScale.y); + } + + if (this.autoAlpha) + { + particle.setAlphaData(this.alphaData); + } + else + { + particle.alpha = rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha); + } + + particle.blendMode = this.blendMode; + + var body = particle.body; + + body.updateBounds(); + + body.bounce.copyFrom(this.bounce); + body.drag.copyFrom(this.particleDrag); + + if (this.minAngle != null && this.maxAngle != null) + { + this.game.physics.arcade.velocityFromAngle( + (this.minAngle === this.maxAngle) ? this.minAngle : rnd.between(this.minAngle, this.maxAngle), + (this.minSpeed === this.maxSpeed) ? this.minSpeed : rnd.between(this.minSpeed, this.maxSpeed), + body.velocity + ); + } + else + { + body.velocity.x = rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x); + body.velocity.y = rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y); + } + + body.angularVelocity = rnd.between(this.minRotation, this.maxRotation); + body.gravity.copyFrom(this.gravity); + body.angularDrag = this.angularDrag; + + particle.onEmit(); + +}; + +/** +* Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. +* +* @method Phaser.Particles.Arcade.Emitter#destroy +*/ +Phaser.Particles.Arcade.Emitter.prototype.destroy = function () { + + this.game.particles.remove(this); + + Phaser.Group.prototype.destroy.call(this, true, false); + +}; + +/** +* A more compact way of setting the width and height of the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#setSize +* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). +* @param {number} height - The desired height of the emitter. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { + + this.area.width = width; + this.area.height = height; + + return this; + +}; + +/** +* A more compact way of setting the X velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setXSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.x = min; + this.maxParticleSpeed.x = max; + + return this; + +}; + +/** +* A more compact way of setting the Y velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setYSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.y = min; + this.maxParticleSpeed.y = max; + + return this; + +}; + +/** +* A more compact way of setting the angular velocity constraints of the particles. +* +* @method Phaser.Particles.Arcade.Emitter#setRotation +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minRotation = min; + this.maxRotation = max; + + return this; + +}; + +/** +* A more compact way of setting the alpha constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. +* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setAlpha +* @param {number} [min=1] - The minimum value for this range. +* @param {number} [max=1] - The maximum value for this range. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) { + + if (min === undefined) { min = 1; } + if (max === undefined) { max = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.alphaData.reverse(); + this.autoAlpha = true; + } + + return this; + +}; + +/** +* A more compact way of setting the scale constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. +* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setScale +* @param {number} [minX=1] - The minimum value of Particle.scale.x. +* @param {number} [maxX=1] - The maximum value of Particle.scale.x. +* @param {number} [minY=1] - The minimum value of Particle.scale.y. +* @param {number} [maxY=1] - The maximum value of Particle.scale.y. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) { + + if (minX === undefined) { minX = 1; } + if (maxX === undefined) { maxX = 1; } + if (minY === undefined) { minY = 1; } + if (maxY === undefined) { maxY = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (yoyo === undefined) { yoyo = false; } + + // Reset these + 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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.scaleData.reverse(); + this.autoScale = true; + } + + return this; + +}; + +/** + * Sets a radial pattern for emitting particles. + * + * This is a shorthand for setting {@link #minAngle}, {@link #maxAngle}, {@link #minSpeed}, and {@link #maxSpeed}. + * + * To remove the radial pattern, use `setAngle(null, null)`. + * + * @method Phaser.Particles.Arcade.Emitter#setAngle + * @param {?number} minAngle - The minimum angle of initial particle velocities, in degrees. + * @param {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. + * @param {number} [minSpeed] - The minimum initial particle speed. + * @param {number} [maxSpeed] - The maximum initial particle speed. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ +Phaser.Particles.Arcade.Emitter.prototype.setAngle = function (minAngle, maxAngle, minSpeed, maxSpeed) { + + this.minAngle = minAngle; + this.maxAngle = maxAngle; + + if (minSpeed != null) { this.minSpeed = minSpeed; } + if (maxSpeed != null) { this.maxSpeed = maxSpeed; } + + return this; + +}; + +/** +* Change the emitter's center to match the center of any object with a `center` property, such as an Arcade Body. +* If the object doesn't have a `center` property it will be set to the object's anchor-adjusted world position (`object.world`). +* +* @method Phaser.Particles.Arcade.Emitter#at +* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +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); + } + + return this; + +}; + +/** + * @name Phaser.Particles.Arcade.Emitter#gravity + * @property {Phaser.Point} gravity - Sets the `body.gravity` of each particle sprite to this on launch. + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "gravity", { + + get: function () { + return this._gravity; + }, + + set: function (value) { + if (typeof value === "number") + { + this._gravity.y = value; + } + else + { + this._gravity = value; + } + } + +}); + + +/** +* @name Phaser.Particles.Arcade.Emitter#id +* @property {number} id - Gets the internal ID that represents this emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "id", { + get: function () { + return this._id; + } +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#width +* @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", { + + get: function () { + return this.area.width; + }, + + set: function (value) { + this.area.width = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#height +* @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", { + + get: function () { + return this.area.height; + }, + + set: function (value) { + this.area.height = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#x +* @property {number} x - Gets or sets the x position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", { + + get: function () { + return this.emitX; + }, + + set: function (value) { + this.emitX = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#y +* @property {number} y - Gets or sets the y position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", { + + get: function () { + return this.emitY; + }, + + set: function (value) { + this.emitY = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#left +* @property {number} left - Gets the left position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", { + + get: function () { + return Math.floor(this.x - (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#right +* @property {number} right - Gets the right position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", { + + get: function () { + return Math.floor(this.x + (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#top +* @property {number} top - Gets the top position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", { + + get: function () { + return Math.floor(this.y - (this.area.height / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#bottom +* @property {number} bottom - Gets the bottom position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", { + + get: function () { + return Math.floor(this.y + (this.area.height / 2)); + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#output + * @property {number} output - The number of particles released per second, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "output", { + + get: function () { + return 1000 * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#lifespanOutput + * @property {number} lifespanOutput - The number of particles released during one particle's {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "lifespanOutput", { + + get: function () { + return (this.lifespan === 0 ? Infinity : this.lifespan) * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#remainder + * @property {number} remainder - The expected number of unreleased particles after a flow interval of {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "remainder", { + + get: function () { + return this.maxParticles - this.lifespanOutput; + } + +}); + +/** +* The last particle released, if any. +* +* You should treat this as read-only (and also avoid {@link #next} and {@link #previous}) once the emitter is started. Phaser uses it internally to track particles. +* +* @name Phaser.Particles.Arcade.Emitter#cursor +* @property {?DisplayObject} cursor +* @readonly +*/ +// Inherited from Phaser.Group#cursor + +/** +* Advances the cursor to the next particle. +* +* @method Phaser.Particles.Arcade.Emitter#next +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#next + +/** +* Moves the group cursor to the previous particle. +* +* @method Phaser.Particles.Arcade.Emitter#previous +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#previous + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Weapon Plugin provides the ability to easily create a bullet pool and manager. +* +* Weapons fire {@link Phaser.Bullet} objects, which are essentially Sprites with a few extra properties. +* The Bullets are enabled for {@link Phaser.Physics.Arcade Arcade Physics}. They do not currently work with P2 Physics. +* +* The Bullets are created inside of {@link #bullets weapon.bullets}, which is a {@link Phaser.Group} instance. Anything you +* can usually do with a Group, such as move it around the display list, iterate it, etc can be done +* to the bullets Group too. +* +* Bullets can have textures and even animations. You can control the speed at which they are fired, +* the firing rate, the firing angle, and even set things like gravity for them. +* +* A small example, using {@link Phaser.GameObjectFactory#weapon add.weapon}, assumed to be running from within a {@link Phaser.State#create} method: +* +* ```javascript +* var weapon = this.add.weapon(10, 'bullet'); +* weapon.fireFrom.set(300, 300); +* this.input.onDown.add(weapon.fire, this); +* ``` +* +* If you want to (re)create the bullet pool separately, you can use: +* +* ```javascript +* var weapon = this.game.plugins.add(Phaser.Weapon); +* // … +* weapon.createBullets(10, 'bullet'); +* ``` +* +* @class Phaser.Weapon +* @constructor +* @param {Phaser.Game} game - A reference to the current Phaser.Game instance. +* @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin. +*/ +Phaser.Weapon = function (game, parent) { + + Phaser.Plugin.call(this, game, parent); + + /** + * This is the Phaser.Group that contains all of the bullets managed by this plugin. + * @type {Phaser.Group} + */ + this.bullets = null; + + /** + * Should the bullet pool run out of bullets (i.e. they are all in flight) then this + * boolean controls if the Group will create a brand new bullet object or not. + * @type {boolean} + * @default + */ + this.autoExpandBulletsGroup = false; + + /** + * Will this weapon auto fire? If set to true then a new bullet will be fired + * based on the {@link #fireRate} value. + * @type {boolean} + * @default + */ + this.autofire = false; + + /** + * The total number of bullets this Weapon has fired so far. + * You can limit the number of shots allowed (via {@link #fireLimit}), and reset + * this total via {@link #resetShots}. + * @type {number} + * @default + */ + this.shots = 0; + + /** + * The maximum number of shots that this Weapon is allowed to fire before it stops. + * When the limit is his the {@link #onFireLimit} Signal is dispatched. + * You can reset the shot counter via {@link #resetShots}. + * @type {number} + * @default + */ + this.fireLimit = 0; + + /** + * The minimum interval between shots, in milliseconds. + * @type {number} + * @default + */ + this.fireRate = 100; + + /** + * This is a modifier that is added to the {@link #fireRate} each update to add variety + * to the firing rate of the Weapon. The value is given in milliseconds. + * If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual + * firing rate of the Weapon will be between 150 and 250. + * @type {number} + * @default + */ + this.fireRateVariance = 0; + + /** + * This is a Rectangle from within which the bullets are fired. By default it's a 1x1 + * rectangle, the equivalent of a Point. But you can change the width and height, and if + * larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from. + * @type {Phaser.Rectangle} + */ + this.fireFrom = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE_UP + * or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right. + * @type {integer} + * @default + */ + this.fireAngle = Phaser.ANGLE_UP; + + /** + * When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set. + * @type {boolean} + * @default + */ + this.bulletInheritSpriteSpeed = false; + + /** + * The string based name of the animation that the Bullet will be given on launch. + * This is set via {@link #addBulletAnimation}. + * @type {string} + * @default + */ + this.bulletAnimation = ''; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to pick a random frame from the set. + * @type {boolean} + * @default + */ + this.bulletFrameRandom = false; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to use the next frame in the set. The frame index is then + * advanced one frame until it reaches the end of the set, then it starts from the start + * again. Cycling frames like this allows you to create varied bullet effects via + * sprite sheets. + * @type {boolean} + * @default + */ + this.bulletFrameCycle = false; + + /** + * Should the Bullets wrap around the world bounds? This automatically calls + * `World.wrap` on the Bullet each frame. See the docs for that method for details. + * @type {boolean} + * @default + */ + this.bulletWorldWrap = false; + + /** + * If `bulletWorldWrap` is true then you can provide an optional padding value with this + * property. It's added to the calculations determining when the Bullet should wrap around + * the world or not. The value is given in pixels. + * @type {integer} + * @default + */ + this.bulletWorldWrapPadding = 0; + + /** + * An optional angle offset applied to the Bullets when they are launched. + * This is useful if for example your bullet sprites have been drawn facing up, instead of + * to the right, and you want to fire them at an angle. In which case you can set the + * angle offset to be 90 and they'll be properly rotated when fired. + * @type {number} + * @default + */ + this.bulletAngleOffset = 0; + + /** + * This is a variance added to the angle of Bullets when they are fired. + * If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual + * angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a + * great 'spread' effect to a Weapon. + * @type {number} + * @default + */ + this.bulletAngleVariance = 0; + + /** + * The initial velocity of fired bullets, in pixels per second. + * @type {number} + * @default + */ + this.bulletSpeed = 200; + + /** + * This is a variance added to the speed of Bullets when they are fired. + * If bullets have a {@link #bulletSpeed} value of 200, and a `bulletSpeedVariance` of 50 + * then the actual speed of the Bullets will be between 150 and 250 pixels per second. + * @type {number} + * @default + */ + this.bulletSpeedVariance = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount + * of lifespan the Bullets have set on launch. The value is given in milliseconds. + * When a Bullet hits its lifespan limit it will be automatically killed. + * @type {number} + * @default + */ + this.bulletLifespan = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_DISTANCE` this controls the distance + * the Bullet can travel before it is automatically killed. The distance is given in pixels. + * @type {number} + * @default + */ + this.bulletKillDistance = 0; + + /** + * This is the amount of {@link Phaser.Physics.Arcade.Body#gravity} added to the Bullets physics body when fired. + * Gravity is expressed in pixels / second / second. + * @type {Phaser.Point} + */ + this.bulletGravity = new Phaser.Point(0, 0); + + /** + * Bullets can optionally adjust their rotation in-flight to match their velocity. + * This can create the effect of a bullet 'pointing' to the path it is following, for example + * an arrow being fired from a bow, and works especially well when added to {@link #bulletGravity}. + * @type {boolean} + * @default + */ + this.bulletRotateToVelocity = false; + + /** + * The Texture Key that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string} + * @default + */ + this.bulletKey = ''; + + /** + * The Texture Frame that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string|integer} + * @default + */ + this.bulletFrame = ''; + + /** + * Private var that holds the public `bulletClass` property. + * @type {function} + * @private + */ + this._bulletClass = Phaser.Bullet; + + /** + * Private var that holds the public `bulletCollideWorldBounds` property. + * @type {boolean} + * @private + */ + this._bulletCollideWorldBounds = false; + + /** + * Private var that holds the public `bulletKillType` property. + * @type {integer} + * @private + */ + this._bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; + + /** + * Holds internal data about custom bullet body sizes. + * + * @type {Object} + * @private + */ + this._data = { + customBody: false, + width: 0, + height: 0, + offsetX: 0, + offsetY: 0 + }; + + /** + * This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not. + * It's used in combination with {@link #bulletKillType} when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS` + * or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored. + * If you are tracking a Sprite or Point then the bounds are centered on that object every frame. + * + * @type {Phaser.Rectangle} + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The Rectangle used to calculate the bullet bounds from. + * + * @type {Phaser.Rectangle} + * @private + */ + this.bulletBounds = game.world.bounds; + + /** + * This array stores the frames added via @link #setBulletFrames. + * + * @type {Array} + * @protected + */ + this.bulletFrames = []; + + /** + * The index of the frame within {@link #bulletFrames} that is currently being used. + * This value is only used if {@link #bulletFrameCycle} is set to `true`. + * @type {number} + * @private + */ + this.bulletFrameIndex = 0; + + /** + * An internal object that stores the animation data added via {@link #addBulletAnimation}. + * @type {Object} + * @private + */ + this.anims = {}; + + /** + * The onFire Signal is dispatched each time {@link #fire} is called, and a Bullet is + * _successfully_ launched. The callback is set two arguments: a reference to the bullet sprite itself, + * and a reference to the Weapon that fired the bullet. + * + * @type {Phaser.Signal} + */ + this.onFire = new Phaser.Signal(); + + /** + * The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result + * of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance. + * The callback is sent one argument: A reference to the bullet sprite itself. + * + * @type {Phaser.Signal} + */ + this.onKill = new Phaser.Signal(); + + /** + * The onFireLimit Signal is dispatched if {@link #fireLimit} is > 0, and a bullet launch takes the number + * of shots fired to equal the fire limit. + * The callback is sent two arguments: A reference to this Weapon, and the value of + * {@link #fireLimit}. + * + * @type {Phaser.Signal} + */ + this.onFireLimit = new Phaser.Signal(); + + /** + * The Sprite currently being tracked by the Weapon, if any. + * This is set via the {@link #trackSprite} method. + * + * @type {Phaser.Sprite|Object} + */ + this.trackedSprite = null; + + /** + * The Pointer currently being tracked by the Weapon, if any. + * This is set via the {@link #trackPointer} method. + * + * @type {Phaser.Pointer} + */ + this.trackedPointer = null; + + /** + * If you want this Weapon to be able to fire more than 1 bullet in a single + * update, then set this property to `true`. When `true` the Weapon plugin won't + * set the shot / firing timers until the `postRender` phase of the game loop. + * This means you can call `fire` (and similar methods) as often as you like in one + * single game update. + * + * @type {boolean} + * @default + */ + this.multiFire = false; + + /** + * Internal multiFire test flag. + * + * @type {boolean} + */ + this._hasFired = false; + + /** + * If the Weapon is tracking a Sprite, should it also track the Sprites rotation? + * This is useful for a game such as Asteroids, where you want the weapon to fire based + * on the sprites rotation. + * + * @type {boolean} + * @default + */ + this.trackRotation = false; + + /** + * The Track Offset is a Point object that allows you to specify a pixel offset that bullets use + * when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels + * in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have + * the bullet launched from the center of the Sprite. + * + * @type {Phaser.Point} + */ + this.trackOffset = new Phaser.Point(); + + /** + * Internal firing rate time tracking variable. + * + * @type {number} + * @private + */ + this._nextFire = 0; + + /** + * Internal firing rate time tracking variable used by multiFire. + * + * @type {number} + * @private + */ + this._tempNextFire = 0; + + /** + * Internal firing rotation tracking point. + * + * @type {Phaser.Point} + * @private + */ + this._rotatedPoint = new Phaser.Point(); + +}; + +Phaser.Weapon.prototype = Object.create(Phaser.Plugin.prototype); +Phaser.Weapon.prototype.constructor = Phaser.Weapon; + +/** +* A {@link #bulletKillType} constant that stops the bullets from ever being destroyed automatically. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_NEVER = 0; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when their {@link #bulletLifespan} expires. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_LIFESPAN = 1; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets after they +* exceed the {@link #bulletDistance} from their original firing position. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_DISTANCE = 2; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WEAPON_BOUNDS = 3; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.Camera#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_CAMERA_BOUNDS = 4; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.World#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WORLD_BOUNDS = 5; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_STATIC_BOUNDS = 6; + +/** +* This method performs two actions: First it will check to see if the {@link #bullets} Group exists or not, +* and if not it creates it, adding it the `group` given as the 4th argument. +* +* Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame +* provided (if any). +* +* If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets +* in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of +* the in-flight bullets have been killed, freeing them up for use by the Weapon again. +* +* If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will +* keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however, +* so be careful it doesn't grow too large. +* +* You can either set the texture key and frame here, or via the {@link #bulletKey} and {@link #bulletFrame} +* properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a +* single Weapon instance must share the same texture key however. +* +* @method Phaser.Weapon#createBullets +* @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. +* @param {string} [key] - The Game.cache key of the image that this Sprite will use. +* @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. +* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.createBullets = function (quantity, key, frame, group) { + + if (quantity === undefined) { quantity = 1; } + if (group === undefined) { group = this.game.world; } + + if (this.bullets && !this.bullets.game) + { + this.bullets = null; + } + + if (!this.bullets) + { + this.bullets = this.game.add.physicsGroup(Phaser.Physics.ARCADE, group); + this.bullets.classType = this._bulletClass; + } + + if (quantity !== 0) + { + if (quantity === -1) + { + this.autoExpandBulletsGroup = true; + quantity = 1; + } + + this.bullets.createMultiple(quantity, key, frame); + + this.bullets.setAll('data.bulletManager', this); + + this.bulletKey = key; + this.bulletFrame = frame; + } + + return this; + +}; + +/** +* Call a function on each in-flight bullet in this Weapon. +* +* See {@link Phaser.Group#forEachExists forEachExists} for more details. +* +* @method Phaser.Weapon#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.forEach = function (callback, callbackContext) { + + this.bullets.forEachExists(callback, callbackContext, arguments); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `false` on each bullet in this Weapon. +* This has the effect of stopping them in-flight should they be moving. +* It also stops them being able to be checked for collision. +* +* @method Phaser.Weapon#pauseAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.pauseAll = function () { + + this.bullets.setAll('body.enable', false); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `true` on each bullet in this Weapon. +* This has the effect of resuming their motion should they be in-flight. +* It also enables them for collision checks again. +* +* @method Phaser.Weapon#resumeAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resumeAll = function () { + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Calls {@link Phaser.Bullet#kill} on every in-flight bullet in this Weapon. +* Also re-enables their physics bodies, should they have been disabled via {@link #pauseAll}. +* +* @method Phaser.Weapon#killAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.killAll = function () { + + this.bullets.callAllExists('kill', true); + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Resets the {@link #shots} counter back to zero. This is used when you've set +* {@link #fireLimit} and have hit (or just wish to reset) your limit. +* +* @method Phaser.Weapon#resetShots +* @param {integer} [newLimit] - Optionally set a new {@link #fireLimit}. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resetShots = function (newLimit) { + + this.shots = 0; + + if (newLimit !== undefined) + { + this.fireLimit = newLimit; + } + + return this; + +}; + +/** +* Destroys this Weapon. It removes itself from the PluginManager, destroys +* the {@link #bullets} Group, and nulls internal references. +* +* @method Phaser.Weapon#destroy +*/ +Phaser.Weapon.prototype.destroy = function () { + + this.parent.remove(this, false); + + this.bullets.destroy(); + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#update +* @protected +*/ +Phaser.Weapon.prototype.update = function () { + + if (this._bulletKillType === Phaser.Weapon.KILL_WEAPON_BOUNDS) + { + if (this.trackedSprite) + { + this.trackedSprite.updateTransform(); + this.bounds.centerOn(this.trackedSprite.worldPosition.x, this.trackedSprite.worldPosition.y); + } + else if (this.trackedPointer) + { + this.bounds.centerOn(this.trackedPointer.worldX, this.trackedPointer.worldY); + } + } + + if (this.autofire) + { + this.fire(); + } + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#postRender +* @protected +*/ +Phaser.Weapon.prototype.postRender = function () { + + if (!this.multiFire || !this._hasFired) + { + return; + } + + this._hasFired = false; + + this._nextFire = this._tempNextFire; + +}; + +/** +* Sets this Weapon to track the given Sprite, or any Object with a public {@link Phaser.Component.Core#world world} Point object. +* When a Weapon tracks a Sprite it will automatically update its {@link #fireFrom} value to match the Sprite's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location. +* +* Calling `trackSprite` will reset {@link #trackedPointer} to null, should it have been set, as you can +* only track _either_ a Sprite, or a Pointer, at once, but not both. +* +* @method Phaser.Weapon#trackSprite +* @param {Phaser.Sprite|Object} sprite - The Sprite to track the position of. +* @param {integer} [offsetX=0] - The horizontal offset from the Sprites position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Sprites position to be applied to the Weapon. +* @param {boolean} [trackRotation=false] - Should the Weapon also track the Sprites rotation? +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackSprite = function (sprite, offsetX, offsetY, trackRotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (trackRotation === undefined) { trackRotation = false; } + + this.trackedPointer = null; + this.trackedSprite = sprite; + this.trackRotation = trackRotation; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Sets this Weapon to track the given Pointer. +* When a Weapon tracks a Pointer it will automatically update its {@link #fireFrom} value to match the Pointer's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location. +* +* Calling `trackPointer` will reset {@link #trackedSprite} to null, should it have been set, as you can +* only track _either_ a Pointer, or a Sprite, at once, but not both. +* +* @method Phaser.Weapon#trackPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to track the position of. Defaults to `Input.activePointer` if not specified. +* @param {integer} [offsetX=0] - The horizontal offset from the Pointers position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Pointers position to be applied to the Weapon. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackPointer = function (pointer, offsetX, offsetY) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this.trackedPointer = pointer; + this.trackedSprite = null; + this.trackRotation = false; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Attempts to fire multiple bullets from the positions defined in the given array. +* +* If you provide a `from` argument, or if there is a tracked Sprite or Pointer, then +* the positions are treated as __offsets__ from the given objects position. +* +* If `from` is undefined, and there is no tracked object, then the bullets are fired +* from the given positions, as they exist in the world. +* +* Calling this method sets {@link #multiFire} to `true`. +* +* If there are not enough bullets available in the pool, and the pool cannot be extended, +* then this method may not fire from all of the given positions. +* +* When the bullets are launched they have their texture and frame updated, as required. +* The velocity of the bullets are calculated based on Weapon properties like {@link #bulletSpeed}. +* +* @method Phaser.Weapon#fireMany +* @param {array} positions - An array of positions. Each position can be any Object, as long as it has public `x` and `y` properties, such as Phaser.Point, { x: 0, y: 0 }, Phaser.Sprite, etc. +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullets **from** the `x` and `y` properties of this object, _instead_ of any {@link #trackedSprite} or `trackedPointer` that is set. +* @return {array} An array containing all of the fired Phaser.Bullet objects, if a launch was successful, otherwise an empty array. +*/ +Phaser.Weapon.prototype.fireMany = function (positions, from) { + + this.multiFire = true; + + var bullets = []; + + var _this = this; + + if (from || this.trackedSprite || this.trackedPointer) + { + positions.forEach(function(offset) { + + bullets.push(_this.fire(from, null, null, offset.x, offset.y)); + + }); + } + else + { + positions.forEach(function(position) { + + bullets.push(_this.fire(position)); + + }); + } + + return bullets; + +}; + +/** +* Attempts to fire a single Bullet from a tracked Sprite or Pointer, but applies an offset +* to the position first. This is the same as calling {@link #fire} and passing in the offset arguments. +* +* If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like {@link #bulletSpeed}. +* +* If you wish to fire multiple bullets in a single game update, then set {@link #multiFire} to `true` +* and you can call this method as many times as you like, per loop. See also {@link #fireMany}. +* +* @method Phaser.Weapon#fireOffset +* @param {number} [offsetX=0] - The horizontal offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @param {number} [offsetY=0] - The vertical offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fireOffset = function (offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + return this.fire(null, null, null, offsetX, offsetY); + +}; + +/** +* Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at. +* +* If you don't provide any of the arguments then it uses those set via properties such as {@link #trackedSprite}, +* {@link #bulletAngle} and so on. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like `bulletSpeed`. +* +* If you wish to fire multiple bullets in a single game update, then set `Weapon.multiFire = true` +* and you can call `fire` as many times as you like, per loop. Multiple fires in a single update +* only counts once towards the `shots` total, but you will still receive a Signal for each bullet. +* +* @method Phaser.Weapon#fire +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides {@link #trackedSprite} or `trackedPointer`. Pass `null` to ignore it. +* @param {number} [x] - The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [offsetX=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a horizontal offset from the launch position. +* @param {number} [offsetY=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a vertical offset from the launch position. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fire = function (from, x, y, offsetX, offsetY) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (this.game.time.now < this._nextFire || (this.fireLimit > 0 && this.shots === this.fireLimit)) + { + return null; + } + + var speed = this.bulletSpeed; + + // Apply +- speed variance + if (this.bulletSpeedVariance !== 0) + { + speed += Phaser.Math.between(-this.bulletSpeedVariance, this.bulletSpeedVariance); + } + + if (from) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(from.x, from.y); + } + else + { + this.fireFrom.x = from.x; + this.fireFrom.y = from.y; + } + } + else if (this.trackedSprite) + { + if (this.trackRotation) + { + this._rotatedPoint.set(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.worldRotation); + + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this._rotatedPoint.x, this._rotatedPoint.y); + } + else + { + this.fireFrom.x = this._rotatedPoint.x; + this.fireFrom.y = this._rotatedPoint.y; + } + } + else + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedSprite.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedSprite.world.y + this.trackOffset.y; + } + } + + if (this.bulletInheritSpriteSpeed) + { + speed += this.trackedSprite.body.speed; + } + } + else if (this.trackedPointer) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedPointer.world.x + this.trackOffset.x, this.trackedPointer.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedPointer.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedPointer.world.y + this.trackOffset.y; + } + } + + if (offsetX !== undefined) + { + this.fireFrom.x += offsetX; + } + + if (offsetY !== undefined) + { + this.fireFrom.y += offsetY; + } + + var fromX = (this.fireFrom.width > 1) ? this.fireFrom.randomX : this.fireFrom.x; + var fromY = (this.fireFrom.height > 1) ? this.fireFrom.randomY : this.fireFrom.y; + + var angle = (this.trackRotation) ? this.trackedSprite.angle : this.fireAngle; + + // The position (in world space) to fire the bullet towards, if set + if (x !== null && y !== null) + { + angle = this.game.math.radToDeg(Math.atan2(y - fromY, x - fromX)); + } + + // Apply +- angle variance + if (this.bulletAngleVariance !== 0) + { + angle += Phaser.Math.between(-this.bulletAngleVariance, this.bulletAngleVariance); + } + + var moveX = 0; + var moveY = 0; + + // Avoid sin/cos for right-angled shots + if (angle === 0 || angle === 180) + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + } + else if (angle === 90 || angle === 270) + { + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + else + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + + var bullet = null; + + if (this.autoExpandBulletsGroup) + { + bullet = this.bullets.getFirstExists(false, true, fromX, fromY, this.bulletKey, this.bulletFrame); + + bullet.data.bulletManager = this; + } + else + { + bullet = this.bullets.getFirstExists(false); + } + + if (bullet) + { + bullet.reset(fromX, fromY); + + bullet.data.fromX = fromX; + bullet.data.fromY = fromY; + bullet.data.killType = this.bulletKillType; + bullet.data.killDistance = this.bulletKillDistance; + bullet.data.rotateToVelocity = this.bulletRotateToVelocity; + + if (this.bulletKillType === Phaser.Weapon.KILL_LIFESPAN) + { + bullet.lifespan = this.bulletLifespan; + } + + bullet.angle = angle + this.bulletAngleOffset; + + // Frames and Animations + if (this.bulletAnimation !== '') + { + if (bullet.animations.getAnimation(this.bulletAnimation) === null) + { + var anim = this.anims[this.bulletAnimation]; + + bullet.animations.add(anim.name, anim.frames, anim.frameRate, anim.loop, anim.useNumericIndex); + } + + bullet.animations.play(this.bulletAnimation); + } + else + { + if (this.bulletFrameCycle) + { + bullet.frame = this.bulletFrames[this.bulletFrameIndex]; + + this.bulletFrameIndex++; + + if (this.bulletFrameIndex >= this.bulletFrames.length) + { + this.bulletFrameIndex = 0; + } + } + else if (this.bulletFrameRandom) + { + bullet.frame = this.bulletFrames[Math.floor(Math.random() * this.bulletFrames.length)]; + } + } + + if (bullet.data.bodyDirty) + { + if (this._data.customBody) + { + bullet.body.setSize(this._data.width, this._data.height, this._data.offsetX, this._data.offsetY); + } + + bullet.body.collideWorldBounds = this.bulletCollideWorldBounds; + + bullet.data.bodyDirty = false; + } + + bullet.body.velocity.set(moveX, moveY); + bullet.body.gravity.set(this.bulletGravity.x, this.bulletGravity.y); + + var next = 0; + + if (this.bulletSpeedVariance !== 0) + { + var rate = this.fireRate; + + rate += Phaser.Math.between(-this.fireRateVariance, this.fireRateVariance); + + if (rate < 0) + { + rate = 0; + } + + next = this.game.time.now + rate; + } + else + { + next = this.game.time.now + this.fireRate; + } + + if (this.multiFire) + { + if (!this._hasFired) + { + // We only add 1 to the 'shots' count for multiFire shots + this._hasFired = true; + this._tempNextFire = next; + this.shots++; + } + } + else + { + this._nextFire = next; + + this.shots++; + } + + this.onFire.dispatch(bullet, this, speed); + + if (this.fireLimit > 0 && this.shots === this.fireLimit) + { + this.onFireLimit.dispatch(this, this.fireLimit); + } + } + + return bullet; + +}; + +/** +* Fires a bullet **at** the given Pointer. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtPointer = function (pointer) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + + return this.fire(null, pointer.worldX, pointer.worldY); + +}; + +/** +* Fires a bullet **at** the given Sprite. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtSprite +* @param {Phaser.Sprite} [sprite] - The Sprite to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtSprite = function (sprite) { + + return this.fire(null, sprite.world.x, sprite.world.y); + +}; + +/** +* Fires a bullet **at** the given coordinates. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtXY +* @param {number} [x] - The x coordinate, in world space, to fire the bullet towards. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtXY = function (x, y) { + + return this.fire(null, x, y); + +}; + +/** +* You can modify the size of the physics Body the Bullets use to be any dimension you need. +* This allows you to make it smaller, or larger, than the parent Sprite. +* You can also control the x and y offset of the Body. This is the position of the +* Body relative to the top-left of the Sprite _texture_. +* +* For example: If you have a Sprite with a texture that is 80x100 in size, +* and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: +* +* `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, 34)` +* +* Where the first two parameters are the new Body size (32x32 pixels) relative to the Sprite's scale. +* 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 +* is the vertical offset. +* +* @method Phaser.Weapon#setBulletBodyOffset +* @param {number} width - The width of the Body. +* @param {number} height - The height of the Body. +* @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture. +* @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture. +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletBodyOffset = function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this._data.customBody = true; + this._data.width = width; + this._data.height = height; + this._data.offsetX = offsetX; + this._data.offsetY = offsetY; + + // Update all bullets in the pool + this.bullets.callAll('body.setSize', 'body', width, height, offsetX, offsetY); + this.bullets.setAll('data.bodyDirty', false); + + return this; + +}; + +/** +* Sets the texture frames that the bullets can use when being launched. +* +* This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet. +* +* It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values +* provided. Then it sets the frame index to be zero. +* +* You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames +* when they're fired, or pick one at random. +* +* @method Phaser.Weapon#setBulletFrames +* @param {integer} min - The minimum value the frame can be. Usually zero. +* @param {integer} max - The maximum value the frame can be. +* @param {boolean} [cycle=true] - Should the bullet frames cycle as they are fired? +* @param {boolean} [random=false] - Should the bullet frames be picked at random as they are fired? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletFrames = function (min, max, cycle, random) { + + if (cycle === undefined) { cycle = true; } + if (random === undefined) { random = false; } + + this.bulletFrames = Phaser.ArrayUtils.numberArray(min, max); + + this.bulletFrameIndex = 0; + + this.bulletFrameCycle = cycle; + this.bulletFrameRandom = random; + + return this; + +}; + +/** +* Adds a new animation under the given key. Optionally set the frames, frame rate and loop. +* The arguments are all the same as for `Animation.add`, and work in the same way. +* +* {@link #bulletAnimation} will be set to this animation after it's created. From that point on, all +* bullets fired will play using this animation. You can swap between animations by calling this method +* several times, and then just changing the {@link #bulletAnimation} property to the name of the animation +* you wish to play for the next launched bullet. +* +* If you wish to stop using animations at all, set {@link #bulletAnimation} to '' (an empty string). +* +* @method Phaser.Weapon#addBulletAnimation +* @param {string} name - The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast". +* @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.addBulletAnimation = function (name, frames, frameRate, loop, useNumericIndex) { + + this.anims[name] = { + name: name, + frames: frames, + frameRate: frameRate, + loop: loop, + useNumericIndex: useNumericIndex + }; + + // Add the animation to any existing bullets in the pool + this.bullets.callAll('animations.add', 'animations', name, frames, frameRate, loop, useNumericIndex); + + this.bulletAnimation = name; + + return this; + +}; + +/** +* Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets +* both in-flight, and available. And optionally the physics debug bodies of the bullets. +* +* @method Phaser.Weapon#debug +* @param {integer} [x=16] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {integer} [y=32] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {boolean} [debugBodies=false] - Optionally draw the physics body of every bullet in-flight. +*/ +Phaser.Weapon.prototype.debug = function (x, y, debugBodies) { + + if (x === undefined) { x = 16; } + if (y === undefined) { y = 32; } + if (debugBodies === undefined) { debugBodies = false; } + + this.game.debug.text("Weapon Plugin", x, y); + this.game.debug.text("Bullets Alive: " + this.bullets.total + " - Total: " + this.bullets.length, x, y + 24); + + if (debugBodies) + { + this.bullets.forEachExists(this.game.debug.body, this.game.debug, 'rgba(255, 0, 255, 0.8)'); + } + +}; + +/** +* The Class of the bullets that are launched by this Weapon. Defaults to {@link Phaser.Bullet}, but can be +* overridden before calling `createBullets` and set to your own class type. +* +* It should be a constructor function accepting `(game, x, y, key, frame)`. +* +* @name Phaser.Weapon#bulletClass +* @property {function} bulletClass +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletClass", { + + get: function () { + + return this._bulletClass; + + }, + + set: function (classType) { + + this._bulletClass = classType; + + // `this.bullets` exists only after createBullets() + if (this.bullets) { + this.bullets.classType = this._bulletClass; + } + } + +}); + +/** +* This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`. +* +* There are 7 different "kill types" available: +* +* * `Phaser.Weapon.KILL_NEVER` +* The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code. +* +* * `Phaser.Weapon.KILL_LIFESPAN` +* The bullets are automatically killed when their `bulletLifespan` amount expires. +* +* * `Phaser.Weapon.KILL_DISTANCE` +* The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position. +* +* * `Phaser.Weapon.KILL_WEAPON_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* +* * `Phaser.Weapon.KILL_CAMERA_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.Camera#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_WORLD_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.World#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_STATIC_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to +* match the position of a tracked sprite or pointer. +* +* @name Phaser.Weapon#bulletKillType +* @property {integer} bulletKillType +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletKillType", { + + get: function () { + + return this._bulletKillType; + + }, + + set: function (type) { + + switch (type) + { + case Phaser.Weapon.KILL_STATIC_BOUNDS: + case Phaser.Weapon.KILL_WEAPON_BOUNDS: + this.bulletBounds = this.bounds; + break; + + case Phaser.Weapon.KILL_CAMERA_BOUNDS: + this.bulletBounds = this.game.camera.view; + break; + + case Phaser.Weapon.KILL_WORLD_BOUNDS: + this.bulletBounds = this.game.world.bounds; + break; + } + + this._bulletKillType = type; + + } + +}); + +/** +* Should bullets collide with the World bounds or not? +* +* @name Phaser.Weapon#bulletCollideWorldBounds +* @property {boolean} bulletCollideWorldBounds +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletCollideWorldBounds", { + + get: function () { + + return this._bulletCollideWorldBounds; + + }, + + set: function (value) { + + this._bulletCollideWorldBounds = value; + + this.bullets.setAll('body.collideWorldBounds', value); + this.bullets.setAll('data.bodyDirty', false); + + } + +}); + +/** +* The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Weapon.prototype, "x", { + + get: function () { + + return this.fireFrom.x; + + }, + + set: function (value) { + + this.fireFrom.x = value; + } + +}); + +/** +* The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Weapon.prototype, "y", { + + get: function () { + + return this.fireFrom.y; + + }, + + set: function (value) { + + this.fireFrom.y = value; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites, +* with a few extra properties in the data object to handle Weapon specific features. +* +* @class Phaser.Bullet +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Bullet = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + this.anchor.set(0.5); + + this.data = { + bulletManager: null, + fromX: 0, + fromY: 0, + bodyDirty: true, + rotateToVelocity: false, + killType: 0, + killDistance: 0 + }; + +}; + +Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Bullet.prototype.constructor = Phaser.Bullet; + +/** +* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool. +* Also dispatches the `Weapon.onKill` signal. +* +* @method Phaser.Bullet#kill +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + this.data.bulletManager.onKill.dispatch(this); + + return this; + +}; + +/** +* Updates the Bullet, killing as required. +* +* @method Phaser.Bullet#update +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.update = function () { + + if (!this.exists) + { + return; + } + + if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN) + { + if (this.data.killType === Phaser.Weapon.KILL_DISTANCE) + { + if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance) + { + this.kill(); + } + } + else + { + if (!this.data.bulletManager.bulletBounds.intersects(this)) + { + this.kill(); + } + } + } + + if (this.data.rotateToVelocity) + { + this.rotation = this.body.velocity.atan(); + } + + if (this.data.bulletManager.bulletWorldWrap) + { + this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding); + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. +* +* Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to +* the Video instead (see `startMediaStream` method) +* +* The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback +* changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. +* +* Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. +* +* If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. +* Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. +* +* On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. +* This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio +* it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` +* method to try and work around this limitation, but see the method help for details. +* +* Small screen devices, especially iPod and iPhone will launch the video in its own native video player, +* outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. +* +* Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) +* then you need to add your own event listener +* +* @class Phaser.Video +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. +* @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) +*/ +Phaser.Video = function (game, key, url) { + + if (key === undefined) { key = null; } + if (url === undefined) { url = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. + * @default null + */ + this.key = key; + + /** + * @property {number} width - The width of the video in pixels. + * @default + */ + this.width = 0; + + /** + * @property {number} height - The height of the video in pixels. + * @default + */ + this.height = 0; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.VIDEO; + + /** + * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. + * @default + */ + this.touchLocked = false; + + /** + * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. + */ + this.onChangeSource = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam. + */ + this.onAccess = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. + */ + this.onError = new Phaser.Signal(); + + /** + * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. + * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. + * @property {Phaser.Signal} onTimeout + */ + this.onTimeout = new Phaser.Signal(); + + /** + * This signal is dispatched when the Video is unlocked. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * Start playing the video when it's unlocked. + * @property {boolean} playWhenUnlocked + * @default + */ + this.playWhenUnlocked = true; + + /** + * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. + * @default + */ + this.timeout = 15000; + + /** + * @property {integer} _timeOutID - setTimeout ID. + * @private + */ + this._timeOutID = null; + + /** + * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document. + */ + this.video = null; + + /** + * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. + */ + this.videoStream = null; + + /** + * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam. + */ + this.isStreaming = false; + + /** + * When starting playback of a video Phaser will monitor its readyState using a setTimeout call. + * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * @property {integer} retryLimit + * @default + */ + this.retryLimit = 20; + + /** + * @property {integer} retry - The current retry attempt. + * @default + */ + this.retry = 0; + + /** + * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video. + * @default + */ + this.retryInterval = 500; + + /** + * @property {integer} _retryID - The callback ID of the retry setTimeout. + * @private + */ + this._retryID = null; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {boolean} _codePaused - Internal paused tracking var. + * @private + * @default + */ + this._codePaused = false; + + /** + * @property {boolean} _paused - Internal paused tracking var. + * @private + * @default + */ + this._paused = false; + + /** + * @property {boolean} _pending - Internal var tracking play pending. + * @private + * @default + */ + this._pending = false; + + /** + * @property {boolean} _pendingChangeSource - Internal var tracking play pending. + * @private + * @default + */ + this._pendingChangeSource = false; + + /** + * @property {boolean} _autoplay - Internal var tracking autoplay when changing source. + * @private + * @default + */ + this._autoplay = false; + + /** + * @property {function} _endCallback - The addEventListener ended function. + * @private + */ + this._endCallback = null; + + /** + * @property {function} _playCallback - The addEventListener playing function. + * @private + */ + this._playCallback = null; + + if (key && this.game.cache.checkVideoKey(key)) + { + var _video = this.game.cache.getVideo(key); + + if (_video.isBlob) + { + this.createVideoFromBlob(_video.data); + } + else + { + this.video = _video.data; + } + + this.width = this.video.videoWidth; + this.height = this.video.videoHeight; + } + else if (url) + { + this.createVideoFromURL(url, false); + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + if (this.video && !url) + { + this.baseTexture = new PIXI.BaseTexture(this.video, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + else + { + this.baseTexture = new PIXI.BaseTexture(Phaser.Cache.DEFAULT.baseTexture.source, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering. + * @default + */ + this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video'); + + this.texture.setFrame(this.textureFrame); + + this.texture.valid = false; + + if (key !== null && this.video) + { + this.texture.valid = this.video.canplay; + } + + /** + * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). + * When called the BitmapData is updated with a grab taken from the current video playing or active video stream. + * If Phaser has been compiled without BitmapData support this property will always be `null`. + * + * @property {Phaser.BitmapData} snapshot + * @readOnly + */ + this.snapshot = null; + + if (Phaser.BitmapData) + { + this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height); + } + + if (this.game.device.needsTouchUnlock()) + { + this.setTouchLock(); + } + else + { + if (_video) + { + _video.locked = false; + } + } + +}; + +Phaser.Video.prototype = { + + /** + * Connects to an external media stream for the webcam, rather than using a local one. + * + * @method Phaser.Video#connectToMediaStream + * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses. + * @param {MediaStream} stream - The Video Stream data. + * @return {Phaser.Video} This Video object for method chaining. + */ + connectToMediaStream: function (video, stream) { + + if (video && stream) + { + this.video = video; + this.videoStream = stream; + + this.isStreaming = true; + this.baseTexture.source = this.video; + this.updateTexture(null, this.video.videoWidth, this.video.videoHeight); + + this.onAccess.dispatch(this); + } + + return this; + + }, + + /** + * Instead of playing a video file this method allows you to stream video data from an attached webcam. + * + * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam. + * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream. + * + * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError + * or MediaStreamError event. + * + * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions. + * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device. + * You can listen for this with the onChangeSource signal. + * + * @method Phaser.Video#startMediaStream + * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream. + * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source. + * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source. + * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia. + */ + startMediaStream: function (captureAudio, width, height) { + + if (captureAudio === undefined) { captureAudio = false; } + if (width === undefined) { width = null; } + if (height === undefined) { height = null; } + + if (!this.game.device.getUserMedia) + { + this.onError.dispatch(this, 'No getUserMedia'); + return false; + } + + if (this.videoStream !== null) + { + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + this.videoStream.stop(); + } + } + + this.removeVideoElement(); + + this.video = document.createElement("video"); + this.video.setAttribute('autoplay', 'autoplay'); + + if (width !== null) + { + this.video.width = width; + } + + if (height !== null) + { + this.video.height = height; + } + + // Request access to the webcam + + this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout); + + try { + navigator.getUserMedia( + { "audio": captureAudio, "video": true }, + this.getUserMediaSuccess.bind(this), + this.getUserMediaError.bind(this) + ); + } + catch (error) + { + this.getUserMediaError(error); + } + + return this; + + }, + + /** + * @method Phaser.Video#getUserMediaTimeout + * @private + */ + getUserMediaTimeout: function () { + + clearTimeout(this._timeOutID); + + this.onTimeout.dispatch(this); + + }, + + /** + * @method Phaser.Video#getUserMediaError + * @private + */ + getUserMediaError: function (event) { + + clearTimeout(this._timeOutID); + + this.onError.dispatch(this, event); + + }, + + /** + * @method Phaser.Video#getUserMediaSuccess + * @private + */ + getUserMediaSuccess: function (stream) { + + clearTimeout(this._timeOutID); + + // Attach the stream to the video + this.videoStream = stream; + + // Set the source of the video element with the stream from the camera + if (this.video.mozSrcObject !== undefined) + { + this.video.mozSrcObject = stream; + } + else + { + this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; + } + + var self = this; + + this.video.onloadeddata = function () { + + var retry = 10; + + function checkStream () { + + if (retry > 0) + { + if (self.video.videoWidth > 0) + { + // Patch for Firefox bug where the height can't be read from the video + var width = self.video.videoWidth; + var height = self.video.videoHeight; + + if (isNaN(self.video.videoHeight)) + { + height = width / (4/3); + } + + self.video.play(); + + self.isStreaming = true; + self.baseTexture.source = self.video; + self.updateTexture(null, width, height); + self.onAccess.dispatch(self); + } + else + { + window.setTimeout(checkStream, 500); + } + } + else + { + console.warn('Unable to connect to video stream. Webcam error?'); + } + + retry--; + } + + checkStream(); + + }; + + }, + + /** + * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format. + * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience. + * + * @method Phaser.Video#createVideoFromBlob + * @param {Blob} blob - The Blob containing the video data. + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromBlob: function (blob) { + + var _this = this; + + this.video = document.createElement("video"); + this.video.controls = false; + this.video.setAttribute('autoplay', 'autoplay'); + this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true); + this.video.src = window.URL.createObjectURL(blob); + this.video.canplay = true; + + return this; + + }, + + /** + * Creates a new Video element from the given URL. + * + * @method Phaser.Video#createVideoFromURL + * @param {string} url - The URL of the video. + * @param {boolean} [autoplay=false] - Automatically start the video? + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromURL: function (url, autoplay) { + + if (autoplay === undefined) { autoplay = false; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + if (this.texture) + { + this.texture.valid = false; + } + + this.video = document.createElement("video"); + this.video.controls = false; + + if (autoplay) + { + this.video.setAttribute('autoplay', 'autoplay'); + } + + this.video.src = url; + + this.video.canplay = true; + + this.video.load(); + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.key = url; + + return this; + + }, + + /** + * Called automatically if the video source changes and updates the internal texture dimensions. + * Then dispatches the onChangeSource signal. + * + * @method Phaser.Video#updateTexture + * @param {object} [event] - The event which triggered the texture update. + * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used. + * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used. + */ + updateTexture: function (event, width, height) { + + var change = false; + + if (width === undefined || width === null) { width = this.video.videoWidth; change = true; } + if (height === undefined || height === null) { height = this.video.videoHeight; } + + this.width = width; + this.height = height; + + if (this.baseTexture.source !== this.video) + { + this.baseTexture.source = this.video; + } + + this.baseTexture.forceLoaded(width, height); + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.valid = true; + + if (this.snapshot) + { + this.snapshot.resize(width, height); + } + + if (change && this.key !== null) + { + this.onChangeSource.dispatch(this, width, height); + + if (this._autoplay) + { + this.video.play(); + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + } + + }, + + /** + * Called when the video completes playback (reaches and ended state). + * Dispatches the Video.onComplete signal. + * + * @method Phaser.Video#complete + */ + complete: function () { + + this.onComplete.dispatch(this); + + }, + + /** + * Starts this video playing. + * + * If the video is already playing, or has been queued to play with `changeSource` then this method just returns. + * + * @method Phaser.Video#play + * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. + * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate. + * @return {Phaser.Video} This Video object for method chaining. + */ + play: function (loop, playbackRate) { + + if (this._pendingChangeSource) + { + return this; + } + + if (loop === undefined) { loop = false; } + if (playbackRate === undefined) { playbackRate = 1; } + + if (this.game.sound.onMute) + { + this.game.sound.onMute.add(this.setMute, this); + this.game.sound.onUnMute.add(this.unsetMute, this); + + if (this.game.sound.mute) + { + this.setMute(); + } + } + + this.game.onPause.add(this.setPause, this); + this.game.onResume.add(this.setResume, this); + + this._endCallback = this.complete.bind(this); + + this.video.addEventListener('ended', this._endCallback, true); + this.video.addEventListener('webkitendfullscreen', this._endCallback, true); + + if (loop) + { + this.video.loop = 'loop'; + } + else + { + this.video.loop = ''; + } + + this.video.playbackRate = playbackRate; + + if (this.touchLocked) + { + this._pending = true; + } + else + { + this._pending = false; + + if (this.key !== null) + { + if (this.video.readyState !== 4) + { + this.retry = this.retryLimit; + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + this._playCallback = this.playHandler.bind(this); + this.video.addEventListener('playing', this._playCallback, true); + } + } + + this.video.play(); + + this.onPlay.dispatch(this, loop, playbackRate); + } + + return this; + + }, + + /** + * Called when the video starts to play. Updates the texture. + * + * @method Phaser.Video#playHandler + * @private + */ + playHandler: function () { + + this.video.removeEventListener('playing', this._playCallback, true); + + this.updateTexture(); + + }, + + /** + * Stops the video playing. + * + * This removes all locally set signals. + * + * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead. + * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to + * call `Video.destroy` instead. + * + * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam. + * + * @method Phaser.Video#stop + * @return {Phaser.Video} This Video object for method chaining. + */ + stop: function () { + + if (this.game.sound.onMute) + { + this.game.sound.onMute.remove(this.setMute, this); + this.game.sound.onUnMute.remove(this.unsetMute, this); + } + + this.game.onPause.remove(this.setPause, this); + this.game.onResume.remove(this.setResume, this); + + // Stream or file? + + if (this.isStreaming) + { + if (this.video.mozSrcObject) + { + this.video.mozSrcObject.stop(); + this.video.src = null; + } + else + { + this.video.src = ''; + + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + if (this.videoStream.getTracks) + { + this.videoStream.getTracks().forEach(function (track) { + track.stop(); + }); + } + else + { + this.videoStream.stop(); + } + } + } + + this.videoStream = null; + this.isStreaming = false; + } + else + { + this.video.removeEventListener('ended', this._endCallback, true); + this.video.removeEventListener('webkitendfullscreen', this._endCallback, true); + this.video.removeEventListener('playing', this._playCallback, true); + + if (this.touchLocked) + { + this._pending = false; + } + else + { + this.video.pause(); + } + } + + return this; + + }, + + /** + * Updates the given Display Objects so they use this Video as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.Video#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.Video} This Video object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. + * + * @method Phaser.Video#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set Video.disableTextureUpload to `true`. + * + * @method Phaser.Video#render + */ + render: function () { + + if (!this.disableTextureUpload && this.playing) + { + this.baseTexture.dirty(); + } + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + this.video.muted = true; + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + this.video.muted = false; + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setPause + * @private + */ + setPause: function () { + + if (this._paused || this.touchLocked) + { + return; + } + + this._paused = true; + + this.video.pause(); + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setResume + * @private + */ + setResume: function () { + + if (!this._paused || this._codePaused || this.touchLocked) + { + return; + } + + this._paused = false; + + if (!this.video.ended) + { + this.video.play(); + } + + }, + + /** + * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it. + * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over" + * split into three different Video objects, then you will need the user to touch-unlock every single one of them. + * + * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains + * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again. + * + * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate. + * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it + * cannot render the new video on iOS (desktop browsers cope better). + * + * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know + * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state + * are adopted automatically by the new video. + * + * @method Phaser.Video#changeSource + * @param {string} src - The new URL to change the video.src to. + * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated? + * @return {Phaser.Video} This Video object for method chaining. + */ + changeSource: function (src, autoplay) { + + if (autoplay === undefined) { autoplay = true; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + this.texture.valid = false; + + this.video.pause(); + + this._pendingChangeSource = true; + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.video.src = src; + + this.video.load(); + + this._autoplay = autoplay; + + if (!autoplay) + { + this.paused = true; + } + + return this; + + }, + + /** + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.Video#checkVideoProgress + * @private + */ + checkVideoProgress: function () { + + // if (this.video.readyState === 2 || this.video.readyState === 4) + if (this.video.readyState === 4) + { + this._pendingChangeSource = false; + + // We've got enough data to update the texture for playback + this.updateTexture(); + } + else + { + this.retry--; + + if (this.retry > 0) + { + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming); + } + } + + }, + + /** + * Sets the Input Manager touch callback to be Video.unlock. + * Required for mobile video unlocking. Mostly just used internally. + * + * @method Phaser.Video#setTouchLock + */ + setTouchLock: function () { + + this.game.input.addTouchLockCallback(this.unlock, this, true); + this.touchLocked = true; + + }, + + /** + * Enables the video on mobile devices, usually after the first touch. + * If the SoundManager hasn't been unlocked then this will automatically unlock that as well. + * Only one video can be pending unlock at any one time. + * + * @method Phaser.Video#unlock + */ + unlock: function () { + + this.touchLocked = false; + + if (this.playWhenUnlocked) + { + this.video.play(); + + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + + if (this.key) + { + var _video = this.game.cache.getVideo(this.key); + + if (_video && !_video.isBlob) + { + _video.locked = false; + } + } + + this.onTouchUnlock.dispatch(this); + + return true; + + }, + + /** + * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData. + * + * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw. + * + * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy. + * + * @method Phaser.Video#grab + * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false. + * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining. + */ + grab: function (clear, alpha, blendMode) { + + if (clear === undefined) { clear = false; } + if (alpha === undefined) { alpha = 1; } + if (blendMode === undefined) { blendMode = null; } + + if (this.snapshot === null) + { + console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable'); + return; + } + + if (clear) + { + this.snapshot.cls(); + } + + this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode); + + return this.snapshot; + + }, + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * Also removes the autoplay and src attributes and nulls the reference. + * + * @method Phaser.Video#removeVideoElement + */ + removeVideoElement: function () { + + if (!this.video) + { + return; + } + + if (this.video.parentNode) + { + this.video.parentNode.removeChild(this.video); + } + + while (this.video.hasChildNodes()) + { + this.video.removeChild(this.video.firstChild); + } + + this.video.removeAttribute('autoplay'); + this.video.removeAttribute('src'); + + this.video = null; + + }, + + /** + * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`. + * If any Sprites are using this Video as their texture it is up to you to manage those. + * + * @method Phaser.Video#destroy + */ + destroy: function () { + + this.stop(); + + this.removeVideoElement(); + + if (this.touchLocked) + { + this.game.input.touch.removeTouchLockCallback(this.unlock, this); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + + } + +}; + +/** +* @name Phaser.Video#currentTime +* @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time. +*/ +Object.defineProperty(Phaser.Video.prototype, "currentTime", { + + get: function () { + + return (this.video) ? this.video.currentTime : 0; + + }, + + set: function (value) { + + this.video.currentTime = value; + + } + +}); + +/** +* @name Phaser.Video#duration +* @property {number} duration - The duration of the video in seconds. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "duration", { + + get: function () { + + return (this.video) ? this.video.duration : 0; + + } + +}); + +/** +* @name Phaser.Video#progress +* @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "progress", { + + get: function () { + + return (this.video) ? (this.video.currentTime / this.video.duration) : 0; + + } + +}); + +/** +* @name Phaser.Video#mute +* @property {boolean} mute - Gets or sets the muted state of the Video. +*/ +Object.defineProperty(Phaser.Video.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || null; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* Gets or sets the paused state of the Video. +* If the video is still touch locked (such as on iOS devices) this call has no effect. +* +* @name Phaser.Video#paused +* @property {boolean} paused +*/ +Object.defineProperty(Phaser.Video.prototype, "paused", { + + get: function () { + + return this._paused; + + }, + + set: function (value) { + + value = value || null; + + if (this.touchLocked) + { + return; + } + + if (value) + { + if (this._paused) + { + return; + } + + this._codePaused = true; + this.setPause(); + } + else + { + if (!this._paused) + { + return; + } + + this._codePaused = false; + this.setResume(); + } + } + +}); + +/** +* @name Phaser.Video#volume +* @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Video.prototype, "volume", { + + get: function () { + + return (this.video) ? this.video.volume : 1; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this.video) + { + this.video.volume = value; + } + + } + +}); + +/** +* @name Phaser.Video#playbackRate +* @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing. +*/ +Object.defineProperty(Phaser.Video.prototype, "playbackRate", { + + get: function () { + + return (this.video) ? this.video.playbackRate : 1; + + }, + + set: function (value) { + + if (this.video) + { + this.video.playbackRate = value; + } + + } + +}); + +/** +* Gets or sets if the Video is set to loop. +* Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. +* If the video isn't yet set this will always return false. +* +* @name Phaser.Video#loop +* @property {boolean} loop +*/ +Object.defineProperty(Phaser.Video.prototype, "loop", { + + get: function () { + + return (this.video) ? this.video.loop : false; + + }, + + set: function (value) { + + if (value && this.video) + { + this.video.loop = 'loop'; + } + else if (this.video) + { + this.video.loop = ''; + } + + } + +}); + +/** +* @name Phaser.Video#playing +* @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "playing", { + + get: function () { + + return (this.video) ? !(this.video.paused && this.video.ended) : false; + + } + +}); + +Phaser.Video.prototype.constructor = Phaser.Video; + +/* global Phaser:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Pixi expects these globals to exist + +if (PIXI.blendModes === undefined) +{ + PIXI.blendModes = Phaser.blendModes; +} + +if (PIXI.scaleModes === undefined) +{ + PIXI.scaleModes = Phaser.scaleModes; +} + +if (PIXI.Texture.emptyTexture === undefined) +{ + PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture()); +} + +if (PIXI.DisplayObject._tempMatrix === undefined) +{ + PIXI.DisplayObject._tempMatrix = new Phaser.Matrix(); +} + +PIXI.TextureSilentFail = true; + +// Required by Particle Storm +PIXI.canUseNewCanvasBlendModes = function () { + return Phaser.Device.canUseMultiply; +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = Phaser; + } + exports.Phaser = Phaser; + } else if (typeof define !== 'undefined' && define.amd) { + define('Phaser', (function() { return root.Phaser = Phaser; })() ); + } else { + root.Phaser = Phaser; + } + + return Phaser; +}).call(this); + +/* +* "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer +*/ diff --git a/Iteration Sequence 2.2/js/phaser.map b/Iteration Sequence 2.2/js/phaser.map new file mode 100644 index 000000000..70723bbf8 --- /dev/null +++ b/Iteration Sequence 2.2/js/phaser.map @@ -0,0 +1 @@ +{"version":3,"sources":["phaser.js"],"names":["e","exports","module","f","window","global","self","p2","t","n","r","s","o","u","a","require","i","Error","call","length","1","_dereq_","Line","Scalar","lineInt","l1","l2","precision","a1","b1","c1","a2","b2","c2","det","eq","segmentsIntersect","p1","q1","q2","dx","dy","da","db","./Scalar","2","Point","area","b","c","left","leftOn","right","rightOn","tmpPoint1","tmpPoint2","collinear","thresholdAngle","ab","bc","dot","magA","Math","sqrt","magB","acos","sqdist","3","Polygon","this","vertices","getIntersectionPoint","delta","prototype","at","v","first","last","clear","append","poly","from","to","push","makeCCW","br","reverse","tmp","N","pop","isReflex","tmpLine1","tmpLine2","canSee","p","dist","copy","j","targetPoly","k","getCutEdges","min","tmp1","tmp2","tmpPoly","nDiags","Number","MAX_VALUE","decomp","edges","slice","cutEdges","Array","polys","cutEdge","result","splice","indexOf","isSimple","path","quickDecomp","reflexVertices","steinerPoints","maxlevel","level","upperInt","lowerInt","upperDist","lowerDist","d","closestDist","upperIndex","lowerIndex","closestIndex","lowerPoly","upperPoly","console","warn","removeCollinearPoints","num","./Line","./Point","4","abs","5","./Polygon","6","name","version","description","author","keywords","main","engines","node","repository","type","url","bugs","licenses","devDependencies","grunt","grunt-contrib-jshint","grunt-contrib-nodeunit","grunt-contrib-uglify","grunt-contrib-watch","grunt-browserify","grunt-contrib-concat","dependencies","poly-decomp","7","AABB","options","lowerBound","vec2","create","upperBound","setFromPoints","points","position","angle","skinSize","l","rotate","cosAngle","cos","sinAngle","sin","x","y","add","aabb","extend","overlaps","u1","u2","containsPoint","point","overlapsRay","ray","dirFracX","direction","dirFracY","t1","t2","t3","t4","tmin","max","tmax","../math/vec2","../utils/Utils","8","Broadphase","world","boundingVolumeType","Body","BOUNDING_CIRCLE","setWorld","getCollisionPairs","boundingRadiusCheck","bodyA","bodyB","sub","d2","squaredLength","boundingRadius","aabbCheck","getAABB","boundingVolumeCheck","canCollide","KINEMATIC","STATIC","sleepState","SLEEPING","NAIVE","SAP","../objects/Body","9","NaiveBroadphase","constructor","bodies","Ncolliding","bi","bj","aabbQuery","aabbNeedsUpdate","updateAABB","../collision/Broadphase","../shapes/Circle","../shapes/Particle","../shapes/Plane","../shapes/Shape","10","Narrowphase","contactEquations","frictionEquations","enableFriction","enabledEquations","slipForce","frictionCoefficient","surfaceVelocity","contactEquationPool","ContactEquationPool","size","frictionEquationPool","FrictionEquationPool","restitution","stiffness","Equation","DEFAULT_STIFFNESS","relaxation","DEFAULT_RELAXATION","frictionStiffness","frictionRelaxation","enableFrictionReduction","collidingBodiesLastStep","TupleDictionary","contactSkinSize","setConvexToCapsuleShapeMiddle","convexShape","capsuleShape","set","radius","pointInConvex","worldPoint","convexOffset","convexAngle","worldVertex0","pic_worldVertex0","worldVertex1","pic_worldVertex1","r0","pic_r0","r1","pic_r1","verts","lastCross","v0","v1","cross","crossLength","Circle","Convex","Shape","Box","yAxis","fromValues","tmp3","tmp4","tmp5","tmp6","tmp7","tmp8","tmp9","tmp10","tmp11","tmp12","tmp13","tmp14","tmp15","tmp16","tmp17","tmp18","tmpArray","bodiesOverlap_shapePositionA","bodiesOverlap_shapePositionB","bodiesOverlap","shapePositionA","shapePositionB","Nshapesi","shapes","shapeA","toWorldFrame","Nshapesj","shapeB","collidedLastStep","id1","id","id2","get","reset","eqs","ce","fe","release","createContactEquation","firstImpact","needsUpdate","enabled","offset","createFrictionEquation","setSlipForce","relativeVelocity","createFrictionFromContact","contactPointA","contactPointB","rotate90cw","normalA","createFrictionFromAverage","numContacts","invNumContacts","scale","normalize","LINE","CONVEX","convexLine","convexBody","lineBody","lineShape","lineOffset","lineAngle","justTest","BOX","lineBox","boxBody","boxShape","boxOffset","boxAngle","convexCapsule_tempRect","width","height","convexCapsule_tempVec","CAPSULE","convexCapsule","convexPosition","capsuleBody","capsulePosition","capsuleAngle","circlePos","result1","circleConvex","result2","convexConvex","lineCapsule","linePosition","capsuleCapsule_tempVec1","capsuleCapsule_tempVec2","capsuleCapsule_tempRect1","capsuleCapsule","si","xi","ai","sj","xj","aj","circlePosi","circlePosj","enableFrictionBefore","circleCircle","rect","lineLine","positionA","angleA","positionB","angleB","PLANE","planeLine","planeBody","planeShape","planeOffset","planeAngle","worldVertex01","worldVertex11","worldEdge","worldEdgeUnit","worldNormal","worldTangent","PARTICLE","particleCapsule","particleBody","particleShape","particlePosition","particleAngle","circleLine","CIRCLE","circleBody","circleShape","circleOffset","circleAngle","lineRadius","circleRadius","orthoDist","lineToCircleOrthoUnit","projectedPoint","centerDist","lineToCircle","lineEndToLineRadius","radiusSum","pos","pos0","pos1","pow","circleCapsule","worldVertex","closestEdgeProjectedPoint","candidate","candidateDist","minCandidate","found","minCandidateDistance","candidateDistance","localVertex","particleConvex","particleOffset","convexToparticle","minEdgeNormal","offsetA","offsetB","radiusA","radiusB","planeConvex","numReported","particlePlane","circleParticle","planeCapsule_tmpCircle","planeCapsule_tmp1","planeCapsule_tmp2","planeCapsule","capsuleOffset","end1","end2","circle","numContacts1","circlePlane","numContacts2","numTotal","planeToCircle","temp","contact","sepAxis","worldPoint0","worldPoint1","penetrationVec","findSeparatingAxis","closestEdge1","getClosestEdge","closestEdge2","closestEdgeA","closestEdgeB","insideNumEdges","pcoa_tmp1","projectConvexOntoAxis","worldAxis","value","localAxis","fsa_tmp1","fsa_tmp2","fsa_tmp3","fsa_tmp4","fsa_tmp5","fsa_tmp6","offset1","angle1","offset2","angle2","maxDist","overlap","edge","normal","span1","span2","gce_tmp1","gce_tmp2","gce_tmp3","axis","flip","closestEdge","maxDot","circleHeightfield_candidate","circleHeightfield_dist","circleHeightfield_v0","circleHeightfield_v1","circleHeightfield_minCandidate","circleHeightfield_worldNormal","circleHeightfield_minCandidateNormal","HEIGHTFIELD","circleHeightfield","hfBody","hfShape","hfPos","hfAngle","data","heights","w","elementWidth","minCandidateNormal","idxA","floor","idxB","ceil","PI","convexHeightfield_v0","convexHeightfield_v1","convexHeightfield_tilePos","convexHeightfield_tempConvexShape","convexHeightfield","convexPos","tilePos","tileConvex","../equations/ContactEquation","../equations/Equation","../equations/FrictionEquation","../shapes/Box","../shapes/Convex","../utils/ContactEquationPool","../utils/FrictionEquationPool","../utils/TupleDictionary","11","Ray","checkCollisionResponse","undefined","skipBackfaces","collisionMask","collisionGroup","mode","ANY","callback","update","distanceFromIntersectionSquared","intersect","squaredDistance","CLOSEST","ALL","intersectBodies","shouldStop","body","intersectBody","intersectBody_worldPosition","collisionResponse","worldPosition","shape","worldAngle","intersectShape","_currentBody","_currentShape","raycast","reportIntersection","fraction","faceIndex","hasHit","../collision/AABB","../collision/RaycastResult","12","RaycastResult","isStopped","getHitDistance","distance","getHitPoint","out","lerp","stop","../collision/Ray","13","SAPBroadphase","axisList","axisIndex","that","_addBodyHandler","_removeBodyHandler","idx","Utils","appendArray","off","on","sortAxisList","sortList","14","Constraint","defaults","collideConnected","wakeUpBodies","equations","wakeUp","DISTANCE","GEAR","LOCK","PRISMATIC","REVOLUTE","setStiffness","setRelaxation","15","DistanceConstraint","localAnchorA","localAnchorB","worldAnchorA","worldAnchorB","maxForce","ri","rj","computeGq","setMaxForce","upperLimitEnabled","upperLimit","lowerLimitEnabled","lowerLimit","normalEquation","G","violating","minForce","rixn","rjxn","getMaxForce","./Constraint","16","GearConstraint","ratio","AngleLockEquation","maxTorque","setMaxTorque","setRatio","torque","getMaxTorque","../equations/AngleLockEquation","17","LockConstraint","localAngleB","rot","g","localOffsetB","force","xAxis","18","PrismaticConstraint","localAxisA","trans","gg","updateJacobian","disableRotationalLock","RotationalLockEquation","velocity","upperLimitEquation","ContactEquation","lowerLimitEquation","motorEquation","motorEnabled","motorSpeed","computeGW","vi","vj","wi","angularVelocity","wj","gmult","worldAxisA","orientedAnchorA","orientedAnchorB","relPosition","enableMotor","disableMotor","setLimits","lower","upper","../equations/RotationalLockEquation","19","RevoluteConstraint","pivotA","pivotB","worldPivot","localPivotA","localPivotB","worldPivotA","worldPivotB","RotationalVelocityEquation","relAngle","setMotorSpeed","speed","getMotorSpeed","../equations/RotationalVelocityEquation","20","./Equation","21","computeB","h","GW","Gq","computeGiMf","relVel","getVelocityAlongNormal","getVelocityAtPoint","subtract","22","ARRAY_TYPE","epsilon","timeStep","multiplier","qi","qj","computeGWlambda","vlambda","wlambda","iMfi","iMfj","fi","ti","angularForce","fj","tj","invMassi","invMassSolve","invMassj","invIi","invInertiaSolve","invIj","multiply","massMultiplier","computeGiMGt","addToWlambda_temp","addToWlambda_Gi","addToWlambda_Gj","addToWlambda","deltalambda","Gi","Gj","computeInvC","eps","23","FrictionEquation","getSlipForce","24","worldVectorA","worldVectorB","25","GiMf","26","EventEmitter","listener","context","_listeners","listeners","has","index","emit","event","listenerArray","target","27","ContactMaterial","materialA","materialB","Material","idCounter","friction","./Material","28","29","PolyK","GetArea","sum","Triangulate","tgs","avl","al","i0","i1","i2","ax","ay","bx","by","cx","cy","earFound","_convex","_PointInTriangle","px","py","v0x","v0y","v1x","v1y","v2x","v2y","dot00","dot01","dot02","dot11","dot12","invDenom","30","crossVZ","vec","zcomp","crossZV","toLocalFrame","framePosition","frameAngle","toGlobalFrame","localPoint","vectorToLocalFrame","worldVector","vectorToGlobalFrame","localVector","centroid","clone","mul","divide","div","sqrDist","len","sqrLen","negate","str","reflect","vector","getLineSegmentsIntersection","p0","p3","getLineSegmentsIntersectionFraction","s1_x","s1_y","s2_x","s2_y","31","_idCounter","mass","invMass","inertia","invInertia","fixedRotation","fixedX","fixedY","interpolatedPosition","interpolatedAngle","previousPosition","previousAngle","damping","angularDamping","DYNAMIC","allowSleep","wantsToSleep","AWAKE","sleepSpeedLimit","sleepTimeLimit","gravityScale","idleTime","timeLastSleepy","ccdSpeedThreshold","ccdIterations","concavePath","_wakeUpAfterNarrowphase","updateMassProperties","updateSolveMassProperties","setDensity","density","totalArea","getArea","shapeAABB","bodyAngle","computeAABB","updateBoundingRadius","addShape","removeShape","m","I","r2","computeMomentOfInertia","applyForce","relativePoint","rotForce","Body_applyForce_forceWorld","Body_applyForce_pointWorld","Body_applyForce_pointLocal","applyForceLocal","localForce","worldForce","vectorToWorldFrame","Body_applyImpulse_velo","applyImpulse","impulseVector","velo","rotVelo","Body_applyImpulse_impulseWorld","Body_applyImpulse_pointWorld","Body_applyImpulse_pointLocal","applyImpulseLocal","localImpulse","worldImpulse","fromPolygon","convexes","optimalDecomp","cm","centerOfMass","updateTriangles","updateCenterOfMass","adjustCenterOfMass","adjustCenterOfMass_tmp2","adjustCenterOfMass_tmp3","adjustCenterOfMass_tmp4","offset_times_area","setZeroForce","resetConstraintVelocity","addConstraintVelocity","applyDamping","dt","wakeUpEvent","sleep","sleepEvent","sleepTick","time","dontSleep","SLEEPY","overlapKeeper","bodiesAreOverlapping","integrate_fhMinv","integrate_velodt","integrate","minv","integrateToTimeOfImpact","end","startToEnd","rememberPosition","hit","startToEndAngle","timeOfImpact","rememberAngle","iter","tmid","narrowphase","sleepyEvent","../events/EventEmitter","32","LinearSpring","Spring","setWorldAnchorA","setWorldAnchorB","getWorldAnchorA","getWorldAnchorB","worldDistance","restLength","applyForce_r","applyForce_r_unit","applyForce_u","applyForce_f","applyForce_worldAnchorA","applyForce_worldAnchorB","applyForce_ri","applyForce_rj","applyForce_tmp","r_unit","rlen","ri_x_f","rj_x_f","./Spring","33","RotationalSpring","restAngle","34","35","TopDownVehicle","chassisBody","wheels","groundBody","preStepCallback","WheelConstraint","vehicle","forwardEquation","sideEquation","steerValue","engineForce","setSideFriction","sideFriction","localForwardVector","localPosition","apply","setBrakeForce","addToWorld","addBody","wheel","addConstraint","removeFromWorld","removeBody","removeConstraint","addWheel","wheelOptions","worldVelocity","getSpeed","tmpVec","../constraints/Constraint","36","Capsule","GSSolver","Heightfield","Particle","Plane","Pool","Solver","World","Object","defineProperty","../package.json","./collision/AABB","./collision/Broadphase","./collision/NaiveBroadphase","./collision/Narrowphase","./collision/Ray","./collision/RaycastResult","./collision/SAPBroadphase","./constraints/Constraint","./constraints/DistanceConstraint","./constraints/GearConstraint","./constraints/LockConstraint","./constraints/PrismaticConstraint","./constraints/RevoluteConstraint","./equations/AngleLockEquation","./equations/ContactEquation","./equations/Equation","./equations/FrictionEquation","./equations/RotationalVelocityEquation","./events/EventEmitter","./material/ContactMaterial","./material/Material","./math/vec2","./objects/Body","./objects/LinearSpring","./objects/RotationalSpring","./objects/Spring","./objects/TopDownVehicle","./shapes/Box","./shapes/Capsule","./shapes/Circle","./shapes/Convex","./shapes/Heightfield","./shapes/Line","./shapes/Particle","./shapes/Plane","./shapes/Shape","./solver/GSSolver","./solver/Solver","./utils/ContactEquationPool","./utils/FrictionEquationPool","./utils/Pool","./utils/Utils","./world/World","37","arguments","axes","updateArea","./Convex","./Shape","38","intersectCapsule_hitPointWorld","intersectCapsule_normal","intersectCapsule_l0","intersectCapsule_l1","intersectCapsule_unit_y","hitPointWorld","l0","halfLen","diagonalLengthSquared","sqrtDelta","inv2a","d1","39","Ray_intersectSphere_intersectionPoint","Ray_intersectSphere_normal","intersectionPoint","40","isArray","triangles","polyk","tmpVec1","tmpVec2","projectOntoLocalAxis","projectOntoWorldAxis","shapeOffset","shapeAngle","polykVerts","id3","updateCenterOfMass_centroid","updateCenterOfMass_centroid_times_mass","updateCenterOfMass_a","updateCenterOfMass_b","updateCenterOfMass_c","centroid_times_mass","triangleArea","denom","numer","intersectConvex_rayStart","intersectConvex_rayEnd","intersectConvex_normal","rayStart","rayEnd","../math/polyk","41","key","maxValue","minValue","updateMaxMinValues","getLineSegment","start","getSegmentIndex","getClampedSegmentIndex","intersectHeightfield_worldNormal","intersectHeightfield_l0","intersectHeightfield_l1","intersectHeightfield_localFrom","intersectHeightfield_localTo","localFrom","localTo","42","raycast_normal","raycast_l0","raycast_l1","raycast_unit_y","43","44","intersectPlane_planePointToFrom","intersectPlane_normal","intersectPlane_len","planePointToFrom","planeToFrom","n_dot_dir","45","material","sensor","46","GS","iterations","tolerance","arrayStep","lambda","Bs","invCs","useZeroRHS","frictionIterations","usedIterations","setArrayZero","array","solve","sortEquations","maxIter","maxFrictionIter","Neq","tolSquared","Nbodies","deltalambdaTot","iterateEquation","updateMultipliers","invDt","B","invC","lambdaj","GWlambda","lambdaj_plus_deltalambda","./Solver","47","equationSortFunction","mockWorld","solveIsland","island","removeAllEquations","addEquations","getBodies","sort","addEquation","removeEquation","ISLAND","48","destroy","equation","./Pool","49","50","IslandNodePool","IslandNode","../world/IslandNode","51","IslandPool","Island","../world/Island","52","OverlapKeeper","overlappingShapesLastState","overlappingShapesCurrentState","recordPool","OverlapKeeperRecordPool","tmpDict","tmpArray1","tick","current","keys","lastObject","getByKey","setOverlapping","getNewOverlaps","getDiff","getEndOverlaps","dictA","dictB","isNewOverlap","idA","idB","getNewBodyOverlaps","getBodyDiff","getEndBodyOverlaps","accumulator","./OverlapKeeperRecord","./OverlapKeeperRecordPool","./TupleDictionary","./Utils","53","OverlapKeeperRecord","54","record","55","objects","resize","object","56","getKey","dict","57","howmany","P2_ARRAY_TYPE","Float32Array","58","bodyIds","59","IslandManager","nodePool","islandPool","islands","nodes","queue","getUnvisitedNode","Nnodes","visited","visit","bds","Neqs","bfs","root","child","neighbors","split","ni","nj","./../utils/IslandNodePool","./../utils/IslandPool","./Island","./IslandNode","60","61","springs","disabledBodyCollisionPairs","solver","islandManager","gravity","frictionGravity","useWorldGravityAsFrictionGravity","useFrictionGravityOnZeroGravity","broadphase","constraints","defaultMaterial","defaultContactMaterial","lastTimeStep","applySpringForces","applyGravity","solveConstraints","contactMaterials","stepping","bodiesToBeRemoved","islandSplit","emitImpactEvent","_constraintIdCounter","_bodyIdCounter","postStepEvent","addBodyEvent","removeBodyEvent","addSpringEvent","spring","impactEvent","contactEquation","postBroadphaseEvent","pairs","sleepMode","NO_SLEEPING","beginContactEvent","endContactEvent","preSolveEvent","BODY_SLEEPING","ISLAND_SLEEPING","constraint","addContactMaterial","contactMaterial","removeContactMaterial","getContactMaterial","cmats","step_mg","xiw","xjw","step","timeSinceLastCalled","maxSubSteps","internalStep","substeps","endOverlaps","Nsprings","np","mg","gravityLen","ignoredPairs","Nconstraints","Nresults","runNarrowphase","ev","glen","aiw","ajw","reducedMass","resolver","numFrictionBefore","numFrictionEquations","addSpring","evt","removeSpring","getBodyById","disableBodyCollision","enableBodyCollision","cs","cms","hitTest_tmp1","hitTest_tmp2","hitTest","pb","ps","NS","setGlobalStiffness","setGlobalRelaxation","tmpAABB","../../package.json","../collision/Narrowphase","../collision/SAPBroadphase","../constraints/DistanceConstraint","../constraints/GearConstraint","../constraints/LockConstraint","../constraints/PrismaticConstraint","../constraints/RevoluteConstraint","../material/ContactMaterial","../material/Material","../objects/LinearSpring","../objects/RotationalSpring","../shapes/Capsule","../shapes/Line","../solver/GSSolver","../solver/Solver","../utils/OverlapKeeper","./IslandManager","_CreateEmptyTexture","gl","scaleMode","texture","createTexture","bindTexture","TEXTURE_2D","texParameteri","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","TEXTURE_MAG_FILTER","PIXI","scaleModes","LINEAR","NEAREST","TEXTURE_MIN_FILTER","texImage2D","RGBA","UNSIGNED_BYTE","_CreateFramebuffer","textureUnit","framebuffer","createFramebuffer","depthStencilBuffer","createRenderbuffer","colorBuffer","fbStatus","activeTexture","TEXTURE0","bindFramebuffer","FRAMEBUFFER","bindRenderbuffer","RENDERBUFFER","framebufferRenderbuffer","DEPTH_STENCIL_ATTACHMENT","renderBuffer","framebufferTexture2D","COLOR_ATTACHMENT0","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","error","_fbErrors","targetTexture","DisplayObject","pivot","rotation","alpha","visible","hitArea","renderable","parent","worldAlpha","worldTransform","Phaser","Matrix","worldScale","worldRotation","filterArea","_sr","_cr","_bounds","Rectangle","_currentBounds","_mask","_cacheAsBitmap","_cacheIsDirty","children","_destroyCachedSprite","updateTransform","game","tx","ty","pt","wt","PI2","rotationCache","determ","HALF_PI","transformCallback","transformCallbackContext","preUpdate","generateTexture","resolution","renderer","bounds","getLocalBounds","renderTexture","RenderTexture","_tempMatrix","render","updateCache","_generateCachedSprite","toGlobal","toLocal","applyInverse","_renderCachedSprite","renderSession","_cachedSprite","Sprite","_renderWebGL","_renderCanvas","baseTexture","_enableMultiTextureToggle","textureIndex","tempFilters","_filters","filters","anchor","displayObjectUpdateTransform","defineProperties","worldVisible","item","mask","isMask","passes","filterPasses","_filterBlock","blendMode","blendModes","MULTIPLY","NORMAL","cacheAsBitmap","DisplayObjectContainer","ignoreChildInput","addChild","addChildAt","removeChild","swapChildren","child2","index1","getChildIndex","index2","setChildIndex","currentIndex","getChildAt","removeChildAt","removeChildren","beginIndex","endIndex","range","removed","displayObjectContainerUpdateTransform","getBounds","targetCoordinateSpace","isTargetCoordinateSpaceDisplayObject","isTargetCoordinateSpaceThisOrParent","contains","matrixCache","identityMatrix","childBounds","childMaxX","childMaxY","minX","Infinity","minY","maxX","maxY","childVisible","w0","w1","h0","h1","x1","y1","x2","y2","x3","y3","x4","y4","targetCoordinateSpaceBounds","spriteBatch","flush","filterManager","pushFilter","maskManager","pushMask","popMask","popFilter","_width","_height","defaultAnchor","Texture","emptyTexture","tint","cachedTint","tintedTexture","shader","exists","hasLoaded","onTextureUpdate","frame","setTexture","destroyBase","skipRender","valid","matrix","crop","currentBlendMode","globalCompositeOperation","blendModesCanvas","globalAlpha","smoothProperty","trim","shakeX","shakeY","cw","ch","rotated","roundPixels","setTransform","requiresReTint","CanvasTinter","getTintedTexture","drawImage","source","initDefaultShaders","CompileVertexShader","shaderSrc","_CompileShader","VERTEX_SHADER","CompileFragmentShader","FRAGMENT_SHADER","shaderType","src","join","createShader","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","log","getShaderInfoLog","compileProgram","vertexSrc","fragmentSrc","fragmentShader","vertexShader","shaderProgram","createProgram","attachShader","linkProgram","getProgramParameter","LINK_STATUS","getProgramInfoLog","PixiShader","_UID","program","textureCount","firstRun","dirty","attributes","init","initMultitexShader","MAX_TEXTURES","getParameter","MAX_TEXTURE_IMAGE_UNITS","dynamicIfs","defaultVertexSrc","useProgram","uSamplerArray","getUniformLocation","projectionVector","offsetVector","dimensions","aVertexPosition","getAttribLocation","aTextureCoord","colorAttribute","aTextureIndex","indices","tempTexture","RGB","uniform1iv","uniforms","uniformLocation","initUniforms","initDefaultShader","uSampler","usingFilter","uniform","_init","initSampler2D","glMatrix","glValueLength","glFunc","uniformMatrix2fv","uniformMatrix3fv","uniformMatrix4fv","_glTextures","textureData","magFilter","minFilter","wrapS","wrapT","format","LUMINANCE","repeat","REPEAT","pixelStorei","UNPACK_FLIP_Y_WEBGL","flipY","border","uniform1i","syncUniforms","transpose","z","_dirty","instances","updateTexture","deleteProgram","PixiFastShader","uMatrix","aPositionCoord","aScale","aRotation","StripShader","translationMatrix","attribute","PrimitiveShader","tintColor","ComplexPrimitiveShader","color","glContexts","WebGLRenderer","config","defaultRenderer","extensions","WEBGL","transparent","autoResize","preserveDrawingBuffer","clearBeforeRender","view","canvas","_contextOptions","antialias","failIfMajorPerformanceCaveat","premultipliedAlpha","stencil","projection","shaderManager","WebGLShaderManager","WebGLSpriteBatch","WebGLMaskManager","WebGLFilterManager","stencilManager","WebGLStencilManager","blendModeManager","WebGLBlendModeManager","currentBatchedTextures","drawCount","maxTextureAvailableSpace","initContext","mapBlendModes","getContext","maxTextures","maxTextureSize","MAX_TEXTURE_SIZE","glContextId","disable","DEPTH_TEST","CULL_FACE","enable","BLEND","setContext","compression","etc1","getExtension","pvrtc","s3tc","ETC1","PVRTC","S3TC","setTexturePriority","textureNameCollection","clampPot","potSize","imageCache","cache","_cache","image","imageName","base","stage","contextLost","viewport","clearColor","_bgColor","COLOR_BUFFER_BIT","camera","_shake","renderDisplayObject","displayObject","buffer","setBlendMode","begin","style","updateCompressedTexture","textureMetaData","compressedTexImage2D","glExtensionFormat","mipmap","isPowerOfTwo","LINEAR_MIPMAP_LINEAR","NEAREST_MIPMAP_NEAREST","generateMipmap","_powerOf2","compressionAlgorithm","UNPACK_PREMULTIPLY_ALPHA_WEBGL","CanvasPool","remove","blendModesWebGL","modes","ONE","ONE_MINUS_SRC_ALPHA","ADD","SRC_ALPHA","DST_ALPHA","DST_COLOR","SCREEN","OVERLAY","DARKEN","LIGHTEN","COLOR_DODGE","COLOR_BURN","HARD_LIGHT","SOFT_LIGHT","DIFFERENCE","EXCLUSION","HUE","SATURATION","COLOR","LUMINOSITY","getMaxTextureUnit","enableMultiTexture","textureArray","blendModeWebGL","blendFunc","maskData","WebGLGraphics","updateGraphics","_webGL","pushStencil","popStencil","stencilStack","count","graphics","webGLData","bindGraphics","STENCIL_TEST","STENCIL_BUFFER_BIT","colorMask","stencilFunc","ALWAYS","stencilOp","KEEP","INVERT","drawElements","TRIANGLE_FAN","UNSIGNED_SHORT","EQUAL","DECR","INCR","TRIANGLE_STRIP","_currentGraphics","complexPrimitiveShader","setShader","uniform1f","toArray","uniform2f","uniform3fv","Color","hexToRGBArray","bindBuffer","ARRAY_BUFFER","vertexAttribPointer","FLOAT","ELEMENT_ARRAY_BUFFER","indexBuffer","primitiveShader","maxAttibs","attribState","tempAttribState","stack","defaultShader","fastShader","stripShader","creatureShader","CreatureShader","setAttribs","attribs","attribId","enableVertexAttribArray","disableVertexAttribArray","_currentId","currentShader","vertSize","vertexSize","numVerts","numIndices","ArrayBuffer","positions","colors","Uint32Array","Uint16Array","lastIndexCount","drawing","currentBatchSize","currentBaseTexture","textures","shaders","sprites","Filter","vertexBuffer","createBuffer","bufferData","STATIC_DRAW","DYNAMIC_DRAW","sprite","uvs","_uvs","aX","aY","a0","b0","c0","d0","_w1","_w0","_updateUvsInverted","x0","y0","renderTilingSprite","tilingTexture","TextureUvs","tilePosition","tileScaleOffset","offsetX","offsetY","scaleX","tileScale","scaleY","stride","bufferSubData","subarray","nextTexture","nextBlendMode","nextShader","batchSize","blendSwap","shaderSwap","skip","renderBatch","startIndex","TRIANGLES","deleteBuffer","WebGLFastSpriteBatch","maxSize","renderSprite","filterStack","texturePool","initShaderBuffers","filterBlock","_filterArea","_previous_stencil_mgr","filter","FilterTexture","padding","frameBuffer","_glFilterTexture","vertexArray","uvBuffer","uvArray","inputTexture","outputTexture","filterPass","applyFilterPass","sizeX","sizeY","currentFilter","colorArray","36054","36055","36057","36061","DEFAULT","renderbufferStorage","DEPTH_STENCIL","deleteFramebuffer","deleteTexture","CanvasBuffer","clearRect","CanvasMaskManager","save","cacheAlpha","transform","CanvasGraphics","renderGraphicsMask","clip","restore","tintMethod","tintWithMultiply","fillStyle","toString","substr","fillRect","tintWithPerPixel","rgbValues","pixelData","getImageData","pixels","canHandleAlpha","putImageData","CanvasRenderer","CANVAS","refresh","Canvas","getSmoothingPrefix","navigator","isCocoonJS","screencanvas","rgba","removeView","useNew","device","canUseMultiply","BaseTexture","complete","naturalWidth","naturalHeight","forceLoaded","removeByCanvas","unloadFromGPU","glTexture","fromCanvas","TextureSilentFail","noFrame","isTiling","requiresUpdate","setFrame","onBaseTextureLoaded","_updateUvs","tw","th","define","amd","WheelEventProxy","scaleFactor","deltaMode","_scaleFactor","_deltaMode","originalEvent","VERSION","GAMES","AUTO","HEADLESS","WEBGL_MULTI","NONE","LEFT","RIGHT","UP","DOWN","SPRITE","BUTTON","IMAGE","GRAPHICS","TEXT","TILESPRITE","BITMAPTEXT","GROUP","RENDERTEXTURE","TILEMAP","TILEMAPLAYER","EMITTER","POLYGON","BITMAPDATA","CANVAS_FILTER","WEBGL_FILTER","ELLIPSE","SPRITEBATCH","RETROFONT","POINTER","ROPE","RECTANGLE","MATRIX","POINT","ROUNDEDRECTANGLE","CREATURE","VIDEO","PENDING_ATLAS","HORIZONTAL","VERTICAL","LANDSCAPE","PORTRAIT","ANGLE_UP","ANGLE_DOWN","ANGLE_LEFT","ANGLE_RIGHT","ANGLE_NORTH_EAST","ANGLE_NORTH_WEST","ANGLE_SOUTH_EAST","ANGLE_SOUTH_WEST","TOP_LEFT","TOP_CENTER","TOP_RIGHT","LEFT_TOP","LEFT_CENTER","LEFT_BOTTOM","CENTER","RIGHT_TOP","RIGHT_CENTER","RIGHT_BOTTOM","BOTTOM_LEFT","BOTTOM_CENTER","BOTTOM_RIGHT","trunc","Function","bind","thisArg","bound","args","boundArgs","concat","TypeError","F","proto","arg","forEach","fun","CheapArray","assert","assign","varArgs","hasOwn","hasOwnProperty","nextSource","nextKey","reverseString","string","getProperty","obj","parts","_getProperty","setProperties","props","setProperty","_setProperty","val","currentObj","chanceRoll","chance","random","randomChoice","choice1","choice2","parseDimension","dimension","parseInt","innerWidth","innerHeight","pad","dir","padlen","isPlainObject","nodeType","copyIsArray","deep","mixinPrototype","mixin","replace","mixinKeys","childNodes","cloneNode","diameter","_diameter","_radius","circumference","setTo","copyFrom","copyTo","dest","round","output","circumferencePoint","asDegrees","sample","steps","startAngle","endAngle","linear","offsetPoint","top","bottom","equals","intersects","degToRad","intersectsRectangle","halfWidth","halfHeight","xCornerDist","yCornerDist","intersectsLine","returnPoints","del","p0Exists","pointOnSegment","p1Exists","Ellipse","normx","normy","fromPoints","fromSprite","startSprite","endSprite","useCenter","centerX","centerY","fromAngle","rotateAround","line","asSegment","intersectsPoints","midPoint","centerOn","pointOnLine","fuzzyEqual","xMin","xMax","yMin","yMax","coordinatesOnLine","stepRate","results","sx","sy","err","e2","wrap","uc","ua","ub","empty","bx1","by1","bx2","by2","intersectionWithRectangle","edgeIntersection","closestDistance","normalAngle","fromArray","newPos","translate","tx1","identity","invert","setToPolar","azimuth","clampX","clamp","clampY","equalsXY","fuzzyEquals","fuzzyEqualsXY","angleXY","atan2","radToDeg","atan","getMagnitude","getMagnitudeSq","setMagnitude","magnitude","isZero","limit","expand","perp","rperp","normalRightHand","negative","multiplyAdd","interpolate","project","amt","projectUnit","pointslength","parse","xProp","yProp","isPoint","sortClockwise","center","_points","closed","flattened","toNumberArray","flatten","inside","ix","iy","jx","jy","calculateArea","avgHeight","floorAll","ceilAll","copyFromBounds","inflate","containsRect","intersection","intersectsRaw","union","randomX","randomY","getPoint","sides","inflatePoint","createFromBounds","containsRaw","rx","ry","rw","rh","volume","sameDimensions","NEGATIVE_INFINITY","POSITIVE_INFINITY","EmptyRectangle","RoundedRectangle","Camera","deadzone","roundPx","atLimit","totalInView","onShakeComplete","Signal","onFlashComplete","onFadeComplete","fx","_targetPosition","_edge","_position","intensity","duration","horizontal","vertical","shakeBounds","_fxDuration","_fxType","_fixedView","FOLLOW_LOCKON","FOLLOW_PLATFORMER","FOLLOW_TOPDOWN","FOLLOW_TOPDOWN_TIGHT","SHAKE_BOTH","SHAKE_HORIZONTAL","SHAKE_VERTICAL","ENABLE_FX","boot","Graphics","follow","lerpX","lerpY","helper","unfollow","focusOn","setPosition","focusOnXY","shake","flash","beginFill","drawRect","endFill","fade","updateFX","updateShake","checkBounds","elapsedMS","dispatch","rnd","frac","updateTarget","math","setBoundsToWorld","vx","vw","vy","vh","setSize","resetFX","State","make","input","load","sound","state","tweens","particles","physics","preload","loadUpdate","loadRender","preRender","paused","resumed","pauseUpdate","shutdown","StateManager","pendingState","states","_pendingState","_clearWorld","_clearCache","_created","_args","onStateChange","onInitCallback","onPreloadCallback","onCreateCallback","onUpdateCallback","onRenderCallback","onResizeCallback","onPreRenderCallback","onLoadUpdateCallback","onLoadRenderCallback","onPausedCallback","onResumedCallback","onPauseUpdateCallback","onShutDownCallback","onPause","pause","onResume","resume","autoStart","newState","isBooted","callbackContext","clearWorld","clearCache","checkState","restart","dummy","previousStateKey","clearCurrentState","setCurrentState","totalQueuedFiles","totalQueuedPacks","loadComplete","removeAll","debug","link","unlink","_kickstart","getCurrentState","elapsedTime","renderType","_bindings","_prevParams","memorize","_shouldPropagate","active","_boundDispatch","validateListener","fnName","_registerListener","isOnce","listenerContext","priority","binding","prevIndex","_indexOfListener","SignalBinding","_addBinding","execute","_priority","cur","_listener","addOnce","_destroy","getNumListeners","halt","bindings","paramsArr","forget","dispose","_this","signal","_isOnce","_signal","callCount","params","handlerReturn","detach","isBound","getListener","getSignal","prevPoint","Date","mouse","date","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","sampleRate","iChannel0","iChannel1","iChannel2","iChannel3","setResolution","pointer","toFixed","totalElapsedSeconds","anchorX","anchorY","Cache","Plugin","hasPreUpdate","hasUpdate","hasPostUpdate","hasRender","hasPostRender","postRender","PluginManager","plugins","_len","_i","plugin","postUpdate","Stage","disableVisibilityChange","currentRenderOrderID","_hiddenVar","_onChange","parseConfig","setBackgroundColor","DOM","getOffset","setUserSelect","setTouchAction","checkVisibility","document","hidden","webkitHidden","mozHidden","msHidden","visibilityChange","_onClick","hasFocus","addEventListener","onblur","onfocus","onpagehide","onpageshow","cocoonJSApp","CocoonJS","App","onSuspended","onActivated","focusLoss","focusGain","gamePaused","gameResumed","valueToColor","updateColor","removeEventListener","silent","hash","removeFromHash","Group","addToStage","enableBody","physicsBodyType","Physics","ARCADE","physicsType","alive","ignoreDestroy","pendingDestroy","classType","cursor","inputEnableChildren","updateOnlyExistingChildren","onChildInputDown","onChildInputUp","onChildInputOver","onChildInputOut","enableBodyDebug","physicsSortDirection","onDestroy","cursorIndex","fixedToCamera","cameraOffset","_sortProperty","RETURN_NONE","RETURN_TOTAL","RETURN_CHILD","RETURN_ALL","SORT_ASCENDING","SORT_DESCENDING","updateZ","addToHash","inputEnabled","events","onAddedToGroup$dispatch","addAt","addMultiple","moveAll","getAt","createMultiple","quantity","singleKey","singleFrame","align","cellWidth","cellHeight","alignIn","resetCursor","next","previous","swap","child1","bringToTop","getIndex","sendToBack","moveUp","moveDown","xy","getByName","oldChild","newChild","hasProperty","operation","checkProperty","checkAlive","checkVisible","setAll","setAllChildren","checkAll","checkAny","addAll","property","amount","subAll","multiplyAll","divideAll","kill","killAll","callAllExists","revive","reviveAll","resetAll","checkExists","resetChild","existsValue","callbackFromArray","callAll","method","methodLength","contextLength","renderOrderID","predicate","ArraySet","forEachExists","iterate","forEachAlive","forEachDead","order","ascendingSortHandler","descendingSortHandler","customSort","sortHandler","returnType","total","getFirst","getFirstExists","createIfNull","getFirstAlive","getFirstDead","loadTexture","getTop","getBottom","getClosestTo","tempDistance","getFurthestFrom","countLiving","countDead","getRandom","ArrayUtils","getRandomItem","getRandomExists","list","getAll","pick","destroyPhase","onRemovedFromGroup$dispatch","group","destroyTexture","removeBetween","scatter","shuffle","destroyChildren","soft","_definedSize","stateChange","setBounds","useBounds","wrapAll","between","Game","physicsConfig","multiTexture","isRunning","raf","net","Device","lockRender","pendingStep","stepCount","onBlur","onFocus","_paused","_codePaused","currentUpdateID","updatesThisFrame","rendersThisFrame","_deltaTime","_lastCount","_spiraling","fpsProblemNotifier","forceSingleUpdate","forceSingleRender","dropFrames","_nextFpsNotification","enableDebug","RandomDataGenerator","now","whenReady","seed","ScaleManager","setUpRenderer","GameObjectFactory","GameObjectCreator","Loader","Time","TweenManager","Input","SoundManager","Particles","Create","Net","Debug","isDisabled","showDebugHeader","RequestAnimationFrame","stopFocus","focus","isReady","onReady","hideBanner","webAudio","ie","setImageRenderingCrisp","webGL","contextRestored","webGLRendererError","cocoonJS","smoothed","addToDOM","preventDefault","clearGLTextures","updateLogic","desiredFpsMult","updateRender","slowMotion","desiredFps","slowStep","elapsed","countUpdate","countRender","enableStep","disableStep","removeFromDOM","muteOnPause","setMute","cordova","iOS","unsetMute","hitCanvas","hitContext","moveCallbacks","customCandidateHandler","customCandidateHandlerContext","pollRate","multiInputOverride","MOUSE_TOUCH_COMBINE","maxPointers","tapRate","doubleTapRate","holdRate","justPressedRate","justReleasedRate","recordPointerHistory","recordRate","recordLimit","touchLockCallbacks","pointer1","pointer2","pointer3","pointer4","pointer5","pointer6","pointer7","pointer8","pointer9","pointer10","pointers","activePointer","mousePointer","keyboard","touch","mspointer","gamepad","resetLocked","onDown","onUp","onTap","onHold","minPriorityID","interactiveItems","_localPoint","_pollCounter","_oldPosition","_x","_y","MOUSE_OVERRIDES_TOUCH","TOUCH_OVERRIDES_MOUSE","MAX_POINTERS","Pointer","PointerMode","CURSOR","addPointer","Mouse","Touch","MSPointer","Keyboard","Gamepad","_onClickTrampoline","onClickTrampoline","setInteractiveCandidateHandler","addMoveCallback","addTouchLockCallback","onEnd","removeTouchLockCallback","executeTouchLockCallbacks","cb","deleteMoveCallback","CONTACT","hard","resetSpeed","startPointer","countActivePointers","updatePointer","identifier","move","stopPointer","getPointer","isActive","getPointerFromIdentifier","getPointerFromId","pointerId","getLocalPosition","Creature","TileSprite","graphicsData","fill","processClickTrampolines","mouseDownCallback","mouseUpCallback","mouseOutCallback","mouseOverCallback","mouseWheelCallback","capture","button","wheelDelta","locked","stopOnGameOut","pointerLock","_onMouseDown","_onMouseMove","_onMouseUp","_onMouseOut","_onMouseOver","_onMouseWheel","_wheelEvent","NO_BUTTON","LEFT_BUTTON","MIDDLE_BUTTON","RIGHT_BUTTON","BACK_BUTTON","FORWARD_BUTTON","WHEEL_UP","WHEEL_DOWN","android","chrome","onMouseDown","onMouseMove","onMouseUp","_onMouseUpGlobal","onMouseUpGlobal","_onMouseOutGlobal","onMouseOutGlobal","onMouseOut","onMouseOver","onMouseWheel","wheelEvent","mouseMoveCallback","withinGame","resetButtons","bindEvent","deltaY","requestPointerLock","element","mozRequestPointerLock","webkitRequestPointerLock","_pointerLockChange","pointerLockChange","pointerLockElement","mozPointerLockElement","webkitPointerLockElement","releasePointerLock","exitPointerLock","mozExitPointerLock","webkitExitPointerLock","_stubsGenerated","prop","makeBinder","detail","deltaX","wheelDeltaX","deltaZ","pointerDownCallback","pointerMoveCallback","pointerUpCallback","_onMSPointerDown","_onMSPointerMove","_onMSPointerUp","_onMSPointerUpGlobal","_onMSPointerOut","_onMSPointerOver","onPointerDown","onPointerMove","onPointerUp","onPointerUpGlobal","onPointerOut","onPointerOver","pointerType","DeviceButton","buttonCode","isDown","isUp","timeDown","timeUp","repeats","altKey","shiftKey","ctrlKey","onFloat","startStop","condition","padFloat","justPressed","justReleased","pointerMode","leftButton","middleButton","rightButton","backButton","forwardButton","eraserButton","ERASER_BUTTON","_holdSent","_history","_nextDrop","_stateReset","clientX","clientY","pageX","pageY","screenX","screenY","rawMovementX","rawMovementY","movementX","movementY","isMouse","previousTapTime","totalTouches","msSinceLastClick","targetObject","interactiveCandidates","positionDown","positionUp","_clickTrampolines","_trampolineTargetObject","processButtonsDown","processButtonsUp","processButtonsUpDown","buttons","down","toLowerCase","updateButtons","totalActivePointers","_touchedHandler","processInteractiveObjects","shift","fromClick","pollLocked","mozMovementX","webkitMovementX","mozMovementY","webkitMovementY","noPause","isDragged","highestRenderOrderID","highestInputPriorityID","candidateTarget","currentNode","checked","validForInput","checkPointerDown","checkPointerOver","priorityID","swapTarget","newTarget","_pointerOutHandler","_pointerOverHandler","leave","currentPointers","addClickTrampoline","callbackArgs","trampolines","trampoline","_releasedHandler","resetMovement","touchStartCallback","touchMoveCallback","touchEndCallback","touchEnterCallback","touchLeaveCallback","touchCancelCallback","_onTouchStart","_onTouchMove","_onTouchEnd","_onTouchEnter","_onTouchLeave","_onTouchCancel","onTouchStart","onTouchMove","onTouchEnd","onTouchEnter","onTouchLeave","onTouchCancel","consumeDocumentTouches","_documentTouchMove","changedTouches","InputHandler","useHandCursor","_setHandCursor","allowHorizontalDrag","allowVerticalDrag","snapOffset","snapOnDrag","snapOnRelease","snapX","snapY","snapOffsetX","snapOffsetY","pixelPerfectOver","pixelPerfectClick","pixelPerfectAlpha","draggable","boundsRect","boundsSprite","scaleLayer","dragOffset","dragFromCenter","dragStopBlocksInputUp","dragStartPoint","dragDistanceThreshold","dragTimeThreshold","downPoint","snapPoint","_dragPoint","_dragPhase","_pendingDrag","_dragTimePass","_dragDistancePass","_wasEnabled","_tempPoint","_pointerData","camX","camY","isOver","isOut","timeOver","timeOut","downDuration","onAddedToGroup","addedToGroup","onRemovedFromGroup","removedFromGroup","highestID","highestRenderID","includePixelPerfect","isPixelPerfect","pointerX","pointerY","pointerDown","pointerUp","pointerTimeDown","pointerTimeUp","pointerOver","pointerOut","pointerTimeOver","pointerTimeOut","pointerDragged","fastTest","checkPixel","_dx","_dy","startDrag","_draggedPointerID","updateDrag","sendEvent","onInputOver$dispatch","onInputOut$dispatch","onInputDown$dispatch","dragTimeElapsed","onInputUp$dispatch","stopDrag","fromStart","pointerLocalCoord","globalToLocal","checkBoundsRect","checkBoundsSprite","onDragUpdate","justOver","delay","overDuration","justOut","enableDrag","lockCenter","pixelPerfect","alphaThreshold","disableDrag","boundsCenterLocalCoord","onDragStart$dispatch","globalToLocalX","grid","boundsFluid","scaleFluidInversed","globalToLocalY","globalCoord","onDragStop$dispatch","setDragLock","allowHorizontal","allowVertical","enableSnap","onDrag","onRelease","disableSnap","_gamepadIndexMap","_rawPads","_active","_gamepadSupportAvailable","webkitGetGamepads","webkitGamepads","userAgent","getGamepads","_prevRawGamepadTypes","_prevTimestamps","onConnectCallback","onDisconnectCallback","onDownCallback","onUpCallback","onAxisCallback","onFloatCallback","_ongamepadconnected","_gamepaddisconnected","_gamepads","SinglePad","addCallbacks","callbacks","onConnect","onDisconnect","onAxis","_onGamepadConnected","onGamepadConnected","_onGamepadDisconnected","onGamepadDisconnected","newPad","connect","removedPad","disconnect","_pollGamepads","pad1","pollStatus","pad2","pad3","pad4","rawGamepads","gamepadsChanged","_rawPad","singlePad","validConnections","rawIndices","padIndices","connected","rawPad","setDeadZones","deadZone","BUTTON_0","BUTTON_1","BUTTON_2","BUTTON_3","BUTTON_4","BUTTON_5","BUTTON_6","BUTTON_7","BUTTON_8","BUTTON_9","BUTTON_10","BUTTON_11","BUTTON_12","BUTTON_13","BUTTON_14","BUTTON_15","AXIS_0","AXIS_1","AXIS_2","AXIS_3","AXIS_4","AXIS_5","AXIS_6","AXIS_7","AXIS_8","AXIS_9","XBOX360_A","XBOX360_B","XBOX360_X","XBOX360_Y","XBOX360_LEFT_BUMPER","XBOX360_RIGHT_BUMPER","XBOX360_LEFT_TRIGGER","XBOX360_RIGHT_TRIGGER","XBOX360_BACK","XBOX360_START","XBOX360_STICK_LEFT_BUTTON","XBOX360_STICK_RIGHT_BUTTON","XBOX360_DPAD_LEFT","XBOX360_DPAD_RIGHT","XBOX360_DPAD_UP","XBOX360_DPAD_DOWN","XBOX360_STICK_LEFT_X","XBOX360_STICK_LEFT_Y","XBOX360_STICK_RIGHT_X","XBOX360_STICK_RIGHT_Y","PS3XC_X","PS3XC_CIRCLE","PS3XC_SQUARE","PS3XC_TRIANGLE","PS3XC_L1","PS3XC_R1","PS3XC_L2","PS3XC_R2","PS3XC_SELECT","PS3XC_START","PS3XC_STICK_LEFT_BUTTON","PS3XC_STICK_RIGHT_BUTTON","PS3XC_DPAD_UP","PS3XC_DPAD_DOWN","PS3XC_DPAD_LEFT","PS3XC_DPAD_RIGHT","PS3XC_STICK_LEFT_X","PS3XC_STICK_LEFT_Y","PS3XC_STICK_RIGHT_X","PS3XC_STICK_RIGHT_Y","padParent","_padParent","_prevTimestamp","_buttons","_buttonsLen","_axes","_axesLen","getButton","timestamp","rawButtonVal","isNaN","processButtonDown","processButtonUp","processButtonFloat","processAxisChange","triggerCallback","disconnectingIndex","axisCode","buttonValue","Key","keycode","_enabled","durationUp","keyCode","onHoldCallback","onHoldContext","_justDown","_justUp","processKeyDown","processKeyUp","upDuration","pressEvent","onPressCallback","_keys","_capture","_onKeyDown","_onKeyPress","_onKeyUp","_k","onPress","removeCallbacks","addKey","addKeyCapture","addKeys","removeKey","removeKeyCapture","createCursorKeys","up","KeyCode","processKeyPress","clearCaptures","String","fromCharCode","charCode","A","charCodeAt","C","D","E","H","J","K","L","M","O","P","Q","R","S","T","U","V","W","X","Y","Z","ZERO","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","NUMPAD_0","NUMPAD_1","NUMPAD_2","NUMPAD_3","NUMPAD_4","NUMPAD_5","NUMPAD_6","NUMPAD_7","NUMPAD_8","NUMPAD_9","NUMPAD_MULTIPLY","NUMPAD_ADD","NUMPAD_ENTER","NUMPAD_SUBTRACT","NUMPAD_DECIMAL","NUMPAD_DIVIDE","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","F13","F14","F15","COLON","EQUALS","COMMA","UNDERSCORE","PERIOD","QUESTION_MARK","TILDE","OPEN_BRACKET","BACKWARD_SLASH","CLOSED_BRACKET","QUOTES","BACKSPACE","TAB","CLEAR","ENTER","SHIFT","CONTROL","ALT","CAPS_LOCK","ESC","SPACEBAR","PAGE_UP","PAGE_DOWN","END","HOME","PLUS","MINUS","INSERT","DELETE","HELP","NUM_LOCK","match","Component","Angle","wrapAngle","Animation","play","frameRate","loop","killOnComplete","animations","AutoCull","autoCull","inCamera","checkWorldBounds","Bounds","container","alignTo","BringToTop","Core","skipTypeChecks","install","components","Events","PhysicsBody","AnimationManager","LoadTexture","FixedToCamera","previousRotation","preUpdateChildren","fresh","_exists","P2JS","customRender","Crop","cropRect","_crop","updateCrop","resetFrame","oldX","oldY","oldW","oldH","_frame","Delta","Destroy","onDestroy$dispatch","removeFrom","Video","onChangeSource","resizeFrame","BitmapText","_glyphs","_parent","_onDestroy","_onAddedToGroup","_onRemovedFromGroup","_onKilled","_onRevived","_onEnterBounds","_onOutOfBounds","_onInputOver","_onInputOut","_onInputDown","_onInputUp","_onDragStart","_onDragUpdate","_onDragStop","_onAnimationStart","_onAnimationComplete","_onAnimationLoop","onKilled","onRevived","onOutOfBounds","onEnterBounds","onInputOver","onInputOut","onInputDown","onInputUp","onDragStart","onDragStop","onAnimationStart","onAnimationComplete","onAnimationLoop","backing","_fixedToCamera","Health","health","maxHealth","damage","setHealth","heal","InCamera","InputEnabled","InWorld","outOfCameraBoundsKill","_outOfBoundsFired","onEnterBounds$dispatch","onOutOfBounds$dispatch","outOfBoundsKill","inWorld","LifeSpan","lifespan","physicsElapsedMS","onRevived$dispatch","onKilled$dispatch","stopAnimation","BitmapData","hasFrameData","loadFrameData","getFrameData","frameData","Tilemap","TilemapLayer","img","getImage","trimmed","spriteSourceSizeX","spriteSourceSizeY","sourceSizeW","sourceSizeH","refreshTexture","frameName","Overlap","_reset","Reset","ScaleMinMax","scaleMin","scaleMax","checkTransform","setScaleMinMax","Smoothed","existing","weapon","bulletClass","Weapon","createBullets","Image","creature","mesh","tween","physicsGroup","SpriteBatch","audio","audioSprite","addSprite","tileSprite","rope","Rope","text","Text","overFrame","outFrame","downFrame","upFrame","Button","emitter","maxParticles","Arcade","Emitter","retroFont","font","characterWidth","characterHeight","chars","charsPerRow","xSpacing","ySpacing","xOffset","yOffset","RetroFont","bitmapText","tilemap","tileWidth","tileHeight","addToCache","uuid","addRenderTexture","video","bitmapData","addBitmapData","Tween","preUpdatePhysics","preUpdateLifeSpan","preUpdateInWorld","preUpdateCore","_onOverFrame","_onOutFrame","_onDownFrame","_onUpFrame","onOverSound","onOutSound","onDownSound","onUpSound","onOverSoundMarker","onOutSoundMarker","onDownSoundMarker","onUpSoundMarker","onOverMouseOnly","justReleasedPreventsOver","freezeFrames","forceOut","setFrames","onInputOverHandler","onInputOutHandler","onInputDownHandler","onInputUpHandler","clearFrames","setStateFrame","switchImmediately","frameKey","changeStateFrame","setStateSound","marker","soundKey","markerKey","Sound","AudioSprite","playStateSound","setSounds","overSound","overMarker","downSound","downMarker","outSound","outMarker","upSound","upMarker","setOverSound","setOutSound","setDownSound","setUpSound","fastSpriteBatch","ready","isRotated","childTransform","skipPool","ctx","imageData","FrameData","textureFrame","addFrame","Frame","disableTextureUpload","cls","_image","_pos","_size","_scale","_rotate","_alpha","prev","_anchor","_tempR","_tempG","_tempB","_circle","_swapCanvas","moveH","moveV","draw","onload","addImage","toDataURL","processPixelRGB","pixel","createColor","unpackPixel","getPixel32","setPixel32","processPixel","replaceRGB","g1","g2","region","packPixel","setHSL","bHaveH","bHaveS","bHaveL","HSLtoRGB","shiftHSL","red","green","blue","immediate","LITTLE_ENDIAN","setPixel","getPixel","getPixelRGB","hsl","hsv","getPixels","getFirstPixel","scan","newWidth","newHeight","getCanvas","op","copyTransform","copyRect","drawGroup","drawGroupProxy","drawFull","renderGraphics","shadow","blur","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","alphaMask","sourceRect","maskRect","blendSourceAtop","blendReset","extract","destination","prevFont","fillText","beginPath","arc","closePath","moveTo","lineTo","lineWidth","strokeStyle","stroke","polygon","textureLine","createPattern","blendSourceOver","blendSourceIn","blendSourceOut","blendDestinationOver","blendDestinationIn","blendDestinationOut","blendDestinationAtop","blendXor","blendAdd","blendMultiply","blendScreen","blendOverlay","blendDarken","blendLighten","blendColorDodge","blendColorBurn","blendHardLight","blendSoftLight","blendDifference","blendExclusion","blendHue","blendSaturation","blendColor","blendLuminosity","copyBitmapData","destRowStart","getSmoothingEnabled","setSmoothingEnabled","getTransform","translateX","translateY","skewX","skewY","EarCut","holeIndices","dim","hasHoles","outerLen","outerNode","linkedList","eliminateHoles","earcutLinked","clockwise","insertNode","filterPoints","again","steiner","removeNode","ear","pass","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","minTX","minTY","maxTX","maxTY","minZ","zOrder","maxZ","nextZ","prevZ","locallyInside","isValidDiagonal","splitPolygon","getLeftmost","compareX","eliminateHole","hole","findHoleBridge","hx","hy","qx","tan","tanMin","sortLinked","q","tail","numMerges","pSize","qSize","inSize","leftmost","intersectsPolygon","middleInside","Node","an","bp","stencilBufferLimit","lastIndex","clearDirty","graphicsDataPool","switchMode","buildPoly","buildComplexPoly","buildLine","buildRectangle","buildCircle","buildRoundedRectangle","upload","WebGLGraphicsData","rectData","fillColor","fillAlpha","vertPos","tempPoints","rrectData","recPoints","quadraticBezierCurve","vecPos","fromX","fromY","cpX","cpY","toX","toY","getPt","n1","n2","perc","xa","ya","xb","yb","circleData","seg","totalSegs","firstPoint","lastPoint","midPointX","midPointY","unshift","p1x","p1y","p2x","p2y","p3x","p3y","perpx","perpy","perp2x","perp2y","perp3x","perp3y","indexCount","indexStart","lineColor","lineAlpha","glPoints","glIndicies","updateGraphicsTint","_fillTint","_lineTint","strokeRect","ox","oy","xe","ye","xm","ym","bezierCurveTo","maxRadius","quadraticCurveTo","tintR","tintG","tintB","GraphicsData","currentPath","boundsPadding","_localBounds","_boundsDirty","webGLDirty","cachedSpriteDirty","updateLocalBounds","drawTriangle","cull","triangle","cameraToFace","faceNormal","drawPolygon","drawTriangles","point1","point2","point3","lineStyle","drawShape","cpX2","cpY2","dt2","dt3","arcTo","mm","dd","cc","tt","k1","k2","j1","j2","qy","anticlockwise","segments","sweep","segs","startX","startY","filling","theta","theta2","cTheta","sTheta","segMinus","remainder","drawRoundedRect","drawCircle","drawEllipse","canvasBuffer","updateCachedSpriteTexture","_prevTint","tempPoint","cachedSprite","destroyCachedSprite","textureBuffer","tempMatrix","renderXY","renderRawXY","updateBase","realResolution","getBase64","webGLPixels","Uint8Array","readPixels","tempCanvas","canvasData","textBounds","strokeColors","fontStyles","fontWeights","autoRound","useAdvancedWrap","splitRegExp","characterLimitSize","characterLimitSuffix","_res","_text","_fontComponents","_lineSpacing","_charCount","setStyle","updateText","setShadow","shadowStroke","shadowFill","newStyle","backgroundColor","boundsAlignH","boundsAlignV","strokeThickness","wordWrap","wordWrapWidth","maxLines","tabs","fontToComponents","fontStyle","fontVariant","fontWeight","fontSize","componentsToFont","outputText","substring","runWordWrap","lines","lineWidths","maxLineWidth","fontProperties","determineFontProperties","drawnLines","measureLine","measureText","tab","section","snapToCeil","lineHeight","lineSpacing","textBaseline","lineCap","lineJoin","linePositionX","linePositionY","ascent","updateLine","updateShadow","strokeText","renderTabLine","snap","lineLength","letter","clearColors","clearFontValues","addColor","addStrokeColor","addFontStyle","addFontWeight","weight","precalculateWordWrap","advancedWordWrap","basicWordWrap","linesCount","currentLineWidth","words","word","wordWithSpace","wordWidth","newWord","secondPart","spaceLeft","wordWidthWithSpace","updateFont","family","exec","fontFamily","setText","parseList","setTextBounds","properties","fontPropertiesCache","fontPropertiesCanvas","fontPropertiesContext","baseline","descent","imagedata","setCharacterLimit","characterLimit","suffix","parseFloat","createElement","textWidth","textHeight","_prevAnchor","_maxWidth","_data","getBitmapFont","_font","_fontSize","_align","_tint","sourceWidth","sourceHeight","scanLine","lastSpace","wrappedWidth","prevCharCode","maxWidth","test","charAt","charData","kerning","xAdvance","cleanText","re","purgeGlyphs","kept","checkImageKey","characterSpacingX","characterSpacingY","characterPerRow","multiLine","autoUpperCase","customSpacingX","customSpacingY","fixedWidth","fontSet","grabData","currentX","currentY","updateFrameData","stamp","ALIGN_LEFT","ALIGN_RIGHT","ALIGN_CENTER","TEXT_SET1","TEXT_SET2","TEXT_SET3","TEXT_SET4","TEXT_SET5","TEXT_SET6","TEXT_SET7","TEXT_SET8","TEXT_SET9","TEXT_SET10","TEXT_SET11","setFixedWidth","lineAlignment","content","characterSpacing","allowLowerCase","buildRetroFontText","getLongestLine","pasteLine","longestLine","removeUnsupportedCharacters","stripCR","newString","aChar","code","updateOffset","diffX","diffY","frames","getFrames","newText","toUpperCase","_hasUpdateAnimation","_updateAnimationCallback","canvasPadding","drawMode","updateAnimation","nextPoint","perpLength","_vertexBuffer","_initWebGL","_renderStrip","_indexBuffer","_uvBuffer","_colorBuffer","_renderCanvasTriangleStrip","_renderCanvasTriangles","_renderCanvasDrawTriangle","index0","textureSource","textureWidth","textureHeight","u0","v2","paddingX","paddingY","normX","normY","deltaA","deltaB","deltaC","deltaD","deltaE","deltaF","renderStripFlat","strip","rawX","rawY","_updateAnimation","difference","_scroll","textureDebug","tilePattern","frameWidth","frameHeight","physicsElapsed","autoScroll","stopScroll","generateTilingTexture","restartBatch","sessionBlendMode","forcePowerOfTwo","targetWidth","targetHeight","getNextPowerOfTwo","pool","getTotal","getFree","deviceReadyAt","initialized","desktop","iOSVersion","nodeWebkit","electron","ejecta","crosswalk","chromeOS","linux","macOS","windows","windowsPhone","canvasBitBltShift","file","fileSystem","localStorage","worker","css3D","typedArray","vibration","getUserMedia","quirksMode","arora","chromeVersion","epiphany","firefox","firefoxVersion","ieVersion","trident","tridentVersion","mobileSafari","midori","opera","safari","safariVersion","webApp","silk","audioData","ogg","opus","mp3","wav","m4a","webm","dolby","oggVideo","h264Video","mp4Video","webmVideo","vp9Video","hlsVideo","iPhone","iPhone4","iPad","pixelRatio","littleEndian","support32bit","fullscreen","requestFullscreen","cancelFullscreen","fullscreenKeyboard","onInitialized","nonPrimer","readyCheck","_readyCheck","_monitor","_queue","readyState","setTimeout","_initialize","_checkIsLittleEndian","_checkIsUint8ClampedImageData","Uint8ClampedArray","createImageData","vita","kindle","RegExp","$1","_checkOS","$3","process","versions","_checkBrowser","audioElement","canPlayType","major","minor","$2","_checkAudio","videoElement","_checkVideo","has3d","el","transforms","webkitTransform","OTransform","msTransform","MozTransform","insertBefore","getComputedStyle","getPropertyValue","_checkCSS3D","Int8Array","Int32Array","vibrate","webkitVibrate","mozVibrate","msVibrate","getItem","WebGLRenderingContext","compatMode","webkitGetUserMedia","mozGetUserMedia","msGetUserMedia","oGetUserMedia","URL","webkitURL","mozURL","msURL","_checkFeatures","s1","s2","_checkCanvasFeatures","fs","cfs","Element","_checkFullScreenSupport","documentElement","maxTouchPoints","PointerEvent","MSPointerEvent","msPointerEnabled","pointerEnabled","canPlayAudio","canPlayVideo","needsTouchUnlock","PhaserGlobal","fakeiOSTouchLock","isAndroidStockBrowser","matches","display","msTouchAction","overflowHidden","getElementById","overflow","appendChild","parentNode","vendor","prefix","types","msInterpolationMode","setImageRenderingBicubic","forceSetTimeOut","vendors","requestAnimationFrame","cancelAnimationFrame","_isSetTimeOut","_onLoop","_timeOutID","updateSetTimeout","updateRAF","rafTime","timeToCall","clearTimeout","isSetTimeOut","isRAF","DEG_TO_RAD","RAD_TO_DEG","degrees","radians","fuzzyLessThan","fuzzyGreaterThan","fuzzyCeil","fuzzyFloor","average","shear","snapTo","gap","snapToFloor","roundTo","place","floorTo","ceilTo","rotateToAngle","currentAngle","targetAngle","getShortestAngle","angleBetween","angleBetweenY","angleBetweenPoints","angleBetweenPointsY","reverseAngle","angleRad","normalizeAngle","maxAdd","minSub","wrapValue","isOdd","isEven","minProperty","maxProperty","linearInterpolation","bezierInterpolation","bernstein","catmullRomInterpolation","catmullRom","factorial","res","roundAwayFromZero","sinCosGenerator","sinAmplitude","cosAmplitude","frequency","frq","cosTable","sinTable","hypot","distanceSq","distancePow","clampBottom","within","mapLinear","smoothstep","smootherstep","sign","percent","seeds","s0","sow","integer","real","integerInRange","realInRange","ary","weightedPick","QuadTree","maxObjects","maxLevels","_empty","subWidth","subHeight","populate","populateHandler","insert","retrieve","returnObjects","getHostName","location","hostname","checkDomainName","domain","updateQueryString","redirect","href","separator","getQueryString","parameter","keyValues","search","decodeURI","decodeURIComponent","frameBased","_tweens","_add","easeMap","Power0","Easing","Power1","Power2","Power3","Power4","Linear","None","Quad","Quadratic","Out","Cubic","Quart","Quartic","Quint","Quintic","Sine","Sinusoidal","Expo","Exponential","Circ","Circular","Elastic","Back","Bounce","Quad.easeIn","In","Cubic.easeIn","Quart.easeIn","Quint.easeIn","Sine.easeIn","Expo.easeIn","Circ.easeIn","Elastic.easeIn","Back.easeIn","Bounce.easeIn","Quad.easeOut","Cubic.easeOut","Quart.easeOut","Quint.easeOut","Sine.easeOut","Expo.easeOut","Circ.easeOut","Elastic.easeOut","Back.easeOut","Bounce.easeOut","Quad.easeInOut","InOut","Cubic.easeInOut","Quart.easeInOut","Quint.easeInOut","Sine.easeInOut","Expo.easeInOut","Circ.easeInOut","Elastic.easeInOut","Back.easeInOut","Bounce.easeInOut","_pauseAll","_resumeAll","pendingDelete","_manager","addTweens","numTweens","isTweening","checkIsRunning","some","_pause","_resume","pauseAll","resumeAll","manager","timeline","timeScale","repeatCounter","onStart","onLoop","onRepeat","onChildComplete","onComplete","chainedTween","isPaused","_onUpdateCallback","_onUpdateCallbackContext","_pausedTime","_hasStarted","ease","yoyo","Default","TweenData","vEnd","loadValues","updateTweenData","repeatDelay","yoyoDelay","easing","interpolation","repeatAll","chain","startTime","status","PENDING","RUNNING","LOOPED","COMPLETE","generateData","vStart","vStartCache","vEndCache","repeatTotal","inReverse","easingFunction","interpolationFunction","interpolationContext","isFrom","ms","fps","blob","reversed","asin","prevTime","_desiredFps","suggestedFps","advancedTiming","updates","renders","ups","rps","fpsMin","fpsMax","msMin","msMax","pauseDuration","timeExpected","Timer","_frameCount","_elapsedAccumulator","_started","_timeLastSecond","_pauseStarted","_justResumed","_timers","timer","autoDestroy","previousDateNow","updateAdvancedTiming","updateTimers","interval","elapsedSince","since","elapsedSecondsSince","running","expired","nextTick","timeCap","_pauseTotal","_now","_marked","_diff","_newTick","MINUTE","SECOND","HALF","QUARTER","repeatCount","TimerEvent","clearEvents","clearPendingEvents","adjustEvents","baseTime","currentFrame","currentAnim","updateIfVisible","isLoaded","_frameData","_anims","_outputFrames","anim","copyFrameData","useNumericIndex","getFrameIndexes","validateFrames","checkFrameName","isPlaying","getAnimation","refreshFrame","gotFrame","getFrame","getFrameByName","_frameIndex","_frames","loopCount","isFinished","_pauseStartTime","_frameDiff","_frameSkip","onUpdate","isReversed","_timeLastFrame","_timeNextFrame","updateCurrentFrame","onAnimationStart$dispatch","reverseOnce","frameId","useLocalFrameIndex","frameIndex","directionalOffset","dispatchComplete","onAnimationComplete$dispatch","onAnimationLoop$dispatch","signalUpdate","fromPlay","generateFrameNames","zeroPad","spriteSourceSizeW","spriteSourceSizeH","setTrim","actualWidth","actualHeight","destX","destY","destWidth","destHeight","getRect","_frameNames","getFrameRange","AnimationParser","spriteSheet","frameMax","margin","spacing","skipFrames","JSONData","json","newFrame","filename","sourceSize","spriteSourceSize","JSONDataPyxel","tileheight","tilewidth","JSONDataHash","XMLData","xml","getElementsByTagName","frameX","frameY","autoResolveURL","binary","bitmapFont","compressedTexture","_urlMap","_urlResolver","_urlTemp","onSoundUnlock","_cacheMap","TEXTURE","SOUND","PHYSICS","BINARY","BITMAPFONT","JSON","XML","SHADER","RENDER_TEXTURE","_pendingCount","_addImages","DEFAULT_KEY","DEFAULT_SRC","MISSING","MISSING_KEY","MISSING_SRC","READY_TIMEOUT","addCompressedTextureMetaData","extension","arrayBuffer","removeImage","LoaderParser","fileFormat","_resolveURL","addCanvas","addImageAsync","_removePending","_addPending","addDefaultImage","addMissingImage","addSound","audioTag","decoded","isDecoding","touchLocked","addText","addPhysicsData","addTilemap","mapData","addBinary","binaryData","addBitmapFont","atlasData","atlasType","jsonBitmapFont","xmlBitmapFont","addBitmapFontFromAtlas","atlasKey","atlasFrame","dataKey","dataType","getBaseTexture","fontData","getJSON","getXML","addJSON","addXML","addVideo","isBlob","addShader","addSpriteSheet","addTextureAtlas","TEXTURE_ATLAS_XML_STARLING","TEXTURE_ATLAS_JSON_PYXEL","reloadSound","getSound","reloadSoundComplete","updateSound","decodedSound","isSoundDecoded","isSoundReady","checkKey","checkURL","checkCanvasKey","checkTextureKey","checkSoundKey","checkTextKey","checkPhysicsKey","checkTilemapKey","checkBinaryKey","checkBitmapDataKey","checkBitmapFontKey","checkJSONKey","checkXMLKey","checkVideoKey","checkShaderKey","checkRenderTextureKey","full","getTextureFrame","getSoundData","getText","getPhysicsData","fixtureKey","fixtures","fixture","getTilemapData","getBinary","getBitmapData","getVideo","getShader","getRenderTexture","getFrameCount","getFrameByIndex","getURL","getKeys","removeCanvas","destroyBaseTexture","removeSound","removeText","removePhysics","removeTilemap","removeBinary","removeBitmapData","removeBitmapFont","removeJSON","removeXML","removeVideo","removeShader","removeRenderTexture","removeSpriteSheet","removeTextureAtlas","baseURL","destroyItem","readyTimeout","_ready","_checkReady","isLoading","preloadSprite","crossOrigin","headers","requestedWith","onLoadStart","onLoadComplete","onPackComplete","onFileStart","onFileComplete","onFileError","enableParallel","maxParallelDownloads","_withSyncPointDepth","_fileList","_flightQueue","_processingHead","_fileLoadStarted","_totalPackCount","_totalFileCount","_loadedPackCount","_loadedFileCount","TEXTURE_ATLAS_JSON_ARRAY","TEXTURE_ATLAS_JSON_HASH","PHYSICS_LIME_CORONA_JSON","PHYSICS_PHASER_JSON","setPreloadSprite","checkKeyExists","getAssetIndex","bestFound","loaded","loading","getAsset","fileIndex","addToFileList","overwrite","syncPoint","currentFile","replaceInFileList","pack","imageFromBitmapData","imageFromGrid","imageFromTexture","pixelWidth","pixelHeight","palette","exkey","images","urls","script","spritesheet","autoDecode","noAudio","jsonURL","jsonData","audiosprite","loadEvent","asBlob","CSV","TILED_JSON","LIME_CORONA_JSON","textureURL","atlasURL","parseXml","atlasJSONArray","atlas","atlasJSONHash","atlasXML","withSyncPoint","addSyncPoint","asset","removeFile","updateProgress","processLoadQueue","finishedLoading","requestUrl","requestObject","progress","syncblock","inflightLimit","processPack","loadFile","abnormal","asyncComplete","errorMessage","packData","transformUrl","xhrLoad","fileComplete","loadImageTag","getAudioURL","usingWebAudio","usingAudioTag","loadAudioTag","fileError","getVideoURL","loadVideoTag","jsonLoadComplete","xmlLoadComplete","csvLoadComplete","onerror","controls","autoplay","videoLoadEvent","canplay","Audio","playThroughEvent","xhr","XMLHttpRequest","open","responseType","setRequestHeader","message","send","videoType","uri","lastIndexOf","audioType","reason","loadNext","responseText","response","decode","language","defer","head","contentType","domparser","DOMParser","parseFromString","ActiveXObject","async","loadXML","totalLoadedFiles","totalLoadedPacks","progressFloat","info","common","getAttribute","letters","kernings","second","finalizeBitmapFont","_face","_lineHeight","_id","_xoffset","_yoffset","_xadvance","_second","_first","_amount","bitmapFontData","pvr","uintArray","byteArray","pvrHeader","pixelFormat","flags","colorSpace","channelType","depth","numberOfSurfaces","numberOfFaces","numberOfMipmaps","metaDataSize","byteLength","dds","ddsHeader","pitch","mipmapCount","formatSize","formatFlag","formatFourCC","formatBitCount","formatRBitMask","formatGBitMask","formatBBitMask","formatABitMask","caps1","caps2","caps3","caps4","reserved2","DXGIFormat","resourceDimension","miscFlag","arraySize","ktx","ktxHeader","imageSizeOffset","imageSize","glInternalFormat","endianness","glType","glTypeSize","glFormat","glBaseInternalFormat","pixelDepth","numberOfArrayElements","numberOfMipmapLevels","bytesOfKeyValueData","keyAndValueByteSize","pkm","pkmHeader","originalWidth","originalHeight","autoplayKey","sounds","spritemap","addMarker","connectToMaster","markers","totalDuration","currentTime","durationMS","stopTime","pausedPosition","pausedTime","currentMarker","fadeTween","pendingPlayback","override","allowMultiple","externalNode","masterGainNode","gainNode","_sound","_globalVolume","_markedToDelete","_removeFromSoundManager","masterGain","createGain","createGainNode","gain","soundHasUnlocked","onDecoded","onPlay","onStop","onMute","onMarkerComplete","_volume","_buffer","_muted","_tempMarker","_tempPosition","_tempVolume","_tempPause","_muteVolume","_tempLoop","_onDecodedEventDispatched","removeMarker","onEndedHandler","onended","isDecoded","loopFull","forceRestart","noteOff","createBufferSource","noteGrainOn","muted","mute","prevMarker","fadeIn","fadeTo","fadeOut","fadeComplete","updateGlobalVolume","globalVolume","onSoundDecode","onVolumeChange","onUnMute","onTouchUnlock","channels","_codeMuted","_unlockSource","_sounds","_watchList","_watching","_watchCallback","_watchContext","disableAudio","disableWebAudio","audioContext","setTouchLock","unlock","setTouchUnlock","noteOn","stopAll","soundData","decodeAudioData","setDecodedCallback","files","playbackState","PLAYING_STATE","FINISHED_STATE","removeByKey","close","dom","minWidth","minHeight","maxHeight","forceLandscape","forcePortrait","incorrectOrientation","_pageAlignHorizontally","_pageAlignVertically","onOrientationChange","enterIncorrectOrientation","leaveIncorrectOrientation","hasPhaserSetFullScreen","fullScreenTarget","_createdFullScreenTarget","onFullScreenInit","onFullScreenChange","onFullScreenError","screenOrientation","getScreenOrientation","scaleFactorInversed","aspectRatio","sourceAspectRatio","windowConstraints","compatibility","supportsFullScreen","orientationFallback","noMargins","scrollTo","forceMinimumDocumentHeight","canExpandParent","clickTrampoline","_scaleMode","NO_SCALE","_fullScreenScaleMode","parentIsWindow","parentScaleFactor","trackParentInterval","onSizeChange","onResize","onResizeContext","_pendingScaleMode","_fullScreenRestore","_gameSize","_userScaleFactor","_userScaleTrim","_lastUpdate","_updateThrottle","_updateThrottleReset","_parentBounds","_tempBounds","_lastReportedCanvasSize","_lastReportedGameSize","_booted","setupScale","EXACT_FIT","SHOW_ALL","RESIZE","USER_SCALE","MODES","compat","_orientationChange","orientationChange","_windowResize","windowResize","_fullScreenChange","fullScreenChange","_fullScreenError","fullScreenError","_gameResumed","setGameSize","FlexGrid","fullScreenScaleMode","pageAlignHorizontally","alignH","pageAlignVertically","alignV","scaleH","scaleV","setUserScale","trimH","trimV","getParentBounds","visualBounds","updateDimensions","queueUpdate","currentScaleMode","hScale","vScale","hTrim","vTrim","setResizeCallback","signalSizeChange","setMinMax","prevThrottle","prevWidth","prevHeight","boundsChanged","orientationChanged","updateOrientationState","updateLayout","throttle","updateScalingAndBounds","forceOrientation","classifyOrientation","orientation","previousOrientation","previouslyIncorrect","isLandscape","isPortrait","changed","correctnessChanged","scrollTop","setMaximum","setExactFit","isFullScreen","boundingParent","setShowAll","resetCanvas","reflowCanvas","reflowGame","layoutBounds","clientRect","getBoundingClientRect","parentRect","offsetParent","wc","windowBounds","alignCanvas","parentBounds","canvasBounds","currentEdge","targetEdge","marginLeft","marginRight","marginTop","marginBottom","cssWidth","cssHeight","expanding","createFullScreenTarget","fsTarget","background","startFullScreen","allowTrampoline","cleanupCreatedTarget","initData","targetElement","ALLOW_KEYBOARD_INPUT","stopFullScreen","prepScreenMode","enteringFullscreen","createdTarget","scaleSprite","letterBox","scaleX1","scaleY1","scaleX2","scaleY2","scaleOnWidth","bmd","columnWidth","renderShadow","currentColor","currentAlpha","_line","_rect","soundInfo","filled","rectangle","geom","cameraInfo","hideIfUp","downColor","upColor","worldX","worldY","spriteInputInfo","justDown","justUp","inputInfo","spriteBounds","ropeSegments","segment","spriteInfo","spriteCoords","lineInfo","forceType","ellipse","quadTree","quadtree","NINJA","Ninja","BOX2D","Box2D","renderBody","bodyInfo","renderBodyInfo","box2d","box2dWorld","renderDebugDraw","box2dBody","displayList","canvasPool","phaser","factor","loader","box","scrollY","scrollLeft","scrollX","clientTop","clientLeft","cushion","calibrate","coords","getAspectRatio","inLayoutViewport","primaryFallback","screen","mozOrientation","msOrientation","matchMedia","documentBounds","pageXOffset","pageYOffset","clientWidth","clientHeight","offsetWidth","scrollWidth","offsetHeight","scrollHeight","randomIndex","removeRandomItem","newLength","transposeMatrix","sourceRowCount","sourceColCount","rotateMatrix","findClosest","arr","NaN","low","high","rotateRight","rotateLeft","numberArray","numberArrayStep","LinkedList","entity","palettes","0","PALETTE_ARNE","PALETTE_JMP","PALETTE_CGA","PALETTE_C64","PALETTE_JAPANESE_MACHINE","row","boundsCustom","boundsFull","boundsNone","positionCustom","positionFluid","positionFull","positionNone","scaleCustom","scaleFluid","scaleFull","scaleNone","customWidth","customHeight","customOffsetX","customOffsetY","ratioH","ratioV","layers","createCustomLayer","layer","FlexLayer","createFluidLayer","createFullLayer","createFixedLayer","persist","fitSprite","topLeft","topMiddle","topRight","bottomLeft","bottomMiddle","bottomRight","RED","ORANGE","YELLOW","GREEN","AQUA","BLUE","VIOLET","WHITE","BLACK","GRAY","RGBtoHSL","RGBtoHSV","fromRGBA","toRGBA","toABGR","RGBArrayToHex","rgb","hueToColor","HSVtoRGB","color32","getColor","getColor32","RGBtoString","componentToHex","hexToRGB","hex","hexToColor","webToColor","web","tempColor","getRGB","HSVColorWheel","HSLColorWheel","interpolateColor","color1","color2","currentStep","src1","src2","hsv1","hsv2","dh","h3","interpolateColorWithRGB","or","og","ob","interpolateRGB","getRandomColor","getWebRGB","getAlpha","getAlphaFloat","getRed","getGreen","getBlue","blendNormal","blendAverage","blendSubtract","blendNegation","blendLinearDodge","blendLinearBurn","blendLinearLight","blendVividLight","blendPinLight","blendHardMix","blendReflect","blendGlow","blendPhoenix","arcade","ninja","chipmunk","matter","CHIPMUNK","MATTERJS","P2","Matter","startSystem","system","enableAABB","checkCollision","OVERLAP_BIAS","forceX","sortDirection","LEFT_RIGHT","skipQuadTree","_total","SORT_NONE","RIGHT_LEFT","TOP_BOTTOM","BOTTOM_TOP","updateMotion","allowRotation","velocityDelta","computeVelocity","angularAcceleration","angularDrag","maxAngular","acceleration","drag","maxVelocity","allowGravity","allowDrag","object1","object2","overlapCallback","processCallback","collideObjects","collide","collideCallback","sortLeftRight","sortRightLeft","sortTopBottom","sortBottomTop","overlapOnly","collideHandler","collideGroupVsSelf","collideSpriteVsSprite","collideSpriteVsGroup","collideSpriteVsTilemapLayer","collideGroupVsGroup","collideGroupVsTilemapLayer","sprite1","sprite2","separate","items","bounds1","bounds2","group1","group2","body1","body2","none","isCircle","separateCircle","bodyRect","bodyCircle","resultX","resultY","separateX","separateY","onOverlap","onCollide","circleBodyIntersects","getOverlapX","getOverlapY","angleCollision","immovable","customSeparateX","tempVel1","tempVel2","bounce","maxOverlap","deltaAbsX","embedded","touching","overlapX","deltaAbsY","overlapY","moves","nv1","nv2","avg","customSeparateY","getObjectsUnderPointer","getObjectsAtLocation","callbackArg","moveToObject","maxTime","distanceBetween","moveToPointer","angleToPointer","distanceToPointer","moveToXY","distanceToXY","velocityFromAngle","velocityFromRotation","accelerationFromRotation","accelerateToObject","xSpeedMax","ySpeedMax","accelerateToPointer","accelerateToXY","angleToXY","closest","targets","farthest","angleBetweenCenters","worldAngleToPointer","preRotation","newVelocity","deltaMax","worldBounce","onWorldBounds","facing","overlapR","collideWorldBounds","wasTouching","blocked","tilePadding","syncBounds","isMoving","stopVelocityOnCollide","moveTimer","moveDistance","moveDuration","moveTarget","moveEnd","onMoveComplete","movementCallback","movementCallbackContext","_sx","_sy","updateBounds","asx","asy","updateCenter","updateMovement","collided","stopMovement","stopVelocity","check","moveFrom","setCircle","onFloor","onCeiling","onWall","TilemapCollision","TILE_BIAS","tilemapLayer","getTiles","getTileOffsetX","getTileOffsetY","separateTile","tile","tilemapLayerOffsetX","tilemapLayerOffsetY","collisionCallback","collisionCallbackContext","faceLeft","faceRight","faceTop","faceBottom","tileCheckX","tileCheckY","collideRight","collideLeft","processTileSeparationX","collideDown","collideUp","processTileSeparationY","useElapsedTime","materials","InversePointProxy","walls","onBodyAdded","onBodyRemoved","onSpringAdded","onSpringRemoved","onConstraintAdded","onConstraintRemoved","onContactMaterialAdded","onContactMaterialRemoved","postBroadphaseCallback","onBeginContact","onEndContact","mpx","mpxi","pxm","pxmi","beginContactHandler","endContactHandler","collisionGroups","nothingCollisionGroup","CollisionGroup","boundsCollisionGroup","everythingCollisionGroup","boundsCollidesWith","_toRemove","_collisionGroupID","_boundsLeft","_boundsRight","_boundsTop","_boundsBottom","_boundsOwnGroup","removeBodyNextStep","setImpactEvents","impactHandler","setPostBroadphaseCallback","postBroadphaseHandler","_bodyCallbacks","_bodyCallbackContext","_groupCallbacks","_groupCallbackContext","setCollisionGroup","setWorldMaterial","updateBoundsCollisionGroup","setupWall","wall","fixedStepTime","impactCallback","createDistanceConstraint","getBody","createGearConstraint","createRevoluteConstraint","createLockConstraint","createPrismaticConstraint","lockRotation","anchorA","anchorB","setMaterial","createMaterial","createContactMaterial","getSprings","getConstraints","filterStatic","physicsPosition","query","toJSON","createCollisionGroup","bitmask","createSpring","worldA","worldB","localA","localB","createRotationalSpring","createBody","addPolygon","createParticle","convertCollisionObjects","map","collision","shapeData","polyline","addRectangle","clearTilemapLayerBodies","getLayer","convertTilemap","optimize","collides","getTileRight","FixtureList","rawList","namedFixtures","groupedFixtures","allFixtures","setCategory","bit","getFixtures","setMask","setSensor","getFixtureByKey","getGroup","groupID","_ref","_results","callee","PointProxy","collidesWith","removeNextStep","debugBody","_collideWorldBounds","setRectangleFromSprite","createBodyCallback","createGroupCallback","getCollisionMask","updateCollisionMask","clearCollision","clearGroup","clearMask","removeCollisionGroup","clearCallback","shapeChanged","impulse","localX","localY","setZeroRotation","setZeroVelocity","setZeroDamping","moveForward","moveBackward","thrust","thrustLeft","thrustRight","moveLeft","moveRight","updateSpriteTransform","resetDamping","resetMass","clearShapes","addCircle","addPlane","addParticle","addLine","addCapsule","setRectangle","addPhaserPolygon","createdFixtures","fixtureData","shapesOfFixture","addFixture","generatedShapes","categoryBits","maskBits","isSensor","polygons","loadPolygon","BodyDebug","settings","defaultSettings","pixelsPerLengthUnit","debugPolygons","ppu","lw","vrot","_j","_ref1","randomPastelHex","drawCapsule","drawPlane","drawLine","drawRectangle","drawConvex","drawPath","lastx","lasty","diagMargin","diagSize","maxLength","xd","yd","mix","rgbToHex","ImageCollection","firstgid","imageWidth","imageHeight","imageMargin","imageSpacing","containsImageIndex","imageIndex","gid","Tile","flipped","scanned","setCollisionCallback","setCollision","resetCollision","isInteresting","faces","TilemapParser","widthInPixels","heightInPixels","tilesets","imagecollections","tiles","collideIndexes","currentLayer","debugMap","_tempA","NORTH","EAST","SOUTH","WEST","setTileSize","createBlankLayer","addTilesetImage","tileset","tileMargin","tileSpacing","getTilesetIndex","setImage","newSet","Tileset","countX","countY","columns","rows","createFromObjects","CustomClass","adjustY","adjustSize","createFromTiles","replacements","customClass","lh","createLayer","getLayerIndex","rootLayer","groupEnd","indexes","getImageIndex","setTileIndexCallback","setTileLocationCallback","recalculate","setCollisionByIndex","calculateFaces","setCollisionBetween","setCollisionByExclusion","layerArg","setPreventRecalculate","preventingRecalculate","needToRecalculate","above","below","getTileAbove","getTileBelow","getTileLeft","setLayer","hasTile","removeTile","removeTileWorldXY","putTile","putTileWorldXY","searchTileIndex","getTile","nonNull","getTileWorldXY","paste","tileblock","tileA","tileB","swapHandler","removeAllLayers","dump","txt","renderSettings","enableScrollDelta","overdrawRatio","copyCanvas","debugSettings","missingImageFill","debuggedTileOverfill","forceFullRedraw","debugAlpha","facingEdgeStroke","collidingTileOverfill","scrollFactorX","scrollFactorY","rayStepRate","_wrap","_mc","renderWidth","renderHeight","_scrollX","_scrollY","tileOffset","ensureSharedCopyCanvas","sharedCopyCanvas","resizeWorld","_fixX","_unfixX","_fixY","_unfixY","getTileX","getTileY","getTileXY","getRayCastTiles","interestingFace","coord","fetchAll","wy","wx","resolveTileset","tileIndex","setIndex","containsTileIndex","resetTilesetCache","setScale","xScale","yScale","shiftCanvas","copyW","copyH","copyContext","renderRegion","lastAlpha","xmax","ymax","baseX","normStartX","renderDeltaScroll","shiftX","shiftY","renderW","renderH","trueTop","trueBottom","trueLeft","trueRight","renderFull","redrawAll","mc","renderDebug","baseY","normStartY","INSERT_NULL","getEmptyData","parseCSV","parseTiledJSON","column","_slice","fields","sliced","parseObjectGroup","objectGroup","objectsCollection","collisionCollection","nameKey","relativePosition","curl","encoding","binaryString","atob","bytes","opacity","offsetx","offsety","flippedVal","curi","tilesetGroupObjects","lastSet","tileproperties","tileProperties","updateTileData","imagewidth","imageheight","newCollection","objectgroup","lastgid","sid","drawCoords","coordIndex","setSpacing","rowCount","colCount","autoScale","scaleData","_s","autoAlpha","alphaData","_a","onEmit","setAlphaData","setScaleData","emitters","ID","minAngle","maxAngle","minSpeed","maxSpeed","minParticleSpeed","maxParticleSpeed","minParticleScale","maxParticleScale","minRotation","maxRotation","minParticleAlpha","maxParticleAlpha","particleClass","particleDrag","particleAnchor","emitX","emitY","particleBringToTop","particleSendToBack","counts","emitted","failed","totalEmitted","totalFailed","_gravity","_minParticleScale","_maxParticleScale","_timer","_counter","_flowQuantity","_flowTotal","_explode","emitParticle","makeParticles","particleArguments","particle","rndKey","rndFrame","explode","flow","forceQuantity","getNextParticle","resetParticle","setXSpeed","setYSpeed","setRotation","setAlpha","rate","tweenData","setAngle","lifespanOutput","bullets","autoExpandBulletsGroup","autofire","shots","fireLimit","fireRate","fireRateVariance","fireFrom","fireAngle","bulletInheritSpriteSpeed","bulletAnimation","bulletFrameRandom","bulletFrameCycle","bulletWorldWrap","bulletWorldWrapPadding","bulletAngleOffset","bulletAngleVariance","bulletSpeed","bulletSpeedVariance","bulletLifespan","bulletKillDistance","bulletGravity","bulletRotateToVelocity","bulletKey","bulletFrame","_bulletClass","Bullet","_bulletCollideWorldBounds","_bulletKillType","KILL_WORLD_BOUNDS","customBody","bulletBounds","bulletFrames","bulletFrameIndex","anims","onFire","onKill","onFireLimit","trackedSprite","trackedPointer","multiFire","_hasFired","trackRotation","trackOffset","_nextFire","_tempNextFire","_rotatedPoint","KILL_NEVER","KILL_LIFESPAN","KILL_DISTANCE","KILL_WEAPON_BOUNDS","KILL_CAMERA_BOUNDS","KILL_STATIC_BOUNDS","resetShots","newLimit","fire","trackSprite","trackPointer","fireMany","fireOffset","moveX","moveY","bullet","bulletManager","killType","bulletKillType","killDistance","rotateToVelocity","bodyDirty","bulletCollideWorldBounds","fireAtPointer","fireAtSprite","fireAtXY","setBulletBodyOffset","setBulletFrames","cycle","addBulletAnimation","debugBodies","onAccess","onError","onTimeout","playWhenUnlocked","timeout","videoStream","isStreaming","retryLimit","retry","retryInterval","_retryID","_pending","_pendingChangeSource","_autoplay","_endCallback","_playCallback","_video","createVideoFromBlob","videoWidth","videoHeight","createVideoFromURL","snapshot","connectToMediaStream","stream","startMediaStream","captureAudio","removeVideoElement","setAttribute","getUserMediaTimeout","getUserMediaSuccess","getUserMediaError","mozSrcObject","createObjectURL","onloadeddata","checkStream","checkVideoProgress","change","playbackRate","setPause","setResume","playHandler","getTracks","track","playing","ended","changeSource","grab","hasChildNodes","firstChild","removeAttribute","canUseNewCanvasBlendModes"],"mappings":";;CAoDC,SAASA,GAAG,GAAG,iBAAiBC,QAAQC,OAAOD,QAAQD,QAAS,CAAmD,IAAIG,EAAE,oBAAoBC,OAAOD,EAAEC,OAAO,oBAAoBC,OAAOF,EAAEE,OAAO,oBAAoBC,OAAOH,EAAEG,MAAMH,EAAEI,GAAGP,KAAzO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,EAASitB,KAAW4wB,EAEpB79C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIW,GACxB/0D,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAIpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW4wB,EAEpB79C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAItW,GACxB99C,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAGpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIpW,GACxBh+C,EAASitB,KAAWmnC,EAAInW,GAExBj+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAKpBn6C,EAASitB,KAAW0wB,EACpB39C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU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AAKm+G,MAAM1K,MAIrCpmG,IAAK,SAAU8N,GAEPA,GAASnb,KAAKm+G,MAEdn+G,KAAKm+G,MAAM1K,KAAO,OAEbzzG,KAAKm+G,QAEVn+G,KAAKm+G,MAAM1K,KAAO,OAY9Bt2E,OAAOC,eAAe8Z,EAAO++D,MAAM71G,UAAW,WAE1C2Q,IAAK,WAED,QAAQ/Q,KAAU,SAAMA,KAAKm+G,MAAM3rC,QAAUxyE,KAAKm+G,MAAMunF,UAMhExuJ,EAAO++D,MAAM71G,UAAUuK,YAAcusC,EAAO++D,WAWpB32F,IAApBk1B,KAAK2G,aAEL3G,KAAK2G,WAAajE,EAAOiE,iBAGL77B,IAApBk1B,KAAKC,aAELD,KAAKC,WAAayC,EAAOzC,iBAGKn1B,IAA9Bk1B,KAAK2K,QAAQC,eAEb5K,KAAK2K,QAAQC,aAAe,IAAI5K,KAAK2K,QAAQ,IAAI3K,KAAKwmB,mBAGnB17C,IAAnCk1B,KAAKgC,cAAc6C,cAEnB7E,KAAKgC,cAAc6C,YAAc,IAAInC,EAAOC,QAGhD3C,KAAKinB,mBAAoB,EAGzBjnB,KAAKwxJ,0BAA4B,WAC7B,OAAO9uJ,EAAOgvC,OAAOnrB,gBASE,oBAAZn/D,SACe,oBAAXC,QAA0BA,OAAOD,UACxCA,QAAUC,OAAOD,QAAUs7C,GAE/Bt7C,QAAQs7C,OAASA,GACQ,oBAAXglB,QAA0BA,OAAOC,IAC/CD,OAAO,SAA+B3vB,EAAK2K,OAASA,GAEpD3K,EAAK2K,OAASA,EAGXA,GACRr6C,KAAKmD","file":"phaser.min.js"} \ No newline at end of file diff --git a/Iteration Sequence 2.2/js/phaser.min.js b/Iteration Sequence 2.2/js/phaser.min.js new file mode 100644 index 000000000..6eb048b7a --- /dev/null +++ b/Iteration Sequence 2.2/js/phaser.min.js @@ -0,0 +1,4 @@ +/* Phaser v2.10.0 - http://phaser.io - @photonstorm - (c) 2016 Photon Storm Ltd. */ + +!function(t){if("object"==typeof exports)module.exports=t();else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.p2=t()}}(function(){return function t(e,i,s){function n(o,a){if(!i[o]){if(!e[o]){var h="function"==typeof require&&require;if(!a&&h)return h(o,!0);if(r)return r(o,!0);throw new Error("Cannot find module '"+o+"'")}var l=i[o]={exports:{}};e[o][0].call(l.exports,function(t){var i=e[o][1][t];return n(i||t)},l,l.exports,t,e,i,s)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;se[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;ia)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var T=0;Tm&&(m+=this.vertices.length),g=Number.MAX_VALUE,m3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e) (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.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.1"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;ca[f]&&(a[f]=u[f]),u[f]i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle");var n=t("../collision/Broadphase");t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;az&&Y0)for(G=0;GMath.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=x,f=b,g=_,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var w=r.vertices[y];if(o.rotate(p,w,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var T=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(T.normalA,f);var P=l(g,T.normalA);o.scale(g,T.normalA,P),a(T.contactPointB,p,n.position),a(T.contactPointA,p,g),a(T.contactPointA,T.contactPointA,t.position),this.contactEquations.push(T),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(T))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=x,p=b;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=x;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,w=u;w=w||0;var T=x,P=b,C=_;a(T,g,y),o.rotate(P,v,w);var S=l(P,T);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,P),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,T,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=x,m=b,y=_,v=w,P=T,E=C,M=S,R=A,L=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(M,u,i),l(g,M)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),I=s.getClosestEdge(c,d,g);if(-1===B||-1===I)return 0;for(var O=0;O<2;O++){var k=B,F=I,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===O){var q;q=k,k=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H=3){if(p)return!0;var Z=this.createContactEquation(j,V,D,U);L++;var J=D.vertices[k%D.vertices.length],Q=D.vertices[(k+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(P,v,y),o.rotate90cw(Z.normalA,P),o.normalize(Z.normalA,Z.normalA),a(M,m,y);var $=l(Z.normalA,M);o.scale(E,Z.normalA,$),a(Z.contactPointA,m,G),a(Z.contactPointA,Z.contactPointA,E),h(Z.contactPointA,Z.contactPointA,G),a(Z.contactPointA,Z.contactPointA,j.position),a(Z.contactPointB,m,N),h(Z.contactPointB,Z.contactPointB,N),a(Z.contactPointB,Z.contactPointB,V.position),this.contactEquations.push(Z),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Z))}}}return this.enableFrictionReduction&&this.enableFriction&&L&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;dh)&&(h=a),(null===c||ah){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,x=nt;if(t instanceof y&&n instanceof y)for(P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(C=0;2!==C;C++){0===C?o.set(m,0,1):1===C&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0),u=(S=T[0]-w[1])<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(var C=0;C!==b.vertices.length;C++){o.rotate(f,b.vertices[C],_),o.rotate(g,b.vertices[(C+1)%b.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0);var S=T[0]-w[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,x=pt,b=ct,_=ut,w=Math.floor((i[0]-d-l[0])/f),T=Math.ceil((i[0]+d-l[0])/f);w<0&&(w=0),T>=p.length&&(T=p.length-1);for(var P=p[w],C=p[T],S=w;SP&&(P=p[S]);if(i[1]-d>P)return!u&&0;for(var A=!1,S=w;S=b[0]&&m[0]<_[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,x,-E),o.add(y,m,g),o.copy(v,x);M=this.createContactEquation(n,t,r,e);o.copy(M.normalA,v),o.scale(M.contactPointB,M.normalA,-d),h(M.contactPointB,M.contactPointB,i),a(M.contactPointB,M.contactPointB,t.position),o.copy(M.contactPointA,y),o.sub(M.contactPointA,M.contactPointA,n.position),this.contactEquations.push(M),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(M))}}if(A=!1,d>0)for(S=w;S<=T;S++)if(o.set(b,S*f,p[S]),o.add(b,b,l),o.sub(g,i,b),o.squaredLength(g)=c.length&&(y=c.length-1);for(var v=c[m],x=c[y],b=m;bv&&(v=c[b]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var _=0,b=m;b=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;ne.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){this.from,this.to;var o=this._currentShape,a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;cthis.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.positioni?(a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n)):-1!==(b=t.indexOf(n))&&t.splice(b,1),this.lowerLimitEnabled&&va?(f.angle=a,-1===n.indexOf(f)&&n.push(f)):-1!==(y=n.indexOf(f))&&n.splice(y,1),this.lowerLimitEnabled&&m>1;if(e<3)return[];for(var i=[],n=[],r=0;r3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,x=1/(f*y-g*g),b=(y*m-g*v)*x,_=(f*v-g*m)*x;return b>=0&&_>=0&&b+_<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;ei&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),x=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||x;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(h=this.shapes.length;h>=0;--h)this.removeShape(this.shapes[h]);var i=new r.Polygon;if(i.vertices=t,i.makeCCW(),"number"==typeof e.removeCollinearPoints&&i.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!i.isSimple())return!1;this.concavePath=i.vertices.slice(0);for(h=0;h=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var T=n.create(),P=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(T,i,t*e),n.multiply(T,this.massMultiplier,T),n.add(r,T,r),this.integrateToTimeOfImpact(t)||(n.scale(P,r,t),n.add(s,s,P),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),M=n.create(),R=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)=l&&h=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var b=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),w=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),T=Math.pow(_,2)-4*b*w;if(!(T<0))if(0===T){if(r.lerp(d,n,o,T),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}else{var P=Math.sqrt(T),C=1/(2*b),S=(-_-P)*C,A=(-_+P)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,x=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;x>=0&&x<=1&&(r.lerp(f,n,h,x),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,x,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;in)&&(n=s),(null===o||sn){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;ee&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),nv){var x=y;y=v,v=x}for(var b=0;b=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,_,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};r.create();var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){(t=t||{}).type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){(t=t||{}).type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=t.lowerBound,a=t.upperBound;n(o,-1e7,-1e7),n(a,1e7,1e7),0===s?a[1]=0:s===Math.PI/2?o[0]=0:s===Math.PI?o[1]=0:s===3*Math.PI/2&&(a[0]=0)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}t("../utils/Utils");var n=t("../events/EventEmitter");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){this.overlappingShapesLastState;var n=this.overlappingShapesCurrentState;if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var s=t,n=e;(i=i||[]).length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;)(n=i.getByKey(i.keys[s]))&&e.push(n.bodyA,n.bodyB);return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s=t&&s=0;T-=2)for(S=b.length-2;S>=0;S-=2)(w[T]===b[S]&&w[T+1]===b[S+1]||w[T+1]===b[S]&&w[T]===b[S+1])&&b.splice(S,2);q=u.length;for(T=0;T!==q;T++){var C=u[T];if(!C.collideConnected)for(var S=b.length-2;S>=0;S-=2)(C.bodyA===b[S]&&C.bodyB===b[S+1]||C.bodyB===b[S]&&C.bodyA===b[S+1])&&b.splice(S,2)}this.postBroadphaseEvent.pairs=b,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var T=0,A=b.length;T!==A;T+=2)for(var E=b[T],M=b[T+1],R=0,L=E.shapes.length;R!==L;R++)for(var B=E.shapes[R],I=B.position,O=B.angle,k=0,F=M.shapes.length;k!==F;k++){var D=M.shapes[k],U=D.position,G=D.angle,N=this.defaultContactMaterial;if(B.material&&D.material){var X=this.getContactMaterial(B.material,D.material);X&&(N=X)}this.runNarrowphase(c,E,B,I,O,M,D,U,G,N,this.frictionGravity)}for(T=0;T!==h;T++)(H=n[T])._wakeUpAfterNarrowphase&&(H.wakeUp(),H._wakeUpAfterNarrowphase=!1);if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(P);for(var W=this.endContactEvent,k=P.length;k--;){var j=P[k];W.shapeA=j.shapeA,W.shapeB=j.shapeB,W.bodyA=j.bodyA,W.bodyB=j.bodyB,this.emit(W)}P.length=0}var V=this.preSolveEvent;V.contactEquations=c.contactEquations,V.frictionEquations=c.frictionEquations,this.emit(V),V.contactEquations=V.frictionEquations=null;var q=u.length;for(T=0;T!==q;T++)u[T].update();if(c.contactEquations.length||c.frictionEquations.length||q)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),T=0;T!==q;T++)v.appendArray(g.equations,u[T].equations);g.split(this);for(T=0;T!==g.islands.length;T++)(K=g.islands[T]).equations.length&&a.solveIsland(t,K)}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),T=0;T!==q;T++)a.addEquations(u[T].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(T=0;T!==h;T++){var H=n[T];H.integrate(t)}for(T=0;T!==h;T++)n[T].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var Y=this.impactEvent,T=0;T!==c.contactEquations.length;T++){var z=c.contactEquations[T];z.firstImpact&&(Y.bodyA=z.bodyA,Y.bodyB=z.bodyB,Y.shapeA=z.shapeA,Y.shapeB=z.shapeB,Y.contactEquation=z,this.emit(Y))}if(this.sleepMode===s.BODY_SLEEPING)for(T=0;T!==h;T++)n[T].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(T=0;T!==h;T++)n[T].sleepTick(this.time,!0,t);for(T=0;T0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,x=t.frictionEquations.length;y=i.type=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0),o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC&&r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0),this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var _=this.beginContactEvent;if(_.shapeA=i,_.shapeB=a,_.bodyA=e,_.bodyB=o,_.contactEquations.length=0,"number"==typeof y)for(P=t.contactEquations.length-y;P1)for(var P=t.frictionEquations.length-b;P=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var x=e[y],b=0,_=x.shapes.length;b!==_;b++){var w=x.shapes[b];r.rotate(p,w.position,x.angle),r.add(p,p,x.position);var T=w.angle+x.angle;(w instanceof o&&g.circleParticle(x,w,p,T,s,n,u,0,!0)||w instanceof a&&g.particleConvex(s,n,u,0,x,w,p,T,!0)||w instanceof h&&g.particlePlane(s,n,u,0,x,w,p,T,!0)||w instanceof l&&g.particleCapsule(s,n,u,0,x,w,p,T,!0)||w instanceof c&&r.squaredLength(r.sub(f,p,t))0?Math.acos(i/u):-Math.acos(i/u),this.worldScale.x=u,this.worldScale.y=c/u}else if(n||r){var d=Math.sqrt(n*n+r*r);this.worldRotation=Phaser.Math.HALF_PI-(r>0?Math.acos(-n/d):-Math.acos(n/d)),this.worldScale.x=c/d,this.worldScale.y=d}else this.worldScale.x=0,this.worldScale.y=0;return this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.x=l.tx,this.worldPosition.y=l.ty,this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,l,h),this},preUpdate:function(){},generateTexture:function(t,e,i){var n=this.getLocalBounds(),r=new Phaser.RenderTexture(this.game,0|n.width,0|n.height,i,e,t);return s.DisplayObject._tempMatrix.tx=-n.x,s.DisplayObject._tempMatrix.ty=-n.y,r.render(this,s.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?s.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):s.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=0;this.texture&&this.texture.baseTexture&&s._enableMultiTextureToggle&&(e=this.texture.baseTexture.textureIndex);var i=new Phaser.RenderTexture(this.game,t.width,t.height,void 0,void 0,void 0,void 0,e);this._cachedSprite=new s.Sprite(i),this._cachedSprite.worldTransform=this.worldTransform}var n=this._filters;this._filters=null,this._cachedSprite.filters=n,s.DisplayObject._tempMatrix.tx=-t.x,s.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,s.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=n,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},s.DisplayObject.prototype.displayObjectUpdateTransform=s.DisplayObject.prototype.updateTransform,Object.defineProperties(s.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],i=0;i=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},s.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},s.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},s.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},s.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},s.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},s.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},s.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(t,i),n=0;na?u:a,d=d>h?d:h);var f=this._bounds;if(!p){var g=(f=new s.Rectangle).x,m=f.width+f.x,y=f.y,v=f.height+f.y,x=this.worldTransform,b=x.a,_=x.b,w=x.c,T=x.d,P=x.tx,C=x.ty,S=b*m+w*v+P,A=T*v+_*m+C,E=b*g+w*v+P,M=T*v+_*g+C,R=b*g+w*y+P,L=T*y+_*g+C,B=b*m+w*y+P,I=T*y+_*m+C;u=S,d=A,c=A,l=B<(l=R<(l=E<(l=S)?E:l)?R:l)?B:l,c=I<(c=L<(c=M(u=R>(u=E>u?E:u)?R:u)?B:u,d=I>(d=L>(d=M>d?M:d)?L:d)?I:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n(f=T>(f=_>(f=x>f?x:f)?_:f)?T:f)?C:f,g=S>(g=P>(g=w>(g=b>g?b:g)?w:g)?P:g)?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},s.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=Phaser.identityMatrix;for(var e=0;e= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}","}"];var n=s.compileProgram(t,this.vertexSrc||s.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(n),this.uSamplerArray=t.getUniformLocation(n,"uSamplerArray[0]"),this.projectionVector=t.getUniformLocation(n,"projectionVector"),this.offsetVector=t.getUniformLocation(n,"offsetVector"),this.dimensions=t.getUniformLocation(n,"dimensions"),this.aVertexPosition=t.getAttribLocation(n,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(n,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(n,"aColor"),this.aTextureIndex=t.getAttribLocation(n,"aTextureIndex");var r=[],o=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var a=0;a 0.0) gl_Position = vec4(0.0);"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);"," vTextureIndex = aTextureIndex;","}"],s.PixiFastShader=function(t){if(this._UID=Phaser._UID++,this.gl=t,this.program=null,s._enableMultiTextureToggle){var t=this.gl;this.MAX_TEXTURES=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(var e="\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n",i=1;i= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["// PixiFastShader Fragment Shader.","precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;","}"];this.vertexSrc=["// PixiFastShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","attribute float aTextureIndex;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;"," vColor = aColor;","}"],this.textureCount=0,this.init()},s.PixiFastShader.prototype.constructor=s.PixiFastShader,s.PixiFastShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["//StripShader Fragment Shader.","precision mediump float;","varying vec2 vTextureCoord;","varying float vTextureIndex;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord);","}"];this.vertexSrc=["//StripShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aTextureIndex;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;","}"],this.init()},s.StripShader.prototype.constructor=s.StripShader,s.StripShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t},i=this.gl,n=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),r=i.getParameter(i.MAX_TEXTURE_SIZE),o=this.game.cache._cache.image,a=null,h=0;h=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var a=i._uvs;if(a){var h,l,c,u,d=t.anchor.x,p=t.anchor.y;if(i.trim){var f=i.trim;h=(l=f.x-d*f.width)+i.crop.width,c=(u=f.y-p*f.height)+i.crop.height}else h=i.frame.width*(1-d),l=i.frame.width*-d,c=i.frame.height*(1-p),u=i.frame.height*-p;var g=this.currentBatchSize*this.vertexSize,m=(this.currentBatchSize,i.baseTexture.resolution),y=i.baseTexture.textureIndex,v=o.a/m,x=o.b/m,b=o.c/m,_=o.d/m,w=o.tx,T=o.ty,P=(i.crop.width,i.crop.height);if(i.rotated){var C=o.a,S=o.b,A=o.c,E=o.d,M=l,R=h;w=o.c*P+w,T=o.d*P+T,v=6.123233995736766e-17*C-A,x=6.123233995736766e-17*S-E,b=C+6.123233995736766e-17*A,_=S+6.123233995736766e-17*E,i._updateUvsInverted(),h=c,l=u,c=R,u=M}var L=this.colors,B=this.positions,I=t.tint,O=(I>>16)+(65280&I)+((255&I)<<16)+(255*t.worldAlpha<<24);this.renderSession.roundPixels?(B[g++]=v*l+b*u+w|0,B[g++]=_*u+x*l+T|0,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w|0,B[g++]=_*u+x*h+T|0,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w|0,B[g++]=_*c+x*h+T|0,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w|0,B[g++]=_*c+x*l+T|0,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y):(B[g++]=v*l+b*u+w,B[g++]=_*u+x*l+T,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w,B[g++]=_*u+x*h+T,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w,B[g++]=_*c+x*h+T,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w,B[g++]=_*c+x*l+T,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y),this.sprites[this.currentBatchSize++]=t}},s.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture,i=e.baseTexture,n=this.gl,r=t.texture.baseTexture.textureIndex;s.WebGLRenderer.textureArray[r]!=i&&(this.flush(),n.activeTexture(n.TEXTURE0+r),n.bindTexture(n.TEXTURE_2D,i._glTextures[n.id]),s.WebGLRenderer.textureArray[r]=i),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new s.TextureUvs);var o=t._uvs,a=e.baseTexture.width,h=e.baseTexture.height;t.tilePosition.x%=a*t.tileScaleOffset.x,t.tilePosition.y%=h*t.tileScaleOffset.y;var l=t.tilePosition.x/(a*t.tileScaleOffset.x),c=t.tilePosition.y/(h*t.tileScaleOffset.y),u=t.width/a/(t.tileScale.x*t.tileScaleOffset.x),d=t.height/h/(t.tileScale.y*t.tileScaleOffset.y);o.x0=0-l,o.y0=0-c,o.x1=1*u-l,o.y1=0-c,o.x2=1*u-l,o.y2=1*d-c,o.x3=0-l,o.y3=1*d-c;var p=t.tint,f=(p>>16)+(65280&p)+((255&p)<<16)+(255*t.worldAlpha<<24),g=this.positions,m=this.colors,y=t.width,v=t.height,x=t.anchor.x,b=t.anchor.y,_=y*(1-x),w=y*-x,T=v*(1-b),P=v*-b,C=this.currentBatchSize*this.vertexSize,S=e.baseTexture.resolution,A=t.worldTransform,E=A.a/S,M=A.b/S,R=A.c/S,L=A.d/S,B=A.tx,I=A.ty;g[C++]=E*w+R*P+B,g[C++]=L*P+M*w+I,g[C++]=o.x0,g[C++]=o.y0,m[C++]=f,g[C++]=r,g[C++]=E*_+R*P+B,g[C++]=L*P+M*_+I,g[C++]=o.x1,g[C++]=o.y1,m[C++]=f,g[C++]=r,g[C++]=E*_+R*T+B,g[C++]=L*T+M*_+I,g[C++]=o.x2,g[C++]=o.y2,m[C++]=f,g[C++]=r,g[C++]=E*w+R*T+B,g[C++]=L*T+M*w+I,g[C++]=o.x3,g[C++]=o.y3,m[C++]=f,g[C++]=r,this.sprites[this.currentBatchSize++]=t},s.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,t=this.defaultShader.shaders[e.id],e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var i=this.vertexSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,i,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,i,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,i,16),e.vertexAttribPointer(t.aTextureIndex,1,e.FLOAT,!1,i,20)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);var n=this.positions.subarray(0,this.currentBatchSize*this.vertexSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m0&&(v=!1),(f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){(t=(p=a).shaders[e.id])||((t=new s.PixiShader(e)).fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var x=this.renderSession.projection;e.uniform2f(t.projectionVector,x.x,x.y);var b=this.renderSession.offset;e.uniform2f(t.offsetVector,b.x,b.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},s.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},s.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},s.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},s.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},s.WebGLFastSpriteBatch=function(t){this.vertSize=11,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,i=6*this.maxSize;this.vertices=new Float32Array(e),this.indices=new Uint16Array(i),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var s=0,n=0;s=this.size&&this.flush()}},s.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]){if(this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}else this.renderSession.renderer.updateTexture(this.currentBaseTexture,t)}},s.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},s.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36),t.vertexAttribPointer(this.shader.aTextureIndex,1,t.FLOAT,!1,i,40)},s.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},s.WebGLFilterManager.prototype.constructor=s.WebGLFilterManager,s.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},s.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},s.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,i=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new s.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),i.x=a.width/2,i.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},s.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),i=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,i.width*this.renderSession.resolution,i.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=i.height,this.vertexArray[2]=i.width,this.vertexArray[3]=i.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=i.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=i.width/this.width,this.uvArray[5]=i.height/this.height,this.uvArray[6]=i.width/this.width,this.uvArray[7]=i.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,i,p,f),this.texturePool.push(n),e._glFilterTexture=null},s.WebGLFilterManager.prototype.applyFilterPass=function(t,e,i,n){var r=this.gl,o=t.shaders[r.id];o||((o=new s.PixiShader(r)).fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(!0),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,i/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},s.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},s.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e=0;t--){var e=this._glTextures[t],i=s.glContexts[t];i&&e&&i.deleteTexture(e)}this._glTextures.length=0,this.dirty()},s.BaseTexture.fromCanvas=function(t,e,i){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),i=i||1,new s.BaseTexture(t,e,i)},s.TextureSilentFail=!1,s.Texture=function(t,e,i,n){this.noFrame=!1,e||(this.noFrame=!0,e=new s.Rectangle(0,0,1,1)),t instanceof s.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=i||new s.Rectangle(0,0,1,1),this.rotated=!1,t.hasLoaded&&(this.noFrame&&(e=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},s.Texture.prototype.constructor=s.Texture,s.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},s.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},s.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,this.trim||!(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height))this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs();else{if(!s.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=!1}},s.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/i},s.Texture.prototype._updateUvsInverted=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.height)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.height)/e,this._uvs.y2=(t.y+t.width)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.width)/i},s.Texture.fromCanvas=function(t,e){var i=s.BaseTexture.fromCanvas(t,e);return new s.Texture(i)},s.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=s),exports.PIXI=s):"undefined"!=typeof define&&define.amd?define("PIXI",i.PIXI=s):i.PIXI=s,s}.call(this),function(){function t(t,e){this._scaleFactor=t,this._deltaMode=e,this.originalEvent=null}var e=this,i=i||{VERSION:"2.10.0",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,WEBGL_MULTI:4,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,PENDING_ATLAS:-1,HORIZONTAL:0,VERTICAL:1,LANDSCAPE:0,PORTRAIT:1,ANGLE_UP:270,ANGLE_DOWN:90,ANGLE_LEFT:180,ANGLE_RIGHT:0,ANGLE_NORTH_EAST:315,ANGLE_NORTH_WEST:225,ANGLE_SOUTH_EAST:45,ANGLE_SOUTH_WEST:135,TOP_LEFT:0,TOP_CENTER:1,TOP_RIGHT:2,LEFT_TOP:3,LEFT_CENTER:4,LEFT_BOTTOM:5,CENTER:6,RIGHT_TOP:7,RIGHT_CENTER:8,RIGHT_BOTTOM:9,BOTTOM_LEFT:10,BOTTOM_CENTER:11,BOTTOM_RIGHT:12,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},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{},_UID:0};if(Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Function.prototype.bind||(Function.prototype.bind=function(){var t=Array.prototype.slice;return function(e){function i(){var r=n.concat(t.call(arguments));s.apply(this instanceof i?this:e,r)}var s=this,n=t.call(arguments,1);if("function"!=typeof s)throw new TypeError;return i.prototype=function t(e){if(e&&(t.prototype=e),!(this instanceof t))return new t}(s.prototype),i}}()),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var s=arguments.length>=2?arguments[1]:void 0,n=0;n0&&100*Math.random()<=t},randomChoice:function(t,e){return Math.random()<.5?t:e},parseDimension:function(t,e){var i=0,s=0;return"string"==typeof t?"%"===t.substr(-1)?(i=parseInt(t,10)/100,s=0===e?window.innerWidth*i:window.innerHeight*i):s=parseInt(t,10):s=t,s},pad:function(t,e,i,s){if(void 0===e)var e=0;if(void 0===i)var i=" ";if(void 0===s)var s=3;var n=0;if(e+1>=(t=t.toString()).length)switch(s){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((n=e-t.length)/2),o=n-r;t=new Array(o+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t},isPlainObject:function(t){if("object"!=typeof t||t.nodeType||t===t.window)return!1;try{if(t.constructor&&!{}.hasOwnProperty.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},extend:function(){var t,e,s,n,r,o,a=arguments[0]||{},h=1,l=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[1]||{},h=2),l===h&&(a=this,--h);h0&&(this._radius=.5*s),this.type=i.CIRCLE},i.Circle.prototype={circumference:function(){return Math.PI*this._radius*2},random:function(t){void 0===t&&(t=new i.Point);var e=2*Math.PI*Math.random(),s=Math.random()+Math.random(),n=s>1?2-s:s,r=n*Math.cos(e),o=n*Math.sin(e);return t.x=this.x+r*this.radius,t.y=this.y+o*this.radius,t},getBounds:function(){return new i.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(t,e,i){return this.x=t,this.y=e,this._diameter=i,this._radius=.5*i,this},copyFrom:function(t){return this.setTo(t.x,t.y,t.diameter)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.diameter=this._diameter,t},distance:function(t,e){var s=i.Math.distance(this.x,this.y,t.x,t.y);return e?Math.round(s):s},clone:function(t){return void 0===t||null===t?t=new i.Circle(this.x,this.y,this.diameter):t.setTo(this.x,this.y,this.diameter),t},contains:function(t,e){return i.Circle.contains(this,t,e)},circumferencePoint:function(t,e,s){return i.Circle.circumferencePoint(this,t,e,s)},sample:function(t,e,s,n,r){t||(t=60),null==e&&(e=0),null==s&&(s=i.Math.PI2),r||(r=[]);for(var o=0;o0&&(this._diameter=t,this._radius=.5*t)}}),Object.defineProperty(i.Circle.prototype,"radius",{get:function(){return this._radius},set:function(t){t>0&&(this._radius=t,this._diameter=2*t)}}),Object.defineProperty(i.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(t){t>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-t}}),Object.defineProperty(i.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(t){tthis.y?(this._radius=0,this._diameter=0):this.radius=this.y-t}}),Object.defineProperty(i.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(t){t0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(i.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(t){!0===t&&this.setTo(0,0,0)}}),i.Circle.contains=function(t,e,i){return t.radius>0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius},i.Circle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.diameter===e.diameter},i.Circle.intersects=function(t,e){return i.Math.distance(t.x,t.y,e.x,e.y)<=t.radius+e.radius},i.Circle.circumferencePoint=function(t,e,s,n){return void 0===s&&(s=!1),void 0===n&&(n=new i.Point),!0===s&&(e=i.Math.degToRad(e)),n.x=t.x+t.radius*Math.cos(e),n.y=t.y+t.radius*Math.sin(e),n},i.Circle.intersectsRectangle=function(t,e){var i=Math.abs(t.x-e.x-e.halfWidth);if(i>e.halfWidth+t.radius)return!1;var s=Math.abs(t.y-e.y-e.halfHeight);if(s>e.halfHeight+t.radius)return!1;if(i<=e.halfWidth||s<=e.halfHeight)return!0;var n=i-e.halfWidth,r=s-e.halfHeight;return n*n+r*r<=t.radius*t.radius},i.Circle.intersectsLine=function(t,e,s){var n=t.x,r=t.y,o=(e.end.y-e.start.y)/(e.end.x-e.start.x),a=e.end.y-o*e.end.x,h=t.radius,l=t.radius,c=a+o*n,u=(n*(l*l)-o*(h*h)*(a-r)+h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),d=(n*(l*l)-o*(h*h)*(a-r)-h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),p=o*u+a,f=o*d+a,g=new i.Point(u,p),m=new i.Point(d,f),y=e.pointOnSegment(g.x,g.y,.01),v=e.pointOnSegment(m.x,m.y,.01);return y&&v?!s||[g,m]:y?!s||[g]:v?!s||[m]:!!s&&[]},PIXI.Circle=i.Circle,i.Ellipse=function(t,e,s,n){t=t||0,e=e||0,s=s||0,n=n||0,this.x=t,this.y=e,this.width=s,this.height=n,this.type=i.ELLIPSE},i.Ellipse.prototype={setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},getBounds:function(){return new i.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},clone:function(t){return void 0===t||null===t?t=new i.Ellipse(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t},contains:function(t,e){return i.Ellipse.contains(this,t,e)},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random()*Math.PI*2,s=Math.random();return t.x=Math.sqrt(s)*Math.cos(e),t.y=Math.sqrt(s)*Math.sin(e),t.x=this.x+t.x*this.width/2,t.y=this.y+t.y*this.height/2,t},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},i.Ellipse.prototype.constructor=i.Ellipse,Object.defineProperty(i.Ellipse.prototype,"left",{get:function(){return this.x},set:function(t){this.x=t}}),Object.defineProperty(i.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t=s&&t<=n&&e>=r&&e<=o},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random();return t.x=this.start.x+e*(this.end.x-this.start.x),t.y=this.start.y+e*(this.end.y-this.start.y),t},coordinatesOnLine:function(t,e){void 0===t&&(t=1),void 0===e&&(e=[]);var i=Math.round(this.start.x),s=Math.round(this.start.y),n=Math.round(this.end.x),r=Math.round(this.end.y),o=Math.abs(n-i),a=Math.abs(r-s),h=i-a&&(c-=a,i+=h),d=0&&g<=1&&m>=0&&m<=1?o:null}return o},i.Line.intersects=function(t,e,s,n){return i.Line.intersectsPoints(t.start,t.end,e.start,e.end,s,n)},i.Line.intersectsRectangle=function(t,e){if(0===t.length||e.empty)return!1;var i=t.start.x,s=t.start.y,n=t.end.x,r=t.end.y,o=e.x,a=e.y,h=e.right,l=e.bottom,c=0;if(i>=o&&i<=h&&s>=a&&s<=l||n>=o&&n<=h&&r>=a&&r<=l)return!0;if(i=o){if((c=s+(r-s)*(o-i)/(n-i))>a&&c<=l)return!0}else if(i>h&&n<=h&&(c=s+(r-s)*(h-i)/(n-i))>=a&&c<=l)return!0;if(s=a){if((c=i+(n-i)*(a-s)/(r-s))>=o&&c<=h)return!0}else if(s>l&&r<=l&&(c=i+(n-i)*(l-s)/(r-s))>=o&&c<=h)return!0;return!1},i.Line.intersectionWithRectangle=function(t,e,s){var n=i.Line.intersectionWithRectangle;s||(s=new i.Point),n.edges||(n.edges=[new i.Line,new i.Line,new i.Line,new i.Line]),n.edgeIntersection||(n.edgeIntersection=new i.Point);var r=n.edges,o=n.edgeIntersection.set(0),a=e.x,h=e.y,l=e.right,c=e.bottom,u=1/0;r[0].setTo(a,h,l,h),r[1].setTo(a,c,l,c),r[2].setTo(a,h,a,c),r[3].setTo(l,h,l,c);for(var d,p=0;d=r[p];p++)if(t.intersects(d,!0,o)){var f=t.start.distance(o);fs&&(this.x=s),this.yn&&(this.y=n),this},clone:function(t){return void 0===t||null===t?t=new i.Point(this.x,this.y):t.setTo(this.x,this.y),t},copyTo:function(t){return t.x=this.x,t.y=this.y,t},distance:function(t,e){return i.Point.distance(this,t,e)},equals:function(t){return t.x===this.x&&t.y===this.y},equalsXY:function(t,e){return this.x===t&&this.y===e},fuzzyEquals:function(t,e){return i.Point.fuzzyEquals(this,t,e)},fuzzyEqualsXY:function(t,e,s){return i.Point.fuzzyEqualsXY(this,t,e,s)},angle:function(t,e){return this.angleXY(t.x,t.y,e)},angleXY:function(t,e,s){var n=Math.atan2(e-this.y,t-this.x);return s?i.Math.radToDeg(n):n},atan:function(t){var e=Math.atan2(this.y,this.x);return t?i.Math.radToDeg(e):e},rotate:function(t,e,s,n,r){return i.Point.rotate(this,t,e,s,n,r)},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(t){return this.normalize().multiply(t,t)},normalize:function(){if(!this.isZero()){var t=this.getMagnitude();this.x/=t,this.y/=t}return this},limit:function(t){return this.getMagnitudeSq()>t*t&&this.setMagnitude(t),this},expand:function(t){return this.getMagnitudeSq()=0&&e.x-i<0)return-1;if(t.x-i<0&&e.x-i>=0)return 1;if(t.x-i==0&&e.x-i==0)return t.y-s>=0||e.y-s>=0?t.y>e.y?1:-1:e.y>t.y?1:-1;var n=(t.x-i)*-(e.y-s)-(e.x-i)*-(t.y-s);return n<0?-1:n>0?1:(t.x-i)*(t.x-i)+(t.y-s)*(t.y-s)>(e.x-i)*(e.x-i)+(e.y-s)*(e.y-s)?-1:1})},PIXI.Point=i.Point,i.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.flattened=!1,this.type=i.POLYGON},i.Polygon.prototype={toNumberArray:function(t){void 0===t&&(t=[]);for(var e=0;e0){Array.isArray(t)||(t=Array.prototype.slice.call(arguments));for(var e=Number.MAX_VALUE,i=0,s=t.length;i=this.right?this.width=0:this.width=this.right-t,this.x=t}}),Object.defineProperty(i.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(i.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(i.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(i.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(t){this.x=t-this.halfWidth}}),Object.defineProperty(i.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(t){this.y=t-this.halfHeight}}),Object.defineProperty(i.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(i.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(i.Rectangle.prototype,"top",{get:function(){return this.y},set:function(t){t>=this.bottom?(this.height=0,this.y=t):this.height=this.bottom-t}}),Object.defineProperty(i.Rectangle.prototype,"topLeft",{get:function(){return new i.Point(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"topRight",{get:function(){return new i.Point(this.x+this.width,this.y)},set:function(t){this.right=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),i.Rectangle.prototype.constructor=i.Rectangle,i.Rectangle.inflate=function(t,e,i){return t.x-=e,t.width+=2*e,t.y-=i,t.height+=2*i,t},i.Rectangle.inflatePoint=function(t,e){return i.Rectangle.inflate(t,e.x,e.y)},i.Rectangle.size=function(t,e){return void 0===e||null===e?e=new i.Point(t.width,t.height):e.setTo(t.width,t.height),e},i.Rectangle.clone=function(t,e){return void 0===e||null===e?e=new i.Rectangle(t.x,t.y,t.width,t.height):e.setTo(t.x,t.y,t.width,t.height),e},i.Rectangle.createFromBounds=function(t,e){return void 0!==e&&null!==e||(e=new i.Rectangle(t.x,t.y,t.width,t.height)),e.copyFromBounds(t)},i.Rectangle.contains=function(t,e,i){return!(t.width<=0||t.height<=0)&&(e>=t.x&&e=t.y&&i=t&&n=e&&re.volume)&&(t.x>=e.x&&t.y>=e.y&&t.righte.right||t.y>e.bottom)},i.Rectangle.intersectsRaw=function(t,e,i,s,n,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||ns&&(s=t.x),t.xr&&(r=t.y),t.y=i&&t<=i+this.width){var s=this.y;if(e>=s&&e<=s+this.height)return!0}return!1}},i.RoundedRectangle.prototype.constructor=i.RoundedRectangle,PIXI.RoundedRectangle=i.RoundedRectangle,i.Camera=function(t,e,s,n,r,o){this.game=t,this.world=t.world,this.id=0,this.view=new i.Rectangle(s,n,r,o),this.bounds=new i.Rectangle(s,n,r,o),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this.lerp=new i.Point(1,1),this.onShakeComplete=new i.Signal,this.onFlashComplete=new i.Signal,this.onFadeComplete=new i.Signal,this.fx=null,this._targetPosition=new i.Point,this._edge=0,this._position=new i.Point,this._shake={intensity:0,duration:0,horizontal:!1,vertical:!1,shakeBounds:!0,x:0,y:0},this._fxDuration=0,this._fxType=0,this._fixedView=new i.Rectangle},i.Camera.FOLLOW_LOCKON=0,i.Camera.FOLLOW_PLATFORMER=1,i.Camera.FOLLOW_TOPDOWN=2,i.Camera.FOLLOW_TOPDOWN_TIGHT=3,i.Camera.SHAKE_BOTH=4,i.Camera.SHAKE_HORIZONTAL=5,i.Camera.SHAKE_VERTICAL=6,i.Camera.ENABLE_FX=!0,i.Camera.prototype={boot:function(){this.displayObject=this.game.world,this.scale=this.game.world.scale,this.game.camera=this,i.Graphics&&i.Camera.ENABLE_FX&&(this.fx=new i.Graphics(this.game),this.game.stage.addChild(this.fx))},preUpdate:function(){this.totalInView=0},follow:function(t,e,s,n){void 0===e&&(e=i.Camera.FOLLOW_LOCKON),void 0===s&&(s=1),void 0===n&&(n=1),this.target=t,this.lerp.set(s,n);var r;switch(e){case i.Camera.FOLLOW_PLATFORMER:var o=this.width/8,a=this.height/3;this.deadzone=new i.Rectangle((this.width-o)/2,(this.height-a)/2-.25*a,o,a);break;case i.Camera.FOLLOW_TOPDOWN:r=Math.max(this.width,this.height)/4,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_TOPDOWN_TIGHT:r=Math.max(this.width,this.height)/8,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_LOCKON:default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(t){this.setPosition(Math.round(t.x-this.view.halfWidth),Math.round(t.y-this.view.halfHeight))},focusOnXY:function(t,e){this.setPosition(Math.round(t-this.view.halfWidth),Math.round(e-this.view.halfHeight))},shake:function(t,e,s,n,r){return void 0===t&&(t=.05),void 0===e&&(e=500),void 0===s&&(s=!0),void 0===n&&(n=i.Camera.SHAKE_BOTH),void 0===r&&(r=!0),!(!s&&this._shake.duration>0)&&(this._shake.intensity=t,this._shake.duration=e,this._shake.shakeBounds=r,this._shake.x=0,this._shake.y=0,this._shake.horizontal=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_HORIZONTAL,this._shake.vertical=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_VERTICAL,!0)},flash:function(t,e,i,s){return void 0===t&&(t=16777215),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=1,this._fxDuration=e,this._fxType=0,!0)},fade:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=0,this._fxDuration=e,this._fxType=1,!0)},update:function(){this._fxDuration>0&&this.updateFX(),this._shake.duration>0&&this.updateShake(),this.bounds&&this.checkBounds(),this.roundPx&&(this.view.floor(),this._shake.x=Math.floor(this._shake.x),this._shake.y=Math.floor(this._shake.y)),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateFX:function(){0===this._fxType?(this.fx.alpha-=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha<=0&&(this._fxDuration=0,this.fx.alpha=0,this.onFlashComplete.dispatch())):(this.fx.alpha+=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha>=1&&(this._fxDuration=0,this.fx.alpha=1,this.onFadeComplete.dispatch()))},updateShake:function(){this._shake.duration-=this.game.time.elapsedMS,this._shake.duration<=0?(this.onShakeComplete.dispatch(),this._shake.x=0,this._shake.y=0):(this._shake.horizontal&&(this._shake.x=this.game.rnd.frac()*this._shake.intensity*this.view.width*2-this._shake.intensity*this.view.width),this._shake.vertical&&(this._shake.y=this.game.rnd.frac()*this._shake.intensity*this.view.height*2-this._shake.intensity*this.view.height))},updateTarget:function(){this._targetPosition.x=this.view.x+this.target.worldPosition.x,this._targetPosition.y=this.view.y+this.target.worldPosition.y,this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edgethis.deadzone.right&&(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.right,this.lerp.x)),this._edge=this._targetPosition.y-this.view.y,this._edgethis.deadzone.bottom&&(this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.bottom,this.lerp.y))):(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.view.halfWidth,this.lerp.x),this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.view.halfHeight,this.lerp.y)),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},setBoundsToWorld:function(){this.bounds&&this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1;var t=this.view.x+this._shake.x,e=this.view.right+this._shake.x,i=this.view.y+this._shake.y,s=this.view.bottom+this._shake.y;t<=this.bounds.x*this.scale.x?(this.atLimit.x=!0,this.view.x=this.bounds.x*this.scale.x,this._shake.shakeBounds||(this._shake.x=0)):e>=this.bounds.right*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.right*this.scale.x-this.width,this._shake.shakeBounds||(this._shake.x=0)),i<=this.bounds.top*this.scale.y?(this.atLimit.y=!0,this.view.y=this.bounds.top*this.scale.y,this._shake.shakeBounds||(this._shake.y=0)):s>=this.bounds.bottom*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom*this.scale.y-this.height,this._shake.shakeBounds||(this._shake.y=0))},setPosition:function(t,e){this.view.x=t,this.view.y=e,this.bounds&&this.checkBounds()},setSize:function(t,e){this.view.width=t,this.view.height=e},reset:function(){this.target=null,this.view.x=0,this.view.y=0,this._shake.duration=0,this._shake.x=0,this._shake.y=0,this.resetFX()},resetFX:function(){this.fx&&(this.fx.clear(),this.fx.alpha=0),this._fxDuration=0}},i.Camera.prototype.constructor=i.Camera,Object.defineProperty(i.Camera.prototype,"x",{get:function(){return this.view.x},set:function(t){this.view.x=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"y",{get:function(){return this.view.y},set:function(t){this.view.y=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"position",{get:function(){return this._position.set(this.view.x,this.view.y),this._position},set:function(t){void 0!==t.x&&(this.view.x=t.x),void 0!==t.y&&(this.view.y=t.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"width",{get:function(){return this.view.width},set:function(t){this.view.width=t}}),Object.defineProperty(i.Camera.prototype,"height",{get:function(){return this.view.height},set:function(t){this.view.height=t}}),Object.defineProperty(i.Camera.prototype,"shakeIntensity",{get:function(){return this._shake.intensity},set:function(t){this._shake.intensity=t}}),Object.defineProperty(i.Camera.prototype,"fixedView",{get:function(){return this._fixedView.setTo(0,0,this.view.width,this.view.height),this._fixedView}}),i.State=function(){this.game=null,this.key="",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.state=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},i.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},i.State.prototype.constructor=i.State,i.StateManager=function(t,e){this.game=t,this.states={},this._pendingState=null,void 0!==e&&null!==e&&(this._pendingState=e),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new i.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},i.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(t,e,s){void 0===s&&(s=!1);var n;return e instanceof i.State?n=e:"object"==typeof e?(n=e).game=this.game:"function"==typeof e&&(n=new e(this.game)),this.states[t]=n,s&&(this.game.isBooted?this.start(t):this._pendingState=t),n},remove:function(t){this.current===t&&(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.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[t]},start:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1),this.checkState(t)&&(this._pendingState=t,this._clearWorld=e,this._clearCache=i,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!1),this._pendingState=this.current,this._clearWorld=t,this._clearCache=e,arguments.length>2&&(this._args=Array.prototype.slice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var t=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,t),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache&&this.game.cache.destroy()))},checkState:function(t){var e=this.states[t];return e?!!(e.preload||e.create||e.update||e.render)||(console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"),!1):(console.warn("Phaser.StateManager - No state found with the key: "+t),!1)},link:function(t){var e=this.states[t];e.game=this.game,e.add=this.game.add,e.make=this.game.make,e.camera=this.game.camera,e.cache=this.game.cache,e.input=this.game.input,e.load=this.game.load,e.math=this.game.math,e.sound=this.game.sound,e.scale=this.game.scale,e.state=this,e.stage=this.game.stage,e.time=this.game.time,e.tweens=this.game.tweens,e.world=this.game.world,e.particles=this.game.particles,e.rnd=this.game.rnd,e.physics=this.game.physics,e.key=t},unlink:function(t){var e=this.states[t];e&&(e.game=null,e.add=null,e.make=null,e.camera=null,e.cache=null,e.input=null,e.load=null,e.math=null,e.sound=null,e.scale=null,e.state=null,e.stage=null,e.time=null,e.tweens=null,e.world=null,e.particles=null,e.rnd=null,e.physics=null)},setCurrentState:function(t){var e=this.states[t];this.callbackContext=e,this.link(t),this.onInitCallback=e.init||this.dummy,this.onPreloadCallback=e.preload||null,this.onLoadRenderCallback=e.loadRender||null,this.onLoadUpdateCallback=e.loadUpdate||null,this.onCreateCallback=e.create||null,this.onUpdateCallback=e.update||null,this.onPreRenderCallback=e.preRender||null,this.onRenderCallback=e.render||null,this.onResizeCallback=e.resize||null,this.onPausedCallback=e.paused||null,this.onResumedCallback=e.resumed||null,this.onPauseUpdateCallback=e.pauseUpdate||null,this.onShutDownCallback=e.shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=t,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),t===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){!1===this._created&&this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game),!1===this._created&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(t){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,t)},resize:function(t,e){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,t,e)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===i.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this._clearWorld=!0,this._clearCache=!0,this.clearCurrentState(),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,this.current=""}},i.StateManager.prototype.constructor=i.StateManager,Object.defineProperty(i.StateManager.prototype,"created",{get:function(){return this._created}}),i.Signal=function(){},i.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!1,validateListener:function(t,e){if("function"!=typeof t)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",e))},_registerListener:function(t,e,s,n,r){var o,a=this._indexOfListener(t,s);if(-1!==a){if((o=this._bindings[a]).isOnce()!==e)throw new Error("You cannot add"+(e?"":"Once")+"() then add"+(e?"Once":"")+"() the same listener without removing the relationship first.")}else o=new i.SignalBinding(this,t,e,s,n,r),this._addBinding(o);return this.memorize&&this._prevParams&&o.execute(this._prevParams),o},_addBinding:function(t){this._bindings||(this._bindings=[]);var e=this._bindings.length;do{e--}while(this._bindings[e]&&t._priority<=this._bindings[e]._priority);this._bindings.splice(e+1,0,t)},_indexOfListener:function(t,e){if(!this._bindings)return-1;void 0===e&&(e=null);for(var i,s=this._bindings.length;s--;)if((i=this._bindings[s])._listener===t&&i.context===e)return s;return-1},has:function(t,e){return-1!==this._indexOfListener(t,e)},add:function(t,e,i){this.validateListener(t,"add");var s=[];if(arguments.length>3)for(var n=3;n3)for(var n=3;n=this.children.length?-1:this.getChildAt(t)},i.Group.prototype.create=function(t,e,i,s,n,r){void 0===n&&(n=!0);var o=new this.classType(this.game,t,e,i,s);return o.exists=n,o.visible=n,o.alive=n,this.add(o,!1,r)},i.Group.prototype.createMultiple=function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=!1),Array.isArray(e)||(e=[e]),Array.isArray(i)||(i=[i]);var o=this,a=[];return e.forEach(function(e){i.forEach(function(i){for(var h=0;hthis.children.length||-1===t&&-1===e)return!1;for(var a=new i.Rectangle(0,0,s,n),h=t*s,l=e*n,c=o;cthis.children.length-1&&(t=0),this.cursor)return this.cursorIndex=t,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.next=function(){if(this.cursor)return this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.previous=function(){if(this.cursor)return 0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.swap=function(t,e){this.swapChildren(t,e),this.updateZ()},i.Group.prototype.bringToTop=function(t){return t.parent===this&&this.getIndex(t)0&&(this.remove(t,!1,!0),this.addAt(t,0,!0)),t},i.Group.prototype.moveUp=function(t){if(t.parent===this&&this.getIndex(t)0){var e=this.getIndex(t),i=this.getAt(e-1);i&&this.swap(t,i)}return t},i.Group.prototype.xy=function(t,e,i){if(t<0||t>this.children.length)return-1;this.getChildAt(t).x=e,this.getChildAt(t).y=i},i.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},i.Group.prototype.getIndex=function(t){return this.children.indexOf(t)},i.Group.prototype.getByName=function(t){for(var e=0;e0))return!1;var r=e.length;return 1===r?0===s?t[e[0]]=i:1===s?t[e[0]]+=i:2===s?t[e[0]]-=i:3===s?t[e[0]]*=i:4===s&&(t[e[0]]/=i):2===r?0===s?t[e[0]][e[1]]=i:1===s?t[e[0]][e[1]]+=i:2===s?t[e[0]][e[1]]-=i:3===s?t[e[0]][e[1]]*=i:4===s&&(t[e[0]][e[1]]/=i):3===r?0===s?t[e[0]][e[1]][e[2]]=i:1===s?t[e[0]][e[1]][e[2]]+=i:2===s?t[e[0]][e[1]][e[2]]-=i:3===s?t[e[0]][e[1]][e[2]]*=i:4===s&&(t[e[0]][e[1]][e[2]]/=i):4===r&&(0===s?t[e[0]][e[1]][e[2]][e[3]]=i:1===s?t[e[0]][e[1]][e[2]][e[3]]+=i:2===s?t[e[0]][e[1]][e[2]][e[3]]-=i:3===s?t[e[0]][e[1]][e[2]][e[3]]*=i:4===s&&(t[e[0]][e[1]][e[2]][e[3]]/=i)),!0},i.Group.prototype.checkProperty=function(t,e,s,n){if(void 0===n&&(n=!1),this!==t.parent)return!1;var r=i.Utils.getProperty(t,e);return!(void 0===r&&n||r!==s)},i.Group.prototype.set=function(t,e,i,s,n,r,o){if(void 0===o&&(o=!1),e=e.split("."),void 0===s&&(s=!1),void 0===n&&(n=!1),(!1===s||s&&t.alive)&&(!1===n||n&&t.visible))return this.setProperty(t,e,i,r,o)},i.Group.prototype.setAll=function(t,e,i,s,n,r){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===r&&(r=!1),t=t.split("."),n=n||0;for(var o=0;o2){i=[];for(s=2;s2){n=[];for(a=2;a=e&&(t=e-1);var i=this.children[t];this.updateOnlyExistingChildren&&!i.exists||i.update()}},i.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y);for(var t=0;t2){s=[null];for(var n=2;n2){s=[null];for(var n=2;n2){s=[null];for(var n=2;ne[this._sortProperty]?1:t.ze[this._sortProperty]?-1:0},i.Group.prototype.iterate=function(t,e,s,n,r,o){if(0===this.children.length){if(s===i.Group.RETURN_TOTAL)return 0;if(s===i.Group.RETURN_ALL)return[]}var a=0;if(s===i.Group.RETURN_ALL)var h=[];for(var l=0;l0)return this.children[this.children.length-1]},i.Group.prototype.getBottom=function(){if(this.children.length>0)return this.children[0]},i.Group.prototype.getClosestTo=function(t,e,s){for(var n=Number.MAX_VALUE,r=0,o=null,a=0;an&&(!e||e.call(s,h,r))&&(n=r,o=h)}return o},i.Group.prototype.count=function(t,e){return this.iterate(t,e,i.Group.RETURN_TOTAL)},i.Group.prototype.countLiving=function(){return this.count("alive",!0)},i.Group.prototype.countDead=function(){return this.count("alive",!1)},i.Group.prototype.getRandom=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.children.length),0===e?null:i.ArrayUtils.getRandomItem(this.children,t,e)},i.Group.prototype.getRandomExists=function(t,e){var i=this.getAll("exists",!0,t,e);return this.game.rnd.pick(i)},i.Group.prototype.getAll=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=this.children.length);for(var n=[],r=i;r0&&t instanceof i.Group){do{t.add(this.children[0],e)}while(this.children.length>0);this.hash=[],this.cursor=null}return t},i.Group.prototype.removeAll=function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),0!==this.children.length){do{!e&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var s=this.removeChild(this.children[0]);this.removeFromHash(s),t&&s&&s.destroy(!0,i)}while(this.children.length>0);this.hash=[],this.cursor=null}},i.Group.prototype.removeBetween=function(t,e,i,s){if(void 0===e&&(e=this.children.length-1),void 0===i&&(i=!1),void 0===s&&(s=!1),0!==this.children.length){if(t>e||t<0||e>this.children.length)return!1;for(var n=e;n>=t;){!s&&this.children[n].events&&this.children[n].events.onRemovedFromGroup$dispatch(this.children[n],this);var r=this.removeChild(this.children[n]);this.removeFromHash(r),i&&r&&r.destroy(!0),this.cursor===this.children[n]&&(this.cursor=null),n--}this.updateZ()}},i.Group.prototype.scatter=function(t,e){null==t&&(t=this.game.world.bounds),this.forEach(function(e){e.position.set(t.randomX,t.randomY)},null,e)},i.Group.prototype.shuffle=function(){i.ArrayUtils.shuffle(this.children),this.updateZ()},i.Group.prototype.destroy=function(t,e){null===this.game||this.ignoreDestroy||(void 0===t&&(t=!0),void 0===e&&(e=!1),this.onDestroy.dispatch(this,t,e),this.removeAll(t),this.cursor=null,this.filters=null,this.pendingDestroy=!1,e||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(i.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,i.Group.RETURN_TOTAL)}}),Object.defineProperty(i.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(i.Group.prototype,"angle",{get:function(){return i.Math.radToDeg(this.rotation)},set:function(t){this.rotation=i.Math.degToRad(t)}}),Object.defineProperty(i.Group.prototype,"centerX",{get:function(){return this.getBounds(this.parent).centerX},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.halfWidth}}),Object.defineProperty(i.Group.prototype,"centerY",{get:function(){return this.getBounds(this.parent).centerY},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.halfHeight}}),Object.defineProperty(i.Group.prototype,"left",{get:function(){return this.getBounds(this.parent).left},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i}}),Object.defineProperty(i.Group.prototype,"right",{get:function(){return this.getBounds(this.parent).right},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.width}}),Object.defineProperty(i.Group.prototype,"top",{get:function(){return this.getBounds(this.parent).top},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i}}),Object.defineProperty(i.Group.prototype,"bottom",{get:function(){return this.getBounds(this.parent).bottom},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.height}}),i.World=function(t){i.Group.call(this,t,null,"__world",!1),this.bounds=new i.Rectangle(0,0,t.width,t.height),this.camera=null,this._definedSize=!1,this._width=t.width,this._height=t.height,this.game.state.onStateChange.add(this.stateChange,this)},i.World.prototype=Object.create(i.Group.prototype),i.World.prototype.constructor=i.World,i.World.prototype.boot=function(){this.camera=new i.Camera(this.game,0,0,0,this.game.width,this.game.height),this.game.stage.addChild(this),this.camera.boot()},i.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},i.World.prototype.setBounds=function(t,e,i,s){this._definedSize=!0,this._width=i,this._height=s,this.bounds.setTo(t,e,i,s),this.x=t,this.y=e,this.camera.bounds&&this.camera.bounds.setTo(t,e,Math.max(i,this.game.width),Math.max(s,this.game.height)),this.game.physics.setBoundsToWorld()},i.World.prototype.resize=function(t,e){this._definedSize&&(tthis.bounds.right&&(t.x=this.bounds.left)),n&&(t.y+t._currentBounds.heightthis.bounds.bottom&&(t.y=this.bounds.top))):(s&&t.x+ethis.bounds.right&&(t.x=this.bounds.left-e),n&&t.y+ethis.bounds.bottom&&(t.y=this.bounds.top-e))},i.World.prototype.wrapAll=function(t,e,i,s,n,r){t.forEach(this.wrap,this,e,i,s,n,r)},Object.defineProperty(i.World.prototype,"width",{get:function(){return this.bounds.width},set:function(t){t1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.dropFrames?this.rendersThisFrame=0:(this.updateRender(this.time.slowMotion*this.time.desiredFps),this.rendersThisFrame=1);else{var e=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*e,this.time.elapsed),0);var i=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/e),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame)),this.forceSingleRender?this.rendersThisFrame=1:this.rendersThisFrame=Math.min(1,this.updatesThisFrame);this._deltaTime>=e&&(this._deltaTime-=e,this.currentUpdateID=i,this.updateLogic(this.time.desiredFpsMult),i++,!this.forceSingleUpdate||1!==i);)this.time.refresh();i>this._lastCount?this._spiraling++:i0&&this.updateRender(this._deltaTime/e)}}},updateLogic:function(t){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(t),this.debug.preUpdate(),this.input.pauseUpdate()):(this.stepping&&(this.pendingStep=!0),this.time.countUpdate(),this.scale.preUpdate(),this.debug.preUpdate(),this.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(t),this.plugins.preUpdate(t),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(),this.sound.update(),this.input.update(),this.physics.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate()),this.stage.updateTransform()},updateRender:function(t){this.lockRender||(this.time.countRender(),this.state.preRender(t),this.renderType!==i.HEADLESS&&(this.renderer.render(this.stage),this.plugins.render(t),this.state.render(t)),this.plugins.postRender(t))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.debug.destroy&&this.debug.destroy(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.plugins.destroy(),this.debug=null,this.state=null,this.sound=null,this.scale=null,this.stage=null,this.input=null,this.physics=null,this.plugins=null,this.cache=null,this.load=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),i.Canvas.removeFromDOM(this.canvas),PIXI.defaultRenderer=null,i.GAMES[this.id]=null},gamePaused:function(t){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.muteOnPause&&this.sound.setMute(),this.onPause.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(t){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.muteOnPause&&this.sound.unsetMute(),this.onResume.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(t){this.onBlur.dispatch(t),this.stage.disableVisibilityChange||this.gamePaused(t)},focusGain:function(t){this.onFocus.dispatch(t),this.stage.disableVisibilityChange||this.gameResumed(t)}},i.Game.prototype.constructor=i.Game,Object.defineProperty(i.Game.prototype,"paused",{get:function(){return this._paused},set:function(t){!0===t?(!1===this._paused&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),i.Input=function(t){this.game=t,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.customCandidateHandler=null,this.customCandidateHandlerContext=null,this.pollRate=0,this.enabled=!0,this.multiInputOverride=i.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.touchLockCallbacks=[],this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new i.ArraySet,this._localPoint=new i.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},i.Input.MOUSE_OVERRIDES_TOUCH=0,i.Input.TOUCH_OVERRIDES_MOUSE=1,i.Input.MOUSE_TOUCH_COMBINE=2,i.Input.MAX_POINTERS=10,i.Input.prototype={boot:function(){this.mousePointer=new i.Pointer(this.game,0,i.PointerMode.CURSOR),this.addPointer(),this.addPointer(),this.mouse=new i.Mouse(this.game),this.touch=new i.Touch(this.game),this.mspointer=new i.MSPointer(this.game),i.Keyboard&&(this.keyboard=new i.Keyboard(this.game)),i.Gamepad&&(this.gamepad=new i.Gamepad(this.game)),this.onDown=new i.Signal,this.onUp=new i.Signal,this.onTap=new i.Signal,this.onHold=new i.Signal,this.scale=new i.Point(1,1),this.speed=new i.Point,this.position=new i.Point,this._oldPosition=new i.Point,this.circle=new i.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=i.CanvasPool.create(this,1,1),this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.game.device.mspointer||this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var t=this;this._onClickTrampoline=function(e){t.onClickTrampoline(e)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],i.CanvasPool.remove(this),this.game.canvas.removeEventListener("click",this._onClickTrampoline)},setInteractiveCandidateHandler:function(t,e){this.customCandidateHandler=t,this.customCandidateHandlerContext=e},addMoveCallback:function(t,e){this.moveCallbacks.push({callback:t,context:e})},addTouchLockCallback:function(t,e,i){void 0===i&&(i=!1),this.touchLockCallbacks.push({callback:t,context:e,onEnd:i})},removeTouchLockCallback:function(t,e){for(var i=this.touchLockCallbacks.length;i--;)if(this.touchLockCallbacks[i].callback===t&&this.touchLockCallbacks[i].context===e)return this.touchLockCallbacks.splice(i,1),!0;return!1},executeTouchLockCallbacks:function(t,e){for(var i=this.touchLockCallbacks.length;i--;){var s=this.touchLockCallbacks[i];s.onEnd===t&&s.callback.call(s.context,this,e)&&this.touchLockCallbacks.splice(i,1)}},deleteMoveCallback:function(t,e){for(var i=this.moveCallbacks.length;i--;)if(this.moveCallbacks[i].callback===t&&this.moveCallbacks[i].context===e)return void this.moveCallbacks.splice(i,1)},addPointer:function(){if(this.pointers.length>=i.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+i.Input.MAX_POINTERS+" pointers reached."),null;var t=this.pointers.length+1,e=new i.Pointer(this.game,t,i.PointerMode.CONTACT);return this.pointers.push(e),this["pointer"+t]=e,e},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(t);if(!this.pointer2.active)return this.pointer2.start(t);for(var e=2;e0;i++)this.pointers[i].active&&e--;return t-e},getPointer:function(t){void 0===t&&(t=!1);for(var e=0;e=o&&this.game.camera.x+e.x=a&&this.game.camera.y+e.y=o&&this._localPoint.x=a&&this._localPoint.y=o&&this._localPoint.x=a&&this._localPoint.y0&&this._pollCounterthis.game.time.time},justReleased:function(t){return t=t||250,this.isUp&&this.timeUp+t>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},i.DeviceButton.prototype.constructor=i.DeviceButton,Object.defineProperty(i.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),i.Pointer=function(t,e,s){this.game=t,this.id=e,this.type=i.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.pointerMode=s||i.PointerMode.CURSOR|i.PointerMode.CONTACT,this.target=null,this.button=null,this.leftButton=new i.DeviceButton(this,i.Pointer.LEFT_BUTTON),this.middleButton=new i.DeviceButton(this,i.Pointer.MIDDLE_BUTTON),this.rightButton=new i.DeviceButton(this,i.Pointer.RIGHT_BUTTON),this.backButton=new i.DeviceButton(this,i.Pointer.BACK_BUTTON),this.forwardButton=new i.DeviceButton(this,i.Pointer.FORWARD_BUTTON),this.eraserButton=new i.DeviceButton(this,i.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===e,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.interactiveCandidates=[],this.active=!1,this.dirty=!1,this.position=new i.Point,this.positionDown=new i.Point,this.positionUp=new i.Point,this.circle=new i.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},i.Pointer.NO_BUTTON=0,i.Pointer.LEFT_BUTTON=1,i.Pointer.RIGHT_BUTTON=2,i.Pointer.MIDDLE_BUTTON=4,i.Pointer.BACK_BUTTON=8,i.Pointer.FORWARD_BUTTON=16,i.Pointer.ERASER_BUTTON=32,i.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.start(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.start(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.start(e),t===i.Mouse.BACK_BUTTON&&this.backButton.start(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.start(e)},processButtonsUp:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.stop(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.stop(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(e),t===i.Mouse.BACK_BUTTON&&this.backButton.stop(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(e)},processButtonsUpDown:function(t,e){var s="down"===e.type.toLowerCase().substr(-4),n="move"===e.type.toLowerCase().substr(-4);void 0!==t?(s&&1===t&&e.ctrlKey&&(t=2),this.leftButton.startStop(i.Pointer.LEFT_BUTTON&t,e),this.rightButton.startStop(i.Pointer.RIGHT_BUTTON&t,e),this.middleButton.startStop(i.Pointer.MIDDLE_BUTTON&t,e),this.backButton.startStop(i.Pointer.BACK_BUTTON&t,e),this.forwardButton.startStop(i.Pointer.FORWARD_BUTTON&t,e),this.eraserButton.startStop(i.Pointer.ERASER_BUTTON&t,e)):void 0!==e.button?s&&e.ctrlKey&&0===e.button?this.rightButton.start(e):s?this.processButtonsDown(e.button,e):n||this.processButtonsUp(e.button,e):s?e.ctrlKey?this.rightButton.start(e):this.leftButton.start(e):(this.leftButton.stop(e),this.rightButton.stop(e))},updateButtons:function(t){this.button=t.button,this.processButtonsUpDown(t.buttons,t),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(t){var e=this.game.input;return t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.isMouse?this.updateButtons(t):(this.isDown=!0,this.isUp=!1),this.active=!0,this.withinGame=!0,this.dirty=!1,this._history=[],this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(t,!0),this.positionDown.setTo(this.x,this.y),(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.x=this.x,e.y=this.y,e.position.setTo(this.x,this.y),e.onDown.dispatch(this,t),e.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){var t=this.game.input;this.active&&(this.dirty&&(t.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),!1===this._holdSent&&this.duration>=t.holdRate&&((t.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||t.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||t.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===t.totalActivePointers)&&t.onHold.dispatch(this),this._holdSent=!0),t.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+t.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>t.recordLimit&&this._history.shift()))},move:function(t,e){var s=this.game.input;if(!s.pollLocked){void 0===e&&(e=!1),void 0!==t.button&&(this.button=t.button),this.isMouse&&this.updateButtons(t),this.clientX=t.clientX,this.clientY=t.clientY,this.pageX=t.pageX,this.pageY=t.pageY,this.screenX=t.screenX,this.screenY=t.screenY,this.isMouse&&s.mouse.locked&&!e&&(this.rawMovementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.rawMovementY=t.movementY||t.mozMovementY||t.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*s.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*s.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(s.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||s.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||s.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===s.totalActivePointers)&&(s.activePointer=this,s.x=this.x,s.y=this.y,s.position.setTo(s.x,s.y),s.circle.x=s.x,s.circle.y=s.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY);for(var n=s.moveCallbacks.length;n--;)s.moveCallbacks[n].callback.call(s.moveCallbacks[n].context,this,this.x,this.y,e);return null===this.targetObject||this.game.paused&&!this.targetObject.noPause||!0!==this.targetObject.isDragged?s.interactiveItems.total>0&&this.processInteractiveObjects(e):!1===this.targetObject.update(this)&&(this.targetObject=null),this}},processInteractiveObjects:function(t){var e=0,i=-1,s=null,n=this.game.input.interactiveItems.first;for(this.interactiveCandidates=[];n;)n.checked=!1,!n.validForInput(i,e,!1)||this.game.paused&&!n.sprite.noPause||(n.checked=!0,(t&&n.checkPointerDown(this,!0)||!t&&n.checkPointerOver(this,!0))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n))),n=this.game.input.interactiveItems.next;for(n=this.game.input.interactiveItems.first;n;)!n.checked&&n.validForInput(i,e,!0)&&(t&&n.checkPointerDown(this,!1)||!t&&n.checkPointerOver(this,!1))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n)),n=this.game.input.interactiveItems.next;return this.game.input.customCandidateHandler&&(s=this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext,this,this.interactiveCandidates,s)),this.swapTarget(s,!1),null!==this.targetObject},swapTarget:function(t,e){void 0===e&&(e=!1),null===t?this.targetObject&&(this.targetObject._pointerOutHandler(this,e),this.targetObject=null):null===this.targetObject?(this.targetObject=t,t._pointerOverHandler(this,e)):this.targetObject===t?!1===t.update(this)&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this,e),this.targetObject=t,this.targetObject._pointerOverHandler(this,e))},leave:function(t){this.withinGame=!1,this.move(t,!1)},stop:function(t){var e=this.game.input;{if(!this._stateReset||!this.withinGame)return this.timeUp=this.game.time.time,(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.onUp.dispatch(this,t),this.duration>=0&&this.duration<=e.tapRate&&(this.timeUp-this.previousTapTime0&&(this.active=!1),this.withinGame=this.game.scale.bounds.contains(t.pageX,t.pageY),this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),!1===this.isMouse&&e.currentPointers--,e.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this;t.preventDefault()}},justPressed:function(t){return t=t||this.game.input.justPressedRate,!0===this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||this.game.input.justReleasedRate,this.isUp&&this.timeUp+t>this.game.time.time},addClickTrampoline:function(t,e,i,s){if(this.isDown){for(var n=this._clickTrampolines=this._clickTrampolines||[],r=0;rt||this.priorityID===t&&this.sprite.renderOrderID>e))},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(t){return t=t||0,this._pointerData[t].x},pointerY:function(t){return t=t||0,this._pointerData[t].y},pointerDown:function(t){return t=t||0,this._pointerData[t].isDown},pointerUp:function(t){return t=t||0,this._pointerData[t].isUp},pointerTimeDown:function(t){return t=t||0,this._pointerData[t].timeDown},pointerTimeUp:function(t){return t=t||0,this._pointerData[t].timeUp},pointerOver:function(t){if(!this.enabled)return!1;if(void 0===t){for(var e=0;e<10;e++)if(this._pointerData[e].isOver)return!0;return!1}return this._pointerData[t].isOver},pointerOut:function(t){if(!this.enabled)return!1;if(void 0!==t)return this._pointerData[t].isOut;for(var e=0;e<10;e++)if(this._pointerData[e].isOut)return!0},pointerTimeOver:function(t){return t=t||0,this._pointerData[t].timeOver},pointerTimeOut:function(t){return t=t||0,this._pointerData[t].timeOut},pointerDragged:function(t){return t=t||0,this._pointerData[t].isDragged},checkPointerDown:function(t,e){return!!(t.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectClick)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPointerOver:function(t,e){return!!(this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectOver)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPixel:function(t,e,i){if(this.sprite.texture.baseTexture.source){if(null===t&&null===e){this.game.input.getLocalPosition(this.sprite,i,this._tempPoint);var t=this._tempPoint.x,e=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(t-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(e-=-this.sprite.texture.frame.height*this.sprite.anchor.y),t+=this.sprite.texture.frame.x,e+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(t-=this.sprite.texture.trim.x,e-=this.sprite.texture.trim.y,tthis.sprite.texture.crop.right||ethis.sprite.texture.crop.bottom))return this._dx=t,this._dy=e,!1;if(this._dx=t,this._dy=e,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,t,e,1,1,0,0,1,1),this.game.input.hitContext.getImageData(0,0,1,1).data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(t){if(null!==this.sprite&&void 0!==this.sprite.parent)return this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this._pendingDrag?(this._dragDistancePass||(this._dragDistancePass=i.Math.distance(t.x,t.y,this.downPoint.x,this.downPoint.y)>=this.dragDistanceThreshold),this._dragDistancePass&&this._dragTimePass&&this.startDrag(t),!0):this.draggable&&this._draggedPointerID===t.id?this.updateDrag(t,!1):this._pointerData[t.id].isOver?this.checkPointerOver(t)?(this._pointerData[t.id].x=t.x-this.sprite.x,this._pointerData[t.id].y=t.y-this.sprite.y,!0):(this._pointerOutHandler(t),!1):void 0:(this._pointerOutHandler(t),!1)},_pointerOverHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];if(!1===i.isOver||t.dirty){var s=!1===i.isOver;i.isOver=!0,i.isOut=!1,i.timeOver=this.game.time.time,i.x=t.x-this.sprite.x,i.y=t.y-this.sprite.y,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),!e&&s&&this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,t),this.sprite.parent&&this.sprite.parent.onChildInputOver&&this.sprite.parent.onChildInputOver.dispatch(this.sprite,t)}}},_pointerOutHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];i.isOver=!1,i.isOut=!0,i.timeOut=this.game.time.time,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="",this._setHandCursor=!1),!e&&this.sprite&&this.sprite.events&&(this.sprite.events.onInputOut$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputOut&&this.sprite.parent.onChildInputOut.dispatch(this.sprite,t))}},_touchedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(!e.isDown&&e.isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,t))return;if(e.isDown=!0,e.isUp=!1,e.timeDown=this.game.time.time,this.downPoint.set(t.x,t.y),t.dirty=!0,this.sprite&&this.sprite.events&&(this.sprite.events.onInputDown$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputDown&&this.sprite.parent.onChildInputDown.dispatch(this.sprite,t),null===this.sprite))return;this.draggable&&!1===this.isDragged&&(0===this.dragTimeThreshold&&0===this.dragDistanceThreshold?this.startDrag(t):(this._pendingDrag=!0,this._dragDistancePass=0===this.dragDistanceThreshold,this.dragTimeThreshold>0?(this._dragTimePass=!1,this.game.time.events.add(this.dragTimeThreshold,this.dragTimeElapsed,this,t)):this._dragTimePass=!0)),this.bringToTop&&this.sprite.bringToTop()}}},dragTimeElapsed:function(t){this._dragTimePass=!0,this._pendingDrag&&this.sprite&&this._dragDistancePass&&this.startDrag(t)},_releasedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(e.isDown&&t.isUp){e.isDown=!1,e.isUp=!0,e.timeUp=this.game.time.time,e.downDuration=e.timeUp-e.timeDown;var i=this.checkPointerOver(t);this.sprite&&this.sprite.events&&(this.dragStopBlocksInputUp&&(!this.dragStopBlocksInputUp||this.draggable&&this.isDragged&&this._draggedPointerID===t.id)||this.sprite.events.onInputUp$dispatch(this.sprite,t,i),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputUp&&this.sprite.parent.onChildInputUp.dispatch(this.sprite,t,i),i&&(i=this.checkPointerOver(t))),e.isOver=i,!i&&this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),t.dirty=!0,this._pendingDrag=!1,this.draggable&&this.isDragged&&this._draggedPointerID===t.id&&this.stopDrag(t)}}},updateDrag:function(t,e){if(void 0===e&&(e=!1),t.isUp)return this.stopDrag(t),!1;var i=this.globalToLocal(t);if(this.sprite.fixedToCamera)var s=this.game.camera.scale.x*i.x+this._dragPoint.x+this.dragOffset.x,n=this.game.camera.scale.y*i.y+this._dragPoint.y+this.dragOffset.y;else var s=i.x+this._dragPoint.x+this.dragOffset.x,n=i.y+this._dragPoint.y+this.dragOffset.y;if(this.sprite.fixedToCamera)this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=s-this.game.camera.x),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=n-this.game.camera.y),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y));else{var r=this.game.camera.x-this._pointerData[t.id].camX,o=this.game.camera.y-this._pointerData[t.id].camY;this.allowHorizontalDrag&&(this.sprite.x=s+r),this.allowVerticalDrag&&(this.sprite.y=n+o),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.x,this.sprite.y))}return this.sprite.events.onDragUpdate.dispatch(this.sprite,t,s,n,this.snapPoint,e),!0},justOver:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOver&&this.overDuration(t)this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.ythis.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.leftthis.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.xthis.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.ythis.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.leftthis.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},i.InputHandler.prototype.constructor=i.InputHandler,i.Gamepad=function(t){this.game=t,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!==navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this)]},i.Gamepad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},start:function(){if(!this._active){this._active=!0;var t=this;this._onGamepadConnected=function(e){return t.onGamepadConnected(e)},this._onGamepadDisconnected=function(e){return t.onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(t){var e=t.gamepad;this._rawPads.push(e),this._gamepads[e.index].connect(e)},onGamepadDisconnected:function(t){var e=t.gamepad;for(var i in this._rawPads)this._rawPads[i].index===e.index&&this._rawPads.splice(i,1);this._gamepads[e.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(this._active){if(navigator.getGamepads)t=navigator.getGamepads();else if(navigator.webkitGetGamepads)t=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var t=navigator.webkitGamepads();if(t){this._rawPads=[];for(var e=!1,i=0;i0&&s>this.deadZone||s<0&&s<-this.deadZone?this.processAxisChange(i,s):this.processAxisChange(i,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(t){var e=!this.connected;this.connected=!0,this.index=t.index,this._rawPad=t,this._buttons=[],this._buttonsLen=t.buttons.length,this._axes=[],this._axesLen=t.axes.length;for(var s=0;sthis.maxHealth&&(this.health=this.maxHealth),this},heal:function(t){return this.alive&&(this.health+=t,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},i.Component.InCamera=function(){},i.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},i.Component.InputEnabled=function(){},i.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(t){t?null===this.input?(this.input=new i.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},i.Component.InWorld=function(){},i.Component.InWorld.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(this.autoCull||this.checkWorldBounds){if(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull)if(this.game.world.camera.view.intersects(this._bounds))this.renderable=!0,this.game.world.camera.totalInView++;else if(this.renderable=!1,this.outOfCameraBoundsKill)return this.kill(),!1;if(this.checkWorldBounds)if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1}return!0},i.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,outOfCameraBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},i.Component.LifeSpan=function(){},i.Component.LifeSpan.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):!(this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0))||(this.kill(),!1)},i.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(t){return void 0===t&&(t=100),this.alive=!0,this.exists=!0,this.visible=!0,"function"==typeof this.setHealth&&this.setHealth(t),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},i.Component.LoadTexture=function(){},i.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(t,e,s){t===i.PENDING_ATLAS?(t=e,e=0):e=e||0,(s||void 0===s)&&this.animations&&this.animations.stop(),this.key=t,this.customRender=!1;var n=this.game.cache,r=!0,o=!this.texture.baseTexture.scaleMode;if(i.RenderTexture&&t instanceof i.RenderTexture)this.key=t.key,this.setTexture(t);else if(i.BitmapData&&t instanceof i.BitmapData)this.customRender=!0,this.setTexture(t.texture),r=n.hasFrameData(t.key,i.Cache.BITMAPDATA)?!this.animations.loadFrameData(n.getFrameData(t.key,i.Cache.BITMAPDATA),e):!this.animations.loadFrameData(t.frameData,0);else if(i.Video&&t instanceof i.Video){this.customRender=!0;var a=t.texture.valid;this.setTexture(t.texture),this.setFrame(t.texture.frame.clone()),t.onChangeSource.add(this.resizeFrame,this),this.texture.valid=a}else if(i.Tilemap&&t instanceof i.TilemapLayer)this.setTexture(PIXI.Texture.fromCanvas(t.canvas));else if(t instanceof PIXI.Texture)this.setTexture(t);else{var h=n.getImage(t,!0);this.key=h.key,this.setTexture(new PIXI.Texture(h.base)),this.texture.baseTexture.skipRender="__default"===t,r=!this.animations.loadFrameData(h.frameData,e)}r&&(this._frame=i.Rectangle.clone(this.texture.frame)),o||(this.texture.baseTexture.scaleMode=1)},setFrame:function(t){this._frame=t,this.texture.frame.x=t.x,this.texture.frame.y=t.y,this.texture.frame.width=t.width,this.texture.frame.height=t.height,this.texture.crop.x=t.x,this.texture.crop.y=t.y,this.texture.crop.width=t.width,this.texture.crop.height=t.height,t.trimmed?(this.texture.trim?(this.texture.trim.x=t.spriteSourceSizeX,this.texture.trim.y=t.spriteSourceSizeY,this.texture.trim.width=t.sourceSizeW,this.texture.trim.height=t.sourceSizeH):this.texture.trim={x:t.spriteSourceSizeX,y:t.spriteSourceSizeY,width:t.sourceSizeW,height:t.sourceSizeH},this.texture.width=t.sourceSizeW,this.texture.height=t.sourceSizeH,this.texture.frame.width=t.sourceSizeW,this.texture.frame.height=t.sourceSizeH):!t.trimmed&&this.texture.trim&&(this.texture.trim=null),t.rotated&&(this.texture.rotated=!0),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(t,e,i){this.texture.frame.resize(e,i),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(t){this.animations.frame=t}},frameName:{get:function(){return this.animations.frameName},set:function(t){this.animations.frameName=t}}},i.Component.Overlap=function(){},i.Component.Overlap.prototype={overlap:function(t){return i.Rectangle.intersects(this.getBounds(),t.getBounds())}},i.Component.PhysicsBody=function(){},i.Component.PhysicsBody.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):this.fresh&&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.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,this.preUpdateChildren(),!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!(!this._exists||!this.parent.exists)||(this.renderOrderID=-1,!1))},i.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},i.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(t){this.position.x=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},i.Component.Reset=function(){},i.Component.Reset.prototype.reset=function(t,e,i){return void 0===i&&(i=1),this.world.set(t,e),this.position.set(t,e),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=i),this.components.PhysicsBody&&this.body&&this.body.reset(t,e,!1,!1),this},i.Component.ScaleMinMax=function(){},i.Component.ScaleMinMax.prototype={transformCallback:null,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(t){this.scaleMin&&(t.athis.scaleMax.x&&(t.a=this.scaleMax.x),t.d>this.scaleMax.y&&(t.d=this.scaleMax.y))},setScaleMinMax:function(t,e,s,n){void 0===e?e=s=n=t:void 0===s&&(s=n=e,e=t),null===t?this.scaleMin=null:this.scaleMin?this.scaleMin.set(t,e):this.scaleMin=new i.Point(t,e),null===s?this.scaleMax=null:this.scaleMax?this.scaleMax.set(s,n):this.scaleMax=new i.Point(s,n),null===this.scaleMin?this.transformCallback=null:(this.transformCallback=this.checkTransform,this.transformCallbackContext=this)}},i.Component.Smoothed=function(){},i.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(t){t?this.texture&&(this.texture.baseTexture.scaleMode=0,this.texture.baseTexture.dirty()):this.texture&&(this.texture.baseTexture.scaleMode=1,this.texture.baseTexture.dirty())}}},i.GameObjectFactory=function(t){this.game=t,this.world=this.game.world},i.GameObjectFactory.prototype={existing:function(t){return this.world.add(t)},weapon:function(t,e,s,n,r){var o=this.game.plugins.add(i.Weapon);return r&&(o.bulletClass=r),o.createBullets(t,e,s,n),o},image:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Image(this.game,t,e,s,n))},sprite:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Sprite(this.game,t,e,s,n))},creature:function(t,e,s,n,r){void 0===r&&(r=this.world);var o=new i.Creature(this.game,t,e,s,n);return r.add(o),o},tween:function(t){return this.game.tweens.create(t)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},physicsGroup:function(t,e,s,n){return new i.Group(this.game,e,s,n,!0,t)},spriteBatch:function(t,e,s){return void 0===t&&(t=null),void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},tileSprite:function(t,e,s,n,r,o,a){return void 0===a&&(a=this.world),a.add(new i.TileSprite(this.game,t,e,s,n,r,o))},rope:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.Rope(this.game,t,e,s,n,r))},text:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Text(this.game,t,e,s,n))},button:function(t,e,s,n,r,o,a,h,l,c){return void 0===c&&(c=this.world),c.add(new i.Button(this.game,t,e,s,n,r,o,a,h,l))},graphics:function(t,e,s){return void 0===s&&(s=this.world),s.add(new i.Graphics(this.game,t,e))},emitter:function(t,e,s){return this.game.particles.add(new i.Particles.Arcade.Emitter(this.game,t,e,s))},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.BitmapText(this.game,t,e,s,n,r))},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},video:function(t,e){return new i.Video(this.game,t,e)},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t},plugin:function(t){return this.game.plugins.add(t)}},i.GameObjectFactory.prototype.constructor=i.GameObjectFactory,i.GameObjectCreator=function(t){this.game=t,this.world=this.game.world},i.GameObjectCreator.prototype={image:function(t,e,s,n){return new i.Image(this.game,t,e,s,n)},sprite:function(t,e,s,n){return new i.Sprite(this.game,t,e,s,n)},tween:function(t){return new i.Tween(t,this.game,this.game.tweens)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},spriteBatch:function(t,e,s){return void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},tileSprite:function(t,e,s,n,r,o){return new i.TileSprite(this.game,t,e,s,n,r,o)},rope:function(t,e,s,n,r){return new i.Rope(this.game,t,e,s,n,r)},text:function(t,e,s,n){return new i.Text(this.game,t,e,s,n)},button:function(t,e,s,n,r,o,a,h,l){return new i.Button(this.game,t,e,s,n,r,o,a,h,l)},graphics:function(t,e){return new i.Graphics(this.game,t,e)},emitter:function(t,e,s){return new i.Particles.Arcade.Emitter(this.game,t,e,s)},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return new i.BitmapText(this.game,t,e,s,n,r,o)},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t}},i.GameObjectCreator.prototype.constructor=i.GameObjectCreator,i.Sprite=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.SPRITE,this.physicsType=i.SPRITE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Sprite.prototype=Object.create(PIXI.Sprite.prototype),i.Sprite.prototype.constructor=i.Sprite,i.Component.Core.install.call(i.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Sprite.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Sprite.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Sprite.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Sprite.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Sprite.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Image=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.IMAGE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Image.prototype=Object.create(PIXI.Sprite.prototype),i.Image.prototype.constructor=i.Image,i.Component.Core.install.call(i.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","ScaleMinMax","Smoothed"]),i.Image.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Image.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Image.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Image.prototype.preUpdate=function(){return!(!this.preUpdateInWorld()||!this.preUpdateLifeSpan())&&this.preUpdateCore()},i.Button=function(t,e,s,n,r,o,a,h,l,c){e=e||0,s=s||0,n=n||null,r=r||null,o=o||this,i.Image.call(this,t,e,s,n,h),this.type=i.BUTTON,this.physicsType=i.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new i.Signal,this.onInputOut=new i.Signal,this.onInputDown=new i.Signal,this.onInputUp=new i.Signal,this.onOverMouseOnly=!0,this.justReleasedPreventsOver=i.PointerMode.CONTACT,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(a,h,l,c),null!==r&&this.onInputUp.add(r,o),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this)},i.Button.prototype=Object.create(i.Image.prototype),i.Button.prototype.constructor=i.Button;return i.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},i.Button.prototype.setStateFrame=function(t,e,i){var s="_on"+t+"Frame";null!==e?(this[s]=e,i&&this.changeStateFrame(t)):this[s]=null},i.Button.prototype.changeStateFrame=function(t){if(this.freezeFrames)return!1;var e=this["_on"+t+"Frame"];return"string"==typeof e?(this.frameName=e,!0):"number"==typeof e&&(this.frame=e,!0)},i.Button.prototype.setFrames=function(t,e,i,s){this.setStateFrame("Over",t,this.input.pointerOver()),this.setStateFrame("Out",e,!this.input.pointerOver()),this.setStateFrame("Down",i,this.input.pointerDown()),this.setStateFrame("Up",s,this.input.pointerUp())},i.Button.prototype.setStateSound=function(t,e,s){var n="on"+t+"Sound",r="on"+t+"SoundMarker";e instanceof i.Sound||e instanceof i.AudioSprite?(this[n]=e,this[r]="string"==typeof s?s:""):(this[n]=null,this[r]="")},i.Button.prototype.playStateSound=function(t){var e=this["on"+t+"Sound"];if(e){var i=this["on"+t+"SoundMarker"];return e.play(i),!0}return!1},i.Button.prototype.setSounds=function(t,e,i,s,n,r,o,a){this.setStateSound("Over",t,e),this.setStateSound("Out",n,r),this.setStateSound("Down",i,s),this.setStateSound("Up",o,a)},i.Button.prototype.setOverSound=function(t,e){this.setStateSound("Over",t,e)},i.Button.prototype.setOutSound=function(t,e){this.setStateSound("Out",t,e)},i.Button.prototype.setDownSound=function(t,e){this.setStateSound("Down",t,e)},i.Button.prototype.setUpSound=function(t,e){this.setStateSound("Up",t,e)},i.Button.prototype.onInputOverHandler=function(t,e){e.justReleased()&&(this.justReleasedPreventsOver&e.pointerMode)===e.pointerMode||(this.changeStateFrame("Over"),this.onOverMouseOnly&&!e.isMouse||(this.playStateSound("Over"),this.onInputOver&&this.onInputOver.dispatch(this,e)))},i.Button.prototype.onInputOutHandler=function(t,e){this.changeStateFrame("Out"),this.playStateSound("Out"),this.onInputOut&&this.onInputOut.dispatch(this,e)},i.Button.prototype.onInputDownHandler=function(t,e){this.changeStateFrame("Down"),this.playStateSound("Down"),this.onInputDown&&this.onInputDown.dispatch(this,e)},i.Button.prototype.onInputUpHandler=function(t,e,i){this.playStateSound("Up"),this.onInputUp&&this.onInputUp.dispatch(this,e,i),this.freezeFrames||(!0===this.forceOut||(this.forceOut&e.pointerMode)===e.pointerMode?this.changeStateFrame("Out"):this.changeStateFrame("Up")||(i?this.changeStateFrame("Over"):this.changeStateFrame("Out")))},i.SpriteBatch=function(t,e,s,n){void 0!==e&&null!==e||(e=t.world),i.Group.call(this,t,e,s,n),this.type=i.SPRITEBATCH,this.fastSpriteBatch=null,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.Group.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||(this.fastSpriteBatch=new PIXI.WebGLFastSpriteBatch(t.gl),this.ready=!0),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n=0&&t<=this.width&&e>=0&&e<=this.height&&(i.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|n<<8|s:this.pixels[e*this.width+t]=s<<24|n<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,s){s||(s=i.Color.createColor());var n=~~(t+e*this.width);return n*=4,s.r=this.data[n],s.g=this.data[++n],s.b=this.data[++n],s.a=this.data[++n],s},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,s,n,r){return i.Color.unpackPixel(this.getPixel32(t,e),s,n,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=i.Color.createColor(),s=0,n=0,r=1,o=!1;1===t?(r=-1,n=this.height):3===t&&(r=-1,s=this.width);do{i.Color.unpackPixel(this.getPixel32(s,n),e),0===t||1===t?++s===this.width&&(s=0,((n+=r)>=this.height||n<=0)&&(o=!0)):2!==t&&3!==t||++n===this.height&&(n=0,((s+=r)>=this.width||s<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=s,e.y=n,e},getBounds:function(t){return void 0===t&&(t=new i.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,s,n,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),t instanceof i.RenderTexture&&(t=t.getCanvas()),this._image=t,t instanceof i.Sprite||t instanceof i.Image||t instanceof i.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof i.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==s&&null!==s||(s=0),n&&(this._size.x=n),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=s),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+s,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var n=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===n.a||0===n.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=n.tx,o=n.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),s&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(n.a,n.b,n.c,n.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,s){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,s),t.type===i.GROUP&&t.exists)this.drawGroup(t,e,s);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var n=0;ne.width&&(n=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,s),this._circle=new i.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,n,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),i.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this},copyBitmapData:function(t,e,i){t.update();for(var s,n=0;n80*s){h=c=t[0],l=u=t[1];for(var g=s;gc&&(c=d),p>u&&(u=p);f=Math.max(c-h,u-l)}return i.EarCut.earcutLinked(o,a,s,h,l,f),a},i.EarCut.linkedList=function(t,e,s,n,r){var o,a,h,l=0;for(o=e,a=s-n;o0)for(o=e;o=e;o-=n)h=i.EarCut.insertNode(o,t[o],t[o+1],h);return h},i.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var s,n=t;do{if(s=!1,n.steiner||!i.EarCut.equals(n,n.next)&&0!==i.EarCut.area(n.prev,n,n.next))n=n.next;else{if(i.EarCut.removeNode(n),(n=e=n.prev)===n.next)return null;s=!0}}while(s||n!==e);return e},i.EarCut.earcutLinked=function(t,e,s,n,r,o,a){if(t){!a&&o&&i.EarCut.indexCurve(t,n,r,o);for(var h,l,c=t;t.prev!==t.next;)if(h=t.prev,l=t.next,o?i.EarCut.isEarHashed(t,n,r,o):i.EarCut.isEar(t))e.push(h.i/s),e.push(t.i/s),e.push(l.i/s),i.EarCut.removeNode(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?(t=i.EarCut.cureLocalIntersections(t,e,s),i.EarCut.earcutLinked(t,e,s,n,r,o,2)):2===a&&i.EarCut.splitEarcut(t,e,s,n,r,o):i.EarCut.earcutLinked(i.EarCut.filterPoints(t),e,s,n,r,o,1);break}}},i.EarCut.isEar=function(t){var e=t.prev,s=t,n=t.next;if(i.EarCut.area(e,s,n)>=0)return!1;for(var r=t.next.next;r!==t.prev;){if(i.EarCut.pointInTriangle(e.x,e.y,s.x,s.y,n.x,n.y,r.x,r.y)&&i.EarCut.area(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},i.EarCut.isEarHashed=function(t,e,s,n){var r=t.prev,o=t,a=t.next;if(i.EarCut.area(r,o,a)>=0)return!1;for(var h=r.xo.x?r.x>a.x?r.x:a.x:o.x>a.x?o.x:a.x,u=r.y>o.y?r.y>a.y?r.y:a.y:o.y>a.y?o.y:a.y,d=i.EarCut.zOrder(h,l,e,s,n),p=i.EarCut.zOrder(c,u,e,s,n),f=t.nextZ;f&&f.z<=p;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=d;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0},i.EarCut.cureLocalIntersections=function(t,e,s){var n=t;do{var r=n.prev,o=n.next.next;i.EarCut.intersects(r,n,n.next,o)&&i.EarCut.locallyInside(r,o)&&i.EarCut.locallyInside(o,r)&&(e.push(r.i/s),e.push(n.i/s),e.push(o.i/s),i.EarCut.removeNode(n),i.EarCut.removeNode(n.next),n=t=o),n=n.next}while(n!==t);return n},i.EarCut.splitEarcut=function(t,e,s,n,r,o){var a=t;do{for(var h=a.next.next;h!==a.prev;){if(a.i!==h.i&&i.EarCut.isValidDiagonal(a,h)){var l=i.EarCut.splitPolygon(a,h);return a=i.EarCut.filterPoints(a,a.next),l=i.EarCut.filterPoints(l,l.next),i.EarCut.earcutLinked(a,e,s,n,r,o),void i.EarCut.earcutLinked(l,e,s,n,r,o)}h=h.next}a=a.next}while(a!==t)},i.EarCut.eliminateHoles=function(t,e,s,n){var r,o,a,h,l,c=[];for(r=0,o=e.length;r=n.next.y){var h=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);h<=r&&h>a&&(a=h,s=n.x=n.x&&n.x>=s.x&&i.EarCut.pointInTriangle(os.x)&&i.EarCut.locallyInside(n,t)&&(s=n,u=l),n=n.next;return s},i.EarCut.indexCurve=function(t,e,s,n){var r=t;do{null===r.z&&(r.z=i.EarCut.zOrder(r.x,r.y,e,s,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,i.EarCut.sortLinked(r)},i.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},i.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},i.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},i.EarCut.isValidDiagonal=function(t,e){return i.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!i.EarCut.intersectsPolygon(t,e)&&i.EarCut.locallyInside(t,e)&&i.EarCut.locallyInside(e,t)&&i.EarCut.middleInside(t,e)},i.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},i.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},i.EarCut.intersects=function(t,e,s,n){return i.EarCut.area(t,e,s)>0!=i.EarCut.area(t,e,n)>0&&i.EarCut.area(s,n,t)>0!=i.EarCut.area(s,n,e)>0},i.EarCut.intersectsPolygon=function(t,e){var s=t;do{if(s.i!==t.i&&s.next.i!==t.i&&s.i!==e.i&&s.next.i!==e.i&&i.EarCut.intersects(s,s.next,t,e))return!0;s=s.next}while(s!==t);return!1},i.EarCut.locallyInside=function(t,e){return i.EarCut.area(t.prev,t,t.next)<0?i.EarCut.area(t,e,t.next)>=0&&i.EarCut.area(t,t.prev,e)>=0:i.EarCut.area(t,e,t.prev)<0||i.EarCut.area(t,t.next,e)<0},i.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},i.EarCut.splitPolygon=function(t,e){var s=new i.EarCut.Node(t.i,t.x,t.y),n=new i.EarCut.Node(e.i,e.x,e.y),r=t.next,o=e.prev;return t.next=e,e.prev=t,s.next=r,r.prev=s,n.next=s,s.prev=n,o.next=n,n.prev=o,n},i.EarCut.insertNode=function(t,e,s,n){var r=new i.EarCut.Node(t,e,s);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r},i.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},i.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var s,n=e.gl,r=e.projection,o=e.offset,a=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,n);var h=t._webGL[n.id];if(h)for(var l=0;l=PIXI.WebGLGraphics.stencilBufferLimit&&(a.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit?(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildPoly(a,o)||(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))),a.lineWidth>0&&(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildLine(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,0),a.type===i.RECTANGLE?PIXI.WebGLGraphics.buildRectangle(a,o):a.type===i.CIRCLE||a.type===i.ELLIPSE?PIXI.WebGLGraphics.buildCircle(a,o):a.type===i.ROUNDEDRECTANGLE&&PIXI.WebGLGraphics.buildRoundedRectangle(a,o)),s.lastIndex++}for(n=0;n19600?(_=y-x,w=v-b,_/=R=Math.sqrt(_*_+w*w),w/=R,_*=F,w*=F,L.push(p-_,f-w),L.push(G,N,X,U),L.push(p+_,f+w),L.push(G,N,X,U),L.push(p-_,f-w),L.push(G,N,X,U),O++):(L.push(l,c),L.push(G,N,X,U),L.push(p-(l-p),f-(c-f)),L.push(G,N,X,U));for(u=n[2*(I-2)],d=n[2*(I-2)+1],p=n[2*(I-1)],y=-(d-(f=n[2*(I-1)+1])),v=u-p,y/=R=Math.sqrt(y*y+v*v),v/=R,y*=F,v*=F,L.push(p-y,f-v),L.push(G,N,X,U),L.push(p+y,f+v),L.push(G,N,X,U),B.push(k),s=0;sh?r:h,l=oc?o:c;s.push(a,l,h,l,h,c,a,c);var d=s.length/2;for(u=0;uS?S:C,e.beginPath(),e.moveTo(_,w+C),e.lineTo(_,w+P-C),e.quadraticCurveTo(_,w+P,_+C,w+P),e.lineTo(_+T-C,w+P),e.quadraticCurveTo(_+T,w+P,_+T,w+P-C),e.lineTo(_+T,w+C),e.quadraticCurveTo(_+T,w,_+T-C,w),e.lineTo(_+C,w),e.quadraticCurveTo(_,w,_,w+C),e.closePath(),(r.fillColor||0===r.fillColor)&&(e.globalAlpha=r.fillAlpha*s,e.fillStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.fill()),r.lineWidth&&(e.globalAlpha=r.lineAlpha*s,e.strokeStyle="#"+("00000"+(0|h).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var s=t.graphicsData.length;if(0!==s){e.beginPath();for(var n=0;nP?P:T,e.moveTo(x,b+T),e.lineTo(x,b+w-T),e.quadraticCurveTo(x,b+w,x+T,b+w),e.lineTo(x+_-T,b+w),e.quadraticCurveTo(x+_,b+w,x+_,b+w-T),e.lineTo(x+_,b+T),e.quadraticCurveTo(x+_,b,x+_-T,b),e.lineTo(x+T,b),e.quadraticCurveTo(x,b,x,b+T),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},i.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},i.GraphicsData.prototype.constructor=i.GraphicsData,i.GraphicsData.prototype.clone=function(){return new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},i.Graphics=function(t,e,s){void 0===e&&(e=0),void 0===s&&(s=0),this.type=i.GRAPHICS,this.physicsType=i.SPRITE,this.anchor=new i.Point,PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new i.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1,i.Component.Core.init.call(this,t,e,s,"",null)},i.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Graphics.prototype.constructor=i.Graphics,i.Component.Core.install.call(i.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),i.Graphics.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Graphics.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Graphics.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Graphics.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Graphics.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Graphics.prototype.postUpdate=function(){i.Component.PhysicsBody.postUpdate.call(this),i.Component.FixedToCamera.postUpdate.call(this),this._boundsDirty&&(this.updateLocalBounds(),this._boundsDirty=!1);for(var t=0;t0&&this.drawPolygon(s)}else this.drawPolygon(s)},i.Graphics.prototype.drawTriangles=function(t,e,s){void 0===s&&(s=!1);var n,r=new i.Point,o=new i.Point,a=new i.Point,h=[];if(e)if(t[0]instanceof i.Point)for(n=0;nc*a)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var x=d+s+p*(v+y*v),b=Math.cos(x),_=-Math.sin(x);u.push((f*b+g*_)*i+t,(f*-_+g*b)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},i.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},i.Graphics.prototype.drawRect=function(t,e,s,n){return this.drawShape(new i.Rectangle(t,e,s,n)),this},i.Graphics.prototype.drawRoundedRect=function(t,e,s,n,r){return this.drawShape(new i.RoundedRectangle(t,e,s,n,r)),this},i.Graphics.prototype.drawCircle=function(t,e,s){return this.drawShape(new i.Circle(t,e,s)),this},i.Graphics.prototype.drawEllipse=function(t,e,s,n){return this.drawShape(new i.Ellipse(t,e,s,n)),this},i.Graphics.prototype.drawPolygon=function(t){t instanceof i.Polygon&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var s=0;sw?m:w,w=v>w?v:w,w=b>w?b:w,T=y>T?y:T,T=x>T?x:T,T=_>T?_:T,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=C,this._bounds.height=T-C,this._currentBounds=this._bounds,this._currentBounds},i.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;ee?a+l:e,s=hn?h+c:n;else if(p===i.CIRCLE)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else if(p===i.ELLIPSE)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else{o=r.points;for(var g=0;ge?a+f:e,s=h-fn?h+f:n}}else t=0,e=0,s=0,n=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=s-m,this._localBounds.height=n-s+2*m},i.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},i.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},i.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},i.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof i.Polygon&&(t=t.clone()).flatten();var e=new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===i.POLYGON&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(i.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),i.RenderTexture=function(t,e,s,n,r,o,a,h){if(void 0===e&&(e=100),void 0===s&&(s=100),void 0===n&&(n=""),void 0===r&&(r=i.scaleModes.DEFAULT),void 0===o&&(o=1),void 0===a&&(a=PIXI.defaultRenderer),void 0===h&&(h=0),this.game=t,this.key=n,this.type=i.RENDERTEXTURE,this._tempMatrix=new i.Matrix,this.width=e,this.height=s,this.resolution=o,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=this.frame.clone(),this.baseTexture=new PIXI.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=r,this.baseTexture.hasLoaded=!0,PIXI.Texture.call(this,this.baseTexture,this.frame.clone()),this.renderer=a,this.renderer.type===i.WEBGL){var l=this.renderer.gl;this.baseTexture.textureIndex=h,this.baseTexture._dirty[l.id]=!1,this.textureBuffer=new PIXI.FilterTexture(l,this.width,this.height,this.baseTexture.scaleMode,h),this.baseTexture._glTextures[l.id]=this.textureBuffer.texture,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.textureBuffer=new PIXI.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new i.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(PIXI.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.renderXY=function(t,e,s,n){t.updateTransform(),this._tempMatrix.copyFrom(t.worldTransform),this._tempMatrix.tx=e,this._tempMatrix.ty=s,this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.renderRawXY=function(t,e,s,n){this._tempMatrix.identity().translate(e,s),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.render=function(t,e,s){void 0===e||null===e?this._tempMatrix.copyFrom(t.worldTransform):this._tempMatrix.copyFrom(e),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,s):this._renderCanvas(t,this._tempMatrix,s)},i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype._renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n-1&&this.characterLimitSize0&&this.style.maxLines0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(e[a]):l+=this.context.measureText(e[a]).width,this.style.wordWrap&&(l-=this.context.measureText(" ").width)}else{var h=e[a].split(/(?:\t)/),l=this.padding.x+this.style.strokeThickness;if(Array.isArray(i))for(var c=0,u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.measureLine(h[u]):Math.ceil(this.context.measureText(h[u]).width),u>0&&(c+=i[u-1]),l=c+d}else for(u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(h[u]):l+=Math.ceil(this.context.measureText(h[u]).width),l+=this.game.math.snapToCeil(l,i)-l}s[a]=Math.ceil(l),n=Math.max(n,s[a])}this.canvas.width=n*this._res;var p=r.fontSize+this.style.strokeThickness+this.padding.y,f=p*o,g=this._lineSpacing;g<0&&Math.abs(g)>p&&(g=-p),0!==g&&(f+=g>0?g*e.length:g*(e.length-1)),this.canvas.height=f*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var m,y;for(this._charCount=0,a=0;a0&&(y+=g*a),"right"===this.style.align?m+=n-s[a]:"center"===this.style.align&&(m+=(n-s[a])/2),this.autoRound&&(m=Math.round(m),y=Math.round(y)),this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.updateLine(e[a],m,y):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===i?this.context.strokeText(e[a],m,y):this.renderTabLine(e[a],m,y,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===i?this.context.fillText(e[a],m,y):this.renderTabLine(e[a],m,y,!0)));this.updateTexture(),this.dirty=!1},i.Text.prototype.renderTabLine=function(t,e,i,s){var n=t.split(/(?:\t)/),r=this.style.tabs,o=0;if(Array.isArray(r))for(var a=0,h=0;h0&&(a+=r[h-1]),o=e+a,s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i);else for(h=0;h0||this.fontStyles.length>0){var n=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(n.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(n.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(n)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill)),e+=this.context.measureText(s).width,this._charCount++}return Math.ceil(e)},i.Text.prototype.updateLine=function(t,e,i){for(var s=0;s0||this.fontStyles.length>0){var r=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(r.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(r.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(r)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(n,e,i)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(n,e,i)),e+=this.context.measureText(n).width,this._charCount++}},i.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},i.Text.prototype.clearFontValues=function(){return this.fontStyles=[],this.fontWeights=[],this.dirty=!0,this},i.Text.prototype.addColor=function(t,e){return this.colors[e]=t,this.dirty=!0,this},i.Text.prototype.addStrokeColor=function(t,e){return this.strokeColors[e]=t,this.dirty=!0,this},i.Text.prototype.addFontStyle=function(t,e){return this.fontStyles[e]=t,this.dirty=!0,this},i.Text.prototype.addFontWeight=function(t,e){return this.fontWeights[e]=t,this.dirty=!0,this},i.Text.prototype.precalculateWordWrap=function(t){return this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font,this.runWordWrap(t).split(/(?:\r\n|\r|\n)/)},i.Text.prototype.runWordWrap=function(t){return this.useAdvancedWrap?this.advancedWordWrap(t):this.basicWordWrap(t)},i.Text.prototype.advancedWordWrap=function(t){for(var e=this.context,i=this.style.wordWrapWidth,s="",n=t.replace(/ +/gi," ").split(/\r?\n/gi),r=n.length,o=0;ol){if(0===u){for(var g=p;g.length&&(g=g.slice(0,-1),!((f=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var m=d.substr(g.length);c[u]=m,h+=g}var y=c[u].length?u:u+1,v=c.slice(y).join(" ").replace(/[ \n]*$/gi,"");n[o+1]=v+" "+(n[o+1]||""),r=n.length;break}h+=p,l-=f}s+=h.replace(/[ \n]*$/gi,"")+"\n"}}return s=s.replace(/[\s|\n]*$/gi,"")},i.Text.prototype.basicWordWrap=function(t){for(var e="",i=t.split("\n"),s=0;sn?(o>0&&(e+="\n"),e+=r[o]+" ",n=this.style.wordWrapWidth-a):(n-=h,e+=r[o]+" ")}ss&&(this.style.wordWrapWidth=s)),this.updateTexture(),this},i.Text.prototype.updateTexture=function(){var t=this.texture.baseTexture,e=this.texture.crop,i=this.texture.frame,s=this.canvas.width,n=this.canvas.height;if(t.width=s,t.height=n,e.width=s,e.height=n,i.width=s,i.height=n,this.texture.width=s,this.texture.height=n,this._width=s,this._height=n,this.textBounds){var r=this.textBounds.x,o=this.textBounds.y;"right"===this.style.boundsAlignH?r+=this.textBounds.width-this.canvas.width/this.resolution:"center"===this.style.boundsAlignH&&(r+=this.textBounds.halfWidth-this.canvas.width/this.resolution/2),"bottom"===this.style.boundsAlignV?o+=this.textBounds.height-this.canvas.height/this.resolution:"middle"===this.style.boundsAlignV&&(o+=this.textBounds.halfHeight-this.canvas.height/this.resolution/2),this.pivot.x=-r,this.pivot.y=-o}this.renderable=0!==s&&0!==n,this.texture.requiresReTint=!0,this.texture.baseTexture.dirty()},i.Text.prototype._renderWebGL=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.Text.prototype._renderCanvas=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.Text.prototype.determineFontProperties=function(t){var e=i.Text.fontPropertiesCache[t];if(!e){e={};var s=i.Text.fontPropertiesCanvas,n=i.Text.fontPropertiesContext;n.font=t;var r=Math.ceil(n.measureText("|MÉq").width),o=Math.ceil(n.measureText("|MÉq").width),a=2*o;if(o=1.4*o|0,s.width=r,s.height=a,n.fillStyle="#f00",n.fillRect(0,0,r,a),n.font=t,n.textBaseline="alphabetic",n.fillStyle="#000",n.fillText("|MÉq",0,o),!n.getImageData(0,0,r,a))return e.ascent=o,e.descent=o+6,e.fontSize=e.ascent+e.descent,i.Text.fontPropertiesCache[t]=e,e;var h,l,c=n.getImageData(0,0,r,a).data,u=c.length,d=4*r,p=0,f=!1;for(h=0;ho;h--){for(l=0;l0?this._maxWidth:null,l=[],c=0;c=h&&r>-1)return{width:o||n,text:i.substr(0,c-(c-r)),end:!1,chars:l};n+=(p.xAdvance+g)*e,l.push(s+(p.xOffset+g)*e),s+=(p.xAdvance+g)*e,a=d}return{width:n,text:i,end:u,chars:l}},i.BitmapText.prototype.cleanText=function(t,e){void 0===e&&(e="");var i=this._data.font;if(!i)return"";for(var s=/\r\n|\n\r|\n|\r/g,n=t.replace(s,"\n").split("\n"),r=0;rthis.textWidth&&(this.textWidth=c.width),n+=t.lineHeight*i,e=e.substr(c.text.length+1)}while(!1===c.end);this.textHeight=n;for(var r=0,o=0,a=this.textWidth*this.anchor.x,h=this.textHeight*this.anchor.y,l=0;l0&&(this._fontSize=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"smoothed",{get:function(){return!this._data.base.scaleMode},set:function(t){this._data.base.scaleMode=t?0:1,this._data.base.dirty()}}),i.RetroFont=function(t,e,s,n,r,o,a,h,l,c){if(!t.cache.checkImageKey(e))return!1;void 0!==o&&null!==o||(o=t.cache.getImage(e).width/s),this.characterWidth=s,this.characterHeight=n,this.characterSpacingX=a||0,this.characterSpacingY=h||0,this.characterPerRow=o,this.offsetX=l||0,this.offsetY=c||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=t.cache.getImage(e),this._text="",this.grabData=[],this.frameData=new i.FrameData;for(var u=this.offsetX,d=this.offsetY,p=0,f=0;f?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",i.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",i.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",i.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",i.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",i.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",i.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",i.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",i.RetroFont.prototype.setFixedWidth=function(t,e){void 0===e&&(e="left"),this.fixedWidth=t,this.align=e},i.RetroFont.prototype.setText=function(t,e,i,s,n,r){this.multiLine=e||!1,this.customSpacingX=i||0,this.customSpacingY=s||0,this.align=n||"left",this.autoUpperCase=!r,t.length>0&&(this.text=t)},i.RetroFont.prototype.buildRetroFontText=function(){var t=0,e=0;if(this.clear(),this.multiLine){var s=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var n=0;n0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),t=0,this.align===i.RetroFont.ALIGN_RIGHT?t=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===i.RetroFont.ALIGN_CENTER&&(t=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(this._text,t,0,this.customSpacingX);this.requiresReTint=!0},i.RetroFont.prototype.pasteLine=function(t,e,i,s){for(var n=0;n=0&&(this.stamp.frame=this.grabData[t.charCodeAt(n)],this.renderXY(this.stamp,e,i,!1),(e+=this.characterWidth+s)>this.width))break},i.RetroFont.prototype.getLongestLine=function(){var t=0;if(this._text.length>0)for(var e=this._text.split("\n"),i=0;it&&(t=e[i].length);return t},i.RetroFont.prototype.removeUnsupportedCharacters=function(t){for(var e="",i=0;i=0||!t&&"\n"===s)&&(e=e.concat(s))}return e},i.RetroFont.prototype.updateOffset=function(t,e){if(this.offsetX!==t||this.offsetY!==e){for(var i=t-this.offsetX,s=e-this.offsetY,n=this.game.cache.getFrameData(this.stamp.key).getFrames(),r=n.length;r--;)n[r].x+=i,n[r].y+=s;this.buildRetroFontText()}},Object.defineProperty(i.RetroFont.prototype,"text",{get:function(){return this._text},set:function(t){var e;(e=this.autoUpperCase?t.toUpperCase():t)!==this._text&&(this._text=e,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(i.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(t){this.stamp.smoothed=t,this.buildRetroFontText()}}),i.Rope=function(t,e,s,n,r,o){this.points=o||[],this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.ROPE,PIXI.DisplayObjectContainer.call(this),this.texture=i.Cache.DEFAULT,this.uvs=new Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new Float32Array([0,0,100,0,100,100,0,100]),this.colors=new Float32Array([1,1,1,1]),this.indices=new Uint16Array([0,1,2,3]),o&&(this.vertices=new Float32Array(4*o.length),this.uvs=new Float32Array(4*o.length),this.colors=new Float32Array(2*o.length),this.indices=new Uint16Array(2*o.length)),this.dirty=!0,this.canvasPadding=0,this.drawMode=i.Rope.TRIANGLE_STRIP,i.Component.Core.init.call(this,t,e,s,n,r),this.refresh()},i.Rope.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Rope.prototype.constructor=i.Rope,i.Component.Core.install.call(i.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Rope.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Rope.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Rope.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Rope.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Rope.TRIANGLE_STRIP=0,i.Rope.TRIANGLES=1,i.Rope.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},i.Rope.prototype.reset=function(t,e){return i.Component.Reset.prototype.reset.call(this,t,e),this},i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=this.indices,s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o=t.length,a=1;a1&&1,o=Math.sqrt(s.x*s.x+s.y*s.y),a=this.texture.height/2,s.x/=o,s.y/=o,s.x*=a,s.y*=a,h[r]=n.x+s.x,h[r+1]=n.y+s.y,h[r+2]=n.x-s.x,h[r+3]=n.y-s.y,i=n;PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.Rope.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Rope.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Rope.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Rope.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Rope.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Rope.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Rope.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n0){var _=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,T=(l+c+u)/3,P=(d+p+f)/3,C=l-T,S=d-P,A=Math.sqrt(C*C+S*S);l=T+C/A*(A+_),d=P+S/A*(A+w),S=p-P,c=T+(C=c-T)/(A=Math.sqrt(C*C+S*S))*(A+_),p=P+S/A*(A+w),S=f-P,u=T+(C=u-T)/(A=Math.sqrt(C*C+S*S))*(A+_),f=P+S/A*(A+w)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*x+v*y+m*b-x*y-v*m-g*b,M=l*x+v*u+c*b-x*u-v*c-l*b,R=g*c+l*y+m*u-c*y-l*m-g*u,L=g*x*u+v*c*y+l*m*b-l*x*y-v*m*u-g*c*b,B=d*x+v*f+p*b-x*f-v*p-d*b,I=g*p+d*y+m*f-p*y-d*m-g*f,O=g*x*f+v*p*y+d*m*b-d*x*y-v*m*f-g*p*b;t.transform(M/E,B/E,R/E,I/E,L/E,O/E),t.drawImage(o,0,0),t.restore()},i.Rope.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;nh?m:h,l=y>l?y:l}if(c===-1/0||l===1/0)return PIXI.EmptyRectangle;var v=this._bounds;return v.x=c,v.width=h-c,v.y=u,v.height=l-u,this._currentBounds=v,v},Object.defineProperty(i.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(t){t&&"function"==typeof t?(this._hasUpdateAnimation=!0,this._updateAnimation=t):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(i.Rope.prototype,"segments",{get:function(){for(var t,e,s,n,r,o,a,h,l=[],c=0;c(_=y>(_=g>(_=p>_?p:_)?g:_)?y:_)?x:_,w=b>(w=v>(w=m>(w=f>w?f:w)?m:w)?v:w)?b:w;var C=this._bounds;return C.x=T,C.width=_-T,C.y=P,C.height=w-P,this._currentBounds=C,C},Object.defineProperty(i.TileSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TileSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var e=parseInt(RegExp.$1,10),i=parseInt(RegExp.$2,10);(10===e&&i>=11||e>10)&&(s.dolby=!0)}}catch(t){}}(),function(){var t=document.createElement("video");try{!!t.canPlayType&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(s.oggVideo=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.h264Video=!0,s.mp4Video=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(s.webmVideo=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(s.vp9Video=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.hlsVideo=!0))}catch(t){}}(),function(){var t,e=document.createElement("p"),i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var n in i)void 0!==e.style[n]&&(e.style[n]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(i[n]));document.body.removeChild(e),s.css3D=void 0!==t&&t.length>0&&"none"!==t}(),s.pixelRatio=window.devicePixelRatio||1,s.iPhone=-1!==navigator.userAgent.toLowerCase().indexOf("iphone"),s.iPhone4=2===s.pixelRatio&&s.iPhone,s.iPad=-1!==navigator.userAgent.toLowerCase().indexOf("ipad"),"undefined"!=typeof Int8Array?s.typedArray=!0:s.typedArray=!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(s.littleEndian=t(),s.LITTLE_ENDIAN=s.littleEndian),s.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==s.littleEndian&&e(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(s.vibration=!0),function(){s.canvas=!!window.CanvasRenderingContext2D||s.cocoonJS;try{s.localStorage=!!localStorage.getItem}catch(t){s.localStorage=!1}s.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),s.fileSystem=!!window.requestFileSystem,s.webGL=!!window.WebGLRenderingContext,s.worker=!!window.Worker,s.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,s.quirksMode="CSS1Compat"!==document.compatMode,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,s.getUserMedia=s.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,s.firefox&&s.firefoxVersion<21&&(s.getUserMedia=!1),!s.iOS&&(s.ie||s.firefox||s.chrome)&&(s.canvasBitBltShift=!0),(s.safari||s.mobileSafari)&&(s.canvasBitBltShift=!1)}(),function(){var t=i.CanvasPool.create(this,6,1),e=t.getContext("2d");e.fillStyle="rgba(10, 20, 30, 0.5)",e.fillRect(0,0,1,1);var n=e.getImageData(0,0,1,1);if(n){e.putImageData(n,1,0);var r=e.getImageData(1,0,1,1);s.canHandleAlpha=r.data[0]===n.data[0]&&r.data[1]===n.data[1]&&r.data[2]===n.data[2]&&r.data[3]===n.data[3]}e.globalCompositeOperation="multiply",s.canUseMultiply="multiply"===e.globalCompositeOperation,i.CanvasPool.removeByCanvas(t),PIXI.CanvasTinter.tintMethod=s.canUseMultiply?PIXI.CanvasTinter.tintWithMultiply:PIXI.CanvasTinter.tintWithPerPixel}(),function(){for(var t=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],e=document.createElement("div"),i=0;i=1)&&(s.touch=!0),(window.PointerEvent||window.MSPointerEvent||window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(s.mspointer=!0),s.cocoonJS||("onwheel"in window||s.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":s.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"))},i.Device.canPlayAudio=function(t){return!("mp3"!==t||!this.mp3)||(!("ogg"!==t||!this.ogg&&!this.opus)||(!("m4a"!==t||!this.m4a)||(!("opus"!==t||!this.opus)||(!("wav"!==t||!this.wav)||(!("webm"!==t||!this.webm)||!("mp4"!==t||!this.dolby))))))},i.Device.canPlayVideo=function(t){return!("webm"!==t||!this.webmVideo&&!this.vp9Video)||(!("mp4"!==t||!this.mp4Video&&!this.h264Video)||(!("ogg"!==t&&"ogv"!==t||!this.oggVideo)||!("mpeg"!==t||!this.hlsVideo)))},i.Device.needsTouchUnlock=function(){return!!(!this.cocoonJS&&(this.iOS||this.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)},i.Device.isAndroidStockBrowser=function(){var t=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return t&&t[1]<537},i.Canvas={create:function(t,e,s,n,r){e=e||256,s=s||256;var o=r?document.createElement("canvas"):i.CanvasPool.create(t,e,s);return"string"==typeof n&&""!==n&&(o.id=n),o.width=e,o.height=s,o.style.display="block",o},setBackgroundColor:function(t,e){return e=e||"rgb(0,0,0)",t.style.backgroundColor=e,t},setTouchAction:function(t,e){return e=e||"none",t.style.msTouchAction=e,t.style["ms-touch-action"]=e,t.style["touch-action"]=e,t},setUserSelect:function(t,e){return e=e||"none",t.style["-webkit-touch-callout"]=e,t.style["-webkit-user-select"]=e,t.style["-khtml-user-select"]=e,t.style["-moz-user-select"]=e,t.style["-ms-user-select"]=e,t.style["user-select"]=e,t.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",t},addToDOM:function(t,e,i){var s;return void 0===i&&(i=!0),e&&("string"==typeof e?s=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(s=e)),s||(s=document.body),i&&s.style&&(s.style.overflow="hidden"),s.appendChild(t),t},removeFromDOM:function(t){t.parentNode&&t.parentNode.removeChild(t)},setTransform:function(t,e,i,s,n,r,o){return t.setTransform(s,r,o,n,e,i),t},setSmoothingEnabled:function(t,e){var s=i.Canvas.getSmoothingPrefix(t);return s&&(t[s]=e),t},getSmoothingPrefix:function(t){var e=["i","webkitI","msI","mozI","oI"];for(var i in e){var s=e[i]+"mageSmoothingEnabled";if(s in t)return s}return null},getSmoothingEnabled:function(t){var e=i.Canvas.getSmoothingPrefix(t);if(e)return t[e]},setImageRenderingCrisp:function(t){for(var e=["-webkit-optimize-contrast","-moz-crisp-edges","crisp-edges","pixelated"],i=0;i0&&0==(t&t-1))return t;for(var e=1;e0&&0==(t&t-1)&&e>0&&0==(e&e-1)},random:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return Math.random()*(e-t)+t},between:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t},fuzzyEqual:function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)e-i},fuzzyCeil:function(t,e){return void 0===e&&(e=1e-4),Math.ceil(t-e)},fuzzyFloor:function(t,e){return void 0===e&&(e=1e-4),Math.floor(t+e)},average:function(){for(var t=0,e=arguments.length,i=0;i=i.Math.PI2-s?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=s:e=0?t:t+2*Math.PI},maxAdd:function(t,e,i){return Math.min(t+e,i)},minSub:function(t,e,i){return Math.max(t-e,i)},wrap:function(t,e,i){var s=i-e;if(s<=0)return 0;var n=(t-e)%s;return n<0&&(n+=s),n+e},wrapValue:function(t,e,i){return t=Math.abs(t),e=Math.abs(e),i=Math.abs(i),(t+e)%i},isOdd:function(t){return!!(1&t)},isEven:function(t){return!(1&t)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;et[i]&&(i=e);return t[i]},minProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;ie[s][t]&&(s=i);return e[s][t]},wrapAngle:function(t,e){return e?this.wrap(t,-Math.PI,Math.PI):this.wrap(t,-180,180)},linearInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return e<0?this.linear(t[0],t[1],s):e>1?this.linear(t[i],t[i-1],i-s):this.linear(t[n],t[n+1>i?i:n+1],s-n)},bezierInterpolation:function(t,e){for(var i=0,s=t.length-1,n=0;n<=s;n++)i+=Math.pow(1-e,s-n)*Math.pow(e,n)*t[n]*this.bernstein(s,n);return i},catmullRomInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return t[0]===t[i]?(e<0&&(n=Math.floor(s=i*(1+e))),this.catmullRom(t[(n-1+i)%i],t[n],t[(n+1)%i],t[(n+2)%i],s-n)):e<0?t[0]-(this.catmullRom(t[0],t[0],t[1],t[1],-s)-t[0]):e>1?t[i]-(this.catmullRom(t[i],t[i],t[i-1],t[i-1],s-i)-t[i]):this.catmullRom(t[n?n-1:0],t[n],t[i0?Math.ceil(t):Math.floor(t)},sinCosGenerator:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1);for(var n=e,r=i,o=s*Math.PI/t,a=[],h=[],l=0;l0?1:0},percent:function(t,e,i){return void 0===i&&(i=0),t>e||i>e?1:tt?0:(t-i)/e}},i.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},i.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e>>0,s=(e*=s)>>>0,s+=4294967296*(e-=s);return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},i.RandomDataGenerator.prototype.constructor=i.RandomDataGenerator,i.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},i.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new i.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new i.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new i.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new i.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null==this.nodes[0]||-1===(e=this.getIndex(t))){if(this.objects.push(t),this.objects.length>this.maxObjects&&this.levelthis.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.ythis.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof i.Rectangle)var e=this.objects,s=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,s=this.getIndex(t.body)}return this.nodes[0]&&(e=-1!==s?e.concat(this.nodes[s].retrieve(t)):(e=(e=(e=e.concat(this.nodes[0].retrieve(t))).concat(this.nodes[1].retrieve(t))).concat(this.nodes[2].retrieve(t))).concat(this.nodes[3].retrieve(t))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},i.QuadTree.prototype.constructor=i.QuadTree,i.Net=function(t){this.game=t},i.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},i.Net.prototype.constructor=i.Net,i.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:i.Easing.Power0,Power1:i.Easing.Power1,Power2:i.Easing.Power2,Power3:i.Easing.Power3,Power4:i.Easing.Power4,Linear:i.Easing.Linear.None,Quad:i.Easing.Quadratic.Out,Cubic:i.Easing.Cubic.Out,Quart:i.Easing.Quartic.Out,Quint:i.Easing.Quintic.Out,Sine:i.Easing.Sinusoidal.Out,Expo:i.Easing.Exponential.Out,Circ:i.Easing.Circular.Out,Elastic:i.Easing.Elastic.Out,Back:i.Easing.Back.Out,Bounce:i.Easing.Bounce.Out,"Quad.easeIn":i.Easing.Quadratic.In,"Cubic.easeIn":i.Easing.Cubic.In,"Quart.easeIn":i.Easing.Quartic.In,"Quint.easeIn":i.Easing.Quintic.In,"Sine.easeIn":i.Easing.Sinusoidal.In,"Expo.easeIn":i.Easing.Exponential.In,"Circ.easeIn":i.Easing.Circular.In,"Elastic.easeIn":i.Easing.Elastic.In,"Back.easeIn":i.Easing.Back.In,"Bounce.easeIn":i.Easing.Bounce.In,"Quad.easeOut":i.Easing.Quadratic.Out,"Cubic.easeOut":i.Easing.Cubic.Out,"Quart.easeOut":i.Easing.Quartic.Out,"Quint.easeOut":i.Easing.Quintic.Out,"Sine.easeOut":i.Easing.Sinusoidal.Out,"Expo.easeOut":i.Easing.Exponential.Out,"Circ.easeOut":i.Easing.Circular.Out,"Elastic.easeOut":i.Easing.Elastic.Out,"Back.easeOut":i.Easing.Back.Out,"Bounce.easeOut":i.Easing.Bounce.Out,"Quad.easeInOut":i.Easing.Quadratic.InOut,"Cubic.easeInOut":i.Easing.Cubic.InOut,"Quart.easeInOut":i.Easing.Quartic.InOut,"Quint.easeInOut":i.Easing.Quintic.InOut,"Sine.easeInOut":i.Easing.Sinusoidal.InOut,"Expo.easeInOut":i.Easing.Exponential.InOut,"Circ.easeInOut":i.Easing.Circular.InOut,"Elastic.easeInOut":i.Easing.Elastic.InOut,"Back.easeInOut":i.Easing.Back.InOut,"Bounce.easeInOut":i.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},i.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t,e){return e||(e=!1),this._tweens.some(function(i){return i.target===t&&(!e||i.isRunning&&!i.pendingDelete)})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},i.TweenManager.prototype.constructor=i.TweenManager,i.Tween=function(t,e,s){this.game=e,this.target=t,this.manager=s,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new i.Signal,this.onLoop=new i.Signal,this.onRepeat=new i.Signal,this.onChildComplete=new i.Signal,this.onComplete=new i.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=s.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},i.Tween.updateColor=function(t){i.Color.updateColor(t.target)},i.Tween.prototype={to:function(t,e,s,n,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).to(t,e,s,r,o,a)),n&&this.start(),this)},from:function(t,e,s,n,r,o,a){return void 0===e&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).from(t,e,s,r,o,a)),n&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),this.pendingDelete)return console.warn("Phaser.Tween.start cannot be called after Tween.stop"),this;if(null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(i=0;ithis.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(s=0;s0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t=this.startTime))return i.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var s in this.vEnd){var n=this.vStart[s],r=this.vEnd[s];Array.isArray(r)?this.parent.target[s]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[s]=n+(r-n)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():i.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction.call(this.interpolationContext,a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,i.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return i.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,i.TweenData.LOOPED}},i.TweenData.prototype.constructor=i.TweenData,i.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-i.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*i.Easing.Bounce.In(2*t):.5*i.Easing.Bounce.Out(2*t-1)+.5}}},i.Easing.Default=i.Easing.Linear.None,i.Easing.Power0=i.Easing.Linear.None,i.Easing.Power1=i.Easing.Quadratic.Out,i.Easing.Power2=i.Easing.Cubic.Out,i.Easing.Power3=i.Easing.Quartic.Out,i.Easing.Power4=i.Easing.Quintic.Out,i.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.updates=0,this.renders=0,this.fps=0,this.ups=0,this.rps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new i.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},i.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new i.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3){var t=this.now-this._timeLastSecond;this.fps=Math.round(1e3*this.frames/t),this.ups=Math.round(1e3*this.updates/t),this.rps=Math.round(1e3*this.renders/t),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0,this.updates=0,this.renders=0}},countUpdate:function(){this.advancedTiming&&this.updates++},countRender:function(){this.advancedTiming&&this.renders++},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(i.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),i.Time.prototype.constructor=i.Time,i.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new i.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},i.Timer.MINUTE=6e4,i.Timer.SECOND=1e3,i.Timer.HALF=500,i.Timer.QUARTER=250,i.Timer.prototype={create:function(t,e,s,n,r,o){var a=t=Math.round(t);0===this._now?a+=this.game.time.time:a+=this._now;var h=new i.TimerEvent(this,t,a,s,e,n,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.ticke.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i=e.tick)||e.pendingDelete)break;this._newTick=this._now+e.delay-(this._now-e.tick),this._newTick<0&&(this._newTick=this._now+e.delay),!0===e.loop?(e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):e.repeatCount>0?(e.repeatCount--,e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):(this._marked++,e.pendingDelete=!0,e.callback.apply(e.callbackContext,e.args)),this._i++}this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;ethis._now?this.nextTick-this._now:0}}),Object.defineProperty(i.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(i.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(i.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),i.Timer.prototype.constructor=i.Timer,i.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},i.TimerEvent.prototype.constructor=i.TimerEvent,i.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},i.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,s,n,r){return e=e||[],s=s||60,void 0===n&&(n=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new i.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,s,n),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;ithis._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},i.AnimationManager.prototype.constructor=i.AnimationManager,Object.defineProperty(i.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(i.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(i.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(i.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(i.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){var e;"number"==typeof t&&this._frameData&&(e=this._frameData.getFrame(t))&&(this.currentFrame=e,this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(i.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){var e;"string"==typeof t&&this._frameData&&(e=this._frameData.getFrameByName(t))?(this.currentFrame=e,this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame)):console.warn("Cannot set frameName: "+t)}}),i.Animation=function(t,e,s,n,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=n,this.name=s,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new i.Signal,this.onUpdate=null,this.onComplete=new i.Signal,this.onLoop=new i.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},i.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(s=0;s=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay?(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay):this._frameDiff=0,this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(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=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},i.Animation.prototype.constructor=i.Animation,Object.defineProperty(i.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(i.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(i.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(i.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(i.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(i.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new i.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),i.Animation.generateFrameNames=function(t,e,s,n,r){void 0===n&&(n="");var o=[],a="";if(e=s;h--)a=t+(a="number"==typeof r?i.Utils.pad(h.toString(),r,"0",1):h.toString())+n,o.push(a);return o},i.Frame=function(t,e,s,n,r,o){this.index=t,this.x=e,this.y=s,this.width=n,this.height=r,0!==this.width&&0!==this.height||console.warn('Phaser.Frame: Frame "'+this.name+'" has a width or height of zero'),this.name=o,this.centerX=Math.floor(n/2),this.centerY=Math.floor(r/2),this.distance=i.Math.distance(0,0,n,r),this.rotated=!1,this.trimmed=!1,this.sourceSizeW=n,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},i.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=i.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new i.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new i.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},i.Frame.prototype.constructor=i.Frame,i.FrameData=function(){this._frames=[],this._frameNames=[]},i.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new i.FrameData,e=0;ed||h<-d)return console.warn("Phaser.AnimationParser.spriteSheet: skipFrames = "+h.toString()+" is larger than total sprite number "+d.toString()),null;if(h<0&&(h=d+h),-1!==r&&(d=h+r),0===c||0===u||cc&&(f=o,g+=n+a);return p},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var s,n=new i.FrameData,r=e.frames,o=0;o tag")}},i.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{},compressedTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new i.Signal,this._cacheMap=[],this._cacheMap[i.Cache.CANVAS]=this._cache.canvas,this._cacheMap[i.Cache.IMAGE]=this._cache.image,this._cacheMap[i.Cache.TEXTURE]=this._cache.texture,this._cacheMap[i.Cache.SOUND]=this._cache.sound,this._cacheMap[i.Cache.TEXT]=this._cache.text,this._cacheMap[i.Cache.PHYSICS]=this._cache.physics,this._cacheMap[i.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[i.Cache.BINARY]=this._cache.binary,this._cacheMap[i.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[i.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[i.Cache.JSON]=this._cache.json,this._cacheMap[i.Cache.XML]=this._cache.xml,this._cacheMap[i.Cache.VIDEO]=this._cache.video,this._cacheMap[i.Cache.SHADER]=this._cache.shader,this._cacheMap[i.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this._pendingCount=0,this.onReady=new i.Signal,this._addImages()},i.Cache.CANVAS=1,i.Cache.IMAGE=2,i.Cache.TEXTURE=3,i.Cache.SOUND=4,i.Cache.TEXT=5,i.Cache.PHYSICS=6,i.Cache.TILEMAP=7,i.Cache.BINARY=8,i.Cache.BITMAPDATA=9,i.Cache.BITMAPFONT=10,i.Cache.JSON=11,i.Cache.XML=12,i.Cache.VIDEO=13,i.Cache.SHADER=14,i.Cache.RENDER_TEXTURE=15,i.Cache.DEFAULT=null,i.Cache.DEFAULT_KEY="__default",i.Cache.DEFAULT_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==",i.Cache.MISSING=null,i.Cache.MISSING_KEY="__missing",i.Cache.MISSING_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==",i.Cache.READY_TIMEOUT=1e3,i.Cache.prototype={addCompressedTextureMetaData:function(t,e,s,n){this.checkImageKey(t)&&this.removeImage(t);var r=s in i.LoaderParser?i.LoaderParser[s](n):n,o={key:t,url:e,data:r,base:new PIXI.BaseTexture(r,null,this.game.resolution),frame:new i.Frame(0,0,0,r.width,r.height,t),frameData:new i.FrameData,fileFormat:s};return o.frameData.addFrame(new i.Frame(0,0,0,r.width,r.height,e)),this._cache.image[t]=o,this._resolveURL(e,o),o},addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,s){this.checkImageKey(t)&&this.removeImage(t),!1===s.complete&&console.warn('Phaser.Cache.addImage: Image "'+t+"\" hasn't been retrieved yet");var n={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution),frame:new i.Frame(0,0,0,s.width,s.height,t),frameData:new i.FrameData};return n.frameData.addFrame(new i.Frame(0,0,0,s.width,s.height,e)),this._cache.image[t]=n,this._resolveURL(e,n),"__default"===t?i.Cache.DEFAULT=new PIXI.Texture(n.base):"__missing"===t&&(i.Cache.MISSING=new PIXI.Texture(n.base)),n},addImageAsync:function(t,e,i){var s=this,n=new Image;n.onload=function(){i.call(this,s.addImage(t,null,n)),s._removePending(),n.onload=null},this._addPending(),n.src=e},addDefaultImage:function(){this.addImageAsync(i.Cache.DEFAULT_KEY,i.Cache.DEFAULT_SRC,function(t){t.base.skipRender=!0,i.Cache.DEFAULT=new PIXI.Texture(t.base)})},addMissingImage:function(){this.addImageAsync(i.Cache.MISSING_KEY,i.Cache.MISSING_SRC,function(t){i.Cache.MISSING=new PIXI.Texture(t.base)})},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,s){return e.key=t,void 0===s&&(s=new i.FrameData).addFrame(e.textureFrame),this._cache.bitmapData[t]={data:e,frameData:s},e},addBitmapFont:function(t,e,s,n,r,o,a){var h={url:e,data:s,font:null,base:new PIXI.BaseTexture(s,null,this.game.resolution)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?i.LoaderParser.jsonBitmapFont(n,h.base,o,a,!1,this.game.resolution):i.LoaderParser.xmlBitmapFont(n,h.base,o,a,!1,this.game.resolution),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addBitmapFontFromAtlas:function(t,e,s,n,r,o,a){var h=this.getFrameByName(e,s);if(h){var l={font:null,base:this.getBaseTexture(e),frame:h};void 0===o&&(o=0),void 0===a&&(a=0);var c;"json"===r?(c=this.getJSON(n),l.font=i.LoaderParser.jsonBitmapFont(c,l.base,o,a,h,this.game.resolution)):(c=this.getXML(n),l.font=i.LoaderParser.xmlBitmapFont(c,l.base,o,a,h,this.game.resolution)),this._cache.bitmapFont[t]=l}},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new i.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,s,n,r,o,a,h,l){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var c={key:t,url:e,data:s,frameWidth:n,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(s,null,this.game.resolution),frameData:i.AnimationParser.spriteSheet(this.game,s,n,r,o,a,h,l)};this._cache.image[t]=c,this._resolveURL(e,c)},addTextureAtlas:function(t,e,s,n,r){var o={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution)};r===i.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=i.AnimationParser.XMLData(this.game,n,t):r===i.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=i.AnimationParser.JSONDataPyxel(this.game,n,t):Array.isArray(n.frames)?o.frameData=i.AnimationParser.JSONData(this.game,n,t):o.frameData=i.AnimationParser.JSONDataHash(this.game,n,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(i.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(i.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(i.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(i.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(i.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(i.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(i.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(i.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(i.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(i.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(i.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(i.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(i.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(i.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(i.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,i.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var s=this.getItem(t,i.Cache.IMAGE,"getImage");return null===s&&(s=this.getItem("__missing",i.Cache.IMAGE,"getImage")),e?s:s.data},getTextureFrame:function(t){return this.getItem(t,i.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,i.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,i.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,i.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,s){var n=this.getItem(t,i.Cache.PHYSICS,"getPhysicsData","data");if(null===n||void 0===e||null===e)return n;if(n[e]){var r=n[e];if(!r||!s)return r;for(var o in r)if((o=r[o]).fixtureKey===s)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+s+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,i.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,i.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,i.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,i.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var s=this.getItem(t,i.Cache.JSON,"getJSON","data");return s?e?i.Utils.extend(!0,Array.isArray(s)?[]:{},s):s:null},getXML:function(t){return this.getItem(t,i.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,i.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,i.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,i.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,s){void 0===s&&(s=i.Cache.IMAGE),this._cacheMap[s][t]&&(this._cacheMap[s][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){return(t=this._resolveURL(t))?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=i.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var s in this._cacheMap[t])"__default"!==s&&"__missing"!==s&&e.push(s);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.image[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t0?setTimeout(function(){t.isReady||(console.warn("Phaser.Cache: Still waiting for images after %s ms.",e),t._ready())},i.Cache.READY_TIMEOUT):this._ready()},_addPending:function(){this._pendingCount+=1},_removePending:function(){this._pendingCount-=1,this._checkReady()},_checkReady:function(){this.isReady&&this._ready()},_ready:function(){this._pendingCount=0,this.onReady.dispatch(this)}},i.Cache.prototype.constructor=i.Cache,Object.defineProperty(i.Cache.prototype,"isReady",{get:function(){return this._pendingCount<=0}}),i.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new i.Signal,this.onLoadComplete=new i.Signal,this.onPackComplete=new i.Signal,this.onFileStart=new i.Signal,this.onFileComplete=new i.Signal,this.onFileError=new i.Signal,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},i.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,i.Loader.TEXTURE_ATLAS_JSON_HASH=1,i.Loader.TEXTURE_ATLAS_XML_STARLING=2,i.Loader.PHYSICS_LIME_CORONA_JSON=3,i.Loader.PHYSICS_PHASER_JSON=4,i.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,i.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new i.Rectangle(0,0,1,t.height):new i.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r=e||t&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var n=this;setTimeout(function(){n.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.reset(),this.onLoadComplete.dispatch(),this.game.state&&this.game.state.loadComplete())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(e)for(var s=0;s=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},getVideoURL:function(t){for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s="error loading asset from URL "+(t.requestUrl||this.transformUrl(t.url,t));!i&&e&&(i=e.status),i&&(s=s+" ("+i+")"),this.asyncComplete(t,s)},fileComplete:function(t,e){var s=!0;switch(t.type){case"packfile":r=JSON.parse(e.responseText);t.data=r||{};break;case"texture":var n=/\.([^.]+)$/.exec(t.url.split("?",1)[0])[1].toLowerCase();null!==t.data?this.cache.addCompressedTextureMetaData(t.key,t.url,n,t.data):this.cache.addCompressedTextureMetaData(t.key,t.url,n,e.response);break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing,t.skipFrames);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(s=!1,t.format===i.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===i.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===i.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==i.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(s=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var r=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,r,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}s&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else(e=new ActiveXObject("Microsoft.XMLDOM")).async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(i.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return i.Math.clamp(t||0,0,100)}}),Object.defineProperty(i.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),i.Loader.prototype.constructor=i.Loader,i.LoaderParser={bitmapFont:function(t,e,i,s,n,r){return this.xmlBitmapFont(t,e,i,s,n,r)},xmlBitmapFont:function(t,e,i,s,n,r){null==r&&(r=1);var o={},a=t.getElementsByTagName("info")[0],h=t.getElementsByTagName("common")[0];o.font=a.getAttribute("face"),o.size=parseInt(a.getAttribute("size"),10),o.lineHeight=parseInt(h.getAttribute("lineHeight"),10)+s,o.chars={};for(var l=t.getElementsByTagName("char"),c=n?n.x:0,u=n?n.y:0,d=0;d=0){switch(r>=0&&r<=3?e="PVRTC":r>=7&&r<=11?e="S3TC":6===r&&(e="ETC1"),r){case 0:o=35841;break;case 1:o=35843;break;case 2:o=35840;break;case 3:o=35842;break;case 6:o=36196;break;case 7:o=33777;break;case 9:o=33778;break;case 11:o=33779;break;default:o=-1}n={complete:!0,fileFormat:"PVR",compressionAlgorithm:e,flags:i[1],pixelFormat:r,colorSpace:i[4],channelType:i[5],height:i[6],width:i[7],depth:i[8],numberOfSurfaces:i[9],numberOfFaces:i[10],numberOfMipmaps:i[11],metaDataSize:i[12],textureData:s.subarray(52+i[12],s.byteLength),glExtensionFormat:o}}return n},dds:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null;return 68===e[0]&&68===e[1]&&83===e[2]&&32===e[3]&&"DX10"===(s={complete:!0,fileFormat:"DDS",compressionAlgorithm:"S3TC",size:i[1],flags:i[2],height:i[3],width:i[4],pitch:i[5],depth:i[6],mipmapCount:i[7],formatSize:i[19],formatFlag:i[19],formatFourCC:[String.fromCharCode(e[84]),String.fromCharCode(e[85]),String.fromCharCode(e[86]),String.fromCharCode(e[87])].join(""),formatBitCount:i[21],formatRBitMask:i[22],formatGBitMask:i[23],formatBBitMask:i[24],formatABitMask:i[25],caps1:i[26],caps2:i[27],caps3:i[28],caps4:i[29],reserved2:i[30],DXGIFormat:null,resourceDimension:null,miscFlag:null,arraySize:null,textureData:e.subarray(i[1]+4,e.byteLength)}).formatFourCC&&(s.DXGIFormat=i[31],s.resourceDimension=i[32],s.miscFlag=i[33],s.arraySize=i[34],s.miscFlag=i[35]),s},ktx:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null,n=16+i[15]/4|0,r=i[n],o=i[7],a=0;if(171===e[0]&&75===e[1]&&84===e[2]&&88===e[3]&&32===e[4]&&49===e[5]&&49===e[6]&&187===e[7]&&13===e[8]&&10===e[9]&&26===e[10]&&10===e[11]&&[36196,35840,35841,35842,35843,33776,33777,33778,33779].indexOf(o)>=0){switch(o){case 36196:a="ETC1";break;case 35840:case 35841:case 35842:case 35843:a="PVRTC";break;case 33776:case 33777:case 33778:case 33779:a="S3TC"}s={complete:!0,fileFormat:"KTX",compressionAlgorithm:a,endianness:i[3],glType:i[4],glTypeSize:i[5],glFormat:i[6],glInternalFormat:i[7],glBaseInternalFormat:i[8],width:i[9],height:i[10],pixelDepth:i[11],numberOfArrayElements:i[12],numberOfFaces:i[13],numberOfMipmapLevels:i[14],bytesOfKeyValueData:i[15],keyAndValueByteSize:i[16],imageSize:r,textureData:e.subarray(4*(n+1),r+100)}}return s},pkm:function(t){var e=new Uint8Array(t),i=null;return 80===e[0]&&75===e[1]&&77===e[2]&&32===e[3]&&(i={complete:!0,fileFormat:"PKM",compressionAlgorithm:"ETC1",format:65535&(e[6]<<8|e[7]),width:65535&(e[8]<<8|e[9]),height:65535&(e[10]<<8|e[11]),originalWidth:65535&(e[12]<<8|e[13]),originalHeight:65535&(e[14]<<8|e[15]),textureData:e.subarray(16,e.length)}),i}},i.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},i.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},i.AudioSprite.prototype.constructor=i.AudioSprite,i.Sound=function(t,e,s,n,r){void 0===s&&(s=1),void 0===n&&(n=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=n,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this._globalVolume=1,this._markedToDelete=!1,this._removeFromSoundManager=!1,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=s,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new i.Signal,this.onPlay=new i.Signal,this.onPause=new i.Signal,this.onResume=new i.Signal,this.onLoop=new i.Signal,this.onStop=new i.Signal,this.onMute=new i.Signal,this.onMarkerComplete=new i.Signal,this.onFadeComplete=new i.Signal,this._volume=s,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},i.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop(),this._markedToDelete&&(this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode),this._removeFromSoundManager?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()))},update:function(){this.game.cache.checkSoundKey(this.key)?(this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))):this.destroy()},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){this.isPlaying&&!this.paused&&e!==this.volume&&(void 0===t&&(t=1e3),void 0!==e?(this.fadeTween=this.game.add.tween(this).to({volume:e},t,i.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)):console.warn("Phaser.Sound.fadeTo: No Volume Specified."))},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._globalVolume=t,this._sound.volume=this._globalVolume*this._volume)},destroy:function(t){void 0===t&&(t=!0),this._markedToDelete=!0,this._removeFromSoundManager=t,this.stop(),t?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())}},i.Sound.prototype.constructor=i.Sound,Object.defineProperty(i.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(i.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(i.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(i.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted?this._muteVolume=t:(this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=this._globalVolume*t))}}),i.SoundManager=function(t){this.game=t,this.onSoundDecode=new i.Signal,this.onVolumeChange=new i.Signal,this.onMute=new i.Signal,this.onUnMute=new i.Signal,this.onTouchUnlock=new i.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new i.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},i.SoundManager.prototype={boot:function(){var t=this.game.device,e=window.PhaserGlobal;if(t.iOS&&!1===t.webAudio&&(this.channels=1),e){if(!0===e.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===e.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(e&&e.audioContext)this.context=e.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||t.needsTouchUnlock()&&this.setTouchLock(),this.usingWebAudio&&t.chrome&&t.chromeVersion<=65&&console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. ')},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0)},setTouchUnlock:function(){this.touchLocked=!1,this._unlockSource=null,this.onTouchUnlock.dispatch()},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.setTouchUnlock();else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0),"suspended"===this._unlockSource.context.state&&this._unlockSource.context.resume()}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,s=this._parentBounds.height,n=this.getParentBounds(this._parentBounds),r=n.width!==e||n.height!==s,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,n),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottlee;return(h=h?s:!s)?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},i.ScaleManager.prototype.constructor=i.ScaleManager,Object.defineProperty(i.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(i.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(i.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(i.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),i.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.lineWidth=1,this.renderShadow=!0,this.currentColor=null,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1,this.isDisabled=!1,this._line=null,this._rect=null},i.Utils.Debug.prototype={boot:function(){this.game.renderType===i.CANVAS?this.context=this.game.context:(this.bmd=new i.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=i.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d")),this._line=new i.Line,this._rect=new i.Rectangle},resize:function(){this.bmd.resize(this.game.width,this.game.height),this.canvas.width=this.game.width,this.canvas.height=this.game.height},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e0)for(var e=0;e=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new i.Rectangle,layoutBounds:new i.Rectangle,documentBounds:new i.Rectangle},i.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},s=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(i.DOM,"scrollX",{get:e}),Object.defineProperty(i.DOM,"scrollY",{get:s}),Object.defineProperty(i.DOM.visualBounds,"x",{get:e}),Object.defineProperty(i.DOM.visualBounds,"y",{get:s}),Object.defineProperty(i.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(i.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var n=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(i.DOM.visualBounds,"width",{get:n}),Object.defineProperty(i.DOM.visualBounds,"height",{get:r}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:n}),Object.defineProperty(i.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(i.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(i.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(i.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(i.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(i.ArraySet.prototype,"next",{get:function(){return this.position=s||0===i)){null==i&&(i=1);for(var n=s-i,r=e;r0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=(t=i.ArrayUtils.transposeMatrix(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=i.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var s=0;s>>0:(t<<24|e<<16|s<<8|n)>>>0},unpackPixel:function(t,e,s,n){return void 0!==e&&null!==e||(e=i.Color.createColor()),void 0!==s&&null!==s||(s=!1),void 0!==n&&null!==n||(n=!1),i.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",s&&i.Color.RGBtoHSL(e.r,e.g,e.b,e),n&&i.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=i.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},hexToRGBArray:function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},RGBArrayToHex:function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},RGBtoHSL:function(t,e,s,n){n||(n=i.Color.createColor(t,e,s,1)),t/=255,e/=255,s/=255;var r=Math.min(t,e,s),o=Math.max(t,e,s);if(n.h=0,n.s=0,n.l=(o+r)/2,o!==r){var a=o-r;n.s=n.l>.5?a/(2-o-r):a/(o+r),o===t?n.h=(e-s)/a+(e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,s,n,r,o,a,h){var l={r:t||0,g:e||0,b:s||0,a:n||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return i.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toFixed()+","+t.g.toFixed()+","+t.b.toFixed()+","+t.a.toString()+")",t.color=i.Color.getColor(t.r,t.g,t.b),t.color32=i.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,s,n,r){return void 0===n&&(n=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+s).toString(16).slice(1):"0x"+i.Color.componentToHex(n)+i.Color.componentToHex(t)+i.Color.componentToHex(e)+i.Color.componentToHex(s)},hexToRGB:function(t){var e=i.Color.hexToColor(t);if(e)return i.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var s=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(s){var n=parseInt(s[1],16),r=parseInt(s[2],16),o=parseInt(s[3],16);e?(e.r=n,e.g=r,e.b=o):e=i.Color.createColor(n,r,o)}return e},webToColor:function(t,e){e||(e=i.Color.createColor());var s=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return s&&(e.r=~~Number(s[1]),e.g=~~Number(s[2]),e.b=~~Number(s[3]),e.a=void 0!==s[4]?Number(s[4]):1,i.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=i.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?i.Color.webToColor(t,e):(e.a=1,i.Color.hexToColor(t,e));if("number"==typeof t){var s=i.Color.getRGB(t);return e.r=s.r,e.g=s.g,e.b=s.b,e.a=s.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSVtoRGB(n/359,t,e));return s},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSLtoRGB(n/359,t,e));return s},interpolateColor:function(t,e,s,n,r,o){void 0===r&&(r=255),void 0===o&&(o=0);var a=i.Color.getRGB(t),h=i.Color.getRGB(e);if(0===o)var l=(h.red-a.red)*n/s+a.red,c=(h.green-a.green)*n/s+a.green,u=(h.blue-a.blue)*n/s+a.blue;if(1===o){var d,p=i.Color.RGBtoHSV(a.r,a.g,a.b),f=i.Color.RGBtoHSV(h.r,h.g,h.b),g=f.h-p.h;if(p.h>f.h){var m=f.h;f.h=p.h,p.h=m,g=-g,n=s-n}g>.5&&(p.h=p.h+1,d=((f.h-p.h)*n/s+p.h)%1),g<=.5&&(d=(f.h-p.h)*n/s+p.h);var y=(f.s-p.s)*n/s+p.s,v=(f.v-p.v)*n/s+p.v,x=i.Color.HSVtoRGB(d,y,v,x),l=x.r,c=x.g,u=x.b}return i.Color.getColor32(r,l,c,u)},interpolateColorWithRGB:function(t,e,s,n,r,o){var a=i.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(s-a.green)*o/r+a.green,c=(n-a.blue)*o/r+a.blue;return i.Color.getColor(h,l,c)},interpolateRGB:function(t,e,s,n,r,o,a,h){var l=(n-t)*h/a+t,c=(r-e)*h/a+e,u=(o-s)*h/a+s;return i.Color.getColor(l,c,u)},linear:function(t,e,i){return this.interpolateColor(t,e,1,i)},linearInterpolation:function(t,e){var s=i.Math.linear(0,t.length-1,e),n=t[Math.floor(s)],r=t[Math.ceil(s)];return this.linear(n,r,s%1)},getRandomColor:function(t,e,s){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===s&&(s=255),e>255||t>e)return i.Color.getColor(255,255,255);var n=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return i.Color.getColor32(s,n,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=i.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return i.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return i.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return i.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?i.Color.blendLinearBurn(t,2*e):i.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?i.Color.blendColorBurn(t,2*e):i.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?i.Color.blendDarken(t,2*e):i.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return i.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return i.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},i.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},i.Physics.ARCADE=0,i.Physics.P2JS=1,i.Physics.NINJA=2,i.Physics.BOX2D=3,i.Physics.CHIPMUNK=4,i.Physics.MATTERJS=5,i.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!i.Physics.hasOwnProperty("Arcade")||(this.arcade=new i.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&i.Physics.hasOwnProperty("Ninja")&&(this.ninja=new i.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&i.Physics.hasOwnProperty("P2")&&(this.p2=new i.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&i.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new i.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&i.Physics.hasOwnProperty("Matter")&&(this.matter=new i.Physics.Matter(this.game,this.config))},startSystem:function(t){t===i.Physics.ARCADE?this.arcade=new i.Physics.Arcade(this.game):t===i.Physics.P2JS?null===this.p2?this.p2=new i.Physics.P2(this.game,this.config):this.p2.reset():t===i.Physics.NINJA?this.ninja=new i.Physics.Ninja(this.game):t===i.Physics.BOX2D?null===this.box2d?this.box2d=new i.Physics.Box2D(this.game,this.config):this.box2d.reset():t===i.Physics.MATTERJS&&(null===this.matter?this.matter=new i.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,s){void 0===e&&(e=i.Physics.ARCADE),void 0===s&&(s=!1),e===i.Physics.ARCADE?this.arcade.enable(t):e===i.Physics.P2JS&&this.p2?this.p2.enable(t,s):e===i.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===i.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===i.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},i.Physics.prototype.constructor=i.Physics,i.Physics.Arcade=function(t){this.game=t,this.gravity=new i.Point,this.bounds=new i.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=i.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new i.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._total=0,this.setBoundsToWorld()},i.Physics.Arcade.prototype.constructor=i.Physics.Arcade,i.Physics.Arcade.SORT_NONE=0,i.Physics.Arcade.LEFT_RIGHT=1,i.Physics.Arcade.RIGHT_LEFT=2,i.Physics.Arcade.TOP_BOTTOM=3,i.Physics.Arcade.BOTTOM_TOP=4,i.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof i.Group?this.enable(t[s].children,e):(this.enableBody(t[s]),e&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],!0));else t instanceof i.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.Arcade.Body(t),t.parent&&t.parent instanceof i.Group&&t.parent.addToHash(t))},updateMotion:function(t){if(t.allowRotation){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed}t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&e.allowDrag&&(i-(n*=this.game.time.physicsElapsed)>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!0),this._total>0},collide:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!1),this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===i.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===i.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===i.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===i.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideObjects:function(t,e,i,s,n,r){if(!Array.isArray(t)&&Array.isArray(e))for(o=0;oa.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(t.body.bottoma.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,s,n,r,o)}}else{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(e);for(var c=this.quadTree.retrieve(t),h=0;hc.right)continue;if(c.x>a.right)break}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(a.bottomc.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,s,n,r)}}}}},collideGroupVsGroup:function(t,e,s,n,r,o){if(0!==t.length&&0!==e.length)for(var a=0;aa.bottom)&&(h.xa.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var s=i.Math.clamp(t.center.x,e.left,e.right),n=i.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-s)*(t.center.x-s)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},separateCircle:function(t,e,s){this.getOverlapX(t,e),this.getOverlapY(t,e);var n=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,n),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.center.x:e.center.x,y:t.isCircle?t.center.y:e.center.y,radius:t.isCircle?t.halfWidth:e.halfWidth};l.yh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.xh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.halfWidth+e.halfWidth-i.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(s||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.yMath.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x)>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0):t.deltaX()n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y)>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0):t.deltaY()n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,s,n,r,o){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(s);for(var a=new i.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c0&&(s=this.distanceBetween(t,e)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.setToPolar(n,e),n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},velocityFromAngle:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e,!0)},velocityFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerationFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(o,s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i,s){void 0===i&&(i=!1);var n,r;return s?(n=t.centerX-e.centerX,r=t.centerY-e.centerY):i?(n=t.world.x-e.world.x,r=t.world.y-e.world.y):(n=t.x-e.x,r=t.y-e.y),Math.sqrt(n*n+r*r)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},closest:function(t,e,i,s){for(var n=1/0,r=null,o=0,a=e.length;on&&(r=h,n=l)}return r},angleBetween:function(t,e,s){return void 0===s&&(s=!1),s?i.Point.angle(e.world,t.world):i.Point.angle(e,t)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},i.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=i.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new i.Point,this.position=new i.Point(t.x,t.y),this.prev=new i.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new i.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new i.Point,this.newVelocity=new i.Point,this.deltaMax=new i.Point,this.acceleration=new i.Point,this.allowDrag=!0,this.drag=new i.Point,this.allowGravity=!0,this.gravity=new i.Point,this.bounce=new i.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new i.Point(1e4,1e4),this.friction=new i.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=i.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.tilePadding=new i.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new i.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},i.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter())},updateCenter:function(){this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,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=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.none=!0,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.overlapR=0,this.overlapX=0,this.overlapY=0,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.updateCenter(),this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),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,this.updateCenter(),this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=this.velocity.atan()),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=i.LEFT:this.deltaX()>0&&(this.facing=i.RIGHT),this.deltaY()<0?this.facing=i.UP:this.deltaY()>0&&(this.facing=i.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.updateCenter(),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0,this.blocked.none=!1),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0,this.blocked.none=!1),!this.blocked.none},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.setToPolar(s,e),this.isMoving=!0,!0},moveTo:function(t,e,s){var n=e/(t/1e3);if(0===n)return!1;var r;return void 0===s?(r=this.angle,s=this.game.math.radToDeg(r)):r=this.game.math.degToRad(s),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new i.Line,this.moveEnd=new i.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===s||180===s?this.velocity.set(Math.cos(r)*n,0):90===s||270===s?this.velocity.set(0,Math.sin(r)*n):this.velocity.setToPolar(r,n),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,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(i,s),this.updateCenter(),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,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(e,i),this.updateCenter()):this.isCircle=!1},reset:function(t,e){this.stop(),this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this.updateBounds(),this.updateCenter()},stop:function(){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?i.Circle.contains(this,t,e):i.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},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},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof i.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(i.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),i.Physics.Arcade.Body.render=function(t,e,i,s,n){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,t.lineWidth=n||1,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.halfWidth,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},i.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},i.Physics.Arcade.Body.prototype.constructor=i.Physics.Arcade.Body,i.Physics.Arcade.TilemapCollision=function(){},i.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x-e.getTileOffsetX(),t.body.position.y-t.body.tilePadding.y-e.getTileOffsetY(),t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;ae.deltaAbsY()?l=-1:e.deltaAbsX()0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.getTileOffsetY();return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?(t.blocked.left=!0,t.blocked.none=!1):e>0&&(t.blocked.right=!0,t.blocked.none=!1),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?(t.blocked.up=!0,t.blocked.none=!1):e>0&&(t.blocked.down=!0,t.blocked.none=!1),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},i.Utils.mixinPrototype(i.Physics.Arcade.prototype,i.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,i.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new i.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new i.Signal,this.onBodyRemoved=new i.Signal,this.onSpringAdded=new i.Signal,this.onSpringRemoved=new i.Signal,this.onConstraintAdded=new i.Signal,this.onConstraintRemoved=new i.Signal,this.onContactMaterialAdded=new i.Signal,this.onContactMaterialRemoved=new i.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},i.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,s){void 0===e&&(e=!1),void 0===s&&(s=!0);var n=1;if(Array.isArray(t))for(n=t.length;n--;)t[n]instanceof i.Group?this.enable(t[n].children,e,s):(this.enableBody(t[n],e),s&&t[n].hasOwnProperty("children")&&t[n].children.length>0&&this.enable(t[n],e,!0));else t instanceof i.Group?this.enable(t.children,e,s):(this.enableBody(t,e),s&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);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.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.DistanceConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,s,n){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.GearConstraint(this,t,e,s,n));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),s=this.getBody(s),t&&s)return this.addConstraint(new i.Physics.P2.RevoluteConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,s,n,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.LockConstraint(this,t,e,s,n,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,s,n,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.PrismaticConstraint(this,t,e,s,n,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var s=new i.Physics.P2.Material(t);return this.materials.push(s),void 0!==e&&e.setMaterial(s),s},createContactMaterial:function(t,e,s){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var n=new i.Physics.P2.ContactMaterial(t,e,s);return this.addContactMaterial(n)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof i.Physics.P2.Body?t.data:t.body&&t.body.type===i.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,s,n){void 0===e&&(e=this.world.bodies),void 0===s&&(s=5),void 0===n&&(n=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof i.Physics.P2.Body&&(!n||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!n||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof i.Sprite&&e[a].hasOwnProperty("body")&&(!n||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,s)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var s=new i.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(s),t&&this.setCollisionGroup(t,s),s},setCollisionGroup:function(t,e){if(t instanceof i.Group)for(var s=0;s-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides?n+=u.width:((p=this.createBody(r,o,0,!1)).addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0)}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(i.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(i.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(i.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(i.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(i.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(i.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(i.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(i.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(i.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),i.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},i.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionGroup=t})},setMask:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionMask=t})},setSensor:function(t,e){this.getFixtures(e).forEach(function(e){e.sensor=t})},setMaterial:function(t,e){this.getFixtures(e).forEach(function(e){e.material=t})},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},i.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.PointProxy.prototype.constructor=i.Physics.P2.PointProxy,Object.defineProperty(i.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),i.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.InversePointProxy.prototype.constructor=i.Physics.P2.InversePointProxy,Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),i.Physics.P2.Body=function(t,e,s,n,r){e=e||null,s=s||0,n=n||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=i.Physics.P2JS,this.offset=new i.Point,this.data=new p2.Body({position:[this.world.pxmi(s),this.world.pxmi(n)],mass:r}),this.data.parent=this,this.velocity=new i.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new i.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new i.Point,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},i.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(r=0;r-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var n=this.getCollisionMask();if(void 0===i)for(var r=this.data.shapes.length-1;r>=0;r--)this.data.shapes[r].collisionMask=n;else i.collisionMask=n},collides:function(t,e,i,s){if(Array.isArray(t))for(r=0;r=0;r--)this.data.shapes[r].collisionMask=n;else s.collisionMask=n},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},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(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;np;n=0<=p?++d:--d)l=e.vertices[n],p2.vec2.rotate(u,l,t),c.push([(u[0]+a[0])*this.ppu,-(u[1]+a[1])*this.ppu]);this.drawConvex(h,c,e.triangles,16711680,i,r,this.settings.debugPolygons,[a[0]*this.ppu,-a[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)p=(c=e[l])[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return 2===(e=t.toString(16)).length?e:e+"0"}}),i.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1);var c={restLength:s=t.pxm(s),stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},i.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),i.Physics.P2.Material.prototype.constructor=i.Physics.P2.Material,i.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},i.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),i.Physics.P2.ContactMaterial.prototype.constructor=i.Physics.P2.ContactMaterial,i.Physics.P2.CollisionGroup=function(t){this.mask=t},i.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t;var a={distance:s=t.pxm(s),localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},i.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),i.Physics.P2.DistanceConstraint.prototype.constructor=i.Physics.P2.DistanceConstraint,i.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},i.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),i.Physics.P2.GearConstraint.prototype.constructor=i.Physics.P2.GearConstraint,i.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t;var o={localOffsetB:s=[t.pxm(s[0]),t.pxm(s[1])],localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},i.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),i.Physics.P2.LockConstraint.prototype.constructor=i.Physics.P2.LockConstraint,i.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t;var h={localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},i.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),i.Physics.P2.PrismaticConstraint.prototype.constructor=i.Physics.P2.PrismaticConstraint,i.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},i.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),i.Physics.P2.RevoluteConstraint.prototype.constructor=i.Physics.P2.RevoluteConstraint,i.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},i.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&tthis.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},i.Tile.prototype.constructor=i.Tile,Object.defineProperty(i.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(i.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(i.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(i.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(i.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(i.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),i.Tilemap=function(t,e,s,n,r,o){this.game=t,this.key=e;var a=i.TilemapParser.parse(this.game,e,s,n,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},i.Tilemap.CSV=0,i.Tilemap.TILED_JSON=1,i.Tilemap.NORTH=0,i.Tilemap.EAST=1,i.Tilemap.SOUTH=2,i.Tilemap.WEST=3,i.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,s,n,r,o,a){if(void 0===t)return null;void 0===s&&(s=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===s&&(s=32),0===n&&(n=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof i.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===i.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),console.log("Tilesets: ",this.tilesets),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new i.Tileset(t,a,s,n,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y1)for(u=0;uthis.layers.length)return console.warn('Tilemap.createLayer: Invalid layer ID given: "'+t+'"'),void console.log("Layers: ",this.layers);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===s||s<=0?s=Math.min(this.game.height,this.layers[r].heightInPixels):s>this.game.height&&(s=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",s),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=n.add(new i.TilemapLayer(this.game,this,r,e,s));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,s,n,r,o){void 0===o&&(o=this.game.world);{if(null===this.getLayerIndex(t)){for(var a,h={name:t,x:0,y:0,width:e,height:s,widthInPixels:e*n,heightInPixels:s*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;cthis.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height),(l=new i.TilemapLayer(this.game,this,this.layers.length-1,d,p)).name=t,o.add(l)}console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t)}},getIndex:function(t,e){for(var i=0;ie)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n-1&&this.collideIndexes.splice(n,1)}for(var r=0;r0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e-1},removeTile:function(t,e,s){if(s=this.getLayer(s),t>=0&&t=0&&e=0&&e=0&&s-1?this.layers[n].data[s][e].setCollision(!0,!0,!0,!0):this.layers[n].data[s][e].resetCollision(),this.layers[n].dirty=!0,this.calculateFaces(n),this.layers[n].data[s][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(r=this.layers[s].height-1;r>=0;r--)for(o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r=0&&t=0&&ethis.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},i.Tilemap.prototype.constructor=i.Tilemap,Object.defineProperty(i.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),i.TilemapLayer=function(t,e,s,n,r){n|=0,r|=0,i.Sprite.call(this,t,0,0),this.map=e,this.index=s,this.layer=e.layers[s],this.canvas=i.CanvasPool.create(this,n,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas,null,this.game.resolution))),this.type=i.TILEMAPLAYER,this.physicsType=i.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!0,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this.tileOffset=new i.Point(this.layer.offsetX||0,this.layer.offsetY||0),this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=i.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},i.TilemapLayer.prototype=Object.create(i.Sprite.prototype),i.TilemapLayer.prototype.constructor=i.TilemapLayer,i.TilemapLayer.prototype.preUpdateCore=i.Component.Core.preUpdate,i.TilemapLayer.sharedCopyCanvas=null,i.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=i.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},i.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},i.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y},i.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.TilemapLayer.prototype.destroy=function(){i.CanvasPool.remove(this),i.Component.Destroy.prototype.destroy.call(this)},i.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},i.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},i.TilemapLayer.prototype.getTileOffsetX=function(){return this.tileOffset.x||(this.fixedToCamera?0:this.position.x)},i.TilemapLayer.prototype.getTileOffsetY=function(){return this.tileOffset.y||(this.fixedToCamera?0:this.position.y)},i.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},i.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},i.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},i.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},i.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},i.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},i.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},i.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a=0;m++,v--,f+=c){m>=h&&(m-=h);var _=this.layer.data[m];for(g=b,y=n-i,p=x;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var w=_[g];if(w&&!(w.index<0)){var T=w.index,P=u[T];void 0===P&&(P=this.resolveTileset(T)),w.alpha===d||this.debug||(o.globalAlpha=w.alpha,d=w.alpha),P?w.rotation||w.flipped?(o.save(),o.translate(p+w.centerX,f+w.centerY),o.rotate(w.rotation),w.flipped&&o.scale(-1,1),P.draw(o,-w.centerX,-w.centerY,T),o.restore()):P.draw(o,p,f,T):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),w.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},i.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},i.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},i.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)=0;s++,r--,e+=f){s>=d&&(s-=d);var T=this.layer.data[s];for(i=_,n=m-g,t=x;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var P=T[i];!P||P.index<0||!P.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),P.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),P.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),P.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),P.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(i.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),i.TilemapParser={INSERT_NULL:!1,parse:function(t,e,s,n,r,o){if(void 0===s&&(s=32),void 0===n&&(n=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(s,n,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===i.Tilemap.CSV)return this.parseCSV(e,a.data,s,n);if(!a.format||a.format===i.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,s,n){for(var r=this.getEmptyData(),o=[],a=(e=e.trim()).split("\n"),h=a.length,l=0,c=0;c>>0;r.data=h,delete r.encoding}else if(r.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+r.name+"'");continue}k={name:r.name,x:r.x,y:r.y,width:r.width,height:r.height,widthInPixels:r.width*t.tilewidth,heightInPixels:r.height*t.tileheight,alpha:r.opacity,offsetX:r.offsetx,offsetY:r.offsety,visible:r.visible,properties:{},indexes:[],callbacks:[],bodies:[]};r.properties&&(k.properties=r.properties);for(var c,u,d,p=0,f=[],g=[],m=0,a=r.data.length;m536870912)switch(A>2147483648&&(A-=2147483648,d+=4),A>1073741824&&(A-=1073741824,d+=2),A>536870912&&(A-=536870912,d+=1),d){case 5:c=Math.PI/2;break;case 6:c=Math.PI;break;case 3:c=3*Math.PI/2;break;case 4:c=0,u=!0;break;case 7:c=Math.PI/2,u=!0;break;case 2:c=Math.PI,u=!0;break;case 1:c=3*Math.PI/2,u=!0}A>0?((F=new i.Tile(k,A,p,g.length,t.tilewidth,t.tileheight)).rotation=c,F.flipped=u,0!==d&&(F.flippedVal=d),f.push(F)):i.TilemapParser.INSERT_NULL?f.push(null):f.push(new i.Tile(k,-1,p,g.length,t.tilewidth,t.tileheight)),++p===r.width&&(g.push(f),p=0,f=[])}k.data=g,s.push(k)}e.layers=s;for(var y=[],n=0;n=0&&n+1=this.firstgid&&t=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(t=0;t=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._total>0&&this._counter>=this._total&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},i.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1),void 0===r&&(r=null);var o,a=0,h=t,l=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);athis.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},i.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),this.resetParticle(n,o,a),!0},i.Particles.Arcade.Emitter.prototype.getNextParticle=function(){for(var t=this.length;t--;){var e=this.next();if(!e.exists)return e}return null},i.Particles.Arcade.Emitter.prototype.resetParticle=function(t,e,i){var s=this.game.rnd;t.reset(e,i),t.angle=0,t.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(t):this.particleSendToBack&&this.sendToBack(t),this.autoScale?t.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?t.scale.set(s.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y?t.scale.set(s.realInRange(this._minParticleScale.x,this._maxParticleScale.x),s.realInRange(this._minParticleScale.y,this._maxParticleScale.y)):t.scale.set(this._minParticleScale.x,this._minParticleScale.y),this.autoAlpha?t.setAlphaData(this.alphaData):t.alpha=s.realInRange(this.minParticleAlpha,this.maxParticleAlpha),t.blendMode=this.blendMode;var n=t.body;n.updateBounds(),n.bounce.copyFrom(this.bounce),n.drag.copyFrom(this.particleDrag),null!=this.minAngle&&null!=this.maxAngle?this.game.physics.arcade.velocityFromAngle(this.minAngle===this.maxAngle?this.minAngle:s.between(this.minAngle,this.maxAngle),this.minSpeed===this.maxSpeed?this.minSpeed:s.between(this.minSpeed,this.maxSpeed),n.velocity):(n.velocity.x=s.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),n.velocity.y=s.between(this.minParticleSpeed.y,this.maxParticleSpeed.y)),n.angularVelocity=s.between(this.minRotation,this.maxRotation),n.gravity.copyFrom(this.gravity),n.angularDrag=this.angularDrag,t.onEmit()},i.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),i.Group.prototype.destroy.call(this,!0,!1)},i.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},i.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},i.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},i.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},i.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,s,n,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=0),void 0===n&&(n=i.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,s>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},s,n);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},i.Particles.Arcade.Emitter.prototype.setScale=function(t,e,s,n,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=1),void 0===n&&(n=1),void 0===r&&(r=0),void 0===o&&(o=i.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,s),this._maxParticleScale.set(e,n),this.autoScale=!1,r>0&&(t!==e||s!==n)){var h={x:t,y:s},l=this.game.make.tween(h).to({x:e,y:n},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},i.Particles.Arcade.Emitter.prototype.setAngle=function(t,e,i,s){return this.minAngle=t,this.maxAngle=e,null!=i&&(this.minSpeed=i),null!=s&&(this.maxSpeed=s),this},i.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"gravity",{get:function(){return this._gravity},set:function(t){"number"==typeof t?this._gravity.y=t:this._gravity=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"id",{get:function(){return this._id}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"output",{get:function(){return 1e3*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"lifespanOutput",{get:function(){return(0===this.lifespan?1/0:this.lifespan)*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"remainder",{get:function(){return this.maxParticles-this.lifespanOutput}}),i.Weapon=function(t,e){i.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new i.Rectangle(0,0,1,1),this.fireAngle=i.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new i.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=i.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=i.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new i.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new i.Signal,this.onKill=new i.Signal,this.onFireLimit=new i.Signal,this.trackedSprite=null,this.trackedPointer=null,this.multiFire=!1,this._hasFired=!1,this.trackRotation=!1,this.trackOffset=new i.Point,this._nextFire=0,this._tempNextFire=0,this._rotatedPoint=new i.Point},i.Weapon.prototype=Object.create(i.Plugin.prototype),i.Weapon.prototype.constructor=i.Weapon,i.Weapon.KILL_NEVER=0,i.Weapon.KILL_LIFESPAN=1,i.Weapon.KILL_DISTANCE=2,i.Weapon.KILL_WEAPON_BOUNDS=3,i.Weapon.KILL_CAMERA_BOUNDS=4,i.Weapon.KILL_WORLD_BOUNDS=5,i.Weapon.KILL_STATIC_BOUNDS=6,i.Weapon.prototype.createBullets=function(t,e,s,n){return void 0===t&&(t=1),void 0===n&&(n=this.game.world),this.bullets&&!this.bullets.game&&(this.bullets=null),this.bullets||(this.bullets=this.game.add.physicsGroup(i.Physics.ARCADE,n),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,s),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=s),this},i.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},i.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},i.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},i.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},i.Weapon.prototype.update=function(){this._bulletKillType===i.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},i.Weapon.prototype.postRender=function(){this.multiFire&&this._hasFired&&(this._hasFired=!1,this._nextFire=this._tempNextFire)},i.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},i.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},i.Weapon.prototype.fireMany=function(t,e){this.multiFire=!0;var i=[],s=this;return e||this.trackedSprite||this.trackedPointer?t.forEach(function(t){i.push(s.fire(e,null,null,t.x,t.y))}):t.forEach(function(t){i.push(s.fire(t))}),i},i.Weapon.prototype.fireOffset=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.fire(null,null,null,t,e)},i.Weapon.prototype.fire=function(t,e,s,n,r){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game.time.now0&&this.shots===this.fireLimit)return null;var o=this.bulletSpeed;0!==this.bulletSpeedVariance&&(o+=i.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.worldRotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(o+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y)),void 0!==n&&(this.fireFrom.x+=n),void 0!==r&&(this.fireFrom.y+=r);var a=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,h=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,l=this.trackRotation?this.trackedSprite.angle:this.fireAngle;null!==e&&null!==s&&(l=this.game.math.radToDeg(Math.atan2(s-h,e-a))),0!==this.bulletAngleVariance&&(l+=i.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var c=0,u=0;0===l||180===l?c=Math.cos(this.game.math.degToRad(l))*o:90===l||270===l?u=Math.sin(this.game.math.degToRad(l))*o:(c=Math.cos(this.game.math.degToRad(l))*o,u=Math.sin(this.game.math.degToRad(l))*o);var d=null;if(this.autoExpandBulletsGroup?(d=this.bullets.getFirstExists(!1,!0,a,h,this.bulletKey,this.bulletFrame)).data.bulletManager=this:d=this.bullets.getFirstExists(!1),d){if(d.reset(a,h),d.data.fromX=a,d.data.fromY=h,d.data.killType=this.bulletKillType,d.data.killDistance=this.bulletKillDistance,d.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===i.Weapon.KILL_LIFESPAN&&(d.lifespan=this.bulletLifespan),d.angle=l+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===d.animations.getAnimation(this.bulletAnimation)){var p=this.anims[this.bulletAnimation];d.animations.add(p.name,p.frames,p.frameRate,p.loop,p.useNumericIndex)}d.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(d.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(d.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);d.data.bodyDirty&&(this._data.customBody&&d.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),d.body.collideWorldBounds=this.bulletCollideWorldBounds,d.data.bodyDirty=!1),d.body.velocity.set(c,u),d.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y);var f=0;if(0!==this.bulletSpeedVariance){var g=this.fireRate;(g+=i.Math.between(-this.fireRateVariance,this.fireRateVariance))<0&&(g=0),f=this.game.time.now+g}else f=this.game.time.now+this.fireRate;this.multiFire?this._hasFired||(this._hasFired=!0,this._tempNextFire=f,this.shots++):(this._nextFire=f,this.shots++),this.onFire.dispatch(d,this,o),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return d},i.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},i.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},i.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},i.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},i.Weapon.prototype.setBulletFrames=function(t,e,s,n){return void 0===s&&(s=!0),void 0===n&&(n=!1),this.bulletFrames=i.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=s,this.bulletFrameRandom=n,this},i.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},i.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(i.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets&&(this.bullets.classType=this._bulletClass)}}),Object.defineProperty(i.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case i.Weapon.KILL_STATIC_BOUNDS:case i.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case i.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case i.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(i.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(i.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(i.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),i.Bullet=function(t,e,s,n,r){i.Sprite.call(this,t,e,s,n,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},i.Bullet.prototype=Object.create(i.Sprite.prototype),i.Bullet.prototype.constructor=i.Bullet,i.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},i.Bullet.prototype.update=function(){this.exists&&(this.data.killType>i.Weapon.KILL_LIFESPAN&&(this.data.killType===i.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=this.body.velocity.atan()),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},i.Video=function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=i.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new i.Signal,this.onChangeSource=new i.Signal,this.onComplete=new i.Signal,this.onAccess=new i.Signal,this.onError=new i.Signal,this.onTimeout=new i.Signal,this.onTouchUnlock=new i.Signal,this.playWhenUnlocked=!0,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._pendingChangeSource=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var n=this.game.cache.getVideo(e);n.isBlob?this.createVideoFromBlob(n.data):this.video=n.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else s&&this.createVideoFromURL(s,!1);this.video&&!s?(this.baseTexture=new PIXI.BaseTexture(this.video,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(i.Cache.DEFAULT.baseTexture.source,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new i.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,i.BitmapData&&(this.snapshot=new i.BitmapData(this.game,"",this.width,this.height)),this.game.device.needsTouchUnlock()?this.setTouchLock():n&&(n.locked=!1)},i.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return this._pendingChangeSource?this:(void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this)},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming)},setTouchLock:function(){this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.playWhenUnlocked&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return this.onTouchUnlock.dispatch(this),!0},grab:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null!==this.snapshot)return t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot;console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable")},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(i.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(i.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(i.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(i.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(i.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(i.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(i.Video.prototype,"playing",{get:function(){return!!this.video&&!(this.video.paused&&this.video.ended)}}),i.Video.prototype.constructor=i.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=i.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=i.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new i.Matrix),PIXI.TextureSilentFail=!0,PIXI.canUseNewCanvasBlendModes=function(){return i.Device.canUseMultiply},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=i),exports.Phaser=i):"undefined"!=typeof define&&define.amd?define("Phaser",e.Phaser=i):e.Phaser=i,i}.call(this); +//# sourceMappingURL=phaser.map \ No newline at end of file diff --git a/Iteration Sequence 2.2/sources.txt b/Iteration Sequence 2.2/sources.txt new file mode 100644 index 000000000..2a825b957 --- /dev/null +++ b/Iteration Sequence 2.2/sources.txt @@ -0,0 +1,5 @@ +Turret.png: Scribblenauts turret sprite. https://vignette.wikia.nocookie.net/scribblenauts/images/3/35/Turret_SU.png/revision/latest?cb=20130512101053 +Character.png: http://i2.photobucket.com/albums/y22/Avadan/Resources/VX/Spacece.png +Tank: https://kenney.nl/assets + +https://phaser.io/examples/v2/groups/remove \ No newline at end of file diff --git a/Iteration Sequence 2/assets/Attack.png b/Iteration Sequence 2/assets/Attack.png new file mode 100644 index 000000000..254b6eaf5 Binary files /dev/null and b/Iteration Sequence 2/assets/Attack.png differ diff --git a/Iteration Sequence 2/assets/Move.png b/Iteration Sequence 2/assets/Move.png new file mode 100644 index 000000000..31994c184 Binary files /dev/null and b/Iteration Sequence 2/assets/Move.png differ diff --git a/Iteration Sequence 2/assets/Play.png b/Iteration Sequence 2/assets/Play.png new file mode 100644 index 000000000..32ec4a7a7 Binary files /dev/null and b/Iteration Sequence 2/assets/Play.png differ diff --git a/Iteration Sequence 2/assets/Turret.png b/Iteration Sequence 2/assets/Turret.png new file mode 100644 index 000000000..6c0a3a042 Binary files /dev/null and b/Iteration Sequence 2/assets/Turret.png differ diff --git a/Iteration Sequence 2/assets/background.png b/Iteration Sequence 2/assets/background.png new file mode 100644 index 000000000..c80bf6d67 Binary files /dev/null and b/Iteration Sequence 2/assets/background.png differ diff --git a/Iteration Sequence 2/assets/character.png b/Iteration Sequence 2/assets/character.png new file mode 100644 index 000000000..1cb3e4d3c Binary files /dev/null and b/Iteration Sequence 2/assets/character.png differ diff --git a/Iteration Sequence 2/assets/grid.png b/Iteration Sequence 2/assets/grid.png new file mode 100644 index 000000000..b7815c713 Binary files /dev/null and b/Iteration Sequence 2/assets/grid.png differ diff --git a/Iteration Sequence 2/assets/play_button.json b/Iteration Sequence 2/assets/play_button.json new file mode 100644 index 000000000..174926e9c --- /dev/null +++ b/Iteration Sequence 2/assets/play_button.json @@ -0,0 +1,36 @@ +{"frames": [ + +{ + "filename": "down", + "frame": {"x":0,"y":142,"w":193,"h":71}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":193,"h":71}, + "sourceSize": {"w":193,"h":71} +}, +{ + "filename": "out", + "frame": {"x":0,"y":71,"w":193,"h":71}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":193,"h":71}, + "sourceSize": {"w":193,"h":71} +}, +{ + "filename": "over", + "frame": {"x":0,"y":0,"w":193,"h":71}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":193,"h":71}, + "sourceSize": {"w":193,"h":71} +}], +"meta": { + "app": "http://www.texturepacker.com", + "version": "1.0", + "image": "button_texture_atlas.png", + "format": "RGBA8888", + "size": {"w":193,"h":213}, + "scale": "1", + "smartupdate": "$TexturePacker:SmartUpdate:94df81041404a206a4e9cd597a1e3495$" +} +} diff --git a/Iteration Sequence 2/assets/preloader_background.jpg b/Iteration Sequence 2/assets/preloader_background.jpg new file mode 100644 index 000000000..feae1e6e1 Binary files /dev/null and b/Iteration Sequence 2/assets/preloader_background.jpg differ diff --git a/Iteration Sequence 2/assets/preloader_bar.png b/Iteration Sequence 2/assets/preloader_bar.png new file mode 100644 index 000000000..ee98e864e Binary files /dev/null and b/Iteration Sequence 2/assets/preloader_bar.png differ diff --git a/Iteration Sequence 2/assets/spot.png b/Iteration Sequence 2/assets/spot.png new file mode 100644 index 000000000..e30a50194 Binary files /dev/null and b/Iteration Sequence 2/assets/spot.png differ diff --git a/Iteration Sequence 2/assets/tank.png b/Iteration Sequence 2/assets/tank.png new file mode 100644 index 000000000..ad378c7a7 Binary files /dev/null and b/Iteration Sequence 2/assets/tank.png differ diff --git a/Iteration Sequence 2/assets/test.json b/Iteration Sequence 2/assets/test.json new file mode 100644 index 000000000..428eed420 --- /dev/null +++ b/Iteration Sequence 2/assets/test.json @@ -0,0 +1,100 @@ +{"frames": [ + +{ + "filename": "run00", + "frame": {"x":34,"y":128,"w":56,"h":60}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":2,"w":56,"h":60}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run01", + "frame": {"x":54,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run02", + "frame": {"x":54,"y":58,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run03", + "frame": {"x":0,"y":192,"w":34,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":11,"y":0,"w":34,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run04", + "frame": {"x":0,"y":64,"w":54,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":1,"y":0,"w":54,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run05", + "frame": {"x":196,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run06", + "frame": {"x":0,"y":0,"w":54,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":1,"y":0,"w":54,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run07", + "frame": {"x":140,"y":0,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run08", + "frame": {"x":34,"y":188,"w":50,"h":60}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":3,"y":2,"w":50,"h":60}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run09", + "frame": {"x":0,"y":128,"w":34,"h":64}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":11,"y":0,"w":34,"h":64}, + "sourceSize": {"w":56,"h":64} +}, +{ + "filename": "run10", + "frame": {"x":84,"y":188,"w":56,"h":58}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":3,"w":56,"h":58}, + "sourceSize": {"w":56,"h":64} +}], +"meta": { + "app": "http://www.texturepacker.com", + "version": "1.0", + "image": "running_bot.png", + "format": "RGBA8888", + "size": {"w":252,"h":256}, + "scale": "0.2", + "smartupdate": "$TexturePacker:SmartUpdate:fb56f261b1eb04e3215824426595f64c$" +} +} diff --git a/Iteration Sequence 2/assets/title.jpg b/Iteration Sequence 2/assets/title.jpg new file mode 100644 index 000000000..d416d3bb1 Binary files /dev/null and b/Iteration Sequence 2/assets/title.jpg differ diff --git a/Iteration Sequence 2/index.html b/Iteration Sequence 2/index.html new file mode 100644 index 000000000..4161c198a --- /dev/null +++ b/Iteration Sequence 2/index.html @@ -0,0 +1,142 @@ + + + + + Iteration Sequence 2 + + + + + + + + + + + + + + +
+
+

Iteration Sequence 2

+
    +
  • Originality: + What is original about your game? +
  • +
      +
    • + Game is work in progress. This is a game of zone control where players are actively trying to control multiple zones for economy and fighting advantage. +
    • +
    +
  • Technical Merit: + What is interesting about your game technology? +
  • +
      +
    • Players can select/deselect their own units.
    • +
    • Players can view stats for individual units.
    • +
    • (Soon)Players will be able to purchase additional units as well as build turrets.
    • +
    • (Soon)Players will be able to engage in combats and destroy enemy units.
    • +
    +
  • Prototype Postmortem: + What did you learn from this prototype? What was the easiest or hardest part of making it? +
  • +
      +
    • I am somewhat learning object oriented programming through javascript
    • +
    • Creating different keys for different function calls.
    • +
    • How to destory sprite/objects.
    • +
    • (Soon)How to balance the stats of the units
    • +
    +
  • Prototype Assets: + Did you make your prototype assets from scratch? Did you borrow them? Cite your sources here. + +
  • Prototype Closest Other Game: + Which other game most closely resembles your game? If you are borrowing code from a Phaser Example, you must say so here. If you borrow code from elsewhere, you must say so here. +
  • +
      +
    • Idea was inspired by starcraft but core mechanics should be original.
    • +
    +
  • High Concept: + A one-sentence summary of your game. +
  • +
      +
    • (Soon)Build turrets to reinforce your troops whlie conquering your oppoenents.
    • +
    +
  • Theme: + State which of the Storymatic themes you used. +
  • +
      +
    • Soldier
    • +
    +
  • Mandated Variety: + State which input, randomness, genre, and play style you used in this prototype. +
  • +
      +
    • Input: keyboard clicks + mouse clicks.
    • +
    • Randomness: (Soon) Most elements are deterministic.
    • +
    • Play style: Competitor, Explorer, Director. Trying their best to defeat the opponent. Player directs their units to a certain grid and chooses whether they want to attack. If this game were to be a real game the map would be a lot bigger allowing players to explore.
    • +
    • Genre: Real Time Strategy
    • +
    +
  • Prototype Goal: + What game mechanic is this prototype evaluating? +
  • +
      +
    • This prototype has only implemented the basic ideas of my physical prototype.
    • +
    • This prototype will help me with balancing the stats for each unit
    • +
    +
  • Player Experience Goals: + What experience do you want players to have when playing your game? +
  • +
      +
    • Enjoyment from getting stronger every turn.
    • +
    • Strategicaly placing units and fighting opponents.
    • +
    +
  • Gameplay: + A paragraph describing the actions the player can perform, the system dynamics, and the core mechanic. Include a concise explanation of the prototype’s inputs and their expected effects (how to play). You can also describe game play that is not in the prototype. You may include mock-up images for parts of the game not in the prototype. +
  • +
      +
    • To be announced.
    • +
    +
  • Strategies: + What player strategies do you expect will be effective at playing this game? +
  • +
      +
    • TBA
    • +
    +
  • Story/Setting/Premise: + A paragraph about the world your game is set in and who the characters are. What makes the game world and its occupants unique and interesting? Do the tokens represent something? If the game has a backstory, mention it here. If the game is abstract, then say so. + How will the dramatic tension interact with the gameplay tension? +
  • +
      +
    • No Story for this game for now.
    • +
    +
  • Target Audience: + A single sentence that describes the demographic you're trying to reach. +
  • +
      +
    • Ages 12+
    • +
    +
  • Play Time: + How long does your game take to play? +
  • +
      +
    • Depends on how fast player thinks. My estimate would be around 10 minutes.
    • +
    +
+ + \ No newline at end of file diff --git a/Iteration Sequence 2/js/Boot.js b/Iteration Sequence 2/js/Boot.js new file mode 100644 index 000000000..349a93294 --- /dev/null +++ b/Iteration Sequence 2/js/Boot.js @@ -0,0 +1,48 @@ +"use strict"; + +var GameStates = {}; + +GameStates.makeBoot = function( game ) { + return { + init: function () { + + // Unless you specifically know your game needs to support multi-touch I would recommend setting this to 1 + game.input.maxPointers = 1; + + // Phaser will automatically pause if the browser tab the game is in loses focus. You can disable that here: + game.stage.disableVisibilityChange = true; + + if (game.device.desktop) + { + // If you have any desktop specific settings, they can go in here + game.scale.pageAlignHorizontally = true; + } + else + { + // Same goes for mobile settings. + // In this case we're saying "scale the game, no lower than 480x260 and no higher than 1024x768" + game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; + game.scale.setMinMax(480, 260, 1024, 768); + game.scale.forceLandscape = true; + game.scale.pageAlignHorizontally = true; + } + + }, + + preload: function () { + + // Here we load the assets required for our Preloader state (in this case a background and a loading bar) + game.load.image('preloaderBackground', 'assets/preloader_background.jpg'); + game.load.image('preloaderBar', 'assets/preloader_bar.png'); + + }, + + create: function () { + + // By this point the preloader assets have loaded to the cache, we've set the game settings + // So now let's start the real preloader going + game.state.start('Preloader'); + + } + }; +}; diff --git a/Iteration Sequence 2/js/Game.js b/Iteration Sequence 2/js/Game.js new file mode 100644 index 000000000..712a3952f --- /dev/null +++ b/Iteration Sequence 2/js/Game.js @@ -0,0 +1,304 @@ +"use strict"; + +GameStates.makeGame = function( game, shared ) { + // Create your own variables. + var grid; + var attack = false; + var move = false; + var attack_button; + var move_button; + + var soldier; + var sniper; + var tank; + var turret; + + var selected; + + var esc_key; + var space_key; + var a_key; + var m_key; + var p_key; + + var player; + var cursors; + + var txt_style = {font: "20px Arial"}; + var stat_msg; + var stat_msg2; + var unit_msg; + var unit_msg2; + var event_msg; + var event_msg2; + + function createSoldier(soldier) + { + soldier.type = 'soldier'; + soldier.hp = 2; + soldier.atk = 1; + soldier.range = 1; + soldier.move = 1; + soldier.cost = 1; + soldier.diagonal = false; + + soldier.inputEnabled = true; + soldier.events.onInputDown.add( controlUnit, this ); + + //this.sprite = sprite; + // might be a better way to implement this. + //this.inputEnabled = true; + //this.events.onInputDown.add( displayStat, this ); + } + + function createSniper(sniper) + { + sniper.type = 'sniper'; + sniper.hp = 1; + sniper.atk = 1; + sniper.range = 1; + sniper.move = 1; + sniper.cost = 2; + sniper.diagonal = true; + + sniper.inputEnabled = true; + sniper.events.onInputDown.add( controlUnit, this ); + } + + function createTank(tank) + { + tank.type = 'tank'; + tank.hp = 5; + tank.atk = 1; + tank.range = 1; + tank.move = 1; + tank.cost = 4; + tank.diagonal = true; + + tank.inputEnabled = true; + tank.events.onInputDown.add( controlUnit, this ); + } + + function createTurret(turret) + { + turret.type = 'turret'; + turret.hp = 3; + turret.atk = 2; + turret.range = 1; + turret.move = 0; + turret.cost = 1; + turret.diagonal = true; + + turret.inputEnabled = true; + turret.events.onInputDown.add( controlUnit, this ); + } + + function createGrid() + { + grid = new Array(4); + + for (let i = 0; i < grid.length; i++) + { + grid[i] = new Array(grid.length); + + for (let j = 0; j < grid[i].length; j++) + { + grid[i][j] = game.add.image(500 + 110 * j, 100 + 110 * i, 'grid'); + } + } + + } + + function issueAttack() + { + //console.log('issueAttack'); + resetMove(); + + if (attack == false) + { + attack = true; + attack_button.loadTexture('attack', 1); + console.log('A is down'); + } + else + { + attack = false; + attack_button.loadTexture('attack', 0); + console.log('A is up'); + } + } + + function issueMove() + { + resetAttack(); + + if (move == false) + { + move = true; + move_button.loadTexture('move', 1); + } + else + { + move = false; + move_button.loadTexture('move', 0); + } + } + + function resetClick() + { + resetAttack(); + resetMove(); + selected = null; + stat_msg2.setText(''); + unit_msg2.setText(''); + } + + function resetAttack() + { + if (attack == true) + { + attack = false; + attack_button.loadTexture('attack', 0); + } + } + + function resetMove() + { + if (move == true) + { + move = false; + move_button.loadTexture('move', 0); + } + } + + function quitGame() { + // Here you should destroy anything you no longer need. + // Stop music, delete sprites, purge caches, free resources, all that good stuff. + + // Then let's go back to the main menu. + game.state.start('MainMenu'); + + } + + function bossFight() { + + if (shared.stat_remain == 0) + { + game.state.start('Boss'); + } + else + { + stat_msg2.setText("Consume all your stat points before\nfighting the boss.") + } + } + + function controlUnit(unit) + { + //console.log('controlUnit'); + //console.log(attack); + if (selected == null || (attack == false && move == false)) + { + resetAttack(); + resetMove(); + stat_msg2.setText(unit.type + '\n' + unit.hp + '\n' + unit.atk + '\n' + unit.range + '\n' + unit.move + '\n' + unit.cost); + unit_msg2.setText(unit.type); + selected = unit; + } + else if (attack == true) + { + dealDamage(selected, unit); + resetAttack(); + } + } + + function checkRange(arg1, arg2) + { + + } + + function dealDamage(arg1, arg2) + { + console.log(arg1 + ' Deal Damage to ' + arg2); + arg2.hp -= arg1.atk; + if (arg2.hp <= 0) + { + arg2.destroy(); + } + } + + function pauseGame() { + console.log('pauseGame'); + // Here you should destroy anything you no longer need. + // Stop music, delete sprites, purge caches, free resources, all that good stuff. + + // Then let's go back to the main menu. + game.state.start('Pause'); + + } + + return { + + create: function () { + + console.log('Test Game'); + + // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! + game.add.tileSprite(0, 0, 1024, 700, 'background'); + game.world.setBounds(0, 0, 1024, 700); + + cursors = game.input.keyboard.createCursorKeys(); + + createGrid(); + + soldier = game.add.sprite(400, 100, 'char', 7); + createSoldier(soldier); + sniper = game.add.sprite(400, 200, 'char', 1); + createSniper(sniper); + sniper = game.add.sprite(450, 200, 'char', 1); + createSniper(sniper); + tank = game.add.sprite(400, 300, 'tank', 0); + tank.scale.setTo(0.5, 0.5); + createTank(tank); + turret = game.add.sprite(400, 400, 'turret'); + turret.scale.setTo(0.5, 0.5); + createTurret(turret); + + attack_button = game.add.sprite(0, 500, 'attack', 0); + move_button = game.add.sprite(100, 500, 'move', 0); + + a_key = game.input.keyboard.addKey(Phaser.Keyboard.A); + m_key = game.input.keyboard.addKey(Phaser.Keyboard.M); + p_key = game.input.keyboard.addKey(Phaser.Keyboard.P); + esc_key = game.input.keyboard.addKey(Phaser.Keyboard.ESC); + space_key = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); + + stat_msg = game.add.text(0, 0, 'Stats\nHP: \nAttack: \nRange: \nMovement: \nCost:'); + stat_msg2 = game.add.text(250, 0 , 'Test'); + + unit_msg = game.add.text (0, 400, 'Selected: '); + unit_msg2 = game.add.text (150, 400); + + // Add some text using a CSS style. + // Center it in X, and position its top 15 pixels from the top of the world. + //var style = { font: "25px Verdana", fill: "#9999ff", align: "center" }; + //var text = game.add.text( game.world.centerX, 15, "Build something amazing.", style ); + //text.anchor.setTo( 0.5, 0.0 ); + + // When you click on the sprite, you go back to the MainMenu. + //bouncy.inputEnabled = true; + //bouncy.events.onInputDown.add( function() { quitGame(); }, this ); + }, + + update: function () { + // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! + a_key.onDown.addOnce(issueAttack, this); + m_key.onDown.addOnce(issueMove, this); + p_key.onDown.addOnce(pauseGame, this); + esc_key.onDown.addOnce(resetClick, this); + + + + //stat_change.onDown.add(changeStats, this); + } + }; +}; diff --git a/Iteration Sequence 2/js/MainMenu.js b/Iteration Sequence 2/js/MainMenu.js new file mode 100644 index 000000000..5616daf32 --- /dev/null +++ b/Iteration Sequence 2/js/MainMenu.js @@ -0,0 +1,41 @@ +"use strict"; + +GameStates.makeMainMenu = function( game, shared ) { + + var music = null; + var playButton = null; + + function startGame(pointer) + { + // Ok, the Play Button has been clicked or touched, so let's stop the music (otherwise it'll carry on playing) + //music.stop(); + console.log('Starting game'); + // And start the actual game + game.state.start('Game'); + } + + return { + + create: function () { + + // We've already preloaded our assets, so let's kick right into the Main Menu itself. + // Here all we're doing is playing some music and adding a picture and button + // Naturally I expect you to do something significantly better :) + + //music = game.add.audio('titleMusic'); + //music.play(); + + game.add.sprite(0, 0, 'preloaderBackground'); + playButton = game.add.button( 500, 300, 'playButton', startGame, null, 'out', 'over', 'down'); + playButton.anchor.setTo(0.5); + + }, + + update: function () { + + // Do some nice funky main menu effect here + + } + + }; +}; diff --git a/Iteration Sequence 2/js/Preloader.js b/Iteration Sequence 2/js/Preloader.js new file mode 100644 index 000000000..8dbc6669c --- /dev/null +++ b/Iteration Sequence 2/js/Preloader.js @@ -0,0 +1,72 @@ +"use strict"; + +GameStates.makePreloader = function( game ) +{ + + var background = null; + var preloadBar = null; + + var ready = false; + + return { + + preload: function () + { + // These are the assets we loaded in Boot.js + // A nice sparkly background and a loading progress bar + background = game.add.sprite(0, 0, 'preloaderBackground'); + preloadBar = game.add.sprite(500, 300, 'preloaderBar'); + preloadBar.anchor.setTo(0.5); + + // This sets the preloadBar sprite as a loader sprite. + // What that does is automatically crop the sprite from 0 to full-width + // as the files below are loaded in. + game.load.setPreloadSprite(preloadBar); + + // Here we load the rest of the assets our game needs. + // As this is just a Project Template I've not provided these assets, swap them for your own. + game.load.atlas('playButton', 'assets/Play.png', 'assets/play_button.json'); + // + lots of other required assets here + + // My Assets + game.load.image('background','assets/background.png'); + game.load.image('spot','assets/spot.png'); + game.load.image('grid','assets/grid.png'); + game.load.spritesheet('move', 'assets/Move.png', 80, 80); + game.load.spritesheet('attack', 'assets/Attack.png', 80, 80); + + game.load.spritesheet('char','assets/character.png', 32, 32); + game.load.spritesheet('tank','assets/tank.png', 92, 70); + game.load.image('turret','assets/Turret.png'); + + //game.load.spritesheet('tile','assets/sheet.png', 70, 70); + }, + + create: function () + { + // Once the load has finished we disable the crop because we're going to sit in the update loop for a short while as the music decodes + preloadBar.cropEnabled = false; + + }, + + update: function () + { + // You don't actually need to do this, but I find it gives a much smoother game experience. + // Basically it will wait for our audio file to be decoded before proceeding to the MainMenu. + // You can jump right into the menu if you want and still play the music, but you'll have a few + // seconds of delay while the mp3 decodes - so if you need your music to be in-sync with your menu + // it's best to wait for it to decode here first, then carry on. + + // If you don't have any music in your game then put the game.state.start line into the create function and delete + // the update function completely. + + + if (ready == false) + { + ready = true; + game.state.start('MainMenu'); + } + } + + }; +}; diff --git a/Iteration Sequence 2/js/game_boss.js b/Iteration Sequence 2/js/game_boss.js new file mode 100644 index 000000000..be45a9ec9 --- /dev/null +++ b/Iteration Sequence 2/js/game_boss.js @@ -0,0 +1,259 @@ +"use strict"; + +GameStates.makeBoss = function( game, shared ) { + // Create your own variables. + var boss_bg; + + var player; + var zombie; + var fire; + var boundaries; + + var stat_text; + var stat_text2; + var stat_text3; + var tip_text; + + var player_hp = 50; + var enemy_hp = 100; + var tookDamage = false; + var inputEnabled = false; + + /* + var timer; + var fire_group; + function Fire(game) { + + var x = 600; + var y = game.rnd.between(400, 600); + + Phaser.Sprite.call(this, game, x, y, 'fire', 1); + + game.physics.arcade.enable(this); + }*/ + + function returnMenu() { + + shared.stat_strength = 0; + shared.stat_resist = 0; + shared.stat_speed = 0; + shared.stat_luck = 0; + shared.stat_remain = 7; + + player_hp = 50; + enemy_hp = 100; + tookDamage = false; + inputEnabled = false; + + game.state.start('MainMenu'); + } + + function stopGravity(obj1, obj2) + { + obj1.body.gravity.y = 0; + //console.log(obj1.y); + } + + function dealDamage(obj1, obj2) + { + var bonusDamage; + switch (shared.stat_strength) + { + case 1: + bonusDamage = 1; + break; + case 2: + bonusDamage = 2; + break; + case 3: + bonusDamage = 4; + break; + default: + bonusDamage = 0; + break; + } + + enemy_hp = enemy_hp - 5 - bonusDamage; + + stat_text3.setText(enemy_hp); + zombieAttack(); + } + + function zombieAttack() + { + player.x = 100; + } + + function takeDamage(obj1, obj2) + { + var bonusResist; + + //console.log('TD: ' + tookDamage); + if (tookDamage == false) + { + //console.log('SSR: ' + shared.stat_resist); + switch (shared.stat_resist) + { + case 1: + bonusResist = 1; + break; + case 2: + bonusResist = 2; + break; + case 3: + bonusResist = 4; + break; + default: + bonusResist = 0; + break; + } + + //console.log('Player hp = ' + player_hp); + player_hp = player_hp - (8 - bonusResist); + //console.log('Collision: hp = ' + player_hp); + stat_text2.setText(player_hp); + tookDamage = true; + fire.body.checkCollision.none = true; + } + + } + + /* + function spawnFire() + { + fire_group.add(new Fire(game)); + } + */ + + return { + + create: function () { + + boss_bg = game.add.tileSprite(0, 0, 1000, 600, 'boss_bg'); + //game.add.tileSprite(0, 0, 300, 250, 'stat'); + //game.add.tileSprite(400, 0, 300, 250, 'stat'); + //stat_text = game.add.text(0, 0, 'Hit Points:\nStrength: \nResistance: \nSpeed: \nLuck: '); + //stat_text2 = game.add.text(250, 0, player_hp + '\n' + shared.stat_strength + '\n' + shared.stat_resist + '\n' + shared.stat_speed + '\n' + shared.stat_luck); + stat_text = game.add.text(0, 0, 'Hit Points: '); + stat_text2 = game.add.text(250, 0, player_hp); + tip_text = game.add.text(0, 150, 'Use the arrow keys to move and jump.\nCollide with the zombie to deal damage.\nPlayers will lose hp if they collide with the fire.'); + + game.add.text(600, 0, 'Hit Points: '); + stat_text3 = game.add.text(750, 0, enemy_hp); + + zombie = game.add.sprite(700, 450, 'zombie', 0); + zombie.anchor.setTo(0.5, 0.5); + zombie.scale.setTo(1, 1); + + player = game.add.sprite(100, 450, 'man', 0); + player.anchor.setTo(0.5, 0.5); + player.scale.setTo(1, 1); + + zombie.animations.add('run', [6,7,8,12,13,14]) + zombie.animations.play('run', 8, true); + + player.animations.add('run', [0,9]); + player.animations.play('run', 8, true); + + boundaries = game.add.sprite(0, 510, 'boundaries', 0); + + fire = game.add.sprite(600, 450, 'fire', 0); + + game.physics.startSystem(Phaser.Physics.ARCADE); + + // Set the world (global) gravity + game.physics.arcade.gravity.y = 1500; + + // Enable physics on those sprites + game.physics.enable( [ player, zombie, boundaries, fire ], Phaser.Physics.ARCADE); + + player.body.collideWorldBounds = true; + player.body.bounce.y = 0; + + zombie.body.allowGravity = false; + zombie.body.immovable = true; + zombie.body.collideWorldBounds = true; + //zombie.body.bounce.y = 0; + zombie.body.setSize(60, 85, 10, 25); + + + boundaries.body.allowGravity = false; + boundaries.body.collideWolrdBounds = true; + boundaries.visible = false; + boundaries.body.immovable = true; + + /* + timer = game.time.create(); + timer.loop(2000, spawnFire(), this); + fire_group = game.add.group(); + timer.start(); + */ + + fire.body.gravity.y = 0; + fire.body.allowGravity = false; + fire.body.velocity.x = -200; + fire.body.checkCollision.up = false; + fire.body.checkCollision.down = false; + + }, + + update: function () { + + player.body.velocity.x = 0; + fire.body.velocity.x = -200; + + game.physics.arcade.collide(player, boundaries, stopGravity, null, this); + game.physics.arcade.collide(zombie, boundaries, stopGravity, null, this); + game.physics.arcade.collide(player, fire, takeDamage, null, this); + game.physics.arcade.collide(player, zombie, dealDamage, null, this); + + + if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) + { + player.body.velocity.x = -(150 * (1 + shared.stat_speed)); + } + else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) + { + player.body.velocity.x = 150 * (1 + shared.stat_speed); + } + + if (game.input.keyboard.isDown(Phaser.Keyboard.UP) && player.y >= 455) + { + //player.body.gravity.y; + player.body.velocity.y = -500 - 50 * shared.stat_speed; + } + + if (fire.x < -200) + { + fire.x = 600; + tookDamage = false; + fire.body.checkCollision.none = false; + } + + if (player_hp <= 0 && inputEnabled == false) + { + tip_text.setText('You lose. Click ESC to return to main menu.'); + inputEnabled = true; + + } + else if (enemy_hp <= 0 && inputEnabled == false) + { + tip_text.setText('You win. Click ESC to return to main menu.'); + inputEnabled = true; + + } + + if (inputEnabled == true && game.input.keyboard.isDown(Phaser.Keyboard.ESC)) + { + returnMenu(); + } + + if (inputEnabled == true) + { + player.body.moves = false; + fire.body.moves = false; + } + + } + }; +}; diff --git a/Iteration Sequence 2/js/main.js b/Iteration Sequence 2/js/main.js new file mode 100644 index 000000000..994fe4ba0 --- /dev/null +++ b/Iteration Sequence 2/js/main.js @@ -0,0 +1,31 @@ +"use strict"; + +window.onload = function() +{ + + // Create your Phaser game and inject it into the 'game' div. + // We did it in a window.onload event, but you can do it anywhere (requireJS load, anonymous function, jQuery dom ready, - whatever floats your boat) + var game = new Phaser.Game( 1024, 700, Phaser.AUTO, 'game' ); + + // Add the States your game has. + // You don't have to do this in the html, it could be done in your Boot state too, but for simplicity I'll keep it here. + + // An object for shared variables, so that them main menu can show + // the high score if you want. + var shared = + { + stat_type: -1, + } + + game.state.add( 'Boot', GameStates.makeBoot( game ) ); + game.state.add( 'Preloader', GameStates.makePreloader( game ) ); + game.state.add( 'MainMenu', GameStates.makeMainMenu( game, shared ) ); + game.state.add( 'Game', GameStates.makeGame( game, shared ) ); + game.state.add( 'Boss', GameStates.makeBoss( game, shared ) ); + game.state.add( 'Pause', GameStates.makePause( game, shared ) ); + + + // Now start the Boot state. + game.state.start('Boot'); + +}; diff --git a/Iteration Sequence 2/js/pause.js b/Iteration Sequence 2/js/pause.js new file mode 100644 index 000000000..a09b111b7 --- /dev/null +++ b/Iteration Sequence 2/js/pause.js @@ -0,0 +1,40 @@ +"use strict"; + +GameStates.makePause = function( game, shared ) { + // Create your own variables. + var stat_text; + var instruction; + var txt_style = {fill: "#ffffff"}; + var tip_text; + + var esc_key; + + function returnGame() { + // Here you should destroy anything you no longer need. + // Stop music, delete sprites, purge caches, free resources, all that good stuff. + + // Then let's go back to the main menu. + game.state.start('Game'); + + } + + + + return { + + create: function () { + + stat_text = game.add.text(0, 0, 'Pause Screen', txt_style); + instruction = game.add.text(300, 0, 'Click ESC to return to Game.', txt_style); + tip_text = game.add.text(0, 300, 'TIPS' , txt_style); + + + esc_key = game.input.keyboard.addKey(Phaser.Keyboard.ESC); + esc_key.onDown.addOnce(returnGame, this); + }, + + update: function () { + + } + }; +}; diff --git a/Iteration Sequence 2/js/phaser.js b/Iteration Sequence 2/js/phaser.js new file mode 100644 index 000000000..3bac171a7 --- /dev/null +++ b/Iteration Sequence 2/js/phaser.js @@ -0,0 +1,107825 @@ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +* +* @overview +* +* Phaser - http://phaser.io +* +* v2.10.0 "2018-01-18" - Built: Thu Jan 18 2018 16:35:03 +* +* By Richard Davey http://www.photonstorm.com @photonstorm +* +* Phaser is a fun, free and fast 2D game framework for making HTML5 games +* for desktop and mobile web browsers, supporting Canvas and WebGL rendering. +* +* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23 +* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe +* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com +* +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate. +* +* Follow development at http://phaser.io and on our forum +* +* "If you want your children to be intelligent, read them fairy tales." +* "If you want them to be more intelligent, read them more fairy tales." +* -- Albert Einstein +*/ + +/** + * The MIT License (MIT) + * + * Copyright (c) 2015 p2.js authors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=0 && s<=1 && t>=0 && t<=1); +}; + + +},{"./Scalar":4}],2:[function(_dereq_,module,exports){ +module.exports = Point; + +/** + * Point related functions + * @class Point + */ +function Point(){}; + +/** + * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. + * @static + * @method area + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +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 = []; + +/** + * Check if three points are collinear + * @method collinear + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. + * @return {Boolean} + */ +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 angle < thresholdAngle; + } +}; + +Point.sqdist = function(a,b){ + var dx = b[0] - a[0]; + var dy = b[1] - a[1]; + return dx * dx + dy * dy; +}; + +},{}],3:[function(_dereq_,module,exports){ +var Line = _dereq_("./Line") +, Point = _dereq_("./Point") +, Scalar = _dereq_("./Scalar") + +module.exports = Polygon; + +/** + * Polygon class. + * @class Polygon + * @constructor + */ +function Polygon(){ + + /** + * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] + * @property vertices + * @type {Array} + */ + this.vertices = []; +} + +/** + * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. + * @method at + * @param {Number} i + * @return {Array} + */ +Polygon.prototype.at = function(i){ + var v = this.vertices, + s = v.length; + return v[i < 0 ? i % s + s : i % s]; +}; + +/** + * Get first vertex + * @method first + * @return {Array} + */ +Polygon.prototype.first = function(){ + return this.vertices[0]; +}; + +/** + * Get last vertex + * @method last + * @return {Array} + */ +Polygon.prototype.last = function(){ + return this.vertices[this.vertices.length-1]; +}; + +/** + * Clear the polygon data + * @method clear + * @return {Array} + */ +Polygon.prototype.clear = function(){ + this.vertices.length = 0; +}; + +/** + * Append points "from" to "to"-1 from an other polygon "poly" onto this one. + * @method append + * @param {Polygon} poly The polygon to get points from. + * @param {Number} from The vertex index in "poly". + * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. + * @return {Array} + */ +Polygon.prototype.append = function(poly,from,to){ + if(typeof(from) == "undefined") throw new Error("From is not given!"); + if(typeof(to) == "undefined") throw new Error("To is not given!"); + + if(to-1 < from) throw new Error("lol1"); + if(to > poly.vertices.length) throw new Error("lol2"); + if(from < 0) throw new Error("lol3"); + + for(var i=from; i v[br][0])) { + br = i; + } + } + + // reverse poly if clockwise + if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { + this.reverse(); + } +}; + +/** + * Reverse the vertices in the polygon + * @method 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; +}; + +/** + * Check if a point in the polygon is a reflex point + * @method isReflex + * @param {Number} i + * @return {Boolean} + */ +Polygon.prototype.isReflex = function(i){ + return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); +}; + +var tmpLine1=[], + tmpLine2=[]; + +/** + * Check if two vertices in the polygon can see each other + * @method canSee + * @param {Number} a Vertex index 1 + * @param {Number} b Vertex index 2 + * @return {Boolean} + */ +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) { // for each edge + if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges + 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))) { // if diag intersects an edge + 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) < dist) { // if edge is blocking visibility to b + return false; + } + } + } + + return true; +}; + +/** + * Copy the polygon from vertex i to vertex j. + * @method copy + * @param {Number} i + * @param {Number} j + * @param {Polygon} [targetPoly] Optional target polygon to save in. + * @return {Polygon} The resulting copy. + */ +Polygon.prototype.copy = function(i,j,targetPoly){ + var p = targetPoly || new Polygon(); + p.clear(); + if (i < j) { + // Insert all vertices from i to j + for(var k=i; k<=j; k++) + p.vertices.push(this.vertices[k]); + + } else { + + // Insert vertices 0 to j + for(var k=0; k<=j; k++) + p.vertices.push(this.vertices[k]); + + // Insert vertices i to end + for(var k=i; k 0) + return this.slice(edges); + else + return [this]; +}; + +/** + * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. + * @method slice + * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() + * @return {Array} + */ +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; i maxlevel){ + console.warn("quickDecomp: max level ("+maxlevel+") reached."); + return result; + } + + for (var i = 0; i < this.vertices.length; ++i) { + if (poly.isReflex(i)) { + reflexVertices.push(poly.vertices[i]); + upperDist = lowerDist = Number.MAX_VALUE; + + + for (var j = 0; j < this.vertices.length; ++j) { + if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge + p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection + if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly + d = Point.sqdist(poly.vertices[i], p); + if (d < lowerDist) { // keep only the closest intersection + lowerDist = d; + lowerInt = p; + lowerIndex = j; + } + } + } + if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); + if (Point.left(poly.at(i - 1), poly.at(i), p)) { + d = Point.sqdist(poly.vertices[i], p); + if (d < upperDist) { + upperDist = d; + upperInt = p; + upperIndex = j; + } + } + } + } + + // if there are no vertices to connect to, choose a point in the middle + if (lowerIndex == (upperIndex + 1) % this.vertices.length) { + //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); + p[0] = (lowerInt[0] + upperInt[0]) / 2; + p[1] = (lowerInt[1] + upperInt[1]) / 2; + steinerPoints.push(p); + + if (i < upperIndex) { + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); + lowerPoly.append(poly, i, upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + if (lowerIndex != 0){ + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); + upperPoly.append(poly,lowerIndex,poly.vertices.length); + } + //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); + lowerPoly.append(poly,i,poly.vertices.length); + } + //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); + lowerPoly.append(poly,0,upperIndex+1); + lowerPoly.vertices.push(p); + upperPoly.vertices.push(p); + //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); + upperPoly.append(poly,lowerIndex,i+1); + } + } else { + // connect to the closest point within the triangle + //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); + + if (lowerIndex > upperIndex) { + upperIndex += this.vertices.length; + } + closestDist = Number.MAX_VALUE; + + if(upperIndex < lowerIndex){ + return result; + } + + for (var j = lowerIndex; j <= upperIndex; ++j) { + if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) + && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { + d = Point.sqdist(poly.at(i), poly.at(j)); + if (d < closestDist) { + closestDist = d; + closestIndex = j % this.vertices.length; + } + } + } + + if (i < closestIndex) { + lowerPoly.append(poly,i,closestIndex+1); + if (closestIndex != 0){ + upperPoly.append(poly,closestIndex,v.length); + } + upperPoly.append(poly,0,i+1); + } else { + if (i != 0){ + lowerPoly.append(poly,i,v.length); + } + lowerPoly.append(poly,0,closestIndex+1); + upperPoly.append(poly,closestIndex,i+1); + } + } + + // solve smallest poly first + if (lowerPoly.vertices.length < upperPoly.vertices.length) { + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } else { + upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); + } + + return result; + } + } + result.push(this); + + return result; +}; + +/** + * Remove collinear points in the polygon. + * @method removeCollinearPoints + * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. + * @return {Number} The number of points removed + */ +Polygon.prototype.removeCollinearPoints = function(precision){ + var num = 0; + for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ + if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ + // Remove the middle point + this.vertices.splice(i%this.vertices.length,1); + i--; // Jump one point forward. Otherwise we may get a chain removal + num++; + } + } + return num; +}; + +},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){ +module.exports = Scalar; + +/** + * Scalar functions + * @class Scalar + */ +function Scalar(){} + +/** + * Check if two scalars are equal + * @static + * @method eq + * @param {Number} a + * @param {Number} b + * @param {Number} [precision] + * @return {Boolean} + */ +Scalar.eq = function(a,b,precision){ + precision = precision || 0; + return Math.abs(a-b) < precision; +}; + +},{}],5:[function(_dereq_,module,exports){ +module.exports = { + Polygon : _dereq_("./Polygon"), + Point : _dereq_("./Point"), +}; + +},{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){ +module.exports={ + "name": "p2", + "version": "0.7.1", + "description": "A JavaScript 2D physics engine.", + "author": "Stefan Hedman (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.5", + "grunt-contrib-jshint": "^0.11.2", + "grunt-contrib-nodeunit": "^0.4.1", + "grunt-contrib-uglify": "~0.4.0", + "grunt-contrib-watch": "~0.5.0", + "grunt-browserify": "~2.0.1", + "grunt-contrib-concat": "^0.4.0" + }, + "dependencies": { + "poly-decomp": "0.1.1" + } +} + +},{}],7:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = AABB; + +/** + * Axis aligned bounding box class. + * @class AABB + * @constructor + * @param {Object} [options] + * @param {Array} [options.upperBound] + * @param {Array} [options.lowerBound] + */ +function AABB(options){ + + /** + * The lower bound of the bounding box. + * @property lowerBound + * @type {Array} + */ + this.lowerBound = vec2.create(); + if(options && options.lowerBound){ + vec2.copy(this.lowerBound, options.lowerBound); + } + + /** + * The upper bound of the bounding box. + * @property upperBound + * @type {Array} + */ + this.upperBound = vec2.create(); + if(options && options.upperBound){ + vec2.copy(this.upperBound, options.upperBound); + } +} + +var tmp = vec2.create(); + +/** + * Set the AABB bounds from a set of points, transformed by the given position and angle. + * @method setFromPoints + * @param {Array} points An array of vec2's. + * @param {Array} position + * @param {number} angle + * @param {number} skinSize Some margin to be added to the AABB. + */ +AABB.prototype.setFromPoints = function(points, position, angle, skinSize){ + var l = this.lowerBound, + u = this.upperBound; + + if(typeof(angle) !== "number"){ + angle = 0; + } + + // Set to the first point + if(angle !== 0){ + vec2.rotate(l, points[0], angle); + } else { + vec2.copy(l, points[0]); + } + vec2.copy(u, l); + + // Compute cosines and sines just once + var cosAngle = Math.cos(angle), + sinAngle = Math.sin(angle); + for(var i = 1; i u[j]){ + u[j] = p[j]; + } + if(p[j] < l[j]){ + l[j] = p[j]; + } + } + } + + // Add offset + if(position){ + vec2.add(this.lowerBound, this.lowerBound, position); + vec2.add(this.upperBound, this.upperBound, position); + } + + if(skinSize){ + this.lowerBound[0] -= skinSize; + this.lowerBound[1] -= skinSize; + this.upperBound[0] += skinSize; + this.upperBound[1] += skinSize; + } +}; + +/** + * Copy bounds from an AABB to this AABB + * @method copy + * @param {AABB} aabb + */ +AABB.prototype.copy = function(aabb){ + vec2.copy(this.lowerBound, aabb.lowerBound); + vec2.copy(this.upperBound, aabb.upperBound); +}; + +/** + * Extend this AABB so that it covers the given AABB too. + * @method extend + * @param {AABB} aabb + */ +AABB.prototype.extend = function(aabb){ + // Loop over x and y + var i = 2; + while(i--){ + // Extend lower bound + var l = aabb.lowerBound[i]; + if(this.lowerBound[i] > l){ + this.lowerBound[i] = l; + } + + // Upper + var u = aabb.upperBound[i]; + if(this.upperBound[i] < u){ + this.upperBound[i] = u; + } + } +}; + +/** + * Returns true if the given AABB overlaps this AABB. + * @method overlaps + * @param {AABB} aabb + * @return {Boolean} + */ +AABB.prototype.overlaps = function(aabb){ + var l1 = this.lowerBound, + u1 = this.upperBound, + l2 = aabb.lowerBound, + u2 = aabb.upperBound; + + // l2 u2 + // |---------| + // |--------| + // l1 u1 + + 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])); +}; + +/** + * @method containsPoint + * @param {Array} point + * @return {boolean} + */ +AABB.prototype.containsPoint = function(point){ + var l = this.lowerBound, + u = this.upperBound; + return l[0] <= point[0] && point[0] <= u[0] && l[1] <= point[1] && point[1] <= u[1]; +}; + +/** + * Check if the AABB is hit by a ray. + * @method overlapsRay + * @param {Ray} ray + * @return {number} -1 if no hit, a number between 0 and 1 if hit. + */ +AABB.prototype.overlapsRay = function(ray){ + var t = 0; + + // ray.direction is unit direction vector of ray + var dirFracX = 1 / ray.direction[0]; + var dirFracY = 1 / ray.direction[1]; + + // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner + var t1 = (this.lowerBound[0] - ray.from[0]) * dirFracX; + var t2 = (this.upperBound[0] - ray.from[0]) * dirFracX; + var t3 = (this.lowerBound[1] - ray.from[1]) * dirFracY; + var t4 = (this.upperBound[1] - ray.from[1]) * dirFracY; + + var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4))); + var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4))); + + // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us + if (tmax < 0){ + //t = tmax; + return -1; + } + + // if tmin > tmax, ray doesn't intersect AABB + if (tmin > tmax){ + //t = tmax; + return -1; + } + + return tmin; +}; +},{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Body = _dereq_('../objects/Body'); + +module.exports = Broadphase; + +/** + * Base class for broadphase implementations. + * @class Broadphase + * @constructor + */ +function Broadphase(type){ + + this.type = type; + + /** + * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). + * @property result + * @type {Array} + */ + this.result = []; + + /** + * The world to search for collision pairs in. To change it, use .setWorld() + * @property world + * @type {World} + * @readOnly + */ + this.world = null; + + /** + * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE. + * @property {Number} boundingVolumeType + */ + this.boundingVolumeType = Broadphase.AABB; +} + +/** + * Axis aligned bounding box type. + * @static + * @property {Number} AABB + */ +Broadphase.AABB = 1; + +/** + * Bounding circle type. + * @static + * @property {Number} BOUNDING_CIRCLE + */ +Broadphase.BOUNDING_CIRCLE = 2; + +/** + * Set the world that we are searching for collision pairs in. + * @method setWorld + * @param {World} world + */ +Broadphase.prototype.setWorld = function(world){ + this.world = world; +}; + +/** + * Get all potential intersecting body pairs. + * @method getCollisionPairs + * @param {World} world The world to search in. + * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). + */ +Broadphase.prototype.getCollisionPairs = function(world){}; + +var dist = vec2.create(); + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.aabbCheck = function(bodyA, bodyB){ + return bodyA.getAABB().overlaps(bodyB.getAABB()); +}; + +/** + * Check whether the bounding radius of two bodies overlap. + * @method boundingRadiusCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +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; +}; + +/** + * Check whether two bodies are allowed to collide at all. + * @method canCollide + * @param {Body} bodyA + * @param {Body} bodyB + * @return {Boolean} + */ +Broadphase.canCollide = function(bodyA, bodyB){ + var KINEMATIC = Body.KINEMATIC; + var STATIC = Body.STATIC; + + // Cannot collide static bodies + if(bodyA.type === STATIC && bodyB.type === STATIC){ + return false; + } + + // Cannot collide static vs kinematic bodies + if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) || + (bodyA.type === STATIC && bodyB.type === KINEMATIC)){ + return false; + } + + // Cannot collide kinematic vs kinematic + if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){ + return false; + } + + // Cannot collide both sleeping bodies + if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ + return false; + } + + // Cannot collide if one is static and the other is sleeping + if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === STATIC) || + (bodyB.sleepState === Body.SLEEPING && bodyA.type === STATIC)){ + return false; + } + + return true; +}; + +Broadphase.NAIVE = 1; +Broadphase.SAP = 2; + +},{"../math/vec2":30,"../objects/Body":31}],9:[function(_dereq_,module,exports){ +var Circle = _dereq_('../shapes/Circle'), + Plane = _dereq_('../shapes/Plane'), + Shape = _dereq_('../shapes/Shape'), + Particle = _dereq_('../shapes/Particle'), + Broadphase = _dereq_('../collision/Broadphase'), + vec2 = _dereq_('../math/vec2'); + +module.exports = NaiveBroadphase; + +/** + * Naive broadphase implementation. Does N^2 tests. + * + * @class NaiveBroadphase + * @constructor + * @extends Broadphase + */ +function NaiveBroadphase(){ + Broadphase.call(this, Broadphase.NAIVE); +} +NaiveBroadphase.prototype = new Broadphase(); +NaiveBroadphase.prototype.constructor = NaiveBroadphase; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +NaiveBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = world.bodies, + result = this.result; + + result.length = 0; + + for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ + var bi = bodies[i]; + + for(var j=0; j pos0 && pos < pos1){ + // We got contact! + + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape); + + vec2.scale(c.normalA, orthoDist, -1); + vec2.normalize(c.normalA, c.normalA); + + vec2.scale( c.contactPointA, c.normalA, circleRadius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + sub(c.contactPointB, projectedPoint, lineOffset); + add(c.contactPointB, c.contactPointB, lineOffset); + sub(c.contactPointB, c.contactPointB, lineBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; + } + } + + // Add corner + verts[0] = worldVertex0; + verts[1] = worldVertex1; + + for(var i=0; i 0){ + for(var i=0; i Math.pow(r,2)){ + return 0; + } + + if(justTest){ + return true; + } + + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + 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; +}; + +/** + * Plane/Convex Narrowphase + * @method planeConvex + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} convexBody + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = +Narrowphase.prototype[Shape.PLANE | Shape.BOX] = +Narrowphase.prototype.planeConvex = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + convexBody, + convexShape, + convexOffset, + convexAngle, + justTest +){ + var worldVertex = tmp1, + worldNormal = tmp2, + dist = tmp3; + + var numReported = 0; + vec2.rotate(worldNormal, yAxis, planeAngle); + + for(var i=0; i!==convexShape.vertices.length; i++){ + var v = convexShape.vertices[i]; + vec2.rotate(worldVertex, v, convexAngle); + add(worldVertex, worldVertex, convexOffset); + + sub(dist, worldVertex, planeOffset); + + if(dot(dist,worldNormal) <= 0){ + + if(justTest){ + return true; + } + + // Found vertex + numReported++; + + var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); + + sub(dist, worldVertex, planeOffset); + + vec2.copy(c.normalA, worldNormal); + + var d = dot(dist, c.normalA); + vec2.scale(dist, c.normalA, d); + + // rj is from convex center to contact + sub(c.contactPointB, worldVertex, convexBody.position); + + + // ri is from plane center to contact + sub( c.contactPointA, worldVertex, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + this.contactEquations.push(c); + + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numReported){ + this.frictionEquations.push(this.createFrictionFromAverage(numReported)); + } + } + + return numReported; +}; + +/** + * Narrowphase for particle vs plane + * @method particlePlane + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Body} planeBody + * @param {Plane} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = +Narrowphase.prototype.particlePlane = function( + particleBody, + particleShape, + particleOffset, + particleAngle, + planeBody, + planeShape, + planeOffset, + planeAngle, + justTest +){ + var dist = tmp1, + worldNormal = tmp2; + + planeAngle = planeAngle || 0; + + sub(dist, particleOffset, planeOffset); + vec2.rotate(worldNormal, yAxis, planeAngle); + + var d = dot(dist, worldNormal); + + if(d > 0){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape); + + vec2.copy(c.normalA, worldNormal); + vec2.scale( dist, c.normalA, d ); + // dist is now the distance vector in the normal direction + + // ri is the particle position projected down onto the plane, from the plane center + sub( c.contactPointA, particleOffset, dist); + sub( c.contactPointA, c.contactPointA, planeBody.position); + + // rj is from the body center to the particle center + sub( c.contactPointB, particleOffset, particleBody.position ); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + return 1; +}; + +/** + * Circle/Particle Narrowphase + * @method circleParticle + * @param {Body} circleBody + * @param {Circle} circleShape + * @param {Array} circleOffset + * @param {Number} circleAngle + * @param {Body} particleBody + * @param {Particle} particleShape + * @param {Array} particleOffset + * @param {Number} particleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = +Narrowphase.prototype.circleParticle = function( + circleBody, + circleShape, + circleOffset, + circleAngle, + particleBody, + particleShape, + particleOffset, + particleAngle, + justTest +){ + var dist = tmp1; + + sub(dist, particleOffset, circleOffset); + if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){ + return 0; + } + if(justTest){ + return true; + } + + var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape); + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + // Vector from circle to contact point is the normal times the circle radius + vec2.scale(c.contactPointA, c.normalA, circleShape.radius); + add(c.contactPointA, c.contactPointA, circleOffset); + sub(c.contactPointA, c.contactPointA, circleBody.position); + + // Vector from particle center to contact point is zero + sub(c.contactPointB, particleOffset, particleBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + + return 1; +}; + +var planeCapsule_tmpCircle = new Circle({ radius: 1 }), + planeCapsule_tmp1 = vec2.create(), + planeCapsule_tmp2 = vec2.create(), + planeCapsule_tmp3 = vec2.create(); + +/** + * @method planeCapsule + * @param {Body} planeBody + * @param {Circle} planeShape + * @param {Array} planeOffset + * @param {Number} planeAngle + * @param {Body} capsuleBody + * @param {Particle} capsuleShape + * @param {Array} capsuleOffset + * @param {Number} capsuleAngle + * @param {Boolean} justTest + */ +Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = +Narrowphase.prototype.planeCapsule = function( + planeBody, + planeShape, + planeOffset, + planeAngle, + capsuleBody, + capsuleShape, + capsuleOffset, + capsuleAngle, + justTest +){ + var end1 = planeCapsule_tmp1, + end2 = planeCapsule_tmp2, + circle = planeCapsule_tmpCircle, + dst = planeCapsule_tmp3; + + // Compute world end positions + vec2.set(end1, -capsuleShape.length/2, 0); + vec2.rotate(end1,end1,capsuleAngle); + add(end1,end1,capsuleOffset); + + vec2.set(end2, capsuleShape.length/2, 0); + vec2.rotate(end2,end2,capsuleAngle); + add(end2,end2,capsuleOffset); + + circle.radius = capsuleShape.radius; + + var enableFrictionBefore; + + // Temporarily turn off friction + if(this.enableFrictionReduction){ + enableFrictionBefore = this.enableFriction; + this.enableFriction = false; + } + + // Do Narrowphase as two circles + var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest), + numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest); + + // Restore friction + if(this.enableFrictionReduction){ + this.enableFriction = enableFrictionBefore; + } + + if(justTest){ + return numContacts1 || numContacts2; + } else { + var numTotal = numContacts1 + numContacts2; + if(this.enableFrictionReduction){ + if(numTotal){ + this.frictionEquations.push(this.createFrictionFromAverage(numTotal)); + } + } + return numTotal; + } +}; + +/** + * Creates ContactEquations and FrictionEquations for a collision. + * @method circlePlane + * @param {Body} bi The first body that should be connected to the equations. + * @param {Circle} si The circle shape participating in the collision. + * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. + * @param {Body} bj The second body that should be connected to the equations. + * @param {Plane} sj The Plane shape that is participating + * @param {Array} xj Extra offset for the plane shape. + * @param {Number} aj Extra angle to apply to the plane + */ +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, // Offset from body center, rotated! + planeBody = bj, + shapeB = sj, + planeOffset = xj, + planeAngle = aj; + + planeAngle = planeAngle || 0; + + // Vector from plane to circle + var planeToCircle = tmp1, + worldNormal = tmp2, + temp = tmp3; + + sub(planeToCircle, circleOffset, planeOffset); + + // World plane normal + vec2.rotate(worldNormal, yAxis, planeAngle); + + // Normal direction distance + var d = dot(worldNormal, planeToCircle); + + if(d > circleShape.radius){ + return 0; // No overlap. Abort. + } + + if(justTest){ + return true; + } + + // Create contact + var contact = this.createContactEquation(planeBody,circleBody,sj,si); + + // ni is the plane world normal + vec2.copy(contact.normalA, worldNormal); + + // rj is the vector from circle center to the contact point + vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); + add(contact.contactPointB, contact.contactPointB, circleOffset); + sub(contact.contactPointB, contact.contactPointB, circleBody.position); + + // ri is the distance from plane center to contact. + vec2.scale(temp, contact.normalA, d); + sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector + 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; +}; + +/** + * Convex/convex Narrowphase.See this article for more info. + * @method convexConvex + * @param {Body} bi + * @param {Convex} si + * @param {Array} xi + * @param {Number} ai + * @param {Body} bj + * @param {Convex} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CONVEX] = +Narrowphase.prototype[Shape.CONVEX | Shape.BOX] = +Narrowphase.prototype[Shape.BOX] = +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 = typeof(precision) === 'number' ? precision : 0; + + var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); + if(!found){ + return 0; + } + + // Make sure the separating axis is directed from shape i to shape j + sub(dist,xj,xi); + if(dot(sepAxis,dist) > 0){ + vec2.scale(sepAxis,sepAxis,-1); + } + + // Find edges with normals closest to the separating axis + var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis + closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); + + if(closestEdge1 === -1 || closestEdge2 === -1){ + return 0; + } + + // Loop over the shapes + 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){ + // Swap! + 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; + } + + // Loop over 2 points in convex B + for(var j=closestEdgeB; j= 3){ + + if(justTest){ + return true; + } + + // worldPoint was on the "inside" side of each of the 3 checked edges. + // Project it to the center edge and use the projection direction as normal + + // Create contact + var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); + numContacts++; + + // Get center edge from body A + var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], + v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; + + // Construct the edge + 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); // Normal points out of convex A + vec2.normalize(c.normalA,c.normalA); + + sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point + var d = dot(c.normalA,dist); // Penetration + vec2.scale(penetrationVec, c.normalA, d); // Vector penetration + + 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); + + // Todo reduce to 1 friction equation if we have 2 contact points + if(!this.enableFrictionReduction){ + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + } + + if(this.enableFrictionReduction){ + if(this.enableFriction && numContacts){ + this.frictionEquations.push(this.createFrictionFromAverage(numContacts)); + } + } + + return numContacts; +}; + +// .projectConvex is called by other functions, need local tmp vectors +var pcoa_tmp1 = vec2.fromValues(0,0); + +/** + * Project a Convex onto a world-oriented axis + * @method projectConvexOntoAxis + * @static + * @param {Convex} convexShape + * @param {Array} convexOffset + * @param {Number} convexAngle + * @param {Array} worldAxis + * @param {Array} result + */ +Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = pcoa_tmp1; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, worldAxis, -convexAngle); + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + // Project the position of the body onto the axis - need to add this to the result + var offset = dot(convexOffset, worldAxis); + + vec2.set( result, min + offset, max + offset); +}; + +// .findSeparatingAxis is called by other functions, need local tmp vectors +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); + +/** + * Find a separating axis between the shapes, that maximizes the separating distance between them. + * @method findSeparatingAxis + * @static + * @param {Convex} c1 + * @param {Array} offset1 + * @param {Number} angle1 + * @param {Convex} c2 + * @param {Array} offset2 + * @param {Number} angle2 + * @param {Array} sepAxis The resulting axis + * @return {Boolean} Whether the axis could be found. + */ +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; + + if(c1 instanceof Box && c2 instanceof Box){ + + for(var j=0; j!==2; j++){ + var c = c1, + angle = angle1; + if(j===1){ + c = c2; + angle = angle2; + } + + for(var i=0; i!==2; i++){ + + // Get the world edge + if(i === 0){ + vec2.set(normal, 0, 1); + } else if(i === 1) { + vec2.set(normal, 1, 0); + } + if(angle !== 0){ + vec2.rotate(normal, normal, angle); + } + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + + } else { + + 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++){ + // Get the world edge + vec2.rotate(worldPoint0, c.vertices[i], angle); + vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); + + sub(edge, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, edge); + vec2.normalize(normal,normal); + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); + Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + var dist = b[0] - a[1]; + overlap = (dist <= 0); + + if(maxDist===null || dist > maxDist){ + vec2.copy(sepAxis, normal); + maxDist = dist; + found = overlap; + } + } + } + } + + + /* + // Needs to be tested some more + 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.axes.length; i++){ + + var normal = c.axes[i]; + + // Project hulls onto that normal + Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1); + Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2); + + // Order by span position + var a=span1, + b=span2, + swapped = false; + if(span1[0] > span2[0]){ + b=span1; + a=span2; + swapped = true; + } + + // Get separating distance + 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; +}; + +// .getClosestEdge is called by other functions, need local tmp vectors +var gce_tmp1 = vec2.fromValues(0,0) +, gce_tmp2 = vec2.fromValues(0,0) +, gce_tmp3 = vec2.fromValues(0,0); + +/** + * Get the edge that has a normal closest to an axis. + * @method getClosestEdge + * @static + * @param {Convex} c + * @param {Number} angle + * @param {Array} axis + * @param {Boolean} flip + * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. + */ +Narrowphase.getClosestEdge = function(c,angle,axis,flip){ + var localAxis = gce_tmp1, + edge = gce_tmp2, + normal = gce_tmp3; + + // Convert the axis to local coords of the body + vec2.rotate(localAxis, axis, -angle); + if(flip){ + vec2.scale(localAxis,localAxis,-1); + } + + var closestEdge = -1, + N = c.vertices.length, + maxDot = -1; + for(var i=0; i!==N; i++){ + // Get the edge + sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + 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(); + +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = +Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, + hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ + var data = hfShape.heights, + 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; + + // Get the index of the points to test against + var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), + idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); + + /*if(idxB < 0 || idxA >= data.length) + return justTest ? false : 0;*/ + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(circlePos[1]-radius > max){ + return justTest ? false : 0; + } + + /* + if(circlePos[1]+radius < min){ + // Below the minimum point... We can just guess. + // TODO + } + */ + + // 1. Check so center of circle is not inside the field. If it is, this wont work... + // 2. For each edge + // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) + // 2. 2. Check if point is inside. + + var found = false; + + // Check all edges first + for(var i=idxA; i= v0[0] && candidate[0] < v1[0] && d <= 0){ + + if(justTest){ + return true; + } + + found = true; + + // Store the candidate point, projected to the edge + vec2.scale(dist,worldNormal,-d); + vec2.add(minCandidate,candidate,dist); + vec2.copy(minCandidateNormal,worldNormal); + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Normal is out of the heightfield + vec2.copy(c.normalA, minCandidateNormal); + + // Vector from circle to heightfield + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + vec2.copy(c.contactPointA, minCandidate); + vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push( this.createFrictionFromContact(c) ); + } + } + } + + // Check all vertices + found = false; + if(radius > 0){ + for(var i=idxA; i<=idxB; i++){ + + // Get point + vec2.set(v0, i*w, data[i]); + vec2.add(v0,v0,hfPos); + + vec2.sub(dist, circlePos, v0); + + if(vec2.squaredLength(dist) < Math.pow(radius, 2)){ + + if(justTest){ + return true; + } + + found = true; + + var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); + + // Construct normal - out of heightfield + vec2.copy(c.normalA, dist); + vec2.normalize(c.normalA,c.normalA); + + vec2.scale(c.contactPointB, c.normalA, -radius); + add(c.contactPointB, c.contactPointB, circlePos); + sub(c.contactPointB, c.contactPointB, circleBody.position); + + sub(c.contactPointA, v0, hfPos); + add(c.contactPointA, c.contactPointA, hfPos); + sub(c.contactPointA, c.contactPointA, hfBody.position); + + this.contactEquations.push(c); + + if(this.enableFriction){ + this.frictionEquations.push(this.createFrictionFromContact(c)); + } + } + } + } + + if(found){ + return 1; + } + + return 0; + +}; + +var convexHeightfield_v0 = vec2.create(), + convexHeightfield_v1 = vec2.create(), + convexHeightfield_tilePos = vec2.create(), + convexHeightfield_tempConvexShape = new Convex({ vertices: [vec2.create(),vec2.create(),vec2.create(),vec2.create()] }); +/** + * @method circleHeightfield + * @param {Body} bi + * @param {Circle} si + * @param {Array} xi + * @param {Body} bj + * @param {Heightfield} sj + * @param {Array} xj + * @param {Number} aj + */ +Narrowphase.prototype[Shape.BOX | Shape.HEIGHTFIELD] = +Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = +Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, + hfBody,hfShape,hfPos,hfAngle, justTest ){ + var data = hfShape.heights, + w = hfShape.elementWidth, + v0 = convexHeightfield_v0, + v1 = convexHeightfield_v1, + tilePos = convexHeightfield_tilePos, + tileConvex = convexHeightfield_tempConvexShape; + + // Get the index of the points to test against + var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), + idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); + + if(idxA < 0){ + idxA = 0; + } + if(idxB >= data.length){ + idxB = data.length-1; + } + + // Get max and min + var max = data[idxA], + min = data[idxB]; + for(var i=idxA; i max){ + max = data[i]; + } + } + + if(convexBody.aabb.lowerBound[1] > max){ + return justTest ? false : 0; + } + + var found = false; + var numContacts = 0; + + // Loop over all edges + // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape) + for(var i=idxA; i= 0 || aabb.containsPoint(this.from)){ + this.intersectBody(result, body); + } + } +}; + +var intersectBody_worldPosition = vec2.create(); + +/** + * Shoot a ray at a body, get back information about the hit. + * @method intersectBody + * @private + * @param {Body} body + */ +Ray.prototype.intersectBody = function (result, body) { + var checkCollisionResponse = this.checkCollisionResponse; + + if(checkCollisionResponse && !body.collisionResponse){ + return; + } + + var worldPosition = intersectBody_worldPosition; + + for (var i = 0, N = body.shapes.length; i < N; i++) { + var shape = body.shapes[i]; + + if(checkCollisionResponse && !shape.collisionResponse){ + continue; // Skip + } + + if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){ + continue; + } + + // Get world angle and position of the shape + vec2.rotate(worldPosition, shape.position, body.angle); + vec2.add(worldPosition, worldPosition, body.position); + var worldAngle = shape.angle + body.angle; + + this.intersectShape( + result, + shape, + worldAngle, + worldPosition, + body + ); + + if(result.shouldStop(this)){ + break; + } + } +}; + +/** + * @method intersectShape + * @private + * @param {Shape} shape + * @param {number} angle + * @param {array} position + * @param {Body} body + */ +Ray.prototype.intersectShape = function(result, shape, angle, position, body){ + var from = this.from; + + // Checking radius + var distance = distanceFromIntersectionSquared(from, this.direction, position); + if (distance > shape.boundingRadius * shape.boundingRadius) { + return; + } + + this._currentBody = body; + this._currentShape = shape; + + shape.raycast(result, this, position, angle); + + this._currentBody = this._currentShape = null; +}; + +/** + * Get the AABB of the ray. + * @method getAABB + * @param {AABB} aabb + */ +Ray.prototype.getAABB = function(result){ + var to = this.to; + var from = this.from; + vec2.set( + result.lowerBound, + Math.min(to[0], from[0]), + Math.min(to[1], from[1]) + ); + vec2.set( + result.upperBound, + Math.max(to[0], from[0]), + Math.max(to[1], from[1]) + ); +}; + +var hitPointWorld = vec2.create(); + +/** + * @method reportIntersection + * @private + * @param {number} fraction + * @param {array} normal + * @param {number} [faceIndex=-1] + * @return {boolean} True if the intersections should continue + */ +Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){ + var from = this.from; + var to = this.to; + var shape = this._currentShape; + var body = this._currentBody; + + // Skip back faces? + if(this.skipBackfaces && vec2.dot(normal, this.direction) > 0){ + return; + } + + switch(this.mode){ + + case Ray.ALL: + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + this.callback(result); + break; + + case Ray.CLOSEST: + + // Store if closer than current closest + if(fraction < result.fraction || !result.hasHit()){ + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + } + break; + + case Ray.ANY: + + // Report and stop. + result.set( + normal, + shape, + body, + fraction, + faceIndex + ); + break; + } +}; + +var v0 = vec2.create(), + intersect = vec2.create(); +function distanceFromIntersectionSquared(from, direction, position) { + + // v0 is vector from from to position + vec2.sub(v0, position, from); + var dot = vec2.dot(v0, direction); + + // intersect = direction * dot + from + vec2.scale(intersect, direction, dot); + vec2.add(intersect, intersect, from); + + return vec2.squaredDistance(position, intersect); +} + + +},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Ray = _dereq_('../collision/Ray'); + +module.exports = RaycastResult; + +/** + * Storage for Ray casting hit data. + * @class RaycastResult + * @constructor + */ +function RaycastResult(){ + + /** + * The normal of the hit, oriented in world space. + * @property {array} normal + */ + this.normal = vec2.create(); + + /** + * The hit shape, or null. + * @property {Shape} shape + */ + this.shape = null; + + /** + * The hit body, or null. + * @property {Body} body + */ + this.body = null; + + /** + * The index of the hit triangle, if the hit shape was indexable. + * @property {number} faceIndex + * @default -1 + */ + this.faceIndex = -1; + + /** + * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet. + * @property {number} fraction + * @default -1 + */ + this.fraction = -1; + + /** + * If the ray should stop traversing. + * @readonly + * @property {Boolean} isStopped + */ + this.isStopped = false; +} + +/** + * Reset all result data. Must be done before re-using the result object. + * @method reset + */ +RaycastResult.prototype.reset = function () { + vec2.set(this.normal, 0, 0); + this.shape = null; + this.body = null; + this.faceIndex = -1; + this.fraction = -1; + this.isStopped = false; +}; + +/** + * Get the distance to the hit point. + * @method getHitDistance + * @param {Ray} ray + */ +RaycastResult.prototype.getHitDistance = function (ray) { + return vec2.distance(ray.from, ray.to) * this.fraction; +}; + +/** + * Returns true if the ray hit something since the last reset(). + * @method hasHit + */ +RaycastResult.prototype.hasHit = function () { + return this.fraction !== -1; +}; + +/** + * Get world hit point. + * @method getHitPoint + * @param {array} out + * @param {Ray} ray + */ +RaycastResult.prototype.getHitPoint = function (out, ray) { + vec2.lerp(out, ray.from, ray.to, this.fraction); +}; + +/** + * Can be called while iterating over hits to stop searching for hit points. + * @method stop + */ +RaycastResult.prototype.stop = function(){ + this.isStopped = true; +}; + +/** + * @method shouldStop + * @private + * @param {Ray} ray + * @return {boolean} + */ +RaycastResult.prototype.shouldStop = function(ray){ + return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY); +}; + +/** + * @method set + * @private + * @param {array} normal + * @param {Shape} shape + * @param {Body} body + * @param {number} fraction + */ +RaycastResult.prototype.set = function( + normal, + shape, + body, + fraction, + faceIndex +){ + vec2.copy(this.normal, normal); + this.shape = shape; + this.body = body; + this.fraction = fraction; + this.faceIndex = faceIndex; +}; +},{"../collision/Ray":11,"../math/vec2":30}],13:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, Broadphase = _dereq_('../collision/Broadphase'); + +module.exports = SAPBroadphase; + +/** + * Sweep and prune broadphase along one axis. + * + * @class SAPBroadphase + * @constructor + * @extends Broadphase + */ +function SAPBroadphase(){ + Broadphase.call(this,Broadphase.SAP); + + /** + * List of bodies currently in the broadphase. + * @property axisList + * @type {Array} + */ + this.axisList = []; + + /** + * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance. + * @property axisIndex + * @type {Number} + */ + this.axisIndex = 0; + + var that = this; + this._addBodyHandler = function(e){ + that.axisList.push(e.body); + }; + + this._removeBodyHandler = function(e){ + // Remove from list + var idx = that.axisList.indexOf(e.body); + if(idx !== -1){ + that.axisList.splice(idx,1); + } + }; +} +SAPBroadphase.prototype = new Broadphase(); +SAPBroadphase.prototype.constructor = SAPBroadphase; + +/** + * Change the world + * @method setWorld + * @param {World} world + */ +SAPBroadphase.prototype.setWorld = function(world){ + // Clear the old axis array + this.axisList.length = 0; + + // Add all bodies from the new world + Utils.appendArray(this.axisList, world.bodies); + + // Remove old handlers, if any + world + .off("addBody",this._addBodyHandler) + .off("removeBody",this._removeBodyHandler); + + // Add handlers to update the list of bodies. + world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); + + this.world = world; +}; + +/** + * Sorts bodies along an axis. + * @method sortAxisList + * @param {Array} a + * @param {number} axisIndex + * @return {Array} + */ +SAPBroadphase.sortAxisList = function(a, axisIndex){ + axisIndex = axisIndex|0; + for(var i=1,l=a.length; 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.sortList = function(){ + var bodies = this.axisList, + axisIndex = this.axisIndex; + + // Sort the lists + SAPBroadphase.sortAxisList(bodies, axisIndex); +}; + +/** + * Get the colliding pairs + * @method getCollisionPairs + * @param {World} world + * @return {Array} + */ +SAPBroadphase.prototype.getCollisionPairs = function(world){ + var bodies = this.axisList, + result = this.result, + axisIndex = this.axisIndex; + + result.length = 0; + + // Update all AABBs if needed + var l = bodies.length; + while(l--){ + var b = bodies[l]; + if(b.aabbNeedsUpdate){ + b.updateAABB(); + } + } + + // Sort the lists + this.sortList(); + + // Look through the X list + for(var i=0, N=bodies.length|0; i!==N; i++){ + var bi = bodies[i]; + + for(var j=i+1; j G = [-n -rixn n rjxn] + + var r = vec2.create(); + var ri = vec2.create(); // worldAnchorA + var rj = vec2.create(); // worldAnchorB + var that = this; + normal.computeGq = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + xi = bodyA.position, + xj = bodyB.position; + + // Transform local anchors to world + vec2.rotate(ri, localAnchorA, bodyA.angle); + vec2.rotate(rj, localAnchorB, bodyB.angle); + + vec2.add(r, xj, rj); + vec2.sub(r, r, ri); + vec2.sub(r, r, xi); + + //vec2.sub(r, bodyB.position, bodyA.position); + return vec2.length(r) - that.distance; + }; + + // Make the contact constraint bilateral + this.setMaxForce(maxForce); + + /** + * If the upper limit is enabled or not. + * @property {Boolean} upperLimitEnabled + */ + this.upperLimitEnabled = false; + + /** + * The upper constraint limit. + * @property {number} upperLimit + */ + this.upperLimit = 1; + + /** + * If the lower limit is enabled or not. + * @property {Boolean} lowerLimitEnabled + */ + this.lowerLimitEnabled = false; + + /** + * The lower constraint limit. + * @property {number} lowerLimit + */ + this.lowerLimit = 0; + + /** + * Current constraint position. This is equal to the current distance between the world anchor points. + * @property {number} position + */ + this.position = 0; +} +DistanceConstraint.prototype = new Constraint(); +DistanceConstraint.prototype.constructor = DistanceConstraint; + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +var n = vec2.create(); +var ri = vec2.create(); // worldAnchorA +var rj = vec2.create(); // worldAnchorB +DistanceConstraint.prototype.update = function(){ + var normal = this.equations[0], + bodyA = this.bodyA, + bodyB = this.bodyB, + distance = this.distance, + xi = bodyA.position, + xj = bodyB.position, + normalEquation = this.equations[0], + G = normal.G; + + // Transform local anchors to world + vec2.rotate(ri, this.localAnchorA, bodyA.angle); + vec2.rotate(rj, this.localAnchorB, bodyB.angle); + + // Get world anchor points and normal + vec2.add(n, xj, rj); + vec2.sub(n, n, ri); + vec2.sub(n, n, xi); + this.position = vec2.length(n); + + var violating = false; + if(this.upperLimitEnabled){ + if(this.position > this.upperLimit){ + normalEquation.maxForce = 0; + normalEquation.minForce = -this.maxForce; + this.distance = this.upperLimit; + violating = true; + } + } + + if(this.lowerLimitEnabled){ + if(this.position < this.lowerLimit){ + normalEquation.maxForce = this.maxForce; + normalEquation.minForce = 0; + this.distance = this.lowerLimit; + violating = true; + } + } + + if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){ + // No constraint needed. + normalEquation.enabled = false; + return; + } + + normalEquation.enabled = true; + + vec2.normalize(n,n); + + // Caluclate cross products + var rixn = vec2.crossLength(ri, n), + rjxn = vec2.crossLength(rj, n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; +}; + +/** + * Set the max force to be used + * @method setMaxForce + * @param {Number} maxForce + */ +DistanceConstraint.prototype.setMaxForce = function(maxForce){ + var normal = this.equations[0]; + normal.minForce = -maxForce; + normal.maxForce = maxForce; +}; + +/** + * Get the max force + * @method getMaxForce + * @return {Number} + */ +DistanceConstraint.prototype.getMaxForce = function(){ + var normal = this.equations[0]; + return normal.maxForce; +}; + +},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, AngleLockEquation = _dereq_('../equations/AngleLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = GearConstraint; + +/** + * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB. + * @class GearConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for). + * @param {Number} [options.ratio=1] Gear ratio. + * @param {Number} [options.maxTorque] Maximum torque to apply. + * @extends Constraint + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + * + * @example + * var constraint = new GearConstraint(bodyA, bodyB, { + * ratio: 2, + * maxTorque: 1000 + * }); + * world.addConstraint(constraint); + */ +function GearConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); + + /** + * The gear ratio. + * @property ratio + * @type {Number} + */ + this.ratio = options.ratio !== undefined ? options.ratio : 1; + + /** + * The relative angle + * @property angle + * @type {Number} + */ + this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle; + + // Send same parameters to the equation + options.angle = this.angle; + options.ratio = this.ratio; + + this.equations = [ + new AngleLockEquation(bodyA,bodyB,options), + ]; + + // Set max torque + if(options.maxTorque !== undefined){ + this.setMaxTorque(options.maxTorque); + } +} +GearConstraint.prototype = new Constraint(); +GearConstraint.prototype.constructor = GearConstraint; + +GearConstraint.prototype.update = function(){ + var eq = this.equations[0]; + if(eq.ratio !== this.ratio){ + eq.setRatio(this.ratio); + } + eq.angle = this.angle; +}; + +/** + * Set the max torque for the constraint. + * @method setMaxTorque + * @param {Number} torque + */ +GearConstraint.prototype.setMaxTorque = function(torque){ + this.equations[0].setMaxTorque(torque); +}; + +/** + * Get the max torque for the constraint. + * @method getMaxTorque + * @return {Number} + */ +GearConstraint.prototype.getMaxTorque = function(torque){ + return this.equations[0].maxForce; +}; +},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('../equations/Equation'); + +module.exports = LockConstraint; + +/** + * Locks the relative position and rotation between two bodies. + * + * @class LockConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions. + * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles. + * @param {number} [options.maxForce] + * @extends Constraint + * + * @example + * // Locks the relative position and rotation between bodyA and bodyB + * var constraint = new LockConstraint(bodyA, bodyB); + * world.addConstraint(constraint); + */ +function LockConstraint(bodyA, bodyB, options){ + options = options || {}; + + Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); + + var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); + + var localAngleB = options.localAngleB || 0; + + // Use 3 equations: + // gx = (xj - xi - l) * xhat = 0 + // gy = (xj - xi - l) * yhat = 0 + // gr = (xi - xj + r) * that = 0 + // + // ...where: + // l is the localOffsetB vector rotated to world in bodyA frame + // r is the same vector but reversed and rotated from bodyB frame + // xhat, yhat are world axis vectors + // that is the tangent of r + // + // For the first two constraints, we get + // G*W = (vj - vi - ldot ) * xhat + // = (vj - vi - wi x l) * xhat + // + // Since (wi x l) * xhat = (l x xhat) * wi, we get + // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] + // + // The last constraint gives + // GW = (vi - vj + wj x r) * that + // = [ that 0 -that (r x t) ] + + var x = new Equation(bodyA,bodyB,-maxForce,maxForce), + y = new Equation(bodyA,bodyB,-maxForce,maxForce), + rot = new Equation(bodyA,bodyB,-maxForce,maxForce); + + var l = vec2.create(), + g = vec2.create(), + that = this; + x.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[0]; + }; + y.computeGq = function(){ + vec2.rotate(l, that.localOffsetB, bodyA.angle); + vec2.sub(g, bodyB.position, bodyA.position); + vec2.sub(g, g, l); + return g[1]; + }; + var r = vec2.create(), + t = vec2.create(); + rot.computeGq = function(){ + vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); + vec2.scale(r,r,-1); + vec2.sub(g,bodyA.position,bodyB.position); + vec2.add(g,g,r); + vec2.rotate(t,r,-Math.PI/2); + vec2.normalize(t,t); + return vec2.dot(g,t); + }; + + /** + * The offset of bodyB in bodyA's frame. + * @property {Array} localOffsetB + */ + this.localOffsetB = vec2.create(); + if(options.localOffsetB){ + vec2.copy(this.localOffsetB, options.localOffsetB); + } else { + // Construct from current positions + vec2.sub(this.localOffsetB, bodyB.position, bodyA.position); + vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle); + } + + /** + * The offset angle of bodyB in bodyA's frame. + * @property {Number} localAngleB + */ + this.localAngleB = 0; + if(typeof(options.localAngleB) === 'number'){ + this.localAngleB = options.localAngleB; + } else { + // Construct + this.localAngleB = bodyB.angle - bodyA.angle; + } + + this.equations.push(x, y, rot); + this.setMaxForce(maxForce); +} +LockConstraint.prototype = new Constraint(); +LockConstraint.prototype.constructor = LockConstraint; + +/** + * Set the maximum force to be applied. + * @method setMaxForce + * @param {Number} force + */ +LockConstraint.prototype.setMaxForce = function(force){ + var eqs = this.equations; + for(var i=0; ithis tutorial. Also called "slider constraint". + * + * @class PrismaticConstraint + * @constructor + * @extends Constraint + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.maxForce] Max force to be applied by the constraint + * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. + * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. + * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. + * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. + * @param {Number} [options.upperLimit] + * @param {Number} [options.lowerLimit] + * @todo Ability to create using only a point and a worldAxis + */ +function PrismaticConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); + + // Get anchors + var localAnchorA = vec2.fromValues(0,0), + localAxisA = vec2.fromValues(1,0), + localAnchorB = vec2.fromValues(0,0); + if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); } + if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); } + if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); } + + /** + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = localAnchorA; + + /** + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = localAnchorB; + + /** + * @property localAxisA + * @type {Array} + */ + this.localAxisA = localAxisA; + + /* + + The constraint violation for the common axis point is + + g = ( xj + rj - xi - ri ) * t := gg*t + + where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. + + gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) + + Note the use of the chain rule. Now we identify the jacobian + + G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] + + The rotational part is just a rotation lock. + + */ + + var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE; + + // Translational part + var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); + var ri = new vec2.create(), + rj = new vec2.create(), + gg = new vec2.create(), + t = new vec2.create(); + trans.computeGq = function(){ + // g = ( xj + rj - xi - ri ) * t + return vec2.dot(gg,t); + }; + trans.updateJacobian = function(){ + var G = this.G, + xi = bodyA.position, + xj = bodyB.position; + vec2.rotate(ri,localAnchorA,bodyA.angle); + vec2.rotate(rj,localAnchorB,bodyB.angle); + vec2.add(gg,xj,rj); + vec2.sub(gg,gg,xi); + vec2.sub(gg,gg,ri); + vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); + + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + }; + this.equations.push(trans); + + // Rotational part + if(!options.disableRotationalLock){ + var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); + this.equations.push(rot); + } + + /** + * The position of anchor A relative to anchor B, along the constraint axis. + * @property position + * @type {Number} + */ + this.position = 0; + + // Is this one used at all? + this.velocity = 0; + + /** + * Set to true to enable lower limit. + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; + + /** + * Set to true to enable upper limit. + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; + + /** + * Lower constraint limit. The constraint position is forced to be larger than this value. + * @property lowerLimit + * @type {Number} + */ + this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; + + /** + * Upper constraint limit. The constraint position is forced to be smaller than this value. + * @property upperLimit + * @type {Number} + */ + this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; + + // Equations used for limits + this.upperLimitEquation = new ContactEquation(bodyA,bodyB); + this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); + + // Set max/min forces + this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; + this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; + + /** + * Equation used for the motor. + * @property motorEquation + * @type {Equation} + */ + this.motorEquation = new Equation(bodyA,bodyB); + + /** + * The current motor state. Enable or disable the motor using .enableMotor + * @property motorEnabled + * @type {Boolean} + */ + this.motorEnabled = false; + + /** + * Set the target speed for the motor. + * @property motorSpeed + * @type {Number} + */ + this.motorSpeed = 0; + + var that = this; + var motorEquation = this.motorEquation; + var old = motorEquation.computeGW; + motorEquation.computeGq = function(){ return 0; }; + motorEquation.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed; + }; +} + +PrismaticConstraint.prototype = new Constraint(); +PrismaticConstraint.prototype.constructor = PrismaticConstraint; + +var worldAxisA = vec2.create(), + worldAnchorA = vec2.create(), + worldAnchorB = vec2.create(), + orientedAnchorA = vec2.create(), + orientedAnchorB = vec2.create(), + tmp = vec2.create(); + +/** + * Update the constraint equations. Should be done if any of the bodies changed position, before solving. + * @method update + */ +PrismaticConstraint.prototype.update = function(){ + var eqs = this.equations, + trans = eqs[0], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation, + bodyA = this.bodyA, + bodyB = this.bodyB, + localAxisA = this.localAxisA, + localAnchorA = this.localAnchorA, + localAnchorB = this.localAnchorB; + + trans.updateJacobian(); + + // Transform local things to world + vec2.rotate(worldAxisA, localAxisA, bodyA.angle); + vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); + vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); + vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); + vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); + + var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); + + // Motor + if(this.motorEnabled){ + // G = [ a a x ri -a -a x rj ] + var G = this.motorEquation.G; + G[0] = worldAxisA[0]; + G[1] = worldAxisA[1]; + G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); + G[3] = -worldAxisA[0]; + G[4] = -worldAxisA[1]; + G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); + } + + /* + Limits strategy: + Add contact equation, with normal along the constraint axis. + min/maxForce is set so the constraint is repulsive in the correct direction. + Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. + + ^ + | + upperLimit x + | ------ + anchorB x<---| B | + | | | + ------ | ------ + | | | + | A |-->x anchorA + ------ | + x lowerLimit + | + axis + */ + + + if(this.upperLimitEnabled && relPosition > upperLimit){ + // Update contact constraint normal, etc + 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 && relPosition < lowerLimit){ + // Update contact constraint normal, etc + vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); + vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); + vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); + vec2.scale(tmp,worldAxisA,lowerLimit); + vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } +}; + +/** + * Enable the motor + * @method enableMotor + */ +PrismaticConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +PrismaticConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the constraint limits. + * @method setLimits + * @param {number} lower Lower limit. + * @param {number} upper Upper limit. + */ +PrismaticConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + + +},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(_dereq_,module,exports){ +var Constraint = _dereq_('./Constraint') +, Equation = _dereq_('../equations/Equation') +, RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation') +, RotationalLockEquation = _dereq_('../equations/RotationalLockEquation') +, vec2 = _dereq_('../math/vec2'); + +module.exports = RevoluteConstraint; + +var worldPivotA = vec2.create(), + worldPivotB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1), + g = vec2.create(); + +/** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * @class RevoluteConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to. + * @param {Array} [options.localPivotB] See localPivotA. + * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. + * @extends Constraint + * + * @example + * // This will create a revolute constraint between two bodies with pivot point in between them. + * var bodyA = new Body({ mass: 1, position: [-1, 0] }); + * var bodyB = new Body({ mass: 1, position: [1, 0] }); + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * worldPivot: [0, 0] + * }); + * world.addConstraint(constraint); + * + * // Using body-local pivot points, the constraint could have been constructed like this: + * var constraint = new RevoluteConstraint(bodyA, bodyB, { + * localPivotA: [1, 0], + * localPivotB: [-1, 0] + * }); + */ +function RevoluteConstraint(bodyA, bodyB, options){ + options = options || {}; + Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); + + var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; + + /** + * @property {Array} pivotA + */ + this.pivotA = vec2.create(); + + /** + * @property {Array} pivotB + */ + this.pivotB = vec2.create(); + + if(options.worldPivot){ + // Compute pivotA and pivotB + vec2.sub(this.pivotA, options.worldPivot, bodyA.position); + vec2.sub(this.pivotB, options.worldPivot, bodyB.position); + // Rotate to local coordinate system + vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle); + vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle); + } else { + // Get pivotA and pivotB + vec2.copy(this.pivotA, options.localPivotA); + vec2.copy(this.pivotB, options.localPivotB); + } + + // Equations to be fed to the solver + var eqs = this.equations = [ + new Equation(bodyA,bodyB,-maxForce,maxForce), + new Equation(bodyA,bodyB,-maxForce,maxForce), + ]; + + var x = eqs[0]; + var y = eqs[1]; + var that = this; + + x.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,xAxis); + }; + + y.computeGq = function(){ + vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); + vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); + vec2.add(g, bodyB.position, worldPivotB); + vec2.sub(g, g, bodyA.position); + vec2.sub(g, g, worldPivotA); + return vec2.dot(g,yAxis); + }; + + y.minForce = x.minForce = -maxForce; + y.maxForce = x.maxForce = maxForce; + + this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); + + /** + * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. + * @property {Boolean} motorEnabled + * @readOnly + */ + this.motorEnabled = false; + + /** + * The constraint position. + * @property angle + * @type {Number} + * @readOnly + */ + this.angle = 0; + + /** + * Set to true to enable lower limit + * @property lowerLimitEnabled + * @type {Boolean} + */ + this.lowerLimitEnabled = false; + + /** + * Set to true to enable upper limit + * @property upperLimitEnabled + * @type {Boolean} + */ + this.upperLimitEnabled = false; + + /** + * The lower limit on the constraint angle. + * @property lowerLimit + * @type {Boolean} + */ + this.lowerLimit = 0; + + /** + * The upper limit on the constraint angle. + * @property upperLimit + * @type {Boolean} + */ + this.upperLimit = 0; + + this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); + this.upperLimitEquation.minForce = 0; + this.lowerLimitEquation.maxForce = 0; +} +RevoluteConstraint.prototype = new Constraint(); +RevoluteConstraint.prototype.constructor = RevoluteConstraint; + +/** + * Set the constraint angle limits. + * @method setLimits + * @param {number} lower Lower angle limit. + * @param {number} upper Upper angle limit. + */ +RevoluteConstraint.prototype.setLimits = function (lower, upper) { + if(typeof(lower) === 'number'){ + this.lowerLimit = lower; + this.lowerLimitEnabled = true; + } else { + this.lowerLimit = lower; + this.lowerLimitEnabled = false; + } + + if(typeof(upper) === 'number'){ + this.upperLimit = upper; + this.upperLimitEnabled = true; + } else { + this.upperLimit = upper; + this.upperLimitEnabled = false; + } +}; + +RevoluteConstraint.prototype.update = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + pivotA = this.pivotA, + pivotB = this.pivotB, + eqs = this.equations, + normal = eqs[0], + tangent= eqs[1], + x = eqs[0], + y = eqs[1], + upperLimit = this.upperLimit, + lowerLimit = this.lowerLimit, + upperLimitEquation = this.upperLimitEquation, + lowerLimitEquation = this.lowerLimitEquation; + + var relAngle = this.angle = bodyB.angle - bodyA.angle; + + if(this.upperLimitEnabled && relAngle > upperLimit){ + 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 < lowerLimit){ + lowerLimitEquation.angle = lowerLimit; + if(eqs.indexOf(lowerLimitEquation) === -1){ + eqs.push(lowerLimitEquation); + } + } else { + var idx = eqs.indexOf(lowerLimitEquation); + if(idx !== -1){ + eqs.splice(idx,1); + } + } + + /* + + The constraint violation is + + g = xj + rj - xi - ri + + ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: + + gdot = vj + wj x rj - vi - wi x ri + + We split this into x and y directions. (let x and y be unit vectors along the respective axes) + + gdot * x = ( vj + wj x rj - vi - wi x ri ) * x + = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x + = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi + = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] + = G*W + + ...and similar for y. We have then identified the jacobian entries for x and y directions: + + Gx = [ x (rj x x) -x -(ri x x)] + Gy = [ y (rj x y) -y -(ri x y)] + + */ + + vec2.rotate(worldPivotA, pivotA, bodyA.angle); + vec2.rotate(worldPivotB, pivotB, bodyB.angle); + + // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc + + x.G[0] = -1; + x.G[1] = 0; + x.G[2] = -vec2.crossLength(worldPivotA,xAxis); + x.G[3] = 1; + x.G[4] = 0; + x.G[5] = vec2.crossLength(worldPivotB,xAxis); + + y.G[0] = 0; + y.G[1] = -1; + y.G[2] = -vec2.crossLength(worldPivotA,yAxis); + y.G[3] = 0; + y.G[4] = 1; + y.G[5] = vec2.crossLength(worldPivotB,yAxis); +}; + +/** + * Enable the rotational motor + * @method enableMotor + */ +RevoluteConstraint.prototype.enableMotor = function(){ + if(this.motorEnabled){ + return; + } + this.equations.push(this.motorEquation); + this.motorEnabled = true; +}; + +/** + * Disable the rotational motor + * @method disableMotor + */ +RevoluteConstraint.prototype.disableMotor = function(){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations.splice(i,1); + this.motorEnabled = false; +}; + +/** + * Set the speed of the rotational constraint motor + * @method setMotorSpeed + * @param {Number} speed + */ +RevoluteConstraint.prototype.setMotorSpeed = function(speed){ + if(!this.motorEnabled){ + return; + } + var i = this.equations.indexOf(this.motorEquation); + this.equations[i].relativeVelocity = speed; +}; + +/** + * Get the speed of the rotational constraint motor + * @method getMotorSpeed + * @return {Number} The current speed, or false if the motor is not enabled. + */ +RevoluteConstraint.prototype.getMotorSpeed = function(){ + if(!this.motorEnabled){ + return false; + } + return this.motorEquation.relativeVelocity; +}; + +},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = AngleLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class AngleLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in body A. + * @param {Number} [options.ratio] Gear ratio + */ +function AngleLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); + this.angle = options.angle || 0; + + /** + * The gear ratio. + * @property {Number} ratio + * @private + * @see setRatio + */ + this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; + + this.setRatio(this.ratio); +} +AngleLockEquation.prototype = new Equation(); +AngleLockEquation.prototype.constructor = AngleLockEquation; + +AngleLockEquation.prototype.computeGq = function(){ + return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; +}; + +/** + * Set the gear ratio for this equation + * @method setRatio + * @param {Number} ratio + */ +AngleLockEquation.prototype.setRatio = function(ratio){ + var G = this.G; + G[2] = ratio; + G[5] = -1; + this.ratio = ratio; +}; + +/** + * Set the max force for the equation. + * @method setMaxTorque + * @param {Number} torque + */ +AngleLockEquation.prototype.setMaxTorque = function(torque){ + this.maxForce = torque; + this.minForce = -torque; +}; + +},{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = ContactEquation; + +/** + * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive. + * + * @class ContactEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function ContactEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); + + /** + * Vector from body i center of mass to the contact point. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + this.penetrationVec = vec2.create(); + + /** + * World-oriented vector from body A center of mass to the contact point. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * The normal vector, pointing out of body i + * @property normalA + * @type {Array} + */ + this.normalA = vec2.create(); + + /** + * The restitution to use (0=no bounciness, 1=max bounciness). + * @property restitution + * @type {Number} + */ + this.restitution = 0; + + /** + * This property is set to true if this is the first impact between the bodies (not persistant contact). + * @property firstImpact + * @type {Boolean} + * @readOnly + */ + this.firstImpact = false; + + /** + * The shape in body i that triggered this contact. + * @property shapeA + * @type {Shape} + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this contact. + * @property shapeB + * @type {Shape} + */ + this.shapeB = null; +} +ContactEquation.prototype = new Equation(); +ContactEquation.prototype.constructor = ContactEquation; +ContactEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + xi = bi.position, + xj = bj.position; + + var penetrationVec = this.penetrationVec, + n = this.normalA, + G = this.G; + + // Caluclate cross products + var rixn = vec2.crossLength(ri,n), + rjxn = vec2.crossLength(rj,n); + + // G = [-n -rixn n rjxn] + G[0] = -n[0]; + G[1] = -n[1]; + G[2] = -rixn; + G[3] = n[0]; + G[4] = n[1]; + G[5] = rjxn; + + // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector + vec2.add(penetrationVec,xj,rj); + vec2.sub(penetrationVec,penetrationVec,xi); + vec2.sub(penetrationVec,penetrationVec,ri); + + // Compute iteration + var GW, Gq; + if(this.firstImpact && this.restitution !== 0){ + Gq = 0; + GW = (1/b)*(1+this.restitution) * this.computeGW(); + } else { + Gq = vec2.dot(n,penetrationVec) + this.offset; + GW = this.computeGW(); + } + + var GiMf = this.computeGiMf(); + var B = - Gq * a - GW * b - h*GiMf; + + return B; +}; + +var vi = vec2.create(); +var vj = vec2.create(); +var relVel = vec2.create(); + +/** + * Get the relative velocity along the normal vector. + * @return {number} + */ +ContactEquation.prototype.getVelocityAlongNormal = function(){ + + this.bodyA.getVelocityAtPoint(vi, this.contactPointA); + this.bodyB.getVelocityAtPoint(vj, this.contactPointB); + + vec2.subtract(relVel, vi, vj); + + return vec2.dot(this.normalA, relVel); +}; +},{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){ +module.exports = Equation; + +var vec2 = _dereq_('../math/vec2'), + Utils = _dereq_('../utils/Utils'), + Body = _dereq_('../objects/Body'); + +/** + * Base class for constraint equations. + * @class Equation + * @constructor + * @param {Body} bodyA First body participating in the equation + * @param {Body} bodyB Second body participating in the equation + * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE + * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE + */ +function Equation(bodyA, bodyB, minForce, maxForce){ + + /** + * Minimum force to apply when solving. + * @property minForce + * @type {Number} + */ + this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; + + /** + * Max force to apply when solving. + * @property maxForce + * @type {Number} + */ + this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; + + /** + * First body participating in the constraint + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second body participating in the constraint + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; + + /** + * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. + * @property stiffness + * @type {Number} + */ + this.stiffness = Equation.DEFAULT_STIFFNESS; + + /** + * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. + * @property relaxation + * @type {Number} + */ + this.relaxation = Equation.DEFAULT_RELAXATION; + + /** + * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). + * @property G + * @type {Array} + */ + this.G = new Utils.ARRAY_TYPE(6); + for(var i=0; i<6; i++){ + this.G[i]=0; + } + + this.offset = 0; + + this.a = 0; + this.b = 0; + this.epsilon = 0; + this.timeStep = 1/60; + + /** + * Indicates if stiffness or relaxation was changed. + * @property {Boolean} needsUpdate + */ + this.needsUpdate = true; + + /** + * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. + * @property multiplier + * @type {Number} + */ + this.multiplier = 0; + + /** + * Relative velocity. + * @property {Number} relativeVelocity + */ + this.relativeVelocity = 0; + + /** + * Whether this equation is enabled or not. If true, it will be added to the solver. + * @property {Boolean} enabled + */ + this.enabled = true; +} +Equation.prototype.constructor = Equation; + +/** + * The default stiffness when creating a new Equation. + * @static + * @property {Number} DEFAULT_STIFFNESS + * @default 1e6 + */ +Equation.DEFAULT_STIFFNESS = 1e6; + +/** + * The default relaxation when creating a new Equation. + * @static + * @property {Number} DEFAULT_RELAXATION + * @default 4 + */ +Equation.DEFAULT_RELAXATION = 4; + +/** + * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the SPOOK notes. + * @method update + */ +Equation.prototype.update = function(){ + var k = this.stiffness, + d = this.relaxation, + h = this.timeStep; + + this.a = 4.0 / (h * (1 + 4 * d)); + this.b = (4.0 * d) / (1 + 4 * d); + this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); + + this.needsUpdate = false; +}; + +/** + * Multiply a jacobian entry with corresponding positions or velocities + * @method gmult + * @return {Number} + */ +Equation.prototype.gmult = function(G,vi,wi,vj,wj){ + return G[0] * vi[0] + + G[1] * vi[1] + + G[2] * wi + + G[3] * vj[0] + + G[4] * vj[1] + + G[5] * wj; +}; + +/** + * Computes the RHS of the SPOOK equation + * @method computeB + * @return {Number} + */ +Equation.prototype.computeB = function(a,b,h){ + var GW = this.computeGW(); + var Gq = this.computeGq(); + var GiMf = this.computeGiMf(); + return - Gq * a - GW * b - GiMf*h; +}; + +/** + * Computes G\*q, where q are the generalized body coordinates + * @method computeGq + * @return {Number} + */ +var qi = vec2.create(), + qj = vec2.create(); +Equation.prototype.computeGq = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + xi = bi.position, + xj = bj.position, + ai = bi.angle, + aj = bj.angle; + + return this.gmult(G, qi, ai, qj, aj) + this.offset; +}; + +/** + * Computes G\*W, where W are the body velocities + * @method computeGW + * @return {Number} + */ +Equation.prototype.computeGW = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity, + wj = bj.angularVelocity; + return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity; +}; + +/** + * Computes G\*Wlambda, where W are the body velocities + * @method computeGWlambda + * @return {Number} + */ +Equation.prototype.computeGWlambda = function(){ + var G = this.G, + bi = this.bodyA, + bj = this.bodyB, + vi = bi.vlambda, + vj = bj.vlambda, + wi = bi.wlambda, + wj = bj.wlambda; + return this.gmult(G,vi,wi,vj,wj); +}; + +/** + * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. + * @method computeGiMf + * @return {Number} + */ +var iMfi = vec2.create(), + iMfj = vec2.create(); +Equation.prototype.computeGiMf = function(){ + var bi = this.bodyA, + bj = this.bodyB, + fi = bi.force, + ti = bi.angularForce, + fj = bj.force, + tj = bj.angularForce, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + vec2.scale(iMfi, fi, invMassi); + vec2.multiply(iMfi, bi.massMultiplier, iMfi); + vec2.scale(iMfj, fj,invMassj); + vec2.multiply(iMfj, bj.massMultiplier, iMfj); + + return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); +}; + +/** + * Computes G\*inv(M)\*G' + * @method computeGiMGt + * @return {Number} + */ +Equation.prototype.computeGiMGt = function(){ + var bi = this.bodyA, + bj = this.bodyB, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + G = this.G; + + return G[0] * G[0] * invMassi * bi.massMultiplier[0] + + G[1] * G[1] * invMassi * bi.massMultiplier[1] + + G[2] * G[2] * invIi + + G[3] * G[3] * invMassj * bj.massMultiplier[0] + + G[4] * G[4] * invMassj * bj.massMultiplier[1] + + G[5] * G[5] * invIj; +}; + +var addToWlambda_temp = vec2.create(), + addToWlambda_Gi = vec2.create(), + addToWlambda_Gj = vec2.create(), + addToWlambda_ri = vec2.create(), + addToWlambda_rj = vec2.create(), + addToWlambda_Mdiag = vec2.create(); + +/** + * Add constraint velocity to the bodies. + * @method addToWlambda + * @param {Number} deltalambda + */ +Equation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bodyA, + bj = this.bodyB, + temp = addToWlambda_temp, + Gi = addToWlambda_Gi, + Gj = addToWlambda_Gj, + ri = addToWlambda_ri, + rj = addToWlambda_rj, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaSolve, + invIj = bj.invInertiaSolve, + Mdiag = addToWlambda_Mdiag, + G = this.G; + + Gi[0] = G[0]; + Gi[1] = G[1]; + Gj[0] = G[3]; + Gj[1] = G[4]; + + // Add to linear velocity + // v_lambda += inv(M) * delta_lamba * G + vec2.scale(temp, Gi, invMassi*deltalambda); + vec2.multiply(temp, temp, bi.massMultiplier); + vec2.add( bi.vlambda, bi.vlambda, temp); + // This impulse is in the offset frame + // Also add contribution to angular + //bi.wlambda -= vec2.crossLength(temp,ri); + bi.wlambda += invIi * G[2] * deltalambda; + + + vec2.scale(temp, Gj, invMassj*deltalambda); + vec2.multiply(temp, temp, bj.massMultiplier); + vec2.add( bj.vlambda, bj.vlambda, temp); + //bj.wlambda -= vec2.crossLength(temp,rj); + bj.wlambda += invIj * G[5] * deltalambda; +}; + +/** + * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps + * @method computeInvC + * @param {Number} eps + * @return {Number} + */ +Equation.prototype.computeInvC = function(eps){ + return 1.0 / (this.computeGiMGt() + eps); +}; + +},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Equation = _dereq_('./Equation') +, Utils = _dereq_('../utils/Utils'); + +module.exports = FrictionEquation; + +/** + * Constrains the slipping in a contact along a tangent + * + * @class FrictionEquation + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Number} slipForce + * @extends Equation + */ +function FrictionEquation(bodyA, bodyB, slipForce){ + Equation.call(this, bodyA, bodyB, -slipForce, slipForce); + + /** + * Relative vector from center of body A to the contact point, world oriented. + * @property contactPointA + * @type {Array} + */ + this.contactPointA = vec2.create(); + + /** + * Relative vector from center of body B to the contact point, world oriented. + * @property contactPointB + * @type {Array} + */ + this.contactPointB = vec2.create(); + + /** + * Tangent vector that the friction force will act along. World oriented. + * @property t + * @type {Array} + */ + this.t = vec2.create(); + + /** + * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average. + * @property contactEquations + * @type {ContactEquation} + */ + this.contactEquations = []; + + /** + * The shape in body i that triggered this friction. + * @property shapeA + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeA... + */ + this.shapeA = null; + + /** + * The shape in body j that triggered this friction. + * @property shapeB + * @type {Shape} + * @todo Needed? The shape can be looked up via contactEquation.shapeB... + */ + this.shapeB = null; + + /** + * The friction coefficient to use. + * @property frictionCoefficient + * @type {Number} + */ + this.frictionCoefficient = 0.3; +} +FrictionEquation.prototype = new Equation(); +FrictionEquation.prototype.constructor = FrictionEquation; + +/** + * Set the slipping condition for the constraint. The friction force cannot be + * larger than this value. + * @method setSlipForce + * @param {Number} slipForce + */ +FrictionEquation.prototype.setSlipForce = function(slipForce){ + this.maxForce = slipForce; + this.minForce = -slipForce; +}; + +/** + * Get the max force for the constraint. + * @method getSlipForce + * @return {Number} + */ +FrictionEquation.prototype.getSlipForce = function(){ + return this.maxForce; +}; + +FrictionEquation.prototype.computeB = function(a,b,h){ + var bi = this.bodyA, + bj = this.bodyB, + ri = this.contactPointA, + rj = this.contactPointB, + t = this.t, + G = this.G; + + // G = [-t -rixt t rjxt] + // And remember, this is a pure velocity constraint, g is always zero! + G[0] = -t[0]; + G[1] = -t[1]; + G[2] = -vec2.crossLength(ri,t); + G[3] = t[0]; + G[4] = t[1]; + G[5] = vec2.crossLength(rj,t); + + var GW = this.computeGW(), + GiMf = this.computeGiMf(); + + var B = /* - g * a */ - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalLockEquation; + +/** + * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. + * + * @class RotationalLockEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {Number} [options.angle] Angle to add to the local vector in bodyA. + */ +function RotationalLockEquation(bodyA, bodyB, options){ + options = options || {}; + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + + /** + * @property {number} angle + */ + this.angle = options.angle || 0; + + var G = this.G; + G[2] = 1; + G[5] = -1; +} +RotationalLockEquation.prototype = new Equation(); +RotationalLockEquation.prototype.constructor = RotationalLockEquation; + +var worldVectorA = vec2.create(), + worldVectorB = vec2.create(), + xAxis = vec2.fromValues(1,0), + yAxis = vec2.fromValues(0,1); +RotationalLockEquation.prototype.computeGq = function(){ + vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); + vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); + return vec2.dot(worldVectorA,worldVectorB); +}; + +},{"../math/vec2":30,"./Equation":22}],25:[function(_dereq_,module,exports){ +var Equation = _dereq_("./Equation"), + vec2 = _dereq_('../math/vec2'); + +module.exports = RotationalVelocityEquation; + +/** + * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). + * + * @class RotationalVelocityEquation + * @constructor + * @extends Equation + * @param {Body} bodyA + * @param {Body} bodyB + */ +function RotationalVelocityEquation(bodyA, bodyB){ + Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); + this.relativeVelocity = 1; + this.ratio = 1; +} +RotationalVelocityEquation.prototype = new Equation(); +RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; +RotationalVelocityEquation.prototype.computeB = function(a,b,h){ + var G = this.G; + G[2] = -1; + G[5] = this.ratio; + + var GiMf = this.computeGiMf(); + var GW = this.computeGW(); + var B = - GW * b - h*GiMf; + + return B; +}; + +},{"../math/vec2":30,"./Equation":22}],26:[function(_dereq_,module,exports){ +/** + * Base class for objects that dispatches events. + * @class EventEmitter + * @constructor + */ +var EventEmitter = function () {}; + +module.exports = EventEmitter; + +EventEmitter.prototype = { + constructor: EventEmitter, + + /** + * Add an event listener + * @method on + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + on: function ( type, listener, context ) { + listener.context = context || this; + if ( this._listeners === undefined ){ + this._listeners = {}; + } + var listeners = this._listeners; + if ( listeners[ type ] === undefined ) { + listeners[ type ] = []; + } + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + listeners[ type ].push( listener ); + } + return this; + }, + + /** + * Check if an event listener is added + * @method has + * @param {String} type + * @param {Function} listener + * @return {Boolean} + */ + has: function ( type, listener ) { + if ( this._listeners === undefined ){ + return false; + } + var listeners = this._listeners; + if(listener){ + if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { + return true; + } + } else { + if ( listeners[ type ] !== undefined ) { + return true; + } + } + + return false; + }, + + /** + * Remove an event listener + * @method off + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ + off: function ( type, listener ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var index = listeners[ type ].indexOf( listener ); + if ( index !== - 1 ) { + listeners[ type ].splice( index, 1 ); + } + return this; + }, + + /** + * Emit an event. + * @method emit + * @param {Object} event + * @param {String} event.type + * @return {EventEmitter} The self object, for chainability. + */ + emit: function ( event ) { + if ( this._listeners === undefined ){ + return this; + } + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; + if ( listenerArray !== undefined ) { + event.target = this; + for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { + var listener = listenerArray[ i ]; + listener.call( listener.context, event ); + } + } + return this; + } +}; + +},{}],27:[function(_dereq_,module,exports){ +var Material = _dereq_('./Material'); +var Equation = _dereq_('../equations/Equation'); + +module.exports = ContactMaterial; + +/** + * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. + * @class ContactMaterial + * @constructor + * @param {Material} materialA + * @param {Material} materialB + * @param {Object} [options] + * @param {Number} [options.friction=0.3] Friction coefficient. + * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". + * @param {Number} [options.stiffness] ContactEquation stiffness. + * @param {Number} [options.relaxation] ContactEquation relaxation. + * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. + * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. + * @param {Number} [options.surfaceVelocity=0] Surface velocity. + * @author schteppe + */ +function ContactMaterial(materialA, materialB, options){ + options = options || {}; + + if(!(materialA instanceof Material) || !(materialB instanceof Material)){ + throw new Error("First two arguments must be Material instances."); + } + + /** + * The contact material identifier + * @property id + * @type {Number} + */ + this.id = ContactMaterial.idCounter++; + + /** + * First material participating in the contact material + * @property materialA + * @type {Material} + */ + this.materialA = materialA; + + /** + * Second material participating in the contact material + * @property materialB + * @type {Material} + */ + this.materialB = materialB; + + /** + * Friction coefficient to use in the contact of these two materials. Friction = 0 will make the involved objects super slippery, and friction = 1 will make it much less slippery. A friction coefficient larger than 1 will allow for very large friction forces, which can be convenient for preventing car tires not slip on the ground. + * @property friction + * @type {Number} + * @default 0.3 + */ + this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; + + /** + * Restitution, or "bounciness" to use in the contact of these two materials. A restitution of 0 will make no bounce, while restitution=1 will approximately bounce back with the same velocity the object came with. + * @property restitution + * @type {Number} + * @default 0 + */ + this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0; + + /** + * Hardness of the contact. Less stiffness will make the objects penetrate more, and will make the contact act more like a spring than a contact force. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property stiffness + * @type {Number} + */ + this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting ContactEquation that this ContactMaterial generate. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property relaxation + * @type {Number} + */ + this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Stiffness of the resulting friction force. For most cases, the value of this property should be a large number. I cannot think of any case where you would want less frictionStiffness. Default value is {{#crossLink "Equation/DEFAULT_STIFFNESS:property"}}Equation.DEFAULT_STIFFNESS{{/crossLink}}. + * @property frictionStiffness + * @type {Number} + */ + this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; + + /** + * Relaxation of the resulting friction force. The default value should be good for most simulations. Default value is {{#crossLink "Equation/DEFAULT_RELAXATION:property"}}Equation.DEFAULT_RELAXATION{{/crossLink}}. + * @property frictionRelaxation + * @type {Number} + */ + this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; + + /** + * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + * @property {Number} surfaceVelocity + * @default 0 + */ + this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; + + /** + * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts". + * @property contactSkinSize + * @type {Number} + */ + this.contactSkinSize = 0.005; +} + +ContactMaterial.idCounter = 0; + +},{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){ +module.exports = Material; + +/** + * Defines a physics material. + * @class Material + * @constructor + * @param {number} id Material identifier + * @author schteppe + */ +function Material(id){ + /** + * The material identifier + * @property id + * @type {Number} + */ + this.id = id || Material.idCounter++; +} + +Material.idCounter = 0; + +},{}],29:[function(_dereq_,module,exports){ + + /* + PolyK library + url: http://polyk.ivank.net + Released under MIT licence. + + Copyright (c) 2012 Ivan Kuckir + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + */ + + var PolyK = {}; + + /* + Is Polygon self-intersecting? + + O(n^2) + */ + /* + PolyK.IsSimple = function(p) + { + var n = p.length>>1; + if(n<4) return true; + var a1 = new PolyK._P(), a2 = new PolyK._P(); + var b1 = new PolyK._P(), b2 = new PolyK._P(); + var c = new PolyK._P(); + + for(var i=0; i>1; + if(n<3) return []; + var tgs = []; + var avl = []; + for(var i=0; i 3) + { + 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; j 3*al) break; // no convex angles :( + } + tgs.push(avl[0], avl[1], avl[2]); + return tgs; + } + /* + PolyK.ContainsPoint = function(p, px, py) + { + var n = p.length>>1; + var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; + var depth = 0; + for(var i=0; i=0 && by>=0) continue; // both "up" or both "donw" + if(ax< 0 && bx< 0) continue; + + var lx = ax + (bx-ax)*(-ay)/(by-ay); + if(lx>0) depth++; + } + return (depth & 1) == 1; + } + + PolyK.Slice = function(p, ax, ay, bx, by) + { + if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; + + var a = new PolyK._P(ax, ay); + var b = new PolyK._P(bx, by); + var iscs = []; // intersections + var ps = []; // points + for(var i=0; i 0) + { + var n = ps.length; + var i0 = iscs[0]; + var i1 = iscs[1]; + var ind0 = ps.indexOf(i0); + var ind1 = ps.indexOf(i1); + var solved = false; + + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + else + { + i0 = iscs[1]; + i1 = iscs[0]; + ind0 = ps.indexOf(i0); + ind1 = ps.indexOf(i1); + if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; + } + if(solved) + { + dir--; + var pgn = PolyK._getPoints(ps, ind0, ind1); + pgs.push(pgn); + ps = PolyK._getPoints(ps, ind1, ind0); + i0.flag = i1.flag = false; + iscs.splice(0,2); + if(iscs.length == 0) pgs.push(ps); + } + else { dir++; iscs.reverse(); } + if(dir>1) break; + } + var result = []; + for(var i=0; i>1, isc); + } + b1.x = b2.x; b1.y = b2.y; + b2.x = p[0]; b2.y = p[1]; + PolyK._pointLineDist(a1, b1, b2, l>>1, isc); + + var idst = 1/isc.dist; + isc.norm.x = (x-isc.point.x)*idst; + isc.norm.y = (y-isc.point.y)*idst; + return isc; + } + + PolyK._pointLineDist = function(p, a, b, edge, isc) + { + var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; + + var A = x - x1; + var B = y - y1; + var C = x2 - x1; + var D = y2 - y1; + + var dot = A * C + B * D; + var len_sq = C * C + D * D; + var param = dot / len_sq; + + var xx, yy; + + if (param < 0 || (x1 == x2 && y1 == y2)) { + xx = x1; + yy = y1; + } + else if (param > 1) { + xx = x2; + yy = y2; + } + else { + xx = x1 + param * C; + yy = y1 + param * D; + } + + var dx = x - xx; + var dy = y - yy; + var dst = Math.sqrt(dx * dx + dy * dy); + if(dst= 0) && (v >= 0) && (u + v < 1); + } + /* + PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) + { + var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); + var day = (a1.y-a2.y), dby = (b1.y-b2.y); + + var Den = dax*dby - day*dbx; + if (Den == 0) return null; // parallel + + var A = (a1.x * a2.y - a1.y * a2.x); + var B = (b1.x * b2.y - b1.y * b2.x); + + var I = c; + var iDen = 1/Den; + I.x = ( A*dbx - dax*B ) * iDen; + I.y = ( A*dby - day*B ) * iDen; + + if(!PolyK._InRect(I, b1, b2)) return null; + if((day>0 && I.y>a1.y) || (day<0 && I.y0 && I.x>a1.x) || (dax<0 && I.x=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); + if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); + + if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) + && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) + return true; + return false; + } + */ + PolyK._convex = function(ax, ay, bx, by, cx, cy) + { + return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; + } + /* + PolyK._P = function(x,y) + { + this.x = x; + this.y = y; + this.flag = false; + } + PolyK._P.prototype.toString = function() + { + return "Point ["+this.x+", "+this.y+"]"; + } + PolyK._P.dist = function(a,b) + { + var dx = b.x-a.x; + var dy = b.y-a.y; + return Math.sqrt(dx*dx + dy*dy); + } + + PolyK._tp = []; + for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); + */ + +module.exports = PolyK; + +},{}],30:[function(_dereq_,module,exports){ +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net. + * @class vec2 + */ + +var vec2 = module.exports = {}; + +var Utils = _dereq_('../utils/Utils'); + +/** + * Make a cross product and only return the z component + * @method crossLength + * @static + * @param {Array} a + * @param {Array} b + * @return {Number} + */ +vec2.crossLength = function(a,b){ + return a[0] * b[1] - a[1] * b[0]; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossVZ + * @static + * @param {Array} out + * @param {Array} vec + * @param {Number} zcomp + * @return {Number} + */ +vec2.crossVZ = function(out, vec, zcomp){ + vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Cross product between a vector and the Z component of a vector + * @method crossZV + * @static + * @param {Array} out + * @param {Number} zcomp + * @param {Array} vec + * @return {Number} + */ +vec2.crossZV = function(out, zcomp, vec){ + vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule + vec2.scale(out,out,zcomp); // Scale with z + return out; +}; + +/** + * Rotate a vector by an angle + * @method rotate + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate = function(out,a,angle){ + if(angle !== 0){ + 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; + } else { + out[0] = a[0]; + out[1] = a[1]; + } +}; + +/** + * Rotate a vector 90 degrees clockwise + * @method rotate90cw + * @static + * @param {Array} out + * @param {Array} a + * @param {Number} angle + */ +vec2.rotate90cw = function(out, a) { + var x = a[0]; + var y = a[1]; + out[0] = y; + out[1] = -x; +}; + +/** + * Transform a point position to local frame. + * @method toLocalFrame + * @param {Array} out + * @param {Array} worldPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ + vec2.copy(out, worldPoint); + vec2.sub(out, out, framePosition); + vec2.rotate(out, out, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localPoint + * @param {Array} framePosition + * @param {Number} frameAngle + */ +vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ + vec2.copy(out, localPoint); + vec2.rotate(out, out, frameAngle); + vec2.add(out, out, framePosition); +}; + +/** + * Transform a vector to local frame. + * @method vectorToLocalFrame + * @param {Array} out + * @param {Array} worldVector + * @param {Number} frameAngle + */ +vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){ + vec2.rotate(out, worldVector, -frameAngle); +}; + +/** + * Transform a point position to global frame. + * @method toGlobalFrame + * @param {Array} out + * @param {Array} localVector + * @param {Number} frameAngle + */ +vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){ + vec2.rotate(out, localVector, frameAngle); +}; + +/** + * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php + * @method centroid + * @static + * @param {Array} out + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Array} The out object + */ +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; +}; + +/** + * Creates a new, empty vec2 + * @static + * @method create + * @return {Array} a new 2D vector + */ +vec2.create = function() { + var out = new Utils.ARRAY_TYPE(2); + out[0] = 0; + out[1] = 0; + return out; +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * @static + * @method clone + * @param {Array} a vector to clone + * @return {Array} a new 2D vector + */ +vec2.clone = function(a) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Creates a new vec2 initialized with the given values + * @static + * @method fromValues + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} a new 2D vector + */ +vec2.fromValues = function(x, y) { + var out = new Utils.ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Copy the values from one vec2 to another + * @static + * @method copy + * @param {Array} out the receiving vector + * @param {Array} a the source vector + * @return {Array} out + */ +vec2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * @static + * @method set + * @param {Array} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @return {Array} out + */ +vec2.set = function(out, x, y) { + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Adds two vec2's + * @static + * @method add + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +}; + +/** + * Subtracts two vec2's + * @static + * @method subtract + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +}; + +/** + * Alias for vec2.subtract + * @static + * @method sub + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * @static + * @method multiply + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +}; + +/** + * Alias for vec2.multiply + * @static + * @method mul + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * @static + * @method divide + * @param {Array} out the receiving vector + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Array} out + */ +vec2.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +}; + +/** + * Alias for vec2.divide + * @static + * @method div + */ +vec2.div = vec2.divide; + +/** + * Scales a vec2 by a scalar number + * @static + * @method scale + * @param {Array} out the receiving vector + * @param {Array} a the vector to scale + * @param {Number} b amount to scale the vector by + * @return {Array} out + */ +vec2.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * @static + * @method distance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} distance between a and b + */ +vec2.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.distance + * @static + * @method dist + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * @static + * @method squaredDistance + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} squared distance between a and b + */ +vec2.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredDistance + * @static + * @method sqrDist + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * @static + * @method length + * @param {Array} a vector to calculate length of + * @return {Number} length of a + */ +vec2.length = function (a) { + var x = a[0], + y = a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for vec2.length + * @method len + * @static + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * @static + * @method squaredLength + * @param {Array} a vector to calculate squared length of + * @return {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a[0], + y = a[1]; + return x*x + y*y; +}; + +/** + * Alias for vec2.squaredLength + * @static + * @method sqrLen + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * @static + * @method negate + * @param {Array} out the receiving vector + * @param {Array} a vector to negate + * @return {Array} out + */ +vec2.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +}; + +/** + * Normalize a vec2 + * @static + * @method normalize + * @param {Array} out the receiving vector + * @param {Array} a vector to normalize + * @return {Array} out + */ +vec2.normalize = function(out, a) { + var x = a[0], + y = a[1]; + var len = x*x + y*y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * @static + * @method dot + * @param {Array} a the first operand + * @param {Array} b the second operand + * @return {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1]; +}; + +/** + * Returns a string representation of a vector + * @static + * @method str + * @param {Array} vec vector to represent as a string + * @return {String} string representation of the vector + */ +vec2.str = function (a) { + return 'vec2(' + a[0] + ', ' + a[1] + ')'; +}; + +/** + * Linearly interpolate/mix two vectors. + * @static + * @method lerp + * @param {Array} out + * @param {Array} a First vector + * @param {Array} b Second vector + * @param {number} t Lerp factor + */ +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; +}; + +/** + * Reflect a vector along a normal. + * @static + * @method reflect + * @param {Array} out + * @param {Array} vector + * @param {Array} normal + */ +vec2.reflect = function(out, vector, normal){ + var dot = vector[0] * normal[0] + vector[1] * normal[1]; + out[0] = vector[0] - 2 * normal[0] * dot; + out[1] = vector[1] - 2 * normal[1] * dot; +}; + +/** + * Get the intersection point between two line segments. + * @static + * @method getLineSegmentsIntersection + * @param {Array} out + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {boolean} True if there was an intersection, otherwise false. + */ +vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) { + var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3); + if(t < 0){ + return false; + } else { + out[0] = p0[0] + (t * (p1[0] - p0[0])); + out[1] = p0[1] + (t * (p1[1] - p0[1])); + return true; + } +}; + +/** + * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0) + * @static + * @method getLineSegmentsIntersectionFraction + * @param {Array} p0 + * @param {Array} p1 + * @param {Array} p2 + * @param {Array} p3 + * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1. + */ +vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) { + var s1_x = p1[0] - p0[0]; + var s1_y = p1[1] - p0[1]; + var s2_x = p3[0] - p2[0]; + var s2_y = p3[1] - p2[1]; + + var s, t; + s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y); + t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y); + if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + return t; + } + return -1; // No collision +}; + +},{"../utils/Utils":57}],31:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, decomp = _dereq_('poly-decomp') +, Convex = _dereq_('../shapes/Convex') +, RaycastResult = _dereq_('../collision/RaycastResult') +, Ray = _dereq_('../collision/Ray') +, AABB = _dereq_('../collision/AABB') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Body; + +/** + * A rigid body. Has got a center of mass, position, velocity and a number of + * shapes that are used for collisions. + * + * @class Body + * @constructor + * @extends EventEmitter + * @param {Array} [options.force] + * @param {Array} [options.position] + * @param {Array} [options.velocity] + * @param {Boolean} [options.allowSleep] + * @param {Boolean} [options.collisionResponse] + * @param {Number} [options.angle=0] + * @param {Number} [options.angularForce=0] + * @param {Number} [options.angularVelocity=0] + * @param {Number} [options.ccdIterations=10] + * @param {Number} [options.ccdSpeedThreshold=-1] + * @param {Number} [options.fixedRotation=false] + * @param {Number} [options.gravityScale] + * @param {Number} [options.id] + * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC. + * @param {Number} [options.sleepSpeedLimit] + * @param {Number} [options.sleepTimeLimit] + * @param {Object} [options] + * + * @example + * + * // Create a typical dynamic body + * var body = new Body({ + * mass: 1, + * position: [0, 0], + * angle: 0, + * velocity: [0, 0], + * angularVelocity: 0 + * }); + * + * // Add a circular shape to the body + * body.addShape(new Circle({ radius: 1 })); + * + * // Add the body to the world + * world.addBody(body); + */ +function Body(options){ + options = options || {}; + + EventEmitter.call(this); + + /** + * The body identifyer + * @property id + * @type {Number} + */ + this.id = options.id || ++Body._idCounter; + + /** + * The world that this body is added to. This property is set to NULL if the body is not added to any world. + * @property world + * @type {World} + */ + this.world = null; + + /** + * The shapes of the body. + * + * @property shapes + * @type {Array} + */ + this.shapes = []; + + /** + * The mass of the body. + * @property mass + * @type {number} + */ + this.mass = options.mass || 0; + + /** + * The inverse mass of the body. + * @property invMass + * @type {number} + */ + this.invMass = 0; + + /** + * The inertia of the body around the Z axis. + * @property inertia + * @type {number} + */ + this.inertia = 0; + + /** + * The inverse inertia of the body. + * @property invInertia + * @type {number} + */ + this.invInertia = 0; + + this.invMassSolve = 0; + this.invInertiaSolve = 0; + + /** + * Set to true if you want to fix the rotation of the body. + * @property fixedRotation + * @type {Boolean} + */ + this.fixedRotation = !!options.fixedRotation; + + /** + * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y. + * @property {Boolean} fixedX + */ + this.fixedX = !!options.fixedX; + + /** + * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X. + * @property {Boolean} fixedY + */ + this.fixedY = !!options.fixedY; + + /** + * @private + * @property {array} massMultiplier + */ + this.massMultiplier = vec2.create(); + + /** + * The position of the body + * @property position + * @type {Array} + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * The interpolated position of the body. Use this for rendering. + * @property interpolatedPosition + * @type {Array} + */ + this.interpolatedPosition = vec2.fromValues(0,0); + + /** + * The interpolated angle of the body. Use this for rendering. + * @property interpolatedAngle + * @type {Number} + */ + this.interpolatedAngle = 0; + + /** + * The previous position of the body. + * @property previousPosition + * @type {Array} + */ + this.previousPosition = vec2.fromValues(0,0); + + /** + * The previous angle of the body. + * @property previousAngle + * @type {Number} + */ + this.previousAngle = 0; + + /** + * The current velocity of the body. + * @property velocity + * @type {Array} + */ + this.velocity = vec2.fromValues(0,0); + if(options.velocity){ + vec2.copy(this.velocity, options.velocity); + } + + /** + * Constraint velocity that was added to the body during the last step. + * @property vlambda + * @type {Array} + */ + this.vlambda = vec2.fromValues(0,0); + + /** + * Angular constraint velocity that was added to the body during last step. + * @property wlambda + * @type {Array} + */ + this.wlambda = 0; + + /** + * The angle of the body, in radians. + * @property angle + * @type {number} + * @example + * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. + * // If you need a value between 0 and 2*pi, use the following function to normalize it. + * function normalizeAngle(angle){ + * angle = angle % (2*Math.PI); + * if(angle < 0){ + * angle += (2*Math.PI); + * } + * return angle; + * } + */ + this.angle = options.angle || 0; + + /** + * The angular velocity of the body, in radians per second. + * @property angularVelocity + * @type {number} + */ + this.angularVelocity = options.angularVelocity || 0; + + /** + * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. + * @property force + * @type {Array} + * + * @example + * // This produces a forcefield of 1 Newton in the positive x direction. + * for(var i=0; i radius){ + radius = offset + r; + } + } + + this.boundingRadius = radius; +}; + +/** + * Add a shape to the body. You can pass a local transform when adding a shape, + * so that the shape gets an offset and angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * + * @method addShape + * @param {Shape} shape + * @param {Array} [offset] Local body offset of the shape. + * @param {Number} [angle] Local body angle. + * + * @example + * var body = new Body(), + * shape = new Circle({ radius: 1 }); + * + * // Add the shape to the body, positioned in the center + * body.addShape(shape); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. + * body.addShape(shape,[1,0]); + * + * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. + * body.addShape(shape,[0,1],Math.PI/2); + */ +Body.prototype.addShape = function(shape, offset, angle){ + if(shape.body){ + throw new Error('A shape can only be added to one body.'); + } + shape.body = this; + + // Copy the offset vector + if(offset){ + vec2.copy(shape.position, offset); + } else { + vec2.set(shape.position, 0, 0); + } + + shape.angle = angle || 0; + + this.shapes.push(shape); + this.updateMassProperties(); + this.updateBoundingRadius(); + + this.aabbNeedsUpdate = true; +}; + +/** + * Remove a shape + * @method removeShape + * @param {Shape} shape + * @return {Boolean} True if the shape was found and removed, else false. + */ +Body.prototype.removeShape = function(shape){ + var idx = this.shapes.indexOf(shape); + + if(idx !== -1){ + this.shapes.splice(idx,1); + this.aabbNeedsUpdate = true; + shape.body = null; + return true; + } else { + return false; + } +}; + +/** + * Updates .inertia, .invMass, .invInertia for this Body. Should be called when + * changing the structure or mass of the Body. + * + * @method updateMassProperties + * + * @example + * body.mass += 1; + * body.updateMassProperties(); + */ +Body.prototype.updateMassProperties = function(){ + if(this.type === Body.STATIC || this.type === 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; + } + + // Inverse mass properties are easy + this.invMass = 1 / this.mass; + + vec2.set( + this.massMultiplier, + this.fixedX ? 0 : 1, + this.fixedY ? 0 : 1 + ); + } +}; + +var Body_applyForce_r = vec2.create(); + +/** + * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero. + * @method applyForce + * @param {Array} force The force to add. + * @param {Array} [relativePoint] A world point to apply the force on. + */ +Body.prototype.applyForce = function(force, relativePoint){ + + // Add linear force + vec2.add(this.force, this.force, force); + + if(relativePoint){ + + // Compute produced rotational force + var rotForce = vec2.crossLength(relativePoint,force); + + // Add rotational force + this.angularForce += rotForce; + } +}; + +/** + * Apply force to a body-local point. + * @method applyForceLocal + * @param {Array} localForce The force vector to add, oriented in local body space. + * @param {Array} [localPoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyForce_forceWorld = vec2.create(); +var Body_applyForce_pointWorld = vec2.create(); +var Body_applyForce_pointLocal = vec2.create(); +Body.prototype.applyForceLocal = function(localForce, localPoint){ + localPoint = localPoint || Body_applyForce_pointLocal; + var worldForce = Body_applyForce_forceWorld; + var worldPoint = Body_applyForce_pointWorld; + this.vectorToWorldFrame(worldForce, localForce); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyForce(worldForce, worldPoint); +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulse + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_velo = vec2.create(); +Body.prototype.applyImpulse = function(impulseVector, relativePoint){ + if(this.type !== Body.DYNAMIC){ + return; + } + + // Compute produced central impulse velocity + var velo = Body_applyImpulse_velo; + vec2.scale(velo, impulseVector, this.invMass); + vec2.multiply(velo, this.massMultiplier, velo); + + // Add linear impulse + vec2.add(this.velocity, velo, this.velocity); + + if(relativePoint){ + // Compute produced rotational impulse velocity + var rotVelo = vec2.crossLength(relativePoint, impulseVector); + rotVelo *= this.invInertia; + + // Add rotational Impulse + this.angularVelocity += rotVelo; + } +}; + +/** + * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulseLocal + * @param {Array} impulse The impulse vector to add, oriented in world space. + * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass. + */ +var Body_applyImpulse_impulseWorld = vec2.create(); +var Body_applyImpulse_pointWorld = vec2.create(); +var Body_applyImpulse_pointLocal = vec2.create(); +Body.prototype.applyImpulseLocal = function(localImpulse, localPoint){ + localPoint = localPoint || Body_applyImpulse_pointLocal; + var worldImpulse = Body_applyImpulse_impulseWorld; + var worldPoint = Body_applyImpulse_pointWorld; + this.vectorToWorldFrame(worldImpulse, localImpulse); + this.vectorToWorldFrame(worldPoint, localPoint); + this.applyImpulse(worldImpulse, worldPoint); +}; + +/** + * Transform a world point to local body frame. + * @method toLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldPoint The input world point + */ +Body.prototype.toLocalFrame = function(out, worldPoint){ + vec2.toLocalFrame(out, worldPoint, this.position, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method toWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localPoint The input local point + */ +Body.prototype.toWorldFrame = function(out, localPoint){ + vec2.toGlobalFrame(out, localPoint, this.position, this.angle); +}; + +/** + * Transform a world point to local body frame. + * @method vectorToLocalFrame + * @param {Array} out The vector to store the result in + * @param {Array} worldVector The input world vector + */ +Body.prototype.vectorToLocalFrame = function(out, worldVector){ + vec2.vectorToLocalFrame(out, worldVector, this.angle); +}; + +/** + * Transform a local point to world frame. + * @method vectorToWorldFrame + * @param {Array} out The vector to store the result in + * @param {Array} localVector The input local vector + */ +Body.prototype.vectorToWorldFrame = function(out, localVector){ + vec2.vectorToGlobalFrame(out, localVector, this.angle); +}; + +/** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. + * @method fromPolygon + * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. + * @param {Object} [options] + * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. + * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @return {Boolean} True on success, else false. + */ +Body.prototype.fromPolygon = function(path,options){ + options = options || {}; + + // Remove all shapes + for(var i=this.shapes.length; i>=0; --i){ + this.removeShape(this.shapes[i]); + } + + var p = new decomp.Polygon(); + p.vertices = path; + + // Make it counter-clockwise + p.makeCCW(); + + if(typeof(options.removeCollinearPoints) === "number"){ + p.removeCollinearPoints(options.removeCollinearPoints); + } + + // Check if any line segment intersects the path itself + if(typeof(options.skipSimpleCheck) === "undefined"){ + if(!p.isSimple()){ + return false; + } + } + + // Save this path for later + this.concavePath = p.vertices.slice(0); + for(var i=0; ithis for details. + * @method applyDamping + * @param {number} dt Current time step + */ +Body.prototype.applyDamping = function(dt){ + if(this.type === Body.DYNAMIC){ // Only for dynamic bodies + var v = this.velocity; + vec2.scale(v, v, Math.pow(1.0 - this.damping,dt)); + this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt); + } +}; + +/** + * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. + * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. + * @method wakeUp + */ +Body.prototype.wakeUp = function(){ + var s = this.sleepState; + this.sleepState = Body.AWAKE; + this.idleTime = 0; + if(s !== Body.AWAKE){ + this.emit(Body.wakeUpEvent); + } +}; + +/** + * Force body sleep + * @method sleep + */ +Body.prototype.sleep = function(){ + this.sleepState = Body.SLEEPING; + this.angularVelocity = 0; + this.angularForce = 0; + vec2.set(this.velocity,0,0); + vec2.set(this.force,0,0); + this.emit(Body.sleepEvent); +}; + +/** + * Called every timestep to update internal sleep timer and change sleep state if needed. + * @method sleepTick + * @param {number} time The world time in seconds + * @param {boolean} dontSleep + * @param {number} dt + */ +Body.prototype.sleepTick = function(time, dontSleep, dt){ + if(!this.allowSleep || this.type === Body.SLEEPING){ + return; + } + + this.wantsToSleep = false; + + var sleepState = this.sleepState, + speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), + speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); + + // Add to idle time + if(speedSquared >= 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; + } + } +}; + +/** + * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. + * @method overlaps + * @param {Body} body + * @return {boolean} + */ +Body.prototype.overlaps = function(body){ + return this.world.overlapKeeper.bodiesAreOverlapping(this, body); +}; + +var integrate_fhMinv = vec2.create(); +var integrate_velodt = vec2.create(); + +/** + * Move the body forward in time given its current velocity. + * @method integrate + * @param {Number} dt + */ +Body.prototype.integrate = function(dt){ + var minv = this.invMass, + f = this.force, + pos = this.position, + velo = this.velocity; + + // Save old position + vec2.copy(this.previousPosition, this.position); + this.previousAngle = this.angle; + + // Velocity update + if(!this.fixedRotation){ + this.angularVelocity += this.angularForce * this.invInertia * dt; + } + vec2.scale(integrate_fhMinv, f, dt * minv); + vec2.multiply(integrate_fhMinv, this.massMultiplier, integrate_fhMinv); + vec2.add(velo, integrate_fhMinv, velo); + + // CCD + if(!this.integrateToTimeOfImpact(dt)){ + + // Regular position update + vec2.scale(integrate_velodt, velo, dt); + vec2.add(pos, pos, integrate_velodt); + if(!this.fixedRotation){ + this.angle += this.angularVelocity * dt; + } + } + + this.aabbNeedsUpdate = true; +}; + +var result = new RaycastResult(); +var ray = new Ray({ + mode: Ray.ALL +}); +var direction = vec2.create(); +var end = vec2.create(); +var startToEnd = vec2.create(); +var rememberPosition = vec2.create(); +Body.prototype.integrateToTimeOfImpact = function(dt){ + + if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){ + return false; + } + + vec2.normalize(direction, this.velocity); + + vec2.scale(end, this.velocity, dt); + vec2.add(end, end, this.position); + + vec2.sub(startToEnd, end, this.position); + var startToEndAngle = this.angularVelocity * dt; + var len = vec2.length(startToEnd); + + var timeOfImpact = 1; + + var hit; + var that = this; + result.reset(); + ray.callback = function (result) { + if(result.body === that){ + return; + } + hit = result.body; + result.getHitPoint(end, ray); + vec2.sub(startToEnd, end, that.position); + timeOfImpact = vec2.length(startToEnd) / len; + result.stop(); + }; + vec2.copy(ray.from, this.position); + vec2.copy(ray.to, end); + ray.update(); + this.world.raycast(result, ray); + + if(!hit){ + return false; + } + + var rememberAngle = this.angle; + vec2.copy(rememberPosition, this.position); + + // Got a start and end point. Approximate time of impact using binary search + var iter = 0; + var tmin = 0; + var tmid = 0; + var tmax = timeOfImpact; + while (tmax >= tmin && iter < this.ccdIterations) { + iter++; + + // calculate the midpoint + tmid = (tmax - tmin) / 2; + + // Move the body to that point + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, rememberPosition, integrate_velodt); + this.angle = rememberAngle + startToEndAngle * timeOfImpact; + this.updateAABB(); + + // check overlap + var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit); + + if (overlaps) { + // change min to search upper interval + tmin = tmid; + } else { + // change max to search lower interval + tmax = tmid; + } + } + + timeOfImpact = tmid; + + vec2.copy(this.position, rememberPosition); + this.angle = rememberAngle; + + // move to TOI + vec2.scale(integrate_velodt, startToEnd, timeOfImpact); + vec2.add(this.position, this.position, integrate_velodt); + if(!this.fixedRotation){ + this.angle += startToEndAngle * timeOfImpact; + } + + return true; +}; + +/** + * Get velocity of a point in the body. + * @method getVelocityAtPoint + * @param {Array} result A vector to store the result in + * @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from + * @return {Array} The result vector + */ +Body.prototype.getVelocityAtPoint = function(result, relativePoint){ + vec2.crossVZ(result, relativePoint, this.angularVelocity); + vec2.subtract(result, this.velocity, result); + return result; +}; + +/** + * @event sleepy + */ +Body.sleepyEvent = { + type: "sleepy" +}; + +/** + * @event sleep + */ +Body.sleepEvent = { + type: "sleep" +}; + +/** + * @event wakeup + */ +Body.wakeUpEvent = { + type: "wakeup" +}; + +/** + * Dynamic body. + * @property DYNAMIC + * @type {Number} + * @static + */ +Body.DYNAMIC = 1; + +/** + * Static body. + * @property STATIC + * @type {Number} + * @static + */ +Body.STATIC = 2; + +/** + * Kinematic body. + * @property KINEMATIC + * @type {Number} + * @static + */ +Body.KINEMATIC = 4; + +/** + * @property AWAKE + * @type {Number} + * @static + */ +Body.AWAKE = 0; + +/** + * @property SLEEPY + * @type {Number} + * @static + */ +Body.SLEEPY = 1; + +/** + * @property SLEEPING + * @type {Number} + * @static + */ +Body.SLEEPING = 2; + + +},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = LinearSpring; + +/** + * A spring, connecting two bodies. + * + * The Spring explicitly adds force and angularForce to the bodies. + * + * @class LinearSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + */ +function LinearSpring(bodyA,bodyB,options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Anchor for bodyA in local bodyA coordinates. + * @property localAnchorA + * @type {Array} + */ + this.localAnchorA = vec2.fromValues(0,0); + + /** + * Anchor for bodyB in local bodyB coordinates. + * @property localAnchorB + * @type {Array} + */ + this.localAnchorB = vec2.fromValues(0,0); + + if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); } + if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); } + if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } + if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } + + var worldAnchorA = vec2.create(); + var worldAnchorB = vec2.create(); + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + var worldDistance = vec2.distance(worldAnchorA, worldAnchorB); + + /** + * Rest length of the spring. + * @property restLength + * @type {number} + */ + this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance; +} +LinearSpring.prototype = new Spring(); +LinearSpring.prototype.constructor = LinearSpring; + +/** + * Set the anchor point on body A, using world coordinates. + * @method setWorldAnchorA + * @param {Array} worldAnchorA + */ +LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){ + this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); +}; + +/** + * Set the anchor point on body B, using world coordinates. + * @method setWorldAnchorB + * @param {Array} worldAnchorB + */ +LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){ + this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); +}; + +/** + * Get the anchor point on body A, in world coordinates. + * @method getWorldAnchorA + * @param {Array} result The vector to store the result in. + */ +LinearSpring.prototype.getWorldAnchorA = function(result){ + this.bodyA.toWorldFrame(result, this.localAnchorA); +}; + +/** + * Get the anchor point on body B, in world coordinates. + * @method getWorldAnchorB + * @param {Array} result The vector to store the result in. + */ +LinearSpring.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(); + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +LinearSpring.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; + + // Get world anchors + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + + // Get offset points + vec2.sub(ri, worldAnchorA, bodyA.position); + vec2.sub(rj, worldAnchorB, bodyB.position); + + // Compute distance vector between world anchor points + vec2.sub(r, worldAnchorB, worldAnchorA); + var rlen = vec2.len(r); + vec2.normalize(r_unit,r); + + //console.log(rlen) + //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) + + // Compute relative velocity of the anchor points, u + 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); + + // F = - k * ( x - L ) - D * ( u ) + vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); + + // Add forces to bodies + vec2.sub( bodyA.force, bodyA.force, f); + vec2.add( bodyB.force, bodyB.force, f); + + // Angular force + 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":57,"./Spring":34}],33:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Spring = _dereq_('./Spring'); + +module.exports = RotationalSpring; + +/** + * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies. + * + * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap. + * + * @class RotationalSpring + * @extends Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. + */ +function RotationalSpring(bodyA, bodyB, options){ + options = options || {}; + + Spring.call(this, bodyA, bodyB, options); + + /** + * Rest angle of the spring. + * @property restAngle + * @type {number} + */ + this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle; +} +RotationalSpring.prototype = new Spring(); +RotationalSpring.prototype.constructor = RotationalSpring; + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +RotationalSpring.prototype.applyForce = function(){ + var k = this.stiffness, + d = this.damping, + l = this.restAngle, + bodyA = this.bodyA, + bodyB = this.bodyB, + x = bodyB.angle - bodyA.angle, + u = bodyB.angularVelocity - bodyA.angularVelocity; + + var torque = - k * (x - l) - d * u * 0; + + bodyA.angularForce -= torque; + bodyB.angularForce += torque; +}; + +},{"../math/vec2":30,"./Spring":34}],34:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = Spring; + +/** + * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver. + * + * @class Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. + * @param {number} [options.damping=1] A number >= 0. Default: 1 + * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. + * @param {Array} [options.localAnchorB] + * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. + * @param {Array} [options.worldAnchorB] + */ +function Spring(bodyA, bodyB, options){ + options = Utils.defaults(options,{ + stiffness: 100, + damping: 1, + }); + + /** + * Stiffness of the spring. + * @property stiffness + * @type {number} + */ + this.stiffness = options.stiffness; + + /** + * Damping of the spring. + * @property damping + * @type {number} + */ + this.damping = options.damping; + + /** + * First connected body. + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second connected body. + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; +} + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +Spring.prototype.applyForce = function(){ + // To be implemented by subclasses +}; + +},{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2'); +var Utils = _dereq_('../utils/Utils'); +var Constraint = _dereq_('../constraints/Constraint'); +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Body = _dereq_('../objects/Body'); + +module.exports = TopDownVehicle; + +/** + * @class TopDownVehicle + * @constructor + * @param {Body} chassisBody A dynamic body, already added to the world. + * @param {Object} [options] + * + * @example + * + * // Create a dynamic body for the chassis + * var chassisBody = new Body({ + * mass: 1 + * }); + * var boxShape = new Box({ width: 0.5, height: 1 }); + * chassisBody.addShape(boxShape); + * world.addBody(chassisBody); + * + * // Create the vehicle + * var vehicle = new TopDownVehicle(chassisBody); + * + * // Add one front wheel and one back wheel - we don't actually need four :) + * var frontWheel = vehicle.addWheel({ + * localPosition: [0, 0.5] // front + * }); + * frontWheel.setSideFriction(4); + * + * // Back wheel + * var backWheel = vehicle.addWheel({ + * localPosition: [0, -0.5] // back + * }); + * backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift + * vehicle.addToWorld(world); + * + * // Steer value zero means straight forward. Positive is left and negative right. + * frontWheel.steerValue = Math.PI / 16; + * + * // Engine force forward + * backWheel.engineForce = 10; + * backWheel.setBrakeForce(0); + */ +function TopDownVehicle(chassisBody, options){ + options = options || {}; + + /** + * @property {Body} chassisBody + */ + this.chassisBody = chassisBody; + + /** + * @property {Array} wheels + */ + this.wheels = []; + + // A dummy body to constrain the chassis to + this.groundBody = new Body({ mass: 0 }); + + this.world = null; + + var that = this; + this.preStepCallback = function(){ + that.update(); + }; +} + +/** + * @method addToWorld + * @param {World} world + */ +TopDownVehicle.prototype.addToWorld = function(world){ + this.world = world; + world.addBody(this.groundBody); + world.on('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.addConstraint(wheel); + } +}; + +/** + * @method removeFromWorld + * @param {World} world + */ +TopDownVehicle.prototype.removeFromWorld = function(){ + var world = this.world; + world.removeBody(this.groundBody); + world.off('preStep', this.preStepCallback); + for (var i = 0; i < this.wheels.length; i++) { + var wheel = this.wheels[i]; + world.removeConstraint(wheel); + } + this.world = null; +}; + +/** + * @method addWheel + * @param {object} [wheelOptions] + * @return {WheelConstraint} + */ +TopDownVehicle.prototype.addWheel = function(wheelOptions){ + var wheel = new WheelConstraint(this,wheelOptions); + this.wheels.push(wheel); + return wheel; +}; + +/** + * @method update + */ +TopDownVehicle.prototype.update = function(){ + for (var i = 0; i < this.wheels.length; i++) { + this.wheels[i].update(); + } +}; + +/** + * @class WheelConstraint + * @constructor + * @extends {Constraint} + * @param {Vehicle} vehicle + * @param {object} [options] + * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero. + * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body. + * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction. + */ +function WheelConstraint(vehicle, options){ + options = options || {}; + + this.vehicle = vehicle; + + this.forwardEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + this.sideEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody); + + /** + * @property {number} steerValue + */ + this.steerValue = 0; + + /** + * @property {number} engineForce + */ + this.engineForce = 0; + + this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5); + + /** + * @property {Array} localForwardVector + */ + this.localForwardVector = vec2.fromValues(0, 1); + if(options.localForwardVector){ + vec2.copy(this.localForwardVector, options.localForwardVector); + } + + /** + * @property {Array} localPosition + */ + this.localPosition = vec2.fromValues(0, 0); + if(options.localPosition){ + vec2.copy(this.localPosition, options.localPosition); + } + + Constraint.apply(this, vehicle.chassisBody, vehicle.groundBody); + + this.equations.push( + this.forwardEquation, + this.sideEquation + ); + + this.setBrakeForce(0); +} +WheelConstraint.prototype = new Constraint(); + +/** + * @method setForwardFriction + */ +WheelConstraint.prototype.setBrakeForce = function(force){ + this.forwardEquation.setSlipForce(force); +}; + +/** + * @method setSideFriction + */ +WheelConstraint.prototype.setSideFriction = function(force){ + this.sideEquation.setSlipForce(force); +}; + +var worldVelocity = vec2.create(); +var relativePoint = vec2.create(); + +/** + * @method getSpeed + */ +WheelConstraint.prototype.getSpeed = function(){ + this.vehicle.chassisBody.vectorToWorldFrame(relativePoint, this.localForwardVector); + this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity, relativePoint); + return vec2.dot(worldVelocity, relativePoint); +}; + +var tmpVec = vec2.create(); + +/** + * @method update + */ +WheelConstraint.prototype.update = function(){ + + // Directional + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t, this.localForwardVector); + vec2.rotate(this.sideEquation.t, this.localForwardVector, Math.PI / 2); + this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t, this.sideEquation.t); + + vec2.rotate(this.forwardEquation.t, this.forwardEquation.t, this.steerValue); + vec2.rotate(this.sideEquation.t, this.sideEquation.t, this.steerValue); + + // Attachment point + this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB, this.localPosition); + vec2.copy(this.sideEquation.contactPointB, this.forwardEquation.contactPointB); + + this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA, this.localPosition); + vec2.copy(this.sideEquation.contactPointA, this.forwardEquation.contactPointA); + + // Add engine force + vec2.normalize(tmpVec, this.forwardEquation.t); + vec2.scale(tmpVec, tmpVec, this.engineForce); + + this.vehicle.chassisBody.applyForce(tmpVec, this.forwardEquation.contactPointA); +}; +},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(_dereq_,module,exports){ +// Export p2 classes +var p2 = module.exports = { + AABB : _dereq_('./collision/AABB'), + AngleLockEquation : _dereq_('./equations/AngleLockEquation'), + Body : _dereq_('./objects/Body'), + Broadphase : _dereq_('./collision/Broadphase'), + Capsule : _dereq_('./shapes/Capsule'), + Circle : _dereq_('./shapes/Circle'), + Constraint : _dereq_('./constraints/Constraint'), + ContactEquation : _dereq_('./equations/ContactEquation'), + ContactEquationPool : _dereq_('./utils/ContactEquationPool'), + ContactMaterial : _dereq_('./material/ContactMaterial'), + Convex : _dereq_('./shapes/Convex'), + DistanceConstraint : _dereq_('./constraints/DistanceConstraint'), + Equation : _dereq_('./equations/Equation'), + EventEmitter : _dereq_('./events/EventEmitter'), + FrictionEquation : _dereq_('./equations/FrictionEquation'), + FrictionEquationPool : _dereq_('./utils/FrictionEquationPool'), + GearConstraint : _dereq_('./constraints/GearConstraint'), + GSSolver : _dereq_('./solver/GSSolver'), + Heightfield : _dereq_('./shapes/Heightfield'), + Line : _dereq_('./shapes/Line'), + LockConstraint : _dereq_('./constraints/LockConstraint'), + Material : _dereq_('./material/Material'), + Narrowphase : _dereq_('./collision/Narrowphase'), + NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'), + Particle : _dereq_('./shapes/Particle'), + Plane : _dereq_('./shapes/Plane'), + Pool : _dereq_('./utils/Pool'), + RevoluteConstraint : _dereq_('./constraints/RevoluteConstraint'), + PrismaticConstraint : _dereq_('./constraints/PrismaticConstraint'), + Ray : _dereq_('./collision/Ray'), + RaycastResult : _dereq_('./collision/RaycastResult'), + Box : _dereq_('./shapes/Box'), + RotationalVelocityEquation : _dereq_('./equations/RotationalVelocityEquation'), + SAPBroadphase : _dereq_('./collision/SAPBroadphase'), + Shape : _dereq_('./shapes/Shape'), + Solver : _dereq_('./solver/Solver'), + Spring : _dereq_('./objects/Spring'), + TopDownVehicle : _dereq_('./objects/TopDownVehicle'), + LinearSpring : _dereq_('./objects/LinearSpring'), + RotationalSpring : _dereq_('./objects/RotationalSpring'), + Utils : _dereq_('./utils/Utils'), + World : _dereq_('./world/World'), + vec2 : _dereq_('./math/vec2'), + version : _dereq_('../package.json').version, +}; + +Object.defineProperty(p2, 'Rectangle', { + get: function() { + console.warn('The Rectangle class has been renamed to Box.'); + return this.Box; + } +}); +},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":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/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Shape = _dereq_('./Shape') +, Convex = _dereq_('./Convex'); + +module.exports = Box; + +/** + * Box shape class. + * @class Box + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.width=1] Total width of the box + * @param {Number} [options.height=1] Total height of the box + * @extends Convex + */ +function Box(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + width: arguments[0], + height: arguments[1] + }; + console.warn('The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })'); + } + options = options || {}; + + /** + * Total width of the box + * @property width + * @type {Number} + */ + var width = this.width = options.width || 1; + + /** + * Total height of the box + * @property height + * @type {Number} + */ + var height = this.height = options.height || 1; + + var verts = [ + vec2.fromValues(-width/2, -height/2), + vec2.fromValues( width/2, -height/2), + vec2.fromValues( width/2, height/2), + vec2.fromValues(-width/2, height/2) + ]; + var axes = [ + vec2.fromValues(1, 0), + vec2.fromValues(0, 1) + ]; + + options.vertices = verts; + options.axes = axes; + options.type = Shape.BOX; + Convex.call(this, options); +} +Box.prototype = new Convex(); +Box.prototype.constructor = Box; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Box.prototype.computeMomentOfInertia = function(mass){ + var w = this.width, + h = this.height; + return mass * (h*h + w*w) / 12; +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Box.prototype.updateBoundingRadius = function(){ + var w = this.width, + h = this.height; + this.boundingRadius = Math.sqrt(w*w + h*h) / 2; +}; + +var corner1 = vec2.create(), + corner2 = vec2.create(), + corner3 = vec2.create(), + corner4 = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Box.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices,position,angle,0); +}; + +Box.prototype.updateArea = function(){ + this.area = this.width * this.height; +}; + + +},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Capsule; + +/** + * Capsule shape class. + * @class Capsule + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The distance between the end points + * @param {Number} [options.radius=1] Radius of the capsule + * @example + * var capsuleShape = new Capsule({ + * length: 1, + * radius: 2 + * }); + * body.addShape(capsuleShape); + */ +function Capsule(options){ + if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){ + options = { + length: arguments[0], + radius: arguments[1] + }; + console.warn('The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })'); + } + options = options || {}; + + /** + * The distance between the end points. + * @property {Number} length + */ + this.length = options.length || 1; + + /** + * The radius of the capsule. + * @property {Number} radius + */ + this.radius = options.radius || 1; + + options.type = Shape.CAPSULE; + Shape.call(this, options); +} +Capsule.prototype = new Shape(); +Capsule.prototype.constructor = Capsule; + +/** + * Compute the mass moment of inertia of the Capsule. + * @method conputeMomentOfInertia + * @param {Number} mass + * @return {Number} + * @todo + */ +Capsule.prototype.computeMomentOfInertia = function(mass){ + // Approximate with rectangle + var r = this.radius, + w = this.length + r, // 2*r is too much, 0 is too little + h = r*2; + return mass * (h*h + w*w) / 12; +}; + +/** + * @method updateBoundingRadius + */ +Capsule.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius + this.length/2; +}; + +/** + * @method updateArea + */ +Capsule.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; +}; + +var r = vec2.create(); + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Capsule.prototype.computeAABB = function(out, position, angle){ + var radius = this.radius; + + // Compute center position of one of the the circles, world oriented, but with local offset + vec2.set(r,this.length / 2,0); + if(angle !== 0){ + vec2.rotate(r,r,angle); + } + + // Get bounds + 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)); + + // Add offset + vec2.add(out.lowerBound, out.lowerBound, position); + vec2.add(out.upperBound, out.upperBound, position); +}; + +var intersectCapsule_hitPointWorld = vec2.create(); +var intersectCapsule_normal = vec2.create(); +var intersectCapsule_l0 = vec2.create(); +var intersectCapsule_l1 = vec2.create(); +var intersectCapsule_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Capsule.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectCapsule_hitPointWorld; + var normal = intersectCapsule_normal; + var l0 = intersectCapsule_l0; + var l1 = intersectCapsule_l1; + + // The sides + var halfLen = this.length / 2; + for(var i=0; i<2; i++){ + + // get start and end of the line + var y = this.radius * (i*2-1); + vec2.set(l0, -halfLen, y); + vec2.set(l1, halfLen, y); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var delta = vec2.getLineSegmentsIntersectionFraction(from, to, l0, l1); + if(delta >= 0){ + vec2.rotate(normal, intersectCapsule_unit_y, angle); + vec2.scale(normal, normal, (i*2-1)); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + // Circles + var diagonalLengthSquared = Math.pow(this.radius, 2) + Math.pow(halfLen, 2); + for(var i=0; i<2; i++){ + vec2.set(l0, halfLen * (i*2-1), 0); + vec2.toGlobalFrame(l0, l0, position, angle); + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - l0[0]) + (to[1] - from[1]) * (from[1] - l0[1])); + var c = Math.pow(from[0] - l0[0], 2) + Math.pow(from[1] - l0[1], 2) - Math.pow(this.radius, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + if(delta < 0){ + // No intersection + continue; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(hitPointWorld, from, to, delta); + + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, delta, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(hitPointWorld, from, to, d1); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d1, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(hitPointWorld, from, to, d2); + if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){ + vec2.sub(normal, hitPointWorld, l0); + vec2.normalize(normal,normal); + ray.reportIntersection(result, d2, normal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } + } + } +}; +},{"../math/vec2":30,"./Shape":45}],39:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Circle; + +/** + * Circle shape class. + * @class Circle + * @extends Shape + * @constructor + * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {number} [options.radius=1] The radius of this circle + * + * @example + * var circleShape = new Circle({ radius: 1 }); + * body.addShape(circleShape); + */ +function Circle(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + radius: arguments[0] + }; + console.warn('The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })'); + } + options = options || {}; + + /** + * The radius of the circle. + * @property radius + * @type {number} + */ + this.radius = options.radius || 1; + + options.type = Shape.CIRCLE; + Shape.call(this, options); +} +Circle.prototype = new Shape(); +Circle.prototype.constructor = Circle; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Circle.prototype.computeMomentOfInertia = function(mass){ + var r = this.radius; + return mass * r * r / 2; +}; + +/** + * @method updateBoundingRadius + * @return {Number} + */ +Circle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.radius; +}; + +/** + * @method updateArea + * @return {Number} + */ +Circle.prototype.updateArea = function(){ + this.area = Math.PI * this.radius * this.radius; +}; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +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); + } +}; + +var Ray_intersectSphere_intersectionPoint = vec2.create(); +var Ray_intersectSphere_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Circle.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from, + to = ray.to, + r = this.radius; + + var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2); + var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1])); + var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2); + var delta = Math.pow(b, 2) - 4 * a * c; + + var intersectionPoint = Ray_intersectSphere_intersectionPoint; + var normal = Ray_intersectSphere_normal; + + if(delta < 0){ + // No intersection + return; + + } else if(delta === 0){ + // single intersection point + vec2.lerp(intersectionPoint, from, to, delta); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, delta, normal, -1); + + } else { + var sqrtDelta = Math.sqrt(delta); + var inv2a = 1 / (2 * a); + var d1 = (- b - sqrtDelta) * inv2a; + var d2 = (- b + sqrtDelta) * inv2a; + + if(d1 >= 0 && d1 <= 1){ + vec2.lerp(intersectionPoint, from, to, d1); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d1, normal, -1); + + if(result.shouldStop(ray)){ + return; + } + } + + if(d2 >= 0 && d2 <= 1){ + vec2.lerp(intersectionPoint, from, to, d2); + + vec2.sub(normal, intersectionPoint, position); + vec2.normalize(normal,normal); + + ray.reportIntersection(result, d2, normal, -1); + } + } +}; +},{"../math/vec2":30,"./Shape":45}],40:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, polyk = _dereq_('../math/polyk') +, decomp = _dereq_('poly-decomp'); + +module.exports = Convex; + +/** + * Convex shape class. + * @class Convex + * @constructor + * @extends Shape + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. + * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex. + * @example + * // Create a box + * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]]; + * var convexShape = new Convex({ vertices: vertices }); + * body.addShape(convexShape); + */ +function Convex(options){ + if(Array.isArray(arguments[0])){ + options = { + vertices: arguments[0], + axes: arguments[1] + }; + console.warn('The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })'); + } + options = options || {}; + + /** + * Vertices defined in the local frame. + * @property vertices + * @type {Array} + */ + this.vertices = []; + + // Copy the verts + var vertices = options.vertices !== undefined ? options.vertices : []; + for(var i=0; i < vertices.length; i++){ + var v = vec2.create(); + vec2.copy(v, vertices[i]); + this.vertices.push(v); + } + + /** + * Axes defined in the local frame. + * @property axes + * @type {Array} + */ + this.axes = []; + + if(options.axes){ + + // Copy the axes + for(var i=0; i < options.axes.length; i++){ + var axis = vec2.create(); + vec2.copy(axis, options.axes[i]); + this.axes.push(axis); + } + + } else { + + // Construct axes from the vertex data + for(var i = 0; i < this.vertices.length; i++){ + // Get the world edge + var worldPoint0 = this.vertices[i]; + var worldPoint1 = this.vertices[(i+1) % this.vertices.length]; + + var normal = vec2.create(); + vec2.sub(normal, worldPoint1, worldPoint0); + + // Get normal - just rotate 90 degrees since vertices are given in CCW + vec2.rotate90cw(normal, normal); + vec2.normalize(normal, normal); + + this.axes.push(normal); + } + + } + + /** + * The center of mass of the Convex + * @property centerOfMass + * @type {Array} + */ + this.centerOfMass = vec2.fromValues(0,0); + + /** + * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. + * @property triangles + * @type {Array} + */ + this.triangles = []; + + if(this.vertices.length){ + this.updateTriangles(); + this.updateCenterOfMass(); + } + + /** + * The bounding radius of the convex + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + options.type = Shape.CONVEX; + Shape.call(this, options); + + this.updateBoundingRadius(); + this.updateArea(); + if(this.area < 0){ + throw new Error("Convex vertices must be given in conter-clockwise winding."); + } +} +Convex.prototype = new Shape(); +Convex.prototype.constructor = Convex; + +var tmpVec1 = vec2.create(); +var tmpVec2 = vec2.create(); + +/** + * Project a Convex onto a world-oriented axis + * @method projectOntoAxis + * @static + * @param {Array} offset + * @param {Array} localAxis + * @param {Array} result + */ +Convex.prototype.projectOntoLocalAxis = function(localAxis, result){ + var max=null, + min=null, + v, + value, + localAxis = tmpVec1; + + // Get projected position of all vertices + for(var i=0; i max){ + max = value; + } + if(min === null || value < min){ + min = value; + } + } + + if(min > max){ + var t = min; + min = max; + max = t; + } + + vec2.set(result, min, max); +}; + +Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){ + var worldAxis = tmpVec2; + + this.projectOntoLocalAxis(localAxis, result); + + // Project the position of the body onto the axis - need to add this to the result + if(shapeAngle !== 0){ + vec2.rotate(worldAxis, localAxis, shapeAngle); + } else { + worldAxis = localAxis; + } + var offset = vec2.dot(shapeOffset, worldAxis); + + vec2.set(result, result[0] + offset, result[1] + offset); +}; + + +/** + * Update the .triangles property + * @method updateTriangles + */ +Convex.prototype.updateTriangles = function(){ + + this.triangles.length = 0; + + // Rewrite on polyk notation, array of numbers + var polykVerts = []; + for(var i=0; i r2){ + r2 = l2; + } + } + + this.boundingRadius = Math.sqrt(r2); +}; + +/** + * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. + * @static + * @method triangleArea + * @param {Array} a + * @param {Array} b + * @param {Array} c + * @return {Number} + */ +Convex.triangleArea = function(a,b,c){ + return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; +}; + +/** + * Update the .area + * @method updateArea + */ +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]]; + + // Get mass for the triangle (density=1 in this case) + var m = Convex.triangleArea(a,b,c); + this.area += m; + } +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Convex.prototype.computeAABB = function(out, position, angle){ + out.setFromPoints(this.vertices, position, angle, 0); +}; + +var intersectConvex_rayStart = vec2.create(); +var intersectConvex_rayEnd = vec2.create(); +var intersectConvex_normal = vec2.create(); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Convex.prototype.raycast = function(result, ray, position, angle){ + var rayStart = intersectConvex_rayStart; + var rayEnd = intersectConvex_rayEnd; + var normal = intersectConvex_normal; + var vertices = this.vertices; + + // Transform to local shape space + vec2.toLocalFrame(rayStart, ray.from, position, angle); + vec2.toLocalFrame(rayEnd, ray.to, position, angle); + + var n = vertices.length; + + for (var i = 0; i < n && !result.shouldStop(ray); i++) { + var q1 = vertices[i]; + var q2 = vertices[(i+1) % n]; + var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2); + + if(delta >= 0){ + vec2.sub(normal, q2, q1); + vec2.rotate(normal, normal, -Math.PI / 2 + angle); + vec2.normalize(normal, normal); + ray.reportIntersection(result, delta, normal, i); + } + } +}; + +},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Heightfield; + +/** + * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". + * @class Heightfield + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {array} [options.heights] An array of Y values that will be used to construct the terrain. + * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given. + * @param {Number} [options.maxValue] Maximum value. + * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction. + * + * @example + * // Generate some height data (y-values). + * var heights = []; + * for(var i = 0; i < 1000; i++){ + * var y = 0.5 * Math.cos(0.2 * i); + * heights.push(y); + * } + * + * // Create the heightfield shape + * var heightfieldShape = new Heightfield({ + * heights: heights, + * elementWidth: 1 // Distance between the data points in X direction + * }); + * var heightfieldBody = new Body(); + * heightfieldBody.addShape(heightfieldShape); + * world.addBody(heightfieldBody); + * + * @todo Should use a scale property with X and Y direction instead of just elementWidth + */ +function Heightfield(options){ + if(Array.isArray(arguments[0])){ + options = { + heights: arguments[0] + }; + + if(typeof(arguments[1]) === 'object'){ + for(var key in arguments[1]){ + options[key] = arguments[1][key]; + } + } + + console.warn('The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })'); + } + options = options || {}; + + /** + * An array of numbers, or height values, that are spread out along the x axis. + * @property {array} heights + */ + this.heights = options.heights ? options.heights.slice(0) : []; + + /** + * Max value of the heights + * @property {number} maxValue + */ + this.maxValue = options.maxValue || null; + + /** + * Max value of the heights + * @property {number} minValue + */ + this.minValue = options.minValue || null; + + /** + * The width of each element + * @property {number} elementWidth + */ + this.elementWidth = options.elementWidth || 0.1; + + if(options.maxValue === undefined || options.minValue === undefined){ + this.updateMaxMinValues(); + } + + options.type = Shape.HEIGHTFIELD; + Shape.call(this, options); +} +Heightfield.prototype = new Shape(); +Heightfield.prototype.constructor = Heightfield; + +/** + * Update the .minValue and the .maxValue + * @method updateMaxMinValues + */ +Heightfield.prototype.updateMaxMinValues = function(){ + var data = this.heights; + var maxValue = data[0]; + var minValue = data[0]; + for(var i=0; i !== data.length; i++){ + var v = data[i]; + if(v > maxValue){ + maxValue = v; + } + if(v < minValue){ + minValue = v; + } + } + this.maxValue = maxValue; + this.minValue = minValue; +}; + +/** + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} + */ +Heightfield.prototype.computeMomentOfInertia = function(mass){ + return Number.MAX_VALUE; +}; + +Heightfield.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +Heightfield.prototype.updateArea = function(){ + var data = this.heights, + area = 0; + for(var i=0; i= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected + var intX = p0[0] + (t * s1_x); + var intY = p0[1] + (t * s1_y); + out[0] = intX; + out[1] = intY; + return t; + } + return -1; // No collision +} + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Heightfield.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + + var hitPointWorld = intersectHeightfield_hitPointWorld; + var worldNormal = intersectHeightfield_worldNormal; + var l0 = intersectHeightfield_l0; + var l1 = intersectHeightfield_l1; + var localFrom = intersectHeightfield_localFrom; + var localTo = intersectHeightfield_localTo; + + // get local ray start and end + vec2.toLocalFrame(localFrom, from, position, angle); + vec2.toLocalFrame(localTo, to, position, angle); + + // Get the segment range + var i0 = this.getClampedSegmentIndex(localFrom); + var i1 = this.getClampedSegmentIndex(localTo); + if(i0 > i1){ + var tmp = i0; + i0 = i1; + i1 = tmp; + } + + // The segments + for(var i=0; i= 0){ + vec2.sub(worldNormal, l1, l0); + vec2.rotate(worldNormal, worldNormal, angle + Math.PI / 2); + vec2.normalize(worldNormal, worldNormal); + ray.reportIntersection(result, t, worldNormal, -1); + if(result.shouldStop(ray)){ + return; + } + } + } +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Line; + +/** + * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * @class Line + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @param {Number} [options.length=1] The total length of the line + * @extends Shape + * @constructor + */ +function Line(options){ + if(typeof(arguments[0]) === 'number'){ + options = { + length: arguments[0] + }; + console.warn('The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })'); + } + options = options || {}; + + /** + * Length of this line + * @property {Number} length + * @default 1 + */ + this.length = options.length || 1; + + options.type = Shape.LINE; + Shape.call(this, options); +} +Line.prototype = new Shape(); +Line.prototype.constructor = Line; + +Line.prototype.computeMomentOfInertia = function(mass){ + return mass * Math.pow(this.length,2) / 12; +}; + +Line.prototype.updateBoundingRadius = function(){ + this.boundingRadius = this.length/2; +}; + +var points = [vec2.create(),vec2.create()]; + +/** + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position + * @param {Number} angle + */ +Line.prototype.computeAABB = function(out, position, angle){ + var l2 = this.length / 2; + vec2.set(points[0], -l2, 0); + vec2.set(points[1], l2, 0); + out.setFromPoints(points,position,angle,0); +}; + +var raycast_hitPoint = vec2.create(); +var raycast_normal = vec2.create(); +var raycast_l0 = vec2.create(); +var raycast_l1 = vec2.create(); +var raycast_unit_y = vec2.fromValues(0,1); + +/** + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @param {number} angle + * @param {array} position + */ +Line.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + + var l0 = raycast_l0; + var l1 = raycast_l1; + + // get start and end of the line + var halfLen = this.length / 2; + vec2.set(l0, -halfLen, 0); + vec2.set(l1, halfLen, 0); + vec2.toGlobalFrame(l0, l0, position, angle); + vec2.toGlobalFrame(l1, l1, position, angle); + + var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to); + if(fraction >= 0){ + var normal = raycast_normal; + vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from + ray.reportIntersection(result, fraction, normal, -1); + } +}; +},{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2'); + +module.exports = Particle; + +/** + * Particle shape class. + * @class Particle + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + * @extends Shape + */ +function Particle(options){ + options = options || {}; + options.type = Shape.PARTICLE; + Shape.call(this, options); +} +Particle.prototype = new Shape(); +Particle.prototype.constructor = Particle; + +Particle.prototype.computeMomentOfInertia = function(mass){ + return 0; // Can't rotate a particle +}; + +Particle.prototype.updateBoundingRadius = function(){ + this.boundingRadius = 0; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Particle.prototype.computeAABB = function(out, position, angle){ + vec2.copy(out.lowerBound, position); + vec2.copy(out.upperBound, position); +}; + +},{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){ +var Shape = _dereq_('./Shape') +, vec2 = _dereq_('../math/vec2') +, Utils = _dereq_('../utils/Utils'); + +module.exports = Plane; + +/** + * Plane shape class. The plane is facing in the Y direction. + * @class Plane + * @extends Shape + * @constructor + * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.) + */ +function Plane(options){ + options = options || {}; + options.type = Shape.PLANE; + Shape.call(this, options); +} +Plane.prototype = new Shape(); +Plane.prototype.constructor = Plane; + +/** + * Compute moment of inertia + * @method computeMomentOfInertia + */ +Plane.prototype.computeMomentOfInertia = function(mass){ + return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here +}; + +/** + * Update the bounding radius + * @method updateBoundingRadius + */ +Plane.prototype.updateBoundingRadius = function(){ + this.boundingRadius = Number.MAX_VALUE; +}; + +/** + * @method computeAABB + * @param {AABB} out + * @param {Array} position + * @param {Number} angle + */ +Plane.prototype.computeAABB = function(out, position, angle){ + var a = angle % (2 * Math.PI); + var set = vec2.set; + var max = 1e7; + var lowerBound = out.lowerBound; + var upperBound = out.upperBound; + + // Set max bounds + set(lowerBound, -max, -max); + set(upperBound, max, max); + + if(a === 0){ + // y goes from -inf to 0 + upperBound[1] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, max, 0); + + } else if(a === Math.PI / 2){ + + // x goes from 0 to inf + lowerBound[0] = 0; + // set(lowerBound, 0, -max); + // set(upperBound, max, max); + + } else if(a === Math.PI){ + + // y goes from 0 to inf + lowerBound[1] = 0; + // set(lowerBound, -max, 0); + // set(upperBound, max, max); + + } else if(a === 3*Math.PI/2){ + + // x goes from -inf to 0 + upperBound[0] = 0; + // set(lowerBound, -max, -max); + // set(upperBound, 0, max); + + } +}; + +Plane.prototype.updateArea = function(){ + this.area = Number.MAX_VALUE; +}; + +var intersectPlane_planePointToFrom = vec2.create(); +var intersectPlane_dir_scaled_with_t = vec2.create(); +var intersectPlane_hitPoint = vec2.create(); +var intersectPlane_normal = vec2.create(); +var intersectPlane_len = vec2.create(); + +/** + * @method raycast + * @param {RayResult} result + * @param {Ray} ray + * @param {array} position + * @param {number} angle + */ +Plane.prototype.raycast = function(result, ray, position, angle){ + var from = ray.from; + var to = ray.to; + var direction = ray.direction; + var planePointToFrom = intersectPlane_planePointToFrom; + var dir_scaled_with_t = intersectPlane_dir_scaled_with_t; + var hitPoint = intersectPlane_hitPoint; + var normal = intersectPlane_normal; + var len = intersectPlane_len; + + // Get plane normal + vec2.set(normal, 0, 1); + vec2.rotate(normal, normal, angle); + + vec2.sub(len, from, position); + var planeToFrom = vec2.dot(len, normal); + vec2.sub(len, to, position); + var planeToTo = vec2.dot(len, normal); + + if(planeToFrom * planeToTo > 0){ + // "from" and "to" are on the same side of the plane... bail out + return; + } + + if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){ + return; + } + + var n_dot_dir = vec2.dot(normal, direction); + + vec2.sub(planePointToFrom, from, position); + var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length; + + ray.reportIntersection(result, t, normal, -1); +}; +},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(_dereq_,module,exports){ +module.exports = Shape; + +var vec2 = _dereq_('../math/vec2'); + +/** + * Base class for shapes. + * @class Shape + * @constructor + * @param {object} [options] + * @param {array} [options.position] + * @param {number} [options.angle=0] + * @param {number} [options.collisionGroup=1] + * @param {number} [options.collisionMask=1] + * @param {boolean} [options.sensor=false] + * @param {boolean} [options.collisionResponse=true] + * @param {object} [options.type=0] + */ +function Shape(options){ + options = options || {}; + + /** + * The body this shape is attached to. A shape can only be attached to a single body. + * @property {Body} body + */ + this.body = null; + + /** + * Body-local position of the shape. + * @property {Array} position + */ + this.position = vec2.fromValues(0,0); + if(options.position){ + vec2.copy(this.position, options.position); + } + + /** + * Body-local angle of the shape. + * @property {number} angle + */ + this.angle = options.angle || 0; + + /** + * The type of the shape. One of: + * + * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} + * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} + * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} + * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} + * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} + * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}} + * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} + * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} + * + * @property {number} type + */ + this.type = options.type || 0; + + /** + * Shape object identifier. + * @type {Number} + * @property id + */ + this.id = Shape.idCounter++; + + /** + * Bounding circle radius of this shape + * @property boundingRadius + * @type {Number} + */ + this.boundingRadius = 0; + + /** + * Collision group that this shape belongs to (bit mask). See this tutorial. + * @property collisionGroup + * @type {Number} + * @example + * // Setup bits for each available group + * var PLAYER = Math.pow(2,0), + * ENEMY = Math.pow(2,1), + * GROUND = Math.pow(2,2) + * + * // Put shapes into their groups + * player1Shape.collisionGroup = PLAYER; + * player2Shape.collisionGroup = PLAYER; + * enemyShape .collisionGroup = ENEMY; + * groundShape .collisionGroup = GROUND; + * + * // Assign groups that each shape collide with. + * // Note that the players can collide with ground and enemies, but not with other players. + * player1Shape.collisionMask = ENEMY | GROUND; + * player2Shape.collisionMask = ENEMY | GROUND; + * enemyShape .collisionMask = PLAYER | GROUND; + * groundShape .collisionMask = PLAYER | ENEMY; + * + * @example + * // How collision check is done + * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ + * // The shapes will collide + * } + */ + this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1; + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc. + * @property {Boolean} collisionResponse + */ + this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true; + + /** + * Collision mask of this shape. See .collisionGroup. + * @property collisionMask + * @type {Number} + */ + this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1; + + /** + * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. + * @property material + * @type {Material} + */ + this.material = options.material || null; + + /** + * Area of this shape. + * @property area + * @type {Number} + */ + this.area = 0; + + /** + * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. + * @property {Boolean} sensor + */ + this.sensor = options.sensor !== undefined ? options.sensor : false; + + if(this.type){ + this.updateBoundingRadius(); + } + + this.updateArea(); +} + +Shape.idCounter = 0; + +/** + * @static + * @property {Number} CIRCLE + */ +Shape.CIRCLE = 1; + +/** + * @static + * @property {Number} PARTICLE + */ +Shape.PARTICLE = 2; + +/** + * @static + * @property {Number} PLANE + */ +Shape.PLANE = 4; + +/** + * @static + * @property {Number} CONVEX + */ +Shape.CONVEX = 8; + +/** + * @static + * @property {Number} LINE + */ +Shape.LINE = 16; + +/** + * @static + * @property {Number} BOX + */ +Shape.BOX = 32; + +/** + * @static + * @property {Number} CAPSULE + */ +Shape.CAPSULE = 64; + +/** + * @static + * @property {Number} HEIGHTFIELD + */ +Shape.HEIGHTFIELD = 128; + +/** + * Should return the moment of inertia around the Z axis of the body given the total mass. See Wikipedia's list of moments of inertia. + * @method computeMomentOfInertia + * @param {Number} mass + * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. + */ +Shape.prototype.computeMomentOfInertia = function(mass){}; + +/** + * Returns the bounding circle radius of this shape. + * @method updateBoundingRadius + * @return {Number} + */ +Shape.prototype.updateBoundingRadius = function(){}; + +/** + * Update the .area property of the shape. + * @method updateArea + */ +Shape.prototype.updateArea = function(){ + // To be implemented in all subclasses +}; + +/** + * Compute the world axis-aligned bounding box (AABB) of this shape. + * @method computeAABB + * @param {AABB} out The resulting AABB. + * @param {Array} position World position of the shape. + * @param {Number} angle World angle of the shape. + */ +Shape.prototype.computeAABB = function(out, position, angle){ + // To be implemented in each subclass +}; + +/** + * Perform raycasting on this shape. + * @method raycast + * @param {RayResult} result Where to store the resulting data. + * @param {Ray} ray The Ray that you want to use for raycasting. + * @param {array} position World position of the shape (the .position property will be ignored). + * @param {number} angle World angle of the shape (the .angle property will be ignored). + */ +Shape.prototype.raycast = function(result, ray, position, angle){ + // To be implemented in each subclass +}; +},{"../math/vec2":30}],46:[function(_dereq_,module,exports){ +var vec2 = _dereq_('../math/vec2') +, Solver = _dereq_('./Solver') +, Utils = _dereq_('../utils/Utils') +, FrictionEquation = _dereq_('../equations/FrictionEquation'); + +module.exports = GSSolver; + +/** + * Iterative Gauss-Seidel constraint equation solver. + * + * @class GSSolver + * @constructor + * @extends Solver + * @param {Object} [options] + * @param {Number} [options.iterations=10] + * @param {Number} [options.tolerance=0] + */ +function GSSolver(options){ + Solver.call(this,options,Solver.GS); + options = options || {}; + + /** + * The max number of iterations to do when solving. More gives better results, but is more expensive. + * @property iterations + * @type {Number} + */ + this.iterations = options.iterations || 10; + + /** + * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. + * @property tolerance + * @type {Number} + * @default 1e-7 + */ + this.tolerance = options.tolerance || 1e-7; + + this.arrayStep = 30; + this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); + + /** + * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. + * @property useZeroRHS + * @type {Boolean} + * @todo Remove, not used + */ + this.useZeroRHS = false; + + /** + * Number of solver iterations that are used to approximate normal forces used for friction (F_friction = mu * F_normal). These friction forces will override any other friction forces that are set. If you set frictionIterations = 0, then this feature will be disabled. + * + * Use only frictionIterations > 0 if the approximated normal force (F_normal = mass * gravity) is not good enough. Examples of where it can happen is in space games where gravity is zero, or in tall stacks where the normal force is large at bottom but small at top. + * + * @property frictionIterations + * @type {Number} + * @default 0 + */ + this.frictionIterations = options.frictionIterations !== undefined ? 0 : options.frictionIterations; + + /** + * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. + * @property {Number} usedIterations + */ + this.usedIterations = 0; +} +GSSolver.prototype = new Solver(); +GSSolver.prototype.constructor = GSSolver; + +function setArrayZero(array){ + var l = array.length; + while(l--){ + array[l] = +0.0; + } +} + +/** + * Solve the system of equations + * @method solve + * @param {Number} h Time step + * @param {World} world World to solve + */ +GSSolver.prototype.solve = function(h, world){ + + this.sortEquations(); + + var iter = 0, + maxIter = this.iterations, + maxFrictionIter = this.frictionIterations, + equations = this.equations, + Neq = equations.length, + tolSquared = Math.pow(this.tolerance*Neq, 2), + bodies = world.bodies, + Nbodies = world.bodies.length, + add = vec2.add, + set = vec2.set, + useZeroRHS = this.useZeroRHS, + lambda = this.lambda; + + this.usedIterations = 0; + + if(Neq){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Update solve mass + b.updateSolveMassProperties(); + } + } + + // Things that does not change during iteration can be computed once + if(lambda.length < Neq){ + lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); + } + setArrayZero(lambda); + var invCs = this.invCs, + Bs = this.Bs, + lambda = this.lambda; + + for(var i=0; i!==equations.length; i++){ + var c = equations[i]; + if(c.timeStep !== h || c.needsUpdate){ + c.timeStep = h; + c.update(); + } + Bs[i] = c.computeB(c.a,c.b,h); + invCs[i] = c.computeInvC(c.epsilon); + } + + var q, B, c, deltalambdaTot,i,j; + + if(Neq !== 0){ + + for(i=0; i!==Nbodies; i++){ + var b = bodies[i]; + + // Reset vlambda + b.resetConstraintVelocity(); + } + + if(maxFrictionIter){ + // Iterate over contact equations to get normal forces + for(iter=0; iter!==maxFrictionIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + + // Set computed friction force + for(j=0; j!==Neq; j++){ + var eq = equations[j]; + if(eq instanceof FrictionEquation){ + var f = 0.0; + for(var k=0; k!==eq.contactEquations.length; k++){ + f += eq.contactEquations[k].multiplier; + } + f *= eq.frictionCoefficient / eq.contactEquations.length; + eq.maxForce = f; + eq.minForce = -f; + } + } + } + + // Iterate over all equations + for(iter=0; iter!==maxIter; iter++){ + + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for(j=0; j!==Neq; j++){ + c = equations[j]; + + var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); + deltalambdaTot += Math.abs(deltalambda); + } + + this.usedIterations++; + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot <= tolSquared){ + break; + } + } + + // Add result to velocity + for(i=0; i!==Nbodies; i++){ + bodies[i].addConstraintVelocity(); + } + + GSSolver.updateMultipliers(equations, lambda, 1/h); + } +}; + +// Sets the .multiplier property of each equation +GSSolver.updateMultipliers = function(equations, lambda, invDt){ + // Set the .multiplier property of each equation + var l = equations.length; + while(l--){ + equations[l].multiplier = lambda[l] * invDt; + } +}; + +GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ + // Compute iteration + var B = Bs[j], + invC = invCs[j], + lambdaj = lambda[j], + GWlambda = eq.computeGWlambda(); + + var maxForce = eq.maxForce, + minForce = eq.minForce; + + if(useZeroRHS){ + B = 0; + } + + var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); + + // Clamp if we are not within the min/max interval + var lambdaj_plus_deltalambda = lambdaj + deltalambda; + if(lambdaj_plus_deltalambda < minForce*dt){ + deltalambda = minForce*dt - lambdaj; + } else if(lambdaj_plus_deltalambda > maxForce*dt){ + deltalambda = maxForce*dt - lambdaj; + } + lambda[j] += deltalambda; + eq.addToWlambda(deltalambda); + + return deltalambda; +}; + +},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils') +, EventEmitter = _dereq_('../events/EventEmitter'); + +module.exports = Solver; + +/** + * Base class for constraint solvers. + * @class Solver + * @constructor + * @extends EventEmitter + */ +function Solver(options,type){ + options = options || {}; + + EventEmitter.call(this); + + this.type = type; + + /** + * Current equations in the solver. + * + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Function that is used to sort all equations before each solve. + * @property equationSortFunction + * @type {function|boolean} + */ + this.equationSortFunction = options.equationSortFunction || false; +} +Solver.prototype = new EventEmitter(); +Solver.prototype.constructor = Solver; + +/** + * Method to be implemented in each subclass + * @method solve + * @param {Number} dt + * @param {World} world + */ +Solver.prototype.solve = function(dt,world){ + throw new Error("Solver.solve should be implemented by subclasses!"); +}; + +var mockWorld = {bodies:[]}; + +/** + * Solves all constraints in an island. + * @method solveIsland + * @param {Number} dt + * @param {Island} island + */ +Solver.prototype.solveIsland = function(dt,island){ + + this.removeAllEquations(); + + if(island.equations.length){ + // Add equations to solver + this.addEquations(island.equations); + mockWorld.bodies.length = 0; + island.getBodies(mockWorld.bodies); + + // Solve + if(mockWorld.bodies.length){ + this.solve(dt,mockWorld); + } + } +}; + +/** + * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. + * @method sortEquations + */ +Solver.prototype.sortEquations = function(){ + if(this.equationSortFunction){ + this.equations.sort(this.equationSortFunction); + } +}; + +/** + * Add an equation to be solved. + * + * @method addEquation + * @param {Equation} eq + */ +Solver.prototype.addEquation = function(eq){ + if(eq.enabled){ + this.equations.push(eq); + } +}; + +/** + * Add equations. Same as .addEquation, but this time the argument is an array of Equations + * + * @method addEquations + * @param {Array} eqs + */ +Solver.prototype.addEquations = function(eqs){ + //Utils.appendArray(this.equations,eqs); + for(var i=0, N=eqs.length; i!==N; i++){ + var eq = eqs[i]; + if(eq.enabled){ + this.equations.push(eq); + } + } +}; + +/** + * Remove an equation. + * + * @method removeEquation + * @param {Equation} eq + */ +Solver.prototype.removeEquation = function(eq){ + var i = this.equations.indexOf(eq); + if(i !== -1){ + this.equations.splice(i,1); + } +}; + +/** + * Remove all currently added equations. + * + * @method removeAllEquations + */ +Solver.prototype.removeAllEquations = function(){ + this.equations.length=0; +}; + +Solver.GS = 1; +Solver.ISLAND = 2; + +},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){ +var ContactEquation = _dereq_('../equations/ContactEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = ContactEquationPool; + +/** + * @class + */ +function ContactEquationPool() { + Pool.apply(this, arguments); +} +ContactEquationPool.prototype = new Pool(); +ContactEquationPool.prototype.constructor = ContactEquationPool; + +/** + * @method create + * @return {ContactEquation} + */ +ContactEquationPool.prototype.create = function () { + return new ContactEquation(); +}; + +/** + * @method destroy + * @param {ContactEquation} equation + * @return {ContactEquationPool} + */ +ContactEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){ +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Pool = _dereq_('./Pool'); + +module.exports = FrictionEquationPool; + +/** + * @class + */ +function FrictionEquationPool() { + Pool.apply(this, arguments); +} +FrictionEquationPool.prototype = new Pool(); +FrictionEquationPool.prototype.constructor = FrictionEquationPool; + +/** + * @method create + * @return {FrictionEquation} + */ +FrictionEquationPool.prototype.create = function () { + return new FrictionEquation(); +}; + +/** + * @method destroy + * @param {FrictionEquation} equation + * @return {FrictionEquationPool} + */ +FrictionEquationPool.prototype.destroy = function (equation) { + equation.bodyA = equation.bodyB = null; + return this; +}; + +},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){ +var IslandNode = _dereq_('../world/IslandNode'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandNodePool; + +/** + * @class + */ +function IslandNodePool() { + Pool.apply(this, arguments); +} +IslandNodePool.prototype = new Pool(); +IslandNodePool.prototype.constructor = IslandNodePool; + +/** + * @method create + * @return {IslandNode} + */ +IslandNodePool.prototype.create = function () { + return new IslandNode(); +}; + +/** + * @method destroy + * @param {IslandNode} node + * @return {IslandNodePool} + */ +IslandNodePool.prototype.destroy = function (node) { + node.reset(); + return this; +}; + +},{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){ +var Island = _dereq_('../world/Island'); +var Pool = _dereq_('./Pool'); + +module.exports = IslandPool; + +/** + * @class + */ +function IslandPool() { + Pool.apply(this, arguments); +} +IslandPool.prototype = new Pool(); +IslandPool.prototype.constructor = IslandPool; + +/** + * @method create + * @return {Island} + */ +IslandPool.prototype.create = function () { + return new Island(); +}; + +/** + * @method destroy + * @param {Island} island + * @return {IslandPool} + */ +IslandPool.prototype.destroy = function (island) { + island.reset(); + return this; +}; + +},{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){ +var TupleDictionary = _dereq_('./TupleDictionary'); +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool'); +var Utils = _dereq_('./Utils'); + +module.exports = OverlapKeeper; + +/** + * Keeps track of overlaps in the current state and the last step state. + * @class OverlapKeeper + * @constructor + */ +function OverlapKeeper() { + this.overlappingShapesLastState = new TupleDictionary(); + this.overlappingShapesCurrentState = new TupleDictionary(); + this.recordPool = new OverlapKeeperRecordPool({ size: 16 }); + this.tmpDict = new TupleDictionary(); + this.tmpArray1 = []; +} + +/** + * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current. + * @method tick + */ +OverlapKeeper.prototype.tick = function() { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Save old objects into pool + var l = last.keys.length; + while(l--){ + var key = last.keys[l]; + var lastObject = last.getByKey(key); + var currentObject = current.getByKey(key); + if(lastObject){ + // The record is only used in the "last" dict, and will be removed. We might as well pool it. + this.recordPool.release(lastObject); + } + } + + // Clear last object + last.reset(); + + // Transfer from new object to old + last.copy(current); + + // Clear current object + current.reset(); +}; + +/** + * @method setOverlapping + * @param {Body} bodyA + * @param {Body} shapeA + * @param {Body} bodyB + * @param {Body} shapeB + */ +OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + + // Store current contact state + if(!current.get(shapeA.id, shapeB.id)){ + var data = this.recordPool.get(); + data.set(bodyA, shapeA, bodyB, shapeB); + current.set(shapeA.id, shapeB.id, data); + } +}; + +OverlapKeeper.prototype.getNewOverlaps = function(result){ + return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result); +}; + +OverlapKeeper.prototype.getEndOverlaps = function(result){ + return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result); +}; + +/** + * Checks if two bodies are currently overlapping. + * @method bodiesAreOverlapping + * @param {Body} bodyA + * @param {Body} bodyB + * @return {boolean} + */ +OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){ + var current = this.overlappingShapesCurrentState; + var l = current.keys.length; + while(l--){ + var key = current.keys[l]; + var data = current.data[key]; + if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){ + return true; + } + } + return false; +}; + +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){ + // Not overlapping in last state, but in current. + result.push(data); + } + } + + return result; +}; + +OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ + var idA = shapeA.id|0, + idB = shapeB.id|0; + var last = this.overlappingShapesLastState; + var current = this.overlappingShapesCurrentState; + // Not in last but in new + return !!!last.get(idA, idB) && !!current.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]; + + // Since we use body id's for the accumulator, these will be a subset of the original one + accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); + } + + l = accumulator.keys.length; + while(l--){ + var data = accumulator.getByKey(accumulator.keys[l]); + if(data){ + result.push(data.bodyA, data.bodyB); + } + } + + accumulator.reset(); + + return result; +}; + +},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){ +module.exports = OverlapKeeperRecord; + +/** + * Overlap data container for the OverlapKeeper + * @class OverlapKeeperRecord + * @constructor + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ + /** + * @property {Shape} shapeA + */ + this.shapeA = shapeA; + /** + * @property {Shape} shapeB + */ + this.shapeB = shapeB; + /** + * @property {Body} bodyA + */ + this.bodyA = bodyA; + /** + * @property {Body} bodyB + */ + this.bodyB = bodyB; +} + +/** + * Set the data for the record + * @method set + * @param {Body} bodyA + * @param {Shape} shapeA + * @param {Body} bodyB + * @param {Shape} shapeB + */ +OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ + OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); +}; + +},{}],54:[function(_dereq_,module,exports){ +var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord'); +var Pool = _dereq_('./Pool'); + +module.exports = OverlapKeeperRecordPool; + +/** + * @class + */ +function OverlapKeeperRecordPool() { + Pool.apply(this, arguments); +} +OverlapKeeperRecordPool.prototype = new Pool(); +OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool; + +/** + * @method create + * @return {OverlapKeeperRecord} + */ +OverlapKeeperRecordPool.prototype.create = function () { + return new OverlapKeeperRecord(); +}; + +/** + * @method destroy + * @param {OverlapKeeperRecord} record + * @return {OverlapKeeperRecordPool} + */ +OverlapKeeperRecordPool.prototype.destroy = function (record) { + record.bodyA = record.bodyB = record.shapeA = record.shapeB = null; + return this; +}; + +},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){ +module.exports = Pool; + +/** + * @class Object pooling utility. + */ +function Pool(options) { + options = options || {}; + + /** + * @property {Array} objects + * @type {Array} + */ + this.objects = []; + + if(options.size !== undefined){ + this.resize(options.size); + } +} + +/** + * @method resize + * @param {number} size + * @return {Pool} Self, for chaining + */ +Pool.prototype.resize = function (size) { + var objects = this.objects; + + while (objects.length > size) { + objects.pop(); + } + + while (objects.length < size) { + objects.push(this.create()); + } + + return this; +}; + +/** + * Get an object from the pool or create a new instance. + * @method get + * @return {Object} + */ +Pool.prototype.get = function () { + var objects = this.objects; + return objects.length ? objects.pop() : this.create(); +}; + +/** + * Clean up and put the object back into the pool for later use. + * @method release + * @param {Object} object + * @return {Pool} Self for chaining + */ +Pool.prototype.release = function (object) { + this.destroy(object); + this.objects.push(object); + return this; +}; + +},{}],56:[function(_dereq_,module,exports){ +var Utils = _dereq_('./Utils'); + +module.exports = TupleDictionary; + +/** + * @class TupleDictionary + * @constructor + */ +function TupleDictionary() { + + /** + * The data storage + * @property data + * @type {Object} + */ + this.data = {}; + + /** + * Keys that are currently used. + * @property {Array} keys + */ + this.keys = []; +} + +/** + * Generate a key given two integers + * @method getKey + * @param {number} i + * @param {number} j + * @return {string} + */ +TupleDictionary.prototype.getKey = function(id1, id2) { + id1 = id1|0; + id2 = id2|0; + + if ( (id1|0) === (id2|0) ){ + return -1; + } + + // valid for values < 2^16 + return ((id1|0) > (id2|0) ? + (id1 << 16) | (id2 & 0xFFFF) : + (id2 << 16) | (id1 & 0xFFFF))|0 + ; +}; + +/** + * @method getByKey + * @param {Number} key + * @return {Object} + */ +TupleDictionary.prototype.getByKey = function(key) { + key = key|0; + return this.data[key]; +}; + +/** + * @method get + * @param {Number} i + * @param {Number} j + * @return {Number} + */ +TupleDictionary.prototype.get = function(i, j) { + return this.data[this.getKey(i, j)]; +}; + +/** + * Set a value. + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +TupleDictionary.prototype.set = function(i, j, value) { + if(!value){ + throw new Error("No data!"); + } + + var key = this.getKey(i, j); + + // Check if key already exists + if(!this.data[key]){ + this.keys.push(key); + } + + this.data[key] = value; + + return key; +}; + +/** + * Remove all data. + * @method reset + */ +TupleDictionary.prototype.reset = function() { + var data = this.data, + keys = this.keys; + + var l = keys.length; + while(l--) { + delete data[keys[l]]; + } + + keys.length = 0; +}; + +/** + * Copy another TupleDictionary. Note that all data in this dictionary will be removed. + * @method copy + * @param {TupleDictionary} dict The TupleDictionary to copy into this one. + */ +TupleDictionary.prototype.copy = function(dict) { + this.reset(); + Utils.appendArray(this.keys, dict.keys); + var l = dict.keys.length; + while(l--){ + var key = dict.keys[l]; + this.data[key] = dict.data[key]; + } +}; + +},{"./Utils":57}],57:[function(_dereq_,module,exports){ +/* global P2_ARRAY_TYPE */ + +module.exports = Utils; + +/** + * Misc utility functions + * @class Utils + * @constructor + */ +function Utils(){} + +/** + * Append the values in array b to the array a. See this for an explanation. + * @method appendArray + * @static + * @param {Array} a + * @param {Array} b + */ +Utils.appendArray = function(a,b){ + if (b.length < 150000) { + a.push.apply(a, b); + } else { + for (var i = 0, len = b.length; i !== len; ++i) { + a.push(b[i]); + } + } +}; + +/** + * Garbage free Array.splice(). Does not allocate a new array. + * @method splice + * @static + * @param {Array} array + * @param {Number} index + * @param {Number} howmany + */ +Utils.splice = function(array,index,howmany){ + howmany = howmany || 1; + for (var i=index, len=array.length-howmany; i < len; i++){ + array[i] = array[i + howmany]; + } + array.length = len; +}; + +/** + * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below. + * @static + * @property {function} ARRAY_TYPE + * @example + * + * + */ +if(typeof P2_ARRAY_TYPE !== 'undefined') { + Utils.ARRAY_TYPE = P2_ARRAY_TYPE; +} else if (typeof Float32Array !== 'undefined'){ + Utils.ARRAY_TYPE = Float32Array; +} else { + Utils.ARRAY_TYPE = Array; +} + +/** + * Extend an object with the properties of another + * @static + * @method extend + * @param {object} a + * @param {object} b + */ +Utils.extend = function(a,b){ + for(var key in b){ + a[key] = b[key]; + } +}; + +/** + * Extend an options object with default values. + * @static + * @method defaults + * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. + * @param {object} defaults An object containing default values. + * @return {object} The modified options object. + */ +Utils.defaults = function(options, defaults){ + options = options || {}; + for(var key in defaults){ + if(!(key in options)){ + options[key] = defaults[key]; + } + } + return options; +}; + +},{}],58:[function(_dereq_,module,exports){ +var Body = _dereq_('../objects/Body'); + +module.exports = Island; + +/** + * An island of bodies connected with equations. + * @class Island + * @constructor + */ +function Island(){ + + /** + * Current equations in this island. + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * Current bodies in this island. + * @property bodies + * @type {Array} + */ + this.bodies = []; +} + +/** + * Clean this island from bodies and equations. + * @method reset + */ +Island.prototype.reset = function(){ + this.equations.length = this.bodies.length = 0; +}; + +var bodyIds = []; + +/** + * Get all unique bodies in this island. + * @method getBodies + * @return {Array} An array of Body + */ +Island.prototype.getBodies = function(result){ + var bodies = result || [], + eqs = this.equations; + bodyIds.length = 0; + for(var i=0; i!==eqs.length; i++){ + var eq = eqs[i]; + if(bodyIds.indexOf(eq.bodyA.id)===-1){ + bodies.push(eq.bodyA); + bodyIds.push(eq.bodyA.id); + } + if(bodyIds.indexOf(eq.bodyB.id)===-1){ + bodies.push(eq.bodyB); + bodyIds.push(eq.bodyB.id); + } + } + return bodies; +}; + +/** + * Check if the entire island wants to sleep. + * @method wantsToSleep + * @return {Boolean} + */ +Island.prototype.wantsToSleep = function(){ + for(var i=0; i= dt && substeps < maxSubSteps) { + // Do fixed steps to catch up + this.internalStep(dt); + this.time += dt; + this.accumulator -= dt; + substeps++; + } + + var t = (this.accumulator % dt) / dt; + for(var j=0; j!==this.bodies.length; j++){ + var b = this.bodies[j]; + vec2.lerp(b.interpolatedPosition, b.previousPosition, b.position, t); + b.interpolatedAngle = b.previousAngle + t * (b.angle - b.previousAngle); + } + } +}; + +var endOverlaps = []; + +/** + * Make a fixed step. + * @method internalStep + * @param {number} dt + * @private + */ +World.prototype.internalStep = function(dt){ + this.stepping = true; + + var that = this, + Nsprings = this.springs.length, + springs = this.springs, + bodies = this.bodies, + g = this.gravity, + solver = this.solver, + Nbodies = this.bodies.length, + broadphase = this.broadphase, + np = this.narrowphase, + constraints = this.constraints, + t0, t1, + fhMinv = step_fhMinv, + velodt = step_velodt, + mg = step_mg, + scale = vec2.scale, + add = vec2.add, + rotate = vec2.rotate, + islandManager = this.islandManager; + + this.overlapKeeper.tick(); + + this.lastTimeStep = dt; + + // Update approximate friction gravity. + if(this.useWorldGravityAsFrictionGravity){ + var gravityLen = vec2.length(this.gravity); + if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){ + // Nonzero gravity. Use it. + this.frictionGravity = gravityLen; + } + } + + // Add gravity to bodies + if(this.applyGravity){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i], + fi = b.force; + if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ + continue; + } + vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g + add(fi,fi,mg); + } + } + + // Add spring forces + if(this.applySpringForces){ + for(var i=0; i!==Nsprings; i++){ + var s = springs[i]; + s.applyForce(); + } + } + + if(this.applyDamping){ + for(var i=0; i!==Nbodies; i++){ + var b = bodies[i]; + if(b.type === Body.DYNAMIC){ + b.applyDamping(dt); + } + } + } + + // Broadphase + var result = broadphase.getCollisionPairs(this); + + // Remove ignored collision pairs + var ignoredPairs = this.disabledBodyCollisionPairs; + for(var i=ignoredPairs.length-2; 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); + } + } + } + + // Remove constrained pairs with collideConnected == false + 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); + } + } + } + } + + // postBroadphase event + this.postBroadphaseEvent.pairs = result; + this.emit(this.postBroadphaseEvent); + this.postBroadphaseEvent.pairs = null; + + // Narrowphase + np.reset(this); + for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ + var bi = result[i], + bj = result[i+1]; + + // Loop over all shapes of body i + for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ + var si = bi.shapes[k], + xi = si.position, + ai = si.angle; + + // All shapes of body j + for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ + var sj = bj.shapes[l], + xj = sj.position, + aj = sj.angle; + + 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); + } + } + } + + // Wake up bodies + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + if(body._wakeUpAfterNarrowphase){ + body.wakeUp(); + body._wakeUpAfterNarrowphase = false; + } + } + + // Emit end overlap events + 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.bodyB; + this.emit(e); + } + endOverlaps.length = 0; + } + + var preSolveEvent = this.preSolveEvent; + preSolveEvent.contactEquations = np.contactEquations; + preSolveEvent.frictionEquations = np.frictionEquations; + this.emit(preSolveEvent); + preSolveEvent.contactEquations = preSolveEvent.frictionEquations = null; + + // update constraint equations + var Nconstraints = constraints.length; + for(i=0; i!==Nconstraints; i++){ + constraints[i].update(); + } + + if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){ + if(this.islandSplit){ + // Split into islands + 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 { + + // Add contact equations to solver + solver.addEquations(np.contactEquations); + solver.addEquations(np.frictionEquations); + + // Add user-defined constraint equations + for(i=0; i!==Nconstraints; i++){ + solver.addEquations(constraints[i].equations); + } + + if(this.solveConstraints){ + solver.solve(dt,this); + } + + solver.removeAllEquations(); + } + } + + // Step forward + for(var i=0; i!==Nbodies; i++){ + var body = bodies[i]; + + // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){ + body.integrate(dt); + // } + } + + // Reset force + for(var i=0; i!==Nbodies; i++){ + bodies[i].setZeroForce(); + } + + // Emit impact event + 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); + } + } + } + + // Sleeping update + if(this.sleepMode === World.BODY_SLEEPING){ + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, false, dt); + } + } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){ + + // Tell all bodies to sleep tick but dont sleep yet + for(i=0; i!==Nbodies; i++){ + bodies[i].sleepTick(this.time, true, dt); + } + + // Sleep islands + for(var i=0; i 0; + np.frictionCoefficient = cm.friction; + var reducedMass; + if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){ + reducedMass = bj.mass; + } else if(bj.type === Body.STATIC || bj.type === 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; + np.contactSkinSize = cm.contactSkinSize; + np.enabledEquations = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse; + + 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 < sj.type) { + numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); + } else { + numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); + } + var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; + + if(numContacts){ + + if( bi.allowSleep && + bi.type === Body.DYNAMIC && + bi.sleepState === Body.SLEEPING && + bj.sleepState === Body.AWAKE && + bj.type !== Body.STATIC + ){ + var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); + var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); + if(speedSquaredB >= speedLimitSquaredB*2){ + bi._wakeUpAfterNarrowphase = true; + } + } + + if( bj.allowSleep && + bj.type === Body.DYNAMIC && + bj.sleepState === Body.SLEEPING && + bi.sleepState === Body.AWAKE && + bi.type !== 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)){ + + // Report new shape overlap + var e = this.beginContactEvent; + e.shapeA = si; + e.shapeB = sj; + e.bodyA = bi; + e.bodyB = bj; + + // Reset contact equations + e.contactEquations.length = 0; + + if(typeof(numContacts)==="number"){ + for(var i=np.contactEquations.length-numContacts; i 1){ // Why divide by 1? + for(var i=np.frictionEquations.length-numFrictionEquations; i=0; i--){ + this.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.bodies; + for(var i=bodies.length-1; i>=0; i--){ + this.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.springs; + for(var i=springs.length-1; i>=0; i--){ + this.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.contactMaterials; + for(var i=cms.length-1; i>=0; i--){ + this.removeContactMaterial(cms[i]); + } + + World.apply(this); +}; + +var hitTest_tmp1 = vec2.create(), + hitTest_zero = vec2.fromValues(0,0), + hitTest_tmp2 = vec2.fromValues(0,0); + +/** + * Test if a world point overlaps bodies + * @method hitTest + * @param {Array} worldPoint Point to use for intersection tests + * @param {Array} bodies A list of objects to check for intersection + * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @return {Array} Array of bodies that overlap the point + * @todo Should use an api similar to the raycast function + * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient + * @todo Should use the broadphase + */ +World.prototype.hitTest = function(worldPoint,bodies,precision){ + precision = precision || 0; + + // Create a dummy particle body with a particle shape to test against the bodies + 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 = []; + + // Check bodies + 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]; + + // Get shape world position + angle + vec2.rotate(x, s.position, b.angle); + vec2.add(x, x, b.position); + var a = s.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)) < precision*precision) + ){ + result.push(b); + } + } + } + + return result; +}; + +/** + * Set the stiffness for all equations and contact materials. + * @method setGlobalStiffness + * @param {Number} stiffness + */ +World.prototype.setGlobalStiffness = function(stiffness){ + + // Set for all constraints + var constraints = this.constraints; + for(var i=0; i !== constraints.length; i++){ + var c = constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.stiffness = stiffness; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + var contactMaterials = this.contactMaterials; + for(var i=0; i !== contactMaterials.length; i++){ + var c = contactMaterials[i]; + c.stiffness = c.frictionStiffness = stiffness; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.stiffness = c.frictionStiffness = stiffness; +}; + +/** + * Set the relaxation for all equations and contact materials. + * @method setGlobalRelaxation + * @param {Number} relaxation + */ +World.prototype.setGlobalRelaxation = function(relaxation){ + + // Set for all constraints + for(var i=0; i !== this.constraints.length; i++){ + var c = this.constraints[i]; + for(var j=0; j !== c.equations.length; j++){ + var eq = c.equations[j]; + eq.relaxation = relaxation; + eq.needsUpdate = true; + } + } + + // Set for all contact materials + for(var i=0; i !== this.contactMaterials.length; i++){ + var c = this.contactMaterials[i]; + c.relaxation = c.frictionRelaxation = relaxation; + } + + // Set for default contact material + var c = this.defaultContactMaterial; + c.relaxation = c.frictionRelaxation = relaxation; +}; + +var tmpAABB = new AABB(); +var tmpArray = []; + +/** + * Ray cast against all bodies in the world. + * @method raycast + * @param {RaycastResult} result + * @param {Ray} ray + * @return {boolean} True if any body was hit. + * + * @example + * var ray = new Ray({ + * mode: Ray.CLOSEST, // or ANY + * from: [0, 0], + * to: [10, 0], + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * @example + * var ray = new Ray({ + * mode: Ray.ALL, + * from: [0, 0], + * to: [10, 0], + * callback: function(result){ + * + * // Print some info about the hit + * console.log('Hit body and shape: ', result.body, result.shape); + * + * // Get the hit point + * var hitPoint = vec2.create(); + * result.getHitPoint(hitPoint, ray); + * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray)); + * + * // If you are happy with the hits you got this far, you can stop the traversal here: + * result.stop(); + * } + * }); + * var result = new RaycastResult(); + * world.raycast(result, ray); + */ +World.prototype.raycast = function(result, ray){ + + // Get all bodies within the ray AABB + ray.getAABB(tmpAABB); + this.broadphase.aabbQuery(this, tmpAABB, tmpArray); + ray.intersectBodies(result, tmpArray); + tmpArray.length = 0; + + return result.hasHit(); +}; + +},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36]) +(36) +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +(function(){ + + var root = this; + +/** + * Namespace-class for [pixi.js](http://www.pixijs.com/). + * + * Contains assorted static properties and enumerations. + * + * @namespace PIXI + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ +var PIXI = PIXI || {}; + +/** +* @author Mat Groves http://matgroves.com @Doormat23 +* @author Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The base class for all objects that are rendered. Contains properties for position, scaling, +* rotation, masks and cache handling. +* +* This is an abstract class and should not be used on its own, rather it should be extended. +* +* It is used internally by the likes of PIXI.Sprite. +* +* @class PIXI.DisplayObject +* @constructor +*/ +PIXI.DisplayObject = function () { + + /** + * The coordinates, in pixels, of this DisplayObject, relative to its parent container. + * + * The value of this property does not reflect any positioning happening further up the display list. + * To obtain that value please see the `worldPosition` property. + * + * @property {PIXI.Point} position + * @default + */ + this.position = new PIXI.Point(0, 0); + + /** + * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject + * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on. + * + * The value of this property does not reflect any scaling happening further up the display list. + * To obtain that value please see the `worldScale` property. + * + * @property {PIXI.Point} scale + * @default + */ + this.scale = new PIXI.Point(1, 1); + + /** + * The pivot point of this DisplayObject that it rotates around. The values are expressed + * in pixel values. + * @property {PIXI.Point} pivot + * @default + */ + this.pivot = new PIXI.Point(0, 0); + + /** + * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on + * a right-handed orientation. + * + * The value of this property does not reflect any rotation happening further up the display list. + * To obtain that value please see the `worldRotation` property. + * + * @property {number} rotation + * @default + */ + this.rotation = 0; + + /** + * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * Please note that an object with an alpha value of 0 is skipped during the render pass. + * + * The value of this property does not reflect any alpha values set further up the display list. + * To obtain that value please see the `worldAlpha` property. + * + * @property {number} alpha + * @default + */ + this.alpha = 1; + + /** + * The visibility of this DisplayObject. A value of `false` makes the object invisible. + * A value of `true` makes it visible. Please note that an object with a visible value of + * `false` is skipped during the render pass. Equally a DisplayObject with visible false will + * not render any of its children. + * + * The value of this property does not reflect any visible values set further up the display list. + * To obtain that value please see the `worldVisible` property. + * + * @property {boolean} visible + * @default + */ + this.visible = true; + + /** + * This is the defined area that will pick up mouse / touch events. It is null by default. + * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children) + * + * @property hitArea + * @type Rectangle|Circle|Ellipse|Polygon + */ + this.hitArea = null; + + /** + * Should this DisplayObject be rendered by the renderer? An object with a renderable value of + * `false` is skipped during the render pass. + * + * @property {boolean} renderable + * @default + */ + this.renderable = false; + + /** + * The parent DisplayObjectContainer that this DisplayObject is a child of. + * All DisplayObjects must belong to a parent in order to be rendered. + * The root parent is the Stage object. This property is set automatically when the + * DisplayObject is added to, or removed from, a DisplayObjectContainer. + * + * @property {PIXI.DisplayObjectContainer} parent + * @default + * @readOnly + */ + this.parent = null; + + /** + * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects + * in the display list. + * + * To obtain, and set, the local alpha value, see the `alpha` property. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldAlpha + * @readOnly + */ + this.worldAlpha = 1; + + /** + * The current transform of this DisplayObject. + * + * This property contains the calculated total, based on the transforms of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {Phaser.Matrix} worldTransform + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * The coordinates, in pixels, of this DisplayObject within the world. + * + * This property contains the calculated total, based on the positions of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldPosition + * @readOnly + */ + this.worldPosition = new PIXI.Point(0, 0); + + /** + * The global scale of this DisplayObject. + * + * This property contains the calculated total, based on the scales of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldScale + * @readOnly + */ + this.worldScale = new PIXI.Point(1, 1); + + /** + * The rotation, in radians, of this DisplayObject. + * + * This property contains the calculated total, based on the rotations of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldRotation + * @readOnly + */ + this.worldRotation = 0; + + /** + * The rectangular area used by filters when rendering a shader for this DisplayObject. + * + * @property {PIXI.Rectangle} filterArea + * @type Rectangle + * @default + */ + this.filterArea = null; + + /** + * @property {number} _sr - Cached rotation value. + * @private + */ + this._sr = 0; + + /** + * @property {number} _cr - Cached rotation value. + * @private + */ + this._cr = 1; + + /** + * @property {PIXI.Rectangle} _bounds - The cached bounds of this object. + * @private + */ + this._bounds = new PIXI.Rectangle(0, 0, 0, 0); + + /** + * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object. + * @private + */ + this._currentBounds = null; + + /** + * @property {PIXI.Rectangle} _mask - The cached mask of this object. + * @private + */ + this._mask = null; + + /** + * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag. + * @private + */ + this._cacheAsBitmap = false; + + /** + * @property {boolean} _cacheIsDirty - Internal dirty cache flag. + * @private + */ + this._cacheIsDirty = false; + +}; + +PIXI.DisplayObject.prototype = { + + constructor: PIXI.DisplayObject, + + /** + * Destroy this DisplayObject. + * + * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask. + * + * Also iteratively calls `destroy` on any children. + * + * @method PIXI.DisplayObject#destroy + */ + destroy: function () { + + if (this.children) + { + var i = this.children.length; + + while (i--) + { + this.children[i].destroy(); + } + + this.children = []; + } + + this.hitArea = null; + this.parent = null; + this.worldTransform = null; + this.filterArea = null; + this.renderable = false; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + }, + + /** + * Updates the transform matrix this DisplayObject uses for rendering. + * + * If the object has no parent, and no parent parameter is provided, it will default to + * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place. + * + * The `parent` parameter has priority over the actual parent. Use it as a parent override. + * Setting it does **not** change the actual parent of this DisplayObject. + * + * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale` + * and `worldRotation` properties. + * + * If a `transformCallback` has been specified, it is called at the end of this method, and is passed + * the new, updated, worldTransform property, along with the parent transform used. + * + * @method PIXI.DisplayObject#updateTransform + * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from. + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateTransform: function (parent) { + + if (!parent && !this.parent && !this.game) + { + return this; + } + + var p = this.parent; + + if (parent) + { + p = parent; + } + else if (!this.parent) + { + p = this.game.world; + } + + // create some matrix refs for easy access + var pt = p.worldTransform; + var wt = this.worldTransform; + + // temporary matrix variables + var a, b, c, d, tx, ty; + + // so if rotation is between 0 then we can simplify the multiplication process.. + if (this.rotation % Phaser.Math.PI2) + { + // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes + if (this.rotation !== this.rotationCache) + { + this.rotationCache = this.rotation; + this._sr = Math.sin(this.rotation); + this._cr = Math.cos(this.rotation); + } + + // get the matrix values of the displayobject based on its transform properties.. + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + tx = this.position.x; + ty = this.position.y; + + // check for pivot.. not often used so geared towards that fact! + if (this.pivot.x || this.pivot.y) + { + tx -= this.pivot.x * a + this.pivot.y * c; + ty -= this.pivot.x * b + this.pivot.y * d; + } + + // concat the parent matrix with the objects transform. + wt.a = a * pt.a + b * pt.c; + wt.b = a * pt.b + b * pt.d; + wt.c = c * pt.a + d * pt.c; + wt.d = c * pt.b + d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + else + { + // lets do the fast version as we know there is no rotation.. + a = this.scale.x; + b = 0; + c = 0; + d = this.scale.y; + tx = this.position.x - this.pivot.x * a; + ty = this.position.y - this.pivot.y * d; + + wt.a = a * pt.a; + wt.b = a * pt.b; + wt.c = d * pt.c; + wt.d = d * pt.d; + wt.tx = tx * pt.a + ty * pt.c + pt.tx; + wt.ty = tx * pt.b + ty * pt.d + pt.ty; + } + + a = wt.a; + b = wt.b; + c = wt.c; + d = wt.d; + + var determ = (a * d) - (b * c); + + if (a || b) + { + var r = Math.sqrt((a * a) + (b * b)); + + this.worldRotation = (b > 0) ? Math.acos(a / r) : -Math.acos(a / r); + this.worldScale.x = r; + this.worldScale.y = determ / r; + } + else if (c || d) + { + var s = Math.sqrt((c * c) + (d * d)); + + this.worldRotation = Phaser.Math.HALF_PI - ((d > 0) ? Math.acos(-c / s) : -Math.acos(c / s)); + this.worldScale.x = determ / s; + this.worldScale.y = s; + } + else + { + this.worldScale.x = 0; + this.worldScale.y = 0; + } + + // Set the World values + this.worldAlpha = this.alpha * p.worldAlpha; + this.worldPosition.x = wt.tx; + this.worldPosition.y = wt.ty; + + // reset the bounds each time this is called! + this._currentBounds = null; + + // Custom callback? + if (this.transformCallback) + { + this.transformCallback.call(this.transformCallbackContext, wt, pt); + } + + return this; + + }, + + /** + * To be overridden by classes that require it. + * + * @method PIXI.DisplayObject#preUpdate + */ + preUpdate: function () { + + }, + + /** + * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites. + * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times. + * + * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures, + * and references to them, so they don't linger in memory. + * + * @method PIXI.DisplayObject#generateTexture + * @param {number} [resolution=1] - The resolution of the texture being generated. + * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values. + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture. + * @return {Phaser.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked. + */ + generateTexture: function (resolution, scaleMode, renderer) { + + var bounds = this.getLocalBounds(); + + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + + renderTexture.render(this, PIXI.DisplayObject._tempMatrix); + + return renderTexture; + + }, + + /** + * If this DisplayObject has a cached Sprite, this method generates and updates it. + * + * @method PIXI.DisplayObject#updateCache + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ + updateCache: function () { + + this._generateCachedSprite(); + + return this; + + }, + + /** + * Calculates the global position of this DisplayObject, based on the position given. + * + * @method PIXI.DisplayObject#toGlobal + * @param {PIXI.Point} position - The global position to calculate from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toGlobal: function (position) { + + this.updateTransform(); + + return this.worldTransform.apply(position); + + }, + + /** + * Calculates the local position of this DisplayObject, relative to another point. + * + * @method PIXI.DisplayObject#toLocal + * @param {PIXI.Point} position - The world origin to calculate from. + * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ + toLocal: function (position, from) { + + if (from) + { + position = from.toGlobal(position); + } + + this.updateTransform(); + + return this.worldTransform.applyInverse(position); + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_renderCachedSprite + * @private + * @param {Object} renderSession - The render session + */ + _renderCachedSprite: function (renderSession) { + + this._cachedSprite.worldAlpha = this.worldAlpha; + + if (renderSession.gl) + { + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + } + else + { + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + } + + }, + + /** + * Internal method. + * + * @method PIXI.DisplayObject#_generateCachedSprite + * @private + */ + _generateCachedSprite: function () { + + this._cacheAsBitmap = false; + + var bounds = this.getLocalBounds(); + + // Round it off and force non-zero dimensions + bounds.width = Math.max(1, Math.ceil(bounds.width)); + bounds.height = Math.max(1, Math.ceil(bounds.height)); + + this.updateTransform(); + + if (!this._cachedSprite) + { + var textureUnit = 0; + if (this.texture && this.texture.baseTexture && PIXI._enableMultiTextureToggle) + { + textureUnit = this.texture.baseTexture.textureIndex; + } + var renderTexture = new Phaser.RenderTexture(this.game, bounds.width, bounds.height, undefined, undefined, undefined, undefined, textureUnit); + this._cachedSprite = new PIXI.Sprite(renderTexture); + this._cachedSprite.worldTransform = this.worldTransform; + } + else + { + this._cachedSprite.texture.resize(bounds.width, bounds.height); + } + + // Remove filters + var tempFilters = this._filters; + + this._filters = null; + this._cachedSprite.filters = tempFilters; + + PIXI.DisplayObject._tempMatrix.tx = -bounds.x; + PIXI.DisplayObject._tempMatrix.ty = -bounds.y; + this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true); + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + this._filters = tempFilters; + + this._cacheAsBitmap = true; + + }, + + /** + * Destroys a cached Sprite. + * + * @method PIXI.DisplayObject#_destroyCachedSprite + * @private + */ + _destroyCachedSprite: function () { + + if (!this._cachedSprite) + { + return; + } + + this._cachedSprite.texture.destroy(true); + + this._cachedSprite = null; + + } + +}; + +// Alias for updateTransform. As used in DisplayObject container, etc. +PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform; + +Object.defineProperties(PIXI.DisplayObject.prototype, { + + /** + * The horizontal position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#x + * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent. + */ + 'x': { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + } + + }, + + /** + * The vertical position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#y + * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent. + */ + 'y': { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + + }, + + /** + * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + * @name PIXI.DisplayObject#worldVisible + * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + */ + 'worldVisible': { + + get: function () { + + if (!this.visible) + { + return false; + } + else + { + var item = this.parent; + + if (!item) + { + return this.visible; + } + else + { + do + { + if (!item.visible) + { + return false; + } + + item = item.parent; + } + while (item); + + } + + return true; + } + + } + + }, + + /** + * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object. + * When applied it limits the visible area of this DisplayObject to the shape of the mask. + * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer. + * To remove a mask, set this property to `null`. + * + * @name PIXI.DisplayObject#mask + * @property {Phaser.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask. + */ + 'mask': { + + get: function () { + + return this._mask; + + }, + + set: function (value) { + + if (this._mask) + { + this._mask.isMask = false; + } + + this._mask = value; + + if (value) + { + this._mask.isMask = true; + } + + } + + }, + + /** + * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas + * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter + * using `DisplayObject.filterArea`. + * + * To remove filters, set this property to `null`. + * + * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a + * filter will reset this DisplayObjects blend mode to NORMAL. + * + * @name PIXI.DisplayObject#filters + * @property {Array} filters - An Array of Phaser.Filter objects, or objects that extend them. + */ + 'filters': { + + get: function () { + + return this._filters; + + }, + + set: function (value) { + + if (Array.isArray(value)) + { + // Put all the passes in one place. + var passes = []; + + for (var i = 0; i < value.length; i++) + { + var filterPasses = value[i].passes; + + for (var j = 0; j < filterPasses.length; j++) + { + passes.push(filterPasses[j]); + } + } + + // Needed any more? + this._filterBlock = { target: this, filterPasses: passes }; + } + + this._filters = value; + + if (this.blendMode && this.blendMode === PIXI.blendModes.MULTIPLY) + { + this.blendMode = PIXI.blendModes.NORMAL; + } + + } + + }, + + /** + * Sets if this DisplayObject should be cached as a bitmap. + * + * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it + * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a + * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not + * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`. + * + * To remove a cached bitmap, set this property to `null`. + * + * @name PIXI.DisplayObject#cacheAsBitmap + * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap. + */ + 'cacheAsBitmap': { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + if (this._cacheAsBitmap === value) + { + return; + } + + if (value) + { + this._generateCachedSprite(); + } + else + { + this._destroyCachedSprite(); + } + + this._cacheAsBitmap = value; + + } + + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A DisplayObjectContainer represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + * @class PIXI.DisplayObjectContainer + * @extends PIXI.DisplayObject + * @constructor + */ +PIXI.DisplayObjectContainer = function () { + + PIXI.DisplayObject.call(this); + + /** + * [read-only] The array of children of this container. + * + * @property children + * @type Array(DisplayObject) + * @readOnly + */ + this.children = []; + + /** + * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events. + * + * If this property is `true` then the children will _not_ be considered as valid for Input events. + * + * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. + * @property {boolean} ignoreChildInput + * @default + */ + this.ignoreChildInput = false; + +}; + +PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); +PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; + +/** + * Adds a child to the container. + * + * @method PIXI.DisplayObjectContainer#addChild + * @param child {DisplayObject} The DisplayObject to add to the container + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChild = function (child) { + + return this.addChildAt(child, this.children.length); + +}; + +/** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @method PIXI.DisplayObjectContainer#addChildAt + * @param child {DisplayObject} The child to add + * @param index {Number} The index to place the child in + * @return {DisplayObject} The child that was added. + */ +PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) { + + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + return child; + } + else + { + throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); + } + +}; + +/** + * Swaps the position of 2 Display Objects within this container. + * + * @method PIXI.DisplayObjectContainer#swapChildren + * @param child {DisplayObject} + * @param child2 {DisplayObject} + */ +PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) { + + if (child === child2) + { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(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; + +}; + +/** + * Returns the index position of a child DisplayObject instance + * + * @method PIXI.DisplayObjectContainer#getChildIndex + * @param child {DisplayObject} The DisplayObject instance to identify + * @return {Number} The index position of the child display object to identify + */ +PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + +}; + +/** + * Changes the position of an existing child in the display object container + * + * @method PIXI.DisplayObjectContainer#setChildIndex + * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number + * @param index {Number} The resulting index number for the child display object + */ +PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + this.children.splice(currentIndex, 1); //remove from old position + this.children.splice(index, 0, child); //add at new position + +}; + +/** + * Returns the child at the specified index + * + * @method PIXI.DisplayObjectContainer#getChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child at the given index, if any. + */ +PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller'); + } + + return this.children[index]; + +}; + +/** + * Removes a child from the container. + * + * @method PIXI.DisplayObjectContainer#removeChild + * @param child {DisplayObject} The DisplayObject to remove + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChild = function (child) { + + var index = this.children.indexOf(child); + + if (index === -1) + { + return; + } + + return this.removeChildAt(index); + +}; + +/** + * Removes a child from the specified index position. + * + * @method PIXI.DisplayObjectContainer#removeChildAt + * @param index {Number} The index to get the child from + * @return {DisplayObject} The child that was removed. + */ +PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) { + + var child = this.getChildAt(index); + + if (child) + { + child.parent = undefined; + + this.children.splice(index, 1); + } + + return child; + +}; + +/** +* Removes all children from this container that are within the begin and end indexes. +* +* @method PIXI.DisplayObjectContainer#removeChildren +* @param beginIndex {Number} The beginning position. Default value is 0. +* @param endIndex {Number} The ending position. Default value is size of the container. +*/ +PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { + + if (beginIndex === undefined) { beginIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var range = endIndex - beginIndex; + + if (range > 0 && range <= endIndex) + { + var removed = this.children.splice(beginIndex, range); + + for (var i = 0; i < removed.length; i++) + { + var child = removed[i]; + child.parent = undefined; + } + + return removed; + } + else if (range === 0 && this.children.length === 0) + { + return []; + } + else + { + throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' ); + } + +}; + +/* + * Updates the transform on all children of this container for rendering + * + * @method PIXI.DisplayObjectContainer#updateTransform + * @private + */ +PIXI.DisplayObjectContainer.prototype.updateTransform = function () { + + if (!this.visible) + { + return; + } + + this.displayObjectUpdateTransform(); + + if (this._cacheAsBitmap) + { + return; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +// performance increase to avoid using call.. (10x faster) +PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform; + +/** + * Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getBounds + * @param {PIXI.DisplayObject|Phaser.Matrix} [targetCoordinateSpace] Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpace) { + + var isTargetCoordinateSpaceDisplayObject = (targetCoordinateSpace && targetCoordinateSpace instanceof PIXI.DisplayObject); + var isTargetCoordinateSpaceThisOrParent = true; + + if (!isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace = this; + } + else if (targetCoordinateSpace instanceof PIXI.DisplayObjectContainer) + { + isTargetCoordinateSpaceThisOrParent = targetCoordinateSpace.contains(this); + } + else + { + isTargetCoordinateSpaceThisOrParent = false; + } + + var i; + + if (isTargetCoordinateSpaceDisplayObject) + { + var matrixCache = targetCoordinateSpace.worldTransform; + + targetCoordinateSpace.worldTransform = Phaser.identityMatrix; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + var minX = Infinity; + var minY = Infinity; + + var maxX = -Infinity; + var maxY = -Infinity; + + var childBounds; + var childMaxX; + var childMaxY; + + var childVisible = false; + + for (i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + childVisible = true; + + childBounds = this.children[i].getBounds(); + + minX = (minX < childBounds.x) ? minX : childBounds.x; + minY = (minY < childBounds.y) ? minY : childBounds.y; + + childMaxX = childBounds.width + childBounds.x; + childMaxY = childBounds.height + childBounds.y; + + maxX = (maxX > childMaxX) ? maxX : childMaxX; + maxY = (maxY > childMaxY) ? maxY : childMaxY; + } + + var bounds = this._bounds; + + if (!childVisible) + { + bounds = new PIXI.Rectangle(); + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + maxX = x1; + maxY = y1; + + minX = x1; + minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + } + + bounds.x = minX; + bounds.y = minY; + bounds.width = maxX - minX; + bounds.height = maxY - minY; + + if (isTargetCoordinateSpaceDisplayObject) + { + targetCoordinateSpace.worldTransform = matrixCache; + + for (i = 0; i < targetCoordinateSpace.children.length; i++) + { + targetCoordinateSpace.children[i].updateTransform(); + } + } + + if (!isTargetCoordinateSpaceThisOrParent) + { + var targetCoordinateSpaceBounds = targetCoordinateSpace.getBounds(); + + bounds.x -= targetCoordinateSpaceBounds.x; + bounds.y -= targetCoordinateSpaceBounds.y; + } + + return bounds; + +}; + +/** + * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration. + * + * @method PIXI.DisplayObjectContainer#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.DisplayObjectContainer.prototype.getLocalBounds = function () { + + return this.getBounds(this); + +}; + +/** +* Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. +* +* @method PIXI.DisplayObjectContainer#contains +* @param {DisplayObject} child +* @returns {boolean} +*/ +PIXI.DisplayObjectContainer.prototype.contains = function (child) { + + if (!child) + { + return false; + } + else if (child === this) + { + return true; + } + else + { + return this.contains(child.parent); + } +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.DisplayObjectContainer#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + var i; + + if (this._mask || this._filters) + { + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + renderSession.spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + renderSession.spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + renderSession.spriteBatch.start(); + } + + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + renderSession.spriteBatch.start(); + } + else + { + // simple render children! + for (i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.DisplayObjectContainer#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) { + + if (this.visible === false || this.alpha === 0) + { + return; + } + + if (this._cacheAsBitmap) + { + this._renderCachedSprite(renderSession); + return; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', { + + get: function() { + return this.getLocalBounds().width * this.scale.x; + }, + + set: function(value) { + + var width = this.getLocalBounds().width; + + if (width !== 0) + { + this.scale.x = value / width; + } + else + { + this.scale.x = 1; + } + + this._width = value; + } +}); + +/** + * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', { + + get: function() { + return this.getLocalBounds().height * this.scale.y; + }, + + set: function(value) { + + var height = this.getLocalBounds().height; + + if (height !== 0) + { + this.scale.y = value / height; + } + else + { + this.scale.y = 1; + } + + this._height = value; + } + +}); + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * @class PIXI.Sprite + * @extends PIXI.DisplayObjectContainer + * @constructor + * @param texture {Texture} The texture for this sprite + */ +PIXI.Sprite = function (texture) { + + PIXI.DisplayObjectContainer.call(this); + + /** + * The anchor sets the origin point of the texture. + * The default (0, 0) is the top left. + * (0.5, 0.5) is the center. + * (1, 1) is the bottom right. + * + * You can modify the default values in PIXI.Sprite.defaultAnchor. + * + * @property anchor + * @type Point + */ + this.anchor = new PIXI.Point(PIXI.Sprite.defaultAnchor.x, PIXI.Sprite.defaultAnchor.y); + + /** + * The texture that the sprite is using + * + * @property texture + * @type Texture + */ + this.texture = texture || PIXI.Texture.emptyTexture; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @property _width + * @type Number + * @private + */ + this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @property _height + * @type Number + * @private + */ + this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF (Phaser.Color.WHITE) will remove any tint effect. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @property cachedTint + * @private + * @type Number + * @default -1 + */ + this.cachedTint = -1; + + /** + * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this) + * + * @property tintedTexture + * @type Canvas + * @default null + */ + this.tintedTexture = null; + + /** + * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode. + * + * Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * The shader that will be used to render this Sprite. + * Set to null to remove a current shader. + * + * @property shader + * @type Phaser.Filter + * @default null + */ + this.shader = null; + + /** + * Controls if this Sprite is processed by the core Phaser game loops and Group loops (except {@link Phaser.Group#update}). + * + * @property exists + * @type Boolean + * @default true + */ + this.exists = true; + + if (this.texture.baseTexture.hasLoaded) + { + this.onTextureUpdate(); + } + + this.renderable = true; + +}; + +/** + * @property PIXI.Sprite.defaultAnchor - A Point-like object. + * @type {{x: number, y: number}} + * @default + */ +PIXI.Sprite.defaultAnchor = {x: 0, y: 0}; + +// constructor +PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +PIXI.Sprite.prototype.constructor = PIXI.Sprite; + +/** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'width', { + + get: function() { + return this.scale.x * this.texture.frame.width; + }, + + set: function(value) { + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ +Object.defineProperty(PIXI.Sprite.prototype, 'height', { + + get: function() { + return this.scale.y * this.texture.frame.height; + }, + + set: function(value) { + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +/** + * Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous + * texture this Sprite was using. + * + * @method PIXI.Sprite#setTexture + * @param texture {Texture} The PIXI texture that is displayed by the sprite + * @param [destroy=false] {boolean} Call Texture.destroy on the current texture before replacing it with the new one? + */ +PIXI.Sprite.prototype.setTexture = function(texture, destroyBase) +{ + if (destroyBase) + { + this.texture.baseTexture.destroy(); + } + + // Over-ridden by loadTexture as needed + this.texture.baseTexture.skipRender = false; + this.texture = texture; + this.texture.valid = true; + this.cachedTint = -1; +}; + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @method PIXI.Sprite#onTextureUpdate + * @param event + * @private + */ +PIXI.Sprite.prototype.onTextureUpdate = function() +{ + // so if _width is 0 then width was not set.. + if (this._width) this.scale.x = this._width / this.texture.frame.width; + if (this._height) this.scale.y = this._height / this.texture.frame.height; +}; + +/** +* Returns the bounds of the Sprite as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* It is important to note that the transform is not updated when you call this method. +* So if this Sprite is the child of a Display Object which has had its transform +* updated since the last render pass, those changes will not yet have been applied +* to this Sprites worldTransform. If you need to ensure that all parent transforms +* are factored into this getBounds operation then you should call `updateTransform` +* on the root most object in this Sprites display list first. +* +* @method PIXI.Sprite#getBounds +* @param matrix {Matrix} the transformation matrix of the sprite +* @return {Rectangle} the framing rectangle +*/ +PIXI.Sprite.prototype.getBounds = function(matrix) +{ + var width = this.texture.frame.width; + var height = this.texture.frame.height; + + var w0 = width * (1-this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1-this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + if (b === 0 && c === 0) + { + // scale may be negative! + if (a < 0) + { + a *= -1; + var temp = w0; + w0 = -w1; + w1 = -temp; + } + + if (d < 0) + { + d *= -1; + var temp = h0; + h0 = -h1; + h1 = -temp; + } + + // this means there is no rotation going on right? RIGHT? + // if thats the case then we can avoid checking the bound values! yay + minX = a * w1 + tx; + maxX = a * w0 + tx; + minY = d * h1 + ty; + maxY = d * h0 + ty; + } + else + { + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; +}; + +/** + * Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration. + * + * @method PIXI.Sprite#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +PIXI.Sprite.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method PIXI.Sprite#_renderWebGL +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix) +{ + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha <= 0 || !this.renderable) return; + + // They provided an alternative rendering matrix, so use it + var wt = this.worldTransform; + + if (matrix) + { + wt = matrix; + } + + // A quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) + { + var spriteBatch = renderSession.spriteBatch; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (this._filters) + { + spriteBatch.flush(); + renderSession.filterManager.pushFilter(this._filterBlock); + } + + if (this._mask) + { + spriteBatch.stop(); + renderSession.maskManager.pushMask(this.mask, renderSession); + spriteBatch.start(); + } + + // add this sprite to the batch + spriteBatch.render(this); + + // now loop through the children and make sure they get rendered + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + // time to stop the sprite batch as either a mask element or a filter draw will happen next + spriteBatch.stop(); + + if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession); + if (this._filters) renderSession.filterManager.popFilter(); + + spriteBatch.start(); + } + else + { + renderSession.spriteBatch.render(this); + + // Render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession, wt); + } + + } +}; + +/** +* Renders the object using the Canvas renderer +* +* @method PIXI.Sprite#_renderCanvas +* @param renderSession {RenderSession} +* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. +* @private +*/ +PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix) +{ + // If the sprite is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.alpha === 0 || !this.renderable || this.texture.crop.width <= 0 || this.texture.crop.height <= 0) + { + return; + } + + var wt = this.worldTransform; + + // If they provided an alternative rendering matrix then use it + if (matrix) + { + wt = matrix; + } + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + // Ignore null sources + if (!this.texture.valid) + { + // Update the children and leave + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + return; + } + + var resolution = this.texture.baseTexture.resolution / renderSession.resolution; + + renderSession.context.globalAlpha = this.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for this texture + if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode) + { + renderSession.scaleMode = this.texture.baseTexture.scaleMode; + renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + + // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions + var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width; + var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height; + + var tx = (wt.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (wt.ty * renderSession.resolution) + renderSession.shakeY; + + var cw = this.texture.crop.width; + var ch = this.texture.crop.height; + + if (this.texture.rotated) + { + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var e = cw; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + wt.a = a * 6.123233995736766e-17 + -c; + wt.b = b * 6.123233995736766e-17 + -d; + wt.c = a + c * 6.123233995736766e-17; + wt.d = b + d * 6.123233995736766e-17; + + // Update cropping dimensions. + cw = ch; + ch = e; + } + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx | 0, ty | 0); + dx |= 0; + dy |= 0; + } + else + { + renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + } + + dx /= resolution; + dy /= resolution; + + if (this.tint !== 0xFFFFFF) + { + if (this.texture.requiresReTint || this.cachedTint !== this.tint) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + } + + renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + else + { + var cx = this.texture.crop.x; + var cy = this.texture.crop.y; + + cw = Math.floor(cw) + ch = Math.floor(ch) + + renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @method PIXI.initDefaultShaders +* @static +* @private +*/ +PIXI.initDefaultShaders = function() +{ +}; + +/** +* @method PIXI.CompileVertexShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileVertexShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); +}; + +/** +* @method PIXI.CompileFragmentShader +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @return {Any} +*/ +PIXI.CompileFragmentShader = function(gl, shaderSrc) +{ + return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); +}; + +/** +* @method PIXI._CompileShader +* @static +* @private +* @param gl {WebGLContext} the current WebGL drawing context +* @param shaderSrc {Array} +* @param shaderType {Number} +* @return {Any} +*/ +PIXI._CompileShader = function(gl, shaderSrc, shaderType) +{ + var src = shaderSrc; + + if (Array.isArray(shaderSrc)) + { + 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; +}; + +/** +* @method PIXI.compileProgram +* @static +* @param gl {WebGLContext} the current WebGL drawing context +* @param vertexSrc {Array} +* @param fragmentSrc {Array} +* @return {Any} +*/ +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(gl.getProgramInfoLog(shaderProgram)); + window.console.log("Could not initialise shaders"); + } + + return shaderProgram; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + * @author Richard Davey http://www.photonstorm.com @photonstorm + */ + +/** +* @class PIXI.PixiShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PixiShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = null; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + /** + * A local flag + * @property firstRun + * @type Boolean + * @private + */ + this.firstRun = true; + + /** + * A dirty flag + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Uniform attributes cache. + * @property attributes + * @type Array + * @private + */ + this.attributes = []; + + this.init(); +}; + +PIXI.PixiShader.prototype.constructor = PIXI.PixiShader; + +PIXI.PixiShader.prototype.initMultitexShader = function () { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.fragmentSrc = [ + '// PixiShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}', + '}' + ]; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + //this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.uSamplerArray = gl.getUniformLocation(program, 'uSamplerArray[0]'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSamplerArray, indices); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; + +PIXI.PixiShader.prototype.initDefaultShader = function () { + + if (this.fragmentSrc === null) { + this.fragmentSrc = [ + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;', + '}' + ]; + } + + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = gl.getUniformLocation(program, 'uSampler'); + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its something to do with the current state of the gl context. + // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if(this.colorAttribute === -1) + { + this.colorAttribute = 2; + } + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute, this.aTextureIndex]; + + // End worst hack eva // + + // add those custom shaders! + for (var key in this.uniforms) + { + // get the uniform locations.. + this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); + } + + this.initUniforms(); + + this.program = program; +}; +/** +* Initialises the shader. +* +* @method PIXI.PixiShader#init +*/ +PIXI.PixiShader.prototype.init = function(usingFilter) +{ + if (PIXI._enableMultiTextureToggle && !usingFilter) { + this.initMultitexShader(); + } else { + this.initDefaultShader(); + } +}; + +/** +* Initialises the shader uniform values. +* +* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ +* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf +* +* @method PIXI.PixiShader#initUniforms +*/ +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') + { + // These require special handling + 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 + { + // GL function reference + 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; + } + } + } + +}; + +/** +* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) +* +* @method PIXI.PixiShader#initSampler2D +*/ +PIXI.PixiShader.prototype.initSampler2D = function(uniform) +{ + if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) + { + return; + } + + var gl = this.gl; + + // No need to do string manipulation for this. + gl.activeTexture(gl.TEXTURE0 + this.textureCount); + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + + // Extended texture data + if (uniform.textureData) + { + var data = uniform.textureData; + + // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); + // GLTextureLinear = mag/min linear, wrap clamp + // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat + // GLTextureNearest = mag/min nearest, wrap clamp + // AudioTexture = whatever + luminance + width 512, height 2, border 0 + // KeyTexture = whatever + luminance + width 256, height 2, border 0 + + // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + + 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; + + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels); + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null); + } + else + { + // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels); + 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++; + +}; + +/** +* Updates the shader uniform values. +* +* @method PIXI.PixiShader#syncUniforms +*/ +PIXI.PixiShader.prototype.syncUniforms = function() +{ + this.textureCount = 1; + var uniform; + var gl = this.gl; + + // This would probably be faster in an array and it would guarantee key order + 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]); + + if(uniform.value.baseTexture._dirty[gl.id]) + { + PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]); + } + + // 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); + } + } + } + +}; + +/** +* Destroys the shader. +* +* @method PIXI.PixiShader#destroy +*/ +PIXI.PixiShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** +* The Default Vertex shader source. +* +* @property defaultVertexSrc +* @type String +*/ +PIXI.PixiShader.defaultVertexSrc = [ + '// PixiShader Vertex Shader', + '// With multi-texture rendering', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute vec4 aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + + 'const vec2 center = vec2(-1.0, 1.0);', + + 'void main(void) {', + ' if (aTextureIndex > 0.0) gl_Position = vec4(0.0);', + ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);', + ' vTextureCoord = aTextureCoord;', + ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);', + ' vTextureIndex = aTextureIndex;', + '}' +]; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @class PIXI.PixiFastShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.PixiFastShader = function (gl) { + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + this.fragmentSrc = [ + '// PixiFastShader Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '// PixiFastShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aPositionCoord;', + 'attribute vec2 aScale;', + 'attribute float aRotation;', + 'attribute vec2 aTextureCoord;', + 'attribute float aColor;', + 'attribute float aTextureIndex;', + + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform mat3 uMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + 'varying float vTextureIndex;', + + '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;', + ' vTextureIndex = aTextureIndex;', + // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;', + ' vColor = aColor;', + '}' + ]; + + /** + * A local texture counter for multi-texture shaders. + * @property textureCount + * @type Number + */ + this.textureCount = 0; + + this.init(); +}; + +PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader; + +/** + * Initialises the shader. + * + * @method PIXI.PixiFastShader#init + */ +PIXI.PixiFastShader.prototype.init = function () { + + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.dimensions = gl.getUniformLocation(program, 'dimensions'); + this.uMatrix = gl.getUniformLocation(program, 'uMatrix'); + + // get and store the attributes + 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'); + + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + + // Begin worst hack eva // + + // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + // maybe its somthing to do with the current state of the gl context. + // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + // If theres any webGL people that know why could happen please help :) + if (this.colorAttribute === -1) { + this.colorAttribute = 2; + } + + this.attributes = [ + this.aVertexPosition, + this.aPositionCoord, + this.aScale, + this.aRotation, + this.aTextureCoord, + this.colorAttribute, + this.aTextureIndex + ]; + + // End worst hack eva // + + this.program = program; +}; + +/** + * Destroys the shader. + * + * @method PIXI.PixiFastShader#destroy + */ +PIXI.PixiFastShader.prototype.destroy = function () { + this.gl.deleteProgram(this.program); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.StripShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.StripShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + if (PIXI._enableMultiTextureToggle) { + var gl = this.gl; + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var dynamicIfs = '\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord);return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) + { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) { gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) ;return;}\n' + } + + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'bool isnan( float val ) { return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; }', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + // Blue color means that you are trying to bound + // a texture out of the limits of the hardware. + 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', + // If you get a red color means you are out of memory + // or in some way corrupted the vertex buffer. + 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', + 'void main(void) {', + dynamicIfs, + ' if(vTextureIndex >= ' + this.MAX_TEXTURES + '.0) { gl_FragColor = BLUE;return;}', + ' if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}', + '}' + ]; + } else { + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + '//StripShader Fragment Shader.', + 'precision mediump float;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // 'varying float vColor;', + 'uniform float alpha;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord);', + '}' + ]; + } + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + '//StripShader Vertex Shader.', + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute float aTextureIndex;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + // 'uniform float alpha;', + // 'uniform vec3 tint;', + 'varying vec2 vTextureCoord;', + 'varying float vTextureIndex;', + // '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);', + ' vTextureCoord = aTextureCoord;', + ' vTextureIndex = aTextureIndex;', + // ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.StripShader.prototype.constructor = PIXI.StripShader; + +/** +* Initialises the shader. +* +* @method PIXI.StripShader#init +*/ +PIXI.StripShader.prototype.init = function() +{ + var gl = this.gl; + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.uSampler = PIXI._enableMultiTextureToggle ? + gl.getUniformLocation(program, 'uSamplerArray[0]') : + gl.getUniformLocation(program, 'uSampler'); + + + if (PIXI._enableMultiTextureToggle) { + var indices = []; + // HACK: we bind an empty texture to avoid WebGL warning spam. + var tempTexture = gl.createTexture(); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, null); + for (var i = 0; i < this.MAX_TEXTURES; ++i) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, tempTexture); + indices.push(i); + } + gl.activeTexture(gl.TEXTURE0); + gl.uniform1iv(this.uSampler, indices); + } + + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.colorAttribute = gl.getAttribLocation(program, 'aColor'); + this.aTextureIndex = gl.getAttribLocation(program, 'aTextureIndex'); + //this.dimensions = gl.getUniformLocation(this.program, 'dimensions'); + + // get and store the attributes + this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); + this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord'); + + this.attributes = [this.aVertexPosition, this.aTextureCoord, this.aTextureIndex]; + + this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix'); + this.alpha = gl.getUniformLocation(program, 'alpha'); + + this.program = program; +}; + +/** +* Destroys the shader. +* +* @method PIXI.StripShader#destroy +*/ +PIXI.StripShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.PrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.PrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + 'precision mediump float;', + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + 'uniform float alpha;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.PrimitiveShader#init +*/ +PIXI.PrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.PrimitiveShader#destroy +*/ +PIXI.PrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attributes = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.ComplexPrimitiveShader +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.ComplexPrimitiveShader = function(gl) +{ + /** + * @property _UID + * @type Number + * @private + */ + this._UID = Phaser._UID++; + + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + + /** + * The WebGL program. + * @property program + * @type Any + */ + this.program = null; + + /** + * The fragment shader. + * @property fragmentSrc + * @type Array + */ + this.fragmentSrc = [ + + 'precision mediump float;', + + 'varying vec4 vColor;', + + 'void main(void) {', + ' gl_FragColor = vColor;', + '}' + ]; + + /** + * The vertex shader. + * @property vertexSrc + * @type Array + */ + this.vertexSrc = [ + 'attribute vec2 aVertexPosition;', + //'attribute vec4 aColor;', + 'uniform mat3 translationMatrix;', + 'uniform vec2 projectionVector;', + 'uniform vec2 offsetVector;', + + 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 color;', + 'uniform float flipY;', + '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 * -flipY) + flipY , 0.0, 1.0);', + ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);', + '}' + ]; + + this.init(); +}; + +PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader; + +/** +* Initialises the shader. +* +* @method PIXI.ComplexPrimitiveShader#init +*/ +PIXI.ComplexPrimitiveShader.prototype.init = function() +{ + var gl = this.gl; + + var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); + gl.useProgram(program); + + // get and store the uniforms for the shader + this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); + this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); + this.tintColor = gl.getUniformLocation(program, 'tint'); + this.color = gl.getUniformLocation(program, 'color'); + this.flipY = gl.getUniformLocation(program, 'flipY'); + + // get and store the attributes + 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; +}; + +/** +* Destroys the shader. +* +* @method PIXI.ComplexPrimitiveShader#destroy +*/ +PIXI.ComplexPrimitiveShader.prototype.destroy = function() +{ + this.gl.deleteProgram( this.program ); + this.uniforms = null; + this.gl = null; + + this.attribute = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +PIXI.glContexts = []; // this is where we store the webGL contexts for easy access. +PIXI.instances = []; +PIXI._enableMultiTextureToggle = false; + +/** + * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class PIXI.WebGLRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.WebGLRenderer = function(game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + this.extensions = {}; + + /** + * @property type + * @type Number + */ + this.type = Phaser.WEBGL; + + /** + * The resolution of the renderer + * + * @property resolution + * @type Number + * @default 1 + */ + this.resolution = game.resolution; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * + * @property preserveDrawingBuffer + * @type Boolean + */ + this.preserveDrawingBuffer = game.preserveDrawingBuffer; + + /** + * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true: + * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0). + * If the Stage is transparent, Pixi will clear to the target Stage's background color. + * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * The width of the canvas view + * + * @property width + * @type Number + */ + this.width = game.width; + + /** + * The height of the canvas view + * + * @property height + * @type Number + */ + this.height = game.height; + + /** + * The canvas element that everything is drawn to + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * @property _contextOptions + * @type Object + * @private + */ + this._contextOptions = { + alpha: this.transparent, + antialias: game.antialias, + failIfMajorPerformanceCaveat: config.failIfMajorPerformanceCaveat, + premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: this.preserveDrawingBuffer + }; + + /** + * @property projection + * @type Point + */ + this.projection = new PIXI.Point(); + + /** + * @property offset + * @type Point + */ + this.offset = new PIXI.Point(); + + // time to create the render managers! each one focuses on managing a state in webGL + + /** + * Deals with managing the shader programs and their attribs + * @property shaderManager + * @type WebGLShaderManager + */ + this.shaderManager = new PIXI.WebGLShaderManager(); + + /** + * Manages the rendering of sprites + * @property spriteBatch + * @type WebGLSpriteBatch + */ + this.spriteBatch = new PIXI.WebGLSpriteBatch(game); + + /** + * Manages the masks using the stencil buffer + * @property maskManager + * @type WebGLMaskManager + */ + this.maskManager = new PIXI.WebGLMaskManager(); + + /** + * Manages the filters + * @property filterManager + * @type WebGLFilterManager + */ + this.filterManager = new PIXI.WebGLFilterManager(); + + /** + * Manages the stencil buffer + * @property stencilManager + * @type WebGLStencilManager + */ + this.stencilManager = new PIXI.WebGLStencilManager(); + + /** + * Manages the blendModes + * @property blendModeManager + * @type WebGLBlendModeManager + */ + this.blendModeManager = new PIXI.WebGLBlendModeManager(); + + /** + * @property renderSession + * @type Object + */ + this.renderSession = {}; + + /** + * @property currentBatchedTextures + * @type Array + */ + this.currentBatchedTextures = []; + + // Needed? + this.renderSession.game = this.game; + this.renderSession.gl = this.gl; + this.renderSession.drawCount = 0; + this.renderSession.shaderManager = this.shaderManager; + this.renderSession.maskManager = this.maskManager; + this.renderSession.filterManager = this.filterManager; + this.renderSession.blendModeManager = this.blendModeManager; + this.renderSession.spriteBatch = this.spriteBatch; + this.renderSession.stencilManager = this.stencilManager; + this.renderSession.renderer = this; + this.renderSession.resolution = this.resolution; + this.renderSession.roundPixels = config.roundPixels || false; + this.renderSession.maxTextureAvailableSpace = null; // filled in setTexturePriority() + + // time init the context.. + this.initContext(); + + // map some webGL blend modes.. + this.mapBlendModes(); + +}; + +// constructor +PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer; + +/** +* @method PIXI.WebGLRenderer#initContext +*/ +PIXI.WebGLRenderer.prototype.initContext = function() +{ + var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); + + this.gl = gl; + + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + this.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.maxTextureSize = this.gl.getParameter(gl.MAX_TEXTURE_SIZE); + + this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++; + + PIXI.glContexts[this.glContextId] = gl; + + PIXI.instances[this.glContextId] = this; + + // set up the default pixi settings.. + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.CULL_FACE); + gl.enable(gl.BLEND); + + // need to set the context for all the managers... + this.shaderManager.setContext(gl); + this.spriteBatch.setContext(gl); + this.maskManager.setContext(gl); + this.filterManager.setContext(gl); + this.blendModeManager.setContext(gl); + this.stencilManager.setContext(gl); + + this.renderSession.gl = this.gl; + + // now resize and we are good to go! + this.resize(this.width, this.height); + + // Load WebGL extension + this.extensions.compression = {}; + + var etc1 = gl.getExtension('WEBGL_compressed_texture_etc1') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'); + var pvrtc = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); + var s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); + + if (etc1) { this.extensions.compression.ETC1 = etc1; } + if (pvrtc) { this.extensions.compression.PVRTC = pvrtc; } + if (s3tc) { this.extensions.compression.S3TC = s3tc; } +}; + +/** +* If Multi Texture support has been enabled, then calling this method will enable batching on the given +* textures. The texture collection is an array of keys, that map to Phaser.Cache image entries. +* +* The number of textures that can be batched is dependent on hardware. If you provide more textures +* than can be batched by the GPU, then only those at the start of the array will be used. Generally +* you shouldn't provide more than 16 textures to this method. You can check the hardware limit via the +* `maxTextures` property. +* +* You can also check the property `currentBatchedTextures` at any time, to see which textures are currently +* being batched. +* +* To stop all textures from being batched, call this method again with an empty array. +* +* To change the textures being batched, call this method with a new array of image keys. The old ones +* will all be purged out and no-longer batched, and the new ones enabled. +* +* Note: Throws a warning if you haven't enabled Multiple Texture batching support in the Phaser Game config. +* +* @method PIXI.WebGLRenderer#setTexturePriority +* @param textureNameCollection {Array} An Array of Texture Cache keys to use for multi-texture batching. +* @return {Array} An array containing the texture keys that were enabled for batching. +*/ +PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + if (!PIXI._enableMultiTextureToggle) + { + console.warn('setTexturePriority error: Multi Texture support hasn\'t been enabled in the Phaser Game Config.'); + return; + } + var clampPot = function (potSize) { + --potSize; + potSize |= potSize >> 1; + potSize |= potSize >> 2; + potSize |= potSize >> 4; + potSize |= potSize >> 8; + potSize |= potSize >> 16; + return ++potSize; + }; + var gl = this.gl; + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + var imageCache = this.game.cache._cache.image; + var imageName = null; + + // Clear out all previously batched textures and reset their flags. + // If the array has been modified, then the developer will have to + // deal with that in their own way. + for (var i = 0; i < this.currentBatchedTextures.length; i++) + { + imageName = this.currentBatchedTextures[i]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + + imageCache[imageName].base.textureIndex = 0; + } + var maxTextureAvailableSpace = (maxTextureSize) - clampPot(Math.max(this.width, this.height)); + this.currentBatchedTextures.length = 0; + // We start from 1 because framebuffer texture uses unit 0. + for (var j = 0; j < textureNameCollection.length; ++j) + { + imageName = textureNameCollection[j]; + + if (!(imageName in imageCache)) + { + console.warn('setTexturePriority: There is no image "%s" in the image cache.', imageName); + continue; + } + // Unit 0 is reserved for Pixi's framebuffer + var base = imageCache[imageName].base; + maxTextureAvailableSpace -= clampPot(Math.max(base.width, base.height)); + if (maxTextureAvailableSpace <= 0) { + base.textureIndex = 0; + console.warn('setTexturePriority: Image "%s" was given textureIndex=0 because there is no available texture space (%s).', + imageName, maxTextureAvailableSpace); + } else { + base.textureIndex = (1 + (j % (maxTextures - 1))); + } + this.currentBatchedTextures.push(imageName); + } + + this.renderSession.maxTextureAvailableSpace = maxTextureAvailableSpace; + + return this.currentBatchedTextures; + +}; + +/** + * Renders the stage to its webGL view + * + * @method PIXI.WebGLRenderer#render + * @param stage {Stage} the Stage element to be rendered + */ +PIXI.WebGLRenderer.prototype.render = function(stage) +{ + // no point rendering if our context has been blown up! + if (this.contextLost) + { + return; + } + + var gl = this.gl; + + // -- Does this need to be set every frame? -- // + gl.viewport(0, 0, this.width, this.height); + + // make sure we are bound to the main frame buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + if (this.game.clearBeforeRender) + { + gl.clearColor(stage._bgColor.r, stage._bgColor.g, stage._bgColor.b, stage._bgColor.a); + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + this.offset.x = this.game.camera._shake.x; + this.offset.y = this.game.camera._shake.y; + + this.renderDisplayObject(stage, this.projection); +}; + +/** + * Renders a Display Object. + * + * @method PIXI.WebGLRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The DisplayObject to render + * @param projection {Point} The projection + * @param buffer {Array} a standard WebGL buffer + */ +PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix) +{ + this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL); + + // reset the render session data.. + this.renderSession.drawCount = 0; + + // make sure to flip the Y if using a render texture.. + this.renderSession.flipY = buffer ? -1 : 1; + + // set the default projection + this.renderSession.projection = projection; + + //set the default offset + this.renderSession.offset = this.offset; + + // start the sprite batch + this.spriteBatch.begin(this.renderSession); + + // start the filter manager + this.filterManager.begin(this.renderSession, buffer); + + // render the scene! + displayObject._renderWebGL(this.renderSession, matrix); + + // finish the sprite batch + this.spriteBatch.end(); +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @method PIXI.WebGLRenderer#resize + * @param width {Number} the new width of the webGL view + * @param height {Number} the new height of the webGL view + */ +PIXI.WebGLRenderer.prototype.resize = function(width, height) +{ + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } + + this.gl.viewport(0, 0, this.width, this.height); + + this.projection.x = this.width / 2 / this.resolution; + this.projection.y = -this.height / 2 / this.resolution; +}; + +/** + * Updates and creates a WebGL compressed texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateCompressedTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateCompressedTexture = function (texture) { + if (!texture.hasLoaded) + { + return false; + } + var gl = this.gl; + var textureMetaData = texture.source; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + textureMetaData.glExtensionFormat, + textureMetaData.width, + textureMetaData.height, + 0, + textureMetaData.textureData + ); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + texture._dirty[gl.id] = false; + return true; +}; + +/** + * Updates and Creates a WebGL texture for the renderers context. + * + * @method PIXI.WebGLRenderer#updateTexture + * @param texture {Texture} the texture to update + * @return {boolean} True if the texture was successfully bound, otherwise false. + */ +PIXI.WebGLRenderer.prototype.updateTexture = function(texture) +{ + if (!texture.hasLoaded) + { + return false; + } + if (texture.source.compressionAlgorithm) { + return this.updateCompressedTexture(texture); + } + + var gl = this.gl; + + if (!texture._glTextures[gl.id]) + { + texture._glTextures[gl.id] = gl.createTexture(); + } + gl.activeTexture(gl.TEXTURE0 + texture.textureIndex); + + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha); + + 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); + + if (texture.mipmap && Phaser.Math.isPowerOfTwo(texture.width, texture.height)) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + gl.generateMipmap(gl.TEXTURE_2D); + } + else + { + 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); + } + + texture._dirty[gl.id] = false; + + // return texture._glTextures[gl.id]; + return true; + +}; + +/** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @method PIXI.WebGLRenderer#destroy + */ +PIXI.WebGLRenderer.prototype.destroy = function() +{ + 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; + + Phaser.CanvasPool.remove(this); + + PIXI.instances[this.glContextId] = null; + + PIXI.WebGLRenderer.glContextId--; +}; + +/** + * Maps Pixi blend modes to WebGL blend modes. + * + * @method PIXI.WebGLRenderer#mapBlendModes + */ +PIXI.WebGLRenderer.prototype.mapBlendModes = function() +{ + var gl = this.gl; + + if (!PIXI.blendModesWebGL) + { + var b = []; + var modes = PIXI.blendModes; + + b[modes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA]; + b[modes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SCREEN] = [gl.SRC_ALPHA, gl.ONE]; + b[modes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + b[modes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + PIXI.blendModesWebGL = b; + } +}; + +PIXI.WebGLRenderer.prototype.getMaxTextureUnit = function() { + var gl = this.gl; + return gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); +}; + +PIXI.enableMultiTexture = function() { + PIXI._enableMultiTextureToggle = true; +}; + +PIXI.WebGLRenderer.glContextId = 0; +PIXI.WebGLRenderer.textureArray = []; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLBlendModeManager +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLBlendModeManager = function() +{ + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 99999; +}; + +PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLBlendModeManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLBlendModeManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Sets-up the given blendMode from WebGL's point of view. +* +* @method PIXI.WebGLBlendModeManager#setBlendMode +* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD +*/ +PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode) +{ + if(this.currentBlendMode === blendMode)return false; + + this.currentBlendMode = blendMode; + + var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode]; + + if (blendModeWebGL) + { + this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLBlendModeManager#destroy +*/ +PIXI.WebGLBlendModeManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLMaskManager +* @constructor +* @private +*/ +PIXI.WebGLMaskManager = function() +{ +}; + +PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLMaskManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLMaskManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLMaskManager#pushMask +* @param maskData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession) +{ + var gl = renderSession.gl; + + if (maskData.dirty) + { + PIXI.WebGLGraphics.updateGraphics(maskData, gl); + } + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLMaskManager#popMask +* @param maskData {Array} +* @param renderSession {Object} an object containing all the useful parameters +*/ +PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession) +{ + var gl = this.gl; + + if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0) + { + return; + } + + renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); + +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLMaskManager#destroy +*/ +PIXI.WebGLMaskManager.prototype.destroy = function() +{ + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLStencilManager +* @constructor +* @private +*/ +PIXI.WebGLStencilManager = function() +{ + this.stencilStack = []; + this.reverse = true; + this.count = 0; +}; + +/** +* Sets the drawing context to the one given in parameter. +* +* @method PIXI.WebGLStencilManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLStencilManager.prototype.setContext = function(gl) +{ + this.gl = gl; +}; + +/** +* Applies the Mask and adds it to the current filter stack. +* +* @method PIXI.WebGLStencilManager#pushMask +* @param graphics {Graphics} +* @param webGLData {Array} +* @param renderSession {Object} +*/ +PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.bindGraphics(graphics, webGLData, renderSession); + + if(this.stencilStack.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + this.reverse = true; + this.count = 0; + } + + this.stencilStack.push(webGLData); + + var level = this.count; + + gl.colorMask(false, false, false, false); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + + if(webGLData.mode === 1) + { + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + + this.reverse = !this.reverse; + } + else + { + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + this.count++; +}; + +/** + * TODO this does not belong here! + * + * @method PIXI.WebGLStencilManager#bindGraphics + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession) +{ + //if(this._currentGraphics === graphics)return; + this._currentGraphics = graphics; + + var gl = this.gl; + + // bind the graphics object.. + var projection = renderSession.projection, + offset = renderSession.offset, + shader;// = renderSession.shaderManager.primitiveShader; + + if(webGLData.mode === 1) + { + shader = renderSession.shaderManager.complexPrimitiveShader; + + renderSession.shaderManager.setShader( shader ); + + gl.uniform1f(shader.flipY, renderSession.flipY); + + 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, Phaser.Color.hexToRGBArray(graphics.tint)); + gl.uniform3fv(shader.color, webGLData.color); + + gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0); + + + // now do the rest.. + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } + else + { + //renderSession.shaderManager.activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + renderSession.shaderManager.setShader( shader ); + + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, renderSession.flipY); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + } +}; + +/** + * @method PIXI.WebGLStencilManager#popStencil + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ +PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession) +{ + var gl = this.gl; + this.stencilStack.pop(); + + this.count--; + + if(this.stencilStack.length === 0) + { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + + } + else + { + + var level = this.count; + + this.bindGraphics(graphics, webGLData, renderSession); + + gl.colorMask(false, false, false, false); + + if(webGLData.mode === 1) + { + this.reverse = !this.reverse; + + if(this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + // draw a quad to increment.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + gl.stencilFunc(gl.ALWAYS,0,0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT); + + // draw the triangle strip! + gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + + } + else + { + // console.log("<<>>") + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + } + else + { + gl.stencilFunc(gl.EQUAL,level+1, 0xFF); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + } + + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + + if(!this.reverse) + { + gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF); + } + else + { + gl.stencilFunc(gl.EQUAL,level, 0xFF); + } + } + + gl.colorMask(true, true, true, true); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + + + } +}; + +/** +* Destroys the mask stack. +* +* @method PIXI.WebGLStencilManager#destroy +*/ +PIXI.WebGLStencilManager.prototype.destroy = function() +{ + this.stencilStack = null; + this.gl = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLShaderManager +* @constructor +* @private +*/ +PIXI.WebGLShaderManager = function() +{ + /** + * @property maxAttibs + * @type Number + */ + this.maxAttibs = 10; + + /** + * @property attribState + * @type Array + */ + this.attribState = []; + + /** + * @property tempAttribState + * @type Array + */ + this.tempAttribState = []; + + for (var i = 0; i < this.maxAttibs; i++) + { + this.attribState[i] = false; + } + + /** + * @property stack + * @type Array + */ + this.stack = []; + +}; + +PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLShaderManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLShaderManager.prototype.setContext = function(gl) +{ + this.gl = gl; + + // the next one is used for rendering primitives + this.primitiveShader = new PIXI.PrimitiveShader(gl); + + // the next one is used for rendering triangle strips + this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl); + + // this shader is used for the default sprite rendering + this.defaultShader = new PIXI.PixiShader(gl); + + // this shader is used for the fast sprite rendering + this.fastShader = new PIXI.PixiFastShader(gl); + + // the next one is used for rendering triangle strips + this.stripShader = new PIXI.StripShader(gl); + + // the next one is used for rendering creature meshes + this.creatureShader = PIXI.CreatureShader ? new PIXI.CreatureShader(gl) : null; + + this.setShader(this.defaultShader); +}; + +/** +* Takes the attributes given in parameters. +* +* @method PIXI.WebGLShaderManager#setAttribs +* @param attribs {Array} attribs +*/ +PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs) +{ + // reset temp state + var i; + + for (i = 0; i < this.tempAttribState.length; i++) + { + this.tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + var attribId = attribs[i]; + this.tempAttribState[attribId] = true; + } + + var gl = this.gl; + + for (i = 0; i < this.attribState.length; i++) + { + if(this.attribState[i] !== this.tempAttribState[i]) + { + this.attribState[i] = this.tempAttribState[i]; + + if(this.tempAttribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } +}; + +/** +* Sets the current shader. +* +* @method PIXI.WebGLShaderManager#setShader +* @param shader {Any} +*/ +PIXI.WebGLShaderManager.prototype.setShader = function(shader) +{ + if(this._currentId === shader._UID)return false; + + this._currentId = shader._UID; + + this.currentShader = shader; + + this.gl.useProgram(shader.program); + this.setAttribs(shader.attributes); + + return true; +}; + +/** +* Destroys this object. +* +* @method PIXI.WebGLShaderManager#destroy +*/ +PIXI.WebGLShaderManager.prototype.destroy = function() +{ + this.attribState = null; + + this.tempAttribState = null; + + this.primitiveShader.destroy(); + + this.complexPrimitiveShader.destroy(); + + this.defaultShader.destroy(); + + this.fastShader.destroy(); + + this.stripShader.destroy(); + + if (this.creatureShader) { + this.creatureShader.destroy(); + } + + this.gl = null; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** + * + * @class PIXI.WebGLSpriteBatch + * @private + * @constructor + */ +PIXI.WebGLSpriteBatch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 5; + + /** + * The number of images in the SpriteBatch before it flushes + * @property size + * @type Number + */ + this.size = 2000; //Math.pow(2, 16) / this.vertSize; + + //the total number of bytes in our batch + // Including texture index: + // position + uv + color + textureIndex + // vec2 + vec2 + (char * 4) + float + this.vertexSize = (4 * 2) + (4 * 2) + (4) + (4); + var numVerts = this.vertexSize * this.size * 4; + //this.size * 4 * 4 * this.vertSize; + //the total number of indices in our batch + var numIndices = this.size * 6; + + /** + * Holds the vertices + * + * @property vertices + * @type ArrayBuffer + */ + this.vertices = new ArrayBuffer(numVerts); + + /** + * View on the vertices as a Float32Array + * + * @property positions + * @type Float32Array + */ + this.positions = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array + * + * @property colors + * @type Uint32Array + */ + this.colors = new Uint32Array(this.vertices); + + /** + * Holds the indices + * + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * @property textures + * @type Array + */ + this.textures = []; + + /** + * @property blendModes + * @type Array + */ + this.blendModes = []; + + /** + * @property shaders + * @type Array + */ + this.shaders = []; + + /** + * @property sprites + * @type Array + */ + this.sprites = []; + + /** + * @property defaultShader + * @type Phaser.Filter + */ + this.defaultShader = null; +}; + +/** + * @method PIXI.WebGLSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLSpriteBatch.prototype.setContext = function (gl) { + this.MAX_TEXTURES = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.gl = gl; + if (PIXI._enableMultiTextureToggle) { + var dynamicIfs = '\tif (vTextureIndex == 0.0) {gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n' + for (var index = 1; index < this.MAX_TEXTURES; ++index) { + dynamicIfs += '\tif (vTextureIndex == ' + + index + '.0) {gl_FragColor = texture2D(uSamplerArray[' + + index + '], vTextureCoord) * vColor;return;}\n' + } + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', + 'void main(void) {', + dynamicIfs, + '\tgl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;', + '}' + ]); + } + else + { + this.defaultShader = new Phaser.Filter( + this.game, + undefined, + [ + '//WebGLSpriteBatch Fragment Shader.', + 'precision lowp float;', + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureIndex;', + 'uniform sampler2D uSampler;', + 'void main(void) {', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', + '}' + ]); + } + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + this.currentBlendMode = 99999; + + var shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = this.defaultShader.fragmentSrc; + shader.uniforms = {}; + shader.init(); + + this.defaultShader.shaders[gl.id] = shader; +}; + +/** + * @method PIXI.WebGLSpriteBatch#begin + * @param renderSession {Object} The RenderSession object + */ +PIXI.WebGLSpriteBatch.prototype.begin = function (renderSession) { + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.defaultShader; + + this.start(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#end + */ +PIXI.WebGLSpriteBatch.prototype.end = function () { + this.flush(); +}; + +/** + * @method PIXI.WebGLSpriteBatch#render + * @param sprite {Sprite} the sprite to render when using this spritebatch + * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. + */ +PIXI.WebGLSpriteBatch.prototype.render = function (sprite, matrix) { + var texture = sprite.texture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + if (PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + baseTexture.textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[baseTexture.textureIndex] = baseTexture; + } + + // They provided an alternative rendering matrix, so use it + var wt = sprite.worldTransform; + + if (matrix) { + wt = matrix; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // get the uvs for the texture + var uvs = texture._uvs; + + // if the uvs have not updated then no point rendering just yet! + if (!uvs) { + return; + } + + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + + var w0, w1, h0, h1; + + if (texture.trim) { + // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords. + var trim = texture.trim; + + w1 = trim.x - aX * trim.width; + w0 = w1 + texture.crop.width; + + h1 = trim.y - aY * trim.height; + h0 = h1 + texture.crop.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 i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + var tiOffset = this.currentBatchSize * 4; + var resolution = texture.baseTexture.resolution; + var textureIndex = texture.baseTexture.textureIndex; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + + var cw = texture.crop.width; + var ch = texture.crop.height; + + if (texture.rotated) + { + var a0 = wt.a; + var b0 = wt.b; + var c0 = wt.c; + var d0 = wt.d; + var _w1 = w1; + var _w0 = w0; + + // Offset before rotating + tx = wt.c * ch + tx; + ty = wt.d * ch + ty; + + // Rotate matrix by 90 degrees + // We use precalculated values for sine and cosine of rad(90) + a = a0 * 6.123233995736766e-17 + -c0; + b = b0 * 6.123233995736766e-17 + -d0; + c = a0 + c0 * 6.123233995736766e-17; + d = b0 + d0 * 6.123233995736766e-17; + + // Update UV coordinates + texture._updateUvsInverted(); + + // Rotate dimensions + w0 = h0; + w1 = h1; + h0 = _w0; + h1 = _w1; + } + + var colors = this.colors; + var positions = this.positions; + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + if (this.renderSession.roundPixels) { + positions[i++] = a * w1 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w1 + ty | 0; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx | 0; + positions[i++] = d * h1 + b * w0 + ty | 0; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w0 + ty | 0; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx | 0; + positions[i++] = d * h0 + b * w1 + ty | 0; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } else { + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h1 + tx; + positions[i++] = d * h1 + b * w0 + ty; + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + colors[i++] = color; + positions[i++] = textureIndex; + + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + colors[i++] = color; + positions[i++] = textureIndex; + } + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders a TilingSprite using the spriteBatch. + * + * @method PIXI.WebGLSpriteBatch#renderTilingSprite + * @param sprite {TilingSprite} the sprite to render + */ +PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function (sprite) { + var texture = sprite.tilingTexture; + var baseTexture = texture.baseTexture; + var gl = this.gl; + var textureIndex = sprite.texture.baseTexture.textureIndex; + if (PIXI.WebGLRenderer.textureArray[textureIndex] != baseTexture) { + this.flush(); + gl.activeTexture(gl.TEXTURE0 + textureIndex); + gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); + PIXI.WebGLRenderer.textureArray[textureIndex] = baseTexture; + } + + // check texture.. + if (this.currentBatchSize >= this.size) { + this.flush(); + this.currentBaseTexture = texture.baseTexture; + } + + // set the textures uvs temporarily + if (!sprite._uvs) { + sprite._uvs = new PIXI.TextureUvs(); + } + + var uvs = sprite._uvs; + + var w = texture.baseTexture.width; + var h = texture.baseTexture.height; + + // var w = sprite._frame.sourceSizeW; + // var h = sprite._frame.sourceSizeH; + + // w = 16; + // h = 16; + + sprite.tilePosition.x %= w * sprite.tileScaleOffset.x; + sprite.tilePosition.y %= h * sprite.tileScaleOffset.y; + + var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x); + var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y); + + var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x); + var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.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; + + // Get the sprites current alpha and tint and combine them into a single color + var tint = sprite.tint; + var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24); + + var positions = this.positions; + var colors = this.colors; + + var width = sprite.width; + var height = sprite.height; + + // TODO trim?? + var aX = sprite.anchor.x; + var aY = sprite.anchor.y; + var w0 = width * (1 - aX); + var w1 = width * -aX; + + var h0 = height * (1 - aY); + var h1 = height * -aY; + + var i = this.currentBatchSize * this.vertexSize; //4 * this.vertSize; + + var resolution = texture.baseTexture.resolution; + + var wt = sprite.worldTransform; + + var a = wt.a / resolution; + var b = wt.b / resolution; + var c = wt.c / resolution; + var d = wt.d / resolution; + var tx = wt.tx; + var ty = wt.ty; + // xy + positions[i++] = a * w1 + c * h1 + tx; + positions[i++] = d * h1 + b * w1 + ty; + // uv + positions[i++] = uvs.x0; + positions[i++] = uvs.y0; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = (a * w0 + c * h1 + tx); + positions[i++] = d * h1 + b * w0 + ty; + // uv + positions[i++] = uvs.x1; + positions[i++] = uvs.y1; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w0 + c * h0 + tx; + positions[i++] = d * h0 + b * w0 + ty; + // uv + positions[i++] = uvs.x2; + positions[i++] = uvs.y2; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // xy + positions[i++] = a * w1 + c * h0 + tx; + positions[i++] = d * h0 + b * w1 + ty; + // uv + positions[i++] = uvs.x3; + positions[i++] = uvs.y3; + // color + colors[i++] = color; + // texture index + positions[i++] = textureIndex; + + // increment the batchsize + this.sprites[this.currentBatchSize++] = sprite; +}; + +/** + * Renders the content and empties the current batch. + * + * @method PIXI.WebGLSpriteBatch#flush + */ +PIXI.WebGLSpriteBatch.prototype.flush = function () { + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize === 0) { + return; + } + + var gl = this.gl; + var shader; + + if (this.dirty) { + this.dirty = false; + + shader = this.defaultShader.shaders[gl.id]; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + // this is the same for each shader? + var stride = this.vertexSize; //this.vertSize * 4; + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 8); + + // color attributes will be interpreted as unsigned bytes and normalized + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 16); + + // Texture index + gl.vertexAttribPointer(shader.aTextureIndex, 1, gl.FLOAT, false, stride, 20); + } + + // upload the verts to the buffer + if (this.currentBatchSize > (this.size * 0.5)) { + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + } else { + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + var view = this.positions.subarray(0, this.currentBatchSize * this.vertexSize); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, view); + } + + var nextTexture, nextBlendMode, nextShader; + var batchSize = 0; + var start = 0; + + var currentBaseTexture = null; + var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode; + var currentShader = null; + + var blendSwap = false; + var shaderSwap = false; + var sprite; + var textureIndex = 0; + + for (var i = 0, j = this.currentBatchSize; i < j; i++) { + + sprite = this.sprites[i]; + + if (sprite.tilingTexture) { + nextTexture = sprite.tilingTexture.baseTexture; + } else { + nextTexture = sprite.texture.baseTexture; + } + + nextBlendMode = sprite.blendMode; + nextShader = sprite.shader || this.defaultShader; + + blendSwap = currentBlendMode !== nextBlendMode; + shaderSwap = currentShader !== nextShader; // should I use _UIDS??? + + var skip = nextTexture.skipRender; + + if (skip && sprite.children.length > 0) { + skip = false; + } + // + if (/*(currentBaseTexture != nextTexture && !skip) ||*/ + blendSwap || + shaderSwap) { + this.renderBatch(currentBaseTexture, batchSize, start); + + start = i; + batchSize = 0; + currentBaseTexture = nextTexture; + + if (blendSwap) { + currentBlendMode = nextBlendMode; + this.renderSession.blendModeManager.setBlendMode(currentBlendMode); + } + + if (shaderSwap) { + currentShader = nextShader; + + shader = currentShader.shaders[gl.id]; + + if (!shader) { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = currentShader.fragmentSrc; + shader.uniforms = currentShader.uniforms; + shader.init(); + + currentShader.shaders[gl.id] = shader; + } + + // set shader function??? + this.renderSession.shaderManager.setShader(shader); + + if (shader.dirty) { + shader.syncUniforms(); + } + + // both these only need to be set if they are changing.. + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(shader.projectionVector, projection.x, projection.y); + + // TODO - this is temporary! + var offsetVector = this.renderSession.offset; + gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y); + + // set the pointers + } + } + + batchSize++; + } + + this.renderBatch(currentBaseTexture, batchSize, start); + + // then reset the batch! + this.currentBatchSize = 0; +}; + +/** + * @method PIXI.WebGLSpriteBatch#renderBatch + * @param texture {Texture} + * @param size {Number} + * @param startIndex {Number} + */ +PIXI.WebGLSpriteBatch.prototype.renderBatch = function (texture, size, startIndex) { + if (size === 0) { + return; + } + + var gl = this.gl; + + // check if a texture is dirty.. + if (texture._dirty[gl.id]) { + if (!this.renderSession.renderer.updateTexture(texture)) { + // If updateTexture returns false then we cannot render it, so bail out now + return; + } + }else { + gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); + } + + gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2); + // increment the draw count + this.renderSession.drawCount++; +}; + +/** + * @method PIXI.WebGLSpriteBatch#stop + */ +PIXI.WebGLSpriteBatch.prototype.stop = function () { + this.flush(); + this.dirty = true; +}; + +/** + * @method PIXI.WebGLSpriteBatch#start + */ +PIXI.WebGLSpriteBatch.prototype.start = function () { + this.dirty = true; +}; + +/** + * Destroys the SpriteBatch. + * + * @method PIXI.WebGLSpriteBatch#destroy + */ +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; +}; + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * + * Heavily inspired by LibGDX's WebGLSpriteBatch: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java + */ + +/** +* @class PIXI.WebGLFastSpriteBatch +* @constructor +*/ +PIXI.WebGLFastSpriteBatch = function(gl) +{ + + /** + * @property vertSize + * @type Number + */ + this.vertSize = 11; + + /** + * @property maxSize + * @type Number + */ + this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize; + + /** + * @property size + * @type Number + */ + this.size = this.maxSize; + + //the total number of floats in our batch + var numVerts = this.size * 4 * this.vertSize; + + //the total number of indices in our batch + var numIndices = this.maxSize * 6; + + /** + * Vertex data + * @property vertices + * @type Float32Array + */ + this.vertices = new Float32Array(numVerts); + + /** + * Index data + * @property indices + * @type Uint16Array + */ + this.indices = new Uint16Array(numIndices); + + /** + * @property vertexBuffer + * @type Object + */ + this.vertexBuffer = null; + + /** + * @property indexBuffer + * @type Object + */ + this.indexBuffer = null; + + /** + * @property lastIndexCount + * @type Number + */ + this.lastIndexCount = 0; + + for (var i=0, j=0; i < numIndices; i += 6, j += 4) + { + this.indices[i + 0] = j + 0; + this.indices[i + 1] = j + 1; + this.indices[i + 2] = j + 2; + this.indices[i + 3] = j + 0; + this.indices[i + 4] = j + 2; + this.indices[i + 5] = j + 3; + } + + /** + * @property drawing + * @type Boolean + */ + this.drawing = false; + + /** + * @property currentBatchSize + * @type Number + */ + this.currentBatchSize = 0; + + /** + * @property currentBaseTexture + * @type BaseTexture + */ + this.currentBaseTexture = null; + + /** + * @property currentBlendMode + * @type Number + */ + this.currentBlendMode = 0; + + /** + * @property renderSession + * @type Object + */ + this.renderSession = null; + + /** + * @property shader + * @type Object + */ + this.shader = null; + + /** + * @property matrix + * @type Matrix + */ + this.matrix = null; + + this.setContext(gl); +}; + +PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch; + +/** + * Sets the WebGL Context. + * + * @method PIXI.WebGLFastSpriteBatch#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl) +{ + this.gl = gl; + + // create a couple of buffers + this.vertexBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // 65535 is max index, so 65535 / 6 = 10922. + + //upload the index data + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#begin + * @param spriteBatch {WebGLSpriteBatch} + * @param renderSession {Object} + */ +PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession) +{ + this.renderSession = renderSession; + this.shader = this.renderSession.shaderManager.fastShader; + + this.matrix = spriteBatch.worldTransform.toArray(true); + + this.start(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#end + */ +PIXI.WebGLFastSpriteBatch.prototype.end = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#render + * @param spriteBatch {WebGLSpriteBatch} + */ +PIXI.WebGLFastSpriteBatch.prototype.render = function (spriteBatch) +{ + var children = spriteBatch.children; + var sprite = children[0]; + + // if the uvs have not updated then no point rendering just yet! + + // check texture. + if(!sprite.texture._uvs)return; + + this.currentBaseTexture = sprite.texture.baseTexture; + + // check blend mode + if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode) + { + this.flush(); + this.renderSession.blendModeManager.setBlendMode(sprite.blendMode); + } + + for(var i=0,j= children.length; i= this.size) + { + this.flush(); + } +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#flush + */ +PIXI.WebGLFastSpriteBatch.prototype.flush = function() +{ + // If the batch is length 0 then return as there is nothing to draw + if (this.currentBatchSize===0)return; + + var gl = this.gl; + + // bind the current texture + + if(!this.currentBaseTexture._glTextures[gl.id]) { + this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl); + return; + } + + //gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]); + + // upload the verts to the buffer + + if(this.currentBatchSize > ( this.size * 0.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); + } + + // now draw those suckas! + gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0); + + // then reset the batch! + this.currentBatchSize = 0; + + // increment the draw count + this.renderSession.drawCount++; + +}; + + +/** + * @method PIXI.WebGLFastSpriteBatch#stop + */ +PIXI.WebGLFastSpriteBatch.prototype.stop = function() +{ + this.flush(); +}; + +/** + * @method PIXI.WebGLFastSpriteBatch#start + */ +PIXI.WebGLFastSpriteBatch.prototype.start = function() +{ + var gl = this.gl; + + // bind the main texture + gl.activeTexture(gl.TEXTURE0); + + // bind the buffers + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // set the projection + var projection = this.renderSession.projection; + gl.uniform2f(this.shader.projectionVector, projection.x, projection.y); + + // set the matrix + gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix); + + // set the pointers + 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); + gl.vertexAttribPointer(this.shader.aTextureIndex, 1, gl.FLOAT, false, stride, 10 * 4); + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** +* @class PIXI.WebGLFilterManager +* @constructor +*/ +PIXI.WebGLFilterManager = function() +{ + /** + * @property filterStack + * @type Array + */ + this.filterStack = []; + + /** + * @property offsetX + * @type Number + */ + this.offsetX = 0; + + /** + * @property offsetY + * @type Number + */ + this.offsetY = 0; +}; + +PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager; + +/** +* Initialises the context and the properties. +* +* @method PIXI.WebGLFilterManager#setContext +* @param gl {WebGLContext} the current WebGL drawing context +*/ +PIXI.WebGLFilterManager.prototype.setContext = function(gl) +{ + this.gl = gl; + this.texturePool = []; + + this.initShaderBuffers(); +}; + +/** +* @method PIXI.WebGLFilterManager#begin +* @param renderSession {RenderSession} +* @param buffer {ArrayBuffer} +*/ +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; +}; + +/** +* Applies the filter and adds it to the current filter stack. +* +* @method PIXI.WebGLFilterManager#pushFilter +* @param filterBlock {Object} the filter that will be pushed to the current filter stack +*/ +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(); + + // >>> modify by nextht + filterBlock._previous_stencil_mgr = this.renderSession.stencilManager; + this.renderSession.stencilManager = new PIXI.WebGLStencilManager(); + this.renderSession.stencilManager.setContext(gl); + gl.disable(gl.STENCIL_TEST); + // <<< modify by nextht + + // filter program + // OPTIMISATION - the first filter is free if its a simple color change? + 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.renderSession.resolution, this.height * this.renderSession.resolution); + } + else + { + texture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + } + + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea; + + var padding = filter.padding; + filterArea.x -= padding; + filterArea.y -= padding; + filterArea.width += padding * 2; + filterArea.height += padding * 2; + + // cap filter to screen size.. + 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer); + + // set view port + gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + projection.x = filterArea.width/2; + projection.y = -filterArea.height/2; + + offset.x = -filterArea.x; + offset.y = -filterArea.y; + + // update projection + // now restore the regular shader.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + //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; + +}; + +/** +* Removes the last filter from the filter stack and doesn't return it. +* +* @method PIXI.WebGLFilterManager#popFilter +*/ +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 * this.renderSession.resolution, filterArea.height * this.renderSession.resolution); + + 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); + // now set the uvs.. + 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.renderSession.resolution, this.height * this.renderSession.resolution); + outputTexture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution); + + // need to clear this FBO as it may have some left over elements from a previous filter. + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + gl.clear(gl.COLOR_BUFFER_BIT); + + gl.disable(gl.BLEND); + + for (var i = 0; i < filterBlock.filterPasses.length-1; i++) + { + var filterPass = filterBlock.filterPasses[i]; + + gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture); + + // draw texture.. + //filterPass.applyFilterPass(filterArea.width, filterArea.height); + this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height); + + // swap the textures.. + var temp = inputTexture; + inputTexture = outputTexture; + outputTexture = temp; + } + + gl.enable(gl.BLEND); + + texture = inputTexture; + this.texturePool.push(outputTexture); + } + + var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1]; + + this.offsetX -= filterArea.x; + this.offsetY -= filterArea.y; + + var sizeX = this.width; + var sizeY = this.height; + + var offsetX = 0; + var offsetY = 0; + + var buffer = this.buffer; + + // time to render the filters texture to the previous scene + if(this.filterStack.length === 0) + { + gl.colorMask(true, true, true, true);//this.transparent); + } + else + { + var currentFilter = this.filterStack[this.filterStack.length-1]; + filterArea = currentFilter._filterArea; + + sizeX = filterArea.width; + sizeY = filterArea.height; + + offsetX = filterArea.x; + offsetY = filterArea.y; + + buffer = currentFilter._glFilterTexture.frameBuffer; + } + + // TODO need to remove these global elements.. + projection.x = sizeX/2; + projection.y = -sizeY/2; + + offset.x = offsetX; + offset.y = offsetY; + + filterArea = filterBlock._filterArea; + + var x = filterArea.x-offsetX; + var y = filterArea.y-offsetY; + + // update the buffers.. + // make sure to flip the y! + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + + this.vertexArray[0] = x; + this.vertexArray[1] = y + filterArea.height; + + this.vertexArray[2] = x + filterArea.width; + this.vertexArray[3] = y + filterArea.height; + + this.vertexArray[4] = x; + this.vertexArray[5] = y; + + this.vertexArray[6] = x + filterArea.width; + this.vertexArray[7] = y; + + 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); + + gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution); + + // bind the buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, buffer ); + + // set the blend mode! + //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + + // set texture + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + + // >>> modify by nextht + if (this.renderSession.stencilManager) { + this.renderSession.stencilManager.destroy(); + } + this.renderSession.stencilManager = filterBlock._previous_stencil_mgr; + filterBlock._previous_stencil_mgr = null; + if (this.renderSession.stencilManager.count > 0) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + // <<< modify by nextht + + // apply! + this.applyFilterPass(filter, filterArea, sizeX, sizeY); + + // now restore the regular shader.. should happen automatically now.. + // this.renderSession.shaderManager.setShader(this.defaultShader); + // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2); + // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY); + + // return the texture to the pool + this.texturePool.push(texture); + filterBlock._glFilterTexture = null; +}; + + +/** +* Applies the filter to the specified area. +* +* @method PIXI.WebGLFilterManager#applyFilterPass +* @param filter {Phaser.Filter} the filter that needs to be applied +* @param filterArea {Texture} TODO - might need an update +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +*/ +PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height) +{ + // use program + var gl = this.gl; + var shader = filter.shaders[gl.id]; + + if(!shader) + { + shader = new PIXI.PixiShader(gl); + + shader.fragmentSrc = filter.fragmentSrc; + shader.uniforms = filter.uniforms; + shader.init(true); + + filter.shaders[gl.id] = shader; + } + + // set the shader + this.renderSession.shaderManager.setShader(shader); + +// gl.useProgram(shader.program); + + gl.uniform2f(shader.projectionVector, width/2, -height/2); + gl.uniform2f(shader.offsetVector, 0,0); + + if(filter.uniforms.dimensions) + { + filter.uniforms.dimensions.value[0] = this.width;//width; + filter.uniforms.dimensions.value[1] = this.height;//height; + filter.uniforms.dimensions.value[2] = this.vertexArray[0]; + filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height; + } + + shader.syncUniforms(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + + // draw the filter... + gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + + this.renderSession.drawCount++; +}; + +/** +* Initialises the shader buffers. +* +* @method PIXI.WebGLFilterManager#initShaderBuffers +*/ +PIXI.WebGLFilterManager.prototype.initShaderBuffers = function() +{ + var gl = this.gl; + + // create some buffers + this.vertexBuffer = gl.createBuffer(); + this.uvBuffer = gl.createBuffer(); + this.colorBuffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + + // bind and upload the vertexs.. + // keep a reference to the vertexFloatData.. + this.vertexArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW); + + // bind and upload the uv buffer + this.uvArray = new Float32Array([0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW); + + this.colorArray = new Float32Array([1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF, + 1.0, 0xFFFFFF]); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW); + + // bind and upload the index + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW); + +}; + +/** +* Destroys the filter and removes it from the filter stack. +* +* @method PIXI.WebGLFilterManager#destroy +*/ +PIXI.WebGLFilterManager.prototype.destroy = function() +{ + var gl = this.gl; + + this.filterStack = null; + + this.offsetX = 0; + this.offsetY = 0; + + // destroy textures + for (var i = 0; i < this.texturePool.length; i++) { + this.texturePool[i].destroy(); + } + + this.texturePool = null; + + //destroy buffers.. + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.uvBuffer); + gl.deleteBuffer(this.colorBuffer); + gl.deleteBuffer(this.indexBuffer); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @private + */ +function _CreateEmptyTexture(gl, width, height, scaleMode) { + var texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + return texture; +} + +/** + * @private + */ +var _fbErrors = { + 36054: 'Incomplete attachment', + 36055: 'Missing attachment', + 36057: 'Incomplete dimensions', + 36061: 'Framebuffer unsupported' +}; + +/** + * @private + */ +function _CreateFramebuffer(gl, width, height, scaleMode, textureUnit) { + var framebuffer = gl.createFramebuffer(); + var depthStencilBuffer = gl.createRenderbuffer(); + var colorBuffer = null; + var fbStatus = 0; + + gl.activeTexture(gl.TEXTURE0 + textureUnit); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer); + colorBuffer = _CreateEmptyTexture(gl, width, height, scaleMode); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorBuffer, 0); + fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + if(fbStatus !== gl.FRAMEBUFFER_COMPLETE) { + console.error('Incomplete GL framebuffer. ', _fbErrors[fbStatus]); + } + framebuffer.width = width; + framebuffer.height = height; + framebuffer.targetTexture = colorBuffer; + framebuffer.renderBuffer = depthStencilBuffer; + return framebuffer; +} + +/** +* @class PIXI.FilterTexture +* @constructor +* @param gl {WebGLContext} the current WebGL drawing context +* @param width {Number} the horizontal range of the filter +* @param height {Number} the vertical range of the filter +* @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values +*/ +PIXI.FilterTexture = function(gl, width, height, scaleMode, textureUnit) +{ + textureUnit = typeof textureUnit === 'number' ? textureUnit : 0; + /** + * @property gl + * @type WebGLContext + */ + this.gl = gl; + // next time to create a frame buffer and texture + + /** + * @property frameBuffer + * @type Any + */ + this.frameBuffer = _CreateFramebuffer(gl, width, height, scaleMode || PIXI.scaleModes.DEFAULT, textureUnit); + /** + * @property texture + * @type Any + */ + this.texture = this.frameBuffer.targetTexture; + this.width = width; + this.height = height; + this.renderBuffer = this.frameBuffer.renderBuffer; +}; + +PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture; + +/** +* Clears the filter texture. +* +* @method PIXI.FilterTexture#clear +*/ +PIXI.FilterTexture.prototype.clear = function() +{ + var gl = this.gl; + + gl.clearColor(0,0,0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Resizes the texture to the specified width and height + * + * @method PIXI.FilterTexture#resize + * @param width {Number} the new width of the texture + * @param height {Number} the new height of the texture + */ +PIXI.FilterTexture.prototype.resize = function(width, height) +{ + if(this.width === width && this.height === height) return; + + this.width = width; + this.height = height; + + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height ); +}; + +/** +* Destroys the filter texture. +* +* @method PIXI.FilterTexture#destroy +*/ +PIXI.FilterTexture.prototype.destroy = function() +{ + var gl = this.gl; + gl.deleteFramebuffer( this.frameBuffer ); + gl.deleteTexture( this.texture ); + + this.frameBuffer = null; + this.texture = null; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Creates a Canvas element of the given size. + * + * @class PIXI.CanvasBuffer + * @constructor + * @param width {Number} the width for the newly created canvas + * @param height {Number} the height for the newly created canvas + */ +PIXI.CanvasBuffer = function(width, height) +{ + /** + * The width of the Canvas in pixels. + * + * @property width + * @type Number + */ + this.width = width; + + /** + * The height of the Canvas in pixels. + * + * @property height + * @type Number + */ + this.height = height; + + /** + * The Canvas object that belongs to this CanvasBuffer. + * + * @property canvas + * @type HTMLCanvasElement + */ + this.canvas = Phaser.CanvasPool.create(this, this.width, this.height); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.canvas.getContext("2d"); + + this.canvas.width = width; + this.canvas.height = height; +}; + +PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer; + +/** + * Clears the canvas that was created by the CanvasBuffer class. + * + * @method PIXI.CanvasBuffer#clear + * @private + */ +PIXI.CanvasBuffer.prototype.clear = function() +{ + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0,0, this.width, this.height); +}; + +/** + * Resizes the canvas to the specified width and height. + * + * @method PIXI.CanvasBuffer#resize + * @param width {Number} the new width of the canvas + * @param height {Number} the new height of the canvas + */ +PIXI.CanvasBuffer.prototype.resize = function(width, height) +{ + this.width = this.canvas.width = width; + this.height = this.canvas.height = height; +}; + +/** + * Frees the canvas up for use again. + * + * @method PIXI.CanvasBuffer#destroy + */ +PIXI.CanvasBuffer.prototype.destroy = function() +{ + Phaser.CanvasPool.remove(this); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used to handle masking. + * + * @class PIXI.CanvasMaskManager + * @constructor + */ +PIXI.CanvasMaskManager = function() +{ +}; + +PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; + +/** + * This method adds it to the current stack of masks. + * + * @method PIXI.CanvasMaskManager#pushMask + * @param maskData {Object} the maskData that will be pushed + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) { + + var context = renderSession.context; + + context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.worldTransform; + + var resolution = renderSession.resolution; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution); + + PIXI.CanvasGraphics.renderGraphicsMask(maskData, context); + + context.clip(); + + maskData.worldAlpha = cacheAlpha; +}; + +/** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @method PIXI.CanvasMaskManager#popMask + * @param renderSession {Object} The renderSession whose context will be used for this mask manager. + */ +PIXI.CanvasMaskManager.prototype.popMask = function(renderSession) +{ + renderSession.context.restore(); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class PIXI.CanvasTinter + * @static + */ +PIXI.CanvasTinter = function() {}; + +/** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @method PIXI.CanvasTinter#getTintedTexture + * @static + * @param sprite {Sprite} the sprite to tint + * @param color {Number} the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ +PIXI.CanvasTinter.getTintedTexture = function(sprite, color) +{ + var canvas = sprite.tintedTexture || Phaser.CanvasPool.create(this); + + PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas); + + return canvas; +}; + +/** + * Tint a texture using the "multiply" operation. + * + * @method PIXI.CanvasTinter#tintWithMultiply + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.clearRect(0, 0, w, h); + + context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, w, h); + + context.globalCompositeOperation = "multiply"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + context.globalCompositeOperation = "destination-atop"; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + +}; + +/** + * Tint a texture pixel per pixel. + * + * @method PIXI.CanvasTinter#tintPerPixel + * @static + * @param texture {Texture} the texture to tint + * @param color {Number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ +PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas) +{ + var context = canvas.getContext("2d"); + + var crop = texture.crop; + var w = crop.width; + var h = crop.height; + + if (texture.rotated) + { + w = h; + h = crop.width; + } + + if (canvas.width !== w || canvas.height !== h) + { + canvas.width = w; + canvas.height = h; + } + + context.globalCompositeOperation = "copy"; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); + + var rgbValues = Phaser.Color.hexToRGBArray(color); + var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, w, h); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) + { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + + if (!PIXI.CanvasTinter.canHandleAlpha) + { + var alpha = pixels[i + 3]; + + pixels[i + 0] /= 255 / alpha; + pixels[i + 1] /= 255 / alpha; + pixels[i + 2] /= 255 / alpha; + } + } + + context.putImageData(pixelData, 0, 0); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class PIXI.CanvasRenderer + * @constructor + * @param game {Phaser.Game} A reference to the Phaser Game instance + */ +PIXI.CanvasRenderer = function (game, config) { + + /** + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ + this.game = game; + + if (!PIXI.defaultRenderer) + { + PIXI.defaultRenderer = this; + } + + /** + * The renderer type. + * + * @property type + * @type Number + */ + this.type = Phaser.CANVAS; + + /** + * The resolution of the canvas. + * + * @property resolution + * @type Number + */ + this.resolution = game.resolution; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. + * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame. + * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. + * + * @property clearBeforeRender + * @type Boolean + * @default + */ + this.clearBeforeRender = game.clearBeforeRender; + + /** + * Whether the render view is transparent + * + * @property transparent + * @type Boolean + */ + this.transparent = game.transparent; + + /** + * Whether the render view should be resized automatically + * + * @property autoResize + * @type Boolean + */ + this.autoResize = false; + + /** + * The width of the canvas view + * + * @property width + * @type Number + * @default 800 + */ + this.width = game.width * this.resolution; + + /** + * The height of the canvas view + * + * @property height + * @type Number + * @default 600 + */ + this.height = game.height * this.resolution; + + /** + * The canvas element that everything is drawn to. + * + * @property view + * @type HTMLCanvasElement + */ + this.view = game.canvas; + + /** + * The canvas 2d context that everything is drawn with + * @property context + * @type CanvasRenderingContext2D + */ + this.context = this.view.getContext("2d", { alpha: this.transparent } ); + + /** + * Boolean flag controlling canvas refresh. + * + * @property refresh + * @type Boolean + */ + this.refresh = true; + + /** + * Internal var. + * + * @property count + * @type Number + */ + this.count = 0; + + /** + * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer + * @property CanvasMaskManager + * @type CanvasMaskManager + */ + this.maskManager = new PIXI.CanvasMaskManager(); + + /** + * The render session is just a bunch of parameter used for rendering + * @property renderSession + * @type Object + */ + this.renderSession = { + context: this.context, + maskManager: this.maskManager, + scaleMode: null, + smoothProperty: Phaser.Canvas.getSmoothingPrefix(this.context), + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + */ + roundPixels: config.roundPixels || false + }; + + this.mapBlendModes(); + + this.resize(this.width, this.height); + +}; + +// constructor +PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer; + +/** + * Renders the DisplayObjectContainer, usually the Phaser.Stage, to this canvas view. + * + * @method PIXI.CanvasRenderer#render + * @param root {Phaser.Stage|PIXI.DisplayObjectContainer} The root element to be rendered. + */ +PIXI.CanvasRenderer.prototype.render = function (root) { + + this.context.setTransform(1, 0, 0, 1, 0, 0); + + this.context.globalAlpha = 1; + + this.renderSession.currentBlendMode = 0; + this.renderSession.shakeX = this.game.camera._shake.x; + this.renderSession.shakeY = this.game.camera._shake.y; + + this.context.globalCompositeOperation = 'source-over'; + + if (navigator.isCocoonJS && this.view.screencanvas) + { + this.context.fillStyle = "black"; + this.context.clear(); + } + + if (this.clearBeforeRender) + { + if (this.transparent) + { + this.context.clearRect(0, 0, this.width, this.height); + } + else if (root._bgColor) + { + this.context.fillStyle = root._bgColor.rgba; + this.context.fillRect(0, 0, this.width , this.height); + } + } + + this.renderDisplayObject(root); + +}; + +PIXI.CanvasRenderer.prototype.setTexturePriority = function (textureNameCollection) { + + // Does nothing on Canvas, but here to allow you to simply set + // `game.renderer.setTexturePriority()` without having to worry about + // running in WebGL or not. + +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @method PIXI.CanvasRenderer#destroy + * @param [removeView=true] {boolean} Removes the Canvas element from the DOM. + */ +PIXI.CanvasRenderer.prototype.destroy = function (removeView) { + + if (removeView === undefined) { removeView = true; } + + if (removeView && this.view.parent) + { + this.view.parent.removeChild(this.view); + } + + this.view = null; + this.context = null; + this.maskManager = null; + this.renderSession = null; + +}; + +/** + * Resizes the canvas view to the specified width and height + * + * @method PIXI.CanvasRenderer#resize + * @param width {Number} the new width of the canvas view + * @param height {Number} the new height of the canvas view + */ +PIXI.CanvasRenderer.prototype.resize = function (width, height) { + + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) + { + this.view.style.width = this.width / this.resolution + "px"; + this.view.style.height = this.height / this.resolution + "px"; + } + + if (this.renderSession.smoothProperty) + { + this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR); + } + +}; + +/** + * Renders a display object + * + * @method PIXI.CanvasRenderer#renderDisplayObject + * @param displayObject {DisplayObject} The displayObject to render + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. + * @private + */ +PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) { + + this.renderSession.context = context || this.context; + this.renderSession.resolution = this.resolution; + displayObject._renderCanvas(this.renderSession, matrix); + +}; + +/** + * Maps Pixi blend modes to canvas blend modes. + * + * @method PIXI.CanvasRenderer#mapBlendModes + * @private + */ +PIXI.CanvasRenderer.prototype.mapBlendModes = function () { + + if (!PIXI.blendModesCanvas) + { + var b = []; + var modes = PIXI.blendModes; + var useNew = this.game.device.canUseMultiply; + + b[modes.NORMAL] = 'source-over'; + b[modes.ADD] = 'lighter'; + b[modes.MULTIPLY] = (useNew) ? 'multiply' : 'source-over'; + b[modes.SCREEN] = (useNew) ? 'screen' : 'source-over'; + b[modes.OVERLAY] = (useNew) ? 'overlay' : 'source-over'; + b[modes.DARKEN] = (useNew) ? 'darken' : 'source-over'; + b[modes.LIGHTEN] = (useNew) ? 'lighten' : 'source-over'; + b[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : 'source-over'; + b[modes.COLOR_BURN] = (useNew) ? 'color-burn' : 'source-over'; + b[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : 'source-over'; + b[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : 'source-over'; + b[modes.DIFFERENCE] = (useNew) ? 'difference' : 'source-over'; + b[modes.EXCLUSION] = (useNew) ? 'exclusion' : 'source-over'; + b[modes.HUE] = (useNew) ? 'hue' : 'source-over'; + b[modes.SATURATION] = (useNew) ? 'saturation' : 'source-over'; + b[modes.COLOR] = (useNew) ? 'color' : 'source-over'; + b[modes.LUMINOSITY] = (useNew) ? 'luminosity' : 'source-over'; + + PIXI.blendModesCanvas = b; + } + +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class PIXI.BaseTexture + * @constructor + * @param source {String|Canvas} the source object (image or canvas) + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + */ +PIXI.BaseTexture = function(source, scaleMode, resolution) +{ + /** + * The Resolution of the texture. + * + * @property resolution + * @type Number + */ + this.resolution = resolution || 1; + + /** + * [read-only] The width of the base texture set when the image has loaded + * + * @property width + * @type Number + * @readOnly + */ + this.width = 100; + + /** + * [read-only] The height of the base texture set when the image has loaded + * + * @property height + * @type Number + * @readOnly + */ + this.height = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @property scaleMode + * @type {Number} + * @default PIXI.scaleModes.LINEAR + */ + this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT; + + /** + * [read-only] Set to true once the base texture has loaded + * + * @property hasLoaded + * @type Boolean + * @readOnly + */ + this.hasLoaded = false; + + /** + * The image source that is used to create the texture. + * + * @property source + * @type Image + */ + this.source = source; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * + * @property premultipliedAlpha + * @type Boolean + * @default true + */ + this.premultipliedAlpha = true; + + // used for webGL + + /** + * @property _glTextures + * @type Array + * @private + */ + this._glTextures = []; + + /** + * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @property mipmap + * @type {Boolean} + */ + this.mipmap = false; + + /** + * The multi texture batching index number. + * @property textureIndex + * @type Number + */ + this.textureIndex = 0; + + /** + * @property _dirty + * @type Array + * @private + */ + this._dirty = [true, true, true, true]; + + if (!source) + { + return; + } + + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { + this.hasLoaded = true; + this.width = this.source.naturalWidth || this.source.width; + this.height = this.source.naturalHeight || this.source.height; + this.dirty(); + } + + /** + * A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch. + * + * You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture) + * that has children that you do want to render, without causing a batch flush in the process. + * + * @property skipRender + * @type Boolean + */ + this.skipRender = false; + + /** + * @property _powerOf2 + * @type Boolean + * @private + */ + this._powerOf2 = false; + +}; + +PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture; + +/** + * Forces this BaseTexture to be set as loaded, with the given width and height. + * Then calls BaseTexture.dirty. + * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have. + * + * @method PIXI.BaseTexture#forceLoaded + * @param {number} width - The new width to force the BaseTexture to be. + * @param {number} height - The new height to force the BaseTexture to be. + */ +PIXI.BaseTexture.prototype.forceLoaded = function(width, height) +{ + this.hasLoaded = true; + this.width = width; + this.height = height; + this.dirty(); +}; + +/** + * Destroys this base texture + * + * @method PIXI.BaseTexture#destroy + */ +PIXI.BaseTexture.prototype.destroy = function() +{ + if (this.source) + { + Phaser.CanvasPool.removeByCanvas(this.source); + } + + this.source = null; + + this.unloadFromGPU(); +}; + +/** + * Sets all glTextures to be dirty. + * + * @method PIXI.BaseTexture#dirty + */ +PIXI.BaseTexture.prototype.dirty = function() +{ + for (var i = 0; i < this._glTextures.length; i++) + { + this._dirty[i] = true; + } +}; + +/** + * Removes the base texture from the GPU, useful for managing resources on the GPU. + * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it. + * + * @method PIXI.BaseTexture#unloadFromGPU + */ +PIXI.BaseTexture.prototype.unloadFromGPU = function() +{ + this.dirty(); + + // delete the webGL textures if any. + for (var i = this._glTextures.length - 1; i >= 0; i--) + { + var glTexture = this._glTextures[i]; + var gl = PIXI.glContexts[i]; + + if(gl && glTexture) + { + gl.deleteTexture(glTexture); + } + + } + + this._glTextures.length = 0; + + this.dirty(); +}; + +/** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @method PIXI.BaseTexture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @param [resolution] {Number} the resolution of the texture (for HiDPI displays) + * @return {BaseTexture} + */ +PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode, resolution) +{ + if (canvas.width === 0) + { + canvas.width = 1; + } + + if (canvas.height === 0) + { + canvas.height = 1; + } + + resolution = resolution || 1; + + return new PIXI.BaseTexture(canvas, scaleMode, resolution); +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * TextureSilentFail is a boolean that defaults to `false`. + * If `true` then {@link PIXI.Texture#setFrame} will no longer throw an error if the texture dimensions are incorrect. + * Instead {@link PIXI.Texture#valid} will be set to `false` (#1556) + * + * @type {boolean} + */ +PIXI.TextureSilentFail = false; + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used. + * + * @class PIXI.Texture + * @constructor + * @param baseTexture {BaseTexture} The base texture source to create the texture from + * @param frame {Rectangle} The rectangle frame of the texture to show + * @param [crop] {Rectangle} The area of original texture + * @param [trim] {Rectangle} Trimmed texture rectangle + */ +PIXI.Texture = function(baseTexture, frame, crop, trim) +{ + /** + * Does this Texture have any frame data assigned to it? + * + * @property noFrame + * @type Boolean + */ + this.noFrame = false; + + if (!frame) + { + this.noFrame = true; + frame = new PIXI.Rectangle(0,0,1,1); + } + + if (baseTexture instanceof PIXI.Texture) + { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = baseTexture; + + /** + * The frame specifies the region of the base texture that this texture uses + * + * @property frame + * @type Rectangle + */ + this.frame = frame; + + /** + * The texture trim data. + * + * @property trim + * @type Rectangle + */ + this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @property valid + * @type Boolean + */ + this.valid = false; + + /** + * Is this a tiling texture? As used by the likes of a TilingSprite. + * + * @property isTiling + * @type Boolean + */ + this.isTiling = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @property requiresUpdate + * @type Boolean + */ + this.requiresUpdate = false; + + /** + * This will let a renderer know that a tinted parent has updated its texture. + * + * @property requiresReTint + * @type Boolean + */ + this.requiresReTint = false; + + /** + * The WebGL UV data cache. + * + * @property _uvs + * @type Object + * @private + */ + this._uvs = null; + + /** + * The width of the Texture in pixels. + * + * @property width + * @type Number + */ + this.width = 0; + + /** + * The height of the Texture in pixels. + * + * @property height + * @type Number + */ + this.height = 0; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @property crop + * @type Rectangle + */ + this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1); + + /** + * A flag that controls if this frame is rotated or not. + * Rotation allows you to use rotated frames in texture atlas packing, it has nothing to do with + * Sprite rotation. + * + * @property rotated + * @type Boolean + */ + this.rotated = false; + + if (baseTexture.hasLoaded) + { + if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + this.setFrame(frame); + } + +}; + +PIXI.Texture.prototype.constructor = PIXI.Texture; + +/** + * Called when the base texture is loaded + * + * @method PIXI.Texture#onBaseTextureLoaded + * @private + */ +PIXI.Texture.prototype.onBaseTextureLoaded = function() +{ + var baseTexture = this.baseTexture; + + if (this.noFrame) + { + this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } + + this.setFrame(this.frame); +}; + +/** + * Destroys this texture + * + * @method PIXI.Texture#destroy + * @param destroyBase {Boolean} Whether to destroy the base texture as well + */ +PIXI.Texture.prototype.destroy = function(destroyBase) +{ + if (destroyBase) this.baseTexture.destroy(); + + this.valid = false; +}; + +/** + * Specifies the region of the baseTexture that this texture will use. + * + * @method PIXI.Texture#setFrame + * @param frame {Rectangle} The frame of the texture to set it to + */ +PIXI.Texture.prototype.setFrame = function(frame) +{ + this.noFrame = false; + + this.frame = frame; + this.width = frame.width; + this.height = frame.height; + + this.crop.x = frame.x; + this.crop.y = frame.y; + this.crop.width = frame.width; + this.crop.height = frame.height; + + if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)) + { + if (!PIXI.TextureSilentFail) + { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + this.valid = false; + return; + } + + this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + + if (this.trim) + { + this.width = this.trim.width; + this.height = this.trim.height; + this.frame.width = this.trim.width; + this.frame.height = this.trim.height; + } + + if (this.valid) this._updateUvs(); + +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvs + * @private + */ +PIXI.Texture.prototype._updateUvs = function() +{ + if(!this._uvs)this._uvs = new PIXI.TextureUvs(); + + var frame = this.crop; + 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; +}; + +/** + * Updates the internal WebGL UV cache. + * + * @method PIXI.Texture#_updateUvsInverted + * @private + */ +PIXI.Texture.prototype._updateUvsInverted = function () { + + if (!this._uvs) { this._uvs = new PIXI.TextureUvs(); } + + var frame = this.crop; + 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.height) / tw; + this._uvs.y1 = frame.y / th; + + this._uvs.x2 = (frame.x + frame.height) / tw; + this._uvs.y2 = (frame.y + frame.width) / th; + + this._uvs.x3 = frame.x / tw; + this._uvs.y3 = (frame.y + frame.width) / th; + +}; + +/** + * Helper function that creates a new a Texture based on the given canvas element. + * + * @static + * @method PIXI.Texture#fromCanvas + * @param canvas {Canvas} The canvas element source of the texture + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + * @return {Texture} + */ +PIXI.Texture.fromCanvas = function(canvas, scaleMode) +{ + var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode); + + return new PIXI.Texture(baseTexture); +}; + +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.y3 = 0; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = PIXI; + } + exports.PIXI = PIXI; + } else if (typeof define !== 'undefined' && define.amd) { + define('PIXI', (function() { return root.PIXI = PIXI; })() ); + } else { + root.PIXI = PIXI; + } + + return PIXI; +}).call(this); +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +(function(){ + + var root = this; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @namespace Phaser +*/ +var Phaser = Phaser || { // jshint ignore:line + + /** + * The Phaser version number. + * @constant Phaser.VERSION + * @type {string} + */ + VERSION: '2.10.0', + + /** + * An array of Phaser game instances. + * @constant Phaser.GAMES + * @type {array} + */ + GAMES: [], + + /** + * AUTO renderer - picks between WebGL or Canvas based on device. + * @constant Phaser.AUTO + * @type {integer} + */ + AUTO: 0, + + /** + * Canvas Renderer. + * @constant Phaser.CANVAS + * @type {integer} + */ + CANVAS: 1, + + /** + * WebGL Renderer. + * @constant Phaser.WEBGL + * @type {integer} + */ + WEBGL: 2, + + /** + * Headless renderer (not visual output) + * @constant Phaser.HEADLESS + * @type {integer} + */ + HEADLESS: 3, + + /** + * WebGL Renderer with MultiTexture support enabled. + * @constant Phaser.WEBGL_MULTI + * @type {integer} + */ + WEBGL_MULTI: 4, + + /** + * Direction constant. + * @constant Phaser.NONE + * @type {integer} + */ + NONE: 0, + + /** + * Direction constant. + * @constant Phaser.LEFT + * @type {integer} + */ + LEFT: 1, + + /** + * Direction constant. + * @constant Phaser.RIGHT + * @type {integer} + */ + RIGHT: 2, + + /** + * Direction constant. + * @constant Phaser.UP + * @type {integer} + */ + UP: 3, + + /** + * Direction constant. + * @constant Phaser.DOWN + * @type {integer} + */ + DOWN: 4, + + /** + * Game Object type. + * @constant Phaser.SPRITE + * @type {integer} + */ + SPRITE: 0, + + /** + * Game Object type. + * @constant Phaser.BUTTON + * @type {integer} + */ + BUTTON: 1, + + /** + * Game Object type. + * @constant Phaser.IMAGE + * @type {integer} + */ + IMAGE: 2, + + /** + * Game Object type. + * @constant Phaser.GRAPHICS + * @type {integer} + */ + GRAPHICS: 3, + + /** + * Game Object type. + * @constant Phaser.TEXT + * @type {integer} + */ + TEXT: 4, + + /** + * Game Object type. + * @constant Phaser.TILESPRITE + * @type {integer} + */ + TILESPRITE: 5, + + /** + * Game Object type. + * @constant Phaser.BITMAPTEXT + * @type {integer} + */ + BITMAPTEXT: 6, + + /** + * Game Object type. + * @constant Phaser.GROUP + * @type {integer} + */ + GROUP: 7, + + /** + * Game Object type. + * @constant Phaser.RENDERTEXTURE + * @type {integer} + */ + RENDERTEXTURE: 8, + + /** + * Game Object type. + * @constant Phaser.TILEMAP + * @type {integer} + */ + TILEMAP: 9, + + /** + * Game Object type. + * @constant Phaser.TILEMAPLAYER + * @type {integer} + */ + TILEMAPLAYER: 10, + + /** + * Game Object type. + * @constant Phaser.EMITTER + * @type {integer} + */ + EMITTER: 11, + + /** + * Game Object type. + * @constant Phaser.POLYGON + * @type {integer} + */ + POLYGON: 12, + + /** + * Game Object type. + * @constant Phaser.BITMAPDATA + * @type {integer} + */ + BITMAPDATA: 13, + + /** + * Game Object type. + * @constant Phaser.CANVAS_FILTER + * @type {integer} + */ + CANVAS_FILTER: 14, + + /** + * Game Object type. + * @constant Phaser.WEBGL_FILTER + * @type {integer} + */ + WEBGL_FILTER: 15, + + /** + * Game Object type. + * @constant Phaser.ELLIPSE + * @type {integer} + */ + ELLIPSE: 16, + + /** + * Game Object type. + * @constant Phaser.SPRITEBATCH + * @type {integer} + */ + SPRITEBATCH: 17, + + /** + * Game Object type. + * @constant Phaser.RETROFONT + * @type {integer} + */ + RETROFONT: 18, + + /** + * Game Object type. + * @constant Phaser.POINTER + * @type {integer} + */ + POINTER: 19, + + /** + * Game Object type. + * @constant Phaser.ROPE + * @type {integer} + */ + ROPE: 20, + + /** + * Game Object type. + * @constant Phaser.CIRCLE + * @type {integer} + */ + CIRCLE: 21, + + /** + * Game Object type. + * @constant Phaser.RECTANGLE + * @type {integer} + */ + RECTANGLE: 22, + + /** + * Game Object type. + * @constant Phaser.LINE + * @type {integer} + */ + LINE: 23, + + /** + * Game Object type. + * @constant Phaser.MATRIX + * @type {integer} + */ + MATRIX: 24, + + /** + * Game Object type. + * @constant Phaser.POINT + * @type {integer} + */ + POINT: 25, + + /** + * Game Object type. + * @constant Phaser.ROUNDEDRECTANGLE + * @type {integer} + */ + ROUNDEDRECTANGLE: 26, + + /** + * Game Object type. + * @constant Phaser.CREATURE + * @type {integer} + */ + CREATURE: 27, + + /** + * Game Object type. + * @constant Phaser.VIDEO + * @type {integer} + */ + VIDEO: 28, + + /** + * Game Object type. + * @constant Phaser.PENDING_ATLAS + * @type {integer} + */ + PENDING_ATLAS: -1, + + /** + * A horizontal orientation + * @constant Phaser.HORIZONTAL + * @type {integer} + */ + HORIZONTAL: 0, + + /** + * A vertical orientation + * @constant Phaser.VERTICAL + * @type {integer} + */ + VERTICAL: 1, + + /** + * A landscape orientation + * @constant Phaser.LANDSCAPE + * @type {integer} + */ + LANDSCAPE: 0, + + /** + * A portrait orientation + * @constant Phaser.PORTRAIT + * @type {integer} + */ + PORTRAIT: 1, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face up. + * @constant Phaser.ANGLE_UP + * @type {integer} + */ + ANGLE_UP: 270, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face down. + * @constant Phaser.ANGLE_DOWN + * @type {integer} + */ + ANGLE_DOWN: 90, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face left. + * @constant Phaser.ANGLE_LEFT + * @type {integer} + */ + ANGLE_LEFT: 180, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face right. + * @constant Phaser.ANGLE_RIGHT + * @type {integer} + */ + ANGLE_RIGHT: 0, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north east. + * @constant Phaser.ANGLE_NORTH_EAST + * @type {integer} + */ + ANGLE_NORTH_EAST: 315, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face north west. + * @constant Phaser.ANGLE_NORTH_WEST + * @type {integer} + */ + ANGLE_NORTH_WEST: 225, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south east. + * @constant Phaser.ANGLE_SOUTH_EAST + * @type {integer} + */ + ANGLE_SOUTH_EAST: 45, + + /** + * The Angle (in degrees) a Game Object needs to be set to in order to face south west. + * @constant Phaser.ANGLE_SOUTH_WEST + * @type {integer} + */ + ANGLE_SOUTH_WEST: 135, + + /** + * A constant representing a top-left alignment or position. + * @constant Phaser.TOP_LEFT + * @type {integer} + */ + TOP_LEFT: 0, + + /** + * A constant representing a top-center alignment or position. + * @constant Phaser.TOP_CENTER + * @type {integer} + */ + TOP_CENTER: 1, + + /** + * A constant representing a top-right alignment or position. + * @constant Phaser.TOP_RIGHT + * @type {integer} + */ + TOP_RIGHT: 2, + + /** + * A constant representing a left-top alignment or position. + * @constant Phaser.Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_TOP: 3, + + /** + * A constant representing a left-center alignment or position. + * @constant Phaser.LEFT_TOP + * @type {integer} + */ + LEFT_CENTER: 4, + + /** + * A constant representing a left-bottom alignment or position. + * @constant Phaser.LEFT_BOTTOM + * @type {integer} + */ + LEFT_BOTTOM: 5, + + /** + * A constant representing a center alignment or position. + * @constant Phaser.CENTER + * @type {integer} + */ + CENTER: 6, + + /** + * A constant representing a right-top alignment or position. + * @constant Phaser.RIGHT_TOP + * @type {integer} + */ + RIGHT_TOP: 7, + + /** + * A constant representing a right-center alignment or position. + * @constant Phaser.RIGHT_CENTER + * @type {integer} + */ + RIGHT_CENTER: 8, + + /** + * A constant representing a right-bottom alignment or position. + * @constant Phaser.RIGHT_BOTTOM + * @type {integer} + */ + RIGHT_BOTTOM: 9, + + /** + * A constant representing a bottom-left alignment or position. + * @constant Phaser.BOTTOM_LEFT + * @type {integer} + */ + BOTTOM_LEFT: 10, + + /** + * A constant representing a bottom-center alignment or position. + * @constant Phaser.BOTTOM_CENTER + * @type {integer} + */ + BOTTOM_CENTER: 11, + + /** + * A constant representing a bottom-right alignment or position. + * @constant Phaser.BOTTOM_RIGHT + * @type {integer} + */ + BOTTOM_RIGHT: 12, + + /** + * Various blend modes supported by Pixi. See the samples in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing Canvas Tutorial: Compositing}. + * + * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * + * @constant {Object} Phaser.blendModes + * @property {Number} blendModes.NORMAL - Draws new shapes on top of the existing content. This is the default setting. + * @property {Number} blendModes.ADD - Where both shapes overlap the color is determined by adding color values. + * @property {Number} blendModes.MULTIPLY - The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer, making a darker picture. + * @property {Number} blendModes.SCREEN - The pixels are inverted, multiplied, and inverted again, making a lighter picture. + * @property {Number} blendModes.OVERLAY + * @property {Number} blendModes.DARKEN + * @property {Number} blendModes.LIGHTEN + * @property {Number} blendModes.COLOR_DODGE + * @property {Number} blendModes.COLOR_BURN + * @property {Number} blendModes.HARD_LIGHT + * @property {Number} blendModes.SOFT_LIGHT + * @property {Number} blendModes.DIFFERENCE + * @property {Number} blendModes.EXCLUSION + * @property {Number} blendModes.HUE + * @property {Number} blendModes.SATURATION + * @property {Number} blendModes.COLOR + * @property {Number} blendModes.LUMINOSITY + * @static + */ + 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 + }, + + /** + * The scale modes that are supported by Pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @constant {Object} Phaser.scaleModes + * @property {Number} Phaser.scaleModes.DEFAULT=LINEAR + * @property {Number} Phaser.scaleModes.LINEAR Smooth scaling + * @property {Number} Phaser.scaleModes.NEAREST Pixelating scaling + * @static + */ + scaleModes: { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 + }, + + PIXI: PIXI || {}, + + // Used to create IDs for various Pixi objects. + _UID: 0 + +}; + +/** +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc +if (!Math.trunc) { + Math.trunc = function trunc(x) { + return x < 0 ? Math.ceil(x) : Math.floor(x); + }; +} + +/** +* A polyfill for Function.prototype.bind +*/ +if (!Function.prototype.bind) { + + /* jshint freeze: false */ + 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)) + { + /* jshint supernew: true */ + return new F; + } + })(target.prototype); + + return bound; + }; + })(); +} + +/** +* A polyfill for Array.isArray +*/ +if (!Array.isArray) +{ + Array.isArray = function (arg) + { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + +/** +* A polyfill for Array.forEach +* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach +*/ +if (!Array.prototype.forEach) +{ + Array.prototype.forEach = function(fun /*, thisArg */) + { + "use strict"; + + if (this === void 0 || this === null) + { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + if (typeof fun !== "function") + { + throw new TypeError(); + } + + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + + for (var i = 0; i < len; i++) + { + if (i in t) + { + fun.call(thisArg, t[i], i, t); + } + } + }; +} + +/** +* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 +* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ +* Cameron Foale (http://www.kibibu.com) +*/ +if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object") +{ + var CheapArray = function(type) + { + var proto = new Array(); // jshint ignore:line + + window[type] = function(arg) { + + if (typeof(arg) === "number") + { + Array.call(this, arg); + this.length = arg; + + for (var i = 0; i < this.length; i++) + { + this[i] = 0; + } + } + else + { + Array.call(this, arg.length); + + this.length = arg.length; + + for (var i = 0; i < this.length; i++) + { + this[i] = arg[i]; + } + } + }; + + window[type].prototype = proto; + window[type].constructor = window[type]; + }; + + CheapArray('Float32Array'); // jshint ignore:line + CheapArray('Uint32Array'); // jshint ignore:line + CheapArray('Uint16Array'); // jshint ignore:line + CheapArray('Int16Array'); // jshint ignore:line + CheapArray('ArrayBuffer'); // jshint ignore:line +} + +/** + * Also fix for the absent console in IE9 + */ +if (!window.console) +{ + window.console = {}; + window.console.log = window.console.assert = function(){}; + window.console.warn = window.console.assert = function(){}; +} + +/** + * Fix for Object.assign not existing on older devices + */ + +if (!Object.assign) { + /* jshint -W098 */ + // We include `varArgs` (unused) to ensure Object.assign.length === 2 + Object.assign = function(target, varArgs) { + /* jshint +W098 */ + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + var hasOwn = Object.prototype.hasOwnProperty; + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (hasOwn.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }; +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @class Phaser.Utils +* @static +*/ +Phaser.Utils = { + + /** + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @method Phaser.Utils.reverseString + * @param {string} string - The string to be reversed. + * @return {string} The reversed string. + */ + reverseString: function (string) { + + return string.split('').reverse().join(''); + + }, + + /** + * Gets an object's property by string. + * + * @method Phaser.Utils.getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + getProperty: function(obj, name) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + return obj[name]; + case 2: + return obj[parts[0]][parts[1]]; + case 3: + return obj[parts[0]][parts[1]][parts[2]]; + case 4: + return obj[parts[0]][parts[1]][parts[2]][parts[3]]; + default: + return this._getProperty(obj, name); + } + + }, + + /** + * Sets an object's properties from a map of property names and values. + * + * ```javascript + * Phaser.Utils.setProperties(sprite, { + * 'animations.paused': true, + * 'body.enable': false, + * 'input.draggable': true, + * }); + * ``` + * + * @method Phaser.Utils.setProperties + * @param {object} obj - The object to modify. + * @param {object} props - The property names and values to set on the object (see {@link #setProperty}). + * @return {object} The modified object. + */ + setProperties: function(obj, props) { + + for (var name in props) + { + this.setProperty(obj, name, props[name]); + } + + return obj; + + }, + + /** + * Sets an object's property by name and value. + * + * ```javascript + * Phaser.Utils.setProperty(sprite, 'body.velocity.x', 60); + * ``` + * + * @method Phaser.Utils.setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + + setProperty: function(obj, name, value) { + + var parts = name.split('.'); + + switch (parts.length) + { + case 1: + obj[name] = value; + break; + case 2: + obj[parts[0]][parts[1]] = value; + break; + case 3: + obj[parts[0]][parts[1]][parts[2]] = value; + break; + case 4: + obj[parts[0]][parts[1]][parts[2]][parts[3]] = value; + break; + default: + this._setProperty(obj, name, value); + } + }, + + /** + * Gets an object's property by string. + * + * @private + * @method Phaser.Utils._getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property whose value will be returned. + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ + _getProperty: function(obj, name) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + val = obj; + + while (i < len) + { + var key = parts[i]; + + if (val != null) + { + val = val[key]; + i++; + } + else + { + return undefined; + } + } + + return val; + + }, + + /** + * Sets an object's property by name and value. + * + * @private + * @method Phaser.Utils._setProperty + * @param {object} obj - The object to modify. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @param {any} value - The value. + * @return {object} The modified object. + */ + _setProperty: function(obj, name, value) { + + var parts = name.split('.'), + len = parts.length, + i = 0, + currentObj = obj, + key = parts[0]; + + if (len === 1) + { + obj[name] = value; + } + else + { + while (i < (len - 1)) + { + currentObj = currentObj[key]; + i++; + key = parts[i]; + } + + currentObj[key] = value; + } + + return obj; + + }, + + /** + * Generate a random bool result based on the chance value. + * + * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance + * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. + * + * @method Phaser.Utils#chanceRoll + * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). + * @return {boolean} True if the roll passed, or false otherwise. + */ + chanceRoll: function (chance) { + if (chance === undefined) { chance = 50; } + return chance > 0 && (Math.random() * 100 <= chance); + }, + + /** + * Choose between one of two values randomly. + * + * @method Phaser.Utils#randomChoice + * @param {any} choice1 + * @param {any} choice2 + * @return {any} The randomly selected choice + */ + randomChoice: function (choice1, choice2) { + return (Math.random() < 0.5) ? choice1 : choice2; + }, + + /** + * Get a unit dimension from a string. + * + * @method Phaser.Utils.parseDimension + * @param {string|number} size - The size to parse. + * @param {number} dimension - The window dimension to check. + * @return {number} The parsed dimension. + */ + parseDimension: function (size, dimension) { + + var f = 0; + var px = 0; + + if (typeof size === 'string') + { + // %? + if (size.substr(-1) === '%') + { + f = parseInt(size, 10) / 100; + + if (dimension === 0) + { + px = window.innerWidth * f; + } + else + { + px = window.innerHeight * f; + } + } + else + { + px = parseInt(size, 10); + } + } + else + { + px = size; + } + + return px; + + }, + + /** + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @method Phaser.Utils.pad + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * @return {string} The padded string. + */ + pad: function (str, len, pad, dir) { + + if (len === undefined) { var len = 0; } + if (pad === undefined) { var pad = ' '; } + if (dir === undefined) { var dir = 3; } + + str = str.toString(); + + 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; + + }, + + /** + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * @method Phaser.Utils.isPlainObject + * @param {object} obj - The object to inspect. + * @return {boolean} - true if the object is plain, otherwise false. + */ + isPlainObject: function (obj) { + + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) + { + return false; + } + + // Support: Firefox <20 + // The try/catch suppresses exceptions thrown when attempting to access + // the "constructor" property of certain host objects, ie. |window.location| + // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + try { + if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) + { + return false; + } + } catch (e) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + /** + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @method Phaser.Utils.extend + * @param {boolean} deep - Perform a deep copy? + * @param {object} target - The target object to copy to. + * @return {object} The extended object. + */ + extend: function () { + + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if (typeof target === "boolean") + { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } + + for (; i < length; i++) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) + { + continue; + } + + // Recurse if we're merging plain objects or arrays + if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = Phaser.Utils.extend(deep, clone, copy); + + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } + + // Return the modified object + return target; + + }, + + /** + * Mixes in an existing mixin object with the target. + * + * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` + * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and + * the result is assigned directly. + * + * @method Phaser.Utils.mixinPrototype + * @param {object} target - The target object to receive the new functions. + * @param {object} mixin - The object to copy the functions from. + * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not? + */ + mixinPrototype: function (target, mixin, replace) { + + if (replace === undefined) { replace = false; } + + var mixinKeys = Object.keys(mixin); + + for (var i = 0; i < mixinKeys.length; i++) + { + var key = mixinKeys[i]; + var value = mixin[key]; + + if (!replace && (key in target)) + { + // Not overwriting existing property + continue; + } + else + { + if (value && + (typeof value.get === 'function' || typeof value.set === 'function')) + { + // Special case for classes like Phaser.Point which has a 'set' function! + if (typeof value.clone === 'function') + { + target[key] = value.clone(); + } + else + { + Object.defineProperty(target, key, value); + } + } + else + { + target[key] = value; + } + } + } + + }, + + /** + * Mixes the source object into the destination object, returning the newly modified destination object. + * Based on original code by @mudcube + * + * @method Phaser.Utils.mixin + * @param {object} from - The object to copy (the source object). + * @param {object} to - The object to copy to (the destination object). + * @return {object} The modified destination object. + */ + mixin: function (from, to) { + + if (!from || typeof (from) !== "object") + { + return to; + } + + for (var key in from) + { + var o = from[key]; + + if (o.childNodes || o.cloneNode) + { + continue; + } + + var type = typeof (from[key]); + + if (!from[key] || type !== "object") + { + to[key] = from[key]; + } + else + { + // Clone sub-object + if (typeof (to[key]) === type) + { + to[key] = Phaser.Utils.mixin(from[key], to[key]); + } + else + { + to[key] = Phaser.Utils.mixin(from[key], new o.constructor()); + } + } + } + + return to; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. +* If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. +* +* @class Phaser.Circle +* @constructor +* @param {number} [x=0] - The x coordinate of the center of the circle. +* @param {number} [y=0] - The y coordinate of the center of the circle. +* @param {number} [diameter=0] - The diameter of the circle. +*/ +Phaser.Circle = function (x, y, diameter) { + + x = x || 0; + y = y || 0; + diameter = diameter || 0; + + /** + * @property {number} x - The x coordinate of the center of the circle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the center of the circle. + */ + this.y = y; + + /** + * @property {number} _diameter - The diameter of the circle. + * @private + */ + this._diameter = diameter; + + /** + * @property {number} _radius - The radius of the circle. + * @private + */ + this._radius = 0; + + if (diameter > 0) + { + this._radius = diameter * 0.5; + } + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.CIRCLE; + +}; + +Phaser.Circle.prototype = { + + /** + * The circumference of the circle. + * + * @method Phaser.Circle#circumference + * @return {number} The circumference of the circle. + */ + circumference: function () { + + return 2 * (Math.PI * this._radius); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Circle. + * + * @method Phaser.Circle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = 2 * Math.PI * Math.random(); + var u = Math.random() + Math.random(); + var r = (u > 1) ? 2 - u : u; + var x = r * Math.cos(t); + var y = r * Math.sin(t); + + out.x = this.x + (x * this.radius); + out.y = this.y + (y * this.radius); + + return out; + + }, + + /** + * Returns the framing rectangle of the circle as a Phaser.Rectangle object. + * + * @method Phaser.Circle#getBounds + * @return {Phaser.Rectangle} The bounds of the Circle. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter); + + }, + + /** + * Sets the members of Circle to the specified values. + * @method Phaser.Circle#setTo + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} diameter - The diameter of the circle. + * @return {Circle} This circle object. + */ + setTo: function (x, y, diameter) { + + this.x = x; + this.y = y; + this._diameter = diameter; + this._radius = diameter * 0.5; + + return this; + + }, + + /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method Phaser.Circle#copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.diameter); + + }, + + /** + * Copies the x, y and diameter properties from this Circle to any given object. + * @method Phaser.Circle#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.diameter = this._diameter; + + return dest; + + }, + + /** + * Returns the distance from the center of the Circle object to the given object + * (can be Circle, Point or anything with x/y properties) + * @method Phaser.Circle#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round=false] - Round the distance to the nearest integer. + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y); + return round ? Math.round(distance) : distance; + + }, + + /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. + * @method Phaser.Circle#clone + * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} The cloned Circle object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Circle(this.x, this.y, this.diameter); + } + else + { + output.setTo(this.x, this.y, this.diameter); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Circle object. + * @method Phaser.Circle#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this circle, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Circle.contains(this, x, y); + + }, + + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method Phaser.Circle#circumferencePoint + * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ + circumferencePoint: function (angle, asDegrees, out) { + + return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out); + + }, + + + /** + * Creates or positions points on the circle. + * + * The points are equally distributed in the half-closed interval [startAngle, endAngle). The default arc is the entire circle. + * + * If the `out` argument is omitted, this method creates and returns an array of {@link Phaser.Point points}. If an array is passed as `out`, its items are treated as points and placed in the same way. + * + * @param {type} [steps=60] - The number of points to place. + * @param {type} [startAngle=0] - The starting angle in radians (unless asDegrees is true). + * @param {type} [endAngle=Phaser.Math.PI2] - The end angle in radians (unless asDegrees is true). + * @param {type} [asDegrees=false] - Are the given angles in radians (false) or degrees (true)? + * @param {any[]} [out] - An array of points or point-like objects (e.g., sprites). It should start at index 0 and its length should be equal to or greater than `steps`. + * @return {any[]} - The modified `out` argument or a new array of points. + */ + sample: function (steps, startAngle, endAngle, asDegrees, out) { + + if (!steps) { steps = 60; } + if (startAngle == null) { startAngle = 0; } + if (endAngle == null) { endAngle = Phaser.Math.PI2; } + if (!out) { out = []; } + + var i = 0; + + while (i < steps) + { + this.circumferencePoint( + Phaser.Math.linear(startAngle, endAngle, i / steps), + asDegrees, + out[i] || (out[i] = new Phaser.Point()) + ); + + i += 1; + } + + return out; + + }, + + /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method Phaser.Circle#offset + * @param {number} dx - Moves the x value of the Circle object by this amount. + * @param {number} dy - Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Circle#offsetPoint + * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). + * @return {Circle} This Circle object. + */ + offsetPoint: function (point) { + return this.offset(point.x, point.y); + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Circle#toString + * @return {string} a string representation of the instance. + */ + toString: function () { + return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; + } + +}; + +Phaser.Circle.prototype.constructor = Phaser.Circle; + +/** +* The largest distance between any two points on the circle. The same as the radius * 2. +* +* @name Phaser.Circle#diameter +* @property {number} diameter - Gets or sets the diameter of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "diameter", { + + get: function () { + return this._diameter; + }, + + set: function (value) { + + if (value > 0) + { + this._diameter = value; + this._radius = value * 0.5; + } + } + +}); + +/** +* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. +* @name Phaser.Circle#radius +* @property {number} radius - Gets or sets the radius of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "radius", { + + get: function () { + return this._radius; + }, + + set: function (value) { + + if (value > 0) + { + this._radius = value; + this._diameter = value * 2; + } + + } + +}); + +/** +* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#left +* @propety {number} left - Gets or sets the value of the leftmost point of the circle. +*/ +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; + } + + } + +}); + +/** +* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. +* @name Phaser.Circle#right +* @property {number} right - Gets or sets the value of the rightmost point of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "right", { + + get: function () { + return this.x + this._radius; + }, + + set: function (value) { + + if (value < this.x) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.x; + } + + } + +}); + +/** +* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#top +* @property {number} top - Gets or sets the top of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "top", { + + get: function () { + return this.y - this._radius; + }, + + set: function (value) { + + if (value > this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = this.y - value; + } + + } + +}); + +/** +* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. +* @name Phaser.Circle#bottom +* @property {number} bottom - Gets or sets the bottom of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "bottom", { + + get: function () { + return this.y + this._radius; + }, + + set: function (value) { + + if (value < this.y) + { + this._radius = 0; + this._diameter = 0; + } + else + { + this.radius = value - this.y; + } + + } + +}); + +/** +* The area of this Circle. +* @name Phaser.Circle#area +* @property {number} area - The area of this circle. +* @readonly +*/ +Object.defineProperty(Phaser.Circle.prototype, "area", { + + get: function () { + + if (this._radius > 0) + { + return Math.PI * this._radius * this._radius; + } + else + { + return 0; + } + + } + +}); + +/** +* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. +* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. +* @name Phaser.Circle#empty +* @property {boolean} empty - Gets or sets the empty state of the circle. +*/ +Object.defineProperty(Phaser.Circle.prototype, "empty", { + + get: function () { + return (this._diameter === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Circle object. +* @method Phaser.Circle.contains +* @param {Phaser.Circle} a - The Circle to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this circle, otherwise false. +*/ +Phaser.Circle.contains = function (a, x, y) { + + // Check if x/y are within the bounds first + 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; + } + +}; + +/** +* Determines whether the two Circle objects match. This method compares the x, y and diameter properties. +* @method Phaser.Circle.equals +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. +*/ +Phaser.Circle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.diameter === b.diameter); + +}; + +/** +* Determines whether the two Circle objects intersect. +* This method checks the radius distances between the two Circle objects to see if they intersect. +* @method Phaser.Circle.intersects +* @param {Phaser.Circle} a - The first Circle object. +* @param {Phaser.Circle} b - The second Circle object. +* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. +*/ +Phaser.Circle.intersects = function (a, b) { + + return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius)); + +}; + +/** +* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. +* @method Phaser.Circle.circumferencePoint +* @param {Phaser.Circle} a - The first Circle object. +* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. +* @return {Phaser.Point} The Point object holding the result. +*/ +Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) { + + if (asDegrees === undefined) { asDegrees = false; } + if (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; + +}; + +/** +* Checks if the given Circle and Rectangle objects intersect. +* @method Phaser.Circle.intersectsRectangle +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Rectangle} r - The Rectangle object to test. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +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; + +}; + +/** +* Checks if the given Circle and Line objects intersect. +* @method Phaser.Circle.intersectsLine +* @param {Phaser.Circle} c - The Circle object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnpoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Circle.intersectsLine = function (c, l, returnPoints) { + var h = c.x; + var k = c.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = c.radius; + var b = c.radius; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Circle = Phaser.Circle; + +/** +* @author Richard Davey +* @author Chad Engler +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a Ellipse object. A curve on a plane surrounding two focal points. +* +* @class Phaser.Ellipse +* @constructor +* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. +* @param {number} [width=0] - The overall width of this ellipse. +* @param {number} [height=0] - The overall height of this ellipse. +*/ +Phaser.Ellipse = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.x = x; + + /** + * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ + this.y = y; + + /** + * @property {number} width - The overall width of this ellipse. + */ + this.width = width; + + /** + * @property {number} height - The overall height of this ellipse. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ELLIPSE; + +}; + +Phaser.Ellipse.prototype = { + + /** + * Sets the members of the Ellipse to the specified values. + * @method Phaser.Ellipse#setTo + * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} width - The overall width of this ellipse. + * @param {number} height - The overall height of this ellipse. + * @return {Phaser.Ellipse} This Ellipse object. + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. + * + * @method Phaser.Ellipse#getBounds + * @return {Phaser.Rectangle} The bounds of the Ellipse. + */ + getBounds: function () { + + return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Ellipse. + * + * @method Phaser.Ellipse#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Ellipse} This Ellipse object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Ellipse to any given object. + * @method Phaser.Ellipse#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ + copyTo: function(dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. + * @method Phaser.Ellipse#clone + * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. + * @return {Phaser.Ellipse} The cloned Ellipse object. + */ + clone: function(output) { + + if (output === undefined || output === null) + { + output = new Phaser.Ellipse(this.x, this.y, this.width, this.height); + } + else + { + output.setTo(this.x, this.y, this.width, this.height); + } + + return output; + + }, + + /** + * Return true if the given x/y coordinates are within this Ellipse object. + * + * @method Phaser.Ellipse#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this ellipse, otherwise false. + */ + contains: function (x, y) { + + return Phaser.Ellipse.contains(this, x, y); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Ellipse. + * + * @method Phaser.Ellipse#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var p = Math.random() * Math.PI * 2; + var r = Math.random(); + + out.x = Math.sqrt(r) * Math.cos(p); + out.y = Math.sqrt(r) * Math.sin(p); + + out.x = this.x + (out.x * this.width / 2.0); + out.y = this.y + (out.y * this.height / 2.0); + + return out; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Ellipse#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]"; + } + +}; + +Phaser.Ellipse.prototype.constructor = Phaser.Ellipse; + +/** +* The left coordinate of the Ellipse. The same as the X coordinate. +* @name Phaser.Ellipse#left +* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + + this.x = value; + + } + +}); + +/** +* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. +* @name Phaser.Ellipse#right +* @property {number} right - Gets or sets the value of the rightmost point of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "right", { + + get: function () { + return this.x + this.width; + }, + + set: function (value) { + + if (value < this.x) + { + this.width = 0; + } + else + { + this.width = value - this.x; + } + } + +}); + +/** +* The top of the Ellipse. The same as its y property. +* @name Phaser.Ellipse#top +* @property {number} top - Gets or sets the top of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "top", { + + get: function () { + return this.y; + }, + + set: function (value) { + this.y = value; + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. +* @name Phaser.Ellipse#bottom +* @property {number} bottom - Gets or sets the bottom of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value < this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + } + +}); + +/** +* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. +* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. +* @name Phaser.Ellipse#empty +* @property {boolean} empty - Gets or sets the empty state of the ellipse. +*/ +Object.defineProperty(Phaser.Ellipse.prototype, "empty", { + + get: function () { + return (this.width === 0 || this.height === 0); + }, + + set: function (value) { + + if (value === true) + { + this.setTo(0, 0, 0, 0); + } + + } + +}); + +/** +* Return true if the given x/y coordinates are within the Ellipse object. +* +* @method Phaser.Ellipse.contains +* @param {Phaser.Ellipse} a - The Ellipse to be checked. +* @param {number} x - The X value of the coordinate to test. +* @param {number} y - The Y value of the coordinate to test. +* @return {boolean} True if the coordinates are within this ellipse, otherwise false. +*/ +Phaser.Ellipse.contains = function (a, x, y) { + + if (a.width <= 0 || a.height <= 0) { + return false; + } + + // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5 + var normx = ((x - a.x) / a.width) - 0.5; + var normy = ((y - a.y) / a.height) - 0.5; + + normx *= normx; + normy *= normy; + + return (normx + normy < 0.25); + +}; + +/** +* Checks if the given Ellipse and Line objects intersect. +* @method Phaser.Ellipse.intersectsLine +* @param {Phaser.Ellipse} e - The Ellipse object to test. +* @param {Phaser.Line} l - The Line object to test. +* @param {boolean} [returnPoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. +* @return {boolean} True if the two objects intersect, otherwise false. +*/ +Phaser.Ellipse.intersectsLine = function (e, l, returnPoints) { + var h = e.x; + var k = e.y; + var m = ((l.end.y - l.start.y) / (l.end.x - l.start.x)); + var n = l.end.y - (m * l.end.x); + var a = e.width / 2; + var b = e.height / 2; + var del = n + m * h; + + var x0 = (h * (b * b) - m * (a * a) * (n - k) + a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + var x1 = (h * (b * b) - m * (a * a) * (n - k) - a * b * (Math.sqrt((a * a) * (m * m) + (b * b) - (del * del) - (k * k) + (2 * del * k)))) / ((a * a) * (m * m) + (b * b)); + + var y0 = m * x0 + n; + var y1 = m * x1 + n; + var p0 = new Phaser.Point(x0, y0); + var p1 = new Phaser.Point(x1, y1); + var p0Exists = l.pointOnSegment(p0.x, p0.y, 0.01); + var p1Exists = l.pointOnSegment(p1.x, p1.y, 0.01); + + if (p0Exists && p1Exists) + { + return returnPoints ? [p0, p1] : true; + } + else if (p0Exists) + { + return returnPoints ? [p0] : true; + } + else if (p1Exists) + { + return returnPoints ? [p1] : true; + } + else + { + return returnPoints ? [] : false; + } +}; + + +// Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Ellipse = Phaser.Ellipse; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Line object with a start and an end point. +* +* @class Phaser.Line +* @constructor +* @param {number} [x1=0] - The x coordinate of the start of the line. +* @param {number} [y1=0] - The y coordinate of the start of the line. +* @param {number} [x2=0] - The x coordinate of the end of the line. +* @param {number} [y2=0] - The y coordinate of the end of the line. +*/ +Phaser.Line = function (x1, y1, x2, y2) { + + x1 = x1 || 0; + y1 = y1 || 0; + x2 = x2 || 0; + y2 = y2 || 0; + + /** + * @property {Phaser.Point} start - The start point of the line. + */ + this.start = new Phaser.Point(x1, y1); + + /** + * @property {Phaser.Point} end - The end point of the line. + */ + this.end = new Phaser.Point(x2, y2); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.LINE; + +}; + +Phaser.Line.prototype = { + + /** + * Sets the components of the Line to the specified values. + * + * @method Phaser.Line#setTo + * @param {number} [x1=0] - The x coordinate of the start of the line. + * @param {number} [y1=0] - The y coordinate of the start of the line. + * @param {number} [x2=0] - The x coordinate of the end of the line. + * @param {number} [y2=0] - The y coordinate of the end of the line. + * @return {Phaser.Line} This line object + */ + setTo: function (x1, y1, x2, y2) { + + this.start.setTo(x1, y1); + this.end.setTo(x2, y2); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given points. + * + * @param {any} start - A {@link Phaser.Point} or point-like object. + * @param {any} end - A {@link Phaser.Point} or point-like object. + * @return {Phaser.Line} - This line object. + */ + fromPoints: function (start, end) { + + this.setTo(start.x, start.y, end.x, end.y); + + return this; + + }, + + /** + * Sets the line to match the x/y coordinates of the two given sprites. + * Can optionally be calculated from their center coordinates. + * + * @method Phaser.Line#fromSprite + * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {boolean} [useCenter=false] - If true it will use startSprite.centerX, if false startSprite.x. + * @return {Phaser.Line} This line object + */ + fromSprite: function (startSprite, endSprite, useCenter) { + + if (useCenter === undefined) { useCenter = false; } + + if (useCenter) + { + return this.setTo(startSprite.centerX, startSprite.centerY, endSprite.centerX, endSprite.centerY); + } + + return this.fromPoints(startSprite, endSprite); + + }, + + /** + * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. + * + * @method Phaser.Line#fromAngle + * @param {number} x - The x coordinate of the start of the line. + * @param {number} y - The y coordinate of the start of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line in pixels. + * @return {Phaser.Line} This line object + */ + fromAngle: function (x, y, angle, length) { + + this.start.setTo(x, y); + this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length)); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place from the center of the line. + * If you wish to rotate around a different point see Line.rotateAround. + * + * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. + * + * @method Phaser.Line#rotate + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotate: function (angle, asDegrees) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + this.start.rotate(cx, cy, angle, asDegrees); + this.end.rotate(cx, cy, angle, asDegrees); + + return this; + + }, + + /** + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place around the coordinates given. + * + * @method Phaser.Line#rotateAround + * @param {number} x - The x coordinate to offset the rotation from. + * @param {number} y - The y coordinate to offset the rotation from. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ + rotateAround: function (x, y, angle, asDegrees) { + + this.start.rotate(x, y, angle, asDegrees); + this.end.rotate(x, y, angle, asDegrees); + + return this; + + }, + + /** + * Checks for intersection between this line and another Line. + * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * + * @method Phaser.Line#intersects + * @param {Phaser.Line} line - The line to check against this one. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ + intersects: function (line, asSegment, result) { + + return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result); + + }, + + /** + * Returns the reflected angle between two lines. + * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. + * + * @method Phaser.Line#reflect + * @param {Phaser.Line} line - The line to reflect off this line. + * @return {number} The reflected angle in radians. + */ + reflect: function (line) { + + return Phaser.Line.reflect(this, line); + + }, + + /** + * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. + * + * @method Phaser.Line#midPoint + * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. + * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. + */ + midPoint: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = (this.start.x + this.end.x) / 2; + out.y = (this.start.y + this.end.y) / 2; + + return out; + + }, + + /** + * Centers this Line on the given coordinates. + * + * The line is centered by positioning the start and end points so that the lines midpoint matches + * the coordinates given. + * + * @method Phaser.Line#centerOn + * @param {number} x - The x position to center the line on. + * @param {number} y - The y position to center the line on. + * @return {Phaser.Line} This line object + */ + centerOn: function (x, y) { + + var cx = (this.start.x + this.end.x) / 2; + var cy = (this.start.y + this.end.y) / 2; + + var tx = x - cx; + var ty = y - cy; + + this.start.add(tx, ty); + this.end.add(tx, ty); + + }, + + /** + * Tests if the given coordinates fall on this line. See {@link #pointOnSegment} to test against just the line segment. + * + * @method Phaser.Line#pointOnLine + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line, false if not. + */ + pointOnLine: function (x, y, epsilon) { + + return Phaser.Math.fuzzyEqual((x - this.start.x) * (this.end.y - this.start.y), (this.end.x - this.start.x) * (y - this.start.y), epsilon || 0); + + }, + + /** + * Tests if the given coordinates fall on this line and within the segment. See {@link #pointOnLine} to test against just the line. + * + * @method Phaser.Line#pointOnSegment + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line and segment, false if not. + */ + pointOnSegment: function (x, y, epsilon) { + + var xMin = Math.min(this.start.x, this.end.x); + var xMax = Math.max(this.start.x, this.end.x); + var yMin = Math.min(this.start.y, this.end.y); + var yMax = Math.max(this.start.y, this.end.y); + + return (this.pointOnLine(x, y, epsilon) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)); + + }, + + /** + * Picks a random point from anywhere on the Line segment and returns it. + * + * @method Phaser.Line#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var t = Math.random(); + + out.x = this.start.x + t * (this.end.x - this.start.x); + out.y = this.start.y + t * (this.end.y - this.start.y); + + return out; + + }, + + /** + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * The start and end points are rounded before this runs as the algorithm works on integers. + * + * @method Phaser.Line#coordinatesOnLine + * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. + * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. + * @return {array} An array of coordinates. + */ + coordinatesOnLine: function (stepRate, results) { + + if (stepRate === undefined) { stepRate = 1; } + if (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 < x2) ? 1 : -1; + var sy = (y1 < y2) ? 1 : -1; + var err = dx - dy; + + results.push([x1, y1]); + + var i = 1; + + while (!((x1 === x2) && (y1 === y2))) + { + var e2 = err << 1; + + if (e2 > -dy) + { + err -= dy; + x1 += sx; + } + + if (e2 < dx) + { + err += dx; + y1 += sy; + } + + if (i % stepRate === 0) + { + results.push([x1, y1]); + } + + i++; + + } + + return results; + + }, + + /** + * Returns a new Line object with the same values for the start and end properties as this Line object. + * @method Phaser.Line#clone + * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned. + * @return {Phaser.Line} The cloned Line object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y); + } + else + { + output.setTo(this.start.x, this.start.y, this.end.x, this.end.y); + } + + return output; + + } + +}; + +/** +* @name Phaser.Line#length +* @property {number} length - Gets the length of the line segment. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "length", { + + get: function () { + return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#angle +* @property {number} angle - Gets the angle of the line in radians. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "angle", { + + get: function () { + return Phaser.Point.angle(this.end, this.start); + } + +}); + +/** +* @name Phaser.Line#slope +* @property {number} slope - Gets the slope of the line (y/x). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "slope", { + + get: function () { + return (this.end.y - this.start.y) / (this.end.x - this.start.x); + } + +}); + +/** +* @name Phaser.Line#perpSlope +* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "perpSlope", { + + get: function () { + return -((this.end.x - this.start.x) / (this.end.y - this.start.y)); + } + +}); + +/** +* @name Phaser.Line#x +* @property {number} x - Gets the x coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "x", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#y +* @property {number} y - Gets the y coordinate of the top left of the bounds around this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "y", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#left +* @property {number} left - Gets the left-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "left", { + + get: function () { + return Math.min(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#right +* @property {number} right - Gets the right-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "right", { + + get: function () { + return Math.max(this.start.x, this.end.x); + } + +}); + +/** +* @name Phaser.Line#top +* @property {number} top - Gets the top-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "top", { + + get: function () { + return Math.min(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#bottom +* @property {number} bottom - Gets the bottom-most point of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "bottom", { + + get: function () { + return Math.max(this.start.y, this.end.y); + } + +}); + +/** +* @name Phaser.Line#width +* @property {number} width - Gets the width of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "width", { + + get: function () { + return Math.abs(this.start.x - this.end.x); + } + +}); + +/** +* @name Phaser.Line#height +* @property {number} height - Gets the height of this bounds of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "height", { + + get: function () { + return Math.abs(this.start.y - this.end.y); + } + +}); + +/** +* @name Phaser.Line#normalX +* @property {number} normalX - Gets the x component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalX", { + + get: function () { + return Math.cos(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalY +* @property {number} normalY - Gets the y component of the left-hand normal of this line. +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalY", { + + get: function () { + return Math.sin(this.angle - 1.5707963267948966); + } + +}); + +/** +* @name Phaser.Line#normalAngle +* @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) +* @readonly +*/ +Object.defineProperty(Phaser.Line.prototype, "normalAngle", { + + get: function () { + return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI); + } + +}); + +/** +* Checks for intersection between two lines as defined by the given start and end points. +* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersectsPoints +* @param {Phaser.Point} a - The start of the first Line to be checked. +* @param {Phaser.Point} b - The end of the first line to be checked. +* @param {Phaser.Point} e - The start of the second Line to be checked. +* @param {Phaser.Point} f - The end of the second line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) { + + if (asSegment === undefined) { asSegment = true; } + if (result === undefined) { result = new Phaser.Point(); } + + var a1 = b.y - a.y; + var a2 = f.y - e.y; + var b1 = a.x - b.x; + var b2 = e.x - f.x; + var c1 = (b.x * a.y) - (a.x * b.y); + var c2 = (f.x * e.y) - (e.x * f.y); + var denom = (a1 * b2) - (a2 * b1); + + if (denom === 0) + { + return null; + } + + result.x = ((b1 * c2) - (b2 * c1)) / denom; + result.y = ((a2 * c1) - (a1 * c2)) / denom; + + if (asSegment) + { + var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y)); + var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc; + var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc; + + if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) + { + return result; + } + else + { + return null; + } + } + + return result; + +}; + +/** +* Checks for intersection between two lines. +* If asSegment is true it will check for segment intersection. +* If asSegment is false it will check for line intersection. +* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. +* Adapted from code by Keith Hair +* +* @method Phaser.Line.intersects +* @param {Phaser.Line} a - The first Line to be checked. +* @param {Phaser.Line} b - The second Line to be checked. +* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. +* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. +* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. +*/ +Phaser.Line.intersects = function (a, b, asSegment, result) { + + return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result); + +}; + +/** +* Checks for intersection between the Line and a Rectangle shape, or a rectangle-like +* object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. +* +* An intersection is considered valid if: +* +* The line starts within or ends within the rectangle; or +* The line segment intersects one of the 4 rectangle edges; and +* The line has a non-zero length; and +* The rectangle is not empty. +* +* For the purposes of this function rectangles are considered 'solid'. +* +* @method Phaser.Line.intersectsRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle. +*/ +Phaser.Line.intersectsRectangle = function (line, rect) { + + // Quick bail out + if (line.length === 0 || rect.empty) + { + return false; + } + + var x1 = line.start.x; + var y1 = line.start.y; + + var x2 = line.end.x; + var y2 = line.end.y; + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + + var t = 0; + + // If the start or end of the line is inside the rect then we assume + // collision, as rects are solid for our use-case. + + if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || + (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) + { + return true; + } + + if (x1 < bx1 && x2 >= bx1) + { + // Left edge + t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); + + if (t > by1 && t <= by2) + { + return true; + } + } + else if (x1 > bx2 && x2 <= bx2) + { + // Right edge + t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); + + if (t >= by1 && t <= by2) + { + return true; + } + } + + if (y1 < by1 && y2 >= by1) + { + // Top edge + t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + else if (y1 > by2 && y2 <= by2) + { + // Bottom edge + t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); + + if (t >= bx1 && t <= bx2) + { + return true; + } + } + + return false; + +}; + +/** +* Finds the closest intersection between the Line and a Rectangle shape, or a rectangle-like +* object, such as a Sprite or Body. +* +* @method Phaser.Line.intersectionWithRectangle +* @param {Phaser.Line} line - The line to check for intersection with. +* @param {Phaser.Rectangle} rect - The rectangle, or rectangle-like object, to check for intersection with. +* @param {Phaser.Point} [result] - A Point object to store the result in. +* @return {?Phaser.Point} - The intersection closest to the Line's start, or null if there is no intersection. +*/ +Phaser.Line.intersectionWithRectangle = function (line, rect, result) { + + var self = Phaser.Line.intersectionWithRectangle; + + if (!result) + { + result = new Phaser.Point(); + } + + if (!self.edges) + { + self.edges = [new Phaser.Line(), new Phaser.Line(), new Phaser.Line(), new Phaser.Line()]; + } + + if (!self.edgeIntersection) + { + self.edgeIntersection = new Phaser.Point(); + } + + var edges = self.edges; + var edgeIntersection = self.edgeIntersection.set(0); + + var bx1 = rect.x; + var by1 = rect.y; + var bx2 = rect.right; + var by2 = rect.bottom; + var closestDistance = Infinity; + + edges[0].setTo(bx1, by1, bx2, by1); + edges[1].setTo(bx1, by2, bx2, by2); + edges[2].setTo(bx1, by1, bx1, by2); + edges[3].setTo(bx2, by1, bx2, by2); + + for (var edge, i = 0; (edge = edges[i]); i++) + { + if (line.intersects(edge, true, edgeIntersection)) + { + var distance = line.start.distance(edgeIntersection); + + if (distance < closestDistance) + { + closestDistance = distance; + result.copyFrom(edgeIntersection); + } + } + } + + if (distance != null) + { + return result; + } + + return null; + +}; + +/** +* Returns the reflected angle between two lines. +* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. +* +* @method Phaser.Line.reflect +* @param {Phaser.Line} a - The base line. +* @param {Phaser.Line} b - The line to be reflected from the base line. +* @return {number} The reflected angle in radians. +*/ +Phaser.Line.reflect = function (a, b) { + + return 2 * b.normalAngle - 3.141592653589793 - a.angle; + +}; + +/** +* @author Mat Groves http://matgroves.com/ @Doormat23 +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. +* +* It is represented like so: +* +* | a | b | tx | +* | c | d | ty | +* | 0 | 0 | 1 | +* +* @class Phaser.Matrix +* @constructor +* @param {number} [a=1] - Horizontal scaling +* @param {number} [b=0] - Horizontal skewing +* @param {number} [c=0] - Vertical skewing +* @param {number} [d=1] - Vertical scaling +* @param {number} [tx=0] - Horizontal translation +* @param {number} [ty=0] - Vertical translation +*/ +Phaser.Matrix = function (a, b, c, d, tx, ty) { + + if (a === undefined || a === null) { a = 1; } + if (b === undefined || b === null) { b = 0; } + if (c === undefined || c === null) { c = 0; } + if (d === undefined || d === null) { d = 1; } + if (tx === undefined || tx === null) { tx = 0; } + if (ty === undefined || ty === null) { ty = 0; } + + /** + * @property {number} a + * @default 1 + */ + this.a = a; + + /** + * @property {number} b + * @default 0 + */ + this.b = b; + + /** + * @property {number} c + * @default 0 + */ + this.c = c; + + /** + * @property {number} d + * @default 1 + */ + this.d = d; + + /** + * @property {number} tx + * @default 0 + */ + this.tx = tx; + + /** + * @property {number} ty + * @default 0 + */ + this.ty = ty; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.MATRIX; + +}; + +Phaser.Matrix.prototype = { + + /** + * Sets the values of this Matrix to the values in the given array. + * + * The Array elements should be set as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @method Phaser.Matrix#fromArray + * @param {Array} array - The array to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + fromArray: function (array) { + + return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]); + + }, + + /** + * Sets the values of this Matrix to the given values. + * + * @method Phaser.Matrix#setTo + * @param {number} a - Horizontal scaling + * @param {number} b - Horizontal skewing + * @param {number} c - Vertical skewing + * @param {number} d - Vertical scaling + * @param {number} tx - Horizontal translation + * @param {number} ty - Vertical translation + * @return {Phaser.Matrix} This Matrix object. + */ + setTo: function (a, b, c, d, tx, ty) { + + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + + }, + + /** + * Creates a new Matrix object based on the values of this Matrix. + * If you provide the output parameter the values of this Matrix will be copied over to it. + * If the output parameter is blank a new Matrix object will be created. + * + * @method Phaser.Matrix#clone + * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created. + * @return {Phaser.Matrix} A clone of this Matrix. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); + } + else + { + output.a = this.a; + output.b = this.b; + output.c = this.c; + output.d = this.d; + output.tx = this.tx; + output.ty = this.ty; + } + + return output; + + }, + + /** + * Copies the properties from this Matrix to the given Matrix. + * + * @method Phaser.Matrix#copyTo + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} The destination Matrix object. + */ + copyTo: function (matrix) { + + matrix.copyFrom(this); + + return matrix; + + }, + + /** + * Copies the properties from the given Matrix into this Matrix. + * + * @method Phaser.Matrix#copyFrom + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ + copyFrom: function (matrix) { + + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + + return this; + + }, + + /** + * Creates a Float32 Array with values populated from this Matrix object. + * + * @method Phaser.Matrix#toArray + * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not. + * @param {Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created. + * @return {Float32Array} The newly created array which contains the matrix. + */ + toArray: function (transpose, array) { + + if (array === undefined) { array = new Float32Array(9); } + + if (transpose) + { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else + { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + + }, + + /** + * Get a new position with the current transformation applied. + * + * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) + * + * @method Phaser.Matrix#apply + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, transformed through this matrix. + */ + apply: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + newPos.x = this.a * pos.x + this.c * pos.y + this.tx; + newPos.y = this.b * pos.x + this.d * pos.y + this.ty; + + return newPos; + + }, + + /** + * Get a new position with the inverse of the current transformation applied. + * + * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) + * + * @method Phaser.Matrix#applyInverse + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, inverse transformed through this matrix. + */ + applyInverse: function (pos, newPos) { + + if (newPos === undefined) { newPos = new Phaser.Point(); } + + var id = 1 / (this.a * this.d + this.c * -this.b); + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + + }, + + /** + * Translates the matrix on the x and y. + * This is the same as Matrix.tx += x. + * + * @method Phaser.Matrix#translate + * @param {number} x - The x value to translate on. + * @param {number} y - The y value to translate on. + * @return {Phaser.Matrix} This Matrix object. + */ + translate: function (x, y) { + + this.tx += x; + this.ty += y; + + return this; + + }, + + /** + * Applies a scale transformation to this matrix. + * + * @method Phaser.Matrix#scale + * @param {number} x - The amount to scale horizontally. + * @param {number} y - The amount to scale vertically. + * @return {Phaser.Matrix} This Matrix object. + */ + scale: function (x, y) { + + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + + }, + + /** + * Applies a rotation transformation to this matrix. + * + * @method Phaser.Matrix#rotate + * @param {number} angle - The angle to rotate by, given in radians. + * @return {Phaser.Matrix} This Matrix object. + */ + rotate: function (angle) { + + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos-this.b * sin; + this.b = a1 * sin+this.b * cos; + this.c = c1 * cos-this.d * sin; + this.d = c1 * sin+this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + + }, + + /** + * Appends the given Matrix to this Matrix. + * + * @method Phaser.Matrix#append + * @param {Phaser.Matrix} matrix - The matrix to append to this one. + * @return {Phaser.Matrix} This Matrix object. + */ + append: function (matrix) { + + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + + }, + + /** + * Resets this Matrix to an identity (default) matrix. + * + * @method Phaser.Matrix#identity + * @return {Phaser.Matrix} This Matrix object. + */ + identity: function () { + + return this.setTo(1, 0, 0, 1, 0, 0); + + } + +}; + +Phaser.identityMatrix = new Phaser.Matrix(); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. +* The following code creates a point at (0,0): +* `var myPoint = new Phaser.Point();` +* You can also use them as 2D Vectors and you'll find different vector related methods in this class. +* +* @class Phaser.Point +* @constructor +* @param {number} [x=0] - The horizontal position of this Point. +* @param {number} [y=0] - The vertical position of this Point. +*/ +Phaser.Point = function (x, y) { + + x = x || 0; + y = y || 0; + + /** + * @property {number} x - The x value of the point. + */ + this.x = x; + + /** + * @property {number} y - The y value of the point. + */ + this.y = y; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINT; + +}; + +Phaser.Point.prototype = { + + /** + * Copies the x and y properties from any given object to this Point. + * + * @method Phaser.Point#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Point} This Point object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y); + + }, + + /** + * Inverts the x and y values of this Point + * + * @method Phaser.Point#invert + * @return {Phaser.Point} This Point object. + */ + invert: function () { + + return this.setTo(this.y, this.x); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.setTo(2)` is the same as `Point.setTo(2, 2)` + * + * Identical to {@link #set}. + * + * @method Phaser.Point#setTo + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setTo: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.set(2)` is the same as `Point.set(2, 2)` + * + * Identical to {@link #setTo}. + * + * @method Phaser.Point#set + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + set: function (x, y) { + + return Phaser.Point.set(this, x, y); + + }, + + /** + * Sets the `x` and `y` values of this Point object from a given polar coordinate. + * + * @method Phaser.Point#setToPolar + * @param {number} azimuth - The angular coordinate, in radians (unless `asDegrees`). + * @param {number} [radius=1] - The radial coordinate (length). + * @param {boolean} [asDegrees=false] - True if `azimuth` is in degrees. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + setToPolar: function(azimuth, radius, asDegrees) { + + if (radius == null) { radius = 1; } + if (asDegrees) { azimuth = Phaser.Math.degToRad(azimuth); } + + return this.setTo(Math.cos(azimuth) * radius, Math.sin(azimuth) * radius); + + }, + + /** + * Adds the given x and y values to this Point. + * + * @method Phaser.Point#add + * @param {number} x - The value to add to Point.x. + * @param {number} y - The value to add to Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + add: function (x, y) { + + this.x += x; + this.y += y; + return this; + + }, + + /** + * Subtracts the given x and y values from this Point. + * + * @method Phaser.Point#subtract + * @param {number} x - The value to subtract from Point.x. + * @param {number} y - The value to subtract from Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + subtract: function (x, y) { + + this.x -= x; + this.y -= y; + return this; + + }, + + /** + * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. + * + * @method Phaser.Point#multiply + * @param {number} x - The value to multiply Point.x by. + * @param {number} y - The value to multiply Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + multiply: function (x, y) { + + this.x *= x; + this.y *= y; + return this; + + }, + + /** + * Divides Point.x and Point.y by the given x and y values. + * + * @method Phaser.Point#divide + * @param {number} x - The value to divide Point.x by. + * @param {number} y - The value to divide Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ + divide: function (x, y) { + + this.x /= x; + this.y /= y; + return this; + + }, + + /** + * Clamps the x value of this Point to be between the given min and max. + * + * @method Phaser.Point#clampX + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampX: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + return this; + + }, + + /** + * Clamps the y value of this Point to be between the given min and max + * + * @method Phaser.Point#clampY + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clampY: function (min, max) { + + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * Clamps this Point object values to be between the given min and max. + * + * @method Phaser.Point#clamp + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ + clamp: function (min, max) { + + this.x = Phaser.Math.clamp(this.x, min, max); + this.y = Phaser.Math.clamp(this.y, min, max); + return this; + + }, + + /** + * If this Point is not within the given object, moves it inside (at the nearest edge). + * + * @method Phaser.Point#clip + * @param {any} rect - A {@link Phaser.Rectangle} or any object with left, top, right, and bottom properties. + * @return {Phaser.Point} This Point object. + */ + clip: function (rect) { + + var left = rect.left, top = rect.top, right = rect.right, bottom = rect.bottom; + + if (this.x < left ) { this.x = left; } + else if (this.x > right) { this.x = right; } + if (this.y < top) { this.y = top; } + else if (this.y > bottom) { this.y = bottom; } + + return this; + + }, + + /** + * Creates a copy of the given Point. + * + * @method Phaser.Point#clone + * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The new Point object. + */ + clone: function (output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(this.x, this.y); + } + else + { + output.setTo(this.x, this.y); + } + + return output; + + }, + + /** + * Copies the x and y properties from this Point to any given object. + * + * @method Phaser.Point#copyTo + * @param {any} dest - The object to copy to. + * @return {object} The dest object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + + return dest; + + }, + + /** + * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) + * + * @method Phaser.Point#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round] - Round the distance to the nearest integer (default false). + * @return {number} The distance between this Point object and the destination Point object. + */ + distance: function (dest, round) { + + return Phaser.Point.distance(this, dest, round); + + }, + + /** + * Determines whether the given objects x/y values are equal to this Point object. + * + * @method Phaser.Point#equals + * @param {Phaser.Point|any} a - The object to compare with this Point. + * @return {boolean} A value of true if the x and y points are equal, otherwise false. + */ + equals: function (a) { + + return a.x === this.x && a.y === this.y; + + }, + + /** + * Determines whether a set of x-y coordinates are equal to this Point's. + * + * @method Phaser.Point#equalsXY + * @param {number} x - The x-coordinate to compare with this Point. + * @param {number} y - The y-coordinate to compare with this Point. + * @return {boolean} A value of true if the Point's coordinates are identical to the arguments, otherwise false. + */ + equalsXY: function (x, y) { + + return this.x === x && this.y === y; + + }, + + fuzzyEquals: function (a, epsilon) { + + return Phaser.Point.fuzzyEquals(this, a, epsilon); + + }, + + fuzzyEqualsXY: function (x, y, epsilon) { + + return Phaser.Point.fuzzyEqualsXY(this, x, y, epsilon); + + }, + + /** + * Returns the angle between this Point object and another object with public x and y properties. + * + * @method Phaser.Point#angle + * @param {Phaser.Point|any} a - The object to get the angle from this Point to. + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angle: function (a, asDegrees) { + + return this.angleXY(a.x, a.y, asDegrees); + + }, + + /** + * Returns the angle between this Point object and an x-y coordinate pair. + * + * @method Phaser.Point#angleXY + * @param {number} x - The x-coordinate + * @param {number} y - The y-coordinate + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ + angleXY: function (x, y, asDegrees) { + + var angle = Math.atan2(y - this.y, x - this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Returns the arctangent of this Point. + * + * @method Phaser.Point#atan + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where the vertex is (0, 0). Within [-pi, pi] or [-180deg, 180deg]. + */ + atan: function (asDegrees) { + + var angle = Math.atan2(this.y, this.x); + + if (asDegrees) + { + return Phaser.Math.radToDeg(angle); + } + else + { + return angle; + } + + }, + + /** + * Rotates this Point around the x/y coordinates given to the desired angle. + * + * @method Phaser.Point#rotate + * @param {number} x - The x coordinate of the anchor point. + * @param {number} y - The y coordinate of the anchor point. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {number} [distance] - An optional distance constraint between the Point and the anchor. + * @return {Phaser.Point} The modified point object. + */ + rotate: function (x, y, angle, asDegrees, distance) { + + return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance); + + }, + + /** + * Calculates the length of the Point object. + * + * @method Phaser.Point#getMagnitude + * @return {number} The length of the Point. + */ + getMagnitude: function () { + + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + + }, + + /** + * Calculates the length squared of the Point object. + * + * @method Phaser.Point#getMagnitudeSq + * @return {number} The length ^ 2 of the Point. + */ + getMagnitudeSq: function () { + + return (this.x * this.x) + (this.y * this.y); + + }, + + /** + * Alters the length of the Point without changing the direction. + * + * @method Phaser.Point#setMagnitude + * @param {number} magnitude - The desired magnitude of the resulting Point. + * @return {Phaser.Point} This Point object. + */ + setMagnitude: function (magnitude) { + + return this.normalize().multiply(magnitude, magnitude); + + }, + + /** + * Alters the Point object so that its length is 1, but it retains the same direction. + * + * @method Phaser.Point#normalize + * @return {Phaser.Point} This Point object. + */ + normalize: function () { + + if (!this.isZero()) + { + var m = this.getMagnitude(); + this.x /= m; + this.y /= m; + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at most the max value. + * + * @method Phaser.Point#limit + * @param {number} max - The maximum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#expand + */ + limit: function (max) { + + if (this.getMagnitudeSq() > max * max) + { + this.setMagnitude(max); + } + + return this; + + }, + + /** + * Alters the Point object so its magnitude is at least the min value. + * + * @method Phaser.Point#expand + * @param {number} min - The minimum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#limit + */ + expand: function (min) { + + if (this.getMagnitudeSq() < min * min) + { + this.setMagnitude(min); + } + + return this; + + }, + + /** + * Determine if this point is at 0,0. + * + * @method Phaser.Point#isZero + * @return {boolean} True if this Point is 0,0, otherwise false. + */ + isZero: function () { + + return (this.x === 0 && this.y === 0); + + }, + + /** + * The dot product of this and another Point object. + * + * @method Phaser.Point#dot + * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point. + * @return {number} The result. + */ + dot: function (a) { + + return ((this.x * a.x) + (this.y * a.y)); + + }, + + /** + * The cross product of this and another Point object. + * + * @method Phaser.Point#cross + * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point. + * @return {number} The result. + */ + cross: function (a) { + + return ((this.x * a.y) - (this.y * a.x)); + + }, + + /** + * Make this Point perpendicular (90 degrees rotation) + * + * @method Phaser.Point#perp + * @return {Phaser.Point} This Point object. + */ + perp: function () { + + return this.setTo(-this.y, this.x); + + }, + + /** + * Make this Point perpendicular (-90 degrees rotation) + * + * @method Phaser.Point#rperp + * @return {Phaser.Point} This Point object. + */ + rperp: function () { + + return this.setTo(this.y, -this.x); + + }, + + /** + * Right-hand normalize (make unit length) this Point. + * + * @method Phaser.Point#normalRightHand + * @return {Phaser.Point} This Point object. + */ + normalRightHand: function () { + + return this.setTo(this.y * -1, this.x); + + }, + + /** + * Math.floor() both the x and y properties of this Point. + * + * @method Phaser.Point#floor + * @return {Phaser.Point} This Point object. + */ + floor: function () { + + return this.setTo(Math.floor(this.x), Math.floor(this.y)); + + }, + + /** + * Math.ceil() both the x and y properties of this Point. + * + * @method Phaser.Point#ceil + * @return {Phaser.Point} This Point object. + */ + ceil: function () { + + return this.setTo(Math.ceil(this.x), Math.ceil(this.y)); + + }, + + /** + * Math.round() both the x and y properties of this Point. + * + * @method Phaser.Point#round + * @return {Phaser.Point} This Point object. + */ + round: function () { + + return this.setTo(Math.round(this.x), Math.round(this.y)); + + }, + + /** + * Returns a string representation of this object. + * + * @method Phaser.Point#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; + + } + +}; + +Phaser.Point.prototype.constructor = Phaser.Point; + +/** +* Adds the coordinates of two points together to create a new point. +* +* @method Phaser.Point.add +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.add = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x + b.x; + out.y = a.y + b.y; + + return out; + +}; + +/** +* Subtracts the coordinates of two points to create a new point. +* +* @method Phaser.Point.subtract +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.subtract = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x - b.x; + out.y = a.y - b.y; + + return out; + +}; + +/** +* Multiplies the coordinates of two points to create a new point. +* +* @method Phaser.Point.multiply +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiply = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x * b.x; + out.y = a.y * b.y; + + return out; + +}; + +/** +* Divides the coordinates of two points to create a new point. +* +* @method Phaser.Point.divide +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.divide = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = a.x / b.x; + out.y = a.y / b.y; + + return out; + +}; + +/** +* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. +* +* @method Phaser.Point.equals +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {boolean} A value of true if the Points are equal, otherwise false. +*/ +Phaser.Point.equals = function (a, b) { + + return a.x === b.x && a.y === b.y; + +}; + +Phaser.Point.equalsXY = function (a, x, y) { + + return a.x === x && a.y === y; + +}; + +Phaser.Point.fuzzyEquals = function (a, b, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, b.x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, b.y, epsilon); + +}; + +Phaser.Point.fuzzyEqualsXY = function (a, x, y, epsilon) { + + return Phaser.Math.fuzzyEquals(a.x, x, epsilon) && + Phaser.Math.fuzzyEquals(a.y, y, epsilon); + +}; + +/** +* Returns the angle between two Point objects. +* +* @method Phaser.Point.angle +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @return {number} The angle, where b is the vertex. Within [-pi, pi]. +*/ +Phaser.Point.angle = function (a, b) { + + return Math.atan2(a.y - b.y, a.x - b.x); + +}; + +/** +* Creates a negative Point. +* +* @method Phaser.Point.negative +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.negative = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.x, -a.y); + +}; + +/** +* Adds two 2D Points together and multiplies the result by the given scalar. +* +* @method Phaser.Point.multiplyAdd +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} s - The scaling value. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.multiplyAdd = function (a, b, s, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + b.x * s, a.y + b.y * s); + +}; + +/** +* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. +* +* @method Phaser.Point.interpolate +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.interpolate = function (a, b, f, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f); + +}; + +/** +* Return a perpendicular vector (90 degrees rotation) +* +* @method Phaser.Point.perp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.perp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(-a.y, a.x); + +}; + +/** +* Return a perpendicular vector (-90 degrees rotation) +* +* @method Phaser.Point.rperp +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.rperp = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y, -a.x); + +}; + +/** +* Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). +* +* @method Phaser.Point.distance +* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. +* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. +* @param {boolean} [round=false] - Round the distance to the nearest integer. +* @return {number} The distance between this Point object and the destination Point object. +*/ +Phaser.Point.distance = function (a, b, round) { + + var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y); + return round ? Math.round(distance) : distance; + +}; + +/** +* Project two Points onto another Point. +* +* @method Phaser.Point.project +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.project = function (a, b, out) { + + if (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; + +}; + +/** +* Project two Points onto a Point of unit length. +* +* @method Phaser.Point.projectUnit +* @param {Phaser.Point} a - The first Point object. +* @param {Phaser.Point} b - The second Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.projectUnit = function (a, b, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var amt = a.dot(b); + + if (amt !== 0) + { + out.setTo(amt * b.x, amt * b.y); + } + + return out; + +}; + +/** +* Right-hand normalize (make unit length) a Point. +* +* @method Phaser.Point.normalRightHand +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalRightHand = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + return out.setTo(a.y * -1, a.x); + +}; + +/** +* Normalize (make unit length) a Point. +* +* @method Phaser.Point.normalize +* @param {Phaser.Point} a - The Point object. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.normalize = function (a, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + var m = a.getMagnitude(); + + if (m !== 0) + { + out.setTo(a.x / m, a.y / m); + } + + return out; + +}; + +/** +* Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by +* the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument +* is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. +* +* The distance allows you to specify a distance constraint for the rotation between the point and the +* coordinates. If none is given the distance between the two is calculated and used. +* +* @method Phaser.Point.rotate +* @param {Phaser.Point} a - The Point object to rotate. +* @param {number} x - The x coordinate of the anchor point +* @param {number} y - The y coordinate of the anchor point +* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by. +* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? +* @param {number} [distance] - An optional distance constraint between the Point and the anchor. +* @return {Phaser.Point} The modified point object. +*/ +Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) { + + if (asDegrees) { angle = Phaser.Math.degToRad(angle); } + + if (distance === undefined) + { + a.subtract(x, y); + + var s = Math.sin(angle); + var c = Math.cos(angle); + + var tx = c * a.x - s * a.y; + var ty = s * a.x + c * a.y; + + a.x = tx + x; + a.y = ty + y; + } + else + { + var t = angle + Math.atan2(a.y - y, a.x - x); + a.x = x + distance * Math.cos(t); + a.y = y + distance * Math.sin(t); + } + + return a; + +}; + +/** +* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. +* +* @method Phaser.Point.centroid +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.centroid = function (points, out) { + + if (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 < pointslength; i++) + { + Phaser.Point.add(out, points[i], out); + } + + out.divide(pointslength, pointslength); + + return out; + +}; + +/** +* Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. +* If the object doesn't contain those properties a Point with x/y of zero will be returned. +* +* @method Phaser.Point.parse +* @static +* @param {object} obj - The object to parse. +* @param {string} [xProp='x'] - The property used to set the Point.x value. +* @param {string} [yProp='y'] - The property used to set the Point.y value. +* @return {Phaser.Point} The new Point object. +*/ +Phaser.Point.parse = function(obj, xProp, yProp) { + + xProp = xProp || 'x'; + yProp = yProp || 'y'; + + var point = new Phaser.Point(); + + if (obj[xProp]) + { + point.x = parseInt(obj[xProp], 10); + } + + if (obj[yProp]) + { + point.y = parseInt(obj[yProp], 10); + } + + return point; + +}; + +/** + * Tests a Point or Point-like object. + * + * @method Phaser.Point.isPoint + * @static + * @return {boolean} - True if the object has numeric x and y properties. + */ +Phaser.Point.isPoint = function(obj) { + + return (obj != null) && (typeof obj.x === 'number') && (typeof obj.y === 'number'); + +}; + +/** +* Sets the `x` and `y` values of an object and returns the object. +* +* @method Phaser.Point#set +* @static +* @param {object} obj - An object with numeric x and y properties. +* @param {number} x - The x value. +* @param {number} [y] - The y value. If not given the x value will be used in its place. +* @return {object} The object. Useful for chaining method calls. +*/ +Phaser.Point.set = function(obj, x, y) { + + obj.x = x || 0; + obj.y = y || ( (y !== 0) ? obj.x : 0 ); + + return obj; + +}; + +/** +* Sorts an array of points in a clockwise direction, relative to a reference point. +* +* The sort is clockwise relative to the display, starting from a 12 o'clock position. +* (In the Cartesian plane, it is anticlockwise, starting from the -y direction.) +* +* Example sequence: (0, -1), (1, 0), (0, 1), (-1, 0) +* +* @method Phaser.Point#sortClockwise +* @static +* @param {array} points - An array of Points or point-like objects (e.g., sprites). +* @param {object|Phaser.Point} [center] - The reference point. If omitted, the {@link #centroid} (midpoint) of the points is used. +* @return {array} The sorted array. +*/ +Phaser.Point.sortClockwise = function(points, center) { + + // Adapted from (ciamej) + + if (!center) + { + center = this.centroid(points); + } + + var cx = center.x; + var cy = center.y; + + var sort = function(a, b) { + if (a.x - cx >= 0 && b.x - cx < 0) + { + return -1; + } + + if (a.x - cx < 0 && b.x - cx >= 0) + { + return 1; + } + + if (a.x - cx === 0 && b.x - cx === 0) + { + if (a.y - cy >= 0 || b.y - cy >= 0) + { + return (a.y > b.y) ? 1 : -1; + } + + return (b.y > a.y) ? 1 : -1; + } + + // Compute the cross product of vectors (center -> a) * (center -> b) + var det = (a.x - cx) * -(b.y - cy) - (b.x - cx) * -(a.y - cy); + + if (det < 0) + { + return -1; + } + + if (det > 0) + { + return 1; + } + + // Points a and b are on the same line from the center + // Check which point is closer to the center + var d1 = (a.x - cx) * (a.x - cx) + (a.y - cy) * (a.y - cy); + var d2 = (b.x - cx) * (b.x - cx) + (b.y - cy) * (b.y - cy); + + return (d1 > d2) ? -1 : 1; + }; + + return points.sort(sort); + +}; + + +// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Point = Phaser.Point; + +/** +* @author Richard Davey +* @author Adrien Brault +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Polygon. +* +* The points can be set from a variety of formats: +* +* - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` +* - An array of objects with public x/y properties: `[obj1, obj2, ...]` +* - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` +* - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` +* - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` +* - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` +* +* @class Phaser.Polygon +* @constructor +* @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. +*/ +Phaser.Polygon = function () { + + /** + * @property {number} area - The area of this Polygon. + */ + this.area = 0; + + /** + * @property {array} _points - An array of Points that make up this Polygon. + * @private + */ + this._points = []; + + if (arguments.length > 0) + { + this.setTo.apply(this, arguments); + } + + /** + * @property {boolean} closed - Is the Polygon closed or not? + */ + this.closed = true; + + /** + * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ? + */ + this.flattened = false; + + /** + * @property {number} type - The base object type. + */ + this.type = Phaser.POLYGON; + +}; + +Phaser.Polygon.prototype = { + + /** + * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ] + * + * @method Phaser.Polygon#toNumberArray + * @param {array} [output] - The array to append the points to. If not specified a new array will be created. + * @return {array} The flattened array. + */ + toNumberArray: function (output) { + + if (output === undefined) { output = []; } + + for (var i = 0; i < this._points.length; i++) + { + if (typeof this._points[i] === 'number') + { + output.push(this._points[i]); + output.push(this._points[i + 1]); + i++; + } + else + { + output.push(this._points[i].x); + output.push(this._points[i].y); + } + } + + return output; + + }, + + /** + * Flattens this Polygon so the points are a sequence of numbers. + * Any Point objects found are removed and replaced with two numbers. + * Also sets the Polygon.flattened property to `true`. + * + * @method Phaser.Polygon#flatten + * @return {Phaser.Polygon} This Polygon object + */ + flatten: function () { + + this._points = this.toNumberArray(); + + this.flattened = true; + + return this; + + }, + + /** + * Creates a copy of the given Polygon. + * This is a deep clone, the resulting copy contains new Phaser.Point objects + * + * @method Phaser.Polygon#clone + * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created. + * @return {Phaser.Polygon} The cloned (`output`) polygon object. + */ + clone: function (output) { + + var points = this._points.slice(); + + if (output === undefined || output === null) + { + output = new Phaser.Polygon(points); + } + else + { + output.setTo(points); + } + + return output; + + }, + + /** + * Checks whether the x and y coordinates are contained within this polygon. + * + * @method Phaser.Polygon#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this polygon, otherwise false. + */ + contains: function (x, y) { + + // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva + + var inside = false; + + if (this.flattened) + { + for (var i = -2, j = this._points.length - 2; (i += 2) < this._points.length; j = i) + { + var ix = this._points[i]; + var iy = this._points[i + 1]; + + var jx = this._points[j]; + var jy = this._points[j + 1]; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + + } + else + { + for (var i = -1, j = this._points.length - 1; ++i < this._points.length; j = i) + { + var ix = this._points[i].x; + var iy = this._points[i].y; + + var jx = this._points[j].x; + var jy = this._points[j].y; + + if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) + { + inside = !inside; + } + } + } + + return inside; + + }, + + /** + * Sets this Polygon to the given points. + * + * The points can be set from a variety of formats: + * + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]` + * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` + * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` + * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` + * + * `setTo` may also be called without any arguments to remove all points. + * + * @method Phaser.Polygon#setTo + * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. + * @return {Phaser.Polygon} This Polygon object + */ + setTo: function (points) { + + this.area = 0; + this._points = []; + + if (arguments.length > 0) + { + // If points isn't an array, use arguments as the array + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments); + } + + var y0 = Number.MAX_VALUE; + + // Allows for mixed-type arguments + for (var i = 0, len = points.length; i < len; i++) + { + if (typeof points[i] === 'number') + { + var p = new PIXI.Point(points[i], points[i + 1]); + i++; + } + else if (Array.isArray(points[i])) + { + var p = new PIXI.Point(points[i][0], points[i][1]); + } + else + { + var p = new PIXI.Point(points[i].x, points[i].y); + } + + this._points.push(p); + + // Lowest boundary + if (p.y < y0) + { + y0 = p.y; + } + } + + this.calculateArea(y0); + } + + return this; + + }, + + /** + * Calcuates the area of the Polygon. This is available in the property Polygon.area + * + * @method Phaser.Polygon#calculateArea + * @private + * @param {number} y0 - The lowest boundary + * @return {number} The area of the Polygon. + */ + calculateArea: function (y0) { + + var p1; + var p2; + var avgHeight; + var width; + + for (var i = 0, len = this._points.length; i < len; i++) + { + p1 = this._points[i]; + + if (i === len - 1) + { + p2 = this._points[0]; + } + else + { + p2 = this._points[i + 1]; + } + + avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2; + width = p1.x - p2.x; + this.area += avgHeight * width; + } + + return this.area; + + } + +}; + +Phaser.Polygon.prototype.constructor = Phaser.Polygon; + +/** +* The points of this polygon. +* +* You can modify these with {@link Phaser.Polygon#setTo setTo}. +* +* @name Phaser.Polygon#points +* @property {Phaser.Point[]} points - The array of vertex points. +* @readonly +*/ +Object.defineProperty(Phaser.Polygon.prototype, 'points', { + + get: function() { + return this._points; + } + +}); + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Polygon = Phaser.Polygon; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. +* If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. +* +* @class Phaser.Rectangle +* @constructor +* @param {number} x - The x coordinate of the top-left corner of the Rectangle. +* @param {number} y - The y coordinate of the top-left corner of the Rectangle. +* @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. +*/ +Phaser.Rectangle = function (x, y, width, height) { + + x = x || 0; + y = y || 0; + width = width || 0; + height = height || 0; + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.RECTANGLE; + +}; + +Phaser.Rectangle.prototype = { + + /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method Phaser.Rectangle#offset + * @param {number} dx - Moves the x value of the Rectangle object by this amount. + * @param {number} dy - Moves the y value of the Rectangle object by this amount. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offset: function (dx, dy) { + + this.x += dx; + this.y += dy; + + return this; + + }, + + /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Rectangle#offsetPoint + * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object. + * @return {Phaser.Rectangle} This Rectangle object. + */ + offsetPoint: function (point) { + + return this.offset(point.x, point.y); + + }, + + /** + * Sets the members of Rectangle to the specified values. + * @method Phaser.Rectangle#setTo + * @param {number} x - The x coordinate of the top-left corner of the Rectangle. + * @param {number} y - The y coordinate of the top-left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + setTo: function (x, y, width, height) { + + this.x = x; + this.y = y; + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Scales the width and height of this Rectangle by the given amounts. + * + * @method Phaser.Rectangle#scale + * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. + * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. + * @return {Phaser.Rectangle} This Rectangle object + */ + scale: function (x, y) { + + if (y === undefined) { y = x; } + + this.width *= x; + this.height *= y; + + return this; + + }, + + /** + * Centers this Rectangle so that the center coordinates match the given x and y values. + * + * @method Phaser.Rectangle#centerOn + * @param {number} x - The x coordinate to place the center of the Rectangle at. + * @param {number} y - The y coordinate to place the center of the Rectangle at. + * @return {Phaser.Rectangle} This Rectangle object + */ + centerOn: function (x, y) { + + this.centerX = x; + this.centerY = y; + + return this; + + }, + + /** + * Runs Math.floor() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#floor + */ + floor: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + + }, + + /** + * Runs Math.floor() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#floorAll + */ + floorAll: function () { + + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.width = Math.floor(this.width); + this.height = Math.floor(this.height); + + }, + + /** + * Runs Math.ceil() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#ceil + */ + ceil: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + + }, + + /** + * Runs Math.ceil() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#ceilAll + */ + ceilAll: function () { + + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.width = Math.ceil(this.width); + this.height = Math.ceil(this.height); + + }, + + /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFrom: function (source) { + + return this.setTo(source.x, source.y, source.width, source.height); + + }, + + /** + * Copies the left, top, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFromBounds + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ + copyFromBounds: function(source) { + + return this.setTo(source.left, source.top, source.width, source.height); + + }, + + /** + * Copies the x, y, width and height properties from this Rectangle to any given object. + * @method Phaser.Rectangle#copyTo + * @param {any} source - The object to copy to. + * @return {object} This object. + */ + copyTo: function (dest) { + + dest.x = this.x; + dest.y = this.y; + dest.width = this.width; + dest.height = this.height; + + return dest; + + }, + + /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method Phaser.Rectangle#inflate + * @param {number} dx - The amount to be added to the left side of the Rectangle. + * @param {number} dy - The amount to be added to the bottom side of the Rectangle. + * @return {Phaser.Rectangle} This Rectangle object. + */ + inflate: function (dx, dy) { + + return Phaser.Rectangle.inflate(this, dx, dy); + + }, + + /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method Phaser.Rectangle#size + * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object. + */ + size: function (output) { + + return Phaser.Rectangle.size(this, output); + + }, + + /** + * Resize the Rectangle by providing a new width and height. + * The x and y positions remain unchanged. + * + * @method Phaser.Rectangle#resize + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + + return this; + + }, + + /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method Phaser.Rectangle#clone + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ + clone: function (output) { + + return Phaser.Rectangle.clone(this, output); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method Phaser.Rectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + contains: function (x, y) { + + return Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method Phaser.Rectangle#containsRect + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ + containsRect: function (b) { + + return Phaser.Rectangle.containsRect(b, this); + + }, + + /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method Phaser.Rectangle#equals + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + */ + equals: function (b) { + + return Phaser.Rectangle.equals(this, b); + + }, + + /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method Phaser.Rectangle#intersection + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ + intersection: function (b, out) { + + return Phaser.Rectangle.intersection(this, b, out); + + }, + + /** + * Determines whether this Rectangle and another given Rectangle intersect with each other. + * This method checks the x, y, width, and height properties of the two Rectangles. + * + * @method Phaser.Rectangle#intersects + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + */ + intersects: function (b) { + + return Phaser.Rectangle.intersects(this, b); + + }, + + /** + * Determines whether the coordinates given intersects (overlaps) with this Rectangle. + * + * @method Phaser.Rectangle#intersectsRaw + * @param {number} left - The x coordinate of the left of the area. + * @param {number} right - The right coordinate of the area. + * @param {number} top - The y coordinate of the area. + * @param {number} bottom - The bottom coordinate of the area. + * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 + * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + */ + intersectsRaw: function (left, right, top, bottom, tolerance) { + + return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance); + + }, + + /** + * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. + * @method Phaser.Rectangle#union + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ + union: function (b, out) { + + return Phaser.Rectangle.union(this, b, out); + + }, + + /** + * Returns a uniformly distributed random point from anywhere within this Rectangle. + * + * @method Phaser.Rectangle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ + random: function (out) { + + if (out === undefined) { out = new Phaser.Point(); } + + out.x = this.randomX; + out.y = this.randomY; + + return out; + + }, + + /** + * Returns a point based on the given position constant, which can be one of: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * This method returns the same values as calling Rectangle.bottomLeft, etc, but those + * calls always create a new Point object, where-as this one allows you to use your own. + * + * @method Phaser.Rectangle#getPoint + * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. + * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the point in its `x` and `y` properties. + */ + getPoint: function (position, out) { + + if (out === undefined) { out = new Phaser.Point(); } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + return out.set(this.x, this.y); + + case Phaser.TOP_CENTER: + return out.set(this.centerX, this.y); + + case Phaser.TOP_RIGHT: + return out.set(this.right, this.y); + + case Phaser.LEFT_CENTER: + return out.set(this.x, this.centerY); + + case Phaser.CENTER: + return out.set(this.centerX, this.centerY); + + case Phaser.RIGHT_CENTER: + return out.set(this.right, this.centerY); + + case Phaser.BOTTOM_LEFT: + return out.set(this.x, this.bottom); + + case Phaser.BOTTOM_CENTER: + return out.set(this.centerX, this.bottom); + + case Phaser.BOTTOM_RIGHT: + return out.set(this.right, this.bottom); + } + + }, + + /** + * Creates or positions four {@link Phaser.Line} lines representing the Rectangle's sides. + * + * @method Phaser.Rectangle#sides + * @param {Phaser.Line} [top] + * @param {Phaser.Line} [right] + * @param {Phaser.Line} [bottom] + * @param {Phaser.Line} [left] + * @return {?Phaser.Line[]} - An array containing four lines (if no arguments were given), or null. + */ + sides: function (top, right, bottom, left) { + + if (!arguments.length) { + top = new Phaser.Line(); + right = new Phaser.Line(); + bottom = new Phaser.Line(); + left = new Phaser.Line(); + } + + var x1 = this.x; + var y1 = this.y; + var x2 = this.right; + var y2 = this.bottom; + + top.setTo(x1, y1, x2, y1); + right.setTo(x2, y1, x2, y2); + bottom.setTo(x1, y2, x2, y2); + left.setTo(x1, y1, x1, y2); + + if (!arguments.length) { + return [top, right, bottom, left]; + } + + return null; + + }, + + /** + * Returns a string representation of this object. + * @method Phaser.Rectangle#toString + * @return {string} A string representation of the instance. + */ + toString: function () { + + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + + } + +}; + +/** +* @name Phaser.Rectangle#halfWidth +* @property {number} halfWidth - Half of the width of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", { + + get: function () { + return Math.round(this.width / 2); + } + +}); + +/** +* @name Phaser.Rectangle#halfHeight +* @property {number} halfHeight - Half of the height of the Rectangle. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", { + + get: function () { + return Math.round(this.height / 2); + } + +}); + +/** +* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. +* @name Phaser.Rectangle#bottom +* @property {number} bottom - The sum of the y and height properties. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottom", { + + get: function () { + return this.y + this.height; + }, + + set: function (value) { + + if (value <= this.y) + { + this.height = 0; + } + else + { + this.height = value - this.y; + } + + } + +}); + +/** +* The location of the Rectangles bottom left corner as a Point object. +* @name Phaser.Rectangle#bottomLeft +* @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", { + + get: function () { + return new Phaser.Point(this.x, this.bottom); + }, + + set: function (value) { + this.x = value.x; + this.bottom = value.y; + } + +}); + +/** +* The location of the Rectangles bottom right corner as a Point object. +* @name Phaser.Rectangle#bottomRight +* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", { + + get: function () { + return new Phaser.Point(this.right, this.bottom); + }, + + set: function (value) { + this.right = value.x; + this.bottom = value.y; + } + +}); + +/** +* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. +* @name Phaser.Rectangle#left +* @property {number} left - The x coordinate of the left of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "left", { + + get: function () { + return this.x; + }, + + set: function (value) { + if (value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + } + +}); + +/** +* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. +* @name Phaser.Rectangle#right +* @property {number} right - The sum of the x and width properties. +*/ +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 = value - this.x; + } + } + +}); + +/** +* The volume of the Rectangle derived from width * height. +* @name Phaser.Rectangle#volume +* @property {number} volume - The volume of the Rectangle derived from width * height. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "volume", { + + get: function () { + return this.width * this.height; + } + +}); + +/** +* The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @name Phaser.Rectangle#perimeter +* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. +* @readonly +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", { + + get: function () { + return (this.width * 2) + (this.height * 2); + } + +}); + +/** +* The x coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerX +* @property {number} centerX - The x coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerX", { + + get: function () { + return this.x + this.halfWidth; + }, + + set: function (value) { + this.x = value - this.halfWidth; + } + +}); + +/** +* The y coordinate of the center of the Rectangle. +* @name Phaser.Rectangle#centerY +* @property {number} centerY - The y coordinate of the center of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "centerY", { + + get: function () { + return this.y + this.halfHeight; + }, + + set: function (value) { + this.y = value - this.halfHeight; + } + +}); + +/** +* A random value between the left and right values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomX +* @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomX", { + + get: function () { + + return this.x + (Math.random() * this.width); + + } + +}); + +/** +* A random value between the top and bottom values (inclusive) of the Rectangle. +* +* @name Phaser.Rectangle#randomY +* @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "randomY", { + + get: function () { + + return this.y + (Math.random() * this.height); + + } + +}); + +/** +* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. +* However it does affect the height property, whereas changing the y value does not affect the height property. +* @name Phaser.Rectangle#top +* @property {number} top - The y coordinate of the top of the Rectangle. +*/ +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); + } + } + +}); + +/** +* The location of the Rectangles top left corner as a Point object. +* @name Phaser.Rectangle#topLeft +* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. +*/ +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; + } + +}); + +/** +* The location of the Rectangles top right corner as a Point object. +* @name Phaser.Rectangle#topRight +* @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object. +*/ +Object.defineProperty(Phaser.Rectangle.prototype, "topRight", { + + get: function () { + return new Phaser.Point(this.x + this.width, this.y); + }, + + set: function (value) { + this.right = value.x; + this.y = value.y; + } + +}); + +/** +* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. +* If set to true then all of the Rectangle properties are set to 0. +* @name Phaser.Rectangle#empty +* @property {boolean} empty - Gets or sets the Rectangles empty state. +*/ +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; + +/** +* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. +* @method Phaser.Rectangle.inflate +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} dx - The amount to be added to the left side of the Rectangle. +* @param {number} dy - The amount to be added to the bottom side of the Rectangle. +* @return {Phaser.Rectangle} This Rectangle object. +*/ +Phaser.Rectangle.inflate = function (a, dx, dy) { + + a.x -= dx; + a.width += 2 * dx; + a.y -= dy; + a.height += 2 * dy; + + return a; + +}; + +/** +* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. +* @method Phaser.Rectangle.inflatePoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. +* @return {Phaser.Rectangle} The Rectangle object. +*/ +Phaser.Rectangle.inflatePoint = function (a, point) { + + return Phaser.Rectangle.inflate(a, point.x, point.y); + +}; + +/** +* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. +* @method Phaser.Rectangle.size +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. +* @return {Phaser.Point} The size of the Rectangle object +*/ +Phaser.Rectangle.size = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Point(a.width, a.height); + } + else + { + output.setTo(a.width, a.height); + } + + return output; + +}; + +/** +* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. +* @method Phaser.Rectangle.clone +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.clone = function (a, output) { + + if (output === undefined || output === null) + { + 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; + +}; + +/** +* Returns a new Rectangle object with the same values for the left, top, width, and height properties as the original object. +* @method Phaser.Rectangle.createFromBounds +* @param {any} a - An object with `left`, `top`, `width`, and `height` properties. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} +*/ +Phaser.Rectangle.createFromBounds = function (a, output) { + + if (output === undefined || output === null) + { + output = new Phaser.Rectangle(a.x, a.y, a.width, a.height); + } + + return output.copyFromBounds(a); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by this Rectangle object. +* @method Phaser.Rectangle.contains +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +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); + +}; + +/** +* Determines whether the specified coordinates are contained within the region defined by the given raw values. +* @method Phaser.Rectangle.containsRaw +* @param {number} rx - The x coordinate of the top left of the area. +* @param {number} ry - The y coordinate of the top left of the area. +* @param {number} rw - The width of the area. +* @param {number} rh - The height of the area. +* @param {number} x - The x coordinate of the point to test. +* @param {number} y - The y coordinate of the point to test. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) { + + return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh)); + +}; + +/** +* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. +* @method Phaser.Rectangle.containsPoint +* @param {Phaser.Rectangle} a - The Rectangle object. +* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsPoint = function (a, point) { + + return Phaser.Rectangle.contains(a, point.x, point.y); + +}; + +/** +* Determines whether the first Rectangle object is fully contained within the second Rectangle object. +* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. +* @method Phaser.Rectangle.containsRect +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. +*/ +Phaser.Rectangle.containsRect = function (a, b) { + + // If the given rect has a larger volume than this one then it can never contain it + if (a.volume > b.volume) + { + return false; + } + + return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom); + +}; + +/** +* Determines whether the two Rectangles are equal. +* This method compares the x, y, width and height properties of each Rectangle. +* @method Phaser.Rectangle.equals +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. +*/ +Phaser.Rectangle.equals = function (a, b) { + + return (a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height); + +}; + +/** +* Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. +* @method Phaser.Rectangle.sameDimensions +* @param {Rectangle-like} a - The first Rectangle object. +* @param {Rectangle-like} b - The second Rectangle object. +* @return {boolean} True if the object have equivalent values for the width and height properties. +*/ +Phaser.Rectangle.sameDimensions = function (a, b) { + + return (a.width === b.width && a.height === b.height); + +}; + +/** +* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. +* @method Phaser.Rectangle.intersection +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. +*/ +Phaser.Rectangle.intersection = function (a, b, output) { + + if (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; + +}; + +/** +* Determines whether the two Rectangles intersect with each other. +* This method checks the x, y, width, and height properties of the Rectangles. +* @method Phaser.Rectangle.intersects +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. +*/ +Phaser.Rectangle.intersects = function (a, b) { + + if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) + { + return false; + } + + return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom); + +}; + +/** +* Determines whether the object specified intersects (overlaps) with the given values. +* @method Phaser.Rectangle.intersectsRaw +* @param {number} left - The x coordinate of the left of the area. +* @param {number} right - The right coordinate of the area. +* @param {number} top - The y coordinate of the area. +* @param {number} bottom - The bottom coordinate of the area. +* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 +* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. +*/ +Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) { + + if (tolerance === undefined) { tolerance = 0; } + + return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); + +}; + +/** +* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. +* @method Phaser.Rectangle.union +* @param {Phaser.Rectangle} a - The first Rectangle object. +* @param {Phaser.Rectangle} b - The second Rectangle object. +* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. +* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. +*/ +Phaser.Rectangle.union = function (a, b, output) { + + if (output === undefined) + { + output = new Phaser.Rectangle(); + } + + return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top)); + +}; + +/** +* Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. +* +* @method Phaser.Rectangle#aabb +* @param {Phaser.Point[]} points - The array of one or more points. +* @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. +* @return {Phaser.Rectangle} The new Rectangle object. +* @static +*/ +Phaser.Rectangle.aabb = function(points, out) { + + if (out === undefined) { + out = new Phaser.Rectangle(); + } + + var xMax = Number.NEGATIVE_INFINITY, + xMin = Number.POSITIVE_INFINITY, + yMax = Number.NEGATIVE_INFINITY, + yMin = Number.POSITIVE_INFINITY; + + points.forEach(function(point) { + if (point.x > xMax) { + xMax = point.x; + } + if (point.x < xMin) { + xMin = point.x; + } + + if (point.y > yMax) { + yMax = point.y; + } + if (point.y < yMin) { + yMin = point.y; + } + }); + + out.setTo(xMin, yMin, xMax - xMin, yMax - yMin); + + return out; +}; + +// Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.Rectangle = Phaser.Rectangle; +PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0); + +/** +* @author Mat Groves http://matgroves.com/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Rounded Rectangle object is an area defined by its position and has nice rounded corners, +* as indicated by its top-left corner point (x, y) and by its width and its height. +* +* @class Phaser.RoundedRectangle +* @constructor +* @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle. +* @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle. +* @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value. +* @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value. +* @param {number} [radius=20] - Controls the radius of the rounded corners. +*/ +Phaser.RoundedRectangle = function(x, y, width, height, radius) +{ + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = 0; } + if (height === undefined) { height = 0; } + if (radius === undefined) { radius = 20; } + + /** + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ + this.x = x; + + /** + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ + this.y = y; + + /** + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ + this.width = width; + + /** + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ + this.height = height; + + /** + * @property {number} radius - The radius of the rounded corners. + */ + this.radius = radius || 20; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROUNDEDRECTANGLE; +}; + +Phaser.RoundedRectangle.prototype = { + + /** + * Returns a new RoundedRectangle object with the same values for the x, y, width, height and + * radius properties as this RoundedRectangle object. + * + * @method Phaser.RoundedRectangle#clone + * @return {Phaser.RoundedRectangle} + */ + clone: function () { + + return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + + }, + + /** + * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. + * + * @method Phaser.RoundedRectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. + */ + 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; + + } + +}; + +Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle; + +// Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion. +PIXI.RoundedRectangle = Phaser.RoundedRectangle; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. +* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y +* +* @class Phaser.Camera +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera +* @param {number} x - Position of the camera on the X axis +* @param {number} y - Position of the camera on the Y axis +* @param {number} width - The width of the view rectangle +* @param {number} height - The height of the view rectangle +*/ +Phaser.Camera = function (game, id, x, y, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + */ + this.world = game.world; + + /** + * @property {number} id - Reserved for future multiple camera set-ups. + * @default + */ + this.id = 0; + + /** + * Camera view. + * The view into the world we wish to render (by default the game dimensions). + * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. + * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. + * @property {Phaser.Rectangle} view + */ + this.view = new Phaser.Rectangle(x, y, width, height); + + /** + * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. + * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound + * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. + * + * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. + */ + this.bounds = new Phaser.Rectangle(x, y, width, height); + + /** + * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move. + */ + this.deadzone = null; + + /** + * @property {boolean} visible - Whether this camera is visible or not. + * @default + */ + this.visible = true; + + /** + * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. + * @default + */ + this.roundPx = true; + + /** + * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. + */ + this.atLimit = { x: false, y: false }; + + /** + * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. + * @default + */ + this.target = null; + + /** + * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot. + */ + this.displayObject = null; + + /** + * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot. + */ + this.scale = null; + + /** + * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. + * @readonly + */ + this.totalInView = 0; + + /** + * The linear interpolation value to use when following a target. + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * @property {Phaser.Point} lerp + * @default + */ + this.lerp = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes. + */ + this.onShakeComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes. + */ + this.onFlashComplete = new Phaser.Signal(); + + /** + * This signal is dispatched when the camera fade effect completes. + * When the fade effect completes you will be left with the screen black (or whatever + * color you faded to). In order to reset this call `Camera.resetFX`. This is called + * automatically when you change State. + * @property {Phaser.Signal} onFadeComplete + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * The Graphics object used to handle camera fx such as fade and flash. + * @property {Phaser.Graphics} fx + * @protected + */ + this.fx = null; + + /** + * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position. + * @private + */ + this._targetPosition = new Phaser.Point(); + + /** + * @property {number} edge - Edge property. + * @private + * @default + */ + this._edge = 0; + + /** + * @property {Phaser.Point} position - Current position of the camera in world. + * @private + * @default + */ + this._position = new Phaser.Point(); + + /** + * @property {Object} _shake - The shake effect container. + * @private + */ + this._shake = { + intensity: 0, + duration: 0, + horizontal: false, + vertical: false, + shakeBounds: true, + x: 0, + y: 0 + }; + + /** + * @property {number} _fxDuration - FX duration timer. + * @private + */ + this._fxDuration = 0; + + /** + * @property {number} _fxType - The FX type running. + * @private + */ + this._fxType = 0; + + /** + * @property {Phaser.Rectangle} + * @private + */ + this._fixedView = new Phaser.Rectangle(); + +}; + +/** +* A follow style that uses no deadzone. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_LOCKON = 0; + +/** +* A follow style that uses a tall, narrow deadzone (0.33 x 0.125) with a center slightly above the view center. +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_PLATFORMER = 1; + +/** +* A follow style that uses a square deadzone (0.25 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN = 2; + +/** +* A follow style that uses a small square deadzone (0.125 of the larger view edge). +* +* @constant +* @type {number} +*/ +Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_BOTH = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_HORIZONTAL = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Camera.SHAKE_VERTICAL = 6; + +/** +* @constant +* @type {boolean} +*/ +Phaser.Camera.ENABLE_FX = true; + +Phaser.Camera.prototype = { + + /** + * Called automatically by Phaser.World. + * + * @method Phaser.Camera#boot + * @private + */ + boot: function () { + + this.displayObject = this.game.world; + + this.scale = this.game.world.scale; + + this.game.camera = this; + + if (Phaser.Graphics && Phaser.Camera.ENABLE_FX) + { + this.fx = new Phaser.Graphics(this.game); + + this.game.stage.addChild(this.fx); + } + + }, + + /** + * Camera preUpdate. Sets the total view counter to zero. + * + * @method Phaser.Camera#preUpdate + */ + preUpdate: function () { + + this.totalInView = 0; + + }, + + /** + * Tell the camera which sprite to follow. + * + * You can set the follow type and a linear interpolation value. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. + * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. + * + * @method Phaser.Camera#follow + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything. + * @param {number} [style] - Leverage one of the existing {@link deadzone} presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + */ + follow: function (target, style, lerpX, lerpY) { + + if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; } + if (lerpX === undefined) { lerpX = 1; } + if (lerpY === undefined) { lerpY = 1; } + + this.target = target; + this.lerp.set(lerpX, lerpY); + + var helper; + + switch (style) { + + case Phaser.Camera.FOLLOW_PLATFORMER: + var w = this.width / 8; + var h = this.height / 3; + this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN: + helper = Math.max(this.width, this.height) / 4; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT: + helper = Math.max(this.width, this.height) / 8; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + + case Phaser.Camera.FOLLOW_LOCKON: + this.deadzone = null; + break; + + default: + this.deadzone = null; + break; + } + + }, + + /** + * Sets the Camera follow target to null, stopping it from following an object if it's doing so. + * + * @method Phaser.Camera#unfollow + */ + unfollow: function () { + + this.target = null; + + }, + + /** + * Move the camera focus on a display object instantly. + * @method Phaser.Camera#focusOn + * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. + */ + focusOn: function (displayObject) { + + this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight)); + + }, + + /** + * Move the camera focus on a location instantly. + * @method Phaser.Camera#focusOnXY + * @param {number} x - X position. + * @param {number} y - Y position. + */ + focusOnXY: function (x, y) { + + this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight)); + + }, + + /** + * This creates a camera shake effect. It works by applying a random amount of additional + * spacing on the x and y axis each frame. You can control the intensity and duration + * of the effect, and if it should effect both axis or just one. + * + * When the shake effect ends the signal Camera.onShakeComplete is dispatched. + * + * @method Phaser.Camera#shake + * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. + * @param {number} [duration=500] - The duration of the shake effect in milliseconds. + * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL. + * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?). + * @return {boolean} True if the shake effect was started, otherwise false. + */ + shake: function (intensity, duration, force, direction, shakeBounds) { + + if (intensity === undefined) { intensity = 0.05; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = true; } + if (direction === undefined) { direction = Phaser.Camera.SHAKE_BOTH; } + if (shakeBounds === undefined) { shakeBounds = true; } + + if (!force && this._shake.duration > 0) + { + // Can't reset an already running shake + return false; + } + + this._shake.intensity = intensity; + this._shake.duration = duration; + this._shake.shakeBounds = shakeBounds; + + this._shake.x = 0; + this._shake.y = 0; + + this._shake.horizontal = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_HORIZONTAL); + this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL); + + return true; + + }, + + /** + * This creates a camera flash effect. It works by filling the game with the solid fill + * color specified, and then fading it away to alpha 0 over the duration given. + * + * You can use this for things such as hit feedback effects. + * + * When the effect ends the signal Camera.onFlashComplete is dispatched. + * + * @method Phaser.Camera#flash + * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the flash effect in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the flash effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + flash: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0xffffff; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 1; + + this._fxDuration = duration; + this._fxType = 0; + + return true; + + }, + + /** + * This creates a camera fade effect. It works by filling the game with the + * color specified, over the duration given, ending with a solid fill. + * + * You can use this for things such as transitioning to a new scene. + * + * The game will be left 'filled' at the end of this effect, likely obscuring + * everything. In order to reset it you can call `Camera.resetFX` and it will clear the + * fade. Or you can call `Camera.flash` with the same color as the fade, and it will + * reverse the process, bringing the game back into view again. + * + * When the effect ends the signal Camera.onFadeComplete is dispatched. + * + * @method Phaser.Camera#fade + * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the fade in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the fade effect. + * @return {boolean} True if the effect was started, otherwise false. + */ + fade: function (color, duration, force, alpha) { + + if (color === undefined) { color = 0x000000; } + if (duration === undefined) { duration = 500; } + if (force === undefined) { force = false; } + if (alpha === undefined) { alpha = 1; } + + if (!this.fx || (!force && this._fxDuration > 0)) + { + return false; + } + + this.fx.clear(); + + this.fx.beginFill(color, alpha); + this.fx.drawRect(0, 0, this.width, this.height); + this.fx.endFill(); + + this.fx.alpha = 0; + + this._fxDuration = duration; + this._fxType = 1; + + return true; + + }, + + /** + * The camera update loop. This is called automatically by the core game loop. + * + * @method Phaser.Camera#update + * @protected + */ + update: function () { + + if (this._fxDuration > 0) + { + this.updateFX(); + } + + if (this._shake.duration > 0) + { + this.updateShake(); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + this._shake.x = Math.floor(this._shake.x); + this._shake.y = Math.floor(this._shake.y); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the camera flash and fade effects. + * + * @method Phaser.Camera#updateFX + * @private + */ + updateFX: function () { + + if (this._fxType === 0) + { + // flash + this.fx.alpha -= this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha <= 0) + { + this._fxDuration = 0; + this.fx.alpha = 0; + this.onFlashComplete.dispatch(); + } + } + else + { + // fade + this.fx.alpha += this.game.time.elapsedMS / this._fxDuration; + + if (this.fx.alpha >= 1) + { + this._fxDuration = 0; + this.fx.alpha = 1; + this.onFadeComplete.dispatch(); + } + } + + }, + + /** + * Update the camera shake effect. + * + * @method Phaser.Camera#updateShake + * @private + */ + updateShake: function () { + + this._shake.duration -= this.game.time.elapsedMS; + + if (this._shake.duration <= 0) + { + this.onShakeComplete.dispatch(); + this._shake.x = 0; + this._shake.y = 0; + } + else + { + if (this._shake.horizontal) + { + this._shake.x = this.game.rnd.frac() * this._shake.intensity * this.view.width * 2 - this._shake.intensity * this.view.width; + } + + if (this._shake.vertical) + { + this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height; + } + } + + }, + + /** + * Internal method that handles tracking a sprite. + * + * @method Phaser.Camera#updateTarget + * @private + */ + updateTarget: function () { + + this._targetPosition.x = this.view.x + this.target.worldPosition.x; + this._targetPosition.y = this.view.y + this.target.worldPosition.y; + + if (this.deadzone) + { + this._edge = this._targetPosition.x - this.view.x; + + if (this._edge < this.deadzone.left) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.left, this.lerp.x); + } + else if (this._edge > this.deadzone.right) + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.right, this.lerp.x); + } + + this._edge = this._targetPosition.y - this.view.y; + + if (this._edge < this.deadzone.top) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.top, this.lerp.y); + } + else if (this._edge > this.deadzone.bottom) + { + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.bottom, this.lerp.y); + } + } + else + { + this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.view.halfWidth, this.lerp.x); + this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.view.halfHeight, this.lerp.y); + } + + if (this.bounds) + { + this.checkBounds(); + } + + if (this.roundPx) + { + this.view.floor(); + } + + this.displayObject.position.x = -this.view.x; + this.displayObject.position.y = -this.view.y; + + }, + + /** + * Update the Camera bounds to match the game world. + * + * @method Phaser.Camera#setBoundsToWorld + */ + setBoundsToWorld: function () { + + if (this.bounds) + { + this.bounds.copyFrom(this.game.world.bounds); + } + + }, + + /** + * Method called to ensure the camera doesn't venture outside of the game world. + * Called automatically by Camera.update. + * + * @method Phaser.Camera#checkBounds + * @protected + */ + checkBounds: function () { + + this.atLimit.x = false; + this.atLimit.y = false; + + var vx = this.view.x + this._shake.x; + var vw = this.view.right + this._shake.x; + var vy = this.view.y + this._shake.y; + var vh = this.view.bottom + this._shake.y; + + // Make sure we didn't go outside the cameras bounds + if (vx <= this.bounds.x * this.scale.x) + { + this.atLimit.x = true; + this.view.x = this.bounds.x * this.scale.x; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + else if (vw >= this.bounds.right * this.scale.x) + { + this.atLimit.x = true; + this.view.x = (this.bounds.right * this.scale.x) - this.width; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.x = 0; + } + } + + if (vy <= this.bounds.top * this.scale.y) + { + this.atLimit.y = true; + this.view.y = this.bounds.top * this.scale.y; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + else if (vh >= this.bounds.bottom * this.scale.y) + { + this.atLimit.y = true; + this.view.y = (this.bounds.bottom * this.scale.y) - this.height; + + if (!this._shake.shakeBounds) + { + // The camera is up against the bounds, so reset the shake + this._shake.y = 0; + } + } + + }, + + /** + * A helper function to set both the X and Y properties of the camera at once + * without having to use game.camera.x and game.camera.y. + * + * @method Phaser.Camera#setPosition + * @param {number} x - X position. + * @param {number} y - Y position. + */ + setPosition: function (x, y) { + + this.view.x = x; + this.view.y = y; + + if (this.bounds) + { + this.checkBounds(); + } + + }, + + /** + * Sets the size of the view rectangle given the width and height in parameters. + * + * @method Phaser.Camera#setSize + * @param {number} width - The desired width. + * @param {number} height - The desired height. + */ + setSize: function (width, height) { + + this.view.width = width; + this.view.height = height; + + }, + + /** + * Resets the camera back to 0,0 and un-follows any object it may have been tracking. + * Also immediately resets any camera effects that may have been running such as + * shake, flash or fade. + * + * @method Phaser.Camera#reset + */ + reset: function () { + + this.target = null; + + this.view.x = 0; + this.view.y = 0; + + this._shake.duration = 0; + this._shake.x = 0; + this._shake.y = 0; + + this.resetFX(); + + }, + + /** + * Resets any active FX, such as a fade or flash and immediately clears it. + * Useful to calling after a fade in order to remove the fade from the Stage. + * + * @method Phaser.Camera#resetFX + */ + resetFX: function () { + + if (this.fx) + { + this.fx.clear(); + this.fx.alpha = 0; + } + + this._fxDuration = 0; + + } + +}; + +Phaser.Camera.prototype.constructor = Phaser.Camera; + +/** +* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#x +* @property {number} x - Gets or sets the cameras x position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "x", { + + get: function () { + + return this.view.x; + + }, + + set: function (value) { + + this.view.x = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#y +* @property {number} y - Gets or sets the cameras y position. +*/ +Object.defineProperty(Phaser.Camera.prototype, "y", { + + get: function () { + + return this.view.y; + + }, + + set: function (value) { + + this.view.y = value; + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras position. This value is automatically clamped if it falls outside of the World bounds. +* @name Phaser.Camera#position +* @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object. +*/ +Object.defineProperty(Phaser.Camera.prototype, "position", { + + get: function () { + + this._position.set(this.view.x, this.view.y); + + return this._position; + + }, + + set: function (value) { + + if (typeof value.x !== "undefined") { this.view.x = value.x; } + if (typeof value.y !== "undefined") { this.view.y = value.y; } + + if (this.bounds) + { + this.checkBounds(); + } + } + +}); + +/** +* The Cameras width. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#width +* @property {number} width - Gets or sets the cameras width. +*/ +Object.defineProperty(Phaser.Camera.prototype, "width", { + + get: function () { + + return this.view.width; + + }, + + set: function (value) { + + this.view.width = value; + + } + +}); + +/** +* The Cameras height. By default this is the same as the Game size and should not be adjusted for now. +* @name Phaser.Camera#height +* @property {number} height - Gets or sets the cameras height. +*/ +Object.defineProperty(Phaser.Camera.prototype, "height", { + + get: function () { + + return this.view.height; + + }, + + set: function (value) { + + this.view.height = value; + + } + +}); + + +/** +* The Cameras shake intensity. +* @name Phaser.Camera#shakeIntensity +* @property {number} shakeIntensity - Gets or sets the cameras shake intensity. +*/ +Object.defineProperty(Phaser.Camera.prototype, "shakeIntensity", { + + get: function () { + + return this._shake.intensity; + + }, + + set: function (value) { + + this._shake.intensity = value; + + } + +}); + + +/** + * Immobile {@link #view} rectangle. Its top-left is always (0, 0). You can use this align fixedToCamera objects. + * @name Phaser.Camera#fixedView + * @property {Phaser.Rectangle} fixedView + * @readonly + */ +Object.defineProperty(Phaser.Camera.prototype, "fixedView", { + + get: function () { + + this._fixedView.setTo(0, 0, this.view.width, this.view.height); + + return this._fixedView; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base State class which can be extended if you are creating your own game. +* It provides quick access to common functions such as the camera, cache, input, match, sound and more. +* +* #### Callbacks +* +* | start | preload | loaded | paused | stop | +* |-------|-------------|------------|--------------|----------| +* | init | | | | | +* | | preload | create | paused | | +* | | loadUpdate* | update* | pauseUpdate* | | +* | | | preRender* | | | +* | | loadRender* | render* | render* | | +* | | | | resumed | | +* | | | | | shutdown | +* +* Update and render calls (*) are repeated. +* +* If your State has a constructor, it will be invoked exactly once, during {@link {@link Phaser.StateManager#add}. +* +* @class Phaser.State +* @constructor +*/ +Phaser.State = function () { + + /** + * @property {Phaser.Game} game - This is a reference to the currently running Game. + */ + this.game = null; + + /** + * @property {string} key - The string based identifier given to the State when added into the State Manager. + */ + this.key = ''; + + /** + * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects. + */ + this.make = null; + + /** + * @property {Phaser.Camera} camera - A handy reference to World.camera. + */ + this.camera = null; + + /** + * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - A reference to the Input Manager. + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions. + */ + this.math = null; + + /** + * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. + */ + this.sound = null; + + /** + * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays. + */ + this.scale = null; + + /** + * @property {Phaser.Stage} stage - A reference to the Stage. + */ + this.stage = null; + + /** + * @property {Phaser.StateManager} stage - A reference to the State Manager, which controls state changes. + */ + this.state = null; + + /** + * @property {Phaser.Time} time - A reference to the game clock and timed events system. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - A reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. + */ + this.world = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. + */ + this.particles = null; + + /** + * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser. + */ + this.physics = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator. + */ + this.rnd = null; + +}; + +Phaser.State.prototype = { + + /** + * init is the very first function called when your State starts up. It's called before preload, create or anything else. + * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables + * or objects before the preloading starts. + * + * @method Phaser.State#init + * @param {...any} args - Any extra arguments passed to {@link Phaser.StateManager#start} or {@link Phaser.StateManager#restart}. + */ + init: function () { + }, + + /** + * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) + * You shouldn't create any objects in this method that require assets that you're also loading in this method, as + * they won't yet be available. + * + * @method Phaser.State#preload + * @param {Phaser.Game} game + */ + preload: function () { + }, + + /** + * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * + * @method Phaser.State#loadUpdate + * @param {Phaser.Game} game + */ + loadUpdate: function () { + }, + + /** + * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. + * + * @method Phaser.State#loadRender + * @param {Phaser.Game} game + */ + loadRender: function () { + }, + + /** + * create is called once preload has completed, this includes the loading of any assets from the Loader. + * If you don't have a preload method then create is the first method called in your State. + * + * @method Phaser.State#create + * @param {Phaser.Game} game + */ + create: function () { + }, + + /** + * The update method is left empty for your own use. + * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. + * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. + * + * @method Phaser.State#update + * @param {Phaser.Game} game + */ + update: function () { + }, + + /** + * The preRender method is called after all Game Objects have been updated, but before any rendering takes place. + * + * @method Phaser.State#preRender + * @param {Phaser.Game} game + * @param {number} elapsedTime + */ + preRender: function () { + }, + + /** + * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. + * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any + * final post-processing style effects here. Note that this happens before plugins postRender takes place. + * + * @method Phaser.State#render + * @param {Phaser.Game} game + */ + render: function () { + }, + + /** + * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. + * + * @method Phaser.State#resize + * @param {number} width + * @param {number} height + */ + resize: function () { + }, + + /** + * This method will be called if the core game loop is paused. + * + * @method Phaser.State#paused + * @param {Phaser.Game} game + */ + paused: function () { + }, + + /** + * This method will be called when the core game loop resumes from a paused state. + * + * @method Phaser.State#resumed + * @param {Phaser.Game} game + */ + resumed: function () { + }, + + /** + * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. + * + * @method Phaser.State#pauseUpdate + * @param {Phaser.Game} game + */ + pauseUpdate: function () { + }, + + /** + * This method will be called when the State is shutdown (i.e. you switch to another state from this one). + * + * @method Phaser.State#shutdown + * @param {Phaser.Game} game + */ + shutdown: function () { + } + +}; + +Phaser.State.prototype.constructor = Phaser.State; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The State Manager is responsible for loading, setting up and switching game states. +* +* @class Phaser.StateManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. +*/ +Phaser.StateManager = function (game, pendingState) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {object} states - The object containing Phaser.States. + */ + this.states = {}; + + /** + * @property {Phaser.State} _pendingState - The state to be switched to in the next frame. + * @private + */ + this._pendingState = null; + + if (typeof pendingState !== 'undefined' && pendingState !== null) + { + this._pendingState = pendingState; + } + + /** + * @property {boolean} _clearWorld - Clear the world when we switch state? + * @private + */ + this._clearWorld = false; + + /** + * @property {boolean} _clearCache - Clear the cache when we switch state? + * @private + */ + this._clearCache = false; + + /** + * @property {boolean} _created - Flag that sets if the State has been created or not. + * @private + */ + this._created = false; + + /** + * @property {any[]} _args - Temporary container when you pass vars from one State to another. + * @private + */ + this._args = []; + + /** + * @property {string} current - The current active State object. + * @default + */ + this.current = ''; + + /** + * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. + * + * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start + * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states + * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. + * + * The callback you specify is sent two parameters: the string based key of the new state, + * and the second parameter is the string based key of the old / previous state. + * + * @property {Phaser.Signal} onStateChange + */ + this.onStateChange = new Phaser.Signal(); + + /** + * @property {function} onInitCallback - This is called when the state is set as the active state. + * @default + */ + this.onInitCallback = null; + + /** + * @property {function} onPreloadCallback - This is called when the state starts to load assets. + * @default + */ + this.onPreloadCallback = null; + + /** + * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins. + * @default + */ + this.onCreateCallback = null; + + /** + * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). + * @default + */ + this.onUpdateCallback = null; + + /** + * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). + * @default + */ + this.onRenderCallback = null; + + /** + * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. + * @default + */ + this.onResizeCallback = null; + + /** + * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. + * @default + */ + this.onPreRenderCallback = null; + + /** + * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase. + * @default + */ + this.onLoadUpdateCallback = null; + + /** + * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase. + * @default + */ + this.onLoadRenderCallback = null; + + /** + * @property {function} onPausedCallback - This is called when the game is paused. + * @default + */ + this.onPausedCallback = null; + + /** + * @property {function} onResumedCallback - This is called when the game is resumed from a paused state. + * @default + */ + this.onResumedCallback = null; + + /** + * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused. + * @default + */ + this.onPauseUpdateCallback = null; + + /** + * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state). + * @default + */ + this.onShutDownCallback = null; + +}; + +Phaser.StateManager.prototype = { + + /** + * The Boot handler is called by Phaser.Game when it first starts up. + * @method Phaser.StateManager#boot + * @private + */ + boot: function () { + + this.game.onPause.add(this.pause, this); + this.game.onResume.add(this.resume, this); + + if (this._pendingState !== null && typeof this._pendingState !== 'string') + { + this.add('default', this._pendingState, true); + } + + }, + + /** + * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. + * + * The State can be any of + * + * - a plain JavaScript object containing at least one required callback (see {@link #checkState}) + * - an instance of {@link Phaser.State} + * - an instance of a class extending Phaser.State + * - a constructor function (class) + * + * If a function is given a new state object will be created by calling it, passing the current {@link Phaser.Game game} as the first argument. + * + * @method Phaser.StateManager#add + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + * @param {Phaser.State|object|function} state - The state you want to switch to. + * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it. + */ + add: function (key, state, autoStart) { + + if (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; + + }, + + /** + * Delete the given state. + * @method Phaser.StateManager#remove + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + */ + 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.onPreRenderCallback = null; + this.onRenderCallback = null; + this.onResizeCallback = null; + this.onPausedCallback = null; + this.onResumedCallback = null; + this.onPauseUpdateCallback = null; + } + + delete this.states[key]; + + }, + + /** + * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. + * + * @method Phaser.StateManager#start + * @param {string} key - The key of the state you want to start. + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one). + */ + start: function (key, clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + if (this.checkState(key)) + { + // Place the state in the queue. It will be started the next time the game loop begins. + this._pendingState = key; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 3) + { + this._args = Array.prototype.splice.call(arguments, 3); + } + } + + }, + + /** + * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. + * + * @method Phaser.StateManager#restart + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one. + */ + restart: function (clearWorld, clearCache) { + + if (clearWorld === undefined) { clearWorld = true; } + if (clearCache === undefined) { clearCache = false; } + + // Place the state in the queue. It will be started the next time the game loop starts. + this._pendingState = this.current; + this._clearWorld = clearWorld; + this._clearCache = clearCache; + + if (arguments.length > 2) + { + this._args = Array.prototype.slice.call(arguments, 2); + } + + }, + + /** + * Used by onInit and onShutdown when those functions don't exist on the state + * @method Phaser.StateManager#dummy + * @private + */ + dummy: function () { + }, + + /** + * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. + * + * @method Phaser.StateManager#preUpdate + */ + preUpdate: function () { + + if (this._pendingState && this.game.isBooted) + { + var previousStateKey = this.current; + + // Already got a state running? + this.clearCurrentState(); + + this.setCurrentState(this._pendingState); + + this.onStateChange.dispatch(this.current, previousStateKey); + + if (this.current !== this._pendingState) + { + return; + } + else + { + this._pendingState = null; + } + + // If StateManager.start has been called from the init of a State that ALSO has a preload, then + // onPreloadCallback will be set, but must be ignored + if (this.onPreloadCallback) + { + this.game.load.reset(true); + this.onPreloadCallback.call(this.callbackContext, this.game); + + // Is the loader empty? + if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0) + { + this.loadComplete(); + } + else + { + // Start the loader going as we have something in the queue + this.game.load.start(); + } + } + else + { + // No init? Then there was nothing to load either + this.loadComplete(); + } + } + + }, + + /** + * This method clears the current State, calling its shutdown callback. The process also removes any active tweens, + * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. + * + * @method Phaser.StateManager#clearCurrentState + */ + clearCurrentState: function () { + + if (this.current) + { + if (this.onShutDownCallback) + { + 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(); + + this.game.scale.reset(this._clearWorld); + + if (this.game.debug) + { + this.game.debug.reset(); + } + + if (this._clearWorld) + { + this.game.world.shutdown(); + + if (this._clearCache) + { + this.game.cache.destroy(); + } + } + } + + }, + + /** + * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. + * + * @method Phaser.StateManager#checkState + * @param {string} key - The key of the state you want to check. + * @return {boolean} true if the State has the required functions, otherwise false. + */ + checkState: function (key) { + + var state = this.states[key]; + + if (state) + { + if (state.preload || state.create || state.update || state.render) + { + return true; + } + else + { + console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"); + return false; + } + } + else + { + console.warn("Phaser.StateManager - No state found with the key: " + key); + return false; + } + + }, + + /** + * Links game properties to the State given by the key. + * + * @method Phaser.StateManager#link + * @param {string} key - State key. + * @protected + */ + link: function (key) { + + var state = this.states[key]; + + state.game = this.game; + state.add = this.game.add; + state.make = this.game.make; + state.camera = this.game.camera; + state.cache = this.game.cache; + state.input = this.game.input; + state.load = this.game.load; + state.math = this.game.math; + state.sound = this.game.sound; + state.scale = this.game.scale; + state.state = this; + state.stage = this.game.stage; + state.time = this.game.time; + state.tweens = this.game.tweens; + state.world = this.game.world; + state.particles = this.game.particles; + state.rnd = this.game.rnd; + state.physics = this.game.physics; + state.key = key; + + }, + + /** + * Nulls all State level Phaser properties, including a reference to Game. + * + * @method Phaser.StateManager#unlink + * @param {string} key - State key. + * @protected + */ + unlink: function (key) { + + var state = this.states[key]; + + if (state) + { + state.game = null; + state.add = null; + state.make = null; + state.camera = null; + state.cache = null; + state.input = null; + state.load = null; + state.math = null; + state.sound = null; + state.scale = null; + state.state = null; + state.stage = null; + state.time = null; + state.tweens = null; + state.world = null; + state.particles = null; + state.rnd = null; + state.physics = null; + } + + }, + + /** + * Sets the current State. Should not be called directly (use StateManager.start) + * + * @method Phaser.StateManager#setCurrentState + * @param {string} key - State key. + * @private + */ + setCurrentState: function (key) { + + var state = this.states[key]; + + this.callbackContext = state; + + this.link(key); + + // Used when the state is set as being the current active state + this.onInitCallback = state['init'] || this.dummy; + + this.onPreloadCallback = state['preload'] || null; + this.onLoadRenderCallback = state['loadRender'] || null; + this.onLoadUpdateCallback = state['loadUpdate'] || null; + this.onCreateCallback = state['create'] || null; + this.onUpdateCallback = state['update'] || null; + this.onPreRenderCallback = state['preRender'] || null; + this.onRenderCallback = state['render'] || null; + this.onResizeCallback = state['resize'] || null; + this.onPausedCallback = state['paused'] || null; + this.onResumedCallback = state['resumed'] || null; + this.onPauseUpdateCallback = state['pauseUpdate'] || null; + + // Used when the state is no longer the current active state + this.onShutDownCallback = state['shutdown'] || this.dummy; + + // Reset the physics system, but not on the first state start + if (this.current !== '') + { + this.game.physics.reset(); + } + + this.current = key; + this._created = false; + + // At this point key and pendingState should equal each other + this.onInitCallback.apply(this.callbackContext, this._args); + + // If they no longer do then the init callback hit StateManager.start + if (key === this._pendingState) + { + this._args = []; + } + + this.game._kickstart = true; + + }, + + /** + * Gets the current State. + * + * @method Phaser.StateManager#getCurrentState + * @return {Phaser.State} + * @public + */ + getCurrentState: function() { + return this.states[this.current]; + }, + + /** + * @method Phaser.StateManager#loadComplete + * @protected + */ + loadComplete: function () { + + // Make sure to do load-update one last time before state is set to _created + if (this._created === false && this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + + if (this._created === false && this.onCreateCallback) + { + this._created = true; + this.onCreateCallback.call(this.callbackContext, this.game); + } + else + { + this._created = true; + } + + }, + + /** + * @method Phaser.StateManager#pause + * @protected + */ + pause: function () { + + if (this._created && this.onPausedCallback) + { + this.onPausedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#resume + * @protected + */ + resume: function () { + + if (this._created && this.onResumedCallback) + { + this.onResumedCallback.call(this.callbackContext, this.game); + } + + }, + + /** + * @method Phaser.StateManager#update + * @protected + */ + update: function () { + + if (this._created) + { + if (this.onUpdateCallback) + { + this.onUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#pauseUpdate + * @protected + */ + pauseUpdate: function () { + + if (this._created) + { + if (this.onPauseUpdateCallback) + { + this.onPauseUpdateCallback.call(this.callbackContext, this.game); + } + } + else + { + if (this.onLoadUpdateCallback) + { + this.onLoadUpdateCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * @method Phaser.StateManager#preRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + preRender: function (elapsedTime) { + + if (this._created && this.onPreRenderCallback) + { + this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime); + } + + }, + + /** + * @method Phaser.StateManager#resize + * @protected + */ + resize: function (width, height) { + + if (this.onResizeCallback) + { + this.onResizeCallback.call(this.callbackContext, width, height); + } + + }, + + /** + * @method Phaser.StateManager#render + * @protected + */ + render: function () { + + if (this._created) + { + if (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); + this.game.context.restore(); + } + else + { + this.onRenderCallback.call(this.callbackContext, this.game); + } + } + } + else + { + if (this.onLoadRenderCallback) + { + this.onLoadRenderCallback.call(this.callbackContext, this.game); + } + } + + }, + + /** + * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. + * You don't recover from this without rebuilding the Phaser instance again. + * @method Phaser.StateManager#destroy + */ + destroy: function () { + + this._clearWorld = true; + this._clearCache = true; + + this.clearCurrentState(); + + 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; + this.current = ''; + + } + +}; + +Phaser.StateManager.prototype.constructor = Phaser.StateManager; + +/** +* @name Phaser.StateManager#created +* @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default). +* @readOnly +*/ +Object.defineProperty(Phaser.StateManager.prototype, "created", { + + get: function () { + + return this._created; + + } + +}); + +/** +* "It's like nailing jelly to a kitten" - Gary Penn +*/ + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Signals are what Phaser uses to handle events and event dispatching. +* You can listen for a Signal by binding a callback / function to it. +* This is done by using either `Signal.add` or `Signal.addOnce`. +* +* For example you can listen for a touch or click event from the Input Manager +* by using its `onDown` Signal: +* +* `game.input.onDown.add(function() { ... });` +* +* Rather than inline your function, you can pass a reference: +* +* `game.input.onDown.add(clicked, this);` +* `function clicked () { ... }` +* +* In this case the second argument (`this`) is the context in which your function should be called. +* +* Now every time the InputManager dispatches the `onDown` signal (or event), your function +* will be called. +* +* Multiple callbacks can be bound to the same signal. +* They're ordered first by their `priority` arguments and then by the order in which they were added. +* If a callback calls {@link #halt} or returns `false`, any remaining callbacks are skipped. +* +* Very often a Signal will send arguments to your function. +* This is specific to the Signal itself. +* If you're unsure then check the documentation, or failing that simply do: +* +* `Signal.add(function() { console.log(arguments); })` +* +* and it will log all of the arguments your function received from the Signal. +* +* Sprites have lots of default signals you can listen to in their Events class, such as: +* +* `sprite.events.onKilled` +* +* Which is called automatically whenever the Sprite is killed. +* There are lots of other events, see the Events component for a list. +* +* As well as listening to pre-defined Signals you can also create your own: +* +* `var mySignal = new Phaser.Signal();` +* +* This creates a new Signal. You can bind a callback to it: +* +* `mySignal.add(myCallback, this);` +* +* and then finally when ready you can dispatch the Signal: +* +* `mySignal.dispatch(your arguments);` +* +* And your callback will be invoked. See the dispatch method for more details. +* +* @class Phaser.Signal +* @constructor +*/ +Phaser.Signal = function () {}; + +Phaser.Signal.prototype = { + + /** + * @property {?Array.} _bindings - Internal variable. + * @private + */ + _bindings: null, + + /** + * @property {any} _prevParams - Internal variable. + * @private + */ + _prevParams: null, + + /** + * Memorize the previously dispatched event? + * + * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}. + * Use {@link #forget} to clear any currently memorized event. + * + * @property {boolean} memorize + */ + memorize: false, + + /** + * @property {boolean} _shouldPropagate + * @private + */ + _shouldPropagate: true, + + /** + * Is the Signal active? Only active signals will broadcast dispatched events. + * + * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}. + * + * @property {boolean} active + * @default + */ + active: true, + + /** + * @property {function} _boundDispatch - The bound dispatch function, if any. + * @private + */ + _boundDispatch: false, + + /** + * @method Phaser.Signal#validateListener + * @param {function} listener - Signal handler function. + * @param {string} fnName - Function name. + * @private + */ + validateListener: function (listener, fnName) { + + if (typeof listener !== 'function') + { + throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); + } + + }, + + /** + * @method Phaser.Signal#_registerListener + * @private + * @param {function} listener - Signal handler function. + * @param {boolean} isOnce - Should the listener only be called once? + * @param {object} [listenerContext] - The context under which the listener is invoked. + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + _registerListener: function (listener, isOnce, listenerContext, priority, args) { + + var prevIndex = this._indexOfListener(listener, listenerContext); + var binding; + + if (prevIndex !== -1) + { + binding = this._bindings[prevIndex]; + + if (binding.isOnce() !== isOnce) + { + throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); + } + } + else + { + binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args); + this._addBinding(binding); + } + + if (this.memorize && this._prevParams) + { + binding.execute(this._prevParams); + } + + return binding; + + }, + + /** + * @method Phaser.Signal#_addBinding + * @private + * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. + */ + _addBinding: function (binding) { + + if (!this._bindings) + { + this._bindings = []; + } + + // Simplified insertion sort + var n = this._bindings.length; + + do { + n--; + } + while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); + + this._bindings.splice(n + 1, 0, binding); + + }, + + /** + * @method Phaser.Signal#_indexOfListener + * @private + * @param {function} listener - Signal handler function. + * @param {object} [context=null] - Signal handler function. + * @return {number} The index of the listener within the private bindings array. + */ + _indexOfListener: function (listener, context) { + + if (!this._bindings) + { + return -1; + } + + if (context === undefined) { context = null; } + + var n = this._bindings.length; + var cur; + + while (n--) + { + cur = this._bindings[n]; + + if (cur._listener === listener && cur.context === context) + { + return n; + } + } + + return -1; + + }, + + /** + * Check if a specific listener is attached. + * + * @method Phaser.Signal#has + * @param {function} listener - Signal handler function. + * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @return {boolean} If Signal has the specified listener. + */ + has: function (listener, context) { + + return this._indexOfListener(listener, context) !== -1; + + }, + + /** + * Add an event listener for this signal. + * + * An event listener is a callback with a related context and priority. + * + * You can optionally provide extra arguments which will be passed to the callback after any internal parameters. + * + * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. + * Any arguments you've specified after `priority` will be sent as well: + * + * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` + * + * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. + * + * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', + * and the value 100 were the custom arguments given in the call to 'add'. + * + * If the callback calls {@link #halt} or returns `false`, any remaining callbacks bound to this Signal are skipped. + * + * @method Phaser.Signal#add + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + add: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'add'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, false, listenerContext, priority, args); + + }, + + /** + * Add a one-time listener - the listener is automatically removed after the first execution. + * + * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and + * the listener will be removed immediately. + * + * @method Phaser.Signal#addOnce + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ + addOnce: function (listener, listenerContext, priority) { + + this.validateListener(listener, 'addOnce'); + + var args = []; + + if (arguments.length > 3) + { + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + return this._registerListener(listener, true, listenerContext, priority, args); + + }, + + /** + * Remove a single event listener. + * + * @method Phaser.Signal#remove + * @param {function} listener - Handler function that should be removed. + * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {function} Listener handler function. + */ + remove: function (listener, context) { + + this.validateListener(listener, 'remove'); + + var i = this._indexOfListener(listener, context); + + if (i !== -1) + { + this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal + this._bindings.splice(i, 1); + } + + return listener; + + }, + + /** + * Remove all event listeners. + * + * @method Phaser.Signal#removeAll + * @param {object} [context=null] - If specified only listeners for the given context will be removed. + */ + removeAll: function (context) { + + if (context === undefined) { context = null; } + + if (!this._bindings) + { + return; + } + + var n = this._bindings.length; + + while (n--) + { + if (context) + { + if (this._bindings[n].context === context) + { + this._bindings[n]._destroy(); + this._bindings.splice(n, 1); + } + } + else + { + this._bindings[n]._destroy(); + } + } + + if (!context) + { + this._bindings.length = 0; + } + + }, + + /** + * Gets the total number of listeners attached to this Signal. + * + * @method Phaser.Signal#getNumListeners + * @return {integer} Number of listeners attached to the Signal. + */ + getNumListeners: function () { + + return this._bindings ? this._bindings.length : 0; + + }, + + /** + * Stop propagation of the event, blocking the dispatch to next listener on the queue. + * + * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. + * See {@link #active} to enable/disable the signal entirely. + * + * @method Phaser.Signal#halt + */ + halt: function () { + + this._shouldPropagate = false; + + }, + + /** + * Dispatch / broadcast the event to all listeners. + * + * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}. + * + * @method Phaser.Signal#dispatch + * @param {any} [params] - Parameters that should be passed to each handler. + */ + dispatch: function () { + + if (!this.active || !this._bindings) + { + return; + } + + var paramsArr = Array.prototype.slice.call(arguments); + var n = this._bindings.length; + var bindings; + + if (this.memorize) + { + this._prevParams = paramsArr; + } + + if (!n) + { + // Should come after memorize + return; + } + + bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch + this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. + + //execute all callbacks until end of the list or until a callback returns `false` or stops propagation + //reverse loop since listeners with higher priority will be added at the end of the list + do { + n--; + } + while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); + + }, + + /** + * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any. + * + * @method Phaser.Signal#forget + */ + forget: function() { + + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * Dispose the signal - no more events can be dispatched. + * + * This removes all event listeners and clears references to external objects. + * Calling methods on a disposed objects results in undefined behavior. + * + * @method Phaser.Signal#dispose + */ + dispose: function () { + + this.removeAll(); + + this._bindings = null; + if (this._prevParams) + { + this._prevParams = null; + } + + }, + + /** + * A string representation of the object. + * + * @method Phaser.Signal#toString + * @return {string} String representation of the object. + */ + toString: function () { + + return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']'; + + } + +}; + +/** +* Create a `dispatch` function that maintains a binding to the original Signal context. +* +* Use the resulting value if the dispatch function needs to be passed somewhere +* or called independently of the Signal object. +* +* @memberof Phaser.Signal +* @property {function} boundDispatch +*/ +Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", { + + get: function () { + var _this = this; + return this._boundDispatch || (this._boundDispatch = function () { + return _this.dispatch.apply(_this, arguments); + }); + } + +}); + +Phaser.Signal.prototype.constructor = Phaser.Signal; + +/** +* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Object that represents a binding between a Signal and a listener function. +* This is an internal constructor and shouldn't be created directly. +* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. +* +* @class Phaser.SignalBinding +* @constructor +* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to. +* @param {function} listener - Handler function bound to the signal. +* @param {boolean} isOnce - If binding should be executed just once. +* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). +* @param {number} [priority] - The priority level of the event listener. (default = 0). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. +*/ +Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) { + + /** + * @property {Phaser.Game} _listener - Handler function bound to the signal. + * @private + */ + this._listener = listener; + + if (isOnce) + { + this._isOnce = true; + } + + if (listenerContext != null) /* not null/undefined */ + { + this.context = listenerContext; + } + + /** + * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to. + * @private + */ + this._signal = signal; + + if (priority) + { + this._priority = priority; + } + + if (args && args.length) + { + this._args = args; + } + +}; + +Phaser.SignalBinding.prototype = { + + /** + * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + */ + context: null, + + /** + * @property {boolean} _isOnce - If binding should be executed just once. + * @private + */ + _isOnce: false, + + /** + * @property {number} _priority - Listener priority. + * @private + */ + _priority: 0, + + /** + * @property {array} _args - Listener arguments. + * @private + */ + _args: null, + + /** + * @property {number} callCount - The number of times the handler function has been called. + */ + callCount: 0, + + /** + * If binding is active and should be executed. + * @property {boolean} active + * @default + */ + active: true, + + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). + * @property {array|null} params + * @default + */ + params: null, + + /** + * Call listener passing arbitrary parameters. + * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. + * @method Phaser.SignalBinding#execute + * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener. + * @return {any} Value returned by the listener. + */ + execute: function(paramsArr) { + + var handlerReturn, params; + + if (this.active && !!this._listener) + { + params = this.params ? this.params.concat(paramsArr) : paramsArr; + + if (this._args) + { + params = params.concat(this._args); + } + + handlerReturn = this._listener.apply(this.context, params); + + this.callCount++; + + if (this._isOnce) + { + this.detach(); + } + } + + return handlerReturn; + + }, + + /** + * Detach binding from signal. + * alias to: @see mySignal.remove(myBinding.getListener()); + * @method Phaser.SignalBinding#detach + * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ + detach: function () { + return this.isBound() ? this._signal.remove(this._listener, this.context) : null; + }, + + /** + * @method Phaser.SignalBinding#isBound + * @return {boolean} True if binding is still bound to the signal and has a listener. + */ + isBound: function () { + return (!!this._signal && !!this._listener); + }, + + /** + * @method Phaser.SignalBinding#isOnce + * @return {boolean} If SignalBinding will only be executed once. + */ + isOnce: function () { + return this._isOnce; + }, + + /** + * @method Phaser.SignalBinding#getListener + * @return {function} Handler function bound to the signal. + */ + getListener: function () { + return this._listener; + }, + + /** + * @method Phaser.SignalBinding#getSignal + * @return {Phaser.Signal} Signal that listener is currently bound to. + */ + getSignal: function () { + return this._signal; + }, + + /** + * Delete instance properties + * @method Phaser.SignalBinding#_destroy + * @private + */ + _destroy: function () { + delete this._signal; + delete this._listener; + delete this.context; + }, + + /** + * @method Phaser.SignalBinding#toString + * @return {string} String representation of the object. + */ + toString: function () { + return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']'; + } + +}; + +Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding; + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Filter class to use for any Phaser filter development. +* If you want to make a custom filter, this should be your base class. +* +* The default uniforms, types and values for all Filters are: +* +* ```javascript +* resolution: { type: '2f', value: { x: 256, y: 256 }} +* time: { type: '1f', value: 0 } +* mouse: { type: '2f', value: { x: 0.0, y: 0.0 } } +* date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] } +* sampleRate: { type: '1f', value: 44100.0 } +* iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } +* ``` +* +* The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and +* therefore only work in WebGL and are not supported by Canvas at all. +* +* @class Phaser.Filter +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [uniforms] - Uniform mappings object. The uniforms are added on the default uniforms, or replace them if the keys are the same. +* @param {Array|string} [fragmentSrc] - The fragment shader code. Either an array, one element per line of code, or a string. +*/ +Phaser.Filter = function (game, uniforms, fragmentSrc) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. + * @default + */ + this.type = Phaser.WEBGL_FILTER; + + /** + * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. + * For example the blur filter has two passes blurX and blurY. + * @property {array} passes - An array of filter objects. + * @private + */ + this.passes = [ this ]; + + /** + * @property {array} shaders - Array an array of shaders. + * @private + */ + this.shaders = []; + + /** + * @property {boolean} dirty - Internal PIXI var. + * @default + */ + this.dirty = true; + + /** + * @property {number} padding - Internal PIXI var. + * @default + */ + this.padding = 0; + + /** + * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same) + */ + this.prevPoint = new Phaser.Point(); + + /* + * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D. + */ + + var d = new Date(); + + /** + * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. + */ + this.uniforms = { + + resolution: { type: '2f', value: { x: 256, y: 256 }}, + time: { type: '1f', value: 0 }, + mouse: { type: '2f', value: { x: 0.0, y: 0.0 } }, + date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] }, + sampleRate: { type: '1f', value: 44100.0 }, + iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } }, + iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + + }; + + // Copy over / replace any passed in the constructor + if (uniforms) + { + for (var key in uniforms) + { + this.uniforms[key] = uniforms[key]; + } + } + + // If fragmentSrc is a string, split it based on new-lines into an array + if (typeof fragmentSrc === 'string') + { + fragmentSrc = fragmentSrc.split('\n'); + } + + /** + * @property {array|string} fragmentSrc - The fragment shader code. + */ + this.fragmentSrc = fragmentSrc || []; + +}; + +Phaser.Filter.prototype = { + + /** + * This should be over-ridden. Will receive a variable number of arguments. + * + * @method Phaser.Filter#init + */ + init: function () { + + // This should be over-ridden. Will receive a variable number of arguments. + + }, + + /** + * Set the resolution uniforms on the filter. + * + * @method Phaser.Filter#setResolution + * @param {number} width - The width of the display. + * @param {number} height - The height of the display. + */ + setResolution: function (width, height) { + + this.uniforms.resolution.value.x = width; + this.uniforms.resolution.value.y = height; + + }, + + /** + * Updates the filter. + * + * @method Phaser.Filter#update + * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. + */ + update: function (pointer) { + + if (pointer) + { + var x = pointer.x / this.game.width; + var y = 1 - pointer.y / this.game.height; + + if (x !== this.prevPoint.x || y !== this.prevPoint.y) + { + this.uniforms.mouse.value.x = x.toFixed(2); + this.uniforms.mouse.value.y = y.toFixed(2); + this.prevPoint.set(x, y); + } + } + + this.uniforms.time.value = this.game.time.totalElapsedSeconds(); + + }, + + /** + * Creates a new Phaser.Image object using a blank texture and assigns + * this Filter to it. The image is then added to the world. + * + * If you don't provide width and height values then Filter.width and Filter.height are used. + * + * If you do provide width and height values then this filter will be resized to match those + * values. + * + * @method Phaser.Filter#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. + * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, width, height, anchorX, anchorY) { + + if (anchorX === undefined) { anchorX = 0; } + if (anchorY === undefined) { anchorY = 0; } + + if (width !== undefined && width !== null) + { + this.width = width; + } + else + { + width = this.width; + } + + if (height !== undefined && height !== null) + { + this.height = height; + } + else + { + height = this.height; + } + + var image = this.game.add.image(x, y, Phaser.Cache.DEFAULT); + + image.width = width; + image.height = height; + + image.anchor.set(anchorX, anchorY); + + image.filters = [ this ]; + + return image; + + }, + + /** + * Syncs the uniforms between the class object and the shaders. + * + * @method Phaser.Filter#syncUniforms + */ + syncUniforms: function () { + + for (var i = 0; i < this.shaders.length; i++) + { + this.shaders[i].dirty = true; + } + + }, + + /** + * Clear down this Filter and null out references to game. + * + * @method Phaser.Filter#destroy + */ + destroy: function () { + + this.passes.length = 0; + this.shaders.length = 0; + this.fragmentSrc.length = 0; + + this.game = null; + this.uniforms = null; + this.prevPoint = null; + + } + +}; + +Phaser.Filter.prototype.constructor = Phaser.Filter; + +/** +* @name Phaser.Filter#width +* @property {number} width - The width (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'width', { + + get: function () { + + return this.uniforms.resolution.value.x; + + }, + + set: function (value) { + + this.uniforms.resolution.value.x = value; + + } + +}); + +/** +* @name Phaser.Filter#height +* @property {number} height - The height (resolution uniform) +*/ +Object.defineProperty(Phaser.Filter.prototype, 'height', { + + get: function () { + + return this.uniforms.resolution.value.y; + + }, + + set: function (value) { + + this.uniforms.resolution.value.y = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is a base Plugin template to use for any Phaser plugin development. +* +* ##### Callbacks +* +* add | active | visible | remove +* -----|-------------|-------------|-------- +* init | | | +* | preUpdate* | | +* | update* | render* | +* | postUpdate* | postRender* | +* | | | destroy +* +* Update and render calls are repeated (*). +* +* @class Phaser.Plugin +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager. +*/ +Phaser.Plugin = function (game, parent) { + + if (parent === undefined) { parent = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. + */ + this.parent = parent; + + /** + * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. + * @default + */ + this.active = false; + + /** + * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. + * @default + */ + this.visible = false; + + /** + * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. + * @default + */ + this.hasPreUpdate = false; + + /** + * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. + * @default + */ + this.hasUpdate = false; + + /** + * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. + * @default + */ + this.hasPostUpdate = false; + + /** + * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. + * @default + */ + this.hasRender = false; + + /** + * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. + * @default + */ + this.hasPostRender = false; + +}; + +Phaser.Plugin.prototype = { + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It is only called if active is set to true. + * @method Phaser.Plugin#preUpdate + */ + preUpdate: function () { + }, + + /** + * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It is only called if active is set to true. + * @method Phaser.Plugin#update + */ + update: function () { + }, + + /** + * Render is called right after the Game Renderer completes, but before the State.render. + * It is only called if visible is set to true. + * @method Phaser.Plugin#render + */ + render: function () { + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It is only called if visible is set to true. + * @method Phaser.Plugin#postRender + */ + postRender: function () { + }, + + /** + * Clear down this Plugin and null out references + * @method Phaser.Plugin#destroy + */ + destroy: function () { + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + + } + +}; + +Phaser.Plugin.prototype.constructor = Phaser.Plugin; + +/* jshint newcap: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. +* +* @class Phaser.PluginManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.PluginManager = function(game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager. + */ + this.plugins = []; + + /** + * @property {number} _len - Internal cache var. + * @private + */ + this._len = 0; + + /** + * @property {number} _i - Internal cache var. + * @private + */ + this._i = 0; + +}; + +Phaser.PluginManager.prototype = { + + /** + * Add a new Plugin into the PluginManager. + * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.PluginManager#add + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + add: function (plugin) { + + var args = Array.prototype.slice.call(arguments, 1); + var result = false; + + // Prototype? + if (typeof plugin === 'function') + { + plugin = new plugin(this.game, this); + } + else + { + plugin.game = this.game; + plugin.parent = this; + } + + // Check for methods now to avoid having to do this every loop + 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; + } + + // The plugin must have at least one of the above functions to be added to the PluginManager. + 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); + + // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager + if (typeof plugin['init'] === 'function') + { + plugin.init.apply(plugin, args); + } + + return plugin; + } + else + { + return null; + } + }, + + /** + * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. + * + * @method Phaser.PluginManager#remove + * @param {Phaser.Plugin} plugin - The plugin to be removed. + * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed? + */ + remove: function (plugin, destroy) { + + if (destroy === undefined) { destroy = true; } + + this._i = this._len; + + while (this._i--) + { + if (this.plugins[this._i] === plugin) + { + if (destroy) + { + plugin.destroy(); + } + + this.plugins.splice(this._i, 1); + this._len--; + return; + } + } + + }, + + /** + * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. + * + * @method Phaser.PluginManager#removeAll + */ + removeAll: function() { + + this._i = this._len; + + while (this._i--) + { + this.plugins[this._i].destroy(); + } + + this.plugins.length = 0; + this._len = 0; + + }, + + /** + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#preUpdate + */ + 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 is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#update + */ + 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 is the last thing to be called before the world render. + * In particular, it is called after the world postUpdate, which means the camera has been adjusted. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#postUpdate + */ + 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 is called right after the Game Renderer completes, but before the State.render. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#render + */ + 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(); + } + } + + }, + + /** + * Post-render is called after the Game Renderer and State.render have run. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#postRender + */ + 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(); + } + } + + }, + + /** + * Clear down this PluginManager, calls destroy on every plugin and nulls out references. + * + * @method Phaser.PluginManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.game = null; + + } + +}; + +Phaser.PluginManager.prototype.constructor = Phaser.PluginManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Stage controls root level display objects upon which everything is displayed. +* It also handles browser visibility handling and the pausing due to loss of focus. +* +* @class Phaser.Stage +* @extends PIXI.DisplayObjectContainer +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Stage = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {string} name - The name of this object. + * @default + */ + this.name = '_stage_root'; + + /** + * By default if the browser tab loses focus the game will pause. + * You can stop that behavior by setting this property to true. + * Note that the browser can still elect to pause your game if it wishes to do so, + * for example swapping to another browser tab. This will cause the RAF callback to halt, + * effectively pausing your game, even though no in-game pause event is triggered if you enable this property. + * @property {boolean} disableVisibilityChange + * @default + */ + this.disableVisibilityChange = false; + + /** + * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. + * @default + */ + this.exists = true; + + /** + * @property {Phaser.Matrix} worldTransform - Current transform of the object based on world (parent) factors + * @private + * @readOnly + */ + this.worldTransform = new Phaser.Matrix(); + + /** + * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage) + * @private + * @readOnly + */ + this.stage = this; + + /** + * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. + */ + this.currentRenderOrderID = 0; + + /** + * @property {string} hiddenVar - The page visibility API event name. + * @private + */ + this._hiddenVar = 'hidden'; + + /** + * @property {function} _onChange - The blur/focus event handler. + * @private + */ + this._onChange = null; + + /** + * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor. + * @private + */ + this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' }; + + if (!this.game.transparent) + { + // transparent = 0,0,0,0 - otherwise r,g,b,1 + this._bgColor.a = 1; + } + + if (game.config) + { + this.parseConfig(game.config); + } + +}; + +Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Stage.prototype.constructor = Phaser.Stage; + +/** +* Parses a Game configuration object. +* +* @method Phaser.Stage#parseConfig +* @protected +* @param {object} config -The configuration object to parse. +*/ +Phaser.Stage.prototype.parseConfig = function (config) { + + if (config['disableVisibilityChange']) + { + this.disableVisibilityChange = config['disableVisibilityChange']; + } + + if (config['backgroundColor']) + { + this.setBackgroundColor(config['backgroundColor']); + } + +}; + +/** +* Initialises the stage and adds the event listeners. +* @method Phaser.Stage#boot +* @private +*/ +Phaser.Stage.prototype.boot = function () { + + Phaser.DOM.getOffset(this.game.canvas, this.offset); + + Phaser.Canvas.setUserSelect(this.game.canvas, 'none'); + Phaser.Canvas.setTouchAction(this.game.canvas, 'none'); + + this.checkVisibility(); + +}; + +/** +* This is called automatically after the plugins preUpdate and before the State.update. +* Most objects have preUpdate methods and it's where initial movement and positioning is done. +* +* @method Phaser.Stage#preUpdate +*/ +Phaser.Stage.prototype.preUpdate = function () { + + this.currentRenderOrderID = 0; + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + +}; + +/** +* This is called automatically after the State.update, but before particles or plugins update. +* +* @method Phaser.Stage#update +*/ +Phaser.Stage.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + this.children[i].update(); + } + +}; + +/** +* This is called automatically before the renderer runs and after the plugins have updated. +* In postUpdate this is where all the final physics calculations and object positioning happens. +* The objects are processed in the order of the display list. +* +* @method Phaser.Stage#postUpdate +*/ +Phaser.Stage.prototype.postUpdate = function () { + + // Apply the camera shake, fade, bounds, etc + this.game.camera.update(); + + // Camera target first? + if (this.game.camera.target) + { + this.game.camera.target.postUpdate(); + + this.updateTransform(); + + this.game.camera.updateTarget(); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + this.updateTransform(); + +}; + +/** +* Updates the transforms for all objects on the display list. +* This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. +* +* @method Phaser.Stage#updateTransform +*/ +Phaser.Stage.prototype.updateTransform = function () { + + this.worldAlpha = 1; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + +}; + +/** +* Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. +* Also listens for window.onblur and window.onfocus. +* +* @method Phaser.Stage#checkVisibility +*/ +Phaser.Stage.prototype.checkVisibility = function () { + + if (document.hidden !== undefined) + { + this._hiddenVar = 'visibilitychange'; + } + else if (document.webkitHidden !== undefined) + { + this._hiddenVar = 'webkitvisibilitychange'; + } + else if (document.mozHidden !== undefined) + { + this._hiddenVar = 'mozvisibilitychange'; + } + else if (document.msHidden !== undefined) + { + this._hiddenVar = 'msvisibilitychange'; + } + else + { + this._hiddenVar = null; + } + + var _this = this; + + this._onChange = function (event) { + return _this.visibilityChange(event); + }; + + this._onClick = function (event) { + if ((document.hasFocus !== undefined) && !document.hasFocus()) + { + _this.visibilityChange(event); + } + }; + + // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus + if (this._hiddenVar) + { + document.addEventListener(this._hiddenVar, this._onChange, false); + } + + window.onblur = this._onChange; + window.onfocus = this._onChange; + + window.onpagehide = this._onChange; + window.onpageshow = this._onChange; + + window.addEventListener('click', this._onClick); + + if (this.game.device.cocoonJSApp) + { + CocoonJS.App.onSuspended.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" }); + }); + + CocoonJS.App.onActivated.addEventListener(function () { + Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" }); + }); + } + +}; + +/** +* This method is called when the document visibility is changed. +* +* - `blur` and `pagehide` events trigger {@link Phaser.Game#onBlur}. They {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `click`, `focus`, and `pageshow` trigger {@link Phaser.Game#onFocus}. They {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (hidden) and CocoonJS's `onSuspended` {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. +* - `visibilitychange` (visible) and CocoonJS's `onActivated` {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. +* +* @method Phaser.Stage#visibilityChange +* @param {Event} event - Its type will be used to decide whether the game should be paused or not. +*/ +Phaser.Stage.prototype.visibilityChange = function (event) { + + // These events always trigger the Game#onBlur or Game#onFocus signals. + + switch (event.type) + { + case 'blur': + case 'pagehide': + this.game.focusLoss(event); + return; + case 'click': + case 'focus': + case 'pageshow': + this.game.focusGain(event); + return; + } + + if (this.disableVisibilityChange) + { + return; + } + + if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause") + { + this.game.gamePaused(event); + } + else + { + this.game.gameResumed(event); + } + +}; + +/** +* Sets the background color for the Stage. +* +* The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). +* +* An alpha channel is _not_ supported and will be ignored. +* +* If you've set your game to be {@link Phaser.Game#transparent transparent} then calls to setBackgroundColor are ignored. +* +* If {@link Phaser.Game#clearBeforeRender} is off then the background color won't appear. +* +* @method Phaser.Stage#setBackgroundColor +* @param {number|string} color - The color of the background. +*/ +Phaser.Stage.prototype.setBackgroundColor = function (color) { + + if (this.game.transparent) { return; } + + Phaser.Color.valueToColor(color, this._bgColor); + Phaser.Color.updateColor(this._bgColor); + + // For gl.clearColor (canvas uses _bgColor.rgba) + this._bgColor.r /= 255; + this._bgColor.g /= 255; + this._bgColor.b /= 255; + this._bgColor.a = 1; + +}; + +/** +* Destroys the Stage and removes event listeners. +* +* @method Phaser.Stage#destroy +*/ +Phaser.Stage.prototype.destroy = function () { + + if (this._hiddenVar) + { + document.removeEventListener(this._hiddenVar, this._onChange, false); + } + + window.onpagehide = null; + window.onpageshow = null; + + window.onblur = null; + window.onfocus = null; + + window.removeEventListener('click', this._onClick); + +}; + +/** +* Adds an existing object to the Stage. +* +* The child is automatically added to the front of the Stage, and is displayed above every previous child. +* Or if the _optional_ `index` is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the object was already on the Stage, it is simply returned, and nothing else happens to it. +* +* @method Phaser.Stage#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent] - Unused. Kept for compatibility with {@link Phaser.Group#add}. +* @param {integer} [index] - The index to insert the object to. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Stage.prototype.add = function (child, silent, index) { + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + this.addChild(child); + } + else + { + this.addChildAt(child, index); + } + + return child; + +}; + +/** +* @name Phaser.Stage#backgroundColor +* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' +* @see Phaser.Stage#setBackgroundColor +*/ +Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", { + + get: function () { + + return this._bgColor.color; + + }, + + set: function (color) { + + this.setBackgroundColor(color); + + } + +}); + +/** +* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. +* +* @name Phaser.Stage#smoothed +* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) +*/ +Object.defineProperty(Phaser.Stage.prototype, "smoothed", { + + get: function () { + + return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR; + + }, + + set: function (value) { + + if (value) + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR; + } + else + { + PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}. +* +* Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. +* For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. +* +* In addition, Groups provides support for fast pooling and object recycling. +* +* Groups are also display objects and can be nested as children within other Groups. +* +* @class Phaser.Group +* @extends PIXI.DisplayObjectContainer +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to. +* If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent. +* @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World. +* @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}. +* @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values. +*/ +Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) { + + if (addToStage === undefined) { addToStage = false; } + if (enableBody === undefined) { enableBody = false; } + if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + if (parent === undefined) + { + parent = game.world; + } + + /** + * A name for this group. Not used internally but useful for debugging. + * @property {string} name + */ + this.name = name || 'group'; + + /** + * The z-depth value of this object within its parent container/Group - the World is a Group as well. + * This value must be unique for each child in a Group. + * @property {integer} z + * @readOnly + */ + this.z = 0; + + PIXI.DisplayObjectContainer.call(this); + + if (addToStage) + { + this.game.stage.addChild(this); + this.z = this.game.stage.children.length; + } + else + { + if (parent) + { + parent.addChild(this); + this.z = parent.children.length; + } + } + + /** + * Internal Phaser Type value. + * @property {integer} type + * @protected + */ + this.type = Phaser.GROUP; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. + * @property {boolean} alive + * @default + */ + this.alive = true; + + /** + * If exists is false the group will be excluded from collision checks and filters such as {@link #forEachExists}. The group will not call `preUpdate` and `postUpdate` on its children and the children will not receive physics updates or camera/world boundary checks. The group will still be {@link #visible} and will still call `update` on its children (unless {@link #updateOnlyExistingChildren} is true). + * @property {boolean} exists + * @default + */ + this.exists = true; + + /** + * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. + * @property {boolean} ignoreDestroy + * @default + */ + this.ignoreDestroy = false; + + /** + * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method + * called on the next logic update. + * You can set it directly to flag the Group to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy a Group from within one of its own callbacks + * or a callback of one of its children. + * + * @property {boolean} pendingDestroy + */ + this.pendingDestroy = false; + + /** + * The type of objects that will be created when using {@link #create} or {@link #createMultiple}. + * + * It should extend either Sprite or Image and accept the same constructor arguments: `(game, x, y, key, frame)`. + * + * @property {function} classType + * @default {@link Phaser.Sprite} + */ + this.classType = Phaser.Sprite; + + /** + * The current display object that the group cursor is pointing to, if any. (Can be set manually.) + * + * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}. + * @property {?DisplayObject} cursor + */ + this.cursor = null; + + /** + * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` + * on any children _added_ to, or _created by_, this Group. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * @property {boolean} inputEnableChildren + * @default + */ + this.inputEnableChildren = false; + + /** + * Skip children with `exists = false` in {@link #update}. + * + * @property {boolean} updateOnlyExistingChildren + * @default + */ + this.updateOnlyExistingChildren = false; + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputDown + */ + this.onChildInputDown = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, + * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer + * is still over the Sprite or not. + * + * @property {Phaser.Signal} onChildInputUp + */ + this.onChildInputUp = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOver + */ + this.onChildInputOver = new Phaser.Signal(); + + /** + * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOut + */ + this.onChildInputOut = new Phaser.Signal(); + + /** + * If true all Sprites created by, or added to this group, will have a physics body enabled on them. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * The default body type is controlled with {@link #physicsBodyType}. + * @property {boolean} enableBody + */ + this.enableBody = enableBody; + + /** + * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well. + * + * This only works for P2 bodies. + * @property {boolean} enableBodyDebug + * @default + */ + this.enableBodyDebug = false; + + /** + * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites. + * + * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc. + * @property {integer} physicsBodyType + */ + this.physicsBodyType = physicsBodyType; + + /** + * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. + * + * It should be set to one of the Phaser.Physics.Arcade sort direction constants: + * + * Phaser.Physics.Arcade.SORT_NONE + * Phaser.Physics.Arcade.LEFT_RIGHT + * Phaser.Physics.Arcade.RIGHT_LEFT + * Phaser.Physics.Arcade.TOP_BOTTOM + * Phaser.Physics.Arcade.BOTTOM_TOP + * + * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. + * + * @property {integer} physicsSortDirection + * @default + */ + this.physicsSortDirection = null; + + /** + * This signal is dispatched when the group is destroyed. + * @property {Phaser.Signal} onDestroy + */ + this.onDestroy = new Phaser.Signal(); + + /** + * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next. + * @readOnly + */ + this.cursorIndex = 0; + + /** + * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. + * + * Note that the cameraOffset values are in addition to any parent in the display list. + * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x + * + * @property {boolean} fixedToCamera + */ + this.fixedToCamera = false; + + /** + * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view. + * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. + * @property {Phaser.Point} cameraOffset + */ + this.cameraOffset = new Phaser.Point(); + + /** + * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. + * + * Only children of this Group can be added to and removed from the hash. + * + * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. + * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own + * sorting and filtering of Group children without touching their z-index (and therefore display draw order) + * + * @property {array} hash + */ + this.hash = []; + + /** + * The property on which children are sorted. + * @property {string} _sortProperty + * @private + */ + this._sortProperty = 'z'; + +}; + +Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Group.prototype.constructor = Phaser.Group; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_NONE = 0; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_TOTAL = 1; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_CHILD = 2; + +/** +* A returnType value, as specified in {@link #iterate} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.RETURN_ALL = 3; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_ASCENDING = -1; + +/** +* A sort ordering value, as specified in {@link #sort} eg. +* @constant +* @type {integer} +*/ +Phaser.Group.SORT_DESCENDING = 1; + +/** +* Adds an existing object as the top child in this group. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If the child was already in this Group, it is simply returned, and nothing else happens to it. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* Use {@link #create} to create and add a new child. +* +* @method Phaser.Group#add +* @param {DisplayObject} child - The display object to add as a child. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.add = function (child, silent, index) { + + if (silent === undefined) { silent = false; } + + if (child.parent === this) + { + return child; + } + + if (child.body && child.parent && child.parent.hash) + { + child.parent.removeFromHash(child); + } + + if (index === undefined) + { + child.z = this.children.length; + + this.addChild(child); + } + else + { + this.addChildAt(child, index); + + this.updateZ(); + } + + if (this.enableBody && child.hasOwnProperty('body') && child.body === null) + { + this.game.physics.enable(child, this.physicsBodyType); + } + else if (child.body) + { + this.addToHash(child); + } + + if (this.inputEnableChildren && (!child.input || child.inputEnabled)) + { + child.inputEnabled = true; + } + + if (!silent && child.events) + { + child.events.onAddedToGroup$dispatch(child, this); + } + + if (this.cursor === null) + { + this.cursor = child; + } + + return child; + +}; + +/** +* Adds an existing object to this group. +* +* The child is added to the group at the location specified by the index value, this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#addAt +* @param {DisplayObject} child - The display object to add as a child. +* @param {integer} [index=0] - The index within the group to insert the child to. +* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject} The child that was added to the group. +*/ +Phaser.Group.prototype.addAt = function (child, index, silent) { + + return this.add(child, silent, index); + +}; + +/** +* Adds a child of this Group into the hash array. +* This call will return false if the child is not a child of this Group, or is already in the hash. +* +* @method Phaser.Group#addToHash +* @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. +* @return {boolean} True if the child was successfully added to the hash, otherwise false. +*/ +Phaser.Group.prototype.addToHash = function (child) { + + if (child.parent === this) + { + var index = this.hash.indexOf(child); + + if (index === -1) + { + this.hash.push(child); + return true; + } + } + + return false; + +}; + +/** +* Removes a child of this Group from the hash array. +* This call will return false if the child is not in the hash. +* +* @method Phaser.Group#removeFromHash +* @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash. +* @return {boolean} True if the child was successfully removed from the hash, otherwise false. +*/ +Phaser.Group.prototype.removeFromHash = function (child) { + + if (child) + { + var index = this.hash.indexOf(child); + + if (index !== -1) + { + this.hash.splice(index, 1); + return true; + } + } + + return false; + +}; + +/** +* Adds an array of existing Display Objects to this Group. +* +* The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. +* +* As well as an array you can also pass another Group as the first argument. In this case all of the children from that +* Group will be removed from it and added into this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#addMultiple +* @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event. +* @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group. +*/ +Phaser.Group.prototype.addMultiple = function (children, silent) { + + if (children instanceof Phaser.Group) + { + children.moveAll(this, silent); + } + else if (Array.isArray(children)) + { + for (var i = 0; i < children.length; i++) + { + this.add(children[i], silent); + } + } + + return children; + +}; + +/** +* Returns the child found at the given index within this group. +* +* @method Phaser.Group#getAt +* @param {integer} index - The index to return the child from. +* @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index. +*/ +Phaser.Group.prototype.getAt = function (index) { + + if (index < 0 || index >= this.children.length) + { + return -1; + } + else + { + return this.getChildAt(index); + } + +}; + +/** +* Creates a new Phaser.Sprite object and adds it to the top of this group. +* +* Use {@link #classType} to change the type of object created. +* +* The child is automatically added to the top of the group, and is displayed above every previous child. +* +* Or if the _optional_ index is specified, the child is added at the location specified by the index value, +* this allows you to control child ordering. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#create +* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. +* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {boolean} [exists=true] - The default exists state of the Sprite. +* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. +* @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed. +*/ +Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) { + + if (exists === undefined) { exists = true; } + + var child = new this.classType(this.game, x, y, key, frame); + + child.exists = exists; + child.visible = exists; + child.alive = exists; + + return this.add(child, false, index); + +}; + +/** +* Creates multiple Phaser.Sprite objects and adds them to the top of this Group. +* +* This method is useful if you need to quickly generate a pool of sprites, such as bullets. +* +* Use {@link #classType} to change the type of object created. +* +* You can provide an array as the `key` and / or `frame` arguments. When you do this +* it will create `quantity` Sprites for every key (and frame) in the arrays. +* +* For example: +* +* `createMultiple(25, ['ball', 'carrot'])` +* +* In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be +* created in total, 25 of each. You can also have the `frame` as an array: +* +* `createMultiple(5, 'bricks', [0, 1, 2, 3])` +* +* In the above there is one key (bricks), which is a sprite sheet. The frames array tells +* this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because +* the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with +* frame 1, and so on. +* +* If you set both the key and frame arguments to be arrays then understand it will create +* a total quantity of sprites equal to the size of both arrays times each other. I.e.: +* +* `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` +* +* The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. +* It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. +* In total it will have created 120 sprites. +* +* By default the Sprites will have their `exists` property set to `false`, and they will be +* positioned at 0x0, relative to the `Group.x / y` values. +* +* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. +* +* @method Phaser.Group#createMultiple +* @param {integer} quantity - The number of Sprites to create. +* @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. +* @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. +* @param {boolean} [exists=false] - The default exists state of the Sprite. +* @param {function} [callback] - The function that will be called for each applicable child. It will be passed the new child and the loop index (0 through quantity - 1). +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). The default context is the new child. +* @return {array} An array containing all of the Sprites that were created. +*/ +Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, callback, callbackContext) { + + if (frame === undefined) { frame = 0; } + if (exists === undefined) { exists = false; } + + if (!Array.isArray(key)) + { + key = [ key ]; + } + + if (!Array.isArray(frame)) + { + frame = [ frame ]; + } + + var _this = this; + var children = []; + + key.forEach(function(singleKey) { + + frame.forEach(function(singleFrame) { + + for (var i = 0; i < quantity; i++) + { + var child = _this.create(0, 0, singleKey, singleFrame, exists); + + if (callback) { callback.call(callbackContext || child, child, i); } + + children.push(child); + } + + }); + + }); + + return children; + +}; + +/** +* Internal method that re-applies all of the children's Z values. +* +* This must be called whenever children ordering is altered so that their `z` indices are correctly updated. +* +* @method Phaser.Group#updateZ +* @protected +*/ +Phaser.Group.prototype.updateZ = function () { + + var i = this.children.length; + + while (i--) + { + this.children[i].z = i; + } + +}; + +/** +* This method iterates through all children in the Group (regardless if they are visible or exist) +* and then changes their position so they are arranged in a Grid formation. Children must have +* the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have +* this. +* +* The grid dimensions are determined by the first four arguments. The `width` and `height` arguments +* relate to the width and height of the grid respectively. +* +* For example if the Group had 100 children in it: +* +* `Group.align(10, 10, 32, 32)` +* +* This will align all of the children into a grid formation of 10x10, using 32 pixels per +* grid cell. If you want a wider grid, you could do: +* +* `Group.align(25, 4, 32, 32)` +* +* This will align the children into a grid of 25x4, again using 32 pixels per grid cell. +* +* You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method +* to keep on aligning children until there are no children left. For example if this Group had +* 48 children in it, the following: +* +* `Group.align(-1, 8, 32, 32)` +* +* ... will align the children so that there are 8 children vertically (the second argument), +* and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) +* +* You can also do: +* +* `Group.align(10, -1, 32, 32)` +* +* In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit +* all of the children in. +* +* The `position` property allows you to control where in each grid cell the child is positioned. +* This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, +* `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, +* `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* +* The final argument; `offset` lets you start the alignment from a specific child index. +* +* @method Phaser.Group#align +* @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. +* @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. +* @param {integer} cellWidth - The width of each grid cell, in pixels. +* @param {integer} cellHeight - The height of each grid cell, in pixels. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. +* @return {boolean} True if the Group children were aligned, otherwise false. +*/ +Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, position, offset) { + + if (position === undefined) { position = Phaser.TOP_LEFT; } + if (offset === undefined) { offset = 0; } + + if (this.children.length === 0 || offset > this.children.length || (width === -1 && height === -1)) + { + return false; + } + + var r = new Phaser.Rectangle(0, 0, cellWidth, cellHeight); + var w = (width * cellWidth); + var h = (height * cellHeight); + + for (var i = offset; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child['alignIn']) + { + child.alignIn(r, position); + } + else + { + continue; + } + + if (width === -1) + { + // We keep laying them out horizontally until we've done them all + r.y += cellHeight; + + if (r.y === h) + { + r.x += cellWidth; + r.y = 0; + } + } + else if (height === -1) + { + // We keep laying them out vertically until we've done them all + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + } + } + else + { + // We keep laying them out until we hit the column limit + r.x += cellWidth; + + if (r.x === w) + { + r.x = 0; + r.y += cellHeight; + + if (r.y === h) + { + // We've hit the column limit, so return, even if there are children left + return true; + } + } + } + } + + return true; + +}; + +/** +* Sets the group cursor to the first child in the group. +* +* If the optional index parameter is given it sets the cursor to the object at that index instead. +* +* @method Phaser.Group#resetCursor +* @param {integer} [index=0] - Set the cursor to point to a specific index. +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.resetCursor = function (index) { + + if (index === undefined) { index = 0; } + + if (index > this.children.length - 1) + { + index = 0; + } + + if (this.cursor) + { + this.cursorIndex = index; + this.cursor = this.children[this.cursorIndex]; + return this.cursor; + } + +}; + +/** +* Advances the group cursor to the next (higher) object in the group. +* +* If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). +* +* @method Phaser.Group#next +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.next = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex >= this.children.length - 1) + { + this.cursorIndex = 0; + } + else + { + this.cursorIndex++; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Moves the group cursor to the previous (lower) child in the group. +* +* If the cursor is at the start of the group (bottom child) it is moved to the end (top child). +* +* @method Phaser.Group#previous +* @return {any} The child the cursor now points to. +*/ +Phaser.Group.prototype.previous = function () { + + if (this.cursor) + { + // Wrap the cursor? + if (this.cursorIndex === 0) + { + this.cursorIndex = this.children.length - 1; + } + else + { + this.cursorIndex--; + } + + this.cursor = this.children[this.cursorIndex]; + + return this.cursor; + } + +}; + +/** +* Swaps the position of two children in this group. +* +* Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. +* +* @method Phaser.Group#swap +* @param {any} child1 - The first child to swap. +* @param {any} child2 - The second child to swap. +*/ +Phaser.Group.prototype.swap = function (child1, child2) { + + this.swapChildren(child1, child2); + this.updateZ(); + +}; + +/** +* Brings the given child to the top of this group so it renders above all other children. +* +* @method Phaser.Group#bringToTop +* @param {any} child - The child to bring to the top of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.bringToTop = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length) + { + this.remove(child, false, true); + this.add(child, true); + } + + return child; + +}; + +/** +* Sends the given child to the bottom of this group so it renders below all other children. +* +* @method Phaser.Group#sendToBack +* @param {any} child - The child to send to the bottom of this group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.sendToBack = function (child) { + + if (child.parent === this && this.getIndex(child) > 0) + { + this.remove(child, false, true); + this.addAt(child, 0, true); + } + + return child; + +}; + +/** +* Moves the given child up one place in this group unless it's already at the top. +* +* @method Phaser.Group#moveUp +* @param {any} child - The child to move up in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveUp = function (child) { + + if (child.parent === this && this.getIndex(child) < this.children.length - 1) + { + var a = this.getIndex(child); + var b = this.getAt(a + 1); + + if (b) + { + this.swap(child, b); + } + } + + return child; + +}; + +/** +* Moves the given child down one place in this group unless it's already at the bottom. +* +* @method Phaser.Group#moveDown +* @param {any} child - The child to move down in the group. +* @return {any} The child that was moved. +*/ +Phaser.Group.prototype.moveDown = 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; + +}; + +/** +* Positions the child found at the given index within this group to the given x and y coordinates. +* +* @method Phaser.Group#xy +* @param {integer} index - The index of the child in the group to set the position of. +* @param {number} x - The new x position of the child. +* @param {number} y - The new y position of the 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; + } + +}; + +/** +* Reverses all children in this group. +* +* This operation applies only to immediate children and does not propagate to subgroups. +* +* @method Phaser.Group#reverse +*/ +Phaser.Group.prototype.reverse = function () { + + this.children.reverse(); + this.updateZ(); + +}; + +/** +* Get the index position of the given child in this group, which should match the child's `z` property. +* +* @method Phaser.Group#getIndex +* @param {any} child - The child to get the index for. +* @return {integer} The index of the child or -1 if it's not a member of this group. +*/ +Phaser.Group.prototype.getIndex = function (child) { + + return this.children.indexOf(child); + +}; + +/** +* Searches the Group for the first instance of a child with the `name` +* property matching the given argument. Should more than one child have +* the same name only the first instance is returned. +* +* @method Phaser.Group#getByName +* @param {string} name - The name to search for. +* @return {any} The first child with a matching name, or null if none were found. +*/ +Phaser.Group.prototype.getByName = function (name) { + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].name === name) + { + return this.children[i]; + } + } + + return null; + +}; + +/** +* Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. +* +* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. +* +* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. +* +* @method Phaser.Group#replace +* @param {any} oldChild - The child in this group that will be replaced. +* @param {any} newChild - The child to be inserted into this group. +* @return {any} Returns the oldChild that was replaced within this group. +*/ +Phaser.Group.prototype.replace = function (oldChild, newChild) { + + var index = this.getIndex(oldChild); + + if (index !== -1) + { + if (newChild.parent) + { + if (newChild.parent instanceof Phaser.Group) + { + newChild.parent.remove(newChild); + } + else + { + newChild.parent.removeChild(newChild); + } + } + + this.remove(oldChild); + + this.addAt(newChild, index); + + return oldChild; + } + +}; + +/** +* Checks if the child has the given property. +* +* Will scan up to 4 levels deep only. +* +* @method Phaser.Group#hasProperty +* @param {any} child - The child to check for the existence of the property on. +* @param {string[]} key - An array of strings that make up the property. +* @return {boolean} True if the child has the property, otherwise false. +*/ +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; + +}; + +/** +* Sets a property to the given value on the child. The operation parameter controls how the value is set. +* +* The operations are: +* - 0: set the existing value to the given value; if force is `true` a new property will be created if needed +* - 1: will add the given value to the value already present. +* - 2: will subtract the given value from the value already present. +* - 3: will multiply the value already present by the given value. +* - 4: will divide the value already present by the given value. +* +* @method Phaser.Group#setProperty +* @param {any} child - The child to set the property value on. +* @param {array} key - An array of strings that make up the property that will be set. +* @param {any} value - The value that will be set. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) { + + if (force === undefined) { force = false; } + + operation = operation || 0; + + // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration. + + // 0 = Equals + // 1 = Add + // 2 = Subtract + // 3 = Multiply + // 4 = Divide + + // We can't force a property in and the child doesn't have it, so abort. + // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too. + 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; + +}; + +/** +* Checks a property for the given value on the child. +* +* @method Phaser.Group#checkProperty +* @param {any} child - The child to check the property value on. +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} True if `child` is a child of this Group and the property was equal to value, false if not. +*/ +Phaser.Group.prototype.checkProperty = function (child, key, value, force) { + + if (force === undefined) { force = false; } + + if (this !== child.parent) + { + return false; + } + + var result = Phaser.Utils.getProperty(child, key); + + if (((result === undefined) && force) || (result !== value)) + { + return false; + } + + return true; + +}; + +/** +* Quickly set a property on a single child of this group to a new value. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#set +* @param {Phaser.Sprite} child - The child to set the property on. +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true. +* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +* @return {boolean} True if the property was set, false if not. +*/ +Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) { + + if (force === undefined) { force = false; } + + key = key.split('.'); + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible))) + { + return this.setProperty(child, key, value, operation, force); + } + +}; + +/** +* Quickly set the same property across all children of this group to a new value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. +* If you need that ability please see `Group.setAllChildren`. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAll +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + key = key.split('.'); + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + this.setProperty(this.children[i], key, value, operation, force); + } + } + +}; + +/** +* Quickly set the same property across all children of this group, and any child Groups, to a new value. +* +* If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. +* Unlike with `setAll` the property is NOT set on child Groups itself. +* +* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. +* +* @method Phaser.Group#setAllChildren +* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' +* @param {any} value - The value that will be set. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. +* @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. +* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. +*/ +Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + operation = operation || 0; + + for (var i = 0; i < this.children.length; i++) + { + if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible))) + { + if (this.children[i] instanceof Phaser.Group) + { + this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force); + } + else + { + this.setProperty(this.children[i], key.split('.'), value, operation, force); + } + } + } + +}; + +/** +* Test that the same property across all children of this group is equal to the given value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAll +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). +* @return {boolean} - True if all eligible children have the given property value (but see `force`); otherwise false. +*/ +Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + if (force === undefined) { force = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (!this.checkProperty(child, key, value, force)) + { + return false; + } + } + } + + return true; + +}; + +/** +* Test that at least one child of this group has the given property value. +* +* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. +* +* @method Phaser.Group#checkAny +* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' +* @param {any} value - The value that will be checked. +* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. +* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. +* @return {boolean} - True if at least one eligible child has the given property value; otherwise false. +*/ +Phaser.Group.prototype.checkAny = function (key, value, checkAlive, checkVisible) { + + if (checkAlive === undefined) { checkAlive = false; } + if (checkVisible === undefined) { checkVisible = false; } + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if ((!checkAlive || (checkAlive && child.alive)) && (!checkVisible || (checkVisible && child.visible))) + { + if (this.checkProperty(child, key, value)) + { + return true; + } + } + } + + return false; + +}; + +/** +* Adds the amount to the given property on all children in this group. +* +* `Group.addAll('x', 10)` will add 10 to the child.x value for each child. +* +* @method Phaser.Group#addAll +* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. +* @param {boolean} [checkAlive] - If true the property will only be changed if the child is alive. +* @param {boolean} [checkVisible] - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 1); + +}; + +/** +* Subtracts the amount from the given property on all children in this group. +* +* `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. +* +* @method Phaser.Group#subAll +* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 2); + +}; + +/** +* Multiplies the given property by the amount on all children in this group. +* +* `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. +* +* @method Phaser.Group#multiplyAll +* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 3); + +}; + +/** +* Divides the given property by the amount on all children in this group. +* +* `Group.divideAll('x', 2)` will half the child.x value for each child. +* +* @method Phaser.Group#divideAll +* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. +* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. +* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. +* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. +*/ +Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) { + + this.setAll(property, amount, checkAlive, checkVisible, 4); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to false. + * + * @method Phaser.Group#kill + */ +Phaser.Group.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + +}; + +/** + * Kills all children having exists=true. + * + * @method Phaser.Group#killAll + */ +Phaser.Group.prototype.killAll = function () { + + this.callAllExists('kill', true); + +}; + +/** + * Sets {@link #alive}, {@link #exists}, and {@link #visible} to true. + * + * @method Phaser.Group#revive + */ +Phaser.Group.prototype.revive = function () { + + this.alive = true; + this.exists = true; + this.visible = true; + +}; + +/** + * Revives all children having exists=false. + * + * @method Phaser.Group#reviveAll + */ +Phaser.Group.prototype.reviveAll = function () { + + this.callAllExists('revive', false); + +}; + +/** +* Calls {@link #resetChild} on each child (or each existing child). +* +* @method Phaser.Group#resetAll +* @param {number} [x] - The x coordinate to reset each child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset each child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image or texture used by the Sprite during rendering. +* @param {string|number} [frame] - The frame of a sprite sheet or texture atlas. +* @param {boolean} [checkExists=false] - Reset only existing children. +*/ +Phaser.Group.prototype.resetAll = function (x, y, key, frame, checkExists) { + + this.forEach(this.resetChild, this, checkExists, x, y, key, frame); + +}; + +/** +* Calls a function, specified by name, on all children in the group who exist (or do not exist). +* +* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. +* +* @method Phaser.Group#callAllExists +* @param {string} callback - Name of the function on the children to call. +* @param {boolean} existsValue - Only children with exists=existsValue will be called. +* @param {...any} parameter - Additional parameters that will be passed to the callback. +*/ +Phaser.Group.prototype.callAllExists = function (callback, existsValue) { + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].exists === existsValue && this.children[i][callback]) + { + this.children[i][callback].apply(this.children[i], args); + } + } + +}; + +/** +* Returns a reference to a function that exists on a child of the group based on the given callback array. +* +* @method Phaser.Group#callbackFromArray +* @param {object} child - The object to inspect. +* @param {array} callback - The array of function names. +* @param {integer} length - The size of the array (pre-calculated in callAll). +* @protected +*/ +Phaser.Group.prototype.callbackFromArray = function (child, callback, length) { + + // Kinda looks like a Christmas tree + + if (length === 1) + { + if (child[callback[0]]) + { + return child[callback[0]]; + } + } + else if (length === 2) + { + if (child[callback[0]][callback[1]]) + { + return child[callback[0]][callback[1]]; + } + } + else if (length === 3) + { + if (child[callback[0]][callback[1]][callback[2]]) + { + return child[callback[0]][callback[1]][callback[2]]; + } + } + else if (length === 4) + { + if (child[callback[0]][callback[1]][callback[2]][callback[3]]) + { + return child[callback[0]][callback[1]][callback[2]][callback[3]]; + } + } + else if (child[callback]) + { + return child[callback]; + } + + return false; + +}; + +/** +* Calls a function, specified by name, on all on children. +* +* The function is called for all children regardless if they are dead or alive (see callAllExists for different options). +* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. +* +* @method Phaser.Group#callAll +* @param {string} method - Name of the function on the child to call. Deep property lookup is supported. +* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child. +* @param {...any} args - Additional parameters that will be passed to the method. +*/ +Phaser.Group.prototype.callAll = function (method, context) { + + if (method === undefined) + { + return; + } + + // Extract the method into an array + method = method.split('.'); + + var methodLength = method.length; + + if (context === undefined || context === null || context === '') + { + context = null; + } + else + { + // Extract the context into an array + if (typeof context === 'string') + { + context = context.split('.'); + var contextLength = context.length; + } + } + + var args; + + if (arguments.length > 2) + { + args = []; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + var callback = null; + var callbackContext = null; + + for (var i = 0; i < this.children.length; i++) + { + callback = this.callbackFromArray(this.children[i], method, methodLength); + + if (context && callback) + { + callbackContext = this.callbackFromArray(this.children[i], context, contextLength); + + if (callback) + { + callback.apply(callbackContext, args); + } + } + else if (callback) + { + callback.apply(this.children[i], args); + } + } + +}; + +/** +* The core preUpdate - as called by World. +* @method Phaser.Group#preUpdate +* @protected +*/ +Phaser.Group.prototype.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + // This chunk is identical to Phaser.Component.Core.prototype.preUpdateChildren, which is not yet defined. + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + return true; + +}; + +/** +* The core update - as called by World. +* +* Children with `exists = false` are updated unless {@link #updateOnlyExistingChildren} is true. +* +* @method Phaser.Group#update +* @protected +*/ +Phaser.Group.prototype.update = function () { + + // Goes in reverse, because it's highly likely the child will destroy itself in `update` + var i = this.children.length; + + while (i--) + { + var len = this.children.length; + + if (i >= len) { i = len - 1; } + + var child = this.children[i]; + + if (!this.updateOnlyExistingChildren || child.exists) { + child.update(); + } + } + +}; + +/** +* The core postUpdate - as called by World. +* @method Phaser.Group#postUpdate +* @protected +*/ +Phaser.Group.prototype.postUpdate = function () { + + // Fixed to Camera? + if (this.fixedToCamera) + { + this.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; + this.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Find children matching a certain predicate. +* +* For example: +* +* var healthyList = Group.filter(function(child, index, children) { +* return child.health > 10 ? true : false; +* }, true); +* healthyList.callAll('attack'); +* +* Note: Currently this will skip any children which are Groups themselves. +* +* @method Phaser.Group#filter +* @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third +* @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. +* @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for +*/ +Phaser.Group.prototype.filter = function (predicate, checkExists) { + + var index = -1; + var length = this.children.length; + var results = []; + + while (++index < length) + { + var child = this.children[index]; + + if (!checkExists || (checkExists && child.exists)) + { + if (predicate(child, index, this.children)) + { + results.push(child); + } + } + } + + return new Phaser.ArraySet(results); + +}; + +/** +* Call a function on each child in this group. +* +* Additional arguments for the callback can be specified after the `checkExists` parameter. For example, +* +* Group.forEach(awardBonusGold, this, true, 100, 500) +* +* would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. +* +* Note: This check will skip any children which are Groups themselves. +* +* @method Phaser.Group#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) { + + if (checkExists === undefined) { checkExists = false; } + + if (arguments.length <= 3) + { + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + callback.call(callbackContext, this.children[i]); + } + } + } + else + { + // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE. + // Using an array and pushing each element (not a slice!) is _significantly_ faster. + var args = [null]; + + for (var i = 3; i < arguments.length; i++) + { + args.push(arguments[i]); + } + + for (var i = 0; i < this.children.length; i++) + { + if (!checkExists || (checkExists && this.children[i].exists)) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + } + } + +}; + +/** +* Call a function on each existing child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachExists +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachExists = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each alive child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachAlive +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Call a function on each dead child in this group. +* +* See {@link Phaser.Group#forEach forEach} for details. +* +* @method Phaser.Group#forEachDead +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +*/ +Phaser.Group.prototype.forEachDead = function (callback, callbackContext) { + + var args; + + if (arguments.length > 2) + { + args = [null]; + + for (var i = 2; i < arguments.length; i++) + { + args.push(arguments[i]); + } + } + + this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); + +}; + +/** +* Sort the children in the group according to a particular key and ordering. +* +* Call this function to sort the group according to a particular key value and order. +* +* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. +* +* Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including +* alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. +* +* @method Phaser.Group#sort +* @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value. +* @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}). +*/ +Phaser.Group.prototype.sort = function (key, order) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + if (key === undefined) { key = 'z'; } + if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; } + + this._sortProperty = key; + + if (order === Phaser.Group.SORT_ASCENDING) + { + this.children.sort(this.ascendingSortHandler.bind(this)); + } + else + { + this.children.sort(this.descendingSortHandler.bind(this)); + } + + this.updateZ(); + +}; + +/** +* Sort the children in the group according to custom sort function. +* +* The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). +* It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. +* +* @method Phaser.Group#customSort +* @param {function} sortHandler - The custom sort function. +* @param {object} [context=undefined] - The context in which the sortHandler is called. +*/ +Phaser.Group.prototype.customSort = function (sortHandler, context) { + + if (this.children.length < 2) + { + // Nothing to swap + return; + } + + this.children.sort(sortHandler.bind(context)); + + this.updateZ(); + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#ascendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.ascendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return -1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return 1; + } + else + { + if (a.z < b.z) + { + return -1; + } + else + { + return 1; + } + } + +}; + +/** +* An internal helper function for the sort process. +* +* @method Phaser.Group#descendingSortHandler +* @protected +* @param {object} a - The first object being sorted. +* @param {object} b - The second object being sorted. +*/ +Phaser.Group.prototype.descendingSortHandler = function (a, b) { + + if (a[this._sortProperty] < b[this._sortProperty]) + { + return 1; + } + else if (a[this._sortProperty] > b[this._sortProperty]) + { + return -1; + } + else + { + return 0; + } + +}; + +/** +* Iterates over the children of the group performing one of several actions for matched children. +* +* A child is considered a match when it has a property, named `key`, whose value is equal to `value` +* according to a strict equality comparison. +* +* The result depends on the `returnType`: +* +* - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}: +* The callback, if any, is applied to all matching children. The number of matched children is returned. +* - {@link Phaser.Group.RETURN_NONE RETURN_NONE}: +* The callback, if any, is applied to all matching children. No value is returned. +* - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}: +* The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. +* If there is no matching child then null is returned. +* +* If `args` is specified it must be an array. The matched child will be assigned to the first +* element and the entire array will be applied to the callback function. +* +* @method Phaser.Group#iterate +* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' +* @param {any} value - A child matches if `child[key] === value` is true. +* @param {integer} returnType - How to iterate the children and what to return. +* @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. +* @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null. +*/ +Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) { + + if (this.children.length === 0) + { + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return 0; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return []; + } + } + + var total = 0; + + if (returnType === Phaser.Group.RETURN_ALL) + { + var output = []; + } + + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i][key] === value) + { + total++; + + if (callback) + { + if (args) + { + args[0] = this.children[i]; + callback.apply(callbackContext, args); + } + else + { + callback.call(callbackContext, this.children[i]); + } + } + + if (returnType === Phaser.Group.RETURN_CHILD) + { + return this.children[i]; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + output.push(this.children[i]); + } + } + } + + if (returnType === Phaser.Group.RETURN_TOTAL) + { + return total; + } + else if (returnType === Phaser.Group.RETURN_ALL) + { + return output; + } + else + { + // RETURN_CHILD or RETURN_NONE + return null; + } + +}; + +/** +* Get the first display object with the given property name and value. +* +* @method Phaser.Group#getFirst +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {DisplayObject} The first child matching the query, or `null` if none were found. +*/ +Phaser.Group.prototype.getFirst = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_CHILD); + +}; + +/** +* Get the first display object that exists, or doesn't exist. +* +* You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstExists +* @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child. +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + if (typeof exists !== 'boolean') + { + exists = true; + } + + var child = this.getFirst('exists', exists); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is alive (`child.alive === true`). +* +* This is handy for choosing a squad leader, etc. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstAlive +* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', true); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Get the first child that is dead (`child.alive === false`). +* +* This is handy for checking if everything has been wiped out and adding to the pool as needed. +* +* You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. +* +* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. +* +* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child +* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. +* +* @method Phaser.Group#getFirstDead +* @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false. +*/ +Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) { + + if (createIfNull === undefined) { createIfNull = false; } + + var child = this.getFirst('alive', false); + + return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); + +}; + +/** +* Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. +* +* If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. +* +* The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. +* +* @method Phaser.Group#resetChild +* @param {DisplayObject} child - The child to reset and/or load the texture on. +* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. +* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}. +*/ +Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) { + + if (child === null) + { + return null; + } + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (x !== null && y !== null) + { + child.reset(x, y); + } + + if (key !== undefined) + { + child.loadTexture(key, frame); + } + + return child; + +}; + +/** +* Return the child at the top of this group. +* +* The top child is the child displayed (rendered) above every other child. +* +* @method Phaser.Group#getTop +* @return {any} The child at the top of the Group. +*/ +Phaser.Group.prototype.getTop = function () { + + if (this.children.length > 0) + { + return this.children[this.children.length - 1]; + } + +}; + +/** +* Returns the child at the bottom of this group. +* +* The bottom child the child being displayed (rendered) below every other child. +* +* @method Phaser.Group#getBottom +* @return {any} The child at the bottom of the Group. +*/ +Phaser.Group.prototype.getBottom = function () { + + if (this.children.length > 0) + { + return this.children[0]; + } + +}; + +/** +* Get the closest child to given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getClosestTo +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child closest to given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContext) { + + var distance = Number.MAX_VALUE; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance < distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the child furthest away from the given Object, with optional callback to filter children. +* +* This can be a Sprite, Group, Image or any object with public x and y properties. +* +* 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. +* +* You can use the optional `callback` argument to apply your own filter to the distance checks. +* If the child is closer then the previous child, it will be sent to `callback` as the first argument, +* with the distance as the second. The callback should return `true` if it passes your +* filtering criteria, otherwise it should return `false`. +* +* @method Phaser.Group#getFurthestFrom +* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. +* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. +* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). +* @return {any} The child furthest from the given object, or `null` if no child was found. +*/ +Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackContext) { + + var distance = 0; + var tempDistance = 0; + var result = null; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (child.exists) + { + tempDistance = Math.abs(Phaser.Point.distance(object, child)); + + if (tempDistance > distance && (!callback || callback.call(callbackContext, child, tempDistance))) + { + distance = tempDistance; + result = child; + } + } + } + + return result; + +}; + +/** +* Get the number of children with the given property name and value. +* +* @method Phaser.Group#count +* @param {string} key - The child property to check. +* @param {string} value - A child matches if `child[key] === value` is true. +* @return {integer} The number of children matching the query. +*/ +Phaser.Group.prototype.count = function (key, value) { + + return this.iterate(key, value, Phaser.Group.RETURN_TOTAL); + +}; + +/** +* Get the number of living children in this group. +* +* @method Phaser.Group#countLiving +* @return {integer} The number of children flagged as alive. +*/ +Phaser.Group.prototype.countLiving = function () { + + return this.count('alive', true); + +}; + +/** +* Get the number of dead children in this group. +* +* @method Phaser.Group#countDead +* @return {integer} The number of children flagged as dead. +*/ +Phaser.Group.prototype.countDead = function () { + + return this.count('alive', false); + +}; + +/** +* Returns a random child from the group. +* +* @method Phaser.Group#getRandom +* @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). +* @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. +* @return {any} A random child of this Group. +*/ +Phaser.Group.prototype.getRandom = function (startIndex, length) { + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = this.children.length; } + + if (length === 0) + { + return null; + } + + return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length); + +}; + +/** +* Returns a random child from the Group that has `exists` set to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only +* the first 50 children in the Group. +* +* @method Phaser.Group#getRandomExists +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up to. +* @return {any} A random child of this Group that exists. +*/ +Phaser.Group.prototype.getRandomExists = function (startIndex, endIndex) { + + var list = this.getAll('exists', true, startIndex, endIndex); + + return this.game.rnd.pick(list); + +}; + +/** +* Returns all children in this Group. +* +* You can optionally specify a matching criteria using the `property` and `value` arguments. +* +* For example: `getAll('exists', true)` would return only children that have an `exists` property equal to `true`. +* +* Optionally you can specify a start and end index. For example if this Group had 100 children, +* and you set `startIndex` to 0 and `endIndex` to 50, it would return the first 50 children in the Group. +* If `property` and `value` are also specified, only children within the given index range are searched. +* +* @method Phaser.Group#getAll +* @param {string} [property] - An optional property to test against the value argument. +* @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results. +* @param {integer} [startIndex=0] - The first child index to start the search from. +* @param {integer} [endIndex] - The last child index to search up until. +* @return {array} - An array containing all, some, or none of the Children of this Group. +*/ +Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) { + + if (startIndex === undefined) { startIndex = 0; } + if (endIndex === undefined) { endIndex = this.children.length; } + + var output = []; + + for (var i = startIndex; i < endIndex; i++) + { + var child = this.children[i]; + + if (property) + { + if (child[property] === value) + { + output.push(child); + } + } + else + { + output.push(child); + } + } + + return output; + +}; + +/** +* Removes the given child from this group. +* +* This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. +* +* If the group cursor was referring to the removed child it is updated to refer to the next child. +* +* @method Phaser.Group#remove +* @param {any} child - The child to remove. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child. +* @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event. +* @return {boolean} true if the child was removed from this group, otherwise false. +*/ +Phaser.Group.prototype.remove = function (child, destroy, silent) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + + if (this.children.length === 0 || this.children.indexOf(child) === -1) + { + return false; + } + + if (!silent && child.events && !child.destroyPhase) + { + child.events.onRemovedFromGroup$dispatch(child, this); + } + + var removed = this.removeChild(child); + + this.removeFromHash(child); + + this.updateZ(); + + if (this.cursor === child) + { + this.next(); + } + + if (destroy && removed) + { + removed.destroy(true); + } + + return true; + +}; + +/** +* Moves all children from this Group to the Group given. +* +* @method Phaser.Group#moveAll +* @param {Phaser.Group} group - The new Group to which the children will be moved to. +* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group. +* @return {Phaser.Group} The Group to which all the children were moved. +*/ +Phaser.Group.prototype.moveAll = function (group, silent) { + + if (silent === undefined) { silent = false; } + + if (this.children.length > 0 && group instanceof Phaser.Group) + { + do + { + group.add(this.children[0], silent); + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + } + + return group; + +}; + +/** +* Removes all children from this Group, but does not remove the group from its parent. +* +* The children can be optionally destroyed as they are removed. +* +* You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've +* more than one Game Object sharing the same BaseTexture. +* +* @method Phaser.Group#removeAll +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +* @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. +*/ +Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) { + + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = false; } + if (destroyTexture === undefined) { destroyTexture = false; } + + if (this.children.length === 0) + { + return; + } + + do + { + if (!silent && this.children[0].events) + { + this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this); + } + + var removed = this.removeChild(this.children[0]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true, destroyTexture); + } + } + while (this.children.length > 0); + + this.hash = []; + + this.cursor = null; + +}; + +/** +* Removes all children from this group whose index falls beteen the given startIndex and endIndex values. +* +* @method Phaser.Group#removeBetween +* @param {integer} startIndex - The index to start removing children from. +* @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. +* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. +*/ +Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) { + + if (endIndex === undefined) { endIndex = this.children.length - 1; } + if (destroy === undefined) { destroy = false; } + if (silent === undefined) { silent = 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 (!silent && this.children[i].events) + { + this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this); + } + + var removed = this.removeChild(this.children[i]); + + this.removeFromHash(removed); + + if (destroy && removed) + { + removed.destroy(true); + } + + if (this.cursor === this.children[i]) + { + this.cursor = null; + } + + i--; + } + + this.updateZ(); + +}; + +/** + * Places each child at a random position within the given Rectangle (or the {@link Phaser.World#bounds World bounds}). + * + * @method Phaser.Group#scatter + * @param {Phaser.Rectangle} [rect=this.game.world.bounds] - A Rectangle. If omitted {@link Phaser.World#bounds} is used. + * @param {boolean} [checkExists=false] - Place only children with exists=true. + */ +Phaser.Group.prototype.scatter = function (rect, checkExists) { + + if (rect == null) { rect = this.game.world.bounds; } + + this.forEach(function (child) { + + child.position.set(rect.randomX, rect.randomY); + + }, null, checkExists); + +}; + +/** + * Orders this Group's children randomly. + * + * This can be more efficient than calling {@link #getRandom} repeatedly. + * + * @method Phaser.Group#shuffle + */ +Phaser.Group.prototype.shuffle = function () { + + Phaser.ArrayUtils.shuffle(this.children); + this.updateZ(); + +}; + +/** +* Destroys this group. +* +* Removes all children, then removes this group from its parent and nulls references. +* +* @method Phaser.Group#destroy +* @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child. +* @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. +*/ +Phaser.Group.prototype.destroy = function (destroyChildren, soft) { + + if (this.game === null || this.ignoreDestroy) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (soft === undefined) { soft = false; } + + this.onDestroy.dispatch(this, destroyChildren, soft); + + this.removeAll(destroyChildren); + + this.cursor = null; + this.filters = null; + this.pendingDestroy = false; + + if (!soft) + { + if (this.parent) + { + this.parent.removeChild(this); + } + + this.game = null; + this.exists = false; + } + +}; + +/** +* Total number of existing children in the group. +* +* @name Phaser.Group#total +* @property {integer} total +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "total", { + + get: function () { + + return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); + + } + +}); + +/** +* Total number of children in this group, regardless of exists/alive status. +* +* @name Phaser.Group#length +* @property {integer} length +* @readonly +*/ +Object.defineProperty(Phaser.Group.prototype, "length", { + + get: function () { + + return this.children.length; + + } + +}); + +/** +* The angle of rotation of the group container, in degrees. +* +* This adjusts the group itself by modifying its local rotation transform. +* +* This has no impact on the rotation/angle properties of the children, but it will update their worldTransform +* and on-screen orientation and position. +* +* @name Phaser.Group#angle +* @property {number} angle +*/ +Object.defineProperty(Phaser.Group.prototype, "angle", { + + get: function() { + return Phaser.Math.radToDeg(this.rotation); + }, + + set: function(value) { + this.rotation = Phaser.Math.degToRad(value); + } + +}); + +/** +* The center x coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerX +* @property {number} centerX +*/ +Object.defineProperty(Phaser.Group.prototype, "centerX", { + + get: function () { + + return this.getBounds(this.parent).centerX; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.halfWidth; + + } + +}); + +/** +* The center y coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#centerY +* @property {number} centerY +*/ +Object.defineProperty(Phaser.Group.prototype, "centerY", { + + get: function () { + + return this.getBounds(this.parent).centerY; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.halfHeight; + + } + +}); + +/** +* The left coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#left +* @property {number} left +*/ +Object.defineProperty(Phaser.Group.prototype, "left", { + + get: function () { + + return this.getBounds(this.parent).left; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = value + offset; + + } + +}); + +/** +* The right coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#right +* @property {number} right +*/ +Object.defineProperty(Phaser.Group.prototype, "right", { + + get: function () { + + return this.getBounds(this.parent).right; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.x - r.x; + + this.x = (value + offset) - r.width; + + } + +}); + +/** +* The top coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#top +* @property {number} top +*/ +Object.defineProperty(Phaser.Group.prototype, "top", { + + get: function () { + + return this.getBounds(this.parent).top; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset); + + } + +}); + +/** +* The bottom coordinate of this Group. +* +* It is derived by calling `getBounds`, calculating the Groups dimensions based on its +* visible children. +* +* @name Phaser.Group#bottom +* @property {number} bottom +*/ +Object.defineProperty(Phaser.Group.prototype, "bottom", { + + get: function () { + + return this.getBounds(this.parent).bottom; + + }, + + set: function (value) { + + var r = this.getBounds(this.parent); + var offset = this.y - r.y; + + this.y = (value + offset) - r.height; + + } + +}); + +/** +* Aligns this Group within another Game Object, or Rectangle, known as the +* 'container', to one of 9 possible positions. +* +* The container must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the container. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, +* `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, +* `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* container, taking into consideration rotation and scale of its children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignIn +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* Aligns this Group to the side of another Game Object, or Rectangle, known as the +* 'parent', in one of 11 possible positions. +* +* The parent must be a Game Object, or Phaser.Rectangle object. This can include properties +* such as `World.bounds` or `Camera.view`, for aligning Groups within the world +* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, +* TileSprites or Buttons. +* +* Please note that aligning a Group to another Game Object does **not** make it a child of +* the parent. It simply modifies its position coordinates so it aligns with it. +* +* The position constants you can use are: +* +* `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, +* `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, +* `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` +* and `Phaser.BOTTOM_RIGHT`. +* +* Groups are placed in such a way that their _bounds_ align with the +* parent, taking into consideration rotation and scale of the children. +* This allows you to neatly align Groups, irrespective of their position value. +* +* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final +* aligned position of the Group. For example: +* +* `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` +* +* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. +* Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. +* So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive +* one expands it. +* +* @method Phaser.Group#alignTo +* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. +* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. +* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. +* @return {Phaser.Group} This Group. +*/ + +// This function is set at the bottom of src/gameobjects/components/Bounds.js + +/** +* A display object is any object that can be rendered in the Phaser/pixi.js scene graph: +* +* - {@link PIXI.DisplayObject} +* - {@link PIXI.DisplayObjectContainer} +* - {@link Phaser.BitmapText} +* - {@link Phaser.Creature} +* - {@link Phaser.Graphics} +* - {@link Phaser.Group} +* - {@link Phaser.FlexLayer} +* - {@link Phaser.Particles.Arcade.Emitter} +* - {@link Phaser.Physics.P2.BodyDebug} +* - {@link Phaser.SpriteBatch} +* - {@link Phaser.World} +* - {@link Phaser.Rope} +* - {@link Phaser.Stage} +* - {@link PIXI.Sprite} +* - {@link Phaser.Image} +* - {@link Phaser.Button} +* - {@link Phaser.Sprite} +* - {@link Phaser.Bullet} +* - {@link Phaser.Particle} +* - {@link Phaser.Text} +* - {@link Phaser.TilemapLayer} +* - {@link Phaser.TileSprite} +* +* @typedef {object} DisplayObject +*/ +// Documentation stub for linking. + +/** +* The x coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#x +* @property {number} x +*/ + +/** +* The y coordinate of the group container. +* +* You can adjust the group container itself by modifying its coordinates. +* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#y +* @property {number} y +*/ + +/** +* The angle of rotation of the group container, in radians. +* +* This will adjust the group container itself by modifying its rotation. +* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. +* @name Phaser.Group#rotation +* @property {number} rotation +*/ + +/** +* The visible state of the group. Non-visible Groups and all of their children are not rendered. +* +* @name Phaser.Group#visible +* @property {boolean} visible +*/ + +/** +* The alpha value of the group container. +* +* @name Phaser.Group#alpha +* @property {number} alpha +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* "This world is but a canvas to our imagination." - Henry David Thoreau +* +* A game has only one world. The world is an abstract place in which all game objects live. It is not bound +* by stage limits and can be any size. You look into the world via cameras. All game objects live within +* the world at world-based coordinates. By default a world is created the same size as your Stage. +* +* @class Phaser.World +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.World = function (game) { + + Phaser.Group.call(this, game, null, '__world', false); + + /** + * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. + * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. + * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. + * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. + * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height); + + /** + * @property {Phaser.Camera} camera - Camera instance. + */ + this.camera = null; + + /** + * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. + * @readonly + */ + this._definedSize = false; + + /** + * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._width = game.width; + + /** + * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ + this._height = game.height; + + this.game.state.onStateChange.add(this.stateChange, this); + +}; + +Phaser.World.prototype = Object.create(Phaser.Group.prototype); +Phaser.World.prototype.constructor = Phaser.World; + +/** +* Initialises the game world. +* +* @method Phaser.World#boot +* @protected +*/ +Phaser.World.prototype.boot = function () { + + this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height); + + this.game.stage.addChild(this); + + this.camera.boot(); + +}; + +/** +* Called whenever the State changes or resets. +* +* It resets the world.x and world.y coordinates back to zero, +* then resets the Camera. +* +* @method Phaser.World#stateChange +* @protected +*/ +Phaser.World.prototype.stateChange = function () { + + this.x = 0; + this.y = 0; + + this.camera.reset(); + +}; + +/** +* Updates the size of this world and sets World.x/y to the given values +* The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. +* +* @method Phaser.World#setBounds +* @param {number} x - Top left most corner of the world. +* @param {number} y - Top left most corner of the world. +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.setBounds = function (x, y, width, height) { + + this._definedSize = true; + this._width = width; + this._height = height; + + this.bounds.setTo(x, y, width, height); + + this.x = x; + this.y = y; + + if (this.camera.bounds) + { + // The Camera can never be smaller than the game size + this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height)); + } + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Updates this world's width and height (but not smaller than any previous {@link #setBounds defined size}). +* +* Phaser uses this to adapt to {@link Phaser.ScaleManager#updateDimensions layout changes}. +* You probably want to use {@link #setBounds} instead. +* +* @method Phaser.World#resize +* @param {number} width - New width of the game world in pixels. +* @param {number} height - New height of the game world in pixels. +*/ +Phaser.World.prototype.resize = function (width, height) { + + // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size + + if (this._definedSize) + { + if (width < this._width) + { + width = this._width; + } + + if (height < this._height) + { + height = this._height; + } + } + + this.bounds.width = width; + this.bounds.height = height; + + this.game.camera.setBoundsToWorld(); + + this.game.physics.setBoundsToWorld(); + +}; + +/** +* Destroyer of worlds. +* +* @method Phaser.World#shutdown +*/ +Phaser.World.prototype.shutdown = function () { + + // World is a Group, so run a soft destruction on this and all children. + this.destroy(true, true); + +}; + +/** +* This will take the given game object and check if its x/y coordinates fall outside of the world bounds. +* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. +* If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. +* +* Please understand there are limitations to this method. For example if you have scaled the World +* then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. +* +* @method Phaser.World#wrap +* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) { + + if (padding === undefined) { padding = 0; } + if (useBounds === undefined) { useBounds = false; } + if (horizontal === undefined) { horizontal = true; } + if (vertical === undefined) { vertical = true; } + + if (!useBounds) + { + if (horizontal && sprite.x + padding < this.bounds.x) + { + sprite.x = this.bounds.right + padding; + } + else if (horizontal && sprite.x - padding > this.bounds.right) + { + sprite.x = this.bounds.left - padding; + } + + if (vertical && sprite.y + padding < this.bounds.top) + { + sprite.y = this.bounds.bottom + padding; + } + else if (vertical && sprite.y - padding > this.bounds.bottom) + { + sprite.y = this.bounds.top - padding; + } + } + else + { + sprite.getBounds(); + + if (horizontal) + { + if ((sprite.x + sprite._currentBounds.width) < this.bounds.x) + { + sprite.x = this.bounds.right; + } + else if (sprite.x > this.bounds.right) + { + sprite.x = this.bounds.left; + } + } + + if (vertical) + { + if ((sprite.y + sprite._currentBounds.height) < this.bounds.top) + { + sprite.y = this.bounds.bottom; + } + else if (sprite.y > this.bounds.bottom) + { + sprite.y = this.bounds.top; + } + } + } + +}; + +/** +* @method Phaser.World#wrapAll +* @param {Phaser.Group} group - A group of sprites. +* @param {boolean} [checkExists=false] - Wrap only sprites having `exists=true`. +* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. +* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. +* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. +* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. +*/ +Phaser.World.prototype.wrapAll = function (group, checkExists, padding, useBounds, horizontal, vertical) { + + group.forEach(this.wrap, this, checkExists, padding, useBounds, horizontal, vertical); + +}; + +/** +* @name Phaser.World#width +* @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "width", { + + get: function () { + return this.bounds.width; + }, + + set: function (value) { + + if (value < this.game.width) + { + value = this.game.width; + } + + this.bounds.width = value; + this._width = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#height +* @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. +*/ +Object.defineProperty(Phaser.World.prototype, "height", { + + get: function () { + return this.bounds.height; + }, + + set: function (value) { + + if (value < this.game.height) + { + value = this.game.height; + } + + this.bounds.height = value; + this._height = value; + this._definedSize = true; + + } + +}); + +/** +* @name Phaser.World#centerX +* @property {number} centerX - Gets the X position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerX", { + + get: function () { + return this.bounds.halfWidth + this.bounds.x; + } + +}); + +/** +* @name Phaser.World#centerY +* @property {number} centerY - Gets the Y position corresponding to the center point of the world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "centerY", { + + get: function () { + return this.bounds.halfHeight + this.bounds.y; + } + +}); + +/** +* @name Phaser.World#randomX +* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomX", { + + get: function () { + + if (this.bounds.x < 0) + { + return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x))); + } + else + { + return this.game.rnd.between(this.bounds.x, this.bounds.width); + } + + } + +}); + +/** +* @name Phaser.World#randomY +* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. +* @readonly +*/ +Object.defineProperty(Phaser.World.prototype, "randomY", { + + get: function () { + + if (this.bounds.y < 0) + { + return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y))); + } + else + { + return this.game.rnd.between(this.bounds.y, this.bounds.height); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Game object is the main controller for the entire Phaser game. It is responsible +* for handling the boot process, parsing the configuration values, creating the renderer, +* and setting-up all of the Phaser systems, such as physics, sound and input. +* Once that is complete it will start the default State, and then begin the main game loop. +* +* You can access lots of the Phaser systems via the properties on the `game` object. For +* example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on. +* +* Anywhere you can access the `game` property, you can access all of these core systems. +* For example a Sprite has a `game` property, allowing you to talk to the various parts +* of Phaser directly, without having to look after your own references. +* +* In it's most simplest form, a Phaser game can be created by providing the arguments +* to the constructor: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create }); +* ``` +* +* In the example above it is passing in a State object directly. You can also use the State +* Manager to do this: +* +* ```javascript +* var game = new Phaser.Game(800, 600, Phaser.AUTO); +* game.state.add('Boot', BasicGame.Boot); +* game.state.add('Preloader', BasicGame.Preloader); +* game.state.add('MainMenu', BasicGame.MainMenu); +* game.state.add('Game', BasicGame.Game); +* game.state.start('Boot'); +* ``` +* +* In the example above, 4 States are added to the State Manager, and Phaser is told to +* start running the `Boot` state when it has finished initializing. There are example +* project templates you can use in the Phaser GitHub repo, inside the `resources` folder. +* +* Instead of specifying arguments you can also pass {@link GameConfig a single object} instead: +* +* ```javascript +* var config = { +* width: 800, +* height: 600, +* renderer: Phaser.AUTO, +* antialias: true, +* multiTexture: true, +* state: { +* preload: preload, +* create: create, +* update: update +* } +* } +* +* var game = new Phaser.Game(config); +* ``` +* +* @class Phaser.Game +* @constructor +* @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. +* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. +* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). +* @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body. +* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. +* @param {boolean} [transparent=false] - Use a transparent canvas background or not. +* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) { + + /** + * @property {number} id - Phaser Game ID + * @readonly + */ + this.id = Phaser.GAMES.push(this) - 1; + + /** + * @property {object} config - The Phaser.Game configuration object. + */ + this.config = null; + + /** + * @property {object} physicsConfig - The Phaser.Physics.World configuration object. + */ + this.physicsConfig = physicsConfig; + + /** + * @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted. + * @readonly + * @default + */ + this.parent = ''; + + /** + * The current Game Width in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} width + * @readonly + * @default + */ + this.width = 800; + + /** + * The current Game Height in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} height + * @readonly + * @default + */ + this.height = 600; + + /** + * The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object. + * + * @property {integer} resolution + * @readonly + * @default + */ + this.resolution = 1; + + /** + * @property {integer} _width - Private internal var. + * @private + */ + this._width = 800; + + /** + * @property {integer} _height - Private internal var. + * @private + */ + this._height = 600; + + /** + * @property {boolean} transparent - Use a transparent canvas background or not. + * @default + */ + this.transparent = false; + + /** + * @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead. + * @readonly + * @default + */ + this.antialias = true; + + /** + * Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property. + * To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game + * Configuration object with the property `multiTexture` set to true. It has to be enabled before + * Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it + * via the `game.renderer.setTexturePriority` method. + * + * @property {boolean} multiTexture + * @readonly + * @default + */ + this.multiTexture = false; + + /** + * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * @default + */ + this.preserveDrawingBuffer = false; + + /** + * Clear the Canvas each frame before rendering the display list. + * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. + * This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage. + * @property {boolean} clearBeforeRender + * @default + */ + this.clearBeforeRender = true; + + /** + * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. + * @protected + */ + this.renderer = null; + + /** + * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `render` hooks but not `preRender` or `postRender`; set {@link lockRender} to skip those as well. + * @readonly + */ + this.renderType = Phaser.AUTO; + + /** + * @property {Phaser.StateManager} state - The StateManager. + */ + this.state = null; + + /** + * @property {boolean} isBooted - Whether the game engine is booted, aka available. + * @readonly + */ + this.isBooted = false; + + /** + * @property {boolean} isRunning - Is game running or paused? + * @readonly + */ + this.isRunning = false; + + /** + * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout + * @protected + */ + this.raf = null; + + /** + * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. + */ + this.add = null; + + /** + * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. + */ + this.make = null; + + /** + * @property {Phaser.Cache} cache - Reference to the assets cache. + */ + this.cache = null; + + /** + * @property {Phaser.Input} input - Reference to the input manager + */ + this.input = null; + + /** + * @property {Phaser.Loader} load - Reference to the assets loader. + */ + this.load = null; + + /** + * @property {Phaser.Math} math - Reference to the math helper. + */ + this.math = null; + + /** + * @property {Phaser.Net} net - Reference to the network class. + */ + this.net = null; + + /** + * @property {Phaser.ScaleManager} scale - The game scale manager. + */ + this.scale = null; + + /** + * @property {Phaser.SoundManager} sound - Reference to the sound manager. + */ + this.sound = null; + + /** + * @property {Phaser.Stage} stage - Reference to the stage. + */ + this.stage = null; + + /** + * @property {Phaser.Time} time - Reference to the core game clock. + */ + this.time = null; + + /** + * @property {Phaser.TweenManager} tweens - Reference to the tween manager. + */ + this.tweens = null; + + /** + * @property {Phaser.World} world - Reference to the world. + */ + this.world = null; + + /** + * @property {Phaser.Physics} physics - Reference to the physics manager. + */ + this.physics = null; + + /** + * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. + */ + this.plugins = null; + + /** + * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. + */ + this.rnd = null; + + /** + * @property {Phaser.Device} device - Contains device information and capabilities. + */ + this.device = Phaser.Device; + + /** + * @property {Phaser.Camera} camera - A handy reference to world.camera. + */ + this.camera = null; + + /** + * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) + */ + this.context = null; + + /** + * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. + */ + this.debug = null; + + /** + * @property {Phaser.Particles} particles - The Particle Manager. + */ + this.particles = null; + + /** + * @property {Phaser.Create} create - The Asset Generator. + */ + this.create = null; + + /** + * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. + * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. + * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. + * @property {boolean} lockRender + * @default + */ + this.lockRender = false; + + /** + * @property {boolean} pendingDestroy - Destroy the game at the next update. + * @default + */ + this.pendingDestroy = false; + + /** + * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). + * @default + * @readonly + */ + this.stepping = false; + + /** + * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. + * @default + * @readonly + */ + this.pendingStep = false; + + /** + * @property {number} stepCount - When stepping is enabled this contains the current step cycle. + * @default + * @readonly + */ + this.stepCount = 0; + + /** + * @property {Phaser.Signal} onPause - This event is fired when the game pauses. + */ + this.onPause = null; + + /** + * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. + */ + this.onResume = null; + + /** + * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). + */ + this.onBlur = null; + + /** + * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). + */ + this.onFocus = null; + + /** + * @property {boolean} _paused - Is game paused? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _codePaused - Was the game paused via code or a visibility change? + * @private + */ + this._codePaused = false; + + /** + * The ID of the current/last logic update applied this animation frame, starting from 0. + * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` + * @property {integer} currentUpdateID + * @protected + */ + this.currentUpdateID = 0; + + /** + * Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed). + * @property {integer} updatesThisFrame + * @protected + */ + this.updatesThisFrame = 1; + + /** + * Number of renders expected to occur this animation frame. May be 0 if {@link #dropFrames is on} or {@link #forceSingleRender} is off; otherwise it will be 1. + * @property {integer} updatesThisFrame + * @protected + */ + this.rendersThisFrame = 1; + + /** + * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. + * @private + */ + this._deltaTime = 0; + + /** + * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. + * @private + */ + this._lastCount = 0; + + /** + * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. + * @private + */ + this._spiraling = 0; + + /** + * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) + * @private + */ + this._kickstart = true; + + /** + * If the game is struggling to maintain the desired FPS, this signal will be dispatched. + * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. + * @property {Phaser.Signal} fpsProblemNotifier + * @public + */ + this.fpsProblemNotifier = new Phaser.Signal(); + + /** + * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? You can toggle it on the fly. + */ + this.forceSingleUpdate = true; + + /** + * @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update? (During spiraling conditions, {@link #dropFrames} is used instead.) + */ + this.forceSingleRender = true; + + /** + * @property {boolean} dropFrames - When {@link #forceSingleUpdate} is off, skip {@link #updateRender rendering} if logic updates are spiraling upwards. + */ + this.dropFrames = false; + + /** + * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. + * @private + */ + this._nextFpsNotification = 0; + + // Parse the configuration object (if any) + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + this.parseConfig(arguments[0]); + } + else + { + this.config = { enableDebug: true }; + + if (typeof width !== 'undefined') + { + this._width = width; + } + + if (typeof height !== 'undefined') + { + this._height = height; + } + + if (typeof renderer !== 'undefined') + { + 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); + } + + this.device.whenReady(this.boot, this); + + return this; + +}; + +/** +* A configuration object for {@link Phaser.Game}. +* +* @typedef {object} GameConfig +* @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}. +* @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}. +* @property {number|string} [GameConfig.antialias=true] +* @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}. +* @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in. +* @property {string} [GameConfig.canvasId] - `id` attribute value to assign to the game canvas. +* @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas. +* @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}. +* @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange} +* @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing. +* @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production. +* @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO. +* @property {boolean} [GameConfig.forceSetTimeout] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeOut} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available. +* @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen. +* @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked. +* @property {number|string} [GameConfig.height=600] +* @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`. +* @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected. +* @property {object} [GameConfig.physicsConfig] +* @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering. +* @property {number} [GameConfig.renderer=Phaser.AUTO] +* @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels. +* @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices. +* @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen. +* @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode. +* @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}. +* @property {object} [GameConfig.state] +* @property {boolean} [GameConfig.transparent=false] +* @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode. +* @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode. +* @property {number|string} [GameConfig.width=800] +*/ +// Documentation stub for linking. + +Phaser.Game.prototype = { + + /** + * Parses a Game configuration object. + * + * @method Phaser.Game#parseConfig + * @protected + */ + parseConfig: function (config) { + + this.config = config; + + if (config['enableDebug'] === undefined) + { + this.config.enableDebug = true; + } + + if (config['width']) + { + this._width = config['width']; + } + + if (config['height']) + { + this._height = config['height']; + } + + if (config['renderer']) + { + this.renderType = config['renderer']; + } + + if (config['parent']) + { + this.parent = config['parent']; + } + + if (config['transparent'] !== undefined) + { + this.transparent = config['transparent']; + } + + if (config['antialias'] !== undefined) + { + this.antialias = config['antialias']; + } + + if (config['multiTexture'] !== undefined) + { + this.multiTexture = config['multiTexture']; + } + + if (config['resolution']) + { + this.resolution = config['resolution']; + } + + if (config['preserveDrawingBuffer'] !== undefined) + { + this.preserveDrawingBuffer = config['preserveDrawingBuffer']; + } + + 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); + + }, + + /** + * Initialize engine sub modules and start the game. + * + * @method Phaser.Game#boot + * @protected + */ + boot: function () { + + if (this.isBooted) + { + return; + } + + this.onPause = new Phaser.Signal(); + this.onResume = new Phaser.Signal(); + this.onBlur = new Phaser.Signal(); + this.onFocus = new Phaser.Signal(); + + this.isBooted = true; + + PIXI.game = this; + + this.math = Phaser.Math; + + this.scale = new Phaser.ScaleManager(this, this._width, this._height); + this.stage = new Phaser.Stage(this); + + this.setUpRenderer(); + + 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.create = new Phaser.Create(this); + this.plugins = new Phaser.PluginManager(this); + this.net = new Phaser.Net(this); + + this.time.boot(); + this.stage.boot(); + this.world.boot(); + this.scale.boot(); + this.input.boot(); + this.sound.boot(); + this.state.boot(); + + if (this.config['enableDebug']) + { + this.debug = new Phaser.Utils.Debug(this); + this.debug.boot(); + } + else + { + this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {}, isDisabled: true }; + } + + 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._kickstart = true; + + if (window['focus']) + { + if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus)) + { + window.focus(); + } + } + + if (this.config['disableStart']) + { + return; + } + + if (this.cache.isReady) + { + this.raf.start(); + } + else + { + this.cache.onReady.addOnce(function () { + this.raf.start(); + }, this); + } + + }, + + /** + * Displays a Phaser version debug header in the console. + * + * @method Phaser.Game#showDebugHeader + * @protected + */ + showDebugHeader: function () { + + if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner) + { + return; + } + + 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.ie) // https://developer.mozilla.org/en-US/docs/Web/API/Console/log#Browser_compatibility + { + var args = [ + '%c %c %c Phaser CE v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665', + 'background: #fb8cb3', + 'background: #d44a52', + 'color: #ffffff; background: #871905;', + 'background: #d44a52', + 'background: #fb8cb3', + 'background: #ffffff' + ]; + + for (var i = 0; i < 3; i++) + { + if (i < c) + { + args.push('color: #ff2424; background: #fff'); + } + else + { + args.push('color: #959595; background: #fff'); + } + } + + console.log.apply(console, args); + } + else if (window['console']) + { + console.log('Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' | http://phaser.io'); + } + + }, + + /** + * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. + * + * @method Phaser.Game#setUpRenderer + * @protected + */ + setUpRenderer: function () { + + if (!this.device.canvas) + { + // Nothing else to do + throw new Error('Phaser.Game - Cannot create Canvas 2d context, aborting.'); + } + + if (this.config['canvas']) + { + this.canvas = this.config['canvas']; + } + else + { + this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true); + } + + if (this.config['canvasStyle']) + { + this.canvas.style = this.config['canvasStyle']; + } + else + { + this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; + } + + if (this.config['crisp']) + { + Phaser.Canvas.setImageRenderingCrisp(this.canvas); + } + + if ((this.renderType === Phaser.WEBGL) || + (this.renderType === Phaser.WEBGL_MULTI) || + (this.renderType === Phaser.AUTO && this.device.webGL)) + { + if (this.multiTexture || this.renderType === Phaser.WEBGL_MULTI) + { + PIXI.enableMultiTexture(); + this.multiTexture = true; + } + + try + { + this.renderer = new PIXI.WebGLRenderer(this, this.config); + this.renderType = Phaser.WEBGL; + this.context = null; + this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); + this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); + } + catch (webGLRendererError) + { + this.renderer = null; + this.multiTexture = false; + PIXI._enableMultiTextureToggle = false; + + if (this.renderType === Phaser.WEBGL) + { + // No fallback + throw webGLRendererError; + } + } + } + + if (!this.renderer) + { + this.renderer = new PIXI.CanvasRenderer(this, this.config); + this.context = this.renderer.context; + + if (this.renderType === Phaser.AUTO) + { + this.renderType = Phaser.CANVAS; + } + } + + if (this.device.cocoonJS) + { + this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false; + } + + if (this.renderType !== Phaser.HEADLESS) + { + this.stage.smoothed = this.antialias; + + Phaser.Canvas.addToDOM(this.canvas, this.parent, false); + Phaser.Canvas.setTouchAction(this.canvas); + } + + }, + + /** + * Handles WebGL context loss. + * + * @method Phaser.Game#contextLost + * @private + * @param {Event} event - The webglcontextlost event. + */ + contextLost: function (event) { + + event.preventDefault(); + + this.renderer.contextLost = true; + + }, + + /** + * Handles WebGL context restoration. + * + * @method Phaser.Game#contextRestored + * @private + */ + contextRestored: function () { + + this.renderer.initContext(); + + this.cache.clearGLTextures(); + + this.renderer.contextLost = false; + + }, + + /** + * The core game loop. + * + * @method Phaser.Game#update + * @protected + * @param {number} time - The current time as provided by RequestAnimationFrame. + */ + update: function (time) { + + if (this.pendingDestroy) + { + this.destroy(); + return; + } + + this.time.update(time); + + if (this._kickstart) + { + this.updateLogic(this.time.desiredFpsMult); + + // call the game render update exactly once every frame + this.updateRender(this.time.slowMotion * this.time.desiredFps); + + this._kickstart = false; + + return; + } + + // if the logic time is spiraling upwards, skip a frame entirely + if (this._spiraling > 1 && !this.forceSingleUpdate) + { + // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate + if (this.time.time > this._nextFpsNotification) + { + // only permit one fps notification per 10 seconds + this._nextFpsNotification = this.time.time + 10000; + + // dispatch the notification signal + this.fpsProblemNotifier.dispatch(); + } + + // reset the _deltaTime accumulator which will cause all pending late updates to be permanently skipped + this._deltaTime = 0; + this._spiraling = 0; + + if (this.dropFrames) + { + this.rendersThisFrame = 0; + } + else + { + this.updateRender(this.time.slowMotion * this.time.desiredFps); + this.rendersThisFrame = 1; + } + } + else + { + // step size taking into account the slow motion speed + var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps; + + // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals + this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0); + + // call the game update logic multiple times if necessary to "catch up" with dropped frames + // unless forceSingleUpdate is true + var count = 0; + + this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); + + if (this.forceSingleUpdate) + { + this.updatesThisFrame = Math.min(1, this.updatesThisFrame); + } + + if (this.forceSingleRender) + { + this.rendersThisFrame = 1; + } + else + { + this.rendersThisFrame = Math.min(1, this.updatesThisFrame); + } + + while (this._deltaTime >= slowStep) + { + this._deltaTime -= slowStep; + this.currentUpdateID = count; + + this.updateLogic(this.time.desiredFpsMult); + + count++; + + if (this.forceSingleUpdate && count === 1) + { + break; + } + else + { + this.time.refresh(); + } + } + + // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly) + if (count > this._lastCount) + { + this._spiraling++; + } + else if (count < this._lastCount) + { + // looks like it caught up successfully, reset the spiral alert counter + this._spiraling = 0; + } + + this._lastCount = count; + + if (this.rendersThisFrame > 0) + { + this.updateRender(this._deltaTime / slowStep); + } + } + + }, + + /** + * Updates all logic subsystems in Phaser. Called automatically by Game.update. + * + * @method Phaser.Game#updateLogic + * @protected + * @param {number} timeStep - The current timeStep value as determined by Game.update. + */ + updateLogic: function (timeStep) { + + if (!this._paused && !this.pendingStep) + { + if (this.stepping) + { + this.pendingStep = true; + } + + this.time.countUpdate(); + + this.scale.preUpdate(); + this.debug.preUpdate(); + this.camera.preUpdate(); + this.physics.preUpdate(); + this.state.preUpdate(timeStep); + this.plugins.preUpdate(timeStep); + this.stage.preUpdate(); + + this.state.update(); + this.stage.update(); + this.tweens.update(); + this.sound.update(); + this.input.update(); + this.physics.update(); + this.plugins.update(); + + this.stage.postUpdate(); + this.plugins.postUpdate(); + } + else + { + // Scaling and device orientation changes are still reflected when paused. + this.scale.pauseUpdate(); + this.state.pauseUpdate(timeStep); + this.debug.preUpdate(); + this.input.pauseUpdate(); + } + + this.stage.updateTransform(); + + }, + + /** + * Runs the Render cycle. + * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. + * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. + * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. + * After this State.render is called. Any rendering that happens here will take place on-top of the display list. + * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. + * This method is called automatically by Game.update, you don't need to call it directly. + * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. + * Phaser will only render when this boolean is `false`. + * + * @method Phaser.Game#updateRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ + updateRender: function (elapsedTime) { + + if (this.lockRender) + { + return; + } + + this.time.countRender(); + + this.state.preRender(elapsedTime); + + if (this.renderType !== Phaser.HEADLESS) + { + this.renderer.render(this.stage); + + this.plugins.render(elapsedTime); + + this.state.render(elapsedTime); + } + + this.plugins.postRender(elapsedTime); + + }, + + /** + * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) + * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! + * + * @method Phaser.Game#enableStep + */ + enableStep: function () { + + this.stepping = true; + this.pendingStep = false; + this.stepCount = 0; + + }, + + /** + * Disables core game loop stepping. + * + * @method Phaser.Game#disableStep + */ + disableStep: function () { + + this.stepping = false; + this.pendingStep = false; + + }, + + /** + * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. + * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. + * + * @method Phaser.Game#step + */ + step: function () { + + this.pendingStep = false; + this.stepCount++; + + }, + + /** + * Nukes the entire game from orbit. + * + * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. + * + * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM + * and resets the PIXI default renderer. + * + * To destroy the game during an update callback, set {@link #pendingDestroy} instead. + * + * @method Phaser.Game#destroy + */ + destroy: function () { + + this.raf.stop(); + + if (this.debug.destroy) + { + this.debug.destroy(); + } + + this.state.destroy(); + this.sound.destroy(); + this.scale.destroy(); + this.stage.destroy(); + this.input.destroy(); + this.physics.destroy(); + this.plugins.destroy(); + + this.debug = null; + this.state = null; + this.sound = null; + this.scale = null; + this.stage = null; + this.input = null; + this.physics = null; + this.plugins = null; + + this.cache = null; + this.load = null; + this.time = null; + this.world = null; + + this.isBooted = false; + + this.renderer.destroy(false); + + Phaser.Canvas.removeFromDOM(this.canvas); + + PIXI.defaultRenderer = null; + + Phaser.GAMES[this.id] = null; + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gamePaused + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gamePaused: function (event) { + + // If the game is already paused it was done via game code, so don't re-pause it + if (!this._paused) + { + this._paused = true; + + this.time.gamePaused(); + + if (this.sound.muteOnPause) + { + this.sound.setMute(); + } + + this.onPause.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = true; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gameResumed + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + gameResumed: function (event) { + + // Game is paused, but wasn't paused via code, so resume it + if (this._paused && !this._codePaused) + { + this._paused = false; + + this.time.gameResumed(); + + this.input.reset(); + + if (this.sound.muteOnPause) + { + this.sound.unsetMute(); + } + + this.onResume.dispatch(event); + + // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 + if (this.device.cordova && this.device.iOS) + { + this.lockRender = false; + } + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusLoss + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusLoss: function (event) { + + this.onBlur.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gamePaused(event); + } + + }, + + /** + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusGain + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ + focusGain: function (event) { + + this.onFocus.dispatch(event); + + if (!this.stage.disableVisibilityChange) + { + this.gameResumed(event); + } + + } + +}; + +Phaser.Game.prototype.constructor = Phaser.Game; + +/** +* The paused state of the Game. A paused game doesn't update any of its subsystems. +* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. +* @name Phaser.Game#paused +* @property {boolean} paused - Gets and sets the paused state of the Game. +*/ +Object.defineProperty(Phaser.Game.prototype, "paused", { + + get: function () { + return this._paused; + }, + + set: function (value) { + + if (value === true) + { + if (this._paused === false) + { + this._paused = true; + this.sound.setMute(); + this.time.gamePaused(); + this.onPause.dispatch(this); + } + this._codePaused = true; + } + else + { + if (this._paused) + { + this._paused = false; + this.input.reset(); + this.sound.unsetMute(); + this.time.gameResumed(); + this.onResume.dispatch(this); + } + this._codePaused = false; + } + + } + +}); + +/** + * + * "Deleted code is debugged code." - Jeff Sickel + * + * ヽ(〃^▽^〃)ノ + * +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. +* The Input manager is updated automatically by the core game loop. +* +* @class Phaser.Input +* @constructor +* @param {Phaser.Game} game - Current game instance. +*/ +Phaser.Input = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. + * @default + */ + this.hitCanvas = null; + + /** + * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. + * @default + */ + this.hitContext = null; + + /** + * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. + * To add a callback to this array please use `Input.addMoveCallback`. + * @property {array} moveCallbacks + * @protected + */ + this.moveCallbacks = []; + + /** + * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandler = null; + + /** + * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler. + * @private + */ + this.customCandidateHandlerContext = null; + + /** + * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. + * @default + */ + this.pollRate = 0; + + /** + * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. + * + * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. + * @default + */ + this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE; + + /** + * @property {Phaser.Point} position - A point object representing the current position of the Pointer. + * @default + */ + this.position = null; + + /** + * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. + */ + this.speed = null; + + /** + * A Circle object centered on the x/y screen coordinates of the Input. + * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. + * @property {Phaser.Circle} circle + */ + this.circle = null; + + /** + * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. + */ + this.scale = null; + + /** + * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1. + * @default -1 (Limited by total pointers.) + */ + this.maxPointers = -1; + + /** + * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. + * @default + */ + this.tapRate = 200; + + /** + * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. + * @default + */ + this.doubleTapRate = 300; + + /** + * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. + * @default + */ + this.holdRate = 2000; + + /** + * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. + * @default + */ + this.justPressedRate = 200; + + /** + * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . + * @default + */ + this.justReleasedRate = 200; + + /** + * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. + * The history is cleared each time the Pointer is pressed down. + * The history is updated at the rate specified in Input.pollRate + * @property {boolean} recordPointerHistory + * @default + */ + this.recordPointerHistory = false; + + /** + * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. + * @default + */ + this.recordRate = 100; + + /** + * The total number of entries that can be recorded into the Pointer objects tracking history. + * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. + * @property {number} recordLimit + * @default + */ + this.recordLimit = 100; + + /** + * An array of callbacks that will be fired every time a native touch start or touch end event (pointerdown or pointerup when using Pointer events) is received from the browser. + * This is used internally to handle audio and video unlocking on mobile devices. + * To add a callback to this array please use `Input.addTouchLockCallback`. + * @property {array} touchLockCallbacks + * @protected + */ + this.touchLockCallbacks = []; + + /** + * @property {Phaser.Pointer} pointer1 - A Pointer object. + */ + this.pointer1 = null; + + /** + * @property {Phaser.Pointer} pointer2 - A Pointer object. + */ + this.pointer2 = null; + + /** + * @property {Phaser.Pointer} pointer3 - A Pointer object. + */ + this.pointer3 = null; + + /** + * @property {Phaser.Pointer} pointer4 - A Pointer object. + */ + this.pointer4 = null; + + /** + * @property {Phaser.Pointer} pointer5 - A Pointer object. + */ + this.pointer5 = null; + + /** + * @property {Phaser.Pointer} pointer6 - A Pointer object. + */ + this.pointer6 = null; + + /** + * @property {Phaser.Pointer} pointer7 - A Pointer object. + */ + this.pointer7 = null; + + /** + * @property {Phaser.Pointer} pointer8 - A Pointer object. + */ + this.pointer8 = null; + + /** + * @property {Phaser.Pointer} pointer9 - A Pointer object. + */ + this.pointer9 = null; + + /** + * @property {Phaser.Pointer} pointer10 - A Pointer object. + */ + this.pointer10 = null; + + /** + * An array of non-mouse pointers that have been added to the game. + * The properties `pointer1..N` are aliases for `pointers[0..N-1]`. + * @property {Phaser.Pointer[]} pointers + * @public + * @readonly + */ + this.pointers = []; + + /** + * The most recently active Pointer object. + * + * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. + * + * @property {Phaser.Pointer} activePointer + */ + this.activePointer = null; + + /** + * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. + * + * @property {Pointer} mousePointer + */ + this.mousePointer = null; + + /** + * The Mouse Input manager. + * + * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Mouse} mouse + */ + this.mouse = null; + + /** + * The Keyboard Input manager. + * + * @property {Phaser.Keyboard} keyboard + */ + this.keyboard = null; + + /** + * The Touch Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Touch} touch + */ + this.touch = null; + + /** + * The MSPointer Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.MSPointer} mspointer + */ + this.mspointer = null; + + /** + * The Gamepad Input manager. + * + * @property {Phaser.Gamepad} gamepad + */ + this.gamepad = null; + + /** + * If the Input Manager has been reset locked then all calls made to InputManager.reset, + * such as from a State change, are ignored. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is pressed down. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onDown + */ + this.onDown = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is released. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onUp + */ + this.onUp = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is tapped. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {boolean} True if this was a double tap. + * + * @property {Phaser.Signal} onTap + */ + this.onTap = null; + + /** + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is held down. + * It is sent one argument: + * + * - {Phaser.Pointer} The pointer that caused the event. + * + * @property {Phaser.Signal} onHold + */ + this.onHold = null; + + /** + * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. + * This is useful when stacking UI layers. Set to zero to disable. + * @property {number} minPriorityID + * @default + */ + this.minPriorityID = 0; + + /** + * A list of interactive objects. The InputHandler components add and remove themselves from this list. + * @property {Phaser.ArraySet} interactiveItems + */ + this.interactiveItems = new Phaser.ArraySet(); + + /** + * @property {Phaser.Point} _localPoint - Internal cache var. + * @private + */ + this._localPoint = new Phaser.Point(); + + /** + * @property {number} _pollCounter - Internal var holding the current poll counter. + * @private + */ + this._pollCounter = 0; + + /** + * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. + * @private + */ + this._oldPosition = null; + + /** + * @property {number} _x - x coordinate of the most recent Pointer event + * @private + */ + this._x = 0; + + /** + * @property {number} _y - Y coordinate of the most recent Pointer event + * @private + */ + this._y = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Input.MOUSE_TOUCH_COMBINE = 2; + +/** +* The maximum number of pointers that can be added. This excludes the mouse pointer. +* @constant +* @type {integer} +*/ +Phaser.Input.MAX_POINTERS = 10; + +Phaser.Input.prototype = { + + /** + * Starts the Input Manager running. + * + * @method Phaser.Input#boot + * @protected + */ + boot: function () { + + this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR); + this.addPointer(); + this.addPointer(); + + this.mouse = new Phaser.Mouse(this.game); + this.touch = new Phaser.Touch(this.game); + this.mspointer = new Phaser.MSPointer(this.game); + + if (Phaser.Keyboard) + { + this.keyboard = new Phaser.Keyboard(this.game); + } + + if (Phaser.Gamepad) + { + this.gamepad = new Phaser.Gamepad(this.game); + } + + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + + this.scale = new Phaser.Point(1, 1); + this.speed = new Phaser.Point(); + this.position = new Phaser.Point(); + this._oldPosition = new Phaser.Point(); + + this.circle = new Phaser.Circle(0, 0, 44); + + this.activePointer = this.mousePointer; + + this.hitCanvas = Phaser.CanvasPool.create(this, 1, 1); + this.hitContext = this.hitCanvas.getContext('2d'); + + this.mouse.start(); + if (!this.game.device.mspointer) + { + // Chrome >= 55 fires both PointerEvent and TouchEvent. + // Pick only one. + this.touch.start(); + } + this.mspointer.start(); + this.mousePointer.active = true; + + if (this.keyboard) + { + this.keyboard.start(); + } + + var _this = this; + + this._onClickTrampoline = function (event) { + _this.onClickTrampoline(event); + }; + + this.game.canvas.addEventListener('click', this._onClickTrampoline, false); + + }, + + /** + * Stops all of the Input Managers from running. + * + * @method Phaser.Input#destroy + */ + destroy: function () { + + this.mouse.stop(); + this.touch.stop(); + this.mspointer.stop(); + + if (this.keyboard) + { + this.keyboard.stop(); + } + + if (this.gamepad) + { + this.gamepad.stop(); + } + + this.moveCallbacks = []; + + Phaser.CanvasPool.remove(this); + + this.game.canvas.removeEventListener('click', this._onClickTrampoline); + + }, + + /** + * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. + * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to + * interact with. It works by polling all of the valid game objects, and then slowly discounting those + * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). + * + * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid + * for input and overlap with the Pointer. If you need fine-grained control over which of the items is + * selected then you can use this callback to do so. + * + * The callback will be sent 3 parameters: + * + * 1) A reference to the Phaser.Pointer object that is processing the Items. + * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. + * 3) The current 'favorite' candidate, based on its priorityID and position in the display list. + * + * Your callback MUST return one of the candidates sent to it. + * + * @method Phaser.Input#setInteractiveCandidateHandler + * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. + * @param {object} context - The context in which the callback will be called. + */ + setInteractiveCandidateHandler: function (callback, context) { + + this.customCandidateHandler = callback; + this.customCandidateHandlerContext = context; + + }, + + /** + * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. + * + * The callback will be sent 4 parameters: + * + * A reference to the Phaser.Pointer object that moved, + * The x position of the pointer, + * The y position, + * A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down). + * + * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best + * to only use if you've limited input to a single pointer (i.e. mouse or touch). + * + * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. + * + * @method Phaser.Input#addMoveCallback + * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. + * @param {object} context - The context in which the callback will be called. + */ + addMoveCallback: function (callback, context) { + + this.moveCallbacks.push({ callback: callback, context: context }); + + }, + + + /** + * Adds a callback that is fired when a browser touchstart/pointerdown or touchend/pointerup event is received. + * + * This is used internally to handle audio and video unlocking on mobile devices. + * + * If the callback returns 'true' then the callback is automatically deleted once invoked. + * + * The callback is added to the {@link #touchLockCallbacks} array and should be removed with {@link #removeTouchLockCallback}. + * + * @method Phaser.Input#addTouchLockCallback + * @param {function} callback - The callback that will be called when a touchstart event is received. + * @param {object} context - The context in which the callback will be called. + * @param {boolean} [onEnd=false] - Will the callback fire on a touchstart/pointerdown (default) or touchend/pointerup event? + */ + addTouchLockCallback: function (callback, context, onEnd) { + + if (onEnd === undefined) { onEnd = false; } + + this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd }); + + }, + + /** + * Removes the callback at the defined index from the {@link #touchLockCallbacks} array + * + * @method Phaser.Input#removeTouchLockCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + * @return {boolean} True if the callback was deleted, otherwise false. + */ + removeTouchLockCallback: function (callback, context) { + + var i = this.touchLockCallbacks.length; + + while (i--) + { + if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context) + { + this.touchLockCallbacks.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Execute any {@link #touchLockCallbacks} of the given type. + * + * @method Phaser.Input#executeTouchLockCallbacks + * @private + * @param {boolean} onEnd - Execute the touchend/pointerup callbacks (true) or the touchstart/pointerdown callbacks (false). Required! + * @param {Event} event - The native event from the browser. + */ + executeTouchLockCallbacks: function (onEnd, event) { + var i = this.touchLockCallbacks.length; + + while (i--) + { + var cb = this.touchLockCallbacks[i]; + + if (cb.onEnd === onEnd && cb.callback.call(cb.context, this, event)) + { + this.touchLockCallbacks.splice(i, 1); + } + } + }, + + /** + * Removes the callback from the Phaser.Input.moveCallbacks array. + * + * @method Phaser.Input#deleteMoveCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + */ + deleteMoveCallback: function (callback, context) { + + var i = this.moveCallbacks.length; + + while (i--) + { + if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context) + { + this.moveCallbacks.splice(i, 1); + return; + } + } + + }, + + /** + * Add a new Pointer object to the Input Manager. + * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. + * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). + * + * @method Phaser.Input#addPointer + * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. + */ + addPointer: function () { + + if (this.pointers.length >= Phaser.Input.MAX_POINTERS) + { + console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached."); + return null; + } + + var id = this.pointers.length + 1; + var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.CONTACT); + + this.pointers.push(pointer); + this['pointer' + id] = pointer; + + return pointer; + + }, + + /** + * Updates the Input Manager. Called by the core Game loop. + * + * @method Phaser.Input#update + * @protected + */ + update: function () { + + if (this.keyboard) + { + this.keyboard.update(); + } + + if (this.pollRate > 0 && this._pollCounter < this.pollRate) + { + this._pollCounter++; + return; + } + + this.speed.x = this.position.x - this._oldPosition.x; + this.speed.y = this.position.y - this._oldPosition.y; + + this._oldPosition.copyFrom(this.position); + this.mousePointer.update(); + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].update(); + } + + this._pollCounter = 0; + + }, + + /** + * Update method while paused. + * + * @method Phaser.Input#pauseUpdate + * @private + */ + pauseUpdate: function () { + + if (this.gamepad && this.gamepad.active) + { + this.gamepad.update(); + } + + }, + + /** + * Reset all of the Pointers and Input states. + * + * The optional `hard` parameter will reset any events or callbacks that may be bound. + * Input.reset is called automatically during a State change or if a game loses focus / visibility. + * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. + * + * @method Phaser.Input#reset + * @public + * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. + */ + reset: function (hard) { + + if (!this.game.isBooted || this.resetLocked) + { + return; + } + + if (hard === undefined) { hard = false; } + + this.mousePointer.reset(); + + if (this.keyboard) + { + this.keyboard.reset(hard); + } + + for (var i = 0; i < this.pointers.length; i++) + { + this.pointers[i].reset(); + } + + if (this.game.canvas.style.cursor !== 'none') + { + this.game.canvas.style.cursor = ''; + } + + if (hard) + { + this.onDown.dispose(); + this.onUp.dispose(); + this.onTap.dispose(); + this.onHold.dispose(); + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + this.onTap = new Phaser.Signal(); + this.onHold = new Phaser.Signal(); + this.moveCallbacks = []; + } + + this._pollCounter = 0; + + }, + + /** + * Resets the speed and old position properties. + * + * @method Phaser.Input#resetSpeed + * @param {number} x - Sets the oldPosition.x value. + * @param {number} y - Sets the oldPosition.y value. + */ + resetSpeed: function (x, y) { + + this._oldPosition.setTo(x, y); + this.speed.setTo(0, 0); + + }, + + /** + * Find the first free Pointer object and start it, passing in the event data. + * This is called automatically by Phaser.Touch and Phaser.MSPointer. + * + * @method Phaser.Input#startPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. + */ + startPointer: function (event) { + + if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers) + { + return null; + } + + if (!this.pointer1.active) + { + return this.pointer1.start(event); + } + + if (!this.pointer2.active) + { + return this.pointer2.start(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (!pointer.active) + { + return pointer.start(event); + } + } + + return null; + + }, + + /** + * Updates the matching Pointer object, passing in the event data. + * This is called automatically and should not normally need to be invoked. + * + * @method Phaser.Input#updatePointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. + */ + updatePointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.move(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.move(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.move(event); + } + } + + return null; + + }, + + /** + * Stops the matching Pointer object, passing in the event data. + * + * @method Phaser.Input#stopPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. + */ + stopPointer: function (event) { + + if (this.pointer1.active && this.pointer1.identifier === event.identifier) + { + return this.pointer1.stop(event); + } + + if (this.pointer2.active && this.pointer2.identifier === event.identifier) + { + return this.pointer2.stop(event); + } + + for (var i = 2; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active && pointer.identifier === event.identifier) + { + return pointer.stop(event); + } + } + + return null; + + }, + + /** + * Returns the total number of active pointers, not exceeding the specified limit + * + * @name Phaser.Input#countActivePointers + * @private + * @property {integer} [limit=(max pointers)] - Stop counting after this. + * @return {integer} The number of active pointers, or limit - whichever is less. + */ + countActivePointers: function (limit) { + + if (limit === undefined) { limit = this.pointers.length; } + + var count = limit; + + for (var i = 0; i < this.pointers.length && count > 0; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active) + { + count--; + } + } + + return (limit - count); + + }, + + /** + * Get the first Pointer with the given active state. + * + * @method Phaser.Input#getPointer + * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. + */ + getPointer: function (isActive) { + + if (isActive === undefined) { isActive = false; } + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.active === isActive) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `identifier` property matches the given identifier value. + * + * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down, and is not fixed once set. + * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. + * + * @method Phaser.Input#getPointerFromIdentifier + * @param {number} identifier - The Pointer.identifier value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromIdentifier: function (identifier) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.identifier === identifier) + { + return pointer; + } + } + + return null; + + }, + + /** + * Get the Pointer object whos `pointerId` property matches the given value. + * + * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down if the browser recycles it. + * + * @method Phaser.Input#getPointerFromId + * @param {number} pointerId - The `pointerId` (not 'id') value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ + getPointerFromId: function (pointerId) { + + for (var i = 0; i < this.pointers.length; i++) + { + var pointer = this.pointers[i]; + + if (pointer.pointerId === pointerId) + { + return pointer; + } + } + + return null; + + }, + + /** + * This will return the local coordinates of the specified displayObject based on the given Pointer. + * + * @method Phaser.Input#getLocalPosition + * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. + * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. + * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. + */ + getLocalPosition: function (displayObject, pointer, output) { + + if (output === undefined) { output = new Phaser.Point(); } + + var wt = displayObject.worldTransform; + var id = 1 / (wt.a * wt.d + wt.c * -wt.b); + + return output.setTo( + wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id, + wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id + ); + + }, + + /** + * Tests if the pointer hits the given object. + * + * @method Phaser.Input#hitTest + * @param {DisplayObject} displayObject - The displayObject to test for a hit. + * @param {Phaser.Pointer} pointer - The pointer to use for the test. + * @param {Phaser.Point} localPoint - The local translated point. + */ + hitTest: function (displayObject, pointer, localPoint) { + + if (!displayObject.worldVisible) + { + return false; + } + + this.getLocalPosition(displayObject, pointer, this._localPoint); + + localPoint.copyFrom(this._localPoint); + + if (displayObject.hitArea && displayObject.hitArea.contains) + { + return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y)); + } + else if (Phaser.Creature && displayObject instanceof Phaser.Creature) { + var width = Math.abs(displayObject.width); + var height = Math.abs(displayObject.height); + var x1 = displayObject.x - (width * displayObject.anchorX); + + if (this.game.camera.x + pointer.x >= x1 && this.game.camera.x + pointer.x < x1 + width) + { + var y1 = displayObject.y - (height * displayObject.anchorY); + + if (this.game.camera.y + pointer.y >= y1 && this.game.camera.y + pointer.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.TileSprite) + { + var width = displayObject.width; + var height = displayObject.height; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof PIXI.Sprite) + { + var width = displayObject.texture.frame.width / displayObject.texture.baseTexture.resolution; + var height = displayObject.texture.frame.height / displayObject.texture.baseTexture.resolution; + var x1 = -width * displayObject.anchor.x; + + if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width) + { + var y1 = -height * displayObject.anchor.y; + + if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height) + { + return true; + } + } + } + else if (displayObject instanceof Phaser.Graphics) + { + for (var i = 0; i < displayObject.graphicsData.length; i++) + { + var data = displayObject.graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // Only deal with fills.. + if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y)) + { + return true; + } + } + } + + // Didn't hit the parent, does it have any children? + + for (var i = 0; i < displayObject.children.length; i++) + { + if (this.hitTest(displayObject.children[i], pointer, localPoint)) + { + return true; + } + } + + return false; + }, + + /** + * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. + * + * @method Phaser.Input#onClickTrampoline + * @private + */ + onClickTrampoline: function () { + + // It might not always be the active pointer, but this does work on + // Desktop browsers (read: IE) with Mouse or MSPointer input. + this.activePointer.processClickTrampolines(); + + } + +}; + +Phaser.Input.prototype.constructor = Phaser.Input; + +/** +* The X coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. +* @name Phaser.Input#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Input.prototype, "x", { + + get: function () { + return this._x; + }, + + set: function (value) { + this._x = Math.floor(value); + } + +}); + +/** +* The Y coordinate of the most recently active pointer. +* This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. +* @name Phaser.Input#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Input.prototype, "y", { + + get: function () { + return this._y; + }, + + set: function (value) { + this._y = Math.floor(value); + } + +}); + +/** +* True if the Input is currently poll rate locked. +* @name Phaser.Input#pollLocked +* @property {boolean} pollLocked +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "pollLocked", { + + get: function () { + return (this.pollRate > 0 && this._pollCounter < this.pollRate); + } + +}); + +/** +* The total number of inactive Pointers. +* @name Phaser.Input#totalInactivePointers +* @property {number} totalInactivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", { + + get: function () { + return this.pointers.length - this.countActivePointers(); + } + +}); + +/** +* The total number of active Pointers, not counting the mouse pointer. +* @name Phaser.Input#totalActivePointers +* @property {integers} totalActivePointers +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", { + + get: function () { + return this.countActivePointers(); + } + +}); + +/** +* The world X coordinate of the most recently active pointer. +* @name Phaser.Input#worldX +* @property {number} worldX - The world X coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldX", { + + get: function () { + return this.game.camera.view.x + this.x; + } + +}); + +/** +* The world Y coordinate of the most recently active pointer. +* @name Phaser.Input#worldY +* @property {number} worldY - The world Y coordinate of the most recently active pointer. +* @readonly +*/ +Object.defineProperty(Phaser.Input.prototype, "worldY", { + + get: function () { + return this.game.camera.view.y + this.y; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Mouse class is responsible for handling all aspects of mouse interaction with the browser. +* +* It captures and processes mouse events that happen on the game canvas object. +* It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released +* when not over the game. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object +* which normalises all game input for you, including accurate button handling. +* +* @class Phaser.Mouse +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Mouse = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down. + */ + this.mouseDownCallback = null; + + /** + * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state. + */ + this.mouseUpCallback = null; + + /** + * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas. + */ + this.mouseOutCallback = null; + + /** + * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). + */ + this.mouseOverCallback = null; + + /** + * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used. + */ + this.mouseWheelCallback = null; + + /** + * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully. + */ + this.capture = false; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + * @default + */ + this.button = -1; + + /** + * The direction of the _last_ mousewheel usage 1 for up -1 for down. + * @property {number} wheelDelta + */ + this.wheelDelta = 0; + + /** + * Mouse input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true. + * @default + */ + this.locked = false; + + /** + * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas. + * @default + */ + this.stopOnGameOut = false; + + /** + * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state. + * @default + */ + this.pointerLock = new Phaser.Signal(); + + /** + * The browser mouse DOM event. Will be null if no mouse event has ever been received. + * Access this property only inside a Mouse event handler and do not keep references to it. + * @property {MouseEvent|null} event + * @default + */ + this.event = null; + + /** + * @property {function} _onMouseDown - Internal event handler reference. + * @private + */ + this._onMouseDown = null; + + /** + * @property {function} _onMouseMove - Internal event handler reference. + * @private + */ + this._onMouseMove = null; + + /** + * @property {function} _onMouseUp - Internal event handler reference. + * @private + */ + this._onMouseUp = null; + + /** + * @property {function} _onMouseOut - Internal event handler reference. + * @private + */ + this._onMouseOut = null; + + /** + * @property {function} _onMouseOver - Internal event handler reference. + * @private + */ + this._onMouseOver = null; + + /** + * @property {function} _onMouseWheel - Internal event handler reference. + * @private + */ + this._onMouseWheel = null; + + /** + * Wheel proxy event object, if required. Shared for all wheel events for this mouse. + * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent + * @private + */ + this._wheelEvent = null; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.NO_BUTTON = -1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.LEFT_BUTTON = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.MIDDLE_BUTTON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.RIGHT_BUTTON = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.BACK_BUTTON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Mouse.FORWARD_BUTTON = 4; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_UP = 1; + +/** + * @constant + * @type {number} + */ +Phaser.Mouse.WHEEL_DOWN = -1; + +Phaser.Mouse.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Mouse#start + */ + start: function () { + + if (this.game.device.android && this.game.device.chrome === false) + { + // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ... + return; + } + + if (this._onMouseDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onMouseDown = function (event) { + return _this.onMouseDown(event); + }; + + this._onMouseMove = function (event) { + return _this.onMouseMove(event); + }; + + this._onMouseUp = function (event) { + return _this.onMouseUp(event); + }; + + this._onMouseUpGlobal = function (event) { + return _this.onMouseUpGlobal(event); + }; + + this._onMouseOutGlobal = function (event) { + return _this.onMouseOutGlobal(event); + }; + + this._onMouseOut = function (event) { + return _this.onMouseOut(event); + }; + + this._onMouseOver = function (event) { + return _this.onMouseOver(event); + }; + + this._onMouseWheel = function (event) { + return _this.onMouseWheel(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('mousedown', this._onMouseDown, true); + canvas.addEventListener('mousemove', this._onMouseMove, true); + canvas.addEventListener('mouseup', this._onMouseUp, true); + + if (!this.game.device.cocoonJS) + { + window.addEventListener('mouseup', this._onMouseUpGlobal, true); + window.addEventListener('mouseout', this._onMouseOutGlobal, true); + canvas.addEventListener('mouseover', this._onMouseOver, true); + canvas.addEventListener('mouseout', this._onMouseOut, true); + } + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.addEventListener(wheelEvent, this._onMouseWheel, true); + + if (wheelEvent === 'mousewheel') + { + this._wheelEvent = new WheelEventProxy(-1/40, 1); + } + else if (wheelEvent === 'DOMMouseScroll') + { + this._wheelEvent = new WheelEventProxy(1, 1); + } + } + + }, + + /** + * The internal method that handles the mouse down event from the browser. + * @method Phaser.Mouse#onMouseDown + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseDown: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseDownCallback) + { + this.mouseDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.start(event); + + }, + + /** + * The internal method that handles the mouse move event from the browser. + * @method Phaser.Mouse#onMouseMove + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseMoveCallback) + { + this.mouseMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.move(event); + + }, + + /** + * The internal method that handles the mouse up event from the browser. + * @method Phaser.Mouse#onMouseUp + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUp: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.Mouse#onMouseUpGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseUpGlobal: function (event) { + + if (!this.input.mousePointer.withinGame) + { + if (this.mouseUpCallback) + { + this.mouseUpCallback.call(this.callbackContext, event); + } + + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + }, + + /** + * The internal method that handles the mouse out event from the window. + * + * @method Phaser.Mouse#onMouseOutGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOutGlobal: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (!this.input.enabled || !this.enabled) + { + return; + } + + // If we get a mouseout event from the window then basically + // something serious has gone down, usually along the lines of + // the browser opening a context-menu or similar. + // On OS X Chrome especially this is bad news, as it blocks + // us then getting a mouseup event, so we need to force that through. + // + // No matter what, we must cancel the left and right buttons + + this.input.mousePointer.stop(event); + + // Clear the button states (again?) + this.input.mousePointer.resetButtons(); + + }, + + /** + * The internal method that handles the mouse out event from the browser. + * + * @method Phaser.Mouse#onMouseOut + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = false; + + if (this.mouseOutCallback) + { + this.mouseOutCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.stopOnGameOut) + { + event['identifier'] = 0; + + this.input.mousePointer.stop(event); + } + + this.input.interactiveItems.callAll('_pointerOutHandler', this.input.mousePointer); + + }, + + /** + * The internal method that handles the mouse over event from the browser. + * + * @method Phaser.Mouse#onMouseOver + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ + onMouseOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + this.input.mousePointer.withinGame = true; + + if (this.mouseOverCallback) + { + this.mouseOverCallback.call(this.callbackContext, event); + } + + }, + + /** + * The internal method that handles the mouse wheel event from the browser. + * + * @method Phaser.Mouse#onMouseWheel + * @param {MouseEvent} event - The native event from the browser. + */ + onMouseWheel: function (event) { + + if (this._wheelEvent) { + event = this._wheelEvent.bindEvent(event); + } + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + // reverse detail for firefox + this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1); + + if (this.mouseWheelCallback) + { + this.mouseWheelCallback.call(this.callbackContext, event); + } + + }, + + /** + * If the browser supports it you can request that the pointer be locked to the browser window. + * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key. + * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'. + * @method Phaser.Mouse#requestPointerLock + */ + requestPointerLock: function () { + + if (this.game.device.pointerLock) + { + var element = this.game.canvas; + + element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; + + element.requestPointerLock(); + + var _this = this; + + this._pointerLockChange = function (event) { + return _this.pointerLockChange(event); + }; + + document.addEventListener('pointerlockchange', this._pointerLockChange, true); + document.addEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true); + } + + }, + + /** + * Internal pointerLockChange handler. + * + * @method Phaser.Mouse#pointerLockChange + * @param {Event} event - The native event from the browser. This gets stored in Mouse.event. + */ + pointerLockChange: function (event) { + + var element = this.game.canvas; + + if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) + { + // Pointer was successfully locked + this.locked = true; + this.pointerLock.dispatch(true, event); + } + else + { + // Pointer was unlocked + this.locked = false; + this.pointerLock.dispatch(false, event); + } + + }, + + /** + * Internal release pointer lock handler. + * @method Phaser.Mouse#releasePointerLock + */ + releasePointerLock: function () { + + document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; + + document.exitPointerLock(); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + }, + + /** + * Stop the event listeners. + * @method Phaser.Mouse#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('mousedown', this._onMouseDown, true); + canvas.removeEventListener('mousemove', this._onMouseMove, true); + canvas.removeEventListener('mouseup', this._onMouseUp, true); + canvas.removeEventListener('mouseover', this._onMouseOver, true); + canvas.removeEventListener('mouseout', this._onMouseOut, true); + + var wheelEvent = this.game.device.wheelEvent; + + if (wheelEvent) + { + canvas.removeEventListener(wheelEvent, this._onMouseWheel, true); + } + + window.removeEventListener('mouseup', this._onMouseUpGlobal, true); + window.removeEventListener('mouseout', this._onMouseOutGlobal, true); + + document.removeEventListener('pointerlockchange', this._pointerLockChange, true); + document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); + document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); + + } + +}; + +Phaser.Mouse.prototype.constructor = Phaser.Mouse; + +/* jshint latedef:nofunc */ +/** +* A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel' +* events to 'wheel'-like events. +* +* See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode. +* +* @method Phaser.Mouse#WheelEventProxy +* @private +* @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. +* @param {integer} deltaMode - The reported delta mode. +*/ +function WheelEventProxy (scaleFactor, deltaMode) { + + /** + * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. + * @private + */ + this._scaleFactor = scaleFactor; + + /** + * @property {number} _deltaMode - The reported delta mode. + * @private + */ + this._deltaMode = deltaMode; + + /** + * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit. + * @private + */ + this.originalEvent = null; + +} + +WheelEventProxy.prototype = {}; +WheelEventProxy.prototype.constructor = WheelEventProxy; + +WheelEventProxy.prototype.bindEvent = function (event) { + + // Generate stubs automatically + if (!WheelEventProxy._stubsGenerated && event) + { + var makeBinder = function (name) { + + return function () { + var v = this.originalEvent[name]; + return typeof v !== 'function' ? v : v.bind(this.originalEvent); + }; + + }; + + for (var prop in event) + { + if (!(prop in WheelEventProxy.prototype)) + { + Object.defineProperty(WheelEventProxy.prototype, prop, { + get: makeBinder(prop) + }); + } + } + WheelEventProxy._stubsGenerated = true; + } + + this.originalEvent = event; + return this; + +}; + +Object.defineProperties(WheelEventProxy.prototype, { + "type": { value: "wheel" }, + "deltaMode": { get: function () { return this._deltaMode; } }, + "deltaY": { + get: function () { + return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0; + } + }, + "deltaX": { + get: function () { + return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0; + } + }, + "deltaZ": { value: 0 } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The MSPointer class handles {@link https://developers.google.com/web/updates/2016/10/pointer-events Pointer-event} interactions with the game via a dedicated {@link Phaser.Pointer}. (It's named after the nonstandard {@link https://msdn.microsoft.com/library/hh673557(v=vs.85).aspx MSPointerEvent} since that was the first browser implementation.) +* +* It's {@link http://caniuse.com/#feat=pointer currently supported in IE 10+, Edge, Chrome (including Android), and Opera}. +* +* You should not normally access this class directly, but instead use a {@link Phaser.Pointer} object which +* normalises all game input for you including accurate button handling. +* +* Please note that at the current time of writing Phaser does not yet support chorded button interactions: +* http://www.w3.org/TR/pointerevents/#chorded-button-interactions +* +* You can disable Phaser's use of Pointer Events by either of two ways: +* +* ```javascript +* // **Before** `new Phaser.Game(…)`: +* Phaser.Device.onInitialized.add(function () { +* this.mspointer = false; +* }); +* ``` +* +* ```javascript +* // Once, in the earliest State `init` or `create` callback (e.g., Boot): +* this.input.mspointer.stop(); +* ``` +* +* @class Phaser.MSPointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.MSPointer = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ + this.input = game.input; + + /** + * @property {object} callbackContext - The context under which callbacks are called (defaults to game). + */ + this.callbackContext = this.game; + + /** + * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event. + */ + this.pointerDownCallback = null; + + /** + * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event. + */ + this.pointerMoveCallback = null; + + /** + * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event. + */ + this.pointerUpCallback = null; + + /** + * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, canceling the corresponding MouseEvent or TouchEvent. + */ + this.capture = true; + + /** + * This property was removed in Phaser 2.4 and should no longer be used. + * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on. + * Or Pointer.button holds the DOM event button value if you require that. + * @property {number} button + */ + this.button = -1; + + /** + * The most recent PointerEvent from the browser. Will be null if no event has ever been received. + * Access this property only inside a Pointer event handler and do not keep references to it. + * @property {MSPointerEvent|PointerEvent|null} event + * @default + */ + this.event = null; + + /** + * PointerEvent input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {function} _onMSPointerDown - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerDown = null; + + /** + * @property {function} _onMSPointerMove - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerMove = null; + + /** + * @property {function} _onMSPointerUp - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUp = null; + + /** + * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerUpGlobal = null; + + /** + * @property {function} _onMSPointerOut - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOut = null; + + /** + * @property {function} _onMSPointerOver - Internal function to handle MSPointer events. + * @private + */ + this._onMSPointerOver = null; + +}; + +Phaser.MSPointer.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.MSPointer#start + */ + start: function () { + + if (this._onMSPointerDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + if (this.game.device.mspointer) + { + this._onMSPointerDown = function (event) { + return _this.onPointerDown(event); + }; + + this._onMSPointerMove = function (event) { + return _this.onPointerMove(event); + }; + + this._onMSPointerUp = function (event) { + return _this.onPointerUp(event); + }; + + this._onMSPointerUpGlobal = function (event) { + return _this.onPointerUpGlobal(event); + }; + + this._onMSPointerOut = function (event) { + return _this.onPointerOut(event); + }; + + this._onMSPointerOver = function (event) { + return _this.onPointerOver(event); + }; + + var canvas = this.game.canvas; + + canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.addEventListener('pointerdown', this._onMSPointerDown, false); + canvas.addEventListener('pointermove', this._onMSPointerMove, false); + canvas.addEventListener('pointerup', this._onMSPointerUp, false); + + canvas.style['-ms-content-zooming'] = 'none'; + canvas.style['-ms-touch-action'] = 'none'; + + if (!this.game.device.cocoonJS) + { + window.addEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.addEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.addEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.addEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.addEventListener('pointerover', this._onMSPointerOver, true); + canvas.addEventListener('pointerout', this._onMSPointerOut, true); + } + } + + }, + + /** + * The function that handles the PointerDown event. + * + * @method Phaser.MSPointer#onPointerDown + * @param {PointerEvent} event - The native DOM event. + */ + onPointerDown: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerDownCallback) + { + this.pointerDownCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.start(event); + } + else + { + this.input.startPointer(event); + } + + }, + + /** + * The function that handles the PointerMove event. + * @method Phaser.MSPointer#onPointerMove + * @param {PointerEvent} event - The native DOM event. + */ + onPointerMove: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerMoveCallback) + { + this.pointerMoveCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.move(event); + } + else + { + this.input.updatePointer(event); + } + + }, + + /** + * The function that handles the PointerUp event. + * @method Phaser.MSPointer#onPointerUp + * @param {PointerEvent} event - The native DOM event. + */ + onPointerUp: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (this.pointerUpCallback) + { + this.pointerUpCallback.call(this.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + event.identifier = event.pointerId; + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.stop(event); + } + else + { + this.input.stopPointer(event); + } + + }, + + /** + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.MSPointer#onPointerUpGlobal + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerUpGlobal: function (event) { + + if ((event.pointerType === 'mouse' || event.pointerType === 0x00000004) && !this.input.mousePointer.withinGame) + { + this.onPointerUp(event); + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer && pointer.withinGame) + { + this.onPointerUp(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOut: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = false; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = false; + } + } + + if (this.input.mouse.mouseOutCallback) + { + this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext, event); + } + + if (!this.input.enabled || !this.enabled) + { + return; + } + + if (this.input.mouse.stopOnGameOut) + { + event['identifier'] = 0; + + if (pointer) + { + pointer.stop(event); + } + else + { + this.input.mousePointer.stop(event); + } + } + + }, + + /** + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ + onPointerOver: function (event) { + + this.event = event; + + if (this.capture) + { + event.preventDefault(); + } + + if (event.pointerType === 'mouse' || event.pointerType === 0x00000004) + { + this.input.mousePointer.withinGame = true; + } + else + { + var pointer = this.input.getPointerFromIdentifier(event.identifier); + + if (pointer) + { + pointer.withinGame = true; + } + } + + if (this.input.mouse.mouseOverCallback) + { + this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext, event); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.MSPointer#stop + */ + stop: function () { + + var canvas = this.game.canvas; + + canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false); + canvas.removeEventListener('MSPointerMove', this._onMSPointerMove, false); + canvas.removeEventListener('MSPointerUp', this._onMSPointerUp, false); + + // IE11+ uses non-prefix events + canvas.removeEventListener('pointerdown', this._onMSPointerDown, false); + canvas.removeEventListener('pointermove', this._onMSPointerMove, false); + canvas.removeEventListener('pointerup', this._onMSPointerUp, false); + + window.removeEventListener('MSPointerUp', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('MSPointerOver', this._onMSPointerOver, true); + canvas.removeEventListener('MSPointerOut', this._onMSPointerOut, true); + + // IE11+ uses non-prefix events + window.removeEventListener('pointerup', this._onMSPointerUpGlobal, true); + canvas.removeEventListener('pointerover', this._onMSPointerOver, true); + canvas.removeEventListener('pointerout', this._onMSPointerOut, true); + + } + +}; + +Phaser.MSPointer.prototype.constructor = Phaser.MSPointer; + +/** +* @author Richard Davey +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. +* +* For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, +* middle button and advanced buttons like back and forward. +* +* Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. +* +* On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. +* +* At the time of writing this there are device limitations you should be aware of: +* +* - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions +* (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, +* even when they are pressed. +* - On Linux (GTK), the 4th button and the 5th button are not supported. +* - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. +* +* @class Phaser.DeviceButton +* @constructor +* @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad. +* @param {number} buttonCode - The button code this DeviceButton is responsible for. +*/ +Phaser.DeviceButton = function (parent, buttonCode) { + + /** + * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = parent.game; + + /** + * @property {object} event - The DOM event that caused the change in button state. + * @default + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the button. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the button. + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - The timestamp when the button was last pressed down. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - The timestamp when the button was last released. + * @default + */ + this.timeUp = 0; + + /** + * Gamepad only. + * If a button is held down this holds down the number of times the button has 'repeated'. + * @property {number} repeats + * @default + */ + this.repeats = 0; + + /** + * True if the alt key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} altKey + * @default + */ + this.altKey = false; + + /** + * True if the shift key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} shiftKey + * @default + */ + this.shiftKey = false; + + /** + * True if the control key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} ctrlKey + * @default + */ + this.ctrlKey = false; + + /** + * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. + * @default + */ + this.value = 0; + + /** + * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. + */ + this.buttonCode = buttonCode; + + /** + * This Signal is dispatched every time this DeviceButton is pressed down. + * It is only dispatched once (until the button is released again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onDown + */ + this.onDown = new Phaser.Signal(); + + /** + * This Signal is dispatched every time this DeviceButton is released from a down state. + * It is only dispatched once (until the button is pressed again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onUp + */ + this.onUp = new Phaser.Signal(); + + /** + * Gamepad only. + * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onFloat + */ + this.onFloat = new Phaser.Signal(); + +}; + +Phaser.DeviceButton.prototype = { + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button down state. + * + * @method Phaser.DeviceButton#start + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + start: function (event, value) { + + if (this.isDown) + { + return; + } + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onDown.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button up state. + * + * @method Phaser.DeviceButton#stop + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + stop: function (event, value) { + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + + this.event = event; + this.value = value; + + if (event) + { + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.ctrlKey = event.ctrlKey; + } + + this.onUp.dispatch(this, value); + + }, + + /** + * Called automatically by Phaser.Pointer. + * Starts or stops button based on condition. + * + * @method Phaser.DeviceButton#startStop + * @protected + * @param {boolean} [condition] - The condition that decides between start or stop. + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ + startStop: function (condition, event, value) { + + if (condition) + { + this.start(event, value); + } + else + { + this.stop(event, value); + } + + }, + + /** + * Called automatically by Phaser.SinglePad. + * + * @method Phaser.DeviceButton#padFloat + * @protected + * @param {number} value - Button value + */ + padFloat: function (value) { + + this.isDown = false; + this.isUp = false; + + this.value = value; + + this.onFloat.dispatch(this, value); + + }, + + /** + * Returns the "just pressed" state of this button. + * Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justPressed + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (duration) { + + duration = duration || 250; + + return (this.isDown && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * Returns the "just released" state of this button. + * Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justReleased + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (duration) { + + duration = duration || 250; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. + * + * @method Phaser.DeviceButton#reset + */ + reset: function () { + + this.isDown = false; + this.isUp = true; + + this.timeDown = this.game.time.time; + this.repeats = 0; + + this.altKey = false; + this.shiftKey = false; + this.ctrlKey = false; + + }, + + /** + * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals + * and clears the parent and game references. + * + * @method Phaser.DeviceButton#destroy + */ + destroy: function () { + + this.onDown.dispose(); + this.onUp.dispose(); + this.onFloat.dispose(); + + this.parent = null; + this.game = null; + + } + +}; + +Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton; + +/** +* How long the button has been held down for in milliseconds. +* If not currently down it returns -1. +* +* @name Phaser.DeviceButton#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.DeviceButton.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. +* +* @class Phaser.Pointer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. +* @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or CONTACT. +*/ +Phaser.Pointer = function (game, id, pointerMode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. + */ + this.id = id; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.POINTER; + + /** + * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps. + * @default + */ + this.exists = true; + + /** + * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.identifier = 0; + + /** + * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. + * @default + */ + this.pointerId = null; + + /** + * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer. + */ + this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT); + + /** + * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ + this.target = null; + + /** + * The button property of the most recent DOM event when this Pointer is started. + * You should not rely on this value for accurate button detection, instead use the Pointer properties + * `leftButton`, `rightButton`, `middleButton` and so on. + * @property {any} button + * @default + */ + this.button = null; + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * @property {Phaser.DeviceButton} leftButton + * @default + */ + this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} middleButton + * @default + */ + this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} rightButton + * @default + */ + this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} backButton + * @default + */ + this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON); + + /** + * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} forwardButton + * @default + */ + this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON); + + /** + * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} eraserButton + * @default + */ + this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON); + + /** + * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event. + * @private + * @default + */ + this._holdSent = false; + + /** + * @property {array} _history - Local private variable storing the short-term history of pointer movements. + * @private + */ + this._history = []; + + /** + * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur. + * @private + */ + this._nextDrop = 0; + + /** + * @property {boolean} _stateReset - Monitor events outside of a state reset loop. + * @private + */ + this._stateReset = false; + + /** + * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false. + */ + this.withinGame = false; + + /** + * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientX = -1; + + /** + * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ + this.clientY = -1; + + /** + * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document. + */ + this.pageX = -1; + + /** + * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document. + */ + this.pageY = -1; + + /** + * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen. + */ + this.screenX = -1; + + /** + * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen. + */ + this.screenY = -1; + + /** + * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementX = 0; + + /** + * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event. + * @default + */ + this.rawMovementY = 0; + + /** + * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementX = 0; + + /** + * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event. + * @default + */ + this.movementY = 0; + + /** + * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.x = -1; + + /** + * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ + this.y = -1; + + /** + * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false. + */ + this.isMouse = (id === 0); + + /** + * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. + * @property {boolean} isDown + * @default + */ + this.isDown = false; + + /** + * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. + * @property {boolean} isUp + * @default + */ + this.isUp = true; + + /** + * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen. + * @default + */ + this.timeDown = 0; + + /** + * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen. + * @default + */ + this.timeUp = 0; + + /** + * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked. + * @default + */ + this.previousTapTime = 0; + + /** + * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen. + * @default + */ + this.totalTouches = 0; + + /** + * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event. + * @default + */ + this.msSinceLastClick = Number.MAX_VALUE; + + /** + * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging. + * @default + */ + this.targetObject = null; + + /** + * This array is erased and re-populated every time this Pointer is updated. It contains references to all + * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be + * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over + * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset + * every frame. + * @property {array} interactiveCandidates + * @default + */ + this.interactiveCandidates = []; + + /** + * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active. + * @default + */ + this.active = false; + + /** + * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. + * @default + */ + this.dirty = false; + + /** + * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display. + */ + this.position = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. + */ + this.positionDown = new Phaser.Point(); + + /** + * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released. + */ + this.positionUp = new Phaser.Point(); + + /** + * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. + * The Circle size is 44px (Apples recommended "finger tip" size). + * @property {Phaser.Circle} circle + */ + this.circle = new Phaser.Circle(0, 0, 44); + + /** + * Click trampolines associated with this pointer. See `addClickTrampoline`. + * @property {object[]|null} _clickTrampolines + * @private + */ + this._clickTrampolines = null; + + /** + * When the Pointer has click trampolines the last target object is stored here + * so it can be used to check for validity of the trampoline in a post-Up/'stop'. + * @property {object} _trampolineTargetObject + * @private + */ + this._trampolineTargetObject = null; + +}; + +/** +* No buttons at all. +* @constant +* @type {number} +*/ +Phaser.Pointer.NO_BUTTON = 0; + +/** +* The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. +* @constant +* @type {number} +*/ +Phaser.Pointer.LEFT_BUTTON = 1; + +/** +* The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. +* @constant +* @type {number} +*/ +Phaser.Pointer.RIGHT_BUTTON = 2; + +/** +* The Middle Mouse button. +* @constant +* @type {number} +*/ +Phaser.Pointer.MIDDLE_BUTTON = 4; + +/** +* The X1 button. This is typically the mouse Back button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.BACK_BUTTON = 8; + +/** +* The X2 button. This is typically the mouse Forward button, but is often reconfigured. +* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. +* @constant +* @type {number} +*/ +Phaser.Pointer.FORWARD_BUTTON = 16; + +/** +* The Eraser pen button on PointerEvent supported devices only. +* @constant +* @type {number} +*/ +Phaser.Pointer.ERASER_BUTTON = 32; + +Phaser.Pointer.prototype = { + + /** + * Resets the states of all the button booleans. + * + * @method Phaser.Pointer#resetButtons + * @protected + */ + resetButtons: function () { + + this.isDown = false; + this.isUp = true; + + if (this.isMouse) + { + this.leftButton.reset(); + this.middleButton.reset(); + this.rightButton.reset(); + this.backButton.reset(); + this.forwardButton.reset(); + this.eraserButton.reset(); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsDown + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsDown: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.start(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.start(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.start(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.start(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.start(event); + } + + }, + + /** + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsUp + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUp: function (button, event) { + + // Note: These are bitwise checks, not booleans + + if (button === Phaser.Mouse.LEFT_BUTTON) + { + this.leftButton.stop(event); + } + + if (button === Phaser.Mouse.RIGHT_BUTTON) + { + this.rightButton.stop(event); + } + + if (button === Phaser.Mouse.MIDDLE_BUTTON) + { + this.middleButton.stop(event); + } + + if (button === Phaser.Mouse.BACK_BUTTON) + { + this.backButton.stop(event); + } + + if (button === Phaser.Mouse.FORWARD_BUTTON) + { + this.forwardButton.stop(event); + } + + }, + + /** + * Called by updateButtons. + * + * @method Phaser.Pointer#processButtonsUpDown + * @private + * @param {integer} buttons - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons MouseEvent#buttons} value. + * @param {MouseEvent} event - The DOM event. + */ + processButtonsUpDown: function (buttons, event) { + + var down = (event.type.toLowerCase().substr(-4) === 'down'); + var move = (event.type.toLowerCase().substr(-4) === 'move'); + + if (buttons !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && buttons === 1 && event.ctrlKey) + { + buttons = 2; + } + + // Note: These are bitwise checks, not booleans + this.leftButton.startStop(Phaser.Pointer.LEFT_BUTTON & buttons, event); + this.rightButton.startStop(Phaser.Pointer.RIGHT_BUTTON & buttons, event); + this.middleButton.startStop(Phaser.Pointer.MIDDLE_BUTTON & buttons, event); + this.backButton.startStop(Phaser.Pointer.BACK_BUTTON & buttons, event); + this.forwardButton.startStop(Phaser.Pointer.FORWARD_BUTTON & buttons, event); + this.eraserButton.startStop(Phaser.Pointer.ERASER_BUTTON & buttons, event); + } + else + { + // No buttons property (like Safari on OSX when using a trackpad) + // Attempt to use event.button property or fallback to default + if (event.button !== undefined) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (down && event.ctrlKey && event.button === 0) + { + this.rightButton.start(event); + } + else + { + if (down) + { + this.processButtonsDown(event.button, event); + } + else if (!move) + { + this.processButtonsUp(event.button, event); + } + } + } + else + { + if (down) + { + // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. + if (event.ctrlKey) + { + this.rightButton.start(event); + } + else + { + this.leftButton.start(event); + } + } + else + { + this.leftButton.stop(event); + this.rightButton.stop(event); + } + } + } + + }, + + /** + * Called when the event.buttons property changes from zero. + * Contains a button bitmask. + * + * @method Phaser.Pointer#updateButtons + * @protected + * @param {MouseEvent} event - The DOM event. + */ + updateButtons: function (event) { + + this.button = event.button; + this.processButtonsUpDown(event.buttons, event); + + this.isUp = true; + this.isDown = false; + + if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown) + { + this.isUp = false; + this.isDown = true; + } + + }, + + /** + * Called when the Pointer is pressed onto the touchscreen. + * @method Phaser.Pointer#start + * @param {any} event - The DOM event from the browser. + */ + start: function (event) { + + var input = this.game.input; + + if (event['pointerId']) + { + this.pointerId = event.pointerId; + } + + this.identifier = event.identifier; + this.target = event.target; + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = true; + this.isUp = false; + } + + this.active = true; + this.withinGame = true; + this.dirty = false; + + this._history = []; + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + // Work out how long it has been since the last click + this.msSinceLastClick = this.game.time.time - this.timeDown; + this.timeDown = this.game.time.time; + this._holdSent = false; + + // This sets the x/y and other local values + this.move(event, true); + + // x and y are the old values here? + this.positionDown.setTo(this.x, this.y); + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.x = this.x; + input.y = this.y; + input.position.setTo(this.x, this.y); + input.onDown.dispatch(this, event); + input.resetSpeed(this.x, this.y); + } + + this._stateReset = false; + + this.totalTouches++; + + if (this.targetObject !== null) + { + this.targetObject._touchedHandler(this); + } + + return this; + + }, + + /** + * Called by the Input Manager. + * @method Phaser.Pointer#update + */ + update: function () { + + var input = this.game.input; + + if (this.active) + { + // Force a check? + if (this.dirty) + { + if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(false); + } + + this.dirty = false; + } + + if (this._holdSent === false && this.duration >= input.holdRate) + { + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onHold.dispatch(this); + } + + this._holdSent = true; + } + + // Update the droppings history + if (input.recordPointerHistory && this.game.time.time >= this._nextDrop) + { + this._nextDrop = this.game.time.time + input.recordRate; + + this._history.push({ + x: this.position.x, + y: this.position.y + }); + + if (this._history.length > input.recordLimit) + { + this._history.shift(); + } + } + } + + }, + + /** + * Called when the Pointer is moved. + * + * @method Phaser.Pointer#move + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + * @param {boolean} [fromClick=false] - Was this called from the click event? + */ + move: function (event, fromClick) { + + var input = this.game.input; + + if (input.pollLocked) + { + return; + } + + if (fromClick === undefined) { fromClick = false; } + + if (event.button !== undefined) + { + this.button = event.button; + } + + if (this.isMouse) + { + this.updateButtons(event); + } + + 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 && 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.scale.offset.x) * input.scale.x; + this.y = (this.pageY - this.game.scale.offset.y) * input.scale.y; + + this.position.setTo(this.x, this.y); + this.circle.x = this.x; + this.circle.y = this.y; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.activePointer = this; + input.x = this.x; + input.y = this.y; + input.position.setTo(input.x, input.y); + input.circle.x = input.x; + input.circle.y = input.y; + } + + this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY); + + var i = input.moveCallbacks.length; + + while (i--) + { + input.moveCallbacks[i].callback.call(input.moveCallbacks[i].context, this, this.x, this.y, fromClick); + } + + // Easy out if we're dragging something and it still exists + if (this.targetObject !== null && (!this.game.paused || this.targetObject.noPause) && this.targetObject.isDragged === true) + { + if (this.targetObject.update(this) === false) + { + this.targetObject = null; + } + } + else if (input.interactiveItems.total > 0) + { + this.processInteractiveObjects(fromClick); + } + + return this; + + }, + + /** + * Process all interactive objects to find out which ones were updated in the recent Pointer move. + * + * @method Phaser.Pointer#processInteractiveObjects + * @protected + * @param {boolean} [fromClick=false] - Was this called from the click event? + * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. + */ + processInteractiveObjects: function (fromClick) { + + // Work out which object is on the top + var highestRenderOrderID = 0; + var highestInputPriorityID = -1; + var candidateTarget = null; + + // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID + // We know they'll be valid for input detection but not which is the top just yet + + var currentNode = this.game.input.interactiveItems.first; + + this.interactiveCandidates = []; + + while (currentNode) + { + // Reset checked status + currentNode.checked = false; + + if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false) && (!this.game.paused || currentNode.sprite.noPause)) + { + // Flag it as checked so we don't re-scan it on the next phase + currentNode.checked = true; + + if ((fromClick && currentNode.checkPointerDown(this, true)) || + (!fromClick && currentNode.checkPointerOver(this, true))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID + // because if their ID is lower anyway then we can just automatically discount them + // (A node that was previously checked did not request a pixel-perfect check.) + + currentNode = this.game.input.interactiveItems.first; + + while (currentNode) + { + if (!currentNode.checked && + currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true)) + { + if ((fromClick && currentNode.checkPointerDown(this, false)) || + (!fromClick && currentNode.checkPointerOver(this, false))) + { + highestRenderOrderID = currentNode.sprite.renderOrderID; + highestInputPriorityID = currentNode.priorityID; + candidateTarget = currentNode; + this.interactiveCandidates.push(currentNode); + } + } + + currentNode = this.game.input.interactiveItems.next; + } + + if (this.game.input.customCandidateHandler) + { + candidateTarget = this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext, this, this.interactiveCandidates, candidateTarget); + } + + this.swapTarget(candidateTarget, false); + + return (this.targetObject !== null); + + }, + + /** + * This will change the `Pointer.targetObject` object to be the one provided. + * + * This allows you to have fine-grained control over which object the Pointer is targeting. + * + * Note that even if you set a new Target here, it is still able to be replaced by any other valid + * target during the next Pointer update. + * + * @method Phaser.Pointer#swapTarget + * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. + * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. + */ + swapTarget: function (newTarget, silent) { + + if (silent === undefined) { silent = false; } + + // Now we know the top-most item (if any) we can process it + if (newTarget === null) + { + // The pointer isn't currently over anything, check if we've got a lingering previous target + if (this.targetObject) + { + this.targetObject._pointerOutHandler(this, silent); + this.targetObject = null; + } + } + else + { + if (this.targetObject === null) + { + // And now set the new one + this.targetObject = newTarget; + newTarget._pointerOverHandler(this, silent); + } + else + { + // We've got a target from the last update + if (this.targetObject === newTarget) + { + // Same target as before, so update it + if (newTarget.update(this) === false) + { + this.targetObject = null; + } + } + else + { + // The target has changed, so tell the old one we've left it + this.targetObject._pointerOutHandler(this, silent); + + // And now set the new one + this.targetObject = newTarget; + this.targetObject._pointerOverHandler(this, silent); + } + } + } + + }, + + /** + * Called when the Pointer leaves the target area. + * + * @method Phaser.Pointer#leave + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + leave: function (event) { + + this.withinGame = false; + this.move(event, false); + + }, + + /** + * Called when the Pointer leaves the touchscreen. + * + * @method Phaser.Pointer#stop + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ + stop: function (event) { + + var input = this.game.input; + + if (this._stateReset && this.withinGame) + { + event.preventDefault(); + return; + } + + this.timeUp = this.game.time.time; + + if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || + input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || + (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0)) + { + input.onUp.dispatch(this, event); + + // Was it a tap? + if (this.duration >= 0 && this.duration <= input.tapRate) + { + // Was it a double-tap? + if (this.timeUp - this.previousTapTime < input.doubleTapRate) + { + // Yes, let's dispatch the signal then with the 2nd parameter set to true + input.onTap.dispatch(this, true); + } + else + { + // Wasn't a double-tap, so dispatch a single tap signal + input.onTap.dispatch(this, false); + } + + this.previousTapTime = this.timeUp; + } + } + + if (this.isMouse) + { + this.updateButtons(event); + } + else + { + this.isDown = false; + this.isUp = true; + } + + // Mouse is always active + if (this.id > 0) + { + this.active = false; + } + + this.withinGame = this.game.scale.bounds.contains(event.pageX, event.pageY); + this.pointerId = null; + this.identifier = null; + + this.positionUp.setTo(this.x, this.y); + + if (this.isMouse === false) + { + input.currentPointers--; + } + + input.interactiveItems.callAll('_releasedHandler', this); + + if (this._clickTrampolines) + { + this._trampolineTargetObject = this.targetObject; + } + + this.targetObject = null; + + return this; + + }, + + /** + * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. + * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. + * @method Phaser.Pointer#justPressed + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate. + * @return {boolean} true if the Pointer was pressed down within the duration given. + */ + justPressed: function (duration) { + + duration = duration || this.game.input.justPressedRate; + + return (this.isDown === true && (this.timeDown + duration) > this.game.time.time); + + }, + + /** + * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. + * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. + * @method Phaser.Pointer#justReleased + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate. + * @return {boolean} true if the Pointer was released within the duration given. + */ + justReleased: function (duration) { + + duration = duration || this.game.input.justReleasedRate; + + return (this.isUp && (this.timeUp + duration) > this.game.time.time); + + }, + + /** + * Add a click trampoline to this pointer. + * + * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily + * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen + * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. + * + * This is used internally by the ScaleManager; click trampoline usage is uncommon. + * Click trampolines can only be added to pointers that are currently down. + * + * @method Phaser.Pointer#addClickTrampoline + * @protected + * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer. + * @param {function} callback - Callback to run/trampoline. + * @param {object} callbackContext - Context of the callback. + * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array. + */ + addClickTrampoline: function (name, callback, callbackContext, callbackArgs) { + + if (!this.isDown) + { + return; + } + + var trampolines = (this._clickTrampolines = this._clickTrampolines || []); + + for (var i = 0; i < trampolines.length; i++) + { + if (trampolines[i].name === name) + { + trampolines.splice(i, 1); + break; + } + } + + trampolines.push({ + name: name, + targetObject: this.targetObject, + callback: callback, + callbackContext: callbackContext, + callbackArgs: callbackArgs + }); + + }, + + /** + * Fire all click trampolines for which the pointers are still referring to the registered object. + * @method Phaser.Pointer#processClickTrampolines + * @private + */ + processClickTrampolines: function () { + + var trampolines = this._clickTrampolines; + + if (!trampolines) + { + return; + } + + for (var i = 0; i < trampolines.length; i++) + { + var trampoline = trampolines[i]; + + if (trampoline.targetObject === this._trampolineTargetObject) + { + trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs); + } + } + + this._clickTrampolines = null; + this._trampolineTargetObject = null; + + }, + + /** + * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. + * @method Phaser.Pointer#reset + */ + reset: function () { + + if (this.isMouse === false) + { + this.active = false; + } + + this.pointerId = null; + this.identifier = null; + this.dirty = false; + this.totalTouches = 0; + this._holdSent = false; + this._history.length = 0; + this._stateReset = true; + + this.resetButtons(); + + if (this.targetObject) + { + this.targetObject._releasedHandler(this); + } + + this.targetObject = null; + + }, + + /** + * Resets the movementX and movementY properties. Use in your update handler after retrieving the values. + * @method Phaser.Pointer#resetMovement + */ + resetMovement: function() { + + this.movementX = 0; + this.movementY = 0; + + } + +}; + +Phaser.Pointer.prototype.constructor = Phaser.Pointer; + +/** +* How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. +* If not currently down it returns -1. +* If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. +* +* @name Phaser.Pointer#duration +* @property {number} duration +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "duration", { + + get: function () { + + if (this.isUp) + { + return -1; + } + + return this.game.time.time - this.timeDown; + + } + +}); + +/** +* Gets the X value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldX +* @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldX", { + + get: function () { + + return this.game.world.camera.x + this.x; + + } + +}); + +/** +* Gets the Y value of this Pointer in world coordinates based on the world camera. +* @name Phaser.Pointer#worldY +* @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera. +* @readonly +*/ +Object.defineProperty(Phaser.Pointer.prototype, "worldY", { + + get: function () { + + return this.game.world.camera.y + this.y; + + } + +}); + +/** +* Enumeration categorizing operational modes of pointers. +* +* PointerType values represent valid bitmasks. +* For example, a value representing both Mouse and Touch devices +* can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. +* +* Values may be added for future mode categorizations. +* @class Phaser.PointerMode +*/ +Phaser.PointerMode = { + + /** + * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. + * + * It has the property that a cursor is passively moved without activating the input. + * This currently corresponds with {@link Phaser.Pointer#isMouse} property. + * @constant + */ + CURSOR: 1 << 0, + + /** + * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. + * @constant + */ + CONTACT: 1 << 1 + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. +* +* You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. +* +* @class Phaser.Touch +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Touch = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * Touch events will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} callbackContext - The context under which callbacks are called. + */ + this.callbackContext = this.game; + + /** + * @property {function} touchStartCallback - A callback that can be fired on a touchStart event. + */ + this.touchStartCallback = null; + + /** + * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event. + */ + this.touchMoveCallback = null; + + /** + * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event. + */ + this.touchEndCallback = null; + + /** + * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event. + */ + this.touchEnterCallback = null; + + /** + * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event. + */ + this.touchLeaveCallback = null; + + /** + * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event. + */ + this.touchCancelCallback = null; + + /** + * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it. + * @default + */ + this.preventDefault = true; + + /** + * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received. + * @default + */ + this.event = null; + + /** + * @property {function} _onTouchStart - Internal event handler reference. + * @private + */ + this._onTouchStart = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + + /** + * @property {function} _onTouchEnd - Internal event handler reference. + * @private + */ + this._onTouchEnd = null; + + /** + * @property {function} _onTouchEnter - Internal event handler reference. + * @private + */ + this._onTouchEnter = null; + + /** + * @property {function} _onTouchLeave - Internal event handler reference. + * @private + */ + this._onTouchLeave = null; + + /** + * @property {function} _onTouchCancel - Internal event handler reference. + * @private + */ + this._onTouchCancel = null; + + /** + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ + this._onTouchMove = null; + +}; + +Phaser.Touch.prototype = { + + /** + * Starts the event listeners running. + * @method Phaser.Touch#start + */ + start: function () { + + if (this._onTouchStart !== null) + { + // Avoid setting multiple listeners + 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('touchcancel', this._onTouchCancel, false); + + if (!this.game.device.cocoonJS) + { + this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false); + this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false); + } + } + + }, + + /** + * Consumes all touchmove events on the document (only enable this if you know you need it!). + * @method Phaser.Touch#consumeTouchMove + */ + consumeDocumentTouches: function () { + + this._documentTouchMove = function (event) { + event.preventDefault(); + }; + + document.addEventListener('touchmove', this._documentTouchMove, false); + + }, + + /** + * The internal method that handles the touchstart event from the browser. + * @method Phaser.Touch#onTouchStart + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchStart: function (event) { + + this.game.input.executeTouchLockCallbacks(false, event); + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.touchStartCallback) + { + this.touchStartCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.startPointer(event.changedTouches[i]); + } + + }, + + /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. + * @method Phaser.Touch#onTouchCancel + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchCancel: function (event) { + + this.event = event; + + if (this.touchCancelCallback) + { + this.touchCancelCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchEnter + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnter: function (event) { + + this.event = event; + + if (this.touchEnterCallback) + { + this.touchEnterCallback.call(this.callbackContext, event); + } + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchLeave + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchLeave: function (event) { + + this.event = event; + + if (this.touchLeaveCallback) + { + this.touchLeaveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + }, + + /** + * The handler for the touchmove events. + * @method Phaser.Touch#onTouchMove + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchMove: function (event) { + + this.event = event; + + if (this.touchMoveCallback) + { + this.touchMoveCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.updatePointer(event.changedTouches[i]); + } + + }, + + /** + * The handler for the touchend events. + * @method Phaser.Touch#onTouchEnd + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ + onTouchEnd: function (event) { + + this.game.input.executeTouchLockCallbacks(true, event); + + this.event = event; + + if (this.touchEndCallback) + { + this.touchEndCallback.call(this.callbackContext, event); + } + + if (this.preventDefault) + { + event.preventDefault(); + } + + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for (var i = 0; i < event.changedTouches.length; i++) + { + this.game.input.stopPointer(event.changedTouches[i]); + } + + }, + + /** + * Stop the event listeners. + * @method Phaser.Touch#stop + */ + stop: function () { + + if (this.game.device.touch) + { + this.game.canvas.removeEventListener('touchstart', this._onTouchStart); + this.game.canvas.removeEventListener('touchmove', this._onTouchMove); + this.game.canvas.removeEventListener('touchend', this._onTouchEnd); + this.game.canvas.removeEventListener('touchenter', this._onTouchEnter); + this.game.canvas.removeEventListener('touchleave', this._onTouchLeave); + this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel); + } + + } + +}; + +Phaser.Touch.prototype.constructor = Phaser.Touch; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. +* +* @class Phaser.InputHandler +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. +*/ +Phaser.InputHandler = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = sprite.game; + + /** + * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity. + * @default + */ + this.enabled = false; + + /** + * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks. + * @protected + */ + this.checked = false; + + /** + * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have + * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can + * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. + * @property {number} priorityID + * @default + */ + this.priorityID = 0; + + /** + * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. + * @default + */ + this.useHandCursor = false; + + /** + * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor? + * @private + */ + this._setHandCursor = false; + + /** + * @property {boolean} isDragged - true if the Sprite is being currently dragged. + * @default + */ + this.isDragged = false; + + /** + * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally. + * @default + */ + this.allowHorizontalDrag = true; + + /** + * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically. + * @default + */ + this.allowVerticalDrag = true; + + /** + * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. + * @default + */ + this.bringToTop = false; + + /** + * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset. + * @default + */ + this.snapOffset = null; + + /** + * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. + * @default + */ + this.snapOnDrag = false; + + /** + * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release. + * @default + */ + this.snapOnRelease = false; + + /** + * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid. + * @default + */ + this.snapX = 0; + + /** + * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid. + * @default + */ + this.snapY = 0; + + /** + * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid. + * @default + */ + this.snapOffsetX = 0; + + /** + * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid.. + * @default + */ + this.snapOffsetY = 0; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. + * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over. + * @default + */ + this.pixelPerfectOver = false; + + /** + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive so only enable if you really need it. + * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite. + * @default + */ + this.pixelPerfectClick = false; + + /** + * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. + * @default + */ + this.pixelPerfectAlpha = 255; + + /** + * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no + * @default + */ + this.draggable = false; + + /** + * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag. + * @default + */ + this.boundsRect = null; + + /** + * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. + * @default + */ + this.boundsSprite = null; + + /** + * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. + */ + this.scaleLayer = false; + + /** + * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from. + */ + this.dragOffset = new Phaser.Point(); + + /** + * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? + */ + this.dragFromCenter = false; + + /** + * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. + */ + this.dragStopBlocksInputUp = false; + + /** + * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. + */ + this.dragStartPoint = new Phaser.Point(); + + /** + * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. + */ + this.dragDistanceThreshold = 0; + + /** + * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. + */ + this.dragTimeThreshold = 0; + + /** + * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. + */ + this.downPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. + */ + this.snapPoint = new Phaser.Point(); + + /** + * @property {Phaser.Point} _dragPoint - Internal cache var. + * @private + */ + this._dragPoint = new Phaser.Point(); + + /** + * @property {boolean} _dragPhase - Internal cache var. + * @private + */ + this._dragPhase = false; + + /** + * @property {boolean} _pendingDrag - Internal cache var. + * @private + */ + this._pendingDrag = false; + + /** + * @property {boolean} _dragTimePass - Internal cache var. + * @private + */ + this._dragTimePass = false; + + /** + * @property {boolean} _dragDistancePass - Internal cache var. + * @private + */ + this._dragDistancePass = false; + + /** + * @property {boolean} _wasEnabled - Internal cache var. + * @private + */ + this._wasEnabled = false; + + /** + * @property {Phaser.Point} _tempPoint - Internal cache var. + * @private + */ + this._tempPoint = new Phaser.Point(); + + /** + * @property {array} _pointerData - Internal cache var. + * @private + */ + this._pointerData = []; + + this._pointerData.push({ + id: 0, + x: 0, + y: 0, + camX: 0, + camY: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }); + +}; + +Phaser.InputHandler.prototype = { + + /** + * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. + * + * @method Phaser.InputHandler#start + * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. + * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) + * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound. + */ + start: function (priority, useHandCursor) { + + priority = priority || 0; + if (useHandCursor === undefined) { useHandCursor = false; } + + // Turning on + if (this.enabled === false) + { + // Register, etc + this.game.input.interactiveItems.add(this); + this.useHandCursor = useHandCursor; + this.priorityID = priority; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + + this.snapOffset = new Phaser.Point(); + this.enabled = true; + this._wasEnabled = true; + + } + + this.sprite.events.onAddedToGroup.add(this.addedToGroup, this); + this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this); + + return this.sprite; + + }, + + /** + * Handles when the parent Sprite is added to a new Group. + * + * @method Phaser.InputHandler#addedToGroup + * @private + */ + addedToGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this._wasEnabled && !this.enabled) + { + this.start(); + } + + }, + + /** + * Handles when the parent Sprite is removed from a Group. + * + * @method Phaser.InputHandler#removedFromGroup + * @private + */ + removedFromGroup: function () { + + if (this._dragPhase) + { + return; + } + + if (this.enabled) + { + this._wasEnabled = true; + this.stop(); + } + else + { + this._wasEnabled = false; + } + + }, + + /** + * Resets the Input Handler and disables it. + * @method Phaser.InputHandler#reset + */ + reset: function () { + + this.enabled = false; + + for (var i = 0; i < 10; i++) + { + this._pointerData[i] = { + id: i, + x: 0, + y: 0, + isDown: false, + isUp: false, + isOver: false, + isOut: false, + timeOver: 0, + timeOut: 0, + timeDown: 0, + timeUp: 0, + downDuration: 0, + isDragged: false + }; + } + }, + + /** + * Stops the Input Handler from running. + * @method Phaser.InputHandler#stop + */ + stop: function () { + + // Turning off + if (this.enabled === false) + { + return; + } + else + { + // De-register, etc + this.enabled = false; + this.game.input.interactiveItems.remove(this); + } + + }, + + /** + * Clean up memory. + * @method Phaser.InputHandler#destroy + */ + destroy: function () { + + if (this.sprite) + { + if (this._setHandCursor) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + this.enabled = false; + + this.game.input.interactiveItems.remove(this); + + this._pointerData.length = 0; + this.boundsRect = null; + this.boundsSprite = null; + this.sprite = null; + } + + }, + + /** + * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. + * This is called by Phaser.Pointer and shouldn't typically be called directly. + * + * @method Phaser.InputHandler#validForInput + * @protected + * @param {number} highestID - The highest ID currently processed by the Pointer. + * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer. + * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? + * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection. + */ + validForInput: function (highestID, highestRenderID, includePixelPerfect) { + + if (includePixelPerfect === undefined) { includePixelPerfect = true; } + + if (!this.enabled || + this.sprite.scale.x === 0 || + this.sprite.scale.y === 0 || + this.priorityID < this.game.input.minPriorityID || + (this.sprite.parent && this.sprite.parent.ignoreChildInput)) + { + return false; + } + + // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it + if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver)) + { + return false; + } + + if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID > highestRenderID)) + { + return true; + } + + return false; + + }, + + /** + * Is this object using pixel perfect checking? + * + * @method Phaser.InputHandler#isPixelPerfect + * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. + */ + isPixelPerfect: function () { + + return (this.pixelPerfectClick || this.pixelPerfectOver); + + }, + + /** + * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerX + * @param {integer} [pointerId=0] + * @return {number} The x coordinate of the Input pointer. + */ + pointerX: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].x; + + }, + + /** + * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerY + * @param {integer} [pointerId=0] + * @return {number} The y coordinate of the Input pointer. + */ + pointerY: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].y; + + }, + + /** + * If the Pointer is down this returns true. + * This *only* checks if the Pointer is down, not if it's down over any specific Sprite. + * + * @method Phaser.InputHandler#pointerDown + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is down, otherwise false. + */ + pointerDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDown; + + }, + + /** + * If the Pointer is up this returns true. + * This *only* checks if the Pointer is up, not if it's up over any specific Sprite. + * + * @method Phaser.InputHandler#pointerUp + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is up, otherwise false. + */ + pointerUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isUp; + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeDown + * @param {integer} [pointerId=(check all)] + * @return {number} + */ + pointerTimeDown: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeDown; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeUp + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeUp: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeUp; + + }, + + /** + * Is the Pointer over this Sprite? + * + * @method Phaser.InputHandler#pointerOver + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object. + */ + pointerOver: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOver) + { + return true; + } + } + + return false; + } + else + { + return this._pointerData[pointerId].isOver; + } + + }, + + /** + * Is the Pointer outside of this Sprite? + * + * @method Phaser.InputHandler#pointerOut + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. + */ + pointerOut: function (pointerId) { + + if (!this.enabled) + { + return false; + } + + if (pointerId === undefined) + { + for (var i = 0; i < 10; i++) + { + if (this._pointerData[i].isOut) + { + return true; + } + } + } + else + { + return this._pointerData[pointerId].isOut; + } + + }, + + /** + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOver + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOver: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOver; + + }, + + /** + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOut + * @param {integer} [pointerId=0] + * @return {number} + */ + pointerTimeOut: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].timeOut; + + }, + + /** + * Is this sprite being dragged by the mouse or not? + * + * @method Phaser.InputHandler#pointerDragged + * @param {integer} [pointerId=0] + * @return {boolean} True if the pointer is dragging an object, otherwise false. + */ + pointerDragged: function (pointerId) { + + pointerId = pointerId || 0; + + return this._pointerData[pointerId].isDragged; + + }, + + /** + * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerDown + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} True if the pointer is down, otherwise false. + */ + checkPointerDown: function (pointer, fastTest) { + + if (!pointer.isDown || + !this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectClick) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Checks if the given pointer is over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerOver + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} + */ + checkPointerOver: function (pointer, fastTest) { + + if (!this.enabled || + !this.sprite || + !this.sprite.parent || + !this.sprite.visible || + !this.sprite.parent.visible || + this.sprite.worldScale.x === 0 || + this.sprite.worldScale.y === 0) + { + return false; + } + + // Need to pass it a temp point, in case we need it again for the pixel check + if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint)) + { + if (fastTest === undefined) + { + fastTest = false; + } + + if (!fastTest && this.pixelPerfectOver) + { + return this.checkPixel(this._tempPoint.x, this._tempPoint.y); + } + else + { + return true; + } + } + + return false; + + }, + + /** + * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. + * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. + * + * @method Phaser.InputHandler#checkPixel + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters. + * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha + */ + checkPixel: function (x, y, pointer) { + + // Grab a pixel from our image into the hitCanvas and then test it + if (this.sprite.texture.baseTexture.source) + { + if (x === null && y === null) + { + // Use the pointer parameter + this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint); + + var x = this._tempPoint.x; + var y = this._tempPoint.y; + } + + if (this.sprite.anchor.x !== 0) + { + x -= -this.sprite.texture.frame.width * this.sprite.anchor.x; + } + + if (this.sprite.anchor.y !== 0) + { + y -= -this.sprite.texture.frame.height * this.sprite.anchor.y; + } + + x += this.sprite.texture.frame.x; + y += this.sprite.texture.frame.y; + + if (this.sprite.texture.trim) + { + x -= this.sprite.texture.trim.x; + y -= this.sprite.texture.trim.y; + + // If the coordinates are outside the trim area we return false immediately, to save doing a draw call + if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom) + { + this._dx = x; + this._dy = y; + return false; + } + } + + this._dx = x; + this._dy = y; + + this.game.input.hitContext.clearRect(0, 0, 1, 1); + this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1); + + var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1); + + if (rgb.data[3] >= this.pixelPerfectAlpha) + { + return true; + } + } + + return false; + + }, + + /** + * Internal Update method. This is called automatically and handles the Pointer + * and drag update loops. + * + * @method Phaser.InputHandler#update + * @protected + * @param {Phaser.Pointer} pointer + * @return {boolean} True if the pointer is still active, otherwise false. + */ + update: function (pointer) { + + if (this.sprite === null || this.sprite.parent === undefined) + { + // Abort. We've been destroyed. + return; + } + + if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible) + { + this._pointerOutHandler(pointer); + return false; + } + + if (this._pendingDrag) + { + if (!this._dragDistancePass) + { + this._dragDistancePass = (Phaser.Math.distance(pointer.x, pointer.y, this.downPoint.x, this.downPoint.y) >= this.dragDistanceThreshold); + } + + if (this._dragDistancePass && this._dragTimePass) + { + this.startDrag(pointer); + } + + return true; + } + else if (this.draggable && this._draggedPointerID === pointer.id) + { + return this.updateDrag(pointer, false); + } + else if (this._pointerData[pointer.id].isOver) + { + 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; + } + } + }, + + /** + * Internal method handling the pointer over event. + * + * @method Phaser.InputHandler#_pointerOverHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOverHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (data.isOver === false || pointer.dirty) + { + var sendEvent = (data.isOver === false); + + data.isOver = true; + data.isOut = false; + data.timeOver = this.game.time.time; + data.x = pointer.x - this.sprite.x; + data.y = pointer.y - this.sprite.y; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = "pointer"; + this._setHandCursor = true; + } + + if (!silent && sendEvent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOver$dispatch(this.sprite, pointer); + } + + if (this.sprite.parent && this.sprite.parent.onChildInputOver) + { + this.sprite.parent.onChildInputOver.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the pointer out event. + * + * @method Phaser.InputHandler#_pointerOutHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ + _pointerOutHandler: function (pointer, silent) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + data.isOver = false; + data.isOut = true; + data.timeOut = this.game.time.time; + + if (this.useHandCursor && data.isDragged === false) + { + this.game.canvas.style.cursor = ""; + this._setHandCursor = false; + } + + if (!silent && this.sprite && this.sprite.events) + { + this.sprite.events.onInputOut$dispatch(this.sprite, pointer); + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputOut) + { + this.sprite.parent.onChildInputOut.dispatch(this.sprite, pointer); + } + } + + }, + + /** + * Internal method handling the touched / clicked event. + * + * @method Phaser.InputHandler#_touchedHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + */ + _touchedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + if (!data.isDown && data.isOver) + { + if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer)) + { + return; + } + + data.isDown = true; + data.isUp = false; + data.timeDown = this.game.time.time; + + this.downPoint.set(pointer.x, pointer.y); + + // It's possible the onInputDown event creates a new Sprite that is on-top of this one, so we ought to force a Pointer update + pointer.dirty = true; + + if (this.sprite && this.sprite.events) + { + this.sprite.events.onInputDown$dispatch(this.sprite, pointer); + + // The event above might have destroyed this sprite. + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputDown) + { + this.sprite.parent.onChildInputDown.dispatch(this.sprite, pointer); + } + + // The events might have destroyed this sprite. + if (this.sprite === null) + { + return; + } + } + + // Start drag + if (this.draggable && this.isDragged === false) + { + if (this.dragTimeThreshold === 0 && this.dragDistanceThreshold === 0) + { + this.startDrag(pointer); + } + else + { + this._pendingDrag = true; + + this._dragDistancePass = (this.dragDistanceThreshold === 0); + + if (this.dragTimeThreshold > 0) + { + this._dragTimePass = false; + this.game.time.events.add(this.dragTimeThreshold, this.dragTimeElapsed, this, pointer); + } + else + { + this._dragTimePass = true; + } + } + } + + if (this.bringToTop) + { + this.sprite.bringToTop(); + } + } + + }, + + /** + * Internal method handling the drag threshold timer. + * + * @method Phaser.InputHandler#dragTimeElapsed + * @private + * @param {Phaser.Pointer} pointer + */ + dragTimeElapsed: function (pointer) { + + this._dragTimePass = true; + + if (this._pendingDrag && this.sprite) + { + if (this._dragDistancePass) + { + this.startDrag(pointer); + } + } + + }, + + /** + * Internal method handling the pointer released event. + * @method Phaser.InputHandler#_releasedHandler + * @private + * @param {Phaser.Pointer} pointer + */ + _releasedHandler: function (pointer) { + + if (this.sprite === null) + { + // Abort. We've been destroyed. + return; + } + + var data = this._pointerData[pointer.id]; + + // If was previously touched by this Pointer, check if still is AND still over this item + if (data.isDown && pointer.isUp) + { + data.isDown = false; + data.isUp = true; + data.timeUp = this.game.time.time; + data.downDuration = data.timeUp - data.timeDown; + + // Only release the InputUp signal if the pointer is still over this sprite + var isOver = this.checkPointerOver(pointer); + + if (this.sprite && this.sprite.events) + { + if (!this.dragStopBlocksInputUp || + this.dragStopBlocksInputUp && !(this.draggable && this.isDragged && this._draggedPointerID === pointer.id)) + { + this.sprite.events.onInputUp$dispatch(this.sprite, pointer, isOver); + } + + if (this.sprite && this.sprite.parent && this.sprite.parent.onChildInputUp) + { + this.sprite.parent.onChildInputUp.dispatch(this.sprite, pointer, isOver); + } + + // The onInputUp event may have changed the sprite so that checkPointerOver is no longer true, so update it. + if (isOver) + { + isOver = this.checkPointerOver(pointer); + } + } + + data.isOver = isOver; + + if (!isOver && this.useHandCursor) + { + this.game.canvas.style.cursor = "default"; + this._setHandCursor = false; + } + + // It's possible the onInputUp event created a new Sprite that is on-top of this one, so force a Pointer update + pointer.dirty = true; + + this._pendingDrag = false; + + // Stop drag + if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id) + { + this.stopDrag(pointer); + } + } + + }, + + /** + * Called as a Pointer actively drags this Game Object. + * + * @method Phaser.InputHandler#updateDrag + * @private + * @param {Phaser.Pointer} pointer - The Pointer causing the drag update. + * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started. + * @return {boolean} + */ + updateDrag: function (pointer, fromStart) { + + if (fromStart === undefined) { fromStart = false; } + + if (pointer.isUp) + { + this.stopDrag(pointer); + return false; + } + + var pointerLocalCoord = this.globalToLocal(pointer); + + if (this.sprite.fixedToCamera) + { + var px = this.game.camera.scale.x * pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = this.game.camera.scale.y * pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + else + { + var px = pointerLocalCoord.x + this._dragPoint.x + this.dragOffset.x; + var py = pointerLocalCoord.y + this._dragPoint.y + this.dragOffset.y; + } + + if (this.sprite.fixedToCamera) + { + if (this.allowHorizontalDrag) + { + this.sprite.cameraOffset.x = px - this.game.camera.x; + } + + if (this.allowVerticalDrag) + { + this.sprite.cameraOffset.y = py - this.game.camera.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); + this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y); + } + } + else + { + var cx = this.game.camera.x - this._pointerData[pointer.id].camX; + var cy = this.game.camera.y - this._pointerData[pointer.id].camY; + + if (this.allowHorizontalDrag) + { + this.sprite.x = px + cx; + } + + if (this.allowVerticalDrag) + { + this.sprite.y = py + cy; + } + + 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); + this.snapPoint.set(this.sprite.x, this.sprite.y); + } + } + + this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint, fromStart); + + return true; + + }, + + /** + * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOver + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justOver: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOut + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justOut: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay)); + + }, + + /** + * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justPressed + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ + justPressed: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay); + + }, + + /** + * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justReleased + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ + justReleased: function (pointerId, delay) { + + pointerId = pointerId || 0; + delay = delay || 500; + + return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay)); + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#overDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. + */ + overDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isOver) + { + return this.game.time.time - this._pointerData[pointerId].timeOver; + } + + return -1; + + }, + + /** + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#downDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. + */ + downDuration: function (pointerId) { + + pointerId = pointerId || 0; + + if (this._pointerData[pointerId].isDown) + { + return this.game.time.time - this._pointerData[pointerId].timeDown; + } + + return -1; + + }, + + /** + * Allow this Sprite to be dragged by any valid pointer. + * + * When the drag begins the Sprite.events.onDragStart event will be dispatched. + * + * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. + * + * You can control the thresholds over when a drag starts via the properties: + * + * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move + * before the drag will start. + * + * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on + * the Sprite before the drag will start. + * + * You can set either (or both) of these properties after enabling a Sprite for drag. + * + * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually + * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`. + * + * @method Phaser.InputHandler#enableDrag + * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. + * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group. + * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. + * @param {integer} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. + * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. + * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. + */ + enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) { + + if (lockCenter === undefined) { lockCenter = false; } + if (bringToTop === undefined) { bringToTop = false; } + if (pixelPerfect === undefined) { pixelPerfect = false; } + if (alphaThreshold === undefined) { alphaThreshold = 255; } + if (boundsRect === undefined) { boundsRect = null; } + if (boundsSprite === undefined) { boundsSprite = null; } + + this._dragPoint = new Phaser.Point(); + this.draggable = true; + this.bringToTop = bringToTop; + this.dragOffset = new Phaser.Point(); + this.dragFromCenter = lockCenter; + + this.pixelPerfectClick = pixelPerfect; + this.pixelPerfectAlpha = alphaThreshold; + + if (boundsRect) + { + this.boundsRect = boundsRect; + } + + if (boundsSprite) + { + this.boundsSprite = boundsSprite; + } + + }, + + /** + * Stops this sprite from being able to be dragged. + * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. + * + * @method Phaser.InputHandler#disableDrag + */ + disableDrag: function () { + + if (this._pointerData) + { + for (var i = 0; i < 10; i++) + { + this._pointerData[i].isDragged = false; + } + } + + this.draggable = false; + this.isDragged = false; + this._draggedPointerID = -1; + this._pendingDrag = false; + + }, + + /** + * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#startDrag + * @param {Phaser.Pointer} pointer + */ + startDrag: function (pointer) { + + var x = this.sprite.x; + var y = this.sprite.y; + var pointerLocalCoord = this.globalToLocal(pointer); + + this.isDragged = true; + this._draggedPointerID = pointer.id; + + this._pointerData[pointer.id].camX = this.game.camera.x; + this._pointerData[pointer.id].camY = this.game.camera.y; + + this._pointerData[pointer.id].isDragged = true; + + if (this.sprite.fixedToCamera) + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.cameraOffset.x = pointerLocalCoord.x + (this.sprite.cameraOffset.x - boundsCenterLocalCoord.x); + this.sprite.cameraOffset.y = pointerLocalCoord.y + (this.sprite.cameraOffset.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y); + } + else + { + if (this.dragFromCenter) + { + var bounds = this.sprite.getBounds(); + var boundsCenterLocalCoord = this.globalToLocal(new Phaser.Point(bounds.centerX, bounds.centerY)); + + this.sprite.x = pointerLocalCoord.x + (this.sprite.x - boundsCenterLocalCoord.x); + this.sprite.y = pointerLocalCoord.y + (this.sprite.y - boundsCenterLocalCoord.y); + } + + this._dragPoint.setTo(this.sprite.x - pointerLocalCoord.x, this.sprite.y - pointerLocalCoord.y); + } + + this.updateDrag(pointer, true); + + if (this.bringToTop) + { + this._dragPhase = true; + this.sprite.bringToTop(); + } + + this.dragStartPoint.set(x, y); + + this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y); + + this._pendingDrag = false; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalX + * @param {number} x + */ + globalToLocalX: function (x) { + + if (this.scaleLayer) + { + x -= this.game.scale.grid.boundsFluid.x; + x *= this.game.scale.grid.scaleFluidInversed.x; + } + + return x; + + }, + + /** + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalY + * @param {number} y + */ + globalToLocalY: function (y) { + + if (this.scaleLayer) + { + y -= this.game.scale.grid.boundsFluid.y; + y *= this.game.scale.grid.scaleFluidInversed.y; + } + + return y; + + }, + + /** + * Convert global coordinates to local sprite coordinates + * + * @method Phaser.InputHandler#globalToLocal + * @param {Phaser.Point} globalCoord - The global coordinates to convert. + * @return {Phaser.Point} A point containing the local coordinates. + */ + globalToLocal: function (globalCoord) { + + if (this.sprite.parent) + { + return this.game.input.getLocalPosition(this.sprite.parent, {x: globalCoord.x, y: globalCoord.y}); + } + else + { + return globalCoord; + } + + }, + + /** + * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#stopDrag + * @param {Phaser.Pointer} pointer + */ + stopDrag: function (pointer) { + + this.isDragged = false; + this._draggedPointerID = -1; + this._pointerData[pointer.id].isDragged = false; + this._dragPhase = false; + this._pendingDrag = false; + + if (this.snapOnRelease) + { + if (this.sprite.fixedToCamera) + { + 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 + { + 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); + } + } + + this.sprite.events.onDragStop$dispatch(this.sprite, pointer); + + if (this.checkPointerOver(pointer) === false) + { + this._pointerOutHandler(pointer); + } + + }, + + /** + * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! + * + * @method Phaser.InputHandler#setDragLock + * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false. + * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false. + */ + setDragLock: function (allowHorizontal, allowVertical) { + + if (allowHorizontal === undefined) { allowHorizontal = true; } + if (allowVertical === undefined) { allowVertical = true; } + + this.allowHorizontalDrag = allowHorizontal; + this.allowVerticalDrag = allowVertical; + + }, + + /** + * Make this Sprite snap to the given grid either during drag or when it's released. + * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. + * + * @method Phaser.InputHandler#enableSnap + * @param {number} snapX - The width of the grid cell to snap to. + * @param {number} snapY - The height of the grid cell to snap to. + * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged. + * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released. + * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid. + * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid. + */ + enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) { + + if (onDrag === undefined) { onDrag = true; } + if (onRelease === undefined) { onRelease = false; } + if (snapOffsetX === undefined) { snapOffsetX = 0; } + if (snapOffsetY === undefined) { snapOffsetY = 0; } + + this.snapX = snapX; + this.snapY = snapY; + this.snapOffsetX = snapOffsetX; + this.snapOffsetY = snapOffsetY; + this.snapOnDrag = onDrag; + this.snapOnRelease = onRelease; + + }, + + /** + * Stops the sprite from snapping to a grid during drag or release. + * + * @method Phaser.InputHandler#disableSnap + */ + disableSnap: function () { + + this.snapOnDrag = false; + this.snapOnRelease = false; + + }, + + /** + * Bounds Rect check for the sprite drag + * + * @method Phaser.InputHandler#checkBoundsRect + */ + checkBoundsRect: function () { + + if (this.sprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsRect.left) + { + this.sprite.cameraOffset.x = this.boundsRect.left; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right) + { + this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsRect.top) + { + this.sprite.cameraOffset.y = this.boundsRect.top; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom) + { + this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsRect.left) + { + this.sprite.x = this.boundsRect.x + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsRect.right) + { + this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsRect.top) + { + this.sprite.y = this.boundsRect.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsRect.bottom) + { + this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + }, + + /** + * Parent Sprite Bounds check for the sprite drag. + * + * @method Phaser.InputHandler#checkBoundsSprite + */ + checkBoundsSprite: function () { + + if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera) + { + if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x) + { + this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x; + } + else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width)) + { + this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width; + } + + if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y) + { + this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y; + } + else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height)) + { + this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height; + } + } + else + { + if (this.sprite.left < this.boundsSprite.left) + { + this.sprite.x = this.boundsSprite.left + this.sprite.offsetX; + } + else if (this.sprite.right > this.boundsSprite.right) + { + this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX); + } + + if (this.sprite.top < this.boundsSprite.top) + { + this.sprite.y = this.boundsSprite.top + this.sprite.offsetY; + } + else if (this.sprite.bottom > this.boundsSprite.bottom) + { + this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY); + } + } + + } + +}; + +Phaser.InputHandler.prototype.constructor = Phaser.InputHandler; + +/** +* @author @karlmacklin +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Gamepad class handles gamepad input and dispatches gamepad events. +* +* Remember to call `gamepad.start()`. +* +* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! +* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it +* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. +* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. +* +* @class Phaser.Gamepad +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Gamepad = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads + * @private + */ + this._gamepadIndexMap = {}; + + /** + * @property {Array} _rawPads - The raw state of the gamepads from the browser + * @private + */ + this._rawPads = []; + + /** + * @property {boolean} _active - Private flag for whether or not the API is polled + * @private + * @default + */ + this._active = false; + + /** + * Gamepad input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation. + * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not? + * @private + */ + this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') !== -1) || !!navigator.getGamepads; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevRawGamepadTypes + * @private + * @default + */ + this._prevRawGamepadTypes = []; + + /** + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevTimestamps + * @private + * @default + */ + this._prevTimestamps = []; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._ongamepadconnected = null; + + /** + * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling + * @private + */ + this._gamepaddisconnected = null; + + /** + * @property {Array} _gamepads - The four Phaser Gamepads. + * @private + */ + this._gamepads = [ + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this), + new Phaser.SinglePad(game, this) + ]; + +}; + +Phaser.Gamepad.prototype = { + + /** + * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. + * + * @method Phaser.Gamepad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callback methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + this.callbackContext = context; + } + + }, + + /** + * Starts the Gamepad event handling. + * This MUST be called manually before Phaser will start polling the Gamepad API. + * + * @method Phaser.Gamepad#start + */ + start: function () { + + if (this._active) + { + // Avoid setting multiple listeners + return; + } + + this._active = true; + + var _this = this; + + this._onGamepadConnected = function (event) { + return _this.onGamepadConnected(event); + }; + + this._onGamepadDisconnected = function (event) { + return _this.onGamepadDisconnected(event); + }; + + window.addEventListener('gamepadconnected', this._onGamepadConnected, false); + window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false); + + }, + + /** + * Handles the connection of a Gamepad. + * + * @method onGamepadConnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadConnected: function (event) { + + var newPad = event.gamepad; + this._rawPads.push(newPad); + this._gamepads[newPad.index].connect(newPad); + + }, + + /** + * Handles the disconnection of a Gamepad. + * + * @method onGamepadDisconnected + * @private + * @param {object} event - The DOM event. + */ + onGamepadDisconnected: function (event) { + + var removedPad = event.gamepad; + + for (var i in this._rawPads) + { + if (this._rawPads[i].index === removedPad.index) + { + this._rawPads.splice(i,1); + } + } + + this._gamepads[removedPad.index].disconnect(); + + }, + + /** + * Main gamepad update loop. Should not be called manually. + * @method Phaser.Gamepad#update + * @protected + */ + update: function () { + + this._pollGamepads(); + + this.pad1.pollStatus(); + this.pad2.pollStatus(); + this.pad3.pollStatus(); + this.pad4.pollStatus(); + + }, + + /** + * Updating connected gamepads (for Google Chrome). Should not be called manually. + * + * @method Phaser.Gamepad#_pollGamepads + * @private + */ + _pollGamepads: function () { + + if (!this._active) + { + return; + } + + if (navigator['getGamepads']) + { + var rawGamepads = navigator.getGamepads(); + } + else if (navigator['webkitGetGamepads']) + { + var rawGamepads = navigator.webkitGetGamepads(); + } + else if (navigator['webkitGamepads']) + { + var rawGamepads = navigator.webkitGamepads(); + } + + if (rawGamepads) + { + this._rawPads = []; + + var gamepadsChanged = false; + + for (var i = 0; i < rawGamepads.length; i++) + { + if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i]) + { + gamepadsChanged = true; + this._prevRawGamepadTypes[i] = typeof rawGamepads[i]; + } + + if (rawGamepads[i]) + { + this._rawPads.push(rawGamepads[i]); + } + + // Support max 4 pads at the moment + if (i === 3) + { + break; + } + } + + for (var g = 0; g < this._gamepads.length; g++) + { + this._gamepads[g]._rawPad = this._rawPads[g]; + } + + if (gamepadsChanged) + { + var validConnections = { rawIndices: {}, padIndices: {} }; + var singlePad; + + for (var j = 0; j < this._gamepads.length; j++) + { + singlePad = this._gamepads[j]; + + if (singlePad.connected) + { + for (var k = 0; k < this._rawPads.length; k++) + { + if (this._rawPads[k].index === singlePad.index) + { + validConnections.rawIndices[singlePad.index] = true; + validConnections.padIndices[j] = true; + } + } + } + } + + for (var l = 0; l < this._gamepads.length; l++) + { + singlePad = this._gamepads[l]; + + if (validConnections.padIndices[l]) + { + continue; + } + + if (this._rawPads.length < 1) + { + singlePad.disconnect(); + } + + for (var m = 0; m < this._rawPads.length; m++) + { + if (validConnections.padIndices[l]) + { + break; + } + + var rawPad = this._rawPads[m]; + + if (rawPad) + { + if (validConnections.rawIndices[rawPad.index]) + { + singlePad.disconnect(); + continue; + } + else + { + singlePad.connect(rawPad); + validConnections.rawIndices[rawPad.index] = true; + validConnections.padIndices[l] = true; + } + } + else + { + singlePad.disconnect(); + } + } + } + } + } + }, + + /** + * Sets the deadZone variable for all four gamepads + * @method Phaser.Gamepad#setDeadZones + */ + setDeadZones: function (value) { + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].deadZone = value; + } + + }, + + /** + * Stops the Gamepad event handling. + * + * @method Phaser.Gamepad#stop + */ + stop: function () { + + this._active = false; + + window.removeEventListener('gamepadconnected', this._onGamepadConnected); + window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected); + + }, + + /** + * Reset all buttons/axes of all gamepads + * @method Phaser.Gamepad#reset + */ + reset: function () { + + this.update(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].reset(); + } + + }, + + /** + * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justPressed(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].justReleased(buttonCode, duration) === true) + { + return true; + } + } + + return false; + + }, + + /** + * Returns true if the button is currently pressed down, on ANY gamepad. + * @method Phaser.Gamepad#isDown + * @param {number} buttonCode - The buttonCode of the button to check for. + * @return {boolean} True if a button is currently down. + */ + isDown: function (buttonCode) { + + for (var i = 0; i < this._gamepads.length; i++) + { + if (this._gamepads[i].isDown(buttonCode) === true) + { + return true; + } + } + + return false; + }, + + /** + * Destroys this object and the associated event listeners. + * + * @method Phaser.Gamepad#destroy + */ + destroy: function () { + + this.stop(); + + for (var i = 0; i < this._gamepads.length; i++) + { + this._gamepads[i].destroy(); + } + + } + +}; + +Phaser.Gamepad.prototype.constructor = Phaser.Gamepad; + +/** +* If the gamepad input is active or not - if not active it should not be updated from Input.js +* @name Phaser.Gamepad#active +* @property {boolean} active - If the gamepad input is active or not. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "active", { + + get: function () { + return this._active; + } + +}); + +/** +* Whether or not gamepads are supported in current browser. +* @name Phaser.Gamepad#supported +* @property {boolean} supported - Whether or not gamepads are supported in current browser. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "supported", { + + get: function () { + return this._gamepadSupportAvailable; + } + +}); + +/** +* How many live gamepads are currently connected. +* @name Phaser.Gamepad#padsConnected +* @property {number} padsConnected - How many live gamepads are currently connected. +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", { + + get: function () { + return this._rawPads.length; + } + +}); + +/** +* Gamepad #1 +* @name Phaser.Gamepad#pad1 +* @property {Phaser.SinglePad} pad1 - Gamepad #1; +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad1", { + + get: function () { + return this._gamepads[0]; + } + +}); + +/** +* Gamepad #2 +* @name Phaser.Gamepad#pad2 +* @property {Phaser.SinglePad} pad2 - Gamepad #2 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad2", { + + get: function () { + return this._gamepads[1]; + } + +}); + +/** +* Gamepad #3 +* @name Phaser.Gamepad#pad3 +* @property {Phaser.SinglePad} pad3 - Gamepad #3 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad3", { + + get: function () { + return this._gamepads[2]; + } + +}); + +/** +* Gamepad #4 +* @name Phaser.Gamepad#pad4 +* @property {Phaser.SinglePad} pad4 - Gamepad #4 +* @readonly +*/ +Object.defineProperty(Phaser.Gamepad.prototype, "pad4", { + + get: function () { + return this._gamepads[3]; + } + +}); + +Phaser.Gamepad.BUTTON_0 = 0; +Phaser.Gamepad.BUTTON_1 = 1; +Phaser.Gamepad.BUTTON_2 = 2; +Phaser.Gamepad.BUTTON_3 = 3; +Phaser.Gamepad.BUTTON_4 = 4; +Phaser.Gamepad.BUTTON_5 = 5; +Phaser.Gamepad.BUTTON_6 = 6; +Phaser.Gamepad.BUTTON_7 = 7; +Phaser.Gamepad.BUTTON_8 = 8; +Phaser.Gamepad.BUTTON_9 = 9; +Phaser.Gamepad.BUTTON_10 = 10; +Phaser.Gamepad.BUTTON_11 = 11; +Phaser.Gamepad.BUTTON_12 = 12; +Phaser.Gamepad.BUTTON_13 = 13; +Phaser.Gamepad.BUTTON_14 = 14; +Phaser.Gamepad.BUTTON_15 = 15; + +Phaser.Gamepad.AXIS_0 = 0; +Phaser.Gamepad.AXIS_1 = 1; +Phaser.Gamepad.AXIS_2 = 2; +Phaser.Gamepad.AXIS_3 = 3; +Phaser.Gamepad.AXIS_4 = 4; +Phaser.Gamepad.AXIS_5 = 5; +Phaser.Gamepad.AXIS_6 = 6; +Phaser.Gamepad.AXIS_7 = 7; +Phaser.Gamepad.AXIS_8 = 8; +Phaser.Gamepad.AXIS_9 = 9; + +// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7). +// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button. +// In other words - discrepancies when using gamepads. + +Phaser.Gamepad.XBOX360_A = 0; +Phaser.Gamepad.XBOX360_B = 1; +Phaser.Gamepad.XBOX360_X = 2; +Phaser.Gamepad.XBOX360_Y = 3; +Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4; +Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5; +Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6; +Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7; +Phaser.Gamepad.XBOX360_BACK = 8; +Phaser.Gamepad.XBOX360_START = 9; +Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11; + +Phaser.Gamepad.XBOX360_DPAD_LEFT = 14; +Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15; +Phaser.Gamepad.XBOX360_DPAD_UP = 12; +Phaser.Gamepad.XBOX360_DPAD_DOWN = 13; + +// On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right +Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0; +Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1; +Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2; +Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3; + +// PlayStation 3 controller (masquerading as xbox360 controller) button mappings + +Phaser.Gamepad.PS3XC_X = 0; +Phaser.Gamepad.PS3XC_CIRCLE = 1; +Phaser.Gamepad.PS3XC_SQUARE = 2; +Phaser.Gamepad.PS3XC_TRIANGLE = 3; +Phaser.Gamepad.PS3XC_L1 = 4; +Phaser.Gamepad.PS3XC_R1 = 5; +Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1 +Phaser.Gamepad.PS3XC_SELECT = 8; +Phaser.Gamepad.PS3XC_START = 9; +Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10; +Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11; +Phaser.Gamepad.PS3XC_DPAD_UP = 12; +Phaser.Gamepad.PS3XC_DPAD_DOWN = 13; +Phaser.Gamepad.PS3XC_DPAD_LEFT = 14; +Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15; +Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1 +Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1 + +/** +* @author @karlmacklin +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A single Phaser Gamepad +* +* @class Phaser.SinglePad +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this) +*/ +Phaser.SinglePad = function (game, padParent) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {number} index - The gamepad index as per browsers data + * @readonly + */ + this.index = null; + + /** + * @property {boolean} connected - Whether or not this particular gamepad is connected or not. + * @readonly + */ + this.connected = false; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected + */ + this.onConnectCallback = null; + + /** + * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected + */ + this.onDisconnectCallback = null; + + /** + * @property {function} onDownCallback - This callback is invoked every time a button is pressed down. + */ + this.onDownCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released. + */ + this.onUpCallback = null; + + /** + * @property {function} onAxisCallback - This callback is invoked every time an axis is changed. + */ + this.onAxisCallback = null; + + /** + * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1. + */ + this.onFloatCallback = null; + + /** + * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates. + */ + this.deadZone = 0.26; + + /** + * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object + * @private + */ + this._padParent = padParent; + + /** + * @property {object} _rawPad - The 'raw' gamepad data. + * @private + */ + this._rawPad = null; + + /** + * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads. + * @private + */ + this._prevTimestamp = null; + + /** + * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected. + * @private + */ + this._buttons = []; + + /** + * @property {number} _buttonsLen - Length of the _buttons array. + * @private + */ + this._buttonsLen = 0; + + /** + * @property {Array} _axes - Current axes state. + * @private + */ + this._axes = []; + + /** + * @property {number} _axesLen - Length of the _axes array. + * @private + */ + this._axesLen = 0; + +}; + +Phaser.SinglePad.prototype = { + + /** + * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. + * + * @method Phaser.SinglePad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callbak methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ + addCallbacks: function (context, callbacks) { + + if (typeof callbacks !== 'undefined') + { + this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; + this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback; + this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback; + this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback; + this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback; + this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; + + this.callbackContext = context; + } + }, + + /** + * Gets a DeviceButton object from this controller to be stored and referenced locally. + * The DeviceButton object can then be polled, have events attached to it, etc. + * + * @method Phaser.SinglePad#getButton + * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc. + * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly. + */ + getButton: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode]; + } + else + { + return null; + } + + }, + + /** + * Main update function called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#pollStatus + */ + pollStatus: function () { + + if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp))) + { + return; + } + + for (var i = 0; i < this._buttonsLen; i++) + { + var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i]; + + if (rawButtonVal !== this._buttons[i].value) + { + if (rawButtonVal === 1) + { + this.processButtonDown(i, rawButtonVal); + } + else if (rawButtonVal === 0) + { + this.processButtonUp(i, rawButtonVal); + } + else + { + this.processButtonFloat(i, rawButtonVal); + } + } + } + + for (var index = 0; index < this._axesLen; index++) + { + var value = this._rawPad.axes[index]; + + if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone)) + { + this.processAxisChange(index, value); + } + else + { + this.processAxisChange(index, 0); + } + } + + this._prevTimestamp = this._rawPad.timestamp; + + }, + + /** + * Gamepad connect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#connect + * @param {object} rawPad - The raw gamepad object + */ + connect: function (rawPad) { + + var triggerCallback = !this.connected; + + this.connected = true; + this.index = rawPad.index; + + this._rawPad = rawPad; + + this._buttons = []; + this._buttonsLen = rawPad.buttons.length; + + this._axes = []; + this._axesLen = rawPad.axes.length; + + for (var a = 0; a < this._axesLen; a++) + { + this._axes[a] = rawPad.axes[a]; + } + + for (var buttonCode in rawPad.buttons) + { + buttonCode = parseInt(buttonCode, 10); + this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode); + } + + if (triggerCallback && this._padParent.onConnectCallback) + { + this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index); + } + + if (triggerCallback && this.onConnectCallback) + { + this.onConnectCallback.call(this.callbackContext); + } + + }, + + /** + * Gamepad disconnect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#disconnect + */ + disconnect: function () { + + var triggerCallback = this.connected; + var disconnectingIndex = this.index; + + this.connected = false; + this.index = null; + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + if (triggerCallback && this._padParent.onDisconnectCallback) + { + this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex); + } + + if (triggerCallback && this.onDisconnectCallback) + { + this.onDisconnectCallback.call(this.callbackContext); + } + + }, + + /** + * Destroys this object and associated callback references. + * + * @method Phaser.SinglePad#destroy + */ + destroy: function () { + + this._rawPad = undefined; + + for (var i = 0; i < this._buttonsLen; i++) + { + this._buttons[i].destroy(); + } + + this._buttons = []; + this._buttonsLen = 0; + + this._axes = []; + this._axesLen = 0; + + this.onConnectCallback = null; + this.onDisconnectCallback = null; + this.onDownCallback = null; + this.onUpCallback = null; + this.onAxisCallback = null; + this.onFloatCallback = null; + + }, + + /** + * Handles changes in axis. + * + * @method Phaser.SinglePad#processAxisChange + * @param {object} axisState - State of the relevant axis + */ + processAxisChange: function (index, value) { + + if (this._axes[index] === value) + { + return; + } + + this._axes[index] = value; + + if (this._padParent.onAxisCallback) + { + this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value); + } + + if (this.onAxisCallback) + { + this.onAxisCallback.call(this.callbackContext, this, index, value); + } + + }, + + /** + * Handles button down press. + * + * @method Phaser.SinglePad#processButtonDown + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonDown: function (buttonCode, value) { + + if (this._buttons[buttonCode]) + { + this._buttons[buttonCode].start(null, value); + } + + 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); + } + + }, + + /** + * Handles button release. + * + * @method Phaser.SinglePad#processButtonUp + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ + processButtonUp: function (buttonCode, value) { + + 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._buttons[buttonCode]) + { + this._buttons[buttonCode].stop(null, value); + } + + }, + + /** + * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) + * + * @method Phaser.SinglePad#processButtonFloat + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. + */ + processButtonFloat: function (buttonCode, value) { + + 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].padFloat(value); + } + + }, + + /** + * Returns value of requested axis. + * + * @method Phaser.SinglePad#axis + * @param {number} axisCode - The index of the axis to check + * @return {number} Axis value if available otherwise false + */ + axis: function (axisCode) { + + if (this._axes[axisCode]) + { + return this._axes[axisCode]; + } + + return false; + + }, + + /** + * Returns true if the button is pressed down. + * + * @method Phaser.SinglePad#isDown + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is pressed down. + */ + isDown: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isDown; + } + + return false; + + }, + + /** + * Returns true if the button is not currently pressed. + * + * @method Phaser.SinglePad#isUp + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is not currently pressed down. + */ + isUp: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].isUp; + } + + return false; + + }, + + /** + * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justReleased + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ + justReleased: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justReleased(duration); + } + + }, + + /** + * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ + justPressed: function (buttonCode, duration) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].justPressed(duration); + } + + }, + + /** + * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example + * analog trigger buttons on the XBOX 360 controller. + * + * @method Phaser.SinglePad#buttonValue + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. + */ + buttonValue: function (buttonCode) { + + if (this._buttons[buttonCode]) + { + return this._buttons[buttonCode].value; + } + + return null; + + }, + + /** + * Reset all buttons/axes of this gamepad. + * + * @method Phaser.SinglePad#reset + */ + reset: function () { + + for (var j = 0; j < this._axes.length; j++) + { + this._axes[j] = 0; + } + + } + +}; + +Phaser.SinglePad.prototype.constructor = Phaser.SinglePad; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. +* +* @class Phaser.Key +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}. +*/ +Phaser.Key = function (game, keycode) { + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * The enabled state of the key - see `enabled`. + * @property {boolean} _enabled + * @private + */ + this._enabled = true; + + /** + * @property {object} event - Stores the most recent DOM event. + * @readonly + */ + this.event = null; + + /** + * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * @default + */ + this.isDown = false; + + /** + * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * @default + */ + this.isUp = true; + + /** + * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. + * @default + */ + this.altKey = false; + + /** + * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. + * @default + */ + this.ctrlKey = false; + + /** + * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. + * @default + */ + this.shiftKey = false; + + /** + * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now. + */ + this.timeDown = 0; + + /** + * If the key is down this value holds the duration of that key press and is constantly updated. + * If the key is up it holds the duration of the previous down session. + * @property {number} duration - The number of milliseconds this key has been held down for. + * @default + */ + this.duration = 0; + + /** + * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now. + * @default + */ + this.timeUp = -2500; + + /** + * If the key is up this value holds the duration of that key release and is constantly updated. + * If the key is down it holds the duration of the previous up session. + * @property {number} duration - The number of milliseconds this key has been up for. + * @default + */ + this.durationUp = -2500; + + /** + * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. + * @default + */ + this.repeats = 0; + + /** + * @property {number} keyCode - The keycode of this key. + */ + this.keyCode = keycode; + + /** + * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). + */ + this.onDown = new Phaser.Signal(); + + /** + * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. + */ + this.onHoldCallback = null; + + /** + * @property {object} onHoldContext - The context under which the onHoldCallback will be called. + */ + this.onHoldContext = null; + + /** + * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). + */ + this.onUp = new Phaser.Signal(); + + /** + * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justDown = false; + + /** + * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter) + * @private + */ + this._justUp = false; + +}; + +Phaser.Key.prototype = { + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#update + * @protected + */ + update: function () { + + if (!this._enabled) { return; } + + if (this.isDown) + { + this.duration = this.game.time.time - this.timeDown; + this.repeats++; + + if (this.onHoldCallback) + { + this.onHoldCallback.call(this.onHoldContext, this); + } + } + else + { + this.durationUp = this.game.time.time - this.timeUp; + } + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyDown + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyDown: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + // exit if this key down is from auto-repeat + if (this.isDown) + { + return; + } + + this.altKey = event.altKey; + this.ctrlKey = event.ctrlKey; + this.shiftKey = event.shiftKey; + + this.isDown = true; + this.isUp = false; + this.timeDown = this.game.time.time; + this.duration = 0; + this.durationUp = this.game.time.time - this.timeUp; + this.repeats = 0; + + // _justDown will remain true until it is read via the justDown Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justDown = true; + + this.onDown.dispatch(this); + + }, + + /** + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyUp + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ + processKeyUp: function (event) { + + if (!this._enabled) { return; } + + this.event = event; + + if (this.isUp) + { + return; + } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = this.game.time.time - this.timeDown; + this.durationUp = 0; + + // _justUp will remain true until it is read via the justUp Getter + // this enables the game to poll for past presses, or reset it at the start of a new game state + this._justUp = true; + + this.onUp.dispatch(this); + + }, + + /** + * Resets the state of this Key. + * + * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key. + * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. + * + * @method Phaser.Key#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.isDown = false; + this.isUp = true; + this.timeUp = this.game.time.time; + this.duration = 0; + this.durationUp = -2500; + this._enabled = true; // .enabled causes reset(false) + this._justDown = false; + this._justUp = false; + + if (hard) + { + this.onDown.removeAll(); + this.onUp.removeAll(); + this.onHoldCallback = null; + this.onHoldContext = null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#downDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration. + */ + downDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (this.isDown && this.duration < duration); + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#upDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration. + */ + upDuration: function (duration) { + + if (duration === undefined) { duration = 50; } + + return (!this.isDown && ((this.game.time.time - this.timeUp) < duration)); + + }, + + /** + * Returns `true` if the Key was just pressed down this update tick, or `false` if it either isn't down, + * or was pressed down on a previous update tick. + * + * @method Phaser.Key#justPressed + * @return {boolean} True if the key was just pressed down this update tick. + */ + justPressed: function () { + + return (this.isDown && this.duration === 0); + + }, + + /** + * Returns `true` if the Key was just released this update tick, or `false` if it either isn't up, + * or was released on a previous update tick. + * + * @method Phaser.Key#justReleased + * @return {boolean} True if the key was just released this update tick. + */ + justReleased: function () { + + return (!this.isDown && this.durationUp === 0); + + } + +}; + +/** +* The justDown value allows you to test if this Key has just been pressed down or not. +* When you check this value it will return `true` if the Key is down, otherwise `false`. +* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. +* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justDown +* @property {boolean} justDown +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justDown", { + + get: function () { + + var current = this._justDown; + this._justDown = false; + return current; + + } + +}); + +/** +* The justUp value allows you to test if this Key has just been released or not. +* When you check this value it will return `true` if the Key is up, otherwise `false`. +* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again. +* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop. +* +* @name Phaser.Key#justUp +* @property {boolean} justUp +* @memberof Phaser.Key +* @default false +*/ +Object.defineProperty(Phaser.Key.prototype, "justUp", { + + get: function () { + + var current = this._justUp; + this._justUp = false; + return current; + + } + +}); + +/** +* An enabled key processes its update and dispatches events. +* A key can be disabled momentarily at runtime instead of deleting it. +* @name Phaser.Key#enabled +* @property {boolean} enabled +* @memberof Phaser.Key +* @default true +*/ +Object.defineProperty(Phaser.Key.prototype, "enabled", { + + get: function () { + + return this._enabled; + + }, + + set: function (value) { + + value = !!value; + + if (value !== this._enabled) + { + if (!value) + { + this.reset(false); + } + + this._enabled = value; + } + } + +}); + +Phaser.Key.prototype.constructor = Phaser.Key; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Keyboard class monitors keyboard input and dispatches keyboard events. +* +* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. +* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. +* +* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. +* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. +* So please check your extensions before opening Phaser issues. +* +* @class Phaser.Keyboard +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Keyboard = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Keyboard input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ + this.enabled = true; + + /** + * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. + */ + this.event = null; + + /** + * @property {object} pressEvent - The most recent DOM event from keypress. + */ + this.pressEvent = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are run. + */ + this.callbackContext = this; + + /** + * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. + */ + this.onDownCallback = null; + + /** + * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. + */ + this.onPressCallback = null; + + /** + * @property {function} onUpCallback - This callback is invoked every time a key is released. + */ + this.onUpCallback = null; + + /** + * @property {array} _keys - The array the Phaser.Key objects are stored in. + * @private + */ + this._keys = []; + + /** + * @property {array} _capture - The array the key capture values are stored in. + * @private + */ + this._capture = []; + + /** + * @property {function} _onKeyDown + * @private + * @default + */ + this._onKeyDown = null; + + /** + * @property {function} _onKeyPress + * @private + * @default + */ + this._onKeyPress = null; + + /** + * @property {function} _onKeyUp + * @private + * @default + */ + this._onKeyUp = null; + + /** + * @property {number} _i - Internal cache var + * @private + */ + this._i = 0; + + /** + * @property {number} _k - Internal cache var + * @private + */ + this._k = 0; + +}; + +Phaser.Keyboard.prototype = { + + /** + * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. + * + * @method Phaser.Keyboard#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down. + * @param {function} [onUp=null] - This callback is invoked every time a key is released. + * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised. + */ + addCallbacks: function (context, onDown, onUp, onPress) { + + this.callbackContext = context; + + if (onDown !== undefined && onDown !== null) + { + this.onDownCallback = onDown; + } + + if (onUp !== undefined && onUp !== null) + { + this.onUpCallback = onUp; + } + + if (onPress !== undefined && onPress !== null) + { + this.onPressCallback = onPress; + } + + }, + + /** + * Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}. + * + * @method Phaser.Keyboard#removeCallbacks + */ + removeCallbacks: function () { + + this.callbackContext = this; + this.onDownCallback = null; + this.onUpCallback = null; + this.onPressCallback = null; + + }, + + /** + * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. + * The Key object can then be polled, have events attached to it, etc. + * + * @method Phaser.Keyboard#addKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key. + * @return {Phaser.Key} The Key object which you can store locally and reference directly. + */ + addKey: function (keycode) { + + if (!this._keys[keycode]) + { + this._keys[keycode] = new Phaser.Key(this.game, keycode); + + this.addKeyCapture(keycode); + } + + return this._keys[keycode]; + + }, + + /** + * A practical way to create an object containing user selected hotkeys. + * + * For example, + * + * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); + * + * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object. + * + * @method Phaser.Keyboard#addKeys + * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. + * @return {object} An object containing the properties mapped to {@link Phaser.Key} values. + */ + addKeys: function (keys) { + + var output = {}; + + for (var key in keys) + { + output[key] = this.addKey(keys[key]); + } + + return output; + + }, + + /** + * Removes a Key object from the Keyboard manager. + * + * @method Phaser.Keyboard#removeKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove. + */ + removeKey: function (keycode) { + + if (this._keys[keycode]) + { + this._keys[keycode] = null; + + this.removeKeyCapture(keycode); + } + + }, + + /** + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. + * + * @method Phaser.Keyboard#createCursorKeys + * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects. + */ + createCursorKeys: function () { + + return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT }); + + }, + + /** + * Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window. + * This is called automatically by Phaser.Input and should not normally be invoked directly. + * + * @method Phaser.Keyboard#start + * @protected + */ + start: function () { + + if (this.game.device.cocoonJS) + { + return; + } + + if (this._onKeyDown !== null) + { + // Avoid setting multiple listeners + return; + } + + var _this = this; + + this._onKeyDown = function (event) { + return _this.processKeyDown(event); + }; + + this._onKeyUp = function (event) { + return _this.processKeyUp(event); + }; + + this._onKeyPress = function (event) { + return _this.processKeyPress(event); + }; + + window.addEventListener('keydown', this._onKeyDown, false); + window.addEventListener('keyup', this._onKeyUp, false); + window.addEventListener('keypress', this._onKeyPress, false); + + }, + + /** + * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. + * + * @method Phaser.Keyboard#stop + */ + stop: function () { + + window.removeEventListener('keydown', this._onKeyDown); + window.removeEventListener('keyup', this._onKeyUp); + window.removeEventListener('keypress', this._onKeyPress); + + this._onKeyDown = null; + this._onKeyUp = null; + this._onKeyPress = null; + + }, + + /** + * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. + * Also clears all key captures and currently created Key objects. + * + * @method Phaser.Keyboard#destroy + */ + destroy: function () { + + this.stop(); + + this.clearCaptures(); + + this._keys.length = 0; + this._i = 0; + + }, + + /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Pass in either a single keycode or an array/hash of keycodes. + * + * @method Phaser.Keyboard#addKeyCapture + * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`. + */ + addKeyCapture: function (keycode) { + + if (typeof keycode === 'object') + { + for (var key in keycode) + { + this._capture[keycode[key]] = true; + } + } + else + { + this._capture[keycode] = true; + } + }, + + /** + * Removes an existing key capture. + * + * @method Phaser.Keyboard#removeKeyCapture + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of. + */ + removeKeyCapture: function (keycode) { + + delete this._capture[keycode]; + + }, + + /** + * Clear all set key captures. + * + * @method Phaser.Keyboard#clearCaptures + */ + clearCaptures: function () { + + this._capture = {}; + + }, + + /** + * Updates all currently defined keys. + * + * @method Phaser.Keyboard#update + */ + update: function () { + + this._i = this._keys.length; + + while (this._i--) + { + if (this._keys[this._i]) + { + this._keys[this._i].update(); + } + } + + }, + + /** + * Process the keydown event. + * + * @method Phaser.Keyboard#processKeyDown + * @param {KeyboardEvent} event + * @protected + */ + processKeyDown: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + // The event is being captured but another hotkey may need it + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyDown(event); + + this._k = key; + + if (this.onDownCallback) + { + this.onDownCallback.call(this.callbackContext, event); + } + + }, + + /** + * Process the keypress event. + * + * @method Phaser.Keyboard#processKeyPress + * @param {KeyboardEvent} event + * @protected + */ + processKeyPress: function (event) { + + this.pressEvent = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + if (this.onPressCallback) + { + this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event); + } + + }, + + /** + * Process the keyup event. + * + * @method Phaser.Keyboard#processKeyUp + * @param {KeyboardEvent} event + * @protected + */ + processKeyUp: function (event) { + + this.event = event; + + if (!this.game.input.enabled || !this.enabled) + { + return; + } + + var key = event.keyCode; + + if (this._capture[key]) + { + event.preventDefault(); + } + + if (!this._keys[key]) + { + this._keys[key] = new Phaser.Key(this.game, key); + } + + this._keys[key].processKeyUp(event); + + if (this.onUpCallback) + { + this.onUpCallback.call(this.callbackContext, event); + } + + }, + + /** + * Resets all Keys. + * + * @method Phaser.Keyboard#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. + */ + reset: function (hard) { + + if (hard === undefined) { hard = true; } + + this.event = null; + + var i = this._keys.length; + + while (i--) + { + if (this._keys[i]) + { + this._keys[i].reset(hard); + } + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#downDuration + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. + */ + downDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].downDuration(duration); + } + else + { + return null; + } + + }, + + /** + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#upDuration + * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found. + */ + upDuration: function (keycode, duration) { + + if (this._keys[keycode]) + { + return this._keys[keycode].upDuration(duration); + } + else + { + return null; + } + + }, + + justPressed: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justPressed(); + } + else + { + return null; + } + + }, + + justReleased: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].justReleased(); + } + else + { + return null; + } + + }, + + /** + * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. + * + * @method Phaser.Keyboard#isDown + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found. + */ + isDown: function (keycode) { + + if (this._keys[keycode]) + { + return this._keys[keycode].isDown; + } + else + { + return null; + } + + } + +}; + +/** +* Returns the string value of the most recently pressed key. +* @name Phaser.Keyboard#lastChar +* @property {string} lastChar - The string value of the most recently pressed key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", { + + get: function () { + + if (this.event && this.event.charCode === 32) + { + return ''; + } + else if (this.pressEvent) + { + return String.fromCharCode(this.pressEvent.charCode); + } + else + { + return null; + } + + } + +}); + +/** +* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. +* @name Phaser.Keyboard#lastKey +* @property {Phaser.Key} lastKey - The most recently pressed Key. +* @readonly +*/ +Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", { + + get: function () { + + return this._keys[this._k]; + + } + +}); + +Phaser.Keyboard.prototype.constructor = Phaser.Keyboard; + +/** +* A key code represents a physical key on a keyboard. +* +* The KeyCode class contains commonly supported keyboard key codes which can be used +* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods. +* +* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. +* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. +* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property. +* +* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; +* the latter approach is supported for compatibility. +* +* @class Phaser.KeyCode +*/ +Phaser.KeyCode = { + /** @static */ + A: "A".charCodeAt(0), + /** @static */ + B: "B".charCodeAt(0), + /** @static */ + C: "C".charCodeAt(0), + /** @static */ + D: "D".charCodeAt(0), + /** @static */ + E: "E".charCodeAt(0), + /** @static */ + F: "F".charCodeAt(0), + /** @static */ + G: "G".charCodeAt(0), + /** @static */ + H: "H".charCodeAt(0), + /** @static */ + I: "I".charCodeAt(0), + /** @static */ + J: "J".charCodeAt(0), + /** @static */ + K: "K".charCodeAt(0), + /** @static */ + L: "L".charCodeAt(0), + /** @static */ + M: "M".charCodeAt(0), + /** @static */ + N: "N".charCodeAt(0), + /** @static */ + O: "O".charCodeAt(0), + /** @static */ + P: "P".charCodeAt(0), + /** @static */ + Q: "Q".charCodeAt(0), + /** @static */ + R: "R".charCodeAt(0), + /** @static */ + S: "S".charCodeAt(0), + /** @static */ + T: "T".charCodeAt(0), + /** @static */ + U: "U".charCodeAt(0), + /** @static */ + V: "V".charCodeAt(0), + /** @static */ + W: "W".charCodeAt(0), + /** @static */ + X: "X".charCodeAt(0), + /** @static */ + Y: "Y".charCodeAt(0), + /** @static */ + Z: "Z".charCodeAt(0), + /** @static */ + ZERO: "0".charCodeAt(0), + /** @static */ + ONE: "1".charCodeAt(0), + /** @static */ + TWO: "2".charCodeAt(0), + /** @static */ + THREE: "3".charCodeAt(0), + /** @static */ + FOUR: "4".charCodeAt(0), + /** @static */ + FIVE: "5".charCodeAt(0), + /** @static */ + SIX: "6".charCodeAt(0), + /** @static */ + SEVEN: "7".charCodeAt(0), + /** @static */ + EIGHT: "8".charCodeAt(0), + /** @static */ + NINE: "9".charCodeAt(0), + /** @static */ + NUMPAD_0: 96, + /** @static */ + NUMPAD_1: 97, + /** @static */ + NUMPAD_2: 98, + /** @static */ + NUMPAD_3: 99, + /** @static */ + NUMPAD_4: 100, + /** @static */ + NUMPAD_5: 101, + /** @static */ + NUMPAD_6: 102, + /** @static */ + NUMPAD_7: 103, + /** @static */ + NUMPAD_8: 104, + /** @static */ + NUMPAD_9: 105, + /** @static */ + NUMPAD_MULTIPLY: 106, + /** @static */ + NUMPAD_ADD: 107, + /** @static */ + NUMPAD_ENTER: 108, + /** @static */ + NUMPAD_SUBTRACT: 109, + /** @static */ + NUMPAD_DECIMAL: 110, + /** @static */ + NUMPAD_DIVIDE: 111, + /** @static */ + F1: 112, + /** @static */ + F2: 113, + /** @static */ + F3: 114, + /** @static */ + F4: 115, + /** @static */ + F5: 116, + /** @static */ + F6: 117, + /** @static */ + F7: 118, + /** @static */ + F8: 119, + /** @static */ + F9: 120, + /** @static */ + F10: 121, + /** @static */ + F11: 122, + /** @static */ + F12: 123, + /** @static */ + F13: 124, + /** @static */ + F14: 125, + /** @static */ + F15: 126, + /** @static */ + COLON: 186, + /** @static */ + EQUALS: 187, + /** @static */ + COMMA: 188, + /** @static */ + UNDERSCORE: 189, + /** @static */ + PERIOD: 190, + /** @static */ + QUESTION_MARK: 191, + /** @static */ + TILDE: 192, + /** @static */ + OPEN_BRACKET: 219, + /** @static */ + BACKWARD_SLASH: 220, + /** @static */ + CLOSED_BRACKET: 221, + /** @static */ + QUOTES: 222, + /** @static */ + BACKSPACE: 8, + /** @static */ + TAB: 9, + /** @static */ + CLEAR: 12, + /** @static */ + ENTER: 13, + /** @static */ + SHIFT: 16, + /** @static */ + CONTROL: 17, + /** @static */ + ALT: 18, + /** @static */ + CAPS_LOCK: 20, + /** @static */ + ESC: 27, + /** @static */ + SPACEBAR: 32, + /** @static */ + PAGE_UP: 33, + /** @static */ + PAGE_DOWN: 34, + /** @static */ + END: 35, + /** @static */ + HOME: 36, + /** @static */ + LEFT: 37, + /** @static */ + UP: 38, + /** @static */ + RIGHT: 39, + /** @static */ + DOWN: 40, + /** @static */ + PLUS: 43, + /** @static */ + MINUS: 44, + /** @static */ + INSERT: 45, + /** @static */ + DELETE: 46, + /** @static */ + HELP: 47, + /** @static */ + NUM_LOCK: 144 +}; + +// Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility +for (var key in Phaser.KeyCode) +{ + if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/)) + { + Phaser.Keyboard[key] = Phaser.KeyCode[key]; + } +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +Phaser.Component = function () {}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. +* +* @class +*/ +Phaser.Component.Angle = function () {}; + +Phaser.Component.Angle.prototype = { + + /** + * The angle property is the rotation of the Game Object in *degrees* from its original orientation. + * + * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. + * + * Values outside this range are added to or subtracted from 360 to obtain a value within the range. + * For example, the statement player.angle = 450 is the same as player.angle = 90. + * + * If you wish to work in radians instead of degrees you can use the property `rotation` instead. + * Working in radians is slightly faster as it doesn't have to perform any calculations. + * + * @property {number} angle + */ + angle: { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); + + }, + + set: function(value) { + + this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. +* +* @class +*/ +Phaser.Component.Animation = function () {}; + +Phaser.Component.Animation.prototype = { + + /** + * Plays an Animation. + * + * The animation should have previously been created via `animations.add`. + * + * If the animation is already playing calling this again won't do anything. + * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. + * + * @method + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation. + */ + play: function (name, frameRate, loop, killOnComplete) { + + if (this.animations) + { + return this.animations.play(name, frameRate, loop, killOnComplete); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. +* It is used by the InWorld component. +* +* @class +*/ +Phaser.Component.AutoCull = function () {}; + +Phaser.Component.AutoCull.prototype = { + + /** + * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. + * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. + * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} autoCull + * @default + */ + autoCull: false, + + /** + * Checks if the Game Objects bounds intersect with the Game Camera bounds. + * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + if (!this.autoCull && !this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + } + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Bounds component contains properties related to the bounds of the Game Object. +* +* @class +*/ +Phaser.Component.Bounds = function () {}; + +Phaser.Component.Bounds.prototype = { + + /** + * The amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * anchor.x`. + * It will only be > 0 if anchor.x is not equal to zero. + * + * @property {number} offsetX + * @readOnly + */ + offsetX: { + + get: function () { + + return this.anchor.x * this.width; + + } + + }, + + /** + * The amount the Game Object is visually offset from its y coordinate. + * This is the same as `height * anchor.y`. + * It will only be > 0 if anchor.y is not equal to zero. + * + * @property {number} offsetY + * @readOnly + */ + offsetY: { + + get: function () { + + return this.anchor.y * this.height; + + } + + }, + + /** + * The local center x coordinate of the Game Object. + * This is the same as `(x - offsetX) + (width / 2)`. + * + * @property {number} centerX + */ + centerX: { + + get: function () { + + return (this.x - this.offsetX) + (this.width * 0.5); + + }, + + set: function (value) { + + this.x = (value + this.offsetX) - (this.width * 0.5); + + } + + }, + + /** + * The local center y coordinate of the Game Object. + * This is the same as `(y - offsetY) + (height / 2)`. + * + * @property {number} centerY + */ + centerY: { + + get: function () { + + return (this.y - this.offsetY) + (this.height * 0.5); + + }, + + set: function (value) { + + this.y = (value + this.offsetY) - (this.height * 0.5); + + } + + }, + + /** + * The left coordinate of the Game Object. + * This is the same as `x - offsetX`. + * + * @property {number} left + */ + left: { + + get: function () { + + return this.x - this.offsetX; + + }, + + set: function (value) { + + this.x = value + this.offsetX; + + } + + }, + + /** + * The right coordinate of the Game Object. + * This is the same as `x + width - offsetX`. + * + * @property {number} right + */ + right: { + + get: function () { + + return (this.x + this.width) - this.offsetX; + + }, + + set: function (value) { + + this.x = value - (this.width) + this.offsetX; + + } + + }, + + /** + * The y coordinate of the Game Object. + * This is the same as `y - offsetY`. + * + * @property {number} top + */ + top: { + + get: function () { + + return this.y - this.offsetY; + + }, + + set: function (value) { + + this.y = value + this.offsetY; + + } + + }, + + /** + * The sum of the y and height properties. + * This is the same as `y + height - offsetY`. + * + * @property {number} bottom + */ + bottom: { + + get: function () { + + return (this.y + this.height) - this.offsetY; + + }, + + set: function (value) { + + this.y = value - (this.height) + this.offsetY; + + } + + }, + + /** + * Aligns this Game Object within another Game Object, or Rectangle, known as the + * 'container', to one of 9 possible positions. + * + * The container must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the container. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, + * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * container, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignIn: function (container, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = container.left - offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = container.centerX + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = container.right + offsetX; + this.top = container.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.left = container.left - offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.CENTER: + this.centerX = container.centerX + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.right = container.right + offsetX; + this.centerY = container.centerY + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = container.left - offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = container.centerX + offsetX; + this.bottom = container.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = container.right + offsetX; + this.bottom = container.bottom + offsetY; + break; + } + + return this; + + }, + + /** + * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the + * 'parent', in one of 11 possible positions. + * + * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the parent. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, + * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, + * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * parent, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ + alignTo: function (parent, position, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + switch (position) + { + default: + case Phaser.TOP_LEFT: + this.left = parent.left - offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_CENTER: + this.centerX = parent.centerX + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.TOP_RIGHT: + this.right = parent.right + offsetX; + this.bottom = parent.top - offsetY; + break; + + case Phaser.LEFT_TOP: + this.right = parent.left - offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.LEFT_CENTER: + this.right = parent.left - offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.LEFT_BOTTOM: + this.right = parent.left - offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.RIGHT_TOP: + this.left = parent.right + offsetX; + this.top = parent.top - offsetY; + break; + + case Phaser.RIGHT_CENTER: + this.left = parent.right + offsetX; + this.centerY = parent.centerY + offsetY; + break; + + case Phaser.RIGHT_BOTTOM: + this.left = parent.right + offsetX; + this.bottom = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_LEFT: + this.left = parent.left - offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_CENTER: + this.centerX = parent.centerX + offsetX; + this.top = parent.bottom + offsetY; + break; + + case Phaser.BOTTOM_RIGHT: + this.right = parent.right + offsetX; + this.top = parent.bottom + offsetY; + break; + } + + return this; + + } + +}; + +// Phaser.Group extensions + +Phaser.Group.prototype.alignIn = Phaser.Component.Bounds.prototype.alignIn; +Phaser.Group.prototype.alignTo = Phaser.Component.Bounds.prototype.alignTo; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The BringToTop Component features quick access to Group sorting related methods. +* +* @class +*/ +Phaser.Component.BringToTop = function () {}; + +/** +* Brings this Game Object to the top of its parents display list. +* Visually this means it will render over the top of any old child in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.bringToTop = function() { + + if (this.parent) + { + this.parent.bringToTop(this); + } + + return this; + +}; + +/** +* Sends this Game Object to the bottom of its parents display list. +* Visually this means it will render below all other children in the same Group. +* +* If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.sendToBack = function() { + + if (this.parent) + { + this.parent.sendToBack(this); + } + + return this; + +}; + +/** +* Moves this Game Object up one place in its parents display list. +* This call has no effect if the Game Object is already at the top of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveUp = function () { + + if (this.parent) + { + this.parent.moveUp(this); + } + + return this; + +}; + +/** +* Moves this Game Object down one place in its parents display list. +* This call has no effect if the Game Object is already at the bottom of the display list. +* +* If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, +* because the World is the root Group from which all Game Objects descend. +* +* @method +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.BringToTop.prototype.moveDown = function () { + + if (this.parent) + { + this.parent.moveDown(this); + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Core Component Features. +* +* @class +*/ +Phaser.Component.Core = function () {}; + +/** + * @property {boolean} skipTypeChecks - Skip type checks in {@link #init}. + * @static + * @default + */ +Phaser.Component.Core.skipTypeChecks = false; + +/** +* Installs / registers mixin components. +* +* The `this` context should be that of the applicable object instance or prototype. +* +* @method +* @protected +*/ +Phaser.Component.Core.install = function (components) { + + // Always install 'Core' first + Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype); + + this.components = {}; + + for (var i = 0; i < components.length; i++) + { + var id = components[i]; + var replace = false; + + if (id === 'Destroy') + { + replace = true; + } + + Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace); + + this.components[id] = true; + } + +}; + +/** +* Initializes the mixin components. +* +* The `this` context should be an instance of the component mixin target. +* +* @method +* @protected +*/ +Phaser.Component.Core.init = function (game, x, y, key, frame) { + + if (!Phaser.Component.Core.skipTypeChecks) + { + if (!(game instanceof Phaser.Game)) + { + throw new Error('The value passed as the `game` argument (' + game + ') is not an instance of Phaser.Game.'); + } + + if (typeof x !== 'number') + { + console.warn('The `x` argument value (%s) should be a number.', x); + x = 0; // This would be done implicitly in position.set(). + } + + if (typeof y !== 'number') + { + console.warn('The `y` argument value (%s) should be a number.', y); + y = 0; // This would be done implicitly in position.set(). + } + } + + this.game = game; + this.key = key; + this.data = {}; + + this.position.set(x, y); + this.world = new Phaser.Point(x, y); + this.previousPosition = new Phaser.Point(x, y); + + this.events = new Phaser.Events(this); + + this._bounds = new Phaser.Rectangle(); + + if (this.components.PhysicsBody) + { + // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype. + this.body = this.body; + } + + if (this.components.Animation) + { + this.animations = new Phaser.AnimationManager(this); + } + + if (this.components.LoadTexture && key !== null) + { + this.loadTexture(key, frame); + } + + if (this.components.FixedToCamera) + { + this.cameraOffset = new Phaser.Point(x, y); + } + +}; + +Phaser.Component.Core.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this.exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty); + + if (this.visible) + { + this.renderOrderID = this.game.stage.currentRenderOrderID++; + } + + if (this.animations) + { + this.animations.update(); + } + + if (this.body) + { + this.body.preUpdate(); + } + + this.preUpdateChildren(); + + return true; + +}; + +Phaser.Component.Core.prototype = { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + game: null, + + /** + * A user defined name given to this Game Object. + * This value isn't ever used internally by Phaser, it is meant as a game level property. + * @property {string} name + * @default + */ + name: '', + + /** + * An empty Object that belongs to this Game Object. + * This value isn't ever used internally by Phaser, but may be used by your own code, or + * by Phaser Plugins, to store data that needs to be associated with the Game Object, + * without polluting the Game Object directly. + * @property {Object} data + * @default + */ + data: {}, + + /** + * The components this Game Object has installed. + * @property {object} components + * @protected + */ + components: {}, + + /** + * The z depth of this Game Object within its parent Group. + * No two objects in a Group can have the same z value. + * This value is adjusted automatically whenever the Group hierarchy changes. + * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. + * @property {number} z + * @readOnly + */ + z: 0, + + /** + * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this + * Game Object, or any of its components. + * @see Phaser.Events + * @property {Phaser.Events} events + */ + events: undefined, + + /** + * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. + * Through it you can create, play, pause and stop animations. + * @see Phaser.AnimationManager + * @property {Phaser.AnimationManager} animations + */ + animations: undefined, + + /** + * The key of the image or texture used by this Game Object during rendering. + * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. + * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. + * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. + * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key + */ + key: '', + + /** + * The world coordinates of this Game Object in pixels. + * Depending on where in the display list this Game Object is placed this value can differ from `position`, + * which contains the x/y coordinates relative to the Game Objects parent. + * @property {Phaser.Point} world + */ + world: null, + + /** + * A debug flag designed for use with `Game.enableStep`. + * @property {boolean} debug + * @default + */ + debug: false, + + /** + * The position the Game Object was located in the previous frame. + * @property {Phaser.Point} previousPosition + * @readOnly + */ + previousPosition: null, + + /** + * The rotation the Game Object was in set to in the previous frame. Value is in radians. + * @property {number} previousRotation + * @readOnly + */ + previousRotation: 0, + + /** + * The render order ID is used internally by the renderer and Input Manager and should not be modified. + * This property is mostly used internally by the renderers, but is exposed for the use of plugins. + * @property {number} renderOrderID + * @readOnly + */ + renderOrderID: 0, + + /** + * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. + * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. + * @property {boolean} fresh + * @readOnly + */ + fresh: true, + + /** + * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. + * You can set it directly to allow you to flag an object to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy an object from within one of its own callbacks + * such as with Buttons or other Input events. + * + * @property {boolean} pendingDestroy + */ + pendingDestroy: false, + + /** + * @property {Phaser.Rectangle} _bounds - Internal cache var. + * @private + */ + _bounds: null, + + /** + * @property {boolean} _exists - Internal cache var. + * @private + */ + _exists: true, + + /** + * Controls if this Game Object is processed by the core game loop. + * If this Game Object has a physics body it also controls if its physics body is updated or not. + * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. + * It also toggles the `visible` property to false as well. + * + * Setting `exists` to true will add its physics body back in to the physics world, if it has one. + * It will also set the `visible` property to `true`. + * + * @property {boolean} exists + */ + exists: { + + get: function () { + + return this._exists; + + }, + + set: function (value) { + + if (value) + { + this._exists = true; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.addToWorld(); + } + + this.visible = true; + } + else + { + this._exists = false; + + if (this.body && this.body.type === Phaser.Physics.P2JS) + { + this.body.removeFromWorld(); + } + + this.visible = false; + } + + } + + }, + + /** + * Internal method called by preUpdate. + * + * @method + * @protected + */ + preUpdateChildren: function() { + + // This can't loop in reverse, we need the renderOrderID to be in sequence + var i = 0; + + while (i < this.children.length) + { + var child = this.children[i]; + + child.preUpdate(); + + if (this === child.parent) + { + i++; + } + } + + }, + + /** + * Override this method in your own custom objects to handle any update requirements. + * It is called immediately after `preUpdate` and before `postUpdate`. + * Remember if this Game Object has any children you should call update on those too. + * + * @method + */ + update: function() { + + }, + + /** + * Internal method called by the World postUpdate cycle. + * + * @method + * @protected + */ + postUpdate: function() { + + if (this.customRender) + { + this.key.render(); + } + + if (this.components.PhysicsBody) + { + Phaser.Component.PhysicsBody.postUpdate.call(this); + } + + if (this.components.FixedToCamera) + { + Phaser.Component.FixedToCamera.postUpdate.call(this); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, +* which can be updated in real-time. +* +* @class +*/ +Phaser.Component.Crop = function () {}; + +Phaser.Component.Crop.prototype = { + + /** + * The Rectangle used to crop the texture this Game Object uses. + * Set this property via `crop`. + * If you modify this property directly you must call `updateCrop` in order to have the change take effect. + * @property {Phaser.Rectangle} cropRect + * @default + */ + cropRect: null, + + /** + * @property {Phaser.Rectangle} _crop - Internal cache var. + * @private + */ + _crop: null, + + /** + * Crop allows you to crop the texture being used to display this Game Object. + * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. + * + * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, + * or by modifying `cropRect` property directly and then calling `updateCrop`. + * + * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object + * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. + * + * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, + * in which case the values are duplicated to a local object. + * + * @method + * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. + * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. + */ + crop: function (rect, copy) { + + if (copy === undefined) { copy = false; } + + if (rect) + { + if (copy && this.cropRect !== null) + { + this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height); + } + else if (copy && this.cropRect === null) + { + this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height); + } + else + { + this.cropRect = rect; + } + + this.updateCrop(); + } + else + { + this._crop = null; + this.cropRect = null; + + this.resetFrame(); + } + + }, + + /** + * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, + * or the rectangle it references, then you need to update the crop frame by calling this method. + * + * @method + */ + updateCrop: function () { + + if (!this.cropRect) + { + return; + } + + var oldX = this.texture.crop.x; + var oldY = this.texture.crop.y; + var oldW = this.texture.crop.width; + var oldH = this.texture.crop.height; + + this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop); + this._crop.x += this._frame.x; + this._crop.y += this._frame.y; + + var cx = Math.max(this._frame.x, this._crop.x); + var cy = Math.max(this._frame.y, this._crop.y); + var cw = Math.min(this._frame.right, this._crop.right) - cx; + var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy; + + this.texture.crop.x = cx; + this.texture.crop.y = cy; + this.texture.crop.width = cw; + this.texture.crop.height = ch; + + this.texture.frame.width = Math.min(cw, this.cropRect.width); + this.texture.frame.height = Math.min(ch, this.cropRect.height); + + this.texture.width = this.texture.frame.width; + this.texture.height = this.texture.frame.height; + + this.texture._updateUvs(); + + if (this.tint !== 0xffffff && (oldX !== cx || oldY !== cy || oldW !== cw || oldH !== ch)) + { + this.texture.requiresReTint = true; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Delta component provides access to delta values between the Game Objects current and previous position. +* +* @class +*/ +Phaser.Component.Delta = function () {}; + +Phaser.Component.Delta.prototype = { + + /** + * Returns the delta x value. The difference between world.x now and in the previous frame. + * + * The value will be positive if the Game Object has moved to the right or negative if to the left. + * + * @property {number} deltaX + * @readonly + */ + deltaX: { + + get: function() { + + return this.world.x - this.previousPosition.x; + + } + + }, + + /** + * Returns the delta y value. The difference between world.y now and in the previous frame. + * + * The value will be positive if the Game Object has moved down or negative if up. + * + * @property {number} deltaY + * @readonly + */ + deltaY: { + + get: function() { + + return this.world.y - this.previousPosition.y; + + } + + }, + + /** + * Returns the delta z value. The difference between rotation now and in the previous frame. + * + * @property {number} deltaZ - The delta value. + * @readonly + */ + deltaZ: { + + get: function() { + + return this.rotation - this.previousRotation; + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Destroy component is responsible for destroying a Game Object. +* +* @class +*/ +Phaser.Component.Destroy = function () {}; + +Phaser.Component.Destroy.prototype = { + + /** + * As a Game Object runs through its destroy method this flag is set to true, + * and can be checked in any sub-systems or plugins it is being destroyed from. + * @property {boolean} destroyPhase + * @readOnly + */ + destroyPhase: false, + + /** + * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present + * and nulls its reference to `game`, freeing it up for garbage collection. + * + * If this Game Object has the Events component it will also dispatch the `onDestroy` event. + * + * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've + * more than one Game Object sharing the same BaseTexture. + * + * @method + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? + * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. + */ + destroy: function (destroyChildren, destroyTexture) { + + if (this.game === null || this.destroyPhase) { return; } + + if (destroyChildren === undefined) { destroyChildren = true; } + if (destroyTexture === undefined) { destroyTexture = false; } + + this.destroyPhase = true; + + if (this.events) + { + this.events.onDestroy$dispatch(this); + } + + if (this.parent) + { + if (this.parent instanceof Phaser.Group) + { + this.parent.remove(this); + } + else + { + this.parent.removeChild(this); + } + } + + if (this.input) + { + this.input.destroy(); + } + + if (this.animations) + { + this.animations.destroy(); + } + + if (this.body) + { + this.body.destroy(); + } + + if (this.events) + { + this.events.destroy(); + } + + this.game.tweens.removeFrom(this); + + var i = this.children.length; + + if (destroyChildren) + { + while (i--) + { + this.children[i].destroy(destroyChildren); + } + } + else + { + while (i--) + { + this.removeChild(this.children[i]); + } + } + + if (this._crop) + { + this._crop = null; + this.cropRect = null; + } + + if (this._frame) + { + this._frame = null; + } + + if (Phaser.Video && this.key instanceof Phaser.Video) + { + this.key.onChangeSource.remove(this.resizeFrame, this); + } + + if (Phaser.BitmapText && this._glyphs) + { + this._glyphs = []; + } + + this.alive = false; + this.exists = false; + this.visible = false; + + this.filters = null; + this.mask = null; + this.game = null; + + this.data = {}; + + // In case Pixi is still going to try and render it even though destroyed + this.renderable = false; + + if (this.transformCallback) + { + this.transformCallback = null; + this.transformCallbackContext = null; + } + + // Pixi level DisplayObject destroy + this.hitArea = null; + this.parent = null; + this.stage = null; + this.worldTransform = null; + this.filterArea = null; + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this._destroyCachedSprite(); + + // Texture? + if (destroyTexture) + { + this.texture.destroy(true); + } + + this.destroyPhase = false; + this.pendingDestroy = false; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Events component is a collection of events fired by the parent Game Object. +* +* Phaser uses what are known as 'Signals' for all event handling. All of the events in +* this class are signals you can subscribe to, much in the same way you'd "listen" for +* an event. +* +* For example to tell when a Sprite has been added to a new group, you can bind a function +* to the {@link #onAddedToGroup} signal: +* +* `sprite.events.onAddedToGroup.add(yourFunction, this);` +* +* Where `yourFunction` is the function you want called when this event occurs. +* +* For more details about how signals work please see the {@link Phaser.Signal} class. +* +* The Input-related events will only be dispatched if the Sprite has had {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true` +* and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. +* +* @class Phaser.Events +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. +*/ +Phaser.Events = function (sprite) { + + /** + * @property {Phaser.Sprite} parent - The Sprite that owns these events. + */ + this.parent = sprite; + + // The signals are automatically added by the corresponding proxy properties + +}; + +Phaser.Events.prototype = { + + /** + * Removes all events. + * + * @method Phaser.Events#destroy + */ + destroy: function () { + + this._parent = null; + + if (this._onDestroy) { this._onDestroy.dispose(); } + if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } + if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } + if (this._onKilled) { this._onKilled.dispose(); } + if (this._onRevived) { this._onRevived.dispose(); } + if (this._onEnterBounds) { this._onEnterBounds.dispose(); } + if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } + + if (this._onInputOver) { this._onInputOver.dispose(); } + if (this._onInputOut) { this._onInputOut.dispose(); } + if (this._onInputDown) { this._onInputDown.dispose(); } + if (this._onInputUp) { this._onInputUp.dispose(); } + if (this._onDragStart) { this._onDragStart.dispose(); } + if (this._onDragUpdate) { this._onDragUpdate.dispose(); } + if (this._onDragStop) { this._onDragStop.dispose(); } + + if (this._onAnimationStart) { this._onAnimationStart.dispose(); } + if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } + if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } + + }, + + // The following properties are sentinels that will be replaced with getters + + /** + * This signal is dispatched when this Game Object is added to a new {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was added to the Group. + * - {Phaser.Group} The Group it was added to. + * + * @property {Phaser.Signal} onAddedToGroup + */ + onAddedToGroup: null, + + /** + * This signal is dispatched when the Game Object is removed from a {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was removed from the Group. + * - {Phaser.Group} The Group it was removed from. + * + * @property {Phaser.Signal} onRemovedFromGroup + */ + onRemovedFromGroup: null, + + /** + * This signal is dispatched when the Game Object is destroyed. + * This happens when {@link Phaser.Sprite#destroy Sprite.destroy()} is called, or {@link Phaser.Group#destroy Group.destroy()} with `destroyChildren` set to true. + * It is sent one argument: + * + * - {any} The Game Object that was destroyed. + * + * @property {Phaser.Signal} onDestroy + */ + onDestroy: null, + + /** + * This signal is dispatched when the Game Object is killed. + * This happens when {@link Phaser.Sprite#kill Sprite.kill()} is called. + * Please understand the difference between {@link Phaser.Sprite#kill kill} and {@link Phaser.Sprite#destroy destroy} by looking at their respective methods. + * It is sent one argument: + * + * - {any} The Game Object that was killed. + * + * @property {Phaser.Signal} onKilled + */ + onKilled: null, + + /** + * This signal is dispatched when the Game Object is revived from a previously killed state. + * This happens when {@link Phaser.Sprite#revive Sprite.revive()} is called. + * It is sent one argument: + * + * - {any} The Game Object that was revived. + * + * @property {Phaser.Signal} onRevived + */ + onRevived: null, + + /** + * This signal is dispatched when the Game Object leaves the Phaser.World {@link Phaser.World#bounds bounds}. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that left the World bounds. + * + * @property {Phaser.Signal} onOutOfBounds + */ + onOutOfBounds: null, + + /** + * This signal is dispatched when the Game Object returns within the Phaser.World {@link Phaser.World#bounds bounds}, having previously been outside of them. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that entered the World bounds. + * + * @property {Phaser.Signal} onEnterBounds + */ + onEnterBounds: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an over event from a {@link Phaser.Pointer}. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOver + */ + onInputOver: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an out event from a {@link Phaser.Pointer}, which was previously over it. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOut + */ + onInputOut: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives a down event from a {@link Phaser.Pointer}. This effectively means the Pointer has been + * pressed down (but not yet released) on the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputDown + */ + onInputDown: null, + + /** + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an up event from a {@link Phaser.Pointer}. This effectively means the Pointer had been + * pressed down, and was then released on the Game Object. + * It is sent three arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {boolean} isOver - Is the Pointer still over the Game Object? + * + * @property {Phaser.Signal} onInputUp + */ + onInputUp: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} starts to drag the Game Object, taking into consideration the various + * drag limitations that may be set. + * It is sent four arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The x coordinate that the drag started from. + * - {number} The y coordinate that the drag started from. + * + * @property {Phaser.Signal} onDragStart + */ + onDragStart: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} is actively dragging the Game Object. + * Be warned: This is a high volume Signal. Be careful what you bind to it. + * It is sent six arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The new x coordinate of the Game Object. + * - {number} The new y coordinate of the Game Object. + * - {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. + * - {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. + * + * @property {Phaser.Signal} onDragUpdate + */ + onDragUpdate: null, + + /** + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} stops dragging the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onDragStop + */ + onDragStop: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been played. + * You can also listen to {@link Phaser.Animation#onStart} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was started. + * + * @property {Phaser.Signal} onAnimationStart + */ + onAnimationStart: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been stopped (via {@link Phaser.AnimationManager#stop animation.stop()} and the `dispatchComplete` argument has been set. + * You can also listen to {@link Phaser.Animation#onComplete} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was stopped. + * + * @property {Phaser.Signal} onAnimationComplete + */ + onAnimationComplete: null, + + /** + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has looped playback. + * You can also listen to {@link Phaser.Animation#onLoop} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that looped. + * + * @property {Phaser.Signal} onAnimationLoop + */ + onAnimationLoop: null + +}; + +Phaser.Events.prototype.constructor = Phaser.Events; + +// Create an auto-create proxy getter and dispatch method for all events. +// The backing property is the same as the event name, prefixed with '_' +// and the dispatch method is the same as the event name postfixed with '$dispatch'. +for (var prop in Phaser.Events.prototype) +{ + if (!Phaser.Events.prototype.hasOwnProperty(prop) || + prop.indexOf('on') !== 0 || + Phaser.Events.prototype[prop] !== null) + { + continue; + } + + (function (prop, backing) { + 'use strict'; + + // The accessor creates a new Signal; and so it should only be used from user-code. + Object.defineProperty(Phaser.Events.prototype, prop, { + get: function () { + return this[backing] || (this[backing] = new Phaser.Signal()); + } + }); + + // The dispatcher will only broadcast on an already-created signal; call this internally. + Phaser.Events.prototype[prop + '$dispatch'] = function () { + return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; + }; + + })(prop, '_' + prop); + +} + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless +* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. +* +* @class +*/ +Phaser.Component.FixedToCamera = function () {}; + +/** + * The FixedToCamera component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.FixedToCamera.postUpdate = function () { + + if (this.fixedToCamera) + { + 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.Component.FixedToCamera.prototype = { + + /** + * @property {boolean} _fixedToCamera + * @private + */ + _fixedToCamera: false, + + /** + * A Game Object that is "fixed" to the camera is rendered at a given x/y offsets from the top left of the camera. The offsets + * are stored in the `cameraOffset` property, which is initialized with the current object coordinates. + * + * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. + * + * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world + * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times + * regardless where in the world the camera is. + * + * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. + * + * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. + * + * @property {boolean} fixedToCamera + */ + fixedToCamera: { + + get: function () { + + return this._fixedToCamera; + + }, + + set: function (value) { + + if (value) + { + this._fixedToCamera = true; + this.cameraOffset.set(this.x, this.y); + } + else + { + this._fixedToCamera = false; + } + + } + + }, + + /** + * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. + * + * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. + * @property {Phaser.Point} cameraOffset + */ + cameraOffset: new Phaser.Point() + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Health component provides the ability for Game Objects to have a `health` property +* that can be damaged and reset through game code. +* Requires the LifeSpan component. +* +* @class +*/ +Phaser.Component.Health = function () {}; + +Phaser.Component.Health.prototype = { + + /** + * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. + * + * It can be used in combination with the `damage` method or modified directly. + * + * @property {number} health + * @default + */ + health: 1, + + /** + * The Game Objects maximum health value. This works in combination with the `heal` method to ensure + * the health value never exceeds the maximum. + * + * @property {number} maxHealth + * @default + */ + maxHealth: 100, + + /** + * Damages the Game Object. This removes the given amount of health from the `health` property. + * + * If health is taken below or is equal to zero then the `kill` method is called. + * + * @method + * @param {number} amount - The amount to subtract from the current `health` value. + * @return {Phaser.Sprite} This instance. + */ + damage: function (amount) { + + if (this.alive) + { + this.health -= amount; + + if (this.health <= 0) + { + this.kill(); + } + } + + return this; + + }, + + /** + * Sets the health property of the Game Object to the given amount. + * Will never exceed the `maxHealth` value. + * + * @method + * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + setHealth: function (amount) { + + this.health = amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + + return this; + + }, + + /** + * Heal the Game Object. This adds the given amount of health to the `health` property. + * + * @method + * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ + heal: function (amount) { + + if (this.alive) + { + this.health += amount; + + if (this.health > this.maxHealth) + { + this.health = this.maxHealth; + } + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InCamera component checks if the Game Object intersects with the Game Camera. +* +* @class +*/ +Phaser.Component.InCamera = function () {}; + +Phaser.Component.InCamera.prototype = { + + /** + * Checks if this Game Objects bounds intersects with the Game Cameras bounds. + * + * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. + * + * An object outside the bounds can be considered for camera culling if it has the AutoCull component. + * + * @property {boolean} inCamera + * @readonly + */ + inCamera: { + + get: function() { + + return this.game.world.camera.view.intersects(this._bounds); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. +* +* @class +*/ +Phaser.Component.InputEnabled = function () {}; + +Phaser.Component.InputEnabled.prototype = { + + /** + * The Input Handler for this Game Object. + * + * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. + * + * After you have done this, this property will be a reference to the Phaser InputHandler. + * @property {Phaser.InputHandler|null} input + */ + input: null, + + /** + * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created + * for this Game Object and it will then start to process click / touch events and more. + * + * You can then access the Input Handler via `this.input`. + * + * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. + * + * If you set this property to false it will stop the Input Handler from processing any more input events. + * + * If you want to _temporarily_ disable input for a Game Object, then it's better to set + * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. + * You can then toggle this back on as needed. + * + * @property {boolean} inputEnabled + */ + inputEnabled: { + + get: function () { + + return (this.input && this.input.enabled); + + }, + + set: function (value) { + + if (value) + { + if (this.input === null) + { + this.input = new Phaser.InputHandler(this); + this.input.start(); + } + else if (this.input && !this.input.enabled) + { + this.input.start(); + } + } + else + { + if (this.input && this.input.enabled) + { + this.input.stop(); + } + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The InWorld component checks if a Game Object is within the Game World Bounds. +* An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. +* If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. +* +* @class +*/ +Phaser.Component.InWorld = function () {}; + +/** + * The InWorld component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.InWorld.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + // Cache the bounds if we need it + if (this.autoCull || this.checkWorldBounds) + { + this._bounds.copyFrom(this.getBounds()); + + this._bounds.x += this.game.camera.view.x; + this._bounds.y += this.game.camera.view.y; + + if (this.autoCull) + { + // Won't get rendered but will still get its transform updated + if (this.game.world.camera.view.intersects(this._bounds)) + { + this.renderable = true; + this.game.world.camera.totalInView++; + } + else + { + this.renderable = false; + + if (this.outOfCameraBoundsKill) + { + this.kill(); + return false; + } + } + } + + if (this.checkWorldBounds) + { + // The Sprite is already out of the world bounds, so let's check to see if it has come back again + if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds)) + { + this._outOfBoundsFired = false; + this.events.onEnterBounds$dispatch(this); + } + else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds)) + { + // The Sprite WAS in the screen, but has now left. + this._outOfBoundsFired = true; + this.events.onOutOfBounds$dispatch(this); + + if (this.outOfBoundsKill) + { + this.kill(); + return false; + } + } + } + } + + return true; + +}; + +Phaser.Component.InWorld.prototype = { + + /** + * If this is set to `true` the Game Object checks if it is within the World bounds each frame. + * + * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. + * + * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. + * + * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. + * + * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} checkWorldBounds + * @default + */ + checkWorldBounds: false, + + /** + * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. + * + * @property {boolean} outOfBoundsKill + * @default + */ + outOfBoundsKill: false, + + /** + * If this and the `autoCull` property are both set to `true`, then the `kill` method + * is called as soon as the Game Object leaves the camera bounds. + * + * @property {boolean} outOfCameraBoundsKill + * @default + */ + outOfCameraBoundsKill: false, + + /** + * @property {boolean} _outOfBoundsFired - Internal state var. + * @private + */ + _outOfBoundsFired: false, + + /** + * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. + * + * @property {boolean} inWorld + * @readonly + */ + inWorld: { + + get: function () { + + return this.game.world.bounds.intersects(this.getBounds()); + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* LifeSpan Component Features. +* +* @class +*/ +Phaser.Component.LifeSpan = function () {}; + +/** + * The LifeSpan component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.LifeSpan.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.lifespan > 0) + { + this.lifespan -= this.game.time.physicsElapsedMS; + + if (this.lifespan <= 0) + { + this.kill(); + return false; + } + } + + return true; + +}; + +Phaser.Component.LifeSpan.prototype = { + + /** + * A useful flag to control if the Game Object is alive or dead. + * + * This is set automatically by the Health components `damage` method should the object run out of health. + * Or you can toggle it via your game code. + * + * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. + * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. + * @property {boolean} alive + * @default + */ + alive: true, + + /** + * The lifespan allows you to give a Game Object a lifespan in milliseconds. + * + * Once the Game Object is 'born' you can set this to a positive value. + * + * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. + * When it reaches zero it will call the `kill` method. + * + * Very handy for particles, bullets, collectibles, or any other short-lived entity. + * + * @property {number} lifespan + * @default + */ + lifespan: 0, + + /** + * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. + * + * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. + * + * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. + * + * @method + * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. + * @return {PIXI.DisplayObject} This instance. + */ + revive: function (health) { + + if (health === undefined) { health = 100; } + + this.alive = true; + this.exists = true; + this.visible = true; + + if (typeof this.setHealth === 'function') + { + this.setHealth(health); + } + + if (this.events) + { + this.events.onRevived$dispatch(this); + } + + return this; + + }, + + /** + * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. + * + * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. + * + * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, + * it doesn't destroy the object or free it up from memory. + * + * If you don't need this Game Object any more you should call `destroy` instead. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ + kill: function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + if (this.events) + { + this.events.onKilled$dispatch(this); + } + + return this; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. +* +* @class +*/ +Phaser.Component.LoadTexture = function () {}; + +Phaser.Component.LoadTexture.prototype = { + + /** + * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) + * @private + */ + customRender: false, + + /** + * @property {Phaser.Rectangle} _frame - Internal cache var. + * @private + */ + _frame: null, + + /** + * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. + * + * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. + * + * You should only use `loadTexture` if you want to replace the base texture entirely. + * + * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. + * + * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. + * Doing this then sets the key to be the `frame` argument (the frame is set to zero). + * + * This allows you to create sprites using `load.image` during development, and then change them + * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' + * and swapping it to be the key of the atlas data. + * + * Note: You cannot use a RenderTexture as a texture for a TileSprite. + * + * @method + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. + */ + loadTexture: function (key, frame, stopAnimation) { + + if (key === Phaser.PENDING_ATLAS) + { + key = frame; + frame = 0; + } + else + { + frame = frame || 0; + } + + if ((stopAnimation || stopAnimation === undefined) && this.animations) + { + this.animations.stop(); + } + + this.key = key; + this.customRender = false; + var cache = this.game.cache; + + var setFrame = true; + var smoothed = !this.texture.baseTexture.scaleMode; + + if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture) + { + this.key = key.key; + this.setTexture(key); + } + else if (Phaser.BitmapData && key instanceof Phaser.BitmapData) + { + this.customRender = true; + + this.setTexture(key.texture); + + if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA)) + { + setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame); + } + else + { + setFrame = !this.animations.loadFrameData(key.frameData, 0); + } + } + else if (Phaser.Video && key instanceof Phaser.Video) + { + this.customRender = true; + + // This works from a reference, which probably isn't what we need here + var valid = key.texture.valid; + this.setTexture(key.texture); + this.setFrame(key.texture.frame.clone()); + key.onChangeSource.add(this.resizeFrame, this); + this.texture.valid = valid; + } + else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer) + { + // this.customRender = true; + + this.setTexture(PIXI.Texture.fromCanvas(key.canvas)); + } + else if (key instanceof PIXI.Texture) + { + this.setTexture(key); + } + else + { + var img = cache.getImage(key, true); + + this.key = img.key; + this.setTexture(new PIXI.Texture(img.base)); + + if (key === '__default') + { + this.texture.baseTexture.skipRender = true; + } + else + { + this.texture.baseTexture.skipRender = false; + } + + setFrame = !this.animations.loadFrameData(img.frameData, frame); + } + + if (setFrame) + { + this._frame = Phaser.Rectangle.clone(this.texture.frame); + } + + if (!smoothed) + { + this.texture.baseTexture.scaleMode = 1; + } + + }, + + /** + * Sets the texture frame the Game Object uses for rendering. + * + * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. + * + * @method + * @param {Phaser.Frame} frame - The Frame to be used by the texture. + */ + setFrame: function (frame) { + + this._frame = frame; + + this.texture.frame.x = frame.x; + this.texture.frame.y = frame.y; + this.texture.frame.width = frame.width; + this.texture.frame.height = frame.height; + + this.texture.crop.x = frame.x; + this.texture.crop.y = frame.y; + this.texture.crop.width = frame.width; + this.texture.crop.height = frame.height; + + if (frame.trimmed) + { + if (this.texture.trim) + { + this.texture.trim.x = frame.spriteSourceSizeX; + this.texture.trim.y = frame.spriteSourceSizeY; + this.texture.trim.width = frame.sourceSizeW; + this.texture.trim.height = frame.sourceSizeH; + } + else + { + this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH }; + } + + this.texture.width = frame.sourceSizeW; + this.texture.height = frame.sourceSizeH; + this.texture.frame.width = frame.sourceSizeW; + this.texture.frame.height = frame.sourceSizeH; + } + else if (!frame.trimmed && this.texture.trim) + { + this.texture.trim = null; + } + + if (frame.rotated) + { + this.texture.rotated = true; + } + + if (this.cropRect) + { + this.updateCrop(); + } + + this.texture.requiresReTint = true; + + this.texture._updateUvs(); + + if (this.tilingTexture) + { + this.refreshTexture = true; + } + + }, + + /** + * Resizes the Frame dimensions that the Game Object uses for rendering. + * + * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData + * it can be useful to adjust the dimensions directly in this way. + * + * @method + * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. + * @param {integer} width - The new width of the texture. + * @param {integer} height - The new height of the texture. + */ + resizeFrame: function (parent, width, height) { + + this.texture.frame.resize(width, height); + this.texture.setFrame(this.texture.frame); + + }, + + /** + * Resets the texture frame dimensions that the Game Object uses for rendering. + * + * @method + */ + resetFrame: function () { + + if (this._frame) + { + this.setFrame(this._frame); + } + + }, + + /** + * Gets or sets the current frame index of the texture being used to render this Game Object. + * + * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, + * for example: `player.frame = 4`. + * + * If the frame index given doesn't exist it will revert to the first frame found in the texture. + * + * If you are using a texture atlas then you should use the `frameName` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {integer} frame + */ + frame: { + + get: function () { + return this.animations.frame; + }, + + set: function (value) { + this.animations.frame = value; + } + + }, + + /** + * Gets or sets the current frame name of the texture being used to render this Game Object. + * + * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, + * for example: `player.frameName = "idle"`. + * + * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. + * + * If you are using a sprite sheet then you should use the `frame` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {string} frameName + */ + frameName: { + + get: function () { + return this.animations.frameName; + }, + + set: function (value) { + this.animations.frameName = value; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. +* +* @class +*/ +Phaser.Component.Overlap = function () {}; + +Phaser.Component.Overlap.prototype = { + + /** + * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, + * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. + * + * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. + * + * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. + * It should be fine for low-volume testing where physics isn't required. + * + * @method + * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. + * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. + */ + overlap: function (displayObject) { + + return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds()); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The PhysicsBody component manages the Game Objects physics body and physics enabling. +* It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. +* +* @class +*/ +Phaser.Component.PhysicsBody = function () {}; + +/** + * The PhysicsBody component preUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.preUpdate = function () { + + if (this.pendingDestroy) + { + this.destroy(); + return false; + } + + if (this.fresh && 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.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (this.body) + { + this.body.preUpdate(); + } + + this.fresh = false; + + this.preUpdateChildren(); + + return false; + } + + this.previousPosition.set(this.world.x, this.world.y); + this.previousRotation = this.rotation; + + if (!this._exists || !this.parent.exists) + { + this.renderOrderID = -1; + return false; + } + + return true; + +}; + +/** + * The PhysicsBody component postUpdate handler. + * Called automatically by the Game Object. + * + * @method + */ +Phaser.Component.PhysicsBody.postUpdate = function () { + + if (this.exists && this.body) + { + this.body.postUpdate(); + } + +}; + +Phaser.Component.PhysicsBody.prototype = { + + /** + * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated + * properties and methods via it. + * + * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. + * + * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object + * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. + * + * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. + * + * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, + * so the physics body is centered on the Game Object. + * + * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. + * + * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body + * @default + */ + body: null, + + /** + * The position of the Game Object on the x axis relative to the local coordinates of the parent. + * + * @property {number} x + */ + x: { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + }, + + /** + * The position of the Game Object on the y axis relative to the local coordinates of the parent. + * + * @property {number} y + */ + y: { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + if (this.body && !this.body.dirty) + { + this.body._reset = true; + } + + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Reset component allows a Game Object to be reset and repositioned to a new location. +* +* @class +*/ +Phaser.Component.Reset = function () {}; + +/** +* Resets the Game Object. +* +* This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, +* `visible` and `renderable` to true. +* +* If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. +* +* If this Game Object has a Physics Body it will reset the Body. +* +* @method +* @param {number} x - The x coordinate (in world space) to position the Game Object at. +* @param {number} y - The y coordinate (in world space) to position the Game Object at. +* @param {number} [health=1] - The health to give the Game Object if it has the Health component. +* @return {PIXI.DisplayObject} This instance. +*/ +Phaser.Component.Reset.prototype.reset = function (x, y, health) { + + if (health === undefined) { health = 1; } + + this.world.set(x, y); + this.position.set(x, y); + + this.fresh = true; + this.exists = true; + this.visible = true; + this.renderable = true; + + if (this.components.InWorld) + { + this._outOfBoundsFired = false; + } + + if (this.components.LifeSpan) + { + this.alive = true; + this.health = health; + } + + if (this.components.PhysicsBody) + { + if (this.body) + { + this.body.reset(x, y, false, false); + } + } + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. +* +* @class +*/ +Phaser.Component.ScaleMinMax = function () {}; + +Phaser.Component.ScaleMinMax.prototype = { + + /** + * The callback that will apply any scale limiting to the worldTransform. + * @property {function} transformCallback + */ + transformCallback: null, + + /** + * The context under which `transformCallback` is called. + * @property {object} transformCallbackContext + */ + transformCallbackContext: this, + + /** + * The minimum scale this Game Object will scale down to. + * + * It allows you to prevent a parent from scaling this Game Object lower than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMin + */ + scaleMin: null, + + /** + * The maximum scale this Game Object will scale up to. + * + * It allows you to prevent a parent from scaling this Game Object higher than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMax + */ + scaleMax: null, + + /** + * Adjust scaling limits, if set, to this Game Object. + * + * @method + * @private + * @param {Phaser.Matrix} wt - The updated worldTransform matrix. + */ + checkTransform: function (wt) { + + if (this.scaleMin) + { + if (wt.a < this.scaleMin.x) + { + wt.a = this.scaleMin.x; + } + + if (wt.d < this.scaleMin.y) + { + wt.d = this.scaleMin.y; + } + } + + if (this.scaleMax) + { + if (wt.a > this.scaleMax.x) + { + wt.a = this.scaleMax.x; + } + + if (wt.d > this.scaleMax.y) + { + wt.d = this.scaleMax.y; + } + } + + }, + + /** + * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. + * + * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored + * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. + * + * By setting these values you can carefully control how Game Objects deal with responsive scaling. + * + * If only one parameter is given then that value will be used for both scaleMin and scaleMax: + * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 + * + * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: + * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 + * + * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, + * or pass `null` for the `maxX` and `maxY` parameters. + * + * Call `setScaleMinMax(null)` to clear all previously set values. + * + * @method + * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to. + * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to. + * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to. + * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to. + */ + setScaleMinMax: function (minX, minY, maxX, maxY) { + + if (minY === undefined) + { + // 1 parameter, set all to it + minY = maxX = maxY = minX; + } + else if (maxX === undefined) + { + // 2 parameters, the first is min, the second max + maxX = maxY = minY; + minY = minX; + } + + if (minX === null) + { + this.scaleMin = null; + } + else + { + if (this.scaleMin) + { + this.scaleMin.set(minX, minY); + } + else + { + this.scaleMin = new Phaser.Point(minX, minY); + } + } + + if (maxX === null) + { + this.scaleMax = null; + } + else + { + if (this.scaleMax) + { + this.scaleMax.set(maxX, maxY); + } + else + { + this.scaleMax = new Phaser.Point(maxX, maxY); + } + } + + if (this.scaleMin === null) + { + this.transformCallback = null; + } + else + { + this.transformCallback = this.checkTransform; + this.transformCallbackContext = this; + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. +* +* @class +*/ +Phaser.Component.Smoothed = function () {}; + +Phaser.Component.Smoothed.prototype = { + + /** + * Enable or disable texture smoothing for this Game Object. + * + * It only takes effect if the Game Object is using an image based texture. + * + * Smoothing is enabled by default. + * + * @property {boolean} smoothed + */ + smoothed: { + + get: function () { + + return !this.texture.baseTexture.scaleMode; + + }, + + set: function (value) { + + if (value) + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 0; + this.texture.baseTexture.dirty(); + } + } + else + { + if (this.texture) + { + this.texture.baseTexture.scaleMode = 1; + this.texture.baseTexture.dirty(); + } + } + } + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectFactory is a quick way to create many common game objects +* using {@linkcode Phaser.Game#add `game.add`}. +* +* Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group. +* +* @class Phaser.GameObjectFactory +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectFactory = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectFactory.prototype = { + + /** + * Adds an existing display object to the game world. + * + * @method Phaser.GameObjectFactory#existing + * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object. + * @return {any} The child that was added to the World. + */ + existing: function (object) { + + return this.world.add(object); + + }, + + /** + * Weapons provide the ability to easily create a bullet pool and manager. + * + * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. + * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. + * + * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you + * can usually do with a Group, such as move it around the display list, iterate it, etc can be done + * to the bullets Group too. + * + * Bullets can have textures and even animations. You can control the speed at which they are fired, + * the firing rate, the firing angle, and even set things like gravity for them. + * + * @method Phaser.GameObjectFactory#weapon + * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group. + * @param {function} [bulletClass] - The Class of the bullets that are launched by this Weapon. See {@link Phaser.Weapon#bulletClass} + * @returns {Phaser.Weapon} A Weapon instance. + */ + weapon: function (quantity, key, frame, group, bulletClass) { + + var weapon = this.game.plugins.add(Phaser.Weapon); + + if (bulletClass) + { + weapon.bulletClass = bulletClass; + } + + weapon.createBullets(quantity, key, frame, group); + + return weapon; + + }, + + /** + * Create a new `Image` object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * + * It can still rotate, scale, crop and receive input events. + * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectFactory#image + * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Image} The newly created Image object. + */ + image: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Image(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. + * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), + * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. + * + * @method Phaser.GameObjectFactory#sprite + * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Sprite} The newly created Sprite object. + */ + sprite: function (x, y, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Sprite(this.game, x, y, key, frame)); + + }, + + /** + * Create a new Creature Animation object. + * + * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. + * + * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). + * + * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. + * + * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them + * loaded before your Phaser game boots. + * + * See the Phaser custom build process for more details. + * + * @method Phaser.GameObjectFactory#creature + * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Creature} The newly created Creature object. + */ + creature: function (x, y, key, mesh, group) { + + if (group === undefined) { group = this.world; } + + var obj = new Phaser.Creature(this.game, x, y, key, mesh); + + group.add(obj); + + return obj; + + }, + + /** + * Create a tween on a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectFactory#tween + * @param {object} object - Object the tween will be run on. + * @return {Phaser.Tween} The newly created Phaser.Tween object. + */ + tween: function (object) { + + return this.game.tweens.create(object); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectFactory#group + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates + * are automatically given a physics body. + * + * @method Phaser.GameObjectFactory#physicsGroup + * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc. + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.Group} The newly created Group. + */ + physicsGroup: function (physicsBodyType, parent, name, addToStage) { + + return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType); + + }, + + /** + * A SpriteBatch is a really fast version of a Phaser Group built solely for speed. + * Use when you need a lot of sprites or particles all sharing the same texture. + * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. + * + * @method Phaser.GameObjectFactory#spriteBatch + * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. + * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. + * @return {Phaser.SpriteBatch} The newly created Sprite Batch. + */ + spriteBatch: function (parent, name, addToStage) { + + if (parent === undefined) { parent = null; } + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectFactory#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectFactory#tileSprite + * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TileSprite} The newly created TileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); + + }, + + /** + * Creates a new Rope object. + * + * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js + * + * @method Phaser.GameObjectFactory#rope + * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Array} points - An array of {Phaser.Point}. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Rope} The newly created Rope object. + */ + rope: function (x, y, key, frame, points, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Rope(this.game, x, y, key, frame, points)); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectFactory#text + * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {string} [text=''] - The text string that will be displayed. + * @param {object} [style] - The style object containing style attributes like font, font size , etc. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Text(this.game, x, y, text, style)); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectFactory#button + * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] - The function to call when this button is pressed + * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Button} The newly created Button object. + */ + button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectFactory#graphics + * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.Graphics(this.game, x, y)); + + }, + + /** + * Create a new Emitter. + * + * A particle emitter can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accordingly. + * + * @method Phaser.GameObjectFactory#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles)); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectFactory#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectFactory#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, group) { + + if (group === undefined) { group = this.world; } + + return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size)); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectFactory#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {Phaser.Tilemap} The newly created tilemap object. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectFactory#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a Video object. + * + * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. + * + * @method Phaser.GameObjectFactory#video + * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. + * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) + * @return {Phaser.Video} The newly created Video object. + */ + video: function (key, url) { + + return new Phaser.Video(this.game, key, url); + + }, + + /** + * Create a BitmapData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectFactory#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectFactory#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + }, + + /** + * Add a new Plugin into the PluginManager. + * + * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.GameObjectFactory#plugin + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ + plugin: function (plugin) { + + return this.game.plugins.add(plugin); + + } + +}; + +Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world. +* The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}. +* +* @class Phaser.GameObjectCreator +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.GameObjectCreator = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ + this.game = game; + + /** + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ + this.world = this.game.world; + +}; + +Phaser.GameObjectCreator.prototype = { + + /** + * Create a new Image object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectCreator#image + * @param {number} x - X position of the image. + * @param {number} y - Y position of the image. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Image} the newly created sprite object. + */ + image: function (x, y, key, frame) { + + return new Phaser.Image(this.game, x, y, key, frame); + + }, + + /** + * Create a new Sprite with specific position and sprite sheet key. + * + * @method Phaser.GameObjectCreator#sprite + * @param {number} x - X position of the new sprite. + * @param {number} y - Y position of the new sprite. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Sprite} the newly created sprite object. + */ + sprite: function (x, y, key, frame) { + + return new Phaser.Sprite(this.game, x, y, key, frame); + + }, + + /** + * Create a tween object for a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectCreator#tween + * @param {object} obj - Object the tween will be run on. + * @return {Phaser.Tween} The Tween object. + */ + tween: function (obj) { + + return new Phaser.Tween(obj, this.game, this.game.tweens); + + }, + + /** + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectCreator#group + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ + group: function (parent, name, addToStage, enableBody, physicsBodyType) { + + return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); + + }, + + /** + * Create a new SpriteBatch. + * + * @method Phaser.GameObjectCreator#spriteBatch + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.SpriteBatch} The newly created group. + */ + spriteBatch: function (parent, name, addToStage) { + + if (name === undefined) { name = 'group'; } + if (addToStage === undefined) { addToStage = false; } + + return new Phaser.SpriteBatch(this.game, parent, name, addToStage); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + audio: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new AudioSprite object. + * + * @method Phaser.GameObjectCreator#audioSprite + * @param {string} key - The Game.cache key of the sound that this object will use. + * @return {Phaser.AudioSprite} The newly created AudioSprite object. + */ + audioSprite: function (key) { + + return this.game.sound.addSprite(key); + + }, + + /** + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ + sound: function (key, volume, loop, connect) { + + return this.game.sound.add(key, volume, loop, connect); + + }, + + /** + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectCreator#tileSprite + * @param {number} x - The x coordinate (in world space) to position the TileSprite at. + * @param {number} y - The y coordinate (in world space) to position the TileSprite at. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.TileSprite} The newly created tileSprite object. + */ + tileSprite: function (x, y, width, height, key, frame) { + + return new Phaser.TileSprite(this.game, x, y, width, height, key, frame); + + }, + + /** + * Creates a new Rope object. + * + * @method Phaser.GameObjectCreator#rope + * @param {number} x - The x coordinate (in world space) to position the Rope at. + * @param {number} y - The y coordinate (in world space) to position the Rope at. + * @param {number} width - The width of the Rope. + * @param {number} height - The height of the Rope. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.Rope} The newly created rope object. + */ + rope: function (x, y, key, frame, points) { + + return new Phaser.Rope(this.game, x, y, key, frame, points); + + }, + + /** + * Creates a new Text object. + * + * @method Phaser.GameObjectCreator#text + * @param {number} x - X position of the new text object. + * @param {number} y - Y position of the new text object. + * @param {string} text - The actual text that will be written. + * @param {object} style - The style object containing style attributes like font, font size , etc. + * @return {Phaser.Text} The newly created text object. + */ + text: function (x, y, text, style) { + + return new Phaser.Text(this.game, x, y, text, style); + + }, + + /** + * Creates a new Button object. + * + * @method Phaser.GameObjectCreator#button + * @param {number} [x] X position of the new button object. + * @param {number} [y] Y position of the new button object. + * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] The function to call when this button is pressed + * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @return {Phaser.Button} The newly created button object. + */ + 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); + + }, + + /** + * Creates a new Graphics object. + * + * @method Phaser.GameObjectCreator#graphics + * @param {number} [x=0] - X position of the new graphics object. + * @param {number} [y=0] - Y position of the new graphics object. + * @return {Phaser.Graphics} The newly created graphics object. + */ + graphics: function (x, y) { + + return new Phaser.Graphics(this.game, x, y); + + }, + + /** + * Creat a new Emitter. + * + * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accorindgly. + * + * @method Phaser.GameObjectCreator#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Emitter} The newly created emitter object. + */ + emitter: function (x, y, maxParticles) { + + return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles); + + }, + + /** + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectCreator#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ + 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); + + }, + + /** + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectCreator#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ + bitmapText: function (x, y, font, text, size, align) { + + return new Phaser.BitmapText(this.game, x, y, font, text, size, align); + + }, + + /** + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectCreator#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + */ + tilemap: function (key, tileWidth, tileHeight, width, height) { + + return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); + + }, + + /** + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectCreator#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ + renderTexture: function (width, height, key, addToCache) { + + if (key === undefined || key === '') { key = this.game.rnd.uuid(); } + if (addToCache === undefined) { addToCache = false; } + + var texture = new Phaser.RenderTexture(this.game, width, height, key); + + if (addToCache) + { + this.game.cache.addRenderTexture(key, texture); + } + + return texture; + + }, + + /** + * Create a BitmpaData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectCreator#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ + bitmapData: function (width, height, key, addToCache) { + + if (addToCache === undefined) { addToCache = false; } + if (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; + + }, + + /** + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectCreator#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ + filter: function (filter) { + + var args = Array.prototype.slice.call(arguments, 1); + + var filter = new Phaser.Filter[filter](this.game); + + filter.init.apply(filter, args); + + return filter; + + } + +}; + +Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Sprites are the lifeblood of your game, used for nearly everything visual. +* +* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. +* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), +* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. +* +* @class Phaser.Sprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. If this argument is omitted, the sprite will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Sprite = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.SPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Sprite.prototype.constructor = Phaser.Sprite; + +Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.Sprite +* @return {boolean} True if the Sprite was rendered, otherwise false. +*/ +Phaser.Sprite.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image is a light-weight object you can use to display anything that doesn't need health, physics, or complex position monitoring. +* +* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. +* +* @class Phaser.Image +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. If this argument is omitted, the image will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. +* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Image = function (game, x, y, key, frame) { + + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.IMAGE; + + PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.Image.prototype.constructor = Phaser.Image; + +Phaser.Component.Core.install.call(Phaser.Image.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Image.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Image#preUpdate +* @memberof Phaser.Image +*/ +Phaser.Image.prototype.preUpdate = function() { + + if (!this.preUpdateInWorld() || !this.preUpdateLifeSpan()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. +* +* The four states a Button responds to are: +* +* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. +* * 'Out' - when the Pointer that was previously over the Button moves out of it. +* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. +* * 'Up' - when the Pointer that was pressed down on the Button is released again. +* +* A different texture/frame and activation sound can be specified for any of the states. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. +* +* @class Phaser.Button +* @constructor +* @extends Phaser.Image +* @param {Phaser.Game} game Current game instance. +* @param {number} [x=0] - X position of the Button. +* @param {number} [y=0] - Y position of the Button. +* @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button. +* @param {function} [callback] - The function to call when this Button is pressed, receiving `this` (the Button), `pointer`, and `isOver` (see {@link Phaser.Events#onInputUp}.) +* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) { + + x = x || 0; + y = y || 0; + key = key || null; + callback = callback || null; + callbackContext = callbackContext || this; + + Phaser.Image.call(this, game, x, y, key, outFrame); + + /** + * The Phaser Object Type. + * @property {number} type + * @readonly + */ + this.type = Phaser.BUTTON; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * The name or ID of the Over state frame. + * @property {string|integer} onOverFrame + * @private + */ + this._onOverFrame = null; + + /** + * The name or ID of the Out state frame. + * @property {string|integer} onOutFrame + * @private + */ + this._onOutFrame = null; + + /** + * The name or ID of the Down state frame. + * @property {string|integer} onDownFrame + * @private + */ + this._onDownFrame = null; + + /** + * The name or ID of the Up state frame. + * @property {string|integer} onUpFrame + * @private + */ + this._onUpFrame = null; + + /** + * The Sound to be played when this Buttons Over state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound + * @readonly + */ + this.onOverSound = null; + + /** + * The Sound to be played when this Buttons Out state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound + * @readonly + */ + this.onOutSound = null; + + /** + * The Sound to be played when this Buttons Down state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound + * @readonly + */ + this.onDownSound = null; + + /** + * The Sound to be played when this Buttons Up state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound + * @readonly + */ + this.onUpSound = null; + + /** + * The Sound Marker used in conjunction with the onOverSound. + * @property {string} onOverSoundMarker + * @readonly + */ + this.onOverSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onOutSound. + * @property {string} onOutSoundMarker + * @readonly + */ + this.onOutSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onDownSound. + * @property {string} onDownSoundMarker + * @readonly + */ + this.onDownSoundMarker = ''; + + /** + * The Sound Marker used in conjunction with the onUpSound. + * @property {string} onUpSoundMarker + * @readonly + */ + this.onUpSoundMarker = ''; + + /** + * The Signal (or event) dispatched when this Button is in an Over state. + * @property {Phaser.Signal} onInputOver + */ + this.onInputOver = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Out state. + * @property {Phaser.Signal} onInputOut + */ + this.onInputOut = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Down state. + * @property {Phaser.Signal} onInputDown + */ + this.onInputDown = new Phaser.Signal(); + + /** + * The Signal (or event) dispatched when this Button is in an Up state. + * @property {Phaser.Signal} onInputUp + */ + this.onInputUp = new Phaser.Signal(); + + /** + * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. + * The frame will still be changed as applicable. + * + * @property {boolean} onOverMouseOnly + * @default + */ + this.onOverMouseOnly = true; + + /** + * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}. + * + * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. + * + * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR + */ + this.justReleasedPreventsOver = Phaser.PointerMode.CONTACT; + + /** + * When true the the texture frame will not be automatically switched on up/down/over/out events. + * @property {boolean} freezeFrames + * @default + */ + this.freezeFrames = false; + + /** + * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". + * + * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control. + * + * @property {boolean|Phaser.PointerMode} forceOut=false + * @default + */ + this.forceOut = false; + + this.inputEnabled = true; + + this.input.start(0, true); + + this.input.useHandCursor = true; + + this.setFrames(overFrame, outFrame, downFrame, upFrame); + + if (callback !== null) + { + this.onInputUp.add(callback, callbackContext); + } + + // Redirect the input events to here so we can handle animation updates, etc + this.events.onInputOver.add(this.onInputOverHandler, this); + this.events.onInputOut.add(this.onInputOutHandler, this); + this.events.onInputDown.add(this.onInputDownHandler, this); + this.events.onInputUp.add(this.onInputUpHandler, this); + +}; + +Phaser.Button.prototype = Object.create(Phaser.Image.prototype); +Phaser.Button.prototype.constructor = Phaser.Button; + +// State constants; local only. These are tied to property names in Phaser.Button. +var STATE_OVER = 'Over'; +var STATE_OUT = 'Out'; +var STATE_DOWN = 'Down'; +var STATE_UP = 'Up'; + +/** +* Clears all of the frames set on this Button. +* +* @method Phaser.Button#clearFrames +*/ +Phaser.Button.prototype.clearFrames = function () { + + this.setFrames(null, null, null, null); + +}; + +/** +* Set the frame name/ID for the given state. +* +* @method Phaser.Button#setStateFrame +* @private +* @param {object} state - See `STATE_*` +* @param {number|string} frame - The number or string representing the frame. +* @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true. +*/ +Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately) +{ + var frameKey = '_on' + state + 'Frame'; + + if (frame !== null) // not null or undefined + { + this[frameKey] = frame; + + if (switchImmediately) + { + this.changeStateFrame(state); + } + } + else + { + this[frameKey] = null; + } + +}; + +/** +* Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen". +* +* @method Phaser.Button#changeStateFrame +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if the frame was assigned a value, possibly the same one it already had. +*/ +Phaser.Button.prototype.changeStateFrame = function (state) { + + if (this.freezeFrames) + { + return false; + } + + var frameKey = '_on' + state + 'Frame'; + var frame = this[frameKey]; + + if (typeof frame === 'string') + { + this.frameName = frame; + return true; + } + else if (typeof frame === 'number') + { + this.frame = frame; + return true; + } + else + { + return false; + } + +}; + +/** +* Used to manually set the frames that will be used for the different states of the Button. +* +* Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. +* +* @method Phaser.Button#setFrames +* @public +* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. +* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. +* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. +* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. +*/ +Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) { + + this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver()); + this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver()); + this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown()); + this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp()); + +}; + +/** +* Set the sound/marker for the given state. +* +* @method Phaser.Button#setStateSound +* @private +* @param {object} state - See `STATE_*` +* @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound. +* @param {string} [marker=''] - Sound marker. +*/ +Phaser.Button.prototype.setStateSound = function (state, sound, marker) { + + var soundKey = 'on' + state + 'Sound'; + var markerKey = 'on' + state + 'SoundMarker'; + + if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite) + { + this[soundKey] = sound; + this[markerKey] = typeof marker === 'string' ? marker : ''; + } + else + { + this[soundKey] = null; + this[markerKey] = ''; + } + +}; + +/** +* Play the sound for the given state, _if_ the state has a sound assigned. +* +* @method Phaser.Button#playStateSound +* @private +* @param {object} state - See `STATE_*` +* @return {boolean} True only if a sound was played. +*/ +Phaser.Button.prototype.playStateSound = function (state) { + + var soundKey = 'on' + state + 'Sound'; + var sound = this[soundKey]; + + if (sound) + { + var markerKey = 'on' + state + 'SoundMarker'; + var marker = this[markerKey]; + + sound.play(marker); + return true; + } + else + { + return false; + } + +}; + +/** +* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. +* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. +* +* Call this function with no parameters to reset all sounds on this Button. +* +* @method Phaser.Button#setSounds +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound. +* @param {string} [overMarker] - Over Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound. +* @param {string} [downMarker] - Down Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound. +* @param {string} [outMarker] - Out Button Sound Marker. +* @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound. +* @param {string} [upMarker] - Up Button Sound Marker. +*/ +Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) { + + this.setStateSound(STATE_OVER, overSound, overMarker); + this.setStateSound(STATE_OUT, outSound, outMarker); + this.setStateSound(STATE_DOWN, downSound, downMarker); + this.setStateSound(STATE_UP, upSound, upMarker); + +}; + +/** +* The Sound to be played when a Pointer moves over this Button. +* +* @method Phaser.Button#setOverSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOverSound = function (sound, marker) { + + this.setStateSound(STATE_OVER, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer moves out of this Button. +* +* @method Phaser.Button#setOutSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setOutSound = function (sound, marker) { + + this.setStateSound(STATE_OUT, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer presses down on this Button. +* +* @method Phaser.Button#setDownSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setDownSound = function (sound, marker) { + + this.setStateSound(STATE_DOWN, sound, marker); + +}; + +/** +* The Sound to be played when a Pointer has pressed down and is released from this Button. +* +* @method Phaser.Button#setUpSound +* @public +* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. +* @param {string} [marker] - A Sound Marker that will be used in the playback. +*/ +Phaser.Button.prototype.setUpSound = function (sound, marker) { + + this.setStateSound(STATE_UP, sound, marker); + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOverHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) { + + if (pointer.justReleased() && + (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode) + { + // If the Pointer was only just released then we don't fire an over event + return; + } + + this.changeStateFrame(STATE_OVER); + + if (this.onOverMouseOnly && !pointer.isMouse) + { + return; + } + + this.playStateSound(STATE_OVER); + + if (this.onInputOver) + { + this.onInputOver.dispatch(this, pointer); + } + +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputOutHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_OUT); + + this.playStateSound(STATE_OUT); + + if (this.onInputOut) + { + this.onInputOut.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputDownHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) { + + this.changeStateFrame(STATE_DOWN); + + this.playStateSound(STATE_DOWN); + + if (this.onInputDown) + { + this.onInputDown.dispatch(this, pointer); + } +}; + +/** +* Internal function that handles input events. +* +* @method Phaser.Button#onInputUpHandler +* @protected +* @param {Phaser.Button} sprite - The Button that the event occurred on. +* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. +*/ +Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) { + + this.playStateSound(STATE_UP); + + // Input dispatched early, before state change (but after sound) + if (this.onInputUp) + { + this.onInputUp.dispatch(this, pointer, isOver); + } + + if (this.freezeFrames) + { + return; + } + + if (this.forceOut === true || (this.forceOut & pointer.pointerMode) === pointer.pointerMode) + { + this.changeStateFrame(STATE_OUT); + } + else + { + var changedUp = this.changeStateFrame(STATE_UP); + if (!changedUp) + { + // No Up frame to show.. + if (isOver) + { + this.changeStateFrame(STATE_OVER); + } + else + { + this.changeStateFrame(STATE_OUT); + } + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. +* It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over +* 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled +* Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. +* +* Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. +* +* @class Phaser.SpriteBatch +* @extends Phaser.Group +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. +* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. +* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. +*/ +Phaser.SpriteBatch = function (game, parent, name, addToStage) { + + if (parent === undefined || parent === null) { parent = game.world; } + + Phaser.Group.call(this, game, parent, name, addToStage); + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.SPRITEBATCH; + + /** + * @property {Object} fastSpriteBatch - WebGL Batch Shader. + * @private + */ + this.fastSpriteBatch = null; + + /** + * @property {boolean} ready - Internal flag. + * @private + */ + this.ready = false; + +}; + +Phaser.SpriteBatch.prototype = Object.create(Phaser.Group.prototype); + +Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch; + +/** +* Renders the Sprite Batch using the WebGL renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + if (!this.ready) + { + this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(renderSession.gl); + + this.ready = true; + } + + if (this.fastSpriteBatch.gl !== renderSession.gl) + { + this.fastSpriteBatch.setContext(renderSession.gl); + } + + renderSession.spriteBatch.stop(); + + renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader); + + this.fastSpriteBatch.begin(this, renderSession); + this.fastSpriteBatch.render(this); + + renderSession.spriteBatch.start(); + +}; + +/** +* Renders the Sprite Batch using the Canvas renderer. +* +* @private +* @method +* @memberof Phaser.SpriteBatch +* @param {RenderSession} renderSession +*/ +Phaser.SpriteBatch.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || this.alpha <= 0 || !this.children.length) + { + return; + } + + var context = renderSession.context; + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + var transform = this.worldTransform; + + var isRotated = true; + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + var texture = child.texture; + var frame = texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) + { + // If rotation === 0 we can avoid setTransform + + if (isRotated) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty); + isRotated = false; + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5 + renderSession.shakeX) | 0, + ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5 + renderSession.shakeY) | 0, + frame.width * child.scale.x, + frame.height * child.scale.y); + } + else + { + if (!isRotated) + { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + var tx = (childTransform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (childTransform.ty * renderSession.resolution) + renderSession.shakeY; + + // allow for trimming + + if (renderSession.roundPixels) + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx, ty); + } + + context.drawImage( + texture.baseTexture.source, + frame.x, + frame.y, + frame.width, + frame.height, + ((child.anchor.x) * (-frame.width) + 0.5) | 0, + ((child.anchor.y) * (-frame.height) + 0.5) | 0, + frame.width, + frame.height); + } + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. +* A single BitmapData can be used as the texture for one or many Images / Sprites. +* So if you need to dynamically create a Sprite texture then they are a good choice. +* +* Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't +* live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy +* in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. +* +* @class Phaser.BitmapData +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string} key - Internal Phaser reference key for the BitmapData. +* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value. +* @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. +*/ +Phaser.BitmapData = function (game, key, width, height, skipPool) { + + if (width === undefined || width === 0) { width = 256; } + if (height === undefined || height === 0) { height = 256; } + if (skipPool === undefined) { skipPool = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the BitmapData in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} width - The width of the BitmapData in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the BitmapData in pixels. + */ + this.height = height; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. + * @default + */ + this.canvas = Phaser.Canvas.create(this, width, height, null, skipPool); + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + * @default + */ + this.context = this.canvas.getContext('2d', { alpha: true }); + + /** + * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context. + */ + this.ctx = this.context; + + /** + * @property {string} smoothProperty - The context property needed for smoothing this Canvas. + */ + this.smoothProperty = (game.renderType === Phaser.CANVAS) ? game.renderer.renderSession.smoothProperty : Phaser.Canvas.getSmoothingPrefix(this.context); + + /** + * @property {ImageData} imageData - The context image data. + * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. + * This property is updated automatically after the first game loop, according to the dirty flag property. + */ + this.imageData = this.context.getImageData(0, 0, width, height); + + /** + * A Uint8ClampedArray view into BitmapData.buffer. + * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) + * @property {Uint8ClampedArray} data + */ + this.data = null; + + if (this.imageData) + { + this.data = this.imageData.data; + } + + /** + * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer. + */ + this.pixels = null; + + /** + * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData. + */ + if (this.data) + { + 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; + } + } + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + this.baseTexture = new PIXI.BaseTexture(this.canvas, null, this.game.resolution); + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering. + */ + this.frameData = new Phaser.FrameData(); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. + * @default + */ + this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData')); + + this.texture.frame = this.textureFrame; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.BITMAPDATA; + + /** + * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} dirty - If dirty this BitmapData will be re-rendered. + */ + this.dirty = false; + + // Aliases + this.cls = this.clear; + + /** + * @property {number} _image - Internal cache var. + * @private + */ + this._image = null; + + /** + * @property {Phaser.Point} _pos - Internal cache var. + * @private + */ + this._pos = new Phaser.Point(); + + /** + * @property {Phaser.Point} _size - Internal cache var. + * @private + */ + this._size = new Phaser.Point(); + + /** + * @property {Phaser.Point} _scale - Internal cache var. + * @private + */ + this._scale = new Phaser.Point(); + + /** + * @property {number} _rotate - Internal cache var. + * @private + */ + this._rotate = 0; + + /** + * @property {object} _alpha - Internal cache var. + * @private + */ + this._alpha = { prev: 1, current: 1 }; + + /** + * @property {Phaser.Point} _anchor - Internal cache var. + * @private + */ + this._anchor = new Phaser.Point(); + + /** + * @property {number} _tempR - Internal cache var. + * @private + */ + this._tempR = 0; + + /** + * @property {number} _tempG - Internal cache var. + * @private + */ + this._tempG = 0; + + /** + * @property {number} _tempB - Internal cache var. + * @private + */ + this._tempB = 0; + + /** + * @property {Phaser.Circle} _circle - Internal cache var. + * @private + */ + this._circle = new Phaser.Circle(); + + /** + * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods. + * @private + */ + this._swapCanvas = undefined; + +}; + +Phaser.BitmapData.prototype = { + + /** + * Shifts the contents of this BitmapData by the distances given. + * + * The image will wrap-around the edges on all sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#move + * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + move: function (x, y, wrap) { + + if (x !== 0) + { + this.moveH(x, wrap); + } + + if (y !== 0) + { + this.moveV(y, wrap); + } + + return this; + + }, + + /** + * Shifts the contents of this BitmapData horizontally. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveH + * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveH: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var h = this.height; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving to the left + var w = this.width - distance; + + // Left-hand chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h); + } + else + { + // Moving to the right + var w = this.width - distance; + + // Right-hand chunk + if (wrap) + { + ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Shifts the contents of this BitmapData vertically. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveV + * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + moveV: function (distance, wrap) { + + if (wrap === undefined) { wrap = true; } + + if (this._swapCanvas === undefined) + { + this._swapCanvas = Phaser.CanvasPool.create(this, this.width, this.height); + } + + var c = this._swapCanvas; + var ctx = c.getContext('2d'); + var w = this.width; + var src = this.canvas; + + ctx.clearRect(0, 0, this.width, this.height); + + if (distance < 0) + { + distance = Math.abs(distance); + + // Moving up + var h = this.height - distance; + + // Top chunk + if (wrap) + { + ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h); + } + else + { + // Moving down + var h = this.height - distance; + + // Bottom chunk + if (wrap) + { + ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance); + } + + // Rest of the image + ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h); + } + + this.clear(); + + return this.copy(this._swapCanvas); + + }, + + /** + * Updates the given objects so that they use this BitmapData as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.BitmapData#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. + * The source game object is not modified by this operation. + * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. + * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. + * + * @method Phaser.BitmapData#load + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + load: function (source) { + + if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + } + + if (source) + { + this.resize(source.width, source.height); + this.cls(); + } + else + { + return; + } + + this.draw(source); + + this.update(); + + return this; + + }, + + /** + * Clears the BitmapData context using a clearRect. + * + * @method Phaser.BitmapData#cls + */ + + /** + * Clears the BitmapData context using a clearRect. + * + * You can optionally define the area to clear. + * If the arguments are left empty it will clear the entire canvas. + * + * You may need to call BitmapData.update after this in order to clear out the pixel data, + * but Phaser will not do this automatically for you. + * + * @method Phaser.BitmapData#clear + * @param {number} [x=0] - The x coordinate of the top-left of the area to clear. + * @param {number} [y=0] - The y coordinate of the top-left of the area to clear. + * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width. + * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + clear: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + this.context.clearRect(x, y, width, height); + + this.dirty = true; + + return this; + + }, + + /** + * Fills the BitmapData with the given color. + * + * @method Phaser.BitmapData#fill + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} [a=1] - The alpha color value, between 0 and 1. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + fill: function (r, g, b, a) { + + if (a === undefined) { a = 1; } + + this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; + this.context.fillRect(0, 0, this.width, this.height); + this.dirty = true; + + return this; + + }, + + /** + * Creates a new {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image} element by converting this BitmapDatas canvas into a dataURL. + * + * The image is then stored in the {@link Phaser.Cache image Cache} using the key given. + * + * Finally a {@link PIXI.Texture} is created based on the image and returned. + * + * You can apply the texture to a sprite or any other supporting object by using either the + * key or the texture. First call `generateTexture`: + * + * ```javascript + * var texture = bitmapdata.generateTexture('ball'); + * ``` + * + * Then you can either apply the texture to a sprite: + * + * ```javascript + * game.add.sprite(0, 0, texture); + * ``` + * + * or by using the string based key: + * + * ```javascript + * game.add.sprite(0, 0, 'ball'); + * ``` + * + * Most browsers now load the image data asynchronously, so you should use a callback: + * + * ```javascript + * bitmapdata.generateTexture('ball', function (texture) { + * game.add.sprite(0, 0, texture); + * // or + * game.add.sprite(0, 0, 'ball'); + * }); + * ``` + * + * If this BitmapData is available during preload, you can use {@link Phaser.Loader#imageFromBitmapData} instead. + * + * @method Phaser.BitmapData#generateTexture + * @param {string} key - The key which will be used to store the image in the Cache. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {PIXI.Texture|null} The newly generated texture, or `null` if a callback was passed and the texture isn't available yet. + */ + generateTexture: function (key, callback, callbackContext) { + + var cache = this.game.cache; + var image = new Image(); + + if (callback) + { + image.onload = function () { + var obj = cache.addImage(key, '', image); + var texture = new PIXI.Texture(obj.base); + + callback.call(callbackContext || null, texture); + + image.onload = null; + }; + } + + image.src = this.canvas.toDataURL("image/png"); + + if (!callback) + { + var obj = cache.addImage(key, '', image); + + return new PIXI.Texture(obj.base); + } + + return null; + + }, + + /** + * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. + * + * @method Phaser.BitmapData#resize + * @param {integer} width - The new width of the BitmapData. + * @param {integer} height - The new height of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + resize: function (width, height) { + + if (width !== this.width || height !== this.height) + { + this.width = width; + this.height = height; + + this.canvas.width = width; + this.canvas.height = height; + + if (this._swapCanvas !== undefined) + { + this._swapCanvas.width = width; + this._swapCanvas.height = height; + } + + this.baseTexture.width = width; + this.baseTexture.height = height; + + this.textureFrame.width = width; + this.textureFrame.height = height; + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.update(); + this.dirty = true; + } + + return this; + + }, + + /** + * This re-creates the BitmapData.imageData from the current context. + * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. + * If not given the dimensions defaults to the full size of the context. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.BitmapData#update + * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from. + * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from. + * @param {number} [width=1] - The width of the image data area. + * @param {number} [height=1] - The height of the image data area. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + update: function (x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = Math.max(1, this.width); } + if (height === undefined) { height = Math.max(1, this.height); } + + this.imageData = this.context.getImageData(x, y, width, height); + this.data = this.imageData.data; + + 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; + } + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. + * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. + * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. + * The `color` property is an Int32 of the full color. Note the endianess of this will change per system. + * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. + * The callback will also be sent the pixels x and y coordinates respectively. + * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. + * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. + * + * @method Phaser.BitmapData#processPixelRGB + * @param {function} callback - The callback that will be sent each pixel color object to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixelRGB: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = Phaser.Color.createColor(); + var result = { r: 0, g: 0, b: 0, a: 0 }; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel); + + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== false && result !== null && result !== undefined) + { + this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false); + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. + * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. + * Note that the format of the color received will be different depending on if the system is big or little endian. + * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. + * The callback will also be sent the pixels x and y coordinates respectively. + * + * @method Phaser.BitmapData#processPixel + * @param {function} callback - The callback that will be sent each pixel color to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + processPixel: function (callback, callbackContext, x, y, width, height) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + + var w = x + width; + var h = y + height; + var pixel = 0; + var result = 0; + var dirty = false; + + for (var ty = y; ty < h; ty++) + { + for (var tx = x; tx < w; tx++) + { + pixel = this.getPixel32(tx, ty); + result = callback.call(callbackContext, pixel, tx, ty); + + if (result !== pixel) + { + this.pixels[ty * this.width + tx] = result; + dirty = true; + } + } + } + + if (dirty) + { + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + } + + return this; + + }, + + /** + * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. + * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. + * + * @method Phaser.BitmapData#replaceRGB + * @param {number} r1 - The red color value to be replaced. Between 0 and 255. + * @param {number} g1 - The green color value to be replaced. Between 0 and 255. + * @param {number} b1 - The blue color value to be replaced. Between 0 and 255. + * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255. + * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255. + * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255. + * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255. + * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255. + * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) { + + var sx = 0; + var sy = 0; + var w = this.width; + var h = this.height; + var source = Phaser.Color.packPixel(r1, g1, b1, a1); + + if (region !== undefined && region instanceof Phaser.Rectangle) + { + sx = region.x; + sy = region.y; + w = region.width; + h = region.height; + } + + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + if (this.getPixel32(sx + x, sy + y) === source) + { + this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false); + } + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * + * @method Phaser.BitmapData#setHSL + * @param {number} [h=null] - The hue, in the range 0 - 1. + * @param {number} [s=null] - The saturation, in the range 0 - 1. + * @param {number} [l=null] - The lightness, in the range 0 - 1. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setHSL: function (h, s, l, region) { + + var bHaveH = h || h === 0; + var bHaveS = s || s === 0; + var bHaveL = l || l === 0; + + if (!bHaveH && !bHaveS && !bHaveL) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (bHaveH) + { + pixel.h = h; + } + + if (bHaveS) + { + pixel.s = s; + } + + if (bHaveL) + { + pixel.l = l; + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * Shifting will add the given value onto the current h, s and l values, not replace them. + * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. + * + * @method Phaser.BitmapData#shiftHSL + * @param {number} [h=null] - The amount to shift the hue by. Within [-1, 1]. + * @param {number} [s=null] - The amount to shift the saturation by. Within [-1, 1]. + * @param {number} [l=null] - The amount to shift the lightness by. Within [-1, 1]. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shiftHSL: function (h, s, l, region) { + + if (h === undefined || h === null) { h = false; } + if (s === undefined || s === null) { s = false; } + if (l === undefined || l === null) { l = false; } + + if (!h && !s && !l) + { + return; + } + + if (region === undefined) + { + region = new Phaser.Rectangle(0, 0, this.width, this.height); + } + + var pixel = Phaser.Color.createColor(); + + for (var y = region.y; y < region.bottom; y++) + { + for (var x = region.x; x < region.right; x++) + { + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true); + + if (h) + { + pixel.h = this.game.math.wrap(pixel.h + h, 0, 1); + } + + if (s) + { + pixel.s = this.game.math.clamp(pixel.s + s, 0, 1); + } + + if (l) + { + pixel.l = this.game.math.clamp(pixel.l + l, 0, 1); + } + + Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel); + this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false); + } + } + + this.context.putImageData(this.imageData, 0, 0); + this.dirty = true; + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green, blue and alpha values. + * + * @method Phaser.BitmapData#setPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel32: function (x, y, red, green, blue, alpha, immediate) { + + if (immediate === undefined) { immediate = true; } + + if (x >= 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; + } + } + + return this; + + }, + + /** + * Sets the color of the given pixel to the specified red, green and blue values. + * + * @method Phaser.BitmapData#setPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + setPixel: function (x, y, red, green, blue, immediate) { + + return this.setPixel32(x, y, red, green, blue, 255, immediate); + + }, + + /** + * Get the color of a specific pixel in the context into a color object. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + getPixel: function (x, y, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var index = ~~(x + (y * this.width)); + + index *= 4; + + out.r = this.data[index]; + out.g = this.data[++index]; + out.b = this.data[++index]; + out.a = this.data[++index]; + + return out; + + }, + + /** + * Get the color of a specific pixel including its alpha value. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. + * + * @method Phaser.BitmapData#getPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @return {number} A native color value integer (format: 0xAARRGGBB) + */ + getPixel32: function (x, y) { + + if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) + { + return this.pixels[y * this.width + x]; + } + + }, + + /** + * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixelRGB + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + getPixelRGB: function (x, y, out, hsl, hsv) { + + return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv); + + }, + + /** + * Gets all the pixels from the region specified by the given Rectangle object. + * + * @method Phaser.BitmapData#getPixels + * @param {Phaser.Rectangle} rect - The Rectangle region to get. + * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property. + */ + getPixels: function (rect) { + + return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); + + }, + + /** + * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). + * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. + * + * The direction parameter controls from which direction it should start the scan: + * + * 0 = top to bottom + * 1 = bottom to top + * 2 = left to right + * 3 = right to left + * + * @method Phaser.BitmapData#getFirstPixel + * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. + * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. + */ + getFirstPixel: function (direction) { + + if (direction === undefined) { direction = 0; } + + var pixel = Phaser.Color.createColor(); + + var x = 0; + var y = 0; + var v = 1; + var scan = false; + + if (direction === 1) + { + v = -1; + y = this.height; + } + else if (direction === 3) + { + v = -1; + x = this.width; + } + + do { + + Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel); + + if (direction === 0 || direction === 1) + { + // Top to Bottom / Bottom to Top + x++; + + if (x === this.width) + { + x = 0; + y += v; + + if (y >= this.height || y <= 0) + { + scan = true; + } + } + } + else if (direction === 2 || direction === 3) + { + // Left to Right / Right to Left + y++; + + if (y === this.height) + { + y = 0; + x += v; + + if (x >= this.width || x <= 0) + { + scan = true; + } + } + } + } + while (pixel.a === 0 && !scan); + + pixel.x = x; + pixel.y = y; + + return pixel; + + }, + + /** + * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. + * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. + * + * @method Phaser.BitmapData#getBounds + * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. + * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. + */ + getBounds: function (rect) { + + if (rect === undefined) { rect = new Phaser.Rectangle(); } + + rect.x = this.getFirstPixel(2).x; + + // If we hit this, there's no point scanning any more, the image is empty + if (rect.x === this.width) + { + return rect.setTo(0, 0, 0, 0); + } + + rect.y = this.getFirstPixel(0).y; + rect.width = (this.getFirstPixel(3).x - rect.x) + 1; + rect.height = (this.getFirstPixel(1).y - rect.y) + 1; + + return rect; + + }, + + /** + * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. + * + * @method Phaser.BitmapData#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself. + * + * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn. + * + * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters. + * + * Note that the source image can also be this BitmapData, which can create some interesting effects. + * + * This method has a lot of parameters for maximum control. + * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all. + * + * You may prefer to use `copyTransform` if you're simply trying to draw a Sprite to this BitmapData, + * and don't wish to translate, scale or rotate it from its original values. + * + * @method Phaser.BitmapData#copy + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image. + * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image. + * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width. + * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height. + * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`. + * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`. + * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter. + * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter. + * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters. + * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) { + + if (source === undefined || source === null) { source = this; } + + if (source instanceof Phaser.RenderTexture) + { + source = source.getCanvas(); + } + + this._image = source; + + if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text || source instanceof PIXI.Sprite) + { + // Copy over sprite values + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + this._scale.set(source.scale.x, source.scale.y); + this._anchor.set(source.anchor.x, source.anchor.y); + this._rotate = source.rotation; + this._alpha.current = source.alpha; + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + if (tx === undefined || tx === null) { tx = source.x; } + if (ty === undefined || ty === null) { ty = source.y; } + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + } + else + { + // Reset + this._pos.set(0); + this._scale.set(1); + this._anchor.set(0); + this._rotate = 0; + this._alpha.current = 1; + + if (source instanceof Phaser.BitmapData) + { + this._image = source.canvas; + } + else if (typeof source === 'string') + { + source = this.game.cache.getImage(source); + + if (source === null) + { + return; + } + else + { + this._image = source; + } + } + + this._size.set(this._image.width, this._image.height); + } + + // The source region to copy from + if (x === undefined || x === null) { x = 0; } + if (y === undefined || y === null) { y = 0; } + + // If they set a width/height then we override the frame values with them + if (width) + { + this._size.x = width; + } + + if (height) + { + this._size.y = height; + } + + // The destination region to copy to + if (tx === undefined || tx === null) { tx = x; } + if (ty === undefined || ty === null) { ty = y; } + if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; } + if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; } + + // Rotation - if set this will override any potential Sprite value + if (typeof rotate === 'number') + { + this._rotate = rotate; + } + + // Anchor - if set this will override any potential Sprite value + if (typeof anchorX === 'number') + { + this._anchor.x = anchorX; + } + + if (typeof anchorY === 'number') + { + this._anchor.y = anchorY; + } + + // Scaling - if set this will override any potential Sprite value + if (typeof scaleX === 'number') + { + this._scale.x = scaleX; + } + + if (typeof scaleY === 'number') + { + this._scale.y = scaleY; + } + + // Effects + if (typeof alpha === 'number') + { + this._alpha.current = alpha; + } + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + // Doesn't work fully with children, or nested scale + rotation transforms (see copyTransform) + ctx.translate(tx, ty); + + ctx.scale(this._scale.x, this._scale.y); + + ctx.rotate(this._rotate); + + ctx.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight); + + // Carry on ... + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the + * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. + * It takes the objects tint and scale mode into consideration before drawing. + * + * You can optionally specify Blend Mode and Round Pixels arguments. + * + * @method Phaser.BitmapData#copyTransform + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyTransform: function (source, blendMode, roundPx) { + + if (blendMode === undefined) { blendMode = null; } + if (roundPx === undefined) { roundPx = false; } + + if (!source.hasOwnProperty('worldTransform') || !source.worldVisible || source.worldAlpha === 0) + { + return this; + } + + var wt = source.worldTransform; + + this._pos.set(source.texture.crop.x, source.texture.crop.y); + this._size.set(source.texture.crop.width, source.texture.crop.height); + + if (wt.a === 0 || wt.d === 0 || this._size.x === 0 || this._size.y === 0) + { + // Why bother wasting CPU cycles drawing something you can't see? + return this; + } + + if (source.texture instanceof Phaser.RenderTexture) + { + this._image = source.texture.getCanvas(); + } + else + { + this._image = source.texture.baseTexture.source; + } + + var tx = wt.tx; + var ty = wt.ty; + + if (source.texture.trim) + { + // Offset the translation coordinates by the trim amount + tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width; + ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height; + } + + if (source.tint !== 0xFFFFFF) + { + if (source.cachedTint !== source.tint) + { + source.cachedTint = source.tint; + source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint); + } + + this._image = source.tintedTexture; + this._pos.set(0); + } + + if (roundPx) + { + tx |= 0; + ty |= 0; + } + + var ctx = this.context; + + this._alpha.prev = ctx.globalAlpha; + + ctx.save(); + + ctx.globalAlpha = this._alpha.current; + + if (blendMode) + { + this.op = blendMode; + } + + ctx[this.smoothProperty] = (source.texture.baseTexture.scaleMode === PIXI.scaleModes.LINEAR); + + ctx.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty); + + ctx.drawImage(this._image, + this._pos.x, + this._pos.y, + this._size.x, + this._size.y, + -this._size.x * source.anchor.x, + -this._size.y * source.anchor.y, + this._size.x, + this._size.y); + + ctx.restore(); + + ctx.globalAlpha = this._alpha.prev; + + this.dirty = true; + + return this; + + }, + + /** + * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. + * + * @method Phaser.BitmapData#copyRect + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. + * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image. + * @param {number} x - The destination x coordinate to copy the image to. + * @param {number} y - The destination y coordinate to copy the image to. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyRect: function (source, area, x, y, alpha, blendMode, roundPx) { + + return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx); + + }, + + /** + * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. + * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. + * + * @method Phaser.BitmapData#draw + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData. + * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`. + * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`. + * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`. + * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + draw: function (source, x, y, width, height, blendMode, roundPx) { + + // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here + return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx); + + }, + + /** + * Draws the immediate children of a Phaser.Group to this BitmapData. + * + * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. + * + * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. + * + * @method Phaser.BitmapData#drawGroup + * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawGroup: function (group, blendMode, roundPx) { + + if (group.total > 0) + { + group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx); + } + + return this; + + }, + + /** + * A proxy for drawGroup that handles child iteration for more complex Game Objects. + * + * @method Phaser.BitmapData#drawGroupProxy + * @private + * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + */ + drawGroupProxy: function (child, blendMode, roundPx) { + + if (child.hasOwnProperty('texture')) + { + this.copyTransform(child, blendMode, roundPx); + } + + if (child.type === Phaser.GROUP && child.exists) + { + this.drawGroup(child, blendMode, roundPx); + } + else + { + if (child.hasOwnProperty('children') && child.children.length > 0) + { + for (var i = 0; i < child.children.length; i++) + { + if (child.children[i].exists) + { + this.copyTransform(child.children[i], blendMode, roundPx); + } + } + } + } + + }, + + /** + * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. + * + * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData + * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the + * bounds of the top-level Game Object. + * + * When drawing it will take into account the child's world rotation, scale and alpha values. + * + * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. + * + * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update + * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can + * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. + * + * @method Phaser.BitmapData#drawFull + * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + drawFull: function (parent, blendMode, roundPx) { + + if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false)) + { + return this; + } + + if (parent.type !== Phaser.GROUP && parent.type !== Phaser.EMITTER && parent.type !== Phaser.BITMAPTEXT) + { + if (parent.type === Phaser.GRAPHICS) + { + var bounds = parent.getBounds(); + this.ctx.save(); + this.ctx.translate(bounds.x, bounds.y); + PIXI.CanvasGraphics.renderGraphics(parent, this.ctx); + this.ctx.restore(); + } + else + { + this.copy(parent, null, null, null, null, parent.worldPosition.x, parent.worldPosition.y, null, null, parent.worldRotation, null, null, parent.worldScale.x, parent.worldScale.y, parent.worldAlpha, blendMode, roundPx); + } + } + + if (parent.children) + { + for (var i = 0; i < parent.children.length; i++) + { + this.drawFull(parent.children[i], blendMode, roundPx); + } + } + + return this; + + }, + + /** + * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. + * You can cancel an existing shadow by calling this method and passing no parameters. + * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. + * + * @method Phaser.BitmapData#shadow + * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. + * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. + * @param {number} [x=10] - The horizontal offset of the shadow in pixels. + * @param {number} [y=10] - The vertical offset of the shadow in pixels. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + shadow: function (color, blur, x, y) { + + var ctx = this.context; + + if (color === undefined || color === null) + { + ctx.shadowColor = 'rgba(0,0,0,0)'; + } + else + { + ctx.shadowColor = color; + ctx.shadowBlur = blur || 5; + ctx.shadowOffsetX = x || 10; + ctx.shadowOffsetY = y || 10; + } + + return this; + + }, + + /** + * Draws the image onto this BitmapData using an image as an alpha mask. + * + * @method Phaser.BitmapData#alphaMask + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. + * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. + * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + alphaMask: function (source, mask, sourceRect, maskRect) { + + if (maskRect === undefined || maskRect === null) + { + this.draw(mask).blendSourceAtop(); + } + else + { + this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop(); + } + + if (sourceRect === undefined || sourceRect === null) + { + this.draw(source).blendReset(); + } + else + { + this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset(); + } + + return this; + + }, + + /** + * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. + * The original BitmapData remains unchanged. + * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. + * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: + * `picture.extract(mask, r, g, b)` + * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. + * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint + * the color during extraction. + * + * @method Phaser.BitmapData#extract + * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. + * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied? + * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255. + * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255. + * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255. + * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on. + */ + extract: function (destination, r, g, b, a, resize, r2, g2, b2) { + + if (a === undefined) { a = 255; } + if (resize === undefined) { resize = false; } + if (r2 === undefined) { r2 = r; } + if (g2 === undefined) { g2 = g; } + if (b2 === undefined) { b2 = b; } + + if (resize) + { + destination.resize(this.width, this.height); + } + + this.processPixelRGB( + function (pixel, x, y) + { + if (pixel.r === r && pixel.g === g && pixel.b === b) + { + destination.setPixel32(x, y, r2, g2, b2, a, false); + } + return false; + }, + this); + + destination.context.putImageData(destination.imageData, 0, 0); + destination.dirty = true; + + return destination; + + }, + + /** + * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. + * + * @method Phaser.BitmapData#rect + * @param {number} x - The x coordinate of the top-left of the Rectangle. + * @param {number} y - The y coordinate of the top-left of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + rect: function (x, y, width, height, fillStyle) { + + if (typeof fillStyle !== 'undefined') + { + this.context.fillStyle = fillStyle; + } + + this.context.fillRect(x, y, width, height); + + return this; + + }, + + /** + * Draws text to the BitmapData in the given font and color. + * The default font is 14px Courier, so useful for quickly drawing debug text. + * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. + * + * @method Phaser.BitmapData#text + * @param {string} text - The text to write to the BitmapData. + * @param {number} x - The x coordinate of the top-left of the text string. + * @param {number} y - The y coordinate of the top-left of the text string. + * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can. + * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in. + * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1) + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + text: function (text, x, y, font, color, shadow) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (font === undefined) { font = '14px Courier'; } + if (color === undefined) { color = 'rgb(255,255,255)'; } + if (shadow === undefined) { shadow = true; } + + var ctx = this.context; + var prevFont = ctx.font; + + ctx.font = font; + + if (shadow) + { + ctx.fillStyle = 'rgb(0,0,0)'; + ctx.fillText(text, x + 1, y + 1); + } + + ctx.fillStyle = color; + ctx.fillText(text, x, y); + + ctx.font = prevFont; + + return this; + + }, + + /** + * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. + * + * @method Phaser.BitmapData#circle + * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle. + * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle. + * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + circle: function (x, y, radius, fillStyle) { + + var ctx = this.context; + + if (fillStyle !== undefined) + { + ctx.fillStyle = fillStyle; + } + + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2, false); + ctx.closePath(); + + ctx.fill(); + + return this; + + }, + + /** + * Draws a line between the coordinates given in the color and thickness specified. + * + * @method Phaser.BitmapData#line + * @param {number} x1 - The x coordinate to start the line from. + * @param {number} y1 - The y coordinate to start the line from. + * @param {number} x2 - The x coordinate to draw the line to. + * @param {number} y2 - The y coordinate to draw the line to. + * @param {string} [color='#fff'] - The stroke color that the line will be drawn in. + * @param {number} [width=1] - The line thickness. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + line: function (x1, y1, x2, y2, color, width) { + + if (color === undefined) { color = '#fff'; } + if (width === undefined) { width = 1; } + + var ctx = this.context; + + ctx.beginPath(); + + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); + + ctx.closePath(); + + return this; + + }, + + /** + * Draws a polygon. + * + * @method Phaser.BitmapData#polygon + * @param {object[]} points - An array of {@link Phaser.Point} or point-like objects. + * @param {CanvasGradient|CanvasPattern|string} [fillStyle] - A color, gradient, or pattern. + * @param {number} [lineWidth=0] - The line thickness. + * @param {CanvasGradient|CanvasPattern|string} [strokeStyle='#fff'] - The line color, gradient, or pattern (when `lineWidth` > 0). + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + polygon: function (points, fillStyle, lineWidth, strokeStyle) { + + // Could reject points.length < 3 + + if (strokeStyle === undefined) { strokeStyle = '#fff'; } + if (lineWidth === undefined) { lineWidth = 0; } + + var ctx = this.context; + + if (fillStyle) + { + ctx.fillStyle = fillStyle; + } + + if (lineWidth) + { + ctx.lineWidth = lineWidth; + ctx.strokeStyle = strokeStyle; + } + + ctx.beginPath(); + + ctx.moveTo(points[0].x, points[0].y); + + for (var i = 1, len = points.length; i < len; i++) + { + var point = points[i]; + ctx.lineTo(point.x, point.y); + } + + ctx.closePath(); + + if (fillStyle) { ctx.fill(); } + if (lineWidth) { ctx.stroke(); } + + return this; + + }, + + /** + * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. + * + * @method Phaser.BitmapData#textureLine + * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line. + * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. + * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + textureLine: function (line, image, repeat) { + + if (repeat === undefined) { repeat = 'repeat-x'; } + + if (typeof image === 'string') + { + image = this.game.cache.getImage(image); + + if (!image) + { + return; + } + } + + var width = line.length; + + if (repeat === 'no-repeat' && width > image.width) + { + width = image.width; + } + + var ctx = this.context; + + ctx.fillStyle = ctx.createPattern(image, repeat); + + this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height); + + this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos); + + ctx.save(); + ctx.translate(this._pos.x, this._pos.y); + ctx.rotate(line.angle); + ctx.fillRect(0, 0, width, image.height); + ctx.restore(); + + this.dirty = true; + + return this; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. + * + * @method Phaser.BitmapData#render + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + render: function () { + + if (!this.disableTextureUpload && this.dirty) + { + this.baseTexture.dirty(); + this.dirty = false; + } + + return this; + + }, + + /** + * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. + * + * @method Phaser.BitmapData#destroy + */ + destroy: function () { + + this.frameData.destroy(); + + this.texture.destroy(true); + + Phaser.CanvasPool.remove(this); + + }, + + /** + * Resets the blend mode (effectively sets it to 'source-over') + * + * @method Phaser.BitmapData#blendReset + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendReset: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-over' + * + * @method Phaser.BitmapData#blendSourceOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOver: function () { + + this.op = 'source-over'; + return this; + + }, + + /** + * Sets the blend mode to 'source-in' + * + * @method Phaser.BitmapData#blendSourceIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceIn: function () { + + this.op = 'source-in'; + return this; + + }, + + /** + * Sets the blend mode to 'source-out' + * + * @method Phaser.BitmapData#blendSourceOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceOut: function () { + + this.op = 'source-out'; + return this; + + }, + + /** + * Sets the blend mode to 'source-atop' + * + * @method Phaser.BitmapData#blendSourceAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSourceAtop: function () { + + this.op = 'source-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-over' + * + * @method Phaser.BitmapData#blendDestinationOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOver: function () { + + this.op = 'destination-over'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-in' + * + * @method Phaser.BitmapData#blendDestinationIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationIn: function () { + + this.op = 'destination-in'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-out' + * + * @method Phaser.BitmapData#blendDestinationOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationOut: function () { + + this.op = 'destination-out'; + return this; + + }, + + /** + * Sets the blend mode to 'destination-atop' + * + * @method Phaser.BitmapData#blendDestinationAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDestinationAtop: function () { + + this.op = 'destination-atop'; + return this; + + }, + + /** + * Sets the blend mode to 'xor' + * + * @method Phaser.BitmapData#blendXor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendXor: function () { + + this.op = 'xor'; + return this; + + }, + + /** + * Sets the blend mode to 'lighter' + * + * @method Phaser.BitmapData#blendAdd + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendAdd: function () { + + this.op = 'lighter'; + return this; + + }, + + /** + * Sets the blend mode to 'multiply' + * + * @method Phaser.BitmapData#blendMultiply + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendMultiply: function () { + + this.op = 'multiply'; + return this; + + }, + + /** + * Sets the blend mode to 'screen' + * + * @method Phaser.BitmapData#blendScreen + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendScreen: function () { + + this.op = 'screen'; + return this; + + }, + + /** + * Sets the blend mode to 'overlay' + * + * @method Phaser.BitmapData#blendOverlay + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendOverlay: function () { + + this.op = 'overlay'; + return this; + + }, + + /** + * Sets the blend mode to 'darken' + * + * @method Phaser.BitmapData#blendDarken + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDarken: function () { + + this.op = 'darken'; + return this; + + }, + + /** + * Sets the blend mode to 'lighten' + * + * @method Phaser.BitmapData#blendLighten + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLighten: function () { + + this.op = 'lighten'; + return this; + + }, + + /** + * Sets the blend mode to 'color-dodge' + * + * @method Phaser.BitmapData#blendColorDodge + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorDodge: function () { + + this.op = 'color-dodge'; + return this; + + }, + + /** + * Sets the blend mode to 'color-burn' + * + * @method Phaser.BitmapData#blendColorBurn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColorBurn: function () { + + this.op = 'color-burn'; + return this; + + }, + + /** + * Sets the blend mode to 'hard-light' + * + * @method Phaser.BitmapData#blendHardLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHardLight: function () { + + this.op = 'hard-light'; + return this; + + }, + + /** + * Sets the blend mode to 'soft-light' + * + * @method Phaser.BitmapData#blendSoftLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSoftLight: function () { + + this.op = 'soft-light'; + return this; + + }, + + /** + * Sets the blend mode to 'difference' + * + * @method Phaser.BitmapData#blendDifference + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendDifference: function () { + + this.op = 'difference'; + return this; + + }, + + /** + * Sets the blend mode to 'exclusion' + * + * @method Phaser.BitmapData#blendExclusion + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendExclusion: function () { + + this.op = 'exclusion'; + return this; + + }, + + /** + * Sets the blend mode to 'hue' + * + * @method Phaser.BitmapData#blendHue + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendHue: function () { + + this.op = 'hue'; + return this; + + }, + + /** + * Sets the blend mode to 'saturation' + * + * @method Phaser.BitmapData#blendSaturation + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendSaturation: function () { + + this.op = 'saturation'; + return this; + + }, + + /** + * Sets the blend mode to 'color' + * + * @method Phaser.BitmapData#blendColor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendColor: function () { + + this.op = 'color'; + return this; + + }, + + /** + * Sets the blend mode to 'luminosity' + * + * @method Phaser.BitmapData#blendLuminosity + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + blendLuminosity: function () { + + this.op = 'luminosity'; + return this; + + }, + + /** + * Updates a portion of the BitmapData from a source Bitmap. + * This optimization is important if calling update() on a large Bitmap is causing performance issues. + * Make sure you use getPixel32() instead of getPixel(). + * This does not work with floating point numbers for x and y. + * + * @method Phaser.BitmapData#copyBitmapData + * @param {Phaser.BitmapData} [source] - The BitmapData you wish to copy. + * @param {number} [x] - The x coordinate of the top-left of the area to copy. + * @param {number} [y] - The y coordinate of the top-left of the area to copy. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ + copyBitmapData: function(source, x, y) { + + source.update(); + for (var i = 0, destRowStart; i < source.height; i++) { + destRowStart = (y + i) * this.width + x; + for (var j = 0; j < source.width; j++) { + this.pixels[destRowStart + j] = source.pixels[i * source.width + j]; + } + } + return this; + + } + +}; + +/** +* @memberof Phaser.BitmapData +* @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", { + + get: function () { + + Phaser.Canvas.getSmoothingEnabled(this.context); + + }, + + set: function (value) { + + Phaser.Canvas.setSmoothingEnabled(this.context, value); + + } + +}); + +/** +* @memberof Phaser.BitmapData +* @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas. +*/ +Object.defineProperty(Phaser.BitmapData.prototype, "op", { + + get: function () { + + return this.context.globalCompositeOperation; + + }, + + set: function (value) { + + this.context.globalCompositeOperation = value; + + } + +}); + +/** + * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform. + * + * @method Phaser.BitmapData.getTransform + * @param {number} translateX - The x translate value. + * @param {number} translateY - The y translate value. + * @param {number} scaleX - The scale x value. + * @param {number} scaleY - The scale y value. + * @param {number} skewX - The skew x value. + * @param {number} skewY - The skew y value. + * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms. + */ +Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) { + + if (typeof translateX !== 'number') { translateX = 0; } + if (typeof translateY !== 'number') { translateY = 0; } + if (typeof scaleX !== 'number') { scaleX = 1; } + if (typeof scaleY !== 'number') { scaleY = 1; } + if (typeof skewX !== 'number') { skewX = 0; } + if (typeof skewY !== 'number') { skewY = 0; } + + return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY }; + +}; + +Phaser.BitmapData.prototype.constructor = Phaser.BitmapData; + +/* jshint ignore:start */ + +/* +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ + +/** +* @class EarCut +*/ +Phaser.EarCut = {}; + +Phaser.EarCut.Triangulate = function (data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = Phaser.EarCut.linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = Phaser.EarCut.eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + Phaser.EarCut.earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +}; + +// create a circular doubly linked list from polygon points in the specified winding order + +Phaser.EarCut.linkedList = function (data, start, end, dim, clockwise) { + var sum = 0, + i, j, last; + + // calculate original winding order of a polygon ring + for (i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + + // link points into circular doubly-linked list in the specified winding order + if (clockwise === (sum > 0)) { + for (i = start; i < end; i += dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = Phaser.EarCut.insertNode(i, data[i], data[i + 1], last); + } + + return last; +}; + +// eliminate colinear or duplicate points + +Phaser.EarCut.filterPoints = function (start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (Phaser.EarCut.equals(p, p.next) || Phaser.EarCut.area(p.prev, p, p.next) === 0)) { + Phaser.EarCut.removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +}; + +// main ear slicing loop which triangulates a polygon (given as a linked list) + +Phaser.EarCut.earcutLinked = function (ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) Phaser.EarCut.indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? Phaser.EarCut.isEarHashed(ear, minX, minY, size) : Phaser.EarCut.isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + Phaser.EarCut.removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + Phaser.EarCut.earcutLinked(Phaser.EarCut.filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = Phaser.EarCut.cureLocalIntersections(ear, triangles, dim); + Phaser.EarCut.earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + Phaser.EarCut.splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +}; + +// check whether a polygon node forms a valid ear with adjacent nodes + +Phaser.EarCut.isEar = function (ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +}; + +Phaser.EarCut.isEarHashed = function (ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (Phaser.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = Phaser.EarCut.zOrder(minTX, minTY, minX, minY, size), + maxZ = Phaser.EarCut.zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + Phaser.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + Phaser.EarCut.area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +}; + +// go through all polygon nodes and cure small local self-intersections + +Phaser.EarCut.cureLocalIntersections = function (start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) + if (Phaser.EarCut.intersects(a, p, p.next, b) && Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + Phaser.EarCut.removeNode(p); + Phaser.EarCut.removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +}; + +// try splitting polygon into two and triangulate them independently + +Phaser.EarCut.splitEarcut = function (start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && Phaser.EarCut.isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = Phaser.EarCut.splitPolygon(a, b); + + // filter colinear points around the cuts + a = Phaser.EarCut.filterPoints(a, a.next); + c = Phaser.EarCut.filterPoints(c, c.next); + + // run earcut on each half + Phaser.EarCut.earcutLinked(a, triangles, dim, minX, minY, size); + Phaser.EarCut.earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +}; + +// link every hole into the outer loop, producing a single-ring polygon without holes + +Phaser.EarCut.eliminateHoles = function (data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = Phaser.EarCut.linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(Phaser.EarCut.getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + Phaser.EarCut.eliminateHole(queue[i], outerNode); + outerNode = Phaser.EarCut.filterPoints(outerNode, outerNode.next); + } + + return outerNode; +}; + +Phaser.EarCut.compareX = function (a, b) { + return a.x - b.x; +}; + +// find a bridge between vertices that connects hole with an outer ring and and link it + +Phaser.EarCut.eliminateHole = function (hole, outerNode) { + outerNode = Phaser.EarCut.findHoleBridge(hole, outerNode); + if (outerNode) { + var b = Phaser.EarCut.splitPolygon(outerNode, hole); + Phaser.EarCut.filterPoints(b, b.next); + } +}; + +// David Eberly's algorithm for finding a bridge between hole and outer polygon + +Phaser.EarCut.findHoleBridge = function (hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hole.x === m.x) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= m.x && + Phaser.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && Phaser.EarCut.locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +}; + +// interlink polygon nodes in z-order + +Phaser.EarCut.indexCurve = function (start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = Phaser.EarCut.zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + Phaser.EarCut.sortLinked(p); +}; + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + +Phaser.EarCut.sortLinked = function (list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +}; + +// z-order of a point given coords and size of the data bounding box + +Phaser.EarCut.zOrder = function (x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +}; + +// find the leftmost node of a polygon ring + +Phaser.EarCut.getLeftmost = function (start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +}; + +// check if a point lies within a convex triangle + +Phaser.EarCut.pointInTriangle = function (ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +}; + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) + +Phaser.EarCut.isValidDiagonal = function (a, b) { + return Phaser.EarCut.equals(a, b) || a.next.i !== b.i && a.prev.i !== b.i && !Phaser.EarCut.intersectsPolygon(a, b) && + Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a) && Phaser.EarCut.middleInside(a, b); +}; + +// signed area of a triangle + +Phaser.EarCut.area = function (p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +}; + +// check if two points are equal + +Phaser.EarCut.equals = function (p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +}; + +// check if two segments intersect + +Phaser.EarCut.intersects = function (p1, q1, p2, q2) { + return Phaser.EarCut.area(p1, q1, p2) > 0 !== Phaser.EarCut.area(p1, q1, q2) > 0 && + Phaser.EarCut.area(p2, q2, p1) > 0 !== Phaser.EarCut.area(p2, q2, q1) > 0; +}; + +// check if a polygon diagonal intersects any polygon segments + +Phaser.EarCut.intersectsPolygon = function (a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + Phaser.EarCut.intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +}; + +// check if a polygon diagonal is locally inside the polygon + +Phaser.EarCut.locallyInside = function (a, b) { + return Phaser.EarCut.area(a.prev, a, a.next) < 0 ? + Phaser.EarCut.area(a, b, a.next) >= 0 && Phaser.EarCut.area(a, a.prev, b) >= 0 : + Phaser.EarCut.area(a, b, a.prev) < 0 || Phaser.EarCut.area(a, a.next, b) < 0; +}; + +// check if the middle point of a polygon diagonal is inside the polygon + +Phaser.EarCut.middleInside = function (a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +}; + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring + +Phaser.EarCut.splitPolygon = function (a, b) { + var a2 = new Phaser.EarCut.Node(a.i, a.x, a.y), + b2 = new Phaser.EarCut.Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +}; + +// create a node and optionally link it with previous one (in a circular doubly linked list) + +Phaser.EarCut.insertNode = function (i, x, y, last) { + var p = new Phaser.EarCut.Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +}; + +Phaser.EarCut.removeNode = function (p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +}; + +Phaser.EarCut.Node = function (i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +}; + +/* jshint ignore:end */ + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * A set of functions used by the webGL renderer to draw the primitive graphics data + * + * @class PIXI.WebGLGraphics + * @private + * @static + */ +PIXI.WebGLGraphics = function() +{ +}; + +/** + * The number of points beyond which Pixi swaps to using the Stencil Buffer to render the Graphics. + * + * @type {number} + */ +PIXI.WebGLGraphics.stencilBufferLimit = 6; + +/** + * Renders the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.renderGraphics + * @param graphics {Graphics} + * @param renderSession {Object} + */ +PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset) +{ + var gl = renderSession.gl; + var projection = renderSession.projection, + offset = renderSession.offset, + shader = renderSession.shaderManager.primitiveShader, + webGLData; + + if(graphics.dirty) + { + PIXI.WebGLGraphics.updateGraphics(graphics, gl); + } + + var webGL = graphics._webGL[gl.id]; + + // if the graphics object does not exist in the webGL context skip rendering! + if(!webGL) + { + return; + } + + // This could be speeded up for sure! + + for (var i = 0; i < webGL.data.length; i++) + { + if(webGL.data[i].mode === 1) + { + webGLData = webGL.data[i]; + + renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession); + + // render quad.. + gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 ); + + renderSession.stencilManager.popStencil(graphics, webGLData, renderSession); + } + else + { + webGLData = webGL.data[i]; + + + renderSession.shaderManager.setShader( shader );//activatePrimitiveShader(); + shader = renderSession.shaderManager.primitiveShader; + gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true)); + + gl.uniform1f(shader.flipY, 1); + + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + + gl.uniform3fv(shader.tintColor, Phaser.Color.hexToRGBArray(graphics.tint)); + + gl.uniform1f(shader.alpha, graphics.worldAlpha); + + + gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer); + + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); + gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); + + // set the index buffer! + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); + gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 ); + } + } +}; + +/** + * Updates the graphics object + * + * @static + * @private + * @method PIXI.WebGLGraphics.updateGraphics + * @param graphicsData {Graphics} The graphics object to update + * @param gl {WebGLContext} the current WebGL drawing context + */ +PIXI.WebGLGraphics.updateGraphics = function(graphics, gl) +{ + // get the contexts graphics object + var webGL = graphics._webGL[gl.id]; + // if the graphics object does not exist in the webGL context time to create it! + if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl}; + + // flag the graphics as not dirty as we are about to update it... + graphics.dirty = false; + + var i; + + // if the user cleared the graphics object we will need to clear every object + if(graphics.clearDirty) + { + graphics.clearDirty = false; + + // lop through and return all the webGLDatas to the object pool so than can be reused later on + for (i = 0; i < webGL.data.length; i++) + { + var graphicsData = webGL.data[i]; + graphicsData.reset(); + PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData ); + } + + // clear the array and reset the index.. + webGL.data = []; + webGL.lastIndex = 0; + } + + var webGLData; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + if (data.type === Phaser.POLYGON) + { + // need to add the points the the graphics object.. + data.points = data.shape.points.slice(); + if(data.shape.closed) + { + // close the poly if the value is true! + if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1]) + { + data.points.push(data.points[0], data.points[1]); + } + } + + // MAKE SURE WE HAVE THE CORRECT TYPE.. + if(data.fill) + { + if(data.points.length >= PIXI.WebGLGraphics.stencilBufferLimit) + { + if(data.points.length < PIXI.WebGLGraphics.stencilBufferLimit * 2) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData); + // console.log(canDrawUsingSimple); + + if(!canDrawUsingSimple) + { + // console.log("<>>>") + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); + PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); + } + } + } + + if(data.lineWidth > 0) + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + PIXI.WebGLGraphics.buildLine(data, webGLData); + + } + } + else + { + webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); + + if (data.type === Phaser.RECTANGLE) + { + PIXI.WebGLGraphics.buildRectangle(data, webGLData); + } + else if (data.type === Phaser.CIRCLE || data.type === Phaser.ELLIPSE) + { + PIXI.WebGLGraphics.buildCircle(data, webGLData); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData); + } + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (i = 0; i < webGL.data.length; i++) + { + webGLData = webGL.data[i]; + if(webGLData.dirty)webGLData.upload(); + } +}; + +/** + * @static + * @private + * @method PIXI.WebGLGraphics.switchMode + * @param webGL {WebGLContext} + * @param type {Number} + */ +PIXI.WebGLGraphics.switchMode = function(webGL, type) +{ + var webGLData; + + if(!webGL.data.length) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + else + { + webGLData = webGL.data[webGL.data.length-1]; + + if(webGLData.mode !== type || type === 1) + { + webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl); + webGLData.mode = type; + webGL.data.push(webGLData); + } + } + + webGLData.dirty = true; + + return webGLData; +}; + +/** + * Builds a rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData) +{ + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; + + // start + 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); + + // insert 2 dead triangles.. + 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; + } +}; + +/** + * Builds a rounded rectangle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildRoundedRectangle + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData) +{ + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + recPoints.push(x, y + radius); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y)); + recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius)); + + if (graphicsData.fill) { + var color = Phaser.Color.hexToRGBArray(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; + + var triangles = Phaser.EarCut.Triangulate(recPoints, null, 2); + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i+1] + vecPos); + indices.push(triangles[i+2] + vecPos); + indices.push(triangles[i+2] + vecPos); + } + + + for (i = 0; i < recPoints.length; i++) + { + verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @static + * @private + * @method PIXI.WebGLGraphics.quadraticBezierCurve + * @param fromX {Number} Origin point x + * @param fromY {Number} Origin point x + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Array(Number)} + */ +PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) { + + var xa, + ya, + xb, + yb, + x, + y, + n = 20, + points = []; + + function getPt(n1 , n2, perc) { + var diff = n2 - n1; + + return n1 + ( diff * perc ); + } + + var j = 0; + for (var i = 0; i <= n; i++ ) + { + j = i / n; + + // The Green Line + xa = getPt( fromX , cpX , j ); + ya = getPt( fromY , cpY , j ); + xb = getPt( cpX , toX , j ); + yb = getPt( cpY , toY , j ); + + // The Black Dot + x = getPt( xa , xb , j ); + y = getPt( ya , yb , j ); + + points.push(x, y); + } + return points; +}; + +/** + * Builds a circle to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildCircle + * @param graphicsData {Graphics} The graphics object to draw + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData) +{ + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + + // TODO - bit hacky?? + if (graphicsData.type === Phaser.CIRCLE) + { + width = circleData.radius; + height = circleData.radius; + } + else + { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = 40; + var seg = (Math.PI * 2) / totalSegs ; + + var i = 0; + + if(graphicsData.fill) + { + var color = Phaser.Color.hexToRGBArray(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; i < totalSegs + 1 ; i++) + { + verts.push(x,y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos-1); + } + + if(graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (i = 0; i < totalSegs + 1; i++) + { + graphicsData.points.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height); + } + + PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Builds a line to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildLine + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData) +{ + // TODO OPTIMISE! + var i = 0; + var points = graphicsData.points; + if(points.length === 0)return; + + // if the line width is an odd number add 0.5 to align to a whole pixel + if(graphicsData.lineWidth%2) + { + for (i = 0; i < points.length; i++) { + points[i] += 0.5; + } + } + + // get first and last point.. figure out the middle! + var firstPoint = new PIXI.Point( points[0], points[1] ); + var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + // if the first point is the last point - gonna have issues :) + if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length/6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var px, py, p1x, p1y, p2x, p2y, p3x, p3y; + var perpx, perpy, perp2x, perp2y, perp3x, perp3y; + var a1, b1, c1, a2, b2, c2; + var denom, pdist, dist; + + p1x = points[0]; + p1y = points[1]; + + p2x = points[2]; + p2y = points[3]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx , p1y - perpy, + r, g, b, alpha); + + verts.push(p1x + perpx , p1y + perpy, + r, g, b, alpha); + + for (i = 1; i < length-1; i++) + { + p1x = points[(i-1)*2]; + p1y = points[(i-1)*2 + 1]; + + p2x = points[(i)*2]; + p2y = points[(i)*2 + 1]; + + p3x = points[(i+1)*2]; + p3y = points[(i+1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + a1 = (-perpy + p1y) - (-perpy + p2y); + b1 = (-perpx + p2x) - (-perpx + p1x); + c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + a2 = (-perp2y + p3y) - (-perp2y + p2y); + b2 = (-perp2x + p2x) - (-perp2x + p3x); + c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + denom = a1*b2 - a2*b1; + + if(Math.abs(denom) < 0.1 ) + { + + denom+=10.1; + verts.push(p2x - perpx , p2y - perpy, + r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy, + r, g, b, alpha); + + continue; + } + + px = (b1*c2 - b2*c1)/denom; + py = (a2*c1 - a1*c2)/denom; + + + pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); + + + if(pdist > 140 * 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 < indexCount; i++) + { + indices.push(indexStart++); + } + + indices.push(indexStart-1); +}; + +/** + * Builds a complex polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildComplexPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData) +{ + //TODO - no need to copy this as it gets turned into a FLoat32Array anyways.. + var points = graphicsData.points.slice(); + if(points.length < 6)return; + + // get first and last point.. figure out the middle! + var indices = webGLData.indices; + webGLData.points = points; + webGLData.alpha = graphicsData.fillAlpha; + webGLData.color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + + /* + calclate the bounds.. + */ + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + var x,y; + + // get size.. + for (var i = 0; i < points.length; i+=2) + { + x = points[i]; + y = points[i+1]; + + minX = x < minX ? x : minX; + maxX = x > maxX ? x : maxX; + + minY = y < minY ? y : minY; + maxY = y > maxY ? y : maxY; + } + + // add a quad to the end cos there is no point making another buffer! + points.push(minX, minY, + maxX, minY, + maxX, maxY, + minX, maxY); + + // push a quad onto the end.. + + //TODO - this aint needed! + var length = points.length / 2; + for (i = 0; i < length; i++) + { + indices.push( i ); + } + +}; + +/** + * Builds a polygon to draw + * + * @static + * @private + * @method PIXI.WebGLGraphics.buildPoly + * @param graphicsData {Graphics} The graphics object containing all the necessary properties + * @param webGLData {Object} + */ +PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData) +{ + var points = graphicsData.points; + + if(points.length < 6)return; + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = Phaser.EarCut.Triangulate(points, null, 2); + + if(!triangles)return false; + + var vertPos = verts.length / 6; + + var i = 0; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i] + vertPos); + indices.push(triangles[i+1] + vertPos); + indices.push(triangles[i+2] +vertPos); + indices.push(triangles[i+2] + vertPos); + } + + for (i = 0; i < length; i++) + { + verts.push(points[i * 2], points[i * 2 + 1], + r, g, b, alpha); + } + + return true; +}; + +PIXI.WebGLGraphics.graphicsDataPool = []; + +/** + * @class WebGLGraphicsData + * @private + * @static + */ +PIXI.WebGLGraphicsData = function(gl) +{ + this.gl = gl; + + //TODO does this need to be split before uploding?? + this.color = [0,0,0]; // color split! + this.points = []; + this.indices = []; + this.buffer = gl.createBuffer(); + this.indexBuffer = gl.createBuffer(); + this.mode = 1; + this.alpha = 1; + this.dirty = true; +}; + +/** + * @method PIXI.WebGLGraphics.reset + */ +PIXI.WebGLGraphicsData.prototype.reset = function() +{ + this.points = []; + this.indices = []; +}; + +/** + * @method PIXI.WebGLGraphics.upload + */ +PIXI.WebGLGraphicsData.prototype.upload = function() +{ + var gl = this.gl; + +// this.lastIndex = graphics.graphicsData.length; + this.glPoints = new Float32Array(this.points); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW); + + this.glIndicies = new Uint16Array(this.indices); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW); + + this.dirty = false; +}; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + + +/** + * A set of functions used by the canvas renderer to draw the primitive graphics data. + * + * @class PIXI.CanvasGraphics + * @static + */ +PIXI.CanvasGraphics = function() +{ +}; + +/** + * Renders a {@link Phaser.Graphics} object to a canvas. + * + * @method PIXI.CanvasGraphics.renderGraphics + * @static + * @param graphics {Graphics} the actual graphics object to render + * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas + */ +PIXI.CanvasGraphics.renderGraphics = function(graphics, context) +{ + var worldAlpha = graphics.worldAlpha; + + if (graphics.dirty) + { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === Phaser.POLYGON) + { + context.beginPath(); + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (shape.closed) + { + context.lineTo(points[0], points[1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.RECTANGLE) + { + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ELLIPSE) + { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + context.beginPath(); + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + +}; + +/** + * Renders a graphics mask + * + * @static + * @private + * @method PIXI.CanvasGraphics.renderGraphicsMask + * @param graphics {Graphics} the graphics which will be used as a mask + * @param context {CanvasRenderingContext2D} the context 2d method of the canvas + */ +PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context) +{ + var len = graphics.graphicsData.length; + + if (len === 0) + { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === Phaser.POLYGON) + { + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + } + else if (data.type === Phaser.RECTANGLE) + { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } + else if (data.type === Phaser.CIRCLE) + { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } + else if (data.type === Phaser.ELLIPSE) + { + + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } + else if (data.type === Phaser.ROUNDEDRECTANGLE) + { + + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } +}; + +PIXI.CanvasGraphics.updateGraphicsTint = function(graphics) +{ + if (graphics.tint === 0xFFFFFF) + { + return; + } + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF)/ 255; + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255); + data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255); + + } + +}; + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + * @param lineWidth {number} the width of the line to draw + * @param lineColor {number} the color of the line to draw + * @param lineAlpha {number} the alpha of the line to draw + * @param fillColor {number} the color of the fill + * @param fillAlpha {number} the alpha of the fill + * @param fill {boolean} whether or not the shape is filled with a colour + * @param shape {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + +Phaser.GraphicsData = function (lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { + + /* + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /* + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /* + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /* + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /* + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /* + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /* + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /* + * @member {boolean} whether or not the shape is filled with a color + */ + this.fill = fill; + + /* + * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw. + */ + this.shape = shape; + + /* + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + +}; + +Phaser.GraphicsData.prototype.constructor = Phaser.GraphicsData; + +/** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {GraphicsData} + */ +Phaser.GraphicsData.prototype.clone = function () { + + return new Phaser.GraphicsData( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.fill, + this.shape + ); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, +* Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will +* be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: +* +* ```javascript +* graphics.beginFill(0xff0000); +* graphics.drawCircle(50, 50, 100); +* graphics.endFill(); +* ``` +* +* This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. +* +* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or +* WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the +* graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. +* +* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help +* performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. +* You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then +* you should avoid doing this, as it will constantly generate new textures, which will consume memory. +* +* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful +* in their complexity and quantity of them in your game. +* +* @class Phaser.Graphics +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - X position of the new graphics object. +* @param {number} [y=0] - Y position of the new graphics object. +*/ +Phaser.Graphics = function (game, x, y) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.GRAPHICS; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value. + * @private + */ + this.anchor = new Phaser.Point(); + + PIXI.DisplayObjectContainer.call(this); + + this.renderable = true; + + /** + * The alpha value used when filling the Graphics object. + * + * @property fillAlpha + * @type Number + */ + this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @property lineWidth + * @type Number + */ + this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @property lineColor + * @type String + * @default 0 + */ + this.lineColor = 0; + + /** + * Graphics data + * + * @property graphicsData + * @type Array + * @private + */ + this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF (Phaser.Color.WHITE) to reset the tint. + * + * @property tint + * @type Number + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. + * + * @property blendMode + * @type Number + * @default PIXI.blendModes.NORMAL; + */ + this.blendMode = PIXI.blendModes.NORMAL; + + /** + * Current path + * + * @property currentPath + * @type Object + * @private + */ + this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @property _webGL + * @type Array + * @private + */ + this._webGL = []; + + /** + * Whether this shape is being used as a mask. + * + * @property isMask + * @type Boolean + */ + this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @property boundsPadding + * @type Number + */ + this.boundsPadding = 0; + + this._localBounds = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property dirty + * @type Boolean + * @private + */ + this.dirty = true; + + /** + * Used to detect if the bounds have been invalidated, by this Graphics being cleared or drawn to. + * If this is set to true then the updateLocalBounds is called once in the postUpdate method. + * + * @property _boundsDirty + * @type Boolean + * @private + */ + this._boundsDirty = false; + + /** + * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated. + * + * @property webGLDirty + * @type Boolean + * @private + */ + this.webGLDirty = false; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @property cachedSpriteDirty + * @type Boolean + * @private + */ + this.cachedSpriteDirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.Graphics.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Graphics.prototype.constructor = Phaser.Graphics; + +Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Graphics#preUpdate +*/ +Phaser.Graphics.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World +* +* @method Phaser.Graphics#postUpdate +*/ +Phaser.Graphics.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this._boundsDirty) + { + this.updateLocalBounds(); + this._boundsDirty = false; + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].postUpdate(); + } + +}; + +/** +* Destroy this Graphics instance. +* +* @method Phaser.Graphics#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Graphics.prototype.destroy = function (destroyChildren) { + + this.clear(); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Draws a single {@link Phaser.Polygon} triangle from a {@link Phaser.Point} array +* +* @method Phaser.Graphics#drawTriangle +* @param {Array} points - An array of Phaser.Points that make up the three vertices of this triangle +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangle = function (points, cull) { + + if (cull === undefined) { cull = false; } + + var triangle = new Phaser.Polygon(points); + + if (cull) + { + var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y); + var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y); + var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y); + var faceNormal = cb.cross(ab); + + if (cameraToFace.dot(faceNormal) > 0) + { + this.drawPolygon(triangle); + } + } + else + { + this.drawPolygon(triangle); + } + +}; + +/** +* Draws {@link Phaser.Polygon} triangles +* +* @method Phaser.Graphics#drawTriangles +* @param {Array|Array} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles +* @param {Array} [indices=null] - An array of numbers that describe what order to draw the vertices in +* @param {boolean} [cull=false] - Should we check if the triangle is back-facing +*/ +Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) { + + if (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 < vertices.length / 3; i++) + { + this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull); + } + } + else + { + for (i = 0; i < vertices.length / 6; i++) + { + point1.x = vertices[i * 6 + 0]; + point1.y = vertices[i * 6 + 1]; + point2.x = vertices[i * 6 + 2]; + point2.y = vertices[i * 6 + 3]; + point3.x = vertices[i * 6 + 4]; + point3.y = vertices[i * 6 + 5]; + this.drawTriangle([point1, point2, point3], cull); + } + } + } + else + { + if (vertices[0] instanceof Phaser.Point) + { + for (i = 0; i < indices.length /3; i++) + { + points.push(vertices[indices[i * 3 ]]); + points.push(vertices[indices[i * 3 + 1]]); + points.push(vertices[indices[i * 3 + 2]]); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + else + { + for (i = 0; i < indices.length; i++) + { + point1.x = vertices[indices[i] * 2]; + point1.y = vertices[indices[i] * 2 + 1]; + points.push(point1.copyTo({})); + + if (points.length === 3) + { + this.drawTriangle(points, cull); + points = []; + } + } + } + } +}; + +/** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. + * + * @method Phaser.Graphics#lineStyle + * @param lineWidth {Number} width of the line to draw, will update the objects stored style + * @param color {Number} color of the line to draw, will update the objects stored style + * @param alpha {Number} alpha of the line to draw, will update the objects stored style + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { + + this.lineWidth = lineWidth || 0; + this.lineColor = color || 0; + this.lineAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { + // halfway through a line? start a new one! + this.drawShape(new Phaser.Polygon(this.currentPath.shape.points.slice(-2))); + } + else + { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + +}; + +/** + * Moves the current drawing position to x, y. + * + * @method Phaser.Graphics#moveTo + * @param x {Number} the X coordinate to move to + * @param y {Number} the Y coordinate to move to + * @return {Graphics} + */ +Phaser.Graphics.prototype.moveTo = function (x, y) { + + this.drawShape(new Phaser.Polygon([ x, y ])); + + return this; + +}; + +/** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @method Phaser.Graphics#lineTo + * @param x {Number} the X coordinate to draw to + * @param y {Number} the Y coordinate to draw to + * @return {Graphics} + */ +Phaser.Graphics.prototype.lineTo = function (x, y) { + + if (!this.currentPath) + { + this.moveTo(0, 0); + } + + this.currentPath.shape.points.push(x, y); + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @method Phaser.Graphics#quadraticCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [ 0, 0 ]; + } + } + else + { + this.moveTo(0,0); + } + + var xa, + ya, + n = 20, + points = this.currentPath.shape.points; + + if (points.length === 0) + { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var j = 0; + for (var i = 1; i <= n; ++i) + { + j = i / n; + + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + + points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), + ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Calculate the points for a bezier curve and then draws it. + * + * @method Phaser.Graphics#bezierCurveTo + * @param cpX {Number} Control point x + * @param cpY {Number} Control point y + * @param cpX2 {Number} Second Control point x + * @param cpY2 {Number} Second Control point y + * @param toX {Number} Destination point x + * @param toY {Number} Destination point y + * @return {Graphics} + */ +Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + var n = 20, + dt, + dt2, + dt3, + t2, + t3, + points = this.currentPath.shape.points; + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + var j = 0; + + for (var i = 1; i <= n; ++i) + { + j = i / n; + + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, + dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @method Phaser.Graphics#arcTo + * @param x1 {Number} The x-coordinate of the beginning of the arc + * @param y1 {Number} The y-coordinate of the beginning of the arc + * @param x2 {Number} The x-coordinate of the end of the arc + * @param y2 {Number} The y-coordinate of the end of the arc + * @param radius {Number} The radius of the arc + * @return {Graphics} + */ +Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points.push(x1, y1); + } + } + else + { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points, + fromX = points[points.length-2], + fromY = points[points.length-1], + a1 = fromY - y1, + b1 = fromX - x1, + a2 = y2 - y1, + b2 = x2 - x1, + mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { + points.push(x1, y1); + } + } + else + { + var dd = a1 * a1 + b1 * b1, + cc = a2 * a2 + b2 * b2, + tt = a1 * a2 + b1 * b2, + k1 = radius * Math.sqrt(dd) / mm, + k2 = radius * Math.sqrt(cc) / mm, + j1 = k1 * tt / dd, + j2 = k2 * tt / cc, + cx = k1 * b2 + k2 * b1, + cy = k1 * a2 + k2 * a1, + px = b1 * (k2 + j1), + py = a1 * (k2 + j1), + qx = b2 * (k1 + j2), + qy = a2 * (k1 + j2), + startAngle = Math.atan2(py - cy, px - cx), + endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @method Phaser.Graphics#arc + * @param cx {Number} The x-coordinate of the center of the circle + * @param cy {Number} The y-coordinate of the center of the circle + * @param radius {Number} The radius of the circle + * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) + * @param endAngle {Number} The ending angle, in radians + * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. + * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. + * @return {Graphics} + */ +Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise, segments) { + + // If we do this we can never draw a full circle + if (startAngle === endAngle) + { + return this; + } + + if (anticlockwise === undefined) { anticlockwise = false; } + if (segments === undefined) { segments = 40; } + + if (!anticlockwise && endAngle <= startAngle) + { + endAngle += Math.PI * 2; + } + else if (anticlockwise && startAngle <= endAngle) + { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments; + + // Sweep check - moved here because we don't want to do the moveTo below if the arc fails + if (sweep === 0) + { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (anticlockwise && this.filling) + { + this.moveTo(cx, cy); + } + else + { + this.moveTo(startX, startY); + } + + // currentPath will always exist after calling a moveTo + var points = this.currentPath.shape.points; + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = (segMinus % 1) / segMinus; + + for (var i = 0; i <= segMinus; i++) + { + var real = i + remainder * i; + + var angle = ((theta) + startAngle + (theta2 * real)); + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, + ( (cTheta * -s) + (sTheta * c) ) * radius + cy); + } + + this.dirty = true; + this._boundsDirty = true; + + return this; + +}; + +/** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @method Phaser.Graphics#beginFill + * @param color {Number} the color of the fill + * @param alpha {Number} the alpha of the fill + * @return {Graphics} + */ +Phaser.Graphics.prototype.beginFill = function (color, alpha) { + + this.filling = true; + this.fillColor = color || 0; + this.fillAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + +}; + +/** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @method Phaser.Graphics#endFill + * @return {Graphics} + */ +Phaser.Graphics.prototype.endFill = function () { + + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRect + * + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawRect = function (x, y, width, height) { + + this.drawShape(new Phaser.Rectangle(x, y, width, height)); + + return this; + +}; + +/** + * @method Phaser.Graphics#drawRoundedRect + * @param x {Number} The X coord of the top-left of the rectangle + * @param y {Number} The Y coord of the top-left of the rectangle + * @param width {Number} The width of the rectangle + * @param height {Number} The height of the rectangle + * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. + */ +Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + + this.drawShape(new Phaser.RoundedRectangle(x, y, width, height, radius)); + + return this; + +}; + +/** + * Draws a circle. + * + * @method Phaser.Graphics#drawCircle + * @param x {Number} The X coordinate of the center of the circle + * @param y {Number} The Y coordinate of the center of the circle + * @param diameter {Number} The diameter of the circle + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) { + + this.drawShape(new Phaser.Circle(x, y, diameter)); + + return this; + +}; + +/** + * Draws an ellipse. + * + * @method Phaser.Graphics#drawEllipse + * @param x {Number} The X coordinate of the center of the ellipse + * @param y {Number} The Y coordinate of the center of the ellipse + * @param width {Number} The half width of the ellipse + * @param height {Number} The half height of the ellipse + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawEllipse = function (x, y, width, height) { + + this.drawShape(new Phaser.Ellipse(x, y, width, height)); + + return this; + +}; + +/** + * Draws a polygon using the given path. + * + * @method Phaser.Graphics#drawPolygon + * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. + * @return {Graphics} + */ +Phaser.Graphics.prototype.drawPolygon = function (path) { + + if (path instanceof Phaser.Polygon) + { + path = path.points; + } + + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) + { + points[i] = arguments[i]; + } + } + + this.drawShape(new Phaser.Polygon(points)); + + return this; + +}; + +/** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @method Phaser.Graphics#clear + * @return {Graphics} + */ +Phaser.Graphics.prototype.clear = function () { + + this.lineWidth = 0; + this.filling = false; + + this.dirty = true; + this._boundsDirty = true; + this.clearDirty = true; + this.graphicsData = []; + + this.updateLocalBounds(); + + return this; + +}; + +/** + * Useful function that returns a texture of the graphics object that can then be used to create sprites + * This can be quite useful if your geometry is complicated and needs to be reused multiple times. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * @method Phaser.Graphics#generateTexture + * @param [resolution=1] {Number} The resolution of the texture being generated + * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts + * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0) + * @return {Texture} a texture of the graphics object + */ +Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, padding) { + + if (resolution === undefined) { resolution = 1; } + if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; } + if (padding === undefined) { padding = 0; } + + var bounds = this.getBounds(); + + bounds.width += padding; + bounds.height += padding; + + var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution); + + var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + + canvasBuffer.context.scale(resolution, resolution); + + canvasBuffer.context.translate(-bounds.x, -bounds.y); + + PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context); + + return texture; + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Graphics#_renderWebGL +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderWebGL = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture on the gpu too! + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.worldAlpha = this.worldAlpha; + + PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); + + return; + } + else + { + renderSession.spriteBatch.stop(); + renderSession.blendModeManager.setBlendMode(this.blendMode); + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + if (this._filters) + { + renderSession.filterManager.pushFilter(this._filterBlock); + } + + // check blend mode + if (this.blendMode !== renderSession.spriteBatch.currentBlendMode) + { + renderSession.spriteBatch.currentBlendMode = this.blendMode; + var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode]; + renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); + } + + // check if the webgl graphic needs to be updated + if (this.webGLDirty) + { + this.dirty = true; + this.webGLDirty = false; + } + + PIXI.WebGLGraphics.renderGraphics(this, renderSession); + + // only render if it has children! + if (this.children.length) + { + renderSession.spriteBatch.start(); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + renderSession.spriteBatch.stop(); + } + + if (this._filters) + { + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + renderSession.maskManager.popMask(this.mask, renderSession); + } + + renderSession.drawCount++; + + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the object using the Canvas renderer +* +* @method Phaser.Graphics#_renderCanvas +* @param renderSession {RenderSession} +* @private +*/ +Phaser.Graphics.prototype._renderCanvas = function (renderSession) { + + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.visible === false || this.alpha === 0 || this.isMask === true) + { + return; + } + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) + { + this.dirty = true; + this._prevTint = this.tint; + } + + if (this._cacheAsBitmap) + { + if (this.dirty || this.cachedSpriteDirty) + { + this._generateCachedSprite(); + + // we will also need to update the texture + this.updateCachedSpriteTexture(); + + this.cachedSpriteDirty = false; + this.dirty = false; + } + + this._cachedSprite.alpha = this.alpha; + + PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); + + return; + } + else + { + var context = renderSession.context; + var transform = this.worldTransform; + + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + var resolution = renderSession.resolution; + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + tx, + ty); + + PIXI.CanvasGraphics.renderGraphics(this, context); + + // simple render children! + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + } + +}; + +/** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @method Phaser.Graphics#getBounds + * @return {Rectangle} the rectangular bounding area + */ +Phaser.Graphics.prototype.getBounds = function (matrix) { + + if (this._currentBounds) + { + return this._currentBounds; + } + + // Return an empty object if the item is a mask! + if (!this.renderable) + { + return Phaser.EmptyRectangle; + } + + if (this.dirty) + { + this.updateLocalBounds(); + this.webGLDirty = true; + this.cachedSpriteDirty = true; + this.dirty = false; + } + + var bounds = this._localBounds; + + var w0 = bounds.x; + var w1 = bounds.width + bounds.x; + + var h0 = bounds.y; + var h1 = bounds.height + bounds.y; + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = x1; + var maxY = y1; + + var minX = x1; + var minY = y1; + + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x2 > maxX ? 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; + + this._bounds.x = minX; + this._bounds.width = maxX - minX; + + this._bounds.y = minY; + this._bounds.height = maxY - minY; + + this._currentBounds = this._bounds; + + return this._currentBounds; + +}; + +/** + * Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration. + * + * @method Phaser.Graphics#getLocalBounds + * @return {Rectangle} The rectangular bounding area + */ +Phaser.Graphics.prototype.getLocalBounds = function () { + + var matrixCache = this.worldTransform; + + this.worldTransform = Phaser.identityMatrix; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + var bounds = this.getBounds(); + + this.worldTransform = matrixCache; + + for (i = 0; i < this.children.length; i++) + { + this.children[i].updateTransform(); + } + + return bounds; + +}; + +/** +* Tests if a point is inside this graphics object +* +* @param point {Point} the point to test +* @return {boolean} the result of the test +*/ +Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) { + + if (tempPoint === undefined) { tempPoint = new Phaser.Point(); } + + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; i++) + { + var data = graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // only deal with fills.. + if (data.shape) + { + if (data.shape.contains(tempPoint.x, tempPoint.y)) + { + return true; + } + } + } + + return false; + +}; + +/** + * Update the bounds of the object + * + * @method Phaser.Graphics#updateLocalBounds + */ +Phaser.Graphics.prototype.updateLocalBounds = function () { + + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) + { + var shape, points, x, y, w, h; + + for (var i = 0; i < this.graphicsData.length; i++) + { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + shape = data.shape; + + if (type === Phaser.RECTANGLE || type === Phaser.ROUNDEDRECTANGLE) + { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.CIRCLE) + { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === Phaser.ELLIPSE) + { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else + { + // POLY - assumes points are sequential, not Point objects + points = shape.points; + + for (var j = 0; j < points.length; j++) + { + if (points[j] instanceof Phaser.Point) + { + x = points[j].x; + y = points[j].y; + } + else + { + x = points[j]; + y = points[j + 1]; + + if (j < points.length - 1) + { + j++; + } + } + + minX = x - lineWidth < minX ? x - lineWidth : minX; + maxX = x + lineWidth > maxX ? x + lineWidth : maxX; + + minY = y - lineWidth < minY ? y - lineWidth : minY; + maxY = y + lineWidth > maxY ? y + lineWidth : maxY; + } + } + } + } + else + { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.x = minX - padding; + this._localBounds.width = (maxX - minX) + padding * 2; + + this._localBounds.y = minY - padding; + this._localBounds.height = (maxY - minY) + padding * 2; + +}; + +/** + * Generates the cached sprite when the sprite has cacheAsBitmap = true + * + * @method Phaser.Graphics#_generateCachedSprite + * @private + */ +Phaser.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); + } + + // leverage the anchor to account for the offset of the element + this._cachedSprite.anchor.x = -(bounds.x / bounds.width); + this._cachedSprite.anchor.y = -(bounds.y / bounds.height); + + // this._cachedSprite.buffer.context.save(); + this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y); + + // make sure we set the alpha of the graphics to 1 for the render.. + this.worldAlpha = 1; + + // now render the graphic.. + PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context); + this._cachedSprite.alpha = this.alpha; + +}; + +/** + * Updates texture size based on canvas size + * + * @method Phaser.Graphics#updateCachedSpriteTexture + * @private + */ +Phaser.Graphics.prototype.updateCachedSpriteTexture = function () { + + var cachedSprite = this._cachedSprite; + var texture = cachedSprite.texture; + var canvas = cachedSprite.buffer.canvas; + + texture.baseTexture.width = canvas.width; + texture.baseTexture.height = canvas.height; + texture.crop.width = texture.frame.width = canvas.width; + texture.crop.height = texture.frame.height = canvas.height; + + cachedSprite._width = canvas.width; + cachedSprite._height = canvas.height; + + // update the dirty base textures + texture.baseTexture.dirty(); + +}; + +/** + * Destroys a previous cached sprite. + * + * @method Phaser.Graphics#destroyCachedSprite + */ +Phaser.Graphics.prototype.destroyCachedSprite = function () { + + this._cachedSprite.texture.destroy(true); + this._cachedSprite = null; + +}; + +/** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @method Phaser.Graphics#drawShape + * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. + * @return {GraphicsData} The generated GraphicsData object. + */ +Phaser.Graphics.prototype.drawShape = function (shape) { + + if (this.currentPath) + { + // check current path! + if (this.currentPath.shape.points.length <= 2) + { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + // Handle mixed-type polygons + if (shape instanceof Phaser.Polygon) + { + shape = shape.clone(); + shape.flatten(); + } + + var data = new Phaser.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === Phaser.POLYGON) + { + data.shape.closed = this.filling; + this.currentPath = data; + } + + this.dirty = true; + this._boundsDirty = true; + + return data; + +}; + +/** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory. + * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas. + * This is not recommended if you are constantly redrawing the graphics element. + * + * @property cacheAsBitmap + * @type Boolean + * @default false + * @private + */ +Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', { + + get: function () { + + return this._cacheAsBitmap; + + }, + + set: function (value) { + + this._cacheAsBitmap = value; + + if (this._cacheAsBitmap) + { + this._generateCachedSprite(); + } + else + { + this.destroyCachedSprite(); + } + + this.dirty = true; + this.webGLDirty = true; + + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and +* render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. +* +* @class Phaser.RenderTexture +* @constructor +* @extends PIXI.Texture +* @param {Phaser.Game} game - Current game instance. +* @param {number} [width=100] - The width of the render texture. +* @param {number} [height=100] - The height of the render texture. +* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there. +* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts. +* @param {number} [resolution=1] - The resolution of the texture being generated. +*/ +Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution, renderer, textureUnit) { + + if (width === undefined) { width = 100; } + if (height === undefined) { height = 100; } + if (key === undefined) { key = ''; } + if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; } + if (resolution === undefined) { resolution = 1; } + if (renderer === undefined) { renderer = PIXI.defaultRenderer; } + if (textureUnit === undefined) { textureUnit = 0; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the RenderTexture in the Cache, if stored there. + */ + this.key = key; + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RENDERTEXTURE; + + /** + * @property {Phaser.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture. + * @private + */ + this._tempMatrix = new Phaser.Matrix(); + + this.width = width; + this.height = height; + this.resolution = resolution; + + this.frame = new Phaser.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); + + this.crop = this.frame.clone(); + + /** + * The base texture object that this texture uses + * + * @property baseTexture + * @type BaseTexture + */ + this.baseTexture = new PIXI.BaseTexture(); + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + this.baseTexture._glTextures = []; + this.baseTexture.resolution = this.resolution; + + this.baseTexture.scaleMode = scaleMode; + + this.baseTexture.hasLoaded = true; + + PIXI.Texture.call(this, this.baseTexture, this.frame.clone()); + + /** + * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. + * + * @property renderer + * @type CanvasRenderer|WebGLRenderer + */ + this.renderer = renderer; + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + this.baseTexture.textureIndex = textureUnit; + this.baseTexture._dirty[gl.id] = false; + + this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode, textureUnit); + this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; + + this.projection = new Phaser.Point(this.width * 0.5, -this.height * 0.5); + } + else + { + this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution); + this.baseTexture.source = this.textureBuffer.canvas; + } + + /** + * @property valid + * @type Boolean + */ + this.valid = true; + + this.tempMatrix = new Phaser.Matrix(); + + this._updateUvs(); + +}; + +Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype); +Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it takes into account scale and rotation. +* +* If you don't want those then use RenderTexture.renderRawXY instead. +* +* @method Phaser.RenderTexture.prototype.renderXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) { + + displayObject.updateTransform(); + + this._tempMatrix.copyFrom(displayObject.worldTransform); + this._tempMatrix.tx = x; + this._tempMatrix.ty = y; + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture at the given coordinates. +* +* When the display object is drawn it doesn't take into account scale, rotation or translation. +* +* If you need those then use RenderTexture.renderXY instead. +* +* @method Phaser.RenderTexture.prototype.renderRawXY +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {number} x - The x position to render the object at. +* @param {number} y - The y position to render the object at. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) { + + this._tempMatrix.identity().translate(x, y); + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* This function will draw the display object to the RenderTexture. +* +* In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. +* This is now a Matrix allowing you much more control over how the Display Object is rendered. +* If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. +* +* If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either +* pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. +* +* @method Phaser.RenderTexture.prototype.render +* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. +* @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. +* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. +*/ +Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) { + + if (matrix === undefined || matrix === null) + { + this._tempMatrix.copyFrom(displayObject.worldTransform); + } + else + { + this._tempMatrix.copyFrom(matrix); + } + + if (this.renderer.type === Phaser.WEBGL) + { + this._renderWebGL(displayObject, this._tempMatrix, clear); + } + else + { + this._renderCanvas(displayObject, this._tempMatrix, clear); + } + +}; + +/** +* Resizes the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.resize +* @param {number} width - The width to resize to. +* @param {number} height - The height to resize to. +* @param {boolean} updateBase - Should the baseTexture.width and height values be resized as well? +*/ +Phaser.RenderTexture.prototype.resize = function (width, height, updateBase) { + + if (width === this.width && height === this.height) + { + return; + } + + this.valid = (width > 0 && height > 0); + + this.width = width; + this.height = height; + this.frame.width = this.crop.width = width * this.resolution; + this.frame.height = this.crop.height = height * this.resolution; + + if (updateBase) + { + this.baseTexture.width = this.width * this.resolution; + this.baseTexture.height = this.height * this.resolution; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.projection.x = this.width / 2; + this.projection.y = -this.height / 2; + } + + if (!this.valid) + { + return; + } + + this.textureBuffer.resize(this.width, this.height); + +}; + +/** +* Clears the RenderTexture. +* +* @method Phaser.RenderTexture.prototype.clear +*/ +Phaser.RenderTexture.prototype.clear = function () { + + if (!this.valid) + { + return; + } + + if (this.renderer.type === Phaser.WEBGL) + { + this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + } + + this.textureBuffer.clear(); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderWebGL +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +* @private +*/ +Phaser.RenderTexture.prototype._renderWebGL = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + wt.translate(0, this.projection.y * 2); + + if (matrix) + { + wt.append(matrix); + } + + wt.scale(1, -1); + + // Time to update all the children of the displayObject with the new matrix. + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + // Time for the webGL fun stuff! + var gl = this.renderer.gl; + + gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + + if (clear) + { + this.textureBuffer.clear(); + } + + this.renderer.spriteBatch.dirty = true; + + this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix); + + this.renderer.spriteBatch.dirty = true; + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + +}; + +/** +* This function will draw the display object to the texture. +* +* @private +* @method Phaser.RenderTexture.prototype._renderCanvas +* @param displayObject {DisplayObject} The display object to render this texture on +* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. +* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn +*/ +Phaser.RenderTexture.prototype._renderCanvas = function (displayObject, matrix, clear) { + + if (!this.valid || displayObject.alpha === 0) + { + return; + } + + // Let's create a nice matrix to apply to our display object. + // Frame buffers come in upside down so we need to flip the matrix. + var wt = displayObject.worldTransform; + wt.identity(); + + if (matrix) + { + wt.append(matrix); + } + + // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!) + for (var i = 0; i < displayObject.children.length; i++) + { + displayObject.children[i].updateTransform(); + } + + if (clear) + { + this.textureBuffer.clear(); + } + + var realResolution = this.renderer.resolution; + + this.renderer.resolution = this.resolution; + + this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix); + + this.renderer.resolution = realResolution; + +}; + +/** +* Will return a HTML Image of the texture +* +* @method Phaser.RenderTexture.prototype.getImage +* @return {Image} +*/ +Phaser.RenderTexture.prototype.getImage = function () { + + var image = new Image(); + image.src = this.getBase64(); + + return image; + +}; + +/** +* Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. +* +* @method Phaser.RenderTexture.prototype.getBase64 +* @return {String} A base64 encoded string of the texture. +*/ +Phaser.RenderTexture.prototype.getBase64 = function () { + + return this.getCanvas().toDataURL(); + +}; + +/** +* Creates a Canvas element, renders this RenderTexture to it and then returns it. +* +* @method Phaser.RenderTexture.prototype.getCanvas +* @return {HTMLCanvasElement} A Canvas element with the texture rendered on. +*/ +Phaser.RenderTexture.prototype.getCanvas = function () { + + if (this.renderer.type === Phaser.WEBGL) + { + var gl = this.renderer.gl; + var width = this.textureBuffer.width; + var height = this.textureBuffer.height; + + var webGLPixels = new Uint8Array(4 * width * height); + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer); + gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + var tempCanvas = new PIXI.CanvasBuffer(width, height); + var canvasData = tempCanvas.context.getImageData(0, 0, width, height); + canvasData.data.set(webGLPixels); + + tempCanvas.context.putImageData(canvasData, 0, 0); + + return tempCanvas.canvas; + } + else + { + return this.textureBuffer.canvas; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new game object for displaying Text. +* +* This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. +* Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. +* +* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers. +* +* @class Phaser.Text +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {number} x - X position of the new text object. +* @param {number} y - Y position of the new text object. +* @param {string} text - The actual text that will be written. +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +*/ +Phaser.Text = function (game, x, y, text, style) { + + x = x || 0; + y = y || 0; + + if (text === undefined || text === null) + { + text = ''; + } + else + { + text = text.toString(); + } + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.TEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * Specify a padding value which is added to the line width and height when calculating the Text size. + * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. + * @property {Phaser.Point} padding + */ + this.padding = new Phaser.Point(); + + /** + * The textBounds property allows you to specify a rectangular region upon which text alignment is based. + * See `Text.setTextBounds` for more details. + * @property {Phaser.Rectangle} textBounds + * @readOnly + */ + this.textBounds = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered. + */ + this.canvas = Phaser.CanvasPool.create(this); + + /** + * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to. + */ + this.context = this.canvas.getContext('2d'); + + /** + * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}. + */ + this.colors = []; + + /** + * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}. + */ + this.strokeColors = []; + + /** + * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}. + */ + this.fontStyles = []; + + /** + * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}. + */ + this.fontWeights = []; + + /** + * Should the linePositionX and Y values be automatically rounded before rendering the Text? + * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. + * @property {boolean} autoRound + * @default + */ + this.autoRound = false; + + /** + * Will this Text object use Basic or Advanced Word Wrapping? + * + * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. + * White space is condensed (e.g., consecutive spaces are replaced with one). + * Lines are trimmed of white space before processing. + * + * It throws an error if wordWrapWidth is less than a single character. + * @property {boolean} useAdvancedWrap + * @default + */ + this.useAdvancedWrap = false; + + /** + * The Regular Expression that is used to split the text up into lines, in + * multi-line text. By default this is `/(?:\r\n|\r|\n)/`. + * You can change this RegExp to be anything else that you may need. + * @property {Object} splitRegExp + */ + this.splitRegExp = /(?:\r\n|\r|\n)/; + + + /** The maximum number of characters that can be set. + * @property {number} characterLimitSize + */ + this.characterLimitSize = -1; + + /** The suffix that is applied to truncated text that is longer than the + * characterLimitSize. + * @property {string} characterLimitSuffix + */ + this.characterLimitSuffix = ''; + + /** + * @property {number} _res - Internal canvas resolution var. + * @private + */ + this._res = game.renderer.resolution; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text; + + /** + * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`. + * @private + */ + this._fontComponents = null; + + /** + * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. + * @private + */ + this._lineSpacing = 0; + + /** + * @property {number} _charCount - Internal character counter used by the text coloring. + * @private + */ + this._charCount = 0; + + /** + * @property {number} _width - Internal width var. + * @private + */ + this._width = 0; + + /** + * @property {number} _height - Internal height var. + * @private + */ + this._height = 0; + + Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas)); + + /** + * @property {object} style + * @private + */ + this.style = {}; + + this.setStyle(style || {}); + + if (text !== '') + { + this.updateText(); + } + +}; + +Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Text.prototype.constructor = Phaser.Text; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Text#preUpdate +* @protected +*/ +Phaser.Text.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override this function to handle any special update requirements. +* +* @method Phaser.Text#update +* @protected +*/ +Phaser.Text.prototype.update = function() { + +}; + +/** +* Destroy this Text object, removing it from the group it belongs to. +* +* @method Phaser.Text#destroy +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.Text.prototype.destroy = function (destroyChildren) { + + this.texture.destroy(true); + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + +}; + +/** +* Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. +* The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. +* The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. +* To remove a shadow already in place you can call this method with no parameters set. +* +* @method Phaser.Text#setShadow +* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +* @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. +* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +* @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set). +* @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; } + if (blur === undefined) { blur = 0; } + if (shadowStroke === undefined) { shadowStroke = true; } + if (shadowFill === undefined) { shadowFill = true; } + + this.style.shadowOffsetX = x; + this.style.shadowOffsetY = y; + this.style.shadowColor = color; + this.style.shadowBlur = blur; + this.style.shadowStroke = shadowStroke; + this.style.shadowFill = shadowFill; + this.dirty = true; + + return this; + +}; + +/** +* Set the style of the text by passing a single style object to it. +* +* @method Phaser.Text#setStyle +* @param {object} [style] - The style properties to be set on the Text. +* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. +* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. +* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. +* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. +* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. +* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. +* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). +* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. +* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). +* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. +* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. +* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. +* @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. +* @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setStyle = function (style, update) { + + if (update === undefined) { update = false; } + + var newStyle = Object.assign({}, style); + newStyle.font = style.font || 'bold 20pt Arial'; + newStyle.backgroundColor = style.backgroundColor || null; + newStyle.fill = style.fill || 'black'; + newStyle.align = (style.align || 'left').toLowerCase(); + newStyle.boundsAlignH = (style.boundsAlignH || 'left').toLowerCase(); + newStyle.boundsAlignV = (style.boundsAlignV || 'top').toLowerCase(); + newStyle.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136 + newStyle.strokeThickness = Number(style.strokeThickness) || 0; + newStyle.wordWrap = style.wordWrap || false; + newStyle.wordWrapWidth = style.wordWrapWidth || 100; + newStyle.maxLines = style.maxLines || 0; + newStyle.shadowOffsetX = style.shadowOffsetX || 0; + newStyle.shadowOffsetY = style.shadowOffsetY || 0; + newStyle.shadowColor = style.shadowColor || 'rgba(0,0,0,0)'; + newStyle.shadowBlur = style.shadowBlur || 0; + newStyle.tabs = style.tabs || 0; + + var components = this.fontToComponents(newStyle.font); + + if (newStyle.fontStyle) + { + components.fontStyle = newStyle.fontStyle; + } + + if (newStyle.fontVariant) + { + components.fontVariant = newStyle.fontVariant; + } + + if (newStyle.fontWeight) + { + components.fontWeight = newStyle.fontWeight; + } + + if (newStyle.fontSize) + { + if (typeof newStyle.fontSize === 'number') + { + newStyle.fontSize = newStyle.fontSize + 'px'; + } + + components.fontSize = newStyle.fontSize; + } + + this._fontComponents = components; + + newStyle.font = this.componentsToFont(this._fontComponents); + + this.style = newStyle; + this.dirty = true; + + if (update) + { + this.updateText(); + } + + return this; + +}; + +/** +* Renders text to the internal canvas. +* +* @method Phaser.Text#updateText +* @private +*/ +Phaser.Text.prototype.updateText = function () { + + this.texture.baseTexture.resolution = this._res; + + this.context.font = this.style.font; + + var outputText = this.text; + + if (this.characterLimitSize > -1 && this.characterLimitSize < outputText.length) { + outputText = this.text.substring(0, this.characterLimitSize) + this.characterLimitSuffix; + } + + if (this.style.wordWrap) + { + outputText = this.runWordWrap(this.text); + } + + // Split text into lines + var lines = outputText.split(this.splitRegExp); + + // Calculate text width + var tabs = this.style.tabs; + var lineWidths = []; + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this.style.font); + + var drawnLines = lines.length; + + if (this.style.maxLines > 0 && this.style.maxLines < lines.length) + { + drawnLines = this.style.maxLines; + } + + this._charCount = 0; + + for (var i = 0; i < drawnLines; i++) + { + if (tabs === 0) + { + // Simple layout (no tabs) + var lineWidth = this.style.strokeThickness + this.padding.x; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(lines[i]); + } + else + { + lineWidth += this.context.measureText(lines[i]).width; + } + + // Adjust for wrapped text + if (this.style.wordWrap) + { + lineWidth -= this.context.measureText(' ').width; + } + } + else + { + // Complex layout (tabs) + var line = lines[i].split(/(?:\t)/); + var lineWidth = this.padding.x + this.style.strokeThickness; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < line.length; c++) + { + var section = 0; + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + section = this.measureLine(line[c]); + } + else + { + section = Math.ceil(this.context.measureText(line[c]).width); + } + + if (c > 0) + { + tab += tabs[c - 1]; + } + + lineWidth = tab + section; + } + } + else + { + for (var c = 0; c < line.length; c++) + { + // How far to the next tab? + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + lineWidth += this.measureLine(line[c]); + } + else + { + lineWidth += Math.ceil(this.context.measureText(line[c]).width); + } + + var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth; + + lineWidth += diff; + } + } + } + + lineWidths[i] = Math.ceil(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidths[i]); + } + + this.canvas.width = maxLineWidth * this._res; + + // Calculate text height + var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y; + var height = lineHeight * drawnLines; + var lineSpacing = this._lineSpacing; + + if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight) + { + lineSpacing = -lineHeight; + } + + // Adjust for line spacing + if (lineSpacing !== 0) + { + height += (lineSpacing > 0) ? lineSpacing * lines.length : lineSpacing * (lines.length - 1); + } + + this.canvas.height = height * this._res; + + this.context.scale(this._res, this._res); + + if (navigator.isCocoonJS) + { + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + } + + if (this.style.backgroundColor) + { + this.context.fillStyle = this.style.backgroundColor; + this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); + } + + this.context.fillStyle = this.style.fill; + this.context.font = this.style.font; + this.context.strokeStyle = this.style.stroke; + this.context.textBaseline = 'alphabetic'; + + this.context.lineWidth = this.style.strokeThickness; + this.context.lineCap = 'round'; + this.context.lineJoin = 'round'; + + var linePositionX; + var linePositionY; + + this._charCount = 0; + + // Draw text line by line + for (i = 0; i < drawnLines; i++) + { + // Split the line by + + linePositionX = this.style.strokeThickness / 2; + linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (i > 0) + { + linePositionY += (lineSpacing * i); + } + + if (this.style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (this.style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (this.autoRound) + { + linePositionX = Math.round(linePositionX); + linePositionY = Math.round(linePositionY); + } + + if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + this.updateLine(lines[i], linePositionX, linePositionY); + } + else + { + if (this.style.stroke && this.style.strokeThickness) + { + this.updateShadow(this.style.shadowStroke); + + if (tabs === 0) + { + this.context.strokeText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, false); + } + } + + if (this.style.fill) + { + this.updateShadow(this.style.shadowFill); + + if (tabs === 0) + { + this.context.fillText(lines[i], linePositionX, linePositionY); + } + else + { + this.renderTabLine(lines[i], linePositionX, linePositionY, true); + } + } + } + } + + this.updateTexture(); + + this.dirty = false; + +}; + +/** +* Renders a line of text that contains tab characters if Text.tab > 0. +* Called automatically by updateText. +* +* @method Phaser.Text#renderTabLine +* @private +* @param {string} line - The line of text to render. +* @param {integer} x - The x position to start rendering from. +* @param {integer} y - The y position to start rendering from. +* @param {boolean} fill - If true uses fillText, if false uses strokeText. +*/ +Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) { + + var text = line.split(/(?:\t)/); + var tabs = this.style.tabs; + var snap = 0; + + if (Array.isArray(tabs)) + { + var tab = 0; + + for (var c = 0; c < text.length; c++) + { + if (c > 0) + { + tab += tabs[c - 1]; + } + + snap = x + tab; + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + } + } + else + { + for (var c = 0; c < text.length; c++) + { + var section = Math.ceil(this.context.measureText(text[c]).width); + + // How far to the next tab? + snap = this.game.math.snapToCeil(x, tabs); + + if (fill) + { + this.context.fillText(text[c], snap, y); + } + else + { + this.context.strokeText(text[c], snap, y); + } + + x = snap + section; + } + } + +}; + +/** +* Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. +* This is called automatically by Text.updateText. +* +* @method Phaser.Text#updateShadow +* @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero. +*/ +Phaser.Text.prototype.updateShadow = function (state) { + + if (state) + { + this.context.shadowOffsetX = this.style.shadowOffsetX; + this.context.shadowOffsetY = this.style.shadowOffsetY; + this.context.shadowColor = this.style.shadowColor; + this.context.shadowBlur = this.style.shadowBlur; + } + else + { + this.context.shadowOffsetX = 0; + this.context.shadowOffsetY = 0; + this.context.shadowColor = 0; + this.context.shadowBlur = 0; + } + +}; + +/** +* Measures a line of text character by character taking into the account the specified character styles. +* +* @method Phaser.Text#measureLine +* @private +* @param {string} line - The line of text to measure. +* @return {integer} length of the line. +*/ +Phaser.Text.prototype.measureLine = function (line) { + + var lineLength = 0; + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + } + + lineLength += this.context.measureText(letter).width; + + this._charCount++; + } + + return Math.ceil(lineLength); +}; + +/** +* Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable. +* +* @method Phaser.Text#updateLine +* @private +*/ +Phaser.Text.prototype.updateLine = function (line, x, y) { + + for (var i = 0; i < line.length; i++) + { + var letter = line[i]; + + if (this.fontWeights.length > 0 || this.fontStyles.length > 0) + { + var components = this.fontToComponents(this.context.font); + + if (this.fontStyles[this._charCount]) + { + components.fontStyle = this.fontStyles[this._charCount]; + } + + if (this.fontWeights[this._charCount]) + { + components.fontWeight = this.fontWeights[this._charCount]; + } + + this.context.font = this.componentsToFont(components); + } + + if (this.style.stroke && this.style.strokeThickness) + { + if (this.strokeColors[this._charCount]) + { + this.context.strokeStyle = this.strokeColors[this._charCount]; + } + + this.updateShadow(this.style.shadowStroke); + this.context.strokeText(letter, x, y); + } + + if (this.style.fill) + { + if (this.colors[this._charCount]) + { + this.context.fillStyle = this.colors[this._charCount]; + } + + this.updateShadow(this.style.shadowFill); + this.context.fillText(letter, x, y); + } + + x += this.context.measureText(letter).width; + + this._charCount++; + } + +}; + +/** +* Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. +* +* @method Phaser.Text#clearColors +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearColors = function () { + + this.colors = []; + this.strokeColors = []; + this.dirty = true; + + return this; + +}; + +/** +* Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. +* +* @method Phaser.Text#clearFontValues +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.clearFontValues = function () { + + this.fontStyles = []; + this.fontWeights = []; + this.dirty = true; + + return this; + +}; + +/** +* Set specific colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* If you wish to change the stroke color see addStrokeColor instead. +* +* @method Phaser.Text#addColor +* @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addColor = function (color, position) { + + this.colors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific stroke colors for certain characters within the Text. +* +* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. +* The position value is the index of the character in the Text string to start applying this color to. +* Once set the color remains in use until either another color or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. +* +* This has no effect if stroke is disabled or has a thickness of 0. +* +* If you wish to change the text fill color see addColor instead. +* +* @method Phaser.Text#addStrokeColor +* @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. +* @param {number} position - The index of the character in the string to start applying this color value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addStrokeColor = function (color, position) { + + this.strokeColors[position] = color; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font styles for certain characters within the Text. +* +* It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. +* The position value is the index of the character in the Text string to start applying this font style to. +* Once set the font style remains in use until either another font style or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. +* +* If you wish to change the text font weight see addFontWeight instead. +* +* @method Phaser.Text#addFontStyle +* @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. +* @param {number} position - The index of the character in the string to start applying this font style value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontStyle = function (style, position) { + + this.fontStyles[position] = style; + this.dirty = true; + + return this; + +}; + +/** +* Set specific font weights for certain characters within the Text. +* +* It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. +* The position value is the index of the character in the Text string to start applying this font weight to. +* Once set the font weight remains in use until either another font weight or the end of the string is encountered. +* For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. +* +* If you wish to change the text font style see addFontStyle instead. +* +* @method Phaser.Text#addFontWeight +* @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. +* @param {number} position - The index of the character in the string to start applying this font weight value from. +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.addFontWeight = function (weight, position) { + + this.fontWeights[position] = weight; + this.dirty = true; + + return this; + +}; + +/** +* Runs the given text through the Text.runWordWrap function and returns +* the results as an array, where each element of the array corresponds to a wrapped +* line of text. +* +* Useful if you wish to control pagination on long pieces of content. +* +* @method Phaser.Text#precalculateWordWrap +* @param {string} text - The text for which the wrapping will be calculated. +* @return {array} An array of strings with the pieces of wrapped text. +*/ +Phaser.Text.prototype.precalculateWordWrap = function (text) { + + this.texture.baseTexture.resolution = this._res; + this.context.font = this.style.font; + + var wrappedLines = this.runWordWrap(text); + + return wrappedLines.split(/(?:\r\n|\r|\n)/); + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#runWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.runWordWrap = function (text) { + + if (this.useAdvancedWrap) + { + return this.advancedWordWrap(text); + } + else + { + return this.basicWordWrap(text); + } + +}; + +/** +* Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* White space is condensed (e.g., consecutive spaces are replaced with one). +* Lines are trimmed of white space before processing. +* Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character. +* +* @method Phaser.Text#advancedWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.advancedWordWrap = function (text) { + + var context = this.context; + var wordWrapWidth = this.style.wordWrapWidth; + + var output = ''; + + // (1) condense whitespace + // (2) split into lines + var lines = text + .replace(/ +/gi, ' ') + .split(/\r?\n/gi); + + var linesCount = lines.length; + + for (var i = 0; i < linesCount; i++) + { + var line = lines[i]; + var out = ''; + + // trim whitespace + line = line.replace(/^ *|\s*$/gi, ''); + + // if entire line is less than wordWrapWidth + // append the entire line and exit early + var lineWidth = context.measureText(line).width; + + if (lineWidth < wordWrapWidth) + { + output += line + '\n'; + continue; + } + + // otherwise, calculate new lines + var currentLineWidth = wordWrapWidth; + + // split into words + var words = line.split(' '); + + for (var j = 0; j < words.length; j++) + { + var word = words[j]; + var wordWithSpace = word + ' '; + var wordWidth = context.measureText(wordWithSpace).width; + + if (wordWidth > currentLineWidth) + { + // break word + if (j === 0) + { + // shave off letters from word until it's small enough + var newWord = wordWithSpace; + + while (newWord.length) + { + newWord = newWord.slice(0, -1); + wordWidth = context.measureText(newWord).width; + + if (wordWidth <= currentLineWidth) + { + break; + } + } + + // if wordWrapWidth is too small for even a single + // letter, shame user failure with a fatal error + if (!newWord.length) + { + throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); + } + + // replace current word in array with remainder + var secondPart = word.substr(newWord.length); + + words[j] = secondPart; + + // append first piece to output + out += newWord; + } + + // if existing word length is 0, don't include it + var offset = (words[j].length) ? j : j + 1; + + // collapse rest of sentence + var remainder = words.slice(offset).join(' ') + // remove any trailing white space + .replace(/[ \n]*$/gi, ''); + + // prepend remainder to next line + lines[i + 1] = remainder + ' ' + (lines[i + 1] || ''); + linesCount = lines.length; + + break; // processing on this line + + // append word with space to output + } + else + { + out += wordWithSpace; + currentLineWidth -= wordWidth; + } + } + + // append processed line to output + output += out.replace(/[ \n]*$/gi, '') + '\n'; + } + + // trim the end of the string + output = output.replace(/[\s|\n]*$/gi, ''); + + return output; + +}; + +/** +* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. +* +* @method Phaser.Text#basicWordWrap +* @param {string} text - The text to perform word wrap detection against. +* @private +*/ +Phaser.Text.prototype.basicWordWrap = function (text) { + + var result = ''; + var lines = text.split('\n'); + + for (var i = 0; i < lines.length; i++) + { + var spaceLeft = this.style.wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) + { + var wordWidth = this.context.measureText(words[j]).width; + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is greater than the word wrap width. + if (j > 0) + { + result += '\n'; + } + result += words[j] + ' '; + spaceLeft = this.style.wordWrapWidth - wordWidth; + } + else + { + spaceLeft -= wordWidthWithSpace; + result += words[j] + ' '; + } + } + + if (i < lines.length-1) + { + result += '\n'; + } + } + + return result; + +}; + +/** +* Updates the internal `style.font` if it now differs according to generation from components. +* +* @method Phaser.Text#updateFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.updateFont = function (components) { + + var font = this.componentsToFont(components); + + if (this.style.font !== font) + { + this.style.font = font; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + +}; + +/** +* Converting a short CSS-font string into the relevant components. +* +* @method Phaser.Text#fontToComponents +* @private +* @param {string} font - a CSS font string +*/ +Phaser.Text.prototype.fontToComponents = function (font) { + + // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand: + // style - normal | italic | oblique | inherit + // variant - normal | small-caps | inherit + // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit + // size - xx-small | x-small | small | medium | large | x-large | xx-large, + // larger | smaller + // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %) + // font-family - rest (but identifiers or quoted with comma separation) + var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/); + + if (m) + { + var family = m[5].trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(family) && !/['",]/.exec(family)) + { + family = "'" + family + "'"; + } + + return { + font: font, + fontStyle: m[1] || 'normal', + fontVariant: m[2] || 'normal', + fontWeight: m[3] || 'normal', + fontSize: m[4] || 'medium', + fontFamily: family + }; + } + else + { + console.warn("Phaser.Text - unparsable CSS font: " + font); + + return { + font: font + }; + } + +}; + +/** +* Converts individual font components (see `fontToComponents`) to a short CSS font string. +* +* @method Phaser.Text#componentsToFont +* @private +* @param {object} components - Font components. +*/ +Phaser.Text.prototype.componentsToFont = function (components) { + + var parts = []; + var v; + + v = components.fontStyle; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontVariant; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontWeight; + if (v && v !== 'normal') { parts.push(v); } + + v = components.fontSize; + if (v && v !== 'medium') { parts.push(v); } + + v = components.fontFamily; + if (v) { parts.push(v); } + + if (!parts.length) + { + // Fallback to whatever value the 'font' was + parts.push(components.font); + } + + return parts.join(" "); + +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* Use the optional `immediate` argument if you need the Text display to update immediately. +* +* If not it will re-create the texture of this Text object during the next time the render +* loop is called. +* +* @method Phaser.Text#setText +* @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present. +* @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). +* @return {Phaser.Text} This Text instance. +*/ +Phaser.Text.prototype.setText = function (text, immediate) { + + if (immediate === undefined) { immediate = false; } + + this.text = text.toString() || ''; + + if (immediate) + { + this.updateText(); + } + else + { + this.dirty = true; + } + + return this; + +}; + +/** + * Converts the given array into a tab delimited string and then updates this Text object. + * This is mostly used when you want to display external data using tab stops. + * + * The array can be either single or multi dimensional depending on the result you need: + * + * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`. + * + * Where as: + * + * `[ + * [ 'a', 'b', 'c' ], + * [ 'd', 'e', 'f'] + * ]` + * + * would convert in to: `"a\tb\tc\nd\te\tf"` + * + * @method Phaser.Text#parseList + * @param {array} list - The array of data to convert into a string. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.parseList = function (list) { + + if (!Array.isArray(list)) + { + return this; + } + else + { + var s = ""; + + for (var i = 0; i < list.length; i++) + { + if (Array.isArray(list[i])) + { + s += list[i].join("\t"); + + if (i < list.length - 1) + { + s += "\n"; + } + } + else + { + s += list[i]; + + if (i < list.length - 1) + { + s += "\t"; + } + } + } + } + + this.text = s; + this.dirty = true; + + return this; + +}; + +/** + * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned, + * regardless of the number of lines in the text, the font size or any other attribute. + * + * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly + * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment. + * + * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to + * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of + * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center + * of the text bounds. + * + * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions + * may vary based on font (say for multi-lingual games). + * + * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width. + * + * Call this method with no arguments given to reset an existing textBounds. + * + * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts + * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot` + * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then + * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot. + * + * @method Phaser.Text#setTextBounds + * @param {number} [x] - The x coordinate of the Text Bounds region. + * @param {number} [y] - The y coordinate of the Text Bounds region. + * @param {number} [width] - The width of the Text Bounds region. + * @param {number} [height] - The height of the Text Bounds region. + * @return {Phaser.Text} This Text instance. + */ +Phaser.Text.prototype.setTextBounds = function (x, y, width, height) { + + if (x === undefined) + { + this.textBounds = null; + } + else + { + if (!this.textBounds) + { + this.textBounds = new Phaser.Rectangle(x, y, width, height); + } + else + { + this.textBounds.setTo(x, y, width, height); + } + + if (this.style.wordWrapWidth > width) + { + this.style.wordWrapWidth = width; + } + } + + this.updateTexture(); + + return this; + +}; + +/** + * Updates the texture based on the canvas dimensions. + * + * @method Phaser.Text#updateTexture + * @private + */ +Phaser.Text.prototype.updateTexture = function () { + + var base = this.texture.baseTexture; + var crop = this.texture.crop; + var frame = this.texture.frame; + + var w = this.canvas.width; + var h = this.canvas.height; + + base.width = w; + base.height = h; + + crop.width = w; + crop.height = h; + + frame.width = w; + frame.height = h; + + this.texture.width = w; + this.texture.height = h; + + this._width = w; + this._height = h; + + if (this.textBounds) + { + var x = this.textBounds.x; + var y = this.textBounds.y; + + // Align the canvas based on the bounds + if (this.style.boundsAlignH === 'right') + { + x += this.textBounds.width - this.canvas.width / this.resolution; + } + else if (this.style.boundsAlignH === 'center') + { + x += this.textBounds.halfWidth - (this.canvas.width / this.resolution / 2); + } + + if (this.style.boundsAlignV === 'bottom') + { + y += this.textBounds.height - this.canvas.height / this.resolution; + } + else if (this.style.boundsAlignV === 'middle') + { + y += this.textBounds.halfHeight - (this.canvas.height / this.resolution / 2); + } + + this.pivot.x = -x; + this.pivot.y = -y; + } + + // Can't render something with a zero sized dimension + this.renderable = (w !== 0 && h !== 0); + + this.texture.requiresReTint = true; + + this.texture.baseTexture.dirty(); + +}; + +/** +* Renders the object using the WebGL renderer +* +* @method Phaser.Text#_renderWebGL +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderWebGL = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Renders the object using the Canvas renderer. +* +* @method Phaser.Text#_renderCanvas +* @private +* @param {RenderSession} renderSession - The Render Session to render the Text on. +*/ +Phaser.Text.prototype._renderCanvas = function (renderSession) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Calculates the ascent, descent and fontSize of a given font style. +* +* @method Phaser.Text#determineFontProperties +* @private +* @param {object} fontStyle +*/ +Phaser.Text.prototype.determineFontProperties = function (fontStyle) { + + var properties = Phaser.Text.fontPropertiesCache[fontStyle]; + + if (!properties) + { + properties = {}; + + var canvas = Phaser.Text.fontPropertiesCanvas; + var context = Phaser.Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('|MÉq').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + if (!context.getImageData(0, 0, width, height)) + { + properties.ascent = baseline; + properties.descent = baseline + 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + } + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i, j; + + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + properties.descent = i - baseline; + //TODO might need a tweak. kind of a temp fix! + properties.descent += 6; + properties.fontSize = properties.ascent + properties.descent; + + Phaser.Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; + +}; + +/** +* Returns the bounds of the Text as a rectangle. +* The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Text#getBounds +* @param {Phaser.Matrix} matrix - The transformation matrix of the Text. +* @return {Phaser.Rectangle} The framing rectangle +*/ +Phaser.Text.prototype.getBounds = function (matrix) { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return PIXI.Sprite.prototype.getBounds.call(this, matrix); + +}; + +/** +* Sets the character limit of the text, with a suffix. +* If the text is longer than this limit, it is truncated and the suffix is appended. +* +* @method Phaser.Text#setCharacterLimit +* @param {number} [characterLimit] - The x coordinate of the Text Bounds region. +* @param {string} [suffix] - The suffix to append to the truncated text. +*/ +Phaser.Text.prototype.setCharacterLimit = function (characterLimit, suffix) { + + this.characterLimitSuffix = (suffix === undefined) ? '' : suffix; + this.characterLimitSize = characterLimit; + + this.updateText(); +}; + +/** +* The text to be displayed by this Text object. +* Use a \n to insert a carriage return and split the text. +* The text will be rendered with any style currently set. +* +* @name Phaser.Text#text +* @property {string} text +*/ +Object.defineProperty(Phaser.Text.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* Change the font used. +* +* This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except +* that unlike using `setStyle` this will not change any current font fill/color settings. +* +* The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. +* +* @name Phaser.Text#cssFont +* @property {string} cssFont +*/ +Object.defineProperty(Phaser.Text.prototype, 'cssFont', { + + get: function() { + return this.componentsToFont(this._fontComponents); + }, + + set: function (value) + { + value = value || 'bold 20pt Arial'; + this._fontComponents = this.fontToComponents(value); + this.updateFont(this._fontComponents); + } + +}); + +/** +* Change the font family that the text will be rendered in, such as 'Arial'. +* +* Multiple CSS font families and generic fallbacks can be specified as long as +* {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed. +* +* To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`. +* +* @name Phaser.Text#font +* @property {string} font +*/ +Object.defineProperty(Phaser.Text.prototype, 'font', { + + get: function() { + return this._fontComponents.fontFamily; + }, + + set: function(value) { + + value = value || 'Arial'; + value = value.trim(); + + // If it looks like the value should be quoted, but isn't, then quote it. + if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value)) + { + value = "'" + value + "'"; + } + + this._fontComponents.fontFamily = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The size of the font. +* +* If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing +* the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). +* +* @name Phaser.Text#fontSize +* @property {number|string} fontSize +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontSize', { + + get: function() { + + var size = this._fontComponents.fontSize; + + if (size && /(?:^0$|px$)/.exec(size)) + { + return parseInt(size, 10); + } + else + { + return size; + } + + }, + + set: function(value) { + + value = value || '0'; + + if (typeof value === 'number') + { + value = value + 'px'; + } + + this._fontComponents.fontSize = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}. +* @name Phaser.Text#fontWeight +* @property {string} fontWeight +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontWeight', { + + get: function() { + return this._fontComponents.fontWeight || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontWeight = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The style of the font: 'normal', 'italic', 'oblique' +* @name Phaser.Text#fontStyle +* @property {string} fontStyle +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontStyle', { + + get: function() { + return this._fontComponents.fontStyle || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontStyle = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* The variant the font: 'normal', 'small-caps' +* @name Phaser.Text#fontVariant +* @property {string} fontVariant +*/ +Object.defineProperty(Phaser.Text.prototype, 'fontVariant', { + + get: function() { + return this._fontComponents.fontVariant || 'normal'; + }, + + set: function(value) { + + value = value || 'normal'; + this._fontComponents.fontVariant = value; + this.updateFont(this._fontComponents); + + } + +}); + +/** +* @name Phaser.Text#fill +* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'fill', { + + get: function() { + return this.style.fill; + }, + + set: function(value) { + + if (value !== this.style.fill) + { + this.style.fill = value; + this.dirty = true; + } + + } + +}); + +/** +* Controls the horizontal alignment for multiline text. +* Can be: 'left', 'center' or 'right'. +* Does not affect single lines of text. For that please see `setTextBounds`. +* @name Phaser.Text#align +* @property {string} align +*/ +Object.defineProperty(Phaser.Text.prototype, 'align', { + + get: function() { + return this.style.align; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.align) + { + this.style.align = value; + this.dirty = true; + } + + } + +}); + +/** +* The resolution of the canvas the text is rendered to. +* This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. +* @name Phaser.Text#resolution +* @property {integer} resolution +*/ +Object.defineProperty(Phaser.Text.prototype, 'resolution', { + + get: function() { + return this._res; + }, + + set: function(value) { + + if (value !== this._res) + { + this._res = value; + this.dirty = true; + } + + } + +}); + +/** +* The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. +* Can be an integer or an array of varying tab sizes, one tab per element. +* For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. +* If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. +* +* @name Phaser.Text#tabs +* @property {integer|array} tabs +*/ +Object.defineProperty(Phaser.Text.prototype, 'tabs', { + + get: function() { + return this.style.tabs; + }, + + set: function(value) { + + if (value !== this.style.tabs) + { + this.style.tabs = value; + this.dirty = true; + } + + } + +}); + +/** +* Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. +* @name Phaser.Text#boundsAlignH +* @property {string} boundsAlignH +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', { + + get: function() { + return this.style.boundsAlignH; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignH) + { + this.style.boundsAlignH = value; + this.dirty = true; + } + + } + +}); + +/** +* Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. +* @name Phaser.Text#boundsAlignV +* @property {string} boundsAlignV +*/ +Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', { + + get: function() { + return this.style.boundsAlignV; + }, + + set: function(value) { + + value = value.toLowerCase(); + if (value !== this.style.boundsAlignV) + { + this.style.boundsAlignV = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#stroke +* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. +*/ +Object.defineProperty(Phaser.Text.prototype, 'stroke', { + + get: function() { + return this.style.stroke; + }, + + set: function(value) { + + if (value !== this.style.stroke) + { + this.style.stroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#strokeThickness +* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke) +*/ +Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', { + + get: function() { + return this.style.strokeThickness; + }, + + set: function(value) { + + if (value !== this.style.strokeThickness) + { + this.style.strokeThickness = Number(value); + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrap +* @property {boolean} wordWrap - Indicates if word wrap should be used. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrap', { + + get: function() { + return this.style.wordWrap; + }, + + set: function(value) { + + if (value !== this.style.wordWrap) + { + this.style.wordWrap = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#wordWrapWidth +* @property {number} wordWrapWidth - The width at which text will wrap. +*/ +Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', { + + get: function() { + return this.style.wordWrapWidth; + }, + + set: function(value) { + + if (value !== this.style.wordWrapWidth) + { + this.style.wordWrapWidth = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#lineSpacing +* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. +*/ +Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { + + get: function() { + return this._lineSpacing; + }, + + set: function(value) { + + if (value !== this._lineSpacing) + { + this._lineSpacing = parseFloat(value); + this.dirty = true; + + if (this.parent) + { + this.updateTransform(); + } + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetX +* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', { + + get: function() { + return this.style.shadowOffsetX; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetX) + { + this.style.shadowOffsetX = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowOffsetY +* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', { + + get: function() { + return this.style.shadowOffsetY; + }, + + set: function(value) { + + if (value !== this.style.shadowOffsetY) + { + this.style.shadowOffsetY = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowColor +* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowColor', { + + get: function() { + return this.style.shadowColor; + }, + + set: function(value) { + + if (value !== this.style.shadowColor) + { + this.style.shadowColor = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowBlur +* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', { + + get: function() { + return this.style.shadowBlur; + }, + + set: function(value) { + + if (value !== this.style.shadowBlur) + { + this.style.shadowBlur = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowStroke +* @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', { + + get: function() { + return this.style.shadowStroke; + }, + + set: function(value) { + + if (value !== this.style.shadowStroke) + { + this.style.shadowStroke = value; + this.dirty = true; + } + + } + +}); + +/** +* @name Phaser.Text#shadowFill +* @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill. +*/ +Object.defineProperty(Phaser.Text.prototype, 'shadowFill', { + + get: function() { + return this.style.shadowFill; + }, + + set: function(value) { + + if (value !== this.style.shadowFill) + { + this.style.shadowFill = value; + this.dirty = true; + } + + } + +}); + +/** +* The width of the Text object in pixels. This is width of the Texture frame / the Text.resolution. +* @name Phaser.Text#width +* @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'width', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.x * (this.texture.frame.width / this.resolution); + }, + + set: function(value) { + + this.scale.x = value / this.texture.frame.width; + this._width = value; + } + +}); + +/** +* The height of the Text object in pixels. This is height of the Texture frame / the Text.resolution. +* @name Phaser.Text#height +* @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested. +*/ +Object.defineProperty(Phaser.Text.prototype, 'height', { + + get: function() { + + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } + + return this.scale.y * (this.texture.frame.height / this.resolution); + }, + + set: function(value) { + + this.scale.y = value / this.texture.frame.height; + this._height = value; + } + +}); + +Phaser.Text.fontPropertiesCache = {}; + +Phaser.Text.fontPropertiesCanvas = document.createElement('canvas'); +Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d'); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. +* It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to +* match the font structure. +* +* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability +* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by +* processing the font texture in an image editor, applying fills and any other effects required. +* +* To create multi-line text insert \r, \n or \r\n escape codes into the text string. +* +* If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly +* updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. +* +* To create a BitmapText data files you can use: +* +* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ +* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner +* Littera (Web-based, free): http://kvazars.com/littera/ +* +* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of +* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson +* +* If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. +* +* @class Phaser.BitmapText +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - X coordinate to display the BitmapText object at. +* @param {number} y - Y coordinate to display the BitmapText object at. +* @param {string} font - The key of the BitmapText as stored in Phaser.Cache. +* @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. +* @param {number} [size=32] - The size the font will be rendered at in pixels. +* @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. +*/ +Phaser.BitmapText = function (game, x, y, font, text, size, align) { + + x = x || 0; + y = y || 0; + font = font || ''; + text = text || ''; + size = size || 32; + align = align || 'left'; + + PIXI.DisplayObjectContainer.call(this); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.BITMAPTEXT; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textWidth = 0; + + /** + * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ + this.textHeight = 0; + + /** + * @property {Phaser.Point} anchor - The anchor value of this BitmapText. + */ + this.anchor = new Phaser.Point(); + + /** + * @property {Phaser.Point} _prevAnchor - The previous anchor value. + * @private + */ + this._prevAnchor = new Phaser.Point(); + + /** + * @property {array} _glyphs - Private tracker for the letter sprite pool. + * @private + */ + this._glyphs = []; + + /** + * @property {number} _maxWidth - Internal cache var. + * @private + */ + this._maxWidth = 0; + + /** + * @property {string} _text - Internal cache var. + * @private + */ + this._text = text.toString() || ''; + + /** + * @property {string} _data - Internal cache var. + * @private + */ + this._data = game.cache.getBitmapFont(font); + + /** + * @property {string} _font - Internal cache var. + * @private + */ + this._font = font; + + /** + * @property {number} _fontSize - Internal cache var. + * @private + */ + this._fontSize = size; + + /** + * @property {string} _align - Internal cache var. + * @private + */ + this._align = align; + + /** + * @property {number} _tint - Internal cache var. + * @private + */ + this._tint = 0xFFFFFF; + + this.updateText(); + + /** + * @property {boolean} dirty - The dirty state of this object. + */ + this.dirty = false; + + Phaser.Component.Core.init.call(this, game, x, y, '', null); + +}; + +Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.BitmapText.prototype.constructor = Phaser.BitmapText; + +Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [ + 'Angle', + 'AutoCull', + 'Bounds', + 'Destroy', + 'FixedToCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'PhysicsBody', + 'Reset' +]); + +Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method +* @memberof Phaser.BitmapText +* @return {boolean} True if the BitmapText was rendered, otherwise false. +*/ +Phaser.BitmapText.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.preUpdate. +* @method Phaser.BitmapText.prototype.postUpdate +*/ +Phaser.BitmapText.prototype.postUpdate = function () { + + Phaser.Component.PhysicsBody.postUpdate.call(this); + Phaser.Component.FixedToCamera.postUpdate.call(this); + + if (this.body && this.body.type === Phaser.Physics.ARCADE) + { + if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight)) + { + this.body.setSize(this.textWidth, this.textHeight); + } + } + +}; + +/** +* The text to be displayed by this BitmapText object. +* +* It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. +* +* @method Phaser.BitmapText.prototype.setText +* @param {string} text - The text to be displayed by this BitmapText object. +*/ +Phaser.BitmapText.prototype.setText = function (text) { + + this.text = text; + +}; + +/** +* Given the input text this will scan the characters until either a newline is encountered, +* or the line exceeds maxWidth, taking into account kerning, character widths and scaling. +* +* @method Phaser.BitmapText.prototype.scanLine +* @private +* @param {object} data - A reference to the font object in the Phaser.Cache. +* @param {float} scale - The scale of the font in relation to the texture. +* @param {string} text - The text to parse. +* @return {object} An object containing the parsed characters, total pixel width and x offsets. +*/ +Phaser.BitmapText.prototype.scanLine = function (data, scale, text) { + + var x = 0; + var w = 0; + var lastSpace = -1; + var wrappedWidth = 0; + var prevCharCode = null; + var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null; + var chars = []; + + // Let's scan the text and work out if any of the lines are > maxWidth + for (var i = 0; i < text.length; i++) + { + var end = (i === text.length - 1) ? true : false; + + if (/(?:\r\n|\r|\n)/.test(text.charAt(i))) + { + return { width: w, text: text.substr(0, i), end: end, chars: chars }; + } + else + { + var charCode = text.charCodeAt(i); + var charData = data.chars[charCode]; + + var c = 0; + + // If the character data isn't found in the data array + // then we replace it with a blank space + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + // Adjust for kerning from previous character to this one + var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0; + + // Record the last space in the string and the current width + if (/(\s)/.test(text.charAt(i))) + { + lastSpace = i; + wrappedWidth = w; + } + + // What will the line width be if we add this character to it? + c = (kerning + charData.texture.width + charData.xOffset) * scale; + + // Do we need to line-wrap? + if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1) + { + // The last space was at "lastSpace" which was "i - lastSpace" characters ago + return { width: wrappedWidth || w, text: text.substr(0, i - (i - lastSpace)), end: false, chars: chars }; + } + else + { + w += (charData.xAdvance + kerning) * scale; + + chars.push(x + (charData.xOffset + kerning) * scale); + + x += (charData.xAdvance + kerning) * scale; + + prevCharCode = charCode; + } + } + } + + return { width: w, text: text, end: end, chars: chars }; + +}; + +/** +* Given a text string this will scan each character in the string to ensure it exists +* in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. +* +* If no font data has been loaded at all this returns an empty string, as nothing can be rendered. +* +* @method Phaser.BitmapText.prototype.cleanText +* @param {string} text - The text to parse. +* @param {string} [replace=''] - The replacement string for any missing characters. +* @return {string} The cleaned text string. +*/ +Phaser.BitmapText.prototype.cleanText = function (text, replace) { + + if (replace === undefined) + { + replace = ''; + } + + var data = this._data.font; + + if (!data) + { + return ''; + } + + var re = /\r\n|\n\r|\n|\r/g; + var lines = text.replace(re, "\n").split("\n"); + + for (var i = 0; i < lines.length; i++) + { + var output = ''; + var line = lines[i]; + + for (var c = 0; c < line.length; c++) + { + if (data.chars[line.charCodeAt(c)]) + { + output = output.concat(line[c]); + } + else + { + output = output.concat(replace); + } + } + + lines[i] = output; + } + + return lines.join("\n"); + +}; + +/** +* Renders text and updates it when needed. +* +* @method Phaser.BitmapText.prototype.updateText +* @private +*/ +Phaser.BitmapText.prototype.updateText = function () { + + var data = this._data.font; + + if (!data) + { + return; + } + + var text = this.text; + var scale = this._fontSize / data.size; + var lines = []; + + var y = 0; + + this.textWidth = 0; + + do + { + var line = this.scanLine(data, scale, text); + + line.y = y; + + lines.push(line); + + if (line.width > this.textWidth) + { + this.textWidth = line.width; + } + + y += (data.lineHeight * scale); + + text = text.substr(line.text.length + 1); + + } while (line.end === false); + + this.textHeight = y; + + var t = 0; + var align = 0; + var ax = this.textWidth * this.anchor.x; + var ay = this.textHeight * this.anchor.y; + + for (var i = 0; i < lines.length; i++) + { + var line = lines[i]; + + if (this._align === 'right') + { + align = this.textWidth - line.width; + } + else if (this._align === 'center') + { + align = (this.textWidth - line.width) / 2; + } + + for (var c = 0; c < line.text.length; c++) + { + var charCode = line.text.charCodeAt(c); + var charData = data.chars[charCode]; + + if (charData === undefined) + { + charCode = 32; + charData = data.chars[charCode]; + } + + var g = this._glyphs[t]; + + if (g) + { + // Sprite already exists in the glyphs pool, so we'll reuse it for this letter + g.texture = charData.texture; + } + else + { + // We need a new sprite as the pool is empty or exhausted + g = new PIXI.Sprite(charData.texture); + g.name = line.text[c]; + this._glyphs.push(g); + } + + g.position.x = (line.chars[c] + align) - ax; + g.position.y = (line.y + (charData.yOffset * scale)) - ay; + + g.scale.set(scale); + g.tint = this.tint; + g.texture.requiresReTint = true; + g.cachedTint = 0xFFFFFF; + + if (!g.parent) + { + this.addChild(g); + } + + t++; + } + } + + // Remove unnecessary children + // This moves them from the display list (children array) but retains them in the _glyphs pool + for (i = t; i < this._glyphs.length; i++) + { + this.removeChild(this._glyphs[i]); + } + +}; + +/** +* If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of +* Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they +* still take up memory while sat in the glyphs pool waiting to be re-used in the future. +* +* If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool +* by calling this method. +* +* Calling this doesn't prevent you from increasing the length of the text again in the future. +* +* @method Phaser.BitmapText.prototype.purgeGlyphs +* @return {integer} The amount of glyphs removed from the pool. +*/ +Phaser.BitmapText.prototype.purgeGlyphs = function () { + + var len = this._glyphs.length; + var kept = []; + + for (var i = 0; i < this._glyphs.length; i++) + { + if (this._glyphs[i].parent !== this) + { + this._glyphs[i].destroy(); + } + else + { + kept.push(this._glyphs[i]); + } + } + + this._glyphs = []; + this._glyphs = kept; + + this.updateText(); + + return len - kept.length; + +}; + +/** +* Updates the transform of this object. +* +* @method Phaser.BitmapText.prototype.updateTransform +* @private +*/ +Phaser.BitmapText.prototype.updateTransform = function () { + + if (this.dirty || !this.anchor.equals(this._prevAnchor)) + { + this.updateText(); + this.dirty = false; + this._prevAnchor.copyFrom(this.anchor); + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/** +* @name Phaser.BitmapText#align +* @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'align', { + + get: function() { + return this._align; + }, + + set: function(value) { + + if (value !== this._align && (value === 'left' || value === 'center' || value === 'right')) + { + this._align = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#tint +* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'tint', { + + get: function() { + return this._tint; + }, + + set: function(value) { + + if (value !== this._tint) + { + this._tint = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#font +* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'font', { + + get: function() { + return this._font; + }, + + set: function(value) { + + if (value !== this._font) + { + this._font = value.trim(); + this._data = this.game.cache.getBitmapFont(this._font); + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#fontSize +* @property {number} fontSize - The size of the font in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { + + get: function() { + return this._fontSize; + }, + + set: function(value) { + + value = parseInt(value, 10); + + if (value !== this._fontSize && value > 0) + { + this._fontSize = value; + this.updateText(); + } + + } + +}); + +/** +* @name Phaser.BitmapText#text +* @property {string} text - The text to be displayed by this BitmapText object. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'text', { + + get: function() { + return this._text; + }, + + set: function(value) { + + if (value !== this._text) + { + this._text = value.toString() || ''; + this.updateText(); + } + + } + +}); + +/** +* The maximum display width of this BitmapText in pixels. +* +* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped +* based on the last whitespace character found in the line. +* +* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. +* +* Disable maxWidth by setting the value to 0. +* +* @name Phaser.BitmapText#maxWidth +* @property {number} maxWidth - The maximum width of this BitmapText in pixels. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', { + + get: function() { + + return this._maxWidth; + + }, + + set: function(value) { + + if (value !== this._maxWidth) + { + this._maxWidth = value; + this.updateText(); + } + + } + +}); + +/** +* Enable or disable texture smoothing for this BitmapText. +* +* The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. +* +* Smoothing is enabled by default. +* +* @name Phaser.BitmapText#smoothed +* @property {boolean} smoothed +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', { + + get: function() { + + return !this._data.base.scaleMode; + + }, + + set: function(value) { + + if (value) + { + this._data.base.scaleMode = 0; + } + else + { + this._data.base.scaleMode = 1; + } + this._data.base.dirty(); + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont +* is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. +* +* @class Phaser.RetroFont +* @extends Phaser.RenderTexture +* @constructor +* @param {Phaser.Game} game - Current game instance. +* @param {string} key - The font set graphic set as stored in the Game.Cache. +* @param {number} characterWidth - The width of each character in the font set. +* @param {number} characterHeight - The height of each character in the font set. +* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. +* @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. +* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. +* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { + + if (!game.cache.checkImageKey(key)) + { + return false; + } + + if (charsPerRow === undefined || charsPerRow === null) + { + charsPerRow = game.cache.getImage(key).width / characterWidth; + } + + /** + * @property {number} characterWidth - The width of each character in the font set. + */ + this.characterWidth = characterWidth; + + /** + * @property {number} characterHeight - The height of each character in the font set. + */ + this.characterHeight = characterHeight; + + /** + * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here. + */ + this.characterSpacingX = xSpacing || 0; + + /** + * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here. + */ + this.characterSpacingY = ySpacing || 0; + + /** + * @property {number} characterPerRow - The number of characters per row in the font set. + */ + this.characterPerRow = charsPerRow; + + /** + * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @readonly + */ + this.offsetX = xOffset || 0; + + /** + * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @readonly + */ + this.offsetY = yOffset || 0; + + /** + * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + */ + this.align = "left"; + + /** + * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) + * @default + */ + this.multiLine = false; + + /** + * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. + * @default + */ + this.autoUpperCase = true; + + /** + * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels. + * @default + */ + this.customSpacingX = 0; + + /** + * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels. + * @default + */ + this.customSpacingY = 0; + + /** + * If you need this RetroFont image to have a fixed width you can set the width in this value. + * If text is wider than the width specified it will be cropped off. + * @property {number} fixedWidth + */ + this.fixedWidth = 0; + + /** + * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font. + */ + this.fontSet = game.cache.getImage(key); + + /** + * @property {string} _text - The text of the font image. + * @private + */ + this._text = ''; + + /** + * @property {array} grabData - An array of rects for faster character pasting. + * @private + */ + this.grabData = []; + + /** + * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font. + */ + this.frameData = new Phaser.FrameData(); + + // Now generate our rects for faster copying later on + var currentX = this.offsetX; + var currentY = this.offsetY; + var r = 0; + + for (var c = 0; c < chars.length; c++) + { + var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight)); + + this.grabData[chars.charCodeAt(c)] = frame.index; + + r++; + + if (r === this.characterPerRow) + { + r = 0; + currentX = this.offsetX; + currentY += this.characterHeight + this.characterSpacingY; + } + else + { + currentX += this.characterWidth + this.characterSpacingX; + } + } + + game.cache.updateFrameData(key, this.frameData); + + /** + * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font. + * @readonly + */ + this.stamp = new Phaser.Image(game, 0, 0, key, 0); + + Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST); + + /** + * @property {number} type - Base Phaser object type. + */ + this.type = Phaser.RETROFONT; + +}; + +Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype); +Phaser.RetroFont.prototype.constructor = Phaser.RetroFont; + +/** +* Align each line of multi-line text to the left. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_LEFT = "left"; + +/** +* Align each line of multi-line text to the right. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_RIGHT = "right"; + +/** +* Align each line of multi-line text in the center. +* @constant +* @type {string} +*/ +Phaser.RetroFont.ALIGN_CENTER = "center"; + +/** +* Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + +/** +* Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "; + +/** +* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789"; + +/** +* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789"; + +/** +* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' "; + +/** +* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39"; + +/** +* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!"; + +/** +* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +/** +* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 +* @constant +* @type {string} +*/ +Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789"; + +/** +* If you need this RetroFont to have a fixed width and custom alignment you can set the width here. +* If text is wider than the width specified it will be cropped off. +* +* @method Phaser.RetroFont#setFixedWidth +* @memberof Phaser.RetroFont +* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. +* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +*/ +Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) { + + if (lineAlignment === undefined) { lineAlignment = 'left'; } + + this.fixedWidth = width; + this.align = lineAlignment; + +}; + +/** +* A helper function that quickly sets lots of variables at once, and then updates the text. +* +* @method Phaser.RetroFont#setText +* @memberof Phaser.RetroFont +* @param {string} content - The text of this sprite. +* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. +* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels. +* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels. +* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. +* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. +*/ +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; + } + +}; + +/** +* Updates the texture with the new text. +* +* @method Phaser.RetroFont#buildRetroFontText +* @memberof Phaser.RetroFont +*/ +Phaser.RetroFont.prototype.buildRetroFontText = function () { + + var cx = 0; + var cy = 0; + + // Clears the textureBuffer + 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); + } + + // Loop through each line of text + for (var i = 0; i < lines.length; i++) + { + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + // This line of text is held in lines[i] - need to work out the alignment + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(lines[i], cx, cy, this.customSpacingX); + + cy += this.characterHeight + this.customSpacingY; + } + } + else + { + if (this.fixedWidth > 0) + { + this.resize(this.fixedWidth, this.characterHeight, true); + } + else + { + this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true); + } + + // Phaser.RetroFont.ALIGN_LEFT + cx = 0; + + if (this.align === Phaser.RetroFont.ALIGN_RIGHT) + { + cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX)); + } + else if (this.align === Phaser.RetroFont.ALIGN_CENTER) + { + cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2); + cx += this.customSpacingX / 2; + } + + // Sanity checks + if (cx < 0) + { + cx = 0; + } + + this.pasteLine(this._text, cx, 0, this.customSpacingX); + } + + this.requiresReTint = true; + +}; + +/** +* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. +* Used by getLine and getMultiLine +* +* @method Phaser.RetroFont#pasteLine +* @memberof Phaser.RetroFont +* @param {string} line - The single line of text to paste. +* @param {number} x - The x coordinate. +* @param {number} y - The y coordinate. +* @param {number} customSpacingX - Custom X spacing. +*/ +Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) { + + for (var c = 0; c < line.length; c++) + { + // If it's a space then there is no point copying, so leave a blank space + if (line.charAt(c) === " ") + { + x += this.characterWidth + customSpacingX; + } + else + { + // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it + if (this.grabData[line.charCodeAt(c)] >= 0) + { + this.stamp.frame = this.grabData[line.charCodeAt(c)]; + this.renderXY(this.stamp, x, y, false); + + x += this.characterWidth + customSpacingX; + + if (x > this.width) + { + break; + } + } + } + } +}; + +/** +* Works out the longest line of text in _text and returns its length +* +* @method Phaser.RetroFont#getLongestLine +* @memberof Phaser.RetroFont +* @return {number} The length of the longest line of text. +*/ +Phaser.RetroFont.prototype.getLongestLine = function () { + + var longestLine = 0; + + if (this._text.length > 0) + { + var lines = this._text.split("\n"); + + for (var i = 0; i < lines.length; i++) + { + if (lines[i].length > longestLine) + { + longestLine = lines[i].length; + } + } + } + + return longestLine; +}; + +/** +* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set. +* +* @method Phaser.RetroFont#removeUnsupportedCharacters +* @memberof Phaser.RetroFont +* @protected +* @param {boolean} [stripCR=true] - Should it strip carriage returns as well? +* @return {string} A clean version of the string. +*/ +Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) { + + var newString = ""; + + for (var c = 0; c < this._text.length; c++) + { + var aChar = this._text[c]; + var code = aChar.charCodeAt(0); + + if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n")) + { + newString = newString.concat(aChar); + } + } + + return newString; + +}; + +/** +* Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. +* Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. +* So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. +* +* @method Phaser.RetroFont#updateOffset +* @memberof Phaser.RetroFont +* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. +* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. +*/ +Phaser.RetroFont.prototype.updateOffset = function (x, y) { + + if (this.offsetX === x && this.offsetY === y) + { + return; + } + + var diffX = x - this.offsetX; + var diffY = y - this.offsetY; + + var frames = this.game.cache.getFrameData(this.stamp.key).getFrames(); + var i = frames.length; + + while (i--) + { + frames[i].x += diffX; + frames[i].y += diffY; + } + + this.buildRetroFontText(); + +}; + +/** +* @name Phaser.RetroFont#text +* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. +*/ +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(); + } + + } + +}); + +/** +* @name Phaser.RetroFont#smoothed +* @property {boolean} smoothed - Sets if the stamp is smoothed or not. +*/ +Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", { + + get: function () { + + return this.stamp.smoothed; + + }, + + set: function (value) { + + this.stamp.smoothed = value; + this.buildRetroFontText(); + + } + +}); + +/** +* @author Richard Davey +* @author Mat Groves (@Doormat23) +* @author Rovanion Luckey +* @copyright 2016 Photon Storm Ltd, Richard Davey +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Rope is a Sprite that has a repeating texture. +* +* The texture will automatically wrap on the edges as it moves. +* +* Please note that Ropes cannot have an input handler. +* +* @class Phaser.Rope +* @constructor +* @extends PIXI.DisplayObjectContainer +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Crop +* @extends Phaser.Component.Delta +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.ScaleMinMax +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Rope at. +* @param {number} y - The y coordinate (in world space) to position the Rope at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @param {Array} points - An array of {Phaser.Point}. +*/ +Phaser.Rope = function (game, x, y, key, frame, points) { + + this.points = points || []; + this._hasUpdateAnimation = false; + this._updateAnimationCallback = null; + x = x || 0; + y = y || 0; + key = key || null; + frame = frame || null; + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.ROPE; + + PIXI.DisplayObjectContainer.call(this); + + this.texture = Phaser.Cache.DEFAULT; + + // set up the main bits.. + this.uvs = new Float32Array([0, 1, + 1, 1, + 1, 0, + 0, 1]); + + this.vertices = new Float32Array([0, 0, + 100, 0, + 100, 100, + 0, 100]); + + this.colors = new Float32Array([1, 1, 1, 1]); + + this.indices = new Uint16Array([0, 1, 2, 3]); + + if (points) + { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + /** + * Whether the strip is dirty or not + * + * @property dirty + * @type Boolean + */ + this.dirty = true; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. + * + * @property canvasPadding + * @type Number + */ + this.canvasPadding = 0; + + this.drawMode = Phaser.Rope.TRIANGLE_STRIP; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + + this.refresh(); + +}; + +Phaser.Rope.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); +Phaser.Rope.prototype.constructor = Phaser.Rope; + +Phaser.Component.Core.install.call(Phaser.Rope.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Crop', + 'Delta', + 'Destroy', + 'FixedToCamera', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'ScaleMinMax', + 'Smoothed' +]); + +Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +Phaser.Rope.TRIANGLE_STRIP = 0; +Phaser.Rope.TRIANGLES = 1; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.Rope#preUpdate +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.preUpdate = function () { + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Override and use this function in your own custom objects to handle any update requirements you may have. +* +* @method Phaser.Rope#update +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.update = function() { + + if (this._hasUpdateAnimation) + { + this.updateAnimation.call(this); + } + +}; + +/** +* Resets the Rope. This places the Rope at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the Rope has a physics body that too is reset. +* +* @method Phaser.Rope#reset +* @memberof Phaser.Rope +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.Rope} This instance. +*/ +Phaser.Rope.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + return this; + +}; + +/* +* Refreshes the rope texture and UV coordinates. +* +* @method Phaser.Rope#refresh +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.refresh = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + this.count -= 0.2; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + var index; + var amount; + + for (var i = 1; i < total; i++) + { + index = i * 4; + + // time to do some smart drawing! + amount = i / (total - 1); + + if (i % 2) + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + else + { + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + +}; + +/* +* Updates the Ropes transform ready for rendering. +* +* @method Phaser.Rope#updateTransform +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.updateTransform = function () { + + var points = this.points; + + if (points.length < 1) + { + return; + } + + var lastPoint = points[0]; + var nextPoint; + var perp = { x:0, y:0 }; + + this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + var point; + var index; + var ratio; + var perpLength; + var num; + + for (var i = 0; i < total; i++) + { + point = points[i]; + index = i * 4; + + if(i < points.length - 1) + { + nextPoint = points[i + 1]; + } + else + { + nextPoint = point; + } + + perp.y = -(nextPoint.x - lastPoint.x); + perp.x = nextPoint.y - lastPoint.y; + + ratio = (1 - (i / (total - 1))) * 10; + + if (ratio > 1) + { + ratio = 1; + } + + perpLength = Math.sqrt((perp.x * perp.x) + (perp.y * perp.y)); + num = this.texture.height / 2; + perp.x /= perpLength; + perp.y /= perpLength; + + perp.x *= num; + perp.y *= num; + + vertices[index] = point.x + perp.x; + vertices[index + 1] = point.y + perp.y; + vertices[index + 2] = point.x - perp.x; + vertices[index + 3] = point.y - perp.y; + + lastPoint = point; + } + + PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); + +}; + +/* +* Sets the Texture this Rope uses for rendering. +* +* @method Phaser.Rope#setTexture +* @memberof Phaser.Rope +* @param {Texture} texture - The texture that will be used. +*/ +Phaser.Rope.prototype.setTexture = function (texture) { + + this.texture = texture; + +}; + +/* +* Renders the Rope to WebGL. +* +* @private +* @method Phaser.Rope#_renderWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || this.alpha <= 0) + { + return; + } + + renderSession.spriteBatch.stop(); + + if (!this._vertexBuffer) + { + this._initWebGL(renderSession); + } + + renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader); + + this._renderStrip(renderSession); + + renderSession.spriteBatch.start(); + +}; + +/* +* Builds the Strip. +* +* @private +* @method Phaser.Rope#_initWebGL +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._initWebGL = function (renderSession) { + + // build the strip! + var gl = renderSession.gl; + + this._vertexBuffer = gl.createBuffer(); + this._indexBuffer = gl.createBuffer(); + this._uvBuffer = gl.createBuffer(); + this._colorBuffer = gl.createBuffer(); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + +}; + +/* +* Renders the Strip to WebGL. +* +* @private +* @method Phaser.Rope#_renderStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderStrip = function (renderSession) { + + var gl = renderSession.gl; + var projection = renderSession.projection; + var offset = renderSession.offset; + var shader = renderSession.shaderManager.stripShader; + + var drawMode = (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + renderSession.blendModeManager.setBlendMode(this.blendMode); + + // set uniforms + gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true)); + gl.uniform2f(shader.projectionVector, projection.x, -projection.y); + gl.uniform2f(shader.offsetVector, -offset.x, -offset.y); + gl.uniform1f(shader.alpha, this.worldAlpha); + + if (!this.dirty) + { + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + // bind the current texture + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + } + else + { + this.dirty = false; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); + + // update the uvs + gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW); + gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); + + gl.activeTexture(gl.TEXTURE0); + + // check if a texture is dirty.. + if (this.texture.baseTexture._dirty[gl.id]) + { + renderSession.renderer.updateTexture(this.texture.baseTexture); + } + else + { + gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); + } + + gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0); + +}; + +/* +* Renders the Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvas +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvas = function (renderSession) { + + var context = renderSession.context; + + var transform = this.worldTransform; + + var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX; + var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY; + + if (renderSession.roundPixels) + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx | 0, ty | 0); + } + else + { + context.setTransform(transform.a, transform.b, transform.c, transform.d, tx, ty); + } + + if (this.drawMode === Phaser.Rope.TRIANGLE_STRIP) + { + this._renderCanvasTriangleStrip(context); + } + else + { + this._renderCanvasTriangles(context); + } + +}; + +/* +* Renders a Triangle Strip to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangleStrip +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangleStrip = function (context) { + + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + + var length = vertices.length / 2; + + this.count++; + + for (var i = 0; i < length - 2; i++) + { + var index = i * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasTriangles +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasTriangles = function (context) { + + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + + var length = indices.length; + + this.count++; + + for (var i = 0; i < length; i += 3) + { + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } + +}; + +/* +* Renders a Triangle to Canvas. +* +* @private +* @method Phaser.Rope#_renderCanvasDrawTriangle +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { + + var textureSource = this.texture.baseTexture.source; + var textureWidth = this.texture.width; + var textureHeight = this.texture.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var u0 = uvs[index0] * textureWidth; + var u1 = uvs[index1] * textureWidth; + var u2 = uvs[index2] * textureWidth; + var v0 = uvs[index0 + 1] * textureHeight; + var v1 = uvs[index1 + 1] * textureHeight; + var v2 = uvs[index2 + 1] * textureHeight; + + if (this.canvasPadding > 0) + { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt((normX * normX) + (normY * normY)); + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt((normX * normX) + (normY * normY)); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2); + var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2); + var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2); + var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2); + var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2); + var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2); + var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2); + + context.transform( + deltaA / delta, + deltaD / delta, + deltaB / delta, + deltaE / delta, + deltaC / delta, + deltaF / delta); + + context.drawImage(textureSource, 0, 0); + context.restore(); + +}; + +/* +* Renders a flat strip. +* +* @method Phaser.Rope#renderStripFlat +* @memberof Phaser.Rope +*/ +Phaser.Rope.prototype.renderStripFlat = function (strip) { + + var context = this.context; + var vertices = strip.vertices; + + var length = vertices.length / 2; + + this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; i++) + { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var x1 = vertices[index + 2]; + var x2 = vertices[index + 4]; + var y0 = vertices[index + 1]; + var y1 = vertices[index + 3]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + +}; + +/* +* Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. +* +* @method Phaser.Rope#getBounds +* @memberof Phaser.Rope +* @param {Matrix} matrix - The transformation matrix of the Sprite. +* @return {Rectangle} The framing rectangle. +*/ +Phaser.Rope.prototype.getBounds = function (matrix) { + + var worldTransform = matrix || this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + var vertices = this.vertices; + + for (var i = 0; i < vertices.length; i += 2) + { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + if (minX === -Infinity || maxY === Infinity) + { + return PIXI.EmptyRectangle; + } + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // Store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* A Rope will call its updateAnimation function on each update loop if it has one. +* +* @name Phaser.Rope#updateAnimation +* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. +*/ +Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", { + + get: function () { + + return this._updateAnimation; + + }, + + set: function (value) { + + if (value && typeof value === 'function') + { + this._hasUpdateAnimation = true; + this._updateAnimation = value; + } + else + { + this._hasUpdateAnimation = false; + this._updateAnimation = null; + } + + } + +}); + +/** +* The segments that make up the rope body as an array of Phaser.Rectangles +* +* @name Phaser.Rope#segments +* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope +*/ +Object.defineProperty(Phaser.Rope.prototype, "segments", { + + get: function () { + + var segments = []; + var index, x1, y1, x2, y2, width, height, rect; + + for (var i = 0; i < this.points.length; i++) + { + index = i * 4; + + x1 = this.vertices[index] * this.scale.x; + y1 = this.vertices[index + 1] * this.scale.y; + x2 = this.vertices[index + 4] * this.scale.x; + y2 = this.vertices[index + 3] * this.scale.y; + + width = Phaser.Math.difference(x1, x2); + height = Phaser.Math.difference(y1, y2); + + x1 += this.world.x; + y1 += this.world.y; + rect = new Phaser.Rectangle(x1, y1, width, height); + segments.push(rect); + } + + return segments; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. +* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. +* +* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. +* +* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background +* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` +* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will +* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to +* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. +* +* An important note about texture dimensions: +* +* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be +* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two +* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and +* bottom of your frame. To avoid this ensure your textures are perfect powers of two. +* +* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However +* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive +* additional padding to enforce it to be so. +* +* @class Phaser.TileSprite +* @constructor +* @extends PIXI.Sprite +* @extends Phaser.Component.Core +* @extends Phaser.Component.Angle +* @extends Phaser.Component.Animation +* @extends Phaser.Component.AutoCull +* @extends Phaser.Component.Bounds +* @extends Phaser.Component.BringToTop +* @extends Phaser.Component.Destroy +* @extends Phaser.Component.FixedToCamera +* @extends Phaser.Component.Health +* @extends Phaser.Component.InCamera +* @extends Phaser.Component.InputEnabled +* @extends Phaser.Component.InWorld +* @extends Phaser.Component.LifeSpan +* @extends Phaser.Component.LoadTexture +* @extends Phaser.Component.Overlap +* @extends Phaser.Component.PhysicsBody +* @extends Phaser.Component.Reset +* @extends Phaser.Component.Smoothed +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} [x=0] - The x coordinate (in world space) to position the TileSprite at. +* @param {number} [y=0] - The y coordinate (in world space) to position the TileSprite at. +* @param {number} [width=256] - The width of the TileSprite. +* @param {number} [height=256] - The height of the TileSprite. +* @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. +* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.TileSprite = function (game, x, y, width, height, key, frame) { + + x = x || 0; + y = y || 0; + width = width || 256; + height = height || 256; + key = key || null; + frame = frame || null; + + PIXI.Sprite.call(this, new PIXI.Texture(Phaser.Cache.DEFAULT.baseTexture), width, height); + + /** + * @property {number} type - The const type of this object. + * @readonly + */ + this.type = Phaser.TILESPRITE; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.SPRITE; + + /** + * @property {Phaser.Point} _scroll - Internal cache var. + * @private + */ + this._scroll = new Phaser.Point(); + + /** + * @property {Phaser.Point} tileScale - The scale applied to the image being tiled. + */ + this.tileScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tileScaleOffset - The scale offset applied to the image being tiled. + */ + this.tileScaleOffset = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} tilePosition - The offset position of the image being tiled. + */ + this.tilePosition = new Phaser.Point(); + + /** + * If enabled a green rectangle will be drawn behind the generated tiling texture, + * allowing you to visually debug the texture being used. + * + * @property {boolean} textureDebug + */ + this.textureDebug = false; + + /** + * The CanvasBuffer object that the tiled texture is drawn to. + * + * @property {PIXI.CanvasBuffer} canvasBuffer + */ + this.canvasBuffer = null; + + /** + * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. + * + * @property {PIXI.Texture} tilingTexture + */ + this.tilingTexture = null; + + /** + * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). + * + * @property {object} tilePattern + */ + this.tilePattern = null; + + /** + * If true the TileSprite will run `generateTexture` on its **next** render pass. + * This is set by the likes of Phaser.LoadTexture.setFrame. + * + * @property {boolean} refreshTexture + */ + this.refreshTexture = true; + + this.frameWidth = 0; + this.frameHeight = 0; + + this._width = width; + this._height = height; + + Phaser.Component.Core.init.call(this, game, x, y, key, frame); + +}; + +Phaser.TileSprite.prototype = Object.create(PIXI.Sprite.prototype); +Phaser.TileSprite.prototype.constructor = Phaser.TileSprite; + +Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [ + 'Angle', + 'Animation', + 'AutoCull', + 'Bounds', + 'BringToTop', + 'Destroy', + 'FixedToCamera', + 'Health', + 'InCamera', + 'InputEnabled', + 'InWorld', + 'LifeSpan', + 'LoadTexture', + 'Overlap', + 'PhysicsBody', + 'Reset', + 'Smoothed' +]); + +Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate; +Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate; +Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; +Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TileSprite#preUpdate +* @memberof Phaser.TileSprite +* @return {boolean} +*/ +Phaser.TileSprite.prototype.preUpdate = function () { + + if (this._scroll.x !== 0) + { + this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed; + } + + if (this._scroll.y !== 0) + { + this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed; + } + + if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) + { + return false; + } + + return this.preUpdateCore(); + +}; + +/** +* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). +* The scroll speed is specified in pixels per second. +* A negative x value will scroll to the left. A positive x value will scroll to the right. +* A negative y value will scroll up. A positive y value will scroll down. +* +* @method Phaser.TileSprite#autoScroll +* @memberof Phaser.TileSprite +* @param {number} x - Horizontal scroll speed in pixels per second. +* @param {number} y - Vertical scroll speed in pixels per second. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.autoScroll = function (x, y) { + + this._scroll.set(x, y); + + return this; + +}; + +/** +* Stops an automatically scrolling TileSprite. +* +* @method Phaser.TileSprite#stopScroll +* @memberof Phaser.TileSprite +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.stopScroll = function () { + + this._scroll.set(0, 0); + + return this; + +}; + +/** +* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present +* and nulls its reference to game, freeing it up for garbage collection. +* +* @method Phaser.TileSprite#destroy +* @memberof Phaser.TileSprite +* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? +*/ +Phaser.TileSprite.prototype.destroy = function (destroyChildren) { + + Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); + + PIXI.Sprite.prototype.destroy.call(this); + + if (this.canvasBuffer) + { + this.canvasBuffer.destroy(); + this.canvasBuffer = null; + } + + this.tileScale = null; + this.tileScaleOffset = null; + this.tilePosition = null; + + if (this.tilingTexture) + { + this.tilingTexture.destroy(true); + this.tilingTexture = null; + } + +}; + +/** +* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. +* If the TileSprite has a physics body that too is reset. +* +* @method Phaser.TileSprite#reset +* @memberof Phaser.TileSprite +* @param {number} x - The x coordinate (in world space) to position the Sprite at. +* @param {number} y - The y coordinate (in world space) to position the Sprite at. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.reset = function (x, y) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y); + + this.tilePosition.x = 0; + this.tilePosition.y = 0; + + return this; + +}; + +/** +* Changes the texture being rendered by this TileSprite. +* Causes a texture refresh to take place on the next render. +* +* @method Phaser.TileSprite#setTexture +* @memberof Phaser.TileSprite +* @param {PIXI.Texture} texture - The texture to apply to this TileSprite. +* @return {Phaser.TileSprite} This instance. +*/ +Phaser.TileSprite.prototype.setTexture = function (texture) { + + if (this.texture !== texture) + { + this.texture = texture; + this.refreshTexture = true; + this.cachedTint = 0xFFFFFF; + } + + return this; + +}; + +/** +* Renders the TileSprite using the WebGL Renderer. +* +* @private +* @method Phaser.TileSprite#_renderWebGL +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderWebGL = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + 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.refreshTexture) + { + this.generateTilingTexture(true, renderSession); + + if (this.tilingTexture) + { + if (this.tilingTexture.needsUpdate) + { + this.tilingTexture.baseTexture.textureIndex = this.texture.baseTexture.textureIndex; + renderSession.renderer.updateTexture(this.tilingTexture.baseTexture); + this.tilingTexture.needsUpdate = false; + } + } + else + { + return; + } + } + + renderSession.spriteBatch.renderTilingSprite(this); + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderWebGL(renderSession); + } + + var restartBatch = false; + + if (this._filters) + { + restartBatch = true; + renderSession.spriteBatch.stop(); + renderSession.filterManager.popFilter(); + } + + if (this._mask) + { + if (!restartBatch) + { + renderSession.spriteBatch.stop(); + } + + renderSession.maskManager.popMask(this._mask, renderSession); + } + + if (restartBatch) + { + renderSession.spriteBatch.start(); + } + +}; + +/** +* Renders the TileSprite using the Canvas Renderer. +* +* @private +* @method Phaser.TileSprite#_renderCanvas +* @memberof Phaser.TileSprite +* @param {object} renderSession +*/ +Phaser.TileSprite.prototype._renderCanvas = function (renderSession) { + + if (!this.visible || !this.renderable || this.alpha === 0) + { + return; + } + + var context = renderSession.context; + + if (this._mask) + { + renderSession.maskManager.pushMask(this._mask, renderSession); + } + + context.globalAlpha = this.worldAlpha; + + var wt = this.worldTransform; + var resolution = renderSession.resolution; + var tx = (wt.tx * resolution) + renderSession.shakeX; + var ty = (wt.ty * resolution) + renderSession.shakeY; + + context.setTransform(wt.a * resolution, wt.b * resolution, wt.c * resolution, wt.d * resolution, tx, ty); + + if (this.tint !== 0xFFFFFF && (this.texture.requiresReTint || this.cachedTint !== this.tint)) + { + this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint); + + this.cachedTint = this.tint; + this.texture.requiresReTint = false; + this.refreshTexture = true; + } + + if (this.refreshTexture) + { + this.generateTilingTexture(false, renderSession); + + if (this.tilingTexture) + { + this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat'); + } + else + { + return; + } + } + + var sessionBlendMode = renderSession.currentBlendMode; + + // Check blend mode + if (this.blendMode !== renderSession.currentBlendMode) + { + renderSession.currentBlendMode = this.blendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; + } + + var tilePosition = this.tilePosition; + var tileScale = this.tileScale; + + tilePosition.x %= this.tilingTexture.baseTexture.width; + tilePosition.y %= this.tilingTexture.baseTexture.height; + + // Translate + context.scale(tileScale.x, tileScale.y); + context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height)); + + context.fillStyle = this.tilePattern; + + tx = -tilePosition.x; + ty = -tilePosition.y; + + var tw = this._width / tileScale.x; + var th = this._height / tileScale.y; + + // Allow for pixel rounding + if (renderSession.roundPixels) + { + tx |= 0; + ty |= 0; + tw |= 0; + th |= 0; + } + + context.fillRect(tx, ty, tw, th); + + // Translate back again + context.scale(1 / tileScale.x, 1 / tileScale.y); + context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height)); + + if (this._mask) + { + renderSession.maskManager.popMask(renderSession); + } + + for (var i = 0; i < this.children.length; i++) + { + this.children[i]._renderCanvas(renderSession); + } + + // Reset blend mode + if (sessionBlendMode !== this.blendMode) + { + renderSession.currentBlendMode = sessionBlendMode; + context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode]; + } + +}; + +/** +* Override the Sprite method. +* +* @private +* @method Phaser.TileSprite#onTextureUpdate +* @memberof Phaser.TileSprite +*/ +Phaser.TileSprite.prototype.onTextureUpdate = function () { + + // overriding the sprite version of this! + +}; + +/** +* Internal method that generates a new tiling texture. +* +* @method Phaser.TileSprite#generateTilingTexture +* @memberof Phaser.TileSprite +* @param {boolean} forcePowerOfTwo - Whether we want to force the texture to be a power of two +*/ +Phaser.TileSprite.prototype.generateTilingTexture = function (forcePowerOfTwo) { + + if (!this.texture.baseTexture.hasLoaded) + { + return; + } + + var texture = this.texture; + var frame = texture.frame; + + var targetWidth = this._frame.sourceSizeW || this._frame.width; + var targetHeight = this._frame.sourceSizeH || this._frame.height; + + var dx = 0; + var dy = 0; + + if (this._frame.trimmed) + { + dx = this._frame.spriteSourceSizeX; + dy = this._frame.spriteSourceSizeY; + } + + if (forcePowerOfTwo) + { + targetWidth = Phaser.Math.getNextPowerOfTwo(targetWidth); + targetHeight = Phaser.Math.getNextPowerOfTwo(targetHeight); + } + + if (this.canvasBuffer) + { + this.canvasBuffer.resize(targetWidth, targetHeight); + this.tilingTexture.baseTexture.width = targetWidth; + this.tilingTexture.baseTexture.height = targetHeight; + this.tilingTexture.needsUpdate = true; + } + else + { + this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight); + this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas); + this.tilingTexture.isTiling = true; + this.tilingTexture.needsUpdate = true; + } + + if (this.textureDebug) + { + this.canvasBuffer.context.strokeStyle = '#00ff00'; + this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight); + } + + // If a sprite sheet we need this: + var w = texture.crop.width; + var h = texture.crop.height; + + if (w !== targetWidth || h !== targetHeight) + { + w = targetWidth; + h = targetHeight; + } + + var targetTexture = this.tintedTexture ? this.tintedTexture : texture.baseTexture.source; + + this.canvasBuffer.context.drawImage( + targetTexture, + texture.crop.x, + texture.crop.y, + texture.crop.width, + texture.crop.height, + dx, + dy, + w, + h + ); + + this.tileScaleOffset.x = frame.width / targetWidth; + this.tileScaleOffset.y = frame.height / targetHeight; + + this.refreshTexture = false; + + this.tilingTexture.baseTexture._powerOf2 = true; + +}; + +/** +* Returns the framing rectangle of the Tile Sprite. +* +* @method Phaser.TileSprite#getBounds +* @memberof Phaser.TileSprite +* @return {Phaser.Rectangle} The bounds of the Tile Sprite. +*/ +Phaser.TileSprite.prototype.getBounds = function () { + + var width = this._width; + var height = this._height; + + var w0 = width * (1 - this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1 - this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = (a * w1) + (c * h1) + tx; + var y1 = (d * h1) + (b * w1) + ty; + + var x2 = (a * w0) + (c * h1) + tx; + var y2 = (d * h1) + (b * w0) + ty; + + var x3 = (a * w0) + (c * h0) + tx; + var y3 = (d * h0) + (b * w0) + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var maxX = -Infinity; + var maxY = -Infinity; + + var minX = Infinity; + var minY = Infinity; + + minX = x1 < minX ? x1 : minX; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1 < minY ? y1 : minY; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1 > maxX ? 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; + + // TODO: This is surely always undefined? As it's not set anywhere in the parent objects + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + +}; + +/** +* The width of the sprite, setting this will actually modify the scale to achieve the value set +* +* @property width +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'width', { + + get: function () { + + return this._width; + + }, + + set: function (value) { + + this._width = value; + + } + +}); + +/** +* The height of the TilingSprite, setting this will actually modify the scale to achieve the value set +* +* @property height +* @type Number +*/ +Object.defineProperty(Phaser.TileSprite.prototype, 'height', { + + get: function () { + + return this._height; + + }, + + set: function (value) { + + this._height = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The CanvasPool is a global static object, that allows Phaser to recycle and pool Canvas DOM elements. +* +* @class Phaser.CanvasPool +* @static +*/ +Phaser.CanvasPool = { + + /** + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @method Phaser.CanvasPool.create + * @static + * @param {any} parent - The parent of the canvas element. + * @param {number} width - The width of the canvas element. + * @param {number} height - The height of the canvas element. + * @return {HTMLCanvasElement} The canvas element. + */ + create: function (parent, width, height) { + + var idx = Phaser.CanvasPool.getFirst(); + var canvas; + + if (idx === -1) + { + var container = { + parent: parent, + canvas: document.createElement('canvas') + }; + + Phaser.CanvasPool.pool.push(container); + + canvas = container.canvas; + } + else + { + Phaser.CanvasPool.pool[idx].parent = parent; + + canvas = Phaser.CanvasPool.pool[idx].canvas; + } + + if (width !== undefined) + { + canvas.width = width; + canvas.height = height; + } + + return canvas; + + }, + + /** + * Gets the first free canvas index from the pool. + * + * @static + * @method Phaser.CanvasPool.getFirst + * @return {number} + */ + getFirst: function () { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + return i; + } + } + + return -1; + + }, + + /** + * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.remove + * @param {any} parent - The parent of the canvas element. + */ + remove: function (parent) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent === parent) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Looks up a canvas based on its type, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.removeByCanvas + * @param {HTMLCanvasElement} canvas - The canvas element to remove. + */ + removeByCanvas: function (canvas) { + + var pool = Phaser.CanvasPool.pool; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].canvas === canvas) + { + pool[i].parent = null; + pool[i].canvas.width = 1; + pool[i].canvas.height = 1; + } + } + + }, + + /** + * Gets the total number of used canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getTotal + * @return {number} The number of in-use (parented) canvas elements in the pool. + */ + getTotal: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (pool[i].parent) + { + c++; + } + } + + return c; + + }, + + /** + * Gets the total number of free canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getFree + * @return {number} The number of free (un-parented) canvas elements in the pool. + */ + getFree: function () { + + var pool = Phaser.CanvasPool.pool; + var c = 0; + + for (var i = 0; i < pool.length; i++) + { + if (!pool[i].parent) + { + c++; + } + } + + return c; + + }, + + + /** + * Prints in-use, free, and total counts to console.log. + * + * @static + * @method Phaser.CanvasPool.log + */ + log: function () { + + console.log('CanvasPool: %s used, %s free, %s total', this.getTotal(), this.getFree(), this.pool.length); + + } + +}; + +/** + * The pool into which the canvas elements are placed. + * + * @property pool + * @type Array + * @static + */ +Phaser.CanvasPool.pool = []; + + +/** + * The total number of canvas elements in the {@link Phaser.CanvasPool.pool pool}. + * + * @property length + * @type number + * @static + * @readonly + */ +Object.defineProperty(Phaser.CanvasPool, 'length', { + get: function () { + return this.pool.length; + } +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}. +* +* This class represents a singleton object that can be accessed directly as `game.device` +* (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it. +* +* Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization +* occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase. +* Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal, e.g., +* +* ```javascript +* Phaser.Device.onInitialized.add(function (device) { +* +* device.canvasBitBltShift = true; +* device.mspointer = false; +* +* }); +* +* var game = new Phaser.Game(); +* ``` +* +* When checking features using the exposed properties only the *truth-iness* of the value should be relied upon +* unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined` +* when indicating the lack of a feature. +* +* Uses elements from System.js by MrDoob and Modernizr +* +* @description +* It is not possible to instantiate the Device class manually. +* +* @class +* @protected +*/ +Phaser.Device = function () { + + /** + * The time the device became ready. + * @property {integer} deviceReadyAt + * @protected + */ + this.deviceReadyAt = 0; + + /** + * The time as which initialization has completed. + * @property {boolean} initialized + * @protected + */ + this.initialized = false; + + // Browser / Host / Operating System + + /** + * @property {boolean} desktop - Is running on a desktop? + * @default + */ + this.desktop = false; + + /** + * @property {boolean} iOS - Is running on iOS? + * @default + */ + this.iOS = false; + + /** + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @default + */ + this.iOSVersion = 0; + + /** + * @property {boolean} cocoonJS - Is the game running under CocoonJS? + * @default + */ + this.cocoonJS = false; + + /** + * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App? + * @default + */ + this.cocoonJSApp = false; + + /** + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @default + */ + this.cordova = false; + + /** + * @property {boolean} node - Is the game running under Node.js? + * @default + */ + this.node = false; + + /** + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @default + */ + this.nodeWebkit = false; + + /** + * @property {boolean} electron - Is the game running under GitHub Electron? + * @default + */ + this.electron = false; + + /** + * @property {boolean} ejecta - Is the game running under Ejecta? + * @default + */ + this.ejecta = false; + + /** + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @default + */ + this.crosswalk = false; + + /** + * @property {boolean} android - Is running on android? + * @default + */ + this.android = false; + + /** + * @property {boolean} chromeOS - Is running on chromeOS? + * @default + */ + this.chromeOS = false; + + /** + * @property {boolean} linux - Is running on linux? + * @default + */ + this.linux = false; + + /** + * @property {boolean} macOS - Is running on macOS? + * @default + */ + this.macOS = false; + + /** + * @property {boolean} windows - Is running on windows? + * @default + */ + this.windows = false; + + /** + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @default + */ + this.windowsPhone = false; + + // Features + + /** + * @property {boolean} canvas - Is canvas available? + * @default + */ + this.canvas = false; + + /** + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @default + */ + this.canvasBitBltShift = null; + + /** + * If the browser isn't capable of handling tinting with alpha this will be false. + * @property {boolean} canHandleAlpha + * @default + */ + this.canHandleAlpha = false; + + /** + * Whether or not the {@link http://caniuse.com/#feat=canvas-blending Canvas Blend Modes} are supported, consequently the ability to tint using the multiply method. + * + * Expect `false` in Internet Explorer <= 11. + * + * @property {boolean} canUseMultiply + * @default + */ + this.canUseMultiply = false; + + /** + * @property {boolean} webGL - Is webGL available? + * @default + */ + this.webGL = false; + + /** + * @property {boolean} file - Is file available? + * @default + */ + this.file = false; + + /** + * @property {boolean} fileSystem - Is fileSystem available? + * @default + */ + this.fileSystem = false; + + /** + * @property {boolean} localStorage - Is localStorage available? + * @default + */ + this.localStorage = false; + + /** + * @property {boolean} worker - Is worker available? + * @default + */ + this.worker = false; + + /** + * @property {boolean} css3D - Is css3D available? + * @default + */ + this.css3D = false; + + /** + * @property {boolean} pointerLock - Is Pointer Lock available? + * @default + */ + this.pointerLock = false; + + /** + * @property {boolean} typedArray - Does the browser support TypedArrays? + * @default + */ + this.typedArray = false; + + /** + * @property {boolean} vibration - Does the device support the Vibration API? + * @default + */ + this.vibration = false; + + /** + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @default + */ + this.getUserMedia = true; + + /** + * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true) + * @default + */ + this.quirksMode = false; + + // Input + + /** + * @property {boolean} touch - Is touch available? + * @default + */ + this.touch = false; + + /** + * @property {boolean} mspointer - Is mspointer available? + * @default + */ + this.mspointer = false; + + /** + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @default + * @protected + */ + this.wheelEvent = null; + + // Browser + + /** + * @property {boolean} arora - Set to true if running in Arora. + * @default + */ + this.arora = false; + + /** + * @property {boolean} chrome - Set to true if running in Chrome. + * @default + */ + this.chrome = false; + + /** + * @property {number} chromeVersion - If running in Chrome this will contain the major version number. + * @default + */ + this.chromeVersion = 0; + + /** + * @property {boolean} epiphany - Set to true if running in Epiphany. + * @default + */ + this.epiphany = false; + + /** + * @property {boolean} firefox - Set to true if running in Firefox. + * @default + */ + this.firefox = false; + + /** + * @property {number} firefoxVersion - If running in Firefox this will contain the major version number. + * @default + */ + this.firefoxVersion = 0; + + /** + * @property {boolean} ie - Set to true if running in Internet Explorer. + * @default + */ + this.ie = false; + + /** + * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. + * @default + */ + this.ieVersion = 0; + + /** + * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+) + * @default + */ + this.trident = false; + + /** + * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx} + * @default + */ + this.tridentVersion = 0; + + /** + * @property {boolean} edge - Set to true if running in Microsoft Edge browser. + * @default + */ + this.edge = false; + + /** + * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. + * @default + */ + this.mobileSafari = false; + + /** + * @property {boolean} midori - Set to true if running in Midori. + * @default + */ + this.midori = false; + + /** + * @property {boolean} opera - Set to true if running in Opera. + * @default + */ + this.opera = false; + + /** + * @property {boolean} safari - Set to true if running in Safari. + * @default + */ + this.safari = false; + + /** + * @property {number} safariVersion - If running in Safari this will contain the major version number. + * @default + */ + this.safariVersion = 0; + + /** + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @default + */ + this.webApp = false; + + /** + * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle) + * @default + */ + this.silk = false; + + // Audio + + /** + * @property {boolean} audioData - Are Audio tags available? + * @default + */ + this.audioData = false; + + /** + * @property {boolean} webAudio - Is the WebAudio API available? + * @default + */ + this.webAudio = false; + + /** + * @property {boolean} ogg - Can this device play ogg files? + * @default + */ + this.ogg = false; + + /** + * @property {boolean} opus - Can this device play opus files? + * @default + */ + this.opus = false; + + /** + * @property {boolean} mp3 - Can this device play mp3 files? + * @default + */ + this.mp3 = false; + + /** + * @property {boolean} wav - Can this device play wav files? + * @default + */ + this.wav = false; + + /** + * Can this device play m4a files? + * @property {boolean} m4a - True if this device can play m4a files. + * @default + */ + this.m4a = false; + + /** + * @property {boolean} webm - Can this device play webm files? + * @default + */ + this.webm = false; + + /** + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @default + */ + this.dolby = false; + + // Video + + /** + * @property {boolean} oggVideo - Can this device play ogg video files? + * @default + */ + this.oggVideo = false; + + /** + * @property {boolean} h264Video - Can this device play h264 mp4 video files? + * @default + */ + this.h264Video = false; + + /** + * @property {boolean} mp4Video - Can this device play h264 mp4 video files? + * @default + */ + this.mp4Video = false; + + /** + * @property {boolean} webmVideo - Can this device play webm video files? + * @default + */ + this.webmVideo = false; + + /** + * @property {boolean} vp9Video - Can this device play vp9 video files? + * @default + */ + this.vp9Video = false; + + /** + * @property {boolean} hlsVideo - Can this device play hls video files? + * @default + */ + this.hlsVideo = false; + + // Device + + /** + * @property {boolean} iPhone - Is running on iPhone? + * @default + */ + this.iPhone = false; + + /** + * @property {boolean} iPhone4 - Is running on iPhone4? + * @default + */ + this.iPhone4 = false; + + /** + * @property {boolean} iPad - Is running on iPad? + * @default + */ + this.iPad = false; + + // Device features + + /** + * @property {number} pixelRatio - PixelRatio of the host device? + * @default + */ + this.pixelRatio = 0; + + /** + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @default + */ + this.littleEndian = false; + + /** + * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`. + * @default + */ + this.LITTLE_ENDIAN = false; + + /** + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @default + */ + this.support32bit = false; + + /** + * @property {boolean} fullscreen - Does the browser support the Full Screen API? + * @default + */ + this.fullscreen = false; + + /** + * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it. + * @default + */ + this.requestFullscreen = ''; + + /** + * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @default + */ + this.cancelFullscreen = ''; + + /** + * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @default + */ + this.fullscreenKeyboard = false; + +}; + +// Device is really a singleton/static entity; instantiate it +// and add new methods directly sans-prototype. +Phaser.Device = new Phaser.Device(); + +/** +* This signal is dispatched after device initialization occurs but before any of the ready +* callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked. +* +* Local "patching" for a particular device can/should be done in this event. +* +* _Note_: This signal is removed after the device has been readied; if a handler has not been +* added _before_ `new Phaser.Game(..)` it is probably too late. +* +* @type {?Phaser.Signal} +* @static +*/ +Phaser.Device.onInitialized = new Phaser.Signal(); + +/** +* Add a device-ready handler and ensure the device ready sequence is started. +* +* Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added, +* which is normally done automatically be calling `new Phaser.Game(..)`. +* +* The handler is invoked when the device is considered "ready", which may be immediately +* if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}. +* +* @method +* @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. +* @param {object} [context] - Context in which to invoke the handler +* @param {boolean} [nonPrimer=false] - If true the device ready check will not be started. +*/ +Phaser.Device.whenReady = function (callback, context, nonPrimer) { + + var readyCheck = this._readyCheck; + + if (this.deviceReadyAt || !readyCheck) + { + callback.call(context, this); + } + else if (readyCheck._monitor || nonPrimer) + { + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + } + else + { + readyCheck._monitor = readyCheck.bind(this); + readyCheck._queue = readyCheck._queue || []; + readyCheck._queue.push([callback, context]); + + var cordova = typeof window.cordova !== 'undefined'; + var cocoonJS = navigator['isCocoonJS']; + + if (document.readyState === 'complete' || document.readyState === 'interactive') + { + // Why is there an additional timeout here? + window.setTimeout(readyCheck._monitor, 0); + } + else if (cordova && !cocoonJS) + { + // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + // Cordova, but NOT Cocoon? + document.addEventListener('deviceready', readyCheck._monitor, false); + } + else + { + document.addEventListener('DOMContentLoaded', readyCheck._monitor, false); + window.addEventListener('load', readyCheck._monitor, false); + } + } + +}; + +/** +* Internal method used for checking when the device is ready. +* This function is removed from Phaser.Device when the device becomes ready. +* +* @method +* @private +*/ +Phaser.Device._readyCheck = function () { + + var readyCheck = this._readyCheck; + + if (!document.body) + { + window.setTimeout(readyCheck._monitor, 20); + } + else if (!this.deviceReadyAt) + { + this.deviceReadyAt = Date.now(); + + document.removeEventListener('deviceready', readyCheck._monitor); + document.removeEventListener('DOMContentLoaded', readyCheck._monitor); + window.removeEventListener('load', readyCheck._monitor); + + this._initialize(); + this.initialized = true; + + this.onInitialized.dispatch(this); + + var item; + while ((item = readyCheck._queue.shift())) + { + var callback = item[0]; + var context = item[1]; + callback.call(context, this); + } + + // Remove no longer useful methods and properties. + this._readyCheck = null; + this._initialize = null; + this.onInitialized = null; + } + +}; + +/** +* Internal method to initialize the capability checks. +* This function is removed from Phaser.Device once the device is initialized. +* +* @method +* @private +*/ +Phaser.Device._initialize = function () { + + var device = this; + + /** + * Check which OS is game running on. + */ + function _checkOS () { + + var ua = navigator.userAgent; + + if (/Playstation Vita/.test(ua)) + { + device.vita = true; + } + else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua)) + { + device.kindle = true; + // This will NOT detect early generations of Kindle Fire, I think there is no reliable way... + // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true" + } + else if (/Android/.test(ua)) + { + device.android = true; + } + else if (/CrOS/.test(ua)) + { + device.chromeOS = true; + } + else if (/iP[ao]d|iPhone/i.test(ua)) + { + device.iOS = true; + (navigator.appVersion).match(/OS (\d+)/); + device.iOSVersion = parseInt(RegExp.$1, 10); + } + else if (/Linux/.test(ua)) + { + device.linux = true; + } + else if (/Mac OS/.test(ua)) + { + device.macOS = true; + } + else if (/Windows/.test(ua)) + { + device.windows = true; + } + + if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua)) + { + device.android = false; + device.iOS = false; + device.macOS = false; + device.windows = true; + device.windowsPhone = true; + } + + var silk = /Silk/.test(ua); // detected in browsers + + if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS) + { + device.desktop = true; + } + + // Windows Phone / Table reset + if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua)))) + { + device.desktop = false; + } + + } + + /** + * Checks if the browser correctly supports putImageData alpha channels. + * If the browser isn't capable of handling tinting with alpha, `Device.canHandleAlpha` will be false. + * Also checks whether the Canvas BlendModes are supported by the current browser for drawImage. + */ + function _checkCanvasFeatures () { + + var canvas = Phaser.CanvasPool.create(this, 6, 1); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgba(10, 20, 30, 0.5)'; + + // Draw a single pixel + context.fillRect(0, 0, 1, 1); + + // Get the color values + var s1 = context.getImageData(0, 0, 1, 1); + + if (s1) + { + // Plot them to x2 + context.putImageData(s1, 1, 0); + + // Get those values + var s2 = context.getImageData(1, 0, 1, 1); + + // Compare and set + device.canHandleAlpha = ( + s2.data[0] === s1.data[0] && + s2.data[1] === s1.data[1] && + s2.data[2] === s1.data[2] && + s2.data[3] === s1.data[3] + ); + } + + // Checks whether the Canvas BlendModes are supported by the current browser for drawImage. + context.globalCompositeOperation = 'multiply'; + device.canUseMultiply = (context.globalCompositeOperation === 'multiply'); + + Phaser.CanvasPool.removeByCanvas(canvas); + + PIXI.CanvasTinter.tintMethod = (device.canUseMultiply) ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel; + + } + + /** + * Check HTML5 features of the host environment. + */ + function _checkFeatures () { + + device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS; + + try { + device.localStorage = !!localStorage.getItem; + } catch (error) { + device.localStorage = false; + } + + device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; + device.fileSystem = !!window['requestFileSystem']; + + device.webGL = !!window.WebGLRenderingContext; + + device.worker = !!window['Worker']; + + device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; + + device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + + device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL; + + // Older versions of firefox (< 21) apparently claim support but user media does not actually work + if (device.firefox && device.firefoxVersion < 21) + { + device.getUserMedia = false; + } + + // TODO: replace canvasBitBltShift detection with actual feature check + + // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it + // is safer to not try and use the fast copy-over method. + if (!device.iOS && (device.ie || device.firefox || device.chrome)) + { + device.canvasBitBltShift = true; + } + + // Known not to work + if (device.safari || device.mobileSafari) + { + device.canvasBitBltShift = false; + } + + } + + /** + * Checks/configures various input. + */ + function _checkInput () { + + if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1)) + { + device.touch = true; + } + + if (window.PointerEvent || window.MSPointerEvent || window.navigator.msPointerEnabled || window.navigator.pointerEnabled) + { + device.mspointer = true; + } + + if (!device.cocoonJS) + { + // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel + if ('onwheel' in window || (device.ie && 'WheelEvent' in window)) + { + // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+ + device.wheelEvent = 'wheel'; + } + else if ('onmousewheel' in window) + { + // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7. + device.wheelEvent = 'mousewheel'; + } + else if (device.firefox && 'MouseScrollEvent' in window) + { + // FF prior to 17. This should probably be scrubbed. + device.wheelEvent = 'DOMMouseScroll'; + } + } + + } + + /** + * Checks for support of the Full Screen API. + */ + function _checkFullScreenSupport () { + + var fs = [ + 'requestFullscreen', + 'requestFullScreen', + 'webkitRequestFullscreen', + 'webkitRequestFullScreen', + 'msRequestFullscreen', + 'msRequestFullScreen', + 'mozRequestFullScreen', + 'mozRequestFullscreen' + ]; + + var element = document.createElement('div'); + + for (var i = 0; i < fs.length; i++) + { + if (element[fs[i]]) + { + device.fullscreen = true; + device.requestFullscreen = fs[i]; + break; + } + } + + var cfs = [ + 'cancelFullScreen', + 'exitFullscreen', + 'webkitCancelFullScreen', + 'webkitExitFullscreen', + 'msCancelFullScreen', + 'msExitFullscreen', + 'mozCancelFullScreen', + 'mozExitFullscreen' + ]; + + if (device.fullscreen) + { + for (var i = 0; i < cfs.length; i++) + { + if (document[cfs[i]]) + { + device.cancelFullscreen = cfs[i]; + break; + } + } + } + + // Keyboard Input? + if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT']) + { + device.fullscreenKeyboard = true; + } + + } + + /** + * Check what browser is game running in. + */ + function _checkBrowser () { + + var ua = navigator.userAgent; + + if (/Arora/.test(ua)) + { + device.arora = true; + } + else if (/Edge\/\d+/.test(ua)) + { + device.edge = true; + } + else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.chrome = true; + device.chromeVersion = parseInt(RegExp.$1, 10); + } + else if (/Epiphany/.test(ua)) + { + device.epiphany = true; + } + else if (/Firefox\D+(\d+)/.test(ua)) + { + device.firefox = true; + device.firefoxVersion = parseInt(RegExp.$1, 10); + } + else if (/AppleWebKit/.test(ua) && device.iOS) + { + device.mobileSafari = true; + } + else if (/MSIE (\d+\.\d+);/.test(ua)) + { + device.ie = true; + device.ieVersion = parseInt(RegExp.$1, 10); + } + else if (/Midori/.test(ua)) + { + device.midori = true; + } + else if (/Opera/.test(ua)) + { + device.opera = true; + } + else if (/Safari\/(\d+)/.test(ua) && !device.windowsPhone) + { + device.safari = true; + + if (/Version\/(\d+)\./.test(ua)) + { + device.safariVersion = parseInt(RegExp.$1, 10); + } + } + else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua)) + { + device.ie = true; + device.trident = true; + device.tridentVersion = parseInt(RegExp.$1, 10); + device.ieVersion = parseInt(RegExp.$3, 10); + } + + // Silk gets its own if clause because its ua also contains 'Safari' + if (/Silk/.test(ua)) + { + device.silk = true; + } + + // WebApp mode in iOS + if (navigator['standalone']) + { + device.webApp = true; + } + + if (typeof window.cordova !== 'undefined') + { + device.cordova = true; + } + + if (typeof process !== 'undefined' && typeof require !== 'undefined') + { + device.node = true; + } + + if (device.node && typeof process.versions === 'object') + { + device.nodeWebkit = !!process.versions['node-webkit']; + + device.electron = !!process.versions.electron; + } + + if (navigator['isCocoonJS']) + { + device.cocoonJS = true; + } + + if (device.cocoonJS) + { + try { + device.cocoonJSApp = (typeof CocoonJS !== 'undefined'); + } + catch(error) + { + device.cocoonJSApp = false; + } + } + + if (typeof window.ejecta !== 'undefined') + { + device.ejecta = true; + } + + if (/Crosswalk/.test(ua)) + { + device.crosswalk = true; + } + + } + + /** + * Check video support. + */ + function _checkVideo () { + + var videoElement = document.createElement("video"); + var result = false; + + try { + if (result = !!videoElement.canPlayType) + { + if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '')) + { + device.oggVideo = true; + } + + if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 + device.h264Video = true; + device.mp4Video = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '')) + { + device.webmVideo = true; + } + + if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '')) + { + device.vp9Video = true; + } + + if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '')) + { + device.hlsVideo = true; + } + } + } catch (e) {} + } + + /** + * Check audio support. + */ + function _checkAudio () { + + device.audioData = !!(window['Audio']); + device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']); + var audioElement = document.createElement('audio'); + var result = false; + + try { + if (result = !!audioElement.canPlayType) + { + if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) + { + device.ogg = true; + } + + if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, '')) + { + device.opus = true; + } + + if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) + { + device.mp3 = true; + } + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) + { + device.wav = true; + } + + if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) + { + device.m4a = true; + } + + if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) + { + device.webm = true; + } + + if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '') + { + if (device.edge) + { + device.dolby = true; + } + else if (device.safari && device.safariVersion >= 9) + { + if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)) + { + var major = parseInt(RegExp.$1, 10); + var minor = parseInt(RegExp.$2, 10); + + if ((major === 10 && minor >= 11) || major > 10) + { + device.dolby = true; + } + } + } + } + } + } catch (e) { + } + + } + + /** + * Check Little or Big Endian system. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsLittleEndian () { + + var a = new ArrayBuffer(4); + var b = new Uint8Array(a); + var c = new Uint32Array(a); + + b[0] = 0xa1; + b[1] = 0xb2; + b[2] = 0xc3; + b[3] = 0xd4; + + if (c[0] === 0xd4c3b2a1) + { + return true; + } + + if (c[0] === 0xa1b2c3d4) + { + return false; + } + else + { + // Could not determine endianness + return null; + } + + } + + /** + * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + * + * @author Matt DesLauriers (@mattdesl) + */ + function _checkIsUint8ClampedImageData () { + + if (Uint8ClampedArray === undefined) + { + return false; + } + + var elem = Phaser.CanvasPool.create(this, 1, 1); + var ctx = elem.getContext('2d'); + + if (!ctx) + { + return false; + } + + var image = ctx.createImageData(1, 1); + + Phaser.CanvasPool.remove(this); + + return image.data instanceof Uint8ClampedArray; + + } + + /** + * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess. + */ + function _checkDevice () { + + device.pixelRatio = window['devicePixelRatio'] || 1; + device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1; + device.iPhone4 = (device.pixelRatio === 2 && device.iPhone); + device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') !== -1; + + if (typeof Int8Array !== 'undefined') + { + device.typedArray = true; + } + else + { + device.typedArray = false; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined') + { + device.littleEndian = _checkIsLittleEndian(); + device.LITTLE_ENDIAN = device.littleEndian; + } + + device.support32bit = (typeof ArrayBuffer !== 'undefined' && typeof Uint8ClampedArray !== 'undefined' && typeof Int32Array !== 'undefined' && device.littleEndian !== null && _checkIsUint8ClampedImageData()); + + navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; + + if (navigator.vibrate) + { + device.vibration = true; + } + + } + + /** + * Check whether the host environment support 3D CSS. + */ + function _checkCSS3D () { + + var el = document.createElement('p'); + var has3d; + var transforms = { + 'webkitTransform': '-webkit-transform', + 'OTransform': '-o-transform', + 'msTransform': '-ms-transform', + 'MozTransform': '-moz-transform', + 'transform': 'transform' + }; + + // Add it to the body to get the computed style. + document.body.insertBefore(el, null); + + for (var t in transforms) + { + if (el.style[t] !== undefined) + { + el.style[t] = "translate3d(1px,1px,1px)"; + has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]); + } + } + + document.body.removeChild(el); + device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none"); + + } + + // Run the checks + _checkOS(); + _checkBrowser(); + _checkAudio(); + _checkVideo(); + _checkCSS3D(); + _checkDevice(); + _checkFeatures(); + _checkCanvasFeatures(); + _checkFullScreenSupport(); + _checkInput(); + +}; + +/** +* Check whether the host environment can play audio. +* +* @method canPlayAudio +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.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 === 'opus' && this.opus) + { + return true; + } + else if (type === 'wav' && this.wav) + { + return true; + } + else if (type === 'webm' && this.webm) + { + return true; + } + else if (type === 'mp4' && this.dolby) + { + return true; + } + + return false; + +}; + +/** +* Check whether the host environment can play video files. +* +* @method canPlayVideo +* @memberof Phaser.Device.prototype +* @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. +* @return {boolean} True if the given file type is supported by the browser, otherwise false. +*/ +Phaser.Device.canPlayVideo = function (type) { + + if (type === 'webm' && (this.webmVideo || this.vp9Video)) + { + return true; + } + else if (type === 'mp4' && (this.mp4Video || this.h264Video)) + { + return true; + } + else if ((type === 'ogg' || type === 'ogv') && this.oggVideo) + { + return true; + } + else if (type === 'mpeg' && this.hlsVideo) + { + return true; + } + + return false; + +}; + +/** + * Whether the device plays audio/video only in response to a user touch event. + * + * @method needsTouchUnlock + * @memberof Phaser.Device.prototype + * @return {boolean} + */ +Phaser.Device.needsTouchUnlock = function () { + return !!(!this.cocoonJS && (this.iOS || this.android) || (window.PhaserGlobal && window.PhaserGlobal.fakeiOSTouchLock)); +}; + +/** +* Detect if the host is a an Android Stock browser. +* This is available before the device "ready" event. +* +* Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. +* +* @example +* var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; +* +* @method isAndroidStockBrowser +* @memberof Phaser.Device.prototype +*/ +Phaser.Device.isAndroidStockBrowser = function () { + + var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/); + return matches && matches[1] < 537; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, +* including styles, offset and aspect ratio. +* +* @class Phaser.Canvas +* @static +*/ +Phaser.Canvas = { + + /** + * Creates a `canvas` DOM element. The element is not automatically added to the document. + * + * @method Phaser.Canvas.create + * @param {object} parent - The object that will own the canvas that is created. + * @param {number} [width=256] - The width of the canvas element. + * @param {number} [height=256] - The height of the canvas element.. + * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. + * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global. + * @return {HTMLCanvasElement} The newly created canvas element. + */ + create: function (parent, width, height, id, skipPool) { + + width = width || 256; + height = height || 256; + + var canvas = (skipPool) ? document.createElement('canvas') : Phaser.CanvasPool.create(parent, width, height); + + if (typeof id === 'string' && id !== '') + { + canvas.id = id; + } + + canvas.width = width; + canvas.height = height; + canvas.style.display = 'block'; + + return canvas; + + }, + + /** + * Sets the background color behind the canvas. This changes the canvas style property. + * + * @method Phaser.Canvas.setBackgroundColor + * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. + * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setBackgroundColor: function (canvas, color) { + + color = color || 'rgb(0,0,0)'; + + canvas.style.backgroundColor = color; + + return canvas; + + }, + + /** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @method Phaser.Canvas.setTouchAction + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @method Phaser.Canvas.setUserSelect + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source 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; + + }, + + /** + * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. + * If no parent is given it will be added as a child of the document.body. + * + * @method Phaser.Canvas.addToDOM + * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM. + * @param {string|HTMLElement} parent - The DOM element to add the canvas to. + * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + addToDOM: function (canvas, parent, overflowHidden) { + + var target; + + if (overflowHidden === undefined) { overflowHidden = true; } + + if (parent) + { + if (typeof parent === 'string') + { + // hopefully an element ID + target = document.getElementById(parent); + } + else if (typeof parent === 'object' && parent.nodeType === 1) + { + // quick test for a HTMLelement + target = parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + target = document.body; + } + + if (overflowHidden && target.style) + { + target.style.overflow = 'hidden'; + } + + target.appendChild(canvas); + + return canvas; + + }, + + /** + * Removes the given canvas element from the DOM. + * + * @method Phaser.Canvas.removeFromDOM + * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM. + */ + removeFromDOM: function (canvas) { + + if (canvas.parentNode) + { + canvas.parentNode.removeChild(canvas); + } + + }, + + /** + * Sets the transform of the given canvas to the matrix values provided. + * + * @method Phaser.Canvas.setTransform + * @param {CanvasRenderingContext2D} context - The context to set the transform on. + * @param {number} translateX - The value to translate horizontally by. + * @param {number} translateY - The value to translate vertically by. + * @param {number} scaleX - The value to scale horizontally by. + * @param {number} scaleY - The value to scale vertically by. + * @param {number} skewX - The value to skew horizontaly by. + * @param {number} skewY - The value to skew vertically by. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) { + + context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); + + return context; + + }, + + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @method Phaser.Canvas.setSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. + * @return {CanvasRenderingContext2D} Returns the source context. + */ + setSmoothingEnabled: function (context, value) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + context[s] = value; + } + + return context; + + }, + + /** + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @method Phaser.Canvas.getSmoothingPrefix + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context. + */ + getSmoothingPrefix: function (context) { + + var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; + + for (var prefix in vendor) + { + var s = vendor[prefix] + 'mageSmoothingEnabled'; + + if (s in context) + { + return s; + } + } + + return null; + + }, + + /** + * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`. + * + * @method Phaser.Canvas.getSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to check for smoothing on. + * @return {boolean} True if the given context has image smoothing enabled, otherwise false. + */ + getSmoothingEnabled: function (context) { + + var s = Phaser.Canvas.getSmoothingPrefix(context); + + if (s) + { + return context[s]; + } + + }, + + /** + * Sets the CSS image-rendering property to `pixelated` or `crisp-edges`. + * This can remove blurring when the game canvas is scaled up. + * In some browsers this has no visible effect in WEBGL mode. + * Note that if this doesn't given the desired result then see the setSmoothingEnabled. + * + * @method Phaser.Canvas.setImageRenderingCrisp + * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. + * @return {HTMLCanvasElement} Returns the source canvas. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering + * @see https://caniuse.com/#feat=css-crisp-edges + */ + setImageRenderingCrisp: function (canvas) { + + var types = [ '-webkit-optimize-contrast', '-moz-crisp-edges', 'crisp-edges', 'pixelated' ]; + + for (var i = 0; i < types.length; i++) + { + canvas.style['image-rendering'] = types[i]; + } + + canvas.style.msInterpolationMode = 'nearest-neighbor'; + + return canvas; + + }, + + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method Phaser.Canvas.setImageRenderingBicubic + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ + setImageRenderingBicubic: function (canvas) { + + canvas.style['image-rendering'] = 'auto'; + canvas.style.msInterpolationMode = 'bicubic'; + + return canvas; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Abstracts away the use of RAF or setTimeOut for the core game update loop. +* +* @class Phaser.RequestAnimationFrame +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available. +*/ +Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) { + + if (forceSetTimeOut === undefined) { forceSetTimeOut = false; } + + /** + * @property {Phaser.Game} game - The currently running game. + */ + this.game = game; + + /** + * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available. + */ + this.forceSetTimeOut = forceSetTimeOut; + + var vendors = [ + 'ms', + 'moz', + 'webkit', + 'o' + ]; + + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) + { + window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; + } + + /** + * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. + * @private + */ + this._isSetTimeOut = false; + + /** + * @property {function} _onLoop - The function called by the update. + * @private + */ + this._onLoop = null; + + /** + * @property {number} _timeOutID - The callback ID used when calling cancel. + * @private + */ + this._timeOutID = null; + +}; + +Phaser.RequestAnimationFrame.prototype = { + + /** + * Starts the requestAnimationFrame running or setTimeout if unavailable in browser + * @method Phaser.RequestAnimationFrame#start + */ + start: function () { + + this.isRunning = true; + + var _this = this; + + if (!window.requestAnimationFrame || this.forceSetTimeOut) + { + this._isSetTimeOut = true; + + this._onLoop = function () { + return _this.updateSetTimeout(); + }; + + this._timeOutID = window.setTimeout(this._onLoop, 0); + } + else + { + this._isSetTimeOut = false; + + this._onLoop = function (time) { + return _this.updateRAF(time); + }; + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the requestAnimationFrame + * @method Phaser.RequestAnimationFrame#updateRAF + */ + updateRAF: function (rafTime) { + + if (this.isRunning) + { + // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below) + this.game.update(Math.floor(rafTime)); + + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } + + }, + + /** + * The update method for the setTimeout. + * @method Phaser.RequestAnimationFrame#updateSetTimeout + */ + updateSetTimeout: function () { + + if (this.isRunning) + { + this.game.update(Date.now()); + + this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); + } + + }, + + /** + * Stops the requestAnimationFrame from running. + * @method Phaser.RequestAnimationFrame#stop + */ + stop: function () { + + if (this._isSetTimeOut) + { + clearTimeout(this._timeOutID); + } + else + { + window.cancelAnimationFrame(this._timeOutID); + } + + this.isRunning = false; + + }, + + /** + * Is the browser using setTimeout? + * @method Phaser.RequestAnimationFrame#isSetTimeOut + * @return {boolean} + */ + isSetTimeOut: function () { + return this._isSetTimeOut; + }, + + /** + * Is the browser using requestAnimationFrame? + * @method Phaser.RequestAnimationFrame#isRAF + * @return {boolean} + */ + isRAF: function () { + return (this._isSetTimeOut === false); + } + +}; + +Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of useful mathematical functions. +* +* These are normally accessed through `game.math`. +* +* @class Phaser.Math +* @static +* @see {@link Phaser.Utils} +* @see {@link Phaser.ArrayUtils} +*/ +Phaser.Math = { + + /** + * Twice PI. + * @property {number} Phaser.Math#PI2 + * @default ~6.283 + */ + PI2: Math.PI * 2, + + /** + * Half PI. + * @property {number} Phaser.Math#HALF_PI + * @default ~1.570 + */ + HALF_PI: Math.PI * 0.5, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#DEG_TO_RAD + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * Degrees to Radians factor. + * @property {number} Phaser.Math#RAD_TO_DEG + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * Convert degrees to radians. + * + * @method Phaser.Math#degToRad + * @param {number} degrees - Angle in degrees. + * @return {number} Angle in radians. + */ + degToRad: function (degrees) { + + return degrees * Phaser.Math.DEG_TO_RAD; + + }, + + /** + * Convert radians to degrees. + * + * @method Phaser.Math#radToDeg + * @param {number} radians - Angle in radians. + * @return {number} Angle in degrees + */ + radToDeg: function (radians) { + + return radians * Phaser.Math.RAD_TO_DEG; + + }, + + /** + * Given a number, this function returns the closest number that is a power of two. + * This function is from the Starling Framework. + * + * @method Phaser.Math#getNextPowerOfTwo + * @param {number} value - The value to get the closest power of two from. + * @return {number} The closest number that is a power of two. + */ + getNextPowerOfTwo: function (value) { + + if (value > 0 && (value & (value - 1)) === 0) + { + // http://goo.gl/D9kPj + return value; + } + else + { + var result = 1; + + while (result < value) + { + result <<= 1; + } + + return result; + } + + }, + + /** + * Checks if the given dimensions make a power of two texture. + * + * @method Phaser.Math#isPowerOfTwo + * @param {number} width - The width to check. + * @param {number} height - The height to check. + * @return {boolean} True if the width and height are a power of two. + */ + isPowerOfTwo: function (width, height) { + + return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); + + }, + + /** + * Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#random + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} A floating point number between min (inclusive) and max (exclusive). + */ + random: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + return (Math.random() * (max - min) + min); + + }, + + /** + * Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#between + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} An integer between min (inclusive) and max (inclusive). + */ + between: function (min, max) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 1; } + + if (min === max) + { + return min; + } + + if (min > max) + { + var temp = min; + min = max; + max = temp; + } + + min = Math.ceil(min); + max = Math.floor(max); + + return Math.floor(Math.random() * (max - min + 1)) + min; + + }, + + /** + * Two number are fuzzyEqual if their difference is less than epsilon. + * + * @method Phaser.Math#fuzzyEqual + * @param {number} a - The first number to compare. + * @param {number} b - The second number to compare. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {boolean} True if |a-b|b+epsilon + */ + fuzzyGreaterThan: function (a, b, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return a > b - epsilon; + + }, + + /** + * Applies a fuzzy ceil to the given value. + * + * @method Phaser.Math#fuzzyCeil + * @param {number} val - The value to ceil. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} ceiling(val-epsilon) + */ + fuzzyCeil: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.ceil(val - epsilon); + + }, + + /** + * Applies a fuzzy floor to the given value. + * + * @method Phaser.Math#fuzzyFloor + * @param {number} val - The value to floor. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} floor(val+epsilon) + */ + fuzzyFloor: function (val, epsilon) { + + if (epsilon === undefined) { epsilon = 0.0001; } + + return Math.floor(val + epsilon); + + }, + + /** + * Averages all values passed to the function and returns the result. + * + * @method Phaser.Math#average + * @params {...number} The numbers to average + * @return {number} The average of all given values. + */ + average: function () { + + var sum = 0; + var len = arguments.length; + + for (var i = 0; i < len; i++) + { + sum += (+arguments[i]); + } + + return sum / len; + + }, + + /** + * @method Phaser.Math#shear + * @param {number} n + * @return {number} n mod 1 + */ + shear: function (n) { + + return n % 1; + + }, + + /** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. + * + * @method Phaser.Math#snapTo + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapTo: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.round(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. + * As will 14 snap to 10... but 16 will snap to 15. + * + * @method Phaser.Math#snapToFloor + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToFloor: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.floor(input / gap); + + return start + input; + + }, + + /** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. + * As will 14 will snap to 15... but 16 will snap to 20. + * + * @method Phaser.Math#snapToCeil + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ + snapToCeil: function (input, gap, start) { + + if (start === undefined) { start = 0; } + + if (gap === 0) { + return input; + } + + input -= start; + input = gap * Math.ceil(input / gap); + + return start + input; + + }, + + /** + * Round to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) === 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + * + * @method Phaser.Math#roundTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + roundTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.round(value * p) / p; + + }, + + /** + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#floorTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + floorTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.floor(value * p) / p; + + }, + + /** + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#ceilTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ + ceilTo: function (value, place, base) { + + if (place === undefined) { place = 0; } + if (base === undefined) { base = 10; } + + var p = Math.pow(base, -place); + + return Math.ceil(value * p) / p; + + }, + + /** + * Rotates currentAngle towards targetAngle, taking the shortest rotation distance. + * The lerp argument is the amount to rotate by in this call. + * + * @method Phaser.Math#rotateToAngle + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * @return {number} The adjusted angle. + */ + rotateToAngle: function (currentAngle, targetAngle, lerp) { + + if (lerp === undefined) { lerp = 0.05; } + + if (currentAngle === targetAngle) + { + return currentAngle; + } + + if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (Phaser.Math.PI2 - lerp)) + { + currentAngle = targetAngle; + } + else + { + if (Math.abs(targetAngle - currentAngle) > Math.PI) + { + if (targetAngle < currentAngle) + { + targetAngle += Phaser.Math.PI2; + } + else + { + targetAngle -= Phaser.Math.PI2; + } + } + + if (targetAngle > currentAngle) + { + currentAngle += lerp; + } + else if (targetAngle < currentAngle) + { + currentAngle -= lerp; + } + } + + return currentAngle; + + }, + + /** + * Gets the shortest angle between `angle1` and `angle2`. + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method, and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * @method Phaser.Math#getShortestAngle + * @param {number} angle1 - The first angle. In the range -180 to 180. + * @param {number} angle2 - The second angle. In the range -180 to 180. + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ + getShortestAngle: function (angle1, angle2) { + + var difference = angle2 - angle1; + + if (difference === 0) + { + return 0; + } + + var times = Math.floor((difference - (-180)) / 360); + + return difference - (times * 360); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @method Phaser.Math#angleBetween + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetween: function (x1, y1, x2, y2) { + + return Math.atan2(y2 - y1, x2 - x1); + + }, + + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels + * down the screen. + * + * @method Phaser.Math#angleBetweenY + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ + angleBetweenY: function (x1, y1, x2, y2) { + + return Math.atan2(x2 - x1, y2 - y1); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * @method Phaser.Math#angleBetweenPoints + * @param {Phaser.Point} point1 - The first point. + * @param {Phaser.Point} point2 - The second point. + * @return {number} The angle between the two points, in radians. + */ + angleBetweenPoints: function (point1, point2) { + + return Math.atan2(point2.y - point1.y, point2.x - point1.x); + + }, + + /** + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * @method Phaser.Math#angleBetweenPointsY + * @param {Phaser.Point} point1 + * @param {Phaser.Point} point2 + * @return {number} The angle, in radians. + */ + angleBetweenPointsY: function (point1, point2) { + + return Math.atan2(point2.x - point1.x, point2.y - point1.y); + + }, + + /** + * Reverses an angle. + * @method Phaser.Math#reverseAngle + * @param {number} angleRad - The angle to reverse, in radians. + * @return {number} The reverse angle, in radians. + */ + reverseAngle: function (angleRad) { + + return this.normalizeAngle(angleRad + Math.PI, true); + + }, + + /** + * Normalizes an angle to the [0,2pi) range. + * @method Phaser.Math#normalizeAngle + * @param {number} angleRad - The angle to normalize, in radians. + * @return {number} The angle, fit within the [0,2pi] range, in radians. + */ + normalizeAngle: function (angleRad) { + + angleRad = angleRad % (2 * Math.PI); + return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI; + + }, + + /** + * Adds the given amount to the value, but never lets the value go over the specified maximum. + * + * @method Phaser.Math#maxAdd + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The new value. + */ + maxAdd: function (value, amount, max) { + + return Math.min(value + amount, max); + + }, + + /** + * Subtracts the given amount from the value, but never lets the value go below the specified minimum. + * + * @method Phaser.Math#minSub + * @param {number} value - The base value. + * @param {number} amount - The amount to subtract from the base value. + * @param {number} min - The minimum the value is allowed to be. + * @return {number} The new value. + */ + minSub: function (value, amount, min) { + + return Math.max(value - amount, min); + + }, + + /** + * Ensures that the value always stays between min and max, by wrapping the value around. + * + * If `max` is not larger than `min` the result is 0. + * + * @method Phaser.Math#wrap + * @param {number} value - The value to wrap. + * @param {number} min - The minimum the value is allowed to be. + * @param {number} max - The maximum the value is allowed to be, should be larger than `min`. + * @return {number} The wrapped value. + */ + wrap: function (value, min, max) { + + var range = max - min; + + if (range <= 0) + { + return 0; + } + + var result = (value - min) % range; + + if (result < 0) + { + result += range; + } + + return result + min; + + }, + + /** + * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. + * + * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. + * + * @method Phaser.Math#wrapValue + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The wrapped value. + */ + wrapValue: function (value, amount, max) { + + var diff; + value = Math.abs(value); + amount = Math.abs(amount); + max = Math.abs(max); + diff = (value + amount) % max; + + return diff; + + }, + + /** + * Returns true if the number given is odd. + * + * @method Phaser.Math#isOdd + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is odd. False if the given number is even. + */ + isOdd: function (n) { + + // Does not work with extremely large values + return !!(n & 1); + + }, + + /** + * Returns true if the number given is even. + * + * @method Phaser.Math#isEven + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is even. False if the given number is odd. + */ + isEven: function (n) { + + // Does not work with extremely large values + return !(n & 1); + + }, + + /** + * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.min` function when appropriate. + * + * @method Phaser.Math#min + * @return {number} The lowest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + 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; i < len; i++) + { + if (data[i] < data[min]) + { + min = i; + } + } + + return data[min]; + + }, + + /** + * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.max` function when appropriate. + * + * @method Phaser.Math#max + * @return {number} The largest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ + max: function () { + + if (arguments.length === 1 && typeof arguments[0] === 'object') + { + var data = arguments[0]; + } + else + { + var data = arguments; + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i] > data[max]) + { + max = i; + } + } + + return data[max]; + + }, + + /** + * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. + * It will find the lowest matching property value from the given objects. + * + * @method Phaser.Math#minProperty + * @return {number} The lowest value from those given. + */ + 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; i < len; i++) + { + if (data[i][property] < data[min][property]) + { + min = i; + } + } + + return data[min][property]; + + }, + + /** + * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. + * It will find the largest matching property value from the given objects. + * + * @method Phaser.Math#maxProperty + * @return {number} The largest value from those given. + */ + maxProperty: function (property) { + + if (arguments.length === 2 && typeof arguments[1] === 'object') + { + var data = arguments[1]; + } + else + { + var data = arguments.slice(1); + } + + for (var i = 1, max = 0, len = data.length; i < len; i++) + { + if (data[i][property] > data[max][property]) + { + max = i; + } + } + + return data[max][property]; + + }, + + /** + * Keeps an angle value between -180 and +180; or -PI and PI if radians. + * + * @method Phaser.Math#wrapAngle + * @param {number} angle - The angle value to wrap + * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected. + * @return {number} The new angle value; will be the same as the input angle if it was within bounds. + */ + wrapAngle: function (angle, radians) { + + return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180); + + }, + + /** + * A Linear Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#linearInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + linearInterpolation: function (v, k) { + + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + + if (k < 0) + { + return this.linear(v[0], v[1], f); + } + + if (k > 1) + { + return this.linear(v[m], v[m - 1], m - f); + } + + return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); + + }, + + /** + * A Bezier Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#bezierInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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; + + }, + + /** + * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#catmullRomInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ + 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[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + } + + }, + + /** + * Calculates a linear (interpolation) value over t. + * + * @method Phaser.Math#linear + * @param {number} p0 + * @param {number} p1 + * @param {number} t - A value between 0 and 1. + * @return {number} + */ + linear: function (p0, p1, t) { + + return (p1 - p0) * t + p0; + + }, + + /** + * @method Phaser.Math#bernstein + * @protected + * @param {number} n + * @param {number} i + * @return {number} + */ + bernstein: function (n, i) { + + return this.factorial(n) / this.factorial(i) / this.factorial(n - i); + + }, + + /** + * @method Phaser.Math#factorial + * @param {number} value - the number you want to evaluate + * @return {number} + */ + factorial: function (value) { + + if (value === 0) + { + return 1; + } + + var res = value; + + while(--value) + { + res *= value; + } + + return res; + + }, + + /** + * Calculates a catmum rom value. + * + * @method Phaser.Math#catmullRom + * @protected + * @param {number} p0 + * @param {number} p1 + * @param {number} p2 + * @param {number} p3 + * @param {number} t + * @return {number} + */ + catmullRom: function (p0, p1, p2, p3, t) { + + var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + + }, + + /** + * The absolute difference between two values. + * + * @method Phaser.Math#difference + * @param {number} a - The first value to check. + * @param {number} b - The second value to check. + * @return {number} The absolute difference between the two values. + */ + difference: function (a, b) { + + return Math.abs(a - b); + + }, + + /** + * Round to the next whole number _away_ from zero. + * + * @method Phaser.Math#roundAwayFromZero + * @param {number} value - Any number. + * @return {integer} The rounded value of that number. + */ + roundAwayFromZero: function (value) { + + // "Opposite" of truncate. + return (value > 0) ? Math.ceil(value) : Math.floor(value); + + }, + + /** + * Generate a sine and cosine table simultaneously and extremely quickly. + * The parameters allow you to specify the length, amplitude and frequency of the wave. + * This generator is fast enough to be used in real-time. + * Code based on research by Franky of scene.at + * + * @method Phaser.Math#sinCosGenerator + * @param {number} length - The length of the wave + * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} frequency - The frequency of the sine and cosine table data + * @return {{sin:number[], cos:number[]}} Returns the table data. + */ + sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) { + + if (sinAmplitude === undefined) { sinAmplitude = 1.0; } + if (cosAmplitude === undefined) { cosAmplitude = 1.0; } + if (frequency === undefined) { frequency = 1.0; } + + var sin = sinAmplitude; + var cos = cosAmplitude; + var frq = frequency * Math.PI / length; + + var cosTable = []; + var sinTable = []; + + for (var c = 0; c < length; c++) { + + cos -= sin * frq; + sin += cos * frq; + + cosTable[c] = cos; + sinTable[c] = sin; + + } + + return { sin: sinTable, cos: cosTable, length: length }; + + }, + + /** + * Returns the length of the hypotenuse connecting two segments of given lengths. + * + * @method Phaser.Math#hypot + * @param {number} a + * @param {number} b + * @return {number} The length of the hypotenuse connecting the given lengths. + */ + hypot: function (a, b) { + + return Math.sqrt(a * a + b * b); + + }, + + /** + * Returns the euclidian distance between the two given set of coordinates. + * + * @method Phaser.Math#distance + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance between the two sets of coordinates. + */ + distance: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Returns the euclidean distance squared between the two given set of + * coordinates (cuts out a square root operation before returning). + * + * @method Phaser.Math#distanceSq + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance squared between the two sets of coordinates. + */ + distanceSq: function (x1, y1, x2, y2) { + + var dx = x1 - x2; + var dy = y1 - y2; + + return dx * dx + dy * dy; + + }, + + /** + * Returns the distance between the two given set of coordinates at the power given. + * + * @method Phaser.Math#distancePow + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} [pow=2] + * @return {number} The distance between the two sets of coordinates. + */ + distancePow: function (x1, y1, x2, y2, pow) { + + if (pow === undefined) { pow = 2; } + + return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); + + }, + + /** + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @method Phaser.Math#clamp + * @param {float} v - The value to be clamped. + * @param {float} min - The minimum bounds. + * @param {float} max - The maximum bounds. + * @return {number} The clamped value. + */ + clamp: function (v, min, max) { + + if (v < min) + { + return min; + } + else if (max < v) + { + return max; + } + else + { + return v; + } + + }, + + /** + * Clamp `x` to the range `[a, Infinity)`. + * Roughly the same as `Math.max(x, a)`, except for NaN handling. + * + * @method Phaser.Math#clampBottom + * @param {number} x + * @param {number} a + * @return {number} + */ + clampBottom: function (x, a) { + + return x < a ? a : x; + + }, + + /** + * Checks if two values are within the given tolerance of each other. + * + * @method Phaser.Math#within + * @param {number} a - The first number to check + * @param {number} b - The second number to check + * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range. + * @return {boolean} True if a is <= tolerance of b. + * @see {@link Phaser.Math.fuzzyEqual} + */ + within: function (a, b, tolerance) { + + return (Math.abs(a - b) <= tolerance); + + }, + + /** + * Linear mapping from range to range + * + * @method Phaser.Math#mapLinear + * @param {number} x - The value to map + * @param {number} a1 - First endpoint of the range + * @param {number} a2 - Final endpoint of the range + * @param {number} b1 - First endpoint of the range + * @param {number} b2 - Final endpoint of the range + * @return {number} + */ + mapLinear: function (x, a1, a2, b1, b2) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + + }, + + /** + * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smoothstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smoothstep: function (x, min, max) { + + // Scale, bias and saturate x to 0..1 range + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + // Evaluate polynomial + return x * x * (3 - 2 * x); + + }, + + /** + * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smootherstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ + smootherstep: function (x, min, max) { + + x = Math.max(0, Math.min(1, (x - min) / (max - min))); + + return x * x * x * (x * (x * 6 - 15) + 10); + + }, + + /** + * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. + * + * This works differently from `Math.sign` for values of NaN and -0, etc. + * + * @method Phaser.Math#sign + * @param {number} x + * @return {integer} An integer in {-1, 0, 1} + */ + sign: function (x) { + + return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); + + }, + + /** + * Work out what percentage value `a` is of value `b` using the given base. + * + * @method Phaser.Math#percent + * @param {number} a - The value to work out the percentage for. + * @param {number} b - The value you wish to get the percentage of. + * @param {number} [base=0] - The base value. + * @return {number} The percentage a is of b, between 0 and 1. + */ + percent: function (a, b, base) { + + if (base === undefined) { base = 0; } + + if (a > b || base > b) + { + return 1; + } + else if (a < base || base > a) + { + return 0; + } + else + { + return (a - base) / b; + } + + } + +}; + +/* jshint noempty: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An extremely useful repeatable random data generator. +* +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. +* +* The random number genererator is based on the Alea PRNG, but is modified. +* - https://github.com/coverslide/node-alea +* - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror +* - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404) +* +* @class Phaser.RandomDataGenerator +* @constructor +* @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}). +*/ +Phaser.RandomDataGenerator = function (seeds) { + + if (seeds === undefined) { seeds = []; } + + /** + * @property {number} c - Internal var. + * @private + */ + this.c = 1; + + /** + * @property {number} s0 - Internal var. + * @private + */ + this.s0 = 0; + + /** + * @property {number} s1 - Internal var. + * @private + */ + this.s1 = 0; + + /** + * @property {number} s2 - Internal var. + * @private + */ + this.s2 = 0; + + if (typeof seeds === 'string') + { + this.state(seeds); + } + else + { + this.sow(seeds); + } + +}; + +Phaser.RandomDataGenerator.prototype = { + + /** + * Private random helper. + * + * @method Phaser.RandomDataGenerator#rnd + * @private + * @return {number} + */ + rnd: function () { + + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + + return this.s2; + }, + + /** + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.RandomDataGenerator#sow + * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used. + */ + sow: function (seeds) { + + // Always reset to default seed + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + this.c = 1; + + if (!seeds) + { + return; + } + + // Apply any seeds + for (var i = 0; i < seeds.length && (seeds[i] != null); i++) + { + var 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); + } + + }, + + /** + * Internal method that creates a seed hash. + * + * @method Phaser.RandomDataGenerator#hash + * @private + * @param {any} data + * @return {number} hashed value. + */ + hash: function (data) { + + var h, i, n; + n = 0xefc8249d; + data = data.toString(); + + for (i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } + + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + + }, + + /** + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#integer + * @return {number} A random integer between 0 and 2^32. + */ + integer: function() { + + return this.rnd.apply(this) * 0x100000000;// 2^32 + + }, + + /** + * Returns a random real number between 0 and 1. + * + * @method Phaser.RandomDataGenerator#frac + * @return {number} A random real number between 0 and 1. + */ + frac: function() { + + return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 + + }, + + /** + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#real + * @return {number} A random real number between 0 and 2^32. + */ + real: function() { + + return this.integer() + this.frac(); + + }, + + /** + * Returns a random integer between and including min and max. + * + * @method Phaser.RandomDataGenerator#integerInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + integerInRange: function (min, max) { + + return Math.floor(this.realInRange(0, max - min + 1) + min); + + }, + + /** + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.RandomDataGenerator#between + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + between: function (min, max) { + + return this.integerInRange(min, max); + + }, + + /** + * Returns a random real number between min and max. + * + * @method Phaser.RandomDataGenerator#realInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ + realInRange: function (min, max) { + + return this.frac() * (max - min) + min; + + }, + + /** + * Returns a random real number between -1 and 1. + * + * @method Phaser.RandomDataGenerator#normal + * @return {number} A random real number between -1 and 1. + */ + normal: function () { + + return 1 - 2 * this.frac(); + + }, + + /** + * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 + * + * @method Phaser.RandomDataGenerator#uuid + * @return {string} A valid RFC4122 version4 ID hex string + */ + 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; + + }, + + /** + * Returns a random member of `array`. + * + * @method Phaser.RandomDataGenerator#pick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + pick: function (ary) { + + return ary[this.integerInRange(0, ary.length - 1)]; + + }, + + /** + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.RandomDataGenerator#sign + * @return {number} -1 or +1. + */ + sign: function () { + + return this.pick([-1, 1]); + + }, + + /** + * Returns a random member of `array`, favoring the earlier entries. + * + * @method Phaser.RandomDataGenerator#weightedPick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + weightedPick: function (ary) { + + return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)]; + + }, + + /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.RandomDataGenerator#timestamp + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random timestamp between min and max. + */ + timestamp: function (min, max) { + + return this.realInRange(min || 946684800000, max || 1577862000000); + + }, + + /** + * Returns a random angle between -180 and 180. + * + * @method Phaser.RandomDataGenerator#angle + * @return {number} A random number between -180 and 180. + */ + angle: function() { + + return this.integerInRange(-180, 180); + + }, + + /** + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.RandomDataGenerator#state + * @param {string} [state] - Generator state to be set. + * @return {string} The current state of the generator. + */ + state: function (state) { + + if (typeof state === 'string' && state.match(/^!rnd/)) + { + state = state.split(','); + + this.c = parseFloat(state[1]); + this.s0 = parseFloat(state[2]); + this.s1 = parseFloat(state[3]); + this.s2 = parseFloat(state[4]); + } + + return ['!rnd', this.c, this.s0, this.s1, this.s2].join(','); + + } + +}; + +Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator; + +/** + * @author Timo Hausmann + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** +* A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. +* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. +* Original version at https://github.com/timohausmann/quadtree-js/ +* +* @class Phaser.QuadTree +* @constructor +* @param {number} x - The top left coordinate of the quadtree. +* @param {number} y - The top left coordinate of the quadtree. +* @param {number} width - The width of the quadtree in pixels. +* @param {number} height - The height of the quadtree in pixels. +* @param {number} [maxObjects=10] - The maximum number of objects per node. +* @param {number} [maxLevels=4] - The maximum number of levels to iterate to. +* @param {number} [level=0] - Which level is this? +*/ +Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) { + + /** + * @property {number} maxObjects - The maximum number of objects per node. + * @default + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - The maximum number of levels to break down to. + * @default + */ + this.maxLevels = 4; + + /** + * @property {number} level - The current level. + */ + this.level = 0; + + /** + * @property {object} bounds - Object that contains the quadtree bounds. + */ + this.bounds = {}; + + /** + * @property {array} objects - Array of quadtree children. + */ + this.objects = []; + + /** + * @property {array} nodes - Array of associated child nodes. + */ + this.nodes = []; + + /** + * @property {array} _empty - Internal empty array. + * @private + */ + this._empty = []; + + this.reset(x, y, width, height, maxObjects, maxLevels, level); + +}; + +Phaser.QuadTree.prototype = { + + /** + * Resets the QuadTree. + * + * @method Phaser.QuadTree#reset + * @param {number} x - The top left coordinate of the quadtree. + * @param {number} y - The top left coordinate of the quadtree. + * @param {number} width - The width of the quadtree in pixels. + * @param {number} height - The height of the quadtree in pixels. + * @param {number} [maxObjects=10] - The maximum number of objects per node. + * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. + * @param {number} [level=0] - Which level is this? + */ + 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; + + }, + + /** + * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. + * + * @method Phaser.QuadTree#populate + * @param {Phaser.Group} group - The Group to add to the quadtree. + */ + populate: function (group) { + + group.forEach(this.populateHandler, this, true); + + }, + + /** + * Handler for the populate method. + * + * @method Phaser.QuadTree#populateHandler + * @param {Phaser.Sprite|object} sprite - The Sprite to check. + */ + populateHandler: function (sprite) { + + if (sprite.body && sprite.exists) + { + this.insert(sprite.body); + } + + }, + + /** + * Split the node into 4 subnodes + * + * @method Phaser.QuadTree#split + */ + split: function () { + + // top right node + this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // top left node + this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom left node + this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + // bottom right node + this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); + + }, + + /** + * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. + * + * @method Phaser.QuadTree#insert + * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. + */ + insert: function (body) { + + var i = 0; + var index; + + // if we have subnodes ... + 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.level < this.maxLevels) + { + // Split if we don't already have subnodes + if (this.nodes[0] == null) + { + this.split(); + } + + // Add objects to subnodes + while (i < this.objects.length) + { + index = this.getIndex(this.objects[i]); + + if (index !== -1) + { + // this is expensive - see what we can do about it + this.nodes[index].insert(this.objects.splice(i, 1)[0]); + } + else + { + i++; + } + } + } + + }, + + /** + * Determine which node the object belongs to. + * + * @method Phaser.QuadTree#getIndex + * @param {Phaser.Rectangle|object} rect - The bounds in which to check. + * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. + */ + getIndex: function (rect) { + + // default is that rect doesn't fit, i.e. it straddles the internal quadrants + var index = -1; + + if (rect.x < this.bounds.right && rect.right < this.bounds.right) + { + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-left quadrant of this quadtree + index = 1; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-left quadrant of this quadtree + index = 2; + } + } + else if (rect.x > this.bounds.right) + { + // rect can completely fit within the right quadrants + if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom) + { + // rect fits within the top-right quadrant of this quadtree + index = 0; + } + else if (rect.y > this.bounds.bottom) + { + // rect fits within the bottom-right quadrant of this quadtree + index = 3; + } + } + + return index; + + }, + + /** + * Return all objects that could collide with the given Sprite or Rectangle. + * + * @method Phaser.QuadTree#retrieve + * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle. + * @return {array} - Array with all detected objects. + */ + 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 rect fits into a subnode .. + if (index !== -1) + { + returnObjects = returnObjects.concat(this.nodes[index].retrieve(source)); + } + else + { + // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed) + 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 the quadtree. + * @method Phaser.QuadTree#clear + */ + 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; + +/** +* Javascript QuadTree +* @version 1.0 +* +* @version 1.3, March 11th 2014 +* @author Richard Davey +* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked +* it massively to add node indexing, removed lots of temp. var creation and significantly +* increased performance as a result. +* +* Original version at https://github.com/timohausmann/quadtree-js/ +*/ + +/** +* @copyright © 2012 Timo Hausmann +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. +* +* @class Phaser.Net +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Net = function (game) { + + this.game = game; + +}; + +Phaser.Net.prototype = { + + /** + * Returns the hostname given by the browser. + * + * @method Phaser.Net#getHostName + * @return {string} + */ + getHostName: function () { + + if (window.location && window.location.hostname) { + return window.location.hostname; + } + + return null; + + }, + + /** + * Compares the given domain name against the hostname of the browser containing the game. + * If the domain name is found it returns true. + * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. + * Do not include 'http://' at the start. + * + * @method Phaser.Net#checkDomainName + * @param {string} domain + * @return {boolean} true if the given domain fragment can be found in the window.location.hostname + */ + checkDomainName: function (domain) { + return window.location.hostname.indexOf(domain) !== -1; + }, + + /** + * Updates a value on the Query String and returns it in full. + * If the value doesn't already exist it is set. + * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. + * Optionally you can redirect to the new url, or just return it as a string. + * + * @method Phaser.Net#updateQueryString + * @param {string} key - The querystring key to update. + * @param {string} value - The new value to be set. If it already exists it will be replaced. + * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. + * @param {string} url - The URL to modify. If none is given it uses window.location.href. + * @return {string} If redirect is false then the modified url and query string is returned. + */ + updateQueryString: function (key, value, redirect, url) { + + if (redirect === undefined) { redirect = false; } + if (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; + } + + }, + + /** + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#getQueryString + * @param {string} [parameter=''] - If specified this will return just the value for that key. + * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. + */ + getQueryString: function (parameter) { + + if (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 && parameter === this.decodeURI(key[0])) + { + return this.decodeURI(key[1]); + } + else + { + output[this.decodeURI(key[0])] = this.decodeURI(key[1]); + } + } + } + + return output; + + }, + + /** + * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and + * decodes it, replacing \ with spaces in the return. Used internally by the Net classes. + * + * @method Phaser.Net#decodeURI + * @param {string} value - The URI component to be decoded. + * @return {string} The decoded value. + */ + decodeURI: function (value) { + return decodeURIComponent(value.replace(/\+/g, " ")); + } + +}; + +Phaser.Net.prototype.constructor = Phaser.Net; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. +* Tweens are hooked into the game clock and pause system, adjusting based on the game state. +* +* TweenManager is based heavily on tween.js by http://soledadpenades.com. +* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. +* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. +* Please see https://github.com/sole/tween.js for a full list of contributors. +* +* @class Phaser.TweenManager +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.TweenManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * @property {boolean} frameBased + * @default + */ + this.frameBased = false; + + /** + * @property {array} _tweens - All of the currently running tweens. + * @private + */ + this._tweens = []; + + /** + * @property {array} _add - All of the tweens queued to be added in the next update. + * @private + */ + this._add = []; + + this.easeMap = { + + "Power0": Phaser.Easing.Power0, + "Power1": Phaser.Easing.Power1, + "Power2": Phaser.Easing.Power2, + "Power3": Phaser.Easing.Power3, + "Power4": Phaser.Easing.Power4, + + "Linear": Phaser.Easing.Linear.None, + "Quad": Phaser.Easing.Quadratic.Out, + "Cubic": Phaser.Easing.Cubic.Out, + "Quart": Phaser.Easing.Quartic.Out, + "Quint": Phaser.Easing.Quintic.Out, + "Sine": Phaser.Easing.Sinusoidal.Out, + "Expo": Phaser.Easing.Exponential.Out, + "Circ": Phaser.Easing.Circular.Out, + "Elastic": Phaser.Easing.Elastic.Out, + "Back": Phaser.Easing.Back.Out, + "Bounce": Phaser.Easing.Bounce.Out, + + "Quad.easeIn": Phaser.Easing.Quadratic.In, + "Cubic.easeIn": Phaser.Easing.Cubic.In, + "Quart.easeIn": Phaser.Easing.Quartic.In, + "Quint.easeIn": Phaser.Easing.Quintic.In, + "Sine.easeIn": Phaser.Easing.Sinusoidal.In, + "Expo.easeIn": Phaser.Easing.Exponential.In, + "Circ.easeIn": Phaser.Easing.Circular.In, + "Elastic.easeIn": Phaser.Easing.Elastic.In, + "Back.easeIn": Phaser.Easing.Back.In, + "Bounce.easeIn": Phaser.Easing.Bounce.In, + + "Quad.easeOut": Phaser.Easing.Quadratic.Out, + "Cubic.easeOut": Phaser.Easing.Cubic.Out, + "Quart.easeOut": Phaser.Easing.Quartic.Out, + "Quint.easeOut": Phaser.Easing.Quintic.Out, + "Sine.easeOut": Phaser.Easing.Sinusoidal.Out, + "Expo.easeOut": Phaser.Easing.Exponential.Out, + "Circ.easeOut": Phaser.Easing.Circular.Out, + "Elastic.easeOut": Phaser.Easing.Elastic.Out, + "Back.easeOut": Phaser.Easing.Back.Out, + "Bounce.easeOut": Phaser.Easing.Bounce.Out, + + "Quad.easeInOut": Phaser.Easing.Quadratic.InOut, + "Cubic.easeInOut": Phaser.Easing.Cubic.InOut, + "Quart.easeInOut": Phaser.Easing.Quartic.InOut, + "Quint.easeInOut": Phaser.Easing.Quintic.InOut, + "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut, + "Expo.easeInOut": Phaser.Easing.Exponential.InOut, + "Circ.easeInOut": Phaser.Easing.Circular.InOut, + "Elastic.easeInOut": Phaser.Easing.Elastic.InOut, + "Back.easeInOut": Phaser.Easing.Back.InOut, + "Bounce.easeInOut": Phaser.Easing.Bounce.InOut + + }; + + this.game.onPause.add(this._pauseAll, this); + this.game.onResume.add(this._resumeAll, this); + +}; + +Phaser.TweenManager.prototype = { + + /** + * Get all the tween objects in an array. + * @method Phaser.TweenManager#getAll + * @returns {Phaser.Tween[]} Array with all tween objects. + */ + getAll: function () { + + return this._tweens; + + }, + + /** + * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. + * @method Phaser.TweenManager#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._tweens.length; i++) + { + this._tweens[i].pendingDelete = true; + } + + this._add = []; + + }, + + /** + * Remove all tweens from a specific object, array of objects or Group. + * + * @method Phaser.TweenManager#removeFrom + * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. + * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. + */ + removeFrom: function (obj, children) { + + if (children === undefined) { children = true; } + + var i; + var len; + + if (Array.isArray(obj)) + { + for (i = 0, len = obj.length; i < len; i++) + { + this.removeFrom(obj[i]); + } + } + else if (obj.type === Phaser.GROUP && children) + { + for (var i = 0, len = obj.children.length; i < len; i++) + { + this.removeFrom(obj.children[i]); + } + } + else + { + for (i = 0, len = this._tweens.length; i < len; i++) + { + if (obj === this._tweens[i].target) + { + this.remove(this._tweens[i]); + } + } + + for (i = 0, len = this._add.length; i < len; i++) + { + if (obj === this._add[i].target) + { + this.remove(this._add[i]); + } + } + } + + }, + + /** + * Add a new tween into the TweenManager. + * + * @method Phaser.TweenManager#add + * @param {Phaser.Tween} tween - The tween object you want to add. + * @returns {Phaser.Tween} The tween object you added to the manager. + */ + add: function (tween) { + + tween._manager = this; + this._add.push(tween); + + }, + + /** + * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.TweenManager#create + * @param {object} object - Object the tween will be run on. + * @returns {Phaser.Tween} The newly created tween object. + */ + create: function (object) { + + return new Phaser.Tween(object, this.game, this); + + }, + + /** + * Remove a tween from this manager. + * + * @method Phaser.TweenManager#remove + * @param {Phaser.Tween} tween - The tween object you want to remove. + */ + remove: function (tween) { + + var i = this._tweens.indexOf(tween); + + if (i !== -1) + { + this._tweens[i].pendingDelete = true; + } + else + { + i = this._add.indexOf(tween); + + if (i !== -1) + { + this._add[i].pendingDelete = true; + } + } + + }, + + /** + * Update all the tween objects you added to this manager. + * + * @method Phaser.TweenManager#update + * @returns {boolean} Return false if there's no tween to update, otherwise return true. + */ + update: function () { + + var addTweens = this._add.length; + var numTweens = this._tweens.length; + + if (numTweens === 0 && addTweens === 0) + { + return false; + } + + var i = 0; + + while (i < numTweens) + { + if (this._tweens[i].update(this.game.time.time)) + { + i++; + } + else + { + this._tweens.splice(i, 1); + + numTweens--; + } + } + + // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running + if (addTweens > 0) + { + this._tweens = this._tweens.concat(this._add); + this._add.length = 0; + } + + return true; + + }, + + /** + * Checks to see if a particular Sprite is currently being tweened. + * + * The `checkIsRunning` parameter will exclude tweens that have **just** completed or been stopped but haven't yet been removed from the manager. + * + * @method Phaser.TweenManager#isTweening + * @param {object} object - The object to check for tweens against. + * @param {boolean} [checkIsRunning=false] - Also check that the tween is running and is not marked for deletion. + * @returns {boolean} Returns true if the object is currently being tweened, false if not. + */ + isTweening: function(object, checkIsRunning) { + + if (!checkIsRunning) { checkIsRunning = false; } + + return this._tweens.some(function(tween) { + return (tween.target === object) && (!checkIsRunning || (tween.isRunning && !tween.pendingDelete)); + }); + + }, + + /** + * Private. Called by game focus loss. Pauses all currently running tweens. + * + * @method Phaser.TweenManager#_pauseAll + * @private + */ + _pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._pause(); + } + + }, + + /** + * Private. Called by game focus loss. Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#_resumeAll + * @private + */ + _resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i]._resume(); + } + + }, + + /** + * Pauses all currently running tweens. + * + * @method Phaser.TweenManager#pauseAll + */ + pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].pause(); + } + + }, + + /** + * Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#resumeAll + */ + resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) + { + this._tweens[i].resume(true); + } + + } + +}; + +Phaser.TweenManager.prototype.constructor = Phaser.TweenManager; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tween allows you to alter one or more properties of a target object over a defined period of time. +* This can be used for things such as alpha fading Sprites, scaling them or motion. +* Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object +* by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and +* are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. +* +* @class Phaser.Tween +* @constructor +* @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. +* @param {Phaser.Game} game - Current game instance. +* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. +*/ +Phaser.Tween = function (target, game, manager) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. + */ + this.target = target; + + /** + * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween. + */ + this.manager = manager; + + /** + * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween. + */ + this.timeline = []; + + /** + * If set to `true` the current tween will play in reverse. + * If the tween hasn't yet started this has no effect. + * If there are child tweens then all child tweens will play in reverse from the current point. + * @property {boolean} reverse + * @default + */ + this.reverse = false; + + /** + * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. + * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. + * + * @property {number} timeScale + * @default + */ + this.timeScale = 1; + + /** + * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count. + */ + this.repeatCounter = 0; + + /** + * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager. + * @default + * @readonly + */ + this.pendingDelete = false; + + /** + * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onStart + */ + this.onStart = new Phaser.Signal(); + + /** + * The onLoop event is fired if the Tween, or any child tweens loop. + * It will be sent 2 parameters: the target object and this tween. + * + * @property {Phaser.Signal} onLoop + */ + this.onLoop = new Phaser.Signal(); + + /** + * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onRepeat + */ + this.onRepeat = new Phaser.Signal(); + + /** + * The onChildComplete event is fired when the Tween or any of its children completes. + * Fires every time a child completes unless a child is set to repeat forever. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onChildComplete + */ + this.onChildComplete = new Phaser.Signal(); + + /** + * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. + * @default + */ + this.isRunning = false; + + /** + * @property {number} current - The current Tween child being run. + * @default + * @readonly + */ + this.current = 0; + + /** + * @property {object} properties - Target property cache used when building the child data values. + */ + this.properties = {}; + + /** + * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it. + */ + this.chainedTween = null; + + /** + * @property {boolean} isPaused - Is this Tween paused or not? + * @default + */ + this.isPaused = false; + + /** + * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * + * The default value is whatever you've set in TweenManager.frameBased. + * + * @property {boolean} frameBased + * @default + */ + this.frameBased = manager.frameBased; + + /** + * @property {function} _onUpdateCallback - An onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallback = null; + + /** + * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. + * @private + * @default null + */ + this._onUpdateCallbackContext = null; + + /** + * @property {number} _pausedTime - Private pause timer. + * @private + * @default + */ + this._pausedTime = 0; + + /** + * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not. + * @private + */ + this._hasStarted = false; +}; + +/** +* A helper for tweening {@link Phaser.Color.createColor color objects}. +* +* It can be passed to {@link #onUpdateCallback}. +* +* ```javascript +* var color = Phaser.Color.createColor(255, 0, 0); // red +* +* var tween = game.add.tween(color).to({ +* r: 0, g: 0, b: 255 // blue +* }); +* +* tween.onUpdateCallback(Phaser.Tween.updateColor); +* +* tween.start(); +* ``` +* +* @method Phaser.Tween.updateColor +* @static +* @param {Phaser.Tween} tween - A Tween with a {@link #target} that is a {@link Phaser.Color.createColor color object}. +*/ +Phaser.Tween.updateColor = function (tween) { + + Phaser.Color.updateColor(tween.target); + +}; + +Phaser.Tween.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#to + * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined || duration <= 0) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.to cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#from + * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ + from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { + + if (duration === undefined) { duration = 1000; } + if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } + if (autoStart === undefined) { autoStart = false; } + if (delay === undefined) { delay = 0; } + if (repeat === undefined) { repeat = 0; } + if (yoyo === undefined) { yoyo = false; } + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + if (this.isRunning) + { + console.warn('Phaser.Tween.from cannot be called after Tween.start'); + return this; + } + + this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo)); + + if (autoStart) + { + this.start(); + } + + return this; + + }, + + /** + * Starts the tween running. Can also be called by the `autoStart` parameter of {@link #to} or {@link #from}. + * This sets the {@link #isRunning} property to `true` and dispatches the {@link #onStart} signal. + * If the tween has a delay set then nothing will start tweening until the delay has expired. + * If the tween is already running, is flagged for deletion (such as after {@link #stop}), + * or has an empty timeline, calling start has no effect and the `onStart` signal is not dispatched. + * + * @method Phaser.Tween#start + * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + start: function (index) { + + if (index === undefined) { index = 0; } + + if (this.pendingDelete) + { + console.warn('Phaser.Tween.start cannot be called after Tween.stop'); + return this; + } + + if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning) + { + return this; + } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + this.manager.add(this); + + this.isRunning = true; + + if (index < 0 || index > this.timeline.length - 1) + { + index = 0; + } + + this.current = index; + + this.timeline[this.current].start(); + + return this; + + }, + + /** + * Stops the tween if running and flags it for deletion from the TweenManager. The tween can't be {@link #start restarted} after this. + * The {@link #onComplete} signal is not dispatched and no chained tweens are started unless the `complete` parameter is set to `true`. + * If you just wish to pause a tween then use {@link #pause} instead. + * If the tween is not running, it is **not** flagged for deletion and can be started again. + * + * @method Phaser.Tween#stop + * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + stop: function (complete) { + + if (complete === undefined) { complete = false; } + + this.isRunning = false; + + this._onUpdateCallback = null; + this._onUpdateCallbackContext = null; + + if (complete) + { + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + } + + this.manager.remove(this); + + return this; + + }, + + /** + * Updates either a single TweenData or all TweenData objects properties to the given value. + * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. + * The property is not checked, so if you pass an invalid one you'll generate a run-time error. + * + * @method Phaser.Tween#updateTweenData + * @param {string} property - The property to update. + * @param {number|function} value - The value to set the property to. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + updateTweenData: function (property, value, index) { + + if (this.timeline.length === 0) { return this; } + + if (index === undefined) { index = 0; } + + if (index === -1) + { + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i][property] = value; + } + } + else + { + this.timeline[index][property] = value; + } + + return this; + + }, + + /** + * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. + * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. + * If you have child tweens and pass -1 as the index value it sets the delay across all of them. + * + * @method Phaser.Tween#delay + * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + delay: function (duration, index) { + + return this.updateTweenData('delay', duration, index); + + }, + + /** + * Sets the number of times this tween will repeat. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. + * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. + * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. + * + * @method Phaser.Tween#repeat + * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeat: function (total, repeatDelay, index) { + + if (repeatDelay === undefined) { repeatDelay = 0; } + + this.updateTweenData('repeatCounter', total, index); + this.updateTweenData('repeatTotal', total, index); + + return this.updateTweenData('repeatDelay', repeatDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will repeat itself. + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#repeatDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatDelay: function (duration, index) { + + return this.updateTweenData('repeatDelay', duration, index); + + }, + + /** + * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. + * Used in combination with repeat you can create endless loops. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. + * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. + * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. + * + * @method Phaser.Tween#yoyo + * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo. + * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyo: function(enable, yoyoDelay, index) { + + if (yoyoDelay === undefined) { yoyoDelay = 0; } + + this.updateTweenData('yoyo', enable, index); + + return this.updateTweenData('yoyoDelay', yoyoDelay, index); + + }, + + /** + * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#yoyoDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + yoyoDelay: function (duration, index) { + + return this.updateTweenData('yoyoDelay', duration, index); + + }, + + /** + * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. + * + * @method Phaser.Tween#easing + * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + easing: function (ease, index) { + + if (typeof ease === 'string' && this.manager.easeMap[ease]) + { + ease = this.manager.easeMap[ease]; + } + + return this.updateTweenData('easingFunction', ease, index); + + }, + + /** + * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. + * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. + * The interpolation function is only used if the target properties is an array. + * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. + * + * @method Phaser.Tween#interpolation + * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) + * @param {object} [context] - The context under which the interpolation function will be run. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + interpolation: function (interpolation, context, index) { + + if (context === undefined) { context = Phaser.Math; } + + this.updateTweenData('interpolationFunction', interpolation, index); + + return this.updateTweenData('interpolationContext', context, index); + + }, + + /** + * Set how many times this tween and all of its children will repeat. + * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. + * + * @method Phaser.Tween#repeatAll + * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + repeatAll: function (total) { + + if (total === undefined) { total = 0; } + + this.repeatCounter = total; + + return this; + + }, + + /** + * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called + * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. + * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. + * For that you should listen to `onComplete` on the final tween in your chain. + * + * If you pass multiple tweens to this method they will be joined into a single long chain. + * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. + * Any previously chained tweens that may have been set will be overwritten. + * + * @method Phaser.Tween#chain + * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + chain: function () { + + var i = arguments.length; + + while (i--) + { + if (i > 0) + { + arguments[i - 1].chainedTween = arguments[i]; + } + else + { + this.chainedTween = arguments[i]; + } + } + + return this; + + }, + + /** + * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. + * + * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. + * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. + * + * Usage: + * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) + * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) + * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) + * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) + * .loop(); + * @method Phaser.Tween#loop + * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + loop: function (value) { + + if (value === undefined) { value = true; } + + this.repeatCounter = (value) ? -1 : 0; + + return this; + + }, + + /** + * Sets a callback to be fired each time this tween updates. + * + * The callback receives the current Tween, the {@link Phaser.TweenData#value 'value' of the current TweenData}, and the current {@link Phaser.TweenData TweenData}. The second parameter is most useful. + * + * ```javascript + * tween.onUpdateCallback(function (tween, value, tweenData) { + * console.log('Tween running -- percent: %.2f value: %.2f', tweenData.percent, value); + * }); + * ``` + * + * @method Phaser.Tween#onUpdateCallback + * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. + * @param {object} callbackContext - The context in which to call the onUpdate callback. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ + onUpdateCallback: function (callback, callbackContext) { + + this._onUpdateCallback = callback; + this._onUpdateCallbackContext = callbackContext; + + return this; + + }, + + /** + * Pauses the tween. Resume playback with Tween.resume. + * + * @method Phaser.Tween#pause + */ + pause: function () { + + this.isPaused = true; + + this._codePaused = true; + + this._pausedTime = this.game.time.time; + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * + * @private + * @method Phaser.Tween#_pause + */ + _pause: function () { + + if (!this._codePaused) + { + this.isPaused = true; + + this._pausedTime = this.game.time.time; + } + + }, + + /** + * Resumes a paused tween. + * + * @method Phaser.Tween#resume + */ + resume: function () { + + if (this.isPaused) + { + this.isPaused = false; + + this._codePaused = false; + + for (var i = 0; i < this.timeline.length; i++) + { + if (!this.timeline[i].isRunning) + { + this.timeline[i].startTime += (this.game.time.time - this._pausedTime); + } + } + } + + }, + + /** + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * @method Phaser.Tween#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Core tween update function called by the TweenManager. Does not need to be invoked directly. + * + * @method Phaser.Tween#update + * @param {number} time - A timestamp passed in by the TweenManager. + * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). + */ + update: function (time) { + + if (this.pendingDelete || !this.target) + { + return false; + } + + if (this.isPaused) + { + return true; + } + + var status = this.timeline[this.current].update(time); + + if (status === Phaser.TweenData.PENDING) + { + return true; + } + else if (status === Phaser.TweenData.RUNNING) + { + if (!this._hasStarted) + { + this.onStart.dispatch(this.target, this); + this._hasStarted = true; + } + + if (this._onUpdateCallback !== null) + { + this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]); + } + + // In case the update callback modifies this tween + return this.isRunning; + } + else if (status === Phaser.TweenData.LOOPED) + { + if (this.timeline[this.current].repeatCounter === -1) + { + this.onLoop.dispatch(this.target, this); + } + else + { + this.onRepeat.dispatch(this.target, this); + } + + return true; + } + else if (status === Phaser.TweenData.COMPLETE) + { + var complete = false; + + // What now? + if (this.reverse) + { + this.current--; + + if (this.current < 0) + { + this.current = this.timeline.length - 1; + complete = true; + } + } + else + { + this.current++; + + if (this.current === this.timeline.length) + { + this.current = 0; + complete = true; + } + } + + if (complete) + { + // We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it? + if (this.repeatCounter === -1) + { + this.timeline[this.current].start(); + this.onLoop.dispatch(this.target, this); + return true; + } + else if (this.repeatCounter > 0) + { + this.repeatCounter--; + + this.timeline[this.current].start(); + this.onRepeat.dispatch(this.target, this); + return true; + } + else + { + // No more repeats and no more children, so we're done + this.isRunning = false; + this.onComplete.dispatch(this.target, this); + this._hasStarted = false; + + if (this.chainedTween) + { + this.chainedTween.start(); + } + + return false; + } + } + else + { + // We've still got some children to go + this.onChildComplete.dispatch(this.target, this); + this.timeline[this.current].start(); + return true; + } + } + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * It ignores delay and repeat counts and any chained tweens, but does include child tweens. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.Tween#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate, data) { + + if (this.game === null || this.target === null) + { + return null; + } + + if (frameRate === undefined) { frameRate = 60; } + if (data === undefined) { data = []; } + + // Populate the tween data + for (var i = 0; i < this.timeline.length; i++) + { + // Build our master property list with the starting values + for (var property in this.timeline[i].vEnd) + { + this.properties[property] = this.target[property] || 0; + + if (!Array.isArray(this.properties[property])) + { + // Ensures we're using numbers, not strings + this.properties[property] *= 1.0; + } + } + } + + for (var i = 0; i < this.timeline.length; i++) + { + this.timeline[i].loadValues(); + } + + for (var i = 0; i < this.timeline.length; i++) + { + data = data.concat(this.timeline[i].generateData(frameRate)); + } + + return data; + + } + +}; + +/** +* @name Phaser.Tween#totalDuration +* @property {number} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds. +*/ +Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', { + + get: function () { + + var total = 0; + + for (var i = 0; i < this.timeline.length; i++) + { + total += this.timeline[i].duration; + } + + return total; + + } + +}); + +Phaser.Tween.prototype.constructor = Phaser.Tween; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the +* starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for +* TweenData objects and can contain multiple TweenData objects. +* +* @class Phaser.TweenData +* @constructor +* @param {Phaser.Tween} parent - The Tween that owns this TweenData object. +*/ +Phaser.TweenData = function (parent) { + + /** + * @property {Phaser.Tween} parent - The Tween which owns this TweenData. + */ + this.parent = parent; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = parent.game; + + /** + * @property {object} vStart - An object containing the values at the start of the tween. + * @private + */ + this.vStart = {}; + + /** + * @property {object} vStartCache - Cached starting values. + * @private + */ + this.vStartCache = {}; + + /** + * @property {object} vEnd - An object containing the values at the end of the tween. + * @private + */ + this.vEnd = {}; + + /** + * @property {object} vEndCache - Cached ending values. + * @private + */ + this.vEndCache = {}; + + /** + * @property {number} duration - The duration of the tween in ms. + * @default + */ + this.duration = 1000; + + /** + * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is. + * @readonly + */ + this.percent = 0; + + /** + * @property {number} value - The output of the easing function for the current {@link #percent}. Depending on the easing function, this will be within [0, 1] or a slightly larger range (e.g., Bounce). When easing is Linear, this will be identical to {@link #percent}. + * @readonly + */ + this.value = 0; + + /** + * @property {number} repeatCounter - If the Tween is set to repeat this is the number of repeats remaining (and `repeatTotal - repeatCounter` is the number of repeats completed). + */ + this.repeatCounter = 0; + + /** + * @property {number} repeatDelay - The amount of time in ms between repeats of this tween. + */ + this.repeatDelay = 0; + + /** + * @property {number} repeatTotal - The total number of times this Tween will repeat. + * @readonly + */ + this.repeatTotal = 0; + + /** + * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween) + * @default + * @todo Appears unused. + */ + this.interpolate = false; + + /** + * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false. + * @default + */ + this.yoyo = false; + + /** + * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween. + */ + this.yoyoDelay = 0; + + /** + * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). + * @default + */ + this.inReverse = false; + + /** + * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. + * @default + */ + this.delay = 0; + + /** + * @property {number} dt - Current time value. + */ + this.dt = 0; + + /** + * @property {number} startTime - The time the Tween started or null if it hasn't yet started. + */ + this.startTime = null; + + /** + * @property {function} easingFunction - The easing function used for the Tween. + * @default Phaser.Easing.Default + */ + this.easingFunction = Phaser.Easing.Default; + + /** + * @property {function} interpolationFunction - The interpolation function used for Array-based Tween. + * @default Phaser.Math.linearInterpolation + */ + this.interpolationFunction = Phaser.Math.linearInterpolation; + + /** + * @property {object} interpolationContext - The interpolation function context used for the Tween. + * @default Phaser.Math + */ + this.interpolationContext = Phaser.Math; + + /** + * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. + * @default + */ + this.isRunning = false; + + /** + * @property {boolean} isFrom - Is this a from tween or a to tween? + * @default + */ + this.isFrom = false; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.PENDING = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.RUNNING = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.LOOPED = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.TweenData.COMPLETE = 3; + +Phaser.TweenData.prototype = { + + /** + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * + * @method Phaser.TweenData#to + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + to: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = false; + + return this; + + }, + + /** + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * + * @method Phaser.TweenData#from + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ + from: function (properties, duration, ease, delay, repeat, yoyo) { + + this.vEnd = properties; + this.duration = duration; + this.easingFunction = ease; + this.delay = delay; + this.repeatTotal = repeat; + this.yoyo = yoyo; + + this.isFrom = true; + + return this; + + }, + + /** + * Starts the Tween running. + * + * @method Phaser.TweenData#start + * @return {Phaser.TweenData} This Tween object. + */ + start: function () { + + this.startTime = this.game.time.time + this.delay; + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + if (this.delay > 0) + { + this.isRunning = false; + } + else + { + this.isRunning = true; + } + + if (this.isFrom) + { + // Reverse them all and instant set them + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + this.parent.target[property] = this.vStart[property]; + } + } + + this.value = 0; + this.repeatCounter = this.repeatTotal; + + return this; + + }, + + /** + * Loads the values from the target object into this Tween. + * + * @private + * @method Phaser.TweenData#loadValues + * @return {Phaser.TweenData} This Tween object. + */ + loadValues: function () { + + for (var property in this.parent.properties) + { + // Load the property from the parent object + this.vStart[property] = this.parent.properties[property]; + + // Check if an Array was provided as property value + if (Array.isArray(this.vEnd[property])) + { + if (this.vEnd[property].length === 0) + { + continue; + } + + if (this.percent === 0) + { + // Put the start value at the beginning of the array + // but we only want to do this once, if the Tween hasn't run before + this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]); + } + } + + if (typeof this.vEnd[property] !== 'undefined') + { + if (typeof this.vEnd[property] === 'string') + { + // Parses relative end values with start as base (e.g.: +10, -3) + this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10); + } + + this.parent.properties[property] = this.vEnd[property]; + } + else + { + // Null tween + this.vEnd[property] = this.vStart[property]; + } + + this.vStartCache[property] = this.vStart[property]; + this.vEndCache[property] = this.vEnd[property]; + } + + return this; + + }, + + /** + * Updates this Tween. This is called automatically by Phaser.Tween. + * + * @protected + * @method Phaser.TweenData#update + * @param {number} time - A timestamp passed in by the Tween parent. + * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. + */ + update: function (time) { + + if (!this.isRunning) + { + if (time >= this.startTime) + { + this.isRunning = true; + } + else + { + return Phaser.TweenData.PENDING; + } + } + else + { + // Is Running, but is waiting to repeat + if (time < this.startTime) + { + return Phaser.TweenData.RUNNING; + } + } + + var ms = (this.parent.frameBased) ? this.game.time.physicsElapsedMS : this.game.time.elapsedMS; + + if (this.parent.reverse) + { + this.dt -= ms * this.parent.timeScale; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += ms * this.parent.timeScale; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + this.parent.target[property] = start + ((end - start) * this.value); + } + } + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + return this.repeat(); + } + + return Phaser.TweenData.RUNNING; + + }, + + /** + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.TweenData#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @return {array} An array of tweened values. + */ + generateData: function (frameRate) { + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + var data = []; + var complete = false; + var fps = (1 / frameRate) * 1000; + + do + { + if (this.parent.reverse) + { + this.dt -= fps; + this.dt = Math.max(this.dt, 0); + } + else + { + this.dt += fps; + this.dt = Math.min(this.dt, this.duration); + } + + this.percent = this.dt / this.duration; + + this.value = this.easingFunction(this.percent); + + var blob = {}; + + for (var property in this.vEnd) + { + var start = this.vStart[property]; + var end = this.vEnd[property]; + + if (Array.isArray(end)) + { + blob[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value); + } + else + { + blob[property] = start + ((end - start) * this.value); + } + } + + data.push(blob); + + if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0)) + { + complete = true; + } + + } while (!complete); + + if (this.yoyo) + { + var reversed = data.slice(); + reversed.reverse(); + data = data.concat(reversed); + } + + return data; + + }, + + /** + * Checks if this Tween is meant to repeat or yoyo and handles doing so. + * + * @private + * @method Phaser.TweenData#repeat + * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE. + */ + repeat: function () { + + // If not a yoyo and repeatCounter = 0 then we're done + if (this.yoyo) + { + // We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end + if (this.inReverse && this.repeatCounter === 0) + { + // Restore the properties + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + this.inReverse = false; + + return Phaser.TweenData.COMPLETE; + } + + this.inReverse = !this.inReverse; + } + else + { + if (this.repeatCounter === 0) + { + return Phaser.TweenData.COMPLETE; + } + } + + if (this.inReverse) + { + // If inReverse we're going from vEnd to vStartCache + for (var property in this.vStartCache) + { + this.vStart[property] = this.vEndCache[property]; + this.vEnd[property] = this.vStartCache[property]; + } + } + else + { + // If not inReverse we're just repopulating the cache again + for (var property in this.vStartCache) + { + this.vStart[property] = this.vStartCache[property]; + this.vEnd[property] = this.vEndCache[property]; + } + + // -1 means repeat forever, otherwise decrement the repeatCounter + // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total + if (this.repeatCounter > 0) + { + this.repeatCounter--; + } + } + + this.startTime = this.game.time.time; + + if (this.yoyo && this.inReverse) + { + this.startTime += this.yoyoDelay; + } + else if (!this.inReverse) + { + this.startTime += this.repeatDelay; + } + + if (this.parent.reverse) + { + this.dt = this.duration; + } + else + { + this.dt = 0; + } + + return Phaser.TweenData.LOOPED; + + } + +}; + +Phaser.TweenData.prototype.constructor = Phaser.TweenData; + +/* jshint curly: false */ + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of easing methods defining ease-in and ease-out curves. +* +* @class Phaser.Easing +*/ +Phaser.Easing = { + + /** + * Linear easing. + * + * @class Phaser.Easing.Linear + */ + Linear: { + + /** + * Linear Easing (no variation). + * + * @method Phaser.Easing.Linear#None + * @param {number} k - The value to be tweened. + * @returns {number} k. + */ + None: function ( k ) { + + return k; + + } + + }, + + /** + * Quadratic easing. + * + * @class Phaser.Easing.Quadratic + */ + Quadratic: { + + /** + * Ease-in. + * + * @method Phaser.Easing.Quadratic#In + * @param {number} k - The value to be tweened. + * @returns {number} k^2. + */ + In: function ( k ) { + + return k * k; + + }, + + /** + * Ease-out. + * + * @method Phaser.Easing.Quadratic#Out + * @param {number} k - The value to be tweened. + * @returns {number} k* (2-k). + */ + Out: function ( k ) { + + return k * ( 2 - k ); + + }, + + /** + * Ease-in/out. + * + * @method Phaser.Easing.Quadratic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; + return - 0.5 * ( --k * ( k - 2 ) - 1 ); + + } + + }, + + /** + * Cubic easing. + * + * @class Phaser.Easing.Cubic + */ + Cubic: { + + /** + * Cubic ease-in. + * + * @method Phaser.Easing.Cubic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k; + + }, + + /** + * Cubic ease-out. + * + * @method Phaser.Easing.Cubic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k + 1; + + }, + + /** + * Cubic ease-in/out. + * + * @method Phaser.Easing.Cubic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k + 2 ); + + } + + }, + + /** + * Quartic easing. + * + * @class Phaser.Easing.Quartic + */ + Quartic: { + + /** + * Quartic ease-in. + * + * @method Phaser.Easing.Quartic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k; + + }, + + /** + * Quartic ease-out. + * + * @method Phaser.Easing.Quartic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return 1 - ( --k * k * k * k ); + + }, + + /** + * Quartic ease-in/out. + * + * @method Phaser.Easing.Quartic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; + return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); + + } + + }, + + /** + * Quintic easing. + * + * @class Phaser.Easing.Quintic + */ + Quintic: { + + /** + * Quintic ease-in. + * + * @method Phaser.Easing.Quintic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k * k * k * k * k; + + }, + + /** + * Quintic ease-out. + * + * @method Phaser.Easing.Quintic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return --k * k * k * k * k + 1; + + }, + + /** + * Quintic ease-in/out. + * + * @method Phaser.Easing.Quintic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); + + } + + }, + + /** + * Sinusoidal easing. + * + * @class Phaser.Easing.Sinusoidal + */ + Sinusoidal: { + + /** + * Sinusoidal ease-in. + * + * @method Phaser.Easing.Sinusoidal#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 1 - Math.cos( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-out. + * + * @method Phaser.Easing.Sinusoidal#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return Math.sin( k * Math.PI / 2 ); + + }, + + /** + * Sinusoidal ease-in/out. + * + * @method Phaser.Easing.Sinusoidal#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if (k === 0) return 0; + if (k === 1) return 1; + return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); + + } + + }, + + /** + * Exponential easing. + * + * @class Phaser.Easing.Exponential + */ + Exponential: { + + /** + * Exponential ease-in. + * + * @method Phaser.Easing.Exponential#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return k === 0 ? 0 : Math.pow( 1024, k - 1 ); + + }, + + /** + * Exponential ease-out. + * + * @method Phaser.Easing.Exponential#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); + + }, + + /** + * Exponential ease-in/out. + * + * @method Phaser.Easing.Exponential#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); + return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); + + } + + }, + + /** + * Circular easing. + * + * @class Phaser.Easing.Circular + */ + Circular: { + + /** + * Circular ease-in. + * + * @method Phaser.Easing.Circular#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Math.sqrt( 1 - k * k ); + + }, + + /** + * Circular ease-out. + * + * @method Phaser.Easing.Circular#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return Math.sqrt( 1 - ( --k * k ) ); + + }, + + /** + * Circular ease-in/out. + * + * @method Phaser.Easing.Circular#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); + return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); + + } + + }, + + /** + * Elastic easing. + * + * @class Phaser.Easing.Elastic + */ + Elastic: { + + /** + * Elastic ease-in. + * + * @method Phaser.Easing.Elastic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + + }, + + /** + * Elastic ease-out. + * + * @method Phaser.Easing.Elastic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); + + }, + + /** + * Elastic ease-in/out. + * + * @method Phaser.Easing.Elastic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; + + } + + }, + + /** + * Back easing. + * + * @class Phaser.Easing.Back + */ + Back: { + + /** + * Back ease-in. + * + * @method Phaser.Easing.Back#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + var s = 1.70158; + return k * k * ( ( s + 1 ) * k - s ); + + }, + + /** + * Back ease-out. + * + * @method Phaser.Easing.Back#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + var s = 1.70158; + return --k * k * ( ( s + 1 ) * k + s ) + 1; + + }, + + /** + * Back ease-in/out. + * + * @method Phaser.Easing.Back#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + var s = 1.70158 * 1.525; + if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); + return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); + + } + + }, + + /** + * Bounce easing. + * + * @class Phaser.Easing.Bounce + */ + Bounce: { + + /** + * Bounce ease-in. + * + * @method Phaser.Easing.Bounce#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { + + return 1 - Phaser.Easing.Bounce.Out( 1 - k ); + + }, + + /** + * Bounce ease-out. + * + * @method Phaser.Easing.Bounce#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + if ( k < ( 1 / 2.75 ) ) { + + return 7.5625 * k * k; + + } else if ( k < ( 2 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; + + } else if ( k < ( 2.5 / 2.75 ) ) { + + return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; + + } else { + + return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; + + } + + }, + + /** + * Bounce ease-in/out. + * + * @method Phaser.Easing.Bounce#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5; + return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5; + + } + + } + +}; + +Phaser.Easing.Default = Phaser.Easing.Linear.None; +Phaser.Easing.Power0 = Phaser.Easing.Linear.None; +Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out; +Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out; +Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out; +Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* This is the core internal game clock. +* +* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, +* and also handles the standard Timer pool. +* +* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}. +* +* There are different *types* of time in Phaser: +* +* - ***Game time*** always runs at the speed of time in real life. +* +* Unlike wall-clock time, *game time stops when Phaser is paused*. +* +* Game time is used for {@link Phaser.Timer timer events}. +* +* - ***Physics time*** represents the amount of time given to physics calculations. +* +* *When {@link #slowMotion} is in effect physics time runs slower than game time.* +* Like game time, physics time stops when Phaser is paused. +* +* Physics time is used for physics calculations and {@link Phaser.Tween tweens}. +* +* - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time. +* +* This time is independent of Phaser and always progresses, regardless of if Phaser is paused. +* +* @class Phaser.Time +* @constructor +* @param {Phaser.Game} game A reference to the currently running game. +*/ +Phaser.Time = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * The `Date.now()` value when the time was last updated. + * @property {integer} time + * @protected + */ + this.time = 0; + + /** + * The `now` when the previous update occurred. + * @property {number} prevTime + * @protected + */ + this.prevTime = 0; + + /** + * An increasing value representing cumulative milliseconds since an undisclosed epoch. + * + * While this value is in milliseconds and can be used to compute time deltas, + * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference. + * + * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; + * the value can only be relied upon within a particular game instance. + * + * @property {number} now + * @protected + */ + this.now = 0; + + /** + * Elapsed time since the last time update, in milliseconds, based on `now`. + * + * This value _may_ include time that the game is paused/inactive. + * + * While the game is active, this will be similar to (1000 / {@link #fps}). + * + * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {number} elapsed + * @see Phaser.Time.time + * @protected + */ + this.elapsed = 0; + + /** + * The time in ms since the last time update, in milliseconds, based on `time`. + * + * This value is corrected for game pauses and will be "about zero" after a game is resumed. + * + * _Note:_ This is updated once per game loop - even if multiple logic update steps are done. + * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead. + * + * @property {integer} elapsedMS + * @protected + */ + this.elapsedMS = 0; + + /** + * The physics update delta, in fractional seconds. + * + * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) + * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system + * is unable to consistently maintain the desired FPS. + * + * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. + * + * @property {number} physicsElapsed + */ + this.physicsElapsed = 1 / 60; + + /** + * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. + * + * @property {number} physicsElapsedMS + */ + this.physicsElapsedMS = (1 / 60) * 1000; + + /** + * The desiredFps multiplier as used by Game.update. + * @property {integer} desiredFpsMult + * @protected + */ + this.desiredFpsMult = 1.0 / 60; + + /** + * The desired frame rate of the game. + * + * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates. + * + * @property {number} _desiredFps + * @private + * @default + */ + this._desiredFps = 60; + + /** + * The suggested frame rate for your game, based on an averaged real frame rate. + * This value is only populated if `Time.advancedTiming` is enabled. + * + * _Note:_ This is not available until after a few frames have passed; until then + * it's set to the same value as desiredFps. + * + * @property {number} suggestedFps + * @default + */ + this.suggestedFps = this.desiredFps; + + /** + * Scaling factor to make the game move smoothly in slow motion (or fast motion) + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * You likely need to adjust {@link #desiredFps} as well such that `desiredFps / slowMotion === 60`. + * + * @property {number} slowMotion + * @default + */ + this.slowMotion = 1.0; + + /** + * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. This isn't expensive, but displaying it with {@link Phaser.Utils.Debug#text} can be, especially in WebGL mode. + * @property {boolean} advancedTiming + * @default + */ + this.advancedTiming = false; + + /** + * Advanced timing result: The number of animation frames received from the browser in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} frames + * @readonly + */ + this.frames = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateLogic logic updates} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} updates + * @readonly + */ + this.updates = 0; + + /** + * Advanced timing result: The number of {@link Phaser.Game#updateRender renders} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} renders + * @readonly + */ + this.renders = 0; + + /** + * Advanced timing result: Frames per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} fps + * @readonly + */ + this.fps = 0; + + /** + * Advanced timing result: Logic updates per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} ups + * @readonly + */ + this.ups = 0; + + /** + * Advanced timing result: Renders per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} rps + * @readonly + */ + this.rps = 0; + + /** + * Advanced timing result: The lowest rate the fps has dropped to. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMin + */ + this.fpsMin = 1000; + + /** + * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMax + */ + this.fpsMax = 0; + + /** + * Advanced timing result: The minimum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMin + * @default + */ + this.msMin = 1000; + + /** + * Advanced timing result: The maximum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMax + */ + this.msMax = 0; + + /** + * Records how long the game was last paused, in milliseconds. + * (This is not updated until the game is resumed.) + * @property {number} pauseDuration + */ + this.pauseDuration = 0; + + /** + * @property {number} timeToCall - The value that setTimeout needs to work out when to next update + * @protected + */ + this.timeToCall = 0; + + /** + * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop + * @protected + */ + this.timeExpected = 0; + + /** + * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to. + * @property {Phaser.Timer} events + */ + this.events = new Phaser.Timer(this.game, false); + + /** + * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated + * @private + */ + this._frameCount = 0; + + /** + * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated + * @private + */ + this._elapsedAccumulator = 0; + + /** + * @property {number} _started - The time at which the Game instance started. + * @private + */ + this._started = 0; + + /** + * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. + * @private + */ + this._timeLastSecond = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {boolean} _justResumed - Internal value used to recover from the game pause state. + * @private + */ + this._justResumed = false; + + /** + * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects. + * @private + */ + this._timers = []; + +}; + +Phaser.Time.prototype = { + + /** + * Called automatically by Phaser.Game after boot. Should not be called directly. + * + * @method Phaser.Time#boot + * @protected + */ + boot: function () { + + this._started = Date.now(); + this.time = Date.now(); + this.events.start(); + this.timeExpected = this.time; + + }, + + /** + * Adds an existing Phaser.Timer object to the Timer pool. + * + * @method Phaser.Time#add + * @param {Phaser.Timer} timer - An existing Phaser.Timer object. + * @return {Phaser.Timer} The given Phaser.Timer object. + */ + add: function (timer) { + + this._timers.push(timer); + + return timer; + + }, + + /** + * Creates a new stand-alone Phaser.Timer object. + * + * @method Phaser.Time#create + * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). + * @return {Phaser.Timer} The Timer object that was created. + */ + create: function (autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + var timer = new Phaser.Timer(this.game, autoDestroy); + + this._timers.push(timer); + + return timer; + + }, + + /** + * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer. + * + * @method Phaser.Time#removeAll + */ + removeAll: function () { + + for (var i = 0; i < this._timers.length; i++) + { + this._timers[i].destroy(); + } + + this._timers = []; + + this.events.removeAll(); + + }, + + /** + * Refreshes the Time.time and Time.elapsedMS properties from the system clock. + * + * @method Phaser.Time#refresh + */ + refresh: function () { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + }, + + /** + * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. + * + * @method Phaser.Time#update + * @protected + * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}. + */ + update: function (time) { + + // Set to the old Date.now value + var previousDateNow = this.time; + + // this.time always holds a Date.now value + this.time = Date.now(); + + // Adjust accordingly. + this.elapsedMS = this.time - previousDateNow; + + // 'now' is currently still holding the time of the last call, move it into prevTime + this.prevTime = this.now; + + // update 'now' to hold the current time + // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now) + this.now = time; + + // elapsed time between previous call and now - this could be a high resolution value + this.elapsed = this.now - this.prevTime; + + if (this.game.raf._isSetTimeOut) + { + // console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time); + + // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game + this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time))); + + // time when the next call is expected if using timers + this.timeExpected = time + this.timeToCall; + + // console.log('Time expect', this.timeExpected); + } + + if (this.advancedTiming) + { + this.updateAdvancedTiming(); + } + + // Paused but still running? + if (!this.game.paused) + { + // Our internal Phaser.Timer + this.events.update(this.time); + + if (this._timers.length) + { + this.updateTimers(); + } + } + + }, + + /** + * Handles the updating of the Phaser.Timers (if any) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateTimers + * @private + */ + updateTimers: function () { + + // Any game level timers + var i = 0; + var len = this._timers.length; + + while (i < len) + { + if (this._timers[i].update(this.time)) + { + i++; + } + else + { + // Timer requests to be removed + this._timers.splice(i, 1); + len--; + } + } + + }, + + /** + * Handles the updating of the advanced timing values (if enabled) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateAdvancedTiming + * @private + */ + updateAdvancedTiming: function () { + + // count the number of time.update calls + this._frameCount++; + this._elapsedAccumulator += this.elapsed; + + // occasionally recalculate the suggestedFps based on the accumulated elapsed time + if (this._frameCount >= this._desiredFps * 2) + { + // this formula calculates suggestedFps in multiples of 5 fps + this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5; + this._frameCount = 0; + this._elapsedAccumulator = 0; + } + + this.msMin = Math.min(this.msMin, this.elapsed); + this.msMax = Math.max(this.msMax, this.elapsed); + + this.frames++; + + if (this.now > this._timeLastSecond + 1000) + { + var interval = this.now - this._timeLastSecond; + this.fps = Math.round((this.frames * 1000) / interval); + this.ups = Math.round((this.updates * 1000) / interval); + this.rps = Math.round((this.renders * 1000) / interval); + this.fpsMin = Math.min(this.fpsMin, this.fps); + this.fpsMax = Math.max(this.fpsMax, this.fps); + this._timeLastSecond = this.now; + this.frames = 0; + this.updates = 0; + this.renders = 0; + } + + }, + + /** + * Counts one logic update (if advanced timing is enabled). + * + * @method Phaser.Time#countUpdate + * @private + */ + countUpdate: function () { + + if (this.advancedTiming) + { + this.updates++; + } + + }, + + /** + * Counts one render (if advanced timing is enabled). + * + * @method Phaser.Time#countRender + * @private + */ + countRender: function () { + + if (this.advancedTiming) + { + this.renders++; + } + + }, + + /** + * Called when the game enters a paused state. + * + * @method Phaser.Time#gamePaused + * @private + */ + gamePaused: function () { + + this._pauseStarted = Date.now(); + + this.events.pause(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._pause(); + } + + }, + + /** + * Called when the game resumes from a paused state. + * + * @method Phaser.Time#gameResumed + * @private + */ + gameResumed: function () { + + // Set the parameter which stores Date.now() to make sure it's correct on resume + this.time = Date.now(); + + this.pauseDuration = this.time - this._pauseStarted; + + this.events.resume(); + + var i = this._timers.length; + + while (i--) + { + this._timers[i]._resume(); + } + + }, + + /** + * The number of seconds that have elapsed since the game was started. + * + * @method Phaser.Time#totalElapsedSeconds + * @return {number} The number of seconds that have elapsed since the game was started. + */ + totalElapsedSeconds: function() { + return (this.time - this._started) * 0.001; + }, + + /** + * How long has passed since the given time. + * + * @method Phaser.Time#elapsedSince + * @param {number} since - The time you want to measure against. + * @return {number} The difference between the given time and now. + */ + elapsedSince: function (since) { + return this.time - since; + }, + + /** + * How long has passed since the given time (in seconds). + * + * @method Phaser.Time#elapsedSecondsSince + * @param {number} since - The time you want to measure (in seconds). + * @return {number} Duration between given time and now (in seconds). + */ + elapsedSecondsSince: function (since) { + return (this.time - since) * 0.001; + }, + + /** + * Resets the private _started value to now and removes all currently running Timers. + * + * @method Phaser.Time#reset + */ + reset: function () { + + this._started = this.time; + this.removeAll(); + + } + +}; + +/** +* The number of logic updates per second. +* +* This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. +* +* The render rate is unaffected unless you also turn off {@link Phaser.Game#forceSingleRender}. +* +* @name Phaser.Time#desiredFps +* @type {integer} +* @default 60 +*/ +Object.defineProperty(Phaser.Time.prototype, "desiredFps", { + + get: function () { + + return this._desiredFps; + + }, + + set: function (value) { + + this._desiredFps = value; + + // Set the physics elapsed time... this will always be 1 / this.desiredFps + // because we're using fixed time steps in game.update + this.physicsElapsed = 1 / value; + + this.physicsElapsedMS = this.physicsElapsed * 1000; + + this.desiredFpsMult = 1.0 / value; + + } + +}); + +Phaser.Time.prototype.constructor = Phaser.Time; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback. +* Many different timer events, with individual delays, can be added to the same Timer. +* +* All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. +* +* Timers are based on real life time, adjusted for game pause durations. +* That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account. +* +* @class Phaser.Timer +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). +*/ +Phaser.Timer = function (game, autoDestroy) { + + if (autoDestroy === undefined) { autoDestroy = true; } + + /** + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ + this.game = game; + + /** + * True if the Timer is actively running. + * + * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer. + * @property {boolean} running + * @default + * @readonly + */ + this.running = false; + + /** + * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). + * @property {boolean} autoDestroy + */ + this.autoDestroy = autoDestroy; + + /** + * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending. + * @readonly + * @default + */ + this.expired = false; + + /** + * @property {number} elapsed - Elapsed time since the last frame (in ms). + * @protected + */ + this.elapsed = 0; + + /** + * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. + */ + this.events = []; + + /** + * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. + * + * The signal is supplied with one argument, `timer`, which is this Timer object. + * + * @property {Phaser.Signal} onComplete + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {number} nextTick - The time the next tick will occur. + * @readonly + * @protected + */ + this.nextTick = 0; + + /** + * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. + */ + this.timeCap = 1000; + + /** + * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. + * @readonly + * @default + */ + this.paused = false; + + /** + * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss? + * @private + */ + this._codePaused = false; + + /** + * @property {number} _started - The time at which this Timer instance started running. + * @private + * @default + */ + this._started = 0; + + /** + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ + this._pauseStarted = 0; + + /** + * @property {number} _pauseTotal - Total paused time. + * @private + */ + this._pauseTotal = 0; + + /** + * @property {number} _now - The current start-time adjusted time. + * @private + */ + this._now = Date.now(); + + /** + * @property {number} _len - Temp. array length variable. + * @private + */ + this._len = 0; + + /** + * @property {number} _marked - Temp. counter variable. + * @private + */ + this._marked = 0; + + /** + * @property {number} _i - Temp. array counter variable. + * @private + */ + this._i = 0; + + /** + * @property {number} _diff - Internal cache var. + * @private + */ + this._diff = 0; + + /** + * @property {number} _newTick - Internal cache var. + * @private + */ + this._newTick = 0; + +}; + +/** +* Number of milliseconds in a minute. +* @constant +* @type {integer} +*/ +Phaser.Timer.MINUTE = 60000; + +/** +* Number of milliseconds in a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.SECOND = 1000; + +/** +* Number of milliseconds in half a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.HALF = 500; + +/** +* Number of milliseconds in a quarter of a second. +* @constant +* @type {integer} +*/ +Phaser.Timer.QUARTER = 250; + +Phaser.Timer.prototype = { + + /** + * Creates a new TimerEvent on this Timer. + * + * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. + * + * @method Phaser.Timer#create + * @private + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {boolean} loop - Should the event loop or not? + * @param {number} repeatCount - The number of times the event will repeat. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {any[]} arguments - The values to be sent to your callback function when it is called. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + create: function (delay, loop, repeatCount, callback, callbackContext, args) { + + delay = Math.round(delay); + + var tick = delay; + + if (this._now === 0) + { + tick += this.game.time.time; + } + else + { + tick += this._now; + } + + var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args); + + this.events.push(event); + + this.order(); + + this.expired = false; + + return event; + + }, + + /** + * Adds a new Event to this Timer. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#add + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + add: function (delay, callback, callbackContext) { + + return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. + * If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#repeat + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + repeat: function (delay, repeatCount, callback, callbackContext) { + + return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4)); + + }, + + /** + * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#loop + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ + loop: function (delay, callback, callbackContext) { + + return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); + + }, + + /** + * Starts this Timer running. + * @method Phaser.Timer#start + * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start. + */ + start: function (delay) { + + if (this.running) + { + return; + } + + this._started = this.game.time.time + (delay || 0); + + this.running = true; + + for (var i = 0; i < this.events.length; i++) + { + this.events[i].tick = this.events[i].delay + this._started; + } + + }, + + /** + * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. + * @method Phaser.Timer#stop + * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain. + */ + stop: function (clearEvents) { + + this.running = false; + + if (clearEvents === undefined) { clearEvents = true; } + + if (clearEvents) + { + this.events.length = 0; + } + + }, + + /** + * Removes a pending TimerEvent from the queue. + * @param {Phaser.TimerEvent} event - The event to remove from the queue. + * @method Phaser.Timer#remove + */ + remove: function (event) { + + for (var i = 0; i < this.events.length; i++) + { + if (this.events[i] === event) + { + this.events[i].pendingDelete = true; + return true; + } + } + + return false; + + }, + + /** + * Orders the events on this Timer so they are in tick order. + * This is called automatically when new events are created. + * @method Phaser.Timer#order + * @protected + */ + order: function () { + + if (this.events.length > 0) + { + // Sort the events so the one with the lowest tick is first + this.events.sort(this.sortHandler); + + this.nextTick = this.events[0].tick; + } + + }, + + /** + * Sort handler used by Phaser.Timer.order. + * @method Phaser.Timer#sortHandler + * @private + */ + sortHandler: function (a, b) { + + if (a.tick < b.tick) + { + return -1; + } + else if (a.tick > b.tick) + { + return 1; + } + + return 0; + + }, + + /** + * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values. + * + * @method Phaser.Timer#clearPendingEvents + * @protected + */ + 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; + + }, + + /** + * The main Timer update event, called automatically by Phaser.Time.update. + * + * @method Phaser.Timer#update + * @protected + * @param {number} time - The time from the core game clock. + * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. + */ + update: function (time) { + + if (this.paused) + { + return true; + } + + this.elapsed = time - this._now; + this._now = time; + + // spike-dislike + if (this.elapsed > this.timeCap) + { + // For some reason the time between now and the last time the game was updated was larger than our timeCap. + // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause. + // In this case we need to adjust the TimerEvents and nextTick. + this.adjustEvents(time - this.elapsed); + } + + this._marked = 0; + + // Clears events marked for deletion and resets _len and _i to 0. + this.clearPendingEvents(); + + if (this.running && this._now >= this.nextTick && this._len > 0) + { + while (this._i < this._len && this.running) + { + var event = this.events[this._i]; + + if (this._now >= event.tick && !event.pendingDelete) + { + // (now + delay) - (time difference from last tick to now) + this._newTick = (this._now + event.delay) - (this._now - event.tick); + + if (this._newTick < 0) + { + this._newTick = this._now + event.delay; + } + + if (event.loop === true) + { + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else if (event.repeatCount > 0) + { + event.repeatCount--; + event.tick = this._newTick; + event.callback.apply(event.callbackContext, event.args); + } + else + { + this._marked++; + event.pendingDelete = true; + event.callback.apply(event.callbackContext, event.args); + } + + this._i++; + } + else + { + break; + } + } + + // Are there any events left? + 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; + } + + }, + + /** + * Pauses the Timer and all events in the queue. + * @method Phaser.Timer#pause + */ + pause: function () { + + if (!this.running) + { + return; + } + + this._codePaused = true; + + if (this.paused) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Internal pause/resume control - user code should use Timer.pause instead. + * @method Phaser.Timer#_pause + * @private + */ + _pause: function () { + + if (this.paused || !this.running) + { + return; + } + + this._pauseStarted = this.game.time.time; + + this.paused = true; + + }, + + /** + * Adjusts the time of all pending events and the nextTick by the given baseTime. + * + * @method Phaser.Timer#adjustEvents + * @protected + */ + adjustEvents: function (baseTime) { + + for (var i = 0; i < this.events.length; i++) + { + if (!this.events[i].pendingDelete) + { + // Work out how long there would have been from when the game paused until the events next tick + var t = this.events[i].tick - baseTime; + + if (t < 0) + { + t = 0; + } + + // Add the difference on to the time now + this.events[i].tick = this._now + t; + } + } + + var d = this.nextTick - baseTime; + + if (d < 0) + { + this.nextTick = this._now; + } + else + { + this.nextTick = this._now + d; + } + + }, + + /** + * Resumes the Timer and updates all pending events. + * + * @method Phaser.Timer#resume + */ + resume: function () { + + if (!this.paused) + { + return; + } + + var now = this.game.time.time; + this._pauseTotal += now - this._now; + this._now = now; + + this.adjustEvents(this._pauseStarted); + + this.paused = false; + this._codePaused = false; + + }, + + /** + * Internal pause/resume control - user code should use Timer.resume instead. + * @method Phaser.Timer#_resume + * @private + */ + _resume: function () { + + if (this._codePaused) + { + return; + } + else + { + this.resume(); + } + + }, + + /** + * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#removeAll + */ + removeAll: function () { + + this.onComplete.removeAll(); + this.events.length = 0; + this._len = 0; + this._i = 0; + + }, + + /** + * Destroys this Timer. Any pending Events are not dispatched. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#destroy + */ + destroy: function () { + + this.onComplete.removeAll(); + this.running = false; + this.expired = true; + this.events = []; + this._len = 0; + this._i = 0; + + } + +}; + +/** +* @name Phaser.Timer#next +* @property {number} next - The time at which the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "next", { + + get: function () { + return this.nextTick; + } + +}); + +/** +* @name Phaser.Timer#duration +* @property {number} duration - The duration in ms remaining until the next event will occur. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "duration", { + + get: function () { + + if (this.running && this.nextTick > this._now) + { + return this.nextTick - this._now; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#length +* @property {number} length - The number of pending events in the queue. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "length", { + + get: function () { + return this.events.length; + } + +}); + +/** +* @name Phaser.Timer#ms +* @property {number} ms - The duration in milliseconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "ms", { + + get: function () { + + if (this.running) + { + return this._now - this._started - this._pauseTotal; + } + else + { + return 0; + } + + } + +}); + +/** +* @name Phaser.Timer#seconds +* @property {number} seconds - The duration in seconds that this Timer has been running for. +* @readonly +*/ +Object.defineProperty(Phaser.Timer.prototype, "seconds", { + + get: function () { + + if (this.running) + { + return this.ms * 0.001; + } + else + { + return 0; + } + + } + +}); + +Phaser.Timer.prototype.constructor = Phaser.Timer; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TimerEvent is a single event that is processed by a Phaser.Timer. +* +* It consists of a delay, which is a value in milliseconds after which the event will fire. +* When the event fires it calls a specific callback with the specified arguments. +* +* TimerEvents are removed by their parent timer once finished firing or repeating. +* +* Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. +* +* @class Phaser.TimerEvent +* @constructor +* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. +* @param {number} delay - The delay in ms at which this TimerEvent fires. +* @param {number} tick - The tick is the next game clock time that this event will fire at. +* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times. +* @param {boolean} loop - True if this TimerEvent loops, otherwise false. +* @param {function} callback - The callback that will be called when the TimerEvent occurs. +* @param {object} callbackContext - The context in which the callback will be called. +* @param {any[]} arguments - Additional arguments to be passed to the callback. +*/ +Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) { + + /** + * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. + * @protected + * @readonly + */ + this.timer = timer; + + /** + * @property {number} delay - The delay in ms at which this TimerEvent fires. + */ + this.delay = delay; + + /** + * @property {number} tick - The tick is the next game clock time that this event will fire at. + */ + this.tick = tick; + + /** + * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times. + */ + this.repeatCount = repeatCount - 1; + + /** + * @property {boolean} loop - True if this TimerEvent loops, otherwise false. + */ + this.loop = loop; + + /** + * @property {function} callback - The callback that will be called when the TimerEvent occurs. + */ + this.callback = callback; + + /** + * @property {object} callbackContext - The context in which the callback will be called. + */ + this.callbackContext = callbackContext; + + /** + * @property {any[]} arguments - Additional arguments to be passed to the callback. + */ + this.args = args; + + /** + * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion. + * @protected + */ + this.pendingDelete = false; + +}; + +Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Animation Manager is used to add, play and update Phaser Animations. +* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. +* +* @class Phaser.AnimationManager +* @constructor +* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. +*/ +Phaser.AnimationManager = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = sprite.game; + + /** + * The currently displayed Frame of animation, if any. + * This property is only set once an Animation starts playing. Until that point it remains set as `null`. + * + * @property {Phaser.Frame} currentFrame + * @default + */ + this.currentFrame = null; + + /** + * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any. + * @default + */ + this.currentAnim = null; + + /** + * @property {boolean} updateIfVisible - Update the animation data only while the the sprite is {@link Phaser.Sprite#visible}. Set to `false` to continue updating while the sprite is invisible. + * @default + */ + this.updateIfVisible = true; + + /** + * @property {boolean} isLoaded - Set to true once animation data has been loaded. + * @default + */ + this.isLoaded = false; + + /** + * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. + * @private + * @default + */ + this._frameData = null; + + /** + * @property {object} _anims - An internal object that stores all of the Animation instances. + * @private + */ + this._anims = {}; + + /** + * @property {object} _outputFrames - An internal object to help avoid gc. + * @private + */ + this._outputFrames = []; + +}; + +Phaser.AnimationManager.prototype = { + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#loadFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + loadFrameData: function (frameData, frame) { + + if (frameData === undefined) + { + return false; + } + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(frameData); + } + } + + this._frameData = frameData; + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#copyFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ + copyFrameData: function (frameData, frame) { + + this._frameData = frameData.clone(); + + if (this.isLoaded) + { + // We need to update the frameData that the animations are using + for (var anim in this._anims) + { + this._anims[anim].updateFrameData(this._frameData); + } + } + + if (frame === undefined || frame === null) + { + this.frame = 0; + } + else + { + if (typeof frame === 'string') + { + this.frameName = frame; + } + else + { + this.frame = frame; + } + } + + this.isLoaded = true; + + return true; + }, + + /** + * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. + * Animations added in this way are played back with the play function. + * + * @method Phaser.AnimationManager#add + * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". + * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. + * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. + * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? + * @return {Phaser.Animation} The Animation object that was created. + */ + add: function (name, frames, frameRate, loop, useNumericIndex) { + + frames = frames || []; + frameRate = frameRate || 60; + + if (loop === undefined) { loop = false; } + + // If they didn't set the useNumericIndex then let's at least try and guess it + if (useNumericIndex === undefined) + { + if (frames && typeof frames[0] === 'number') + { + useNumericIndex = true; + } + else + { + useNumericIndex = false; + } + } + + this._outputFrames = []; + + 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]; + + if (this.sprite.tilingTexture) + { + this.sprite.refreshTexture = true; + } + + return this._anims[name]; + + }, + + /** + * Check whether the frames in the given array are valid and exist. + * + * @method Phaser.AnimationManager#validateFrames + * @param {Array} frames - An array of frames to be validated. + * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) + * @return {boolean} True if all given Frames are valid, otherwise false. + */ + validateFrames: function (frames, useNumericIndex) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + + for (var i = 0; i < frames.length; i++) + { + if (useNumericIndex === true) + { + if (frames[i] > this._frameData.total) + { + return false; + } + } + else + { + if (this._frameData.checkFrameName(frames[i]) === false) + { + return false; + } + } + } + + return true; + + }, + + /** + * Play an animation based on the given key. The animation should previously have been added via `animations.add` + * + * If the requested animation is already playing this request will be ignored. + * If you need to reset an already running animation do so directly on the Animation object itself. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.AnimationManager#play + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation instance. + */ + 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); + } + + return this.currentAnim; + } + else + { + if (this.currentAnim && this.currentAnim.isPlaying) + { + this.currentAnim.stop(); + } + + this.currentAnim = this._anims[name]; + this.currentAnim.paused = false; + this.currentFrame = this.currentAnim.currentFrame; + return this.currentAnim.play(frameRate, loop, killOnComplete); + } + } + + }, + + /** + * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. + * The currentAnim property of the AnimationManager is automatically set to the animation given. + * + * @method Phaser.AnimationManager#stop + * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. + * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) + */ + stop: function (name, resetFrame) { + + if (resetFrame === undefined) { resetFrame = false; } + + if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name)) + { + this.currentAnim.stop(resetFrame); + } + + }, + + /** + * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. + * + * @method Phaser.AnimationManager#update + * @protected + * @return {boolean} True if a new animation frame has been set, otherwise false. + */ + update: function () { + + if (this.updateIfVisible && !this.sprite.visible) + { + return false; + } + + if (this.currentAnim && this.currentAnim.update()) + { + this.currentFrame = this.currentAnim.currentFrame; + return true; + } + + return false; + + }, + + /** + * Advances by the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.next(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Moves backwards the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (this.currentAnim) + { + this.currentAnim.previous(quantity); + this.currentFrame = this.currentAnim.currentFrame; + } + + }, + + /** + * Returns an animation that was previously added by name. + * + * @method Phaser.AnimationManager#getAnimation + * @param {string} name - The name of the animation to be returned, e.g. "fire". + * @return {Phaser.Animation} The Animation instance, if found, otherwise null. + */ + getAnimation: function (name) { + + if (typeof name === 'string') + { + if (this._anims[name]) + { + return this._anims[name]; + } + } + + return null; + + }, + + /** + * Refreshes the current frame data back to the parent Sprite and also resets the texture data. + * + * @method Phaser.AnimationManager#refreshFrame + */ + refreshFrame: function () { + + // TODO + // this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); + + }, + + /** + * Destroys all references this AnimationManager contains. + * Iterates through the list of animations stored in this manager and calls destroy on each of them. + * + * @method Phaser.AnimationManager#destroy + */ + destroy: function () { + + var anim = null; + + for (var anim in this._anims) + { + if (this._anims.hasOwnProperty(anim)) + { + this._anims[anim].destroy(); + } + } + + this._anims = {}; + this._outputFrames = []; + this._frameData = null; + this.currentAnim = null; + this.currentFrame = null; + this.sprite = null; + this.game = null; + + } + +}; + +Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager; + +/** +* @name Phaser.AnimationManager#frameData +* @property {Phaser.FrameData} frameData - The current animations FrameData. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', { + + get: function () { + return this._frameData; + } + +}); + +/** +* @name Phaser.AnimationManager#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', { + + get: function () { + + return this._frameData.total; + } + +}); + +/** +* @name Phaser.AnimationManager#paused +* @property {boolean} paused - Gets and sets the paused state of the current animation. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', { + + get: function () { + + return this.currentAnim.isPaused; + + }, + + set: function (value) { + + this.currentAnim.paused = value; + + } + +}); + +/** +* @name Phaser.AnimationManager#name +* @property {string} name - Gets the current animation name, if set. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'name', { + + get: function () { + + if (this.currentAnim) + { + return this.currentAnim.name; + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.index; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'number' && this._frameData && (gotFrame = this._frameData.getFrame(value))) + { + this.currentFrame = gotFrame; + this.sprite.setFrame(this.currentFrame); + } + + } + +}); + +/** +* @name Phaser.AnimationManager#frameName +* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. +*/ +Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', { + + get: function () { + + if (this.currentFrame) + { + return this.currentFrame.name; + } + + }, + + set: function (value) { + + var gotFrame; + + if (typeof value === 'string' && this._frameData && (gotFrame = this._frameData.getFrameByName(value))) + { + this.currentFrame = gotFrame; + this._frameIndex = this.currentFrame.index; + this.sprite.setFrame(this.currentFrame); + } + else + { + console.warn('Cannot set frameName: ' + value); + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Animation instance contains a single animation and the controls to play it. +* +* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. +* +* @class Phaser.Animation +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {Phaser.Sprite} parent - A reference to the owner of this Animation. +* @param {string} name - The unique name for this animation, used in playback commands. +* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. +* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +*/ +Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) { + + if (loop === undefined) { loop = false; } + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. + * @private + */ + this._parent = parent; + + /** + * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. + * @private + */ + this._frameData = frameData; + + /** + * @property {string} name - The user defined name given to this Animation. + */ + this.name = name; + + /** + * @property {array} _frames + * @private + */ + this._frames = []; + this._frames = this._frames.concat(frames); + + /** + * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. + */ + this.delay = 1000 / frameRate; + + /** + * @property {boolean} loop - The loop state of the Animation. + */ + this.loop = loop; + + /** + * @property {number} loopCount - The number of times the animation has looped since it was last started. + */ + this.loopCount = 0; + + /** + * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? + * @default + */ + this.killOnComplete = false; + + /** + * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. + * @default + */ + this.isFinished = false; + + /** + * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. + * @default + */ + this.isPlaying = false; + + /** + * @property {boolean} isPaused - The paused state of the Animation. + * @default + */ + this.isPaused = false; + + /** + * @property {boolean} _pauseStartTime - The time the animation paused. + * @private + * @default + */ + this._pauseStartTime = 0; + + /** + * @property {number} _frameIndex + * @private + * @default + */ + this._frameIndex = 0; + + /** + * @property {number} _frameDiff + * @private + * @default + */ + this._frameDiff = 0; + + /** + * @property {number} _frameSkip + * @private + * @default + */ + this._frameSkip = 1; + + /** + * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. + */ + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + /** + * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. + */ + this.onStart = new Phaser.Signal(); + + /** + * This event is dispatched when the Animation changes frame. + * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. + * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations + * will automatically frame-skip to try and claw back time, so do not base your code on expecting to + * receive a perfectly sequential set of frames from this event. + * @property {Phaser.Signal|null} onUpdate + * @default + */ + this.onUpdate = null; + + /** + * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {boolean} isReversed - Indicates if the animation will play backwards. + * @default + */ + this.isReversed = false; + + // Set-up some event listeners + this.game.onPause.add(this.onPause, this); + this.game.onResume.add(this.onResume, this); + +}; + +Phaser.Animation.prototype = { + + /** + * Plays this animation. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.Animation#play + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} - A reference to this Animation instance. + */ + play: function (frameRate, loop, killOnComplete) { + + if (typeof frameRate === 'number') + { + // If they set a new frame rate then use it, otherwise use the one set on creation + this.delay = 1000 / frameRate; + } + + if (typeof loop === 'boolean') + { + // If they set a new loop value then use it, otherwise use the one set on creation + this.loop = loop; + } + + if (typeof killOnComplete !== 'undefined') + { + // Remove the parent sprite once the animation has finished? + this.killOnComplete = killOnComplete; + } + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = this.isReversed ? this._frames.length - 1 : 0; + this.updateCurrentFrame(false, true); + + this._parent.events.onAnimationStart$dispatch(this._parent, this); + + this.onStart.dispatch(this._parent, this); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + return this; + + }, + + /** + * Sets this animation back to the first frame and restarts the animation. + * + * @method Phaser.Animation#restart + */ + restart: function () { + + this.isPlaying = true; + this.isFinished = false; + this.paused = false; + this.loopCount = 0; + + this._timeLastFrame = this.game.time.time; + this._timeNextFrame = this.game.time.time + this.delay; + + this._frameIndex = 0; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + this._parent.setFrame(this.currentFrame); + + this._parent.animations.currentAnim = this; + this._parent.animations.currentFrame = this.currentFrame; + + this.onStart.dispatch(this._parent, this); + + }, + + /** + * Reverses the animation direction. + * + * @method Phaser.Animation#reverse + * @return {Phaser.Animation} The animation instance. + */ + reverse: function () { + + this.reversed = !this.reversed; + + return this; + + }, + + /** + * Reverses the animation direction for the current/next animation only + * Once the onComplete event is called this method will be called again and revert + * the reversed state. + * + * @method Phaser.Animation#reverseOnce + * @return {Phaser.Animation} The animation instance. + */ + reverseOnce: function () { + + this.onComplete.addOnce(this.reverse, this); + + return this.reverse(); + + }, + + /** + * Sets this animations playback to a given frame with the given ID. + * + * @method Phaser.Animation#setFrame + * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. + * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. + */ + setFrame: function(frameId, useLocalFrameIndex) { + + var frameIndex; + + if (useLocalFrameIndex === undefined) + { + useLocalFrameIndex = false; + } + + // Find the index to the desired frame. + if (typeof frameId === "string") + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frameData.getFrame(this._frames[i]).name === frameId) + { + frameIndex = i; + } + } + } + else if (typeof frameId === "number") + { + if (useLocalFrameIndex) + { + frameIndex = frameId; + } + else + { + for (var i = 0; i < this._frames.length; i++) + { + if (this._frames[i] === frameId) + { + frameIndex = i; + } + } + } + } + + if (frameIndex) + { + // Set the current frame index to the found index. Subtract a directional offset so that it animates to the desired frame on update. + var directionalOffset = this.isReversed ? -1 : 1; + this._frameIndex = frameIndex - directionalOffset; + + // Make the animation update at next update + this._timeNextFrame = this.game.time.time; + + this.update(); + } + + }, + + /** + * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. + * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. + * + * @method Phaser.Animation#stop + * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. + * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? + */ + stop: function (resetFrame, dispatchComplete) { + + if (resetFrame === undefined) { resetFrame = false; } + if (dispatchComplete === undefined) { dispatchComplete = false; } + + this.isPlaying = false; + this.isFinished = true; + this.paused = false; + + if (resetFrame) + { + this.currentFrame = this._frameData.getFrame(this._frames[0]); + this._parent.setFrame(this.currentFrame); + } + + if (dispatchComplete) + { + this._parent.events.onAnimationComplete$dispatch(this._parent, this); + this.onComplete.dispatch(this._parent, this); + } + + }, + + /** + * Called when the Game enters a paused state. + * + * @method Phaser.Animation#onPause + */ + onPause: function () { + + if (this.isPlaying) + { + this._frameDiff = this._timeNextFrame - this.game.time.time; + } + + }, + + /** + * Called when the Game resumes from a paused state. + * + * @method Phaser.Animation#onResume + */ + onResume: function () { + + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this._frameDiff; + } + + }, + + /** + * Updates this animation. Called automatically by the AnimationManager. + * + * @method Phaser.Animation#update + */ + update: function () { + + if (this.isPaused) + { + return false; + } + + if (this.isPlaying && this.game.time.time >= this._timeNextFrame) + { + this._frameSkip = 1; + + // Lagging? + this._frameDiff = this.game.time.time - this._timeNextFrame; + + this._timeLastFrame = this.game.time.time; + + if (this._frameDiff > this.delay) + { + // We need to skip a frame, work out how many + this._frameSkip = Math.floor(this._frameDiff / this.delay); + this._frameDiff -= (this._frameSkip * this.delay); + } + else + { + this._frameDiff = 0; + } + + // And what's left now? + this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff); + + if (this.isReversed) + { + this._frameIndex -= this._frameSkip; + } + else + { + this._frameIndex += this._frameSkip; + } + + if (!this.isReversed && this._frameIndex >= this._frames.length || this.isReversed && this._frameIndex <= -1) + { + if (this.loop) + { + // Update current state before event callback + this._frameIndex = Math.abs(this._frameIndex) % this._frames.length; + + if (this.isReversed) + { + this._frameIndex = this._frames.length - 1 - this._frameIndex; + } + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + // Instead of calling updateCurrentFrame we do it here instead + if (this.currentFrame) + { + this._parent.setFrame(this.currentFrame); + } + + this.loopCount++; + this._parent.events.onAnimationLoop$dispatch(this._parent, this); + this.onLoop.dispatch(this._parent, this); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + } + else + { + this.complete(); + return false; + } + } + else + { + return this.updateCurrentFrame(true); + } + } + + return false; + + }, + + /** + * Changes the currentFrame per the _frameIndex, updates the display state, + * and triggers the update signal. + * + * Returns true if the current frame update was 'successful', false otherwise. + * + * @method Phaser.Animation#updateCurrentFrame + * @private + * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. + * @param {boolean} fromPlay - Was this call made from the playing of a new animation? + * @return {boolean} True if the current frame was updated, otherwise false. + */ + updateCurrentFrame: function (signalUpdate, fromPlay) { + + if (fromPlay === undefined) { fromPlay = false; } + + if (!this._frameData) + { + // The animation is already destroyed, probably from a callback + return false; + } + + // Previous index + var idx = this.currentFrame.index; + + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index))) + { + this._parent.setFrame(this.currentFrame); + } + + if (this.onUpdate && signalUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + + // False if the animation was destroyed from within a callback + return !!this._frameData; + } + else + { + return true; + } + + }, + + /** + * Advances by the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#next + * @param {number} [quantity=1] - The number of frames to advance. + */ + next: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex + quantity; + + if (frame >= this._frames.length) + { + if (this.loop) + { + frame %= this._frames.length; + } + else + { + frame = this._frames.length - 1; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ + previous: function (quantity) { + + if (quantity === undefined) { quantity = 1; } + + var frame = this._frameIndex - quantity; + + if (frame < 0) + { + if (this.loop) + { + frame = this._frames.length + frame; + } + else + { + frame++; + } + } + + if (frame !== this._frameIndex) + { + this._frameIndex = frame; + this.updateCurrentFrame(true); + } + + }, + + /** + * Changes the FrameData object this Animation is using. + * + * @method Phaser.Animation#updateFrameData + * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. + */ + updateFrameData: function (frameData) { + + this._frameData = frameData; + this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null; + + }, + + /** + * Cleans up this animation ready for deletion. Nulls all values and references. + * + * @method Phaser.Animation#destroy + */ + destroy: function () { + + if (!this._frameData) + { + // Already destroyed + return; + } + + 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(); + + if (this.onUpdate) + { + this.onUpdate.dispose(); + } + + }, + + /** + * Called internally when the animation finishes playback. + * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. + * + * @method Phaser.Animation#complete + */ + complete: function () { + + this._frameIndex = this._frames.length - 1; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + + 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; + +/** +* @name Phaser.Animation#paused +* @property {boolean} paused - Gets and sets the paused state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'paused', { + + get: function () { + + return this.isPaused; + + }, + + set: function (value) { + + this.isPaused = value; + + if (value) + { + // Paused + this._pauseStartTime = this.game.time.time; + } + else + { + // Un-paused + if (this.isPlaying) + { + this._timeNextFrame = this.game.time.time + this.delay; + } + } + + } + +}); + +/** +* @name Phaser.Animation#reversed +* @property {boolean} reversed - Gets and sets the isReversed state of this Animation. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'reversed', { + + get: function () { + + return this.isReversed; + + }, + + set: function (value) { + + this.isReversed = value; + + } + +}); + +/** +* @name Phaser.Animation#frameTotal +* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. +* @readonly +*/ +Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @name Phaser.Animation#frame +* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. +*/ +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.setFrame(this.currentFrame); + + if (this.onUpdate) + { + this.onUpdate.dispatch(this, this.currentFrame); + } + } + + } + +}); + +/** +* @name Phaser.Animation#speed +* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'speed', { + + get: function () { + + return 1000 / this.delay; + + }, + + set: function (value) { + + if (value > 0) + { + this.delay = 1000 / value; + } + + } + +}); + +/** +* @name Phaser.Animation#enableUpdate +* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. +*/ +Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { + + get: function () { + + return (this.onUpdate !== null); + + }, + + set: function (value) { + + if (value && this.onUpdate === null) + { + this.onUpdate = new Phaser.Signal(); + } + else if (!value && this.onUpdate !== null) + { + this.onUpdate.dispose(); + this.onUpdate = null; + } + + } + +}); + +/** +* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. +* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' +* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); +* +* @method Phaser.Animation.generateFrameNames +* @static +* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. +* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. +* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. +* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'. +* @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. +* @return {string[]} An array of framenames. +*/ +Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { + + if (suffix === undefined) { suffix = ''; } + + var output = []; + var frame = ''; + + if (start < stop) + { + for (var i = start; i <= stop; i++) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + else + { + for (var i = start; i >= stop; i--) + { + if (typeof zeroPad === 'number') + { + // str, len, pad, dir + frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); + } + else + { + frame = i.toString(); + } + + frame = prefix + frame + suffix; + + output.push(frame); + } + } + + return output; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Frame is a single frame of an animation and is part of a FrameData collection. +* +* @class Phaser.Frame +* @constructor +* @param {number} index - The index of this Frame within the FrameData set it is being added to. +* @param {number} x - X position of the frame within the texture image. +* @param {number} y - Y position of the frame within the texture image. +* @param {number} width - Width of the frame within the texture image. +* @param {number} height - Height of the frame within the texture image. +* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. +*/ +Phaser.Frame = function (index, x, y, width, height, name) { + + /** + * @property {number} index - The index of this Frame within the FrameData set it is being added to. + */ + this.index = index; + + /** + * @property {number} x - X position within the image to cut from. + */ + this.x = x; + + /** + * @property {number} y - Y position within the image to cut from. + */ + this.y = y; + + /** + * @property {number} width - Width of the frame. + */ + this.width = width; + + /** + * @property {number} height - Height of the frame. + */ + this.height = height; + + if (this.width === 0 || this.height === 0) + { + console.warn('Phaser.Frame: Frame "' + this.name + '" has a width or height of zero'); + } + + /** + * @property {string} name - Useful for Texture Atlas files (is set to the filename value). + */ + this.name = name; + + /** + * @property {number} centerX - Center X position within the image to cut from. + */ + this.centerX = Math.floor(width / 2); + + /** + * @property {number} centerY - Center Y position within the image to cut from. + */ + this.centerY = Math.floor(height / 2); + + /** + * @property {number} distance - The distance from the top left to the bottom-right of this Frame. + */ + this.distance = Phaser.Math.distance(0, 0, width, height); + + /** + * @property {boolean} rotated - Is the frame rotated in the source texture? + * @default + */ + this.rotated = false; + + /** + * @property {boolean} trimmed - Was it trimmed when packed? + * @default + */ + this.trimmed = false; + + /** + * @property {number} sourceSizeW - Width of the original sprite before it was trimmed. + */ + this.sourceSizeW = width; + + /** + * @property {number} sourceSizeH - Height of the original sprite before it was trimmed. + */ + this.sourceSizeH = height; + + /** + * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeX = 0; + + /** + * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. + * @default + */ + this.spriteSourceSizeY = 0; + + /** + * @property {number} spriteSourceSizeW - Width of the trimmed sprite. + * @default + */ + this.spriteSourceSizeW = 0; + + /** + * @property {number} spriteSourceSizeH - Height of the trimmed sprite. + * @default + */ + this.spriteSourceSizeH = 0; + + /** + * @property {number} right - The right of the Frame (x + width). + */ + this.right = this.x + this.width; + + /** + * @property {number} bottom - The bottom of the frame (y + height). + */ + this.bottom = this.y + this.height; + +}; + +Phaser.Frame.prototype = { + + /** + * Adjusts of all the Frame properties based on the given width and height values. + * + * @method Phaser.Frame#resize + * @param {integer} width - The new width of the Frame. + * @param {integer} height - The new height of the Frame. + */ + resize: function (width, height) { + + this.width = width; + this.height = height; + this.centerX = Math.floor(width / 2); + this.centerY = Math.floor(height / 2); + this.distance = Phaser.Math.distance(0, 0, width, height); + this.sourceSizeW = width; + this.sourceSizeH = height; + this.right = this.x + width; + this.bottom = this.y + height; + + }, + + /** + * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. + * + * @method Phaser.Frame#setTrim + * @param {boolean} trimmed - If this frame was trimmed or not. + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + */ + setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { + + this.trimmed = trimmed; + + if (trimmed) + { + 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; + } + + }, + + /** + * Clones this Frame into a new Phaser.Frame object and returns it. + * Note that all properties are cloned, including the name and index. + * + * @method Phaser.Frame#clone + * @return {Phaser.Frame} An exact copy of this Frame object. + */ + clone: function () { + + var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name); + + for (var prop in this) + { + if (this.hasOwnProperty(prop)) + { + output[prop] = this[prop]; + } + } + + return output; + + }, + + /** + * Returns a Rectangle set to the dimensions of this Frame. + * + * @method Phaser.Frame#getRect + * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to. + * @return {Phaser.Rectangle} A rectangle. + */ + getRect: function (out) { + + if (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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. +* +* @class Phaser.FrameData +* @constructor +*/ +Phaser.FrameData = function () { + + /** + * @property {Array} _frames - Local array of frames. + * @private + */ + this._frames = []; + + /** + * @property {Array} _frameNames - Local array of frame names for name to index conversions. + * @private + */ + this._frameNames = []; + +}; + +Phaser.FrameData.prototype = { + + /** + * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. + * + * @method Phaser.FrameData#addFrame + * @param {Phaser.Frame} frame - The frame to add to this FrameData set. + * @return {Phaser.Frame} The frame that was just added. + */ + addFrame: function (frame) { + + frame.index = this._frames.length; + + this._frames.push(frame); + + if (frame.name !== '') + { + this._frameNames[frame.name] = frame.index; + } + + return frame; + + }, + + /** + * Get a Frame by its numerical index. + * + * @method Phaser.FrameData#getFrame + * @param {number} index - The index of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or undefined. + */ + getFrame: function (index) { + + if (index >= this._frames.length) + { + index = 0; + } + + return this._frames[index]; + + }, + + /** + * Get a Frame by its frame name. + * + * @method Phaser.FrameData#getFrameByName + * @param {string} name - The name of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or null. + */ + getFrameByName: function (name) { + + if (typeof this._frameNames[name] === 'number') + { + return this._frames[this._frameNames[name]]; + } + + return null; + + }, + + /** + * Check if there is a Frame with the given name. + * + * @method Phaser.FrameData#checkFrameName + * @param {string} name - The name of the frame you want to check. + * @return {boolean} True if the frame is found, otherwise false. + */ + checkFrameName: function (name) { + + if (this._frameNames[name] == null) + { + return false; + } + + return true; + + }, + + /** + * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains. + * + * @method Phaser.FrameData#clone + * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains. + */ + clone: function () { + + var output = new Phaser.FrameData(); + + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output._frames.push(this._frames[i].clone()); + } + + for (var p in this._frameNames) + { + if (this._frameNames.hasOwnProperty(p)) + { + output._frameNames.push(this._frameNames[p]); + } + } + + return output; + + }, + + /** + * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. + * + * @method Phaser.FrameData#getFrameRange + * @param {number} start - The starting frame index. + * @param {number} end - The ending frame index. + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. + */ + getFrameRange: function (start, end, output) { + + if (output === undefined) { output = []; } + + for (var i = start; i <= end; i++) + { + output.push(this._frames[i]); + } + + return output; + + }, + + /** + * Returns all of the Frames in this FrameData set where the frame index is found in the input array. + * The frames are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrames + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. + */ + getFrames: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No input array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + // We only need the indexes + output.push(this._frames[i]); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the input array contain names or indexes? + if (useNumericIndex) + { + // The actual frame + output.push(this.getFrame(frames[i])); + } + else + { + // The actual frame + output.push(this.getFrameByName(frames[i])); + } + } + } + + return output; + + }, + + /** + * Returns all of the Frame indexes in this FrameData set. + * The frames indexes are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrameIndexes + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frame indexes matching the given names or IDs. + */ + getFrameIndexes: function (frames, useNumericIndex, output) { + + if (useNumericIndex === undefined) { useNumericIndex = true; } + if (output === undefined) { output = []; } + + if (frames === undefined || frames.length === 0) + { + // No frames array, so we loop through all frames + for (var i = 0; i < this._frames.length; i++) + { + output.push(this._frames[i].index); + } + } + else + { + // Input array given, loop through that instead + for (var i = 0; i < frames.length; i++) + { + // Does the frames array contain names or indexes? + if (useNumericIndex && this._frames[frames[i]]) + { + output.push(this._frames[frames[i]].index); + } + else + { + if (this.getFrameByName(frames[i])) + { + output.push(this.getFrameByName(frames[i]).index); + } + } + } + } + + return output; + + }, + + /** + * Destroys this FrameData collection by nulling the _frames and _frameNames arrays. + * + * @method Phaser.FrameData#destroy + */ + destroy: function () { + + this._frames = null; + this._frameNames = null; + + } + +}; + +Phaser.FrameData.prototype.constructor = Phaser.FrameData; + +/** +* @name Phaser.FrameData#total +* @property {number} total - The total number of frames in this FrameData set. +* @readonly +*/ +Object.defineProperty(Phaser.FrameData.prototype, "total", { + + get: function () { + return this._frames.length; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +* +* @class Phaser.AnimationParser +* @static +*/ +Phaser.AnimationParser = { + + /** + * Parse a Sprite Sheet and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.spriteSheet + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. + * @param {number} frameWidth - The fixed width of each frame of the animation. + * @param {number} frameHeight - The fixed height of each frame of the animation. + * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + var img = key; + + if (typeof key === 'string') + { + img = game.cache.getImage(key); + } + + if (img === null) + { + return null; + } + + var width = img.width; + var height = img.height; + + if (frameWidth <= 0) + { + frameWidth = Math.floor(-width / Math.min(-1, frameWidth)); + } + + if (frameHeight <= 0) + { + frameHeight = Math.floor(-height / Math.min(-1, frameHeight)); + } + + var row = Math.floor((width - margin) / (frameWidth + spacing)); + var column = Math.floor((height - margin) / (frameHeight + spacing)); + var total = row * column; + + if (skipFrames > total || skipFrames < -total) + { + console.warn( + "Phaser.AnimationParser.spriteSheet: skipFrames = " + + skipFrames.toString() + " is larger than total sprite number " + + total.toString()); + return null; + } + + if (skipFrames < 0) + { + // Allow negative skipframes. + skipFrames = total + skipFrames; + } + + if (frameMax !== -1) + { + total = skipFrames + frameMax; + } + + // Zero or smaller than frame sizes? + if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0) + { + console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight"); + return null; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var x = margin; + var y = margin; + + for (var i = 0; i < total; i++) + { + data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '')); + + x += frameWidth + spacing; + + if (x + frameWidth > width) + { + x = margin; + y += frameHeight + spacing; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONData: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].frame.x, + frames[i].frame.y, + frames[i].frame.w, + frames[i].frame.h, + frames[i].filename + )); + + if (frames[i].trimmed) + { + newFrame.setTrim( + frames[i].trimmed, + frames[i].sourceSize.w, + frames[i].sourceSize.h, + frames[i].spriteSourceSize.x, + frames[i].spriteSourceSize.y, + frames[i].spriteSourceSize.w, + frames[i].spriteSourceSize.h + ); + } + + if (frames[i].rotated) + { + newFrame.rotated = true; + } + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataPyxel + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataPyxel: function (game, json) { + + // Malformed? There are a few keys to check here. + var signature = ['layers', 'tilewidth','tileheight','tileswide', 'tileshigh']; + + signature.forEach( function(key) { + if (!json[key]) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "' + key + '" key.'); + console.log(json); + return; + } + }); + + // For this purpose, I only care about parsing tilemaps with a single layer. + if (json['layers'].length !== 1) + { + console.warn('Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps.'); + console.log(json); + return; + } + + var data = new Phaser.FrameData(); + + var tileheight = json['tileheight']; + var tilewidth = json['tilewidth']; + + var frames = json['layers'][0]['tiles']; + var newFrame; + + for (var i = 0; i < frames.length; i++) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[i].x, + frames[i].y, + tilewidth, + tileheight, + "frame_" + i // No names are included in pyxel tilemap data. + )); + + // No trim data is included. + newFrame.setTrim(false); + } + + return data; + + }, + + /** + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataHash + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + JSONDataHash: function (game, json) { + + // Malformed? + if (!json['frames']) + { + console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"); + console.log(json); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + + // By this stage frames is a fully parsed array + var frames = json['frames']; + var newFrame; + var i = 0; + + for (var key in frames) + { + newFrame = data.addFrame(new Phaser.Frame( + i, + frames[key].frame.x, + frames[key].frame.y, + frames[key].frame.w, + frames[key].frame.h, + key + )); + + if (frames[key].trimmed) + { + newFrame.setTrim( + frames[key].trimmed, + frames[key].sourceSize.w, + frames[key].sourceSize.h, + frames[key].spriteSourceSize.x, + frames[key].spriteSourceSize.y, + frames[key].spriteSourceSize.w, + frames[key].spriteSourceSize.h + ); + } + + if (frames[key].rotated) + { + newFrame.rotated = true; + } + + i++; + } + + return data; + + }, + + /** + * Parse the XML data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.XMLData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ + XMLData: function (game, xml) { + + // Malformed? + if (!xml.getElementsByTagName('TextureAtlas')) + { + console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing tag"); + return; + } + + // Let's create some frames then + var data = new Phaser.FrameData(); + var frames = xml.getElementsByTagName('SubTexture'); + var newFrame; + + var name; + var frame; + var x; + var y; + var width; + var height; + var frameX; + var frameY; + var frameWidth; + var frameHeight; + + for (var i = 0; i < frames.length; i++) + { + frame = frames[i].attributes; + + name = frame.name.value; + x = parseInt(frame.x.value, 10); + y = parseInt(frame.y.value, 10); + width = parseInt(frame.width.value, 10); + height = parseInt(frame.height.value, 10); + + frameX = null; + frameY = null; + + if (frame.frameX) + { + frameX = Math.abs(parseInt(frame.frameX.value, 10)); + frameY = Math.abs(parseInt(frame.frameY.value, 10)); + frameWidth = parseInt(frame.frameWidth.value, 10); + frameHeight = parseInt(frame.frameHeight.value, 10); + } + + newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name)); + + // Trimmed? + if (frameX !== null || frameY !== null) + { + newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight); + } + } + + return data; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser has one single cache in which it stores all assets. +* +* The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using +* a unique string-based key as their identifier. Assets stored in different areas of the cache can have the +* same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, +* because they are unique data types. +* +* The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets +* such as images they are automatically placed into their respective cache. Most common Game Objects, such as +* Sprites and Videos automatically query the cache to extract the assets they need on instantiation. +* +* You can access the cache from within a State via `this.cache`. From here you can call any public method it has, +* including adding new entries to it, deleting them or querying them. +* +* Understand that almost without exception when you get an item from the cache it will return a reference to the +* item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original +* object in the cache will also be updated, even if you don't put it back into the cache again. +* +* By default when you change State the cache is _not_ cleared, although there is an option to clear it should +* your game require it. In a typical game set-up the cache is populated once after the main game has loaded and +* then used as an asset store. +* +* @class Phaser.Cache +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Cache = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. + * @property {boolean} autoResolveURL + */ + this.autoResolveURL = false; + + /** + * The main cache object into which all resources are placed. + * @property {object} _cache + * @private + */ + this._cache = { + canvas: {}, + image: {}, + texture: {}, + sound: {}, + video: {}, + text: {}, + json: {}, + xml: {}, + physics: {}, + tilemap: {}, + binary: {}, + bitmapData: {}, + bitmapFont: {}, + shader: {}, + renderTexture: {}, + compressedTexture: {} + }; + + /** + * @property {object} _urlMap - Maps URLs to resources. + * @private + */ + this._urlMap = {}; + + /** + * @property {Image} _urlResolver - Used to resolve URLs to the absolute path. + * @private + */ + this._urlResolver = new Image(); + + /** + * @property {string} _urlTemp - Temporary variable to hold a resolved url. + * @private + */ + this._urlTemp = null; + + /** + * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices. + */ + this.onSoundUnlock = new Phaser.Signal(); + + /** + * @property {array} _cacheMap - Const to cache object look-up array. + * @private + */ + this._cacheMap = []; + + this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas; + this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image; + this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture; + this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound; + this._cacheMap[Phaser.Cache.TEXT] = this._cache.text; + this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics; + this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap; + this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary; + this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData; + this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont; + this._cacheMap[Phaser.Cache.JSON] = this._cache.json; + this._cacheMap[Phaser.Cache.XML] = this._cache.xml; + this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video; + this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader; + this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture; + + /** + * @property {number} + * @private + */ + this._pendingCount = 0; + + /** + * Dispatched when the DEFAULT and MISSING images have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). + * + * @property {Phaser.Signal} onReady + */ + this.onReady = new Phaser.Signal(); + + this._addImages(); + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.CANVAS = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.IMAGE = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXTURE = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SOUND = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TEXT = 5; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.PHYSICS = 6; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.TILEMAP = 7; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BINARY = 8; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPDATA = 9; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.BITMAPFONT = 10; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.JSON = 11; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.XML = 12; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.VIDEO = 13; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.SHADER = 14; + +/** +* @constant +* @type {number} +*/ +Phaser.Cache.RENDER_TEXTURE = 15; + +/** +* The default image used for a texture when no other is specified. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.DEFAULT = null; + +/** + * Key for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_KEY = '__default'; + +/** + * URL for the DEFAULT texture. + * @constant + * @type {string} + */ +Phaser.Cache.DEFAULT_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='; + +/** +* The default image used for a texture when the source image is missing. +* @constant +* @type {PIXI.Texture} +*/ +Phaser.Cache.MISSING = null; + +/** + * Key for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_KEY = '__missing'; + +/** + * URL for the MISSING texture. + * @constant + * @type {string} + */ +Phaser.Cache.MISSING_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='; + +/** +* The maximum amount of time (ms) to wait for the built-in DEFAULT and MISSING images to load. +* @static +* @type {number} +* @default +*/ +Phaser.Cache.READY_TIMEOUT = 1000; + +Phaser.Cache.prototype = { + + ////////////////// + // Add Methods // + ////////////////// + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCompressedTextureMetaData + * @private + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url + * @param {string} extension + * @param {array} arrayBuffer + * @return {object} The compressed texture entry. + */ + addCompressedTextureMetaData: function (key, url, extension, arrayBuffer) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + var data = (extension in Phaser.LoaderParser) ? Phaser.LoaderParser[extension](arrayBuffer) : arrayBuffer; + + var texture = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData(), + fileFormat: extension + }; + + texture.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = texture; + + this._resolveURL(url, texture); + + return texture; + + }, + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCanvas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {HTMLCanvasElement} canvas - The Canvas DOM element. + * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`. + */ + addCanvas: function (key, canvas, context) { + + if (context === undefined) { context = canvas.getContext('2d'); } + + this._cache.canvas[key] = { canvas: canvas, context: context }; + + }, + + /** + * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. + * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. + * + * If the image has not yet been fetched (successfully or not), a `console.warn` message will be displayed. + * + * @method Phaser.Cache#addImage + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra image data. + * @return {object} The full image object that was added to the cache. + */ + addImage: function (key, url, data) { + + if (this.checkImageKey(key)) + { + this.removeImage(key); + } + + if (data.complete === false) + { + console.warn('Phaser.Cache.addImage: Image "' + key + '" hasn\'t been retrieved yet'); + } + + var img = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key), + frameData: new Phaser.FrameData() + }; + + img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url)); + + this._cache.image[key] = img; + + this._resolveURL(url, img); + + if (key === '__default') + { + Phaser.Cache.DEFAULT = new PIXI.Texture(img.base); + } + else if (key === '__missing') + { + Phaser.Cache.MISSING = new PIXI.Texture(img.base); + } + + return img; + + }, + + /** + * @method Phaser.Cache#addImageAsync + * @private + */ + addImageAsync: function (key, src, callback) { + + var self = this; + var img = new Image(); + + img.onload = function () { + callback.call(this, self.addImage(key, null, img)); + self._removePending(); + img.onload = null; + }; + + this._addPending(); + img.src = src; + + }, + + /** + * Adds a default image to be used in special cases such as WebGL Filters. + * It uses the special reserved key of `__default`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addDefaultImage + * @protected + */ + addDefaultImage: function () { + + this.addImageAsync(Phaser.Cache.DEFAULT_KEY, Phaser.Cache.DEFAULT_SRC, function (obj) { + // Because we don't want to invalidate the sprite batch for an invisible texture + obj.base.skipRender = true; + + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.DEFAULT = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds an image to be used when a key is wrong / missing. + * It uses the special reserved key of `__missing`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addMissingImage + * @protected + */ + addMissingImage: function () { + + this.addImageAsync(Phaser.Cache.MISSING_KEY, Phaser.Cache.MISSING_SRC, function (obj) { + // Make it easily available within the rest of Phaser / Pixi + Phaser.Cache.MISSING = new PIXI.Texture(obj.base); + }); + + }, + + /** + * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addSound + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sound data. + * @param {boolean} webAudio - True if the file is using web audio. + * @param {boolean} audioTag - True if the file is using legacy HTML audio. + */ + addSound: function (key, url, data, webAudio, audioTag) { + + if (webAudio === undefined) { webAudio = true; audioTag = false; } + if (audioTag === undefined) { webAudio = false; audioTag = true; } + + var decoded = false; + + if (audioTag) + { + decoded = true; + } + + this._cache.sound[key] = { + url: url, + data: data, + isDecoding: false, + decoded: decoded, + webAudio: webAudio, + audioTag: audioTag, + locked: this.game.sound.touchLocked + }; + + this._resolveURL(url, this._cache.sound[key]); + + }, + + /** + * Add a new text data. + * + * @method Phaser.Cache#addText + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addText: function (key, url, data) { + + this._cache.text[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.text[key]); + + }, + + /** + * Add a new physics data object to the Cache. + * + * @method Phaser.Cache#addPhysicsData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} JSONData - The physics data object (a JSON file). + * @param {number} format - The format of the physics data. + */ + addPhysicsData: function (key, url, JSONData, format) { + + this._cache.physics[key] = { url: url, data: JSONData, format: format }; + + this._resolveURL(url, this._cache.physics[key]); + + }, + + /** + * Add a new tilemap to the Cache. + * + * @method Phaser.Cache#addTilemap + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} mapData - The tilemap data object (either a CSV or JSON file). + * @param {number} format - The format of the tilemap data. + */ + addTilemap: function (key, url, mapData, format) { + + this._cache.tilemap[key] = { url: url, data: mapData, format: format }; + + this._resolveURL(url, this._cache.tilemap[key]); + + }, + + /** + * Add a binary object in to the cache. + * + * @method Phaser.Cache#addBinary + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {object} binaryData - The binary object to be added to the cache. + */ + addBinary: function (key, binaryData) { + + this._cache.binary[key] = binaryData; + + }, + + /** + * Add a BitmapData object to the cache. + * + * @method Phaser.Cache#addBitmapData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. + * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. + * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. + */ + addBitmapData: function (key, bitmapData, frameData) { + + bitmapData.key = key; + + if (frameData === undefined) + { + frameData = new Phaser.FrameData(); + frameData.addFrame(bitmapData.textureFrame); + } + + this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData }; + + return bitmapData; + + }, + + /** + * Add a new Bitmap Font to the Cache. + * + * @method Phaser.Cache#addBitmapFont + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra font data. + * @param {object} atlasData - The Bitmap Font data. + * @param {string} [atlasType='xml'] - The format of the Bitmap Font data file: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) { + + var obj = { + url: url, + data: data, + font: null, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + if (atlasType === 'json') + { + obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + else + { + obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing, false, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new Bitmap Font to the Cache, where the font texture is part of a Texture Atlas. + * + * The atlas must already exist in the cache, and be available based on the given `atlasKey`. + * + * The `atlasFrame` specifies the name of the frame within the atlas that the Bitmap Font is + * stored in. + * + * The `dataKey` is the key of the XML or JSON Bitmap Font Data, which must already be in + * the Cache. + * + * @method Phaser.Cache#addBitmapFontFromAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} atlasKey - The key of the Texture Atlas in the Cache. + * @param {string} atlasFrame - The frame of the Texture Atlas that the Bitmap Font is in. + * @param {string} dataKey - The key of the Bitmap Font data in the Cache + * @param {string} [dataType='xml'] - The format of the Bitmap Font data: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ + addBitmapFontFromAtlas: function (key, atlasKey, atlasFrame, dataKey, dataType, xSpacing, ySpacing) { + + var frame = this.getFrameByName(atlasKey, atlasFrame); + + if (!frame) + { + return; + } + + var obj = { + font: null, + base: this.getBaseTexture(atlasKey), + frame: frame + }; + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + var fontData; + + if (dataType === 'json') + { + fontData = this.getJSON(dataKey); + obj.font = Phaser.LoaderParser.jsonBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + else + { + fontData = this.getXML(dataKey); + obj.font = Phaser.LoaderParser.xmlBitmapFont(fontData, obj.base, xSpacing, ySpacing, frame, this.game.resolution); + } + + this._cache.bitmapFont[key] = obj; + + }, + + /** + * Add a new json object into the cache. + * + * @method Phaser.Cache#addJSON + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra json data. + */ + addJSON: function (key, url, data) { + + this._cache.json[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.json[key]); + + }, + + /** + * Add a new xml object into the cache. + * + * @method Phaser.Cache#addXML + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ + addXML: function (key, url, data) { + + this._cache.xml[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.xml[key]); + + }, + + /** + * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addVideo + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra video data. + * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. + */ + addVideo: function (key, url, data, isBlob) { + + this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true }; + + this._resolveURL(url, this._cache.video[key]); + + }, + + /** + * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addShader + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra shader data. + */ + addShader: function (key, url, data) { + + this._cache.shader[key] = { url: url, data: data }; + + this._resolveURL(url, this._cache.shader[key]); + + }, + + /** + * Add a new Phaser.RenderTexture in to the cache. + * + * @method Phaser.Cache#addRenderTexture + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture. + */ + addRenderTexture: function (key, texture) { + + this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') }; + + }, + + /** + * Add a new sprite sheet in to the cache. + * + * @method Phaser.Cache#addSpriteSheet + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sprite sheet data. + * @param {number} frameWidth - Width of the sprite sheet. + * @param {number} frameHeight - Height of the sprite sheet. + * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + */ + addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + var obj = { + key: key, + url: url, + data: data, + frameWidth: frameWidth, + frameHeight: frameHeight, + margin: margin, + spacing: spacing, + base: new PIXI.BaseTexture(data, null, this.game.resolution), + frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) + }; + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + /** + * Add a new texture atlas to the Cache. + * + * @method Phaser.Cache#addTextureAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra texture atlas data. + * @param {object} atlasData - Texture atlas frames data. + * @param {number} format - The format of the texture atlas. + */ + addTextureAtlas: function (key, url, data, atlasData, format) { + + var obj = { + key: key, + url: url, + data: data, + base: new PIXI.BaseTexture(data, null, this.game.resolution) + }; + + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key); + } + else if (format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + obj.frameData = Phaser.AnimationParser.JSONDataPyxel(this.game, atlasData, key); + } + else + { + // Let's just work it out from the frames array + if (Array.isArray(atlasData.frames)) + { + obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key); + } + else + { + obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key); + } + } + + this._cache.image[key] = obj; + + this._resolveURL(url, obj); + + }, + + //////////////////////////// + // Sound Related Methods // + //////////////////////////// + + /** + * Reload a Sound file from the server. + * + * @method Phaser.Cache#reloadSound + * @param {string} key - The key of the asset within the cache. + */ + reloadSound: function (key) { + + var _this = this; + + var sound = this.getSound(key); + + if (sound) + { + sound.data.src = sound.url; + + sound.data.addEventListener('canplaythrough', function () { + return _this.reloadSoundComplete(key); + }, false); + + sound.data.load(); + } + + }, + + /** + * Fires the onSoundUnlock event when the sound has completed reloading. + * + * @method Phaser.Cache#reloadSoundComplete + * @param {string} key - The key of the asset within the cache. + */ + reloadSoundComplete: function (key) { + + var sound = this.getSound(key); + + if (sound) + { + sound.locked = false; + this.onSoundUnlock.dispatch(key); + } + + }, + + /** + * Updates the sound object in the cache. + * + * @method Phaser.Cache#updateSound + * @param {string} key - The key of the asset within the cache. + */ + updateSound: function (key, property, value) { + + var sound = this.getSound(key); + + if (sound) + { + sound[property] = value; + } + + }, + + /** + * Add a new decoded sound. + * + * @method Phaser.Cache#decodedSound + * @param {string} key - The key of the asset within the cache. + * @param {object} data - Extra sound data. + */ + decodedSound: function (key, data) { + + var sound = this.getSound(key); + + sound.data = data; + sound.decoded = true; + sound.isDecoding = false; + + }, + + /** + * Check if the given sound has finished decoding. + * + * @method Phaser.Cache#isSoundDecoded + * @param {string} key - The key of the asset within the cache. + * @return {boolean} The decoded state of the Sound object. + */ + isSoundDecoded: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return sound.decoded; + } + + }, + + /** + * Check if the given sound is ready for playback. + * A sound is considered ready when it has finished decoding and the device is no longer touch locked. + * + * @method Phaser.Cache#isSoundReady + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the sound is decoded and the device is not touch locked. + */ + isSoundReady: function (key) { + + var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); + + if (sound) + { + return (sound.decoded && !this.game.sound.touchLocked); + } + + }, + + //////////////////////// + // Check Key Methods // + //////////////////////// + + /** + * Checks if a key for the given cache object type exists. + * + * @method Phaser.Cache#checkKey + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists, otherwise false. + */ + checkKey: function (cache, key) { + + if (this._cacheMap[cache][key]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given URL has been loaded into the Cache. + * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. + * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox + * which may cause double-load instances. + * + * @method Phaser.Cache#checkURL + * @param {string} url - The url to check for in the cache. + * @return {boolean} True if the url exists, otherwise false. + */ + checkURL: function (url) { + + if (this._urlMap[this._resolveURL(url)]) + { + return true; + } + + return false; + + }, + + /** + * Checks if the given key exists in the Canvas Cache. + * + * @method Phaser.Cache#checkCanvasKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkCanvasKey: function (key) { + + return this.checkKey(Phaser.Cache.CANVAS, key); + + }, + + /** + * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. + * + * @method Phaser.Cache#checkImageKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkImageKey: function (key) { + + return this.checkKey(Phaser.Cache.IMAGE, key); + + }, + + /** + * Checks if the given key exists in the Texture Cache. + * + * @method Phaser.Cache#checkTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXTURE, key); + + }, + + /** + * Checks if the given key exists in the Sound Cache. + * + * @method Phaser.Cache#checkSoundKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkSoundKey: function (key) { + + return this.checkKey(Phaser.Cache.SOUND, key); + + }, + + /** + * Checks if the given key exists in the Text Cache. + * + * @method Phaser.Cache#checkTextKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTextKey: function (key) { + + return this.checkKey(Phaser.Cache.TEXT, key); + + }, + + /** + * Checks if the given key exists in the Physics Cache. + * + * @method Phaser.Cache#checkPhysicsKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkPhysicsKey: function (key) { + + return this.checkKey(Phaser.Cache.PHYSICS, key); + + }, + + /** + * Checks if the given key exists in the Tilemap Cache. + * + * @method Phaser.Cache#checkTilemapKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkTilemapKey: function (key) { + + return this.checkKey(Phaser.Cache.TILEMAP, key); + + }, + + /** + * Checks if the given key exists in the Binary Cache. + * + * @method Phaser.Cache#checkBinaryKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBinaryKey: function (key) { + + return this.checkKey(Phaser.Cache.BINARY, key); + + }, + + /** + * Checks if the given key exists in the BitmapData Cache. + * + * @method Phaser.Cache#checkBitmapDataKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapDataKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPDATA, key); + + }, + + /** + * Checks if the given key exists in the BitmapFont Cache. + * + * @method Phaser.Cache#checkBitmapFontKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkBitmapFontKey: function (key) { + + return this.checkKey(Phaser.Cache.BITMAPFONT, key); + + }, + + /** + * Checks if the given key exists in the JSON Cache. + * + * @method Phaser.Cache#checkJSONKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkJSONKey: function (key) { + + return this.checkKey(Phaser.Cache.JSON, key); + + }, + + /** + * Checks if the given key exists in the XML Cache. + * + * @method Phaser.Cache#checkXMLKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkXMLKey: function (key) { + + return this.checkKey(Phaser.Cache.XML, key); + + }, + + /** + * Checks if the given key exists in the Video Cache. + * + * @method Phaser.Cache#checkVideoKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkVideoKey: function (key) { + + return this.checkKey(Phaser.Cache.VIDEO, key); + + }, + + /** + * Checks if the given key exists in the Fragment Shader Cache. + * + * @method Phaser.Cache#checkShaderKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkShaderKey: function (key) { + + return this.checkKey(Phaser.Cache.SHADER, key); + + }, + + /** + * Checks if the given key exists in the Render Texture Cache. + * + * @method Phaser.Cache#checkRenderTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ + checkRenderTextureKey: function (key) { + + return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key); + + }, + + //////////////// + // Get Items // + //////////////// + + /** + * Get an item from a cache based on the given key and property. + * + * This method is mostly used internally by other Cache methods such as `getImage` but is exposed + * publicly for your own use as well. + * + * @method Phaser.Cache#getItem + * @param {string} key - The key of the asset within the cache. + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output. + * @param {string} [property] - If you require a specific property from the cache item, specify it here. + * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. + */ + getItem: function (key, cache, method, property) { + + if (!this.checkKey(cache, key)) + { + if (method) + { + console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.'); + } + } + else + { + if (property === undefined) + { + return this._cacheMap[cache][key]; + } + else + { + return this._cacheMap[cache][key][property]; + } + } + + return null; + + }, + + /** + * Gets a Canvas object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getCanvas + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The canvas object or `null` if no item could be found matching the given key. + */ + getCanvas: function (key) { + + return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas'); + + }, + + /** + * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. + * + * If you need the image used by a bitmap font or similar then please use those respective 'get' methods. + * + * @method Phaser.Cache#getImage + * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. + * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned. + * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. + */ + getImage: function (key, full) { + + if (key === undefined || key === null) + { + key = '__default'; + } + + if (full === undefined) { full = false; } + + var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage'); + + if (img === null) + { + img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage'); + } + + if (full) + { + return img; + } + else + { + return img.data; + } + + }, + + /** + * Get a single texture frame by key. + * + * You'd only do this to get the default Frame created for a non-atlas / spritesheet image. + * + * @method Phaser.Cache#getTextureFrame + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Frame} The frame data. + */ + getTextureFrame: function (key) { + + return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame'); + + }, + + /** + * Gets a Phaser.Sound object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSound + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Sound} The sound object. + */ + getSound: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSound'); + + }, + + /** + * Gets a raw Sound data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSoundData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The sound data. + */ + getSoundData: function (key) { + + return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data'); + + }, + + /** + * Gets a Text object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getText + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The text data. + */ + getText: function (key) { + + return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data'); + + }, + + /** + * Gets a Physics Data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can get either the entire data set, a single object or a single fixture of an object from it. + * + * @method Phaser.Cache#getPhysicsData + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all. + * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. + * @return {object} The requested physics object data if found. + */ + getPhysicsData: function (key, object, fixtureKey) { + + var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data'); + + if (data === null || object === undefined || object === null) + { + return data; + } + else + { + if (data[object]) + { + var fixtures = data[object]; + + // Try to find a fixture by its fixture key if given + if (fixtures && fixtureKey) + { + for (var fixture in fixtures) + { + // This contains the fixture data of a polygon or a circle + fixture = fixtures[fixture]; + + // Test the key + if (fixture.fixtureKey === fixtureKey) + { + return fixture; + } + } + + // We did not find the requested fixture + console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"'); + } + else + { + return fixtures; + } + } + else + { + console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"'); + } + } + + return null; + + }, + + /** + * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getTilemapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The raw tilemap data in CSV or JSON format. + */ + getTilemapData: function (key) { + + return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData'); + + }, + + /** + * Gets a binary object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBinary + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The binary data object. + */ + getBinary: function (key) { + + return this.getItem(key, Phaser.Cache.BINARY, 'getBinary'); + + }, + + /** + * Gets a BitmapData object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. + */ + getBitmapData: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data'); + + }, + + /** + * Gets a Bitmap Font object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapFont + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not. + */ + getBitmapFont: function (key) { + + return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont'); + + }, + + /** + * Gets a JSON object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can either return the object by reference (the default), or return a clone + * of it by setting the `clone` argument to `true`. + * + * @method Phaser.Cache#getJSON + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false) + * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. + */ + getJSON: function (key, clone) { + + var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data'); + + if (data) + { + if (clone) + { + return Phaser.Utils.extend(true, Array.isArray(data) ? [] : {}, data); + } + else + { + return data; + } + } + else + { + return null; + } + + }, + + /** + * Gets an XML object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getXML + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The XML object. + */ + getXML: function (key) { + + return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data'); + + }, + + /** + * Gets a Phaser.Video object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getVideo + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Video} The video object. + */ + getVideo: function (key) { + + return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo'); + + }, + + /** + * Gets a fragment shader object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getShader + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {string} The shader object. + */ + getShader: function (key) { + + return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data'); + + }, + + /** + * Gets a RenderTexture object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getRenderTexture + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame. + */ + getRenderTexture: function (key) { + + return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture'); + + }, + + //////////////////////////// + // Frame Related Methods // + //////////////////////////// + + /** + * Gets a PIXI.BaseTexture by key from the given Cache. + * + * @method Phaser.Cache#getBaseTexture + * @param {string} key - Asset key of the image for which you want the BaseTexture for. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {PIXI.BaseTexture} The BaseTexture object. + */ + getBaseTexture: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getBaseTexture', 'base'); + + }, + + /** + * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. + * + * @method Phaser.Cache#getFrame + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.Frame} The frame data. + */ + getFrame: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrame', 'frame'); + + }, + + /** + * Get the total number of frames contained in the FrameData object specified by the given key. + * + * @method Phaser.Cache#getFrameCount + * @param {string} key - Asset key of the FrameData you want. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {number} Then number of frames. 0 if the image is not found. + */ + getFrameCount: function (key, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.total; + } + else + { + return 0; + } + + }, + + /** + * Gets a Phaser.FrameData object from the Image Cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.FrameData} The frame data. + */ + getFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return this.getItem(key, cache, 'getFrameData', 'frameData'); + + }, + + /** + * Check if the FrameData for the given key exists in the Image Cache. + * + * @method Phaser.Cache#hasFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {boolean} True if the given key has frameData in the cache, otherwise false. + */ + hasFrameData: function (key, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + return (this.getItem(key, cache, '', 'frameData') !== null); + + }, + + /** + * Replaces a set of frameData with a new Phaser.FrameData object. + * + * @method Phaser.Cache#updateFrameData + * @param {string} key - The unique key by which you will reference this object. + * @param {number} frameData - The new FrameData. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + */ + updateFrameData: function (key, frameData, cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + if (this._cacheMap[cache][key]) + { + this._cacheMap[cache][key].frameData = frameData; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByIndex + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {number} index - The index of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByIndex: function (key, index, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrame(index); + } + else + { + return null; + } + + }, + + /** + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByName + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {string} name - The name of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ + getFrameByName: function (key, name, cache) { + + var data = this.getFrameData(key, cache); + + if (data) + { + return data.getFrameByName(name); + } + else + { + return null; + } + + }, + + /** + * Get a cached object by the URL. + * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. + * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. + * + * @method Phaser.Cache#getURL + * @param {string} url - The url for the object loaded to get from the cache. + * @return {object} The cached object. + */ + getURL: function (url) { + + var url = this._resolveURL(url); + + if (url) + { + return this._urlMap[url]; + } + else + { + console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false'); + return null; + } + + }, + + /** + * Gets all keys used in the requested Cache. + * + * @method Phaser.Cache#getKeys + * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. + * @return {Array} The array of keys in the requested cache. + */ + getKeys: function (cache) { + + if (cache === undefined) { cache = Phaser.Cache.IMAGE; } + + var out = []; + + if (this._cacheMap[cache]) + { + for (var key in this._cacheMap[cache]) + { + if (key !== '__default' && key !== '__missing') + { + out.push(key); + } + } + } + + return out; + + }, + + ///////////////////// + // Remove Methods // + ///////////////////// + + /** + * Removes a canvas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeCanvas + * @param {string} key - Key of the asset you want to remove. + */ + removeCanvas: function (key) { + + delete this._cache.canvas[key]; + + }, + + /** + * Removes an image from the cache. + * + * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. + * + * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeImage + * @param {string} key - Key of the asset you want to remove. + * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed? + */ + removeImage: function (key, destroyBaseTexture) { + + if (destroyBaseTexture === undefined) { destroyBaseTexture = true; } + + var img = this.getImage(key, true); + + if (destroyBaseTexture && img.base) + { + img.base.destroy(); + } + + delete this._cache.image[key]; + + }, + + /** + * Removes a sound from the cache. + * + * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will + * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then + * you must finish your house-keeping and destroy them all yourself first, before calling this method. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSound + * @param {string} key - Key of the asset you want to remove. + */ + removeSound: function (key) { + + delete this._cache.sound[key]; + + }, + + /** + * Removes a text file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeText + * @param {string} key - Key of the asset you want to remove. + */ + removeText: function (key) { + + delete this._cache.text[key]; + + }, + + /** + * Removes a physics data file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removePhysics + * @param {string} key - Key of the asset you want to remove. + */ + removePhysics: function (key) { + + delete this._cache.physics[key]; + + }, + + /** + * Removes a tilemap from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTilemap + * @param {string} key - Key of the asset you want to remove. + */ + removeTilemap: function (key) { + + delete this._cache.tilemap[key]; + + }, + + /** + * Removes a binary file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBinary + * @param {string} key - Key of the asset you want to remove. + */ + removeBinary: function (key) { + + delete this._cache.binary[key]; + + }, + + /** + * Removes a bitmap data from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapData + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapData: function (key) { + + delete this._cache.bitmapData[key]; + + }, + + /** + * Removes a bitmap font from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapFont + * @param {string} key - Key of the asset you want to remove. + */ + removeBitmapFont: function (key) { + + delete this._cache.bitmapFont[key]; + + }, + + /** + * Removes a json object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeJSON + * @param {string} key - Key of the asset you want to remove. + */ + removeJSON: function (key) { + + delete this._cache.json[key]; + + }, + + /** + * Removes a xml object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeXML + * @param {string} key - Key of the asset you want to remove. + */ + removeXML: function (key) { + + delete this._cache.xml[key]; + + }, + + /** + * Removes a video from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeVideo + * @param {string} key - Key of the asset you want to remove. + */ + removeVideo: function (key) { + + delete this._cache.video[key]; + + }, + + /** + * Removes a shader from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeShader + * @param {string} key - Key of the asset you want to remove. + */ + removeShader: function (key) { + + delete this._cache.shader[key]; + + }, + + /** + * Removes a Render Texture from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeRenderTexture + * @param {string} key - Key of the asset you want to remove. + */ + removeRenderTexture: function (key) { + + delete this._cache.renderTexture[key]; + + }, + + /** + * Removes a Sprite Sheet from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSpriteSheet + * @param {string} key - Key of the asset you want to remove. + */ + removeSpriteSheet: function (key) { + + delete this._cache.spriteSheet[key]; + + }, + + /** + * Removes a Texture Atlas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTextureAtlas + * @param {string} key - Key of the asset you want to remove. + */ + removeTextureAtlas: function (key) { + + delete this._cache.image[key]; + + }, + + /** + * Empties out all of the GL Textures from Images stored in the cache. + * This is called automatically when the WebGL context is lost and then restored. + * + * @method Phaser.Cache#clearGLTextures + * @protected + */ + clearGLTextures: function () { + + for (var key in this._cache.image) + { + this._cache.image[key].base._glTextures = []; + } + + }, + + /** + * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`. + * This is then looked-up by the Cache.getURL and Cache.checkURL calls. + * + * @method Phaser.Cache#_resolveURL + * @private + * @param {string} url - The URL to resolve. This is appended to Loader.baseURL. + * @param {object} [data] - The data associated with the URL to be stored to the URL Map. + * @return {string} The resolved URL. + */ + _resolveURL: function (url, data) { + + if (!this.autoResolveURL) + { + return null; + } + + this._urlResolver.src = this.game.load.baseURL + url; + + this._urlTemp = this._urlResolver.src; + + // Ensure no request is actually made + this._urlResolver.src = ''; + + // Record the URL to the map + if (data) + { + this._urlMap[this._urlTemp] = data; + } + + return this._urlTemp; + + }, + + /** + * Clears the cache. Removes every local cache object reference. + * If an object in the cache has a `destroy` method it will be called; + * otherwise, `destroy` will be called on any of the object's `base`, `data`, + * `frameData`, or `texture` properties. + * + * @method Phaser.Cache#destroy + */ + destroy: function () { + + for (var i = 0; i < this._cacheMap.length; i++) + { + var cache = this._cacheMap[i]; + + for (var key in cache) + { + if (key !== '__default' && key !== '__missing') + { + this.destroyItem(cache[key]); + + delete cache[key]; + } + } + } + + this._urlMap = null; + this._urlResolver = null; + this._urlTemp = null; + + }, + + /** + * @method Phaser.Cache#destroyItem + * @protected + * @param {object} item + */ + destroyItem: function (item) { + + if (item.destroy) + { + item.destroy(); + } + else + { + if (item.base && item.base.destroy) + { + item.base.destroy(); + } + + if (item.data && item.data.destroy) + { + item.data.destroy(); + } + + if (item.frameData && item.frameData.destroy) + { + item.frameData.destroy(); + } + + if (item.texture && item.texture.destroy) + { + item.texture.destroy(true); + } + } + + }, + + /** + * Starts loading the DEFAULT and MISSING images. + * + * @private + */ + _addImages: function () { + + this._pendingCount = 0; + + this.addDefaultImage(); + this.addMissingImage(); + + var self = this; + var readyTimeout = Phaser.Cache.READY_TIMEOUT; + + if (Phaser.Cache.READY_TIMEOUT > 0) + { + setTimeout(function () { + if (!self.isReady) + { + console.warn('Phaser.Cache: Still waiting for images after %s ms.', readyTimeout); + + self._ready(); + } + }, Phaser.Cache.READY_TIMEOUT); + } + else + { + this._ready(); + } + + }, + + + /** + * Increments the pending count. + * + * @private + */ + _addPending: function () { + + this._pendingCount += 1; + + }, + + + /** + * Decrements the pending count and checks if complete. + * + * @private + */ + _removePending: function () { + + this._pendingCount -= 1; + this._checkReady(); + + }, + + + /** + * Calls {@link #_ready} if no pending items remain. + * + * @private + */ + _checkReady: function () { + + if (this.isReady) + { + this._ready(); + } + + }, + + + /** + * Resets pending count and triggers {@link #onReady}. + * + * @private + */ + _ready: function () { + + this._pendingCount = 0; + this.onReady.dispatch(this); + + } + +}; + +Phaser.Cache.prototype.constructor = Phaser.Cache; + +/** +* The DEFAULT and MISSING textures have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). +* +* @property {boolean} Phaser.Cache#isReady +*/ +Object.defineProperty(Phaser.Cache.prototype, 'isReady', { + get: function () { + return this._pendingCount <= 0; + } +}); + +/* jshint wsh:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* +* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. +* +* Parallel loading (see {@link #enableParallel}) is supported and enabled by default. +* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}. +* +* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and +* [Shoebox](http://renderhjs.net/shoebox/) +* +* @class Phaser.Loader +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Loader = function (game) { + + /** + * Local reference to game. + * @property {Phaser.Game} game + * @protected + */ + this.game = game; + + /** + * Local reference to the Phaser.Cache. + * @property {Phaser.Cache} cache + * @protected + */ + this.cache = game.cache; + + /** + * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. + * @property {boolean} resetLocked + * @default + */ + this.resetLocked = false; + + /** + * True if the Loader is in the process of loading the queue. + * @property {boolean} isLoading + * @default + */ + this.isLoading = false; + + /** + * True if all assets in the queue have finished loading. + * @property {boolean} hasLoaded + * @default + */ + this.hasLoaded = false; + + /** + * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}. + * + * This property is an object containing: sprite, rect, direction, width and height + * + * @property {?object} preloadSprite + * @protected + */ + this.preloadSprite = null; + + /** + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * @property {boolean|string} crossOrigin + * @default + */ + this.crossOrigin = false; + + /** + * If you want to append a URL before the path of any asset you can set this here. + * Useful if allowing the asset base url to be configured outside of the game code. + * The string _must_ end with a "/". + * + * @property {string} baseURL + */ + this.baseURL = ''; + + /** + * The value of `path`, if set, is placed before any _relative_ file path given. For example: + * + * ```javascript + * load.path = "images/sprites/"; + * load.image("ball", "ball.png"); + * load.image("tree", "level1/oaktree.png"); + * load.image("boom", "http://server.com/explode.png"); + * ``` + * + * Would load the `ball` file from `images/sprites/ball.png` and the tree from + * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL + * given as it's an absolute URL. + * + * Please note that the path is added before the filename but *after* the baseURL (if set.) + * + * The string _must_ end with a "/". + * + * @property {string} path + */ + this.path = ''; + + /** + * Used to map the application mime-types to to the Accept header in XHR requests. + * If you don't require these mappings, or they cause problems on your server, then + * remove them from the headers object and the XHR request will not try to use them. + * + * This object can also be used to set the `X-Requested-With` header to + * `XMLHttpRequest` (or any other value you need). To enable this do: + * + * ```javascript + * this.load.headers.requestedWith = 'XMLHttpRequest' + * ``` + * + * before adding anything to the Loader. The XHR loader will then call: + * + * ```javascript + * setRequestHeader('X-Requested-With', this.headers['requestedWith']) + * ``` + * + * @property {object} headers + * @default + */ + this.headers = { + "requestedWith": false, + "json": "application/json", + "xml": "application/xml" + }; + + /** + * This event is dispatched when the loading process starts: before the first file has been requested, + * but after all the initial packs have been loaded. + * + * @property {Phaser.Signal} onLoadStart + */ + this.onLoadStart = new Phaser.Signal(); + + /** + * This event is dispatched when the final file in the load queue has either loaded or failed. + * + * @property {Phaser.Signal} onLoadComplete + */ + this.onLoadComplete = new Phaser.Signal(); + + /** + * This event is dispatched when an asset pack has either loaded or failed to load. + * + * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. + * + * Params: `(pack key, success?, total packs loaded, total packs)` + * + * @property {Phaser.Signal} onPackComplete + */ + this.onPackComplete = new Phaser.Signal(); + + /** + * This event is dispatched immediately before a file starts loading. + * It's possible the file may fail (eg. download error, invalid format) after this event is sent. + * + * Params: `(progress, file key, file url)` + * + * @property {Phaser.Signal} onFileStart + */ + this.onFileStart = new Phaser.Signal(); + + /** + * This event is dispatched when a file has either loaded or failed to load. + * + * Any function bound to this will receive the following parameters: + * + * progress, file key, success?, total loaded files, total files + * + * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. + * + * @property {Phaser.Signal} onFileComplete + */ + this.onFileComplete = new Phaser.Signal(); + + /** + * This event is dispatched when a file (or pack) errors as a result of the load request. + * + * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. + * + * Params: `(file key, file)` + * + * @property {Phaser.Signal} onFileError + */ + this.onFileError = new Phaser.Signal(); + + /** + * If true (the default) then parallel downloading will be enabled. + * + * To disable all parallel downloads this must be set to false prior to any resource being loaded. + * + * @property {boolean} enableParallel + */ + this.enableParallel = true; + + /** + * The number of concurrent / parallel resources to try and fetch at once. + * + * Many current browsers limit 6 requests per domain; this is slightly conservative. + * + * This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently. + * + * @property {integer} maxParallelDownloads + */ + this.maxParallelDownloads = 4; + + /** + * A counter: if more than zero, files will be automatically added as a synchronization point. + * @property {integer} _withSyncPointDepth; + */ + this._withSyncPointDepth = 0; + + /** + * Contains all the information for asset files (including packs) to load. + * + * File/assets are only removed from the list after all loading completes. + * + * @property {file[]} _fileList + * @private + */ + this._fileList = []; + + /** + * Inflight files (or packs) that are being fetched/processed. + * + * This means that if there are any files in the flight queue there should still be processing + * going on; it should only be empty before or after loading. + * + * The files in the queue may have additional properties added to them, + * including `requestObject` which is normally the associated XHR. + * + * @property {file[]} _flightQueue + * @private + */ + this._flightQueue = []; + + /** + * The offset into the fileList past all the complete (loaded or error) entries. + * + * @property {integer} _processingHead + * @private + */ + this._processingHead = 0; + + /** + * True when the first file (not pack) has loading started. + * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded. + * + * @property {boolean} _initialPacksLoaded + * @private + */ + this._fileLoadStarted = false; + + /** + * Total packs seen - adjusted when a pack is added. + * @property {integer} _totalPackCount + * @private + */ + this._totalPackCount = 0; + + /** + * Total files seen - adjusted when a file is added. + * @property {integer} _totalFileCount + * @private + */ + this._totalFileCount = 0; + + /** + * Total packs loaded - adjusted just prior to `onPackComplete`. + * @property {integer} _loadedPackCount + * @private + */ + this._loadedPackCount = 0; + + /** + * Total files loaded - adjusted just prior to `onFileComplete`. + * @property {integer} _loadedFileCount + * @private + */ + this._loadedFileCount = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.PHYSICS_PHASER_JSON = 4; + +/** +* @constant +* @type {number} +*/ +Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5; + +Phaser.Loader.prototype = { + + /** + * Set a Sprite to be a "preload" sprite by passing it to this method. + * + * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. + * This allows you to easily make loading bars for games. + * + * The sprite will automatically be made visible when calling this. + * + * @method Phaser.Loader#setPreloadSprite + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load. + * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. + */ + setPreloadSprite: function (sprite, direction) { + + direction = direction || 0; + + this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null }; + + if (direction === 0) + { + // Horizontal rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height); + } + else + { + // Vertical rect + this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1); + } + + sprite.crop(this.preloadSprite.rect); + + sprite.visible = true; + + }, + + /** + * Called automatically by ScaleManager when the game resizes in RESIZE scalemode. + * + * This can be used to adjust the preloading sprite size, eg. + * + * @method Phaser.Loader#resize + * @protected + */ + resize: function () { + + if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height) + { + this.preloadSprite.rect.height = this.preloadSprite.sprite.height; + } + + }, + + /** + * Check whether a file/asset with a specific key is queued to be loaded. + * + * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey} + * + * @method Phaser.Loader#checkKeyExists + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ + checkKeyExists: function (type, key) { + + return this.getAssetIndex(type, key) > -1; + + }, + + /** + * Get the queue-index of the file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAssetIndex + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {number} The index of this key in the filelist, or -1 if not found. + * The index may change and should only be used immediately following this call + */ + getAssetIndex: function (type, key) { + + var bestFound = -1; + + for (var i = 0; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + if (file.type === type && file.key === key) + { + bestFound = i; + + // An already loaded/loading file may be superceded. + if (!file.loaded && !file.loading) + { + break; + } + } + } + + return bestFound; + + }, + + /** + * Find a file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAsset + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. + * The index may change and should only be used immediately following this call. + */ + getAsset: function (type, key) { + + var fileIndex = this.getAssetIndex(type, key); + + if (fileIndex > -1) + { + return { index: fileIndex, file: this._fileList[fileIndex] }; + } + + return false; + + }, + + /** + * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. + * + * This will abort any loading and clear any queued assets. + * + * Optionally you can clear any associated events. + * + * @method Phaser.Loader#reset + * @protected + * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared. + * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them. + */ + reset: function (hard, clearEvents) { + + if (clearEvents === undefined) { clearEvents = false; } + + if (this.resetLocked) + { + return; + } + + if (hard) + { + this.preloadSprite = null; + } + + this.isLoading = false; + + this._processingHead = 0; + this._fileList.length = 0; + this._flightQueue.length = 0; + + this._fileLoadStarted = false; + this._totalFileCount = 0; + this._totalPackCount = 0; + this._loadedPackCount = 0; + this._loadedFileCount = 0; + + if (clearEvents) + { + this.onLoadStart.removeAll(); + this.onLoadComplete.removeAll(); + this.onPackComplete.removeAll(); + this.onFileStart.removeAll(); + this.onFileComplete.removeAll(); + this.onFileError.removeAll(); + } + + }, + + /** + * Internal function that adds a new entry to the file list. Do not call directly. + * + * @method Phaser.Loader#addToFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} [url] - The URL the asset will be loaded from. + * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. + * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. + * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. + * @return {Phaser.Loader} This instance of the Phaser Loader. + */ + addToFileList: function (type, key, url, properties, overwrite, extension) { + + if (overwrite === undefined) { overwrite = false; } + + if (key === undefined || key === '') + { + console.warn("Phaser.Loader: Invalid or no key given of type " + type); + return this; + } + + if (url === undefined || url === null) + { + if (extension) + { + url = key + extension; + } + else + { + console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key); + return this; + } + } + + var file = { + type: type, + key: key, + path: this.path, + url: url, + syncPoint: this._withSyncPointDepth > 0, + data: null, + loading: false, + loaded: false, + error: false + }; + + if (properties) + { + for (var prop in properties) + { + file[prop] = properties[prop]; + } + } + + var fileIndex = this.getAssetIndex(type, key); + + if (overwrite && fileIndex > -1) + { + var currentFile = this._fileList[fileIndex]; + + if (!currentFile.loading && !currentFile.loaded) + { + this._fileList[fileIndex] = file; + } + else + { + this._fileList.push(file); + this._totalFileCount++; + } + } + else if (fileIndex === -1) + { + this._fileList.push(file); + this._totalFileCount++; + } + + return this; + + }, + + /** + * Internal function that replaces an existing entry in the file list with a new one. Do not call directly. + * + * @method Phaser.Loader#replaceInFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} url - The URL the asset will be loaded from. + * @param {object} properties - Any additional properties needed to load the file. + */ + replaceInFileList: function (type, key, url, properties) { + + return this.addToFileList(type, key, url, properties, true); + + }, + + /** + * Add a JSON resource pack ('packfile') to the Loader. + * + * A packfile is a JSON file that contains a list of assets to the be loaded. + * Please see the example 'loader/asset pack' in the Phaser Examples repository. + * + * Packs are always put before the first non-pack file that is not loaded / loading. + * + * This means that all packs added before any loading has started are added to the front + * of the file queue, in the order added. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#pack + * @param {string} key - Unique asset key of this resource pack. + * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. + * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO + * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. + * @return {Phaser.Loader} This Loader instance. + */ + pack: function (key, url, data, callbackContext) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (callbackContext === undefined) { callbackContext = null; } + + if (!url && !data) + { + console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.'); + + return this; + } + + var pack = { + type: 'packfile', + key: key, + url: url, + path: this.path, + syncPoint: true, + data: null, + loading: false, + loaded: false, + error: false, + callbackContext: callbackContext + }; + + // A data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + pack.data = data || {}; + + // Already consider 'loaded' + pack.loaded = true; + } + + // Add before first non-pack/no-loaded ~ last pack from start prior to loading + // (Read one past for splice-to-end) + for (var i = 0; i < this._fileList.length + 1; i++) + { + var file = this._fileList[i]; + + if (!file || (!file.loaded && !file.loading && file.type !== 'packfile')) + { + this._fileList.splice(i, 0, pack); + this._totalPackCount++; + break; + } + } + + return this; + + }, + + /** + * Adds an Image to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * This method also supports passing in a texture object as the `url` argument. This allows you to load + * compressed textures into Phaser. You can also use `Loader.texture` to do this. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.image('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * @method Phaser.Loader#image + * @param {string} key - Unique asset key of this image file. + * @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + image: function (key, url, overwrite) { + + if (typeof url === 'object') + { + return this.texture(key, url, overwrite); + } + else + { + return this.addToFileList('image', key, url, undefined, overwrite, '.png'); + } + + }, + + /** + * Generate an image from a BitmapData object and add it to the current load queue. + * + * @method Phaser.Loader#imageFromBitmapData + * @param {string} key - Unique asset key for the generated image. + * @param {Phaser.BitmapData} bitmapData + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + imageFromBitmapData: function (key, bitmapData, overwrite) { + + return this.image(key, bitmapData.canvas.toDataURL('image/png'), overwrite); + + }, + + /** + * Generate a grid image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromGrid + * @see Phaser.Create#grid + */ + imageFromGrid: function (key, width, height, cellWidth, cellHeight, color) { + + return this.imageFromBitmapData(key, this.game.create.grid(key, width, height, cellWidth, cellHeight, color, false)); + + }, + + /** + * Generate a texture image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromTexture + * @see Phaser.Create#texture + */ + imageFromTexture: function (key, data, pixelWidth, pixelHeight, palette) { + + return this.imageFromBitmapData(key, this.game.create.texture(key, data, pixelWidth, pixelHeight, palette, false)); + + }, + + /** + * Adds a Compressed Texture Image to the current load queue. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.texture('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#texture + * @param {string} key - Unique asset key of this image file. + * @param {object} object - The texture path data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + texture: function (key, object, overwrite) { + + if (this.game.renderType === Phaser.WEBGL) + { + var compression = this.game.renderer.extensions.compression; + var exkey; + + for (exkey in object) + { + if (exkey.toUpperCase() in compression) + { + return this.addToFileList('texture', key, object[exkey], undefined, overwrite, '.pvr'); + } + } + } + + // Check if we have a truecolor texture to fallback. + // Also catches calls to this function that are from a Canvas renderer + + if (object['truecolor']) + { + this.addToFileList('image', key, object['truecolor'], undefined, overwrite, '.png'); + } + + return this; + + }, + + /** + * Adds an array of images to the current load queue. + * + * It works by passing each element of the array to the Loader.image method. + * + * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. + * + * Retrieve the images via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#images + * @param {array} keys - An array of unique asset keys of the image files. + * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. + * @return {Phaser.Loader} This Loader instance. + */ + images: function (keys, urls) { + + if (Array.isArray(urls)) + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i], urls[i]); + } + } + else + { + for (var i = 0; i < keys.length; i++) + { + this.image(keys[i]); + } + } + + return this; + + }, + + /** + * Adds a Text file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getText(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#text + * @param {string} key - Unique asset key of the text file. + * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + text: function (key, url, overwrite) { + + return this.addToFileList('text', key, url, undefined, overwrite, '.txt'); + + }, + + /** + * Adds a JSON file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#json + * @param {string} key - Unique asset key of the json file. + * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + json: function (key, url, overwrite) { + + return this.addToFileList('json', key, url, undefined, overwrite, '.json'); + + }, + + /** + * Adds a fragment shader file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getShader(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" + * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#shader + * @param {string} key - Unique asset key of the fragment file. + * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + shader: function (key, url, overwrite) { + + return this.addToFileList('shader', key, url, undefined, overwrite, '.frag'); + + }, + + /** + * Adds an XML file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getXML(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#xml + * @param {string} key - Unique asset key of the xml file. + * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ + xml: function (key, url, overwrite) { + + return this.addToFileList('xml', key, url, undefined, overwrite, '.xml'); + + }, + + /** + * Adds a JavaScript file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. + * If you do not desire this action then provide a URL. + * + * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! + * + * A callback, which will be invoked as the script tag has been created, can also be specified. + * The callback must return relevant `data`. + * + * @method Phaser.Loader#script + * @param {string} key - Unique asset key of the script file. + * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing. + * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. + * @return {Phaser.Loader} This Loader instance. + */ + script: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + if (callback !== false && callbackContext === undefined) { callbackContext = this; } + + return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js'); + + }, + + /** + * Adds a binary file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBinary(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. + * If you do not desire this action then provide a URL. + * + * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. + * When the callback is called it will be passed 2 parameters: the key of the file and the file data. + * + * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. + * + * @method Phaser.Loader#binary + * @param {string} key - Unique asset key of the binary file. + * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it. + * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context. + * @return {Phaser.Loader} This Loader instance. + */ + binary: function (key, url, callback, callbackContext) { + + if (callback === undefined) { callback = false; } + + // Why is the default callback context the ..callback? + if (callback !== false && callbackContext === undefined) { callbackContext = callback; } + + return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin'); + + }, + + /** + * Adds a Sprite Sheet to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal + * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. + * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. + * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming + * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. + * If you've got an atlas then use `Loader.atlas` instead. + * + * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#spritesheet + * @param {string} key - Unique asset key of the sheet file. + * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet. + * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.Loader} This Loader instance. + */ + spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { + + if (frameMax === undefined) { frameMax = -1; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + if (skipFrames === undefined) { skipFrames = 0; } + + return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing, skipFrames: skipFrames }, false, '.png'); + + }, + + /** + * Adds an audio file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getSound(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. + * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. + * The solution is to use a lower encoding rate such as 44100 Hz. + * + * @method Phaser.Loader#audio + * @param {string} key - Unique asset key of the audio file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp3']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audio: function (key, urls, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (autoDecode === undefined) { autoDecode = true; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); + + }, + + /** + * Adds an audio sprite file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Audio Sprites are a combination of audio files and a JSON configuration. + * + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * Retrieve the file via `Cache.getSoundData(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#audioSprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + if (this.game.sound.noAudio) + { + return this; + } + + if (jsonURL === undefined) { jsonURL = null; } + if (jsonData === undefined) { jsonData = null; } + if (autoDecode === undefined) { autoDecode = true; } + + this.audio(key, urls, autoDecode); + + if (jsonURL) + { + this.json(key + '-audioatlas', jsonURL); + } + else if (jsonData) + { + if (typeof jsonData === 'string') + { + jsonData = JSON.parse(jsonData); + } + + this.cache.addJSON(key + '-audioatlas', '', jsonData); + } + else + { + console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object'); + } + + return this; + + }, + + /** + * A legacy alias for Loader.audioSprite. Please see that method for documentation. + * + * @method Phaser.Loader#audiosprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ + audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) { + + return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode); + + }, + + /** + * Adds a video file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getVideo(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. + * + * @method Phaser.Loader#video + * @param {string} key - Unique asset key of the video file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp4']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete. + * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. + * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. + * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the + * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. + * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set. + * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. + * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. + * @return {Phaser.Loader} This Loader instance. + */ + video: function (key, urls, loadEvent, asBlob) { + + if (loadEvent === undefined) + { + if (this.game.device.firefox) + { + loadEvent = 'loadeddata'; + } + else + { + loadEvent = 'canplaythrough'; + } + } + + if (asBlob === undefined) { asBlob = false; } + + if (typeof urls === 'string') + { + urls = [urls]; + } + + return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent }); + + }, + + /** + * Adds a Tile Map data file to the current load queue. + * + * Phaser can load data in two different formats: CSV and Tiled JSON. + * + * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". + * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#tilemap + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. + * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + * @return {Phaser.Loader} This Loader instance. + */ + tilemap: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Tilemap.CSV; } + + if (!url && !data) + { + if (format === Phaser.Tilemap.CSV) + { + url = key + '.csv'; + } + else + { + url = key + '.json'; + } + } + + // A map data object has been given + if (data) + { + switch (format) + { + // A csv string or object has been given + case Phaser.Tilemap.CSV: + break; + + // A json string or object has been given + case Phaser.Tilemap.TILED_JSON: + + if (typeof data === 'string') + { + data = JSON.parse(data); + } + break; + } + + this.cache.addTilemap(key, null, data, format); + } + else + { + this.addToFileList('tilemap', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds a physics data file to the current load queue. + * + * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". + * It will always use `.json` as the extension. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#physics + * @param {string} key - Unique asset key of the physics json data. + * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. + * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data. + * @return {Phaser.Loader} This Loader instance. + */ + physics: function (key, url, data, format) { + + if (url === undefined) { url = null; } + if (data === undefined) { data = null; } + if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; } + + if (!url && !data) + { + url = key + '.json'; + } + + // A map data object has been given + if (data) + { + if (typeof data === 'string') + { + data = JSON.parse(data); + } + + this.cache.addPhysicsData(key, null, data, format); + } + else + { + this.addToFileList('physics', key, url, { format: format }); + } + + return this; + + }, + + /** + * Adds Bitmap Font files to the current load queue. + * + * To create the Bitmap Font files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `xmlData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#bitmapFont + * @param {string} key - Unique asset key of the bitmap font. + * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". + * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". + * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json). + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + * @return {Phaser.Loader} This Loader instance. + */ + bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (atlasURL === null && atlasData === null) + { + atlasURL = key + '.xml'; + } + + if (xSpacing === undefined) { xSpacing = 0; } + if (ySpacing === undefined) { ySpacing = 0; } + + // A URL to a json/xml atlas has been given + if (atlasURL) + { + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing }); + } + else + { + // A stringified xml/json atlas has been given + if (typeof atlasData === 'string') + { + var json, xml; + + try + { + json = JSON.parse(atlasData); + } + catch ( e ) + { + xml = this.parseXml(atlasData); + } + + if (!xml && !json) + { + throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given"); + } + + this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml, + atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing }); + } + } + + return this; + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONArray + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONHash + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * This call expects the atlas data to be in the Starling XML data format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasXML + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ + atlasXML: function (key, textureURL, atlasURL, atlasData) { + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + + if (!atlasURL && !atlasData) + { + atlasURL = key + '.xml'; + } + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); + + }, + + /** + * Adds a Texture Atlas file to the current load queue. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlas + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. + * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING. + * @return {Phaser.Loader} This Loader instance. + */ + atlas: function (key, textureURL, atlasURL, atlasData, format) { + + if (textureURL === undefined || textureURL === null) + { + textureURL = key + '.png'; + } + + if (atlasURL === undefined) { atlasURL = null; } + if (atlasData === undefined) { atlasData = null; } + if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } + + if (!atlasURL && !atlasData) + { + if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + atlasURL = key + '.xml'; + } + else + { + atlasURL = key + '.json'; + } + } + + // A URL to a json/xml file has been given + if (atlasURL) + { + this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); + } + else + { + switch (format) + { + // A json string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: + + if (typeof atlasData === 'string') + { + atlasData = JSON.parse(atlasData); + } + break; + + // An xml string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: + + if (typeof atlasData === 'string') + { + var xml = this.parseXml(atlasData); + + if (!xml) + { + throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); + } + + atlasData = xml; + } + break; + } + + this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); + + } + + return this; + + }, + + /** + * Add a synchronization point to the assets / files added within the supplied callback. + * + * A synchronization point denotes that an asset _must_ be completely loaded before + * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait + * for previous assets to load (unless they are sync-points). Resources, such as packs, may still + * be downloaded around sync-points, as long as they do not finalize loading. + * + * @method Phaser.Loader#withSyncPoint + * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader. + * @param {object} [callbackContext=(loader)] - Context for the callback. + * @return {Phaser.Loader} This Loader instance. + */ + withSyncPoint: function (callback, callbackContext) { + + this._withSyncPointDepth++; + + try { + callback.call(callbackContext || this, this); + } finally { + this._withSyncPointDepth--; + } + + return this; + }, + + /** + * Add a synchronization point to a specific file/asset in the load queue. + * + * This has no effect on already loaded assets. + * + * @method Phaser.Loader#addSyncPoint + * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc). + * @param {string} key - Key of the file you want to turn into a sync point. + * @return {Phaser.Loader} This Loader instance. + * @see {@link Phaser.Loader#withSyncPoint withSyncPoint} + */ + addSyncPoint: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + asset.file.syncPoint = true; + } + + return this; + }, + + /** + * Remove a file/asset from the loading queue. + * + * A file that is loaded or has started loading cannot be removed. + * + * @method Phaser.Loader#removeFile + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - Key of the file you want to remove. + */ + removeFile: function (type, key) { + + var asset = this.getAsset(type, key); + + if (asset) + { + if (!asset.loaded && !asset.loading) + { + this._fileList.splice(asset.index, 1); + } + } + + }, + + /** + * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead. + * + * @method Phaser.Loader#removeAll + * @protected + */ + removeAll: function () { + + this._fileList.length = 0; + this._flightQueue.length = 0; + + }, + + /** + * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. + * + * @method Phaser.Loader#start + */ + start: function () { + + if (this.isLoading) + { + return; + } + + this.hasLoaded = false; + this.isLoading = true; + + this.updateProgress(); + + this.processLoadQueue(); + + }, + + /** + * Process the next item(s) in the file/asset queue. + * + * Process the queue and start loading enough items to fill up the inflight queue. + * + * If a sync-file is encountered then subsequent asset processing is delayed until it completes. + * The exception to this rule is that packfiles can be downloaded (but not processed) even if + * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel. + * such as during the start phaser. + * + * @method Phaser.Loader#processLoadQueue + * @private + */ + processLoadQueue: function () { + + if (!this.isLoading) + { + console.warn('Phaser.Loader - active loading canceled / reset'); + this.finishedLoading(true); + return; + } + + // Empty the flight queue as applicable + for (var i = 0; i < this._flightQueue.length; i++) + { + var file = this._flightQueue[i]; + + if (file.loaded || file.error) + { + this._flightQueue.splice(i, 1); + i--; + + file.loading = false; + file.requestUrl = null; + file.requestObject = null; + + if (file.error) + { + this.onFileError.dispatch(file.key, file); + } + + if (file.type !== 'packfile') + { + this._loadedFileCount++; + this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount); + } + else if (file.type === 'packfile' && file.error) + { + // Non-error pack files are handled when processing the file queue + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + } + } + + // When true further non-pack file downloads are suppressed + var syncblock = false; + + var inflightLimit = this.enableParallel ? Math.max(1, this.maxParallelDownloads) : 1; + + for (var i = this._processingHead; i < this._fileList.length; i++) + { + var file = this._fileList[i]; + + // Pack is fetched (ie. has data) and is currently at the start of the process queue. + if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead) + { + // Processing the pack / adds more files + this.processPack(file); + + this._loadedPackCount++; + this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); + } + + if (file.loaded || file.error) + { + // Item at the start of file list finished, can skip it in future + if (i === this._processingHead) + { + this._processingHead = i + 1; + } + } + else if (!file.loading && this._flightQueue.length < inflightLimit) + { + // -> not loaded/failed, not loading + if (file.type === 'packfile' && !file.data) + { + // Fetches the pack data: the pack is processed above as it reaches queue-start. + // (Packs do not trigger onLoadStart or onFileStart.) + this._flightQueue.push(file); + file.loading = true; + + this.loadFile(file); + } + else if (!syncblock) + { + if (!this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this._flightQueue.push(file); + file.loading = true; + this.onFileStart.dispatch(this.progress, file.key, file.url); + + this.loadFile(file); + } + } + + if (!file.loaded && file.syncPoint) + { + syncblock = true; + } + + // Stop looking if queue full - or if syncblocked and there are no more packs. + // (As only packs can be loaded around a syncblock) + if (this._flightQueue.length >= inflightLimit || + (syncblock && this._loadedPackCount === this._totalPackCount)) + { + break; + } + } + + this.updateProgress(); + + // True when all items in the queue have been advanced over + // (There should be no inflight items as they are complete - loaded/error.) + if (this._processingHead >= this._fileList.length) + { + this.finishedLoading(); + } + else if (!this._flightQueue.length) + { + // Flight queue is empty but file list is not done being processed. + // This indicates a critical internal error with no known recovery. + console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled"); + + var _this = this; + + setTimeout(function () { + _this.finishedLoading(true); + }, 2000); + } + + }, + + /** + * The loading is all finished. + * + * @method Phaser.Loader#finishedLoading + * @private + * @param {boolean} [abnormal=true] - True if the loading finished abnormally. + */ + finishedLoading: function (abnormal) { + + if (this.hasLoaded) + { + return; + } + + this.hasLoaded = true; + this.isLoading = false; + + // If there were no files make sure to trigger the event anyway, for consistency + if (!abnormal && !this._fileLoadStarted) + { + this._fileLoadStarted = true; + this.onLoadStart.dispatch(); + } + + this.reset(); + + this.onLoadComplete.dispatch(); + + // Check if the state still exists since destroy could have occurred while loading + if (this.game.state) + { + this.game.state.loadComplete(); + } + + }, + + /** + * Informs the loader that the given file resource has been fetched and processed; + * or such a request has failed. + * + * @method Phaser.Loader#asyncComplete + * @private + * @param {object} file + * @param {string} [error=''] - The error message, if any. No message implies no error. + */ + asyncComplete: function (file, errorMessage) { + + if (errorMessage === undefined) { errorMessage = ''; } + + file.loaded = true; + file.error = !!errorMessage; + + if (errorMessage) + { + file.errorMessage = errorMessage; + + console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage); + } + + this.processLoadQueue(); + + }, + + /** + * Process pack data. This will usually modify the file list. + * + * @method Phaser.Loader#processPack + * @private + * @param {object} pack + */ + processPack: function (pack) { + + var packData = pack.data[pack.key]; + + if (!packData) + { + console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key'); + return; + } + + for (var i = 0; i < packData.length; i++) + { + var file = packData[i]; + + switch (file.type) + { + case "image": + this.image(file.key, file.url, file.overwrite); + break; + + case "text": + this.text(file.key, file.url, file.overwrite); + break; + + case "json": + this.json(file.key, file.url, file.overwrite); + break; + + case "xml": + this.xml(file.key, file.url, file.overwrite); + break; + + case "script": + this.script(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "binary": + this.binary(file.key, file.url, file.callback, pack.callbackContext || this); + break; + + case "spritesheet": + this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case "video": + this.video(file.key, file.urls); + break; + + case "audio": + this.audio(file.key, file.urls, file.autoDecode); + break; + + case "audiosprite": + this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode); + break; + + case "tilemap": + this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]); + break; + + case "physics": + this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]); + break; + + case "bitmapFont": + this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing); + break; + + case "atlasJSONArray": + this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasJSONHash": + this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlasXML": + this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData); + break; + + case "atlas": + this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]); + break; + + case "shader": + this.shader(file.key, file.url, file.overwrite); + break; + } + } + + }, + + /** + * Transforms the asset URL. + * + * The default implementation prepends the baseURL if the url doesn't begin with http or // + * + * @method Phaser.Loader#transformUrl + * @protected + * @param {string} url - The url to transform. + * @param {object} file - The file object being transformed. + * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead. + */ + transformUrl: function (url, file) { + + if (!url) + { + return false; + } + + if (url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) + { + return url; + } + else + { + return this.baseURL + file.path + url; + } + + }, + + /** + * Start fetching a resource. + * + * All code paths, async or otherwise, from this function must return to `asyncComplete`. + * + * @method Phaser.Loader#loadFile + * @private + * @param {object} file + */ + loadFile: function (file) { + + // Image or Data? + switch (file.type) + { + case 'packfile': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'image': + case 'spritesheet': + case 'textureatlas': + case 'bitmapfont': + this.loadImageTag(file); + break; + + case 'audio': + file.url = this.getAudioURL(file.url); + + if (file.url) + { + // WebAudio or Audio Tag? + if (this.game.sound.usingWebAudio) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + else if (this.game.sound.usingAudioTag) + { + this.loadAudioTag(file); + } + } + else + { + this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support'); + } + break; + + case 'video': + file.url = this.getVideoURL(file.url); + + if (file.url) + { + if (file.asBlob) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'blob', this.fileComplete); + } + else + { + this.loadVideoTag(file); + } + } + else + { + this.fileError(file, null, 'No supported video URL specified or device does not have video playback support'); + } + break; + + case 'json': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + break; + + case 'xml': + + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete); + break; + + case 'tilemap': + + if (file.format === Phaser.Tilemap.TILED_JSON) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Tilemap.CSV) + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete); + } + else + { + this.asyncComplete(file, "invalid Tilemap format: " + file.format); + } + break; + + case 'text': + case 'script': + case 'shader': + case 'physics': + this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete); + break; + + case 'texture': + + if (file.key.split('_').pop() === 'truecolor') + { + this.loadImageTag(file); + } + else + { + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + } + break; + + case 'binary': + this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); + break; + } + + }, + + /** + * Continue async loading through an Image tag. + * @private + */ + loadImageTag: function (file) { + var _this = this; + + file.data = new Image(); + file.data.name = file.key; + + if (this.crossOrigin) + { + file.data.crossOrigin = this.crossOrigin; + } + + file.data.onload = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileComplete(file); + } + }; + + file.data.onerror = function () { + if (file.data.onload) + { + file.data.onload = null; + file.data.onerror = null; + _this.fileError(file); + } + }; + + file.data.src = this.transformUrl(file.url, file); + + // Image is immediately-available/cached + // Special Firefox magic, exclude from cached reload + // More info here: https://github.com/photonstorm/phaser/issues/2534 + if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height) + { + file.data.onload = null; + file.data.onerror = null; + this.fileComplete(file); + } + + }, + + /** + * Continue async loading through a Video tag. + * @private + */ + loadVideoTag: function (file) { + + var _this = this; + + file.data = document.createElement("video"); + file.data.name = file.key; + file.data.controls = false; + file.data.autoplay = false; + + var videoLoadEvent = function () { + + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = true; + Phaser.GAMES[_this.game.id].load.fileComplete(file); + + }; + + file.data.onerror = function () { + file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); + file.data.onerror = null; + file.data.canplay = false; + _this.fileError(file); + }; + + file.data.addEventListener(file.loadEvent, videoLoadEvent, false); + + file.data.src = this.transformUrl(file.url, file); + file.data.load(); + + }, + + /** + * Continue async loading through an Audio tag. + * @private + */ + loadAudioTag: function (file) { + + var _this = this; + + if (this.game.sound.touchLocked) + { + // If audio is locked we can't do this yet, so need to queue this load request. Bum. + file.data = new Audio(); + file.data.name = file.key; + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + + this.fileComplete(file); + } + else + { + file.data = new Audio(); + file.data.name = file.key; + + var playThroughEvent = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileComplete(file); + }; + + file.data.onerror = function () { + file.data.removeEventListener('canplaythrough', playThroughEvent, false); + file.data.onerror = null; + _this.fileError(file); + }; + + file.data.preload = 'auto'; + file.data.src = this.transformUrl(file.url, file); + file.data.addEventListener('canplaythrough', playThroughEvent, false); + file.data.load(); + } + + }, + + /** + * Starts the xhr loader. + * + * This is designed specifically to use with asset file processing. + * + * @method Phaser.Loader#xhrLoad + * @private + * @param {object} file - The file/pack to load. + * @param {string} url - The URL of the file. + * @param {string} type - The xhr responseType. + * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments. + * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments. + */ + xhrLoad: function (file, url, type, onload, onerror) { + + var xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = type; + + if (this.headers['requestedWith'] !== false) + { + xhr.setRequestHeader('X-Requested-With', this.headers['requestedWith']); + } + + if (this.headers[file.type]) + { + xhr.setRequestHeader('Accept', this.headers[file.type]); + } + + onerror = onerror || this.fileError; + + var _this = this; + + xhr.onload = function () { + + try { + if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called. + return onerror.call(_this, file, xhr); + } + else { + return onload.call(_this, file, xhr); + } + } catch (e) { + + // If this was the last file in the queue and an error is thrown in the create method + // then it's caught here, so be sure we don't carry on processing it + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + } + }; + + xhr.onerror = function () { + + try { + + return onerror.call(_this, file, xhr); + + } catch (e) { + + if (!_this.hasLoaded) + { + _this.asyncComplete(file, e.message || 'Exception'); + } + else + { + if (window['console']) + { + console.error(e); + } + } + + } + }; + + file.requestObject = xhr; + file.requestUrl = url; + + xhr.send(); + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getVideoURL + * @private + * @param {object[]|string[]} urls - See {@link #video} for format. + * @return {string} The URL to try and fetch; or null. + */ + getVideoURL: function (urls) { + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var videoType; + + if (url.uri) // {uri: .., type: ..} pair + { + videoType = url.type; + url = url.uri; + + if (this.game.device.canPlayVideo(videoType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + videoType = extension.toLowerCase(); + + if (this.game.device.canPlayVideo(videoType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getAudioURL + * @private + * @param {object[]|string[]} urls - See {@link #audio} for format. + * @return {string} The URL to try and fetch; or null. + */ + getAudioURL: function (urls) { + + if (this.game.sound.noAudio) + { + return null; + } + + for (var i = 0; i < urls.length; i++) + { + var url = urls[i]; + var audioType; + + if (url.uri) // {uri: .., type: ..} pair + { + audioType = url.type; + url = url.uri; + + if (this.game.device.canPlayAudio(audioType)) + { + return url; + } + } + else + { + // Assume direct-data URI can be played if not in a paired form; select immediately + if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) + { + return url; + } + + if (url.indexOf("?") >= 0) // Remove query from URL + { + url = url.substr(0, url.indexOf("?")); + } + + var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1); + + audioType = extension.toLowerCase(); + + if (this.game.device.canPlayAudio(audioType)) + { + return urls[i]; + } + } + } + + return null; + + }, + + /** + * Error occurred when loading a file. + * + * @method Phaser.Loader#fileError + * @private + * @param {object} file + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + * @param {string} reason + */ + fileError: function (file, xhr, reason) { + + var url = file.requestUrl || this.transformUrl(file.url, file); + var message = 'error loading asset from URL ' + url; + + if (!reason && xhr) + { + reason = xhr.status; + } + + if (reason) + { + message = message + ' (' + reason + ')'; + } + + this.asyncComplete(file, message); + + }, + + /** + * Called when a file has been downloaded and needs to be processed further. + * + * @method Phaser.Loader#fileComplete + * @private + * @param {object} file - File loaded + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + */ + fileComplete: function (file, xhr) { + + var loadNext = true; + + switch (file.type) + { + case 'packfile': + + // Pack data must never be false-ish after it is fetched without error + var data = JSON.parse(xhr.responseText); + file.data = data || {}; + break; + + case 'texture': + + var extension = /\.([^.]+)$/.exec(file.url.split('?', 1)[0])[1].toLowerCase(); + if (file.data !== null) + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, file.data); + } + else + { + this.cache.addCompressedTextureMetaData(file.key, file.url, extension, xhr.response); + } + break; + + case 'image': + + this.cache.addImage(file.key, file.url, file.data); + break; + + case 'spritesheet': + + this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing, file.skipFrames); + break; + + case 'textureatlas': + + if (file.atlasURL == null) + { + this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); + } + else + { + // Load the JSON or XML before carrying on with the next file + loadNext = false; + + if (file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_HASH || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete); + } + else if (file.format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete); + } + else + { + throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); + } + } + break; + + case 'bitmapfont': + + if (!file.atlasURL) + { + this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing); + } + else + { + // Load the XML before carrying on with the next file + loadNext = false; + this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) { + var json; + + try + { + // Try to parse as JSON, if it fails, then it's hopefully XML + json = JSON.parse(xhr.responseText); + } + catch (e) {} + + if (!!json) + { + file.atlasType = 'json'; + this.jsonLoadComplete(file, xhr); + } + else + { + file.atlasType = 'xml'; + this.xmlLoadComplete(file, xhr); + } + }); + } + break; + + case 'video': + + if (file.asBlob) + { + try + { + file.data = xhr.response; + } + catch (e) + { + throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key); + } + } + + this.cache.addVideo(file.key, file.url, file.data, file.asBlob); + break; + + case 'audio': + + if (this.game.sound.usingWebAudio) + { + file.data = xhr.response; + + this.cache.addSound(file.key, file.url, file.data, true, false); + + if (file.autoDecode) + { + this.game.sound.decode(file.key); + } + } + else + { + this.cache.addSound(file.key, file.url, file.data, false, true); + } + break; + + case 'text': + file.data = xhr.responseText; + this.cache.addText(file.key, file.url, file.data); + break; + + case 'shader': + file.data = xhr.responseText; + this.cache.addShader(file.key, file.url, file.data); + break; + + case 'physics': + var data = JSON.parse(xhr.responseText); + this.cache.addPhysicsData(file.key, file.url, data, file.format); + break; + + case 'script': + file.data = document.createElement('script'); + file.data.language = 'javascript'; + file.data.type = 'text/javascript'; + file.data.defer = false; + file.data.text = xhr.responseText; + document.head.appendChild(file.data); + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText); + } + break; + + case 'binary': + if (file.callback) + { + file.data = file.callback.call(file.callbackContext, file.key, xhr.response); + } + else + { + file.data = xhr.response; + } + + this.cache.addBinary(file.key, file.data); + + break; + } + + if (loadNext) + { + this.asyncComplete(file); + } + + }, + + /** + * Successfully loaded a JSON file - only used for certain types. + * + * @method Phaser.Loader#jsonLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + jsonLoadComplete: function (file, xhr) { + + var data = JSON.parse(xhr.responseText); + + if (file.type === 'tilemap') + { + this.cache.addTilemap(file.key, file.url, data, file.format); + } + else if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'json') + { + this.cache.addJSON(file.key, file.url, data); + } + else + { + this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); + } + + this.asyncComplete(file); + }, + + /** + * Successfully loaded a CSV file - only used for certain types. + * + * @method Phaser.Loader#csvLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + csvLoadComplete: function (file, xhr) { + + var data = xhr.responseText; + + this.cache.addTilemap(file.key, file.url, data, file.format); + + this.asyncComplete(file); + + }, + + /** + * Successfully loaded an XML file - only used for certain types. + * + * @method Phaser.Loader#xmlLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ + xmlLoadComplete: function (file, xhr) { + + // Always try parsing the content as XML, regardless of actually response type + var data = xhr.responseText; + var xml = this.parseXml(data); + + if (!xml) + { + var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest + console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')'); + this.asyncComplete(file, "invalid XML"); + return; + } + + if (file.type === 'bitmapfont') + { + this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing); + } + else if (file.type === 'textureatlas') + { + this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); + } + else if (file.type === 'xml') + { + this.cache.addXML(file.key, file.url, xml); + } + + this.asyncComplete(file); + + }, + + /** + * Parses string data as XML. + * + * @method Phaser.Loader#parseXml + * @private + * @param {string} data - The XML text to parse + * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document. + */ + parseXml: function (data) { + + var xml; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + // Why is this 'false'? + xml.async = 'false'; + xml.loadXML(data); + } + } + catch (e) + { + xml = null; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + return null; + } + else + { + return xml; + } + + }, + + /** + * Update the loading sprite progress. + * + * @method Phaser.Loader#updateProgress + * @private + */ + updateProgress: function () { + + if (this.preloadSprite) + { + if (this.preloadSprite.direction === 0) + { + this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress); + } + else + { + this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress); + } + + if (this.preloadSprite.sprite) + { + this.preloadSprite.sprite.updateCrop(); + } + else + { + // We seem to have lost our sprite - maybe it was destroyed? + this.preloadSprite = null; + } + } + + }, + + /** + * Returns the number of files that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedFiles + * @protected + * @return {number} The number of files that have already been loaded (even if they errored) + */ + totalLoadedFiles: function () { + + return this._loadedFileCount; + + }, + + /** + * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedFiles + * @protected + * @return {number} The number of files that still remain in the load queue. + */ + totalQueuedFiles: function () { + + return this._totalFileCount - this._loadedFileCount; + + }, + + /** + * Returns the number of asset packs that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedPacks + * @protected + * @return {number} The number of asset packs that have already been loaded (even if they errored) + */ + totalLoadedPacks: function () { + + return this._totalPackCount; + + }, + + /** + * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedPacks + * @protected + * @return {number} The number of asset packs that still remain in the load queue. + */ + totalQueuedPacks: function () { + + return this._totalPackCount - this._loadedPackCount; + + } + +}; + +/** +* The non-rounded load progress value (from 0.0 to 100.0). +* +* A general indicator of the progress. +* It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. +* +* @name Phaser.Loader#progressFloat +* @property {number} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progressFloat", { + + get: function () { + var progress = (this._loadedFileCount / this._totalFileCount) * 100; + return Phaser.Math.clamp(progress || 0, 0, 100); + } + +}); + +/** +* The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}. +* +* @name Phaser.Loader#progress +* @property {integer} +*/ +Object.defineProperty(Phaser.Loader.prototype, "progress", { + + get: function () { + return Math.round(this.progressFloat); + } + +}); + +Phaser.Loader.prototype.constructor = Phaser.Loader; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. +* +* @class Phaser.LoaderParser +*/ +Phaser.LoaderParser = { + + /** + * Alias for xmlBitmapFont, for backwards compatibility. + * + * @method Phaser.LoaderParser.bitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + bitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing, frame, resolution); + + }, + + /** + * Parse a Bitmap Font from an XML file. + * + * @method Phaser.LoaderParser.xmlBitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing; + data.chars = {}; + + var letters = xml.getElementsByTagName('char'); + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + for (var i = 0; i < letters.length; i++) + { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + data.chars[charCode] = { + x: x + parseInt(letters[i].getAttribute('x'), 10), + y: y + parseInt(letters[i].getAttribute('y'), 10), + width: parseInt(letters[i].getAttribute('width'), 10), + height: parseInt(letters[i].getAttribute('height'), 10), + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10) / resolution, + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10) / resolution, + xAdvance: (parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing) / resolution, + kerning: {} + }; + } + + var kernings = xml.getElementsByTagName('kerning'); + + for (i = 0; i < kernings.length; i++) + { + var first = parseInt(kernings[i].getAttribute('first'), 10); + var second = parseInt(kernings[i].getAttribute('second'), 10); + var amount = parseInt(kernings[i].getAttribute('amount'), 10) / resolution; + + data.chars[second].kerning[first] = amount; + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Parse a Bitmap Font from a JSON file. + * + * @method Phaser.LoaderParser.jsonBitmapFont + * @param {object} json - JSON data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ + jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing, frame, resolution) { + + if (resolution == null) + { + resolution = 1; + } + + var data = { + font: json.font.info._face, + size: parseInt(json.font.info._size, 10), + lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing, + chars: {} + }; + + var x = (frame) ? frame.x : 0; + var y = (frame) ? frame.y : 0; + + json.font.chars["char"].forEach( + + function parseChar(letter) { + + var charCode = parseInt(letter._id, 10); + + data.chars[charCode] = { + x: x + parseInt(letter._x, 10), + y: y + parseInt(letter._y, 10), + width: parseInt(letter._width, 10), + height: parseInt(letter._height, 10), + xOffset: parseInt(letter._xoffset, 10) / resolution, + yOffset: parseInt(letter._yoffset, 10) / resolution, + xAdvance: (parseInt(letter._xadvance, 10) + xSpacing) / resolution, + kerning: {} + }; + } + + ); + + if (json.font.kernings && json.font.kernings.kerning) + { + json.font.kernings.kerning.forEach( + + function parseKerning(kerning) { + + data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10) / resolution; + + } + + ); + } + + return this.finalizeBitmapFont(baseTexture, data); + + }, + + /** + * Finalize Bitmap Font parsing. + * + * @method Phaser.LoaderParser.finalizeBitmapFont + * @private + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {object} bitmapFontData - Pre-parsed bitmap font data. + * @return {object} The parsed Bitmap Font data. + */ + finalizeBitmapFont: function (baseTexture, bitmapFontData) { + + Object.keys(bitmapFontData.chars).forEach( + + function addTexture(charCode) { + + var letter = bitmapFontData.chars[charCode]; + + letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height)); + + } + + ); + + return bitmapFontData; + + }, + + /** + * Extract PVR header from loaded binary + * + * @method Phaser.LoaderParser.pvr + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PVR file including texture data. + */ + pvr: function (arrayBuffer) { + + // Reference: http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf + // PVR 3 header structure + // --------------------------------------- + // address: 0, size: 4 bytes version + // address: 4, size: 4 bytes flags + // address: 8, size: 8 bytes pixel format + // address: 16, size: 4 bytes color space + // address: 20, size: 4 bytes channel type + // address: 24, size: 4 bytes height + // address: 28, size: 4 bytes width + // address: 32, size: 4 bytes depth + // address: 36, size: 4 bytes number of surfaces + // address: 40, size: 4 bytes number of faces + // address: 44, size: 4 bytes number of mipmaps + // address: 48, size: 4 bytes meta data size + // --------------------------------------- + var uintArray = new Uint32Array(arrayBuffer.slice(0, 52)), + byteArray = new Uint8Array(arrayBuffer), + pvrHeader = null, + pixelFormat = (uintArray[3] << 32 | uintArray[2]), + compressionAlgorithm, + glExtensionFormat = 0; + + if (uintArray[0] === 0x03525650 && + [ // Validate WebGL Pixel Format + 0, 1, 2, 3, + 6, 7, 9, 11 + ].indexOf(pixelFormat) >= 0 + ) { + if (pixelFormat >= 0 && pixelFormat <= 3) { + compressionAlgorithm = 'PVRTC'; + } else if (pixelFormat >= 7 && pixelFormat <= 11) { + compressionAlgorithm = 'S3TC'; + } else if (pixelFormat === 6) { + compressionAlgorithm = 'ETC1'; + } + + switch (pixelFormat) { + case 0: + glExtensionFormat = 0x8C01; + break; + case 1: + glExtensionFormat = 0x8C03; + break; + case 2: + glExtensionFormat = 0x8C00; + break; + case 3: + glExtensionFormat = 0x8C02; + break; + case 6: + glExtensionFormat = 0x8D64; + break; + case 7: + glExtensionFormat = 0x83F1; + break; + case 9: + glExtensionFormat = 0x83F2; + break; + case 11: + glExtensionFormat = 0x83F3; + break; + default: + glExtensionFormat = -1; + } + + pvrHeader = { + complete: true, + fileFormat: 'PVR', + compressionAlgorithm: compressionAlgorithm, + flags: uintArray[1], + pixelFormat: pixelFormat, + colorSpace: uintArray[4], + channelType: uintArray[5], + height: uintArray[6], + width: uintArray[7], + depth: uintArray[8], + numberOfSurfaces: uintArray[9], + numberOfFaces: uintArray[10], + numberOfMipmaps: uintArray[11], + metaDataSize: uintArray[12], + textureData: byteArray.subarray(52 + uintArray[12], byteArray.byteLength), + glExtensionFormat: glExtensionFormat + }; + } + + return pvrHeader; + + }, + + /** + * Extract DDS header from loaded binary + * + * @method Phaser.LoaderParser.dds + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed DDS file including texture data. + */ + dds: function (arrayBuffer) { + + // Reference at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx + // DDS header structure + // --------------------------------------- + // address: 0, size: 4 bytes Identifier 'DDS ' + // address: 4, size: 4 bytes size + // address: 8, size: 4 bytes flags + // address: 12, size: 4 bytes height + // address: 16, size: 4 bytes width + // address: 20, size: 4 bytes pitch or linear size + // address: 24, size: 4 bytes depth + // address: 28, size: 4 bytes mipmap count + // address: 32, size: 44 bytes reserved space 1 + // address: 76, size: 4 pixel format size + // address: 80, size: 4 pixel format flag + // address: 84, size: 4 pixel format four CC + // address: 88, size: 4 pixel format bit count + // address: 92, size: 4 pixel format R bit mask + // address: 96, size: 4 pixel format G bit mask + // address: 100, size: 4 pixel format B bit mask + // address: 104, size: 4 pixel format A bit mask + // address: 108, size: 4 caps 1 + // address: 112, size: 4 caps 2 + // address: 116, size: 4 caps 3 + // address: 120, size: 4 caps 4 + // address: 124, size: 4 reserved 2 + // -- DXT10 extension + // address: 130, size: 4 DXGI Format + // address: 134, size: 4 resource dimension + // address: 138, size: 4 misc flag + // address: 142, size: 4 array size + // address: 146, size: 4 misc flag 2 + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ddsHeader = null; + + if (byteArray[0] === 0x44 && + byteArray[1] === 0x44 && + byteArray[2] === 0x53 && + byteArray[3] === 0x20) { + ddsHeader = { + complete: true, + fileFormat: 'DDS', + compressionAlgorithm: 'S3TC', + size: uintArray[1], + flags: uintArray[2], + height: uintArray[3], + width: uintArray[4], + pitch: uintArray[5], + depth: uintArray[6], + mipmapCount: uintArray[7], + formatSize: uintArray[19], + formatFlag: uintArray[19], + formatFourCC: [ + String.fromCharCode(byteArray[84]), + String.fromCharCode(byteArray[85]), + String.fromCharCode(byteArray[86]), + String.fromCharCode(byteArray[87]) + ].join(''), + formatBitCount: uintArray[21], + formatRBitMask: uintArray[22], + formatGBitMask: uintArray[23], + formatBBitMask: uintArray[24], + formatABitMask: uintArray[25], + caps1: uintArray[26], + caps2: uintArray[27], + caps3: uintArray[28], + caps4: uintArray[29], + reserved2: uintArray[30], + DXGIFormat: null, + resourceDimension: null, + miscFlag: null, + arraySize: null, + textureData: byteArray.subarray(uintArray[1] + 4, byteArray.byteLength) + }; + if (ddsHeader.formatFourCC === 'DX10') { + ddsHeader.DXGIFormat = uintArray[31]; + ddsHeader.resourceDimension = uintArray[32]; + ddsHeader.miscFlag = uintArray[33]; + ddsHeader.arraySize = uintArray[34]; + ddsHeader.miscFlag = uintArray[35]; + } + } + + return ddsHeader; + + }, + + /** + * Extract KTX header from loaded binary + * + * @method Phaser.LoaderParser.ktx + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed KTX file including texture data. + */ + ktx: function (arrayBuffer) { + + // Reference: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + // KTX header structure + // --------------------------------------- + // address: 0, size 12 bytes: Identifier '«KTX 11»\r\n\x1A\n' + // address: 12, size 4 bytes: endianness + // address: 16, size 4 bytes: GL type + // address: 20, size 4 bytes: GL type size + // address: 24, size 4 bytes: GL format + // address: 28, size 4 bytes: GL internal format + // address: 32, size 4 bytes: GL base internal format + // address: 36, size 4 bytes: pixel width + // address: 40, size 4 bytes: pixel height + // address: 44, size 4 bytes: pixel depth + // address: 48, size 4 bytes: number of array elements + // address: 52, size 4 bytes: number of faces + // address: 56, size 4 bytes: number of mipmap levels + // address: 60, size 4 bytes: bytes of key value data + // address: 64, size 4 bytes: key and value bytes size + // address: X, size 1 byte : key and value + // address: X, size 1 byte : value padding + // address: X, size 4 byte : image size + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + uintArray = new Uint32Array(arrayBuffer), + ktxHeader = null, + imageSizeOffset = 16 + (uintArray[15] / 4) | 0, + imageSize = uintArray[imageSizeOffset], + glInternalFormat = uintArray[7], + compressionAlgorithm = 0; + + if (byteArray[0] === 0xAB && byteArray[1] === 0x4B && + byteArray[2] === 0x54 && byteArray[3] === 0x58 && + byteArray[4] === 0x20 && byteArray[5] === 0x31 && + byteArray[6] === 0x31 && byteArray[7] === 0xBB && + byteArray[8] === 0x0D && byteArray[9] === 0x0A && + byteArray[10] === 0x1A && byteArray[11] === 0x0A && + //Check if internal GL format is supported by WebGL + [ + // ETC1 + 0x8D64, + // PVRTC + 0x8C00, 0x8C01, 0x8C02, 0x8C03, + // DXTC | S3TC + 0x83F0, 0x83F1, 0x83F2, 0x83F3 + ].indexOf(glInternalFormat) >= 0) { + switch (glInternalFormat) { + case 0x8D64: + compressionAlgorithm = 'ETC1'; + break; + case 0x8C00: + case 0x8C01: + case 0x8C02: + case 0x8C03: + compressionAlgorithm = 'PVRTC'; + break; + case 0x83F0: + case 0x83F1: + case 0x83F2: + case 0x83F3: + compressionAlgorithm = 'S3TC'; + break; + } + + ktxHeader = { + complete: true, + fileFormat: 'KTX', + compressionAlgorithm: compressionAlgorithm, + endianness: uintArray[3], + glType: uintArray[4], + glTypeSize: uintArray[5], + glFormat: uintArray[6], + glInternalFormat: uintArray[7], + glBaseInternalFormat: uintArray[8], + width: uintArray[9], + height: uintArray[10], + pixelDepth: uintArray[11], + numberOfArrayElements: uintArray[12], + numberOfFaces: uintArray[13], + numberOfMipmapLevels: uintArray[14], + bytesOfKeyValueData: uintArray[15], + keyAndValueByteSize: uintArray[16], + imageSize: imageSize, + textureData: byteArray.subarray((imageSizeOffset + 1) * 4, imageSize + 100) + }; + } + + return ktxHeader; + + }, + + /** + * Extract PKM header from loaded binary + * + * @method Phaser.LoaderParser.pkm + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PKM file including texture data. + */ + pkm: function (arrayBuffer) { + + // PKM header structure + // --------------------------------------- + // address: 0, size 4 bytes: for 'PKM ' + // address: 4, size 2 bytes: for version + // address: 6, size 2 bytes: for type + // address: 8, size 2 bytes: for extended width + // address: 10, size 2 bytes: for extended height + // address: 12, size 2 bytes: for original width + // address: 14, size 2 bytes: for original height + // address: 16, texture data + // --------------------------------------- + var byteArray = new Uint8Array(arrayBuffer), + pkmHeader = null; + + if (byteArray[0] === 0x50 && + byteArray[1] === 0x4B && + byteArray[2] === 0x4D && + byteArray[3] === 0x20) { + + pkmHeader = { + complete: true, + fileFormat: 'PKM', + compressionAlgorithm: 'ETC1', + format: ((byteArray[6] << 8 | byteArray[7])) & 0xFFFF, + width: ((byteArray[8] << 8 | byteArray[9])) & 0xFFFF, + height: ((byteArray[10] << 8 | byteArray[11])) & 0xFFFF, + originalWidth: ((byteArray[12] << 8 | byteArray[13])) & 0xFFFF, + originalHeight: ((byteArray[14] << 8 | byteArray[15])) & 0xFFFF, + textureData: byteArray.subarray(16, byteArray.length) + }; + } + + return pkmHeader; + + } + +}; + +/** + * @author Jeremy Dowell + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * Audio Sprites are a combination of audio files and a JSON configuration. + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * @class Phaser.AudioSprite + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + * @param {string} key - Asset key for the sound. + */ +Phaser.AudioSprite = function (game, key) { + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * Asset key for the Audio Sprite. + * @property {string} key + */ + this.key = key; + + /** + * JSON audio atlas object. + * @property {object} config + */ + this.config = this.game.cache.getJSON(key + '-audioatlas'); + + /** + * If a sound is set to auto play, this holds the marker key of it. + * @property {string} autoplayKey + */ + this.autoplayKey = null; + + /** + * Is a sound set to autoplay or not? + * @property {boolean} autoplay + * @default + */ + this.autoplay = false; + + /** + * An object containing the Phaser.Sound objects for the Audio Sprite. + * @property {object} sounds + */ + this.sounds = {}; + + for (var k in this.config.spritemap) + { + var marker = this.config.spritemap[k]; + var sound = this.game.add.sound(this.key); + + sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop); + + this.sounds[k] = sound; + } + + if (this.config.autoplay) + { + this.autoplayKey = this.config.autoplay; + this.play(this.autoplayKey); + this.autoplay = this.sounds[this.autoplayKey]; + } + +}; + +Phaser.AudioSprite.prototype = { + + /** + * Play a sound with the given name. + * + * @method Phaser.AudioSprite#play + * @param {string} [marker] - The name of sound to play + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, volume) { + + if (volume === undefined) { volume = 1; } + + return this.sounds[marker].play(marker, null, volume); + + }, + + /** + * Stop a sound with the given name. + * + * @method Phaser.AudioSprite#stop + * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite. + */ + stop: function (marker) { + + if (!marker) + { + for (var key in this.sounds) + { + this.sounds[key].stop(); + } + } + else + { + this.sounds[marker].stop(); + } + + }, + + /** + * Get a sound with the given name. + * + * @method Phaser.AudioSprite#get + * @param {string} marker - The name of sound to get. + * @return {Phaser.Sound} The sound instance. + */ + get: function(marker) { + + return this.sounds[marker]; + + } + +}; + +Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound class constructor. +* +* @class Phaser.Sound +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {string} key - Asset key for the sound. +* @param {number} [volume=1] - Default value for the volume, between 0 and 1. +* @param {boolean} [loop=false] - Whether or not the sound will loop. +*/ +Phaser.Sound = function (game, key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = game.sound.connectToMaster; } + + /** + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ + this.game = game; + + /** + * @property {string} name - Name of the sound. + */ + this.name = key; + + /** + * @property {string} key - Asset key for the sound. + */ + this.key = key; + + /** + * @property {boolean} loop - Whether or not the sound or current sound marker will loop. + */ + this.loop = loop; + + /** + * @property {object} markers - The sound markers. + */ + this.markers = {}; + + /** + * @property {AudioContext} context - Reference to the AudioContext instance. + */ + this.context = null; + + /** + * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically. + */ + this.autoplay = false; + + /** + * @property {number} totalDuration - The total duration of the sound in seconds. + */ + this.totalDuration = 0; + + /** + * @property {number} startTime - The time the sound starts at in ms (typically 0 unless starting from a marker). + * @default + */ + this.startTime = 0; + + /** + * @property {number} currentTime - The current time of sound playback in ms. + */ + this.currentTime = 0; + + /** + * @property {number} duration - The duration of the current sound marker in seconds. + */ + this.duration = 0; + + /** + * @property {number} durationMS - The duration of the current sound marker in ms. + */ + this.durationMS = 0; + + /** + * @property {number} position - The position of the current sound marker in ms. + */ + this.position = 0; + + /** + * @property {number} stopTime - The time the sound stopped in ms. + */ + this.stopTime = 0; + + /** + * @property {boolean} paused - true if the sound is paused, otherwise false. + * @default + */ + this.paused = false; + + /** + * @property {number} pausedPosition - The position the sound had reached when it was paused in ms. + */ + this.pausedPosition = 0; + + /** + * @property {number} pausedTime - The game time (ms) at which the sound was paused. + */ + this.pausedTime = 0; + + /** + * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false. + * @default + */ + this.isPlaying = false; + + /** + * @property {string} currentMarker - The string ID of the currently playing marker, if any. + * @default + */ + this.currentMarker = ''; + + /** + * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. + */ + this.fadeTween = null; + + /** + * @property {boolean} pendingPlayback - true if the sound file is pending playback + * @readonly + */ + this.pendingPlayback = false; + + /** + * @property {boolean} override - if true when you play this sound it will always start from the beginning. + * @default + */ + this.override = false; + + /** + * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. + * @default + */ + this.allowMultiple = false; + + /** + * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio. + * @readonly + */ + this.usingWebAudio = this.game.sound.usingWebAudio; + + /** + * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag. + */ + this.usingAudioTag = this.game.sound.usingAudioTag; + + /** + * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. + */ + this.externalNode = null; + + /** + * @property {object} masterGainNode - The master gain node in a Web Audio system. + */ + this.masterGainNode = null; + + /** + * @property {object} gainNode - The gain node in a Web Audio system. + */ + this.gainNode = null; + + /** + * @property {object} _sound - Internal var. + * @private + */ + this._sound = null; + + /** + * @property {object} _globalVolume - Internal var for keeping track of global volume when using AudioTag + * @private + */ + this._globalVolume = 1; + + /** + * @property {boolean} _markedToDelete - When audio stops, disconnect Web Audio nodes. + * @private + */ + this._markedToDelete = false; + + /** + * @property {boolean} _removeFromSoundManager - When audio stops, remove it from the Sound Manager and destroy it. + * @private + */ + this._removeFromSoundManager = false; + + + + if (this.usingWebAudio) + { + this.context = this.game.sound.context; + this.masterGainNode = this.game.sound.masterGain; + + if (this.context.createGain === undefined) + { + this.gainNode = this.context.createGainNode(); + } + else + { + this.gainNode = this.context.createGain(); + } + + this.gainNode.gain.value = volume; + + if (connect) + { + this.gainNode.connect(this.masterGainNode); + } + } + else if (this.usingAudioTag) + { + if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key)) + { + this._sound = this.game.cache.getSoundData(key); + this.totalDuration = 0; + + if (this._sound.duration) + { + this.totalDuration = this._sound.duration; + } + } + else + { + this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this); + } + } + + /** + * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files). It passes one argument, this sound. + */ + this.onDecoded = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played or a looping marker is restarted. It passes one argument, this sound. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. It passes one argument, this sound. + */ + this.onPause = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. It passes one argument, this sound. + */ + this.onResume = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. It passes one argument, this sound. + */ + this.onLoop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback or when a non-looping marker completes. It passes two arguments: this sound and any {@link #currentMarker marker} that was playing. + */ + this.onStop = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted. It passes one argument, this sound. + */ + this.onMute = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. It passes two arguments: the {@link #currentMarker} and this sound. + */ + this.onMarkerComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out. It passes two arguments: this sound and its current {@link #volume}. + */ + this.onFadeComplete = new Phaser.Signal(); + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + */ + this._volume = volume; + + /** + * @property {any} _buffer - Decoded data buffer / Audio tag. + * @private + */ + this._buffer = null; + + /** + * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. + * @private + */ + this._muted = false; + + /** + * @property {number} _tempMarker - Internal marker var. + * @private + */ + this._tempMarker = 0; + + /** + * @property {number} _tempPosition - Internal marker var. + * @private + */ + this._tempPosition = 0; + + /** + * @property {number} _tempVolume - Internal marker var. + * @private + */ + this._tempVolume = 0; + + /** + * @property {number} _tempPause - Internal marker var. + * @private + */ + this._tempPause = 0; + + /** + * @property {number} _muteVolume - Internal cache var. + * @private + */ + this._muteVolume = 0; + + /** + * @property {boolean} _tempLoop - Internal cache var. + * @private + */ + this._tempLoop = 0; + + /** + * @property {boolean} _paused - Was this sound paused via code or a game event? + * @private + */ + this._paused = false; + + /** + * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched? + * @private + */ + this._onDecodedEventDispatched = false; + +}; + +Phaser.Sound.prototype = { + + /** + * Called automatically when this sound is unlocked. + * @method Phaser.Sound#soundHasUnlocked + * @param {string} key - The Phaser.Cache key of the sound file to check for decoding. + * @protected + */ + soundHasUnlocked: function (key) { + + if (key === this.key) + { + this._sound = this.game.cache.getSoundData(this.key); + this.totalDuration = this._sound.duration; + } + + }, + + /** + * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound#addMarker + * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. + * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). + * @param {boolean} [loop=false] - Sets if the sound will loop or not. + */ + addMarker: function (name, start, duration, volume, loop) { + + if (duration === undefined || duration === null) { duration = 1; } + if (volume === undefined || volume === null) { volume = 1; } + if (loop === undefined) { loop = false; } + + this.markers[name] = { + name: name, + start: start, + stop: start + duration, + volume: volume, + duration: duration, + durationMS: duration * 1000, + loop: loop + }; + + }, + + /** + * Removes a marker from the sound. + * @method Phaser.Sound#removeMarker + * @param {string} name - The key of the marker to remove. + */ + removeMarker: function (name) { + + delete this.markers[name]; + + }, + + /** + * Called automatically by the AudioContext when the sound stops playing. + * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. + * + * @method Phaser.Sound#onEndedHandler + * @protected + */ + onEndedHandler: function () { + + this._sound.onended = null; + this.isPlaying = false; + this.currentTime = this.durationMS; + this.stop(); + + if (this._markedToDelete) + { + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + if (this._removeFromSoundManager) + { + this.game.sound.remove(this); + } + else + { + 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(); + } + } + }, + + /** + * Called automatically by Phaser.SoundManager. + * @method Phaser.Sound#update + * @protected + */ + update: function () { + + if (!this.game.cache.checkSoundKey(this.key)) + { + this.destroy(); + return; + } + + if (this.isDecoded && !this._onDecodedEventDispatched) + { + this.onDecoded.dispatch(this); + this._onDecodedEventDispatched = true; + } + + if (this.pendingPlayback && this.game.cache.isSoundReady(this.key)) + { + this.pendingPlayback = false; + this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop); + } + + if (this.isPlaying) + { + this.currentTime = this.game.time.time - this.startTime; + + if (this.currentTime >= this.durationMS) + { + if (this.usingWebAudio) + { + if (this.loop) + { + // won't work with markers, needs to reset the position + this.onLoop.dispatch(this); + + // Gets reset by the play function + this.isPlaying = false; + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + this.isPlaying = true; // play not called again in this case + } + else + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + this.play(this.currentMarker, 0, this.volume, true, true); + } + } + else + { + // Stop if we're using an audio marker, otherwise we let onended handle it + if (this.currentMarker !== '') + { + this.stop(); + } + } + } + else + { + if (this.loop) + { + this.onLoop.dispatch(this); + + if (this.currentMarker === '') + { + this.currentTime = 0; + this.startTime = this.game.time.time; + } + + // Gets reset by the play function + this.isPlaying = false; + + this.play(this.currentMarker, 0, this.volume, true, true); + } + else + { + this.stop(); + } + } + } + } + }, + + /** + * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters. + * + * @method Phaser.Sound#loopFull + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @return {Phaser.Sound} This sound instance. + */ + loopFull: function (volume) { + + return this.play(null, 0, volume, true); + + }, + + /** + * Play this sound, or a marked section of it. + * + * @method Phaser.Sound#play + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. + * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. + * @return {Phaser.Sound} This sound instance. + */ + play: function (marker, position, volume, loop, forceRestart) { + + if (marker === undefined || marker === false || marker === null) { marker = ''; } + if (forceRestart === undefined) { forceRestart = true; } + + if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override) + { + // Use Restart instead + return this; + } + + if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart)) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) { + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + + this.isPlaying = false; + } + + if (marker === '' && Object.keys(this.markers).length > 0) + { + // If they didn't specify a marker but this is an audio sprite, + // we should never play the entire thing + return this; + } + + if (marker !== '') + { + if (this.markers[marker]) + { + this.currentMarker = marker; + + // Playing a marker? Then we default to the marker values + 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 (volume === undefined) { volume = this._volume; } + if (loop === undefined) { loop = this.loop; } + + this.position = Math.max(0, 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) + { + // Does the sound need decoding? + if (this.game.cache.isSoundDecoded(this.key)) + { + this._sound = this.context.createBufferSource(); + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + this._buffer = this.game.cache.getSoundData(this.key); + this._sound.buffer = this._buffer; + + if (this.loop && marker === '') + { + this._sound.loop = true; + } + + if (!this.loop && marker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + this.totalDuration = this._sound.buffer.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = Math.ceil(this.totalDuration * 1000); + } + + // Useful to cache this somewhere perhaps? + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, this.position, this.duration); + } + else + { + if (this.loop && marker === '') + { + this._sound.start(0, 0); + } + else + { + this._sound.start(0, this.position, this.duration); + } + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + 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 doesn't become available until you call play(), wonderful ... + this.totalDuration = this._sound.duration; + + if (this.duration === 0) + { + this.duration = this.totalDuration; + this.durationMS = this.totalDuration * 1000; + } + + this._sound.currentTime = this.position; + this._sound.muted = this._muted; + + if (this._muted || this.game.sound.mute) + { + this._sound.volume = 0; + } + else + { + this._sound.volume = this._volume; + } + + this.isPlaying = true; + this.startTime = this.game.time.time; + this.currentTime = 0; + this.stopTime = this.startTime + this.durationMS; + + this.onPlay.dispatch(this); + } + else + { + this.pendingPlayback = true; + } + } + } + + return this; + + }, + + /** + * Restart the sound, or a marked section of it. + * + * @method Phaser.Sound#restart + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. + * @param {boolean} [loop=false] - Loop when it finished playing? + */ + restart: function (marker, position, volume, loop) { + + marker = marker || ''; + position = position || 0; + volume = volume || 1; + if (loop === undefined) { loop = false; } + + this.play(marker, position, volume, loop, true); + + }, + + /** + * Pauses the sound. + * + * @method Phaser.Sound#pause + */ + pause: function () { + + if (this.isPlaying && this._sound) + { + this.paused = true; + this.pausedPosition = this.currentTime; + this.pausedTime = this.game.time.time; + this._tempPause = this._sound.currentTime; + this.onPause.dispatch(this); + this.stop(); + } + + }, + + /** + * Resumes the sound. + * + * @method Phaser.Sound#resume + */ + resume: function () { + + if (this.paused && this._sound) + { + if (this.usingWebAudio) + { + var p = Math.max(0, this.position + (this.pausedPosition / 1000)); + + this._sound = this.context.createBufferSource(); + this._sound.buffer = this._buffer; + + if (this.externalNode) + { + this._sound.connect(this.externalNode); + } + else + { + this._sound.connect(this.gainNode); + } + + if (this.loop) + { + this._sound.loop = true; + } + + if (!this.loop && this.currentMarker === '') + { + this._sound.onended = this.onEndedHandler.bind(this); + } + + var duration = this.duration - (this.pausedPosition / 1000); + + if (this._sound.start === undefined) + { + this._sound.noteGrainOn(0, p, duration); + //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it + } + else + { + if (this.loop && this.game.device.chrome) + { + // Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099 + if (this.game.device.chromeVersion === 42) + { + this._sound.start(0); + } + else + { + this._sound.start(0, p); + } + } + else + { + this._sound.start(0, p, duration); + } + } + } + else + { + this._sound.currentTime = this._tempPause; + this._sound.play(); + } + + this.isPlaying = true; + this.paused = false; + this.startTime += (this.game.time.time - this.pausedTime); + this.onResume.dispatch(this); + } + + }, + + /** + * Stop playing this sound. + * + * @method Phaser.Sound#stop + */ + stop: function () { + + if (this.isPlaying && this._sound) + { + if (this.usingWebAudio) + { + if (this._sound.stop === undefined) + { + this._sound.noteOff(0); + } + else + { + try { + this._sound.stop(0); + } + catch (e) + { + // Thanks Android 4.4 + } + } + + if (this.externalNode) + { + this._sound.disconnect(this.externalNode); + } + else if (this.gainNode) + { + this._sound.disconnect(this.gainNode); + } + + } + else if (this.usingAudioTag) + { + this._sound.pause(); + this._sound.currentTime = 0; + } + } + + this.pendingPlayback = false; + this.isPlaying = false; + + if (!this.paused) + { + var prevMarker = this.currentMarker; + + if (this.currentMarker !== '') + { + this.onMarkerComplete.dispatch(this.currentMarker, this); + } + + this.currentMarker = ''; + + if (this.fadeTween !== null) + { + this.fadeTween.stop(); + } + + this.onStop.dispatch(this, prevMarker); + } + + }, + + /** + * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. + * Then increases the volume from 0 to 1 over the duration specified. + * + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (1) as the second parameter. + * + * @method Phaser.Sound#fadeIn + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in. + * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. + * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. + */ + fadeIn: function (duration, loop, marker) { + + if (loop === undefined) { loop = false; } + if (marker === undefined) { marker = this.currentMarker; } + + if (this.paused) + { + return; + } + + this.play(marker, 0, 0, loop); + + this.fadeTo(duration, 1); + + }, + + /** + * Decreases the volume of this Sound from its current value to 0 over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (0) as the second parameter. + * + * @method Phaser.Sound#fadeOut + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out. + */ + fadeOut: function (duration) { + + this.fadeTo(duration, 0); + + }, + + /** + * Fades the volume of this Sound from its current value to the given volume over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (volume) as the second parameter. + * + * @method Phaser.Sound#fadeTo + * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out. + * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1. + */ + fadeTo: function (duration, volume) { + + if (!this.isPlaying || this.paused || volume === this.volume) + { + return; + } + + if (duration === undefined) { duration = 1000; } + + if (volume === undefined) + { + console.warn("Phaser.Sound.fadeTo: No Volume Specified."); + return; + } + + this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true); + + this.fadeTween.onComplete.add(this.fadeComplete, this); + + }, + + /** + * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo. + * + * @method Phaser.Sound#fadeComplete + * @private + */ + fadeComplete: function () { + + this.onFadeComplete.dispatch(this, this.volume); + + if (this.volume === 0) + { + this.stop(); + } + + }, + + /** + * Called automatically by SoundManager.volume. + * + * Sets the volume of AudioTag Sounds as a percentage of the Global Volume. + * + * You should not normally call this directly. + * + * @method Phaser.Sound#updateGlobalVolume + * @protected + * @param {float} globalVolume - The global SoundManager volume. + */ + updateGlobalVolume: function (globalVolume) { + + // this._volume is the % of the global volume this sound should be played at + + if (this.usingAudioTag && this._sound) + { + this._globalVolume = globalVolume; + this._sound.volume = this._globalVolume * this._volume; + } + + }, + + /** + * Destroys this sound and all associated events and removes it from the SoundManager. + * + * @method Phaser.Sound#destroy + * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager. + */ + destroy: function (remove) { + + if (remove === undefined) { remove = true; } + + this._markedToDelete = true; + this._removeFromSoundManager = remove; + this.stop(); + + if (remove) + { + this.game.sound.remove(this); + } + else + { + 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; + +/** +* @name Phaser.Sound#isDecoding +* @property {boolean} isDecoding - Returns true if the sound file is still decoding. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoding", { + + get: function () { + return this.game.cache.getSound(this.key).isDecoding; + } + +}); + +/** +* @name Phaser.Sound#isDecoded +* @property {boolean} isDecoded - Returns true if the sound file has decoded. +* @readonly +*/ +Object.defineProperty(Phaser.Sound.prototype, "isDecoded", { + + get: function () { + return this.game.cache.isSoundDecoded(this.key); + } + +}); + +/** +* @name Phaser.Sound#mute +* @property {boolean} mute - Gets or sets the muted state of this sound. +*/ +Object.defineProperty(Phaser.Sound.prototype, "mute", { + + get: function () { + + return (this._muted || this.game.sound.mute); + + }, + + set: function (value) { + + value = value || false; + + if (value === this._muted) + { + return; + } + + if (value) + { + this._muted = true; + this._muteVolume = this._tempVolume; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = 0; + } + else if (this.usingAudioTag && this._sound) + { + 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); + + } + +}); + +/** +* @name Phaser.Sound#volume +* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Sound.prototype, "volume", { + + get: function () { + return this._volume; + }, + + set: function (value) { + + // Causes an Index size error if you don't clamp the value + if (this.usingAudioTag) + { + value = this.game.math.clamp(value, 0, 1); + } + + if (this._muted) + { + this._muteVolume = value; + return; + } + + this._tempVolume = value; + this._volume = value; + + if (this.usingWebAudio) + { + this.gainNode.gain.value = value; + } + else if (this.usingAudioTag && this._sound) + { + this._sound.volume = this._globalVolume * value; + } + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. +* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. +* The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. +* There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ +* +* If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out +* of AudioContext nodes. If this is the case create a global var called {@link PhaserGlobal} on the window object before creating the game. The active +* AudioContext will then be saved to `window.PhaserGlobal.audioContext` when the Phaser game is destroyed, and re-used when it starts again. +* +* Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. +* When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. +* The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will +* be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. +* +* @class Phaser.SoundManager +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +*/ +Phaser.SoundManager = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) + */ + this.onSoundDecode = new Phaser.Signal(); + + /** + * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. + * @property {Phaser.Signal} onVolumeChange + */ + this.onVolumeChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. + * @property {Phaser.Signal} onMute + */ + this.onMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. + * @property {Phaser.Signal} onUnMute + */ + this.onUnMute = new Phaser.Signal(); + + /** + * This signal is dispatched when the SoundManager is touch-unlocked. + * If the device doesn't {@link Phaser.Device.needsTouchUnlock need touch-unlocking}, the signal won't be dispatched. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * @property {AudioContext} context - The AudioContext being used for playback. + * @default + */ + this.context = null; + + /** + * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio. + * @readonly + */ + this.usingWebAudio = false; + + /** + * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio. + * @readonly + */ + this.usingAudioTag = false; + + /** + * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. + * @default + */ + this.noAudio = false; + + /** + * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. + * @default + */ + this.connectToMaster = true; + + /** + * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. + * @default + */ + this.touchLocked = false; + + /** + * @property {number} channels - The number of audio channels to use in playback. + * @default + */ + this.channels = 32; + + /** + * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), + * or set to false to keep audio playing, regardless of the game pause state. You may need to + * do this should you wish to control audio muting via external DOM buttons or similar. + * @property {boolean} muteOnPause + * @default + */ + this.muteOnPause = true; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {AudioContext} _unlockSource - Internal unlock tracking var. + * @private + * @default + */ + this._unlockSource = null; + + /** + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + * @default + */ + this._volume = 1; + + + /** + * @property {array} _sounds - An array containing all the sounds + * @private + */ + this._sounds = []; + + /** + * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status. + * @private + */ + this._watchList = new Phaser.ArraySet(); + + /** + * @property {boolean} _watching - Is the SoundManager monitoring the watchList? + * @private + */ + this._watching = false; + + /** + * @property {function} _watchCallback - The callback to invoke once the watchlist is clear. + * @private + */ + this._watchCallback = null; + + /** + * @property {object} _watchContext - The context in which to call the watchlist callback. + * @private + */ + this._watchContext = null; + +}; + +Phaser.SoundManager.prototype = { + + /** + * Initialises the sound manager. + * @method Phaser.SoundManager#boot + * @protected + */ + boot: function () { + + var device = this.game.device; + var PhaserGlobal = window.PhaserGlobal; + + if (device.iOS && device.webAudio === false) + { + this.channels = 1; + } + + // PhaserGlobal overrides + if (PhaserGlobal) + { + // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class) + if (PhaserGlobal.disableAudio === true) + { + this.noAudio = true; + this.touchLocked = false; + return; + } + + // Check if the Web Audio API is disabled (for testing Audio Tag playback during development) + if (PhaserGlobal.disableWebAudio === true) + { + this.usingAudioTag = true; + this.touchLocked = false; + return; + } + } + + if (PhaserGlobal && PhaserGlobal.audioContext) + { + this.context = PhaserGlobal.audioContext; + } + else + { + if (!!window['AudioContext']) + { + try { + this.context = new window['AudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + else if (!!window['webkitAudioContext']) + { + try { + this.context = new window['webkitAudioContext'](); + } catch (error) { + this.context = null; + this.usingWebAudio = false; + this.touchLocked = false; + } + } + } + + if (this.context === null) + { + // No Web Audio support - how about legacy Audio? + if (window['Audio'] === undefined) + { + this.noAudio = true; + return; + } + else + { + this.usingAudioTag = true; + } + } + else + { + this.usingWebAudio = true; + + if (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); + } + + if (!this.noAudio) + { + // On mobile we need a native touch event before we can play anything, so capture it here + if (device.needsTouchUnlock()) + { + this.setTouchLock(); + } + } + + if (this.usingWebAudio && device.chrome && device.chromeVersion <= 65) + { + console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. '); + } + + }, + + /** + * Sets the Input Manager touch callback to be SoundManager.unlock. + * Required for iOS audio device unlocking. Mostly just used internally. + * + * @method Phaser.SoundManager#setTouchLock + */ + setTouchLock: function () { + + if (this.noAudio || (window.PhaserGlobal && window.PhaserGlobal.disableAudio === true)) + { + return; + } + + this.game.input.addTouchLockCallback(this.unlock, this, true); + + this.touchLocked = true; + + }, + + /** + * Turns off {@link #touchLocked} and dispatches {@link #onTouchUnlock}. + * + * @method Phaser.SoundManager#setTouchUnlock + * @private + */ + setTouchUnlock: function () { + + this.touchLocked = false; + this._unlockSource = null; + this.onTouchUnlock.dispatch(); + + }, + + /** + * Enables the audio, usually after the first touch. + * + * @method Phaser.SoundManager#unlock + * @return {boolean} True if the callback should be removed, otherwise false. + */ + unlock: function () { + + if (this.noAudio || !this.touchLocked || this._unlockSource !== null) + { + return true; + } + + // Global override (mostly for Audio Tag testing) + if (this.usingAudioTag) + { + this.setTouchUnlock(); + } + else if (this.usingWebAudio) + { + // Create empty buffer and play it + // The SoundManager.update loop captures the state of it and then resets touchLocked to false + + var buffer = this.context.createBuffer(1, 1, 22050); + this._unlockSource = this.context.createBufferSource(); + this._unlockSource.buffer = buffer; + this._unlockSource.connect(this.context.destination); + + if (this._unlockSource.start === undefined) + { + this._unlockSource.noteOn(0); + } + else + { + this._unlockSource.start(0); + } + + //This fixes locked audio in Chrome > 55 cross origin iframes + if (this._unlockSource.context.state === 'suspended') { + this._unlockSource.context.resume(); + } + } + + // We can remove the event because we've done what we needed (started the unlock sound playing) + return true; + + }, + + /** + * Stops all the sounds in the game. + * + * @method Phaser.SoundManager#stopAll + */ + stopAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].stop(); + } + } + + }, + + /** + * Pauses all the sounds in the game. + * + * @method Phaser.SoundManager#pauseAll + */ + pauseAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].pause(); + } + } + + }, + + /** + * Resumes every sound in the game. + * + * @method Phaser.SoundManager#resumeAll + */ + resumeAll: function () { + + if (this.noAudio) + { + return; + } + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].resume(); + } + } + + }, + + /** + * Decode a sound by its asset key. + * + * @method Phaser.SoundManager#decode + * @param {string} key - Assets key of the sound to be decoded. + * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. + */ + decode: function (key, sound) { + + sound = sound || null; + + var soundData = this.game.cache.getSoundData(key); + + if (soundData) + { + if (this.game.cache.isSoundDecoded(key) === false) + { + this.game.cache.updateSound(key, 'isDecoding', true); + + var _this = this; + + try { + this.context.decodeAudioData(soundData, function (buffer) { + + if (buffer) + { + _this.game.cache.decodedSound(key, buffer); + _this.onSoundDecode.dispatch(key, sound); + } + }); + } + catch (e) {} + } + } + + }, + + /** + * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback. + * Once all of the Sound files have finished decoding the callback will be invoked. + * The amount of time spent decoding depends on the codec used and file size. + * If all of the files given have already decoded the callback is triggered immediately. + * + * @method Phaser.SoundManager#setDecodedCallback + * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache. + * @param {Function} callback - The callback which will be invoked once all files have finished decoding. + * @param {Object} callbackContext - The context in which the callback will run. + */ + setDecodedCallback: function (files, callback, callbackContext) { + + if (typeof files === 'string') + { + files = [ files ]; + } + + this._watchList.reset(); + + for (var i = 0; i < files.length; i++) + { + if (files[i] instanceof Phaser.Sound) + { + if (!this.game.cache.isSoundDecoded(files[i].key)) + { + this._watchList.add(files[i].key); + } + } + else if (!this.game.cache.isSoundDecoded(files[i])) + { + this._watchList.add(files[i]); + } + } + + // All decoded already? + if (this._watchList.total === 0) + { + this._watching = false; + callback.call(callbackContext); + } + else + { + this._watching = true; + this._watchCallback = callback; + this._watchContext = callbackContext; + } + + }, + + /** + * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. + * + * @method Phaser.SoundManager#update + * @protected + */ + update: function () { + + if (this.noAudio) + { + return; + } + + if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE)) + { + this.setTouchUnlock(); + } + + for (var i = 0; i < this._sounds.length; i++) + { + this._sounds[i].update(); + } + + if (this._watching) + { + var key = this._watchList.first; + + while (key) + { + if (this.game.cache.isSoundDecoded(key)) + { + this._watchList.remove(key); + } + + key = this._watchList.next; + } + + if (this._watchList.total === 0) + { + this._watching = false; + this._watchCallback.call(this._watchContext); + } + } + + }, + + /** + * Adds a new Sound into the SoundManager. + * + * @method Phaser.SoundManager#add + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The new sound instance. + */ + add: function (key, volume, loop, connect) { + + if (volume === undefined) { volume = 1; } + if (loop === undefined) { loop = false; } + if (connect === undefined) { connect = this.connectToMaster; } + + var sound = new Phaser.Sound(this.game, key, volume, loop, connect); + + this._sounds.push(sound); + + return sound; + + }, + + /** + * Adds a new AudioSprite into the SoundManager. + * + * @method Phaser.SoundManager#addSprite + * @param {string} key - Asset key for the sound. + * @return {Phaser.AudioSprite} The new AudioSprite instance. + */ + addSprite: function(key) { + + var audioSprite = new Phaser.AudioSprite(this.game, key); + + return audioSprite; + + }, + + /** + * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. + * + * @method Phaser.SoundManager#remove + * @param {Phaser.Sound} sound - The sound object to remove. + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ + remove: function (sound) { + + var i = this._sounds.length; + + while (i--) + { + if (this._sounds[i] === sound) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + return true; + } + } + + return false; + + }, + + /** + * Removes all Sounds from the SoundManager. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeAll + */ + removeAll: function () { + + this.stopAll(); + + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i]) + { + this._sounds[i].destroy(); + } + } + + this._sounds.length = 0; + + }, + + /** + * Removes all Sounds from the SoundManager that have an asset key matching the given value. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeByKey + * @param {string} key - The key to match when removing sound objects. + * @return {number} The number of matching sound objects that were removed. + */ + removeByKey: function (key) { + + var i = this._sounds.length; + var removed = 0; + + while (i--) + { + if (this._sounds[i].key === key) + { + this._sounds[i].destroy(false); + this._sounds.splice(i, 1); + removed++; + } + } + + return removed; + + }, + + /** + * Adds a new Sound into the SoundManager and starts it playing. + * + * @method Phaser.SoundManager#play + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @return {Phaser.Sound} The new sound instance. + */ + play: function (key, volume, loop) { + + if (this.noAudio) + { + return; + } + + var sound = this.add(key, volume, loop); + + sound.play(); + + return sound; + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + if (this.usingWebAudio) + { + this._muteVolume = this.masterGain.gain.value; + this.masterGain.gain.value = 0; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = true; + } + } + + this.onMute.dispatch(); + + }, + + /** + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = this._muteVolume; + } + + // Loop through sounds + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].mute = false; + } + } + + this.onUnMute.dispatch(); + + }, + + /** + * Stops all the sounds in the game, then destroys them and finally clears up any callbacks. + * + * @method Phaser.SoundManager#destroy + */ + destroy: function () { + + this.removeAll(); + + this.onSoundDecode.dispose(); + + if (this.context) + { + if (window.PhaserGlobal) + { + // Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing + window.PhaserGlobal.audioContext = this.context; + } + else + { + if (this.context.close) + { + this.context.close(); + } + } + } + + } + +}; + +Phaser.SoundManager.prototype.constructor = Phaser.SoundManager; + +/** +* @name Phaser.SoundManager#mute +* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || false; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* @name Phaser.SoundManager#volume +* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.SoundManager.prototype, "volume", { + + get: function () { + + return this._volume; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this._volume !== value) + { + this._volume = value; + + if (this.usingWebAudio) + { + this.masterGain.gain.value = value; + } + else + { + // Loop through the sound cache and change the volume of all html audio tags + for (var i = 0; i < this._sounds.length; i++) + { + if (this._sounds[i].usingAudioTag) + { + this._sounds[i].updateGlobalVolume(value); + } + } + } + + this.onVolumeChange.dispatch(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* @classdesc +* The ScaleManager object handles the the scaling, resizing, and alignment of the +* Game size and the game Display canvas. +* +* The Game size is the logical size of the game; the Display canvas has size as an HTML element. +* +* The calculations of these are heavily influenced by the bounding Parent size which is the computed +* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the +* canvas's Parent element play an important role_ in the operation of the ScaleManager. +* +* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size. +* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}). +* +* #### Parent and Display canvas containment guidelines: +* +* - Style the Parent element (of the game canvas) to control the Parent size and +* thus the Display canvas's size and layout. +* +* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior. +* +* - The Parent element should _not_ apply a padding as this is not accounted for. +* If a padding is required apply it to the Parent's parent or apply a margin to the Parent. +* If you need to add a border, margin or any other CSS around your game container, then use a parent element and +* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container. +* +* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as +* they may be updated by the ScaleManager. +* +* #### Example Uses +* +* - ##### Fixed game size; scale canvas proportionally to fill its container +* +* Use `scaleMode` SHOW_ALL. +* +* - ##### Fixed game size; stretch canvas to fill its container (uncommon) +* +* Use `scaleMode` EXACT_FIT. +* +* - ##### Fixed game size; scale canvas proportionally by some other criteria +* +* Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary. +* +* - ##### Fluid game/canvas size +* +* Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary. +* +* - ##### Preferred orientation +* +* Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals. +* +* @description +* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game} +* +* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. +* +* @class +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number|string} width - The width of the game. See above. +* @param {number|string} height - The height of the game. See above. +*/ +Phaser.ScaleManager = function (game, width, height) { + + /** + * A reference to the currently running game. + * @property {Phaser.Game} game + * @protected + * @readonly + */ + this.game = game; + + /** + * Provides access to some cross-device DOM functions. + * @property {Phaser.DOM} dom + * @protected + * @readonly + */ + this.dom = Phaser.DOM; + + /** + * _EXPERIMENTAL:_ A responsive grid on which you can align game objects. + * @property {Phaser.FlexGrid} grid + * @public + */ + this.grid = null; + + /** + * Target width (in pixels) of the Display canvas. + * @property {number} width + * @readonly + */ + this.width = 0; + + /** + * Target height (in pixels) of the Display canvas. + * @property {number} height + * @readonly + */ + this.height = 0; + + /** + * Minimum width the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minWidth + * @readonly + * @protected + */ + this.minWidth = null; + + /** + * Maximum width the canvas should be scaled to (in pixels). + * If null it will scale to whatever width the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxWidth + * @readonly + * @protected + */ + this.maxWidth = null; + + /** + * Minimum height the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minHeight + * @readonly + * @protected + */ + this.minHeight = null; + + /** + * Maximum height the canvas should be scaled to (in pixels). + * If null it will scale to whatever height the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxHeight + * @readonly + * @protected + */ + this.maxHeight = null; + + /** + * The offset coordinates of the Display canvas from the top-left of the browser window. + * The is used internally by Phaser.Pointer (for Input) and possibly other types. + * @property {Phaser.Point} offset + * @readonly + * @protected + */ + this.offset = new Phaser.Point(); + + /** + * If true, the game should only run in a landscape orientation. + * Change with {@link #forceOrientation}. + * @property {boolean} forceLandscape + * @readonly + * @default + * @protected + */ + this.forceLandscape = false; + + /** + * If true, the game should only run in a portrait + * Change with {@link #forceOrientation}. + * @property {boolean} forcePortrait + * @readonly + * @default + * @protected + */ + this.forcePortrait = false; + + /** + * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation. + * + * This value is not updated immediately. + * + * @property {boolean} incorrectOrientation + * @readonly + * @protected + */ + this.incorrectOrientation = false; + + /** + * See {@link #pageAlignHorizontally}. + * @property {boolean} _pageAlignHorizontally + * @private + */ + this._pageAlignHorizontally = false; + + /** + * See {@link #pageAlignVertically}. + * @property {boolean} _pageAlignVertically + * @private + */ + this._pageAlignVertically = false; + + /** + * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes. + * + * The signal is supplied with the following arguments: + * - `scale` - the ScaleManager object + * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}. + * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. + * + * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. + * Thus the following tests can be done: + * + * // The orientation itself changed: + * scale.screenOrientation !== prevOrientation + * // The orientation just became incorrect: + * scale.incorrectOrientation && !wasIncorrect + * + * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation + * correctness changes even if the orientation itself does not change. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onOrientationChange + * @public + */ + this.onOrientationChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} enterIncorrectOrientation + * @public + */ + this.enterIncorrectOrientation = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} leaveIncorrectOrientation + * @public + */ + this.leaveIncorrectOrientation = new Phaser.Signal(); + + /** + * This boolean provides you with a way to determine if the browser is in Full Screen + * mode (via the Full Screen API), and Phaser was the one responsible for activating it. + * + * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the + * one that made the browser go full-screen, so this flag lets you determine that. + * + * @property {boolean} hasPhaserSetFullScreen + * @default + */ + this.hasPhaserSetFullScreen = false; + + /** + * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. + * The target element must have the correct CSS styling and contain the Display canvas. + * + * The elements style will be modified (ie. the width and height might be set to 100%) + * but it will not be added to, removed from, or repositioned within the DOM. + * An attempt is made to restore relevant style changes when fullscreen mode is left. + * + * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. + * + * @property {?DOMElement} fullScreenTarget + * @default + */ + this.fullScreenTarget = null; + + /** + * The fullscreen target, as created by {@link #createFullScreenTarget}. + * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends. + * @property {?DOMElement} _createdFullScreenTarget + * @private + */ + this._createdFullScreenTarget = null; + + /** + * This signal is dispatched when fullscreen mode is ready to be initialized but + * before the fullscreen request. + * + * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. + * + * The `targetElement` is the {@link #fullScreenTarget} element, + * if such is assigned, or a new element created by {@link #createFullScreenTarget}. + * + * Custom CSS styling or resets can be applied to `targetElement` as required. + * + * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}: + * - After initialization the Display canvas is moved onto the `targetElement` for + * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. + * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. + * + * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}. + * + * @property {Phaser.Signal} onFullScreenInit + * @public + */ + this.onFullScreenInit = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine + * if currently running in Fullscreen mode. + * + * @property {Phaser.Signal} onFullScreenChange + * @public + */ + this.onFullScreenChange = new Phaser.Signal(); + + /** + * This signal is dispatched when the browser fails to enter fullscreen mode; + * or if the device does not support fullscreen mode and `startFullScreen` is invoked. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). + * + * @property {Phaser.Signal} onFullScreenError + * @public + */ + this.onFullScreenError = new Phaser.Signal(); + + /** + * The _last known_ orientation of the screen, as defined in the Window Screen Web API. + * See {@link Phaser.DOM.getScreenOrientation} for possible values. + * + * @property {string} screenOrientation + * @readonly + * @public + */ + this.screenOrientation = this.dom.getScreenOrientation(); + + /** + * The _current_ scale factor based on the game dimensions vs. the scaled dimensions. + * @property {Phaser.Point} scaleFactor + * @readonly + */ + this.scaleFactor = new Phaser.Point(1, 1); + + /** + * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions. + * @property {Phaser.Point} scaleFactorInversed + * @readonly + * @protected + */ + this.scaleFactorInversed = new Phaser.Point(1, 1); + + /** + * The Display canvas is aligned by adjusting the margins; the last margins are stored here. + * + * @property {Bounds-like} margin + * @readonly + * @protected + */ + this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0}; + + /** + * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. + * @property {Phaser.Rectangle} bounds + * @readonly + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The aspect ratio of the scaled Display canvas. + * @property {number} aspectRatio + * @readonly + */ + this.aspectRatio = 0; + + /** + * The aspect ratio of the original game dimensions. + * @property {number} sourceAspectRatio + * @readonly + */ + this.sourceAspectRatio = 0; + + /** + * The native browser events from Fullscreen API changes. + * @property {any} event + * @readonly + * @private + */ + this.event = null; + + /** + * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container. + * + * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. + * - If 'visual', the edge will be constrained to the Window / displayed screen area + * - If 'layout', the edge will be constrained to the CSS Layout bounds + * - An invalid value is treated as 'visual' + * + * @member + * @property {string} bottom + * @property {string} right + * @default + */ + this.windowConstraints = { + right: 'layout', + bottom: '' + }; + + /** + * Various compatibility settings. + * A value of "(auto)" indicates the setting is configured based on device and runtime information. + * + * A {@link #refresh} may need to be performed after making changes. + * + * @protected + * + * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.) + * + * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}. + * + * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. + * + * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh. + * + * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates. + * The height set varies by device and may either be the height of the window or the viewport. + * + * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. + * + * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. + * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. + * Any other string value (including the empty string) prevents using click trampolines. + * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}. + */ + this.compatibility = { + supportsFullScreen: false, + orientationFallback: null, + noMargins: false, + scrollTo: null, + forceMinimumDocumentHeight: false, + canExpandParent: true, + clickTrampoline: '' + }; + + /** + * Scale mode to be used when not in fullscreen. + * @property {number} _scaleMode + * @private + */ + this._scaleMode = Phaser.ScaleManager.NO_SCALE; + + /* + * Scale mode to be used in fullscreen. + * @property {number} _fullScreenScaleMode + * @private + */ + this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE; + + /** + * True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * The {@link #parentNode} property is generally ignored while this is in effect. + * + * @property {boolean} parentIsWindow + */ + this.parentIsWindow = false; + + /** + * The _original_ DOM element for the parent of the Display canvas. + * This may be different in fullscreen - see {@link #createFullScreenTarget}. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * This should only be changed after moving the Game canvas to a different DOM parent. + * + * @property {?DOMElement} parentNode + */ + this.parentNode = null; + + /** + * The scale of the game in relation to its parent container. + * @property {Phaser.Point} parentScaleFactor + * @readonly + */ + this.parentScaleFactor = new Phaser.Point(1, 1); + + /** + * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). + * Update checks normally happen quicker in response to other events. + * + * @property {integer} trackParentInterval + * @default + * @protected + * @see {@link Phaser.ScaleManager#refresh refresh} + */ + this.trackParentInterval = 2000; + + /** + * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. + * When invoked this is done _after_ the Canvas size/position have been updated. + * + * The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.) + * + * This signal is _only_ called when a change occurs and a reflow may be required. + * For example, if the canvas does not change sizes because of CSS settings (such as min-width) + * then this signal will _not_ be triggered. + * + * Use this to handle responsive game layout options. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onSizeChange + */ + this.onSizeChange = new Phaser.Signal(); + + /** + * The callback that will be called each the parent container resizes. + * @property {function} onResize + * @private + */ + this.onResize = null; + + /** + * The context in which the {@link #onResize} callback will be called. + * @property {object} onResizeContext + * @private + */ + this.onResizeContext = null; + + /** + * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot. + * @private + */ + this._pendingScaleMode = null; + + /** + * Information saved when fullscreen mode is started. + * @property {?object} _fullScreenRestore + * @private + */ + this._fullScreenRestore = null; + + /** + * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}. + * @property {Phaser.Rectangle} _gameSize + * @private + */ + this._gameSize = new Phaser.Rectangle(); + + /** + * The user-supplied scale factor, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleFactor + * @private + */ + this._userScaleFactor = new Phaser.Point(1, 1); + + /** + * The user-supplied scale trim, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleTrim + * @private + */ + this._userScaleTrim = new Phaser.Point(0, 0); + + /** + * The last time the bounds were checked in `preUpdate`. + * @property {number} _lastUpdate + * @private + */ + this._lastUpdate = 0; + + /** + * Size checks updates are delayed according to the throttle. + * The throttle increases to `trackParentInterval` over time and is used to more + * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety. + * @property {integer} _updateThrottle + * @private + */ + this._updateThrottle = 0; + + /** + * The minimum throttle allowed until it has slowed down sufficiently. + * @property {integer} _updateThrottleReset + * @private + */ + this._updateThrottleReset = 100; + + /** + * The cached result of the parent (possibly window) bounds; used to invalidate sizing. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._parentBounds = new Phaser.Rectangle(); + + /** + * Temporary bounds used for internal work to cut down on new objects created. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ + this._tempBounds = new Phaser.Rectangle(); + + /** + * The Canvas size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedCanvasSize + * @private + */ + this._lastReportedCanvasSize = new Phaser.Rectangle(); + + /** + * The Game size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedGameSize + * @private + */ + this._lastReportedGameSize = new Phaser.Rectangle(); + + /** + * @property {boolean} _booted - ScaleManager booted state. + * @private + */ + this._booted = false; + + if (game.config) + { + this.parseConfig(game.config); + } + + this.setupScale(width, height); + +}; + +/** +* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.EXACT_FIT = 0; + +/** +* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.NO_SCALE = 1; + +/** +* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.SHOW_ALL = 2; + +/** +* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.RESIZE = 3; + +/** +* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}. +* +* @constant +* @type {integer} +*/ +Phaser.ScaleManager.USER_SCALE = 4; + +/** +* Names of the scale modes, indexed by value. +* +* @constant +* @type {string[]} +*/ +Phaser.ScaleManager.MODES = [ + 'EXACT_FIT', + 'NO_SCALE', + 'SHOW_ALL', + 'RESIZE', + 'USER_SCALE' +]; + +Phaser.ScaleManager.prototype = { + + /** + * Start the ScaleManager. + * + * @method Phaser.ScaleManager#boot + * @protected + */ + boot: function () { + + // Configure device-dependent compatibility + + var compat = this.compatibility; + + compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS; + + // We can't do anything about the status bars in iPads, web apps or desktops + if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop) + { + if (this.game.device.android && !this.game.device.chrome) + { + compat.scrollTo = new Phaser.Point(0, 1); + } + else + { + compat.scrollTo = new Phaser.Point(0, 0); + } + } + + if (this.game.device.desktop) + { + compat.orientationFallback = 'screen'; + compat.clickTrampoline = 'when-not-mouse'; + } + else + { + compat.orientationFallback = ''; + compat.clickTrampoline = ''; + } + + // Configure event listeners + + var _this = this; + + this._orientationChange = function(event) { + return _this.orientationChange(event); + }; + + this._windowResize = function(event) { + return _this.windowResize(event); + }; + + // This does not appear to be on the standards track + window.addEventListener('orientationchange', this._orientationChange, false); + window.addEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + this._fullScreenChange = function(event) { + return _this.fullScreenChange(event); + }; + + this._fullScreenError = function(event) { + return _this.fullScreenError(event); + }; + + document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.addEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.addEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.addEventListener('fullscreenchange', this._fullScreenChange, false); + + document.addEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.addEventListener('mozfullscreenerror', this._fullScreenError, false); + document.addEventListener('MSFullscreenError', this._fullScreenError, false); + document.addEventListener('fullscreenerror', this._fullScreenError, false); + } + + this.game.onResume.add(this._gameResumed, this); + + // Initialize core bounds + + this.dom.getOffset(this.game.canvas, this.offset); + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + this.setGameSize(this.game.width, this.game.height); + + // Don't use updateOrientationState so events are not fired + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + if (Phaser.FlexGrid) + { + this.grid = new Phaser.FlexGrid(this, this.width, this.height); + } + + this._booted = true; + + if (this._pendingScaleMode !== null) + { + this.scaleMode = this._pendingScaleMode; + this._pendingScaleMode = null; + } + + }, + + /** + * Load configuration settings. + * + * @method Phaser.ScaleManager#parseConfig + * @protected + * @param {object} config - The game configuration object. + */ + parseConfig: function (config) { + + if (config['scaleMode'] !== undefined) + { + if (this._booted) + { + this.scaleMode = config['scaleMode']; + } + else + { + this._pendingScaleMode = config['scaleMode']; + } + } + + if (config['fullScreenScaleMode'] !== undefined) + { + this.fullScreenScaleMode = config['fullScreenScaleMode']; + } + + if (config['fullScreenTarget']) + { + this.fullScreenTarget = config['fullScreenTarget']; + } + + this.pageAlignHorizontally = config.alignH || false; + this.pageAlignVertically = config.alignV || false; + + if (config.scaleH && config.scaleV) + { + this.setUserScale(config.scaleH, config.scaleV, config.trimH, config.trimV); + } + + }, + + /** + * Calculates and sets the game dimensions based on the given width and height. + * + * This should _not_ be called when in fullscreen mode. + * + * @method Phaser.ScaleManager#setupScale + * @protected + * @param {number|string} width - The width of the game. + * @param {number|string} height - The height of the game. + */ + setupScale: function (width, height) { + + var target; + var rect = new Phaser.Rectangle(); + + if (this.game.parent !== '') + { + if (typeof this.game.parent === 'string') + { + // hopefully an element ID + target = document.getElementById(this.game.parent); + } + else if (this.game.parent && this.game.parent.nodeType === 1) + { + // quick test for a HTMLelement + target = this.game.parent; + } + } + + // Fallback, covers an invalid ID and a non HTMLelement object + if (!target) + { + // Use the full window + this.parentNode = null; + this.parentIsWindow = true; + + rect.width = this.dom.visualBounds.width; + rect.height = this.dom.visualBounds.height; + + this.offset.set(0, 0); + } + else + { + this.parentNode = target; + this.parentIsWindow = false; + + this.getParentBounds(this._parentBounds); + + rect.width = this._parentBounds.width; + rect.height = this._parentBounds.height; + + this.offset.set(this._parentBounds.x, this._parentBounds.y); + } + + var newWidth = 0; + var newHeight = 0; + + if (typeof width === 'number') + { + newWidth = width; + } + else + { + // Percentage based + this.parentScaleFactor.x = parseInt(width, 10) / 100; + newWidth = rect.width * this.parentScaleFactor.x; + } + + if (typeof height === 'number') + { + newHeight = height; + } + else + { + // Percentage based + this.parentScaleFactor.y = parseInt(height, 10) / 100; + newHeight = rect.height * this.parentScaleFactor.y; + } + + newWidth = Math.floor(newWidth); + newHeight = Math.floor(newHeight); + + this._gameSize.setTo(0, 0, newWidth, newHeight); + + this.updateDimensions(newWidth, newHeight, false); + + }, + + /** + * Invoked when the game is resumed. + * + * @method Phaser.ScaleManager#_gameResumed + * @private + */ + _gameResumed: function () { + + this.queueUpdate(true); + + }, + + /** + * Set the actual Game size. + * Use this instead of directly changing `game.width` or `game.height`. + * + * The actual physical display (Canvas element size) depends on various settings including + * - Scale mode + * - Scaling factor + * - Size of Canvas's parent element or CSS rules such as min-height/max-height; + * - The size of the Window + * + * @method Phaser.ScaleManager#setGameSize + * @public + * @param {integer} width - _Game width_, in pixels. + * @param {integer} height - _Game height_, in pixels. + */ + setGameSize: function (width, height) { + + this._gameSize.setTo(0, 0, width, height); + + if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE) + { + this.updateDimensions(width, height, true); + } + + this.queueUpdate(true); + + }, + + /** + * Set a User scaling factor used in the USER_SCALE scaling mode. + * + * The target canvas size is computed by: + * + * canvas.width = (game.width * hScale) - hTrim + * canvas.height = (game.height * vScale) - vTrim + * + * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly. + * + * @method Phaser.ScaleManager#setUserScale + * @param {number} hScale - Horizontal scaling factor. + * @param {numer} vScale - Vertical scaling factor. + * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling. + * @param {integer} [vTrim=0] - Vertical trim, applied after scaling. + * @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate + * @param {boolean} [force=true] - Force a resize during the next preUpdate + */ + setUserScale: function (hScale, vScale, hTrim, vTrim, queueUpdate, force) { + + this._userScaleFactor.setTo(hScale, vScale); + this._userScaleTrim.setTo(hTrim | 0, vTrim | 0); + + if (queueUpdate === undefined) { queueUpdate = true; } + if (force === undefined) { force = true; } + + if (queueUpdate) + { + this.queueUpdate(force); + } + + }, + + /** + * Sets the callback that will be invoked before sizing calculations. + * + * Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries: + * the browser window has been resized, the device has been rotated, or the parent container's size has changed. + * At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all + * after it makes its sizing calculations). You can read the size of the parent container from the + * `parentBounds` argument to the callback. + * + * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling. + * + * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager + * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. + * + * This callback + * - May be invoked even though the parent container or canvas sizes have not changed + * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated + * - Will be invoked from `preUpdate`, _even when_ the game is paused + * + * See {@link #onSizeChange} for a better way of reacting to layout updates. + * + * @method Phaser.ScaleManager#setResizeCallback + * @public + * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes. + * @param {object} context - The context in which the callback will be called. + */ + setResizeCallback: function (callback, context) { + + this.onResize = callback; + this.onResizeContext = context; + + }, + + /** + * Signals a resize - IF the canvas or Game size differs from the last signal. + * + * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager). + * + * It dispatches the {@link #onSizeChange} signal. + * + * @method Phaser.ScaleManager#signalSizeChange + * @private + */ + signalSizeChange: function () { + + if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) || + !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize)) + { + var width = this.width; + var height = this.height; + + this._lastReportedCanvasSize.setTo(0, 0, width, height); + this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height); + + if (this.grid) + { + this.grid.onResize(width, height); + } + + this.onSizeChange.dispatch(this, width, height); + + // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode. + if (this.currentScaleMode === Phaser.ScaleManager.RESIZE) + { + this.game.state.resize(width, height); + this.game.load.resize(width, height); + } + } + + }, + + /** + * Set the min and max dimensions for the Display canvas. + * + * _Note:_ The min/max dimensions are only applied in some cases + * - When the device is not in an incorrect orientation; or + * - The scale mode is EXACT_FIT when not in fullscreen + * + * @method Phaser.ScaleManager#setMinMax + * @public + * @param {number} minWidth - The minimum width the game is allowed to scale down to. + * @param {number} minHeight - The minimum height the game is allowed to scale down to. + * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified. + * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified. + * @todo These values are only sometimes honored. + */ + setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) { + + this.minWidth = minWidth; + this.minHeight = minHeight; + + if (typeof maxWidth !== 'undefined') + { + this.maxWidth = maxWidth; + } + + if (typeof maxHeight !== 'undefined') + { + this.maxHeight = maxHeight; + } + + }, + + /** + * The ScaleManager.preUpdate is called automatically by the core Game loop. + * + * @method Phaser.ScaleManager#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.game.time.time < (this._lastUpdate + this._updateThrottle)) + { + return; + } + + var prevThrottle = this._updateThrottle; + this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100; + + this.dom.getOffset(this.game.canvas, this.offset); + + var prevWidth = this._parentBounds.width; + var prevHeight = this._parentBounds.height; + var bounds = this.getParentBounds(this._parentBounds); + + var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight; + + // Always invalidate on a newly detected orientation change + var orientationChanged = this.updateOrientationState(); + + if (boundsChanged || orientationChanged) + { + if (this.onResize) + { + this.onResize.call(this.onResizeContext, this, bounds); + } + + this.updateLayout(); + + this.signalSizeChange(); + } + + // Next throttle, eg. 25, 50, 100, 200.. + var throttle = this._updateThrottle * 2; + + // Don't let an update be too eager about resetting the throttle. + if (this._updateThrottle < prevThrottle) + { + throttle = Math.min(prevThrottle, this._updateThrottleReset); + } + + this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval); + this._lastUpdate = this.game.time.time; + + }, + + /** + * Update method while paused. + * + * @method Phaser.ScaleManager#pauseUpdate + * @private + */ + pauseUpdate: function () { + + this.preUpdate(); + + // Updates at slowest. + this._updateThrottle = this.trackParentInterval; + + }, + + /** + * Update the dimensions taking the parent scaling factor into account. + * + * @method Phaser.ScaleManager#updateDimensions + * @private + * @param {number} width - The new width of the parent container. + * @param {number} height - The new height of the parent container. + * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars. + */ + updateDimensions: function (width, height, resize) { + + this.width = width * this.parentScaleFactor.x; + this.height = height * this.parentScaleFactor.y; + + this.game.width = this.width; + this.game.height = this.height; + + this.sourceAspectRatio = this.width / this.height; + this.updateScalingAndBounds(); + + if (resize) + { + // Resize the renderer (which in turn resizes the Display canvas!) + this.game.renderer.resize(this.width, this.height); + + // The Camera can never be smaller than the Game size + this.game.camera.setSize(this.width, this.height); + + // This should only happen if the world is smaller than the new canvas size + this.game.world.resize(this.width, this.height); + } + + }, + + /** + * Update relevant scaling values based on the ScaleManager dimension and game dimensions, + * which should already be set. This does not change {@link #sourceAspectRatio}. + * + * @method Phaser.ScaleManager#updateScalingAndBounds + * @private + */ + updateScalingAndBounds: function () { + + this.scaleFactor.x = this.game.width / this.width; + this.scaleFactor.y = this.game.height / this.height; + + this.scaleFactorInversed.x = this.width / this.game.width; + this.scaleFactorInversed.y = this.height / this.game.height; + + this.aspectRatio = this.width / this.height; + + // This can be invoked in boot pre-canvas + if (this.game.canvas) + { + this.dom.getOffset(this.game.canvas, this.offset); + } + + this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height); + + // Can be invoked in boot pre-input + if (this.game.input && this.game.input.scale) + { + this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y); + } + + }, + + /** + * Force the game to run in only one orientation. + * + * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. + * + * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor + * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the + * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` + * + * @method Phaser.ScaleManager#forceOrientation + * @public + * @param {boolean} forceLandscape - true if the game should run in landscape mode only. + * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. + */ + forceOrientation: function (forceLandscape, forcePortrait) { + + if (forcePortrait === undefined) { forcePortrait = false; } + + if (forceLandscape === true && forcePortrait === true) + { + console.warn('Phaser.ScaleManager: forceLandscape and forcePortrait cannot both be true.'); + return; + } + + this.forceLandscape = forceLandscape; + this.forcePortrait = forcePortrait; + + this.queueUpdate(true); + + }, + + /** + * Classify the orientation, per `getScreenOrientation`. + * + * @method Phaser.ScaleManager#classifyOrientation + * @private + * @param {string} orientation - The orientation string, e.g. 'portrait-primary'. + * @return {?string} The classified orientation: 'portrait', 'landscape`, or null. + */ + classifyOrientation: function (orientation) { + + if (orientation === 'portrait-primary' || orientation === 'portrait-secondary') + { + return 'portrait'; + } + else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary') + { + return 'landscape'; + } + else + { + return null; + } + + }, + + /** + * Updates the current orientation and dispatches orientation change events. + * + * @method Phaser.ScaleManager#updateOrientationState + * @private + * @return {boolean} True if the orientation state changed which means a forced update is likely required. + */ + updateOrientationState: function () { + + var previousOrientation = this.screenOrientation; + var previouslyIncorrect = this.incorrectOrientation; + + this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback); + + this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) || + (this.forcePortrait && !this.isPortrait); + + var changed = previousOrientation !== this.screenOrientation; + var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation; + + if (correctnessChanged) + { + if (this.incorrectOrientation) + { + this.enterIncorrectOrientation.dispatch(); + } + else + { + this.leaveIncorrectOrientation.dispatch(); + } + } + + if (changed || correctnessChanged) + { + this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect); + } + + return changed || correctnessChanged; + + }, + + /** + * window.orientationchange event handler. + * + * @method Phaser.ScaleManager#orientationChange + * @private + * @param {Event} event - The orientationchange event data. + */ + orientationChange: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * window.resize event handler. + * + * @method Phaser.ScaleManager#windowResize + * @private + * @param {Event} event - The resize event data. + */ + windowResize: function (event) { + + this.event = event; + + this.queueUpdate(true); + + }, + + /** + * Scroll to the top - in some environments. See `compatibility.scrollTo`. + * + * @method Phaser.ScaleManager#scrollTop + * @private + */ + scrollTop: function () { + + var scrollTo = this.compatibility.scrollTo; + + if (scrollTo) + { + window.scrollTo(scrollTo.x, scrollTo.y); + } + + }, + + /** + * The "refresh" methods informs the ScaleManager that a layout refresh is required. + * + * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) + * when the browser is resized, the orientation changes, or when there is a detected change + * of the Parent size. Refreshing is also done automatically when public properties, + * such as {@link #scaleMode}, are updated or state-changing methods are invoked. + * + * The "refresh" method _may_ need to be used in a few (rare) situtations when + * + * - a device change event is not correctly detected; or + * - the Parent size changes (and an immediate reflow is desired); or + * - the ScaleManager state is updated by non-standard means; or + * - certain {@link #compatibility} properties are manually changed. + * + * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. + * + * @method Phaser.ScaleManager#refresh + * @public + */ + refresh: function () { + + this.scrollTop(); + this.queueUpdate(true); + + }, + + /** + * Updates the game / canvas position and size. + * + * @method Phaser.ScaleManager#updateLayout + * @private + */ + updateLayout: function () { + + var scaleMode = this.currentScaleMode; + + if (scaleMode === Phaser.ScaleManager.RESIZE) + { + this.reflowGame(); + return; + } + + this.scrollTop(); + + if (this.compatibility.forceMinimumDocumentHeight) + { + // (This came from older code, by why is it here?) + // Set minimum height of content to new window height + document.documentElement.style.minHeight = window.innerHeight + 'px'; + } + + if (this.incorrectOrientation) + { + this.setMaximum(); + } + else + { + if (scaleMode === Phaser.ScaleManager.EXACT_FIT) + { + this.setExactFit(); + } + else if (scaleMode === Phaser.ScaleManager.SHOW_ALL) + { + if (!this.isFullScreen && this.boundingParent && + this.compatibility.canExpandParent) + { + // Try to expand parent out, but choosing maximizing dimensions. + // Then select minimize dimensions which should then honor parent + // maximum bound applications. + this.setShowAll(true); + this.resetCanvas(); + this.setShowAll(); + } + else + { + this.setShowAll(); + } + } + else if (scaleMode === Phaser.ScaleManager.NO_SCALE) + { + this.width = this.game.width; + this.height = this.game.height; + } + else if (scaleMode === Phaser.ScaleManager.USER_SCALE) + { + this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x; + this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y; + } + } + + if (!this.compatibility.canExpandParent && + (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE)) + { + var bounds = this.getParentBounds(this._tempBounds); + this.width = Math.min(this.width, bounds.width); + this.height = Math.min(this.height, bounds.height); + } + + // Always truncate / force to integer + this.width = this.width | 0; + this.height = this.height | 0; + + this.reflowCanvas(); + + }, + + /** + * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. + * + * If in fullscreen mode or without parent (see {@link #parentIsWindow}), + * this will be the bounds of the visual viewport itself. + * + * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside + * the viewport then this function may return a smaller than expected size. + * + * Values are rounded to the nearest pixel. + * + * @method Phaser.ScaleManager#getParentBounds + * @protected + * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed. + * @return {Phaser.Rectangle} The established parent bounds. + */ + getParentBounds: function (target) { + + var bounds = target || new Phaser.Rectangle(); + var parentNode = this.boundingParent; + var visualBounds = this.dom.visualBounds; + var layoutBounds = this.dom.layoutBounds; + + if (!parentNode) + { + bounds.setTo(0, 0, visualBounds.width, visualBounds.height); + } + else + { + // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect + var clientRect = parentNode.getBoundingClientRect(); + var parentRect = (parentNode.offsetParent) ? parentNode.offsetParent.getBoundingClientRect() : parentNode.getBoundingClientRect(); + + bounds.setTo(clientRect.left - parentRect.left, clientRect.top - parentRect.top, clientRect.width, clientRect.height); + + var wc = this.windowConstraints; + + if (wc.right) + { + var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds; + bounds.right = Math.min(bounds.right, windowBounds.width); + } + + if (wc.bottom) + { + var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds; + bounds.bottom = Math.min(bounds.bottom, windowBounds.height); + } + } + + bounds.setTo( + Math.round(bounds.x), Math.round(bounds.y), + Math.round(bounds.width), Math.round(bounds.height)); + + return bounds; + + }, + + + /** + * Shorthand for setting {@link #pageAlignHorizontally} and {@link #pageAlignVertically}. + * + * @method Phaser.ScaleManager#align + * @param {boolean} [horizontal] - Value for {@link #pageAlignHorizontally}. Pass `null` to leave unchanged. + * @param {boolean} [vertical] - Value for {@link #pageAlignVertically}. Omit or pass `null` to leave unchanged. + */ + align: function (horizontal, vertical) { + + if (horizontal != null) + { + this.pageAlignHorizontally = horizontal; + } + + if (vertical != null) + { + this.pageAlignVertically = vertical; + } + + }, + + /** + * Update the canvas position/margins - for alignment within the parent container. + * + * The canvas margins _must_ be reset/cleared prior to invoking this. + * + * @method Phaser.ScaleManager#alignCanvas + * @private + * @param {boolean} horizontal - Align horizontally? + * @param {boolean} vertical - Align vertically? + */ + alignCanvas: function (horizontal, vertical) { + + var parentBounds = this.getParentBounds(this._tempBounds); + var canvas = this.game.canvas; + var margin = this.margin; + + if (horizontal) + { + margin.left = margin.right = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.width < parentBounds.width && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.left - parentBounds.x; + var targetEdge = (parentBounds.width / 2) - (this.width / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + + margin.left = Math.round(offset); + } + + canvas.style.marginLeft = margin.left + 'px'; + + if (margin.left !== 0) + { + margin.right = -(parentBounds.width - canvasBounds.width - margin.left); + canvas.style.marginRight = margin.right + 'px'; + } + } + + if (vertical) + { + margin.top = margin.bottom = 0; + + var canvasBounds = canvas.getBoundingClientRect(); + + if (this.height < parentBounds.height && !this.incorrectOrientation) + { + var currentEdge = canvasBounds.top - parentBounds.y; + var targetEdge = (parentBounds.height / 2) - (this.height / 2); + + targetEdge = Math.max(targetEdge, 0); + + var offset = targetEdge - currentEdge; + margin.top = Math.round(offset); + } + + canvas.style.marginTop = margin.top + 'px'; + + if (margin.top !== 0) + { + margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top); + canvas.style.marginBottom = margin.bottom + 'px'; + } + } + + // Silly backwards compatibility.. + margin.x = margin.left; + margin.y = margin.top; + + }, + + /** + * Updates the Game state / size. + * + * The canvas margins may always be adjusted, even if alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowGame + * @private + */ + reflowGame: function () { + + this.resetCanvas('', ''); + + var bounds = this.getParentBounds(this._tempBounds); + this.updateDimensions(bounds.width, bounds.height, true); + + }, + + /** + * Updates the Display canvas size. + * + * The canvas margins may always be adjusted, even alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowCanvas + * @private + */ + reflowCanvas: function () { + + if (!this.incorrectOrientation) + { + this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width); + this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height); + } + + this.resetCanvas(); + + if (!this.compatibility.noMargins) + { + if (this.isFullScreen && this._createdFullScreenTarget) + { + this.alignCanvas(true, true); + } + else + { + this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically); + } + } + + this.updateScalingAndBounds(); + + }, + + /** + * "Reset" the Display canvas and set the specified width/height. + * + * @method Phaser.ScaleManager#resetCanvas + * @private + * @param {string} [cssWidth=(current width)] - The css width to set. + * @param {string} [cssHeight=(current height)] - The css height to set. + */ + resetCanvas: function (cssWidth, cssHeight) { + + if (cssWidth === undefined) { cssWidth = this.width + 'px'; } + if (cssHeight === undefined) { cssHeight = this.height + 'px'; } + + var canvas = this.game.canvas; + + if (!this.compatibility.noMargins) + { + canvas.style.marginLeft = ''; + canvas.style.marginTop = ''; + canvas.style.marginRight = ''; + canvas.style.marginBottom = ''; + } + + canvas.style.width = cssWidth; + canvas.style.height = cssHeight; + + }, + + /** + * Queues/marks a size/bounds check as needing to occur (from `preUpdate`). + * + * @method Phaser.ScaleManager#queueUpdate + * @private + * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty. + */ + queueUpdate: function (force) { + + if (force) + { + this._parentBounds.width = 0; + this._parentBounds.height = 0; + } + + this._updateThrottle = this._updateThrottleReset; + + }, + + /** + * Reset internal data/state. + * + * @method Phaser.ScaleManager#reset + * @private + */ + reset: function (clearWorld) { + + if (clearWorld && this.grid) + { + this.grid.reset(); + } + + }, + + /** + * Updates the width/height to that of the window. + * + * @method Phaser.ScaleManager#setMaximum + * @private + */ + setMaximum: function () { + + this.width = this.dom.visualBounds.width; + this.height = this.dom.visualBounds.height; + + }, + + /** + * Updates the width/height such that the game is scaled proportionally. + * + * @method Phaser.ScaleManager#setShowAll + * @private + * @param {boolean} expanding - If true then the maximizing dimension is chosen. + */ + setShowAll: function (expanding) { + + var bounds = this.getParentBounds(this._tempBounds); + var width = bounds.width; + var height = bounds.height; + + var multiplier; + + if (expanding) + { + multiplier = Math.max((height / this.game.height), (width / this.game.width)); + } + else + { + multiplier = Math.min((height / this.game.height), (width / this.game.width)); + } + + this.width = Math.round(this.game.width * multiplier); + this.height = Math.round(this.game.height * multiplier); + + }, + + /** + * Updates the width/height such that the game is stretched to the available size. + * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen. + * + * @method Phaser.ScaleManager#setExactFit + * @private + */ + setExactFit: function () { + + var bounds = this.getParentBounds(this._tempBounds); + + this.width = bounds.width; + this.height = bounds.height; + + if (this.isFullScreen) + { + // Max/min not honored fullscreen + return; + } + + if (this.maxWidth) + { + this.width = Math.min(this.width, this.maxWidth); + } + + if (this.maxHeight) + { + this.height = Math.min(this.height, this.maxHeight); + } + + }, + + /** + * Creates a fullscreen target. This is called automatically as as needed when entering + * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}. + * + * Use {@link #onFullScreenInit} to customize the created object. + * + * @method Phaser.ScaleManager#createFullScreenTarget + * @protected + */ + createFullScreenTarget: function () { + + var fsTarget = document.createElement('div'); + + fsTarget.style.margin = '0'; + fsTarget.style.padding = '0'; + fsTarget.style.background = '#000'; + + return fsTarget; + + }, + + /** + * Display the game in the browser's fullscreen mode. + * + * This _must_ be called from a user-input Pointer or Mouse event (and possibly a {@link https://www.chromestatus.com/feature/6131337345892352 "user gesture"}), e.g., + * + * - {@link Phaser.Events#onInputUp} + * - {@link Phaser.Input#onUp} or {@link Phaser.Input#onTap} + * - `click`, `mousedown`, `mouseup`, `pointerup`, or `touchend` + * + * Games within an iframe will also be blocked from fullscreen unless the iframe has the `allowfullscreen` attribute. + * + * The {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} must be {@link http://caniuse.com/#search=fullscreen supported by the browser} for this to work - it is not the same as setting + * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current + * device is reported to support fullscreen mode. + * + * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. + * + * Safari blocks access to keyboard events in fullscreen mode (as a security measure). + * + * @method Phaser.ScaleManager#startFullScreen + * @public + * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. + * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed. + * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) + */ + startFullScreen: function (antialias, allowTrampoline) { + + if (this.isFullScreen) + { + return false; + } + + if (!this.compatibility.supportsFullScreen) + { + // Error is called in timeout to emulate the real fullscreenerror event better + var _this = this; + + setTimeout(function () { + _this.fullScreenError(); + }, 10); + + return; + } + + if (this.compatibility.clickTrampoline === 'when-not-mouse') + { + var input = this.game.input; + + if (input.activePointer && + input.activePointer !== input.mousePointer && + (allowTrampoline || allowTrampoline !== false)) + { + input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]); + return; + } + } + + if (antialias !== undefined && this.game.renderType === Phaser.CANVAS) + { + this.game.stage.smoothed = antialias; + } + + var fsTarget = this.fullScreenTarget; + + if (!fsTarget) + { + this.cleanupCreatedTarget(); + + this._createdFullScreenTarget = this.createFullScreenTarget(); + fsTarget = this._createdFullScreenTarget; + } + + var initData = { + targetElement: fsTarget + }; + + this.hasPhaserSetFullScreen = true; + + this.onFullScreenInit.dispatch(this, initData); + + if (this._createdFullScreenTarget) + { + // Move the Display canvas inside of the target and add the target to the DOM + // (The target has to be added for the Fullscreen API to work.) + var canvas = this.game.canvas; + var parent = canvas.parentNode; + parent.insertBefore(fsTarget, canvas); + fsTarget.appendChild(canvas); + } + + if (this.game.device.fullscreenKeyboard) + { + fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT); + } + else + { + fsTarget[this.game.device.requestFullscreen](); + } + + return true; + + }, + + /** + * Stops / exits fullscreen mode, if active. + * + * @method Phaser.ScaleManager#stopFullScreen + * @public + * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. + */ + stopFullScreen: function () { + + if (!this.isFullScreen || !this.compatibility.supportsFullScreen) + { + return false; + } + + this.hasPhaserSetFullScreen = false; + + document[this.game.device.cancelFullscreen](); + + return true; + + }, + + /** + * Cleans up the previous fullscreen target, if such was automatically created. + * This ensures the canvas is restored to its former parent, assuming the target didn't move. + * + * @method Phaser.ScaleManager#cleanupCreatedTarget + * @private + */ + cleanupCreatedTarget: function () { + + var fsTarget = this._createdFullScreenTarget; + + if (fsTarget && fsTarget.parentNode) + { + // Make sure to cleanup synthetic target for sure; + // swap the canvas back to the parent. + var parent = fsTarget.parentNode; + parent.insertBefore(this.game.canvas, fsTarget); + parent.removeChild(fsTarget); + } + + this._createdFullScreenTarget = null; + + }, + + /** + * Used to prepare/restore extra fullscreen mode settings. + * (This does move any elements within the DOM tree.) + * + * @method Phaser.ScaleManager#prepScreenMode + * @private + * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_. + */ + prepScreenMode: function (enteringFullscreen) { + + var createdTarget = !!this._createdFullScreenTarget; + var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget; + + if (enteringFullscreen) + { + if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT) + { + // Resize target, as long as it's not the canvas + if (fsTarget !== this.game.canvas) + { + this._fullScreenRestore = { + targetWidth: fsTarget.style.width, + targetHeight: fsTarget.style.height + }; + + fsTarget.style.width = '100%'; + fsTarget.style.height = '100%'; + } + } + } + else + { + // Have restore information + if (this._fullScreenRestore) + { + fsTarget.style.width = this._fullScreenRestore.targetWidth; + fsTarget.style.height = this._fullScreenRestore.targetHeight; + + this._fullScreenRestore = null; + } + + // Always reset to game size + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.resetCanvas(); + } + + }, + + /** + * Called automatically when the browser enters of leaves fullscreen mode. + * + * @method Phaser.ScaleManager#fullScreenChange + * @private + * @param {Event} [event=undefined] - The fullscreenchange event + */ + fullScreenChange: function (event) { + + this.event = event; + + if (this.isFullScreen) + { + this.prepScreenMode(true); + + this.updateLayout(); + this.queueUpdate(true); + } + else + { + this.prepScreenMode(false); + + this.cleanupCreatedTarget(); + + this.updateLayout(); + this.queueUpdate(true); + } + + this.onFullScreenChange.dispatch(this, this.width, this.height); + + }, + + /** + * Called automatically when the browser fullscreen request fails; + * or called when a fullscreen request is made on a device for which it is not supported. + * + * @method Phaser.ScaleManager#fullScreenError + * @private + * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API. + */ + fullScreenError: function (event) { + + this.event = event; + + this.cleanupCreatedTarget(); + + console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API'); + + this.onFullScreenError.dispatch(this); + + }, + + /** + * Takes a Sprite or Image object and scales it to fit the given dimensions. + * Scaling happens proportionally without distortion to the sprites texture. + * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the + * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either + * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. + * + * @method Phaser.ScaleManager#scaleSprite + * @protected + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale. + * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. + * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. + * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. + * @return {Phaser.Sprite|Phaser.Image} The scaled sprite. + */ + scaleSprite: function (sprite, width, height, letterBox) { + + if (width === undefined) { width = this.width; } + if (height === undefined) { height = this.height; } + if (letterBox === undefined) { letterBox = false; } + + if (!sprite || !sprite['scale']) + { + return sprite; + } + + sprite.scale.x = 1; + sprite.scale.y = 1; + + if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0)) + { + return sprite; + } + + var scaleX1 = width; + var scaleY1 = (sprite.height * width) / sprite.width; + + var scaleX2 = (sprite.width * height) / sprite.height; + var scaleY2 = height; + + var scaleOnWidth = (scaleX2 > width); + + if (scaleOnWidth) + { + scaleOnWidth = letterBox; + } + else + { + scaleOnWidth = !letterBox; + } + + if (scaleOnWidth) + { + sprite.width = Math.floor(scaleX1); + sprite.height = Math.floor(scaleY1); + } + else + { + sprite.width = Math.floor(scaleX2); + sprite.height = Math.floor(scaleY2); + } + + // Enable at some point? + // sprite.x = Math.floor((width - sprite.width) / 2); + // sprite.y = Math.floor((height - sprite.height) / 2); + + return sprite; + + }, + + /** + * Destroys the ScaleManager and removes any event listeners. + * This should probably only be called when the game is destroyed. + * + * @method Phaser.ScaleManager#destroy + * @protected + */ + destroy: function () { + + this.game.onResume.remove(this._gameResumed, this); + + window.removeEventListener('orientationchange', this._orientationChange, false); + window.removeEventListener('resize', this._windowResize, false); + + if (this.compatibility.supportsFullScreen) + { + document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false); + document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false); + document.removeEventListener('fullscreenchange', this._fullScreenChange, false); + + document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false); + document.removeEventListener('mozfullscreenerror', this._fullScreenError, false); + document.removeEventListener('MSFullscreenError', this._fullScreenError, false); + document.removeEventListener('fullscreenerror', this._fullScreenError, false); + } + + } + +}; + +Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager; + +/** +* The DOM element that is considered the Parent bounding element, if any. +* +* This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified. +* It will also be null if there is no game canvas or if the game canvas has no parent. +* +* @name Phaser.ScaleManager#boundingParent +* @property {?DOMElement} boundingParent +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", { + + get: function () { + + if (this.parentIsWindow || + (this.isFullScreen && this.hasPhaserSetFullScreen && !this._createdFullScreenTarget)) + { + return null; + } + + var parentNode = this.game.canvas && this.game.canvas.parentNode; + + return parentNode || null; + + } + +}); + +/** +* The scaling method used by the ScaleManager when not in fullscreen. +* +*
+*
{@link Phaser.ScaleManager.NO_SCALE}
+*
+* The Game display area will not be scaled - even if it is too large for the canvas/screen. +* This mode _ignores_ any applied scaling factor and displays the canvas at the Game size. +*
+*
{@link Phaser.ScaleManager.EXACT_FIT}
+*
+* The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen. +* Proportions are not maintained. +*
+*
{@link Phaser.ScaleManager.SHOW_ALL}
+*
+* Show the entire game display area while _maintaining_ the original aspect ratio. +*
+*
{@link Phaser.ScaleManager.RESIZE}
+*
+* The dimensions of the game display area are changed to match the size of the parent container. +* That is, this mode _changes the Game size_ to match the display size. +*

+* Any manually set Game size (see {@link #setGameSize}) is ignored while in effect. +*

+*
{@link Phaser.ScaleManager.USER_SCALE}
+*
+* The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}. +*

+* This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback} +* for flexible custom-sizing needs. +*

+*
+* +* @name Phaser.ScaleManager#scaleMode +* @property {integer} scaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", { + + get: function () { + + return this._scaleMode; + + }, + + set: function (value) { + + if (value !== this._scaleMode) + { + if (!this.isFullScreen) + { + this.updateDimensions(this._gameSize.width, this._gameSize.height, true); + this.queueUpdate(true); + } + + this._scaleMode = value; + } + + return this._scaleMode; + + } + +}); + +/** +* The scaling method used by the ScaleManager when in fullscreen. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#fullScreenScaleMode +* @property {integer} fullScreenScaleMode +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", { + + get: function () { + + return this._fullScreenScaleMode; + + }, + + set: function (value) { + + if (value !== this._fullScreenScaleMode) + { + // If in fullscreen then need a wee bit more work + if (this.isFullScreen) + { + this.prepScreenMode(false); + this._fullScreenScaleMode = value; + this.prepScreenMode(true); + + this.queueUpdate(true); + } + else + { + this._fullScreenScaleMode = value; + } + } + + return this._fullScreenScaleMode; + + } + +}); + +/** +* Returns the current scale mode - for normal or fullscreen operation. +* +* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. +* +* @name Phaser.ScaleManager#currentScaleMode +* @property {number} currentScaleMode +* @protected +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", { + + get: function () { + + return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode; + + } + +}); + +/** +* When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align horizontally across the page the Display canvas should be added directly to page; +* or the parent container should itself be horizontally aligned. +* +* Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignHorizontally +* @property {boolean} pageAlignHorizontally +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", { + + get: function () { + + return this._pageAlignHorizontally; + + }, + + set: function (value) { + + if (value !== this._pageAlignHorizontally) + { + this._pageAlignHorizontally = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). +* +* To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain +* a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically +* _within_ the remaining available height dictated by the Parent element. +* +* One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. +* If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). +* +* _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height. +* To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true. +* +* Vertical alignment is not applicable with the {@link .RESIZE} scaling mode. +* +* @name Phaser.ScaleManager#pageAlignVertically +* @property {boolean} pageAlignVertically +* @default false +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", { + + get: function () { + + return this._pageAlignVertically; + + }, + + set: function (value) { + + if (value !== this._pageAlignVertically) + { + this._pageAlignVertically = value; + this.queueUpdate(true); + } + + } + +}); + +/** +* Returns true if the browser is in fullscreen mode, otherwise false. +* @name Phaser.ScaleManager#isFullScreen +* @property {boolean} isFullScreen +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", { + + get: function () { + return !!(document['fullscreenElement'] || + document['webkitFullscreenElement'] || + document['mozFullScreenElement'] || + document['msFullscreenElement']); + } + +}); + +/** +* Returns true if the screen orientation is in portrait mode. +* +* @name Phaser.ScaleManager#isPortrait +* @property {boolean} isPortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'portrait'; + } + +}); + +/** +* Returns true if the screen orientation is in landscape mode. +* +* @name Phaser.ScaleManager#isLandscape +* @property {boolean} isLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", { + + get: function () { + return this.classifyOrientation(this.screenOrientation) === 'landscape'; + } + +}); + +/** +* Returns true if the game dimensions are portrait (height > width). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGamePortrait +* @property {boolean} isGamePortrait +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", { + + get: function () { + return (this.height > this.width); + } + +}); + +/** +* Returns true if the game dimensions are landscape (width > height). +* This is especially useful to check when using the RESIZE scale mode +* but wanting to maintain game orientation on desktop browsers, +* where typically the screen orientation will always be landscape regardless of the browser viewport. +* +* @name Phaser.ScaleManager#isGameLandscape +* @property {boolean} isGameLandscape +* @readonly +*/ +Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", { + + get: function () { + return (this.width > this.height); + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A collection of methods for displaying debug information about game objects. +* +* If your game is running in Canvas mode, then you should invoke all of the Debug methods from +* your games `render` function. This is because they are drawn directly onto the game canvas +* itself, so if you call any debug methods outside of `render` they are likely to be overwritten +* by the game itself. +* +* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture +* to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug +* in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! +* +* @class Phaser.Utils.Debug +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Utils.Debug = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.Image} sprite - If debugging in WebGL mode, this is the Image displaying the debug {@link #bmd BitmapData}. + */ + this.sprite = null; + + /** + * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.context = null; + + /** + * @property {string} font - The font that the debug information is rendered in. + * @default + */ + this.font = '14px Courier'; + + /** + * @property {number} columnWidth - The spacing between columns. + * @default + */ + this.columnWidth = 100; + + /** + * @property {number} lineHeight - The line height between the debug text. + * @default + */ + this.lineHeight = 16; + + /** + * @property {number} lineWidth - The width of the stroke on lines and shapes. A positive number. + * @default + */ + this.lineWidth = 1; + + /** + * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. + * @default + */ + this.renderShadow = true; + + /** + * @property {string} currentColor - The color last set by {@link #start} or {@link #text}. + * @default + * @protected + */ + this.currentColor = null; + + /** + * @property {number} currentX - The current X position the debug information will be rendered at. + * @default + */ + this.currentX = 0; + + /** + * @property {number} currentY - The current Y position the debug information will be rendered at. + * @default + */ + this.currentY = 0; + + /** + * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it. + * @default + */ + this.currentAlpha = 1; + + /** + * @property {boolean} dirty - Does the canvas need re-rendering? + * @default + */ + this.dirty = false; + + /** + * @property {boolean} isDisabled - If `enableDebug: false` is passed to {@link Phaser.Game} or if Phaser is built without the Debug class, this will be true. + * @default + * @readonly + */ + this.isDisabled = false; + + /** + * @property {Phaser.Line} _line - A reusable rendering line. + * @private + */ + this._line = null; + + /** + * @property {Phaser.Rectangle} _rect - A reusable rendering rectangle. + * @private + */ + this._rect = null; + +}; + +Phaser.Utils.Debug.prototype = { + + /** + * Internal method that boots the debug displayer. + * + * @method Phaser.Utils.Debug#boot + * @protected + */ + boot: function () { + + if (this.game.renderType === Phaser.CANVAS) + { + this.context = this.game.context; + } + else + { + this.bmd = new Phaser.BitmapData(this.game, '__DEBUG', this.game.width, this.game.height, true); + this.sprite = this.game.make.image(0, 0, this.bmd); + this.game.stage.addChild(this.sprite); + + this.game.scale.onSizeChange.add(this.resize, this); + + this.canvas = Phaser.CanvasPool.create(this, this.game.width, this.game.height); + this.context = this.canvas.getContext('2d'); + } + + this._line = new Phaser.Line(); + this._rect = new Phaser.Rectangle(); + + }, + + /** + * Internal method that resizes the BitmapData and Canvas. + * Called by ScaleManager.onSizeChange only in WebGL mode. + * + * @method Phaser.Utils.Debug#resize + * @protected + */ + resize: function () { + + this.bmd.resize(this.game.width, this.game.height); + + this.canvas.width = this.game.width; + this.canvas.height = this.game.height; + + }, + + /** + * Internal method that clears the canvas (if a Sprite) ready for a new debug session. + * + * @method Phaser.Utils.Debug#preUpdate + * @protected + */ + preUpdate: function () { + + if (this.dirty && this.sprite) + { + this.bmd.clear(); + this.bmd.draw(this.canvas, 0, 0); + + this.context.clearRect(0, 0, this.game.width, this.game.height); + this.dirty = false; + } + + }, + + /** + * Clears the Debug canvas. + * + * @method Phaser.Utils.Debug#reset + */ + reset: function () { + + if (this.context) + { + this.context.clearRect(0, 0, this.game.width, this.game.height); + } + + if (this.sprite) + { + this.bmd.clear(); + } + + }, + + /** + * Internal method that resets and starts the debug output values. + * + * @method Phaser.Utils.Debug#start + * @protected + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + * @param {number} [columnWidth=0] - The spacing between columns. + */ + start: function (x, y, color, columnWidth) { + + if (typeof x !== 'number') { x = 0; } + if (typeof y !== 'number') { y = 0; } + color = color || 'rgb(255,255,255)'; + if (columnWidth === undefined) { columnWidth = 0; } + + this.currentX = x; + this.currentY = y; + this.currentColor = color; + this.columnWidth = columnWidth; + + this.dirty = true; + + this.context.save(); + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.strokeStyle = color; + this.context.fillStyle = color; + this.context.font = this.font; + this.context.globalAlpha = this.currentAlpha; + + }, + + /** + * Internal method that stops the debug output. + * + * @method Phaser.Utils.Debug#stop + * @protected + */ + stop: function () { + + this.context.restore(); + + }, + + /** + * Internal method that outputs a single line of text split over as many columns as needed, one per parameter. + * + * @method Phaser.Utils.Debug#line + * @protected + */ + line: function () { + + var x = this.currentX; + + for (var i = 0; i < arguments.length; i++) + { + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(arguments[i], x + 1, this.currentY + 1); + this.context.fillStyle = this.currentColor; + } + + this.context.fillText(arguments[i], x, this.currentY); + + x += this.columnWidth; + } + + this.currentY += this.lineHeight; + + }, + + /** + * Render Sound Manager information, including volume, mute, audio mode, and locked status. + * + * @method Phaser.Utils.Debug#sound + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + sound: function (x, y, color) { + + var sound = this.game.sound; + + this.start(x, y, color); + + if (sound.noAudio) + { + this.line('Audio is disabled'); + } + else + { + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Mute on pause: ' + sound.muteOnPause); + this.line('Using: ' + (sound.usingWebAudio ? ('Web Audio - ' + sound.context.state) : 'Audio Tag')); + this.line('Touch locked: ' + sound.touchLocked); + } + + this.stop(); + + }, + + /** + * Render Sound information, including decoded state, duration, volume and more. + * + * @method Phaser.Utils.Debug#soundInfo + * @param {Phaser.Sound} sound - The sound object to debug. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + soundInfo: function (sound, x, y, color) { + + this.start(x, y, color); + this.line('Sound: ' + sound.key + ' Touch locked: ' + sound.game.sound.touchLocked); + this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback); + this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding); + this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying + ' Loop: ' + sound.loop); + this.line('Time: ' + sound.currentTime); + this.line('Volume: ' + sound.volume.toFixed(2) + (sound.mute ? ' (Mute)' : '')); + this.line('Using: ' + (sound.usingWebAudio ? 'Web Audio' : 'Audio Tag')); + + if (sound.currentMarker !== '') + { + this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')'); + this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop); + this.line('Position: ' + sound.position); + } + + this.stop(); + + }, + + /** + * Marks the follow {@link #target} and {@link #deadzone}. + * + * @method Phaser.Utils.Debug#camera + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {string} [color] - Color of the debug shapes to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the shapes filled (default, true) or stroked (false). + */ + camera: function (camera, color, filled) { + + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + if (deadzone) + { + this._rect.setTo(view.x + deadzone.x, view.y + deadzone.y, deadzone.width, deadzone.height); + this.rectangle(this._rect, color, filled); + } + + if (target) + { + this._line.setTo(view.centerX, view.centerY, target.x, target.y); + this.geom(this._line, color, filled); + this.geom(target, color, false, 3); + } + + }, + + /** + * Render camera information including dimensions and location. + * + * @method Phaser.Utils.Debug#cameraInfo + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + cameraInfo: function (camera, x, y, color) { + + var bounds = camera.bounds; + var deadzone = camera.deadzone; + var target = camera.target; + var view = camera.view; + + this.start(x, y, color); + this.line('Camera (' + camera.width + ' x ' + camera.height + ')'); + this.line('x: ' + camera.x + ' y: ' + camera.y); + this.line('Bounds: ' + (bounds ? ('x: ' + bounds.x + ' y: ' + bounds.y + ' w: ' + bounds.width + ' h: ' + bounds.height) : 'none')); + this.line('View: x: ' + view.x + ' y: ' + view.y + ' w: ' + view.width + ' h: ' + view.height); + this.line('Deadzone: ' + (deadzone ? ('x: ' + deadzone.x + ' y: ' + deadzone.y + ' w: ' + deadzone.width + ' h: ' + deadzone.height) : deadzone)); + this.line('Total in view: ' + camera.totalInView); + this.line('At limit: x: ' + camera.atLimit.x + ' y: ' + camera.atLimit.y); + this.line('Target: ' + (target ? (target.name || target) : 'none')); + this.stop(); + + }, + + /** + * Render Timer information. + * + * @method Phaser.Utils.Debug#timer + * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + timer: function (timer, x, y, color) { + + this.start(x, y, color); + this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')'); + this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration); + this.line('Paused: ' + timer.paused + ' Length: ' + timer.length); + this.stop(); + + }, + + /** + * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text. + * + * @method Phaser.Utils.Debug#pointer + * @param {Phaser.Pointer} pointer - The Pointer you wish to display. + * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. + * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down. + * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false). + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + pointer: function (pointer, hideIfUp, downColor, upColor, color) { + + if (pointer == null) + { + return; + } + + if (hideIfUp === undefined) { hideIfUp = false; } + downColor = downColor || 'rgba(0,255,0,0.5)'; + upColor = upColor || 'rgba(255,0,0,0.5)'; + + if (hideIfUp === true && pointer.isUp === true) + { + return; + } + + this.start(pointer.x, pointer.y - 100, color); + this.context.beginPath(); + this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2); + + if (pointer.active) + { + this.context.fillStyle = downColor; + } + else + { + this.context.fillStyle = upColor; + } + + this.context.fill(); + this.context.closePath(); + + // Render the points + this.context.beginPath(); + this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y); + this.context.lineTo(pointer.position.x, pointer.position.y); + this.context.lineWidth = 2; + this.context.stroke(); + this.context.closePath(); + + // Render the text + this.line('ID: ' + pointer.id + " Active: " + pointer.active); + this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY); + this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y + " In: " + pointer.withinGame); + this.line('Duration: ' + pointer.duration + " ms"); + this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp); + this.stop(); + + }, + + /** + * Render Sprite Input Debug information. + * + * @method Phaser.Utils.Debug#spriteInputInfo + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInputInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')'); + this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1)); + this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0)); + this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0)); + this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut()); + this.stop(); + + }, + + /** + * Renders Phaser.Key object information. + * + * @method Phaser.Utils.Debug#key + * @param {Phaser.Key} key - The Key to render the information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + key: function (key, x, y, color) { + + this.start(x, y, color, 150); + + this.line('Key:', key.keyCode, 'isDown:', key.isDown); + this.line('justDown:', key.justDown, 'justUp:', key.justUp); + this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0)); + + this.stop(); + + }, + + /** + * Render debug information about the Input object. + * + * @method Phaser.Utils.Debug#inputInfo + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + inputInfo: function (x, y, color) { + + this.start(x, y, color); + this.line('Input'); + this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y); + this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY); + this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1)); + this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY); + this.stop(); + + }, + + /** + * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! + * + * @method Phaser.Utils.Debug#spriteBounds + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + spriteBounds: function (sprite, color, filled) { + + var bounds = sprite.getBounds(); + + bounds.x += this.game.camera.x; + bounds.y += this.game.camera.y; + + this.rectangle(bounds, color, filled); + + }, + + /** + * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it + * + * @method Phaser.Utils.Debug#ropeSegments + * @param {Phaser.Rope} rope - The rope to display the segments of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ + ropeSegments: function (rope, color, filled) { + + var segments = rope.segments; + + var self = this; + + segments.forEach(function(segment) { + self.rectangle(segment, color, filled); + }, this); + + }, + + /** + * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. + * + * @method Phaser.Utils.Debug#spriteInfo + * @param {Phaser.Sprite} sprite - The Sprite to display the information of. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteInfo: function (sprite, x, y, color) { + + this.start(x, y, color); + + this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y); + this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1)); + this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1)); + this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera); + this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1)); + + this.stop(); + + }, + + /** + * Renders the sprite coordinates in local, positional and world space. + * + * @method Phaser.Utils.Debug#spriteCoords + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + spriteCoords: function (sprite, x, y, color) { + + this.start(x, y, color, 100); + + if (sprite.name) + { + this.line(sprite.name); + } + + this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2)); + this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2)); + this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2)); + + this.stop(); + + }, + + /** + * Renders Line information in the given color. + * + * @method Phaser.Utils.Debug#lineInfo + * @param {Phaser.Line} line - The Line to display the data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + lineInfo: function (line, x, y, color) { + + this.start(x, y, color, 80); + this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2)); + this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2)); + this.line('length:', line.length.toFixed(2), 'angle:', line.angle); + this.stop(); + + }, + + /** + * Renders a single pixel at the given size. + * + * @method Phaser.Utils.Debug#pixel + * @param {number} x - X position of the pixel to be rendered. + * @param {number} y - Y position of the pixel to be rendered. + * @param {string} [color] - Color of the pixel (format is css color string). + * @param {number} [size=2] - The 'size' to render the pixel at. + */ + pixel: function (x, y, color, size) { + + size = size || 2; + + this.start(); + this.context.fillStyle = color; + this.context.fillRect(x, y, size, size); + this.stop(); + + }, + + /** + * Renders a Phaser geometry object including Rectangle, Circle, Ellipse, Point or Line. + * + * @method Phaser.Utils.Debug#geom + * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Ellipse|Phaser.Point|Phaser.Line} object - The geometry object to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) + * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle,3 = Point, 4 = Line and 5 = Ellipse. + */ + geom: function (object, color, filled, forceType) { + + if (filled === undefined) { filled = true; } + if (forceType === undefined) { forceType = 0; } + + color = color || 'rgba(0,255,0,0.4)'; + + this.start(); + + this.context.fillStyle = color; + this.context.strokeStyle = color; + this.context.lineWidth = this.lineWidth; + + if (object instanceof Phaser.Rectangle || forceType === 1) + { + if (filled) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + } + else if (object instanceof Phaser.Circle || forceType === 2) + { + this.context.beginPath(); + this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + else if (object instanceof Phaser.Point || forceType === 3) + { + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4); + } + else if (object instanceof Phaser.Line || forceType === 4) + { + this.context.beginPath(); + this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y); + this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y); + this.context.closePath(); + this.context.stroke(); + } + else if (object instanceof Phaser.Ellipse || forceType === 5) + { + this.context.beginPath(); + this.context.ellipse(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width/2, object.height/2, 0,2 * Math.PI,false); + this.context.closePath(); + + if (filled) + { + this.context.fill(); + } + else + { + this.context.stroke(); + } + } + + this.stop(); + + }, + + /** + * Renders a Rectangle. + * + * @method Phaser.Utils.Debug#rectangle + * @param {Phaser.Rectangle|object} object - The rectangle to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as filled (default, true) or a stroked (false) + */ + rectangle: function (object, color, filled) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0, 255, 0, 0.4)'; + + this.start(); + + if (filled) + { + this.context.fillStyle = color; + this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + else + { + this.context.lineWidth = this.lineWidth; + this.context.strokeStyle = color; + this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height); + } + + this.stop(); + + }, + + /** + * Render a string of text. + * + * @method Phaser.Utils.Debug#text + * @param {string} text - The line of text to draw. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {string} [font] - The font of text to draw. + */ + text: function (text, x, y, color, font) { + + color = color || 'rgb(255,255,255)'; + font = font || '16px Courier'; + + this.start(); + this.context.font = font; + + if (this.renderShadow) + { + this.context.fillStyle = 'rgb(0,0,0)'; + this.context.fillText(text, x + 1, y + 1); + } + + this.context.fillStyle = color; + this.context.fillText(text, x, y); + + this.stop(); + + }, + + /** + * Visually renders a QuadTree to the display. + * + * @method Phaser.Utils.Debug#quadTree + * @param {Phaser.QuadTree} quadtree - The quadtree to render. + * @param {string} color - The color of the lines in the quadtree. + */ + quadTree: function (quadtree, color) { + + color = color || 'rgba(255,0,0,0.3)'; + + this.start(); + + var bounds = quadtree.bounds; + + if (quadtree.nodes.length === 0) + { + this.context.strokeStyle = color; + this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height); + this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier'); + + this.context.strokeStyle = 'rgb(0,255,0)'; + + for (var i = 0; i < quadtree.objects.length; i++) + { + this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height); + } + } + else + { + for (var i = 0; i < quadtree.nodes.length; i++) + { + this.quadTree(quadtree.nodes[i]); + } + } + + this.stop(); + + }, + + /** + * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. + * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. + * To display a P2 Physics body you should enable debug mode on the body when creating it. + * + * @method Phaser.Utils.Debug#body + * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false) + */ + body: function (sprite, color, filled) { + + if (sprite.body) + { + this.start(); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled, this.lineWidth); + } + else if (sprite.body.type === Phaser.Physics.NINJA) + { + Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color); + } + + this.stop(); + } + + }, + + /** + * Render a Sprites Physic Body information. + * + * @method Phaser.Utils.Debug#bodyInfo + * @param {Phaser.Sprite} sprite - The sprite to be rendered. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ + bodyInfo: function (sprite, x, y, color) { + + if (sprite.body) + { + this.start(x, y, color, 210); + + if (sprite.body.type === Phaser.Physics.ARCADE) + { + Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body); + } + else if (sprite.body.type === Phaser.Physics.BOX2D) + { + this.game.physics.box2d.renderBodyInfo(this, sprite.body); + } + + this.stop(); + } + + }, + + /** + * Renders 'debug draw' data for the Box2D world if it exists. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by + * the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dWorld + */ + box2dWorld: function () { + + this.start(); + + this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0); + this.game.physics.box2d.renderDebugDraw(this.context); + + this.stop(); + + }, + + /** + * Renders 'debug draw' data for the given Box2D body. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dBody + * @param {Phaser.Physics.Box2D.Body} body - The body to be rendered. + * @param {string} [color='rgb(0,255,0)'] - Color of the rendering (format is css color string). + */ + box2dBody: function (body, color) { + + this.start(); + Phaser.Physics.Box2D.renderBody(this.context, body, color); + this.stop(); + + }, + + /** + * Call this function from the Dev Tools console. + * + * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. + * + * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) + * + * @method Phaser.Utils.Debug#displayList + * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World. + */ + displayList: function (displayObject) { + + if (displayObject === undefined) { displayObject = this.game.world; } + + if (displayObject.hasOwnProperty('renderOrderID')) + { + console.log('[' + displayObject.renderOrderID + ']', displayObject); + } + else + { + console.log('[]', displayObject); + } + + if (displayObject.children && displayObject.children.length > 0) + { + for (var i = 0; i < displayObject.children.length; i++) + { + this.game.debug.displayList(displayObject.children[i]); + } + } + + }, + + /** + * Prints a description of the {@link Phaser.Game#renderer renderer} and render session. + * + * @method Phaser.Utils.Debug#renderer + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + renderer: function (x, y, color) { + + var r = this.game.renderer; + var s = r.renderSession; + + this.start(x, y, color); + + this.line((r.gl ? 'WebGL' : 'Canvas') + ' Renderer (' + r.width + ' x ' + r.height + ')'); + this.line('autoResize: ' + r.autoResize); + this.line('clearBeforeRender: ' + r.clearBeforeRender); + this.line('resolution: ' + r.resolution); + this.line('transparent: ' + r.transparent); + this.line('renderSession:'); + + if (r.gl) + { + this.line(' currentBatchedTextures: ('+ r.currentBatchedTextures.length + ')'); + + for (var i = 0; i < r.currentBatchedTextures.length; i++) + { + this.line(' ' + r.currentBatchedTextures[i]); + } + + this.line(' drawCount: ' + s.drawCount); + this.line(' maxTextures: ' + r.maxTextures); + this.line(' maxTextureSize: ' + r.maxTextureSize); + this.line(' maxTextureAvailableSpace: ' + s.maxTextureAvailableSpace); + this.line(' roundPixels: ' + s.roundPixels); + } + else + { + this.line(' roundPixels: ' + s.roundPixels); + this.line(' scaleMode: ' + (s.scaleMode === 0 ? 'LINEAR' : (s.scaleMode === 1 ? 'NEAREST' : s.scaleMode))); + } + + this.stop(); + + }, + + canvasPool: function (x, y, color, columnWidth) { + var pool = Phaser.CanvasPool; + + this.start(x, y, color, columnWidth || 100); + this.line('Canvas Pool'); + this.line('Used:', pool.getTotal()); + this.line('Free:', pool.getFree()); + this.line('Total:', pool.length); + this.stop(); + }, + + /** + * Render each physics {@link #body} in a group. + * + * @method Phaser.Utils.Debug#physicsGroup + * @param {Phaser.Group} group - A group containing physics-enabled sprites. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false). + * @param {boolean} [checkExists=false] Render only children with `exists=true`. + */ + physicsGroup: function (group, color, filled, checkExists) { + + group.forEach(this.body, this, checkExists, color, filled); + + }, + + /** + * Prints Phaser {@link Phaser.VERSION version}, {@link Phaser.Game.#renderType rendering mode}, and {@link Phaser.Device#webAudio device audio support}. + * + * @method Phaser.Utils.Debug#phaser + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + phaser: function (x, y, color) { + + this.text('Phaser v' + Phaser.VERSION + ' ' + + (this.game.renderType === Phaser.WEBGL ? 'WebGL' : 'Canvas') + ' ' + + (this.game.device.webAudio ? 'WebAudio' : 'HTML Audio'), + x, y, color, this.font); + + }, + + /** + * Prints game/canvas dimensions and {@link Phaser.ScaleManager game scale} settings. + * + * @method Phaser.Utils.Debug#scale + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + scale: function (x, y, color) { + + this.start(x, y, color); + + var scale = this.game.scale; + var factor = scale.scaleFactorInversed; + var bounds = scale._parentBounds; + var x = ' x '; + + this.line('Game: ' + this.game.width + x + this.game.height); + this.line('Canvas: ' + scale.width + x + scale.height + + ' (' + factor.x.toFixed(2) + x + factor.y.toFixed(2) + ')' + + ' [' + scale.aspectRatio.toFixed(2) + ']'); + this.line('Mode: ' + Phaser.ScaleManager.MODES[scale.currentScaleMode] + + (scale.currentScaleMode === Phaser.ScaleManager.USER_SCALE ? + (' (' + scale._userScaleFactor.x + x + scale._userScaleFactor.y + ')') : + '')); + this.line('Parent: ' + (scale.parentIsWindow ? 'window' : scale.parentNode) + + (bounds.empty ? '' : (' (' + bounds.width + x + bounds.height + ')'))); + this.line('Screen: ' + scale.classifyOrientation(scale.screenOrientation) + + (scale.incorrectOrientation ? ' (incorrect)' : '')); + + this.stop(); + + }, + + /** + * Prints the progress of a {@link Phaser.Loader}. + * + * Typically you would call this within a {@link State#loadRender} callback and pass `game.load` ({@link Phaser.Game#load}). + * + * You can enable {@link Phaser.Loader#resetLocked} to temporarily hold the loader in its 'complete' state. + * Just remember to disable it before restarting the loader (such as when changing states). + * + * @method Phaser.Utils.Debug#loader + * @param {Phaser.Loader} loader - The loader. Usually `game.load` ({@link Phaser.Game#load}). + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ + loader: function (loader, x, y, color) { + + var pad = Phaser.Utils.pad; + + this.start(x, y, color); + + if (loader.hasLoaded) + { + this.line('Complete' + (loader.resetLocked ? ' [locked]' : '')); + } + else if (loader.isLoading) + { + this.line('Loading'); + } + else + { + this.line('Not started'); + } + + if (!loader.hasLoaded || loader.resetLocked) + { + this.line('Progress: ' + (pad(loader.progress, 3) + '%')); + this.line('Files: ' + loader._loadedFileCount + ' of ' + + loader._totalFileCount); + this.line('Packs: ' + loader._loadedPackCount + ' of ' + + loader._loadedPackCount); + } + + this.stop(); + + }, + + /** + * Destroy this object. + * + * @method Phaser.Utils.Debug#destroy + */ + destroy: function () { + + Phaser.CanvasPool.remove(this); + + } + +}; + +Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* DOM utility class. +* +* Provides a useful Window and Element functions as well as cross-browser compatibility buffer. +* +* Some code originally derived from {@link https://github.com/ryanve/verge verge}. +* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. +* +* @class Phaser.DOM +* @static +*/ +Phaser.DOM = { + + /** + * Get the [absolute] position of the element relative to the Document. + * + * The value may vary slightly as the page is scrolled due to rounding errors. + * + * @method Phaser.DOM.getOffset + * @param {DOMElement} element - The targeted element that we want to retrieve the offset. + * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. + * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. + */ + getOffset: function (element, point) { + + point = point || new Phaser.Point(); + + var box = element.getBoundingClientRect(); + + var scrollTop = Phaser.DOM.scrollY; + var scrollLeft = Phaser.DOM.scrollX; + var clientTop = document.documentElement.clientTop; + var clientLeft = document.documentElement.clientLeft; + + point.x = box.left + scrollLeft - clientLeft; + point.y = box.top + scrollTop - clientTop; + + return point; + + }, + + /** + * A cross-browser element.getBoundingClientRect method with optional cushion. + * + * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. + * Its properties match the native rectangle. + * The cushion parameter is an amount of pixels (+/-) to cushion the element. + * It adjusts the measurements such that it is possible to detect when an element is near the viewport. + * + * @method Phaser.DOM.getBounds + * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for. + * @param {number} [cushion] - A +/- pixel adjustment amount. + * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. + */ + getBounds: function (element, cushion) { + + if (cushion === undefined) { cushion = 0; } + + element = element && !element.nodeType ? element[0] : element; + + if (!element || element.nodeType !== 1) + { + return false; + } + else + { + return this.calibrate(element.getBoundingClientRect(), cushion); + } + + }, + + /** + * Calibrates element coordinates for `inLayoutViewport` checks. + * + * @method Phaser.DOM.calibrate + * @private + * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}` + * @param {number} [cushion] - A value to adjust the coordinates by. + * @return {object} The calibrated element coordinates + */ + calibrate: function (coords, cushion) { + + cushion = +cushion || 0; + + var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 }; + + output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion); + output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion); + + return output; + + }, + + /** + * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) + * + * @method Phaser.DOM.getAspectRatio + * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. + * @return {number} The aspect ratio. + */ + getAspectRatio: function (object) { + + object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object; + + var w = object['width']; + var h = object['height']; + + if (typeof w === 'function') + { + w = w.call(object); + } + + if (typeof h === 'function') + { + h = h.call(object); + } + + return w / h; + + }, + + /** + * Tests if the given DOM element is within the Layout viewport. + * + * The optional cushion parameter allows you to specify a distance. + * + * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. + * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. + * + * @method Phaser.DOM.inLayoutViewport + * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas. + * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport. + * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it. + */ + inLayoutViewport: function (element, cushion) { + + var r = this.getBounds(element, cushion); + + return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height; + + }, + + /** + * Returns the device screen orientation. + * + * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. + * + * Order of resolving: + * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. + * - Screen size ratio check - If fallback is 'screen', suited for desktops. + * - Viewport size ratio check - If fallback is 'viewport', suited for mobile. + * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. + * - Media query + * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..) + * + * See + * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) + * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) + * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx + * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries + * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation + * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation + * + * @method Phaser.DOM.getScreenOrientation + * @protected + * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'. + */ + getScreenOrientation: function (primaryFallback) { + + var screen = window.screen; + var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; + + if (orientation && typeof orientation.type === 'string') + { + // Screen Orientation API specification + return orientation.type; + } + else if (typeof orientation === 'string') + { + // moz/ms-orientation are strings + return orientation; + } + + var PORTRAIT = 'portrait-primary'; + var LANDSCAPE = 'landscape-primary'; + + if (primaryFallback === 'screen') + { + return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'viewport') + { + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + } + else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number') + { + // This may change by device based on "natural" orientation. + return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE; + } + else if (window.matchMedia) + { + if (window.matchMedia("(orientation: portrait)").matches) + { + return PORTRAIT; + } + else if (window.matchMedia("(orientation: landscape)").matches) + { + return LANDSCAPE; + } + } + + return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; + + }, + + /** + * The bounds of the Visual viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one} + * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers. + * + * Supported mobile: + * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} x - Scroll, left offset - eg. "scrollX" + * @property {number} y - Scroll, top offset - eg. "scrollY" + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + visualBounds: new Phaser.Rectangle(), + + /** + * The bounds of the Layout viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two}; + * but honoring the constraints as specified applicable viewport meta-tag. + * + * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see + * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}). + * + * This is _not_ representative of the Visual bounds: in particular the non-primary axis will + * generally be significantly larger than the screen height on mobile devices when running with a + * constrained viewport. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ + layoutBounds: new Phaser.Rectangle(), + + /** + * The size of the document / Layout viewport. + * + * This incorrectly reports the dimensions in IE. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Document width in pixels. + * @property {number} height - Document height in pixels. + * @readonly + */ + documentBounds: new Phaser.Rectangle() + +}; + +Phaser.Device.whenReady(function (device) { + + // All target browsers should support page[XY]Offset. + var scrollX = window && ('pageXOffset' in window) ? + function () { return window.pageXOffset; } : + function () { return document.documentElement.scrollLeft; }; + + var scrollY = window && ('pageYOffset' in window) ? + function () { return window.pageYOffset; } : + function () { return document.documentElement.scrollTop; }; + + /** + * A cross-browser window.scrollX. + * + * @name Phaser.DOM.scrollX + * @property {number} scrollX + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollX", { + get: scrollX + }); + + /** + * A cross-browser window.scrollY. + * + * @name Phaser.DOM.scrollY + * @property {number} scrollY + * @readonly + * @protected + */ + Object.defineProperty(Phaser.DOM, "scrollY", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "x", { + get: scrollX + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "y", { + get: scrollY + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "y", { + value: 0 + }); + + var treatAsDesktop = device.desktop && + (document.documentElement.clientWidth <= window.innerWidth) && + (document.documentElement.clientHeight <= window.innerHeight); + + // Desktop browsers align the layout viewport with the visual viewport. + // This differs from mobile browsers with their zooming design. + // Ref. http://quirksmode.org/mobile/tableViewport.html + if (treatAsDesktop) + { + + // PST- When scrollbars are not included this causes upstream issues in ScaleManager. + // So reverted to the old "include scrollbars." + var clientWidth = function () { + return Math.max(window.innerWidth, document.documentElement.clientWidth); + }; + var clientHeight = function () { + return Math.max(window.innerHeight, document.documentElement.clientHeight); + }; + + // Interested in area sans-scrollbar + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: clientHeight + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + get: clientWidth + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + get: clientHeight + }); + + } else { + + Object.defineProperty(Phaser.DOM.visualBounds, "width", { + get: function () { + return window.innerWidth; + } + }); + + Object.defineProperty(Phaser.DOM.visualBounds, "height", { + get: function () { + return window.innerHeight; + } + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "width", { + + get: function () { + var a = document.documentElement.clientWidth; + var b = window.innerWidth; + + return a < b ? b : a; // max + } + + }); + + Object.defineProperty(Phaser.DOM.layoutBounds, "height", { + + get: function () { + var a = document.documentElement.clientHeight; + var b = window.innerHeight; + + return a < b ? b : a; // max + } + + }); + + } + + // For Phaser.DOM.documentBounds + // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html + + Object.defineProperty(Phaser.DOM.documentBounds, "x", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "y", { + value: 0 + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "width", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth); + } + + }); + + Object.defineProperty(Phaser.DOM.documentBounds, "height", { + + get: function () { + var d = document.documentElement; + return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight); + } + + }); + +}, null, true); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* ArraySet is a Set data structure (items must be unique within the set) that also maintains order. +* This allows specific items to be easily added or removed from the Set. +* +* Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. +* +* This used primarily by the Input subsystem. +* +* @class Phaser.ArraySet +* @constructor +* @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet. +*/ +Phaser.ArraySet = function (list) { + + /** + * Current cursor position as established by `first` and `next`. + * @property {integer} position + * @default + */ + this.position = 0; + + /** + * The backing array. + * @property {any[]} list + */ + this.list = list || []; + +}; + +Phaser.ArraySet.prototype = { + + /** + * Adds a new element to the end of the list. + * If the item already exists in the list it is not moved. + * + * @method Phaser.ArraySet#add + * @param {any} item - The element to add to this list. + * @return {any} The item that was added. + */ + add: function (item) { + + if (!this.exists(item)) + { + this.list.push(item); + } + + return item; + + }, + + /** + * Gets the index of the item in the list, or -1 if it isn't in the list. + * + * @method Phaser.ArraySet#getIndex + * @param {any} item - The element to get the list index for. + * @return {integer} The index of the item or -1 if not found. + */ + getIndex: function (item) { + + return this.list.indexOf(item); + + }, + + /** + * Gets an item from the set based on the property strictly equaling the value given. + * Returns null if not found. + * + * @method Phaser.ArraySet#getByKey + * @param {string} property - The property to check against the value. + * @param {any} value - The value to check if the property strictly equals. + * @return {any} The item that was found, or null if nothing matched. + */ + getByKey: function (property, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i][property] === value) + { + return this.list[i]; + } + } + + return null; + + }, + + /** + * Checks for the item within this list. + * + * @method Phaser.ArraySet#exists + * @param {any} item - The element to get the list index for. + * @return {boolean} True if the item is found in the list, otherwise false. + */ + exists: function (item) { + + return (this.list.indexOf(item) > -1); + + }, + + /** + * Removes all the items. + * + * @method Phaser.ArraySet#reset + */ + reset: function () { + + this.list.length = 0; + + }, + + /** + * Removes the given element from this list if it exists. + * + * @method Phaser.ArraySet#remove + * @param {any} item - The item to be removed from the list. + * @return {any} item - The item that was removed. + */ + remove: function (item) { + + var idx = this.list.indexOf(item); + + if (idx > -1) + { + this.list.splice(idx, 1); + return item; + } + + }, + + /** + * Sets the property `key` to the given value on all members of this list. + * + * @method Phaser.ArraySet#setAll + * @param {any} key - The property of the item to set. + * @param {any} value - The value to set the property to. + */ + setAll: function (key, value) { + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + this.list[i][key] = value; + } + } + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * + * If the `key` property is present it must be a function. + * The function is invoked using the item as the context. + * + * @method Phaser.ArraySet#callAll + * @param {string} key - The name of the property with the function to call. + * @param {...*} parameter - Additional parameters that will be passed to the callback. + */ + callAll: function (key) { + + var args = Array.prototype.slice.call(arguments, 1); + + var i = this.list.length; + + while (i--) + { + if (this.list[i] && this.list[i][key]) + { + this.list[i][key].apply(this.list[i], args); + } + } + + }, + + /** + * Removes every member from this ArraySet and optionally destroys it. + * + * @method Phaser.ArraySet#removeAll + * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set. + */ + removeAll: function (destroy) { + + if (destroy === undefined) { destroy = false; } + + var i = this.list.length; + + while (i--) + { + if (this.list[i]) + { + var item = this.remove(this.list[i]); + + if (destroy) + { + item.destroy(); + } + } + } + + this.position = 0; + this.list = []; + + } + +}; + +/** +* Number of items in the ArraySet. Same as `list.length`. +* +* @name Phaser.ArraySet#total +* @property {integer} total +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "total", { + + get: function () { + return this.list.length; + } + +}); + +/** +* Returns the first item and resets the cursor to the start. +* +* @name Phaser.ArraySet#first +* @property {any} first +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "first", { + + get: function () { + + this.position = 0; + + if (this.list.length > 0) + { + return this.list[0]; + } + else + { + return null; + } + + } + +}); + +/** +* Returns the the next item (based on the cursor) and advances the cursor. +* +* @name Phaser.ArraySet#next +* @property {any} next +*/ +Object.defineProperty(Phaser.ArraySet.prototype, "next", { + + get: function () { + + if (this.position < this.list.length) + { + this.position++; + + return this.list[this.position]; + } + else + { + return null; + } + + } + +}); + +Phaser.ArraySet.prototype.constructor = Phaser.ArraySet; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Utility functions for dealing with Arrays. +* +* @class Phaser.ArrayUtils +* @static +*/ +Phaser.ArrayUtils = { + + /** + * Fetch a random entry from the given array. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.getRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was selected. + */ + getRandomItem: function (objects, startIndex, length) { + + if (objects === null) { return null; } + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + + return objects[randomIndex] === undefined ? null : objects[randomIndex]; + + }, + + /** + * Removes a random object from the given array and returns it. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.removeRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was removed. + */ + removeRandomItem: function (objects, startIndex, length) { + + if (objects == null) { // undefined or null + return null; + } + + if (startIndex === undefined) { startIndex = 0; } + if (length === undefined) { length = objects.length; } + + var randomIndex = startIndex + Math.floor(Math.random() * length); + if (randomIndex < objects.length) + { + var removed = objects.splice(randomIndex, 1); + return removed[0] === undefined ? null : removed[0]; + } + else + { + return null; + } + + }, + + /** + * Remove one or more items at the given index and reorder the array. + * + * The new array length will be `array.length - count`. + * + * This is an alternative to `array.splice(startIndex, count)`. + * + * @see https://github.com/mreinstein/remove-array-items + * @see https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ + * + * @method Phaser.ArrayUtils.remove + * @param {any[]} array + * @param {integer} startIndex + * @param {integer} [count=1] + * @return {any[]} The modified array. + */ + remove: function (array, startIndex, count) + { + var length = array.length; + + if (startIndex >= length || count === 0) { return; } + + if (count == null) { count = 1; } + + var newLength = length - count; + + for (var i = startIndex; i < newLength; ++i) + { + array[i] = array[i + count]; + } + + array.length = newLength; + }, + + /** + * A standard Fisher-Yates Array shuffle implementation which modifies the array in place. + * + * @method Phaser.ArrayUtils.shuffle + * @param {any[]} array - The array to shuffle. + * @return {any[]} The original array, now shuffled. + */ + shuffle: function (array) { + + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; + + }, + + /** + * Transposes the elements of the given matrix (array of arrays). + * + * @method Phaser.ArrayUtils.transposeMatrix + * @param {Array} array - The matrix to transpose. + * @return {Array} A new transposed matrix + */ + transposeMatrix: function (array) { + + var sourceRowCount = array.length; + var sourceColCount = array[0].length; + + var result = new Array(sourceColCount); + + for (var i = 0; i < sourceColCount; i++) + { + result[i] = new Array(sourceRowCount); + + for (var j = sourceRowCount - 1; j > -1; j--) + { + result[i][j] = array[j][i]; + } + } + + return result; + + }, + + /** + * Rotates the given matrix (array of arrays). + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @method Phaser.ArrayUtils.rotateMatrix + * @param {Array} matrix - The array to rotate; this matrix _may_ be altered. + * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). + * @return {Array} The rotated matrix. The source matrix should be discarded for the returned matrix. + */ + rotateMatrix: function (matrix, direction) { + + if (typeof direction !== 'string') + { + direction = ((direction % 360) + 360) % 360; + } + + if (direction === 90 || direction === -270 || direction === 'rotateLeft') + { + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + matrix = matrix.reverse(); + } + else if (direction === -90 || direction === 270 || direction === 'rotateRight') + { + matrix = matrix.reverse(); + matrix = Phaser.ArrayUtils.transposeMatrix(matrix); + } + else if (Math.abs(direction) === 180 || direction === 'rotate180') + { + for (var i = 0; i < matrix.length; i++) + { + matrix[i].reverse(); + } + + matrix = matrix.reverse(); + } + + return matrix; + + }, + + /** + * Snaps a value to the nearest value in a sorted numeric array. + * The result will always be in the range `[first_value, last_value]`. + * + * @method Phaser.ArrayUtils.findClosest + * @param {number} value - The search value + * @param {number[]} arr - The input array which _must_ be sorted. + * @return {number} The nearest value found. + */ + findClosest: function (value, arr) { + + if (!arr.length) + { + return NaN; + } + else if (arr.length === 1 || value < arr[0]) + { + return arr[0]; + } + + var i = 1; + while (arr[i] < value) { + i++; + } + + var low = arr[i - 1]; + var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; + + return ((high - value) <= (value - low)) ? high : low; + + }, + + /** + * Moves the element from the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ F, A, B, C, D, E ]` + * + * See also Phaser.ArrayUtils.rotateLeft. + * + * @method Phaser.ArrayUtils.rotateRight + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The shifted value. + */ + rotateRight: function (array) { + + var s = array.pop(); + array.unshift(s); + + return s; + + }, + + /** + * Moves the element from the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ B, C, D, E, F, A ]` + * + * See also Phaser.ArrayUtils.rotateRight + * + * @method Phaser.ArrayUtils.rotateLeft + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The rotated value. + */ + rotateLeft: function (array) { + + var s = array.shift(); + array.push(s); + + return s; + + }, + + /** + * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]` (or `[0, start]`, if `end` is omitted). + * This is equivalent to `numberArrayStep(start, 1 + end, 1)`. + * + * When exactly one argument is passed, it's used as `end` and 0 is used as `start`. The length of the result is (1 + end). + * + * ##### Examples + * + * ```javascript + * numberArray(3); // -> [0, 1, 2, 3] + * numberArray(0, 3); // -> [0, 1, 2, 3] + * numberArray(1, 3); // -> [1, 2, 3] + * ``` + * + * @method Phaser.ArrayUtils.numberArray + * @param {number} start - The minimum value the array starts with. + * @param {number} [end] - The maximum value the array contains. + * @return {number[]} The array of number values. + */ + numberArray: function (start, end) { + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + var result = []; + + for (var i = start; i <= end; i++) + { + result.push(i); + } + + return result; + + }, + + /** + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @method Phaser.ArrayUtils.numberArrayStep + * @param {number} start - The start of the range. + * @param {number} [end] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * @returns {Array} Returns the new array of numbers. + * @example + * Phaser.ArrayUtils.numberArrayStep(4); + * // => [0, 1, 2, 3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * Phaser.ArrayUtils.numberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * Phaser.ArrayUtils.numberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * Phaser.ArrayUtils.numberArrayStep(0); + * // => [] + */ + numberArrayStep: function (start, end, step) { + + if (start === undefined || start === null) { start = 0; } + + if (end === undefined || end === null) + { + end = start; + start = 0; + } + + if (step === undefined) { step = 1; } + + var result = []; + var total = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0); + + for (var i = 0; i < total; i++) + { + result.push(start); + start += step; + } + + return result; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A basic Linked List data structure. +* +* This implementation _modifies_ the `prev` and `next` properties of each item added: +* - The `prev` and `next` properties must be writable and should not be used for any other purpose. +* - Items _cannot_ be added to multiple LinkedLists at the same time. +* - Only objects can be added. +* +* @class Phaser.LinkedList +* @constructor +*/ +Phaser.LinkedList = function () { + + /** + * Next element in the list. + * @property {object} next + * @default + */ + this.next = null; + + /** + * Previous element in the list. + * @property {object} prev + * @default + */ + this.prev = null; + + /** + * First element in the list. + * @property {object} first + * @default + */ + this.first = null; + + /** + * Last element in the list. + * @property {object} last + * @default + */ + this.last = null; + + /** + * Number of elements in the list. + * @property {integer} total + * @default + */ + this.total = 0; + +}; + +Phaser.LinkedList.prototype = { + + /** + * Adds a new element to this linked list. + * + * @method Phaser.LinkedList#add + * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. + * @return {object} The item that was added. + */ + add: function (item) { + + // If the list is empty + if (this.total === 0 && this.first === null && this.last === null) + { + this.first = item; + this.last = item; + this.next = item; + item.prev = this; + this.total++; + return item; + } + + // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list) + this.last.next = item; + + item.prev = this.last; + + this.last = item; + + this.total++; + + return item; + + }, + + /** + * Resets the first, last, next and previous node pointers in this list. + * + * @method Phaser.LinkedList#reset + */ + reset: function () { + + this.first = null; + this.last = null; + this.next = null; + this.prev = null; + this.total = 0; + + }, + + /** + * Removes the given element from this linked list if it exists. + * + * @method Phaser.LinkedList#remove + * @param {object} item - The item to be removed from the list. + */ + remove: function (item) { + + if (this.total === 1) + { + this.reset(); + item.next = item.prev = null; + return; + } + + if (item === this.first) + { + // It was 'first', make 'first' point to first.next + this.first = this.first.next; + } + else if (item === this.last) + { + // It was 'last', make 'last' point to last.prev + this.last = this.last.prev; + } + + if (item.prev) + { + // make item.prev.next point to childs.next instead of item + item.prev.next = item.next; + } + + if (item.next) + { + // make item.next.prev point to item.prev instead of item + item.next.prev = item.prev; + } + + item.next = item.prev = null; + + if (this.first === null ) + { + this.last = null; + } + + this.total--; + + }, + + /** + * Calls a function on all members of this list, using the member as the context for the callback. + * The function must exist on the member. + * + * @method Phaser.LinkedList#callAll + * @param {function} callback - The function to call. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content +* quickly and easily, without the need for any external files. You can create textures for sprites and in +* coming releases we'll add dynamic sound effect generation support as well (like sfxr). +* +* Access this via `Game.create` (`this.game.create` from within a State object). +* +* @class Phaser.Create +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. + */ +Phaser.Create = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from. + */ + this.bmd = null; + + /** + * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses. + */ + this.canvas = null; + + /** + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ + this.ctx = null; + + /** + * @property {array} palettes - A range of 16 color palettes for use with sprite generation. + */ + this.palettes = [ + { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' }, + { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' }, + { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' }, + { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' } + ]; + +}; + +/** +* A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_ARNE = 0; + +/** +* A 16 color JMP inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JMP = 1; + +/** +* A 16 color CGA inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_CGA = 2; + +/** +* A 16 color C64 inspired palette. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_C64 = 3; + +/** +* A 16 color palette inspired by Japanese computers like the MSX. +* @constant +* @type {number} +*/ +Phaser.Create.PALETTE_JAPANESE_MACHINE = 4; + +Phaser.Create.prototype = { + + /** + * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite. + * + * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images + * rather than Phaser.Graphics objects, which are expensive to render and limited in scope. + * + * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts. + * + * For example: + * + * `var data = [ + * ' 333 ', + * ' 777 ', + * 'E333E', + * ' 333 ', + * ' 3 3 ' + * ];` + * + * `game.create.texture('bob', data);` + * + * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it + * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');` + * + * Use {@link Phaser.Loader#imageFromTexture} to preload an image of the same. + * + * @method Phaser.Create#texture + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {array} data - An array of pixel data. + * @param {integer} [pixelWidth=8] - The width of each pixel. + * @param {integer} [pixelHeight=8] - The height of each pixel. + * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + texture: function (key, data, pixelWidth, pixelHeight, palette, generateTexture, callback, callbackContext) { + + if (pixelWidth === undefined) { pixelWidth = 8; } + if (pixelHeight === undefined) { pixelHeight = pixelWidth; } + if (palette === undefined) { palette = 0; } + if (generateTexture === undefined) { generateTexture = true; } + + var w = data[0].length * pixelWidth; + var h = data.length * pixelHeight; + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(w, h); + this.bmd.clear(); + + // Draw it + for (var y = 0; y < data.length; y++) + { + var row = data[y]; + + for (var x = 0; x < row.length; x++) + { + var d = row[x]; + + if (d !== '.' && d !== ' ') + { + this.ctx.fillStyle = this.palettes[palette][d]; + this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight); + } + } + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Creates a grid texture based on the given dimensions. + * + * Use {@link Phaser.Loader#imageFromGrid} to preload an image of the same. + * + * @method Phaser.Create#grid + * @param {string} key - The key used to store this texture in the Phaser Cache. + * @param {integer} width - The width of the grid in pixels. + * @param {integer} height - The height of the grid in pixels. + * @param {integer} cellWidth - The width of the grid cells in pixels. + * @param {integer} cellHeight - The height of the grid cells in pixels. + * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`. + * @param {boolean} [generateTexture=true] - When false, a new BitmapData object is returned instead. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {?PIXI.Texture|Phaser.BitmapData} The newly generated texture, or a new BitmapData object if `generateTexture` is false, or `null` if a callback was passed and the texture isn't available yet. + */ + grid: function (key, width, height, cellWidth, cellHeight, color, generateTexture, callback, callbackContext) { + + if (generateTexture === undefined) { generateTexture = true; } + + // No bmd? Let's make one + if (this.bmd === null) + { + this.bmd = this.game.make.bitmapData(); + this.canvas = this.bmd.canvas; + this.ctx = this.bmd.context; + } + + this.bmd.resize(width, height); + + this.ctx.fillStyle = color; + + for (var y = 0; y < height; y += cellHeight) + { + this.ctx.fillRect(0, y, width, 1); + } + + for (var x = 0; x < width; x += cellWidth) + { + this.ctx.fillRect(x, 0, 1, height); + } + + return generateTexture ? + this.bmd.generateTexture(key, callback, callbackContext) : + this.copy(); + + }, + + /** + * Copies the contents of {@link bmd Create's canvas} to the given BitmapData object, or a new BitmapData object. + * + * @param {Phaser.BitmapData} [dest] - The BitmapData receiving the copied image. + * @param {number} [x=0] - The x coordinate to translate to before drawing. + * @param {number} [y=0] - The y coordinate to translate to before drawing. + * @param {number} [width] - The new width of the Sprite being copied. + * @param {number} [height] - The new height of the Sprite being copied. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} - The `dest` argument (if passed), or a new BitmapData object + */ + copy: function (dest, x, y, width, height, blendMode, roundPx) { + + if (dest == null) { dest = this.game.make.bitmapData(); } + + dest.resize(this.bmd.width, this.bmd.height); + + return dest.draw(this.bmd, x, y, width, height, blendMode, roundPx); + + } + +}; + +Phaser.Create.prototype.constructor = Phaser.Create; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers +* to provide for game object positioning in a responsive manner. +* +* @class Phaser.FlexGrid +* @constructor +* @param {Phaser.ScaleManager} manager - The ScaleManager. +* @param {number} width - The width of the game. +* @param {number} height - The height of the game. +*/ +Phaser.FlexGrid = function (manager, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = manager.game; + + /** + * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager. + */ + this.manager = manager; + + // The perfect dimensions on which everything else is based + this.width = width; + this.height = height; + + this.boundsCustom = new Phaser.Rectangle(0, 0, width, height); + this.boundsFluid = new Phaser.Rectangle(0, 0, width, height); + this.boundsFull = new Phaser.Rectangle(0, 0, width, height); + this.boundsNone = new Phaser.Rectangle(0, 0, width, height); + + /** + * @property {Phaser.Point} position - + * @readonly + */ + this.positionCustom = new Phaser.Point(0, 0); + this.positionFluid = new Phaser.Point(0, 0); + this.positionFull = new Phaser.Point(0, 0); + this.positionNone = new Phaser.Point(0, 0); + + /** + * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. + * @readonly + */ + this.scaleCustom = new Phaser.Point(1, 1); + this.scaleFluid = new Phaser.Point(1, 1); + this.scaleFluidInversed = new Phaser.Point(1, 1); + this.scaleFull = new Phaser.Point(1, 1); + this.scaleNone = new Phaser.Point(1, 1); + + this.customWidth = 0; + this.customHeight = 0; + this.customOffsetX = 0; + this.customOffsetY = 0; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.multiplier = 0; + + this.layers = []; + +}; + +Phaser.FlexGrid.prototype = { + + /** + * Sets the core game size. This resets the w/h parameters and bounds. + * + * @method Phaser.FlexGrid#setSize + * @param {number} width - The new dimensions. + * @param {number} height - The new dimensions. + */ + setSize: function (width, height) { + + // These are locked and don't change until setSize is called again + this.width = width; + this.height = height; + + this.ratioH = width / height; + this.ratioV = height / width; + + this.scaleNone = new Phaser.Point(1, 1); + + this.boundsNone.width = this.width; + this.boundsNone.height = this.height; + + this.refresh(); + + }, + + // Need ability to create your own layers with custom scaling, etc. + + /** + * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createCustomLayer + * @param {number} width - Width of this layer in pixels. + * @param {number} height - Height of this layer in pixels. + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createCustomLayer: function (width, height, children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + this.customWidth = width; + this.customHeight = height; + + this.boundsCustom.width = width; + this.boundsCustom.height = height; + + var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down. + * + * @method Phaser.FlexGrid#createFluidLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFluidLayer: function (children, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid); + + if (addToWorld) + { + this.game.world.add(layer); + } + + this.layers.push(layer); + + if (typeof children !== 'undefined' && typeof children !== null) + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios. + * + * @method Phaser.FlexGrid#createFullLayer + * @param {array} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFullLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled. + * + * @method Phaser.FlexGrid#createFixedLayer + * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer. + * @return {Phaser.FlexLayer} The Layer object. + */ + createFixedLayer: function (children) { + + var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone); + + this.game.world.add(layer); + + this.layers.push(layer); + + if (typeof children !== 'undefined') + { + layer.addMultiple(children); + } + + return layer; + + }, + + /** + * Resets the layer children references + * + * @method Phaser.FlexGrid#reset + */ + reset: function () { + + var i = this.layers.length; + + while (i--) + { + if (!this.layers[i].persist) + { + // Remove references to this class + this.layers[i].position = null; + this.layers[i].scale = null; + this.layers.slice(i, 1); + } + } + + }, + + /** + * Called when the game container changes dimensions. + * + * @method Phaser.FlexGrid#onResize + * @param {number} width - The new width of the game container. + * @param {number} height - The new height of the game container. + */ + onResize: function (width, height) { + + this.ratioH = width / height; + this.ratioV = height / width; + + this.refresh(width, height); + + }, + + /** + * Updates all internal vars such as the bounds and scale values. + * + * @method Phaser.FlexGrid#refresh + */ + refresh: function () { + + this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width)); + + this.boundsFluid.width = Math.round(this.width * this.multiplier); + this.boundsFluid.height = Math.round(this.height * this.multiplier); + + this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height); + this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height); + + this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height); + + this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x); + this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y); + + this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY); + + this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y); + this.positionNone.set(this.boundsNone.x, this.boundsNone.y); + + }, + + /** + * Fits a sprites width to the bounds. + * + * @method Phaser.FlexGrid#fitSprite + * @param {Phaser.Sprite} sprite - The Sprite to fit. + */ + fitSprite: function (sprite) { + + this.manager.scaleSprite(sprite); + + sprite.x = this.manager.bounds.centerX; + sprite.y = this.manager.bounds.centerY; + + }, + + /** + * Call in the render function to output the bounds rects. + * + * @method Phaser.FlexGrid#debug + */ + debug: function () { + + // for (var i = 0; i < this.layers.length; i++) + // { + // this.layers[i].debug(); + // } + + // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16); + // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false); + + this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16); + this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false); + + // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16); + // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false); + + // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16); + // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false); + + } + +}; + +Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. +* Please try to avoid using in production games with a long time to build. +* This is also why the documentation is incomplete. +* +* A responsive grid layer. +* +* @class Phaser.FlexLayer +* @extends Phaser.Group +* @constructor +* @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer. +* @param {Phaser.Point} position - A reference to the Point object used for positioning. +* @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds. +* @param {Phaser.Point} scale - A reference to the Point object used for layer scaling. +*/ +Phaser.FlexLayer = function (manager, position, bounds, scale) { + + Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false); + + /** + * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager. + */ + this.manager = manager.manager; + + /** + * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer. + */ + this.grid = manager; + + /** + * Should the FlexLayer remain through a State swap? + * + * @type {boolean} + */ + this.persist = false; + + /** + * @property {Phaser.Point} position + */ + this.position = position; + + /** + * @property {Phaser.Rectangle} bounds + */ + this.bounds = bounds; + + /** + * @property {Phaser.Point} scale + */ + this.scale = scale; + + /** + * @property {Phaser.Point} topLeft + */ + this.topLeft = bounds.topLeft; + + /** + * @property {Phaser.Point} topMiddle + */ + this.topMiddle = new Phaser.Point(bounds.halfWidth, 0); + + /** + * @property {Phaser.Point} topRight + */ + this.topRight = bounds.topRight; + + /** + * @property {Phaser.Point} bottomLeft + */ + this.bottomLeft = bounds.bottomLeft; + + /** + * @property {Phaser.Point} bottomMiddle + */ + this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom); + + /** + * @property {Phaser.Point} bottomRight + */ + this.bottomRight = bounds.bottomRight; + +}; + +Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype); +Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer; + +/** + * Resize. + * + * @method Phaser.FlexLayer#resize + */ +Phaser.FlexLayer.prototype.resize = function () { +}; + +/** + * Debug. + * + * @method Phaser.FlexLayer#debug + */ +Phaser.FlexLayer.prototype.debug = function () { + + this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16); + this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false); + + this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9'); + this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9'); + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. +* +* @class Phaser.Color +*/ +Phaser.Color = { + + /** + * Red (0xff0000) + * + * @type number + * @constant + * @default + */ + RED: 0xff0000, + + /** + * Orange (0xff9900) + * + * @type number + * @constant + * @default + */ + ORANGE: 0xff9900, + + /** + * Yellow (0xffff00) + * + * @type number + * @constant + * @default + */ + YELLOW: 0xffff00, + + /** + * Green (0x00ff00) + * + * @type number + * @constant + * @default + */ + GREEN: 0x00ff00, + + /** + * Aqua (0x00ffff) + * + * @type number + * @constant + * @default + */ + AQUA: 0x00ffff, + + /** + * Blue (0x0000ff) + * + * @type number + * @constant + * @default + */ + BLUE: 0x0000ff, + + /** + * Violet/purple (0xff00ff) + * + * @type number + * @constant + * @default + */ + VIOLET: 0xff00ff, + + /** + * White (0xffffff) + * + * @type number + * @constant + * @default + */ + WHITE: 0xffffff, + + /** + * Black (0x000000) + * + * @type number + * @constant + * @default + */ + BLACK: 0, + + /** + * Gray (0x666666) + * + * @type number + * @constant + * @default + */ + GRAY: 0x666666, + + /** + * Packs the r, g, b, a components into a single integer, for use with Int32Array. + * If device is little endian then ABGR order is used. Otherwise RGBA order is used. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.packPixel + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} The packed color as uint32 + */ + packPixel: function (r, g, b, a) { + + if (Phaser.Device.LITTLE_ENDIAN) + { + return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0; + } + else + { + return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0; + } + + }, + + /** + * Unpacks the r, g, b, a components into the specified color object, or a new + * object, for use with Int32Array. If little endian, then ABGR order is used when + * unpacking, otherwise, RGBA order is used. The resulting color object has the + * `r, g, b, a` properties which are unrelated to endianness. + * + * Note that the integer is assumed to be packed in the correct endianness. On little-endian + * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a + * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.unpackPixel + * @static + * @param {number} rgba - The integer, packed in endian order by packPixel. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + unpackPixel: function (rgba, out, hsl, hsv) { + + if (out === undefined || out === null) { out = Phaser.Color.createColor(); } + if (hsl === undefined || hsl === null) { hsl = false; } + if (hsv === undefined || hsv === null) { hsv = false; } + + if (Phaser.Device.LITTLE_ENDIAN) + { + out.a = ((rgba & 0xff000000) >>> 24); + out.b = ((rgba & 0x00ff0000) >>> 16); + out.g = ((rgba & 0x0000ff00) >>> 8); + out.r = ((rgba & 0x000000ff)); + } + else + { + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + } + + 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; + + }, + + /** + * A utility to convert an integer in 0xRRGGBBAA format to a color object. + * This does not rely on endianness. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.fromRGBA + * @static + * @param {number} rgba - An RGBA hex + * @param {object} [out] - The object to use, optional. + * @return {object} A color object. + */ + fromRGBA: function (rgba, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + out.r = ((rgba & 0xff000000) >>> 24); + out.g = ((rgba & 0x00ff0000) >>> 16); + out.b = ((rgba & 0x0000ff00) >>> 8); + out.a = ((rgba & 0x000000ff)); + + out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')'; + + return out; + + }, + + /** + * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.toRGBA + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toRGBA: function (r, g, b, a) { + + return (r << 24) | (g << 16) | (b << 8) | a; + + }, + + /** + * Converts RGBA components to a 32 bit integer in AABBGGRR format. + * + * @method Phaser.Color.toABGR + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ + toABGR: function (r, g, b, a) { + + return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; + + }, + + /** + * Converts a hex color value to an [R, G, B] array. + * + * @static + * @method Phaser.Color.hexToRGBArray + * @param {number} color - The color to convert to an RGB array. In the format 0xRRGGBB. + * @return {array} An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + */ + hexToRGBArray: function (color) { + + return [ + (color >> 16 & 0xFF) / 255, + (color >> 8 & 0xFF) / 255, + (color & 0xFF) / 255 + ]; + + }, + + /** + * Converts an RGB color array, in the format: [R, G, B], to a hex color value. + * + * @static + * @method Phaser.Color.RGBArrayToHex + * @param {array} rgb - An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + * @return {number} The color value, in the format 0xRRGGBB. + */ + RGBArrayToHex: function (rgb) { + + return ((rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255); + + }, + + /** + * Converts an RGB color value to HSL (hue, saturation and lightness). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSL + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. + */ + 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); + + // achromatic by default + out.h = 0; + out.s = 0; + out.l = (max + min) / 2; + + if (max !== min) + { + var d = max - min; + + out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min); + + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSL (hue, saturation and lightness) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSLtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} l - The lightness, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSLtoRGB: function (h, s, l, out) { + + if (!out) + { + out = Phaser.Color.createColor(l, l, l); + } + else + { + // achromatic by default + out.r = l; + out.g = l; + out.b = l; + } + + if (s !== 0) + { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3); + out.g = Phaser.Color.hueToColor(p, q, h); + out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3); + } + + // out.r = (out.r * 255 | 0); + // out.g = (out.g * 255 | 0); + // out.b = (out.b * 255 | 0); + + out.r = Math.floor((out.r * 255 | 0)); + out.g = Math.floor((out.g * 255 | 0)); + out.b = Math.floor((out.b * 255 | 0)); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts an RGB color value to HSV (hue, saturation and value). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSV + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and value set in the h, s and v properties. + */ + RGBtoHSV: function (r, g, b, out) { + + if (!out) + { + out = Phaser.Color.createColor(r, g, b, 255); + } + + r /= 255; + g /= 255; + b /= 255; + + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var d = max - min; + + // achromatic by default + out.h = 0; + out.s = max === 0 ? 0 : d / max; + out.v = max; + + if (max !== min) + { + if (max === r) + { + out.h = (g - b) / d + (g < b ? 6 : 0); + } + else if (max === g) + { + out.h = (b - r) / d + 2; + } + else if (max === b) + { + out.h = (r - g) / d + 4; + } + + out.h /= 6; + } + + return out; + + }, + + /** + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSVtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} v - The value, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + HSVtoRGB: function (h, s, v, out) { + + if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); } + + var r, g, b; + var i = Math.floor(h * 6); + var f = h * 6 - i; + var p = v * (1 - s); + var q = v * (1 - f * s); + var t = v * (1 - (1 - f) * s); + + switch (i % 6) + { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } + + out.r = Math.floor(r * 255); + out.g = Math.floor(g * 255); + out.b = Math.floor(b * 255); + + Phaser.Color.updateColor(out); + + return out; + + }, + + /** + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.hueToColor + * @static + * @param {number} p + * @param {number} q + * @param {number} t + * @return {number} The color component value. + */ + hueToColor: function (p, q, t) { + + if (t < 0) + { + t += 1; + } + + if (t > 1) + { + t -= 1; + } + + if (t < 1 / 6) + { + return p + (q - p) * 6 * t; + } + + if (t < 1 / 2) + { + return q; + } + + if (t < 2 / 3) + { + return p + (q - p) * (2 / 3 - t) * 6; + } + + return p; + + }, + + /** + * A utility function to create a lightweight 'color' object with the default components. + * Any components that are not specified will default to zero. + * + * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.createColor + * @static + * @param {number} [r=0] - The red color component, in the range 0 - 255. + * @param {number} [g=0] - The green color component, in the range 0 - 255. + * @param {number} [b=0] - The blue color component, in the range 0 - 255. + * @param {number} [a=1] - The alpha color component, in the range 0 - 1. + * @param {number} [h=0] - The hue, in the range 0 - 1. + * @param {number} [s=0] - The saturation, in the range 0 - 1. + * @param {number} [l=0] - The lightness, in the range 0 - 1. + * @param {number} [v=0] - The value, in the range 0 - 1. + * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. + */ + 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, color32: 0, rgba: '' }; + + return Phaser.Color.updateColor(out); + + }, + + /** + * Takes a color object and updates the rgba, color and color32 properties. + * + * @method Phaser.Color.updateColor + * @static + * @param {object} out - The color object to update. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + updateColor: function (out) { + + out.rgba = 'rgba(' + out.r.toFixed() + ',' + out.g.toFixed() + ',' + out.b.toFixed() + ',' + out.a.toString() + ')'; + out.color = Phaser.Color.getColor(out.r, out.g, out.b); + out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b); + + return out; + + }, + + /** + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor32 + * @static + * @param {number} a - The alpha color component, in the range 0 - 255. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ + getColor32: function (a, r, g, b) { + + return a << 24 | r << 16 | g << 8 | b; + + }, + + /** + * Given 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xRRGGBB). + */ + getColor: function (r, g, b) { + + return r << 16 | g << 8 | b; + + }, + + /** + * Converts the given color values into a string. + * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + * + * @method Phaser.Color.RGBtoString + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255. + * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. + * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + */ + RGBtoString: function (r, g, b, a, prefix) { + + if (a === undefined) { a = 255; } + if (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); + } + + }, + + /** + * Converts a hex string into an integer color value. + * + * @method Phaser.Color.hexToRGB + * @static + * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. + * @return {number} The rgb color value in the format 0xAARRGGBB. + */ + hexToRGB: function (hex) { + + var rgb = Phaser.Color.hexToColor(hex); + + if (rgb) + { + return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b); + } + + }, + + /** + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @method Phaser.Color.hexToColor + * @static + * @param {string} hex - The color string in a hex format. + * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ + hexToColor: function (hex, out) { + + // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") + hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { + return r + r + g + g + b + b; + }); + + var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + + if (result) + { + var r = parseInt(result[1], 16); + var g = parseInt(result[2], 16); + var b = parseInt(result[3], 16); + + if (!out) + { + out = Phaser.Color.createColor(r, g, b); + } + else + { + out.r = r; + out.g = g; + out.b = b; + } + } + + return out; + + }, + + /** + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @method Phaser.Color.webToColor + * @static + * @param {string} web - The color string in CSS 'web' format. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ + webToColor: function (web, out) { + + if (!out) + { + out = Phaser.Color.createColor(); + } + + var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web); + + if (result) + { + out.r = ~~Number(result[1]); + out.g = ~~Number(result[2]); + out.b = ~~Number(result[3]); + out.a = result[4] !== undefined ? Number(result[4]) : 1; + Phaser.Color.updateColor(out); + } + + return out; + + }, + + /** + * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. + * + * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). + * + * An alpha channel is _not_ supported when specifying a hex string. + * + * @method Phaser.Color.valueToColor + * @static + * @param {string|number} value - The color expressed as a recognized string format or a packed integer. + * @param {object} [out] - The object to use for the output. If not provided a new object will be created. + * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. + */ + valueToColor: function (value, out) { + + // The behavior is not consistent between hexToColor/webToColor on invalid input. + // This unifies both by returning a new object, but returning null may be better. + if (!out) + { + out = Phaser.Color.createColor(); + } + + if (typeof value === 'string') + { + if (value.indexOf('rgb') === 0) + { + return Phaser.Color.webToColor(value, out); + } + else + { + // `hexToColor` does not support alpha; match `createColor`. + out.a = 1; + return Phaser.Color.hexToColor(value, out); + } + } + else if (typeof value === 'number') + { + // `getRGB` does not take optional object to modify; + // alpha is also adjusted to match `createColor`. + var tempColor = Phaser.Color.getRGB(value); + out.r = tempColor.r; + out.g = tempColor.g; + out.b = tempColor.b; + out.a = tempColor.a / 255; + return out; + } + else + { + return out; + } + + }, + + /** + * Return a string containing a hex representation of the given color component. + * + * @method Phaser.Color.componentToHex + * @static + * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. + * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ + componentToHex: function (color) { + + var hex = color.toString(16); + + return (hex.length === 1) ? '0' + hex : hex; + + }, + + /** + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSVColorWheel + * @static + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSV color wheel. + */ + HSVColorWheel: function (s, v) { + + if (s === undefined) { s = 1.0; } + if (v === undefined) { v = 1.0; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v)); + } + + return colors; + + }, + + /** + * Get HSL color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSLColorWheel + * @static + * @param {number} [s=0.5] - The saturation, in the range 0 - 1. + * @param {number} [l=0.5] - The lightness, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSL color wheel. + */ + HSLColorWheel: function (s, l) { + + if (s === undefined) { s = 0.5; } + if (l === undefined) { l = 0.5; } + + var colors = []; + + for (var c = 0; c <= 359; c++) + { + colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l)); + } + + return colors; + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColor + * @static + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @param {number} [alpha] - The alpha of the returned color. + * @param {number} [colorSpace=0] - The color space to interpolate in. 0 = RGB, 1 = HSV. + * @returns {number} The interpolated color value. + */ + interpolateColor: function (color1, color2, steps, currentStep, alpha, colorSpace) { + + if (alpha === undefined) { alpha = 255; } + if (colorSpace === undefined) { colorSpace = 0; } + + var src1 = Phaser.Color.getRGB(color1); + var src2 = Phaser.Color.getRGB(color2); + + if (colorSpace === 0) + { + 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; + } + + if (colorSpace === 1) + { + var hsv1 = Phaser.Color.RGBtoHSV(src1.r, src1.g, src1.b); + var hsv2 = Phaser.Color.RGBtoHSV(src2.r, src2.g, src2.b); + var dh = hsv2.h - hsv1.h; + var h; + + if (hsv1.h > hsv2.h) + { + var h3 = hsv2.h; + hsv2.h = hsv1.h; + hsv1.h = h3; + dh = -dh; + currentStep = steps - currentStep; + } + + if (dh > 0.5) + { + hsv1.h = hsv1.h + 1; + h = (((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h) % 1; + } + + if (dh <= 0.5) + { + h = ((hsv2.h - hsv1.h) * currentStep / steps) + hsv1.h; + } + + var s = (((hsv2.s - hsv1.s) * currentStep) / steps) + hsv1.s; + var v = (((hsv2.v - hsv1.v) * currentStep) / steps) + hsv1.v; + + var rgb = Phaser.Color.HSVtoRGB(h, s, v, rgb); + var r = rgb.r; + var g = rgb.g; + var b = rgb.b; + } + + return Phaser.Color.getColor32(alpha, r, g, b); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColorWithRGB + * @static + * @param {number} color - The first color value. + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + /** + * Interpolates the two given colours based on the supplied step and currentStep properties. + * @method Phaser.Color.interpolateRGB + * @static + * @param {number} r1 - The red color value, between 0 and 0xFF (255). + * @param {number} g1 - The green color value, between 0 and 0xFF (255). + * @param {number} b1 - The blue color value, between 0 and 0xFF (255). + * @param {number} r2 - The red color value, between 0 and 0xFF (255). + * @param {number} g2 - The green color value, between 0 and 0xFF (255). + * @param {number} b2 - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ + 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); + + }, + + + /** + * Calculates a linear (interpolation) value of two colors over t. + * + * This is a slightly simpler interface to {@link Phaser.Color.interpolateColor}. + * + * The arguments are similar to {@link Phaser.Math.linear}. + * + * @method Phaser.Color.linear + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linear: function (color1, color2, t) { + + return this.interpolateColor(color1, color2, 1, t); + + }, + + /** + * Calculates a linear (interpolation) value of an array of colors over t. + * + * The arguments are similar to {@link Phaser.Math.linearInterpolation}. + * + * This can be used as a {@link Phaser.TweenData#interpolationFunction}. + * + * @method Phaser.Color.linearInterpolation + * @param {number[]} colors - The input array of color values to interpolate between. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ + linearInterpolation: function (colors, t) { + + var k = Phaser.Math.linear(0, colors.length - 1, t); + var color1 = colors[ Math.floor(k) ]; + var color2 = colors[ Math.ceil(k)] ; + + return this.linear(color1, color2, k % 1); + + }, + + /** + * Returns a random color value between black and white + * Set the min value to start each channel from the given offset. + * Set the max value to restrict the maximum color used per channel. + * + * @method Phaser.Color.getRandomColor + * @static + * @param {number} [min=0] - The lowest value to use for the color. + * @param {number} [max=255] - The highest value to use for the color. + * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). + * @returns {number} 32-bit color value with alpha. + */ + getRandomColor: function (min, max, alpha) { + + if (min === undefined) { min = 0; } + if (max === undefined) { max = 255; } + if (alpha === undefined) { alpha = 255; } + + // Sanity checks + 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); + + }, + + /** + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exist in the given color (0xAARRGGBB) + * + * @method Phaser.Color.getRGB + * @static + * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). + * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. + */ + getRGB: function (color) { + + if (color > 16777215) + { + // The color value has an alpha component + return { + alpha: color >>> 24, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: color >>> 24, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + else + { + return { + alpha: 255, + red: color >> 16 & 0xFF, + green: color >> 8 & 0xFF, + blue: color & 0xFF, + a: 255, + r: color >> 16 & 0xFF, + g: color >> 8 & 0xFF, + b: color & 0xFF + }; + } + + }, + + /** + * Returns a CSS friendly string value from the given color. + * + * @method Phaser.Color.getWebRGB + * @static + * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. + * @returns {string} A string in the format: 'rgba(r,g,b,a)' + */ + getWebRGB: function (color) { + + if (typeof color === 'object') + { + return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')'; + } + else + { + var rgb = Phaser.Color.getRGB(color); + return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')'; + } + + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. + * + * @method Phaser.Color.getAlpha + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlpha: function (color) { + return color >>> 24; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. + * + * @method Phaser.Color.getAlphaFloat + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ + getAlphaFloat: function (color) { + return (color >>> 24) / 255; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. + * + * @method Phaser.Color.getRed + * @static + * @param {number} color In the format 0xAARRGGBB. + * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). + */ + getRed: function (color) { + return color >> 16 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. + * + * @method Phaser.Color.getGreen + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). + */ + getGreen: function (color) { + return color >> 8 & 0xFF; + }, + + /** + * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. + * + * @method Phaser.Color.getBlue + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). + */ + getBlue: function (color) { + return color & 0xFF; + }, + + /** + * Blends the source color, ignoring the backdrop. + * + * @method Phaser.Color.blendNormal + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNormal: function (a) { + return a; + }, + + /** + * Selects the lighter of the backdrop and source colors. + * + * @method Phaser.Color.blendLighten + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLighten: function (a, b) { + return (b > a) ? b : a; + }, + + /** + * Selects the darker of the backdrop and source colors. + * + * @method Phaser.Color.blendDarken + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDarken: function (a, b) { + return (b > a) ? a : b; + }, + + /** + * Multiplies the backdrop and source color values. + * The result color is always at least as dark as either of the two constituent + * colors. Multiplying any color with black produces black; + * multiplying with white leaves the original color unchanged. + * + * @method Phaser.Color.blendMultiply + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendMultiply: function (a, b) { + return (a * b) / 255; + }, + + /** + * Takes the average of the source and backdrop colors. + * + * @method Phaser.Color.blendAverage + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAverage: function (a, b) { + return (a + b) / 2; + }, + + /** + * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. + * + * @method Phaser.Color.blendAdd + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendAdd: function (a, b) { + return Math.min(255, a + b); + }, + + /** + * Combines the source and backdrop colors and returns their value minus 255. + * + * @method Phaser.Color.blendSubtract + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSubtract: function (a, b) { + return Math.max(0, a + b - 255); + }, + + /** + * Subtracts the darker of the two constituent colors from the lighter. + * + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendDifference + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendDifference: function (a, b) { + return Math.abs(a - b); + }, + + /** + * Negation blend mode. + * + * @method Phaser.Color.blendNegation + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendNegation: function (a, b) { + return 255 - Math.abs(255 - a - b); + }, + + /** + * Multiplies the complements of the backdrop and source color values, then complements the result. + * The result color is always at least as light as either of the two constituent colors. + * Screening any color with white produces white; screening with black leaves the original color unchanged. + * + * @method Phaser.Color.blendScreen + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendScreen: function (a, b) { + return 255 - (((255 - a) * (255 - b)) >> 8); + }, + + /** + * Produces an effect similar to that of the Difference mode, but lower in contrast. + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendExclusion + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendExclusion: function (a, b) { + return a + b - 2 * a * b / 255; + }, + + /** + * Multiplies or screens the colors, depending on the backdrop color. + * Source colors overlay the backdrop while preserving its highlights and shadows. + * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. + * + * @method Phaser.Color.blendOverlay + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendOverlay: function (a, b) { + return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255); + }, + + /** + * Darkens or lightens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. + * The effect is similar to shining a diffused spotlight on the backdrop. + * + * @method Phaser.Color.blendSoftLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendSoftLight: function (a, b) { + return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255); + }, + + /** + * Multiplies or screens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; + * this is useful for adding shadows to a scene. + * + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. + * + * @method Phaser.Color.blendHardLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardLight: function (a, b) { + return Phaser.Color.blendOverlay(b, a); + }, + + /** + * Brightens the backdrop color to reflect the source color. + * Painting with black produces no change. + * + * @method Phaser.Color.blendColorDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorDodge: function (a, b) { + return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b))); + }, + + /** + * Darkens the backdrop color to reflect the source color. + * Painting with white produces no change. + * + * @method Phaser.Color.blendColorBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendColorBurn: function (a, b) { + return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b)); + }, + + /** + * An alias for blendAdd, it simply sums the values of the two colors. + * + * @method Phaser.Color.blendLinearDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearDodge: function (a, b) { + return Phaser.Color.blendAdd(a, b); + }, + + /** + * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. + * + * @method Phaser.Color.blendLinearBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearBurn: function (a, b) { + return Phaser.Color.blendSubtract(a, b); + }, + + /** + * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). + * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. + * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. + * + * @method Phaser.Color.blendLinearLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendLinearLight: function (a, b) { + return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128))); + }, + + /** + * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). + * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. + * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom + * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. + * + * @method Phaser.Color.blendVividLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendVividLight: function (a, b) { + return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128))); + }, + + /** + * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. + * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. + * + * @method Phaser.Color.blendPinLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPinLight: function (a, b) { + return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128))); + }, + + /** + * Runs blendVividLight on the source and backdrop colors. + * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. + * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. + * This changes all pixels to primary additive colors (red, green, or blue), white, or black. + * + * @method Phaser.Color.blendHardMix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendHardMix: function (a, b) { + return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255; + }, + + /** + * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. + * + * @method Phaser.Color.blendReflect + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendReflect: function (a, b) { + return b === 255 ? b : Math.min(255, (a * a / (255 - b))); + }, + + /** + * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. + * + * @method Phaser.Color.blendGlow + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendGlow: function (a, b) { + return Phaser.Color.blendReflect(b, a); + }, + + /** + * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. + * + * @method Phaser.Color.blendPhoenix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ + blendPhoenix: function (a, b) { + return Math.min(a, b) - Math.max(a, b) + 255; + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Manager is responsible for looking after all of the running physics systems. +* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. +* +* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. +* +* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the +* faster (due to being much simpler) Arcade Physics system. +* +* @class Phaser.Physics +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. +*/ +Phaser.Physics = function (game, config) { + + config = config || {}; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {object} config - The physics configuration object as passed to the game on creation. + */ + this.config = config; + + /** + * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. + */ + this.arcade = null; + + /** + * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. + */ + this.p2 = null; + + /** + * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. + */ + this.ninja = null; + + /** + * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. + */ + this.box2d = null; + + /** + * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). + */ + this.chipmunk = null; + + /** + * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). + */ + this.matter = null; + + this.parseConfig(); + +}; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.ARCADE = 0; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.P2JS = 1; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.NINJA = 2; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.BOX2D = 3; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.CHIPMUNK = 4; + +/** +* @const +* @type {number} +*/ +Phaser.Physics.MATTERJS = 5; + +Phaser.Physics.prototype = { + + /** + * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. + * + * @method Phaser.Physics#parseConfig + */ + parseConfig: function () { + + if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade')) + { + // If Arcade isn't specified, we create it automatically if we can + this.arcade = new Phaser.Physics.Arcade(this.game); + } + + 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); + } + + if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D')) + { + this.box2d = new Phaser.Physics.BOX2D(this.game, this.config); + } + + if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter')) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + + }, + + /** + * This will create an instance of the requested physics simulation. + * Phaser.Physics.Arcade is running by default, but all others need activating directly. + * + * You can start the following physics systems: + * + * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. + * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) + * + * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. + * They are not bundled into the core Phaser library. + * + * If the physics world has already been created (i.e. in another state in your game) then + * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors + * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. + * + * @method Phaser.Physics#startSystem + * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. + */ + startSystem: function (system) { + + if (system === Phaser.Physics.ARCADE) + { + this.arcade = new Phaser.Physics.Arcade(this.game); + } + else if (system === Phaser.Physics.P2JS) + { + if (this.p2 === null) + { + this.p2 = new Phaser.Physics.P2(this.game, this.config); + } + else + { + this.p2.reset(); + } + } + else if (system === Phaser.Physics.NINJA) + { + this.ninja = new Phaser.Physics.Ninja(this.game); + } + else if (system === Phaser.Physics.BOX2D) + { + if (this.box2d === null) + { + this.box2d = new Phaser.Physics.Box2D(this.game, this.config); + } + else + { + this.box2d.reset(); + } + } + else if (system === Phaser.Physics.MATTERJS) + { + if (this.matter === null) + { + this.matter = new Phaser.Physics.Matter(this.game, this.config); + } + else + { + this.matter.reset(); + } + } + + }, + + /** + * This will create a default physics body on the given game object or array of objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * It can be for any of the physics systems that have been started: + * + * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. + * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. + * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 + * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) + * Phaser.Physics.CHIPMUNK is still in development. + * + * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the + * individual physics systems `enable` methods instead of using this generic one. + * + * @method Phaser.Physics#enable + * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. + * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. + * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. + */ + enable: function (object, system, debug) { + + if (system === undefined) { system = Phaser.Physics.ARCADE; } + if (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); + } + else if (system === Phaser.Physics.BOX2D && this.box2d) + { + this.box2d.enable(object); + } + else if (system === Phaser.Physics.MATTERJS && this.matter) + { + this.matter.enable(object); + } + else + { + console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.'); + } + + }, + + /** + * preUpdate checks. + * + * @method Phaser.Physics#preUpdate + * @protected + */ + preUpdate: function () { + + // ArcadePhysics / Ninja don't have a core to preUpdate + + if (this.p2) + { + this.p2.preUpdate(); + } + + if (this.box2d) + { + this.box2d.preUpdate(); + } + + if (this.matter) + { + this.matter.preUpdate(); + } + + }, + + /** + * Updates all running physics systems. + * + * @method Phaser.Physics#update + * @protected + */ + update: function () { + + // ArcadePhysics / Ninja don't have a core to update + + if (this.p2) + { + this.p2.update(); + } + + if (this.box2d) + { + this.box2d.update(); + } + + if (this.matter) + { + this.matter.update(); + } + + }, + + /** + * Updates the physics bounds to match the world dimensions. + * + * @method Phaser.Physics#setBoundsToWorld + * @protected + */ + setBoundsToWorld: function () { + + if (this.arcade) + { + this.arcade.setBoundsToWorld(); + } + + if (this.ninja) + { + this.ninja.setBoundsToWorld(); + } + + if (this.p2) + { + this.p2.setBoundsToWorld(); + } + + if (this.box2d) + { + this.box2d.setBoundsToWorld(); + } + + if (this.matter) + { + this.matter.setBoundsToWorld(); + } + + }, + + /** + * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. + * + * @method Phaser.Physics#clear + * @protected + */ + clear: function () { + + if (this.p2) + { + this.p2.clear(); + } + + if (this.box2d) + { + this.box2d.clear(); + } + + if (this.matter) + { + this.matter.clear(); + } + + }, + + /** + * Resets the active physics system. Called automatically on a Phaser.State swap. + * + * @method Phaser.Physics#reset + * @protected + */ + reset: function () { + + if (this.p2) + { + this.p2.reset(); + } + + if (this.box2d) + { + this.box2d.reset(); + } + + if (this.matter) + { + this.matter.reset(); + } + + }, + + /** + * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. + * + * @method Phaser.Physics#destroy + */ + destroy: function () { + + if (this.p2) + { + this.p2.destroy(); + } + + if (this.box2d) + { + this.box2d.destroy(); + } + + if (this.matter) + { + this.matter.destroy(); + } + + this.arcade = null; + this.ninja = null; + this.p2 = null; + this.box2d = null; + this.matter = null; + + } + +}; + +Phaser.Physics.prototype.constructor = Phaser.Physics; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. +* +* @class Phaser.Physics.Arcade +* @constructor +* @param {Phaser.Game} game - reference to the current game instance. +*/ +Phaser.Physics.Arcade = function (game) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. + */ + this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height); + + /** + * Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`. + * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. + * @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right). + */ + this.checkCollision = { up: true, down: true, left: true, right: true }; + + /** + * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. + */ + this.maxObjects = 10; + + /** + * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. + */ + this.maxLevels = 4; + + /** + * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. + * @default + */ + this.OVERLAP_BIAS = 4; + + /** + * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. + */ + this.forceX = false; + + /** + * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT. + * @default + */ + this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT; + + /** + * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. + */ + this.skipQuadTree = true; + + /** + * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. + */ + this.isPaused = false; + + /** + * @property {Phaser.QuadTree} quadTree - The world QuadTree. + */ + 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); + + /** + * @property {number} _total - Internal cache var. + * @private + */ + this._total = 0; + + // By default we want the bounds the same size as the world bounds + this.setBoundsToWorld(); + +}; + +Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade; + +/** +* A constant used for the sortDirection value. +* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.SORT_NONE = 0; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.LEFT_RIGHT = 1; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.RIGHT_LEFT = 2; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.TOP_BOTTOM = 3; + +/** +* A constant used for the sortDirection value. +* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) +* @constant +* @type {number} +*/ +Phaser.Physics.Arcade.BOTTOM_TOP = 4; + +Phaser.Physics.Arcade.prototype = { + + /** + * Updates the size of this physics world. + * + * @method Phaser.Physics.Arcade#setBounds + * @param {number} x - Top left most corner of the world. + * @param {number} y - Top left most corner of the world. + * @param {number} width - New width of the world. Can never be smaller than the Game.width. + * @param {number} height - New height of the world. Can never be smaller than the Game.height. + */ + setBounds: function (x, y, width, height) { + + this.bounds.setTo(x, y, width, height); + + }, + + /** + * Updates the size of this physics world to match the size of the game world. + * + * @method Phaser.Physics.Arcade#setBoundsToWorld + */ + setBoundsToWorld: function () { + + this.bounds.copyFrom(this.game.world.bounds); + + }, + + /** + * This will create an Arcade Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * + * @method Phaser.Physics.Arcade#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, children) { + + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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) + { + // If it's a Group then we do it on the children regardless + this.enable(object.children, children); + } + else + { + this.enableBody(object); + + if (children && object.hasOwnProperty('children') && object.children.length > 0) + { + this.enable(object.children, true); + } + } + } + + }, + + /** + * Creates an Arcade Physics body on the given game object. + * + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. + * + * @method Phaser.Physics.Arcade#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + */ + enableBody: function (object) { + + if (object.hasOwnProperty('body') && object.body === null) + { + object.body = new Phaser.Physics.Arcade.Body(object); + + if (object.parent && object.parent instanceof Phaser.Group) + { + object.parent.addToHash(object); + } + } + + }, + + /** + * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. + * + * @method Phaser.Physics.Arcade#updateMotion + * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. + */ + updateMotion: function (body) { + + if (body.allowRotation) + { + var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity; + body.angularVelocity += 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); + + }, + + /** + * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * Based on a function in Flixel by @ADAMATOMIC + * + * @method Phaser.Physics.Arcade#computeVelocity + * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical. + * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. + * @param {number} velocity - Any component of velocity (e.g. 20). + * @param {number} acceleration - Rate at which the velocity is changing. + * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. + * @param {number} [max=10000] - An absolute value cap for the velocity. + * @return {number} The altered Velocity value. + */ + computeVelocity: function (axis, body, velocity, acceleration, drag, max) { + + if (max === undefined) { max = 10000; } + + 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 && body.allowDrag) + { + drag *= this.game.time.physicsElapsed; + + if (velocity - drag > 0) + { + velocity -= drag; + } + else if (velocity + drag < 0) + { + velocity += drag; + } + else + { + velocity = 0; + } + } + + if (velocity > max) + { + velocity = max; + } + else if (velocity < -max) + { + velocity = -max; + } + + return velocity; + + }, + + /** + * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. + * + * Unlike {@link #collide} the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. + * Both the first and second parameter can be arrays of objects, of differing types. + * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups within Groups). + * + * ##### Tilemaps + * + * Any overlapping tiles, including blank/null tiles, will give a positive result. Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) have no special status, and callbacks added via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} are not invoked. So calling this method without any callbacks isn't very useful. + * + * If you're interested only in whether an object overlaps a certain tile or class of tiles, filter the tiles with `processCallback` and then use the result returned by this method. Blank/null tiles can be excluded by their {@link Phaser.Tile#index index} (-1). + * + * If you want to take action on certain overlaps, examine the tiles in `collideCallback` and then handle as you like. + * + * @method Phaser.Physics.Arcade#overlap + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if an overlap occurred otherwise false. + */ + overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) { + + overlapCallback = overlapCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || overlapCallback; + + this._total = 0; + + this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); + + return (this._total > 0); + + }, + + /** + * Checks for collision between two game objects and separates them if colliding ({@link https://gist.github.com/samme/cbb81dd19f564dcfe2232761e575063d details}). If you don't require separation then use {@link #overlap} instead. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. + * Both the `object1` and `object2` can be arrays of objects, of differing types. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If one Group **only** is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If either object is `null` the collision test will fail. + * + * Bodies with `enable = false` and Sprites with `exists = false` are skipped (ignored). + * + * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. + * + * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). + * + * ##### Examples + * + * ```javascript + * collide(group); + * collide(group, undefined); // equivalent + * + * collide(sprite1, sprite2); + * + * collide(sprite, group); + * + * collide(group1, group2); + * + * collide([sprite1, sprite2], [sprite3, sprite4]); // 1 vs. 3, 1 vs. 4, 2 vs. 3, 2 vs. 4 + * ``` + * + * ##### Tilemaps + * + * Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) are "solid". If a Sprite collides with one of these tiles, the two are separated by moving the Sprite outside the tile's edges. Enable {@link Phaser.TilemapLayer#debug} to see the colliding edges of the Tilemap. + * + * Tiles with a callback attached via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} invoke the callback if a Sprite collides with them. If a tile has a callback attached via both methods, only the location callback is invoked. The colliding Sprite is separated from the tile only if the callback returns `true`. + * + * @method Phaser.Physics.Arcade#collide + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. + * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if a collision occurred otherwise false. + */ + collide: function (object1, object2, collideCallback, processCallback, callbackContext) { + + collideCallback = collideCallback || null; + processCallback = processCallback || null; + callbackContext = callbackContext || collideCallback; + + this._total = 0; + + this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); + + return (this._total > 0); + + }, + + /** + * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortLeftRight + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortLeftRight: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.x - b.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortRightLeft + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortRightLeft: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.x - a.body.x; + + }, + + /** + * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortTopBottom + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortTopBottom: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return a.body.y - b.body.y; + + }, + + /** + * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction. + * + * This is called automatically by World.sort + * + * @method Phaser.Physics.Arcade#sortBottomTop + * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body. + * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body. + * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid. + */ + sortBottomTop: function (a, b) { + + if (!a.body || !b.body) + { + return 0; + } + + return b.body.y - a.body.y; + + }, + + /** + * This method will sort a Groups hash array. + * + * If the Group has `physicsSortDirection` set it will use the sort direction defined. + * + * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection. + * + * By changing Group.physicsSortDirection you can customise each Group to sort in a different order. + * + * @method Phaser.Physics.Arcade#sort + * @param {Phaser.Group} group - The Group to sort. + * @param {integer} [sortDirection] - The sort direction used to sort this Group. + */ + sort: function (group, sortDirection) { + + if (group.physicsSortDirection !== null) + { + sortDirection = group.physicsSortDirection; + } + else + { + if (sortDirection === undefined) { sortDirection = this.sortDirection; } + } + + if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + // Game world is say 2000x600 and you start at 0 + group.hash.sort(this.sortLeftRight); + } + else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + // Game world is say 2000x600 and you start at 2000 + group.hash.sort(this.sortRightLeft); + } + else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + // Game world is say 800x2000 and you start at 0 + group.hash.sort(this.sortTopBottom); + } + else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + // Game world is say 800x2000 and you start at 2000 + group.hash.sort(this.sortBottomTop); + } + + }, + + /** + * Internal collision handler. Extracts objects for {@link #collideHandler}. + * + * @method Phaser.Physics.Arcade#collideObjects + * @private + */ + collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object2.length; i++) + { + if (!object2[i]) { continue; } + + this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && !Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else if (Array.isArray(object1) && Array.isArray(object2)) + { + for (var i = 0; i < object1.length; i++) + { + if (!object1[i]) { continue; } + + for (var j = 0; j < object2.length; j++) + { + if (!object2[j]) { continue; } + + this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + else + { + this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + + }, + + /** + * Internal collision handler. Matches arguments to other handlers. + * + * @method Phaser.Physics.Arcade#collideHandler + * @private + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { + + // Only collide valid objects + if (object2 === undefined && object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly); + return; + } + + // If neither of the objects are set or exist then bail out + if (!object1 || !object2 || !object1.exists || !object2.exists) + { + return; + } + + // Groups? Sort them + if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE) + { + if (object1.physicsType === Phaser.GROUP) + { + this.sort(object1); + } + + if (object2.physicsType === Phaser.GROUP) + { + this.sort(object2); + } + } + + // SPRITES + if (object1.physicsType === Phaser.SPRITE) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // GROUPS + else if (object1.physicsType === Phaser.GROUP) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.TILEMAPLAYER) + { + this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + // TILEMAP LAYERS + else if (object1.physicsType === Phaser.TILEMAPLAYER) + { + if (object2.physicsType === Phaser.SPRITE) + { + this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + else if (object2.physicsType === Phaser.GROUP) + { + this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsSprite + * @private + * @param {Phaser.Sprite} sprite1 - The first sprite to check. + * @param {Phaser.Sprite} sprite2 - The second sprite to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + 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; + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsGroup + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0 || !sprite.body) + { + return; + } + + if (this.skipQuadTree || sprite.body.skipQuadTree) + { + var bounds = {}; + + for (var i = 0; i < group.hash.length; i++) + { + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds object + bounds = object1.body.getBounds(bounds); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (sprite.body.right < bounds.x) + { + break; + } + else if (bounds.right < sprite.body.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (sprite.body.x > bounds.right) + { + break; + } + else if (bounds.x > sprite.body.right) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (sprite.body.bottom < bounds.y) + { + break; + } + else if (bounds.bottom < sprite.body.y) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (sprite.body.y > bounds.bottom) + { + break; + } + else if (bounds.y > sprite.body.bottom) + { + continue; + } + } + + this.collideSpriteVsSprite(sprite, object1, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + else + { + // What is the sprite colliding with in the quadtree? + 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 items = this.quadTree.retrieve(sprite); + + for (var i = 0; i < items.length; i++) + { + // We have our potential suspects, are they in this group? + if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly)) + { + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, items[i].sprite); + } + + this._total++; + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsSelf + * @private + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ + collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.hash.length; i++) + { + var bounds1 = {}; + var object1 = group.hash[i]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object1 || !object1.exists || !object1.body) + { + continue; + } + + // Inject the Body bounds data into the bounds1 object + bounds1 = object1.body.getBounds(bounds1); + + for (var j = i + 1; j < group.hash.length; j++) + { + var bounds2 = {}; + var object2 = group.hash[j]; + + // Skip duff entries - we can't check a non-existent sprite or one with no body + if (!object2 || !object2.exists || !object2.body) + { + continue; + } + + // Inject the Body bounds data into the bounds2 object + bounds2 = object2.body.getBounds(bounds2); + + // Skip items either side of the sprite + if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT) + { + if (bounds1.right < bounds2.x) + { + break; + } + else if (bounds2.right < bounds1.x) + { + continue; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT) + { + if (bounds1.x > bounds2.right) + { + continue; + } + else if (bounds2.x > bounds1.right) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM) + { + if (bounds1.bottom < bounds2.y) + { + continue; + } + else if (bounds2.bottom < bounds1.y) + { + break; + } + } + else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP) + { + if (bounds1.y > bounds2.bottom) + { + continue; + } + else if (bounds2.y > object1.body.bottom) + { + break; + } + } + + this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsGroup + * @private + * @param {Phaser.Group} group1 - The first Group to check. + * @param {Phaser.Group} group2 - The second Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group1.length === 0 || group2.length === 0) + { + return; + } + + for (var i = 0; i < group1.children.length; i++) + { + if (group1.children[i].exists) + { + if (group1.children[i].physicsType === Phaser.GROUP) + { + this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + else + { + this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + } + + }, + + /** + * The core separation function to separate two physics bodies. + * + * @private + * @method Phaser.Physics.Arcade#separate + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true. + * @param {object} [callbackContext] - The context in which to run the process callback. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} Returns true if the bodies collided, otherwise false. + */ + separate: function (body1, body2, processCallback, callbackContext, overlapOnly) { + + if ( + !body1.enable || + !body2.enable || + body1.checkCollision.none || + body2.checkCollision.none || + !this.intersects(body1, body2)) + { + return false; + } + + // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort. + if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false) + { + return false; + } + + // Circle vs. Circle quick bail out + if (body1.isCircle && body2.isCircle) + { + return this.separateCircle(body1, body2, overlapOnly); + } + + // We define the behavior of bodies in a collision circle and rectangle + // If a collision occurs in the corner points of the rectangle, the body behave like circles + + // Either body1 or body2 is a circle + if (body1.isCircle !== body2.isCircle) + { + var bodyRect = (body1.isCircle) ? body2 : body1; + var bodyCircle = (body1.isCircle) ? body1 : body2; + + var rect = { + x: bodyRect.x, + y: bodyRect.y, + right: bodyRect.right, + bottom: bodyRect.bottom + }; + + var circle = bodyCircle.center; + + if (circle.y < rect.y || circle.y > rect.bottom) + { + if (circle.x < rect.x || circle.x > rect.right) + { + return this.separateCircle(body1, body2, overlapOnly); + } + } + } + + var resultX = false; + var resultY = false; + + // Do we separate on x or y first? + if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) + { + resultX = this.separateX(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultY = this.separateY(body1, body2, overlapOnly); + } + } + else + { + resultY = this.separateY(body1, body2, overlapOnly); + + // Are they still intersecting? Let's do the other axis then + if (this.intersects(body1, body2)) + { + resultX = this.separateX(body1, body2, overlapOnly); + } + } + + var result = (resultX || resultY); + + if (result) + { + if (overlapOnly) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + else + { + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + } + } + + return result; + + }, + + /** + * Check for intersection against two bodies. + * + * @method Phaser.Physics.Arcade#intersects + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check. + * @return {boolean} True if they intersect, otherwise false. + */ + intersects: function (body1, body2) { + + if (body1 === body2) + { + return false; + } + + if (body1.isCircle) + { + if (body2.isCircle) + { + // Circle vs. Circle + return Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.halfWidth + body2.halfWidth); + } + else + { + // Circle vs. Rect + return this.circleBodyIntersects(body1, body2); + } + } + else + { + if (body2.isCircle) + { + // Rect vs. Circle + return this.circleBodyIntersects(body2, body1); + } + else + { + // Rect vs. Rect + if (body1.right <= body2.position.x) + { + return false; + } + + if (body1.bottom <= body2.position.y) + { + return false; + } + + if (body1.position.x >= body2.right) + { + return false; + } + + if (body1.position.y >= body2.bottom) + { + return false; + } + + return true; + } + } + + }, + + /** + * Checks to see if a circular Body intersects with a Rectangular Body. + * + * @method Phaser.Physics.Arcade#circleBodyIntersects + * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set. + * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape) + * @return {boolean} Returns true if the bodies intersect, otherwise false. + */ + circleBodyIntersects: function (circle, body) { + + var x = Phaser.Math.clamp(circle.center.x, body.left, body.right); + var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom); + + var dx = (circle.center.x - x) * (circle.center.x - x); + var dy = (circle.center.y - y) * (circle.center.y - y); + + return (dx + dy) <= (circle.halfWidth * circle.halfWidth); + + }, + + /** + * The core separation function to separate two circular physics bodies. + * + * @method Phaser.Physics.Arcade#separateCircle + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateCircle: function (body1, body2, overlapOnly) { + + // Set the bounding box overlap values + this.getOverlapX(body1, body2); + this.getOverlapY(body1, body2); + + var dx = body2.center.x - body1.center.x; + var dy = body2.center.y - body1.center.y; + + var angleCollision = Math.atan2(dy, dx); + + var overlap = 0; + + if (body1.isCircle !== body2.isCircle) + { + var rect = { + x: (body2.isCircle) ? body1.position.x : body2.position.x, + y: (body2.isCircle) ? body1.position.y : body2.position.y, + right: (body2.isCircle) ? body1.right : body2.right, + bottom: (body2.isCircle) ? body1.bottom : body2.bottom + }; + + var circle = { + x: (body1.isCircle) ? body1.center.x : body2.center.x, + y: (body1.isCircle) ? body1.center.y : body2.center.y, + radius: (body1.isCircle) ? body1.halfWidth : body2.halfWidth + }; + + if (circle.y < rect.y) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.y) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.y) - circle.radius; + } + } + else if (circle.y > rect.bottom) + { + if (circle.x < rect.x) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.bottom) - circle.radius; + } + else if (circle.x > rect.right) + { + overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.bottom) - circle.radius; + } + } + + overlap *= -1; + } + else + { + overlap = (body1.halfWidth + body2.halfWidth) - Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y); + } + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + if (overlap !== 0) + { + if (body1.onOverlap) + { + body1.onOverlap.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onOverlap) + { + body2.onOverlap.dispatch(body2.sprite, body1.sprite); + } + } + + // return true if there was some overlap, otherwise false + return (overlap !== 0); + } + + // Transform the velocity vector to the coordinate system oriented along the direction of impact. + // This is done to eliminate the vertical component of the velocity + var v1 = { + x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision), + y: body1.velocity.x * Math.sin(angleCollision) - body1.velocity.y * Math.cos(angleCollision) + }; + + var v2 = { + x: body2.velocity.x * Math.cos(angleCollision) + body2.velocity.y * Math.sin(angleCollision), + y: body2.velocity.x * Math.sin(angleCollision) - body2.velocity.y * Math.cos(angleCollision) + }; + + // We expect the new velocity after impact + var tempVel1 = ((body1.mass - body2.mass) * v1.x + 2 * body2.mass * v2.x) / (body1.mass + body2.mass); + var tempVel2 = (2 * body1.mass * v1.x + (body2.mass - body1.mass) * v2.x) / (body1.mass + body2.mass); + + // We convert the vector to the original coordinate system and multiplied by factor of rebound + if (!body1.immovable) + { + body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x; + body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y; + } + + if (!body2.immovable) + { + body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x; + body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y; + } + + // When the collision angle is almost perpendicular to the total initial velocity vector + // (collision on a tangent) vector direction can be determined incorrectly. + // This code fixes the problem + + if (Math.abs(angleCollision) < Math.PI / 2) + { + if ((body1.velocity.x > 0) && !body1.immovable && (body2.velocity.x > body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x < 0) && !body2.immovable && (body1.velocity.x < body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y > 0) && !body1.immovable && (body2.velocity.y > body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y < 0) && !body2.immovable && (body1.velocity.y < body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + else if (Math.abs(angleCollision) > Math.PI / 2) + { + if ((body1.velocity.x < 0) && !body1.immovable && (body2.velocity.x < body1.velocity.x)) + { + body1.velocity.x *= -1; + } + else if ((body2.velocity.x > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.x)) + { + body2.velocity.x *= -1; + } + else if ((body1.velocity.y < 0) && !body1.immovable && (body2.velocity.y < body1.velocity.y)) + { + body1.velocity.y *= -1; + } + else if ((body2.velocity.y > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.y)) + { + body2.velocity.y *= -1; + } + } + + if (!body1.immovable) + { + body1.x += (body1.velocity.x * this.game.time.physicsElapsed) - overlap * Math.cos(angleCollision); + body1.y += (body1.velocity.y * this.game.time.physicsElapsed) - overlap * Math.sin(angleCollision); + } + + if (!body2.immovable) + { + body2.x += (body2.velocity.x * this.game.time.physicsElapsed) + overlap * Math.cos(angleCollision); + body2.y += (body2.velocity.y * this.game.time.physicsElapsed) + overlap * Math.sin(angleCollision); + } + + if (body1.onCollide) + { + body1.onCollide.dispatch(body1.sprite, body2.sprite); + } + + if (body2.onCollide) + { + body2.onCollide.dispatch(body2.sprite, body1.sprite); + } + + return true; + + }, + + /** + * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: + * `touching.left`, `touching.right` and `overlapX`. + * + * @method Phaser.Physics.Arcade#getOverlapX + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of horizontal overlap between the two bodies. + */ + getOverlapX: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS; + + if (body1.deltaX() === 0 && body2.deltaX() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaX() > body2.deltaX()) + { + // Body1 is moving right and / or Body2 is moving left + overlap = body1.right - body2.x; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.right = true; + body2.touching.none = false; + body2.touching.left = true; + } + } + else if (body1.deltaX() < body2.deltaX()) + { + // Body1 is moving left and/or Body2 is moving right + overlap = body1.x - body2.width - body2.x; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.left = true; + body2.touching.none = false; + body2.touching.right = true; + } + } + + // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapX = overlap; + body2.overlapX = overlap; + + return overlap; + + }, + + /** + * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: + * `touching.up`, `touching.down` and `overlapY`. + * + * @method Phaser.Physics.Arcade#getOverlapY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of vertical overlap between the two bodies. + */ + getOverlapY: function (body1, body2, overlapOnly) { + + var overlap = 0; + var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS; + + if (body1.deltaY() === 0 && body2.deltaY() === 0) + { + // They overlap but neither of them are moving + body1.embedded = true; + body2.embedded = true; + } + else if (body1.deltaY() > body2.deltaY()) + { + // Body1 is moving down and/or Body2 is moving up + overlap = body1.bottom - body2.y; + + if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.down = true; + body2.touching.none = false; + body2.touching.up = true; + } + } + else if (body1.deltaY() < body2.deltaY()) + { + // Body1 is moving up and/or Body2 is moving down + overlap = body1.y - body2.bottom; + + if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false) + { + overlap = 0; + } + else + { + body1.touching.none = false; + body1.touching.up = true; + body2.touching.none = false; + body2.touching.down = true; + } + } + + // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is + body1.overlapY = overlap; + body2.overlapY = overlap; + + return overlap; + + }, + + /** + * The core separation function to separate two physics bodies on the x axis. + * + * @method Phaser.Physics.Arcade#separateX + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateX: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapX(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.x; + var v2 = body2.velocity.x; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.x -= overlap; + body2.x += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.x = avg + nv1 * body1.bounce.x; + body2.velocity.x = avg + nv2 * body2.bounce.x; + } + else if (!body1.immovable) + { + body1.x -= overlap; + body1.velocity.x = v2 - v1 * body1.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body2.moves) + { + body1.y += (body2.y - body2.prev.y) * body2.friction.y; + } + } + else + { + body2.x += overlap; + body2.velocity.x = v1 - v2 * body2.bounce.x; + + // This is special case code that handles things like vertically moving platforms you can ride + if (body1.moves) + { + body2.y += (body1.y - body1.prev.y) * body1.friction.y; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * The core separation function to separate two physics bodies on the y axis. + * + * @private + * @method Phaser.Physics.Arcade#separateY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ + separateY: function (body1, body2, overlapOnly) { + + var overlap = this.getOverlapY(body1, body2, overlapOnly); + + // Can't separate two immovable bodies, or a body with its own custom separation logic + if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY) + { + // return true if there was some overlap, otherwise false + return (overlap !== 0) || (body1.embedded && body2.embedded); + } + + // Adjust their positions and velocities accordingly (if there was any overlap) + var v1 = body1.velocity.y; + var v2 = body2.velocity.y; + + if (!body1.immovable && !body2.immovable) + { + overlap *= 0.5; + + body1.y -= overlap; + body2.y += overlap; + + var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1); + var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1); + var avg = (nv1 + nv2) * 0.5; + + nv1 -= avg; + nv2 -= avg; + + body1.velocity.y = avg + nv1 * body1.bounce.y; + body2.velocity.y = avg + nv2 * body2.bounce.y; + } + else if (!body1.immovable) + { + body1.y -= overlap; + body1.velocity.y = v2 - v1 * body1.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body2.moves) + { + body1.x += (body2.x - body2.prev.x) * body2.friction.x; + } + } + else + { + body2.y += overlap; + body2.velocity.y = v1 - v2 * body2.bounce.y; + + // This is special case code that handles things like horizontal moving platforms you can ride + if (body1.moves) + { + body2.x += (body1.x - body1.prev.x) * body1.friction.x; + } + } + + // If we got this far then there WAS overlap, and separation is complete, so return true + return true; + + }, + + /** + * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. + * + * @method Phaser.Physics.Arcade#getObjectsUnderPointer + * @param {Phaser.Pointer} pointer - The Pointer to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. + * @param {object} [callbackContext] - The context in which to run the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates. + */ + getObjectsUnderPointer: function (pointer, group, callback, callbackContext) { + + if (group.length === 0 || !pointer.exists) + { + return; + } + + return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer); + + }, + + /** + * Given a Group and a location this will check to see which Group children overlap with the coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. + * + * @method Phaser.Physics.Arcade#getObjectsAtLocation + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. + * @param {object} [callbackContext] - The context in which to run the callback. + * @param {object} [callbackArg] - An argument to pass to the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates. + */ + getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) { + + 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(x, y, 1, 1); + var output = []; + + var items = this.quadTree.retrieve(rect); + + for (var i = 0; i < items.length; i++) + { + if (items[i].hitTest(x, y)) + { + if (callback) + { + callback.call(callbackContext, callbackArg, items[i].sprite); + } + + output.push(items[i].sprite); + } + } + + return output; + + }, + + /** + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToObject: function (displayObject, destination, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Phaser.Point.angle(destination, displayObject); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#moveToPointer + * @param {any} displayObject - The display object to move. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToPointer: function (displayObject, speed, pointer, maxTime) { + + if (speed === undefined) { speed = 60; } + pointer = pointer || this.game.input.activePointer; + if (maxTime === undefined) { maxTime = 0; } + + var angle = this.angleToPointer(displayObject, pointer); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ + moveToXY: function (displayObject, x, y, speed, maxTime) { + + if (speed === undefined) { speed = 60; } + if (maxTime === undefined) { maxTime = 0; } + + var angle = Math.atan2(y - displayObject.y, x - displayObject.x); + + if (maxTime > 0) + { + // We know how many pixels we need to move, but how fast? + speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); + } + + displayObject.body.velocity.setToPolar(angle, speed); + + return angle; + + }, + + /** + * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromAngle + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromAngle: function (angle, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(angle, speed, true); + + }, + + /** + * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ + velocityFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. + * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. + * + * @method Phaser.Physics.Arcade#accelerationFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. + * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. + */ + accelerationFromRotation: function (rotation, speed, point) { + + if (speed === undefined) { speed = 60; } + point = point || new Phaser.Point(); + + return point.setToPolar(rotation, speed); + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleBetween(displayObject, destination); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToPointer + * @param {any} displayObject - The display object to move. + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToPointer(displayObject, pointer); + + displayObject.body.acceleration.setToPolar(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ + accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) { + + if (speed === undefined) { speed = 60; } + if (xSpeedMax === undefined) { xSpeedMax = 1000; } + if (ySpeedMax === undefined) { ySpeedMax = 1000; } + + var angle = this.angleToXY(displayObject, x, y); + + displayObject.body.acceleration.setTo(angle, speed); + displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); + + return angle; + + }, + + /** + * Find the distance between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * If you have nested objects and need to calculate the distance between their centers in World coordinates, + * set their anchors to (0.5, 0.5) and use the `world` argument. + * + * If objects aren't nested or they share a parent's offset, you can calculate the distance between their + * centers with the `useCenter` argument, regardless of their anchor values. + * + * @method Phaser.Physics.Arcade#distanceBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {number} The distance between the source and target objects. + */ + distanceBetween: function (source, target, world, useCenter) { + + if (world === undefined) { world = false; } + + var dx; + var dy; + + if (useCenter) + { + dx = source.centerX - target.centerX; + dy = source.centerY - target.centerY; + } + else if (world) + { + dx = source.world.x - target.world.x; + dy = source.world.y - target.world.y; + } + else + { + dx = source.x - target.x; + dy = source.y - target.y; + } + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and the given x/y coordinates. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the x/y coordinates. + */ + distanceToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - x : displayObject.x - x; + var dy = (world) ? displayObject.world.y - y : displayObject.y - y; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + /** + * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the Pointer. + */ + distanceToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + var dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.x - pointer.worldX; + var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY; + + return Math.sqrt(dx * dx + dy * dy); + + }, + + + /** + * From a set of points or display objects, find the one closest to a source point or object. + * + * @method Phaser.Physics.Arcade#closest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The first target closest to the origin. + */ + closest: function (source, targets, world, useCenter) { + var min = Infinity; + var closest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance < min) + { + closest = target; + min = distance; + } + } + + return closest; + }, + + /** + * From a set of points or display objects, find the one farthest from a source point or object. + * + * @method Phaser.Physics.Arcade#farthest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The target closest to the origin. + */ + farthest: function (source, targets, world, useCenter) { + var max = -1; + var farthest = null; + + for (var i = 0, len = targets.length; i < len; i++) + { + var target = targets[i]; + var distance = this.distanceBetween(source, target, world, useCenter); + + if (distance > max) + { + farthest = target; + max = distance; + } + } + + return farthest; + }, + + /** + * Find the angle in radians between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetween: function (source, target, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Phaser.Point.angle(target.world, source.world); + } + else + { + return Phaser.Point.angle(target, source); + } + + }, + + /** + * Find the angle in radians between centers of two display objects (like Sprites). + * + * @method Phaser.Physics.Arcade#angleBetweenCenters + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @return {number} The angle in radians between the source and target display objects. + */ + angleBetweenCenters: function (source, target) { + + var dx = target.centerX - source.centerX; + var dy = target.centerY - source.centerY; + + return Math.atan2(dy, dx); + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to get the angle to. + * @param {number} y - The y coordinate to get the angle to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToXY: function (displayObject, x, y, world) { + + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(y - displayObject.world.y, x - displayObject.world.x); + } + else + { + return Math.atan2(y - displayObject.y, x - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ + angleToPointer: function (displayObject, pointer, world) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (world === undefined) { world = false; } + + if (world) + { + return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x); + } + else + { + return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x); + } + + }, + + /** + * Find the angle in radians between a display object (like a Sprite) and a Pointer, + * taking their x/y and center into account relative to the world. + * + * @method Phaser.Physics.Arcade#worldAngleToPointer + * @param {any} displayObject - The DisplayObjerct to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY + */ + worldAngleToPointer: function (displayObject, pointer) { + + return this.angleToPointer(displayObject, pointer, true); + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than +* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. +* +* @class Phaser.Physics.Arcade.Body +* @constructor +* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. +*/ +Phaser.Physics.Arcade.Body = function (sprite) { + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = sprite.game; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.ARCADE; + + /** + * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. + * @default + */ + this.enable = true; + + /** + * If `true` this Body is using circular collision detection. If `false` it is using rectangular. + * Use `Body.setCircle` to control the collision shape this Body uses. + * @property {boolean} isCircle + * @default + * @readOnly + */ + this.isCircle = false; + + /** + * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled, relative to the Sprite's _texture_. + * If you wish to change the radius then call {@link #setCircle} again with the new value. + * If you wish to stop the Body using a circle then call {@link #setCircle} with a radius of zero (or undefined). + * The actual radius of the Body (at any Sprite scale) is equal to {@link #halfWidth} and the diameter is equal to {@link #width}. + * @property {number} radius + * @default + * @readOnly + */ + this.radius = 0; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite's texture. + */ + this.offset = new Phaser.Point(); + + /** + * @property {Phaser.Point} position - The position of the physics body, equivalent to ({@link #left}, {@link #top}). + * @readonly + */ + this.position = new Phaser.Point(sprite.x, sprite.y); + + /** + * @property {Phaser.Point} prev - The previous position of the physics body. + * @readonly + */ + this.prev = new Phaser.Point(this.position.x, this.position.y); + + /** + * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) + * @default + */ + this.allowRotation = true; + + /** + * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body + * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. + * @property {number} rotation + */ + this.rotation = sprite.angle; + + /** + * @property {number} preRotation - The previous rotation of the physics body, in degrees. + * @readonly + */ + this.preRotation = sprite.angle; + + /** + * @property {number} width - The calculated width of the physics body. + * @readonly + */ + this.width = sprite.width; + + /** + * @property {number} height - The calculated height of the physics body. + * @readonly + */ + this.height = sprite.height; + + /** + * @property {number} sourceWidth - The un-scaled original size. + * @readonly + */ + this.sourceWidth = sprite.width; + + /** + * @property {number} sourceHeight - The un-scaled original size. + * @readonly + */ + this.sourceHeight = sprite.height; + + if (sprite.texture) + { + this.sourceWidth = sprite.texture.frame.width; + this.sourceHeight = sprite.texture.frame.height; + } + + /** + * @property {number} halfWidth - The calculated width / 2 of the physics body. + * @readonly + */ + this.halfWidth = Math.abs(sprite.width / 2); + + /** + * @property {number} halfHeight - The calculated height / 2 of the physics body. + * @readonly + */ + this.halfHeight = Math.abs(sprite.height / 2); + + /** + * @property {Phaser.Point} center - The center coordinate of the Physics Body. + * @readonly + */ + this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight); + + /** + * @property {Phaser.Point} velocity - The velocity, or rate of change the Body's position. Measured in pixels per second. + */ + this.velocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} newVelocity - The distanced traveled during the last update, equal to `velocity * physicsElapsed`. Calculated during the Body.preUpdate and applied to its position. + * @readonly + */ + this.newVelocity = new Phaser.Point(); + + /** + * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. + */ + this.deltaMax = new Phaser.Point(); + + /** + * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + */ + this.acceleration = new Phaser.Point(); + + /** + * @property {boolean} allowDrag - Allow this Body to be influenced by {@link #drag}? + * @default + */ + this.allowDrag = true; + + /** + * @property {Phaser.Point} drag - The drag applied to the motion of the Body (when {@link #allowDrag} is enabled). Measured in pixels per second squared. + */ + this.drag = new Phaser.Point(); + + /** + * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local. + * @default + */ + this.allowGravity = true; + + /** + * @property {Phaser.Point} gravity - This Body's local gravity, **added** to any world gravity, unless Body.allowGravity is set to false. + */ + this.gravity = new Phaser.Point(); + + /** + * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. + */ + this.bounce = new Phaser.Point(); + + /** + * The elasticity of the Body when colliding with the World bounds. + * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property + * to a Phaser.Point object in order to enable a World bounds specific bounce value. + * @property {Phaser.Point} worldBounce + */ + this.worldBounce = null; + + /** + * A Signal that is dispatched when this Body collides with the world bounds. + * Due to the potentially high volume of signals this could create it is disabled by default. + * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` + * and it will be called when a collision happens, passing five arguments: + * `onWorldBounds(sprite, up, down, left, right)` + * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans + * indicating on which side of the world the Body collided. + * @property {Phaser.Signal} onWorldBounds + */ + this.onWorldBounds = null; + + /** + * A Signal that is dispatched when this Body collides with another Body. + * + * You still need to call `game.physics.arcade.collide` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `collide` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onCollide + */ + this.onCollide = null; + + /** + * A Signal that is dispatched when this Body overlaps with another Body. + * + * You still need to call `game.physics.arcade.overlap` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `overlap` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onOverlap + */ + this.onOverlap = null; + + /** + * @property {Phaser.Point} maxVelocity - The maximum velocity (in pixels per second squared) that the Body can reach. + * @default + */ + this.maxVelocity = new Phaser.Point(10000, 10000); + + /** + * @property {Phaser.Point} friction - If this Body is {@link #immovable} and moving, and another Body is 'riding' this one, this is the amount of motion the riding Body receives on each axis. + */ + this.friction = new Phaser.Point(1, 0); + + /** + * @property {number} angularVelocity - The angular velocity is the rate of change of the Body's rotation. It is measured in degrees per second. + * @default + */ + this.angularVelocity = 0; + + /** + * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. + * @default + */ + this.angularAcceleration = 0; + + /** + * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach. + * @default + */ + this.maxAngular = 1000; + + /** + * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. + * @default + */ + this.mass = 1; + + /** + * @property {number} angle - The angle of the Body's **velocity** in radians. + * @readonly + */ + this.angle = 0; + + /** + * @property {number} speed - The speed of the Body in pixels per second, equal to the magnitude of the velocity. + * @readonly + */ + this.speed = 0; + + /** + * @property {number} facing - A const reference to the direction the Body is traveling or facing: Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.UP, or Phaser.DOWN. If the Body is moving on both axes, UP and DOWN take precedence. + * @default + */ + this.facing = Phaser.NONE; + + /** + * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. **Two** immovable Bodies can't separate or exchange momentum and will pass through each other. + * @default + */ + this.immovable = false; + + /** + * Whether the physics system should update the Body's position and rotation based on its velocity, acceleration, drag, and gravity. + * + * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never + * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. + * If you want the physics system to move the body around, then set moves to true. + * + * A Body with moves = false can still be moved slightly (but not accelerated) during collision separation unless you set {@link #immovable} as well. + * + * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually. + * @default + */ + this.moves = true; + + /** + * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateX = false; + + /** + * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? + * @default + */ + this.customSeparateY = false; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapX - The amount of horizontal overlap during the collision. + */ + this.overlapX = 0; + + /** + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapY - The amount of vertical overlap during the collision. + */ + this.overlapY = 0; + + /** + * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. + * @property {number} overlapR - The amount of overlap during the collision. + */ + this.overlapR = 0; + + /** + * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. + * @property {boolean} embedded - Body embed value. + */ + this.embedded = false; + + /** + * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. + * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? + */ + this.collideWorldBounds = false; + + /** + * Set the checkCollision properties to control which directions collision is processed for this Body. + * For example checkCollision.up = false means it won't collide when the collision happened while moving up. + * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. + * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. + * @property {object} checkCollision - An object containing allowed collision (none, up, down, left, right). + */ + this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; + + /** + * This object is populated with boolean values when the Body collides with another. + * touching.up = true means the collision happened to the top of this Body for example. + * @property {object} touching - An object containing touching results (none, up, down, left, right). + */ + this.touching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with previous touching values from the bodies previous collision. + * @property {object} wasTouching - An object containing previous touching results (none, up, down, left, right). + */ + this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; + + /** + * This object is populated with boolean values when the Body collides with the World bounds or a Tile. + * For example if blocked.up is true then the Body cannot move up. + * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any (none, up, down, left, right). + */ + this.blocked = { none: true, up: false, down: false, left: false, right: false }; + + /** + * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. + * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. + * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision. + */ + this.tilePadding = new Phaser.Point(); + + /** + * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state? + */ + this.dirty = false; + + /** + * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. + */ + this.skipQuadTree = false; + + /** + * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. + * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. + * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, + * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. + * @property {boolean} syncBounds + * @default + */ + this.syncBounds = false; + + /** + * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods. + */ + this.isMoving = false; + + /** + * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods. + */ + this.stopVelocityOnCollide = true; + + /** + * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveTimer = 0; + + /** + * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDistance = 0; + + /** + * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods. + * @private + */ + this.moveDuration = 0; + + /** + * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveTarget = null; + + /** + * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame. + * @private + */ + this.moveEnd = null; + + /** + * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events. + */ + this.onMoveComplete = new Phaser.Signal(); + + /** + * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. + */ + this.movementCallback = null; + + /** + * @property {object} movementCallbackContext - Context in which to call the movementCallback. + */ + this.movementCallbackContext = null; + + /** + * @property {boolean} _reset - Internal cache var. + * @private + */ + this._reset = true; + + /** + * @property {number} _sx - Internal cache var. + * @private + */ + this._sx = sprite.scale.x; + + /** + * @property {number} _sy - Internal cache var. + * @private + */ + this._sy = sprite.scale.y; + + /** + * @property {number} _dx - Internal cache var. + * @private + */ + this._dx = 0; + + /** + * @property {number} _dy - Internal cache var. + * @private + */ + this._dy = 0; + +}; + +Phaser.Physics.Arcade.Body.prototype = { + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @protected + */ + updateBounds: function () { + + if (this.syncBounds) + { + var b = this.sprite.getBounds(); + b.ceilAll(); + + if (b.width !== this.width || b.height !== this.height) + { + this.width = b.width; + this.height = b.height; + this._reset = true; + } + } + else + { + 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._sx = asx; + this._sy = asy; + this._reset = true; + } + } + + if (this._reset) + { + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.updateCenter(); + } + + }, + + /** + * Update the Body's center from its position. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @protected + */ + updateCenter: function () { + + this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight); + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @protected + */ + preUpdate: function () { + + if (!this.enable || this.game.physics.arcade.isPaused) + { + return; + } + + this.dirty = true; + + // Store and reset collision flags + 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.none = true; + this.blocked.up = false; + this.blocked.down = false; + this.blocked.left = false; + this.blocked.right = false; + + this.overlapR = 0; + this.overlapX = 0; + this.overlapY = 0; + + this.embedded = false; + + this.updateBounds(); + + this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.updateCenter(); + + this.rotation = this.sprite.angle; + + this.preRotation = this.rotation; + + if (this._reset || this.sprite.fresh) + { + 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; + this.updateCenter(); + + if (this.position.x !== this.prev.x || this.position.y !== this.prev.y) + { + this.angle = this.velocity.atan(); + } + + this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); + + // Now the State update will throw collision checks at the Body + // And finally we'll integrate the new position back to the Sprite in postUpdate + + if (this.collideWorldBounds) + { + if (this.checkWorldBounds() && this.onWorldBounds) + { + this.onWorldBounds.dispatch(this.sprite, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right); + } + } + } + + this._dx = this.deltaX(); + this._dy = this.deltaY(); + + this._reset = false; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateMovement + * @protected + */ + updateMovement: function () { + + var percent = 0; + var collided = (this.overlapX !== 0 || this.overlapY !== 0); + + // Duration or Distance based? + + if (this.moveDuration > 0) + { + this.moveTimer += this.game.time.elapsedMS; + + percent = this.moveTimer / this.moveDuration; + } + else + { + this.moveTarget.end.set(this.position.x, this.position.y); + + percent = this.moveTarget.length / this.moveDistance; + } + + if (this.movementCallback) + { + var result = this.movementCallback.call(this.movementCallbackContext, this, this.velocity, percent); + } + + if (collided || percent >= 1 || (result !== undefined && result !== true)) + { + this.stopMovement((percent >= 1) || (this.stopVelocityOnCollide && collided)); + return false; + } + + return true; + + }, + + /** + * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it + * has Body.isMoving true), then calling this method will stop the movement before + * either the duration or distance counters expire. + * + * The `onMoveComplete` signal is dispatched. + * + * @method Phaser.Physics.Arcade.Body#stopMovement + * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero? + */ + stopMovement: function (stopVelocity) { + + if (this.isMoving) + { + this.isMoving = false; + + if (stopVelocity) + { + this.velocity.set(0); + } + + // Send the Sprite this Body belongs to + // and a boolean indicating if it stopped because of a collision or not + this.onMoveComplete.dispatch(this.sprite, (this.overlapX !== 0 || this.overlapY !== 0)); + } + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @protected + */ + postUpdate: function () { + + // Only allow postUpdate to be called once per frame + if (!this.enable || !this.dirty) + { + return; + } + + // Moving? + if (this.isMoving) + { + this.updateMovement(); + } + + this.dirty = false; + + 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.position.x += this._dx; + this.sprite.position.y += this._dy; + this._reset = true; + } + + this.updateCenter(); + + if (this.allowRotation) + { + this.sprite.angle += this.deltaZ(); + } + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + }, + + /** + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @protected + * @return {boolean} True if the Body collided with the world bounds, otherwise false. + */ + checkWorldBounds: function () { + + var pos = this.position; + var bounds = this.game.physics.arcade.bounds; + var check = this.game.physics.arcade.checkCollision; + + var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x; + var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y; + + if (pos.x < bounds.x && check.left) + { + pos.x = bounds.x; + this.velocity.x *= bx; + this.blocked.left = true; + this.blocked.none = false; + } + else if (this.right > bounds.right && check.right) + { + pos.x = bounds.right - this.width; + this.velocity.x *= bx; + this.blocked.right = true; + this.blocked.none = false; + } + + if (pos.y < bounds.y && check.up) + { + pos.y = bounds.y; + this.velocity.y *= by; + this.blocked.up = true; + this.blocked.none = false; + } + else if (this.bottom > bounds.bottom && check.down) + { + pos.y = bounds.bottom - this.height; + this.velocity.y *= by; + this.blocked.down = true; + this.blocked.none = false; + } + + return !this.blocked.none; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal timer, and then + * monitoring the duration each frame. When the duration is up the movement is + * stopped and the `Body.onMoveComplete` signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * You can optionally set a speed in pixels per second. If not specified it + * will use the current `Body.speed` value. If this is zero, the function will return false. + * + * Please note that due to browser timings you should allow for a variance in + * when the duration will actually expire. Depending on system it may be as much as + * +- 50ms. Also this method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveFrom + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveFrom: function (duration, speed, direction) { + + if (speed === undefined) { speed = this.speed; } + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + this.moveTimer = 0; + this.moveDuration = duration; + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal distance counter. + * The distance is monitored each frame. When the distance equals the distance + * specified in this call, the movement is stopped, and the `Body.onMoveComplete` + * signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * Please note that due to browser timings you should allow for a variance in + * when the distance will actually expire. + * + * Note: This method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveTo + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} distance - The distance, in pixels, the Body will move. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ + moveTo: function (duration, distance, direction) { + + var speed = distance / (duration / 1000); + + if (speed === 0) + { + return false; + } + + var angle; + + if (direction === undefined) + { + angle = this.angle; + direction = this.game.math.radToDeg(angle); + } + else + { + angle = this.game.math.degToRad(direction); + } + + distance = Math.abs(distance); + + this.moveDuration = 0; + this.moveDistance = distance; + + if (this.moveTarget === null) + { + this.moveTarget = new Phaser.Line(); + this.moveEnd = new Phaser.Point(); + } + + this.moveTarget.fromAngle(this.x, this.y, angle, distance); + + this.moveEnd.set(this.moveTarget.end.x, this.moveTarget.end.y); + + this.moveTarget.setTo(this.x, this.y, this.x, this.y); + + // Avoid sin/cos + if (direction === 0 || direction === 180) + { + this.velocity.set(Math.cos(angle) * speed, 0); + } + else if (direction === 90 || direction === 270) + { + this.velocity.set(0, Math.sin(angle) * speed); + } + else + { + this.velocity.setToPolar(angle, speed); + } + + this.isMoving = true; + + return true; + + }, + + /** + * You can modify the size of the physics Body to be any dimension you need. + * This allows you to make it smaller, or larger, than the parent Sprite. You + * can also control the x and y offset of the Body. + * + * The width, height, and offset arguments are relative to the Sprite + * _texture_ and are scaled with the Sprite's {@link Phaser.Sprite#scale} + * (but **not** the scale of any ancestors or the {@link Phaser.Camera#scale + * Camera scale}). + * + * For example: If you have a Sprite with a texture that is 80x100 in size, + * and you want the physics body to be 32x32 pixels in the middle of the + * texture, you would do: + * + * `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, + * 34)` + * + * Where the first two parameters are the new Body size (32x32 pixels) + * relative to the Sprite's scale. 24 is the horizontal offset of the Body + * from the top-left of the Sprites texture, and 34 is the vertical offset. + * + * If you've scaled a Sprite by altering its `width`, `height`, or `scale` + * and you want to position the Body relative to the Sprite's dimensions + * (which will differ from its texture's dimensions), you should divide these + * arguments by the Sprite's current scale: + * + * `setSize(32 / sprite.scale.x, 32 / sprite.scale.y)` + * + * Calling `setSize` on a Body that has already had `setCircle` will reset + * all of the Circle properties, making this Body rectangular again. + * @method Phaser.Physics.Arcade.Body#setSize + * @param {number} width - The width of the Body, relative to the Sprite's + * texture. + * @param {number} height - The height of the Body, relative to the Sprite's + * texture. + * @param {number} [offsetX] - The X offset of the Body from the left of the + * Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the + * Sprite's texture. + */ + setSize: function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { 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.updateCenter(); + + this.isCircle = false; + this.radius = 0; + + }, + + /** + * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. + * The radius is given in pixels (relative to the Sprite's _texture_) and is the distance from the center of the circle to the edge. + * + * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite's texture. + * + * To change a Body back to being rectangular again call `Body.setSize`. + * + * Note: Circular collision only happens with other Arcade Physics bodies, it does not + * work against tile maps, where rectangular collision is the only method supported. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. + * @param {number} [offsetX] - The X offset of the Body from the left of the Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the Sprite's texture. + */ + setCircle: function (radius, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = this.offset.x; } + if (offsetY === undefined) { offsetY = this.offset.y; } + + if (radius > 0) + { + this.isCircle = true; + this.radius = radius; + + this.sourceWidth = radius * 2; + this.sourceHeight = radius * 2; + + 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.updateCenter(); + } + else + { + this.isCircle = false; + } + + }, + + /** + * Resets all Body values (velocity, acceleration, rotation, etc) + * + * @method Phaser.Physics.Arcade.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new y position of the Body. + */ + reset: function (x, y) { + + this.stop(); + + this.position.x = (x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; + this.position.x -= this.sprite.scale.x < 0 ? this.width : 0; + + this.position.y = (y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y; + this.position.y -= this.sprite.scale.y < 0 ? this.height : 0; + + this.prev.x = this.position.x; + this.prev.y = this.position.y; + + this.rotation = this.sprite.angle; + this.preRotation = this.rotation; + + this.updateBounds(); + + this.updateCenter(); + + }, + + /** + * Sets acceleration, velocity, and {@link #speed} to 0. + * + * @method Phaser.Physics.Arcade.Body#stop + */ + stop: function () { + + this.velocity.set(0); + this.acceleration.set(0); + this.speed = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + + }, + + /** + * Returns the bounds of this physics body. + * + * Only used internally by the World collision methods. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @param {object} obj - The object in which to set the bounds values. + * @return {object} The object that was given to this method. + */ + getBounds: function (obj) { + + obj.x = this.x; + obj.y = this.y; + obj.right = this.right; + obj.bottom = this.bottom; + + return obj; + + }, + + /** + * Tests if a world point lies within this Body. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @param {number} x - The world x coordinate to test. + * @param {number} y - The world y coordinate to test. + * @return {boolean} True if the given coordinates are inside this Body, otherwise false. + */ + hitTest: function (x, y) { + + return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y); + + }, + + /** + * Returns true if the bottom of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onFloor: function () { + + return this.blocked.down; + + }, + + /** + * Returns true if the top of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onCeiling: function(){ + + return this.blocked.up; + + }, + + /** + * Returns true if either side of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @return {boolean} True if in contact with either the world bounds or a tile. + */ + onWall: function () { + + return (this.blocked.left || this.blocked.right); + + }, + + /** + * Returns the absolute delta x value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @return {number} The absolute delta value. + */ + deltaAbsX: function () { + + return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); + + }, + + /** + * Returns the absolute delta y value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @return {number} The absolute delta value. + */ + deltaAbsY: function () { + + return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); + + }, + + /** + * Returns the delta x value. The difference between Body.x now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. + */ + deltaX: function () { + + return this.position.x - this.prev.x; + + }, + + /** + * Returns the delta y value. The difference between Body.y now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. + */ + deltaY: function () { + + return this.position.y - this.prev.y; + + }, + + /** + * Returns the delta z value. The difference between Body.rotation now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise. + */ + deltaZ: function () { + + return this.rotation - this.preRotation; + + }, + + /** + * Destroys this Body. + * + * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. + * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. + * + * @method Phaser.Physics.Arcade.Body#destroy + */ + destroy: function () { + + if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group) + { + this.sprite.parent.removeFromHash(this.sprite); + } + + this.sprite.body = null; + this.sprite = null; + + } + +}; + +/** +* @name Phaser.Physics.Arcade.Body#left +* @property {number} left - The x position of the Body. The same as `Body.x`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "left", { + + get: function () { + + return this.position.x; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#right +* @property {number} right - The right value of this Body (same as Body.x + Body.width) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", { + + get: function () { + + return this.position.x + this.width; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#top +* @property {number} top - The y position of the Body. The same as `Body.y`. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "top", { + + get: function () { + + return this.position.y; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#bottom +* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) +* @readonly +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", { + + get: function () { + + return this.position.y + this.height; + + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#x +* @property {number} x - The x position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", { + + get: function () { + + return this.position.x; + + }, + + set: function (value) { + + this.position.x = value; + } + +}); + +/** +* @name Phaser.Physics.Arcade.Body#y +* @property {number} y - The y position. +*/ +Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", { + + get: function () { + + return this.position.y; + + }, + + set: function (value) { + + this.position.y = value; + + } + +}); + +/** +* Render Sprite Body. +* +* @method Phaser.Physics.Arcade.Body#render +* @param {object} context - The context to render to. +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string). +* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) +* @param {number} [lineWidth=1] - The width of the stroke when unfilled. +*/ +Phaser.Physics.Arcade.Body.render = function (context, body, color, filled, lineWidth) { + + if (filled === undefined) { filled = true; } + + color = color || 'rgba(0,255,0,0.4)'; + + context.fillStyle = color; + context.strokeStyle = color; + context.lineWidth = lineWidth || 1; + + if (body.isCircle) + { + context.beginPath(); + context.arc(body.center.x - body.game.camera.x, body.center.y - body.game.camera.y, body.halfWidth, 0, 2 * Math.PI); + + if (filled) + { + context.fill(); + } + else + { + context.stroke(); + } + } + else + { + if (filled) + { + context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + else + { + context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); + } + } + +}; + +/** +* Render Sprite Body Physics Data as text. +* +* @method Phaser.Physics.Arcade.Body#renderBodyInfo +* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. +* @param {number} x - X position of the debug info to be rendered. +* @param {number} y - Y position of the debug info to be rendered. +* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). +*/ +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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Arcade Physics Tile map collision methods. +* +* @class Phaser.Physics.Arcade.TilemapCollision +* @constructor +*/ +Phaser.Physics.Arcade.TilemapCollision = function () {}; + +Phaser.Physics.Arcade.TilemapCollision.prototype = { + + /** + * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling. + */ + TILE_BIAS: 16, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (!sprite.body) + { + return; + } + + var mapData = tilemapLayer.getTiles( + sprite.body.position.x - sprite.body.tilePadding.x - tilemapLayer.getTileOffsetX(), + sprite.body.position.y - sprite.body.tilePadding.y - tilemapLayer.getTileOffsetY(), + sprite.body.width + sprite.body.tilePadding.x, + sprite.body.height + sprite.body.tilePadding.y, + false, false); + + if (mapData.length === 0) + { + return; + } + + for (var i = 0; i < mapData.length; i++) + { + if (processCallback) + { + if (processCallback.call(callbackContext, sprite, mapData[i])) + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + else + { + if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly)) + { + this._total++; + + if (collideCallback) + { + collideCallback.call(callbackContext, sprite, mapData[i]); + } + } + } + } + + }, + + /** + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @private + * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer + * @param {Phaser.Group} group - The Group to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ + collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { + + if (group.length === 0) + { + return; + } + + for (var i = 0; i < group.children.length; i++) + { + if (group.children[i].exists) + { + this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly); + } + } + + }, + + /** + * The core separation function to separate a physics body and a tile. + * + * @private + * @method Phaser.Physics.Arcade#separateTile + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to collide against. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {boolean} Returns true if the body was separated, otherwise false. + */ + separateTile: function (i, body, tile, tilemapLayer, overlapOnly) { + + if (!body.enable) + { + return false; + } + + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + // We re-check for collision in case body was separated in a previous step + if (!tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + // no collision so bail out (separated in a previous step) + return false; + } + else if (overlapOnly) + { + // There is an overlap, and we don't need to separate. Bail. + return true; + } + + // They overlap. Any custom callbacks? + + // A local callback always takes priority over a layer level callback + if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + else if (typeof tile.layer.callbacks !== 'undefined' && tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile)) + { + // If it returns true then we can carry on, otherwise we should abort. + return false; + } + + // We don't need to go any further if this tile doesn't actually separate + if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom) + { + // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation + return false; + } + + var ox = 0; + var oy = 0; + var minX = 0; + var minY = 1; + + if (body.deltaAbsX() > body.deltaAbsY()) + { + // Moving faster horizontally, check X axis first + minX = -1; + } + else if (body.deltaAbsX() < body.deltaAbsY()) + { + // Moving faster vertically, check Y axis first + minY = -1; + } + + if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom)) + { + // We only need do this if both axis have checking faces AND we're moving in both directions + minX = Math.min(Math.abs((body.position.x - tilemapLayerOffsetX) - tile.right), Math.abs((body.right - tilemapLayerOffsetX) - tile.left)); + minY = Math.min(Math.abs((body.position.y - tilemapLayerOffsetY) - tile.bottom), Math.abs((body.bottom - tilemapLayerOffsetY) - tile.top)); + } + + if (minX < minY) + { + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + + // That's horizontal done, check if we still intersects? If not then we can return now + if (ox !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + } + } + else + { + if (tile.faceTop || tile.faceBottom) + { + oy = this.tileCheckY(body, tile, tilemapLayer); + + // That's vertical done, check if we still intersects? If not then we can return now + if (oy !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY))) + { + return true; + } + } + + if (tile.faceLeft || tile.faceRight) + { + ox = this.tileCheckX(body, tile, tilemapLayer); + } + } + + return (ox !== 0 || oy !== 0); + + }, + + /** + * Check the body against the given tile on the X axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckX: function (body, tile, tilemapLayer) { + + var ox = 0; + var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); + + if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left) + { + // Body is moving LEFT + if (tile.faceRight && (body.x - tilemapLayerOffsetX) < tile.right) + { + ox = (body.x - tilemapLayerOffsetX) - tile.right; + + if (ox < -this.TILE_BIAS) + { + ox = 0; + } + } + } + else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right) + { + // Body is moving RIGHT + if (tile.faceLeft && (body.right - tilemapLayerOffsetX) > tile.left) + { + ox = (body.right - tilemapLayerOffsetX) - tile.left; + + if (ox > this.TILE_BIAS) + { + ox = 0; + } + } + } + + if (ox !== 0) + { + if (body.customSeparateX) + { + body.overlapX = ox; + } + else + { + this.processTileSeparationX(body, ox); + } + } + + return ox; + + }, + + /** + * Check the body against the given tile on the Y axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ + tileCheckY: function (body, tile, tilemapLayer) { + + var oy = 0; + var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); + + if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up) + { + // Body is moving UP + if (tile.faceBottom && (body.y - tilemapLayerOffsetY) < tile.bottom) + { + oy = (body.y - tilemapLayerOffsetY) - tile.bottom; + + if (oy < -this.TILE_BIAS) + { + oy = 0; + } + } + } + else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down) + { + // Body is moving DOWN + if (tile.faceTop && (body.bottom - tilemapLayerOffsetY) > tile.top) + { + oy = (body.bottom - tilemapLayerOffsetY) - tile.top; + + if (oy > this.TILE_BIAS) + { + oy = 0; + } + } + } + + if (oy !== 0) + { + if (body.customSeparateY) + { + body.overlapY = oy; + } + else + { + this.processTileSeparationY(body, oy); + } + } + + return oy; + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} x - The x separation amount. + */ + processTileSeparationX: function (body, x) { + + if (x < 0) + { + body.blocked.left = true; + body.blocked.none = false; + } + else if (x > 0) + { + body.blocked.right = true; + body.blocked.none = false; + } + + body.position.x -= x; + + if (body.bounce.x === 0) + { + body.velocity.x = 0; + } + else + { + body.velocity.x = -body.velocity.x * body.bounce.x; + } + + }, + + /** + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} y - The y separation amount. + */ + processTileSeparationY: function (body, y) { + + if (y < 0) + { + body.blocked.up = true; + body.blocked.none = false; + } + else if (y > 0) + { + body.blocked.down = true; + body.blocked.none = false; + } + + body.position.y -= y; + + if (body.bounce.y === 0) + { + body.velocity.y = 0; + } + else + { + body.velocity.y = -body.velocity.y * body.bounce.y; + } + + } + +}; + +// Merge this with the Arcade Physics prototype +Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Add an extra properties to p2 that we need +p2.Body.prototype.parent = null; +p2.Spring.prototype.parent = null; + +/** +* This is your main access to the P2 Physics World. +* From here you can create materials, listen for events and add bodies into the physics simulation. +* +* @class Phaser.Physics.P2 +* @constructor +* @param {Phaser.Game} game - Reference to the current game instance. +* @param {object} [config] - Physics configuration object passed in from the game constructor. +*/ +Phaser.Physics.P2 = function (game, config) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + if (config === undefined) + { + config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; + } + else + { + if (!config.hasOwnProperty('gravity')) + { + config.gravity = [0, 0]; + } + + if (!config.hasOwnProperty('broadphase')) + { + config.broadphase = new p2.SAPBroadphase(); + } + } + + /** + * @property {object} config - The p2 World configuration object. + * @protected + */ + this.config = config; + + /** + * @property {p2.World} world - The p2 World in which the simulation is run. + * @protected + */ + this.world = new p2.World(this.config); + + /** + * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. + * @default + */ + this.frameRate = 1 / 60; + + /** + * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. + * @default + */ + this.useElapsedTime = false; + + /** + * @property {boolean} paused - The paused state of the P2 World. + * @default + */ + this.paused = false; + + /** + * @property {array} materials - A local array of all created Materials. + * @protected + */ + this.materials = []; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. + */ + this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); + + /** + * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. + */ + this.walls = { left: null, right: null, top: null, bottom: null }; + + /** + * This signal is dispatched when a new Body is added to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world. + * + * @property {Phaser.Signal} onBodyAdded + */ + this.onBodyAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Body is removed to the World. + * + * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world. + * + * @property {Phaser.Signal} onBodyRemoved + */ + this.onBodyRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is added to the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world. + * + * @property {Phaser.Signal} onSpringAdded + */ + this.onSpringAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Spring is removed from the World. + * + * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world. + * + * @property {Phaser.Signal} onSpringRemoved + */ + this.onSpringRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is added to the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world. + * + * @property {Phaser.Signal} onConstraintAdded + */ + this.onConstraintAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Constraint is removed from the World. + * + * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world. + * + * @property {Phaser.Signal} onConstraintRemoved + */ + this.onConstraintRemoved = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is added to the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world. + * + * @property {Phaser.Signal} onContactMaterialAdded + */ + this.onContactMaterialAdded = new Phaser.Signal(); + + /** + * This signal is dispatched when a Contact Material is removed from the World. + * + * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world. + * + * @property {Phaser.Signal} onContactMaterialRemoved + */ + this.onContactMaterialRemoved = new Phaser.Signal(); + + /** + * @property {function} postBroadphaseCallback - A postBroadphase callback. + */ + this.postBroadphaseCallback = null; + + /** + * @property {object} callbackContext - The context under which the callbacks are fired. + */ + this.callbackContext = null; + + /** + * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done. + * + * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done. + * + * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`. + * + * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this + * in your own code to avoid processing potentially null physics bodies. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + // Pixel to meter function overrides + if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) + { + this.mpx = config.mpx; + this.mpxi = config.mpxi; + this.pxm = config.pxm; + this.pxmi = config.pxmi; + } + + // Hook into the World events + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + /** + * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. + */ + this.collisionGroups = []; + + /** + * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. + */ + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. + */ + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + + /** + * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. + */ + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + /** + * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. + */ + this.boundsCollidesWith = []; + + /** + * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. + * @private + */ + this._toRemove = []; + + /** + * @property {number} _collisionGroupID - Internal var. + * @private + */ + this._collisionGroupID = 2; + + /** + * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsLeft = true; + + /** + * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsRight = true; + + /** + * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsTop = true; + + /** + * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsBottom = true; + + /** + * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings. + * @private + */ + this._boundsOwnGroup = false; + + // By default we want everything colliding with everything + this.setBoundsToWorld(true, true, true, true, false); + +}; + +Phaser.Physics.P2.prototype = { + + /** + * This will add a P2 Physics body into the removal list for the next step. + * + * @method Phaser.Physics.P2#removeBodyNextStep + * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. + */ + removeBodyNextStep: function (body) { + + this._toRemove.push(body); + + }, + + /** + * Called at the start of the core update loop. Purges flagged bodies from the world. + * + * @method Phaser.Physics.P2#preUpdate + */ + preUpdate: function () { + + var i = this._toRemove.length; + + while (i--) + { + this.removeBody(this._toRemove[i]); + } + + this._toRemove.length = 0; + + }, + + /** + * This will create a P2 Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. + * + * @method Phaser.Physics.P2#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [debug=false] - Create a debug object to go with this body? + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ + enable: function (object, debug, children) { + + if (debug === undefined) { debug = false; } + if (children === undefined) { children = true; } + + var i = 1; + + if (Array.isArray(object)) + { + i = object.length; + + while (i--) + { + if (object[i] instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + this.enable(object[i].children, debug, children); + } + else + { + this.enableBody(object[i], debug); + + if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) + { + this.enable(object[i], debug, true); + } + } + } + } + else + { + if (object instanceof Phaser.Group) + { + // If it's a Group then we do it on the children regardless + 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); + } + } + } + + }, + + /** + * Creates a P2 Physics body on the given game object. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * @method Phaser.Physics.P2#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + * @param {boolean} debug - Create a debug object to go with this body? + */ + 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; + if (typeof object.anchor !== 'undefined') { + object.anchor.set(0.5); + } + } + + }, + + /** + * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. + * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. + * + * @method Phaser.Physics.P2#setImpactEvents + * @param {boolean} state - Set to true to enable impact events, or false to disable. + */ + setImpactEvents: function (state) { + + if (state) + { + this.world.on("impact", this.impactHandler, this); + } + else + { + this.world.off("impact", this.impactHandler, this); + } + + }, + + /** + * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. + * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. + * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. + * Returning `true` from the callback will ensure they are checked in the narrowphase. + * + * @method Phaser.Physics.P2#setPostBroadphaseCallback + * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. + * @param {object} context - The context under which the callback will be fired. + */ + 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); + } + + }, + + /** + * Internal handler for the postBroadphase event. + * + * @method Phaser.Physics.P2#postBroadphaseHandler + * @private + * @param {object} event - The event data. + */ + postBroadphaseHandler: function (event) { + + if (!this.postBroadphaseCallback || event.pairs.length === 0) + { + return; + } + + for (var i = event.pairs.length - 2; i >= 0; 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); + } + } + + }, + + /** + * Handles a p2 impact event. + * + * @method Phaser.Physics.P2#impactHandler + * @private + * @param {object} event - The event data. + */ + impactHandler: function (event) { + + if (event.bodyA.parent && event.bodyB.parent) + { + // Body vs. Body callbacks + 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); + } + + // Body vs. Group callbacks + 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); + } + } + + }, + + /** + * Handles a p2 begin contact event. + * + * @method Phaser.Physics.P2#beginContactHandler + * @param {object} event - The event data. + */ + beginContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + 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.bodyB, event.shapeA, event.shapeB, event.contactEquations); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations); + } + } + + }, + + /** + * Handles a p2 end contact event. + * + * @method Phaser.Physics.P2#endContactHandler + * @param {object} event - The event data. + */ + endContactHandler: function (event) { + + if (event.bodyA && event.bodyB) + { + this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); + + if (event.bodyA.parent) + { + event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB); + } + + if (event.bodyB.parent) + { + event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA); + } + } + + }, + + /** + * Sets the bounds of the Physics world to match the Game.World dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * + * @method Phaser.Physics#setBoundsToWorld + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + 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); + + }, + + /** + * Sets the given material against the 4 bounds of this World. + * + * @method Phaser.Physics#setWorldMaterial + * @param {Phaser.Physics.P2.Material} material - The material to set. + * @param {boolean} [left=true] - If true will set the material on the left bounds wall. + * @param {boolean} [right=true] - If true will set the material on the right bounds wall. + * @param {boolean} [top=true] - If true will set the material on the top bounds wall. + * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. + */ + setWorldMaterial: function (material, left, right, top, bottom) { + + if (left === undefined) { left = true; } + if (right === undefined) { right = true; } + if (top === undefined) { top = true; } + if (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; + } + + }, + + /** + * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. + * If you start to use your own collision groups then your objects will no longer collide with the bounds. + * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. + * + * @method Phaser.Physics.P2#updateBoundsCollisionGroup + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + updateBoundsCollisionGroup: function (setCollisionGroup) { + + if (setCollisionGroup === undefined) { setCollisionGroup = true; } + + var mask = (setCollisionGroup) ? this.boundsCollisionGroup.mask : this.everythingCollisionGroup.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; + } + + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Sets the bounds of the Physics world to match the given world pixel dimensions. + * You can optionally set which 'walls' to create: left, right, top or bottom. + * If none of the walls are given it will default to use the walls settings it had previously. + * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size + * the newly created bounds will also not have the left and right walls. + * Explicitly state them in the parameters to override this. + * + * @method Phaser.Physics.P2#setBounds + * @param {number} x - The x coordinate of the top-left corner of the bounds. + * @param {number} y - The y coordinate of the top-left corner of the bounds. + * @param {number} width - The width of the bounds. + * @param {number} height - The height of the bounds. + * @param {boolean} [left=true] - If true will create the left bounds wall. + * @param {boolean} [right=true] - If true will create the right bounds wall. + * @param {boolean} [top=true] - If true will create the top bounds wall. + * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { + + if (left === undefined) { left = this._boundsLeft; } + if (right === undefined) { right = this._boundsRight; } + if (top === undefined) { top = this._boundsTop; } + if (bottom === undefined) { bottom = this._boundsBottom; } + if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; } + + this.setupWall(left, 'left', x, y, 1.5707963267948966, setCollisionGroup); + this.setupWall(right, 'right', x + width, y, -1.5707963267948966, setCollisionGroup); + this.setupWall(top, 'top', x, y, -3.141592653589793, setCollisionGroup); + this.setupWall(bottom, 'bottom', x, y + height, 0, setCollisionGroup); + + // Remember the bounds settings in case they change later on via World.setBounds + this._boundsLeft = left; + this._boundsRight = right; + this._boundsTop = top; + this._boundsBottom = bottom; + this._boundsOwnGroup = setCollisionGroup; + + }, + + /** + * Internal method called by setBounds. Responsible for creating, updating or + * removing the wall body shapes. + * + * @method Phaser.Physics.P2#setupWall + * @private + * @param {boolean} create - True to create the wall shape, false to remove it. + * @param {string} wall - The wall segment to update. + * @param {number} x - The x coordinate of the wall. + * @param {number} y - The y coordinate of the wall. + * @param {float} angle - The angle of the wall. + * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. + */ + setupWall: function (create, wall, x, y, angle, setCollisionGroup) { + + if (create) + { + // We need a left wall. Do we have one already? + if (this.walls[wall]) + { + this.walls[wall].position = [ this.pxmi(x), this.pxmi(y) ]; + } + else + { + this.walls[wall] = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: angle }); + this.walls[wall].addShape(new p2.Plane()); + + this.world.addBody(this.walls[wall]); + } + + if (setCollisionGroup) + { + this.walls[wall].shapes[0].collisionGroup = this.boundsCollisionGroup.mask; + } + } + else + { + if (this.walls[wall]) + { + this.world.removeBody(this.walls[wall]); + this.walls[wall] = null; + } + } + + }, + + /** + * Pauses the P2 World independent of the game pause state. + * + * @method Phaser.Physics.P2#pause + */ + pause: function() { + + this.paused = true; + + }, + + /** + * Resumes a paused P2 World. + * + * @method Phaser.Physics.P2#resume + */ + resume: function() { + + this.paused = false; + + }, + + /** + * Internal P2 update loop. + * + * @method Phaser.Physics.P2#update + */ + update: function () { + + // Do nothing if the physics engine was paused before + if (this.paused) + { + return; + } + + if (this.useElapsedTime) + { + this.world.step(this.game.time.physicsElapsed); + } + else + { + this.world.step(this.frameRate); + } + + }, + + /** + * Called by Phaser.Physics when a State swap occurs. + * Starts the begin and end Contact listeners again. + * + * @method Phaser.Physics.P2#reset + */ + reset: function () { + + this.world.on("beginContact", this.beginContactHandler, this); + this.world.on("endContact", this.endContactHandler, this); + + this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); + this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); + this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); + + this._collisionGroupID = 2; + + this.setBoundsToWorld(true, true, true, true, false); + + }, + + /** + * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. + * + * The P2 world is also cleared: + * + * * Removes all solver equations + * * Removes all constraints + * * Removes all bodies + * * Removes all springs + * * Removes all contact materials + * + * This is called automatically when you switch state. + * + * @method Phaser.Physics.P2#clear + */ + clear: function () { + + this.world.time = 0; + this.world.fixedStepTime = 0; + + // Remove all solver equations + if (this.world.solver && this.world.solver.equations.length) + { + this.world.solver.removeAllEquations(); + } + + // Remove all constraints + var cs = this.world.constraints; + + for (var i = cs.length - 1; i >= 0; i--) + { + this.world.removeConstraint(cs[i]); + } + + // Remove all bodies + var bodies = this.world.bodies; + + for (var i = bodies.length - 1; i >= 0; i--) + { + this.world.removeBody(bodies[i]); + } + + // Remove all springs + var springs = this.world.springs; + + for (var i = springs.length - 1; i >= 0; i--) + { + this.world.removeSpring(springs[i]); + } + + // Remove all contact materials + var cms = this.world.contactMaterials; + + for (var i = cms.length - 1; i >= 0; i--) + { + this.world.removeContactMaterial(cms[i]); + } + + 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.boundsCollidesWith = []; + + // Remove the world bounds + this.walls = { left: null, right: null, top: null, bottom: null }; + + }, + + /** + * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. + * + * @method Phaser.Physics.P2#destroy + */ + destroy: function () { + + this.clear(); + + this.game = null; + + }, + + /** + * Add a body to the world. + * + * @method Phaser.Physics.P2#addBody + * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. + * @return {boolean} True if the Body was added successfully, otherwise false. + */ + addBody: function (body) { + + if (body.data.world) + { + return false; + } + else + { + this.world.addBody(body.data); + + this.onBodyAdded.dispatch(body); + + return true; + } + + }, + + /** + * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. + * + * @method Phaser.Physics.P2#removeBody + * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. + * @return {Phaser.Physics.P2.Body} The Body that was removed. + */ + removeBody: function (body) { + + if (body.data.world === this.world) + { + this.world.removeBody(body.data); + + this.onBodyRemoved.dispatch(body); + } + + return body; + + }, + + /** + * Adds a Spring to the world. + * + * @method Phaser.Physics.P2#addSpring + * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was added. + */ + addSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.addSpring(spring.data); + } + else + { + this.world.addSpring(spring); + } + + this.onSpringAdded.dispatch(spring); + + return spring; + + }, + + /** + * Removes a Spring from the world. + * + * @method Phaser.Physics.P2#removeSpring + * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. + * @return {Phaser.Physics.P2.Spring} The Spring that was removed. + */ + removeSpring: function (spring) { + + if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) + { + this.world.removeSpring(spring.data); + } + else + { + this.world.removeSpring(spring); + } + + this.onSpringRemoved.dispatch(spring); + + return spring; + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createDistanceConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} distance - The distance to keep between the bodies. + * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. + * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.DistanceConstraint} The constraint + */ + createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, 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, localAnchorA, localAnchorB, maxForce)); + } + + }, + + /** + * Creates a constraint that tries to keep the distance between two bodies constant. + * + * @method Phaser.Physics.P2#createGearConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [angle=0] - The relative angle + * @param {number} [ratio=1] - The gear ratio. + * @return {Phaser.Physics.P2.GearConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Connects two bodies at given offset points, letting them rotate relative to each other around this point. + * The pivot points are given in world (pixel) coordinates. + * + * @method Phaser.Physics.P2#createRevoluteConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. + * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. + * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint + */ + createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + 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, worldPivot)); + } + + }, + + /** + * Locks the relative position between two bodies. + * + * @method Phaser.Physics.P2#createLockConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.LockConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Constraint that only allows bodies to move along a line, relative to each other. + * See http://www.iforce2d.net/b2dtut/joints-prismatic + * + * @method Phaser.Physics.P2#createPrismaticConstraint + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. + * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. + * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. + * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint + */ + 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)); + } + + }, + + /** + * Adds a Constraint to the world. + * + * @method Phaser.Physics.P2#addConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. + */ + addConstraint: function (constraint) { + + this.world.addConstraint(constraint); + + this.onConstraintAdded.dispatch(constraint); + + return constraint; + + }, + + /** + * Removes a Constraint from the world. + * + * @method Phaser.Physics.P2#removeConstraint + * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. + * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. + */ + removeConstraint: function (constraint) { + + this.world.removeConstraint(constraint); + + this.onConstraintRemoved.dispatch(constraint); + + return constraint; + + }, + + /** + * Adds a Contact Material to the world. + * + * @method Phaser.Physics.P2#addContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. + */ + addContactMaterial: function (material) { + + this.world.addContactMaterial(material); + + this.onContactMaterialAdded.dispatch(material); + + return material; + + }, + + /** + * Removes a Contact Material from the world. + * + * @method Phaser.Physics.P2#removeContactMaterial + * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. + */ + removeContactMaterial: function (material) { + + this.world.removeContactMaterial(material); + + this.onContactMaterialRemoved.dispatch(material); + + return material; + + }, + + /** + * Gets a Contact Material based on the two given Materials. + * + * @method Phaser.Physics.P2#getContactMaterial + * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. + * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. + * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. + */ + getContactMaterial: function (materialA, materialB) { + + return this.world.getContactMaterial(materialA, materialB); + + }, + + /** + * Sets the given Material against all Shapes owned by all the Bodies in the given array. + * + * @method Phaser.Physics.P2#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. + * @param {array} bodies - An Array of Body objects that the given Material will be set on. + */ + setMaterial: function (material, bodies) { + + var i = bodies.length; + + while (i--) + { + bodies[i].setMaterial(material); + } + + }, + + /** + * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). + * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. + * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. + * + * @method Phaser.Physics.P2#createMaterial + * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. + * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. + * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. + */ + 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; + + }, + + /** + * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. + * + * @method Phaser.Physics.P2#createContactMaterial + * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. + * @param {object} [options] - Material options object. + * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. + */ + createContactMaterial: function (materialA, materialB, options) { + + if (materialA === undefined) { materialA = this.createMaterial(); } + if (materialB === undefined) { materialB = this.createMaterial(); } + + var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); + + return this.addContactMaterial(contact); + + }, + + /** + * Populates and returns an array with references to of all current Bodies in the world. + * + * @method Phaser.Physics.P2#getBodies + * @return {array} An array containing all current Bodies in the world. + */ + getBodies: function () { + + var output = []; + var i = this.world.bodies.length; + + while (i--) + { + output.push(this.world.bodies[i].parent); + } + + return output; + + }, + + /** + * Checks the given object to see if it has a p2.Body and if so returns it. + * + * @method Phaser.Physics.P2#getBody + * @param {object} object - The object to check for a p2.Body on. + * @return {p2.Body} The p2.Body, or null if not found. + */ + getBody: function (object) { + + if (object instanceof p2.Body) + { + // Native p2 body + return object; + } + else if (object instanceof Phaser.Physics.P2.Body) + { + // Phaser P2 Body + return object.data; + } + else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) + { + // Sprite, TileSprite, etc + return object.body.data; + } + + return null; + + }, + + /** + * Populates and returns an array of all current Springs in the world. + * + * @method Phaser.Physics.P2#getSprings + * @return {array} An array containing all current Springs in the world. + */ + getSprings: function () { + + var output = []; + var i = this.world.springs.length; + + while (i--) + { + output.push(this.world.springs[i].parent); + } + + return output; + + }, + + /** + * Populates and returns an array of all current Constraints in the world. + * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain + * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type. + * + * @method Phaser.Physics.P2#getConstraints + * @return {array} An array containing all current Constraints in the world. + */ + getConstraints: function () { + + var output = []; + var i = this.world.constraints.length; + + while (i--) + { + output.push(this.world.constraints[i]); + } + + return output; + + }, + + /** + * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to + * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. + * + * @method Phaser.Physics.P2#hitTest + * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. + * @param {Array} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) + * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. + * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. + * @return {Array} Array of bodies that overlap the point. + */ + hitTest: function (worldPoint, bodies, precision, filterStatic) { + + if (bodies === undefined) { bodies = this.world.bodies; } + if (precision === undefined) { precision = 5; } + if (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.type === p2.Body.STATIC)) + { + query.push(bodies[i].data); + } + else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC)) + { + query.push(bodies[i]); + } + else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC)) + { + query.push(bodies[i].body.data); + } + } + + return this.world.hitTest(physicsPosition, query, precision); + + }, + + /** + * Converts the current world into a JSON object. + * + * @method Phaser.Physics.P2#toJSON + * @return {object} A JSON representation of the world. + */ + toJSON: function () { + + return this.world.toJSON(); + + }, + + /** + * Creates a new Collision Group and optionally applies it to the given object. + * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. + * + * @method Phaser.Physics.P2#createCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + */ + 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; + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. + * + * @method Phaser.Physics.P2y#setCollisionGroup + * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + */ + setCollisionGroup: function (object, group) { + + if (object instanceof Phaser.Group) + { + for (var i = 0; i < object.total; i++) + { + if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) + { + object.children[i].body.setCollisionGroup(group); + } + } + } + else + { + object.body.setCollisionGroup(group); + } + + }, + + /** + * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restLength=1] - Rest length of the spring. A number > 0. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. + * @return {Phaser.Physics.P2.Spring} The spring + */ + createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); + } + + }, + + /** + * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. + * + * @method Phaser.Physics.P2#createRotationalSpring + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. + * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. + * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. + * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. + * @param {number} [damping=1] - Damping of the spring. A number >= 0. + * @return {Phaser.Physics.P2.RotationalSpring} The spring + */ + createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) { + + bodyA = this.getBody(bodyA); + bodyB = this.getBody(bodyB); + + if (!bodyA || !bodyB) + { + console.warn('Cannot create Rotational Spring, invalid body objects given'); + } + else + { + return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping)); + } + + }, + + /** + * Creates a new Body and adds it to the World. + * + * @method Phaser.Physics.P2#createBody + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {Phaser.Physics.P2.Body} The body + */ + createBody: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Creates a new Particle and adds it to the World. + * + * @method Phaser.Physics.P2#createParticle + * @param {number} x - The x coordinate of Body. + * @param {number} y - The y coordinate of Body. + * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. + * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], + * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + */ + createParticle: function (x, y, mass, addToWorld, options, data) { + + if (addToWorld === undefined) { addToWorld = false; } + + var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); + + if (data) + { + var result = body.addPolygon(options, data); + + if (!result) + { + return false; + } + } + + if (addToWorld) + { + this.world.addBody(body.data); + } + + return body; + + }, + + /** + * Converts all of the polyline, polygon, and rectangle objects inside a Tiled ObjectGroup into physics bodies that are added to the world. + * Note that the polylines and polygons must be created in such a way that they can withstand polygon decomposition. + * + * @method Phaser.Physics.P2#convertCollisionObjects + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. + * @return {array} An array of the Phaser.Physics.Body objects that have been created. + */ + convertCollisionObjects: function (map, layer, addToWorld) { + + if (addToWorld === undefined) { addToWorld = true; } + + var output = []; + + for (var i = 0, len = map.collision[layer].length; i < len; i++) + { + // name: json.layers[i].objects[v].name, + // x: json.layers[i].objects[v].x, + // y: json.layers[i].objects[v].y, + // width: json.layers[i].objects[v].width, + // height: json.layers[i].objects[v].height, + // visible: json.layers[i].objects[v].visible, + // properties: json.layers[i].objects[v].properties, + // polyline: json.layers[i].objects[v].polyline + + var object = map.collision[layer][i]; + var shapeData = object.polyline || object.polygon; + + // polyline/polygon shape data present + if (shapeData) + { + var body = this.createBody(object.x, object.y, 0, addToWorld, {}, shapeData); + } + + // tilemap parser sets rectangle=true when parsing object groups + else if (object.rectangle) + { + var body = this.createBody(object.x, object.y, 0, addToWorld); + body.addRectangle(object.width, object.height, object.width / 2, object.height / 2); + } + + // ellipse could be added here, but Tiled ellipses use height/width instead of radius + // (to support oblong ellipses), which p2 doesn't currently support. + + if (body) + { + output.push(body); + } + } + + return output; + + }, + + /** + * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. + * + * @method Phaser.Physics.P2#clearTilemapLayerBodies + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + */ + 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 = 0; + + }, + + /** + * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. + * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. + * Every time you call this method it will destroy any previously created bodies and remove them from the world. + * Therefore understand it's a very expensive operation and not to be done in a core game update loop. + * + * @method Phaser.Physics.P2#convertTilemap + * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. + * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. + * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. + * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. + */ + convertTilemap: function (map, layer, addToWorld, optimize) { + + layer = map.getLayer(layer); + + if (addToWorld === undefined) { addToWorld = true; } + if (optimize === undefined) { optimize = true; } + + // If the bodies array is already populated we need to nuke it + this.clearTilemapLayerBodies(map, layer); + + var width = 0; + var sx = 0; + var sy = 0; + + for (var y = 0, h = map.layers[layer].height; y < h; y++) + { + width = 0; + + for (var x = 0, w = map.layers[layer].width; x < w; x++) + { + var tile = map.layers[layer].data[y][x]; + + if (tile && tile.index > -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; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpx + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpx: function (v) { + + return v *= 20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters). + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxm + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxm: function (v) { + + return v * 0.05; + + }, + + /** + * Convert p2 physics value (meters) to pixel scale and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#mpxi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + mpxi: function (v) { + + return v *= -20; + + }, + + /** + * Convert pixel value to p2 physics scale (meters) and inverses it. + * By default Phaser uses a scale of 20px per meter. + * If you need to modify this you can over-ride these functions via the Physics Configuration object. + * + * @method Phaser.Physics.P2#pxmi + * @param {number} v - The value to convert. + * @return {number} The scaled value. + */ + pxmi: function (v) { + + return v * -0.05; + + } + +}; + +/** +* @name Phaser.Physics.P2#friction +* @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { + + get: function () { + + return this.world.defaultContactMaterial.friction; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.friction = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#restitution +* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { + + get: function () { + + return this.world.defaultContactMaterial.restitution; + + }, + + set: function (value) { + + this.world.defaultContactMaterial.restitution = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#contactMaterial +* @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { + + get: function () { + + return this.world.defaultContactMaterial; + + }, + + set: function (value) { + + this.world.defaultContactMaterial = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applySpringForces +* @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { + + get: function () { + + return this.world.applySpringForces; + + }, + + set: function (value) { + + this.world.applySpringForces = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyDamping +* @property {boolean} applyDamping - Enable to automatically apply body damping each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { + + get: function () { + + return this.world.applyDamping; + + }, + + set: function (value) { + + this.world.applyDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#applyGravity +* @property {boolean} applyGravity - Enable to automatically apply gravity each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { + + get: function () { + + return this.world.applyGravity; + + }, + + set: function (value) { + + this.world.applyGravity = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#solveConstraints +* @property {boolean} solveConstraints - Enable/disable constraint solving in each step. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { + + get: function () { + + return this.world.solveConstraints; + + }, + + set: function (value) { + + this.world.solveConstraints = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#time +* @property {boolean} time - The World time. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "time", { + + get: function () { + + return this.world.time; + + } + +}); + +/** +* @name Phaser.Physics.P2#emitImpactEvent +* @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { + + get: function () { + + return this.world.emitImpactEvent; + + }, + + set: function (value) { + + this.world.emitImpactEvent = value; + + } + +}); + +/** +* How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. +* If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. +* @name Phaser.Physics.P2#sleepMode +* @property {number} sleepMode +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", { + + get: function () { + + return this.world.sleepMode; + + }, + + set: function (value) { + + this.world.sleepMode = value; + + } + +}); + +/** +* @name Phaser.Physics.P2#total +* @property {number} total - The total number of bodies in the world. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.prototype, "total", { + + get: function () { + + return this.world.bodies.length; + + } + +}); + +/* jshint noarg: false */ + +/** +* @author Georgios Kaleadis https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Allow to access a list of created fixture (coming from Body#addPhaserPolygon) +* which itself parse the input from PhysicsEditor with the custom phaser exporter. +* You can access fixtures of a Body by a group index or even by providing a fixture Key. + +* You can set the fixture key and also the group index for a fixture in PhysicsEditor. +* This gives you the power to create a complex body built of many fixtures and modify them +* during runtime (to remove parts, set masks, categories & sensor properties) +* +* @class Phaser.Physics.P2.FixtureList +* @constructor +* @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) +*/ +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 = { + + /** + * @method Phaser.Physics.P2.FixtureList#init + */ + init: function () { + + /** + * @property {object} namedFixtures - Collect all fixtures with a key + * @private + */ + this.namedFixtures = {}; + + /** + * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group + * @private + */ + this.groupedFixtures = []; + + /** + * @property {Array} allFixtures - This is a list of everything in this collection + * @private + */ + this.allFixtures = []; + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setCategory + * @param {number} bit - The bit to set as the collision group. + * @param {string} fixtureKey - Only apply to the fixture with the given key. + */ + setCategory: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionGroup = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMask + * @param {number} bit - The bit to set as the collision mask + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMask: function (bit, fixtureKey) { + + var setter = function(fixture) { + fixture.collisionMask = bit; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setSensor + * @param {boolean} value - sensor true or false + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setSensor: function (value, fixtureKey) { + + var setter = function(fixture) { + fixture.sensor = value; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * @method Phaser.Physics.P2.FixtureList#setMaterial + * @param {Object} material - The contact material for a fixture + * @param {string} fixtureKey - Only apply to the fixture with the given key + */ + setMaterial: function (material, fixtureKey) { + + var setter = function(fixture) { + fixture.material = material; + }; + + this.getFixtures(fixtureKey).forEach(setter); + + }, + + /** + * Accessor to get either a list of specified fixtures by key or the whole fixture list + * + * @method Phaser.Physics.P2.FixtureList#getFixtures + * @param {array} keys - A list of fixture keys + */ + 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; + } + + }, + + /** + * Accessor to get either a single fixture by its key. + * + * @method Phaser.Physics.P2.FixtureList#getFixtureByKey + * @param {string} key - The key of the fixture. + */ + getFixtureByKey: function (key) { + + return this.namedFixtures[key]; + + }, + + /** + * Accessor to get a group of fixtures by its group index. + * + * @method Phaser.Physics.P2.FixtureList#getGroup + * @param {number} groupID - The group index. + */ + getGroup: function (groupID) { + + return this.groupedFixtures[groupID]; + + }, + + /** + * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon + * + * @method Phaser.Physics.P2.FixtureList#parse + */ + 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)); + } + + }, + + /** + * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. + * + * @method Phaser.Physics.P2.FixtureList#flatten + * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. + */ + 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; + + } + +}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. +* +* @class Phaser.Physics.P2.PointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.PointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; + +/** +* @name Phaser.Physics.P2.PointProxy#x +* @property {number} x - The x property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { + + get: function () { + + return this.world.mpx(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#y +* @property {number} y - The y property of this PointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { + + get: function () { + + return this.world.mpx(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxm(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#mx +* @property {number} mx - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.PointProxy#my +* @property {number} my - The x property of this PointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. +* +* @class Phaser.Physics.P2.InversePointProxy +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {any} destination - The object to bind to. +*/ +Phaser.Physics.P2.InversePointProxy = function (world, destination) { + + this.world = world; + this.destination = destination; + +}; + +Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; + +/** +* @name Phaser.Physics.P2.InversePointProxy#x +* @property {number} x - The x property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.destination[0]); + + }, + + set: function (value) { + + this.destination[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#y +* @property {number} y - The y property of this InversePointProxy get and set in pixels. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.destination[1]); + + }, + + set: function (value) { + + this.destination[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#mx +* @property {number} mx - The x property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", { + + get: function () { + + return this.destination[0]; + + }, + + set: function (value) { + + this.destination[0] = -value; + + } + +}); + +/** +* @name Phaser.Physics.P2.InversePointProxy#my +* @property {number} my - The y property of this InversePointProxy get and set in meters. +*/ +Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", { + + get: function () { + + return this.destination[1]; + + }, + + set: function (value) { + + this.destination[1] = -value; + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. +* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. +* In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. +* By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. +* Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. +* Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. +* +* @class Phaser.Physics.P2.Body +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. +* @param {number} [x=0] - The x coordinate of this Body. +* @param {number} [y=0] - The y coordinate of this Body. +* @param {number} [mass=1] - The default mass of this Body (0 = static). +*/ +Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { + + sprite = sprite || null; + x = x || 0; + y = y || 0; + if (mass === undefined) { mass = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to the P2 World. + */ + this.world = game.physics.p2; + + /** + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ + this.sprite = sprite; + + /** + * @property {number} type - The type of physics system this body belongs to. + */ + this.type = Phaser.Physics.P2JS; + + /** + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. + */ + this.offset = new Phaser.Point(); + + /** + * @property {p2.Body} data - The p2 Body data. + * @protected + */ + this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); + + this.data.parent = this; + + /** + * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. + */ + this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); + + /** + * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body. + */ + this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); + + /** + * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. + */ + this.gravity = new Phaser.Point(); + + /** + * Dispatched when a first contact is created between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 5 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body is in contact with. + * The Shape from this body that caused the contact. + * The Shape from the contact body. + * The Contact Equation data array. + * + * @property {Phaser.Signal} onBeginContact + */ + this.onBeginContact = new Phaser.Signal(); + + /** + * Dispatched when contact ends between shapes in two bodies. + * This event is fired during the step, so collision has already taken place. + * + * The event will be sent 4 arguments in this order: + * + * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. + * The p2.Body this Body has ended contact with. + * The Shape from this body that caused the original contact. + * The Shape from the contact body. + * + * @property {Phaser.Signal} onEndContact + */ + this.onEndContact = new Phaser.Signal(); + + /** + * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. + */ + this.collidesWith = []; + + /** + * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. + */ + this.removeNextStep = false; + + /** + * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. + */ + this.debugBody = null; + + /** + * @property {boolean} dirty - Internally used by Sprite.x/y + */ + this.dirty = false; + + /** + * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. + * @private + */ + this._collideWorldBounds = true; + + /** + * @property {object} _bodyCallbacks - Array of Body callbacks. + * @private + */ + this._bodyCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Body callback contexts. + * @private + */ + this._bodyCallbackContext = {}; + + /** + * @property {object} _groupCallbacks - Array of Group callbacks. + * @private + */ + this._groupCallbacks = {}; + + /** + * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. + * @private + */ + this._groupCallbackContext = {}; + + /** + * @property {boolean} _reset - Internal var. + * @private + */ + this._reset = false; + + // Set-up the default shape + if (sprite) + { + this.setRectangleFromSprite(sprite); + + if (sprite.exists) + { + this.game.physics.p2.addBody(this); + } + } + +}; + +Phaser.Physics.P2.Body.prototype = { + + /** + * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createBodyCallback + * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + 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; + } + } + + }, + + /** + * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. + * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. + * This callback will only fire if this Body has been assigned a collision group. + * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. + * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. + * + * @method Phaser.Physics.P2.Body#createGroupCallback + * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. + * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. + * @param {object} callbackContext - The context under which the callback will fire. + */ + createGroupCallback: function (group, callback, callbackContext) { + + if (callback === null) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + else + { + this._groupCallbacks[group.mask] = callback; + this._groupCallbackContext[group.mask] = callbackContext; + } + + }, + + /** + * Gets the collision bitmask from the groups this body collides with. + * + * @method Phaser.Physics.P2.Body#getCollisionMask + * @return {number} The bitmask. + */ + getCollisionMask: function () { + + var mask = 0; + + if (this._collideWorldBounds) + { + mask = this.game.physics.p2.boundsCollisionGroup.mask; + } + + for (var i = 0; i < this.collidesWith.length; i++) + { + mask = mask | this.collidesWith[i].mask; + } + + return mask; + + }, + + /** + * Updates the collisionMask. + * + * @method Phaser.Physics.P2.Body#updateCollisionMask + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + updateCollisionMask: function (shape) { + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. + * This also resets the collisionMask. + * + * @method Phaser.Physics.P2.Body#setCollisionGroup + * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. + */ + setCollisionGroup: function (group, shape) { + + var mask = this.getCollisionMask(); + + if (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; + } + + }, + + /** + * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. + * + * @method Phaser.Physics.P2.Body#clearCollision + * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? + * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. + */ + clearCollision: function (clearGroup, clearMask, shape) { + + if (clearGroup === undefined) { clearGroup = true; } + if (clearMask === undefined) { clearMask = true; } + + if (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; + } + + }, + + /** + * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#removeCollisionGroup + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore. + * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group? + * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body. + */ + removeCollisionGroup: function (group, clearCallback, shape) { + + if (clearCallback === undefined) { clearCallback = true; } + + var index; + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + index = this.collidesWith.indexOf(group[i]); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + } + else + { + index = this.collidesWith.indexOf(group); + + if (index > -1) + { + this.collidesWith.splice(index, 1); + + if (clearCallback) + { + delete (this._groupCallbacks[group.mask]); + delete (this._groupCallbackContext[group.mask]); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. + * + * @method Phaser.Physics.P2.Body#collides + * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. + * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. + * @param {object} [callbackContext] - The context under which the callback will be called. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. + */ + collides: function (group, callback, callbackContext, shape) { + + if (Array.isArray(group)) + { + for (var i = 0; i < group.length; i++) + { + if (this.collidesWith.indexOf(group[i]) === -1) + { + this.collidesWith.push(group[i]); + + if (callback) + { + this.createGroupCallback(group[i], callback, callbackContext); + } + } + } + } + else + { + if (this.collidesWith.indexOf(group) === -1) + { + this.collidesWith.push(group); + + if (callback) + { + this.createGroupCallback(group, callback, callbackContext); + } + } + } + + var mask = this.getCollisionMask(); + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].collisionMask = mask; + } + } + else + { + shape.collisionMask = mask; + } + + }, + + /** + * Moves the shape offsets so their center of mass becomes the body center of mass. + * + * @method Phaser.Physics.P2.Body#adjustCenterOfMass + */ + adjustCenterOfMass: function () { + + this.data.adjustCenterOfMass(); + this.shapeChanged(); + + }, + + /** + * Gets the velocity of a point in the body. + * + * @method Phaser.Physics.P2.Body#getVelocityAtPoint + * @param {Array} result - A vector to store the result in. + * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from. + * @return {Array} The result vector. + */ + getVelocityAtPoint: function (result, relativePoint) { + + return this.data.getVelocityAtPoint(result, relativePoint); + + }, + + /** + * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. + * + * @method Phaser.Physics.P2.Body#applyDamping + * @param {number} dt - Current time step. + */ + applyDamping: function (dt) { + + this.data.applyDamping(dt); + + }, + + /** + * Apply impulse to a point relative to the body. + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulse + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space. + * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. + */ + applyImpulse: function (impulse, worldX, worldY) { + + this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Apply impulse to a point local to the body. + * + * This could for example be a point on the Body surface. An impulse is a force added to a body during a short + * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * + * @method Phaser.Physics.P2.Body#applyImpulseLocal + * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space. + * @param {number} localX - A local point on the body. + * @param {number} localY - A local point on the body. + */ + applyImpulseLocal: function (impulse, localX, localY) { + + this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]); + + }, + + /** + * Apply force to a world point. + * + * This could for example be a point on the RigidBody surface. Applying force + * this way will add to Body.force and Body.angularForce. + * + * @method Phaser.Physics.P2.Body#applyForce + * @param {Float32Array|Array} force - The force vector to add. + * @param {number} worldX - The world x point to apply the force on. + * @param {number} worldY - The world y point to apply the force on. + */ + applyForce: function (force, worldX, worldY) { + + this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); + + }, + + /** + * Sets the force on the body to zero. + * + * @method Phaser.Physics.P2.Body#setZeroForce + */ + setZeroForce: function () { + + this.data.setZeroForce(); + + }, + + /** + * If this Body is dynamic then this will zero its angular velocity. + * + * @method Phaser.Physics.P2.Body#setZeroRotation + */ + setZeroRotation: function () { + + this.data.angularVelocity = 0; + + }, + + /** + * If this Body is dynamic then this will zero its velocity on both axis. + * + * @method Phaser.Physics.P2.Body#setZeroVelocity + */ + setZeroVelocity: function () { + + this.data.velocity[0] = 0; + this.data.velocity[1] = 0; + + }, + + /** + * Sets the Body damping and angularDamping to zero. + * + * @method Phaser.Physics.P2.Body#setZeroDamping + */ + setZeroDamping: function () { + + this.data.damping = 0; + this.data.angularDamping = 0; + + }, + + /** + * Transform a world point to local body frame. + * + * @method Phaser.Physics.P2.Body#toLocalFrame + * @param {Float32Array|Array} out - The vector to store the result in. + * @param {Float32Array|Array} worldPoint - The input world vector. + */ + toLocalFrame: function (out, worldPoint) { + + return this.data.toLocalFrame(out, worldPoint); + + }, + + /** + * Transform a local point to world frame. + * + * @method Phaser.Physics.P2.Body#toWorldFrame + * @param {Array} out - The vector to store the result in. + * @param {Array} localPoint - The input local vector. + */ + toWorldFrame: function (out, localPoint) { + + return this.data.toWorldFrame(out, localPoint); + + }, + + /** + * This will rotate the Body by the given speed to the left (counter-clockwise). + * + * @method Phaser.Physics.P2.Body#rotateLeft + * @param {number} speed - The speed at which it should rotate. + */ + rotateLeft: function (speed) { + + this.data.angularVelocity = this.world.pxm(-speed); + + }, + + /** + * This will rotate the Body by the given speed to the left (clockwise). + * + * @method Phaser.Physics.P2.Body#rotateRight + * @param {number} speed - The speed at which it should rotate. + */ + rotateRight: function (speed) { + + this.data.angularVelocity = this.world.pxm(speed); + + }, + + /** + * Moves the Body forwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveForward + * @param {number} speed - The speed at which it should move forwards. + */ + 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); + + }, + + /** + * Moves the Body backwards based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveBackward + * @param {number} speed - The speed at which it should move backwards. + */ + 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)); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrust + * @param {number} speed - The speed at which it should thrust. + */ + 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); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustLeft + * @param {number} speed - The speed at which it should move to the left. + */ + thrustLeft: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] += magnitude * Math.cos(angle); + this.data.force[1] += magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#thrustRight + * @param {number} speed - The speed at which it should move to the right. + */ + thrustRight: function (speed) { + + var magnitude = this.world.pxmi(-speed); + var angle = this.data.angle; + + this.data.force[0] -= magnitude * Math.cos(angle); + this.data.force[1] -= magnitude * Math.sin(angle); + + }, + + /** + * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#reverse + * @param {number} speed - The speed at which it should reverse. + */ + 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); + + }, + + /** + * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveLeft + * @param {number} speed - The speed at which it should move to the left, in pixels per second. + */ + moveLeft: function (speed) { + + this.data.velocity[0] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveRight + * @param {number} speed - The speed at which it should move to the right, in pixels per second. + */ + moveRight: function (speed) { + + this.data.velocity[0] = this.world.pxmi(speed); + + }, + + /** + * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveUp + * @param {number} speed - The speed at which it should move up, in pixels per second. + */ + moveUp: function (speed) { + + this.data.velocity[1] = this.world.pxmi(-speed); + + }, + + /** + * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. + * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). + * + * @method Phaser.Physics.P2.Body#moveDown + * @param {number} speed - The speed at which it should move down, in pixels per second. + */ + moveDown: function (speed) { + + this.data.velocity[1] = this.world.pxmi(speed); + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#preUpdate + * @protected + */ + preUpdate: function () { + + this.dirty = true; + + if (this.removeNextStep) + { + this.removeFromWorld(); + this.removeNextStep = false; + } + + }, + + /** + * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. + * + * @method Phaser.Physics.P2.Body#postUpdate + * @protected + */ + postUpdate: function () { + + this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x; + this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y; + + if (!this.fixedRotation) + { + this.sprite.rotation = this.data.angle; + } + + if (this.debugBody) + { + this.debugBody.updateSpriteTransform(); + } + + this.dirty = false; + + }, + + /** + * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. + * + * @method Phaser.Physics.P2.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new x position of the Body. + * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. + * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. + */ + reset: function (x, y, resetDamping, resetMass) { + + if (resetDamping === undefined) { resetDamping = false; } + if (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; + + }, + + /** + * Adds this physics body to the world. + * + * @method Phaser.Physics.P2.Body#addToWorld + */ + addToWorld: function () { + + if (this.game.physics.p2._toRemove) + { + for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) + { + if (this.game.physics.p2._toRemove[i] === this) + { + this.game.physics.p2._toRemove.splice(i, 1); + } + } + } + + if (this.data.world !== this.game.physics.p2.world) + { + this.game.physics.p2.addBody(this); + } + + }, + + /** + * Removes this physics body from the world. + * + * @method Phaser.Physics.P2.Body#removeFromWorld + */ + removeFromWorld: function () { + + if (this.data.world === this.game.physics.p2.world) + { + this.game.physics.p2.removeBodyNextStep(this); + } + + }, + + /** + * Destroys this Body and all references it holds to other objects. + * + * @method Phaser.Physics.P2.Body#destroy + */ + destroy: function () { + + this.removeFromWorld(); + + this.clearShapes(); + + this._bodyCallbacks = {}; + this._bodyCallbackContext = {}; + this._groupCallbacks = {}; + this._groupCallbackContext = {}; + + if (this.debugBody) + { + this.debugBody.destroy(true, true); + } + + this.debugBody = null; + + if (this.sprite) + { + this.sprite.body = null; + this.sprite = null; + } + + }, + + /** + * Removes all Shapes from this Body. + * + * @method Phaser.Physics.P2.Body#clearShapes + */ + clearShapes: function () { + + var i = this.data.shapes.length; + + while (i--) + { + this.data.removeShape(this.data.shapes[i]); + } + + this.shapeChanged(); + + }, + + /** + * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. + * Will automatically update the mass properties and bounding radius. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#addShape + + * @param {p2.Shape} shape - The shape to add to the body. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Shape} The shape that was added to the body. + */ + addShape: function (shape, offsetX, offsetY, rotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (rotation === undefined) { rotation = 0; } + + this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); + this.shapeChanged(); + + return shape; + + }, + + /** + * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Circle} The Circle shape that was added to the Body. + */ + addCircle: function (radius, offsetX, offsetY, rotation) { + + var shape = new p2.Circle({ radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addRectangle + * @param {number} width - The width of the rectangle in pixels. + * @param {number} height - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Box} The shape that was added to the Body. + */ + addRectangle: function (width, height, offsetX, offsetY, rotation) { + + var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addPlane + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Plane} The Plane shape that was added to the Body. + */ + addPlane: function (offsetX, offsetY, rotation) { + + var shape = new p2.Plane(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addParticle + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Particle} The Particle shape that was added to the Body. + */ + addParticle: function (offsetX, offsetY, rotation) { + + var shape = new p2.Particle(); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Line shape to this Body. + * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addLine + * @param {number} length - The length of this line (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Line} The Line shape that was added to the Body. + */ + addLine: function (length, offsetX, offsetY, rotation) { + + var shape = new p2.Line({ length: this.world.pxm(length)}); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Adds a Capsule shape to this Body. + * You can control the offset from the center of the body and the rotation. + * + * @method Phaser.Physics.P2.Body#addCapsule + * @param {number} length - The distance between the end points in pixels. + * @param {number} radius - Radius of the capsule in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Capsule} The Capsule shape that was added to the Body. + */ + addCapsule: function (length, radius, offsetX, offsetY, rotation) { + + var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) }); + + return this.addShape(shape, offsetX, offsetY, rotation); + + }, + + /** + * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. + * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. + * + * @method Phaser.Physics.P2.Body#addPolygon + * @param {object} options - An object containing the build options: + * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. + * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. + * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. + * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. + * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...]. In the first form **the array will mutate**. + * Or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. + * @return {boolean} True on success, else false. + */ + addPolygon: function (options, points) { + + options = options || {}; + + if (!Array.isArray(points)) + { + points = Array.prototype.slice.call(arguments, 1); + } + + var path = []; + + // Did they pass in a single array of points? + if (points.length === 1 && Array.isArray(points[0])) + { + path = points[0].slice(0); + } + else if (Array.isArray(points[0])) + { + path = points.slice(); + } + else if (typeof points[0] === 'number') + { + // We've a list of numbers + for (var i = 0, len = points.length; i < len; i += 2) + { + path.push([points[i], points[i + 1]]); + } + } + + // top and tail + var idx = path.length - 1; + + if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) + { + path.pop(); + } + + // Now process them into p2 values + for (var p = 0; p < path.length; p++) + { + path[p][0] = this.world.pxmi(path[p][0]); + path[p][1] = this.world.pxmi(path[p][1]); + } + + var result = this.data.fromPolygon(path, options); + + this.shapeChanged(); + + return result; + + }, + + /** + * Remove a shape from the body. Will automatically update the mass properties and bounding radius. + * + * @method Phaser.Physics.P2.Body#removeShape + * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. + * @return {boolean} True if the shape was found and removed, else false. + */ + removeShape: function (shape) { + + var result = this.data.removeShape(shape); + + this.shapeChanged(); + + return result; + }, + + /** + * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setCircle + * @param {number} radius - The radius of this circle (in pixels) + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + */ + setCircle: function (radius, offsetX, offsetY, rotation) { + + this.clearShapes(); + + return this.addCircle(radius, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. + * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangle + * @param {number} [width=16] - The width of the rectangle in pixels. + * @param {number} [height=16] - The height of the rectangle in pixels. + * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. + * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. + * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangle: function (width, height, offsetX, offsetY, rotation) { + + if (width === undefined) { width = 16; } + if (height === undefined) { height = 16; } + + this.clearShapes(); + + return this.addRectangle(width, height, offsetX, offsetY, rotation); + + }, + + /** + * Clears any previously set shapes. + * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. + * If no Sprite is given it defaults to using the parent of this Body. + * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. + * + * @method Phaser.Physics.P2.Body#setRectangleFromSprite + * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. + * @return {p2.Rectangle} The Rectangle shape that was added to the Body. + */ + setRectangleFromSprite: function (sprite) { + + if (sprite === undefined) { sprite = this.sprite; } + + this.clearShapes(); + + return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); + + }, + + /** + * Adds the given Material to all Shapes that belong to this Body. + * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. + * + * @method Phaser.Physics.P2.Body#setMaterial + * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. + * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. + */ + setMaterial: function (material, shape) { + + if (shape === undefined) + { + for (var i = this.data.shapes.length - 1; i >= 0; i--) + { + this.data.shapes[i].material = material; + } + } + else + { + shape.material = material; + } + + }, + + /** + * Updates the debug draw if any body shapes change. + * + * @method Phaser.Physics.P2.Body#shapeChanged + */ + shapeChanged: function() { + + if (this.debugBody) + { + this.debugBody.draw(); + } + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * The shape data format is based on the output of the + * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for + * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor} + * + * @method Phaser.Physics.P2.Body#addPhaserPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. + * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. + * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList + */ + addPhaserPolygon: function (key, object) { + + var data = this.game.cache.getPhysicsData(key, object); + var createdFixtures = []; + + // Cycle through the fixtures + for (var i = 0; i < data.length; i++) + { + var fixtureData = data[i]; + var shapesOfFixture = this.addFixture(fixtureData); + + // Always add to a group + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; + createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); + + // if (unique) fixture key is provided + if (fixtureData.fixtureKey) + { + createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; + } + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return createdFixtures; + + }, + + /** + * Add a polygon fixture. This is used during #loadPolygon. + * + * @method Phaser.Physics.P2.Body#addFixture + * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. + * @return {array} An array containing the generated shapes for the given polygon. + */ + addFixture: function (fixtureData) { + + var generatedShapes = []; + + if (fixtureData.circle) + { + var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) }); + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + var offset = p2.vec2.create(); + offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); + offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); + + this.data.addShape(shape, offset); + generatedShapes.push(shape); + } + else + { + var polygons = fixtureData.polygons; + var cm = p2.vec2.create(); + + for (var i = 0; i < polygons.length; i++) + { + var shapes = polygons[i]; + var vertices = []; + + for (var s = 0; s < shapes.length; s += 2) + { + vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); + } + + var shape = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== shape.vertices.length; j++) + { + var v = shape.vertices[j]; + p2.vec2.sub(v, v, shape.centerOfMass); + } + + p2.vec2.scale(cm, shape.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + shape.updateTriangles(); + shape.updateCenterOfMass(); + shape.updateBoundingRadius(); + + shape.collisionGroup = fixtureData.filter.categoryBits; + shape.collisionMask = fixtureData.filter.maskBits; + shape.sensor = fixtureData.isSensor; + + this.data.addShape(shape, cm); + + generatedShapes.push(shape); + } + } + + return generatedShapes; + + }, + + /** + * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. + * + * As well as reading the data from the Cache you can also pass `null` as the first argument and a + * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance. + * + * For more details see the format of the Lime / Corona Physics Editor export. + * + * @method Phaser.Physics.P2.Body#loadPolygon + * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the + * data as the 2nd argument. + * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from, + * or if key is null pass the actual physics data object itself as this parameter. + * @param {number} [scale=1] - Optionally resize the loaded polygon. + * @return {boolean} True on success, else false. + */ + loadPolygon: function (key, object, scale) { + + if (key === null) + { + var data = object; + } + else + { + var data = this.game.cache.getPhysicsData(key, object); + } + + if (typeof scale !== "number") + { + scale = 1; + } + + // We've multiple Convex shapes, they should be CCW automatically + var cm = p2.vec2.create(); + + for (var i = 0; i < data.length; i++) + { + var vertices = []; + + for (var s = 0; s < data[i].shape.length; s += 2) + { + vertices.push([ + this.world.pxmi(data[i].shape[s] * scale), + this.world.pxmi(data[i].shape[s + 1] * scale) + ]); + } + + var c = new p2.Convex({ vertices: vertices }); + + // Move all vertices so its center of mass is in the local center of the convex + for (var j = 0; j !== c.vertices.length; j++) + { + var v = c.vertices[j]; + p2.vec2.sub(v, v, c.centerOfMass); + } + + p2.vec2.scale(cm, c.centerOfMass, 1); + + cm[0] -= this.world.pxmi(this.sprite.width / 2); + cm[1] -= this.world.pxmi(this.sprite.height / 2); + + c.updateTriangles(); + c.updateCenterOfMass(); + c.updateBoundingRadius(); + + this.data.addShape(c, cm); + } + + this.data.aabbNeedsUpdate = true; + this.shapeChanged(); + + return true; + + } + +}; + +Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; + +/** + * Dynamic body. Dynamic bodies body can move and respond to collisions and forces. + * @property DYNAMIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.DYNAMIC = 1; + +/** + * Static body. Static bodies do not move, and they do not respond to forces or collision. + * @property STATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.STATIC = 2; + +/** + * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. + * @property KINEMATIC + * @type {Number} + * @static + */ +Phaser.Physics.P2.Body.KINEMATIC = 4; + +/** +* @name Phaser.Physics.P2.Body#static +* @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.STATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#dynamic +* @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.DYNAMIC; + this.mass = 1; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#kinematic +* @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { + + get: function () { + + return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC); + + }, + + set: function (value) { + + if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.KINEMATIC; + this.mass = 4; + } + else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC) + { + this.data.type = Phaser.Physics.P2.Body.STATIC; + this.mass = 0; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#allowSleep +* @property {boolean} allowSleep - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { + + get: function () { + + return this.data.allowSleep; + + }, + + set: function (value) { + + if (value !== this.data.allowSleep) + { + this.data.allowSleep = value; + } + + } + +}); + +/** +* The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. +* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. +* If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#angle +* @property {number} angle - The angle of this Body in degrees. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { + + get: function() { + + return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); + + }, + + set: function(value) { + + this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#angularDamping +* @property {number} angularDamping - The angular damping acting acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { + + get: function () { + + return this.data.angularDamping; + + }, + + set: function (value) { + + this.data.angularDamping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularForce +* @property {number} angularForce - The angular force acting on the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { + + get: function () { + + return this.data.angularForce; + + }, + + set: function (value) { + + this.data.angularForce = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#angularVelocity +* @property {number} angularVelocity - The angular velocity of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { + + get: function () { + + return this.data.angularVelocity; + + }, + + set: function (value) { + + this.data.angularVelocity = value; + + } + +}); + +/** +* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. +* @name Phaser.Physics.P2.Body#damping +* @property {number} damping - The linear damping acting on the body in the velocity direction. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { + + get: function () { + + return this.data.damping; + + }, + + set: function (value) { + + this.data.damping = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#fixedRotation +* @property {boolean} fixedRotation - +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { + + get: function () { + + return this.data.fixedRotation; + + }, + + set: function (value) { + + if (value !== this.data.fixedRotation) + { + this.data.fixedRotation = value; + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#inertia +* @property {number} inertia - The inertia of the body around the Z axis.. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { + + get: function () { + + return this.data.inertia; + + }, + + set: function (value) { + + this.data.inertia = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#mass +* @property {number} mass - The mass of the body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { + + get: function () { + + return this.data.mass; + + }, + + set: function (value) { + + if (value !== this.data.mass) + { + this.data.mass = value; + this.data.updateMassProperties(); + } + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#motionState +* @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { + + get: function () { + + return this.data.type; + + }, + + set: function (value) { + + if (value !== this.data.type) + { + this.data.type = value; + } + + } + +}); + +/** +* The angle of the Body in radians. +* If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. +* +* @name Phaser.Physics.P2.Body#rotation +* @property {number} rotation - The angle of this Body in radians. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { + + get: function() { + + return this.data.angle; + + }, + + set: function(value) { + + this.data.angle = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#sleepSpeedLimit +* @property {number} sleepSpeedLimit - . +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { + + get: function () { + + return this.data.sleepSpeedLimit; + + }, + + set: function (value) { + + this.data.sleepSpeedLimit = value; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#x +* @property {number} x - The x coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { + + get: function () { + + return this.world.mpxi(this.data.position[0]); + + }, + + set: function (value) { + + this.data.position[0] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#y +* @property {number} y - The y coordinate of this Body. +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { + + get: function () { + + return this.world.mpxi(this.data.position[1]); + + }, + + set: function (value) { + + this.data.position[1] = this.world.pxmi(value); + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#id +* @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. +* @readonly +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { + + get: function () { + + return this.data.id; + + } + +}); + +/** +* @name Phaser.Physics.P2.Body#debug +* @property {boolean} debug - Enable or disable debug drawing of this body +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { + + get: function () { + + return (this.debugBody !== null); + + }, + + set: function (value) { + + if (value && !this.debugBody) + { + // This will be added to the global space + this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); + } + else if (!value && this.debugBody) + { + this.debugBody.destroy(); + this.debugBody = null; + } + + } + +}); + +/** +* A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. +* Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. +* Also note that when you set this it will only affect Body shapes that already exist. If you then add further shapes to your Body +* after setting this it will *not* proactively set them to collide with the bounds. +* +* @name Phaser.Physics.P2.Body#collideWorldBounds +* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? +* @default true +*/ +Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { + + get: function () { + + return this._collideWorldBounds; + + }, + + set: function (value) { + + if (value && !this._collideWorldBounds) + { + this._collideWorldBounds = true; + this.updateCollisionMask(); + } + else if (!value && this._collideWorldBounds) + { + this._collideWorldBounds = false; + this.updateCollisionMask(); + } + + } + +}); + +/** +* @author George https://github.com/georgiee +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Draws a P2 Body to a Graphics instance for visual debugging. +* Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. +* So use sparingly and rarely (if ever) in production code. +* +* Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you +* manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will +* need to manually adjust its BodyDebug as well. +* +* @class Phaser.Physics.P2.BodyDebug +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. +* @param {object} settings - Settings object. +*/ +Phaser.Physics.P2.BodyDebug = function(game, body, settings) { + + Phaser.Group.call(this, game); + + /** + * @property {object} defaultSettings - Default debug settings. + * @private + */ + var defaultSettings = { + pixelsPerLengthUnit: game.physics.p2.mpx(1), + debugPolygons: false, + lineWidth: 1, + alpha: 0.5 + }; + + this.settings = Object.assign(defaultSettings, settings); + + /** + * @property {number} ppu - Pixels per Length Unit. + */ + this.ppu = this.settings.pixelsPerLengthUnit; + this.ppu = -1 * this.ppu; + + /** + * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. + */ + this.body = body; + + /** + * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. + */ + this.canvas = new Phaser.Graphics(game); + + this.canvas.alpha = this.settings.alpha; + + this.add(this.canvas); + + this.draw(); + + this.updateSpriteTransform(); + +}; + +Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); +Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; + +Object.assign(Phaser.Physics.P2.BodyDebug.prototype, { + + /** + * Core update. + * + * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform + */ + updateSpriteTransform: function() { + + this.position.x = this.body.position[0] * this.ppu; + this.position.y = this.body.position[1] * this.ppu; + this.rotation = this.body.angle; + + }, + + /** + * Draws the P2 shapes to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#draw + */ + draw: function() { + + var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; + + obj = this.body; + sprite = this.canvas; + sprite.clear(); + color = parseInt(this.randomPastelHex(), 16); + lineColor = 0xff0000; + lw = this.lineWidth; + + if (obj instanceof p2.Body && obj.shapes.length) + { + var l = obj.shapes.length; + + i = 0; + + while (i !== l) + { + child = obj.shapes[i]; + offset = child.position || 0; + angle = child.angle || 0; + + if (child instanceof p2.Circle) + { + this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); + } + else if (child instanceof p2.Capsule) + { + this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw); + } + 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.Box) + { + this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); + } + else if (child instanceof p2.Convex) + { + verts = []; + vrot = p2.vec2.create(); + + for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _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]); + } + + i++; + } + } + + }, + + /** + * Draws a p2.Box to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawRectangle + * @private + */ + drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + g.beginFill(fillColor); + g.drawRect(x - w / 2, y - h / 2, w, h); + + }, + + /** + * Draws a p2.Circle to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCircle + * @private + */ + drawCircle: function(g, x, y, angle, radius, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + g.lineStyle(lineWidth, 0x000000, 1); + g.beginFill(color, 1.0); + g.drawCircle(x, y, -radius*2); + g.endFill(); + g.moveTo(x, y); + g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); + + }, + + /** + * Draws a p2.Line to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawLine + * @private + */ + drawLine: function(g, len, color, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth * 5, color, 1); + g.moveTo(-len / 2, 0); + g.lineTo(len / 2, 0); + + }, + + /** + * Draws a p2.Convex to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawConvex + * @private + */ + drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { + + var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + 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 = [0xff0000, 0x00ff00, 0x0000ff]; + 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, 0x000000, 1); + return g.drawCircle(offset[0], offset[1], lineWidth * 2); + } + + }, + + /** + * Draws a p2.Path to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPath + * @private + */ + drawPath: function(g, path, color, fillColor, lineWidth) { + + var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + if (typeof fillColor === "number") + { + g.beginFill(fillColor); + } + + lastx = null; + lasty = null; + i = 0; + + while (i < path.length) + { + v = path[i]; + x = v[0]; + y = v[1]; + + if (x !== lastx || y !== lasty) + { + if (i === 0) + { + g.moveTo(x, y); + } + else + { + p1x = lastx; + p1y = lasty; + p2x = x; + p2y = y; + p3x = path[(i + 1) % path.length][0]; + p3y = path[(i + 1) % path.length][1]; + area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); + + if (area !== 0) + { + g.lineTo(x, y); + } + } + lastx = x; + lasty = y; + } + + i++; + + } + + if (typeof fillColor === "number") + { + g.endFill(); + } + + if (path.length > 2 && typeof fillColor === "number") + { + g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); + g.lineTo(path[0][0], path[0][1]); + } + + }, + + /** + * Draws a p2.Plane to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawPlane + * @private + */ + drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { + + var max, xd, yd; + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0xffffff; } + + 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); + + }, + + /** + * Draws a p2.Capsule to the Graphics object. + * + * @method Phaser.Physics.P2.BodyDebug#drawCapsule + * @private + */ + drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) { + + if (lineWidth === undefined) { lineWidth = 1; } + if (color === undefined) { color = 0x000000; } + + g.lineStyle(lineWidth, color, 1); + + // Draw circles at ends + var c = Math.cos(angle); + var s = Math.sin(angle); + + g.beginFill(fillColor, 1); + g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2); + g.drawCircle( len/2*c + x, len/2*s + y, -radius * 2); + g.endFill(); + + // Draw rectangle + g.lineStyle(lineWidth, color, 0); + g.beginFill(fillColor, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.endFill(); + + // Draw lines in between + g.lineStyle(lineWidth, color, 1); + g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y); + g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y); + g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y); + g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y); + + }, + + /** + * Picks a random pastel color. + * + * @method Phaser.Physics.P2.BodyDebug#randomPastelHex + * @private + */ + 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); + + }, + + /** + * Converts from RGB to Hex. + * + * @method Phaser.Physics.P2.BodyDebug#rgbToHex + * @private + */ + rgbToHex: function(r, g, b) { + return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); + }, + + /** + * Component to hex conversion. + * + * @method Phaser.Physics.P2.BodyDebug#componentToHex + * @private + */ + componentToHex: function(c) { + + var hex; + hex = c.toString(16); + + if (hex.length === 2) + { + return hex; + } + else + { + return hex + '0'; + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.Spring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restLength=1] - Rest length of the spring. A number > 0. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. +*/ +Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restLength === undefined) { restLength = 1; } + if (stiffness === undefined) { stiffness = 100; } + if (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]) ]; + } + + /** + * @property {p2.LinearSpring} data - The actual p2 spring object. + */ + this.data = new p2.LinearSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. +* +* @class Phaser.Physics.P2.RotationalSpring +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. +* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. +* @param {number} [damping=1] - Damping of the spring. A number >= 0. +*/ +Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) { + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + if (restAngle === undefined) { restAngle = null; } + if (stiffness === undefined) { stiffness = 100; } + if (damping === undefined) { damping = 1; } + + if (restAngle) + { + restAngle = world.pxm(restAngle); + } + + var options = { + restAngle: restAngle, + stiffness: stiffness, + damping: damping + }; + + /** + * @property {p2.RotationalSpring} data - The actual p2 spring object. + */ + this.data = new p2.RotationalSpring(bodyA, bodyB, options); + + this.data.parent = this; + +}; + +Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A P2 Material. +* +* \o/ ~ "Because I'm a Material girl" +* +* @class Phaser.Physics.P2.Material +* @constructor +* @param {string} name - The user defined name given to this Material. +*/ +Phaser.Physics.P2.Material = function (name) { + + /** + * @property {string} name - The user defined name given to this Material. + * @default + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Defines a physics material +* +* @class Phaser.Physics.P2.ContactMaterial +* @constructor +* @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. +* @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. +* @param {object} [options] - Additional configuration options. +*/ +Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { + + /** + * @property {number} id - The contact material identifier. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. + */ + + /** + * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material. + */ + + /** + * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. + */ + + /** + * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. + */ + + /** + * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generates. + */ + + /** + * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. + */ + + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Collision Group +* +* @class Phaser.Physics.P2.CollisionGroup +* @constructor +* @param {number} bitmask - The CollisionGroup bitmask. +*/ +Phaser.Physics.P2.CollisionGroup = function (bitmask) { + + /** + * @property {number} mask - The CollisionGroup bitmask. + */ + this.mask = bitmask; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A constraint that tries to keep the distance between two bodies constant. +* +* @class Phaser.Physics.P2.DistanceConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} distance - The distance to keep between the bodies. +* @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. +* @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. +* @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply. +*/ +Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { + + if (distance === undefined) { distance = 100; } + if (localAnchorA === undefined) { localAnchorA = [0, 0]; } + if (localAnchorB === undefined) { localAnchorB = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + distance = world.pxm(distance); + + localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ]; + localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ]; + + var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce }; + + p2.DistanceConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); +Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.GearConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {number} [angle=0] - The relative angle +* @param {number} [ratio=1] - The gear ratio. +*/ +Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { + + if (angle === undefined) { angle = 0; } + if (ratio === undefined) { ratio = 1; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Locks the relative position between two bodies. +* +* @class Phaser.Physics.P2.LockConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [angle=0] - The angle of bodyB in bodyA's frame. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { + + if (offset === undefined) { offset = [0, 0]; } + if (angle === undefined) { angle = 0; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* +* @class Phaser.Physics.P2.PrismaticConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {p2.Body} bodyB - Second connected body. +* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. +* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. +*/ +Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { + + if (lockRotation === undefined) { lockRotation = true; } + if (anchorA === undefined) { anchorA = [0, 0]; } + if (anchorB === undefined) { anchorB = [0, 0]; } + if (axis === undefined) { axis = [0, 0]; } + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + 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; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Connects two bodies at given offset points, letting them rotate relative to each other around this point. +* The pivot points are given in world (pixel) coordinates. +* +* @class Phaser.Physics.P2.RevoluteConstraint +* @constructor +* @param {Phaser.Physics.P2} world - A reference to the P2 World. +* @param {p2.Body} bodyA - First connected body. +* @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {p2.Body} bodyB - Second connected body. +* @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. +* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. +* @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. +*/ +Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { + + if (maxForce === undefined) { maxForce = Number.MAX_VALUE; } + if (worldPivot === undefined) { worldPivot = null; } + + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = world.game; + + /** + * @property {Phaser.Physics.P2} world - Local reference to P2 World. + */ + this.world = world; + + pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; + pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; + + if (worldPivot) + { + worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ]; + } + + var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce }; + + p2.RevoluteConstraint.call(this, bodyA, bodyB, options); + +}; + +Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); +Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* An Image Collection is a special tileset containing mulitple images, with no slicing into each image. +* +* Image Collections are normally created automatically when Tiled data is loaded. +* +* @class Phaser.ImageCollection +* @constructor +* @param {string} name - The name of the image collection in the map data. +* @param {integer} firstgid - The first image index this image collection contains. +* @param {integer} [width=32] - Width of widest image (in pixels). +* @param {integer} [height=32] - Height of tallest image (in pixels). +* @param {integer} [margin=0] - The margin around all images in the collection (in pixels). +* @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). +* @param {object} [properties={}] - Custom Image Collection properties. +*/ +Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Image Collection. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of the widest image (in pixels). + * @property {integer} imageWidth + * @readonly + */ + this.imageWidth = width | 0; + + /** + * The height of the tallest image (in pixels). + * @property {integer} imageHeight + * @readonly + */ + this.imageHeight = height | 0; + + /** + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageMarge + * @readonly + */ + // Modified internally + this.imageMargin = margin | 0; + + /** + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageSpacing + * @readonly + */ + this.imageSpacing = spacing | 0; + + /** + * Image Collection-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached images that are a part of this collection. + * @property {array} images + * @readonly + */ + // Modified internally + this.images = []; + + /** + * The total number of images in the image collection. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; +}; + +Phaser.ImageCollection.prototype = { + + /** + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.ImageCollection#containsImageIndex + * @param {integer} imageIndex - The image index to search for. + * @return {boolean} True if this Image Collection contains the given index. + */ + containsImageIndex: function (imageIndex) { + + return ( + imageIndex >= this.firstgid && + imageIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Add an image to this Image Collection. + * + * @method Phaser.ImageCollection#addImage + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + */ + addImage: function (gid, image) { + + this.images.push({ gid: gid, image: image }); + this.total++; + + } + +}; + +Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile is a representation of a single tile within the Tilemap. +* +* @class Phaser.Tile +* @constructor +* @param {object} layer - The layer in the Tilemap data that this tile belongs to. +* @param {number} index - The index of this tile type in the core map data. +* @param {number} x - The x coordinate of this tile. +* @param {number} y - The y coordinate of this tile. +* @param {number} width - Width of the tile. +* @param {number} height - Height of the tile. +*/ +Phaser.Tile = function (layer, index, x, y, width, height) { + + /** + * @property {object} layer - The layer in the Tilemap data that this tile belongs to. + */ + this.layer = layer; + + /** + * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. + */ + this.index = index; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.x = x; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.y = y; + + /** + * @property {number} rotation - The rotation angle of this tile. + */ + this.rotation = 0; + + /** + * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not. + */ + this.flipped = false; + + /** + * @property {number} x - The x map coordinate of this tile. + */ + this.worldX = x * width; + + /** + * @property {number} y - The y map coordinate of this tile. + */ + this.worldY = y * height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.width = width; + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.height = height; + + /** + * @property {number} width - The width of the tile in pixels. + */ + this.centerX = Math.abs(width / 2); + + /** + * @property {number} height - The height of the tile in pixels. + */ + this.centerY = Math.abs(height / 2); + + /** + * @property {number} alpha - The alpha value at which this tile is drawn to the canvas. + */ + this.alpha = 1; + + /** + * @property {object} properties - Tile specific properties. + */ + this.properties = {}; + + /** + * @property {boolean} scanned - Has this tile been walked / turned into a poly? + */ + this.scanned = false; + + /** + * @property {boolean} faceTop - Is the top of this tile an interesting edge? + */ + this.faceTop = false; + + /** + * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge? + */ + this.faceBottom = false; + + /** + * @property {boolean} faceLeft - Is the left of this tile an interesting edge? + */ + this.faceLeft = false; + + /** + * @property {boolean} faceRight - Is the right of this tile an interesting edge? + */ + this.faceRight = false; + + /** + * @property {boolean} collideLeft - Indicating collide with any object on the left. + * @default + */ + this.collideLeft = false; + + /** + * @property {boolean} collideRight - Indicating collide with any object on the right. + * @default + */ + this.collideRight = false; + + /** + * @property {boolean} collideUp - Indicating collide with any object on the top. + * @default + */ + this.collideUp = false; + + /** + * @property {boolean} collideDown - Indicating collide with any object on the bottom. + * @default + */ + this.collideDown = false; + + /** + * @property {function} collisionCallback - Tile collision callback. + * @default + */ + this.collisionCallback = null; + + /** + * @property {object} collisionCallbackContext - The context in which the collision callback will be called. + * @default + */ + this.collisionCallbackContext = this; + + /** + * @property {boolean} debug + * @default + */ + this.debug = false; + +}; + +Phaser.Tile.prototype = { + + /** + * Check if the given x and y world coordinates are within this Tile. + * + * @method Phaser.Tile#containsPoint + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ + containsPoint: function (x, y) { + + return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom); + + }, + + /** + * Check for intersection with this tile. + * + * @method Phaser.Tile#intersects + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + */ + 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; + + }, + + /** + * Set a callback to be called when this tile is hit by an object. + * The callback must true true for collision processing to take place. + * + * @method Phaser.Tile#setCollisionCallback + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + */ + setCollisionCallback: function (callback, context) { + + this.collisionCallback = callback; + this.collisionCallbackContext = context; + + }, + + /** + * Clean up memory. + * + * @method Phaser.Tile#destroy + */ + destroy: function () { + + this.collisionCallback = null; + this.collisionCallbackContext = null; + this.properties = null; + + }, + + /** + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tile#setCollision + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} right - Indicating collide with any object on the right. + * @param {boolean} up - Indicating collide with any object on the top. + * @param {boolean} down - Indicating collide with any object on the bottom. + */ + setCollision: function (left, right, up, down) { + + this.collideLeft = left; + this.collideRight = right; + this.collideUp = up; + this.collideDown = down; + + this.faceLeft = left; + this.faceRight = right; + this.faceTop = up; + this.faceBottom = down; + + }, + + /** + * Reset collision status flags. + * + * @method Phaser.Tile#resetCollision + */ + 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; + + }, + + /** + * Is this tile interesting? + * + * @method Phaser.Tile#isInteresting + * @param {boolean} collides - If true will check any collides value. + * @param {boolean} faces - If true will check any face value. + * @return {boolean} True if the Tile is interesting, otherwise false. + */ + isInteresting: function (collides, faces) { + + if (collides && faces) + { + // Does this tile have any collide flags OR interesting face? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback); + } + else if (collides) + { + // Does this tile collide? + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + else if (faces) + { + // Does this tile have an interesting face? + return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight); + } + + return false; + + }, + + /** + * Copies the tile data and properties from the given tile to this tile. + * + * @method Phaser.Tile#copy + * @param {Phaser.Tile} tile - The tile to copy from. + */ + 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; + +/** +* @name Phaser.Tile#collides +* @property {boolean} collides - True if this tile can collide on any of its faces. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "collides", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown); + } + +}); + +/** +* @name Phaser.Tile#canCollide +* @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "canCollide", { + + get: function () { + return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback); + } + +}); + +/** +* @name Phaser.Tile#left +* @property {number} left - The x value in pixels. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "left", { + + get: function () { + return this.worldX; + } + +}); + +/** +* @name Phaser.Tile#right +* @property {number} right - The sum of the x and width properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "right", { + + get: function () { + return this.worldX + this.width; + } + +}); + +/** +* @name Phaser.Tile#top +* @property {number} top - The y value. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "top", { + + get: function () { + return this.worldY; + } + +}); + +/** +* @name Phaser.Tile#bottom +* @property {number} bottom - The sum of the y and height properties. +* @readonly +*/ +Object.defineProperty(Phaser.Tile.prototype, "bottom", { + + get: function () { + return this.worldY + this.height; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. +* +* Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org +* +* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. +* When using CSV data you must provide the key and the tileWidth and tileHeight parameters. +* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. +* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. +* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. +* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. +* +* @class Phaser.Tilemap +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. +* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. +* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. +*/ +Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {string} key - The key of this map data in the Phaser.Cache. + */ + this.key = key; + + var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height); + + if (data === null) + { + return; + } + + /** + * @property {number} width - The width of the map (in tiles). + */ + this.width = data.width; + + /** + * @property {number} height - The height of the map (in tiles). + */ + this.height = data.height; + + /** + * @property {number} tileWidth - The base width of the tiles in the map (in pixels). + */ + this.tileWidth = data.tileWidth; + + /** + * @property {number} tileHeight - The base height of the tiles in the map (in pixels). + */ + this.tileHeight = data.tileHeight; + + /** + * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + */ + this.orientation = data.orientation; + + /** + * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + */ + this.format = data.format; + + /** + * @property {number} version - The version of the map data (as specified in Tiled, usually 1). + */ + this.version = data.version; + + /** + * @property {object} properties - Map specific properties as specified in Tiled. + */ + this.properties = data.properties; + + /** + * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth. + */ + this.widthInPixels = data.widthInPixels; + + /** + * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight. + */ + this.heightInPixels = data.heightInPixels; + + /** + * @property {array} layers - An array of Tilemap layer data. + */ + this.layers = data.layers; + + /** + * @property {array} tilesets - An array of Tilesets. + */ + this.tilesets = data.tilesets; + + /** + * @property {array} imagecollections - An array of Image Collections. + */ + this.imagecollections = data.imagecollections; + + /** + * @property {array} tiles - The super array of Tiles. + */ + this.tiles = data.tiles; + + /** + * @property {array} objects - An array of Tiled Object Layers. + */ + this.objects = data.objects; + + /** + * @property {array} collideIndexes - An array of tile indexes that collide. + */ + this.collideIndexes = []; + + /** + * @property {array} collision - An array of collision data (polylines, etc). + */ + this.collision = data.collision; + + /** + * @property {array} images - An array of Tiled Image Layers. + */ + this.images = data.images; + + /** + * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data. + */ + this.enableDebug = false; + + /** + * @property {number} currentLayer - The current layer. + */ + this.currentLayer = 0; + + /** + * @property {array} debugMap - Map data used for debug values only. + */ + this.debugMap = []; + + /** + * @property {array} _results - Internal var. + * @private + */ + this._results = []; + + /** + * @property {number} _tempA - Internal var. + * @private + */ + this._tempA = 0; + + /** + * @property {number} _tempB - Internal var. + * @private + */ + this._tempB = 0; + +}; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.CSV = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.TILED_JSON = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.NORTH = 0; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.EAST = 1; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.SOUTH = 2; + +/** +* @constant +* @type {number} +*/ +Phaser.Tilemap.WEST = 3; + +Phaser.Tilemap.prototype = { + + /** + * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. + * + * @method Phaser.Tilemap#create + * @param {string} name - The name of the default layer of the map. + * @param {number} width - The width of the map in tiles. + * @param {number} height - The height of the map in tiles. + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + create: function (name, width, height, tileWidth, tileHeight, group) { + + if (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); + + }, + + /** + * Sets the base tile size for the map. + * + * @method Phaser.Tilemap#setTileSize + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + */ + setTileSize: function (tileWidth, tileHeight) { + + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.widthInPixels = this.width * tileWidth; + this.heightInPixels = this.height * tileHeight; + + }, + + /** + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. + * + * @method Phaser.Tilemap#addTilesetImage + * @param {string} tileset - The name of the tileset as specified in the map data. + * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset. + * If `undefined` or `null` it will look for an image with a key matching the tileset parameter. + * You can also pass in a BitmapData which can be used instead of an Image. + * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. + * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. + * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. + * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. + * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. + * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed. + */ + addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { + + if (tileset === undefined) { return null; } + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + if (tileMargin === undefined) { tileMargin = 0; } + if (tileSpacing === undefined) { tileSpacing = 0; } + if (gid === undefined) { gid = 0; } + + // In-case we're working from a blank map + if (tileWidth === 0) + { + tileWidth = 32; + } + + if (tileHeight === 0) + { + tileHeight = 32; + } + + var img = null; + + if (key === undefined || key === null) + { + key = tileset; + } + + if (key instanceof Phaser.BitmapData) + { + img = key.canvas; + } + else + { + if (!this.game.cache.checkImageKey(key)) + { + console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"'); + return null; + } + + img = this.game.cache.getImage(key); + } + + var idx = this.getTilesetIndex(tileset); + + if (idx === null && this.format === Phaser.Tilemap.TILED_JSON) + { + console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + tileset + '"'); + console.log('Tilesets: ', this.tilesets); + return null; + } + + if (this.tilesets[idx]) + { + this.tilesets[idx].setImage(img); + return this.tilesets[idx]; + } + else + { + var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {}); + + newSet.setImage(img); + + 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; t < gid + newSet.total; t++) + { + this.tiles[t] = [x, y, i]; + + x += tileWidth + tileSpacing; + + count++; + + if (count === newSet.total) + { + break; + } + + countX++; + + if (countX === newSet.columns) + { + x = tileMargin; + y += tileHeight + tileSpacing; + + countX = 0; + countY++; + + if (countY === newSet.rows) + { + break; + } + } + } + + return newSet; + + } + + return null; + + }, + + /** + * Creates a Sprite for every {@link http://doc.mapeditor.org/reference/tmx-map-format/#object object} matching the `gid` argument. You can optionally specify the group that the Sprite will be created in. If none is + * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to + * configure Sprite properties from within the map editor. For example giving an object a property of `alpha: 0.5` in the map editor will duplicate that when the + * Sprite is created. You could also give it a value like: `body.velocity.x: 100` to set it moving automatically. + * + * The `gid` argument is matched against: + * + * 1. For a tile object, the tile identifier (`gid`); or + * 2. The object's unique ID (`id`); or + * 3. The object's `name` (a string) + * + * @method Phaser.Tilemap#createFromObjects + * @param {string} name - The name of the Object Group to create Sprites from. + * @param {number|string} gid - The object's tile reference (gid), unique ID (id) or name. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. + * @param {boolean} [exists=true] - The default exists state of the Sprite. + * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. + * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. + * @param {boolean} [adjustSize=true] - By default the width and height of the objects are transferred to the sprite. This parameter controls that behavior. + */ + createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY, adjustSize) { + + if (exists === undefined) { exists = true; } + if (autoCull === undefined) { autoCull = false; } + if (group === undefined) { group = this.game.world; } + if (CustomClass === undefined) { CustomClass = Phaser.Sprite; } + if (adjustY === undefined) { adjustY = true; } + if (adjustSize === undefined) { adjustSize = true; } + + if (!this.objects[name]) + { + console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name); + console.log('Objects: ', this.objects); + return; + } + + for (var i = 0; i < this.objects[name].length; i++) + { + var found = false; + var obj = this.objects[name][i]; + + if (obj.gid !== undefined && typeof gid === 'number' && obj.gid === gid) + { + found = true; + } + else if (obj.id !== undefined && typeof gid === 'number' && obj.id === gid) + { + found = true; + } + else if (obj.name !== undefined && typeof gid === 'string' && obj.name === gid) + { + found = true; + } + + if (found) + { + var sprite = new CustomClass(this.game, parseFloat(obj.x, 10), parseFloat(obj.y, 10), key, frame); + + sprite.name = obj.name; + sprite.autoCull = autoCull; + sprite.exists = exists; + sprite.visible = obj.visible; + + if (adjustSize) + { + if (obj.width) + { + sprite.width = obj.width; + } + + if (obj.height) + { + sprite.height = obj.height; + } + } + + if (obj.rotation) + { + sprite.angle = obj.rotation; + } + + if (adjustY) + { + sprite.y -= sprite.height; + } + + group.add(sprite); + + for (var property in obj.properties) + { + group.set(sprite, property, obj.properties[property], false, false, 0, true); + } + } + } + + }, + + /** + * Creates a Sprite for every object matching the given tile indexes in the map data. + * You can specify the group that the Sprite will be created in. If none is given it will be created in the World. + * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special + * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemap#createFromTiles + * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from. + * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. + * @return {integer} The number of Sprites that were created. + */ + createFromTiles: function (tiles, replacements, key, layer, group, properties) { + + if (typeof tiles === 'number') { tiles = [tiles]; } + + if (replacements === undefined || replacements === null) + { + replacements = []; + } + else if (typeof replacements === 'number') + { + replacements = [replacements]; + } + + layer = this.getLayer(layer); + + if (group === undefined) { group = this.game.world; } + if (properties === undefined) { properties = {}; } + + if (properties.customClass === undefined) + { + properties.customClass = Phaser.Sprite; + } + + if (properties.adjustY === undefined) + { + properties.adjustY = true; + } + + var lw = this.layers[layer].width; + var lh = this.layers[layer].height; + + this.copy(0, 0, lw, lh, layer); + + if (this._results.length < 2) + { + return 0; + } + + var total = 0; + var sprite; + + for (var i = 1, len = this._results.length; i < len; i++) + { + if (tiles.indexOf(this._results[i].index) !== -1) + { + sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key); + + for (var property in properties) + { + sprite[property] = properties[property]; + } + + group.add(sprite); + total++; + } + + } + + if (replacements.length === 1) + { + // Assume 1 replacement for all types of tile given + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer); + } + } + else if (replacements.length > 1) + { + // Assume 1 for 1 mapping + for (i = 0; i < tiles.length; i++) + { + this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer); + } + } + + return total; + + }, + + /** + * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. + * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. + * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. + * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. + * + * @method Phaser.Tilemap#createLayer + * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. + * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. + * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. + * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. + */ + createLayer: function (layer, width, height, group) { + + // Add Buffer support for the left of the canvas + + if (width === undefined) { width = this.game.width; } + if (height === undefined) { height = this.game.height; } + if (group === undefined) { group = this.game.world; } + + var index = layer; + + if (typeof layer === 'string') + { + index = this.getLayerIndex(layer); + } + + if (index === null || index > this.layers.length) + { + console.warn('Tilemap.createLayer: Invalid layer ID given: "' + layer + '"'); + console.log('Layers: ', this.layers); + return; + } + + // Sort out the display dimensions, so they never render too much, or too little. + + if (width === undefined || width <= 0) + { + width = Math.min(this.game.width, this.layers[index].widthInPixels); + } + else if (width > this.game.width) + { + width = this.game.width; + } + + if (height === undefined || height <= 0) + { + height = Math.min(this.game.height, this.layers[index].heightInPixels); + } + else if (height > this.game.height) + { + height = this.game.height; + } + + if (this.enableDebug) + { + console.group('Tilemap.createLayer'); + console.log('Name:', this.layers[index].name); + console.log('Size:', width, 'x', height); + console.log('Tileset:', this.tilesets[0].name, 'index:', index); + } + + var rootLayer = group.add(new Phaser.TilemapLayer(this.game, this, index, width, height)); + + if (this.enableDebug) + { + console.groupEnd(); + } + + return rootLayer; + + }, + + + /** + * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. + * + * @method Phaser.Tilemap#createBlankLayer + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {number} width - The width of the layer in tiles. + * @param {number} height - The height of the layer in tiles. + * @param {number} tileWidth - The width of the tiles the layer uses for calculations. + * @param {number} tileHeight - The height of the tiles the layer uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ + createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) { + + if (group === undefined) { group = this.game.world; } + + if (this.getLayerIndex(name) !== null) + { + console.warn('Tilemap.createBlankLayer: Layer with matching name already exists: ' + name); + 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; y < height; y++) + { + row = []; + + for (var x = 0; x < width; x++) + { + row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight)); + } + + output.push(row); + } + + layer.data = output; + + this.layers.push(layer); + + this.currentLayer = this.layers.length - 1; + + var w = layer.widthInPixels; + var h = layer.heightInPixels; + + if (w > this.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); + + }, + + /** + * Gets the layer index based on the layers name. + * + * @method Phaser.Tilemap#getIndex + * @protected + * @param {array} location - The local array to search. + * @param {string} name - The name of the array element to get. + * @return {number} The index of the element in the array, or null if not found. + */ + getIndex: function (location, name) { + + for (var i = 0; i < location.length; i++) + { + if (location[i].name === name) + { + return i; + } + } + + return null; + + }, + + /** + * Gets the layer index based on its name. + * + * @method Phaser.Tilemap#getLayerIndex + * @param {string} name - The name of the layer to get. + * @return {number} The index of the layer in this tilemap, or null if not found. + */ + getLayerIndex: function (name) { + + return this.getIndex(this.layers, name); + + }, + + /** + * Gets the tileset index based on its name. + * + * @method Phaser.Tilemap#getTilesetIndex + * @param {string} name - The name of the tileset to get. + * @return {number} The index of the tileset in this tilemap, or null if not found. + */ + getTilesetIndex: function (name) { + + return this.getIndex(this.tilesets, name); + + }, + + /** + * Gets the image index based on its name. + * + * @method Phaser.Tilemap#getImageIndex + * @param {string} name - The name of the image to get. + * @return {number} The index of the image in this tilemap, or null if not found. + */ + getImageIndex: function (name) { + + return this.getIndex(this.images, name); + + }, + + /** + * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileIndexCallback + * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileIndexCallback: function (indexes, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes]; + } + else + { + // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much + // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit. + this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext }; + } + } + else + { + for (var i = 0, len = indexes.length; i < len; i++) + { + if (callback === null) + { + delete this.layers[layer].callbacks[indexes[i]]; + } + else + { + this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext }; + } + } + } + + }, + + /** + * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileLocationCallback + * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} width - The width of the area to copy (given in tiles, not pixels) + * @param {number} height - The height of the area to copy (given in tiles, not pixels) + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ + setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].setCollisionCallback(callback, callbackContext); + } + + }, + + /** + * Sets collision on the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [2, 3, 15, 20]. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * Collision-enabled tiles can be collided against Sprites using {@link Phaser.Physics.Arcade#collide}. + * + * You can verify the collision faces by enabling {@link Phaser.TilemapLayer#debug}. + * + * @method Phaser.Tilemap#setCollision + * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollision: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (typeof indexes === 'number') + { + return this.setCollisionByIndex(indexes, collides, layer, true); + } + else if (Array.isArray(indexes)) + { + // Collide all of the IDs given in the indexes array + for (var i = 0; i < indexes.length; i++) + { + this.setCollisionByIndex(indexes[i], collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + } + + }, + + /** + * Sets collision on a range of tiles where the tile IDs increment sequentially. + * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionBetween + * @param {number} start - The first index of the tile to be set for collision. + * @param {number} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionBetween: function (start, stop, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + if (start > stop) + { + return; + } + + for (var index = start; index <= stop; index++) + { + this.setCollisionByIndex(index, collides, layer, false); + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision on all tiles in the given layer, except for the IDs of those in the given array. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionByExclusion + * @param {array} indexes - An array of the tile IDs to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByExclusion: function (indexes, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (recalculate === undefined) { recalculate = true; } + + layer = this.getLayer(layer); + + // Collide everything, except the IDs given in the indexes array + for (var i = 0, len = this.tiles.length; i < len; i++) + { + if (indexes.indexOf(i) === -1) + { + this.setCollisionByIndex(i, collides, layer, false); + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + }, + + /** + * Sets collision values on a tile in the set. + * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. + * + * @method Phaser.Tilemap#setCollisionByIndex + * @protected + * @param {number} index - The index of the tile on the layer. + * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile. + * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ + setCollisionByIndex: function (index, collides, layer, recalculate) { + + if (collides === undefined) { collides = true; } + if (layer === undefined) { layer = this.currentLayer; } + if (recalculate === undefined) { recalculate = true; } + + if (collides) + { + this.collideIndexes.push(index); + } + else + { + var i = this.collideIndexes.indexOf(index); + + if (i > -1) + { + this.collideIndexes.splice(i, 1); + } + } + + for (var y = 0; y < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile && tile.index === index) + { + if (collides) + { + tile.setCollision(true, true, true, true); + } + else + { + tile.resetCollision(); + } + + tile.faceTop = collides; + tile.faceBottom = collides; + tile.faceLeft = collides; + tile.faceRight = collides; + } + } + } + + if (recalculate) + { + // Now re-calculate interesting faces + this.calculateFaces(layer); + } + + return layer; + + }, + + /** + * Gets the TilemapLayer index as used in the setCollision calls. + * + * @method Phaser.Tilemap#getLayer + * @protected + * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer. + * @return {number} The TilemapLayer index. + */ + getLayer: function (layer) { + + if (layer === undefined) + { + layer = this.currentLayer; + } + else if (typeof layer === 'string') + { + var layerArg = layer; + + layer = this.getLayerIndex(layer); + + if (!layer) + { + console.warn('No such layer name: ' + layerArg); + } + } + else if (layer instanceof Phaser.TilemapLayer) + { + layer = layer.index; + } + + return layer; + + }, + + /** + * Turn off/on the recalculation of faces for tile or collision updates. + * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. + * + * @method Phaser.Tilemap#setPreventRecalculate + * @param {boolean} value - If true it will put the recalculation on hold. + */ + setPreventRecalculate: function (value) { + + if (value === true && this.preventingRecalculate !== true) + { + this.preventingRecalculate = true; + this.needToRecalculate = {}; + } + + if (value === false && this.preventingRecalculate === true) + { + this.preventingRecalculate = false; + + for (var i in this.needToRecalculate) + { + this.calculateFaces(i); + } + + this.needToRecalculate = false; + } + + }, + + /** + * Internal function. + * + * @method Phaser.Tilemap#calculateFaces + * @protected + * @param {number} layer - The index of the TilemapLayer to operate on. + */ + calculateFaces: function (layer) { + + if (this.preventingRecalculate) + { + this.needToRecalculate[layer] = true; + return; + } + + var above = null; + var below = null; + var left = null; + var right = null; + + for (var y = 0, h = this.layers[layer].height; y < h; y++) + { + for (var x = 0, w = this.layers[layer].width; x < w; x++) + { + var tile = this.layers[layer].data[y][x]; + + if (tile) + { + above = this.getTileAbove(layer, x, y); + below = this.getTileBelow(layer, x, y); + left = this.getTileLeft(layer, x, y); + right = this.getTileRight(layer, x, y); + + if (tile.collides) + { + tile.faceTop = true; + tile.faceBottom = true; + tile.faceLeft = true; + tile.faceRight = true; + } + + if (above && above.collides) + { + // There is a tile above this one that also collides, so the top of this tile is no longer interesting + tile.faceTop = false; + } + + if (below && below.collides) + { + // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting + tile.faceBottom = false; + } + + if (left && left.collides) + { + // There is a tile left this one that also collides, so the left of this tile is no longer interesting + tile.faceLeft = false; + } + + if (right && right.collides) + { + // There is a tile right this one that also collides, so the right of this tile is no longer interesting + tile.faceRight = false; + } + } + } + } + + }, + + /** + * Gets the tile above the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileAbove + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileAbove: function (layer, x, y) { + + if (y > 0) + { + return this.layers[layer].data[y - 1][x]; + } + + return null; + + }, + + /** + * Gets the tile below the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileBelow + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileBelow: function (layer, x, y) { + + if (y < this.layers[layer].height - 1) + { + return this.layers[layer].data[y + 1][x]; + } + + return null; + + }, + + /** + * Gets the tile to the left of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileLeft + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileLeft: function (layer, x, y) { + + if (x > 0) + { + return this.layers[layer].data[y][x - 1]; + } + + return null; + + }, + + /** + * Gets the tile to the right of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileRight + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ + getTileRight: function (layer, x, y) { + + if (x < this.layers[layer].width - 1) + { + return this.layers[layer].data[y][x + 1]; + } + + return null; + + }, + + /** + * Sets the current layer to the given index. + * + * @method Phaser.Tilemap#setLayer + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + */ + setLayer: function (layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer]) + { + this.currentLayer = layer; + } + + }, + + /** + * Checks if there is a tile at the given location. + * + * @method Phaser.Tilemap#hasTile + * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels) + * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + * @return {boolean} True if there is a tile at the given location, otherwise false. + */ + hasTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined) + { + return false; + } + + return (this.layers[layer].data[y][x].index > -1); + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. + * + * @method Phaser.Tilemap#removeTile + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTile: function (x, y, layer) { + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.hasTile(x, y, layer)) + { + var tile = this.layers[layer].data[y][x]; + + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight); + + this.layers[layer].dirty = true; + + this.calculateFaces(layer); + + return tile; + } + } + + }, + + /** + * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#removeTileWorldXY + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ + removeTileWorldXY: function (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.removeTile(x, y, layer); + + }, + + /** + * Puts a tile of the given index value at the coordinate specified. + * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. + * + * @method Phaser.Tilemap#putTile + * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map. + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + putTile: function (tile, x, y, layer) { + + if (tile === null) + { + return this.removeTile(x, y, layer); + } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + var index; + + if (tile instanceof Phaser.Tile) + { + index = tile.index; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].copy(tile); + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height); + } + } + else + { + index = tile; + + if (this.hasTile(x, y, layer)) + { + this.layers[layer].data[y][x].index = index; + } + else + { + this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight); + } + } + + if (this.collideIndexes.indexOf(index) > -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; + + }, + + /** + * Puts a tile into the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#putTileWorldXY + * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object. + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ + 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); + + }, + + /** + * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. + * If no match is found it returns null. + * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. + * + * @method Phaser.Tilemap#searchTileIndex + * @param {number} index - The tile index value to search for. + * @param {number} [skip=0] - The number of times to skip a matching tile before returning. + * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @return {Phaser.Tile} The first (or n skipped) tile with the matching index. + */ + searchTileIndex: function (index, skip, reverse, layer) { + + if (skip === undefined) { skip = 0; } + if (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 < this.layers[layer].height; y++) + { + for (var x = 0; x < this.layers[layer].width; x++) + { + if (this.layers[layer].data[y][x].index === index) + { + if (c === skip) + { + return this.layers[layer].data[y][x]; + } + else + { + c++; + } + } + } + } + } + + return null; + + }, + + /** + * Gets a tile from the Tilemap Layer. The coordinates are given in tile values. + * + * @method Phaser.Tilemap#getTile + * @param {number} x - X position to get the tile from (given in tile units, not pixels) + * @param {number} y - Y position to get the tile from (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ + getTile: function (x, y, layer, nonNull) { + + if (nonNull === undefined) { nonNull = false; } + + layer = this.getLayer(layer); + + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + if (this.layers[layer].data[y][x].index === -1) + { + if (nonNull) + { + return this.layers[layer].data[y][x]; + } + else + { + return null; + } + } + else + { + return this.layers[layer].data[y][x]; + } + } + else + { + return null; + } + + }, + + /** + * Gets a tile from the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#getTileWorldXY + * @param {number} x - X position to get the tile from (given in pixels) + * @param {number} y - Y position to get the tile from (given in pixels) + * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used. + * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates. + */ + getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) { + + if (tileWidth === undefined) { tileWidth = this.tileWidth; } + if (tileHeight === undefined) { tileHeight = this.tileHeight; } + + layer = this.getLayer(layer); + + x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; + y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; + + return this.getTile(x, y, layer, nonNull); + + }, + + /** + * Copies all of the tiles in the given rectangular block into the tilemap data buffer. + * + * @method Phaser.Tilemap#copy + * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} width - The width of the area to copy (given in tiles, not pixels) + * @param {integer} height - The height of the area to copy (given in tiles, not pixels) + * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from. + * @return {array} An array of the tiles that were copied. + */ + copy: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + if (!this.layers[layer]) + { + this._results.length = 0; + return; + } + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + if (width === undefined) { width = this.layers[layer].width; } + if (height === undefined) { height = this.layers[layer].height; } + + if (x < 0) + { + x = 0; + } + + if (y < 0) + { + y = 0; + } + + if (width > this.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; ty < y + height; ty++) + { + for (var tx = x; tx < x + width; tx++) + { + this._results.push(this.layers[layer].data[ty][tx]); + } + } + + return this._results; + + }, + + /** + * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. + * + * @method Phaser.Tilemap#paste + * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels) + * @param {array} tileblock - The block of tiles to paste. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into. + */ + paste: function (x, y, tileblock, layer) { + + if (x === undefined) { x = 0; } + if (y === undefined) { y = 0; } + + layer = this.getLayer(layer); + + if (!tileblock || tileblock.length < 2) + { + return; + } + + // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste + var diffX = x - tileblock[1].x; + var diffY = y - tileblock[1].y; + + for (var i = 1; i < tileblock.length; i++) + { + this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]); + } + + this.layers[layer].dirty = true; + this.calculateFaces(layer); + + }, + + /** + * Scans the given area for tiles with an index matching tileA and swaps them with tileB. + * + * @method Phaser.Tilemap#swap + * @param {number} tileA - First tile index. + * @param {number} tileB - Second tile index. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + swap: function (tileA, tileB, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._tempA = tileA; + this._tempB = tileB; + + this._results.forEach(this.swapHandler, this); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Internal function that handles the swapping of tiles. + * + * @method Phaser.Tilemap#swapHandler + * @private + * @param {number} value + */ + swapHandler: function (value) { + + if (value.index === this._tempA) + { + // Swap A with B + value.index = this._tempB; + } + else if (value.index === this._tempB) + { + // Swap B with A + value.index = this._tempA; + } + + }, + + /** + * For each tile in the given area defined by x/y and width/height run the given callback. + * + * @method Phaser.Tilemap#forEach + * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {number} context - The context under which the callback should be run. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + forEach: function (callback, context, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + this._results.forEach(callback, context); + + this.paste(x, y, this._results, layer); + + }, + + /** + * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. + * + * @method Phaser.Tilemap#replace + * @param {number} source - The tile index value to scan for. + * @param {number} dest - The tile index value to replace found tiles with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + replace: function (source, dest, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + if (this._results[i].index === source) + { + this._results[i].index = dest; + } + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Randomises a set of tiles in a given area. + * + * @method Phaser.Tilemap#random + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + random: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + var idx = this._results[t].index; + + if (indexes.indexOf(idx) === -1) + { + indexes.push(idx); + } + } + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = this.game.rnd.pick(indexes); + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! + * + * @method Phaser.Tilemap#shuffle + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + shuffle: function (x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + var indexes = []; + + for (var t = 1; t < this._results.length; t++) + { + if (this._results[t].index) + { + indexes.push(this._results[t].index); + } + } + + Phaser.ArrayUtils.shuffle(indexes); + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = indexes[i - 1]; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Fills the given area with the specified tile. + * + * @method Phaser.Tilemap#fill + * @param {number} index - The index of the tile that the area will be filled with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ + fill: function (index, x, y, width, height, layer) { + + layer = this.getLayer(layer); + + this.copy(x, y, width, height, layer); + + if (this._results.length < 2) + { + return; + } + + for (var i = 1; i < this._results.length; i++) + { + this._results[i].index = index; + } + + this.paste(x, y, this._results, layer); + + }, + + /** + * Removes all layers from this tile map. + * + * @method Phaser.Tilemap#removeAllLayers + */ + removeAllLayers: function () { + + this.layers.length = 0; + this.currentLayer = 0; + + }, + + /** + * Dumps the tilemap data out to the console. + * + * @method Phaser.Tilemap#dump + */ + dump: function () { + + var txt = ''; + var args = ['']; + + for (var y = 0; y < this.layers[this.currentLayer].height; y++) + { + for (var x = 0; x < this.layers[this.currentLayer].width; x++) + { + txt += "%c "; + + if (this.layers[this.currentLayer].data[y][x] > 1) + { + 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); + + }, + + /** + * Removes all layer data from this tile map and nulls the game reference. + * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. + * + * @method Phaser.Tilemap#destroy + */ + destroy: function () { + + this.removeAllLayers(); + this.data = []; + this.game = null; + + } + +}; + +Phaser.Tilemap.prototype.constructor = Phaser.Tilemap; + +/** +* @name Phaser.Tilemap#layer +* @property {number|string|Phaser.TilemapLayer} layer - The current layer object. +*/ +Object.defineProperty(Phaser.Tilemap.prototype, "layer", { + + get: function () { + + return this.layers[this.currentLayer]; + + }, + + set: function (value) { + + if (value !== this.currentLayer) + { + this.setLayer(value); + } + + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. +* +* Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. +* +* By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. +* +* @class Phaser.TilemapLayer +* @extends Phaser.Sprite +* @constructor +* @param {Phaser.Game} game - Game reference to the currently running game. +* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs. +* @param {integer} index - The index of the TileLayer to render within the Tilemap. +* @param {integer} width - Width of the renderable area of the layer (in pixels). +* @param {integer} height - Height of the renderable area of the layer (in pixels). +*/ +Phaser.TilemapLayer = function (game, tilemap, index, width, height) { + + width |= 0; + height |= 0; + + Phaser.Sprite.call(this, game, 0, 0); + + /** + * The Tilemap to which this layer is bound. + * @property {Phaser.Tilemap} map + * @protected + * @readonly + */ + this.map = tilemap; + + /** + * The index of this layer within the Tilemap. + * @property {number} index + * @protected + * @readonly + */ + this.index = index; + + /** + * The layer object within the Tilemap that this layer represents. + * @property {object} layer + * @protected + * @readonly + */ + this.layer = tilemap.layers[index]; + + /** + * The canvas to which this TilemapLayer draws. + * @property {HTMLCanvasElement} canvas + * @protected + */ + this.canvas = Phaser.CanvasPool.create(this, width, height); + + /** + * The 2d context of the canvas. + * @property {CanvasRenderingContext2D} context + * @private + */ + this.context = this.canvas.getContext('2d'); + + this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas, null, this.game.resolution))); + + /** + * The const type of this object. + * @property {number} type + * @readonly + * @protected + * @default Phaser.TILEMAPLAYER + */ + this.type = Phaser.TILEMAPLAYER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.TILEMAPLAYER; + + /** + * Settings that control standard (non-diagnostic) rendering. + * + * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view. + * This can greatly improve scrolling rendering performance, especially when there are many small tiles. + * It should only be disabled in rare cases. + * + * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas. + * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior + * in some browsers, notably Safari. + * + * @default + */ + this.renderSettings = { + enableScrollDelta: true, + overdrawRatio: 0.20, + copyCanvas: null + }; + + /** + * Enable an additional "debug rendering" pass to display collision information. + * + * @property {boolean} debug + * @default + */ + this.debug = false; + + /** + * @property {boolean} exists - Controls if the core game loop and physics update this game object or not. + */ + this.exists = true; + + /** + * Settings used for debugging and diagnostics. + * + * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. + * + * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. + * + * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. + * + * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. + * + */ + this.debugSettings = { + + missingImageFill: 'rgb(255,255,255)', + debuggedTileOverfill: 'rgba(0,255,0,0.4)', + + forceFullRedraw: true, + + debugAlpha: 0.5, + facingEdgeStroke: 'rgba(0,255,0,1)', + collidingTileOverfill: 'rgba(0,255,0,0.2)' + + }; + + /** + * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). + * @property {number} scrollFactorX + * @public + * @default + */ + this.scrollFactorX = 1; + + /** + * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) + * @property {number} scrollFactorY + * @public + * @default + */ + this.scrollFactorY = 1; + + /** + * If true tiles will be force rendered, even if such is not believed to be required. + * @property {boolean} dirty + * @protected + */ + this.dirty = true; + + /** + * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. + * @property {integer} rayStepRate + * @default + */ + this.rayStepRate = 4; + + /** + * Flag controlling if the layer tiles wrap at the edges. + * @property {boolean} _wrap + * @private + */ + this._wrap = false; + + /** + * Local map data and calculation cache. + * @property {object} _mc + * @private + */ + this._mc = { + + // Used to bypass rendering without reliance on `dirty` and detect changes. + scrollX: 0, + scrollY: 0, + renderWidth: 0, + renderHeight: 0, + + tileWidth: tilemap.tileWidth, + tileHeight: tilemap.tileHeight, + + // Collision width/height (pixels) + // What purpose do these have? Most things use tile width/height directly. + // This also only extends collisions right and down. + cw: tilemap.tileWidth, + ch: tilemap.tileHeight, + + // Cached tilesets from index -> Tileset + tilesets: [] + + }; + + /** + * The current canvas left after scroll is applied. + * @property {number} _scrollX + * @private + */ + this._scrollX = 0; + + /** + * The current canvas top after scroll is applied. + * @property {number} _scrollY + * @private + */ + this._scrollY = 0; + + /** + * The position offset of the layer's tiles. + * @property {Phaser.Point} + */ + this.tileOffset = new Phaser.Point(this.layer.offsetX || 0, this.layer.offsetY || 0); + + /** + * Used for caching the tiles / array of tiles. + * @property {Phaser.Tile[]} _results + * @private + */ + this._results = []; + + if (!game.device.canvasBitBltShift) + { + this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas(); + } + + this.fixedToCamera = true; + +}; + +Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer; + +Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; + +/** +* The shared double-copy canvas, created as needed. +* +* @private +* @static +*/ +Phaser.TilemapLayer.sharedCopyCanvas = null; + +/** +* Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. +* +* Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. +* +* @method Phaser.TilemapLayer#ensureSharedCopyCanvas +* @protected +* @static +*/ +Phaser.TilemapLayer.ensureSharedCopyCanvas = function () { + + if (!this.sharedCopyCanvas) + { + this.sharedCopyCanvas = Phaser.CanvasPool.create(this, 2, 2); + } + + return this.sharedCopyCanvas; + +}; + +/** +* Automatically called by World.preUpdate. +* +* @method Phaser.TilemapLayer#preUpdate +*/ +Phaser.TilemapLayer.prototype.preUpdate = function() { + + return this.preUpdateCore(); + +}; + +/** +* Automatically called by World.postUpdate. Handles cache updates. +* +* @method Phaser.TilemapLayer#postUpdate +* @protected +*/ +Phaser.TilemapLayer.prototype.postUpdate = function () { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderCanvas function. +* +* @method Phaser.TilemapLayer#_renderCanvas +* @private +*/ +Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); + +}; + +/** +* Automatically called by the Canvas Renderer. +* Overrides the Sprite._renderWebGL function. +* +* @method Phaser.TilemapLayer#_renderWebGL +* @private +*/ +Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) { + + if (this.fixedToCamera) + { + 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; + } + + this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; + this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; + + this.render(); + + PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); + +}; + +/** +* Destroys this TilemapLayer. +* +* @method Phaser.TilemapLayer#destroy +*/ +Phaser.TilemapLayer.prototype.destroy = function() { + + Phaser.CanvasPool.remove(this); + + Phaser.Component.Destroy.prototype.destroy.call(this); + +}; + +/** +* Resizes the internal canvas and texture frame used by this TilemapLayer. +* +* This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully +* selected times. +* +* Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not +* modified either. You will have to handle both of these things from your game code if required. +* +* @method Phaser.TilemapLayer#resize +* @param {number} width - The new width of the TilemapLayer +* @param {number} height - The new height of the TilemapLayer +*/ +Phaser.TilemapLayer.prototype.resize = function (width, height) { + + this.canvas.width = width; + this.canvas.height = height; + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.crop.width = width; + this.texture.crop.height = height; + + this.texture.baseTexture.width = width; + this.texture.baseTexture.height = height; + + this.texture.baseTexture.dirty(); + this.texture.requiresUpdate = true; + + this.texture._updateUvs(); + + this.dirty = true; + +}; + +/** +* Sets the world size to match the size of this layer. +* +* @method Phaser.TilemapLayer#resizeWorld +* @public +*/ +Phaser.TilemapLayer.prototype.resizeWorld = function () { + + this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y); + +}; + +/** + * Get the X axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getLayerOffsetX + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetX = function () { + + return this.tileOffset.x || ((!this.fixedToCamera) ? this.position.x : 0); + +}; + +/** + * Get the Y axis position offset of this layer's tiles. + * + * @method Phaser.TilemapLayer#getTileOffsetY + * @public + * @return {number} + */ +Phaser.TilemapLayer.prototype.getTileOffsetY = function () { + + return this.tileOffset.y || ((!this.fixedToCamera) ? this.position.y : 0); + +}; + +/** +* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixX +* @private +* @param {number} x - x coordinate in camera space +* @return {number} x coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixX = function (x) { + + if (this.scrollFactorX === 1 || (this.scrollFactorX === 0 && this.position.x === 0)) + { + return x; + } + + // This executes if the scrollFactorX is 0 and the x position of the tilemap is off from standard. + if (this.scrollFactorX === 0 && this.position.x !== 0) + { + return x - this.position.x; + } + + return this._scrollX + (x - (this._scrollX / this.scrollFactorX)); + +}; + +/** +* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixX +* @private +* @param {number} x - x coordinate in scrollFactor-adjusted dimensions +* @return {number} x coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixX = function (x) { + + if (this.scrollFactorX === 1) + { + return x; + } + + return (this._scrollX / this.scrollFactorX) + (x - this._scrollX); + +}; + +/** +* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space. +* +* @method Phaser.TilemapLayer#_fixY +* @private +* @param {number} y - y coordinate in camera space +* @return {number} y coordinate in scrollFactor-adjusted dimensions +*/ +Phaser.TilemapLayer.prototype._fixY = function (y) { + + if (this.scrollFactorY === 1 || (this.scrollFactorY === 0 && this.position.y === 0)) + { + return y; + } + + // This executes if the scrollFactorY is 0 and the y position of the tilemap is off from standard. + if (this.scrollFactorY === 0 && this.position.y !== 0) + { + return y - this.position.y; + } + + return this._scrollY + (y - (this._scrollY / this.scrollFactorY)); + +}; + +/** +* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space. +* +* @method Phaser.TilemapLayer#_unfixY +* @private +* @param {number} y - y coordinate in scrollFactor-adjusted dimensions +* @return {number} y coordinate in camera space +*/ +Phaser.TilemapLayer.prototype._unfixY = function (y) { + + if (this.scrollFactorY === 1) + { + return y; + } + + return (this._scrollY / this.scrollFactorY) + (y - this._scrollY); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileX +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @return {integer} The X map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileX = function (x) { + + // var tileWidth = this.tileWidth * this.scale.x; + return Math.floor(this._fixX(x) / this._mc.tileWidth); + +}; + +/** +* Convert a pixel value to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileY +* @public +* @param {number} y - Y position of the point in target tile (in pixels). +* @return {integer} The Y map location of the tile. +*/ +Phaser.TilemapLayer.prototype.getTileY = function (y) { + + // var tileHeight = this.tileHeight * this.scale.y; + return Math.floor(this._fixY(y) / this._mc.tileHeight); + +}; + +/** +* Convert a pixel coordinate to a tile coordinate. +* +* @method Phaser.TilemapLayer#getTileXY +* @public +* @param {number} x - X position of the point in target tile (in pixels). +* @param {number} y - Y position of the point in target tile (in pixels). +* @param {(Phaser.Point|object)} point - The Point/object to update. +* @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set. +*/ +Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) { + + point.x = this.getTileX(x); + point.y = this.getTileY(y); + + return point; + +}; + +/** +* Gets all tiles that intersect with the given line. +* +* @method Phaser.TilemapLayer#getRayCastTiles +* @public +* @param {Phaser.Line} line - The line used to determine which tiles to return. +* @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`. +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {Phaser.Tile[]} An array of Phaser.Tiles. +*/ +Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) { + + if (!stepRate) { stepRate = this.rayStepRate; } + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + // First get all tiles that touch the bounds of the line + var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace); + + if (tiles.length === 0) + { + return []; + } + + // Now we only want the tiles that intersect with the points on this line + var coords = line.coordinatesOnLine(stepRate); + var results = []; + + for (var i = 0; i < tiles.length; i++) + { + for (var t = 0; t < coords.length; t++) + { + var tile = tiles[i]; + var coord = coords[t]; + if (tile.containsPoint(coord[0], coord[1])) + { + results.push(tile); + break; + } + } + } + + return results; + +}; + +/** +* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. +* +* @method Phaser.TilemapLayer#getTiles +* @public +* @param {number} x - X position of the top left corner (in pixels). +* @param {number} y - Y position of the top left corner (in pixels). +* @param {number} width - Width of the area to get (in pixels). +* @param {number} height - Height of the area to get (in pixels). +* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. +* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. +* @return {array} An array of Tiles. +*/ +Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) { + + // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all) + if (collides === undefined) { collides = false; } + if (interestingFace === undefined) { interestingFace = false; } + + var fetchAll = !(collides || interestingFace); + + // Adjust the x,y coordinates for scrollFactor + x = this._fixX(x); + y = this._fixY(y); + + // Convert the pixel values into tile coordinates + var tx = Math.floor(x / (this._mc.cw * this.scale.x)); + var ty = Math.floor(y / (this._mc.ch * this.scale.y)); + // Don't just use ceil(width/cw) to allow account for x/y diff within cell + var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx; + var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty; + + while (this._results.length) + { + this._results.pop(); + } + + for (var wy = ty; wy < ty + th; wy++) + { + for (var wx = tx; wx < tx + tw; wx++) + { + var row = this.layer.data[wy]; + + if (row && row[wx]) + { + if (fetchAll || row[wx].isInteresting(collides, interestingFace)) + { + this._results.push(row[wx]); + } + } + } + } + + return this._results.slice(); + +}; + +/** +* Returns the appropriate tileset for the index, updating the internal cache as required. +* This should only be called if `tilesets[index]` evaluates to undefined. +* +* @method Phaser.TilemapLayer#resolveTileset +* @private +* @param {integer} Tile index +* @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping. +*/ +Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) { + + var tilesets = this._mc.tilesets; + + // Try for dense array if reasonable + if (tileIndex < 2000) + { + while (tilesets.length < tileIndex) + { + tilesets.push(undefined); + } + } + + var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2]; + + if (setIndex !== null) + { + var tileset = this.map.tilesets[setIndex]; + + if (tileset && tileset.containsTileIndex(tileIndex)) + { + return (tilesets[tileIndex] = tileset); + } + } + + return (tilesets[tileIndex] = null); + +}; + +/** +* The TilemapLayer caches tileset look-ups. +* +* Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. +* +* @method Phaser.TilemapLayer#resetTilesetCache +* @public +*/ +Phaser.TilemapLayer.prototype.resetTilesetCache = function () { + + var tilesets = this._mc.tilesets; + + while (tilesets.length) + { + tilesets.pop(); + } + +}; + +/** + * This method will set the scale of the tilemap as well as update the underlying block data of this layer. + * + * @method Phaser.TilemapLayer#setScale + * @param {number} [xScale=1] - The scale factor along the X-plane + * @param {number} [yScale] - The scale factor along the Y-plane + */ +Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) { + + xScale = xScale || 1; + yScale = yScale || xScale; + + for (var y = 0; y < this.layer.data.length; y++) + { + var row = this.layer.data[y]; + + for (var x = 0; x < row.length; x++) + { + var tile = row[x]; + + tile.width = this.map.tileWidth * xScale; + tile.height = this.map.tileHeight * yScale; + + tile.worldX = tile.x * tile.width; + tile.worldY = tile.y * tile.height; + } + } + + this.scale.setTo(xScale, yScale); + +}; + +/** +* Shifts the contents of the canvas - does extra math so that different browsers agree on the result. +* +* The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in. +* +* @method Phaser.TilemapLayer#shiftCanvas +* @private +* @param {CanvasRenderingContext2D} context - The context to shift +* @param {integer} x +* @param {integer} y +*/ +Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) { + + var canvas = context.canvas; + var copyW = canvas.width - Math.abs(x); + var copyH = canvas.height - Math.abs(y); + + // When x/y non-negative + var dx = 0; + var dy = 0; + var sx = x; + var sy = y; + + if (x < 0) + { + dx = -x; + sx = 0; + } + + if (y < 0) + { + dy = -y; + sy = 0; + } + + var copyCanvas = this.renderSettings.copyCanvas; + + if (copyCanvas) + { + // Use a second copy buffer, without slice support, for Safari .. again. + // Ensure copy canvas is large enough + if (copyCanvas.width < copyW || copyCanvas.height < copyH) + { + copyCanvas.width = copyW; + copyCanvas.height = copyH; + } + + var copyContext = copyCanvas.getContext('2d'); + copyContext.clearRect(0, 0, copyW, copyH); + copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH); + // clear allows default 'source-over' semantics + context.clearRect(sx, sy, copyW, copyH); + context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH); + } + else + { + // Avoids a second copy but flickers in Safari / Safari Mobile + // Ref. https://github.com/photonstorm/phaser/issues/1439 + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH); + context.restore(); + } + +}; + +/** +* Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor. +* This will constrain the tile coordinates based on wrapping but not physical coordinates. +* +* @method Phaser.TilemapLayer#renderRegion +* @private +* @param {integer} scrollX - Render x offset/scroll. +* @param {integer} scrollY - Render y offset/scroll. +* @param {integer} left - Leftmost column to render. +* @param {integer} top - Topmost row to render. +* @param {integer} right - Rightmost column to render. +* @param {integer} bottom - Bottommost row to render. +*/ +Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) { + + var context = this.context; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var tilesets = this._mc.tilesets; + var lastAlpha = NaN; + + if (!this._wrap) + { + if (left <= right) // Only adjust if going to render + { + left = Math.max(0, left); + right = Math.min(width - 1, right); + } + if (top <= bottom) + { + top = Math.max(0, top); + bottom = Math.min(height - 1, bottom); + } + } + + // top-left pixel of top-left cell + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values. + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + // tx/ty - are pixel coordinates where tile is drawn + // x/y - is cell location, normalized [0..width/height) in loop + // xmax/ymax - remaining cells to render on column/row + var tx, ty, x, y, xmax, ymax; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + + if (!tile || tile.index < 0) + { + continue; + } + + var index = tile.index; + + var set = tilesets[index]; + + if (set === undefined) + { + set = this.resolveTileset(index); + } + + // Setting the globalAlpha is "surprisingly expensive" in Chrome (38) + if (tile.alpha !== lastAlpha && !this.debug) + { + context.globalAlpha = tile.alpha; + lastAlpha = tile.alpha; + } + + if (set) + { + if (tile.rotation || tile.flipped) + { + context.save(); + context.translate(tx + tile.centerX, ty + tile.centerY); + context.rotate(tile.rotation); + + if (tile.flipped) + { + context.scale(-1, 1); + } + + set.draw(context, -tile.centerX, -tile.centerY, index); + context.restore(); + } + else + { + set.draw(context, tx, ty, index); + } + } + else if (this.debugSettings.missingImageFill) + { + context.fillStyle = this.debugSettings.missingImageFill; + context.fillRect(tx, ty, tw, th); + } + + if (tile.debug && this.debugSettings.debuggedTileOverfill) + { + context.fillStyle = this.debugSettings.debuggedTileOverfill; + context.fillRect(tx, ty, tw, th); + } + + } + + } + +}; + +/** +* Shifts the canvas and render damaged edge tiles. +* +* @method Phaser.TilemapLayer#renderDeltaScroll +* @private +*/ +Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds. + + // Start in pixels + var left = 0; + var right = -tw; + var top = 0; + var bottom = -th; + + if (shiftX < 0) // layer moving left, damage right + { + left = renderW + shiftX; // shiftX neg. + right = renderW - 1; + } + else if (shiftX > 0) + { + // left -> 0 + right = shiftX; + } + + if (shiftY < 0) // layer moving down, damage top + { + top = renderH + shiftY; // shiftY neg. + bottom = renderH - 1; + } + else if (shiftY > 0) + { + // top -> 0 + bottom = shiftY; + } + + this.shiftCanvas(this.context, shiftX, shiftY); + + // Transform into tile-space + left = Math.floor((left + scrollX) / tw); + right = Math.floor((right + scrollX) / tw); + top = Math.floor((top + scrollY) / th); + bottom = Math.floor((bottom + scrollY) / th); + + if (left <= right) + { + // Clear left or right edge + this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH); + + var trueTop = Math.floor((0 + scrollY) / th); + var trueBottom = Math.floor((renderH - 1 + scrollY) / th); + this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom); + } + + if (top <= bottom) + { + // Clear top or bottom edge + this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th); + + var trueLeft = Math.floor((0 + scrollX) / tw); + var trueRight = Math.floor((renderW - 1 + scrollX) / tw); + this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom); + } + +}; + +/** +* Clear and render the entire canvas. +* +* @method Phaser.TilemapLayer#renderFull +* @private +*/ +Phaser.TilemapLayer.prototype.renderFull = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + this.context.clearRect(0, 0, renderW, renderH); + + this.renderRegion(scrollX, scrollY, left, top, right, bottom); + +}; + +/** +* Renders the tiles to the layer canvas and pushes to the display. +* +* @method Phaser.TilemapLayer#render +* @protected +*/ +Phaser.TilemapLayer.prototype.render = function () { + + var redrawAll = false; + + if (!this.visible) + { + return; + } + + if (this.dirty || this.layer.dirty) + { + this.layer.dirty = false; + redrawAll = true; + } + + var renderWidth = this.canvas.width; // Use Sprite.width/height? + var renderHeight = this.canvas.height; + + // Scrolling bias; whole pixels only + var scrollX = this._scrollX | 0; + var scrollY = this._scrollY | 0; + + var mc = this._mc; + var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down + var shiftY = mc.scrollY - scrollY; + + if (!redrawAll && + shiftX === 0 && shiftY === 0 && + mc.renderWidth === renderWidth && mc.renderHeight === renderHeight) + { + // No reason to redraw map, looking at same thing and not invalidated. + return; + } + + this.context.save(); + + mc.scrollX = scrollX; + mc.scrollY = scrollY; + + if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight) + { + // Could support automatic canvas resizing + mc.renderWidth = renderWidth; + mc.renderHeight = renderHeight; + } + + if (this.debug) + { + this.context.globalAlpha = this.debugSettings.debugAlpha; + + if (this.debugSettings.forceFullRedraw) + { + redrawAll = true; + } + } + + if (!redrawAll && + this.renderSettings.enableScrollDelta && + (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight)) + { + this.renderDeltaScroll(shiftX, shiftY); + } + else + { + // Too much change or otherwise requires full render + this.renderFull(); + } + + if (this.debug) + { + this.context.globalAlpha = 1; + this.renderDebug(); + } + + this.texture.baseTexture.dirty(); + + this.dirty = false; + + this.context.restore(); + + return true; + +}; + +/** +* Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true. +* +* See `debugSettings` for assorted configuration options. +* +* @method Phaser.TilemapLayer#renderDebug +* @private +*/ +Phaser.TilemapLayer.prototype.renderDebug = function () { + + var scrollX = this._mc.scrollX; + var scrollY = this._mc.scrollY; + + var context = this.context; + var renderW = this.canvas.width; + var renderH = this.canvas.height; + + var width = this.layer.width; + var height = this.layer.height; + var tw = this._mc.tileWidth; + var th = this._mc.tileHeight; + + var left = Math.floor(scrollX / tw); + var right = Math.floor((renderW - 1 + scrollX) / tw); + var top = Math.floor(scrollY / th); + var bottom = Math.floor((renderH - 1 + scrollY) / th); + + var baseX = (left * tw) - scrollX; + var baseY = (top * th) - scrollY; + + var normStartX = (left + ((1 << 20) * width)) % width; + var normStartY = (top + ((1 << 20) * height)) % height; + + var tx, ty, x, y, xmax, ymax; + + context.strokeStyle = this.debugSettings.facingEdgeStroke; + + for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) + { + if (y >= height) + { + y -= height; + } + + var row = this.layer.data[y]; + + for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw) + { + if (x >= width) + { + x -= width; + } + + var tile = row[x]; + if (!tile || tile.index < 0 || !tile.collides) + { + continue; + } + + if (this.debugSettings.collidingTileOverfill) + { + context.fillStyle = this.debugSettings.collidingTileOverfill; + context.fillRect(tx, ty, this._mc.cw, this._mc.ch); + } + + if (this.debugSettings.facingEdgeStroke) + { + context.beginPath(); + + if (tile.faceTop) + { + context.moveTo(tx, ty); + context.lineTo(tx + this._mc.cw, ty); + } + + if (tile.faceBottom) + { + context.moveTo(tx, ty + this._mc.ch); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + if (tile.faceLeft) + { + context.moveTo(tx, ty); + context.lineTo(tx, ty + this._mc.ch); + } + + if (tile.faceRight) + { + context.moveTo(tx + this._mc.cw, ty); + context.lineTo(tx + this._mc.cw, ty + this._mc.ch); + } + + context.closePath(); + + context.stroke(); + } + + } + + } + +}; + +/** +* Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size. +* +* @property {boolean} wrap +* @memberof Phaser.TilemapLayer +* @public +* @default false +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", { + + get: function () { + return this._wrap; + }, + + set: function (value) { + this._wrap = value; + this.dirty = true; + } + +}); + +/** +* Scrolls the map horizontally or returns the current x position. +* +* @property {number} scrollX +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", { + + get: function () { + return this._scrollX; + }, + + set: function (value) { + this._scrollX = value; + } + +}); + +/** +* Scrolls the map vertically or returns the current y position. +* +* @property {number} scrollY +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", { + + get: function () { + return this._scrollY; + }, + + set: function (value) { + this._scrollY = value; + } + +}); + +/** +* The width of the collision tiles (in pixels). +* +* @property {integer} collisionWidth +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", { + + get: function () { + return this._mc.cw; + }, + + set: function (value) { + this._mc.cw = value | 0; + this.dirty = true; + } + +}); + +/** +* The height of the collision tiles (in pixels). +* +* @property {integer} collisionHeight +* @memberof Phaser.TilemapLayer +* @public +*/ +Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", { + + get: function () { + return this._mc.ch; + }, + + set: function (value) { + this._mc.ch = value | 0; + this.dirty = true; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. +* +* @class Phaser.TilemapParser +* @static +*/ +Phaser.TilemapParser = { + + /** + * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or + * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type + * depends how this should be configured. If you've a large sparsely populated map and the tile + * data doesn't need to change then setting this value to `true` will help with memory consumption. + * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes + * during the game) then leave the default value set. + * + * @constant + * @type {boolean} + */ + INSERT_NULL: false, + + /** + * Parse tilemap data from the cache and creates data for a Tilemap object. + * + * @method Phaser.TilemapParser.parse + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {string} key - The key of the tilemap in the Cache. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {object} The parsed map object. + */ + parse: function (game, key, tileWidth, tileHeight, width, height) { + + if (tileWidth === undefined) { tileWidth = 32; } + if (tileHeight === undefined) { tileHeight = 32; } + if (width === undefined) { width = 10; } + if (height === undefined) { height = 10; } + + if (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); + } + + }, + + /** + * Parses a CSV file into valid map data. + * + * @method Phaser.TilemapParser.parseCSV + * @param {string} key - The name you want to give the map data. + * @param {string} data - The CSV file data. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @return {object} Generated map data. + */ + parseCSV: function (key, data, tileWidth, tileHeight) { + + var map = this.getEmptyData(); + + // Trim any rogue whitespace from the data + data = data.trim(); + + var output = []; + var rows = data.split("\n"); + var height = rows.length; + var width = 0; + + for (var y = 0; y < rows.length; y++) + { + output[y] = []; + + var column = rows[y].split(","); + + for (var x = 0; x < column.length; x++) + { + output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight); + } + + if (width === 0) + { + width = column.length; + } + } + + map.format = Phaser.Tilemap.CSV; + map.name = key; + map.width = width; + map.height = height; + map.tileWidth = tileWidth; + map.tileHeight = tileHeight; + map.widthInPixels = width * tileWidth; + map.heightInPixels = height * tileHeight; + + map.layers[0].width = width; + map.layers[0].height = height; + map.layers[0].widthInPixels = map.widthInPixels; + map.layers[0].heightInPixels = map.heightInPixels; + map.layers[0].data = output; + + return map; + + }, + + /** + * Returns an empty map data object. + * + * @method Phaser.TilemapParser.getEmptyData + * @return {object} Generated map data. + */ + getEmptyData: function (tileWidth, tileHeight, width, height) { + + return { + width: (width !== undefined && width !== null) ? width : 0, + height: (height !== undefined && height !== null) ? height : 0, + tileWidth: (tileWidth !== undefined && tileWidth !== null) ? tileWidth : 0, + tileHeight: (tileHeight !== undefined && tileHeight !== null) ? tileHeight : 0, + orientation: 'orthogonal', + version: '1', + properties: {}, + widthInPixels: 0, + heightInPixels: 0, + layers: [ + { + name: 'layer', + x: 0, + y: 0, + width: 0, + height: 0, + widthInPixels: 0, + heightInPixels: 0, + alpha: 1, + visible: true, + properties: {}, + indexes: [], + callbacks: [], + bodies: [], + data: [] + } + ], + images: [], + objects: {}, + collision: {}, + tilesets: [], + tiles: [] + }; + + }, + + _slice: function(obj, fields) { + var sliced = {}; + + for (var k in fields) + { + var key = fields[k]; + + if (typeof obj[key] !== 'undefined') + { + sliced[key] = obj[key]; + } + } + + return sliced; + }, + + /** + * Parses an object group in Tiled JSON files. Object groups can be found in both layers and tilesets. Called internally in parseTiledJSON. + * @method Phaser.TilemapParser.parseObjectGroup + * @param {object} objectGroup - A JSON object group. + * @param {object} objectsCollection - An object into which new array of Tiled map objects will be added. + * @param {object} collisionCollection - An object into which new array of collision objects will be added. Currently only polylines are added. + * @param {string} [nameKey=objectGroup.name] - Key under which to store objects in collisions in objectsCollection and collisionCollection + * @param {object} [relativePosition={x: 0, y: 0}] - Coordinates the object group's position is relative to. + * @return {object} A object literal containing the objectsCollection and collisionCollection + */ + parseObjectGroup: function(objectGroup, objectsCollection, collisionCollection, nameKey, relativePosition) { + + var nameKey = nameKey || objectGroup.name; + var relativePosition = relativePosition || {x: 0, y: 0}; + var slice = this._slice; + + if (!nameKey) + { + console.warn('No name found for objectGroup', objectGroup); + } + + if (relativePosition.x === undefined || relativePosition.y === undefined) + { + console.warn('Malformed xy properties in relativePosition', relativePosition); + } + + objectsCollection[nameKey] = objectsCollection[nameKey] || []; + collisionCollection[nameKey] = collisionCollection[nameKey] || []; + + for (var v = 0, len = objectGroup.objects.length; v < len; v++) + { + var o = objectGroup.objects[v]; + + // Object Tiles + if (o.gid) + { + var object = { + gid: o.gid, + name: o.name, + type: o.type || '', + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + objectsCollection[nameKey].push(object); + } + else if (o.polyline) + { + var object = { + name: o.name, + type: o.type, + x: o.x + relativePosition.x, + y: o.y + relativePosition.y, + width: o.width, + height: o.height, + visible: o.visible, + properties: o.properties + }; + + if (o.rotation) + { + object.rotation = o.rotation; + } + + object.polyline = []; + + // Parse the polyline into an array + for (var p = 0; p < o.polyline.length; p++) + { + object.polyline.push([o.polyline[p].x, o.polyline[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // polygon + else if (o.polygon) + { + var object = slice(o, ['name', 'type', 'x', 'y', 'visible', 'rotation', 'properties']); + + object.x += relativePosition.x; + object.y += relativePosition.y; + + // Parse the polygon into an array + object.polygon = []; + + for (var p = 0; p < o.polygon.length; p++) + { + object.polygon.push([o.polygon[p].x, o.polygon[p].y]); + } + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // ellipse + else if (o.ellipse) + { + var object = slice(o, ['name', 'type', 'ellipse', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + // otherwise it's a rectangle + else + { + var object = slice(o, ['name', 'type', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']); + object.x += relativePosition.x; + object.y += relativePosition.y; + + object.rectangle = true; + collisionCollection[nameKey].push(object); + objectsCollection[nameKey].push(object); + } + } + + return { + objectsCollection: objectsCollection, + collisionCollection: collisionCollection + }; + }, + + /** + * Parses a Tiled JSON file into valid map data. + * @method Phaser.TilemapParser.parseTiledJSON + * @param {object} json - The JSON map data. + * @return {object} Generated and parsed map data. + */ + parseTiledJSON: function (json) { + + if (json.orientation !== 'orthogonal') + { + console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser'); + return null; + } + + // Map data will consist of: layers, objects, images, tilesets, sizes + var map = { + width: json.width, + height: json.height, + tileWidth: json.tilewidth, + tileHeight: json.tileheight, + orientation: json.orientation, + format: Phaser.Tilemap.TILED_JSON, + version: json.version, + properties: json.properties, + widthInPixels: json.width * json.tilewidth, + heightInPixels: json.height * json.tileheight + }; + + // Tile Layers + var layers = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'tilelayer') + { + continue; + } + + var curl = json.layers[i]; + + // Base64 decode data if necessary + // NOTE: uncompressed base64 only. + + if (!curl.compression && curl.encoding && curl.encoding === 'base64') + { + var binaryString = window.atob(curl.data); + var len = binaryString.length; + var bytes = new Array(len); + + // Interpret binaryString as an array of bytes representing + // little-endian encoded uint32 values. + for (var j = 0; j < len; j+=4) + { + bytes[j / 4] = ( + binaryString.charCodeAt(j) | + binaryString.charCodeAt(j + 1) << 8 | + binaryString.charCodeAt(j + 2) << 16 | + binaryString.charCodeAt(j + 3) << 24 + ) >>> 0; + } + + curl.data = bytes; + + delete curl.encoding; + } + else if (curl.compression) + { + console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\''); + continue; + } + + var layer = { + + name: curl.name, + x: curl.x, + y: curl.y, + width: curl.width, + height: curl.height, + widthInPixels: curl.width * json.tilewidth, + heightInPixels: curl.height * json.tileheight, + alpha: curl.opacity, + offsetX: curl.offsetx, + offsetY: curl.offsety, + visible: curl.visible, + properties: {}, + indexes: [], + callbacks: [], + bodies: [] + + }; + + if (curl.properties) + { + layer.properties = curl.properties; + } + + var x = 0; + var row = []; + var output = []; + var rotation, flipped, flippedVal, gid; + + // Loop through the data field in the JSON. + + // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV) + // If the map contains multiple tilesets then the indexes are relative to that which the set starts from. + // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset. + + for (var t = 0, len = curl.data.length; t < len; t++) + { + rotation = 0; + flipped = false; + gid = curl.data[t]; + flippedVal = 0; + + // If true the current tile is flipped or rotated (Tiled TMX format) + if (gid > 0x20000000) + { + // FlippedX + if (gid > 0x80000000) + { + gid -= 0x80000000; + flippedVal += 4; + } + + // FlippedY + if (gid > 0x40000000) + { + gid -= 0x40000000; + flippedVal += 2; + } + + // FlippedAD (anti-diagonal = top-right is swapped with bottom-left corners) + if (gid > 0x20000000) + { + gid -= 0x20000000; + flippedVal += 1; + } + + switch (flippedVal) + { + case 5: + rotation = Math.PI / 2; + break; + + case 6: + rotation = Math.PI; + break; + + case 3: + rotation = 3 * Math.PI / 2; + break; + + case 4: + rotation = 0; + flipped = true; + break; + + case 7: + rotation = Math.PI / 2; + flipped = true; + break; + + case 2: + rotation = Math.PI; + flipped = true; + break; + + case 1: + rotation = 3 * Math.PI / 2; + flipped = true; + break; + } + } + + // index, x, y, width, height + if (gid > 0) + { + var tile = new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight); + + tile.rotation = rotation; + tile.flipped = flipped; + + if (flippedVal !== 0) + { + // The WebGL renderer uses this to flip UV coordinates before drawing + tile.flippedVal = flippedVal; + } + + row.push(tile); + } + else + { + if (Phaser.TilemapParser.INSERT_NULL) + { + row.push(null); + } + else + { + row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight)); + } + } + + x++; + + if (x === curl.width) + { + output.push(row); + x = 0; + row = []; + } + } + + layer.data = output; + + layers.push(layer); + } + + map.layers = layers; + + // Images + var images = []; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'imagelayer') + { + continue; + } + + var curi = json.layers[i]; + + var image = { + + name: curi.name, + image: curi.image, + x: curi.x, + y: curi.y, + alpha: curi.opacity, + visible: curi.visible, + properties: {} + + }; + + if (curi.properties) + { + image.properties = curi.properties; + } + + images.push(image); + + } + + map.images = images; + + // Tilesets & Image Collections + var tilesets = []; + var tilesetGroupObjects = {}; + var imagecollections = []; + var lastSet = null; + + for (var i = 0; i < json.tilesets.length; i++) + { + // name, firstgid, width, height, margin, spacing, properties + var set = json.tilesets[i]; + + if (set.source) + { + console.warn('Phaser.TilemapParser - Phaser can\'t load external tilesets (%s). Use the Embed Tileset button and then export the map again.', set.source); + } + else if (set.image) + { + var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + if (set.tileproperties) + { + newSet.tileProperties = set.tileproperties; + } + + // For a normal sliced tileset the row/count/size information is computed when updated. + // This is done (again) after the image is set. + newSet.updateTileData(set.imagewidth, set.imageheight); + + tilesets.push(newSet); + } + else if (set.tiles) + { + var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); + + for (var ti in set.tiles) + { + var image = set.tiles[ti].image; + var gid = set.firstgid + parseInt(ti, 10); + newCollection.addImage(gid, image); + } + + imagecollections.push(newCollection); + } + else + { + throw new Error('Tileset ' + set.name + ' has no `image` or `tiles` property.'); + } + + // build a temporary object for objectgroups found in the tileset's tiles + for (var ti in set.tiles) + { + var objectGroup = set.tiles[ti].objectgroup; + + if (!objectGroup) + { + continue; + } + + tilesetGroupObjects[parseInt(ti, 10) + set.firstgid] = objectGroup; + } + + // We've got a new Tileset, so set the lastgid into the previous one + if (lastSet) + { + lastSet.lastgid = set.firstgid - 1; + } + + lastSet = set; + } + + if (tilesets.length === 0 && imagecollections.length === 0) + { + throw new Error('This tilemap has no tilesets.'); + } + + map.tilesets = tilesets; + map.imagecollections = imagecollections; + + // Objects & Collision Data (polylines, etc) + var objects = {}; + var collision = {}; + + for (var i = 0; i < json.layers.length; i++) + { + if (json.layers[i].type !== 'objectgroup') + { + continue; + } + + var objectGroup = json.layers[i]; + this.parseObjectGroup(objectGroup, objects, collision); + } + + map.objects = objects; + map.collision = collision; + + map.tiles = []; + + // Finally lets build our super tileset index + for (var i = 0; i < map.tilesets.length; i++) + { + var set = map.tilesets[i]; + + var x = set.tileMargin; + var y = set.tileMargin; + + var count = 0; + var countX = 0; + var countY = 0; + + for (var t = set.firstgid; t < set.firstgid + set.total; t++) + { + // Can add extra properties here as needed + map.tiles[t] = [x, y, i]; + + x += set.tileWidth + set.tileSpacing; + + count++; + + if (count === set.total) + { + break; + } + + countX++; + + if (countX === set.columns) + { + x = set.tileMargin; + y += set.tileHeight + set.tileSpacing; + + countX = 0; + countY++; + + if (countY === set.rows) + { + break; + } + } + } + + } + + // assign tile properties + + var layer; + var tile; + var sid; + var set; + + // go through each of the map data layers + for (var i = 0; i < map.layers.length; i++) + { + layer = map.layers[i]; + collision[layer.name] = []; + set = null; + + // rows of tiles + for (var j = 0; j < layer.data.length; j++) + { + row = layer.data[j]; + + // individual tiles + for (var k = 0; k < row.length; k++) + { + tile = row[k]; + + if (tile === null || tile.index < 0) + { + continue; + } + + // find the relevant tileset + + sid = map.tiles[tile.index][2]; + set = map.tilesets[sid]; + + + // if that tile type has any properties, add them to the tile object + + if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) + { + tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties); + } + + var objectGroup = tilesetGroupObjects[tile.index]; + if (objectGroup) + { + // build collisions and objects for objectgroups found in the tileset's tiles + this.parseObjectGroup( + objectGroup, + map.objects, + map.collision, + tile.layer.name, + { + x: tile.worldX + objectGroup.x, + y: tile.worldY + objectGroup.y + }); + } + + } + } + } + + return map; + + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Tile set is a combination of an image containing the tiles and collision data per tile. +* +* Tilesets are normally created automatically when Tiled data is loaded. +* +* @class Phaser.Tileset +* @constructor +* @param {string} name - The name of the tileset in the map data. +* @param {integer} firstgid - The first tile index this tileset contains. +* @param {integer} [width=32] - Width of each tile (in pixels). +* @param {integer} [height=32] - Height of each tile (in pixels). +* @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels). +* @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels). +* @param {object} [properties={}] - Custom Tileset properties. +*/ +Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) { + + if (width === undefined || width <= 0) { width = 32; } + if (height === undefined || height <= 0) { height = 32; } + if (margin === undefined) { margin = 0; } + if (spacing === undefined) { spacing = 0; } + + /** + * The name of the Tileset. + * @property {string} name + */ + this.name = name; + + /** + * The Tiled firstgid value. + * This is the starting index of the first tile index this Tileset contains. + * @property {integer} firstgid + */ + this.firstgid = firstgid | 0; + + /** + * The width of each tile (in pixels). + * @property {integer} tileWidth + * @readonly + */ + this.tileWidth = width | 0; + + /** + * The height of each tile (in pixels). + * @property {integer} tileHeight + * @readonly + */ + this.tileHeight = height | 0; + + /** + * The margin around the tiles in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileMarge + * @readonly + */ + // Modified internally + this.tileMargin = margin | 0; + + /** + * The spacing between each tile in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileSpacing + * @readonly + */ + this.tileSpacing = spacing | 0; + + /** + * Tileset-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ + this.properties = properties || {}; + + /** + * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set. + * @property {?object} image + * @readonly + */ + // Modified internally + this.image = null; + + /** + * The number of tile rows in the the tileset. + * @property {integer} + * @readonly + */ + // Modified internally + this.rows = 0; + + /** + * The number of tile columns in the tileset. + * @property {integer} columns + * @readonly + */ + // Modified internally + this.columns = 0; + + /** + * The total number of tiles in the tileset. + * @property {integer} total + * @readonly + */ + // Modified internally + this.total = 0; + + /** + * The look-up table to specific tile image offsets. + * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1. + * @property {integer[]} drawCoords + * @private + */ + this.drawCoords = []; + +}; + +Phaser.Tileset.prototype = { + + /** + * Draws a tile from this Tileset at the given coordinates on the context. + * + * @method Phaser.Tileset#draw + * @public + * @param {CanvasRenderingContext2D} context - The context to draw the tile onto. + * @param {number} x - The x coordinate to draw to. + * @param {number} y - The y coordinate to draw to. + * @param {integer} index - The index of the tile within the set to draw. + */ + draw: function (context, x, y, index) { + + // Correct the tile index for the set and bias for interlacing + var coordIndex = (index - this.firstgid) << 1; + + if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length) + { + context.drawImage( + this.image, + this.drawCoords[coordIndex], + this.drawCoords[coordIndex + 1], + this.tileWidth, + this.tileHeight, + x, + y, + this.tileWidth, + this.tileHeight + ); + } + + }, + + /** + * Returns true if and only if this tileset contains the given tile index. + * + * @method Phaser.Tileset#containsTileIndex + * @public + * @param {number} tileIndex + * @return {boolean} True if this tileset contains the given index. + */ + containsTileIndex: function (tileIndex) { + + return ( + tileIndex >= this.firstgid && + tileIndex < (this.firstgid + this.total) + ); + + }, + + /** + * Set the image associated with this Tileset and update the tile data. + * + * @method Phaser.Tileset#setImage + * @public + * @param {Image} image - The image that contains the tiles. + */ + setImage: function (image) { + + this.image = image; + this.updateTileData(image.width, image.height); + + }, + + /** + * Sets tile spacing and margins. + * + * @method Phaser.Tileset#setSpacing + * @public + * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels). + */ + setSpacing: function (margin, spacing) { + + this.tileMargin = margin | 0; + this.tileSpacing = spacing | 0; + + if (this.image) + { + this.updateTileData(this.image.width, this.image.height); + } + + }, + + /** + * Updates tile coordinates and tileset data. + * + * @method Phaser.Tileset#updateTileData + * @private + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + */ + updateTileData: function (imageWidth, imageHeight) { + + // May be fractional values + var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); + var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); + + if (rowCount % 1 !== 0 || colCount % 1 !== 0) + { + console.warn( + "Phaser.Tileset - '%s' image tile area (%s x %s) is not a whole multiple of tile size (%s x %s + %s + %s)", + this.name, imageWidth, imageHeight, this.tileWidth, this.tileHeight, this.tileMargin, this.tileSpacing + ); + } + + // In Tiled a tileset image that is not an even multiple of the tile dimensions + // is truncated - hence the floor when calculating the rows/columns. + rowCount = Math.floor(rowCount); + colCount = Math.floor(colCount); + + if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount)) + { + console.warn( + "Phaser.Tileset - Tile layout from image '%s' (%s rows by %s columns) differs from tileset '%s' (%s rows by %s columns)", + this.image.name, colCount, rowCount, this.name, this.columns, this.rows + ); + } + + this.rows = rowCount; + this.columns = colCount; + this.total = rowCount * colCount; + + this.drawCoords.length = 0; + + var tx = this.tileMargin; + var ty = this.tileMargin; + + for (var y = 0; y < this.rows; y++) + { + for (var x = 0; x < this.columns; x++) + { + this.drawCoords.push(tx); + this.drawCoords.push(ty); + tx += this.tileWidth + this.tileSpacing; + } + + tx = this.tileMargin; + ty += this.tileHeight + this.tileSpacing; + } + + } + +}; + +Phaser.Tileset.prototype.constructor = Phaser.Tileset; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. +* +* @class Phaser.Particle +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Particle = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + /** + * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData. + * @protected + */ + this.autoScale = false; + + /** + * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.scaleData = null; + + /** + * @property {number} _s - Internal cache var for tracking auto scale. + * @private + */ + this._s = 0; + + /** + * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. + * @protected + */ + this.autoAlpha = false; + + /** + * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle. + * @protected + */ + this.alphaData = null; + + /** + * @property {number} _a - Internal cache var for tracking auto alpha. + * @private + */ + this._a = 0; + +}; + +Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Particle.prototype.constructor = Phaser.Particle; + +/** +* Updates the Particle scale or alpha if autoScale and autoAlpha are set. +* +* @method Phaser.Particle#update +* @memberof 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; + } + } + +}; + +/** +* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. +* +* @method Phaser.Particle#onEmit +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.onEmit = function() { +}; + +/** +* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. +* +* @method Phaser.Particle#setAlphaData +* @memberof Phaser.Particle +*/ +Phaser.Particle.prototype.setAlphaData = function(data) { + + this.alphaData = data; + this._a = data.length - 1; + this.alpha = this.alphaData[this._a].v; + this.autoAlpha = true; + +}; + +/** +* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. +* +* @method Phaser.Particle#setScaleData +* @memberof Phaser.Particle +*/ +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; + +}; + +/** +* Resets the Particle. This places the Particle at the given x/y world coordinates and then +* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. +* If the Particle has a physics body that too is reset. +* +* @method Phaser.Particle#reset +* @memberof Phaser.Particle +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {number} [health=1] - The health to give the Particle. +* @return {Phaser.Particle} This instance. +*/ +Phaser.Particle.prototype.reset = function(x, y, health) { + + Phaser.Component.Reset.prototype.reset.call(this, x, y, health); + + this.alpha = 1; + this.scale.set(1); + + this.autoScale = false; + this.autoAlpha = false; + + return this; + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Phaser.Particles tracks any Emitters attached to it. +* +* @class Phaser.Particles +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +*/ +Phaser.Particles = function (game) { + + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + + /** + * @property {object} emitters - Internal emitters store. + */ + this.emitters = {}; + + /** + * @property {number} ID - + * @default + */ + this.ID = 0; + +}; + +Phaser.Particles.prototype = { + + /** + * Adds a new Particle Emitter to the Particle Manager. + * @method Phaser.Particles#add + * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. + * @return {Phaser.Emitter} The emitter that was added. + */ + add: function (emitter) { + this.emitters[emitter.id] = emitter; + return emitter; + }, + + /** + * Removes an existing Particle Emitter from the Particle Manager. + * @method Phaser.Particles#remove + * @param {Phaser.Emitter} emitter - The emitter to remove. + */ + remove: function (emitter) { + delete this.emitters[emitter.id]; + } + +}; + +Phaser.Particles.prototype.constructor = Phaser.Particles; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Arcade Particles is a Particle System integrated with Arcade Physics. +* +* @class Phaser.Particles.Arcade +*/ +Phaser.Particles.Arcade = {}; +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Emitter is a lightweight particle emitter that uses Arcade Physics. +* It can be used for one-time explosions or for continuous effects like rain and fire. +* All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. +* +* @class Phaser.Particles.Arcade.Emitter +* @constructor +* @extends Phaser.Group +* @param {Phaser.Game} game - Current game instance. +* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. +* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. +* @param {number} [maxParticles=50] - The total number of particles in this emitter. +*/ +Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { + + /** + * @property {number} maxParticles - The total number of particles in this emitter. + * @default + */ + this.maxParticles = maxParticles || 50; + + Phaser.Group.call(this, game); + + /** + * @property {number} _id - Internal ID for this emitter -- only used by the Particle System in most cases + * @private + */ + this._id = this.game.particles.ID++; + + /** + * @property {string} name - A handy string name for this emitter. Can be set to anything. + */ + this.name = 'emitter' + this.id; + + /** + * @property {number} type - Internal Phaser Type value. + * @protected + */ + this.type = Phaser.EMITTER; + + /** + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ + this.physicsType = Phaser.GROUP; + + /** + * @property {Phaser.Rectangle} area - The {@link #setSize size} of the emitter's emit area. The **actual** emit area is a rectangle of this size centered on (emitX, emitY): `{x: this.left, y: this.top, width: this.area.width, height: this.area.height}`. Particles are generated at a random position within this area. + * @default + */ + this.area = new Phaser.Rectangle(x, y, 1, 1); + + /** + * @property {?number} minAngle - The minimum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #maxAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.minAngle = null; + + /** + * @property {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. When set to a non-null value (with {@link #minAngle}), {@link #minSpeed} and {@link #maxSpeed} are used and {@link #minParticleSpeed} and {@link #maxParticleSpeed} are ignored. + * @default + */ + this.maxAngle = null; + + /** + * @property {number} minSpeed - The minimum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.minSpeed = 0; + + /** + * @property {number} maxSpeed - The maximum initial speed of particles released within {@link #minAngle} and {@link #maxAngle}. + * @default + */ + this.maxSpeed = 100; + + /** + * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle. + * @default + */ + this.minParticleSpeed = new Phaser.Point(-100, -100); + + /** + * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle. + * @default + */ + this.maxParticleSpeed = new Phaser.Point(100, 100); + + /** + * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. + * @default + */ + this.minParticleScale = 1; + + /** + * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. + * @default + */ + this.maxParticleScale = 1; + + /** + * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0. + */ + this.scaleData = null; + + /** + * @property {number} minRotation - The minimum possible angular velocity of a particle. + * @default + */ + this.minRotation = -360; + + /** + * @property {number} maxRotation - The maximum possible angular velocity of a particle. + * @default + */ + this.maxRotation = 360; + + /** + * @property {number} minParticleAlpha - The minimum possible alpha value of a particle. + * @default + */ + this.minParticleAlpha = 1; + + /** + * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle. + * @default + */ + this.maxParticleAlpha = 1; + + /** + * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0. + */ + this.alphaData = null; + + /** + * @property {function} particleClass - For emitting your own particle class types. They must extend Phaser.Particle. + * @default + */ + this.particleClass = Phaser.Particle; + + /** + * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter. + */ + this.particleDrag = new Phaser.Point(); + + /** + * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating. + * @default + */ + this.angularDrag = 0; + + /** + * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false). + * @default + */ + this.frequency = 100; + + /** + * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. + * @default + */ + this.lifespan = 2000; + + /** + * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. + */ + this.bounce = new Phaser.Point(); + + /** + * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. + * @default + */ + this.on = false; + + /** + * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) + * @default + */ + this.particleAnchor = new Phaser.Point(0.5, 0.5); + + /** + * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) + * @default + */ + this.blendMode = Phaser.blendModes.NORMAL; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitX + */ + this.emitX = x; + + /** + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitY + */ + this.emitY = y; + + /** + * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. + */ + this.autoScale = false; + + /** + * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. + */ + this.autoAlpha = false; + + /** + * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. + * @default + */ + this.particleBringToTop = false; + + /** + * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. + * @default + */ + this.particleSendToBack = false; + + /** + * @property {object} counts - Records emitter activity. + * @property {number} counts.emitted - How many particles were emitted during the last update. + * @property {number} counts.failed - How many particles could not be emitted during the last update (because no particles were available). + * @property {number} counts.totalEmitted - How many particles have been emitted. + * @property {number} counts.totalFailed - How many particles could not be emitted when they were due (because no particles were available). + */ + this.counts = { + emitted: 0, + failed: 0, + totalEmitted: 0, + totalFailed: 0 + }; + + /** + * @property {Phaser.Point} _gravity - Internal gravity value. + * @private + */ + this._gravity = new Phaser.Point(0, 100); + + /** + * @property {Phaser.Point} _minParticleScale - Internal particle scale var. + * @private + */ + this._minParticleScale = new Phaser.Point(1, 1); + + /** + * @property {Phaser.Point} _maxParticleScale - Internal particle scale var. + * @private + */ + this._maxParticleScale = new Phaser.Point(1, 1); + + /** + * @property {number} _total - Internal helper for deciding how many particles to launch (via {@link #start}). + * @private + */ + this._total = 0; + + /** + * @property {number} _timer - Internal helper for deciding when to launch particles or kill them. + * @private + */ + this._timer = 0; + + /** + * @property {number} _counter - Internal counter for figuring out how many particles to launch. + * @private + */ + this._counter = 0; + + /** + * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update. + * @private + */ + this._flowQuantity = 0; + + /** + * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total (via {@link #flow}). + * @private + */ + this._flowTotal = 0; + + /** + * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time). + * @private + */ + this._explode = true; + + /** + * @property {any} _frames - Internal helper for the particle frame. + * @private + */ + this._frames = null; + +}; + +Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); +Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter; + +/** +* Called automatically by the game loop, decides when to launch particles and when to "die". +* +* @method Phaser.Particles.Arcade.Emitter#update +*/ +Phaser.Particles.Arcade.Emitter.prototype.update = function () { + + this.counts.emitted = 0; + this.counts.failed = 0; + + if (this.on && this.game.time.time >= this._timer) + { + this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion; + + if (this._flowTotal !== 0) + { + if (this._flowQuantity > 0) + { + for (var i = 0; i < this._flowQuantity; i++) + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + break; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._flowTotal !== -1 && this._counter >= this._flowTotal) + { + this.on = false; + } + } + } + } + else + { + if (this.emitParticle()) + { + this._counter++; + + if (this._total > 0 && this._counter >= this._total) + { + this.on = false; + } + } + } + + } + + var i = this.children.length; + + while (i--) + { + if (this.children[i].exists) + { + this.children[i].update(); + } + } + +}; + +/** +* This function generates a new set of particles for use by this emitter. +* The particles are stored internally waiting to be emitted via Emitter.start. +* +* @method Phaser.Particles.Arcade.Emitter#makeParticles +* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. +* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random. +* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. +* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. +* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. +* @param {object} [particleArguments=null] - Custom arguments to pass to your particle class +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds, particleArguments) { + + if (frames === undefined) { frames = 0; } + if (quantity === undefined) { quantity = this.maxParticles; } + if (collide === undefined) { collide = false; } + if (collideWorldBounds === undefined) { collideWorldBounds = false; } + if (particleArguments === undefined) { particleArguments = null; } + + var particle; + var i = 0; + var rndKey = keys; + var rndFrame = frames; + this._frames = frames; + + if (quantity > this.maxParticles) + { + this.maxParticles = quantity; + } + + while (i < quantity) + { + if (Array.isArray(keys)) + { + rndKey = this.game.rnd.pick(keys); + } + + if (Array.isArray(frames)) + { + rndFrame = this.game.rnd.pick(frames); + } + + particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame, particleArguments); + + this.game.physics.arcade.enable(particle, false); + + particle.body.checkCollision.none = !collide; + particle.body.collideWorldBounds = collideWorldBounds; + particle.body.skipQuadTree = true; + + particle.exists = false; + particle.visible = false; + particle.anchor.copyFrom(this.particleAnchor); + + this.add(particle); + + i++; + } + + return this; + +}; + +/** +* Call this function to turn off all the particles and the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#kill +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.kill = function () { + + this.on = false; + this.alive = false; + this.exists = false; + + return this; + +}; + +/** +* Handy for bringing game objects "back to life". Just sets alive and exists back to true. +* +* @method Phaser.Particles.Arcade.Emitter#revive +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.revive = function () { + + this.alive = true; + this.exists = true; + + return this; + +}; + +/** +* Call this function to emit the given quantity of particles at all once (an explosion) +* +* @method Phaser.Particles.Arcade.Emitter#explode +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [quantity=this.maxParticles] - How many particles to launch. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) { + + if (quantity === undefined) { + quantity = this.maxParticles; + } + + this._flowTotal = 0; + + this.start(true, lifespan, 0, quantity, false); + + return this; + +}; + +/** +* Call this function to start emitting a flow of particles. +* `quantity` particles are released every interval of `frequency` ms until `total` particles have been released (or forever). +* If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 × 5 = 20 total) and then turn {@link #on off}. +* If you set the total to be -1 then no quantity cap is used and it will keep emitting (as long as there are inactive particles available). +* +* {@link #output}, {@link #lifespanOutput}, and {@link #remainder} describe the particle flow rate. +* During a stable flow, the number of active particles approaches {@link #lifespanOutput} and the number of inactive particles approaches {@link #remainder}. +* If {@link #remainder} is less than 0, there will likely be no particles available for a portion of the flow (see {@link #count}). +* +* @method Phaser.Particles.Arcade.Emitter#flow +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of particles, given in ms. Values between 0 and 16.66 will behave the same (60 releases per second). +* @param {number} [quantity=1] - How many particles to launch at each interval. Not larger than {@link #maxParticles}. +* @param {number} [total=-1] - Turn {@link #on off} after launching this many particles in total. If -1 it will carry on indefinitely. +* @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) { + + if (frequency === undefined || frequency === null) { frequency = 250; } + if (quantity === undefined || quantity === 0) { quantity = 1; } + if (total === undefined) { total = -1; } + if (immediate === undefined) { immediate = true; } + + if (quantity > this.maxParticles) + { + quantity = this.maxParticles; + } + + this._counter = 0; + this._flowQuantity = quantity; + this._flowTotal = total; + + if (immediate) + { + this.start(true, lifespan, frequency, quantity); + + this._counter += quantity; + this.on = true; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + else + { + this.start(false, lifespan, frequency, quantity); + } + + return this; + +}; + +/** +* Start emitting particles. +* +* {@link #explode} and {@link #flow} are simpler methods. +* +* There are two patterns, based on the `explode` argument: +* +* ##### explode=true +* +* start(true, lifespan=0, null, total) +* +* When `explode` is true or `forceQuantity` is true, `start` emits `total` particles immediately. You should pass a nonzero `total`. +* +* ##### explode=false +* +* start(false, lifespan=0, frequency=250, total=0) +* +* When `explode` is false and `forceQuantity` is false, `start` emits 1 particle every interval of `frequency` ms. If `total` is not zero, the emitter turns itself off after `total` particles have been released. If `total` is zero, the emitter keeps emitting particles as long as they are available. To emit more than 1 particle per flow interval, use {@link #flow} instead. +* +* `forceQuantity` seems equivalent to `explode` and can probably be avoided. +* +* @method Phaser.Particles.Arcade.Emitter#start +* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false). +* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. +* @param {number} [frequency=250] - The interval between each release of 1 particle, when `explode` is false. Value given in ms. Ignored if `explode` is set to true. +* @param {number} [total=0] - Turn {@link #on off} after launching this many particles in total. +* @param {number} [forceQuantity=false] - Equivalent to `explodes`. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, total, forceQuantity) { + + if (explode === undefined) { explode = true; } + if (lifespan === undefined) { lifespan = 0; } + if (frequency === undefined || frequency === null) { frequency = 250; } + if (total === undefined) { total = 0; } + if (forceQuantity === undefined) { forceQuantity = false; } + + if (total > this.maxParticles) + { + total = this.maxParticles; + } + + this.revive(); + + this.visible = true; + + this.lifespan = lifespan; + this.frequency = frequency; + + if (explode || forceQuantity) + { + for (var i = 0; i < total; i++) + { + this.emitParticle(); + } + } + else + { + this.on = true; + this._total = total; + this._counter = 0; + this._timer = this.game.time.time + frequency * this.game.time.slowMotion; + } + + return this; + +}; + +/** +* This function is used internally to emit the next particle in the queue. +* +* However it can also be called externally to emit a particle. +* +* When called externally you can use the arguments to override any defaults the Emitter has set. +* +* The newly emitted particle is available in {@link Phaser.Particles.Arcade.Emitter#cursor}. +* +* @method Phaser.Particles.Arcade.Emitter#emitParticle +* @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. +* @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. +* @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +* @return {boolean} True if a particle was emitted, otherwise false. +*/ +Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + var particle = this.getNextParticle(); + + if (particle === null) + { + this.counts.failed++; + this.counts.totalFailed++; + + return false; + } + + this.counts.emitted++; + this.counts.totalEmitted++; + + var rnd = this.game.rnd; + + if (key !== undefined && frame !== undefined) + { + particle.loadTexture(key, frame); + } + else if (key !== undefined) + { + particle.loadTexture(key); + particle.frame = Array.isArray(this._frames) ? rnd.pick(this._frames) : this._frames; + } + + var emitX = this.emitX; + var emitY = this.emitY; + + if (x !== null) + { + emitX = x; + } + else if (this.width > 1) + { + emitX = rnd.between(this.left, this.right); + } + + if (y !== null) + { + emitY = y; + } + else if (this.height > 1) + { + emitY = rnd.between(this.top, this.bottom); + } + + this.resetParticle(particle, emitX, emitY); + + return true; + +}; + + +/** +* Helper for {@link #emitParticle}. Gets the next available particle. +* +* @private +* @return {?Phaser.Particle} The first particle with exists=false, or null +*/ +Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () { + + var i = this.length; + + while (i--) + { + var next = this.next(); + + if (!next.exists) + { + return next; + } + } + + return null; + +}; + +/** + * Helper for {@link #emitParticle}. Sets particle properties and calls {@link Particle#onEmit}. + * + * @private + * @param {Phaser.Particle} particle + * @param {number} x + * @param {number} y + */ +Phaser.Particles.Arcade.Emitter.prototype.resetParticle = function (particle, x, y) { + + var rnd = this.game.rnd; + + particle.reset(x, y); + + 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(rnd.realInRange(this.minParticleScale, this.maxParticleScale)); + } + else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y)) + { + particle.scale.set(rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y)); + } + else + { + particle.scale.set(this._minParticleScale.x, this._minParticleScale.y); + } + + if (this.autoAlpha) + { + particle.setAlphaData(this.alphaData); + } + else + { + particle.alpha = rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha); + } + + particle.blendMode = this.blendMode; + + var body = particle.body; + + body.updateBounds(); + + body.bounce.copyFrom(this.bounce); + body.drag.copyFrom(this.particleDrag); + + if (this.minAngle != null && this.maxAngle != null) + { + this.game.physics.arcade.velocityFromAngle( + (this.minAngle === this.maxAngle) ? this.minAngle : rnd.between(this.minAngle, this.maxAngle), + (this.minSpeed === this.maxSpeed) ? this.minSpeed : rnd.between(this.minSpeed, this.maxSpeed), + body.velocity + ); + } + else + { + body.velocity.x = rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x); + body.velocity.y = rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y); + } + + body.angularVelocity = rnd.between(this.minRotation, this.maxRotation); + body.gravity.copyFrom(this.gravity); + body.angularDrag = this.angularDrag; + + particle.onEmit(); + +}; + +/** +* Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. +* +* @method Phaser.Particles.Arcade.Emitter#destroy +*/ +Phaser.Particles.Arcade.Emitter.prototype.destroy = function () { + + this.game.particles.remove(this); + + Phaser.Group.prototype.destroy.call(this, true, false); + +}; + +/** +* A more compact way of setting the width and height of the emitter. +* +* @method Phaser.Particles.Arcade.Emitter#setSize +* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). +* @param {number} height - The desired height of the emitter. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { + + this.area.width = width; + this.area.height = height; + + return this; + +}; + +/** +* A more compact way of setting the X velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setXSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.x = min; + this.maxParticleSpeed.x = max; + + return this; + +}; + +/** +* A more compact way of setting the Y velocity range of the emitter. +* @method Phaser.Particles.Arcade.Emitter#setYSpeed +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minParticleSpeed.y = min; + this.maxParticleSpeed.y = max; + + return this; + +}; + +/** +* A more compact way of setting the angular velocity constraints of the particles. +* +* @method Phaser.Particles.Arcade.Emitter#setRotation +* @param {number} [min=0] - The minimum value for this range. +* @param {number} [max=0] - The maximum value for this range. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { + + min = min || 0; + max = max || 0; + + this.minRotation = min; + this.maxRotation = max; + + return this; + +}; + +/** +* A more compact way of setting the alpha constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. +* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setAlpha +* @param {number} [min=1] - The minimum value for this range. +* @param {number} [max=1] - The maximum value for this range. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) { + + if (min === undefined) { min = 1; } + if (max === undefined) { max = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.alphaData.reverse(); + this.autoAlpha = true; + } + + return this; + +}; + +/** +* A more compact way of setting the scale constraints of the particles. +* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. +* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. +* +* @method Phaser.Particles.Arcade.Emitter#setScale +* @param {number} [minX=1] - The minimum value of Particle.scale.x. +* @param {number} [maxX=1] - The maximum value of Particle.scale.x. +* @param {number} [minY=1] - The minimum value of Particle.scale.y. +* @param {number} [maxY=1] - The maximum value of Particle.scale.y. +* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. +* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. +* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) { + + if (minX === undefined) { minX = 1; } + if (maxX === undefined) { maxX = 1; } + if (minY === undefined) { minY = 1; } + if (maxY === undefined) { maxY = 1; } + if (rate === undefined) { rate = 0; } + if (ease === undefined) { ease = Phaser.Easing.Linear.None; } + if (yoyo === undefined) { yoyo = false; } + + // Reset these + 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); + + // Inverse it so we don't have to do array length look-ups in Particle update loops + this.scaleData.reverse(); + this.autoScale = true; + } + + return this; + +}; + +/** + * Sets a radial pattern for emitting particles. + * + * This is a shorthand for setting {@link #minAngle}, {@link #maxAngle}, {@link #minSpeed}, and {@link #maxSpeed}. + * + * To remove the radial pattern, use `setAngle(null, null)`. + * + * @method Phaser.Particles.Arcade.Emitter#setAngle + * @param {?number} minAngle - The minimum angle of initial particle velocities, in degrees. + * @param {?number} maxAngle - The maximum angle of initial particle velocities, in degrees. + * @param {number} [minSpeed] - The minimum initial particle speed. + * @param {number} [maxSpeed] - The maximum initial particle speed. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ +Phaser.Particles.Arcade.Emitter.prototype.setAngle = function (minAngle, maxAngle, minSpeed, maxSpeed) { + + this.minAngle = minAngle; + this.maxAngle = maxAngle; + + if (minSpeed != null) { this.minSpeed = minSpeed; } + if (maxSpeed != null) { this.maxSpeed = maxSpeed; } + + return this; + +}; + +/** +* Change the emitter's center to match the center of any object with a `center` property, such as an Arcade Body. +* If the object doesn't have a `center` property it will be set to the object's anchor-adjusted world position (`object.world`). +* +* @method Phaser.Particles.Arcade.Emitter#at +* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with. +* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. +*/ +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); + } + + return this; + +}; + +/** + * @name Phaser.Particles.Arcade.Emitter#gravity + * @property {Phaser.Point} gravity - Sets the `body.gravity` of each particle sprite to this on launch. + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "gravity", { + + get: function () { + return this._gravity; + }, + + set: function (value) { + if (typeof value === "number") + { + this._gravity.y = value; + } + else + { + this._gravity = value; + } + } + +}); + + +/** +* @name Phaser.Particles.Arcade.Emitter#id +* @property {number} id - Gets the internal ID that represents this emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "id", { + get: function () { + return this._id; + } +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#width +* @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", { + + get: function () { + return this.area.width; + }, + + set: function (value) { + this.area.width = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#height +* @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", { + + get: function () { + return this.area.height; + }, + + set: function (value) { + this.area.height = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#x +* @property {number} x - Gets or sets the x position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", { + + get: function () { + return this.emitX; + }, + + set: function (value) { + this.emitX = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#y +* @property {number} y - Gets or sets the y position of the Emitter. +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", { + + get: function () { + return this.emitY; + }, + + set: function (value) { + this.emitY = value; + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#left +* @property {number} left - Gets the left position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", { + + get: function () { + return Math.floor(this.x - (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#right +* @property {number} right - Gets the right position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", { + + get: function () { + return Math.floor(this.x + (this.area.width / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#top +* @property {number} top - Gets the top position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", { + + get: function () { + return Math.floor(this.y - (this.area.height / 2)); + } + +}); + +/** +* @name Phaser.Particles.Arcade.Emitter#bottom +* @property {number} bottom - Gets the bottom position of the Emitter. +* @readonly +*/ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", { + + get: function () { + return Math.floor(this.y + (this.area.height / 2)); + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#output + * @property {number} output - The number of particles released per second, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "output", { + + get: function () { + return 1000 * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#lifespanOutput + * @property {number} lifespanOutput - The number of particles released during one particle's {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "lifespanOutput", { + + get: function () { + return (this.lifespan === 0 ? Infinity : this.lifespan) * this._flowQuantity / this.frequency; + } + +}); + +/** + * @name Phaser.Particles.Arcade.Emitter#remainder + * @property {number} remainder - The expected number of unreleased particles after a flow interval of {@link #lifespan}, after calling {@link #flow}. + * @readonly + */ +Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "remainder", { + + get: function () { + return this.maxParticles - this.lifespanOutput; + } + +}); + +/** +* The last particle released, if any. +* +* You should treat this as read-only (and also avoid {@link #next} and {@link #previous}) once the emitter is started. Phaser uses it internally to track particles. +* +* @name Phaser.Particles.Arcade.Emitter#cursor +* @property {?DisplayObject} cursor +* @readonly +*/ +// Inherited from Phaser.Group#cursor + +/** +* Advances the cursor to the next particle. +* +* @method Phaser.Particles.Arcade.Emitter#next +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#next + +/** +* Moves the group cursor to the previous particle. +* +* @method Phaser.Particles.Arcade.Emitter#previous +* @protected +* @return {any} The child the cursor now points to. +*/ +// Inherited from Phaser.Group#previous + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* The Weapon Plugin provides the ability to easily create a bullet pool and manager. +* +* Weapons fire {@link Phaser.Bullet} objects, which are essentially Sprites with a few extra properties. +* The Bullets are enabled for {@link Phaser.Physics.Arcade Arcade Physics}. They do not currently work with P2 Physics. +* +* The Bullets are created inside of {@link #bullets weapon.bullets}, which is a {@link Phaser.Group} instance. Anything you +* can usually do with a Group, such as move it around the display list, iterate it, etc can be done +* to the bullets Group too. +* +* Bullets can have textures and even animations. You can control the speed at which they are fired, +* the firing rate, the firing angle, and even set things like gravity for them. +* +* A small example, using {@link Phaser.GameObjectFactory#weapon add.weapon}, assumed to be running from within a {@link Phaser.State#create} method: +* +* ```javascript +* var weapon = this.add.weapon(10, 'bullet'); +* weapon.fireFrom.set(300, 300); +* this.input.onDown.add(weapon.fire, this); +* ``` +* +* If you want to (re)create the bullet pool separately, you can use: +* +* ```javascript +* var weapon = this.game.plugins.add(Phaser.Weapon); +* // … +* weapon.createBullets(10, 'bullet'); +* ``` +* +* @class Phaser.Weapon +* @constructor +* @param {Phaser.Game} game - A reference to the current Phaser.Game instance. +* @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin. +*/ +Phaser.Weapon = function (game, parent) { + + Phaser.Plugin.call(this, game, parent); + + /** + * This is the Phaser.Group that contains all of the bullets managed by this plugin. + * @type {Phaser.Group} + */ + this.bullets = null; + + /** + * Should the bullet pool run out of bullets (i.e. they are all in flight) then this + * boolean controls if the Group will create a brand new bullet object or not. + * @type {boolean} + * @default + */ + this.autoExpandBulletsGroup = false; + + /** + * Will this weapon auto fire? If set to true then a new bullet will be fired + * based on the {@link #fireRate} value. + * @type {boolean} + * @default + */ + this.autofire = false; + + /** + * The total number of bullets this Weapon has fired so far. + * You can limit the number of shots allowed (via {@link #fireLimit}), and reset + * this total via {@link #resetShots}. + * @type {number} + * @default + */ + this.shots = 0; + + /** + * The maximum number of shots that this Weapon is allowed to fire before it stops. + * When the limit is his the {@link #onFireLimit} Signal is dispatched. + * You can reset the shot counter via {@link #resetShots}. + * @type {number} + * @default + */ + this.fireLimit = 0; + + /** + * The minimum interval between shots, in milliseconds. + * @type {number} + * @default + */ + this.fireRate = 100; + + /** + * This is a modifier that is added to the {@link #fireRate} each update to add variety + * to the firing rate of the Weapon. The value is given in milliseconds. + * If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual + * firing rate of the Weapon will be between 150 and 250. + * @type {number} + * @default + */ + this.fireRateVariance = 0; + + /** + * This is a Rectangle from within which the bullets are fired. By default it's a 1x1 + * rectangle, the equivalent of a Point. But you can change the width and height, and if + * larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from. + * @type {Phaser.Rectangle} + */ + this.fireFrom = new Phaser.Rectangle(0, 0, 1, 1); + + /** + * The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE_UP + * or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right. + * @type {integer} + * @default + */ + this.fireAngle = Phaser.ANGLE_UP; + + /** + * When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set. + * @type {boolean} + * @default + */ + this.bulletInheritSpriteSpeed = false; + + /** + * The string based name of the animation that the Bullet will be given on launch. + * This is set via {@link #addBulletAnimation}. + * @type {string} + * @default + */ + this.bulletAnimation = ''; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to pick a random frame from the set. + * @type {boolean} + * @default + */ + this.bulletFrameRandom = false; + + /** + * If you've added a set of frames via {@link #setBulletFrames} then you can optionally + * chose for each Bullet fired to use the next frame in the set. The frame index is then + * advanced one frame until it reaches the end of the set, then it starts from the start + * again. Cycling frames like this allows you to create varied bullet effects via + * sprite sheets. + * @type {boolean} + * @default + */ + this.bulletFrameCycle = false; + + /** + * Should the Bullets wrap around the world bounds? This automatically calls + * `World.wrap` on the Bullet each frame. See the docs for that method for details. + * @type {boolean} + * @default + */ + this.bulletWorldWrap = false; + + /** + * If `bulletWorldWrap` is true then you can provide an optional padding value with this + * property. It's added to the calculations determining when the Bullet should wrap around + * the world or not. The value is given in pixels. + * @type {integer} + * @default + */ + this.bulletWorldWrapPadding = 0; + + /** + * An optional angle offset applied to the Bullets when they are launched. + * This is useful if for example your bullet sprites have been drawn facing up, instead of + * to the right, and you want to fire them at an angle. In which case you can set the + * angle offset to be 90 and they'll be properly rotated when fired. + * @type {number} + * @default + */ + this.bulletAngleOffset = 0; + + /** + * This is a variance added to the angle of Bullets when they are fired. + * If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual + * angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a + * great 'spread' effect to a Weapon. + * @type {number} + * @default + */ + this.bulletAngleVariance = 0; + + /** + * The initial velocity of fired bullets, in pixels per second. + * @type {number} + * @default + */ + this.bulletSpeed = 200; + + /** + * This is a variance added to the speed of Bullets when they are fired. + * If bullets have a {@link #bulletSpeed} value of 200, and a `bulletSpeedVariance` of 50 + * then the actual speed of the Bullets will be between 150 and 250 pixels per second. + * @type {number} + * @default + */ + this.bulletSpeedVariance = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount + * of lifespan the Bullets have set on launch. The value is given in milliseconds. + * When a Bullet hits its lifespan limit it will be automatically killed. + * @type {number} + * @default + */ + this.bulletLifespan = 0; + + /** + * If you've set {@link #bulletKillType} to `Phaser.Weapon.KILL_DISTANCE` this controls the distance + * the Bullet can travel before it is automatically killed. The distance is given in pixels. + * @type {number} + * @default + */ + this.bulletKillDistance = 0; + + /** + * This is the amount of {@link Phaser.Physics.Arcade.Body#gravity} added to the Bullets physics body when fired. + * Gravity is expressed in pixels / second / second. + * @type {Phaser.Point} + */ + this.bulletGravity = new Phaser.Point(0, 0); + + /** + * Bullets can optionally adjust their rotation in-flight to match their velocity. + * This can create the effect of a bullet 'pointing' to the path it is following, for example + * an arrow being fired from a bow, and works especially well when added to {@link #bulletGravity}. + * @type {boolean} + * @default + */ + this.bulletRotateToVelocity = false; + + /** + * The Texture Key that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string} + * @default + */ + this.bulletKey = ''; + + /** + * The Texture Frame that the Bullets use when rendering. + * Changing this has no effect on bullets in-flight, only on newly spawned bullets. + * @type {string|integer} + * @default + */ + this.bulletFrame = ''; + + /** + * Private var that holds the public `bulletClass` property. + * @type {function} + * @private + */ + this._bulletClass = Phaser.Bullet; + + /** + * Private var that holds the public `bulletCollideWorldBounds` property. + * @type {boolean} + * @private + */ + this._bulletCollideWorldBounds = false; + + /** + * Private var that holds the public `bulletKillType` property. + * @type {integer} + * @private + */ + this._bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; + + /** + * Holds internal data about custom bullet body sizes. + * + * @type {Object} + * @private + */ + this._data = { + customBody: false, + width: 0, + height: 0, + offsetX: 0, + offsetY: 0 + }; + + /** + * This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not. + * It's used in combination with {@link #bulletKillType} when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS` + * or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored. + * If you are tracking a Sprite or Point then the bounds are centered on that object every frame. + * + * @type {Phaser.Rectangle} + */ + this.bounds = new Phaser.Rectangle(); + + /** + * The Rectangle used to calculate the bullet bounds from. + * + * @type {Phaser.Rectangle} + * @private + */ + this.bulletBounds = game.world.bounds; + + /** + * This array stores the frames added via @link #setBulletFrames. + * + * @type {Array} + * @protected + */ + this.bulletFrames = []; + + /** + * The index of the frame within {@link #bulletFrames} that is currently being used. + * This value is only used if {@link #bulletFrameCycle} is set to `true`. + * @type {number} + * @private + */ + this.bulletFrameIndex = 0; + + /** + * An internal object that stores the animation data added via {@link #addBulletAnimation}. + * @type {Object} + * @private + */ + this.anims = {}; + + /** + * The onFire Signal is dispatched each time {@link #fire} is called, and a Bullet is + * _successfully_ launched. The callback is set two arguments: a reference to the bullet sprite itself, + * and a reference to the Weapon that fired the bullet. + * + * @type {Phaser.Signal} + */ + this.onFire = new Phaser.Signal(); + + /** + * The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result + * of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance. + * The callback is sent one argument: A reference to the bullet sprite itself. + * + * @type {Phaser.Signal} + */ + this.onKill = new Phaser.Signal(); + + /** + * The onFireLimit Signal is dispatched if {@link #fireLimit} is > 0, and a bullet launch takes the number + * of shots fired to equal the fire limit. + * The callback is sent two arguments: A reference to this Weapon, and the value of + * {@link #fireLimit}. + * + * @type {Phaser.Signal} + */ + this.onFireLimit = new Phaser.Signal(); + + /** + * The Sprite currently being tracked by the Weapon, if any. + * This is set via the {@link #trackSprite} method. + * + * @type {Phaser.Sprite|Object} + */ + this.trackedSprite = null; + + /** + * The Pointer currently being tracked by the Weapon, if any. + * This is set via the {@link #trackPointer} method. + * + * @type {Phaser.Pointer} + */ + this.trackedPointer = null; + + /** + * If you want this Weapon to be able to fire more than 1 bullet in a single + * update, then set this property to `true`. When `true` the Weapon plugin won't + * set the shot / firing timers until the `postRender` phase of the game loop. + * This means you can call `fire` (and similar methods) as often as you like in one + * single game update. + * + * @type {boolean} + * @default + */ + this.multiFire = false; + + /** + * Internal multiFire test flag. + * + * @type {boolean} + */ + this._hasFired = false; + + /** + * If the Weapon is tracking a Sprite, should it also track the Sprites rotation? + * This is useful for a game such as Asteroids, where you want the weapon to fire based + * on the sprites rotation. + * + * @type {boolean} + * @default + */ + this.trackRotation = false; + + /** + * The Track Offset is a Point object that allows you to specify a pixel offset that bullets use + * when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels + * in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have + * the bullet launched from the center of the Sprite. + * + * @type {Phaser.Point} + */ + this.trackOffset = new Phaser.Point(); + + /** + * Internal firing rate time tracking variable. + * + * @type {number} + * @private + */ + this._nextFire = 0; + + /** + * Internal firing rate time tracking variable used by multiFire. + * + * @type {number} + * @private + */ + this._tempNextFire = 0; + + /** + * Internal firing rotation tracking point. + * + * @type {Phaser.Point} + * @private + */ + this._rotatedPoint = new Phaser.Point(); + +}; + +Phaser.Weapon.prototype = Object.create(Phaser.Plugin.prototype); +Phaser.Weapon.prototype.constructor = Phaser.Weapon; + +/** +* A {@link #bulletKillType} constant that stops the bullets from ever being destroyed automatically. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_NEVER = 0; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when their {@link #bulletLifespan} expires. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_LIFESPAN = 1; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets after they +* exceed the {@link #bulletDistance} from their original firing position. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_DISTANCE = 2; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WEAPON_BOUNDS = 3; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.Camera#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_CAMERA_BOUNDS = 4; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link Phaser.World#bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_WORLD_BOUNDS = 5; + +/** +* A {@link #bulletKillType} constant that automatically kills the bullets when they leave the {@link #bounds} rectangle. +* @constant +* @type {integer} +*/ +Phaser.Weapon.KILL_STATIC_BOUNDS = 6; + +/** +* This method performs two actions: First it will check to see if the {@link #bullets} Group exists or not, +* and if not it creates it, adding it the `group` given as the 4th argument. +* +* Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame +* provided (if any). +* +* If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets +* in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of +* the in-flight bullets have been killed, freeing them up for use by the Weapon again. +* +* If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will +* keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however, +* so be careful it doesn't grow too large. +* +* You can either set the texture key and frame here, or via the {@link #bulletKey} and {@link #bulletFrame} +* properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a +* single Weapon instance must share the same texture key however. +* +* @method Phaser.Weapon#createBullets +* @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. +* @param {string} [key] - The Game.cache key of the image that this Sprite will use. +* @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. +* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.createBullets = function (quantity, key, frame, group) { + + if (quantity === undefined) { quantity = 1; } + if (group === undefined) { group = this.game.world; } + + if (this.bullets && !this.bullets.game) + { + this.bullets = null; + } + + if (!this.bullets) + { + this.bullets = this.game.add.physicsGroup(Phaser.Physics.ARCADE, group); + this.bullets.classType = this._bulletClass; + } + + if (quantity !== 0) + { + if (quantity === -1) + { + this.autoExpandBulletsGroup = true; + quantity = 1; + } + + this.bullets.createMultiple(quantity, key, frame); + + this.bullets.setAll('data.bulletManager', this); + + this.bulletKey = key; + this.bulletFrame = frame; + } + + return this; + +}; + +/** +* Call a function on each in-flight bullet in this Weapon. +* +* See {@link Phaser.Group#forEachExists forEachExists} for more details. +* +* @method Phaser.Weapon#forEach +* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. +* @param {object} callbackContext - The context in which the function should be called (usually 'this'). +* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.forEach = function (callback, callbackContext) { + + this.bullets.forEachExists(callback, callbackContext, arguments); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `false` on each bullet in this Weapon. +* This has the effect of stopping them in-flight should they be moving. +* It also stops them being able to be checked for collision. +* +* @method Phaser.Weapon#pauseAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.pauseAll = function () { + + this.bullets.setAll('body.enable', false); + + return this; + +}; + +/** +* Sets {@link Phaser.Physics.Arcade.Body#enable} to `true` on each bullet in this Weapon. +* This has the effect of resuming their motion should they be in-flight. +* It also enables them for collision checks again. +* +* @method Phaser.Weapon#resumeAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resumeAll = function () { + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Calls {@link Phaser.Bullet#kill} on every in-flight bullet in this Weapon. +* Also re-enables their physics bodies, should they have been disabled via {@link #pauseAll}. +* +* @method Phaser.Weapon#killAll +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.killAll = function () { + + this.bullets.callAllExists('kill', true); + + this.bullets.setAll('body.enable', true); + + return this; + +}; + +/** +* Resets the {@link #shots} counter back to zero. This is used when you've set +* {@link #fireLimit} and have hit (or just wish to reset) your limit. +* +* @method Phaser.Weapon#resetShots +* @param {integer} [newLimit] - Optionally set a new {@link #fireLimit}. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.resetShots = function (newLimit) { + + this.shots = 0; + + if (newLimit !== undefined) + { + this.fireLimit = newLimit; + } + + return this; + +}; + +/** +* Destroys this Weapon. It removes itself from the PluginManager, destroys +* the {@link #bullets} Group, and nulls internal references. +* +* @method Phaser.Weapon#destroy +*/ +Phaser.Weapon.prototype.destroy = function () { + + this.parent.remove(this, false); + + this.bullets.destroy(); + + this.game = null; + this.parent = null; + this.active = false; + this.visible = false; + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#update +* @protected +*/ +Phaser.Weapon.prototype.update = function () { + + if (this._bulletKillType === Phaser.Weapon.KILL_WEAPON_BOUNDS) + { + if (this.trackedSprite) + { + this.trackedSprite.updateTransform(); + this.bounds.centerOn(this.trackedSprite.worldPosition.x, this.trackedSprite.worldPosition.y); + } + else if (this.trackedPointer) + { + this.bounds.centerOn(this.trackedPointer.worldX, this.trackedPointer.worldY); + } + } + + if (this.autofire) + { + this.fire(); + } + +}; + +/** +* Internal update method, called by the PluginManager. +* +* @method Phaser.Weapon#postRender +* @protected +*/ +Phaser.Weapon.prototype.postRender = function () { + + if (!this.multiFire || !this._hasFired) + { + return; + } + + this._hasFired = false; + + this._nextFire = this._tempNextFire; + +}; + +/** +* Sets this Weapon to track the given Sprite, or any Object with a public {@link Phaser.Component.Core#world world} Point object. +* When a Weapon tracks a Sprite it will automatically update its {@link #fireFrom} value to match the Sprite's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location. +* +* Calling `trackSprite` will reset {@link #trackedPointer} to null, should it have been set, as you can +* only track _either_ a Sprite, or a Pointer, at once, but not both. +* +* @method Phaser.Weapon#trackSprite +* @param {Phaser.Sprite|Object} sprite - The Sprite to track the position of. +* @param {integer} [offsetX=0] - The horizontal offset from the Sprites position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Sprites position to be applied to the Weapon. +* @param {boolean} [trackRotation=false] - Should the Weapon also track the Sprites rotation? +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackSprite = function (sprite, offsetX, offsetY, trackRotation) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + if (trackRotation === undefined) { trackRotation = false; } + + this.trackedPointer = null; + this.trackedSprite = sprite; + this.trackRotation = trackRotation; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Sets this Weapon to track the given Pointer. +* When a Weapon tracks a Pointer it will automatically update its {@link #fireFrom} value to match the Pointer's +* position within the Game World, adjusting the coordinates based on the offset arguments. +* +* This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location. +* +* Calling `trackPointer` will reset {@link #trackedSprite} to null, should it have been set, as you can +* only track _either_ a Pointer, or a Sprite, at once, but not both. +* +* @method Phaser.Weapon#trackPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to track the position of. Defaults to `Input.activePointer` if not specified. +* @param {integer} [offsetX=0] - The horizontal offset from the Pointers position to be applied to the Weapon. +* @param {integer} [offsetY=0] - The vertical offset from the Pointers position to be applied to the Weapon. +* @return {Phaser.Weapon} This Weapon instance. +*/ +Phaser.Weapon.prototype.trackPointer = function (pointer, offsetX, offsetY) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this.trackedPointer = pointer; + this.trackedSprite = null; + this.trackRotation = false; + + this.trackOffset.set(offsetX, offsetY); + + return this; + +}; + +/** +* Attempts to fire multiple bullets from the positions defined in the given array. +* +* If you provide a `from` argument, or if there is a tracked Sprite or Pointer, then +* the positions are treated as __offsets__ from the given objects position. +* +* If `from` is undefined, and there is no tracked object, then the bullets are fired +* from the given positions, as they exist in the world. +* +* Calling this method sets {@link #multiFire} to `true`. +* +* If there are not enough bullets available in the pool, and the pool cannot be extended, +* then this method may not fire from all of the given positions. +* +* When the bullets are launched they have their texture and frame updated, as required. +* The velocity of the bullets are calculated based on Weapon properties like {@link #bulletSpeed}. +* +* @method Phaser.Weapon#fireMany +* @param {array} positions - An array of positions. Each position can be any Object, as long as it has public `x` and `y` properties, such as Phaser.Point, { x: 0, y: 0 }, Phaser.Sprite, etc. +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullets **from** the `x` and `y` properties of this object, _instead_ of any {@link #trackedSprite} or `trackedPointer` that is set. +* @return {array} An array containing all of the fired Phaser.Bullet objects, if a launch was successful, otherwise an empty array. +*/ +Phaser.Weapon.prototype.fireMany = function (positions, from) { + + this.multiFire = true; + + var bullets = []; + + var _this = this; + + if (from || this.trackedSprite || this.trackedPointer) + { + positions.forEach(function(offset) { + + bullets.push(_this.fire(from, null, null, offset.x, offset.y)); + + }); + } + else + { + positions.forEach(function(position) { + + bullets.push(_this.fire(position)); + + }); + } + + return bullets; + +}; + +/** +* Attempts to fire a single Bullet from a tracked Sprite or Pointer, but applies an offset +* to the position first. This is the same as calling {@link #fire} and passing in the offset arguments. +* +* If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like {@link #bulletSpeed}. +* +* If you wish to fire multiple bullets in a single game update, then set {@link #multiFire} to `true` +* and you can call this method as many times as you like, per loop. See also {@link #fireMany}. +* +* @method Phaser.Weapon#fireOffset +* @param {number} [offsetX=0] - The horizontal offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @param {number} [offsetY=0] - The vertical offset from the position of the tracked Sprite or Pointer, as set with {@link #trackSprite}. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fireOffset = function (offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + return this.fire(null, null, null, offsetX, offsetY); + +}; + +/** +* Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended, +* then this method returns `null`. It will also return `null` if not enough time has expired since the last time +* the Weapon was fired, as defined in the {@link #fireRate} property. +* +* Otherwise the first available bullet is selected, launched, and returned. +* +* The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at. +* +* If you don't provide any of the arguments then it uses those set via properties such as {@link #trackedSprite}, +* {@link #bulletAngle} and so on. +* +* When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is +* calculated based on Weapon properties like `bulletSpeed`. +* +* If you wish to fire multiple bullets in a single game update, then set `Weapon.multiFire = true` +* and you can call `fire` as many times as you like, per loop. Multiple fires in a single update +* only counts once towards the `shots` total, but you will still receive a Signal for each bullet. +* +* @method Phaser.Weapon#fire +* @param {Phaser.Sprite|Phaser.Point|Object|string} [from] - Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides {@link #trackedSprite} or `trackedPointer`. Pass `null` to ignore it. +* @param {number} [x] - The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined`, or `null`, the bullet direction is based on its angle. +* @param {number} [offsetX=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a horizontal offset from the launch position. +* @param {number} [offsetY=0] - If the bullet is fired from a tracked Sprite or Pointer, or the `from` argument is set, this applies a vertical offset from the launch position. +* @return {Phaser.Bullet} The fired bullet, if a launch was successful, otherwise `null`. +*/ +Phaser.Weapon.prototype.fire = function (from, x, y, offsetX, offsetY) { + + if (x === undefined) { x = null; } + if (y === undefined) { y = null; } + + if (this.game.time.now < this._nextFire || (this.fireLimit > 0 && this.shots === this.fireLimit)) + { + return null; + } + + var speed = this.bulletSpeed; + + // Apply +- speed variance + if (this.bulletSpeedVariance !== 0) + { + speed += Phaser.Math.between(-this.bulletSpeedVariance, this.bulletSpeedVariance); + } + + if (from) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(from.x, from.y); + } + else + { + this.fireFrom.x = from.x; + this.fireFrom.y = from.y; + } + } + else if (this.trackedSprite) + { + if (this.trackRotation) + { + this._rotatedPoint.set(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.worldRotation); + + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this._rotatedPoint.x, this._rotatedPoint.y); + } + else + { + this.fireFrom.x = this._rotatedPoint.x; + this.fireFrom.y = this._rotatedPoint.y; + } + } + else + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedSprite.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedSprite.world.y + this.trackOffset.y; + } + } + + if (this.bulletInheritSpriteSpeed) + { + speed += this.trackedSprite.body.speed; + } + } + else if (this.trackedPointer) + { + if (this.fireFrom.width > 1) + { + this.fireFrom.centerOn(this.trackedPointer.world.x + this.trackOffset.x, this.trackedPointer.world.y + this.trackOffset.y); + } + else + { + this.fireFrom.x = this.trackedPointer.world.x + this.trackOffset.x; + this.fireFrom.y = this.trackedPointer.world.y + this.trackOffset.y; + } + } + + if (offsetX !== undefined) + { + this.fireFrom.x += offsetX; + } + + if (offsetY !== undefined) + { + this.fireFrom.y += offsetY; + } + + var fromX = (this.fireFrom.width > 1) ? this.fireFrom.randomX : this.fireFrom.x; + var fromY = (this.fireFrom.height > 1) ? this.fireFrom.randomY : this.fireFrom.y; + + var angle = (this.trackRotation) ? this.trackedSprite.angle : this.fireAngle; + + // The position (in world space) to fire the bullet towards, if set + if (x !== null && y !== null) + { + angle = this.game.math.radToDeg(Math.atan2(y - fromY, x - fromX)); + } + + // Apply +- angle variance + if (this.bulletAngleVariance !== 0) + { + angle += Phaser.Math.between(-this.bulletAngleVariance, this.bulletAngleVariance); + } + + var moveX = 0; + var moveY = 0; + + // Avoid sin/cos for right-angled shots + if (angle === 0 || angle === 180) + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + } + else if (angle === 90 || angle === 270) + { + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + else + { + moveX = Math.cos(this.game.math.degToRad(angle)) * speed; + moveY = Math.sin(this.game.math.degToRad(angle)) * speed; + } + + var bullet = null; + + if (this.autoExpandBulletsGroup) + { + bullet = this.bullets.getFirstExists(false, true, fromX, fromY, this.bulletKey, this.bulletFrame); + + bullet.data.bulletManager = this; + } + else + { + bullet = this.bullets.getFirstExists(false); + } + + if (bullet) + { + bullet.reset(fromX, fromY); + + bullet.data.fromX = fromX; + bullet.data.fromY = fromY; + bullet.data.killType = this.bulletKillType; + bullet.data.killDistance = this.bulletKillDistance; + bullet.data.rotateToVelocity = this.bulletRotateToVelocity; + + if (this.bulletKillType === Phaser.Weapon.KILL_LIFESPAN) + { + bullet.lifespan = this.bulletLifespan; + } + + bullet.angle = angle + this.bulletAngleOffset; + + // Frames and Animations + if (this.bulletAnimation !== '') + { + if (bullet.animations.getAnimation(this.bulletAnimation) === null) + { + var anim = this.anims[this.bulletAnimation]; + + bullet.animations.add(anim.name, anim.frames, anim.frameRate, anim.loop, anim.useNumericIndex); + } + + bullet.animations.play(this.bulletAnimation); + } + else + { + if (this.bulletFrameCycle) + { + bullet.frame = this.bulletFrames[this.bulletFrameIndex]; + + this.bulletFrameIndex++; + + if (this.bulletFrameIndex >= this.bulletFrames.length) + { + this.bulletFrameIndex = 0; + } + } + else if (this.bulletFrameRandom) + { + bullet.frame = this.bulletFrames[Math.floor(Math.random() * this.bulletFrames.length)]; + } + } + + if (bullet.data.bodyDirty) + { + if (this._data.customBody) + { + bullet.body.setSize(this._data.width, this._data.height, this._data.offsetX, this._data.offsetY); + } + + bullet.body.collideWorldBounds = this.bulletCollideWorldBounds; + + bullet.data.bodyDirty = false; + } + + bullet.body.velocity.set(moveX, moveY); + bullet.body.gravity.set(this.bulletGravity.x, this.bulletGravity.y); + + var next = 0; + + if (this.bulletSpeedVariance !== 0) + { + var rate = this.fireRate; + + rate += Phaser.Math.between(-this.fireRateVariance, this.fireRateVariance); + + if (rate < 0) + { + rate = 0; + } + + next = this.game.time.now + rate; + } + else + { + next = this.game.time.now + this.fireRate; + } + + if (this.multiFire) + { + if (!this._hasFired) + { + // We only add 1 to the 'shots' count for multiFire shots + this._hasFired = true; + this._tempNextFire = next; + this.shots++; + } + } + else + { + this._nextFire = next; + + this.shots++; + } + + this.onFire.dispatch(bullet, this, speed); + + if (this.fireLimit > 0 && this.shots === this.fireLimit) + { + this.onFireLimit.dispatch(this, this.fireLimit); + } + } + + return bullet; + +}; + +/** +* Fires a bullet **at** the given Pointer. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtPointer +* @param {Phaser.Pointer} [pointer] - The Pointer to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtPointer = function (pointer) { + + if (pointer === undefined) { pointer = this.game.input.activePointer; } + + return this.fire(null, pointer.worldX, pointer.worldY); + +}; + +/** +* Fires a bullet **at** the given Sprite. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtSprite +* @param {Phaser.Sprite} [sprite] - The Sprite to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtSprite = function (sprite) { + + return this.fire(null, sprite.world.x, sprite.world.y); + +}; + +/** +* Fires a bullet **at** the given coordinates. The bullet will be launched from the {@link #fireFrom} position, +* or from a Tracked Sprite or Pointer, if you have one set. +* +* @method Phaser.Weapon#fireAtXY +* @param {number} [x] - The x coordinate, in world space, to fire the bullet towards. +* @param {number} [y] - The y coordinate, in world space, to fire the bullet towards. +* @return {Phaser.Bullet} The fired bullet if successful, null otherwise. +*/ +Phaser.Weapon.prototype.fireAtXY = function (x, y) { + + return this.fire(null, x, y); + +}; + +/** +* You can modify the size of the physics Body the Bullets use to be any dimension you need. +* This allows you to make it smaller, or larger, than the parent Sprite. +* You can also control the x and y offset of the Body. This is the position of the +* Body relative to the top-left of the Sprite _texture_. +* +* For example: If you have a Sprite with a texture that is 80x100 in size, +* and you want the physics body to be 32x32 pixels in the middle of the texture, you would do: +* +* `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, 34)` +* +* Where the first two parameters are the new Body size (32x32 pixels) relative to the Sprite's scale. +* 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34 +* is the vertical offset. +* +* @method Phaser.Weapon#setBulletBodyOffset +* @param {number} width - The width of the Body. +* @param {number} height - The height of the Body. +* @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture. +* @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture. +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletBodyOffset = function (width, height, offsetX, offsetY) { + + if (offsetX === undefined) { offsetX = 0; } + if (offsetY === undefined) { offsetY = 0; } + + this._data.customBody = true; + this._data.width = width; + this._data.height = height; + this._data.offsetX = offsetX; + this._data.offsetY = offsetY; + + // Update all bullets in the pool + this.bullets.callAll('body.setSize', 'body', width, height, offsetX, offsetY); + this.bullets.setAll('data.bodyDirty', false); + + return this; + +}; + +/** +* Sets the texture frames that the bullets can use when being launched. +* +* This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet. +* +* It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values +* provided. Then it sets the frame index to be zero. +* +* You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames +* when they're fired, or pick one at random. +* +* @method Phaser.Weapon#setBulletFrames +* @param {integer} min - The minimum value the frame can be. Usually zero. +* @param {integer} max - The maximum value the frame can be. +* @param {boolean} [cycle=true] - Should the bullet frames cycle as they are fired? +* @param {boolean} [random=false] - Should the bullet frames be picked at random as they are fired? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.setBulletFrames = function (min, max, cycle, random) { + + if (cycle === undefined) { cycle = true; } + if (random === undefined) { random = false; } + + this.bulletFrames = Phaser.ArrayUtils.numberArray(min, max); + + this.bulletFrameIndex = 0; + + this.bulletFrameCycle = cycle; + this.bulletFrameRandom = random; + + return this; + +}; + +/** +* Adds a new animation under the given key. Optionally set the frames, frame rate and loop. +* The arguments are all the same as for `Animation.add`, and work in the same way. +* +* {@link #bulletAnimation} will be set to this animation after it's created. From that point on, all +* bullets fired will play using this animation. You can swap between animations by calling this method +* several times, and then just changing the {@link #bulletAnimation} property to the name of the animation +* you wish to play for the next launched bullet. +* +* If you wish to stop using animations at all, set {@link #bulletAnimation} to '' (an empty string). +* +* @method Phaser.Weapon#addBulletAnimation +* @param {string} name - The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast". +* @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. +* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. +* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. +* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? +* @return {Phaser.Weapon} The Weapon Plugin. +*/ +Phaser.Weapon.prototype.addBulletAnimation = function (name, frames, frameRate, loop, useNumericIndex) { + + this.anims[name] = { + name: name, + frames: frames, + frameRate: frameRate, + loop: loop, + useNumericIndex: useNumericIndex + }; + + // Add the animation to any existing bullets in the pool + this.bullets.callAll('animations.add', 'animations', name, frames, frameRate, loop, useNumericIndex); + + this.bulletAnimation = name; + + return this; + +}; + +/** +* Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets +* both in-flight, and available. And optionally the physics debug bodies of the bullets. +* +* @method Phaser.Weapon#debug +* @param {integer} [x=16] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {integer} [y=32] - The coordinate, in screen space, at which to draw the Weapon debug data. +* @param {boolean} [debugBodies=false] - Optionally draw the physics body of every bullet in-flight. +*/ +Phaser.Weapon.prototype.debug = function (x, y, debugBodies) { + + if (x === undefined) { x = 16; } + if (y === undefined) { y = 32; } + if (debugBodies === undefined) { debugBodies = false; } + + this.game.debug.text("Weapon Plugin", x, y); + this.game.debug.text("Bullets Alive: " + this.bullets.total + " - Total: " + this.bullets.length, x, y + 24); + + if (debugBodies) + { + this.bullets.forEachExists(this.game.debug.body, this.game.debug, 'rgba(255, 0, 255, 0.8)'); + } + +}; + +/** +* The Class of the bullets that are launched by this Weapon. Defaults to {@link Phaser.Bullet}, but can be +* overridden before calling `createBullets` and set to your own class type. +* +* It should be a constructor function accepting `(game, x, y, key, frame)`. +* +* @name Phaser.Weapon#bulletClass +* @property {function} bulletClass +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletClass", { + + get: function () { + + return this._bulletClass; + + }, + + set: function (classType) { + + this._bulletClass = classType; + + // `this.bullets` exists only after createBullets() + if (this.bullets) { + this.bullets.classType = this._bulletClass; + } + } + +}); + +/** +* This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`. +* +* There are 7 different "kill types" available: +* +* * `Phaser.Weapon.KILL_NEVER` +* The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code. +* +* * `Phaser.Weapon.KILL_LIFESPAN` +* The bullets are automatically killed when their `bulletLifespan` amount expires. +* +* * `Phaser.Weapon.KILL_DISTANCE` +* The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position. +* +* * `Phaser.Weapon.KILL_WEAPON_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* +* * `Phaser.Weapon.KILL_CAMERA_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.Camera#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_WORLD_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link Phaser.World#bounds} rectangle. +* +* * `Phaser.Weapon.KILL_STATIC_BOUNDS` +* The bullets are automatically killed when they no longer intersect with the {@link #bounds} rectangle. +* The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to +* match the position of a tracked sprite or pointer. +* +* @name Phaser.Weapon#bulletKillType +* @property {integer} bulletKillType +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletKillType", { + + get: function () { + + return this._bulletKillType; + + }, + + set: function (type) { + + switch (type) + { + case Phaser.Weapon.KILL_STATIC_BOUNDS: + case Phaser.Weapon.KILL_WEAPON_BOUNDS: + this.bulletBounds = this.bounds; + break; + + case Phaser.Weapon.KILL_CAMERA_BOUNDS: + this.bulletBounds = this.game.camera.view; + break; + + case Phaser.Weapon.KILL_WORLD_BOUNDS: + this.bulletBounds = this.game.world.bounds; + break; + } + + this._bulletKillType = type; + + } + +}); + +/** +* Should bullets collide with the World bounds or not? +* +* @name Phaser.Weapon#bulletCollideWorldBounds +* @property {boolean} bulletCollideWorldBounds +*/ +Object.defineProperty(Phaser.Weapon.prototype, "bulletCollideWorldBounds", { + + get: function () { + + return this._bulletCollideWorldBounds; + + }, + + set: function (value) { + + this._bulletCollideWorldBounds = value; + + this.bullets.setAll('body.collideWorldBounds', value); + this.bullets.setAll('data.bodyDirty', false); + + } + +}); + +/** +* The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#x +* @property {number} x +*/ +Object.defineProperty(Phaser.Weapon.prototype, "x", { + + get: function () { + + return this.fireFrom.x; + + }, + + set: function (value) { + + this.fireFrom.x = value; + } + +}); + +/** +* The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and +* can be overridden by the {@link #fire} arguments. +* +* @name Phaser.Weapon#y +* @property {number} y +*/ +Object.defineProperty(Phaser.Weapon.prototype, "y", { + + get: function () { + + return this.fireFrom.y; + + }, + + set: function (value) { + + this.fireFrom.y = value; + } + +}); + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites, +* with a few extra properties in the data object to handle Weapon specific features. +* +* @class Phaser.Bullet +* @constructor +* @extends Phaser.Sprite +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {number} x - The x coordinate (in world space) to position the Particle at. +* @param {number} y - The y coordinate (in world space) to position the Particle at. +* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. +* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. +*/ +Phaser.Bullet = function (game, x, y, key, frame) { + + Phaser.Sprite.call(this, game, x, y, key, frame); + + this.anchor.set(0.5); + + this.data = { + bulletManager: null, + fromX: 0, + fromY: 0, + bodyDirty: true, + rotateToVelocity: false, + killType: 0, + killDistance: 0 + }; + +}; + +Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype); +Phaser.Bullet.prototype.constructor = Phaser.Bullet; + +/** +* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool. +* Also dispatches the `Weapon.onKill` signal. +* +* @method Phaser.Bullet#kill +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.kill = function () { + + this.alive = false; + this.exists = false; + this.visible = false; + + this.data.bulletManager.onKill.dispatch(this); + + return this; + +}; + +/** +* Updates the Bullet, killing as required. +* +* @method Phaser.Bullet#update +* @memberof Phaser.Bullet +*/ +Phaser.Bullet.prototype.update = function () { + + if (!this.exists) + { + return; + } + + if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN) + { + if (this.data.killType === Phaser.Weapon.KILL_DISTANCE) + { + if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance) + { + this.kill(); + } + } + else + { + if (!this.data.bulletManager.bulletBounds.intersects(this)) + { + this.kill(); + } + } + } + + if (this.data.rotateToVelocity) + { + this.rotation = this.body.velocity.atan(); + } + + if (this.data.bulletManager.bulletWorldWrap) + { + this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding); + } + +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +/** +* A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. +* +* Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to +* the Video instead (see `startMediaStream` method) +* +* The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback +* changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. +* +* Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. +* +* If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. +* Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. +* +* On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. +* This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio +* it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` +* method to try and work around this limitation, but see the method help for details. +* +* Small screen devices, especially iPod and iPhone will launch the video in its own native video player, +* outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. +* +* Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) +* then you need to add your own event listener +* +* @class Phaser.Video +* @constructor +* @param {Phaser.Game} game - A reference to the currently running game. +* @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. +* @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) +*/ +Phaser.Video = function (game, key, url) { + + if (key === undefined) { key = null; } + if (url === undefined) { url = null; } + + /** + * @property {Phaser.Game} game - A reference to the currently running game. + */ + this.game = game; + + /** + * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. + * @default null + */ + this.key = key; + + /** + * @property {number} width - The width of the video in pixels. + * @default + */ + this.width = 0; + + /** + * @property {number} height - The height of the video in pixels. + * @default + */ + this.height = 0; + + /** + * @property {number} type - The const type of this object. + * @default + */ + this.type = Phaser.VIDEO; + + /** + * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. + */ + this.disableTextureUpload = false; + + /** + * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. + * @default + */ + this.touchLocked = false; + + /** + * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. + */ + this.onPlay = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. + */ + this.onChangeSource = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. + */ + this.onComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam. + */ + this.onAccess = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. + */ + this.onError = new Phaser.Signal(); + + /** + * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. + * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. + * @property {Phaser.Signal} onTimeout + */ + this.onTimeout = new Phaser.Signal(); + + /** + * This signal is dispatched when the Video is unlocked. + * @property {Phaser.Signal} onTouchUnlock + */ + this.onTouchUnlock = new Phaser.Signal(); + + /** + * Start playing the video when it's unlocked. + * @property {boolean} playWhenUnlocked + * @default + */ + this.playWhenUnlocked = true; + + /** + * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. + * @default + */ + this.timeout = 15000; + + /** + * @property {integer} _timeOutID - setTimeout ID. + * @private + */ + this._timeOutID = null; + + /** + * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document. + */ + this.video = null; + + /** + * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. + */ + this.videoStream = null; + + /** + * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam. + */ + this.isStreaming = false; + + /** + * When starting playback of a video Phaser will monitor its readyState using a setTimeout call. + * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * @property {integer} retryLimit + * @default + */ + this.retryLimit = 20; + + /** + * @property {integer} retry - The current retry attempt. + * @default + */ + this.retry = 0; + + /** + * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video. + * @default + */ + this.retryInterval = 500; + + /** + * @property {integer} _retryID - The callback ID of the retry setTimeout. + * @private + */ + this._retryID = null; + + /** + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ + this._codeMuted = false; + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ + this._muted = false; + + /** + * @property {boolean} _codePaused - Internal paused tracking var. + * @private + * @default + */ + this._codePaused = false; + + /** + * @property {boolean} _paused - Internal paused tracking var. + * @private + * @default + */ + this._paused = false; + + /** + * @property {boolean} _pending - Internal var tracking play pending. + * @private + * @default + */ + this._pending = false; + + /** + * @property {boolean} _pendingChangeSource - Internal var tracking play pending. + * @private + * @default + */ + this._pendingChangeSource = false; + + /** + * @property {boolean} _autoplay - Internal var tracking autoplay when changing source. + * @private + * @default + */ + this._autoplay = false; + + /** + * @property {function} _endCallback - The addEventListener ended function. + * @private + */ + this._endCallback = null; + + /** + * @property {function} _playCallback - The addEventListener playing function. + * @private + */ + this._playCallback = null; + + if (key && this.game.cache.checkVideoKey(key)) + { + var _video = this.game.cache.getVideo(key); + + if (_video.isBlob) + { + this.createVideoFromBlob(_video.data); + } + else + { + this.video = _video.data; + } + + this.width = this.video.videoWidth; + this.height = this.video.videoHeight; + } + else if (url) + { + this.createVideoFromURL(url, false); + } + + /** + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ + if (this.video && !url) + { + this.baseTexture = new PIXI.BaseTexture(this.video, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + else + { + this.baseTexture = new PIXI.BaseTexture(Phaser.Cache.DEFAULT.baseTexture.source, null, this.game.resolution); + this.baseTexture.forceLoaded(this.width, this.height); + } + + /** + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ + this.texture = new PIXI.Texture(this.baseTexture); + + /** + * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering. + * @default + */ + this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video'); + + this.texture.setFrame(this.textureFrame); + + this.texture.valid = false; + + if (key !== null && this.video) + { + this.texture.valid = this.video.canplay; + } + + /** + * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). + * When called the BitmapData is updated with a grab taken from the current video playing or active video stream. + * If Phaser has been compiled without BitmapData support this property will always be `null`. + * + * @property {Phaser.BitmapData} snapshot + * @readOnly + */ + this.snapshot = null; + + if (Phaser.BitmapData) + { + this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height); + } + + if (this.game.device.needsTouchUnlock()) + { + this.setTouchLock(); + } + else + { + if (_video) + { + _video.locked = false; + } + } + +}; + +Phaser.Video.prototype = { + + /** + * Connects to an external media stream for the webcam, rather than using a local one. + * + * @method Phaser.Video#connectToMediaStream + * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses. + * @param {MediaStream} stream - The Video Stream data. + * @return {Phaser.Video} This Video object for method chaining. + */ + connectToMediaStream: function (video, stream) { + + if (video && stream) + { + this.video = video; + this.videoStream = stream; + + this.isStreaming = true; + this.baseTexture.source = this.video; + this.updateTexture(null, this.video.videoWidth, this.video.videoHeight); + + this.onAccess.dispatch(this); + } + + return this; + + }, + + /** + * Instead of playing a video file this method allows you to stream video data from an attached webcam. + * + * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam. + * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream. + * + * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError + * or MediaStreamError event. + * + * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions. + * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device. + * You can listen for this with the onChangeSource signal. + * + * @method Phaser.Video#startMediaStream + * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream. + * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source. + * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source. + * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia. + */ + startMediaStream: function (captureAudio, width, height) { + + if (captureAudio === undefined) { captureAudio = false; } + if (width === undefined) { width = null; } + if (height === undefined) { height = null; } + + if (!this.game.device.getUserMedia) + { + this.onError.dispatch(this, 'No getUserMedia'); + return false; + } + + if (this.videoStream !== null) + { + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + this.videoStream.stop(); + } + } + + this.removeVideoElement(); + + this.video = document.createElement("video"); + this.video.setAttribute('autoplay', 'autoplay'); + + if (width !== null) + { + this.video.width = width; + } + + if (height !== null) + { + this.video.height = height; + } + + // Request access to the webcam + + this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout); + + try { + navigator.getUserMedia( + { "audio": captureAudio, "video": true }, + this.getUserMediaSuccess.bind(this), + this.getUserMediaError.bind(this) + ); + } + catch (error) + { + this.getUserMediaError(error); + } + + return this; + + }, + + /** + * @method Phaser.Video#getUserMediaTimeout + * @private + */ + getUserMediaTimeout: function () { + + clearTimeout(this._timeOutID); + + this.onTimeout.dispatch(this); + + }, + + /** + * @method Phaser.Video#getUserMediaError + * @private + */ + getUserMediaError: function (event) { + + clearTimeout(this._timeOutID); + + this.onError.dispatch(this, event); + + }, + + /** + * @method Phaser.Video#getUserMediaSuccess + * @private + */ + getUserMediaSuccess: function (stream) { + + clearTimeout(this._timeOutID); + + // Attach the stream to the video + this.videoStream = stream; + + // Set the source of the video element with the stream from the camera + if (this.video.mozSrcObject !== undefined) + { + this.video.mozSrcObject = stream; + } + else + { + this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; + } + + var self = this; + + this.video.onloadeddata = function () { + + var retry = 10; + + function checkStream () { + + if (retry > 0) + { + if (self.video.videoWidth > 0) + { + // Patch for Firefox bug where the height can't be read from the video + var width = self.video.videoWidth; + var height = self.video.videoHeight; + + if (isNaN(self.video.videoHeight)) + { + height = width / (4/3); + } + + self.video.play(); + + self.isStreaming = true; + self.baseTexture.source = self.video; + self.updateTexture(null, width, height); + self.onAccess.dispatch(self); + } + else + { + window.setTimeout(checkStream, 500); + } + } + else + { + console.warn('Unable to connect to video stream. Webcam error?'); + } + + retry--; + } + + checkStream(); + + }; + + }, + + /** + * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format. + * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience. + * + * @method Phaser.Video#createVideoFromBlob + * @param {Blob} blob - The Blob containing the video data. + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromBlob: function (blob) { + + var _this = this; + + this.video = document.createElement("video"); + this.video.controls = false; + this.video.setAttribute('autoplay', 'autoplay'); + this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true); + this.video.src = window.URL.createObjectURL(blob); + this.video.canplay = true; + + return this; + + }, + + /** + * Creates a new Video element from the given URL. + * + * @method Phaser.Video#createVideoFromURL + * @param {string} url - The URL of the video. + * @param {boolean} [autoplay=false] - Automatically start the video? + * @return {Phaser.Video} This Video object for method chaining. + */ + createVideoFromURL: function (url, autoplay) { + + if (autoplay === undefined) { autoplay = false; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + if (this.texture) + { + this.texture.valid = false; + } + + this.video = document.createElement("video"); + this.video.controls = false; + + if (autoplay) + { + this.video.setAttribute('autoplay', 'autoplay'); + } + + this.video.src = url; + + this.video.canplay = true; + + this.video.load(); + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.key = url; + + return this; + + }, + + /** + * Called automatically if the video source changes and updates the internal texture dimensions. + * Then dispatches the onChangeSource signal. + * + * @method Phaser.Video#updateTexture + * @param {object} [event] - The event which triggered the texture update. + * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used. + * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used. + */ + updateTexture: function (event, width, height) { + + var change = false; + + if (width === undefined || width === null) { width = this.video.videoWidth; change = true; } + if (height === undefined || height === null) { height = this.video.videoHeight; } + + this.width = width; + this.height = height; + + if (this.baseTexture.source !== this.video) + { + this.baseTexture.source = this.video; + } + + this.baseTexture.forceLoaded(width, height); + + this.texture.frame.resize(width, height); + + this.texture.width = width; + this.texture.height = height; + + this.texture.valid = true; + + if (this.snapshot) + { + this.snapshot.resize(width, height); + } + + if (change && this.key !== null) + { + this.onChangeSource.dispatch(this, width, height); + + if (this._autoplay) + { + this.video.play(); + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + } + + }, + + /** + * Called when the video completes playback (reaches and ended state). + * Dispatches the Video.onComplete signal. + * + * @method Phaser.Video#complete + */ + complete: function () { + + this.onComplete.dispatch(this); + + }, + + /** + * Starts this video playing. + * + * If the video is already playing, or has been queued to play with `changeSource` then this method just returns. + * + * @method Phaser.Video#play + * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. + * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate. + * @return {Phaser.Video} This Video object for method chaining. + */ + play: function (loop, playbackRate) { + + if (this._pendingChangeSource) + { + return this; + } + + if (loop === undefined) { loop = false; } + if (playbackRate === undefined) { playbackRate = 1; } + + if (this.game.sound.onMute) + { + this.game.sound.onMute.add(this.setMute, this); + this.game.sound.onUnMute.add(this.unsetMute, this); + + if (this.game.sound.mute) + { + this.setMute(); + } + } + + this.game.onPause.add(this.setPause, this); + this.game.onResume.add(this.setResume, this); + + this._endCallback = this.complete.bind(this); + + this.video.addEventListener('ended', this._endCallback, true); + this.video.addEventListener('webkitendfullscreen', this._endCallback, true); + + if (loop) + { + this.video.loop = 'loop'; + } + else + { + this.video.loop = ''; + } + + this.video.playbackRate = playbackRate; + + if (this.touchLocked) + { + this._pending = true; + } + else + { + this._pending = false; + + if (this.key !== null) + { + if (this.video.readyState !== 4) + { + this.retry = this.retryLimit; + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + this._playCallback = this.playHandler.bind(this); + this.video.addEventListener('playing', this._playCallback, true); + } + } + + this.video.play(); + + this.onPlay.dispatch(this, loop, playbackRate); + } + + return this; + + }, + + /** + * Called when the video starts to play. Updates the texture. + * + * @method Phaser.Video#playHandler + * @private + */ + playHandler: function () { + + this.video.removeEventListener('playing', this._playCallback, true); + + this.updateTexture(); + + }, + + /** + * Stops the video playing. + * + * This removes all locally set signals. + * + * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead. + * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to + * call `Video.destroy` instead. + * + * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam. + * + * @method Phaser.Video#stop + * @return {Phaser.Video} This Video object for method chaining. + */ + stop: function () { + + if (this.game.sound.onMute) + { + this.game.sound.onMute.remove(this.setMute, this); + this.game.sound.onUnMute.remove(this.unsetMute, this); + } + + this.game.onPause.remove(this.setPause, this); + this.game.onResume.remove(this.setResume, this); + + // Stream or file? + + if (this.isStreaming) + { + if (this.video.mozSrcObject) + { + this.video.mozSrcObject.stop(); + this.video.src = null; + } + else + { + this.video.src = ''; + + if (this.videoStream['active']) + { + this.videoStream.active = false; + } + else + { + if (this.videoStream.getTracks) + { + this.videoStream.getTracks().forEach(function (track) { + track.stop(); + }); + } + else + { + this.videoStream.stop(); + } + } + } + + this.videoStream = null; + this.isStreaming = false; + } + else + { + this.video.removeEventListener('ended', this._endCallback, true); + this.video.removeEventListener('webkitendfullscreen', this._endCallback, true); + this.video.removeEventListener('playing', this._playCallback, true); + + if (this.touchLocked) + { + this._pending = false; + } + else + { + this.video.pause(); + } + } + + return this; + + }, + + /** + * Updates the given Display Objects so they use this Video as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.Video#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.Video} This Video object for method chaining. + */ + add: function (object) { + + if (Array.isArray(object)) + { + for (var i = 0; i < object.length; i++) + { + if (object[i]['loadTexture']) + { + object[i].loadTexture(this); + } + } + } + else + { + object.loadTexture(this); + } + + return this; + + }, + + /** + * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. + * + * @method Phaser.Video#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ + addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { + + scaleX = scaleX || 1; + scaleY = scaleY || 1; + + var image = this.game.add.image(x, y, this); + + image.anchor.set(anchorX, anchorY); + image.scale.set(scaleX, scaleY); + + return image; + + }, + + /** + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set Video.disableTextureUpload to `true`. + * + * @method Phaser.Video#render + */ + render: function () { + + if (!this.disableTextureUpload && this.playing) + { + this.baseTexture.dirty(); + } + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#setMute + * @private + */ + setMute: function () { + + if (this._muted) + { + return; + } + + this._muted = true; + + this.video.muted = true; + + }, + + /** + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#unsetMute + * @private + */ + unsetMute: function () { + + if (!this._muted || this._codeMuted) + { + return; + } + + this._muted = false; + + this.video.muted = false; + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setPause + * @private + */ + setPause: function () { + + if (this._paused || this.touchLocked) + { + return; + } + + this._paused = true; + + this.video.pause(); + + }, + + /** + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setResume + * @private + */ + setResume: function () { + + if (!this._paused || this._codePaused || this.touchLocked) + { + return; + } + + this._paused = false; + + if (!this.video.ended) + { + this.video.play(); + } + + }, + + /** + * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it. + * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over" + * split into three different Video objects, then you will need the user to touch-unlock every single one of them. + * + * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains + * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again. + * + * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate. + * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it + * cannot render the new video on iOS (desktop browsers cope better). + * + * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know + * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state + * are adopted automatically by the new video. + * + * @method Phaser.Video#changeSource + * @param {string} src - The new URL to change the video.src to. + * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated? + * @return {Phaser.Video} This Video object for method chaining. + */ + changeSource: function (src, autoplay) { + + if (autoplay === undefined) { autoplay = true; } + + // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) + this.texture.valid = false; + + this.video.pause(); + + this._pendingChangeSource = true; + + this.retry = this.retryLimit; + + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + + this.video.src = src; + + this.video.load(); + + this._autoplay = autoplay; + + if (!autoplay) + { + this.paused = true; + } + + return this; + + }, + + /** + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.Video#checkVideoProgress + * @private + */ + checkVideoProgress: function () { + + // if (this.video.readyState === 2 || this.video.readyState === 4) + if (this.video.readyState === 4) + { + this._pendingChangeSource = false; + + // We've got enough data to update the texture for playback + this.updateTexture(); + } + else + { + this.retry--; + + if (this.retry > 0) + { + this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval); + } + else + { + console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming); + } + } + + }, + + /** + * Sets the Input Manager touch callback to be Video.unlock. + * Required for mobile video unlocking. Mostly just used internally. + * + * @method Phaser.Video#setTouchLock + */ + setTouchLock: function () { + + this.game.input.addTouchLockCallback(this.unlock, this, true); + this.touchLocked = true; + + }, + + /** + * Enables the video on mobile devices, usually after the first touch. + * If the SoundManager hasn't been unlocked then this will automatically unlock that as well. + * Only one video can be pending unlock at any one time. + * + * @method Phaser.Video#unlock + */ + unlock: function () { + + this.touchLocked = false; + + if (this.playWhenUnlocked) + { + this.video.play(); + + this.onPlay.dispatch(this, this.loop, this.playbackRate); + } + + if (this.key) + { + var _video = this.game.cache.getVideo(this.key); + + if (_video && !_video.isBlob) + { + _video.locked = false; + } + } + + this.onTouchUnlock.dispatch(this); + + return true; + + }, + + /** + * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData. + * + * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw. + * + * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy. + * + * @method Phaser.Video#grab + * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false. + * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining. + */ + grab: function (clear, alpha, blendMode) { + + if (clear === undefined) { clear = false; } + if (alpha === undefined) { alpha = 1; } + if (blendMode === undefined) { blendMode = null; } + + if (this.snapshot === null) + { + console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable'); + return; + } + + if (clear) + { + this.snapshot.cls(); + } + + this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode); + + return this.snapshot; + + }, + + /** + * Removes the Video element from the DOM by calling parentNode.removeChild on itself. + * Also removes the autoplay and src attributes and nulls the reference. + * + * @method Phaser.Video#removeVideoElement + */ + removeVideoElement: function () { + + if (!this.video) + { + return; + } + + if (this.video.parentNode) + { + this.video.parentNode.removeChild(this.video); + } + + while (this.video.hasChildNodes()) + { + this.video.removeChild(this.video.firstChild); + } + + this.video.removeAttribute('autoplay'); + this.video.removeAttribute('src'); + + this.video = null; + + }, + + /** + * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`. + * If any Sprites are using this Video as their texture it is up to you to manage those. + * + * @method Phaser.Video#destroy + */ + destroy: function () { + + this.stop(); + + this.removeVideoElement(); + + if (this.touchLocked) + { + this.game.input.touch.removeTouchLockCallback(this.unlock, this); + } + + if (this._retryID) + { + window.clearTimeout(this._retryID); + } + + } + +}; + +/** +* @name Phaser.Video#currentTime +* @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time. +*/ +Object.defineProperty(Phaser.Video.prototype, "currentTime", { + + get: function () { + + return (this.video) ? this.video.currentTime : 0; + + }, + + set: function (value) { + + this.video.currentTime = value; + + } + +}); + +/** +* @name Phaser.Video#duration +* @property {number} duration - The duration of the video in seconds. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "duration", { + + get: function () { + + return (this.video) ? this.video.duration : 0; + + } + +}); + +/** +* @name Phaser.Video#progress +* @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "progress", { + + get: function () { + + return (this.video) ? (this.video.currentTime / this.video.duration) : 0; + + } + +}); + +/** +* @name Phaser.Video#mute +* @property {boolean} mute - Gets or sets the muted state of the Video. +*/ +Object.defineProperty(Phaser.Video.prototype, "mute", { + + get: function () { + + return this._muted; + + }, + + set: function (value) { + + value = value || null; + + if (value) + { + if (this._muted) + { + return; + } + + this._codeMuted = true; + this.setMute(); + } + else + { + if (!this._muted) + { + return; + } + + this._codeMuted = false; + this.unsetMute(); + } + } + +}); + +/** +* Gets or sets the paused state of the Video. +* If the video is still touch locked (such as on iOS devices) this call has no effect. +* +* @name Phaser.Video#paused +* @property {boolean} paused +*/ +Object.defineProperty(Phaser.Video.prototype, "paused", { + + get: function () { + + return this._paused; + + }, + + set: function (value) { + + value = value || null; + + if (this.touchLocked) + { + return; + } + + if (value) + { + if (this._paused) + { + return; + } + + this._codePaused = true; + this.setPause(); + } + else + { + if (!this._paused) + { + return; + } + + this._codePaused = false; + this.setResume(); + } + } + +}); + +/** +* @name Phaser.Video#volume +* @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. +*/ +Object.defineProperty(Phaser.Video.prototype, "volume", { + + get: function () { + + return (this.video) ? this.video.volume : 1; + + }, + + set: function (value) { + + if (value < 0) + { + value = 0; + } + else if (value > 1) + { + value = 1; + } + + if (this.video) + { + this.video.volume = value; + } + + } + +}); + +/** +* @name Phaser.Video#playbackRate +* @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing. +*/ +Object.defineProperty(Phaser.Video.prototype, "playbackRate", { + + get: function () { + + return (this.video) ? this.video.playbackRate : 1; + + }, + + set: function (value) { + + if (this.video) + { + this.video.playbackRate = value; + } + + } + +}); + +/** +* Gets or sets if the Video is set to loop. +* Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. +* If the video isn't yet set this will always return false. +* +* @name Phaser.Video#loop +* @property {boolean} loop +*/ +Object.defineProperty(Phaser.Video.prototype, "loop", { + + get: function () { + + return (this.video) ? this.video.loop : false; + + }, + + set: function (value) { + + if (value && this.video) + { + this.video.loop = 'loop'; + } + else if (this.video) + { + this.video.loop = ''; + } + + } + +}); + +/** +* @name Phaser.Video#playing +* @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false. +* @readOnly +*/ +Object.defineProperty(Phaser.Video.prototype, "playing", { + + get: function () { + + return (this.video) ? !(this.video.paused && this.video.ended) : false; + + } + +}); + +Phaser.Video.prototype.constructor = Phaser.Video; + +/* global Phaser:true */ +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + +// Pixi expects these globals to exist + +if (PIXI.blendModes === undefined) +{ + PIXI.blendModes = Phaser.blendModes; +} + +if (PIXI.scaleModes === undefined) +{ + PIXI.scaleModes = Phaser.scaleModes; +} + +if (PIXI.Texture.emptyTexture === undefined) +{ + PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture()); +} + +if (PIXI.DisplayObject._tempMatrix === undefined) +{ + PIXI.DisplayObject._tempMatrix = new Phaser.Matrix(); +} + +PIXI.TextureSilentFail = true; + +// Required by Particle Storm +PIXI.canUseNewCanvasBlendModes = function () { + return Phaser.Device.canUseMultiply; +}; + +/** +* @author Richard Davey +* @copyright 2016 Photon Storm Ltd. +* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} +*/ + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = Phaser; + } + exports.Phaser = Phaser; + } else if (typeof define !== 'undefined' && define.amd) { + define('Phaser', (function() { return root.Phaser = Phaser; })() ); + } else { + root.Phaser = Phaser; + } + + return Phaser; +}).call(this); + +/* +* "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer +*/ diff --git a/Iteration Sequence 2/js/phaser.map b/Iteration Sequence 2/js/phaser.map new file mode 100644 index 000000000..70723bbf8 --- /dev/null +++ b/Iteration Sequence 2/js/phaser.map @@ -0,0 +1 @@ +{"version":3,"sources":["phaser.js"],"names":["e","exports","module","f","window","global","self","p2","t","n","r","s","o","u","a","require","i","Error","call","length","1","_dereq_","Line","Scalar","lineInt","l1","l2","precision","a1","b1","c1","a2","b2","c2","det","eq","segmentsIntersect","p1","q1","q2","dx","dy","da","db","./Scalar","2","Point","area","b","c","left","leftOn","right","rightOn","tmpPoint1","tmpPoint2","collinear","thresholdAngle","ab","bc","dot","magA","Math","sqrt","magB","acos","sqdist","3","Polygon","this","vertices","getIntersectionPoint","delta","prototype","at","v","first","last","clear","append","poly","from","to","push","makeCCW","br","reverse","tmp","N","pop","isReflex","tmpLine1","tmpLine2","canSee","p","dist","copy","j","targetPoly","k","getCutEdges","min","tmp1","tmp2","tmpPoly","nDiags","Number","MAX_VALUE","decomp","edges","slice","cutEdges","Array","polys","cutEdge","result","splice","indexOf","isSimple","path","quickDecomp","reflexVertices","steinerPoints","maxlevel","level","upperInt","lowerInt","upperDist","lowerDist","d","closestDist","upperIndex","lowerIndex","closestIndex","lowerPoly","upperPoly","console","warn","removeCollinearPoints","num","./Line","./Point","4","abs","5","./Polygon","6","name","version","description","author","keywords","main","engines","node","repository","type","url","bugs","licenses","devDependencies","grunt","grunt-contrib-jshint","grunt-contrib-nodeunit","grunt-contrib-uglify","grunt-contrib-watch","grunt-browserify","grunt-contrib-concat","dependencies","poly-decomp","7","AABB","options","lowerBound","vec2","create","upperBound","setFromPoints","points","position","angle","skinSize","l","rotate","cosAngle","cos","sinAngle","sin","x","y","add","aabb","extend","overlaps","u1","u2","containsPoint","point","overlapsRay","ray","dirFracX","direction","dirFracY","t1","t2","t3","t4","tmin","max","tmax","../math/vec2","../utils/Utils","8","Broadphase","world","boundingVolumeType","Body","BOUNDING_CIRCLE","setWorld","getCollisionPairs","boundingRadiusCheck","bodyA","bodyB","sub","d2","squaredLength","boundingRadius","aabbCheck","getAABB","boundingVolumeCheck","canCollide","KINEMATIC","STATIC","sleepState","SLEEPING","NAIVE","SAP","../objects/Body","9","NaiveBroadphase","constructor","bodies","Ncolliding","bi","bj","aabbQuery","aabbNeedsUpdate","updateAABB","../collision/Broadphase","../shapes/Circle","../shapes/Particle","../shapes/Plane","../shapes/Shape","10","Narrowphase","contactEquations","frictionEquations","enableFriction","enabledEquations","slipForce","frictionCoefficient","surfaceVelocity","contactEquationPool","ContactEquationPool","size","frictionEquationPool","FrictionEquationPool","restitution","stiffness","Equation","DEFAULT_STIFFNESS","relaxation","DEFAULT_RELAXATION","frictionStiffness","frictionRelaxation","enableFrictionReduction","collidingBodiesLastStep","TupleDictionary","contactSkinSize","setConvexToCapsuleShapeMiddle","convexShape","capsuleShape","set","radius","pointInConvex","worldPoint","convexOffset","convexAngle","worldVertex0","pic_worldVertex0","worldVertex1","pic_worldVertex1","r0","pic_r0","r1","pic_r1","verts","lastCross","v0","v1","cross","crossLength","Circle","Convex","Shape","Box","yAxis","fromValues","tmp3","tmp4","tmp5","tmp6","tmp7","tmp8","tmp9","tmp10","tmp11","tmp12","tmp13","tmp14","tmp15","tmp16","tmp17","tmp18","tmpArray","bodiesOverlap_shapePositionA","bodiesOverlap_shapePositionB","bodiesOverlap","shapePositionA","shapePositionB","Nshapesi","shapes","shapeA","toWorldFrame","Nshapesj","shapeB","collidedLastStep","id1","id","id2","get","reset","eqs","ce","fe","release","createContactEquation","firstImpact","needsUpdate","enabled","offset","createFrictionEquation","setSlipForce","relativeVelocity","createFrictionFromContact","contactPointA","contactPointB","rotate90cw","normalA","createFrictionFromAverage","numContacts","invNumContacts","scale","normalize","LINE","CONVEX","convexLine","convexBody","lineBody","lineShape","lineOffset","lineAngle","justTest","BOX","lineBox","boxBody","boxShape","boxOffset","boxAngle","convexCapsule_tempRect","width","height","convexCapsule_tempVec","CAPSULE","convexCapsule","convexPosition","capsuleBody","capsulePosition","capsuleAngle","circlePos","result1","circleConvex","result2","convexConvex","lineCapsule","linePosition","capsuleCapsule_tempVec1","capsuleCapsule_tempVec2","capsuleCapsule_tempRect1","capsuleCapsule","si","xi","ai","sj","xj","aj","circlePosi","circlePosj","enableFrictionBefore","circleCircle","rect","lineLine","positionA","angleA","positionB","angleB","PLANE","planeLine","planeBody","planeShape","planeOffset","planeAngle","worldVertex01","worldVertex11","worldEdge","worldEdgeUnit","worldNormal","worldTangent","PARTICLE","particleCapsule","particleBody","particleShape","particlePosition","particleAngle","circleLine","CIRCLE","circleBody","circleShape","circleOffset","circleAngle","lineRadius","circleRadius","orthoDist","lineToCircleOrthoUnit","projectedPoint","centerDist","lineToCircle","lineEndToLineRadius","radiusSum","pos","pos0","pos1","pow","circleCapsule","worldVertex","closestEdgeProjectedPoint","candidate","candidateDist","minCandidate","found","minCandidateDistance","candidateDistance","localVertex","particleConvex","particleOffset","convexToparticle","minEdgeNormal","offsetA","offsetB","radiusA","radiusB","planeConvex","numReported","particlePlane","circleParticle","planeCapsule_tmpCircle","planeCapsule_tmp1","planeCapsule_tmp2","planeCapsule","capsuleOffset","end1","end2","circle","numContacts1","circlePlane","numContacts2","numTotal","planeToCircle","temp","contact","sepAxis","worldPoint0","worldPoint1","penetrationVec","findSeparatingAxis","closestEdge1","getClosestEdge","closestEdge2","closestEdgeA","closestEdgeB","insideNumEdges","pcoa_tmp1","projectConvexOntoAxis","worldAxis","value","localAxis","fsa_tmp1","fsa_tmp2","fsa_tmp3","fsa_tmp4","fsa_tmp5","fsa_tmp6","offset1","angle1","offset2","angle2","maxDist","overlap","edge","normal","span1","span2","gce_tmp1","gce_tmp2","gce_tmp3","axis","flip","closestEdge","maxDot","circleHeightfield_candidate","circleHeightfield_dist","circleHeightfield_v0","circleHeightfield_v1","circleHeightfield_minCandidate","circleHeightfield_worldNormal","circleHeightfield_minCandidateNormal","HEIGHTFIELD","circleHeightfield","hfBody","hfShape","hfPos","hfAngle","data","heights","w","elementWidth","minCandidateNormal","idxA","floor","idxB","ceil","PI","convexHeightfield_v0","convexHeightfield_v1","convexHeightfield_tilePos","convexHeightfield_tempConvexShape","convexHeightfield","convexPos","tilePos","tileConvex","../equations/ContactEquation","../equations/Equation","../equations/FrictionEquation","../shapes/Box","../shapes/Convex","../utils/ContactEquationPool","../utils/FrictionEquationPool","../utils/TupleDictionary","11","Ray","checkCollisionResponse","undefined","skipBackfaces","collisionMask","collisionGroup","mode","ANY","callback","update","distanceFromIntersectionSquared","intersect","squaredDistance","CLOSEST","ALL","intersectBodies","shouldStop","body","intersectBody","intersectBody_worldPosition","collisionResponse","worldPosition","shape","worldAngle","intersectShape","_currentBody","_currentShape","raycast","reportIntersection","fraction","faceIndex","hasHit","../collision/AABB","../collision/RaycastResult","12","RaycastResult","isStopped","getHitDistance","distance","getHitPoint","out","lerp","stop","../collision/Ray","13","SAPBroadphase","axisList","axisIndex","that","_addBodyHandler","_removeBodyHandler","idx","Utils","appendArray","off","on","sortAxisList","sortList","14","Constraint","defaults","collideConnected","wakeUpBodies","equations","wakeUp","DISTANCE","GEAR","LOCK","PRISMATIC","REVOLUTE","setStiffness","setRelaxation","15","DistanceConstraint","localAnchorA","localAnchorB","worldAnchorA","worldAnchorB","maxForce","ri","rj","computeGq","setMaxForce","upperLimitEnabled","upperLimit","lowerLimitEnabled","lowerLimit","normalEquation","G","violating","minForce","rixn","rjxn","getMaxForce","./Constraint","16","GearConstraint","ratio","AngleLockEquation","maxTorque","setMaxTorque","setRatio","torque","getMaxTorque","../equations/AngleLockEquation","17","LockConstraint","localAngleB","rot","g","localOffsetB","force","xAxis","18","PrismaticConstraint","localAxisA","trans","gg","updateJacobian","disableRotationalLock","RotationalLockEquation","velocity","upperLimitEquation","ContactEquation","lowerLimitEquation","motorEquation","motorEnabled","motorSpeed","computeGW","vi","vj","wi","angularVelocity","wj","gmult","worldAxisA","orientedAnchorA","orientedAnchorB","relPosition","enableMotor","disableMotor","setLimits","lower","upper","../equations/RotationalLockEquation","19","RevoluteConstraint","pivotA","pivotB","worldPivot","localPivotA","localPivotB","worldPivotA","worldPivotB","RotationalVelocityEquation","relAngle","setMotorSpeed","speed","getMotorSpeed","../equations/RotationalVelocityEquation","20","./Equation","21","computeB","h","GW","Gq","computeGiMf","relVel","getVelocityAlongNormal","getVelocityAtPoint","subtract","22","ARRAY_TYPE","epsilon","timeStep","multiplier","qi","qj","computeGWlambda","vlambda","wlambda","iMfi","iMfj","fi","ti","angularForce","fj","tj","invMassi","invMassSolve","invMassj","invIi","invInertiaSolve","invIj","multiply","massMultiplier","computeGiMGt","addToWlambda_temp","addToWlambda_Gi","addToWlambda_Gj","addToWlambda","deltalambda","Gi","Gj","computeInvC","eps","23","FrictionEquation","getSlipForce","24","worldVectorA","worldVectorB","25","GiMf","26","EventEmitter","listener","context","_listeners","listeners","has","index","emit","event","listenerArray","target","27","ContactMaterial","materialA","materialB","Material","idCounter","friction","./Material","28","29","PolyK","GetArea","sum","Triangulate","tgs","avl","al","i0","i1","i2","ax","ay","bx","by","cx","cy","earFound","_convex","_PointInTriangle","px","py","v0x","v0y","v1x","v1y","v2x","v2y","dot00","dot01","dot02","dot11","dot12","invDenom","30","crossVZ","vec","zcomp","crossZV","toLocalFrame","framePosition","frameAngle","toGlobalFrame","localPoint","vectorToLocalFrame","worldVector","vectorToGlobalFrame","localVector","centroid","clone","mul","divide","div","sqrDist","len","sqrLen","negate","str","reflect","vector","getLineSegmentsIntersection","p0","p3","getLineSegmentsIntersectionFraction","s1_x","s1_y","s2_x","s2_y","31","_idCounter","mass","invMass","inertia","invInertia","fixedRotation","fixedX","fixedY","interpolatedPosition","interpolatedAngle","previousPosition","previousAngle","damping","angularDamping","DYNAMIC","allowSleep","wantsToSleep","AWAKE","sleepSpeedLimit","sleepTimeLimit","gravityScale","idleTime","timeLastSleepy","ccdSpeedThreshold","ccdIterations","concavePath","_wakeUpAfterNarrowphase","updateMassProperties","updateSolveMassProperties","setDensity","density","totalArea","getArea","shapeAABB","bodyAngle","computeAABB","updateBoundingRadius","addShape","removeShape","m","I","r2","computeMomentOfInertia","applyForce","relativePoint","rotForce","Body_applyForce_forceWorld","Body_applyForce_pointWorld","Body_applyForce_pointLocal","applyForceLocal","localForce","worldForce","vectorToWorldFrame","Body_applyImpulse_velo","applyImpulse","impulseVector","velo","rotVelo","Body_applyImpulse_impulseWorld","Body_applyImpulse_pointWorld","Body_applyImpulse_pointLocal","applyImpulseLocal","localImpulse","worldImpulse","fromPolygon","convexes","optimalDecomp","cm","centerOfMass","updateTriangles","updateCenterOfMass","adjustCenterOfMass","adjustCenterOfMass_tmp2","adjustCenterOfMass_tmp3","adjustCenterOfMass_tmp4","offset_times_area","setZeroForce","resetConstraintVelocity","addConstraintVelocity","applyDamping","dt","wakeUpEvent","sleep","sleepEvent","sleepTick","time","dontSleep","SLEEPY","overlapKeeper","bodiesAreOverlapping","integrate_fhMinv","integrate_velodt","integrate","minv","integrateToTimeOfImpact","end","startToEnd","rememberPosition","hit","startToEndAngle","timeOfImpact","rememberAngle","iter","tmid","narrowphase","sleepyEvent","../events/EventEmitter","32","LinearSpring","Spring","setWorldAnchorA","setWorldAnchorB","getWorldAnchorA","getWorldAnchorB","worldDistance","restLength","applyForce_r","applyForce_r_unit","applyForce_u","applyForce_f","applyForce_worldAnchorA","applyForce_worldAnchorB","applyForce_ri","applyForce_rj","applyForce_tmp","r_unit","rlen","ri_x_f","rj_x_f","./Spring","33","RotationalSpring","restAngle","34","35","TopDownVehicle","chassisBody","wheels","groundBody","preStepCallback","WheelConstraint","vehicle","forwardEquation","sideEquation","steerValue","engineForce","setSideFriction","sideFriction","localForwardVector","localPosition","apply","setBrakeForce","addToWorld","addBody","wheel","addConstraint","removeFromWorld","removeBody","removeConstraint","addWheel","wheelOptions","worldVelocity","getSpeed","tmpVec","../constraints/Constraint","36","Capsule","GSSolver","Heightfield","Particle","Plane","Pool","Solver","World","Object","defineProperty","../package.json","./collision/AABB","./collision/Broadphase","./collision/NaiveBroadphase","./collision/Narrowphase","./collision/Ray","./collision/RaycastResult","./collision/SAPBroadphase","./constraints/Constraint","./constraints/DistanceConstraint","./constraints/GearConstraint","./constraints/LockConstraint","./constraints/PrismaticConstraint","./constraints/RevoluteConstraint","./equations/AngleLockEquation","./equations/ContactEquation","./equations/Equation","./equations/FrictionEquation","./equations/RotationalVelocityEquation","./events/EventEmitter","./material/ContactMaterial","./material/Material","./math/vec2","./objects/Body","./objects/LinearSpring","./objects/RotationalSpring","./objects/Spring","./objects/TopDownVehicle","./shapes/Box","./shapes/Capsule","./shapes/Circle","./shapes/Convex","./shapes/Heightfield","./shapes/Line","./shapes/Particle","./shapes/Plane","./shapes/Shape","./solver/GSSolver","./solver/Solver","./utils/ContactEquationPool","./utils/FrictionEquationPool","./utils/Pool","./utils/Utils","./world/World","37","arguments","axes","updateArea","./Convex","./Shape","38","intersectCapsule_hitPointWorld","intersectCapsule_normal","intersectCapsule_l0","intersectCapsule_l1","intersectCapsule_unit_y","hitPointWorld","l0","halfLen","diagonalLengthSquared","sqrtDelta","inv2a","d1","39","Ray_intersectSphere_intersectionPoint","Ray_intersectSphere_normal","intersectionPoint","40","isArray","triangles","polyk","tmpVec1","tmpVec2","projectOntoLocalAxis","projectOntoWorldAxis","shapeOffset","shapeAngle","polykVerts","id3","updateCenterOfMass_centroid","updateCenterOfMass_centroid_times_mass","updateCenterOfMass_a","updateCenterOfMass_b","updateCenterOfMass_c","centroid_times_mass","triangleArea","denom","numer","intersectConvex_rayStart","intersectConvex_rayEnd","intersectConvex_normal","rayStart","rayEnd","../math/polyk","41","key","maxValue","minValue","updateMaxMinValues","getLineSegment","start","getSegmentIndex","getClampedSegmentIndex","intersectHeightfield_worldNormal","intersectHeightfield_l0","intersectHeightfield_l1","intersectHeightfield_localFrom","intersectHeightfield_localTo","localFrom","localTo","42","raycast_normal","raycast_l0","raycast_l1","raycast_unit_y","43","44","intersectPlane_planePointToFrom","intersectPlane_normal","intersectPlane_len","planePointToFrom","planeToFrom","n_dot_dir","45","material","sensor","46","GS","iterations","tolerance","arrayStep","lambda","Bs","invCs","useZeroRHS","frictionIterations","usedIterations","setArrayZero","array","solve","sortEquations","maxIter","maxFrictionIter","Neq","tolSquared","Nbodies","deltalambdaTot","iterateEquation","updateMultipliers","invDt","B","invC","lambdaj","GWlambda","lambdaj_plus_deltalambda","./Solver","47","equationSortFunction","mockWorld","solveIsland","island","removeAllEquations","addEquations","getBodies","sort","addEquation","removeEquation","ISLAND","48","destroy","equation","./Pool","49","50","IslandNodePool","IslandNode","../world/IslandNode","51","IslandPool","Island","../world/Island","52","OverlapKeeper","overlappingShapesLastState","overlappingShapesCurrentState","recordPool","OverlapKeeperRecordPool","tmpDict","tmpArray1","tick","current","keys","lastObject","getByKey","setOverlapping","getNewOverlaps","getDiff","getEndOverlaps","dictA","dictB","isNewOverlap","idA","idB","getNewBodyOverlaps","getBodyDiff","getEndBodyOverlaps","accumulator","./OverlapKeeperRecord","./OverlapKeeperRecordPool","./TupleDictionary","./Utils","53","OverlapKeeperRecord","54","record","55","objects","resize","object","56","getKey","dict","57","howmany","P2_ARRAY_TYPE","Float32Array","58","bodyIds","59","IslandManager","nodePool","islandPool","islands","nodes","queue","getUnvisitedNode","Nnodes","visited","visit","bds","Neqs","bfs","root","child","neighbors","split","ni","nj","./../utils/IslandNodePool","./../utils/IslandPool","./Island","./IslandNode","60","61","springs","disabledBodyCollisionPairs","solver","islandManager","gravity","frictionGravity","useWorldGravityAsFrictionGravity","useFrictionGravityOnZeroGravity","broadphase","constraints","defaultMaterial","defaultContactMaterial","lastTimeStep","applySpringForces","applyGravity","solveConstraints","contactMaterials","stepping","bodiesToBeRemoved","islandSplit","emitImpactEvent","_constraintIdCounter","_bodyIdCounter","postStepEvent","addBodyEvent","removeBodyEvent","addSpringEvent","spring","impactEvent","contactEquation","postBroadphaseEvent","pairs","sleepMode","NO_SLEEPING","beginContactEvent","endContactEvent","preSolveEvent","BODY_SLEEPING","ISLAND_SLEEPING","constraint","addContactMaterial","contactMaterial","removeContactMaterial","getContactMaterial","cmats","step_mg","xiw","xjw","step","timeSinceLastCalled","maxSubSteps","internalStep","substeps","endOverlaps","Nsprings","np","mg","gravityLen","ignoredPairs","Nconstraints","Nresults","runNarrowphase","ev","glen","aiw","ajw","reducedMass","resolver","numFrictionBefore","numFrictionEquations","addSpring","evt","removeSpring","getBodyById","disableBodyCollision","enableBodyCollision","cs","cms","hitTest_tmp1","hitTest_tmp2","hitTest","pb","ps","NS","setGlobalStiffness","setGlobalRelaxation","tmpAABB","../../package.json","../collision/Narrowphase","../collision/SAPBroadphase","../constraints/DistanceConstraint","../constraints/GearConstraint","../constraints/LockConstraint","../constraints/PrismaticConstraint","../constraints/RevoluteConstraint","../material/ContactMaterial","../material/Material","../objects/LinearSpring","../objects/RotationalSpring","../shapes/Capsule","../shapes/Line","../solver/GSSolver","../solver/Solver","../utils/OverlapKeeper","./IslandManager","_CreateEmptyTexture","gl","scaleMode","texture","createTexture","bindTexture","TEXTURE_2D","texParameteri","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","TEXTURE_MAG_FILTER","PIXI","scaleModes","LINEAR","NEAREST","TEXTURE_MIN_FILTER","texImage2D","RGBA","UNSIGNED_BYTE","_CreateFramebuffer","textureUnit","framebuffer","createFramebuffer","depthStencilBuffer","createRenderbuffer","colorBuffer","fbStatus","activeTexture","TEXTURE0","bindFramebuffer","FRAMEBUFFER","bindRenderbuffer","RENDERBUFFER","framebufferRenderbuffer","DEPTH_STENCIL_ATTACHMENT","renderBuffer","framebufferTexture2D","COLOR_ATTACHMENT0","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","error","_fbErrors","targetTexture","DisplayObject","pivot","rotation","alpha","visible","hitArea","renderable","parent","worldAlpha","worldTransform","Phaser","Matrix","worldScale","worldRotation","filterArea","_sr","_cr","_bounds","Rectangle","_currentBounds","_mask","_cacheAsBitmap","_cacheIsDirty","children","_destroyCachedSprite","updateTransform","game","tx","ty","pt","wt","PI2","rotationCache","determ","HALF_PI","transformCallback","transformCallbackContext","preUpdate","generateTexture","resolution","renderer","bounds","getLocalBounds","renderTexture","RenderTexture","_tempMatrix","render","updateCache","_generateCachedSprite","toGlobal","toLocal","applyInverse","_renderCachedSprite","renderSession","_cachedSprite","Sprite","_renderWebGL","_renderCanvas","baseTexture","_enableMultiTextureToggle","textureIndex","tempFilters","_filters","filters","anchor","displayObjectUpdateTransform","defineProperties","worldVisible","item","mask","isMask","passes","filterPasses","_filterBlock","blendMode","blendModes","MULTIPLY","NORMAL","cacheAsBitmap","DisplayObjectContainer","ignoreChildInput","addChild","addChildAt","removeChild","swapChildren","child2","index1","getChildIndex","index2","setChildIndex","currentIndex","getChildAt","removeChildAt","removeChildren","beginIndex","endIndex","range","removed","displayObjectContainerUpdateTransform","getBounds","targetCoordinateSpace","isTargetCoordinateSpaceDisplayObject","isTargetCoordinateSpaceThisOrParent","contains","matrixCache","identityMatrix","childBounds","childMaxX","childMaxY","minX","Infinity","minY","maxX","maxY","childVisible","w0","w1","h0","h1","x1","y1","x2","y2","x3","y3","x4","y4","targetCoordinateSpaceBounds","spriteBatch","flush","filterManager","pushFilter","maskManager","pushMask","popMask","popFilter","_width","_height","defaultAnchor","Texture","emptyTexture","tint","cachedTint","tintedTexture","shader","exists","hasLoaded","onTextureUpdate","frame","setTexture","destroyBase","skipRender","valid","matrix","crop","currentBlendMode","globalCompositeOperation","blendModesCanvas","globalAlpha","smoothProperty","trim","shakeX","shakeY","cw","ch","rotated","roundPixels","setTransform","requiresReTint","CanvasTinter","getTintedTexture","drawImage","source","initDefaultShaders","CompileVertexShader","shaderSrc","_CompileShader","VERTEX_SHADER","CompileFragmentShader","FRAGMENT_SHADER","shaderType","src","join","createShader","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","log","getShaderInfoLog","compileProgram","vertexSrc","fragmentSrc","fragmentShader","vertexShader","shaderProgram","createProgram","attachShader","linkProgram","getProgramParameter","LINK_STATUS","getProgramInfoLog","PixiShader","_UID","program","textureCount","firstRun","dirty","attributes","init","initMultitexShader","MAX_TEXTURES","getParameter","MAX_TEXTURE_IMAGE_UNITS","dynamicIfs","defaultVertexSrc","useProgram","uSamplerArray","getUniformLocation","projectionVector","offsetVector","dimensions","aVertexPosition","getAttribLocation","aTextureCoord","colorAttribute","aTextureIndex","indices","tempTexture","RGB","uniform1iv","uniforms","uniformLocation","initUniforms","initDefaultShader","uSampler","usingFilter","uniform","_init","initSampler2D","glMatrix","glValueLength","glFunc","uniformMatrix2fv","uniformMatrix3fv","uniformMatrix4fv","_glTextures","textureData","magFilter","minFilter","wrapS","wrapT","format","LUMINANCE","repeat","REPEAT","pixelStorei","UNPACK_FLIP_Y_WEBGL","flipY","border","uniform1i","syncUniforms","transpose","z","_dirty","instances","updateTexture","deleteProgram","PixiFastShader","uMatrix","aPositionCoord","aScale","aRotation","StripShader","translationMatrix","attribute","PrimitiveShader","tintColor","ComplexPrimitiveShader","color","glContexts","WebGLRenderer","config","defaultRenderer","extensions","WEBGL","transparent","autoResize","preserveDrawingBuffer","clearBeforeRender","view","canvas","_contextOptions","antialias","failIfMajorPerformanceCaveat","premultipliedAlpha","stencil","projection","shaderManager","WebGLShaderManager","WebGLSpriteBatch","WebGLMaskManager","WebGLFilterManager","stencilManager","WebGLStencilManager","blendModeManager","WebGLBlendModeManager","currentBatchedTextures","drawCount","maxTextureAvailableSpace","initContext","mapBlendModes","getContext","maxTextures","maxTextureSize","MAX_TEXTURE_SIZE","glContextId","disable","DEPTH_TEST","CULL_FACE","enable","BLEND","setContext","compression","etc1","getExtension","pvrtc","s3tc","ETC1","PVRTC","S3TC","setTexturePriority","textureNameCollection","clampPot","potSize","imageCache","cache","_cache","image","imageName","base","stage","contextLost","viewport","clearColor","_bgColor","COLOR_BUFFER_BIT","camera","_shake","renderDisplayObject","displayObject","buffer","setBlendMode","begin","style","updateCompressedTexture","textureMetaData","compressedTexImage2D","glExtensionFormat","mipmap","isPowerOfTwo","LINEAR_MIPMAP_LINEAR","NEAREST_MIPMAP_NEAREST","generateMipmap","_powerOf2","compressionAlgorithm","UNPACK_PREMULTIPLY_ALPHA_WEBGL","CanvasPool","remove","blendModesWebGL","modes","ONE","ONE_MINUS_SRC_ALPHA","ADD","SRC_ALPHA","DST_ALPHA","DST_COLOR","SCREEN","OVERLAY","DARKEN","LIGHTEN","COLOR_DODGE","COLOR_BURN","HARD_LIGHT","SOFT_LIGHT","DIFFERENCE","EXCLUSION","HUE","SATURATION","COLOR","LUMINOSITY","getMaxTextureUnit","enableMultiTexture","textureArray","blendModeWebGL","blendFunc","maskData","WebGLGraphics","updateGraphics","_webGL","pushStencil","popStencil","stencilStack","count","graphics","webGLData","bindGraphics","STENCIL_TEST","STENCIL_BUFFER_BIT","colorMask","stencilFunc","ALWAYS","stencilOp","KEEP","INVERT","drawElements","TRIANGLE_FAN","UNSIGNED_SHORT","EQUAL","DECR","INCR","TRIANGLE_STRIP","_currentGraphics","complexPrimitiveShader","setShader","uniform1f","toArray","uniform2f","uniform3fv","Color","hexToRGBArray","bindBuffer","ARRAY_BUFFER","vertexAttribPointer","FLOAT","ELEMENT_ARRAY_BUFFER","indexBuffer","primitiveShader","maxAttibs","attribState","tempAttribState","stack","defaultShader","fastShader","stripShader","creatureShader","CreatureShader","setAttribs","attribs","attribId","enableVertexAttribArray","disableVertexAttribArray","_currentId","currentShader","vertSize","vertexSize","numVerts","numIndices","ArrayBuffer","positions","colors","Uint32Array","Uint16Array","lastIndexCount","drawing","currentBatchSize","currentBaseTexture","textures","shaders","sprites","Filter","vertexBuffer","createBuffer","bufferData","STATIC_DRAW","DYNAMIC_DRAW","sprite","uvs","_uvs","aX","aY","a0","b0","c0","d0","_w1","_w0","_updateUvsInverted","x0","y0","renderTilingSprite","tilingTexture","TextureUvs","tilePosition","tileScaleOffset","offsetX","offsetY","scaleX","tileScale","scaleY","stride","bufferSubData","subarray","nextTexture","nextBlendMode","nextShader","batchSize","blendSwap","shaderSwap","skip","renderBatch","startIndex","TRIANGLES","deleteBuffer","WebGLFastSpriteBatch","maxSize","renderSprite","filterStack","texturePool","initShaderBuffers","filterBlock","_filterArea","_previous_stencil_mgr","filter","FilterTexture","padding","frameBuffer","_glFilterTexture","vertexArray","uvBuffer","uvArray","inputTexture","outputTexture","filterPass","applyFilterPass","sizeX","sizeY","currentFilter","colorArray","36054","36055","36057","36061","DEFAULT","renderbufferStorage","DEPTH_STENCIL","deleteFramebuffer","deleteTexture","CanvasBuffer","clearRect","CanvasMaskManager","save","cacheAlpha","transform","CanvasGraphics","renderGraphicsMask","clip","restore","tintMethod","tintWithMultiply","fillStyle","toString","substr","fillRect","tintWithPerPixel","rgbValues","pixelData","getImageData","pixels","canHandleAlpha","putImageData","CanvasRenderer","CANVAS","refresh","Canvas","getSmoothingPrefix","navigator","isCocoonJS","screencanvas","rgba","removeView","useNew","device","canUseMultiply","BaseTexture","complete","naturalWidth","naturalHeight","forceLoaded","removeByCanvas","unloadFromGPU","glTexture","fromCanvas","TextureSilentFail","noFrame","isTiling","requiresUpdate","setFrame","onBaseTextureLoaded","_updateUvs","tw","th","define","amd","WheelEventProxy","scaleFactor","deltaMode","_scaleFactor","_deltaMode","originalEvent","VERSION","GAMES","AUTO","HEADLESS","WEBGL_MULTI","NONE","LEFT","RIGHT","UP","DOWN","SPRITE","BUTTON","IMAGE","GRAPHICS","TEXT","TILESPRITE","BITMAPTEXT","GROUP","RENDERTEXTURE","TILEMAP","TILEMAPLAYER","EMITTER","POLYGON","BITMAPDATA","CANVAS_FILTER","WEBGL_FILTER","ELLIPSE","SPRITEBATCH","RETROFONT","POINTER","ROPE","RECTANGLE","MATRIX","POINT","ROUNDEDRECTANGLE","CREATURE","VIDEO","PENDING_ATLAS","HORIZONTAL","VERTICAL","LANDSCAPE","PORTRAIT","ANGLE_UP","ANGLE_DOWN","ANGLE_LEFT","ANGLE_RIGHT","ANGLE_NORTH_EAST","ANGLE_NORTH_WEST","ANGLE_SOUTH_EAST","ANGLE_SOUTH_WEST","TOP_LEFT","TOP_CENTER","TOP_RIGHT","LEFT_TOP","LEFT_CENTER","LEFT_BOTTOM","CENTER","RIGHT_TOP","RIGHT_CENTER","RIGHT_BOTTOM","BOTTOM_LEFT","BOTTOM_CENTER","BOTTOM_RIGHT","trunc","Function","bind","thisArg","bound","args","boundArgs","concat","TypeError","F","proto","arg","forEach","fun","CheapArray","assert","assign","varArgs","hasOwn","hasOwnProperty","nextSource","nextKey","reverseString","string","getProperty","obj","parts","_getProperty","setProperties","props","setProperty","_setProperty","val","currentObj","chanceRoll","chance","random","randomChoice","choice1","choice2","parseDimension","dimension","parseInt","innerWidth","innerHeight","pad","dir","padlen","isPlainObject","nodeType","copyIsArray","deep","mixinPrototype","mixin","replace","mixinKeys","childNodes","cloneNode","diameter","_diameter","_radius","circumference","setTo","copyFrom","copyTo","dest","round","output","circumferencePoint","asDegrees","sample","steps","startAngle","endAngle","linear","offsetPoint","top","bottom","equals","intersects","degToRad","intersectsRectangle","halfWidth","halfHeight","xCornerDist","yCornerDist","intersectsLine","returnPoints","del","p0Exists","pointOnSegment","p1Exists","Ellipse","normx","normy","fromPoints","fromSprite","startSprite","endSprite","useCenter","centerX","centerY","fromAngle","rotateAround","line","asSegment","intersectsPoints","midPoint","centerOn","pointOnLine","fuzzyEqual","xMin","xMax","yMin","yMax","coordinatesOnLine","stepRate","results","sx","sy","err","e2","wrap","uc","ua","ub","empty","bx1","by1","bx2","by2","intersectionWithRectangle","edgeIntersection","closestDistance","normalAngle","fromArray","newPos","translate","tx1","identity","invert","setToPolar","azimuth","clampX","clamp","clampY","equalsXY","fuzzyEquals","fuzzyEqualsXY","angleXY","atan2","radToDeg","atan","getMagnitude","getMagnitudeSq","setMagnitude","magnitude","isZero","limit","expand","perp","rperp","normalRightHand","negative","multiplyAdd","interpolate","project","amt","projectUnit","pointslength","parse","xProp","yProp","isPoint","sortClockwise","center","_points","closed","flattened","toNumberArray","flatten","inside","ix","iy","jx","jy","calculateArea","avgHeight","floorAll","ceilAll","copyFromBounds","inflate","containsRect","intersection","intersectsRaw","union","randomX","randomY","getPoint","sides","inflatePoint","createFromBounds","containsRaw","rx","ry","rw","rh","volume","sameDimensions","NEGATIVE_INFINITY","POSITIVE_INFINITY","EmptyRectangle","RoundedRectangle","Camera","deadzone","roundPx","atLimit","totalInView","onShakeComplete","Signal","onFlashComplete","onFadeComplete","fx","_targetPosition","_edge","_position","intensity","duration","horizontal","vertical","shakeBounds","_fxDuration","_fxType","_fixedView","FOLLOW_LOCKON","FOLLOW_PLATFORMER","FOLLOW_TOPDOWN","FOLLOW_TOPDOWN_TIGHT","SHAKE_BOTH","SHAKE_HORIZONTAL","SHAKE_VERTICAL","ENABLE_FX","boot","Graphics","follow","lerpX","lerpY","helper","unfollow","focusOn","setPosition","focusOnXY","shake","flash","beginFill","drawRect","endFill","fade","updateFX","updateShake","checkBounds","elapsedMS","dispatch","rnd","frac","updateTarget","math","setBoundsToWorld","vx","vw","vy","vh","setSize","resetFX","State","make","input","load","sound","state","tweens","particles","physics","preload","loadUpdate","loadRender","preRender","paused","resumed","pauseUpdate","shutdown","StateManager","pendingState","states","_pendingState","_clearWorld","_clearCache","_created","_args","onStateChange","onInitCallback","onPreloadCallback","onCreateCallback","onUpdateCallback","onRenderCallback","onResizeCallback","onPreRenderCallback","onLoadUpdateCallback","onLoadRenderCallback","onPausedCallback","onResumedCallback","onPauseUpdateCallback","onShutDownCallback","onPause","pause","onResume","resume","autoStart","newState","isBooted","callbackContext","clearWorld","clearCache","checkState","restart","dummy","previousStateKey","clearCurrentState","setCurrentState","totalQueuedFiles","totalQueuedPacks","loadComplete","removeAll","debug","link","unlink","_kickstart","getCurrentState","elapsedTime","renderType","_bindings","_prevParams","memorize","_shouldPropagate","active","_boundDispatch","validateListener","fnName","_registerListener","isOnce","listenerContext","priority","binding","prevIndex","_indexOfListener","SignalBinding","_addBinding","execute","_priority","cur","_listener","addOnce","_destroy","getNumListeners","halt","bindings","paramsArr","forget","dispose","_this","signal","_isOnce","_signal","callCount","params","handlerReturn","detach","isBound","getListener","getSignal","prevPoint","Date","mouse","date","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","sampleRate","iChannel0","iChannel1","iChannel2","iChannel3","setResolution","pointer","toFixed","totalElapsedSeconds","anchorX","anchorY","Cache","Plugin","hasPreUpdate","hasUpdate","hasPostUpdate","hasRender","hasPostRender","postRender","PluginManager","plugins","_len","_i","plugin","postUpdate","Stage","disableVisibilityChange","currentRenderOrderID","_hiddenVar","_onChange","parseConfig","setBackgroundColor","DOM","getOffset","setUserSelect","setTouchAction","checkVisibility","document","hidden","webkitHidden","mozHidden","msHidden","visibilityChange","_onClick","hasFocus","addEventListener","onblur","onfocus","onpagehide","onpageshow","cocoonJSApp","CocoonJS","App","onSuspended","onActivated","focusLoss","focusGain","gamePaused","gameResumed","valueToColor","updateColor","removeEventListener","silent","hash","removeFromHash","Group","addToStage","enableBody","physicsBodyType","Physics","ARCADE","physicsType","alive","ignoreDestroy","pendingDestroy","classType","cursor","inputEnableChildren","updateOnlyExistingChildren","onChildInputDown","onChildInputUp","onChildInputOver","onChildInputOut","enableBodyDebug","physicsSortDirection","onDestroy","cursorIndex","fixedToCamera","cameraOffset","_sortProperty","RETURN_NONE","RETURN_TOTAL","RETURN_CHILD","RETURN_ALL","SORT_ASCENDING","SORT_DESCENDING","updateZ","addToHash","inputEnabled","events","onAddedToGroup$dispatch","addAt","addMultiple","moveAll","getAt","createMultiple","quantity","singleKey","singleFrame","align","cellWidth","cellHeight","alignIn","resetCursor","next","previous","swap","child1","bringToTop","getIndex","sendToBack","moveUp","moveDown","xy","getByName","oldChild","newChild","hasProperty","operation","checkProperty","checkAlive","checkVisible","setAll","setAllChildren","checkAll","checkAny","addAll","property","amount","subAll","multiplyAll","divideAll","kill","killAll","callAllExists","revive","reviveAll","resetAll","checkExists","resetChild","existsValue","callbackFromArray","callAll","method","methodLength","contextLength","renderOrderID","predicate","ArraySet","forEachExists","iterate","forEachAlive","forEachDead","order","ascendingSortHandler","descendingSortHandler","customSort","sortHandler","returnType","total","getFirst","getFirstExists","createIfNull","getFirstAlive","getFirstDead","loadTexture","getTop","getBottom","getClosestTo","tempDistance","getFurthestFrom","countLiving","countDead","getRandom","ArrayUtils","getRandomItem","getRandomExists","list","getAll","pick","destroyPhase","onRemovedFromGroup$dispatch","group","destroyTexture","removeBetween","scatter","shuffle","destroyChildren","soft","_definedSize","stateChange","setBounds","useBounds","wrapAll","between","Game","physicsConfig","multiTexture","isRunning","raf","net","Device","lockRender","pendingStep","stepCount","onBlur","onFocus","_paused","_codePaused","currentUpdateID","updatesThisFrame","rendersThisFrame","_deltaTime","_lastCount","_spiraling","fpsProblemNotifier","forceSingleUpdate","forceSingleRender","dropFrames","_nextFpsNotification","enableDebug","RandomDataGenerator","now","whenReady","seed","ScaleManager","setUpRenderer","GameObjectFactory","GameObjectCreator","Loader","Time","TweenManager","Input","SoundManager","Particles","Create","Net","Debug","isDisabled","showDebugHeader","RequestAnimationFrame","stopFocus","focus","isReady","onReady","hideBanner","webAudio","ie","setImageRenderingCrisp","webGL","contextRestored","webGLRendererError","cocoonJS","smoothed","addToDOM","preventDefault","clearGLTextures","updateLogic","desiredFpsMult","updateRender","slowMotion","desiredFps","slowStep","elapsed","countUpdate","countRender","enableStep","disableStep","removeFromDOM","muteOnPause","setMute","cordova","iOS","unsetMute","hitCanvas","hitContext","moveCallbacks","customCandidateHandler","customCandidateHandlerContext","pollRate","multiInputOverride","MOUSE_TOUCH_COMBINE","maxPointers","tapRate","doubleTapRate","holdRate","justPressedRate","justReleasedRate","recordPointerHistory","recordRate","recordLimit","touchLockCallbacks","pointer1","pointer2","pointer3","pointer4","pointer5","pointer6","pointer7","pointer8","pointer9","pointer10","pointers","activePointer","mousePointer","keyboard","touch","mspointer","gamepad","resetLocked","onDown","onUp","onTap","onHold","minPriorityID","interactiveItems","_localPoint","_pollCounter","_oldPosition","_x","_y","MOUSE_OVERRIDES_TOUCH","TOUCH_OVERRIDES_MOUSE","MAX_POINTERS","Pointer","PointerMode","CURSOR","addPointer","Mouse","Touch","MSPointer","Keyboard","Gamepad","_onClickTrampoline","onClickTrampoline","setInteractiveCandidateHandler","addMoveCallback","addTouchLockCallback","onEnd","removeTouchLockCallback","executeTouchLockCallbacks","cb","deleteMoveCallback","CONTACT","hard","resetSpeed","startPointer","countActivePointers","updatePointer","identifier","move","stopPointer","getPointer","isActive","getPointerFromIdentifier","getPointerFromId","pointerId","getLocalPosition","Creature","TileSprite","graphicsData","fill","processClickTrampolines","mouseDownCallback","mouseUpCallback","mouseOutCallback","mouseOverCallback","mouseWheelCallback","capture","button","wheelDelta","locked","stopOnGameOut","pointerLock","_onMouseDown","_onMouseMove","_onMouseUp","_onMouseOut","_onMouseOver","_onMouseWheel","_wheelEvent","NO_BUTTON","LEFT_BUTTON","MIDDLE_BUTTON","RIGHT_BUTTON","BACK_BUTTON","FORWARD_BUTTON","WHEEL_UP","WHEEL_DOWN","android","chrome","onMouseDown","onMouseMove","onMouseUp","_onMouseUpGlobal","onMouseUpGlobal","_onMouseOutGlobal","onMouseOutGlobal","onMouseOut","onMouseOver","onMouseWheel","wheelEvent","mouseMoveCallback","withinGame","resetButtons","bindEvent","deltaY","requestPointerLock","element","mozRequestPointerLock","webkitRequestPointerLock","_pointerLockChange","pointerLockChange","pointerLockElement","mozPointerLockElement","webkitPointerLockElement","releasePointerLock","exitPointerLock","mozExitPointerLock","webkitExitPointerLock","_stubsGenerated","prop","makeBinder","detail","deltaX","wheelDeltaX","deltaZ","pointerDownCallback","pointerMoveCallback","pointerUpCallback","_onMSPointerDown","_onMSPointerMove","_onMSPointerUp","_onMSPointerUpGlobal","_onMSPointerOut","_onMSPointerOver","onPointerDown","onPointerMove","onPointerUp","onPointerUpGlobal","onPointerOut","onPointerOver","pointerType","DeviceButton","buttonCode","isDown","isUp","timeDown","timeUp","repeats","altKey","shiftKey","ctrlKey","onFloat","startStop","condition","padFloat","justPressed","justReleased","pointerMode","leftButton","middleButton","rightButton","backButton","forwardButton","eraserButton","ERASER_BUTTON","_holdSent","_history","_nextDrop","_stateReset","clientX","clientY","pageX","pageY","screenX","screenY","rawMovementX","rawMovementY","movementX","movementY","isMouse","previousTapTime","totalTouches","msSinceLastClick","targetObject","interactiveCandidates","positionDown","positionUp","_clickTrampolines","_trampolineTargetObject","processButtonsDown","processButtonsUp","processButtonsUpDown","buttons","down","toLowerCase","updateButtons","totalActivePointers","_touchedHandler","processInteractiveObjects","shift","fromClick","pollLocked","mozMovementX","webkitMovementX","mozMovementY","webkitMovementY","noPause","isDragged","highestRenderOrderID","highestInputPriorityID","candidateTarget","currentNode","checked","validForInput","checkPointerDown","checkPointerOver","priorityID","swapTarget","newTarget","_pointerOutHandler","_pointerOverHandler","leave","currentPointers","addClickTrampoline","callbackArgs","trampolines","trampoline","_releasedHandler","resetMovement","touchStartCallback","touchMoveCallback","touchEndCallback","touchEnterCallback","touchLeaveCallback","touchCancelCallback","_onTouchStart","_onTouchMove","_onTouchEnd","_onTouchEnter","_onTouchLeave","_onTouchCancel","onTouchStart","onTouchMove","onTouchEnd","onTouchEnter","onTouchLeave","onTouchCancel","consumeDocumentTouches","_documentTouchMove","changedTouches","InputHandler","useHandCursor","_setHandCursor","allowHorizontalDrag","allowVerticalDrag","snapOffset","snapOnDrag","snapOnRelease","snapX","snapY","snapOffsetX","snapOffsetY","pixelPerfectOver","pixelPerfectClick","pixelPerfectAlpha","draggable","boundsRect","boundsSprite","scaleLayer","dragOffset","dragFromCenter","dragStopBlocksInputUp","dragStartPoint","dragDistanceThreshold","dragTimeThreshold","downPoint","snapPoint","_dragPoint","_dragPhase","_pendingDrag","_dragTimePass","_dragDistancePass","_wasEnabled","_tempPoint","_pointerData","camX","camY","isOver","isOut","timeOver","timeOut","downDuration","onAddedToGroup","addedToGroup","onRemovedFromGroup","removedFromGroup","highestID","highestRenderID","includePixelPerfect","isPixelPerfect","pointerX","pointerY","pointerDown","pointerUp","pointerTimeDown","pointerTimeUp","pointerOver","pointerOut","pointerTimeOver","pointerTimeOut","pointerDragged","fastTest","checkPixel","_dx","_dy","startDrag","_draggedPointerID","updateDrag","sendEvent","onInputOver$dispatch","onInputOut$dispatch","onInputDown$dispatch","dragTimeElapsed","onInputUp$dispatch","stopDrag","fromStart","pointerLocalCoord","globalToLocal","checkBoundsRect","checkBoundsSprite","onDragUpdate","justOver","delay","overDuration","justOut","enableDrag","lockCenter","pixelPerfect","alphaThreshold","disableDrag","boundsCenterLocalCoord","onDragStart$dispatch","globalToLocalX","grid","boundsFluid","scaleFluidInversed","globalToLocalY","globalCoord","onDragStop$dispatch","setDragLock","allowHorizontal","allowVertical","enableSnap","onDrag","onRelease","disableSnap","_gamepadIndexMap","_rawPads","_active","_gamepadSupportAvailable","webkitGetGamepads","webkitGamepads","userAgent","getGamepads","_prevRawGamepadTypes","_prevTimestamps","onConnectCallback","onDisconnectCallback","onDownCallback","onUpCallback","onAxisCallback","onFloatCallback","_ongamepadconnected","_gamepaddisconnected","_gamepads","SinglePad","addCallbacks","callbacks","onConnect","onDisconnect","onAxis","_onGamepadConnected","onGamepadConnected","_onGamepadDisconnected","onGamepadDisconnected","newPad","connect","removedPad","disconnect","_pollGamepads","pad1","pollStatus","pad2","pad3","pad4","rawGamepads","gamepadsChanged","_rawPad","singlePad","validConnections","rawIndices","padIndices","connected","rawPad","setDeadZones","deadZone","BUTTON_0","BUTTON_1","BUTTON_2","BUTTON_3","BUTTON_4","BUTTON_5","BUTTON_6","BUTTON_7","BUTTON_8","BUTTON_9","BUTTON_10","BUTTON_11","BUTTON_12","BUTTON_13","BUTTON_14","BUTTON_15","AXIS_0","AXIS_1","AXIS_2","AXIS_3","AXIS_4","AXIS_5","AXIS_6","AXIS_7","AXIS_8","AXIS_9","XBOX360_A","XBOX360_B","XBOX360_X","XBOX360_Y","XBOX360_LEFT_BUMPER","XBOX360_RIGHT_BUMPER","XBOX360_LEFT_TRIGGER","XBOX360_RIGHT_TRIGGER","XBOX360_BACK","XBOX360_START","XBOX360_STICK_LEFT_BUTTON","XBOX360_STICK_RIGHT_BUTTON","XBOX360_DPAD_LEFT","XBOX360_DPAD_RIGHT","XBOX360_DPAD_UP","XBOX360_DPAD_DOWN","XBOX360_STICK_LEFT_X","XBOX360_STICK_LEFT_Y","XBOX360_STICK_RIGHT_X","XBOX360_STICK_RIGHT_Y","PS3XC_X","PS3XC_CIRCLE","PS3XC_SQUARE","PS3XC_TRIANGLE","PS3XC_L1","PS3XC_R1","PS3XC_L2","PS3XC_R2","PS3XC_SELECT","PS3XC_START","PS3XC_STICK_LEFT_BUTTON","PS3XC_STICK_RIGHT_BUTTON","PS3XC_DPAD_UP","PS3XC_DPAD_DOWN","PS3XC_DPAD_LEFT","PS3XC_DPAD_RIGHT","PS3XC_STICK_LEFT_X","PS3XC_STICK_LEFT_Y","PS3XC_STICK_RIGHT_X","PS3XC_STICK_RIGHT_Y","padParent","_padParent","_prevTimestamp","_buttons","_buttonsLen","_axes","_axesLen","getButton","timestamp","rawButtonVal","isNaN","processButtonDown","processButtonUp","processButtonFloat","processAxisChange","triggerCallback","disconnectingIndex","axisCode","buttonValue","Key","keycode","_enabled","durationUp","keyCode","onHoldCallback","onHoldContext","_justDown","_justUp","processKeyDown","processKeyUp","upDuration","pressEvent","onPressCallback","_keys","_capture","_onKeyDown","_onKeyPress","_onKeyUp","_k","onPress","removeCallbacks","addKey","addKeyCapture","addKeys","removeKey","removeKeyCapture","createCursorKeys","up","KeyCode","processKeyPress","clearCaptures","String","fromCharCode","charCode","A","charCodeAt","C","D","E","H","J","K","L","M","O","P","Q","R","S","T","U","V","W","X","Y","Z","ZERO","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","NUMPAD_0","NUMPAD_1","NUMPAD_2","NUMPAD_3","NUMPAD_4","NUMPAD_5","NUMPAD_6","NUMPAD_7","NUMPAD_8","NUMPAD_9","NUMPAD_MULTIPLY","NUMPAD_ADD","NUMPAD_ENTER","NUMPAD_SUBTRACT","NUMPAD_DECIMAL","NUMPAD_DIVIDE","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","F13","F14","F15","COLON","EQUALS","COMMA","UNDERSCORE","PERIOD","QUESTION_MARK","TILDE","OPEN_BRACKET","BACKWARD_SLASH","CLOSED_BRACKET","QUOTES","BACKSPACE","TAB","CLEAR","ENTER","SHIFT","CONTROL","ALT","CAPS_LOCK","ESC","SPACEBAR","PAGE_UP","PAGE_DOWN","END","HOME","PLUS","MINUS","INSERT","DELETE","HELP","NUM_LOCK","match","Component","Angle","wrapAngle","Animation","play","frameRate","loop","killOnComplete","animations","AutoCull","autoCull","inCamera","checkWorldBounds","Bounds","container","alignTo","BringToTop","Core","skipTypeChecks","install","components","Events","PhysicsBody","AnimationManager","LoadTexture","FixedToCamera","previousRotation","preUpdateChildren","fresh","_exists","P2JS","customRender","Crop","cropRect","_crop","updateCrop","resetFrame","oldX","oldY","oldW","oldH","_frame","Delta","Destroy","onDestroy$dispatch","removeFrom","Video","onChangeSource","resizeFrame","BitmapText","_glyphs","_parent","_onDestroy","_onAddedToGroup","_onRemovedFromGroup","_onKilled","_onRevived","_onEnterBounds","_onOutOfBounds","_onInputOver","_onInputOut","_onInputDown","_onInputUp","_onDragStart","_onDragUpdate","_onDragStop","_onAnimationStart","_onAnimationComplete","_onAnimationLoop","onKilled","onRevived","onOutOfBounds","onEnterBounds","onInputOver","onInputOut","onInputDown","onInputUp","onDragStart","onDragStop","onAnimationStart","onAnimationComplete","onAnimationLoop","backing","_fixedToCamera","Health","health","maxHealth","damage","setHealth","heal","InCamera","InputEnabled","InWorld","outOfCameraBoundsKill","_outOfBoundsFired","onEnterBounds$dispatch","onOutOfBounds$dispatch","outOfBoundsKill","inWorld","LifeSpan","lifespan","physicsElapsedMS","onRevived$dispatch","onKilled$dispatch","stopAnimation","BitmapData","hasFrameData","loadFrameData","getFrameData","frameData","Tilemap","TilemapLayer","img","getImage","trimmed","spriteSourceSizeX","spriteSourceSizeY","sourceSizeW","sourceSizeH","refreshTexture","frameName","Overlap","_reset","Reset","ScaleMinMax","scaleMin","scaleMax","checkTransform","setScaleMinMax","Smoothed","existing","weapon","bulletClass","Weapon","createBullets","Image","creature","mesh","tween","physicsGroup","SpriteBatch","audio","audioSprite","addSprite","tileSprite","rope","Rope","text","Text","overFrame","outFrame","downFrame","upFrame","Button","emitter","maxParticles","Arcade","Emitter","retroFont","font","characterWidth","characterHeight","chars","charsPerRow","xSpacing","ySpacing","xOffset","yOffset","RetroFont","bitmapText","tilemap","tileWidth","tileHeight","addToCache","uuid","addRenderTexture","video","bitmapData","addBitmapData","Tween","preUpdatePhysics","preUpdateLifeSpan","preUpdateInWorld","preUpdateCore","_onOverFrame","_onOutFrame","_onDownFrame","_onUpFrame","onOverSound","onOutSound","onDownSound","onUpSound","onOverSoundMarker","onOutSoundMarker","onDownSoundMarker","onUpSoundMarker","onOverMouseOnly","justReleasedPreventsOver","freezeFrames","forceOut","setFrames","onInputOverHandler","onInputOutHandler","onInputDownHandler","onInputUpHandler","clearFrames","setStateFrame","switchImmediately","frameKey","changeStateFrame","setStateSound","marker","soundKey","markerKey","Sound","AudioSprite","playStateSound","setSounds","overSound","overMarker","downSound","downMarker","outSound","outMarker","upSound","upMarker","setOverSound","setOutSound","setDownSound","setUpSound","fastSpriteBatch","ready","isRotated","childTransform","skipPool","ctx","imageData","FrameData","textureFrame","addFrame","Frame","disableTextureUpload","cls","_image","_pos","_size","_scale","_rotate","_alpha","prev","_anchor","_tempR","_tempG","_tempB","_circle","_swapCanvas","moveH","moveV","draw","onload","addImage","toDataURL","processPixelRGB","pixel","createColor","unpackPixel","getPixel32","setPixel32","processPixel","replaceRGB","g1","g2","region","packPixel","setHSL","bHaveH","bHaveS","bHaveL","HSLtoRGB","shiftHSL","red","green","blue","immediate","LITTLE_ENDIAN","setPixel","getPixel","getPixelRGB","hsl","hsv","getPixels","getFirstPixel","scan","newWidth","newHeight","getCanvas","op","copyTransform","copyRect","drawGroup","drawGroupProxy","drawFull","renderGraphics","shadow","blur","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","alphaMask","sourceRect","maskRect","blendSourceAtop","blendReset","extract","destination","prevFont","fillText","beginPath","arc","closePath","moveTo","lineTo","lineWidth","strokeStyle","stroke","polygon","textureLine","createPattern","blendSourceOver","blendSourceIn","blendSourceOut","blendDestinationOver","blendDestinationIn","blendDestinationOut","blendDestinationAtop","blendXor","blendAdd","blendMultiply","blendScreen","blendOverlay","blendDarken","blendLighten","blendColorDodge","blendColorBurn","blendHardLight","blendSoftLight","blendDifference","blendExclusion","blendHue","blendSaturation","blendColor","blendLuminosity","copyBitmapData","destRowStart","getSmoothingEnabled","setSmoothingEnabled","getTransform","translateX","translateY","skewX","skewY","EarCut","holeIndices","dim","hasHoles","outerLen","outerNode","linkedList","eliminateHoles","earcutLinked","clockwise","insertNode","filterPoints","again","steiner","removeNode","ear","pass","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","minTX","minTY","maxTX","maxTY","minZ","zOrder","maxZ","nextZ","prevZ","locallyInside","isValidDiagonal","splitPolygon","getLeftmost","compareX","eliminateHole","hole","findHoleBridge","hx","hy","qx","tan","tanMin","sortLinked","q","tail","numMerges","pSize","qSize","inSize","leftmost","intersectsPolygon","middleInside","Node","an","bp","stencilBufferLimit","lastIndex","clearDirty","graphicsDataPool","switchMode","buildPoly","buildComplexPoly","buildLine","buildRectangle","buildCircle","buildRoundedRectangle","upload","WebGLGraphicsData","rectData","fillColor","fillAlpha","vertPos","tempPoints","rrectData","recPoints","quadraticBezierCurve","vecPos","fromX","fromY","cpX","cpY","toX","toY","getPt","n1","n2","perc","xa","ya","xb","yb","circleData","seg","totalSegs","firstPoint","lastPoint","midPointX","midPointY","unshift","p1x","p1y","p2x","p2y","p3x","p3y","perpx","perpy","perp2x","perp2y","perp3x","perp3y","indexCount","indexStart","lineColor","lineAlpha","glPoints","glIndicies","updateGraphicsTint","_fillTint","_lineTint","strokeRect","ox","oy","xe","ye","xm","ym","bezierCurveTo","maxRadius","quadraticCurveTo","tintR","tintG","tintB","GraphicsData","currentPath","boundsPadding","_localBounds","_boundsDirty","webGLDirty","cachedSpriteDirty","updateLocalBounds","drawTriangle","cull","triangle","cameraToFace","faceNormal","drawPolygon","drawTriangles","point1","point2","point3","lineStyle","drawShape","cpX2","cpY2","dt2","dt3","arcTo","mm","dd","cc","tt","k1","k2","j1","j2","qy","anticlockwise","segments","sweep","segs","startX","startY","filling","theta","theta2","cTheta","sTheta","segMinus","remainder","drawRoundedRect","drawCircle","drawEllipse","canvasBuffer","updateCachedSpriteTexture","_prevTint","tempPoint","cachedSprite","destroyCachedSprite","textureBuffer","tempMatrix","renderXY","renderRawXY","updateBase","realResolution","getBase64","webGLPixels","Uint8Array","readPixels","tempCanvas","canvasData","textBounds","strokeColors","fontStyles","fontWeights","autoRound","useAdvancedWrap","splitRegExp","characterLimitSize","characterLimitSuffix","_res","_text","_fontComponents","_lineSpacing","_charCount","setStyle","updateText","setShadow","shadowStroke","shadowFill","newStyle","backgroundColor","boundsAlignH","boundsAlignV","strokeThickness","wordWrap","wordWrapWidth","maxLines","tabs","fontToComponents","fontStyle","fontVariant","fontWeight","fontSize","componentsToFont","outputText","substring","runWordWrap","lines","lineWidths","maxLineWidth","fontProperties","determineFontProperties","drawnLines","measureLine","measureText","tab","section","snapToCeil","lineHeight","lineSpacing","textBaseline","lineCap","lineJoin","linePositionX","linePositionY","ascent","updateLine","updateShadow","strokeText","renderTabLine","snap","lineLength","letter","clearColors","clearFontValues","addColor","addStrokeColor","addFontStyle","addFontWeight","weight","precalculateWordWrap","advancedWordWrap","basicWordWrap","linesCount","currentLineWidth","words","word","wordWithSpace","wordWidth","newWord","secondPart","spaceLeft","wordWidthWithSpace","updateFont","family","exec","fontFamily","setText","parseList","setTextBounds","properties","fontPropertiesCache","fontPropertiesCanvas","fontPropertiesContext","baseline","descent","imagedata","setCharacterLimit","characterLimit","suffix","parseFloat","createElement","textWidth","textHeight","_prevAnchor","_maxWidth","_data","getBitmapFont","_font","_fontSize","_align","_tint","sourceWidth","sourceHeight","scanLine","lastSpace","wrappedWidth","prevCharCode","maxWidth","test","charAt","charData","kerning","xAdvance","cleanText","re","purgeGlyphs","kept","checkImageKey","characterSpacingX","characterSpacingY","characterPerRow","multiLine","autoUpperCase","customSpacingX","customSpacingY","fixedWidth","fontSet","grabData","currentX","currentY","updateFrameData","stamp","ALIGN_LEFT","ALIGN_RIGHT","ALIGN_CENTER","TEXT_SET1","TEXT_SET2","TEXT_SET3","TEXT_SET4","TEXT_SET5","TEXT_SET6","TEXT_SET7","TEXT_SET8","TEXT_SET9","TEXT_SET10","TEXT_SET11","setFixedWidth","lineAlignment","content","characterSpacing","allowLowerCase","buildRetroFontText","getLongestLine","pasteLine","longestLine","removeUnsupportedCharacters","stripCR","newString","aChar","code","updateOffset","diffX","diffY","frames","getFrames","newText","toUpperCase","_hasUpdateAnimation","_updateAnimationCallback","canvasPadding","drawMode","updateAnimation","nextPoint","perpLength","_vertexBuffer","_initWebGL","_renderStrip","_indexBuffer","_uvBuffer","_colorBuffer","_renderCanvasTriangleStrip","_renderCanvasTriangles","_renderCanvasDrawTriangle","index0","textureSource","textureWidth","textureHeight","u0","v2","paddingX","paddingY","normX","normY","deltaA","deltaB","deltaC","deltaD","deltaE","deltaF","renderStripFlat","strip","rawX","rawY","_updateAnimation","difference","_scroll","textureDebug","tilePattern","frameWidth","frameHeight","physicsElapsed","autoScroll","stopScroll","generateTilingTexture","restartBatch","sessionBlendMode","forcePowerOfTwo","targetWidth","targetHeight","getNextPowerOfTwo","pool","getTotal","getFree","deviceReadyAt","initialized","desktop","iOSVersion","nodeWebkit","electron","ejecta","crosswalk","chromeOS","linux","macOS","windows","windowsPhone","canvasBitBltShift","file","fileSystem","localStorage","worker","css3D","typedArray","vibration","getUserMedia","quirksMode","arora","chromeVersion","epiphany","firefox","firefoxVersion","ieVersion","trident","tridentVersion","mobileSafari","midori","opera","safari","safariVersion","webApp","silk","audioData","ogg","opus","mp3","wav","m4a","webm","dolby","oggVideo","h264Video","mp4Video","webmVideo","vp9Video","hlsVideo","iPhone","iPhone4","iPad","pixelRatio","littleEndian","support32bit","fullscreen","requestFullscreen","cancelFullscreen","fullscreenKeyboard","onInitialized","nonPrimer","readyCheck","_readyCheck","_monitor","_queue","readyState","setTimeout","_initialize","_checkIsLittleEndian","_checkIsUint8ClampedImageData","Uint8ClampedArray","createImageData","vita","kindle","RegExp","$1","_checkOS","$3","process","versions","_checkBrowser","audioElement","canPlayType","major","minor","$2","_checkAudio","videoElement","_checkVideo","has3d","el","transforms","webkitTransform","OTransform","msTransform","MozTransform","insertBefore","getComputedStyle","getPropertyValue","_checkCSS3D","Int8Array","Int32Array","vibrate","webkitVibrate","mozVibrate","msVibrate","getItem","WebGLRenderingContext","compatMode","webkitGetUserMedia","mozGetUserMedia","msGetUserMedia","oGetUserMedia","URL","webkitURL","mozURL","msURL","_checkFeatures","s1","s2","_checkCanvasFeatures","fs","cfs","Element","_checkFullScreenSupport","documentElement","maxTouchPoints","PointerEvent","MSPointerEvent","msPointerEnabled","pointerEnabled","canPlayAudio","canPlayVideo","needsTouchUnlock","PhaserGlobal","fakeiOSTouchLock","isAndroidStockBrowser","matches","display","msTouchAction","overflowHidden","getElementById","overflow","appendChild","parentNode","vendor","prefix","types","msInterpolationMode","setImageRenderingBicubic","forceSetTimeOut","vendors","requestAnimationFrame","cancelAnimationFrame","_isSetTimeOut","_onLoop","_timeOutID","updateSetTimeout","updateRAF","rafTime","timeToCall","clearTimeout","isSetTimeOut","isRAF","DEG_TO_RAD","RAD_TO_DEG","degrees","radians","fuzzyLessThan","fuzzyGreaterThan","fuzzyCeil","fuzzyFloor","average","shear","snapTo","gap","snapToFloor","roundTo","place","floorTo","ceilTo","rotateToAngle","currentAngle","targetAngle","getShortestAngle","angleBetween","angleBetweenY","angleBetweenPoints","angleBetweenPointsY","reverseAngle","angleRad","normalizeAngle","maxAdd","minSub","wrapValue","isOdd","isEven","minProperty","maxProperty","linearInterpolation","bezierInterpolation","bernstein","catmullRomInterpolation","catmullRom","factorial","res","roundAwayFromZero","sinCosGenerator","sinAmplitude","cosAmplitude","frequency","frq","cosTable","sinTable","hypot","distanceSq","distancePow","clampBottom","within","mapLinear","smoothstep","smootherstep","sign","percent","seeds","s0","sow","integer","real","integerInRange","realInRange","ary","weightedPick","QuadTree","maxObjects","maxLevels","_empty","subWidth","subHeight","populate","populateHandler","insert","retrieve","returnObjects","getHostName","location","hostname","checkDomainName","domain","updateQueryString","redirect","href","separator","getQueryString","parameter","keyValues","search","decodeURI","decodeURIComponent","frameBased","_tweens","_add","easeMap","Power0","Easing","Power1","Power2","Power3","Power4","Linear","None","Quad","Quadratic","Out","Cubic","Quart","Quartic","Quint","Quintic","Sine","Sinusoidal","Expo","Exponential","Circ","Circular","Elastic","Back","Bounce","Quad.easeIn","In","Cubic.easeIn","Quart.easeIn","Quint.easeIn","Sine.easeIn","Expo.easeIn","Circ.easeIn","Elastic.easeIn","Back.easeIn","Bounce.easeIn","Quad.easeOut","Cubic.easeOut","Quart.easeOut","Quint.easeOut","Sine.easeOut","Expo.easeOut","Circ.easeOut","Elastic.easeOut","Back.easeOut","Bounce.easeOut","Quad.easeInOut","InOut","Cubic.easeInOut","Quart.easeInOut","Quint.easeInOut","Sine.easeInOut","Expo.easeInOut","Circ.easeInOut","Elastic.easeInOut","Back.easeInOut","Bounce.easeInOut","_pauseAll","_resumeAll","pendingDelete","_manager","addTweens","numTweens","isTweening","checkIsRunning","some","_pause","_resume","pauseAll","resumeAll","manager","timeline","timeScale","repeatCounter","onStart","onLoop","onRepeat","onChildComplete","onComplete","chainedTween","isPaused","_onUpdateCallback","_onUpdateCallbackContext","_pausedTime","_hasStarted","ease","yoyo","Default","TweenData","vEnd","loadValues","updateTweenData","repeatDelay","yoyoDelay","easing","interpolation","repeatAll","chain","startTime","status","PENDING","RUNNING","LOOPED","COMPLETE","generateData","vStart","vStartCache","vEndCache","repeatTotal","inReverse","easingFunction","interpolationFunction","interpolationContext","isFrom","ms","fps","blob","reversed","asin","prevTime","_desiredFps","suggestedFps","advancedTiming","updates","renders","ups","rps","fpsMin","fpsMax","msMin","msMax","pauseDuration","timeExpected","Timer","_frameCount","_elapsedAccumulator","_started","_timeLastSecond","_pauseStarted","_justResumed","_timers","timer","autoDestroy","previousDateNow","updateAdvancedTiming","updateTimers","interval","elapsedSince","since","elapsedSecondsSince","running","expired","nextTick","timeCap","_pauseTotal","_now","_marked","_diff","_newTick","MINUTE","SECOND","HALF","QUARTER","repeatCount","TimerEvent","clearEvents","clearPendingEvents","adjustEvents","baseTime","currentFrame","currentAnim","updateIfVisible","isLoaded","_frameData","_anims","_outputFrames","anim","copyFrameData","useNumericIndex","getFrameIndexes","validateFrames","checkFrameName","isPlaying","getAnimation","refreshFrame","gotFrame","getFrame","getFrameByName","_frameIndex","_frames","loopCount","isFinished","_pauseStartTime","_frameDiff","_frameSkip","onUpdate","isReversed","_timeLastFrame","_timeNextFrame","updateCurrentFrame","onAnimationStart$dispatch","reverseOnce","frameId","useLocalFrameIndex","frameIndex","directionalOffset","dispatchComplete","onAnimationComplete$dispatch","onAnimationLoop$dispatch","signalUpdate","fromPlay","generateFrameNames","zeroPad","spriteSourceSizeW","spriteSourceSizeH","setTrim","actualWidth","actualHeight","destX","destY","destWidth","destHeight","getRect","_frameNames","getFrameRange","AnimationParser","spriteSheet","frameMax","margin","spacing","skipFrames","JSONData","json","newFrame","filename","sourceSize","spriteSourceSize","JSONDataPyxel","tileheight","tilewidth","JSONDataHash","XMLData","xml","getElementsByTagName","frameX","frameY","autoResolveURL","binary","bitmapFont","compressedTexture","_urlMap","_urlResolver","_urlTemp","onSoundUnlock","_cacheMap","TEXTURE","SOUND","PHYSICS","BINARY","BITMAPFONT","JSON","XML","SHADER","RENDER_TEXTURE","_pendingCount","_addImages","DEFAULT_KEY","DEFAULT_SRC","MISSING","MISSING_KEY","MISSING_SRC","READY_TIMEOUT","addCompressedTextureMetaData","extension","arrayBuffer","removeImage","LoaderParser","fileFormat","_resolveURL","addCanvas","addImageAsync","_removePending","_addPending","addDefaultImage","addMissingImage","addSound","audioTag","decoded","isDecoding","touchLocked","addText","addPhysicsData","addTilemap","mapData","addBinary","binaryData","addBitmapFont","atlasData","atlasType","jsonBitmapFont","xmlBitmapFont","addBitmapFontFromAtlas","atlasKey","atlasFrame","dataKey","dataType","getBaseTexture","fontData","getJSON","getXML","addJSON","addXML","addVideo","isBlob","addShader","addSpriteSheet","addTextureAtlas","TEXTURE_ATLAS_XML_STARLING","TEXTURE_ATLAS_JSON_PYXEL","reloadSound","getSound","reloadSoundComplete","updateSound","decodedSound","isSoundDecoded","isSoundReady","checkKey","checkURL","checkCanvasKey","checkTextureKey","checkSoundKey","checkTextKey","checkPhysicsKey","checkTilemapKey","checkBinaryKey","checkBitmapDataKey","checkBitmapFontKey","checkJSONKey","checkXMLKey","checkVideoKey","checkShaderKey","checkRenderTextureKey","full","getTextureFrame","getSoundData","getText","getPhysicsData","fixtureKey","fixtures","fixture","getTilemapData","getBinary","getBitmapData","getVideo","getShader","getRenderTexture","getFrameCount","getFrameByIndex","getURL","getKeys","removeCanvas","destroyBaseTexture","removeSound","removeText","removePhysics","removeTilemap","removeBinary","removeBitmapData","removeBitmapFont","removeJSON","removeXML","removeVideo","removeShader","removeRenderTexture","removeSpriteSheet","removeTextureAtlas","baseURL","destroyItem","readyTimeout","_ready","_checkReady","isLoading","preloadSprite","crossOrigin","headers","requestedWith","onLoadStart","onLoadComplete","onPackComplete","onFileStart","onFileComplete","onFileError","enableParallel","maxParallelDownloads","_withSyncPointDepth","_fileList","_flightQueue","_processingHead","_fileLoadStarted","_totalPackCount","_totalFileCount","_loadedPackCount","_loadedFileCount","TEXTURE_ATLAS_JSON_ARRAY","TEXTURE_ATLAS_JSON_HASH","PHYSICS_LIME_CORONA_JSON","PHYSICS_PHASER_JSON","setPreloadSprite","checkKeyExists","getAssetIndex","bestFound","loaded","loading","getAsset","fileIndex","addToFileList","overwrite","syncPoint","currentFile","replaceInFileList","pack","imageFromBitmapData","imageFromGrid","imageFromTexture","pixelWidth","pixelHeight","palette","exkey","images","urls","script","spritesheet","autoDecode","noAudio","jsonURL","jsonData","audiosprite","loadEvent","asBlob","CSV","TILED_JSON","LIME_CORONA_JSON","textureURL","atlasURL","parseXml","atlasJSONArray","atlas","atlasJSONHash","atlasXML","withSyncPoint","addSyncPoint","asset","removeFile","updateProgress","processLoadQueue","finishedLoading","requestUrl","requestObject","progress","syncblock","inflightLimit","processPack","loadFile","abnormal","asyncComplete","errorMessage","packData","transformUrl","xhrLoad","fileComplete","loadImageTag","getAudioURL","usingWebAudio","usingAudioTag","loadAudioTag","fileError","getVideoURL","loadVideoTag","jsonLoadComplete","xmlLoadComplete","csvLoadComplete","onerror","controls","autoplay","videoLoadEvent","canplay","Audio","playThroughEvent","xhr","XMLHttpRequest","open","responseType","setRequestHeader","message","send","videoType","uri","lastIndexOf","audioType","reason","loadNext","responseText","response","decode","language","defer","head","contentType","domparser","DOMParser","parseFromString","ActiveXObject","async","loadXML","totalLoadedFiles","totalLoadedPacks","progressFloat","info","common","getAttribute","letters","kernings","second","finalizeBitmapFont","_face","_lineHeight","_id","_xoffset","_yoffset","_xadvance","_second","_first","_amount","bitmapFontData","pvr","uintArray","byteArray","pvrHeader","pixelFormat","flags","colorSpace","channelType","depth","numberOfSurfaces","numberOfFaces","numberOfMipmaps","metaDataSize","byteLength","dds","ddsHeader","pitch","mipmapCount","formatSize","formatFlag","formatFourCC","formatBitCount","formatRBitMask","formatGBitMask","formatBBitMask","formatABitMask","caps1","caps2","caps3","caps4","reserved2","DXGIFormat","resourceDimension","miscFlag","arraySize","ktx","ktxHeader","imageSizeOffset","imageSize","glInternalFormat","endianness","glType","glTypeSize","glFormat","glBaseInternalFormat","pixelDepth","numberOfArrayElements","numberOfMipmapLevels","bytesOfKeyValueData","keyAndValueByteSize","pkm","pkmHeader","originalWidth","originalHeight","autoplayKey","sounds","spritemap","addMarker","connectToMaster","markers","totalDuration","currentTime","durationMS","stopTime","pausedPosition","pausedTime","currentMarker","fadeTween","pendingPlayback","override","allowMultiple","externalNode","masterGainNode","gainNode","_sound","_globalVolume","_markedToDelete","_removeFromSoundManager","masterGain","createGain","createGainNode","gain","soundHasUnlocked","onDecoded","onPlay","onStop","onMute","onMarkerComplete","_volume","_buffer","_muted","_tempMarker","_tempPosition","_tempVolume","_tempPause","_muteVolume","_tempLoop","_onDecodedEventDispatched","removeMarker","onEndedHandler","onended","isDecoded","loopFull","forceRestart","noteOff","createBufferSource","noteGrainOn","muted","mute","prevMarker","fadeIn","fadeTo","fadeOut","fadeComplete","updateGlobalVolume","globalVolume","onSoundDecode","onVolumeChange","onUnMute","onTouchUnlock","channels","_codeMuted","_unlockSource","_sounds","_watchList","_watching","_watchCallback","_watchContext","disableAudio","disableWebAudio","audioContext","setTouchLock","unlock","setTouchUnlock","noteOn","stopAll","soundData","decodeAudioData","setDecodedCallback","files","playbackState","PLAYING_STATE","FINISHED_STATE","removeByKey","close","dom","minWidth","minHeight","maxHeight","forceLandscape","forcePortrait","incorrectOrientation","_pageAlignHorizontally","_pageAlignVertically","onOrientationChange","enterIncorrectOrientation","leaveIncorrectOrientation","hasPhaserSetFullScreen","fullScreenTarget","_createdFullScreenTarget","onFullScreenInit","onFullScreenChange","onFullScreenError","screenOrientation","getScreenOrientation","scaleFactorInversed","aspectRatio","sourceAspectRatio","windowConstraints","compatibility","supportsFullScreen","orientationFallback","noMargins","scrollTo","forceMinimumDocumentHeight","canExpandParent","clickTrampoline","_scaleMode","NO_SCALE","_fullScreenScaleMode","parentIsWindow","parentScaleFactor","trackParentInterval","onSizeChange","onResize","onResizeContext","_pendingScaleMode","_fullScreenRestore","_gameSize","_userScaleFactor","_userScaleTrim","_lastUpdate","_updateThrottle","_updateThrottleReset","_parentBounds","_tempBounds","_lastReportedCanvasSize","_lastReportedGameSize","_booted","setupScale","EXACT_FIT","SHOW_ALL","RESIZE","USER_SCALE","MODES","compat","_orientationChange","orientationChange","_windowResize","windowResize","_fullScreenChange","fullScreenChange","_fullScreenError","fullScreenError","_gameResumed","setGameSize","FlexGrid","fullScreenScaleMode","pageAlignHorizontally","alignH","pageAlignVertically","alignV","scaleH","scaleV","setUserScale","trimH","trimV","getParentBounds","visualBounds","updateDimensions","queueUpdate","currentScaleMode","hScale","vScale","hTrim","vTrim","setResizeCallback","signalSizeChange","setMinMax","prevThrottle","prevWidth","prevHeight","boundsChanged","orientationChanged","updateOrientationState","updateLayout","throttle","updateScalingAndBounds","forceOrientation","classifyOrientation","orientation","previousOrientation","previouslyIncorrect","isLandscape","isPortrait","changed","correctnessChanged","scrollTop","setMaximum","setExactFit","isFullScreen","boundingParent","setShowAll","resetCanvas","reflowCanvas","reflowGame","layoutBounds","clientRect","getBoundingClientRect","parentRect","offsetParent","wc","windowBounds","alignCanvas","parentBounds","canvasBounds","currentEdge","targetEdge","marginLeft","marginRight","marginTop","marginBottom","cssWidth","cssHeight","expanding","createFullScreenTarget","fsTarget","background","startFullScreen","allowTrampoline","cleanupCreatedTarget","initData","targetElement","ALLOW_KEYBOARD_INPUT","stopFullScreen","prepScreenMode","enteringFullscreen","createdTarget","scaleSprite","letterBox","scaleX1","scaleY1","scaleX2","scaleY2","scaleOnWidth","bmd","columnWidth","renderShadow","currentColor","currentAlpha","_line","_rect","soundInfo","filled","rectangle","geom","cameraInfo","hideIfUp","downColor","upColor","worldX","worldY","spriteInputInfo","justDown","justUp","inputInfo","spriteBounds","ropeSegments","segment","spriteInfo","spriteCoords","lineInfo","forceType","ellipse","quadTree","quadtree","NINJA","Ninja","BOX2D","Box2D","renderBody","bodyInfo","renderBodyInfo","box2d","box2dWorld","renderDebugDraw","box2dBody","displayList","canvasPool","phaser","factor","loader","box","scrollY","scrollLeft","scrollX","clientTop","clientLeft","cushion","calibrate","coords","getAspectRatio","inLayoutViewport","primaryFallback","screen","mozOrientation","msOrientation","matchMedia","documentBounds","pageXOffset","pageYOffset","clientWidth","clientHeight","offsetWidth","scrollWidth","offsetHeight","scrollHeight","randomIndex","removeRandomItem","newLength","transposeMatrix","sourceRowCount","sourceColCount","rotateMatrix","findClosest","arr","NaN","low","high","rotateRight","rotateLeft","numberArray","numberArrayStep","LinkedList","entity","palettes","0","PALETTE_ARNE","PALETTE_JMP","PALETTE_CGA","PALETTE_C64","PALETTE_JAPANESE_MACHINE","row","boundsCustom","boundsFull","boundsNone","positionCustom","positionFluid","positionFull","positionNone","scaleCustom","scaleFluid","scaleFull","scaleNone","customWidth","customHeight","customOffsetX","customOffsetY","ratioH","ratioV","layers","createCustomLayer","layer","FlexLayer","createFluidLayer","createFullLayer","createFixedLayer","persist","fitSprite","topLeft","topMiddle","topRight","bottomLeft","bottomMiddle","bottomRight","RED","ORANGE","YELLOW","GREEN","AQUA","BLUE","VIOLET","WHITE","BLACK","GRAY","RGBtoHSL","RGBtoHSV","fromRGBA","toRGBA","toABGR","RGBArrayToHex","rgb","hueToColor","HSVtoRGB","color32","getColor","getColor32","RGBtoString","componentToHex","hexToRGB","hex","hexToColor","webToColor","web","tempColor","getRGB","HSVColorWheel","HSLColorWheel","interpolateColor","color1","color2","currentStep","src1","src2","hsv1","hsv2","dh","h3","interpolateColorWithRGB","or","og","ob","interpolateRGB","getRandomColor","getWebRGB","getAlpha","getAlphaFloat","getRed","getGreen","getBlue","blendNormal","blendAverage","blendSubtract","blendNegation","blendLinearDodge","blendLinearBurn","blendLinearLight","blendVividLight","blendPinLight","blendHardMix","blendReflect","blendGlow","blendPhoenix","arcade","ninja","chipmunk","matter","CHIPMUNK","MATTERJS","P2","Matter","startSystem","system","enableAABB","checkCollision","OVERLAP_BIAS","forceX","sortDirection","LEFT_RIGHT","skipQuadTree","_total","SORT_NONE","RIGHT_LEFT","TOP_BOTTOM","BOTTOM_TOP","updateMotion","allowRotation","velocityDelta","computeVelocity","angularAcceleration","angularDrag","maxAngular","acceleration","drag","maxVelocity","allowGravity","allowDrag","object1","object2","overlapCallback","processCallback","collideObjects","collide","collideCallback","sortLeftRight","sortRightLeft","sortTopBottom","sortBottomTop","overlapOnly","collideHandler","collideGroupVsSelf","collideSpriteVsSprite","collideSpriteVsGroup","collideSpriteVsTilemapLayer","collideGroupVsGroup","collideGroupVsTilemapLayer","sprite1","sprite2","separate","items","bounds1","bounds2","group1","group2","body1","body2","none","isCircle","separateCircle","bodyRect","bodyCircle","resultX","resultY","separateX","separateY","onOverlap","onCollide","circleBodyIntersects","getOverlapX","getOverlapY","angleCollision","immovable","customSeparateX","tempVel1","tempVel2","bounce","maxOverlap","deltaAbsX","embedded","touching","overlapX","deltaAbsY","overlapY","moves","nv1","nv2","avg","customSeparateY","getObjectsUnderPointer","getObjectsAtLocation","callbackArg","moveToObject","maxTime","distanceBetween","moveToPointer","angleToPointer","distanceToPointer","moveToXY","distanceToXY","velocityFromAngle","velocityFromRotation","accelerationFromRotation","accelerateToObject","xSpeedMax","ySpeedMax","accelerateToPointer","accelerateToXY","angleToXY","closest","targets","farthest","angleBetweenCenters","worldAngleToPointer","preRotation","newVelocity","deltaMax","worldBounce","onWorldBounds","facing","overlapR","collideWorldBounds","wasTouching","blocked","tilePadding","syncBounds","isMoving","stopVelocityOnCollide","moveTimer","moveDistance","moveDuration","moveTarget","moveEnd","onMoveComplete","movementCallback","movementCallbackContext","_sx","_sy","updateBounds","asx","asy","updateCenter","updateMovement","collided","stopMovement","stopVelocity","check","moveFrom","setCircle","onFloor","onCeiling","onWall","TilemapCollision","TILE_BIAS","tilemapLayer","getTiles","getTileOffsetX","getTileOffsetY","separateTile","tile","tilemapLayerOffsetX","tilemapLayerOffsetY","collisionCallback","collisionCallbackContext","faceLeft","faceRight","faceTop","faceBottom","tileCheckX","tileCheckY","collideRight","collideLeft","processTileSeparationX","collideDown","collideUp","processTileSeparationY","useElapsedTime","materials","InversePointProxy","walls","onBodyAdded","onBodyRemoved","onSpringAdded","onSpringRemoved","onConstraintAdded","onConstraintRemoved","onContactMaterialAdded","onContactMaterialRemoved","postBroadphaseCallback","onBeginContact","onEndContact","mpx","mpxi","pxm","pxmi","beginContactHandler","endContactHandler","collisionGroups","nothingCollisionGroup","CollisionGroup","boundsCollisionGroup","everythingCollisionGroup","boundsCollidesWith","_toRemove","_collisionGroupID","_boundsLeft","_boundsRight","_boundsTop","_boundsBottom","_boundsOwnGroup","removeBodyNextStep","setImpactEvents","impactHandler","setPostBroadphaseCallback","postBroadphaseHandler","_bodyCallbacks","_bodyCallbackContext","_groupCallbacks","_groupCallbackContext","setCollisionGroup","setWorldMaterial","updateBoundsCollisionGroup","setupWall","wall","fixedStepTime","impactCallback","createDistanceConstraint","getBody","createGearConstraint","createRevoluteConstraint","createLockConstraint","createPrismaticConstraint","lockRotation","anchorA","anchorB","setMaterial","createMaterial","createContactMaterial","getSprings","getConstraints","filterStatic","physicsPosition","query","toJSON","createCollisionGroup","bitmask","createSpring","worldA","worldB","localA","localB","createRotationalSpring","createBody","addPolygon","createParticle","convertCollisionObjects","map","collision","shapeData","polyline","addRectangle","clearTilemapLayerBodies","getLayer","convertTilemap","optimize","collides","getTileRight","FixtureList","rawList","namedFixtures","groupedFixtures","allFixtures","setCategory","bit","getFixtures","setMask","setSensor","getFixtureByKey","getGroup","groupID","_ref","_results","callee","PointProxy","collidesWith","removeNextStep","debugBody","_collideWorldBounds","setRectangleFromSprite","createBodyCallback","createGroupCallback","getCollisionMask","updateCollisionMask","clearCollision","clearGroup","clearMask","removeCollisionGroup","clearCallback","shapeChanged","impulse","localX","localY","setZeroRotation","setZeroVelocity","setZeroDamping","moveForward","moveBackward","thrust","thrustLeft","thrustRight","moveLeft","moveRight","updateSpriteTransform","resetDamping","resetMass","clearShapes","addCircle","addPlane","addParticle","addLine","addCapsule","setRectangle","addPhaserPolygon","createdFixtures","fixtureData","shapesOfFixture","addFixture","generatedShapes","categoryBits","maskBits","isSensor","polygons","loadPolygon","BodyDebug","settings","defaultSettings","pixelsPerLengthUnit","debugPolygons","ppu","lw","vrot","_j","_ref1","randomPastelHex","drawCapsule","drawPlane","drawLine","drawRectangle","drawConvex","drawPath","lastx","lasty","diagMargin","diagSize","maxLength","xd","yd","mix","rgbToHex","ImageCollection","firstgid","imageWidth","imageHeight","imageMargin","imageSpacing","containsImageIndex","imageIndex","gid","Tile","flipped","scanned","setCollisionCallback","setCollision","resetCollision","isInteresting","faces","TilemapParser","widthInPixels","heightInPixels","tilesets","imagecollections","tiles","collideIndexes","currentLayer","debugMap","_tempA","NORTH","EAST","SOUTH","WEST","setTileSize","createBlankLayer","addTilesetImage","tileset","tileMargin","tileSpacing","getTilesetIndex","setImage","newSet","Tileset","countX","countY","columns","rows","createFromObjects","CustomClass","adjustY","adjustSize","createFromTiles","replacements","customClass","lh","createLayer","getLayerIndex","rootLayer","groupEnd","indexes","getImageIndex","setTileIndexCallback","setTileLocationCallback","recalculate","setCollisionByIndex","calculateFaces","setCollisionBetween","setCollisionByExclusion","layerArg","setPreventRecalculate","preventingRecalculate","needToRecalculate","above","below","getTileAbove","getTileBelow","getTileLeft","setLayer","hasTile","removeTile","removeTileWorldXY","putTile","putTileWorldXY","searchTileIndex","getTile","nonNull","getTileWorldXY","paste","tileblock","tileA","tileB","swapHandler","removeAllLayers","dump","txt","renderSettings","enableScrollDelta","overdrawRatio","copyCanvas","debugSettings","missingImageFill","debuggedTileOverfill","forceFullRedraw","debugAlpha","facingEdgeStroke","collidingTileOverfill","scrollFactorX","scrollFactorY","rayStepRate","_wrap","_mc","renderWidth","renderHeight","_scrollX","_scrollY","tileOffset","ensureSharedCopyCanvas","sharedCopyCanvas","resizeWorld","_fixX","_unfixX","_fixY","_unfixY","getTileX","getTileY","getTileXY","getRayCastTiles","interestingFace","coord","fetchAll","wy","wx","resolveTileset","tileIndex","setIndex","containsTileIndex","resetTilesetCache","setScale","xScale","yScale","shiftCanvas","copyW","copyH","copyContext","renderRegion","lastAlpha","xmax","ymax","baseX","normStartX","renderDeltaScroll","shiftX","shiftY","renderW","renderH","trueTop","trueBottom","trueLeft","trueRight","renderFull","redrawAll","mc","renderDebug","baseY","normStartY","INSERT_NULL","getEmptyData","parseCSV","parseTiledJSON","column","_slice","fields","sliced","parseObjectGroup","objectGroup","objectsCollection","collisionCollection","nameKey","relativePosition","curl","encoding","binaryString","atob","bytes","opacity","offsetx","offsety","flippedVal","curi","tilesetGroupObjects","lastSet","tileproperties","tileProperties","updateTileData","imagewidth","imageheight","newCollection","objectgroup","lastgid","sid","drawCoords","coordIndex","setSpacing","rowCount","colCount","autoScale","scaleData","_s","autoAlpha","alphaData","_a","onEmit","setAlphaData","setScaleData","emitters","ID","minAngle","maxAngle","minSpeed","maxSpeed","minParticleSpeed","maxParticleSpeed","minParticleScale","maxParticleScale","minRotation","maxRotation","minParticleAlpha","maxParticleAlpha","particleClass","particleDrag","particleAnchor","emitX","emitY","particleBringToTop","particleSendToBack","counts","emitted","failed","totalEmitted","totalFailed","_gravity","_minParticleScale","_maxParticleScale","_timer","_counter","_flowQuantity","_flowTotal","_explode","emitParticle","makeParticles","particleArguments","particle","rndKey","rndFrame","explode","flow","forceQuantity","getNextParticle","resetParticle","setXSpeed","setYSpeed","setRotation","setAlpha","rate","tweenData","setAngle","lifespanOutput","bullets","autoExpandBulletsGroup","autofire","shots","fireLimit","fireRate","fireRateVariance","fireFrom","fireAngle","bulletInheritSpriteSpeed","bulletAnimation","bulletFrameRandom","bulletFrameCycle","bulletWorldWrap","bulletWorldWrapPadding","bulletAngleOffset","bulletAngleVariance","bulletSpeed","bulletSpeedVariance","bulletLifespan","bulletKillDistance","bulletGravity","bulletRotateToVelocity","bulletKey","bulletFrame","_bulletClass","Bullet","_bulletCollideWorldBounds","_bulletKillType","KILL_WORLD_BOUNDS","customBody","bulletBounds","bulletFrames","bulletFrameIndex","anims","onFire","onKill","onFireLimit","trackedSprite","trackedPointer","multiFire","_hasFired","trackRotation","trackOffset","_nextFire","_tempNextFire","_rotatedPoint","KILL_NEVER","KILL_LIFESPAN","KILL_DISTANCE","KILL_WEAPON_BOUNDS","KILL_CAMERA_BOUNDS","KILL_STATIC_BOUNDS","resetShots","newLimit","fire","trackSprite","trackPointer","fireMany","fireOffset","moveX","moveY","bullet","bulletManager","killType","bulletKillType","killDistance","rotateToVelocity","bodyDirty","bulletCollideWorldBounds","fireAtPointer","fireAtSprite","fireAtXY","setBulletBodyOffset","setBulletFrames","cycle","addBulletAnimation","debugBodies","onAccess","onError","onTimeout","playWhenUnlocked","timeout","videoStream","isStreaming","retryLimit","retry","retryInterval","_retryID","_pending","_pendingChangeSource","_autoplay","_endCallback","_playCallback","_video","createVideoFromBlob","videoWidth","videoHeight","createVideoFromURL","snapshot","connectToMediaStream","stream","startMediaStream","captureAudio","removeVideoElement","setAttribute","getUserMediaTimeout","getUserMediaSuccess","getUserMediaError","mozSrcObject","createObjectURL","onloadeddata","checkStream","checkVideoProgress","change","playbackRate","setPause","setResume","playHandler","getTracks","track","playing","ended","changeSource","grab","hasChildNodes","firstChild","removeAttribute","canUseNewCanvasBlendModes"],"mappings":";;CAoDC,SAASA,GAAG,GAAG,iBAAiBC,QAAQC,OAAOD,QAAQD,QAAS,CAAmD,IAAIG,EAAE,oBAAoBC,OAAOD,EAAEC,OAAO,oBAAoBC,OAAOF,EAAEE,OAAO,oBAAoBC,OAAOH,EAAEG,MAAMH,EAAEI,GAAGP,KAAzO,CAA+O,WAAqC,OAAO,SAAUA,EAAEQ,EAAEC,EAAEC,GAAG,SAASC,EAAEC,EAAEC,GAAG,IAAIJ,EAAEG,GAAG,CAAC,IAAIJ,EAAEI,GAAG,CAAC,IAAIE,EAAkB,mBAATC,SAAqBA,QAAQ,IAAIF,GAAGC,EAAE,OAAOA,EAAEF,GAAE,GAAI,GAAGI,EAAE,OAAOA,EAAEJ,GAAE,GAAI,MAAM,IAAIK,MAAM,uBAAuBL,EAAE,KAAK,IAAIT,EAAEM,EAAEG,IAAIX,YAAYO,EAAEI,GAAG,GAAGM,KAAKf,EAAEF,QAAQ,SAASD,GAAG,IAAIS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B79C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAItW,GACxB99C,EAASitB,KAAWmnC,EAAIrW,GAExB/9C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAGpBn6C,EAASitB,KAAWywB,EACpB19C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIpW,GACxBh+C,EAASitB,KAAWmnC,EAAInW,GAExBj+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,EAKpBn6C,EAASitB,KAAW0wB,EACpB39C,EAASitB,KAAW2wB,EAEpB59C,EAASitB,KAAWknC,EAAOttD,SAASS,EACpCtH,EAASitB,KAAWknC,EAAOttD,SAASU,EAGpCvH,EAASitB,KAAWknC,EAAO/hD,MAAM9K,EACjCtH,EAASitB,KAAWknC,EAAO/hD,MAAM7K,EAGjCvH,EAASitB,KAAWknC,EAAO1d,SAG3Bz2C,EAASitB,KAAWmnC,EAAIlW,GACxBl+C,EAASitB,KAAWmnC,EAAIjW,GAExBn+C,EAASitB,KAAWknC,EAAOzd,MAE3B12C,EAASitB,KAAWktB,IAGpBp6C,KAAKyzD,kBAEuBzzD,KAAKmM,MAE7BnM,KAAKy+C,UAObjK,EAAKkiB,qBAAqBt2D,UAAUq+C,MAAQ,WAGxC,GAA4B,IAAxBz+C,KAAKyzD,iBAAT,CA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EAAOiE,iBAGL77B,IAApBk1B,KAAKC,aAELD,KAAKC,WAAayC,EAAOzC,iBAGKn1B,IAA9Bk1B,KAAK2K,QAAQC,eAEb5K,KAAK2K,QAAQC,aAAe,IAAI5K,KAAK2K,QAAQ,IAAI3K,KAAKwmB,mBAGnB17C,IAAnCk1B,KAAKgC,cAAc6C,cAEnB7E,KAAKgC,cAAc6C,YAAc,IAAInC,EAAOC,QAGhD3C,KAAKinB,mBAAoB,EAGzBjnB,KAAKwxJ,0BAA4B,WAC7B,OAAO9uJ,EAAOgvC,OAAOnrB,gBASE,oBAAZn/D,SACe,oBAAXC,QAA0BA,OAAOD,UACxCA,QAAUC,OAAOD,QAAUs7C,GAE/Bt7C,QAAQs7C,OAASA,GACQ,oBAAXglB,QAA0BA,OAAOC,IAC/CD,OAAO,SAA+B3vB,EAAK2K,OAASA,GAEpD3K,EAAK2K,OAASA,EAGXA,GACRr6C,KAAKmD","file":"phaser.min.js"} \ No newline at end of file diff --git a/Iteration Sequence 2/js/phaser.min.js b/Iteration Sequence 2/js/phaser.min.js new file mode 100644 index 000000000..6eb048b7a --- /dev/null +++ b/Iteration Sequence 2/js/phaser.min.js @@ -0,0 +1,4 @@ +/* Phaser v2.10.0 - http://phaser.io - @photonstorm - (c) 2016 Photon Storm Ltd. */ + +!function(t){if("object"==typeof exports)module.exports=t();else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.p2=t()}}(function(){return function t(e,i,s){function n(o,a){if(!i[o]){if(!e[o]){var h="function"==typeof require&&require;if(!a&&h)return h(o,!0);if(r)return r(o,!0);throw new Error("Cannot find module '"+o+"'")}var l=i[o]={exports:{}};e[o][0].call(l.exports,function(t){var i=e[o][1][t];return n(i||t)},l,l.exports,t,e,i,s)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;se[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;ia)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var T=0;Tm&&(m+=this.vertices.length),g=Number.MAX_VALUE,m3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e) (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.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.1"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;ca[f]&&(a[f]=u[f]),u[f]i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle");var n=t("../collision/Broadphase");t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;az&&Y0)for(G=0;GMath.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=x,f=b,g=_,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var w=r.vertices[y];if(o.rotate(p,w,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var T=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(T.normalA,f);var P=l(g,T.normalA);o.scale(g,T.normalA,P),a(T.contactPointB,p,n.position),a(T.contactPointA,p,g),a(T.contactPointA,T.contactPointA,t.position),this.contactEquations.push(T),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(T))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=x,p=b;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=x;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,w=u;w=w||0;var T=x,P=b,C=_;a(T,g,y),o.rotate(P,v,w);var S=l(P,T);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,P),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,T,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=x,m=b,y=_,v=w,P=T,E=C,M=S,R=A,L=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(M,u,i),l(g,M)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),I=s.getClosestEdge(c,d,g);if(-1===B||-1===I)return 0;for(var O=0;O<2;O++){var k=B,F=I,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===O){var q;q=k,k=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H=3){if(p)return!0;var Z=this.createContactEquation(j,V,D,U);L++;var J=D.vertices[k%D.vertices.length],Q=D.vertices[(k+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(P,v,y),o.rotate90cw(Z.normalA,P),o.normalize(Z.normalA,Z.normalA),a(M,m,y);var $=l(Z.normalA,M);o.scale(E,Z.normalA,$),a(Z.contactPointA,m,G),a(Z.contactPointA,Z.contactPointA,E),h(Z.contactPointA,Z.contactPointA,G),a(Z.contactPointA,Z.contactPointA,j.position),a(Z.contactPointB,m,N),h(Z.contactPointB,Z.contactPointB,N),a(Z.contactPointB,Z.contactPointB,V.position),this.contactEquations.push(Z),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(Z))}}}return this.enableFrictionReduction&&this.enableFriction&&L&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;dh)&&(h=a),(null===c||ah){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,x=nt;if(t instanceof y&&n instanceof y)for(P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(C=0;2!==C;C++){0===C?o.set(m,0,1):1===C&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0),u=(S=T[0]-w[1])<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var P=0;2!==P;P++){var b=t,_=i;1===P&&(b=n,_=h);for(var C=0;C!==b.vertices.length;C++){o.rotate(f,b.vertices[C],_),o.rotate(g,b.vertices[(C+1)%b.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,x);var w=v,T=x;v[0]>x[0]&&(T=v,w=x,!0);var S=T[0]-w[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,x=pt,b=ct,_=ut,w=Math.floor((i[0]-d-l[0])/f),T=Math.ceil((i[0]+d-l[0])/f);w<0&&(w=0),T>=p.length&&(T=p.length-1);for(var P=p[w],C=p[T],S=w;SP&&(P=p[S]);if(i[1]-d>P)return!u&&0;for(var A=!1,S=w;S=b[0]&&m[0]<_[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,x,-E),o.add(y,m,g),o.copy(v,x);M=this.createContactEquation(n,t,r,e);o.copy(M.normalA,v),o.scale(M.contactPointB,M.normalA,-d),h(M.contactPointB,M.contactPointB,i),a(M.contactPointB,M.contactPointB,t.position),o.copy(M.contactPointA,y),o.sub(M.contactPointA,M.contactPointA,n.position),this.contactEquations.push(M),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(M))}}if(A=!1,d>0)for(S=w;S<=T;S++)if(o.set(b,S*f,p[S]),o.add(b,b,l),o.sub(g,i,b),o.squaredLength(g)=c.length&&(y=c.length-1);for(var v=c[m],x=c[y],b=m;bv&&(v=c[b]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var _=0,b=m;b=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;ne.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){this.from,this.to;var o=this._currentShape,a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;cthis.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.positioni?(a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n)):-1!==(b=t.indexOf(n))&&t.splice(b,1),this.lowerLimitEnabled&&va?(f.angle=a,-1===n.indexOf(f)&&n.push(f)):-1!==(y=n.indexOf(f))&&n.splice(y,1),this.lowerLimitEnabled&&m>1;if(e<3)return[];for(var i=[],n=[],r=0;r3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,x=1/(f*y-g*g),b=(y*m-g*v)*x,_=(f*v-g*m)*x;return b>=0&&_>=0&&b+_<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;ei&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),x=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||x;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(h=this.shapes.length;h>=0;--h)this.removeShape(this.shapes[h]);var i=new r.Polygon;if(i.vertices=t,i.makeCCW(),"number"==typeof e.removeCollinearPoints&&i.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!i.isSimple())return!1;this.concavePath=i.vertices.slice(0);for(h=0;h=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var T=n.create(),P=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(T,i,t*e),n.multiply(T,this.massMultiplier,T),n.add(r,T,r),this.integrateToTimeOfImpact(t)||(n.scale(P,r,t),n.add(s,s,P),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),M=n.create(),R=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)=l&&h=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var b=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),w=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),T=Math.pow(_,2)-4*b*w;if(!(T<0))if(0===T){if(r.lerp(d,n,o,T),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,T,p,-1),t.shouldStop(e)))return}else{var P=Math.sqrt(T),C=1/(2*b),S=(-_-P)*C,A=(-_+P)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,x=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;x>=0&&x<=1&&(r.lerp(f,n,h,x),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,x,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;in)&&(n=s),(null===o||sn){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;ee&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),nv){var x=y;y=v,v=x}for(var b=0;b=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,_,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};r.create();var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){(t=t||{}).type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){(t=t||{}).type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=t.lowerBound,a=t.upperBound;n(o,-1e7,-1e7),n(a,1e7,1e7),0===s?a[1]=0:s===Math.PI/2?o[0]=0:s===Math.PI?o[1]=0:s===3*Math.PI/2&&(a[0]=0)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}t("../utils/Utils");var n=t("../events/EventEmitter");e.exports=s,(s.prototype=new n).constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){this.overlappingShapesLastState;var n=this.overlappingShapesCurrentState;if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var s=t,n=e;(i=i||[]).length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;)(n=i.getByKey(i.keys[s]))&&e.push(n.bodyA,n.bodyB);return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,(s.prototype=new r).constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s=t&&s=0;T-=2)for(S=b.length-2;S>=0;S-=2)(w[T]===b[S]&&w[T+1]===b[S+1]||w[T+1]===b[S]&&w[T]===b[S+1])&&b.splice(S,2);q=u.length;for(T=0;T!==q;T++){var C=u[T];if(!C.collideConnected)for(var S=b.length-2;S>=0;S-=2)(C.bodyA===b[S]&&C.bodyB===b[S+1]||C.bodyB===b[S]&&C.bodyA===b[S+1])&&b.splice(S,2)}this.postBroadphaseEvent.pairs=b,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var T=0,A=b.length;T!==A;T+=2)for(var E=b[T],M=b[T+1],R=0,L=E.shapes.length;R!==L;R++)for(var B=E.shapes[R],I=B.position,O=B.angle,k=0,F=M.shapes.length;k!==F;k++){var D=M.shapes[k],U=D.position,G=D.angle,N=this.defaultContactMaterial;if(B.material&&D.material){var X=this.getContactMaterial(B.material,D.material);X&&(N=X)}this.runNarrowphase(c,E,B,I,O,M,D,U,G,N,this.frictionGravity)}for(T=0;T!==h;T++)(H=n[T])._wakeUpAfterNarrowphase&&(H.wakeUp(),H._wakeUpAfterNarrowphase=!1);if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(P);for(var W=this.endContactEvent,k=P.length;k--;){var j=P[k];W.shapeA=j.shapeA,W.shapeB=j.shapeB,W.bodyA=j.bodyA,W.bodyB=j.bodyB,this.emit(W)}P.length=0}var V=this.preSolveEvent;V.contactEquations=c.contactEquations,V.frictionEquations=c.frictionEquations,this.emit(V),V.contactEquations=V.frictionEquations=null;var q=u.length;for(T=0;T!==q;T++)u[T].update();if(c.contactEquations.length||c.frictionEquations.length||q)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),T=0;T!==q;T++)v.appendArray(g.equations,u[T].equations);g.split(this);for(T=0;T!==g.islands.length;T++)(K=g.islands[T]).equations.length&&a.solveIsland(t,K)}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),T=0;T!==q;T++)a.addEquations(u[T].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(T=0;T!==h;T++){var H=n[T];H.integrate(t)}for(T=0;T!==h;T++)n[T].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var Y=this.impactEvent,T=0;T!==c.contactEquations.length;T++){var z=c.contactEquations[T];z.firstImpact&&(Y.bodyA=z.bodyA,Y.bodyB=z.bodyB,Y.shapeA=z.shapeA,Y.shapeB=z.shapeB,Y.contactEquation=z,this.emit(Y))}if(this.sleepMode===s.BODY_SLEEPING)for(T=0;T!==h;T++)n[T].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(T=0;T!==h;T++)n[T].sleepTick(this.time,!0,t);for(T=0;T0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,x=t.frictionEquations.length;y=i.type=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0),o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC&&r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0),this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var _=this.beginContactEvent;if(_.shapeA=i,_.shapeB=a,_.bodyA=e,_.bodyB=o,_.contactEquations.length=0,"number"==typeof y)for(P=t.contactEquations.length-y;P1)for(var P=t.frictionEquations.length-b;P=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var x=e[y],b=0,_=x.shapes.length;b!==_;b++){var w=x.shapes[b];r.rotate(p,w.position,x.angle),r.add(p,p,x.position);var T=w.angle+x.angle;(w instanceof o&&g.circleParticle(x,w,p,T,s,n,u,0,!0)||w instanceof a&&g.particleConvex(s,n,u,0,x,w,p,T,!0)||w instanceof h&&g.particlePlane(s,n,u,0,x,w,p,T,!0)||w instanceof l&&g.particleCapsule(s,n,u,0,x,w,p,T,!0)||w instanceof c&&r.squaredLength(r.sub(f,p,t))0?Math.acos(i/u):-Math.acos(i/u),this.worldScale.x=u,this.worldScale.y=c/u}else if(n||r){var d=Math.sqrt(n*n+r*r);this.worldRotation=Phaser.Math.HALF_PI-(r>0?Math.acos(-n/d):-Math.acos(n/d)),this.worldScale.x=c/d,this.worldScale.y=d}else this.worldScale.x=0,this.worldScale.y=0;return this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.x=l.tx,this.worldPosition.y=l.ty,this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,l,h),this},preUpdate:function(){},generateTexture:function(t,e,i){var n=this.getLocalBounds(),r=new Phaser.RenderTexture(this.game,0|n.width,0|n.height,i,e,t);return s.DisplayObject._tempMatrix.tx=-n.x,s.DisplayObject._tempMatrix.ty=-n.y,r.render(this,s.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?s.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):s.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=0;this.texture&&this.texture.baseTexture&&s._enableMultiTextureToggle&&(e=this.texture.baseTexture.textureIndex);var i=new Phaser.RenderTexture(this.game,t.width,t.height,void 0,void 0,void 0,void 0,e);this._cachedSprite=new s.Sprite(i),this._cachedSprite.worldTransform=this.worldTransform}var n=this._filters;this._filters=null,this._cachedSprite.filters=n,s.DisplayObject._tempMatrix.tx=-t.x,s.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,s.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=n,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},s.DisplayObject.prototype.displayObjectUpdateTransform=s.DisplayObject.prototype.updateTransform,Object.defineProperties(s.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],i=0;i=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},s.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},s.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},s.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},s.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},s.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},s.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},s.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(t,i),n=0;na?u:a,d=d>h?d:h);var f=this._bounds;if(!p){var g=(f=new s.Rectangle).x,m=f.width+f.x,y=f.y,v=f.height+f.y,x=this.worldTransform,b=x.a,_=x.b,w=x.c,T=x.d,P=x.tx,C=x.ty,S=b*m+w*v+P,A=T*v+_*m+C,E=b*g+w*v+P,M=T*v+_*g+C,R=b*g+w*y+P,L=T*y+_*g+C,B=b*m+w*y+P,I=T*y+_*m+C;u=S,d=A,c=A,l=B<(l=R<(l=E<(l=S)?E:l)?R:l)?B:l,c=I<(c=L<(c=M(u=R>(u=E>u?E:u)?R:u)?B:u,d=I>(d=L>(d=M>d?M:d)?L:d)?I:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n(f=T>(f=_>(f=x>f?x:f)?_:f)?T:f)?C:f,g=S>(g=P>(g=w>(g=b>g?b:g)?w:g)?P:g)?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},s.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=Phaser.identityMatrix;for(var e=0;e= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) { gl_FragColor = RED;return;}","}"];var n=s.compileProgram(t,this.vertexSrc||s.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(n),this.uSamplerArray=t.getUniformLocation(n,"uSamplerArray[0]"),this.projectionVector=t.getUniformLocation(n,"projectionVector"),this.offsetVector=t.getUniformLocation(n,"offsetVector"),this.dimensions=t.getUniformLocation(n,"dimensions"),this.aVertexPosition=t.getAttribLocation(n,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(n,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(n,"aColor"),this.aTextureIndex=t.getAttribLocation(n,"aTextureIndex");var r=[],o=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var a=0;a 0.0) gl_Position = vec4(0.0);"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);"," vTextureIndex = aTextureIndex;","}"],s.PixiFastShader=function(t){if(this._UID=Phaser._UID++,this.gl=t,this.program=null,s._enableMultiTextureToggle){var t=this.gl;this.MAX_TEXTURES=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(var e="\tif (vTextureIndex == 0.0) { gl_FragColor = texture2D(uSamplerArray[0], vTextureCoord) * vColor;return;}\n",i=1;i= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["// PixiFastShader Fragment Shader.","precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;","}"];this.vertexSrc=["// PixiFastShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","attribute float aTextureIndex;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;"," vColor = aColor;","}"],this.textureCount=0,this.init()},s.PixiFastShader.prototype.constructor=s.PixiFastShader,s.PixiFastShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r= "+this.MAX_TEXTURES+".0) { gl_FragColor = BLUE;return;}"," if(isnan(vTextureIndex)) {gl_FragColor = RED;return;}","}"]}else this.fragmentSrc=["//StripShader Fragment Shader.","precision mediump float;","varying vec2 vTextureCoord;","varying float vTextureIndex;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord);","}"];this.vertexSrc=["//StripShader Vertex Shader.","attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aTextureIndex;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying float vTextureIndex;","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;"," vTextureIndex = aTextureIndex;","}"],this.init()},s.StripShader.prototype.constructor=s.StripShader,s.StripShader.prototype.init=function(){var t=this.gl,e=s.compileProgram(t,this.vertexSrc,this.fragmentSrc);if(t.useProgram(e),this.uSampler=s._enableMultiTextureToggle?t.getUniformLocation(e,"uSamplerArray[0]"):t.getUniformLocation(e,"uSampler"),s._enableMultiTextureToggle){var i=[],n=t.createTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGB,1,1,0,t.RGB,t.UNSIGNED_BYTE,null);for(var r=0;r>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t},i=this.gl,n=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),r=i.getParameter(i.MAX_TEXTURE_SIZE),o=this.game.cache._cache.image,a=null,h=0;h=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var a=i._uvs;if(a){var h,l,c,u,d=t.anchor.x,p=t.anchor.y;if(i.trim){var f=i.trim;h=(l=f.x-d*f.width)+i.crop.width,c=(u=f.y-p*f.height)+i.crop.height}else h=i.frame.width*(1-d),l=i.frame.width*-d,c=i.frame.height*(1-p),u=i.frame.height*-p;var g=this.currentBatchSize*this.vertexSize,m=(this.currentBatchSize,i.baseTexture.resolution),y=i.baseTexture.textureIndex,v=o.a/m,x=o.b/m,b=o.c/m,_=o.d/m,w=o.tx,T=o.ty,P=(i.crop.width,i.crop.height);if(i.rotated){var C=o.a,S=o.b,A=o.c,E=o.d,M=l,R=h;w=o.c*P+w,T=o.d*P+T,v=6.123233995736766e-17*C-A,x=6.123233995736766e-17*S-E,b=C+6.123233995736766e-17*A,_=S+6.123233995736766e-17*E,i._updateUvsInverted(),h=c,l=u,c=R,u=M}var L=this.colors,B=this.positions,I=t.tint,O=(I>>16)+(65280&I)+((255&I)<<16)+(255*t.worldAlpha<<24);this.renderSession.roundPixels?(B[g++]=v*l+b*u+w|0,B[g++]=_*u+x*l+T|0,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w|0,B[g++]=_*u+x*h+T|0,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w|0,B[g++]=_*c+x*h+T|0,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w|0,B[g++]=_*c+x*l+T|0,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y):(B[g++]=v*l+b*u+w,B[g++]=_*u+x*l+T,B[g++]=a.x0,B[g++]=a.y0,L[g++]=O,B[g++]=y,B[g++]=v*h+b*u+w,B[g++]=_*u+x*h+T,B[g++]=a.x1,B[g++]=a.y1,L[g++]=O,B[g++]=y,B[g++]=v*h+b*c+w,B[g++]=_*c+x*h+T,B[g++]=a.x2,B[g++]=a.y2,L[g++]=O,B[g++]=y,B[g++]=v*l+b*c+w,B[g++]=_*c+x*l+T,B[g++]=a.x3,B[g++]=a.y3,L[g++]=O,B[g++]=y),this.sprites[this.currentBatchSize++]=t}},s.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture,i=e.baseTexture,n=this.gl,r=t.texture.baseTexture.textureIndex;s.WebGLRenderer.textureArray[r]!=i&&(this.flush(),n.activeTexture(n.TEXTURE0+r),n.bindTexture(n.TEXTURE_2D,i._glTextures[n.id]),s.WebGLRenderer.textureArray[r]=i),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new s.TextureUvs);var o=t._uvs,a=e.baseTexture.width,h=e.baseTexture.height;t.tilePosition.x%=a*t.tileScaleOffset.x,t.tilePosition.y%=h*t.tileScaleOffset.y;var l=t.tilePosition.x/(a*t.tileScaleOffset.x),c=t.tilePosition.y/(h*t.tileScaleOffset.y),u=t.width/a/(t.tileScale.x*t.tileScaleOffset.x),d=t.height/h/(t.tileScale.y*t.tileScaleOffset.y);o.x0=0-l,o.y0=0-c,o.x1=1*u-l,o.y1=0-c,o.x2=1*u-l,o.y2=1*d-c,o.x3=0-l,o.y3=1*d-c;var p=t.tint,f=(p>>16)+(65280&p)+((255&p)<<16)+(255*t.worldAlpha<<24),g=this.positions,m=this.colors,y=t.width,v=t.height,x=t.anchor.x,b=t.anchor.y,_=y*(1-x),w=y*-x,T=v*(1-b),P=v*-b,C=this.currentBatchSize*this.vertexSize,S=e.baseTexture.resolution,A=t.worldTransform,E=A.a/S,M=A.b/S,R=A.c/S,L=A.d/S,B=A.tx,I=A.ty;g[C++]=E*w+R*P+B,g[C++]=L*P+M*w+I,g[C++]=o.x0,g[C++]=o.y0,m[C++]=f,g[C++]=r,g[C++]=E*_+R*P+B,g[C++]=L*P+M*_+I,g[C++]=o.x1,g[C++]=o.y1,m[C++]=f,g[C++]=r,g[C++]=E*_+R*T+B,g[C++]=L*T+M*_+I,g[C++]=o.x2,g[C++]=o.y2,m[C++]=f,g[C++]=r,g[C++]=E*w+R*T+B,g[C++]=L*T+M*w+I,g[C++]=o.x3,g[C++]=o.y3,m[C++]=f,g[C++]=r,this.sprites[this.currentBatchSize++]=t},s.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,t=this.defaultShader.shaders[e.id],e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var i=this.vertexSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,i,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,i,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,i,16),e.vertexAttribPointer(t.aTextureIndex,1,e.FLOAT,!1,i,20)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);var n=this.positions.subarray(0,this.currentBatchSize*this.vertexSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m0&&(v=!1),(f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){(t=(p=a).shaders[e.id])||((t=new s.PixiShader(e)).fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var x=this.renderSession.projection;e.uniform2f(t.projectionVector,x.x,x.y);var b=this.renderSession.offset;e.uniform2f(t.offsetVector,b.x,b.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},s.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},s.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},s.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},s.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},s.WebGLFastSpriteBatch=function(t){this.vertSize=11,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,i=6*this.maxSize;this.vertices=new Float32Array(e),this.indices=new Uint16Array(i),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var s=0,n=0;s=this.size&&this.flush()}},s.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]){if(this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}else this.renderSession.renderer.updateTexture(this.currentBaseTexture,t)}},s.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},s.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36),t.vertexAttribPointer(this.shader.aTextureIndex,1,t.FLOAT,!1,i,40)},s.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},s.WebGLFilterManager.prototype.constructor=s.WebGLFilterManager,s.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},s.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},s.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,i=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new s.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),i.x=a.width/2,i.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},s.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),i=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,i.width*this.renderSession.resolution,i.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=i.height,this.vertexArray[2]=i.width,this.vertexArray[3]=i.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=i.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=i.width/this.width,this.uvArray[5]=i.height/this.height,this.uvArray[6]=i.width/this.width,this.uvArray[7]=i.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new s.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,i,p,f),this.texturePool.push(n),e._glFilterTexture=null},s.WebGLFilterManager.prototype.applyFilterPass=function(t,e,i,n){var r=this.gl,o=t.shaders[r.id];o||((o=new s.PixiShader(r)).fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(!0),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,i/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},s.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},s.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e=0;t--){var e=this._glTextures[t],i=s.glContexts[t];i&&e&&i.deleteTexture(e)}this._glTextures.length=0,this.dirty()},s.BaseTexture.fromCanvas=function(t,e,i){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),i=i||1,new s.BaseTexture(t,e,i)},s.TextureSilentFail=!1,s.Texture=function(t,e,i,n){this.noFrame=!1,e||(this.noFrame=!0,e=new s.Rectangle(0,0,1,1)),t instanceof s.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=i||new s.Rectangle(0,0,1,1),this.rotated=!1,t.hasLoaded&&(this.noFrame&&(e=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},s.Texture.prototype.constructor=s.Texture,s.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new s.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},s.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},s.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,this.trim||!(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height))this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs();else{if(!s.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=!1}},s.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/i},s.Texture.prototype._updateUvsInverted=function(){this._uvs||(this._uvs=new s.TextureUvs);var t=this.crop,e=this.baseTexture.width,i=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/i,this._uvs.x1=(t.x+t.height)/e,this._uvs.y1=t.y/i,this._uvs.x2=(t.x+t.height)/e,this._uvs.y2=(t.y+t.width)/i,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.width)/i},s.Texture.fromCanvas=function(t,e){var i=s.BaseTexture.fromCanvas(t,e);return new s.Texture(i)},s.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=s),exports.PIXI=s):"undefined"!=typeof define&&define.amd?define("PIXI",i.PIXI=s):i.PIXI=s,s}.call(this),function(){function t(t,e){this._scaleFactor=t,this._deltaMode=e,this.originalEvent=null}var e=this,i=i||{VERSION:"2.10.0",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,WEBGL_MULTI:4,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,PENDING_ATLAS:-1,HORIZONTAL:0,VERTICAL:1,LANDSCAPE:0,PORTRAIT:1,ANGLE_UP:270,ANGLE_DOWN:90,ANGLE_LEFT:180,ANGLE_RIGHT:0,ANGLE_NORTH_EAST:315,ANGLE_NORTH_WEST:225,ANGLE_SOUTH_EAST:45,ANGLE_SOUTH_WEST:135,TOP_LEFT:0,TOP_CENTER:1,TOP_RIGHT:2,LEFT_TOP:3,LEFT_CENTER:4,LEFT_BOTTOM:5,CENTER:6,RIGHT_TOP:7,RIGHT_CENTER:8,RIGHT_BOTTOM:9,BOTTOM_LEFT:10,BOTTOM_CENTER:11,BOTTOM_RIGHT:12,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},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{},_UID:0};if(Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Function.prototype.bind||(Function.prototype.bind=function(){var t=Array.prototype.slice;return function(e){function i(){var r=n.concat(t.call(arguments));s.apply(this instanceof i?this:e,r)}var s=this,n=t.call(arguments,1);if("function"!=typeof s)throw new TypeError;return i.prototype=function t(e){if(e&&(t.prototype=e),!(this instanceof t))return new t}(s.prototype),i}}()),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var s=arguments.length>=2?arguments[1]:void 0,n=0;n0&&100*Math.random()<=t},randomChoice:function(t,e){return Math.random()<.5?t:e},parseDimension:function(t,e){var i=0,s=0;return"string"==typeof t?"%"===t.substr(-1)?(i=parseInt(t,10)/100,s=0===e?window.innerWidth*i:window.innerHeight*i):s=parseInt(t,10):s=t,s},pad:function(t,e,i,s){if(void 0===e)var e=0;if(void 0===i)var i=" ";if(void 0===s)var s=3;var n=0;if(e+1>=(t=t.toString()).length)switch(s){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((n=e-t.length)/2),o=n-r;t=new Array(o+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t},isPlainObject:function(t){if("object"!=typeof t||t.nodeType||t===t.window)return!1;try{if(t.constructor&&!{}.hasOwnProperty.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},extend:function(){var t,e,s,n,r,o,a=arguments[0]||{},h=1,l=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[1]||{},h=2),l===h&&(a=this,--h);h0&&(this._radius=.5*s),this.type=i.CIRCLE},i.Circle.prototype={circumference:function(){return Math.PI*this._radius*2},random:function(t){void 0===t&&(t=new i.Point);var e=2*Math.PI*Math.random(),s=Math.random()+Math.random(),n=s>1?2-s:s,r=n*Math.cos(e),o=n*Math.sin(e);return t.x=this.x+r*this.radius,t.y=this.y+o*this.radius,t},getBounds:function(){return new i.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(t,e,i){return this.x=t,this.y=e,this._diameter=i,this._radius=.5*i,this},copyFrom:function(t){return this.setTo(t.x,t.y,t.diameter)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.diameter=this._diameter,t},distance:function(t,e){var s=i.Math.distance(this.x,this.y,t.x,t.y);return e?Math.round(s):s},clone:function(t){return void 0===t||null===t?t=new i.Circle(this.x,this.y,this.diameter):t.setTo(this.x,this.y,this.diameter),t},contains:function(t,e){return i.Circle.contains(this,t,e)},circumferencePoint:function(t,e,s){return i.Circle.circumferencePoint(this,t,e,s)},sample:function(t,e,s,n,r){t||(t=60),null==e&&(e=0),null==s&&(s=i.Math.PI2),r||(r=[]);for(var o=0;o0&&(this._diameter=t,this._radius=.5*t)}}),Object.defineProperty(i.Circle.prototype,"radius",{get:function(){return this._radius},set:function(t){t>0&&(this._radius=t,this._diameter=2*t)}}),Object.defineProperty(i.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(t){t>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-t}}),Object.defineProperty(i.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(t){tthis.y?(this._radius=0,this._diameter=0):this.radius=this.y-t}}),Object.defineProperty(i.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(t){t0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(i.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(t){!0===t&&this.setTo(0,0,0)}}),i.Circle.contains=function(t,e,i){return t.radius>0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom&&(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius},i.Circle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.diameter===e.diameter},i.Circle.intersects=function(t,e){return i.Math.distance(t.x,t.y,e.x,e.y)<=t.radius+e.radius},i.Circle.circumferencePoint=function(t,e,s,n){return void 0===s&&(s=!1),void 0===n&&(n=new i.Point),!0===s&&(e=i.Math.degToRad(e)),n.x=t.x+t.radius*Math.cos(e),n.y=t.y+t.radius*Math.sin(e),n},i.Circle.intersectsRectangle=function(t,e){var i=Math.abs(t.x-e.x-e.halfWidth);if(i>e.halfWidth+t.radius)return!1;var s=Math.abs(t.y-e.y-e.halfHeight);if(s>e.halfHeight+t.radius)return!1;if(i<=e.halfWidth||s<=e.halfHeight)return!0;var n=i-e.halfWidth,r=s-e.halfHeight;return n*n+r*r<=t.radius*t.radius},i.Circle.intersectsLine=function(t,e,s){var n=t.x,r=t.y,o=(e.end.y-e.start.y)/(e.end.x-e.start.x),a=e.end.y-o*e.end.x,h=t.radius,l=t.radius,c=a+o*n,u=(n*(l*l)-o*(h*h)*(a-r)+h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),d=(n*(l*l)-o*(h*h)*(a-r)-h*l*Math.sqrt(h*h*(o*o)+l*l-c*c-r*r+2*c*r))/(h*h*(o*o)+l*l),p=o*u+a,f=o*d+a,g=new i.Point(u,p),m=new i.Point(d,f),y=e.pointOnSegment(g.x,g.y,.01),v=e.pointOnSegment(m.x,m.y,.01);return y&&v?!s||[g,m]:y?!s||[g]:v?!s||[m]:!!s&&[]},PIXI.Circle=i.Circle,i.Ellipse=function(t,e,s,n){t=t||0,e=e||0,s=s||0,n=n||0,this.x=t,this.y=e,this.width=s,this.height=n,this.type=i.ELLIPSE},i.Ellipse.prototype={setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},getBounds:function(){return new i.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},clone:function(t){return void 0===t||null===t?t=new i.Ellipse(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t},contains:function(t,e){return i.Ellipse.contains(this,t,e)},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random()*Math.PI*2,s=Math.random();return t.x=Math.sqrt(s)*Math.cos(e),t.y=Math.sqrt(s)*Math.sin(e),t.x=this.x+t.x*this.width/2,t.y=this.y+t.y*this.height/2,t},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},i.Ellipse.prototype.constructor=i.Ellipse,Object.defineProperty(i.Ellipse.prototype,"left",{get:function(){return this.x},set:function(t){this.x=t}}),Object.defineProperty(i.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t=s&&t<=n&&e>=r&&e<=o},random:function(t){void 0===t&&(t=new i.Point);var e=Math.random();return t.x=this.start.x+e*(this.end.x-this.start.x),t.y=this.start.y+e*(this.end.y-this.start.y),t},coordinatesOnLine:function(t,e){void 0===t&&(t=1),void 0===e&&(e=[]);var i=Math.round(this.start.x),s=Math.round(this.start.y),n=Math.round(this.end.x),r=Math.round(this.end.y),o=Math.abs(n-i),a=Math.abs(r-s),h=i-a&&(c-=a,i+=h),d=0&&g<=1&&m>=0&&m<=1?o:null}return o},i.Line.intersects=function(t,e,s,n){return i.Line.intersectsPoints(t.start,t.end,e.start,e.end,s,n)},i.Line.intersectsRectangle=function(t,e){if(0===t.length||e.empty)return!1;var i=t.start.x,s=t.start.y,n=t.end.x,r=t.end.y,o=e.x,a=e.y,h=e.right,l=e.bottom,c=0;if(i>=o&&i<=h&&s>=a&&s<=l||n>=o&&n<=h&&r>=a&&r<=l)return!0;if(i=o){if((c=s+(r-s)*(o-i)/(n-i))>a&&c<=l)return!0}else if(i>h&&n<=h&&(c=s+(r-s)*(h-i)/(n-i))>=a&&c<=l)return!0;if(s=a){if((c=i+(n-i)*(a-s)/(r-s))>=o&&c<=h)return!0}else if(s>l&&r<=l&&(c=i+(n-i)*(l-s)/(r-s))>=o&&c<=h)return!0;return!1},i.Line.intersectionWithRectangle=function(t,e,s){var n=i.Line.intersectionWithRectangle;s||(s=new i.Point),n.edges||(n.edges=[new i.Line,new i.Line,new i.Line,new i.Line]),n.edgeIntersection||(n.edgeIntersection=new i.Point);var r=n.edges,o=n.edgeIntersection.set(0),a=e.x,h=e.y,l=e.right,c=e.bottom,u=1/0;r[0].setTo(a,h,l,h),r[1].setTo(a,c,l,c),r[2].setTo(a,h,a,c),r[3].setTo(l,h,l,c);for(var d,p=0;d=r[p];p++)if(t.intersects(d,!0,o)){var f=t.start.distance(o);fs&&(this.x=s),this.yn&&(this.y=n),this},clone:function(t){return void 0===t||null===t?t=new i.Point(this.x,this.y):t.setTo(this.x,this.y),t},copyTo:function(t){return t.x=this.x,t.y=this.y,t},distance:function(t,e){return i.Point.distance(this,t,e)},equals:function(t){return t.x===this.x&&t.y===this.y},equalsXY:function(t,e){return this.x===t&&this.y===e},fuzzyEquals:function(t,e){return i.Point.fuzzyEquals(this,t,e)},fuzzyEqualsXY:function(t,e,s){return i.Point.fuzzyEqualsXY(this,t,e,s)},angle:function(t,e){return this.angleXY(t.x,t.y,e)},angleXY:function(t,e,s){var n=Math.atan2(e-this.y,t-this.x);return s?i.Math.radToDeg(n):n},atan:function(t){var e=Math.atan2(this.y,this.x);return t?i.Math.radToDeg(e):e},rotate:function(t,e,s,n,r){return i.Point.rotate(this,t,e,s,n,r)},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(t){return this.normalize().multiply(t,t)},normalize:function(){if(!this.isZero()){var t=this.getMagnitude();this.x/=t,this.y/=t}return this},limit:function(t){return this.getMagnitudeSq()>t*t&&this.setMagnitude(t),this},expand:function(t){return this.getMagnitudeSq()=0&&e.x-i<0)return-1;if(t.x-i<0&&e.x-i>=0)return 1;if(t.x-i==0&&e.x-i==0)return t.y-s>=0||e.y-s>=0?t.y>e.y?1:-1:e.y>t.y?1:-1;var n=(t.x-i)*-(e.y-s)-(e.x-i)*-(t.y-s);return n<0?-1:n>0?1:(t.x-i)*(t.x-i)+(t.y-s)*(t.y-s)>(e.x-i)*(e.x-i)+(e.y-s)*(e.y-s)?-1:1})},PIXI.Point=i.Point,i.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.flattened=!1,this.type=i.POLYGON},i.Polygon.prototype={toNumberArray:function(t){void 0===t&&(t=[]);for(var e=0;e0){Array.isArray(t)||(t=Array.prototype.slice.call(arguments));for(var e=Number.MAX_VALUE,i=0,s=t.length;i=this.right?this.width=0:this.width=this.right-t,this.x=t}}),Object.defineProperty(i.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(i.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(i.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(i.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(t){this.x=t-this.halfWidth}}),Object.defineProperty(i.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(t){this.y=t-this.halfHeight}}),Object.defineProperty(i.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(i.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(i.Rectangle.prototype,"top",{get:function(){return this.y},set:function(t){t>=this.bottom?(this.height=0,this.y=t):this.height=this.bottom-t}}),Object.defineProperty(i.Rectangle.prototype,"topLeft",{get:function(){return new i.Point(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"topRight",{get:function(){return new i.Point(this.x+this.width,this.y)},set:function(t){this.right=t.x,this.y=t.y}}),Object.defineProperty(i.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),i.Rectangle.prototype.constructor=i.Rectangle,i.Rectangle.inflate=function(t,e,i){return t.x-=e,t.width+=2*e,t.y-=i,t.height+=2*i,t},i.Rectangle.inflatePoint=function(t,e){return i.Rectangle.inflate(t,e.x,e.y)},i.Rectangle.size=function(t,e){return void 0===e||null===e?e=new i.Point(t.width,t.height):e.setTo(t.width,t.height),e},i.Rectangle.clone=function(t,e){return void 0===e||null===e?e=new i.Rectangle(t.x,t.y,t.width,t.height):e.setTo(t.x,t.y,t.width,t.height),e},i.Rectangle.createFromBounds=function(t,e){return void 0!==e&&null!==e||(e=new i.Rectangle(t.x,t.y,t.width,t.height)),e.copyFromBounds(t)},i.Rectangle.contains=function(t,e,i){return!(t.width<=0||t.height<=0)&&(e>=t.x&&e=t.y&&i=t&&n=e&&re.volume)&&(t.x>=e.x&&t.y>=e.y&&t.righte.right||t.y>e.bottom)},i.Rectangle.intersectsRaw=function(t,e,i,s,n,r){return void 0===r&&(r=0),!(e>t.right+r||it.bottom+r||ns&&(s=t.x),t.xr&&(r=t.y),t.y=i&&t<=i+this.width){var s=this.y;if(e>=s&&e<=s+this.height)return!0}return!1}},i.RoundedRectangle.prototype.constructor=i.RoundedRectangle,PIXI.RoundedRectangle=i.RoundedRectangle,i.Camera=function(t,e,s,n,r,o){this.game=t,this.world=t.world,this.id=0,this.view=new i.Rectangle(s,n,r,o),this.bounds=new i.Rectangle(s,n,r,o),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this.lerp=new i.Point(1,1),this.onShakeComplete=new i.Signal,this.onFlashComplete=new i.Signal,this.onFadeComplete=new i.Signal,this.fx=null,this._targetPosition=new i.Point,this._edge=0,this._position=new i.Point,this._shake={intensity:0,duration:0,horizontal:!1,vertical:!1,shakeBounds:!0,x:0,y:0},this._fxDuration=0,this._fxType=0,this._fixedView=new i.Rectangle},i.Camera.FOLLOW_LOCKON=0,i.Camera.FOLLOW_PLATFORMER=1,i.Camera.FOLLOW_TOPDOWN=2,i.Camera.FOLLOW_TOPDOWN_TIGHT=3,i.Camera.SHAKE_BOTH=4,i.Camera.SHAKE_HORIZONTAL=5,i.Camera.SHAKE_VERTICAL=6,i.Camera.ENABLE_FX=!0,i.Camera.prototype={boot:function(){this.displayObject=this.game.world,this.scale=this.game.world.scale,this.game.camera=this,i.Graphics&&i.Camera.ENABLE_FX&&(this.fx=new i.Graphics(this.game),this.game.stage.addChild(this.fx))},preUpdate:function(){this.totalInView=0},follow:function(t,e,s,n){void 0===e&&(e=i.Camera.FOLLOW_LOCKON),void 0===s&&(s=1),void 0===n&&(n=1),this.target=t,this.lerp.set(s,n);var r;switch(e){case i.Camera.FOLLOW_PLATFORMER:var o=this.width/8,a=this.height/3;this.deadzone=new i.Rectangle((this.width-o)/2,(this.height-a)/2-.25*a,o,a);break;case i.Camera.FOLLOW_TOPDOWN:r=Math.max(this.width,this.height)/4,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_TOPDOWN_TIGHT:r=Math.max(this.width,this.height)/8,this.deadzone=new i.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case i.Camera.FOLLOW_LOCKON:default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(t){this.setPosition(Math.round(t.x-this.view.halfWidth),Math.round(t.y-this.view.halfHeight))},focusOnXY:function(t,e){this.setPosition(Math.round(t-this.view.halfWidth),Math.round(e-this.view.halfHeight))},shake:function(t,e,s,n,r){return void 0===t&&(t=.05),void 0===e&&(e=500),void 0===s&&(s=!0),void 0===n&&(n=i.Camera.SHAKE_BOTH),void 0===r&&(r=!0),!(!s&&this._shake.duration>0)&&(this._shake.intensity=t,this._shake.duration=e,this._shake.shakeBounds=r,this._shake.x=0,this._shake.y=0,this._shake.horizontal=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_HORIZONTAL,this._shake.vertical=n===i.Camera.SHAKE_BOTH||n===i.Camera.SHAKE_VERTICAL,!0)},flash:function(t,e,i,s){return void 0===t&&(t=16777215),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=1,this._fxDuration=e,this._fxType=0,!0)},fade:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=500),void 0===i&&(i=!1),void 0===s&&(s=1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t,s),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=0,this._fxDuration=e,this._fxType=1,!0)},update:function(){this._fxDuration>0&&this.updateFX(),this._shake.duration>0&&this.updateShake(),this.bounds&&this.checkBounds(),this.roundPx&&(this.view.floor(),this._shake.x=Math.floor(this._shake.x),this._shake.y=Math.floor(this._shake.y)),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateFX:function(){0===this._fxType?(this.fx.alpha-=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha<=0&&(this._fxDuration=0,this.fx.alpha=0,this.onFlashComplete.dispatch())):(this.fx.alpha+=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha>=1&&(this._fxDuration=0,this.fx.alpha=1,this.onFadeComplete.dispatch()))},updateShake:function(){this._shake.duration-=this.game.time.elapsedMS,this._shake.duration<=0?(this.onShakeComplete.dispatch(),this._shake.x=0,this._shake.y=0):(this._shake.horizontal&&(this._shake.x=this.game.rnd.frac()*this._shake.intensity*this.view.width*2-this._shake.intensity*this.view.width),this._shake.vertical&&(this._shake.y=this.game.rnd.frac()*this._shake.intensity*this.view.height*2-this._shake.intensity*this.view.height))},updateTarget:function(){this._targetPosition.x=this.view.x+this.target.worldPosition.x,this._targetPosition.y=this.view.y+this.target.worldPosition.y,this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edgethis.deadzone.right&&(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.right,this.lerp.x)),this._edge=this._targetPosition.y-this.view.y,this._edgethis.deadzone.bottom&&(this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.bottom,this.lerp.y))):(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.view.halfWidth,this.lerp.x),this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.view.halfHeight,this.lerp.y)),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},setBoundsToWorld:function(){this.bounds&&this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1;var t=this.view.x+this._shake.x,e=this.view.right+this._shake.x,i=this.view.y+this._shake.y,s=this.view.bottom+this._shake.y;t<=this.bounds.x*this.scale.x?(this.atLimit.x=!0,this.view.x=this.bounds.x*this.scale.x,this._shake.shakeBounds||(this._shake.x=0)):e>=this.bounds.right*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.right*this.scale.x-this.width,this._shake.shakeBounds||(this._shake.x=0)),i<=this.bounds.top*this.scale.y?(this.atLimit.y=!0,this.view.y=this.bounds.top*this.scale.y,this._shake.shakeBounds||(this._shake.y=0)):s>=this.bounds.bottom*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom*this.scale.y-this.height,this._shake.shakeBounds||(this._shake.y=0))},setPosition:function(t,e){this.view.x=t,this.view.y=e,this.bounds&&this.checkBounds()},setSize:function(t,e){this.view.width=t,this.view.height=e},reset:function(){this.target=null,this.view.x=0,this.view.y=0,this._shake.duration=0,this._shake.x=0,this._shake.y=0,this.resetFX()},resetFX:function(){this.fx&&(this.fx.clear(),this.fx.alpha=0),this._fxDuration=0}},i.Camera.prototype.constructor=i.Camera,Object.defineProperty(i.Camera.prototype,"x",{get:function(){return this.view.x},set:function(t){this.view.x=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"y",{get:function(){return this.view.y},set:function(t){this.view.y=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"position",{get:function(){return this._position.set(this.view.x,this.view.y),this._position},set:function(t){void 0!==t.x&&(this.view.x=t.x),void 0!==t.y&&(this.view.y=t.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(i.Camera.prototype,"width",{get:function(){return this.view.width},set:function(t){this.view.width=t}}),Object.defineProperty(i.Camera.prototype,"height",{get:function(){return this.view.height},set:function(t){this.view.height=t}}),Object.defineProperty(i.Camera.prototype,"shakeIntensity",{get:function(){return this._shake.intensity},set:function(t){this._shake.intensity=t}}),Object.defineProperty(i.Camera.prototype,"fixedView",{get:function(){return this._fixedView.setTo(0,0,this.view.width,this.view.height),this._fixedView}}),i.State=function(){this.game=null,this.key="",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.state=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},i.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},i.State.prototype.constructor=i.State,i.StateManager=function(t,e){this.game=t,this.states={},this._pendingState=null,void 0!==e&&null!==e&&(this._pendingState=e),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new i.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},i.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(t,e,s){void 0===s&&(s=!1);var n;return e instanceof i.State?n=e:"object"==typeof e?(n=e).game=this.game:"function"==typeof e&&(n=new e(this.game)),this.states[t]=n,s&&(this.game.isBooted?this.start(t):this._pendingState=t),n},remove:function(t){this.current===t&&(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.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[t]},start:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1),this.checkState(t)&&(this._pendingState=t,this._clearWorld=e,this._clearCache=i,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!1),this._pendingState=this.current,this._clearWorld=t,this._clearCache=e,arguments.length>2&&(this._args=Array.prototype.slice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var t=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,t),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache&&this.game.cache.destroy()))},checkState:function(t){var e=this.states[t];return e?!!(e.preload||e.create||e.update||e.render)||(console.warn("Invalid Phaser State object given. Must contain at least one of the required functions: preload, create, update or render"),!1):(console.warn("Phaser.StateManager - No state found with the key: "+t),!1)},link:function(t){var e=this.states[t];e.game=this.game,e.add=this.game.add,e.make=this.game.make,e.camera=this.game.camera,e.cache=this.game.cache,e.input=this.game.input,e.load=this.game.load,e.math=this.game.math,e.sound=this.game.sound,e.scale=this.game.scale,e.state=this,e.stage=this.game.stage,e.time=this.game.time,e.tweens=this.game.tweens,e.world=this.game.world,e.particles=this.game.particles,e.rnd=this.game.rnd,e.physics=this.game.physics,e.key=t},unlink:function(t){var e=this.states[t];e&&(e.game=null,e.add=null,e.make=null,e.camera=null,e.cache=null,e.input=null,e.load=null,e.math=null,e.sound=null,e.scale=null,e.state=null,e.stage=null,e.time=null,e.tweens=null,e.world=null,e.particles=null,e.rnd=null,e.physics=null)},setCurrentState:function(t){var e=this.states[t];this.callbackContext=e,this.link(t),this.onInitCallback=e.init||this.dummy,this.onPreloadCallback=e.preload||null,this.onLoadRenderCallback=e.loadRender||null,this.onLoadUpdateCallback=e.loadUpdate||null,this.onCreateCallback=e.create||null,this.onUpdateCallback=e.update||null,this.onPreRenderCallback=e.preRender||null,this.onRenderCallback=e.render||null,this.onResizeCallback=e.resize||null,this.onPausedCallback=e.paused||null,this.onResumedCallback=e.resumed||null,this.onPauseUpdateCallback=e.pauseUpdate||null,this.onShutDownCallback=e.shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=t,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),t===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){!1===this._created&&this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game),!1===this._created&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(t){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,t)},resize:function(t,e){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,t,e)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===i.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this._clearWorld=!0,this._clearCache=!0,this.clearCurrentState(),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,this.current=""}},i.StateManager.prototype.constructor=i.StateManager,Object.defineProperty(i.StateManager.prototype,"created",{get:function(){return this._created}}),i.Signal=function(){},i.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!1,validateListener:function(t,e){if("function"!=typeof t)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",e))},_registerListener:function(t,e,s,n,r){var o,a=this._indexOfListener(t,s);if(-1!==a){if((o=this._bindings[a]).isOnce()!==e)throw new Error("You cannot add"+(e?"":"Once")+"() then add"+(e?"Once":"")+"() the same listener without removing the relationship first.")}else o=new i.SignalBinding(this,t,e,s,n,r),this._addBinding(o);return this.memorize&&this._prevParams&&o.execute(this._prevParams),o},_addBinding:function(t){this._bindings||(this._bindings=[]);var e=this._bindings.length;do{e--}while(this._bindings[e]&&t._priority<=this._bindings[e]._priority);this._bindings.splice(e+1,0,t)},_indexOfListener:function(t,e){if(!this._bindings)return-1;void 0===e&&(e=null);for(var i,s=this._bindings.length;s--;)if((i=this._bindings[s])._listener===t&&i.context===e)return s;return-1},has:function(t,e){return-1!==this._indexOfListener(t,e)},add:function(t,e,i){this.validateListener(t,"add");var s=[];if(arguments.length>3)for(var n=3;n3)for(var n=3;n=this.children.length?-1:this.getChildAt(t)},i.Group.prototype.create=function(t,e,i,s,n,r){void 0===n&&(n=!0);var o=new this.classType(this.game,t,e,i,s);return o.exists=n,o.visible=n,o.alive=n,this.add(o,!1,r)},i.Group.prototype.createMultiple=function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=!1),Array.isArray(e)||(e=[e]),Array.isArray(i)||(i=[i]);var o=this,a=[];return e.forEach(function(e){i.forEach(function(i){for(var h=0;hthis.children.length||-1===t&&-1===e)return!1;for(var a=new i.Rectangle(0,0,s,n),h=t*s,l=e*n,c=o;cthis.children.length-1&&(t=0),this.cursor)return this.cursorIndex=t,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.next=function(){if(this.cursor)return this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.previous=function(){if(this.cursor)return 0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor},i.Group.prototype.swap=function(t,e){this.swapChildren(t,e),this.updateZ()},i.Group.prototype.bringToTop=function(t){return t.parent===this&&this.getIndex(t)0&&(this.remove(t,!1,!0),this.addAt(t,0,!0)),t},i.Group.prototype.moveUp=function(t){if(t.parent===this&&this.getIndex(t)0){var e=this.getIndex(t),i=this.getAt(e-1);i&&this.swap(t,i)}return t},i.Group.prototype.xy=function(t,e,i){if(t<0||t>this.children.length)return-1;this.getChildAt(t).x=e,this.getChildAt(t).y=i},i.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},i.Group.prototype.getIndex=function(t){return this.children.indexOf(t)},i.Group.prototype.getByName=function(t){for(var e=0;e0))return!1;var r=e.length;return 1===r?0===s?t[e[0]]=i:1===s?t[e[0]]+=i:2===s?t[e[0]]-=i:3===s?t[e[0]]*=i:4===s&&(t[e[0]]/=i):2===r?0===s?t[e[0]][e[1]]=i:1===s?t[e[0]][e[1]]+=i:2===s?t[e[0]][e[1]]-=i:3===s?t[e[0]][e[1]]*=i:4===s&&(t[e[0]][e[1]]/=i):3===r?0===s?t[e[0]][e[1]][e[2]]=i:1===s?t[e[0]][e[1]][e[2]]+=i:2===s?t[e[0]][e[1]][e[2]]-=i:3===s?t[e[0]][e[1]][e[2]]*=i:4===s&&(t[e[0]][e[1]][e[2]]/=i):4===r&&(0===s?t[e[0]][e[1]][e[2]][e[3]]=i:1===s?t[e[0]][e[1]][e[2]][e[3]]+=i:2===s?t[e[0]][e[1]][e[2]][e[3]]-=i:3===s?t[e[0]][e[1]][e[2]][e[3]]*=i:4===s&&(t[e[0]][e[1]][e[2]][e[3]]/=i)),!0},i.Group.prototype.checkProperty=function(t,e,s,n){if(void 0===n&&(n=!1),this!==t.parent)return!1;var r=i.Utils.getProperty(t,e);return!(void 0===r&&n||r!==s)},i.Group.prototype.set=function(t,e,i,s,n,r,o){if(void 0===o&&(o=!1),e=e.split("."),void 0===s&&(s=!1),void 0===n&&(n=!1),(!1===s||s&&t.alive)&&(!1===n||n&&t.visible))return this.setProperty(t,e,i,r,o)},i.Group.prototype.setAll=function(t,e,i,s,n,r){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===r&&(r=!1),t=t.split("."),n=n||0;for(var o=0;o2){i=[];for(s=2;s2){n=[];for(a=2;a=e&&(t=e-1);var i=this.children[t];this.updateOnlyExistingChildren&&!i.exists||i.update()}},i.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y);for(var t=0;t2){s=[null];for(var n=2;n2){s=[null];for(var n=2;n2){s=[null];for(var n=2;ne[this._sortProperty]?1:t.ze[this._sortProperty]?-1:0},i.Group.prototype.iterate=function(t,e,s,n,r,o){if(0===this.children.length){if(s===i.Group.RETURN_TOTAL)return 0;if(s===i.Group.RETURN_ALL)return[]}var a=0;if(s===i.Group.RETURN_ALL)var h=[];for(var l=0;l0)return this.children[this.children.length-1]},i.Group.prototype.getBottom=function(){if(this.children.length>0)return this.children[0]},i.Group.prototype.getClosestTo=function(t,e,s){for(var n=Number.MAX_VALUE,r=0,o=null,a=0;an&&(!e||e.call(s,h,r))&&(n=r,o=h)}return o},i.Group.prototype.count=function(t,e){return this.iterate(t,e,i.Group.RETURN_TOTAL)},i.Group.prototype.countLiving=function(){return this.count("alive",!0)},i.Group.prototype.countDead=function(){return this.count("alive",!1)},i.Group.prototype.getRandom=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.children.length),0===e?null:i.ArrayUtils.getRandomItem(this.children,t,e)},i.Group.prototype.getRandomExists=function(t,e){var i=this.getAll("exists",!0,t,e);return this.game.rnd.pick(i)},i.Group.prototype.getAll=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=this.children.length);for(var n=[],r=i;r0&&t instanceof i.Group){do{t.add(this.children[0],e)}while(this.children.length>0);this.hash=[],this.cursor=null}return t},i.Group.prototype.removeAll=function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),0!==this.children.length){do{!e&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var s=this.removeChild(this.children[0]);this.removeFromHash(s),t&&s&&s.destroy(!0,i)}while(this.children.length>0);this.hash=[],this.cursor=null}},i.Group.prototype.removeBetween=function(t,e,i,s){if(void 0===e&&(e=this.children.length-1),void 0===i&&(i=!1),void 0===s&&(s=!1),0!==this.children.length){if(t>e||t<0||e>this.children.length)return!1;for(var n=e;n>=t;){!s&&this.children[n].events&&this.children[n].events.onRemovedFromGroup$dispatch(this.children[n],this);var r=this.removeChild(this.children[n]);this.removeFromHash(r),i&&r&&r.destroy(!0),this.cursor===this.children[n]&&(this.cursor=null),n--}this.updateZ()}},i.Group.prototype.scatter=function(t,e){null==t&&(t=this.game.world.bounds),this.forEach(function(e){e.position.set(t.randomX,t.randomY)},null,e)},i.Group.prototype.shuffle=function(){i.ArrayUtils.shuffle(this.children),this.updateZ()},i.Group.prototype.destroy=function(t,e){null===this.game||this.ignoreDestroy||(void 0===t&&(t=!0),void 0===e&&(e=!1),this.onDestroy.dispatch(this,t,e),this.removeAll(t),this.cursor=null,this.filters=null,this.pendingDestroy=!1,e||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(i.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,i.Group.RETURN_TOTAL)}}),Object.defineProperty(i.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(i.Group.prototype,"angle",{get:function(){return i.Math.radToDeg(this.rotation)},set:function(t){this.rotation=i.Math.degToRad(t)}}),Object.defineProperty(i.Group.prototype,"centerX",{get:function(){return this.getBounds(this.parent).centerX},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.halfWidth}}),Object.defineProperty(i.Group.prototype,"centerY",{get:function(){return this.getBounds(this.parent).centerY},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.halfHeight}}),Object.defineProperty(i.Group.prototype,"left",{get:function(){return this.getBounds(this.parent).left},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i}}),Object.defineProperty(i.Group.prototype,"right",{get:function(){return this.getBounds(this.parent).right},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.width}}),Object.defineProperty(i.Group.prototype,"top",{get:function(){return this.getBounds(this.parent).top},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i}}),Object.defineProperty(i.Group.prototype,"bottom",{get:function(){return this.getBounds(this.parent).bottom},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.height}}),i.World=function(t){i.Group.call(this,t,null,"__world",!1),this.bounds=new i.Rectangle(0,0,t.width,t.height),this.camera=null,this._definedSize=!1,this._width=t.width,this._height=t.height,this.game.state.onStateChange.add(this.stateChange,this)},i.World.prototype=Object.create(i.Group.prototype),i.World.prototype.constructor=i.World,i.World.prototype.boot=function(){this.camera=new i.Camera(this.game,0,0,0,this.game.width,this.game.height),this.game.stage.addChild(this),this.camera.boot()},i.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},i.World.prototype.setBounds=function(t,e,i,s){this._definedSize=!0,this._width=i,this._height=s,this.bounds.setTo(t,e,i,s),this.x=t,this.y=e,this.camera.bounds&&this.camera.bounds.setTo(t,e,Math.max(i,this.game.width),Math.max(s,this.game.height)),this.game.physics.setBoundsToWorld()},i.World.prototype.resize=function(t,e){this._definedSize&&(tthis.bounds.right&&(t.x=this.bounds.left)),n&&(t.y+t._currentBounds.heightthis.bounds.bottom&&(t.y=this.bounds.top))):(s&&t.x+ethis.bounds.right&&(t.x=this.bounds.left-e),n&&t.y+ethis.bounds.bottom&&(t.y=this.bounds.top-e))},i.World.prototype.wrapAll=function(t,e,i,s,n,r){t.forEach(this.wrap,this,e,i,s,n,r)},Object.defineProperty(i.World.prototype,"width",{get:function(){return this.bounds.width},set:function(t){t1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.dropFrames?this.rendersThisFrame=0:(this.updateRender(this.time.slowMotion*this.time.desiredFps),this.rendersThisFrame=1);else{var e=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*e,this.time.elapsed),0);var i=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/e),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame)),this.forceSingleRender?this.rendersThisFrame=1:this.rendersThisFrame=Math.min(1,this.updatesThisFrame);this._deltaTime>=e&&(this._deltaTime-=e,this.currentUpdateID=i,this.updateLogic(this.time.desiredFpsMult),i++,!this.forceSingleUpdate||1!==i);)this.time.refresh();i>this._lastCount?this._spiraling++:i0&&this.updateRender(this._deltaTime/e)}}},updateLogic:function(t){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(t),this.debug.preUpdate(),this.input.pauseUpdate()):(this.stepping&&(this.pendingStep=!0),this.time.countUpdate(),this.scale.preUpdate(),this.debug.preUpdate(),this.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(t),this.plugins.preUpdate(t),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(),this.sound.update(),this.input.update(),this.physics.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate()),this.stage.updateTransform()},updateRender:function(t){this.lockRender||(this.time.countRender(),this.state.preRender(t),this.renderType!==i.HEADLESS&&(this.renderer.render(this.stage),this.plugins.render(t),this.state.render(t)),this.plugins.postRender(t))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.debug.destroy&&this.debug.destroy(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.plugins.destroy(),this.debug=null,this.state=null,this.sound=null,this.scale=null,this.stage=null,this.input=null,this.physics=null,this.plugins=null,this.cache=null,this.load=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),i.Canvas.removeFromDOM(this.canvas),PIXI.defaultRenderer=null,i.GAMES[this.id]=null},gamePaused:function(t){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.muteOnPause&&this.sound.setMute(),this.onPause.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(t){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.muteOnPause&&this.sound.unsetMute(),this.onResume.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(t){this.onBlur.dispatch(t),this.stage.disableVisibilityChange||this.gamePaused(t)},focusGain:function(t){this.onFocus.dispatch(t),this.stage.disableVisibilityChange||this.gameResumed(t)}},i.Game.prototype.constructor=i.Game,Object.defineProperty(i.Game.prototype,"paused",{get:function(){return this._paused},set:function(t){!0===t?(!1===this._paused&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),i.Input=function(t){this.game=t,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.customCandidateHandler=null,this.customCandidateHandlerContext=null,this.pollRate=0,this.enabled=!0,this.multiInputOverride=i.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.touchLockCallbacks=[],this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new i.ArraySet,this._localPoint=new i.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},i.Input.MOUSE_OVERRIDES_TOUCH=0,i.Input.TOUCH_OVERRIDES_MOUSE=1,i.Input.MOUSE_TOUCH_COMBINE=2,i.Input.MAX_POINTERS=10,i.Input.prototype={boot:function(){this.mousePointer=new i.Pointer(this.game,0,i.PointerMode.CURSOR),this.addPointer(),this.addPointer(),this.mouse=new i.Mouse(this.game),this.touch=new i.Touch(this.game),this.mspointer=new i.MSPointer(this.game),i.Keyboard&&(this.keyboard=new i.Keyboard(this.game)),i.Gamepad&&(this.gamepad=new i.Gamepad(this.game)),this.onDown=new i.Signal,this.onUp=new i.Signal,this.onTap=new i.Signal,this.onHold=new i.Signal,this.scale=new i.Point(1,1),this.speed=new i.Point,this.position=new i.Point,this._oldPosition=new i.Point,this.circle=new i.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=i.CanvasPool.create(this,1,1),this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.game.device.mspointer||this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var t=this;this._onClickTrampoline=function(e){t.onClickTrampoline(e)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],i.CanvasPool.remove(this),this.game.canvas.removeEventListener("click",this._onClickTrampoline)},setInteractiveCandidateHandler:function(t,e){this.customCandidateHandler=t,this.customCandidateHandlerContext=e},addMoveCallback:function(t,e){this.moveCallbacks.push({callback:t,context:e})},addTouchLockCallback:function(t,e,i){void 0===i&&(i=!1),this.touchLockCallbacks.push({callback:t,context:e,onEnd:i})},removeTouchLockCallback:function(t,e){for(var i=this.touchLockCallbacks.length;i--;)if(this.touchLockCallbacks[i].callback===t&&this.touchLockCallbacks[i].context===e)return this.touchLockCallbacks.splice(i,1),!0;return!1},executeTouchLockCallbacks:function(t,e){for(var i=this.touchLockCallbacks.length;i--;){var s=this.touchLockCallbacks[i];s.onEnd===t&&s.callback.call(s.context,this,e)&&this.touchLockCallbacks.splice(i,1)}},deleteMoveCallback:function(t,e){for(var i=this.moveCallbacks.length;i--;)if(this.moveCallbacks[i].callback===t&&this.moveCallbacks[i].context===e)return void this.moveCallbacks.splice(i,1)},addPointer:function(){if(this.pointers.length>=i.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+i.Input.MAX_POINTERS+" pointers reached."),null;var t=this.pointers.length+1,e=new i.Pointer(this.game,t,i.PointerMode.CONTACT);return this.pointers.push(e),this["pointer"+t]=e,e},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(t);if(!this.pointer2.active)return this.pointer2.start(t);for(var e=2;e0;i++)this.pointers[i].active&&e--;return t-e},getPointer:function(t){void 0===t&&(t=!1);for(var e=0;e=o&&this.game.camera.x+e.x=a&&this.game.camera.y+e.y=o&&this._localPoint.x=a&&this._localPoint.y=o&&this._localPoint.x=a&&this._localPoint.y0&&this._pollCounterthis.game.time.time},justReleased:function(t){return t=t||250,this.isUp&&this.timeUp+t>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},i.DeviceButton.prototype.constructor=i.DeviceButton,Object.defineProperty(i.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),i.Pointer=function(t,e,s){this.game=t,this.id=e,this.type=i.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.pointerMode=s||i.PointerMode.CURSOR|i.PointerMode.CONTACT,this.target=null,this.button=null,this.leftButton=new i.DeviceButton(this,i.Pointer.LEFT_BUTTON),this.middleButton=new i.DeviceButton(this,i.Pointer.MIDDLE_BUTTON),this.rightButton=new i.DeviceButton(this,i.Pointer.RIGHT_BUTTON),this.backButton=new i.DeviceButton(this,i.Pointer.BACK_BUTTON),this.forwardButton=new i.DeviceButton(this,i.Pointer.FORWARD_BUTTON),this.eraserButton=new i.DeviceButton(this,i.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===e,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.interactiveCandidates=[],this.active=!1,this.dirty=!1,this.position=new i.Point,this.positionDown=new i.Point,this.positionUp=new i.Point,this.circle=new i.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},i.Pointer.NO_BUTTON=0,i.Pointer.LEFT_BUTTON=1,i.Pointer.RIGHT_BUTTON=2,i.Pointer.MIDDLE_BUTTON=4,i.Pointer.BACK_BUTTON=8,i.Pointer.FORWARD_BUTTON=16,i.Pointer.ERASER_BUTTON=32,i.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.start(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.start(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.start(e),t===i.Mouse.BACK_BUTTON&&this.backButton.start(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.start(e)},processButtonsUp:function(t,e){t===i.Mouse.LEFT_BUTTON&&this.leftButton.stop(e),t===i.Mouse.RIGHT_BUTTON&&this.rightButton.stop(e),t===i.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(e),t===i.Mouse.BACK_BUTTON&&this.backButton.stop(e),t===i.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(e)},processButtonsUpDown:function(t,e){var s="down"===e.type.toLowerCase().substr(-4),n="move"===e.type.toLowerCase().substr(-4);void 0!==t?(s&&1===t&&e.ctrlKey&&(t=2),this.leftButton.startStop(i.Pointer.LEFT_BUTTON&t,e),this.rightButton.startStop(i.Pointer.RIGHT_BUTTON&t,e),this.middleButton.startStop(i.Pointer.MIDDLE_BUTTON&t,e),this.backButton.startStop(i.Pointer.BACK_BUTTON&t,e),this.forwardButton.startStop(i.Pointer.FORWARD_BUTTON&t,e),this.eraserButton.startStop(i.Pointer.ERASER_BUTTON&t,e)):void 0!==e.button?s&&e.ctrlKey&&0===e.button?this.rightButton.start(e):s?this.processButtonsDown(e.button,e):n||this.processButtonsUp(e.button,e):s?e.ctrlKey?this.rightButton.start(e):this.leftButton.start(e):(this.leftButton.stop(e),this.rightButton.stop(e))},updateButtons:function(t){this.button=t.button,this.processButtonsUpDown(t.buttons,t),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(t){var e=this.game.input;return t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.isMouse?this.updateButtons(t):(this.isDown=!0,this.isUp=!1),this.active=!0,this.withinGame=!0,this.dirty=!1,this._history=[],this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(t,!0),this.positionDown.setTo(this.x,this.y),(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.x=this.x,e.y=this.y,e.position.setTo(this.x,this.y),e.onDown.dispatch(this,t),e.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){var t=this.game.input;this.active&&(this.dirty&&(t.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),!1===this._holdSent&&this.duration>=t.holdRate&&((t.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||t.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||t.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===t.totalActivePointers)&&t.onHold.dispatch(this),this._holdSent=!0),t.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+t.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>t.recordLimit&&this._history.shift()))},move:function(t,e){var s=this.game.input;if(!s.pollLocked){void 0===e&&(e=!1),void 0!==t.button&&(this.button=t.button),this.isMouse&&this.updateButtons(t),this.clientX=t.clientX,this.clientY=t.clientY,this.pageX=t.pageX,this.pageY=t.pageY,this.screenX=t.screenX,this.screenY=t.screenY,this.isMouse&&s.mouse.locked&&!e&&(this.rawMovementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.rawMovementY=t.movementY||t.mozMovementY||t.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*s.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*s.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(s.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||s.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||s.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===s.totalActivePointers)&&(s.activePointer=this,s.x=this.x,s.y=this.y,s.position.setTo(s.x,s.y),s.circle.x=s.x,s.circle.y=s.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY);for(var n=s.moveCallbacks.length;n--;)s.moveCallbacks[n].callback.call(s.moveCallbacks[n].context,this,this.x,this.y,e);return null===this.targetObject||this.game.paused&&!this.targetObject.noPause||!0!==this.targetObject.isDragged?s.interactiveItems.total>0&&this.processInteractiveObjects(e):!1===this.targetObject.update(this)&&(this.targetObject=null),this}},processInteractiveObjects:function(t){var e=0,i=-1,s=null,n=this.game.input.interactiveItems.first;for(this.interactiveCandidates=[];n;)n.checked=!1,!n.validForInput(i,e,!1)||this.game.paused&&!n.sprite.noPause||(n.checked=!0,(t&&n.checkPointerDown(this,!0)||!t&&n.checkPointerOver(this,!0))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n))),n=this.game.input.interactiveItems.next;for(n=this.game.input.interactiveItems.first;n;)!n.checked&&n.validForInput(i,e,!0)&&(t&&n.checkPointerDown(this,!1)||!t&&n.checkPointerOver(this,!1))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n)),n=this.game.input.interactiveItems.next;return this.game.input.customCandidateHandler&&(s=this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext,this,this.interactiveCandidates,s)),this.swapTarget(s,!1),null!==this.targetObject},swapTarget:function(t,e){void 0===e&&(e=!1),null===t?this.targetObject&&(this.targetObject._pointerOutHandler(this,e),this.targetObject=null):null===this.targetObject?(this.targetObject=t,t._pointerOverHandler(this,e)):this.targetObject===t?!1===t.update(this)&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this,e),this.targetObject=t,this.targetObject._pointerOverHandler(this,e))},leave:function(t){this.withinGame=!1,this.move(t,!1)},stop:function(t){var e=this.game.input;{if(!this._stateReset||!this.withinGame)return this.timeUp=this.game.time.time,(e.multiInputOverride===i.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===i.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===i.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.onUp.dispatch(this,t),this.duration>=0&&this.duration<=e.tapRate&&(this.timeUp-this.previousTapTime0&&(this.active=!1),this.withinGame=this.game.scale.bounds.contains(t.pageX,t.pageY),this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),!1===this.isMouse&&e.currentPointers--,e.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this;t.preventDefault()}},justPressed:function(t){return t=t||this.game.input.justPressedRate,!0===this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||this.game.input.justReleasedRate,this.isUp&&this.timeUp+t>this.game.time.time},addClickTrampoline:function(t,e,i,s){if(this.isDown){for(var n=this._clickTrampolines=this._clickTrampolines||[],r=0;rt||this.priorityID===t&&this.sprite.renderOrderID>e))},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(t){return t=t||0,this._pointerData[t].x},pointerY:function(t){return t=t||0,this._pointerData[t].y},pointerDown:function(t){return t=t||0,this._pointerData[t].isDown},pointerUp:function(t){return t=t||0,this._pointerData[t].isUp},pointerTimeDown:function(t){return t=t||0,this._pointerData[t].timeDown},pointerTimeUp:function(t){return t=t||0,this._pointerData[t].timeUp},pointerOver:function(t){if(!this.enabled)return!1;if(void 0===t){for(var e=0;e<10;e++)if(this._pointerData[e].isOver)return!0;return!1}return this._pointerData[t].isOver},pointerOut:function(t){if(!this.enabled)return!1;if(void 0!==t)return this._pointerData[t].isOut;for(var e=0;e<10;e++)if(this._pointerData[e].isOut)return!0},pointerTimeOver:function(t){return t=t||0,this._pointerData[t].timeOver},pointerTimeOut:function(t){return t=t||0,this._pointerData[t].timeOut},pointerDragged:function(t){return t=t||0,this._pointerData[t].isDragged},checkPointerDown:function(t,e){return!!(t.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectClick)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPointerOver:function(t,e){return!!(this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectOver)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPixel:function(t,e,i){if(this.sprite.texture.baseTexture.source){if(null===t&&null===e){this.game.input.getLocalPosition(this.sprite,i,this._tempPoint);var t=this._tempPoint.x,e=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(t-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(e-=-this.sprite.texture.frame.height*this.sprite.anchor.y),t+=this.sprite.texture.frame.x,e+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(t-=this.sprite.texture.trim.x,e-=this.sprite.texture.trim.y,tthis.sprite.texture.crop.right||ethis.sprite.texture.crop.bottom))return this._dx=t,this._dy=e,!1;if(this._dx=t,this._dy=e,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,t,e,1,1,0,0,1,1),this.game.input.hitContext.getImageData(0,0,1,1).data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(t){if(null!==this.sprite&&void 0!==this.sprite.parent)return this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this._pendingDrag?(this._dragDistancePass||(this._dragDistancePass=i.Math.distance(t.x,t.y,this.downPoint.x,this.downPoint.y)>=this.dragDistanceThreshold),this._dragDistancePass&&this._dragTimePass&&this.startDrag(t),!0):this.draggable&&this._draggedPointerID===t.id?this.updateDrag(t,!1):this._pointerData[t.id].isOver?this.checkPointerOver(t)?(this._pointerData[t.id].x=t.x-this.sprite.x,this._pointerData[t.id].y=t.y-this.sprite.y,!0):(this._pointerOutHandler(t),!1):void 0:(this._pointerOutHandler(t),!1)},_pointerOverHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];if(!1===i.isOver||t.dirty){var s=!1===i.isOver;i.isOver=!0,i.isOut=!1,i.timeOver=this.game.time.time,i.x=t.x-this.sprite.x,i.y=t.y-this.sprite.y,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),!e&&s&&this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,t),this.sprite.parent&&this.sprite.parent.onChildInputOver&&this.sprite.parent.onChildInputOver.dispatch(this.sprite,t)}}},_pointerOutHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];i.isOver=!1,i.isOut=!0,i.timeOut=this.game.time.time,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="",this._setHandCursor=!1),!e&&this.sprite&&this.sprite.events&&(this.sprite.events.onInputOut$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputOut&&this.sprite.parent.onChildInputOut.dispatch(this.sprite,t))}},_touchedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(!e.isDown&&e.isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,t))return;if(e.isDown=!0,e.isUp=!1,e.timeDown=this.game.time.time,this.downPoint.set(t.x,t.y),t.dirty=!0,this.sprite&&this.sprite.events&&(this.sprite.events.onInputDown$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputDown&&this.sprite.parent.onChildInputDown.dispatch(this.sprite,t),null===this.sprite))return;this.draggable&&!1===this.isDragged&&(0===this.dragTimeThreshold&&0===this.dragDistanceThreshold?this.startDrag(t):(this._pendingDrag=!0,this._dragDistancePass=0===this.dragDistanceThreshold,this.dragTimeThreshold>0?(this._dragTimePass=!1,this.game.time.events.add(this.dragTimeThreshold,this.dragTimeElapsed,this,t)):this._dragTimePass=!0)),this.bringToTop&&this.sprite.bringToTop()}}},dragTimeElapsed:function(t){this._dragTimePass=!0,this._pendingDrag&&this.sprite&&this._dragDistancePass&&this.startDrag(t)},_releasedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(e.isDown&&t.isUp){e.isDown=!1,e.isUp=!0,e.timeUp=this.game.time.time,e.downDuration=e.timeUp-e.timeDown;var i=this.checkPointerOver(t);this.sprite&&this.sprite.events&&(this.dragStopBlocksInputUp&&(!this.dragStopBlocksInputUp||this.draggable&&this.isDragged&&this._draggedPointerID===t.id)||this.sprite.events.onInputUp$dispatch(this.sprite,t,i),this.sprite&&this.sprite.parent&&this.sprite.parent.onChildInputUp&&this.sprite.parent.onChildInputUp.dispatch(this.sprite,t,i),i&&(i=this.checkPointerOver(t))),e.isOver=i,!i&&this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),t.dirty=!0,this._pendingDrag=!1,this.draggable&&this.isDragged&&this._draggedPointerID===t.id&&this.stopDrag(t)}}},updateDrag:function(t,e){if(void 0===e&&(e=!1),t.isUp)return this.stopDrag(t),!1;var i=this.globalToLocal(t);if(this.sprite.fixedToCamera)var s=this.game.camera.scale.x*i.x+this._dragPoint.x+this.dragOffset.x,n=this.game.camera.scale.y*i.y+this._dragPoint.y+this.dragOffset.y;else var s=i.x+this._dragPoint.x+this.dragOffset.x,n=i.y+this._dragPoint.y+this.dragOffset.y;if(this.sprite.fixedToCamera)this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=s-this.game.camera.x),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=n-this.game.camera.y),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y));else{var r=this.game.camera.x-this._pointerData[t.id].camX,o=this.game.camera.y-this._pointerData[t.id].camY;this.allowHorizontalDrag&&(this.sprite.x=s+r),this.allowVerticalDrag&&(this.sprite.y=n+o),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),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,this.snapPoint.set(this.sprite.x,this.sprite.y))}return this.sprite.events.onDragUpdate.dispatch(this.sprite,t,s,n,this.snapPoint,e),!0},justOver:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOver&&this.overDuration(t)this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.ythis.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.leftthis.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.xthis.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.ythis.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.leftthis.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.topthis.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},i.InputHandler.prototype.constructor=i.InputHandler,i.Gamepad=function(t){this.game=t,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!==navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this),new i.SinglePad(t,this)]},i.Gamepad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},start:function(){if(!this._active){this._active=!0;var t=this;this._onGamepadConnected=function(e){return t.onGamepadConnected(e)},this._onGamepadDisconnected=function(e){return t.onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(t){var e=t.gamepad;this._rawPads.push(e),this._gamepads[e.index].connect(e)},onGamepadDisconnected:function(t){var e=t.gamepad;for(var i in this._rawPads)this._rawPads[i].index===e.index&&this._rawPads.splice(i,1);this._gamepads[e.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(this._active){if(navigator.getGamepads)t=navigator.getGamepads();else if(navigator.webkitGetGamepads)t=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var t=navigator.webkitGamepads();if(t){this._rawPads=[];for(var e=!1,i=0;i0&&s>this.deadZone||s<0&&s<-this.deadZone?this.processAxisChange(i,s):this.processAxisChange(i,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(t){var e=!this.connected;this.connected=!0,this.index=t.index,this._rawPad=t,this._buttons=[],this._buttonsLen=t.buttons.length,this._axes=[],this._axesLen=t.axes.length;for(var s=0;sthis.maxHealth&&(this.health=this.maxHealth),this},heal:function(t){return this.alive&&(this.health+=t,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},i.Component.InCamera=function(){},i.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},i.Component.InputEnabled=function(){},i.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(t){t?null===this.input?(this.input=new i.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},i.Component.InWorld=function(){},i.Component.InWorld.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(this.autoCull||this.checkWorldBounds){if(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull)if(this.game.world.camera.view.intersects(this._bounds))this.renderable=!0,this.game.world.camera.totalInView++;else if(this.renderable=!1,this.outOfCameraBoundsKill)return this.kill(),!1;if(this.checkWorldBounds)if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1}return!0},i.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,outOfCameraBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},i.Component.LifeSpan=function(){},i.Component.LifeSpan.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):!(this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0))||(this.kill(),!1)},i.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(t){return void 0===t&&(t=100),this.alive=!0,this.exists=!0,this.visible=!0,"function"==typeof this.setHealth&&this.setHealth(t),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},i.Component.LoadTexture=function(){},i.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(t,e,s){t===i.PENDING_ATLAS?(t=e,e=0):e=e||0,(s||void 0===s)&&this.animations&&this.animations.stop(),this.key=t,this.customRender=!1;var n=this.game.cache,r=!0,o=!this.texture.baseTexture.scaleMode;if(i.RenderTexture&&t instanceof i.RenderTexture)this.key=t.key,this.setTexture(t);else if(i.BitmapData&&t instanceof i.BitmapData)this.customRender=!0,this.setTexture(t.texture),r=n.hasFrameData(t.key,i.Cache.BITMAPDATA)?!this.animations.loadFrameData(n.getFrameData(t.key,i.Cache.BITMAPDATA),e):!this.animations.loadFrameData(t.frameData,0);else if(i.Video&&t instanceof i.Video){this.customRender=!0;var a=t.texture.valid;this.setTexture(t.texture),this.setFrame(t.texture.frame.clone()),t.onChangeSource.add(this.resizeFrame,this),this.texture.valid=a}else if(i.Tilemap&&t instanceof i.TilemapLayer)this.setTexture(PIXI.Texture.fromCanvas(t.canvas));else if(t instanceof PIXI.Texture)this.setTexture(t);else{var h=n.getImage(t,!0);this.key=h.key,this.setTexture(new PIXI.Texture(h.base)),this.texture.baseTexture.skipRender="__default"===t,r=!this.animations.loadFrameData(h.frameData,e)}r&&(this._frame=i.Rectangle.clone(this.texture.frame)),o||(this.texture.baseTexture.scaleMode=1)},setFrame:function(t){this._frame=t,this.texture.frame.x=t.x,this.texture.frame.y=t.y,this.texture.frame.width=t.width,this.texture.frame.height=t.height,this.texture.crop.x=t.x,this.texture.crop.y=t.y,this.texture.crop.width=t.width,this.texture.crop.height=t.height,t.trimmed?(this.texture.trim?(this.texture.trim.x=t.spriteSourceSizeX,this.texture.trim.y=t.spriteSourceSizeY,this.texture.trim.width=t.sourceSizeW,this.texture.trim.height=t.sourceSizeH):this.texture.trim={x:t.spriteSourceSizeX,y:t.spriteSourceSizeY,width:t.sourceSizeW,height:t.sourceSizeH},this.texture.width=t.sourceSizeW,this.texture.height=t.sourceSizeH,this.texture.frame.width=t.sourceSizeW,this.texture.frame.height=t.sourceSizeH):!t.trimmed&&this.texture.trim&&(this.texture.trim=null),t.rotated&&(this.texture.rotated=!0),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(t,e,i){this.texture.frame.resize(e,i),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(t){this.animations.frame=t}},frameName:{get:function(){return this.animations.frameName},set:function(t){this.animations.frameName=t}}},i.Component.Overlap=function(){},i.Component.Overlap.prototype={overlap:function(t){return i.Rectangle.intersects(this.getBounds(),t.getBounds())}},i.Component.PhysicsBody=function(){},i.Component.PhysicsBody.preUpdate=function(){return this.pendingDestroy?(this.destroy(),!1):this.fresh&&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.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,this.preUpdateChildren(),!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!(!this._exists||!this.parent.exists)||(this.renderOrderID=-1,!1))},i.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},i.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(t){this.position.x=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},i.Component.Reset=function(){},i.Component.Reset.prototype.reset=function(t,e,i){return void 0===i&&(i=1),this.world.set(t,e),this.position.set(t,e),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=i),this.components.PhysicsBody&&this.body&&this.body.reset(t,e,!1,!1),this},i.Component.ScaleMinMax=function(){},i.Component.ScaleMinMax.prototype={transformCallback:null,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(t){this.scaleMin&&(t.athis.scaleMax.x&&(t.a=this.scaleMax.x),t.d>this.scaleMax.y&&(t.d=this.scaleMax.y))},setScaleMinMax:function(t,e,s,n){void 0===e?e=s=n=t:void 0===s&&(s=n=e,e=t),null===t?this.scaleMin=null:this.scaleMin?this.scaleMin.set(t,e):this.scaleMin=new i.Point(t,e),null===s?this.scaleMax=null:this.scaleMax?this.scaleMax.set(s,n):this.scaleMax=new i.Point(s,n),null===this.scaleMin?this.transformCallback=null:(this.transformCallback=this.checkTransform,this.transformCallbackContext=this)}},i.Component.Smoothed=function(){},i.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(t){t?this.texture&&(this.texture.baseTexture.scaleMode=0,this.texture.baseTexture.dirty()):this.texture&&(this.texture.baseTexture.scaleMode=1,this.texture.baseTexture.dirty())}}},i.GameObjectFactory=function(t){this.game=t,this.world=this.game.world},i.GameObjectFactory.prototype={existing:function(t){return this.world.add(t)},weapon:function(t,e,s,n,r){var o=this.game.plugins.add(i.Weapon);return r&&(o.bulletClass=r),o.createBullets(t,e,s,n),o},image:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Image(this.game,t,e,s,n))},sprite:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Sprite(this.game,t,e,s,n))},creature:function(t,e,s,n,r){void 0===r&&(r=this.world);var o=new i.Creature(this.game,t,e,s,n);return r.add(o),o},tween:function(t){return this.game.tweens.create(t)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},physicsGroup:function(t,e,s,n){return new i.Group(this.game,e,s,n,!0,t)},spriteBatch:function(t,e,s){return void 0===t&&(t=null),void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},tileSprite:function(t,e,s,n,r,o,a){return void 0===a&&(a=this.world),a.add(new i.TileSprite(this.game,t,e,s,n,r,o))},rope:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.Rope(this.game,t,e,s,n,r))},text:function(t,e,s,n,r){return void 0===r&&(r=this.world),r.add(new i.Text(this.game,t,e,s,n))},button:function(t,e,s,n,r,o,a,h,l,c){return void 0===c&&(c=this.world),c.add(new i.Button(this.game,t,e,s,n,r,o,a,h,l))},graphics:function(t,e,s){return void 0===s&&(s=this.world),s.add(new i.Graphics(this.game,t,e))},emitter:function(t,e,s){return this.game.particles.add(new i.Particles.Arcade.Emitter(this.game,t,e,s))},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return void 0===o&&(o=this.world),o.add(new i.BitmapText(this.game,t,e,s,n,r))},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},video:function(t,e){return new i.Video(this.game,t,e)},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t},plugin:function(t){return this.game.plugins.add(t)}},i.GameObjectFactory.prototype.constructor=i.GameObjectFactory,i.GameObjectCreator=function(t){this.game=t,this.world=this.game.world},i.GameObjectCreator.prototype={image:function(t,e,s,n){return new i.Image(this.game,t,e,s,n)},sprite:function(t,e,s,n){return new i.Sprite(this.game,t,e,s,n)},tween:function(t){return new i.Tween(t,this.game,this.game.tweens)},group:function(t,e,s,n,r){return new i.Group(this.game,t,e,s,n,r)},spriteBatch:function(t,e,s){return void 0===e&&(e="group"),void 0===s&&(s=!1),new i.SpriteBatch(this.game,t,e,s)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},tileSprite:function(t,e,s,n,r,o){return new i.TileSprite(this.game,t,e,s,n,r,o)},rope:function(t,e,s,n,r){return new i.Rope(this.game,t,e,s,n,r)},text:function(t,e,s,n){return new i.Text(this.game,t,e,s,n)},button:function(t,e,s,n,r,o,a,h,l){return new i.Button(this.game,t,e,s,n,r,o,a,h,l)},graphics:function(t,e){return new i.Graphics(this.game,t,e)},emitter:function(t,e,s){return new i.Particles.Arcade.Emitter(this.game,t,e,s)},retroFont:function(t,e,s,n,r,o,a,h,l){return new i.RetroFont(this.game,t,e,s,n,r,o,a,h,l)},bitmapText:function(t,e,s,n,r,o){return new i.BitmapText(this.game,t,e,s,n,r,o)},tilemap:function(t,e,s,n,r){return new i.Tilemap(this.game,t,e,s,n,r)},renderTexture:function(t,e,s,n){void 0!==s&&""!==s||(s=this.game.rnd.uuid()),void 0===n&&(n=!1);var r=new i.RenderTexture(this.game,t,e,s);return n&&this.game.cache.addRenderTexture(s,r),r},bitmapData:function(t,e,s,n){void 0===n&&(n=!1),void 0!==s&&""!==s||(s=this.game.rnd.uuid());var r=new i.BitmapData(this.game,s,t,e);return n&&this.game.cache.addBitmapData(s,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1);return(t=new i.Filter[t](this.game)).init.apply(t,e),t}},i.GameObjectCreator.prototype.constructor=i.GameObjectCreator,i.Sprite=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.SPRITE,this.physicsType=i.SPRITE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Sprite.prototype=Object.create(PIXI.Sprite.prototype),i.Sprite.prototype.constructor=i.Sprite,i.Component.Core.install.call(i.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Sprite.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Sprite.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Sprite.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Sprite.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Sprite.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Image=function(t,e,s,n,r){e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.IMAGE,PIXI.Sprite.call(this,i.Cache.DEFAULT),i.Component.Core.init.call(this,t,e,s,n,r)},i.Image.prototype=Object.create(PIXI.Sprite.prototype),i.Image.prototype.constructor=i.Image,i.Component.Core.install.call(i.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","ScaleMinMax","Smoothed"]),i.Image.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Image.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Image.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Image.prototype.preUpdate=function(){return!(!this.preUpdateInWorld()||!this.preUpdateLifeSpan())&&this.preUpdateCore()},i.Button=function(t,e,s,n,r,o,a,h,l,c){e=e||0,s=s||0,n=n||null,r=r||null,o=o||this,i.Image.call(this,t,e,s,n,h),this.type=i.BUTTON,this.physicsType=i.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new i.Signal,this.onInputOut=new i.Signal,this.onInputDown=new i.Signal,this.onInputUp=new i.Signal,this.onOverMouseOnly=!0,this.justReleasedPreventsOver=i.PointerMode.CONTACT,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(a,h,l,c),null!==r&&this.onInputUp.add(r,o),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this)},i.Button.prototype=Object.create(i.Image.prototype),i.Button.prototype.constructor=i.Button;return i.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},i.Button.prototype.setStateFrame=function(t,e,i){var s="_on"+t+"Frame";null!==e?(this[s]=e,i&&this.changeStateFrame(t)):this[s]=null},i.Button.prototype.changeStateFrame=function(t){if(this.freezeFrames)return!1;var e=this["_on"+t+"Frame"];return"string"==typeof e?(this.frameName=e,!0):"number"==typeof e&&(this.frame=e,!0)},i.Button.prototype.setFrames=function(t,e,i,s){this.setStateFrame("Over",t,this.input.pointerOver()),this.setStateFrame("Out",e,!this.input.pointerOver()),this.setStateFrame("Down",i,this.input.pointerDown()),this.setStateFrame("Up",s,this.input.pointerUp())},i.Button.prototype.setStateSound=function(t,e,s){var n="on"+t+"Sound",r="on"+t+"SoundMarker";e instanceof i.Sound||e instanceof i.AudioSprite?(this[n]=e,this[r]="string"==typeof s?s:""):(this[n]=null,this[r]="")},i.Button.prototype.playStateSound=function(t){var e=this["on"+t+"Sound"];if(e){var i=this["on"+t+"SoundMarker"];return e.play(i),!0}return!1},i.Button.prototype.setSounds=function(t,e,i,s,n,r,o,a){this.setStateSound("Over",t,e),this.setStateSound("Out",n,r),this.setStateSound("Down",i,s),this.setStateSound("Up",o,a)},i.Button.prototype.setOverSound=function(t,e){this.setStateSound("Over",t,e)},i.Button.prototype.setOutSound=function(t,e){this.setStateSound("Out",t,e)},i.Button.prototype.setDownSound=function(t,e){this.setStateSound("Down",t,e)},i.Button.prototype.setUpSound=function(t,e){this.setStateSound("Up",t,e)},i.Button.prototype.onInputOverHandler=function(t,e){e.justReleased()&&(this.justReleasedPreventsOver&e.pointerMode)===e.pointerMode||(this.changeStateFrame("Over"),this.onOverMouseOnly&&!e.isMouse||(this.playStateSound("Over"),this.onInputOver&&this.onInputOver.dispatch(this,e)))},i.Button.prototype.onInputOutHandler=function(t,e){this.changeStateFrame("Out"),this.playStateSound("Out"),this.onInputOut&&this.onInputOut.dispatch(this,e)},i.Button.prototype.onInputDownHandler=function(t,e){this.changeStateFrame("Down"),this.playStateSound("Down"),this.onInputDown&&this.onInputDown.dispatch(this,e)},i.Button.prototype.onInputUpHandler=function(t,e,i){this.playStateSound("Up"),this.onInputUp&&this.onInputUp.dispatch(this,e,i),this.freezeFrames||(!0===this.forceOut||(this.forceOut&e.pointerMode)===e.pointerMode?this.changeStateFrame("Out"):this.changeStateFrame("Up")||(i?this.changeStateFrame("Over"):this.changeStateFrame("Out")))},i.SpriteBatch=function(t,e,s,n){void 0!==e&&null!==e||(e=t.world),i.Group.call(this,t,e,s,n),this.type=i.SPRITEBATCH,this.fastSpriteBatch=null,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.Group.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||(this.fastSpriteBatch=new PIXI.WebGLFastSpriteBatch(t.gl),this.ready=!0),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n=0&&t<=this.width&&e>=0&&e<=this.height&&(i.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|n<<8|s:this.pixels[e*this.width+t]=s<<24|n<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,s){s||(s=i.Color.createColor());var n=~~(t+e*this.width);return n*=4,s.r=this.data[n],s.g=this.data[++n],s.b=this.data[++n],s.a=this.data[++n],s},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,s,n,r){return i.Color.unpackPixel(this.getPixel32(t,e),s,n,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=i.Color.createColor(),s=0,n=0,r=1,o=!1;1===t?(r=-1,n=this.height):3===t&&(r=-1,s=this.width);do{i.Color.unpackPixel(this.getPixel32(s,n),e),0===t||1===t?++s===this.width&&(s=0,((n+=r)>=this.height||n<=0)&&(o=!0)):2!==t&&3!==t||++n===this.height&&(n=0,((s+=r)>=this.width||s<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=s,e.y=n,e},getBounds:function(t){return void 0===t&&(t=new i.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,s,n,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),t instanceof i.RenderTexture&&(t=t.getCanvas()),this._image=t,t instanceof i.Sprite||t instanceof i.Image||t instanceof i.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof i.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==s&&null!==s||(s=0),n&&(this._size.x=n),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=s),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+s,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var n=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===n.a||0===n.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof i.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=n.tx,o=n.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),s&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(n.a,n.b,n.c,n.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,s){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,s),t.type===i.GROUP&&t.exists)this.drawGroup(t,e,s);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var n=0;ne.width&&(n=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,s),this._circle=new i.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,n,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),i.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this},copyBitmapData:function(t,e,i){t.update();for(var s,n=0;n80*s){h=c=t[0],l=u=t[1];for(var g=s;gc&&(c=d),p>u&&(u=p);f=Math.max(c-h,u-l)}return i.EarCut.earcutLinked(o,a,s,h,l,f),a},i.EarCut.linkedList=function(t,e,s,n,r){var o,a,h,l=0;for(o=e,a=s-n;o0)for(o=e;o=e;o-=n)h=i.EarCut.insertNode(o,t[o],t[o+1],h);return h},i.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var s,n=t;do{if(s=!1,n.steiner||!i.EarCut.equals(n,n.next)&&0!==i.EarCut.area(n.prev,n,n.next))n=n.next;else{if(i.EarCut.removeNode(n),(n=e=n.prev)===n.next)return null;s=!0}}while(s||n!==e);return e},i.EarCut.earcutLinked=function(t,e,s,n,r,o,a){if(t){!a&&o&&i.EarCut.indexCurve(t,n,r,o);for(var h,l,c=t;t.prev!==t.next;)if(h=t.prev,l=t.next,o?i.EarCut.isEarHashed(t,n,r,o):i.EarCut.isEar(t))e.push(h.i/s),e.push(t.i/s),e.push(l.i/s),i.EarCut.removeNode(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?(t=i.EarCut.cureLocalIntersections(t,e,s),i.EarCut.earcutLinked(t,e,s,n,r,o,2)):2===a&&i.EarCut.splitEarcut(t,e,s,n,r,o):i.EarCut.earcutLinked(i.EarCut.filterPoints(t),e,s,n,r,o,1);break}}},i.EarCut.isEar=function(t){var e=t.prev,s=t,n=t.next;if(i.EarCut.area(e,s,n)>=0)return!1;for(var r=t.next.next;r!==t.prev;){if(i.EarCut.pointInTriangle(e.x,e.y,s.x,s.y,n.x,n.y,r.x,r.y)&&i.EarCut.area(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},i.EarCut.isEarHashed=function(t,e,s,n){var r=t.prev,o=t,a=t.next;if(i.EarCut.area(r,o,a)>=0)return!1;for(var h=r.xo.x?r.x>a.x?r.x:a.x:o.x>a.x?o.x:a.x,u=r.y>o.y?r.y>a.y?r.y:a.y:o.y>a.y?o.y:a.y,d=i.EarCut.zOrder(h,l,e,s,n),p=i.EarCut.zOrder(c,u,e,s,n),f=t.nextZ;f&&f.z<=p;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=d;){if(f!==t.prev&&f!==t.next&&i.EarCut.pointInTriangle(r.x,r.y,o.x,o.y,a.x,a.y,f.x,f.y)&&i.EarCut.area(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0},i.EarCut.cureLocalIntersections=function(t,e,s){var n=t;do{var r=n.prev,o=n.next.next;i.EarCut.intersects(r,n,n.next,o)&&i.EarCut.locallyInside(r,o)&&i.EarCut.locallyInside(o,r)&&(e.push(r.i/s),e.push(n.i/s),e.push(o.i/s),i.EarCut.removeNode(n),i.EarCut.removeNode(n.next),n=t=o),n=n.next}while(n!==t);return n},i.EarCut.splitEarcut=function(t,e,s,n,r,o){var a=t;do{for(var h=a.next.next;h!==a.prev;){if(a.i!==h.i&&i.EarCut.isValidDiagonal(a,h)){var l=i.EarCut.splitPolygon(a,h);return a=i.EarCut.filterPoints(a,a.next),l=i.EarCut.filterPoints(l,l.next),i.EarCut.earcutLinked(a,e,s,n,r,o),void i.EarCut.earcutLinked(l,e,s,n,r,o)}h=h.next}a=a.next}while(a!==t)},i.EarCut.eliminateHoles=function(t,e,s,n){var r,o,a,h,l,c=[];for(r=0,o=e.length;r=n.next.y){var h=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);h<=r&&h>a&&(a=h,s=n.x=n.x&&n.x>=s.x&&i.EarCut.pointInTriangle(os.x)&&i.EarCut.locallyInside(n,t)&&(s=n,u=l),n=n.next;return s},i.EarCut.indexCurve=function(t,e,s,n){var r=t;do{null===r.z&&(r.z=i.EarCut.zOrder(r.x,r.y,e,s,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,i.EarCut.sortLinked(r)},i.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},i.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},i.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},i.EarCut.isValidDiagonal=function(t,e){return i.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!i.EarCut.intersectsPolygon(t,e)&&i.EarCut.locallyInside(t,e)&&i.EarCut.locallyInside(e,t)&&i.EarCut.middleInside(t,e)},i.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},i.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},i.EarCut.intersects=function(t,e,s,n){return i.EarCut.area(t,e,s)>0!=i.EarCut.area(t,e,n)>0&&i.EarCut.area(s,n,t)>0!=i.EarCut.area(s,n,e)>0},i.EarCut.intersectsPolygon=function(t,e){var s=t;do{if(s.i!==t.i&&s.next.i!==t.i&&s.i!==e.i&&s.next.i!==e.i&&i.EarCut.intersects(s,s.next,t,e))return!0;s=s.next}while(s!==t);return!1},i.EarCut.locallyInside=function(t,e){return i.EarCut.area(t.prev,t,t.next)<0?i.EarCut.area(t,e,t.next)>=0&&i.EarCut.area(t,t.prev,e)>=0:i.EarCut.area(t,e,t.prev)<0||i.EarCut.area(t,t.next,e)<0},i.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},i.EarCut.splitPolygon=function(t,e){var s=new i.EarCut.Node(t.i,t.x,t.y),n=new i.EarCut.Node(e.i,e.x,e.y),r=t.next,o=e.prev;return t.next=e,e.prev=t,s.next=r,r.prev=s,n.next=s,s.prev=n,o.next=n,n.prev=o,n},i.EarCut.insertNode=function(t,e,s,n){var r=new i.EarCut.Node(t,e,s);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r},i.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},i.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var s,n=e.gl,r=e.projection,o=e.offset,a=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,n);var h=t._webGL[n.id];if(h)for(var l=0;l=PIXI.WebGLGraphics.stencilBufferLimit&&(a.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit?(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildPoly(a,o)||(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,1),PIXI.WebGLGraphics.buildComplexPoly(a,o))),a.lineWidth>0&&(o=PIXI.WebGLGraphics.switchMode(s,0),PIXI.WebGLGraphics.buildLine(a,o))):(o=PIXI.WebGLGraphics.switchMode(s,0),a.type===i.RECTANGLE?PIXI.WebGLGraphics.buildRectangle(a,o):a.type===i.CIRCLE||a.type===i.ELLIPSE?PIXI.WebGLGraphics.buildCircle(a,o):a.type===i.ROUNDEDRECTANGLE&&PIXI.WebGLGraphics.buildRoundedRectangle(a,o)),s.lastIndex++}for(n=0;n19600?(_=y-x,w=v-b,_/=R=Math.sqrt(_*_+w*w),w/=R,_*=F,w*=F,L.push(p-_,f-w),L.push(G,N,X,U),L.push(p+_,f+w),L.push(G,N,X,U),L.push(p-_,f-w),L.push(G,N,X,U),O++):(L.push(l,c),L.push(G,N,X,U),L.push(p-(l-p),f-(c-f)),L.push(G,N,X,U));for(u=n[2*(I-2)],d=n[2*(I-2)+1],p=n[2*(I-1)],y=-(d-(f=n[2*(I-1)+1])),v=u-p,y/=R=Math.sqrt(y*y+v*v),v/=R,y*=F,v*=F,L.push(p-y,f-v),L.push(G,N,X,U),L.push(p+y,f+v),L.push(G,N,X,U),B.push(k),s=0;sh?r:h,l=oc?o:c;s.push(a,l,h,l,h,c,a,c);var d=s.length/2;for(u=0;uS?S:C,e.beginPath(),e.moveTo(_,w+C),e.lineTo(_,w+P-C),e.quadraticCurveTo(_,w+P,_+C,w+P),e.lineTo(_+T-C,w+P),e.quadraticCurveTo(_+T,w+P,_+T,w+P-C),e.lineTo(_+T,w+C),e.quadraticCurveTo(_+T,w,_+T-C,w),e.lineTo(_+C,w),e.quadraticCurveTo(_,w,_,w+C),e.closePath(),(r.fillColor||0===r.fillColor)&&(e.globalAlpha=r.fillAlpha*s,e.fillStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.fill()),r.lineWidth&&(e.globalAlpha=r.lineAlpha*s,e.strokeStyle="#"+("00000"+(0|h).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var s=t.graphicsData.length;if(0!==s){e.beginPath();for(var n=0;nP?P:T,e.moveTo(x,b+T),e.lineTo(x,b+w-T),e.quadraticCurveTo(x,b+w,x+T,b+w),e.lineTo(x+_-T,b+w),e.quadraticCurveTo(x+_,b+w,x+_,b+w-T),e.lineTo(x+_,b+T),e.quadraticCurveTo(x+_,b,x+_-T,b),e.lineTo(x+T,b),e.quadraticCurveTo(x,b,x,b+T),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},i.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},i.GraphicsData.prototype.constructor=i.GraphicsData,i.GraphicsData.prototype.clone=function(){return new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},i.Graphics=function(t,e,s){void 0===e&&(e=0),void 0===s&&(s=0),this.type=i.GRAPHICS,this.physicsType=i.SPRITE,this.anchor=new i.Point,PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new i.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1,i.Component.Core.init.call(this,t,e,s,"",null)},i.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Graphics.prototype.constructor=i.Graphics,i.Component.Core.install.call(i.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),i.Graphics.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Graphics.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Graphics.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Graphics.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Graphics.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Graphics.prototype.postUpdate=function(){i.Component.PhysicsBody.postUpdate.call(this),i.Component.FixedToCamera.postUpdate.call(this),this._boundsDirty&&(this.updateLocalBounds(),this._boundsDirty=!1);for(var t=0;t0&&this.drawPolygon(s)}else this.drawPolygon(s)},i.Graphics.prototype.drawTriangles=function(t,e,s){void 0===s&&(s=!1);var n,r=new i.Point,o=new i.Point,a=new i.Point,h=[];if(e)if(t[0]instanceof i.Point)for(n=0;nc*a)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var x=d+s+p*(v+y*v),b=Math.cos(x),_=-Math.sin(x);u.push((f*b+g*_)*i+t,(f*-_+g*b)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},i.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},i.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},i.Graphics.prototype.drawRect=function(t,e,s,n){return this.drawShape(new i.Rectangle(t,e,s,n)),this},i.Graphics.prototype.drawRoundedRect=function(t,e,s,n,r){return this.drawShape(new i.RoundedRectangle(t,e,s,n,r)),this},i.Graphics.prototype.drawCircle=function(t,e,s){return this.drawShape(new i.Circle(t,e,s)),this},i.Graphics.prototype.drawEllipse=function(t,e,s,n){return this.drawShape(new i.Ellipse(t,e,s,n)),this},i.Graphics.prototype.drawPolygon=function(t){t instanceof i.Polygon&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var s=0;sw?m:w,w=v>w?v:w,w=b>w?b:w,T=y>T?y:T,T=x>T?x:T,T=_>T?_:T,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=C,this._bounds.height=T-C,this._currentBounds=this._bounds,this._currentBounds},i.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;ee?a+l:e,s=hn?h+c:n;else if(p===i.CIRCLE)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else if(p===i.ELLIPSE)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-le?a+l:e,s=h-cn?h+c:n;else{o=r.points;for(var g=0;ge?a+f:e,s=h-fn?h+f:n}}else t=0,e=0,s=0,n=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=s-m,this._localBounds.height=n-s+2*m},i.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},i.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},i.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},i.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof i.Polygon&&(t=t.clone()).flatten();var e=new i.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===i.POLYGON&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(i.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),i.RenderTexture=function(t,e,s,n,r,o,a,h){if(void 0===e&&(e=100),void 0===s&&(s=100),void 0===n&&(n=""),void 0===r&&(r=i.scaleModes.DEFAULT),void 0===o&&(o=1),void 0===a&&(a=PIXI.defaultRenderer),void 0===h&&(h=0),this.game=t,this.key=n,this.type=i.RENDERTEXTURE,this._tempMatrix=new i.Matrix,this.width=e,this.height=s,this.resolution=o,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=this.frame.clone(),this.baseTexture=new PIXI.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=r,this.baseTexture.hasLoaded=!0,PIXI.Texture.call(this,this.baseTexture,this.frame.clone()),this.renderer=a,this.renderer.type===i.WEBGL){var l=this.renderer.gl;this.baseTexture.textureIndex=h,this.baseTexture._dirty[l.id]=!1,this.textureBuffer=new PIXI.FilterTexture(l,this.width,this.height,this.baseTexture.scaleMode,h),this.baseTexture._glTextures[l.id]=this.textureBuffer.texture,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.textureBuffer=new PIXI.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new i.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(PIXI.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.renderXY=function(t,e,s,n){t.updateTransform(),this._tempMatrix.copyFrom(t.worldTransform),this._tempMatrix.tx=e,this._tempMatrix.ty=s,this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.renderRawXY=function(t,e,s,n){this._tempMatrix.identity().translate(e,s),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,n):this._renderCanvas(t,this._tempMatrix,n)},i.RenderTexture.prototype.render=function(t,e,s){void 0===e||null===e?this._tempMatrix.copyFrom(t.worldTransform):this._tempMatrix.copyFrom(e),this.renderer.type===i.WEBGL?this._renderWebGL(t,this._tempMatrix,s):this._renderCanvas(t,this._tempMatrix,s)},i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype._renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n-1&&this.characterLimitSize0&&this.style.maxLines0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(e[a]):l+=this.context.measureText(e[a]).width,this.style.wordWrap&&(l-=this.context.measureText(" ").width)}else{var h=e[a].split(/(?:\t)/),l=this.padding.x+this.style.strokeThickness;if(Array.isArray(i))for(var c=0,u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.measureLine(h[u]):Math.ceil(this.context.measureText(h[u]).width),u>0&&(c+=i[u-1]),l=c+d}else for(u=0;u0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?l+=this.measureLine(h[u]):l+=Math.ceil(this.context.measureText(h[u]).width),l+=this.game.math.snapToCeil(l,i)-l}s[a]=Math.ceil(l),n=Math.max(n,s[a])}this.canvas.width=n*this._res;var p=r.fontSize+this.style.strokeThickness+this.padding.y,f=p*o,g=this._lineSpacing;g<0&&Math.abs(g)>p&&(g=-p),0!==g&&(f+=g>0?g*e.length:g*(e.length-1)),this.canvas.height=f*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var m,y;for(this._charCount=0,a=0;a0&&(y+=g*a),"right"===this.style.align?m+=n-s[a]:"center"===this.style.align&&(m+=(n-s[a])/2),this.autoRound&&(m=Math.round(m),y=Math.round(y)),this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.updateLine(e[a],m,y):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===i?this.context.strokeText(e[a],m,y):this.renderTabLine(e[a],m,y,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===i?this.context.fillText(e[a],m,y):this.renderTabLine(e[a],m,y,!0)));this.updateTexture(),this.dirty=!1},i.Text.prototype.renderTabLine=function(t,e,i,s){var n=t.split(/(?:\t)/),r=this.style.tabs,o=0;if(Array.isArray(r))for(var a=0,h=0;h0&&(a+=r[h-1]),o=e+a,s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i);else for(h=0;h0||this.fontStyles.length>0){var n=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(n.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(n.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(n)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill)),e+=this.context.measureText(s).width,this._charCount++}return Math.ceil(e)},i.Text.prototype.updateLine=function(t,e,i){for(var s=0;s0||this.fontStyles.length>0){var r=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(r.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(r.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(r)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(n,e,i)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(n,e,i)),e+=this.context.measureText(n).width,this._charCount++}},i.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},i.Text.prototype.clearFontValues=function(){return this.fontStyles=[],this.fontWeights=[],this.dirty=!0,this},i.Text.prototype.addColor=function(t,e){return this.colors[e]=t,this.dirty=!0,this},i.Text.prototype.addStrokeColor=function(t,e){return this.strokeColors[e]=t,this.dirty=!0,this},i.Text.prototype.addFontStyle=function(t,e){return this.fontStyles[e]=t,this.dirty=!0,this},i.Text.prototype.addFontWeight=function(t,e){return this.fontWeights[e]=t,this.dirty=!0,this},i.Text.prototype.precalculateWordWrap=function(t){return this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font,this.runWordWrap(t).split(/(?:\r\n|\r|\n)/)},i.Text.prototype.runWordWrap=function(t){return this.useAdvancedWrap?this.advancedWordWrap(t):this.basicWordWrap(t)},i.Text.prototype.advancedWordWrap=function(t){for(var e=this.context,i=this.style.wordWrapWidth,s="",n=t.replace(/ +/gi," ").split(/\r?\n/gi),r=n.length,o=0;ol){if(0===u){for(var g=p;g.length&&(g=g.slice(0,-1),!((f=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var m=d.substr(g.length);c[u]=m,h+=g}var y=c[u].length?u:u+1,v=c.slice(y).join(" ").replace(/[ \n]*$/gi,"");n[o+1]=v+" "+(n[o+1]||""),r=n.length;break}h+=p,l-=f}s+=h.replace(/[ \n]*$/gi,"")+"\n"}}return s=s.replace(/[\s|\n]*$/gi,"")},i.Text.prototype.basicWordWrap=function(t){for(var e="",i=t.split("\n"),s=0;sn?(o>0&&(e+="\n"),e+=r[o]+" ",n=this.style.wordWrapWidth-a):(n-=h,e+=r[o]+" ")}ss&&(this.style.wordWrapWidth=s)),this.updateTexture(),this},i.Text.prototype.updateTexture=function(){var t=this.texture.baseTexture,e=this.texture.crop,i=this.texture.frame,s=this.canvas.width,n=this.canvas.height;if(t.width=s,t.height=n,e.width=s,e.height=n,i.width=s,i.height=n,this.texture.width=s,this.texture.height=n,this._width=s,this._height=n,this.textBounds){var r=this.textBounds.x,o=this.textBounds.y;"right"===this.style.boundsAlignH?r+=this.textBounds.width-this.canvas.width/this.resolution:"center"===this.style.boundsAlignH&&(r+=this.textBounds.halfWidth-this.canvas.width/this.resolution/2),"bottom"===this.style.boundsAlignV?o+=this.textBounds.height-this.canvas.height/this.resolution:"middle"===this.style.boundsAlignV&&(o+=this.textBounds.halfHeight-this.canvas.height/this.resolution/2),this.pivot.x=-r,this.pivot.y=-o}this.renderable=0!==s&&0!==n,this.texture.requiresReTint=!0,this.texture.baseTexture.dirty()},i.Text.prototype._renderWebGL=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.Text.prototype._renderCanvas=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.Text.prototype.determineFontProperties=function(t){var e=i.Text.fontPropertiesCache[t];if(!e){e={};var s=i.Text.fontPropertiesCanvas,n=i.Text.fontPropertiesContext;n.font=t;var r=Math.ceil(n.measureText("|MÉq").width),o=Math.ceil(n.measureText("|MÉq").width),a=2*o;if(o=1.4*o|0,s.width=r,s.height=a,n.fillStyle="#f00",n.fillRect(0,0,r,a),n.font=t,n.textBaseline="alphabetic",n.fillStyle="#000",n.fillText("|MÉq",0,o),!n.getImageData(0,0,r,a))return e.ascent=o,e.descent=o+6,e.fontSize=e.ascent+e.descent,i.Text.fontPropertiesCache[t]=e,e;var h,l,c=n.getImageData(0,0,r,a).data,u=c.length,d=4*r,p=0,f=!1;for(h=0;ho;h--){for(l=0;l0?this._maxWidth:null,l=[],c=0;c=h&&r>-1)return{width:o||n,text:i.substr(0,c-(c-r)),end:!1,chars:l};n+=(p.xAdvance+g)*e,l.push(s+(p.xOffset+g)*e),s+=(p.xAdvance+g)*e,a=d}return{width:n,text:i,end:u,chars:l}},i.BitmapText.prototype.cleanText=function(t,e){void 0===e&&(e="");var i=this._data.font;if(!i)return"";for(var s=/\r\n|\n\r|\n|\r/g,n=t.replace(s,"\n").split("\n"),r=0;rthis.textWidth&&(this.textWidth=c.width),n+=t.lineHeight*i,e=e.substr(c.text.length+1)}while(!1===c.end);this.textHeight=n;for(var r=0,o=0,a=this.textWidth*this.anchor.x,h=this.textHeight*this.anchor.y,l=0;l0&&(this._fontSize=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.updateText())}}),Object.defineProperty(i.BitmapText.prototype,"smoothed",{get:function(){return!this._data.base.scaleMode},set:function(t){this._data.base.scaleMode=t?0:1,this._data.base.dirty()}}),i.RetroFont=function(t,e,s,n,r,o,a,h,l,c){if(!t.cache.checkImageKey(e))return!1;void 0!==o&&null!==o||(o=t.cache.getImage(e).width/s),this.characterWidth=s,this.characterHeight=n,this.characterSpacingX=a||0,this.characterSpacingY=h||0,this.characterPerRow=o,this.offsetX=l||0,this.offsetY=c||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=t.cache.getImage(e),this._text="",this.grabData=[],this.frameData=new i.FrameData;for(var u=this.offsetX,d=this.offsetY,p=0,f=0;f?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",i.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",i.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",i.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",i.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",i.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",i.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",i.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",i.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",i.RetroFont.prototype.setFixedWidth=function(t,e){void 0===e&&(e="left"),this.fixedWidth=t,this.align=e},i.RetroFont.prototype.setText=function(t,e,i,s,n,r){this.multiLine=e||!1,this.customSpacingX=i||0,this.customSpacingY=s||0,this.align=n||"left",this.autoUpperCase=!r,t.length>0&&(this.text=t)},i.RetroFont.prototype.buildRetroFontText=function(){var t=0,e=0;if(this.clear(),this.multiLine){var s=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),s.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var n=0;n0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),t=0,this.align===i.RetroFont.ALIGN_RIGHT?t=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===i.RetroFont.ALIGN_CENTER&&(t=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(this._text,t,0,this.customSpacingX);this.requiresReTint=!0},i.RetroFont.prototype.pasteLine=function(t,e,i,s){for(var n=0;n=0&&(this.stamp.frame=this.grabData[t.charCodeAt(n)],this.renderXY(this.stamp,e,i,!1),(e+=this.characterWidth+s)>this.width))break},i.RetroFont.prototype.getLongestLine=function(){var t=0;if(this._text.length>0)for(var e=this._text.split("\n"),i=0;it&&(t=e[i].length);return t},i.RetroFont.prototype.removeUnsupportedCharacters=function(t){for(var e="",i=0;i=0||!t&&"\n"===s)&&(e=e.concat(s))}return e},i.RetroFont.prototype.updateOffset=function(t,e){if(this.offsetX!==t||this.offsetY!==e){for(var i=t-this.offsetX,s=e-this.offsetY,n=this.game.cache.getFrameData(this.stamp.key).getFrames(),r=n.length;r--;)n[r].x+=i,n[r].y+=s;this.buildRetroFontText()}},Object.defineProperty(i.RetroFont.prototype,"text",{get:function(){return this._text},set:function(t){var e;(e=this.autoUpperCase?t.toUpperCase():t)!==this._text&&(this._text=e,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(i.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(t){this.stamp.smoothed=t,this.buildRetroFontText()}}),i.Rope=function(t,e,s,n,r,o){this.points=o||[],this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,e=e||0,s=s||0,n=n||null,r=r||null,this.type=i.ROPE,PIXI.DisplayObjectContainer.call(this),this.texture=i.Cache.DEFAULT,this.uvs=new Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new Float32Array([0,0,100,0,100,100,0,100]),this.colors=new Float32Array([1,1,1,1]),this.indices=new Uint16Array([0,1,2,3]),o&&(this.vertices=new Float32Array(4*o.length),this.uvs=new Float32Array(4*o.length),this.colors=new Float32Array(2*o.length),this.indices=new Uint16Array(2*o.length)),this.dirty=!0,this.canvasPadding=0,this.drawMode=i.Rope.TRIANGLE_STRIP,i.Component.Core.init.call(this,t,e,s,n,r),this.refresh()},i.Rope.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),i.Rope.prototype.constructor=i.Rope,i.Component.Core.install.call(i.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),i.Rope.prototype.preUpdatePhysics=i.Component.PhysicsBody.preUpdate,i.Rope.prototype.preUpdateLifeSpan=i.Component.LifeSpan.preUpdate,i.Rope.prototype.preUpdateInWorld=i.Component.InWorld.preUpdate,i.Rope.prototype.preUpdateCore=i.Component.Core.preUpdate,i.Rope.TRIANGLE_STRIP=0,i.Rope.TRIANGLES=1,i.Rope.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},i.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},i.Rope.prototype.reset=function(t,e){return i.Component.Reset.prototype.reset.call(this,t,e),this},i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=this.indices,s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o=t.length,a=1;a1&&1,o=Math.sqrt(s.x*s.x+s.y*s.y),a=this.texture.height/2,s.x/=o,s.y/=o,s.x*=a,s.y*=a,h[r]=n.x+s.x,h[r+1]=n.y+s.y,h[r+2]=n.x-s.x,h[r+3]=n.y-s.y,i=n;PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.Rope.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Rope.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Rope.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Rope.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Rope.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Rope.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Rope.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n0){var _=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,T=(l+c+u)/3,P=(d+p+f)/3,C=l-T,S=d-P,A=Math.sqrt(C*C+S*S);l=T+C/A*(A+_),d=P+S/A*(A+w),S=p-P,c=T+(C=c-T)/(A=Math.sqrt(C*C+S*S))*(A+_),p=P+S/A*(A+w),S=f-P,u=T+(C=u-T)/(A=Math.sqrt(C*C+S*S))*(A+_),f=P+S/A*(A+w)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*x+v*y+m*b-x*y-v*m-g*b,M=l*x+v*u+c*b-x*u-v*c-l*b,R=g*c+l*y+m*u-c*y-l*m-g*u,L=g*x*u+v*c*y+l*m*b-l*x*y-v*m*u-g*c*b,B=d*x+v*f+p*b-x*f-v*p-d*b,I=g*p+d*y+m*f-p*y-d*m-g*f,O=g*x*f+v*p*y+d*m*b-d*x*y-v*m*f-g*p*b;t.transform(M/E,B/E,R/E,I/E,L/E,O/E),t.drawImage(o,0,0),t.restore()},i.Rope.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;nh?m:h,l=y>l?y:l}if(c===-1/0||l===1/0)return PIXI.EmptyRectangle;var v=this._bounds;return v.x=c,v.width=h-c,v.y=u,v.height=l-u,this._currentBounds=v,v},Object.defineProperty(i.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(t){t&&"function"==typeof t?(this._hasUpdateAnimation=!0,this._updateAnimation=t):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(i.Rope.prototype,"segments",{get:function(){for(var t,e,s,n,r,o,a,h,l=[],c=0;c(_=y>(_=g>(_=p>_?p:_)?g:_)?y:_)?x:_,w=b>(w=v>(w=m>(w=f>w?f:w)?m:w)?v:w)?b:w;var C=this._bounds;return C.x=T,C.width=_-T,C.y=P,C.height=w-P,this._currentBounds=C,C},Object.defineProperty(i.TileSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TileSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var e=parseInt(RegExp.$1,10),i=parseInt(RegExp.$2,10);(10===e&&i>=11||e>10)&&(s.dolby=!0)}}catch(t){}}(),function(){var t=document.createElement("video");try{!!t.canPlayType&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(s.oggVideo=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.h264Video=!0,s.mp4Video=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(s.webmVideo=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(s.vp9Video=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.hlsVideo=!0))}catch(t){}}(),function(){var t,e=document.createElement("p"),i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var n in i)void 0!==e.style[n]&&(e.style[n]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(i[n]));document.body.removeChild(e),s.css3D=void 0!==t&&t.length>0&&"none"!==t}(),s.pixelRatio=window.devicePixelRatio||1,s.iPhone=-1!==navigator.userAgent.toLowerCase().indexOf("iphone"),s.iPhone4=2===s.pixelRatio&&s.iPhone,s.iPad=-1!==navigator.userAgent.toLowerCase().indexOf("ipad"),"undefined"!=typeof Int8Array?s.typedArray=!0:s.typedArray=!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(s.littleEndian=t(),s.LITTLE_ENDIAN=s.littleEndian),s.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==s.littleEndian&&e(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(s.vibration=!0),function(){s.canvas=!!window.CanvasRenderingContext2D||s.cocoonJS;try{s.localStorage=!!localStorage.getItem}catch(t){s.localStorage=!1}s.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),s.fileSystem=!!window.requestFileSystem,s.webGL=!!window.WebGLRenderingContext,s.worker=!!window.Worker,s.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,s.quirksMode="CSS1Compat"!==document.compatMode,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,s.getUserMedia=s.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,s.firefox&&s.firefoxVersion<21&&(s.getUserMedia=!1),!s.iOS&&(s.ie||s.firefox||s.chrome)&&(s.canvasBitBltShift=!0),(s.safari||s.mobileSafari)&&(s.canvasBitBltShift=!1)}(),function(){var t=i.CanvasPool.create(this,6,1),e=t.getContext("2d");e.fillStyle="rgba(10, 20, 30, 0.5)",e.fillRect(0,0,1,1);var n=e.getImageData(0,0,1,1);if(n){e.putImageData(n,1,0);var r=e.getImageData(1,0,1,1);s.canHandleAlpha=r.data[0]===n.data[0]&&r.data[1]===n.data[1]&&r.data[2]===n.data[2]&&r.data[3]===n.data[3]}e.globalCompositeOperation="multiply",s.canUseMultiply="multiply"===e.globalCompositeOperation,i.CanvasPool.removeByCanvas(t),PIXI.CanvasTinter.tintMethod=s.canUseMultiply?PIXI.CanvasTinter.tintWithMultiply:PIXI.CanvasTinter.tintWithPerPixel}(),function(){for(var t=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],e=document.createElement("div"),i=0;i=1)&&(s.touch=!0),(window.PointerEvent||window.MSPointerEvent||window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(s.mspointer=!0),s.cocoonJS||("onwheel"in window||s.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":s.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"))},i.Device.canPlayAudio=function(t){return!("mp3"!==t||!this.mp3)||(!("ogg"!==t||!this.ogg&&!this.opus)||(!("m4a"!==t||!this.m4a)||(!("opus"!==t||!this.opus)||(!("wav"!==t||!this.wav)||(!("webm"!==t||!this.webm)||!("mp4"!==t||!this.dolby))))))},i.Device.canPlayVideo=function(t){return!("webm"!==t||!this.webmVideo&&!this.vp9Video)||(!("mp4"!==t||!this.mp4Video&&!this.h264Video)||(!("ogg"!==t&&"ogv"!==t||!this.oggVideo)||!("mpeg"!==t||!this.hlsVideo)))},i.Device.needsTouchUnlock=function(){return!!(!this.cocoonJS&&(this.iOS||this.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)},i.Device.isAndroidStockBrowser=function(){var t=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return t&&t[1]<537},i.Canvas={create:function(t,e,s,n,r){e=e||256,s=s||256;var o=r?document.createElement("canvas"):i.CanvasPool.create(t,e,s);return"string"==typeof n&&""!==n&&(o.id=n),o.width=e,o.height=s,o.style.display="block",o},setBackgroundColor:function(t,e){return e=e||"rgb(0,0,0)",t.style.backgroundColor=e,t},setTouchAction:function(t,e){return e=e||"none",t.style.msTouchAction=e,t.style["ms-touch-action"]=e,t.style["touch-action"]=e,t},setUserSelect:function(t,e){return e=e||"none",t.style["-webkit-touch-callout"]=e,t.style["-webkit-user-select"]=e,t.style["-khtml-user-select"]=e,t.style["-moz-user-select"]=e,t.style["-ms-user-select"]=e,t.style["user-select"]=e,t.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",t},addToDOM:function(t,e,i){var s;return void 0===i&&(i=!0),e&&("string"==typeof e?s=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(s=e)),s||(s=document.body),i&&s.style&&(s.style.overflow="hidden"),s.appendChild(t),t},removeFromDOM:function(t){t.parentNode&&t.parentNode.removeChild(t)},setTransform:function(t,e,i,s,n,r,o){return t.setTransform(s,r,o,n,e,i),t},setSmoothingEnabled:function(t,e){var s=i.Canvas.getSmoothingPrefix(t);return s&&(t[s]=e),t},getSmoothingPrefix:function(t){var e=["i","webkitI","msI","mozI","oI"];for(var i in e){var s=e[i]+"mageSmoothingEnabled";if(s in t)return s}return null},getSmoothingEnabled:function(t){var e=i.Canvas.getSmoothingPrefix(t);if(e)return t[e]},setImageRenderingCrisp:function(t){for(var e=["-webkit-optimize-contrast","-moz-crisp-edges","crisp-edges","pixelated"],i=0;i0&&0==(t&t-1))return t;for(var e=1;e0&&0==(t&t-1)&&e>0&&0==(e&e-1)},random:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return Math.random()*(e-t)+t},between:function(t,e){if(void 0===t&&(t=0),void 0===e&&(e=1),t===e)return t;if(t>e){var i=t;t=e,e=i}return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t},fuzzyEqual:function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)e-i},fuzzyCeil:function(t,e){return void 0===e&&(e=1e-4),Math.ceil(t-e)},fuzzyFloor:function(t,e){return void 0===e&&(e=1e-4),Math.floor(t+e)},average:function(){for(var t=0,e=arguments.length,i=0;i=i.Math.PI2-s?t=e:(Math.abs(e-t)>Math.PI&&(et?t+=s:e=0?t:t+2*Math.PI},maxAdd:function(t,e,i){return Math.min(t+e,i)},minSub:function(t,e,i){return Math.max(t-e,i)},wrap:function(t,e,i){var s=i-e;if(s<=0)return 0;var n=(t-e)%s;return n<0&&(n+=s),n+e},wrapValue:function(t,e,i){return t=Math.abs(t),e=Math.abs(e),i=Math.abs(i),(t+e)%i},isOdd:function(t){return!!(1&t)},isEven:function(t){return!(1&t)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;et[i]&&(i=e);return t[i]},minProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;ie[s][t]&&(s=i);return e[s][t]},wrapAngle:function(t,e){return e?this.wrap(t,-Math.PI,Math.PI):this.wrap(t,-180,180)},linearInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return e<0?this.linear(t[0],t[1],s):e>1?this.linear(t[i],t[i-1],i-s):this.linear(t[n],t[n+1>i?i:n+1],s-n)},bezierInterpolation:function(t,e){for(var i=0,s=t.length-1,n=0;n<=s;n++)i+=Math.pow(1-e,s-n)*Math.pow(e,n)*t[n]*this.bernstein(s,n);return i},catmullRomInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return t[0]===t[i]?(e<0&&(n=Math.floor(s=i*(1+e))),this.catmullRom(t[(n-1+i)%i],t[n],t[(n+1)%i],t[(n+2)%i],s-n)):e<0?t[0]-(this.catmullRom(t[0],t[0],t[1],t[1],-s)-t[0]):e>1?t[i]-(this.catmullRom(t[i],t[i],t[i-1],t[i-1],s-i)-t[i]):this.catmullRom(t[n?n-1:0],t[n],t[i0?Math.ceil(t):Math.floor(t)},sinCosGenerator:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1);for(var n=e,r=i,o=s*Math.PI/t,a=[],h=[],l=0;l0?1:0},percent:function(t,e,i){return void 0===i&&(i=0),t>e||i>e?1:tt?0:(t-i)/e}},i.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},i.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e>>0,s=(e*=s)>>>0,s+=4294967296*(e-=s);return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},i.RandomDataGenerator.prototype.constructor=i.RandomDataGenerator,i.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},i.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new i.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new i.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new i.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new i.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null==this.nodes[0]||-1===(e=this.getIndex(t))){if(this.objects.push(t),this.objects.length>this.maxObjects&&this.levelthis.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.ythis.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof i.Rectangle)var e=this.objects,s=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,s=this.getIndex(t.body)}return this.nodes[0]&&(e=-1!==s?e.concat(this.nodes[s].retrieve(t)):(e=(e=(e=e.concat(this.nodes[0].retrieve(t))).concat(this.nodes[1].retrieve(t))).concat(this.nodes[2].retrieve(t))).concat(this.nodes[3].retrieve(t))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},i.QuadTree.prototype.constructor=i.QuadTree,i.Net=function(t){this.game=t},i.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},i.Net.prototype.constructor=i.Net,i.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:i.Easing.Power0,Power1:i.Easing.Power1,Power2:i.Easing.Power2,Power3:i.Easing.Power3,Power4:i.Easing.Power4,Linear:i.Easing.Linear.None,Quad:i.Easing.Quadratic.Out,Cubic:i.Easing.Cubic.Out,Quart:i.Easing.Quartic.Out,Quint:i.Easing.Quintic.Out,Sine:i.Easing.Sinusoidal.Out,Expo:i.Easing.Exponential.Out,Circ:i.Easing.Circular.Out,Elastic:i.Easing.Elastic.Out,Back:i.Easing.Back.Out,Bounce:i.Easing.Bounce.Out,"Quad.easeIn":i.Easing.Quadratic.In,"Cubic.easeIn":i.Easing.Cubic.In,"Quart.easeIn":i.Easing.Quartic.In,"Quint.easeIn":i.Easing.Quintic.In,"Sine.easeIn":i.Easing.Sinusoidal.In,"Expo.easeIn":i.Easing.Exponential.In,"Circ.easeIn":i.Easing.Circular.In,"Elastic.easeIn":i.Easing.Elastic.In,"Back.easeIn":i.Easing.Back.In,"Bounce.easeIn":i.Easing.Bounce.In,"Quad.easeOut":i.Easing.Quadratic.Out,"Cubic.easeOut":i.Easing.Cubic.Out,"Quart.easeOut":i.Easing.Quartic.Out,"Quint.easeOut":i.Easing.Quintic.Out,"Sine.easeOut":i.Easing.Sinusoidal.Out,"Expo.easeOut":i.Easing.Exponential.Out,"Circ.easeOut":i.Easing.Circular.Out,"Elastic.easeOut":i.Easing.Elastic.Out,"Back.easeOut":i.Easing.Back.Out,"Bounce.easeOut":i.Easing.Bounce.Out,"Quad.easeInOut":i.Easing.Quadratic.InOut,"Cubic.easeInOut":i.Easing.Cubic.InOut,"Quart.easeInOut":i.Easing.Quartic.InOut,"Quint.easeInOut":i.Easing.Quintic.InOut,"Sine.easeInOut":i.Easing.Sinusoidal.InOut,"Expo.easeInOut":i.Easing.Exponential.InOut,"Circ.easeInOut":i.Easing.Circular.InOut,"Elastic.easeInOut":i.Easing.Elastic.InOut,"Back.easeInOut":i.Easing.Back.InOut,"Bounce.easeInOut":i.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},i.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t,e){return e||(e=!1),this._tweens.some(function(i){return i.target===t&&(!e||i.isRunning&&!i.pendingDelete)})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},i.TweenManager.prototype.constructor=i.TweenManager,i.Tween=function(t,e,s){this.game=e,this.target=t,this.manager=s,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new i.Signal,this.onLoop=new i.Signal,this.onRepeat=new i.Signal,this.onChildComplete=new i.Signal,this.onComplete=new i.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=s.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},i.Tween.updateColor=function(t){i.Color.updateColor(t.target)},i.Tween.prototype={to:function(t,e,s,n,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).to(t,e,s,r,o,a)),n&&this.start(),this)},from:function(t,e,s,n,r,o,a){return void 0===e&&(e=1e3),void 0!==s&&null!==s||(s=i.Easing.Default),void 0===n&&(n=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof s&&this.manager.easeMap[s]&&(s=this.manager.easeMap[s]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new i.TweenData(this).from(t,e,s,r,o,a)),n&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),this.pendingDelete)return console.warn("Phaser.Tween.start cannot be called after Tween.stop"),this;if(null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(i=0;ithis.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(s=0;s0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t=this.startTime))return i.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var s in this.vEnd){var n=this.vStart[s],r=this.vEnd[s];Array.isArray(r)?this.parent.target[s]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[s]=n+(r-n)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():i.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction.call(this.interpolationContext,a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,i.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return i.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,i.TweenData.LOOPED}},i.TweenData.prototype.constructor=i.TweenData,i.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-i.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*i.Easing.Bounce.In(2*t):.5*i.Easing.Bounce.Out(2*t-1)+.5}}},i.Easing.Default=i.Easing.Linear.None,i.Easing.Power0=i.Easing.Linear.None,i.Easing.Power1=i.Easing.Quadratic.Out,i.Easing.Power2=i.Easing.Cubic.Out,i.Easing.Power3=i.Easing.Quartic.Out,i.Easing.Power4=i.Easing.Quintic.Out,i.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.updates=0,this.renders=0,this.fps=0,this.ups=0,this.rps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new i.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},i.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new i.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3){var t=this.now-this._timeLastSecond;this.fps=Math.round(1e3*this.frames/t),this.ups=Math.round(1e3*this.updates/t),this.rps=Math.round(1e3*this.renders/t),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0,this.updates=0,this.renders=0}},countUpdate:function(){this.advancedTiming&&this.updates++},countRender:function(){this.advancedTiming&&this.renders++},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(i.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),i.Time.prototype.constructor=i.Time,i.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new i.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},i.Timer.MINUTE=6e4,i.Timer.SECOND=1e3,i.Timer.HALF=500,i.Timer.QUARTER=250,i.Timer.prototype={create:function(t,e,s,n,r,o){var a=t=Math.round(t);0===this._now?a+=this.game.time.time:a+=this._now;var h=new i.TimerEvent(this,t,a,s,e,n,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.ticke.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i=e.tick)||e.pendingDelete)break;this._newTick=this._now+e.delay-(this._now-e.tick),this._newTick<0&&(this._newTick=this._now+e.delay),!0===e.loop?(e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):e.repeatCount>0?(e.repeatCount--,e.tick=this._newTick,e.callback.apply(e.callbackContext,e.args)):(this._marked++,e.pendingDelete=!0,e.callback.apply(e.callbackContext,e.args)),this._i++}this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;ethis._now?this.nextTick-this._now:0}}),Object.defineProperty(i.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(i.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(i.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),i.Timer.prototype.constructor=i.Timer,i.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},i.TimerEvent.prototype.constructor=i.TimerEvent,i.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},i.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,s,n,r){return e=e||[],s=s||60,void 0===n&&(n=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new i.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,s,n),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;ithis._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},i.AnimationManager.prototype.constructor=i.AnimationManager,Object.defineProperty(i.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(i.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(i.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(i.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(i.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){var e;"number"==typeof t&&this._frameData&&(e=this._frameData.getFrame(t))&&(this.currentFrame=e,this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(i.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){var e;"string"==typeof t&&this._frameData&&(e=this._frameData.getFrameByName(t))?(this.currentFrame=e,this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame)):console.warn("Cannot set frameName: "+t)}}),i.Animation=function(t,e,s,n,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=n,this.name=s,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new i.Signal,this.onUpdate=null,this.onComplete=new i.Signal,this.onLoop=new i.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},i.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(s=0;s=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay?(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay):this._frameDiff=0,this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(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=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},i.Animation.prototype.constructor=i.Animation,Object.defineProperty(i.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(i.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(i.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(i.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(i.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(i.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new i.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),i.Animation.generateFrameNames=function(t,e,s,n,r){void 0===n&&(n="");var o=[],a="";if(e=s;h--)a=t+(a="number"==typeof r?i.Utils.pad(h.toString(),r,"0",1):h.toString())+n,o.push(a);return o},i.Frame=function(t,e,s,n,r,o){this.index=t,this.x=e,this.y=s,this.width=n,this.height=r,0!==this.width&&0!==this.height||console.warn('Phaser.Frame: Frame "'+this.name+'" has a width or height of zero'),this.name=o,this.centerX=Math.floor(n/2),this.centerY=Math.floor(r/2),this.distance=i.Math.distance(0,0,n,r),this.rotated=!1,this.trimmed=!1,this.sourceSizeW=n,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},i.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=i.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new i.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new i.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},i.Frame.prototype.constructor=i.Frame,i.FrameData=function(){this._frames=[],this._frameNames=[]},i.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new i.FrameData,e=0;ed||h<-d)return console.warn("Phaser.AnimationParser.spriteSheet: skipFrames = "+h.toString()+" is larger than total sprite number "+d.toString()),null;if(h<0&&(h=d+h),-1!==r&&(d=h+r),0===c||0===u||cc&&(f=o,g+=n+a);return p},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var s,n=new i.FrameData,r=e.frames,o=0;o tag")}},i.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{},compressedTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new i.Signal,this._cacheMap=[],this._cacheMap[i.Cache.CANVAS]=this._cache.canvas,this._cacheMap[i.Cache.IMAGE]=this._cache.image,this._cacheMap[i.Cache.TEXTURE]=this._cache.texture,this._cacheMap[i.Cache.SOUND]=this._cache.sound,this._cacheMap[i.Cache.TEXT]=this._cache.text,this._cacheMap[i.Cache.PHYSICS]=this._cache.physics,this._cacheMap[i.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[i.Cache.BINARY]=this._cache.binary,this._cacheMap[i.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[i.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[i.Cache.JSON]=this._cache.json,this._cacheMap[i.Cache.XML]=this._cache.xml,this._cacheMap[i.Cache.VIDEO]=this._cache.video,this._cacheMap[i.Cache.SHADER]=this._cache.shader,this._cacheMap[i.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this._pendingCount=0,this.onReady=new i.Signal,this._addImages()},i.Cache.CANVAS=1,i.Cache.IMAGE=2,i.Cache.TEXTURE=3,i.Cache.SOUND=4,i.Cache.TEXT=5,i.Cache.PHYSICS=6,i.Cache.TILEMAP=7,i.Cache.BINARY=8,i.Cache.BITMAPDATA=9,i.Cache.BITMAPFONT=10,i.Cache.JSON=11,i.Cache.XML=12,i.Cache.VIDEO=13,i.Cache.SHADER=14,i.Cache.RENDER_TEXTURE=15,i.Cache.DEFAULT=null,i.Cache.DEFAULT_KEY="__default",i.Cache.DEFAULT_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==",i.Cache.MISSING=null,i.Cache.MISSING_KEY="__missing",i.Cache.MISSING_SRC="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==",i.Cache.READY_TIMEOUT=1e3,i.Cache.prototype={addCompressedTextureMetaData:function(t,e,s,n){this.checkImageKey(t)&&this.removeImage(t);var r=s in i.LoaderParser?i.LoaderParser[s](n):n,o={key:t,url:e,data:r,base:new PIXI.BaseTexture(r,null,this.game.resolution),frame:new i.Frame(0,0,0,r.width,r.height,t),frameData:new i.FrameData,fileFormat:s};return o.frameData.addFrame(new i.Frame(0,0,0,r.width,r.height,e)),this._cache.image[t]=o,this._resolveURL(e,o),o},addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,s){this.checkImageKey(t)&&this.removeImage(t),!1===s.complete&&console.warn('Phaser.Cache.addImage: Image "'+t+"\" hasn't been retrieved yet");var n={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution),frame:new i.Frame(0,0,0,s.width,s.height,t),frameData:new i.FrameData};return n.frameData.addFrame(new i.Frame(0,0,0,s.width,s.height,e)),this._cache.image[t]=n,this._resolveURL(e,n),"__default"===t?i.Cache.DEFAULT=new PIXI.Texture(n.base):"__missing"===t&&(i.Cache.MISSING=new PIXI.Texture(n.base)),n},addImageAsync:function(t,e,i){var s=this,n=new Image;n.onload=function(){i.call(this,s.addImage(t,null,n)),s._removePending(),n.onload=null},this._addPending(),n.src=e},addDefaultImage:function(){this.addImageAsync(i.Cache.DEFAULT_KEY,i.Cache.DEFAULT_SRC,function(t){t.base.skipRender=!0,i.Cache.DEFAULT=new PIXI.Texture(t.base)})},addMissingImage:function(){this.addImageAsync(i.Cache.MISSING_KEY,i.Cache.MISSING_SRC,function(t){i.Cache.MISSING=new PIXI.Texture(t.base)})},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,s){return e.key=t,void 0===s&&(s=new i.FrameData).addFrame(e.textureFrame),this._cache.bitmapData[t]={data:e,frameData:s},e},addBitmapFont:function(t,e,s,n,r,o,a){var h={url:e,data:s,font:null,base:new PIXI.BaseTexture(s,null,this.game.resolution)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?i.LoaderParser.jsonBitmapFont(n,h.base,o,a,!1,this.game.resolution):i.LoaderParser.xmlBitmapFont(n,h.base,o,a,!1,this.game.resolution),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addBitmapFontFromAtlas:function(t,e,s,n,r,o,a){var h=this.getFrameByName(e,s);if(h){var l={font:null,base:this.getBaseTexture(e),frame:h};void 0===o&&(o=0),void 0===a&&(a=0);var c;"json"===r?(c=this.getJSON(n),l.font=i.LoaderParser.jsonBitmapFont(c,l.base,o,a,h,this.game.resolution)):(c=this.getXML(n),l.font=i.LoaderParser.xmlBitmapFont(c,l.base,o,a,h,this.game.resolution)),this._cache.bitmapFont[t]=l}},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new i.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,s,n,r,o,a,h,l){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var c={key:t,url:e,data:s,frameWidth:n,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(s,null,this.game.resolution),frameData:i.AnimationParser.spriteSheet(this.game,s,n,r,o,a,h,l)};this._cache.image[t]=c,this._resolveURL(e,c)},addTextureAtlas:function(t,e,s,n,r){var o={key:t,url:e,data:s,base:new PIXI.BaseTexture(s,null,this.game.resolution)};r===i.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=i.AnimationParser.XMLData(this.game,n,t):r===i.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=i.AnimationParser.JSONDataPyxel(this.game,n,t):Array.isArray(n.frames)?o.frameData=i.AnimationParser.JSONData(this.game,n,t):o.frameData=i.AnimationParser.JSONDataHash(this.game,n,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,i.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(i.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(i.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(i.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(i.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(i.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(i.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(i.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(i.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(i.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(i.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(i.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(i.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(i.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(i.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(i.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,i.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var s=this.getItem(t,i.Cache.IMAGE,"getImage");return null===s&&(s=this.getItem("__missing",i.Cache.IMAGE,"getImage")),e?s:s.data},getTextureFrame:function(t){return this.getItem(t,i.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,i.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,i.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,i.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,s){var n=this.getItem(t,i.Cache.PHYSICS,"getPhysicsData","data");if(null===n||void 0===e||null===e)return n;if(n[e]){var r=n[e];if(!r||!s)return r;for(var o in r)if((o=r[o]).fixtureKey===s)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+s+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,i.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,i.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,i.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,i.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var s=this.getItem(t,i.Cache.JSON,"getJSON","data");return s?e?i.Utils.extend(!0,Array.isArray(s)?[]:{},s):s:null},getXML:function(t){return this.getItem(t,i.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,i.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,i.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,i.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=i.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,s){void 0===s&&(s=i.Cache.IMAGE),this._cacheMap[s][t]&&(this._cacheMap[s][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){return(t=this._resolveURL(t))?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=i.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var s in this._cacheMap[t])"__default"!==s&&"__missing"!==s&&e.push(s);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.image[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t0?setTimeout(function(){t.isReady||(console.warn("Phaser.Cache: Still waiting for images after %s ms.",e),t._ready())},i.Cache.READY_TIMEOUT):this._ready()},_addPending:function(){this._pendingCount+=1},_removePending:function(){this._pendingCount-=1,this._checkReady()},_checkReady:function(){this.isReady&&this._ready()},_ready:function(){this._pendingCount=0,this.onReady.dispatch(this)}},i.Cache.prototype.constructor=i.Cache,Object.defineProperty(i.Cache.prototype,"isReady",{get:function(){return this._pendingCount<=0}}),i.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new i.Signal,this.onLoadComplete=new i.Signal,this.onPackComplete=new i.Signal,this.onFileStart=new i.Signal,this.onFileComplete=new i.Signal,this.onFileError=new i.Signal,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},i.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,i.Loader.TEXTURE_ATLAS_JSON_HASH=1,i.Loader.TEXTURE_ATLAS_XML_STARLING=2,i.Loader.PHYSICS_LIME_CORONA_JSON=3,i.Loader.PHYSICS_PHASER_JSON=4,i.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,i.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new i.Rectangle(0,0,1,t.height):new i.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r=e||t&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var n=this;setTimeout(function(){n.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.reset(),this.onLoadComplete.dispatch(),this.game.state&&this.game.state.loadComplete())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(e)for(var s=0;s=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},getVideoURL:function(t){for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e=0&&(s=s.substr(0,s.indexOf("?"))),i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s="error loading asset from URL "+(t.requestUrl||this.transformUrl(t.url,t));!i&&e&&(i=e.status),i&&(s=s+" ("+i+")"),this.asyncComplete(t,s)},fileComplete:function(t,e){var s=!0;switch(t.type){case"packfile":r=JSON.parse(e.responseText);t.data=r||{};break;case"texture":var n=/\.([^.]+)$/.exec(t.url.split("?",1)[0])[1].toLowerCase();null!==t.data?this.cache.addCompressedTextureMetaData(t.key,t.url,n,t.data):this.cache.addCompressedTextureMetaData(t.key,t.url,n,e.response);break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing,t.skipFrames);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(s=!1,t.format===i.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===i.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===i.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==i.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(s=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var r=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,r,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}s&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else(e=new ActiveXObject("Microsoft.XMLDOM")).async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(i.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return i.Math.clamp(t||0,0,100)}}),Object.defineProperty(i.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),i.Loader.prototype.constructor=i.Loader,i.LoaderParser={bitmapFont:function(t,e,i,s,n,r){return this.xmlBitmapFont(t,e,i,s,n,r)},xmlBitmapFont:function(t,e,i,s,n,r){null==r&&(r=1);var o={},a=t.getElementsByTagName("info")[0],h=t.getElementsByTagName("common")[0];o.font=a.getAttribute("face"),o.size=parseInt(a.getAttribute("size"),10),o.lineHeight=parseInt(h.getAttribute("lineHeight"),10)+s,o.chars={};for(var l=t.getElementsByTagName("char"),c=n?n.x:0,u=n?n.y:0,d=0;d=0){switch(r>=0&&r<=3?e="PVRTC":r>=7&&r<=11?e="S3TC":6===r&&(e="ETC1"),r){case 0:o=35841;break;case 1:o=35843;break;case 2:o=35840;break;case 3:o=35842;break;case 6:o=36196;break;case 7:o=33777;break;case 9:o=33778;break;case 11:o=33779;break;default:o=-1}n={complete:!0,fileFormat:"PVR",compressionAlgorithm:e,flags:i[1],pixelFormat:r,colorSpace:i[4],channelType:i[5],height:i[6],width:i[7],depth:i[8],numberOfSurfaces:i[9],numberOfFaces:i[10],numberOfMipmaps:i[11],metaDataSize:i[12],textureData:s.subarray(52+i[12],s.byteLength),glExtensionFormat:o}}return n},dds:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null;return 68===e[0]&&68===e[1]&&83===e[2]&&32===e[3]&&"DX10"===(s={complete:!0,fileFormat:"DDS",compressionAlgorithm:"S3TC",size:i[1],flags:i[2],height:i[3],width:i[4],pitch:i[5],depth:i[6],mipmapCount:i[7],formatSize:i[19],formatFlag:i[19],formatFourCC:[String.fromCharCode(e[84]),String.fromCharCode(e[85]),String.fromCharCode(e[86]),String.fromCharCode(e[87])].join(""),formatBitCount:i[21],formatRBitMask:i[22],formatGBitMask:i[23],formatBBitMask:i[24],formatABitMask:i[25],caps1:i[26],caps2:i[27],caps3:i[28],caps4:i[29],reserved2:i[30],DXGIFormat:null,resourceDimension:null,miscFlag:null,arraySize:null,textureData:e.subarray(i[1]+4,e.byteLength)}).formatFourCC&&(s.DXGIFormat=i[31],s.resourceDimension=i[32],s.miscFlag=i[33],s.arraySize=i[34],s.miscFlag=i[35]),s},ktx:function(t){var e=new Uint8Array(t),i=new Uint32Array(t),s=null,n=16+i[15]/4|0,r=i[n],o=i[7],a=0;if(171===e[0]&&75===e[1]&&84===e[2]&&88===e[3]&&32===e[4]&&49===e[5]&&49===e[6]&&187===e[7]&&13===e[8]&&10===e[9]&&26===e[10]&&10===e[11]&&[36196,35840,35841,35842,35843,33776,33777,33778,33779].indexOf(o)>=0){switch(o){case 36196:a="ETC1";break;case 35840:case 35841:case 35842:case 35843:a="PVRTC";break;case 33776:case 33777:case 33778:case 33779:a="S3TC"}s={complete:!0,fileFormat:"KTX",compressionAlgorithm:a,endianness:i[3],glType:i[4],glTypeSize:i[5],glFormat:i[6],glInternalFormat:i[7],glBaseInternalFormat:i[8],width:i[9],height:i[10],pixelDepth:i[11],numberOfArrayElements:i[12],numberOfFaces:i[13],numberOfMipmapLevels:i[14],bytesOfKeyValueData:i[15],keyAndValueByteSize:i[16],imageSize:r,textureData:e.subarray(4*(n+1),r+100)}}return s},pkm:function(t){var e=new Uint8Array(t),i=null;return 80===e[0]&&75===e[1]&&77===e[2]&&32===e[3]&&(i={complete:!0,fileFormat:"PKM",compressionAlgorithm:"ETC1",format:65535&(e[6]<<8|e[7]),width:65535&(e[8]<<8|e[9]),height:65535&(e[10]<<8|e[11]),originalWidth:65535&(e[12]<<8|e[13]),originalHeight:65535&(e[14]<<8|e[15]),textureData:e.subarray(16,e.length)}),i}},i.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},i.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},i.AudioSprite.prototype.constructor=i.AudioSprite,i.Sound=function(t,e,s,n,r){void 0===s&&(s=1),void 0===n&&(n=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=n,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this._globalVolume=1,this._markedToDelete=!1,this._removeFromSoundManager=!1,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=s,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new i.Signal,this.onPlay=new i.Signal,this.onPause=new i.Signal,this.onResume=new i.Signal,this.onLoop=new i.Signal,this.onStop=new i.Signal,this.onMute=new i.Signal,this.onMarkerComplete=new i.Signal,this.onFadeComplete=new i.Signal,this._volume=s,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},i.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop(),this._markedToDelete&&(this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode),this._removeFromSoundManager?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()))},update:function(){this.game.cache.checkSoundKey(this.key)?(this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))):this.destroy()},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){this.isPlaying&&!this.paused&&e!==this.volume&&(void 0===t&&(t=1e3),void 0!==e?(this.fadeTween=this.game.add.tween(this).to({volume:e},t,i.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)):console.warn("Phaser.Sound.fadeTo: No Volume Specified."))},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._globalVolume=t,this._sound.volume=this._globalVolume*this._volume)},destroy:function(t){void 0===t&&(t=!0),this._markedToDelete=!0,this._removeFromSoundManager=t,this.stop(),t?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())}},i.Sound.prototype.constructor=i.Sound,Object.defineProperty(i.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(i.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(i.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(i.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted?this._muteVolume=t:(this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=this._globalVolume*t))}}),i.SoundManager=function(t){this.game=t,this.onSoundDecode=new i.Signal,this.onVolumeChange=new i.Signal,this.onMute=new i.Signal,this.onUnMute=new i.Signal,this.onTouchUnlock=new i.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new i.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},i.SoundManager.prototype={boot:function(){var t=this.game.device,e=window.PhaserGlobal;if(t.iOS&&!1===t.webAudio&&(this.channels=1),e){if(!0===e.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===e.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(e&&e.audioContext)this.context=e.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||t.needsTouchUnlock()&&this.setTouchLock(),this.usingWebAudio&&t.chrome&&t.chromeVersion<=65&&console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. ')},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0)},setTouchUnlock:function(){this.touchLocked=!1,this._unlockSource=null,this.onTouchUnlock.dispatch()},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.setTouchUnlock();else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0),"suspended"===this._unlockSource.context.state&&this._unlockSource.context.resume()}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,s=this._parentBounds.height,n=this.getParentBounds(this._parentBounds),r=n.width!==e||n.height!==s,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,n),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottlee;return(h=h?s:!s)?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},i.ScaleManager.prototype.constructor=i.ScaleManager,Object.defineProperty(i.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(i.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(i.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(i.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(i.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(i.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),i.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.lineWidth=1,this.renderShadow=!0,this.currentColor=null,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1,this.isDisabled=!1,this._line=null,this._rect=null},i.Utils.Debug.prototype={boot:function(){this.game.renderType===i.CANVAS?this.context=this.game.context:(this.bmd=new i.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=i.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d")),this._line=new i.Line,this._rect=new i.Rectangle},resize:function(){this.bmd.resize(this.game.width,this.game.height),this.canvas.width=this.game.width,this.canvas.height=this.game.height},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e0)for(var e=0;e=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new i.Rectangle,layoutBounds:new i.Rectangle,documentBounds:new i.Rectangle},i.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},s=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(i.DOM,"scrollX",{get:e}),Object.defineProperty(i.DOM,"scrollY",{get:s}),Object.defineProperty(i.DOM.visualBounds,"x",{get:e}),Object.defineProperty(i.DOM.visualBounds,"y",{get:s}),Object.defineProperty(i.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(i.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var n=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(i.DOM.visualBounds,"width",{get:n}),Object.defineProperty(i.DOM.visualBounds,"height",{get:r}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:n}),Object.defineProperty(i.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(i.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(i.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(i.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(i.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(i.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(i.ArraySet.prototype,"next",{get:function(){return this.position=s||0===i)){null==i&&(i=1);for(var n=s-i,r=e;r0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=(t=i.ArrayUtils.transposeMatrix(t)).reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=i.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var s=0;s>>0:(t<<24|e<<16|s<<8|n)>>>0},unpackPixel:function(t,e,s,n){return void 0!==e&&null!==e||(e=i.Color.createColor()),void 0!==s&&null!==s||(s=!1),void 0!==n&&null!==n||(n=!1),i.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",s&&i.Color.RGBtoHSL(e.r,e.g,e.b,e),n&&i.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=i.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},hexToRGBArray:function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},RGBArrayToHex:function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},RGBtoHSL:function(t,e,s,n){n||(n=i.Color.createColor(t,e,s,1)),t/=255,e/=255,s/=255;var r=Math.min(t,e,s),o=Math.max(t,e,s);if(n.h=0,n.s=0,n.l=(o+r)/2,o!==r){var a=o-r;n.s=n.l>.5?a/(2-o-r):a/(o+r),o===t?n.h=(e-s)/a+(e1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,s,n,r,o,a,h){var l={r:t||0,g:e||0,b:s||0,a:n||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return i.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toFixed()+","+t.g.toFixed()+","+t.b.toFixed()+","+t.a.toString()+")",t.color=i.Color.getColor(t.r,t.g,t.b),t.color32=i.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,s,n,r){return void 0===n&&(n=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+s).toString(16).slice(1):"0x"+i.Color.componentToHex(n)+i.Color.componentToHex(t)+i.Color.componentToHex(e)+i.Color.componentToHex(s)},hexToRGB:function(t){var e=i.Color.hexToColor(t);if(e)return i.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var s=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(s){var n=parseInt(s[1],16),r=parseInt(s[2],16),o=parseInt(s[3],16);e?(e.r=n,e.g=r,e.b=o):e=i.Color.createColor(n,r,o)}return e},webToColor:function(t,e){e||(e=i.Color.createColor());var s=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return s&&(e.r=~~Number(s[1]),e.g=~~Number(s[2]),e.b=~~Number(s[3]),e.a=void 0!==s[4]?Number(s[4]):1,i.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=i.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?i.Color.webToColor(t,e):(e.a=1,i.Color.hexToColor(t,e));if("number"==typeof t){var s=i.Color.getRGB(t);return e.r=s.r,e.g=s.g,e.b=s.b,e.a=s.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSVtoRGB(n/359,t,e));return s},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var s=[],n=0;n<=359;n++)s.push(i.Color.HSLtoRGB(n/359,t,e));return s},interpolateColor:function(t,e,s,n,r,o){void 0===r&&(r=255),void 0===o&&(o=0);var a=i.Color.getRGB(t),h=i.Color.getRGB(e);if(0===o)var l=(h.red-a.red)*n/s+a.red,c=(h.green-a.green)*n/s+a.green,u=(h.blue-a.blue)*n/s+a.blue;if(1===o){var d,p=i.Color.RGBtoHSV(a.r,a.g,a.b),f=i.Color.RGBtoHSV(h.r,h.g,h.b),g=f.h-p.h;if(p.h>f.h){var m=f.h;f.h=p.h,p.h=m,g=-g,n=s-n}g>.5&&(p.h=p.h+1,d=((f.h-p.h)*n/s+p.h)%1),g<=.5&&(d=(f.h-p.h)*n/s+p.h);var y=(f.s-p.s)*n/s+p.s,v=(f.v-p.v)*n/s+p.v,x=i.Color.HSVtoRGB(d,y,v,x),l=x.r,c=x.g,u=x.b}return i.Color.getColor32(r,l,c,u)},interpolateColorWithRGB:function(t,e,s,n,r,o){var a=i.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(s-a.green)*o/r+a.green,c=(n-a.blue)*o/r+a.blue;return i.Color.getColor(h,l,c)},interpolateRGB:function(t,e,s,n,r,o,a,h){var l=(n-t)*h/a+t,c=(r-e)*h/a+e,u=(o-s)*h/a+s;return i.Color.getColor(l,c,u)},linear:function(t,e,i){return this.interpolateColor(t,e,1,i)},linearInterpolation:function(t,e){var s=i.Math.linear(0,t.length-1,e),n=t[Math.floor(s)],r=t[Math.ceil(s)];return this.linear(n,r,s%1)},getRandomColor:function(t,e,s){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===s&&(s=255),e>255||t>e)return i.Color.getColor(255,255,255);var n=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return i.Color.getColor32(s,n,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=i.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return i.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return i.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return i.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?i.Color.blendLinearBurn(t,2*e):i.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?i.Color.blendColorBurn(t,2*e):i.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?i.Color.blendDarken(t,2*e):i.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return i.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return i.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},i.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},i.Physics.ARCADE=0,i.Physics.P2JS=1,i.Physics.NINJA=2,i.Physics.BOX2D=3,i.Physics.CHIPMUNK=4,i.Physics.MATTERJS=5,i.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!i.Physics.hasOwnProperty("Arcade")||(this.arcade=new i.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&i.Physics.hasOwnProperty("Ninja")&&(this.ninja=new i.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&i.Physics.hasOwnProperty("P2")&&(this.p2=new i.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&i.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new i.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&i.Physics.hasOwnProperty("Matter")&&(this.matter=new i.Physics.Matter(this.game,this.config))},startSystem:function(t){t===i.Physics.ARCADE?this.arcade=new i.Physics.Arcade(this.game):t===i.Physics.P2JS?null===this.p2?this.p2=new i.Physics.P2(this.game,this.config):this.p2.reset():t===i.Physics.NINJA?this.ninja=new i.Physics.Ninja(this.game):t===i.Physics.BOX2D?null===this.box2d?this.box2d=new i.Physics.Box2D(this.game,this.config):this.box2d.reset():t===i.Physics.MATTERJS&&(null===this.matter?this.matter=new i.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,s){void 0===e&&(e=i.Physics.ARCADE),void 0===s&&(s=!1),e===i.Physics.ARCADE?this.arcade.enable(t):e===i.Physics.P2JS&&this.p2?this.p2.enable(t,s):e===i.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===i.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===i.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},i.Physics.prototype.constructor=i.Physics,i.Physics.Arcade=function(t){this.game=t,this.gravity=new i.Point,this.bounds=new i.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=i.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new i.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._total=0,this.setBoundsToWorld()},i.Physics.Arcade.prototype.constructor=i.Physics.Arcade,i.Physics.Arcade.SORT_NONE=0,i.Physics.Arcade.LEFT_RIGHT=1,i.Physics.Arcade.RIGHT_LEFT=2,i.Physics.Arcade.TOP_BOTTOM=3,i.Physics.Arcade.BOTTOM_TOP=4,i.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof i.Group?this.enable(t[s].children,e):(this.enableBody(t[s]),e&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],!0));else t instanceof i.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.Arcade.Body(t),t.parent&&t.parent instanceof i.Group&&t.parent.addToHash(t))},updateMotion:function(t){if(t.allowRotation){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed}t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&e.allowDrag&&(i-(n*=this.game.time.physicsElapsed)>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!0),this._total>0},collide:function(t,e,i,s,n){return i=i||null,s=s||null,n=n||i,this._total=0,this.collideObjects(t,e,i,s,n,!1),this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===i.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===i.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===i.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===i.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideObjects:function(t,e,i,s,n,r){if(!Array.isArray(t)&&Array.isArray(e))for(o=0;oa.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(t.body.bottoma.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,s,n,r,o)}}else{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(e);for(var c=this.quadTree.retrieve(t),h=0;hc.right)continue;if(c.x>a.right)break}else if(this.sortDirection===i.Physics.Arcade.TOP_BOTTOM){if(a.bottomc.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,s,n,r)}}}}},collideGroupVsGroup:function(t,e,s,n,r,o){if(0!==t.length&&0!==e.length)for(var a=0;aa.bottom)&&(h.xa.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var s=i.Math.clamp(t.center.x,e.left,e.right),n=i.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-s)*(t.center.x-s)+(t.center.y-n)*(t.center.y-n)<=t.halfWidth*t.halfWidth},separateCircle:function(t,e,s){this.getOverlapX(t,e),this.getOverlapY(t,e);var n=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,n),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.center.x:e.center.x,y:t.isCircle?t.center.y:e.center.y,radius:t.isCircle?t.halfWidth:e.halfWidth};l.yh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.xh.right&&(a=i.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.halfWidth+e.halfWidth-i.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(s||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.yMath.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x)>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0):t.deltaX()n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y)>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0):t.deltaY()n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,s,n,r,o){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(s);for(var a=new i.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c0&&(s=this.distanceBetween(t,e)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.setToPolar(n,e),n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.setToPolar(r,s),r},velocityFromAngle:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e,!0)},velocityFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerationFromRotation:function(t,e,s){return void 0===e&&(e=60),(s=s||new i.Point).setToPolar(t,e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setToPolar(r,i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(o,s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i,s){void 0===i&&(i=!1);var n,r;return s?(n=t.centerX-e.centerX,r=t.centerY-e.centerY):i?(n=t.world.x-e.world.x,r=t.world.y-e.world.y):(n=t.x-e.x,r=t.y-e.y),Math.sqrt(n*n+r*r)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},closest:function(t,e,i,s){for(var n=1/0,r=null,o=0,a=e.length;on&&(r=h,n=l)}return r},angleBetween:function(t,e,s){return void 0===s&&(s=!1),s?i.Point.angle(e.world,t.world):i.Point.angle(e,t)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},i.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=i.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new i.Point,this.position=new i.Point(t.x,t.y),this.prev=new i.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new i.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new i.Point,this.newVelocity=new i.Point,this.deltaMax=new i.Point,this.acceleration=new i.Point,this.allowDrag=!0,this.drag=new i.Point,this.allowGravity=!0,this.gravity=new i.Point,this.bounce=new i.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new i.Point(1e4,1e4),this.friction=new i.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=i.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={none:!0,up:!1,down:!1,left:!1,right:!1},this.tilePadding=new i.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new i.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},i.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.updateCenter())},updateCenter:function(){this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,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=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.none=!0,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.overlapR=0,this.overlapX=0,this.overlapY=0,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.updateCenter(),this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),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,this.updateCenter(),this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=this.velocity.atan()),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=i.LEFT:this.deltaX()>0&&(this.facing=i.RIGHT),this.deltaY()<0?this.facing=i.UP:this.deltaY()>0&&(this.facing=i.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.updateCenter(),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;return t.xe.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0,this.blocked.none=!1),t.ye.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0,this.blocked.none=!1),!this.blocked.none},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.setToPolar(s,e),this.isMoving=!0,!0},moveTo:function(t,e,s){var n=e/(t/1e3);if(0===n)return!1;var r;return void 0===s?(r=this.angle,s=this.game.math.radToDeg(r)):r=this.game.math.degToRad(s),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new i.Line,this.moveEnd=new i.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===s||180===s?this.velocity.set(Math.cos(r)*n,0):90===s||270===s?this.velocity.set(0,Math.sin(r)*n):this.velocity.setToPolar(r,n),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,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(i,s),this.updateCenter(),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,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(e,i),this.updateCenter()):this.isCircle=!1},reset:function(t,e){this.stop(),this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this.updateBounds(),this.updateCenter()},stop:function(){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0},getBounds:function(t){return t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom,t},hitTest:function(t,e){return this.isCircle?i.Circle.contains(this,t,e):i.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},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},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof i.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(i.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(i.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),i.Physics.Arcade.Body.render=function(t,e,i,s,n){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,t.lineWidth=n||1,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.halfWidth,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},i.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},i.Physics.Arcade.Body.prototype.constructor=i.Physics.Arcade.Body,i.Physics.Arcade.TilemapCollision=function(){},i.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x-e.getTileOffsetX(),t.body.position.y-t.body.tilePadding.y-e.getTileOffsetY(),t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;ae.deltaAbsY()?l=-1:e.deltaAbsX()0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.getTileOffsetY();return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?(t.blocked.left=!0,t.blocked.none=!1):e>0&&(t.blocked.right=!0,t.blocked.none=!1),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?(t.blocked.up=!0,t.blocked.none=!1):e>0&&(t.blocked.down=!0,t.blocked.none=!1),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},i.Utils.mixinPrototype(i.Physics.Arcade.prototype,i.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,i.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new i.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new i.Signal,this.onBodyRemoved=new i.Signal,this.onSpringAdded=new i.Signal,this.onSpringRemoved=new i.Signal,this.onConstraintAdded=new i.Signal,this.onConstraintRemoved=new i.Signal,this.onContactMaterialAdded=new i.Signal,this.onContactMaterialRemoved=new i.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},i.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,s){void 0===e&&(e=!1),void 0===s&&(s=!0);var n=1;if(Array.isArray(t))for(n=t.length;n--;)t[n]instanceof i.Group?this.enable(t[n].children,e,s):(this.enableBody(t[n],e),s&&t[n].hasOwnProperty("children")&&t[n].children.length>0&&this.enable(t[n],e,!0));else t instanceof i.Group?this.enable(t.children,e,s):(this.enableBody(t,e),s&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new i.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new i.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new i.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new i.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);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.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof i.Physics.P2.Spring||t instanceof i.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.DistanceConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,s,n){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.GearConstraint(this,t,e,s,n));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,s,n,r,o){if(t=this.getBody(t),s=this.getBody(s),t&&s)return this.addConstraint(new i.Physics.P2.RevoluteConstraint(this,t,e,s,n,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,s,n,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.LockConstraint(this,t,e,s,n,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,s,n,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new i.Physics.P2.PrismaticConstraint(this,t,e,s,n,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var s=new i.Physics.P2.Material(t);return this.materials.push(s),void 0!==e&&e.setMaterial(s),s},createContactMaterial:function(t,e,s){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var n=new i.Physics.P2.ContactMaterial(t,e,s);return this.addContactMaterial(n)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof i.Physics.P2.Body?t.data:t.body&&t.body.type===i.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,s,n){void 0===e&&(e=this.world.bodies),void 0===s&&(s=5),void 0===n&&(n=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof i.Physics.P2.Body&&(!n||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!n||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof i.Sprite&&e[a].hasOwnProperty("body")&&(!n||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,s)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var s=new i.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(s),t&&this.setCollisionGroup(t,s),s},setCollisionGroup:function(t,e){if(t instanceof i.Group)for(var s=0;s-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides?n+=u.width:((p=this.createBody(r,o,0,!1)).addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0)}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(i.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(i.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(i.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(i.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(i.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(i.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(i.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(i.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(i.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(i.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),i.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},i.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionGroup=t})},setMask:function(t,e){this.getFixtures(e).forEach(function(e){e.collisionMask=t})},setSensor:function(t,e){this.getFixtures(e).forEach(function(e){e.sensor=t})},setMaterial:function(t,e){this.getFixtures(e).forEach(function(e){e.material=t})},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},i.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.PointProxy.prototype.constructor=i.Physics.P2.PointProxy,Object.defineProperty(i.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(i.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),i.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},i.Physics.P2.InversePointProxy.prototype.constructor=i.Physics.P2.InversePointProxy,Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(i.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),i.Physics.P2.Body=function(t,e,s,n,r){e=e||null,s=s||0,n=n||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=i.Physics.P2JS,this.offset=new i.Point,this.data=new p2.Body({position:[this.world.pxmi(s),this.world.pxmi(n)],mass:r}),this.data.parent=this,this.velocity=new i.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new i.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new i.Point,this.onBeginContact=new i.Signal,this.onEndContact=new i.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},i.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(r=0;r-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var n=this.getCollisionMask();if(void 0===i)for(var r=this.data.shapes.length-1;r>=0;r--)this.data.shapes[r].collisionMask=n;else i.collisionMask=n},collides:function(t,e,i,s){if(Array.isArray(t))for(r=0;r=0;r--)this.data.shapes[r].collisionMask=n;else s.collisionMask=n},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},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(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;np;n=0<=p?++d:--d)l=e.vertices[n],p2.vec2.rotate(u,l,t),c.push([(u[0]+a[0])*this.ppu,-(u[1]+a[1])*this.ppu]);this.drawConvex(h,c,e.triangles,16711680,i,r,this.settings.debugPolygons,[a[0]*this.ppu,-a[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)p=(c=e[l])[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return 2===(e=t.toString(16)).length?e:e+"0"}}),i.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1);var c={restLength:s=t.pxm(s),stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},i.Physics.P2.Spring.prototype.constructor=i.Physics.P2.Spring,i.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},i.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),i.Physics.P2.Material.prototype.constructor=i.Physics.P2.Material,i.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},i.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),i.Physics.P2.ContactMaterial.prototype.constructor=i.Physics.P2.ContactMaterial,i.Physics.P2.CollisionGroup=function(t){this.mask=t},i.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t;var a={distance:s=t.pxm(s),localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},i.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),i.Physics.P2.DistanceConstraint.prototype.constructor=i.Physics.P2.DistanceConstraint,i.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},i.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),i.Physics.P2.GearConstraint.prototype.constructor=i.Physics.P2.GearConstraint,i.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t;var o={localOffsetB:s=[t.pxm(s[0]),t.pxm(s[1])],localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},i.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),i.Physics.P2.LockConstraint.prototype.constructor=i.Physics.P2.LockConstraint,i.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t;var h={localAnchorA:n=[t.pxmi(n[0]),t.pxmi(n[1])],localAnchorB:r=[t.pxmi(r[0]),t.pxmi(r[1])],localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},i.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),i.Physics.P2.PrismaticConstraint.prototype.constructor=i.Physics.P2.PrismaticConstraint,i.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},i.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),i.Physics.P2.RevoluteConstraint.prototype.constructor=i.Physics.P2.RevoluteConstraint,i.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},i.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&tthis.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},i.Tile.prototype.constructor=i.Tile,Object.defineProperty(i.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(i.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(i.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(i.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(i.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(i.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),i.Tilemap=function(t,e,s,n,r,o){this.game=t,this.key=e;var a=i.TilemapParser.parse(this.game,e,s,n,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},i.Tilemap.CSV=0,i.Tilemap.TILED_JSON=1,i.Tilemap.NORTH=0,i.Tilemap.EAST=1,i.Tilemap.SOUTH=2,i.Tilemap.WEST=3,i.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,s,n,r,o,a){if(void 0===t)return null;void 0===s&&(s=this.tileWidth),void 0===n&&(n=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===s&&(s=32),0===n&&(n=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof i.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===i.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),console.log("Tilesets: ",this.tilesets),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new i.Tileset(t,a,s,n,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y1)for(u=0;uthis.layers.length)return console.warn('Tilemap.createLayer: Invalid layer ID given: "'+t+'"'),void console.log("Layers: ",this.layers);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===s||s<=0?s=Math.min(this.game.height,this.layers[r].heightInPixels):s>this.game.height&&(s=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",s),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=n.add(new i.TilemapLayer(this.game,this,r,e,s));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,s,n,r,o){void 0===o&&(o=this.game.world);{if(null===this.getLayerIndex(t)){for(var a,h={name:t,x:0,y:0,width:e,height:s,widthInPixels:e*n,heightInPixels:s*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;cthis.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height),(l=new i.TilemapLayer(this.game,this,this.layers.length-1,d,p)).name=t,o.add(l)}console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t)}},getIndex:function(t,e){for(var i=0;ie)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n-1&&this.collideIndexes.splice(n,1)}for(var r=0;r0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e-1},removeTile:function(t,e,s){if(s=this.getLayer(s),t>=0&&t=0&&e=0&&e=0&&s-1?this.layers[n].data[s][e].setCollision(!0,!0,!0,!0):this.layers[n].data[s][e].resetCollision(),this.layers[n].dirty=!0,this.calculateFaces(n),this.layers[n].data[s][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(r=this.layers[s].height-1;r>=0;r--)for(o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r=0&&t=0&&ethis.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},i.Tilemap.prototype.constructor=i.Tilemap,Object.defineProperty(i.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),i.TilemapLayer=function(t,e,s,n,r){n|=0,r|=0,i.Sprite.call(this,t,0,0),this.map=e,this.index=s,this.layer=e.layers[s],this.canvas=i.CanvasPool.create(this,n,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas,null,this.game.resolution))),this.type=i.TILEMAPLAYER,this.physicsType=i.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!0,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this.tileOffset=new i.Point(this.layer.offsetX||0,this.layer.offsetY||0),this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=i.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},i.TilemapLayer.prototype=Object.create(i.Sprite.prototype),i.TilemapLayer.prototype.constructor=i.TilemapLayer,i.TilemapLayer.prototype.preUpdateCore=i.Component.Core.preUpdate,i.TilemapLayer.sharedCopyCanvas=null,i.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=i.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},i.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},i.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y},i.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},i.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(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),this._scrollX=(this.game.camera.view.x-this.tileOffset.x)*this.scrollFactorX/this.scale.x,this._scrollY=(this.game.camera.view.y-this.tileOffset.y)*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},i.TilemapLayer.prototype.destroy=function(){i.CanvasPool.remove(this),i.Component.Destroy.prototype.destroy.call(this)},i.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},i.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},i.TilemapLayer.prototype.getTileOffsetX=function(){return this.tileOffset.x||(this.fixedToCamera?0:this.position.x)},i.TilemapLayer.prototype.getTileOffsetY=function(){return this.tileOffset.y||(this.fixedToCamera?0:this.position.y)},i.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},i.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},i.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},i.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},i.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},i.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},i.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},i.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a=0;m++,v--,f+=c){m>=h&&(m-=h);var _=this.layer.data[m];for(g=b,y=n-i,p=x;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var w=_[g];if(w&&!(w.index<0)){var T=w.index,P=u[T];void 0===P&&(P=this.resolveTileset(T)),w.alpha===d||this.debug||(o.globalAlpha=w.alpha,d=w.alpha),P?w.rotation||w.flipped?(o.save(),o.translate(p+w.centerX,f+w.centerY),o.rotate(w.rotation),w.flipped&&o.scale(-1,1),P.draw(o,-w.centerX,-w.centerY,T),o.restore()):P.draw(o,p,f,T):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),w.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},i.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},i.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},i.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)=0;s++,r--,e+=f){s>=d&&(s-=d);var T=this.layer.data[s];for(i=_,n=m-g,t=x;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var P=T[i];!P||P.index<0||!P.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),P.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),P.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),P.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),P.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(i.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(i.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(i.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),i.TilemapParser={INSERT_NULL:!1,parse:function(t,e,s,n,r,o){if(void 0===s&&(s=32),void 0===n&&(n=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(s,n,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===i.Tilemap.CSV)return this.parseCSV(e,a.data,s,n);if(!a.format||a.format===i.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,s,n){for(var r=this.getEmptyData(),o=[],a=(e=e.trim()).split("\n"),h=a.length,l=0,c=0;c>>0;r.data=h,delete r.encoding}else if(r.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+r.name+"'");continue}k={name:r.name,x:r.x,y:r.y,width:r.width,height:r.height,widthInPixels:r.width*t.tilewidth,heightInPixels:r.height*t.tileheight,alpha:r.opacity,offsetX:r.offsetx,offsetY:r.offsety,visible:r.visible,properties:{},indexes:[],callbacks:[],bodies:[]};r.properties&&(k.properties=r.properties);for(var c,u,d,p=0,f=[],g=[],m=0,a=r.data.length;m536870912)switch(A>2147483648&&(A-=2147483648,d+=4),A>1073741824&&(A-=1073741824,d+=2),A>536870912&&(A-=536870912,d+=1),d){case 5:c=Math.PI/2;break;case 6:c=Math.PI;break;case 3:c=3*Math.PI/2;break;case 4:c=0,u=!0;break;case 7:c=Math.PI/2,u=!0;break;case 2:c=Math.PI,u=!0;break;case 1:c=3*Math.PI/2,u=!0}A>0?((F=new i.Tile(k,A,p,g.length,t.tilewidth,t.tileheight)).rotation=c,F.flipped=u,0!==d&&(F.flippedVal=d),f.push(F)):i.TilemapParser.INSERT_NULL?f.push(null):f.push(new i.Tile(k,-1,p,g.length,t.tilewidth,t.tileheight)),++p===r.width&&(g.push(f),p=0,f=[])}k.data=g,s.push(k)}e.layers=s;for(var y=[],n=0;n=0&&n+1=this.firstgid&&t=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(t=0;t=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._total>0&&this._counter>=this._total&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},i.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1),void 0===r&&(r=null);var o,a=0,h=t,l=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);athis.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},i.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),this.resetParticle(n,o,a),!0},i.Particles.Arcade.Emitter.prototype.getNextParticle=function(){for(var t=this.length;t--;){var e=this.next();if(!e.exists)return e}return null},i.Particles.Arcade.Emitter.prototype.resetParticle=function(t,e,i){var s=this.game.rnd;t.reset(e,i),t.angle=0,t.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(t):this.particleSendToBack&&this.sendToBack(t),this.autoScale?t.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?t.scale.set(s.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y?t.scale.set(s.realInRange(this._minParticleScale.x,this._maxParticleScale.x),s.realInRange(this._minParticleScale.y,this._maxParticleScale.y)):t.scale.set(this._minParticleScale.x,this._minParticleScale.y),this.autoAlpha?t.setAlphaData(this.alphaData):t.alpha=s.realInRange(this.minParticleAlpha,this.maxParticleAlpha),t.blendMode=this.blendMode;var n=t.body;n.updateBounds(),n.bounce.copyFrom(this.bounce),n.drag.copyFrom(this.particleDrag),null!=this.minAngle&&null!=this.maxAngle?this.game.physics.arcade.velocityFromAngle(this.minAngle===this.maxAngle?this.minAngle:s.between(this.minAngle,this.maxAngle),this.minSpeed===this.maxSpeed?this.minSpeed:s.between(this.minSpeed,this.maxSpeed),n.velocity):(n.velocity.x=s.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),n.velocity.y=s.between(this.minParticleSpeed.y,this.maxParticleSpeed.y)),n.angularVelocity=s.between(this.minRotation,this.maxRotation),n.gravity.copyFrom(this.gravity),n.angularDrag=this.angularDrag,t.onEmit()},i.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),i.Group.prototype.destroy.call(this,!0,!1)},i.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},i.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},i.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},i.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},i.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,s,n,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=0),void 0===n&&(n=i.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,s>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},s,n);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},i.Particles.Arcade.Emitter.prototype.setScale=function(t,e,s,n,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===s&&(s=1),void 0===n&&(n=1),void 0===r&&(r=0),void 0===o&&(o=i.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,s),this._maxParticleScale.set(e,n),this.autoScale=!1,r>0&&(t!==e||s!==n)){var h={x:t,y:s},l=this.game.make.tween(h).to({x:e,y:n},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},i.Particles.Arcade.Emitter.prototype.setAngle=function(t,e,i,s){return this.minAngle=t,this.maxAngle=e,null!=i&&(this.minSpeed=i),null!=s&&(this.maxSpeed=s),this},i.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"gravity",{get:function(){return this._gravity},set:function(t){"number"==typeof t?this._gravity.y=t:this._gravity=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"id",{get:function(){return this._id}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"output",{get:function(){return 1e3*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"lifespanOutput",{get:function(){return(0===this.lifespan?1/0:this.lifespan)*this._flowQuantity/this.frequency}}),Object.defineProperty(i.Particles.Arcade.Emitter.prototype,"remainder",{get:function(){return this.maxParticles-this.lifespanOutput}}),i.Weapon=function(t,e){i.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new i.Rectangle(0,0,1,1),this.fireAngle=i.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new i.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=i.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=i.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new i.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new i.Signal,this.onKill=new i.Signal,this.onFireLimit=new i.Signal,this.trackedSprite=null,this.trackedPointer=null,this.multiFire=!1,this._hasFired=!1,this.trackRotation=!1,this.trackOffset=new i.Point,this._nextFire=0,this._tempNextFire=0,this._rotatedPoint=new i.Point},i.Weapon.prototype=Object.create(i.Plugin.prototype),i.Weapon.prototype.constructor=i.Weapon,i.Weapon.KILL_NEVER=0,i.Weapon.KILL_LIFESPAN=1,i.Weapon.KILL_DISTANCE=2,i.Weapon.KILL_WEAPON_BOUNDS=3,i.Weapon.KILL_CAMERA_BOUNDS=4,i.Weapon.KILL_WORLD_BOUNDS=5,i.Weapon.KILL_STATIC_BOUNDS=6,i.Weapon.prototype.createBullets=function(t,e,s,n){return void 0===t&&(t=1),void 0===n&&(n=this.game.world),this.bullets&&!this.bullets.game&&(this.bullets=null),this.bullets||(this.bullets=this.game.add.physicsGroup(i.Physics.ARCADE,n),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,s),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=s),this},i.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},i.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},i.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},i.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},i.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},i.Weapon.prototype.update=function(){this._bulletKillType===i.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},i.Weapon.prototype.postRender=function(){this.multiFire&&this._hasFired&&(this._hasFired=!1,this._nextFire=this._tempNextFire)},i.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},i.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},i.Weapon.prototype.fireMany=function(t,e){this.multiFire=!0;var i=[],s=this;return e||this.trackedSprite||this.trackedPointer?t.forEach(function(t){i.push(s.fire(e,null,null,t.x,t.y))}):t.forEach(function(t){i.push(s.fire(t))}),i},i.Weapon.prototype.fireOffset=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.fire(null,null,null,t,e)},i.Weapon.prototype.fire=function(t,e,s,n,r){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game.time.now0&&this.shots===this.fireLimit)return null;var o=this.bulletSpeed;0!==this.bulletSpeedVariance&&(o+=i.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.worldRotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(o+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y)),void 0!==n&&(this.fireFrom.x+=n),void 0!==r&&(this.fireFrom.y+=r);var a=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,h=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,l=this.trackRotation?this.trackedSprite.angle:this.fireAngle;null!==e&&null!==s&&(l=this.game.math.radToDeg(Math.atan2(s-h,e-a))),0!==this.bulletAngleVariance&&(l+=i.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var c=0,u=0;0===l||180===l?c=Math.cos(this.game.math.degToRad(l))*o:90===l||270===l?u=Math.sin(this.game.math.degToRad(l))*o:(c=Math.cos(this.game.math.degToRad(l))*o,u=Math.sin(this.game.math.degToRad(l))*o);var d=null;if(this.autoExpandBulletsGroup?(d=this.bullets.getFirstExists(!1,!0,a,h,this.bulletKey,this.bulletFrame)).data.bulletManager=this:d=this.bullets.getFirstExists(!1),d){if(d.reset(a,h),d.data.fromX=a,d.data.fromY=h,d.data.killType=this.bulletKillType,d.data.killDistance=this.bulletKillDistance,d.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===i.Weapon.KILL_LIFESPAN&&(d.lifespan=this.bulletLifespan),d.angle=l+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===d.animations.getAnimation(this.bulletAnimation)){var p=this.anims[this.bulletAnimation];d.animations.add(p.name,p.frames,p.frameRate,p.loop,p.useNumericIndex)}d.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(d.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(d.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);d.data.bodyDirty&&(this._data.customBody&&d.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),d.body.collideWorldBounds=this.bulletCollideWorldBounds,d.data.bodyDirty=!1),d.body.velocity.set(c,u),d.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y);var f=0;if(0!==this.bulletSpeedVariance){var g=this.fireRate;(g+=i.Math.between(-this.fireRateVariance,this.fireRateVariance))<0&&(g=0),f=this.game.time.now+g}else f=this.game.time.now+this.fireRate;this.multiFire?this._hasFired||(this._hasFired=!0,this._tempNextFire=f,this.shots++):(this._nextFire=f,this.shots++),this.onFire.dispatch(d,this,o),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return d},i.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},i.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},i.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},i.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},i.Weapon.prototype.setBulletFrames=function(t,e,s,n){return void 0===s&&(s=!0),void 0===n&&(n=!1),this.bulletFrames=i.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=s,this.bulletFrameRandom=n,this},i.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},i.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(i.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets&&(this.bullets.classType=this._bulletClass)}}),Object.defineProperty(i.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case i.Weapon.KILL_STATIC_BOUNDS:case i.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case i.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case i.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(i.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(i.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(i.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),i.Bullet=function(t,e,s,n,r){i.Sprite.call(this,t,e,s,n,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},i.Bullet.prototype=Object.create(i.Sprite.prototype),i.Bullet.prototype.constructor=i.Bullet,i.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},i.Bullet.prototype.update=function(){this.exists&&(this.data.killType>i.Weapon.KILL_LIFESPAN&&(this.data.killType===i.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=this.body.velocity.atan()),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},i.Video=function(t,e,s){if(void 0===e&&(e=null),void 0===s&&(s=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=i.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new i.Signal,this.onChangeSource=new i.Signal,this.onComplete=new i.Signal,this.onAccess=new i.Signal,this.onError=new i.Signal,this.onTimeout=new i.Signal,this.onTouchUnlock=new i.Signal,this.playWhenUnlocked=!0,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._pendingChangeSource=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var n=this.game.cache.getVideo(e);n.isBlob?this.createVideoFromBlob(n.data):this.video=n.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else s&&this.createVideoFromURL(s,!1);this.video&&!s?(this.baseTexture=new PIXI.BaseTexture(this.video,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(i.Cache.DEFAULT.baseTexture.source,null,this.game.resolution),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new i.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,i.BitmapData&&(this.snapshot=new i.BitmapData(this.game,"",this.width,this.height)),this.game.device.needsTouchUnlock()?this.setTouchLock():n&&(n.locked=!1)},i.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return this._pendingChangeSource?this:(void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this)},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming)},setTouchLock:function(){this.game.input.addTouchLockCallback(this.unlock,this,!0),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.playWhenUnlocked&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return this.onTouchUnlock.dispatch(this),!0},grab:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null!==this.snapshot)return t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot;console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable")},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(i.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(i.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(i.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(i.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(i.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(i.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(i.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(i.Video.prototype,"playing",{get:function(){return!!this.video&&!(this.video.paused&&this.video.ended)}}),i.Video.prototype.constructor=i.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=i.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=i.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new i.Matrix),PIXI.TextureSilentFail=!0,PIXI.canUseNewCanvasBlendModes=function(){return i.Device.canUseMultiply},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=i),exports.Phaser=i):"undefined"!=typeof define&&define.amd?define("Phaser",e.Phaser=i):e.Phaser=i,i}.call(this); +//# sourceMappingURL=phaser.map \ No newline at end of file diff --git a/Iteration Sequence 2/sources.txt b/Iteration Sequence 2/sources.txt new file mode 100644 index 000000000..6dfd76416 --- /dev/null +++ b/Iteration Sequence 2/sources.txt @@ -0,0 +1,3 @@ +Turret.png: Scribblenauts turret sprite. https://vignette.wikia.nocookie.net/scribblenauts/images/3/35/Turret_SU.png/revision/latest?cb=20130512101053 +Character.png: http://i2.photobucket.com/albums/y22/Avadan/Resources/VX/Spacece.png +Tank: https://kenney.nl/assets \ No newline at end of file diff --git a/index.html b/index.html index e5f6ada2f..def4c398a 100644 --- a/index.html +++ b/index.html @@ -24,19 +24,19 @@

CS 325 Game Prototypes

I am making creative and experimental game prototypes! Here is the list of them:

    -
  1. Digital Assignment 1
  2. +
  3. Previous work hidden for now.
  4. + +
  5. Iteration Sequence 1
  6. +
  7. Iteration Sequence 1 Updated (04/12/18)
  8. +
  9. Iteration Sequence 2
  10. +
  11. Iteration Sequence 2.2
- -

Here are the templates: - -

- diff --git a/template-gamestate-functional/js/main.js b/template-gamestate-functional/js/main.js index c06f39dd4..2650ba36b 100644 --- a/template-gamestate-functional/js/main.js +++ b/template-gamestate-functional/js/main.js @@ -1,10 +1,11 @@ "use strict"; -window.onload = function() { +window.onload = function() +{ // Create your Phaser game and inject it into the 'game' div. // We did it in a window.onload event, but you can do it anywhere (requireJS load, anonymous function, jQuery dom ready, - whatever floats your boat) - var game = new Phaser.Game( 800, 600, Phaser.AUTO, 'game' ); + var game = new Phaser.Game( 1000, 600, Phaser.AUTO, 'game' ); // Add the States your game has. // You don't have to do this in the html, it could be done in your Boot state too, but for simplicity I'll keep it here. diff --git a/template-gamestate-functional/js/phaser.js b/template-gamestate-functional/js/phaser.js old mode 100755 new mode 100644 diff --git a/template-gamestate-functional/js/phaser.map b/template-gamestate-functional/js/phaser.map old mode 100755 new mode 100644 diff --git a/template-gamestate-functional/js/phaser.min.js b/template-gamestate-functional/js/phaser.min.js old mode 100755 new mode 100644 diff --git a/template-gamestate/js/phaser.js b/template-gamestate/js/phaser.js old mode 100755 new mode 100644 diff --git a/template-gamestate/js/phaser.map b/template-gamestate/js/phaser.map old mode 100755 new mode 100644 diff --git a/template-gamestate/js/phaser.min.js b/template-gamestate/js/phaser.min.js old mode 100755 new mode 100644 diff --git a/template-minimal-gamestate/js/phaser.js b/template-minimal-gamestate/js/phaser.js old mode 100755 new mode 100644 diff --git a/template-minimal-gamestate/js/phaser.map b/template-minimal-gamestate/js/phaser.map old mode 100755 new mode 100644 diff --git a/template-minimal-gamestate/js/phaser.min.js b/template-minimal-gamestate/js/phaser.min.js old mode 100755 new mode 100644 diff --git a/template-minimal/js/phaser.js b/template-minimal/js/phaser.js old mode 100755 new mode 100644 diff --git a/template-minimal/js/phaser.map b/template-minimal/js/phaser.map old mode 100755 new mode 100644 diff --git a/template-minimal/js/phaser.min.js b/template-minimal/js/phaser.min.js old mode 100755 new mode 100644 diff --git a/template-tilemap/js/phaser.js b/template-tilemap/js/phaser.js old mode 100755 new mode 100644 diff --git a/template-tilemap/js/phaser.map b/template-tilemap/js/phaser.map old mode 100755 new mode 100644 diff --git a/template-tilemap/js/phaser.min.js b/template-tilemap/js/phaser.min.js old mode 100755 new mode 100644